hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d1d2564dd6ae40f89cffdc3ff37d830d93ea9aa6 | 1,782 | hpp | C++ | src/pir_client.hpp | duanbing/SealPIR | fa50c570011df61fcdd0409e36595d897a9795ac | [
"MIT"
] | 7 | 2022-01-12T11:52:40.000Z | 2022-03-31T23:35:16.000Z | src/pir_client.hpp | abeams/SealPIR | 63c3cf0edff77374d304f7a56b561635b9839356 | [
"MIT"
] | null | null | null | src/pir_client.hpp | abeams/SealPIR | 63c3cf0edff77374d304f7a56b561635b9839356 | [
"MIT"
] | 1 | 2022-03-02T07:14:03.000Z | 2022-03-02T07:14:03.000Z | #pragma once
#include "pir.hpp"
#include <memory>
#include <vector>
using namespace std;
class PIRClient {
public:
PIRClient(const seal::EncryptionParameters &encparms,
const PirParams &pirparams);
PirQuery generate_query(std::uint64_t desiredIndex);
// Serializes the query into the provided stream and returns number of bytes written
int generate_serialized_query(std::uint64_t desiredIndex, std::stringstream &stream);
seal::Plaintext decode_reply(PirReply &reply);
std::vector<uint64_t> extract_coeffs(seal::Plaintext pt);
std::vector<uint64_t> extract_coeffs(seal::Plaintext pt, std::uint64_t offset);
std::vector<uint8_t> extract_bytes(seal::Plaintext pt, std::uint64_t offset);
std::vector<uint8_t> decode_reply(PirReply &reply, uint64_t offset);
seal::Plaintext decrypt(seal::Ciphertext ct);
seal::GaloisKeys generate_galois_keys();
// Index and offset of an element in an FV plaintext
uint64_t get_fv_index(uint64_t element_index);
uint64_t get_fv_offset(uint64_t element_index);
// Only used for simple_query
seal::Ciphertext get_one();
seal::Plaintext replace_element(seal::Plaintext pt, std::vector<std::uint64_t> new_element, std::uint64_t offset);
private:
seal::EncryptionParameters enc_params_;
PirParams pir_params_;
std::unique_ptr<seal::Encryptor> encryptor_;
std::unique_ptr<seal::Decryptor> decryptor_;
std::unique_ptr<seal::Evaluator> evaluator_;
std::unique_ptr<seal::KeyGenerator> keygen_;
std::unique_ptr<seal::BatchEncoder> encoder_;
std::shared_ptr<seal::SEALContext> context_;
vector<uint64_t> indices_; // the indices for retrieval.
vector<uint64_t> inverse_scales_;
friend class PIRServer;
};
| 31.263158 | 118 | 0.731762 | [
"vector"
] |
d1d8969a0d95f1ba415c790c52d8bb7a87f11cda | 16,853 | cpp | C++ | EBYTE.cpp | MxFxM/EBYTE | 5628efee248669aacbbeb3aba545e2dc6ace6810 | [
"MIT"
] | null | null | null | EBYTE.cpp | MxFxM/EBYTE | 5628efee248669aacbbeb3aba545e2dc6ace6810 | [
"MIT"
] | null | null | null | EBYTE.cpp | MxFxM/EBYTE | 5628efee248669aacbbeb3aba545e2dc6ace6810 | [
"MIT"
] | null | null | null | /*
Original code by: Kris Kasprzak kris.kasprzak@yahoo.com
Modified by: Max-Felix Mueller mxfxmmueller@gmail.com
This library is intended to be used with EBYTE transcievers, small wireless units for MCU's such as
Teensy and Arduino. This library let's users program the operating parameters and both send and recieve data.
This company makes several modules with different capabilities, but most #defines here should be compatible with them
All constants were extracted from several data sheets and listed in binary as that's how the data sheet represented each setting
Hopefully, any changes or additions to constants can be a matter of copying the data sheet constants directly into these #defines
Usage of this library consumes around 970 bytes
*/
#include <EBYTE.h>
#include <Stream.h>
#include <Arduino.h>
/*
Create the tranceiver object
*/
EBYTE::EBYTE(Stream *s, uint8_t PIN_M0, uint8_t PIN_M1, uint8_t PIN_AUX) {
// serial port for communication with the module
_s = s;
// other digital pins connecting the module
_M0 = PIN_M0;
_M1 = PIN_M1;
_AUX = PIN_AUX;
}
/*
Initialize the unit
Read the module parameters and store default parameters for future module settings
*/
bool EBYTE::init() {
// set pins to output
pinMode(_AUX, INPUT);
pinMode(_M0, OUTPUT);
pinMode(_M1, OUTPUT);
// normal operating mode
SetMode(MODE_NORMAL);
// get module data
if (!ReadModelData()) {
return false;
}
// get parameters to put unit defaults into the class variables
if (!ReadParameters()) {
return false;
}
return true;
}
/*
Availability of the serial interface
Returns true if at least 1 byte is available
*/
bool EBYTE::available() {
return _s->available();
}
/*
Wait for all data in the serial buffer to be transmitted
*/
void EBYTE::flush() {
_s->flush();
}
/*
Write a single byte to the module via the serial interface
For more than one byte, send it as a data structure
*/
void EBYTE::SendByte( uint8_t TheByte) {
_s->write(TheByte);
}
/*
Read a single byte from the serial interface
For more than one byte, receive it as a data structure
*/
uint8_t EBYTE::GetByte() {
return _s->read();
}
/*
Send multiple bytes as a data sturcture
TIP: structure definition in a .h file and include in both sender and reciever
NOTE: different MCU's handle ints and floats differently (Arduino, Teensy, ...)
*/
bool EBYTE::SendStruct(const void *dataStruct, uint16_t size_) {
// get the return of the write operation
_buf = _s->write((uint8_t *) dataStruct, size_);
// wait for the transmission to finish
CompleteTask(1000);
// write will return the number of bytes written
// if the number does not match, not all bytes have been written
return (_buf == size_);
}
/*
Read multiple bytes in a data structure
TIP: structure definition in a .h file and include in both sender and reciever
NOTE: different MCU's handle ints and floats differently (Arduino, Teensy, ...)
*/
bool EBYTE::GetStruct(const void *dataStruct, uint16_t size_) {
// read the expected number of bytes
_buf = _s->readBytes((uint8_t *) dataStruct, size_);
// wait for the transmission to finish
CompleteTask(1000);
// readBytes will return the number of bytes read
// if the number does not match, not all bytes have been read
return (_buf == size_);
}
/*
Wait until module is done tranmitting
Timeout in milliseconds is provided to avoid an infinite loop
TIP: if no AUX pin is used, pull the module AUX pin high with 4k7
NOTE: worst case timeout is nearly doubled due to timer overflow handling
NOTE: no AUX pin is necessary, but then a fixed delay of 1 second will be used
*/
void EBYTE::CompleteTask(unsigned long timeout) {
// get starting time of task
unsigned long t = millis();
// if millis would overflow during timeout
if (((unsigned long) (t + timeout)) == 0){
// wait until after the overflow and then start timeout timer
t = 0;
}
// if AUX pin was set up
if (_AUX != -1) {
// wait for a high signal on the AUX pin
while (digitalRead(_AUX) == LOW) {
// and check the timeout
if ((millis() - t) > timeout){
break;
}
}
} else {
// wait at least 1 second if no AUX pin is used
if (timeout < 1000) {
// you may need to adjust this value if transmissions fail
delay(1000);
} else {
delay(timeout);
}
}
// per data sheet control after aux goes high is 2ms so delay for at least that long)
delay(AUX_PIN_RECOVER);
}
/*
Method to set the mode
Available modes are: MODE_NORMAL
MODE_WAKEUP
MODE_POWERDOWN
MODE_PROGRAM
*/
void EBYTE::SetMode(uint8_t mode) {
// give the module some time
delay(PIN_RECOVER);
if (mode == MODE_NORMAL) {
digitalWrite(_M0, LOW);
digitalWrite(_M1, LOW);
}
else if (mode == MODE_WAKEUP) {
digitalWrite(_M0, HIGH);
digitalWrite(_M1, LOW);
}
else if (mode == MODE_POWERDOWN) {
digitalWrite(_M0, LOW);
digitalWrite(_M1, HIGH);
}
else if (mode == MODE_PROGRAM) {
digitalWrite(_M0, HIGH);
digitalWrite(_M1, HIGH);
}
// wait for the module to accept new mode
delay(PIN_RECOVER);
// wait until aux pin goes back low
// CompleteTask(4000);
}
// i have no clue what this is supposed to do
// seems everytime I try using it, it sets all parameters to 0
// i've asked EBYTE what's supposed to happen--got an unclear answer
// hence this is a private function to keep users from crashing their modeules
void EBYTE::Reset() {
SetMode(MODE_PROGRAM);
delay(50);
_s->write(0xC4);
_s->write(0xC4);
_s->write(0xC4);
CompleteTask(4000);
SetMode(MODE_NORMAL);
}
/*
Set the speed of
*/
void EBYTE::SetSpeed(uint8_t val) {
_Speed = val;
}
/*
Get the speed of
*/
uint8_t EBYTE::GetSpeed() {
return _Speed ;
}
/*
Set options
*/
void EBYTE::SetOptions(uint8_t val) {
_Options = val;
}
/*
Get options
*/
uint8_t EBYTE::GetOptions() {
return _Options;
}
/*
Set the high byte of the address
*/
void EBYTE::SetAddressH(uint8_t val) {
_AddressHigh = val;
}
/*
Get the high byte of the address
*/
uint8_t EBYTE::GetAddressH() {
return _AddressHigh;
}
/*
Set the low byte of the address
*/
void EBYTE::SetAddressL(uint8_t val) {
_AddressLow = val;
}
/*
Get the low byte of the address
*/
uint8_t EBYTE::GetAddressL() {
return _AddressLow;
}
/*
Set the channel
*/
void EBYTE::SetChannel(uint8_t val) {
_Channel = val;
}
/*
Get the channel
*/
uint8_t EBYTE::GetChannel() {
return _Channel;
}
/*
Set the air data rate
*/
void EBYTE::SetAirDataRate(uint8_t val) {
_AirDataRate = val;
// part of multiple options in one byte
// combined here
BuildSpeedByte();
}
/*
Get the air data rate
*/
uint8_t EBYTE::GetAirDataRate() {
return _AirDataRate;
}
/*
Set the parity bit
*/
void EBYTE::SetParityBit(uint8_t val) {
_ParityBit = val;
// part of multiple options in one byte
// combined here
BuildSpeedByte();
}
/*
Get the parity bit
*/
uint8_t EBYTE::GetParityBit( ) {
return _ParityBit;
}
/*
Set the transmission mode
*/
void EBYTE::SetTransmissionMode(uint8_t val) {
_OptionTrans = val;
// part of multiple options in one byte
// combined here
BuildOptionByte();
}
/*
Get the transmission mode
*/
uint8_t EBYTE::GetTransmissionMode( ) {
return _OptionTrans;
}
/*
Set the pullup mode
*/
void EBYTE::SetPullupMode(uint8_t val) {
_OptionPullup = val;
// part of multiple options in one byte
// combined here
BuildOptionByte();
}
/*
Get the pullup mode
*/
uint8_t EBYTE::GetPullupMode( ) {
return _OptionPullup;
}
/*
Set the
*/
void EBYTE::SetWORTIming(uint8_t val) {
_OptionWakeup = val;
// part of multiple options in one byte
// combined here
BuildOptionByte();
}
/*
Get the
*/
uint8_t EBYTE::GetWORTIming() {
return _OptionWakeup;
}
/*
Set the fec mode
*/
void EBYTE::SetFECMode(uint8_t val) {
_OptionFEC = val;
// part of multiple options in one byte
// combined here
BuildOptionByte();
}
/*
Set the fec mode
*/
uint8_t EBYTE::GetFECMode( ) {
return _OptionFEC;
}
/*
Set the transmit power
*/
void EBYTE::SetTransmitPower(uint8_t val) {
_OptionPower = val;
// part of multiple options in one byte
// combined here
BuildOptionByte();
}
/*
Get the transmit power
*/
uint8_t EBYTE::GetTransmitPower() {
return _OptionPower;
}
/*
Compute high and low bytes from a 16 bit address
*/
void EBYTE::SetAddress(uint16_t Val) {
_AddressHigh = ((Val & 0xFFFF) >> 8);
_AddressLow = (Val & 0xFF);
}
/*
Get the complete address as 16 bit value
*/
uint16_t EBYTE::GetAddress() {
return (_AddressHigh << 8) | (_AddressLow);
}
/*
Set the UART baud rate
*/
void EBYTE::SetUARTBaudRate(uint8_t val) {
_UARTDataRate = val;
// part of multiple options in one byte
// combined here
BuildSpeedByte();
}
/*
Get the UART baud rate
*/
uint8_t EBYTE::GetUARTBaudRate() {
return _UARTDataRate;
}
/*
Build the byte for programming
This is a collection of: Parity
UART baud rate
Air data rate
*/
void EBYTE::BuildSpeedByte() {
_Speed = 0;
_Speed = ((_ParityBit & 0xFF) << 6) | ((_UARTDataRate & 0xFF) << 3) | (_AirDataRate & 0xFF);
}
/*
Build the option byte for programming
This is a collection of: Transmission mode
Pullup mode
WORTIming
FEC mode
Transmit power
*/
void EBYTE::BuildOptionByte() {
_Options = 0;
_Options = ((_OptionTrans & 0xFF) << 7) | ((_OptionPullup & 0xFF) << 6) | ((_OptionWakeup & 0xFF) << 3) | ((_OptionFEC & 0xFF) << 2) | (_OptionPower&0b11);
}
/*
Save parameters to the module
Either save even when powered down or only temporary
Options are: PERMANENT
TEMPORARY
NOTE: All parameters have to be saved at once
*/
void EBYTE::SaveParameters(uint8_t retention) {
// switch into programming mode
SetMode(MODE_PROGRAM);
// ignore all bytes in serial interface
ClearBuffer();
delay(5);
// send options
_s->write(retention);
_s->write(_AddressHigh);
_s->write(_AddressLow);
_s->write(_Speed);
_s->write(_Channel);
_s->write(_Options);
// wait for transmission to complete
delay(50);
CompleteTask(4000);
// return to normal operating mode
SetMode(MODE_NORMAL);
}
/*
Debug method to print all parameters
Can be called anytime after init()
*/
void EBYTE::PrintParameters() {
_ParityBit = (_Speed & 0XC0) >> 6;
_UARTDataRate = (_Speed & 0X38) >> 3;
_AirDataRate = _Speed & 0X07;
_OptionTrans = (_Options & 0X80) >> 7;
_OptionPullup = (_Options & 0X40) >> 6;
_OptionWakeup = (_Options & 0X38) >> 3;
_OptionFEC = (_Options & 0X07) >> 2;
_OptionPower = (_Options & 0X03);
Serial.println("----------------------------------------");
Serial.print(F("Model no.: ")); Serial.println(_Model, HEX);
Serial.print(F("Version : ")); Serial.println(_Version, HEX);
Serial.print(F("Features : ")); Serial.println(_Features, HEX);
Serial.println(F(" "));
Serial.print(F("Mode (HEX/DEC/BIN): ")); Serial.print(_Save, HEX); Serial.print(F("/")); Serial.print(_Save, DEC); Serial.print(F("/")); Serial.println(_Save, BIN);
Serial.print(F("AddH (HEX/DEC/BIN): ")); Serial.print(_AddressHigh, HEX); Serial.print(F("/")); Serial.print(_AddressHigh, DEC); Serial.print(F("/")); Serial.println(_AddressHigh, BIN);
Serial.print(F("AddL (HEX/DEC/BIN): ")); Serial.print(_AddressLow, HEX); Serial.print(F("/")); Serial.print(_AddressLow, DEC); Serial.print(F("/")); Serial.println(_AddressLow, BIN);
Serial.print(F("Sped (HEX/DEC/BIN): ")); Serial.print(_Speed, HEX); Serial.print(F("/")); Serial.print(_Speed, DEC); Serial.print(F("/")); Serial.println(_Speed, BIN);
Serial.print(F("Chan (HEX/DEC/BIN): ")); Serial.print(_Channel, HEX); Serial.print(F("/")); Serial.print(_Channel, DEC); Serial.print(F("/")); Serial.println(_Channel, BIN);
Serial.print(F("Optn (HEX/DEC/BIN): ")); Serial.print(_Options, HEX); Serial.print(F("/")); Serial.print(_Options, DEC); Serial.print(F("/")); Serial.println(_Options, BIN);
Serial.print(F("Addr (HEX/DEC/BIN): ")); Serial.print(GetAddress(), HEX); Serial.print(F("/")); Serial.print(GetAddress(), DEC); Serial.print(F("/")); Serial.println(GetAddress(), BIN);
Serial.println(F(" "));
Serial.print(F("SpeedParityBit (HEX/DEC/BIN) : ")); Serial.print(_ParityBit, HEX); Serial.print(F("/")); Serial.print(_ParityBit, DEC); Serial.print(F("/")); Serial.println(_ParityBit, BIN);
Serial.print(F("SpeedUARTDataRate (HEX/DEC/BIN) : ")); Serial.print(_UARTDataRate, HEX); Serial.print(F("/")); Serial.print(_UARTDataRate, DEC); Serial.print(F("/")); Serial.println(_UARTDataRate, BIN);
Serial.print(F("SpeedAirDataRate (HEX/DEC/BIN) : ")); Serial.print(_AirDataRate, HEX); Serial.print(F("/")); Serial.print(_AirDataRate, DEC); Serial.print(F("/")); Serial.println(_AirDataRate, BIN);
Serial.print(F("OptionTrans (HEX/DEC/BIN) : ")); Serial.print(_OptionTrans, HEX); Serial.print(F("/")); Serial.print(_OptionTrans, DEC); Serial.print(F("/")); Serial.println(_OptionTrans, BIN);
Serial.print(F("OptionPullup (HEX/DEC/BIN) : ")); Serial.print(_OptionPullup, HEX); Serial.print(F("/")); Serial.print(_OptionPullup, DEC); Serial.print(F("/")); Serial.println(_OptionPullup, BIN);
Serial.print(F("OptionWakeup (HEX/DEC/BIN) : ")); Serial.print(_OptionWakeup, HEX); Serial.print(F("/")); Serial.print(_OptionWakeup, DEC); Serial.print(F("/")); Serial.println(_OptionWakeup, BIN);
Serial.print(F("OptionFEC (HEX/DEC/BIN) : ")); Serial.print(_OptionFEC, HEX); Serial.print(F("/")); Serial.print(_OptionFEC, DEC); Serial.print(F("/")); Serial.println(_OptionFEC, BIN);
Serial.print(F("OptionPower (HEX/DEC/BIN) : ")); Serial.print(_OptionPower, HEX); Serial.print(F("/")); Serial.print(_OptionPower, DEC); Serial.print(F("/")); Serial.println(_OptionPower, BIN);
Serial.println("----------------------------------------");
}
/*
Read all parameters from module
*/
bool EBYTE::ReadParameters() {
// clear stored parameters
_Params[0] = 0;
_Params[1] = 0;
_Params[2] = 0;
_Params[3] = 0;
_Params[4] = 0;
_Params[5] = 0;
// switch into programming mode
SetMode(MODE_PROGRAM);
// clear serial input buffer
ClearBuffer();
delay(5);
// request parameters
_s->write(0xC1);
_s->write(0xC1);
_s->write(0xC1);
delay(5);
// read parameter bytes into array
_s->readBytes((uint8_t*)&_Params, (uint8_t) sizeof(_Params));
delay(5);
// unpack the parameters
_Save = _Params[0];
_AddressHigh = _Params[1];
_AddressLow = _Params[2];
_Speed = _Params[3];
_Channel = _Params[4];
_Options = _Params[5];
_Address = (_AddressHigh << 8) | (_AddressLow);
_ParityBit = (_Speed & 0XC0) >> 6;
_UARTDataRate = (_Speed & 0X38) >> 3;
_AirDataRate = _Speed & 0X07;
_OptionTrans = (_Options & 0X80) >> 7;
_OptionPullup = (_Options & 0X40) >> 6;
_OptionWakeup = (_Options & 0X38) >> 3;
_OptionFEC = (_Options & 0X07) >> 2;
_OptionPower = (_Options & 0X03);
// return to normal operating mode
SetMode(MODE_NORMAL);
// data is only valid, if first parameter is 0xC0
if (0xC0 != _Params[0]){
return false;
}
return true;
}
/*
Read model information
*/
bool EBYTE::ReadModelData() {
// clear stored parameters
_Params[0] = 0;
_Params[1] = 0;
_Params[2] = 0;
_Params[3] = 0;
// switch into programming mode
SetMode(MODE_PROGRAM);
// discard serial input buffer
ClearBuffer();
// request model information
_s->write(0xC3);
_s->write(0xC3);
_s->write(0xC3);
delay(5);
// read model information
_s->readBytes((uint8_t*)& _Params, (uint8_t) sizeof(_Params));
delay(5);
// unpack parameters
_Save = _Params[0];
_Model = _Params[1];
_Version = _Params[2];
_Features = _Params[3];
// return to normal operating mode
SetMode(MODE_NORMAL);
// data is only valid if first parameter is 0xC3
if (0xC3 != _Params[0]) {
return false;
}
return true;
}
/*
Get module model
NOTE: E50-TTL-100 will return 50
*/
uint8_t EBYTE::GetModel() {
return _Model;
}
/*
Get module version
(undocumented as to the value)
*/
uint8_t EBYTE::GetVersion() {
return _Version;
}
/*
Get module features
(undocumented as to the value)
*/
uint8_t EBYTE::GetFeatures() {
return _Features;
}
/*
Clear serial interface input buffer
Will discard any bytes not yet read
*/
void EBYTE::ClearBuffer(){
// discard byte
byte b;
// read all bytes of the input buffer into the discard byte
while(_s->available()) {
b = _s->read();
}
}
| 24.74743 | 207 | 0.658043 | [
"object",
"model"
] |
d1e506c8b5efd35f1cad921cca137c95767309da | 142,620 | cpp | C++ | abcd/ABC_Tx.cpp | lclc/airbitz-core | 372e01807e36bc37ed63fdd76805c6165be9c08e | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | abcd/ABC_Tx.cpp | lclc/airbitz-core | 372e01807e36bc37ed63fdd76805c6165be9c08e | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | abcd/ABC_Tx.cpp | lclc/airbitz-core | 372e01807e36bc37ed63fdd76805c6165be9c08e | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /**
* @file
* AirBitz Tx functions.
*
* This file contains all of the functions associated with transaction creation,
* viewing and modification.
*
* Copyright (c) 2014, Airbitz
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted provided that
* the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
* 3. Redistribution or use of modified source code requires the express written
* permission of Airbitz Inc.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Airbitz Project.
*
* @author See AUTHORS
* @version 1.0
*/
#include "ABC_Tx.h"
#include "ABC_Account.h"
#include "ABC_Exchanges.h"
#include "ABC_Wallet.h"
#include "ABC_Bridge.h"
#include "util/ABC_Crypto.h"
#include "util/ABC_Debug.h"
#include "util/ABC_FileIO.h"
#include "util/ABC_Mutex.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <string.h>
#include <qrencode.h>
#define SATOSHI_PER_BITCOIN 100000000
#define MIN_RECYCLABLE 5
#define TX_MAX_ADDR_ID_LENGTH 20 // largest char count for the string version of the id number - 20 digits should handle it
#define TX_MAX_AMOUNT_LENGTH 100 // should be max length of a bit coin amount string
#define TX_MAX_CATEGORY_LENGTH 512
#define TX_INTERNAL_SUFFIX "-int.json" // the transaction was created by our direct action (i.e., send)
#define TX_EXTERNAL_SUFFIX "-ext.json" // the transaction was created due to events in the block-chain (usually receives)
#define ADDRESS_FILENAME_SEPARATOR '-'
#define ADDRESS_FILENAME_SUFFIX ".json"
#define ADDRESS_FILENAME_MIN_LEN 8 // <id>-<public_addr>.json
#define JSON_DETAILS_FIELD "meta"
#define JSON_CREATION_DATE_FIELD "creationDate"
#define JSON_MALLEABLE_TX_ID "malleableTxId"
#define JSON_AMOUNT_SATOSHI_FIELD "amountSatoshi"
#define JSON_AMOUNT_AIRBITZ_FEE_SATOSHI_FIELD "amountFeeAirBitzSatoshi"
#define JSON_AMOUNT_MINERS_FEE_SATOSHI_FIELD "amountFeeMinersSatoshi"
#define JSON_TX_ID_FIELD "ntxid"
#define JSON_TX_STATE_FIELD "state"
#define JSON_TX_INTERNAL_FIELD "internal"
#define JSON_TX_LOGIN_FIELD "login"
#define JSON_TX_AMOUNT_CURRENCY_FIELD "amountCurrency"
#define JSON_TX_NAME_FIELD "name"
#define JSON_TX_BIZID_FIELD "bizId"
#define JSON_TX_CATEGORY_FIELD "category"
#define JSON_TX_NOTES_FIELD "notes"
#define JSON_TX_ATTRIBUTES_FIELD "attributes"
#define JSON_TX_OUTPUTS_FIELD "outputs"
#define JSON_TX_OUTPUT_FLAG "input"
#define JSON_TX_OUTPUT_VALUE "value"
#define JSON_TX_OUTPUT_ADDRESS "address"
#define JSON_TX_OUTPUT_TXID "txid"
#define JSON_TX_OUTPUT_INDEX "index"
#define JSON_ADDR_SEQ_FIELD "seq"
#define JSON_ADDR_ADDRESS_FIELD "address"
#define JSON_ADDR_STATE_FIELD "state"
#define JSON_ADDR_RECYCLEABLE_FIELD "recycleable"
#define JSON_ADDR_ACTIVITY_FIELD "activity"
#define JSON_ADDR_DATE_FIELD "date"
typedef enum eTxType
{
TxType_None = 0,
TxType_Internal,
TxType_External
} tTxType;
typedef struct sTxStateInfo
{
int64_t timeCreation;
bool bInternal;
char *szMalleableTxId;
} tTxStateInfo;
typedef struct sABC_Tx
{
char *szID; // ntxid from bitcoin
tABC_TxDetails *pDetails;
tTxStateInfo *pStateInfo;
unsigned int countOutputs;
tABC_TxOutput **aOutputs;
} tABC_Tx;
typedef struct sTxAddressActivity
{
char *szTxID; // ntxid from bitcoin associated with this activity
int64_t timeCreation;
int64_t amountSatoshi;
} tTxAddressActivity;
typedef struct sTxAddressStateInfo
{
int64_t timeCreation;
bool bRecycleable;
unsigned int countActivities;
tTxAddressActivity *aActivities;
} tTxAddressStateInfo;
typedef struct sABC_TxAddress
{
int32_t seq; // sequence number
char *szID; // sequence number in string form
char *szPubAddress; // public address
tABC_TxDetails *pDetails;
tTxAddressStateInfo *pStateInfo;
} tABC_TxAddress;
static tABC_CC ABC_TxCreateNewAddress(tABC_WalletID self, tABC_TxDetails *pDetails, tABC_TxAddress **ppAddress, tABC_Error *pError);
static tABC_CC ABC_TxCreateNewAddressForN(tABC_WalletID self, int32_t N, tABC_Error *pError);
static tABC_CC ABC_GetAddressFilename(const char *szWalletUUID, const char *szRequestID, char **pszFilename, tABC_Error *pError);
static tABC_CC ABC_TxParseAddrFilename(const char *szFilename, char **pszID, char **pszPublicAddress, tABC_Error *pError);
static tABC_CC ABC_TxSetAddressRecycle(tABC_WalletID self, const char *szAddress, bool bRecyclable, tABC_Error *pError);
static tABC_CC ABC_TxCheckForInternalEquivalent(const char *szFilename, bool *pbEquivalent, tABC_Error *pError);
static tABC_CC ABC_TxGetTxTypeAndBasename(const char *szFilename, tTxType *pType, char **pszBasename, tABC_Error *pError);
static tABC_CC ABC_TxLoadTransactionInfo(tABC_WalletID self, const char *szFilename, tABC_TxInfo **ppTransaction, tABC_Error *pError);
static tABC_CC ABC_TxLoadTxAndAppendToArray(tABC_WalletID self, int64_t startTime, int64_t endTime, const char *szFilename, tABC_TxInfo ***paTransactions, unsigned int *pCount, tABC_Error *pError);
static tABC_CC ABC_TxGetAddressOwed(tABC_TxAddress *pAddr, int64_t *pSatoshiBalance, tABC_Error *pError);
static tABC_CC ABC_TxBuildFromLabel(tABC_WalletID self, char **pszLabel, tABC_Error *pError);
static void ABC_TxFreeRequest(tABC_RequestInfo *pRequest);
static tABC_CC ABC_TxCreateTxFilename(tABC_WalletID self, char **pszFilename, const char *szTxID, bool bInternal, tABC_Error *pError);
static tABC_CC ABC_TxLoadTransaction(tABC_WalletID self, const char *szFilename, tABC_Tx **ppTx, tABC_Error *pError);
static tABC_CC ABC_TxFindRequest(tABC_WalletID self, const char *szMatchAddress, tABC_TxAddress **ppMatched, tABC_Error *pError);
static tABC_CC ABC_TxDecodeTxState(json_t *pJSON_Obj, tTxStateInfo **ppInfo, tABC_Error *pError);
static tABC_CC ABC_TxDecodeTxDetails(json_t *pJSON_Obj, tABC_TxDetails **ppDetails, tABC_Error *pError);
static void ABC_TxFreeTx(tABC_Tx *pTx);
static tABC_CC ABC_TxCreateTxDir(const char *szWalletUUID, tABC_Error *pError);
static tABC_CC ABC_TxSaveTransaction(tABC_WalletID self, const tABC_Tx *pTx, tABC_Error *pError);
static tABC_CC ABC_TxEncodeTxState(json_t *pJSON_Obj, tTxStateInfo *pInfo, tABC_Error *pError);
static tABC_CC ABC_TxEncodeTxDetails(json_t *pJSON_Obj, tABC_TxDetails *pDetails, tABC_Error *pError);
static int ABC_TxInfoPtrCompare (const void * a, const void * b);
static tABC_CC ABC_TxLoadAddress(tABC_WalletID self, const char *szAddressID, tABC_TxAddress **ppAddress, tABC_Error *pError);
static tABC_CC ABC_TxLoadAddressFile(tABC_WalletID self, const char *szFilename, tABC_TxAddress **ppAddress, tABC_Error *pError);
static tABC_CC ABC_TxDecodeAddressStateInfo(json_t *pJSON_Obj, tTxAddressStateInfo **ppState, tABC_Error *pError);
static tABC_CC ABC_TxSaveAddress(tABC_WalletID self, const tABC_TxAddress *pAddress, tABC_Error *pError);
static tABC_CC ABC_TxEncodeAddressStateInfo(json_t *pJSON_Obj, tTxAddressStateInfo *pInfo, tABC_Error *pError);
static tABC_CC ABC_TxCreateAddressFilename(tABC_WalletID self, char **pszFilename, const tABC_TxAddress *pAddress, tABC_Error *pError);
static tABC_CC ABC_TxCreateAddressDir(const char *szWalletUUID, tABC_Error *pError);
static void ABC_TxFreeAddress(tABC_TxAddress *pAddress);
static void ABC_TxFreeAddressStateInfo(tTxAddressStateInfo *pInfo);
static void ABC_TxFreeAddresses(tABC_TxAddress **aAddresses, unsigned int count);
static tABC_CC ABC_TxGetAddresses(tABC_WalletID self, tABC_TxAddress ***paAddresses, unsigned int *pCount, tABC_Error *pError);
static int ABC_TxAddrPtrCompare(const void * a, const void * b);
static tABC_CC ABC_TxLoadAddressAndAppendToArray(tABC_WalletID self, const char *szFilename, tABC_TxAddress ***paAddresses, unsigned int *pCount, tABC_Error *pError);
//static void ABC_TxPrintAddresses(tABC_TxAddress **aAddresses, unsigned int count);
static tABC_CC ABC_TxMutexLock(tABC_Error *pError);
static tABC_CC ABC_TxMutexUnlock(tABC_Error *pError);
static tABC_CC ABC_TxAddressAddTx(tABC_TxAddress *pAddress, tABC_Tx *pTx, tABC_Error *pError);
static tABC_CC ABC_TxTransactionExists(tABC_WalletID self, const char *szID, tABC_Tx **pTx, tABC_Error *pError);
static void ABC_TxStrTable(const char *needle, int *table);
static int ABC_TxStrStr(const char *haystack, const char *needle, tABC_Error *pError);
static int ABC_TxCopyOuputs(tABC_Tx *pTx, tABC_TxOutput **aOutputs, int countOutputs, tABC_Error *pError);
static tABC_CC ABC_TxTransferPopulate(tABC_TxSendInfo *pInfo, tABC_Tx *pTx, tABC_Tx *pReceiveTx, tABC_Error *pError);
static tABC_CC ABC_TxWalletOwnsAddress(tABC_WalletID self, const char *szAddress, bool *bFound, tABC_Error *pError);
static tABC_CC ABC_TxGetPrivAddresses(tABC_WalletID self, tABC_U08Buf seed, char ***paAddresses, unsigned int *pCount, tABC_Error *pError);
static tABC_CC ABC_TxTrashAddresses(tABC_WalletID self, bool bAdd, tABC_Tx *pTx, tABC_TxOutput **paAddresses, unsigned int addressCount, tABC_Error *pError);
static tABC_CC ABC_TxCalcCurrency(tABC_WalletID self, int64_t amountSatoshi, double *pCurrency, tABC_Error *pError);
/**
* Initializes the
*/
tABC_CC ABC_TxInitialize(tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
return cc;
}
/**
* Allocate a send info struct and populate it with the data given
*/
tABC_CC ABC_TxSendInfoAlloc(tABC_TxSendInfo **ppTxSendInfo,
tABC_WalletID self,
const char *szDestAddress,
const tABC_TxDetails *pDetails,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_TxSendInfo *pTxSendInfo = NULL;
ABC_CHECK_NULL(ppTxSendInfo);
ABC_CHECK_NULL(szDestAddress);
ABC_CHECK_NULL(pDetails);
ABC_NEW(pTxSendInfo, tABC_TxSendInfo);
ABC_CHECK_RET(ABC_WalletIDCopy(&pTxSendInfo->wallet, self, pError));
ABC_STRDUP(pTxSendInfo->szDestAddress, szDestAddress);
ABC_CHECK_RET(ABC_TxDupDetails(&(pTxSendInfo->pDetails), pDetails, pError));
*ppTxSendInfo = pTxSendInfo;
pTxSendInfo = NULL;
exit:
ABC_TxSendInfoFree(pTxSendInfo);
return cc;
}
/**
* Free a send info struct
*/
void ABC_TxSendInfoFree(tABC_TxSendInfo *pTxSendInfo)
{
if (pTxSendInfo)
{
ABC_WalletIDFree(pTxSendInfo->wallet);
ABC_FREE_STR(pTxSendInfo->szDestAddress);
ABC_FREE_STR(pTxSendInfo->szDestWalletUUID);
ABC_FREE_STR(pTxSendInfo->szDestName);
ABC_FREE_STR(pTxSendInfo->szDestCategory);
ABC_FREE_STR(pTxSendInfo->szSrcName);
ABC_FREE_STR(pTxSendInfo->szSrcCategory);
ABC_TxFreeDetails(pTxSendInfo->pDetails);
ABC_CLEAR_FREE(pTxSendInfo, sizeof(tABC_TxSendInfo));
}
}
/**
* Sends the transaction with the given info.
*
* @param pInfo Pointer to transaction information
* @param pszTxID Pointer to hold allocated pointer to transaction ID string
*/
tABC_CC ABC_TxSend(tABC_TxSendInfo *pInfo,
char **pszTxID,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_U08Buf privSeed = ABC_BUF_NULL;
tABC_UnsignedTx *pUtx = NULL;
// Change address variables
tABC_TxAddress *pChangeAddr = NULL;
char *szPrivSeed = NULL;
char **paAddresses = NULL;
char **paPrivAddresses = NULL;
unsigned int countAddresses = 0, privCountAddresses = 0;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_NULL(pInfo);
// take this non-blocking opportunity to update the info from the server if needed
ABC_CHECK_RET(ABC_GeneralUpdateInfo(pError));
ABC_NEW(pUtx, tABC_UnsignedTx);
// find/create a change address
ABC_CHECK_RET(ABC_TxCreateNewAddress(
pInfo->wallet, pInfo->pDetails,
&pChangeAddr, pError));
// save out this address
ABC_CHECK_RET(ABC_TxSaveAddress(pInfo->wallet, pChangeAddr, pError));
// Fetch addresses for this wallet
ABC_CHECK_RET(
ABC_TxGetPubAddresses(pInfo->wallet, &paAddresses, &countAddresses, pError));
// Make an unsigned transaction
ABC_CHECK_RET(
ABC_BridgeTxMake(pInfo, paAddresses, countAddresses,
pChangeAddr->szPubAddress, pUtx, pError));
// Fetch Private Seed
ABC_CHECK_RET(
ABC_WalletGetBitcoinPrivateSeed(pInfo->wallet, &privSeed, pError));
// Fetch the private addresses
ABC_CHECK_RET(
ABC_TxGetPrivAddresses(pInfo->wallet, privSeed,
&paPrivAddresses, &privCountAddresses,
pError));
// Sign and send transaction
ABC_CHECK_RET(
ABC_BridgeTxSignSend(pInfo, paPrivAddresses, privCountAddresses,
pUtx, pError));
// Update the ABC db
ABC_CHECK_RET(ABC_TxSendComplete(pInfo, pUtx, pError));
// return the new tx id
ABC_STRDUP(*pszTxID, pUtx->szTxId);
exit:
ABC_FREE(szPrivSeed);
ABC_TxFreeAddress(pChangeAddr);
ABC_UtilFreeStringArray(paAddresses, countAddresses);
ABC_TxSendInfoFree(pInfo);
ABC_TxFreeOutputs(pUtx->aOutputs, pUtx->countOutputs);
ABC_FREE(pUtx->data);
ABC_FREE(pUtx);
ABC_TxMutexUnlock(NULL);
return cc;
}
tABC_CC ABC_TxSendComplete(tABC_TxSendInfo *pInfo,
tABC_UnsignedTx *pUtx,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_Tx *pTx = NULL;
tABC_Tx *pReceiveTx = NULL;
bool bFound = false;
tABC_WalletInfo *pWallet = NULL;
tABC_WalletInfo *pDestWallet = NULL;
double Currency;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// Start watching all addresses incuding new change addres
ABC_CHECK_RET(ABC_TxWatchAddresses(pInfo->wallet, pError));
// sucessfully sent, now create a transaction
ABC_NEW(pTx, tABC_Tx);
ABC_NEW(pTx->pStateInfo, tTxStateInfo);
// set the state
pTx->pStateInfo->timeCreation = time(NULL);
pTx->pStateInfo->bInternal = true;
ABC_STRDUP(pTx->pStateInfo->szMalleableTxId, pUtx->szTxMalleableId);
// Copy outputs
ABC_TxCopyOuputs(pTx, pUtx->aOutputs, pUtx->countOutputs, pError);
// copy the details
ABC_CHECK_RET(ABC_TxDupDetails(&(pTx->pDetails), pInfo->pDetails, pError));
// Add in tx fees to the amount of the tx
ABC_CHECK_RET(ABC_TxWalletOwnsAddress(pInfo->wallet, pInfo->szDestAddress,
&bFound, pError));
if (bFound)
{
pTx->pDetails->amountSatoshi = pInfo->pDetails->amountFeesAirbitzSatoshi
+ pInfo->pDetails->amountFeesMinersSatoshi;
}
else
{
pTx->pDetails->amountSatoshi = pInfo->pDetails->amountSatoshi
+ pInfo->pDetails->amountFeesAirbitzSatoshi
+ pInfo->pDetails->amountFeesMinersSatoshi;
}
ABC_CHECK_RET(ABC_TxCalcCurrency(
pInfo->wallet, pTx->pDetails->amountSatoshi, &Currency, pError));
pTx->pDetails->amountCurrency = Currency;
if (pTx->pDetails->amountSatoshi > 0)
pTx->pDetails->amountSatoshi *= -1;
if (pTx->pDetails->amountCurrency > 0)
pTx->pDetails->amountCurrency *= -1.0;
// Store transaction ID
ABC_STRDUP(pTx->szID, pUtx->szTxId);
if (pInfo->bTransfer)
{
ABC_NEW(pReceiveTx, tABC_Tx);
ABC_NEW(pReceiveTx->pStateInfo, tTxStateInfo);
// set the state
pReceiveTx->pStateInfo->timeCreation = time(NULL);
pReceiveTx->pStateInfo->bInternal = true;
ABC_STRDUP(pReceiveTx->pStateInfo->szMalleableTxId, pUtx->szTxMalleableId);
// Copy outputs
ABC_TxCopyOuputs(pReceiveTx, pUtx->aOutputs, pUtx->countOutputs, pError);
// copy the details
ABC_CHECK_RET(ABC_TxDupDetails(&(pReceiveTx->pDetails), pInfo->pDetails, pError));
pReceiveTx->pDetails->amountSatoshi = pInfo->pDetails->amountSatoshi;
//
// Since this wallet is receiving, it didn't really get charged AB fees
// This should really be an assert since no transfers should have AB fees
//
pReceiveTx->pDetails->amountFeesAirbitzSatoshi = 0;
tABC_WalletID recvWallet =
ABC_WalletID(pInfo->wallet.pKeys, pInfo->szDestWalletUUID);
ABC_CHECK_RET(ABC_WalletGetInfo(recvWallet, &pDestWallet, pError));
ABC_CHECK_RET(ABC_TxSatoshiToCurrency(recvWallet.pKeys,
pReceiveTx->pDetails->amountSatoshi, &Currency,
pDestWallet->currencyNum, pError));
pReceiveTx->pDetails->amountCurrency = Currency;
if (pReceiveTx->pDetails->amountSatoshi < 0)
pReceiveTx->pDetails->amountSatoshi *= -1;
if (pReceiveTx->pDetails->amountCurrency < 0)
pReceiveTx->pDetails->amountCurrency *= -1.0;
// Store transaction ID
ABC_STRDUP(pReceiveTx->szID, pUtx->szTxId);
// Set the payee and category for both txs
ABC_CHECK_RET(ABC_TxTransferPopulate(pInfo, pTx, pReceiveTx, pError));
// save the transaction
ABC_CHECK_RET(ABC_TxSaveTransaction(recvWallet, pReceiveTx, pError));
}
// save the transaction
ABC_CHECK_RET(
ABC_TxSaveTransaction(pInfo->wallet, pTx, pError));
exit:
ABC_TxFreeTx(pTx);
ABC_TxFreeTx(pReceiveTx);
ABC_TxMutexUnlock(NULL);
ABC_WalletFreeInfo(pWallet);
ABC_WalletFreeInfo(pDestWallet);
return cc;
}
tABC_CC ABC_TxCalcSendFees(tABC_TxSendInfo *pInfo, int64_t *pTotalFees, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_UnsignedTx utx;
tABC_TxAddress *pChangeAddr = NULL;
char **paAddresses = NULL;
unsigned int countAddresses = 0;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_NULL(pInfo);
pInfo->pDetails->amountFeesAirbitzSatoshi = 0;
pInfo->pDetails->amountFeesMinersSatoshi = 0;
// find/create a change address
ABC_CHECK_RET(ABC_TxCreateNewAddress(
pInfo->wallet, pInfo->pDetails,
&pChangeAddr, pError));
// save out this address
ABC_CHECK_RET(ABC_TxSaveAddress(pInfo->wallet, pChangeAddr, pError));
// Fetch addresses for this wallet
ABC_CHECK_RET(
ABC_TxGetPubAddresses(pInfo->wallet, &paAddresses, &countAddresses, pError));
cc = ABC_BridgeTxMake(pInfo, paAddresses, countAddresses,
pChangeAddr->szPubAddress, &utx, pError);
*pTotalFees = pInfo->pDetails->amountFeesAirbitzSatoshi
+ pInfo->pDetails->amountFeesMinersSatoshi;
ABC_CHECK_RET(cc);
exit:
ABC_UtilFreeStringArray(paAddresses, countAddresses);
ABC_TxFreeAddress(pChangeAddr);
ABC_TxMutexUnlock(NULL);
return cc;
}
tABC_CC ABC_TxWalletOwnsAddress(tABC_WalletID self,
const char *szAddress,
bool *bFound,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
char **paAddresses = NULL;
unsigned int countAddresses = 0;
*bFound = false;
ABC_CHECK_RET(
ABC_TxGetPubAddresses(self, &paAddresses, &countAddresses, pError));
for (unsigned i = 0; i < countAddresses; ++i)
{
if (strncmp(szAddress, paAddresses[i], strlen(szAddress)) == 0)
{
*bFound = true;
break;
}
}
exit:
ABC_UtilFreeStringArray(paAddresses, countAddresses);
return cc;
}
/**
* Gets the public addresses associated with the given wallet.
*
* @param paAddresses Pointer to string array of addresses
* @param pCount Pointer to store number of addresses
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxGetPubAddresses(tABC_WalletID self,
char ***paAddresses,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_TxAddress **aAddresses = NULL;
char **sAddresses;
unsigned int countAddresses = 0;
ABC_CHECK_RET(
ABC_TxGetAddresses(self, &aAddresses, &countAddresses, pError));
ABC_ARRAY_NEW(sAddresses, countAddresses, char*);
for (unsigned i = 0; i < countAddresses; i++)
{
const char *s = aAddresses[i]->szPubAddress;
ABC_STRDUP(sAddresses[i], s);
}
*pCount = countAddresses;
*paAddresses = sAddresses;
exit:
ABC_TxFreeAddresses(aAddresses, countAddresses);
return cc;
}
/**
* Gets the private keys with the given wallet.
*
* @param paAddresses Pointer to string array of addresses
* @param pCount Pointer to store number of addresses
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxGetPrivAddresses(tABC_WalletID self,
tABC_U08Buf seed,
char ***paAddresses,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_TxAddress **aAddresses = NULL;
char **sAddresses;
unsigned int countAddresses = 0;
ABC_CHECK_RET(
ABC_TxGetAddresses(self, &aAddresses, &countAddresses, pError));
ABC_ARRAY_NEW(sAddresses, countAddresses, char*);
for (unsigned i = 0; i < countAddresses; i++)
{
ABC_CHECK_RET(
ABC_BridgeGetBitcoinPrivAddress(&sAddresses[i],
seed,
aAddresses[i]->seq,
pError));
}
*pCount = countAddresses;
*paAddresses = sAddresses;
exit:
ABC_TxFreeAddresses(aAddresses, countAddresses);
return cc;
}
tABC_CC ABC_TxWatchAddresses(tABC_WalletID self,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
char *szPubAddress = NULL;
tABC_TxAddress **aAddresses = NULL;
unsigned int countAddresses = 0;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_RET(
ABC_TxGetAddresses(self, &aAddresses, &countAddresses, pError));
for (unsigned i = 0; i < countAddresses; i++)
{
const tABC_TxAddress *a = aAddresses[i];
ABC_CHECK_RET(
ABC_BridgeWatchAddr(self.szUUID,
a->szPubAddress, pError));
}
exit:
ABC_TxFreeAddresses(aAddresses, countAddresses);
ABC_FREE_STR(szPubAddress);
ABC_CHECK_RET(ABC_TxMutexUnlock(pError));
return cc;
}
/**
* Duplicate a TX details struct
*/
tABC_CC ABC_TxDupDetails(tABC_TxDetails **ppNewDetails, const tABC_TxDetails *pOldDetails, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_TxDetails *pNewDetails = NULL;
ABC_CHECK_NULL(ppNewDetails);
ABC_CHECK_NULL(pOldDetails);
ABC_NEW(pNewDetails, tABC_TxDetails);
pNewDetails->amountSatoshi = pOldDetails->amountSatoshi;
pNewDetails->amountFeesAirbitzSatoshi = pOldDetails->amountFeesAirbitzSatoshi;
pNewDetails->amountFeesMinersSatoshi = pOldDetails->amountFeesMinersSatoshi;
pNewDetails->amountCurrency = pOldDetails->amountCurrency;
pNewDetails->bizId = pOldDetails->bizId;
pNewDetails->attributes = pOldDetails->attributes;
if (pOldDetails->szName != NULL)
{
ABC_STRDUP(pNewDetails->szName, pOldDetails->szName);
}
if (pOldDetails->szCategory != NULL)
{
ABC_STRDUP(pNewDetails->szCategory, pOldDetails->szCategory);
}
if (pOldDetails->szNotes != NULL)
{
ABC_STRDUP(pNewDetails->szNotes, pOldDetails->szNotes);
}
// set the pointer for the caller
*ppNewDetails = pNewDetails;
pNewDetails = NULL;
exit:
ABC_TxFreeDetails(pNewDetails);
return cc;
}
/**
* Free a TX details struct
*/
void ABC_TxFreeDetails(tABC_TxDetails *pDetails)
{
if (pDetails)
{
ABC_FREE_STR(pDetails->szName);
ABC_FREE_STR(pDetails->szCategory);
ABC_FREE_STR(pDetails->szNotes);
ABC_CLEAR_FREE(pDetails, sizeof(tABC_TxDetails));
}
}
/**
* Converts amount from Satoshi to Bitcoin
*
* @param satoshi Amount in Satoshi
*/
double ABC_TxSatoshiToBitcoin(int64_t satoshi)
{
return((double) satoshi / (double) SATOSHI_PER_BITCOIN);
}
/**
* Converts amount from Bitcoin to Satoshi
*
* @param bitcoin Amount in Bitcoin
*/
int64_t ABC_TxBitcoinToSatoshi(double bitcoin)
{
return((int64_t) (bitcoin * (double) SATOSHI_PER_BITCOIN));
}
/**
* Converts Satoshi to given currency
*
* @param satoshi Amount in Satoshi
* @param pCurrency Pointer to location to store amount converted to currency.
* @param currencyNum Currency ISO 4217 num
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxSatoshiToCurrency(tABC_SyncKeys *pKeys,
int64_t satoshi,
double *pCurrency,
int currencyNum,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
double pRate;
ABC_CHECK_NULL(pCurrency);
*pCurrency = 0.0;
ABC_CHECK_RET(ABC_ExchangeCurrentRate(pKeys, currencyNum, &pRate, pError));
*pCurrency = ABC_SatoshiToBitcoin(satoshi) * pRate;
exit:
return cc;
}
/**
* Converts given currency to Satoshi
*
* @param currency Amount in given currency
* @param currencyNum Currency ISO 4217 num
* @param pSatoshi Pointer to location to store amount converted to Satoshi
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxCurrencyToSatoshi(tABC_SyncKeys *pKeys,
double currency,
int currencyNum,
int64_t *pSatoshi,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
double pRate;
ABC_CHECK_NULL(pSatoshi);
*pSatoshi = 0;
ABC_CHECK_RET(ABC_ExchangeCurrentRate(pKeys, currencyNum, &pRate, pError));
*pSatoshi = ABC_BitcoinToSatoshi(currency) / pRate;
exit:
return cc;
}
tABC_CC
ABC_TxBlockHeightUpdate(uint64_t height,
tABC_BitCoin_Event_Callback fAsyncBitCoinEventCallback,
void *pData,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
if (fAsyncBitCoinEventCallback)
{
tABC_AsyncBitCoinInfo info;
info.eventType = ABC_AsyncEventType_BlockHeightChange;
info.pData = pData;
ABC_STRDUP(info.szDescription, "Block height change");
fAsyncBitCoinEventCallback(&info);
ABC_FREE_STR(info.szDescription);
}
exit:
return cc;
}
/**
* Handles creating or updating when we receive a transaction
*/
tABC_CC ABC_TxReceiveTransaction(tABC_WalletID self,
uint64_t amountSatoshi, uint64_t feeSatoshi,
tABC_TxOutput **paInAddresses, unsigned int inAddressCount,
tABC_TxOutput **paOutAddresses, unsigned int outAddressCount,
const char *szTxId, const char *szMalTxId,
tABC_BitCoin_Event_Callback fAsyncBitCoinEventCallback,
void *pData,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_U08Buf TxID = ABC_BUF_NULL;
tABC_Tx *pTx = NULL;
tABC_U08Buf IncomingAddress = ABC_BUF_NULL;
double Currency = 0.0;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_RET(ABC_TxCalcCurrency(self, amountSatoshi, &Currency, pError));
// Does the transaction already exist?
ABC_TxTransactionExists(self, szTxId, &pTx, pError);
if (pTx == NULL)
{
// create a transaction
ABC_NEW(pTx, tABC_Tx);
ABC_NEW(pTx->pStateInfo, tTxStateInfo);
ABC_NEW(pTx->pDetails, tABC_TxDetails);
ABC_STRDUP(pTx->pStateInfo->szMalleableTxId, szMalTxId);
pTx->pStateInfo->timeCreation = time(NULL);
pTx->pDetails->amountSatoshi = amountSatoshi;
pTx->pDetails->amountCurrency = Currency;
pTx->pDetails->amountFeesMinersSatoshi = feeSatoshi;
ABC_STRDUP(pTx->pDetails->szName, "");
ABC_STRDUP(pTx->pDetails->szCategory, "");
ABC_STRDUP(pTx->pDetails->szNotes, "");
// set the state
pTx->pStateInfo->timeCreation = time(NULL);
pTx->pStateInfo->bInternal = false;
// store transaction id
ABC_STRDUP(pTx->szID, szTxId);
// store the input addresses
pTx->countOutputs = inAddressCount + outAddressCount;
ABC_ARRAY_NEW(pTx->aOutputs, pTx->countOutputs, tABC_TxOutput*);
for (unsigned i = 0; i < inAddressCount; ++i)
{
ABC_DebugLog("Saving Input address: %s\n", paInAddresses[i]->szAddress);
ABC_NEW(pTx->aOutputs[i], tABC_TxOutput);
ABC_STRDUP(pTx->aOutputs[i]->szAddress, paInAddresses[i]->szAddress);
ABC_STRDUP(pTx->aOutputs[i]->szTxId, paInAddresses[i]->szTxId);
pTx->aOutputs[i]->input = paInAddresses[i]->input;
pTx->aOutputs[i]->value = paInAddresses[i]->value;
}
for (unsigned i = 0; i < outAddressCount; ++i)
{
ABC_DebugLog("Saving Output address: %s\n", paOutAddresses[i]->szAddress);
int newi = i + inAddressCount;
ABC_NEW(pTx->aOutputs[newi], tABC_TxOutput);
ABC_STRDUP(pTx->aOutputs[newi]->szAddress, paOutAddresses[i]->szAddress);
ABC_STRDUP(pTx->aOutputs[newi]->szTxId, paOutAddresses[i]->szTxId);
pTx->aOutputs[newi]->input = paOutAddresses[i]->input;
pTx->aOutputs[newi]->value = paOutAddresses[i]->value;
}
// save the transaction
ABC_CHECK_RET(
ABC_TxSaveTransaction(self, pTx, pError));
// add the transaction to the address
ABC_CHECK_RET(ABC_TxTrashAddresses(self, true,
pTx, paOutAddresses, outAddressCount, pError));
// Mark the wallet cache as dirty in case the Tx wasn't included in the current balance
ABC_CHECK_RET(ABC_WalletDirtyCache(self, pError));
if (fAsyncBitCoinEventCallback)
{
tABC_AsyncBitCoinInfo info;
info.pData = pData;
info.eventType = ABC_AsyncEventType_IncomingBitCoin;
ABC_STRDUP(info.szTxID, pTx->szID);
ABC_STRDUP(info.szWalletUUID, self.szUUID);
ABC_STRDUP(info.szDescription, "Received funds");
fAsyncBitCoinEventCallback(&info);
ABC_FREE_STR(info.szTxID);
ABC_FREE_STR(info.szDescription);
}
}
else
{
ABC_DebugLog("We already have %s\n", szTxId);
ABC_CHECK_RET(ABC_TxTrashAddresses(self, false,
pTx, paOutAddresses, outAddressCount, pError));
// Mark the wallet cache as dirty in case the Tx wasn't included in the current balance
ABC_CHECK_RET(ABC_WalletDirtyCache(self, pError));
if (fAsyncBitCoinEventCallback)
{
tABC_AsyncBitCoinInfo info;
info.pData = pData;
info.eventType = ABC_AsyncEventType_DataSyncUpdate;
ABC_STRDUP(info.szTxID, pTx->szID);
ABC_STRDUP(info.szWalletUUID, self.szUUID);
ABC_STRDUP(info.szDescription, "Updated balance");
fAsyncBitCoinEventCallback(&info);
ABC_FREE_STR(info.szTxID);
ABC_FREE_STR(info.szDescription);
}
}
exit:
ABC_TxMutexUnlock(NULL);
ABC_BUF_FREE(TxID);
ABC_BUF_FREE(IncomingAddress);
ABC_TxFreeTx(pTx);
return cc;
}
/**
* Marks the address as unusable and copies the details to the new Tx
*
* @param pTx The transaction that will be updated
* @param paAddress Addresses that will be search
* @param addressCount Number of address in paAddress
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxTrashAddresses(tABC_WalletID self,
bool bAdd,
tABC_Tx *pTx,
tABC_TxOutput **paAddresses,
unsigned int addressCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_TxAddress *pAddress = NULL;
for (unsigned i = 0; i < addressCount; ++i)
{
ABC_CHECK_RET(ABC_TxFindRequest(self,
paAddresses[i]->szAddress, &pAddress, pError));
if (pAddress)
{
pAddress->pStateInfo->bRecycleable = false;
if (bAdd)
{
ABC_CHECK_RET(ABC_TxAddressAddTx(pAddress, pTx, pError));
}
ABC_CHECK_RET(ABC_TxSaveAddress(self,
pAddress, pError));
int changed = 0;
if (ABC_STRLEN(pTx->pDetails->szName) == 0
&& ABC_STRLEN(pAddress->pDetails->szName) > 0)
{
ABC_STRDUP(pTx->pDetails->szName, pAddress->pDetails->szName);
++changed;
}
if (ABC_STRLEN(pTx->pDetails->szNotes) == 0
&& ABC_STRLEN(pAddress->pDetails->szNotes) > 0)
{
ABC_STRDUP(pTx->pDetails->szNotes, pAddress->pDetails->szNotes);
++changed;
}
if (ABC_STRLEN(pTx->pDetails->szCategory) == 0
&& ABC_STRLEN(pAddress->pDetails->szCategory))
{
ABC_STRDUP(pTx->pDetails->szCategory, pAddress->pDetails->szCategory);
++changed;
}
if (changed)
{
ABC_CHECK_RET(
ABC_TxSaveTransaction(self, pTx, pError));
}
ABC_TxFreeAddress(pAddress);
}
pAddress = NULL;
}
exit:
ABC_TxFreeAddress(pAddress);
return cc;
}
/**
* Calculates the amount of currency based off of Wallet's currency code
*
* @param tABC_WalletID
* @param amountSatoshi
* @param pCurrency Point to double
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxCalcCurrency(tABC_WalletID self, int64_t amountSatoshi,
double *pCurrency, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
double Currency = 0.0;
tABC_WalletInfo *pWallet = NULL;
ABC_CHECK_RET(ABC_WalletGetInfo(self, &pWallet, pError));
ABC_CHECK_RET(ABC_TxSatoshiToCurrency(
self.pKeys, amountSatoshi, &Currency, pWallet->currencyNum, pError));
*pCurrency = Currency;
exit:
ABC_WalletFreeInfo(pWallet);
return cc;
}
/**
* Creates a receive request.
*
* @param szUserName UserName for the account associated with this request
* @param pDetails Pointer to transaction details
* @param pszRequestID Pointer to store allocated ID for this request
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxCreateReceiveRequest(tABC_WalletID self,
tABC_TxDetails *pDetails,
char **pszRequestID,
bool bTransfer,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxAddress *pAddress = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
*pszRequestID = NULL;
// get a new address (re-using a recycleable if we can)
ABC_CHECK_RET(ABC_TxCreateNewAddress(self, pDetails, &pAddress, pError));
// save out this address
ABC_CHECK_RET(ABC_TxSaveAddress(self, pAddress, pError));
// set the id for the caller
ABC_STRDUP(*pszRequestID, pAddress->szID);
// Watch this new address
ABC_CHECK_RET(ABC_TxWatchAddresses(self, pError));
exit:
ABC_TxFreeAddress(pAddress);
ABC_TxMutexUnlock(NULL);
return cc;
}
tABC_CC ABC_TxCreateInitialAddresses(tABC_WalletID self,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxDetails *pDetails = NULL;
ABC_NEW(pDetails, tABC_TxDetails);
ABC_STRDUP(pDetails->szName, "");
ABC_STRDUP(pDetails->szCategory, "");
ABC_STRDUP(pDetails->szNotes, "");
pDetails->attributes = 0x0;
pDetails->bizId = 0;
ABC_CHECK_RET(ABC_TxCreateNewAddress(self, pDetails, NULL, pError));
exit:
ABC_FreeTxDetails(pDetails);
return cc;
}
/**
* Creates a new address.
* First looks to see if we can recycle one, if we can, that is the address returned.
* This new address is not saved to the file system, the caller must make sure it is saved
* if they want it persisted.
*
* @param pDetails Pointer to transaction details to be used for the new address
* (note: a copy of these are made so the caller can do whatever they want
* with the pointer once the call is complete)
* @param ppAddress Location to store pointer to allocated address
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxCreateNewAddress(tABC_WalletID self,
tABC_TxDetails *pDetails,
tABC_TxAddress **ppAddress,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxAddress **aAddresses = NULL;
unsigned int countAddresses = 0;
tABC_TxAddress *pAddress = NULL;
int64_t N = -1;
unsigned recyclable = 0;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// first look for an existing address that we can re-use
// load addresses
ABC_CHECK_RET(ABC_TxGetAddresses(self, &aAddresses, &countAddresses, pError));
// search through all of the addresses, get the highest N and check for one with the recycleable bit set
for (unsigned i = 0; i < countAddresses; i++)
{
// if this is the highest seq number
if (aAddresses[i]->seq > N)
{
N = aAddresses[i]->seq;
}
// if we don't have an address yet and this one is available
ABC_CHECK_NULL(aAddresses[i]->pStateInfo);
if (aAddresses[i]->pStateInfo->bRecycleable == true
&& aAddresses[i]->pStateInfo->countActivities == 0)
{
recyclable++;
if (pAddress == NULL)
{
char *szRegenAddress = NULL;
tABC_U08Buf Seed = ABC_BUF_NULL;
ABC_CHECK_RET(ABC_WalletGetBitcoinPrivateSeedDisk(self, &Seed, pError));
ABC_CHECK_RET(ABC_BridgeGetBitcoinPubAddress(&szRegenAddress, Seed, aAddresses[i]->seq, pError));
if (strncmp(aAddresses[i]->szPubAddress, szRegenAddress, strlen(aAddresses[i]->szPubAddress)) == 0)
{
// set it to NULL so we don't free it as part of the array
// free, we will be sending this back to the caller
pAddress = aAddresses[i];
aAddresses[i] = NULL;
recyclable--;
}
else
{
ABC_DebugLog("********************************\n");
ABC_DebugLog("Address Corrupt\nInitially: %s, Now: %s\nSeq: %d",
aAddresses[i]->szPubAddress,
szRegenAddress,
aAddresses[i]->seq);
ABC_DebugLog("********************************\n");
}
ABC_FREE_STR(szRegenAddress);
ABC_BUF_FREE(Seed);
}
}
}
// Create a new address at N
if (recyclable <= MIN_RECYCLABLE)
{
for (unsigned i = 0; i < MIN_RECYCLABLE - recyclable; ++i)
{
ABC_CHECK_RET(ABC_TxCreateNewAddressForN(self, N + i, pError));
}
}
// Does the caller want a result?
if (ppAddress)
{
// Did we find an address to use?
ABC_CHECK_ASSERT(pAddress != NULL, ABC_CC_NoAvailableAddress, "Unable to locate a non-corrupt address.");
// free state and details as we will be setting them to new data below
ABC_TxFreeAddressStateInfo(pAddress->pStateInfo);
pAddress->pStateInfo = NULL;
ABC_FreeTxDetails(pAddress->pDetails);
pAddress->pDetails = NULL;
// copy over the info we were given
ABC_CHECK_RET(ABC_DuplicateTxDetails(&(pAddress->pDetails), pDetails, pError));
// create the state info
ABC_NEW(pAddress->pStateInfo, tTxAddressStateInfo);
pAddress->pStateInfo->bRecycleable = true;
pAddress->pStateInfo->countActivities = 0;
pAddress->pStateInfo->aActivities = NULL;
pAddress->pStateInfo->timeCreation = time(NULL);
// assigned final address
*ppAddress = pAddress;
pAddress = NULL;
}
exit:
ABC_TxFreeAddresses(aAddresses, countAddresses);
ABC_TxFreeAddress(pAddress);
ABC_TxMutexUnlock(NULL);
return cc;
}
static
tABC_CC ABC_TxCreateNewAddressForN(tABC_WalletID self, int32_t N, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxAddress *pAddress = NULL;
tABC_U08Buf Seed = ABC_BUF_NULL;
// Now we know the latest N, create a new address
ABC_NEW(pAddress, tABC_TxAddress);
// get the private seed so we can generate the public address
ABC_CHECK_RET(ABC_WalletGetBitcoinPrivateSeedDisk(self, &Seed, pError));
// generate the public address
pAddress->szPubAddress = NULL;
pAddress->seq = N;
do
{
// move to the next sequence number
pAddress->seq++;
// Get the public address for our sequence (it can return NULL, if it is invalid)
ABC_CHECK_RET(ABC_BridgeGetBitcoinPubAddress(&(pAddress->szPubAddress), Seed, pAddress->seq, pError));
} while (pAddress->szPubAddress == NULL);
// set the final ID
ABC_STR_NEW(pAddress->szID, TX_MAX_ADDR_ID_LENGTH);
sprintf(pAddress->szID, "%u", pAddress->seq);
ABC_NEW(pAddress->pStateInfo, tTxAddressStateInfo);
pAddress->pStateInfo->bRecycleable = true;
pAddress->pStateInfo->countActivities = 0;
pAddress->pStateInfo->aActivities = NULL;
pAddress->pStateInfo->timeCreation = time(NULL);
ABC_NEW(pAddress->pDetails, tABC_TxDetails);
ABC_STRDUP(pAddress->pDetails->szName, "");
ABC_STRDUP(pAddress->pDetails->szCategory, "");
ABC_STRDUP(pAddress->pDetails->szNotes, "");
pAddress->pDetails->attributes = 0x0;
pAddress->pDetails->bizId = 0;
pAddress->pDetails->amountSatoshi = 0;
pAddress->pDetails->amountCurrency = 0;
pAddress->pDetails->amountFeesAirbitzSatoshi = 0;
pAddress->pDetails->amountFeesMinersSatoshi = 0;
// Save the new Address
ABC_CHECK_RET(ABC_TxSaveAddress(self, pAddress, pError));
exit:
ABC_TxFreeAddress(pAddress);
ABC_BUF_FREE(Seed);
return cc;
}
/**
* Modifies a previously created receive request.
* Note: the previous details will be free'ed so if the user is using the previous details for this request
* they should not assume they will be valid after this call.
*
* @param szRequestID ID of this request
* @param pDetails Pointer to transaction details
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxModifyReceiveRequest(tABC_WalletID self,
const char *szRequestID,
tABC_TxDetails *pDetails,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szFile = NULL;
char *szAddrDir = NULL;
char *szFilename = NULL;
tABC_TxAddress *pAddress = NULL;
tABC_TxDetails *pNewDetails = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// get the filename for this request (note: interally requests are addresses)
ABC_CHECK_RET(ABC_GetAddressFilename(self.szUUID, szRequestID, &szFile, pError));
// get the directory name
ABC_CHECK_RET(ABC_WalletGetAddressDirName(&szAddrDir, self.szUUID, pError));
// create the full filename
ABC_STR_NEW(szFilename, ABC_FILEIO_MAX_PATH_LENGTH + 1);
sprintf(szFilename, "%s/%s", szAddrDir, szFile);
// load the request address
ABC_CHECK_RET(ABC_TxLoadAddressFile(self, szFilename, &pAddress, pError));
// copy the new details
ABC_CHECK_RET(ABC_TxDupDetails(&pNewDetails, pDetails, pError));
// free the old details on this address
ABC_TxFreeDetails(pAddress->pDetails);
// set the new details
pAddress->pDetails = pNewDetails;
pNewDetails = NULL;
// write out the address
ABC_CHECK_RET(ABC_TxSaveAddress(self, pAddress, pError));
exit:
ABC_FREE_STR(szFile);
ABC_FREE_STR(szAddrDir);
ABC_FREE_STR(szFilename);
ABC_TxFreeAddress(pAddress);
ABC_TxFreeDetails(pNewDetails);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Gets the filename for a given address based upon the address id
*
* @param szWalletUUID UUID of the wallet associated with this address
* @param szAddressID ID of this address
* @param pszFilename Address to store pointer to filename
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_GetAddressFilename(const char *szWalletUUID,
const char *szAddressID,
char **pszFilename,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szAddrDir = NULL;
tABC_FileIOList *pFileList = NULL;
bool bExists = false;
char *szID = NULL;
ABC_CHECK_RET(ABC_FileIOMutexLock(pError)); // we want this as an atomic files system function
ABC_CHECK_NULL(szWalletUUID);
ABC_CHECK_ASSERT(strlen(szWalletUUID) > 0, ABC_CC_Error, "No wallet UUID provided");
ABC_CHECK_NULL(szAddressID);
ABC_CHECK_ASSERT(strlen(szAddressID) > 0, ABC_CC_Error, "No address UUID provided");
ABC_CHECK_NULL(pszFilename);
*pszFilename = NULL;
// get the directory name
ABC_CHECK_RET(ABC_WalletGetAddressDirName(&szAddrDir, szWalletUUID, pError));
// Make sure there is an addresses directory
ABC_CHECK_RET(ABC_FileIOFileExists(szAddrDir, &bExists, pError));
ABC_CHECK_ASSERT(bExists == true, ABC_CC_Error, "No existing requests/addresses");
// get all the files in the address directory
ABC_FileIOCreateFileList(&pFileList, szAddrDir, NULL);
for (int i = 0; i < pFileList->nCount; i++)
{
// if this file is a normal file
if (pFileList->apFiles[i]->type == ABC_FileIOFileType_Regular)
{
// parse the elements from the filename
ABC_FREE_STR(szID);
ABC_CHECK_RET(ABC_TxParseAddrFilename(pFileList->apFiles[i]->szName, &szID, NULL, pError));
// if the id matches
if (strcmp(szID, szAddressID) == 0)
{
// copy over the filename
ABC_STRDUP(*pszFilename, pFileList->apFiles[i]->szName);
break;
}
}
}
exit:
ABC_FREE_STR(szAddrDir);
ABC_FREE_STR(szID);
ABC_FileIOFreeFileList(pFileList);
ABC_FileIOMutexUnlock(NULL);
return cc;
}
/**
* Parses out the id and public address from an address filename
*
* @param szFilename Filename to parse
* @param pszID Location to store allocated id (caller must free) - optional
* @param pszPublicAddress Location to store allocated public address(caller must free) - optional
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxParseAddrFilename(const char *szFilename,
char **pszID,
char **pszPublicAddress,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
// if the filename is long enough
if (strlen(szFilename) >= ADDRESS_FILENAME_MIN_LEN)
{
int suffixPos = (int) strlen(szFilename) - (int) strlen(ADDRESS_FILENAME_SUFFIX);
char *szSuffix = (char *) &(szFilename[suffixPos]);
// if the filename ends with the right suffix
if (strcmp(ADDRESS_FILENAME_SUFFIX, szSuffix) == 0)
{
int nPosSeparator = 0;
// go through all the characters up to the separator
for (size_t i = 0; i < strlen(szFilename); i++)
{
// check for id separator
if (szFilename[i] == ADDRESS_FILENAME_SEPARATOR)
{
// found it
nPosSeparator = i;
break;
}
// if no separator, then better be a digit
if (isdigit(szFilename[i]) == 0)
{
// Ran into a non-digit! - no good
break;
}
}
// if we found a legal separator position
if (nPosSeparator > 0)
{
if (pszID != NULL)
{
ABC_STR_NEW(*pszID, nPosSeparator + 1);
strncpy(*pszID, szFilename, nPosSeparator);
}
if (pszPublicAddress != NULL)
{
ABC_STRDUP(*pszPublicAddress, &(szFilename[nPosSeparator + 1]))
(*pszPublicAddress)[strlen(*pszPublicAddress) - strlen(ADDRESS_FILENAME_SUFFIX)] = '\0';
}
}
}
}
exit:
return cc;
}
/**
* Finalizes a previously created receive request.
* This is done by setting the recycle bit to false so that the address is not used again.
*
* @param szRequestID ID of this request
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxFinalizeReceiveRequest(tABC_WalletID self,
const char *szRequestID,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
// set the recycle bool to false (not that the request is actually an address internally)
ABC_CHECK_RET(ABC_TxSetAddressRecycle(self, szRequestID, false, pError));
exit:
return cc;
}
/**
* Cancels a previously created receive request.
* This is done by setting the recycle bit to true so that the address can be used again.
*
* @param szRequestID ID of this request
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxCancelReceiveRequest(tABC_WalletID self,
const char *szRequestID,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
// set the recycle bool to true (not that the request is actually an address internally)
ABC_CHECK_RET(ABC_TxSetAddressRecycle(self, szRequestID, true, pError));
exit:
return cc;
}
/**
* Sets the recycle status on an address as specified
*
* @param szAddress ID of the address
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxSetAddressRecycle(tABC_WalletID self,
const char *szAddress,
bool bRecyclable,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szFile = NULL;
char *szAddrDir = NULL;
char *szFilename = NULL;
tABC_TxAddress *pAddress = NULL;
tABC_TxDetails *pNewDetails = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// get the filename for this address
ABC_CHECK_RET(ABC_GetAddressFilename(self.szUUID, szAddress, &szFile, pError));
// get the directory name
ABC_CHECK_RET(ABC_WalletGetAddressDirName(&szAddrDir, self.szUUID, pError));
// create the full filename
ABC_STR_NEW(szFilename, ABC_FILEIO_MAX_PATH_LENGTH + 1);
sprintf(szFilename, "%s/%s", szAddrDir, szFile);
// load the request address
ABC_CHECK_RET(ABC_TxLoadAddressFile(self, szFilename, &pAddress, pError));
ABC_CHECK_NULL(pAddress->pStateInfo);
// if it isn't already set as required
if (pAddress->pStateInfo->bRecycleable != bRecyclable)
{
// change the recycle boolean
ABC_CHECK_NULL(pAddress->pStateInfo);
pAddress->pStateInfo->bRecycleable = bRecyclable;
// write out the address
ABC_CHECK_RET(ABC_TxSaveAddress(self, pAddress, pError));
}
exit:
ABC_FREE_STR(szFile);
ABC_FREE_STR(szAddrDir);
ABC_FREE_STR(szFilename);
ABC_TxFreeAddress(pAddress);
ABC_TxFreeDetails(pNewDetails);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Generate the QR code for a previously created receive request.
*
* @param szRequestID ID of this request
* @param pszURI Pointer to string to store URI(optional)
* @param paData Pointer to store array of data bytes (0x0 white, 0x1 black)
* @param pWidth Pointer to store width of image (image will be square)
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxGenerateRequestQRCode(tABC_WalletID self,
const char *szRequestID,
char **pszURI,
unsigned char **paData,
unsigned int *pWidth,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxAddress *pAddress = NULL;
QRcode *qr = NULL;
unsigned char *aData = NULL;
unsigned int length = 0;
char *szURI = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// load the request/address
ABC_CHECK_RET(ABC_TxLoadAddress(self, szRequestID, &pAddress, pError));
ABC_CHECK_NULL(pAddress->pDetails);
// Get the URL string for this info
tABC_BitcoinURIInfo infoURI;
memset(&infoURI, 0, sizeof(tABC_BitcoinURIInfo));
infoURI.amountSatoshi = pAddress->pDetails->amountSatoshi;
infoURI.szAddress = pAddress->szPubAddress;
// Set the label if there is one
ABC_CHECK_RET(ABC_TxBuildFromLabel(self, &(infoURI.szLabel), pError));
// if there is a note
if (pAddress->pDetails->szNotes)
{
if (strlen(pAddress->pDetails->szNotes) > 0)
{
infoURI.szMessage = pAddress->pDetails->szNotes;
}
}
ABC_CHECK_RET(ABC_BridgeEncodeBitcoinURI(&szURI, &infoURI, pError));
// encode our string
ABC_DebugLog("Encoding: %s", szURI);
qr = QRcode_encodeString(szURI, 0, QR_ECLEVEL_L, QR_MODE_8, 1);
ABC_CHECK_ASSERT(qr != NULL, ABC_CC_Error, "Unable to create QR code");
length = qr->width * qr->width;
ABC_ARRAY_NEW(aData, length, unsigned char);
for (unsigned i = 0; i < length; i++)
{
aData[i] = qr->data[i] & 0x1;
}
*pWidth = qr->width;
*paData = aData;
aData = NULL;
if (pszURI != NULL)
{
ABC_STRDUP(*pszURI, szURI);
}
exit:
ABC_TxFreeAddress(pAddress);
ABC_FREE_STR(szURI);
QRcode_free(qr);
ABC_CLEAR_FREE(aData, length);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Get the specified transactions.
*
* @param szID ID of the transaction
* @param ppTransaction Location to store allocated transaction
* (caller must free)
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxGetTransaction(tABC_WalletID self,
const char *szID,
tABC_TxInfo **ppTransaction,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szFilename = NULL;
tABC_Tx *pTx = NULL;
tABC_TxInfo *pTransaction = NULL;
bool bExists = false;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
*ppTransaction = NULL;
// find the filename of the existing transaction
// first try the internal
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, true, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
// if the internal doesn't exist
if (bExists == false)
{
// try the external
ABC_FREE_STR(szFilename);
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, false, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
}
ABC_CHECK_ASSERT(bExists == true, ABC_CC_NoTransaction, "Transaction does not exist");
// load the existing transaction
ABC_CHECK_RET(ABC_TxLoadTransactionInfo(self, szFilename, &pTransaction, pError));
// assign final result
*ppTransaction = pTransaction;
pTransaction = NULL;
exit:
ABC_FREE_STR(szFilename);
ABC_TxFreeTx(pTx);
ABC_TxFreeTransaction(pTransaction);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Gets the transactions associated with the given wallet.
*
* @param startTime Return transactions after this time
* @param endTime Return transactions before this time
* @param paTransactions Pointer to store array of transactions info pointers
* @param pCount Pointer to store number of transactions
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxGetTransactions(tABC_WalletID self,
int64_t startTime,
int64_t endTime,
tABC_TxInfo ***paTransactions,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szTxDir = NULL;
tABC_FileIOList *pFileList = NULL;
char *szFilename = NULL;
tABC_TxInfo **aTransactions = NULL;
unsigned int count = 0;
bool bExists = false;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_RET(ABC_FileIOMutexLock(pError)); // we want this as an atomic files system function
*paTransactions = NULL;
*pCount = 0;
// get the directory name
ABC_CHECK_RET(ABC_WalletGetTxDirName(&szTxDir, self.szUUID, pError));
// if there is a transaction directory
ABC_CHECK_RET(ABC_FileIOFileExists(szTxDir, &bExists, pError));
if (bExists == true)
{
ABC_STR_NEW(szFilename, ABC_FILEIO_MAX_PATH_LENGTH + 1);
// get all the files in the transaction directory
ABC_FileIOCreateFileList(&pFileList, szTxDir, NULL);
for (int i = 0; i < pFileList->nCount; i++)
{
// if this file is a normal file
if (pFileList->apFiles[i]->type == ABC_FileIOFileType_Regular)
{
// create the filename for this transaction
sprintf(szFilename, "%s/%s", szTxDir, pFileList->apFiles[i]->szName);
// get the transaction type
tTxType type = TxType_None;
ABC_CHECK_RET(ABC_TxGetTxTypeAndBasename(szFilename, &type, NULL, pError));
// if this is a transaction file (based upon name)
if (type != TxType_None)
{
bool bHasInternalEquivalent = false;
// if this is an external transaction
if (type == TxType_External)
{
// check if it has an internal equivalent and, if so, delete the external
ABC_CHECK_RET(ABC_TxCheckForInternalEquivalent(szFilename, &bHasInternalEquivalent, pError));
}
// if this doesn't not have an internal equivalent (or is an internal itself)
if (bHasInternalEquivalent == false)
{
// add this transaction to the array
ABC_CHECK_RET(ABC_TxLoadTxAndAppendToArray(self,
startTime,
endTime,
szFilename,
&aTransactions,
&count,
pError));
}
}
}
}
}
// if we have more than one, then let's sort them
if (count > 1)
{
// sort the transactions by creation date using qsort
qsort(aTransactions, count, sizeof(tABC_TxInfo *), ABC_TxInfoPtrCompare);
}
// store final results
*paTransactions = aTransactions;
aTransactions = NULL;
*pCount = count;
count = 0;
exit:
ABC_FREE_STR(szTxDir);
ABC_FREE_STR(szFilename);
ABC_FileIOFreeFileList(pFileList);
ABC_TxFreeTransactions(aTransactions, count);
ABC_FileIOMutexUnlock(NULL);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Searches transactions associated with the given wallet.
*
* @param szQuery Query to search
* @param paTransactions Pointer to store array of transactions info pointers
* @param pCount Pointer to store number of transactions
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxSearchTransactions(tABC_WalletID self,
const char *szQuery,
tABC_TxInfo ***paTransactions,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_TxInfo **aTransactions = NULL;
tABC_TxInfo **aSearchTransactions = NULL;
unsigned int i;
unsigned int count = 0;
unsigned int matchCount = 0;
char satoshi[15];
char currency[15];
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
ABC_CHECK_NULL(paTransactions);
*paTransactions = NULL;
ABC_CHECK_NULL(pCount);
*pCount = 0;
ABC_TxGetTransactions(self, ABC_GET_TX_ALL_TIMES, ABC_GET_TX_ALL_TIMES,
&aTransactions, &count, pError);
ABC_ARRAY_NEW(aSearchTransactions, count, tABC_TxInfo*);
for (i = 0; i < count; i++) {
memset(satoshi, '\0', 15);
memset(currency, '\0', 15);
tABC_TxInfo *pInfo = aTransactions[i];
snprintf(satoshi, 15, "%ld", pInfo->pDetails->amountSatoshi);
snprintf(currency, 15, "%f", pInfo->pDetails->amountCurrency);
if (ABC_TxStrStr(satoshi, szQuery, pError))
{
aSearchTransactions[matchCount] = pInfo;
matchCount++;
continue;
}
if (ABC_TxStrStr(currency, szQuery, pError))
{
aSearchTransactions[matchCount] = pInfo;
matchCount++;
continue;
}
if (ABC_TxStrStr(pInfo->pDetails->szName, szQuery, pError))
{
aSearchTransactions[matchCount] = pInfo;
matchCount++;
continue;
}
else if (ABC_TxStrStr(pInfo->pDetails->szCategory, szQuery, pError))
{
aSearchTransactions[matchCount] = pInfo;
matchCount++;
continue;
}
else if (ABC_TxStrStr(pInfo->pDetails->szNotes, szQuery, pError))
{
aSearchTransactions[matchCount] = pInfo;
matchCount++;
continue;
} else {
ABC_TxFreeTransaction(pInfo);
}
aTransactions[i] = NULL;
}
if (matchCount > 0)
{
ABC_ARRAY_RESIZE(aSearchTransactions, matchCount, tABC_TxInfo*);
}
*paTransactions = aSearchTransactions;
*pCount = matchCount;
aTransactions = NULL;
exit:
ABC_FREE(aTransactions);
return cc;
}
/**
* Looks to see if a matching internal (i.e., -int) version of this file exists.
* If it does, this external version is deleted.
*
* @param szFilename Filename of transaction
* @param pbEquivalent Pointer to store result
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxCheckForInternalEquivalent(const char *szFilename,
bool *pbEquivalent,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szBasename = NULL;
char *szFilenameInt = NULL;
tTxType type = TxType_None;
ABC_CHECK_NULL(szFilename);
ABC_CHECK_NULL(pbEquivalent);
*pbEquivalent = false;
// get the type and the basename of this transaction
ABC_CHECK_RET(ABC_TxGetTxTypeAndBasename(szFilename, &type, &szBasename, pError));
// if this is an external
if (type == TxType_External)
{
// create the internal version of the filename
ABC_STR_NEW(szFilenameInt, ABC_FILEIO_MAX_PATH_LENGTH + 1);
sprintf(szFilenameInt, "%s%s", szBasename, TX_INTERNAL_SUFFIX);
// check if this internal version of the file exists
bool bExists = false;
ABC_CHECK_RET(ABC_FileIOFileExists(szFilenameInt, &bExists, pError));
// if the internal version exists
if (bExists)
{
// delete the external version (this one)
ABC_CHECK_RET(ABC_FileIODeleteFile(szFilename, pError));
*pbEquivalent = true;
}
}
exit:
ABC_FREE_STR(szBasename);
ABC_FREE_STR(szFilenameInt);
return cc;
}
/**
* Given a potential transaction filename, determines the type and
* creates an allocated basename if it is a transaction type.
*
* @param szFilename Filename of potential transaction
* @param pType Pointer to store type
* @param pszBasename Pointer to store allocated basename (optional)
* (caller must free)
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxGetTxTypeAndBasename(const char *szFilename,
tTxType *pType,
char **pszBasename,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szBasename = NULL;
unsigned sizeSuffix = 0;
ABC_CHECK_NULL(szFilename);
ABC_CHECK_NULL(pType);
// assume nothing found
*pType = TxType_None;
if (pszBasename != NULL)
{
*pszBasename = NULL;
}
// look for external the suffix
sizeSuffix = strlen(TX_EXTERNAL_SUFFIX);
if (strlen(szFilename) > sizeSuffix)
{
char *szSuffix = (char *) szFilename + (strlen(szFilename) - sizeSuffix);
// if this file ends with the external suffix
if (strcmp(szSuffix, TX_EXTERNAL_SUFFIX) == 0)
{
*pType = TxType_External;
// if they want the basename
if (pszBasename != NULL)
{
ABC_STRDUP(szBasename, szFilename);
szBasename[strlen(szFilename) - sizeSuffix] = '\0';
}
}
}
// if we haven't found it yet
if (TxType_None == *pType)
{
// check for the internal
sizeSuffix = strlen(TX_INTERNAL_SUFFIX);
if (strlen(szFilename) > sizeSuffix)
{
char *szSuffix = (char *) szFilename + (strlen(szFilename) - sizeSuffix);
// if this file ends with the external suffix
if (strcmp(szSuffix, TX_INTERNAL_SUFFIX) == 0)
{
*pType = TxType_Internal;
// if they want the basename
if (pszBasename != NULL)
{
ABC_STRDUP(szBasename, szFilename);
szBasename[strlen(szFilename) - sizeSuffix] = '\0';
}
}
}
}
if (pszBasename != NULL)
{
*pszBasename = szBasename;
}
szBasename = NULL;
exit:
ABC_FREE_STR(szBasename);
return cc;
}
/**
* Load the specified transaction info.
*
* @param szFilename Filename of the transaction
* @param ppTransaction Location to store allocated transaction
* (caller must free)
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxLoadTransactionInfo(tABC_WalletID self,
const char *szFilename,
tABC_TxInfo **ppTransaction,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_Tx *pTx = NULL;
tABC_TxInfo *pTransaction = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
*ppTransaction = NULL;
// load the transaction
ABC_CHECK_RET(ABC_TxLoadTransaction(self, szFilename, &pTx, pError));
ABC_CHECK_NULL(pTx->pDetails);
ABC_CHECK_NULL(pTx->pStateInfo);
// steal the data and assign it to our new struct
ABC_NEW(pTransaction, tABC_TxInfo);
pTransaction->szID = pTx->szID;
pTx->szID = NULL;
pTransaction->szMalleableTxId = pTx->pStateInfo->szMalleableTxId;
pTx->pStateInfo->szMalleableTxId = NULL;
pTransaction->timeCreation = pTx->pStateInfo->timeCreation;
pTransaction->pDetails = pTx->pDetails;
pTx->pDetails = NULL;
pTransaction->countOutputs = pTx->countOutputs;
pTx->countOutputs = 0;
pTransaction->aOutputs = pTx->aOutputs;
pTx->aOutputs = NULL;
// assign final result
*ppTransaction = pTransaction;
pTransaction = NULL;
exit:
ABC_TxFreeTx(pTx);
ABC_TxFreeTransaction(pTransaction);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Loads the given transaction info and adds it to the end of the array
*
* @param szFilename Filename of transaction
* @param paTransactions Pointer to array into which the transaction will be added
* @param pCount Pointer to store number of transactions (will be updated)
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxLoadTxAndAppendToArray(tABC_WalletID self,
int64_t startTime,
int64_t endTime,
const char *szFilename,
tABC_TxInfo ***paTransactions,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxInfo *pTransaction = NULL;
tABC_TxInfo **aTransactions = NULL;
unsigned int count = 0;
// hold on to current values
count = *pCount;
aTransactions = *paTransactions;
// load it into the info transaction structure
ABC_CHECK_RET(ABC_TxLoadTransactionInfo(self, szFilename, &pTransaction, pError));
if ((endTime == ABC_GET_TX_ALL_TIMES) ||
(pTransaction->timeCreation >= startTime &&
pTransaction->timeCreation < endTime))
{
// create space for new entry
if (aTransactions == NULL)
{
ABC_ARRAY_NEW(aTransactions, 1, tABC_TxInfo*);
count = 1;
}
else
{
count++;
ABC_ARRAY_RESIZE(aTransactions, count, tABC_TxInfo*);
}
// add it to the array
aTransactions[count - 1] = pTransaction;
pTransaction = NULL;
// assign the values to the caller
*paTransactions = aTransactions;
*pCount = count;
}
exit:
ABC_TxFreeTransaction(pTransaction);
return cc;
}
/**
* Frees the given transaction
*
* @param pTransaction Pointer to transaction to free
*/
void ABC_TxFreeTransaction(tABC_TxInfo *pTransaction)
{
if (pTransaction)
{
ABC_FREE_STR(pTransaction->szID);
ABC_TxFreeOutputs(pTransaction->aOutputs, pTransaction->countOutputs);
ABC_TxFreeDetails(pTransaction->pDetails);
ABC_CLEAR_FREE(pTransaction, sizeof(tABC_TxInfo));
}
}
/**
* Frees the given array of transactions
*
* @param aTransactions Array of transactions
* @param count Number of transactions
*/
void ABC_TxFreeTransactions(tABC_TxInfo **aTransactions,
unsigned int count)
{
if (aTransactions && count > 0)
{
for (unsigned i = 0; i < count; i++)
{
ABC_TxFreeTransaction(aTransactions[i]);
}
ABC_FREE(aTransactions);
}
}
/**
* Sets the details for a specific existing transaction.
*
* @param szID ID of the transaction
* @param pDetails Details for the transaction
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxSetTransactionDetails(tABC_WalletID self,
const char *szID,
tABC_TxDetails *pDetails,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szFilename = NULL;
tABC_Tx *pTx = NULL;
bool bExists = false;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// find the filename of the existing transaction
// first try the internal
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, true, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
// if the internal doesn't exist
if (bExists == false)
{
// try the external
ABC_FREE_STR(szFilename);
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, false, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
}
ABC_CHECK_ASSERT(bExists == true, ABC_CC_NoTransaction, "Transaction does not exist");
// load the existing transaction
ABC_CHECK_RET(ABC_TxLoadTransaction(self, szFilename, &pTx, pError));
ABC_CHECK_NULL(pTx->pDetails);
ABC_CHECK_NULL(pTx->pStateInfo);
// modify the details
pTx->pDetails->amountSatoshi = pDetails->amountSatoshi;
pTx->pDetails->amountFeesAirbitzSatoshi = pDetails->amountFeesAirbitzSatoshi;
pTx->pDetails->amountFeesMinersSatoshi = pDetails->amountFeesMinersSatoshi;
pTx->pDetails->amountCurrency = pDetails->amountCurrency;
pTx->pDetails->bizId = pDetails->bizId;
pTx->pDetails->attributes = pDetails->attributes;
ABC_FREE_STR(pTx->pDetails->szName);
ABC_STRDUP(pTx->pDetails->szName, pDetails->szName);
ABC_FREE_STR(pTx->pDetails->szCategory);
ABC_STRDUP(pTx->pDetails->szCategory, pDetails->szCategory);
ABC_FREE_STR(pTx->pDetails->szNotes);
ABC_STRDUP(pTx->pDetails->szNotes, pDetails->szNotes);
// re-save the transaction
ABC_CHECK_RET(ABC_TxSaveTransaction(self, pTx, pError));
exit:
ABC_FREE_STR(szFilename);
ABC_TxFreeTx(pTx);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Gets the details for a specific existing transaction.
*
* @param szID ID of the transaction
* @param ppDetails Location to store allocated details for the transaction
* (caller must free)
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxGetTransactionDetails(tABC_WalletID self,
const char *szID,
tABC_TxDetails **ppDetails,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szFilename = NULL;
tABC_Tx *pTx = NULL;
tABC_TxDetails *pDetails = NULL;
bool bExists = false;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// find the filename of the existing transaction
// first try the internal
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, true, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
// if the internal doesn't exist
if (bExists == false)
{
// try the external
ABC_FREE_STR(szFilename);
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, false, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
}
ABC_CHECK_ASSERT(bExists == true, ABC_CC_NoTransaction, "Transaction does not exist");
// load the existing transaction
ABC_CHECK_RET(ABC_TxLoadTransaction(self, szFilename, &pTx, pError));
ABC_CHECK_NULL(pTx->pDetails);
ABC_CHECK_NULL(pTx->pStateInfo);
// duplicate the details
ABC_CHECK_RET(ABC_TxDupDetails(&pDetails, pTx->pDetails, pError));
// assign final result
*ppDetails = pDetails;
pDetails = NULL;
exit:
ABC_FREE_STR(szFilename);
ABC_TxFreeTx(pTx);
ABC_TxFreeDetails(pDetails);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Gets the bit coin public address for a specified request
*
* @param szRequestID ID of request
* @param pszAddress Location to store allocated address string (caller must free)
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxGetRequestAddress(tABC_WalletID self,
const char *szRequestID,
char **pszAddress,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxAddress *pAddress = NULL;
*pszAddress = NULL;
ABC_CHECK_RET(
ABC_TxLoadAddress(self, szRequestID,
&pAddress, pError));
ABC_STRDUP(*pszAddress, pAddress->szPubAddress);
exit:
ABC_TxFreeAddress(pAddress);
return cc;
}
/**
* Gets the pending requests associated with the given wallet.
*
* @param paTransactions Pointer to store array of requests info pointers
* @param pCount Pointer to store number of requests
* @param pError A pointer to the location to store the error if there is one
*/
tABC_CC ABC_TxGetPendingRequests(tABC_WalletID self,
tABC_RequestInfo ***paRequests,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxAddress **aAddresses = NULL;
unsigned int count = 0;
tABC_RequestInfo **aRequests = NULL;
unsigned int countPending = 0;
tABC_RequestInfo *pRequest = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
*paRequests = NULL;
*pCount = 0;
// start by retrieving all address for this wallet
ABC_CHECK_RET(ABC_TxGetAddresses(self, &aAddresses, &count, pError));
// if there are any addresses
if (count > 0)
{
// print out the addresses - debug
//ABC_TxPrintAddresses(aAddresses, count);
// walk through all the addresses looking for those with outstanding balances
for (unsigned i = 0; i < count; i++)
{
tABC_TxAddress *pAddr = aAddresses[i];
ABC_CHECK_NULL(pAddr);
tABC_TxDetails *pDetails = pAddr->pDetails;
// if this address has user details associated with it (i.e., was created by the user)
if (pDetails)
{
tTxAddressStateInfo *pState = pAddr->pStateInfo;
ABC_CHECK_NULL(pState);
// if this is not a recyclable address (i.e., it was specifically used for a transaction)
if (pState->bRecycleable == false)
{
// if this address was used for a request of funds (i.e., not a send)
int64_t requestSatoshi = pDetails->amountSatoshi;
if (requestSatoshi >= 0)
{
// get the outstanding balanace on this request/address
int64_t owedSatoshi = 0;
ABC_CHECK_RET(ABC_TxGetAddressOwed(pAddr, &owedSatoshi, pError));
// if money is still owed
if (owedSatoshi > 0)
{
// create this request
ABC_NEW(pRequest, tABC_RequestInfo);
ABC_STRDUP(pRequest->szID, pAddr->szID);
pRequest->timeCreation = pState->timeCreation;
pRequest->owedSatoshi = owedSatoshi;
pRequest->amountSatoshi = pDetails->amountSatoshi - owedSatoshi;
pRequest->pDetails = pDetails; // steal the info as is
pDetails = NULL;
pAddr->pDetails = NULL; // we are taking this for our own so later we don't want to free it
// increase the array size
if (countPending > 0)
{
countPending++;
ABC_ARRAY_RESIZE(aRequests, countPending, tABC_RequestInfo*);
}
else
{
ABC_ARRAY_NEW(aRequests, 1, tABC_RequestInfo*);
countPending = 1;
}
// add it to the array
aRequests[countPending - 1] = pRequest;
pRequest = NULL;
}
}
}
}
}
}
// assign final results
*paRequests = aRequests;
aRequests = NULL;
*pCount = countPending;
countPending = 0;
exit:
ABC_TxFreeAddresses(aAddresses, count);
ABC_TxFreeRequests(aRequests, countPending);
ABC_TxFreeRequest(pRequest);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Given an address, this function returns the balance remaining on the address
* It does this by checking the activity amounts against the initial request amount.
* Negative indicates satoshi is still 'owed' on the address, 'positive' means excess was paid.
*
* the big assumption here is that address can be used for making payments after they have been used for
* receiving payment but those should not be taken into account when determining what has been paid on the
* address.
*
* @param pAddr Address to check
* @param pSatoshiOwed Ptr into which owed amount is stored
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxGetAddressOwed(tABC_TxAddress *pAddr,
int64_t *pSatoshiOwed,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
int64_t satoshiOwed = 0;
tTxAddressStateInfo *pState = NULL;
tABC_TxDetails *pDetails = NULL;
ABC_CHECK_NULL(pSatoshiOwed);
*pSatoshiOwed = 0;
ABC_CHECK_NULL(pAddr);
pDetails = pAddr->pDetails;
ABC_CHECK_NULL(pDetails);
pState = pAddr->pStateInfo;
ABC_CHECK_NULL(pState);
// start with the amount requested
satoshiOwed = pDetails->amountSatoshi;
// if any activities have occured on this address
if ((pState->aActivities != NULL) && (pState->countActivities > 0))
{
for (unsigned i = 0; i < pState->countActivities; i++)
{
// if this activity is money paid on the address
// note: here is where negative activity is ignored
// the big assumption here is that address can be used
// for making payments after they have been used for
// receiving payment but those should not be taken into
// account when determining what has been paid on the
// address
if (pState->aActivities[i].amountSatoshi > 0)
{
// remove that from the request amount
satoshiOwed -= pState->aActivities[i].amountSatoshi;
}
}
}
// assign final balance
*pSatoshiOwed = satoshiOwed;
exit:
return cc;
}
/**
* Create a label based off the user settings
*
* @param pszLabel The label will be returned in this parameter
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxBuildFromLabel(tABC_WalletID self,
char **pszLabel, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_AccountSettings *pSettings = NULL;
tABC_U08Buf Label = ABC_BUF_NULL;
ABC_CHECK_NULL(pszLabel);
*pszLabel = NULL;
ABC_CHECK_RET(ABC_AccountSettingsLoad(self.pKeys, &pSettings, pError));
if (pSettings->bNameOnPayments && pSettings->szFullName)
{
ABC_BUF_DUP_PTR(Label, pSettings->szFullName, strlen(pSettings->szFullName));
}
if (ABC_BUF_PTR(Label) != NULL)
{
// Append null byte
ABC_BUF_APPEND_PTR(Label, "", 1);
*pszLabel = (char *) ABC_BUF_PTR(Label);
ABC_BUF_CLEAR(Label);
}
exit:
ABC_BUF_FREE(Label);
ABC_FreeAccountSettings(pSettings);
return cc;
}
/**
* Frees the given requets
*
* @param pRequest Ptr to request to free
*/
static
void ABC_TxFreeRequest(tABC_RequestInfo *pRequest)
{
if (pRequest)
{
ABC_TxFreeDetails(pRequest->pDetails);
ABC_CLEAR_FREE(pRequest, sizeof(tABC_RequestInfo));
}
}
/**
* Frees the given array of requets
*
* @param aRequests Array of requests
* @param count Number of requests
*/
void ABC_TxFreeRequests(tABC_RequestInfo **aRequests,
unsigned int count)
{
if (aRequests && count > 0)
{
for (unsigned i = 0; i < count; i++)
{
ABC_TxFreeRequest(aRequests[i]);
}
ABC_FREE(aRequests);
}
}
/**
* Gets the filename for a given transaction
* format is: N-Base58(HMAC256(TxID,MK)).json
*
* @param pszFilename Output filename name. The caller must free this.
*/
static
tABC_CC ABC_TxCreateTxFilename(tABC_WalletID self, char **pszFilename, const char *szTxID, bool bInternal, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
char *szTxDir = NULL;
tABC_U08Buf MK = ABC_BUF_NULL;
tABC_U08Buf DataHMAC = ABC_BUF_NULL;
char *szDataBase58 = NULL;
tABC_U08Buf TxID = ABC_BUF_NULL;
*pszFilename = NULL;
// Get the master key we will need to encode the filename
// (note that this will also make sure the account and wallet exist)
ABC_CHECK_RET(ABC_WalletGetMK(self, &MK, pError));
ABC_CHECK_RET(ABC_WalletGetTxDirName(&szTxDir, self.szUUID, pError));
// create an hmac-256 of the TxID
ABC_BUF_SET_PTR(TxID, (unsigned char *)szTxID, strlen(szTxID));
ABC_CHECK_RET(ABC_CryptoHMAC256(TxID, MK, &DataHMAC, pError));
// create a base58 of the hmac-256 TxID
ABC_CHECK_RET(ABC_CryptoBase58Encode(DataHMAC, &szDataBase58, pError));
ABC_STR_NEW(*pszFilename, ABC_FILEIO_MAX_PATH_LENGTH);
sprintf(*pszFilename, "%s/%s%s", szTxDir, szDataBase58, (bInternal ? TX_INTERNAL_SUFFIX : TX_EXTERNAL_SUFFIX));
exit:
ABC_FREE_STR(szTxDir);
ABC_BUF_FREE(DataHMAC);
ABC_FREE_STR(szDataBase58);
return cc;
}
/**
* Loads a transaction from disk
*
* @param ppTx Pointer to location to hold allocated transaction
* (it is the callers responsiblity to free this transaction)
*/
static
tABC_CC ABC_TxLoadTransaction(tABC_WalletID self,
const char *szFilename,
tABC_Tx **ppTx,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_U08Buf MK = ABC_BUF_NULL;
json_t *pJSON_Root = NULL;
tABC_Tx *pTx = NULL;
bool bExists = false;
json_t *jsonVal = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
*ppTx = NULL;
// Get the master key we will need to decode the transaction data
// (note that this will also make sure the account and wallet exist)
ABC_CHECK_RET(ABC_WalletGetMK(self, &MK, pError));
// make sure the transaction exists
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
ABC_CHECK_ASSERT(bExists == true, ABC_CC_NoTransaction, "Transaction does not exist");
// load the json object (load file, decrypt it, create json object
ABC_CHECK_RET(ABC_CryptoDecryptJSONFileObject(szFilename, MK, &pJSON_Root, pError));
// start decoding
ABC_NEW(pTx, tABC_Tx);
// get the id
jsonVal = json_object_get(pJSON_Root, JSON_TX_ID_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_string(jsonVal)), ABC_CC_JSONError, "Error parsing JSON transaction package - missing id");
ABC_STRDUP(pTx->szID, json_string_value(jsonVal));
// get the state object
ABC_CHECK_RET(ABC_TxDecodeTxState(pJSON_Root, &(pTx->pStateInfo), pError));
// get the details object
ABC_CHECK_RET(ABC_TxDecodeTxDetails(pJSON_Root, &(pTx->pDetails), pError));
// get advanced details
ABC_CHECK_RET(
ABC_BridgeTxDetails(self.szUUID, pTx->pStateInfo->szMalleableTxId,
&(pTx->aOutputs), &(pTx->countOutputs),
&(pTx->pDetails->amountSatoshi),
&(pTx->pDetails->amountFeesMinersSatoshi),
pError));
// assign final result
*ppTx = pTx;
pTx = NULL;
exit:
if (pJSON_Root) json_decref(pJSON_Root);
ABC_TxFreeTx(pTx);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Retrieve an Address by the public address
*
* @param szMatchAddress The public address to find a match against
* @param ppMatched A pointer to store the matched address to (caller must free)
* @param pError A pointer to the location to store the error if there is one
*/
static tABC_CC ABC_TxFindRequest(tABC_WalletID self,
const char *szMatchAddress,
tABC_TxAddress **ppMatched,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
tABC_TxAddress **aAddresses = NULL;
tABC_TxAddress *pMatched = NULL;
unsigned int countAddresses = 0;
ABC_CHECK_NULL(ppMatched);
ABC_CHECK_RET(
ABC_TxGetAddresses(self, &aAddresses, &countAddresses, pError));
for (unsigned i = 0; i < countAddresses; i++)
{
if (strncmp(aAddresses[i]->szPubAddress, szMatchAddress,
strlen(aAddresses[i]->szPubAddress)) == 0) {
ABC_CHECK_RET(ABC_TxLoadAddress(self, aAddresses[i]->szID,
&pMatched, pError));
break;
}
}
*ppMatched = pMatched;
exit:
ABC_TxFreeAddresses(aAddresses, countAddresses);
return cc;
}
/**
* Decodes the transaction state data from a json transaction object
*
* @param ppInfo Pointer to store allocated state info
* (it is the callers responsiblity to free this)
*/
static
tABC_CC ABC_TxDecodeTxState(json_t *pJSON_Obj, tTxStateInfo **ppInfo, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tTxStateInfo *pInfo = NULL;
json_t *jsonState = NULL;
json_t *jsonVal = NULL;
ABC_CHECK_NULL(pJSON_Obj);
ABC_CHECK_NULL(ppInfo);
*ppInfo = NULL;
// allocate the struct
ABC_NEW(pInfo, tTxStateInfo);
// get the state object
jsonState = json_object_get(pJSON_Obj, JSON_TX_STATE_FIELD);
ABC_CHECK_ASSERT((jsonState && json_is_object(jsonState)), ABC_CC_JSONError, "Error parsing JSON transaction package - missing state");
// get the creation date
jsonVal = json_object_get(jsonState, JSON_CREATION_DATE_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_integer(jsonVal)), ABC_CC_JSONError, "Error parsing JSON transaction package - missing creation date");
pInfo->timeCreation = json_integer_value(jsonVal);
jsonVal = json_object_get(jsonState, JSON_MALLEABLE_TX_ID);
if (jsonVal)
{
ABC_CHECK_ASSERT((jsonVal && json_is_string(jsonVal)), ABC_CC_JSONError, "Error parsing JSON transaction package - missing malleable tx id");
ABC_STRDUP(pInfo->szMalleableTxId, json_string_value(jsonVal));
}
// get the internal boolean
jsonVal = json_object_get(jsonState, JSON_TX_INTERNAL_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_boolean(jsonVal)), ABC_CC_JSONError, "Error parsing JSON transaction package - missing internal boolean");
pInfo->bInternal = json_is_true(jsonVal) ? true : false;
// assign final result
*ppInfo = pInfo;
pInfo = NULL;
exit:
ABC_CLEAR_FREE(pInfo, sizeof(tTxStateInfo));
return cc;
}
/**
* Decodes the transaction details data from a json transaction or address object
*
* @param ppInfo Pointer to store allocated meta info
* (it is the callers responsiblity to free this)
*/
static
tABC_CC ABC_TxDecodeTxDetails(json_t *pJSON_Obj, tABC_TxDetails **ppDetails, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxDetails *pDetails = NULL;
json_t *jsonDetails = NULL;
json_t *jsonVal = NULL;
ABC_CHECK_NULL(pJSON_Obj);
ABC_CHECK_NULL(ppDetails);
*ppDetails = NULL;
// allocated the struct
ABC_NEW(pDetails, tABC_TxDetails);
// get the details object
jsonDetails = json_object_get(pJSON_Obj, JSON_DETAILS_FIELD);
ABC_CHECK_ASSERT((jsonDetails && json_is_object(jsonDetails)), ABC_CC_JSONError, "Error parsing JSON details package - missing meta data (details)");
// get the satoshi field
jsonVal = json_object_get(jsonDetails, JSON_AMOUNT_SATOSHI_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_integer(jsonVal)), ABC_CC_JSONError, "Error parsing JSON details package - missing satoshi amount");
pDetails->amountSatoshi = json_integer_value(jsonVal);
// get the airbitz fees satoshi field
jsonVal = json_object_get(jsonDetails, JSON_AMOUNT_AIRBITZ_FEE_SATOSHI_FIELD);
if (jsonVal)
{
ABC_CHECK_ASSERT(json_is_integer(jsonVal), ABC_CC_JSONError, "Error parsing JSON details package - malformed airbitz fees field");
pDetails->amountFeesAirbitzSatoshi = json_integer_value(jsonVal);
}
// get the miners fees satoshi field
jsonVal = json_object_get(jsonDetails, JSON_AMOUNT_MINERS_FEE_SATOSHI_FIELD);
if (jsonVal)
{
ABC_CHECK_ASSERT(json_is_integer(jsonVal), ABC_CC_JSONError, "Error parsing JSON details package - malformed miners fees field");
pDetails->amountFeesMinersSatoshi = json_integer_value(jsonVal);
}
// get the currency field
jsonVal = json_object_get(jsonDetails, JSON_TX_AMOUNT_CURRENCY_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_real(jsonVal)), ABC_CC_JSONError, "Error parsing JSON details package - missing currency amount");
pDetails->amountCurrency = json_real_value(jsonVal);
// get the name field
jsonVal = json_object_get(jsonDetails, JSON_TX_NAME_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_string(jsonVal)), ABC_CC_JSONError, "Error parsing JSON details package - missing name");
ABC_STRDUP(pDetails->szName, json_string_value(jsonVal));
// get the business-directory id field
jsonVal = json_object_get(jsonDetails, JSON_TX_BIZID_FIELD);
if (jsonVal)
{
ABC_CHECK_ASSERT(json_is_integer(jsonVal), ABC_CC_JSONError, "Error parsing JSON details package - malformed directory bizId field");
pDetails->bizId = json_integer_value(jsonVal);
}
// get the category field
jsonVal = json_object_get(jsonDetails, JSON_TX_CATEGORY_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_string(jsonVal)), ABC_CC_JSONError, "Error parsing JSON details package - missing category");
ABC_STRDUP(pDetails->szCategory, json_string_value(jsonVal));
// get the notes field
jsonVal = json_object_get(jsonDetails, JSON_TX_NOTES_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_string(jsonVal)), ABC_CC_JSONError, "Error parsing JSON details package - missing notes");
ABC_STRDUP(pDetails->szNotes, json_string_value(jsonVal));
// get the attributes field
jsonVal = json_object_get(jsonDetails, JSON_TX_ATTRIBUTES_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_integer(jsonVal)), ABC_CC_JSONError, "Error parsing JSON details package - missing attributes");
pDetails->attributes = (unsigned int) json_integer_value(jsonVal);
// assign final result
*ppDetails = pDetails;
pDetails = NULL;
exit:
ABC_TxFreeDetails(pDetails);
return cc;
}
/**
* Free's a tABC_Tx struct and all its elements
*/
static
void ABC_TxFreeTx(tABC_Tx *pTx)
{
if (pTx)
{
ABC_FREE_STR(pTx->szID);
ABC_TxFreeDetails(pTx->pDetails);
ABC_CLEAR_FREE(pTx->pStateInfo, sizeof(tTxStateInfo));
ABC_TxFreeOutputs(pTx->aOutputs, pTx->countOutputs);
ABC_CLEAR_FREE(pTx, sizeof(tABC_Tx));
}
}
/**
* Creates the transaction directory if needed
*/
static
tABC_CC ABC_TxCreateTxDir(const char *szWalletUUID, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
char *szTxDir = NULL;
bool bExists = false;
// get the transaction directory
ABC_CHECK_RET(ABC_WalletGetTxDirName(&szTxDir, szWalletUUID, pError));
// if transaction dir doesn't exist, create it
ABC_CHECK_RET(ABC_FileIOFileExists(szTxDir, &bExists, pError));
if (true != bExists)
{
ABC_CHECK_RET(ABC_FileIOCreateDir(szTxDir, pError));
}
exit:
ABC_FREE_STR(szTxDir);
return cc;
}
/**
* Saves a transaction to disk
*
* @param pTx Pointer to transaction data
*/
static
tABC_CC ABC_TxSaveTransaction(tABC_WalletID self,
const tABC_Tx *pTx,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
int e;
tABC_U08Buf MK = ABC_BUF_NULL;
char *szFilename = NULL;
json_t *pJSON_Root = NULL;
json_t *pJSON_OutputArray = NULL;
json_t **ppJSON_Output = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_NULL(pTx->pStateInfo);
ABC_CHECK_NULL(pTx->szID);
ABC_CHECK_ASSERT(strlen(pTx->szID) > 0, ABC_CC_Error, "No transaction ID provided");
// Get the master key we will need to encode the transaction data
// (note that this will also make sure the account and wallet exist)
ABC_CHECK_RET(ABC_WalletGetMK(self, &MK, pError));
// create the json for the transaction
pJSON_Root = json_object();
ABC_CHECK_ASSERT(pJSON_Root != NULL, ABC_CC_Error, "Could not create transaction JSON object");
// set the ID
json_object_set_new(pJSON_Root, JSON_TX_ID_FIELD, json_string(pTx->szID));
// set the state info
ABC_CHECK_RET(ABC_TxEncodeTxState(pJSON_Root, pTx->pStateInfo, pError));
// set the details
ABC_CHECK_RET(ABC_TxEncodeTxDetails(pJSON_Root, pTx->pDetails, pError));
// create the addresses array object
pJSON_OutputArray = json_array();
// if there are any addresses
if ((pTx->countOutputs > 0) && (pTx->aOutputs != NULL))
{
ABC_ARRAY_NEW(ppJSON_Output, pTx->countOutputs, json_t*);
for (unsigned i = 0; i < pTx->countOutputs; i++)
{
ppJSON_Output[i] = json_object();
int retVal = json_object_set_new(ppJSON_Output[i], JSON_TX_OUTPUT_FLAG, json_boolean(pTx->aOutputs[i]->input));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
retVal = json_object_set_new(ppJSON_Output[i], JSON_TX_OUTPUT_VALUE, json_integer(pTx->aOutputs[i]->value));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
retVal = json_object_set_new(ppJSON_Output[i], JSON_TX_OUTPUT_ADDRESS, json_string(pTx->aOutputs[i]->szAddress));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
retVal = json_object_set_new(ppJSON_Output[i], JSON_TX_OUTPUT_TXID, json_string(pTx->aOutputs[i]->szTxId));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
retVal = json_object_set_new(ppJSON_Output[i], JSON_TX_OUTPUT_INDEX, json_integer(pTx->aOutputs[i]->index));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add output to the array
retVal = json_array_append_new(pJSON_OutputArray, ppJSON_Output[i]);
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
}
}
// add the address array to the object
e = json_object_set(pJSON_Root, JSON_TX_OUTPUTS_FIELD, pJSON_OutputArray);
ABC_CHECK_ASSERT(e == 0, ABC_CC_JSONError, "Could not encode JSON value");
// create the transaction directory if needed
ABC_CHECK_RET(ABC_TxCreateTxDir(self.szUUID, pError));
// get the filename for this transaction
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, pTx->szID, pTx->pStateInfo->bInternal, pError));
// save out the transaction object to a file encrypted with the master key
ABC_CHECK_RET(ABC_CryptoEncryptJSONFileObject(pJSON_Root, MK, ABC_CryptoType_AES256, szFilename, pError));
ABC_CHECK_RET(ABC_WalletDirtyCache(self, pError));
exit:
ABC_FREE_STR(szFilename);
ABC_CLEAR_FREE(ppJSON_Output, sizeof(json_t *) * pTx->countOutputs);
if (pJSON_Root) json_decref(pJSON_Root);
if (pJSON_OutputArray) json_decref(pJSON_OutputArray);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Encodes the transaction state data into the given json transaction object
*
* @param pJSON_Obj Pointer to the json object into which the state data is stored.
* @param pInfo Pointer to the state data to store in the json object.
*/
static
tABC_CC ABC_TxEncodeTxState(json_t *pJSON_Obj, tTxStateInfo *pInfo, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
json_t *pJSON_State = NULL;
int retVal = 0;
ABC_CHECK_NULL(pJSON_Obj);
ABC_CHECK_NULL(pInfo);
// create the state object
pJSON_State = json_object();
// add the creation date to the state object
retVal = json_object_set_new(pJSON_State, JSON_CREATION_DATE_FIELD, json_integer(pInfo->timeCreation));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the creation date to the state object
retVal = json_object_set_new(pJSON_State, JSON_MALLEABLE_TX_ID, json_string(pInfo->szMalleableTxId));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the internal boolean (internally created or created due to bitcoin event)
retVal = json_object_set_new(pJSON_State, JSON_TX_INTERNAL_FIELD, json_boolean(pInfo->bInternal));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the state object to the master object
retVal = json_object_set(pJSON_Obj, JSON_TX_STATE_FIELD, pJSON_State);
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
exit:
if (pJSON_State) json_decref(pJSON_State);
return cc;
}
/**
* Encodes the transaction details data into the given json transaction object
*
* @param pJSON_Obj Pointer to the json object into which the details are stored.
* @param pDetails Pointer to the details to store in the json object.
*/
static
tABC_CC ABC_TxEncodeTxDetails(json_t *pJSON_Obj, tABC_TxDetails *pDetails, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
json_t *pJSON_Details = NULL;
int retVal = 0;
ABC_CHECK_NULL(pJSON_Obj);
ABC_CHECK_NULL(pDetails);
// create the details object
pJSON_Details = json_object();
// add the satoshi field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_AMOUNT_SATOSHI_FIELD, json_integer(pDetails->amountSatoshi));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the airbitz fees satoshi field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_AMOUNT_AIRBITZ_FEE_SATOSHI_FIELD, json_integer(pDetails->amountFeesAirbitzSatoshi));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the miners fees satoshi field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_AMOUNT_MINERS_FEE_SATOSHI_FIELD, json_integer(pDetails->amountFeesMinersSatoshi));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the currency field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_TX_AMOUNT_CURRENCY_FIELD, json_real(pDetails->amountCurrency));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the name field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_TX_NAME_FIELD, json_string(pDetails->szName));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the business-directory id field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_TX_BIZID_FIELD, json_integer(pDetails->bizId));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the category field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_TX_CATEGORY_FIELD, json_string(pDetails->szCategory));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the notes field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_TX_NOTES_FIELD, json_string(pDetails->szNotes));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the attributes field to the details object
retVal = json_object_set_new(pJSON_Details, JSON_TX_ATTRIBUTES_FIELD, json_integer(pDetails->attributes));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the details object to the master object
retVal = json_object_set(pJSON_Obj, JSON_DETAILS_FIELD, pJSON_Details);
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
exit:
if (pJSON_Details) json_decref(pJSON_Details);
return cc;
}
/**
* This function is used to support sorting an array of tTxInfo pointers via qsort.
* qsort has the following documentation for the required function:
*
* Pointer to a function that compares two elements.
* This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:
*
* int compar (const void* p1, const void* p2);
*
* Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):
* return value meaning
* <0 The element pointed by p1 goes before the element pointed by p2
* 0 The element pointed by p1 is equivalent to the element pointed by p2
* >0 The element pointed by p1 goes after the element pointed by p2
*
*/
static
int ABC_TxInfoPtrCompare (const void * a, const void * b)
{
tABC_TxInfo **ppInfoA = (tABC_TxInfo **)a;
tABC_TxInfo *pInfoA = (tABC_TxInfo *)*ppInfoA;
tABC_TxInfo **ppInfoB = (tABC_TxInfo **)b;
tABC_TxInfo *pInfoB = (tABC_TxInfo *)*ppInfoB;
if (pInfoA->timeCreation < pInfoB->timeCreation) return -1;
if (pInfoA->timeCreation == pInfoB->timeCreation) return 0;
if (pInfoA->timeCreation > pInfoB->timeCreation) return 1;
return 0;
}
/**
* Sets the recycle status on an address as specified
*
* @param szAddressID ID of the address
* @param ppAddress Pointer to location to store allocated address info
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxLoadAddress(tABC_WalletID self,
const char *szAddressID,
tABC_TxAddress **ppAddress,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szFile = NULL;
char *szAddrDir = NULL;
char *szFilename = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// get the filename for this address
ABC_CHECK_RET(ABC_GetAddressFilename(self.szUUID, szAddressID, &szFile, pError));
// get the directory name
ABC_CHECK_RET(ABC_WalletGetAddressDirName(&szAddrDir, self.szUUID, pError));
// create the full filename
ABC_STR_NEW(szFilename, ABC_FILEIO_MAX_PATH_LENGTH + 1);
sprintf(szFilename, "%s/%s", szAddrDir, szFile);
// load the request address
ABC_CHECK_RET(ABC_TxLoadAddressFile(self, szFilename, ppAddress, pError));
exit:
ABC_FREE_STR(szFile);
ABC_FREE_STR(szAddrDir);
ABC_FREE_STR(szFilename);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Loads an address from disk given filename (complete path)
*
* @param ppAddress Pointer to location to hold allocated address
* (it is the callers responsiblity to free this address)
*/
static
tABC_CC ABC_TxLoadAddressFile(tABC_WalletID self,
const char *szFilename,
tABC_TxAddress **ppAddress,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_U08Buf MK = ABC_BUF_NULL;
json_t *pJSON_Root = NULL;
tABC_TxAddress *pAddress = NULL;
bool bExists = false;
json_t *jsonVal = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
*ppAddress = NULL;
// Get the master key we will need to decode the transaction data
// (note that this will also make sure the account and wallet exist)
ABC_CHECK_RET(ABC_WalletGetMK(self, &MK, pError));
// make sure the addresss exists
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
ABC_CHECK_ASSERT(bExists == true, ABC_CC_NoRequest, "Request address does not exist");
// load the json object (load file, decrypt it, create json object
ABC_CHECK_RET(ABC_CryptoDecryptJSONFileObject(szFilename, MK, &pJSON_Root, pError));
// start decoding
ABC_NEW(pAddress, tABC_TxAddress);
// get the seq and id
jsonVal = json_object_get(pJSON_Root, JSON_ADDR_SEQ_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_integer(jsonVal)), ABC_CC_JSONError, "Error parsing JSON address package - missing seq");
pAddress->seq = (uint32_t)json_integer_value(jsonVal);
ABC_STR_NEW(pAddress->szID, TX_MAX_ADDR_ID_LENGTH);
sprintf(pAddress->szID, "%u", pAddress->seq);
// get the public address field
jsonVal = json_object_get(pJSON_Root, JSON_ADDR_ADDRESS_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_string(jsonVal)), ABC_CC_JSONError, "Error parsing JSON address package - missing address");
ABC_STRDUP(pAddress->szPubAddress, json_string_value(jsonVal));
// get the state object
ABC_CHECK_RET(ABC_TxDecodeAddressStateInfo(pJSON_Root, &(pAddress->pStateInfo), pError));
// get the details object
ABC_CHECK_RET(ABC_TxDecodeTxDetails(pJSON_Root, &(pAddress->pDetails), pError));
// assign final result
*ppAddress = pAddress;
pAddress = NULL;
exit:
if (pJSON_Root) json_decref(pJSON_Root);
ABC_TxFreeAddress(pAddress);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Decodes the address state info from a json address object
*
* @param ppState Pointer to store allocated state info
* (it is the callers responsiblity to free this)
*/
static
tABC_CC ABC_TxDecodeAddressStateInfo(json_t *pJSON_Obj, tTxAddressStateInfo **ppState, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tTxAddressStateInfo *pState = NULL;
json_t *jsonState = NULL;
json_t *jsonVal = NULL;
json_t *jsonActivity = NULL;
ABC_CHECK_NULL(pJSON_Obj);
ABC_CHECK_NULL(ppState);
*ppState = NULL;
// allocated the struct
ABC_NEW(pState, tTxAddressStateInfo);
// get the state object
jsonState = json_object_get(pJSON_Obj, JSON_ADDR_STATE_FIELD);
ABC_CHECK_ASSERT((jsonState && json_is_object(jsonState)), ABC_CC_JSONError, "Error parsing JSON address package - missing state info");
// get the creation date
jsonVal = json_object_get(jsonState, JSON_CREATION_DATE_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_integer(jsonVal)), ABC_CC_JSONError, "Error parsing JSON transaction package - missing creation date");
pState->timeCreation = json_integer_value(jsonVal);
// get the internal boolean
jsonVal = json_object_get(jsonState, JSON_ADDR_RECYCLEABLE_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_boolean(jsonVal)), ABC_CC_JSONError, "Error parsing JSON address package - missing recycleable boolean");
pState->bRecycleable = json_is_true(jsonVal) ? true : false;
// get the activity array (if it exists)
jsonActivity = json_object_get(jsonState, JSON_ADDR_ACTIVITY_FIELD);
if (jsonActivity)
{
ABC_CHECK_ASSERT(json_is_array(jsonActivity), ABC_CC_JSONError, "Error parsing JSON address package - missing activity array");
// get the number of elements in the array
pState->countActivities = (int) json_array_size(jsonActivity);
if (pState->countActivities > 0)
{
ABC_ARRAY_NEW(pState->aActivities, pState->countActivities, tTxAddressActivity);
for (unsigned i = 0; i < pState->countActivities; i++)
{
json_t *pJSON_Elem = json_array_get(jsonActivity, i);
ABC_CHECK_ASSERT((pJSON_Elem && json_is_object(pJSON_Elem)), ABC_CC_JSONError, "Error parsing JSON address package - missing activity array element");
// get the tx id
jsonVal = json_object_get(pJSON_Elem, JSON_TX_ID_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_string(jsonVal)), ABC_CC_JSONError, "Error parsing JSON address package - missing activity txid");
ABC_STRDUP(pState->aActivities[i].szTxID, json_string_value(jsonVal));
// get the date field
jsonVal = json_object_get(pJSON_Elem, JSON_ADDR_DATE_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_integer(jsonVal)), ABC_CC_JSONError, "Error parsing JSON address package - missing date");
pState->aActivities[i].timeCreation = json_integer_value(jsonVal);
// get the satoshi field
jsonVal = json_object_get(pJSON_Elem, JSON_AMOUNT_SATOSHI_FIELD);
ABC_CHECK_ASSERT((jsonVal && json_is_integer(jsonVal)), ABC_CC_JSONError, "Error parsing JSON address package - missing satoshi amount");
pState->aActivities[i].amountSatoshi = json_integer_value(jsonVal);
}
}
}
else
{
pState->countActivities = 0;
}
// assign final result
*ppState = pState;
pState = NULL;
exit:
ABC_TxFreeAddressStateInfo(pState);
return cc;
}
/**
* Saves an address to disk
*
* @param pAddress Pointer to address data
*/
static
tABC_CC ABC_TxSaveAddress(tABC_WalletID self,
const tABC_TxAddress *pAddress,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_U08Buf MK = ABC_BUF_NULL;
char *szFilename = NULL;
json_t *pJSON_Root = NULL;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_NULL(pAddress->pStateInfo);
ABC_CHECK_NULL(pAddress->szID);
ABC_CHECK_ASSERT(strlen(pAddress->szID) > 0, ABC_CC_Error, "No address ID provided");
// Get the master key we will need to encode the address data
// (note that this will also make sure the account and wallet exist)
ABC_CHECK_RET(ABC_WalletGetMK(self, &MK, pError));
// create the json for the transaction
pJSON_Root = json_object();
ABC_CHECK_ASSERT(pJSON_Root != NULL, ABC_CC_Error, "Could not create address JSON object");
// set the seq
json_object_set_new(pJSON_Root, JSON_ADDR_SEQ_FIELD, json_integer(pAddress->seq));
// set the address
json_object_set_new(pJSON_Root, JSON_ADDR_ADDRESS_FIELD, json_string(pAddress->szPubAddress));
// set the state info
ABC_CHECK_RET(ABC_TxEncodeAddressStateInfo(pJSON_Root, pAddress->pStateInfo, pError));
// set the details
ABC_CHECK_RET(ABC_TxEncodeTxDetails(pJSON_Root, pAddress->pDetails, pError));
// create the address directory if needed
ABC_CHECK_RET(ABC_TxCreateAddressDir(self.szUUID, pError));
// create the filename for this transaction
ABC_CHECK_RET(ABC_TxCreateAddressFilename(self, &szFilename, pAddress, pError));
// save out the transaction object to a file encrypted with the master key
ABC_CHECK_RET(ABC_CryptoEncryptJSONFileObject(pJSON_Root, MK, ABC_CryptoType_AES256, szFilename, pError));
exit:
ABC_FREE_STR(szFilename);
if (pJSON_Root) json_decref(pJSON_Root);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* Encodes the address state data into the given json transaction object
*
* @param pJSON_Obj Pointer to the json object into which the state info is stored.
* @param pInfo Pointer to the state info to store in the json object.
*/
static
tABC_CC ABC_TxEncodeAddressStateInfo(json_t *pJSON_Obj, tTxAddressStateInfo *pInfo, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
json_t *pJSON_State = NULL;
json_t *pJSON_ActivityArray = NULL;
json_t *pJSON_Activity = NULL;
int retVal = 0;
ABC_CHECK_NULL(pJSON_Obj);
ABC_CHECK_NULL(pInfo);
// create the state object
pJSON_State = json_object();
// add the creation date to the state object
retVal = json_object_set_new(pJSON_State, JSON_CREATION_DATE_FIELD, json_integer(pInfo->timeCreation));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the recycleable boolean
retVal = json_object_set_new(pJSON_State, JSON_ADDR_RECYCLEABLE_FIELD, json_boolean(pInfo->bRecycleable));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// create the array object
pJSON_ActivityArray = json_array();
// if there are any activities
if ((pInfo->countActivities > 0) && (pInfo->aActivities != NULL))
{
for (unsigned i = 0; i < pInfo->countActivities; i++)
{
// create the array object
pJSON_Activity = json_object();
// add the ntxid to the activity object
retVal = json_object_set_new(pJSON_Activity, JSON_TX_ID_FIELD, json_string(pInfo->aActivities[i].szTxID));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the date to the activity object
retVal = json_object_set_new(pJSON_Activity, JSON_ADDR_DATE_FIELD, json_integer(pInfo->aActivities[i].timeCreation));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the amount satoshi to the activity object
retVal = json_object_set_new(pJSON_Activity, JSON_AMOUNT_SATOSHI_FIELD, json_integer(pInfo->aActivities[i].amountSatoshi));
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add this activity to the activity array
json_array_append_new(pJSON_ActivityArray, pJSON_Activity);
// the appent_new stole the reference so we are done with it
pJSON_Activity = NULL;
}
}
// add the activity array to the state object
retVal = json_object_set(pJSON_State, JSON_ADDR_ACTIVITY_FIELD, pJSON_ActivityArray);
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
// add the state object to the master object
retVal = json_object_set(pJSON_Obj, JSON_ADDR_STATE_FIELD, pJSON_State);
ABC_CHECK_ASSERT(retVal == 0, ABC_CC_JSONError, "Could not encode JSON value");
exit:
if (pJSON_State) json_decref(pJSON_State);
if (pJSON_ActivityArray) json_decref(pJSON_ActivityArray);
if (pJSON_Activity) json_decref(pJSON_Activity);
return cc;
}
/**
* Gets the filename for a given address
* format is: N-Base58(HMAC256(pub_address,MK)).json
*
* @param pszFilename Output filename name. The caller must free this.
*/
static
tABC_CC ABC_TxCreateAddressFilename(tABC_WalletID self, char **pszFilename, const tABC_TxAddress *pAddress, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
char *szAddrDir = NULL;
tABC_U08Buf MK = ABC_BUF_NULL;
tABC_U08Buf DataHMAC = ABC_BUF_NULL;
char *szDataBase58 = NULL;
tABC_U08Buf PubAddress = ABC_BUF_NULL;
*pszFilename = NULL;
// Get the master key we will need to encode the filename
// (note that this will also make sure the account and wallet exist)
ABC_CHECK_RET(ABC_WalletGetMK(self, &MK, pError));
ABC_CHECK_RET(ABC_WalletGetAddressDirName(&szAddrDir, self.szUUID, pError));
// create an hmac-256 of the public address
ABC_BUF_SET_PTR(PubAddress, (unsigned char *)pAddress->szPubAddress, strlen(pAddress->szPubAddress));
ABC_CHECK_RET(ABC_CryptoHMAC256(PubAddress, MK, &DataHMAC, pError));
// create a base58 of the hmac-256 public address
ABC_CHECK_RET(ABC_CryptoBase58Encode(DataHMAC, &szDataBase58, pError));
// create the filename
ABC_STR_NEW(*pszFilename, ABC_FILEIO_MAX_PATH_LENGTH);
sprintf(*pszFilename, "%s/%u-%s.json", szAddrDir, pAddress->seq, szDataBase58);
exit:
ABC_FREE_STR(szAddrDir);
ABC_BUF_FREE(DataHMAC);
ABC_FREE_STR(szDataBase58);
return cc;
}
/**
* Creates the address directory if needed
*/
static
tABC_CC ABC_TxCreateAddressDir(const char *szWalletUUID, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
char *szAddrDir = NULL;
bool bExists = false;
// get the address directory
ABC_CHECK_RET(ABC_WalletGetAddressDirName(&szAddrDir, szWalletUUID, pError));
// if transaction dir doesn't exist, create it
ABC_CHECK_RET(ABC_FileIOFileExists(szAddrDir, &bExists, pError));
if (true != bExists)
{
ABC_CHECK_RET(ABC_FileIOCreateDir(szAddrDir, pError));
}
exit:
ABC_FREE_STR(szAddrDir);
return cc;
}
/**
* Free's a ABC_TxFreeAddress struct and all its elements
*/
static
void ABC_TxFreeAddress(tABC_TxAddress *pAddress)
{
if (pAddress)
{
ABC_FREE_STR(pAddress->szID);
ABC_FREE_STR(pAddress->szPubAddress);
ABC_TxFreeDetails(pAddress->pDetails);
ABC_TxFreeAddressStateInfo(pAddress->pStateInfo);
ABC_CLEAR_FREE(pAddress, sizeof(tABC_TxAddress));
}
}
/**
* Free's a tTxAddressStateInfo struct and all its elements
*/
static
void ABC_TxFreeAddressStateInfo(tTxAddressStateInfo *pInfo)
{
if (pInfo)
{
if ((pInfo->aActivities != NULL) && (pInfo->countActivities > 0))
{
for (unsigned i = 0; i < pInfo->countActivities; i++)
{
ABC_FREE_STR(pInfo->aActivities[i].szTxID);
}
ABC_CLEAR_FREE(pInfo->aActivities, sizeof(tTxAddressActivity) * pInfo->countActivities);
}
ABC_CLEAR_FREE(pInfo, sizeof(tTxAddressStateInfo));
}
}
/**
* Free's an array of ABC_TxFreeAddress structs
*/
void ABC_TxFreeAddresses(tABC_TxAddress **aAddresses, unsigned int count)
{
if ((aAddresses != NULL) && (count > 0))
{
for (unsigned i = 0; i < count; i++)
{
ABC_TxFreeAddress(aAddresses[i]);
}
ABC_CLEAR_FREE(aAddresses, sizeof(tABC_TxAddress *) * count);
}
}
void ABC_TxFreeOutput(tABC_TxOutput *pOutput)
{
if (pOutput)
{
ABC_FREE_STR(pOutput->szAddress);
ABC_FREE_STR(pOutput->szTxId);
ABC_CLEAR_FREE(pOutput, sizeof(tABC_TxOutput));
}
}
void ABC_TxFreeOutputs(tABC_TxOutput **aOutputs, unsigned int count)
{
if ((aOutputs != NULL) && (count > 0))
{
for (unsigned i = 0; i < count; i++)
{
ABC_TxFreeOutput(aOutputs[i]);
}
ABC_CLEAR_FREE(aOutputs, sizeof(tABC_TxOutput *) * count);
}
}
/**
* Gets the addresses associated with the given wallet.
*
* @param paAddresses Pointer to store array of addresses info pointers
* @param pCount Pointer to store number of addresses
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxGetAddresses(tABC_WalletID self,
tABC_TxAddress ***paAddresses,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
char *szAddrDir = NULL;
tABC_FileIOList *pFileList = NULL;
char *szFilename = NULL;
tABC_TxAddress **aAddresses = NULL;
unsigned int count = 0;
bool bExists = false;
ABC_CHECK_RET(ABC_TxMutexLock(pError));
ABC_CHECK_RET(ABC_FileIOMutexLock(pError)); // we want this as an atomic files system function
*paAddresses = NULL;
*pCount = 0;
// get the directory name
ABC_CHECK_RET(ABC_WalletGetAddressDirName(&szAddrDir, self.szUUID, pError));
// if there is a address directory
ABC_CHECK_RET(ABC_FileIOFileExists(szAddrDir, &bExists, pError));
if (bExists == true)
{
ABC_STR_NEW(szFilename, ABC_FILEIO_MAX_PATH_LENGTH + 1);
// get all the files in the address directory
ABC_FileIOCreateFileList(&pFileList, szAddrDir, NULL);
for (int i = 0; i < pFileList->nCount; i++)
{
// if this file is a normal file
if (pFileList->apFiles[i]->type == ABC_FileIOFileType_Regular)
{
// create the filename for this address
sprintf(szFilename, "%s/%s", szAddrDir, pFileList->apFiles[i]->szName);
// add this address to the array
ABC_CHECK_RET(ABC_TxLoadAddressAndAppendToArray(self, szFilename, &aAddresses, &count, pError));
}
}
}
// if we have more than one, then let's sort them
if (count > 1)
{
// sort the transactions by creation date using qsort
qsort(aAddresses, count, sizeof(tABC_TxAddress *), ABC_TxAddrPtrCompare);
}
// store final results
*paAddresses = aAddresses;
aAddresses = NULL;
*pCount = count;
count = 0;
exit:
ABC_FREE_STR(szAddrDir);
ABC_FREE_STR(szFilename);
ABC_FileIOFreeFileList(pFileList);
ABC_TxFreeAddresses(aAddresses, count);
ABC_FileIOMutexUnlock(NULL);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* This function is used to support sorting an array of tTxAddress pointers via qsort.
* qsort has the following documentation for the required function:
*
* Pointer to a function that compares two elements.
* This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:
*
* int compar (const void* p1, const void* p2);
*
* Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):
* return value meaning
* <0 The element pointed by p1 goes before the element pointed by p2
* 0 The element pointed by p1 is equivalent to the element pointed by p2
* >0 The element pointed by p1 goes after the element pointed by p2
*
*/
static
int ABC_TxAddrPtrCompare(const void * a, const void * b)
{
tABC_TxAddress **ppInfoA = (tABC_TxAddress **)a;
tABC_TxAddress *pInfoA = (tABC_TxAddress *)*ppInfoA;
tABC_TxAddress **ppInfoB = (tABC_TxAddress **)b;
tABC_TxAddress *pInfoB = (tABC_TxAddress *)*ppInfoB;
if (pInfoA->seq < pInfoB->seq) return -1;
if (pInfoA->seq == pInfoB->seq) return 0;
if (pInfoA->seq > pInfoB->seq) return 1;
return 0;
}
/**
* Loads the given address and adds it to the end of the array
*
* @param szFilename Filename of address
* @param paAddress Pointer to array into which the address will be added
* @param pCount Pointer to store number of address (will be updated)
* @param pError A pointer to the location to store the error if there is one
*/
static
tABC_CC ABC_TxLoadAddressAndAppendToArray(tABC_WalletID self,
const char *szFilename,
tABC_TxAddress ***paAddresses,
unsigned int *pCount,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
tABC_TxAddress *pAddress = NULL;
tABC_TxAddress **aAddresses = NULL;
unsigned int count = 0;
// hold on to current values
count = *pCount;
aAddresses = *paAddresses;
// load the address
ABC_CHECK_RET(ABC_TxLoadAddressFile(self, szFilename, &pAddress, pError));
// create space for new entry
if (aAddresses == NULL)
{
ABC_ARRAY_NEW(aAddresses, 1, tABC_TxAddress*);
count = 1;
}
else
{
count++;
ABC_ARRAY_RESIZE(aAddresses, count, tABC_TxAddress*);
}
// add it to the array
aAddresses[count - 1] = pAddress;
pAddress = NULL;
// assign the values to the caller
*paAddresses = aAddresses;
*pCount = count;
exit:
ABC_TxFreeAddress(pAddress);
return cc;
}
#if 0
/**
* For debug purposes, this prints all of the addresses in the given array
*/
static
void ABC_TxPrintAddresses(tABC_TxAddress **aAddresses, unsigned int count)
{
if ((aAddresses != NULL) && (count > 0))
{
for (int i = 0; i < count; i++)
{
ABC_DebugLog("Address - seq: %lld, id: %s, pubAddress: %s\n", aAddresses[i]->seq, aAddresses[i]->szID, aAddresses[i]->szPubAddress);
if (aAddresses[i]->pDetails)
{
ABC_DebugLog("\tDetails - satoshi: %lld, airbitz_fee: %lld, miners_fee: %lld, currency: %lf, name: %s, bizid: %u, category: %s, notes: %s, attributes: %u\n",
aAddresses[i]->pDetails->amountSatoshi,
aAddresses[i]->pDetails->amountFeesAirbitzSatoshi,
aAddresses[i]->pDetails->amountFeesMinersSatoshi,
aAddresses[i]->pDetails->amountCurrency,
aAddresses[i]->pDetails->szName,
aAddresses[i]->pDetails->bizId,
aAddresses[i]->pDetails->szCategory,
aAddresses[i]->pDetails->szNotes,
aAddresses[i]->pDetails->attributes);
}
else
{
ABC_DebugLog("\tNo Details");
}
if (aAddresses[i]->pStateInfo)
{
ABC_DebugLog("\tState Info - timeCreation: %lld, recycleable: %s\n",
aAddresses[i]->pStateInfo->timeCreation,
aAddresses[i]->pStateInfo->bRecycleable ? "yes" : "no");
if (aAddresses[i]->pStateInfo->aActivities && aAddresses[i]->pStateInfo->countActivities)
{
for (int nActivity = 0; nActivity < aAddresses[i]->pStateInfo->countActivities; nActivity++)
{
ABC_DebugLog("\t\tActivity - txID: %s, timeCreation: %lld, satoshi: %lld\n",
aAddresses[i]->pStateInfo->aActivities[nActivity].szTxID,
aAddresses[i]->pStateInfo->aActivities[nActivity].timeCreation,
aAddresses[i]->pStateInfo->aActivities[nActivity].amountSatoshi);
}
}
else
{
ABC_DebugLog("\t\tNo Activities");
}
}
else
{
ABC_DebugLog("\tNo State Info");
}
}
typedef struct sTxAddressActivity
{
char *szTxID; // ntxid from bitcoin associated with this activity
int64_t timeCreation;
int64_t amountSatoshi;
} tTxAddressActivity;
typedef struct sTxAddressStateInfo
{
int64_t timeCreation;
bool bRecycleable;
unsigned int countActivities;
tTxAddressActivity *aActivities;
} tTxAddressStateInfo;
typedef struct sABC_TxAddress
{
int64_t seq; // sequence number
char *szID; // sequence number in string form
char *szPubAddress; // public address
tABC_TxDetails *pDetails;
tTxAddressStateInfo *pStateInfo;
} tABC_TxAddress;
}
else
{
ABC_DebugLog("No addresses");
}
}
#endif
/**
* Locks the mutex
*
* ABC_Tx uses the same mutex as ABC_Login/ABC_Wallet so that there will be no situation in
* which one thread is in ABC_Tx locked on a mutex and calling a thread safe ABC_Login/ABC_Wallet call
* that is locked from another thread calling a thread safe ABC_Tx call.
* In other words, since they call each other, they need to share a recursive mutex.
*/
static
tABC_CC ABC_TxMutexLock(tABC_Error *pError)
{
return ABC_MutexLock(pError);
}
/**
* Unlocks the mutex
*/
static
tABC_CC ABC_TxMutexUnlock(tABC_Error *pError)
{
return ABC_MutexUnlock(pError);
}
/**
* Adds a transaction to an address's activity log.
*
* @param pAddress the address to modify
* @param pTx the transaction to add to the address
*/
static
tABC_CC ABC_TxAddressAddTx(tABC_TxAddress *pAddress, tABC_Tx *pTx, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
unsigned int countActivities;
tTxAddressActivity *aActivities = NULL;
// grow the array:
countActivities = pAddress->pStateInfo->countActivities;
aActivities = pAddress->pStateInfo->aActivities;
ABC_ARRAY_RESIZE(aActivities, countActivities + 1, tTxAddressActivity);
// fill in the new entry:
ABC_STRDUP(aActivities[countActivities].szTxID, pTx->szID);
aActivities[countActivities].timeCreation = pTx->pStateInfo->timeCreation;
aActivities[countActivities].amountSatoshi = pTx->pDetails->amountSatoshi;
// save the array:
pAddress->pStateInfo->countActivities = countActivities + 1;
pAddress->pStateInfo->aActivities = aActivities;
aActivities = NULL;
exit:
ABC_FREE(aActivities);
return cc;
}
tABC_CC ABC_TxTransactionExists(tABC_WalletID self,
const char *szID,
tABC_Tx **pTx,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
char *szFilename = NULL;
bool bExists = false;
ABC_SET_ERR_CODE(pError, ABC_CC_Ok);
ABC_CHECK_RET(ABC_TxMutexLock(pError));
// first try the internal
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, true, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
// if the internal doesn't exist
if (bExists == false)
{
// try the external
ABC_FREE_STR(szFilename);
ABC_CHECK_RET(ABC_TxCreateTxFilename(self, &szFilename, szID, false, pError));
ABC_CHECK_RET(ABC_FileIOFileExists(szFilename, &bExists, pError));
}
if (bExists)
{
ABC_CHECK_RET(ABC_TxLoadTransaction(self, szFilename, pTx, pError));
} else {
*pTx = NULL;
}
exit:
ABC_FREE_STR(szFilename);
ABC_TxMutexUnlock(NULL);
return cc;
}
/**
* This implemens the KMP failure function. Its the preprocessing before we can
* search for substrings.
*
* @param needle - The string to preprocess
* @param table - An array of integers the string length of needle
*
* Returns 1 if a match is found otherwise returns 0
*
*/
static
void ABC_TxStrTable(const char *needle, int *table)
{
size_t pos = 2, cnd = 0;
table[0] = -1;
table[1] = 0;
size_t needle_size = strlen(needle);
while (pos < needle_size)
{
if (tolower(needle[pos - 1]) == tolower(needle[cnd]))
{
cnd = cnd + 1;
table[pos] = cnd;
pos = pos + 1;
}
else if (cnd > 0)
cnd = table[cnd];
else
{
table[pos] = 0;
pos = pos + 1;
}
}
}
/**
* This function implemens the KMP string searching algo. This function is
* used for string matching when searching transactions.
*
* @param haystack - The string to search
* @param needle - The string to find in the haystack
*
* Returns 1 if a match is found otherwise returns 0
*
*/
static
int ABC_TxStrStr(const char *haystack, const char *needle,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
if (haystack == NULL || needle == NULL) {
return 0;
}
int result = -1;
size_t haystack_size;
size_t needle_size;
size_t m = 0, i = 0;
int *table;
haystack_size = strlen(haystack);
needle_size = strlen(needle);
if (haystack_size == 0 || needle_size == 0) {
return 0;
}
ABC_ARRAY_NEW(table, needle_size, int);
ABC_TxStrTable(needle, table);
while (m + i < haystack_size)
{
if (tolower(needle[i]) == tolower(haystack[m + i]))
{
if (i == needle_size - 1)
{
result = m;
break;
}
i = i + 1;
}
else
{
if (table[i] > -1)
{
i = table[i];
m = m + i - table[i];
}
else
{
i = 0;
m = m + 1;
}
}
}
exit:
ABC_FREE(table);
return result > -1 ? 1 : 0;
}
static int
ABC_TxCopyOuputs(tABC_Tx *pTx, tABC_TxOutput **aOutputs, int countOutputs, tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
int i;
ABC_CHECK_NULL(pTx);
ABC_CHECK_NULL(aOutputs);
pTx->countOutputs = countOutputs;
if (pTx->countOutputs > 0)
{
ABC_ARRAY_NEW(pTx->aOutputs, pTx->countOutputs, tABC_TxOutput*);
for (i = 0; i < countOutputs; ++i)
{
ABC_DebugLog("Saving Outputs: %s\n", aOutputs[i]->szAddress);
ABC_NEW(pTx->aOutputs[i], tABC_TxOutput);
ABC_STRDUP(pTx->aOutputs[i]->szAddress, aOutputs[i]->szAddress);
ABC_STRDUP(pTx->aOutputs[i]->szTxId, aOutputs[i]->szTxId);
pTx->aOutputs[i]->input = aOutputs[i]->input;
pTx->aOutputs[i]->value = aOutputs[i]->value;
}
}
exit:
return cc;
}
static
tABC_CC ABC_TxTransferPopulate(tABC_TxSendInfo *pInfo,
tABC_Tx *pTx, tABC_Tx *pReceiveTx,
tABC_Error *pError)
{
tABC_CC cc = ABC_CC_Ok;
// Populate Send Tx
if (pInfo->szSrcName)
{
ABC_FREE_STR(pTx->pDetails->szName);
ABC_STRDUP(pTx->pDetails->szName, pInfo->szSrcName);
}
if (pInfo->szSrcCategory)
{
ABC_FREE_STR(pTx->pDetails->szCategory);
ABC_STRDUP(pTx->pDetails->szCategory, pInfo->szSrcCategory);
}
// Populate Recv Tx
if (pInfo->szDestName)
{
ABC_FREE_STR(pReceiveTx->pDetails->szName);
ABC_STRDUP(pReceiveTx->pDetails->szName, pInfo->szDestName);
}
if (pInfo->szDestCategory)
{
ABC_FREE_STR(pReceiveTx->pDetails->szCategory);
ABC_STRDUP(pReceiveTx->pDetails->szCategory, pInfo->szDestCategory);
}
exit:
return cc;
}
| 34.55779 | 198 | 0.645393 | [
"object"
] |
d1ec0ae25c53da65415160e3dabb603c391dc01f | 248,630 | cxx | C++ | AutoSeg/Gui/AutoSeg/AutoSegGUIControls.cxx | NIRALUser/AutoSeg | 3a0c7b898da93633e177b78c86b1371561608484 | [
"Apache-2.0"
] | 4 | 2016-01-12T14:41:41.000Z | 2018-11-23T17:01:37.000Z | AutoSeg/Gui/AutoSeg/AutoSegGUIControls.cxx | NIRALUser/AutoSeg | 3a0c7b898da93633e177b78c86b1371561608484 | [
"Apache-2.0"
] | 4 | 2015-03-18T19:38:13.000Z | 2019-03-28T15:52:07.000Z | AutoSeg/Gui/AutoSeg/AutoSegGUIControls.cxx | NIRALUser/AutoSeg | 3a0c7b898da93633e177b78c86b1371561608484 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
Program: AutoSeg
Module: $RCSfile: AutoSegGUIControls.cxx,v $
Language: C++
Date: $Date: 2011/04/19 08:04:40 $
Version: $Revision: 1.25 $
Author: Clement Vachet
Copyright (c) 2004 NeuroImaging Lab @ UNC. All rights reserved.
See NeuroLibCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "AutoSegGUIControls.h"
#include <itksys/SystemTools.hxx>
//char *AtlasDirectory = NULL;
//char *TargetDirectory = NULL;
float CalculateIntensityEnergy(const char *fixedDirectory, const char *movingDirectory, const std::string filename )
{
typedef unsigned short PixelType;
// does this really need to be char, switched to short by MST Mar 14,2014
typedef itk::Image< PixelType, 3 > ImageType;
typedef itk::MeanSquaresImageToImageMetric< ImageType, ImageType > MSMMetricType;
typedef itk::NormalizedCorrelationImageToImageMetric< ImageType, ImageType > NCCMetricType;
typedef itk::MutualInformationImageToImageMetric< ImageType, ImageType > MIMetricType;
typedef itk::NormalizedMutualInformationHistogramImageToImageMetric< ImageType, ImageType > NMIMetricType;
typedef itk::RescaleIntensityImageFilter< ImageType, ImageType > RescaleFilterType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer fixedReader = ReaderType::New();
ReaderType::Pointer movingReader = ReaderType::New();
MSMMetricType::Pointer MSMmetric = MSMMetricType::New();
NCCMetricType::Pointer NCCmetric = NCCMetricType::New();
MIMetricType::Pointer MImetric = MIMetricType::New();
NMIMetricType::Pointer NMImetric = NMIMetricType::New();
RescaleFilterType::Pointer rescaleFixFilter = RescaleFilterType::New();
RescaleFilterType::Pointer rescaleMoveFilter = RescaleFilterType::New();
typedef itk::TranslationTransform< double, 3 > TransformType;
TransformType::Pointer translatetransform = TransformType::New( );
typedef itk::AffineTransform<double,3> AffineTransformType;
typedef AffineTransformType::ParametersType affineParametersType;
AffineTransformType::Pointer transform = AffineTransformType::New();
typedef itk::NearestNeighborInterpolateImageFunction< ImageType, double > NNInterpolatorType;
typedef itk::LinearInterpolateImageFunction< ImageType > LinearInterpolatorType;
NNInterpolatorType::Pointer interpolator = NNInterpolatorType::New();
transform->SetIdentity();
fixedReader->SetFileName( fixedDirectory );
movingReader->SetFileName( movingDirectory );
rescaleFixFilter->SetInput( fixedReader->GetOutput() );
rescaleFixFilter->SetOutputMinimum( 0 );
rescaleFixFilter->SetOutputMaximum( 1023 );
rescaleFixFilter->Update();
rescaleMoveFilter->SetInput( movingReader->GetOutput() );
rescaleMoveFilter->SetOutputMinimum( 0 );
rescaleMoveFilter->SetOutputMaximum( 1023 );
rescaleMoveFilter->Update();
ImageType::ConstPointer fixedImage = rescaleFixFilter->GetOutput();
ImageType::ConstPointer movingImage = rescaleMoveFilter->GetOutput();
// mean square metric
MSMmetric->SetTransform( transform );
MSMmetric->SetInterpolator( interpolator );
MSMmetric->SetFixedImage( fixedImage );
MSMmetric->SetMovingImage( movingImage );
// normalized cross correlation
NCCmetric->SetTransform( transform );
NCCmetric->SetInterpolator( interpolator );
NCCmetric->SetFixedImage( fixedImage );
NCCmetric->SetMovingImage( movingImage );
// mutual information
MImetric->SetTransform( transform );
MImetric->SetInterpolator( interpolator );
MImetric->SetFixedImage( fixedImage );
MImetric->SetMovingImage( movingImage );
// normalized mutual information
NMImetric->SetTransform( transform );
NMImetric->SetInterpolator( interpolator );
NMImetric->SetFixedImage( fixedImage );
NMImetric->SetMovingImage( movingImage );
// Software Guide : EndCodeSnippet
MSMmetric->SetFixedImageRegion( fixedImage->GetLargestPossibleRegion( ) );
//NCCmetric->SetFixedImageRegion( fixedImage->GetLargestPossibleRegion( ) );
//MImetric->SetFixedImageRegion( fixedImage->GetLargestPossibleRegion( ) );
//NMImetric->SetFixedImageRegion( fixedImage->GetLargestPossibleRegion( ) );
try {
MSMmetric->Initialize();
//NCCmetric->Initialize();
//MImetric->Initialize();
//NMImetric->Initialize();
}
catch( itk::ExceptionObject & excep ){
std::cerr << "Exception catched !" << std::endl;
std::cerr << excep << std::endl;
return -1;
}
float msm = MSMmetric->GetValue( transform->GetParameters( ) );
// float ncc = NCCmetric->GetValue( transform->GetParameters( ) );
// float mi = MImetric->GetValue( transform->GetParameters( ) );
// float nmi = NMImetric->GetValue( transform->GetParameters( ) );
// std::string filename;
std::ostringstream strFixCase;
// strFixCase << argv[5];
// strFixCase << fixedCase;
// filename = "intensityEnergyMICCAI_target.txt";
std::ofstream efile( filename.c_str() , std::ios::app );
efile << msm << "\n";
efile.close();
std::cout << "mean square metric value: " << msm << std::endl;
//std::cout << "normalized cross correlation value: " << ncc << std::endl;
//std::cout << "mutual information value: " << mi << std::endl;
//std::cout << "normalized mutual information value: " << nmi << std::endl;
return msm;
}
float CalculateHarmonicEnergy(const char *deformedFieldDirectory, const std::string filename)
{
typedef itk::Image< float, 3 > ImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
typedef itk::ImageFileWriter<ImageType> WriterType;
ReaderType::Pointer orientedreader = ReaderType::New();
ImageType::Pointer deformationField;
ImageType::IndexType index;
ImageType::SizeType size;
float HE = 0;
orientedreader->SetFileName( deformedFieldDirectory );
try {
orientedreader->Update();
deformationField = orientedreader->GetOutput();
size = deformationField->GetLargestPossibleRegion().GetSize();
}
catch( itk::ExceptionObject & err ) {
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
for(index[2] = 0; index[2] < (int)size[2]; index[2]++) {
for(index[1] = 0; index[1] < (int)size[1]; index[1]++) {
for(index[0] = 0; index[0] < (int)size[0]; index[0]++) {
// calculate harmonic energy
float tmpHE = 0;
tmpHE += pow(deformationField->GetPixel(index), 2);
HE += sqrt(tmpHE);
}
}
}
std::cout << "harmonic energy: " << HE << std::endl;
std::ofstream hefile( filename.c_str() , std::ios::app );
hefile << HE << "\n";
hefile.close();
return HE;
}
AutoSegGUIControls::AutoSegGUIControls(std::string _AutoSegPath,
const char*AutoSegVersion ,
const char* computationFile ,
const char* parameterFile ,
std::string logOutFileName ,
std::string logErrFileName
)
: AutoSegGUI()
{
m_AutoSegVersion = std::string("Autoseg ") + AutoSegVersion ;
this->g_MainWindow->label( m_AutoSegVersion.c_str() ) ;
bool IsDefaultParameterFile;
char DefaultParameterFile[512];
g_MainWindow->show();
m_BrowserWidths = NULL;
m_AuxBrowserWidths = NULL;
// Set AutoSeg Environment
// size +1 for final string character '\0' and +1 if we need space in CheckDirectoryName() to add an extra '/',
// therefore size +2
char *autoSegPath = new char[ _AutoSegPath.size()+2 ] ;
std::strcpy(autoSegPath,_AutoSegPath.c_str()) ;
CheckDirectoryName(autoSegPath);
m_Computation.SetAutoSegPath(autoSegPath);
delete []autoSegPath ;
// Initialization Computation Parameters
m_Computation.SetStdOutLogFile(logOutFileName);
m_logOutFileName = logOutFileName ;
m_Computation.SetStdErrLogFile(logErrFileName);
m_logErrFileName = logErrFileName ;
m_Computation.SetT2Image(g_T2Button->value());
m_Computation.SetPDImage(g_PDButton->value());
m_Computation.SetAuxT1Image(g_AuxT1Button->value());
m_Computation.SetAuxT2Image(g_AuxT2Button->value());
m_Computation.SetAuxPDImage(g_AuxPDButton->value());
m_Computation.SetAux1Image(g_Aux1Button->value());
m_Computation.SetAux2Image(g_Aux2Button->value());
m_Computation.SetAux3Image(g_Aux3Button->value());
m_Computation.SetAux4Image(g_Aux4Button->value());
m_Computation.SetAux5Image(g_Aux5Button->value());
m_Computation.SetAux6Image(g_Aux6Button->value());
m_Computation.SetAux7Image(g_Aux7Button->value());
m_Computation.SetAux8Image(g_Aux8Button->value());
g_DataAutoSegDirectoryDisp->value("AutoSeg");
m_Computation.SetDataAutoSegDirectory("AutoSeg");
m_Computation.SetComputeVolume(g_ComputeVolumeButton->value());
m_Computation.SetComputeCorticalThickness(g_ComputeCorticalThicknessButton->value());
m_Computation.SetRecompute(g_RecomputeButton->value());
m_Computation.SetUseCondor(g_UseCondorButton->value());
m_Computation.SetMultiModalityMultiSegmentation(g_MultiModalityMultiSegButton->value());
m_Computation.SetMultiModalitySingleSegmentation(g_MultiModalitySingleSegButton->value());
m_Computation.SetMultiAtlasSegmentation(g_MultiAtlasSegButton->value());
m_Computation.SetSingleAtlasSegmentation(g_SingleAtlasSegButton->value());
m_Computation.SetRandomizeSubjects(g_RandomizeSubjectsButton->value());
m_Computation.SetIsAutoSegInProcess(false);
m_Computation.SetSlicerVersion(4.3);
// Initialization Default Parameter Files
std::strcpy(DefaultParameterFile, m_Computation.GetAutoSegPath());
std::strcat(DefaultParameterFile, "AutoSeg_DefaultParameters_Adult.txt");
SetDefaultParameterFile(DefaultParameterFile);
if( parameterFile != NULL )
{
try
{
m_Computation.LoadParameterFile(parameterFile);
}
catch(...)
{
//do nothing
}
UpdateParameterGUI(parameterFile, file , true );
}
else
{
try
{
m_Computation.LoadParameterFile(GetDefaultParameterFile() , file, false);
}
catch(...)
{
//do nothing
}
IsDefaultParameterFile = UpdateParameterGUI(GetDefaultParameterFile(), file , false );
if (!IsDefaultParameterFile)
{
InitializeParameters();
}
}
if( computationFile != NULL )
{
m_Computation.LoadComputationFile(computationFile);
UpdateComputationGUI(computationFile);
}
if( !m_Computation.GetOldFluidRegistrationAvailable() )
{
g_ClassicWarpingButton->deactivate() ;
g_CoarseToFineWarpingButton->deactivate() ;
g_FluidWarpingGroup->deactivate() ;
}
if( !m_Computation.GetReorientationAvailable() )
{
g_ReorientationGroup->deactivate() ;
}
ABCButtonToggled();//This is necessary to initialize the tissue segmentation parameters in m_Computation
SetANTSRegistrationFilterTypeGUI();//This is necessary to initialize the "step" for ANTS registration (default registration)
}
AutoSegGUIControls::~AutoSegGUIControls()
{
if (m_BrowserWidths)
delete[] m_BrowserWidths;
if (m_AuxBrowserWidths)
delete[] m_AuxBrowserWidths;
}
void AutoSegGUIControls::AboutButtonPressed()
{
AboutGUIControls About;
About.AboutGUI_Label->label(m_AutoSegVersion.c_str());
About.g_MainWindow->show();
Fl::run();
}
void AutoSegGUIControls::ExitAutoSeg()
{
if (m_Computation.GetIsAutoSegInProcess())
{
if (!fl_choice("Choose one of the following:","Exit without stopping the current process", "Exit and stop the process", "Cancel"))
g_MainWindow->hide();
else
{
m_Computation.StopBatchMake();
g_MainWindow->hide();
}
}
else
{
if (fl_choice("Do you really want to exit AutoSeg?", "No", "Yes", NULL))
g_MainWindow->hide();
}
}
void AutoSegGUIControls::LoadParameterFileGUI()
{
const char *initialDirectory = m_CurrentDirectory;
Fl_File_Chooser fc(initialDirectory,"*.txt",Fl_File_Chooser::SINGLE,"Load a Parameter File");
fc.show();
while(fc.shown()){
Fl::wait();
}
//if a name has been set
if(fc.count())
{
try
{
m_Computation.LoadParameterFile(fc.value());
}
catch(const std::exception& ex)
{
fl_alert( "%s" , ex.what() ) ;
}
UpdateParameterGUI(fc.value());
}
m_CurrentDirectory = strdup(fc.directory());
}
void MajorityVotingLabelFusion(std::string segmentationfilename, std::string datadirectory )
{
}
void AutoSegGUIControls::WeightedMajorityVotingLabelFusionGUI(std::string segmentationfilename, std::string intfilename, std::string harmonicfilename, std::string selectedtemplatefilename, std::string datadirectory )
{
/*
//run weighted majority voting
std::ostringstream strFixCase;
// strFixCase << (int)g_FixedCase->value();
// std::string filename;
//filename = g_IntensityEnergyDirectoryDisp->value();
std::ifstream efile( intfilename.c_str() );
// filename = g_HarmonicEnergyDirectoryDisp->value();
std::ifstream iefile( harmonicfilename.c_str() );
//filename = g_SelectedTemplateDirectoryDisp->value();
std::ifstream templatefile( selectedtemplatefilename.c_str());
std::string commandLine;
float harmonicE, intensityE, shapeE, weightFactor[NUMBER_OF_CASE * (NUMBER_OF_CASE - 1)], circularity[NUMBER_OF_CASE];
int cases[NUMBER_OF_CASE] = {1000, 1001, 1002, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1017, 1036, 1003};
float alpha = 0.5, beta = 0.5, gama = 0;
bool caseFlag[NUMBER_OF_CASE] = {0};
for (int i = 0; i < NUMBER_OF_CASE; i++){
int temp;
templatefile >> temp;
caseFlag[temp] = 1;
}
templatefile.close();
for (int i = 0; i < NUMBER_OF_CASE; i++){
if (i != (NUMBER_OF_CASE - 1) && caseFlag[i] == 0)
cases[i] = 0;
}
int m = 0;
float minDistance = 1000000, maxDistance = 0;
for ( int i = 0; i < (NUMBER_OF_ATLAS * (NUMBER_OF_ATLAS - 1) + NUMBER_OF_ATLAS); i++){
efile >> harmonicE;
iefile >> intensityE;
if( i >= (NUMBER_OF_ATLAS * (NUMBER_OF_ATLAS - 1)) ){
weightFactor[m] = alpha * harmonicE + beta * intensityE; //+ gama * fabs(circularity[i] - circularity[j]);
if(weightFactor[m] < minDistance)
minDistance = weightFactor[m];
if(weightFactor[m] > maxDistance)
maxDistance = weightFactor[m];
// std::cout << harmonicE << " " << intensityE << " " << 1 - weightFactor[m] << std::endl;
m++;
}
}
for (int i = 0; i < NUMBER_OF_ATLAS; i++){
weightFactor[i] = (weightFactor[i] - minDistance) / (maxDistance - minDistance);
}
efile.close();
iefile.close();
//for conventional majority voting
std::ostringstream strTarget;
strTarget << (int)g_FixedCase->value();
if((int)g_FixedCase->value() == cases[0]) {
std::ostringstream strSourceTmp;
strSourceTmp << cases[1];
commandLine = "~/work/NeuroLib/ImageMath_build/ImageMath ~/work/MICCAI_2012_MultiAtlas_Challenge/registration/Testing/deformedImage_" + strSourceTmp.str() + "to" + strTarget.str() + "_seg.nii.gz -weightedMajorityVoting ";
}
else {
std::ostringstream strSourceTmp;
strSourceTmp << cases[0];
commandLine = "~/work/NeuroLib/ImageMath_build/ImageMath ~/work/MICCAI_2012_MultiAtlas_Challenge/registration/Testing/deformedImage_1000to" + strTarget.str() + "_seg.nii.gz -weightedMajorityVoting ";
}
int z = 0;
for (int i = 0; i < NUMBER_OF_CASE; i++){
if (cases[i] != (int)g_FixedCase->value() && cases[i] != 0) {
// std::cout << cases[i] << ", " << atoi(argv[2]) * (NUMBER_OF_CASE - 1) + z << ": " << weightFactor[atoi(argv[2]) * (NUMBER_OF_CASE - 1) + z] << std::endl;
z++;
}
}
int k = 0;
//for (int i = 0; i < NUMBER_OF_CASE; i++){
for (int i = 0; i < NUMBER_OF_ATLAS; i++){
std::ostringstream strSource;
strSource << cases[i];
if (i < 30) {
if (cases[i] != (int)g_FixedCase->value() && cases[i] != 0) {
commandLine += "~/work/MICCAI_2012_MultiAtlas_Challenge/registration/Testing/deformedImage_" + strSource.str() + "to" + strTarget.str() + "_seg.nii.gz ";
}
}
else {
if (cases[i] != (int)g_FixedCase->value() && cases[i] != 0) {
commandLine += "~/work/MICCAI_2012_MultiAtlas_Challenge/registration/Testing/deformedImage_" + strSource.str() + "fto" + strTarget.str() + "_seg.nii.gz ";
}
}
if (cases[i] != (int)g_FixedCase->value())
k++;
}
commandLine += "-weights ";
bool firstWeightFlag = 0;
k = 0;
// for (int i = 0; i < NUMBER_OF_CASE; i++){
for (int i = 0; i < NUMBER_OF_ATLAS; i++){
std::ostringstream strWFactor;
if(cases[i] != (int)g_FixedCase->value() && cases[i] != 0) {
//if (firstWeightFlag == 1 && weightFactor[atoi(argv[2]) * (NUMBER_OF_CASE - 1) + k - 1] <= WEIGHT_THRESHOLD && k > 0){
if (firstWeightFlag == 1 && k > 0){
commandLine += ",";
}
strWFactor << 1 - weightFactor[k];
// if(weightFactor[atoi(argv[2]) * (NUMBER_OF_CASE - 1) + k] <= WEIGHT_THRESHOLD) {
commandLine += strWFactor.str();
firstWeightFlag = 1;
// std::cout << atoi(argv[2]) * (NUMBER_OF_CASE - 1) + k << ": " << strWFactor.str() << std::endl;
// }
}
if (cases[i] != (int)g_FixedCase->value())
k++;
}
std::ostringstream strSource;
strSource << (int)g_FixedCase->value();
commandLine += " -outfile WeightedMVOutput_seg_" + strSource.str() + ".nii";
std::cout << commandLine.c_str() << std::endl;
system(commandLine.c_str());
*/
}
void AutoSegGUIControls::STAPLELabelFusionGUI()
{
/*
int DATASET_SIZE = 25;
std::string filename;
int usedCase[25] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1, 1, 1};
int cases[NUMBER_OF_CASE] = {1000, 1001, 1002, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1017, 1036, 1003};
int segLabel =(int)g_Label->value(), fixCase = (int)g_FixedCase->value(), numIteration = 1, numCaseUsed = DATASET_SIZE, numCaseWillUse = DATASET_SIZE;
bool terminateCriteria = 1;
char *quotationMark = "\"";
//filename = g_SelectedTemplateDirectoryDisp->value();
std::ifstream templatefile( filename.c_str() );
bool caseFlag[NUMBER_OF_CASE] = {0};
for (int i = 0; i < NUMBER_OF_CASE; i++){
int temp;
templatefile >> temp;
caseFlag[temp] = 1;
}
templatefile.close();
for (int i = 0; i < NUMBER_OF_CASE; i++){
if (i != (NUMBER_OF_CASE - 1) && caseFlag[i] == 0)
cases[i] = 0;
}
std::string commandLine;
std::string strTarget;
std::ifstream readParameter;
std::ostringstream strFixCase;
strFixCase << fixCase;
std::ostringstream numIter;
numCaseUsed = numCaseWillUse;
numCaseWillUse = 0;
numIter << numIteration;
//exclude target image
for (int i = 0; i < DATASET_SIZE; i++){
if (cases[i] == fixCase)
usedCase[i] = 0;
}
commandLine = "crlSTAPLE ";
for (int i = 0; i < NUMBER_OF_CASE; i++){
std::ostringstream strTarget;
std::ostringstream strSource;
strSource << cases[i];
strTarget << (int)g_FixedCase->value();
if (cases[i] != (int)g_FixedCase->value() && cases[i] != 0) {
commandLine += "~/work/MICCAI_2012_MultiAtlas_Challenge/registration/Testing/deformedImage_" + strSource.str() + "to" + strTarget.str() + "_seg.nii.gz ";
}
}
commandLine = commandLine + "--compressOutput --outputImage seg_0" + strFixCase.str() + "_fromAllScans_syn_100x50x25_AllMuscle.nrrd";
std::cout << commandLine << std::endl;
getchar();
system(commandLine.c_str());//run STAPLE
std::cout << "STAPLE finished!" << std::endl;
*/
}
void AutoSegGUIControls::LoadComputationFileGUI()
{
Fl_File_Chooser fc(".","*.txt",Fl_File_Chooser::SINGLE,"Load a Computation File");
fc.show();
while(fc.shown())
Fl::wait();
//if a name has been set
if(fc.count())
{
g_DataBrowser->clear();
m_Computation.LoadComputationFile(fc.value());
UpdateComputationGUI(fc.value());
}
m_CurrentDirectory = strdup(fc.directory());
}
void AutoSegGUIControls::SaveParameterFileGUI()
{
char *NewFile = NULL;
NewFile = fl_file_chooser("Save Parameter File as ?","*.txt",".");
if (NewFile != NULL)
{
UpdateParameters();
m_Computation.WriteParameterFile(NewFile);
}
}
void AutoSegGUIControls::SaveComputationFileGUI()
{
char *NewFile = NULL;
NewFile = fl_file_chooser("Save Computation File as ?","*.txt",".");
if (NewFile != NULL)
{
m_Computation.SetDataAutoSegDirectory(g_DataAutoSegDirectoryDisp->value());
m_Computation.DesallocateDataList();
m_Computation.DesallocateAuxDataList();
InitializeData();
InitializeAuxData();
m_Computation.WriteComputationFile(NewFile);
}
}
void AutoSegGUIControls::UseDefaultParametersGUI()
{
try
{
m_Computation.LoadParameterFile(GetDefaultParameterFile());
}
catch(...)
{
//do nothing
}
UpdateParameterGUI(GetDefaultParameterFile());
}
void AutoSegGUIControls::SetDefaultParametersGUI()
{
if (fl_choice("Do you really want to set the current parameters as default parameters?","No", "Yes", NULL))
{
UpdateParameters();
m_Computation.WriteParameterFile(GetDefaultParameterFile());
}
}
void AutoSegGUIControls::ResetDefaultParametersGUI()
{
InitializeParameters();
m_Computation.WriteParameterFile(GetDefaultParameterFile());
}
void AutoSegGUIControls::SetDefaultParameterFile(const char *_DefaultParameterFile)
{
std::strcpy(m_DefaultParameterFile, _DefaultParameterFile);
}
char * AutoSegGUIControls::GetDefaultParameterFile()
{
return m_DefaultParameterFile;
}
// Update GUI
// THIS IS A DUPLICATION OF THE LOADING OF THE PARAMETER FILE, this needs to be adapted to be called from the main application
void AutoSegGUIControls::UpdateComputationGUI(const char *_FileName , bool showError )
{
FILE* ComputationFile;
char Line[1536];
char Data[1536];
int Length;
// Computation Options
int IsT2Image, IsPDImage;
int ComputeVolume, ComputeCorticalThickness, Recompute, UseCondor, ComputeMultiAtlas;
int boolValue;
if ((ComputationFile = fopen(_FileName,"r")) != NULL)
{
while ( (fgets(Line,1536,ComputationFile)) != NULL)
{
Length = std::strlen(Line);
Line[Length-1] = '\0';
if ( (std::strncmp("Process Data Directory: ", Line, 24)) == 0)
{
if (std::strlen(Line+24) != 0)
{
g_ProcessDataDirectoryDisp->value(Line+24);
g_ProcessDataDirectoryDisp->position(g_ProcessDataDirectoryDisp->size());
}
else
{
g_ProcessDataDirectoryDisp->value("");
}
}
else if ( (std::strncmp("Is T2 Image: ", Line, 13)) == 0)
{
IsT2Image = atoi(Line+13);
if (IsT2Image == 0)
{
g_T2Button->clear();
g_T2Disp->deactivate();
g_T2Disp->value(NULL);
}
else
{
g_T2Button->set();
g_T2Disp->activate();
}
}
else if ( (std::strncmp("Is PD Image: ", Line, 13)) == 0)
{
IsPDImage = atoi(Line+13);
if (IsPDImage == 0)
{
g_PDButton->clear();
g_PDDisp->deactivate();
g_PDDisp->value(NULL);
}
else
{
g_PDButton->set();
g_PDDisp->activate();
}
InitBrowser();
}
else if( (std::strncmp("Data AutoSeg Directory: ", Line, 24)) == 0)
{
if (std::strlen(Line+24))
{
g_DataAutoSegDirectoryDisp->value(Line+24);
}
else
{
g_DataAutoSegDirectoryDisp->value(NULL);
}
}
else if ( (std::strncmp("Data Directory: ", Line, 16)) == 0)
{
if (std::strlen(Line+16) != 0)
{
g_DataDirectoryDisp->value(Line+16);
g_DataDirectoryDisp->position(g_DataDirectoryDisp->size());
}
else
{
g_DataDirectoryDisp->value(NULL);
}
}
else if ( (std::strncmp("T1 Files: ", Line, 10)) == 0)
{
if (std::strlen(Line+10) != 0)
{
g_T1Disp->value(Line+10);
g_T1Disp->position(g_T1Disp->size());
}
else
{
g_T1Disp->value(NULL);
}
}
else if ( (std::strncmp("T2 Files: ", Line, 10)) == 0)
{
if (std::strlen(Line+10) != 0)
{
g_T2Disp->value(Line+10);
g_T2Disp->position(g_T2Disp->size());
}
else
{
g_T2Disp->value(NULL);
}
}
else if ( (std::strncmp("PD Files: ", Line, 10)) == 0)
{
if (std::strlen(Line+10) != 0)
{
g_PDDisp->value(Line+10);
g_PDDisp->position(g_PDDisp->size());
}
else
{
g_PDDisp->value(NULL);
}
}
else if ( (std::strncmp("Compute Volume: ", Line, 16)) == 0)
{
ComputeVolume = atoi(Line+16);
if (ComputeVolume == 1)
g_ComputeVolumeButton->set();
else
g_ComputeVolumeButton->clear();
}
else if ( (std::strncmp("Compute cortical thickness: ", Line, 28)) == 0)
{
ComputeCorticalThickness = atoi(Line+28);
if (ComputeCorticalThickness == 1)
g_ComputeCorticalThicknessButton->set();
else
g_ComputeCorticalThicknessButton->clear();
}
else if ( (std::strncmp("Recompute: ", Line, strlen("Recompute: "))) == 0)
{
Recompute = atoi(Line+strlen("Recompute: "));
if (Recompute == 1)
g_RecomputeButton->set();
else
g_RecomputeButton->clear();
}
else if ( (std::strncmp("Use Condor: ", Line, strlen("Use Condor: "))) == 0)
{
UseCondor = atoi(Line+strlen("Use Condor: "));
if (UseCondor == 1)
g_UseCondorButton->set();
else
g_UseCondorButton->clear();
}
else if ( (std::strncmp("Data: ", Line, strlen("Data: "))) == 0)
{
RightJustifyData(Line+strlen("Data: "), Data);
g_DataBrowser->add(Data);
}
else if ( (std::strncmp("Compute Multi-modality Single-atlas Segmentation: ", Line, strlen("Compute Multi-modality Single-atlas Segmentation: "))) == 0)
{
boolValue = atoi(Line + strlen("Compute Multi-modality Single-atlas Segmentation: "));
if (boolValue == 1) {
g_MultiModalitySingleSegButton->set();
}
else
g_MultiModalitySingleSegButton->clear();
}
else if ( (std::strncmp("Compute Multi-modality Multi-atlas Segmentation: ", Line, strlen("Compute Multi-modality Multi-atlas Segmentation: "))) == 0)
{
boolValue = atoi(Line + strlen("Compute Multi-modality Multi-atlas Segmentation: "));
if (boolValue == 1) {
g_MultiModalityMultiSegButton->set();
}
else
g_MultiModalityMultiSegButton->clear();
}
else if ( (std::strncmp("Compute Multi-atlas Segmentation: ", Line, strlen("Compute Multi-atlas Segmentation: "))) == 0)
{
ComputeMultiAtlas = atoi(Line + strlen("Compute Multi-atlas Segmentation: "));
if (ComputeMultiAtlas == 1) {
g_MultiAtlasSegButton->set();
MultiAtlasSegmentationButtonChecked();
}
else
g_MultiAtlasSegButton->clear();
}
else if ( (std::strncmp("Compute Single-atlas Segmentation: ", Line, strlen("Compute Single-atlas Segmentation: "))) == 0)
{
boolValue = atoi(Line + strlen("Compute Single-atlas Segmentation: "));
if (boolValue == 1) {
g_SingleAtlasSegButton->set();
SingleAtlasSegmentationButtonChecked();
}
else
g_SingleAtlasSegButton->clear();
}
else if ( (std::strncmp("Randomize Subject Order: ", Line, 25)) == 0)
{
boolValue = atoi(Line + 25);
if (boolValue == 1) {
g_RandomizeSubjectsButton->set();
RandomizeSubjectsButtonChecked();
}
else
g_RandomizeSubjectsButton->clear();
}
else if ( (std::strncmp("Conduct Atlas-Atlas Registration: ", Line, 34)) == 0)
{
if (atoi(Line + 34) == 1) {
g_AtlasAtlasRegButton->set();
}
else
g_AtlasAtlasRegButton->clear();
}
else if ( (std::strncmp("Recalculate Atlas-Target Energy: ", Line, 33)) == 0)
{
if (atoi(Line + 33) == 1) {
g_RecalculateAtlasTargetEnergyButton->set();
}
else
g_RecalculateAtlasTargetEnergyButton->clear();
}
else if ( (std::strncmp("Recalculate Atlas-Atlas Energy: ", Line, 32)) == 0)
{
if (atoi(Line + 32) == 1) {
g_RecalculateAtlasAtlasEnergyButton->set();
}
else
g_RecalculateAtlasAtlasEnergyButton->clear();
}
}
fclose(ComputationFile);
}
else
{
if( showError )
{
fl_alert( "Error Opening File: %s" , _FileName) ;
std::cerr << "Error Opening File: " << _FileName << std::endl ;
}
}
}
void AutoSegGUIControls::UpdateAuxComputationGUI(const char *_FileName)
{
FILE* AuxComputationFile;
char Line[1536];
char Data[1536];
int Length;
// Computation Options
int IsAux1Image, IsAux2Image, IsAux3Image, IsAux4Image, IsAux5Image, IsAux6Image, IsAux7Image, IsAux8Image;
int IsAuxT1Image, IsAuxT2Image, IsAuxPDImage;
int RigidTransformation, AffineTransformation, BsplineTransformation, AtlasSpaceImage, BiasCorrectedImage, SkullStrippedImage;
IsAux1Image = IsAux2Image = IsAux3Image = IsAux4Image = IsAux5Image = IsAux6Image = IsAux7Image = IsAux8Image = 0;
if ((AuxComputationFile = fopen(_FileName,"r")) != NULL)
{
while ( (fgets(Line,1536,AuxComputationFile)) != NULL)
{
Length = std::strlen(Line);
Line[Length-1] = '\0';
if ( (std::strncmp("Is AuxT1 Image: ", Line, 16)) == 0)
{
IsAuxT1Image = atoi(Line+16);
if (IsAuxT1Image == 1)
{
g_AuxT1Button->setonly();
}
}
else if ( (std::strncmp("Is AuxT2 Image: ", Line, 16)) == 0)
{
IsAuxT2Image = atoi(Line+16);
if (IsAuxT2Image == 1)
{
g_AuxT2Button->setonly();
}
}
else
{
IsAuxPDImage = atoi(Line+16);
if (IsAuxPDImage == 1)
{
g_AuxPDButton->setonly();
}
}
if ( (std::strncmp("Is Aux1 Image: ", Line, 15)) == 0)
{
IsAux1Image = atoi(Line+15);
if (IsAux1Image == 0)
{
g_Aux1Button->clear();
g_Aux1LabelDisp->deactivate();
g_Aux1LabelDisp->value(NULL);
g_Aux1Disp->deactivate();
g_Aux1Disp->value(NULL);
g_Aux1Title->deactivate();
g_Aux2Button->clear();
g_Aux2Button->deactivate();
g_Aux2LabelDisp->deactivate();
g_Aux2LabelDisp->value(NULL);
g_Aux2Disp->deactivate();
g_Aux2Disp->value(NULL);
g_Aux2Title->deactivate();
g_Aux3Button->clear();
g_Aux3Button->deactivate();
g_Aux3LabelDisp->deactivate();
g_Aux3LabelDisp->value(NULL);
g_Aux3Disp->deactivate();
g_Aux3Disp->value(NULL);
g_Aux3Title->deactivate();
g_Aux4Button->clear();
g_Aux4Button->deactivate();
g_Aux4LabelDisp->deactivate();
g_Aux4LabelDisp->value(NULL);
g_Aux4Disp->deactivate();
g_Aux4Disp->value(NULL);
g_Aux4Title->deactivate();
g_Aux5Button->clear();
g_Aux5Button->deactivate();
g_Aux5LabelDisp->deactivate();
g_Aux5LabelDisp->value(NULL);
g_Aux5Disp->deactivate();
g_Aux5Disp->value(NULL);
g_Aux5Title->deactivate();
g_Aux6Button->clear();
g_Aux6Button->deactivate();
g_Aux6LabelDisp->deactivate();
g_Aux6LabelDisp->value(NULL);
g_Aux6Disp->deactivate();
g_Aux6Disp->value(NULL);
g_Aux6Title->deactivate();
g_Aux7Button->clear();
g_Aux7Button->deactivate();
g_Aux7LabelDisp->deactivate();
g_Aux7LabelDisp->value(NULL);
g_Aux7Disp->deactivate();
g_Aux7Disp->value(NULL);
g_Aux7Title->deactivate();
g_Aux8Button->clear();
g_Aux8Button->deactivate();
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8Title->deactivate();
}
else
{
g_Aux1Button->set();
g_Aux1Title->activate();
g_Aux1Disp->activate();
g_Aux1LabelDisp->activate();
g_Aux2Button->activate();
}
}
else if ( (std::strncmp("Is Aux2 Image: ", Line, 15)) == 0)
{
IsAux2Image = atoi(Line+15);
if ((IsAux2Image == 0) || ((IsAux2Image == 1) && (IsAux1Image == 0)))
{
g_Aux2Button->clear();
g_Aux2Disp->deactivate();
g_Aux2Disp->value(NULL);
g_Aux2LabelDisp->deactivate();
g_Aux2LabelDisp->value(NULL);
g_Aux2Title->deactivate();
g_Aux3Button->clear();
g_Aux3Button->deactivate();
g_Aux3LabelDisp->deactivate();
g_Aux3LabelDisp->value(NULL);
g_Aux3Disp->deactivate();
g_Aux3Disp->value(NULL);
g_Aux3Title->deactivate();
g_Aux4Button->clear();
g_Aux4Button->deactivate();
g_Aux4LabelDisp->deactivate();
g_Aux4LabelDisp->value(NULL);
g_Aux4Disp->deactivate();
g_Aux4Disp->value(NULL);
g_Aux4Title->deactivate();
g_Aux5Button->clear();
g_Aux5Button->deactivate();
g_Aux5LabelDisp->deactivate();
g_Aux5LabelDisp->value(NULL);
g_Aux5Disp->deactivate();
g_Aux5Disp->value(NULL);
g_Aux5Title->deactivate();
g_Aux6Button->clear();
g_Aux6Button->deactivate();
g_Aux6LabelDisp->deactivate();
g_Aux6LabelDisp->value(NULL);
g_Aux6Disp->deactivate();
g_Aux6Disp->value(NULL);
g_Aux6Title->deactivate();
g_Aux7Button->clear();
g_Aux7Button->deactivate();
g_Aux7LabelDisp->deactivate();
g_Aux7LabelDisp->value(NULL);
g_Aux7Disp->deactivate();
g_Aux7Disp->value(NULL);
g_Aux7Title->deactivate();
g_Aux8Button->clear();
g_Aux8Button->deactivate();
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8Title->deactivate();
}
else
{
g_Aux2Button->set();
g_Aux2Title->activate();
g_Aux2Disp->activate();
g_Aux2LabelDisp->activate();
g_Aux3Button->activate();
}
}
else if ( (std::strncmp("Is Aux3 Image: ", Line, 15)) == 0)
{
IsAux3Image = atoi(Line+15);
if ((IsAux3Image == 0) || ((IsAux3Image == 1) && ((IsAux2Image == 0) || (IsAux1Image == 0))))
{
g_Aux3Button->clear();
g_Aux3Title->deactivate();
g_Aux3Disp->deactivate();
g_Aux3Disp->value(NULL);
g_Aux3LabelDisp->deactivate();
g_Aux3LabelDisp->value(NULL);
g_Aux4Button->clear();
g_Aux4Button->deactivate();
g_Aux4LabelDisp->deactivate();
g_Aux4LabelDisp->value(NULL);
g_Aux4Disp->deactivate();
g_Aux4Disp->value(NULL);
g_Aux4Title->deactivate();
g_Aux5Button->clear();
g_Aux5Button->deactivate();
g_Aux5LabelDisp->deactivate();
g_Aux5LabelDisp->value(NULL);
g_Aux5Disp->deactivate();
g_Aux5Disp->value(NULL);
g_Aux5Title->deactivate();
g_Aux6Button->clear();
g_Aux6Button->deactivate();
g_Aux6LabelDisp->deactivate();
g_Aux6LabelDisp->value(NULL);
g_Aux6Disp->deactivate();
g_Aux6Disp->value(NULL);
g_Aux6Title->deactivate();
g_Aux7Button->clear();
g_Aux7Button->deactivate();
g_Aux7LabelDisp->deactivate();
g_Aux7LabelDisp->value(NULL);
g_Aux7Disp->deactivate();
g_Aux7Disp->value(NULL);
g_Aux7Title->deactivate();
g_Aux8Button->clear();
g_Aux8Button->deactivate();
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8Title->deactivate();
}
else
{
g_Aux3Button->set();
g_Aux3Title->activate();
g_Aux3Disp->activate();
g_Aux3LabelDisp->activate();
g_Aux4Button->activate();
}
}
else if ( (std::strncmp("Is Aux4 Image: ", Line, 15)) == 0)
{
IsAux4Image = atoi(Line+15);
if ((IsAux4Image == 0) || ((IsAux4Image == 1) && ((IsAux3Image == 0) || (IsAux2Image == 0) || (IsAux1Image == 0))))
{
g_Aux4Button->clear();
g_Aux4Title->deactivate();
g_Aux4Disp->deactivate();
g_Aux4Disp->value(NULL);
g_Aux4LabelDisp->deactivate();
g_Aux4LabelDisp->value(NULL);
g_Aux5Button->clear();
g_Aux5Button->deactivate();
g_Aux5Disp->deactivate();
g_Aux5Disp->value(NULL);
g_Aux5Title->deactivate();
g_Aux5LabelDisp->deactivate();
g_Aux5LabelDisp->value(NULL);
g_Aux6Button->clear();
g_Aux6Button->deactivate();
g_Aux6Disp->deactivate();
g_Aux6Disp->value(NULL);
g_Aux6Title->deactivate();
g_Aux6LabelDisp->deactivate();
g_Aux6LabelDisp->value(NULL);
g_Aux7Button->clear();
g_Aux7Button->deactivate();
g_Aux7Disp->deactivate();
g_Aux7Disp->value(NULL);
g_Aux7Title->deactivate();
g_Aux7LabelDisp->deactivate();
g_Aux7LabelDisp->value(NULL);
g_Aux8Button->clear();
g_Aux8Button->deactivate();
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8Title->deactivate();
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
}
else
{
g_Aux4Button->set();
g_Aux4Title->activate();
g_Aux4Disp->activate();
g_Aux4LabelDisp->activate();
g_Aux5Button->activate();
}
}
else if ( (std::strncmp("Is Aux5 Image: ", Line, 15)) == 0)
{
IsAux5Image = atoi(Line+15);
if ((IsAux5Image == 0) || ((IsAux5Image == 1) && ((IsAux4Image == 0) || (IsAux3Image == 0) || (IsAux2Image == 0) || (IsAux1Image == 0))))
{
g_Aux5Button->clear();
g_Aux5Title->deactivate();
g_Aux5Disp->deactivate();
g_Aux5Disp->value(NULL);
g_Aux5LabelDisp->deactivate();
g_Aux5LabelDisp->value(NULL);
g_Aux6Button->clear();
g_Aux6Button->deactivate();
g_Aux6Disp->deactivate();
g_Aux6Disp->value(NULL);
g_Aux6Title->deactivate();
g_Aux6LabelDisp->deactivate();
g_Aux6LabelDisp->value(NULL);
g_Aux7Button->clear();
g_Aux7Button->deactivate();
g_Aux7Disp->deactivate();
g_Aux7Disp->value(NULL);
g_Aux7Title->deactivate();
g_Aux7LabelDisp->deactivate();
g_Aux7LabelDisp->value(NULL);
g_Aux8Button->clear();
g_Aux8Button->deactivate();
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8Title->deactivate();
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
}
else
{
g_Aux5Button->set();
g_Aux5Title->activate();
g_Aux5Disp->activate();
g_Aux5LabelDisp->activate();
g_Aux6Button->activate();
}
}
else if ( (std::strncmp("Is Aux6 Image: ", Line, 15)) == 0)
{
IsAux6Image = atoi(Line+15);
if ((IsAux6Image == 0) || ((IsAux6Image == 1) && ((IsAux5Image == 0) || (IsAux4Image == 0) || (IsAux3Image == 0) || (IsAux2Image == 0) || (IsAux1Image == 0))))
{
g_Aux6Button->clear();
g_Aux6Title->deactivate();
g_Aux6Disp->deactivate();
g_Aux6Disp->value(NULL);
g_Aux6LabelDisp->deactivate();
g_Aux6LabelDisp->value(NULL);
g_Aux7Button->clear();
g_Aux7Button->deactivate();
g_Aux7Disp->deactivate();
g_Aux7Disp->value(NULL);
g_Aux7Title->deactivate();
g_Aux7LabelDisp->deactivate();
g_Aux7LabelDisp->value(NULL);
g_Aux8Button->clear();
g_Aux8Button->deactivate();
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8Title->deactivate();
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
}
else
{
g_Aux6Button->set();
g_Aux6Title->activate();
g_Aux6Disp->activate();
g_Aux6LabelDisp->activate();
g_Aux7Button->activate();
}
}
else if ( (std::strncmp("Is Aux7 Image: ", Line, 15)) == 0)
{
IsAux7Image = atoi(Line+15);
if ((IsAux7Image == 0) || ((IsAux7Image == 1) && ((IsAux6Image == 0) || (IsAux5Image == 0) || (IsAux4Image == 0) || (IsAux3Image == 0) || (IsAux2Image == 0) || (IsAux1Image == 0))))
{
g_Aux7Button->clear();
g_Aux7Title->deactivate();
g_Aux7Disp->deactivate();
g_Aux7Disp->value(NULL);
g_Aux7LabelDisp->deactivate();
g_Aux7LabelDisp->value(NULL);
g_Aux8Button->clear();
g_Aux8Button->deactivate();
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8Title->deactivate();
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
}
else
{
g_Aux7Button->set();
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
g_Aux8Button->activate();
}
}
else if ( (std::strncmp("Is Aux8 Image: ", Line, 15)) == 0)
{
IsAux8Image = atoi(Line+15);
if ((IsAux8Image == 0) || ((IsAux8Image == 1) && ((IsAux7Image == 0) || (IsAux6Image == 0) || (IsAux5Image == 0) || (IsAux4Image == 0) || (IsAux3Image == 0) || (IsAux2Image == 0) || (IsAux1Image == 0))))
{
g_Aux8Button->clear();
g_Aux8Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8Disp->value(NULL);
g_Aux8LabelDisp->deactivate();
g_Aux8LabelDisp->value(NULL);
}
else
{
g_Aux8Button->set();
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
}
InitAuxBrowser();
}
else if ( (std::strncmp("Data Directory: ", Line, 16)) == 0)
{
if (std::strlen(Line+16) != 0)
{
g_DataDirectoryDisp->value(Line+16);
g_DataDirectoryDisp->position(g_DataDirectoryDisp->size());
}
else
{
g_DataDirectoryDisp->value(NULL);
}
}
// else if ( (std::strncmp("AuxT1 Files: ", Line, 13)) == 0)
// {
// if (std::strlen(Line+13) != 0)
// {
// m_Computation.SetT1(Line+13);
// }
// else
// {
// m_Computation.SetT1("");
// }
// }
// else if ( (std::strncmp("AuxT2 Files: ", Line, 13)) == 0)
// {
// if (std::strlen(Line+13) != 0)
// {
// m_Computation.SetT2(Line+13);
// }
// else
// {
// m_Computation.SetT2("");
// }
// }
// else if ( (std::strncmp("AuxPD Files: ", Line, 13)) == 0)
// {
// if (std::strlen(Line+13) != 0)
// {
// m_Computation.SetPD(Line+13);
// }
// else
// {
// m_Computation.SetPD("");
// }
// }
else if ( (std::strncmp("Aux1 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux1Disp->value(Line+12);
g_Aux1Disp->position(g_Aux1Disp->size());
}
else
{
g_Aux1Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux2 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux2Disp->value(Line+12);
g_Aux2Disp->position(g_Aux2Disp->size());
}
else
{
g_Aux2Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux3 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux3Disp->value(Line+12);
g_Aux3Disp->position(g_Aux3Disp->size());
}
else
{
g_Aux3Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux4 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux4Disp->value(Line+12);
g_Aux4Disp->position(g_Aux4Disp->size());
}
else
{
g_Aux4Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux5 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux5Disp->value(Line+12);
g_Aux5Disp->position(g_Aux5Disp->size());
}
else
{
g_Aux5Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux6 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux6Disp->value(Line+12);
g_Aux6Disp->position(g_Aux6Disp->size());
}
else
{
g_Aux6Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux7 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux7Disp->value(Line+12);
g_Aux7Disp->position(g_Aux7Disp->size());
}
else
{
g_Aux7Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux8 Files: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_Aux8Disp->value(Line+12);
g_Aux8Disp->position(g_Aux8Disp->size());
}
else
{
g_Aux8Disp->value(NULL);
}
}
else if ( (std::strncmp("Aux1 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux1LabelDisp->value(Line+11);
}
else
{
g_Aux1LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Aux2 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux2LabelDisp->value(Line+11);
}
else
{
g_Aux2LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Aux3 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux3LabelDisp->value(Line+11);
}
else
{
g_Aux3LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Aux4 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux4LabelDisp->value(Line+11);
}
else
{
g_Aux4LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Aux5 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux5LabelDisp->value(Line+11);
}
else
{
g_Aux5LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Aux6 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux6LabelDisp->value(Line+11);
}
else
{
g_Aux6LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Aux7 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux7LabelDisp->value(Line+11);
}
else
{
g_Aux7LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Aux8 Label: ", Line, 11)) == 0)
{
if (std::strlen(Line+11) != 0)
{
g_Aux8LabelDisp->value(Line+11);
}
else
{
g_Aux8LabelDisp->value(NULL);
}
}
else if ( (std::strncmp("Atlas Space Image: ", Line, 19)) == 0)
{
AtlasSpaceImage = atoi(Line+19);
if (AtlasSpaceImage == 1)
{
g_AtlasSpaceButton->set();
g_StrippedButton->clear();
g_BiasCorrectedButton->clear();
BiasCorrectedImage = 0;
SkullStrippedImage = 0;
}
else
g_AtlasSpaceButton->clear();
}
else if ( (std::strncmp("Bias Corrected Image: ", Line, 22)) == 0)
{
BiasCorrectedImage = atoi(Line+22);
if (BiasCorrectedImage == 1)
{
g_BiasCorrectedButton->set();
g_AtlasSpaceButton->clear();
g_StrippedButton->clear();
AtlasSpaceImage = 0;
SkullStrippedImage = 0;
}
else
g_BiasCorrectedButton->clear();
}
else if ( (std::strncmp("Skull Stripped Image: ", Line, 22)) == 0)
{
SkullStrippedImage = atoi(Line+22);
if (SkullStrippedImage == 1)
{
g_StrippedButton->set();
g_BiasCorrectedButton->clear();
g_AtlasSpaceButton->clear();
AtlasSpaceImage = 0;
BiasCorrectedImage = 0;
}
else
g_StrippedButton->clear();
}
else if ( (std::strncmp("Rigid Transformation: ", Line, 22)) == 0)
{
RigidTransformation = atoi(Line+22);
if (RigidTransformation == 1)
{
g_RigidTransformationButton->set();
g_AffineTransformationButton->clear();
g_BsplineTransformationButton->clear();
AffineTransformation = 0;
BsplineTransformation = 0;
}
else
g_RigidTransformationButton->clear();
}
else if ( (std::strncmp("Affine Transformation: ", Line, 23)) == 0)
{
AffineTransformation = atoi(Line+23);
if (AffineTransformation == 1)
{
g_AffineTransformationButton->set();
g_RigidTransformationButton->clear();
g_BsplineTransformationButton->clear();
BsplineTransformation = 0;
RigidTransformation = 0;
}
else
g_AffineTransformationButton->clear();
}
else if ( (std::strncmp("Bspline Transformation: ", Line, 24)) == 0)
{
BsplineTransformation = atoi(Line+24);
if (BsplineTransformation == 1)
{
g_BsplineTransformationButton->set();
g_AffineTransformationButton->clear();
g_RigidTransformationButton->clear();
AffineTransformation = 0;
RigidTransformation = 0;
}
else
g_BsplineTransformationButton->clear();
}
else if ( (std::strncmp("AuxData: ", Line, 9)) == 0)
{
RightJustifyAuxData(Line+9, Data);
g_AuxDataBrowser->add(Data);
}
}
fclose(AuxComputationFile);
}
else
{
fl_alert( "Error Opening File: %s" , _FileName ) ;
std::cerr<<"Error Opening File: "<<_FileName<<std::endl;
}
}
// Update GUI
// Mode = file: Read the total file
// Mode = advancedParameters: Read only the advanced parameters (tissue segmentation, warping parameters and N4 ITK Bias Field Correction parameters)
// Mode = tissueSeg: Read only the tissue segmentation parameters
// Mode = warping: Read only the warping parameters
// Mode = N4biasFieldCorrection: Read only the N4 ITK Bias Field Correction parameters
bool AutoSegGUIControls::UpdateParameterGUI(const char *_FileName, enum Mode mode , bool showError )
{
FILE* ParameterFile;
char Line[512];
int Length;
// Tissue Segmentation
int FilterIterations, MaxBiasDegree, Loop;
float FilterTimeStep, Prior1, Prior2, Prior3, Prior4, Prior5, Prior6, Prior7, Prior8, Prior9, FluidAtlasWarpMaxStep;
int BSplineAtlasWarp;
float BSplineAtlasWarpGridX, BSplineAtlasWarpGridY, BSplineAtlasWarpGridZ;
int FluidAtlasWarp, FluidAtlasFATW, FluidAtlasAffine, FluidAtlasWarpIterations, LoopIteration;
float NeosegPriorThreshold, NeosegParzenKernel, NeosegMahalanobisThreshold;
// Rigid Registration
int RigidRegistration, IsROIAtlasGridTemplate;
int GridTemplateSizeX, GridTemplateSizeY, GridTemplateSizeZ;
float GridTemplateSpacingX, GridTemplateSpacingY, GridTemplateSpacingZ;
int InitRegUseT1InitTransform;
// Atlas Warping
float Alpha, Beta, Gamma, MaxPerturbation, NumBasis,DeformationFieldSmoothingSigma;
int Scale4NbIterations, Scale2NbIterations, Scale1NbIterations,PyramidLevels;
std::string RegistrationFilterType,MovingShrinkFactors,FixedShrinkFactors,IterationCountPyramidLevels;
// - ANTS
std::string ANTSIterations, ANTSRegistrationFilterType, ANTSTransformationStep;
float ANTSCCWeight, ANTSCCRegionRadius, ANTSMIWeight, ANTSMIBins, ANTSMSQWeight, ANTSGaussianSigma;
bool ANTSGaussianSmoothing;
// Skull Stripping
int DeleteVessels;
// Regional histogram
float PointSpacing;
// N4 ITK Bias Field Correction
std::string NbOfIterations,BSplineGridResolutions,HistogramSharpening;
int N4ITKBiasFieldCorrection,StrippedN4ITKBiasFieldCorrection, ShrinkFactor,BSplineOrder;
float ConvergenceThreshold,BSplineBeta,BSplineAlpha,SplineDistance, SlicerVersion;
// Reorientation
int Reorientation;
std::string InputDataOrientation, OutputDataOrientation;
int value;
bool IsParameterFileLoaded=false;
if (mode ==file)
{
// INIT / default setting for backward comaptibility
// Init for EMS loop
g_LoopButton->clear();
g_LoopIteration->deactivate();
g_AtlasLoopGroup->deactivate();
// Init for N4
g_N4ITKBiasFieldCorrectionButton->clear();
g_N4ParametersGroup->deactivate();
g_N4AdvancedParametersGroup->deactivate();
g_StrippedN4ITKBiasFieldCorrectionButton->clear();
g_StrippedN4ITKBiasFieldCorrectionButton->deactivate();
// Init for Reorientation
g_ReorientationButton->clear();
g_InputDataOrientationDisp->deactivate();
g_OutputDataOrientationDisp->deactivate();
// Init for Atlas Warping
g_ANTSWarpingButton->clear();
}
std::string FileNameStr = itksys::SystemTools::CollapseFullPath( _FileName ).c_str() ;
if ((ParameterFile = fopen(FileNameStr.c_str(),"r")) != NULL)
{
IsParameterFileLoaded = true;
while ( (fgets(Line,512,ParameterFile)) != NULL)
{
Length = std::strlen(Line);
Line[Length-1] = '\0';
if (mode == file)
{
if ( (std::strncmp("Common Coordinate Image: ", Line, 25)) == 0)
{
if (std::strlen(Line+25) != 0)
{
g_CommonCoordinateImageDisp->value(Line+25);
g_CommonCoordinateImageDisp->position(g_CommonCoordinateImageDisp->size());
}
else
{
g_CommonCoordinateImageDisp->value(NULL);
}
}
else if ( (std::strncmp("Common Coordinate Image Type: ", Line, 30)) == 0)
{
m_Computation.SetCommonCoordinateImageType(Line+30);
if (std::strcmp(Line+30, "T1") == 0)
{
g_CommonCoordinateImageT1Button->set();
g_CommonCoordinateImageT2Button->clear();
}
else
{
g_CommonCoordinateImageT1Button->clear();
g_CommonCoordinateImageT2Button->set();
}
}
else if ( (std::strncmp("Tissue Segmentation Atlas Directory: ", Line, 37)) == 0)
{
if (std::strlen(Line+37) != 0)
{
g_TissueSegmentationAtlasDirectoryDisp->value(Line+37);
g_TissueSegmentationAtlasDirectoryDisp->position(g_TissueSegmentationAtlasDirectoryDisp->size());
}
else
{
g_TissueSegmentationAtlasDirectoryDisp->value(NULL);
}
}
else if ( (std::strncmp("Tissue Segmentation Atlas Type: ", Line, 32)) == 0)
{
if (std::strcmp(Line+32, "T1") == 0)
{
g_TissueSegmentationAtlasT1Button->set();
g_TissueSegmentationAtlasT2Button->clear();
}
else
{
g_TissueSegmentationAtlasT1Button->clear();
g_TissueSegmentationAtlasT2Button->set();
}
}
else if ( (std::strncmp("ROI Atlas File: ", Line, 16)) == 0)
{
if (std::strlen(Line+16) != 0)
{
g_ROIAtlasFileDisp->value(Line+16);
g_ROIAtlasFileDisp->position(g_ROIAtlasFileDisp->size());
}
else
{
g_ROIAtlasFileDisp->value(NULL);
}
}
else if ( (std::strncmp("ROI Second Atlas File: ", Line, 23)) == 0)
{
if (std::strlen(Line+23) != 0)
{
g_ROIT2AtlasFileDisp->value(Line+23);
g_ROIT2AtlasFileDisp->position(g_ROIAtlasFileDisp->size());
}
else
{
g_ROIT2AtlasFileDisp->value(NULL);
}
}
else if ( (std::strncmp("Amygdala Left: ", Line, 15)) == 0)
{
if (std::strlen(Line+15) != 0)
{
g_AmygdalaLeftButton->set();
g_AmygdalaLeftDisp->activate();
g_AmygdalaLeftDisp->value(Line+15);
g_AmygdalaLeftDisp->position(g_AmygdalaLeftDisp->size());
}
else
{
g_AmygdalaLeftButton->clear();
g_AmygdalaLeftDisp->deactivate();
g_AmygdalaLeftDisp->value(NULL);
}
}
else if ( (std::strncmp("Amygdala Right: ", Line, 16)) == 0)
{
if (std::strlen(Line+16) != 0)
{
g_AmygdalaRightButton->set();
g_AmygdalaRightDisp->activate();
g_AmygdalaRightDisp->value(Line+16);
g_AmygdalaRightDisp->position(g_AmygdalaRightDisp->size());
}
else
{
g_AmygdalaRightButton->clear();
g_AmygdalaRightDisp->deactivate();
g_AmygdalaRightDisp->value(NULL);
}
}
else if ( (std::strncmp("Caudate Left: ", Line, 14)) == 0)
{
if (std::strlen(Line+14) != 0)
{
g_CaudateLeftButton->set();
g_CaudateLeftDisp->activate();
g_CaudateLeftDisp->value(Line+14);
g_CaudateLeftDisp->position(g_CaudateLeftDisp->size());
}
else
{
g_CaudateLeftButton->clear();
g_CaudateLeftDisp->deactivate();
g_CaudateLeftDisp->value(NULL);
}
}
else if ( (std::strncmp("Caudate Right: ", Line, 15)) == 0)
{
if (std::strlen(Line+15) != 0)
{
g_CaudateRightButton->set();
g_CaudateRightDisp->activate();
g_CaudateRightDisp->value(Line+15);
g_CaudateRightDisp->position(g_CaudateRightDisp->size());
}
else
{
g_CaudateRightButton->clear();
g_CaudateRightDisp->deactivate();
g_CaudateRightDisp->value(NULL);
}
}
else if ( (std::strncmp("Hippocampus Left: ", Line, 18)) == 0)
{
if (std::strlen(Line+18) != 0)
{
g_HippocampusLeftButton->set();
g_HippocampusLeftDisp->activate();
g_HippocampusLeftDisp->value(Line+18);
g_HippocampusLeftDisp->position(g_HippocampusLeftDisp->size());
}
else
{
g_HippocampusLeftButton->clear();
g_HippocampusLeftDisp->deactivate();
g_HippocampusLeftDisp->value(NULL);
}
}
else if ( (std::strncmp("Hippocampus Right: ", Line, 19)) == 0)
{
if (std::strlen(Line+19) != 0)
{
g_HippocampusRightButton->set();
g_HippocampusRightDisp->activate();
g_HippocampusRightDisp->value(Line+19);
g_HippocampusRightDisp->position(g_HippocampusRightDisp->size());
}
else
{
g_HippocampusRightButton->clear();
g_HippocampusRightDisp->deactivate();
g_HippocampusRightDisp->value(NULL);
}
}
else if ( (std::strncmp("Pallidus Left: ", Line, 15)) == 0)
{
if (std::strlen(Line+15) != 0)
{
g_PallidusLeftButton->set();
g_PallidusLeftDisp->activate();
g_PallidusLeftDisp->value(Line+15);
g_PallidusLeftDisp->position(g_PallidusLeftDisp->size());
}
else
{
g_PallidusLeftButton->clear();
g_PallidusLeftDisp->deactivate();
g_PallidusLeftDisp->value(NULL);
}
}
else if ( (std::strncmp("Pallidus Right: ", Line, 16)) == 0)
{
if (std::strlen(Line+16) != 0)
{
g_PallidusRightButton->set();
g_PallidusRightDisp->activate();
g_PallidusRightDisp->value(Line+16);
g_PallidusRightDisp->position(g_PallidusRightDisp->size());
}
else
{
g_PallidusRightButton->clear();
g_PallidusRightDisp->deactivate();
g_PallidusRightDisp->value(NULL);
}
}
else if ( (std::strncmp("Putamen Left: ", Line, 14)) == 0)
{
if (std::strlen(Line+14) != 0)
{
g_PutamenLeftButton->set();
g_PutamenLeftDisp->activate();
g_PutamenLeftDisp->value(Line+14);
g_PutamenLeftDisp->position(g_PutamenLeftDisp->size());
}
else
{
g_PutamenLeftButton->clear();
g_PutamenLeftDisp->deactivate();
g_PutamenLeftDisp->value(NULL);
}
}
else if ( (std::strncmp("Putamen Right: ", Line, 15)) == 0)
{
if (std::strlen(Line+15) != 0)
{
g_PutamenRightButton->set();
g_PutamenRightDisp->activate();
g_PutamenRightDisp->value(Line+15);
g_PutamenRightDisp->position(g_PutamenRightDisp->size());
}
else
{
g_PutamenRightButton->clear();
g_PutamenRightDisp->deactivate();
g_PutamenRightDisp->value(NULL);
}
}
else if ( (std::strncmp("Lateral Ventricle Left: ", Line, 24)) == 0)
{
if (std::strlen(Line+24) != 0)
{
g_LateralVentricleLeftButton->set();
g_LateralVentricleLeftDisp->activate();
g_LateralVentricleLeftDisp->value(Line+24);
g_LateralVentricleLeftDisp->position(g_LateralVentricleLeftDisp->size());
}
else
{
g_LateralVentricleLeftButton->clear();
g_LateralVentricleLeftDisp->deactivate();
g_LateralVentricleLeftDisp->value(NULL);
}
}
else if ( (std::strncmp("Lateral Ventricle Right: ", Line, 25)) == 0)
{
if (std::strlen(Line+25) != 0)
{
g_LateralVentricleRightButton->set();
g_LateralVentricleRightDisp->activate();
g_LateralVentricleRightDisp->value(Line+25);
g_LateralVentricleRightDisp->position(g_LateralVentricleRightDisp->size());
}
else
{
g_LateralVentricleRightButton->clear();
g_LateralVentricleRightDisp->deactivate();
g_LateralVentricleRightDisp->value(NULL);
}
}
else if ( (std::strncmp("ROI File 1: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_ROIFile1Button->set();
g_ROIFile1Disp->activate();
g_ROIFile1Disp->value(Line+12);
g_ROIFile1Disp->position(g_ROIFile1Disp->size());
}
else
{
g_ROIFile1Button->clear();
g_ROIFile1Disp->deactivate();
g_ROIFile1Disp->value(NULL);
}
}
else if ( (std::strncmp("ROI File 2: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_ROIFile2Button->set();
g_ROIFile2Disp->activate();
g_ROIFile2Disp->value(Line+12);
g_ROIFile2Disp->position(g_ROIFile2Disp->size());
}
else
{
g_ROIFile2Button->clear();
g_ROIFile2Disp->deactivate();
g_ROIFile2Disp->value(NULL);
}
}
else if ( (std::strncmp("ROI File 3: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_ROIFile3Button->set();
g_ROIFile3Disp->activate();
g_ROIFile3Disp->value(Line+12);
g_ROIFile3Disp->position(g_ROIFile3Disp->size());
}
else
{
g_ROIFile3Button->clear();
g_ROIFile3Disp->deactivate();
g_ROIFile3Disp->value(NULL);
}
}
else if ( (std::strncmp("ROI File 4: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_ROIFile4Button->set();
g_ROIFile4Disp->activate();
g_ROIFile4Disp->value(Line+12);
g_ROIFile4Disp->position(g_ROIFile4Disp->size());
}
else
{
g_ROIFile4Button->clear();
g_ROIFile4Disp->deactivate();
g_ROIFile4Disp->value(NULL);
}
}
else if ( (std::strncmp("ROI File 5: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_ROIFile5Button->set();
g_ROIFile5Disp->activate();
g_ROIFile5Disp->value(Line+12);
g_ROIFile5Disp->position(g_ROIFile5Disp->size());
}
else
{
g_ROIFile5Button->clear();
g_ROIFile5Disp->deactivate();
g_ROIFile5Disp->value(NULL);
}
}
else if ( (std::strncmp("Tissue Map: ", Line, 12)) == 0)
{
if (std::strcmp(Line+12, "Soft") == 0)
{
g_SoftTissueMapButton->set();
g_HardTissueMapButton->clear();
}
else
{
g_SoftTissueMapButton->clear();
g_HardTissueMapButton->set();
}
}
else if ( (std::strncmp("Parcellation File 1: ", Line, 21)) == 0)
{
if (std::strlen(Line+21) != 0)
{
g_ParcellationFile1Button->set();
g_ParcellationFile1Disp->activate();
g_ParcellationFile1Disp->value(Line+21);
g_ParcellationFile1Disp->position(g_ParcellationFile1Disp->size());
}
else
{
g_ParcellationFile1Button->clear();
g_ParcellationFile1Disp->deactivate();
g_ParcellationFile1Disp->value(NULL);
}
}
else if ( (std::strncmp("Parcellation File 2: ", Line, 21)) == 0)
{
if (std::strlen(Line+21) != 0)
{
g_ParcellationFile2Button->set();
g_ParcellationFile2Disp->activate();
g_ParcellationFile2Disp->value(Line+21);
g_ParcellationFile2Disp->position(g_ParcellationFile2Disp->size());
}
else
{
g_ParcellationFile2Button->clear();
g_ParcellationFile2Disp->deactivate();
g_ParcellationFile2Disp->value(NULL);
}
}
else if ( (std::strncmp("Parcellation File 3: ", Line, 21)) == 0)
{
if (std::strlen(Line+21) != 0)
{
g_ParcellationFile3Button->set();
g_ParcellationFile3Disp->activate();
g_ParcellationFile3Disp->value(Line+21);
g_ParcellationFile3Disp->position(g_ParcellationFile3Disp->size());
}
else
{
g_ParcellationFile3Button->clear();
g_ParcellationFile3Disp->deactivate();
g_ParcellationFile3Disp->value(NULL);
}
}
else if ((std::strncmp("Reorientation: ", Line, 15)) == 0)
{
Reorientation = (atoi(Line+15));
if (Reorientation == 1)
{
if( m_Computation.GetReorientationAvailable() )
{
g_ReorientationButton->set();
g_InputDataOrientationDisp->activate();
g_OutputDataOrientationDisp->activate();
}
else
{
std::string message = "Reorientation not availabe: imconvert3 not found on the system " ;
if( showError )
{
fl_alert( "%s" , message.c_str() ) ;
std::cerr << message << std::endl ;
}
g_ReorientationButton->clear();
//Forcing to "no reorientation"
m_Computation.SetReorientation(0);
}
}
else
{
g_ReorientationButton->clear();
g_InputDataOrientationDisp->deactivate();
g_OutputDataOrientationDisp->deactivate();
}
}
else if ( (std::strncmp("Input Orientation: ", Line, 19)) == 0)
{
if (std::strlen(Line+19) != 0)
{
g_InputDataOrientationDisp->activate();
g_InputDataOrientationDisp->value(Line+19);
}
else
{
g_InputDataOrientationDisp->deactivate();
g_InputDataOrientationDisp->value(NULL);
}
}
else if ( (std::strncmp("Output Orientation: ", Line, 20)) == 0)
{
if (std::strlen(Line+20) != 0)
{
g_OutputDataOrientationDisp->activate();
g_OutputDataOrientationDisp->value(Line+20);
}
else
{
g_OutputDataOrientationDisp->deactivate();
g_OutputDataOrientationDisp->value(NULL);
}
}
else if ((std::strncmp("Rigid Registration: ", Line, 20)) == 0)
{
RigidRegistration = (atoi(Line+20));
if (RigidRegistration == 1)
{
g_RigidRegistrationButton->set();
g_RegridingRegistrationGroup->activate();
g_RegistrationInitializationGroup->activate();
}
else
{
g_RigidRegistrationButton->clear();
g_RegridingRegistrationGroup->deactivate();
g_RegistrationInitializationGroup->deactivate();
}
}
else if ((std::strncmp("Use T1 initial transform: ", Line, 26)) == 0)
{
InitRegUseT1InitTransform = atoi(Line+26);
if (InitRegUseT1InitTransform)
g_InitRegUseT1InitTransformButton->set();
else
g_InitRegUseT1InitTransformButton->clear();
}
else if ((std::strncmp("Is ROIAtlasGridTemplate: ", Line, 25)) == 0)
{
IsROIAtlasGridTemplate = atoi(Line+25);
if (IsROIAtlasGridTemplate)
{
g_GridTemplateAtlasButton->set();
g_GridTemplateManualButton->clear();
g_GridParametersGroup->deactivate();
}
else
{
g_GridTemplateAtlasButton->clear();
g_GridTemplateManualButton->set();
g_GridParametersGroup->activate();
}
}
else if ((std::strncmp("GridTemplate SizeX: ", Line, 20)) == 0)
{
GridTemplateSizeX = atoi(Line+20);
g_GridTemplateSizeX->value(GridTemplateSizeX);
}
else if ((std::strncmp("GridTemplate SizeY: ", Line, 20)) == 0)
{
GridTemplateSizeY = atoi(Line+20);
g_GridTemplateSizeY->value(GridTemplateSizeY);
}
else if ((std::strncmp("GridTemplate SizeZ: ", Line, 20)) == 0)
{
GridTemplateSizeZ = atoi(Line+20);
g_GridTemplateSizeZ->value(GridTemplateSizeZ);
}
else if ((std::strncmp("GridTemplate SpacingX: ", Line, 23)) == 0)
{
GridTemplateSpacingX = atof(Line+23);
g_GridTemplateSpacingX->value(GridTemplateSpacingX);
}
else if ((std::strncmp("GridTemplate SpacingY: ", Line, 23)) == 0)
{
GridTemplateSpacingY = atof(Line+23);
g_GridTemplateSpacingY->value(GridTemplateSpacingY);
}
else if ((std::strncmp("GridTemplate SpacingZ: ", Line, 23)) == 0)
{
GridTemplateSpacingZ = atof(Line+23);
g_GridTemplateSpacingZ->value(GridTemplateSpacingZ);
}
else if ((std::strncmp("Registration Initialization: ", Line, 29)) == 0)
{
if (std::strcmp(Line+29,"useCenterOfHeadAlign") == 0)
{
g_InitRegCenterOfHeadButton->set();
g_InitRegMomentsButton->clear();
g_InitRegGeometryButton->clear();
g_InitRegOffButton->clear();
}
else if (std::strcmp(Line+29,"useMomentsAlign") == 0)
{
g_InitRegCenterOfHeadButton->clear();
g_InitRegMomentsButton->set();
g_InitRegGeometryButton->clear();
g_InitRegOffButton->clear();
}
else if (std::strcmp(Line+29,"useGeometryAlign") == 0)
{
g_InitRegCenterOfHeadButton->clear();
g_InitRegMomentsButton->clear();
g_InitRegGeometryButton->set();
g_InitRegOffButton->clear();
}
else if (std::strcmp(Line+29,"Off") == 0)
{
g_InitRegCenterOfHeadButton->clear();
g_InitRegMomentsButton->clear();
g_InitRegGeometryButton->clear();
g_InitRegOffButton->set();
}
}
else if ((std::strncmp("Delete Vessels: ", Line, 16)) == 0)
{
DeleteVessels = (atoi(Line+16));
if (DeleteVessels == 1)
g_DeleteVesselsButton->set();
else
g_DeleteVesselsButton->clear();
}
else if ((std::strncmp("Intensity Rescaling: ", Line, 21)) == 0)
{
if (std::strcmp(Line+21,"Histogram quantile") == 0)
{
g_HistogramQuantileButton->set();
g_TissueMeanMatchButton->clear();
}
else
{
g_TissueMeanMatchButton->set();
g_HistogramQuantileButton->clear();
}
}
else if ( (std::strncmp("Quantiles: ", Line, 11)) == 0)
{
g_QuantilesDisp->value(Line+11);
}
else if ( (std::strncmp("Point Spacing: ", Line, 15)) == 0)
{
PointSpacing = atof(Line+15);
g_PointSpacingDisp->value(PointSpacing);
}
}
if (mode == tissueSeg ||mode == advancedParameters||mode == file)
{
if ((std::strncmp("EM Software: ", Line, 13)) == 0)
{
if (std::strcmp(Line+13,"ABC") == 0)
{
g_ABCButton->set();
g_NeosegButton->clear();
g_FilterMethodChoice->activate();
g_FluidAtlasWarpGroup->activate();
g_BSplineAtlasWarpGroup->deactivate();
g_NeosegParamGroup->deactivate();
g_InitialDistributionEstimatorChoice->activate();
}
else if (std::strcmp(Line+13,"neoseg") == 0)
{
g_NeosegButton->set();
g_ABCButton->clear();
g_FilterMethodChoice->activate();
g_FluidAtlasWarpGroup->deactivate();
g_BSplineAtlasWarpGroup->activate();
g_NeosegParamGroup->activate();
g_InitialDistributionEstimatorChoice->deactivate();
}
else
{
std::string softwareName = "Tissue segmentation software: " ;
softwareName += Line+13 ;
softwareName += "\nNo such EM Software (Beware, itkEMS is no longer supported)!" ;
if( showError )
{
fl_alert( "%s" , softwareName.c_str() ) ;
std::cerr << "Tissue segmentation software: " << Line+13 << std::endl ;
std::cerr << "No such EM Software (Beware, itkEMS is no longer supported)!"<<std::endl;
}
}
}
else if ( (std::strncmp("Filter Iterations: ", Line, 19)) == 0)
{
FilterIterations = atoi(Line+19);
g_FilterIterations->value(FilterIterations);
}
else if ( (std::strncmp("Filter TimeStep: ", Line, 17)) == 0)
{
FilterTimeStep = atof(Line+17);
g_FilterTimeStep->value(FilterTimeStep);
}
else if ( (std::strncmp("Filter Method: ", Line, 15)) == 0)
{
if (std::strcmp(Line+15, "Curvature flow") == 0)
g_FilterMethodChoice->value(1);
else
g_FilterMethodChoice->value(0);
}
else if ( (std::strncmp("Max Bias Degree: ", Line, 17)) == 0)
{
MaxBiasDegree = atoi(Line+17);
g_MaxBiasDegree->value(MaxBiasDegree);
}
else if ( (std::strncmp("Initial Distribution Estimator: ", Line, 32)) == 0)
{
if (std::strcmp(Line+32, "standard") == 0)
g_InitialDistributionEstimatorChoice->value(0);
else
g_InitialDistributionEstimatorChoice->value(1);
}
else if ( (std::strncmp("Prior 1: ", Line, 9)) == 0)
{
Prior1 = atof(Line+9);
g_Prior1->value(Prior1);
}
else if ( (std::strncmp("Prior 2: ", Line, 9)) == 0)
{
Prior2 = atof(Line+9);
g_Prior2->value(Prior2);
}
else if ( (std::strncmp("Prior 3: ", Line, 9)) == 0)
{
Prior3 = atof(Line+9);
g_Prior3->value(Prior3);
}
else if ( (std::strncmp("Prior 4: ", Line, 9)) == 0)
{
Prior4 = atof(Line+9);
g_Prior4->value(Prior4);
}
else if ( (std::strncmp("Prior 5: ", Line, 9)) == 0)
{
Prior5 = atof(Line+9);
g_Prior5->value(Prior5);
}
else if ( (std::strncmp("Prior 6: ", Line, 9)) == 0)
{
Prior6 = atof(Line+9);
g_Prior6->value(Prior6);
}
else if ( (std::strncmp("Prior 7: ", Line, 9)) == 0)
{
Prior7 = atof(Line+9);
g_Prior7->value(Prior7);
}
else if ( (std::strncmp("Prior 8: ", Line, 9)) == 0)
{
Prior8 = atof(Line+9);
g_Prior8->value(Prior8);
}
else if ( (std::strncmp("Prior 9: ", Line, 9)) == 0)
{
Prior9 = atof(Line+9);
g_Prior9->value(Prior9);
}
else if ( (std::strncmp("BSpline Atlas Warp: ", Line, 20)) == 0)
{
BSplineAtlasWarp = atoi(Line+20);
if (BSplineAtlasWarp == 1)
g_BSplineAtlasWarpButton->set();
else
g_BSplineAtlasWarpButton->clear();
}
else if ( (std::strncmp("BSpline Atlas Warp Grid X: ", Line, 27)) == 0)
{
BSplineAtlasWarpGridX = atof(Line+27);
g_BSplineAtlasWarpGridX->value(BSplineAtlasWarpGridX);
}
else if ( (std::strncmp("BSpline Atlas Warp Grid Y: ", Line, 27)) == 0)
{
BSplineAtlasWarpGridY = atof(Line+27);
g_BSplineAtlasWarpGridY->value(BSplineAtlasWarpGridY);
}
else if ( (std::strncmp("BSpline Atlas Warp Grid Z: ", Line, 27)) == 0)
{
BSplineAtlasWarpGridZ = atof(Line+27);
g_BSplineAtlasWarpGridZ->value(BSplineAtlasWarpGridZ);
}
else if ( (std::strncmp("Fluid Atlas Warp: ", Line, 18)) == 0)
{
FluidAtlasWarp = atoi(Line+18);
if (FluidAtlasWarp == 1)
{
g_FluidAtlasWarpButton->set();
g_FluidAtlasAffineButton->clear();
g_FluidAtlasFATWButton->clear();
g_ABCANTSWarpButton->clear();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
else
{
g_FluidAtlasWarpButton->clear();
}
}
else if ( (std::strncmp("Fluid Atlas Affine: ", Line, 20)) == 0)
{
FluidAtlasAffine = atoi(Line+20);
if (FluidAtlasAffine == 1)
{
g_FluidAtlasAffineButton->set();
g_FluidAtlasWarpButton->clear();
g_FluidAtlasFATWButton->clear();
g_ABCANTSWarpButton->clear();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
else
{
g_FluidAtlasAffineButton->clear();
}
}
else if ( (std::strncmp("Fluid Atlas FATW: ", Line, 18)) == 0)
{
FluidAtlasFATW = atoi(Line+18);
if (FluidAtlasFATW == 1)
{
g_FluidAtlasFATWButton->set();
g_FluidAtlasWarpButton->clear();
g_FluidAtlasAffineButton->clear();
g_ABCANTSWarpButton->clear();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
else
{
g_FluidAtlasFATWButton->clear();
}
}
else if ( (std::strncmp("ANTS Warp for ABC: ", Line, 19)) == 0)
{
if (atoi(Line+19) == 1)
{
g_FluidAtlasFATWButton->clear();
g_FluidAtlasWarpButton->clear();
g_FluidAtlasAffineButton->clear();
g_ABCANTSWarpButton->set();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
else
{
g_ABCANTSWarpButton->clear();
}
}
else if ( (std::strncmp("Fluid Atlas Warp Iterations: ", Line, 29)) == 0)
{
FluidAtlasWarpIterations = atoi(Line+29);
g_FluidAtlasWarpIterations->value(FluidAtlasWarpIterations);
}
else if ( (std::strncmp("Fluid Atlas Warp Max Step: ", Line, 27)) == 0)
{
FluidAtlasWarpMaxStep = atof(Line+27);
g_FluidAtlasWarpMaxStep->value(FluidAtlasWarpMaxStep);
}
else if ( (std::strncmp("Atlas Linear Mapping: ", Line, 22)) == 0)
{
if (std::strcmp(Line+22, "affine") == 0)
g_AtlasLinearMappingChoice->value(0);
else if (std::strcmp(Line+22, "id") == 0)
g_AtlasLinearMappingChoice->value(1);
else
g_AtlasLinearMappingChoice->value(2);
}
else if ( (std::strncmp("Image Linear Mapping: ", Line, 22)) == 0)
{
if (std::strcmp(Line+22, "id") == 0)
g_ImageLinearMappingChoice->value(0);
else if (std::strcmp(Line+22, "rigid") == 0)
g_ImageLinearMappingChoice->value(1);
else
g_ImageLinearMappingChoice->value(2);
}
else if ( (std::strncmp("Prior Threshold: ", Line, 17)) == 0)
{
NeosegPriorThreshold = atof(Line+17);
g_NeosegPriorThreshold->value(NeosegPriorThreshold);
}
else if ( (std::strncmp("Parzen Kernel: ", Line, 15)) == 0)
{
NeosegParzenKernel = atof(Line+15);
g_NeosegParzenKernel->value(NeosegParzenKernel);
}
else if ( (std::strncmp("Mahalanobis Threshold: ", Line, 23)) == 0)
{
NeosegMahalanobisThreshold = atof(Line+23);
g_NeosegMahalanobisThreshold->value(NeosegMahalanobisThreshold);
}
else if ((std::strncmp("Loop: ", Line, 6)) == 0)
{
Loop= atoi(Line+6);
if (mode==tissueSeg)
{
g_LoopButton->set();
g_AtlasLoopGroup->activate();
g_LoopIteration->activate();
}
else
{
if (Loop == 1)
{
g_LoopButton->set();
g_AtlasLoopGroup->activate();
g_LoopIteration->activate();
}
else
{
g_LoopButton->clear();
g_AtlasLoopGroup->deactivate();
g_LoopIteration->deactivate();
}
}
}
else if ( (std::strncmp("Atlas Loop: ", Line, 12)) == 0)
{
if (std::strlen(Line+12) != 0)
{
g_AtlasLoopDisp->value(Line+12);
g_AtlasLoopDisp->position(g_AtlasLoopDisp->size());
}
else
{
g_AtlasLoopDisp->value(NULL);
}
}
else if ( (std::strncmp("Loop - Number of iterations: ", Line, 29)) == 0)
{
LoopIteration = atoi(Line+29);
g_LoopIteration->value(LoopIteration);
}
}
if (mode == warping||mode == advancedParameters||mode == file)
{
if ( (std::strncmp("Warping Method: ", Line, 16)) == 0)
{
if (std::strcmp(Line+16, "Classic") == 0 && m_Computation.GetOldFluidRegistrationAvailable() )
{
g_ClassicWarpingButton->set();
g_CoarseToFineWarpingButton->clear();
g_BRAINSDemonWarpButton->clear();
g_ANTSWarpingButton->clear();
g_ANTSWarpingGroup->hide();
g_BRAINSDemonWarpGroup->hide();
g_FluidWarpingGroup->show();
g_NumBasis->activate();
g_Scale4NbIterations->deactivate();
g_Scale2NbIterations->deactivate();
}
else if (std::strcmp(Line+16, "Coarse-to-fine") == 0 && m_Computation.GetOldFluidRegistrationAvailable() )
{
g_CoarseToFineWarpingButton->set();
g_ClassicWarpingButton->clear();
g_BRAINSDemonWarpButton->clear();
g_ANTSWarpingButton->clear();
g_ANTSWarpingGroup->hide();
g_BRAINSDemonWarpGroup->hide();
g_FluidWarpingGroup->show();
g_NumBasis->deactivate();
g_Scale4NbIterations->activate();
g_Scale2NbIterations->activate();
}
else if (std::strcmp(Line+16, "BRAINSDemonWarp") == 0)
{
g_CoarseToFineWarpingButton->clear();
g_ClassicWarpingButton->clear();
g_BRAINSDemonWarpButton->set();
g_ANTSWarpingButton->clear();
g_ANTSWarpingGroup->hide();
g_BRAINSDemonWarpGroup->show();
g_FluidWarpingGroup->hide();
}
else
{
if( std::strcmp(Line+16, "ANTS") != 0 )
{
const char* message = "Error while reading parameter file: warping method incorrect or not supported on this computer!" ;
if( showError )
{
fl_alert( "%s",message ) ;
std::cerr << message << std::endl ;
}
//Forcing ANTS registration in m_Computation
m_Computation.SetClassicWarpingMethod(0);
m_Computation.SetCoarseToFineWarpingMethod(0);
m_Computation.SetBRAINSDemonWarpMethod(0);
m_Computation.SetANTSWarpingMethod(1);
}
g_CoarseToFineWarpingButton->clear();
g_ClassicWarpingButton->clear();
g_BRAINSDemonWarpButton->clear();
g_ANTSWarpingButton->set();
g_ANTSWarpingGroup->show();
g_BRAINSDemonWarpGroup->hide();
g_FluidWarpingGroup->hide();
}
}
else if ( (std::strncmp("Alpha: ", Line, 7)) == 0)
{
Alpha = atof(Line+7);
g_Alpha->value(Alpha);
}
else if ( (std::strncmp("Beta: ", Line, 6)) == 0)
{
Beta = atof(Line+6);
g_Beta->value(Beta);
}
else if ( (std::strncmp("Gamma: ", Line, 7)) == 0)
{
Gamma = atof(Line+7);
g_Gamma->value(Gamma);
}
else if ( (std::strncmp("Max Perturbation: ", Line, 18)) == 0)
{
MaxPerturbation = atof(Line+18);
g_MaxPerturbation->value(MaxPerturbation);
}
else if ( (std::strncmp("Scale 4 - Number Of Iterations: ", Line, 32)) == 0)
{
Scale4NbIterations = atoi(Line+32);
g_Scale4NbIterations->value(Scale4NbIterations);
}
else if ( (std::strncmp("Scale 2 - Number Of Iterations: ", Line, 32)) == 0)
{
Scale2NbIterations = atoi(Line+32);
g_Scale2NbIterations->value(Scale2NbIterations);
}
else if ( (std::strncmp("Scale 1 - Number Of Iterations: ", Line, 32)) == 0)
{
Scale1NbIterations = atoi(Line+32);
g_Scale1NbIterations->value(Scale1NbIterations);
}
else if ( (std::strncmp("Registration Filter Type: ", Line, 26)) == 0)
{
RegistrationFilterType =Line+26;
if (RegistrationFilterType=="Demons"){
g_RegistrationFilterType->value(0);
}
else if(RegistrationFilterType=="FastSymmetricForces"){
g_RegistrationFilterType->value(1);
}
else if(RegistrationFilterType=="Diffeomorphic"){
g_RegistrationFilterType->value(2);
}
else if(RegistrationFilterType=="LogDemons"){
g_RegistrationFilterType->value(3);
}
else if(RegistrationFilterType=="SymmetricLogDemons"){
g_RegistrationFilterType->value(4);
}
}
else if ( (std::strncmp("Deformation Field Smoothing Sigma: ", Line, 35)) == 0)
{
DeformationFieldSmoothingSigma = atof(Line+35);
g_DeformationFieldSmoothingSigma->value(DeformationFieldSmoothingSigma);
}
else if ( (std::strncmp("Pyramid Levels: ", Line, 16)) == 0)
{
PyramidLevels = atoi(Line+16);
g_PyramidLevels->value(PyramidLevels);
}
else if ( (std::strncmp("Moving Shrink Factors: ", Line, 23)) == 0)
{
MovingShrinkFactors =Line+23;
g_MovingShrinkFactors->value(MovingShrinkFactors.c_str());
}
else if ( (std::strncmp("Fixed Shrink Factors: ", Line, 22)) == 0)
{
FixedShrinkFactors =Line+22;
g_FixedShrinkFactors->value(FixedShrinkFactors.c_str());
}
else if ( (std::strncmp("Iteration Count Pyramid Levels: ", Line, 32)) == 0)
{
IterationCountPyramidLevels =Line+32;
g_IterationCountPyramidLevels->value(IterationCountPyramidLevels.c_str());
}
// consistency with the first version of the tool
else if ( (std::strncmp("Number Of Iterations: ", Line, 22)) == 0)
{
Scale1NbIterations = atoi(Line+22);
g_Scale1NbIterations->value(Scale1NbIterations);
}
else if ( (std::strncmp("NumBasis: ", Line, 10)) == 0)
{
NumBasis = atof(Line+10);
g_NumBasis->value(NumBasis);
}
else if ( (std::strncmp("ANTS Iterations: ", Line, 17)) == 0)
{
ANTSIterations = Line+17;
g_ANTSIterations->value(ANTSIterations.c_str());
}
else if ( (std::strncmp("ANTS CC weight: ", Line, 16)) == 0)
{
ANTSCCWeight = atof(Line+16);
g_ANTSCCWeight->value(ANTSCCWeight);
}
else if ( (std::strncmp("ANTS CC region radius: ", Line, 23)) == 0)
{
ANTSCCRegionRadius = atof(Line+23);
g_ANTSCCRegionRadius->value(ANTSCCRegionRadius);
}
else if ( (std::strncmp("ANTS MI weight: ", Line, 16)) == 0)
{
ANTSMIWeight = atof(Line+16);
g_ANTSMIWeight->value(ANTSMIWeight);
}
else if ( (std::strncmp("ANTS MI bins: ", Line, 14)) == 0)
{
ANTSMIBins = atoi(Line+14);
g_ANTSMIBins->value(ANTSMIBins);
}
else if ( (std::strncmp("ANTS MSQ weight: ", Line, 17)) == 0)
{
ANTSMSQWeight = atof(Line+17);
g_ANTSMSQWeight->value(ANTSMSQWeight);
}
else if ( (std::strncmp("ANTS CC weight for 2nd modality: ", Line, 33)) == 0)
{
ANTSCCWeight = atof(Line+33);
g_ANTSCCWeight2nd->value(ANTSCCWeight);
}
else if ( (std::strncmp("ANTS CC region radius for 2nd modality: ", Line, 40)) == 0)
{
ANTSCCRegionRadius = atof(Line+40);
g_ANTSCCRegionRadius2nd->value(ANTSCCRegionRadius);
}
else if ( (std::strncmp("ANTS MI weight for 2nd modality: ", Line, 33)) == 0)
{
ANTSMIWeight = atof(Line+33);
g_ANTSMIWeight2nd->value(ANTSMIWeight);
}
else if ( (std::strncmp("ANTS MI bins for 2nd modality: ", Line, 31)) == 0)
{
ANTSMIBins = atoi(Line+31);
g_ANTSMIBins2nd->value(ANTSMIBins);
}
else if ( (std::strncmp("ANTS MSQ weight for 2nd modality: ", Line, 34)) == 0)
{
ANTSMSQWeight = atof(Line+34);
g_ANTSMSQWeight2nd->value(ANTSMSQWeight);
}
else if ( (std::strncmp("ANTS Registration Type: ", Line, 24)) == 0)
{
ANTSRegistrationFilterType = Line+24;
if (ANTSRegistrationFilterType=="GreedyDiffeomorphism"){
g_ANTSRegistrationFilterType->value(0);
}
else if(ANTSRegistrationFilterType=="SpatiotemporalDiffeomorphism"){
g_ANTSRegistrationFilterType->value(1);
}
else if(ANTSRegistrationFilterType=="Elastic"){
g_ANTSRegistrationFilterType->value(2);
}
else if(ANTSRegistrationFilterType=="Exponential"){
g_ANTSRegistrationFilterType->value(3);
}
}
else if ( (std::strncmp("ANTS Registration Step: ", Line, 24)) == 0)
{
ANTSTransformationStep = Line+24;
g_ANTSTransformationStep->value(ANTSTransformationStep.c_str());
}
else if ( (std::strncmp("ANTS Gaussian Smoothing: ", Line, 25)) == 0)
{
ANTSGaussianSmoothing = atoi(Line+25);
g_ANTSGaussianSmoothingButton->value(ANTSGaussianSmoothing);
}
else if ( (std::strncmp("ANTS Gaussian Sigma: ", Line, 21)) == 0)
{
ANTSGaussianSigma = atof(Line+21);
g_ANTSGaussianSigma->value(ANTSGaussianSigma);
}
}
if(mode == N4biasFieldCorrection||mode == advancedParameters||mode == file)
{
if ((std::strncmp("Bias Correction stripped image: ", Line, 32)) == 0)
{
value = atoi(Line+32);
if (value == 1)
g_StrippedN4ITKBiasFieldCorrectionButton->set();
else
g_StrippedN4ITKBiasFieldCorrectionButton->clear();
}
if ((std::strncmp("N4 ITK Bias Field Correction: ", Line, 30)) == 0)
{
N4ITKBiasFieldCorrection= atoi(Line+30);
if(mode == N4biasFieldCorrection)
{
g_N4ITKBiasFieldCorrectionButton->set();
g_N4ParametersGroup->activate();
g_N4AdvancedParametersGroup->activate();
g_StrippedN4ITKBiasFieldCorrectionButton->activate();
}
else
{
if (N4ITKBiasFieldCorrection == 1)
{
g_N4ITKBiasFieldCorrectionButton->set();
g_N4ParametersGroup->activate();
g_N4AdvancedParametersGroup->activate();
g_StrippedN4ITKBiasFieldCorrectionButton->activate();
}
else
{
g_N4ITKBiasFieldCorrectionButton->clear();
g_N4ParametersGroup->deactivate();
g_N4AdvancedParametersGroup->deactivate();
g_StrippedN4ITKBiasFieldCorrectionButton->deactivate();
g_StrippedN4ITKBiasFieldCorrectionButton->clear();
}
}
}
else if ( (std::strncmp("N4 Number of iterations: ", Line, 25)) == 0)
{
NbOfIterations = Line+25;
g_NbOfIterations->value(NbOfIterations.c_str());
}
else if ( (std::strncmp("N4 Spline distance: ", Line, 20)) == 0)
{
SplineDistance = atof(Line+20);
g_SplineDistance->value(SplineDistance);
}
else if ( (std::strncmp("N4 Shrink factor: ", Line, 18)) == 0)
{
ShrinkFactor = atoi(Line+18);
g_ShrinkFactor->value(ShrinkFactor);
}
else if ( (std::strncmp("N4 Convergence threshold: ", Line, 26)) == 0)
{
ConvergenceThreshold = atof(Line+26);
g_ConvergenceThreshold->value(ConvergenceThreshold);
}
else if ( (std::strncmp("N4 BSpline grid resolutions: ", Line, 29)) == 0)
{
BSplineGridResolutions = Line+29;
g_BSplineGridResolutions->value(BSplineGridResolutions.c_str());
}
else if ( (std::strncmp("N4 BSpline alpha: ", Line, 18)) == 0)
{
BSplineAlpha = atof(Line+18);
//g_BSplineAlpha->value(BSplineAlpha);
}
else if ( (std::strncmp("N4 BSpline beta: ", Line, 17)) == 0)
{
BSplineBeta = atof(Line+17);
// g_BSplineBeta->value(BSplineBeta);
}
else if ( (std::strncmp("N4 Histogram sharpening: ", Line, 25)) == 0)
{
HistogramSharpening = Line+25;
g_HistogramSharpening->value(HistogramSharpening.c_str());
}
else if ( (std::strncmp("N4 BSpline order: ", Line, 18)) == 0)
{
BSplineOrder =atoi(Line+18);
g_BSplineOrder->value(BSplineOrder);
}
else if ( (std::strncmp("The Version of Slicer Used: ", Line, 27)) == 0)
{
SlicerVersion =atof(Line+27);
if (SlicerVersion == 3.0){
g_Slicer4dot3Button->clear();
g_Slicer4Button->clear();
g_Slicer3Button->set();
}
if (SlicerVersion == 4.0){
g_Slicer4dot3Button->clear();
g_Slicer4Button->set();
g_Slicer3Button->clear();
}
if (SlicerVersion == 4.3){
g_Slicer4dot3Button->set();
g_Slicer4Button->clear();
g_Slicer3Button->clear();
// Slicer4dot3ButtonChecked();
}
}
else if ( (std::strncmp("Stripped N4 ITK Bias Field Correction: ", Line, 39)) == 0)
{
StrippedN4ITKBiasFieldCorrection =atoi(Line+39);
if (StrippedN4ITKBiasFieldCorrection)
g_StrippedN4ITKBiasFieldCorrectionButton->set();
else
g_StrippedN4ITKBiasFieldCorrectionButton->clear();
}
else if ( (std::strncmp("Label Fusion Algorithm: ", Line, 24)) == 0)
{
if (std::strcmp(Line+24,"Majority Voting") == 0)
{
g_MajorityVotingButton->set();
g_WeightedMajorityVotingButton->clear();
g_StapleButton->clear();
m_Computation.SetLabelFusionAlgorithm("Majority Voting");
}
if (std::strcmp(Line+24,"Weighted Majority Voting") == 0)
{
g_MajorityVotingButton->clear();
g_WeightedMajorityVotingButton->set();
g_StapleButton->clear();
m_Computation.SetLabelFusionAlgorithm("Weighted Majority Voting");
}
if (std::strcmp(Line+24,"STAPLE") == 0)
{
g_MajorityVotingButton->clear();
g_WeightedMajorityVotingButton->clear();
g_StapleButton->set();
m_Computation.SetLabelFusionAlgorithm("STAPLE");
}
}
else if ( (std::strncmp("Intensity Energy Weight: ", Line, 25)) == 0)
{
g_IntensityEnergyWeight->value(atof(Line + 25));
}
else if ( (std::strncmp("Harmonic Energy Weight: ", Line, 24)) == 0)
{
g_HarmonicEnergyWeight->value(atof(Line + 24));
}
else if ( (std::strncmp("Shape Energy Weight: ", Line, 21)) == 0)
{
g_ShapeEnergyWeight->value(atof(Line + 21));
}
else if ( (std::strncmp("ANTS with brainmask: ", Line, 21)) == 0)
{
g_ANTSWithBrainmaskButton->value(atof(Line + 21));
}
else if ( (std::strncmp("Use Initital Affine Transform: ", Line, 31)) == 0)
{
g_UseInitialAffineButton->value(atof(Line + 31));
}
else if ( (std::strncmp("ANTS Number of Threads: ", Line, 24)) == 0)
{
g_NumberOfThreads->value(atof(Line + 24));
}
else if ( (std::strncmp("Multi-atlas directory: ", Line, 23)) == 0)
{
if (std::strlen(Line+23) != 0)
{
g_MultiAtlasDirectoryDisp->value(Line+23);
SetMultiAtlasDirectoryInitialize(Line+23);
}
else
{
g_DataDirectoryDisp->value(NULL);
}
}
}
}
fclose(ParameterFile);
}
else
{
if( showError )
{
std::string message = std::string( "Error Opening File: " ) + FileNameStr ;
fl_alert( "%s" , message.c_str() ) ;
std::cerr << message << std::endl ;
}
}
return IsParameterFileLoaded;
}
void AutoSegGUIControls::SetProcessDataDirectoryGUI()
{
// char *ProcessDataDirectory = NULL;
// m_ProcessDataDirectory = new char[512];
m_ProcessDataDirectory = fl_dir_chooser("Set the Process Data Directory", NULL);
if(m_ProcessDataDirectory != NULL)
{
CheckDirectoryName(m_ProcessDataDirectory);
m_Computation.SetProcessDataDirectory(m_ProcessDataDirectory);
g_ProcessDataDirectoryDisp->value(m_ProcessDataDirectory);
g_ProcessDataDirectoryDisp->position(g_ProcessDataDirectoryDisp->size());
}
}
void AutoSegGUIControls::SetMultiAtlasDirectoryGUI()
{
std::string tmp;
tmp = fl_dir_chooser("Set the Multi Atlas Directory", NULL);
char MultiAtlasDirectory[256], MultiAtlasDirectoryDisp[256];
char WarpedMultiAtlasAtlasImageDirectory[256];
char MultiAtlasAtlasDisplacementDirectory[256];
bool needWarpAtlasAtlas = 0, needAtlasAtlasDisplacement = 0;
// MultiAtlasDirectory = fl_dir_chooser("Set the Multi Atlas Directory", NULL);
// tmp = MultiAtlasDirectory;
strcpy(MultiAtlasDirectoryDisp, tmp.c_str());
strcpy(MultiAtlasDirectory, tmp.c_str());
strcat(MultiAtlasDirectory, "atlas_image/");
strncpy(WarpedMultiAtlasAtlasImageDirectory, MultiAtlasDirectory, tmp.length() - 12);
strcat(WarpedMultiAtlasAtlasImageDirectory, "warped-atlas-atlas-images/");
strncpy(MultiAtlasAtlasDisplacementDirectory, MultiAtlasDirectory, tmp.length() - 12) ;
strcat(MultiAtlasAtlasDisplacementDirectory, "displacement_field_atlas_to_atlas/");
if(MultiAtlasDirectory != NULL)
{
CheckDirectoryName(MultiAtlasDirectory);
m_Computation.SetMultiAtlasDirectory(MultiAtlasDirectoryDisp);
g_MultiAtlasDirectoryDisp->value(MultiAtlasDirectoryDisp);
g_MultiAtlasDirectoryDisp->position(g_MultiAtlasDirectoryDisp->size());
}
DIR *dir;
struct dirent *ent;
if ((dir = opendir (MultiAtlasDirectory)) != NULL) {
std::string filename;
int i = 0, j = 0, k = 0;
while ((ent = readdir (dir)) != NULL) {
filename = ent->d_name;
if(filename.at(0) == '.') // skip . and ..
continue;
else{
if (!filename.find("atlas")) {
if (filename.find("t1w") != std::string::npos) {
i++;
}
else if (filename.find("t2w") != std::string::npos) {
k++;
}
else {
i++;
}
}
if (!filename.find("label"))
j++;
}
}
m_Computation.SetNbAtlas(i);
m_Computation.SetNb2ndAtlas(k);
m_Computation.SetNbAtlasLabel(j);
}
closedir (dir);
if ((dir = opendir (MultiAtlasDirectory)) != NULL) {
std::string filename;
int i = 0, j = 0, k = 0;
while ((ent = readdir (dir)) != NULL) {
filename = ent->d_name;
if(filename.at(0) == '.') // skip . and ..
continue;
else{
if (!filename.find("atlas")) {
if (filename.find("t1w") != std::string::npos) {
m_Computation.SetAtlasList(filename.c_str(), i);
i++;
}
else if (filename.find("t2w") != std::string::npos) {
m_Computation.Set2ndAtlasList(filename.c_str(), k);
k++;
}
else {
m_Computation.SetAtlasList(filename.c_str(), i);
i++;
}
}
if (!filename.find("label")) {
m_Computation.SetAtlasLabelList(filename.c_str(), j);
j++;
}
}
}
}
closedir (dir);
int numberOfWarpedAtlasAtlasImage = 0;
if ((dir = opendir (WarpedMultiAtlasAtlasImageDirectory)) != NULL) {
std::string filename;
while ((ent = readdir (dir)) != NULL) {
filename = ent->d_name;
if(filename.at(0) == '.') // skip . and ..
continue;
else{
numberOfWarpedAtlasAtlasImage++;
}
}
}
closedir (dir);
if( numberOfWarpedAtlasAtlasImage < (m_Computation.GetNbAtlas() * (m_Computation.GetNbAtlas() - 1)) ) {
needWarpAtlasAtlas = 1;
}
int numberOfAtlasAtlasDisplacement = 0;
if ((dir = opendir (MultiAtlasAtlasDisplacementDirectory)) != NULL) {
std::string filename;
while ((ent = readdir (dir)) != NULL) {
filename = ent->d_name;
if(filename.at(0) == '.') // skip . and ..
continue;
else{
numberOfAtlasAtlasDisplacement++;
}
}
}
closedir (dir);
if( numberOfAtlasAtlasDisplacement < (m_Computation.GetNbAtlas() * (m_Computation.GetNbAtlas() - 1)) ) {
needAtlasAtlasDisplacement = 1;
}
//if(needAtlasAtlasDisplacement || needWarpAtlasAtlas)
// fl_message("Please, conduct the atlas to atlas registration");
}
void AutoSegGUIControls::SetMultiAtlasDirectoryInitialize(char* _AtlasDirectory)
{
std::string tmp;
tmp = _AtlasDirectory;
char MultiAtlasDirectory[256], MultiAtlasDirectoryDisp[256];
char WarpedMultiAtlasAtlasImageDirectory[256];
char MultiAtlasAtlasDisplacementDirectory[256];
bool needWarpAtlasAtlas;
strcpy(MultiAtlasDirectoryDisp, tmp.c_str());
strcpy(MultiAtlasDirectory, tmp.c_str());
strcat(MultiAtlasDirectory, "atlas_image/");
strncpy(WarpedMultiAtlasAtlasImageDirectory, MultiAtlasDirectory, tmp.length() - 12);
strcat(WarpedMultiAtlasAtlasImageDirectory, "warped-atlas-atlas-images/");
strncpy(MultiAtlasAtlasDisplacementDirectory, MultiAtlasDirectory, tmp.length() - 12) ;
strcat(MultiAtlasAtlasDisplacementDirectory, "displacement_field_atlas_to_atlas/");
if(MultiAtlasDirectory != NULL)
{
CheckDirectoryName(MultiAtlasDirectory);
needWarpAtlasAtlas = m_Computation.SetMultiAtlasDirectory(MultiAtlasDirectoryDisp);
g_MultiAtlasDirectoryDisp->value(MultiAtlasDirectoryDisp);
g_MultiAtlasDirectoryDisp->position(g_MultiAtlasDirectoryDisp->size());
}
// if(needWarpAtlasAtlas)
// fl_message("Please, conduct the atlas to atlas registration");
}
void AutoSegGUIControls::T2ButtonChecked()
{
if (g_T2Button->value())
{
g_T2Disp->activate();
m_Computation.SetT2Image(1);
}
else
{
g_T2Disp->deactivate();
m_Computation.SetT2Image(0);
}
}
void AutoSegGUIControls::PDButtonChecked()
{
if (g_PDButton->value())
{
g_PDDisp->activate();
m_Computation.SetPDImage(1);
}
else
{
g_PDDisp->deactivate();
m_Computation.SetPDImage(0);
}
}
void AutoSegGUIControls::AuxT1ButtonChecked()
{
if (g_AuxT1Button->value())
{
m_Computation.SetAuxT1Image(1);
m_Computation.SetAuxT2Image(0);
m_Computation.SetAuxPDImage(0);
}
else
{
m_Computation.SetAuxT1Image(0);
}
}
void AutoSegGUIControls::AuxT2ButtonChecked()
{
if (g_AuxT2Button->value())
{
m_Computation.SetAuxT2Image(1);
m_Computation.SetAuxT1Image(0);
m_Computation.SetAuxPDImage(0);
}
else
{
m_Computation.SetAuxT2Image(0);
}
}
void AutoSegGUIControls::AuxPDButtonChecked()
{
if (g_AuxPDButton->value())
{
m_Computation.SetAuxPDImage(1);
m_Computation.SetAuxT2Image(0);
m_Computation.SetAuxT1Image(0);
}
else
{
m_Computation.SetAuxPDImage(0);
}
}
void AutoSegGUIControls::Aux1ButtonChecked()
{
if (g_Aux1Button->value())
{
g_Aux1Title->activate();
g_Aux1Disp->activate();
g_Aux1LabelDisp->activate();
m_Computation.SetAux1Image(1);
m_Computation.SetAux1Label(g_Aux1LabelDisp->value());
g_Aux2Button->activate();
if (g_Aux2Button->value())
{
g_Aux2Title->activate();
g_Aux2Disp->activate();
g_Aux2LabelDisp->activate();
m_Computation.SetAux2Image(1);
g_Aux3Button->activate();
}
if ((g_Aux3Button->value()) && (g_Aux2Button->value()))
{
g_Aux3Title->activate();
g_Aux3Disp->activate();
g_Aux3LabelDisp->activate();
m_Computation.SetAux3Image(1);
g_Aux4Button->activate();
}
if ((g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()))
{
g_Aux4Title->activate();
g_Aux4Disp->activate();
g_Aux4LabelDisp->activate();
m_Computation.SetAux4Image(1);
g_Aux5Button->activate();
}
if ((g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()))
{
g_Aux5Title->activate();
g_Aux5Disp->activate();
g_Aux5LabelDisp->activate();
m_Computation.SetAux5Image(1);
g_Aux6Button->activate();
}
if ((g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()))
{
g_Aux6Title->activate();
g_Aux6Disp->activate();
g_Aux6LabelDisp->activate();
m_Computation.SetAux6Image(1);
g_Aux7Button->activate();
}
if ((g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()))
{
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
m_Computation.SetAux7Image(1);
g_Aux8Button->activate();
}
if ((g_Aux8Button->value()) && (g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()))
{
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
m_Computation.SetAux8Image(1);
}
}
else
{
g_Aux1Title->deactivate();
g_Aux1Disp->deactivate();
g_Aux1LabelDisp->deactivate();
m_Computation.SetAux1Image(0);
g_Aux2Title->deactivate();
g_Aux2Disp->deactivate();
g_Aux2LabelDisp->deactivate();
m_Computation.SetAux2Image(0);
g_Aux2Button->deactivate();
g_Aux2Button->clear();
g_Aux3Title->deactivate();
g_Aux3Disp->deactivate();
g_Aux3LabelDisp->deactivate();
m_Computation.SetAux3Image(0);
g_Aux3Button->deactivate();
g_Aux3Button->clear();
g_Aux4Title->deactivate();
g_Aux4Disp->deactivate();
g_Aux4LabelDisp->deactivate();
m_Computation.SetAux4Image(0);
g_Aux4Button->deactivate();
g_Aux4Button->clear();
g_Aux5Title->deactivate();
g_Aux5Disp->deactivate();
g_Aux5LabelDisp->deactivate();
m_Computation.SetAux5Image(0);
g_Aux5Button->deactivate();
g_Aux5Button->clear();
g_Aux6Title->deactivate();
g_Aux6Disp->deactivate();
g_Aux6LabelDisp->deactivate();
m_Computation.SetAux6Image(0);
g_Aux6Button->deactivate();
g_Aux6Button->clear();
g_Aux7Title->deactivate();
g_Aux7Disp->deactivate();
g_Aux7LabelDisp->deactivate();
m_Computation.SetAux7Image(0);
g_Aux7Button->deactivate();
g_Aux7Button->clear();
g_Aux8Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
g_Aux8Button->deactivate();
g_Aux8Button->clear();
}
}
void AutoSegGUIControls::Aux2ButtonChecked()
{
if ((g_Aux2Button->value()) && (g_Aux1Button->value()))
{
g_Aux2Title->activate();
g_Aux2Disp->activate();
g_Aux2LabelDisp->activate();
m_Computation.SetAux2Image(1);
g_Aux3Button->activate();
if (g_Aux3Button->value())
{
g_Aux3Title->activate();
g_Aux3Disp->activate();
g_Aux3LabelDisp->activate();
m_Computation.SetAux3Image(1);
g_Aux4Button->activate();
}
if ((g_Aux4Button->value()) && (g_Aux3Button->value()))
{
g_Aux4Title->activate();
g_Aux4Disp->activate();
g_Aux4LabelDisp->activate();
m_Computation.SetAux4Image(1);
g_Aux5Button->activate();
}
if ((g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()))
{
g_Aux5Title->activate();
g_Aux5Disp->activate();
g_Aux5LabelDisp->activate();
m_Computation.SetAux5Image(1);
g_Aux6Button->activate();
}
if ((g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()))
{
g_Aux6Title->activate();
g_Aux6Disp->activate();
g_Aux6LabelDisp->activate();
m_Computation.SetAux6Image(1);
g_Aux7Button->activate();
}
if ((g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()))
{
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
m_Computation.SetAux7Image(1);
g_Aux8Button->activate();
}
if ((g_Aux8Button->value()) && (g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()))
{
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
m_Computation.SetAux8Image(1);
}
}
else
{
g_Aux2Title->deactivate();
g_Aux2Disp->deactivate();
g_Aux2LabelDisp->deactivate();
m_Computation.SetAux2Image(0);
g_Aux3Disp->deactivate();
g_Aux3LabelDisp->deactivate();
m_Computation.SetAux3Image(0);
g_Aux3Button->deactivate();
g_Aux3Button->clear();
g_Aux3Title->deactivate();
g_Aux4Disp->deactivate();
g_Aux4LabelDisp->deactivate();
m_Computation.SetAux4Image(0);
g_Aux4Button->deactivate();
g_Aux4Button->clear();
g_Aux4Title->deactivate();
g_Aux5Disp->deactivate();
g_Aux5LabelDisp->deactivate();
m_Computation.SetAux5Image(0);
g_Aux5Button->deactivate();
g_Aux5Button->clear();
g_Aux5Title->deactivate();
g_Aux6Disp->deactivate();
g_Aux6LabelDisp->deactivate();
m_Computation.SetAux6Image(0);
g_Aux6Button->deactivate();
g_Aux6Button->clear();
g_Aux6Title->deactivate();
g_Aux7Disp->deactivate();
g_Aux7LabelDisp->deactivate();
m_Computation.SetAux7Image(0);
g_Aux7Button->deactivate();
g_Aux7Button->clear();
g_Aux7Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
g_Aux8Button->deactivate();
g_Aux8Button->clear();
g_Aux8Title->deactivate();
}
}
void AutoSegGUIControls::Aux3ButtonChecked()
{
if ((g_Aux3Button->value()) && (g_Aux2Button->value()) && (g_Aux1Button->value()))
{
g_Aux3Title->activate();
g_Aux3Disp->activate();
g_Aux3LabelDisp->activate();
m_Computation.SetAux3Image(1);
g_Aux4Button->activate();
if (g_Aux4Button->value())
{
g_Aux4Title->activate();
g_Aux4Disp->activate();
g_Aux4LabelDisp->activate();
m_Computation.SetAux4Image(1);
g_Aux5Button->activate();
}
if ((g_Aux5Button->value()) && (g_Aux4Button->value()))
{
g_Aux5Title->activate();
g_Aux5Disp->activate();
g_Aux5LabelDisp->activate();
m_Computation.SetAux5Image(1);
g_Aux6Button->activate();
}
if ((g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()))
{
g_Aux6Title->activate();
g_Aux6Disp->activate();
g_Aux6LabelDisp->activate();
m_Computation.SetAux6Image(1);
g_Aux7Button->activate();
}
if ((g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()))
{
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
m_Computation.SetAux7Image(1);
g_Aux8Button->activate();
}
if ((g_Aux8Button->value()) && (g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()))
{
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
m_Computation.SetAux8Image(1);
}
}
else
{
g_Aux3Title->deactivate();
g_Aux3Disp->deactivate();
g_Aux3LabelDisp->deactivate();
m_Computation.SetAux3Image(0);
g_Aux4Disp->deactivate();
g_Aux4LabelDisp->deactivate();
m_Computation.SetAux4Image(0);
g_Aux4Button->deactivate();
g_Aux4Button->clear();
g_Aux4Title->deactivate();
g_Aux5Disp->deactivate();
g_Aux5LabelDisp->deactivate();
m_Computation.SetAux5Image(0);
g_Aux5Button->deactivate();
g_Aux5Button->clear();
g_Aux5Title->deactivate();
g_Aux6Disp->deactivate();
g_Aux6LabelDisp->deactivate();
m_Computation.SetAux6Image(0);
g_Aux6Button->deactivate();
g_Aux6Button->clear();
g_Aux6Title->deactivate();
g_Aux7Disp->deactivate();
g_Aux7LabelDisp->deactivate();
m_Computation.SetAux7Image(0);
g_Aux7Button->deactivate();
g_Aux7Button->clear();
g_Aux7Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
g_Aux8Button->deactivate();
g_Aux8Button->clear();
g_Aux8Title->deactivate();
}
}
void AutoSegGUIControls::Aux4ButtonChecked()
{
if ((g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()) && (g_Aux1Button->value()))
{
g_Aux4Title->activate();
g_Aux4Disp->activate();
g_Aux4LabelDisp->activate();
m_Computation.SetAux4Image(1);
g_Aux5Button->activate();
if (g_Aux5Button->value())
{
g_Aux5Title->activate();
g_Aux5Disp->activate();
g_Aux5LabelDisp->activate();
m_Computation.SetAux5Image(1);
g_Aux6Button->activate();
}
if ((g_Aux6Button->value()) && (g_Aux5Button->value()))
{
g_Aux6Title->activate();
g_Aux6Disp->activate();
g_Aux6LabelDisp->activate();
m_Computation.SetAux6Image(1);
g_Aux7Button->activate();
}
if ((g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()))
{
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
m_Computation.SetAux7Image(1);
g_Aux8Button->activate();
}
if ((g_Aux8Button->value()) && (g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()))
{
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
m_Computation.SetAux8Image(1);
}
}
else
{
g_Aux4Title->deactivate();
g_Aux4Disp->deactivate();
g_Aux4LabelDisp->deactivate();
m_Computation.SetAux4Image(0);
g_Aux5Disp->deactivate();
g_Aux5LabelDisp->deactivate();
m_Computation.SetAux5Image(0);
g_Aux5Button->deactivate();
g_Aux5Button->clear();
g_Aux5Title->deactivate();
g_Aux6Disp->deactivate();
g_Aux6LabelDisp->deactivate();
m_Computation.SetAux6Image(0);
g_Aux6Button->deactivate();
g_Aux6Button->clear();
g_Aux6Title->deactivate();
g_Aux7Disp->deactivate();
g_Aux7LabelDisp->deactivate();
m_Computation.SetAux7Image(0);
g_Aux7Button->deactivate();
g_Aux7Button->clear();
g_Aux7Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
g_Aux8Button->deactivate();
g_Aux8Button->clear();
g_Aux8Title->deactivate();
}
}
void AutoSegGUIControls::Aux5ButtonChecked()
{
if ((g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()) && (g_Aux1Button->value()))
{
g_Aux5Title->activate();
g_Aux5Disp->activate();
g_Aux5LabelDisp->activate();
m_Computation.SetAux5Image(1);
g_Aux6Button->activate();
if (g_Aux6Button->value())
{
g_Aux6Title->activate();
g_Aux6Disp->activate();
g_Aux6LabelDisp->activate();
m_Computation.SetAux6Image(1);
g_Aux7Button->activate();
}
if ((g_Aux7Button->value()) && (g_Aux6Button->value()))
{
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
m_Computation.SetAux7Image(1);
g_Aux8Button->activate();
}
if ((g_Aux8Button->value()) && (g_Aux7Button->value()) && (g_Aux6Button->value()))
{
g_Aux8Title->activate();
g_Aux8LabelDisp->activate();
g_Aux8Disp->activate();
m_Computation.SetAux8Image(1);
}
}
else
{
g_Aux5Title->deactivate();
g_Aux5Disp->deactivate();
g_Aux5LabelDisp->deactivate();
m_Computation.SetAux5Image(0);
g_Aux6Disp->deactivate();
g_Aux6LabelDisp->deactivate();
m_Computation.SetAux6Image(0);
g_Aux6Button->deactivate();
g_Aux6Button->clear();
g_Aux6Title->deactivate();
g_Aux7Disp->deactivate();
g_Aux7LabelDisp->deactivate();
m_Computation.SetAux7Image(0);
g_Aux7Button->deactivate();
g_Aux7Button->clear();
g_Aux7Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
g_Aux8Button->deactivate();
g_Aux8Button->clear();
g_Aux8Title->deactivate();
}
}
void AutoSegGUIControls::Aux6ButtonChecked()
{
if ((g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()) && (g_Aux1Button->value()))
{
g_Aux6Title->activate();
g_Aux6Disp->activate();
g_Aux6LabelDisp->activate();
m_Computation.SetAux6Image(1);
g_Aux7Button->activate();
if (g_Aux7Button->value())
{
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
m_Computation.SetAux7Image(1);
g_Aux8Button->activate();
}
if ((g_Aux8Button->value()) && (g_Aux7Button->value()))
{
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
m_Computation.SetAux8Image(1);
}
}
else
{
g_Aux6Title->deactivate();
g_Aux6Disp->deactivate();
g_Aux6LabelDisp->deactivate();
m_Computation.SetAux6Image(0);
g_Aux7Disp->deactivate();
g_Aux7LabelDisp->deactivate();
m_Computation.SetAux7Image(0);
g_Aux7Button->deactivate();
g_Aux7Button->clear();
g_Aux7Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
g_Aux8Button->deactivate();
g_Aux8Button->clear();
g_Aux8Title->deactivate();
}
}
void AutoSegGUIControls::Aux7ButtonChecked()
{
if ((g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()) && (g_Aux1Button->value()))
{
g_Aux7Title->activate();
g_Aux7Disp->activate();
g_Aux7LabelDisp->activate();
m_Computation.SetAux7Image(1);
g_Aux8Button->activate();
if (g_Aux8Button->value())
{
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
m_Computation.SetAux8Image(1);
}
}
else
{
g_Aux7Title->deactivate();
g_Aux7Disp->deactivate();
g_Aux7LabelDisp->deactivate();
m_Computation.SetAux7Image(0);
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
g_Aux8Button->activate();
g_Aux8Button->clear();
g_Aux8Title->deactivate();
}
}
void AutoSegGUIControls::Aux8ButtonChecked()
{
if ((g_Aux8Button->value()) && (g_Aux7Button->value()) && (g_Aux6Button->value()) && (g_Aux5Button->value()) && (g_Aux4Button->value()) && (g_Aux3Button->value()) && (g_Aux2Button->value()) && (g_Aux1Button->value()))
{
g_Aux8Title->activate();
g_Aux8Disp->activate();
g_Aux8LabelDisp->activate();
m_Computation.SetAux8Image(1);
}
else
{
g_Aux8Title->deactivate();
g_Aux8Disp->deactivate();
g_Aux8LabelDisp->deactivate();
m_Computation.SetAux8Image(0);
}
}
void AutoSegGUIControls::SetDataDirectoryGUI()
{
//char *DataDirectory = NULL;
// m_DataDirectory = new char[512];
m_DataDirectory = fl_dir_chooser("Set the Data Directory", NULL);
if(m_DataDirectory != NULL)
{
CheckDirectoryName(m_DataDirectory);
m_Computation.SetDataDirectory(m_DataDirectory);
g_DataDirectoryDisp->value(m_DataDirectory);
g_DataDirectoryDisp->position(g_DataDirectoryDisp->size());
}
}
// Automatic Data Computation
void AutoSegGUIControls::ComputeDataGUI()
{
bool InputChecked;
InputChecked = CheckInputAutoDataSelection();
if (InputChecked == false)
{
m_Computation.SetT1(g_T1Disp->value());
if (g_T2Button->value())
m_Computation.SetT2(g_T2Disp->value());
else
m_Computation.SetT2("");
if (g_PDButton->value())
m_Computation.SetPD(g_PDDisp->value());
else
m_Computation.SetPD("");
InitBrowser();
m_Computation.ComputeData();
AddBrowserAutoData();
}
}
// Automatic Aux Data Computation
void AutoSegGUIControls::ComputeAuxDataGUI()
{
if (g_Aux1Button->value())
{
m_Computation.SetAux1(g_Aux1Disp->value());
}
else
{
m_Computation.SetAux1("");
}
if (g_Aux2Button->value())
{
m_Computation.SetAux2(g_Aux2Disp->value());
}
else
{
m_Computation.SetAux2("");
}
if (g_Aux3Button->value())
{
m_Computation.SetAux3(g_Aux3Disp->value());
}
else
{
m_Computation.SetAux3("");
}
if (g_Aux4Button->value())
{
m_Computation.SetAux4(g_Aux4Disp->value());
}
else
{
m_Computation.SetAux4("");
}
if (g_Aux5Button->value())
{
m_Computation.SetAux5(g_Aux5Disp->value());
}
else
{
m_Computation.SetAux5("");
}
if (g_Aux6Button->value())
{
m_Computation.SetAux6(g_Aux6Disp->value());
}
else
{
m_Computation.SetAux6("");
}
if (g_Aux7Button->value())
{
m_Computation.SetAux7(g_Aux7Disp->value());
}
else
{
m_Computation.SetAux7("");
}
if (g_Aux8Button->value())
{
m_Computation.SetAux8(g_Aux8Disp->value());
}
else
{
m_Computation.SetAux8("");
}
InitAuxBrowser();
m_Computation.ComputeData();
AddAuxBrowserAutoData();
}
bool AutoSegGUIControls::CheckInputAutoDataSelection()
{
bool Warning = false;
if (std::strlen(g_ProcessDataDirectoryDisp->value()) == 0)
{
fl_message("Please, set the process data directory...");
Warning = true;
}
else if (std::strlen(g_DataDirectoryDisp->value()) == 0)
{
fl_message("Please, set the data directory...");
Warning = true;
}
else if (std::strlen(g_T1Disp->value()) == 0)
{
fl_message("Please, set the T1 files...");
Warning = true;
}
else if ( (g_T2Button->value()) && (std::strlen(g_T2Disp->value()) == 0) )
{
fl_message("Please, set the T2 files...");
Warning = true;
}
else if ( (g_PDButton->value()) && (std::strlen(g_PDDisp->value()) == 0) )
{
fl_message("Please, set the PD files...");
Warning = true;
}
return Warning;
}
bool AutoSegGUIControls::CheckInputAutoAuxDataSelection()
{
bool Warning = false;
if (std::strlen(g_DataDirectoryDisp->value()) == 0)
{
fl_message("Please, set the data directory...");
Warning = true;
}
else if ( (g_Aux1Button->value()) && (std::strlen(g_Aux1Disp->value()) == 0) )
{
fl_message("Please, set the Aux1 files...");
Warning = true;
}
else if ( (g_Aux2Button->value()) && (std::strlen(g_Aux2Disp->value()) == 0) )
{
fl_message("Please, set the Aux2 files...");
Warning = true;
}
else if ( (g_Aux3Button->value()) && (std::strlen(g_Aux3Disp->value()) == 0) )
{
fl_message("Please, set the Aux3 files...");
Warning = true;
}
else if ( (g_Aux4Button->value()) && (std::strlen(g_Aux4Disp->value()) == 0) )
{
fl_message("Please, set the Aux4 files...");
Warning = true;
}
else if ( (g_Aux5Button->value()) && (std::strlen(g_Aux5Disp->value()) == 0) )
{
fl_message("Please, set the Aux5 files...");
Warning = true;
}
else if ( (g_Aux6Button->value()) && (std::strlen(g_Aux6Disp->value()) == 0) )
{
fl_message("Please, set the Aux6 files...");
Warning = true;
}
else if ( (g_Aux7Button->value()) && (std::strlen(g_Aux7Disp->value()) == 0) )
{
fl_message("Please, set the Aux7 files...");
Warning = true;
}
else if ( (g_Aux8Button->value()) && (std::strlen(g_Aux8Disp->value()) == 0) )
{
fl_message("Please, set the Aux8 files...");
Warning = true;
}
return Warning;
}
//Browser Initialization
void AutoSegGUIControls::InitBrowser()
{
g_DataBrowser->clear();
if (m_BrowserWidths)
delete[] m_BrowserWidths;
if ( (g_T2Button->value()) && (g_PDButton->value()) )
{
m_BrowserWidths = new int [3];
m_BrowserWidths[0] = 270;
m_BrowserWidths[1] = 270;
m_BrowserWidths[2] = 0;
g_DataBrowser->column_widths(m_BrowserWidths);
g_DataBrowser->showcolsep(1);
g_DataBrowser->column_char(' ');
g_DataBrowser->type(FL_MULTI_BROWSER);
g_DataBrowser->clear();
g_DataBrowser->add("@B20@b@cT1Image @B20@b@cT2Image @B20@b@cPDImage");
}
else
{
if ( (g_T2Button->value()) || (g_PDButton->value()) )
{
m_BrowserWidths = new int [2];
m_BrowserWidths[0] = 400;
m_BrowserWidths[1] = 0;
g_DataBrowser->column_widths(m_BrowserWidths);
g_DataBrowser->showcolsep(1);
g_DataBrowser->column_char(' ');
g_DataBrowser->type(FL_MULTI_BROWSER);
g_DataBrowser->clear();
if (g_T2Button->value())
g_DataBrowser->add("@B20@b@cT1Image @B20@b@cT2Image");
else
g_DataBrowser->add("@B20@b@cT1Image @B20@b@cPDImage");
}
else
{
m_BrowserWidths = new int [1];
m_BrowserWidths[0] = 0;
g_DataBrowser->column_widths(m_BrowserWidths);
g_DataBrowser->showcolsep(0);
g_DataBrowser->column_char(' ');
g_DataBrowser->type(FL_MULTI_BROWSER);
g_DataBrowser->clear();
g_DataBrowser->add("@B20@b@cT1Image");
}
}
}
//Browser Initialization
void AutoSegGUIControls::InitAuxBrowser()
{
g_AuxDataBrowser->clear();
if (m_AuxBrowserWidths)
delete[] m_AuxBrowserWidths;
if(g_AuxT1Button->value())
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) && (g_Aux8Button->value()) )
{
m_AuxBrowserWidths = new int [9];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 270;
m_AuxBrowserWidths[7] = 270;
m_AuxBrowserWidths[8] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image @B20@b@cAux7Image @B20@b@cAux8Image");
}
else{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) )
{
m_AuxBrowserWidths = new int [8];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 270;
m_AuxBrowserWidths[7] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image @B20@b@cAux7Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) )
{
m_AuxBrowserWidths = new int [7];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) )
{
m_AuxBrowserWidths = new int [6];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) )
{
m_AuxBrowserWidths = new int [5];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) )
{
m_AuxBrowserWidths = new int [4];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) )
{
m_AuxBrowserWidths = new int [3];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image @B20@b@cAux1Image @B20@b@cAux2Image");
}
else
{
if ( (g_Aux1Button->value()) )
{
m_AuxBrowserWidths = new int [2];
m_AuxBrowserWidths[0] = 400;
m_AuxBrowserWidths[1] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cTOrig1Image @B20@b@cAux1Image");
}
else
{
m_AuxBrowserWidths = new int [1];
m_AuxBrowserWidths[0] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(0);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT1Image");
}
}
}
}
}
}
}
}
}
if(g_AuxT2Button->value())
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) && (g_Aux8Button->value()) )
{
m_AuxBrowserWidths = new int [9];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 270;
m_AuxBrowserWidths[7] = 270;
m_AuxBrowserWidths[8] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image @B20@b@cAux7Image @B20@b@cAux8Image");
}
else{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) )
{
m_AuxBrowserWidths = new int [8];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 270;
m_AuxBrowserWidths[7] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image @B20@b@cAux7Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) )
{
m_AuxBrowserWidths = new int [7];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) )
{
m_AuxBrowserWidths = new int [6];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) )
{
m_AuxBrowserWidths = new int [5];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) )
{
m_AuxBrowserWidths = new int [4];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) )
{
m_AuxBrowserWidths = new int [3];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image @B20@b@cAux2Image");
}
else
{
if ( (g_Aux1Button->value()) )
{
m_AuxBrowserWidths = new int [2];
m_AuxBrowserWidths[0] = 400;
m_AuxBrowserWidths[1] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image @B20@b@cAux1Image");
}
else
{
m_AuxBrowserWidths = new int [1];
m_AuxBrowserWidths[0] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(0);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigT2Image");
}
}
}
}
}
}
}
}
}
if (g_AuxPDButton->value())
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) && (g_Aux8Button->value()) )
{
m_AuxBrowserWidths = new int [9];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 270;
m_AuxBrowserWidths[7] = 270;
m_AuxBrowserWidths[8] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image @B20@b@cAux7Image @B20@b@cAux8Image");
}
else{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) )
{
m_AuxBrowserWidths = new int [8];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 270;
m_AuxBrowserWidths[7] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image @B20@b@cAux7Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) )
{
m_AuxBrowserWidths = new int [7];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 270;
m_AuxBrowserWidths[6] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image @B20@b@cAux6Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) )
{
m_AuxBrowserWidths = new int [6];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 270;
m_AuxBrowserWidths[5] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image @B20@b@cAux5Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) )
{
m_AuxBrowserWidths = new int [5];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 270;
m_AuxBrowserWidths[4] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image @B20@b@cAux4Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) )
{
m_AuxBrowserWidths = new int [4];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 270;
m_AuxBrowserWidths[3] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image @B20@b@cAux2Image @B20@b@cAux3Image");
}
else
{
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) )
{
m_AuxBrowserWidths = new int [3];
m_AuxBrowserWidths[0] = 270;
m_AuxBrowserWidths[1] = 270;
m_AuxBrowserWidths[2] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image @B20@b@cAux2Image");
}
else
{
if ( (g_Aux1Button->value()) )
{
m_AuxBrowserWidths = new int [2];
m_AuxBrowserWidths[0] = 400;
m_AuxBrowserWidths[1] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(1);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage @B20@b@cAux1Image");
}
else
{
m_AuxBrowserWidths = new int [1];
m_AuxBrowserWidths[0] = 0;
g_AuxDataBrowser->column_widths(m_AuxBrowserWidths);
g_AuxDataBrowser->showcolsep(0);
g_AuxDataBrowser->column_char(' ');
g_AuxDataBrowser->type(FL_MULTI_BROWSER);
g_AuxDataBrowser->clear();
g_AuxDataBrowser->add("@B20@b@cOrigPDImage");
}
}
}
}
}
}
}
}
}
}
// Add automatically computed data to browser
void AutoSegGUIControls::AddBrowserAutoData()
{
m_Computation.SetManually(0);
FILE* AutoDataFile;
char Line[1536];
char Data[1536];
int Length;
if ((AutoDataFile = fopen(m_Computation.GetDataFile(),"r")) != NULL)
{
while ( (fgets(Line,1536,AutoDataFile)) != NULL)
{
Length = std::strlen(Line);
Line[Length-1] = '\0';
if (std::strncmp(Line, "// ", 2) != 0)
{
CheckData(Line);
CheckData2(Line);
RightJustifyData(Line, Data);
g_DataBrowser->add(Data);
}
}
fclose(AutoDataFile);
}
else
{
const char* errorMessage = "Error Opening File: " ;
std::cerr << errorMessage << m_Computation.GetDataFile() << std::endl ;
fl_alert( "%s %s" , errorMessage , m_Computation.GetDataFile() ) ;
}
}
// Add automatically computed Auxdata to Auxbrowser
void AutoSegGUIControls::AddAuxBrowserAutoData()
{
FILE* AutoAuxDataFile;
char Line[1536];
char Data[1536];
int Length;
if ((AutoAuxDataFile = fopen(m_Computation.GetAuxDataFile(),"r")) != NULL)
{
while ( (fgets(Line,1536,AutoAuxDataFile)) != NULL)
{
Length = std::strlen(Line);
Line[Length-1] = '\0';
if (std::strncmp(Line, "// ", 2) != 0)
{
CheckData(Line);
CheckData2(Line);
RightJustifyAuxData(Line, Data);
g_AuxDataBrowser->add(Data);
CheckData2(Line);
}
}
fclose(AutoAuxDataFile);
}
else
{
const char* errorMessage = "Error Opening File: " ;
std::cerr << errorMessage << m_Computation.GetAuxDataFile() << std::endl ;
fl_alert( "%s %s" , errorMessage , m_Computation.GetDataFile() ) ;
}
}
//Replace strings "//" by '/'
void AutoSegGUIControls::CheckData(char *_Line)
{
std::string Line = _Line;
std::string tmp;
std::string::size_type loc;
int InLoop = 1;
while (InLoop == 1)
{
loc = Line.find( "//", 0);
if( loc != std::string::npos )
{
tmp.assign(Line,0,loc+1);
tmp.append(Line,loc+2, Line.size()-loc);
Line = tmp;
}
else
InLoop = 0;
}
std::strcpy(_Line,Line.c_str());
}
//Deals with "/../" strings
void AutoSegGUIControls::CheckData2(char *_Line)
{
std::string Line = _Line;
std::string tmp1, tmp2;
std::string::size_type loc1,loc2;
int InLoop = 1;
while (InLoop == 1)
{
loc1 = Line.find( "/../", 0);
if( loc1 != std::string::npos )
{
tmp1.assign(Line,0,loc1);
tmp2.assign(Line,loc1+4,Line.size()-loc1-4);
loc2 = tmp1.find_last_of("/",tmp1.size());
tmp1.append("/");
tmp1.replace(loc2+1,tmp2.size(),tmp2);
Line = tmp1;
}
else
InLoop = 0;
}
std::strcpy(_Line, Line.c_str());
}
// Add data manually to browser
void AutoSegGUIControls::AddDataGUI()
{
char Line[1536];
std::strcpy(Line, "");
AddDataGUIControls AddData(g_T2Button->value(), g_PDButton->value());
AddData.g_MainWindow->show();
while(AddData.g_MainWindow->shown())
Fl::wait();
if ( (!g_T2Button->value()) && (!g_PDButton->value()) && (std::strlen(AddData.GetT1File())!= 0) )
std::strcpy(Line, AddData.GetT1File());
else if (std::strlen(AddData.GetT1File())!= 0)
{
std::strcpy(Line, "@r");
std::strcat(Line, AddData.GetT1File());
}
if ( (g_T2Button->value()) && (g_PDButton->value()) && (std::strlen(AddData.GetT2File())!= 0) && (std::strlen(AddData.GetPDFile())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddData.GetT2File());
std::strcat(Line, " ");
std::strcat(Line, AddData.GetPDFile());
}
else if ( (g_T2Button->value()) && (std::strlen(AddData.GetT2File())!= 0) )
{
std::strcat(Line, " ");
std::strcat(Line, AddData.GetT2File());
}
else if (std::strlen(AddData.GetPDFile())!= 0)
{
std::strcat(Line, " ");
std::strcat(Line, AddData.GetPDFile());
}
if (g_DataBrowser->size() < 2)
InitBrowser();
if (std::strlen(Line) != 0)
g_DataBrowser->add(Line);
m_Computation.SetMultiAtlasTargetFile(g_DataBrowser->text(2));
}
// Add data manually to Auxbrowser
void AutoSegGUIControls::AddAuxDataGUI()
{
char Line[1536];
m_Computation.SetManually(1);
std::strcpy(Line, "");
AddAuxDataGUIControls AddAuxData(g_AuxT1Button->value(), g_AuxT2Button->value(), g_AuxPDButton->value(), g_Aux1Button->value(), g_Aux2Button->value(), g_Aux3Button->value(), g_Aux4Button->value(), g_Aux5Button->value(), g_Aux6Button->value(), g_Aux7Button->value(), g_Aux8Button->value());
AddAuxData.g_MainWindow->show();
while(AddAuxData.g_MainWindow->shown())
Fl::wait();
if ( (!g_Aux1Button->value()) && (!g_Aux2Button->value()) && (!g_Aux3Button->value()) && (!g_Aux4Button->value()) && (!g_Aux5Button->value()) && (!g_Aux6Button->value()) && (!g_Aux7Button->value()) && (!g_Aux8Button->value()) && (std::strlen(AddAuxData.GetAuxT1File())!= 0) )
if (g_AuxT1Button->value())
std::strcpy(Line, AddAuxData.GetAuxT1File());
if (g_AuxT2Button->value())
std::strcpy(Line, AddAuxData.GetAuxT2File());
if (g_AuxPDButton->value())
std::strcpy(Line, AddAuxData.GetAuxPDFile());
else if (std::strlen(AddAuxData.GetAuxT1File())!= 0)
{
std::strcpy(Line, "@r");
std::strcat(Line, AddAuxData.GetAuxT1File());
}
else if (std::strlen(AddAuxData.GetAuxT2File())!= 0)
{
std::strcpy(Line, "@r");
std::strcat(Line, AddAuxData.GetAuxT2File());
}
else if (std::strlen(AddAuxData.GetAuxPDFile())!= 0)
{
std::strcpy(Line, "@r");
std::strcat(Line, AddAuxData.GetAuxPDFile());
}
if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) && (g_Aux8Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) && (std::strlen(AddAuxData.GetAux2File())!= 0) && (std::strlen(AddAuxData.GetAux3File())!= 0) && (std::strlen(AddAuxData.GetAux4File())!= 0) && (std::strlen(AddAuxData.GetAux5File())!= 0) && (std::strlen(AddAuxData.GetAux6File())!= 0) && (std::strlen(AddAuxData.GetAux7File())!= 0) && (std::strlen(AddAuxData.GetAux8File())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux1File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux2File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux3File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux4File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux5File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux6File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux7File());
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux8File());
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) && (std::strlen(AddAuxData.GetAux2File())!= 0) && (std::strlen(AddAuxData.GetAux3File())!= 0) && (std::strlen(AddAuxData.GetAux4File())!= 0) && (std::strlen(AddAuxData.GetAux5File())!= 0) && (std::strlen(AddAuxData.GetAux6File())!= 0) && (std::strlen(AddAuxData.GetAux7File())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux1File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux2File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux3File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux4File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux5File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux6File());
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux7File());
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) && (std::strlen(AddAuxData.GetAux2File())!= 0) && (std::strlen(AddAuxData.GetAux3File())!= 0) && (std::strlen(AddAuxData.GetAux4File())!= 0) && (std::strlen(AddAuxData.GetAux5File())!= 0) && (std::strlen(AddAuxData.GetAux6File())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux1File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux2File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux3File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux4File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux5File());
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux6File());
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) && (std::strlen(AddAuxData.GetAux2File())!= 0) && (std::strlen(AddAuxData.GetAux3File())!= 0) && (std::strlen(AddAuxData.GetAux4File())!= 0) && (std::strlen(AddAuxData.GetAux5File())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux1File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux2File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux3File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux4File());
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux5File());
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) && (std::strlen(AddAuxData.GetAux2File())!= 0) && (std::strlen(AddAuxData.GetAux3File())!= 0) && (std::strlen(AddAuxData.GetAux4File())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux1File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux2File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux3File());
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux4File());
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) && (std::strlen(AddAuxData.GetAux2File())!= 0) && (std::strlen(AddAuxData.GetAux3File())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux1File());
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux2File());
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux3File());
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) && (std::strlen(AddAuxData.GetAux2File())!= 0) )
{
std::strcat(Line, " @r");
std::strcat(Line, AddAuxData.GetAux1File());
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux2File());
}
else if ( (g_Aux1Button->value()) && (std::strlen(AddAuxData.GetAux1File())!= 0) )
{
std::strcat(Line, " ");
std::strcat(Line, AddAuxData.GetAux1File());
}
if (g_AuxDataBrowser->size() < 2)
InitAuxBrowser();
if (std::strlen(Line) != 0)
g_AuxDataBrowser->add(Line);
}
// Remove data manually from browser
void AutoSegGUIControls::RemoveDataGUI()
{
int line = 2;
while (line <= g_DataBrowser->size())
{
if (g_DataBrowser->selected(line))
g_DataBrowser->remove(line);
else
line++;
}
}
// Remove data manually from Auxbrowser
void AutoSegGUIControls::RemoveAuxDataGUI()
{
int line = 2;
while (line <= g_AuxDataBrowser->size())
{
if (g_AuxDataBrowser->selected(line))
g_AuxDataBrowser->remove(line);
else
line++;
}
}
// Clear browser
void AutoSegGUIControls::ClearDataGUI()
{
InitBrowser();
}
void AutoSegGUIControls::ClearAuxDataGUI()
{
InitAuxBrowser();
}
void AutoSegGUIControls::SetCommonCoordinateImageGUI()
{
char *CommonCoordinateImage = NULL;
CommonCoordinateImage = fl_file_chooser("Set the Common Coordinate Image","Images (*.{gipl,gipl.gz,nii,nii.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(CommonCoordinateImage != NULL)
{
m_Computation.SetCommonCoordinateImage(CommonCoordinateImage);
g_CommonCoordinateImageDisp->value(CommonCoordinateImage);
g_CommonCoordinateImageDisp->position(g_CommonCoordinateImageDisp->size());
}
}
void AutoSegGUIControls::SetTissueSegmentationAtlasDirectoryGUI()
{
char *TissueSegmentationAtlasDirectory = NULL;
TissueSegmentationAtlasDirectory = fl_dir_chooser("Set the Tissue Segmentation Atlas Directory",NULL);
if(TissueSegmentationAtlasDirectory != NULL)
{
CheckDirectoryName(TissueSegmentationAtlasDirectory);
m_Computation.SetTissueSegmentationAtlasDirectory(TissueSegmentationAtlasDirectory);
g_TissueSegmentationAtlasDirectoryDisp->value(TissueSegmentationAtlasDirectory);
g_TissueSegmentationAtlasDirectoryDisp->position(g_TissueSegmentationAtlasDirectoryDisp->size());
}
}
void AutoSegGUIControls::SetROIAtlasFileGUI()
{
char *ROIAtlasFile = NULL;
ROIAtlasFile = fl_file_chooser("Set the ROI Atlas File", "Images (*.{gipl,gipl.gz,nii,nii.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ROIAtlasFile != NULL)
{
m_Computation.SetROIAtlasFile(ROIAtlasFile);
g_ROIAtlasFileDisp->value(ROIAtlasFile);
g_ROIAtlasFileDisp->position(g_ROIAtlasFileDisp->size());
}
}
void AutoSegGUIControls::SetT2ROIAtlasFileGUI()
{
char *ROIAtlasFile = NULL;
ROIAtlasFile = fl_file_chooser("Set the ROI Atlas File", "Images (*.{gipl,gipl.gz,nii,nii.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ROIAtlasFile != NULL)
{
m_Computation.SetROIT2AtlasFile(ROIAtlasFile);
g_ROIT2AtlasFileDisp->value(ROIAtlasFile);
g_ROIT2AtlasFileDisp->position(g_ROIAtlasFileDisp->size());
m_Computation.SetROIT2Atlas(1);
}
else {
m_Computation.SetROIT2Atlas(0);
}
}
void AutoSegGUIControls::SetLoopGUI()
{
char *AtlasLoopDirectory = NULL;
AtlasLoopDirectory = fl_dir_chooser("Set the Atlas loop directory",NULL);
if(AtlasLoopDirectory != NULL)
{
CheckDirectoryName(AtlasLoopDirectory);
m_Computation.SetAtlasLoop(AtlasLoopDirectory);
g_AtlasLoopDisp->value(AtlasLoopDirectory);
g_AtlasLoopDisp->position(g_AtlasLoopDisp->size());
}
}
void AutoSegGUIControls::TissueSegmentationAtlasT1ButtonToggled()
{
g_TissueSegmentationAtlasT1Button->set();
g_TissueSegmentationAtlasT2Button->clear();
m_Computation.SetTissueSegmentationAtlasType("T1");
}
void AutoSegGUIControls::TissueSegmentationAtlasT2ButtonToggled()
{
g_TissueSegmentationAtlasT2Button->set();
g_TissueSegmentationAtlasT1Button->clear();
m_Computation.SetTissueSegmentationAtlasType("T2");
}
void AutoSegGUIControls::CommonCoordinateImageT1ButtonToggled()
{
g_CommonCoordinateImageT1Button->set();
g_CommonCoordinateImageT2Button->clear();
m_Computation.SetCommonCoordinateImageType("T1");
}
void AutoSegGUIControls::CommonCoordinateImageT2ButtonToggled()
{
g_CommonCoordinateImageT2Button->set();
g_CommonCoordinateImageT1Button->clear();
m_Computation.SetCommonCoordinateImageType("T2");
}
void AutoSegGUIControls::SetAmygdalaLeftGUI()
{
char *AmygdalaLeft = NULL;
AmygdalaLeft = fl_file_chooser("Set the Amygdala File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(AmygdalaLeft != NULL)
{
m_Computation.SetAmygdalaLeft(AmygdalaLeft);
g_AmygdalaLeftDisp->value(AmygdalaLeft);
g_AmygdalaLeftDisp->position(g_AmygdalaLeftDisp->size());
}
}
void AutoSegGUIControls::SetAmygdalaRightGUI()
{
char *AmygdalaRight = NULL;
AmygdalaRight = fl_file_chooser("Set the Amygdala File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(AmygdalaRight != NULL)
{
m_Computation.SetAmygdalaRight(AmygdalaRight);
g_AmygdalaRightDisp->value(AmygdalaRight);
g_AmygdalaRightDisp->position(g_AmygdalaRightDisp->size());
}
}
void AutoSegGUIControls::SetCaudateLeftGUI()
{
char *CaudateLeft = NULL;
CaudateLeft = fl_file_chooser("Set the Caudate File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(CaudateLeft != NULL)
{
m_Computation.SetCaudateLeft(CaudateLeft);
g_CaudateLeftDisp->value(CaudateLeft);
g_CaudateLeftDisp->position(g_CaudateLeftDisp->size());
}
}
void AutoSegGUIControls::SetCaudateRightGUI()
{
char *CaudateRight = NULL;
CaudateRight = fl_file_chooser("Set the Caudate File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(CaudateRight != NULL)
{
m_Computation.SetCaudateRight(CaudateRight);
g_CaudateRightDisp->value(CaudateRight);
g_CaudateRightDisp->position(g_CaudateRightDisp->size());
}
}
void AutoSegGUIControls::SetHippocampusLeftGUI()
{
char *HippocampusLeft = NULL;
HippocampusLeft = fl_file_chooser("Set the Hippocampus File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(HippocampusLeft != NULL)
{
m_Computation.SetHippocampusLeft(HippocampusLeft);
g_HippocampusLeftDisp->value(HippocampusLeft);
g_HippocampusLeftDisp->position(g_HippocampusLeftDisp->size());
}
}
void AutoSegGUIControls::SetHippocampusRightGUI()
{
char *HippocampusRight = NULL;
HippocampusRight = fl_file_chooser("Set the Hippocampus File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(HippocampusRight != NULL)
{
m_Computation.SetHippocampusRight(HippocampusRight);
g_HippocampusRightDisp->value(HippocampusRight);
g_HippocampusRightDisp->position(g_HippocampusRightDisp->size());
}
}
void AutoSegGUIControls::SetPallidusLeftGUI()
{
char *PallidusLeft = NULL;
PallidusLeft = fl_file_chooser("Set the Pallidus File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(PallidusLeft != NULL)
{
m_Computation.SetPallidusLeft(PallidusLeft);
g_PallidusLeftDisp->value(PallidusLeft);
g_PallidusLeftDisp->position(g_PallidusLeftDisp->size());
}
}
void AutoSegGUIControls::SetPallidusRightGUI()
{
char *PallidusRight = NULL;
PallidusRight = fl_file_chooser("Set the Pallidus File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(PallidusRight != NULL)
{
m_Computation.SetPallidusRight(PallidusRight);
g_PallidusRightDisp->value(PallidusRight);
g_PallidusRightDisp->position(g_PallidusRightDisp->size());
}
}
void AutoSegGUIControls::SetPutamenLeftGUI()
{
char *PutamenLeft = NULL;
PutamenLeft = fl_file_chooser("Set the Putamen File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(PutamenLeft != NULL)
{
m_Computation.SetPutamenLeft(PutamenLeft);
g_PutamenLeftDisp->value(PutamenLeft);
g_PutamenLeftDisp->position(g_PutamenLeftDisp->size());
}
}
void AutoSegGUIControls::SetPutamenRightGUI()
{
char *PutamenRight = NULL;
PutamenRight = fl_file_chooser("Set the Putamen File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(PutamenRight != NULL)
{
m_Computation.SetPutamenRight(PutamenRight);
g_PutamenRightDisp->value(PutamenRight);
g_PutamenRightDisp->position(g_PutamenRightDisp->size());
}
}
void AutoSegGUIControls::SetLateralVentricleLeftGUI()
{
char *LateralVentricleLeft = NULL;
LateralVentricleLeft = fl_file_chooser("Set the Lateral Ventricle File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(LateralVentricleLeft != NULL)
{
m_Computation.SetLateralVentricleLeft(LateralVentricleLeft);
g_LateralVentricleLeftDisp->value(LateralVentricleLeft);
g_LateralVentricleLeftDisp->position(g_LateralVentricleLeftDisp->size());
}
}
void AutoSegGUIControls::SetLateralVentricleRightGUI()
{
char *LateralVentricleRight = NULL;
LateralVentricleRight = fl_file_chooser("Set the Lateral Ventricle File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(LateralVentricleRight != NULL)
{
m_Computation.SetLateralVentricleRight(LateralVentricleRight);
g_LateralVentricleRightDisp->value(LateralVentricleRight);
g_LateralVentricleRightDisp->position(g_LateralVentricleRightDisp->size());
}
}
void AutoSegGUIControls::AllStructuresButtonChecked()
{
if (g_AllStructuresButton->value())
{
g_AmygdalaLeftButton->set();
g_AmygdalaRightButton->set();
g_CaudateLeftButton->set();
g_CaudateRightButton->set();
g_HippocampusLeftButton->set();
g_HippocampusRightButton->set();
g_PallidusLeftButton->set();
g_PallidusRightButton->set();
g_PutamenLeftButton->set();
g_PutamenRightButton->set();
g_LateralVentricleLeftButton->set();
g_LateralVentricleRightButton->set();
g_AmygdalaLeftDisp->activate();
g_AmygdalaRightDisp->activate();
g_CaudateLeftDisp->activate();
g_CaudateRightDisp->activate();
g_HippocampusLeftDisp->activate();
g_HippocampusRightDisp->activate();
g_PallidusLeftDisp->activate();
g_PallidusRightDisp->activate();
g_PutamenLeftDisp->activate();
g_PutamenRightDisp->activate();
g_LateralVentricleLeftDisp->activate();
g_LateralVentricleRightDisp->activate();
}
else
{
g_AmygdalaLeftButton->clear();
g_AmygdalaRightButton->clear();
g_CaudateLeftButton->clear();
g_CaudateRightButton->clear();
g_HippocampusLeftButton->clear();
g_HippocampusRightButton->clear();
g_PallidusLeftButton->clear();
g_PallidusRightButton->clear();
g_PutamenLeftButton->clear();
g_PutamenRightButton->clear();
g_LateralVentricleLeftButton->clear();
g_LateralVentricleRightButton->clear();
g_AmygdalaLeftDisp->deactivate();
g_AmygdalaRightDisp->deactivate();
g_CaudateLeftDisp->deactivate();
g_CaudateRightDisp->deactivate();
g_HippocampusLeftDisp->deactivate();
g_HippocampusRightDisp->deactivate();
g_PallidusLeftDisp->deactivate();
g_PallidusRightDisp->deactivate();
g_PutamenLeftDisp->deactivate();
g_PutamenRightDisp->deactivate();
g_LateralVentricleLeftDisp->deactivate();
g_LateralVentricleRightDisp->deactivate();
}
}
void AutoSegGUIControls::AmygdalaLeftButtonChecked()
{
if (g_AmygdalaLeftButton->value())
g_AmygdalaLeftDisp->activate();
else
g_AmygdalaLeftDisp->deactivate();
}
void AutoSegGUIControls::AmygdalaRightButtonChecked()
{
if (g_AmygdalaRightButton->value())
g_AmygdalaRightDisp->activate();
else
g_AmygdalaRightDisp->deactivate();
}
void AutoSegGUIControls::CaudateLeftButtonChecked()
{
if (g_CaudateLeftButton->value())
g_CaudateLeftDisp->activate();
else
g_CaudateLeftDisp->deactivate();
}
void AutoSegGUIControls::CaudateRightButtonChecked()
{
if (g_CaudateRightButton->value())
g_CaudateRightDisp->activate();
else
g_CaudateRightDisp->deactivate();
}
void AutoSegGUIControls::HippocampusLeftButtonChecked()
{
if (g_HippocampusLeftButton->value())
g_HippocampusLeftDisp->activate();
else
g_HippocampusLeftDisp->deactivate();
}
void AutoSegGUIControls::HippocampusRightButtonChecked()
{
if (g_HippocampusRightButton->value())
g_HippocampusRightDisp->activate();
else
g_HippocampusRightDisp->deactivate();
}
void AutoSegGUIControls::PallidusLeftButtonChecked()
{
if (g_PallidusLeftButton->value())
g_PallidusLeftDisp->activate();
else
g_PallidusLeftDisp->deactivate();
}
void AutoSegGUIControls::PallidusRightButtonChecked()
{
if (g_PallidusRightButton->value())
g_PallidusRightDisp->activate();
else
g_PallidusRightDisp->deactivate();
}
void AutoSegGUIControls::PutamenLeftButtonChecked()
{
if (g_PutamenLeftButton->value())
g_PutamenLeftDisp->activate();
else
g_PutamenLeftDisp->deactivate();
}
void AutoSegGUIControls::PutamenRightButtonChecked()
{
if (g_PutamenRightButton->value())
g_PutamenRightDisp->activate();
else
g_PutamenRightDisp->deactivate();
}
void AutoSegGUIControls::LateralVentricleLeftButtonChecked()
{
if (g_LateralVentricleLeftButton->value())
g_LateralVentricleLeftDisp->activate();
else
g_LateralVentricleLeftDisp->deactivate();
}
void AutoSegGUIControls::LateralVentricleRightButtonChecked()
{
if (g_LateralVentricleRightButton->value())
g_LateralVentricleRightDisp->activate();
else
g_LateralVentricleRightDisp->deactivate();
}
void AutoSegGUIControls::SetROIFile1GUI()
{
char *ROIFile1 = NULL;
ROIFile1 = fl_file_chooser("Set the ROI File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ROIFile1 != NULL)
{
m_Computation.SetROIFile1(ROIFile1);
g_ROIFile1Disp->value(ROIFile1);
g_ROIFile1Disp->position(g_ROIFile1Disp->size());
}
}
void AutoSegGUIControls::SetROIFile2GUI()
{
char *ROIFile2 = NULL;
ROIFile2 = fl_file_chooser("Set the ROI File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ROIFile2 != NULL)
{
m_Computation.SetROIFile2(ROIFile2);
g_ROIFile2Disp->value(ROIFile2);
g_ROIFile2Disp->position(g_ROIFile2Disp->size());
}
}
void AutoSegGUIControls::SetROIFile3GUI()
{
char *ROIFile3 = NULL;
ROIFile3 = fl_file_chooser("Set the ROI File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ROIFile3 != NULL)
{
m_Computation.SetROIFile3(ROIFile3);
g_ROIFile3Disp->value(ROIFile3);
g_ROIFile3Disp->position(g_ROIFile3Disp->size());
}
}
void AutoSegGUIControls::SetROIFile4GUI()
{
char *ROIFile4 = NULL;
ROIFile4 = fl_file_chooser("Set the ROI File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ROIFile4 != NULL)
{
m_Computation.SetROIFile4(ROIFile4);
g_ROIFile4Disp->value(ROIFile4);
g_ROIFile4Disp->position(g_ROIFile4Disp->size());
}
}
void AutoSegGUIControls::SetROIFile5GUI()
{
char *ROIFile5 = NULL;
ROIFile5 = fl_file_chooser("Set the ROI File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ROIFile5 != NULL)
{
m_Computation.SetROIFile5(ROIFile5);
g_ROIFile5Disp->value(ROIFile5);
g_ROIFile5Disp->position(g_ROIFile5Disp->size());
}
}
void AutoSegGUIControls::ROIFile1ButtonChecked()
{
if (g_ROIFile1Button->value())
g_ROIFile1Disp->activate();
else
g_ROIFile1Disp->deactivate();
}
void AutoSegGUIControls::ROIFile2ButtonChecked()
{
if (g_ROIFile2Button->value())
g_ROIFile2Disp->activate();
else
g_ROIFile2Disp->deactivate();
}
void AutoSegGUIControls::ROIFile3ButtonChecked()
{
if (g_ROIFile3Button->value())
g_ROIFile3Disp->activate();
else
g_ROIFile3Disp->deactivate();
}
void AutoSegGUIControls::ROIFile4ButtonChecked()
{
if (g_ROIFile4Button->value())
g_ROIFile4Disp->activate();
else
g_ROIFile4Disp->deactivate();
}
void AutoSegGUIControls::ROIFile5ButtonChecked()
{
if (g_ROIFile5Button->value())
g_ROIFile5Disp->activate();
else
g_ROIFile5Disp->deactivate();
}
void AutoSegGUIControls::SetParcellationFile1GUI()
{
char *ParcellationFile1 = NULL;
ParcellationFile1 = fl_file_chooser("Set the Parcellation File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ParcellationFile1 != NULL)
{
m_Computation.SetParcellationFile1(ParcellationFile1);
g_ParcellationFile1Disp->value(ParcellationFile1);
g_ParcellationFile1Disp->position(g_ParcellationFile1Disp->size());
}
}
void AutoSegGUIControls::SetParcellationFile2GUI()
{
char *ParcellationFile2 = NULL;
ParcellationFile2 = fl_file_chooser("Set the Parcellation File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ParcellationFile2 != NULL)
{
m_Computation.SetParcellationFile2(ParcellationFile2);
g_ParcellationFile2Disp->value(ParcellationFile2);
g_ParcellationFile2Disp->position(g_ParcellationFile2Disp->size());
}
}
void AutoSegGUIControls::SetParcellationFile3GUI()
{
char *ParcellationFile3 = NULL;
ParcellationFile3 = fl_file_chooser("Set the Parcellation File","Images (*.{gipl,gipl.gz,mhd,mha,hdr,nhdr,nrrd})",NULL);
if(ParcellationFile3 != NULL)
{
m_Computation.SetParcellationFile3(ParcellationFile3);
g_ParcellationFile3Disp->value(ParcellationFile3);
g_ParcellationFile3Disp->position(g_ParcellationFile3Disp->size());
}
}
void AutoSegGUIControls::SoftTissueMapButtonToggled()
{
g_SoftTissueMapButton->set();
g_HardTissueMapButton->clear();
m_Computation.SetSoftTissueMap("Soft");
}
void AutoSegGUIControls::HardTissueMapButtonToggled()
{
g_SoftTissueMapButton->clear();
g_HardTissueMapButton->set();
m_Computation.SetSoftTissueMap("Hard");
}
void AutoSegGUIControls::ParcellationFile1ButtonChecked()
{
if (g_ParcellationFile1Button->value())
g_ParcellationFile1Disp->activate();
else
g_ParcellationFile1Disp->deactivate();
}
void AutoSegGUIControls::ParcellationFile2ButtonChecked()
{
if (g_ParcellationFile2Button->value())
g_ParcellationFile2Disp->activate();
else
g_ParcellationFile2Disp->deactivate();
}
void AutoSegGUIControls::ParcellationFile3ButtonChecked()
{
if (g_ParcellationFile3Button->value())
g_ParcellationFile3Disp->activate();
else
g_ParcellationFile3Disp->deactivate();
}
void AutoSegGUIControls::ComputeVolumeButtonChecked()
{
if (g_ComputeVolumeButton->value())
m_Computation.SetComputeVolume(1);
else
m_Computation.SetComputeVolume(0);
}
void AutoSegGUIControls::ComputeCorticalThicknessButtonChecked()
{
if (g_ComputeCorticalThicknessButton->value())
m_Computation.SetComputeCorticalThickness(1);
else
m_Computation.SetComputeCorticalThickness(0);
}
void AutoSegGUIControls::MultiModalitySingleSegmentationButtonChecked()
{
if (g_MultiModalitySingleSegButton->value()) {
m_Computation.SetMultiModalitySingleSegmentation(1);
}
else {
m_Computation.SetMultiModalitySingleSegmentation(0);
}
}
void AutoSegGUIControls::MultiModalityMultiSegmentationButtonChecked()
{
if (g_MultiModalityMultiSegButton->value()) {
m_Computation.SetMultiModalityMultiSegmentation(1);
}
else {
m_Computation.SetMultiModalityMultiSegmentation(0);
}
}
void AutoSegGUIControls::MultiAtlasSegmentationButtonChecked()
{
if (g_MultiAtlasSegButton->value()) {
m_Computation.SetMultiAtlasSegmentation(1);
if (g_MajorityVotingButton->value())
m_Computation.SetLabelFusionAlgorithm("Majority Voting");
if (g_WeightedMajorityVotingButton->value())
m_Computation.SetLabelFusionAlgorithm("Weighted Majority Voting");
if (g_StapleButton->value())
m_Computation.SetLabelFusionAlgorithm("STAPLE");
m_Computation.SetWeightIntensityEnergy(g_IntensityEnergyWeight->value());
m_Computation.SetWeightHarmonicEnergy(g_HarmonicEnergyWeight->value());
m_Computation.SetWeightShapeEnergy(g_ShapeEnergyWeight->value());
}
else {
m_Computation.SetMultiAtlasSegmentation(0);
}
}
void AutoSegGUIControls::SingleAtlasSegmentationButtonChecked()
{
if (g_SingleAtlasSegButton->value()) {
m_Computation.SetSingleAtlasSegmentation(1);
}
else {
m_Computation.SetSingleAtlasSegmentation(0);
}
}
void AutoSegGUIControls::RandomizeSubjectsButtonChecked()
{
if (g_RandomizeSubjectsButton->value()) {
m_Computation.SetRandomizeSubjects(1);
}
else {
m_Computation.SetRandomizeSubjects(0);
}
}
void AutoSegGUIControls::RecalculateAtlasTargetEnergyButtonChecked()
{
if (g_RecalculateAtlasTargetEnergyButton->value()) {
m_Computation.SetRecalculateAtlasTargetMultiAtlasEnergy(1);
}
else {
m_Computation.SetRecalculateAtlasTargetMultiAtlasEnergy(0);
}
}
void AutoSegGUIControls::RecalculateAtlasAtlasEnergyButtonChecked()
{
if (g_RecalculateAtlasAtlasEnergyButton->value()) {
m_Computation.SetRecalculateAtlasAtlasMultiAtlasEnergy(1);
}
else {
m_Computation.SetRecalculateAtlasAtlasMultiAtlasEnergy(0);
}
}
void AutoSegGUIControls::MultiAtlasAtlasRegistrationButtonChecked()
{
if (g_AtlasAtlasRegButton->value()){
m_Computation.SetMultiAtlasAtlasRegistration(1);
}
else{
m_Computation.SetMultiAtlasAtlasRegistration(0);
}
}
void AutoSegGUIControls::RecomputeButtonChecked()
{
if (g_RecomputeButton->value())
m_Computation.SetRecompute(1);
else
m_Computation.SetRecompute(0);
}
void AutoSegGUIControls::UseCondorButtonChecked()
{
m_Computation.SetUseCondor(g_UseCondorButton->value());
}
void AutoSegGUIControls::ShowDisplayButtonPressed()
{
m_Computation.ShowDisplay();
}
void AutoSegGUIControls::AtlasSpaceButtonChecked()
{
if (g_AtlasSpaceButton->value())
{
m_Computation.SetAtlasSpaceImage(1);
m_Computation.SetSkullStrippedImage(0);
m_Computation.SetBiasCorrectedImage(0);
}
else
m_Computation.SetAtlasSpaceImage(0);
}
void AutoSegGUIControls::BiasCorrectedButtonChecked()
{
if (g_BiasCorrectedButton->value())
{
m_Computation.SetBiasCorrectedImage(1);
m_Computation.SetSkullStrippedImage(0);
m_Computation.SetAtlasSpaceImage(0);
}
else
m_Computation.SetBiasCorrectedImage(0);
}
void AutoSegGUIControls::StrippedButtonChecked()
{
if (g_StrippedButton->value())
{
m_Computation.SetSkullStrippedImage(1);
m_Computation.SetBiasCorrectedImage(0);
m_Computation.SetAtlasSpaceImage(0);
}
else
m_Computation.SetSkullStrippedImage(0);
}
void AutoSegGUIControls::RigidTransformationButtonChecked()
{
if (g_RigidTransformationButton->value())
{
m_Computation.SetRigidTransformation(1);
m_Computation.SetAffineTransformation(0);
m_Computation.SetBsplineTransformation(0);
}
else
m_Computation.SetRigidTransformation(0);
}
void AutoSegGUIControls::AffineTransformationButtonChecked()
{
if (g_AffineTransformationButton->value())
{
m_Computation.SetAffineTransformation(1);
m_Computation.SetRigidTransformation(0);
m_Computation.SetBsplineTransformation(0);
}
else
m_Computation.SetAffineTransformation(0);
}
void AutoSegGUIControls::BsplineTransformationButtonChecked()
{
if (g_BsplineTransformationButton->value())
{
m_Computation.SetBsplineTransformation(1);
m_Computation.SetRigidTransformation(0);
m_Computation.SetAffineTransformation(0);
}
else
m_Computation.SetBsplineTransformation(0);
}
void AutoSegGUIControls::ShowMRMLSceneButtonPressed()
{
if (std::strlen(g_ProcessDataDirectoryDisp->value()) == 0)
fl_message("Please, set the process data directory...");
else
{
if (fl_choice("Do you want to run Slicer3 with the Mrml scene already loaded?", "No", "Yes", NULL))
{
std::string pathSlicer;
std::string pathSlicerString;
pathSlicerString= itksys::SystemTools::FindProgram("Slicer3");
//if path not found
if(pathSlicerString.empty()==true)
{
Fl_File_Chooser fc(".","*",Fl_File_Chooser::SINGLE,"Select the folder where Slicer3* is saved");
fc.show();
while(fc.shown())
Fl::wait();
if(fc.count())
pathSlicer=fc.value();
}
else
{
//if the Slicer found is in /Slicer/bin/
std::string key ("bin/Slicer3");
size_t found;
found=pathSlicerString.rfind(key);
if (found!=std::string::npos)
pathSlicerString.replace (found,key.length(),"Slicer3");
pathSlicer = pathSlicerString.c_str() ;
}
m_Computation.ExecuteSlicer3withScene(pathSlicer);
}
}
}
void AutoSegGUIControls::StopAutoSeg()
{
if (m_Computation.GetIsAutoSegInProcess())
m_Computation.StopBatchMake();
}
// Compute Automatic Segmentation
void AutoSegGUIControls::ComputeGUI()
{
int ComputeStudy = 1;
if (m_Computation.GetIsAutoSegInProcess())
fl_message("Automatic Segmentation already in process...");
else
{
UpdateParameters();
if (!CheckInputAutoSeg())
{
m_Computation.DesallocateDataList();
m_Computation.DesallocateAuxDataList();
InitializeData();
InitializeAuxData();
m_Computation.SetSubcorticalStructureSegmentation(m_IsSubcorticalStructureSegmentation);
m_Computation.SetGenericROISegmentation(m_IsGenericROISegmentation);
m_Computation.SetParcellationMapSegmentation(m_IsParcellationMapSegmentation);
m_Computation.SetMultiAtlasTargetFile(g_DataBrowser->text(2));
m_Computation.SetMultiModalitySingleSegmentation(g_MultiModalitySingleSegButton->value());
m_Computation.SetMultiModalityMultiSegmentation(g_MultiModalityMultiSegButton->value());
m_Computation.SetDataDirectory(g_DataDirectoryDisp->value());
m_Computation.SetProcessDataDirectory(g_ProcessDataDirectoryDisp->value());
m_Computation.SetWeightIntensityEnergy(g_IntensityEnergyWeight->value());
m_Computation.SetWeightHarmonicEnergy(g_HarmonicEnergyWeight->value());
m_Computation.SetWeightShapeEnergy(g_ShapeEnergyWeight->value());
m_Computation.SetANTSWithBrainmask(g_ANTSWithBrainmaskButton->value());
m_Computation.SetUseInitialAffine(g_UseInitialAffineButton->value());
m_Computation.SetNbANTSThreads((int)g_NumberOfThreads->value());
if (CheckStudy())
{
if (g_RecomputeButton->value())
{
ComputeStudy = fl_choice("A study already exists. Do you really want to recompute your dataset (and delete current results)?", "No", "Yes", NULL);
}
else
{
ComputeStudy = fl_choice("A study already exists. Do you really want to compute this study with this set of parameters?", "No", "Yes", NULL);
}
}
if (ComputeStudy)
{
m_Computation.SetIsAutoSegInProcess(true);
try
{
if( !m_Computation.Computation() )
{
while (m_Computation.GetIsAutoSegInProcess())
{
Fl::check();
}
std::cout << "Done!!" << std::endl;
}
else
{
std::vector< std::string > missingTools = m_Computation.GetMissingTools() ;
if( !missingTools.empty() )
{
std::string message = "Some tools required for computation were not found on the system:" ;
for( size_t i = 0 ; i < missingTools.size() ; i++ )
{
message += std::string( "\n" ) + missingTools[ i ] ;
}
fl_alert( "%s" , message.c_str() ) ;
}
}
}
catch(const std::exception& ex)
{
fl_alert( "%s" , ex.what() ) ;
}
catch(...)
{
fl_alert( "Error during computation. Check log files." ) ;
}
m_Computation.SetIsAutoSegInProcess(false);//Just in case there was an error during computation.
}
}
}
}
int AutoSegGUIControls::CheckStudy()
{
itksys::Glob glob;
std::vector<std::string> Studies;
std::string Expression = g_ProcessDataDirectoryDisp->value();
Expression.insert(Expression.size(),"/AutoSeg_Parameters.txt");
glob.FindFiles(Expression);
Studies = glob.GetFiles();
return Studies.size();
}
void AutoSegGUIControls::InitializeData()
{
int Line;
std::cout << "size of data: " << g_DataBrowser->size() << std::endl;
std::cout << "size of data: " << g_DataBrowser->text(2) << std::endl;
if (g_DataBrowser->size() >= 2)
{
m_Computation.SetNbData(g_DataBrowser->size()-1);
m_Computation.AllocateDataList();
for (Line = 2; Line <= g_DataBrowser->size(); Line++) {
m_Computation.SetDataList(g_DataBrowser->text(Line), Line-2,1);
}
}
}
void AutoSegGUIControls::InitializeAuxData()
{
int Line;
if (g_AuxDataBrowser->size() >= 2)
{
m_Computation.SetNbAuxData(g_AuxDataBrowser->size()-1);
m_Computation.AllocateAuxDataList();
m_Computation.SetAux1Label(g_Aux1LabelDisp->value());
m_Computation.SetAux2Label(g_Aux2LabelDisp->value());
m_Computation.SetAux3Label(g_Aux3LabelDisp->value());
m_Computation.SetAux4Label(g_Aux4LabelDisp->value());
m_Computation.SetAux5Label(g_Aux5LabelDisp->value());
m_Computation.SetAux6Label(g_Aux6LabelDisp->value());
m_Computation.SetAux7Label(g_Aux7LabelDisp->value());
m_Computation.SetAux8Label(g_Aux8LabelDisp->value());
for (Line = 2; Line <= g_AuxDataBrowser->size(); Line++)
m_Computation.SetAuxDataList(g_AuxDataBrowser->text(Line), Line-2);
}
}
void AutoSegGUIControls::SetSubcorticalStructures()
{
m_IsSubcorticalStructureSegmentation = 0;
if (g_AmygdalaLeftButton->value() == 1)
{
if (std::strlen(g_AmygdalaLeftDisp->value()) != 0)
{
m_Computation.SetAmygdalaLeft(g_AmygdalaLeftDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Amygdala Left...");
}
else
m_Computation.SetAmygdalaLeft("");
if (g_AmygdalaRightButton->value() == 1)
{
if (std::strlen(g_AmygdalaRightDisp->value()) != 0)
{
m_Computation.SetAmygdalaRight(g_AmygdalaRightDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Amygdala Right...");
}
else
m_Computation.SetAmygdalaRight("");
if (g_CaudateLeftButton->value() == 1)
{
if (std::strlen(g_CaudateLeftDisp->value()) != 0)
{
m_Computation.SetCaudateLeft(g_CaudateLeftDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Caudate Left...");
}
else
m_Computation.SetCaudateLeft("");
if (g_CaudateRightButton->value() == 1)
{
if (std::strlen(g_CaudateRightDisp->value()) != 0)
{
m_Computation.SetCaudateRight(g_CaudateRightDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Caudate Right...");
}
else
m_Computation.SetCaudateRight("");
if (g_HippocampusLeftButton->value() == 1)
{
if (std::strlen(g_HippocampusLeftDisp->value()) != 0)
{
m_Computation.SetHippocampusLeft(g_HippocampusLeftDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Hippocampus Left...");
}
else
m_Computation.SetHippocampusLeft("");
if (g_HippocampusRightButton->value() == 1)
{
if (std::strlen(g_HippocampusRightDisp->value()) != 0)
{
m_Computation.SetHippocampusRight(g_HippocampusRightDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Hippocampus Right...");
}
else
m_Computation.SetHippocampusRight("");
if (g_PallidusLeftButton->value() == 1)
{
if (std::strlen(g_PallidusLeftDisp->value()) != 0)
{
m_Computation.SetPallidusLeft(g_PallidusLeftDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Pallidus Left...");
}
else
m_Computation.SetPallidusLeft("");
if (g_PallidusRightButton->value() == 1)
{
if (std::strlen(g_PallidusRightDisp->value()) != 0)
{
m_Computation.SetPallidusRight(g_PallidusRightDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Pallidus Right...");
}
else
m_Computation.SetPallidusRight("");
if (g_PutamenLeftButton->value() == 1)
{
if (std::strlen(g_PutamenLeftDisp->value()) != 0)
{
m_Computation.SetPutamenLeft(g_PutamenLeftDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Putamen Left...");
}
else
m_Computation.SetPutamenLeft("");
if (g_PutamenRightButton->value() == 1)
{
if (std::strlen(g_PutamenRightDisp->value()) != 0)
{
m_Computation.SetPutamenRight(g_PutamenRightDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Putamen Right...");
}
else
m_Computation.SetPutamenRight("");
if (g_LateralVentricleLeftButton->value() == 1)
{
if (std::strlen(g_LateralVentricleLeftDisp->value()) != 0)
{
m_Computation.SetLateralVentricleLeft(g_LateralVentricleLeftDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Lateral Ventricle Left...");
}
else
m_Computation.SetLateralVentricleLeft("");
if (g_LateralVentricleRightButton->value() == 1)
{
if (std::strlen(g_LateralVentricleRightDisp->value()) != 0)
{
m_Computation.SetLateralVentricleRight(g_LateralVentricleRightDisp->value());
m_IsSubcorticalStructureSegmentation = 1;
}
else
fl_message("Please, set the Lateral Ventricle Right...");
}
else
m_Computation.SetLateralVentricleRight("");
}
void AutoSegGUIControls::SetGenericROIMaps()
{
m_IsGenericROISegmentation = 0;
if (g_ROIFile1Button->value() == 1)
{
if (std::strlen(g_ROIFile1Disp->value()) != 0)
{
m_Computation.SetROIFile1(g_ROIFile1Disp->value());
m_IsGenericROISegmentation = 1;
}
else
fl_message("Please, set the Generic ROI File 1...");
}
else
m_Computation.SetROIFile1("");
if (g_ROIFile2Button->value() == 1)
{
if (std::strlen(g_ROIFile2Disp->value()) != 0)
{
m_Computation.SetROIFile2(g_ROIFile2Disp->value());
m_IsGenericROISegmentation = 1;
}
else
fl_message("Please, set the Generic ROI File 2...");
}
else
m_Computation.SetROIFile2("");
if (g_ROIFile3Button->value() == 1)
{
if (std::strlen(g_ROIFile3Disp->value()) != 0)
{
m_Computation.SetROIFile3(g_ROIFile3Disp->value());
m_IsGenericROISegmentation = 1;
}
else
fl_message("Please, set the Generic ROI File 3...");
}
else
m_Computation.SetROIFile3("");
if (g_ROIFile4Button->value() == 1)
{
if (std::strlen(g_ROIFile4Disp->value()) != 0)
{
m_Computation.SetROIFile4(g_ROIFile4Disp->value());
m_IsGenericROISegmentation = 1;
}
else
fl_message("Please, set the Generic ROI File 4...");
}
else
m_Computation.SetROIFile4("");
if (g_ROIFile5Button->value() == 1)
{
if (std::strlen(g_ROIFile5Disp->value()) != 0)
{
m_Computation.SetROIFile5(g_ROIFile5Disp->value());
m_IsGenericROISegmentation = 1;
}
else
fl_message("Please, set the Generic ROI File 5...");
}
else
m_Computation.SetROIFile5("");
}
void AutoSegGUIControls::SetParcellationMap()
{
m_IsParcellationMapSegmentation = 0;
if (g_ParcellationFile1Button->value() == 1)
{
if (std::strlen(g_ParcellationFile1Disp->value()) != 0)
{
m_Computation.SetParcellationFile1(g_ParcellationFile1Disp->value());
m_IsParcellationMapSegmentation = 1;
}
else
fl_message("Please, set the Parcellation File 1...");
}
else
m_Computation.SetParcellationFile1("");
if (g_ParcellationFile2Button->value() == 1)
{
if (std::strlen(g_ParcellationFile2Disp->value()) != 0)
{
m_Computation.SetParcellationFile2(g_ParcellationFile2Disp->value());
m_IsParcellationMapSegmentation = 1;
}
else
fl_message("Please, set the Parcellation File 2...");
}
else
m_Computation.SetParcellationFile2("");
if (g_ParcellationFile3Button->value() == 1)
{
if (std::strlen(g_ParcellationFile3Disp->value()) != 0)
{
m_Computation.SetParcellationFile3(g_ParcellationFile3Disp->value());
m_IsParcellationMapSegmentation = 1;
}
else
fl_message("Please, set the Parcellation File 3...");
}
else
m_Computation.SetParcellationFile3("");
}
void AutoSegGUIControls::SetReorientationParameters()
{
if (g_ReorientationButton->value())
m_Computation.SetReorientation(1);
else
m_Computation.SetReorientation(0);
m_Computation.SetInputDataOrientation(g_InputDataOrientationDisp->value());
m_Computation.SetOutputDataOrientation(g_OutputDataOrientationDisp->value());
}
void AutoSegGUIControls::SetN4Parameters()
{
m_Computation.SetN4ITKBiasFieldCorrection(g_N4ITKBiasFieldCorrectionButton->value());
m_Computation.SetNbOfIterations (g_NbOfIterations->value());
m_Computation.SetBSplineGridResolutions (g_BSplineGridResolutions->value());
m_Computation.SetConvergenceThreshold((float)g_ConvergenceThreshold->value());
m_Computation.SetSplineDistance((int)g_SplineDistance->value());
m_Computation.SetShrinkFactor((int)g_ShrinkFactor->value());
m_Computation.SetBSplineOrder((int)g_BSplineOrder->value());
//m_Computation.SetBSplineAlpha((int)g_BSplineAlpha->value());
// m_Computation.SetBSplineBeta((float)g_BSplineBeta->value());
m_Computation.SetHistogramSharpening(g_HistogramSharpening->value());
m_Computation.SetStrippedN4ITKBiasFieldCorrection(g_StrippedN4ITKBiasFieldCorrectionButton->value());
}
void AutoSegGUIControls::SetNumberOfThreadsGUI()
{
m_Computation.SetNbANTSThreads((int)g_NumberOfThreads->value());
}
void AutoSegGUIControls::SetGridTemplateParameters()
{
if (g_GridTemplateAtlasButton->value())
m_Computation.SetROIAtlasGridTemplate(true);
else
{
m_Computation.SetROIAtlasGridTemplate(false);
m_Computation.SetGridTemplateSizeX((int)g_GridTemplateSizeX->value());
m_Computation.SetGridTemplateSizeY((int)g_GridTemplateSizeY->value());
m_Computation.SetGridTemplateSizeZ((int)g_GridTemplateSizeZ->value());
m_Computation.SetGridTemplateSpacingX((float)g_GridTemplateSpacingX->value());
m_Computation.SetGridTemplateSpacingY((float)g_GridTemplateSpacingY->value());
m_Computation.SetGridTemplateSpacingZ((float)g_GridTemplateSpacingZ->value());
}
}
void AutoSegGUIControls::SetIntensityRescalingMethod()
{
if (g_HistogramQuantileButton->value())
m_Computation.SetIntensityRescalingMethod(1);
else
m_Computation.SetIntensityRescalingMethod(2);
}
void AutoSegGUIControls::SetRegionalHistogramParameters()
{
m_Computation.SetQuantiles(g_QuantilesDisp->value());
m_Computation.SetPointSpacing(g_PointSpacingDisp->value());
}
//Check Input Automatic Segmentation Computation
bool AutoSegGUIControls::CheckInputAutoSeg()
{
bool Warning = false;
if (std::strlen(g_ProcessDataDirectoryDisp->value()) == 0)
{
fl_message("Please, set the process data directory (Step 1)...");
Warning = true;
}
else if (std::strlen(g_DataAutoSegDirectoryDisp->value()) == 0)
{
fl_message("Please, set the output directory for each data (Step 3)...");
Warning = true;
}
else if (g_DataBrowser->size() < 2)
{
fl_message("Please, set the data to be computed (Step 4)...");
Warning = true;
}
else if (std::strlen(g_CommonCoordinateImageDisp->value()) == 0)
{
fl_message("Please, set the common coordinate image...");
Warning = true;
}
else if (std::strlen(g_TissueSegmentationAtlasDirectoryDisp->value()) == 0)
{
fl_message("Please, set the tissue segmentation...");
Warning = true;
}
else if (std::strlen(g_ROIAtlasFileDisp->value()) == 0 && g_SingleAtlasSegButton->value())
{
fl_message("Please, set the ROI atlas file...");
Warning = true;
}
else if ( (m_IsSubcorticalStructureSegmentation == 0) && (m_IsGenericROISegmentation == 0) && (m_IsParcellationMapSegmentation == 0) && g_SingleAtlasSegButton->value())
{
fl_message("Please, set a ROI or Parcellation file for the single Atlas segmentation ...");
Warning = true;
}
else if ( (g_ReorientationButton->value() == 1) && ( std::strlen(g_InputDataOrientationDisp->value()) != 3 || std::strlen(g_OutputDataOrientationDisp->value()) != 3))
{
fl_message("Please, set input and output data orientations (e.g RAI)...");
Warning = true;
}
else if ( (g_GridTemplateManualButton->value() == 1) && ( (g_GridTemplateSizeX->value() == 0)||(g_GridTemplateSizeY->value() == 0)||(g_GridTemplateSizeZ->value() == 0)||(g_GridTemplateSpacingX->value() == 0)||(g_GridTemplateSpacingY->value() == 0)||(g_GridTemplateSpacingZ->value() == 0)) )
{
fl_message("Please, set GridTemplate parameters with values different than 0...");
Warning = true;
}
else if (g_Aux1Button->value() != 0)
{
if ((g_AtlasSpaceButton->value() == 0) && (g_StrippedButton->value() == 0) && (g_BiasCorrectedButton->value() == 0))
{
fl_message("Please, set the process step of the source data...");
Warning = true;
}
else if ((g_RigidTransformationButton->value() == 0) && (g_AffineTransformationButton->value() == 0) && (g_BsplineTransformationButton->value() == 0))
{
fl_message("Please, set the transformation...");
Warning = true;
}
else if ((g_Aux1Button->value() != 0) && (std::strlen(g_Aux1LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliary 1 directory name...");
Warning = true;
}
else if ((g_Aux2Button->value() != 0) && (std::strlen(g_Aux2LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliary 2 directory name...");
Warning = true;
}
else if ((g_Aux3Button->value() != 0) && (std::strlen(g_Aux3LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliary 3 directory name...");
Warning = true;
}
else if ((g_Aux4Button->value() != 0) && (std::strlen(g_Aux4LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliary 4 directory name...");
Warning = true;
}
else if ((g_Aux5Button->value() != 0) && (std::strlen(g_Aux5LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliary 5 directory name...");
Warning = true;
}
else if ((g_Aux6Button->value() != 0) && (std::strlen(g_Aux6LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliaiy 6 directory name...");
Warning = true;
}
else if ((g_Aux7Button->value() != 0) && (std::strlen(g_Aux7LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliary 7 directory name...");
Warning = true;
}
else if ((g_Aux8Button->value() != 0) && (std::strlen(g_Aux8LabelDisp->value()) == 0))
{
fl_message("Please, set the auxiliary 8 directory name...");
Warning = true;
}
else if (g_AuxDataBrowser->size() < 2)
{
fl_message("Please, set the auxiliary data to be computed...");
Warning = true;
}
}
return Warning;
}
void AutoSegGUIControls::ABCButtonToggled()
{
g_ABCButton->set();
g_NeosegButton->clear();
g_BSplineAtlasWarpGroup->deactivate();
g_FluidAtlasWarpGroup->activate();
g_NeosegParamGroup->deactivate();
// AdvancedParameters
g_FilterMethodChoice->activate();
g_FilterMethodChoice->value(1);
g_FilterIterations->value(10);
g_FilterTimeStep->value(0.01);
g_MaxBiasDegree->value(4);
g_InitialDistributionEstimatorChoice->activate();
g_InitialDistributionEstimatorChoice->value(1);
g_Prior1->value(1.3);
g_Prior2->value(1.0);
g_Prior3->value(0.7);
g_Prior4->value(1.0);
g_Prior5->value(1.0);
g_Prior6->value(1.0);
g_Prior7->value(1.0);
g_Prior8->value(1.0);
g_Prior9->value(1.0);
g_FluidAtlasWarpButton->set();
g_FluidAtlasAffineButton->clear();
g_FluidAtlasFATWButton->clear();
g_FluidAtlasWarpGroup->activate();
g_FluidAtlasWarpIterations->value(50);
g_FluidAtlasWarpMaxStep->value(0.1);
g_AtlasLinearMappingChoice->value(0);
g_ImageLinearMappingChoice->value(0);
m_Computation.SetEMSoftware("ABC");
m_Computation.SetFilterIterations((int)g_FilterIterations->value());
m_Computation.SetFilterTimeStep((float)g_FilterTimeStep->value());
m_Computation.SetFilterMethod("Curvature flow");
m_Computation.SetMaxBiasDegree((int)g_MaxBiasDegree->value());
m_Computation.SetInitialDistributionEstimator("robust");
m_Computation.SetPrior1((float)g_Prior1->value());
m_Computation.SetPrior2((float)g_Prior2->value());
m_Computation.SetPrior3((float)g_Prior3->value());
m_Computation.SetPrior4((float)g_Prior4->value());
m_Computation.SetPrior5((float)g_Prior5->value());
m_Computation.SetPrior6((float)g_Prior6->value());
m_Computation.SetPrior7((float)g_Prior7->value());
m_Computation.SetPrior8((float)g_Prior8->value());
m_Computation.SetPrior9((float)g_Prior9->value());
m_Computation.SetFluidAtlasWarp(1);
m_Computation.SetFluidAtlasAffine(0);
m_Computation.SetFluidAtlasFATW(0);
m_Computation.SetANTSAtlasABC(0);
m_Computation.SetFluidAtlasWarpIterations((int)g_FluidAtlasWarpIterations->value());
m_Computation.SetFluidAtlasWarpMaxStep((float)g_FluidAtlasWarpMaxStep->value());
m_Computation.SetAtlasLinearMapping("affine");
m_Computation.SetImageLinearMapping("id");
}
void AutoSegGUIControls::NeosegButtonToggled()
{
g_NeosegButton->set();
g_ABCButton->clear();
g_BSplineAtlasWarpGroup->activate();
g_FluidAtlasWarpGroup->deactivate();
g_NeosegParamGroup->activate();
// AdvancedParameters
g_FilterMethodChoice->activate();
g_FilterMethodChoice->value(1);
g_FilterIterations->value(10);
g_FilterTimeStep->value(0.01);
g_MaxBiasDegree->value(4);
g_InitialDistributionEstimatorChoice->deactivate();
g_InitialDistributionEstimatorChoice->value(0);
g_Prior1->value(0.2);
g_Prior2->value(1.4);
g_Prior3->value(1.0);
g_Prior4->value(0.5);
g_Prior5->value(1.0);
g_Prior6->value(1.0);
g_Prior7->value(1.0);
g_Prior8->value(1.0);
g_Prior9->value(1.0);
g_BSplineAtlasWarpButton->set();
g_BSplineAtlasWarpGridX->value(5.0);
g_BSplineAtlasWarpGridY->value(5.0);
g_BSplineAtlasWarpGridZ->value(5.0);
g_AtlasLinearMappingChoice->value(0);
g_ImageLinearMappingChoice->value(0);
g_NeosegPriorThreshold->value(0.8);
g_NeosegParzenKernel->value(0.05);
g_NeosegMahalanobisThreshold->value(2.0);
m_Computation.SetEMSoftware("neoseg");
m_Computation.SetFilterIterations((int)g_FilterIterations->value());
m_Computation.SetFilterTimeStep((float)g_FilterTimeStep->value());
m_Computation.SetFilterMethod("Curvature flow");
m_Computation.SetMaxBiasDegree((int)g_MaxBiasDegree->value());
m_Computation.SetInitialDistributionEstimator("robust");
m_Computation.SetPrior1((float)g_Prior1->value());
m_Computation.SetPrior2((float)g_Prior2->value());
m_Computation.SetPrior3((float)g_Prior3->value());
m_Computation.SetPrior4((float)g_Prior4->value());
m_Computation.SetPrior5((float)g_Prior5->value());
m_Computation.SetPrior6((float)g_Prior6->value());
m_Computation.SetPrior7((float)g_Prior7->value());
m_Computation.SetPrior8((float)g_Prior8->value());
m_Computation.SetPrior9((float)g_Prior9->value());
m_Computation.SetBSplineAtlasWarp(1);
m_Computation.SetBSplineAtlasWarpGridX((float)g_BSplineAtlasWarpGridX->value());
m_Computation.SetBSplineAtlasWarpGridY((float)g_BSplineAtlasWarpGridY->value());
m_Computation.SetBSplineAtlasWarpGridZ((float)g_BSplineAtlasWarpGridZ->value());
m_Computation.SetAtlasLinearMapping("affine");
m_Computation.SetImageLinearMapping("id");
m_Computation.SetNeosegPriorThreshold((float)g_NeosegPriorThreshold->value());
m_Computation.SetNeosegParzenKernel((float)g_NeosegParzenKernel->value());
m_Computation.SetNeosegMahalanobisThreshold((float)g_NeosegMahalanobisThreshold->value());
}
void AutoSegGUIControls::LoopButtonChecked()
{
if (g_LoopButton->value())
{
g_AtlasLoopGroup->activate();
g_LoopIteration->activate();
g_FluidAtlasFATWButton->activate();
m_Computation.SetLoop(1);
}
else
{
g_AtlasLoopGroup->deactivate();
g_LoopIteration->deactivate();
g_FluidAtlasFATWButton->deactivate();
m_Computation.SetLoop(0);
}
}
void AutoSegGUIControls::SetLoopIterationGUI()
{
m_Computation.SetLoopIteration((int)g_LoopIteration->value());
}
void AutoSegGUIControls::SetFilterIterationsGUI()
{
m_Computation.SetFilterIterations((int)g_FilterIterations->value());
}
void AutoSegGUIControls::SetFilterTimeStepGUI()
{
m_Computation.SetFilterTimeStep((float)g_FilterTimeStep->value());
}
void AutoSegGUIControls::SetFilterMethodChoiceGUI()
{
if (g_FilterMethodChoice->value() == 1)
m_Computation.SetFilterMethod("Curvature flow");
else
m_Computation.SetFilterMethod("Grad aniso diffusion");
}
void AutoSegGUIControls::SetInitialDistributionEstimatorChoiceGUI()
{
if (g_InitialDistributionEstimatorChoice->value() == 0)
m_Computation.SetInitialDistributionEstimator("standard");
else
m_Computation.SetInitialDistributionEstimator("robust");
}
void AutoSegGUIControls::SetMaxBiasDegreeGUI()
{
m_Computation.SetMaxBiasDegree((int)g_MaxBiasDegree->value());
}
void AutoSegGUIControls::SetPrior1GUI()
{
m_Computation.SetPrior1((float)g_Prior1->value());
}
void AutoSegGUIControls::SetPrior2GUI()
{
m_Computation.SetPrior2((float)g_Prior2->value());
}
void AutoSegGUIControls::SetPrior3GUI()
{
m_Computation.SetPrior3((float)g_Prior3->value());
}
void AutoSegGUIControls::SetPrior4GUI()
{
m_Computation.SetPrior4((float)g_Prior4->value());
}
void AutoSegGUIControls::SetPrior5GUI()
{
m_Computation.SetPrior5((float)g_Prior5->value());
}
void AutoSegGUIControls::SetPrior6GUI()
{
m_Computation.SetPrior6((float)g_Prior6->value());
}
void AutoSegGUIControls::SetPrior7GUI()
{
m_Computation.SetPrior7((float)g_Prior7->value());
}
void AutoSegGUIControls::SetPrior8GUI()
{
m_Computation.SetPrior8((float)g_Prior8->value());
}
void AutoSegGUIControls::SetPrior9GUI()
{
m_Computation.SetPrior9((float)g_Prior9->value());
}
void AutoSegGUIControls::BSplineAtlasWarpButtonChecked()
{
if (g_BSplineAtlasWarpButton->value())
m_Computation.SetBSplineAtlasWarp(1);
else
m_Computation.SetBSplineAtlasWarp(0);
}
void AutoSegGUIControls::SetBSplineAtlasWarpGridXGUI()
{
m_Computation.SetBSplineAtlasWarpGridX((float)g_BSplineAtlasWarpGridX->value());
}
void AutoSegGUIControls::SetBSplineAtlasWarpGridYGUI()
{
m_Computation.SetBSplineAtlasWarpGridY((float)g_BSplineAtlasWarpGridY->value());
}
void AutoSegGUIControls::SetBSplineAtlasWarpGridZGUI()
{
m_Computation.SetBSplineAtlasWarpGridZ((float)g_BSplineAtlasWarpGridZ->value());
}
void AutoSegGUIControls::FluidAtlasWarpButtonChecked()
{
g_FluidAtlasWarpButton->set();
g_FluidAtlasAffineButton->clear();
g_FluidAtlasFATWButton->clear();
g_ABCANTSWarpButton->clear();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
void AutoSegGUIControls::ABCANTSWarpButtonChecked()
{
g_FluidAtlasWarpButton->clear();
g_FluidAtlasAffineButton->clear();
g_FluidAtlasFATWButton->clear();
g_ABCANTSWarpButton->set();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
void AutoSegGUIControls::FluidAtlasAffineButtonChecked()
{
g_FluidAtlasWarpButton->clear();
g_FluidAtlasAffineButton->set();
g_FluidAtlasFATWButton->clear();
g_ABCANTSWarpButton->clear();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
void AutoSegGUIControls::FluidAtlasFATWButtonChecked()
{
g_FluidAtlasWarpButton->clear();
g_FluidAtlasAffineButton->clear();
g_FluidAtlasFATWButton->set();
g_ABCANTSWarpButton->clear();
m_Computation.SetFluidAtlasWarp(g_FluidAtlasWarpButton->value());
m_Computation.SetFluidAtlasAffine(g_FluidAtlasAffineButton->value());
m_Computation.SetFluidAtlasFATW(g_FluidAtlasFATWButton->value());
m_Computation.SetANTSAtlasABC(g_ABCANTSWarpButton->value());
}
void AutoSegGUIControls::SetFluidAtlasWarpIterationsGUI()
{
m_Computation.SetFluidAtlasWarpIterations((int)g_FluidAtlasWarpIterations->value());
}
void AutoSegGUIControls::SetFluidAtlasWarpMaxStepGUI()
{
m_Computation.SetFluidAtlasWarpMaxStep((float)g_FluidAtlasWarpMaxStep->value());
}
void AutoSegGUIControls::SetAtlasLinearMappingChoiceGUI()
{
if (g_AtlasLinearMappingChoice->value() == 0)
m_Computation.SetAtlasLinearMapping("affine");
else if(g_AtlasLinearMappingChoice->value() == 1)
m_Computation.SetAtlasLinearMapping("id");
else
m_Computation.SetAtlasLinearMapping("rigid");
}
void AutoSegGUIControls::SetNeosegPriorThresholdGUI()
{
m_Computation.SetNeosegPriorThreshold((float)g_NeosegPriorThreshold->value());
}
void AutoSegGUIControls::SetNeosegParzenKernelGUI()
{
m_Computation.SetNeosegParzenKernel((float)g_NeosegParzenKernel->value());
}
void AutoSegGUIControls::SetNeosegMahalanobisThresholdGUI()
{
m_Computation.SetNeosegMahalanobisThreshold((float)g_NeosegMahalanobisThreshold->value());
}
void AutoSegGUIControls::SetImageLinearMappingChoiceGUI()
{
if (g_ImageLinearMappingChoice->value() == 0)
m_Computation.SetImageLinearMapping("id");
else if(g_ImageLinearMappingChoice->value() == 1)
m_Computation.SetImageLinearMapping("rigid");
else
m_Computation.SetImageLinearMapping("affine");
}
void AutoSegGUIControls::RigidRegistrationButtonChecked()
{
if (g_RigidRegistrationButton->value())
{
g_RegridingRegistrationGroup->activate();
g_RegistrationInitializationGroup->activate();
m_Computation.SetRigidRegistration(1);
}
else
{
g_RegridingRegistrationGroup->deactivate();
g_RegistrationInitializationGroup->deactivate();
m_Computation.SetRigidRegistration(0);
}
}
void AutoSegGUIControls::GridTemplateAtlasButtonToggled()
{
g_GridTemplateAtlasButton->set();
g_GridTemplateManualButton->clear();
g_GridParametersGroup->deactivate();
}
void AutoSegGUIControls::GridTemplateManualButtonToggled()
{
g_GridTemplateManualButton->set();
g_GridTemplateAtlasButton->clear();
g_GridParametersGroup->activate();
}
void AutoSegGUIControls::InitRegCenterOfHeadButtonToggled()
{
g_InitRegCenterOfHeadButton->set();
g_InitRegMomentsButton->clear();
g_InitRegGeometryButton->clear();
g_InitRegOffButton->clear();
m_Computation.SetRegistrationInitialization("useCenterOfHeadAlign");
}
void AutoSegGUIControls::InitRegMomentsButtonToggled()
{
g_InitRegCenterOfHeadButton->clear();
g_InitRegMomentsButton->set();
g_InitRegGeometryButton->clear();
g_InitRegOffButton->clear();
m_Computation.SetRegistrationInitialization("useMomentsAlign");
}
void AutoSegGUIControls::InitRegGeometryButtonToggled()
{
g_InitRegCenterOfHeadButton->clear();
g_InitRegMomentsButton->clear();
g_InitRegGeometryButton->set();
g_InitRegOffButton->clear();
m_Computation.SetRegistrationInitialization("useGeometryAlign");
}
void AutoSegGUIControls::InitRegOffButtonToggled()
{
g_InitRegCenterOfHeadButton->clear();
g_InitRegMomentsButton->clear();
g_InitRegGeometryButton->clear();
g_InitRegOffButton->set();
m_Computation.SetRegistrationInitialization("Off");
}
void AutoSegGUIControls::InitRegUseT1InitTransformButtonChecked()
{
if (g_InitRegUseT1InitTransformButton->value())
m_Computation.SetInitRegUseT1InitTransform(1);
else
m_Computation.SetInitRegUseT1InitTransform(0);
}
void AutoSegGUIControls::ClassicWarpingButtonToggled()
{
g_ClassicWarpingButton->set();
g_CoarseToFineWarpingButton->clear();
g_BRAINSDemonWarpButton->clear();
g_ANTSWarpingButton->clear();
g_ANTSWarpingGroup->hide();
g_BRAINSDemonWarpGroup->hide();
g_FluidWarpingGroup->show();
g_NumBasis->value(0.01);
g_NumBasis->activate();
g_Scale4NbIterations->deactivate();
g_Scale2NbIterations->deactivate();
g_Scale1NbIterations->value(100);
m_Computation.SetANTSWarpingMethod(0);
m_Computation.SetClassicWarpingMethod(1);
m_Computation.SetCoarseToFineWarpingMethod(0);
m_Computation.SetBRAINSDemonWarpMethod(0);
m_Computation.SetNumBasis((float)g_NumBasis->value());
m_Computation.SetScale1NbIterations((int)g_Scale1NbIterations->value());
}
void AutoSegGUIControls::CoarseToFineWarpingButtonToggled()
{
g_ClassicWarpingButton->clear();
g_CoarseToFineWarpingButton->set();
g_BRAINSDemonWarpButton->clear();
g_ANTSWarpingButton->clear();
g_ANTSWarpingGroup->hide();
g_BRAINSDemonWarpGroup->hide();
g_FluidWarpingGroup->show();
g_NumBasis->value(2000);
g_NumBasis->deactivate();
g_Scale4NbIterations->activate();
g_Scale2NbIterations->activate();
g_Scale4NbIterations->value(50);
g_Scale2NbIterations->value(25);
g_Scale1NbIterations->value(100);
m_Computation.SetANTSWarpingMethod(0);
m_Computation.SetClassicWarpingMethod(0);
m_Computation.SetCoarseToFineWarpingMethod(1);
m_Computation.SetBRAINSDemonWarpMethod(0);
m_Computation.SetNumBasis((float)g_NumBasis->value());
m_Computation.SetScale4NbIterations((int)g_Scale4NbIterations->value());
m_Computation.SetScale2NbIterations((int)g_Scale2NbIterations->value());
m_Computation.SetScale1NbIterations((int)g_Scale1NbIterations->value());
}
void AutoSegGUIControls::BRAINSDemonWarpButtonToggled()
{
g_ClassicWarpingButton->clear();
g_CoarseToFineWarpingButton->clear();
g_BRAINSDemonWarpButton->set();
g_ANTSWarpingButton->clear();
g_ANTSWarpingGroup->hide();
g_BRAINSDemonWarpGroup->show();
g_FluidWarpingGroup->hide();
m_Computation.SetANTSWarpingMethod(0);
m_Computation.SetBRAINSDemonWarpMethod(1);
m_Computation.SetClassicWarpingMethod(0);
m_Computation.SetCoarseToFineWarpingMethod(0);
}
void AutoSegGUIControls::ANTSWarpingButtonToggled()
{
g_ClassicWarpingButton->clear();
g_CoarseToFineWarpingButton->clear();
g_BRAINSDemonWarpButton->clear();
g_ANTSWarpingButton->set();
g_ANTSWarpingGroup->show();
g_BRAINSDemonWarpGroup->hide();
g_FluidWarpingGroup->hide();
m_Computation.SetANTSWarpingMethod(1);
m_Computation.SetBRAINSDemonWarpMethod(0);
m_Computation.SetClassicWarpingMethod(0);
m_Computation.SetCoarseToFineWarpingMethod(0);
}
void AutoSegGUIControls::SetAlphaGUI()
{
m_Computation.SetAlpha((float)g_Alpha->value());
}
void AutoSegGUIControls::SetBetaGUI()
{
m_Computation.SetBeta((float)g_Beta->value());
}
void AutoSegGUIControls::SetGammaGUI()
{
m_Computation.SetGamma((float)g_Gamma->value());
}
void AutoSegGUIControls::SetMaxPerturbationGUI()
{
m_Computation.SetMaxPerturbation((float)g_MaxPerturbation->value());
}
void AutoSegGUIControls::SetScale4NbIterationsGUI()
{
m_Computation.SetScale4NbIterations((int)g_Scale4NbIterations->value());
}
void AutoSegGUIControls::SetScale2NbIterationsGUI()
{
m_Computation.SetScale2NbIterations((int)g_Scale2NbIterations->value());
}
void AutoSegGUIControls::SetScale1NbIterationsGUI()
{
m_Computation.SetScale1NbIterations((int)g_Scale1NbIterations->value());
}
void AutoSegGUIControls::SetNumBasisGUI()
{
m_Computation.SetNumBasis((float)g_NumBasis->value());
}
void AutoSegGUIControls::SetPyramidLevelsGUI()
{
m_Computation.SetPyramidLevels((int)g_PyramidLevels->value());
}
void AutoSegGUIControls::SetMovingShrinkFactorsGUI()
{
m_Computation.SetMovingShrinkFactors((const char *)g_MovingShrinkFactors->value());
}
void AutoSegGUIControls::SetFixedShrinkFactorsGUI()
{
m_Computation.SetFixedShrinkFactors((const char *)g_FixedShrinkFactors->value());
}
void AutoSegGUIControls::SetIterationCountPyramidLevelsGUI()
{
m_Computation.SetIterationCountPyramidLevels((const char *)g_IterationCountPyramidLevels->value());
}
void AutoSegGUIControls::SetDeformationFieldSmoothingSigmaGUI()
{
m_Computation.SetDeformationFieldSmoothingSigma((float)g_DeformationFieldSmoothingSigma->value());
}
void AutoSegGUIControls::SetRegistrationFilterTypeGUI()
{
if(g_RegistrationFilterType->value()==0)
m_Computation.SetRegistrationFilterType("Demons");
if(g_RegistrationFilterType->value()==1)
m_Computation.SetRegistrationFilterType("FastSymmetricForces");
if(g_RegistrationFilterType->value()==2)
m_Computation.SetRegistrationFilterType("Diffeomorphic");
if(g_RegistrationFilterType->value()==3)
m_Computation.SetRegistrationFilterType("LogDemons");
if(g_RegistrationFilterType->value()==4)
m_Computation.SetRegistrationFilterType("SymmetricLogDemons");
}
void AutoSegGUIControls::SetANTSIterationsGUI()
{
m_Computation.SetANTSIterations(g_ANTSIterations->value());
}
void AutoSegGUIControls::SetANTSCCWeightGUI()
{
m_Computation.SetANTSCCWeight(g_ANTSCCWeight->value());
}
void AutoSegGUIControls::SetANTSCCRegionRadiusGUI()
{
m_Computation.SetANTSCCRegionRadius(g_ANTSCCRegionRadius->value());
}
void AutoSegGUIControls::SetANTSMIWeightGUI()
{
m_Computation.SetANTSMIWeight(g_ANTSMIWeight->value());
}
void AutoSegGUIControls::SetANTSMIBinsGUI()
{
m_Computation.SetANTSMIBins(g_ANTSMIBins->value());
}
void AutoSegGUIControls::SetANTSMSQWeightGUI()
{
m_Computation.SetANTSMSQWeight(g_ANTSMSQWeight->value());
}
//for 2nd modality
void AutoSegGUIControls::SetANTSCCWeightGUI2nd()
{
m_Computation.SetANTSCCWeight2nd(g_ANTSCCWeight2nd->value());
}
void AutoSegGUIControls::SetANTSCCRegionRadiusGUI2nd()
{
m_Computation.SetANTSCCRegionRadius2nd(g_ANTSCCRegionRadius2nd->value());
}
void AutoSegGUIControls::SetANTSMIWeightGUI2nd()
{
m_Computation.SetANTSMIWeight2nd(g_ANTSMIWeight2nd->value());
}
void AutoSegGUIControls::SetANTSMIBinsGUI2nd()
{
m_Computation.SetANTSMIBins2nd(g_ANTSMIBins2nd->value());
}
void AutoSegGUIControls::SetANTSMSQWeightGUI2nd()
{
m_Computation.SetANTSMSQWeight2nd(g_ANTSMSQWeight2nd->value());
}
void AutoSegGUIControls::SetANTSRegistrationFilterTypeGUI()
{
if(g_ANTSRegistrationFilterType->value()==0)
{
g_ANTSTransformationStep->value("0.25");
m_Computation.SetANTSTransformationStep(g_ANTSTransformationStep->value());
m_Computation.SetANTSRegistrationFilterType("GreedyDiffeomorphism");
}
if(g_ANTSRegistrationFilterType->value()==1)
{
g_ANTSTransformationStep->value("0.25,5,0.01");
m_Computation.SetANTSTransformationStep(g_ANTSTransformationStep->value());
m_Computation.SetANTSRegistrationFilterType("SpatiotemporalDiffeomorphism");
}
if(g_ANTSRegistrationFilterType->value()==2)
{
g_ANTSTransformationStep->value("1");
m_Computation.SetANTSTransformationStep(g_ANTSTransformationStep->value());
m_Computation.SetANTSRegistrationFilterType("Elastic");
}
if(g_ANTSRegistrationFilterType->value()==3)
{
g_ANTSTransformationStep->value("0.5,10");
m_Computation.SetANTSTransformationStep(g_ANTSTransformationStep->value());
m_Computation.SetANTSRegistrationFilterType("Exponential");
}
}
void AutoSegGUIControls::SetANTSTransformationStepGUI()
{
m_Computation.SetANTSTransformationStep(g_ANTSTransformationStep->value());
}
void AutoSegGUIControls::ANTSGaussianSmoothingButtonChecked()
{
if (g_ANTSGaussianSmoothingButton->value())
m_Computation.SetANTSGaussianSmoothing(1);
else
m_Computation.SetANTSGaussianSmoothing(0);
}
void AutoSegGUIControls::SetANTSGaussianSigmaGUI()
{
m_Computation.SetANTSGaussianSigma(g_ANTSGaussianSigma->value());
}
void AutoSegGUIControls::UseDefaultEMSAdvancedParametersGUI()
{
try
{
m_Computation.LoadParameterFile(GetDefaultParameterFile(),tissueSeg);
}
catch(...)
{
//do nothing
}
UpdateParameterGUI(GetDefaultParameterFile(),tissueSeg);
}
void AutoSegGUIControls::UseDefaultWarpingAdvancedParametersGUI()
{
try
{
m_Computation.LoadParameterFile(GetDefaultParameterFile(),warping);
}
catch(...)
{
//do nothing
}
UpdateParameterGUI(GetDefaultParameterFile(),warping);
}
void AutoSegGUIControls::UseDefaultN4AdvancedParametersGUI()
{
try
{
m_Computation.LoadParameterFile(GetDefaultParameterFile(),N4biasFieldCorrection);
}
catch(...)
{
//do nothing
}
UpdateParameterGUI(GetDefaultParameterFile(),N4biasFieldCorrection);
}
void AutoSegGUIControls::N4ITKBiasFieldCorrectionButtonChecked()
{
if (g_N4ITKBiasFieldCorrectionButton->value())
{
g_N4ParametersGroup->activate();
g_N4AdvancedParametersGroup->activate();
g_StrippedN4ITKBiasFieldCorrectionButton->activate();
m_Computation.SetN4ITKBiasFieldCorrection(1);
}
else
{
g_N4ParametersGroup->deactivate();
g_N4AdvancedParametersGroup->deactivate();
g_StrippedN4ITKBiasFieldCorrectionButton->deactivate();
g_StrippedN4ITKBiasFieldCorrectionButton->clear();
m_Computation.SetN4ITKBiasFieldCorrection(0);
}
}
void AutoSegGUIControls::StrippedN4ITKBiasFieldCorrectionButtonChecked()
{
if (g_StrippedN4ITKBiasFieldCorrectionButton->value())
m_Computation.SetStrippedN4ITKBiasFieldCorrection(1);
else
m_Computation.SetStrippedN4ITKBiasFieldCorrection(0);
}
void AutoSegGUIControls::ReorientationButtonChecked()
{
if (g_ReorientationButton->value())
{
g_InputDataOrientationDisp->activate();
g_OutputDataOrientationDisp->activate();
m_Computation.SetReorientation(1);
m_Computation.SetInputDataOrientation(g_InputDataOrientationDisp->value());
m_Computation.SetOutputDataOrientation(g_OutputDataOrientationDisp->value());
}
else
{
m_Computation.SetReorientation(0);
g_InputDataOrientationDisp->deactivate();
g_OutputDataOrientationDisp->deactivate();
}
}
void AutoSegGUIControls::SetNbOfIterationsGUI()
{
m_Computation.SetNbOfIterations((const char *)g_NbOfIterations->value());
}
void AutoSegGUIControls::SetBSplineGridResolutionsGUI()
{
m_Computation.SetBSplineGridResolutions((const char *)g_BSplineGridResolutions->value());
}
void AutoSegGUIControls::SetConvergenceThresholdGUI()
{
m_Computation.SetConvergenceThreshold((float)g_ConvergenceThreshold->value());
}
void AutoSegGUIControls::SetSplineDistanceGUI()
{
m_Computation.SetSplineDistance((float)g_SplineDistance->value());
}
void AutoSegGUIControls::SetShrinkFactorGUI()
{
m_Computation.SetShrinkFactor((int)g_ShrinkFactor->value());
}
void AutoSegGUIControls::SetBSplineOrderGUI()
{
m_Computation.SetBSplineOrder((int)g_BSplineOrder->value());
}
void AutoSegGUIControls::SetBSplineAlphaGUI()
{
//m_Computation.SetBSplineAlpha((float)g_BSplineAlpha->value());
}
void AutoSegGUIControls::SetBSplineBetaGUI()
{
//m_Computation.SetBSplineBeta((float)g_BSplineBeta->value());
}
void AutoSegGUIControls::SetHistogramSharpeningGUI()
{
m_Computation.SetHistogramSharpening((const char *)g_HistogramSharpening->value());
}
void AutoSegGUIControls::DeleteVesselsButtonChecked()
{
if (g_DeleteVesselsButton->value())
m_Computation.SetDeleteVessels(1);
else
m_Computation.SetDeleteVessels(0);
}
void AutoSegGUIControls::HistogramQuantileButtonToggled()
{
g_HistogramQuantileButton->set();
g_TissueMeanMatchButton->clear();
}
void AutoSegGUIControls::TissueMeanMatchButtonToggled()
{
g_TissueMeanMatchButton->set();
g_HistogramQuantileButton->clear();
}
void AutoSegGUIControls::SetPointSpacingGUI()
{
m_Computation.SetPointSpacing((int)g_PointSpacingDisp->value());
}
// Initialize Parameters
// _TissueAtlas = 0 (default) -> Sharp Atlas
// _TissueAtlas = 1 -> Fuzzy Atlas
void AutoSegGUIControls::InitializeParameters()
{
// Atlases Parameters
g_TissueSegmentationAtlasDirectoryDisp->value("/tools/atlas/BrainsegAtlas/adult-atlas-asym-T1-RAI/");
g_TissueSegmentationAtlasT1Button->set();
g_TissueSegmentationAtlasT2Button->clear();
m_Computation.SetTissueSegmentationAtlasDirectory(g_TissueSegmentationAtlasDirectoryDisp->value());
m_Computation.SetTissueSegmentationAtlasType("T1");
g_CommonCoordinateImageDisp->value("/tools/atlas/BrainsegAtlas/adult-atlas-asym-T1-RAI/template.nrrd");
g_CommonCoordinateImageT1Button->set();
g_CommonCoordinateImageT2Button->clear();
m_Computation.SetCommonCoordinateImage(g_CommonCoordinateImageDisp->value());
m_Computation.SetCommonCoordinateImageType("T1");
g_ROIAtlasFileDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/template.nrrd");
m_Computation.SetROIAtlasFile(g_ROIAtlasFileDisp->value());
// Probabilistic Subcortical Structures Parameters
g_AllStructuresButton->set();
AllStructuresButtonChecked();
g_AmygdalaLeftDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/amygdalaLeft.nrrd");
g_AmygdalaRightDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/amygdalaRight.nrrd");
g_CaudateLeftDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/caudateLeft.nrrd");
g_CaudateRightDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/caudateRight.nrrd");
g_HippocampusLeftDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/hippocampusLeft.nrrd");
g_HippocampusRightDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/hippocampusRight.nrrd");
g_PallidusLeftDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/pallidusLeft.nrrd");
g_PallidusRightDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/pallidusRight.nrrd");
g_PutamenLeftDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/putamenLeft.nrrd");
g_PutamenRightDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/putamenRight.nrrd");
g_LateralVentricleLeftDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/latVentricleLeftMask.nrrd");
g_LateralVentricleRightDisp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/latVentricleRightMask.nrrd");
m_Computation.SetAmygdalaLeft(g_AmygdalaLeftDisp->value());
m_Computation.SetAmygdalaRight(g_AmygdalaRightDisp->value());
m_Computation.SetCaudateLeft(g_CaudateLeftDisp->value());
m_Computation.SetCaudateRight(g_CaudateRightDisp->value());
m_Computation.SetHippocampusLeft(g_HippocampusLeftDisp->value());
m_Computation.SetHippocampusRight(g_HippocampusRightDisp->value());
m_Computation.SetPallidusLeft(g_PallidusLeftDisp->value());
m_Computation.SetPallidusRight(g_PallidusRightDisp->value());
m_Computation.SetPutamenLeft(g_PutamenLeftDisp->value());
m_Computation.SetPutamenRight(g_PutamenRightDisp->value());
m_Computation.SetLateralVentricleLeft(g_LateralVentricleLeftDisp->value());
m_Computation.SetLateralVentricleRight(g_LateralVentricleRightDisp->value());
//Parcellation Map
g_ParcellationFile1Disp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/Parcellation.nrrd");
g_ParcellationFile2Disp->value(NULL);
g_ParcellationFile3Disp->value(NULL);
g_ParcellationFile1Disp->activate();
g_ParcellationFile2Disp->deactivate();
g_ParcellationFile3Disp->deactivate();
g_ParcellationFile1Button->set();
g_ParcellationFile2Button->clear();
g_ParcellationFile2Button->clear();
g_SoftTissueMapButton->clear();
g_HardTissueMapButton->set();
m_Computation.SetParcellationFile1(g_ParcellationFile1Disp->value());
m_Computation.SetParcellationFile2(g_ParcellationFile2Disp->value());
m_Computation.SetParcellationFile3(g_ParcellationFile3Disp->value());
m_Computation.SetSoftTissueMap("Hard");
//Generic ROI Maps
g_ROIFile1Disp->value("/tools/atlas/BrainROIAtlas/adultT1_RAI/nrrd_aligned_Brainsegatlas_adult-asym/HuangROIAtlas.nrrd");
g_ROIFile2Disp->value(NULL);
g_ROIFile3Disp->value(NULL);
g_ROIFile4Disp->value(NULL);
g_ROIFile5Disp->value(NULL);
g_ROIFile1Button->set();
g_ROIFile2Button->clear();
g_ROIFile3Button->clear();
g_ROIFile4Button->clear();
g_ROIFile5Button->clear();
g_ROIFile1Disp->activate();
g_ROIFile2Disp->deactivate();
g_ROIFile3Disp->deactivate();
g_ROIFile4Disp->deactivate();
g_ROIFile5Disp->deactivate();
m_Computation.SetROIFile1(g_ROIFile1Disp->value());
m_Computation.SetROIFile2(g_ROIFile2Disp->value());
m_Computation.SetROIFile3(g_ROIFile3Disp->value());
m_Computation.SetROIFile4(g_ROIFile4Disp->value());
m_Computation.SetROIFile5(g_ROIFile5Disp->value());
//Tissue Segmentation Parameters
g_ABCButton->set();
g_FilterIterations->value(10);
g_FilterTimeStep->value(0.01);
g_FilterMethodChoice->activate();
g_FilterMethodChoice->value(1);
g_InitialDistributionEstimatorChoice->activate();
g_InitialDistributionEstimatorChoice->value(1);
g_MaxBiasDegree->value(4);
g_Prior1->value(1.3);
g_Prior2->value(1.0);
g_Prior3->value(0.7);
g_Prior4->value(1.0);
g_Prior5->value(1.0);
g_Prior6->value(1.0);
g_Prior7->value(1.0);
g_Prior8->value(1.0);
g_Prior9->value(1.0);
g_BSplineAtlasWarpGroup->deactivate();
g_BSplineAtlasWarpButton->clear();
g_BSplineAtlasWarpGridX->value(5.0);
g_BSplineAtlasWarpGridY->value(5.0);
g_BSplineAtlasWarpGridZ->value(5.0);
g_FluidAtlasWarpGroup->activate();
g_FluidAtlasWarpButton->set();
g_FluidAtlasAffineButton->clear();
g_FluidAtlasFATWButton->clear();
g_ABCANTSWarpButton->clear();
g_FluidAtlasWarpIterations->value(50);
g_FluidAtlasWarpMaxStep->value(0.1);
g_AtlasLinearMappingChoice->value(0);
g_ImageLinearMappingChoice->value(0);
g_NeosegParamGroup->deactivate();
g_NeosegPriorThreshold->value(0.8);
g_NeosegParzenKernel->value(0.05);
g_NeosegMahalanobisThreshold->value(2.0);
g_AtlasLoopDisp->value("/tools/atlas/BrainsegAtlas/adult-atlas-asym-stripped-T1-RAI/");
g_LoopIteration->value(1);
m_Computation.SetFilterIterations((int)g_FilterIterations->value());
m_Computation.SetFilterTimeStep((float)g_FilterTimeStep->value());
m_Computation.SetFilterMethod("Curvature flow");
m_Computation.SetInitialDistributionEstimator("robust");
m_Computation.SetMaxBiasDegree((int)g_MaxBiasDegree->value());
m_Computation.SetPrior1((float)g_Prior1->value());
m_Computation.SetPrior2((float)g_Prior2->value());
m_Computation.SetPrior3((float)g_Prior3->value());
m_Computation.SetPrior4((float)g_Prior4->value());
m_Computation.SetPrior5((float)g_Prior5->value());
m_Computation.SetPrior6((float)g_Prior6->value());
m_Computation.SetPrior7((float)g_Prior7->value());
m_Computation.SetPrior8((float)g_Prior8->value());
m_Computation.SetPrior9((float)g_Prior9->value());
m_Computation.SetBSplineAtlasWarp(0);
m_Computation.SetBSplineAtlasWarpGridX((float)g_BSplineAtlasWarpGridX->value());
m_Computation.SetBSplineAtlasWarpGridY((float)g_BSplineAtlasWarpGridY->value());
m_Computation.SetBSplineAtlasWarpGridZ((float)g_BSplineAtlasWarpGridZ->value());
m_Computation.SetFluidAtlasWarp(1);
m_Computation.SetFluidAtlasAffine(0);
m_Computation.SetFluidAtlasFATW(0);
m_Computation.SetFluidAtlasWarpIterations((int)g_FluidAtlasWarpIterations->value());
m_Computation.SetFluidAtlasWarpMaxStep((float)g_FluidAtlasWarpMaxStep->value());
m_Computation.SetAtlasLinearMapping("affine");
m_Computation.SetImageLinearMapping("id");
m_Computation.SetNeosegPriorThreshold((float)g_NeosegPriorThreshold->value());
m_Computation.SetNeosegParzenKernel((float)g_NeosegParzenKernel->value());
m_Computation.SetNeosegMahalanobisThreshold((float)g_NeosegMahalanobisThreshold->value());
m_Computation.SetAtlasLoop(g_AtlasLoopDisp->value());
m_Computation.SetLoopIteration((int)g_LoopIteration->value());
// Reorientation Parameters
g_ReorientationButton->clear();
m_Computation.SetReorientation(0);
// N4ITKBiasFieldCorrection Parameters
g_N4ITKBiasFieldCorrectionButton->set();
g_N4ParametersGroup->activate();
g_N4AdvancedParametersGroup->activate();
g_NbOfIterations->value("50,40,30");
g_BSplineGridResolutions->value("1,1,1");
g_ConvergenceThreshold->value(0.0001);
g_SplineDistance->value(0);
g_ShrinkFactor->value(4);
g_BSplineOrder->value(3);
//g_BSplineAlpha->value(0);
//g_BSplineBeta->value(0.5);
g_HistogramSharpening->value("0");
g_StrippedN4ITKBiasFieldCorrectionButton->clear();
m_Computation.SetN4ITKBiasFieldCorrection(1);
m_Computation.SetNbOfIterations ("50,40,30");
m_Computation.SetBSplineGridResolutions ("1,1,1");
m_Computation.SetConvergenceThreshold((float)g_ConvergenceThreshold->value());
m_Computation.SetSplineDistance((int)g_SplineDistance->value());
m_Computation.SetShrinkFactor((int)g_ShrinkFactor->value());
m_Computation.SetBSplineOrder((int)g_BSplineOrder->value());
// m_Computation.SetBSplineAlpha((int)g_BSplineAlpha->value());
// m_Computation.SetBSplineBeta((float)g_BSplineBeta->value());
m_Computation.SetHistogramSharpening("0");
m_Computation.SetStrippedN4ITKBiasFieldCorrection(0);
// Rigid Registration Parameters
g_RigidRegistrationButton->set();
g_GridTemplateAtlasButton->set();
g_GridTemplateManualButton->clear();
g_GridTemplateSizeX->value(0);
g_GridTemplateSizeY->value(0);
g_GridTemplateSizeZ->value(0);
g_GridTemplateSpacingX->value(0);
g_GridTemplateSpacingY->value(0);
g_GridTemplateSpacingZ->value(0);
g_InitRegCenterOfHeadButton->set();
g_InitRegMomentsButton->clear();
g_InitRegGeometryButton->clear();
g_InitRegOffButton->clear();
g_InitRegUseT1InitTransformButton->clear();
m_Computation.SetRigidRegistration(1);
m_Computation.SetROIAtlasGridTemplate((bool)g_GridTemplateAtlasButton->value());
m_Computation.SetGridTemplateSizeX((int)g_GridTemplateSizeX->value());
m_Computation.SetGridTemplateSizeY((int)g_GridTemplateSizeY->value());
m_Computation.SetGridTemplateSizeZ((int)g_GridTemplateSizeZ->value());
m_Computation.SetGridTemplateSpacingX((float)g_GridTemplateSpacingX->value());
m_Computation.SetGridTemplateSpacingY((float)g_GridTemplateSpacingY->value());
m_Computation.SetGridTemplateSpacingZ((float)g_GridTemplateSpacingZ->value());
m_Computation.SetRegistrationInitialization("useCenterOfHeadAlign");
m_Computation.SetInitRegUseT1InitTransform(0);
// Warping Parameters
g_ClassicWarpingButton->clear();
g_CoarseToFineWarpingButton->clear();
g_BRAINSDemonWarpButton->clear();
g_ANTSWarpingButton->set();
g_ANTSWarpingGroup->show();
g_BRAINSDemonWarpGroup->hide();
g_FluidWarpingGroup->hide();
// - Fluid Parameters
g_Alpha->value(0.01);
g_Beta->value(0.01);
g_Gamma->value(0.001);
g_MaxPerturbation->value(0.5);
g_NumBasis->value(0.01);
g_Alpha->deactivate();
g_Beta->deactivate();
g_Gamma->deactivate();
g_MaxPerturbation->deactivate();
g_NumBasis->deactivate();
g_Scale4NbIterations->value(50);
g_Scale4NbIterations->deactivate();
g_Scale2NbIterations->value(25);
g_Scale2NbIterations->deactivate();
g_Scale1NbIterations->value(100);
g_Scale1NbIterations->deactivate();
// - BRAINSDemonWarp parameters
g_RegistrationFilterType->value(3);
g_DeformationFieldSmoothingSigma->value(2.0);
g_PyramidLevels->value(5);
g_MovingShrinkFactors->value("16,16,16");
g_FixedShrinkFactors->value("16,16,16");
g_IterationCountPyramidLevels->value("300,50,30,20,15");
// - ANTS parameters
g_ANTSIterations->value("100x50x25");
g_ANTSCCWeight->value(1.0);
g_ANTSCCRegionRadius->value(2.0);
g_ANTSMIWeight->value(0.0);
g_ANTSMIBins->value(32);
g_ANTSMSQWeight->value(0.0);
g_ANTSCCWeight2nd->value(1.0);
g_ANTSCCRegionRadius2nd->value(2.0);
g_ANTSMIWeight2nd->value(0.0);
g_ANTSMIBins2nd->value(32);
g_ANTSMSQWeight2nd->value(0.0);
g_ANTSRegistrationFilterType->value(0);
g_ANTSGaussianSmoothingButton->set();
g_ANTSGaussianSigma->value(3.0);
g_NumberOfThreads->value(1);
//
m_Computation.SetClassicWarpingMethod(0);
m_Computation.SetBRAINSDemonWarpMethod(0);
m_Computation.SetAlpha((float)g_Alpha->value());
m_Computation.SetBeta((float)g_Beta->value());
m_Computation.SetGamma((float)g_Gamma->value());
m_Computation.SetMaxPerturbation((float)g_MaxPerturbation->value());
m_Computation.SetScale4NbIterations((int)g_Scale4NbIterations->value());
m_Computation.SetScale2NbIterations((int)g_Scale2NbIterations->value());
m_Computation.SetScale1NbIterations((int)g_Scale1NbIterations->value());
m_Computation.SetNumBasis((float)g_NumBasis->value());
m_Computation.SetRegistrationFilterType("LogDemons");
m_Computation.SetDeformationFieldSmoothingSigma((float)g_DeformationFieldSmoothingSigma->value());
m_Computation.SetPyramidLevels((int)g_PyramidLevels->value());
m_Computation.SetMovingShrinkFactors("16,16,16");
m_Computation.SetFixedShrinkFactors("16,16,16");
m_Computation.SetIterationCountPyramidLevels("300,50,30,20,15");
m_Computation.SetANTSIterations("100x50x25");
m_Computation.SetANTSCCWeight(1.0);
m_Computation.SetANTSCCRegionRadius(2.0);
m_Computation.SetANTSMIWeight(0.0);
m_Computation.SetANTSMIBins(32);
m_Computation.SetANTSMSQWeight(0.0);
m_Computation.SetANTSCCWeight2nd(1.0);
m_Computation.SetANTSCCRegionRadius2nd(2.0);
m_Computation.SetANTSMIWeight2nd(0.0);
m_Computation.SetANTSMIBins2nd(32);
m_Computation.SetANTSMSQWeight2nd(0.0);
m_Computation.SetANTSRegistrationFilterType("GreedyDiffeomorphism");
m_Computation.SetANTSGaussianSmoothing(1);
m_Computation.SetANTSGaussianSigma(3.0);
m_Computation.SetNbANTSThreads(1);
// Skull Stripping parameters
g_DeleteVesselsButton->clear();
m_Computation.SetDeleteVessels(0);
// Intensity Rescaling parameters
g_HistogramQuantileButton->set();
g_TissueMeanMatchButton->clear();
m_Computation.SetIntensityRescalingMethod(1);
// Regional histogram
g_QuantilesDisp->value("1,5,33,50,66,95,99");
m_Computation.SetQuantiles("1,5,33,50,66,95,99");
// Multi-Atlas Segmentation
g_WeightedMajorityVotingButton->set();
m_Computation.SetLabelFusionAlgorithm("Weighted Majority Voting");
m_Computation.SetWeightIntensityEnergy(g_IntensityEnergyWeight->value());
m_Computation.SetWeightHarmonicEnergy(g_HarmonicEnergyWeight->value());
m_Computation.SetWeightShapeEnergy(g_ShapeEnergyWeight->value());
}
void AutoSegGUIControls::UpdateParameters()
{
m_Computation.SetDataAutoSegDirectory(g_DataAutoSegDirectoryDisp->value());
SetSubcorticalStructures();
SetGenericROIMaps();
SetParcellationMap();
SetReorientationParameters();
SetN4Parameters();
SetGridTemplateParameters();
SetIntensityRescalingMethod();
SetRegionalHistogramParameters();
}
void AutoSegGUIControls::CheckDirectoryName(char *_Directory)
{
int Length;
Length = std::strlen(_Directory);
if (_Directory[Length-1] != '/')
{
_Directory[Length] = '/';
_Directory[Length+1] = '\0';
}
}
void AutoSegGUIControls::RightJustifyData(const char *_Input, char *_Output)
{
int Char1 = 0;
int Char2 = 0;
if ( (!g_T2Button->value()) && (!g_PDButton->value()) )
std::strcpy(_Output, _Input);
else if ( (g_T2Button->value()) && (g_PDButton->value()) )
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, _Input+Char1+Char2+1);
}
else
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output,_Input+Char1);
}
}
void AutoSegGUIControls::MajorityVotingButtonToggled()
{
m_Computation.SetLabelFusionAlgorithm("Majority Voting");
g_MajorityVotingButton->set();
g_WeightedMajorityVotingButton->clear();
g_StapleButton->clear();
}
void AutoSegGUIControls::WeightedMajorityVotingButtonToggled()
{
m_Computation.SetLabelFusionAlgorithm("Weighted Majority Voting");
g_MajorityVotingButton->clear();
g_WeightedMajorityVotingButton->set();
g_StapleButton->clear();
}
void AutoSegGUIControls::StapleButtonToggled()
{
m_Computation.SetLabelFusionAlgorithm("STAPLE");
g_MajorityVotingButton->clear();
g_WeightedMajorityVotingButton->clear();
g_StapleButton->set();
}
void AutoSegGUIControls::Slicer4dot3ButtonChecked()
{
m_Computation.SetSlicerVersion(4.3);
g_Slicer4dot3Button->set();
g_Slicer4Button->clear();
g_Slicer3Button->clear();
}
void AutoSegGUIControls::Slicer4ButtonChecked()
{
m_Computation.SetSlicerVersion(4.0);
g_Slicer4dot3Button->clear();
g_Slicer4Button->set();
g_Slicer3Button->clear();
}
void AutoSegGUIControls::Slicer3ButtonChecked()
{
m_Computation.SetSlicerVersion(3.0);
g_Slicer4dot3Button->clear();
g_Slicer4Button->clear();
g_Slicer3Button->set();
}
void AutoSegGUIControls::ANTSWithBrainmaskButtonChecked()
{
m_Computation.SetANTSWithBrainmask(g_ANTSWithBrainmaskButton->value());
}
void AutoSegGUIControls::UseInitialAffineButtonChecked()
{
m_Computation.SetUseInitialAffine(g_UseInitialAffineButton->value());
}
void AutoSegGUIControls::SetIntensityEnergyGUI()
{
m_Computation.SetWeightIntensityEnergy(g_IntensityEnergyWeight->value());
}
void AutoSegGUIControls::SetHarmonicEnergyGUI()
{
m_Computation.SetWeightHarmonicEnergy(g_HarmonicEnergyWeight->value());
}
void AutoSegGUIControls::SetShapeEnergyGUI()
{
m_Computation.SetWeightShapeEnergy(g_ShapeEnergyWeight->value());
}
void AutoSegGUIControls::RightJustifyAuxData(const char *_Input, char *_Output)
{
int Char1 = 0;
int Char2 = 0;
int Char3 = 0;
int Char4 = 0;
int Char5 = 0;
int Char6 = 0;
int Char7 = 0;
int Char8 = 0;
if ( (!g_Aux1Button->value()) && (!g_Aux2Button->value()) && (!g_Aux3Button->value()) && (!g_Aux4Button->value()) && (!g_Aux5Button->value()) && (!g_Aux6Button->value()) && (!g_Aux7Button->value()) && (!g_Aux8Button->value()) )
std::strcpy(_Output, _Input);
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) && (g_Aux8Button->value()) )
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3, 1) != 0)
Char3++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4, 1) != 0)
Char4++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5, 1) != 0)
Char5++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6, 1) != 0)
Char6++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6+1+Char7, 1) != 0)
Char7++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6+1+Char7+1+Char8, 1) != 0)
Char8++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1, Char3);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1, Char4);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1, Char5);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1, Char6);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6+1, Char7);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6+1+Char7+1, Char8);
std::strcat(_Output, _Input+Char1+Char2+Char3+Char4+Char5+Char6+Char7+Char8+7);
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) && (g_Aux7Button->value()) )
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3, 1) != 0)
Char3++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4, 1) != 0)
Char4++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5, 1) != 0)
Char5++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6, 1) != 0)
Char6++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6+1+Char7, 1) != 0)
Char7++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1, Char3);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1, Char4);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1, Char5);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1, Char6);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6+1, Char7);
std::strcat(_Output, _Input+Char1+Char2+Char3+Char4+Char5+Char6+Char7+6);
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()) && (g_Aux6Button->value()) )
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3, 1) != 0)
Char3++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4, 1) != 0)
Char4++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5, 1) != 0)
Char5++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1+Char6, 1) != 0)
Char6++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1, Char3);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1, Char4);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1, Char5);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5+1, Char6);
std::strcat(_Output, _Input+Char1+Char2+Char3+Char4+Char5+Char6+5);
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) && (g_Aux5Button->value()))
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3, 1) != 0)
Char3++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4, 1) != 0)
Char4++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4+1+Char5, 1) != 0)
Char5++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1, Char3);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1, Char4);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1+Char4+1, Char5);
std::strcat(_Output, _Input+Char1+Char2+Char3+Char4+Char5+4);
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) && (g_Aux4Button->value()) )
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3, 1) != 0)
Char3++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3+1+Char4, 1) != 0)
Char4++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1, Char3);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1+Char3+1, Char4);
std::strcat(_Output, _Input+Char1+Char2+Char3+Char4+3);
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) && (g_Aux3Button->value()) )
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
while (std::strncmp(" ", _Input+Char1+1+Char2+1+Char3, 1) != 0)
Char3++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1+Char2+1, Char3);
std::strcat(_Output, _Input+Char1+Char2+Char3+2);
}
else if ( (g_Aux1Button->value()) && (g_Aux2Button->value()) )
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
while (std::strncmp(" ", _Input+Char1+1+Char2, 1) != 0)
Char2++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output, " @r");
std::strncat(_Output,_Input+Char1+1, Char2);
std::strcat(_Output, _Input+Char1+Char2+1);
}
else
{
while (std::strncmp(" ", _Input+Char1, 1) != 0)
Char1++;
std::strcpy(_Output,"@r");
std::strncat(_Output, _Input, Char1);
std::strcat(_Output,_Input+Char1);
}
}
| 31.871555 | 605 | 0.666878 | [
"shape",
"vector",
"transform"
] |
d1f48fe13b0fd9c34c050ae69ba4c34c3b987a44 | 593 | cpp | C++ | codeforces/237a.free-cash/237a.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | 3 | 2018-01-19T14:09:23.000Z | 2018-02-01T00:40:55.000Z | codeforces/237a.free-cash/237a.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | null | null | null | codeforces/237a.free-cash/237a.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | null | null | null | // K1
// :)
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <bitset>
#include <string>
#include <cmath>
#include <iomanip>
#define MAXN (int(100))
#define EPS 1e-8
#define PI 3.141592653589793
#define point pair <int , int>
#define X first
#define Y second
#define FX(x) fixed << setprecision((x))
using namespace std;
int arr[MAXN][MAXN];
int main()
{
int result = 1;
int n;
cin >> n;
for(int i=0; i<n; i++)
{
int a, b;
cin >> a >> b;
arr[a][b] ++;
if (arr[a][b] > result)
result = arr[a][b];
}
cout << result << endl;
return 0;
}
| 14.463415 | 40 | 0.610455 | [
"vector"
] |
d1feb5f8676f8ad23d33085dd13577c93a385027 | 887 | cpp | C++ | src/main.cpp | Chabam/rt-engine | 318b6b9e9dd4ca61c3c44c7cfebdda528ab96588 | [
"MIT"
] | null | null | null | src/main.cpp | Chabam/rt-engine | 318b6b9e9dd4ca61c3c44c7cfebdda528ab96588 | [
"MIT"
] | null | null | null | src/main.cpp | Chabam/rt-engine | 318b6b9e9dd4ca61c3c44c7cfebdda528ab96588 | [
"MIT"
] | null | null | null | #include "engine/engine.h"
#include "logger/logger.h"
#include "object/cube.h"
#include "object/vertice.h"
#include <array>
#include <stdexcept>
#include <vector>
int main(void)
{
// clang-format off
Engine engine(
Shader("../src/shaders/shader.vert", "../src/shaders/shader.frag")
);
// clang-format on
try
{
engine.init();
// clang-format off
std::vector<Mesh> objects = {Cube(), Cube(Material({0.f, 0.f, 1.f, 1.f}))};
objects[0].applyTransformation(glm::translate(glm::mat4(1.f), glm::vec3(-2.f, 0.f, 0.f)));
objects[1].applyTransformation(glm::translate(glm::mat4(1.f), glm::vec3(2.f, 0.f, 0.f)));
engine.setMeshes(objects);
// clang-format on
engine.start();
}
catch (const std::runtime_error& e)
{
LOG_ERROR(e.what());
return 1;
}
return 0;
}
| 22.74359 | 98 | 0.574972 | [
"mesh",
"object",
"vector"
] |
0603b77bf3e4863610f69846581ea917c0962f5c | 3,996 | hpp | C++ | libpldmresponder/base.hpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | 9 | 2019-06-25T11:08:15.000Z | 2021-12-09T23:11:10.000Z | libpldmresponder/base.hpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | 59 | 2021-08-11T12:03:06.000Z | 2022-03-29T13:49:53.000Z | libpldmresponder/base.hpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | 139 | 2021-06-17T19:37:13.000Z | 2022-03-30T10:58:05.000Z | #pragma once
#include "libpldm/base.h"
#include "libpldmresponder/platform.hpp"
#include "pldmd/handler.hpp"
#include "requester/handler.hpp"
#include <stdint.h>
#include <sdeventplus/source/event.hpp>
#include <vector>
using namespace pldm::dbus_api;
using namespace pldm::responder;
namespace pldm
{
namespace responder
{
namespace base
{
class Handler : public CmdHandler
{
public:
Handler(uint8_t eid, Requester& requester, sdeventplus::Event& event,
pldm::responder::oem_platform::Handler* oemPlatformHandler,
pldm::requester::Handler<pldm::requester::Request>* handler) :
eid(eid),
requester(requester), event(event),
oemPlatformHandler(oemPlatformHandler), handler(handler)
{
handlers.emplace(PLDM_GET_PLDM_TYPES,
[this](const pldm_msg* request, size_t payloadLength) {
return this->getPLDMTypes(request, payloadLength);
});
handlers.emplace(PLDM_GET_PLDM_COMMANDS, [this](const pldm_msg* request,
size_t payloadLength) {
return this->getPLDMCommands(request, payloadLength);
});
handlers.emplace(PLDM_GET_PLDM_VERSION, [this](const pldm_msg* request,
size_t payloadLength) {
return this->getPLDMVersion(request, payloadLength);
});
handlers.emplace(PLDM_GET_TID,
[this](const pldm_msg* request, size_t payloadLength) {
return this->getTID(request, payloadLength);
});
}
/** @brief Handler for getPLDMTypes
*
* @param[in] request - Request message payload
* @param[in] payload_length - Request message payload length
* @param[return] Response - PLDM Response message
*/
Response getPLDMTypes(const pldm_msg* request, size_t payloadLength);
/** @brief Handler for getPLDMCommands
*
* @param[in] request - Request message payload
* @param[in] payload_length - Request message payload length
* @param[return] Response - PLDM Response message
*/
Response getPLDMCommands(const pldm_msg* request, size_t payloadLength);
/** @brief Handler for getPLDMCommands
*
* @param[in] request - Request message payload
* @param[in] payload_length - Request message payload length
* @param[return] Response - PLDM Response message
*/
Response getPLDMVersion(const pldm_msg* request, size_t payloadLength);
/** @brief _processSetEventReceiver does the actual work that needs
* to be carried out for setEventReceiver command. This is deferred
* after sending response for getTID command to the host
*
* @param[in] source - sdeventplus event source
*/
void processSetEventReceiver(sdeventplus::source::EventBase& source);
/** @brief Handler for getTID
*
* @param[in] request - Request message payload
* @param[in] payload_length - Request message payload length
* @param[return] Response - PLDM Response message
*/
Response getTID(const pldm_msg* request, size_t payloadLength);
private:
/** @brief MCTP EID of host firmware */
uint8_t eid;
/** @brief reference to Requester object, primarily used to access API to
* obtain PLDM instance id.
*/
Requester& requester;
/** @brief reference of main event loop of pldmd, primarily used to schedule
* work
*/
sdeventplus::Event& event;
/** @brief OEM platform handler */
pldm::responder::oem_platform::Handler* oemPlatformHandler;
/** @brief PLDM request handler */
pldm::requester::Handler<pldm::requester::Request>* handler;
/** @brief sdeventplus event source */
std::unique_ptr<sdeventplus::source::Defer> survEvent;
};
} // namespace base
} // namespace responder
} // namespace pldm
| 33.3 | 80 | 0.642142 | [
"object",
"vector"
] |
0605d6b9546d84766349329f97baae1df478055c | 2,497 | hpp | C++ | libs/common/obj_utils.hpp | alohamora/iroha | aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7 | [
"Apache-2.0"
] | null | null | null | libs/common/obj_utils.hpp | alohamora/iroha | aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7 | [
"Apache-2.0"
] | null | null | null | libs/common/obj_utils.hpp | alohamora/iroha | aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_COMMON_OBJ_UTILS_HPP
#define IROHA_COMMON_OBJ_UTILS_HPP
#include <optional>
namespace iroha {
/**
* Create map get function for value retrieval by key
* @tparam K - map key type
* @tparam V - map value type
* @param map - map for value retrieval
* @return function which takes key, returns value if key exists,
* nullopt otherwise
*/
template <typename C>
auto makeOptionalGet(C map) {
return [&map](auto key) -> std::optional<typename C::mapped_type> {
auto it = map.find(key);
if (it != std::end(map)) {
return it->second;
}
return std::nullopt;
};
}
/**
* Return function which invokes class method by pointer to member with
* provided arguments
*
* class A {
* int f(int, double);
* }
*
* A a;
* int i = makeMethodInvoke(a, 1, 1.0);
*
* @tparam T - provided class type
* @tparam Args - provided arguments types
* @param object - class object
* @param args - function arguments
* @return described function
*/
template <typename T, typename... Args>
auto makeMethodInvoke(T &object, Args &&... args) {
return [&](auto f) { return (object.*f)(std::forward<Args>(args)...); };
}
/**
* Assign the value to the object member
* @tparam V - object member type
* @tparam B - object type
* @param object - object value for member assignment
* @param member - pointer to member in block
* @return object with deserialized member on success, nullopt otherwise
*/
template <typename V, typename B>
auto assignObjectField(B object, V B::*member) {
return [=](auto value) mutable {
object.*member = value;
return std::make_optional(object);
};
}
/**
* Assign the value to the object member. Block is wrapped in monad
* @tparam P - monadic type
* @tparam V - object member type
* @tparam B - object type
* @param object - object value for member assignment
* @param member - pointer to member in object
* @return object with deserialized member on success, nullopt otherwise
*/
template <template <typename C> class P, typename V, typename B>
auto assignObjectField(P<B> object, V B::*member) {
return [=](auto value) mutable {
(*object).*member = value;
return std::make_optional(object);
};
}
} // namespace iroha
#endif // IROHA_COMMON_OBJ_UTILS_HPP
| 28.05618 | 76 | 0.643973 | [
"object"
] |
06064d59d997a0a4bf2f26e2718d1d6a1f6396e5 | 622 | cc | C++ | kattis/turbo.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | kattis/turbo.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | kattis/turbo.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://open.kattis.com/problems/turbo
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
using vi=vector<int>;
using si=tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n,x;
cin>>n;
vi a(n);
si b;
for(int i=0;i<n;i++){
cin>>x;x--;
a[x]=i;
b.insert(i);
}
for(int i=0;i<=(n-1)/2;i++){
cout<<b.order_of_key(a[i])<<endl;
b.erase(a[i]);
if(i==n-i-1)break;
cout<<b.size()-b.order_of_key(a[n-i-1])-1<<endl;
b.erase(a[n-i-1]);
}
}
| 22.214286 | 85 | 0.615756 | [
"vector"
] |
060af1b83bee83b8131eef1becbb240bd130d690 | 1,304 | cc | C++ | cpp_tests/linalg/sparse_vector_test.cc | lindong28/clink | c8c9cd0b63c73850a93394666bd1c8feb605710f | [
"Apache-2.0"
] | null | null | null | cpp_tests/linalg/sparse_vector_test.cc | lindong28/clink | c8c9cd0b63c73850a93394666bd1c8feb605710f | [
"Apache-2.0"
] | null | null | null | cpp_tests/linalg/sparse_vector_test.cc | lindong28/clink | c8c9cd0b63c73850a93394666bd1c8feb605710f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 The Clink Authors
*
* 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 "clink/linalg/sparse_vector.h"
#include "clink/cpp_tests/test_util.h"
#include "gtest/gtest.h"
namespace clink {
namespace {
TEST(SparseVectorTest, CreatesVector) {
SparseVector vector(5);
EXPECT_EQ(vector.size(), 5);
}
TEST(SparseVectorTest, SetGetValue) {
SparseVector vector(5);
vector.set(1, 1.0);
vector.set(2, 3.0);
vector.set(4, 2.5);
EXPECT_EQ(vector.get(0).get(), 0.0);
EXPECT_EQ(vector.get(1).get(), 1.0);
EXPECT_EQ(vector.get(2).get(), 3.0);
EXPECT_EQ(vector.get(3).get(), 0.0);
EXPECT_EQ(vector.get(4).get(), 2.5);
EXPECT_FALSE((bool)vector.get(4).takeError());
EXPECT_TRUE((bool)vector.get(5).takeError());
}
} // namespace
} // namespace clink
| 27.744681 | 75 | 0.703988 | [
"vector"
] |
060d3afa5f934956fb61fbe3d155dd9bfad0d5c2 | 11,034 | cc | C++ | modules/paxmon/src/reroute.cc | alexandersinkovic/motis | e4a0af04b4c934b8361401b1164db81bec5f1e6b | [
"MIT"
] | null | null | null | modules/paxmon/src/reroute.cc | alexandersinkovic/motis | e4a0af04b4c934b8361401b1164db81bec5f1e6b | [
"MIT"
] | 1 | 2022-03-16T11:44:06.000Z | 2022-03-16T11:44:06.000Z | modules/paxmon/src/reroute.cc | Kingforce01/motis | e4a0af04b4c934b8361401b1164db81bec5f1e6b | [
"MIT"
] | null | null | null | #include "motis/paxmon/reroute.h"
#include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include "utl/enumerate.h"
#include "utl/erase.h"
#include "utl/pairwise.h"
#include "utl/to_vec.h"
#include "utl/verify.h"
#include "motis/core/access/edge_access.h"
#include "motis/core/access/station_access.h"
#include "motis/core/access/trip_iterator.h"
#include "motis/paxmon/capacity.h"
#include "motis/paxmon/graph_access.h"
namespace motis::paxmon {
trip_ev_key to_trip_ev_key(event_node* n) {
return {n->station_, n->schedule_time_, n->type_, n};
}
std::vector<trip_ev_key> to_trip_ev_keys(trip_data_index tdi, universe& uv) {
std::vector<trip_ev_key> teks;
auto const edges = uv.trip_data_.edges(tdi);
teks.reserve(edges.size() * 2);
for (auto const& ei : edges) {
auto const* e = ei.get(uv);
teks.emplace_back(to_trip_ev_key(e->from(uv)));
teks.emplace_back(to_trip_ev_key(e->to(uv)));
}
return teks;
}
std::vector<trip_ev_key> to_trip_ev_keys(
schedule const& sched,
flatbuffers::Vector<flatbuffers::Offset<motis::rt::RtEventInfo>> const&
events) {
return utl::to_vec(events, [&](motis::rt::RtEventInfo const* ei) {
return trip_ev_key{
get_station_node(sched, ei->station_id()->str())->id_,
unix_to_motistime(sched.schedule_begin_, ei->schedule_time()),
ei->event_type() == EventType_DEP ? event_type::DEP : event_type::ARR,
nullptr};
});
}
std::vector<std::pair<diff_op, trip_ev_key>> diff_route(
std::vector<trip_ev_key> const& old_route,
std::vector<trip_ev_key> const& new_route) {
std::vector<std::pair<diff_op, trip_ev_key>> diff;
auto old_start = 0ULL;
auto new_start = 0ULL;
start:
for (auto old_idx = old_start; old_idx < old_route.size(); ++old_idx) {
auto const& old_tek = old_route[old_idx];
for (auto new_idx = new_start; new_idx < new_route.size(); ++new_idx) {
auto const& new_tek = new_route[new_idx];
if (old_tek == new_tek) {
for (auto i = old_start; i < old_idx; ++i) {
diff.emplace_back(diff_op::REMOVE, old_route[i]);
}
for (auto i = new_start; i < new_idx; ++i) {
diff.emplace_back(diff_op::INSERT, new_route[i]);
}
diff.emplace_back(diff_op::KEEP, old_route[old_idx]);
old_start = old_idx + 1;
new_start = new_idx + 1;
goto start;
}
}
}
for (auto i = old_start; i < old_route.size(); ++i) {
diff.emplace_back(diff_op::REMOVE, old_route[i]);
}
for (auto i = new_start; i < new_route.size(); ++i) {
diff.emplace_back(diff_op::INSERT, new_route[i]);
}
return diff;
}
edge* get_connecting_edge(event_node const* from, event_node const* to,
universe& uv) {
if (from == nullptr || to == nullptr) {
return nullptr;
}
for (auto& e : from->outgoing_edges(uv)) {
if (e.to_ == to->index_) {
return &e;
}
}
return nullptr;
}
// the following functions are split because otherwise clang-tidy complains
// that begin(from->outgoing_edges(uv)) allegedly returns nullptr
void disable_outgoing_edges(universe& uv, event_node* from,
edge const* except) {
for (auto& e : from->outgoing_edges(uv)) {
if (&e != except && (e.is_trip() || e.is_wait())) {
e.type_ = edge_type::DISABLED;
}
}
}
void disable_outgoing_edges(universe& uv, event_node* from) {
for (auto& e : from->outgoing_edges(uv)) {
if (e.is_trip() || e.is_wait()) {
e.type_ = edge_type::DISABLED;
}
}
}
void disable_incoming_edges(universe& uv, event_node* to, edge const* except) {
for (auto& e : to->incoming_edges(uv)) {
if (&e != except && (e.is_trip() || e.is_wait())) {
e.type_ = edge_type::DISABLED;
}
}
}
void disable_incoming_edges(universe& uv, event_node* to) {
for (auto& e : to->incoming_edges(uv)) {
if (e.is_trip() || e.is_wait()) {
e.type_ = edge_type::DISABLED;
}
}
}
edge* connect_nodes(event_node* from, event_node* to,
merged_trips_idx merged_trips,
std::uint16_t encoded_capacity, universe& uv) {
if (from == nullptr || to == nullptr) {
return nullptr;
}
utl::verify(
(from->type_ == event_type::DEP && to->type_ == event_type::ARR) ||
(from->type_ == event_type::ARR && to->type_ == event_type::DEP),
"invalid event sequence");
auto const type =
from->type_ == event_type::DEP ? edge_type::TRIP : edge_type::WAIT;
if (auto e = get_connecting_edge(from, to, uv); e != nullptr) {
if (e->is_disabled()) {
e->type_ = type;
}
disable_outgoing_edges(uv, from, e);
disable_incoming_edges(uv, to, e);
return e;
}
disable_outgoing_edges(uv, from);
disable_incoming_edges(uv, to);
auto const cap = from->type_ == event_type::DEP ? encoded_capacity
: UNLIMITED_ENCODED_CAPACITY;
return add_edge(
uv, make_trip_edge(uv, from->index_, to->index_, type, merged_trips, cap,
service_class::OTHER)); // TODO(pablo): service class
}
event_node* get_or_insert_node(universe& uv, trip_data_index const tdi,
trip_ev_key const tek,
std::set<event_node*>& reactivated_nodes) {
for (auto const ni : uv.trip_data_.canceled_nodes(tdi)) {
auto const n = &uv.graph_.nodes_[ni];
if (n->station_ == tek.station_id_ &&
n->schedule_time_ == tek.schedule_time_ && n->type_ == tek.type_) {
n->valid_ = true;
reactivated_nodes.insert(n);
return n;
}
}
return &uv.graph_.emplace_back_node(
static_cast<event_node_index>(uv.graph_.nodes_.size()),
tek.schedule_time_, tek.schedule_time_, tek.type_, true, tek.station_id_);
}
std::pair<std::uint16_t, capacity_source> guess_trip_capacity(
schedule const& sched, capacity_maps const& caps, trip const* trp) {
auto const sections = access::sections(trp);
if (begin(sections) != end(sections)) {
return get_capacity(sched, (*begin(sections)).lcon(),
caps.trip_capacity_map_, caps.category_capacity_map_);
} else {
return {UNKNOWN_CAPACITY, capacity_source::SPECIAL};
}
}
std::set<passenger_group*> collect_passenger_groups(universe& uv,
trip_data_index const tdi) {
std::set<passenger_group*> affected_passenger_groups;
for (auto const& tei : uv.trip_data_.edges(tdi)) {
auto* te = tei.get(uv);
auto groups = uv.pax_connection_info_.groups_[te->pci_];
for (auto pg_id : groups) {
auto* pg = uv.passenger_groups_[pg_id];
affected_passenger_groups.insert(pg);
utl::erase(pg->edges_, tei);
}
groups.clear();
}
return affected_passenger_groups;
}
bool update_passenger_group(trip_data_index const tdi, trip const* trp,
passenger_group* pg, universe& uv) {
static constexpr auto const INVALID_INDEX =
std::numeric_limits<std::size_t>::max();
for (auto const& leg : pg->compact_planned_journey_.legs_) {
if (leg.trip_idx_ == trp->trip_idx_) {
auto const edges = uv.trip_data_.edges(tdi);
auto enter_index = INVALID_INDEX;
auto exit_index = INVALID_INDEX;
for (auto const& [idx, ei] : utl::enumerate(edges)) {
auto const e = ei.get(uv);
auto const from = e->from(uv);
auto const to = e->to(uv);
if (from->station_ == leg.enter_station_id_ &&
from->schedule_time_ == leg.enter_time_) {
enter_index = idx;
} else if (to->station_ == leg.exit_station_id_ &&
to->schedule_time_ == leg.exit_time_) {
exit_index = idx;
break;
}
}
if (enter_index != INVALID_INDEX && exit_index != INVALID_INDEX) {
for (auto idx = enter_index; idx <= exit_index; ++idx) {
auto const& ei = edges[idx];
auto* e = ei.get(uv);
add_passenger_group_to_edge(uv, e, pg);
pg->edges_.emplace_back(ei);
}
return true;
}
return false;
}
}
return false;
}
std::optional<merged_trips_idx> get_merged_trips(trip const* trp) {
if (trp->edges_->empty()) {
return {};
}
return get_lcon(trp->edges_->front().get_edge(), trp->lcon_idx_).trips_;
}
void apply_reroute(universe& uv, capacity_maps const& caps,
schedule const& sched, trip const* trp,
trip_data_index const tdi,
std::vector<trip_ev_key> const& old_route,
std::vector<trip_ev_key> const& new_route,
std::vector<edge_index>& updated_interchange_edges) {
auto const encoded_capacity =
encode_capacity(guess_trip_capacity(sched, caps, trp));
auto const affected_passenger_groups = collect_passenger_groups(uv, tdi);
auto diff = diff_route(old_route, new_route);
std::vector<event_node*> new_nodes;
std::set<event_node*> removed_nodes;
std::set<event_node*>
reactivated_nodes; // TODO(pablo): remove from td.canceled_nodes?
for (auto const& [op, tek] : diff) {
switch (op) {
case diff_op::KEEP: {
new_nodes.emplace_back(tek.node_);
break;
}
case diff_op::REMOVE: {
tek.node_->valid_ = false;
removed_nodes.insert(tek.node_);
break;
}
case diff_op::INSERT: {
auto new_node = get_or_insert_node(uv, tdi, tek, reactivated_nodes);
new_nodes.emplace_back(new_node);
break;
}
}
}
auto edges = uv.trip_data_.edges(tdi);
edges.clear();
if (!new_nodes.empty()) {
auto const merged_trips = get_merged_trips(trp).value();
for (auto const& [from, to] : utl::pairwise(new_nodes)) {
auto e = connect_nodes(from, to, merged_trips, encoded_capacity, uv);
if (e->is_trip()) {
edges.emplace_back(get_edge_index(uv, e));
}
}
}
auto canceled_nodes = uv.trip_data_.canceled_nodes(tdi);
for (auto const* n : removed_nodes) {
canceled_nodes.emplace_back(n->index(uv));
}
for (auto pg : affected_passenger_groups) {
update_passenger_group(tdi, trp, pg, uv);
}
for (auto* n : removed_nodes) {
for (auto& e : n->outgoing_edges(uv)) {
if (e.type_ == edge_type::INTERCHANGE) {
updated_interchange_edges.emplace_back(get_edge_index(uv, &e));
}
}
for (auto& e : n->incoming_edges(uv)) {
if (e.type_ == edge_type::INTERCHANGE) {
updated_interchange_edges.emplace_back(get_edge_index(uv, &e));
}
}
}
for (auto* n : reactivated_nodes) {
for (auto& e : n->outgoing_edges(uv)) {
if (e.type_ == edge_type::INTERCHANGE) {
updated_interchange_edges.emplace_back(get_edge_index(uv, &e));
}
}
for (auto& e : n->incoming_edges(uv)) {
if (e.type_ == edge_type::INTERCHANGE) {
updated_interchange_edges.emplace_back(get_edge_index(uv, &e));
}
}
}
}
} // namespace motis::paxmon
| 32.64497 | 80 | 0.62389 | [
"vector"
] |
060f06ce4c68fb3e359fcd50cc5853b2c6f474d4 | 8,471 | cpp | C++ | ewsclient/ewssyncfolderitemsrequest.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 122 | 2016-03-01T12:53:43.000Z | 2021-11-06T21:14:21.000Z | ewsclient/ewssyncfolderitemsrequest.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 54 | 2016-05-02T10:05:47.000Z | 2022-02-01T18:10:38.000Z | ewsclient/ewssyncfolderitemsrequest.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 17 | 2016-05-18T21:02:08.000Z | 2022-01-27T20:33:26.000Z | /* This file is part of Akonadi EWS Resource
Copyright (C) 2015-2017 Krzysztof Nowicki <krissn@op.pl>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "ewssyncfolderitemsrequest.h"
#include <memory>
#include <QXmlStreamWriter>
#include "ewsclient_debug.h"
#include "ewsxml.h"
enum SyncFolderItemsResponseElementType {
SyncState,
IncludesLastItemInRange,
Changes
};
enum SyncFolderItemsChangeElementType {
Item,
ItemId,
IsRead
};
class EwsSyncFolderItemsRequest::Response : public EwsRequest::Response
{
public:
Response(QXmlStreamReader &reader);
static bool changeReader(QXmlStreamReader &reader, QVariant &val);
EwsSyncFolderItemsRequest::Change::List mChanges;
bool mIncludesLastItem;
QString mSyncState;
};
EwsSyncFolderItemsRequest::EwsSyncFolderItemsRequest(EwsClient& client, QObject *parent)
: EwsRequest(client, parent), mMaxChanges(100), mIncludesLastItem(false)
{
qRegisterMetaType<EwsSyncFolderItemsRequest::Change::List>();
qRegisterMetaType<EwsItem>();
}
EwsSyncFolderItemsRequest::~EwsSyncFolderItemsRequest()
{
}
void EwsSyncFolderItemsRequest::setFolderId(const EwsId &id)
{
mFolderId = id;
}
void EwsSyncFolderItemsRequest::setItemShape(const EwsItemShape &shape)
{
mShape = shape;
}
void EwsSyncFolderItemsRequest::setSyncState(const QString &state)
{
mSyncState = state;
}
void EwsSyncFolderItemsRequest::setMaxChanges(uint max)
{
mMaxChanges = max;
}
void EwsSyncFolderItemsRequest::start()
{
QString reqString;
QXmlStreamWriter writer(&reqString);
startSoapDocument(writer);
writer.writeStartElement(ewsMsgNsUri, QStringLiteral("SyncFolderItems"));
mShape.write(writer);
writer.writeStartElement(ewsMsgNsUri, QStringLiteral("SyncFolderId"));
mFolderId.writeFolderIds(writer);
writer.writeEndElement();
if (!mSyncState.isNull()) {
writer.writeTextElement(ewsMsgNsUri, QStringLiteral("SyncState"), mSyncState);
}
writer.writeTextElement(ewsMsgNsUri, QStringLiteral("MaxChangesReturned"),
QString::number(mMaxChanges));
writer.writeEndElement();
endSoapDocument(writer);
qCDebug(EWSRES_PROTO_LOG) << reqString;
if (EWSRES_REQUEST_LOG().isDebugEnabled()) {
QString st = mSyncState.isNull() ? QStringLiteral("none") : ewsHash(mSyncState);
QString folder;
qCDebugNCS(EWSRES_REQUEST_LOG) << QStringLiteral("Starting SyncFolderItems request (folder: ")
<< mFolderId << QStringLiteral(", state: %1").arg(st);
}
prepare(reqString);
doSend();
}
bool EwsSyncFolderItemsRequest::parseResult(QXmlStreamReader &reader)
{
return parseResponseMessage(reader, QStringLiteral("SyncFolderItems"),
[this](QXmlStreamReader &reader) {return parseItemsResponse(reader);});
}
bool EwsSyncFolderItemsRequest::parseItemsResponse(QXmlStreamReader &reader)
{
EwsSyncFolderItemsRequest::Response *resp = new EwsSyncFolderItemsRequest::Response(reader);
if (resp->responseClass() == EwsResponseUnknown) {
return false;
}
mChanges = resp->mChanges;
mIncludesLastItem = resp->mIncludesLastItem;
mSyncState = resp->mSyncState;
if (EWSRES_REQUEST_LOG().isDebugEnabled()) {
if (resp->isSuccess()) {
qCDebugNC(EWSRES_REQUEST_LOG) << QStringLiteral("Got SyncFolderItems response (%1 changes, last included: %2, state: %3)")
.arg(mChanges.size()).arg(mIncludesLastItem ? QStringLiteral("true") : QStringLiteral("false"))
.arg(qHash(mSyncState), 0, 36);
}
else {
qCDebugNC(EWSRES_REQUEST_LOG) << QStringLiteral("Got SyncFolderItems response - %1")
.arg(resp->responseMessage());
}
}
return true;
}
EwsSyncFolderItemsRequest::Response::Response(QXmlStreamReader &reader)
: EwsRequest::Response(reader)
{
if (mClass == EwsResponseParseError) {
return;
}
static const QVector<EwsXml<SyncFolderItemsResponseElementType>::Item> items = {
{SyncState, QStringLiteral("SyncState"), &ewsXmlTextReader},
{IncludesLastItemInRange, QStringLiteral("IncludesLastItemInRange"), &ewsXmlBoolReader},
{Changes, QStringLiteral("Changes"), &EwsSyncFolderItemsRequest::Response::changeReader},
};
static const EwsXml<SyncFolderItemsResponseElementType> staticReader(items);
EwsXml<SyncFolderItemsResponseElementType> ewsReader(staticReader);
if (!ewsReader.readItems(reader, ewsMsgNsUri,
[this](QXmlStreamReader &reader, const QString &) {
if (!readResponseElement(reader)) {
setErrorMsg(QStringLiteral("Failed to read EWS request - invalid response element."));
return false;
}
return true;
}))
{
mClass = EwsResponseParseError;
return;
}
QHash<SyncFolderItemsResponseElementType, QVariant> values = ewsReader.values();
mSyncState = values[SyncState].toString();
mIncludesLastItem = values[IncludesLastItemInRange].toBool();
mChanges = values[Changes].value<Change::List>();
}
bool EwsSyncFolderItemsRequest::Response::changeReader(QXmlStreamReader &reader, QVariant &val)
{
Change::List changes;
QString elmName(reader.name().toString());
while (reader.readNextStartElement()) {
Change change(reader);
if (!change.isValid()) {
qCWarningNC(EWSRES_LOG) << QStringLiteral("Failed to read %1 element").arg(elmName);
return false;
}
changes.append(change);
}
val = QVariant::fromValue<Change::List>(changes);
return true;
}
EwsSyncFolderItemsRequest::Change::Change(QXmlStreamReader &reader)
{
static const QVector<EwsXml<SyncFolderItemsChangeElementType>::Item> items = {
{Item, QStringLiteral("Item"), &ewsXmlItemReader},
{Item, QStringLiteral("Message"), &ewsXmlItemReader},
{Item, QStringLiteral("CalendarItem"), &ewsXmlItemReader},
{Item, QStringLiteral("Contact"), &ewsXmlItemReader},
{Item, QStringLiteral("DistributionList"), &ewsXmlItemReader},
{Item, QStringLiteral("MeetingMessage"), &ewsXmlItemReader},
{Item, QStringLiteral("MeetingRequest"), &ewsXmlItemReader},
{Item, QStringLiteral("MeetingResponse"), &ewsXmlItemReader},
{Item, QStringLiteral("MeetingCancellation"), &ewsXmlItemReader},
{Item, QStringLiteral("Task"), &ewsXmlItemReader},
{ItemId, QStringLiteral("ItemId"), &ewsXmlIdReader},
{IsRead, QStringLiteral("IsRead"), &ewsXmlBoolReader}
};
static const EwsXml<SyncFolderItemsChangeElementType> staticReader(items);
EwsXml<SyncFolderItemsChangeElementType> ewsReader(staticReader);
if (reader.name() == QStringLiteral("Create")) {
mType = Create;
}
else if (reader.name() == QStringLiteral("Update")) {
mType = Update;
}
else if (reader.name() == QStringLiteral("Delete")) {
mType = Delete;
}
else if (reader.name() == QStringLiteral("ReadFlagChange")) {
mType = ReadFlagChange;
}
if (!ewsReader.readItems(reader, ewsTypeNsUri)) {
return;
}
QHash<SyncFolderItemsChangeElementType, QVariant> values = ewsReader.values();
switch (mType) {
case Create:
case Update:
mItem = values[Item].value<EwsItem>();
mId = mItem[EwsItemFieldItemId].value<EwsId>();
break;
case ReadFlagChange:
mIsRead = values[IsRead].toBool();
/* fall through */
case Delete:
mId = values[ItemId].value<EwsId>();
break;
default:
break;
}
}
| 32.087121 | 134 | 0.685751 | [
"shape"
] |
061112156a3eac1a5cce96f4739a4b8e55b6a8d5 | 6,623 | hpp | C++ | redemption/src/transport/crypto_transport.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/transport/crypto_transport.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/transport/crypto_transport.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Product name: redemption, a FLOSS RDP proxy
* Copyright (C) Wallix 2010-2017
* Author(s): Christophe Grosjean, Raphael Zhou, Jonathan Poelen, Meng Tan, Clément Moroldo
*/
#pragma once
#include "capture/cryptofile.hpp"
#include "utils/sugar/bytes_view.hpp"
#include "utils/file_permissions.hpp"
#include "transport/file_transport.hpp"
#include <memory>
// "MFCW"
constexpr uint32_t WABCRYPTOFILE_MAGIC = 0x4D464357;
constexpr uint32_t WABCRYPTOFILE_EOF_MAGIC = 0x5743464D;
constexpr uint32_t WABCRYPTOFILE_VERSION = 0x00000001;
constexpr std::size_t CRYPTO_BUFFER_SIZE = 4096 * 4;
class Random;
class InCryptoTransport : public Transport //, public PartialIO
{
public:
enum class EncryptionMode { Auto, Encrypted, NotEncrypted };
explicit InCryptoTransport(CryptoContext & cctx, EncryptionMode encryption_mode) noexcept;
~InCryptoTransport();
[[nodiscard]] bool is_encrypted() const;
[[nodiscard]] bool is_open() const;
struct HASH {
uint8_t hash[MD_HASH::DIGEST_LENGTH];
};
// is noexcept
[[nodiscard]] static bool read_qhash(
const char * pathname, uint8_t const (&hmac_key)[HMAC_KEY_LENGTH], HASH& result_hash);
// is noexcept
[[nodiscard]] static bool read_fhash(
const char * pathname, uint8_t const (&hmac_key)[HMAC_KEY_LENGTH], HASH& result_hash);
void open(const char * const pathname, bytes_view derivator);
// derivator implicitly basename(pathname)
void open(const char * const pathname);
void close();
bool is_eof() const noexcept;
void disable_log_decrypt(bool disable = true) noexcept; /*NOLINT*/
private:
// this perform atomic read, partial read will result in exception
void raw_read(uint8_t buffer[], const size_t len);
size_t do_partial_read(uint8_t * buffer, size_t len) override;
Read do_atomic_read(uint8_t * buffer, size_t len) override;
int fd;
bool eof;
uint64_t file_len;
uint64_t current_len;
CryptoContext & cctx;
char clear_data[CRYPTO_BUFFER_SIZE]; // contains either raw data from unencrypted file
// or already decrypted/decompressed data
uint32_t clear_pos; // current position in clear_data buf
uint32_t raw_size; // the unciphered/uncompressed data available in buffer
DecryptContext ectx;
unsigned int MAX_CIPHERED_SIZE; // = MAX_COMPRESSED_SIZE + AES_BLOCK_SIZE;
EncryptionMode encryption_mode;
bool encrypted;
struct EncryptedBufferHandle
{
void allocate(std::size_t n);
uint8_t* raw_buffer(std::size_t encrypted_len);
uint8_t* decrypted_buffer(std::size_t encrypted_len);
private:
std::unique_ptr<uint8_t[]> full_buf;
std::size_t size = 0;
};
EncryptedBufferHandle enc_buffer_handle;
};
struct ocrypto : noncopyable
{
struct Result {
bytes_view buf;
std::size_t consumed;
};
using HashArray = uint8_t[MD_HASH::DIGEST_LENGTH];
ocrypto(CryptoContext & cctx, Random & rnd);
~ocrypto();
Result open(bytes_view derivator);
ocrypto::Result close(HashArray & qhash, HashArray & fhash);
ocrypto::Result write(bytes_view data);
private:
EncryptContext ectx;
SslHMAC_Sha256_Delayed hm; // full hash context
SslHMAC_Sha256_Delayed hm4k; // quick hash context
uint32_t pos; // current position in buf
uint32_t raw_size; // the unciphered/uncompressed file size
uint64_t file_size; // the current file size
uint8_t header_buf[40];
uint8_t result_buffer[65536] = {};
char buf[CRYPTO_BUFFER_SIZE]; //
CryptoContext & cctx;
Random & rnd;
/* Flush procedure (compression, encryption)
* Return 0 on success, negatif on error
*/
void flush(uint8_t * buffer, size_t buflen, size_t & towrite);
void update_hmac(bytes_view buf);
};
class OutCryptoTransport : public Transport
{
public:
using HashArray = ocrypto::HashArray;
explicit OutCryptoTransport(
CryptoContext & cctx, Random & rnd,
std::function<void(const Error & error)> notify_error
) noexcept;
[[nodiscard]] const char * get_finalname() const noexcept { return this->finalname; }
~OutCryptoTransport();
// TODO: CGR: I want to remove that from Transport API
bool disconnect() override;
[[nodiscard]] bool is_open() const;
void open(const char * const finalname, const char * const hash_filename, int groupid, FilePermissions file_permissions, bytes_view derivator);
// derivator implicitly basename(finalname)
void open(const char * finalname, const char * const hash_filename, int groupid, FilePermissions file_permissions);
void close(HashArray & qhash, HashArray & fhash);
void create_hash_file(HashArray const & qhash, HashArray const & fhash);
void do_send(const uint8_t * data, size_t len) override;
bool cancel();
private:
ocrypto encrypter;
OutFileTransport out_file;
char tmpname[2048];
char finalname[2048];
std::string hash_filename;
CryptoContext & cctx;
Random & rnd;
int groupid;
std::vector<uint8_t> derivator;
};
enum class EncryptionSchemeTypeResult
{
Error = -1,
NoEncrypted = 0,
OldScheme,
NewScheme,
};
EncryptionSchemeTypeResult get_encryption_scheme_type(
CryptoContext & cctx, const char * filename, bytes_view derivator, Error * err);
/// \attention if result is \c EncryptionSchemeTypeResult::OldScheme, the CryptoContext::old_encryption_scheme must be set to 1 and the file reopen because some data are lost
EncryptionSchemeTypeResult open_if_possible_and_get_encryption_scheme_type(
InCryptoTransport & in, const char * filename, bytes_view derivator, Error * err);
| 30.242009 | 174 | 0.6947 | [
"vector"
] |
06155ec503ac038a1f57f3ec4d3c00debe1554b6 | 2,953 | cpp | C++ | depends/tinythreadpp/tests/future.cpp | asmodehn/WkCore | bb630656c6184ec27591d3ca0d3b18983845b567 | [
"BSD-2-Clause"
] | 4 | 2016-01-24T00:25:36.000Z | 2019-05-31T09:14:40.000Z | depends/tinythreadpp/tests/future.cpp | asmodehn/WkCore | bb630656c6184ec27591d3ca0d3b18983845b567 | [
"BSD-2-Clause"
] | null | null | null | depends/tinythreadpp/tests/future.cpp | asmodehn/WkCore | bb630656c6184ec27591d3ca0d3b18983845b567 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2012 Jared Duke
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <algorithm>
#include <iostream>
#include <vector>
#define USE_TTHREAD 1
#if USE_TTHREAD
#include <tinythread.h>
#include <tinythread_async.h>
#include <tinythread_future.h>
#define USE_CONTINUATIONS
using namespace tthread;
#else
#include <chrono>
#include <thread>
#include <future>
#endif
using namespace std;
int ackermann(int m, int n) {
if (m == 0) return n + 1;
if (n == 0) return ackermann(m - 1, 1);
return ackermann(m - 1, ackermann(m, n - 1));
}
int main() {
///////////////////////////////////////////////////////////////////////////
#if defined(USE_CONTINUATIONS)
try {
cout << "f(g0(g1(g2(g3()))) = 1*(2*(3*(4*(5)))) = " <<
async([]() {
return 5;
}).then([](int x) {
return x * 4;
}).then([](int x) {
return x * 3;
}).then([](int x) {
return x * 2;
}).then([](int x) {
return x;
}).get() << endl << endl;
} catch (...) {
cout << "Error in async continuation." << endl << endl;
}
#endif
///////////////////////////////////////////////////////////////////////////
cout << "Main thread id: " << this_thread::get_id() << endl;
vector<future<void>> futures;
for (int i = 0; i < 8; ++i) {
futures.emplace_back(async([] {
this_thread::sleep_for(chrono::milliseconds(100));
cout << this_thread::get_id() << " ";
}));
}
for_each(futures.begin(), futures.end(), [](future<void>& f) {
f.wait();
});
cout << endl << endl;
///////////////////////////////////////////////////////////////////////////
packaged_task<int(void)> task(bind(&ackermann, 3, 11));
auto f = task.get_future();
task();
cout << "Sync: Ackerman(3,11) = " << f.get() << endl << endl;
///////////////////////////////////////////////////////////////////////////
vector<future<int>> futures2;
for (int i = 0; i < 8; ++i) {
futures2.emplace_back(async(bind(&ackermann, 3, 11)));
}
for_each(futures2.begin(), futures2.end(), [=](future<int>& f) {
std::cout << "Async: Ackerman(3,11) = " << f.get() << endl;
});
cout << endl << endl;
///////////////////////////////////////////////////////////////////////////
}
| 27.091743 | 78 | 0.563495 | [
"vector"
] |
0617028a605c796243b4983ba9cc946b8ffbc695 | 1,073 | cpp | C++ | src/Entity/Impl/Multimedia.cpp | Allaeddineattia/Valravn | 7afa00bfe3c6f0c8357209601a67508a35b466b5 | [
"MIT"
] | null | null | null | src/Entity/Impl/Multimedia.cpp | Allaeddineattia/Valravn | 7afa00bfe3c6f0c8357209601a67508a35b466b5 | [
"MIT"
] | null | null | null | src/Entity/Impl/Multimedia.cpp | Allaeddineattia/Valravn | 7afa00bfe3c6f0c8357209601a67508a35b466b5 | [
"MIT"
] | 2 | 2021-05-07T20:35:55.000Z | 2021-07-08T15:14:43.000Z | //
// Created by alro on 18/10/2020.
//
#include "Entity/Contract/Multimedia.h"
unsigned int Multimedia::getId() const {
return id;
}
string_view Multimedia::getPath() const {
return path;
}
size_t Multimedia::getSize() const {
return size;
}
string_view Multimedia::getMimeType() const {
return mimeType;
}
Multimedia::Multimedia(unsigned int id, string_view path, size_t size, string_view mimeType) : id(id), path(path),
size(size),
mimeType(mimeType) {}
unique_ptr<Multimedia> Multimedia::fetch_by_id(int T) {
return unique_ptr<Multimedia>();
}
vector<unique_ptr<Multimedia>> Multimedia::get_all() {
return vector<unique_ptr<Multimedia>>();
}
bool Multimedia::operator==(const Multimedia &rhs) const {
return id == rhs.id &&
path == rhs.path &&
mimeType == rhs.mimeType &&
size == rhs.size;
}
Multimedia::~Multimedia() {
}
| 23.326087 | 114 | 0.562908 | [
"vector"
] |
0618d3838aba4c9414a4dbe3cead71937fe4a37b | 5,560 | hpp | C++ | src/include/migraphx/op/deconvolution.hpp | raramakr/AMDMIGraphX | 83e7425367f6ce850ec28fe716fe7c23ce34c79f | [
"MIT"
] | 72 | 2018-12-06T18:31:17.000Z | 2022-03-30T15:01:02.000Z | src/include/migraphx/op/deconvolution.hpp | raramakr/AMDMIGraphX | 83e7425367f6ce850ec28fe716fe7c23ce34c79f | [
"MIT"
] | 1,006 | 2018-11-30T16:32:33.000Z | 2022-03-31T22:43:39.000Z | src/include/migraphx/op/deconvolution.hpp | raramakr/AMDMIGraphX | 83e7425367f6ce850ec28fe716fe7c23ce34c79f | [
"MIT"
] | 36 | 2019-05-07T10:41:46.000Z | 2022-03-28T15:59:56.000Z | #ifndef MIGRAPHX_GUARD_OPERATORS_DECONVOLUTION_HPP
#define MIGRAPHX_GUARD_OPERATORS_DECONVOLUTION_HPP
#include <array>
#include <migraphx/op/common.hpp>
#include <migraphx/check_shapes.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/streamutils.hpp>
#include <migraphx/literal.hpp>
#include <migraphx/shape_for_each.hpp>
#include <migraphx/config.hpp>
#include <migraphx/dfor.hpp>
#include <migraphx/par_dfor.hpp>
#include <cmath>
#include <utility>
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace op {
struct deconvolution
{
std::vector<std::size_t> padding = {0, 0};
std::vector<std::size_t> stride = {1, 1};
std::vector<std::size_t> dilation = {1, 1};
padding_mode_t padding_mode = default_;
int group = 1;
template <class Self, class F>
static auto reflect(Self& self, F f)
{
return pack(f(self.padding, "padding"),
f(self.stride, "stride"),
f(self.dilation, "dilation"),
f(self.padding_mode, "padding_mode"),
f(self.group, "group"));
}
std::string name() const { return "deconvolution"; }
void check_attribute_size() const
{
if(not((padding.size() == stride.size() or (padding.size() / 2) == stride.size()) and
stride.size() == dilation.size()))
{
MIGRAPHX_THROW("deconvolution: inconsistent attribute sizes");
}
}
shape compute_shape(std::vector<shape> inputs) const
{
check_shapes{inputs, *this}.has(2).same_type().same_ndims().min_ndims(3);
const shape& input = inputs.at(0);
const shape& weights = inputs.at(1);
size_t kdims = input.lens().size() - 2;
if(kdims != this->kdims())
{
MIGRAPHX_THROW("deconvolution: input k-dims does not match attribute size");
}
std::vector<size_t> output_lens{input.lens()[0], weights.lens()[1]};
for(size_t i = 0; i < kdims; i++)
{
output_lens.push_back(std::size_t(std::max<std::ptrdiff_t>(
1,
stride[i] * (input.lens()[i + 2] - 1) +
((weights.lens()[i + 2] - 1) * dilation[i] + 1) - 2 * padding[i])));
}
return inputs[0].with_lens(output_lens);
}
argument compute(shape output_shape, std::vector<argument> args) const
{
argument result{output_shape};
auto kdims = this->kdims();
visit_all(result, args[0], args[1])([&](auto output, auto input, auto weights) {
using type = typename decltype(output)::value_type;
std::fill(output.begin(), output.end(), type{0});
auto in_lens = input.get_shape().lens();
auto in_n = in_lens[0];
auto in_c = in_lens[1];
auto wei = weights.get_shape().lens();
auto wei_n = wei[0];
auto wei_c = wei[1];
auto out_lens = output_shape.lens();
std::vector<std::size_t> win_size{in_c};
std::copy(in_lens.begin() + 2, in_lens.end(), std::back_inserter(win_size));
std::copy(wei.begin() + 2, wei.end(), std::back_inserter(win_size));
shape win_shape{output_shape.type(), win_size};
par_dfor(in_n, wei_c)([&](int o, int k) {
shape_for_each(win_shape, [&](auto idx_win) {
const int w = idx_win[0];
auto input_dims_start = idx_win.begin() + 1;
auto wei_dims_start = idx_win.begin() + kdims + 1;
std::vector<std::ptrdiff_t> win_start;
for(std::size_t n = 0; n < kdims; ++n)
{
win_start.push_back(std::ptrdiff_t(*(input_dims_start + n) * stride[n]) -
std::ptrdiff_t(padding[n]));
}
const int group_id = w / (wei_n / group);
const int in_ch = group_id * wei_c + k;
std::vector<std::ptrdiff_t> idx_out{o, in_ch};
for(size_t n = 0; n < kdims; n++)
{
idx_out.push_back(win_start[n] + *(wei_dims_start + n) * dilation[n]);
}
std::vector<std::ptrdiff_t> idx_wei{w, k};
std::copy(wei_dims_start, idx_win.end(), std::back_inserter(idx_wei));
std::vector<std::ptrdiff_t> idx_in{o, w};
std::copy(input_dims_start, wei_dims_start, std::back_inserter(idx_in));
if(std::all_of(
idx_out.begin() + 2, idx_out.end(), [&](auto ii) { return ii >= 0; }) and
std::equal(idx_out.begin() + 2,
idx_out.end(),
out_lens.begin() + 2,
out_lens.end(),
std::less<std::ptrdiff_t>{}))
{
output(idx_out.begin(), idx_out.end()) +=
input(idx_in.begin(), idx_in.end()) *
weights(idx_wei.begin(), idx_wei.end());
}
});
});
});
return result;
}
size_t kdims() const
{
check_attribute_size();
return stride.size();
}
};
} // namespace op
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx
#endif
| 34.320988 | 100 | 0.513849 | [
"shape",
"vector"
] |
0619fd9a91f5e4f2ab8afbac4ae86f38fb954efb | 6,929 | hpp | C++ | src/kernel/lib/yask.hpp | gperrotta/yask | a35aa5a6f52bb5a11c182045c469a55a84fa9b36 | [
"MIT"
] | null | null | null | src/kernel/lib/yask.hpp | gperrotta/yask | a35aa5a6f52bb5a11c182045c469a55a84fa9b36 | [
"MIT"
] | null | null | null | src/kernel/lib/yask.hpp | gperrotta/yask | a35aa5a6f52bb5a11c182045c469a55a84fa9b36 | [
"MIT"
] | null | null | null | /*****************************************************************************
YASK: Yet Another Stencil Kit
Copyright (c) 2014-2019, Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*****************************************************************************/
// This file defines functions, types, and macros needed for common
// (non-stencil-specific) code. This file does not input generated files.
#pragma once
#include "yask_assert.hpp"
// Choose features
#define _POSIX_C_SOURCE 200809L
// MPI or stubs.
// This must come before including the API header to make sure
// MPI_VERSION is defined.
#ifdef USE_MPI
#include "mpi.h"
#else
#define MPI_Barrier(comm) ((void)0)
#define MPI_Finalize() ((void)0)
typedef int MPI_Comm;
typedef int MPI_Win;
typedef int MPI_Group;
typedef int MPI_Request;
#define MPI_PROC_NULL (-1)
#define MPI_COMM_NULL ((MPI_Comm)0x04000000)
#define MPI_REQUEST_NULL ((MPI_Request)0x2c000000)
#define MPI_GROUP_NULL ((MPI_Group)0x08000000)
#ifdef MPI_VERSION
#undef MPI_VERSION
#endif
#endif
// Include the API as early as possible. This helps to ensure that it will stand alone.
#include "yask_kernel_api.hpp"
// Standard C and C++ headers.
#include <algorithm>
#include <cmath>
#include <cfloat>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <limits.h>
#include <malloc.h>
#include <map>
#include <unordered_map>
#include <set>
#include <sstream>
#include <stddef.h>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <time.h>
#include <vector>
#include <unistd.h>
#include <stdint.h>
#include <immintrin.h>
#include <sys/mman.h>
#ifdef USE_PMEM
#include <memkind.h>
#include <sys/syscall.h>
#endif
// Conditional inlining
#if defined(USE_ALWAYS_INLINE) && !defined(CHECK)
#define ALWAYS_INLINE __attribute__((always_inline)) inline
#else
#define ALWAYS_INLINE inline
#endif
// Additional type for unsigned indices.
typedef std::uint64_t uidx_t;
// Common utilities.
#include "common_utils.hpp"
// Floored integer divide and mod.
#include "idiv.hpp"
// Combinations.
#include "combo.hpp"
// Simple macros and stubs.
#ifdef WIN32
#define _Pragma(x)
#endif
#ifndef NO_VEC
#define _NO_VECTOR _Pragma("novector")
#define _VEC_ALIGNED _Pragma("vector aligned")
#define _VEC_UNALIGNED _Pragma("vector unaligned")
#define _VEC_ALWAYS _Pragma("vector always")
#define _VEC_STREAMING _Pragma("vector nontemporal")
#else
#define _NO_VECTOR
#define _VEC_ALIGNED
#define _VEC_UNALIGNED
#define _VEC_ALWAYS
#define _VEC_STREAMING
#endif
#ifndef NO_SIMD
#define _SIMD _Pragma("omp simd")
#else
#define _SIMD
#endif
#ifndef NO_UNROLL
#define _UNROLL _Pragma("unroll")
#else
#define _UNROLL
#endif
#ifdef NO_ASSUME
#define __assume(x) ((void)0)
#define __assume_aligned(p,n) ((void)0)
#endif
// VTune or stubs.
#ifdef USE_VTUNE
#include "ittnotify.h"
#define VTUNE_PAUSE __itt_pause()
#define VTUNE_RESUME __itt_resume()
#else
#define VTUNE_PAUSE ((void)0)
#define VTUNE_RESUME ((void)0)
#endif
// Stringizing hacks for the C preprocessor.
#define YSTR1(s) #s
#define YSTR2(s) YSTR1(s)
// Default alloc settings.
#define CACHELINE_BYTES (64)
#define YASK_PAD (3) // cache-lines between data buffers.
#define YASK_PAD_BYTES (CACHELINE_BYTES * YASK_PAD)
#define YASK_HUGE_ALIGNMENT (2 * 1024 * 1024) // 2MiB-page for large allocs.
#define CACHE_ALIGNED __attribute__ ((aligned (CACHELINE_BYTES)))
#ifndef USE_NUMA
#undef NUMA_PREF
#define NUMA_PREF yask_numa_none
#elif !defined NUMA_PREF
#define NUMA_PREF yask_numa_local
#endif
// Macro for debug message.
// 'os is an ostream.
#define DEBUG_MSG0(os, msg) do { \
KernelEnv::set_debug_lock(); \
(os) << std::boolalpha << std::dec << \
msg << std::endl << std::flush; \
KernelEnv::unset_debug_lock(); \
} while(0)
// 'state' is a pointer to a KernelState.
#define DEBUG_MSG1(state, msg) do { \
if (state->_env->_debug.get()) { \
auto& os = state->_env->_debug.get()->get_ostream(); \
DEBUG_MSG0(os, msg); \
} } while(0)
// Macro for debug message when 'state' is defined.
#define DEBUG_MSG(msg) DEBUG_MSG1(state, msg)
// Macro for trace message.
// Enabled only if compiled with TRACE macro and run with -trace option.
#ifdef TRACE
// 'os is an ostream.
#define TRACE_MSG0(os, msg) do { \
if (state->_env->_trace) { \
DEBUG_MSG0(os, "YASK: " << msg); \
} } while(0)
// 'state' is a pointer to a KernelState.
#define TRACE_MSG1(state, msg) do { \
if (state->_env->_trace) { \
DEBUG_MSG1(state, "YASK: " << msg); \
} } while(0)
#else
#define TRACE_MSG0(os, msg) ((void)0)
#define TRACE_MSG1(state, msg) ((void)0)
#endif
// Macro for trace message when 'state' is defined.
#define TRACE_MSG(msg) TRACE_MSG1(state, msg)
// Macro for mem-trace when 'state' is defined.
// Enabled only if compiled with TRACE_MEM macro and run with -trace option.
#ifdef TRACE_MEM
#define TRACE_MEM_MSG(msg) TRACE_MSG1(state, msg)
#else
#define TRACE_MEM_MSG(msg) ((void)0)
#endif
// breakpoint.
#define INT3 asm volatile("int $3")
// L1 and L2 hints
#define L1_HINT _MM_HINT_T0
#define L2_HINT _MM_HINT_T1
// Set MODEL_CACHE to 1 or 2 to model L1 or L2.
#ifdef MODEL_CACHE
#include "cache_model.hpp"
extern yask::Cache cache_model;
#if MODEL_CACHE==L1
#warning Modeling L1 cache
#elif MODEL_CACHE==L2
#warning Modeling L2 cache
#else
#warning Modeling UNKNOWN cache
#endif
#endif
// Other utilities.
#include "utils.hpp"
#include "tuple.hpp"
| 27.605578 | 87 | 0.68336 | [
"vector",
"model"
] |
061c3e57ad4e6ddd431eb95edd969470de35a27c | 13,684 | cc | C++ | mindspore/lite/tools/optimizer/fusion/layer_norm_fusion.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | 55 | 2020-12-17T10:26:06.000Z | 2022-03-28T07:18:26.000Z | mindspore/lite/tools/optimizer/fusion/layer_norm_fusion.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/optimizer/fusion/layer_norm_fusion.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | 14 | 2021-01-29T02:39:47.000Z | 2022-03-23T05:00:26.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tools/optimizer/fusion/layer_norm_fusion.h"
#include <memory>
#include "src/ops/primitive_c.h"
#include "src/param_value_lite.h"
#include "schema/inner/model_generated.h"
#include "utils/utils.h"
#include "tools/optimizer/common/gllo_utils.h"
#include "securec/include/securec.h"
#include "src/ops/add.h"
#include "src/ops/mul.h"
#include "src/ops/rsqrt.h"
#include "src/ops/reduce.h"
#include "src/ops/sub.h"
namespace mindspore {
namespace opt {
namespace {
constexpr size_t kAddInputsLength = 3;
constexpr size_t kSubInputsLength = 3;
constexpr size_t kMulInputsLength = 3;
constexpr size_t kRsqrtInputsLength = 2;
constexpr size_t kReduceInputsLength = 2;
bool IsAddNode(const BaseRef &n) {
if (utils::isa<CNodePtr>(n) || utils::isa<ValueNodePtr>(n)) {
auto type = opt::GetCNodeType(n);
return type == schema::PrimitiveType_Add;
}
return false;
}
bool IsSquaredDifferenceNode(const BaseRef &n) {
if (utils::isa<CNodePtr>(n) || utils::isa<ValueNodePtr>(n)) {
auto type = opt::GetCNodeType(n);
return type == schema::PrimitiveType_SquaredDifference;
}
return false;
}
bool IsReduceNode(const BaseRef &n) {
if (utils::isa<CNodePtr>(n) || utils::isa<ValueNodePtr>(n)) {
auto type = opt::GetCNodeType(n);
return type == schema::PrimitiveType_Reduce;
}
return false;
}
bool IsRsqrtNode(const BaseRef &n) {
if (utils::isa<CNodePtr>(n) || utils::isa<ValueNodePtr>(n)) {
auto type = opt::GetCNodeType(n);
return type == schema::PrimitiveType_Rsqrt;
}
return false;
}
bool IsMulNode(const BaseRef &n) {
if (utils::isa<CNodePtr>(n) || utils::isa<ValueNodePtr>(n)) {
auto type = opt::GetCNodeType(n);
return type == schema::PrimitiveType_Mul;
}
return false;
}
bool IsSubNode(const BaseRef &n) {
if (utils::isa<CNodePtr>(n) || utils::isa<ValueNodePtr>(n)) {
auto type = opt::GetCNodeType(n);
return type == schema::PrimitiveType_Sub;
}
return false;
}
} // namespace
const BaseRef LayerNormFusion::DefinePattern() const {
auto mean1 = std::make_shared<CondVar>(IsReduceNode);
VectorRef mean1_ref = VectorRef({mean1, input_});
auto squared_diffference1 = std::make_shared<CondVar>(IsSquaredDifferenceNode);
VectorRef squared_diffference1_ref = VectorRef({squared_diffference1, input_, mean1_ref});
auto mul1 = std::make_shared<CondVar>(IsMulNode);
auto mean2 = std::make_shared<CondVar>(IsReduceNode);
VectorRef mean2_ref = VectorRef({mean2, squared_diffference1_ref});
auto add1 = std::make_shared<CondVar>(IsAddNode);
VectorRef add1_ref = VectorRef({add1, mean2_ref, epsilon_});
auto rsqrt1 = std::make_shared<CondVar>(IsRsqrtNode);
VectorRef rsqrt1_ref = VectorRef({rsqrt1, add1_ref});
auto mul2 = std::make_shared<CondVar>(IsMulNode);
VectorRef mul2_ref = VectorRef({mul2, rsqrt1_ref, gamma_});
VectorRef mul1_ref = VectorRef({mul1, input_, mul2_ref});
auto mul3 = std::make_shared<CondVar>(IsMulNode);
VectorRef mul3_ref = VectorRef({mul3, mean1_ref, mul2_ref});
auto sub1 = std::make_shared<CondVar>(IsSubNode);
VectorRef sub1_ref = VectorRef({sub1, beta_, mul3_ref});
auto add2 = std::make_shared<CondVar>(IsAddNode);
VectorRef add2_ref = VectorRef({add2, mul1_ref, sub1_ref});
return add2_ref;
}
CNodePtr LayerNormFusion::CreateLayerNormNode(const FuncGraphPtr &func_graph, const EquivPtr &equiv,
const std::vector<int> &shape, const float epsilon) const {
MS_EXCEPTION_IF_NULL(func_graph);
auto layer_norm_primitive = std::make_unique<schema::PrimitiveT>();
std::unique_ptr<schema::LayerNormT> attr = std::make_unique<schema::LayerNormT>();
attr->normalizedShape = shape;
attr->epsilon = epsilon;
attr->elementwiseAffine = true;
layer_norm_primitive->value.type = schema::PrimitiveType_LayerNorm;
layer_norm_primitive->value.value = attr.release();
auto layer_norm_cvalue = lite::PrimitiveC::Create(layer_norm_primitive.release());
auto value_node = NewValueNode(std::shared_ptr<lite::PrimitiveC>(layer_norm_cvalue));
std::vector<AnfNodePtr> new_node_inputs = {value_node};
auto input_node = utils::cast<AnfNodePtr>((*equiv)[input_]);
MS_EXCEPTION_IF_NULL(input_node);
new_node_inputs.push_back(input_node);
auto gamma_node = utils::cast<AnfNodePtr>((*equiv)[gamma_]);
MS_EXCEPTION_IF_NULL(gamma_node);
new_node_inputs.push_back(gamma_node);
auto beta_node = utils::cast<AnfNodePtr>((*equiv)[beta_]);
MS_EXCEPTION_IF_NULL(beta_node);
new_node_inputs.push_back(beta_node);
auto new_node = func_graph->NewCNode(new_node_inputs);
return new_node;
}
const AnfNodePtr LayerNormFusion::Process(const FuncGraphPtr &func_graph, const AnfNodePtr &node,
const EquivPtr &equiv) const {
MS_ASSERT(func_graph != nullptr);
MS_ASSERT(node != nullptr);
MS_LOG(DEBUG) << "layer_norm pass";
if (CheckIfFuncGraphIsNull(func_graph) != lite::RET_OK || CheckIfAnfNodeIsNull(node) != lite::RET_OK) {
lite::ReturnCode::GetSingleReturnCode()->UpdateReturnCode(lite::RET_NULL_PTR);
return nullptr;
}
// add2
auto add2_cnode = node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(add2_cnode) != lite::RET_OK || CheckInputSize(add2_cnode, kAddInputsLength) != lite::RET_OK) {
return nullptr;
}
auto add2_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(add2_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Add>>(add2_primitivec));
auto add2_op = utils::cast<std::shared_ptr<mindspore::lite::Add>>(add2_primitivec);
MS_ASSERT(add2_op != nullptr);
AnfNodePtr sub1_node = add2_cnode->input(2);
if (CheckIfAnfNodeIsNull(sub1_node) != lite::RET_OK) {
return nullptr;
}
// sub1
auto sub1_cnode = sub1_node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(sub1_cnode) != lite::RET_OK || CheckInputSize(sub1_cnode, kSubInputsLength) != lite::RET_OK) {
return nullptr;
}
auto sub1_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(sub1_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Sub>>(sub1_primitivec));
auto sub1_op = utils::cast<std::shared_ptr<mindspore::lite::Sub>>(sub1_primitivec);
MS_ASSERT(sub1_op != nullptr);
AnfNodePtr beta_node = sub1_cnode->input(1);
AnfNodePtr mul3_node = sub1_cnode->input(2);
if (CheckIfAnfNodeIsNull(beta_node) != lite::RET_OK || CheckIfAnfNodeIsNull(mul3_node) != lite::RET_OK) {
return nullptr;
}
// beta
if (CheckIfNodeIsParam(beta_node) != lite::RET_OK) {
return nullptr;
}
auto beta_param = beta_node->cast<ParameterPtr>()->default_param();
auto beta_tensor = std::dynamic_pointer_cast<ParamValueLite>(beta_param);
auto beta_shape = beta_tensor->tensor_shape();
// mul3
auto mul3_cnode = mul3_node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(mul3_cnode) != lite::RET_OK || CheckInputSize(mul3_cnode, kMulInputsLength) != lite::RET_OK) {
return nullptr;
}
auto mul3_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(mul3_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Mul>>(mul3_primitivec));
auto mul3_op = utils::cast<std::shared_ptr<mindspore::lite::Mul>>(mul3_primitivec);
MS_ASSERT(mul3_op != nullptr);
AnfNodePtr mean1_node = mul3_cnode->input(1);
AnfNodePtr mul2_node = mul3_cnode->input(2);
if (CheckIfAnfNodeIsNull(mean1_node) != lite::RET_OK || CheckIfAnfNodeIsNull(mul2_node) != lite::RET_OK) {
return nullptr;
}
// mul2
auto mul2_cnode = mul2_node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(mul2_cnode) != lite::RET_OK || CheckInputSize(mul2_cnode, kMulInputsLength) != lite::RET_OK) {
return nullptr;
}
auto mul2_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(mul2_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Mul>>(mul2_primitivec));
auto mul2_op = utils::cast<std::shared_ptr<mindspore::lite::Mul>>(mul2_primitivec);
MS_ASSERT(mul2_op != nullptr);
AnfNodePtr rsqrt_node = mul2_cnode->input(1);
AnfNodePtr gamma_node = mul2_cnode->input(2);
if (CheckIfAnfNodeIsNull(rsqrt_node) != lite::RET_OK || CheckIfAnfNodeIsNull(gamma_node) != lite::RET_OK) {
return nullptr;
}
// gamma
if (CheckIfNodeIsParam(gamma_node) != lite::RET_OK) {
return nullptr;
}
auto gamma_param = gamma_node->cast<ParameterPtr>()->default_param();
auto gamma_tensor = std::dynamic_pointer_cast<ParamValueLite>(gamma_param);
auto gamma_shape = gamma_tensor->tensor_shape();
// rsqrt
auto rsqrt_cnode = rsqrt_node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(rsqrt_cnode) != lite::RET_OK ||
CheckInputSize(rsqrt_cnode, kRsqrtInputsLength) != lite::RET_OK) {
return nullptr;
}
auto rsqrt_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(rsqrt_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Rsqrt>>(rsqrt_primitivec));
auto rsqrt_op = utils::cast<std::shared_ptr<mindspore::lite::Rsqrt>>(rsqrt_primitivec);
MS_ASSERT(rsqrt_op != nullptr);
AnfNodePtr add1_node = rsqrt_cnode->input(1);
if (CheckIfAnfNodeIsNull(add1_node) != lite::RET_OK) {
return nullptr;
}
// add1
auto add1_cnode = add1_node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(add1_cnode) != lite::RET_OK || CheckInputSize(add1_cnode, kAddInputsLength) != lite::RET_OK) {
return nullptr;
}
auto add1_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(add1_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Add>>(add1_primitivec));
auto add1_op = utils::cast<std::shared_ptr<mindspore::lite::Add>>(add1_primitivec);
MS_ASSERT(add1_op != nullptr);
AnfNodePtr mean2_node = add1_cnode->input(1);
AnfNodePtr epsilon_node = add1_cnode->input(2);
if (CheckIfAnfNodeIsNull(mean2_node) != lite::RET_OK || CheckIfAnfNodeIsNull(epsilon_node) != lite::RET_OK) {
return nullptr;
}
// epsilon
if (CheckIfNodeIsParam(epsilon_node) != lite::RET_OK) {
// delete[] add_bias_data;
return nullptr;
}
auto epsilon_param = epsilon_node->cast<ParameterPtr>()->default_param();
auto epsilon_tensor = std::dynamic_pointer_cast<ParamValueLite>(epsilon_param);
auto epsilon_data = reinterpret_cast<float *>(epsilon_tensor->tensor_addr());
auto epsilon_shape = epsilon_tensor->tensor_shape();
// mean2
auto mean2_cnode = mean2_node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(mean2_cnode) != lite::RET_OK ||
CheckInputSize(mean2_cnode, kReduceInputsLength) != lite::RET_OK) {
return nullptr;
}
auto mean2_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(mean2_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Reduce>>(mean2_primitivec));
auto mean2_op = utils::cast<std::shared_ptr<mindspore::lite::Reduce>>(mean2_primitivec);
MS_ASSERT(mean2_op != nullptr);
if (mean2_op->GetMode() != schema::ReduceMode_ReduceMean) {
return nullptr;
}
auto mean2_axes = mean2_op->GetAxes();
AnfNodePtr squared_difference_node = mean2_cnode->input(1);
if (CheckIfAnfNodeIsNull(squared_difference_node) != lite::RET_OK) {
return nullptr;
}
// mean1
auto mean1_cnode = mean1_node->cast<CNodePtr>();
if (CheckIfCNodeIsNull(mean1_cnode) != lite::RET_OK ||
CheckInputSize(mean1_cnode, kReduceInputsLength) != lite::RET_OK) {
return nullptr;
}
auto mean1_primitivec = GetValueNode<std::shared_ptr<lite::PrimitiveC>>(mean1_cnode->input(0));
MS_ASSERT(utils::isa<std::shared_ptr<mindspore::lite::Reduce>>(mean1_primitivec));
auto mean1_op = utils::cast<std::shared_ptr<mindspore::lite::Reduce>>(mean1_primitivec);
MS_ASSERT(mean1_op != nullptr);
if (mean1_op->GetMode() != schema::ReduceMode_ReduceMean) {
return nullptr;
}
AnfNodePtr input3_node = mean1_cnode->input(1);
auto mean1_axes = mean1_op->GetAxes();
if (CheckIfAnfNodeIsNull(input3_node) != lite::RET_OK) {
return nullptr;
}
// verify two mean ops have same axes
if (mean1_axes.size() != mean2_axes.size()) {
return nullptr;
}
for (size_t i = 0; i < mean1_axes.size(); ++i) {
if (mean1_axes[i] != mean2_axes[i]) {
return nullptr;
}
}
// verify axes size and gamma/beta size are equal
if (mean1_axes.size() != gamma_shape.size() || mean1_axes.size() != beta_shape.size()) {
return nullptr;
}
// verify gamma and beta have same shape
for (size_t i = 0; i < gamma_shape.size(); ++i) {
if (gamma_shape[i] != beta_shape[i]) {
return nullptr;
}
}
// verify epsilon has exactly one element
float epsilon;
if (epsilon_shape.empty() || (epsilon_shape.size() == 1 && epsilon_shape[0] == 1)) {
epsilon = epsilon_data[0];
} else {
return nullptr;
}
auto layer_norm_cnode = CreateLayerNormNode(func_graph, equiv, gamma_shape, epsilon);
layer_norm_cnode->set_abstract(add2_cnode->abstract()->Clone());
layer_norm_cnode->set_fullname_with_scope("layer_norm_" + add2_cnode->fullname_with_scope());
MS_LOG(INFO) << "layernorm node:" << layer_norm_cnode->fullname_with_scope() << " fusion success";
return layer_norm_cnode;
}
} // namespace opt
} // namespace mindspore
| 40.72619 | 119 | 0.72055 | [
"shape",
"vector"
] |
062151698d6fe6229fc248e8bb002055d0f0e4d6 | 2,197 | hpp | C++ | boost/sync/condition_variables/notify_all_at_thread_exit.hpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 2 | 2015-01-02T14:24:56.000Z | 2015-01-02T14:25:17.000Z | boost/sync/condition_variables/notify_all_at_thread_exit.hpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 2 | 2019-01-13T23:45:51.000Z | 2019-02-03T08:13:26.000Z | boost/sync/condition_variables/notify_all_at_thread_exit.hpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 2 | 2018-04-04T10:55:01.000Z | 2020-04-23T18:52:06.000Z | /*
* 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)
*
* (C) Copyright 2013 Andrey Semashev
*/
/*!
* \file sync/condition_variables/notify_all_at_thread_exit.hpp
*
* \brief This header defines the \c notify_all_at_thread_exit function.
*/
#ifndef BOOST_SYNC_CONDITION_VARIABLES_NOTIFY_ALL_AT_THREAD_EXIT_HPP_INCLUDED_
#define BOOST_SYNC_CONDITION_VARIABLES_NOTIFY_ALL_AT_THREAD_EXIT_HPP_INCLUDED_
#include <boost/assert.hpp>
#include <boost/sync/detail/link_config.hpp>
#include <boost/sync/locks/unique_lock.hpp>
#include <boost/sync/mutexes/mutex.hpp>
#include <boost/sync/condition_variables/condition_variable.hpp>
#include <boost/sync/detail/header.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
namespace sync {
namespace detail {
//! Adds a notification entry at thread termination
BOOST_SYNC_API void add_thread_exit_notify_entry(sync::mutex& mtx, sync::condition_variable& cond);
} // namespace detail
/*!
* Schedules a notification of the condition variable at the calling thread termination. The notification
* shall be performed with the <tt>cond.notify_all()</tt> method shortly before the thread terminates.
*
* The provided lock must be locked, its ownership is transferred to an external storage until the notification
* is performed. If there are threads blocked on the \a cond object, these threads should have used the same
* mutex object as the one referred to by the \a lock.
*
* \param cond Condition variable to perform notification on.
* \param lock The lock that owns the mutex, used to block on the condition variable.
*
* \pre <tt>lock.owns_lock()</tt>
* \post <tt>!lock.owns_lock()</tt>
*/
inline void notify_all_at_thread_exit(sync::condition_variable& cond, sync::unique_lock< sync::mutex > lock)
{
BOOST_ASSERT(lock.owns_lock());
sync::detail::add_thread_exit_notify_entry(*lock.mutex(), cond);
lock.release();
}
} // namespace sync
} // namespace boost
#include <boost/sync/detail/footer.hpp>
#endif // BOOST_SYNC_CONDITION_VARIABLES_NOTIFY_ALL_AT_THREAD_EXIT_HPP_INCLUDED_
| 32.791045 | 111 | 0.769231 | [
"object"
] |
164475076b2a27e6299f7cebb31458cecd5b14f5 | 816 | cpp | C++ | 6-array/6-practice/6p-1-5.cpp | tanle8/cdope | 2218cb2ece25b2d7bd47c3f06384302c300957f3 | [
"MIT"
] | 1 | 2018-04-04T13:43:28.000Z | 2018-04-04T13:43:28.000Z | 6-array/6-practice/6p-1-5.cpp | tanle8/cdope | 2218cb2ece25b2d7bd47c3f06384302c300957f3 | [
"MIT"
] | null | null | null | 6-array/6-practice/6p-1-5.cpp | tanle8/cdope | 2218cb2ece25b2d7bd47c3f06384302c300957f3 | [
"MIT"
] | null | null | null | /* 5. Write a program to find the sum and product of all elements of an array.
*/
#include <iostream>
#include <vector>
using namespace std;
float sumOf(const std::vector<float> &n)
{
float sum = 0; // declare and initialize a variable to store sum.
// Iterate through all elements and add them to sum
for (int i = 0; i < n.size(); i++)
{
sum += n[i];
}
return sum;
}
float productOf(const std::vector<float> &n)
{
float product;
// Iterate through all elements and multiply them
for (int i = 0; i < n.size(); i++)
{
product *= n[i];
}
return product;
}
int main()
{
std::vector<float> a = {1,2,3,4,5,6,7,8,9,10};
float s, p = 0;
s = sumOf(a);
p = productOf(a);
cout << s << endl;
cout << p << endl;
return 0;
}
| 17 | 78 | 0.560049 | [
"vector"
] |
1649b33faf09e8fff0ff9211d33ae269e63c78f5 | 3,481 | cpp | C++ | unittests/basic/adt/SmallSetTest.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | unittests/basic/adt/SmallSetTest.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | unittests/basic/adt/SmallSetTest.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | // This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/10/17.
#include "polarphp/basic/adt/SmallSet.h"
#include "gtest/gtest.h"
#include <string>
using polar::basic::SmallSet;
TEST(SmallSetTest, testInsert)
{
SmallSet<int, 4> s1;
for (int i = 0; i < 4; i++)
s1.insert(i);
for (int i = 0; i < 4; i++)
s1.insert(i);
EXPECT_EQ(4u, s1.size());
for (int i = 0; i < 4; i++)
EXPECT_EQ(1u, s1.count(i));
EXPECT_EQ(0u, s1.count(4));
}
TEST(SmallSetTest, testGrow)
{
SmallSet<int, 4> s1;
for (int i = 0; i < 8; i++)
s1.insert(i);
EXPECT_EQ(8u, s1.size());
for (int i = 0; i < 8; i++)
EXPECT_EQ(1u, s1.count(i));
EXPECT_EQ(0u, s1.count(8));
}
TEST(SmallSetTest, testErase)
{
SmallSet<int, 4> s1;
for (int i = 0; i < 8; i++)
s1.insert(i);
EXPECT_EQ(8u, s1.size());
// Remove elements one by one and check if all other elements are still there.
for (int i = 0; i < 8; i++) {
EXPECT_EQ(1u, s1.count(i));
EXPECT_TRUE(s1.erase(i));
EXPECT_EQ(0u, s1.count(i));
EXPECT_EQ(8u - i - 1, s1.size());
for (int j = i + 1; j < 8; j++)
EXPECT_EQ(1u, s1.count(j));
}
EXPECT_EQ(0u, s1.count(8));
}
TEST(SmallSetTest, testIteratorInt)
{
SmallSet<int, 4> s1;
// Test the 'small' case.
for (int i = 0; i < 3; i++)
s1.insert(i);
std::vector<int> V(s1.begin(), s1.end());
// Make sure the elements are in the expected order.
std::sort(V.begin(), V.end());
for (int i = 0; i < 3; i++)
EXPECT_EQ(i, V[i]);
// Test the 'big' case by adding a few more elements to switch to std::set
// internally.
for (int i = 3; i < 6; i++)
s1.insert(i);
V.assign(s1.begin(), s1.end());
// Make sure the elements are in the expected order.
std::sort(V.begin(), V.end());
for (int i = 0; i < 6; i++)
EXPECT_EQ(i, V[i]);
}
TEST(SmallSetTest, testIteratorString)
{
// Test SmallSetIterator for SmallSet with a type with non-trivial
// ctors/dtors.
SmallSet<std::string, 2> s1;
s1.insert("str 1");
s1.insert("str 2");
s1.insert("str 1");
std::vector<std::string> V(s1.begin(), s1.end());
std::sort(V.begin(), V.end());
EXPECT_EQ(2u, s1.size());
EXPECT_EQ("str 1", V[0]);
EXPECT_EQ("str 2", V[1]);
s1.insert("str 4");
s1.insert("str 0");
s1.insert("str 4");
V.assign(s1.begin(), s1.end());
// Make sure the elements are in the expected order.
std::sort(V.begin(), V.end());
EXPECT_EQ(4u, s1.size());
EXPECT_EQ("str 0", V[0]);
EXPECT_EQ("str 1", V[1]);
EXPECT_EQ("str 2", V[2]);
EXPECT_EQ("str 4", V[3]);
}
TEST(SmallSetTest, testIteratorIncMoveCopy)
{
// Test SmallSetIterator for SmallSet with a type with non-trivial
// ctors/dtors.
SmallSet<std::string, 2> s1;
s1.insert("str 1");
s1.insert("str 2");
auto Iter = s1.begin();
EXPECT_EQ("str 1", *Iter);
++Iter;
EXPECT_EQ("str 2", *Iter);
s1.insert("str 4");
s1.insert("str 0");
auto Iter2 = s1.begin();
Iter = std::move(Iter2);
EXPECT_EQ("str 0", *Iter);
}
| 23.206667 | 85 | 0.59006 | [
"vector"
] |
1650a2cd2578a215298eac5116c22d44d9773b83 | 39,378 | cxx | C++ | Components/Optimizers/CMAEvolutionStrategy/itkCMAEvolutionStrategyOptimizer.cxx | squll1peter/elastix | e58c831a91df6233605f96ad060119439756ca90 | [
"Apache-2.0"
] | 1 | 2020-11-12T12:17:02.000Z | 2020-11-12T12:17:02.000Z | Components/Optimizers/CMAEvolutionStrategy/itkCMAEvolutionStrategyOptimizer.cxx | squll1peter/elastix | e58c831a91df6233605f96ad060119439756ca90 | [
"Apache-2.0"
] | null | null | null | Components/Optimizers/CMAEvolutionStrategy/itkCMAEvolutionStrategyOptimizer.cxx | squll1peter/elastix | e58c831a91df6233605f96ad060119439756ca90 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* 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 __itkCMAEvolutionStrategyOptimizer_cxx
#define __itkCMAEvolutionStrategyOptimizer_cxx
#include "itkCMAEvolutionStrategyOptimizer.h"
#include "itkSymmetricEigenAnalysis.h"
#include "vnl/vnl_math.h"
#include <algorithm>
#include <cmath>
#include "itkCommand.h"
#include "itkEventObject.h"
#include "itkMacro.h"
namespace itk
{
/**
* ******************** Constructor *************************
*/
CMAEvolutionStrategyOptimizer::CMAEvolutionStrategyOptimizer()
{
itkDebugMacro( "Constructor" );
this->m_RandomGenerator = RandomGeneratorType::GetInstance();
this->m_CurrentValue = NumericTraits< MeasureType >::Zero;
this->m_CurrentIteration = 0;
this->m_StopCondition = Unknown;
this->m_Stop = false;
this->m_UseCovarianceMatrixAdaptation = true;
this->m_PopulationSize = 0;
this->m_NumberOfParents = 0;
this->m_UpdateBDPeriod = 1;
this->m_EffectiveMu = 0.0;
this->m_ConjugateEvolutionPathConstant = 0.0;
this->m_SigmaDampingConstant = 0.0;
this->m_CovarianceMatrixAdaptationConstant = 0.0;
this->m_EvolutionPathConstant = 0.0;
this->m_CovarianceMatrixAdaptationWeight = 0.0;
this->m_ExpectationNormNormalDistribution = 0.0;
this->m_HistoryLength = 0;
this->m_CurrentMaximumD = 1.0;
this->m_CurrentMinimumD = 1.0;
this->m_CurrentSigma = 0.0;
this->m_Heaviside = false;
this->m_MaximumNumberOfIterations = 100;
this->m_UseDecayingSigma = false;
this->m_InitialSigma = 1.0;
this->m_SigmaDecayA = 50;
this->m_SigmaDecayAlpha = 0.602;
this->m_RecombinationWeightsPreset = "superlinear";
this->m_MaximumDeviation = NumericTraits< double >::max();
this->m_MinimumDeviation = 0.0;
this->m_PositionToleranceMin = 1e-12;
this->m_PositionToleranceMax = 1e8;
this->m_ValueTolerance = 1e-12;
} // end constructor
/**
* ******************* PrintSelf *********************
*/
void
CMAEvolutionStrategyOptimizer::PrintSelf( std::ostream & os, Indent indent ) const
{
Superclass::PrintSelf( os, indent );
//os << indent << "m_RandomGenerator: " << this->m_RandomGenerator << std::endl;
os << indent << "m_CurrentValue: " << this->m_CurrentValue << std::endl;
os << indent << "m_CurrentIteration: " << this->m_CurrentIteration << std::endl;
os << indent << "m_StopCondition: " << this->m_StopCondition << std::endl;
os << indent << "m_Stop: " << this->m_Stop << std::endl;
os << indent << "m_UseCovarianceMatrixAdaptation: " << this->m_UseCovarianceMatrixAdaptation << std::endl;
os << indent << "m_PopulationSize: " << this->m_PopulationSize << std::endl;
os << indent << "m_NumberOfParents: " << this->m_NumberOfParents << std::endl;
os << indent << "m_UpdateBDPeriod: " << this->m_UpdateBDPeriod << std::endl;
os << indent << "m_EffectiveMu: " << this->m_EffectiveMu << std::endl;
os << indent << "m_ConjugateEvolutionPathConstant: " << this->m_ConjugateEvolutionPathConstant << std::endl;
os << indent << "m_SigmaDampingConstant: " << this->m_SigmaDampingConstant << std::endl;
os << indent << "m_CovarianceMatrixAdaptationConstant: " << this->m_CovarianceMatrixAdaptationConstant << std::endl;
os << indent << "m_EvolutionPathConstant: " << this->m_EvolutionPathConstant << std::endl;
os << indent << "m_CovarianceMatrixAdaptationWeight: " << this->m_CovarianceMatrixAdaptationWeight << std::endl;
os << indent << "m_ExpectationNormNormalDistribution: " << this->m_ExpectationNormNormalDistribution << std::endl;
os << indent << "m_HistoryLength: " << this->m_HistoryLength << std::endl;
os << indent << "m_CurrentSigma: " << this->m_CurrentSigma << std::endl;
os << indent << "m_Heaviside: " << this->m_Heaviside << std::endl;
os << indent << "m_CurrentMaximumD: " << this->m_CurrentMaximumD << std::endl;
os << indent << "m_CurrentMinimumD: " << this->m_CurrentMinimumD << std::endl;
os << indent << "m_MaximumNumberOfIterations: " << this->m_MaximumNumberOfIterations << std::endl;
os << indent << "m_UseDecayingSigma: " << this->m_UseDecayingSigma << std::endl;
os << indent << "m_InitialSigma: " << this->m_InitialSigma << std::endl;
os << indent << "m_SigmaDecayA: " << this->m_SigmaDecayA << std::endl;
os << indent << "m_SigmaDecayAlpha: " << this->m_SigmaDecayAlpha << std::endl;
os << indent << "m_RecombinationWeightsPreset: " << this->m_RecombinationWeightsPreset << std::endl;
os << indent << "m_MaximumDeviation: " << this->m_MaximumDeviation << std::endl;
os << indent << "m_MinimumDeviation: " << this->m_MinimumDeviation << std::endl;
os << indent << "m_PositionToleranceMin: " << this->m_PositionToleranceMin << std::endl;
os << indent << "m_PositionToleranceMax: " << this->m_PositionToleranceMax << std::endl;
os << indent << "m_ValueTolerance: " << this->m_ValueTolerance << std::endl;
os << indent << "m_RecombinationWeights: " << this->m_RecombinationWeights << std::endl;
os << indent << "m_C: " << this->m_C << std::endl;
os << indent << "m_B: " << this->m_B << std::endl;
os << indent << "m_D: " << this->m_D.diagonal() << std::endl;
// template:
//os << indent << ": " << this-> << std::endl;
} // end PrintSelf;
/**
* ******************* StartOptimization *********************
*/
void
CMAEvolutionStrategyOptimizer::StartOptimization()
{
itkDebugMacro( "StartOptimization" );
/** Reset some variables */
this->m_CurrentValue = NumericTraits< MeasureType >::Zero;
this->m_CurrentIteration = 0;
this->m_Stop = false;
this->m_StopCondition = Unknown;
/** Get the number of parameters; checks also if a cost function has been set at all.
* if not: an exception is thrown */
this->GetScaledCostFunction()->GetNumberOfParameters();
/** Initialize the scaledCostFunction with the currently set scales */
this->InitializeScales();
/** Set the current position as the scaled initial position */
this->SetCurrentPosition( this->GetInitialPosition() );
/** Compute default values for a lot of constants */
this->InitializeConstants();
/** Resize/Initialize variables used that are updated during optimisation */
this->InitializeProgressVariables();
/** Resize/Initialize B, C, and D */
this->InitializeBCD();
if( !this->m_Stop )
{
this->ResumeOptimization();
}
} // end StartOptimization
/**
* ******************* ResumeOptimization *********************
*/
void
CMAEvolutionStrategyOptimizer::ResumeOptimization()
{
itkDebugMacro( "ResumeOptimization" );
this->m_Stop = false;
this->m_StopCondition = Unknown;
this->InvokeEvent( StartEvent() );
try
{
this->m_CurrentValue = this->GetScaledValue( this->GetScaledCurrentPosition() );
}
catch( ExceptionObject & err )
{
this->m_StopCondition = MetricError;
this->StopOptimization();
throw err;
}
/** Test if not by chance we are already converged */
bool convergence = this->TestConvergence( true );
if( convergence )
{
this->StopOptimization();
}
/** Start iterating */
while( !this->m_Stop )
{
this->GenerateOffspring();
this->SortCostFunctionValues();
/** Something may have gone wrong during evaluation of the cost function values */
if( this->m_Stop )
{
break;
}
this->AdvanceOneStep();
/** Something may have gone wrong during evalution of the current value */
if( this->m_Stop )
{
break;
}
/** Give the user opportunity to observe progress (current value/position/sigma etc.) */
this->InvokeEvent( IterationEvent() );
if( this->m_Stop )
{
break;
}
/** Prepare for next iteration */
this->UpdateConjugateEvolutionPath();
this->UpdateHeaviside();
this->UpdateEvolutionPath();
this->UpdateC();
this->UpdateSigma();
this->UpdateBD();
this->FixNumericalErrors();
/** Test if convergence has occured in some sense */
convergence = this->TestConvergence( false );
if( convergence )
{
this->StopOptimization();
break;
}
/** Next iteration */
++( this->m_CurrentIteration );
} // end while !m_Stop
} // end ResumeOptimization
/**
* *********************** StopOptimization *****************************
*/
void
CMAEvolutionStrategyOptimizer::StopOptimization()
{
itkDebugMacro( "StopOptimization" );
this->m_Stop = true;
this->InvokeEvent( EndEvent() );
} // end StopOptimization()
/**
* ****************** InitializeConstants *********************
*/
void
CMAEvolutionStrategyOptimizer::InitializeConstants( void )
{
itkDebugMacro( "InitializeConstants" );
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** m_PopulationSize (if not provided by the user) */
if( this->m_PopulationSize == 0 )
{
this->m_PopulationSize = 4 + static_cast< unsigned int >(
std::floor( 3.0 * std::log( static_cast< double >( numberOfParameters ) ) ) );
}
/** m_NumberOfParents (if not provided by the user) */
if( this->m_NumberOfParents == 0 )
{
this->m_NumberOfParents = this->m_PopulationSize / 2;
}
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
const double Nd = static_cast< double >( N );
const unsigned int lambda = this->m_PopulationSize;
const double lambdad = static_cast< double >( lambda );
const unsigned int mu = this->m_NumberOfParents;
const double mud = static_cast< double >( mu );
/** m_RecombinationWeights */
this->m_RecombinationWeights.SetSize( mu );
this->m_RecombinationWeights.Fill( 1.0 ); // "equal" preset
if( this->m_RecombinationWeightsPreset == "linear" )
{
for( unsigned int i = 0; i < mu; ++i )
{
this->m_RecombinationWeights[ i ]
= mud + 1.0 - static_cast< double >( i + 1 );
}
}
else if( this->m_RecombinationWeightsPreset == "superlinear" )
{
const double logmud = std::log( mud + 1.0 );
for( unsigned int i = 0; i < mu; ++i )
{
this->m_RecombinationWeights[ i ]
= logmud - std::log( static_cast< double >( i + 1 ) );
}
}
this->m_RecombinationWeights /= this->m_RecombinationWeights.sum();
/** m_EffectiveMu */
this->m_EffectiveMu = 1.0 / this->m_RecombinationWeights.squared_magnitude();
if( this->m_EffectiveMu >= lambdad )
{
itkExceptionMacro( << "The RecombinationWeights have unreasonable values!" );
}
/** alias: */
const double mueff = this->m_EffectiveMu;
/** m_ConjugateEvolutionPathConstant (c_\sigma) */
this->m_ConjugateEvolutionPathConstant = ( mueff + 2.0 ) / ( Nd + mueff + 3.0 );
/** m_SigmaDampingConstant */
this->m_SigmaDampingConstant = this->m_ConjugateEvolutionPathConstant
+ ( 1.0 + 2.0 * std::max( 0.0, std::sqrt( ( mueff - 1.0 ) / ( Nd + 1.0 ) ) - 1.0 ) )
* std::max( 0.3, 1.0 - Nd / static_cast< double >( this->m_MaximumNumberOfIterations ) );
/** m_CovarianceMatrixAdaptationWeight (\mu_cov)*/
this->m_CovarianceMatrixAdaptationWeight = mueff;
/** alias: */
const double mucov = this->m_CovarianceMatrixAdaptationWeight;
/** m_CovarianceMatrixAdaptationConstant (c_cov) */
this->m_CovarianceMatrixAdaptationConstant
= ( 1.0 / mucov ) * 2.0 / vnl_math::sqr( Nd + std::sqrt( 2.0 ) )
+ ( 1.0 - 1.0 / mucov )
* std::min( 1.0, ( 2.0 * mueff - 1.0 ) / ( vnl_math::sqr( Nd + 2.0 ) + mueff ) );
/** alias: */
const double c_cov = this->m_CovarianceMatrixAdaptationConstant;
/** Update only every 'period' iterations */
if( this->m_UpdateBDPeriod == 0 )
{
this->m_UpdateBDPeriod = static_cast< unsigned int >( std::floor( 1.0 / c_cov / Nd / 10.0 ) );
}
this->m_UpdateBDPeriod = std::max( static_cast< unsigned int >( 1 ), this->m_UpdateBDPeriod );
if( this->m_UpdateBDPeriod >= this->m_MaximumNumberOfIterations )
{
this->SetUseCovarianceMatrixAdaptation( false );
}
/** m_EvolutionPathConstant (c_c)*/
this->m_EvolutionPathConstant = 4.0 / ( Nd + 4.0 );
/** m_ExpectationNormNormalDistribution */
this->m_ExpectationNormNormalDistribution = std::sqrt( Nd )
* ( 1.0 - 1.0 / ( 4.0 * Nd ) + 1.0 / ( 21.0 * vnl_math::sqr( Nd ) ) );
/** m_HistoryLength */
this->m_HistoryLength = static_cast< unsigned long >( std::min(
this->GetMaximumNumberOfIterations(),
10 + static_cast< unsigned long >( std::ceil( 3.0 * 10.0 * Nd / lambdad ) ) ) );
} // end InitializeConstants
/**
* ****************** InitializeProgressVariables *********************
*/
void
CMAEvolutionStrategyOptimizer::InitializeProgressVariables( void )
{
itkDebugMacro( "InitializeProgressVariables" );
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
const unsigned int lambda = this->m_PopulationSize;
/** CurrentSigma */
this->m_CurrentSigma = this->GetInitialSigma();
/** Heaviside */
this->m_Heaviside = 0.0;
/** m_SearchDirs */
ParametersType zeroParam( N );
zeroParam.Fill( 0.0 );
this->m_SearchDirs.clear();
this->m_SearchDirs.resize( lambda, zeroParam );
/** m_NormalizedSearchDirs */
this->m_NormalizedSearchDirs.clear();
this->m_NormalizedSearchDirs.resize( lambda, zeroParam );
/** m_CostFunctionValues */
this->m_CostFunctionValues.clear();
/** m_CurrentScaledStep */
this->m_CurrentScaledStep.SetSize( N );
this->m_CurrentScaledStep.Fill( 0.0 );
/** m_CurrentNormalizedStep */
this->m_CurrentNormalizedStep.SetSize( N );
this->m_CurrentNormalizedStep.Fill( 0.0 );
/** m_EvolutionPath */
this->m_EvolutionPath.SetSize( N );
this->m_EvolutionPath.Fill( 0.0 );
/** m_ConjugateEvolutionPath */
this->m_ConjugateEvolutionPath.SetSize( N );
this->m_ConjugateEvolutionPath.Fill( 0.0 );
/** m_MeasureHistory */
this->m_MeasureHistory.clear();
/** Maximum and minimum square root eigenvalues */
this->m_CurrentMaximumD = 1.0;
this->m_CurrentMinimumD = 1.0;
} // end InitializeProgressVariables
/**
* ****************** InitializeBCD *********************
*/
void
CMAEvolutionStrategyOptimizer::InitializeBCD( void )
{
itkDebugMacro( "InitializeBCD" );
if( this->GetUseCovarianceMatrixAdaptation() )
{
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
/** Resize */
this->m_B.SetSize( N, N );
this->m_C.SetSize( N, N );
this->m_D.set_size( N );
/** Initialize */
this->m_B.Fill( 0.0 );
this->m_C.Fill( 0.0 );
this->m_B.fill_diagonal( 1.0 );
this->m_C.fill_diagonal( 1.0 );
this->m_D.fill( 1.0 );
}
else
{
/** Clear */
this->m_B.SetSize( 0, 0 );
this->m_C.SetSize( 0, 0 );
this->m_D.clear();
}
} // end InitializeBCD
/**
* ****************** GenerateOffspring *********************
*/
void
CMAEvolutionStrategyOptimizer::GenerateOffspring( void )
{
itkDebugMacro( "GenerateOffspring" );
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
const unsigned int lambda = this->m_PopulationSize;
/** Clear the old values */
this->m_CostFunctionValues.clear();
/** Fill the m_NormalizedSearchDirs and SearchDirs */
unsigned int lam = 0;
unsigned int nrOfFails = 0;
while( lam < lambda )
{
/** draw from distribution N(0,I) */
for( unsigned int par = 0; par < N; ++par )
{
this->m_NormalizedSearchDirs[ lam ][ par ]
= this->m_RandomGenerator->GetNormalVariate();
}
/** Make like it was drawn from N(0,C) */
if( this->GetUseCovarianceMatrixAdaptation() )
{
this->m_SearchDirs[ lam ] = this->m_B * ( this->m_D * this->m_NormalizedSearchDirs[ lam ] );
}
else
{
this->m_SearchDirs[ lam ] = this->m_NormalizedSearchDirs[ lam ];
}
/** Make like it was drawn from N( 0, sigma^2 C ) */
this->m_SearchDirs[ lam ] *= this->m_CurrentSigma;
/** Compute the cost function */
MeasureType costFunctionValue = 0.0;
/** x_lam = m + d_lam */
ParametersType x_lam = this->GetScaledCurrentPosition();
x_lam += this->m_SearchDirs[ lam ];
try
{
costFunctionValue = this->GetScaledValue( x_lam );
}
catch( ExceptionObject & err )
{
++nrOfFails;
/** try another parameter vector if we haven't tried that for 10 times already */
if( nrOfFails <= 10 )
{
continue;
}
else
{
this->m_StopCondition = MetricError;
this->StopOptimization();
throw err;
}
}
/** Successfull cost function evaluation */
this->m_CostFunctionValues.push_back(
MeasureIndexPairType( costFunctionValue, lam ) );
/** Reset the number of failed cost function evaluations */
nrOfFails = 0;
/** next offspring member */
++lam;
}
} // end GenerateOffspring
/**
* ****************** SortCostFunctionValues *********************
*/
void
CMAEvolutionStrategyOptimizer::SortCostFunctionValues( void )
{
itkDebugMacro( "SortCostFunctionValues" );
/** Sort the cost function values in order of increasing cost function value */
std::sort( this->m_CostFunctionValues.begin(), this->m_CostFunctionValues.end() );
/** Store the best value in the history, and remove the oldest entry of the
* the history if the history exceeds the HistoryLength */
this->m_MeasureHistory.push_front( this->m_CostFunctionValues[ 0 ].first );
if( this->m_MeasureHistory.size() > this->m_HistoryLength )
{
this->m_MeasureHistory.pop_back();
}
} // end SortCostFunctionValues
/**
* ****************** AdvanceOneStep *********************
*/
void
CMAEvolutionStrategyOptimizer::AdvanceOneStep( void )
{
itkDebugMacro( "AdvanceOneStep" );
/** Some casts/aliases: */
const unsigned int mu = this->m_NumberOfParents;
/** Compute the CurrentScaledStep, using the RecombinationWeights and
* the sorted CostFunctionValues-vector.
* On the fly, also compute the CurrentNormalizedStep */
this->m_CurrentScaledStep.Fill( 0.0 );
this->m_CurrentNormalizedStep.Fill( 0.0 );
for( unsigned int m = 0; m < mu; ++m )
{
const unsigned int lam = this->m_CostFunctionValues[ m ].second;
const double weight = this->m_RecombinationWeights[ m ];
this->m_CurrentScaledStep += ( weight * this->m_SearchDirs[ lam ] );
this->m_CurrentNormalizedStep += ( weight * this->m_NormalizedSearchDirs[ lam ] );
}
/** Set the new current position */
ParametersType newPos = this->GetScaledCurrentPosition();
newPos += this->GetCurrentScaledStep();
this->SetScaledCurrentPosition( newPos );
/** Compute the cost function at the new position */
try
{
this->m_CurrentValue = this->GetScaledValue( this->GetScaledCurrentPosition() );
}
catch( ExceptionObject & err )
{
this->m_StopCondition = MetricError;
this->StopOptimization();
throw err;
}
} // end AdvanceOneStep
/**
* ****************** UpdateConjugateEvolutionPath *********************
*/
void
CMAEvolutionStrategyOptimizer::UpdateConjugateEvolutionPath( void )
{
itkDebugMacro( "UpdateConjugateEvolutionPath" );
/** Some casts/aliases: */
const double c_sigma = this->m_ConjugateEvolutionPathConstant;
/** Update p_sigma */
const double factor = std::sqrt( c_sigma * ( 2.0 - c_sigma ) * this->m_EffectiveMu );
this->m_ConjugateEvolutionPath *= ( 1.0 - c_sigma );
if( this->GetUseCovarianceMatrixAdaptation() )
{
this->m_ConjugateEvolutionPath
+= ( factor * ( this->m_B * this->m_CurrentNormalizedStep ) );
}
else
{
this->m_ConjugateEvolutionPath += ( factor * this->m_CurrentNormalizedStep );
}
} // end UpdateConjugateEvolutionPath
/**
* ****************** UpdateHeaviside *********************
*/
void
CMAEvolutionStrategyOptimizer::UpdateHeaviside( void )
{
itkDebugMacro( "UpdateHeaviside" );
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
const double Nd = static_cast< double >( N );
const double c_sigma = this->m_ConjugateEvolutionPathConstant;
const int nextit = static_cast< int >( this->GetCurrentIteration() + 1 );
const double chiN = this->m_ExpectationNormNormalDistribution;
/** Compute the Heaviside function: */
this->m_Heaviside = false;
const double normps = this->m_ConjugateEvolutionPath.magnitude();
const double denom = std::sqrt( 1.0 - std::pow( 1.0 - c_sigma, 2 * nextit ) );
const double righthandside = 1.5 + 1.0 / ( Nd - 0.5 );
if( ( normps / denom / chiN ) < righthandside )
{
this->m_Heaviside = true;
}
} // end UpdateHeaviside
/**
* ****************** UpdateEvolutionPath *********************
*/
void
CMAEvolutionStrategyOptimizer::UpdateEvolutionPath( void )
{
itkDebugMacro( "UpdateEvolutionPath" );
/** Some casts/aliases: */
const double c_c = this->m_EvolutionPathConstant;
/** Compute the evolution path p_c */
this->m_EvolutionPath *= ( 1.0 - c_c );
if( this->m_Heaviside )
{
const double factor
= std::sqrt( c_c * ( 2.0 - c_c ) * this->m_EffectiveMu ) / this->m_CurrentSigma;
this->m_EvolutionPath += ( factor * this->m_CurrentScaledStep );
}
} // end UpdateEvolutionPath
/**
* ****************** UpdateC *********************
*/
void
CMAEvolutionStrategyOptimizer::UpdateC( void )
{
itkDebugMacro( "UpdateC" );
if( !( this->GetUseCovarianceMatrixAdaptation() ) )
{
/** We don't need C */
return;
}
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
const unsigned int mu = this->m_NumberOfParents;
const double c_c = this->m_EvolutionPathConstant;
const double c_cov = this->m_CovarianceMatrixAdaptationConstant;
const double mu_cov = this->m_CovarianceMatrixAdaptationWeight;
const double sigma = this->m_CurrentSigma;
/** Multiply old m_C with some factor */
double oldCfactor = 1.0 - c_cov;
if( !this->m_Heaviside )
{
oldCfactor += ( c_cov * c_c * ( 2.0 - c_c ) / mu_cov );
}
this->m_C *= oldCfactor;
/** Do rank-one update */
const double rankonefactor = c_cov / mu_cov;
for( unsigned int i = 0; i < N; ++i )
{
const double evolutionPath_i = this->m_EvolutionPath[ i ];
for( unsigned int j = 0; j < N; ++j )
{
const double update = rankonefactor * evolutionPath_i * this->m_EvolutionPath[ j ];
this->m_C[ i ][ j ] += update;
}
}
/** Do rank-mu update */
const double rankmufactor = c_cov * ( 1.0 - 1.0 / mu_cov );
for( unsigned int m = 0; m < mu; ++m )
{
const unsigned int lam = this->m_CostFunctionValues[ m ].second;
const double sqrtweight = std::sqrt( this->m_RecombinationWeights[ m ] );
ParametersType weightedSearchDir = this->m_SearchDirs[ lam ];
weightedSearchDir *= ( sqrtweight / sigma );
for( unsigned int i = 0; i < N; ++i )
{
const double weightedSearchDir_i = weightedSearchDir[ i ];
for( unsigned int j = 0; j < N; ++j )
{
const double update = rankmufactor * weightedSearchDir_i * weightedSearchDir[ j ];
this->m_C[ i ][ j ] += update;
}
}
} // end for m
} // end UpdateC
/**
* ****************** UpdateSigma *********************
*/
void
CMAEvolutionStrategyOptimizer::UpdateSigma( void )
{
itkDebugMacro( "UpdateSigma" );
if( this->GetUseDecayingSigma() )
{
const double it = static_cast< double >( this->GetCurrentIteration() );
const double num = std::pow( this->m_SigmaDecayA + it, this->m_SigmaDecayAlpha );
const double den = std::pow( this->m_SigmaDecayA + it + 1.0, this->m_SigmaDecayAlpha );
this->m_CurrentSigma *= num / den;
}
else
{
const double normps = this->m_ConjugateEvolutionPath.magnitude();
const double chiN = this->m_ExpectationNormNormalDistribution;
const double c_sigma = this->m_ConjugateEvolutionPathConstant;
const double d_sigma = this->m_SigmaDampingConstant;
this->m_CurrentSigma *= std::exp( ( normps / chiN - 1.0 ) * c_sigma / d_sigma );
}
} // end UpdateSigma
/**
* ****************** UpdateBD *********************
*/
void
CMAEvolutionStrategyOptimizer::UpdateBD( void )
{
itkDebugMacro( "UpdateBD" );
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
const int nextit = static_cast< int >( this->GetCurrentIteration() + 1 );
/** Update only every 'm_UpdateBDPeriod' iterations */
unsigned int periodover = nextit % this->m_UpdateBDPeriod;
if( !( this->GetUseCovarianceMatrixAdaptation() ) || ( periodover != 0 ) )
{
/** We don't need to update B and D */
return;
}
typedef itk::SymmetricEigenAnalysis<
CovarianceMatrixType,
EigenValueMatrixType,
CovarianceMatrixType > EigenAnalysisType;
/** In the itkEigenAnalysis only the upper triangle of the matrix will be accessed, so
* we do not need to make sure the matrix is symmetric, like in the
* matlab code. Just run the eigenAnalysis! */
EigenAnalysisType eigenAnalysis( N );
unsigned int returncode = 0;
returncode = eigenAnalysis.ComputeEigenValuesAndVectors( this->m_C, this->m_D, this->m_B );
if( returncode != 0 )
{
itkExceptionMacro( << "EigenAnalysis failed while computing eigenvalue nr: " << returncode );
}
/** itk eigen analysis returns eigen vectors in rows... */
this->m_B.inplace_transpose();
/** limit condition of C to 1e10 + 1, and avoid negative eigenvalues */
const double largeNumber = 1e10;
double dmax = this->m_D.diagonal().max_value();
double dmin = this->m_D.diagonal().min_value();
if( dmin < 0.0 )
{
const double diagadd = dmax / largeNumber;
for( unsigned int i = 0; i < N; ++i )
{
if( this->m_D[ i ] < 0.0 )
{
this->m_D[ i ] = 0.0;
}
this->m_C[ i ][ i ] += diagadd;
this->m_D[ i ] += diagadd;
}
}
dmax = this->m_D.diagonal().max_value();
dmin = this->m_D.diagonal().min_value();
if( dmax > dmin * largeNumber )
{
const double diagadd = dmax / largeNumber - dmin;
for( unsigned int i = 0; i < N; ++i )
{
this->m_C[ i ][ i ] += diagadd;
this->m_D[ i ] += diagadd;
}
}
/** the D matrix is supposed to contain the square root of the eigen values */
for( unsigned int i = 0; i < N; ++i )
{
this->m_D[ i ] = std::sqrt( this->m_D[ i ] );
}
/** Keep for the user */
this->m_CurrentMaximumD = this->m_D.diagonal().max_value();
this->m_CurrentMinimumD = this->m_D.diagonal().min_value();
} // end UpdateBD
/**
* **************** FixNumericalErrors ********************
*/
void
CMAEvolutionStrategyOptimizer::FixNumericalErrors( void )
{
itkDebugMacro( "FixNumericalErrors" );
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
const double c_sigma = this->m_ConjugateEvolutionPathConstant;
const double c_cov = this->m_CovarianceMatrixAdaptationConstant;
const double d_sigma = this->m_SigmaDampingConstant;
const double strange_factor = std::exp( 0.05 + c_sigma / d_sigma );
const double strange_factor2 = std::exp( 0.2 + c_sigma / d_sigma );
const unsigned int nextit = this->m_CurrentIteration + 1;
/** Check if m_MaximumDeviation and m_MinimumDeviation are satisfied. This
* check is different depending on the m_UseCovarianceMatrixAdaptation flag */
if( this->GetUseCovarianceMatrixAdaptation() )
{
/** Check for too large deviation */
for( unsigned int i = 0; i < N; ++i )
{
const double sqrtCii = std::sqrt( this->m_C[ i ][ i ] );
const double actualDev = this->m_CurrentSigma * sqrtCii;
if( actualDev > this->m_MaximumDeviation )
{
this->m_CurrentSigma = this->m_MaximumDeviation / sqrtCii;
}
}
/** Check for too small deviation */
bool minDevViolated = false;
for( unsigned int i = 0; i < N; ++i )
{
const double sqrtCii = std::sqrt( this->m_C[ i ][ i ] );
const double actualDev = this->m_CurrentSigma * sqrtCii;
if( actualDev < this->m_MinimumDeviation )
{
this->m_CurrentSigma = this->m_MinimumDeviation / sqrtCii;
minDevViolated = true;
}
}
if( minDevViolated )
{
/** \todo: does this make sense if m_UseDecayingSigma == true??
* Anyway, we have to do something, in order to satisfy the minimum deviation */
this->m_CurrentSigma *= strange_factor;
}
}
else
{
/** If no covariance matrix adaptation is used, the check becomes simpler */
/** Check for too large deviation */
double actualDev = this->m_CurrentSigma;
if( actualDev > this->m_MaximumDeviation )
{
this->m_CurrentSigma = this->m_MaximumDeviation;
}
/** Check for too small deviation */
bool minDevViolated = false;
actualDev = this->m_CurrentSigma;
if( actualDev < this->m_MinimumDeviation )
{
this->m_CurrentSigma = this->m_MinimumDeviation;
minDevViolated = true;
}
if( minDevViolated )
{
/** \todo: does this make sense if m_UseDecayingSigma == true??
* Anyway, we have to do something, in order to satisfy the minimum deviation */
this->m_CurrentSigma *= strange_factor;
}
} // end else: no covariance matrix adaptation
/** Adjust too low coordinate axis deviations that would cause numerical
* problems (because of finite precision of the datatypes). This check
* is different depending on the m_UseCovarianceMatrixAdaptation flag */
const ParametersType & param = this->GetScaledCurrentPosition();
bool numericalProblemsEncountered = false;
if( this->GetUseCovarianceMatrixAdaptation() )
{
/** Check for numerically too small deviation */
for( unsigned int i = 0; i < N; ++i )
{
const double actualDev = 0.2 * this->m_CurrentSigma * std::sqrt( this->m_C[ i ][ i ] );
if( param[ i ] == ( param[ i ] + actualDev ) )
{
/** The parameters wouldn't change after perturbation, because
* of too low precision. Increase the problematic diagonal element of C */
this->m_C[ i ][ i ] *= ( 1.0 + c_cov );
numericalProblemsEncountered = true;
}
} // end for i
}
else
{
const double actualDev = 0.2 * this->m_CurrentSigma;
for( unsigned int i = 0; i < N; ++i )
{
if( param[ i ] == ( param[ i ] + actualDev ) )
{
/** The parameters wouldn't change after perturbation, because
* of too low precision. Increase the sigma (equivalent to
* increasing a diagonal element of C^0.5). */
this->m_CurrentSigma *= std::sqrt( 1.0 + c_cov );
numericalProblemsEncountered = true;
}
}
} // end else: no covariance matrix adaptation
if( numericalProblemsEncountered )
{
/** \todo: does this make sense if m_UseDecayingSigma == true??
* Anyway, we have to do something, in order to solve the numerical problems */
this->m_CurrentSigma *= strange_factor;
}
/** Check if "main axis standard deviation sigma*D(i,i) has effect" (?),
* with i = 1+floor(mod(countiter,N))
* matlabcode: if all( xmean == xmean + 0.1*sigma*B*D(:,i) )
* B*D(:,i) = i'th column of B times eigenvalue = i'th eigenvector * eigenvalue[i]
* In the code below: colnr=i-1 (zero-based indexing). */
bool numericalProblemsEncountered2 = false;
const unsigned int colnr = static_cast< unsigned int >( nextit % N );
if( this->GetUseCovarianceMatrixAdaptation() )
{
const double sigDcol = 0.1 * this->m_CurrentSigma * this->m_D[ colnr ];
//const ParametersType actualDevVector = sigDcol * this->m_B.get_column(colnr);
const ParametersType::VnlVectorType actualDevVector = sigDcol * this->m_B.get_column( colnr );
if( param == ( param + actualDevVector ) )
{
numericalProblemsEncountered2 = true;
}
}
else
{
/** B and D are not used, so can be considered identity matrices.
* This simplifies the check */
const double sigDcol = 0.1 * this->m_CurrentSigma;
if( param[ colnr ] == ( param[ colnr ] + sigDcol ) )
{
numericalProblemsEncountered2 = true;
}
} // end else: no covariance matrix adaptation
if( numericalProblemsEncountered2 )
{
/** \todo: does this make sense if m_UseDecayingSigma == true??
* Anyway, we have to do something, in order to solve the numerical problems */
this->m_CurrentSigma *= strange_factor2;
}
/** Adjust step size in case of equal function values (flat fitness) */
/** The indices of the two population members whose cost function will
* be compared */
const unsigned int populationMemberA = 0;
const unsigned int populationMemberB = static_cast< unsigned int >(
std::ceil( 0.1 + static_cast< double >( this->m_PopulationSize ) / 4.0 ) );
/** If they are the same: increase sigma with a magic factor */
if( this->m_CostFunctionValues[ populationMemberA ].first ==
this->m_CostFunctionValues[ populationMemberB ].first )
{
this->m_CurrentSigma *= strange_factor2;
}
/** Check if the best function value changes over iterations */
if( this->m_MeasureHistory.size() > 1 )
{
const MeasureType maxhist = *max_element(
this->m_MeasureHistory.begin(), this->m_MeasureHistory.end() );
const MeasureType minhist = *min_element(
this->m_MeasureHistory.begin(), this->m_MeasureHistory.end() );
if( maxhist == minhist )
{
this->m_CurrentSigma *= strange_factor2;
}
}
} // end FixNumericalErrors
/**
* ********************* TestConvergence ************************
*/
bool
CMAEvolutionStrategyOptimizer::TestConvergence( bool firstCheck )
{
itkDebugMacro( "TestConvergence" );
/** Get the number of parameters from the cost function */
const unsigned int numberOfParameters
= this->GetScaledCostFunction()->GetNumberOfParameters();
/** Some casts/aliases: */
const unsigned int N = numberOfParameters;
/** Check if the maximum number of iterations will not be exceeded in the following iteration */
if( ( this->GetCurrentIteration() + 1 ) >= this->GetMaximumNumberOfIterations() )
{
this->m_StopCondition = MaximumNumberOfIterations;
return true;
}
/** Check if the step was not too large:
* if ( sigma * sqrt(C[i,i]) > PositionToleranceMax*sigma0 for any i ) */
const double tolxmax = this->m_PositionToleranceMax * this->m_InitialSigma;
bool stepTooLarge = false;
if( this->GetUseCovarianceMatrixAdaptation() )
{
for( unsigned int i = 0; i < N; ++i )
{
const double sqrtCii = std::sqrt( this->m_C[ i ][ i ] );
const double stepsize = this->m_CurrentSigma * sqrtCii;
if( stepsize > tolxmax )
{
stepTooLarge = true;
break;
}
} // end for i
}
else
{
const double sqrtCii = 1.0;
const double stepsize = this->m_CurrentSigma * sqrtCii;
if( stepsize > tolxmax )
{
stepTooLarge = true;
}
} // end else: if no covariance matrix adaptation
if( stepTooLarge )
{
this->m_StopCondition = PositionToleranceMax;
return true;
}
/** Check for zero steplength (should never happen):
* if ( sigma * D[i] <= 0 for all i ) */
bool zeroStep = false;
if( this->GetUseCovarianceMatrixAdaptation() )
{
if( ( this->m_CurrentSigma * this->m_D.diagonal().max_value() ) <= 0.0 )
{
zeroStep = true;
}
}
else
{
if( this->m_CurrentSigma <= 0.0 )
{
zeroStep = true;
}
}
if( zeroStep )
{
this->m_StopCondition = ZeroStepLength;
return true;
}
/** The very first convergence check can not test for everything yet */
if( firstCheck )
{
return false;
}
/** Check if the step was not too small:
* if ( sigma * max( abs(p_c[i]), sqrt(C[i,i]) ) < PositionToleranceMin*sigma0 for all i ) */
const double tolxmin = this->m_PositionToleranceMin * this->m_InitialSigma;
bool stepTooSmall = true;
for( unsigned int i = 0; i < N; ++i )
{
const double pci = std::abs( this->m_EvolutionPath[ i ] );
double sqrtCii = 1.0;
if( this->m_UseCovarianceMatrixAdaptation )
{
sqrtCii = std::sqrt( this->m_C[ i ][ i ] );
}
const double stepsize = this->m_CurrentSigma * std::max( pci, sqrtCii );
if( stepsize > tolxmin )
{
stepTooSmall = false;
break;
}
}
if( stepTooSmall )
{
this->m_StopCondition = PositionToleranceMin;
return true;
}
/** Check if the best function value changes over iterations */
if( this->m_MeasureHistory.size() > 10 )
{
const MeasureType maxhist = *max_element(
this->m_MeasureHistory.begin(), this->m_MeasureHistory.end() );
const MeasureType minhist = *min_element(
this->m_MeasureHistory.begin(), this->m_MeasureHistory.end() );
if( ( maxhist - minhist ) < this->m_ValueTolerance )
{
this->m_StopCondition = ValueTolerance;
return true;
}
}
return false;
} // end TestConvergence
} // end namespace itk
#endif // #ifndef __itkCMAEvolutionStrategyOptimizer_cxx
| 31.93674 | 118 | 0.63439 | [
"vector"
] |
1650a943efbae4be1bc0cbf7888cb52a7037b5c8 | 26,294 | cpp | C++ | Server/Server.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 150 | 2015-01-14T15:06:38.000Z | 2018-08-28T09:34:17.000Z | Server/Server.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 28 | 2015-05-11T02:45:39.000Z | 2018-08-24T11:43:17.000Z | Server/Server.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 91 | 2015-05-04T09:52:41.000Z | 2018-08-18T13:02:15.000Z | /**
* @file Server.cpp
* @author suxunbin
* @date 12-AUG-2021
* @brief a gStore socket server
*/
#include "Server.h"
using namespace rapidjson;
using namespace std;
bool _stop = false; /**< A stopServer flag. */
Server::Server(int _port)
{
this->connectionPort = _port;
this->connectionMaxNum = Socket::MAX_CONNECTIONS;
this->databaseMaxNum = 10;
this->db_home = Util::global_config["db_home"];
this->db_suffix = Util::global_config["db_suffix"];
}
Server::~Server()
{
}
bool
Server::createConnection()
{
bool flag;
flag = this->socket.create();
if (!flag)
{
cerr << Util::getTimeString() << "Cannot create socket. @Server::createConnection" << endl;
return false;
}
flag = this->socket.bind(this->connectionPort);
if (!flag)
{
cerr << Util::getTimeString() << "Cannot bind to port " << this->connectionPort << ". @Server::createConnection" << endl;
return false;
}
flag = this->socket.listen();
if (!flag)
{
cerr << Util::getTimeString() << "Cannot listen to port" << this->connectionPort << ". @Server::createConnection" << endl;
return false;
}
return true;
}
bool
Server::deleteConnection()
{
bool flag = this->socket.close();
return flag;
}
bool
Server::response(int _code, std::string _msg, Socket& _socket)
{
std::string resJson = CreateJson(_code, _msg, 0);
bool flag = _socket.send(resJson);
return flag;
}
/**
* @brief A socket thread class
*/
class sockThread
{
public:
std::thread TD;
int tid; /**< A thread id. */
static int Threadnum; /**< A thread counter. */
Socket socket; /**< A client socket. */
Server* server;
/**
* @brief A constructor taking an argument.
* @param[in] _socket : A client socket
*/
sockThread(Socket& _socket);
/** @brief A default destructor. */
~sockThread();
/**
* @brief Get the thread id.
* @return The thread id.
*/
int GetThreadID();
/**
* @brief A thread handling function.
*/
void run();
/**
* @brief Start the thread.
*/
void start();
};
int sockThread::Threadnum = 0;
sockThread::sockThread(Socket& _socket)
{
Threadnum++;
tid = Threadnum;
socket = _socket;
}
sockThread::~sockThread()
{
}
int sockThread::GetThreadID()
{
return tid;
}
void sockThread::run()
{
cout << Util::getTimeString() << "Thread:" << tid << " run\n";
server->handler(socket);
}
void sockThread::start()
{
TD = std::thread(&sockThread::run, this);
TD.detach();
}
void
Server::handler(Socket& _socket)
{
int repeated_num = 0;
while (true)
{
if (repeated_num > 10)
break;
/**
* @brief Receive the command message from the client.
*/
std::string recv_cmd;
bool recv_return = _socket.recv(recv_cmd);
if (!recv_return)
{
cerr << Util::getTimeString() << "Receive command from client error. @Server::listen" << endl;
repeated_num++;
continue;
}
cout << Util::getTimeString() << "Received msg: " << recv_cmd << endl;
/**
* @brief Parse the command message and construct an operation.
*/
Operation operation;
bool parser_return = this->parser(recv_cmd, operation);
cout << Util::getTimeString() << "Parser_return=" << parser_return << endl; //debug
if (!parser_return)
{
cout << Util::getTimeString() << "Parser command error. @Server::listen" << endl;
std::string error = "Invalid command.";
this->response(1001, error, _socket);
repeated_num++;
continue;
}
/**
* @brief Execute the specific command function.
*/
std::string ret_msg;
CommandType cmd_type = operation.getCommand();
bool _close = false;
switch (cmd_type)
{
case CMD_TEST:
{
ret_msg = "OK";
break;
}
case CMD_LOGIN:
{
std::string username = operation.getParameter("username");
std::string password = operation.getParameter("password");
this->login(username, password, _socket);
break;
}
case CMD_LOAD:
{
std::string db_name = operation.getParameter("db_name");
this->load(db_name, _socket);
break;
}
case CMD_UNLOAD:
{
std::string db_name = operation.getParameter("db_name");
this->unload(db_name, _socket);
break;
}
case CMD_BUILD:
{
std::string db_name = operation.getParameter("db_name");
std::string db_path = operation.getParameter("db_path");
this->build(db_name, db_path, _socket);
break;
}
case CMD_DROP:
{
std::string db_name = operation.getParameter("db_name");
this->drop(db_name, _socket);
break;
}
case CMD_QUERY:
{
std::string db_name = operation.getParameter("db_name");
std::string sparql = operation.getParameter("sparql");
pthread_t timer = Server::start_timer();
if (timer == 0) {
cerr << Util::getTimeString() << "Failed to start timer." << endl;
}
this->query(db_name, sparql, _socket);
if (timer != 0 && !Server::stop_timer(timer)) {
cerr << Util::getTimeString() << "Failed to stop timer." << endl;
}
break;
}
case CMD_SHOW:
{
this->show(_socket);
break;
}
case CMD_STOP:
{
this->stopServer(_socket);
_stop = true;
_close = true;
break;
}
case CMD_CLOSE:
{
this->closeConnection(_socket);
_close = true;
break;
}
default:
{
cerr << Util::getTimeString() << "This command is not supported by now. @Server::listen" << endl;
std::string error = "Invalid command.";
this->response(1001, error, _socket);
}
}
if (_close)
break;
repeated_num = 0;
}
/**
* @brief Disconnect from the client.
*/
if (logins.find(_socket.username) != logins.end())
logins.erase(_socket.username);
_socket.username = "";
_socket.password = "";
_socket.close();
/**
* @brief Stop the server.
*/
if (_stop)
kill(getpid(), SIGTERM);
}
void
Server::init()
{
/**
* @brief Load the system database.
*/
if (access("system.db", 00) != 0)
{
cerr << Util::getTimeString() << "Can not find system.db." << endl;
return;
}
localDBs.insert(pair<std::string, int>("system", 1));
system_database = new Database("system");
bool flag = system_database->load();
if (!flag)
{
cerr << Util::getTimeString() << "Failed to load the database system.db." << endl;
delete system_database;
system_database = NULL;
return;
}
databases.insert(pair<std::string, Database*>("system", system_database));
importSys();
}
void
Server::listen()
{
this->init();
Socket soc[this->connectionMaxNum];
int i = 0;
Socket new_server_socket;
while (true)
{
/**
* @brief Receive the stopServer signal.
*/
signal(SIGTERM, Server::stop_sigterm_handler);
cout << Util::getTimeString() << "Wait for connection..." << endl;
this->socket.accept(new_server_socket);
cout << Util::getTimeString() << "Accept a new socket connection." << endl;
/**
* @brief Create a thread for a client socket.
*/
memcpy(&soc[i], &new_server_socket, sizeof(Socket));
sockThread* tid = new sockThread(soc[i++]);
tid->server = this;
tid->start();
}
}
std::string Server::checkparamValue(std::string param, std::string value)
{
std::string result = "";
if (value.empty())
{
result = "The value of " + param + " can not be empty!";
return result;
}
if (param == "db_name")
{
std::string database = value;
if (database == "system")
{
result = "You can not operate the system database.";
return result;
}
if (database.length() > 3 && database.substr(database.length() - 3, 3) == ".db")
{
result = "Your db_name to be built should not end with \".db\".";
return result;
}
}
if (param == "db_path")
{
std::string path = value;
if (path == SYSTEM_PATH)
{
result = "You can not operate the system files.";
return result;
}
}
return "";
}
bool Server::checkdbexist(std::string _db_name)
{
bool result = true;
std::map<std::string, int>::iterator it = localDBs.find(_db_name);
if (it == localDBs.end())
result = false;
return result;
}
bool Server::checkdbload(std::string _db_name)
{
bool result = true;
std::map<std::string, Database*>::iterator it = databases.find(_db_name);
if (it == databases.end())
result = false;
return result;
}
bool
Server::parser(std::string _raw_cmd, Operation& _ret_oprt)
{
/**
* @brief Check if the command is a valid JSON string.
*/
Document document;
document.Parse(_raw_cmd.c_str());
if (document.HasParseError())
return false;
/**
* @brief Delete the extra space.
*/
int para_start_pos = 0;
int raw_len = (int)_raw_cmd.size();
for (int i = 0; i < raw_len; i++) {
if (_raw_cmd[i] == '\n') {
_raw_cmd[i] = ' ';
}
}
while (para_start_pos < raw_len && _raw_cmd[para_start_pos] == ' ') {
para_start_pos++;
}
if (para_start_pos == raw_len)
return false;
std::unordered_map<std::string, std::string> paras;
int para_end_pos;
std::vector<std::string> para_vec;
/**
* @brief Get all parameters.
*/
while (true)
{
if (_raw_cmd[para_start_pos] == '"')
{
para_start_pos++;
para_end_pos = para_start_pos;
while (true)
{
if (_raw_cmd[para_end_pos] == '"')
break;
para_end_pos++;
}
std::string para = _raw_cmd.substr(para_start_pos, para_end_pos - para_start_pos);
para_vec.push_back(para);
para_start_pos = para_end_pos;
}
para_start_pos++;
if (_raw_cmd[para_start_pos] == '}')
break;
}
if (para_vec.size() % 2 == 1)
return false;
std::string cmd = "";
for (int i = 0; i < para_vec.size(); i += 2)
{
if (para_vec[i] == "op")
cmd = para_vec[i + 1];
paras.insert(pair<std::string, std::string>(para_vec[i], para_vec[i + 1]));
}
/**
* @brief Check if the parameters are valid.
*/
if (cmd == "")
return false;
int para_num = paras.size();
if (cmd == "test") {
_ret_oprt.setCommand(CMD_TEST);
}
if (cmd == "login") {
_ret_oprt.setCommand(CMD_LOGIN);
if (para_num != 3)
return false;
if ((paras.find("username") == paras.end()) || (paras.find("password") == paras.end()))
return false;
}
else if (cmd == "build") {
_ret_oprt.setCommand(CMD_BUILD);
if (para_num != 3)
return false;
if ((paras.find("db_name") == paras.end()) || (paras.find("db_path") == paras.end()))
return false;
}
else if (cmd == "load") {
_ret_oprt.setCommand(CMD_LOAD);
if (para_num != 2)
return false;
if (paras.find("db_name") == paras.end())
return false;
}
else if (cmd == "unload") {
_ret_oprt.setCommand(CMD_UNLOAD);
if (para_num != 2)
return false;
if (paras.find("db_name") == paras.end())
return false;
}
else if (cmd == "query") {
_ret_oprt.setCommand(CMD_QUERY);
if (para_num != 3)
return false;
if ((paras.find("db_name") == paras.end()) || (paras.find("sparql") == paras.end()))
return false;
}
else if (cmd == "show") {
_ret_oprt.setCommand(CMD_SHOW);
if (para_num != 1)
return false;
}
else if (cmd == "stop") {
_ret_oprt.setCommand(CMD_STOP);
if (para_num != 1)
return false;
}
else if (cmd == "close") {
_ret_oprt.setCommand(CMD_CLOSE);
if (para_num != 1)
return false;
}
else if (cmd == "drop") {
_ret_oprt.setCommand(CMD_DROP);
if (para_num != 2)
return false;
if (paras.find("db_name") == paras.end())
return false;
}
else {
return false;
}
_ret_oprt.setParameter(paras);
return true;
}
bool
Server::drop(std::string _db_name, Socket& _socket)
{
/**
* @brief Check if the client logins.
*/
if (logins.find(_socket.username) == logins.end())
{
std::string error = "Need to login first.";
this->response(1001, error, _socket);
return false;
}
/**
* @brief Check if the database name is legal.
*/
std::string result = checkparamValue("db_name", _db_name);
if (result.empty() == false)
{
this->response(1003, result, _socket);
return false;
}
/**
* @brief Check if database named [db_name] exists.
*/
if (!this->checkdbexist(_db_name))
{
std::string error = "Database not built yet.";
this->response(1004, error, _socket);
return false;
}
/**
* @brief Check if database named [db_name] is already loaded.
*/
if (this->checkdbload(_db_name))
{
std::string error = "Need to unload database first.";
this->response(1004, error, _socket);
return false;
}
std::string cmd = "rm -rf " + _db_name + ".db";
int ret = system(cmd.c_str());
if (ret == 0) {
localDBs.erase(_db_name);
std::string success = "Drop database done.";
this->response(0, success, _socket);
return true;
}
else {
std::string error = "Drop database failed.";
this->response(1005, error, _socket);
return false;
}
}
bool
Server::login(std::string _username, std::string _password, Socket& _socket)
{
/**
* @brief Check if the client's username and password is right.
*/
std::map<std::string, std::string>::iterator iter = users.find(_username);
if (iter == users.end())
{
std::string error = "username not find.";
this->response(903, error, _socket);
return false;
}
else if (iter->second != _password)
{
std::string error = "wrong password.";
this->response(902, error, _socket);
return false;
}
logins.insert(pair<std::string, int>(_username, 1));
std::string success = "Login successfully.";
this->response(0, success, _socket);
_socket.username = _username;
_socket.password = _password;
return true;
}
bool
Server::load(std::string _db_name, Socket& _socket)
{
/**
* @brief Check if the client logins.
*/
if (logins.find(_socket.username) == logins.end())
{
std::string error = "Need to login first.";
this->response(1001, error, _socket);
return false;
}
/**
* @brief Check if the database name is legal.
*/
std::string result = checkparamValue("db_name", _db_name);
if (result.empty() == false)
{
this->response(1003, result, _socket);
return false;
}
/**
* @brief Check if database named [db_name] exists.
*/
if (!this->checkdbexist(_db_name))
{
std::string error = "Database not built yet.";
this->response(1004, error, _socket);
return false;
}
/**
* @brief Check if database named [db_name] is already loaded.
*/
if (this->checkdbload(_db_name))
{
std::string error = "Database already load.";
this->response(0, error, _socket);
return false;
}
Database* database = new Database(_db_name);
bool flag = database->load();
if (!flag)
{
std::string error = "Failed to load the database.";
this->response(1005, error, _socket);
delete database;
database = NULL;
return false;
}
databases.insert(pair<std::string, Database*>(_db_name, database));
std::string success = "Load database successfully.";
this->response(0, success, _socket);
return true;
}
bool
Server::unload(std::string _db_name, Socket& _socket)
{
/**
* @brief Check if the client logins.
*/
if (logins.find(_socket.username) == logins.end())
{
std::string error = "Need to login first.";
this->response(1001, error, _socket);
return false;
}
/**
* @brief Check if the database name is legal.
*/
std::string result = checkparamValue("db_name", _db_name);
if (result.empty() == false)
{
this->response(1003, result, _socket);
return false;
}
/**
* @brief Check if database named [db_name] exists.
*/
if (!this->checkdbexist(_db_name))
{
std::string error = "Database not built yet.";
this->response(1004, error, _socket);
return false;
}
/**
* @brief Check if database named [db_name] is already unloaded.
*/
std::map<std::string, Database*>::iterator iter = databases.find(_db_name);
if (iter == databases.end())
{
std::string error = "Database: " + _db_name + " is not loaded yet.";
this->response(0, error, _socket);
return false;
}
Database* database = iter->second;
delete database;
database = NULL;
databases.erase(_db_name);;
std::string success = "Unload database done.";
this->response(0, success, _socket);
return true;
}
bool
Server::build(std::string _db_name, std::string _db_path, Socket& _socket)
{
/**
* @brief Check if the client logins.
*/
if (logins.find(_socket.username) == logins.end())
{
std::string error = "Need to login first.";
this->response(1001, error, _socket);
return false;
}
/**
* @brief Check if the database name is legal.
*/
std::string result = checkparamValue("db_name", _db_name);
if (result.empty() == false)
{
this->response(1003, result, _socket);
return false;
}
/**
* @brief Check if the rdf file path is legal.
*/
result = checkparamValue("db_path", _db_path);
if (result.empty() == false)
{
this->response(1003, result, _socket);
return false;
}
/**
* @brief Check if database named [db_name] is already built.
*/
if (this->checkdbexist(_db_name))
{
std::string error = "Database already built.";
this->response(1004, error, _socket);
return false;
}
cout << "Import dataset to build database..." << endl;
cout << "DB_store: " << _db_name << "\tRDF_data: " << _db_path << endl;
Database* database = new Database(_db_name);
bool flag = database->build(_db_path, _socket);
delete database;
database = NULL;
/**
* @brief Build the database failed.
*/
if (!flag)
{
std::string error = "Import RDF file to database failed.";
this->response(1005, error, _socket);
std::string cmd = "rm -rf " + _db_name + ".db";
system(cmd.c_str());
return false;
}
/**
* @brief Create a success flag file.
*/
ofstream fsuc;
fsuc.open("./" + _db_name + ".db/success.txt");
fsuc.close();
localDBs.insert(pair<std::string, int>(_db_name, 1));
std::string success = "Import RDF file to database done.";
this->response(0, success, _socket);
return true;
}
bool
Server::query(std::string _db_name, std::string _sparql, Socket& _socket)
{
/**
* @brief Check if the client logins.
*/
if (logins.find(_socket.username) == logins.end())
{
std::string error = "Need to login first.";
this->response(1001, error, _socket);
return false;
}
/**
* @brief Check if the database name is legal.
*/
std::string result = checkparamValue("db_name", _db_name);
if (result.empty() == false)
{
this->response(1003, result, _socket);
return false;
}
/**
* @brief Check if the sparql query is legal.
*/
result = checkparamValue("sparql", _sparql);
if (result.empty() == false)
{
this->response(1003, result, _socket);
return false;
}
/**
* @brief Check if database named [db_name] is already loaded.
*/
std::map<std::string, Database*>::iterator iter = databases.find(_db_name);
if (iter == databases.end())
{
std::string error = "Need to load database first.";
this->response(1004, error, _socket);
return false;
}
Database* database = iter->second;
FILE* output = NULL;
ResultSet res_set;
std::string _ret_msg;
int ret_val = database->query(_sparql, res_set, output);
if (output != NULL)
fclose(output);
/**
* @brief Select query.
*/
if (ret_val < -1)
{
if (ret_val == -100)
{
#ifdef SERVER_SEND_JSON
_ret_msg = res_set.to_JSON();
#else
_ret_msg = res_set.to_str();
#endif
Document resDoc;
Document::AllocatorType& allocator = resDoc.GetAllocator();
resDoc.Parse(_ret_msg.c_str());
resDoc.AddMember("StatusCode", 0, allocator);
resDoc.AddMember("StatusMsg", "success", allocator);
StringBuffer resBuffer;
PrettyWriter<StringBuffer> resWriter(resBuffer);
resDoc.Accept(resWriter);
std::string resJson = resBuffer.GetString();
_socket.send(resJson);
return true;
}
else /**< Query error. */
{
std::string error = "Query failed.";
this->response(1005, error, _socket);
return false;
}
}
else /**< Update query. */
{
if (ret_val >= 0)
{
std::string responsebody = "Update num: " + Util::int2string(ret_val);
std::string success = "success";
std::string resJson = CreateJson(0, success, true, responsebody);
_socket.send(resJson);
return true;
}
else /**< Update error. */
{
std::string error = "Update failed.";
this->response(1005, error, _socket);
return false;
}
}
}
bool
Server::show(Socket& _socket)
{
/**
* @brief Check if the client logins.
*/
if (logins.find(_socket.username) == logins.end())
{
std::string error = "Need to login first.";
this->response(1001, error, _socket);
return false;
}
std::map<std::string, int>::iterator iter;
Document resDoc;
resDoc.SetObject();
Document::AllocatorType& allocator = resDoc.GetAllocator();
Value jsonArray(kArrayType);
for (iter = localDBs.begin(); iter != localDBs.end(); iter++)
{
if (iter->first == "system")
continue;
Value obj(kObjectType);
Value db_name;
db_name.SetString(iter->first.c_str(), iter->first.length(), allocator);
if (databases.find(iter->first) == databases.end())
obj.AddMember(db_name, "unloaded", allocator);
else
obj.AddMember(db_name, "loaded", allocator);
jsonArray.PushBack(obj, allocator);
}
resDoc.AddMember("ResponseBody", jsonArray, allocator);
resDoc.AddMember("StatusCode", 0, allocator);
resDoc.AddMember("StatusMsg", "success", allocator);
StringBuffer resBuffer;
PrettyWriter<StringBuffer> resWriter(resBuffer);
resDoc.Accept(resWriter);
string resJson = resBuffer.GetString();
_socket.send(resJson);
return true;
}
bool Server::stopServer(Socket& _socket)
{
/**
* @brief Check if the client logins.
*/
if (logins.find(_socket.username) == logins.end())
{
std::string error = "Need to login first.";
this->response(1001, error, _socket);
return false;
}
/**
* @brief Check if the client is the root user.
*/
if (_socket.username != "root")
{
std::string error = "You have no rights to stop the server.";
this->response(1002, error, _socket);
return false;
}
std::map<std::string, Database*>::iterator iter;
for (iter = databases.begin(); iter != databases.end(); iter++)
{
delete iter->second;
iter->second = NULL;
}
databases.clear();
users.clear();
localDBs.clear();
logins.clear();
std::string success = "Server stopped.";
this->response(0, success, _socket);
return true;
}
bool Server::closeConnection(Socket& _socket) {
std::string success = "Connection disconnected.";
this->response(0, success, _socket);
return true;
}
pthread_t Server::start_timer() {
pthread_t timer_thread;
if (pthread_create(&timer_thread, NULL, Server::timer, NULL) == 0) {
return timer_thread;
}
return 0;
}
bool Server::stop_timer(pthread_t _timer) {
return pthread_kill(_timer, SIGTERM) == 0;
}
void* Server::timer(void* _args) {
/**
* @brief Receive the stop timer signal.
*/
signal(SIGTERM, Server::timer_sigterm_handler);
sleep(Util::gserver_query_timeout);
cerr << Util::getTimeString() << "Query out of time." << endl;
abort();
}
void Server::timer_sigterm_handler(int _signal_num) {
pthread_exit(0);
}
void Server::stop_sigterm_handler(int _signal_num) {
cout << Util::getTimeString() << "Server stopped." << endl;
exit(_signal_num);
}
void Server::dirTraversal(const char* _dir_name, std::vector<std::string>& _filename)
{
if (_dir_name == NULL)
{
std::cout << "dir_name is NULL ! " << std::endl;
return;
}
struct stat s;
lstat(_dir_name, &s);
if (!S_ISDIR(s.st_mode))
{
std::cout << "dir_name is not a valid directory ! " << std::endl;
return;
}
struct dirent* filename;
DIR* dir;
dir = opendir(_dir_name);
if (dir == NULL)
{
std::cout << "Can not open directory " << _dir_name << std::endl;
return;
}
while ((filename = readdir(dir)) != NULL)
{
if (strcmp(filename->d_name, ".") == 0 ||
strcmp(filename->d_name, "..") == 0)
continue;
_filename.push_back(filename->d_name);
}
return;
}
bool Server::querySys(std::string _sparql, std::string& _res)
{
FILE* output = NULL;
ResultSet res_set;
int ret_val = system_database->query(_sparql, res_set, output);
/**
* @brief Select query.
*/
if (ret_val < -1)
{
if (ret_val == -100)
{
#ifdef SERVER_SEND_JSON
_res = res_set.to_JSON();
#else
_res = res_set.to_str();
#endif
return true;
}
else /**< Query error. */
{
std::string error = "Query failed.";
cerr << Util::getTimeString() << error << endl;
return false;
}
}
else /**< Update query. */
{
if (ret_val >= 0)
{
_res = "Update num: " + Util::int2string(ret_val) + "\n";
return true;
}
else /**< Update error. */
{
std::string error = "Update failed.\n";
cerr << Util::getTimeString() << error << endl;
return false;
}
}
}
void Server::importSys()
{
/**
* @brief Query the system.db and get all users.
*/
std::string sparql = "select ?x ?y where{?x <has_password> ?y.}";
std::string strJson;
querySys(sparql, strJson);
Document document;
document.Parse(strJson.c_str());
Value& p1 = document["results"];
Value& p2 = p1["bindings"];
for (int i = 0; i < p2.Size(); i++)
{
Value& pp = p2[i];
Value& pp1 = pp["x"];
Value& pp2 = pp["y"];
std::string username = pp1["value"].GetString();
std::string password = pp2["value"].GetString();
users.insert(pair<std::string, std::string>(username, password));
}
/**
* @brief Query the system.db and get all databases.
*/
sparql = "select ?x where{?x <database_status> \"already_built\".}";
querySys(sparql, strJson);
document.Parse(strJson.c_str());
p1 = document["results"];
p2 = p1["bindings"];
for (int i = 0; i < p2.Size(); i++)
{
Value& pp = p2[i];
Value& pp1 = pp["x"];
std::string db_name = pp1["value"].GetString();
localDBs.insert(pair<std::string, int>(db_name, 1));
}
/**
* @brief Query the system.db and get the core version.
*/
sparql = "select ?x where{<CoreVersion> <value> ?x.}";
querySys(sparql, strJson);
document.Parse(strJson.c_str());
p1 = document["results"];
p2 = p1["bindings"];
for (int i = 0; i < p2.Size(); i++)
{
Value& pp = p2[i];
Value& pp1 = pp["x"];
CoreVersion = pp1["value"].GetString();
}
/**
* @brief Query the system.db and get the API version.
*/
sparql = "select ?x where{<APIVersion> <value> ?x.}";
querySys(sparql, strJson);
document.Parse(strJson.c_str());
p1 = document["results"];
p2 = p1["bindings"];
for (int i = 0; i < p2.Size(); i++)
{
Value& pp = p2[i];
Value& pp1 = pp["x"];
APIVersion = pp1["value"].GetString();
}
}
std::string Server::CreateJson(int StatusCode, std::string StatusMsg, bool _body_flag, std::string ResponseBody)
{
StringBuffer s;
PrettyWriter<StringBuffer> writer(s);
writer.StartObject();
if (_body_flag)
{
writer.Key("ResponseBody");
writer.String(StringRef(ResponseBody.c_str()));
}
writer.Key("StatusCode");
writer.Uint(StatusCode);
writer.Key("StatusMsg");
writer.String(StringRef(StatusMsg.c_str()));
writer.EndObject();
std::string res = s.GetString();
return res;
} | 21.98495 | 124 | 0.647372 | [
"vector"
] |
165245aaff9fb390a793753993a422bd996d1fe7 | 4,516 | cpp | C++ | source/core/search-manager/WildcardDocumentIterator.cpp | izenecloud/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 77 | 2015-02-12T20:59:20.000Z | 2022-03-05T18:40:49.000Z | source/core/search-manager/WildcardDocumentIterator.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 1 | 2017-04-28T08:55:47.000Z | 2017-07-10T10:10:53.000Z | source/core/search-manager/WildcardDocumentIterator.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 33 | 2015-01-05T03:03:05.000Z | 2022-02-06T04:22:46.000Z | #include "WildcardDocumentIterator.h"
using namespace izenelib::ir::indexmanager;
namespace sf1r
{
WildcardDocumentIterator::WildcardDocumentIterator(
collectionid_t colID,
IndexReader* pIndexReader,
const std::string& property,
unsigned int propertyId,
bool readPositions,
int maxTerms)
:maxTermThreshold_(maxTerms)
,pWildcardDocIteratorQueue_(NULL)
,colID_(colID)
,pIndexReader_(pIndexReader)
,pTermReader_(NULL)
,property_(property)
,propertyId_(propertyId)
,readPositions_(readPositions)
{
pTermReader_ = pIndexReader_->getTermReader(colID);
}
WildcardDocumentIterator::~WildcardDocumentIterator()
{
if (pWildcardDocIteratorQueue_)
delete pWildcardDocIteratorQueue_;
if (pTermReader_)
{
delete pTermReader_;
pTermReader_ = NULL;
}
}
void WildcardDocumentIterator::getTermIds(std::vector<termid_t>& termIds)
{
for (size_t i = 0; i < pWildcardDocIteratorQueue_->size(); ++i)
{
TermDocumentIterator* pDocIterator = pWildcardDocIteratorQueue_->getAt(i);
termIds.push_back(pDocIterator->termId());
}
}
void WildcardDocumentIterator::add(
termid_t termId,
unsigned termIndex,
std::map<termid_t, std::vector<izenelib::ir::indexmanager::TermDocFreqs*> >& termDocReaders)
{
#if PREFETCH_TERMID
std::map<termid_t, std::vector<izenelib::ir::indexmanager::TermDocFreqs*> >::iterator constIt
= termDocReaders.find(termId);
if(constIt != termDocReaders.end())
{
TermDocumentIterator* pIterator =
new TermDocumentIterator(termId,
colID_,
pIndexReader_,
property_,
propertyId_,
termIndex,
readPositions_);
pIterator->set(constIt->second.back() );
add(pIterator);
constIt->second.pop_back();
}
else
#endif
{
size_t df = 0;
Term term(property_.c_str(),termId);
bool find = pTermReader_->seek(&term);
if (find)
{
df = pTermReader_->docFreq(&term);
}
if (df > 0)
{
TermDocumentIterator* pIterator =
new TermDocumentIterator(termId,
colID_,
pIndexReader_,
property_,
propertyId_,
termIndex,
readPositions_);
pIterator->set_df(df);
add(pIterator);
}
}
}
void WildcardDocumentIterator::add(TermDocumentIterator* pDocIterator)
{
if (NULL == pWildcardDocIteratorQueue_)
pWildcardDocIteratorQueue_ = new WildcardDocumentIteratorQueue(maxTermThreshold_);
pWildcardDocIteratorQueue_->insert(pDocIterator);
}
void WildcardDocumentIterator::initDocIteratorQueue()
{
if (pWildcardDocIteratorQueue_->size() < 1)
return;
if (pTermReader_)
{
delete pTermReader_;
pTermReader_ = NULL;
}
pDocIteratorQueue_ = new DocumentIteratorQueue(pWildcardDocIteratorQueue_->size());
for (size_t i = 0; i < pWildcardDocIteratorQueue_->size(); ++i)
{
DocumentIterator* pDocIterator = pWildcardDocIteratorQueue_->getAt(i);
if (pDocIterator->next())
{
docIteratorList_.push_back(pDocIterator);
pDocIteratorQueue_->insert(pDocIterator);
}
}
pWildcardDocIteratorQueue_->setDel(false);
}
bool WildcardDocumentIterator::next()
{
return do_next();
}
void WildcardDocumentIterator::df_cmtf(
DocumentFrequencyInProperties& dfmap,
CollectionTermFrequencyInProperties& ctfmap,
MaxTermFrequencyInProperties& maxtfmap)
{
for (size_t i = 0; i < pWildcardDocIteratorQueue_->size(); ++i)
{
DocumentIterator* pDocIterator = pWildcardDocIteratorQueue_->getAt(i);
pDocIterator->df_cmtf(dfmap, ctfmap, maxtfmap);
}
}
unsigned int WildcardDocumentIterator::numIterators()
{
if (!pWildcardDocIteratorQueue_)
return 0;
else
return pWildcardDocIteratorQueue_->size();
}
} // namespace sf1r
| 28.764331 | 98 | 0.58636 | [
"vector"
] |
165dada3881719c14c7bfaaa41b7c33b213a0b44 | 726 | cpp | C++ | leetcode/algorithms/matrix/search-a-2D-matrix/Q240-search-a-2d-matrix-ii.cpp | jatin69/Revision-cpp | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 4 | 2020-01-16T14:49:46.000Z | 2021-08-23T12:45:19.000Z | leetcode/algorithms/matrix/search-a-2D-matrix/Q240-search-a-2d-matrix-ii.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 2 | 2018-06-06T13:08:11.000Z | 2018-10-02T19:07:32.000Z | leetcode/algorithms/matrix/search-a-2D-matrix/Q240-search-a-2d-matrix-ii.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 5 | 2018-10-02T13:49:16.000Z | 2021-08-11T07:29:50.000Z | /*
* Author : Jatin Rohilla
* Date : June-July-2019
*
* Compiler : g++ 5.1.0
* flags : -std=c++14
*/
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size()==0){
return false;
}
int rows = matrix.size();
int columns = matrix[0].size();
int i = 0;
int j = columns-1;
while(i < rows && j >= 0){
if(matrix[i][j] == target){
return true;
}
if(matrix[i][j] < target){
i++;
}
else{
j--;
}
}
return false;
}
};
| 17.707317 | 64 | 0.42011 | [
"vector"
] |
1664e5912e334d90304b56499f305c3ff97aa592 | 7,687 | cc | C++ | ui/base/x/selection_owner.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-01-16T03:57:39.000Z | 2019-01-16T03:57:39.000Z | ui/base/x/selection_owner.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | ui/base/x/selection_owner.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/x/selection_owner.h"
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include "base/logging.h"
#include "ui/base/x/selection_utils.h"
#include "ui/base/x/x11_util.h"
namespace ui {
namespace {
const char kAtomPair[] = "ATOM_PAIR";
const char kMultiple[] = "MULTIPLE";
const char kSaveTargets[] = "SAVE_TARGETS";
const char kTargets[] = "TARGETS";
const char* kAtomsToCache[] = {
kAtomPair,
kMultiple,
kSaveTargets,
kTargets,
NULL
};
// Gets the value of an atom pair array property. On success, true is returned
// and the value is stored in |value|.
bool GetAtomPairArrayProperty(XID window,
XAtom property,
std::vector<std::pair<XAtom,XAtom> >* value) {
XAtom type = None;
int format = 0; // size in bits of each item in 'property'
unsigned long num_items = 0;
unsigned char* properties = NULL;
unsigned long remaining_bytes = 0;
int result = XGetWindowProperty(gfx::GetXDisplay(),
window,
property,
0, // offset into property data to
// read
(~0L), // entire array
False, // deleted
AnyPropertyType,
&type,
&format,
&num_items,
&remaining_bytes,
&properties);
if (result != Success)
return false;
// GTK does not require |type| to be kAtomPair.
if (format != 32 || num_items % 2 != 0) {
XFree(properties);
return false;
}
XAtom* atom_properties = reinterpret_cast<XAtom*>(properties);
value->clear();
for (size_t i = 0; i < num_items; i+=2)
value->push_back(std::make_pair(atom_properties[i], atom_properties[i+1]));
XFree(properties);
return true;
}
} // namespace
SelectionOwner::SelectionOwner(XDisplay* x_display,
XID x_window,
XAtom selection_name)
: x_display_(x_display),
x_window_(x_window),
selection_name_(selection_name),
atom_cache_(x_display_, kAtomsToCache) {
}
SelectionOwner::~SelectionOwner() {
// If we are the selection owner, we need to release the selection so we
// don't receive further events. However, we don't call ClearSelectionOwner()
// because we don't want to do this indiscriminately.
if (XGetSelectionOwner(x_display_, selection_name_) == x_window_)
XSetSelectionOwner(x_display_, selection_name_, None, CurrentTime);
}
void SelectionOwner::RetrieveTargets(std::vector<XAtom>* targets) {
for (SelectionFormatMap::const_iterator it = format_map_.begin();
it != format_map_.end(); ++it) {
targets->push_back(it->first);
}
}
void SelectionOwner::TakeOwnershipOfSelection(
const SelectionFormatMap& data) {
XSetSelectionOwner(x_display_, selection_name_, x_window_, CurrentTime);
if (XGetSelectionOwner(x_display_, selection_name_) == x_window_) {
// The X server agrees that we are the selection owner. Commit our data.
format_map_ = data;
}
}
void SelectionOwner::ClearSelectionOwner() {
XSetSelectionOwner(x_display_, selection_name_, None, CurrentTime);
format_map_ = SelectionFormatMap();
}
void SelectionOwner::OnSelectionRequest(const XEvent& event) {
XID requestor = event.xselectionrequest.requestor;
XAtom requested_target = event.xselectionrequest.target;
XAtom requested_property = event.xselectionrequest.property;
// Incrementally build our selection. By default this is a refusal, and we'll
// override the parts indicating success in the different cases.
XEvent reply;
reply.xselection.type = SelectionNotify;
reply.xselection.requestor = requestor;
reply.xselection.selection = event.xselectionrequest.selection;
reply.xselection.target = requested_target;
reply.xselection.property = None; // Indicates failure
reply.xselection.time = event.xselectionrequest.time;
if (requested_target == atom_cache_.GetAtom(kMultiple)) {
// The contents of |requested_property| should be a list of
// <target,property> pairs.
std::vector<std::pair<XAtom,XAtom> > conversions;
if (GetAtomPairArrayProperty(requestor,
requested_property,
&conversions)) {
std::vector<XAtom> conversion_results;
for (size_t i = 0; i < conversions.size(); ++i) {
bool conversion_successful = ProcessTarget(conversions[i].first,
requestor,
conversions[i].second);
conversion_results.push_back(conversions[i].first);
conversion_results.push_back(
conversion_successful ? conversions[i].second : None);
}
// Set the property to indicate which conversions succeeded. This matches
// what GTK does.
XChangeProperty(
x_display_,
requestor,
requested_property,
atom_cache_.GetAtom(kAtomPair),
32,
PropModeReplace,
reinterpret_cast<const unsigned char*>(&conversion_results.front()),
conversion_results.size());
reply.xselection.property = requested_property;
}
} else {
if (ProcessTarget(requested_target, requestor, requested_property))
reply.xselection.property = requested_property;
}
// Send off the reply.
XSendEvent(x_display_, requestor, False, 0, &reply);
}
void SelectionOwner::OnSelectionClear(const XEvent& event) {
DLOG(ERROR) << "SelectionClear";
// TODO(erg): If we receive a SelectionClear event while we're handling data,
// we need to delay clearing.
}
bool SelectionOwner::ProcessTarget(XAtom target,
XID requestor,
XAtom property) {
XAtom multiple_atom = atom_cache_.GetAtom(kMultiple);
XAtom save_targets_atom = atom_cache_.GetAtom(kSaveTargets);
XAtom targets_atom = atom_cache_.GetAtom(kTargets);
if (target == multiple_atom || target == save_targets_atom)
return false;
if (target == targets_atom) {
// We have been asked for TARGETS. Send an atom array back with the data
// types we support.
std::vector<XAtom> targets;
targets.push_back(targets_atom);
targets.push_back(save_targets_atom);
targets.push_back(multiple_atom);
RetrieveTargets(&targets);
XChangeProperty(x_display_, requestor, property, XA_ATOM, 32,
PropModeReplace,
reinterpret_cast<unsigned char*>(&targets.front()),
targets.size());
return true;
} else {
// Try to find the data type in map.
SelectionFormatMap::const_iterator it = format_map_.find(target);
if (it != format_map_.end()) {
XChangeProperty(x_display_, requestor, property, target, 8,
PropModeReplace,
const_cast<unsigned char*>(
reinterpret_cast<const unsigned char*>(
it->second->front())),
it->second->size());
return true;
}
// I would put error logging here, but GTK ignores TARGETS and spams us
// looking for its own internal types.
}
return false;
}
} // namespace ui
| 35.100457 | 79 | 0.624821 | [
"vector"
] |
1667734528093f95be758008b5a04fc734012960 | 6,334 | cpp | C++ | src/leveldb-writer.cpp | XHPlus/deep-activity-rec | bb9003390ee3f9a721e4d61deb1a9b3f3144b304 | [
"BSD-2-Clause"
] | 140 | 2016-04-07T14:26:36.000Z | 2022-03-21T17:32:03.000Z | src/leveldb-writer.cpp | XHPlus/deep-activity-rec | bb9003390ee3f9a721e4d61deb1a9b3f3144b304 | [
"BSD-2-Clause"
] | 26 | 2016-09-13T03:01:24.000Z | 2021-10-09T21:21:50.000Z | src/leveldb-writer.cpp | XHPlus/deep-activity-rec | bb9003390ee3f9a721e4d61deb1a9b3f3144b304 | [
"BSD-2-Clause"
] | 42 | 2016-08-24T19:42:08.000Z | 2022-03-15T14:50:10.000Z | /*
* LeveldbWriter.cpp
*
* Created on: 2015-04-02
* Author: Moustafa S. Ibrahim
*/
#include <iostream>
#include "leveldb-writer.h"
using std::cerr;
using std::cout;
#include "utilities.h"
const int WRITING_LIMIT = 1000;
namespace MostCV {
LeveldbWriter::LeveldbWriter(string db_path_, int resize_height_, int resize_width_, int volumeSize, bool is_virtual_) {
max_label_cnt = -1;
db_path = db_path_;
resize_height = resize_height_;
resize_width = resize_width_;
volume_size = volumeSize;
is_virtual = is_virtual_;
cerr<<"\n\nCreates a database at: "<<db_path_<<"\n";
if(is_virtual_)
cerr<<"\tUing VIRTUAL MODE dataset\n\n";
countId = 0;
lastCountId = 0;
internal_idx = 1;
if (resize_height > 0) { // then something already defined for the shape
datum.set_channels(volume_size);
datum.set_height(resize_height);
datum.set_width(resize_width);
cerr<<"\t(H, W, C) = "<<resize_height<<" "<<resize_width<<" "<<volume_size<<"\n";
}
if(!is_virtual) {
// leveldb
leveldb::Options options;
options.error_if_exists = true;
options.create_if_missing = true;
options.write_buffer_size = 268435456; // 8 * 32 * 1024 * 1024
// Open db
LOG(INFO)<< "Opening leveldb " << db_path;
leveldb::Status status = leveldb::DB::Open(options, db_path, &db);
CHECK(status.ok()) << "Failed to open leveldb " << db_path << ". Is it already existing?";
batch = new leveldb::WriteBatch();
}
is_closed = false;
}
LeveldbWriter::~LeveldbWriter() {
forceFinalize();
}
void LeveldbWriter::clearDatum() {
assert(!is_closed);
datum.clear_data();
datum.clear_float_data();
}
void LeveldbWriter::setLabelsRange(int max_label_cnt) {
assert(!is_closed);
this->max_label_cnt = max_label_cnt;
}
void LeveldbWriter::setDatumLabel(int id) {
assert(!is_closed);
assert(id >= 0);
if (max_label_cnt != -1 && id >= max_label_cnt) {
cerr << "Wrong label! (Received, expected) = " << id << " - " << max_label_cnt << "\n";
assert(false);
}
datum.set_label(id);
labels.insert(id);
labelsVec.push_back(id);
}
void LeveldbWriter::addDatumToBatch(string key) {
assert(!is_closed);
if (key != "" && keys.insert(key).second == false)
cerr << "Warning: key duplication: " << key << "\n";
if(is_virtual) return;
string value;
assert(datum.SerializeToString(&value));
string prefix = MostCV::toIntStr("0000000", internal_idx++) + "@";
batch->Put(prefix + key, value);
if (++countId % WRITING_LIMIT == 0)
writeBatch();
clearDatum();
}
void LeveldbWriter::addDatumToBatch(caffe::Datum &datum, string key, int label) {
assert(!is_closed);
if (keys.insert(key).second == false)
cerr << "Warning: Key duplication: " << key << "\n";
assert(label >= 0);
string value;
datum.set_label(label);
labels.insert(label);
labelsVec.push_back(label);
if(is_virtual) return;
assert(datum.SerializeToString(&value));
string prefix = MostCV::toIntStr("0000000", internal_idx++) + "@";
batch->Put(prefix + key, value);
if (++countId % WRITING_LIMIT == 0)
writeBatch();
clearDatum();
}
bool LeveldbWriter::addVectorDatum(const vector<double> &feature_vec) {
assert(!is_closed);
if(is_virtual) return true;
clearDatum();
if (resize_height <= 0) { // use first vector to define the outline
datum.set_height(resize_height = feature_vec.size());
datum.set_channels(1);
datum.set_width(1);
} else
assert((int )feature_vec.size() == resize_height * resize_width * volume_size);
for (int p = 0; p < (int) feature_vec.size(); ++p)
datum.add_float_data(feature_vec[p]);
return true;
}
bool LeveldbWriter::addImageToDatum(Mat imgMat_origin, int num_channels) {
assert(!is_closed);
if(is_virtual) return true;
assert(resize_width > 0 && resize_height > 0);
assert(imgMat_origin.channels() == num_channels); // Weird to send it :D
Mat imgMat;
cv::resize(imgMat_origin, imgMat, Size(resize_width, resize_height));
// add to db: 256 * 256 * 3 = 196608
string* datum_string = datum.mutable_data();
if (num_channels == 3) {
for (int c = 0; c < num_channels; ++c) {
for (int h = 0; h < imgMat.rows; ++h) {
for (int w = 0; w < imgMat.cols; ++w) {
datum_string->push_back(static_cast<uint8_t>(imgMat.at<cv::Vec3b>(h, w)[c]));
}
}
}
} else {
for (int h = 0; h < imgMat.rows; ++h) {
for (int w = 0; w < imgMat.cols; ++w) {
datum_string->push_back(static_cast<uint8_t>(imgMat.at<uchar>(h, w)));
}
}
}
return true;
}
bool LeveldbWriter::addImageToDatum(const string& filename, int num_channels) {
assert(!is_closed);
if(is_virtual) return true;
int cv_read_flag = (num_channels == 3 ? CV_LOAD_IMAGE_COLOR : CV_LOAD_IMAGE_GRAYSCALE);
Mat imgMat_origin = cv::imread(filename, cv_read_flag);
if (!imgMat_origin.data) {
LOG(ERROR)<< "Could not open or find file " << filename;
return false;
}
return addImageToDatum(imgMat_origin, num_channels);
}
void LeveldbWriter::writeBatch() {
if (is_closed)
return;
if(is_virtual) return;
if (countId == lastCountId) // nothing changed
return;
leveldb::Status status = db->Write(leveldb::WriteOptions(), batch);
CHECK(status.ok()) << "Failed to write the batch. Count id: " << countId << "\n";
delete batch;
batch = new leveldb::WriteBatch();
LOG(ERROR)<<db_path<<": Processed " << countId << " files.";
lastCountId = countId;
}
void LeveldbWriter::forceFinalize() {
if (is_closed)
return;
if(!is_virtual) {
// write the last batch
if (countId % WRITING_LIMIT != 0)
writeBatch();
if (batch != NULL)
delete batch;
if (db != NULL)
delete db;
}
if (labels.size() == 1) // Zero case, means caller not interested in setting labels. Just dummy labels.
cerr << "\n\n\nThere is only ONE label in database. There should be a bug\n";
cerr<<"\nLabels Statistics for db "<<db_path<<"\n";
cerr<<"Total Records "<<labelsVec.size()<<"\n";
cerr<<"*********************************************************\n";
MostCV::getFrequencyMap(labelsVec, true);
cerr<<"*********************************************************\n";
MostCV::getFrequencyMapPercent(labelsVec, true);
is_closed = true;
}
}
| 24.08365 | 120 | 0.638143 | [
"shape",
"vector"
] |
1668f80dfaf29d1c088a3911c17fd98ff0eccd16 | 10,102 | cpp | C++ | src/trunk/libs/seiscomp3/datamodel/setup.cpp | quiffman/seiscomp3 | e0e9ad7d9dc53988a64ebdaaba8898c128f1860d | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/trunk/libs/seiscomp3/datamodel/setup.cpp | quiffman/seiscomp3 | e0e9ad7d9dc53988a64ebdaaba8898c128f1860d | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/trunk/libs/seiscomp3/datamodel/setup.cpp | quiffman/seiscomp3 | e0e9ad7d9dc53988a64ebdaaba8898c128f1860d | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | /***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* SeisComP Public License for more details. *
***************************************************************************/
// This file was created by a source code generator.
// Do not modify the contents. Change the definition and run the generator
// again!
#define SEISCOMP_COMPONENT DataModel
#include <seiscomp3/datamodel/setup.h>
#include <seiscomp3/datamodel/configstation.h>
#include <seiscomp3/datamodel/metadata.h>
#include <seiscomp3/logging/log.h>
namespace Seiscomp {
namespace DataModel {
IMPLEMENT_SC_CLASS_DERIVED(Setup, Object, "Setup");
Setup::MetaObject::MetaObject(const Core::RTTI* rtti) : Seiscomp::Core::MetaObject(rtti) {
addProperty(Core::simpleProperty("name", "string", false, false, true, false, false, false, NULL, &Setup::setName, &Setup::name));
addProperty(Core::simpleProperty("parameterSetID", "string", false, false, false, true, false, false, NULL, &Setup::setParameterSetID, &Setup::parameterSetID));
addProperty(Core::simpleProperty("enabled", "boolean", false, false, false, false, false, false, NULL, &Setup::setEnabled, &Setup::enabled));
}
IMPLEMENT_METAOBJECT(Setup)
SetupIndex::SetupIndex() {
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
SetupIndex::SetupIndex(const std::string& name_) {
name = name_;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
SetupIndex::SetupIndex(const SetupIndex& idx) {
name = idx.name;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool SetupIndex::operator==(const SetupIndex& idx) const {
return name == idx.name;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool SetupIndex::operator!=(const SetupIndex& idx) const {
return !operator==(idx);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Setup::Setup() {
_enabled = false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Setup::Setup(const Setup& other)
: Object() {
*this = other;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Setup::~Setup() {
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::operator==(const Setup& rhs) const {
if ( _index != rhs._index ) return false;
if ( _parameterSetID != rhs._parameterSetID ) return false;
if ( _enabled != rhs._enabled ) return false;
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::operator!=(const Setup& rhs) const {
return !operator==(rhs);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::equal(const Setup& other) const {
return *this == other;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Setup::setName(const std::string& name) {
_index.name = name;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const std::string& Setup::name() const {
return _index.name;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Setup::setParameterSetID(const std::string& parameterSetID) {
_parameterSetID = parameterSetID;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const std::string& Setup::parameterSetID() const {
return _parameterSetID;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Setup::setEnabled(bool enabled) {
_enabled = enabled;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::enabled() const {
return _enabled;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const SetupIndex& Setup::index() const {
return _index;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::equalIndex(const Setup* lhs) const {
if ( lhs == NULL ) return false;
return lhs->index() == index();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ConfigStation* Setup::configStation() const {
return static_cast<ConfigStation*>(parent());
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Setup& Setup::operator=(const Setup& other) {
_index = other._index;
_parameterSetID = other._parameterSetID;
_enabled = other._enabled;
return *this;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::assign(Object* other) {
Setup* otherSetup = Setup::Cast(other);
if ( other == NULL )
return false;
*this = *otherSetup;
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::attachTo(PublicObject* parent) {
if ( parent == NULL ) return false;
// check all possible parents
ConfigStation* configStation = ConfigStation::Cast(parent);
if ( configStation != NULL )
return configStation->add(this);
SEISCOMP_ERROR("Setup::attachTo(%s) -> wrong class type", parent->className());
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::detachFrom(PublicObject* object) {
if ( object == NULL ) return false;
// check all possible parents
ConfigStation* configStation = ConfigStation::Cast(object);
if ( configStation != NULL ) {
// If the object has been added already to the parent locally
// just remove it by pointer
if ( object == parent() )
return configStation->remove(this);
// The object has not been added locally so it must be looked up
else {
Setup* child = configStation->setup(index());
if ( child != NULL )
return configStation->remove(child);
else {
SEISCOMP_DEBUG("Setup::detachFrom(ConfigStation): setup has not been found");
return false;
}
}
}
SEISCOMP_ERROR("Setup::detachFrom(%s) -> wrong class type", object->className());
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Setup::detach() {
if ( parent() == NULL )
return false;
return detachFrom(parent());
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Object* Setup::clone() const {
Setup* clonee = new Setup();
*clonee = *this;
return clonee;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Setup::accept(Visitor* visitor) {
visitor->visit(this);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Setup::serialize(Archive& ar) {
// Do not read/write if the archive's version is higher than
// currently supported
if ( ar.isHigherVersion<0,8>() ) {
SEISCOMP_ERROR("Archive version %d.%d too high: Setup skipped",
ar.versionMajor(), ar.versionMinor());
ar.setValidity(false);
return;
}
ar & NAMED_OBJECT_HINT("name", _index.name, Archive::INDEX_ATTRIBUTE);
ar & NAMED_OBJECT_HINT("parameterSetID", _parameterSetID, Archive::XML_ELEMENT);
ar & NAMED_OBJECT_HINT("enabled", _enabled, Archive::XML_MANDATORY);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
}
| 28.536723 | 161 | 0.363294 | [
"object"
] |
166b0cee70dd4f5220395573ebd4ed6251103b0e | 1,468 | cpp | C++ | src/0079_Word_Search.cpp | Dephilia/leetcode_cpp | 2f0d85d842fafd43cae8d5ae99817c9e243d58e4 | [
"MIT"
] | null | null | null | src/0079_Word_Search.cpp | Dephilia/leetcode_cpp | 2f0d85d842fafd43cae8d5ae99817c9e243d58e4 | [
"MIT"
] | null | null | null | src/0079_Word_Search.cpp | Dephilia/leetcode_cpp | 2f0d85d842fafd43cae8d5ae99817c9e243d58e4 | [
"MIT"
] | null | null | null | #include <leetcode.hpp>
class Solution {
public:
bool dfs(vector<vector<char>>& board, const char* w, int x, int y, int& mx, int& my) {
// Important: Use the reference of board instead copy it.
if ( x < 0 ||
y < 0 ||
x >= mx ||
y >= my ||
*w != board[x][y] ||
board[x][y] == '\0') return false;
// cout << x << " " << y << endl;
if ( *(w+1) == '\0') return true;
char t = board[x][y]; // Note: The reference change the cell value, backup it.
board[x][y] = '\0';
if ( dfs(board, w + 1, x + 1, y, mx, my) ||
dfs(board, w + 1, x - 1, y, mx, my) ||
dfs(board, w + 1, x, y + 1, mx, my) ||
dfs(board, w + 1, x, y - 1, mx, my) ) {
return true;
}
board[x][y] = t;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int mx = board.size(), my = board[0].size();
for (int i=0; i<mx; i++) {
for (int j=0; j<my; j++) {
if (board[i][j] != word[0]) continue;
if (dfs(board, word.c_str(), i, j, mx, my)) return true;
}
}
return false;
}
};
int main() {
vector<vector<char>> board{
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
Solution sol;
cout << sol.exist(board, "ABCCED") << endl;
return 0;
}
| 28.230769 | 90 | 0.412125 | [
"vector"
] |
166ec1311bb91b56fa76d90072b99bde3a44af4f | 1,378 | cpp | C++ | RayTracingRenderer/RayTracingRenderer/Main.cpp | Nebye/Simple-Ray-Tracing-Renderer | 63877fa093d57bad04073bd68e2bc2418cd47306 | [
"CC0-1.0"
] | null | null | null | RayTracingRenderer/RayTracingRenderer/Main.cpp | Nebye/Simple-Ray-Tracing-Renderer | 63877fa093d57bad04073bd68e2bc2418cd47306 | [
"CC0-1.0"
] | null | null | null | RayTracingRenderer/RayTracingRenderer/Main.cpp | Nebye/Simple-Ray-Tracing-Renderer | 63877fa093d57bad04073bd68e2bc2418cd47306 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include "vec3.h"
#include "color.h"
#include <thread>
#include <chrono>
int main()
{
/*
std::cout << "Hello World! I am rusty and may keep this here for a lil bit..." << std::endl;
std::cin.get();
*/
// image
const int image_width = 256;
const int image_height = 256;
// render
std::cout << "P3\n" << image_width << ' ' << image_height << "\n255\n";
for (int i = (image_height - 1); i >= 0; i--)
{
// cerr is the error output stream
// first part of the progress indicator
std::cerr << "\rScanlines remaining: " << i << ' ' << std::flush;
// progress bar...a work in progress...
//std::cerr << "\rScanlines remaining: " << std::string(((((i / (image_height - 1)) - 1) * 100) * -1), '#') << ' ' << std::flush;
for (int j = 0; j < image_width; j++)
{
/*
auto r = double(j) / (image_width - 1);
auto g = double(i) / (image_height - 1);
auto b = 0.25;
int ir = static_cast<int>(255.99 * r);
int ig = static_cast<int>(255.99 * g);
int ib = static_cast<int>(255.99 * b);
std::cout << ir << ' ' << ig << ' ' << ib << '\n';
*/
// new implementation using vec3 and color header files
color pixel_color(double(j) / (image_width - 1), double(i) / (image_height - 1), 0.25);
write_color(std::cout, pixel_color);
}
}
// end of the progress indicator
std::cerr << "\nDone.\n";
} | 23.355932 | 131 | 0.563135 | [
"render"
] |
16710bc6dd410aec27f08b5f68716ab931450653 | 740 | hpp | C++ | src/audio/Recorder.hpp | okiwi6/Vominal | ba1b112a15fe8141287de42c8a55a55d36e651f9 | [
"MIT"
] | null | null | null | src/audio/Recorder.hpp | okiwi6/Vominal | ba1b112a15fe8141287de42c8a55a55d36e651f9 | [
"MIT"
] | null | null | null | src/audio/Recorder.hpp | okiwi6/Vominal | ba1b112a15fe8141287de42c8a55a55d36e651f9 | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Audio.hpp>
#include <vector>
#include <string>
#include <functional>
#include "OutputStream.hpp"
class Recorder : public sf::SoundRecorder {
public:
Recorder(std::string inputDevice=Recorder::getInputDevices()[0]);
~Recorder();
void setProcessCallback(std::function<void(const sf::Int16* samples, std::size_t sampleCount, uint16_t channelCount, uint32_t sampleRate)> func);
static std::vector<std::string> getInputDevices();
virtual bool onProcessSamples(const sf::Int16* samples, std::size_t sampleCount);
private:
std::function<void(const sf::Int16* samples, std::size_t sampleCount, uint16_t channelCount, uint32_t sampleRate)> processCallback;
}; | 33.636364 | 153 | 0.717568 | [
"vector"
] |
16744c116aa144e6dc08fbe83561c4af79efa715 | 6,954 | cpp | C++ | syncclient/src/main.cpp | zsuzuki/filesync | 9448e190f0b72e45ece4900ee3f13b5b7c8ea674 | [
"MIT"
] | null | null | null | syncclient/src/main.cpp | zsuzuki/filesync | 9448e190f0b72e45ece4900ee3f13b5b7c8ea674 | [
"MIT"
] | null | null | null | syncclient/src/main.cpp | zsuzuki/filesync | 9448e190f0b72e45ece4900ee3f13b5b7c8ea674 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <atomic>
#include <boost/algorithm/hex.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/uuid/detail/md5.hpp>
#include <connection.hpp>
#include <cstdio>
#include <cxxopts.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <memory>
#include <nlohmann/json.hpp>
#include <string>
#include <thread>
#include <vector>
namespace
{
namespace asio = boost::asio;
namespace fs = boost::filesystem;
using asio::ip::tcp;
using JSON = nlohmann::json;
bool verboseMode = false;
//
//
//
struct FileInfo
{
std::string file_name_;
fs::path real_path_;
std::string old_hash_;
std::string new_hash_;
bool exists_;
bool operator==(const FileInfo& o) { return file_name_ == o.file_name_; }
bool operator==(const std::string fn) { return file_name_ == fn; }
};
std::vector<FileInfo> fileList;
//
//
//
class Client : public Network::ConnectionBase
{
using Super = Network::ConnectionBase;
tcp::resolver resolver_;
std::string server_name_;
fs::path output_dir_;
std::atomic_bool is_connect_;
std::atomic_bool is_finished_;
public:
Client(asio::io_service& io_service)
: Super(io_service), resolver_(io_service), is_connect_(false),
is_finished_(false)
{
}
void start(std::string sv, std::string dir)
{
server_name_ = sv;
output_dir_ = dir;
connect();
}
// ファイルリストリクエスト
void requestFileList(const std::vector<std::string>& cmd)
{
Network::BufferList flist = {"filelist"};
for (auto& f : cmd)
flist.push_back(f);
Super::send("request", flist, [&](bool s) {
if (!s)
{
is_finished_ = false;
}
});
}
// メッセージ送信
void send(Network::BufferList& bl)
{
Super::send("command", bl, [&](bool s) {
if (!s)
{
is_finished_ = false;
}
});
}
bool isConnect() const { return is_connect_; }
bool isFinished() const { return is_finished_; }
private:
void connect()
{
tcp::resolver::query query(server_name_, "34000");
resolver_.async_resolve(
query, [&](auto& err, auto iter) { on_resolve(err, iter); });
}
//
void on_resolve(const boost::system::error_code& error,
tcp::resolver::iterator endpoint_iterator)
{
if (error)
{
std::cout << "resolve failed: " << error.message() << std::endl;
return;
}
asio::async_connect(socket_, endpoint_iterator, [&](auto& err, auto i) {
on_connect(err);
});
}
//
void on_connect(const boost::system::error_code& error)
{
if (error)
{
std::cout << "connect failed : " << error.message() << std::endl;
return;
}
receive();
is_connect_ = true;
}
//
void receive()
{
start_receive([&](auto cmd, auto buff) {
std::string command = cmd;
if (command != "error" && buff.size() > 0)
{
if (command == "filelist")
{
for (size_t i = 0; i < buff.size(); i += 2)
{
auto fname = buff[i];
auto rpath = (output_dir_ / fname).lexically_normal();
auto timestr = i + 1 < buff.size() ? buff[i + 1] : "";
auto wtime = std::stoull(timestr);
time_t uptime = 0;
if (fs::exists(rpath))
{
// ファイルがあるなら更新時刻を取得
uptime = fs::last_write_time(rpath);
}
if (wtime > uptime)
{
// サーバの方が新しい=更新
FileInfo nf;
nf.file_name_ = fname;
nf.real_path_ = rpath;
fileList.push_back(nf);
}
}
}
}
//
if (command == "error" || command == "finish")
{
// finish
is_finished_ = true;
std::cout << "Finished" << std::endl;
}
else
{
asio::post([&]() { copy_loop(0); });
}
});
}
//
void copy_loop(int idx)
{
for (; idx < fileList.size(); idx++)
{
auto& fi = fileList[idx];
Super::send("filereq", {fi.file_name_}, [&](bool) {
start_receive(fi.real_path_.generic_string(), [&]() {
if (fi.old_hash_.empty())
{
std::cout << "create: " << fi.real_path_ << " : " << fi.new_hash_
<< std::endl;
}
else
{
std::cout << "update: " << fi.real_path_ << " : " << fi.old_hash_
<< " -> " << fi.new_hash_ << std::endl;
}
asio::post([&]() { copy_loop(idx + 1); });
});
});
break;
}
if (idx >= fileList.size())
{
// 全転送完了
Super::send("finish", {"no error"}, [&](bool) {});
is_finished_ = true;
}
}
};
} // namespace
//
int
main(int argc, char** argv)
{
const fs::path app(argv[0]);
cxxopts::Options options(app.filename().generic_string(),
"directory synchronize client");
options.add_options()("h,help", "Print usage")(
"hostname",
"Hostname",
cxxopts::value<std::string>()->default_value("localhost"))(
"o,output",
"Output path",
cxxopts::value<std::string>()->default_value("."))(
"r,request",
"request directory",
cxxopts::value<std::string>()->default_value("."))(
"w,without",
"without pattern",
cxxopts::value<std::string>()->default_value(""))(
"v,verbose",
"verbose mode",
cxxopts::value<bool>()->default_value("false"));
options.parse_positional("hostname");
int ret = 0;
try
{
auto result = options.parse(argc, argv);
auto hostname = result["hostname"].as<std::string>();
if (result.count("help"))
{
std::cout << options.help() << std::endl;
return 0;
}
verboseMode = result["verbose"].as<bool>();
asio::io_service io_service;
Client client(io_service);
auto output_dir = result["output"].as<std::string>();
auto w = std::make_shared<asio::io_service::work>(io_service);
auto th = std::thread([&]() { io_service.run(); });
// 接続
client.start(hostname, output_dir);
while (client.isConnect() == false)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
// 要求(まずはファイルリストから)
Network::BufferList req;
req.push_back(result["request"].as<std::string>());
req.push_back(result["without"].as<std::string>());
client.requestFileList(req);
// 転送待ち
while (client.isFinished() == false)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
w.reset();
th.join();
}
catch (std::exception& e)
{
//
std::cout << options.help() << std::endl;
std::cerr << e.what() << std::endl;
ret = 1;
}
return ret;
}
| 23.815068 | 79 | 0.54386 | [
"vector"
] |
1675bb099e2a23386bf7c6d5a93ddcff1a1713f8 | 8,332 | cpp | C++ | src/libs/bindings/megaverse.cpp | DavidSlayback/megaverse | 6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc | [
"MIT"
] | 149 | 2021-06-09T01:28:57.000Z | 2022-03-30T20:31:25.000Z | src/libs/bindings/megaverse.cpp | DavidSlayback/megaverse | 6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc | [
"MIT"
] | 4 | 2021-06-30T17:06:18.000Z | 2022-02-17T21:58:13.000Z | src/libs/bindings/megaverse.cpp | DavidSlayback/megaverse | 6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc | [
"MIT"
] | 13 | 2021-07-10T06:49:24.000Z | 2022-03-08T05:11:35.000Z | #include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <opencv2/core/mat.hpp>
#include <util/tiny_logger.hpp>
#include <env/env.hpp>
#include <scenarios/init.hpp>
#include <magnum_rendering/magnum_env_renderer.hpp>
#ifndef CORRADE_TARGET_APPLE
#include <v4r_rendering/v4r_env_renderer.hpp>
#endif
#ifdef WITH_GUI
#include <viewer/viewer.hpp>
#endif
namespace py = pybind11;
using namespace Megaverse;
void setMegaverseLogLevel(int level)
{
setLogLevel(LogLevel(level));
}
class MegaverseGym
{
public:
MegaverseGym(
const std::string &scenario,
int w, int h,
int numEnvs, int numAgentsPerEnv, int numSimulationThreads,
bool useVulkan,
const std::map<std::string, float> &floatParams
)
: numEnvs{numEnvs}
, numAgentsPerEnv{numAgentsPerEnv}
, useVulkan{useVulkan}
, w{w}
, h{h}
, numSimulationThreads{numSimulationThreads}
{
scenariosGlobalInit();
for (int i = 0; i < numEnvs; ++i)
envs.emplace_back(std::make_unique<Env>(scenario, numAgentsPerEnv, floatParams));
rewards = std::vector<float>(size_t(numEnvs * numAgentsPerEnv));
}
void seed(int seedValue)
{
TLOG(INFO) << "Seeding vector env with seed value " << seedValue;
rng.seed((unsigned long) seedValue);
for (auto &e : envs) {
const auto noise = randRange(0, 1 << 30, rng);
e->seed(noise);
}
}
int numAgents() const
{
return envs.front()->getNumAgents();
}
void reset()
{
if (!vectorEnv) {
if (useVulkan)
#ifdef CORRADE_TARGET_APPLE
TLOG(ERROR) << "Vulkan not supported on MacOS";
#else
renderer = std::make_unique<V4REnvRenderer>(envs, w, h, nullptr, false);
#endif
else
renderer = std::make_unique<MagnumEnvRenderer>(envs, w, h);
vectorEnv = std::make_unique<VectorEnv>(envs, *renderer, numSimulationThreads);
}
// this also resets the main renderer
vectorEnv->reset();
}
std::vector<int> actionSpaceSizes() const
{
return Env::actionSpaceSizes;
}
void setActions(int envIdx, int agentIdx, std::vector<int> actions)
{
int actionIdx = 0, actionMask = 0;
const auto &spaces = Env::actionSpaceSizes;
for (int i = 0; i < int(actions.size()); ++i) {
const auto action = actions[i];
if (action > 0)
actionMask = actionMask | (1 << (actionIdx + action));
const auto numNonIdleActions = spaces[i] - 1;
actionIdx += numNonIdleActions;
}
envs[envIdx]->setAction(agentIdx, Action(actionMask));
}
void step()
{
vectorEnv->step();
}
bool isDone(int envIdx)
{
return vectorEnv->done[envIdx];
}
std::vector<float> getLastRewards()
{
int i = 0;
for (int envIdx = 0; envIdx < numEnvs; ++envIdx)
for (int agentIdx = 0; agentIdx < numAgentsPerEnv; ++agentIdx)
rewards[i++] = envs[envIdx]->getLastReward(agentIdx);
return rewards;
}
py::array_t<uint8_t> getObservation(int envIdx, int agentIdx)
{
const uint8_t *obsData = renderer->getObservation(envIdx, agentIdx);
return py::array_t<uint8_t>({h, w, 4}, obsData, py::none{}); // numpy object does not own memory
}
/**
* Call this before the first call to render()
*/
void setRenderResolution(int hiresW, int hiresH)
{
renderW = hiresW;
renderH = hiresH;
}
void drawHires()
{
if (!hiresRenderer) {
if (useVulkan)
#ifdef CORRADE_TARGET_APPLE
TLOG(ERROR) << "Vulkan not supported on MacOS";
#else
hiresRenderer = std::make_unique<V4REnvRenderer>(envs, renderW, renderH, dynamic_cast<V4REnvRenderer *>(renderer.get()), true);
#endif
else
hiresRenderer = std::make_unique<MagnumEnvRenderer>(envs, renderW, renderH);
for (int envIdx = 0; envIdx < int(envs.size()); ++envIdx)
hiresRenderer->reset(*envs[envIdx], envIdx);
}
for (int envIdx = 0; envIdx < int(envs.size()); ++envIdx) {
if (isDone(envIdx))
hiresRenderer->reset(*envs[envIdx], envIdx);
hiresRenderer->preDraw(*envs[envIdx], envIdx);
}
hiresRenderer->draw(envs);
}
void drawOverview()
{
#ifdef WITH_GUI
if (!viewer && Viewer::viewerExists) {
TLOG(INFO) << "Only one viewer per process is supported";
return;
}
if (!viewer) {
static int argc = 1;
static const char *argv[] = {"Overview"};
Magnum::Platform::Application::Arguments fakeArgs{argc, (char **) argv};
TLOG(INFO) << __FUNCTION__ << " Creating a viewer object";
viewer = std::make_unique<Viewer>(envs, useVulkan, renderer.get(), fakeArgs);
}
viewer->step(vectorEnv->done);
viewer->mainLoopIteration(); // handle events, update the window, that kind of thing
#else
// TLOG(ERROR) << "Megaverse was built without GUI support";
#endif
}
py::array_t<uint8_t> getHiresObservation(int envIdx, int agentIdx)
{
const uint8_t *obsData = hiresRenderer->getObservation(envIdx, agentIdx);
return py::array_t<uint8_t>({renderH, renderW, 4}, obsData, py::none{}); // numpy object does not own memory
}
float trueObjective(int envIdx, int agentIdx) const
{
return vectorEnv->trueObjectives[envIdx][agentIdx];
}
std::map<std::string, float> getRewardShaping(int envIdx, int agentIdx)
{
return envs[envIdx]->getScenario().getRewardShaping(agentIdx);
}
void setRewardShaping(int envIdx, int agentIdx, const std::map<std::string, float> &rewardShaping)
{
envs[envIdx]->getScenario().setRewardShaping(agentIdx, rewardShaping);
}
/**
* Explicitly destroy the env and the renderer to avoid doing this when the Python object goes out-of-scope.
*/
void close()
{
if (vectorEnv)
vectorEnv->close();
#ifdef WITH_GUI
if (viewer)
viewer->exit(0);
viewer.reset();
#endif
hiresRenderer.reset();
renderer.reset();
vectorEnv.reset();
envs.clear();
}
private:
Envs envs;
int numEnvs, numAgentsPerEnv;
std::vector<float> rewards; // to avoid reallocating on every call
std::unique_ptr<VectorEnv> vectorEnv;
std::unique_ptr<EnvRenderer> renderer, hiresRenderer;
Rng rng{std::random_device{}()};
#ifdef WITH_GUI
std::unique_ptr<Viewer> viewer;
#endif
bool useVulkan;
int w, h;
int renderW = 768, renderH = 432;
int numSimulationThreads;
};
PYBIND11_MODULE(megaverse, m)
{
m.doc() = "Megaverse Python bindings"; // optional module docstring
m.def("set_megaverse_log_level", &setMegaverseLogLevel, "Megaverse Log Level (0 to disable all logs, 2 for warnings");
py::class_<MegaverseGym>(m, "MegaverseGym")
.def(py::init<const std::string &, int, int, int, int, int, bool, const FloatParams &>())
.def("num_agents", &MegaverseGym::numAgents)
.def("action_space_sizes", &MegaverseGym::actionSpaceSizes)
.def("seed", &MegaverseGym::seed)
.def("reset", &MegaverseGym::reset)
.def("set_actions", &MegaverseGym::setActions)
.def("step", &MegaverseGym::step)
.def("is_done", &MegaverseGym::isDone)
.def("get_observation", &MegaverseGym::getObservation)
.def("get_last_rewards", &MegaverseGym::getLastRewards)
.def("true_objective", &MegaverseGym::trueObjective)
.def("set_render_resolution", &MegaverseGym::setRenderResolution)
.def("draw_hires", &MegaverseGym::drawHires)
.def("draw_overview", &MegaverseGym::drawOverview)
.def("get_hires_observation", &MegaverseGym::getHiresObservation)
.def("get_reward_shaping", &MegaverseGym::getRewardShaping)
.def("set_reward_shaping", &MegaverseGym::setRewardShaping)
.def("close", &MegaverseGym::close);
}
| 28.43686 | 143 | 0.608857 | [
"render",
"object",
"vector"
] |
1675ea7774b47cea729549a519c75570b19eca49 | 1,100 | hpp | C++ | closed_form.hpp | CorentinLeblond/jcr_pde1d | 12c13a9a230a75f54b0aeb68d05bffd249f80b38 | [
"BSD-3-Clause"
] | null | null | null | closed_form.hpp | CorentinLeblond/jcr_pde1d | 12c13a9a230a75f54b0aeb68d05bffd249f80b38 | [
"BSD-3-Clause"
] | null | null | null | closed_form.hpp | CorentinLeblond/jcr_pde1d | 12c13a9a230a75f54b0aeb68d05bffd249f80b38 | [
"BSD-3-Clause"
] | null | null | null | #ifndef CLOSED_FORM_HPP
#define CLOSED_FORM_HPP
#include <iostream>
#include <vector>
#include <algorithm>
#include "payoff.hpp"// Act on containers through iterators to apply modyfing/non_modifying operations
namespace project{
class VanillaOption
{
public:
PayOff* pay_off; //Pointer
double K;
double r;
double T;
double sigma;
VanillaOption();
VanillaOption(double _K, double _r, double _T,
double _sigma, PayOff* _pay_off);
};
double vanilla_payoff(double fwd, double strike, bool is_call);
double bs_time_value(double fwd, double strike, double volatility, double maturity);
double bs_price(double fwd, double strike, double volatility, double maturity, bool is_call);
std::vector<double> vanilla_payoff(const std::vector<double>& fwd, double strike, bool is_call);
std::vector<double> bs_time_value(const std::vector<double>& fwd, double strike, double volatility, double maturity);
std::vector<double> bs_price(const std::vector<double>& fwd, double strike, double volatility, double maturity, bool is_call);
}
#endif
| 31.428571 | 130 | 0.735455 | [
"vector"
] |
1676dd9b4b611e1cdd48ab22f02fd4a3b96950d3 | 670 | cpp | C++ | ch10/1001ex.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch10/1001ex.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch10/1001ex.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | 1 | 2022-01-25T15:51:34.000Z | 2022-01-25T15:51:34.000Z | #include <iostream>
#include <string>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
int main(void)
{
pair<string, int> temp;
vector<string> svec1;
vector<int> ivec1;
// 1
for(int i = 0; i < 2; i++)
{
cout << i+1 << "/2 " << "Enter string and int: ";
cin >> temp.first >> temp.second;
svec1.push_back(temp.first);
ivec1.push_back(temp.second);
}
// 输出1
for(vector<string>::iterator it = svec1.begin(); it != svec1.end(); it++)
{
cout << *it << ", ";
}
cout << endl;
for(vector<int>::iterator it = ivec1.begin(); it != ivec1.end(); it++)
{
cout << *it << ", ";
}
cout << endl;
return 0;
}
| 16.341463 | 74 | 0.58209 | [
"vector"
] |
167e85d51e80b55924122ed8073b1f9d14860cdb | 7,680 | cc | C++ | tensorflow/core/kernels/critical_section.cc | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/critical_section.cc | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/critical_section.cc | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | /* 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.
==============================================================================*/
#define EIGEN_USE_THREADS
#include <deque>
#include <utility>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/kernels/captured_function.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
class CriticalSection : public ResourceBase {
public:
explicit CriticalSection() : is_locked_(false) {}
~CriticalSection() override {
// Wait for all closures to finish running.
mutex_lock lock(mu_);
while (!closures_.empty()) {
queue_empty_cv_.wait(lock);
}
}
private:
friend class ExecuteInCriticalSectionOp;
void Acquire(std::function<void()> closure) {
std::function<void()> next;
{
mutex_lock ml(mu_);
if (is_locked_) {
closures_.push_back(std::move(closure));
} else {
// This branch is the common case. Avoid the queue.
is_locked_ = true;
next = std::move(closure);
}
}
if (next) {
next();
}
}
void Release() {
std::function<void()> next;
{
mutex_lock ml(mu_);
CHECK(is_locked_);
if (!closures_.empty()) {
// if queue is not empty, start the next entry off the queue.
std::swap(next, closures_.front());
closures_.pop_front();
} else {
is_locked_ = false;
queue_empty_cv_.notify_all();
}
}
if (next) {
next();
}
}
string DebugString() override {
tf_shared_lock ml(mu_);
return strings::StrCat("CriticalSection(locked: ", is_locked_,
" queue_size: ", closures_.size(), ")");
}
private:
mutex mu_;
std::deque<std::function<void()>> closures_ GUARDED_BY(mu_);
bool is_locked_ GUARDED_BY(mu_);
condition_variable queue_empty_cv_ GUARDED_BY(mu_);
};
class ExecuteInCriticalSectionOp : public AsyncOpKernel {
public:
explicit ExecuteInCriticalSectionOp(OpKernelConstruction* c)
: AsyncOpKernel(c) {
OP_REQUIRES_OK(c, c->GetAttr("f", &func_));
}
public:
void ComputeAsync(OpKernelContext* c, DoneCallback done) override {
CriticalSection* critical_section = nullptr;
OP_REQUIRES_OK_ASYNC(c,
LookupOrCreateResource<CriticalSection>(
c, HandleFromInput(c, 0), &critical_section,
[this, c](CriticalSection** ptr) {
*ptr = new CriticalSection;
return Status::OK();
}),
done);
// No need to Unref critical_section; the Closure below will take
// care of the Unref associated with this execution.
auto* execution = new Closure{std::move(done), c, critical_section, &func_};
execution->Start();
}
private:
class Closure {
public:
AsyncOpKernel::DoneCallback done_;
OpKernelContext* ctx_;
CriticalSection* cs_;
FunctionLibraryRuntime::Handle handle_;
FunctionLibraryRuntime::Options opts_;
std::vector<Tensor> arguments_t_;
std::vector<Tensor> output_t_;
NameAttrList* func_;
explicit Closure(AsyncOpKernel::DoneCallback done, OpKernelContext* ctx,
CriticalSection* critical_section, NameAttrList* func)
: done_(std::move(done)),
ctx_(ctx),
cs_(critical_section),
handle_(-1),
func_(func) {}
~Closure();
void Start() {
// Perform ExecuteFunction isnide a separate thread to avoid
// having lightweight Functions be inlined in this thread.
// That inlining would in turn inline DoneAndDelete inside the
// same thread. Since DoneAndDelete can call the next
// ExecuteFunction in the CriticalSection, this can cause a
// stack overflow.
cs_->Acquire(
[this]() { (*ctx_->runner())([this]() { ExecuteFunction(); }); });
}
private:
void ExecuteFunction();
void DoneAndDelete(const Status& status);
};
NameAttrList func_;
};
void ExecuteInCriticalSectionOp::Closure::ExecuteFunction() {
// Arguments to a Function are in the order:
// concat(<formal arguments>, <captured arguments>)
OpInputList arguments;
Status s = ctx_->input_list("arguments", &arguments);
if (!s.ok()) {
DoneAndDelete(s);
return;
}
arguments_t_.reserve(arguments.size());
for (const Tensor& t : arguments) {
arguments_t_.push_back(t);
}
auto* function_library = ctx_->function_library();
s = function_library->Instantiate(func_->name(), AttrSlice(&func_->attr()),
&handle_);
if (!s.ok()) {
DoneAndDelete(s);
return;
}
opts_.step_id = CapturedFunction::generate_step_id();
auto* step_container =
new ScopedStepContainer(opts_.step_id, [this](const string& name) {
ctx_->resource_manager()->Cleanup(name).IgnoreError();
});
opts_.cancellation_manager = ctx_->cancellation_manager();
opts_.step_container = step_container;
opts_.runner = ctx_->runner();
function_library->Run(opts_, handle_, arguments_t_, &output_t_,
[this](const Status& s) { DoneAndDelete(s); });
}
void ExecuteInCriticalSectionOp::Closure::DoneAndDelete(const Status& status) {
cs_->Release();
if (!status.ok()) {
ctx_->SetStatus(status);
} else {
OpOutputList output;
const Status s = ctx_->output_list("outputs", &output);
if (!s.ok()) {
ctx_->SetStatus(s);
} else if (output_t_.size() != output.size()) {
ctx_->SetStatus(errors::Internal(
"Could not set all outputs. Expected output size is ", output.size(),
" but function set ", output_t_.size(), " output values."));
} else {
for (int i = 0; i < output_t_.size(); ++i) {
output.set(i, output_t_[i]);
}
}
}
delete opts_.step_container;
opts_.step_container = nullptr;
done_();
cs_->Unref();
delete this;
}
ExecuteInCriticalSectionOp::Closure::~Closure() {
CHECK(!opts_.step_container)
<< "Initialized closure destroyed without calling Done";
}
REGISTER_KERNEL_BUILDER(Name("ExecuteInCriticalSection").Device(DEVICE_CPU),
ExecuteInCriticalSectionOp);
REGISTER_KERNEL_BUILDER(Name("CriticalSectionOp").Device(DEVICE_CPU),
ResourceHandleOp<CriticalSection>);
// TODO (ebrevdo): Re-enable once the cross-device function execution works. id:2626 gh:2628
#if GOOGLE_CUDA
REGISTER_KERNEL_BUILDER(Name("ExecuteInCriticalSection")
.Device(DEVICE_GPU)
.HostMemory("critical_section"),
ExecuteInCriticalSectionOp);
REGISTER_KERNEL_BUILDER(
Name("CriticalSectionOp").Device(DEVICE_GPU).HostMemory("resource"),
ResourceHandleOp<CriticalSection>);
#endif // GOOGLE_CUDA
} // namespace tensorflow
| 31.093117 | 92 | 0.640885 | [
"vector"
] |
16810b4b20f4212d0444f3a7432e2a20b3805a49 | 4,530 | cpp | C++ | monopoly/Classes/Scene/SelectScene.cpp | xmx-521/Monopoly | 6427672842ed94bb4dad585206ec08ec9a5f7a4d | [
"MIT"
] | 6 | 2020-10-09T14:51:47.000Z | 2021-04-16T08:26:55.000Z | monopoly/Classes/Scene/SelectScene.cpp | xmx-521/Monopoly | 6427672842ed94bb4dad585206ec08ec9a5f7a4d | [
"MIT"
] | null | null | null | monopoly/Classes/Scene/SelectScene.cpp | xmx-521/Monopoly | 6427672842ed94bb4dad585206ec08ec9a5f7a4d | [
"MIT"
] | 3 | 2020-05-12T06:56:40.000Z | 2021-04-30T09:38:12.000Z | #include "Scene/SelectScene.h"
#include "Scene/StartScene.h"
#include "Scene/MapScene.h"
#include "Scene/GameController.h"
#include "AudioEngine.h"
#include "ui/CocosGUI.h"
#include "Common/CommonConstant.h"
Scene *SelectScene::createScene()
{
return SelectScene::create();
}
bool SelectScene::transformToAi(int i, Ref *render, Sprite *ai, Sprite *player, MenuItemFont *item)
{
if (i == 1)
return false;
auto visible_size = Director::getInstance()->getVisibleSize();
auto sound_effect = AudioEngine::play2d("bottom_down.mp3", false);
is_ai_.at(i) = true;
ai->setPosition(Vec2(visible_size.width * (1.5f + i) / 10.f, visible_size.height * 7.f / 10.f));
player->setPosition(Vec2(visible_size.width * 10.f, visible_size.height * 10.f));
item->setCallback([=](Ref *ref) { transformToPlayer(i, ref, ai, player, item); });
return true;
}
bool SelectScene::transformToPlayer(int i, Ref *render, Sprite *ai, Sprite *player, MenuItemFont *item)
{
if (i == 1)
return false;
auto visible_size = Director::getInstance()->getVisibleSize();
auto sound_effect = AudioEngine::play2d("bottom_down.mp3", false);
is_ai_.at(i) = false;
ai->setPosition(Vec2(visible_size.width * 10.f, visible_size.height * 10));
player->setPosition(Vec2(visible_size.width * (1.5f + i) / 10.f, visible_size.height * 7.f / 10.f));
item->setCallback([=](Ref *ref) { transformToAi(i, ref, ai, player, item); });
return true;
}
bool SelectScene::addOption(int i)
{
MenuItemFont::setFontName("fonts/STHUPO.ttf");
MenuItemFont::setFontSize(25);
auto visible_size = Director::getInstance()->getVisibleSize();
auto avatar = Sprite::create(StringUtils::format("%s_avatar.png", player_name[i].c_str()));
avatar->setAnchorPoint(Vec2(0.5, 0.5));
avatar->setPosition(Vec2(visible_size.width * (1.5f + i) / 10.f, visible_size.height * 9.f / 10.f));
this->addChild(avatar, 20);
auto label = Label::createWithSystemFont(player_name[i], "fonts/arial.ttf", 22);
label->setTextColor(Color4B::WHITE);
label->setAnchorPoint(Vec2(0.5, 0.5));
label->setPosition(Vec2(visible_size.width * (1.5f + i) / 10.f, visible_size.height * 8.f / 10.f));
this->addChild(label, 26);
auto ai = Sprite::create("ai_image.png");
ai->setAnchorPoint(Vec2(0.5, 0.5));
ai->setPosition(Vec2(visible_size.width * 10.f, visible_size.height * 10.f));
this->addChild(ai, 50);
auto player = Sprite::create("player_image.png");
player->setAnchorPoint(Vec2(0.5, 0.5));
player->setPosition(Vec2(visible_size.width * (1.5f + i) / 10.f, visible_size.height * 7.f / 10.f));
this->addChild(player, 50);
if (i == 1)
return true;
auto item = MenuItemFont::create("Switch");
item->setCallback([=](Ref *render) {
transformToAi(i, render, ai, player, item);
});
item->setPosition(Vec2(visible_size.width * (1.5f + i) / 10.f, visible_size.height * 6.f / 10.f));
auto menu = Menu::create(item, nullptr);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 5);
return true;
}
bool SelectScene::init()
{
if (!Scene::init())
{
return false;
}
auto visible_size = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto background = Sprite::create("selectbackground.png");
background->setAnchorPoint(Vec2(0, 0));
background->setPosition(origin);
this->addChild(background, 0);
MenuItemFont::setFontName("fonts/STHUPO.ttf");
MenuItemFont::setFontSize(50);
for (int i = 1; i <= 7; i++)
is_ai_.push_back(false);
for (int i = 1; i <= 6; i++)
{
addOption(i);
}
MenuItemFont::setFontName("fonts/STHUPO.ttf");
MenuItemFont::setFontSize(50);
auto exit_item = MenuItemFont::create("Exit", [=](Ref *render) {
auto sound_effect = AudioEngine::play2d("bottom_down.mp3", false);
AudioEngine::stopAll();
auto scene = StartScene::createScene();
Director::getInstance()->replaceScene(TransitionFade::create(0.5f, scene, Color3B(0, 255, 255)));
});
auto start_item = MenuItemFont::create("Start", [=](Ref *render) {
auto sound_effect = AudioEngine::play2d("bottom_down.mp3", false);
auto temp = GameController::create(this->is_ai_);
});
float x = origin.x + visible_size.width / 7;
float y = origin.y + visible_size.width / 5;
start_item->setPosition(Vec2(x, y));
x = origin.x + visible_size.width * 6 / 7;
y = origin.y + visible_size.width / 5;
exit_item->setPosition(Vec2(x, y));
Vector<MenuItem *> menus;
menus.pushBack(start_item);
menus.pushBack(exit_item);
auto menu = Menu::createWithArray(menus);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
return true;
} | 33.555556 | 103 | 0.696909 | [
"render",
"vector"
] |
16840d38efdd5a00b449502bafb01ad6fa0636d3 | 2,742 | cpp | C++ | quantlib/algorithms/anapact/lib/csrc/normal_cuda.cpp | mdatres/quantlab | 09fb24ede78f49768f829afe0fac2ac291b8fd4f | [
"Apache-2.0"
] | null | null | null | quantlib/algorithms/anapact/lib/csrc/normal_cuda.cpp | mdatres/quantlab | 09fb24ede78f49768f829afe0fac2ac291b8fd4f | [
"Apache-2.0"
] | null | null | null | quantlib/algorithms/anapact/lib/csrc/normal_cuda.cpp | mdatres/quantlab | 09fb24ede78f49768f829afe0fac2ac291b8fd4f | [
"Apache-2.0"
] | 1 | 2022-01-02T10:10:46.000Z | 2022-01-02T10:10:46.000Z | /*
* normal_cuda.cpp
*
* Author(s):
* Matteo Spallanzani <spmatteo@iis.ee.ethz.ch>
*
* Copyright (c) 2020-2021 ETH Zurich.
*
* 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 <torch/extension.h>
#include <vector>
// #include <stdio.h> // for debug
// declarations of C++\CUDA interface (executed on: CPU)
torch::Tensor normal_forward_cuda_dispatch(
torch::Tensor x_in,
torch::Tensor q,
torch::Tensor t,
torch::Tensor mi,
torch::Tensor sigma,
torch::Tensor strategy,
torch::Tensor training
);
torch::Tensor normal_backward_cuda_dispatch(
torch::Tensor grad_in,
torch::Tensor x_in,
torch::Tensor q,
torch::Tensor t,
torch::Tensor mi,
torch::Tensor sigma
);
// definitions of C++ wrappers (executed on: CPU)
// goals:
// * check that the memory layout of tensors allocated on GPU memory is correct
// * call the dispatcher
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
torch::Tensor normal_forward_cuda(
torch::Tensor x_in,
torch::Tensor q,
torch::Tensor t,
torch::Tensor mi,
torch::Tensor sigma,
torch::Tensor strategy,
torch::Tensor training
)
{
CHECK_INPUT(x_in);
CHECK_INPUT(q);
CHECK_INPUT(t);
CHECK_INPUT(mi);
CHECK_INPUT(sigma);
CHECK_INPUT(strategy);
CHECK_INPUT(training);
return normal_forward_cuda_dispatch(x_in, q, t, mi, sigma, strategy, training);
}
torch::Tensor normal_backward_cuda(
torch::Tensor grad_in,
torch::Tensor x_in,
torch::Tensor q,
torch::Tensor t,
torch::Tensor mi,
torch::Tensor sigma
)
{
CHECK_INPUT(grad_in);
CHECK_INPUT(x_in);
CHECK_INPUT(q);
CHECK_INPUT(t);
CHECK_INPUT(mi);
CHECK_INPUT(sigma);
return normal_backward_cuda_dispatch(grad_in, x_in, q, t, mi, sigma);
}
// compile into a Python module
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
m.def("forward", &normal_forward_cuda, "ANA normal noise forward (CUDA)");
m.def("backward", &normal_backward_cuda, "ANA normal noise backward (CUDA)");
}
| 25.388889 | 84 | 0.688549 | [
"vector"
] |
1684392ca43db8205111f12dd92311d1134eae22 | 16,165 | cpp | C++ | third_party/WebKit/Source/platform/blob/BlobData.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/blob/BlobData.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/blob/BlobData.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/blob/BlobData.h"
#include <memory>
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/UUID.h"
#include "platform/blob/BlobBytesProvider.h"
#include "platform/blob/BlobRegistry.h"
#include "platform/text/LineEnding.h"
#include "platform/wtf/PassRefPtr.h"
#include "platform/wtf/PtrUtil.h"
#include "platform/wtf/RefPtr.h"
#include "platform/wtf/Vector.h"
#include "platform/wtf/text/CString.h"
#include "platform/wtf/text/TextEncoding.h"
#include "public/platform/FilePathConversion.h"
#include "public/platform/InterfaceProvider.h"
#include "public/platform/Platform.h"
using storage::mojom::blink::BlobPtr;
using storage::mojom::blink::BlobRegistryPtr;
using storage::mojom::blink::BytesProviderPtr;
using storage::mojom::blink::DataElement;
using storage::mojom::blink::DataElementBlob;
using storage::mojom::blink::DataElementPtr;
using storage::mojom::blink::DataElementBytes;
using storage::mojom::blink::DataElementBytesPtr;
using storage::mojom::blink::DataElementFile;
using storage::mojom::blink::DataElementFilesystemURL;
namespace blink {
namespace {
// All consecutive items that are accumulate to < this number will have the
// data appended to the same item.
static const size_t kMaxConsolidatedItemSizeInBytes = 15 * 1024;
// http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob
bool IsValidBlobType(const String& type) {
for (unsigned i = 0; i < type.length(); ++i) {
UChar c = type[i];
if (c < 0x20 || c > 0x7E)
return false;
}
return true;
}
} // namespace
const long long BlobDataItem::kToEndOfFile = -1;
RawData::RawData() {}
void RawData::DetachFromCurrentThread() {}
void BlobDataItem::DetachFromCurrentThread() {
data->DetachFromCurrentThread();
path = path.IsolatedCopy();
file_system_url = file_system_url.Copy();
}
std::unique_ptr<BlobData> BlobData::Create() {
return WTF::WrapUnique(
new BlobData(FileCompositionStatus::NO_UNKNOWN_SIZE_FILES));
}
std::unique_ptr<BlobData> BlobData::CreateForFileWithUnknownSize(
const String& path) {
std::unique_ptr<BlobData> data = WTF::WrapUnique(
new BlobData(FileCompositionStatus::SINGLE_UNKNOWN_SIZE_FILE));
data->items_.push_back(BlobDataItem(path));
return data;
}
std::unique_ptr<BlobData> BlobData::CreateForFileWithUnknownSize(
const String& path,
double expected_modification_time) {
std::unique_ptr<BlobData> data = WTF::WrapUnique(
new BlobData(FileCompositionStatus::SINGLE_UNKNOWN_SIZE_FILE));
data->items_.push_back(BlobDataItem(path, 0, BlobDataItem::kToEndOfFile,
expected_modification_time));
return data;
}
std::unique_ptr<BlobData> BlobData::CreateForFileSystemURLWithUnknownSize(
const KURL& file_system_url,
double expected_modification_time) {
std::unique_ptr<BlobData> data = WTF::WrapUnique(
new BlobData(FileCompositionStatus::SINGLE_UNKNOWN_SIZE_FILE));
data->items_.push_back(BlobDataItem(file_system_url, 0,
BlobDataItem::kToEndOfFile,
expected_modification_time));
return data;
}
void BlobData::DetachFromCurrentThread() {
content_type_ = content_type_.IsolatedCopy();
for (size_t i = 0; i < items_.size(); ++i)
items_.at(i).DetachFromCurrentThread();
}
void BlobData::SetContentType(const String& content_type) {
if (IsValidBlobType(content_type))
content_type_ = content_type;
else
content_type_ = "";
}
void BlobData::AppendData(PassRefPtr<RawData> data,
long long offset,
long long length) {
DCHECK_EQ(file_composition_, FileCompositionStatus::NO_UNKNOWN_SIZE_FILES)
<< "Blobs with a unknown-size file cannot have other items.";
items_.push_back(BlobDataItem(std::move(data), offset, length));
}
void BlobData::AppendFile(const String& path,
long long offset,
long long length,
double expected_modification_time) {
DCHECK_EQ(file_composition_, FileCompositionStatus::NO_UNKNOWN_SIZE_FILES)
<< "Blobs with a unknown-size file cannot have other items.";
DCHECK_NE(length, BlobDataItem::kToEndOfFile)
<< "It is illegal to append file items that have an unknown size. To "
"create a blob with a single file with unknown size, use "
"BlobData::createForFileWithUnknownSize. Otherwise please provide the "
"file size.";
items_.push_back(
BlobDataItem(path, offset, length, expected_modification_time));
}
void BlobData::AppendBlob(PassRefPtr<BlobDataHandle> data_handle,
long long offset,
long long length) {
DCHECK_EQ(file_composition_, FileCompositionStatus::NO_UNKNOWN_SIZE_FILES)
<< "Blobs with a unknown-size file cannot have other items.";
DCHECK(!data_handle->IsSingleUnknownSizeFile())
<< "It is illegal to append an unknown size file blob.";
items_.push_back(BlobDataItem(std::move(data_handle), offset, length));
}
void BlobData::AppendFileSystemURL(const KURL& url,
long long offset,
long long length,
double expected_modification_time) {
DCHECK_EQ(file_composition_, FileCompositionStatus::NO_UNKNOWN_SIZE_FILES)
<< "Blobs with a unknown-size file cannot have other items.";
items_.push_back(
BlobDataItem(url, offset, length, expected_modification_time));
}
void BlobData::AppendText(const String& text,
bool do_normalize_line_endings_to_native) {
DCHECK_EQ(file_composition_, FileCompositionStatus::NO_UNKNOWN_SIZE_FILES)
<< "Blobs with a unknown-size file cannot have other items.";
CString utf8_text =
UTF8Encoding().Encode(text, WTF::kEntitiesForUnencodables);
RefPtr<RawData> data = nullptr;
Vector<char>* buffer;
if (CanConsolidateData(text.length())) {
buffer = items_.back().data->MutableData();
} else {
data = RawData::Create();
buffer = data->MutableData();
}
if (do_normalize_line_endings_to_native) {
NormalizeLineEndingsToNative(utf8_text, *buffer);
} else {
buffer->Append(utf8_text.data(), utf8_text.length());
}
if (data)
items_.push_back(BlobDataItem(std::move(data)));
}
void BlobData::AppendBytes(const void* bytes, size_t length) {
DCHECK_EQ(file_composition_, FileCompositionStatus::NO_UNKNOWN_SIZE_FILES)
<< "Blobs with a unknown-size file cannot have other items.";
if (CanConsolidateData(length)) {
items_.back().data->MutableData()->Append(static_cast<const char*>(bytes),
length);
return;
}
RefPtr<RawData> data = RawData::Create();
Vector<char>* buffer = data->MutableData();
buffer->Append(static_cast<const char*>(bytes), length);
items_.push_back(BlobDataItem(std::move(data)));
}
long long BlobData::length() const {
long long length = 0;
for (Vector<BlobDataItem>::const_iterator it = items_.begin();
it != items_.end(); ++it) {
const BlobDataItem& item = *it;
if (item.length != BlobDataItem::kToEndOfFile) {
DCHECK_GE(item.length, 0);
length += item.length;
continue;
}
switch (item.type) {
case BlobDataItem::kData:
length += item.data->length();
break;
case BlobDataItem::kFile:
case BlobDataItem::kBlob:
case BlobDataItem::kFileSystemURL:
return BlobDataItem::kToEndOfFile;
}
}
return length;
}
bool BlobData::CanConsolidateData(size_t length) {
if (items_.IsEmpty())
return false;
BlobDataItem& last_item = items_.back();
if (last_item.type != BlobDataItem::kData)
return false;
if (last_item.data->length() + length > kMaxConsolidatedItemSizeInBytes)
return false;
return true;
}
BlobDataHandle::BlobDataHandle()
: uuid_(CreateCanonicalUUIDString()),
size_(0),
is_single_unknown_size_file_(false) {
if (RuntimeEnabledFeatures::MojoBlobsEnabled()) {
// TODO(mek): Going through InterfaceProvider to get a BlobRegistryPtr
// ends up going through the main thread. Ideally workers wouldn't need
// to do that.
BlobRegistryPtr registry;
Platform::Current()->GetInterfaceProvider()->GetInterface(
MakeRequest(®istry));
registry->Register(MakeRequest(&blob_), uuid_, "", "", {});
} else {
BlobRegistry::RegisterBlobData(uuid_, BlobData::Create());
}
}
BlobDataHandle::BlobDataHandle(std::unique_ptr<BlobData> data, long long size)
: uuid_(CreateCanonicalUUIDString()),
type_(data->ContentType().IsolatedCopy()),
size_(size),
is_single_unknown_size_file_(data->IsSingleUnknownSizeFile()) {
if (RuntimeEnabledFeatures::MojoBlobsEnabled()) {
// TODO(mek): Going through InterfaceProvider to get a BlobRegistryPtr
// ends up going through the main thread. Ideally workers wouldn't need
// to do that.
BlobRegistryPtr registry;
Platform::Current()->GetInterfaceProvider()->GetInterface(
MakeRequest(®istry));
size_t current_memory_population = 0;
Vector<DataElementPtr> elements;
const DataElementPtr null_element = nullptr;
BlobBytesProvider* last_bytes_provider = nullptr;
// TODO(mek): When the mojo code path is the default BlobData should
// directly create mojom::DataElements rather than BlobDataItems,
// eliminating the need for this loop.
for (const auto& item : data->Items()) {
// Skip zero-byte elements, as they don't matter for the contents of
// the blob.
if (item.length == 0)
continue;
switch (item.type) {
case BlobDataItem::kData: {
// kData elements don't set item.length, so separately check for zero
// byte kData elements.
if (item.data->length() == 0)
continue;
// Since blobs are often constructed with arrays with single bytes,
// consolidate all adjacent memory blob items into one. This should
// massively reduce the overhead of describing all these byte
// elements.
const DataElementPtr& last_element =
elements.IsEmpty() ? null_element : elements.back();
bool should_embed_bytes =
current_memory_population + item.data->length() <=
DataElementBytes::kMaximumEmbeddedDataSize;
bool last_element_is_bytes = last_element && last_element->is_bytes();
if (last_element_is_bytes) {
// Append bytes to previous element.
DCHECK(last_bytes_provider);
const auto& bytes_element = last_element->get_bytes();
bytes_element->length += item.data->length();
if (should_embed_bytes && bytes_element->embedded_data) {
bytes_element->embedded_data->Append(item.data->data(),
item.data->length());
current_memory_population += item.data->length();
} else if (bytes_element->embedded_data) {
current_memory_population -= bytes_element->embedded_data->size();
bytes_element->embedded_data = WTF::nullopt;
}
last_bytes_provider->AppendData(item.data);
} else {
BytesProviderPtr bytes_provider;
// TODO(mek): BytesProvider should be bound on a thread that doesn't
// run javascript to prevent deadlock if javascript starts trying to
// synchronously read the blob before all data has been transported
// to the browser process.
last_bytes_provider = static_cast<BlobBytesProvider*>(
MakeStrongBinding(WTF::MakeUnique<BlobBytesProvider>(item.data),
MakeRequest(&bytes_provider))
->impl());
DataElementBytesPtr bytes_element = DataElementBytes::New(
item.data->length(), WTF::nullopt, std::move(bytes_provider));
if (should_embed_bytes) {
bytes_element->embedded_data = Vector<uint8_t>();
bytes_element->embedded_data->Append(item.data->data(),
item.data->length());
current_memory_population += item.data->length();
}
elements.push_back(DataElement::NewBytes(std::move(bytes_element)));
}
break;
}
case BlobDataItem::kFile:
elements.push_back(DataElement::NewFile(DataElementFile::New(
WebStringToFilePath(item.path), item.offset, item.length,
WTF::Time::FromDoubleT(item.expected_modification_time))));
break;
case BlobDataItem::kFileSystemURL:
elements.push_back(
DataElement::NewFileFilesystem(DataElementFilesystemURL::New(
item.file_system_url, item.offset, item.length,
WTF::Time::FromDoubleT(item.expected_modification_time))));
break;
case BlobDataItem::kBlob: {
BlobPtr blob_clone;
item.blob_data_handle->blob_->Clone(MakeRequest(&blob_clone));
elements.push_back(DataElement::NewBlob(DataElementBlob::New(
std::move(blob_clone), item.offset, item.length)));
break;
}
}
}
registry->Register(MakeRequest(&blob_), uuid_, type_.IsNull() ? "" : type_,
"", std::move(elements));
} else {
BlobRegistry::RegisterBlobData(uuid_, std::move(data));
}
}
BlobDataHandle::BlobDataHandle(const String& uuid,
const String& type,
long long size)
: uuid_(uuid.IsolatedCopy()),
type_(IsValidBlobType(type) ? type.IsolatedCopy() : ""),
size_(size),
is_single_unknown_size_file_(false) {
if (RuntimeEnabledFeatures::MojoBlobsEnabled()) {
// TODO(mek): Going through InterfaceProvider to get a BlobRegistryPtr
// ends up going through the main thread. Ideally workers wouldn't need
// to do that.
storage::mojom::blink::BlobRegistryPtr registry;
Platform::Current()->GetInterfaceProvider()->GetInterface(
MakeRequest(®istry));
registry->GetBlobFromUUID(MakeRequest(&blob_), uuid_);
} else {
BlobRegistry::AddBlobDataRef(uuid_);
}
}
BlobDataHandle::~BlobDataHandle() {
if (!RuntimeEnabledFeatures::MojoBlobsEnabled())
BlobRegistry::RemoveBlobDataRef(uuid_);
}
} // namespace blink
| 39.717445 | 80 | 0.673925 | [
"vector"
] |
16866400752ba5f956b608ac3e94d88d925466dd | 16,769 | cpp | C++ | VrSamples/SampleFramework/Src/Model/ModelTrace.cpp | jmiskovic/lovr-oculus-mobile | 58f165fc47e7230bc5224b108ffdb710231fb0aa | [
"Unlicense"
] | 30 | 2018-10-22T08:10:09.000Z | 2022-02-17T06:56:02.000Z | VrSamples/SampleFramework/Src/Model/ModelTrace.cpp | jmiskovic/lovr-oculus-mobile | 58f165fc47e7230bc5224b108ffdb710231fb0aa | [
"Unlicense"
] | 11 | 2019-01-30T03:07:43.000Z | 2020-08-27T15:11:43.000Z | VrSamples/SampleFramework/Src/Model/ModelTrace.cpp | jmiskovic/lovr-oculus-mobile | 58f165fc47e7230bc5224b108ffdb710231fb0aa | [
"Unlicense"
] | 7 | 2019-01-24T12:44:37.000Z | 2021-09-23T18:25:15.000Z | /************************************************************************************
Filename : ModelTrace.cpp
Content : Ray tracer using a KD-Tree.
Created : May, 2014
Authors : J.M.P. van Waveren
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
*************************************************************************************/
#include "ModelTrace.h"
#include <math.h>
#include <algorithm>
#include <vector>
#include "Misc/Log.h"
using OVR::Matrix4f;
using OVR::Vector2f;
using OVR::Vector3f;
using OVR::Vector4f;
using OVR::Bounds3f;
namespace OVRFW
{
/*
An Efficient and Robust RayBox Intersection Algorithm
Amy Williams, Steve Barrus, R. Keith Morley, Peter Shirley
Journal of Graphics Tools, Issue 10, Pages 49-54, June 2005
Returns true if the ray intersects the bounds.
't0' and 't1' are the distances along the ray where the intersections occurs.
1st intersection = rayStart + t0 * rayDir
2nd intersection = rayStart + t1 * rayDir
*/
bool Intersect_RayBounds( const Vector3f & rayStart, const Vector3f & rayDir,
const Vector3f & mins, const Vector3f & maxs,
float & t0, float & t1 )
{
const float rcpDirX = ( fabsf( rayDir.x ) > MATH_FLOAT_SMALLEST_NON_DENORMAL ) ? ( 1.0f / rayDir.x ) : MATH_FLOAT_HUGE_NUMBER;
const float rcpDirY = ( fabsf( rayDir.y ) > MATH_FLOAT_SMALLEST_NON_DENORMAL ) ? ( 1.0f / rayDir.y ) : MATH_FLOAT_HUGE_NUMBER;
const float rcpDirZ = ( fabsf( rayDir.z ) > MATH_FLOAT_SMALLEST_NON_DENORMAL ) ? ( 1.0f / rayDir.z ) : MATH_FLOAT_HUGE_NUMBER;
const float sX = ( mins.x - rayStart.x ) * rcpDirX;
const float sY = ( mins.y - rayStart.y ) * rcpDirY;
const float sZ = ( mins.z - rayStart.z ) * rcpDirZ;
const float tX = ( maxs.x - rayStart.x ) * rcpDirX;
const float tY = ( maxs.y - rayStart.y ) * rcpDirY;
const float tZ = ( maxs.z - rayStart.z ) * rcpDirZ;
const float minX = std::min( sX, tX );
const float minY = std::min( sY, tY );
const float minZ = std::min( sZ, tZ );
const float maxX = std::max( sX, tX );
const float maxY = std::max( sY, tY );
const float maxZ = std::max( sZ, tZ );
t0 = std::max( minX, std::max( minY, minZ ) );
t1 = std::min( maxX, std::min( maxY, maxZ ) );
return ( t0 <= t1 );
}
/*
Fast, Minimum Storage Ray/Triangle Intersection
Tomas Möller, Ben Trumbore
Journal of Graphics Tools, 1997
Triangles are back-face culled.
Returns true if the ray intersects the triangle.
't0' is the distance along the ray where the intersection occurs.
intersection = rayStart + t0 * rayDir;
'u' and 'v' are the barycentric coordinates.
intersection = ( 1 - u - v ) * v0 + u * v1 + v * v2
*/
bool Intersect_RayTriangle( const Vector3f & rayStart, const Vector3f & rayDir,
const Vector3f & v0, const Vector3f & v1, const Vector3f & v2,
float & t0, float & u, float & v )
{
assert( rayDir.IsNormalized() );
const Vector3f edge1 = v1 - v0;
const Vector3f edge2 = v2 - v0;
const Vector3f tv = rayStart - v0;
const Vector3f pv = rayDir.Cross( edge2 );
const Vector3f qv = tv.Cross( edge1 );
const float det = edge1.Dot( pv );
// If the determinant is negative then the triangle is backfacing.
if ( det <= 0.0f )
{
return false;
}
// This code has been modified to only perform a floating-point
// division if the ray actually hits the triangle. If back facing
// triangles are not culled then the sign of 's' and 't' need to
// be flipped. This can be accomplished by multiplying the values
// with the determinant instead of the reciprocal determinant.
const float s = tv.Dot( pv );
const float t = rayDir.Dot( qv );
if ( s >= 0.0f && s <= det )
{
if ( t >= 0.0f && s + t <= det )
{
// If the determinant is almost zero then the ray lies in the triangle plane.
// This comparison is done last because it is usually rare for
// the ray to lay in the triangle plane.
if ( fabsf( det ) > MATH_FLOAT_SMALLEST_NON_DENORMAL )
{
const float rcpDet = 1.0f / det;
t0 = edge2.Dot( qv ) * rcpDet;
u = s * rcpDet;
v = t * rcpDet;
return true;
}
}
}
return false;
}
/*
Stackless KD-Tree Traversal for High Performance GPU Ray Tracing
Stefan Popov, Johannes Günther, Hans-Peter Seidel, Philipp Slusallek
Eurographics, Volume 26, Number 3, 2007
*/
const int RT_KDTREE_MAX_ITERATIONS = 128;
bool ModelTrace::Validate( const bool fullVerify ) const
{
bool invalid = false;
invalid |= header.numVertices != static_cast< int >( vertices.size() );
invalid |= header.numUvs != static_cast< int >( uvs.size() );
invalid |= header.numIndices != static_cast< int >( indices.size() );
invalid |= header.numNodes != static_cast< int >( nodes.size() );
invalid |= header.numLeafs != static_cast< int >( leafs.size() );
invalid |= header.numOverflow != static_cast< int >( overflow.size() );
if ( !invalid )
{
ALOG( "ModelTrace::Verify - invalid header" );
return false;
}
// the number of uvs must be either equal to the number of vertices, or 0
if ( static_cast< int >( uvs.size() ) != 0 && static_cast< int >( uvs.size() ) != static_cast< int >( vertices.size() ) )
{
ALOG( "ModelTrace::Verify - model must have no uvs, or the same number of uvs as vertices" );
return false;
}
if ( fullVerify )
{
// verify that all child indices are valid in each node
for ( int i = 0; i < static_cast< int >( nodes.size() ); ++i )
{
const kdtree_node_t & node = nodes[i];
const bool isLeaf = ( node.data & 1 ) != 0;
if ( isLeaf )
{
// leaves have no children to verify
continue;
}
int const leftChildIndex = node.data >> 3;
int const rightChildIndex = leftChildIndex + 1;
if ( leftChildIndex < 0 || leftChildIndex >= static_cast< int >( nodes.size() ) )
{
ALOG( "ModelTrace::Verify - leftChildIndex of %i for node %i is out of range, max %i", leftChildIndex, i, static_cast< int >( nodes.size() ) - 1 );
return false;
}
if ( rightChildIndex < 0 || rightChildIndex >= static_cast< int >( nodes.size() ) )
{
ALOG( "ModelTrace::Verify - rightChildIndex of %i for node %i is out of range, max %i", leftChildIndex, i, static_cast< int >( nodes.size() ) - 1 );
return false;
}
}
const int numTris = static_cast< int >( indices.size() ) / 3;
if ( numTris * 3 != static_cast< int >( indices.size() ) * 3 )
{
ALOG( "ModelTrace::Verify - Orphaned indices" );
return false;
}
// verify leaves don't point to any out-of-range triangles
for ( int i = 0; i < static_cast< int >( leafs.size() ); ++i )
{
const kdtree_leaf_t & leaf = leafs[i];
for ( int j = 0; j < RT_KDTREE_MAX_LEAF_TRIANGLES; ++j )
{
// if the triangle index is < 1 this is either the end of
// the triangle list, or an index into the overflow list
const int triIndex = leaf.triangles[j];
if ( triIndex < 0 )
{
if ( triIndex == -1 )
{
break; // no more triangles
}
// this is an index into the overflow -- verify it is in range
const int overflowIndex = triIndex & 0x7FFFFFFF;
if ( overflowIndex < 0 || overflowIndex >= static_cast< int >( overflow.size() ) )
{
ALOG( "ModelTrace::Verify - Leaf %i has an out of range overflow index %i at index %i, max %i", i, overflowIndex, j, numTris - 1 );
return false;
}
// we don't verify the overflow indices are in range of the triangle list here here because
// we'll do that explicity below to make sure we hit even overflow indices that aren't referenced by a leaf
}
else if ( triIndex >= numTris )
{
ALOG( "ModelTrace::Verify - Leaf %i has an out of range triangle of index %i at index %i, max %i", i, triIndex, j, numTris - 1 );
return false;
}
}
}
// verify overflow list doesn't point to any out-of-range triangles
for ( int i = 0; i < static_cast< int >( overflow.size() ); ++i )
{
if ( overflow[i] < 0 || overflow[i] >= numTris )
{
ALOG( "ModelTrace::Verify - overflow index %i value %i is out of range, max %i", i, overflow[i], numTris - 1 );
return false;
}
}
// verify indices do not point to any out-of-range vertices
for ( int i = 0; i < static_cast< int >( indices.size() ); ++i )
{
if ( indices[i] < 0 || indices[i] >= static_cast< int >( vertices.size() ) )
{
ALOG( "Index %i value %i is out of range, max %i", i, indices[i], static_cast< int >( vertices.size() ) - 1 );
return false;
}
}
}
return true;
}
traceResult_t ModelTrace::Trace( const Vector3f & start, const Vector3f & end ) const
{
// in debug, at least warn programmers if they're loading a model
// that fails simple validation.
assert( Validate( false ) );
traceResult_t result;
result.triangleIndex = -1;
result.fraction = 1.0f;
result.uv = Vector2f( 0.0f );
result.normal = Vector3f( 0.0f );
const Vector3f rayDelta = end - start;
const float rayLengthSqr = rayDelta.LengthSq();
const float rayLengthRcp = OVR::RcpSqrt( rayLengthSqr );
const float rayLength = rayLengthSqr * rayLengthRcp;
const Vector3f rayDir = rayDelta * rayLengthRcp;
const float rcpRayDirX = ( fabsf( rayDir.x ) > MATH_FLOAT_SMALLEST_NON_DENORMAL ) ? ( 1.0f / rayDir.x ) : MATH_FLOAT_HUGE_NUMBER;
const float rcpRayDirY = ( fabsf( rayDir.y ) > MATH_FLOAT_SMALLEST_NON_DENORMAL ) ? ( 1.0f / rayDir.y ) : MATH_FLOAT_HUGE_NUMBER;
const float rcpRayDirZ = ( fabsf( rayDir.z ) > MATH_FLOAT_SMALLEST_NON_DENORMAL ) ? ( 1.0f / rayDir.z ) : MATH_FLOAT_HUGE_NUMBER;
const float sX = ( header.bounds.GetMins()[0] - start.x ) * rcpRayDirX;
const float sY = ( header.bounds.GetMins()[1] - start.y ) * rcpRayDirY;
const float sZ = ( header.bounds.GetMins()[2] - start.z ) * rcpRayDirZ;
const float tX = ( header.bounds.GetMaxs()[0] - start.x ) * rcpRayDirX;
const float tY = ( header.bounds.GetMaxs()[1] - start.y ) * rcpRayDirY;
const float tZ = ( header.bounds.GetMaxs()[2] - start.z ) * rcpRayDirZ;
const float minX = std::min( sX, tX );
const float minY = std::min( sY, tY );
const float minZ = std::min( sZ, tZ );
const float maxX = std::max( sX, tX );
const float maxY = std::max( sY, tY );
const float maxZ = std::max( sZ, tZ );
const float t0 = std::max( minX, std::max( minY, minZ ) );
const float t1 = std::min( maxX, std::min( maxY, maxZ ) );
if ( t0 >= t1 )
{
return result;
}
float entryDistance = std::max( t0, 0.0f );
float bestDistance = std::min( t1 + 0.00001f, rayLength );
Vector2f uv;
const kdtree_node_t * currentNode = &nodes[0];
for ( int i = 0; i < RT_KDTREE_MAX_ITERATIONS; i++ )
{
const Vector3f rayEntryPoint = start + rayDir * entryDistance;
// Step down the tree until a leaf node is found.
while ( ( currentNode->data & 1 ) == 0 )
{
// Select the child node based on whether the entry point is left or right of the split plane.
// If the entry point is directly at the split plane then choose the side based on the ray direction.
const int nodePlane = ( ( currentNode->data >> 1 ) & 3 );
int child;
if ( rayEntryPoint[nodePlane] - currentNode->dist < 0.00001f ) child = 0;
else if ( rayEntryPoint[nodePlane] - currentNode->dist > 0.00001f ) child = 1;
else child = ( rayDelta[nodePlane] > 0.0f );
currentNode = &nodes[( currentNode->data >> 3 ) + child];
}
// Check for an intersection with a triangle in this leaf.
const kdtree_leaf_t * currentLeaf = &leafs[( currentNode->data >> 3 )];
const int * leafTriangles = currentLeaf->triangles;
int leafTriangleCount = RT_KDTREE_MAX_LEAF_TRIANGLES;
for ( int j = 0; j < leafTriangleCount; j++ )
{
int currentTriangle = leafTriangles[j];
if ( currentTriangle < 0 )
{
if ( currentTriangle == -1 )
{
break;
}
const int offset = ( currentTriangle & 0x7FFFFFFF );
leafTriangles = &overflow[offset];
leafTriangleCount = header.numOverflow - offset;
j = 0;
currentTriangle = leafTriangles[0];
}
float distance;
float u;
float v;
if ( Intersect_RayTriangle( start, rayDir,
vertices[indices[currentTriangle * 3 + 0]],
vertices[indices[currentTriangle * 3 + 1]],
vertices[indices[currentTriangle * 3 + 2]], distance, u, v ) )
{
if ( distance >= 0.0f && distance < bestDistance )
{
bestDistance = distance;
result.triangleIndex = currentTriangle * 3;
uv.x = u;
uv.y = v;
}
}
}
// Calculate the distance along the ray where the next leaf is entered.
const float sXX = ( currentLeaf->bounds.GetMins()[0] - start.x ) * rcpRayDirX;
const float sYY = ( currentLeaf->bounds.GetMins()[1] - start.y ) * rcpRayDirY;
const float sZZ = ( currentLeaf->bounds.GetMins()[2] - start.z ) * rcpRayDirZ;
const float tXX = ( currentLeaf->bounds.GetMaxs()[0] - start.x ) * rcpRayDirX;
const float tYY = ( currentLeaf->bounds.GetMaxs()[1] - start.y ) * rcpRayDirY;
const float tZZ = ( currentLeaf->bounds.GetMaxs()[2] - start.z ) * rcpRayDirZ;
const float maxXX = std::max( sXX, tXX );
const float maxYY = std::max( sYY, tYY );
const float maxZZ = std::max( sZZ, tZZ );
entryDistance = std::min( maxXX, std::min( maxYY, maxZZ ) );
if ( entryDistance >= bestDistance )
{
break;
}
// Calculate the exit plane.
const int exitX = ( 0 << 1 ) | ( ( sXX < tXX ) ? 1 : 0 );
const int exitY = ( 1 << 1 ) | ( ( sYY < tYY ) ? 1 : 0 );
const int exitZ = ( 2 << 1 ) | ( ( sZZ < tZZ ) ? 1 : 0 );
const int exitPlane = ( maxXX < maxYY ) ? ( maxXX < maxZZ ? exitX : exitZ ) : ( maxYY < maxZZ ? exitY : exitZ );
// Use a rope to enter the adjacent leaf.
const int exitNodeIndex = currentLeaf->ropes[exitPlane];
if ( exitNodeIndex == -1 )
{
break;
}
currentNode = &nodes[exitNodeIndex];
}
if ( result.triangleIndex != -1 )
{
result.fraction = bestDistance * rayLengthRcp;
// return default uvs if the model has no uvs
if ( static_cast< int >( uvs.size() ) == 0 )
{
result.uv = Vector2f( 0.0f, 0.0f );
}
else
{
result.uv = uvs[indices[result.triangleIndex + 0]] * ( 1.0f - uv.x - uv.y ) +
uvs[indices[result.triangleIndex + 1]] * uv.x +
uvs[indices[result.triangleIndex + 2]] * uv.y;
}
const Vector3f d1 = vertices[indices[result.triangleIndex + 1]] - vertices[indices[result.triangleIndex + 0]];
const Vector3f d2 = vertices[indices[result.triangleIndex + 2]] - vertices[indices[result.triangleIndex + 0]];
result.normal = d1.Cross( d2 ).Normalized();
}
return result;
}
traceResult_t ModelTrace::Trace_Exhaustive( const Vector3f & start, const Vector3f & end ) const
{
// in debug, at least warn programmers if they're loading a model
// that fails simple validation.
assert( Validate( false ) );
traceResult_t result;
result.triangleIndex = -1;
result.fraction = 1.0f;
result.uv = Vector2f( 0.0f );
result.normal = Vector3f( 0.0f );
const Vector3f rayDelta = end - start;
const float rayLengthSqr = rayDelta.LengthSq();
const float rayLengthRcp = OVR::RcpSqrt( rayLengthSqr );
const float rayLength = rayLengthSqr * rayLengthRcp;
const Vector3f rayStart = start;
const Vector3f rayDir = rayDelta * rayLengthRcp;
float bestDistance = rayLength;
Vector2f uv;
for ( int i = 0; i < header.numIndices; i += 3 )
{
float distance;
float u;
float v;
if ( Intersect_RayTriangle( rayStart, rayDir,
vertices[indices[i + 0]],
vertices[indices[i + 1]],
vertices[indices[i + 2]], distance, u, v ) )
{
if ( distance >= 0.0f && distance < bestDistance )
{
bestDistance = distance;
result.triangleIndex = i;
uv.x = u;
uv.y = v;
}
}
}
if ( result.triangleIndex != -1 )
{
result.fraction = bestDistance * rayLengthRcp;
// return default uvs if the model has no uvs
if ( static_cast< int >( uvs.size() ) == 0 )
{
result.uv = Vector2f( 0.0f, 0.0f );
}
else
{
result.uv = uvs[indices[result.triangleIndex + 0]] * ( 1.0f - uv.x - uv.y ) +
uvs[indices[result.triangleIndex + 1]] * uv.x +
uvs[indices[result.triangleIndex + 2]] * uv.y;
}
const Vector3f d1 = vertices[indices[result.triangleIndex + 1]] - vertices[indices[result.triangleIndex + 0]];
const Vector3f d2 = vertices[indices[result.triangleIndex + 2]] - vertices[indices[result.triangleIndex + 0]];
result.normal = d1.Cross( d2 ).Normalized();
}
return result;
}
void ModelTrace::PrintStatsToLog() const
{
ALOG( "ModelTrace Stats:");
ALOG( " Vertices: %i", static_cast< int >( vertices.size() ) );
ALOG( " UVs : %i", static_cast< int >( uvs.size() ) );
ALOG( " Indices : %i", static_cast< int >( indices.size() ) );
ALOG( " Nodes : %i", static_cast< int >( nodes.size() ) );
ALOG( " Leaves : %i", static_cast< int >( leafs.size() ) );
ALOG( " Overflow: %i", static_cast< int >( overflow.size() ) );
}
} // namespace OVRFW
| 34.083333 | 152 | 0.639573 | [
"vector",
"model"
] |
168ee0d2971c536d154c0532b58eddf8d0b2a8f6 | 1,445 | hh | C++ | include/libfluid-base/TLS.hh | DavidLiu506/alcor-control-agent | 57682ee3bd061eae930ff81018ce3387ea9eec7a | [
"MIT"
] | 12 | 2020-02-21T19:54:42.000Z | 2021-01-25T20:12:35.000Z | include/libfluid-base/TLS.hh | DavidLiu506/alcor-control-agent | 57682ee3bd061eae930ff81018ce3387ea9eec7a | [
"MIT"
] | 128 | 2020-02-21T19:28:59.000Z | 2022-03-17T02:06:29.000Z | include/libfluid-base/TLS.hh | DavidLiu506/alcor-control-agent | 57682ee3bd061eae930ff81018ce3387ea9eec7a | [
"MIT"
] | 40 | 2020-03-30T23:05:13.000Z | 2021-11-18T01:03:47.000Z | // Copyright (c) 2014 Open Networking Foundation
// Copyright 2020 Futurewei Cloud
//
// 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.
/** @file Functions for secure communication using SSL */
#ifndef __SSL_IMPL_HH__
#define __SSL_IMPL_HH__
namespace fluid_base {
/** SSL implementation pointer for internal library use. */
extern void* tls_obj;
/** Initialize SSL parameters. You must call this function before
asking any object to communicate in a secure manner.
@param cert The controller's certificate signed by a CA
@param privkey The controller's private key to be used with the
certificate
@param trustedcert A CA certificate that signs certificates of trusted
switches */
void libfluid_tls_init(const char* cert, const char* privkey, const char* trustedcert);
/** Free SSL data. You must call this function after you don't need secure
communication anymore. */
void libfluid_tls_clear();
}
#endif | 37.051282 | 88 | 0.754325 | [
"object"
] |
168f08008fc9c70fb8cb238c0c78348ff12d1785 | 6,940 | hpp | C++ | blast/include/objmgr/impl/tse_info_object.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objmgr/impl/tse_info_object.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objmgr/impl/tse_info_object.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | #ifndef OBJECTS_OBJMGR_IMPL___TSE_INFO_OBJECT__HPP
#define OBJECTS_OBJMGR_IMPL___TSE_INFO_OBJECT__HPP
/* $Id: tse_info_object.hpp 516051 2016-10-07 15:16:44Z vasilche $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksey Grichenko, Eugene Vasilchenko
*
* File Description:
* Bioseq info for data source
*
*/
#include <corelib/ncbiobj.hpp>
#include <objmgr/bio_object_id.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
class CDataSource;
class CTSE_Info;
class CSeq_entry;
class CSeq_entry_Info;
class CSeq_annot;
class CSeq_annot_Info;
class CSeq_descr;
////////////////////////////////////////////////////////////////////
//
// CTSE_Info_Object::
//
// Structure to keep bioseq's parent seq-entry along with the list
// of seq-id synonyms for the bioseq.
//
class NCBI_XOBJMGR_EXPORT CTSE_Info_Object : public CObject
{
public:
typedef map<CConstRef<CObject>, CRef<CObject> > TObjectCopyMap;
// 'ctors
CTSE_Info_Object(void);
CTSE_Info_Object(const CTSE_Info_Object& src, TObjectCopyMap* copy_map);
virtual ~CTSE_Info_Object(void);
// Get unique bio object id
virtual const CBioObjectId& GetBioObjectId(void) const;
virtual void SetBioObjectId(const CBioObjectId& id);
// info tree
bool HasDataSource(void) const;
CDataSource& GetDataSource(void) const;
bool HasTSE_Info(void) const;
bool BelongsToTSE_Info(const CTSE_Info& tse) const;
const CTSE_Info& GetTSE_Info(void) const;
CTSE_Info& GetTSE_Info(void);
bool HasParent_Info(void) const;
const CTSE_Info_Object& GetBaseParent_Info(void) const;
CTSE_Info_Object& GetBaseParent_Info(void);
// info tree initialization
void x_DSAttach(CDataSource& ds);
void x_DSDetach(CDataSource& ds);
virtual void x_DSAttachContents(CDataSource& ds);
virtual void x_DSDetachContents(CDataSource& ds);
void x_TSEAttach(CTSE_Info& tse);
void x_TSEDetach(CTSE_Info& tse);
virtual void x_TSEAttachContents(CTSE_Info& tse);
virtual void x_TSEDetachContents(CTSE_Info& tse);
// index support
bool x_DirtyAnnotIndex(void) const;
void x_SetDirtyAnnotIndex(void);
void x_SetParentDirtyAnnotIndex(void);
void x_ResetDirtyAnnotIndex(void);
virtual void x_SetDirtyAnnotIndexNoParent(void);
virtual void x_ResetDirtyAnnotIndexNoParent(void);
void x_UpdateAnnotIndex(CTSE_Info& tse);
virtual void x_UpdateAnnotIndexContents(CTSE_Info& tse);
enum ENeedUpdateAux {
/// number of bits for fields
kNeedUpdate_bits = 8
};
enum ENeedUpdate {
/// all fields of this object
fNeedUpdate_this = (1<<kNeedUpdate_bits)-1,
/// all fields of children objects
fNeedUpdate_children = fNeedUpdate_this<<kNeedUpdate_bits,
/// specific fields of this object
fNeedUpdate_descr = 1<<0, //< descr of this object
fNeedUpdate_annot = 1<<1, //< annot of this object
fNeedUpdate_seq_data = 1<<2, //< seq-data of this object
fNeedUpdate_core = 1<<3, //< core
fNeedUpdate_assembly = 1<<4, //< assembly of this object
fNeedUpdate_bioseq = 1<<5, //< whole bioseq
/// specific fields of children
fNeedUpdate_children_descr = fNeedUpdate_descr <<kNeedUpdate_bits,
fNeedUpdate_children_annot = fNeedUpdate_annot <<kNeedUpdate_bits,
fNeedUpdate_children_seq_data = fNeedUpdate_seq_data<<kNeedUpdate_bits,
fNeedUpdate_children_core = fNeedUpdate_core <<kNeedUpdate_bits,
fNeedUpdate_children_assembly = fNeedUpdate_assembly<<kNeedUpdate_bits,
fNeedUpdate_children_bioseq = fNeedUpdate_bioseq <<kNeedUpdate_bits
};
typedef int TNeedUpdateFlags;
bool x_NeedUpdate(ENeedUpdate flag) const;
void x_SetNeedUpdate(TNeedUpdateFlags flags);
virtual void x_SetNeedUpdateParent(TNeedUpdateFlags flags);
void x_Update(TNeedUpdateFlags flags) const;
virtual void x_DoUpdate(TNeedUpdateFlags flags);
void x_UpdateComplete(void) const;
void x_UpdateCore(void) const;
typedef int TChunkId;
typedef vector<TChunkId> TChunkIds;
void x_LoadChunk(TChunkId chunk_id) const;
void x_LoadChunks(const TChunkIds& chunk_ids) const;
virtual string GetDescription(void) const;
protected:
void x_BaseParentAttach(CTSE_Info_Object& parent);
void x_BaseParentDetach(CTSE_Info_Object& parent);
void x_AttachObject(CTSE_Info_Object& object);
void x_DetachObject(CTSE_Info_Object& object);
private:
CTSE_Info_Object(const CTSE_Info_Object&);
CTSE_Info_Object& operator=(const CTSE_Info_Object&);
// Owner TSE info
CTSE_Info* m_TSE_Info;
CTSE_Info_Object* m_Parent_Info;
bool m_DirtyAnnotIndex;
TNeedUpdateFlags m_NeedUpdateFlags;
CBioObjectId m_UniqueId;
};
/////////////////////////////////////////////////////////////////////
//
// Inline methods
//
/////////////////////////////////////////////////////////////////////
inline
bool CTSE_Info_Object::HasTSE_Info(void) const
{
return m_TSE_Info != 0;
}
inline
bool CTSE_Info_Object::BelongsToTSE_Info(const CTSE_Info& tse) const
{
return m_TSE_Info == &tse;
}
inline
bool CTSE_Info_Object::HasParent_Info(void) const
{
return m_Parent_Info != 0;
}
inline
bool CTSE_Info_Object::x_DirtyAnnotIndex(void) const
{
return m_DirtyAnnotIndex;
}
inline
bool CTSE_Info_Object::x_NeedUpdate(ENeedUpdate flag) const
{
return (m_NeedUpdateFlags & flag) != 0;
}
END_SCOPE(objects)
END_NCBI_SCOPE
#endif//OBJECTS_OBJMGR_IMPL___TSE_INFO_OBJECT__HPP
| 31.261261 | 79 | 0.679251 | [
"object",
"vector"
] |
169281ea568e23def085de64b305b363b7166388 | 1,618 | cpp | C++ | Common/math/transform.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | 2 | 2017-11-24T12:34:14.000Z | 2021-09-10T02:18:34.000Z | Common/math/transform.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | null | null | null | Common/math/transform.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | 6 | 2017-11-24T12:34:56.000Z | 2022-03-22T10:05:45.000Z |
#include "stdafx.h"
#include "transform.h"
using namespace common;
const Transform Transform::Identity;
Transform::Transform()
: pos(0,0,0)
, scale(1,1,1)
{
}
Transform::Transform(const Vector3 &pos_)
: pos(pos_)
, scale(1, 1, 1)
{
}
Transform::Transform(const Quaternion &rot_)
: rot(rot_)
, scale(1, 1, 1)
{
}
Transform::Transform(const Vector3 &pos_, const Vector3 &scale_)
: pos(pos_)
, scale(scale_)
{
}
Transform::Transform(const Vector3 &pos_, const Quaternion &rot_)
: pos(pos_)
, scale(Vector3(1,1,1))
, rot(rot_)
{
}
Transform::Transform(const Vector3 &pos_, const Vector3 &scale_, const Quaternion &rot_)
: pos(pos_)
, scale(scale_)
, rot(rot_)
{
}
// Scale * Rotation * Translation
Matrix44 Transform::GetMatrix() const
{
Matrix44 S;
S.SetScale(scale);
Matrix44 tm;
tm = S * rot.GetMatrix();
tm._41 = pos.x;
tm._42 = pos.y;
tm._43 = pos.z;
return tm;
}
Transform Transform::Inverse() const
{
Transform v;
v.pos = -pos;
v.scale = Vector3(1/scale.x, 1/scale.y, 1/scale.z);
v.rot = rot.Inverse();
return v;
}
// Scale * Rotation * Translation
Transform Transform::operator*(const Transform &rhs) const
{
const Matrix44 tm1 = rhs.rot.GetMatrix();
Transform v;
v.pos = ((pos * rhs.scale) * tm1) + rhs.pos;
v.scale = scale * rhs.scale;
v.rot = rot * rhs.rot;
return v;
//Transform v;
//v.pos = pos + rhs.pos;
//v.scale = Vector3(scale.x * rhs.scale.x
// , scale.y * rhs.scale.y
// , scale.z * rhs.scale.z);
//v.rot = rot * rhs.rot;
//return v;
}
const Transform& Transform::operator*=(const Transform &rhs)
{
*this = operator*(rhs);
return *this;
}
| 15.862745 | 88 | 0.650803 | [
"transform"
] |
169602acef6363a7ca2fda2c8c6f6aa3a83ab1fa | 12,894 | cpp | C++ | image_processor/lane_engine.cpp | kumaxxp/self-driving-ish_computer_vision_system | 833c3e903def019c2bb36fb36b631f4ae1da1e2f | [
"Apache-2.0"
] | 187 | 2021-09-11T22:30:17.000Z | 2022-03-30T20:41:39.000Z | image_processor/lane_engine.cpp | iwatake2222/detection_topview | 601775b734d7b8877680ca2f5d961c7c4ea20aaf | [
"Apache-2.0"
] | 12 | 2021-09-12T13:04:42.000Z | 2022-01-08T14:30:11.000Z | image_processor/lane_engine.cpp | iwatake2222/detection_topview | 601775b734d7b8877680ca2f5d961c7c4ea20aaf | [
"Apache-2.0"
] | 40 | 2021-09-12T03:08:41.000Z | 2022-03-23T09:42:22.000Z | /* Copyright 2021 iwatake2222
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 ***/
/* for general */
#include <cstdint>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <array>
#include <algorithm>
#include <chrono>
#include <fstream>
#include <numeric>
/* for OpenCV */
#include <opencv2/opencv.hpp>
/* for My modules */
#include "common_helper.h"
#include "common_helper_cv.h"
#include "inference_helper.h"
#include "lane_engine.h"
/*** Macro ***/
#define TAG "LaneEngine"
#define PRINT(...) COMMON_HELPER_PRINT(TAG, __VA_ARGS__)
#define PRINT_E(...) COMMON_HELPER_PRINT_E(TAG, __VA_ARGS__)
/* Model parameters */
#if defined(ENABLE_TENSORRT)
#define MODEL_TYPE_ONNX
#else
#define MODEL_TYPE_TFLITE
#endif
#ifdef MODEL_TYPE_TFLITE
#define MODEL_NAME "ultra_fast_lane_detection_culane_288x800.tflite"
#define TENSORTYPE TensorInfo::kTensorTypeFp32
#define INPUT_NAME "input_1"
#define INPUT_DIMS { 1, 288, 800, 3}
#define IS_NCHW false
#define IS_RGB true
#define OUTPUT_NAME "Identity"
#elif defined(MODEL_TYPE_ONNX)
#include "inference_helper_tensorrt.h" // to call SetDlaCore
#define MODEL_NAME "ultra_fast_lane_detection_culane_288x800.onnx"
#define TENSORTYPE TensorInfo::kTensorTypeFp32
#define INPUT_NAME "input.1"
#define INPUT_DIMS { 1, 3, 288, 800}
#define IS_NCHW true
#define IS_RGB true
#define OUTPUT_NAME "200"
#endif
#if 0
static constexpr int32_t culane_row_anchor[] = { 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 172, 176, 180, 184, 188, 192, 196, 200, 204, 208, 212, 216, 220, 224, 228, 232, 236, 240, 244, 248, 252, 256, 260, 264, 268, 272, 276, 280, 284 };
static constexpr int32_t kNumGriding = 101;
static constexpr int32_t kNumClassPerLine = 56;
static constexpr int32_t kNumLine = 4;
#else
static constexpr int32_t culane_row_anchor[] = { 121, 131, 141, 150, 160, 170, 180, 189, 199, 209, 219, 228, 238, 248, 258, 267, 277, 287 };
static constexpr int32_t kNumGriding = 201;
static constexpr int32_t kNumClassPerLine = 18;
static constexpr int32_t kNumLine = 4;
#endif
static constexpr int32_t kNumWidth = 800;
static constexpr int32_t kNumHeight = 288;
static constexpr float kDeltaWidth = ((kNumWidth - 1) - 0) / static_cast<float>((kNumGriding - 1) - 1);
/*** Function ***/
int32_t LaneEngine::Initialize(const std::string& work_dir, const int32_t num_threads)
{
/* Set model information */
std::string model_filename = work_dir + "/model/" + MODEL_NAME;
/* Set input tensor info */
input_tensor_info_list_.clear();
InputTensorInfo input_tensor_info(INPUT_NAME, TENSORTYPE, IS_NCHW);
input_tensor_info.tensor_dims = INPUT_DIMS;
input_tensor_info.data_type = InputTensorInfo::kDataTypeImage;
/* 0 - 1.0 */
input_tensor_info.normalize.mean[0] = 0;
input_tensor_info.normalize.mean[1] = 0;
input_tensor_info.normalize.mean[2] = 0;
input_tensor_info.normalize.norm[0] = 1.0f;
input_tensor_info.normalize.norm[1] = 1.0f;
input_tensor_info.normalize.norm[2] = 1.0f;
//input_tensor_info.normalize.mean[0] = 0.485f;
//input_tensor_info.normalize.mean[1] = 0.456f;
//input_tensor_info.normalize.mean[2] = 0.406f;
//input_tensor_info.normalize.norm[0] = 0.229f;
//input_tensor_info.normalize.norm[1] = 0.224f;
//input_tensor_info.normalize.norm[2] = 0.225f;
input_tensor_info_list_.push_back(input_tensor_info);
/* Set output tensor info */
output_tensor_info_list_.clear();
output_tensor_info_list_.push_back(OutputTensorInfo(OUTPUT_NAME, TENSORTYPE));
/* Create and Initialize Inference Helper */
#if defined(MODEL_TYPE_TFLITE)
//inference_helper_.reset(InferenceHelper::Create(InferenceHelper::kTensorflowLite));
inference_helper_.reset(InferenceHelper::Create(InferenceHelper::kTensorflowLiteXnnpack));
//inference_helper_.reset(InferenceHelper::Create(InferenceHelper::kTensorflowLiteGpu));
//inference_helper_.reset(InferenceHelper::Create(InferenceHelper::kTensorflowLiteEdgetpu));
//inference_helper_.reset(InferenceHelper::Create(InferenceHelper::kTensorflowLiteNnapi));
#elif defined(MODEL_TYPE_ONNX)
inference_helper_.reset(InferenceHelper::Create(InferenceHelper::kTensorrt));
// InferenceHelperTensorRt* p = dynamic_cast<InferenceHelperTensorRt*>(inference_helper_.get());
// if (p) p->SetDlaCore(0); /* Use DLA */
#endif
if (!inference_helper_) {
return kRetErr;
}
if (inference_helper_->SetNumThreads(num_threads) != InferenceHelper::kRetOk) {
inference_helper_.reset();
return kRetErr;
}
if (inference_helper_->Initialize(model_filename, input_tensor_info_list_, output_tensor_info_list_) != InferenceHelper::kRetOk) {
inference_helper_.reset();
return kRetErr;
}
return kRetOk;
}
int32_t LaneEngine::Finalize()
{
if (!inference_helper_) {
PRINT_E("Inference helper is not created\n");
return kRetErr;
}
inference_helper_->Finalize();
return kRetOk;
}
/* out_j = out_j[:, ::-1, :] */
static inline void Flip_1(std::vector<float>& val_list, int32_t num_i, int32_t num_j, int32_t num_k)
{
for (int32_t i = 0; i < num_i; i++) {
for (int32_t j = 0; j < num_j / 2; j++) {
for (int32_t k = 0; k < num_k; k++) {
int32_t new_j = num_j - 1 - j;
std::swap(val_list.at(i * (num_j * num_k) + j * num_k + k), val_list.at(i * (num_j * num_k) + new_j * num_k + k));
}
}
}
}
/* prob = scipy.special.softmax(out_j[:-1, :, :], axis=0) */
static std::vector<float> Softmax_0(const std::vector<float>& val_list, int32_t num_i, int32_t num_j, int32_t num_k)
{
std::vector<float> res(val_list.size());
for (int32_t j = 0; j < num_j; j++) {
for (int32_t k = 0; k < num_k; k++) {
float sum = 0;
for (int32_t i = 0; i < num_i; i++) {
sum += std::exp(val_list.at(i * (num_j * num_k) + j * num_k + k));
}
for (int32_t i = 0; i < num_i; i++) {
float v = std::exp(val_list.at(i * (num_j * num_k) + j * num_k + k)) / sum;
res.at(i * (num_j * num_k) + j * num_k + k) = v;
}
}
}
return res;
}
/* loc = np.sum(prob * idx, axis=0) */
static std::vector<float> MulSum(const std::vector<float>& val_list_0, const std::vector<float>& val_list_1, int32_t num_i, int32_t num_j, int32_t num_k)
{
std::vector<float> res(num_j * num_k);
for (int32_t j = 0; j < num_j; j++) {
for (int32_t k = 0; k < num_k; k++) {
float sum = 0;
for (int32_t i = 0; i < num_i; i++) {
sum += val_list_0.at(i * (num_j * num_k) + j * num_k + k) * val_list_1.at(i);
}
res.at(j * num_k + k) = sum;
}
}
return res;
}
/* out_j = np.argmax(out_j, axis = 0) */
/* loc[out_j == cfg.griding_num] = 0 */
static inline std::vector<bool> CheckIfValid(const std::vector<float>& val_list, int32_t num_i, int32_t num_j, int32_t num_k)
{
std::vector<bool> res(num_j * num_k, true);
for (int32_t j = 0; j < num_j; j++) {
for (int32_t k = 0; k < num_k; k++) {
float max_val = -999;
int32_t max_index = 0;
for (int32_t i = 0; i < num_i; i++) {
float val = val_list.at(i * (num_j * num_k) + j * num_k + k);
if (val > max_val) {
max_val = val;
max_index = i;
}
}
if (max_index == num_i - 1) {
res.at(j * num_k + k) = false;
}
}
}
return res;
}
int32_t LaneEngine::Process(const cv::Mat& original_mat, Result& result)
{
if (!inference_helper_) {
PRINT_E("Inference helper is not created\n");
return kRetErr;
}
/*** PreProcess ***/
const auto& t_pre_process0 = std::chrono::steady_clock::now();
InputTensorInfo& input_tensor_info = input_tensor_info_list_[0];
/* do resize and color conversion here because some inference engine doesn't support these operations */
int32_t crop_x = 0;
int32_t crop_y = 0;
int32_t crop_w = original_mat.cols;
int32_t crop_h = original_mat.rows;
//int32_t crop_x = 0;
//int32_t crop_w = original_mat.cols;
//int32_t crop_h = (crop_w * kNumHeight) / kNumWidth;
//int32_t crop_y = (original_mat.rows - crop_h) / 1;
cv::Mat img_src = cv::Mat::zeros(input_tensor_info.GetHeight(), input_tensor_info.GetWidth(), CV_8UC3);
CommonHelper::CropResizeCvt(original_mat, img_src, crop_x, crop_y, crop_w, crop_h, IS_RGB, CommonHelper::kCropTypeStretch);
//CommonHelper::CropResizeCvt(original_mat, img_src, crop_x, crop_y, crop_w, crop_h, IS_RGB, CommonHelper::kCropTypeCut);
//CommonHelper::CropResizeCvt(original_mat, img_src, crop_x, crop_y, crop_w, crop_h, IS_RGB, CommonHelper::kCropTypeExpand);
input_tensor_info.data = img_src.data;
input_tensor_info.data_type = InputTensorInfo::kDataTypeImage;
input_tensor_info.image_info.width = img_src.cols;
input_tensor_info.image_info.height = img_src.rows;
input_tensor_info.image_info.channel = img_src.channels();
input_tensor_info.image_info.crop_x = 0;
input_tensor_info.image_info.crop_y = 0;
input_tensor_info.image_info.crop_width = img_src.cols;
input_tensor_info.image_info.crop_height = img_src.rows;
input_tensor_info.image_info.is_bgr = false;
input_tensor_info.image_info.swap_color = false;
if (inference_helper_->PreProcess(input_tensor_info_list_) != InferenceHelper::kRetOk) {
return kRetErr;
}
const auto& t_pre_process1 = std::chrono::steady_clock::now();
/*** Inference ***/
const auto& t_inference0 = std::chrono::steady_clock::now();
if (inference_helper_->Process(output_tensor_info_list_) != InferenceHelper::kRetOk) {
return kRetErr;
}
const auto& t_inference1 = std::chrono::steady_clock::now();
/*** PostProcess ***/
const auto& t_post_process0 = std::chrono::steady_clock::now();
/* Retrieve the result */
std::vector<float> output_raw_val(output_tensor_info_list_[0].GetDataAsFloat(), output_tensor_info_list_[0].GetDataAsFloat() + kNumGriding * kNumClassPerLine * kNumLine);
if (output_tensor_info_list_[0].GetElementNum() != kNumGriding * kNumClassPerLine * kNumLine) {
PRINT_E("Invalid output\n");
return kRetErr;
}
/* reference: https://github.com/cfzd/Ultra-Fast-Lane-Detection/blob/master/demo.py#L69 */
std::vector<float> prob = Softmax_0(output_raw_val, kNumGriding - 1, kNumClassPerLine, kNumLine);
std::vector<float> idx(kNumGriding - 1);
std::iota(idx.begin(), idx.end(), 1.0f);
std::vector<float> loc = MulSum(prob, idx, kNumGriding - 1, kNumClassPerLine, kNumLine);
std::vector<bool> valid_map = CheckIfValid(output_raw_val, kNumGriding, kNumClassPerLine, kNumLine);
for (int32_t k = 0; k < kNumLine; k++) {
Line line;
for (int32_t j = 0; j < kNumClassPerLine; j++) {
int32_t index = j * kNumLine + k;
float val = loc.at(index);
if (valid_map.at(index) && val > 0) {
int32_t x = static_cast<int32_t>(val * kDeltaWidth * crop_w / kNumWidth + crop_x);
int32_t y = static_cast<int32_t>(culane_row_anchor[j] * crop_h / kNumHeight + crop_y);
line.push_back({ x, y });
}
}
result.line_list.push_back(line);
}
const auto& t_post_process1 = std::chrono::steady_clock::now();
/* Return the results */
result.crop.x = (std::max)(0, crop_x);
result.crop.y = (std::max)(0, crop_y);
result.crop.w = (std::min)(crop_w, original_mat.cols - result.crop.x);
result.crop.h = (std::min)(crop_h, original_mat.rows - result.crop.y);
result.time_pre_process = static_cast<std::chrono::duration<double>>(t_pre_process1 - t_pre_process0).count() * 1000.0;
result.time_inference = static_cast<std::chrono::duration<double>>(t_inference1 - t_inference0).count() * 1000.0;
result.time_post_process = static_cast<std::chrono::duration<double>>(t_post_process1 - t_post_process0).count() * 1000.0;;
return kRetOk;
}
| 40.420063 | 321 | 0.66147 | [
"vector",
"model"
] |
169bae4c4741c45d6fbf2c525af217a22da264f0 | 320 | cc | C++ | primer-answer/chapter3/3.16.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | 1 | 2018-02-23T11:12:17.000Z | 2018-02-23T11:12:17.000Z | primer-answer/chapter3/3.16.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | null | null | null | primer-answer/chapter3/3.16.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main (int argc, char *argv[]) {
vector<int> vec = {1, 2, 3, 4, 5};
vector<int>::size_type total = vec.size();
for (auto e : vec) {
cout << e << endl;
}
cout << "The amount of vector is: " << total << endl;
return 0;
}
| 16.842105 | 55 | 0.58125 | [
"vector"
] |
16ae56219f0f025c7b0fd0fa120c4c06ca648181 | 4,936 | hh | C++ | parser/ltac/ltac.hh | patrickf2000/upl | a58e3fd3f185e52d40332d4e7473ff7de8245f04 | [
"BSD-3-Clause"
] | null | null | null | parser/ltac/ltac.hh | patrickf2000/upl | a58e3fd3f185e52d40332d4e7473ff7de8245f04 | [
"BSD-3-Clause"
] | 6 | 2019-06-15T12:38:26.000Z | 2019-06-15T13:03:05.000Z | parser/ltac/ltac.hh | patrickf2000/upl | a58e3fd3f185e52d40332d4e7473ff7de8245f04 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include <ast.hh>
#include <types.hh>
// This relates to the overall node types
enum class LtacType {
None,
File,
Data,
Code
};
// This contains the actual instructions
enum class ltac {
None,
Func,
FuncCall,
Label,
Ret,
Var,
Array,
ArrayAcc,
Int,
Byte,
Float,
String,
MathOp,
Math,
Push,
Pop,
Cmp,
ICmp,
Jmp
};
// This relates to ltac data
enum class LtacData {
None,
String,
Float,
Int
};
//Various operators (for math functions)
enum class Operator {
None,
Add,
Sub,
Mul,
Div,
Mod,
PAdd,
PSub,
Equal,
NotEqual,
Greater,
Less,
GreaterEq,
LessEq
};
//The nodes for ltac
//This is the base class for all nodes
class LtacNode {
public:
explicit LtacNode() {}
explicit LtacNode(ltac t) { type = t; }
LtacType node_type;
ltac type = ltac::None; //Because most nodes are code/instruction nodes, we want this
std::vector<LtacNode *> children;
};
//The base class for the data section
class LtacDataSec : public LtacNode {
public:
explicit LtacDataSec() { node_type = LtacType::Data; }
};
//The base class for the for code section
class LtacCodeSec : public LtacNode {
public:
explicit LtacCodeSec() { node_type = LtacType::Code; }
};
//This is the base class for the file
class LtacFile : public LtacNode {
public:
explicit LtacFile() {
node_type = LtacType::File;
}
explicit LtacFile(std::string n) {
node_type = LtacType::File;
name = n;
}
std::string name = "";
LtacDataSec *data;
LtacCodeSec *code;
};
//Labels
class LtacLabel : public LtacNode {
public:
explicit LtacLabel() { type = ltac::Label; }
explicit LtacLabel(std::string n) {
type = ltac::Label;
name = n;
}
std::string name = "";
};
//Functions
class LtacFunc : public LtacLabel {
public:
explicit LtacFunc() { type = ltac::Func; }
explicit LtacFunc(std::string n) {
type = ltac::Func;
name = n;
}
int stack_size = 0;
bool is_global = false;
bool is_extern = false;
};
//Variable assignment/declaration/operation
class LtacVar : public LtacNode {
public:
explicit LtacVar() { type = ltac::Var; }
int pos = 0;
int size = 0;
DataType d_type;
int rvar = -1;
};
//Function calls
class LtacFuncCall : public LtacNode {
public:
explicit LtacFuncCall() { type = ltac::FuncCall; }
explicit LtacFuncCall(std::string n) {
type = ltac::FuncCall;
name = n;
}
std::string name = "";
std::vector<Var> args;
std::vector<LtacVar *> ret_dest;
};
//Integers
class LtacInt : public LtacNode {
public:
explicit LtacInt() { type = ltac::Int; }
explicit LtacInt(int i) {
type = ltac::Int;
val = i;
}
int val = 0;
};
//Characters
// The characters are encoded as ints, but they are
//accessed and stored a little differently, hence separate class
class LtacByte : public LtacInt {
public:
explicit LtacByte() { type = ltac::Byte; }
explicit LtacByte(int i) {
type = ltac::Byte;
val = i;
}
};
//Single-precision floats
class LtacFloat : public LtacNode {
public:
explicit LtacFloat() { type = ltac::Float; }
float val = 0;
int i_val = 0;
std::string name = "";
};
//Strings
class LtacString : public LtacNode {
public:
explicit LtacString() { type = ltac::String; }
explicit LtacString(std::string n, std::string v) {
type = ltac::String;
name = n;
val = v;
}
std::string name = "";
std::string val = "";
};
//Arrays
class LtacArray : public LtacNode {
public:
explicit LtacArray() { type = ltac::Array; }
int stack_pos = 0;
int size = 0;
int type_size = 1;
DataType d_type;
};
//Array access
class LtacArrayAcc : public LtacArray {
public:
explicit LtacArrayAcc() { type = ltac::ArrayAcc; }
};
//Math operations
class LtacMathOp : public LtacNode {
public:
explicit LtacMathOp() { type = ltac::MathOp; }
LtacNode *operand;
Operator op;
};
//Math
class LtacMath : public LtacNode {
public:
explicit LtacMath() { type = ltac::Math; }
LtacNode *init_val;
};
//Comparisons
class LtacCmp : public LtacNode {
public:
explicit LtacCmp() { type = ltac::Cmp; }
LtacNode *lval;
LtacNode *rval;
};
//Integer comparisons
class LtacICmp : public LtacCmp {
public:
explicit LtacICmp() { type = ltac::ICmp; }
};
//Jumps
//Set the operator to none for unconditional jump
class LtacJmp : public LtacNode {
public:
explicit LtacJmp() { type = ltac::Jmp; }
std::string dest;
Operator op = Operator::None;
};
//Useful functions
void print_ltac(LtacFile *file);
| 17.884058 | 96 | 0.604335 | [
"vector"
] |
16b0adb8a240cf3cd053064d5a4426c228c85aa4 | 1,718 | cpp | C++ | CSL/src/wmark/parser_actions/tk_operator_root_action.cpp | mickjagger19/CppTS | b974764858be4000472505a6277b1011f9c34274 | [
"BSD-2-Clause"
] | null | null | null | CSL/src/wmark/parser_actions/tk_operator_root_action.cpp | mickjagger19/CppTS | b974764858be4000472505a6277b1011f9c34274 | [
"BSD-2-Clause"
] | 1 | 2019-12-31T03:35:43.000Z | 2019-12-31T03:36:13.000Z | CSL/src/wmark/parser_actions/tk_operator_root_action.cpp | mickjagger19/CppTS | b974764858be4000472505a6277b1011f9c34274 | [
"BSD-2-Clause"
] | 8 | 2019-04-21T06:06:11.000Z | 2020-05-04T15:20:36.000Z | /*
** Xin YUAN, 2019, BSD (2)
*/
////////////////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "../base/WmarkDef.h"
#include "tk_operator_root_action.h"
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace CSL {
////////////////////////////////////////////////////////////////////////////////
// WmarkParserTkOperatorRootAction
WmarkParserTkOperatorRootAction::WmarkParserTkOperatorRootAction() noexcept
{
}
WmarkParserTkOperatorRootAction::~WmarkParserTkOperatorRootAction() noexcept
{
}
// IRdParserAction methods
void WmarkParserTkOperatorRootAction::SetParameter(const std::any& param)
{
m_pData = std::any_cast<RdParserActionMetaData*>(param);
}
bool WmarkParserTkOperatorRootAction::DoAction(const std::string& strToken, std::vector<std::string>& vecError)
{
//Root
assert( m_pData->posParent.uAddress != 0 );
up();
//subNode duplicate
RdMetaAstNodeInfo currentInfo;
m_pData->spMeta->GetAstNodeInfo(m_pData->posCurrent, currentInfo);
RdMetaAstNodeInfo childInfo;
m_pData->spMeta->GetAstNodeInfo(currentInfo.posChild, childInfo);
m_pData->spMeta->SetAstChild(m_pData->posCurrent, childInfo.posNext);
RdMetaDataPosition pos;
pos.uAddress = 0;
m_pData->spMeta->SetAstNext(currentInfo.posChild, pos);
m_pData->spMeta->SetAstNext(childInfo.posNext, currentInfo.posChild);
return true;
}
////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
| 28.163934 | 112 | 0.526775 | [
"vector"
] |
16b3d11237aca30fb06e283a12c4463dd85d3381 | 8,850 | cpp | C++ | src/plugins/aggregator/dbupdatethreadworker.cpp | devel29a/leechcraft | faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/aggregator/dbupdatethreadworker.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | src/plugins/aggregator/dbupdatethreadworker.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "dbupdatethreadworker.h"
#include <stdexcept>
#include <boost/optional.hpp>
#include <QUrl>
#include <QtDebug>
#include <util/xpc/util.h>
#include <util/xpc/defaulthookproxy.h>
#include <util/sll/lazy.h>
#include <interfaces/core/ientitymanager.h>
#include "xmlsettingsmanager.h"
#include "storagebackend.h"
namespace LeechCraft
{
namespace Aggregator
{
DBUpdateThreadWorker::DBUpdateThreadWorker (const ICoreProxy_ptr& proxy, QObject *parent)
: QObject (parent)
, Proxy_ { proxy }
{
try
{
const QString& strType = XmlSettingsManager::Instance ()->
property ("StorageType").toString ();
SB_ = StorageBackend::Create (strType, "_UpdateThread");
}
catch (const std::runtime_error& s)
{
qWarning () << Q_FUNC_INFO
<< s.what ();
return;
}
catch (...)
{
qWarning () << Q_FUNC_INFO
<< "unknown exception";
return;
}
SB_->Prepare ();
}
void DBUpdateThreadWorker::WithWorker (const std::function<void (DBUpdateThreadWorker*)>& func)
{
func (this);
}
Feed::FeedSettings DBUpdateThreadWorker::GetFeedSettings (IDType_t feedId)
{
const auto itemAge = XmlSettingsManager::Instance ()->property ("ItemsMaxAge").toInt ();
const auto items = XmlSettingsManager::Instance ()->property ("ItemsPerChannel").toUInt ();
try
{
auto settings = SB_->GetFeedSettings (feedId);
if (!settings.ItemAge_)
settings.ItemAge_ = itemAge;
if (!settings.NumItems_)
settings.NumItems_ = items;
return settings;
}
catch (const StorageBackend::FeedSettingsNotFoundError&)
{
}
catch (const std::exception& e)
{
qWarning () << Q_FUNC_INFO
<< "unable to get feed settings for"
<< feedId
<< e.what ();
}
Feed::FeedSettings s { feedId };
s.ItemAge_ = itemAge;
s.NumItems_ = items;
s.AutoDownloadEnclosures_ = false;
return s;
}
void DBUpdateThreadWorker::AddChannel (const Channel_ptr& channel, const Feed::FeedSettings& settings)
{
const auto ipc = static_cast<size_t> (settings.NumItems_);
const auto days = settings.ItemAge_;
size_t truncateAt = (channel->Items_.size () <= ipc) ?
channel->Items_.size () :
ipc;
for (size_t j = 0; j < channel->Items_.size (); j++)
if (channel->Items_ [j]->PubDate_.daysTo (QDateTime::currentDateTime ()) > days)
{
truncateAt = std::min (j, truncateAt);
break;
}
channel->Items_.resize (truncateAt);
SB_->AddChannel (channel);
emit gotNewChannel (channel->ToShort ());
QString str = tr ("Added channel \"%1\" (%n item(s))",
"", channel->Items_.size ())
.arg (channel->Title_);
Proxy_->GetEntityManager ()->HandleEntity (Util::MakeNotification ("Aggregator", str, PInfo_));
}
bool DBUpdateThreadWorker::AddItem (const Item_ptr& item, const Channel_ptr& channel,
const Feed::FeedSettings& settings)
{
if (item->PubDate_.isValid ())
{
if (item->PubDate_.daysTo (QDateTime::currentDateTime ()) >= settings.ItemAge_)
return false;
}
else
item->FixDate ();
item->ChannelID_ = channel->ChannelID_;
SB_->AddItem (item);
emit hookGotNewItems (std::make_shared<Util::DefaultHookProxy> (), { item });
const auto iem = Proxy_->GetEntityManager ();
if (settings.AutoDownloadEnclosures_)
for (const auto& e : item->Enclosures_)
{
auto de = Util::MakeEntity (QUrl (e.URL_),
XmlSettingsManager::Instance ()->
property ("EnclosuresDownloadPath").toString (),
0,
e.Type_);
de.Additional_ [" Tags"] = channel->Tags_;
iem->HandleEntity (de);
}
return true;
}
bool DBUpdateThreadWorker::UpdateItem (const Item_ptr& item, const Item_ptr& ourItem)
{
if (!IsModified (ourItem, item))
return false;
ourItem->Description_ = item->Description_;
ourItem->Categories_ = item->Categories_;
ourItem->NumComments_ = item->NumComments_;
ourItem->CommentsLink_ = item->CommentsLink_;
ourItem->CommentsPageLink_ = item->CommentsPageLink_;
ourItem->Latitude_ = item->Latitude_;
ourItem->Longitude_ = item->Longitude_;
for (auto& enc : item->Enclosures_)
{
if (!ourItem->Enclosures_.contains (enc))
{
enc.ItemID_ = ourItem->ItemID_;
ourItem->Enclosures_ << enc;
}
}
for (auto& entry : item->MRSSEntries_)
if (!ourItem->MRSSEntries_.contains (entry))
{
entry.ItemID_ = ourItem->ItemID_;
ourItem->MRSSEntries_ << entry;
}
SB_->UpdateItem (ourItem);
return true;
}
void DBUpdateThreadWorker::NotifyUpdates (int newItems, int updatedItems, const Channel_ptr& channel)
{
const auto& method = XmlSettingsManager::Instance ()->
property ("NotificationsFeedUpdateBehavior").toString ();
bool shouldShow = true;
if (method == "ShowNo")
shouldShow = false;
else if (method == "ShowNew")
shouldShow = newItems;
else if (method == "ShowAll")
shouldShow = newItems + updatedItems;
if (!shouldShow)
return;
QStringList substrs;
if (newItems)
substrs << tr ("%n new item(s)", "Channel update", newItems);
if (updatedItems)
substrs << tr ("%n updated item(s)", "Channel update", updatedItems);
const auto& str = tr ("Updated channel \"%1\" (%2).")
.arg (channel->Title_)
.arg (substrs.join (", "));
Proxy_->GetEntityManager ()->HandleEntity (Util::MakeNotification ("Aggregator", str, PInfo_));
}
void DBUpdateThreadWorker::toggleChannelUnread (IDType_t channel, bool state)
{
SB_->ToggleChannelUnread (channel, state);
}
void DBUpdateThreadWorker::updateFeed (channels_container_t channels, QString url)
{
auto feedId = SB_->FindFeed (url);
if (feedId == static_cast<decltype (feedId)> (-1))
{
qWarning () << Q_FUNC_INFO
<< "skipping"
<< url
<< "cause seems like it's not in storage yet";
return;
}
const auto& feedSettings = GetFeedSettings (feedId);
const auto ipc = feedSettings.NumItems_;
const auto days = feedSettings.ItemAge_;
for (const auto& channel : channels)
{
Channel_ptr ourChannel;
try
{
const auto ourChannelID = SB_->FindChannel (channel->Title_,
channel->Link_, feedId);
ourChannel = SB_->GetChannel (ourChannelID, feedId);
}
catch (const StorageBackend::ChannelNotFoundError&)
{
AddChannel (channel, feedSettings);
continue;
}
int newItems = 0;
int updatedItems = 0;
for (const auto& item : channel->Items_)
{
auto mkLazy = [] (auto&& f) { return Util::MakeLazyF<boost::optional<IDType_t>> (f); };
const auto& ourItemID = Util::Msum ({
mkLazy ([&] { return SB_->FindItem (item->Title_, item->Link_, ourChannel->ChannelID_); }),
mkLazy ([&] { return SB_->FindItemByLink (item->Link_, ourChannel->ChannelID_); }),
mkLazy ([&]
{
if (!item->Link_.isEmpty ())
return boost::optional<IDType_t> {};
return SB_->FindItemByTitle (item->Title_, ourChannel->ChannelID_);
})
}) ();
if (ourItemID)
{
const auto& ourItem = SB_->GetItem (*ourItemID);
if (UpdateItem (item, ourItem))
++updatedItems;
}
else if (AddItem (item, ourChannel, feedSettings))
++newItems;
}
SB_->TrimChannel (ourChannel->ChannelID_, days, ipc);
NotifyUpdates (newItems, updatedItems, channel);
}
}
}
}
| 29.898649 | 103 | 0.670056 | [
"object"
] |
16c9664ecb5dd38ba680a50d8962e518021afe63 | 7,299 | cpp | C++ | Lab02/glwidget.cpp | FrostByteGER/ComputerGraphics | 1b53a4ba1f8f7db7dab21cf087b1c3d352c385cd | [
"MIT"
] | null | null | null | Lab02/glwidget.cpp | FrostByteGER/ComputerGraphics | 1b53a4ba1f8f7db7dab21cf087b1c3d352c385cd | [
"MIT"
] | null | null | null | Lab02/glwidget.cpp | FrostByteGER/ComputerGraphics | 1b53a4ba1f8f7db7dab21cf087b1c3d352c385cd | [
"MIT"
] | null | null | null | #define _USE_MATH_DEFINES
#include "glwidget.h"
#include <cmath>
GLWidget::GLWidget( const QGLFormat& format, QWidget* parent ) : QGLWidget( format, parent ), vertexBuffer( QOpenGLBuffer::VertexBuffer )
{
}
void GLWidget::initializeGL()
{
QGLFormat glFormat = QGLWidget::format();
if ( !glFormat.sampleBuffers() )
qWarning() << "Could not enable sample buffers";
// Enable Z-Buffering
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Set the clear color to black
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
//By default, render the textures and colors.
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// Prepare a complete shader program…
if ( !prepareShaderProgram( vertexPath, fragmentPath ) )
return;
cameraPosition = QVector3D(0,0,5);
// Set up MVP camera
projection.perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
view.lookAt(cameraPosition,QVector3D(0,0,0),QVector3D(0,1,0)); // Move first vector to variable to control camera position
model = QMatrix4x4();
// Create our first VAO(A triangle in this case)
vao1.create();
vao1.bind();
//Generate the vertices for the sphere
generateSphere(vertices,16);
// VertexBuffer
vertexBuffer.create();
vertexBuffer.setUsagePattern( QOpenGLBuffer::StaticDraw );
if ( !vertexBuffer.bind() )
{
qWarning() << "Could not bind vertex buffer to the context";
return;
}
vertexBuffer.allocate( &vertices[0], vertices.size() * sizeof( GLfloat ) );
// Bind the shader program so that we can associate variables from our application to the shaders
if ( !shader.bind() )
{
qWarning() << "Could not bind shader program to context";
return;
}
// Enable the "vertexPosition_modelspace" attribute to bind it to our currently bound vertex buffer.
shader.setAttributeBuffer( "vertexPosition_modelspace", GL_FLOAT, 0, 3 );
shader.enableAttributeArray( "vertexPosition_modelspace" );
// We attached everything important to our VAO, now release it and repeat to other VAOs if neccessary
vao1.release();
}
void GLWidget::resizeGL( int w, int h )
{
// Set the viewport to window dimensions
glViewport( 0, 0, w, qMax( h, h ) );
}
void GLWidget::paintGL()
{
// Clear the buffer with the current clearing color
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if(updateRenderMode == true)
{
changeRenderMode();
}
// Transfer the now calculated MVP matrix to the vertex shader
shader.setUniformValue("MVP",projection * view * model);
if(rotateMesh == true){
model.rotate(10.0f,QVector3D(0,1,0));
rotateMesh = false;
}
// Draw stuff
// For every VAO, bind, draw and then release. Repeat to EVERY VAO!
vao1.bind();
glDrawArrays( GL_TRIANGLES, 0, vertices.size() );
vao1.release();
}
void GLWidget::changeRenderMode()
{
glGetIntegerv(GL_POLYGON_MODE, &renderMode);
if(renderMode == GL_LINE){
qWarning() << "FILL MODE";
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}else if(renderMode == GL_FILL){
qWarning() << "LINE MODE";
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}else{
qWarning() << "LINE MODE";
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
updateRenderMode = false;
}
void GLWidget::keyPressEvent( QKeyEvent* e )
{
switch ( e->key() )
{
case Qt::Key_Escape:
QApplication::instance()->quit();
break;
case Qt::Key_F1:
updateRenderMode = true;
repaint();
break;
case Qt::Key_F2:
rotateMesh = true;
repaint();
break;
default:
QGLWidget::keyPressEvent( e );
}
}
bool GLWidget::prepareShaderProgram( const QString& vertexShaderPath, const QString& fragmentShaderPath )
{
// First we load and compile the vertex shader…
bool result = shader.addShaderFromSourceFile( QGLShader::Vertex, vertexShaderPath );
if ( !result )
qWarning() << shader.log();
// …now the fragment shader…
result = shader.addShaderFromSourceFile( QGLShader::Fragment, fragmentShaderPath );
if ( !result )
qWarning() << shader.log();
// …and finally we link them to resolve any references.
result = shader.link();
if ( !result )
qWarning() << "Could not link shader program:" << shader.log();
return result;
}
void GLWidget::generateSphere(std::vector<GLfloat>& outVertices ,int size)
{
// Change to double parameter
double pointAmount = static_cast<double>(size);
double circle = M_PI*2.0;
std::vector<GLfloat> circleXpoint = {};
std::vector<GLfloat> circleYpoint = {};
std::vector<GLfloat> circleZpoint = {};
double circleAmount = circle/pointAmount;
double circleRadius = 0.0;
for (double z = 0.0; z < pointAmount+1; z++) {
circleRadius = sin((circleAmount*z)/2.0);
circleZpoint.push_back(cos((circleAmount*z)/2.0));
for (double y = 0.0; y < size*circleAmount; y+=circleAmount) {
circleXpoint.push_back(cos(y)*circleRadius);
circleYpoint.push_back(sin(y)*circleRadius);
}
}
int zint = 0;
//TODO check if -1 is correct
for(int i = 0 ; i < circleXpoint.size()-pointAmount-1 ; i++){
if(i > 0 && (i%size) == 0){
zint++;
}
if(i > 0 && (i%size) == size-1){
outVertices.push_back(circleZpoint[zint]);
outVertices.push_back(circleXpoint[i]);
outVertices.push_back(circleYpoint[i]);
outVertices.push_back(circleZpoint[zint+1]);
outVertices.push_back(circleXpoint[i+size]);
outVertices.push_back(circleYpoint[i+size]);
outVertices.push_back(circleZpoint[zint+1]);
outVertices.push_back(circleXpoint[i+1]);
outVertices.push_back(circleYpoint[i+1]);
outVertices.push_back(circleZpoint[zint+1]);
outVertices.push_back(circleXpoint[i+1]);
outVertices.push_back(circleYpoint[i+1]);
outVertices.push_back(circleZpoint[zint+1]);
outVertices.push_back(circleXpoint[i+size]);
outVertices.push_back(circleYpoint[i+size]);
outVertices.push_back(circleZpoint[zint+2]);
outVertices.push_back(circleXpoint[i+size+1]);
outVertices.push_back(circleYpoint[i+size+1]);
}else{
outVertices.push_back(circleZpoint[zint]);
outVertices.push_back(circleXpoint[i]);
outVertices.push_back(circleYpoint[i]);
outVertices.push_back(circleZpoint[zint+1]);
outVertices.push_back(circleXpoint[i+size]);
outVertices.push_back(circleYpoint[i+size]);
outVertices.push_back(circleZpoint[zint]);
outVertices.push_back(circleXpoint[i+1]);
outVertices.push_back(circleYpoint[i+1]);
outVertices.push_back(circleZpoint[zint]);
outVertices.push_back(circleXpoint[i+1]);
outVertices.push_back(circleYpoint[i+1]);
outVertices.push_back(circleZpoint[zint+1]);
outVertices.push_back(circleXpoint[i+size]);
outVertices.push_back(circleYpoint[i+size]);
outVertices.push_back(circleZpoint[zint+1]);
outVertices.push_back(circleXpoint[i+size+1]);
outVertices.push_back(circleYpoint[i+size+1]);
}
}
// Debug Print
qWarning() << "SUCCESSFULL";
}
| 30.161157 | 137 | 0.656939 | [
"render",
"vector",
"model"
] |
16ca65659155c985ad5cba681b08d94e188ee2e0 | 4,387 | cpp | C++ | Simple MonteCarlo/Simple MonteCarlo/Surface.cpp | magnusstrandberg/Simple_MonteCarlo | 20d8aad5a9c34fd840d6b111f19bed76d9455752 | [
"MIT"
] | null | null | null | Simple MonteCarlo/Simple MonteCarlo/Surface.cpp | magnusstrandberg/Simple_MonteCarlo | 20d8aad5a9c34fd840d6b111f19bed76d9455752 | [
"MIT"
] | null | null | null | Simple MonteCarlo/Simple MonteCarlo/Surface.cpp | magnusstrandberg/Simple_MonteCarlo | 20d8aad5a9c34fd840d6b111f19bed76d9455752 | [
"MIT"
] | null | null | null | #include "Surface.h"
#include "Input.h"
#include <cmath>
#include <math.h>
#include <vector>
Surface::Surface()
{
}
Surface::~Surface()
{
}
void Surface::CreateSurface(std::vector <double> data, int identifier, int placeholder)
{
ID = identifier;
int tmp = 6;
for (int i = 0; i < 10; i++)
{
surf_param[i] = data[i];
if (surf_param[i] == 0 && i < 6)
{
tmp--;
}
}
if (tmp == 0)
{
type = 1;
}
else
{
type = 2;
}
return;
}
int Surface::insideSurf(double * position, bool complement)
{
//Square parameters
double S = surf_param[0]*pow(position[0],2)
+ (surf_param[1]*pow(position[1],2))
+ (surf_param[2] * pow(position[2],2))
//Cross parameters
+ (surf_param[3] * position[0] * position[1])
+ (surf_param[4] * position[1] * position[2])
+ (surf_param[5] * position[2] * position[0])
//Linear parameters
+ (surf_param[6] * position[0])
+ (surf_param[7] * position[1])
+ (surf_param[8] * position[2])
//Constant
+ surf_param[9];
int inside;
if (S < 0)
{
inside = -1;
}
else if(S > 10e-14)
{
inside = 1;
}
else
{
return 0;
}
if (complement) {
return -1 * inside;
}
else
{
return inside;
}
}
/*
A=0 B=1
C=2 D=3
E=4 F=5
G=6 H=7
I=8 J=9
*/
int Surface::distToSurf(double * position, double * direction, double * distance)
{
if (type == 1)
{
double dominator = (surf_param[6] * position[0])
+ (surf_param[7] * position[1])
+ (surf_param[8] * position[2])
+ surf_param[9];
double nominator = +(surf_param[6] * direction[0])
+ (surf_param[7] * direction[1])
+ (surf_param[8] * direction[2]);
if (nominator != 0)
{
distance[0] = -1*(dominator / nominator);
return 1;
}
return 4;
}
else
{
double K, L, M;
K = (surf_param[0] * pow(position[0], 2))
+ (surf_param[1] * pow(position[1], 2))
+ (surf_param[2] * pow(position[2], 2))
+ (surf_param[3] * position[0] * position[1])
+ (surf_param[4] * position[1] * position[2])
+ (surf_param[5] * position[2] * position[0])
+ (surf_param[6] * position[0])
+ (surf_param[7] * position[1])
+ (surf_param[8] * position[2])
+ surf_param[9];
L = (2 * ((surf_param[0] * position[0] * direction[0])
+ (surf_param[1] * position[1] * direction[1])
+ (surf_param[2] * position[2] * direction[2]))
+ (surf_param[3] * ((position[0] * direction[1]) + (position[1] * direction[0])))
+ (surf_param[4] * ((position[1] * direction[2]) + (position[2] * direction[1])))
+ (surf_param[5] * ((position[0] * direction[2]) + (position[2] * direction[0])))
+ (surf_param[6] * position[0])
+ (surf_param[7] * position[1])
+ (surf_param[8] * position[2]));
M = (surf_param[0] * pow(direction[0], 2))
+ (surf_param[1] * pow(direction[1], 2))
+ (surf_param[2] * pow(direction[2], 2))
+ (surf_param[3] * direction[0] * direction[1])
+ (surf_param[4] * direction[1] * direction[2])
+ (surf_param[5] * direction[2] * direction[0]);
//sqrt(L^2-4MK)
if (M == 0)
{
return 3;
}
double square_value = (pow(L, 2) - (4 * M*K));
if (square_value > 0)
{
double tmp[] = { (((-1*L) - sqrt(square_value)) / (2 * M)), (((-1*L) + sqrt(square_value)) / (2 * M)) };
if (0 < tmp[0]) {
distance[0] = tmp[0];
distance[1] = tmp[1];
}
else {
distance[0] = tmp[1];
distance[1] = tmp[0];
}
return 1;
}
else if (square_value < 10e-14 && square_value > 0)
{
distance[0] = (-M) / (2 * M);
return 1;
}
else
{
return 0;
}
}
}
void Surface::surfaceNorm(double * position,double * norm, bool side)
{
double nabS_x;
double nabS_y;
double nabS_z;
double abs_xyz;
nabS_x = ((2 * surf_param[0] * position[0])
+ (surf_param[3] * position[1])
+ (surf_param[5] * position[2])
+ (surf_param[6]));
nabS_y = ((2 * surf_param[1] * position[1])
+ (surf_param[3] * position[0])
+ (surf_param[4] * position[2])
+ (surf_param[7]));
nabS_z = ((2 * surf_param[2] * position[2])
+ (surf_param[4] * position[1])
+ (surf_param[5] * position[0])
+ (surf_param[8]));
abs_xyz = sqrt(pow(nabS_x, 2) + pow(nabS_y, 2) + pow(nabS_z, 2));
//normal on the other side.
if (!side)
{
nabS_x = -1 * nabS_x;
nabS_y = -1 * nabS_y;
nabS_z = -1 * nabS_z;
}
norm[0] = nabS_x / abs_xyz;
norm[1] = nabS_y / abs_xyz;
norm[2] = nabS_z / abs_xyz;
return;
}
int Surface::showID()
{
return ID;
}
| 20.5 | 107 | 0.565079 | [
"vector"
] |
16cfb6ec052f7431efbdc29bfaccef7ddbc65aea | 1,018 | cpp | C++ | CodeForces/Complete/1200-1299/1207C-GasPipeline.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/1200-1299/1207C-GasPipeline.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/1200-1299/1207C-GasPipeline.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <iostream>
#include <vector>
typedef long long ll;
int main(){
std::ios::sync_with_stdio(false);
ll t; std::cin >> t;
while(t--){
ll n, a, b; std::cin >> n >> a >> b;
std::string s; std::cin >> s;
std::vector<ll> v(n, 1e16);
ll nxt(1e16);
for(ll p = v.size() - 1; p >= 0; p--){v[p] = nxt; nxt = (s[p] == '1') ? p : nxt;}
ll cost(n * a + (n + 1) * b);
bool state(0);
for(ll p = 1; p < s.size(); p++){
if(s[p] == s[p - 1]){cost += state * b;}
else if(s[p] == '1'){
cost += (1 - state) * a + b;
state = 1;
}
else if(s[p] == '0'){
state = ((v[p] - p - 1) * b < 2 * a);
cost += (1 - state) * a + state * b;
}
std::cout << p << " \t " << s[p] << " \t " << (state ? 1 : 0) << "\t-> " << cost << std::endl;
}
std::cout << cost << std::endl;
}
return 0;
}
| 27.513514 | 114 | 0.347741 | [
"vector"
] |
16d40c1300127e128fc5d0b1bc87f0d895b745c2 | 3,264 | cpp | C++ | src/duke/streams/FilesStreams.cpp | hradec/duke | efacf7139cd1d7c2cd2f5127079721bd263dda50 | [
"MIT"
] | 51 | 2015-01-07T18:36:39.000Z | 2021-11-30T15:24:44.000Z | src/duke/streams/FilesStreams.cpp | virneo/duke | efacf7139cd1d7c2cd2f5127079721bd263dda50 | [
"MIT"
] | 1 | 2015-01-08T10:48:43.000Z | 2015-02-11T19:32:14.000Z | src/duke/streams/FilesStreams.cpp | virneo/duke | efacf7139cd1d7c2cd2f5127079721bd263dda50 | [
"MIT"
] | 18 | 2015-05-11T12:43:37.000Z | 2019-11-29T11:15:41.000Z | #include "duke/streams/SingleFileStream.hpp"
#include "duke/streams/FileSequenceStream.hpp"
#include "duke/attributes/AttributeKeys.hpp"
#include "duke/attributes/Attributes.hpp"
#include "duke/base/StringAppender.hpp"
#include "duke/filesystem/FsUtils.hpp"
#include "duke/io/ImageLoadUtils.hpp"
#include "duke/memory/Allocator.hpp"
#include <sequence/Item.hpp>
#include <set>
namespace duke {
namespace {
std::vector<IIODescriptor*> findIODescriptors(const sequence::Item& item) {
const auto& filename = item.filename;
const char* pExtension = fileExtension(filename.c_str());
const auto& descriptors = IODescriptors::instance().findDescriptor(pExtension);
return {begin(descriptors), end(descriptors)};
}
bool isFileSequenceReader(const IIODescriptor* pDescriptor) {
return pDescriptor->supports(IIODescriptor::Capability::READER_SINGLE_FRAME);
}
} // namespace
FileSequenceStream::FileSequenceStream(const sequence::Item& item)
: m_FrameStart(item.start), m_Padding(item.padding), m_Descriptors(findIODescriptors(item)) {
CHECK(item.getType() == sequence::Item::PACKED);
CHECK(std::all_of(begin(m_Descriptors), end(m_Descriptors), &isFileSequenceReader));
const auto& filename = item.filename;
const auto begin = filename.begin();
auto firstSharpIndex = filename.find('#');
m_Prefix = std::string(begin, begin + firstSharpIndex);
auto lastSharpIndex = filename.rfind('#');
m_Suffix = std::string(begin + lastSharpIndex + 1, filename.end());
using namespace attribute;
set<MediaFrameCount>(m_State, item.end - item.start + 1);
m_OpenResult = process(0);
}
const ReadFrameResult& FileSequenceStream::openContainer() const { return m_OpenResult; }
// Several threads will access this function at the same time.
ReadFrameResult FileSequenceStream::process(const size_t atFrame) const {
BufferStringAppender<2048> buffer;
const size_t frame = atFrame + m_FrameStart;
const size_t paddingSize = m_Padding > 0 ? m_Padding : digits(frame);
buffer.append(m_Prefix);
appendPaddedFrameNumber(frame, paddingSize, buffer);
buffer.append(m_Suffix);
CHECK(!buffer.full()) << "filename too long";
return duke::load(buffer.c_str());
}
SingleFileStream::SingleFileStream(const sequence::Item& item) : m_OpenResult(load(item.filename.c_str())) {
using namespace attribute;
if (!m_OpenResult) {
set<Error>(m_State, m_OpenResult.error.c_str());
return;
}
CHECK(m_OpenResult.reader);
set<File>(m_State, item.filename.c_str());
set<MediaFrameCount>(m_State, m_OpenResult.reader->getContainerDescription().frames);
}
const ReadFrameResult& SingleFileStream::openContainer() const { return m_OpenResult; }
ReadFrameResult SingleFileStream::process(const size_t frame) const {
if (frame == 0) return m_OpenResult;
CHECK(m_OpenResult.reader);
using namespace attribute;
std::lock_guard<std::mutex> guard(m_Mutex);
ReadFrameResult result;
result.reader = m_OpenResult.reader;
duke::loadImage(result, [frame](const StreamDescription&) {
ReadOptions options;
options.frame = frame;
return options;
});
return result;
}
bool SingleFileStream::isForwardOnly() const {
using namespace attribute;
return getWithDefault<MediaFrameCount>(m_State) > 1;
}
} // namespace duke
| 34.723404 | 108 | 0.75337 | [
"vector"
] |
16dc137bec609b0932d6093b15eee613c663e1cf | 8,451 | cc | C++ | scripts/ppi-benchmark/Parsing/Charniak-Lease-2006Aug-reranking-parser/reranking-parser/second-stage/programs/eval-weights/compare-models.cc | AmmarQaseem/CPI-Pipeline-test | 3866883c54d7bd77753ee4b72997949bdcf76359 | [
"PostgreSQL",
"ISC",
"Intel"
] | null | null | null | scripts/ppi-benchmark/Parsing/Charniak-Lease-2006Aug-reranking-parser/reranking-parser/second-stage/programs/eval-weights/compare-models.cc | AmmarQaseem/CPI-Pipeline-test | 3866883c54d7bd77753ee4b72997949bdcf76359 | [
"PostgreSQL",
"ISC",
"Intel"
] | null | null | null | scripts/ppi-benchmark/Parsing/Charniak-Lease-2006Aug-reranking-parser/reranking-parser/second-stage/programs/eval-weights/compare-models.cc | AmmarQaseem/CPI-Pipeline-test | 3866883c54d7bd77753ee4b72997949bdcf76359 | [
"PostgreSQL",
"ISC",
"Intel"
] | null | null | null | // compare-models.cc
//
// Mark Johnson, 10th May 2005
const char usage[] =
"Usage: compare-models weights1 features1 [weights2 [features2]]\n"
"\n"
" compares the performance of the model weights1 with\n"
" the model weights2. features1 should be the feature vectors\n"
" corresponding to weights1. If weights2 is not given, the second\n"
" model is taken to be one that puts all its weight on the first\n"
" feature. If features2 is not given, then features2 is assumed\n"
" to be the same as features1.\n";
#include "custom_allocator.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <utility>
#include <vector>
#include "cephes.h"
#include "lmdata.h"
#include "popen.h"
#include "utility.h"
typedef std::vector<Float> Floats;
typedef std::pair<Float,Float> FF;
//! pr_type{} calculates standard parseval precision and recall scores.
//
struct pr_type {
size_type ncommon; // number of edges in common
size_type ngold; // number of edges in gold trees
size_type ntest; // number of edges in test trees
pr_type(size_type ncommon = 0, size_type ngold = 0, size_type ntest = 0)
: ncommon(ncommon), ngold(ngold), ntest(ntest) { }
void clear() { ncommon = ngold = ntest = 0; }
Float precision() const {
return (ntest == 0) ? 0 : Float(ncommon)/ntest;
}
Float recall() const {
return (ngold == 0) ? 1 : Float(ncommon)/ngold;
}
Float f_score() const {
return (ntest == 0 && ngold == 0) ? 0 : (2.0 * ncommon) / (ntest+ngold);
} // pr_type::f_score()
Float error_rate() const {
return (ngold + ntest - 2.0*ncommon) / ngold;
} // pr_type::error_rate()
pr_type& operator+= (const pr_type& pr) {
ncommon += pr.ncommon;
ngold += pr.ngold;
ntest += pr.ntest;
return *this;
} // pr_type::operator+=()
}; // pr_type{}
typedef std::vector<pr_type> prs_type;
void read_weights_file(const char* filename, Floats& ws) {
izstream is(filename);
if (!is) {
std::cerr << "## Error in compare-models: unable to read weights file "
<< filename << "\n\n" << usage << std::endl;
exit(EXIT_FAILURE);
}
size_type f;
Float w;
while (is >> f >> " =" >> w) {
assert(f >= 0);
assert(f < ws.size());
ws[f] = w;
}
} // read_weights_file()
void corpus_prs(const corpus_type* corpus, const Floats& ws,
prs_type& prs, pr_type& prsum) {
size_type nsentences = corpus->nsentences;
prs.resize(corpus->nsentences);
prsum.clear();
for (size_type i = 0; i < nsentences; ++i) {
const sentence_type* s = &corpus->sentence[i];
prs[i].ngold = lround(s->g);
if (s->nparses > 0) {
size_type j = max_score_index(s, &ws[0]);
const parse_type* p = &s->parse[j];
prs[i].ntest = lround(p->p);
prs[i].ncommon = lround(p->w);
}
prsum += prs[i];
}
} // corpus_prs()
// fscore_difference sets n1better, n2better and n12tied based on the
// fscores in prs1 and prs2
//
void fscore_difference(const prs_type& prs1, const prs_type& prs2,
size_type& n1better, size_type& n2better,
size_type& n12tied) {
assert(prs1.size() == prs2.size());
n1better = 0;
n2better = 0;
n12tied = 0;
for (size_type i = 0; i < prs1.size(); ++i) {
Float f1 = prs1[i].f_score();
Float f2 = prs2[i].f_score();
if (f1 > f2)
++n1better;
else if (f2 > f1)
++n2better;
else
++n12tied;
}
} // fscore_difference()
//! binomial_significance returns the probability of obtaining k or fewer
//! successes in n trials
//
Float binomial_significance(size_type n, size_type k) {
assert(n >= 1);
assert(n >= k);
if (k <= n/2)
k = n - k; // swap if k is less than half n
return 2*incbet(k, n-k+1, 0.5);
}
//! permutation_test() estimates the significance of the difference
//! in corpus f-scores between prs1 and prs2.
//
Float permutation_test(const prs_type& prs1, const prs_type& prs2,
const size_type ns = 100000) {
assert(prs1.size() == prs2.size());
size_type m = prs1.size();
pr_type prsum1, prsum2;
for (size_type j = 0; j < m; ++j) {
prsum1 += prs1[j];
prsum2 += prs2[j];
}
Float emp_abs_delta_fscore = fabs(prsum1.f_score()-prsum2.f_score());
size_type ngreater = 0;
for (size_type i = 0; i < ns; ++i) {
prsum1.clear();
prsum2.clear();
for (size_type j = 0; j < m; ++j)
if (rand() < RAND_MAX/2) { // randomly permute sentence scores
prsum1 += prs1[j];
prsum2 += prs2[j];
}
else {
prsum1 += prs2[j];
prsum2 += prs1[j];
}
Float sim_abs_delta_fscore = fabs(prsum1.f_score()-prsum2.f_score());
if (sim_abs_delta_fscore >= emp_abs_delta_fscore)
++ngreater;
}
return Float(ngreater)/Float(ns);
} // permutation_test()
//! bootstrap_interval() provides a bootstrap resampling estimate of
//! a confidence interval of the f-score.
//
FF boostrap_interval(const prs_type& prs,
Float lower = 0.025, Float upper = 0.975,
const size_type ns = 100000) {
Floats fscores(ns);
for (size_type is = 0; is < ns; ++is) {
int rfactor = RAND_MAX/prs.size();
pr_type pr_sum;
for (size_type i = 0; i < prs.size(); ++i) {
size_type j;
do j = rand()/rfactor;
while (j >= prs.size());
pr_sum += prs[j];
}
fscores[is] = pr_sum.f_score();
}
size_type lower_index = lrint(lower * ns);
assert(lower_index < ns);
std::nth_element(fscores.begin(), fscores.begin()+lower_index, fscores.end());
Float lowerbound = fscores[lower_index];
size_type upper_index = lrint(upper * ns);
assert(upper_index < ns);
std::nth_element(fscores.begin(), fscores.begin()+upper_index, fscores.end());
Float upperbound = fscores[upper_index];
return FF(lowerbound,upperbound);
} // bootstrap_interval()
int main(int argc, char* argv[]) {
if (argc < 3 || argc > 5) {
std::cerr << usage << std::endl;
exit(EXIT_FAILURE);
}
corpus_type* corpus1 = read_corpus_file(NULL, argv[2]);
if (corpus1 == NULL) {
std::cerr << "## Error in compare-models: unable to read corpus file "
<< argv[2]
<< "\n\n" << usage << std::endl;
exit(EXIT_FAILURE);
}
size_type nf1 = corpus1->nfeatures;
Floats ws1(nf1), ws2(nf1);
read_weights_file(argv[1], ws1);
corpus_type* corpus2 = corpus1;
size_type nf2 = nf1;
if (argc >= 4) {
if (argc >= 5) {
corpus2 = read_corpus_file(NULL, argv[4]);
if (corpus2 == NULL) {
std::cerr << "## Error in compare-models: unable to read corpus file "
<< argv[4]
<< "\n\n" << usage << std::endl;
exit(EXIT_FAILURE);
}
assert(corpus1->nsentences == corpus2->nsentences);
assert(corpus1->maxnparses == corpus2->maxnparses);
}
nf2 = corpus2->nfeatures;
ws2.resize(nf2);
read_weights_file(argv[3], ws2);
}
else {
ws2[0] = ws1[0]; // if no weights file given, put all weight onto feature 0
if (ws2[0] == 0)
ws2[0] = -1;
}
pr_type pr1, pr2;
prs_type prs1, prs2;
corpus_prs(corpus1, ws1, prs1, pr1);
corpus_prs(corpus2, ws2, prs2, pr2);
size_type nsentences = corpus1->nsentences;
std::cout << "nsentences = " << nsentences << " in test corpus." << std::endl;
std::cout << "model 1 nfeatures = " << ws1.size() << ", corpus f-score = " << pr1.f_score() << std::endl;
std::cout << "model 2 nfeatures = " << ws2.size() << ", corpus f-score = " << pr2.f_score() << std::endl;
std::cout << "permutation test significance of corpus f-score difference = "
<< permutation_test(prs1, prs2) << std::endl;
size_type n1better, n2better, n12tied;
fscore_difference(prs1, prs2, n1better, n2better, n12tied);
std::cout << "model 1 better on " << n1better << " = " << (100.0*n1better)/nsentences << "% sentences" << std::endl;
std::cout << "model 2 better on " << n2better << " = " << (100.0*n2better)/nsentences << "% sentences" << std::endl;
std::cout << "models 1 and 2 tied on " << n12tied << " = " << (100*n12tied)/nsentences << "% sentences" << std::endl;
std::cout << "binomial 2-sided significance of sentence-by-sentence comparison = "
<< binomial_significance(n1better+n2better, n2better) << std::endl;
std::cout << "bootstrap 95% confidence interval for model 1 f-scores = " << boostrap_interval(prs1) << std::endl;
std::cout << "bootstrap 95% confidence interval for model 2 f-scores = " << boostrap_interval(prs2) << std::endl;
} // main()
| 29.757042 | 119 | 0.621938 | [
"vector",
"model"
] |
16dff589264c5063db96661b2f5c9c6b62a1ebde | 793 | cpp | C++ | Estrutura/1251-Diga_frequencia.cpp | oDallas/URI | 2f32e224e86e934dc7742ee3e32dd7a48d47921d | [
"MIT"
] | null | null | null | Estrutura/1251-Diga_frequencia.cpp | oDallas/URI | 2f32e224e86e934dc7742ee3e32dd7a48d47921d | [
"MIT"
] | null | null | null | Estrutura/1251-Diga_frequencia.cpp | oDallas/URI | 2f32e224e86e934dc7742ee3e32dd7a48d47921d | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
bool compare(pair <unsigned int, unsigned int> a, pair <unsigned int, unsigned int> b) {
return (
a.second!=b.second ? a.second<b.second :
a.first>b.first
);
}
int main() {
unsigned int i, j;
char text[1001];
bool imprime=false;
while (cin >> text) {
if (imprime) cout << endl;
else imprime=true;
map <unsigned int, unsigned int> cases;
vector <pair <unsigned int, unsigned int>> final;
for (i=0; text[i]; i++) {
cases[text[i]]++;
}
copy(cases.begin(), cases.end(), back_inserter(final));
sort(final.begin(), final.end(), compare);
for (auto F: final) {
cout << F.first << ' ' << F.second << endl;
}
}
return 0;
} | 19.825 | 88 | 0.595208 | [
"vector"
] |
16ea046e43dbe9c65bea35bea2ecff87bf106391 | 431 | cpp | C++ | Beginners/Some Basic C++ Programs/stockBuySell.cpp | Sanjulata19/Hacktoberfest_2021-1 | 720855c9e7e3d1ca04d409cc7defb29381e4a16a | [
"Apache-2.0"
] | 1 | 2021-10-31T14:33:09.000Z | 2021-10-31T14:33:09.000Z | Beginners/Some Basic C++ Programs/stockBuySell.cpp | Sanjulata19/Hacktoberfest_2021-1 | 720855c9e7e3d1ca04d409cc7defb29381e4a16a | [
"Apache-2.0"
] | 4 | 2021-10-31T14:16:14.000Z | 2021-10-31T16:56:12.000Z | Beginners/Some Basic C++ Programs/stockBuySell.cpp | Sanjulata19/Hacktoberfest_2021-1 | 720855c9e7e3d1ca04d409cc7defb29381e4a16a | [
"Apache-2.0"
] | 19 | 2021-10-30T06:23:49.000Z | 2021-10-31T14:51:04.000Z | #include <iostream>
#include <vector>
using namespace std;
void maxProfit(vector<int> &price) {
int profit = 0;
int n = price.size();
if (n < 2) return;
for (int i=1; i<n; i++) {
if (price[i] > price[i-1])
profit += price[i] - price[i-1];
}
cout<<"Maximum possible profit is: "<<profit<<endl;
}
int main() {
vector<int> arr{1, 5, 4, 3, 8, 12};
maxProfit(arr);
return 0;
}
| 19.590909 | 55 | 0.538283 | [
"vector"
] |
16ed9747d2b0f3aaf5ead8f3ed5b956aad185171 | 3,205 | cpp | C++ | src/example/MeshWireframeEx.cpp | HongqiangWei/Alloy-Graphics-Library | 8c2b1436f6f0463f4dae109a0284deeb3486e326 | [
"MIT"
] | null | null | null | src/example/MeshWireframeEx.cpp | HongqiangWei/Alloy-Graphics-Library | 8c2b1436f6f0463f4dae109a0284deeb3486e326 | [
"MIT"
] | null | null | null | src/example/MeshWireframeEx.cpp | HongqiangWei/Alloy-Graphics-Library | 8c2b1436f6f0463f4dae109a0284deeb3486e326 | [
"MIT"
] | null | null | null | /*
* Copyright(C) 2015, Blake C. Lucas, Ph.D. (img.science@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "Alloy.h"
#include "../../include/example/MeshWireframeEx.h"
using namespace aly;
MeshWireframeEx::MeshWireframeEx() :
Application(800, 600, "Mesh with Wireframe Example"), matcapShader(
getFullPath("images/JG_Silver.png")),imageShader(ImageShader::Filter::SMALL_BLUR) {
}
bool MeshWireframeEx::init(Composite& rootNode) {
box3f renderBBox = box3f(float3(-0.5f, -0.5f, -0.5f),
float3(1.0f, 1.0f, 1.0f));
mesh.load(getFullPath("models/monkey.obj"));
Subdivide(mesh,SubDivisionScheme::CatmullClark);
mesh.updateVertexNormals();
//Make region on screen to render 3d view
renderRegion = MakeRegion("Render View", CoordPerPX(0.5f, 0.5f, -256, -256),
CoordPX(512, 512), COLOR_NONE, COLOR_WHITE, UnitPX(1.0f));
//Initialize depth buffer to store the render
depthFrameBuffer.initialize(512, 512);
wireframeFrameBuffer.initialize(512, 512);
//Set up camera
camera.setNearFarPlanes(-2.0f, 2.0f);
camera.setZoom(0.75f);
camera.setCameraType(CameraType::Orthographic);
//Map object geometry into unit bounding box for draw.
camera.setPose(MakeTransform(mesh.getBoundingBox(), renderBBox));
//Add listener to respond to mouse manipulations
addListener(&camera);
//Add render component to root node so it is relatively positioned.
rootNode.add(renderRegion);
setOnResize([=](const int2& dims) {
camera.setDirty(true);
});
wireframeShader.setFaceColor(Color(0.1f,0.1f,1.0f,0.5f));
wireframeShader.setEdgeColor(Color(1.0f,0.8f,0.1f,1.0f));
wireframeShader.setLineWidth(1.5f);
return true;
}
void MeshWireframeEx::draw(AlloyContext* context) {
if (camera.isDirty()) {
depthAndNormalShader.draw(mesh, camera, depthFrameBuffer);
wireframeShader.draw(mesh, camera, wireframeFrameBuffer);
}
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
matcapShader.draw(depthFrameBuffer.getTexture(), camera, context->pixelRatio*renderRegion->getBounds(), context->getViewport(), RGBAf(1.0f));
imageShader.draw(wireframeFrameBuffer.getTexture(), context->pixelRatio*renderRegion->getBounds(), 1.0f, false);
camera.setDirty(false);
}
| 45.140845 | 142 | 0.756942 | [
"mesh",
"geometry",
"render",
"object",
"3d"
] |
a84625d28e96bbadce1b3a766c75541d96532df1 | 9,057 | cc | C++ | builder/submap.cc | Foued70/StaticMapping | 1ca31318386de954702ad88804e1cb41d5ee0486 | [
"MIT"
] | null | null | null | builder/submap.cc | Foued70/StaticMapping | 1ca31318386de954702ad88804e1cb41d5ee0486 | [
"MIT"
] | null | null | null | builder/submap.cc | Foued70/StaticMapping | 1ca31318386de954702ad88804e1cb41d5ee0486 | [
"MIT"
] | null | null | null | // MIT License
// Copyright (c) 2019 Edward Liu
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "builder/submap.h"
#include "common/make_unique.h"
#include "common/point_utils.h"
#include "common/simple_time.h"
namespace static_map {
template <typename PointType>
void Submap<PointType>::InsertFrame(
const std::shared_ptr<Frame<PointType>>& frame) {
CHECK(frame != nullptr);
CHECK(!full_.load());
if (frames_.empty()) {
this->global_pose_ = frame->GlobalPose();
frame->SetLocalPose(Eigen::Matrix4f::Identity());
this->SetTimeStamp(frame->GetTimeStamp());
} else {
frame->SetLocalPose(this->global_pose_.inverse() * frame->GlobalPose());
}
frame->id_.frame_index = frames_.size();
frame->id_.submap_index = id_.submap_index;
frame->id_.trajectory_index = id_.trajectory_index;
frames_.push_back(frame);
if (frames_.size() == options_.frame_count) {
full_ = true;
}
if (full_.load()) {
PointCloudPtr output_cloud(new PointCloudType);
MultiResolutionVoxelMap<PointType> map;
// todo add a parameter : z offset
map.SetOffsetZ(1.2);
for (auto& frame : frames_) {
pcl::transformPointCloud(*frame->Cloud(), *output_cloud,
frame->LocalPose());
if (options_.enable_check) {
FATAL_CHECK_CLOUD(output_cloud);
}
map.InsertPointCloud(output_cloud, frame->LocalTranslation());
}
map.OutputToPointCloud(0.51, this->cloud_);
// check if the submap is valid
if (options_.enable_check) {
FATAL_CHECK_CLOUD(this->cloud_);
}
if (options_.enable_inner_multiview_icp) {
MultiviewRegistratorLumPcl<PointType> multi_matcher;
for (auto& frame : frames_) {
multi_matcher.AddNewCloud(frame->Cloud(), frame->LocalPose());
}
multi_matcher.AlignAll(this->cloud_);
}
if (options_.enable_random_sampleing) {
RandomSamplerWithPlaneDetect<PointType> random_sampler;
random_sampler.SetSamplingRate(options_.random_sampling_rate);
random_sampler.SetInputCloud(this->cloud_);
PointCloudPtr filtered_final_cloud(new PointCloudType);
random_sampler.Filter(filtered_final_cloud);
*this->cloud_ = *filtered_final_cloud;
filtered_final_cloud.reset();
}
if (options_.enable_voxel_filter && !this->cloud_->empty()) {
pcl::ApproximateVoxelGrid<PointType> approximate_voxel_filter;
approximate_voxel_filter.setLeafSize(0.1, 0.1, 0.1);
PointCloudPtr filtered_final_cloud(new PointCloudType);
approximate_voxel_filter.setInputCloud(this->cloud_);
approximate_voxel_filter.filter(*filtered_final_cloud);
*this->cloud_ = *filtered_final_cloud;
filtered_final_cloud.reset();
}
is_cloud_in_memory_ = true;
}
}
template <typename PointType>
void Submap<PointType>::SetId(const SubmapId& id) {
id_ = id;
if (save_filename_.empty()) {
save_filename_ = options_.saving_name_prefix +
std::to_string(id_.trajectory_index) + "_" +
std::to_string(id_.submap_index) + ".pcd";
}
}
template <typename PointType>
void Submap<PointType>::SetSavePath(const std::string& path) {
save_path_ = path;
}
template <typename PointType>
std::vector<std::shared_ptr<Frame<PointType>>>& Submap<PointType>::GetFrames() {
ReadMutexLocker locker(mutex_);
return frames_;
}
template <typename PointType>
std::shared_ptr<Frame<PointType>> Submap<PointType>::GetFrame(
const FrameId& frame_id) {
if (frame_id.submap_index != id_.submap_index ||
frame_id.trajectory_index != id_.trajectory_index) {
return nullptr;
}
ReadMutexLocker locker(mutex_);
if (frame_id.frame_index >= frames_.size()) {
return nullptr;
}
return frames_.at(frame_id.frame_index);
}
template <typename PointType>
void Submap<PointType>::SetMatchedTransformedToNext(const Eigen::Matrix4f& t) {
CHECK(!got_matched_transform_to_next_.load());
got_matched_transform_to_next_ = true;
boost::upgrade_lock<ReadWriteMutex> locker(mutex_);
{
WriteMutexLocker write_locker(locker);
this->SetTransformToNext(t);
}
if (options_.enable_disk_saving) {
CHECK(!save_filename_.empty());
ToPcdFile(save_path_ + save_filename_);
}
}
template <typename PointType>
typename Submap<PointType>::PointCloudPtr Submap<PointType>::Cloud() {
cloud_inactive_time_ = 0;
boost::upgrade_lock<ReadWriteMutex> locker(mutex_);
if (!is_cloud_in_memory_.load()) {
WriteMutexLocker write_locker(locker);
CHECK(pcl::io::loadPCDFile<PointType>(save_path_ + save_filename_,
*this->cloud_) == 0);
is_cloud_in_memory_ = true;
// PRINT_DEBUG_FMT("get submap data %d from disk.", id_.submap_index);
}
return this->cloud_;
}
template <typename PointType>
bool Submap<PointType>::UpdateInactiveTime(const int update_time_in_sec) {
if (!options_.enable_disk_saving) {
return true;
}
if (!got_matched_transform_to_next_.load()) {
return true;
}
boost::upgrade_lock<ReadWriteMutex> locker(mutex_);
if (is_cloud_in_memory_.load()) {
cloud_inactive_time_ += update_time_in_sec;
if (cloud_inactive_time_ > options_.disk_saving_delay) {
WriteMutexLocker write_locker(locker);
this->cloud_->points.clear();
this->cloud_->points.shrink_to_fit();
is_cloud_in_memory_ = false;
// PRINT_DEBUG_FMT("Remove submap %d from RAM.", id_.submap_index);
}
}
return is_cloud_in_memory_.load();
}
template <typename PointType>
void Submap<PointType>::ToPcdFile(const std::string& filename) {
if (!full_.load() || this->cloud_ == nullptr || this->cloud_->empty()) {
return;
}
// PRINT_INFO("Export submap pcd file.");
if (!filename.empty()) {
pcl::io::savePCDFileBinaryCompressed(filename, *this->cloud_);
} else {
pcl::io::savePCDFileBinaryCompressed(
"submap_" + std::to_string(id_.submap_index) + ".pcd", *this->cloud_);
}
}
template <typename PointType>
void Submap<PointType>::ToVtkFile(const std::string& filename) {
if (!full_.load() || this->cloud_ == nullptr || this->cloud_->empty()) {
return;
}
PRINT_INFO("Export submap vtk file.");
pcl::PCLPointCloud2 cloud2;
pcl::toPCLPointCloud2(*this->cloud_, cloud2);
if (!filename.empty()) {
pcl::io::saveVTKFile(filename, cloud2);
} else {
pcl::io::saveVTKFile("submap_" + std::to_string(id_.submap_index) + ".vtk",
cloud2);
}
}
template <typename PointType>
void Submap<PointType>::ToInfoFile(const std::string& filename) {
std::ofstream info_file(filename, std::ios::out | std::ios::binary);
if (info_file.is_open()) {
info_file.close();
} else {
PRINT_ERROR_FMT("Cannot open file: %s", filename.c_str());
}
}
template <typename PointType>
void Submap<PointType>::ClearCloudInFrames() {
CHECK(full_.load());
for (auto& frame : frames_) {
frame->ClearCloud();
}
}
template <typename PointType>
void Submap<PointType>::AddConnectedSubmap(const SubmapId& id) {
// do not need locker now
// boost::upgrade_lock<ReadWriteMutex> locker(mutex_);
// WriteMutexLocker write_locker(locker);
connected_submaps_.push_back(id);
}
template <typename PointType>
std::vector<SubmapId>& Submap<PointType>::GetConnected() {
return connected_submaps_;
}
template <typename PointType>
void Submap<PointType>::UpdateInnerFramePose() {
boost::upgrade_lock<ReadWriteMutex> locker(mutex_);
WriteMutexLocker write_locker(locker);
for (auto& frame : frames_) {
frame->SetGlobalPose(this->global_pose_ * frame->LocalPose());
}
}
template <typename PointType>
std::string Submap<PointType>::SavedFileName() {
if (options_.enable_disk_saving) {
return save_filename_;
}
return "";
}
template <typename PointType>
void Submap<PointType>::SetSavedFileName(const std::string& filename) {
save_filename_ = filename;
}
template <typename PointType>
Submap<PointType>::~Submap() {}
template class Submap<pcl::PointXYZI>;
} // namespace static_map
| 31.778947 | 80 | 0.706194 | [
"vector"
] |
a847ce1662a714fe8242c6b91a9d93d2d4266d14 | 6,321 | cpp | C++ | tests/unit/fem/test_assemblediagonalpa.cpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/fem/test_assemblediagonalpa.cpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/fem/test_assemblediagonalpa.cpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "catch.hpp"
using namespace mfem;
namespace assemblediagonalpa
{
TEST_CASE("massdiag")
{
for (int dimension = 2; dimension < 4; ++dimension)
{
for (int ne = 1; ne < 3; ++ne)
{
std::cout << "Testing " << dimension << "D partial assembly mass diagonal: "
<< std::pow(ne, dimension) << " elements." << std::endl;
for (int order = 1; order < 5; ++order)
{
Mesh * mesh;
if (dimension == 2)
{
mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);
}
else
{
mesh = new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);
}
FiniteElementCollection *h1_fec = new H1_FECollection(order, dimension);
FiniteElementSpace h1_fespace(mesh, h1_fec);
BilinearForm paform(&h1_fespace);
ConstantCoefficient one(1.0);
paform.SetAssemblyLevel(AssemblyLevel::PARTIAL);
paform.AddDomainIntegrator(new MassIntegrator(one));
paform.Assemble();
Vector pa_diag(h1_fespace.GetVSize());
paform.AssembleDiagonal(pa_diag);
BilinearForm faform(&h1_fespace);
faform.AddDomainIntegrator(new MassIntegrator(one));
faform.Assemble();
faform.Finalize();
Vector assembly_diag(h1_fespace.GetVSize());
faform.SpMat().GetDiag(assembly_diag);
assembly_diag -= pa_diag;
double error = assembly_diag.Norml2();
std::cout << " order: " << order << ", error norm: " << error << std::endl;
REQUIRE(assembly_diag.Norml2() < 1.e-12);
delete mesh;
delete h1_fec;
}
}
}
}
TEST_CASE("diffusiondiag")
{
for (int dimension = 2; dimension < 4; ++dimension)
{
for (int ne = 1; ne < 3; ++ne)
{
std::cout << "Testing " << dimension <<
"D partial assembly diffusion diagonal: "
<< std::pow(ne, dimension) << " elements." << std::endl;
for (int order = 1; order < 5; ++order)
{
Mesh * mesh;
if (dimension == 2)
{
mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);
}
else
{
mesh = new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);
}
FiniteElementCollection *h1_fec = new H1_FECollection(order, dimension);
FiniteElementSpace h1_fespace(mesh, h1_fec);
BilinearForm paform(&h1_fespace);
ConstantCoefficient one(1.0);
paform.SetAssemblyLevel(AssemblyLevel::PARTIAL);
paform.AddDomainIntegrator(new DiffusionIntegrator(one));
paform.Assemble();
Vector pa_diag(h1_fespace.GetVSize());
paform.AssembleDiagonal(pa_diag);
BilinearForm faform(&h1_fespace);
faform.AddDomainIntegrator(new DiffusionIntegrator(one));
faform.Assemble();
faform.Finalize();
Vector assembly_diag(h1_fespace.GetVSize());
faform.SpMat().GetDiag(assembly_diag);
assembly_diag -= pa_diag;
double error = assembly_diag.Norml2();
std::cout << " order: " << order << ", error norm: " << error << std::endl;
REQUIRE(assembly_diag.Norml2() < 1.e-12);
delete mesh;
delete h1_fec;
}
}
}
}
template <typename INTEGRATOR>
double test_vdiagpa(int dim, int order)
{
Mesh *mesh = nullptr;
if (dim == 2)
{
mesh = new Mesh(2, 2, Element::QUADRILATERAL, 0, 1.0, 1.0);
}
else if (dim == 3)
{
mesh = new Mesh(2, 2, 2, Element::HEXAHEDRON, 0, 1.0, 1.0, 1.0);
}
H1_FECollection fec(order, dim);
FiniteElementSpace fes(mesh, &fec, dim);
BilinearForm form(&fes);
form.SetAssemblyLevel(AssemblyLevel::PARTIAL);
form.AddDomainIntegrator(new INTEGRATOR);
form.Assemble();
Vector diag(fes.GetVSize());
form.AssembleDiagonal(diag);
BilinearForm form_full(&fes);
form_full.AddDomainIntegrator(new INTEGRATOR);
form_full.Assemble();
form_full.Finalize();
Vector diag_full(fes.GetVSize());
form_full.SpMat().GetDiag(diag_full);
diag_full -= diag;
delete mesh;
return diag_full.Norml2();
}
TEST_CASE("Vector Mass Diagonal PA", "[PartialAssembly], [AssembleDiagonal]")
{
SECTION("2D")
{
REQUIRE(test_vdiagpa<VectorMassIntegrator>(2,
2) == Approx(0.0));
REQUIRE(test_vdiagpa<VectorMassIntegrator>(2,
3) == Approx(0.0));
}
SECTION("3D")
{
REQUIRE(test_vdiagpa<VectorMassIntegrator>(3,
2) == Approx(0.0));
REQUIRE(test_vdiagpa<VectorMassIntegrator>(3,
3) == Approx(0.0));
}
}
TEST_CASE("Vector Diffusion Diagonal PA",
"[PartialAssembly], [AssembleDiagonal]")
{
SECTION("2D")
{
REQUIRE(
test_vdiagpa<VectorDiffusionIntegrator>(2,
2) == Approx(0.0));
REQUIRE(test_vdiagpa<VectorDiffusionIntegrator>(2,
3) == Approx(0.0));
}
SECTION("3D")
{
REQUIRE(test_vdiagpa<VectorDiffusionIntegrator>(3,
2) == Approx(0.0));
REQUIRE(test_vdiagpa<VectorDiffusionIntegrator>(3,
3) == Approx(0.0));
}
}
} // namespace assemblediagonalpa
| 31.447761 | 90 | 0.548015 | [
"mesh",
"vector",
"3d"
] |
a84f705913c9a382e9ff0ff9aa3c5cfa021405e9 | 1,427 | cc | C++ | max-consecutive-ones.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | max-consecutive-ones.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | max-consecutive-ones.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | #include <vector>
#include <algorithm>
class Solution
{
public:
int findMaxConsecutiveOnes(std::vector<int> &nums)
{
return findMaxConsecutiveOnesStateMachine(nums);
}
int findMaxConsecutiveOnesStateMachine(std::vector<int> &nums)
{
int count = 0;
int res = 0;
int state = 0;
for (int i = 0; i < nums.size(); i++)
{
switch (state)
{
case 0:
if (nums[i] == 1)
{
state = 1;
count++;
}
break;
case 1:
if (nums[i] == 0)
{
state = 0;
res = std::max(res, count);
count = 0;
}
else
count++;
break;
default:
break;
}
}
return std::max(res, count);
}
int findMaxConsecutiveOnesSlidingWindow(std::vector<int> &nums)
{
int l = 0, r = 0;
int res = 0;
while (r < nums.size())
{
while (l < nums.size() && nums[l] != 1)
l++;
r = l;
while (r < nums.size() && nums[r] == 1)
r++;
res = std::max(r - l, res);
l++;
}
return res;
}
}; | 21.953846 | 67 | 0.355291 | [
"vector"
] |
a8545b4966f2b1ee08ede79058ee8f72015b815a | 3,019 | cpp | C++ | Engine/gapi/vulkan/vuniformslay.cpp | sam-baumann/Tempest | 6152339e97412d03829fce58a27fc3e66fa67bac | [
"MIT"
] | null | null | null | Engine/gapi/vulkan/vuniformslay.cpp | sam-baumann/Tempest | 6152339e97412d03829fce58a27fc3e66fa67bac | [
"MIT"
] | null | null | null | Engine/gapi/vulkan/vuniformslay.cpp | sam-baumann/Tempest | 6152339e97412d03829fce58a27fc3e66fa67bac | [
"MIT"
] | null | null | null | #include "vuniformslay.h"
#include <Tempest/UniformsLayout>
#include "vdevice.h"
#include "gapi/shaderreflection.h"
using namespace Tempest;
using namespace Tempest::Detail;
VUniformsLay::VUniformsLay(VDevice& dev, const std::vector<UniformsLayout::Binding>& comp)
: dev(dev.device) {
ShaderReflection::merge(lay, pb, comp);
adjustSsboBindings();
if(lay.size()<=32) {
VkDescriptorSetLayoutBinding bind[32]={};
implCreate(bind);
} else {
std::unique_ptr<VkDescriptorSetLayoutBinding[]> bind(new VkDescriptorSetLayoutBinding[lay.size()]);
implCreate(bind.get());
}
}
VUniformsLay::VUniformsLay(VDevice& dev, const std::vector<UniformsLayout::Binding>* sh[], size_t cnt)
: dev(dev.device) {
ShaderReflection::merge(lay, pb, sh, cnt);
adjustSsboBindings();
if(lay.size()<=32) {
VkDescriptorSetLayoutBinding bind[32]={};
implCreate(bind);
} else {
std::unique_ptr<VkDescriptorSetLayoutBinding[]> bind(new VkDescriptorSetLayoutBinding[lay.size()]);
implCreate(bind.get());
}
}
VUniformsLay::~VUniformsLay() {
for(auto& i:pool)
vkDestroyDescriptorPool(dev,i.impl,nullptr);
vkDestroyDescriptorSetLayout(dev,impl,nullptr);
}
void VUniformsLay::implCreate(VkDescriptorSetLayoutBinding* bind) {
static const VkDescriptorType types[] = {
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
VK_DESCRIPTOR_TYPE_STORAGE_IMAGE
};
uint32_t count = 0;
for(size_t i=0;i<lay.size();++i){
auto& b=bind[count];
auto& e=lay[i];
if(e.stage==UniformsLayout::Stage(0))
continue;
b.binding = e.layout;
b.descriptorCount = 1;
b.descriptorType = types[e.cls];
b.stageFlags = 0;
if(e.stage&UniformsLayout::Compute)
b.stageFlags |= VK_SHADER_STAGE_COMPUTE_BIT;
if(e.stage&UniformsLayout::Vertex)
b.stageFlags |= VK_SHADER_STAGE_VERTEX_BIT;
if(e.stage&UniformsLayout::Control)
b.stageFlags |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
if(e.stage&UniformsLayout::Evaluate)
b.stageFlags |= VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
if(e.stage&UniformsLayout::Geometry)
b.stageFlags |= VK_SHADER_STAGE_GEOMETRY_BIT;
if(e.stage&UniformsLayout::Fragment)
b.stageFlags |= VK_SHADER_STAGE_FRAGMENT_BIT;
++count;
}
VkDescriptorSetLayoutCreateInfo info={};
info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
info.bindingCount = count;
info.pBindings = bind;
vkAssert(vkCreateDescriptorSetLayout(dev,&info,nullptr,&impl));
}
void VUniformsLay::adjustSsboBindings() {
for(auto& i:lay)
if(i.size==0)
i.size = VK_WHOLE_SIZE;
for(auto& i:lay)
if(i.cls==UniformsLayout::SsboR ||
i.cls==UniformsLayout::SsboRW ||
i.cls==UniformsLayout::ImgR ||
i.cls==UniformsLayout::ImgRW ) {
hasSSBO = true;
}
}
| 29.31068 | 103 | 0.702882 | [
"geometry",
"vector"
] |
a85b497dd131e3e608146fe9d8f4bd33b7b5c982 | 63,599 | cpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_man_xml_ttyagent_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_man_xml_ttyagent_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_man_xml_ttyagent_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_man_xml_ttyagent_cfg.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_man_xml_ttyagent_cfg {
XrXml::XrXml()
:
agent(std::make_shared<XrXml::Agent>())
{
agent->parent = this;
yang_name = "xr-xml"; yang_parent_name = "Cisco-IOS-XR-man-xml-ttyagent-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
XrXml::~XrXml()
{
}
bool XrXml::has_data() const
{
if (is_presence_container) return true;
return (agent != nullptr && agent->has_data());
}
bool XrXml::has_operation() const
{
return is_set(yfilter)
|| (agent != nullptr && agent->has_operation());
}
std::string XrXml::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "agent")
{
if(agent == nullptr)
{
agent = std::make_shared<XrXml::Agent>();
}
return agent;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(agent != nullptr)
{
_children["agent"] = agent;
}
return _children;
}
void XrXml::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void XrXml::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> XrXml::clone_ptr() const
{
return std::make_shared<XrXml>();
}
std::string XrXml::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string XrXml::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function XrXml::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> XrXml::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool XrXml::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "agent")
return true;
return false;
}
XrXml::Agent::Agent()
:
default_(std::make_shared<XrXml::Agent::Default>())
, tty(std::make_shared<XrXml::Agent::Tty>())
, ssl(std::make_shared<XrXml::Agent::Ssl>())
{
default_->parent = this;
tty->parent = this;
ssl->parent = this;
yang_name = "agent"; yang_parent_name = "xr-xml"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::~Agent()
{
}
bool XrXml::Agent::has_data() const
{
if (is_presence_container) return true;
return (default_ != nullptr && default_->has_data())
|| (tty != nullptr && tty->has_data())
|| (ssl != nullptr && ssl->has_data());
}
bool XrXml::Agent::has_operation() const
{
return is_set(yfilter)
|| (default_ != nullptr && default_->has_operation())
|| (tty != nullptr && tty->has_operation())
|| (ssl != nullptr && ssl->has_operation());
}
std::string XrXml::Agent::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "agent";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default")
{
if(default_ == nullptr)
{
default_ = std::make_shared<XrXml::Agent::Default>();
}
return default_;
}
if(child_yang_name == "tty")
{
if(tty == nullptr)
{
tty = std::make_shared<XrXml::Agent::Tty>();
}
return tty;
}
if(child_yang_name == "ssl")
{
if(ssl == nullptr)
{
ssl = std::make_shared<XrXml::Agent::Ssl>();
}
return ssl;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_ != nullptr)
{
_children["default"] = default_;
}
if(tty != nullptr)
{
_children["tty"] = tty;
}
if(ssl != nullptr)
{
_children["ssl"] = ssl;
}
return _children;
}
void XrXml::Agent::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void XrXml::Agent::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool XrXml::Agent::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default" || name == "tty" || name == "ssl")
return true;
return false;
}
XrXml::Agent::Default::Default()
:
ipv6_enable{YType::boolean, "ipv6-enable"},
ipv4_disable{YType::boolean, "ipv4-disable"},
iteration_size{YType::uint32, "iteration-size"},
enable{YType::empty, "enable"},
streaming_size{YType::uint32, "streaming-size"}
,
session(std::make_shared<XrXml::Agent::Default::Session>())
, throttle(std::make_shared<XrXml::Agent::Default::Throttle>())
, vrfs(std::make_shared<XrXml::Agent::Default::Vrfs>())
{
session->parent = this;
throttle->parent = this;
vrfs->parent = this;
yang_name = "default"; yang_parent_name = "agent"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Default::~Default()
{
}
bool XrXml::Agent::Default::has_data() const
{
if (is_presence_container) return true;
return ipv6_enable.is_set
|| ipv4_disable.is_set
|| iteration_size.is_set
|| enable.is_set
|| streaming_size.is_set
|| (session != nullptr && session->has_data())
|| (throttle != nullptr && throttle->has_data())
|| (vrfs != nullptr && vrfs->has_data());
}
bool XrXml::Agent::Default::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(ipv6_enable.yfilter)
|| ydk::is_set(ipv4_disable.yfilter)
|| ydk::is_set(iteration_size.yfilter)
|| ydk::is_set(enable.yfilter)
|| ydk::is_set(streaming_size.yfilter)
|| (session != nullptr && session->has_operation())
|| (throttle != nullptr && throttle->has_operation())
|| (vrfs != nullptr && vrfs->has_operation());
}
std::string XrXml::Agent::Default::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Default::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Default::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (ipv6_enable.is_set || is_set(ipv6_enable.yfilter)) leaf_name_data.push_back(ipv6_enable.get_name_leafdata());
if (ipv4_disable.is_set || is_set(ipv4_disable.yfilter)) leaf_name_data.push_back(ipv4_disable.get_name_leafdata());
if (iteration_size.is_set || is_set(iteration_size.yfilter)) leaf_name_data.push_back(iteration_size.get_name_leafdata());
if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata());
if (streaming_size.is_set || is_set(streaming_size.yfilter)) leaf_name_data.push_back(streaming_size.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "session")
{
if(session == nullptr)
{
session = std::make_shared<XrXml::Agent::Default::Session>();
}
return session;
}
if(child_yang_name == "throttle")
{
if(throttle == nullptr)
{
throttle = std::make_shared<XrXml::Agent::Default::Throttle>();
}
return throttle;
}
if(child_yang_name == "vrfs")
{
if(vrfs == nullptr)
{
vrfs = std::make_shared<XrXml::Agent::Default::Vrfs>();
}
return vrfs;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Default::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(session != nullptr)
{
_children["session"] = session;
}
if(throttle != nullptr)
{
_children["throttle"] = throttle;
}
if(vrfs != nullptr)
{
_children["vrfs"] = vrfs;
}
return _children;
}
void XrXml::Agent::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ipv6-enable")
{
ipv6_enable = value;
ipv6_enable.value_namespace = name_space;
ipv6_enable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4-disable")
{
ipv4_disable = value;
ipv4_disable.value_namespace = name_space;
ipv4_disable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "iteration-size")
{
iteration_size = value;
iteration_size.value_namespace = name_space;
iteration_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "enable")
{
enable = value;
enable.value_namespace = name_space;
enable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "streaming-size")
{
streaming_size = value;
streaming_size.value_namespace = name_space;
streaming_size.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Default::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ipv6-enable")
{
ipv6_enable.yfilter = yfilter;
}
if(value_path == "ipv4-disable")
{
ipv4_disable.yfilter = yfilter;
}
if(value_path == "iteration-size")
{
iteration_size.yfilter = yfilter;
}
if(value_path == "enable")
{
enable.yfilter = yfilter;
}
if(value_path == "streaming-size")
{
streaming_size.yfilter = yfilter;
}
}
bool XrXml::Agent::Default::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "session" || name == "throttle" || name == "vrfs" || name == "ipv6-enable" || name == "ipv4-disable" || name == "iteration-size" || name == "enable" || name == "streaming-size")
return true;
return false;
}
XrXml::Agent::Default::Session::Session()
:
timeout{YType::uint32, "timeout"}
{
yang_name = "session"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Default::Session::~Session()
{
}
bool XrXml::Agent::Default::Session::has_data() const
{
if (is_presence_container) return true;
return timeout.is_set;
}
bool XrXml::Agent::Default::Session::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(timeout.yfilter);
}
std::string XrXml::Agent::Default::Session::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/default/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Default::Session::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "session";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Default::Session::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Default::Session::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Default::Session::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Default::Session::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "timeout")
{
timeout = value;
timeout.value_namespace = name_space;
timeout.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Default::Session::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "timeout")
{
timeout.yfilter = yfilter;
}
}
bool XrXml::Agent::Default::Session::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "timeout")
return true;
return false;
}
XrXml::Agent::Default::Throttle::Throttle()
:
process_rate{YType::uint32, "process-rate"},
memory{YType::uint32, "memory"}
{
yang_name = "throttle"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Default::Throttle::~Throttle()
{
}
bool XrXml::Agent::Default::Throttle::has_data() const
{
if (is_presence_container) return true;
return process_rate.is_set
|| memory.is_set;
}
bool XrXml::Agent::Default::Throttle::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(process_rate.yfilter)
|| ydk::is_set(memory.yfilter);
}
std::string XrXml::Agent::Default::Throttle::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/default/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Default::Throttle::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "throttle";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Default::Throttle::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (process_rate.is_set || is_set(process_rate.yfilter)) leaf_name_data.push_back(process_rate.get_name_leafdata());
if (memory.is_set || is_set(memory.yfilter)) leaf_name_data.push_back(memory.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Default::Throttle::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Default::Throttle::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Default::Throttle::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "process-rate")
{
process_rate = value;
process_rate.value_namespace = name_space;
process_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "memory")
{
memory = value;
memory.value_namespace = name_space;
memory.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Default::Throttle::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "process-rate")
{
process_rate.yfilter = yfilter;
}
if(value_path == "memory")
{
memory.yfilter = yfilter;
}
}
bool XrXml::Agent::Default::Throttle::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "process-rate" || name == "memory")
return true;
return false;
}
XrXml::Agent::Default::Vrfs::Vrfs()
:
vrf(this, {"vrf_name"})
{
yang_name = "vrfs"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Default::Vrfs::~Vrfs()
{
}
bool XrXml::Agent::Default::Vrfs::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_data())
return true;
}
return false;
}
bool XrXml::Agent::Default::Vrfs::has_operation() const
{
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string XrXml::Agent::Default::Vrfs::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/default/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Default::Vrfs::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrfs";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Default::Vrfs::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Default::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "vrf")
{
auto ent_ = std::make_shared<XrXml::Agent::Default::Vrfs::Vrf>();
ent_->parent = this;
vrf.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Default::Vrfs::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : vrf.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void XrXml::Agent::Default::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void XrXml::Agent::Default::Vrfs::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool XrXml::Agent::Default::Vrfs::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf")
return true;
return false;
}
XrXml::Agent::Default::Vrfs::Vrf::Vrf()
:
vrf_name{YType::str, "vrf-name"},
ipv6_access_list{YType::str, "ipv6-access-list"},
ipv4_access_list{YType::str, "ipv4-access-list"},
access_list{YType::str, "access-list"},
shutdown{YType::empty, "shutdown"}
{
yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Default::Vrfs::Vrf::~Vrf()
{
}
bool XrXml::Agent::Default::Vrfs::Vrf::has_data() const
{
if (is_presence_container) return true;
return vrf_name.is_set
|| ipv6_access_list.is_set
|| ipv4_access_list.is_set
|| access_list.is_set
|| shutdown.is_set;
}
bool XrXml::Agent::Default::Vrfs::Vrf::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(vrf_name.yfilter)
|| ydk::is_set(ipv6_access_list.yfilter)
|| ydk::is_set(ipv4_access_list.yfilter)
|| ydk::is_set(access_list.yfilter)
|| ydk::is_set(shutdown.yfilter);
}
std::string XrXml::Agent::Default::Vrfs::Vrf::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/default/vrfs/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Default::Vrfs::Vrf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrf";
ADD_KEY_TOKEN(vrf_name, "vrf-name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Default::Vrfs::Vrf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata());
if (ipv6_access_list.is_set || is_set(ipv6_access_list.yfilter)) leaf_name_data.push_back(ipv6_access_list.get_name_leafdata());
if (ipv4_access_list.is_set || is_set(ipv4_access_list.yfilter)) leaf_name_data.push_back(ipv4_access_list.get_name_leafdata());
if (access_list.is_set || is_set(access_list.yfilter)) leaf_name_data.push_back(access_list.get_name_leafdata());
if (shutdown.is_set || is_set(shutdown.yfilter)) leaf_name_data.push_back(shutdown.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Default::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Default::Vrfs::Vrf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Default::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "vrf-name")
{
vrf_name = value;
vrf_name.value_namespace = name_space;
vrf_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6-access-list")
{
ipv6_access_list = value;
ipv6_access_list.value_namespace = name_space;
ipv6_access_list.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4-access-list")
{
ipv4_access_list = value;
ipv4_access_list.value_namespace = name_space;
ipv4_access_list.value_namespace_prefix = name_space_prefix;
}
if(value_path == "access-list")
{
access_list = value;
access_list.value_namespace = name_space;
access_list.value_namespace_prefix = name_space_prefix;
}
if(value_path == "shutdown")
{
shutdown = value;
shutdown.value_namespace = name_space;
shutdown.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Default::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "vrf-name")
{
vrf_name.yfilter = yfilter;
}
if(value_path == "ipv6-access-list")
{
ipv6_access_list.yfilter = yfilter;
}
if(value_path == "ipv4-access-list")
{
ipv4_access_list.yfilter = yfilter;
}
if(value_path == "access-list")
{
access_list.yfilter = yfilter;
}
if(value_path == "shutdown")
{
shutdown.yfilter = yfilter;
}
}
bool XrXml::Agent::Default::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf-name" || name == "ipv6-access-list" || name == "ipv4-access-list" || name == "access-list" || name == "shutdown")
return true;
return false;
}
XrXml::Agent::Tty::Tty()
:
iteration_size{YType::uint32, "iteration-size"},
enable{YType::empty, "enable"},
streaming_size{YType::uint32, "streaming-size"}
,
session(std::make_shared<XrXml::Agent::Tty::Session>())
, throttle(std::make_shared<XrXml::Agent::Tty::Throttle>())
{
session->parent = this;
throttle->parent = this;
yang_name = "tty"; yang_parent_name = "agent"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Tty::~Tty()
{
}
bool XrXml::Agent::Tty::has_data() const
{
if (is_presence_container) return true;
return iteration_size.is_set
|| enable.is_set
|| streaming_size.is_set
|| (session != nullptr && session->has_data())
|| (throttle != nullptr && throttle->has_data());
}
bool XrXml::Agent::Tty::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(iteration_size.yfilter)
|| ydk::is_set(enable.yfilter)
|| ydk::is_set(streaming_size.yfilter)
|| (session != nullptr && session->has_operation())
|| (throttle != nullptr && throttle->has_operation());
}
std::string XrXml::Agent::Tty::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Tty::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "tty";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Tty::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (iteration_size.is_set || is_set(iteration_size.yfilter)) leaf_name_data.push_back(iteration_size.get_name_leafdata());
if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata());
if (streaming_size.is_set || is_set(streaming_size.yfilter)) leaf_name_data.push_back(streaming_size.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Tty::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "session")
{
if(session == nullptr)
{
session = std::make_shared<XrXml::Agent::Tty::Session>();
}
return session;
}
if(child_yang_name == "throttle")
{
if(throttle == nullptr)
{
throttle = std::make_shared<XrXml::Agent::Tty::Throttle>();
}
return throttle;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Tty::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(session != nullptr)
{
_children["session"] = session;
}
if(throttle != nullptr)
{
_children["throttle"] = throttle;
}
return _children;
}
void XrXml::Agent::Tty::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "iteration-size")
{
iteration_size = value;
iteration_size.value_namespace = name_space;
iteration_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "enable")
{
enable = value;
enable.value_namespace = name_space;
enable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "streaming-size")
{
streaming_size = value;
streaming_size.value_namespace = name_space;
streaming_size.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Tty::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "iteration-size")
{
iteration_size.yfilter = yfilter;
}
if(value_path == "enable")
{
enable.yfilter = yfilter;
}
if(value_path == "streaming-size")
{
streaming_size.yfilter = yfilter;
}
}
bool XrXml::Agent::Tty::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "session" || name == "throttle" || name == "iteration-size" || name == "enable" || name == "streaming-size")
return true;
return false;
}
XrXml::Agent::Tty::Session::Session()
:
timeout{YType::uint32, "timeout"}
{
yang_name = "session"; yang_parent_name = "tty"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Tty::Session::~Session()
{
}
bool XrXml::Agent::Tty::Session::has_data() const
{
if (is_presence_container) return true;
return timeout.is_set;
}
bool XrXml::Agent::Tty::Session::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(timeout.yfilter);
}
std::string XrXml::Agent::Tty::Session::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/tty/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Tty::Session::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "session";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Tty::Session::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Tty::Session::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Tty::Session::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Tty::Session::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "timeout")
{
timeout = value;
timeout.value_namespace = name_space;
timeout.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Tty::Session::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "timeout")
{
timeout.yfilter = yfilter;
}
}
bool XrXml::Agent::Tty::Session::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "timeout")
return true;
return false;
}
XrXml::Agent::Tty::Throttle::Throttle()
:
process_rate{YType::uint32, "process-rate"},
memory{YType::uint32, "memory"}
{
yang_name = "throttle"; yang_parent_name = "tty"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Tty::Throttle::~Throttle()
{
}
bool XrXml::Agent::Tty::Throttle::has_data() const
{
if (is_presence_container) return true;
return process_rate.is_set
|| memory.is_set;
}
bool XrXml::Agent::Tty::Throttle::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(process_rate.yfilter)
|| ydk::is_set(memory.yfilter);
}
std::string XrXml::Agent::Tty::Throttle::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/tty/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Tty::Throttle::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "throttle";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Tty::Throttle::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (process_rate.is_set || is_set(process_rate.yfilter)) leaf_name_data.push_back(process_rate.get_name_leafdata());
if (memory.is_set || is_set(memory.yfilter)) leaf_name_data.push_back(memory.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Tty::Throttle::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Tty::Throttle::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Tty::Throttle::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "process-rate")
{
process_rate = value;
process_rate.value_namespace = name_space;
process_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "memory")
{
memory = value;
memory.value_namespace = name_space;
memory.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Tty::Throttle::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "process-rate")
{
process_rate.yfilter = yfilter;
}
if(value_path == "memory")
{
memory.yfilter = yfilter;
}
}
bool XrXml::Agent::Tty::Throttle::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "process-rate" || name == "memory")
return true;
return false;
}
XrXml::Agent::Ssl::Ssl()
:
iteration_size{YType::uint32, "iteration-size"},
enable{YType::empty, "enable"},
streaming_size{YType::uint32, "streaming-size"}
,
session(std::make_shared<XrXml::Agent::Ssl::Session>())
, throttle(std::make_shared<XrXml::Agent::Ssl::Throttle>())
, vrfs(std::make_shared<XrXml::Agent::Ssl::Vrfs>())
{
session->parent = this;
throttle->parent = this;
vrfs->parent = this;
yang_name = "ssl"; yang_parent_name = "agent"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Ssl::~Ssl()
{
}
bool XrXml::Agent::Ssl::has_data() const
{
if (is_presence_container) return true;
return iteration_size.is_set
|| enable.is_set
|| streaming_size.is_set
|| (session != nullptr && session->has_data())
|| (throttle != nullptr && throttle->has_data())
|| (vrfs != nullptr && vrfs->has_data());
}
bool XrXml::Agent::Ssl::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(iteration_size.yfilter)
|| ydk::is_set(enable.yfilter)
|| ydk::is_set(streaming_size.yfilter)
|| (session != nullptr && session->has_operation())
|| (throttle != nullptr && throttle->has_operation())
|| (vrfs != nullptr && vrfs->has_operation());
}
std::string XrXml::Agent::Ssl::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Ssl::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ssl";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Ssl::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (iteration_size.is_set || is_set(iteration_size.yfilter)) leaf_name_data.push_back(iteration_size.get_name_leafdata());
if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata());
if (streaming_size.is_set || is_set(streaming_size.yfilter)) leaf_name_data.push_back(streaming_size.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Ssl::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "session")
{
if(session == nullptr)
{
session = std::make_shared<XrXml::Agent::Ssl::Session>();
}
return session;
}
if(child_yang_name == "throttle")
{
if(throttle == nullptr)
{
throttle = std::make_shared<XrXml::Agent::Ssl::Throttle>();
}
return throttle;
}
if(child_yang_name == "vrfs")
{
if(vrfs == nullptr)
{
vrfs = std::make_shared<XrXml::Agent::Ssl::Vrfs>();
}
return vrfs;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Ssl::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(session != nullptr)
{
_children["session"] = session;
}
if(throttle != nullptr)
{
_children["throttle"] = throttle;
}
if(vrfs != nullptr)
{
_children["vrfs"] = vrfs;
}
return _children;
}
void XrXml::Agent::Ssl::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "iteration-size")
{
iteration_size = value;
iteration_size.value_namespace = name_space;
iteration_size.value_namespace_prefix = name_space_prefix;
}
if(value_path == "enable")
{
enable = value;
enable.value_namespace = name_space;
enable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "streaming-size")
{
streaming_size = value;
streaming_size.value_namespace = name_space;
streaming_size.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Ssl::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "iteration-size")
{
iteration_size.yfilter = yfilter;
}
if(value_path == "enable")
{
enable.yfilter = yfilter;
}
if(value_path == "streaming-size")
{
streaming_size.yfilter = yfilter;
}
}
bool XrXml::Agent::Ssl::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "session" || name == "throttle" || name == "vrfs" || name == "iteration-size" || name == "enable" || name == "streaming-size")
return true;
return false;
}
XrXml::Agent::Ssl::Session::Session()
:
timeout{YType::uint32, "timeout"}
{
yang_name = "session"; yang_parent_name = "ssl"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Ssl::Session::~Session()
{
}
bool XrXml::Agent::Ssl::Session::has_data() const
{
if (is_presence_container) return true;
return timeout.is_set;
}
bool XrXml::Agent::Ssl::Session::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(timeout.yfilter);
}
std::string XrXml::Agent::Ssl::Session::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/ssl/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Ssl::Session::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "session";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Ssl::Session::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Ssl::Session::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Ssl::Session::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Ssl::Session::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "timeout")
{
timeout = value;
timeout.value_namespace = name_space;
timeout.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Ssl::Session::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "timeout")
{
timeout.yfilter = yfilter;
}
}
bool XrXml::Agent::Ssl::Session::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "timeout")
return true;
return false;
}
XrXml::Agent::Ssl::Throttle::Throttle()
:
process_rate{YType::uint32, "process-rate"},
memory{YType::uint32, "memory"}
{
yang_name = "throttle"; yang_parent_name = "ssl"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Ssl::Throttle::~Throttle()
{
}
bool XrXml::Agent::Ssl::Throttle::has_data() const
{
if (is_presence_container) return true;
return process_rate.is_set
|| memory.is_set;
}
bool XrXml::Agent::Ssl::Throttle::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(process_rate.yfilter)
|| ydk::is_set(memory.yfilter);
}
std::string XrXml::Agent::Ssl::Throttle::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/ssl/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Ssl::Throttle::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "throttle";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Ssl::Throttle::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (process_rate.is_set || is_set(process_rate.yfilter)) leaf_name_data.push_back(process_rate.get_name_leafdata());
if (memory.is_set || is_set(memory.yfilter)) leaf_name_data.push_back(memory.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Ssl::Throttle::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Ssl::Throttle::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Ssl::Throttle::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "process-rate")
{
process_rate = value;
process_rate.value_namespace = name_space;
process_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "memory")
{
memory = value;
memory.value_namespace = name_space;
memory.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Ssl::Throttle::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "process-rate")
{
process_rate.yfilter = yfilter;
}
if(value_path == "memory")
{
memory.yfilter = yfilter;
}
}
bool XrXml::Agent::Ssl::Throttle::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "process-rate" || name == "memory")
return true;
return false;
}
XrXml::Agent::Ssl::Vrfs::Vrfs()
:
vrf(this, {"vrf_name"})
{
yang_name = "vrfs"; yang_parent_name = "ssl"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Ssl::Vrfs::~Vrfs()
{
}
bool XrXml::Agent::Ssl::Vrfs::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_data())
return true;
}
return false;
}
bool XrXml::Agent::Ssl::Vrfs::has_operation() const
{
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string XrXml::Agent::Ssl::Vrfs::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/ssl/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Ssl::Vrfs::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrfs";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Ssl::Vrfs::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Ssl::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "vrf")
{
auto ent_ = std::make_shared<XrXml::Agent::Ssl::Vrfs::Vrf>();
ent_->parent = this;
vrf.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Ssl::Vrfs::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : vrf.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void XrXml::Agent::Ssl::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void XrXml::Agent::Ssl::Vrfs::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool XrXml::Agent::Ssl::Vrfs::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf")
return true;
return false;
}
XrXml::Agent::Ssl::Vrfs::Vrf::Vrf()
:
vrf_name{YType::str, "vrf-name"},
ipv6_access_list{YType::str, "ipv6-access-list"},
ipv4_access_list{YType::str, "ipv4-access-list"},
access_list{YType::str, "access-list"},
shutdown{YType::empty, "shutdown"}
{
yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = false;
}
XrXml::Agent::Ssl::Vrfs::Vrf::~Vrf()
{
}
bool XrXml::Agent::Ssl::Vrfs::Vrf::has_data() const
{
if (is_presence_container) return true;
return vrf_name.is_set
|| ipv6_access_list.is_set
|| ipv4_access_list.is_set
|| access_list.is_set
|| shutdown.is_set;
}
bool XrXml::Agent::Ssl::Vrfs::Vrf::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(vrf_name.yfilter)
|| ydk::is_set(ipv6_access_list.yfilter)
|| ydk::is_set(ipv4_access_list.yfilter)
|| ydk::is_set(access_list.yfilter)
|| ydk::is_set(shutdown.yfilter);
}
std::string XrXml::Agent::Ssl::Vrfs::Vrf::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:xr-xml/agent/ssl/vrfs/" << get_segment_path();
return path_buffer.str();
}
std::string XrXml::Agent::Ssl::Vrfs::Vrf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrf";
ADD_KEY_TOKEN(vrf_name, "vrf-name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > XrXml::Agent::Ssl::Vrfs::Vrf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata());
if (ipv6_access_list.is_set || is_set(ipv6_access_list.yfilter)) leaf_name_data.push_back(ipv6_access_list.get_name_leafdata());
if (ipv4_access_list.is_set || is_set(ipv4_access_list.yfilter)) leaf_name_data.push_back(ipv4_access_list.get_name_leafdata());
if (access_list.is_set || is_set(access_list.yfilter)) leaf_name_data.push_back(access_list.get_name_leafdata());
if (shutdown.is_set || is_set(shutdown.yfilter)) leaf_name_data.push_back(shutdown.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> XrXml::Agent::Ssl::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> XrXml::Agent::Ssl::Vrfs::Vrf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void XrXml::Agent::Ssl::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "vrf-name")
{
vrf_name = value;
vrf_name.value_namespace = name_space;
vrf_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv6-access-list")
{
ipv6_access_list = value;
ipv6_access_list.value_namespace = name_space;
ipv6_access_list.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ipv4-access-list")
{
ipv4_access_list = value;
ipv4_access_list.value_namespace = name_space;
ipv4_access_list.value_namespace_prefix = name_space_prefix;
}
if(value_path == "access-list")
{
access_list = value;
access_list.value_namespace = name_space;
access_list.value_namespace_prefix = name_space_prefix;
}
if(value_path == "shutdown")
{
shutdown = value;
shutdown.value_namespace = name_space;
shutdown.value_namespace_prefix = name_space_prefix;
}
}
void XrXml::Agent::Ssl::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "vrf-name")
{
vrf_name.yfilter = yfilter;
}
if(value_path == "ipv6-access-list")
{
ipv6_access_list.yfilter = yfilter;
}
if(value_path == "ipv4-access-list")
{
ipv4_access_list.yfilter = yfilter;
}
if(value_path == "access-list")
{
access_list.yfilter = yfilter;
}
if(value_path == "shutdown")
{
shutdown.yfilter = yfilter;
}
}
bool XrXml::Agent::Ssl::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf-name" || name == "ipv6-access-list" || name == "ipv4-access-list" || name == "access-list" || name == "shutdown")
return true;
return false;
}
Netconf::Netconf()
:
agent(std::make_shared<Netconf::Agent>())
{
agent->parent = this;
yang_name = "netconf"; yang_parent_name = "Cisco-IOS-XR-man-xml-ttyagent-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
Netconf::~Netconf()
{
}
bool Netconf::has_data() const
{
if (is_presence_container) return true;
return (agent != nullptr && agent->has_data());
}
bool Netconf::has_operation() const
{
return is_set(yfilter)
|| (agent != nullptr && agent->has_operation());
}
std::string Netconf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:netconf";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Netconf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Netconf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "agent")
{
if(agent == nullptr)
{
agent = std::make_shared<Netconf::Agent>();
}
return agent;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Netconf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(agent != nullptr)
{
_children["agent"] = agent;
}
return _children;
}
void Netconf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Netconf::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Netconf::clone_ptr() const
{
return std::make_shared<Netconf>();
}
std::string Netconf::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string Netconf::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function Netconf::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Netconf::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool Netconf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "agent")
return true;
return false;
}
Netconf::Agent::Agent()
:
tty(std::make_shared<Netconf::Agent::Tty>())
{
tty->parent = this;
yang_name = "agent"; yang_parent_name = "netconf"; is_top_level_class = false; has_list_ancestor = false;
}
Netconf::Agent::~Agent()
{
}
bool Netconf::Agent::has_data() const
{
if (is_presence_container) return true;
return (tty != nullptr && tty->has_data());
}
bool Netconf::Agent::has_operation() const
{
return is_set(yfilter)
|| (tty != nullptr && tty->has_operation());
}
std::string Netconf::Agent::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:netconf/" << get_segment_path();
return path_buffer.str();
}
std::string Netconf::Agent::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "agent";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Netconf::Agent::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Netconf::Agent::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "tty")
{
if(tty == nullptr)
{
tty = std::make_shared<Netconf::Agent::Tty>();
}
return tty;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Netconf::Agent::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(tty != nullptr)
{
_children["tty"] = tty;
}
return _children;
}
void Netconf::Agent::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Netconf::Agent::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Netconf::Agent::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "tty")
return true;
return false;
}
Netconf::Agent::Tty::Tty()
:
enable{YType::empty, "enable"}
,
throttle(std::make_shared<Netconf::Agent::Tty::Throttle>())
, session(std::make_shared<Netconf::Agent::Tty::Session>())
{
throttle->parent = this;
session->parent = this;
yang_name = "tty"; yang_parent_name = "agent"; is_top_level_class = false; has_list_ancestor = false;
}
Netconf::Agent::Tty::~Tty()
{
}
bool Netconf::Agent::Tty::has_data() const
{
if (is_presence_container) return true;
return enable.is_set
|| (throttle != nullptr && throttle->has_data())
|| (session != nullptr && session->has_data());
}
bool Netconf::Agent::Tty::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(enable.yfilter)
|| (throttle != nullptr && throttle->has_operation())
|| (session != nullptr && session->has_operation());
}
std::string Netconf::Agent::Tty::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:netconf/agent/" << get_segment_path();
return path_buffer.str();
}
std::string Netconf::Agent::Tty::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "tty";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Netconf::Agent::Tty::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Netconf::Agent::Tty::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "throttle")
{
if(throttle == nullptr)
{
throttle = std::make_shared<Netconf::Agent::Tty::Throttle>();
}
return throttle;
}
if(child_yang_name == "session")
{
if(session == nullptr)
{
session = std::make_shared<Netconf::Agent::Tty::Session>();
}
return session;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Netconf::Agent::Tty::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(throttle != nullptr)
{
_children["throttle"] = throttle;
}
if(session != nullptr)
{
_children["session"] = session;
}
return _children;
}
void Netconf::Agent::Tty::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "enable")
{
enable = value;
enable.value_namespace = name_space;
enable.value_namespace_prefix = name_space_prefix;
}
}
void Netconf::Agent::Tty::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "enable")
{
enable.yfilter = yfilter;
}
}
bool Netconf::Agent::Tty::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "throttle" || name == "session" || name == "enable")
return true;
return false;
}
Netconf::Agent::Tty::Throttle::Throttle()
:
memory{YType::uint32, "memory"},
offload_memory{YType::uint32, "offload-memory"},
process_rate{YType::uint32, "process-rate"}
{
yang_name = "throttle"; yang_parent_name = "tty"; is_top_level_class = false; has_list_ancestor = false;
}
Netconf::Agent::Tty::Throttle::~Throttle()
{
}
bool Netconf::Agent::Tty::Throttle::has_data() const
{
if (is_presence_container) return true;
return memory.is_set
|| offload_memory.is_set
|| process_rate.is_set;
}
bool Netconf::Agent::Tty::Throttle::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(memory.yfilter)
|| ydk::is_set(offload_memory.yfilter)
|| ydk::is_set(process_rate.yfilter);
}
std::string Netconf::Agent::Tty::Throttle::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:netconf/agent/tty/" << get_segment_path();
return path_buffer.str();
}
std::string Netconf::Agent::Tty::Throttle::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "throttle";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Netconf::Agent::Tty::Throttle::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (memory.is_set || is_set(memory.yfilter)) leaf_name_data.push_back(memory.get_name_leafdata());
if (offload_memory.is_set || is_set(offload_memory.yfilter)) leaf_name_data.push_back(offload_memory.get_name_leafdata());
if (process_rate.is_set || is_set(process_rate.yfilter)) leaf_name_data.push_back(process_rate.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Netconf::Agent::Tty::Throttle::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Netconf::Agent::Tty::Throttle::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Netconf::Agent::Tty::Throttle::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "memory")
{
memory = value;
memory.value_namespace = name_space;
memory.value_namespace_prefix = name_space_prefix;
}
if(value_path == "offload-memory")
{
offload_memory = value;
offload_memory.value_namespace = name_space;
offload_memory.value_namespace_prefix = name_space_prefix;
}
if(value_path == "process-rate")
{
process_rate = value;
process_rate.value_namespace = name_space;
process_rate.value_namespace_prefix = name_space_prefix;
}
}
void Netconf::Agent::Tty::Throttle::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "memory")
{
memory.yfilter = yfilter;
}
if(value_path == "offload-memory")
{
offload_memory.yfilter = yfilter;
}
if(value_path == "process-rate")
{
process_rate.yfilter = yfilter;
}
}
bool Netconf::Agent::Tty::Throttle::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "memory" || name == "offload-memory" || name == "process-rate")
return true;
return false;
}
Netconf::Agent::Tty::Session::Session()
:
timeout{YType::uint32, "timeout"}
{
yang_name = "session"; yang_parent_name = "tty"; is_top_level_class = false; has_list_ancestor = false;
}
Netconf::Agent::Tty::Session::~Session()
{
}
bool Netconf::Agent::Tty::Session::has_data() const
{
if (is_presence_container) return true;
return timeout.is_set;
}
bool Netconf::Agent::Tty::Session::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(timeout.yfilter);
}
std::string Netconf::Agent::Tty::Session::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-man-xml-ttyagent-cfg:netconf/agent/tty/" << get_segment_path();
return path_buffer.str();
}
std::string Netconf::Agent::Tty::Session::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "session";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Netconf::Agent::Tty::Session::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Netconf::Agent::Tty::Session::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Netconf::Agent::Tty::Session::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Netconf::Agent::Tty::Session::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "timeout")
{
timeout = value;
timeout.value_namespace = name_space;
timeout.value_namespace_prefix = name_space_prefix;
}
}
void Netconf::Agent::Tty::Session::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "timeout")
{
timeout.yfilter = yfilter;
}
}
bool Netconf::Agent::Tty::Session::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "timeout")
return true;
return false;
}
}
}
| 27.460708 | 192 | 0.667998 | [
"vector"
] |
a865a6e38b7a788393fdc067320e76d38624559a | 27,225 | cc | C++ | src/RefSetupDetectorConstruction.cc | l-althueser/XeSim | 972ea62a35db7c80c6e4b3349987e31945651399 | [
"BSD-3-Clause"
] | null | null | null | src/RefSetupDetectorConstruction.cc | l-althueser/XeSim | 972ea62a35db7c80c6e4b3349987e31945651399 | [
"BSD-3-Clause"
] | null | null | null | src/RefSetupDetectorConstruction.cc | l-althueser/XeSim | 972ea62a35db7c80c6e4b3349987e31945651399 | [
"BSD-3-Clause"
] | null | null | null | #include <G4Material.hh>
#include <G4NistManager.hh>
#include <G4Box.hh>
#include <G4Tubs.hh>
#include <G4Sphere.hh>
#include <G4Orb.hh>
#include <G4Polyhedra.hh>
#include <G4Trd.hh>
#include <G4Cons.hh>
#include <G4UnionSolid.hh>
#include <G4IntersectionSolid.hh>
#include <G4SubtractionSolid.hh>
#include <G4LogicalVolume.hh>
#include <G4PVPlacement.hh>
#include <G4PVParameterised.hh>
#include <G4OpBoundaryProcess.hh>
#include <G4SDManager.hh>
#include <G4ThreeVector.hh>
#include <G4RotationMatrix.hh>
#include <G4VisAttributes.hh>
#include <G4Colour.hh>
#include <G4PhysicalVolumeStore.hh>
#include <G4VPhysicalVolume.hh>
#include <G4GeometryManager.hh>
#include <G4UnitsTable.hh>
#include <G4SystemOfUnits.hh>
#include <G4UserLimits.hh>
#include <G4RunManager.hh>
#include <globals.hh>
#include <vector>
#include <numeric>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <cassert>
using std::vector;
using std::stringstream;
using std::max;
#include "XeSimLXeSensitiveDetector.hh"
#include "XeSimPhotoDetSensitiveDetector.hh"
#include "RefSetupDetectorConstruction.hh"
//#include "templateDetectorMessenger.hh"
map<G4String, G4double> RefSetupDetectorConstruction::m_hGeometryParameters;
RefSetupDetectorConstruction::RefSetupDetectorConstruction() {
// needs to be set for the AnalysisManager
m_hGeometryParameters["NbPhotoDets"] = 1;
//m_pDetectorMessenger = new templateDetectorMessenger(this);
}
RefSetupDetectorConstruction::~RefSetupDetectorConstruction() {
//delete m_pDetectorMessenger;
}
G4VPhysicalVolume* RefSetupDetectorConstruction::Construct() {
DefineMaterials();
DefineGeometryParameters();
ConstructLaboratory();
ConstructDetector();
return m_pLabPhysicalVolume;
}
G4double RefSetupDetectorConstruction::GetGeometryParameter(const char *szParameter) {
return m_hGeometryParameters[szParameter];
}
void RefSetupDetectorConstruction::DefineMaterials() {
G4Element *Xe = new G4Element("Xenon", "Xe", 54., 131.293*g/mole);
G4Element *H = new G4Element("Hydrogen", "H", 1., 1.0079*g/mole);
G4Element *C = new G4Element("Carbon", "C", 6., 12.011*g/mole);
G4Element *N = new G4Element("Nitrogen", "N", 7., 14.007*g/mole);
G4Element *O = new G4Element("Oxygen", "O", 8., 15.999*g/mole);
G4Element *F = new G4Element("Fluorine", "F", 9., 18.998*g/mole);
G4Element *Al = new G4Element("Aluminium", "Al", 13., 26.982*g/mole);
G4Element *Si = new G4Element("Silicon", "Si", 14., 28.086*g/mole);
G4Element *Cr = new G4Element("Chromium", "Cr", 24., 51.996*g/mole);
G4Element *Mn = new G4Element("Manganese", "Mn", 25., 54.938*g/mole);
G4Element *Fe = new G4Element("Iron", "Fe", 26., 55.85*g/mole);
G4Element *Ni = new G4Element("Nickel", "Ni", 28., 58.693*g/mole);
G4Element *Cu = new G4Element("Copper", "Cu", 29., 63.546*g/mole);
G4Element *Pb = new G4Element("Lead", "Pb", 82., 207.2*g/mole);
G4Element *Mo = new G4Element("Molybdenum","Mo", 42., 95.96*g/mole);
G4NistManager* pNistManager = G4NistManager::Instance();
pNistManager->FindOrBuildMaterial("G4_AIR");
const G4int iNbEntries = 3;
G4Material *Vacuum = new G4Material("Vacuum", 1.e-20*g/cm3, 2, kStateGas);
Vacuum->AddElement(N, 0.755);
Vacuum->AddElement(O, 0.245);
G4MaterialPropertiesTable *pVacuumPropertiesTable = new G4MaterialPropertiesTable();
G4double pdVacuumPhotonMomentum[] = {6.91*eV, 6.98*eV, 7.05*eV}; //178nm
G4double pdVacuumAbsorbtionLength[] = {300.*cm, 300.*cm, 300.*cm};
G4double pdVacuumRefractiveIndex[] = {1., 1., 1.};
pVacuumPropertiesTable->AddProperty("RINDEX", pdVacuumPhotonMomentum, pdVacuumRefractiveIndex, iNbEntries);
pVacuumPropertiesTable->AddProperty("ABSLENGTH", pdVacuumPhotonMomentum, pdVacuumAbsorbtionLength, iNbEntries);
Vacuum->SetMaterialPropertiesTable(pVacuumPropertiesTable);
//-------------------------------- liquid xenon ---------------------------------
G4Material *LXe = new G4Material("LXe", 2.9172*g/cm3, 1, kStateLiquid, 168.15*kelvin, 1.5*atmosphere);
LXe->AddElement(Xe, 1);
G4double pdLXePhotonMomentum[] = {6.91*eV, 6.98*eV, 7.05*eV}; //178nm
G4double pdLXeScintillation[] = {0.1, 1.0, 0.1};
G4double pdLXeRefractiveIndex[] = {1.63, 1.61, 1.58};
//measured at some point in the past:
G4double pdLXeAbsorbtionLength[] = {100.*cm, 100.*cm, 100.*cm};
G4double pdLXeScatteringLength[] = {30.*cm, 30.*cm, 30.*cm};
G4MaterialPropertiesTable *pLXePropertiesTable = new G4MaterialPropertiesTable();
pLXePropertiesTable->AddProperty("FASTCOMPONENT", pdLXePhotonMomentum, pdLXeScintillation, iNbEntries);
pLXePropertiesTable->AddProperty("SLOWCOMPONENT", pdLXePhotonMomentum, pdLXeScintillation, iNbEntries);
pLXePropertiesTable->AddProperty("RINDEX", pdLXePhotonMomentum, pdLXeRefractiveIndex, iNbEntries);
pLXePropertiesTable->AddProperty("ABSLENGTH", pdLXePhotonMomentum, pdLXeAbsorbtionLength, iNbEntries);
pLXePropertiesTable->AddProperty("RAYLEIGH", pdLXePhotonMomentum, pdLXeScatteringLength, iNbEntries);
pLXePropertiesTable->AddConstProperty("SCINTILLATIONYIELD", 0./(21.6*eV));
pLXePropertiesTable->AddConstProperty("RESOLUTIONSCALE", 0);
pLXePropertiesTable->AddConstProperty("FASTTIMECONSTANT", 3.*ns);
pLXePropertiesTable->AddConstProperty("SLOWTIMECONSTANT", 27.*ns);
pLXePropertiesTable->AddConstProperty("YIELDRATIO", 1.0);//ratio btw fast time constant and slow time constant
LXe->SetMaterialPropertiesTable(pLXePropertiesTable);
//-------------------------------- gaseous xenon --------------------------------
G4Material *GXe = new G4Material("GXe", 0.005887*g/cm3, 1, kStateGas, 173.15*kelvin, 1.5*atmosphere);
GXe->AddElement(Xe, 1);
G4double pdGXePhotonMomentum[] = {6.91*eV, 6.98*eV, 7.05*eV};
G4double pdGXeScintillation[] = {0.1, 1.0, 0.1};
G4double pdGXeRefractiveIndex[] = {1.00, 1.00, 1.00};
G4double pdGXeAbsorbtionLength[] = {100*m, 100*m, 100*m};
G4double pdGXeScatteringLength[] = {100*m, 100*m, 100*m};
G4MaterialPropertiesTable *pGXePropertiesTable = new G4MaterialPropertiesTable();
pGXePropertiesTable->AddProperty("FASTCOMPONENT", pdGXePhotonMomentum, pdGXeScintillation, iNbEntries);
pGXePropertiesTable->AddProperty("SLOWCOMPONENT", pdGXePhotonMomentum, pdGXeScintillation, iNbEntries);
pGXePropertiesTable->AddProperty("RINDEX", pdGXePhotonMomentum, pdGXeRefractiveIndex, iNbEntries);
pGXePropertiesTable->AddProperty("ABSLENGTH", pdGXePhotonMomentum, pdGXeAbsorbtionLength, iNbEntries);
pGXePropertiesTable->AddProperty("RAYLEIGH", pdGXePhotonMomentum, pdGXeScatteringLength, iNbEntries);
pGXePropertiesTable->AddConstProperty("SCINTILLATIONYIELD", 0./(21.6*eV));
pGXePropertiesTable->AddConstProperty("RESOLUTIONSCALE", 0);
pGXePropertiesTable->AddConstProperty("FASTTIMECONSTANT", 3.*ns);
pGXePropertiesTable->AddConstProperty("SLOWTIMECONSTANT", 27.*ns);
pGXePropertiesTable->AddConstProperty("YIELDRATIO", 1.0);
GXe->SetMaterialPropertiesTable(pGXePropertiesTable);
//----------------------------------- quartz ------------------------------------
// ref: http://www.sciner.com/Opticsland/FS.htm
G4Material *Quartz = new G4Material("Quartz", 2.201*g/cm3, 2, kStateSolid, 168.15*kelvin, 1.5*atmosphere);
Quartz->AddElement(Si, 1);
Quartz->AddElement(O, 2);
G4double pdQuartzPhotonMomentum[] = {6.91*eV, 6.98*eV, 7.05*eV};
G4double pdQuartzRefractiveIndex[] = {1.50, 1.56, 1.60};
G4double pdQuartzAbsorbtionLength[] = {30*m, 30*m, 30*m};
G4MaterialPropertiesTable *pQuartzPropertiesTable = new G4MaterialPropertiesTable();
pQuartzPropertiesTable->AddProperty("RINDEX", pdQuartzPhotonMomentum, pdQuartzRefractiveIndex, iNbEntries);
pQuartzPropertiesTable->AddProperty("ABSLENGTH", pdQuartzPhotonMomentum, pdQuartzAbsorbtionLength, iNbEntries);
Quartz->SetMaterialPropertiesTable(pQuartzPropertiesTable);
// //------------------------------- stainless steel -------------------------------
G4Material *SS304LSteel = new G4Material("SS304LSteel", 8.00*g/cm3, 5, kStateSolid);
SS304LSteel->AddElement(Fe, 0.65);
SS304LSteel->AddElement(Cr, 0.20);
SS304LSteel->AddElement(Ni, 0.12);
SS304LSteel->AddElement(Mn, 0.02);
SS304LSteel->AddElement(Si, 0.01);
G4double pdSteelPhotonMomentum[] = {6.91*eV, 6.98*eV, 7.05*eV};
G4double pdSteelReflectivity[] = {0.05, 0.05, 0.05}; //{0.15, 0.2, 0.15};
G4MaterialPropertiesTable *pSteelPropertiesTable = new G4MaterialPropertiesTable();
pSteelPropertiesTable->AddProperty("REFLECTIVITY", pdSteelPhotonMomentum, pdSteelReflectivity, iNbEntries);
SS304LSteel->SetMaterialPropertiesTable(pSteelPropertiesTable);
//------------------------------- stainless steel -------------------------------
G4Material *SS316LSteel = new G4Material("SS316LSteel", 8.00*g/cm3, 6, kStateSolid);
SS316LSteel->AddElement(Fe, 0.682);
SS316LSteel->AddElement(Cr, 0.172);
SS316LSteel->AddElement(Ni, 0.109);
SS316LSteel->AddElement(Mn, 0.016);
SS316LSteel->AddElement(C, 0.0002);
SS316LSteel->AddElement(Mo, 0.021);
//As defined above:
//G4double pdSteelPhotonMomentum[] = {6.91*eV, 6.98*eV, 7.05*eV};
//G4double pdSteelReflectivity[] = {0.15, 0.2, 0.15};
//G4MaterialPropertiesTable *pSteelPropertiesTable = new G4MaterialPropertiesTable();
pSteelPropertiesTable->AddProperty("REFLECTIVITY", pdSteelPhotonMomentum, pdSteelReflectivity, iNbEntries);
SS316LSteel->SetMaterialPropertiesTable(pSteelPropertiesTable);
//---------------------------------- aluminium ----------------------------------
pNistManager->FindOrBuildMaterial("G4_Al");
//---------------------------- photocathode aluminium ---------------------------
G4Material *PhotoCathodeAluminium = new G4Material("PhotoCathodeAluminium", 8.00*g/cm3, 1, kStateSolid);
PhotoCathodeAluminium->AddElement(Al, 1);
G4double pdPhotoCathodePhotonMomentum[] = {1.*eV, 6.91*eV, 6.98*eV, 7.05*eV};
G4double pdPhotoCathodeRefractiveIndex[] = {1.50, 1.50, 1.56, 1.60};
G4double pdPhotoCathodeAbsorbtionLength[] = {1.*nm, 1.*nm, 1.*nm, 1.*nm};
G4MaterialPropertiesTable *pPhotoCathodePropertiesTable = new G4MaterialPropertiesTable();
pPhotoCathodePropertiesTable->AddProperty("RINDEX", pdPhotoCathodePhotonMomentum, pdPhotoCathodeRefractiveIndex, iNbEntries);
pPhotoCathodePropertiesTable->AddProperty("ABSLENGTH", pdPhotoCathodePhotonMomentum, pdPhotoCathodeAbsorbtionLength, iNbEntries);
PhotoCathodeAluminium->SetMaterialPropertiesTable(pPhotoCathodePropertiesTable);
//------------------------------------ PTFE -----------------------------------
G4Material* PTFE = new G4Material("LXePTFE", 2.2*g/cm3, 2, kStateSolid);
PTFE->AddElement(C, 0.240183);
PTFE->AddElement(F, 0.759817);
G4double pdPTFEPhotonMomentum[] = {6.91*eV, 6.98*eV, 7.05*eV};
G4double pdPTFERefractiveIndex[] = {1.63, 1.61, 1.58};
G4double pdPTFEReflectivity[] = {0.95, 0.95, 0.95};
G4double pdPTFESpecularLobe[] = {0.01, 0.01, 0.01};
G4double pdPTFESpecularSpike[] = {0.01, 0.01, 0.01};
G4double pdPTFEBackscatter[] = {0.01, 0.01, 0.01};
G4double pdPTFEEfficiency[] = {1.0, 1.0, 1.0};
G4MaterialPropertiesTable *pPTFEPropertiesTable = new G4MaterialPropertiesTable();
pPTFEPropertiesTable->AddProperty("RINDEX", pdPTFEPhotonMomentum, pdPTFERefractiveIndex, iNbEntries);
pPTFEPropertiesTable->AddProperty("REFLECTIVITY", pdPTFEPhotonMomentum, pdPTFEReflectivity, iNbEntries);
pPTFEPropertiesTable->AddProperty("SPECULARLOBECONSTANT", pdPTFEPhotonMomentum, pdPTFESpecularLobe, iNbEntries);
pPTFEPropertiesTable->AddProperty("SPECULARSPIKECONSTANT", pdPTFEPhotonMomentum, pdPTFESpecularSpike, iNbEntries);
pPTFEPropertiesTable->AddProperty("BACKSCATTERCONSTANT", pdPTFEPhotonMomentum, pdPTFEBackscatter, iNbEntries);
pPTFEPropertiesTable->AddProperty("EFFICIENCY", pdPTFEPhotonMomentum, pdPTFEEfficiency, iNbEntries);
PTFE->SetMaterialPropertiesTable(pPTFEPropertiesTable);
//------------------------------------ GXe PTFE -----------------------------------
G4Material* GXePTFE = new G4Material("GXePTFE", 2.2*g/cm3, 2, kStateSolid);
GXePTFE->AddElement(C, 0.240183);
GXePTFE->AddElement(F, 0.759817);
G4double pdGXePTFEPhotonMomentum[iNbEntries] = {6.91*eV, 6.98*eV, 7.05*eV};
G4double pdGXePTFERefractiveIndex[iNbEntries] = {1.63, 1.61, 1.58};
G4double pdGXePTFEReflectivity[iNbEntries] = {0.95, 0.95, 0.95};
G4double pdGXePTFESpecularLobe[iNbEntries] = {0.01, 0.01, 0.01};
G4double pdGXePTFESpecularSpike[iNbEntries] = {0.01, 0.01, 0.01};
G4double pdGXePTFEBackscatter[iNbEntries] = {0.01, 0.01, 0.01};
G4double pdGXePTFEEfficiency[iNbEntries] = {1.0, 1.0, 1.0};
G4MaterialPropertiesTable *pGXePTFEPropertiesTable = new G4MaterialPropertiesTable();
pGXePTFEPropertiesTable->AddProperty("RINDEX", pdGXePTFEPhotonMomentum, pdGXePTFERefractiveIndex, iNbEntries);
pGXePTFEPropertiesTable->AddProperty("REFLECTIVITY", pdGXePTFEPhotonMomentum, pdGXePTFEReflectivity, iNbEntries);
pGXePTFEPropertiesTable->AddProperty("SPECULARLOBECONSTANT", pdGXePTFEPhotonMomentum, pdGXePTFESpecularLobe, iNbEntries);
pGXePTFEPropertiesTable->AddProperty("SPECULARSPIKECONSTANT", pdGXePTFEPhotonMomentum, pdGXePTFESpecularSpike, iNbEntries);
pGXePTFEPropertiesTable->AddProperty("BACKSCATTERCONSTANT", pdGXePTFEPhotonMomentum, pdGXePTFEBackscatter, iNbEntries);
pGXePTFEPropertiesTable->AddProperty("EFFICIENCY", pdGXePTFEPhotonMomentum, pdGXePTFEEfficiency, iNbEntries);
GXePTFE->SetMaterialPropertiesTable(pGXePTFEPropertiesTable);
}
void RefSetupDetectorConstruction::DefineGeometryParameters() {
m_hGeometryParameters["MainVacuumChamberOuterRadius"] = 330.00*mm;
m_hGeometryParameters["MainVacuumChamberInnerRadius"] = 325.00*mm;
m_hGeometryParameters["MainVacuumChamberHalfZ"] = 150.00*mm;
m_hGeometryParameters["MainVacuumChamberFlangeHalfZ"] = 2.50*mm;
m_hGeometryParameters["CenterToPMTSlit"] = 40.50*mm;
m_hGeometryParameters["CenterToPMTCathode"] = 69.25*mm;
// closer to PMT, screw holes for PTFE sample holder
m_hGeometryParameters["CenterFlangeToCenterSS"] = 6.25*mm;
m_hGeometryParameters["CenterFlangeToPTFESamples"] = 16.25*mm;
m_hGeometryParameters["HolderFlangeRadius"] = 35.00*mm;
m_hGeometryParameters["HolderFlangeHeight"] = 12.00*mm;
m_hGeometryParameters["HolderFlangeQuartzTubeInnerRadius"] = 39.00*mm;
m_hGeometryParameters["HolderFlangeQuartzTubeOuterRadius"] = 43.00*mm;
m_hGeometryParameters["PTFEHolderHalfX"] = 0.5*50.00*mm;
m_hGeometryParameters["PTFEHolderHalfY"] = 0.5*27.00*mm;
m_hGeometryParameters["PTFEHolderHalfZ"] = 0.5*9.00*mm;
m_hGeometryParameters["PTFESampleHalfZ"] = 0.5*7.00*mm;
m_hGeometryParameters["PTFESampleHalfX"] = 0.5*10.00*mm;
m_hGeometryParameters["PTFESampleCutHalfX"] = 0.5*5.00*mm;
m_hGeometryParameters["PTFESampleHalfY"] = 0.5*25.00*mm;
m_hGeometryParameters["PTFESampleCutHalfY"] = 0.5*10.00*mm;
m_hGeometryParameters["PTFESampleHoleHalfX"] = 0.5*4.00*mm;
m_hGeometryParameters["PMTScreenHeight"] = 100.00*mm;
}
void RefSetupDetectorConstruction::ConstructLaboratory() {
const G4double dLabHalfX = 1.5*m;
const G4double dLabHalfY = 1.5*m;
const G4double dLabHalfZ = 1.5*m;
G4Box *pLabBox = new G4Box("LabBox", dLabHalfX, dLabHalfY, dLabHalfZ);
G4Material *Air = G4Material::GetMaterial("G4_AIR");
m_pLabLogicalVolume = new G4LogicalVolume(pLabBox, Air, "LabLogicalVolume", 0, 0, 0);
G4Colour LabColor(1.0,0.0,0.0,1.0);
G4VisAttributes *pLabVisAtt = new G4VisAttributes(LabColor);
pLabVisAtt->SetVisibility(false);
m_pLabLogicalVolume->SetVisAttributes(pLabVisAtt);
m_pLabPhysicalVolume = new G4PVPlacement(0, G4ThreeVector(), m_pLabLogicalVolume, "Lab", 0, false, 0);
}
void RefSetupDetectorConstruction::ConstructDetector() {
G4SDManager *pSDManager = G4SDManager::GetSDMpointer();
G4Material *Vacuum = G4Material::GetMaterial("Vacuum");
G4Material *SS316LSteel = G4Material::GetMaterial("SS316LSteel");
G4Material *LXe = G4Material::GetMaterial("LXe");
G4Material *GXe = G4Material::GetMaterial("GXe");
G4Material *GXePTFE = G4Material::GetMaterial("GXePTFE");
G4Material *PhotoDetAluminium = G4Material::GetMaterial("PhotoCathodeAluminium");
// Main vacuum chamber
G4Tubs *pVacuumTubs = new G4Tubs("VacuumTubs", 0., GetGeometryParameter("MainVacuumChamberOuterRadius")-0.01,
GetGeometryParameter("MainVacuumChamberHalfZ")+0.01, 0.*deg, 360.*deg);
m_pVacuumLogicalVolume = new G4LogicalVolume(pVacuumTubs, Vacuum, "VacuumVolume", 0, 0, 0);
m_pVacuumPhysicalVolume = new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), m_pVacuumLogicalVolume,
"Vacuum", m_pLabLogicalVolume, false, 0);
G4Tubs *pMainVacuumChamberTubs = new G4Tubs("MainVacuumChamberTubs", GetGeometryParameter("MainVacuumChamberInnerRadius"),
GetGeometryParameter("MainVacuumChamberOuterRadius"),
GetGeometryParameter("MainVacuumChamberHalfZ"),
0.*deg, 360.*deg);
m_pMainVacuumChamberLogicalVolume = new G4LogicalVolume(pMainVacuumChamberTubs, SS316LSteel, "MainVacuumChamberVolume", 0, 0, 0);
m_pMainVacuumChamberPhysicalVolume = new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), m_pMainVacuumChamberLogicalVolume,
"MainVacuumChamberCylinder", m_pVacuumLogicalVolume, false, 0);
G4Tubs *pMainVacuumChamberFlangeTubs = new G4Tubs("MainVacuumChamberFlangeTubs", 0., GetGeometryParameter("MainVacuumChamberOuterRadius"),
GetGeometryParameter("MainVacuumChamberFlangeHalfZ"), 0.*deg, 360.*deg);
m_pMainVacuumChamberFlangeLogicalVolume = new G4LogicalVolume(pMainVacuumChamberFlangeTubs, SS316LSteel, "MainVacuumChamberFlangeVolume", 0, 0, 0);
m_pMainVacuumChamberFlangeTopPhysicalVolume = new G4PVPlacement(0, G4ThreeVector(0., 0., GetGeometryParameter("MainVacuumChamberHalfZ")+GetGeometryParameter("MainVacuumChamberFlangeHalfZ")), m_pMainVacuumChamberFlangeLogicalVolume,
"MainVacuumChamberFlangeTop", m_pVacuumLogicalVolume, false, 0);
m_pMainVacuumChamberFlangeBottomPhysicalVolume = new G4PVPlacement(0, G4ThreeVector(0., 0., -GetGeometryParameter("MainVacuumChamberHalfZ")-GetGeometryParameter("MainVacuumChamberFlangeHalfZ")), m_pMainVacuumChamberFlangeLogicalVolume,
"MainVacuumChamberFlangeBottom", m_pVacuumLogicalVolume, false, 0);
XeSimLXeSensitiveDetector *pLXeSD = new XeSimLXeSensitiveDetector("RefSetup/LXeSD");
pSDManager->AddNewDetector(pLXeSD);
m_pMainVacuumChamberFlangeLogicalVolume->SetSensitiveDetector(pLXeSD);
// PMT screen
G4Tubs *pPMTScreenTubs = new G4Tubs("PMTScreenTubs", GetGeometryParameter("CenterToPMTSlit"),
GetGeometryParameter("CenterToPMTSlit")+2.00*mm,
0.5*GetGeometryParameter("PMTScreenHeight"),
0.*deg, 320.*deg);
G4RotationMatrix *rm = new G4RotationMatrix;
rm->rotateZ(-20*deg);
m_pPMTScreenLogicalVolume = new G4LogicalVolume(pPMTScreenTubs, PhotoDetAluminium, "PMTScreenVolume", 0, 0, 0);
m_pPMTScreenPhysicalVolume = new G4PVPlacement(rm, G4ThreeVector(0., 0., 0.), m_pPMTScreenLogicalVolume,
"PMTScreen", m_pVacuumLogicalVolume, false, 0);
XeSimPhotoDetSensitiveDetector *pPmtSD = new XeSimPhotoDetSensitiveDetector("RefSetup/PhotoDetSD");
pSDManager->AddNewDetector(pPmtSD);
m_pPMTScreenLogicalVolume->SetSensitiveDetector(pPmtSD);
// Flange
G4Tubs *pSampleHolderFlangeTubs = new G4Tubs("SampleHolderFlangeFlangeTubs", 0., GetGeometryParameter("HolderFlangeRadius"),
0.5*GetGeometryParameter("HolderFlangeHeight"), 0.*deg, 360.*deg);
m_pSampleHolderFlangeLogicalVolume = new G4LogicalVolume(pSampleHolderFlangeTubs, SS316LSteel, "SampleHolderFlangeVolume", 0, 0, 0);
m_pSampleHolderFlangePhysicalVolume = new G4PVPlacement(0, G4ThreeVector(0., 0., -0.5*GetGeometryParameter("HolderFlangeHeight")), m_pSampleHolderFlangeLogicalVolume,
"SampleHolderFlange", m_pVacuumLogicalVolume, false, 0);
// Sample(Holder)
G4Box *pPTFEHolderOuterBox = new G4Box("PTFEHolderOuterBox", GetGeometryParameter("PTFEHolderHalfX"),
GetGeometryParameter("PTFEHolderHalfY"),
GetGeometryParameter("PTFEHolderHalfZ"));
G4Box *pPTFEHolderInnerBox = new G4Box("PTFEHolderInnerBox", GetGeometryParameter("PTFEHolderHalfX")+0.01,
GetGeometryParameter("PTFEHolderHalfY")-1.,
GetGeometryParameter("PTFEHolderHalfZ")-1.);
G4SubtractionSolid* pPTFEHolderBox = new G4SubtractionSolid("PTFEHolderBox", pPTFEHolderOuterBox, pPTFEHolderInnerBox);
m_pPTFEHolderLogicalVolume = new G4LogicalVolume(pPTFEHolderBox, SS316LSteel, "PTFEHolderFlangeVolume", 0, 0, 0);
m_pPTFEHolderPhysicalVolume = new G4PVPlacement(0, G4ThreeVector(GetGeometryParameter("CenterFlangeToCenterSS"), 0., GetGeometryParameter("PTFEHolderHalfZ")), m_pPTFEHolderLogicalVolume,
"PTFEHolderBox", m_pVacuumLogicalVolume, false, 0);
G4Box *pPTFEBox = new G4Box("PTFEBox", GetGeometryParameter("PTFESampleHalfX"),
GetGeometryParameter("PTFESampleHalfY"),
GetGeometryParameter("PTFESampleHalfZ"));
G4Box *pPTFECutBox = new G4Box("PTFECutBox", GetGeometryParameter("PTFESampleCutHalfX")+0.01,
GetGeometryParameter("PTFESampleCutHalfY"),
GetGeometryParameter("PTFESampleHalfZ")+0.01);
G4SubtractionSolid* pPTFESample = new G4SubtractionSolid("_PTFESample", pPTFEBox, pPTFECutBox,
0, G4ThreeVector(-GetGeometryParameter("PTFESampleCutHalfX"), 0., 0.));
G4Tubs *pHoleTubs = new G4Tubs("HoleTubs", 0., 3.,
GetGeometryParameter("PTFESampleHoleHalfX"), 0.*deg, 360.*deg);
G4RotationMatrix *rmHole = new G4RotationMatrix;
rmHole->rotateY(90*deg);
G4SubtractionSolid* pPTFESampleHole = new G4SubtractionSolid("PTFESample", pPTFESample, pHoleTubs,
rmHole, G4ThreeVector(GetGeometryParameter("PTFESampleHalfX")+0.01, 0., 0.));
G4Tubs *pPhotonTubs = new G4Tubs("PhotonTubs", 0., 3.,
0.1, 0.*deg, 360.*deg);
G4SubtractionSolid* pPTFESampleHoles = new G4SubtractionSolid("PTFESample with source", pPTFESampleHole, pPhotonTubs,
rmHole, G4ThreeVector(0.1-GetGeometryParameter("PTFESampleHalfX")-0.00001+2.*GetGeometryParameter("PTFESampleCutHalfX"), 0., 0.));
m_pPTFELogicalVolume = new G4LogicalVolume(pPTFESampleHoles, GXePTFE, "PTFEVolume", 0, 0, 0);
m_pPTFEPhysicalVolume = new G4PVPlacement(0, G4ThreeVector(GetGeometryParameter("CenterFlangeToPTFESamples"), 0., GetGeometryParameter("PTFEHolderHalfZ")), m_pPTFELogicalVolume,
"PTFEHolderBox", m_pVacuumLogicalVolume, false, 0);
m_pPhotonsLogicalVolume = new G4LogicalVolume(pPhotonTubs, Vacuum, "PhotonVolume", 0, 0, 0);
m_pPhotonsPhysicalVolume = new G4PVPlacement(rmHole, G4ThreeVector(0.1+GetGeometryParameter("CenterFlangeToPTFESamples"), 0., GetGeometryParameter("PTFEHolderHalfZ")), m_pPhotonsLogicalVolume,
"PhotonSource", m_pVacuumLogicalVolume, false, 0);
// optical border surface
G4double dSigmaAlpha = 0.1;
G4OpticalSurface *pSS316LSteelOpticalSurface = new G4OpticalSurface("SS316LSteelOpticalSurface",
unified, polished, dielectric_metal, 0.);
G4OpticalSurface *pPTFEOpticalSurface = new G4OpticalSurface("PTFEOpticalSurface",
unified, groundbackpainted, dielectric_dielectric, dSigmaAlpha);
pPTFEOpticalSurface->SetMaterialPropertiesTable(GXePTFE->GetMaterialPropertiesTable());
pSS316LSteelOpticalSurface->SetMaterialPropertiesTable(SS316LSteel->GetMaterialPropertiesTable());
new G4LogicalBorderSurface("VacuumPTFELogicalBorderSurface",
m_pVacuumPhysicalVolume, m_pPTFEPhysicalVolume, pPTFEOpticalSurface);
new G4LogicalBorderSurface("PhotonsPTFELogicalBorderSurface",
m_pPhotonsPhysicalVolume, m_pPTFEPhysicalVolume, pPTFEOpticalSurface);
new G4LogicalBorderSurface("VacuumPTFELogicalBorderSurface",
m_pVacuumPhysicalVolume, m_pSampleHolderFlangePhysicalVolume, pSS316LSteelOpticalSurface);
new G4LogicalBorderSurface("VacuumPTFELogicalBorderSurface",
m_pVacuumPhysicalVolume, m_pPTFEHolderPhysicalVolume, pSS316LSteelOpticalSurface);
// VI attributes
G4Colour hPTFEColor(1., 0., 1., 1.);
G4Colour hSSColor(1., 1., 0., 1.);
G4Colour hSSFlangeColor(1., 0.75, 0., 1.);
G4Colour hPMTColor(0., 1., 0., 1.);
G4Colour hMCColor(0.0,0.0,1.0,0.25);
G4Colour hPhotonsColor(0.0,1.0,1.0,0.25);
G4VisAttributes *pPhotonsVisAtt = new G4VisAttributes(hPhotonsColor);
pPhotonsVisAtt->SetVisibility(true);
m_pPhotonsLogicalVolume->SetVisAttributes(pPhotonsVisAtt);
G4VisAttributes *pPTFEVisAtt = new G4VisAttributes(hPTFEColor);
pPTFEVisAtt->SetVisibility(true);
m_pPTFELogicalVolume->SetVisAttributes(pPTFEVisAtt);
G4VisAttributes *pMCVisAtt = new G4VisAttributes(hMCColor);
pMCVisAtt->SetVisibility(true);
m_pMainVacuumChamberLogicalVolume->SetVisAttributes(pMCVisAtt);
m_pMainVacuumChamberFlangeLogicalVolume->SetVisAttributes(pMCVisAtt);
G4VisAttributes *pSSVisAtt = new G4VisAttributes(hSSColor);
pSSVisAtt->SetVisibility(true);
m_pPTFEHolderLogicalVolume->SetVisAttributes(pSSVisAtt);
G4VisAttributes *pSSFlangeVisAtt = new G4VisAttributes(hSSFlangeColor);
pSSFlangeVisAtt->SetVisibility(true);
m_pSampleHolderFlangeLogicalVolume->SetVisAttributes(pSSFlangeVisAtt);
G4VisAttributes *pPMTVisAtt = new G4VisAttributes(hPMTColor);
pPMTVisAtt->SetVisibility(true);
m_pPMTScreenLogicalVolume->SetVisAttributes(pPMTVisAtt);
} | 55.448065 | 245 | 0.695758 | [
"vector"
] |
a8675e63da44bf639505d2ad09a15f9b9af664b6 | 13,337 | hpp | C++ | Libraries/Geometry/Geometry.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | 3 | 2022-02-11T10:34:33.000Z | 2022-02-24T17:44:17.000Z | Libraries/Geometry/Geometry.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | Libraries/Geometry/Geometry.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | // MIT Licensed (see LICENSE.md).
#pragma once
#include "GeometryStandard.hpp"
namespace Geometry
{
/// Maximum number of support points that will be returned from clipping
const uint cMaxSupportPoints = 8;
/// Calculate the centroid of the 2D polygon. Assumes the 2D points are ordered
/// in such a way that they describe the polygon's perimeter.
void CalculatePolygonCentriod(const Vec2* polyPoints, uint polyPointCount, Vec2Ptr barycenter);
/// Given an ordered set of 2D points that describe the perimeter of a polygon,
/// return whether the points are clockwise (negative) or
/// counter-clockwise (positive).
real DetermineWindingOrder(const Vec2* polyPoints, uint polyPointCount);
/// Generate an axis-aligned bounding box for the given set of 2D points.
void GenerateAabb(const Vec2* points, uint pointCount, Vec2Ptr min, Vec2Ptr max);
/// Returns 2 times the signed triangle area. The result is positive is abc is
/// counter-clockwise, negative if abc is clockwise, zero if abc is degenerate.
real Signed2DTriArea(Vec2Param a, Vec2Param b, Vec2Param c);
/// Generate an axis-aligned bounding box for the given set of 3D points.
void GenerateAabb(const Vec3* points, uint pointCount, Vec3Ptr min, Vec3Ptr max);
/// Get a unit length vector which is orthogonal to the plane that points A, B,
/// and C lie on.
Vec3 GenerateNormal(Vec3Param pointA, Vec3Param pointB, Vec3Param pointC);
/// Returns whether or not the given triangle is valid for physics.
bool IsDegenerate(Vec3Param pointA, Vec3Param pointB, Vec3Param pointC);
/// Get the signed distance of a point to a plane.
real SignedDistanceToPlane(Vec3Param point, Vec3Param planeNormal, real planeDistance);
/// Calculate the barycentric coordinates of the point with respect to the
/// triangle. Returns XYZ correspond to triangle's ABC points, respectively.
void BarycentricTriangle(Vec3Param point,
Vec3Param trianglePointA,
Vec3Param trianglePointB,
Vec3Param trianglePointC,
Vec3Ptr barycentricCoordinates);
/// Calculate the barycentric coordinates of the point with respect to the
/// tetrahedron. Returns XYZW correspond to tetrahedron's ABCD points,
/// respectively.
void BarycentricTetrahedron(Vec3Param point,
Vec3Param tetrahedronPointA,
Vec3Param tetrahedronPointB,
Vec3Param tetrahedronPointC,
Vec3Param tetrahedronPointD,
Vec4Ptr barycentricCoordinates);
/// Clip the set of coplanar polygon points against the plane.
uint ClipPolygonWithPlane(const Vec3* polygonPoints,
uint polygonPointCount,
Vec3Param planeNormal,
real planeDistance,
Vec3Ptr clippedPoints);
/// Clip the set of coplanar polygon points against the given clipping planes.
/// The planes are stored in a Vector4 with the plane normal in the (x,y,z) and
/// the plane's distance in the w.
uint ClipPolygonWithPlanes(const Vec4* clipperPlanes,
uint clipperPlaneCount,
const Vec3* polygonPoints,
uint polygonPointCount,
Vec3Ptr clippedPoints);
/// Clip the set of coplanar polygon points against the planes that define the
/// clipping polygon.
uint ClipPolygonWithPolygon(const Vec3* clipperPoints,
uint clipperPointCount,
const Vec3* polygonPoints,
uint polygonPointCount,
Vec3Ptr clippedPoints);
/// Calculate the barycenter of the given point set.
void CalculateBarycenter(const Vec3* points, uint count, Vec3Ptr barycenter);
/// Given n-gon specified by points v[], compute a good representative plane p.
void ComputeBestFitPlane(const Vec3* polyPoints, uint polyPointCount, Vec3Ptr planeNormal, real* planeDistance);
// Default scale used by the following three functions.
#define NoScale Vec3(real(1.0), real(1.0), real(1.0))
/// Calculate the volume of a triangular mesh, if no scale is provided then it
/// assumes a scale of (1, 1, 1).
real CalculateTriMeshVolume(const Vec3* triMeshPoints,
const uint* triMeshTriangles,
uint triangleCount,
Vec3Param scale = NoScale);
real CalculateTriMeshVolume(const Array<Vec3>& triMeshPoints,
const Array<uint>& triMeshTriangles,
Vec3Param scale = NoScale);
/// Calculate the center of mass of a triangular mesh, assuming uniform density.
/// If no scale is provided then it assumes a scale of (1, 1, 1).
Vec3 CalculateTriMeshCenterOfMass(const Vec3* triMeshPoints,
const uint* triMeshTriangles,
uint triangleCount,
Vec3Param scale = NoScale);
Vec3 CalculateTriMeshCenterOfMass(const Array<Vec3>& triMeshPoints,
const Array<uint>& triMeshTriangles,
Vec3Param scale = NoScale);
/// Scale can be applied afterwards to centerOfMass as scale * centerOfMass
/// and volume can be scaled as scale.x * scale.y * scale.z * volume
void CalculateTriMeshCenterOfMassAndVolume(
const Vec3* triMeshPoints, const uint* triMeshTriangles, uint triangleCount, Vec3Ref centerOfMass, real& volume);
void CalculateTriMeshCenterOfMassAndVolume(const Array<Vec3>& triMeshPoints,
const Array<uint>& triMeshTriangles,
Vec3Ref centerOfMass,
real& volume);
/// Calculate the inertia tensor of a triangular mesh. Providing the center of
/// mass for the mesh is optional, but will increase the accuracy of the inertia
/// tensor calculations (otherwise the origin is used). Assumes a mass of 1,
/// which allows for the mass to be easily factored in later. If no scale is
/// provided then it assumes a scale of (1, 1, 1).
void CalculateTriMeshInertiaTensor(const Vec3* triMeshPoints,
const uint* triMeshTriangles,
uint triangleCount,
Vec3Param centerOfMass,
Mat3Ptr inertiaTensor,
Vec3Param scale = NoScale);
void CalculateTriMeshInertiaTensor(const Array<Vec3>& triMeshPoints,
const Array<uint>& triMeshTriangles,
Vec3Param centerOfMass,
Mat3Ptr inertiaTensor,
Vec3Param scale = NoScale);
#undef NoScale
/// Combines an inertia tensor that was computed about it's local center of mass
/// with one computed about a different center of mass. This is used to compute
/// the total inertia tensor of an object made out of sub pieces. (Parallel axis
/// theorem)
void CombineInertiaTensor(Mat3Ref totalInertiaTensor,
Vec3Param totalCenterOfMass,
Mat3Param localInertiaTensor,
Vec3Param localCenterOfMass,
real localMass);
/// Find the point furthest in the direction on an axis-aligned bounding box.
void SupportAabb(Vec3Param direction, Vec3Param aabbMinPoint, Vec3Param aabbMaxPoint, Vec3Ptr support);
/// Find the point furthest in the direction on a capsule.
void SupportCapsule(
Vec3Param direction, Vec3Param capsulePointA, Vec3Param capsulePointB, real capsuleRadius, Vec3Ptr support);
// Find the point furthest in the direction on a cylinder.
void SupportCylinder(
Vec3Param direction, Vec3Param cylinderPointA, Vec3Param cylinderPointB, real cylinderRadius, Vec3Ptr support);
/// Find the point furthest in the direction on a cylinder.
void SupportCylinder(Vec3Param direction,
Vec3Param cylinderCenter,
real cylinderHalfHeight,
real cylinderRadius,
Mat3Param cylinderBasis,
Vec3Ptr support);
/// Find the point furthest in the direction on an ellipsoid.
void SupportEllipsoid(Vec3Param direction,
Vec3Param ellipsoidCenter,
Vec3Param ellipsoidRadii,
Mat3Param ellipsoidBasis,
Vec3Ptr support);
/// Find the point furthest in the direction on an oriented bounding box.
void SupportObb(
Vec3Param direction, Vec3Param obbCenter, Vec3Param obbHalfExtents, Mat3Param obbBasis, Vec3Ptr support);
/// Find the point furthest in the direction for a given set of points.
void SupportPointSet(Vec3Param direction,
const Vec3Ptr points,
uint pointCount,
Vec3Param center,
Vec3Param scale,
Mat3Param basis,
Vec3Ptr support);
/// Find the point furthest in the direction on a segment.
void SupportSegment(Vec3Param direction, Vec3Param segmentStart, Vec3Param segmentEnd, Vec3Ptr support);
/// Find the point furthest in the direction on a sphere.
void SupportSphere(Vec3Param direction, Vec3Param sphereCenter, real sphereRadius, Vec3Ptr support);
/// Find the point furthest in the direction on a tetrahedron.
void SupportTetrahedron(Vec3Param direction,
Vec3Param tetrahedronPointA,
Vec3Param tetrahedronPointB,
Vec3Param tetrahedronPointC,
Vec3Param tetrahedronPointD,
Vec3Ptr support);
/// Find the point furthest in the direction on a triangle.
void SupportTriangle(
Vec3Param direction, Vec3Param trianglePointA, Vec3Param trianglePointB, Vec3Param trianglePointC, Vec3Ptr support);
/// Get the normal on an axis-aligned bounding box at the specified point on the
/// given axis-aligned bounding box.
Vec3 NormalFromPointOnAabb(Vec3Param point, Vec3Param aabbMinPoint, Vec3Param aabbMaxPoint);
/// Get the normal on a capsule at the specified point on the given capsule.
Vec3 NormalFromPointOnCapsule(Vec3Param point, Vec3Param capsulePointA, Vec3Param capsulePointB, real capsuleRadius);
/// Get the normal on a cylinder at the specified point on the given cylinder.
Vec3 NormalFromPointOnCylinder(
Vec3Param point, Vec3Param cylinderCenter, real cylinderRadius, real cylinderHalfHeight, Mat3Param cylinderBasis);
/// Get the normal on an ellipsoid at the specified point on the given
/// ellipsoid.
Vec3 NormalFromPointOnEllipsoid(Vec3Param point,
Vec3Param ellipsoidCenter,
Vec3Param ellipsoidRadii,
Mat3Param ellipsoidBasis);
/// Get the normal on an oriented bounding box at the specified point on the
/// given oriented bounding box.
Vec3 NormalFromPointOnObb(Vec3Param point, Vec3Param obbCenter, Vec3Param obbHalfExtents, Mat3Param obbBasis);
/// Get the normal on a sphere at the specified point on the given sphere.
Vec3 NormalFromPointOnSphere(Vec3Param point, Vec3Param sphereCenter, real sphereRadius);
/// Get the normal on a torus at the specified point on the given torus. The
/// torus's z-axis is the axis going through its hole.
Vec3 NormalFromPointOnTorus(
Vec3Param point, Vec3Param torusCenter, real torusRingRadius, real torusTubeRadius, Mat3Param torusBasis);
/// Get the normal on a triangle at the specified point on the given triangle.
Vec3 NormalFromPointOnTriangle(Vec3Param point,
Vec3Param trianglePointA,
Vec3Param trianglePointB,
Vec3Param trianglePointC);
/// Get the texture coordinates on a cylinder at the specified point on the
/// given cylinder.
Vec2 TextureCoordinatesFromPointOnCylinder(
Vec3Param point, Vec3Param cylinderCenter, real cylinderHalfHeight, real cylinderRadius, Mat3Param cylinderBasis);
/// Get the texture coordinates on an ellipsoid at the specified point on the
/// given ellipsoid.
Vec2 TextureCoordinatesFromPointOnEllipsoid(Vec3Param point,
Vec3Param ellipsoidCenter,
Vec3Param ellipsoidRadii,
Mat3Param ellipsoidBasis);
/// Get the texture coordinates on an oriented bounding box at the specified
/// point on the given oriented bounding box.
Vec2 TextureCoordinatesFromPointOnObb(Vec3Param point,
Vec3Param obbCenter,
Vec3Param obbHalfExtents,
Mat3Param obbBasis);
/// Get the texture coordinates on a sphere at the specified point on the
/// sphere.
Vec2 TextureCoordinatesFromPointOnSphere(Vec3Param point,
Vec3Param sphereCenter,
real sphereRadius,
Mat3Param sphereBasis);
} // namespace Geometry
| 49.764925 | 120 | 0.657194 | [
"mesh",
"geometry",
"object",
"vector",
"3d"
] |
a86fc826a026ec4cb8b59414fb207ce162f95524 | 51 | hh | C++ | RAVL2/MSVC/include/Ravl/3D/FormatPOVRayFile.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/3D/FormatPOVRayFile.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/3D/FormatPOVRayFile.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null |
#include "../.././3D/MeshIO/FormatPOVRayFile.hh"
| 12.75 | 48 | 0.647059 | [
"3d"
] |
a8738e17d8e659b5b6c9baa54ee3fef3c7169a3a | 3,704 | hpp | C++ | orca_shared/include/orca_shared/mw/map.hpp | clydemcqueen/orca2 | 9a8add5e65201e84af19f037c187d0ce6ec702e3 | [
"BSD-3-Clause"
] | 9 | 2019-07-08T08:55:34.000Z | 2020-11-23T16:57:41.000Z | orca_shared/include/orca_shared/mw/map.hpp | clydemcqueen/orca2 | 9a8add5e65201e84af19f037c187d0ce6ec702e3 | [
"BSD-3-Clause"
] | 11 | 2019-06-01T00:25:18.000Z | 2021-02-06T18:15:58.000Z | orca_shared/include/orca_shared/mw/map.hpp | clydemcqueen/orca2 | 9a8add5e65201e84af19f037c187d0ce6ec702e3 | [
"BSD-3-Clause"
] | 3 | 2019-07-19T10:26:34.000Z | 2020-02-03T09:14:08.000Z | // Copyright (c) 2020, Clyde McQueen.
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef ORCA_SHARED__MW__MAP_HPP_
#define ORCA_SHARED__MW__MAP_HPP_
#include <vector>
#include "fiducial_vlam_msgs/msg/map.hpp"
#include "orca_shared/mw/header.hpp"
#include "orca_shared/mw/marker.hpp"
#include "orca_shared/mw/observations.hpp"
#include "orca_shared/mw/pose.hpp"
namespace mw
{
class Map
{
fiducial_vlam_msgs::msg::Map msg_;
std::vector<mw::Marker> markers_;
public:
Map() = default;
explicit Map(const fiducial_vlam_msgs::msg::Map & msg)
: msg_{msg}
{
for (int i = 0; i < msg_.ids.size(); ++i) {
markers_.emplace_back(msg_.ids[i], msg_.marker_length, Pose{msg_.poses[i].pose});
}
}
fiducial_vlam_msgs::msg::Map msg() const
{
return msg_;
}
bool valid() const
{
return Header{msg_.header}.valid();
}
double marker_length() const
{
return msg_.marker_length;
}
const std::vector<mw::Marker> & markers() const
{
return markers_;
}
const Marker & get(const int & id) const
{
for (const auto & item : markers_) {
if (id == item.id()) {
return item;
}
}
return Marker::None;
}
/**
* Plan a route from start to destination through the smallest number of waypoints.
*
* Ignores marker orientation, so only works for down-facing cameras and markers on the seafloor.
*
* @param target_z Travel depth
* @param max_dead_reckon_dist Max dead reckoning distance
* @param start_pose Start pose
* @param destination_pose Destination pose
* @param waypoints Out: all posts from start to destionat
* @return True if a path was found
*/
bool get_waypoints(
const double & target_z, const double & max_dead_reckon_dist,
const Pose & start_pose, const Pose & destination_pose, std::vector<Pose> & waypoints) const;
bool operator==(const Map & that) const
{
return msg_ == that.msg_;
}
bool operator!=(const Map & that) const
{
return !(*this == that);
}
friend std::ostream & operator<<(std::ostream & os, const Map & v);
};
} // namespace mw
#endif // ORCA_SHARED__MW__MAP_HPP_
| 29.632 | 99 | 0.708693 | [
"vector"
] |
a87ccc27e8d5ba1cdd6ed4fc153d45c230906297 | 765 | cpp | C++ | 455A.cpp | AdithyaViswanathan/Codeforces | 4f045759227845ced165dfae5763ce76cdca852d | [
"MIT"
] | null | null | null | 455A.cpp | AdithyaViswanathan/Codeforces | 4f045759227845ced165dfae5763ce76cdca852d | [
"MIT"
] | null | null | null | 455A.cpp | AdithyaViswanathan/Codeforces | 4f045759227845ced165dfae5763ce76cdca852d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define ll long long
void solve()
{
ll n;
cin>>n;
map<ll,ll>m;
ll maxi=INT_MIN;
vector<ll>v(n);
vector<ll>cnt(100001,0);
for(auto &t:v)
cin>>t,cnt[t]++,maxi=max(maxi,t);
vector<ll>sum(maxi+2,0);
ll index = 0;
ll maxi2=INT_MIN;
for(index=0;index<=maxi;index++)
{ if(index==0)
sum[0]=cnt[0];
else if(index==1)
sum[1]=max(cnt[index]*1,sum[index-1]);
else
sum[index]=max(sum[index-2]+cnt[index]*index,sum[index-1]);
maxi2 = max(maxi2,sum[index]);
}
cout<<maxi2;
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long testcase = 1;
//cin >> testcase ;
while(testcase--)
solve();
return 0;
} | 18.658537 | 62 | 0.616993 | [
"vector"
] |
a87cf927b93c139fba027c27654167463903418f | 1,536 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/spherical.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 326 | 2015-02-08T13:47:49.000Z | 2022-03-16T02:13:59.000Z | ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/spherical.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/azimuth/spherical.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 215 | 2015-01-14T15:50:38.000Z | 2022-02-23T03:58:36.000Z | // Boost.Geometry
// Copyright (c) 2021, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
#ifndef BOOST_GEOMETRY_STRATEGIES_AZIMUTH_SPHERICAL_HPP
#define BOOST_GEOMETRY_STRATEGIES_AZIMUTH_SPHERICAL_HPP
// TODO: move this file to boost/geometry/strategy
#include <boost/geometry/strategies/spherical/azimuth.hpp>
#include <boost/geometry/strategies/azimuth/services.hpp>
#include <boost/geometry/strategies/detail.hpp>
namespace boost { namespace geometry
{
namespace strategies { namespace azimuth
{
template <typename CalculationType = void>
class spherical : strategies::detail::spherical_base<void>
{
using base_t = strategies::detail::spherical_base<void>;
public:
static auto azimuth()
{
return strategy::azimuth::spherical<CalculationType>();
}
};
namespace services
{
template <typename Point1, typename Point2>
struct default_strategy<Point1, Point2, spherical_equatorial_tag, spherical_equatorial_tag>
{
using type = strategies::azimuth::spherical<>;
};
template <typename CT>
struct strategy_converter<strategy::azimuth::spherical<CT> >
{
static auto get(strategy::azimuth::spherical<CT> const&)
{
return strategies::azimuth::spherical<CT>();
}
};
} // namespace services
}} // namespace strategies::azimuth
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_STRATEGIES_AZIMUTH_SPHERICAL_HPP
| 22.588235 | 91 | 0.754557 | [
"geometry"
] |
a88540e21ff3d26b15e9d1d01321b424216bd481 | 4,750 | cc | C++ | modules/audio_processing/aec3/render_delay_controller.cc | bebo/webrtc | 61ab9c5200ffb1281d038978465543cc52598e16 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/audio_processing/aec3/render_delay_controller.cc | bebo/webrtc | 61ab9c5200ffb1281d038978465543cc52598e16 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/audio_processing/aec3/render_delay_controller.cc | bebo/webrtc | 61ab9c5200ffb1281d038978465543cc52598e16 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_processing/aec3/render_delay_controller.h"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "webrtc/modules/audio_processing/aec3/aec3_common.h"
#include "webrtc/modules/audio_processing/aec3/echo_path_delay_estimator.h"
#include "webrtc/modules/audio_processing/aec3/render_delay_controller_metrics.h"
#include "webrtc/rtc_base/atomicops.h"
#include "webrtc/rtc_base/constructormagic.h"
namespace webrtc {
namespace {
class RenderDelayControllerImpl final : public RenderDelayController {
public:
RenderDelayControllerImpl(int sample_rate_hz);
~RenderDelayControllerImpl() override;
void Reset() override;
void SetDelay(size_t render_delay) override;
size_t GetDelay(const DownsampledRenderBuffer& render_buffer,
rtc::ArrayView<const float> capture) override;
rtc::Optional<size_t> AlignmentHeadroomSamples() const override {
return headroom_samples_;
}
private:
static int instance_count_;
std::unique_ptr<ApmDataDumper> data_dumper_;
size_t delay_ = 0;
EchoPathDelayEstimator delay_estimator_;
size_t blocks_since_last_delay_estimate_ = 300000;
int echo_path_delay_samples_ = 0;
size_t align_call_counter_ = 0;
rtc::Optional<size_t> headroom_samples_;
RenderDelayControllerMetrics metrics_;
RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(RenderDelayControllerImpl);
};
size_t ComputeNewBufferDelay(size_t current_delay,
size_t echo_path_delay_samples) {
// The below division is not exact and the truncation is intended.
const int echo_path_delay_blocks = echo_path_delay_samples / kBlockSize;
constexpr int kDelayHeadroomBlocks = 1;
// Compute the buffer delay increase required to achieve the desired latency.
size_t new_delay = std::max(echo_path_delay_blocks - kDelayHeadroomBlocks, 0);
// Add hysteresis.
if (new_delay == current_delay + 1) {
new_delay = current_delay;
}
return new_delay;
}
int RenderDelayControllerImpl::instance_count_ = 0;
RenderDelayControllerImpl::RenderDelayControllerImpl(int sample_rate_hz)
: data_dumper_(
new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
delay_estimator_(data_dumper_.get()) {
RTC_DCHECK(ValidFullBandRate(sample_rate_hz));
}
RenderDelayControllerImpl::~RenderDelayControllerImpl() = default;
void RenderDelayControllerImpl::Reset() {
delay_ = kMinEchoPathDelayBlocks;
blocks_since_last_delay_estimate_ = 300000;
echo_path_delay_samples_ = 0;
align_call_counter_ = 0;
headroom_samples_ = rtc::Optional<size_t>();
delay_estimator_.Reset();
}
void RenderDelayControllerImpl::SetDelay(size_t render_delay) {
if (delay_ != render_delay) {
// If a the delay set does not match the actual delay, reset the delay
// controller.
Reset();
delay_ = render_delay;
}
}
size_t RenderDelayControllerImpl::GetDelay(
const DownsampledRenderBuffer& render_buffer,
rtc::ArrayView<const float> capture) {
RTC_DCHECK_EQ(kBlockSize, capture.size());
++align_call_counter_;
rtc::Optional<size_t> echo_path_delay_samples =
delay_estimator_.EstimateDelay(render_buffer, capture);
if (echo_path_delay_samples) {
blocks_since_last_delay_estimate_ = 0;
echo_path_delay_samples_ = *echo_path_delay_samples;
// Compute and set new render delay buffer delay.
const size_t new_delay =
ComputeNewBufferDelay(delay_, echo_path_delay_samples_);
if (align_call_counter_ > kNumBlocksPerSecond) {
delay_ = new_delay;
// Update render delay buffer headroom.
const int headroom = echo_path_delay_samples_ - delay_ * kBlockSize;
RTC_DCHECK_LE(0, headroom);
headroom_samples_ = rtc::Optional<size_t>(headroom);
}
} else if (++blocks_since_last_delay_estimate_ > 20 * kNumBlocksPerSecond) {
headroom_samples_ = rtc::Optional<size_t>();
}
metrics_.Update(echo_path_delay_samples, delay_);
data_dumper_->DumpRaw("aec3_render_delay_controller_delay", 1,
&echo_path_delay_samples_);
data_dumper_->DumpRaw("aec3_render_delay_controller_buffer_delay", delay_);
return delay_;
}
} // namespace
RenderDelayController* RenderDelayController::Create(int sample_rate_hz) {
return new RenderDelayControllerImpl(sample_rate_hz);
}
} // namespace webrtc
| 33.450704 | 81 | 0.760842 | [
"render",
"vector"
] |
a887f08c9af119e81cefc0e41063256f89ecaa29 | 24,697 | cpp | C++ | simulator_2.0/simulation.cpp | AliceDeLorenci/pray-predator-coevolution | 1b0aa7c909bdb4208d630ec73ee594bae0b6f6a6 | [
"MIT"
] | null | null | null | simulator_2.0/simulation.cpp | AliceDeLorenci/pray-predator-coevolution | 1b0aa7c909bdb4208d630ec73ee594bae0b6f6a6 | [
"MIT"
] | null | null | null | simulator_2.0/simulation.cpp | AliceDeLorenci/pray-predator-coevolution | 1b0aa7c909bdb4208d630ec73ee594bae0b6f6a6 | [
"MIT"
] | null | null | null | #include "simulationmanager.h"
#include "ui_simulationmanager.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <queue>
#include <utility>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <QTimer>
#include <QString>
#include <QtMath>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
using namespace std;
void SimulationManager::initialize_populations(){
int i;
for(i=0; i<herb_sim.size(); i++){
matrix[herb_sim[i].y][herb_sim[i].x] = 0;
}
for(i=0; i<carn_sim.size(); i++){
matrix[carn_sim[i].y][carn_sim[i].x] = 0;
}
for(i=0; i<plant_sim.size(); i++){
matrix[plant_sim[i].y][plant_sim[i].x] = 0;
}
herb_sim.clear();
carn_sim.clear();
plant_sim.clear();
herb_sim.resize(herb_pop);
carn_sim.resize(carn_pop);
plant_sim.resize(plants_pop);
sim_gen = ui->chooseGen->value();
for(i=0; i<herb_pop; i++){
srand(time(0)+i);
herb_sim[i].x = rand()%X;
herb_sim[i].y = rand()%Y;
while(check_disponibility(herb_sim[i].x, herb_sim[i].y) == (-1)){
herb_sim[i].x = rand()%X;
herb_sim[i].y = rand()%Y;
}
herb_sim[i].angle = (float)(rand()%628)/100;
matrix[herb_sim[i].y][herb_sim[i].x] = 1;
}
for(i=0; i<carn_pop; i++){
srand(time(0)+i);
carn_sim[i].x = rand()%X;
carn_sim[i].y = rand()%Y;
while(check_disponibility(carn_sim[i].x, carn_sim[i].y) == (-1)){
carn_sim[i].x = rand()%X;
carn_sim[i].y = rand()%Y;
}
carn_sim[i].angle = (float)(rand()%628)/100;
matrix[carn_sim[i].y][carn_sim[i].x] = 2;
}
for(i=0; i<plants_pop; i++){
srand(time(0)+i);
plant_sim[i].x = rand()%X;
plant_sim[i].y = rand()%Y;
while(check_disponibility(plant_sim[i].x, plant_sim[i].y) == (-1)){
plant_sim[i].x = rand()%X;
plant_sim[i].y = rand()%Y;
}
matrix[plant_sim[i].y][plant_sim[i].x] = 3;
}
Mat frame = print_img();
imshow(environment, frame);
}
int SimulationManager::check_disponibility(int x, int y){
if(matrix[y][x] != 0){
return -1;
}
return 0;
}
void SimulationManager::simulate(){
new_plants();
/////////////////////////////// GENETICALLY DETERMINED ROTATION /////////////////////////////////////////
// TIME IN SECONDS
//time_t start, end;
//start = time(NULL);
// TIME IN MILISSECONDS
// Taking too long! Around 0.35 seconds!
// One call to BFS takes around 0.02 seconds! 0.02 * 15 = 0.3 (15 calls for 15 entities)
// BFS is taking up most of the time!
// struct timespec tstart={0,0}, tend={0,0};
// clock_gettime(CLOCK_MONOTONIC, &tstart);
int i, size;
size = herb_sim.size();
//printf("HERBIVORES\n");
for(i=0; i<size; i++){
//printf("(%d) ",i);
genetic_rotation(herb_sim,herbivores,i);
//printf("Angle: %f\n",herb_sim[i].angle);
}
size = carn_sim.size();
//printf("CARNIVORES\n");
for(i=0; i<size; i++){
//printf("(%d) ",i);
genetic_rotation(carn_sim,carnivores,i);
//printf("Angle: %f\n",carn_sim[i].angle);
}
//end = time(NULL);
//printf("%f\n",difftime(end,start));
// clock_gettime(CLOCK_MONOTONIC, &tend);
// printf("took %.5f seconds\n",
// ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) -
// ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));
///////////////////////////////////////// MOVE //////////////////////////////////////////////////////
move_wanderers(herb_sim,herbivores);
move_carnivores(carn_sim,carnivores);
Mat frame = print_img();
imshow(environment, frame);
}
void SimulationManager::new_plants(){
int i;
int size = plant_sim.size();
//for(i=0; i<size; i++){
// matrix[pop[i].y][pop[i].x] = N;
//}
//pop.clear();
for(i=size; i<plants_pop; i++){
entity ind;
ind.x = rand()%X;
ind.y = rand()%Y;
while(check_disponibility(ind.x, ind.y) == -1){
ind.x = rand()%X;
ind.y = rand()%Y;
}
matrix[ind.y][ind.x] = 3;
plant_sim.push_back(ind);
}
}
void SimulationManager::move_carnivores(QVector<entity>& pop, QVector<QVector<individual>>& primary_pop){
int i, move_x, move_y, x, y;
bool obstacles = false;
int size = pop.size();
float Cos, Sin;
//printf("CARNIVORES\n");
for(i=0; i<size; i++){
matrix[pop[i].y][pop[i].x] = 0;
//if(isnan(pop[i].angle) != 0)
//printf("%f\n",pop[i].angle);
Cos = qCos(pop[i].angle);
Sin = qSin(pop[i].angle);
move_x = Cos*primary_pop[sim_gen][i].speed;
move_y = Sin*primary_pop[sim_gen][i].speed;
x = pop[i].x + move_x;
y = pop[i].y + move_y;
//if(isnan(pop[i].angle) != 0)
//printf("%f\n",pop[i].angle);
int type;
/////////////////////////// ANY OBSTACLES IN MY WAY??? /////////////////////////////////////////
obstacles = carnivores_check_for_obstacles(pop[i].x, pop[i].y, Cos, Sin, primary_pop[sim_gen][i].speed, &type);
// are there any obstacles in the way?
// analyse line from (pop.x)(pop.y) to (x)(y)
// if there is an obstacle, stay still
if(obstacles == false){ // move
if(x < 0){
x = X + x;
}
else if(x >= X){
x = x%X;
}
if(y < 0){
y = Y + y;
}
else if(y >= Y){
y = y%Y;
}
if( x>=0 && x<X && y>=0 && y<Y){
pop[i].x = x;
pop[i].y = y;
}
else{
printf("ERRO (%d) Angle: %f Coordinates: (%d,%d) Should be coordinates: (%d,%d)\n",i,pop[i].angle,pop[i].x,pop[i].y,x,y);
//getchar();
}
}
//printf("%d %d\n",pop[i].y,pop[i].x);
matrix[pop[i].y][pop[i].x] = 2;
//printf("(%d) obstacle:%d\n",i,obstacles);
}
}
void SimulationManager::move_wanderers(QVector<entity>& pop, QVector<QVector<individual>>& primary_pop){
int i, move_x, move_y, x, y;
bool obstacles = false;
int size = pop.size();
float Cos, Sin;
//printf("HERBIVORES\n");
for(i=0; i<size; i++){
matrix[pop[i].y][pop[i].x] = 0;
//if(isnan(pop[i].angle) != 0)
//printf("%f\n",pop[i].angle);
Cos = qCos(pop[i].angle);
Sin = qSin(pop[i].angle);
move_x = Cos*primary_pop[sim_gen][i].speed;
move_y = Sin*primary_pop[sim_gen][i].speed;
x = pop[i].x + move_x;
y = pop[i].y + move_y;
//if(isnan(pop[i].angle) != 0)
//printf("%f\n",pop[i].angle);
int type;
/////////////////////////// ANY OBSTACLES IN MY WAY??? /////////////////////////////////////////
obstacles = check_for_obstacles(pop[i].x, pop[i].y, Cos, Sin, primary_pop[sim_gen][i].speed, &type);
// are there any obstacles in the way?
// analyse line from (pop.x)(pop.y) to (x)(y)
// if there is an obstacle, stay still
if(obstacles == false){ // move
if(x < 0){
x = X + x;
}
else if(x >= X){
x = x%X;
}
if(y < 0){
y = Y + y;
}
else if(y >= Y){
y = y%Y;
}
if( x>=0 && x<X && y>=0 && y<Y){
pop[i].x = x;
pop[i].y = y;
}
else{
printf("ERRO (%d) Angle: %f Coordinates: (%d,%d) Should be coordinates: (%d,%d)\n",i,pop[i].angle,pop[i].x,pop[i].y,x,y);
//getchar();
}
}
else if(obstacles == true){ // don't move, and (DON'T)rotate // THIS ROTATION CAN ALSO EVOLVE!!
//pop[i].angle = pop[i].angle + PI/6;
if(type == 2){ // DIE?
pop[i].angle = pop[i].angle + REFLEX_ARC;
//printf("%f\n",pop[i].angle);
//printf("(%d) Hurt: %d Atacked...\n",i,pop[i].hurt);
}
}
//printf("%d %d\n",pop[i].y,pop[i].x);
matrix[pop[i].y][pop[i].x] = 1;
//printf("(%d) obstacle:%d\n",i,obstacles);
}
}
bool SimulationManager::carnivores_check_for_obstacles(int x0, int y0, float Cos, float Sin, int speed, int *type){
bool obstacles = false;
float distance;
// start point and bottom limit
int x1, y1;
float distance1;
// OBS: if change bellow, change ALSO distance1 and 2 parameters to (speed) intead of (speed+2*RADIUS_WANDER)
//x1 = x0 + Cos*2*RADIUS_WANDER;
//y1 = y0 + Sin*2*RADIUS_WANDER;
x1 = x0 + Cos*RADIUS;
y1 = y0 + Sin*RADIUS;
// end point and top limit
int x2, y2;
float distance2;
x2 = x0 + Cos*(speed+2*RADIUS);
y2 = y0 + Sin*(speed+2*RADIUS);
// for the perpendicular line, its perp_angle is given by <angle-90>
// cos(perp_angle) = sin(angle)
// sin(perp_angle) = -cos(angle)
// so that the director vector is (sin(angle), -cos(angle))
// MAYBE change order? First search between plants, and afterwards in the wanderers population?
int i;
for(i=0; i<herb_pop; i++){
distance = Cos*(herb_sim[i].y - y0) - Sin*(herb_sim[i].x - x0);
if(distance < 0)
distance = -distance;
if(distance <= 2*RADIUS){
distance1 = Sin*(herb_sim[i].y - y1) + Cos*(herb_sim[i].x - x1);
distance2 = Sin*(herb_sim[i].y - y2) + Cos*(herb_sim[i].x - x2);
if(distance1 < 0)
distance1 = -distance1;
if(distance2 < 0)
distance2 = -distance2;
// distance to both restrictive perpendicular lines must be less than or equal to speed
if(distance1 <= (speed+2*RADIUS) && distance2 <= (speed+2*RADIUS)){
obstacles = true;
*type = 1;
return obstacles;
}
}
}
for(i=0; i<carn_pop; i++){
if((carn_sim[i].x != x0) && (carn_sim[i].y != y0)){ // if I'm not myself
distance = Cos*(carn_sim[i].y - y0) - Sin*(carn_sim[i].x - x0);
if(distance < 0)
distance = -distance;
if(distance <= (RADIUS+RADIUS)){
distance1 = Sin*(carn_sim[i].y - y1) + Cos*(carn_sim[i].x - x1);
distance2 = Sin*(carn_sim[i].y - y2) + Cos*(carn_sim[i].x - x2);
if(distance1 < 0)
distance1 = -distance1;
if(distance2 < 0)
distance2 = -distance2;
// distance to both restrictive perpendicular lines must be less than or equal to speed
if(distance1 <= (speed+(RADIUS+RADIUS)) && distance2 <= (speed+(RADIUS+RADIUS))){
obstacles = true;
*type = 2;
return obstacles;
}
}
}
}
int size = plant_sim.size();
for(i=0; i<size; i++){
distance = Cos*(plant_sim[i].y - y0) - Sin*(plant_sim[i].x - x0);
if(distance < 0)
distance = -distance;
if(distance <= (RADIUS+RADIUS)){
distance1 = Sin*(plant_sim[i].y - y1) + Cos*(plant_sim[i].x - x1);
distance2 = Sin*(plant_sim[i].y - y2) + Cos*(plant_sim[i].x - x2);
if(distance1 < 0)
distance1 = -distance1;
if(distance2 < 0)
distance2 = -distance2;
// distance to both restrictive perpendicular lines must be less than or equal to speed
if(distance1 <= (speed+(RADIUS+RADIUS)) && distance2 <= (speed+(RADIUS+RADIUS))){
obstacles = true;
*type = 3;
return obstacles;
}
}
}
return obstacles;
}
bool SimulationManager::check_for_obstacles(int x0, int y0, float Cos, float Sin, int speed, int *type){
bool obstacles = false;
float distance;
// start point and bottom limit
int x1, y1;
float distance1;
// OBS: if change bellow, change ALSO distance1 and 2 parameters to (speed) intead of (speed+2*RADIUS_WANDER)
//x1 = x0 + Cos*2*RADIUS_WANDER;
//y1 = y0 + Sin*2*RADIUS_WANDER;
x1 = x0 + Cos*RADIUS;
y1 = y0 + Sin*RADIUS;
// end point and top limit
int x2, y2;
float distance2;
x2 = x0 + Cos*(speed+2*RADIUS);
y2 = y0 + Sin*(speed+2*RADIUS);
// for the perpendicular line, its perp_angle is given by <angle-90>
// cos(perp_angle) = sin(angle)
// sin(perp_angle) = -cos(angle)
// so that the director vector is (sin(angle), -cos(angle))
// MAYBE change order? First search between plants, and afterwards in the wanderers population?
int i;
for(i=0; i<herb_pop; i++){
if((herb_sim[i].x != x0) && (herb_sim[i].y != y0)){ // if I'm not myself
distance = Cos*(herb_sim[i].y - y0) - Sin*(herb_sim[i].x - x0);
if(distance < 0)
distance = -distance;
if(distance <= 2*RADIUS){
distance1 = Sin*(herb_sim[i].y - y1) + Cos*(herb_sim[i].x - x1);
distance2 = Sin*(herb_sim[i].y - y2) + Cos*(herb_sim[i].x - x2);
if(distance1 < 0)
distance1 = -distance1;
if(distance2 < 0)
distance2 = -distance2;
// distance to both restrictive perpendicular lines must be less than or equal to speed
if(distance1 <= (speed+2*RADIUS) && distance2 <= (speed+2*RADIUS)){
obstacles = true;
*type = 1;
return obstacles;
}
}
}
}
for(i=0; i<carn_pop; i++){
distance = Cos*(carn_sim[i].y - y0) - Sin*(carn_sim[i].x - x0);
if(distance < 0)
distance = -distance;
if(distance <= (RADIUS+RADIUS)){
distance1 = Sin*(carn_sim[i].y - y1) + Cos*(carn_sim[i].x - x1);
distance2 = Sin*(carn_sim[i].y - y2) + Cos*(carn_sim[i].x - x2);
if(distance1 < 0)
distance1 = -distance1;
if(distance2 < 0)
distance2 = -distance2;
// distance to both restrictive perpendicular lines must be less than or equal to speed
if(distance1 <= (speed+(RADIUS+RADIUS)) && distance2 <= (speed+(RADIUS+RADIUS))){
obstacles = true;
*type = 2;
return obstacles;
}
}
}
int size = plant_sim.size();
for(i=0; i<size; i++){
distance = Cos*(plant_sim[i].y - y0) - Sin*(plant_sim[i].x - x0);
if(distance < 0)
distance = -distance;
if(distance <= (RADIUS+RADIUS)){
distance1 = Sin*(plant_sim[i].y - y1) + Cos*(plant_sim[i].x - x1);
distance2 = Sin*(plant_sim[i].y - y2) + Cos*(plant_sim[i].x - x2);
if(distance1 < 0)
distance1 = -distance1;
if(distance2 < 0)
distance2 = -distance2;
// distance to both restrictive perpendicular lines must be less than or equal to speed
if(distance1 <= (speed+(RADIUS+RADIUS)) && distance2 <= (speed+(RADIUS+RADIUS))){
obstacles = true;
*type = 3;
matrix[plant_sim[i].y][plant_sim[i].x] = 0;
plant_sim.erase(plant_sim.begin() + i);
return obstacles;
}
}
}
return obstacles;
}
void SimulationManager::genetic_rotation(QVector<entity>& pop, QVector<QVector<individual>>& primary_pop, int index){
float plant_rotation;
float wond_rotation;
float carn_rotation;
bool b_plant, b_wond, b_carn;
int xplant, yplant;
float plant_angle;
int xwond, ywond;
float wond_angle;
int xcarn, ycarn;
float carn_angle;
float angle;
float p=0, c=0, w=0;
if(primary_pop[sim_gen][index].search_height_limit == 0){
//struct timespec tstart={0,0}, tend={0,0};
//clock_gettime(CLOCK_MONOTONIC, &tstart);
closest_obstacles(index, pop[index].x, pop[index].y, &b_plant, &b_wond, &b_carn, &xplant, &yplant, &xwond, &ywond, &xcarn, &ycarn, primary_pop[sim_gen][index].search_height_limit, primary_pop[sim_gen][index].search_height);
//clock_gettime(CLOCK_MONOTONIC, &tend);
//printf("BFS took %.5f seconds\n",
// ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) -
// ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));
// AQUI SURGE NAN
//printf("(%d)\t",index);
// angular deviation between wonderer orientation and obstacle position
plant_angle = calculate_angle(pop[index].x, pop[index].y, xplant, yplant, pop[index].angle);
//printf("%f\t",plant_angle);
wond_angle = calculate_angle(pop[index].x, pop[index].y, xwond, ywond, pop[index].angle);
//printf("%f\t",wond_angle);
carn_angle = calculate_angle(pop[index].x, pop[index].y, xcarn, ycarn, pop[index].angle);
//printf("%f\n",carn_angle);
if(isnan(plant_angle) == 0){ // not NAN
plant_rotation = ((float)primary_pop[sim_gen][index].plant_const)*2*PI/100; // rotate this in relation to plant_angle
plant_rotation = primary_pop[sim_gen][index].plant_weight*(plant_rotation + plant_angle);
p = 1;
}
else{
plant_rotation = 0;
}
if(isnan(wond_angle) == 0){
wond_rotation = ((float)primary_pop[sim_gen][index].herb_const)*2*PI/100;
wond_rotation = primary_pop[sim_gen][index].herb_weight*(wond_rotation + wond_angle);
w = 1;
}
else{
wond_rotation = 0;
}
if(isnan(carn_angle) == 0){
carn_rotation = ((float)primary_pop[sim_gen][index].carn_const)*2*PI/100;
carn_rotation = primary_pop[sim_gen][index].carn_weight*(carn_rotation + carn_angle);
c = 1;
}
else{
carn_rotation = 0;
}
}
else{ // if there is a height limit
//struct timespec tstart={0,0}, tend={0,0};
//clock_gettime(CLOCK_MONOTONIC, &tstart);
closest_obstacles(index, pop[index].x, pop[index].y, &b_plant, &b_wond, &b_carn, &xplant, &yplant, &xwond, &ywond, &xcarn, &ycarn, primary_pop[sim_gen][index].search_height_limit, primary_pop[sim_gen][index].search_height);
//clock_gettime(CLOCK_MONOTONIC, &tend);
//printf("BFS took %.5f seconds\n",
// ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) -
// ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));
if(b_plant == true){
plant_angle = calculate_angle(pop[index].x, pop[index].y, xplant, yplant, pop[index].angle);
if(isnan(plant_angle) == 0){ // not NAN
plant_rotation = ((float)primary_pop[sim_gen][index].plant_const)*2*PI/100; // rotate this in relation to plant_angle
plant_rotation = primary_pop[sim_gen][index].plant_weight*(plant_rotation + plant_angle);
p = 1;
}
else{
plant_rotation = 0;
}
}else{
plant_rotation = 0;
}
if(b_wond == true){
wond_angle = calculate_angle(pop[index].x, pop[index].y, xwond, ywond, pop[index].angle);
if(isnan(wond_angle) == 0){
wond_rotation = ((float)primary_pop[sim_gen][index].herb_const)*2*PI/100;
wond_rotation = primary_pop[sim_gen][index].herb_weight*(wond_rotation + wond_angle);
w = 1;
}
else{
wond_rotation = 0;
}
}else{
wond_rotation = 0;
}
if(b_carn == true){
carn_angle = calculate_angle(pop[index].x, pop[index].y, xcarn, ycarn, pop[index].angle);
if(isnan(carn_angle) == 0){
carn_rotation = ((float)primary_pop[sim_gen][index].carn_const)*2*PI/100;
carn_rotation = primary_pop[sim_gen][index].carn_weight*(carn_rotation + carn_angle);
c = 1;
}
else{
carn_rotation = 0;
}
}else{
carn_rotation = 0;
}
}
angle = (plant_rotation + wond_rotation + carn_rotation)/(w*primary_pop[sim_gen][index].herb_weight + p*primary_pop[sim_gen][index].plant_weight + c*primary_pop[sim_gen][index].carn_weight);
angle = pop[index].angle + angle;
if((isnan(angle) == 0) && (isfinite(angle) != 0)){ // not NAN and FINITE
//printf("ok\n");
pop[index].angle = angle;
}
//end = time(NULL);
//printf("%lf\n",difftime(end,start));
// caso contrario o angulo nao é modificado, verificar onde o err pe gerado e corrigir!!
}
float SimulationManager::calculate_angle(int x, int y, int xobs, int yobs, float dir_angle){
float angle;
// idealy the angle variation must vary betwen -PI and PI
float dir_vec_x, dir_vec_y;
float obs_vec_x, obs_vec_y;
// NORM = 1
dir_vec_x = qCos(dir_angle);
dir_vec_y = qSin(dir_angle);
obs_vec_x = xobs - x;
obs_vec_y = yobs - y;
float Sin;
Sin = ((dir_vec_x * obs_vec_y)-(obs_vec_x * dir_vec_y))/sqrt(obs_vec_x*obs_vec_x + obs_vec_y*obs_vec_y);
float Cos;
Cos = ((dir_vec_x * obs_vec_x) + (dir_vec_y * obs_vec_y))/sqrt(obs_vec_x*obs_vec_x + obs_vec_y*obs_vec_y);
//printf("acos(%f)=%f asin(%f)=%f\n",Cos,aCos,Sin,aSin);
if(Cos >= 0){
angle = qAsin(Sin);
}
else{
if(Sin >= 0){
angle = qAcos(Cos);
}
else{
angle = -qAcos(Cos);
}
}
return angle;
}
void SimulationManager::closest_obstacles(int index, int startx, int starty, bool* b_plant, bool* b_wond, bool* b_carn, int* xplant, int* yplant, int* xwond, int* ywond, int* xcarn, int* ycarn, bool limit, int height){
*b_plant = *b_wond = *b_carn = true;
int i,size;
float distance, closest, ref;
float wand_dist, carn_dist, plant_dist, dist_lim;
int index_closest;
int x_diff, y_diff;
ref = X*X + Y*Y + 1;
// find closest obstacle of each kind
size = herb_sim.size();
if(size == 0){
(*b_wond) = false;
}
closest = ref;
for(i=0; i<size; i++){
x_diff = herb_sim[i].x - startx;
y_diff = herb_sim[i].y - starty;
distance = x_diff*x_diff + y_diff*y_diff; // no need to take the square root
if(distance != 0 && distance < closest){
closest = distance;
index_closest = i;
}
}
wand_dist = closest;
*xwond = herb_sim[index_closest].x;
*ywond = herb_sim[index_closest].y;
size = carn_sim.size();
if(size == 0){
(*b_carn) = false;
}
closest = ref;
for(i=0; i<size; i++){
x_diff = carn_sim[i].x - startx;
y_diff = carn_sim[i].y - starty;
distance = x_diff*x_diff + y_diff*y_diff; // no need to take the square root
if(distance != 0 && distance < closest){
closest = distance;
index_closest = i;
}
}
carn_dist = closest;
*xcarn = carn_sim[index_closest].x;
*ycarn = carn_sim[index_closest].y;
size = plant_sim.size();
if(size == 0){
(*b_plant) = false;
}
closest = ref;
for(i=0; i<size; i++){
x_diff = plant_sim[i].x - startx;
y_diff = plant_sim[i].y - starty;
distance = x_diff*x_diff + y_diff*y_diff; // no need to take the square root
if(distance < closest){
closest = distance;
index_closest = i;
}
}
plant_dist = closest;
*xplant = plant_sim[index_closest].x;
*yplant = plant_sim[index_closest].y;
// check search height limit
if(limit == true){
dist_lim = height*height;
if(wand_dist > dist_lim)
*b_wond = false;
if(carn_dist > dist_lim)
*b_carn = false;
if(plant_dist > dist_lim)
*b_plant = false;
}
//printf("herb:%d-(%d,%d), carn:%d-(%d,%d), plant%d-(%d,%d), ",(*b_wond),(*xwond),(*ywond),(*b_carn),(*xcarn),(*ycarn),(*b_plant),(*xplant),(*yplant));
}
| 29.899516 | 231 | 0.523019 | [
"vector"
] |
a888014fa1ec66bb6c2518bb835b5f6ac884ac1d | 1,703 | hpp | C++ | include/allocator.hpp | JYLeeLYJ/tair_contest_season1 | 34d00801bb01bb355b630ecb8bd30159ed8b59ef | [
"MIT"
] | 1 | 2021-04-02T06:02:57.000Z | 2021-04-02T06:02:57.000Z | include/allocator.hpp | JYLeeLYJ/tair_contest_code | 34d00801bb01bb355b630ecb8bd30159ed8b59ef | [
"MIT"
] | null | null | null | include/allocator.hpp | JYLeeLYJ/tair_contest_code | 34d00801bb01bb355b630ecb8bd30159ed8b59ef | [
"MIT"
] | null | null | null | #ifndef ALLOCATOR_INCLUDE_H
#define ALLOCATOR_INCLUDE_H
#include <array>
#include <vector>
#include <string>
#include "fmt/format.h"
#include "kvfile.hpp"
//not thread safe
template<std::size_t n_block>
class value_block_allocator{
public:
static constexpr uint32_t null_index = 0xffffffff;
static constexpr uint32_t total_block_num = n_block;
public:
value_block_allocator() = default;
void init(uint32_t beg , uint32_t off){
this->beg = beg;
this->off = off;
free_block_256.reserve(7_MB);
}
uint32_t allocate_128(){
uint32_t addr{null_index};
if(!free_block_128.empty()){
addr = free_block_128.back();
free_block_128.pop_back();
}else{
addr = allocate_256();
if(likely(addr != null_index))
free_block_128.push_back(addr +1);
}
return addr ;
}
uint32_t allocate_256(){
uint32_t addr{null_index};
if(!free_block_256.empty()){
addr = free_block_256.back();
free_block_256.pop_back();
}else if(off + 1 < n_block){
addr = beg + off;
off += 2;
}
return addr;
}
void recollect_128(uint32_t addr){
free_block_128.push_back(addr);
}
void recollect_256(uint32_t addr){
free_block_256.push_back(addr);
}
std::string space_use_log(){
return fmt::format("[{} , {} , remains {}]" , free_block_128.size() , free_block_256.size() , n_block - off );
}
private:
uint32_t beg{0};
uint32_t off{0};
std::vector<uint32_t> free_block_128;
std::vector<uint32_t> free_block_256;
};
#endif | 22.407895 | 118 | 0.600117 | [
"vector"
] |
a88e0d580699077e74586077d672b342ee7e023d | 1,914 | cpp | C++ | aws-cpp-sdk-opsworks/source/model/Architecture.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-opsworks/source/model/Architecture.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-opsworks/source/model/Architecture.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/opsworks/model/Architecture.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace OpsWorks
{
namespace Model
{
namespace ArchitectureMapper
{
static const int x86_64_HASH = HashingUtils::HashString("x86_64");
static const int i386_HASH = HashingUtils::HashString("i386");
Architecture GetArchitectureForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == x86_64_HASH)
{
return Architecture::x86_64;
}
else if (hashCode == i386_HASH)
{
return Architecture::i386;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<Architecture>(hashCode);
}
return Architecture::NOT_SET;
}
Aws::String GetNameForArchitecture(Architecture enumValue)
{
switch(enumValue)
{
case Architecture::x86_64:
return "x86_64";
case Architecture::i386:
return "i386";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace ArchitectureMapper
} // namespace Model
} // namespace OpsWorks
} // namespace Aws
| 26.957746 | 92 | 0.602926 | [
"model"
] |
a88eed317fe7e41b2c7f8bf1ebf9fe6afca96853 | 694 | cpp | C++ | projects/vkworld/wrappers/VkwPerlin.cpp | stefannesic/world | 44c01623ab1777c3224f83f53b74d50b58372fb1 | [
"MIT"
] | 16 | 2021-03-14T16:30:32.000Z | 2022-03-18T13:41:53.000Z | projects/vkworld/wrappers/VkwPerlin.cpp | stefannesic/world | 44c01623ab1777c3224f83f53b74d50b58372fb1 | [
"MIT"
] | 1 | 2020-04-21T12:59:37.000Z | 2020-04-23T17:49:03.000Z | projects/vkworld/wrappers/VkwPerlin.cpp | stefannesic/world | 44c01623ab1777c3224f83f53b74d50b58372fb1 | [
"MIT"
] | 4 | 2020-03-08T14:04:50.000Z | 2020-12-03T08:51:04.000Z | #include "VkwPerlin.h"
#include <numeric>
namespace world {
VkwSubBuffer VkwPerlin::createPerlinHash() {
std::mt19937 rng(std::random_device{}());
std::vector<u32> random(256);
std::iota(random.begin(), random.end(), 0);
std::shuffle(random.begin(), random.end(), rng);
random.insert(random.end(), random.begin(), random.end());
auto &ctx = Vulkan::context();
VkwSubBuffer buf =
ctx.allocate(static_cast<u32>(random.size()) * sizeof(u32),
DescriptorType::STORAGE_BUFFER, MemoryUsage::CPU_WRITES);
buf.setData(&random[0]);
return buf;
}
void VkwPerlin::addPerlinHash(VkwDescriptorSet &dset, u32 id) {}
} // namespace world
| 26.692308 | 78 | 0.652738 | [
"vector"
] |
a89852e0a135813fe9519e2b0c69bda6c712f8ef | 49,504 | cpp | C++ | download/GribStreamer.cpp | fmidev/smartmet-plugin-download | 93de102c3e66b264c975d41751fde01d403f7d21 | [
"MIT"
] | null | null | null | download/GribStreamer.cpp | fmidev/smartmet-plugin-download | 93de102c3e66b264c975d41751fde01d403f7d21 | [
"MIT"
] | null | null | null | download/GribStreamer.cpp | fmidev/smartmet-plugin-download | 93de102c3e66b264c975d41751fde01d403f7d21 | [
"MIT"
] | 1 | 2017-05-31T10:12:12.000Z | 2017-05-31T10:12:12.000Z | // ======================================================================
/*!
* \brief SmartMet download service plugin; grib streaming
*/
// ======================================================================
#include "GribStreamer.h"
#include "Datum.h"
#include "Plugin.h"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/foreach.hpp>
#include <boost/interprocess/sync/lock_options.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <fmt/format.h>
#include <gis/ProjInfo.h>
#include <macgyver/Exception.h>
#include <macgyver/StringConversion.h>
#include <newbase/NFmiEnumConverter.h>
#include <newbase/NFmiQueryData.h>
#include <newbase/NFmiQueryDataUtil.h>
#include <newbase/NFmiTimeList.h>
#include <sys/types.h>
#include <string>
#include <unistd.h>
#ifndef WGS84
#include <newbase/NFmiRotatedLatLonArea.h>
#include <newbase/NFmiStereographicArea.h>
#endif
using namespace std;
using namespace boost::posix_time;
using namespace boost::interprocess;
namespace SmartMet
{
namespace Plugin
{
namespace Download
{
template <typename T>
boost::optional<vector<pair<T, T>>> nPairsOfValues(string &pvs, const char *param, size_t nPairs);
GribStreamer::GribStreamer(const Spine::HTTP::Request &req,
const Config &config,
const Producer &producer,
const ReqParams &reqParams)
: DataStreamer(req, config, producer, reqParams), itsGrib1Flag(reqParams.outputFormat == Grib1)
{
try
{
// Get grib handle
grib_context *c = grib_context_get_default();
itsGribHandle = grib_handle_new_from_samples(c, itsGrib1Flag ? "GRIB1" : "GRIB2");
if (!itsGribHandle)
throw Fmi::Exception(BCP,
string("Could not get handle for grib") + (itsGrib1Flag ? "1" : "2"));
// Set tables version for grib2
if (reqParams.grib2TablesVersion > 0)
gset(itsGribHandle,
"gribMasterTablesVersionNumber", (unsigned long)reqParams.grib2TablesVersion);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
GribStreamer::~GribStreamer()
{
if (itsGribHandle)
grib_handle_delete(itsGribHandle);
}
// ----------------------------------------------------------------------
/*!
* \brief Determine grid x/y scanning directions
*/
// ----------------------------------------------------------------------
void GribStreamer::scanningDirections(long &iNegative, long &jPositive) const
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch-enum"
try
{
// newbase enum includes all kinds of variations
// which are useless here. Should use specific
// enums for specific purposes
//
// ???
//
// Did not quite get the comment above in plugin's point of view, using the same enums as
// newbase
// ...
//
// e.g. NFmiGridBase.cpp:
//
// switch(itsStartingCorner)
// {
// case kBottomLeft:
// return true;
// case kBottomRight:
// {
// }
// case kTopLeft:
// {
// }
// case kTopRight:
// {
// }
// default:
// {
// }
// }
switch (itsGridOrigo)
{
case kTopLeft:
iNegative = 0;
jPositive = 0;
break;
case kTopRight:
iNegative = 1;
jPositive = 0;
break;
case kBottomLeft:
iNegative = 0;
jPositive = 1;
break;
case kBottomRight:
iNegative = 1;
jPositive = 1;
break;
default:
throw Fmi::Exception(BCP, "Unknown grid scanning mode");
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
#pragma clang diagnostic pop
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib latlon projection metadata
*/
// ----------------------------------------------------------------------
void GribStreamer::setLatlonGeometryToGrib() const
{
try
{
gset(itsGribHandle, "typeOfGrid", "regular_ll");
gset(itsGribHandle, "longitudeOfFirstGridPointInDegrees", itsBoundingBox.bottomLeft.X());
gset(itsGribHandle, "latitudeOfFirstGridPointInDegrees", itsBoundingBox.bottomLeft.Y());
gset(itsGribHandle, "longitudeOfLastGridPointInDegrees", itsBoundingBox.topRight.X());
gset(itsGribHandle, "latitudeOfLastGridPointInDegrees", itsBoundingBox.topRight.Y());
gset(itsGribHandle, "Ni", itsNX);
gset(itsGribHandle, "Nj", itsNY);
double gridCellHeightInDegrees =
fabs((itsBoundingBox.topRight.Y() - itsBoundingBox.bottomLeft.Y()) / (itsNY - 1));
double gridCellWidthInDegrees =
fabs((itsBoundingBox.topRight.X() - itsBoundingBox.bottomLeft.X()) / (itsNX - 1));
long iNegative, jPositive;
scanningDirections(iNegative, jPositive);
gset(itsGribHandle, "jScansPositively", jPositive);
gset(itsGribHandle, "iScansNegatively", iNegative);
gset(itsGribHandle, "iDirectionIncrementInDegrees", gridCellWidthInDegrees);
gset(itsGribHandle, "jDirectionIncrementInDegrees", gridCellHeightInDegrees);
// DUMP(itsGribHandle, "geography");
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib rotated latlon projection metadata
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setRotatedLatlonGeometryToGrib(const NFmiArea *area) const
{
try
{
BBoxCorners rotLLBBox;
double slon = 0.0, slat = 0.0;
if (itsReqParams.dataSource == QueryData)
{
if (itsResources.getGeometrySRS())
throw Fmi::Exception(BCP, "setRotatedLatlonGeometryToGrib: use of SRS not supported");
#ifdef WGS84
auto opt_plat = area->ProjInfo().getDouble("o_lat_p");
auto opt_plon = area->ProjInfo().getDouble("o_lon_p");
if (*opt_plon != 0)
throw Fmi::Exception(
BCP, "GRIB does not support rotated latlon areas where longitude is also rotated");
slon = *opt_plon;
slat = -(*opt_plat);
auto fmisphere = fmt::format(
"+proj=latlong +R={:.0f} +over +towgs84=0,0,0 +no_defs", kRearth);
auto rotatedsphere = fmt::format(
"+to_meter=.0174532925199433 +proj=ob_tran +o_proj=latlong +o_lon_p={} +o_lat_p={} "
"+R={:.0f} +over +towgs84=0,0,0 +no_defs",
*opt_plon,
*opt_plat,
kRearth);
std::unique_ptr<NFmiArea> rotatedarea(NFmiArea::CreateFromCorners(
fmisphere, rotatedsphere, itsBoundingBox.bottomLeft, itsBoundingBox.topRight));
rotLLBBox.bottomLeft = rotatedarea->LatLonToWorldXY(itsBoundingBox.bottomLeft);
rotLLBBox.topRight = rotatedarea->LatLonToWorldXY(itsBoundingBox.topRight);
#else
const NFmiRotatedLatLonArea &a = *(dynamic_cast<const NFmiRotatedLatLonArea *>(area));
slon = a.SouthernPole().X();
slat = a.SouthernPole().Y();
rotLLBBox.bottomLeft = a.ToRotLatLon(itsBoundingBox.bottomLeft);
rotLLBBox.topRight = a.ToRotLatLon(itsBoundingBox.topRight);
#endif
}
else
{
slon = itsGridMetaData.southernPoleLon;
slat = itsGridMetaData.southernPoleLat;
rotLLBBox = *(itsGridMetaData.targetBBox);
}
if (slon)
throw Fmi::Exception(
BCP, "GRIB does not support rotated latlon areas where longitude is also rotated");
gset(itsGribHandle, "typeOfGrid", "rotated_ll");
gset(itsGribHandle, "latitudeOfSouthernPoleInDegrees", slat);
gset(itsGribHandle, "longitudeOfFirstGridPointInDegrees", rotLLBBox.bottomLeft.X());
gset(itsGribHandle, "latitudeOfFirstGridPointInDegrees", rotLLBBox.bottomLeft.Y());
gset(itsGribHandle, "longitudeOfLastGridPointInDegrees", rotLLBBox.topRight.X());
gset(itsGribHandle, "latitudeOfLastGridPointInDegrees", rotLLBBox.topRight.Y());
gset(itsGribHandle, "Ni", itsNX);
gset(itsGribHandle, "Nj", itsNY);
double gridCellHeightInDegrees =
(rotLLBBox.topRight.Y() - rotLLBBox.bottomLeft.Y()) / (itsNY - 1);
double gridCellWidthInDegrees =
(rotLLBBox.topRight.X() - rotLLBBox.bottomLeft.X()) / (itsNX - 1);
long iNegative, jPositive;
scanningDirections(iNegative, jPositive);
gset(itsGribHandle, "jScansPositively", jPositive);
gset(itsGribHandle, "iScansNegatively", iNegative);
gset(itsGribHandle, "iDirectionIncrementInDegrees", gridCellWidthInDegrees);
gset(itsGribHandle, "jDirectionIncrementInDegrees", gridCellHeightInDegrees);
// DUMP(itsGribHandle, "geography");
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib stereographic projection metadata
*
* Defaults obtained by a DUMP call once the projection is set:
*
* Nx = 16
* Ny = 31
* latitudeOfFirstGridPointInDegrees = 60
* longitudeOfFirstGridPointInDegrees = 0
* LaDInDegrees = 0
* orientationOfTheGridInDegrees = 0
* DxInMetres = 2000
* DyInMetres = 2000
* iScansNegatively = 0
* jScansPositively = 0
* jPointsAreConsecutive = 0
* gridType = "polar_stereographic"
* bitmapPresent = 0
*
* HOWEVER: GRIB1 has a fixed true latitude of 60 degrees, atleast if you
* look at /usr/share/grib_api/definitions/grib1/grid_definition_5.def
*/
// ----------------------------------------------------------------------
void GribStreamer::setStereographicGeometryToGrib(const NFmiArea *area) const
{
try
{
gset(itsGribHandle, "typeOfGrid", "polar_stereographic");
// Note: grib2 longitude 0-360
double lon = itsBoundingBox.bottomLeft.X();
if ((!itsGrib1Flag) && (lon < 0))
lon += 360;
gset(itsGribHandle, "longitudeOfFirstGridPointInDegrees", lon);
gset(itsGribHandle, "latitudeOfFirstGridPointInDegrees", itsBoundingBox.bottomLeft.Y());
gset(itsGribHandle, "Ni", itsNX);
gset(itsGribHandle, "Nj", itsNY);
gset(itsGribHandle, "DxInMetres", fabs(itsDX));
gset(itsGribHandle, "DyInMetres", fabs(itsDY));
OGRSpatialReference *geometrySRS = itsResources.getGeometrySRS();
double lon_0, lat_0, lat_ts;
if (!geometrySRS)
{
#ifdef WGS84
auto opt_lon_0 = area->ProjInfo().getDouble("lon_0");
auto opt_lat_0 = area->ProjInfo().getDouble("lat_0");
auto opt_lat_ts = area->ProjInfo().getDouble("lat_ts");
lon_0 = (opt_lon_0 ? *opt_lon_0 : 0);
lat_0 = (opt_lat_0 ? *opt_lat_0 : 90);
lat_ts = (opt_lat_ts ? *opt_lat_ts : 90);
#else
const NFmiStereographicArea &a = *(dynamic_cast<const NFmiStereographicArea *>(area));
lon_0 = a.CentralLongitude();
lat_0 = a.CentralLatitude();
lat_ts = a.TrueLatitude();
#endif
}
else
{
lon_0 = getProjParam(*geometrySRS, SRS_PP_CENTRAL_MERIDIAN);
lat_ts = getProjParam(*geometrySRS, SRS_PP_LATITUDE_OF_ORIGIN);
lat_0 = (lat_ts > 0) ? 90 : -90;
}
if ((!itsGrib1Flag) && (lon_0 < 0))
lon_0 += 360;
gset(itsGribHandle, "orientationOfTheGridInDegrees", lon_0);
long iNegative, jPositive;
scanningDirections(iNegative, jPositive);
gset(itsGribHandle, "jScansPositively", jPositive);
gset(itsGribHandle, "iScansNegatively", iNegative);
if (!itsGrib1Flag)
gset(itsGribHandle, "LaDInDegrees", lat_ts);
else if (lat_ts != 60)
throw Fmi::Exception(
BCP,
"GRIB1 true latitude can only be 60 for polar stereographic projections with grib_api "
"library");
if (lat_0 != 90 && lat_0 != -90)
throw Fmi::Exception(BCP, "GRIB format supports only polar stereographic projections");
if (lat_0 != 90)
throw Fmi::Exception(BCP, "Only N-pole polar stereographic projections are supported");
// DUMP(itsGribHandle,"geography");
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib mercator projection metadata
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setMercatorGeometryToGrib() const
{
try
{
gset(itsGribHandle, "typeOfGrid", "mercator");
// Note: grib2 longitude 0-360
double lon = itsBoundingBox.bottomLeft.X();
if ((!itsGrib1Flag) && (lon < 0))
lon += 360;
gset(itsGribHandle, "longitudeOfFirstGridPointInDegrees", lon);
gset(itsGribHandle, "latitudeOfFirstGridPointInDegrees", itsBoundingBox.bottomLeft.Y());
lon = itsBoundingBox.topRight.X();
if ((!itsGrib1Flag) && (lon < 0))
lon += 360;
gset(itsGribHandle, "longitudeOfLastGridPointInDegrees", lon);
gset(itsGribHandle, "latitudeOfLastGridPointInDegrees", itsBoundingBox.topRight.Y());
gset(itsGribHandle, "Ni", itsNX);
gset(itsGribHandle, "Nj", itsNY);
gset(itsGribHandle, "DiInMetres", fabs(itsDX));
gset(itsGribHandle, "DjInMetres", fabs(itsDY));
long iNegative, jPositive;
scanningDirections(iNegative, jPositive);
gset(itsGribHandle, "jScansPositively", jPositive);
gset(itsGribHandle, "iScansNegatively", iNegative);
double lon_0 = 0, lat_ts = 0;
OGRSpatialReference *geometrySRS = itsResources.getGeometrySRS();
if (geometrySRS)
{
lon_0 = getProjParam(*geometrySRS, SRS_PP_CENTRAL_MERIDIAN);
if ((!itsGrib1Flag) && (lon_0 < 0))
lon_0 += 360;
if (EQUAL(itsGridMetaData.projection.c_str(), SRS_PT_MERCATOR_2SP))
{
lat_ts = getProjParam(*geometrySRS, SRS_PP_STANDARD_PARALLEL_1);
}
}
gset(itsGribHandle, "orientationOfTheGridInDegrees", lon_0);
gset(itsGribHandle, "LaDInDegrees", lat_ts);
// DUMP(itsGribHandle,"geography");
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib lambert conformal projection metadata
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setLambertConformalGeometryToGrib() const
{
try
{
OGRSpatialReference *geometrySRS = itsResources.getGeometrySRS();
if (!geometrySRS)
throw Fmi::Exception(BCP, "SRS is not set");
gset(itsGribHandle, "typeOfGrid", "lambert");
// Note: grib2 longitude 0-360
double lon = itsBoundingBox.bottomLeft.X();
if ((!itsGrib1Flag) && (lon < 0))
lon += 360;
gset(itsGribHandle, "longitudeOfFirstGridPointInDegrees", lon);
gset(itsGribHandle, "latitudeOfFirstGridPointInDegrees", itsBoundingBox.bottomLeft.Y());
gset(itsGribHandle, "Nx", itsNX);
gset(itsGribHandle, "Ny", itsNY);
gset(itsGribHandle, "DxInMetres", fabs(itsDX));
gset(itsGribHandle, "DyInMetres", fabs(itsDY));
long iNegative, jPositive;
scanningDirections(iNegative, jPositive);
gset(itsGribHandle, "jScansPositively", jPositive);
gset(itsGribHandle, "iScansNegatively", iNegative);
double southPoleLon = 0;
double southPoleLat = -90;
gset(itsGribHandle, "longitudeOfSouthernPoleInDegrees", southPoleLon);
gset(itsGribHandle, "latitudeOfSouthernPoleInDegrees", southPoleLat);
double lat_ts = getProjParam(*geometrySRS, SRS_PP_LATITUDE_OF_ORIGIN);
double lon_0 = getProjParam(*geometrySRS, SRS_PP_CENTRAL_MERIDIAN);
if ((!itsGrib1Flag) && (lon_0 < 0))
lon_0 += 360;
gset(itsGribHandle, "LaDInDegrees", lat_ts);
gset(itsGribHandle, "LoVInDegrees", lon_0);
double latin1 = getProjParam(*geometrySRS, SRS_PP_STANDARD_PARALLEL_1);
double latin2;
if (EQUAL(itsGridMetaData.projection.c_str(), SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP))
latin2 = getProjParam(*geometrySRS, SRS_PP_STANDARD_PARALLEL_2);
else
latin2 = latin1;
gset(itsGribHandle, "Latin1InDegrees", latin1);
gset(itsGribHandle, "Latin2InDegrees", latin2);
// DUMP(itsGribHandle,"geography");
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib lambert equal area projection metadata
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setLambertAzimuthalEqualAreaGeometryToGrib() const
{
try
{
if (itsGrib1Flag)
throw Fmi::Exception(BCP, "LAEA is not supported in grib1 format");
OGRSpatialReference *geometrySRS = itsResources.getGeometrySRS();
if (!geometrySRS)
throw Fmi::Exception(BCP, "SRS is not set");
gset(itsGribHandle, "typeOfGrid", "lambert_azimuthal_equal_area");
// Note: grib2 longitude 0-360
double lon = itsBoundingBox.bottomLeft.X();
if ((!itsGrib1Flag) && (lon < 0))
lon += 360;
gset(itsGribHandle, "longitudeOfFirstGridPointInDegrees", lon);
gset(itsGribHandle, "latitudeOfFirstGridPointInDegrees", itsBoundingBox.bottomLeft.Y());
gset(itsGribHandle, "Nx", itsNX);
gset(itsGribHandle, "Ny", itsNY);
gset(itsGribHandle, "DxInMetres", fabs(itsDX));
gset(itsGribHandle, "DyInMetres", fabs(itsDY));
long iNegative, jPositive;
scanningDirections(iNegative, jPositive);
gset(itsGribHandle, "jScansPositively", jPositive);
gset(itsGribHandle, "iScansNegatively", iNegative);
double lat_ts = getProjParam(*geometrySRS, SRS_PP_LATITUDE_OF_ORIGIN);
double lon_0 = getProjParam(*geometrySRS, SRS_PP_LONGITUDE_OF_CENTER);
if ((!itsGrib1Flag) && (lon_0 < 0))
lon_0 += 360;
gset(itsGribHandle, "standardParallelInDegrees", lat_ts);
gset(itsGribHandle, "centralLongitudeInDegrees", lon_0);
DUMP(itsGribHandle, "geography");
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib named configuration settings.
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setNamedSettingsToGrib() const
{
try
{
const Producer &pr = itsCfg.getProducer(itsReqParams.producer);
auto setBeg = pr.namedSettingsBegin();
auto setEnd = pr.namedSettingsEnd();
const char *const centre = "centre";
bool hasCentre = false;
for (auto it = setBeg; (it != setEnd); it++)
{
gset(itsGribHandle, (it->first).c_str(), it->second);
if (it->first == centre)
hasCentre = true;
}
// Use default procuder's centre by default
if (!hasCentre)
{
const Producer &dpr = itsCfg.defaultProducer();
const auto dit = dpr.namedSettings.find(centre);
if (dit != dpr.namedSettingsEnd())
gset(itsGribHandle, (dit->first).c_str(), dit->second);
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib projection metadata
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setGeometryToGrib(const NFmiArea *area, bool relative_uv)
{
try
{
int classId = (itsReqParams.areaClassId != A_Native)
? (int) itsReqParams.areaClassId
#ifdef WGS84
: (area->ClassId() == kNFmiProjArea) ? area->DetectClassId() : area->ClassId();
#else
: area->ClassId();
#endif
itsValueArray.resize(itsNX * itsNY);
switch (classId)
{
case kNFmiLatLonArea:
setLatlonGeometryToGrib();
break;
case kNFmiRotatedLatLonArea:
setRotatedLatlonGeometryToGrib(area);
break;
case kNFmiStereographicArea:
setStereographicGeometryToGrib(area);
break;
case kNFmiMercatorArea:
setMercatorGeometryToGrib();
break;
#ifdef WGS84
case kNFmiProjArea:
throw Fmi::Exception(BCP, "Generic PROJ.4 projections not supported yet");
#endif
case kNFmiEquiDistArea:
throw Fmi::Exception(BCP, "Equidistant projection is not supported by GRIB");
case kNFmiGnomonicArea:
throw Fmi::Exception(BCP, "Gnomonic projection is not supported by GRIB");
case kNFmiPKJArea:
throw Fmi::Exception(BCP, "PKJ projection is not supported by GRIB");
case kNFmiYKJArea:
throw Fmi::Exception(BCP, "YKJ projection is not supported by GRIB");
case kNFmiKKJArea:
throw Fmi::Exception(BCP, "KKJ projection is not supported by GRIB");
default:
throw Fmi::Exception(BCP, "Unsupported projection in input data");
}
// Set packing type
if (!itsReqParams.packing.empty())
gset(itsGribHandle, "packingType", itsReqParams.packing);
// Set shape of the earth depending on the datum
long resolAndCompFlags = get_long(itsGribHandle, "resolutionAndComponentFlags");
if (itsGrib1Flag)
{
if (Datum::isDatumShiftToWGS84(itsReqParams.datumShift))
resolAndCompFlags |= (1 << static_cast<int>(Datum::Grib1::Sphere::Wgs84));
else
resolAndCompFlags &= ~(1 << static_cast<int>(Datum::Grib1::Sphere::Wgs84));
}
else
gset(itsGribHandle,
"shapeOfTheEarth",
static_cast<int>((Datum::isDatumShiftToWGS84(itsReqParams.datumShift)
? Datum::Grib2::Sphere::Wgs84
: Datum::Grib2::Sphere::Fmi_6371229m)));
if (relative_uv)
resolAndCompFlags |= (1 << 3);
else
resolAndCompFlags &= ~(1 << 3);
gset(itsGribHandle, "resolutionAndComponentFlags", resolAndCompFlags);
// Bitmap to flag missing values
gset(itsGribHandle, "bitmapPresent", 1);
gset(itsGribHandle, "missingValue", gribMissingValue);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grid origo
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setGridOrigo(const QueryServer::Query &gridQuery)
{
try
{
auto rXAttr = gridQuery.mAttributeList.getAttribute("grid.original.reverseXDirection");
if ((!rXAttr) || ((rXAttr->mValue != "0") && (rXAttr->mValue != "1")))
throw Fmi::Exception::Trace(BCP,
"grid.original.reverseXDirection is missing or has unkown value");
auto rYAttr = gridQuery.mAttributeList.getAttribute("grid.original.reverseYDirection");
if ((!rYAttr) || ((rYAttr->mValue != "0") && (rYAttr->mValue != "1")))
throw Fmi::Exception::Trace(
BCP, "grid.original.reverseYDirection is missing or has unknown value");
bool iNegative = (rXAttr->mValue == "1");
bool jPositive = (rYAttr->mValue == "0");
if ((!iNegative) && (!jPositive))
itsGridOrigo = kTopLeft;
else if (iNegative && (!jPositive))
itsGridOrigo = kTopRight;
else if ((!iNegative) && jPositive)
itsGridOrigo = kBottomLeft;
else
itsGridOrigo = kBottomRight;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grid grib projection metadata
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setGridGeometryToGrib(const QueryServer::Query &gridQuery)
{
try
{
setGridOrigo(gridQuery);
itsValueArray.resize(itsNX * itsNY);
switch (itsGridMetaData.projType)
{
case T::GridProjectionValue::LatLon:
setLatlonGeometryToGrib();
break;
case T::GridProjectionValue::RotatedLatLon:
setRotatedLatlonGeometryToGrib(nullptr);
break;
case T::GridProjectionValue::PolarStereographic:
setStereographicGeometryToGrib(nullptr);
break;
case T::GridProjectionValue::Mercator:
setMercatorGeometryToGrib();
break;
case T::GridProjectionValue::LambertConformal:
setLambertConformalGeometryToGrib();
break;
case T::GridProjectionValue::LambertAzimuthalEqualArea:
setLambertAzimuthalEqualAreaGeometryToGrib();
break;
default:
throw Fmi::Exception(BCP, "Unsupported projection in input data");
}
// Set packing type
if (!itsReqParams.packing.empty())
gset(itsGribHandle, "packingType", itsReqParams.packing);
// Set shape of the earth
long resolAndCompFlags = get_long(itsGribHandle, "resolutionAndComponentFlags");
if (itsGrib1Flag)
{
if (itsGridMetaData.flattening)
resolAndCompFlags |= (1 << static_cast<int>(Datum::Grib1::Sphere::Wgs84));
else
resolAndCompFlags &= ~(1 << static_cast<int>(Datum::Grib1::Sphere::Wgs84));
}
else
{
uint8_t shapeOfTheEarth;
if ((itsGridMetaData.ellipsoid == "WGS 84") ||
((itsGridMetaData.flatteningStr == "298.257223563") &&
(fabs(itsGridMetaData.earthRadiusOrSemiMajorInMeters - 6378137) < 0.01)))
shapeOfTheEarth = 5; // WGS84
else if ((itsGridMetaData.ellipsoid == "GRS 80") ||
((itsGridMetaData.flatteningStr == "298.257222101") &&
(fabs(itsGridMetaData.earthRadiusOrSemiMajorInMeters - 6378137) < 0.01)))
shapeOfTheEarth = 4; // IAG-GRS80
else if (itsGridMetaData.flattening && (fabs(*itsGridMetaData.flattening - 297) < 0.01) &&
(fabs(itsGridMetaData.earthRadiusOrSemiMajorInMeters - 6378160.0) < 0.01))
shapeOfTheEarth = 2; // IAU in 1965
else if (itsGridMetaData.flattening)
throw Fmi::Exception(BCP,
string("Unsupported ellipsoid in input data: ") +
Fmi::to_string(itsGridMetaData.earthRadiusOrSemiMajorInMeters) +
"," + itsGridMetaData.flatteningStr);
else if (fabs(itsGridMetaData.earthRadiusOrSemiMajorInMeters - 6367470.0) < 0.01)
shapeOfTheEarth = 0;
else if (fabs(itsGridMetaData.earthRadiusOrSemiMajorInMeters - 6371229.0) < 0.01)
shapeOfTheEarth = 6;
else
{
// Spherical with radius specified by data producer
shapeOfTheEarth = 1;
}
gset(itsGribHandle, "shapeOfTheEarth", shapeOfTheEarth);
if (shapeOfTheEarth == 1)
{
gset(itsGribHandle, "scaleFactorOfRadiusOfSphericalEarth", 0.0);
gset(itsGribHandle,
"scaledValueOfRadiusOfSphericalEarth",
itsGridMetaData.earthRadiusOrSemiMajorInMeters);
}
}
if (itsGridMetaData.relativeUV)
resolAndCompFlags |= (1 << 3);
else
resolAndCompFlags &= ~(1 << 3);
gset(itsGribHandle, "resolutionAndComponentFlags", resolAndCompFlags);
// Bitmap to flag missing values
gset(itsGribHandle, "bitmapPresent", 1);
gset(itsGribHandle, "missingValue", gribMissingValue);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set grib level and parameter. Parameter's index in config
* table is returned in 'paramIdx'
*
*/
// ----------------------------------------------------------------------
void GribStreamer::setLevelAndParameterToGrib(int level,
const NFmiParam &theParam,
const ParamChangeTable &pTable,
size_t ¶mIdx)
{
// Get parameter id, and configured level type and value for surface data.
//
// Using hardcoded level types for pressure, hybrid and height/depth data and for
// surface data if level configuration is missing.
#define PressureLevel "isobaricInhPa"
#define HybridLevel "hybrid"
#define EntireAtmosphere "entireAtmosphere"
#define HeightLevel "heightAboveSea"
#define DepthLevel "depthBelowSea"
try
{
string centre;
signed long usedParId = theParam.GetIdent();
NFmiLevel *cfgLevel = nullptr;
string levelTypeStr;
size_t i, j;
long templateNumber = 0;
for (i = 0, j = pTable.size(); i < pTable.size(); ++i)
if (usedParId == pTable[i].itsWantedParam.GetIdent())
{
// Preferring entry with level for surface data and without level for pressure and hybrid
// data.
// If preferred entry does not exist, taking the parameter id from the first entry for the
// parameter.
//
cfgLevel = pTable[i].itsLevel;
if ((isSurfaceLevel(itsLevelType) && cfgLevel) ||
(!(isSurfaceLevel(itsLevelType) || cfgLevel)))
break;
if (j == pTable.size())
j = i;
}
if (i >= pTable.size())
i = j;
paramIdx = i;
if (i < pTable.size())
{
usedParId = pTable[i].itsOriginalParamId;
cfgLevel = pTable[i].itsLevel;
centre = pTable[i].itsCentre;
templateNumber = (long)pTable[i].itsTemplateNumber;
}
if (isSurfaceLevel(itsLevelType))
{
if (cfgLevel)
{
levelTypeStr = cfgLevel->GetName();
level = boost::numeric_cast<int>(cfgLevel->LevelValue());
}
else
{
levelTypeStr = EntireAtmosphere;
level = 0;
}
}
else if (isPressureLevel(itsLevelType))
levelTypeStr = PressureLevel;
else if (isHybridLevel(itsLevelType))
levelTypeStr = HybridLevel;
else if (isHeightLevel(itsLevelType, level))
levelTypeStr = HeightLevel;
else if (isDepthLevel(itsLevelType, level))
levelTypeStr = DepthLevel;
else
throw Fmi::Exception(
BCP, "Internal: Unrecognized level type " + boost::lexical_cast<string>(itsLevelType));
if (!centre.empty())
gset(itsGribHandle, "centre", centre);
// Cannot set template number 0 unless stepType has been set
gset(itsGribHandle, "stepType", "instant");
if ((!itsGrib1Flag) && (templateNumber != 0))
gset(itsGribHandle, "productDefinitionTemplateNumber", templateNumber);
gset(itsGribHandle, "paramId", usedParId);
gset(itsGribHandle, "typeOfLevel", levelTypeStr);
gset(itsGribHandle, "level", boost::numeric_cast<long>(abs(level)));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Set step data into grib buffer
*/
// ----------------------------------------------------------------------
void GribStreamer::setStepToGrib(const ParamChangeTable &pTable,
size_t paramIdx,
bool setOriginTime,
const ptime &validTime)
{
try
{
// stepUnits always 'minute' to keep it simple
string stepUnits = "m", stepType;
time_duration fromOriginTime(validTime - itsGribOriginTime);
long step = (fromOriginTime.hours() * 60) + fromOriginTime.minutes();
long startStep = step, endStep = step;
// Set step type and calculate start and end step for aggregates.
//
// Note: There's no metadata available about whether given data/parameter has start or end time
// stamping;
// stamping is selected with boolean 'bDataIsEndTimeStamped'.
const bool bDataIsEndTimeStamped = true;
if ((paramIdx < pTable.size()) && (!pTable[paramIdx].itsStepType.empty()))
{
// Aggregate period length must be the same or multiple of data time step for time steps less
// than day
//
long timeStep = ((itsReqParams.timeStep > 0) ? itsReqParams.timeStep : itsDataTimeStep);
if (timeStep <= 0)
throw Fmi::Exception(BCP,
"Invalid data timestep " + boost::lexical_cast<string>(timeStep) +
" for producer '" + itsReqParams.producer + "'");
if (pTable[paramIdx].itsPeriodLengthMinutes > 0)
{
if (((itsDataTimeStep < minutesInDay) &&
(pTable[paramIdx].itsPeriodLengthMinutes % itsDataTimeStep)) ||
((timeStep >= minutesInDay) && (pTable[paramIdx].itsPeriodLengthMinutes != timeStep)) ||
(timeStep > minutesInMonth))
throw Fmi::Exception(
BCP,
"Aggregate period length " +
boost::lexical_cast<string>(pTable[paramIdx].itsPeriodLengthMinutes) +
" min is not valid for data time step " + boost::lexical_cast<string>(timeStep) +
" min");
if (timeStep < minutesInDay)
{
time_duration td(validTime.time_of_day());
long validTimeMinutes = (td.hours() * 60) + td.minutes();
long periodLengthMinutes = pTable[paramIdx].itsPeriodLengthMinutes;
long periodStartMinutes = (validTimeMinutes / periodLengthMinutes) * periodLengthMinutes;
if (bDataIsEndTimeStamped)
{
// Use validtime as end step
//
if (periodStartMinutes == validTimeMinutes)
{
// Set start step backwards to the start of ending/full aggregate period
//
startStep = step - periodLengthMinutes;
}
else
{
// Set start step backwards to the start of current/incomplete aggregate period
//
startStep = step - (validTimeMinutes - periodStartMinutes);
}
}
else
{
// Set start step to the start of current/incomplete aggregate period and advance end
// step
//
startStep = step - (validTimeMinutes - periodStartMinutes);
endStep += itsDataTimeStep;
}
}
}
if (timeStep >= minutesInDay)
{
// Note: For daily and monthly data aggregate period length (if given/nonzero) must equal
// time
// step;
// we do not support cumulative aggregates
//
ptime validTimeDate = ptime(validTime.date()), periodStart, periodEnd;
if (bDataIsEndTimeStamped)
{
if (timeStep == minutesInDay)
{
// Previous day
//
periodStart = ptime((validTimeDate - time_duration(1, 0, 0)).date());
periodEnd = validTimeDate;
}
else
{
// Previous month
//
boost::gregorian::date d((validTimeDate - time_duration(1, 0, 0)).date());
periodStart = ptime(boost::gregorian::date(d.year(), d.month(), 1));
periodEnd = ptime(boost::gregorian::date(
validTimeDate.date().year(), validTimeDate.date().month(), 1));
}
}
else
{
if (timeStep == minutesInDay)
{
// Current day
//
periodStart = validTimeDate;
periodEnd = ptime((periodStart + time_duration(25, 0, 0)).date());
}
else
{
// Current month
//
periodStart = ptime(boost::gregorian::date(
validTimeDate.date().year(), validTimeDate.date().month(), 1));
ptime t(periodStart + time_duration(32 * 24, 0, 0));
periodEnd = ptime(boost::gregorian::date(t.date().year(), t.date().month(), 1));
}
}
startStep = (periodStart - itsGribOriginTime).hours() * 60;
endStep = (periodEnd - itsGribOriginTime).hours() * 60;
}
if (startStep < 0)
{
// Can't be negative, set start step to 0 and adjust origintime and end step accordingly
//
itsGribOriginTime -= time_duration(0, -startStep, 0);
endStep -= startStep;
startStep = 0;
setOriginTime = true;
}
gset(itsGribHandle, "stepType", pTable[paramIdx].itsStepType);
}
if (setOriginTime)
{
boost::gregorian::date d = itsGribOriginTime.date();
time_duration t = itsGribOriginTime.time_of_day();
long dateLong = d.year() * 10000 + d.month() * 100 + d.day();
long timeLong = t.hours() * 100 + t.minutes();
gset(itsGribHandle, "date", dateLong);
gset(itsGribHandle, "time", timeLong);
}
// Set time step and unit
gset(itsGribHandle, "stepUnits", stepUnits);
gset(itsGribHandle, "startStep", startStep);
gset(itsGribHandle, "endStep", endStep);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return time adjusted backwards to even timestep
*
*/
// ----------------------------------------------------------------------
ptime adjustToTimeStep(const ptime &pt, long timeStepInMinutes)
{
try
{
if (timeStepInMinutes <= 0)
throw Fmi::Exception(BCP,
"adjustToTimeStep: Invalid data timestep " +
boost::lexical_cast<string>(timeStepInMinutes));
if ((timeStepInMinutes == 60) || (timeStepInMinutes == 180) || (timeStepInMinutes == 360) ||
(timeStepInMinutes == 720))
return ptime(pt.date(),
time_duration(pt.time_of_day().hours() -
(pt.time_of_day().hours() % (timeStepInMinutes / 60)),
0,
0));
else if (timeStepInMinutes == DataStreamer::minutesInDay)
return ptime(pt.date(), time_duration(0, 0, 0));
else if (timeStepInMinutes == DataStreamer::minutesInMonth)
return ptime(boost::gregorian::date(pt.date().year(), pt.date().month(), 1),
time_duration(0, 0, 0));
return pt;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Copy data (one level/param/time grid) into grib buffer
*
*/
// ----------------------------------------------------------------------
void GribStreamer::addValuesToGrib(Engine::Querydata::Q q,
const NFmiMetTime &vTime,
int level,
const NFmiDataMatrix<float> &dataValues,
float scale,
float offset)
{
try
{
// Set named configuration settings
setNamedSettingsToGrib();
// Use first validtime as origintime if it is earlier than the origintime.
//
// Note: originTime is unset (is_not_a_date_time()) when called for first time instant.
//
// If the actual data origintime is used, adjust it backwards to even data timestep;
// the output validtimes are set as number of timesteps forwards from the origintime.
ptime oTime = q->originTime();
ptime validTime = vTime;
bool setOriginTime = (itsOriginTime.is_not_a_date_time() || (itsOriginTime != oTime));
if (setOriginTime)
{
// Set origintime
//
itsOriginTime = oTime;
itsGribOriginTime =
((validTime < itsOriginTime) ? validTime
: adjustToTimeStep(itsOriginTime, itsDataTimeStep));
}
// Set level and parameter. Parameter's index in 'ptable' is returned in paramIdx (needed in
// setStep())
NFmiParam param(*(q->param().GetParam()));
const ParamChangeTable &pTable = itsCfg.getParamChangeTable();
size_t paramIdx = pTable.size();
setLevelAndParameterToGrib(level, param, pTable, paramIdx);
// Set start and end step and step type (for average, cumulative etc. data)
setStepToGrib(pTable, paramIdx, setOriginTime, validTime);
// Load the data, cropping the grid/values it if manual cropping is set
bool cropxy = (itsCropping.cropped && itsCropping.cropMan);
size_t x0 = (cropxy ? itsCropping.bottomLeftX : 0), y0 = (cropxy ? itsCropping.bottomLeftY : 0);
size_t xN = (itsCropping.cropped ? (x0 + itsCropping.gridSizeX) : itsReqGridSizeX);
size_t yN = (itsCropping.cropped ? (y0 + itsCropping.gridSizeY) : itsReqGridSizeY);
size_t xStep = (itsReqParams.gridStepXY ? (*(itsReqParams.gridStepXY))[0].first : 1),
yStep = (itsReqParams.gridStepXY ? (*(itsReqParams.gridStepXY))[0].second : 1), x, y;
int i = 0;
for (y = y0; (y < yN); y += yStep)
for (x = x0; (x < xN); x += xStep, i++)
{
float value = dataValues[x][y];
if (value != kFloatMissing)
itsValueArray[i] = (value + offset) / scale;
else
itsValueArray[i] = gribMissingValue;
}
grib_set_double_array(itsGribHandle, "values", &itsValueArray[0], itsValueArray.size());
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Copy grid data (one level/param/time grid) into grib buffer
*
*/
// ----------------------------------------------------------------------
void GribStreamer::addGridValuesToGrib(const QueryServer::Query &gridQuery,
const NFmiMetTime &vTime,
int level,
float scale,
float offset)
{
try
{
// Set named configuration settings
setNamedSettingsToGrib();
// Use first validtime as origintime if it is earlier than the origintime.
//
// Note: originTime is unset (is_not_a_date_time()) when called for first time instant.
//
// If the actual data origintime is used, adjust it backwards to even data timestep;
// the output validtimes are set as number of timesteps forwards from the origintime.
ptime oTime = itsGridMetaData.gridOriginTime, validTime = vTime;
bool setOriginTime = (itsOriginTime.is_not_a_date_time() || (itsOriginTime != oTime));
if (setOriginTime)
{
// Set origintime
//
itsOriginTime = oTime;
itsGribOriginTime =
((validTime < itsOriginTime) ? validTime
: adjustToTimeStep(itsOriginTime, itsDataTimeStep));
}
// Set level and parameter. Parameter's index in 'ptable' is returned in paramIdx (needed in
// setStep())
NFmiParam param(itsParamIterator->number());
const ParamChangeTable &pTable = itsCfg.getParamChangeTable();
size_t paramIdx = pTable.size();
setLevelAndParameterToGrib(level, param, pTable, paramIdx);
// Set start and end step and step type (for average, cumulative etc. data)
setStepToGrib(pTable, paramIdx, setOriginTime, validTime);
// Load the data, cropping the grid/values it if manual cropping is set
bool cropxy = (itsCropping.cropped && itsCropping.cropMan);
size_t x0 = (cropxy ? itsCropping.bottomLeftX : 0), y0 = (cropxy ? itsCropping.bottomLeftY : 0);
size_t xN = (itsCropping.cropped ? (x0 + itsCropping.gridSizeX) : itsReqGridSizeX),
yN = (itsCropping.cropped ? (y0 + itsCropping.gridSizeY) : itsReqGridSizeY);
size_t xStep = (itsReqParams.gridStepXY ? (*(itsReqParams.gridStepXY))[0].first : 1),
yStep = (itsReqParams.gridStepXY ? (*(itsReqParams.gridStepXY))[0].second : 1), x, y;
int i = 0;
auto dataValues = gridQuery.mQueryParameterList.front().mValueList.front()->mValueVector;
for (y = y0; (y < yN); y += yStep)
for (x = x0; (x < xN); x += xStep, i++)
{
float value = dataValues[i];
if (value != ParamValueMissing)
itsValueArray[i] = (value + offset) / scale;
else
itsValueArray[i] = gribMissingValue;
}
grib_set_double_array(itsGribHandle, "values", &itsValueArray[0], itsValueArray.size());
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Add given data values and return complete grib message
*/
// ----------------------------------------------------------------------
string GribStreamer::getGribMessage(Engine::Querydata::Q q,
int level,
const NFmiMetTime &mt,
const NFmiDataMatrix<float> &values,
float scale,
float offset)
{
try
{
addValuesToGrib(q, mt, level, values, scale, offset);
const void *mesg;
size_t mesg_len;
grib_get_message(itsGribHandle, &mesg, &mesg_len);
if (mesg_len == 0)
throw Fmi::Exception(BCP, "Empty grib message returned");
return string((const char *)mesg, mesg_len);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Add given grid data values and return complete grib message
*/
// ----------------------------------------------------------------------
string GribStreamer::getGridGribMessage(const QueryServer::Query &gridQuery,
int level,
const NFmiMetTime &mt,
float scale,
float offset)
{
try
{
addGridValuesToGrib(gridQuery, mt, level, scale, offset);
const void *mesg;
size_t mesg_len;
grib_get_message(itsGribHandle, &mesg, &mesg_len);
if (mesg_len == 0)
throw Fmi::Exception(BCP, "Empty grib message returned");
return string((const char *)mesg, mesg_len);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get next chunk of data. Called from SmartMet server code
*
*/
// ----------------------------------------------------------------------
std::string GribStreamer::getChunk()
{
try
{
try
{
ostringstream chunkBuf;
string chunk;
size_t chunkBufLength = 0, nChunks = 0;
while (!itsDoneFlag)
{
// Get next chunk e.g. next param/level/validtime grid
//
extractData(chunk);
nChunks++;
if (chunk.empty())
itsDoneFlag = true;
else
chunkBufLength += chunk.length();
// To avoid small chunk transfer overhead collect chunks until max chunk length or max count
// of
// collected chunks are reached
if (itsDoneFlag || (nChunks >= itsMaxMsgChunks) || (chunkBufLength >= itsChunkLength))
{
if (itsDoneFlag)
setStatus(ContentStreamer::StreamerStatus::EXIT_OK);
if (nChunks > 1)
{
chunkBuf << chunk;
return chunkBuf.str();
}
return chunk;
}
chunkBuf << chunk;
}
return chunk;
}
catch (...)
{
Fmi::Exception exception(BCP, "Request processing exception!", nullptr);
exception.addParameter("URI", itsRequest.getURI());
std::cerr << exception.getStackTrace();
}
setStatus(ContentStreamer::StreamerStatus::EXIT_ERROR);
itsDoneFlag = true;
return "";
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Load chunk of data; called by DataStreamer to get format specific chunk.
*
*/
// ----------------------------------------------------------------------
void GribStreamer::getDataChunk(Engine::Querydata::Q q,
const NFmiArea *area,
NFmiGrid * /* grid */,
int level,
const NFmiMetTime &mt,
NFmiDataMatrix<float> &values,
string &chunk)
{
try
{
if (itsMetaFlag)
{
// Set geometry
//
setGeometryToGrib(area, q->isRelativeUV());
itsMetaFlag = false;
}
// Build and get grib message
chunk =
getGribMessage(q, level, mt, values, itsScalingIterator->first, itsScalingIterator->second);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Load chunk of grid data; called by DataStreamer to get format specific chunk.
*
*/
// ----------------------------------------------------------------------
void GribStreamer::getGridDataChunk(const QueryServer::Query &gridQuery,
int level,
const NFmiMetTime &mt,
string &chunk)
{
try
{
if (itsMetaFlag)
{
// Set geometry
//
setGridGeometryToGrib(gridQuery);
itsMetaFlag = false;
}
// Build and get grib message
chunk = getGridGribMessage(
gridQuery, level, mt, itsScalingIterator->first, itsScalingIterator->second);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
} // namespace Download
} // namespace Plugin
} // namespace SmartMet
| 30.882096 | 100 | 0.582539 | [
"geometry",
"shape",
"vector"
] |
a89e23daefc0c294cedb5c45bef23b4cdbb0f4ff | 1,179 | cpp | C++ | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/13_Exams/17 November 2019/3.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/13_Exams/17 November 2019/3.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/13_Exams/17 November 2019/3.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <map>
#include <vector>
#include <sstream>
using namespace std;
void readStringVectorFromStringStream(vector<string>& vect, string inputLine);
int main()
{
map<int, vector<string>> resultDict;
int n = 0; cin >> n; cin.ignore();
for (int i = 0; i < n; i++) {
string inputLine = ""; getline(cin, inputLine);
vector<string> stringVect; readStringVectorFromStringStream(stringVect, inputLine);
int n1 = stoi(stringVect[0]);
string oper = stringVect[1];
int n2 = stoi(stringVect[2]);
int res = 0;
if (oper == "+") {
res = n1 + n2;
} else if (oper == "-") {
res = n1 - n2;
} else if (oper == "*") {
res = n1 * n2;
} else if (oper == "/") {
res = n1 / n2;
} else if (oper == "%") {
res = n1 % n2;
}
//cout << res << endl;
resultDict[res].push_back(inputLine);
}
for (auto iter = resultDict.rbegin(); iter != resultDict.rend(); ++iter) {
for (auto line : iter->second) {
cout << line << endl;
}
}
}
void readStringVectorFromStringStream(vector<string>& vect, string inputLine) {
istringstream input(inputLine);
string el;
while (input >> el) {
vect.push_back(el);
}
} | 21.436364 | 85 | 0.612383 | [
"vector"
] |
a8ad9feea1a441f42daa4c686085ffe9bf880df1 | 5,796 | cpp | C++ | src/keystore.cpp | jack-spring/freetradechain | 79b852e86301153ad4e05e0665fb6167a7c3ac14 | [
"MIT"
] | null | null | null | src/keystore.cpp | jack-spring/freetradechain | 79b852e86301153ad4e05e0665fb6167a7c3ac14 | [
"MIT"
] | null | null | null | src/keystore.cpp | jack-spring/freetradechain | 79b852e86301153ad4e05e0665fb6167a7c3ac14 | [
"MIT"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2016 The Coin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "keystore.h"
#include "wallet/wallet.h"
#include "crypter.h"
#include "key.h"
#include "base58.h"
using namespace json_spirit;
Object CKeyCombi::ToJsonObj() const {
Object reply;
if (m_cMainCkey.IsValid()) {
reply.push_back(Pair("address", m_cMainCkey.GetPubKey().GetKeyID().ToAddress()));
reply.push_back(Pair("mCkey", m_cMainCkey.ToString()));
reply.push_back(Pair("mCkeyBase58", CCoinSecret(m_cMainCkey).ToString()));
reply.push_back(Pair("mMainPk", m_cMainCkey.GetPubKey().ToString()));
}
if (m_cMinerCkey.IsValid()) {
reply.push_back(Pair("m_cMinerCkey", m_cMinerCkey.ToString()));
reply.push_back(Pair("mMinerCkeyBase58", CCoinSecret(m_cMinerCkey).ToString()));
reply.push_back(Pair("mMinerPk", m_cMinerCkey.GetPubKey().ToString()));
}
reply.push_back(Pair("m_llCreationTime", m_llCreationTime));
return std::move(reply);
}
bool CKeyCombi::UnSersailFromJson(const Object& obj) {
try {
Object reply;
const Value& mCKey = find_value(obj, "mCkey");
if (mCKey.type() != json_spirit::null_type) {
auto const &tem1 = ::ParseHex(mCKey.get_str());
m_cMainCkey.Set(tem1.begin(), tem1.end(), true);
}
const Value& mMinerKey = find_value(obj, "m_cMinerCkey");
if (mMinerKey.type() != json_spirit::null_type) {
auto const &tem2 = ::ParseHex(mMinerKey.get_str());
m_cMinerCkey.Set(tem2.begin(), tem2.end(), true);
}
const Value& nTime = find_value(obj, "m_llCreationTime").get_int64();
if (nTime.type() != json_spirit::null_type) {
m_llCreationTime = find_value(obj, "m_llCreationTime").get_int64();
}
} catch (...) {
ERRORMSG("UnSersailFromJson Failed !");
return false;
}
return true;
}
bool CKeyCombi::CleanAll() {
m_cMainCkey.Clear();
m_cMinerCkey.Clear();
m_cMainPKey = CPubKey();
m_cMinerPKey = CPubKey();
m_llCreationTime = 0;
return true;
}
bool CKeyCombi::CleanMainKey() {
return m_cMainCkey.Clear();
}
CKeyCombi::CKeyCombi(const CKey& cInkey, int nVersion) {
assert(cInkey.IsValid());
CleanAll();
m_cMainCkey = cInkey;
if (EM_FEATURE_BASE == nVersion) {
m_cMainPKey = m_cMainCkey.GetPubKey();
}
m_llCreationTime = GetTime();
}
CKeyCombi::CKeyCombi(const CKey& cInkey, const CKey& cMinerKey, int nVersion) {
assert(cInkey.IsValid());
assert(cMinerKey.IsValid());
CleanAll();
m_cMinerCkey = cMinerKey;
m_cMainCkey = cInkey;
if (EM_FEATURE_BASE == nVersion) {
m_cMainPKey = m_cMainCkey.GetPubKey();
m_cMinerPKey = m_cMinerCkey.GetPubKey();
}
m_llCreationTime = GetTime();
}
bool CKeyCombi::GetPubKey(CPubKey& cOutKey, bool bIsMine) const {
if (bIsMine == true) {
if (m_cMinerCkey.IsValid()) {
cOutKey = m_cMinerCkey.GetPubKey();
return true;
}
return false;
}
cOutKey = m_cMainCkey.GetPubKey();
return true;
}
string CKeyCombi::ToString() const {
string str("");
if (m_cMainCkey.IsValid()) {
str += strprintf(" MainPKey:%s MainKey:%s", m_cMainCkey.GetPubKey().ToString(), m_cMainCkey.ToString());
}
if (m_cMinerCkey.IsValid()) {
str += strprintf(" MinerPKey:%s MinerKey:%s",m_cMinerCkey.GetPubKey().ToString(), m_cMinerCkey.ToString());
}
str += strprintf(" CreationTime:%d", m_llCreationTime);
return str;
}
bool CKeyCombi::GetCKey(CKey& ckeyOut, bool bIsMine) const {
if (bIsMine) {
ckeyOut = m_cMinerCkey;
} else {
ckeyOut = m_cMainCkey;
}
return ckeyOut.IsValid();
}
bool CKeyCombi::CreateANewKey() {
CleanAll();
m_cMainCkey.MakeNewKey();
m_llCreationTime = GetTime();
return true;
}
CKeyCombi::CKeyCombi() {
CleanAll();
}
int64_t CKeyCombi::GetBirthDay() const {
return m_llCreationTime;
}
CKeyID CKeyCombi::GetCKeyID() const {
if (m_cMainCkey.IsValid()) {
return m_cMainCkey.GetPubKey().GetKeyID();
} else {
CKeyID cKeyId;
return cKeyId;
}
}
void CKeyCombi::SetMainKey(CKey& cMainKey) {
m_cMainCkey = cMainKey;
}
void CKeyCombi::SetMinerKey(CKey & cMinerKey) {
m_cMinerCkey = cMinerKey;
}
bool CKeyCombi::IsContainMinerKey() const {
return m_cMinerCkey.IsValid();
}
bool CKeyCombi::IsContainMainKey() const {
return m_cMainCkey.IsValid();
}
bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut, bool IsMine) const
{
CKey cKey;
if (!GetKey(address, cKey, IsMine)) {
return false;
}
vchPubKeyOut = cKey.GetPubKey();
return true;
}
//
//bool CKeyStore::AddKey(const CKey &key) {
// return AddKeyPubKey(key, key.GetPubKey());
//}
bool CBasicKeyStore::AddKeyCombi(const CKeyID & cKeyId, const CKeyCombi &cKeyCombi)
{
LOCK(cs_KeyStore);
mapKeys[cKeyId] = cKeyCombi;
return true;
}
bool CBasicKeyStore::GetKeyCombi(const CKeyID & cAddress, CKeyCombi & cKeyCombiOut) const {
{
LOCK(cs_KeyStore);
KeyMap::const_iterator mi = mapKeys.find(cAddress);
if (mi != mapKeys.end()) {
cKeyCombiOut = mi->second;
return true;
}
}
return false;
}
//bool CBasicKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
//{
// LOCK(cs_KeyStore);
// mapKeys[pubkey.GetKeyID()] = key;
// return true;
//}
//bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
//{
// LOCK(cs_KeyStore);
// mapScripts[redeemScript.GetID()] = redeemScript;
// return true;
//}
//
//bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
//{
// LOCK(cs_KeyStore);
// return mapScripts.count(hash) > 0;
//}
//bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
//{
// LOCK(cs_KeyStore);
// ScriptMap::const_iterator mi = mapScripts.find(hash);
// if (mi != mapScripts.end())
// {
// redeemScriptOut = (*mi).second;
// return true;
// }
// return false;
//}
| 25.2 | 109 | 0.698758 | [
"object"
] |
a8b8986409d1370bf56d0d08569bb37491c0bd7a | 3,389 | cc | C++ | cogrob_ros/auto_dock_logging/src/workspace/util/file_system.cc | CogRob/TritonBot | d05b521ec7a7f54a04409f5a2897f3e5c75fd3bf | [
"BSD-3-Clause"
] | 8 | 2018-09-21T09:56:02.000Z | 2021-07-26T14:35:14.000Z | cogrob_ros/speak_text_logging/src/workspace/util/file_system.cc | CogRob/TritonBot | d05b521ec7a7f54a04409f5a2897f3e5c75fd3bf | [
"BSD-3-Clause"
] | null | null | null | cogrob_ros/speak_text_logging/src/workspace/util/file_system.cc | CogRob/TritonBot | d05b521ec7a7f54a04409f5a2897f3e5c75fd3bf | [
"BSD-3-Clause"
] | 4 | 2018-08-26T21:44:52.000Z | 2019-08-22T07:38:08.000Z | // Copyright (c) 2018, The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the University of California nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF CALIFORNIA
// 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 "util/file_system.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "third_party/glog.h"
using std::string;
using std::vector;
namespace util {
namespace internal {
void StringSplit(const string& input, char delim, vector<string>* result) {
size_t begin = 0;
size_t current = input.find(delim);
while (current != string::npos) {
result->push_back(input.substr(begin, current - begin));
begin = current + 1;
current = input.find(delim, begin);
}
if (begin <= input.length()) {
result->push_back(input.substr(begin, input.length() - current));
}
}
} // namespace internal
namespace {
} // namespace
Status MakeDirectories(const string& path_in) {
string path = path_in;
while (path.length() > 0 && path[path.length() - 1] == '/') {
path.pop_back();
}
if (path.length() == 0) {
return Status(util::error::INVALID_ARGUMENT, "Empty path string.");
}
if (path[0] != '/') {
return Status(util::error::INVALID_ARGUMENT, "Abosulte path required.");
}
vector<string> path_components;
internal::StringSplit(path, '/', &path_components);
CHECK_GT(path_components.size(), 0);
CHECK_EQ(path_components[0], "");
string current_path;
for (int i = 1; i < path_components.size(); ++i) {
current_path += "/" + path_components[i];
// Checks if current_path already exisits
int mkdir_status =
mkdir(current_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (mkdir_status) {
// There is an error.
if (errno == EEXIST) {
// It is ok.
} else {
return Status(util::error::UNKNOWN, "Create " + current_path
+ " failed, errno = " + std::to_string(errno));
}
}
}
return Status::OK;
}
} // namespace util
| 35.302083 | 80 | 0.699026 | [
"vector"
] |
a8c076dfffbb967038cdca7233ad783b6b8ede18 | 60,791 | cpp | C++ | src/pegasus/regmod/main.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | 4 | 2015-12-16T06:43:14.000Z | 2020-01-24T06:05:47.000Z | src/pegasus/regmod/main.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | null | null | null | src/pegasus/regmod/main.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | null | null | null | /*
**==============================================================================
**
** Copyright (c) 2003 - 2009, Michael Brasher, Karl Schopmeyer
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
**
**==============================================================================
*/
#include <cimple/config.h>
#include <pegasus/utils/pegasus.h>
#include <Pegasus/Client/CIMClient.h>
#include <string>
#include <sys/types.h>
#include <dlfcn.h>
#include <sys/stat.h>
#include <getopt.h>
#include <cstdarg>
#include <vector>
#include <cstdio>
#include <dirent.h>
#include <unistd.h>
#include <cimple/cimple.h>
#include <cimple/Provider_Handle.h>
#include <pegasus/utils/Str.h>
#include <util/util.h>
#include "usage.h"
#define REGISTRATION_NAMESPACE "root/PG_InterOp"
#define DEFAULT_PROVIDING_NAMESPACE "root/cimv2"
#define INCOMPATIBLE \
"provider class not compatible with same class in Pegasus repository: %s. "
using namespace std;
using namespace Pegasus;
const char NO_EMBEDDED_INSTANCES[] =
"Encountered usage of embedded instances "
"but CIMPLE not configured with --enable-embedded-instances";
enum UserContext
{
USER_CONTEXT_REQUESTOR = 2,
USER_CONTEXT_DESIGNATED = 3,
USER_CONTEXT_PRIVILEGED = 4,
USER_CONTEXT_CIMSERVER = 5,
};
static const cimple::Meta_Class* const* _meta_classes = 0;
static size_t _num_meta_classes = 0;
void create_class(
CIMClient& client,
const String& ns,
const cimple::Meta_Class* mc);
void check_class_compatibility(
CIMClient& client,
const String& ns,
const cimple::Meta_Class* mc,
CIMClass& c);
//------------------------------------------------------------------------------
//
// Options:
//
//------------------------------------------------------------------------------
bool class_opt = false;
bool verbose_opt = false;
bool subclass_opt = false;
bool dump_opt = false;
bool help_opt = false;
bool cmpi_opt = false;
bool pegasus_cxx_opt = false;
bool unregister_opt = false;
bool indirect_opt = false;
Array<String> providing_namespaces;
bool absolute_opt = false;
string user_opt;
//------------------------------------------------------------------------------
//
// g_handle
//
//------------------------------------------------------------------------------
void* g_handle = 0;
//------------------------------------------------------------------------------
//
// print()
//
//------------------------------------------------------------------------------
static void _print_elem(const String& x)
{
cout << '"' << x << '"';
}
static void _print_elem(Uint16 x)
{
cout << x;
}
template<class T>
static void _print_value(const CIMValue& v, T*)
{
if (v.isNull())
{
cout << "NULL;";
return;
}
if (v.isArray())
{
Array<T> x;
v.get(x);
cout << "{";
for (Uint32 i = 0; i < x.size(); i++)
{
_print_elem(x[i]);
if (i + 1 != x.size())
cout << ", ";
}
cout << "};";
}
else
{
T x;
v.get(x);
_print_elem(x);
cout << ';';
}
}
void print(CIMInstance& inst)
{
cout << "instance of " << inst.getClassName().getString() << endl;
cout << "{" << endl;
for (Uint32 i = 0; i < inst.getPropertyCount(); i++)
{
CIMProperty prop = inst.getProperty(i);
// Output the name:
cout << " " << prop.getName().getString() << " = ";
const CIMValue& v = prop.getValue();
switch (prop.getType())
{
case CIMTYPE_STRING:
_print_value(v, (String*)0);
break;
case CIMTYPE_UINT16:
_print_value(v, (Uint16*)0);
break;
default:
;
}
cout << endl;
}
cout << "};\n" << endl;
}
int delete_instance(
CIMClient& client,
const char* name_space,
const char* object_path)
{
try
{
if (verbose_opt)
printf("delete_instance(%s, %s)\n", name_space, object_path);
client.deleteInstance(name_space, CIMObjectPath(object_path));
if (verbose_opt)
printf("delete_instance(%s, %s): okay\n", name_space, object_path);
return 0;
}
catch (CIMException& e)
{
if (verbose_opt)
{
printf("delete_instance(%s, %s): error: %s\n",
name_space, object_path, *cimple::Str(e));
}
return -1;
}
catch (Exception& e)
{
if (verbose_opt)
{
printf("delete_instance(%s, %s): error: %s\n",
name_space, object_path, *cimple::Str(e));
}
return -1;
}
catch (...)
{
if (verbose_opt)
{
printf("delete_instance(%s, %s): error: unknown exception\n",
name_space, object_path);
}
return -1;
}
// Unreachable!
return -1;
}
int get_instance(
CIMClient& client,
const char* name_space,
const char* object_path,
CIMInstance& ci)
{
try
{
if (verbose_opt)
printf("get_instance(%s, %s)\n", name_space, object_path);
ci = client.getInstance(name_space, CIMObjectPath(object_path));
if (verbose_opt)
printf("get_instance(%s, %s): okay\n", name_space, object_path);
return 0;
}
catch (CIMException& e)
{
if (verbose_opt)
{
printf("get_instance(%s, %s): error: %s\n",
name_space, object_path, *cimple::Str(e));
}
return -1;
}
catch (Exception& e)
{
if (verbose_opt)
{
printf("get_instance(%s, %s): error: %s\n",
name_space, object_path, *cimple::Str(e));
}
return -1;
}
catch (...)
{
if (verbose_opt)
{
printf("get_instance(%s, %s): error: unknown exception\n",
name_space, object_path);
}
return -1;
}
// Unreachable!
return -1;
}
int create_instance(
CIMClient& client,
const char* name_space,
CIMInstance& ci)
{
CString cstr = ci.getPath().toString().getCString();
const char* object_path = cstr;
try
{
if (verbose_opt)
printf("create_instance(%s, %s)\n", name_space, object_path);
client.createInstance(name_space, ci);
if (verbose_opt)
printf("create_instance(%s, %s): okay\n", name_space, object_path);
return 0;
}
catch (CIMException& e)
{
if (verbose_opt)
{
printf("create_instance(%s, %s): error: %s\n",
name_space, object_path, *cimple::Str(e));
}
return -1;
}
catch (Exception& e)
{
if (verbose_opt)
{
printf("create_instance(%s, %s): error: %s\n",
name_space, object_path, *cimple::Str(e));
}
return -1;
}
catch (...)
{
if (verbose_opt)
{
printf("create_instance(%s, %s): error: unknown exception\n",
name_space, object_path);
}
return -1;
}
// Unreachable!
return -1;
}
//------------------------------------------------------------------------------
//
// load_file()
//
//------------------------------------------------------------------------------
int load_file(const char* path, string& s)
{
FILE* is = fopen(path, "rb");
if (!is)
return -1;
s.erase(s.begin(), s.end());
int c;
while ((c = fgetc(is)) != EOF)
s += c;
fclose(is);
return 0;
}
//------------------------------------------------------------------------------
//
// load_module()
//
//------------------------------------------------------------------------------
cimple::Registration* load_module(
const string& path,
const cimple::Meta_Class* const*& meta_classes,
size_t& num_meta_classes)
{
// Open library:
g_handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
if (!g_handle)
err("cannot load library: %s: %s", path.c_str(), dlerror());
// Figure out which adapter is being used (pegasus or cmpi).
if (dlsym(g_handle, "PegasusCreateProvider"))
{
pegasus_cxx_opt = true;
if (!dump_opt)
printf("Using Pegasus C++ provider interface\n");
if (!dlsym(g_handle, "PegasusCreateProvider"))
err("missing PegasusCreateProvider() entry point: %s: %s",
path.c_str(), dlerror());
}
else
{
cmpi_opt = true;
if (!dump_opt)
printf("Using CMPI provider interface\n");
}
// Get symbol:
const char SYMBOL[] = "cimple_module";
cimple::Module_Proc module_proc =
(cimple::Module_Proc)dlsym(g_handle, SYMBOL);
if (!module_proc)
{
err("cannot find symbol \"%s\" in library %s: %s",
SYMBOL, path.c_str(), dlerror());
}
// Call proc:
cimple::Registration* reg = module_proc();
// Get the meta-repository
cimple::Provider_Handle handle(reg);
const cimple::Meta_Repository* mr = 0;
cimple::Get_Repository_Status status = handle.get_repository(mr);
if (mr == 0)
{
err("Provider is missing meta class repository. This probably means "
"the -r option was not used when the provider class was generated "
"with genclass. Try \"genclass -r <class-name>\" and remember to "
"link in the repository.cpp that it generates.");
}
meta_classes = mr->meta_classes;
num_meta_classes = mr->num_meta_classes;
return reg;
}
//------------------------------------------------------------------------------
//
// unregister_provider()
//
//------------------------------------------------------------------------------
void delete_capabilities(
CIMClient& client,
const string& module_name,
const string& provider_name,
const string& class_name)
{
char buf[1024];
sprintf(buf,
"PG_ProviderCapabilities."
"ProviderName=\"%s\","
"ProviderModuleName=\"%s\","
"CapabilityID=\"%s\"",
provider_name.c_str(),
module_name.c_str(),
class_name.c_str());
if (!dump_opt)
{
delete_instance(client, REGISTRATION_NAMESPACE, buf);
}
}
void unregister_provider(
CIMClient& client,
const string& module_name,
const string& provider_name,
const string& class_name,
const cimple::Meta_Class* meta_class)
{
if (verbose_opt)
printf("=== Deleting provider registration instances\n");
String cn = class_name.c_str();
// Delete the PG_Provider instance.
try
{
char buf[1024];
sprintf(buf,
"PG_Provider.Name=\"%s\","
"ProviderModuleName=\"%s\"",
provider_name.c_str(),
module_name.c_str());
if (!dump_opt)
{
delete_instance(client, REGISTRATION_NAMESPACE, buf);
}
}
catch (...)
{
#ifdef TRACE
fprintf(stderr, "ignored: %d\n", __LINE__);
#endif
}
// Delete the PG_ProviderCapabilities instance.
try
{
if (subclass_opt)
{
for (size_t i = 0; i < _num_meta_classes; i++)
{
if (cimple::is_subclass(meta_class, _meta_classes[i]))
{
delete_capabilities(
client,
module_name,
provider_name,
_meta_classes[i]->name);
}
}
}
else
{
delete_capabilities(
client,
module_name,
provider_name,
class_name);
}
}
catch (...)
{
#ifdef TRACE
fprintf(stderr, "ignored: %d\n", __LINE__);
#endif
}
}
//------------------------------------------------------------------------------
//
// unregister_module()
//
//------------------------------------------------------------------------------
void unregister_module(
CIMClient& client,
const string& module_name)
{
if (verbose_opt)
printf("=== Deleting provider module instance\n");
// Delete the PG_ProviderModule instance.
try
{
char buf[1024];
sprintf(buf, "PG_ProviderModule.Name=\"%s\"", module_name.c_str());
if (!dump_opt)
{
delete_instance(client, REGISTRATION_NAMESPACE, buf);
}
}
catch (...)
{
#ifdef TRACE
fprintf(stderr, "ignored: %d\n", __LINE__);
#endif
}
}
//------------------------------------------------------------------------------
//
// get_PG_ProviderModule()
//
//------------------------------------------------------------------------------
int get_PG_ProviderModule(
CIMClient& client,
const string& module_name,
CIMInstance& ci)
{
char buf[1024];
sprintf(buf, "PG_ProviderModule.Name=\"%s\"", module_name.c_str());
return get_instance(client, REGISTRATION_NAMESPACE, buf, ci);
}
//------------------------------------------------------------------------------
//
// _isValidUser()
//
//------------------------------------------------------------------------------
bool _isValidUser(const string& user)
{
// ATTN: eventually implement this on Linux and Windows.
return true;
}
//------------------------------------------------------------------------------
//
// make_PG_ProviderModule()
//
//------------------------------------------------------------------------------
CIMInstance make_PG_ProviderModule(
const string& module_name,
const string& location)
{
CIMInstance i("PG_ProviderModule");
i.addProperty(CIMProperty("Name", String(module_name.c_str())));
i.addProperty(CIMProperty("Vendor", String("Pegasus")));
String version;
String interface_version;
if (cmpi_opt)
{
version = "2.0.0";
interface_version = "2.0.0";
}
else
{
version = "2.5.0";
interface_version = "2.5.0";
}
i.addProperty(CIMProperty("Version", version));
if (cmpi_opt)
{
i.addProperty(CIMProperty("InterfaceType", String("CMPI")));
}
else if (pegasus_cxx_opt)
{
i.addProperty(CIMProperty(
"InterfaceType", String("C++Default")));
}
else
i.addProperty(CIMProperty("InterfaceType", String("CIMPLE")));
i.addProperty(CIMProperty("InterfaceVersion", interface_version));
i.addProperty(CIMProperty("Location", String(location.c_str())));
// Inject UserContext if any.
if (user_opt.size())
{
// PG_ProviderModule.UserContext:
Uint16 userContext;
if (user_opt == "@requestor")
userContext = USER_CONTEXT_REQUESTOR;
else if (user_opt == "@privileged")
userContext = USER_CONTEXT_PRIVILEGED;
else if (user_opt == "@cimserver")
userContext = USER_CONTEXT_CIMSERVER;
else
userContext = USER_CONTEXT_DESIGNATED;
i.addProperty(CIMProperty("UserContext", userContext));
// PG_ProviderModule.DesignatedUserContext:
if (userContext == USER_CONTEXT_DESIGNATED)
{
if (!_isValidUser(user_opt))
{
err("user given by -U not a valid system user: %s\n",
user_opt.c_str());
}
String designatedUserContext = user_opt.c_str();
i.addProperty(
CIMProperty("DesignatedUserContext",
designatedUserContext));
}
}
return i;
}
//------------------------------------------------------------------------------
//
// compatible_modules()
//
//------------------------------------------------------------------------------
int compatible_property(CIMInstance& x, CIMInstance& y, const String& name)
{
// Find xp:
CIMProperty xp;
try
{
xp = x.getProperty(x.findProperty(name));
}
catch(...)
{
return -1;
}
// Find yp:
CIMProperty yp;
try
{
yp = y.getProperty(y.findProperty(name));
}
catch(...)
{
return -1;
}
if (yp.getName() != xp.getName())
return -1;
if (yp.getValue() != xp.getValue())
return -1;
return 0;
}
int compatible_modules(CIMInstance& x, CIMInstance& y)
{
if (compatible_property(x, y, "Name") != 0)
return -1;
if (compatible_property(x, y, "Vendor") != 0)
return -1;
if (compatible_property(x, y, "Version") != 0)
return -1;
if (compatible_property(x, y, "InterfaceType") != 0)
return -1;
if (compatible_property(x, y, "InterfaceVersion") != 0)
return -1;
if (compatible_property(x, y, "Location") != 0)
return -1;
if (user_opt.size())
{
if (compatible_property(x, y, "UserContext") != 0)
return -1;
if (user_opt != "@requestor" &&
user_opt != "@privileged" &&
user_opt != "@cimserver" &&
compatible_property(x, y, "DesignatedUserContext") != 0)
{
return -1;
}
}
return 0;
}
//------------------------------------------------------------------------------
//
// register_module()
//
//------------------------------------------------------------------------------
void register_module(
const char* lib_path,
const string& short_lib_name,
const string& module_name)
{
if (verbose_opt)
printf("=== Creating PG_ProviderModule\n");
// Connect to client.
try
{
// Remove old registration instance.
CIMClient client;
try
{
client.connectLocal();
}
catch (...)
{
err("failed to connect to local CIM server");
}
string location;
if (absolute_opt)
location = lib_path;
else
location = short_lib_name;
// Make instance of PG_ProviderModule.
CIMInstance pmi = make_PG_ProviderModule(module_name, location);
// If unregister option, unregister module and return now.
if (unregister_opt)
{
unregister_module(client, module_name);
return;
}
// Modify or create PG_ProviderModule instance.
CIMInstance tci;
if (get_PG_ProviderModule(client, module_name, tci) == 0)
{
if (dump_opt)
print(pmi);
else if (compatible_modules(pmi, tci) == 0)
{
if (verbose_opt)
printf("=== Using existing provider module instance\n");
}
else
{
unregister_module(client, module_name);
{
if (verbose_opt)
printf("=== Creating PG_ProviderModule instance\n");
client.createInstance(REGISTRATION_NAMESPACE, pmi);
if (verbose_opt)
printf("=== Created PG_ProviderModule instance\n");
}
}
}
else
{
if (dump_opt)
print(pmi);
else
{
if (verbose_opt)
printf("=== Creating provider module instance\n");
client.createInstance(REGISTRATION_NAMESPACE, pmi);
if (verbose_opt)
printf("=== Created provider module instance\n");
}
}
}
catch (CIMException& e)
{
CString msg = e.getMessage().getCString();
err("unexpected error: %s", (const char*)msg);
}
catch (...)
{
err("unexpected error");
}
}
//------------------------------------------------------------------------------
//
// check_cmpi_entry_point()
//
//------------------------------------------------------------------------------
static void check_cmpi_entry_point(
const char* provider_name,
const char* provider_type)
{
char sym_name[1024];
sprintf(sym_name, "%s_Create_%sMI", provider_name, provider_type);
void* sym = dlsym(g_handle, sym_name);
if (!sym)
err("missing CMPI entry point: \"%s\"\n", sym_name);
// printf("check_cmpi_entry_point: %s\n", sym_name);
}
//------------------------------------------------------------------------------
//
// compute_closure()
//
// Compute the closure with respect to the given class. The output includes
// all classes reachable from this class (via the superclass, references,
// or methods).
//
//------------------------------------------------------------------------------
void compute_closure(
const cimple::Meta_Class* mc,
vector<string>& closure)
{
// Ignore if already in list (to prevent recursion).
for (size_t i = 0; i < closure.size(); i++)
{
if (mc->name == closure[i])
return;
}
// Add this class to closure.
closure.push_back(mc->name);
// Return now unless -f option was given.
if (!indirect_opt)
return;
// Add super class to closure.
if (mc->super_meta_class)
compute_closure(mc->super_meta_class, closure);
// Add any classes reachable via class features to closure.
for (size_t i = 0; i < mc->num_meta_features; i++)
{
const cimple::Meta_Feature* mf = mc->meta_features[i];
if (mf->flags & CIMPLE_FLAG_REFERENCE)
{
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
compute_closure(mr->meta_class, closure);
}
if (mf->flags & CIMPLE_FLAG_METHOD)
{
const cimple::Meta_Method* mm = (cimple::Meta_Method*)mf;
for (size_t j = 0; j < mm->num_meta_features; j++)
{
const cimple::Meta_Feature* mf = mm->meta_features[j];
if (mf->flags & CIMPLE_FLAG_REFERENCE)
{
const cimple::Meta_Reference* mr =
(cimple::Meta_Reference*)mf;
compute_closure(mr->meta_class, closure);
}
}
}
}
}
//------------------------------------------------------------------------------
//
// delete_class()
//
//------------------------------------------------------------------------------
void delete_class(
CIMClient& client,
const String& ns,
const string& class_name)
{
try
{
if (!dump_opt)
client.deleteClass(ns, String(class_name.c_str()));
}
catch (...)
{
return;
}
if (!dump_opt)
printf("Deleted class %s\n", class_name.c_str());
}
//------------------------------------------------------------------------------
//
// uninstall_classes()
//
//------------------------------------------------------------------------------
void uninstall_classes(
CIMClient& client,
const cimple::Meta_Class* meta_class)
{
// Find closure and remove classes with the same prefix as the one
// installed by this provider (assuming thre prefix is not "CIM_").
vector<string> closure;
compute_closure(meta_class, closure);
string cn = meta_class->name;
size_t pos = cn.find('_');
string prefix;
if (pos != size_t(-1))
prefix = cn.substr(0, pos);
if (prefix != "CIM_")
{
for (size_t i = 0; i < closure.size(); i++)
{
string tmp = closure[i];
if (tmp.substr(0, 4) == "CIM_")
continue;
if (tmp.substr(0, prefix.size()) != prefix)
continue;
for (size_t j = 0; j < providing_namespaces.size(); j++)
{
delete_class(client, providing_namespaces[Uint32(j)], tmp);
}
}
}
}
//------------------------------------------------------------------------------
//
// register_provider()
//
//------------------------------------------------------------------------------
static void create_capabilities(
const string& module_name,
const string& provider_name,
const string& class_name,
const cimple::Meta_Class* meta_class,
CIMClient& client)
{
String mn = module_name.c_str();
String pn = provider_name.c_str();
String cn = class_name.c_str();
CIMInstance i("PG_ProviderCapabilities");
i.addProperty(CIMProperty("CapabilityID", cn));
i.addProperty(CIMProperty("ProviderModuleName", mn));
i.addProperty(CIMProperty("ProviderName", pn));
i.addProperty(CIMProperty("ClassName", cn));
i.addProperty(CIMProperty("Namespaces", providing_namespaces));
// Set provider type.
Pegasus::Array<Uint16> providerType;
// Register provider as one or more of the following types:
// - Instance provider
// - Indication provider
// - Association provider
// - Method provider
if (meta_class->flags & CIMPLE_FLAG_INDICATION)
{
// Indication provider:
providerType.append(4);
if (verbose_opt)
printf("=== Registered as indication provider\n");
if (cmpi_opt)
check_cmpi_entry_point(provider_name.c_str(), "Indication");
}
else
{
// Instance provider.
providerType.append(2);
if (verbose_opt)
printf("=== Registered as instance provider\n");
if (cmpi_opt)
check_cmpi_entry_point(provider_name.c_str(), "Instance");
}
if (meta_class->flags & CIMPLE_FLAG_ASSOCIATION)
{
// Association provider.
providerType.append(3);
if (verbose_opt)
printf("=== Registered as association provider\n");
if (cmpi_opt)
check_cmpi_entry_point(
provider_name.c_str(), "Association");
}
if (cimple::has_methods(meta_class))
{
// Method provider.
providerType.append(5);
if (verbose_opt)
printf("=== Registered as method provider\n");
if (cmpi_opt)
check_cmpi_entry_point(provider_name.c_str(), "Method");
}
i.addProperty(CIMProperty("ProviderType", providerType));
// supportedProperties
CIMValue supportedProperties;
supportedProperties.setNullValue(CIMTYPE_STRING, true, 0);
i.addProperty(
CIMProperty("supportedProperties", supportedProperties));
// supportedMethods
CIMValue supportedMethods;
supportedMethods.setNullValue(CIMTYPE_STRING, true, 0);
assert(supportedMethods.isNull());
i.addProperty(
CIMProperty("supportedMethods", supportedMethods));
if (dump_opt)
print(i);
if (!dump_opt)
{
if (verbose_opt)
printf("Creating PG_ProviderCapabilities instance\n");
client.createInstance(REGISTRATION_NAMESPACE, i);
if (verbose_opt)
printf("Created PG_ProviderCapabilities instance\n");
}
}
void register_provider(
const string& module_name,
const string& provider_name,
const cimple::Meta_Class* meta_class)
{
const string& class_name = meta_class->name;
// Print message:
if (!dump_opt)
{
if (unregister_opt)
printf("Unregistering ");
else
printf("Registering ");
printf("%s (class %s)\n", provider_name.c_str(), meta_class->name);
}
// Process.
try
{
// Remove old registration instances.
CIMClient client;
try
{
client.connectLocal();
}
catch (...)
{
err("failed to connect to local CIM server");
}
unregister_provider(
client, module_name, provider_name, class_name, meta_class);
if (unregister_opt && class_opt)
uninstall_classes(client, meta_class);
// Return if unregister option given.
if (unregister_opt)
return;
if (verbose_opt)
printf("=== Creating provider registration instances\n");
// Common definitions.
String mn = module_name.c_str();
String pn = provider_name.c_str();
String cn = class_name.c_str();
// Create PG_Provider instance.
{
CIMInstance i("PG_Provider");
i.addProperty(CIMProperty("Name", pn));
i.addProperty(CIMProperty("ProviderModuleName", mn));
if (dump_opt)
print(i);
if (!dump_opt)
{
if (verbose_opt)
printf("Creating PG_Provider instance\n");
client.createInstance(REGISTRATION_NAMESPACE, i);
if (verbose_opt)
printf("Created PG_Provider instance\n");
}
}
// Create PG_ProviderCapabilities instance.
if (subclass_opt)
{
// With this option, we register the provider to provide all
// subclasses of this class.
for (size_t i = 0; i < _num_meta_classes; i++)
{
if (cimple::is_subclass(meta_class, _meta_classes[i]))
{
try
{
create_capabilities(
module_name,
provider_name,
_meta_classes[i]->name,
_meta_classes[i],
client);
}
catch (CIMException& e)
{
char buf[1024];
sprintf(buf,
"PG_ProviderCapabilities."
"ProviderName=\"%s\","
"ProviderModuleName=\"%s\","
"CapabilityID=\"%s\"",
provider_name.c_str(),
module_name.c_str(),
_meta_classes[i]->name);
CString msg = e.getMessage().getCString();
err("registration error: %s: %s",
buf, (const char*)msg);
}
}
}
}
else
{
// Register provider only to provide the single class.
try
{
create_capabilities(
module_name,
provider_name,
class_name,
meta_class,
client);
}
catch (CIMException& e)
{
char buf[1024];
sprintf(buf,
"PG_ProviderCapabilities."
"ProviderName=\"%s\","
"ProviderModuleName=\"%s\","
"CapabilityID=\"%s\"",
provider_name.c_str(),
module_name.c_str(),
class_name.c_str());
CString msg = e.getMessage().getCString();
err("registration error: %s: %s", buf, (const char*)msg);
}
}
}
catch (CIMException& e)
{
CString msg = e.getMessage().getCString();
err("registration error: %s", (const char*)msg);
}
catch (...)
{
err("registration error");
}
}
//------------------------------------------------------------------------------
//
// get_class()
//
//------------------------------------------------------------------------------
bool get_class(
CIMClient& client,
const String& name_space,
const char* class_name,
CIMClass& cim_class)
{
try
{
const bool local_only = false;
const bool include_qualifiers = true;
cim_class = client.getClass(
name_space, class_name, local_only, include_qualifiers);
return true;
}
catch (...)
{
return false;
}
}
//------------------------------------------------------------------------------
//
// check_method_compatibility()
//
//------------------------------------------------------------------------------
void check_method_compatibility(
CIMClient& client,
const String& ns,
const cimple::Meta_Class* mc,
const cimple::Meta_Method* mm,
CIMMethod& m)
{
for (size_t i = 0; i < mm->num_meta_features; i++)
{
const cimple::Meta_Feature* mf = mm->meta_features[i];
if (strcmp(mf->name, "return_value") == 0)
continue;
Uint32 pos = m.findParameter(mf->name);
if (pos == (Uint32)-1)
{
warn("Parameter not found in Pegasus repository class: %s.%s",
mm->name, mf->name);
continue;
}
CIMParameter p = m.getParameter(pos);
if (mf->flags & CIMPLE_FLAG_EMBEDDED_OBJECT)
{
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
if (p.getType() != CIMTYPE_STRING && p.getType() != CIMTYPE_OBJECT)
{
err(INCOMPATIBLE "Parameters have different types: %s().%s",
mc->name, mm->name, mr->name);
}
Uint32 pos = p.findQualifier("EmbeddedObject");
if (pos == (Uint32)-1)
{
err(INCOMPATIBLE "Parameters have different types: %s",
mc->name, mf->name);
}
}
else if (mf->flags & CIMPLE_FLAG_EMBEDDED_INSTANCE)
{
#ifdef CIMPLE_ENABLE_EMBEDDED_INSTANCES
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
if (p.getType() != CIMTYPE_STRING && p.getType() !=CIMTYPE_INSTANCE)
{
err(INCOMPATIBLE "Parameters have different types: %s",
mc->name, mr->name);
}
Uint32 pos = p.findQualifier("EmbeddedInstance");
if (pos == (Uint32)-1)
{
err(INCOMPATIBLE "Missing EmbeddedInstance qualifier: %s",
mc->name, mf->name);
}
try
{
String t;
p.getQualifier(pos).getValue().get(t);
if (!cimple::eqi(*cimple::Str(t), mr->meta_class->name))
{
err(INCOMPATIBLE "Embedded class name mismatch on %s",
mc->name, mf->name);
}
}
catch (...)
{
err(INCOMPATIBLE "Unexpected error: %s",
mc->name, mf->name);
}
#else /* !CIMPLE_ENABLE_EMBEDDED_INSTANCES */
err(NO_EMBEDDED_INSTANCES);
#endif /* !CIMPLE_ENABLE_EMBEDDED_INSTANCES */
}
else if (mf->flags & CIMPLE_FLAG_PROPERTY)
{
const cimple::Meta_Property* mp = (const cimple::Meta_Property*)mf;
if (p.getType() != mp->type)
err(INCOMPATIBLE "1On this method: %s", mc->name, mm->name);
if (p.isArray() && mp->subscript == 0)
err(INCOMPATIBLE "2On this method: %s", mc->name, mm->name);
}
else if (mf->flags & CIMPLE_FLAG_REFERENCE)
{
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
if (p.getType() != CIMTYPE_REFERENCE)
err(INCOMPATIBLE "3On this method: %s", mc->name, mm->name);
String tmp = p.getReferenceClassName().getString();
if (tmp != mr->meta_class->name)
err(INCOMPATIBLE "4On this method: %s", mc->name, mm->name);
// Check compatibility of these reference classes:
CIMClass cc;
if (!get_class(client, ns, mr->meta_class->name, cc))
err("dependent class not found: %s", mr->meta_class->name);
check_class_compatibility(client, ns, mr->meta_class, cc);
}
}
}
//------------------------------------------------------------------------------
//
// check_class_compatibility()
//
//------------------------------------------------------------------------------
void check_class_compatibility(
CIMClient& client,
const String& ns,
const cimple::Meta_Class* mc,
CIMClass& c)
{
if (verbose_opt)
printf("=== Checking class compatibility (%s)\n", mc->name);
// Check whether they have the same super class.
if (mc->super_meta_class)
{
CString tmp = c.getSuperClassName().getString().getCString();
if (strcasecmp(mc->super_meta_class->name, tmp) != 0)
{
err(INCOMPATIBLE "They have different super classes",
mc->name);
}
CIMClass cc;
if (!get_class(client, ns, mc->super_meta_class->name, cc))
err("dependent class not found: %s", mc->super_meta_class->name);
check_class_compatibility(client, ns, mc->super_meta_class, cc);
}
// Check compatibility of each feature.
for (size_t i = 0; i < mc->num_meta_features; i++)
{
const cimple::Meta_Feature* mf = mc->meta_features[i];
// Check only local features:
if (!mc->locals[i].local)
continue;
// If it's a method, process and then short-circuit the remainder.
if (mf->flags & CIMPLE_FLAG_METHOD)
{
Uint32 pos = c.findMethod(mf->name);
if (pos == (Uint32)-1)
{
err(INCOMPATIBLE "Pegasus class has no method called %s",
mc->name, mf->name);
}
CIMMethod m = c.getMethod(pos);
const cimple::Meta_Method* mm = (const cimple::Meta_Method*)mf;
check_method_compatibility(client, ns, mc, mm, m);
continue;
}
// Find corresponding property in Pegasus class.
Uint32 pos = c.findProperty(mf->name);
if (pos == (Uint32)-1)
{
// ATTN: these are causes by incompatibilities in CIM version.
#if 0
warn("Warning: feature %s.%s found in CIMPLE meta class but not "
"in Pegasus repository class", mc->name, mf->name);
#endif
continue;
}
CIMProperty p = c.getProperty(pos);
// Check feature (object, property, or reference)
if (mf->flags & CIMPLE_FLAG_EMBEDDED_OBJECT)
{
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
// Check type.
if (p.getType() != CIMTYPE_STRING && p.getType() != CIMTYPE_OBJECT)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mr->name);
}
// Check EmbeddedObject qualifier:
Uint32 pos = p.findQualifier("EmbeddedObject");
if (pos == (Uint32)-1)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mf->name);
}
}
else if (mf->flags & CIMPLE_FLAG_EMBEDDED_INSTANCE)
{
#ifdef CIMPLE_ENABLE_EMBEDDED_INSTANCES
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
// Check type.
if (p.getType() != CIMTYPE_STRING && p.getType() !=CIMTYPE_INSTANCE)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mr->name);
}
// Check EmbeddedInstance qualifier:
Uint32 pos = p.findQualifier("EmbeddedInstance");
if (pos == (Uint32)-1)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mf->name);
}
try
{
String t;
p.getQualifier(pos).getValue().get(t);
if (!cimple::eqi(*cimple::Str(t), mr->meta_class->name))
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mf->name);
}
}
catch (...)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mf->name);
}
#else /* !CIMPLE_ENABLE_EMBEDDED_INSTANCES */
err(NO_EMBEDDED_INSTANCES);
#endif /* !CIMPLE_ENABLE_EMBEDDED_INSTANCES */
}
else if (mf->flags & CIMPLE_FLAG_PROPERTY)
{
const cimple::Meta_Property* mp = (const cimple::Meta_Property*)mf;
// Check type.
if (p.getType() != mp->type)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mp->name);
}
// Check array info.
if (p.isArray() && mp->subscript == 0)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mp->name);
}
}
else if (mf->flags & CIMPLE_FLAG_REFERENCE)
{
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
// Check type.
if (p.getType() != CIMTYPE_REFERENCE)
{
err(INCOMPATIBLE "Properties have different types: %s",
mc->name, mr->name);
}
// Check compatibility of these reference classes:
CIMClass cc;
if (!get_class(client, ns, mr->meta_class->name, cc))
err("dependent class not found: %s", mr->meta_class->name);
check_class_compatibility(client, ns, mr->meta_class, cc);
}
if (mf->flags & CIMPLE_FLAG_KEY)
{
Uint32 pos = p.findQualifier("key");
if (pos == (Uint32)-1)
{
err(INCOMPATIBLE "Properties are not both keys: %s",
mc->name, mf->name);
}
}
}
}
//------------------------------------------------------------------------------
//
// class_exists()
//
//------------------------------------------------------------------------------
bool class_exists(
const String& name_space,
CIMClient& client,
const char* class_name)
{
try
{
const bool local_only = true;
const bool include_qualifiers = false;
CIMClass tmp = client.getClass(
name_space, class_name, local_only, include_qualifiers);
return true;
}
catch (...)
{
return false;
}
}
//------------------------------------------------------------------------------
//
// add_method()
//
//------------------------------------------------------------------------------
void add_method(
CIMClient& client,
const String& ns,
CIMClass& cc,
const cimple::Meta_Method* mm)
{
// Create method.
CIMMethod cm(mm->name, CIMType(mm->return_type));
for (size_t i = 0; i < mm->num_meta_features; i++)
{
const cimple::Meta_Feature* mf = mm->meta_features[i];
// Handle return value up front:
if (strcmp(mf->name, "return_value") == 0)
{
if (mf->flags & CIMPLE_FLAG_EMBEDDED_INSTANCE)
{
assert(mf->flags & CIMPLE_FLAG_REFERENCE);
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
create_class(client, ns, mr->meta_class);
CIMQualifier q("EmbeddedInstance",String(mr->meta_class->name));
cm.addQualifier(q);
}
else if (mf->flags & CIMPLE_FLAG_EMBEDDED_OBJECT)
{
assert(mf->flags & CIMPLE_FLAG_REFERENCE);
CIMQualifier q("EmbeddedObject", Boolean(true));
cm.addQualifier(q);
}
continue;
}
// Now add current parameter:
CIMParameter cp;
if (mf->flags & CIMPLE_FLAG_EMBEDDED_OBJECT)
{
assert(mf->flags & CIMPLE_FLAG_REFERENCE);
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
cp = CIMParameter(mf->name, CIMTYPE_STRING);
cp.addQualifier(CIMQualifier("EmbeddedObject", Boolean(true)));
}
else if (mf->flags & CIMPLE_FLAG_EMBEDDED_INSTANCE)
{
assert(mf->flags & CIMPLE_FLAG_REFERENCE);
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
cp = CIMParameter(mf->name, CIMTYPE_STRING);
create_class(client, ns, mr->meta_class);
cp.addQualifier(CIMQualifier(
"EmbeddedInstance", String(mr->meta_class->name)));
}
else if (mf->flags & CIMPLE_FLAG_REFERENCE)
{
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
create_class(client, ns, mr->meta_class);
bool is_array = mr->subscript != 0;
cp = CIMParameter(
mr->name, CIMTYPE_REFERENCE, is_array, 0, mr->meta_class->name);
}
else if (mf->flags & CIMPLE_FLAG_PROPERTY)
{
const cimple::Meta_Property* mp = (const cimple::Meta_Property*)mf;
Uint32 array_size = mp->subscript > 0 ? mp->subscript : 0;
bool is_array = mp->subscript != 0;
cp = CIMParameter(
mp->name, CIMType(mp->type), is_array, array_size);
}
// Fixup in/out qualifiers on new parameter.
if (mf->flags & CIMPLE_FLAG_IN)
cp.addQualifier(CIMQualifier("in", Boolean(true)));
else
cp.addQualifier(CIMQualifier("in", Boolean(false)));
if (mf->flags & CIMPLE_FLAG_OUT)
cp.addQualifier(CIMQualifier("out", Boolean(true)));
// Add parameter to list:
cm.addParameter(cp);
}
cc.addMethod(cm);
}
//------------------------------------------------------------------------------
//
// create_class()
//
//------------------------------------------------------------------------------
void create_class(
CIMClient& client,
const String& ns,
const cimple::Meta_Class* mc)
{
if (class_exists(ns, client, mc->name))
return;
if (verbose_opt)
printf("=== Creating class (%s)\n", mc->name);
if (!dump_opt)
printf("Creating class %s (%s)\n", mc->name,
(const char*)ns.getCString());
// Create superclass if necessary.
if (mc->super_meta_class)
create_class(client, ns, mc->super_meta_class);
// Now create the class itself.
try
{
// Define the class.
string super_class_name;
if (mc->super_meta_class)
super_class_name = mc->super_meta_class->name;
CIMClass c(mc->name);
if (super_class_name.size())
c.setSuperClassName(String(super_class_name.c_str()));
// Add assocation qualifier?
if (mc->flags & CIMPLE_FLAG_ASSOCIATION)
c.addQualifier(CIMQualifier("Association", Boolean(true)));
// Add assocation qualifier?
if (mc->flags & CIMPLE_FLAG_INDICATION)
c.addQualifier(CIMQualifier("Indication", Boolean(true)));
// Add properties.
size_t num_keys = 0;
for (size_t i = 0; i < mc->num_meta_features; i++)
{
const cimple::Meta_Feature* mf = mc->meta_features[i];
if (mf->flags & CIMPLE_FLAG_METHOD)
continue;
if (mf->flags & CIMPLE_FLAG_KEY)
num_keys++;
// Ignore non-local feature:
if (!mc->locals[i].local)
continue;
if (mf->flags & CIMPLE_FLAG_EMBEDDED_OBJECT)
{
assert(mf->flags & CIMPLE_FLAG_REFERENCE);
assert(!(mf->flags & CIMPLE_FLAG_KEY));
CIMValue v(CIMTYPE_STRING, false, 0);
CIMProperty p(mf->name, v, 0);
p.addQualifier(CIMQualifier("EmbeddedObject", Boolean(true)));
c.addProperty(p);
}
else if (mf->flags & CIMPLE_FLAG_EMBEDDED_INSTANCE)
{
#ifdef CIMPLE_ENABLE_EMBEDDED_INSTANCES
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
assert(mf->flags & CIMPLE_FLAG_REFERENCE);
assert(!(mf->flags & CIMPLE_FLAG_KEY));
CIMValue v(CIMTYPE_STRING, false, 0);
CIMProperty p(mf->name, v, 0);
create_class(client, ns, mr->meta_class);
p.addQualifier(CIMQualifier(
"EmbeddedInstance", String(mr->meta_class->name)));
c.addProperty(p);
#else /* !CIMPLE_ENABLE_EMBEDDED_INSTANCES */
err(NO_EMBEDDED_INSTANCES);
#endif /* !CIMPLE_ENABLE_EMBEDDED_INSTANCES */
}
else if (mf->flags & CIMPLE_FLAG_PROPERTY)
{
const cimple::Meta_Property* mp = (cimple::Meta_Property*)mf;
CIMValue v(CIMType(mp->type), Boolean(mp->subscript), 0);
Uint32 array_size = mp->subscript > 0 ? mp->subscript : 0;
CIMProperty p(mp->name, v, array_size);
if (mf->flags & CIMPLE_FLAG_KEY)
p.addQualifier(CIMQualifier("Key", Boolean(true)));
c.addProperty(p);
}
else if (mf->flags & CIMPLE_FLAG_REFERENCE)
{
const cimple::Meta_Reference* mr = (cimple::Meta_Reference*)mf;
CIMValue v(CIMTYPE_REFERENCE, false, 0);
CIMProperty p(mf->name, v, 0, mr->meta_class->name);
if (mf->flags & CIMPLE_FLAG_KEY)
p.addQualifier(CIMQualifier("Key", Boolean(true)));
c.addProperty(p);
create_class(client, ns, mr->meta_class);
}
}
// Add methods to the class.
for (size_t i = 0; i < mc->num_meta_features; i++)
{
const cimple::Meta_Feature* mf = mc->meta_features[i];
if (mf->flags & CIMPLE_FLAG_METHOD)
add_method(client, ns, c, (const cimple::Meta_Method*)mf);
}
if (!dump_opt)
client.createClass(ns, c);
}
catch (Exception& e)
{
CString msg = e.getMessage().getCString();
err("failed to create class: %s: %s", mc->name, (const char*)msg);
}
catch (...)
{
err("failed to create class");
}
}
//------------------------------------------------------------------------------
//
// validate_class()
//
//------------------------------------------------------------------------------
void validate_class(
const String& ns,
const cimple::Meta_Class* meta_class)
{
if (verbose_opt)
printf("=== Validating the Pegasus class\n");
// Find the class.
try
{
// Connect to CIM serer.
CIMClient client;
try
{
client.connectLocal();
}
catch (...)
{
err("failed to connect to local CIM server");
}
// Create class:
if (class_opt)
{
// Create provided class.
create_class(client, ns, meta_class);
// Create subclasses if requested.
if (subclass_opt)
{
for (size_t i = 0; i < _num_meta_classes; i++)
{
if (cimple::is_subclass(meta_class, _meta_classes[i]))
create_class(client, ns, _meta_classes[i]);
}
}
}
// Be sure the class exists.
CIMClass c;
if (!get_class(client, ns, meta_class->name, c))
{
err("The Pegasus repository contains no class called \"%s\". "
"Please add this class to repository or use the -c option.",
meta_class->name);
}
// Check compatibility between meta-data and Pegasus class.
check_class_compatibility(client, ns, meta_class, c);
}
catch (CIMException& e)
{
CString msg = e.getMessage().getCString();
err("error: %s", (const char*)msg);
}
catch (...)
{
err("error while validating class");
}
}
//------------------------------------------------------------------------------
//
// _load_class_deps()
//
//------------------------------------------------------------------------------
static void _load_class_deps(const char* lib_path, vector<string>& class_deps)
{
// Open the input file.
FILE* fp = fopen(lib_path, "rb");
if (!fp)
{
err("failed to open %s", lib_path);
exit(1);
}
// Read library into memory.
char buf[1024];
vector<char> v;
size_t n;
while ((n = fread(buf, 1, sizeof(buf), fp)) > 0)
v.insert(v.end(), buf, buf + n);
v.push_back('\0');
// Close the file:
fclose(fp);
// Search for tags:
const char* p = &v[0];
n = v.size();
while (n)
{
if (n >= 4 && p[0] == '@' && p[1] == '(' && p[2] == '#' && p[3] == ')')
{
p += 4;
string str;
while (n && *p)
{
str += p[0];
n--;
p++;
}
size_t pos = str.find('=');
if (pos != string::npos)
{
string name = str.substr(0, pos);
string value = str.substr(pos+1);
// Skip this in case debugger puts #define macro definitions
// into debugger info.
if (value.find("#CLASS;") == string::npos &&
name == "CLASS_DEPENDENCY")
{
class_deps.push_back(value);
}
}
}
n--;
p++;
}
}
//------------------------------------------------------------------------------
//
// main()
//
//------------------------------------------------------------------------------
static const char* arg0;
int main(int argc, char** argv)
{
arg0 = argv[0];
// Setup arg0 for warn() and err().
set_arg0(argv[0]);
// Extract options:
int opt;
while ((opt = getopt(argc, argv, "r:dcvhn:uisaU:V")) != -1)
{
switch (opt)
{
case 's':
subclass_opt = true;
break;
case 'c':
class_opt = true;
break;
case 'v':
verbose_opt = true;
break;
case 'V':
printf("%s\n", CIMPLE_VERSION_STRING);
exit(0);
break;
case 'd':
dump_opt = true;
break;
case 'n':
providing_namespaces.append(optarg);
break;
case 'a':
absolute_opt = true;
break;
case 'h':
help_opt = true;
break;
case 'u':
unregister_opt = true;
break;
case 'i':
indirect_opt = true;
break;
case 'U':
user_opt = optarg;
break;
default:
{
err("unknown option: -%c\n", opt);
break;
}
}
}
argc -= optind;
argv += optind;
// check arguments.
if (argc < 1 || help_opt)
{
fprintf(stderr, (const char*)USAGE, arg0);
exit(1);
}
// If there were no -n (namespace) options, then use default.
if (providing_namespaces.size() == 0)
providing_namespaces.append(DEFAULT_PROVIDING_NAMESPACE);
const char* lib_path = argv[0];
// Get class dependency list:
// ATTN: CIMPLE_CLASS_DEPENENCY macro scheme is broken in cross
// namespace provider case.
static vector<string> class_deps;
_load_class_deps(lib_path, class_deps);
// Get information from provider.
cimple::Registration* module = load_module(
lib_path, _meta_classes, _num_meta_classes);
// If no modules in this library.
if (!module)
err("module contains no providers: %s", lib_path);
// validate CIMPLE classes against Pegasus classes in each namespace.
if (!unregister_opt && !dump_opt)
{
for (cimple::Registration* p = module; p; p = p->next)
{
// Skip class if not included in command line class list (if any).
if (argc > 1)
{
bool found = false;
for (int i = 1; i < argc; i++)
{
if (strcasecmp(p->meta_class->name, argv[i]) == 0)
{
found = true;
break;
}
}
if (!found)
continue;
}
for (size_t i = 0; i < providing_namespaces.size(); i++)
{
// Validate and CREATE provided class.
validate_class(providing_namespaces[Uint32(i)], p->meta_class);
}
}
// Create class dependencies:
for (size_t i = 0; i < providing_namespaces.size(); i++)
{
// Create class dependency.
for (size_t j = 0; j < class_deps.size(); j++)
{
const char* class_name = class_deps[j].c_str();
const cimple::Meta_Class* mc = cimple::find_meta_class(
module->meta_class, class_name);
if (!mc)
{
err("Unknown class (%s) given by CIMPLE_CLASS_DEPENENCY() "
"macro within provider library. Verify that the class "
"name is spelled correctly and that genclass was given "
"the -r option along with the complete list of "
"required classes. To see a complete list of class "
"dependencies for your library, use the cwhat "
"utility.", class_name);
}
validate_class(providing_namespaces[Uint32(i)], mc);
}
}
}
// Step #5: find short form of library name.
string short_lib_name = shlib_basename(lib_path);
// Step #6: register provider module in Pegasus repository.
string module_name = module->module_name;
register_module(lib_path, short_lib_name, module_name);
// Step #7: register provider module Pegasus repository.
if (argc == 1)
{
// Register all providers in the module.
for (cimple::Registration* p = module; p; p = p->next)
register_provider(module_name, p->provider_name, p->meta_class);
}
else
{
// Register selected providers in the module.
for (int i = 1; i < argc; i++)
{
cimple::Registration* reg = 0;
for (cimple::Registration* p = module; p; p = p->next)
{
if (strcasecmp(argv[i], p->meta_class->name) == 0)
{
reg = p;
break;
}
}
if (!reg)
{
err("Invalid class given as command line argument: %s. "
"There is no provider for that class in %s.",
argv[i], lib_path);
}
register_provider(module_name, reg->provider_name, reg->meta_class);
}
}
return 0;
}
| 26.03469 | 80 | 0.489924 | [
"object",
"vector"
] |
a8c54b924a32ce6f8d05f65eac92072baa454ec8 | 2,997 | cc | C++ | src/codebook/algorithms/CentroidDecomposition.cc | anshika581/competitive-programming-1 | c34fb89820cd7260661daa2283f492b07cd9f8d2 | [
"Apache-2.0",
"MIT"
] | 83 | 2017-08-30T01:20:03.000Z | 2022-02-12T13:50:27.000Z | src/codebook/algorithms/CentroidDecomposition.cc | anshika581/competitive-programming-1 | c34fb89820cd7260661daa2283f492b07cd9f8d2 | [
"Apache-2.0",
"MIT"
] | 1 | 2015-08-20T13:37:59.000Z | 2015-08-26T00:56:39.000Z | src/codebook/algorithms/CentroidDecomposition.cc | anshika581/competitive-programming-1 | c34fb89820cd7260661daa2283f492b07cd9f8d2 | [
"Apache-2.0",
"MIT"
] | 41 | 2017-11-09T06:10:08.000Z | 2022-01-11T14:10:25.000Z | /*
* Centroid decomposition: A variation of the divide and conquer paradigm that is used on trees.
* Find the centroid of the tree and mark it. After running an algorithm on the entire tree,
* remove the centroid. The original tree will decompose into a number of different trees.
* Recursively run the algorithm and continue to divide up the trees.
*
* Reference problem: IOI 2011 Race
*/
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define INF 1 << 30
#define MOD 1000000007
#define rint(x) scanf("%d", &(x))
#define rlong(x) scanf("%lld", &(x))
#define SIZE 200000
#define l(x) x << 1
#define r(x) x << 1 | 1
#define m(x, y) (x + y) / 2
using namespace std;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;
int n, k;
int dist[SIZE];
int cnt[SIZE];
bool exclude[SIZE];
vector<pi> adj[SIZE];
int getSize(int curr, int par) {
int sz = 1;
for (pi next : adj[curr])
if (next.first != par && !exclude[next.first])
sz += getSize(next.first, curr);
return sz;
}
int getCentroid(int curr, int par, int treeSize) {
int n = treeSize;
int sz = 1;
bool valid = true;
for (pi next : adj[curr]) {
if (next.first == par || exclude[next.first])
continue;
int ret = getCentroid(next.first, curr, treeSize);
if (ret >= 0)
return ret;
valid &= -ret <= n / 2;
sz += -ret;
}
valid &= n - sz <= n / 2;
return valid ? curr : -sz;
}
queue<pi> currTree;
void getDist(int u, int par, int distTo, int cntTo, int branch) {
cnt[u] = cntTo;
dist[u] = distTo;
currTree.push(mp(u, branch));
for (pi v : adj[u])
if (v.first != par && !exclude[v.first])
getDist(v.first, u, distTo + v.second, cntTo + 1, par == -1 ? v.first : branch);
}
int main() {
rint(n);
rint(k);
for (int i = 0; i < n - 1; i++) {
int a, b, c;
rint(a), rint(b), rint(c);
adj[a].pb(mp(b, c));
adj[b].pb(mp(a, c));
}
queue<int> q;
q.push(0);
int ans = 1 << 30;
while (!q.empty()) {
int curr = q.front();
q.pop();
int centroid = getCentroid(curr, -1, getSize(curr, -1));
getDist(centroid, -1, 0, 0, -1);
unordered_map<int, int> hm;
queue<int> addToHm;
int prev = -2;
while (!currTree.empty()) {
pi curr = currTree.front();
currTree.pop();
if (curr.second != prev) {
prev = curr.second;
while (!addToHm.empty()) {
int add = addToHm.front();
addToHm.pop();
if (hm.count(dist[add])) {
if (hm[dist[add]] > cnt[add])
hm[dist[add]] = cnt[add];
} else {
hm[dist[add]] = cnt[add];
}
}
}
if (hm.count(k - dist[curr.first])) {
ans = min(ans, cnt[curr.first] + hm[k - dist[curr.first]]);
}
addToHm.push(curr.first);
}
exclude[centroid] = true;
for (pi v : adj[centroid])
if (!exclude[v.first])
q.push(v.first);
}
printf("%d\n", ans == 1 << 30 ? -1 : ans);
return 0;
}
| 24.975 | 96 | 0.56323 | [
"vector"
] |
a8c5a739434790f90c4277a6736beeea580fb5fe | 8,814 | cpp | C++ | cpp/src/cylon/join/join_utils.cpp | vibhatha/cylon | 3f2c5b08935a4332b820818ca113cb44f7ac5da3 | [
"Apache-2.0"
] | 5 | 2021-01-06T04:28:16.000Z | 2021-11-24T01:27:21.000Z | cpp/src/cylon/join/join_utils.cpp | vibhatha/cylon | 3f2c5b08935a4332b820818ca113cb44f7ac5da3 | [
"Apache-2.0"
] | 1 | 2020-09-24T16:35:27.000Z | 2020-09-24T16:35:27.000Z | cpp/src/cylon/join/join_utils.cpp | vibhatha/cylon | 3f2c5b08935a4332b820818ca113cb44f7ac5da3 | [
"Apache-2.0"
] | null | null | null | /*
* 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 <glog/logging.h>
#include <string>
#include <vector>
#include <memory>
#include "join_utils.hpp"
#include "../util/arrow_utils.hpp"
namespace cylon {
namespace join {
namespace util {
arrow::Status build_final_table_inplace_index(size_t left_inplace_column, size_t right_inplace_column,
const std::vector<int64_t> &left_indices,
const std::vector<int64_t> &right_indices,
std::shared_ptr<arrow::UInt64Array> &left_index_sorted_column,
std::shared_ptr<arrow::UInt64Array> &right_index_sorted_column,
const std::shared_ptr<arrow::Table> &left_tab,
const std::shared_ptr<arrow::Table> &right_tab,
const std::string &left_table_prefix,
const std::string &right_table_prefix,
std::shared_ptr<arrow::Table> *final_table,
arrow::MemoryPool *memory_pool) {
// creating joined schema
std::vector<std::shared_ptr<arrow::Field>> fields;
// TODO: get left and right suffixes from user if needed and update it here and replace in the schema with newfileds
std::string prefix = left_table_prefix;
for(const auto &t: {left_tab, right_tab}){
for (const auto &field: t->schema()->fields()){
fields.emplace_back(field->WithName(prefix + field->name()));
}
prefix = right_table_prefix;
}
const auto &schema = arrow::schema(fields);
std::vector<int64_t> indices_indexed;
indices_indexed.reserve(left_indices.size());
for (long v : left_indices) {
if (v < 0){
indices_indexed.push_back(v);
} else {
indices_indexed.push_back(left_index_sorted_column->Value(v));
}
}
left_index_sorted_column.reset();
std::vector<std::shared_ptr<arrow::Array>> data_arrays;
// build arrays for left tab
const std::vector<std::shared_ptr<arrow::ChunkedArray>> &kVector = left_tab->columns();
for (size_t i = 0; i < kVector.size(); i++) {
std::shared_ptr<arrow::ChunkedArray> ca = kVector[i];
std::shared_ptr<arrow::Array> destination_col_array;
arrow::Status status;
if (i == left_inplace_column) {
status = cylon::util::copy_array_by_indices(left_indices,
cylon::util::GetChunkOrEmptyArray(ca, 0),
&destination_col_array,
memory_pool);
} else {
status = cylon::util::copy_array_by_indices(indices_indexed,
cylon::util::GetChunkOrEmptyArray(ca, 0),
&destination_col_array,
memory_pool);
}
if (status != arrow::Status::OK()) {
LOG(FATAL) << "Failed while copying a column to the final table from left table. "
<< status.ToString();
return status;
}
data_arrays.push_back(destination_col_array);
}
indices_indexed.clear();
indices_indexed.reserve(right_indices.size());
for (long v : right_indices) {
if (v < 0){
indices_indexed.push_back(v);
} else {
indices_indexed.push_back(right_index_sorted_column->Value(v));
}
}
right_index_sorted_column.reset();
// build arrays for right tab
const std::vector<std::shared_ptr<arrow::ChunkedArray>> &rvector = right_tab->columns();
for (size_t i = 0; i < rvector.size(); i++) {
std::shared_ptr<arrow::ChunkedArray> ca = rvector[i];
std::shared_ptr<arrow::Array> destination_col_array;
arrow::Status status;
if (i == right_inplace_column) {
status = cylon::util::copy_array_by_indices(right_indices,
cylon::util::GetChunkOrEmptyArray(ca, 0),
&destination_col_array,
memory_pool);
} else {
status = cylon::util::copy_array_by_indices(indices_indexed,
cylon::util::GetChunkOrEmptyArray(ca, 0),
&destination_col_array,
memory_pool);
}
if (status != arrow::Status::OK()) {
LOG(FATAL) << "Failed while copying a column to the final table from right table. "
<< status.ToString();
return status;
}
data_arrays.push_back(destination_col_array);
}
*final_table = arrow::Table::Make(schema, data_arrays);
return arrow::Status::OK();
}
arrow::Status build_final_table(const std::vector<int64_t> &left_indices,
const std::vector<int64_t> &right_indices,
const std::shared_ptr<arrow::Table> &left_tab,
const std::shared_ptr<arrow::Table> &right_tab,
const std::string &left_table_prefix,
const std::string &right_table_prefix,
std::shared_ptr<arrow::Table> *final_table,
arrow::MemoryPool *memory_pool) {
// creating joined schema
std::vector<std::shared_ptr<arrow::Field>> fields;
// TODO: get left and right suffixes from user if needed and update it here and replace in the schema with newfileds
std::string prefix = left_table_prefix;
for(const auto &t: {left_tab, right_tab}){
for (const auto &field: t->schema()->fields()){
fields.emplace_back(field->WithName(prefix + field->name()));
}
prefix = right_table_prefix;
}
const auto &schema = arrow::schema(fields);
std::vector<std::shared_ptr<arrow::Array>> data_arrays;
// build arrays for left tab
for (auto &column : left_tab->columns()) {
std::shared_ptr<arrow::Array> destination_col_array;
arrow::Status
status = cylon::util::copy_array_by_indices(left_indices,
cylon::util::GetChunkOrEmptyArray(column, 0),
&destination_col_array,
memory_pool);
if (status != arrow::Status::OK()) {
LOG(FATAL) << "Failed while copying a column to the final table from left table. "
<< status.ToString();
return status;
}
data_arrays.push_back(destination_col_array);
}
// build arrays for right tab
for (auto &column : right_tab->columns()) {
std::shared_ptr<arrow::Array> destination_col_array;
arrow::Status
status = cylon::util::copy_array_by_indices(right_indices,
cylon::util::GetChunkOrEmptyArray(column, 0),
&destination_col_array,
memory_pool);
if (status != arrow::Status::OK()) {
LOG(FATAL) << "Failed while copying a column to the final table from right table. "
<< status.ToString();
return status;
}
data_arrays.push_back(destination_col_array);
}
*final_table = arrow::Table::Make(schema, data_arrays);
return arrow::Status::OK();
}
arrow::Status CombineChunks(const std::shared_ptr<arrow::Table> &table,
int64_t col_index,
std::shared_ptr<arrow::Table> &output_table,
arrow::MemoryPool *memory_pool) {
if (table->column(col_index)->num_chunks() > 1) {
LOG(INFO) << "Combining chunks " << table->column(col_index)->num_chunks();
arrow::Result<std::shared_ptr<arrow::Table>> result = table->CombineChunks(memory_pool);
if (result.ok()) {
output_table = result.ValueOrDie();
}
return result.status();
} else {
output_table = table;
return arrow::Status::OK();
}
}
} // namespace util
} // namespace join
} // namespace cylon
| 43.418719 | 118 | 0.568527 | [
"vector"
] |
a8c6568d4904919304a6a71d78996f64197fcaa5 | 36,425 | cpp | C++ | src/mlapack/Rsbgst.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rsbgst.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rsbgst.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2008-2010
* Nakata, Maho
* All rights reserved.
*
* $Id: Rsbgst.cpp,v 1.12 2010/08/07 04:48:33 nakatamaho Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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 AUTHOR 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 AUTHOR 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.
*
*/
/*
Copyright (c) 1992-2007 The University of Tennessee. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
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 listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <mblas.h>
#include <mlapack.h>
#define MTRUE 1
#define MFALSE 0
void
Rsbgst(const char *vect, const char *uplo, INTEGER n, INTEGER ka, INTEGER kb, REAL * AB, INTEGER ldab, REAL * bb, INTEGER ldbb, REAL * x, INTEGER ldx, REAL * work, INTEGER * info)
{
INTEGER i, j, k, l, m;
REAL t;
INTEGER i0 = 0, i1 = 0, i2 = 0, j1, j2;
REAL ra;
INTEGER nr, nx, ka1, kb1;
REAL ra1 = 0;
INTEGER j1t, j2t;
REAL bii;
INTEGER kbt = 0, nrt, inca;
INTEGER upper, wantx;
INTEGER update;
REAL Zero = 0.0, One = 1.0;
//Test the input parameters
wantx = Mlsame(vect, "V");
upper = Mlsame(uplo, "U");
ka1 = ka + 1;
kb1 = kb + 1;
*info = 0;
if (!wantx && !Mlsame(vect, "N")) {
*info = -1;
} else if (!upper && !Mlsame(uplo, "L")) {
*info = -2;
} else if (n < 0) {
*info = -3;
} else if (ka < 0) {
*info = -4;
} else if (kb < 0 || kb > ka) {
*info = -5;
} else if (ldab < ka + 1) {
*info = -7;
} else if (ldbb < kb + 1) {
*info = -9;
} else if (ldx < 1 || (wantx && ldx < max((INTEGER) 1, n))) {
*info = -11;
}
if (*info != 0) {
Mxerbla("Rsbgst", -(*info));
return;
}
//Quick return if possible
if (n == 0)
return;
inca = ldab * ka1;
//Initialize X to the unit matrix, if needed
if (wantx) {
Rlaset("Full", n, n, Zero, One, &x[0], ldx);
}
//Set M to the splitting point m. It must be the same value as is
//used in DPBSTF. The chosen value allows the arrays WORK and RWORK
//to be of dimension (N).
m = (n + kb) / 2;
/* The routine works in two phases, corresponding to the two halves */
/* of the split Cholesky factorization of B as S**T*S where */
/* S = ( U ) */
/* ( M L ) */
/* with U upper triangular of order m, and L lower triangular of */
/* order n-m. S has the same bandwidth as B. */
/* S is treated as a product of elementary matrices: */
/* S = S(m)*S(m-1)*...*S(2)*S(1)*S(m+1)*S(m+2)*...*S(n-1)*S(n) */
/* where S(i) is determined by the i-th row of S. */
/* In phase 1, the index i takes the values n, n-1, ... , m+1; */
/* in phase 2, it takes the values 1, 2, ... , m. */
/* For each value of i, the current matrix A is updated by forming */
/* inv(S(i))**T*A*inv(S(i)). This creates a triangular bulge outside */
/* the band of A. The bulge is then pushed down toward the bottom of */
/* A in phase 1, and up toward the top of A in phase 2, by applying */
/* plane rotations. */
/* There are kb*(kb+1)/2 elements in the bulge, but at most 2kb-1 */
/* of them are linearly independent, so annihilating a bulge requires */
/* only 2kb-1 plane rotations. The rotations are divided into a 1st */
/* set of kb-1 rotations, and a 2nd set of kb rotations. */
/* Wherever possible, rotations are generated and applied in vector */
/* operations of length NR between the indices J1 and J2 (sometimes */
/* replaced by modified values NRT, J1T or J2T). */
/* The cosines and sines of the rotations are stored in the array */
/* WORK. The cosines of the 1st set of rotations are stored in */
/* elements n+2:n+m-kb-1 and the sines of the 1st set in elements */
/* 2:m-kb-1; the cosines of the 2nd set are stored in elements */
/* n+m-kb+1:2n and the sines of the second set in elements m-kb+1:n. */
/* The bulges are not formed explicitly; nonzero elements outside the */
/* band are created only when they are required for generating new */
/* rotations; they are stored in the array WORK, in positions where */
/* they are later overwritten by the sines of the rotations which */
/* annihilate them. */
/* **************************** Phase 1 ***************************** */
/* The logical structure of this phase is: */
/* UPDATE = .TRUE. */
/* DO I = N, M + 1, -1 */
/* use S(i) to update A and create a new bulge */
/* apply rotations to push all bulges KA positions downward */
/* END DO */
/* UPDATE = .FALSE. */
/* DO I = M + KA + 1, N - 1 */
/* apply rotations to push all bulges KA positions downward */
/* END DO */
//To avoid duplicating code, the two loops are merged.
update = MTRUE;
i = n + 1;
L10:
if (update) {
i--;
kbt = min(kb, i - 1);
i0 = i - 1;
i1 = min(n, i + ka);
i2 = i - kbt + ka1;
if (i < m + 1) {
update = MFALSE;
i++;
i0 = m;
if (ka == 0) {
goto L480;
}
goto L10;
}
} else {
i += ka;
if (i > n - 1) {
goto L480;
}
}
if (upper) {
//Transform A, working with the upper triangle
if (update) {
//Form inv(S(i))**T * A * inv(S(i))
bii = bb[kb1 + i * ldbb];
for (j = i; j <= i1; j++) {
AB[i - j + ka1 + j * ldab] /= bii;
}
for (j = max((INTEGER) 1, i - ka); j <= i; j++) {
AB[j - i + ka1 + i * ldab] /= bii;
}
for (k = i - kbt; k <= i - 1; k++) {
for (j = i - kbt; j <= k; j++) {
AB[j - k + ka1 + k * ldab] = AB[j - k + ka1 + k *
ldab] - bb[j - i + kb1 + i * ldbb] * AB[k - i + ka1 +
i * ldab] - bb[k - i + kb1 +
i * ldbb] * AB[j - i +
ka1 +
i *
ldab] +
AB[ka1 + i * ldab] * bb[j - i + kb1 + i * ldbb] * bb[k - i + kb1 + i * ldbb];
}
for (j = max((INTEGER) 1, i - ka); j <= i - kbt - 1; j++) {
AB[j - k + ka1 + k * ldab] -= bb[k - i + kb1 + i * ldbb] * AB[j - i + ka1 + i * ldab];
}
}
for (j = i; j <= i1; j++) {
for (k = max(j - ka, i - kbt); k <= i - 1; k++) {
AB[k - j + ka1 + j * ldab] -= bb[k - i + kb1 + i * ldbb] * AB[i - j + ka1 + j * ldab];
}
}
if (wantx) {
//post-multiply X by inv(S(i))
Rscal(n - m, One / bii, &x[m + 1 + i * ldx], 1);
if (kbt > 0) {
Rger(n - m, kbt, -One, &x[m + 1 + i * ldx], 1, &bb[kb1 - kbt + i * ldbb], 1, &x[m + 1 + (i - kbt) * ldx], ldx);
}
}
//store a(i,i1) in RA1 for use in next loop over K
ra1 = AB[i - i1 + ka1 + i1 * ldab];
}
//Generate and apply vectors of rotations to chase all the
//existing bulges KA positions down toward the bottom of the
//band
for (k = 0; k < kb - 1; k++) {
if (update) {
//Determine the rotations which would annihilate the bulge
//which has in theory just been created
if (i - k + ka < n && i - k > 1) {
//generate rotation to annihilate a(i,i-k+ka+1)
Rlartg(AB[k + 1 + (i - k + ka) * ldab], ra1, &work[n + i - k + ka - m], &work[i - k + ka - m], &ra);
//create nonzero element a(i-k,i-k+ka+1) outside the
//band and store it in WORK(i-k)
t = -bb[kb1 - k + i * ldbb] * ra1;
work[i - k] = work[n + i - k + ka - m] * t - work[i - k + ka - m] * AB[(i - k + ka) * ldab + 1];
AB[(i - k + ka) * ldab + 1] = work[i - k + ka - m] * t + work[n + i - k + ka - m] * AB[(i - k + ka) * ldab + 1];
ra1 = ra;
}
}
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 2) * ka1;
nr = (n - j2 + ka) / ka1;
j1 = j2 + (nr - 1) * ka1;
if (update) {
j2t = max(j2, i + (ka << 1) - k + 1);
} else {
j2t = j2;
}
nrt = (n - j2t + ka) / ka1;
for (j = j2t; j < j1; j += ka1) {
//create nonzero element a(j-ka,j+1) outside the band
//and store it in WORK(j-m)
work[j - m] *= AB[(j + 1) * ldab + 1];
AB[(j + 1) * ldab + 1] = work[n + j - m] * AB[(j + 1) * ldab + 1];
}
//generate rotations in 1st set to annihilate elements which
//have been created outside the band
if (nrt > 0) {
Rlargv(nrt, &AB[j2t * ldab + 1], inca, &work[j2t - m], ka1, &work[n + j2t - m], ka1);
}
if (nr > 0) {
//apply rotations in 1st set from the right
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[ka1 - l + j2 * ldab], inca, &AB[ka - l + (j2 + 1) * ldab], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
//apply rotations in 1st set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[ka1 + j2 * ldab], &AB[ka1 + (j2 + 1) * ldab], &AB[ka + (j2 + 1) * ldab], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
//start applying rotations in 1st set from the left
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (n - j2 + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + (j2 + ka1 - l) * ldab], inca, &AB[l + 1 + (j2 + ka1 - l) * ldab], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 1st set
for (j = j2; j < j1; j += ka1) {
Rrot(n - m, &x[m + 1 + j * ldx], 1, &x[m + 1 + (j + 1) * ldx], 1, work[n + j - m], work[j - m]);
}
}
}
if (update) {
if (i2 <= n && kbt > 0) {
//create nonzero element a(i-kbt,i-kbt+ka+1) outside the
//band and store it in WORK(i-kbt)
work[i - kbt] = -bb[kb1 - kbt + i * ldbb] * ra1;
}
}
for (k = kb; k >= 1; k--) {
if (update) {
j2 = i - k - 1 + max((INTEGER) 2, k - i0 + 1) * ka1;
} else {
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 1) * ka1;
}
//finish applying rotations in 2nd set from the left
for (l = kb - k; l >= 1; l--) {
nrt = (n - j2 + ka + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + (j2 - l + 1) * ldab], inca, &AB[l + 1 + (j2 - l + 1) * ldab], inca, &work[n + j2 - ka], &work[j2 - ka], ka1);
}
}
nr = (n - j2 + ka) / ka1;
j1 = j2 + (nr - 1) * ka1;
for (j = j1; j < j2; j = j - ka1) {
work[j] = work[j - ka];
work[n + j] = work[n + j - ka];
}
for (j = j2; j < j1; j += ka1) {
//create nonzero element a(j-ka,j+1) outside the band
//and store it in WORK(j)
work[j] *= AB[(j + 1) * ldab + 1];
AB[(j + 1) * ldab + 1] = work[n + j] * AB[(j + 1) * ldab + 1];
}
if (update) {
if (i - k < n - ka && k <= kbt) {
work[i - k + ka] = work[i - k];
}
}
}
for (k = kb; k >= 1; k--) {
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 1) * ka1;
nr = (n - j2 + ka) / ka1;
j1 = j2 + (nr - 1) * ka1;
if (nr > 0) {
//generate rotations in 2nd set to annihilate elements
//which have been created outside the band
Rlargv(nr, &AB[j2 * ldab + 1], inca, &work[j2], ka1, &work[n + j2], ka1);
//apply rotations in 2nd set from the right
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[ka1 - l + j2 * ldab], inca, &AB[ka - l + (j2 + 1) * ldab], inca, &work[n + j2], &work[j2], ka1);
}
//apply rotations in 2nd set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[ka1 + j2 * ldab], &AB[ka1 + (j2 + 1) * ldab], &AB[ka + (j2 + 1) * ldab], inca, &work[n + j2], &work[j2], ka1);
}
//start applying rotations in 2nd set from the left
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (n - j2 + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + (j2 + ka1 - l) * ldab], inca, &AB[l + 1 + (j2 + ka1 - l) * ldab], inca, &work[n + j2], &work[j2], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 2nd set
for (j = j2; j < j1; j += ka1) {
Rrot(n - m, &x[m + 1 + j * ldx], 1, &x[m + 1 + (j + 1) * ldx], 1, work[n + j], work[j]);
}
}
}
for (k = 0; k < kb - 1; k++) {
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 2) * ka1;
//finish applying rotations in 1st set from the left
for (l = kb - k; l >= 1; l--) {
nrt = (n - j2 + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + (j2 + ka1 - l) * ldab], inca, &AB[l + 1 + (j2 + ka1 - l) * ldab], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
}
}
if (kb > 1) {
for (j = n - 1; j >= i - kb + (ka << 1) + 1; j--) {
work[n + j - m] = work[n + j - ka - m];
work[j - m] = work[j - ka - m];
}
}
} else {
//Transform A, working with the lower triangle
if (update) {
//Form inv(S(i))**T * A * inv(S(i))
bii = bb[i * ldbb + 1];
for (j = i; j <= i1; j++) {
AB[j - i + 1 + i * ldab] /= bii;
}
for (j = max((INTEGER) 1, i - ka); j <= i; j++) {
AB[i - j + 1 + j * ldab] /= bii;
}
for (k = i - kbt; k <= i - 1; k++) {
for (j = i - kbt; j <= k; j++) {
AB[k - j + 1 + j * ldab] = AB[k - j + 1 + j * ldab]
- bb[i - j + 1 + j * ldbb] * AB[i - k + 1
+ k * ldab] - bb[i - k + 1 + k * ldbb] * AB[i - j + 1 +
j * ldab] + AB[i * ldab +
1] * bb[i - j + 1 + j * ldbb] * bb[i - k + 1 + k * ldbb];
}
for (j = max((INTEGER) 1, i - ka); j <= i - kbt - 1; j++) {
AB[k - j + 1 + j * ldab] -= bb[i - k + 1 + k * ldbb] * AB[i - j + 1 + j * ldab];
}
}
for (j = i; j <= i1; j++) {
for (k = max(j - ka, i - kbt); k <= i - 1; k++) {
AB[j - k + 1 + k * ldab] -= bb[i - k + 1 + k * ldbb] * AB[j - i + 1 + i * ldab];
}
}
if (wantx) {
//post-multiply X by inv(S(i))
Rscal(n - m, One / bii, &x[m + 1 + i * ldx], 1);
if (kbt > 0) {
Rger(n - m, kbt, -One, &x[m + 1 + i * ldx], 1, &bb[kbt + 1 + (i - kbt) * ldbb], ldbb - 1, &x[m + 1 + (i - kbt) * ldx], ldx);
}
}
//store a(i1,i) in RA1 for use in next loop over K
ra1 = AB[i1 - i + 1 + i * ldab];
}
//Generate and apply vectors of rotations to chase all the
//existing bulges KA positions down toward the bottom of the
//band
for (k = 0; k < kb - 1; k++) {
if (update) {
//Determine the rotations which would annihilate the bulge
//which has in theory just been created
if (i - k + ka < n && i - k > 1) {
//generate rotation to annihilate a(i-k+ka+1,i)
Rlartg(AB[ka1 - k + i * ldab], ra1, &work[n + i - k + ka - m], &work[i - k + ka - m], &ra);
//create nonzero element a(i-k+ka+1,i-k) outside the
//band and store it in WORK(i-k)
t = -bb[k + 1 + (i - k) * ldbb] * ra1;
work[i - k] = work[n + i - k + ka - m] * t - work[i - k + ka - m] * AB[ka1 + (i - k) * ldab];
AB[ka1 + (i - k) * ldab] = work[i - k + ka - m] * t + work[n + i - k + ka - m] * AB[ka1 + (i - k) * ldab];
ra1 = ra;
}
}
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 2) * ka1;
nr = (n - j2 + ka) / ka1;
j1 = j2 + (nr - 1) * ka1;
if (update) {
j2t = max(j2, i + (ka << 1) - k + 1);
} else {
j2t = j2;
}
nrt = (n - j2t + ka) / ka1;
for (j = j2t; j < j1; j += ka1) {
//create nonzero element a(j+1,j-ka) outside the band
//and store it in WORK(j-m)
work[j - m] *= AB[ka1 + (j - ka + 1) * ldab];
AB[ka1 + (j - ka + 1) * ldab] = work[n + j - m] * AB[ka1 + (j - ka + 1) * ldab];
}
//generate rotations in 1st set to annihilate elements which
//have been created outside the band
if (nrt > 0) {
Rlargv(nrt, &AB[ka1 + (j2t - ka) * ldab], inca, &work[j2t - m], ka1, &work[n + j2t - m], ka1);
}
if (nr > 0) {
//apply rotations in 1st set from the left
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[l + 1 + (j2 - l) * ldab], inca, &AB[l + 2 + (j2 - l) * ldab], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
//apply rotations in 1st set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[j2 * ldab + 1], &AB[(j2 + 1) * ldab + 1], &AB[j2 * ldab + 2], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
//start applying rotations in 1st set from the right
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (n - j2 + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + j2 * ldab], inca, &AB[ka1 - l + (j2 + 1) * ldab], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 1st set
for (j = j2; j <= j1; j += ka1) {
Rrot(n - m, &x[m + 1 + j * ldx], 1, &x[m + 1 + (j + 1) * ldx], 1, work[n + j - m], work[j - m]);
}
}
}
if (update) {
if (i2 <= n && kbt > 0) {
//create nonzero element a(i-kbt+ka+1,i-kbt) outside the
//band and store it in WORK(i-kbt)
work[i - kbt] = -bb[kbt + 1 + (i - kbt) * ldbb] * ra1;
}
}
for (k = kb; k >= 1; k--) {
if (update) {
j2 = i - k - 1 + max((INTEGER) 2, k - i0 + 1) * ka1;
} else {
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 1) * ka1;
}
//finish applying rotations in 2nd set from the right
for (l = kb - k; l >= 1; l--) {
nrt = (n - j2 + ka + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + (j2 - ka) * ldab], inca, &AB[ka1 - l + (j2 - ka + 1) * ldab], inca, &work[n + j2 - ka], &work[j2 - ka], ka1);
}
}
nr = (n - j2 + ka) / ka1;
j1 = j2 + (nr - 1) * ka1;
for (j = j1; j <= j2; j = j - ka1) {
work[j] = work[j - ka];
work[n + j] = work[n + j - ka];
}
for (j = j2; j < j1; j += ka1) {
//create nonzero element a(j+1,j-ka) outside the band
//and store it in WORK(j)
work[j] *= AB[ka1 + (j - ka + 1) * ldab];
AB[ka1 + (j - ka + 1) * ldab] = work[n + j] * AB[ka1 + (j - ka + 1) * ldab];
}
if (update) {
if (i - k < n - ka && k <= kbt) {
work[i - k + ka] = work[i - k];
}
}
}
for (k = kb; k >= 1; k--) {
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 1) * ka1;
nr = (n - j2 + ka) / ka1;
j1 = j2 + (nr - 1) * ka1;
if (nr > 0) {
//generate rotations in 2nd set to annihilate elements
//which have been created outside the band
Rlargv(nr, &AB[ka1 + (j2 - ka) * ldab], inca, &work[j2], ka1, &work[n + j2], ka1);
//apply rotations in 2nd set from the left
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[l + 1 + (j2 - l) * ldab], inca, &AB[l + 2 + (j2 - l) * ldab], inca, &work[n + j2], &work[j2], ka1);
}
//apply rotations in 2nd set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[j2 * ldab + 1], &AB[(j2 + 1) * ldab + 1], &AB[j2 * ldab + 2], inca, &work[n + j2], &work[j2], ka1);
}
//start applying rotations in 2nd set from the right
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (n - j2 + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + j2 * ldab], inca, &AB[ka1 - l + (j2 + 1) * ldab], inca, &work[n + j2], &work[j2], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 2nd set
for (j = j2; j <= j1; j += ka1) {
Rrot(n - m, &x[m + 1 + j * ldx], 1, &x[m + 1 + (j + 1) * ldx], 1, work[n + j], work[j]);
}
}
}
for (k = 0; k < kb - 1; k++) {
j2 = i - k - 1 + max((INTEGER) 1, k - i0 + 2) * ka1;
//finish applying rotations in 1st set from the right
for (l = kb - k; l >= 1; l--) {
nrt = (n - j2 + l) / ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + j2 * ldab], inca, &AB[ka1 - l + (j2 + 1) * ldab], inca, &work[n + j2 - m], &work[j2 - m], ka1);
}
}
}
if (kb > 1) {
for (j = n - 1; j >= i - kb + (ka << 1) + 1; j--) {
work[n + j - m] = work[n + j - ka - m];
work[j - m] = work[j - ka - m];
}
}
}
goto L10;
L480:
/* **************************** Phase 2 ***************************** */
/* The logical structure of this phase is: */
/* UPDATE = .TRUE. */
/* DO I = 1, M */
/* use S(i) to update A and create a new bulge */
/* apply rotations to push all bulges KA positions upward */
/* END DO */
/* UPDATE = .FALSE. */
/* DO I = M - KA - 1, 2, -1 */
/* apply rotations to push all bulges KA positions upward */
/* END DO */
/* To avoid duplicating code, the two loops are merged. */
update = MTRUE;
i = 0;
L490:
if (update) {
i++;
kbt = min(kb, m - i);
i0 = i + 1;
i1 = max((INTEGER) 1, i - ka);
i2 = i + kbt - ka1;
if (i > m) {
update = MFALSE;
i--;
i0 = m + 1;
if (ka == 0) {
return;
}
goto L490;
}
} else {
i -= ka;
if (i < 2) {
return;
}
}
if (i < m - kbt) {
nx = m;
} else {
nx = n;
}
if (upper) {
//Transform A, working with the upper triangle
if (update) {
//Form inv(S(i))**T * A * inv(S(i))
bii = bb[kb1 + i * ldbb];
for (j = i1; j <= i; j++) {
AB[j - i + ka1 + i * ldab] /= bii;
}
for (j = i; j <= min(n, i + ka1); j++) {
AB[i - j + ka1 + j * ldab] /= bii;
}
for (k = i + 1; k <= i + kbt; k++) {
for (j = k; j <= i + kbt; j++) {
AB[k - j + ka1 + j * ldab] = AB[k - j + ka1 + j *
ldab] - bb[i - j + kb1 + j * ldbb] * AB[i - k + ka1 +
k * ldab] - bb[i - k + kb1 +
k * ldbb] * AB[i - j +
ka1 +
j *
ldab] +
AB[ka1 + i * ldab] * bb[i - j + kb1 + j * ldbb] * bb[i - k + kb1 + k * ldbb];
}
for (j = i + kbt + 1; j <= min(n, i + ka); j++) {
AB[k - j + ka1 + j * ldab] -= bb[i - k + kb1 + k * ldbb] * AB[i - j + ka1 + j * ldab];
}
}
for (j = i1; j <= i; j++) {
for (k = i + 1; k <= min(j + ka, i + kbt); k++) {
AB[j - k + ka1 + k * ldab] -= bb[i - k + kb1 + k * ldbb] * AB[j - i + ka1 + i * ldab];
}
}
if (wantx) {
//post-multiply X by inv(S(i))
Rscal(nx, One / bii, &x[i * ldx + 1], 1);
if (kbt > 0) {
Rger(nx, kbt, -One, &x[i * ldx + 1], 1, &bb[kb + (i + 1) * ldbb], ldbb - 1, &x[(i + 1) * ldx + 1], ldx);
}
}
//store a(i1,i) in RA1 for use in next loop over K
ra1 = AB[i1 - i + ka1 + i * ldab];
}
//Generate and apply vectors of rotations to chase all the
//existing bulges KA positions up toward the top of the band
for (k = 0; k < kb - 1; k++) {
if (update) {
//Dtermine the rotations which would annihilate the bulge
//which has in theory just been created
if (i + k - ka1 > 0 && i + k < m) {
//generate rotation to annihilate a(i+k-ka-1,i)
Rlartg(AB[k + 1 + i * ldab], ra1, &work[n + i + k - ka], &work[i + k - ka], &ra);
//create nonzero element a(i+k-ka-1,i+k) outside the
//band and store it in WORK(m-kb+i+k)
t = -bb[kb1 - k + (i + k) * ldbb] * ra1;
work[m - kb + i + k] = work[n + i + k - ka] * t - work[i + k - ka] * AB[(i + k) * ldab + 1];
AB[(i + k) * ldab + 1] = work[i + k - ka] * t + work[n + i + k - ka] * AB[(i + k) * ldab + 1];
ra1 = ra;
}
}
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m + 1) * ka1;
nr = (j2 + ka - 1) / ka1;
j1 = j2 - (nr - 1) * ka1;
if (update) {
j2t = min(j2, i - (ka << 1) + k - 1);
} else {
j2t = j2;
}
nrt = (j2t + ka - 1) / ka1;
for (j = j1; j <= j2t; j += ka1) {
//create nonzero element a(j-1,j+ka) outside the band
//and store it in WORK(j)
work[j] *= AB[(j + ka - 1) * ldab + 1];
AB[(j + ka - 1) * ldab + 1] = work[n + j] * AB[(j + ka - 1) * ldab + 1];
}
//generate rotations in 1st set to annihilate elements which
//have been created outside the band
if (nrt > 0) {
Rlargv(nrt, &AB[(j1 + ka) * ldab + 1], inca, &work[j1], ka1, &work[n + j1], ka1);
}
if (nr > 0) {
//apply rotations in 1st set from the left
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[ka1 - l + (j1 + l) * ldab], inca, &AB[ka - l + (j1 + l) * ldab], inca, &work[n + j1], &work[j1], ka1);
}
//apply rotations in 1st set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[ka1 + j1 * ldab], &AB[ka1 + (j1 - 1) * ldab], &AB[ka + j1 * ldab], inca, &work[n + j1], &work[j1], ka1);
}
//start applying rotations in 1st set from the right
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (j2 + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + j1t * ldab], inca, &AB[l + 1 + (j1t - 1) * ldab], inca, &work[n + j1t], &work[j1t], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 1st set
for (j = j1; j <= j2; j += ka1) {
Rrot(nx, &x[j * ldx + 1], 1, &x[(j - 1) * ldx + 1], 1, work[n + j], work[j]);
}
}
}
if (update) {
if (i2 > 0 && kbt > 0) {
//create nonzero element a(i+kbt-ka-1,i+kbt) outside the
//band and store it in WORK(m-kb+i+kbt)
work[m - kb + i + kbt] = -bb[kb1 - kbt + (i + kbt) * ldbb] * ra1;
}
}
for (k = kb; k >= 1; k--) {
if (update) {
j2 = i + k + 1 - max((INTEGER) 2, k + i0 - m) * ka1;
} else {
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m) * ka1;
}
//finish applying rotations in 2nd set from the right
for (l = kb - k; l >= 1; l--) {
nrt = (j2 + ka + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + (j1t + ka) * ldab], inca, &AB[l + 1 + (j1t + ka - 1) * ldab], inca, &work[n + m - kb + j1t + ka], &work[m - kb + j1t + ka], ka1);
}
}
nr = (j2 + ka - 1) / ka1;
j1 = j2 - (nr - 1) * ka1;
for (j = j1; j <= j2; j += ka1) {
work[m - kb + j] = work[m - kb + j + ka];
work[n + m - kb + j] = work[n + m - kb + j + ka];
}
for (j = j1; j <= j2; j += ka1) {
//create nonzero element a(j-1,j+ka) outside the band
//and store it in WORK(m-kb+j)
work[m - kb + j] *= AB[(j + ka - 1) * ldab + 1];
AB[(j + ka - 1) * ldab + 1] = work[n + m - kb + j] * AB[(j + ka - 1) * ldab + 1];
}
if (update) {
if (i + k > ka1 && k <= kbt) {
work[m - kb + i + k - ka] = work[m - kb + i + k];
}
}
}
for (k = kb; k >= 1; k--) {
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m) * ka1;
nr = (j2 + ka - 1) / ka1;
j1 = j2 - (nr - 1) * ka1;
if (nr > 0) {
//generate rotations in 2nd set to annihilate elements
//which have been created outside the band
Rlargv(nr, &AB[(j1 + ka) * ldab + 1], inca, &work[m - kb + j1], ka1, &work[n + m - kb + j1], ka1);
//apply rotations in 2nd set from the left
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[ka1 - l + (j1 + l) * ldab], inca, &AB[ka - l + (j1 + l) * ldab], inca, &work[n + m - kb + j1], &work[m - kb + j1], ka1);
}
//apply rotations in 2nd set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[ka1 + j1 * ldab], &AB[ka1 + (j1 - 1) * ldab], &AB[ka + j1 * ldab], inca, &work[n + m - kb + j1], &work[m - kb + j1], ka1);
}
//start applying rotations in 2nd set from the right
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (j2 + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + j1t * ldab], inca, &AB[l + 1 + (j1t - 1) * ldab], inca, &work[n + m - kb + j1t], &work[m - kb + j1t], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 2nd set
for (j = j1; j <= j2; j += ka1) {
Rrot(nx, &x[j * ldx + 1], 1, &x[(j - 1) * ldx + 1], 1, work[n + m - kb + j], work[m - kb + j]);
}
}
}
for (k = 0; k < kb - 1; k++) {
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m + 1) * ka1;
//finish applying rotations in 1st set from the right
for (l = kb - k; l >= 1; l--) {
nrt = (j2 + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[l + j1t * ldab], inca, &AB[l + 1 + (j1t - 1) * ldab], inca, &work[n + j1t], &work[j1t], ka1);
}
}
}
if (kb > 1) {
for (j = 2; j <= min(i + kb, m) - (ka << 1) - 1; j++) {
work[n + j] = work[n + j + ka];
work[j] = work[j + ka];
}
}
} else {
//Transform A, working with the lower triangle
if (update) {
//Form inv(S(i))**T * A * inv(S(i))
bii = bb[i * ldbb + 1];
for (j = i1; j <= i; j++) {
AB[i - j + 1 + j * ldab] /= bii;
}
for (j = i; j <= min(n, i + ka); j++) {
AB[j - i + 1 + i * ldab] /= bii;
}
for (k = i + 1; k <= i + kbt; k++) {
for (j = k; j <= i + kbt; j++) {
AB[j - k + 1 + k * ldab] = AB[j - k + 1 + k * ldab]
- bb[j - i + 1 + i * ldbb] * AB[k - i + 1 + i * ldab] - bb[k - i + 1 + i * ldbb] * AB[j - i + 1 + i * ldab] + AB[i * ldab + 1] * bb[j - i + 1 + i * ldbb]
* bb[k - i + 1 + i * ldbb];
}
for (j = i + kbt + 1; j <= min(n, i + ka); j++) {
AB[j - k + 1 + k * ldab] -= bb[k - i + 1 + i * ldbb] * AB[j - i + 1 + i * ldab];
}
}
for (j = i1; j <= i; j++) {
for (k = i + 1; k <= min(j + ka, i + kbt); k++) {
AB[k - j + 1 + j * ldab] -= bb[k - i + 1 + i * ldbb] * AB[i - j + 1 + j * ldab];
}
}
if (wantx) {
//post-multiply X by inv(S(i))
Rscal(nx, One / bii, &x[i * ldx + 1], 1);
if (kbt > 0) {
Rger(nx, kbt, -One, &x[i * ldx + 1], 1, &bb[i * ldbb + 2], 1, &x[(i + 1) * ldx + 1], ldx);
}
}
//store a(i,i1) in RA1 for use in next loop over K
ra1 = AB[i - i1 + 1 + i1 * ldab];
}
//Generate and apply vectors of rotations to chase all the
//existing bulges KA positions up toward the top of the band
for (k = 0; k < kb - 1; k++) {
if (update) {
//Determine the rotations which would annihilate the bulge
//which has in theory just been created
if (i + k - ka1 > 0 && i + k < m) {
//generate rotation to annihilate a(i,i+k-ka-1)
Rlartg(AB[ka1 - k + (i + k - ka) * ldab], ra1, &work[n + i + k - ka], &work[i + k - ka], &ra);
//create nonzero element a(i+k,i+k-ka-1) outside the
//band and store it in WORK(m-kb+i+k)
t = -bb[k + 1 + i * ldbb] * ra1;
work[m - kb + i + k] = work[n + i + k - ka] * t - work[i + k - ka] * AB[ka1 + (i + k - ka) * ldab];
AB[ka1 + (i + k - ka) * ldab] = work[i + k - ka]
* t + work[n + i + k - ka] * AB[ka1 + (i + k - ka) * ldab];
ra1 = ra;
}
}
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m + 1) * ka1;
nr = (j2 + ka - 1) / ka1;
j1 = j2 - (nr - 1) * ka1;
if (update) {
j2t = min(j2, i - (ka << 1) + k - 1);
} else {
j2t = j2;
}
nrt = (j2t + ka - 1) / ka1;
for (j = j1; j <= j2; j += ka1) {
//create nonzero element a(j+ka,j-1) outside the band
//and store it in WORK(j)
work[j] *= AB[ka1 + (j - 1) * ldab];
AB[ka1 + (j - 1) * ldab] = work[n + j] * AB[ka1 + (j - 1) * ldab];
}
//generate rotations in 1st set to annihilate elements which
//have been created outside the band
if (nrt > 0) {
Rlargv(nrt, &AB[ka1 + j1 * ldab], inca, &work[j1], ka1, &work[n + j1], ka1);
}
if (nr > 0) {
//apply rotations in 1st set from the right
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[l + 1 + j1 * ldab], inca, &AB[l + 2 + (j1 - 1) * ldab], inca, &work[n + j1], &work[j1], ka1);
}
//apply rotations in 1st set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[j1 * ldab + 1], &AB[(j1 - 1) * ldab + 1], &AB[(j1 - 1) * ldab + 2], inca, &work[n + j1]
, &work[j1], ka1);
}
//start applying rotations in 1st set from the left
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (j2 + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + (j1t - ka1 + l) * ldab]
, inca, &AB[ka1 - l + (j1t - ka1 + l) * ldab], inca, &work[n + j1t], &work[j1t], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 1st set
for (j = j1; j <= j2; j += ka1) {
Rrot(nx, &x[j * ldx + 1], 1, &x[(j - 1) * ldx + 1], 1, work[n + j], work[j]);
}
}
}
if (update) {
if (i2 > 0 && kbt > 0) {
//create nonzero element a(i+kbt,i+kbt-ka-1) outside the
//band and store it in WORK(m-kb+i+kbt)
work[m - kb + i + kbt] = -bb[kbt + 1 + i * ldbb] * ra1;
}
}
for (k = kb; k >= 1; k--) {
if (update) {
j2 = i + k + 1 - max((INTEGER) 2, k + i0 - m) * ka1;
} else {
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m) * ka1;
}
//finish applying rotations in 2nd set from the left
for (l = kb - k; l >= 1; l--) {
nrt = (j2 + ka + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + (j1t + l - 1) * ldab],
inca, &AB[ka1 - l + (j1t + l - 1) * ldab], inca, &work[n + m - kb + j1t + ka], &work[m - kb + j1t + ka], ka1);
}
}
nr = (j2 + ka - 1) / ka1;
j1 = j2 - (nr - 1) * ka1;
for (j = j1; j <= j2; j += ka1) {
work[m - kb + j] = work[m - kb + j + ka];
work[n + m - kb + j] = work[n + m - kb + j + ka];
}
for (j = j1; j < j2; j += ka1) {
//create nonzero element a(j+ka,j-1) outside the band
//and store it in WORK(m-kb+j)
work[m - kb + j] *= AB[ka1 + (j - 1) * ldab];
AB[ka1 + (j - 1) * ldab] = work[n + m - kb + j] * AB[ka1 + (j - 1) * ldab];
}
if (update) {
if (i + k > ka1 && k <= kbt) {
work[m - kb + i + k - ka] = work[m - kb + i + k];
}
}
}
for (k = kb; k >= 1; k--) {
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m) * ka1;
nr = (j2 + ka - 1) / ka1;
j1 = j2 - (nr - 1) * ka1;
if (nr > 0) {
//generate rotations in 2nd set to annihilate elements
//which have been created outside the band
Rlargv(nr, &AB[ka1 + j1 * ldab], inca, &work[m - kb + j1], ka1, &work[n + m - kb + j1], ka1);
//apply rotations in 2nd set from the right
for (l = 0; l < ka - 1; l++) {
Rlartv(nr, &AB[l + 1 + j1 * ldab], inca, &AB[l + 2 + (j1 - 1) * ldab], inca, &work[n + m - kb + j1], &work[m - kb + j1], ka1);
}
//apply rotations in 2nd set from both sides to diagonal
//blocks
Rlar2v(nr, &AB[j1 * ldab + 1], &AB[(j1 - 1) * ldab + 1], &AB[(j1 - 1) * ldab + 2], inca, &work[n + m - kb + j1], &work[m - kb + j1], ka1);
}
//start applying rotations in 2nd set from the left
for (l = ka - 1; l >= kb - k + 1; l--) {
nrt = (j2 + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + (j1t - ka1 + l) * ldab]
, inca, &AB[ka1 - l + (j1t - ka1 + l) * ldab], inca, &work[n + m - kb + j1t], &work[m - kb + j1t], ka1);
}
}
if (wantx) {
//post-multiply X by product of rotations in 2nd set
for (j = j1; j < j2; j += ka1) {
Rrot(nx, &x[j * ldx + 1], 1, &x[(j - 1) * ldx + 1], 1, work[n + m - kb + j], work[m - kb + j]);
}
}
}
for (k = 0; k < kb - 1; k++) {
j2 = i + k + 1 - max((INTEGER) 1, k + i0 - m + 1) * ka1;
//finish applying rotations in 1st set from the left
for (l = kb - k; l >= 1; l--) {
nrt = (j2 + l - 1) / ka1;
j1t = j2 - (nrt - 1) * ka1;
if (nrt > 0) {
Rlartv(nrt, &AB[ka1 - l + 1 + (j1t - ka1 + l) * ldab]
, inca, &AB[ka1 - l + (j1t - ka1 + l) * ldab], inca, &work[n + j1t], &work[j1t], ka1);
}
}
}
if (kb > 1) {
for (j = 2; j <= min(i + kb, m) - (ka << 1) - 1; j++) {
work[n + j] = work[n + j + ka];
work[j] = work[j + ka];
}
}
}
goto L490;
}
| 35.364078 | 179 | 0.490652 | [
"vector",
"transform"
] |
a8c8e93e78eb36a31f2031bac8ffda22995a8be6 | 5,535 | hpp | C++ | include/Zenject/AnimatorIkHandlerManager.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/Zenject/AnimatorIkHandlerManager.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/Zenject/AnimatorIkHandlerManager.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: IAnimatorIkHandler
class IAnimatorIkHandler;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: Zenject.AnimatorIkHandlerManager
// [TokenAttribute] Offset: FFFFFFFF
class AnimatorIkHandlerManager : public UnityEngine::MonoBehaviour {
public:
// private System.Collections.Generic.List`1<Zenject.IAnimatorIkHandler> _handlers
// Size: 0x8
// Offset: 0x18
System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>* handlers;
// Field size check
static_assert(sizeof(System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>*) == 0x8);
// Creating value type constructor for type: AnimatorIkHandlerManager
AnimatorIkHandlerManager(System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>* handlers_ = {}) noexcept : handlers{handlers_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field: private System.Collections.Generic.List`1<Zenject.IAnimatorIkHandler> _handlers
System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>* _get__handlers();
// Set instance field: private System.Collections.Generic.List`1<Zenject.IAnimatorIkHandler> _handlers
void _set__handlers(System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>* value);
// public System.Void Construct(System.Collections.Generic.List`1<Zenject.IAnimatorIkHandler> handlers)
// Offset: 0x111F6C0
void Construct(System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>* handlers);
// public System.Void OnAnimatorIk()
// Offset: 0x111F6C8
void OnAnimatorIk();
// public System.Void .ctor()
// Offset: 0x111F828
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AnimatorIkHandlerManager* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("Zenject::AnimatorIkHandlerManager::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AnimatorIkHandlerManager*, creationType>()));
}
}; // Zenject.AnimatorIkHandlerManager
#pragma pack(pop)
static check_size<sizeof(AnimatorIkHandlerManager), 24 + sizeof(System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>*)> __Zenject_AnimatorIkHandlerManagerSizeCheck;
static_assert(sizeof(AnimatorIkHandlerManager) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::AnimatorIkHandlerManager*, "Zenject", "AnimatorIkHandlerManager");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Zenject::AnimatorIkHandlerManager::Construct
// Il2CppName: Construct
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Zenject::AnimatorIkHandlerManager::*)(System::Collections::Generic::List_1<Zenject::IAnimatorIkHandler*>*)>(&Zenject::AnimatorIkHandlerManager::Construct)> {
static const MethodInfo* get() {
static auto* handlers = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("Zenject", "IAnimatorIkHandler")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Zenject::AnimatorIkHandlerManager*), "Construct", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{handlers});
}
};
// Writing MetadataGetter for method: Zenject::AnimatorIkHandlerManager::OnAnimatorIk
// Il2CppName: OnAnimatorIk
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Zenject::AnimatorIkHandlerManager::*)()>(&Zenject::AnimatorIkHandlerManager::OnAnimatorIk)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Zenject::AnimatorIkHandlerManager*), "OnAnimatorIk", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Zenject::AnimatorIkHandlerManager::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 57.061856 | 245 | 0.741102 | [
"object",
"vector"
] |
a8cf989f8d98238a9abfc905500f174e00e45f23 | 45,047 | cpp | C++ | itemdb_parse.cpp | zorbathut/d-net | 61f610ca71270c6a95cf57dc3acaeab8559a234b | [
"MIT"
] | 1 | 2016-11-02T06:47:52.000Z | 2016-11-02T06:47:52.000Z | itemdb_parse.cpp | zorbathut/d-net | 61f610ca71270c6a95cf57dc3acaeab8559a234b | [
"MIT"
] | null | null | null | itemdb_parse.cpp | zorbathut/d-net | 61f610ca71270c6a95cf57dc3acaeab8559a234b | [
"MIT"
] | null | null | null |
#include "itemdb_parse.h"
#include "dumper_registry.h"
#include "itemdb_private.h"
#include "itemdb_stream.h"
#include "parse.h"
#include "regex.h"
#include "stream_file.h"
#include "stream_gz.h"
#include "stream_process_string.h"
#include "stream_process_utility.h"
#include "stream_process_vector.h"
#include <fstream>
#include <numeric>
#include <set>
using namespace std;
DEFINE_bool(debugitems, false, "Enable debug items");
REGISTER_bool(debugitems);
class ErrorAccumulator {
public:
void addError(const string &text) {
string tt = StringPrintf("%s:%d - %s", fname.c_str(), line, text.c_str());
dprintf("%s\n", tt.c_str());
errors->push_back(tt);
}
ErrorAccumulator(vector<string> *errors, const string &fname, int line) : errors(errors), fname(fname), line(line) { };
private:
vector<string> *errors;
string fname;
int line;
};
bool prefixed(const string &label, const string &prefix) {
if(label.size() < prefix.size() + 1)
return false;
if(label[prefix.size()] != '.')
return false;
if(strncmp(label.c_str(), prefix.c_str(), prefix.size()))
return false;
return true;
}
template<typename T> T *prepareName(const string &name, map<string, T> *classes, bool reload, const string &prefix = "", string *namestorage = NULL) {
if(prefix.size())
CHECK(prefixed(name, prefix));
if(classes->count(name)) {
if(!reload) {
dprintf("Multiple definition of %s\n", name.c_str());
CHECK(0);
} else {
(*classes)[name] = T();
}
}
return &(*classes)[name];
}
template<typename T> T *prepareName(kvData *chunk, map<string, T> *classes, bool reload, const string &prefix = "", string *namestorage = NULL) {
string name = chunk->consume("name");
if(namestorage)
*namestorage = name;
return prepareName(name, classes, reload, prefix);
}
template<typename T> T *prepareName(kvData *chunk, map<string, T> *classes, bool reload, string *namestorage) {
return prepareName(chunk, classes, reload, "", namestorage);
}
template<typename T> const T *parseSubclass(const string &name, const map<string, T> &classes) {
if(!classes.count(name)) {
dprintf("Can't find token %s\n", name.c_str());
CHECK(0);
}
return &classes.find(name)->second;
}
template<typename T> vector<const T *> parseSubclassSet(kvData *chunk, const string &name, const map<string, T> &classes) {
if(!chunk->kv.count(name))
return vector<const T *>();
vector<const T *> types;
vector<string> items = tokenize(chunk->consume(name), "\n");
CHECK(items.size());
for(int i = 0; i < items.size(); i++) {
if(!classes.count(items[i])) {
dprintf("Can't find object %s\n", items[i].c_str());
CHECK(0);
}
types.push_back(&classes.find(items[i])->second);
}
return types;
}
template<typename T> const T *parseOptionalSubclass(kvData *chunk, const string &label, const map<string, T> &classes) {
if(!chunk->kv.count(label))
return NULL;
return parseSubclass(chunk->consume(label), classes);
}
template<typename T> T parseSingleItem(const string &val);
template<> bool parseSingleItem<bool>(const string &val) {
string lowered;
for(int i = 0; i < val.size(); i++)
lowered += val[i];
if(lowered == "t" || lowered == "true")
return true;
if(lowered == "f" || lowered == "false")
return false;
CHECK(0);
}
template<> int parseSingleItem<int>(const string &val) {
CHECK(val.size());
for(int i = 0; i < val.size(); i++)
CHECK(isdigit(val[i]));
return atoi(val.c_str());
}
template<> float parseSingleItem<float>(const string &val) {
CHECK(val.size());
bool pi_suffix = false;
if(val.size() >= 2 && val[val.size() - 2] == 'p' && val[val.size() - 1] == 'i')
pi_suffix = true;
bool foundperiod = false;
for(int i = 0; i < val.size() - pi_suffix * 2; i++) {
if(val[i] == '-' && i == 0) {
} else if(val[i] == '.') {
CHECK(!foundperiod);
foundperiod = true;
} else {
CHECK(isdigit(val[i]));
}
}
return atof(val.c_str()) * (pi_suffix ? PI : 1);
}
template<> Color parseSingleItem<Color>(const string &val) {
return colorFromString(val);
}
template<> Money parseSingleItem<Money>(const string &val) {
return moneyFromString(val);
}
template<typename T> T parseWithDefault_processing(const string &val, T def) {
CHECK(val.size());
if(tolower(val[val.size() - 1]) == 'x') {
CHECK(val.size() >= 2);
CHECK(tolower(val[val.size() - 2]) != 'x');
T mult = parseWithDefault_processing(string(val.begin(), val.end() - 1), T(1));
return def * mult;
}
return parseSingleItem<T>(val);
}
template<> string parseWithDefault_processing<string>(const string &val, string def) {
return val;
}
template<> Color parseWithDefault_processing<Color>(const string &val, Color def) {
return colorFromString(val);
}
template<> Money parseWithDefault_processing<Money>(const string &val, Money def) {
return moneyFromString(val);
}
template<typename T> T parseWithDefault(kvData *chunk, const string &label, T def) {
if(!chunk->kv.count(label))
return def;
return parseWithDefault_processing(chunk->consume(label), def);
}
string parseWithDefault(kvData *chunk, const string &label, const char *def) {
return parseWithDefault(chunk, label, string(def));
}
float parseWithDefault(kvData *chunk, const string &label, double def) {
return parseWithDefault(chunk, label, float(def));
}
void parseDamagecode(const string &str, float *arr) {
vector<string> toki = tokenize(str, "\n");
CHECK(toki.size() >= 1);
for(int i = 0; i < toki.size(); i++) {
vector<string> qoki = tokenize(toki[i], " ");
CHECK(qoki.size() == 2);
int bucket = -1;
if(qoki[1] == "kinetic")
bucket = IDBAdjustment::DAMAGE_KINETIC;
else if(qoki[1] == "energy")
bucket = IDBAdjustment::DAMAGE_ENERGY;
else if(qoki[1] == "explosive")
bucket = IDBAdjustment::DAMAGE_EXPLOSIVE;
else if(qoki[1] == "trap")
bucket = IDBAdjustment::DAMAGE_TRAP;
else if(qoki[1] == "exotic")
bucket = IDBAdjustment::DAMAGE_EXOTIC;
else
CHECK(0);
CHECK(arr[bucket] == 0);
arr[bucket] = parseSingleItem<float>(qoki[0]);
}
}
vector<pair<int, Color> > parseIonVisuals(const string &in) {
vector<pair<int, Color> > rv;
vector<string> vislist = tokenize(in, "\n");
for(int i = 0; i < vislist.size(); i++) {
boost::smatch mch = match(vislist[i], "([0-9]+) (.*)");
rv.push_back(make_pair(parseSingleItem<int>(mch[1]), parseSingleItem<Color>(mch[2])));
}
return rv;
}
template<typename T> void doStandardPrereq(T *titem, const string &name, map<string, T> *classes) {
titem->has_postreq = false;
{
string lastname = tokenize(name, " ").back();
CHECK(lastname.size()); // if this is wrong something horrible has occured
bool roman = true;
for(int i = 0; i < lastname.size(); i++)
if(lastname[i] != 'I' && lastname[i] != 'V' && lastname[i] != 'X') // I figure nobody will get past X without tripping the checks earlier
roman = false;
if(lastname.size() == 0)
roman = false;
if(!roman) {
titem->prereq = NULL;
} else {
int rv;
for(rv = 0; rv < roman_max(); rv++)
if(lastname == roman_number(rv))
break;
CHECK(rv < roman_max());
if(rv == 0) {
titem->prereq = NULL;
return;
}
string locnam = string(name.c_str(), (const char*)strrchr(name.c_str(), ' ')) + " " + roman_number(rv - 1);
CHECK(classes->count(locnam));
CHECK(!(*classes)[locnam].has_postreq);
titem->prereq = &(*classes)[locnam];
(*classes)[locnam].has_postreq = true;
}
}
}
bool isMountedNode(const string &in) {
vector<string> toks = tokenize(in, ".");
CHECK(toks.size());
if(toks[0] != "ROOT")
CHECK(toks.size() == 1);
return toks[0] == "ROOT";
}
HierarchyNode *findNamedNode(const string &in, int postcut) {
vector<string> toks = tokenize(in, ".");
CHECK(toks.size());
CHECK(toks.size() > postcut);
toks.erase(toks.end() - postcut, toks.end());
CHECK(toks[0] == "ROOT");
HierarchyNode *current = &root;
for(int i = 1; i < toks.size(); i++) {
int fc = 0;
int fi = -1;
for(int k = 0; k < current->branches.size(); k++) {
if(toks[i] == current->branches[k].name) {
fc++;
fi = k;
}
}
if(fc == 0) {
dprintf("Parent node %s not found for item hierarchy!\n", in.c_str());
}
CHECK(fc == 1);
CHECK(fi != -1);
current = ¤t->branches[fi];
}
return current;
}
void parseHierarchy(kvData *chunk, bool reload, ErrorAccumulator &accum) {
HierarchyNode *mountpoint = findNamedNode(chunk->kv["name"], 1);
HierarchyNode tnode;
tnode.name = tokenize(chunk->consume("name"), ".").back();
tnode.type = HierarchyNode::HNT_CATEGORY;
if(chunk->kv.count("pack")) {
tnode.displaymode = HierarchyNode::HNDM_PACK;
tnode.pack = atoi(chunk->consume("pack").c_str());
CHECK(mountpoint->pack == -1);
} else {
tnode.displaymode = HierarchyNode::HNDM_BLANK;
tnode.pack = mountpoint->pack;
}
if(chunk->kv.count("type")) {
if(chunk->kv["type"] == "weapon") {
tnode.cat_restrictiontype = HierarchyNode::HNT_WEAPON;
} else if(chunk->kv["type"] == "upgrade") {
tnode.cat_restrictiontype = HierarchyNode::HNT_UPGRADE;
} else if(chunk->kv["type"] == "glory") {
tnode.cat_restrictiontype = HierarchyNode::HNT_GLORY;
} else if(chunk->kv["type"] == "bombardment") {
tnode.cat_restrictiontype = HierarchyNode::HNT_BOMBARDMENT;
} else if(chunk->kv["type"] == "tank") {
tnode.cat_restrictiontype = HierarchyNode::HNT_TANK;
} else if(chunk->kv["type"] == "implant") {
tnode.cat_restrictiontype = HierarchyNode::HNT_IMPLANT_CAT;
} else {
dprintf("Unknown restriction type in hierarchy node: %s\n", chunk->kv["type"].c_str());
CHECK(0);
}
chunk->consume("type");
}
if(tnode.cat_restrictiontype == -1) {
tnode.cat_restrictiontype = mountpoint->cat_restrictiontype;
}
tnode.spawncash = parseWithDefault(chunk, "spawncash", Money(-1));
tnode.despawncash = parseWithDefault(chunk, "despawncash", Money(-1));
CHECK(tnode.spawncash >= Money(-1));
CHECK(tnode.despawncash >= Money(-1));
CHECK(tnode.despawncash >= tnode.spawncash || tnode.despawncash == Money(-1));
{
string val = parseWithDefault(chunk, "cashscale", "consistent");
if(val == "consistent") {
tnode.cashscale = HierarchyNode::HNCS_CONSISTENT;
} else if(val == "noconsistent") {
tnode.cashscale = HierarchyNode::HNCS_NOCONSISTENT;
} else if(val == "noshorten") {
tnode.cashscale = HierarchyNode::HNCS_NOSHORTEN;
} else {
CHECK(0);
}
}
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
mountpoint->branches.push_back(tnode);
}
void parseLauncher(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBLauncher *titem = prepareName(chunk, &launcherclasses, reload, "launcher");
titem->deploy = parseSubclass(chunk->consume("deploy"), deployclasses);
titem->text = parseOptionalSubclass(chunk, "text", text);
string demotype = parseWithDefault(chunk, "demo", "firingrange");
if(demotype == "firingrange") {
titem->demomode = WDM_FIRINGRANGE;
string distance = parseWithDefault(chunk, "firingrange_distance", "normal");
if(distance == "normal") {
titem->firingrange_distance = WFRD_NORMAL;
} else if(distance == "melee") {
titem->firingrange_distance = WFRD_MELEE;
} else {
CHECK(0);
}
} else if(demotype == "back") {
titem->demomode = WDM_BACKRANGE;
} else if(demotype == "mines") {
titem->demomode = WDM_MINES;
} else {
CHECK(0);
}
}
void parseEffects(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBEffects *titem = prepareName(chunk, &effectsclasses, reload, "effects");
string effecttype = chunk->consume("type");
if(effecttype == "particle") {
titem->type = IDBEffects::EFT_PARTICLE;
titem->particle_distribute = parseWithDefault(chunk, "distribute", false);
titem->particle_multiple_inertia = parseWithDefault(chunk, "multiple_inertia", 0.f);
titem->particle_multiple_reflect = parseWithDefault(chunk, "multiple_reflect", 0.f);
titem->particle_multiple_force = parseWithDefault(chunk, "multiple_force", 0.f);
titem->particle_spread = parseWithDefault(chunk, "spread", 0.f);
titem->particle_slowdown = parseWithDefault(chunk, "slowdown", 1.f);
titem->particle_lifetime = parseSingleItem<float>(chunk->consume("lifetime"));
titem->particle_radius = parseSingleItem<float>(chunk->consume("radius"));
titem->particle_color = parseSingleItem<Color>(chunk->consume("color"));
} else if(effecttype == "ionblast") {
titem->type = IDBEffects::EFT_IONBLAST;
titem->ionblast_radius = parseSingleItem<float>(chunk->consume("radius"));
titem->ionblast_duration = parseSingleItem<float>(chunk->consume("duration"));
titem->ionblast_visuals = parseIonVisuals(chunk->consume("visuals"));
} else {
CHECK(0);
}
titem->quantity = parseWithDefault(chunk, "quantity", 1);
}
void parseWeapon(kvData *chunk, bool reload, ErrorAccumulator &accum) {
string name;
IDBWeapon *titem = prepareName(chunk, &weaponclasses, reload, &name);
const string informal_name = tokenize(name, ".").back();
if(isMountedNode(name)) {
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = informal_name;
tnode.type = HierarchyNode::HNT_WEAPON;
tnode.displaymode = HierarchyNode::HNDM_COST;
tnode.buyable = true;
tnode.pack = mountpoint->pack;
tnode.cat_restrictiontype = HierarchyNode::HNT_WEAPON;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.weapon = titem;
tnode.spawncash = parseWithDefault(chunk, "spawncash", Money(0));
mountpoint->branches.push_back(tnode);
CHECK(mountpoint->pack >= 1);
titem->quantity = mountpoint->pack;
titem->base_cost = moneyFromString(chunk->consume("cost"));
CHECK(titem->base_cost > Money(0));
} else {
CHECK(!chunk->kv.count("cost"));
titem->quantity = 100; // why not?
titem->base_cost = Money(0);
}
titem->firerate = atof(chunk->consume("firerate").c_str());
titem->launcher = parseSubclass(chunk->consume("launcher"), launcherclasses);
titem->recommended = parseWithDefault(chunk, "recommended", -1);
titem->glory_resistance = parseWithDefault(chunk, "glory_resistance", false);
titem->nocache = parseWithDefault(chunk, "nocache", false);
}
void parseUpgrade(kvData *chunk, bool reload, ErrorAccumulator &accum) {
// This one turns out to be rather complicated.
string name;
string category;
IDBUpgrade *titem;
{
name = chunk->consume("name");
category = chunk->consume("category");
string locnam = category + "+" + name;
if(upgradeclasses.count(locnam)) {
if(!reload) {
dprintf("Multiple definition of %s\n", locnam.c_str());
CHECK(0);
} else {
upgradeclasses[locnam] = IDBUpgrade();
}
}
titem = &upgradeclasses[locnam];
}
titem->costmult = strtod(chunk->consume("costmult").c_str(), NULL);
titem->adjustment = parseSubclass(chunk->consume("adjustment"), adjustmentclasses);
titem->category = category;
titem->text = parseOptionalSubclass(chunk, "text", text);
doStandardPrereq(titem, category + "+" + name, &upgradeclasses);
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_UPGRADE;
tnode.displaymode = HierarchyNode::HNDM_COSTUNIQUE;
tnode.buyable = true;
tnode.pack = 1;
CHECK(mountpoint->pack == 1 || mountpoint->pack == -1);
tnode.cat_restrictiontype = HierarchyNode::HNT_UPGRADE;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.upgrade = titem;
mountpoint->branches.push_back(tnode);
}
}
void parseProjectile(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBProjectile *titem = prepareName(chunk, &projectileclasses, reload, "projectile");
titem->visual_thickness = parseWithDefault(chunk, "visual_thickness", 0.5);
set<string> allowed_shapes;
titem->proximity_visibility = -1;
titem->halflife = parseWithDefault(chunk, "halflife", -1.);
titem->halflife_base = parseWithDefault(chunk, "halflife_base", titem->halflife / 2);
titem->penetrating = parseWithDefault(chunk, "penetrating", false);
titem->freeze = parseWithDefault(chunk, "freeze", -1.);
string motion = parseWithDefault(chunk, "motion", "normal");
string defshape = "line";
if(motion == "normal") {
titem->motion = PM_NORMAL;
allowed_shapes.insert("line");
allowed_shapes.insert("drone");
allowed_shapes.insert("arrow");
allowed_shapes.insert("arcpiece");
} else if(motion == "missile") {
titem->motion = PM_MISSILE;
titem->missile_stabstart = parseSingleItem<float>(chunk->consume("missile_stabstart"));
titem->missile_stabilization = parseSingleItem<float>(chunk->consume("missile_stabilization"));
titem->missile_sidelaunch = parseSingleItem<float>(chunk->consume("missile_sidelaunch"));
titem->missile_backlaunch = parseSingleItem<float>(chunk->consume("missile_backlaunch"));
allowed_shapes.insert("line");
allowed_shapes.insert("drone");
allowed_shapes.insert("arrow");
} else if(motion == "airbrake") {
titem->motion = PM_AIRBRAKE;
titem->airbrake_life = parseSingleItem<float>(chunk->consume("airbrake_life"));
titem->airbrake_slowdown = parseSingleItem<float>(chunk->consume("airbrake_slowdown"));
defshape = "line_airbrake";
allowed_shapes.insert("line");
allowed_shapes.insert("line_airbrake");
allowed_shapes.insert("arrow");
} else if(motion == "boomerang") {
titem->motion = PM_BOOMERANG;
titem->boomerang_convergence = parseSingleItem<float>(chunk->consume("boomerang_convergence"));
titem->boomerang_intersection = parseSingleItem<float>(chunk->consume("boomerang_intersection"));
titem->boomerang_maxrotate = parseSingleItem<float>(chunk->consume("boomerang_maxrotate"));
allowed_shapes.insert("arrow");
} else if(motion == "mine") {
titem->motion = PM_MINE;
titem->proximity_visibility = parseWithDefault(chunk, "proximity_visibility", 30.f);
CHECK(titem->halflife != -1);
allowed_shapes.insert("star");
} else if(motion == "spidermine") {
titem->motion = PM_SPIDERMINE;
titem->proximity_visibility = parseWithDefault(chunk, "proximity_visibility", 30.f);
CHECK(titem->halflife != -1);
allowed_shapes.insert("star");
} else if(motion == "hunter") {
titem->motion = PM_HUNTER;
titem->hunter_rotation = parseSingleItem<float>(chunk->consume("hunter_rotation"));
titem->hunter_turnweight = parseSingleItem<float>(chunk->consume("hunter_turnweight"));
allowed_shapes.insert("drone");
} else if(motion == "homing") {
titem->motion = PM_HOMING;
titem->homing_turn = parseSingleItem<float>(chunk->consume("homing_turn"));
allowed_shapes.insert("line");
} else if(motion == "sine") {
titem->motion = PM_SINE;
titem->sine_width = parseSingleItem<float>(chunk->consume("sine_width"));
titem->sine_frequency = parseSingleItem<float>(chunk->consume("sine_frequency"));
titem->sine_frequency_stddev = parseWithDefault(chunk, "sine_frequency_stddev", 0.0);
allowed_shapes.insert("line");
} else if(motion == "dps") {
titem->motion = PM_DPS;
titem->dps_duration = parseSingleItem<float>(chunk->consume("duration"));
titem->dps_instant_warhead = parseSubclassSet(chunk, "dps_instant_warhead", warheadclasses);
if(chunk->kv.count("visuals"))
titem->dps_visuals = parseIonVisuals(chunk->consume("visuals"));
defshape = "invisible";
allowed_shapes.insert("invisible");
} else if(motion == "delay") {
titem->motion = PM_DELAY;
titem->delay_duration = parseSingleItem<float>(chunk->consume("duration"));
titem->delay_repeats = parseWithDefault(chunk, "repeats", 1);
defshape = "invisible";
allowed_shapes.insert("invisible");
} else if(motion == "generator") {
titem->motion = PM_GENERATOR;
titem->generator_duration = parseSingleItem<float>(chunk->consume("duration"));
titem->generator_falloff = parseSingleItem<float>(chunk->consume("falloff"));
titem->generator_per_second = parseSingleItem<float>(chunk->consume("per_second"));
CHECK(titem->generator_per_second <= FPS);
defshape = "invisible";
allowed_shapes.insert("invisible");
} else {
dprintf("Unknown projectile motion: %s\n", motion.c_str());
CHECK(0);
}
titem->velocity = 0;
if(titem->motion != PM_MINE && titem->motion != PM_DPS && titem->motion != PM_DELAY && titem->motion != PM_GENERATOR) {
titem->velocity = parseSingleItem<float>(chunk->consume("velocity"));
titem->velocity_stddev = parseWithDefault(chunk, "velocity_stddev", 0.0);
}
bool has_color = true;
string shape = parseWithDefault(chunk, "shape", defshape);
CHECK(allowed_shapes.count(shape));
if(shape == "line") {
titem->shape = PS_LINE;
titem->line_length = parseWithDefault(chunk, "line_length", titem->velocity / 60); // yes, this is 60, not FPS
} else if(shape == "line_airbrake") {
titem->shape = PS_LINE_AIRBRAKE;
titem->line_airbrake_lengthaddition = parseWithDefault(chunk, "line_airbrake_lengthaddition", 2.0);
} else if(shape == "arrow") {
titem->shape = PS_ARROW;
titem->arrow_height = parseSingleItem<float>(chunk->consume("arrow_height"));
titem->arrow_width = parseSingleItem<float>(chunk->consume("arrow_width"));
titem->arrow_rotate = parseWithDefault(chunk, "arrow_rotate", 0.0);
} else if(shape == "star") {
titem->shape = PS_STAR;
titem->star_radius = atof(chunk->consume("star_radius").c_str());
titem->star_spikes = parseSingleItem<int>(chunk->consume("star_spikes"));
} else if(shape == "drone") {
titem->shape = PS_DRONE;
titem->drone_radius = parseSingleItem<float>(chunk->consume("drone_radius"));
titem->drone_spike = parseSingleItem<float>(chunk->consume("drone_spike"));
} else if(shape == "arcpiece") {
titem->shape = PS_ARCPIECE;
titem->arc_width = parseSingleItem<float>(chunk->consume("arc_width"));
titem->arc_units = parseSingleItem<int>(chunk->consume("arc_units"));
CHECK(titem->arc_units >= 1);
} else if(shape == "invisible") {
titem->shape = PS_INVISIBLE;
has_color = false;
} else {
CHECK(0);
}
if(has_color)
titem->color = parseWithDefault(chunk, "color", C::gray(1.0));
titem->chain_warhead = parseSubclassSet(chunk, "warhead", warheadclasses);
titem->chain_deploy = parseSubclassSet(chunk, "deploy", deployclasses);
titem->chain_effects = parseSubclassSet(chunk, "effects", effectsclasses);
titem->poly_deploy = parseSubclassSet(chunk, "poly_deploy", deployclasses);
titem->burn_effects = parseSubclassSet(chunk, "burn_effects", effectsclasses);
{
string prox = parseWithDefault(chunk, "proximity", "off");
if(prox == "off") {
titem->proximity = -1;
} else if(prox == "auto") {
float rad = -1;
for(int i = 0; i < titem->chain_warhead.size(); i++)
rad = max(rad, titem->chain_warhead[i]->radiusfalloff);
CHECK(rad > 0);
titem->proximity = rad;
} else {
titem->proximity = parseSingleItem<float>(prox);
}
}
if(titem->motion != PM_MINE && titem->motion != PM_DPS && titem->motion != PM_SPIDERMINE && titem->motion != PM_DELAY && titem->motion != PM_GENERATOR) {
titem->no_intersection = parseWithDefault(chunk, "no_intersection", false);
if(!titem->no_intersection)
titem->durability = parseSingleItem<float>(chunk->consume("durability"));
else
titem->durability = -1;
} else {
titem->no_intersection = true;
titem->durability = -1;
}
if(titem->motion == PM_DPS) {
CHECK(titem->chain_warhead.size());
float rad = -1;
for(int i = 0; i < titem->chain_warhead.size(); i++)
rad = max(rad, titem->chain_warhead[i]->radiusfalloff);
CHECK(titem->chain_warhead[0]->radiusfalloff == rad);
}
CHECK(titem->chain_warhead.size() || titem->chain_deploy.size());
}
void parseDeploy(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBDeploy *titem = prepareName(chunk, &deployclasses, reload, "deploy");
string type = parseWithDefault(chunk, "type", "normal");
if(type == "normal") {
titem->type = DT_NORMAL;
} else if(type == "forward") {
titem->type = DT_FORWARD;
} else if(type == "rear") {
titem->type = DT_REAR;
} else if(type == "centroid") {
titem->type = DT_CENTROID;
} else if(type == "minepath") {
titem->type = DT_MINEPATH;
} else if(type == "directed") {
titem->type = DT_DIRECTED;
titem->directed_range = parseSingleItem<float>(chunk->consume("directed_range"));
titem->directed_approach = parseWithDefault(chunk, "directed_approach", 0.);
} else if(type == "reflected") {
titem->type = DT_REFLECTED;
} else if(type == "arc") {
titem->type = DT_ARC;
titem->arc_width = parseSingleItem<float>(chunk->consume("width"));
titem->arc_units = parseSingleItem<int>(chunk->consume("units"));
} else if(type == "vengeance") {
titem->type = DT_VENGEANCE;
} else if(type == "explode") {
titem->type = DT_EXPLODE;
titem->exp_minsplits = parseSingleItem<int>(chunk->consume("exp_minsplits"));
titem->exp_maxsplits = parseSingleItem<int>(chunk->consume("exp_maxsplits"));
titem->exp_minsplitsize = parseSingleItem<int>(chunk->consume("exp_minsplitsize"));
titem->exp_maxsplitsize = parseSingleItem<int>(chunk->consume("exp_maxsplitsize"));
titem->exp_shotspersplit = parseSingleItem<int>(chunk->consume("exp_shotspersplit"));
} else if(type == "chaos") {
titem->type = DT_CHAOS;
titem->chaos_radius = parseSingleItem<float>(chunk->consume("chaos_radius"));
titem->chaos_radiusexplosive = parseWithDefault(chunk, "radiusexplosive", 0.);
} else {
CHECK(0);
}
titem->anglestddev = parseWithDefault(chunk, "anglestddev", 0.0);
titem->anglemodifier = parseWithDefault(chunk, "anglemodifier", 0.0);
titem->multiple = parseWithDefault(chunk, "multiple", 1);
titem->chain_deploy = parseSubclassSet(chunk, "deploy", deployclasses);
titem->chain_projectile = parseSubclassSet(chunk, "projectile", projectileclasses);
titem->chain_warhead = parseSubclassSet(chunk, "warhead", warheadclasses);
titem->chain_effects = parseSubclassSet(chunk, "effects", effectsclasses);
titem->chain_instant = parseSubclassSet(chunk, "instant", instantclasses);
for(int i = 0; i < titem->chain_deploy.size(); i++)
CHECK(titem->chain_deploy[i] != titem);
CHECK(titem->chain_deploy.size() || titem->chain_projectile.size() || titem->chain_warhead.size() || titem->chain_instant.size() || titem->chain_effects.size());
}
void parseWarhead(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBWarhead *titem = prepareName(chunk, &warheadclasses, reload, "warhead");
memset(titem->impactdamage, 0, sizeof(titem->impactdamage));
memset(titem->radiusdamage, 0, sizeof(titem->radiusdamage));
// these must either neither exist, or both exist
CHECK(chunk->kv.count("radiusfalloff") == chunk->kv.count("radiusdamage"));
CHECK(chunk->kv.count("radiusfalloff") == chunk->kv.count("radiusexplosive"));
CHECK(chunk->kv.count("radiuscolor_bright") == chunk->kv.count("radiuscolor_dim"));
// if wallremovalchance exists, wallremovalradius must too
CHECK(chunk->kv.count("wallremovalchance") <= chunk->kv.count("wallremovalradius"));
// if radiuscolor_bright exists, radiusfalloff must too
CHECK(chunk->kv.count("radiuscolor_bright") <= chunk->kv.count("radiusfalloff"));
titem->radiuscolor_bright = parseWithDefault(chunk, "radiuscolor_bright", Color(1.0, 0.8, 0.2));
titem->radiuscolor_dim = parseWithDefault(chunk, "radiuscolor_dim", Color(1.0, 0.2, 0.0));
if(chunk->kv.count("impactdamage"))
parseDamagecode(chunk->consume("impactdamage"), titem->impactdamage);
if(chunk->kv.count("radiusdamage"))
parseDamagecode(chunk->consume("radiusdamage"), titem->radiusdamage);
titem->radiusfalloff = parseWithDefault(chunk, "radiusfalloff", -1.0);
titem->radiusexplosive = parseWithDefault(chunk, "radiusexplosive", -1.0);
if(titem->radiusfalloff != -1)
CHECK(titem->radiusexplosive >= 0 && titem->radiusexplosive <= 1);
titem->wallremovalradius = parseWithDefault(chunk, "wallremovalradius", 0.0);
titem->wallremovalchance = parseWithDefault(chunk, "wallremovalchance", 1.0);
titem->deploy = parseSubclassSet(chunk, "deploy", deployclasses);
titem->effects_impact = parseSubclassSet(chunk, "effects_impact", effectsclasses);
}
void parseGlory(kvData *chunk, bool reload, ErrorAccumulator &accum) {
string name;
IDBGlory *titem = prepareName(chunk, &gloryclasses, reload, &name);
titem->base_cost = moneyFromString(chunk->consume("cost"));
titem->blast = parseSubclassSet(chunk, "blast", deployclasses);
titem->core = parseSubclass(chunk->consume("core"), deployclasses);
if(chunk->kv.count("default") && atoi(chunk->consume("default").c_str())) {
CHECK(!defglory);
defglory = titem;
}
titem->demo_range = parseWithDefault(chunk, "demo_range", 100);
titem->text = parseOptionalSubclass(chunk, "text", text);
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_GLORY;
tnode.displaymode = HierarchyNode::HNDM_COSTUNIQUE;
tnode.buyable = true;
tnode.pack = 1;
tnode.cat_restrictiontype = HierarchyNode::HNT_GLORY;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.glory = titem;
tnode.spawncash = titem->base_cost / 2;
mountpoint->branches.push_back(tnode);
}
}
void parseBombardment(kvData *chunk, bool reload, ErrorAccumulator &accum) {
string name;
IDBBombardment *titem = prepareName(chunk, &bombardmentclasses, reload, &name);
titem->warheads = parseSubclassSet(chunk, "warhead", warheadclasses);
titem->projectiles = parseSubclassSet(chunk, "projectile", projectileclasses);
titem->effects = parseSubclassSet(chunk, "effects", effectsclasses);
titem->showdirection = parseWithDefault(chunk, "showdirection", false);
titem->cost = moneyFromString(chunk->consume("cost"));
titem->lockdelay = atof(chunk->consume("lockdelay").c_str());
titem->unlockdelay = atof(chunk->consume("unlockdelay").c_str());
if(chunk->kv.count("default") && atoi(chunk->consume("default").c_str())) {
CHECK(!defbombardment);
defbombardment = titem;
}
titem->text = parseOptionalSubclass(chunk, "text", text);
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_BOMBARDMENT;
tnode.displaymode = HierarchyNode::HNDM_COSTUNIQUE;
tnode.buyable = true;
tnode.pack = 1;
tnode.cat_restrictiontype = HierarchyNode::HNT_BOMBARDMENT;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.spawncash = titem->cost / 2;
tnode.bombardment = titem;
mountpoint->branches.push_back(tnode);
}
}
void parseTank(kvData *chunk, bool reload, ErrorAccumulator &accum) {
string name;
IDBTank *titem = prepareName(chunk, &tankclasses, reload, &name);
string weapon = chunk->consume("weapon");
if(!weaponclasses.count(weapon))
dprintf("Can't find weapon %s", weapon.c_str());
CHECK(weaponclasses.count(weapon));
titem->weapon = &weaponclasses[weapon];
titem->health = atof(chunk->consume("health").c_str());
titem->handling = atof(chunk->consume("handling").c_str());
titem->engine = atof(chunk->consume("engine").c_str());
titem->mass = atof(chunk->consume("mass").c_str());
titem->adjustment = parseOptionalSubclass(chunk, "adjustment", adjustmentclasses);
titem->upgrades = tokenize(chunk->consume("upgrades"), "\n");
{
vector<string> vtx = tokenize(chunk->consume("vertices"), "\n");
CHECK(vtx.size() >= 3); // triangle is the minimum, no linetanks please
bool got_firepoint = false;
bool got_rearfirepoint = false;
bool in_mine_path = false;
for(int i = 0; i < vtx.size(); i++) {
vector<string> vti = tokenize(vtx[i], " ");
CHECK(vti.size() == 2 || vti.size() == 3);
Coord2 this_vertex = Coord2(atof(vti[0].c_str()), atof(vti[1].c_str()));
titem->vertices.push_back(Coord2(this_vertex));
if(in_mine_path)
titem->minepath.push_back(this_vertex);
if(vti.size() == 3) {
if(vti[2] == "firepoint") {
CHECK(!got_firepoint);
titem->firepoint = this_vertex;
got_firepoint = true;
} else if(vti[2] == "rear_firepoint") {
CHECK(!got_rearfirepoint);
CHECK(in_mine_path);
titem->rearfirepoint = this_vertex;
got_rearfirepoint = true;
} else if(vti[2] == "rear_begin") {
CHECK(!in_mine_path);
CHECK(!titem->minepath.size());
in_mine_path = true;
titem->minepath.push_back(this_vertex);
} else if(vti[2] == "rear_end") {
CHECK(in_mine_path);
CHECK(titem->minepath.size());
in_mine_path = false;
} else {
CHECK(0);
}
}
}
CHECK(titem->minepath.size() >= 2);
CHECK(got_firepoint);
CHECK(got_rearfirepoint);
titem->centering_adjustment = getCentroid(titem->vertices);
for(int i = 0; i < titem->vertices.size(); i++)
titem->vertices[i] -= titem->centering_adjustment;
titem->firepoint -= titem->centering_adjustment;
titem->rearfirepoint -= titem->centering_adjustment;
for(int i = 0; i < titem->minepath.size(); i++)
titem->minepath[i] -= titem->centering_adjustment;
}
titem->base_cost = moneyFromString(chunk->consume("cost"));
titem->upgrade_base = parseWithDefault(chunk, "upgrade_base", titem->base_cost);
if(chunk->kv.count("default") && atoi(chunk->consume("default").c_str())) {
CHECK(!deftank);
deftank = titem;
}
titem->text = parseOptionalSubclass(chunk, "text", text);
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_TANK;
tnode.displaymode = HierarchyNode::HNDM_COSTUNIQUE;
tnode.buyable = true;
tnode.pack = 1;
tnode.cat_restrictiontype = HierarchyNode::HNT_TANK;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.spawncash = titem->base_cost / 2;
tnode.tank = titem;
mountpoint->branches.push_back(tnode);
}
}
void parseAdjustment(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBAdjustment *titem = prepareName(chunk, &adjustmentclasses, reload, "adjustment");
CHECK(ARRAY_SIZE(adjust_text) == IDBAdjustment::COMBO_LAST);
CHECK(ARRAY_SIZE(adjust_human) == IDBAdjustment::COMBO_LAST);
CHECK(ARRAY_SIZE(adjust_unit) == IDBAdjustment::LAST);
int cps = 0;
for(int i = 0; i < IDBAdjustment::LAST; i++) {
if(chunk->kv.count(adjust_text[i])) {
CHECK(cps < ARRAY_SIZE(titem->adjustlist));
int value = atoi(chunk->consume(adjust_text[i]).c_str());
titem->adjusts[i] = value;
titem->adjustlist[cps++] = make_pair(i, value);
}
}
for(int i = IDBAdjustment::LAST; i < IDBAdjustment::COMBO_LAST; i++) {
if(chunk->kv.count(adjust_text[i])) {
CHECK(cps < ARRAY_SIZE(titem->adjustlist));
int value = atoi(chunk->consume(adjust_text[i]).c_str());
titem->adjustlist[cps++] = make_pair(i, value);
if(i == IDBAdjustment::DAMAGE_ALL) {
for(int j = 0; j < IDBAdjustment::DAMAGE_LAST; j++) {
CHECK(titem->adjusts[j] == 0);
titem->adjusts[j] = value;
}
} else if(i == IDBAdjustment::ALL) {
for(int j = 0; j < IDBAdjustment::LAST; j++) {
CHECK(titem->adjusts[j] == 0);
titem->adjusts[j] = value;
}
} else {
CHECK(0);
}
}
}
}
void parseFaction(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBFaction fact;
fact.icon = loadDvec2(FLAGS_fileroot + "base/faction_icons/" + chunk->consume("file"));
fact.color = colorFromString(chunk->consume("color"));
fact.name = chunk->consume("name");
{
vector<int> lines = sti(tokenize(chunk->consume("lines"), " "));
vector<string> words = tokenize(fact.name, " ");
CHECK(words.size() == accumulate(lines.begin(), lines.end(), 0));
int cword = 0;
for(int i = 0; i < lines.size(); i++) {
string acu;
for(int j = 0; j < lines[i]; j++) {
if(j)
acu += " ";
acu += words[cword++];
}
fact.name_lines.push_back(acu);
}
}
adjustmentclasses["null"]; // this is a hideous hack just FYI
for(int i = 0; i < 3; i++)
fact.adjustment[i] = parseSubclass("null", adjustmentclasses); // wheeeeeeeee
fact.adjustment[3] = parseSubclass(chunk->consume("adjustment"), adjustmentclasses);
fact.text = parseOptionalSubclass(chunk, "text", text);
factions.push_back(fact);
}
void parseText(kvData *chunk, bool reload, ErrorAccumulator &accum) {
string *titem = prepareName(chunk, &text, reload, "text");
*titem = chunk->consume("data");
// yay
}
void parseShopcacheFile(const string &fname, vector<string> *errors) {
IStreamGz shopcache(fname);
if(shopcache) {
dprintf("Loading shop cache");
vector<pair<string, FileShopcache> > dat;
shopcache.read(&dat);
for(int i = 0; i < dat.size(); i++) {
const FileShopcache &tdat = dat[i].second;
IDBShopcache *titem = prepareName(dat[i].first, &shopcaches, false);
// easy stuff first
titem->cycles = tdat.cycles;
titem->damageframes = tdat.damageframes;
for(int j = 0; j < tdat.entries.size(); j++) {
IDBShopcache::Entry entry;
entry.warhead = parseSubclass(tdat.entries[j].warhead, warheadclasses);
entry.count = tdat.entries[j].count;
entry.mult = tdat.entries[j].mult;
entry.impact = tdat.entries[j].impact;
entry.adjacencies = tdat.entries[j].adjacencies;
titem->entries.push_back(entry);
}
}
} else {
dprintf("No shop cache available, skipping");
}
}
void parseImplantSlot(kvData *chunk, bool reload, ErrorAccumulator &accum) {
string name;
IDBImplantSlot *titem = prepareName(chunk, &implantslotclasses, reload, &name);
titem->cost = moneyFromString(chunk->consume("cost"));
titem->text = parseOptionalSubclass(chunk, "text", text);
doStandardPrereq(titem, name, &implantslotclasses);
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_IMPLANTSLOT;
tnode.displaymode = HierarchyNode::HNDM_COSTUNIQUE;
tnode.buyable = true;
tnode.pack = 1;
tnode.cat_restrictiontype = HierarchyNode::HNT_IMPLANT_CAT;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.implantslot = titem;
mountpoint->branches.push_back(tnode);
}
}
void parseImplant(kvData *chunk, bool reload, ErrorAccumulator &accum) {
string name;
IDBImplant *titem = prepareName(chunk, &implantclasses, reload, &name);
titem->adjustment = parseSubclass(chunk->consume("adjustment"), adjustmentclasses);
titem->text = parseOptionalSubclass(chunk, "text", text);
// this is kind of grim - we push three nodes in. This could happen at shop manipulation time also, I suppose.
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_IMPLANTITEM;
tnode.displaymode = HierarchyNode::HNDM_BLANK;
tnode.buyable = false;
tnode.selectable = false;
tnode.cat_restrictiontype = HierarchyNode::HNT_IMPLANT_CAT;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.implantitem = titem;
mountpoint->branches.push_back(tnode);
}
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_IMPLANTITEM_EQUIP;
tnode.displaymode = HierarchyNode::HNDM_IMPLANT_EQUIP;
tnode.buyable = true;
tnode.pack = 1;
tnode.cat_restrictiontype = HierarchyNode::HNT_IMPLANT_CAT;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.implantitem = titem;
mountpoint->branches.push_back(tnode);
}
{
HierarchyNode *mountpoint = findNamedNode(name, 1);
HierarchyNode tnode;
tnode.name = tokenize(name, ".").back();
tnode.type = HierarchyNode::HNT_IMPLANTITEM_UPG;
tnode.displaymode = HierarchyNode::HNDM_IMPLANT_UPGRADE;
tnode.buyable = true;
tnode.pack = 1;
tnode.cat_restrictiontype = HierarchyNode::HNT_IMPLANT_CAT;
CHECK(mountpoint->cat_restrictiontype == -1 || tnode.cat_restrictiontype == mountpoint->cat_restrictiontype);
tnode.spawncash = Money(75000);
tnode.implantitem = titem;
mountpoint->branches.push_back(tnode);
}
}
void parseInstant(kvData *chunk, bool reload, ErrorAccumulator &accum) {
IDBInstant *titem = prepareName(chunk, &instantclasses, reload, "instant");
string type = chunk->consume("type");
if(type == "tesla") {
titem->type = IT_TESLA;
titem->tesla_radius = parseSingleItem<float>(chunk->consume("radius"));
titem->tesla_unlockshares = parseWithDefault(chunk, "unlockshares", 0.);
titem->tesla_warhead = parseSubclassSet(chunk, "warhead", warheadclasses);
} else {
CHECK(0);
}
}
kvData currentlyreading;
void printCurread() {
dprintf("%s\n", stringFromKvData(currentlyreading).c_str());
}
void parseItemFile(const string &fname, bool reload, vector<string> *errors) {
dprintf("Trying to open %s\n", fname.c_str());
ifstream tfil(fname.c_str());
CHECK(tfil);
int line = 0;
int nextline = 0;
kvData chunk;
while(getkvData(tfil, &chunk, &line, &nextline)) {
//dprintf("%s\n", chunk.debugOutput().c_str());
if(parseWithDefault(&chunk, "debug", false) && !FLAGS_debugitems) {
continue;
}
currentlyreading = chunk;
registerCrashFunction(printCurread);
ErrorAccumulator erac(errors, fname, line);
if(chunk.category == "hierarchy") {
parseHierarchy(&chunk, reload, erac);
} else if(chunk.category == "weapon") {
parseWeapon(&chunk, reload, erac);
} else if(chunk.category == "upgrade") {
parseUpgrade(&chunk, reload, erac);
} else if(chunk.category == "projectile") {
parseProjectile(&chunk, reload, erac);
} else if(chunk.category == "deploy") {
parseDeploy(&chunk, reload, erac);
} else if(chunk.category == "warhead") {
parseWarhead(&chunk, reload, erac);
} else if(chunk.category == "glory") {
parseGlory(&chunk, reload, erac);
} else if(chunk.category == "bombardment") {
parseBombardment(&chunk, reload, erac);
} else if(chunk.category == "tank") {
parseTank(&chunk, reload, erac);
} else if(chunk.category == "adjustment") {
parseAdjustment(&chunk, reload, erac);
} else if(chunk.category == "faction") {
parseFaction(&chunk, reload, erac);
} else if(chunk.category == "text") {
parseText(&chunk, reload, erac);
} else if(chunk.category == "launcher") {
parseLauncher(&chunk, reload, erac);
} else if(chunk.category == "effects") {
parseEffects(&chunk, reload, erac);
} else if(chunk.category == "implantslot") {
parseImplantSlot(&chunk, reload, erac);
} else if(chunk.category == "implant") {
parseImplant(&chunk, reload, erac);
} else if(chunk.category == "instant") {
parseInstant(&chunk, reload, erac);
} else {
dprintf("Confusing category. Are you insane?\n");
dprintf("%s\n", stringFromKvData(chunk).c_str());
CHECK(0);
}
unregisterCrashFunction(printCurread);
if(!chunk.isDone())
erac.addError(StringPrintf("Chunk still has unparsed data! %s", chunk.debugOutput().c_str()));
}
}
| 36.653377 | 163 | 0.663418 | [
"object",
"shape",
"vector"
] |
a8d4e47a63045a460308a210d1858505a4846973 | 18,791 | cpp | C++ | Cpp/SDK/ServerListItem_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 1 | 2020-08-15T08:31:55.000Z | 2020-08-15T08:31:55.000Z | Cpp/SDK/ServerListItem_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 2 | 2020-08-15T08:43:56.000Z | 2021-01-15T05:04:48.000Z | Cpp/SDK/ServerListItem_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 2 | 2020-08-10T12:05:42.000Z | 2021-02-12T19:56:10.000Z | // Name: S, Version: b
#include "../SDK.h"
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function ServerListItem.ServerListItem_C.Toggle Favourite
// (Public, BlueprintCallable, BlueprintEvent)
void UServerListItem_C::Toggle_Favourite()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Toggle Favourite");
UServerListItem_C_Toggle_Favourite_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.GetFavouriteColor
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FLinearColor UServerListItem_C::GetFavouriteColor()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.GetFavouriteColor");
UServerListItem_C_GetFavouriteColor_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.TooltipFavourite
// (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UWidget* UServerListItem_C::TooltipFavourite()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.TooltipFavourite");
UServerListItem_C_TooltipFavourite_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.TooltipVAC
// (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UWidget* UServerListItem_C::TooltipVAC()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.TooltipVAC");
UServerListItem_C_TooltipVAC_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.TooltipLocked
// (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UWidget* UServerListItem_C::TooltipLocked()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.TooltipLocked");
UServerListItem_C_TooltipLocked_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.TooltipModIcon
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UWidget* UServerListItem_C::TooltipModIcon()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.TooltipModIcon");
UServerListItem_C_TooltipModIcon_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.OnMouseButtonDown
// (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// struct FPointerEvent MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
// struct FEventReply ReturnValue (Parm, OutParm, ReturnParm)
struct FEventReply UServerListItem_C::OnMouseButtonDown(const struct FGeometry& MyGeometry, const struct FPointerEvent& MouseEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.OnMouseButtonDown");
UServerListItem_C_OnMouseButtonDown_Params params;
params.MyGeometry = MyGeometry;
params.MouseEvent = MouseEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.OnMouseButtonDoubleClick
// (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry InMyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// struct FPointerEvent InMouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
// struct FEventReply ReturnValue (Parm, OutParm, ReturnParm)
struct FEventReply UServerListItem_C::OnMouseButtonDoubleClick(const struct FGeometry& InMyGeometry, const struct FPointerEvent& InMouseEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.OnMouseButtonDoubleClick");
UServerListItem_C_OnMouseButtonDoubleClick_Params params;
params.InMyGeometry = InMyGeometry;
params.InMouseEvent = InMouseEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.Get_Modded_Icon_Color
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FLinearColor UServerListItem_C::Get_Modded_Icon_Color()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Get_Modded_Icon_Color");
UServerListItem_C_Get_Modded_Icon_Color_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.Is Modded
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
bool UServerListItem_C::Is_Modded()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Is Modded");
UServerListItem_C_Is_Modded_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.Is Whitelisted
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// bool Is_Whitelisted (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UServerListItem_C::Is_Whitelisted(bool* Is_Whitelisted)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Is Whitelisted");
UServerListItem_C_Is_Whitelisted_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Is_Whitelisted != nullptr)
*Is_Whitelisted = params.Is_Whitelisted;
}
// Function ServerListItem.ServerListItem_C.Set Friend Count
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void UServerListItem_C::Set_Friend_Count()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Set Friend Count");
UServerListItem_C_Set_Friend_Count_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.Get_ImageHealth_ToolTipWidget_1
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UWidget* UServerListItem_C::Get_ImageHealth_ToolTipWidget_1()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Get_ImageHealth_ToolTipWidget_1");
UServerListItem_C_Get_ImageHealth_ToolTipWidget_1_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.IsJoinServer
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// bool selected (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UServerListItem_C::IsJoinServer(bool* selected)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.IsJoinServer");
UServerListItem_C_IsJoinServer_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (selected != nullptr)
*selected = params.selected;
}
// Function ServerListItem.ServerListItem_C.Get Queue Object
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// bool In_Queue (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UServerListItem_C::Get_Queue_Object(bool* In_Queue)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Get Queue Object");
UServerListItem_C_Get_Queue_Object_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (In_Queue != nullptr)
*In_Queue = params.In_Queue;
}
// Function ServerListItem.ServerListItem_C.UpdatePlayerCounts
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void UServerListItem_C::UpdatePlayerCounts()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.UpdatePlayerCounts");
UServerListItem_C_UpdatePlayerCounts_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.IsSelected
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// bool selected (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UServerListItem_C::IsSelected(bool* selected)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.IsSelected");
UServerListItem_C_IsSelected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (selected != nullptr)
*selected = params.selected;
}
// Function ServerListItem.ServerListItem_C.Get Main Color
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// struct FLinearColor ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FLinearColor UServerListItem_C::Get_Main_Color()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Get Main Color");
UServerListItem_C_Get_Main_Color_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ServerListItem.ServerListItem_C.Init
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void UServerListItem_C::Init()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Init");
UServerListItem_C_Init_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.ClientJoinAccepted
// (Event, Public, BlueprintEvent)
void UServerListItem_C::ClientJoinAccepted()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.ClientJoinAccepted");
UServerListItem_C_ClientJoinAccepted_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UServerListItem_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Construct");
UServerListItem_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.Marquee
// (BlueprintCallable, BlueprintEvent)
void UServerListItem_C::Marquee()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Marquee");
UServerListItem_C_Marquee_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.Finished Refresh_Event_1
// (BlueprintCallable, BlueprintEvent)
void UServerListItem_C::Finished_Refresh_Event_1()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Finished Refresh_Event_1");
UServerListItem_C_Finished_Refresh_Event_1_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.OnMouseEnter
// (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// struct FPointerEvent MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
void UServerListItem_C::OnMouseEnter(const struct FGeometry& MyGeometry, const struct FPointerEvent& MouseEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.OnMouseEnter");
UServerListItem_C_OnMouseEnter_Params params;
params.MyGeometry = MyGeometry;
params.MouseEvent = MouseEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.Start Marquee
// (BlueprintCallable, BlueprintEvent)
void UServerListItem_C::Start_Marquee()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Start Marquee");
UServerListItem_C_Start_Marquee_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// float InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UServerListItem_C::Tick(const struct FGeometry& MyGeometry, float InDeltaTime)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.Tick");
UServerListItem_C_Tick_Params params;
params.MyGeometry = MyGeometry;
params.InDeltaTime = InDeltaTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.BndEvt__Button_Fave_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature
// (BlueprintEvent)
void UServerListItem_C::BndEvt__Button_Fave_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature()
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.BndEvt__Button_Fave_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature");
UServerListItem_C_BndEvt__Button_Fave_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.ExecuteUbergraph_ServerListItem
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UServerListItem_C::ExecuteUbergraph_ServerListItem(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.ExecuteUbergraph_ServerListItem");
UServerListItem_C_ExecuteUbergraph_ServerListItem_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ServerListItem.ServerListItem_C.RequestJoin__DelegateSignature
// (Public, Delegate, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UServerListItem_C* Button (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UServerListItem_C::RequestJoin__DelegateSignature(class UServerListItem_C* Button)
{
static auto fn = UObject::FindObject<UFunction>("Function ServerListItem.ServerListItem_C.RequestJoin__DelegateSignature");
UServerListItem_C_RequestJoin__DelegateSignature_Params params;
params.Button = Button;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 32.623264 | 196 | 0.760896 | [
"object"
] |
a8d7c89bc43df2e4c297318c27c740e655defe01 | 3,480 | cpp | C++ | Extern/mssdk_dx7/samples/Multimedia/D3DRM/src/XofLoad/xofload.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 1,040 | 2021-07-27T12:12:06.000Z | 2021-08-02T14:24:49.000Z | Extern/mssdk_dx7/samples/Multimedia/D3DRM/src/XofLoad/xofload.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 20 | 2021-07-27T12:25:22.000Z | 2021-08-02T12:22:19.000Z | Extern/mssdk_dx7/samples/Multimedia/D3DRM/src/XofLoad/xofload.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 71 | 2021-07-27T14:19:49.000Z | 2021-08-02T05:51:52.000Z | //-----------------------------------------------------------------------------
// File: xofload.cpp
//
// Desc: Load a .X File using the DirectXFile API
//
// Copyright (C) 1998-1999 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#define INITGUID
#include <windows.h>
#include <iostream.h>
#include <objbase.h>
#include "dxfile.h"
#include "rmxfguid.h"
#include "rmxftmpl.h"
int main(int argc, char *argv[])
{
LPCSTR szFilename;
LPDIRECTXFILE pxofapi = NULL;
LPDIRECTXFILEENUMOBJECT pxofenum = NULL;
HRESULT hr;
// Get filename from command line argument.
if (argc <2 || argc > 2) {
cout << "XofLoad - Sample program to load a .X File\n";
cout << "Usage : xofload <filename>\n";
return (0);
}
szFilename = argv[1];
// Using a do/while(FALSE) loop instead of goto for errors...
do {
// Create xofapi object.
hr = DirectXFileCreate(&pxofapi);
if (FAILED(hr))
break;
// Registe templates for d3drm.
hr = pxofapi->RegisterTemplates((LPVOID)D3DRM_XTEMPLATES,
D3DRM_XTEMPLATE_BYTES);
if (FAILED(hr))
break;
// Create enum object.
hr = pxofapi->CreateEnumObject((LPVOID)szFilename,
DXFILELOAD_FROMFILE,
&pxofenum);
if (FAILED(hr))
break;
// Enumerate top level objects.
// Top level objects are always data object.
LPDIRECTXFILEDATA pxofobj;
while (SUCCEEDED(pxofenum->GetNextDataObject(&pxofobj))) {
const GUID *type;
// Get the type of the object
hr = pxofobj->GetType(&type);
if (FAILED(hr))
break;
// Display the type
if (*type == TID_DXFILEHeader)
cout << "Header\n";
else if (*type == TID_D3DRMMesh)
cout << "Mesh\n";
// Enumerate child objects.
// Child object can be data, data reference or binary.
// Use QueryInterface() to find what type of object a child is.
LPDIRECTXFILEOBJECT pxofChild;
while (SUCCEEDED(pxofobj->GetNextObject(&pxofChild))) {
cout << " Child\n";
// Query the child for it's FileDtaaReference
LPDIRECTXFILEDATAREFERENCE pxofdr;
hr = pxofChild->QueryInterface(IID_IDirectXFileDataReference,
(LPVOID *)&pxofdr);
if (SUCCEEDED(hr)) {
cout << "Data reference.\n";
// Resolve data reference.
// It's always resolved to a data object.
LPDIRECTXFILEDATA pxofdata;
hr = pxofdr->Resolve(&pxofdata);
if (SUCCEEDED(hr)) {
// Do whatever you want with that data object.
pxofdata->Release();
}
pxofdr->Release();
}
pxofChild->Release();
}
pxofobj->Release();
}
} while (FALSE);
// Clean up any interfaces we still have
if (pxofenum)
pxofenum->Release();
if (pxofapi)
pxofapi->Release();
cout << "Done.\n";
return 0;
}
| 29.243697 | 79 | 0.488218 | [
"mesh",
"object"
] |
a8da1bd4d02d6fbe3af212cdd7b96f40e147a6b2 | 2,403 | cxx | C++ | src/python/lib/graph/rag/get_lifted_edges_from_rag_and_offsets.cxx | abailoni/nifty | 7cc5ef9ee5c46a44d7c248192d9b4812bc685099 | [
"MIT"
] | 1 | 2020-10-28T13:53:08.000Z | 2020-10-28T13:53:08.000Z | src/python/lib/graph/rag/get_lifted_edges_from_rag_and_offsets.cxx | abailoni/nifty | 7cc5ef9ee5c46a44d7c248192d9b4812bc685099 | [
"MIT"
] | null | null | null | src/python/lib/graph/rag/get_lifted_edges_from_rag_and_offsets.cxx | abailoni/nifty | 7cc5ef9ee5c46a44d7c248192d9b4812bc685099 | [
"MIT"
] | 2 | 2020-04-02T01:16:55.000Z | 2020-10-28T13:53:09.000Z | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "xtensor-python/pytensor.hpp"
#include <cstddef>
#include "nifty/graph/rag/grid_rag.hxx"
#include "nifty/graph/rag/get_lifted_edges_from_rag_and_offsets.hxx"
namespace py = pybind11;
namespace nifty {
namespace graph {
using namespace py;
template<std::size_t DIM, class RAG>
void exportComputeLiftedEdgesFromRagAndOffsets(
py::module & ragModule
){
ragModule.def("computeLiftedEdgesFromRagAndOffsets_impl",
[](
const RAG & rag,
const std::vector<std::vector<int>> & offsets,
// xt::pytensor<int64_t, 2> offsets,
const int numberOfThreads
){
typedef typename std::vector<array::StaticArray<int64_t, DIM>> OffsetVectorType;
// OffsetVectorType offsetVector(offsets.shape()[0]);
OffsetVectorType offsetVector(offsets.size());
for(auto i=0; i<offsetVector.size(); ++i){
for(auto d=0; d<DIM; ++d){
offsetVector[i][d] = offsets[i][d];
// offsetVector[i][d] = offsets(i,d);
}
}
return computeLiftedEdgesFromRagAndOffsets(rag, offsetVector, numberOfThreads);
},
py::arg("rag"),
py::arg("offsets"),
py::arg("numberOfThreads") = -1
);
};
void exportComputeLiftedEdges(py::module & ragModule) {
//explicit
{
typedef xt::pytensor<uint32_t, 2> ExplicitLabels2D;
typedef GridRag<2, ExplicitLabels2D> Rag2d;
typedef xt::pytensor<uint32_t, 3> ExplicitLabels3D;
typedef GridRag<3, ExplicitLabels3D> Rag3d;
exportComputeLiftedEdgesFromRagAndOffsets<2, Rag2d>(ragModule);
exportComputeLiftedEdgesFromRagAndOffsets<3, Rag3d>(ragModule);
}
}
}
}
| 34.328571 | 112 | 0.475239 | [
"shape",
"vector"
] |
a8e253542852337f99839ae7b202a27bd5a384d0 | 20,345 | cpp | C++ | vbox/src/VBox/Runtime/common/misc/getoptargv.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/Runtime/common/misc/getoptargv.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/Runtime/common/misc/getoptargv.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | /* $Id: getoptargv.cpp 69111 2017-10-17 14:26:02Z vboxsync $ */
/** @file
* IPRT - Command Line Parsing, Argument Vector.
*/
/*
* Copyright (C) 2010-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include <iprt/getopt.h>
#include "internal/iprt.h"
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/mem.h>
#include <iprt/string.h>
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
/**
* Array indexed by the quoting type and 7-bit ASCII character.
*
* We include some extra stuff here that the corresponding shell would normally
* require quoting of.
*/
static uint8_t
#ifndef IPRT_REGENERATE_QUOTE_CHARS
const
#endif
g_abmQuoteChars[RTGETOPTARGV_CNV_QUOTE_MASK + 1][16] =
{
{ 0xfe, 0xff, 0xff, 0xff, 0x65, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 },
{ 0xfe, 0xff, 0xff, 0xff, 0xd7, 0x07, 0x00, 0xd8, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x50 },
};
#ifdef IPRT_REGENERATE_QUOTE_CHARS /* To re-generate the bitmaps. */
# include <stdio.h>
int main()
{
RT_ZERO(g_abmQuoteChars);
# define SET_ALL(ch) \
do { \
for (size_t iType = 0; iType <= RTGETOPTARGV_CNV_QUOTE_MASK; iType++) \
ASMBitSet(&g_abmQuoteChars[iType], (ch)); \
} while (0)
# define SET(ConstSuffix, ch) \
do { \
ASMBitSet(&g_abmQuoteChars[RTGETOPTARGV_CNV_QUOTE_##ConstSuffix], (ch)); \
printf(#ConstSuffix ": %#x %d %c\n", (ch), (ch), (ch)); \
} while (0)
/* just flag all the control chars as in need of quoting. */
for (char ch = 1; ch < 0x20; ch++)
SET_ALL(ch);
/* ... and space of course */
SET_ALL(' ');
/* MS CRT / CMD.EXE: */
SET(MS_CRT, '"');
SET(MS_CRT, '&');
SET(MS_CRT, '>');
SET(MS_CRT, '<');
SET(MS_CRT, '|');
SET(MS_CRT, '%');
/* Bourne shell: */
SET(BOURNE_SH, '!');
SET(BOURNE_SH, '"');
SET(BOURNE_SH, '$');
SET(BOURNE_SH, '&');
SET(BOURNE_SH, '(');
SET(BOURNE_SH, ')');
SET(BOURNE_SH, '*');
SET(BOURNE_SH, ';');
SET(BOURNE_SH, '<');
SET(BOURNE_SH, '>');
SET(BOURNE_SH, '?');
SET(BOURNE_SH, '[');
SET(BOURNE_SH, '\'');
SET(BOURNE_SH, '\\');
SET(BOURNE_SH, '`');
SET(BOURNE_SH, '|');
SET(BOURNE_SH, '~');
for (size_t iType = 0; iType <= RTGETOPTARGV_CNV_QUOTE_MASK; iType++)
{
printf(" {");
for (size_t iByte = 0; iByte < 16; iByte++)
printf(iByte == 0 ? " 0x%02x" : ", 0x%02x", g_abmQuoteChars[iType][iByte]);
printf(" },\n");
}
return 0;
}
#else /* !IPRT_REGENERATE_QUOTE_CHARS */
/**
* Look for an unicode code point in the separator string.
*
* @returns true if it's a separator, false if it isn't.
* @param Cp The code point.
* @param pszSeparators The separators.
*/
static bool rtGetOptIsUniCpInString(RTUNICP Cp, const char *pszSeparators)
{
/* This could be done in a more optimal fashion. Probably worth a
separate RTStr function at some point. */
for (;;)
{
RTUNICP CpSep;
int rc = RTStrGetCpEx(&pszSeparators, &CpSep);
AssertRCReturn(rc, false);
if (CpSep == Cp)
return true;
if (!CpSep)
return false;
}
}
/**
* Look for an 7-bit ASCII character in the separator string.
*
* @returns true if it's a separator, false if it isn't.
* @param ch The character.
* @param pszSeparators The separators.
* @param cchSeparators The number of separators chars.
*/
DECLINLINE(bool) rtGetOptIsAsciiInSet(char ch, const char *pszSeparators, size_t cchSeparators)
{
switch (cchSeparators)
{
case 8: if (ch == pszSeparators[7]) return true; RT_FALL_THRU();
case 7: if (ch == pszSeparators[6]) return true; RT_FALL_THRU();
case 6: if (ch == pszSeparators[5]) return true; RT_FALL_THRU();
case 5: if (ch == pszSeparators[4]) return true; RT_FALL_THRU();
case 4: if (ch == pszSeparators[3]) return true; RT_FALL_THRU();
case 3: if (ch == pszSeparators[2]) return true; RT_FALL_THRU();
case 2: if (ch == pszSeparators[1]) return true; RT_FALL_THRU();
case 1: if (ch == pszSeparators[0]) return true;
return false;
default:
return memchr(pszSeparators, ch, cchSeparators) != NULL;
}
}
/**
* Checks if the character is in the set of separators
*
* @returns true if it is, false if it isn't.
*
* @param Cp The code point.
* @param pszSeparators The separators.
* @param cchSeparators The length of @a pszSeparators.
*/
DECL_FORCE_INLINE(bool) rtGetOptIsCpInSet(RTUNICP Cp, const char *pszSeparators, size_t cchSeparators)
{
if (RT_LIKELY(Cp <= 127))
return rtGetOptIsAsciiInSet((char)Cp, pszSeparators, cchSeparators);
return rtGetOptIsUniCpInString(Cp, pszSeparators);
}
/**
* Skips any delimiters at the start of the string that is pointed to.
*
* @returns VINF_SUCCESS or RTStrGetCpEx status code.
* @param ppszSrc Where to get and return the string pointer.
* @param pszSeparators The separators.
* @param cchSeparators The length of @a pszSeparators.
*/
static int rtGetOptSkipDelimiters(const char **ppszSrc, const char *pszSeparators, size_t cchSeparators)
{
const char *pszSrc = *ppszSrc;
const char *pszRet;
for (;;)
{
pszRet = pszSrc;
RTUNICP Cp;
int rc = RTStrGetCpEx(&pszSrc, &Cp);
if (RT_FAILURE(rc))
{
*ppszSrc = pszRet;
return rc;
}
if ( !Cp
|| !rtGetOptIsCpInSet(Cp, pszSeparators, cchSeparators))
break;
}
*ppszSrc = pszRet;
return VINF_SUCCESS;
}
RTDECL(int) RTGetOptArgvFromString(char ***ppapszArgv, int *pcArgs, const char *pszCmdLine,
uint32_t fFlags, const char *pszSeparators)
{
/*
* Some input validation.
*/
AssertPtr(pszCmdLine);
AssertPtr(pcArgs);
AssertPtr(ppapszArgv);
AssertReturn( (fFlags & RTGETOPTARGV_CNV_QUOTE_MASK) == RTGETOPTARGV_CNV_QUOTE_BOURNE_SH
|| (fFlags & RTGETOPTARGV_CNV_QUOTE_MASK) == RTGETOPTARGV_CNV_QUOTE_MS_CRT, VERR_INVALID_FLAGS);
AssertReturn(~(fFlags & ~RTGETOPTARGV_CNV_VALID_MASK), VERR_INVALID_FLAGS);
if (!pszSeparators)
pszSeparators = " \t\n\r";
else
AssertPtr(pszSeparators);
size_t const cchSeparators = strlen(pszSeparators);
AssertReturn(cchSeparators > 0, VERR_INVALID_PARAMETER);
/*
* Parse the command line and chop off it into argv individual argv strings.
*/
const char *pszSrc = pszCmdLine;
char *pszDup = NULL;
char *pszDst;
if (fFlags & RTGETOPTARGV_CNV_MODIFY_INPUT)
pszDst = (char *)pszCmdLine;
else
{
pszDst = pszDup = (char *)RTMemAlloc(strlen(pszSrc) + 1);
if (!pszDup)
return VERR_NO_STR_MEMORY;
}
int rc = VINF_SUCCESS;
char **papszArgs = NULL;
unsigned iArg = 0;
while (*pszSrc)
{
/* Skip stuff */
rc = rtGetOptSkipDelimiters(&pszSrc, pszSeparators, cchSeparators);
if (RT_FAILURE(rc))
break;
if (!*pszSrc)
break;
/* Start a new entry. */
if ((iArg % 32) == 0)
{
void *pvNew = RTMemRealloc(papszArgs, (iArg + 33) * sizeof(char *));
if (!pvNew)
{
rc = VERR_NO_MEMORY;
break;
}
papszArgs = (char **)pvNew;
}
papszArgs[iArg++] = pszDst;
/*
* Parse and copy the string over.
*/
RTUNICP uc;
if ((fFlags & RTGETOPTARGV_CNV_QUOTE_MASK) == RTGETOPTARGV_CNV_QUOTE_BOURNE_SH)
{
/*
* Bourne shell style.
*/
RTUNICP ucQuote = 0;
for (;;)
{
rc = RTStrGetCpEx(&pszSrc, &uc);
if (RT_FAILURE(rc) || !uc)
break;
if (!ucQuote)
{
if (uc == '"' || uc == '\'')
ucQuote = uc;
else if (rtGetOptIsCpInSet(uc, pszSeparators, cchSeparators))
break;
else if (uc != '\\')
pszDst = RTStrPutCp(pszDst, uc);
else
{
/* escaped char */
rc = RTStrGetCpEx(&pszSrc, &uc);
if (RT_FAILURE(rc) || !uc)
break;
pszDst = RTStrPutCp(pszDst, uc);
}
}
else if (ucQuote != uc)
{
if (uc != '\\' || ucQuote == '\'')
pszDst = RTStrPutCp(pszDst, uc);
else
{
/* escaped char */
rc = RTStrGetCpEx(&pszSrc, &uc);
if (RT_FAILURE(rc) || !uc)
break;
if ( uc != '"'
&& uc != '\\'
&& uc != '`'
&& uc != '$'
&& uc != '\n')
pszDst = RTStrPutCp(pszDst, ucQuote);
pszDst = RTStrPutCp(pszDst, uc);
}
}
else
ucQuote = 0;
}
}
else
{
/*
* Microsoft CRT style.
*/
Assert((fFlags & RTGETOPTARGV_CNV_QUOTE_MASK) == RTGETOPTARGV_CNV_QUOTE_MS_CRT);
bool fInQuote = false;
for (;;)
{
rc = RTStrGetCpEx(&pszSrc, &uc);
if (RT_FAILURE(rc) || !uc)
break;
if (uc == '"')
{
/* Two double quotes insides a quoted string in an escape
sequence and we output one double quote char.
See http://www.daviddeley.com/autohotkey/parameters/parameters.htm */
if (!fInQuote)
fInQuote = true;
else if (*pszSrc != '"')
fInQuote = false;
else
{
pszDst = RTStrPutCp(pszDst, '"');
pszSrc++;
}
}
else if (!fInQuote && rtGetOptIsCpInSet(uc, pszSeparators, cchSeparators))
break;
else if (uc != '\\')
pszDst = RTStrPutCp(pszDst, uc);
else
{
/* A backslash sequence is only relevant if followed by
a double quote, then it will work like an escape char. */
size_t cSlashes = 1;
while (*pszSrc == '\\')
{
cSlashes++;
pszSrc++;
}
if (*pszSrc != '"')
/* Not an escape sequence. */
while (cSlashes-- > 0)
pszDst = RTStrPutCp(pszDst, '\\');
else
{
/* Escape sequence. Output half of the slashes. If odd
number, output the escaped double quote . */
while (cSlashes >= 2)
{
pszDst = RTStrPutCp(pszDst, '\\');
cSlashes -= 2;
}
if (cSlashes)
{
pszDst = RTStrPutCp(pszDst, '"');
pszSrc++;
}
}
}
}
}
*pszDst++ = '\0';
if (RT_FAILURE(rc) || !uc)
break;
}
if (RT_FAILURE(rc))
{
RTMemFree(pszDup);
RTMemFree(papszArgs);
return rc;
}
/*
* Terminate the array.
* Check for empty string to make sure we've got an array.
*/
if (iArg == 0)
{
RTMemFree(pszDup);
papszArgs = (char **)RTMemAlloc(1 * sizeof(char *));
if (!papszArgs)
return VERR_NO_MEMORY;
}
papszArgs[iArg] = NULL;
*pcArgs = iArg;
*ppapszArgv = papszArgs;
return VINF_SUCCESS;
}
RTDECL(void) RTGetOptArgvFree(char **papszArgv)
{
RTGetOptArgvFreeEx(papszArgv, 0);
}
RTDECL(void) RTGetOptArgvFreeEx(char **papszArgv, uint32_t fFlags)
{
Assert(~(fFlags & ~RTGETOPTARGV_CNV_VALID_MASK));
if (papszArgv)
{
/*
* We've really only _two_ allocations here. Check the code in
* RTGetOptArgvFromString for the particulars.
*/
if (!(fFlags & RTGETOPTARGV_CNV_MODIFY_INPUT))
RTMemFree(papszArgv[0]);
RTMemFree(papszArgv);
}
}
/**
* Checks if the argument needs quoting or not.
*
* @returns true if it needs, false if it don't.
* @param pszArg The argument.
* @param fFlags Quoting style.
* @param pcch Where to store the argument length when quoting
* is not required. (optimization)
*/
DECLINLINE(bool) rtGetOpArgvRequiresQuoting(const char *pszArg, uint32_t fFlags, size_t *pcch)
{
if ((fFlags & RTGETOPTARGV_CNV_QUOTE_MASK) != RTGETOPTARGV_CNV_UNQUOTED)
{
char const *psz = pszArg;
unsigned char ch;
while ((ch = (unsigned char)*psz))
{
if ( ch < 128
&& ASMBitTest(&g_abmQuoteChars[fFlags & RTGETOPTARGV_CNV_QUOTE_MASK], ch))
return true;
psz++;
}
*pcch = psz - pszArg;
}
else
*pcch = strlen(pszArg);
return false;
}
/**
* Grows the command line string buffer.
*
* @returns VINF_SUCCESS or VERR_NO_STR_MEMORY.
* @param ppszCmdLine Pointer to the command line string pointer.
* @param pcbCmdLineAlloc Pointer to the allocation length variable.
* @param cchMin The minimum size to grow with, kind of.
*/
static int rtGetOptArgvToStringGrow(char **ppszCmdLine, size_t *pcbCmdLineAlloc, size_t cchMin)
{
size_t cb = *pcbCmdLineAlloc;
while (cb < cchMin)
cb *= 2;
cb *= 2;
*pcbCmdLineAlloc = cb;
return RTStrRealloc(ppszCmdLine, cb);
}
/**
* Checks if we have a sequence of DOS slashes followed by a double quote char.
*
* @returns true / false accordingly.
* @param psz The string.
*/
DECLINLINE(bool) rtGetOptArgvMsCrtIsSlashQuote(const char *psz)
{
while (*psz == '\\')
psz++;
return *psz == '"' || *psz == '\0';
}
RTDECL(int) RTGetOptArgvToString(char **ppszCmdLine, const char * const *papszArgv, uint32_t fFlags)
{
AssertReturn((fFlags & RTGETOPTARGV_CNV_QUOTE_MASK) <= RTGETOPTARGV_CNV_UNQUOTED, VERR_INVALID_FLAGS);
AssertReturn(!(fFlags & (~RTGETOPTARGV_CNV_VALID_MASK | RTGETOPTARGV_CNV_MODIFY_INPUT)), VERR_INVALID_FLAGS);
#define PUT_CH(ch) \
if (RT_UNLIKELY(off + 1 >= cbCmdLineAlloc)) { \
rc = rtGetOptArgvToStringGrow(&pszCmdLine, &cbCmdLineAlloc, 1); \
if (RT_FAILURE(rc)) \
break; \
} \
pszCmdLine[off++] = (ch)
#define PUT_PSZ(psz, cch) \
if (RT_UNLIKELY(off + (cch) >= cbCmdLineAlloc)) { \
rc = rtGetOptArgvToStringGrow(&pszCmdLine, &cbCmdLineAlloc, (cch)); \
if (RT_FAILURE(rc)) \
break; \
} \
memcpy(&pszCmdLine[off], (psz), (cch)); \
off += (cch);
#define PUT_SZ(sz) PUT_PSZ(sz, sizeof(sz) - 1)
/*
* Take the realloc approach, it requires less code and is probably more
* efficient than figuring out the size first.
*/
int rc = VINF_SUCCESS;
size_t off = 0;
size_t cbCmdLineAlloc = 256;
char *pszCmdLine = RTStrAlloc(256);
if (!pszCmdLine)
return VERR_NO_STR_MEMORY;
for (size_t i = 0; papszArgv[i]; i++)
{
if (i > 0)
{
PUT_CH(' ');
}
/* does it need quoting? */
const char *pszArg = papszArgv[i];
size_t cchArg;
if (!rtGetOpArgvRequiresQuoting(pszArg, fFlags, &cchArg))
{
/* No quoting needed, just append the argument. */
PUT_PSZ(pszArg, cchArg);
}
else if ((fFlags & RTGETOPTARGV_CNV_QUOTE_MASK) == RTGETOPTARGV_CNV_QUOTE_MS_CRT)
{
/*
* Microsoft CRT quoting. Quote the whole argument in double
* quotes to make it easier to read and code.
*/
PUT_CH('"');
char ch;
while ((ch = *pszArg++))
{
if ( ch == '\\'
&& rtGetOptArgvMsCrtIsSlashQuote(pszArg))
{
PUT_SZ("\\\\");
}
else if (ch == '"')
{
PUT_SZ("\\\"");
}
else
{
PUT_CH(ch);
}
}
PUT_CH('"');
}
else
{
/*
* Bourne Shell quoting. Quote the whole thing in single quotes
* and use double quotes for any single quote chars.
*/
PUT_CH('\'');
char ch;
while ((ch = *pszArg++))
{
if (ch == '\'')
{
PUT_SZ("'\"'\"'");
}
else
{
PUT_CH(ch);
}
}
PUT_CH('\'');
}
}
/* Set return value / cleanup. */
if (RT_SUCCESS(rc))
{
pszCmdLine[off] = '\0';
*ppszCmdLine = pszCmdLine;
}
else
RTStrFree(pszCmdLine);
#undef PUT_SZ
#undef PUT_PSZ
#undef PUT_CH
return rc;
}
RTDECL(int) RTGetOptArgvToUtf16String(PRTUTF16 *ppwszCmdLine, const char * const *papszArgv, uint32_t fFlags)
{
char *pszCmdLine;
int rc = RTGetOptArgvToString(&pszCmdLine, papszArgv, fFlags);
if (RT_SUCCESS(rc))
{
rc = RTStrToUtf16(pszCmdLine, ppwszCmdLine);
RTStrFree(pszCmdLine);
}
return rc;
}
#endif /* !IPRT_REGENERATE_QUOTE_CHARS */
| 31.542636 | 130 | 0.496092 | [
"vector"
] |
a8e8637e3305d6f779ee21f08b65cc7358b12512 | 13,792 | cpp | C++ | src/stream_info_impl.cpp | samuelpowell/liblsl | 92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3 | [
"MIT"
] | 1 | 2020-07-13T00:04:51.000Z | 2020-07-13T00:04:51.000Z | src/stream_info_impl.cpp | samuelpowell/liblsl | 92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3 | [
"MIT"
] | null | null | null | src/stream_info_impl.cpp | samuelpowell/liblsl | 92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3 | [
"MIT"
] | null | null | null | #include <boost/thread/lock_guard.hpp>
#include "cast.h"
#include "stream_info_impl.h"
#include "api_config.h"
// === implementation of the stream_info_impl class ===
using namespace lsl;
using namespace pugi;
using std::string;
/// Default Constructor.
stream_info_impl::stream_info_impl(): channel_count_(0), nominal_srate_(0), channel_format_(cft_undefined), version_(0), v4data_port_(0), v4service_port_(0), v6data_port_(0), v6service_port_(0), created_at_(0) {
// initialize XML document
write_xml(doc_);
}
/// Constructor.
stream_info_impl::stream_info_impl(const string &name, const string &type, int channel_count, double nominal_srate, lsl_channel_format_t channel_format, const string &source_id):
name_(name), type_(type), channel_count_(channel_count), nominal_srate_(nominal_srate), channel_format_(channel_format), source_id_(source_id), version_(api_config::get_instance()->use_protocol_version()),
v4data_port_(0), v4service_port_(0), v6data_port_(0), v6service_port_(0), created_at_(0) {
if (name.empty())
throw std::invalid_argument("The name of a stream must be non-empty.");
if (channel_count < 0)
throw std::invalid_argument("The channel_count of a stream must be nonnegative.");
if (nominal_srate < 0)
throw std::invalid_argument("The nominal sampling rate of a stream must be nonnegative.");
if (channel_format < 0 || channel_format > 7)
throw std::invalid_argument("The stream info was created with an unknown channel format.");
// initialize XML document
write_xml(doc_);
}
/// Helper function to add a child node with only a single text node
template<typename T> void append_text_node(xml_node& node, const char* name, const T& value) {
node.append_child(name).append_child(node_pcdata).text().set(value);
}
template<> void append_text_node(xml_node& node, const char* name, const std::string& value) {
node.append_child(name).append_child(node_pcdata).set_value(value.c_str());
}
/// Initialize the XML DOM structure (leaving .desc unchanged) from the data.
void stream_info_impl::write_xml(xml_document &doc) {
const char *channel_format_strings[] = {"undefined","float32","double64","string","int32","int16","int8","int64"};
xml_node info = doc.append_child("info");
append_text_node(info, "name", name_);
append_text_node(info, "type", type_);
append_text_node(info, "channel_count", channel_count_);
append_text_node(info, "channel_format", channel_format_strings[channel_format_]);
append_text_node(info, "source_id", source_id_);
// floating point fields: use locale independent to_string function
append_text_node(info, "nominal_srate", to_string(nominal_srate_));
append_text_node(info, "version", to_string(version_ / 100.));
append_text_node(info, "created_at", to_string(created_at_));
append_text_node(info, "uid", uid_);
append_text_node(info, "session_id", session_id_);
append_text_node(info, "hostname", hostname_);
append_text_node(info, "v4address", v4address_);
append_text_node(info, "v4data_port", v4data_port_);
append_text_node(info, "v4service_port", v4service_port_);
append_text_node(info, "v6address", v6address_);
append_text_node(info, "v6data_port", v6data_port_);
append_text_node(info, "v6service_port", v6service_port_);
info.append_child("desc");
}
/// Read & assign the object's fields from an XML DOM structure.
void stream_info_impl::read_xml(xml_document &doc) {
try {
xml_node info = doc.child("info");
// name
name_ = info.child_value("name");
if (name_.empty())
throw std::runtime_error("Received a stream info with empty <name> field.");
// type
type_ = info.child_value("type");
// channel_count
channel_count_ = from_string<int>(info.child_value("channel_count"));
if (channel_count_ < 0)
throw std::runtime_error("The channel count of the given stream info is smaller than 0.");
// nominal_srate
nominal_srate_ = from_string<double>(info.child_value("nominal_srate"));
if (nominal_srate_ < 0.0)
throw std::runtime_error("The sampling rate of the given stream info is negative.");
// channel_format
channel_format_ = cft_undefined;
string fmt(info.child_value("channel_format"));
if (fmt == "float32")
channel_format_ = cft_float32;
if (fmt == "double64")
channel_format_ = cft_double64;
if (fmt == "string")
channel_format_ = cft_string;
if (fmt == "int32")
channel_format_ = cft_int32;
if (fmt == "int16")
channel_format_ = cft_int16;
if (fmt == "int8")
channel_format_ = cft_int8;
if (fmt == "int64")
channel_format_ = cft_int64;
// source_id
source_id_ = info.child_value("source_id");
// version
version_ = (int)(from_string<double>(info.child_value("version")) * 100.0);
if (version_ <= 0)
throw std::runtime_error("The version of the given stream info is invalid.");
// created_at
created_at_ = from_string<double>(info.child_value("created_at"));
// uid
uid_ = info.child_value("uid");
if (uid_.empty())
throw std::runtime_error("The UID of the given stream info is empty.");
// session_id
session_id_ = info.child_value("session_id");
// hostname
hostname_ = info.child_value("hostname");
// address
v4address_ = info.child_value("v4address");
// data_port
v4data_port_ = from_string<int>(info.child_value("v4data_port"));
// service_port
v4service_port_ = from_string<int>(info.child_value("v4service_port"));
// address
v6address_ = info.child_value("v6address");
// data_port
v6data_port_ = from_string<int>(info.child_value("v6data_port"));
// service_port
v6service_port_ = from_string<int>(info.child_value("v6service_port"));
} catch(std::exception &e) {
// reset the stream info to blank state
*this = stream_info_impl();
name_ = (string("(invalid: ") += e.what()) += ")";
}
}
//
// === Protocol Support Operations Implementation ===
//
/**
* Get the short-info message according to this stream_info.
* The short-info message is a shortened xml representation of the stream_info, excluding the .desc field (which can be megabytes in size).
* This message is sent by a stream outlet in response to a variety of queries.
*/
string stream_info_impl::to_shortinfo_message() {
// make a new document (with an empty <desc> field)
xml_document tmp; write_xml(tmp);
// write it to a stream
std::ostringstream os; tmp.save(os);
// and get the string
return os.str();
}
/**
* Initialize a stream_info from a short-info message .
* This functions resets all fields of the stream_info accoridng to the message. The .desc field will be empty.
*/
void stream_info_impl::from_shortinfo_message(const std::string &m) {
// load the doc from the message string
doc_.load_buffer(m.c_str(),m.size());
// and assign all the struct fields, too...
read_xml(doc_);
}
/**
* Get the full-info message for this stream_info.
* This is a complete XML representation of the stream_info.
*/
std::string stream_info_impl::to_fullinfo_message() {
// write the doc to a stream
std::ostringstream os; doc_.save(os);
// and get the string
return os.str();
}
/**
* Initialize a stream_info from a full-info message.
* This functions resets all fields of the stream_info accoridng to the message.
*/
void stream_info_impl::from_fullinfo_message(const std::string &m) {
// load the doc from the message string
doc_.load_buffer(m.c_str(),m.size());
// and assign all the struct fields, too...
read_xml(doc_);
}
/**
* Test whether this stream info matches the given query string.
*/
bool stream_info_impl::matches_query(const string &query) {
lslboost::lock_guard<lslboost::mutex> lock(cache_mut_);
query_cache::left_iterator it = cached_.left.find(query);
if (it != cached_.left.end()) {
// found in cache
bool is_match = it->second.second;
// update the last-use time stamp
cached_.left.replace_data(it,std::make_pair(lsl_clock(),is_match));
return is_match;
} else {
// not found in cache
try {
// compute whether it matches
string fullquery = (string("/info[") += query) += "]";
bool result = !doc_.select_nodes(fullquery.c_str()).empty();
// insert result into cache
cached_.left.insert(std::make_pair(query,std::make_pair(lsl_clock(),result)));
// remove oldest results until we're within capacity
while ((int)cached_.size() > api_config::get_instance()->max_cached_queries())
cached_.right.erase(cached_.right.begin());
// return result
return result;
} catch(...) {
return false; // error: unsupported query
}
}
}
int stream_info_impl::channel_bytes() const
{
const int channel_format_sizes[] = {0,sizeof(float),sizeof(double),sizeof(std::string),sizeof(int32_t),sizeof(int16_t),sizeof(int8_t),8};
return channel_format_sizes[channel_format_];
}
/**
* Return a handle to the info/desc element.
*/
xml_node stream_info_impl::desc() {return doc_.child("info").child("desc"); }
xml_node stream_info_impl::desc() const { return doc_.child("info").child("desc"); }
/**
* Set the info / protocol version used by the stream.
*/
void stream_info_impl::version(int v) {
version_ = v;
doc_.child("info").child("version").first_child().set_value(to_string(version_ / 100.).c_str());
}
/**
* Set the creation time stamp of a stream.
* This is the time stamp (via now()) of when the stream was first created
* (in the time domain of the providing machine).
*/
void stream_info_impl::created_at(double v) {
created_at_ = v;
doc_.child("info").child("created_at").first_child().set_value(to_string(created_at_).c_str());
}
/**
* Set the UID of a stream instance (once assigned).
* This is a unique identifier of the stream instance, and is guaranteed to be different
* across multiple instantiations of the same stream (e.g., after a re-start).
*/
void stream_info_impl::uid(const std::string &v) {
uid_ = v;
doc_.child("info").child("uid").first_child().set_value(uid_.c_str());
}
/**
* Set the session id for the given stream.
* The session ID is an optional human-assigned identifier of the recording session; only
* inlets and outlets that have the same session id can be paired with each other to avoid
* accidentally recording from an unrelated concurrent session on the same network.
* The session id can be set via the configuration file (see Network Connectivity in the LSL wiki).
*/
void stream_info_impl::session_id(const std::string &v) {
session_id_ = v;
doc_.child("info").child("session_id").first_child().set_value(session_id_.c_str());
}
/**
* Set the provider hostname for the given stream.
*/
void stream_info_impl::hostname(const std::string &v) {
hostname_ = v;
doc_.child("info").child("hostname").first_child().set_value(hostname_.c_str());
}
/**
* Set the host name or IP address where the stream is hosted.
*/
void stream_info_impl::v4address(const std::string &v) {
v4address_ = v;
doc_.child("info").child("v4address").first_child().set_value(v4address_.c_str());
}
/**
* Set the TCP data port where the stream is hosted (once assigned).
* This port is internally used to obtain data and meta-data from a stream.
*/
void stream_info_impl::v4data_port(uint16_t v) {
v4data_port_ = v;
doc_.child("info").child("v4data_port").first_child().text().set(v4data_port_);
}
/**
* Set the UDP service port where the stream is hosted (once assigned).
* This port is internally used to obtain time correction information for a stream.
*/
void stream_info_impl::v4service_port(uint16_t v) {
v4service_port_ = v;
doc_.child("info").child("v4service_port").first_child().text().set(v4service_port_);
}
/**
* Set the host name or IP address where the stream is hosted.
*/
void stream_info_impl::v6address(const std::string &v) {
v6address_ = v;
doc_.child("info").child("v6address").first_child().set_value(v6address_.c_str());
}
/**
* Set the TCP data port where the stream is hosted (once assigned).
* This port is internally used to obtain data and meta-data from a stream.
*/
void stream_info_impl::v6data_port(uint16_t v) {
v6data_port_ = v;
doc_.child("info").child("v6data_port").first_child().text().set(v6data_port_);
}
/**
* Set the UDP service port where the stream is hosted (once assigned).
* This port is internally used to obtain time correction information for a stream.
*/
void stream_info_impl::v6service_port(uint16_t v) {
v6service_port_ = v;
doc_.child("info").child("v6service_port").first_child().text().set(v6service_port_);
}
/**
* Assignment operator.
* Needs special handling because xml_document is non-copyable.
*/
stream_info_impl& stream_info_impl::operator=(stream_info_impl const &rhs) {
if (this == &rhs)
return *this;
name_ = rhs.name_;
type_ = rhs.type_;
channel_count_ = rhs.channel_count_;
nominal_srate_ = rhs.nominal_srate_;
channel_format_ = rhs.channel_format_;
source_id_ = rhs.source_id_;
version_ = rhs.version_;
v4address_ = rhs.v4address_;
v4data_port_ = rhs.v4data_port_;
v4service_port_ = rhs.v4service_port_;
v6address_ = rhs.v6address_;
v6data_port_ = rhs.v6data_port_;
v6service_port_ = rhs.v6service_port_;
uid_ = rhs.uid_;
created_at_ = rhs.created_at_;
session_id_ = rhs.session_id_;
hostname_ = rhs.hostname_;
doc_.reset(rhs.doc_);
return *this;
}
/**
* Copy constructor.
* Needs special handling because xml_document is non-copyable.
*/
stream_info_impl::stream_info_impl(const stream_info_impl &rhs): name_(rhs.name_), type_(rhs.type_), channel_count_(rhs.channel_count_),
nominal_srate_(rhs.nominal_srate_), channel_format_(rhs.channel_format_), source_id_(rhs.source_id_), version_(rhs.version_), v4address_(rhs.v4address_),
v4data_port_(rhs.v4data_port_), v4service_port_(rhs.v4service_port_), v6address_(rhs.v6address_), v6data_port_(rhs.v6data_port_), v6service_port_(rhs.v6service_port_),
uid_(rhs.uid_), created_at_(rhs.created_at_), session_id_(rhs.session_id_), hostname_(rhs.hostname_) {
doc_.reset(rhs.doc_);
}
| 36.975871 | 211 | 0.735571 | [
"object"
] |
a8ebf3ab0fde20a2f7d641f3c8f3052ee1f97853 | 1,944 | cpp | C++ | AtCoder/ABC/ABC-036/SolveD.cpp | MonadicDavidHuang/CompetitiveProgramming | b5b6f39a1be05d257f8ea8e504dd910cc624b153 | [
"MIT"
] | null | null | null | AtCoder/ABC/ABC-036/SolveD.cpp | MonadicDavidHuang/CompetitiveProgramming | b5b6f39a1be05d257f8ea8e504dd910cc624b153 | [
"MIT"
] | null | null | null | AtCoder/ABC/ABC-036/SolveD.cpp | MonadicDavidHuang/CompetitiveProgramming | b5b6f39a1be05d257f8ea8e504dd910cc624b153 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long int;
const int MAX = (int)(1e5 + 5);
const ll INF = (ll)(1e10 + 5);
const int MAX_N = (int)(1e5 + 5);
const ll MOD = (ll)(1e9 + 7);
/////////////////////////////////////////////////////////////
class ModuloOperator {
public:
ll modulo;
ModuloOperator(ll modulo) { this->modulo = modulo; }
ll add(ll a, ll b) {
ll ret = a + b;
ret %= modulo;
return ret;
}
ll sub(ll a, ll b) {
ll ret = a - b;
if (ret < 0)
ret += modulo;
else
ret %= modulo;
return ret;
}
ll mul(ll a, ll b) {
ll ret = a * b;
ret %= modulo;
return ret;
}
ll div(ll a, ll b) { return mul(a, pow(b, modulo - 2)); }
ll pow(ll x, ll y) {
ll res = 1LL;
x %= modulo;
while (y > 0) {
if (y & 1) {
res = mul(res, x);
}
y = y >> 1;
x = mul(x, x);
}
return res;
}
};
/////////////////////////////////////////////////////////////
ModuloOperator mo(MOD);
map<pair<int, char>, ll> memo;
int n;
vector<vector<int>> graph(MAX_N);
ll paint(int parent, int cur, char col) {
auto key = make_pair(cur, col);
if (memo.find(key) != memo.end()) {
return memo[key];
}
ll ret = 1LL;
if (col == 'b') {
for (auto &next : graph[cur]) {
if (next == parent) continue;
ret = mo.mul(ret, paint(cur, next, 'w'));
}
} else { // col == 'w'
for (auto &next : graph[cur]) {
if (next == parent) continue;
ll tmp = 1LL;
tmp = mo.add(paint(cur, next, 'b'), paint(cur, next, 'w'));
ret = mo.mul(ret, tmp);
}
}
return memo[key] = ret;
}
int main(void) {
// Here your code !
scanf("%d", &n);
for (int i = 0; i < n - 1; ++i) {
int a, b;
scanf("%d %d", &a, &b);
graph[a].push_back(b);
graph[b].push_back(a);
}
ll ans = mo.add(paint(0, 1, 'w'), paint(0, 1, 'b'));
printf("%lld\n", ans);
return 0;
}
| 17.357143 | 65 | 0.462449 | [
"vector"
] |
a8edcc65069b9ec05d6315ce0f41af11cfc3c81d | 524 | cpp | C++ | src/Parser/Data_Structures/Non_Terminal/line.cpp | MuhammedKhamis/Camila | 51a0c09f99cf4d624802dac8fc169ad2c06223aa | [
"MIT"
] | 1 | 2018-05-17T07:52:39.000Z | 2018-05-17T07:52:39.000Z | src/Parser/Data_Structures/Non_Terminal/line.cpp | MuhammedKhamis/Camila | 51a0c09f99cf4d624802dac8fc169ad2c06223aa | [
"MIT"
] | null | null | null | src/Parser/Data_Structures/Non_Terminal/line.cpp | MuhammedKhamis/Camila | 51a0c09f99cf4d624802dac8fc169ad2c06223aa | [
"MIT"
] | 1 | 2018-09-29T08:44:15.000Z | 2018-09-29T08:44:15.000Z | //
// Created by muhammed on 25/04/18.
//
#include "line.h"
line::line(string non_terminal) : non_terminal(non_terminal) {}
line::line() {}
void line::add_element(element elem) {
this->productions.emplace_back(elem);
}
vector<string> line::get_follows(string &val) {
vector<string> follows;
for(int i = 0 ; i < productions.size() ; i++){
productions[i].add_follow(follows,val);
}
return follows;
}
void line::setNon_terminal(string non_terminal) {
line::non_terminal = non_terminal;
}
| 19.407407 | 63 | 0.667939 | [
"vector"
] |
6f04b816eb948fc50d54b187fe16d6f74b4a9136 | 4,721 | cpp | C++ | source/sample/transformer/T2TEncoder.cpp | Dynamite12138/NLPwork | 640c0e6b9a96997852a72df169869c7ad058a996 | [
"Apache-2.0"
] | 543 | 2019-11-03T12:15:13.000Z | 2022-03-04T10:12:13.000Z | source/sample/transformer/T2TEncoder.cpp | Dynamite12138/NLPwork | 640c0e6b9a96997852a72df169869c7ad058a996 | [
"Apache-2.0"
] | 8 | 2019-11-07T16:23:49.000Z | 2021-06-05T05:18:25.000Z | source/sample/transformer/T2TEncoder.cpp | Dynamite12138/NLPwork | 640c0e6b9a96997852a72df169869c7ad058a996 | [
"Apache-2.0"
] | 273 | 2019-11-04T04:57:12.000Z | 2022-03-04T10:12:16.000Z | /* NiuTrans.Tensor - an open-source tensor library
* Copyright (C) 2020, Natural Language Processing Lab, Northeastern University.
* 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.
*/
/*
* $Created by: XIAO Tong (xiaotong@mail.neu.edu.cn) 2018-07-31
* $Modified by: HU Chi (huchinlp@gmail.com) 2020-04
*/
#include <cmath>
#include "T2TEncoder.h"
#include "module/T2TUtility.h"
#include "module/T2TLayerNormal.h"
#include "module/T2TCommonModules.h"
#include "../../tensor/core/CHeader.h"
namespace transformer
{
/* constructor */
AttEncoder::AttEncoder()
{
selfAtt = NULL;
fnns = NULL;
attLayerNorms = NULL;
fnnLayerNorms = NULL;
encoderLayerNorm = NULL;
}
/* de-constructor */
AttEncoder::~AttEncoder()
{
delete[] selfAtt;
delete[] fnns;
delete[] attLayerNorms;
delete[] fnnLayerNorms;
if (preNorm)
delete encoderLayerNorm;
}
/*
initialize the model
>> config - configurations for the model
*/
void AttEncoder::InitModel(T2TConfig& config)
{
devID = config.devID;
nlayer = config.nEncLayer;
eSize = config.embSize;
hSize = config.modelSize;
vSize = config.srcVocabSize;
preNorm = config.preNorm;
dropoutP = config.dropout;
CheckNTErrors(nlayer >= 1, "We have one encoding layer at least!");
CheckNTErrors(vSize > 1, "set vocabulary size by \"-vsize\"");
/* embedding model */
embedder.InitModel(config);
selfAtt = new T2TAttention[nlayer];
fnns = new T2TFNN[nlayer];
attLayerNorms = new T2TLN[nlayer];
fnnLayerNorms = new T2TLN[nlayer];
if (preNorm)
encoderLayerNorm = new T2TLN;
/* initialize the stacked layers */
for (int i = 0; i < nlayer; i++) {
selfAtt[i].InitModel(config);
fnns[i].InitModel(config);
attLayerNorms[i].InitModel(config);
fnnLayerNorms[i].InitModel(config);
}
if (preNorm)
encoderLayerNorm->InitModel(config);
}
/*
make the encoding network
>> input - the input tensor of the encoder
>> mask - the mask that indicate each position is valid
>> maskEncDec - no use
>> isTraining - indicates whether the model is used for training
<< return - the output tensor of the encoder
*/
XTensor AttEncoder::Make(XTensor& input, XTensor* mask, XTensor& maskEncDec, bool isTraining)
{
XTensor x;
x = embedder.Make(input, false, isTraining);
/* dropout */
if (isTraining && dropoutP > 0)
x = Dropout(x, dropoutP);
for (int i = 0; i < nlayer; i++) {
XTensor att;
XTensor fnn;
XTensor res;
XTensor attnBefore;
XTensor attnAfter;
XTensor fnnBefore;
/* layer normalization with pre-norm for self-attn */
attnBefore = LayerNorm(x, attLayerNorms[i], preNorm, true, false);
/* self attention */
att = selfAtt[i].Make(attnBefore, attnBefore, attnBefore, mask, isTraining, NULL, 0);
/* dropout */
if (isTraining && dropoutP > 0)
att = Dropout(att, dropoutP);
/* residual connection */
res = Sum(att, x);
/* layer normalization with post-norm for self-attn */
attnAfter = LayerNorm(res, attLayerNorms[i], preNorm, false, true);
/* layer normalization with pre-norm for fnn */
fnnBefore = LayerNorm(attnAfter, fnnLayerNorms[i], preNorm, true, false);
/* fnn */
fnn = fnns[i].Make(fnnBefore, isTraining);
/* dropout */
if (isTraining && dropoutP > 0)
fnn = Dropout(fnn, dropoutP);
/* residual connection */
res = Sum(fnn, attnAfter);
/* layer normalization with post-norm for fnn */
x = LayerNorm(res, fnnLayerNorms[i], preNorm, false, true);
}
if (preNorm)
x = encoderLayerNorm->Make(x);
return x;
}
/*
make the encoding network (wrapper)
>> input - the input tensor of the encoder
>> mask - the mask that indicate each position is valid
>> isTraining - indicates whether the model is used for training
<< return - the output tensor of the encoder
*/
XTensor AttEncoder::Make(XTensor& input, XTensor* mask, bool isTraining)
{
XTensor nothing;
return Make(input, mask, nothing, isTraining);
}
} | 27.289017 | 93 | 0.653251 | [
"model"
] |
6f0731d91c1051c778c9727e92036072570b403f | 5,019 | cc | C++ | alidns/src/model/DescribePdnsRequestStatisticsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | alidns/src/model/DescribePdnsRequestStatisticsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | alidns/src/model/DescribePdnsRequestStatisticsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/alidns/model/DescribePdnsRequestStatisticsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Alidns;
using namespace AlibabaCloud::Alidns::Model;
DescribePdnsRequestStatisticsResult::DescribePdnsRequestStatisticsResult() :
ServiceResult()
{}
DescribePdnsRequestStatisticsResult::DescribePdnsRequestStatisticsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribePdnsRequestStatisticsResult::~DescribePdnsRequestStatisticsResult()
{}
void DescribePdnsRequestStatisticsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allDataNode = value["Data"]["StatisticItem"];
for (auto valueDataStatisticItem : allDataNode)
{
StatisticItem dataObject;
if(!valueDataStatisticItem["UdpTotalCount"].isNull())
dataObject.udpTotalCount = std::stol(valueDataStatisticItem["UdpTotalCount"].asString());
if(!valueDataStatisticItem["IpCount"].isNull())
dataObject.ipCount = std::stol(valueDataStatisticItem["IpCount"].asString());
if(!valueDataStatisticItem["DomainName"].isNull())
dataObject.domainName = valueDataStatisticItem["DomainName"].asString();
if(!valueDataStatisticItem["V6HttpCount"].isNull())
dataObject.v6HttpCount = std::stol(valueDataStatisticItem["V6HttpCount"].asString());
if(!valueDataStatisticItem["V4Count"].isNull())
dataObject.v4Count = std::stol(valueDataStatisticItem["V4Count"].asString());
if(!valueDataStatisticItem["HttpsCount"].isNull())
dataObject.httpsCount = std::stol(valueDataStatisticItem["HttpsCount"].asString());
if(!valueDataStatisticItem["V4HttpsCount"].isNull())
dataObject.v4HttpsCount = std::stol(valueDataStatisticItem["V4HttpsCount"].asString());
if(!valueDataStatisticItem["V6Count"].isNull())
dataObject.v6Count = std::stol(valueDataStatisticItem["V6Count"].asString());
if(!valueDataStatisticItem["SubDomain"].isNull())
dataObject.subDomain = valueDataStatisticItem["SubDomain"].asString();
if(!valueDataStatisticItem["TotalCount"].isNull())
dataObject.totalCount = std::stol(valueDataStatisticItem["TotalCount"].asString());
if(!valueDataStatisticItem["V4HttpCount"].isNull())
dataObject.v4HttpCount = std::stol(valueDataStatisticItem["V4HttpCount"].asString());
if(!valueDataStatisticItem["ThreatCount"].isNull())
dataObject.threatCount = std::stol(valueDataStatisticItem["ThreatCount"].asString());
if(!valueDataStatisticItem["MaxThreatLevel"].isNull())
dataObject.maxThreatLevel = valueDataStatisticItem["MaxThreatLevel"].asString();
if(!valueDataStatisticItem["HttpCount"].isNull())
dataObject.httpCount = std::stol(valueDataStatisticItem["HttpCount"].asString());
if(!valueDataStatisticItem["V6HttpsCount"].isNull())
dataObject.v6HttpsCount = std::stol(valueDataStatisticItem["V6HttpsCount"].asString());
if(!valueDataStatisticItem["DohTotalCount"].isNull())
dataObject.dohTotalCount = std::stol(valueDataStatisticItem["DohTotalCount"].asString());
auto allThreatInfoNode = valueDataStatisticItem["ThreatInfo"]["ThreatItem"];
for (auto valueDataStatisticItemThreatInfoThreatItem : allThreatInfoNode)
{
StatisticItem::ThreatItem threatInfoObject;
if(!valueDataStatisticItemThreatInfoThreatItem["ThreatLevel"].isNull())
threatInfoObject.threatLevel = valueDataStatisticItemThreatInfoThreatItem["ThreatLevel"].asString();
if(!valueDataStatisticItemThreatInfoThreatItem["ThreatType"].isNull())
threatInfoObject.threatType = valueDataStatisticItemThreatInfoThreatItem["ThreatType"].asString();
dataObject.threatInfo.push_back(threatInfoObject);
}
data_.push_back(dataObject);
}
if(!value["TotalCount"].isNull())
totalCount_ = std::stol(value["TotalCount"].asString());
if(!value["PageSize"].isNull())
pageSize_ = std::stol(value["PageSize"].asString());
if(!value["PageNumber"].isNull())
pageNumber_ = std::stol(value["PageNumber"].asString());
}
long DescribePdnsRequestStatisticsResult::getTotalCount()const
{
return totalCount_;
}
long DescribePdnsRequestStatisticsResult::getPageSize()const
{
return pageSize_;
}
long DescribePdnsRequestStatisticsResult::getPageNumber()const
{
return pageNumber_;
}
std::vector<DescribePdnsRequestStatisticsResult::StatisticItem> DescribePdnsRequestStatisticsResult::getData()const
{
return data_;
}
| 42.176471 | 115 | 0.775852 | [
"vector",
"model"
] |
6f080a0d8aefd61b8cfd284e5542a4d6030ead70 | 1,178 | cpp | C++ | N0977-Squares-of-a-Sorted-Array/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0977-Squares-of-a-Sorted-Array/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0977-Squares-of-a-Sorted-Array/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | 2 | 2022-01-25T05:31:31.000Z | 2022-02-26T07:22:23.000Z | //
// main.cpp
// LeetCode-Solution
//
// Created by Loyio Hex on 3/9/22.
//
#include <iostream>
#include <chrono>
#include <vector>
using namespace std;
using namespace std::chrono;
class Solution{
public:
vector<int> sortedSquares(vector<int>& nums){
int len = nums.size();
vector<int> ans(len);
for (int i = 0, j = len -1, pos = len - 1; i <= j;) {
if (nums[i]*nums[i] > nums[j]*nums[j]){
ans[pos] = nums[i]*nums[i];
++i;
}else{
ans[pos] = nums[j]*nums[j];
--j;
}
--pos;
}
return ans;
}
};
int main(int argc, const char * argv[]) {
auto start = high_resolution_clock::now();
// Main Start
vector<int> nums = {-4,-1,0,3,10};
Solution solution;
vector<int> resarray = solution.sortedSquares(nums);
for(const auto& num : resarray){
cout << num << " ";
}
// Main End
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << endl << "Runnig time : " << duration.count() << "ms;" << endl;
return 0;
}
| 22.226415 | 74 | 0.516978 | [
"vector"
] |
6f0e7ef7882f26dc5e69fdc0bc1629f328b6e993 | 4,412 | cc | C++ | src/compositor/shell_surface.cc | kkspeed/NaiveWM | 5da1e816ae3b9ec7a5a8c0b73b569615e231a215 | [
"BSD-3-Clause"
] | null | null | null | src/compositor/shell_surface.cc | kkspeed/NaiveWM | 5da1e816ae3b9ec7a5a8c0b73b569615e231a215 | [
"BSD-3-Clause"
] | 1 | 2017-07-12T06:22:10.000Z | 2017-07-16T17:27:09.000Z | src/compositor/shell_surface.cc | kkspeed/NaiveWM | 5da1e816ae3b9ec7a5a8c0b73b569615e231a215 | [
"BSD-3-Clause"
] | 1 | 2018-07-22T02:02:11.000Z | 2018-07-22T02:02:11.000Z | #include "compositor/shell_surface.h"
#include "compositor/buffer.h"
#include "compositor/surface.h"
#include "wm/window_impl.h"
#include "wm/window_impl/window_impl_wayland.h"
#include "wm/window_manager.h"
namespace naive {
ShellSurface::ShellSurface(Surface* surface)
: surface_(surface), window_(surface->window()) {
window_->SetShellSurface(this);
TRACE("add shell %p as observer to %p", this, surface_);
surface_->AddSurfaceObserver(this);
}
ShellSurface::~ShellSurface() {
TRACE("%p", this);
if (window_) {
static_cast<wm::WindowImplWayland*>(window_->window_impl())
->set_shell_surface(nullptr);
wm::WindowManager::Get()->RemoveWindow(window_);
}
if (surface_)
surface_->RemoveSurfaceObserver(this);
if (cached_window_state_ && cached_window_state_->parent_)
cached_window_state_->parent_->surface()->RemoveSurfaceObserver(this);
}
void ShellSurface::Configure(int32_t width, int32_t height) {
TRACE("configuring: %p, width: %d, height: %d", this, width, height);
if (!window_ || window_->is_transient())
return;
in_configure_ = true;
configure_callback_(width, height);
}
void ShellSurface::Close() {
if (!window_)
return;
close_callback_();
close_callback_ = []() {};
}
void ShellSurface::SetPosition(int32_t x, int32_t y) {
pending_state_.geometry.x_ = x;
pending_state_.geometry.y_ = y;
}
void ShellSurface::SetGeometry(const base::geometry::Rect& rect) {
TRACE("%d %d %d %d", rect.x(), rect.y(), rect.width(), rect.height());
pending_state_.geometry = rect;
}
void ShellSurface::SetVisibleRegion(const base::geometry::Rect& rect) {
TRACE("%d %d %d %d", rect.x(), rect.y(), rect.width(), rect.height());
pending_state_.visible_region = rect;
}
void ShellSurface::Move() {
if (!window_)
return;
window_->BeginMove();
}
void ShellSurface::AcknowledgeConfigure(uint32_t serial) {
in_configure_ = false;
// TODO: need to implement this?
NOTIMPLEMENTED();
}
void ShellSurface::OnCommit(Surface* committed_surface) {
if (!window_)
return;
if (window_->IsManaged() && (!surface_->committed_buffer() ||
!surface_->committed_buffer()->data())) {
// TODO: How to anounce size?
return;
}
state_ = pending_state_;
window_->PushProperty(state_.geometry, state_.visible_region);
window_->MaybeMakeTopLevel();
}
void ShellSurface::OnSurfaceDestroyed(Surface* surface) {
if (surface == surface_) {
CachedWindowState();
wm::WindowManager::Get()->RemoveWindow(window_);
surface_ = nullptr;
window_ = nullptr;
return;
}
if (cached_window_state_ &&
surface->window() == cached_window_state_->parent_) {
cached_window_state_->parent_ = nullptr;
return;
}
}
void ShellSurface::RecoverWindowState(ShellSurface* other) {
TRACE("this: %p, other: %p", this, other);
if (cached_window_state_) {
if (cached_window_state_->parent_)
cached_window_state_->parent_->AddChild(other->window_);
other->window_->override_border(cached_window_state_->has_border_,
cached_window_state_->has_border_);
other->window_->PushProperty(cached_window_state_->geometry_,
cached_window_state_->geometry_);
other->window_->set_transient(cached_window_state_->is_transient_);
other->window_->set_popup(cached_window_state_->is_popup_);
other->window_->WmSetPosition(cached_window_state_->wm_x_,
cached_window_state_->wm_y_);
}
}
void ShellSurface::CacheWindowState() {
TRACE("window: %p, shell: %p", window_, this);
if (!window_)
return;
cached_window_state_ = std::make_unique<CachedWindowState>();
cached_window_state_->geometry_ = window_->geometry();
cached_window_state_->is_popup_ = window_->is_popup();
cached_window_state_->is_transient_ = window_->is_transient();
cached_window_state_->wm_x_ = window_->wm_x();
cached_window_state_->wm_y_ = window_->wm_y();
// TODO: possibly needs to observe parent destruction.. otherwise, it
// might hit NPE.
cached_window_state_->parent_ = window_->parent();
if (cached_window_state_->parent_)
cached_window_state_->parent_->surface()->AddSurfaceObserver(this);
cached_window_state_->has_border_ = window_->has_border();
cached_window_state_->buffer_scale_ = window_->surface()->buffer_scale();
}
} // namespace naive
| 31.514286 | 75 | 0.696736 | [
"geometry"
] |
6f158045403b50cbf1ca8af37f6755496e29d480 | 27,809 | cpp | C++ | src/sw_interface/BaseControllerROS.cpp | evocortex/evo_rd_platform_example | 3123d9c75b09d11f98311651c1c5f31e488d4519 | [
"MIT"
] | null | null | null | src/sw_interface/BaseControllerROS.cpp | evocortex/evo_rd_platform_example | 3123d9c75b09d11f98311651c1c5f31e488d4519 | [
"MIT"
] | 10 | 2020-01-13T15:19:15.000Z | 2021-04-06T09:17:04.000Z | src/sw_interface/BaseControllerROS.cpp | evocortex/evo_rd_platform_example | 3123d9c75b09d11f98311651c1c5f31e488d4519 | [
"MIT"
] | null | null | null | //###############################################################
//# Copyright (C) 2020, Evocortex GmbH, All rights reserved. #
//# Further regulations can be found in LICENSE file. #
//###############################################################
/**
* @file BaseControllerROS.cpp
* @author evocortex (info@evocortex.com) - MMA, MBA
*
* @brief Base Controller Interface for ROS and EvoRobot com
*
* @version 0.3
* @date 2020-20-24
*
* @copyright Copyright (c) 2020 Evocortex GmbH
*
*/
#include "sw_interface/BaseControllerROS.h"
namespace evo {
BaseControllerROS::BaseControllerROS() :
_logger_prefix("BaseControllerROS: "),
_lift_active(false),
_error_present(false),
_is_initialized(false),
_loop_rate_hz(50)
{
evo::log::init("");
}
bool BaseControllerROS::init()
{
evo::log::get() << _logger_prefix << "start init process!" << evo::info;
bool success = true;
// load all relevant parameters
ros::NodeHandle privateNh("~");
// initial firmware checkup
int fw_major_ver, fw_minor_ver, fw_patch_ver;
privateNh.param("firmware_major_version", fw_major_ver, 1);
privateNh.param("firmware_minor_version", fw_minor_ver, 0);
privateNh.param("firmware_patch_version", fw_patch_ver, 0);
if(!checkMbedLibVersion(fw_major_ver, fw_minor_ver, fw_patch_ver))
{
evo::log::get() << _logger_prefix << "Can't init with mismatching firmware versions!" << evo::error;
return false;
}
// parameters for the motor manager
std::string can_interface_name;
privateNh.param("can_interface_name", can_interface_name, std::string("can-motor"));
if(!_motor_handler.initCanInterface(can_interface_name))
{
evo::log::get() << _logger_prefix
<< "initialization of the CAN interface failed!" << evo::error;
evo::log::get() << _logger_prefix << "Check if the interfacename ["
<< can_interface_name << "] is correct!" << evo::error;
evo::log::get() << _logger_prefix << "--> Exit" << evo::error;
return false;
}
// set desired drive type
std::string kinematic_model;
privateNh.param("kinematic_model", kinematic_model, std::string("mecanum"));
if(kinematic_model == "mecanum")
{
_robot_drive_model = std::make_shared<MecanumDrive>();
}
else if(kinematic_model == "diff4")
{
_robot_drive_model = std::make_shared<Diff4Drive>();
}
else
{
evo::log::get() << _logger_prefix << "Unknown kinematic model '" << kinematic_model << "'" << evo::error;
evo::log::get() << _logger_prefix << "--> Exit" << evo::error;
return false;
}
_motor_handler.setConfig(loadConfigROS(privateNh));
success &= _motor_handler.initFromConfig();
_motor_handler.initMotorMapping(*_robot_drive_model, _lift_controller);
success &= _motor_handler.enableAllMotors();
// parameters for the drive
double wheel_radius_in_m, wheel_distance_front_back_in_m, wheel_distance_left_right_in_m;
privateNh.param("wheel_radius_in_m", wheel_radius_in_m, 0.0);
privateNh.param("wheel_distance_front_back_in_m", wheel_distance_front_back_in_m, 0.0);
privateNh.param("wheel_distance_left_right_in_m", wheel_distance_left_right_in_m, 0.0);
_robot_drive_model->setWheelRadiusInM(wheel_radius_in_m);
_robot_drive_model->setWheelDistanceFrontBackInM(wheel_distance_front_back_in_m);
_robot_drive_model->setWheelDistanceLeftRightInM(wheel_distance_left_right_in_m);
success &= _robot_drive_model->checkInitState();
if(!success)
{
evo::log::get() << _logger_prefix << "init process not successful!"
<< evo::error;
return false;
}
// covariances
privateNh.param("covariance_pos_x", _mecanum_covariance.cov_pos_x, 1.0);
privateNh.param("covariance_pos_y", _mecanum_covariance.cov_pos_y, 1.0);
privateNh.param("covariance_pos_yaw", _mecanum_covariance.cov_pos_yaw, 1.0);
privateNh.param("covariance_vel_x", _mecanum_covariance.cov_vel_x, 1.0);
privateNh.param("covariance_vel_y", _mecanum_covariance.cov_vel_y, 1.0);
privateNh.param("covariance_vel_yaw", _mecanum_covariance.cov_vel_yaw, 1.0);
// debug drives
bool debug_motor_mapping = false;
privateNh.param("debug_motor_mapping", debug_motor_mapping, false);
if(debug_motor_mapping)
_robot_drive_model->debugMotorMapping();
// parameters for this class
std::string topic_sub_cmd_vel, topic_sub_cmd_lift, topic_pub_odom, topic_pub_enable_signal_off, topic_srv_reset_odom;
double com_timeout_s, loop_rate_hz;
privateNh.param("loop_rate_hz", loop_rate_hz, 50.0);
_loop_rate_hz = ros::Rate(loop_rate_hz);
// regular topics
privateNh.param("topic_pub_odom", topic_pub_odom, std::string("odom"));
privateNh.param("topic_pub_enable_signal_off", topic_pub_enable_signal_off, std::string("enable_signal_off"));
privateNh.param("topic_sub_cmd_vel", topic_sub_cmd_vel, std::string("cmd_vel"));
privateNh.param("topic_sub_cmd_lift", topic_sub_cmd_lift, std::string("cmd_lift"));
privateNh.param("topic_srv_reset_odom", topic_srv_reset_odom, std::string("reset_odom"));
// timeouts
privateNh.param("com_timeout_s", com_timeout_s, 0.1);
privateNh.param("cmd_vel_timeout_s", _timeout_cmd_vel, 0.1);
privateNh.param("cmd_lift_timeout_s", _timeout_cmd_lift, 0.5);
// odometry
privateNh.param("enable_odom_tf", _enable_odom_tf, true);
privateNh.param("odom_frame_id", _odom_frame_id, std::string("odom"));
privateNh.param("odom_child_frame_id", _odom_child_frame_id, std::string("base_footprint"));
privateNh.param("enable_lift_control", _enable_lift_control, false);
// toggle joint state publishing
privateNh.param("enable_joint_state_publisher", _enable_joint_state_publisher, false);
if(_enable_joint_state_publisher)
{
int n_joints = 0;
std::string topic_joint_states;
privateNh.param("topic_pub_joint_states", topic_joint_states, std::string("base_joint_states"));
_pub_joint_state = _nh.advertise<sensor_msgs::JointState>(topic_joint_states, 1);
_joint_state_msg.name.push_back("joint_wheel_front_left");
_joint_state_msg.name.push_back("joint_wheel_front_right");
_joint_state_msg.name.push_back("joint_wheel_back_right");
_joint_state_msg.name.push_back("joint_wheel_back_left");
n_joints += 4;
if(_enable_lift_control)
{
// TODO
}
else
{
_joint_state_msg.position.resize(n_joints);
_joint_state_msg.velocity.resize(n_joints);
// MMA FEATURE: get effort from motorcontrollers?
// not implemented atm
//_joint_state_msg.effort.resize(n_joints);
}
}
// setup connections
_srvServ_reset_odom = _nh.advertiseService(topic_srv_reset_odom, &BaseControllerROS::srvResetOdometry, this);
_sub_cmd_vel = _nh.subscribe<geometry_msgs::Twist>(topic_sub_cmd_vel, 1, &BaseControllerROS::cbCmdVel, this);
_pub_odom = _nh.advertise<nav_msgs::Odometry>(topic_pub_odom, 1);
_pub_enable_signal_off = _nh.advertise<std_msgs::Bool>(topic_pub_enable_signal_off, 1);
// enable lift if necessary
if(_enable_lift_control)
{
_sub_cmd_lift = _nh.subscribe<std_msgs::Int8>(topic_sub_cmd_lift, 1, &BaseControllerROS::cbCmdLift, this);
const unsigned int num_lift = _lift_controller.getPositionVec().size();
for(auto idx = 0u; idx < num_lift; idx++)
{
ros::Publisher position_pub = _nh.advertise<std_msgs::Float32>("lift/" + std::to_string(idx) + "/position/", 1);
_pub_lift_pos_vec.push_back(position_pub);
}
}
// finish flag
evo::log::get() << _logger_prefix << "finished init process!" << evo::info;
_is_initialized = true;
return true;
}
std::vector<MotorShieldConfig> BaseControllerROS::loadConfigROS(ros::NodeHandle& privateNh)
{
std::vector<MotorShieldConfig> mc_config_ros;
std::string paramName, paramPrefix;
int motorshield_id = 1;
static const int n_motors = 2;
std::map<std::string, double> param_map;
int init_n_shields = 0;
privateNh.param("init_n_motorshields", init_n_shields, 2);
evo::log::get() << _logger_prefix << "Loading config for "
<< init_n_shields << " motorshields" <<
evo::info;
// check if the next motorshield exists
paramPrefix = "ms" + std::to_string(motorshield_id);
while(privateNh.hasParam(paramPrefix + "/enable"))
{
// error prevention
if(motorshield_id > init_n_shields)
{
evo::log::get() << _logger_prefix
<< "param server contains enable for next ms-id"
<< ", but n-ms > init-n-ms! (" << motorshield_id << " > "
<< init_n_shields << ")" << evo::warn;
evo::log::get() << _logger_prefix
<< "do you want to include the next shield? (y/n)" << evo::warn;
char input;
std::cin >> input;
try
{
if(std::tolower(input) != 'y')
{
evo::log::get() << _logger_prefix << "--> NO" << evo::info;
break;
}
evo::log::get() << _logger_prefix << "--> YES" << evo::info;
}
catch(const std::exception& e)
{
evo::log::get() << e.what() << evo::error;
}
}
bool enable_mc = false;
privateNh.getParam(paramPrefix + "/enable", enable_mc);
evo::log::get() << _logger_prefix << "Enable ms" << motorshield_id << ": "
<< enable_mc << evo::info;
if(enable_mc)
{
evo::log::get() << _logger_prefix << "--------------------------"
<< evo::info;
evo::log::get() << _logger_prefix << "Loading parameters for ms"
<< motorshield_id << evo::info;
// load mc param
MotorShieldConfig ms_config;
ms_config.id = motorshield_id;
int timeout_ms = 10;
if(!privateNh.getParam(paramPrefix + "/timeout_ms", timeout_ms))
{
timeout_ms = 10;
evo::log::get() << _logger_prefix
<< "no timeout_ms parameter given! using default: "
<< ms_config.timeout_ms << evo::warn;
}
ms_config.timeout_ms = static_cast<uint32_t>(timeout_ms);
// could also be loaded as param
ms_config.n_motors = n_motors;
// load params for two motors
ms_config.motor_configs.clear();
for(int motor_id = 0; motor_id < ms_config.n_motors; motor_id++)
{
evo::log::get() << _logger_prefix << "Loading parameters for motor"
<< motor_id << evo::info;
// search for these params
param_map["type"] = 0.0;
param_map["ctrl_mode"] = 0.0;
param_map["kp"] = 0.0;
param_map["ki"] = 0.0;
param_map["kd"] = 0.0;
param_map["pwm_limit"] = 0.0;
param_map["rpm_limit"] = 0.0;
param_map["gear_ratio"] = 0.0;
param_map["encoder_res"] = 0.0;
param_map["adc_conv"] = 0.0;
param_map["adc_offs"] = 0.0;
param_map["motor_mapping"] = 0.0;
for(auto& param : param_map)
{
paramName = paramPrefix + "/motor" + std::to_string(motor_id) + "/" +
param.first;
if(privateNh.hasParam(paramName))
{
privateNh.getParam(paramName, param.second);
evo::log::get()
<< _logger_prefix << "received Param: " << param.first << " = "
<< param.second << evo::info;
}
else
{
evo::log::get()
<< _logger_prefix
<< "failed to retrieve param with name: " << paramName
<< evo::warn;
evo::log::get() << _logger_prefix << "using val: " << param.second
<< evo::warn;
}
}
MotorConfig motor_config;
motor_config.type =
static_cast<evo_mbed::MotorType>(param_map.at("type"));
motor_config.mode =
static_cast<evo_mbed::MotorControlMode>(param_map.at("ctrl_mode"));
motor_config.kp = param_map.at("kp");
motor_config.ki = param_map.at("ki");
motor_config.kd = param_map.at("kd");
motor_config.encoder_res = param_map.at("encoder_res");
motor_config.gear_ratio = param_map.at("gear_ratio");
motor_config.pwm_limit = param_map.at("pwm_limit");
motor_config.rpm_limit = param_map.at("rpm_limit");
motor_config.adc_conv_mm_per_tick = param_map.at("adc_conv");
motor_config.adc_offs_mm = param_map.at("adc_offs");
motor_config.motor_mapping =
static_cast<uint8_t>(param_map.at("motor_mapping"));
ms_config.motor_configs.push_back(motor_config);
}
mc_config_ros.push_back(ms_config);
}
++motorshield_id;
paramPrefix = "ms" + std::to_string(motorshield_id);
}
return mc_config_ros;
}
void BaseControllerROS::publishOdomMsg(const Vel2d& odom_vel,
const Pose2d& odom_pose)
{
// create odom nav msg
nav_msgs::Odometry odom;
// header
odom.header.stamp = ros::Time::now();
odom.header.frame_id = _odom_frame_id;
odom.child_frame_id = _odom_child_frame_id;
// pose
odom.pose.pose.position.x = odom_pose._x_m;
odom.pose.pose.position.y = odom_pose._y_m;
// MMA ERROR: should we really use this function?
// MMA FEATURE: if we extend the functionality to lift and tilting, we have to
// change this anyways
tf::Quaternion pose_quaterion = tf::createQuaternionFromYaw(odom_pose._yaw_rad);
odom.pose.pose.orientation.w = pose_quaterion.getW();
odom.pose.pose.orientation.y = pose_quaterion.getY();
odom.pose.pose.orientation.z = pose_quaterion.getZ();
odom.pose.pose.orientation.x = pose_quaterion.getX();
// twist
odom.twist.twist.linear.x = odom_vel._x_ms;
odom.twist.twist.linear.y = odom_vel._y_ms;
odom.twist.twist.angular.z = odom_vel._yaw_rads;
// covariances
const double cpx = _mecanum_covariance.cov_pos_x;
const double cpy = _mecanum_covariance.cov_pos_y;
const double cpyaw = _mecanum_covariance.cov_pos_yaw;
const double cvx = _mecanum_covariance.cov_vel_x;
const double cvy = _mecanum_covariance.cov_vel_y;
const double cvyaw = _mecanum_covariance.cov_vel_yaw;
odom.twist.covariance = {cpx, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, cpy, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, cpyaw, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, cvx, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, cvy, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, cvyaw};
odom.pose.covariance = odom.twist.covariance;
_pub_odom.publish(odom);
}
void BaseControllerROS::publishOdomTF(const Pose2d& odom_pose)
{
tf::StampedTransform tf_odom;
// header
tf_odom.stamp_ = ros::Time::now();
tf_odom.frame_id_ = _odom_frame_id;
tf_odom.child_frame_id_ = _odom_child_frame_id;
// position
tf_odom.setOrigin(tf::Vector3(_odom_pose._x_m, _odom_pose._y_m, 0));
// rotation
tf::Quaternion pose_quaterion = tf::createQuaternionFromYaw(_odom_pose._yaw_rad);
tf_odom.setRotation(pose_quaterion);
// try to prevent false quaternions (may happen with faulty encoder values)
if(pose_quaterion.dot(pose_quaterion) == 0)
{
evo::log::get() << _logger_prefix << "Detected faulty odometry!" << evo::error;
resetOdometry();
return;
}
_tf_pub_odom.sendTransform(tf_odom);
}
void BaseControllerROS::publishJointStates(const WheelData& wheel_positions,
const WheelData& wheel_rotations)
{
_joint_state_msg.position[0] = wheel_positions.front_left;
_joint_state_msg.position[1] = wheel_positions.front_right;
_joint_state_msg.position[2] = wheel_positions.back_right;
_joint_state_msg.position[3] = wheel_positions.back_left;
_joint_state_msg.velocity[0] = wheel_rotations.front_left;
_joint_state_msg.velocity[1] = wheel_rotations.front_right;
_joint_state_msg.velocity[2] = wheel_rotations.back_right;
_joint_state_msg.velocity[3] = wheel_rotations.back_left;
if(_enable_lift_control)
{
// TODO
}
_joint_state_msg.header.stamp = ros::Time::now();
_pub_joint_state.publish(_joint_state_msg);
}
void BaseControllerROS::publishBaseStatus()
{
// get drive data
Vel2d odom_vel;
Pose2d odom_pose_increment;
WheelData wheel_positions;
WheelData wheel_velocities;
_robot_drive_model->getOdomComplete(odom_vel, odom_pose_increment,
wheel_positions, wheel_velocities);
// update pose
_odom_pose.updatePoseFromIncrement(odom_pose_increment);
publishOdomMsg(odom_vel, _odom_pose);
// eventually publish odom TF
if(_enable_odom_tf)
{publishOdomTF(_odom_pose);}
// eventually publish joint states
if(_enable_joint_state_publisher)
{
publishJointStates(wheel_positions, wheel_velocities);
}
// TODO: lift?
}
void BaseControllerROS::publishLiftPos()
{
const std::vector<float> positions = _lift_controller.getPositionVec();
unsigned int idx = 0u;
for(auto& pos : positions)
{
std_msgs::Float32 data;
data.data = pos;
_pub_lift_pos_vec[idx++].publish(data);
}
std::cout << std::endl;
}
void BaseControllerROS::cbCmdVel(const geometry_msgs::Twist::ConstPtr& cmd_vel)
{
_stamp_cmd_vel = ros::Time::now();
_cmd_vel._x_ms = cmd_vel->linear.x;
_cmd_vel._y_ms = cmd_vel->linear.y;
_cmd_vel._yaw_rads = cmd_vel->angular.z;
}
bool BaseControllerROS::resetOdometry()
{
evo::log::get() << _logger_prefix << "Resetting Odometry.." << evo::info;
// stop and disable motors to prevent reset mid drive
_robot_drive_model->setCmdVel(Vel2d());
_motor_handler.disableAllDriveMotors();
if(!_robot_drive_model->resetEncoders())
{
evo::log::get() << _logger_prefix << "Couldn't reset encoders!" << evo::error;
return false;
}
_motor_handler.enableAllDriveMotors();
_odom_pose.reset();
return true;
}
bool BaseControllerROS::srvResetOdometry(evo_rd_platform_example::resetOdomRequest& req,
evo_rd_platform_example::resetOdomResponse& res)
{
return resetOdometry();
}
void BaseControllerROS::cbCmdLift(const std_msgs::Int8::ConstPtr& cmd_lift)
{
_stamp_cmd_lift = ros::Time::now();
_cmd_lift = cmd_lift->data;
}
bool BaseControllerROS::checkMbedLibVersion(const int major_ver, const int minor_ver, const int patch_ver)
{
bool success = true;
if(EVO_MBED_TOOLS_VER_MAJOR != major_ver)
{
evo::log::get() << _logger_prefix << "Major Version mismatch! Expected ["
<< major_ver << "] but evo_mbed is [" << EVO_MBED_TOOLS_VER_MAJOR << "]!" << evo::error;
success &= false;
}
// should be backwards compatible
if(EVO_MBED_TOOLS_VER_MINOR < minor_ver)
{
evo::log::get() << _logger_prefix << "Detected Minor Version mismatch! Expected ["
<< minor_ver << "] but evo_mbed is [" << EVO_MBED_TOOLS_VER_MINOR << "]!" << evo::warn;
success &= false;
}
// patch is not critical, so dont end here
if(EVO_MBED_TOOLS_VER_PATCH < patch_ver)
{
evo::log::get() << _logger_prefix << "Detected Patch Version mismatch! Expected at least ["
<< patch_ver << "] but evo_mbed is [" << EVO_MBED_TOOLS_VER_MINOR << "]!" << evo::warn;
}
if(!success)
{
evo::log::get() << _logger_prefix << "Your ROS Node Version expects the evo_mbed firmware to be at version ["
<< major_ver << "." << minor_ver << "." << patch_ver << "]," << evo::warn;
evo::log::get() << _logger_prefix << "But the installed version is " << EVO_MBED_TOOLS_VER << evo::warn;
evo::log::get() << _logger_prefix << "Please update the evo_mbed firmware or downgrade the ROS Node (not recommended)" << evo::warn;
}
return success;
}
void BaseControllerROS::checkAndApplyCmdVel()
{
static ros::Time throttle_timestamp = ros::Time::now();
// check timestamp
if(ros::Time::now().toSec() > (_stamp_cmd_vel.toSec() + _timeout_cmd_vel))
{
if(ros::Time::now().toSec() > (throttle_timestamp.toSec() + ros::Duration(1.0).toSec()))
{
evo::log::get() << _logger_prefix << "cmd vel timeout detected! stopping robot.." << evo::warn;
throttle_timestamp = ros::Time::now();
}
const Vel2d zero_vel;
_cmd_vel = zero_vel;
}
// only set cmd_vel if lift is not active
if(!_lift_active || !_enable_lift_control)
{
_robot_drive_model->setCmdVel(_cmd_vel);
}
else
{
evo::log::get() << _logger_prefix << "lift active! can't set cmd vel!" << evo::warn;
}
}
void BaseControllerROS::checkAndApplyCmdLift()
{
/* REV
* +++ 1. What does "_strd" mean? Why not "_old" or something similar? -> @TODO @MBA stored
* INFO: +++ 2. Why try exactly 2 times to reenable the drive motors?
* +++ 3. Why is there no error message after the second attempt,
* considering that there will be no next attempt without another edge? (checkStatus() will reenable them?)
* -> @TODO @MBA
* MBA: Changed complete code structure
*/
// check timestamp
if(ros::Time::now().toSec() > (_stamp_cmd_lift.toSec() + _timeout_cmd_lift))
{
evo::log::get() << _logger_prefix
<< "cmd lift timeout detected! stopping lift mechanism.."
<< evo::warn;
// Stop lift movement
_cmd_lift = 0;
}
const bool lift_movement_req = (_cmd_lift != 0);
const bool drive_movement_req = (_cmd_vel._x_ms != 0.0 ||
_cmd_vel._y_ms != 0.0 ||
_cmd_vel._yaw_rads != 0.0);
// State transition: Lift inactive to lift active
if(!_lift_active && lift_movement_req)
{
evo::log::get() << _logger_prefix
<< "disable drives | enable lift"
<< evo::info;
// Try to disable all drive motors to avoid blockage of lift mechanism
// Stopp movement
const Vel2d zero_vel;
_robot_drive_model->setCmdVel(zero_vel);
// Disable all drives motors to avoid blockage of the lift mechanism
if(_motor_handler.disableAllDriveMotors())
{
// Lift is now active
_lift_active = true;
}
else
{
// Disabling of drive motors failed
// Lift is not active
_lift_active = false;
}
}
// State transition: Lift active to lift inactive
// To avoid disabling the lift to fast check for a drive movement
// request
else if(_lift_active && !lift_movement_req && drive_movement_req)
{
evo::log::get() << _logger_prefix
<< "enable drives | disable lift"
<< evo::info;
// Stop lift movement
_lift_controller.setMovingDirection(0);
// Reenable drive motors
if(_motor_handler.enableAllDriveMotors())
{
// Lift movement is disabled
_lift_active = false;
}
else
{
// Failed to enable drive motors
// Lift mechanism is still active
_lift_active = true;
}
}
// Lift mechanism is active
else if(_lift_active)
{
_lift_controller.setMovingDirection(_cmd_lift);
}
// Unknown state -> disable lift movement
else
{
_lift_controller.setMovingDirection(0);
}
}
const bool BaseControllerROS::checkStatus()
{
/* REV
* WHA STYLE: +++ It is not quite clear whether disabling all motors sets the handler to a valid status,
* therefore leading to the else branch. -> TODO MBA clean up code
* INFO: +++ As we only detect an error and create the edge ourselves by toggling the bool,
* I personally wouldn't quite call this edge detection. -> See below
* MPP INFO: +++ Expression "falling edge detection" makes no sense. -> TODO MBA: better name instead of "falling edge detection"
* MBA: Changed complete code structure
*/
// Check drive status
const bool motor_status = _motor_handler.checkStatus();
// State transition: Error to no error
if(motor_status && _error_present)
{
// Try to enable all motors
if(_motor_handler.enableAllMotors())
{
// Error healed
_error_present = false;
}
else
{
// Not able to re-enable drives
// error still present
_error_present = true;
}
}
// State transition: No error to error
else if(!motor_status && !_error_present)
{
// Try to disable all motors
if(_motor_handler.disableAllMotors())
{
// Error active
_error_present = true;
}
else
{
// Unable to disable all drives
// Error is present but not active
_error_present = false;
}
}
if(_error_present)
{
evo::log::get()
<< _logger_prefix
<< " motorshield communication error! -> Missing enable signal?"
<< evo::warn;
// Stop all movement
_lift_active = false;
_lift_controller.setMovingDirection(0);
// Reset command velocity
const Vel2d zero_vel;
_robot_drive_model->setCmdVel(zero_vel);
}
std_msgs::Bool enable_signal_off;
enable_signal_off.data = _error_present;
_pub_enable_signal_off.publish(enable_signal_off);
return !_error_present;
}
void BaseControllerROS::main_loop()
{
if(!_is_initialized)
{
evo::log::get() << _logger_prefix << "Node is not initialized!" << evo::error;
evo::log::get() << _logger_prefix << "Possible Solutions:" << evo::error;
evo::log::get() << _logger_prefix << "[1] Restart node and check if init is successful" << evo::error;
evo::log::get() << _logger_prefix << "[2] Check if the Motorshields are powered" << evo::error;
evo::log::get() << _logger_prefix << "[3] Check if the CAN Interface is initialized" << evo::error;
evo::log::get() << _logger_prefix << "[4] Check if all parameters are set correctly" << evo::error;
evo::log::get() << _logger_prefix << "[5] Check if some motor connections are broken" << evo::error;
evo::log::get() << _logger_prefix << "[6] Update firmware if versions mismatch" << evo::error;
return;
}
else
{
evo::log::get() << _logger_prefix << "starting main control loop.."
<< evo::info;
_motor_handler.enableAllMotors();
while(ros::ok())
{
ros::spinOnce();
publishBaseStatus();
if(_enable_lift_control)
{publishLiftPos();}
if(checkStatus())
{
checkAndApplyCmdVel();
if(_enable_lift_control)
{checkAndApplyCmdLift();}
}
_loop_rate_hz.sleep();
}
}
}
} // namespace evo
| 35.561381 | 138 | 0.616959 | [
"vector",
"model"
] |
6f19dea53b269bee33fa5007fef421842a2e6de5 | 2,500 | cpp | C++ | Projects/Library/InstanceMap.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | 1 | 2018-06-16T17:53:43.000Z | 2018-06-16T17:53:43.000Z | Projects/Library/InstanceMap.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | null | null | null | Projects/Library/InstanceMap.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | null | null | null |
#include "KAI/KAI.h"
#include "KAI/InstanceMap.h"
KAI_BEGIN
InstanceMapInfinite::InstanceMapInfinite(int num_buckets) : buckets(num_buckets)
{
}
void InstanceMapInfinite::SetNumBuckets(int num_buckets)
{
throw;
}
void InstanceMapInfinite::insert(value_type const &value)
{
if (!value.second)
return;
Bucket &bucket = GetBucket(value.first);
bucket.push_back(value);
}
bool InstanceMapInfinite::Contains(Handle const &handle) const
{
return find(handle) != end();
}
InstanceMapInfinite::Bucket &InstanceMapInfinite::GetBucket(Handle const &handle)
{
return buckets[handle.GetValue() % buckets.size()];
}
InstanceMapInfinite::Bucket const &InstanceMapInfinite::GetBucket(Handle const &handle) const
{
return buckets.at(handle.GetValue() % buckets.size());
}
InstanceMapInfinite::const_iterator InstanceMapInfinite::find(Handle const &handle) const
{
Bucket const &bucket = GetBucket(handle);
Bucket::const_iterator object = bucket.begin(), end = bucket.end();
for (; object != end; ++object)
{
if (object->first == handle)
return const_iterator();
}
return this->end();
}
void InstanceMapInfinite::erase(const_iterator const &iter)
{
}
//-------------------------------------------------------------------------
InstanceMapFinite::InstanceMapFinite(int num_buckets) : instances(num_buckets)
{
clear();
}
InstanceMapFinite::const_iterator InstanceMapFinite::begin() const
{
return instances.begin();
}
InstanceMapFinite::const_iterator InstanceMapFinite::end() const
{
return instances.end();
}
void InstanceMapFinite::clear()
{
nstd::fill(instances.begin(), instances.end(), value_type(0, 0));
}
bool InstanceMapFinite::empty() const
{
throw;
}
void InstanceMapFinite::insert(value_type const &value)
{
StorageBase *&ptr = instances[value.first.GetValue()];
if (ptr != 0)
KAI_THROW_0(ObjectExists);
ptr = value.second;
}
InstanceMapFinite::const_iterator InstanceMapFinite::find(key_type const &key) const
{
return instances[key.GetValue()];
}
void InstanceMapFinite::erase(key_type const &key)
{
int num = key.GetValue();
if (num >= (int)instances.size())
KAI_THROW_0(InstancesExhausted);
instances[num] = 0;
}
void InstanceMapFinite::erase(iterator const &iter)
{
*iter = 0;
}
void InstanceMapFinite::SetNumBuckets(int)
{
throw;
}
bool InstanceMapFinite::Contains(key_type const &key) const
{
int num = key.GetValue();
if (num >= (int)instances.size())
KAI_THROW_0(InstancesExhausted);
return instances[num] != 0;
}
KAI_END
//EOF
| 19.685039 | 93 | 0.716 | [
"object"
] |
6f1a7b191d06402cdc71f94acfe8537fe7ec41f9 | 7,629 | cpp | C++ | src/SharedSurfpackApproxData.cpp | jnnccc/Dakota-orb | 96488e723be9c67f0f85be8162b7af52c312b770 | [
"MIT"
] | null | null | null | src/SharedSurfpackApproxData.cpp | jnnccc/Dakota-orb | 96488e723be9c67f0f85be8162b7af52c312b770 | [
"MIT"
] | null | null | null | src/SharedSurfpackApproxData.cpp | jnnccc/Dakota-orb | 96488e723be9c67f0f85be8162b7af52c312b770 | [
"MIT"
] | null | null | null | /* _______________________________________________________________________
DAKOTA: Design Analysis Kit for Optimization and Terascale Applications
Copyright 2014 Sandia Corporation.
This software is distributed under the GNU Lesser General Public License.
For more information, see the README file in the top Dakota directory.
_______________________________________________________________________ */
//- Class: SharedSurfpackApproxData
//- Description: Class implementation of Surfpack response surface
//-
//- Owner: Brian Adams
#include <stdexcept>
#include <typeinfo>
#include "SharedSurfpackApproxData.hpp"
#include "ProblemDescDB.hpp"
#include "DakotaVariables.hpp"
#include "SurrogateData.hpp"
#include "dakota_data_io.hpp"
// Headers from Surfpack
#include "SurfData.h"
#include "SurfpackMatrix.h"
#include <algorithm>
#include <boost/math/special_functions/round.hpp>
namespace Dakota {
/** Initialize the embedded Surfpack surface object and configure it
using the specifications from the input file. Data for the
surface is created later. */
SharedSurfpackApproxData::
SharedSurfpackApproxData(ProblemDescDB& problem_db, size_t num_vars):
SharedApproxData(BaseConstructor(), problem_db, num_vars),
diagnosticSet(problem_db.get_sa("model.metrics")),
crossValidateFlag(problem_db.get_bool("model.surrogate.cross_validate")),
numFolds(problem_db.get_int("model.surrogate.folds")),
percentFold(problem_db.get_real("model.surrogate.percent")),
pressFlag(problem_db.get_bool("model.surrogate.press"))
{
// For Polynomial surface fits
if (approxType == "global_polynomial")
approxOrder = problem_db.get_short("model.surrogate.polynomial_order");
else if (approxType == "global_kriging") {
const String& trend_string =
problem_db.get_string("model.surrogate.trend_order");
if (trend_string == "constant") approxOrder = 0;
else if (trend_string == "linear") approxOrder = 1;
else approxOrder = 2; // empty, reduced_quadratic, quadratic
}
}
/// On-the-fly constructor which uses mostly Surfpack model defaults
SharedSurfpackApproxData::
SharedSurfpackApproxData(const String& approx_type,
const UShortArray& approx_order, size_t num_vars,
short data_order, short output_level):
SharedApproxData(NoDBBaseConstructor(), approx_type, num_vars, data_order,
output_level),
crossValidateFlag(false), numFolds(0), percentFold(0.0), pressFlag(false)
{
approxType = approx_type;
if (approx_order.empty())
approxOrder = 2;
else {
approxOrder = approx_order[0];
if (approx_order.size() != num_vars) {
Cerr << "Error: bad size of " << approx_order.size()
<< " for approx_order in SharedSurfpackApproxData lightweight "
<< "constructor. Expected " << num_vars << "." << std::endl;
abort_handler(-1);
}
for (size_t i=1; i<num_vars; ++i)
if (approx_order[i] != approxOrder) {
Cerr << "Warning: SharedSurfpackApproxData lightweight constructor "
<< "requires homogeneous approximation order. Promoting to max "
<< "value." << std::endl;
approxOrder = std::max(approx_order[i], approxOrder);
}
}
}
void SharedSurfpackApproxData::
merge_variable_arrays(const RealVector& cv, const IntVector& div,
const RealVector& drv, RealArray& ra)
{
size_t num_cv = cv.length(), num_div = div.length(), num_drv = drv.length(),
num_v = num_cv + num_div + num_drv;
ra.resize(num_v);
if (num_cv) copy_data_partial(cv, ra, 0);
if (num_div) merge_data_partial(div, ra, num_cv);
if (num_drv) copy_data_partial(drv, ra, num_cv+num_div);
}
void SharedSurfpackApproxData::
sdv_to_realarray(const Pecos::SurrogateDataVars& sdv, RealArray& ra)
{
// check incoming vars for correct length (active or all views)
const RealVector& cv = sdv.continuous_variables();
const IntVector& div = sdv.discrete_int_variables();
const RealVector& drv = sdv.discrete_real_variables();
if (cv.length() + div.length() + drv.length() == numVars)
merge_variable_arrays(cv, div, drv, ra);
else {
Cerr << "Error: bad parameter set length in SharedSurfpackApproxData::"
<< "sdv_to_realarray(): " << numVars << " != " << cv.length() << " + "
<< div.length() << " + " << drv.length() << "." << std::endl;
abort_handler(-1);
}
}
void SharedSurfpackApproxData::
vars_to_realarray(const Variables& vars, RealArray& ra)
{
// check incoming vars for correct length (active or all views)
if (vars.cv() + vars.div() + vars.drv() == numVars)
merge_variable_arrays(vars.continuous_variables(),
vars.discrete_int_variables(),
vars.discrete_real_variables(), ra);
else if (vars.acv() + vars.adiv() + vars.adrv() == numVars)
merge_variable_arrays(vars.all_continuous_variables(),
vars.all_discrete_int_variables(),
vars.all_discrete_real_variables(), ra);
else {
Cerr << "Error: bad parameter set length in SharedSurfpackApproxData::"
<< "vars_to_realarray()." << std::endl;
abort_handler(-1);
}
}
void SharedSurfpackApproxData::
add_sd_to_surfdata(const Pecos::SurrogateDataVars& sdv,
const Pecos::SurrogateDataResp& sdr, short fail_code,
SurfData& surf_data)
{
// coarse-grained fault tolerance for now: any failure qualifies for omission
if (fail_code)
return;
// Surfpack's RealArray is std::vector<double>; use DAKOTA copy_data helpers.
// For DAKOTA's compact mode, any active discrete {int,real} variables could
// be contained within SDV's continuousVars (see Approximation::add(Real*)),
// although it depends on eval cache lookups as shown in
// ApproximationInterface::update_approximation().
RealArray x;
sdv_to_realarray(sdv, x);
Real f = sdr.response_function();
// for now only allow builds from exactly 1, 3=1+2, or 7=1+2+4; use
// different set functions so the SurfPoint data remains empty if
// not present
switch (buildDataOrder) {
case 1:
surf_data.addPoint(SurfPoint(x, f));
break;
case 3: {
RealArray gradient;
copy_data(sdr.response_gradient(), gradient);
surf_data.addPoint(SurfPoint(x, f, gradient));
break;
}
case 7: {
RealArray gradient;
copy_data(sdr.response_gradient(), gradient);
SurfpackMatrix<Real> hessian;
copy_matrix(sdr.response_hessian(), hessian);
surf_data.addPoint(SurfPoint(x, f, gradient, hessian));
break;
}
default:
Cerr << "\nError (SharedSurfpackApproxData): derivative data may only be "
<< "used if all\nlower-order information is also present. Specified "
<< "buildDataOrder is " << buildDataOrder << "." << std::endl;
abort_handler(-1);
break;
}
}
void SharedSurfpackApproxData::
copy_matrix(const RealSymMatrix& rsm, SurfpackMatrix<Real>& surfpack_matrix)
{
// SymmetricMatrix = symmetric and square, but Dakota::Matrix can be general
// (e.g., functionGradients = numFns x numVars). Therefore, have to verify
// sanity of the copy. Could copy square submatrix of rsm into sm, but
// aborting with an error seems better since this should only currently be
// used for copying Hessian matrices.
size_t nr = rsm.numRows(), nc = rsm.numCols();
if (nr != nc) {
Cerr << "Error: copy_data(const Dakota::RealSymMatrix& rsm, "
<< "SurfpackMatrix<Real>& sm) called with nonsquare rsm." << std::endl;
abort_handler(-1);
}
if (surfpack_matrix.getNRows() != nr | surfpack_matrix.getNCols() != nc)
surfpack_matrix.resize(nr, nc);
for (size_t i=0; i<nr; ++i)
for (size_t j=0; j<nc; ++j)
surfpack_matrix(i,j) = rsm(i,j);
}
} // namespace Dakota
| 35.156682 | 79 | 0.707956 | [
"object",
"vector",
"model"
] |
6f2282edf5b49b3bf14dd70c5018101f94d56e45 | 70,353 | cpp | C++ | ccm/src/AppSvr/ContainerRunTime.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | 2 | 2020-01-06T07:43:30.000Z | 2020-07-11T20:53:53.000Z | ccm/src/AppSvr/ContainerRunTime.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | null | null | null | ccm/src/AppSvr/ContainerRunTime.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | null | null | null | // **********************************************************************
//
// Copyright (c) 2001-2004
// StarMiddleware.net
// www.StarMiddleware.net
//
// All Rights Reserved
//
// Author: Wang Kebo mep@263.net
// Author: Huang Jie huangjie@email.com
// Author: Su Liang centuryfree@yahoo.com.cn
//
// **********************************************************************
// Version: 1.0.0
#include <ContainerRunTime.h>
#include <ContainerBase.h>
#include <UuidGenerator.h>
#include <ExecutorInvoker.h>
#include <string>
#include <FileAccessor.h>
#include <DeployDomainMgr.h>
#ifdef WIN32
#include <conio.h>
#include <time.h>
#else
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <ConfigFile.h>
#include <CCM2Context_impl.h>
#include <UuidGenerator.h>
//added by xiao heping 2004/03/04
//end add
#include <Cookie.h> //added by xiao heping
#include <stdlib.h>
#ifndef LITE_VERSION
#include <CosPersistentState.h>
#endif
extern "C"
{
#include "uuid.h"
}
#include <CommonFunc.h>
using namespace Container;
ContainerRunTime::ContainerRunTime(/*const char *homeRepId,
Components::HomeExecutorBase_ptr home,
PortableServer::POA_ptr homePoa,
PortableServer::POA_ptr componentPoa*/)
{
// homeRepId_ = CORBA::string_dup(homeRepId);
// homePoa_ = PortableServer::POA::_duplicate(homePoa);
// componentPoa_ = PortableServer::POA::_duplicate(componentPoa);
// home_ = Components::HomeExecutorBase::_duplicate(home);
runningComponentsPool_ = new ComponentsPool();
Components::UuidGenerator_var gen = new Components::UuidGenerator();
homeCompositionUUID_ = gen -> generateUuid();
passivator_ = new PassivationArbitor();
passivator_->setPassivatePolicy(COMPONENTCOUNT);
passivator_->setComponentCount(100);
resPool_ = NULL;
//added by xiao heping 2004/03/24
destroy_ = false;
}
ContainerRunTime::~ContainerRunTime()
{
TRACE0(LEVEL6,"ContainerRunTime::~ContainerRunTime()!\n");
executorInvoker_ -> _remove_ref();
homeExecutorInvoker_ -> _remove_ref();
}
//void
//ContainerRunTime::setCompRepId(const char *compRepId)
//{
// compRepId_ = CORBA::string_dup(compRepId);
//}
char*
ContainerRunTime::getCompRepId()
{
return CORBA::string_dup(compRepId_);
}
Components::HomeExecutorBase_ptr
ContainerRunTime::getHomeExecutor()
{
return homeComposition_ -> getHomeExecutor();
}
//void
//ContainerRunTime::setHomeExecutor(Components::HomeExecutorBase_ptr home)
//{
// homeComposition_ -> registerHomeExecutor(home);
//}
//Components::EnterpriseComponent_ptr
//ContainerRunTime::getExecutor()
//{
// return NULL;
//}
char*
ContainerRunTime::getHomeRepId()
{
return CORBA::string_dup(homeRepId_);
}
//void
//ContainerRunTime::setHomeRepId(const char *homeRepId)
//{
// homeRepId_ = CORBA::string_dup(homeRepId);
//}
PortableServer::POA_ptr
ContainerRunTime::getHomePoa()
{
return PortableServer::POA::_duplicate(homePoa_);
}
PortableServer::POA_ptr
ContainerRunTime::getComponentPoa()
{
return PortableServer::POA::_duplicate(componentPoa_);
}
//deleted by xiao heping 2004/03/18
/*
CORBA::Object_ptr
ContainerRunTime::getExecutor(PortableServer::ObjectId* oid)
{
// Guard<FastRecursiveMutex> guard(lock_);
CORBA::Object_var executor;
CORBA::String_var s = PortableServer::ObjectId_to_string(*oid);
std::string id(s.in());
PortableServer::ObjectId_var hId = homeComposition_ -> getObjectId();
CORBA::String_var homeId = PortableServer::ObjectId_to_string(hId);
std::string homeOid(homeId.in());
if( strcmp(id.c_str(),homeOid.c_str()) == 0 )
{
return homeComposition_ -> getHomeExecutor();
}
executor = runningComponentsPool_->getExecutor(oid);
return executor._retn();
}
*/
//end delete xiao heping 2004/03/18
PortableServer::Servant
ContainerRunTime::getServant(PortableServer::ObjectId* oid,
PortableServer::ServantLocator::Cookie& the_cookie,
const char* operation)
{
//modified by xiao heping 2004/03/23
CORBA::String_var id = PortableServer::ObjectId_to_string(*oid);
// std::string id(s.in());
PortableServer::ObjectId_var hId = homeComposition_ -> getObjectId();
CORBA::String_var homeOid = PortableServer::ObjectId_to_string(hId);
// std::string homeOid(homeId.in());
// if( strcmp(id.c_str(),homeOid.c_str()) == 0 )
//end modify xiao heping 2004/03/23
if( strcmp(id.in(),homeOid.in()) == 0 )
{
TRACE0(LEVEL6,"Home servant found\n");
//added by xiao heping 2004/03/25
if(destroy_)
return 0;
// the_cookie = (void*)dynamic_cast<CompositionManager*>(homeComposition_.in());
::Container::Cookie* cookie = new ::Container::Cookie(homeComposition_.in());
the_cookie = (void*)cookie;
homeComposition_ -> _add_ref();
//end add xiao heping 2004/03/25
return homeComposition_ -> getHomeServant();
}
return runningComponentsPool_ -> getServant(oid,the_cookie,operation);
}
PortableServer::Servant
ContainerRunTime::getComponentServant(PortableServer::ObjectId* oid)
{
ComponentComposition_var componentComposition = runningComponentsPool_->getComposition(oid);
if( componentComposition.in() == NULL )
{
TRACE0(LEVEL3,"Component Composition not found\n");
return NULL;
}
return componentComposition->getComponentServant();
}
int
ContainerRunTime::getCompositionType(PortableServer::ObjectId* oid)
{
//modified by xiao heping 2004/03/23
CORBA::String_var id = PortableServer::ObjectId_to_string(*oid);
// std::string id(s.in());
PortableServer::ObjectId_var hId = homeComposition_ -> getObjectId();
CORBA::String_var homeOid = PortableServer::ObjectId_to_string(hId);
// std::string homeOid(homeId.in());
// if( strcmp(id.c_str(),homeOid.c_str()) == 0 )
//end modify xiao heping 2004/03/23
if( strcmp(id.in(),homeOid.in()) == 0 )
{
return HOME;
}
return COMPONENT;
}
void
ContainerRunTime::passivate()
{
#ifndef LITE_VERSION
//get the connector.
CosPersistentState::Session_var _session = storageLoader_ -> getSession();
// CORBA::String_var _connectorId= pssInitializer_->getConnectorId();
// CosPersistentState::Connector_var _connector = _connectorReg -> find_connector(_connectorId.in());
//
// if(!CORBA::is_nil(_connector))
// {
// TRACE0(LEVEL1,"ContainerRunTime::passivate() cannot find the connector!");
// }
//
// //get the session.
// short _mode = pssInitializer_ -> getAccessMode();
// CosPersistentState::ParameterList_var _paraList = pssInitializer_ -> getParaeters();
// CosPersistentState::Session_var _session = _connector -> create_basic_session(_mode,_paraList);
//
// //register_persistent_factories().RunTime_pss.cpp.
// register_persistent_factories(_connector);
//get the homes from PSS.
CosPersistentState::StorageHomeBase_var _runTimeHomeBasePSS = _session -> find_storage_home(ContainerPSS::RunTimeHome::id());
ContainerPSS::RunTimeHome_var _runTimeHomePSS = ContainerPSS::RunTimeHome::_downcast(_runTimeHomeBasePSS);
// CosPersistentState::StorageHomeBase_var _poolHomeBasePSS = _session -> find_storage_home("PSDL:ContainerPSS/PoolHome:1.0");
// ContainerPSS::RunTimeHome_var _poolHomePSS = ContainerPSS::RunTimeHome::_narrow(_poolHomePSSBase);
//
// CosPersistentState::StorageHomeBase_var _componentHomeBasePSS = _session -> find_storage_home("PSDL:ContainerPSS/ComponentHome:1.0");
// ContainerPSS::RunTimeHome_var _componentHomePSS = ContainerPSS::RunTimeHome::_narrow(_componentHomeBasePSS);
//get the storageObjects from PSS.
//save the runtime to PSS.
// CosPersistentState::Pid_var _runTimePid = _connector -> get_pid(this);
//
// if(CORBA::is_nil(_runTimePid))
// {
// ContainerPSS::RunTime_var _runTime = _runTimeHomePSS -> create( uuid_.in() );
// }
// else
// {
// CosPersistentState::StorageObject_var _runTimeObj = _session -> find_by_pid(_runTimePid);
// ContainerPSS::RunTime_var _runTime = ContainerPSS::RunTime::_narrow(_runTimeObj);
// _runTime -> uuid( uuid_.in());
// }
//
try
{
ContainerPSS::RunTime_var _runTime = ContainerPSS::RunTime::_downcast( _runTimeHomePSS -> find_by_uuid( uuid_.in() ));
_runTime -> uuid( uuid_.in());
_runTime -> homeRepositoryId( this -> getHomeRepId());
_runTime -> componentRepositoryId ( this -> getCompRepId());
_runTime -> homePoaId(this -> homePOAName_.in());
_runTime -> componentPoaId(this -> componentPOAName_.in());
_runTime -> containerUuid(container_ -> getUUID());
_runTime -> homeCompositionUuid(this -> homeCompositionUUID_.in());
_session -> flush();
}
catch(CosPersistentState::NotFound& )
// if(CORBA::is_nil(_runTime))
{
ContainerPSS::RunTime_var _runTime = ContainerPSS::RunTime::_downcast( _runTimeHomePSS -> create( uuid_.in() ));
// }
// else
{
_runTime -> uuid( uuid_.in());
}
_runTime -> homeRepositoryId( this -> getHomeRepId());
_runTime -> componentRepositoryId ( this -> getCompRepId());
_runTime -> homePoaId(this -> homePOAName_.in());
_runTime -> componentPoaId(this -> componentPOAName_.in());
_runTime -> containerUuid(container_ -> getUUID());
// PortableServer::ObjectId_var _poolId = PortableServer::POA::reference_to_id(runningComponentsPool_);
// _runTime -> poolUuid(PortableServer::ObjectId_to_string(_poolId));
_runTime -> homeCompositionUuid(this -> homeCompositionUUID_.in());
//flush() the PSS.
_session -> flush();
}
#endif
}
void
ContainerRunTime::incarnate(const char* uuid)
{
#ifndef LITE_VERSION
//SuLiang add . 2003.4.3.
//in this codes ,they can be replaced.!!!
/*
//get the connector.
CosPersistentState::Session_var _session = storageLoader_ -> getSession();
//get the homes from PSS.
CosPersistentState::StorageHomeBase_var _runTimeHomeBasePSS = _session -> find_storage_home(ContainerPSS::RunTimeHome::id());
ContainerPSS::RunTimeHome_var _runTimeHomePSS = ContainerPSS::RunTimeHome::_downcast(_runTimeHomeBasePSS);
ContainerPSS::RunTime_var _runTime = ContainerPSS::RunTime::_downcast( _runTimeHomePSS -> find_by_uuid( uuid ));
homeRepId_ = _runTime -> homeRepositoryId();
compRepId_ = _runTime -> componentRepositoryId ();
homePoa_ = _runTime -> homePoaId();
componentPoa_ = _runTime -> componentPoaId();
container_ -> setUUID( _runTime -> containerUuid() );
homeCompositionUUID_ = _runTime -> homeCompositionUuid();
*/
//SuLiang add . 2003.4.3.
/*
ConfigFile_var config = new ConfigFile();
CORBA::String_var ret;
try
{
ret = config->getServantFile(uuid);
servantsLoader_ = new ServantLoader(ret.in(), this);
ret = config->getExecutorFile(uuid);
executorsLoader_ = new ExecutorLoader(ret.in(), this);
ret = config->getPersistentFile(uuid);
storageLoader_ = new StorageObjectLoader(ret, this);
storageLoader_->loadPSS();
ret = config->getExecutorEntry(uuid);
Components::HomeExecutorBase_var homeExecutor
= executorsLoader_ -> loadHomeExecutor(ret.in());
HomeComposition_var homeComposition = new HomeComposition();
homeComposition->registerHomeExecutor(homeExecutor);
this -> setHomeComposition(homeComposition);
//???
CORBA::String_var uniqueId = Components::UuidGenerator::generateUuid();
PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId(uniqueId);
//homeComposition->setObjectId(oid);
ret = config->getServantEntry(uuid);
PortableServer::Servant homeServant
= servantsLoader_->loadHomeServant(ret.in());
if(homeServant == NULL)
{
TRACE0(LEVEL1,"Load Home servant from dll failed\n");
}
homeComposition->registerHomeServant(oid,homeServant);
//SuLiang add . 2003.4.3.
//set the homeComposition RepId.
ret = config->getHomeRepId(uuid);
homeComposition->setRepId(ret.in());
//registry value type and factories
CORBA::StringSeq_var repIds = config->getValueTypeFactoryRepId(uuid);
CORBA::StringSeq_var valueEntries = config->getValueTypeEntry(uuid);
int i;
for(i = 0; i < repIds->length(); ++i)
{
executorsLoader_->loadValueFactory(valueEntries[i], repIds[i]);
}
//set policies
CORBA::StringSeq_var policies;
ret = config->getHomeRepId(uuid);
policies = config->getHomeMethodPolicies(uuid, ret.in());
for(i = 0; i < policies->length(); ++i)
{
executorInvoker_->setTxnPolicy(ret, policies[i*2], policies[i*2+1]);
}
repIds = config->getComponentRepIds(uuid);
for(i = 0; i < repIds->length(); ++i)
{
policies = config->getComponentMethodPolicies(uuid, repIds[i]);
for(int j = 0; j < policies->length(); ++j)
{
executorInvoker_->setTxnPolicy(repIds[i], policies[j*2], policies[j*2+1]);
}
}
}
catch(CORBA::Exception& ex)
{
}
*/
#endif
}
void
ContainerRunTime::shutdown()
{
}
void
ContainerRunTime::cleanup()
{
//modified by xiao heping 2003/03/13
if (destroy_)
return ;
destroy_ = true;
try
{
runningComponentsPool_->cleanup();
}
catch(Components::RemoveFailure& ex)
{
throw ex;
}
//
//get home object from ContainerRuntime
//
Components::CCMHome_var home = getCcmHome();
::STARCCM::HomeRegistration_var homeReg;
try
{
CORBA::ORB_var orb=container_->getOrb();
CORBA::Object_var objReg = orb->string_to_object(homeRegistration_);
homeReg = ::STARCCM::HomeRegistration::_narrow(objReg);
}
catch(...)
{
TRACE0(LEVEL2,"ERROR:HomeRegisrtation NOT found.\n");
throw new Components::RemoveFailure ();
}
assert(!CORBA::is_nil(homeReg));
//
//unregister home object
//
try
{
homeReg -> unregister_home(home);
}
catch(...)
{
throw new Components::RemoveFailure();
}
//end modify xiao heping 2004/03/13
//Unload the DLL.SuLiang add. 2004.2.25
//deleted by xiao heping 2004/03/29
// executorsLoader_ -> etherealize();
// servantsLoader_ -> etherealize();
//end deleted xiao heping 2004/03/29
//Unload the DLL.SuLiang add. 2004.2.25
}
//void ContainerRunTime::removeHome(Components::CCMHome_ptr href)
//{
// PortableServer::ObjectId_var oid;
//
// oid = homePoa_ -> reference_to_id(href);
//
// //do all cleanup works
//}
void
ContainerRunTime::onCreateComponent(ComponentComposition_ptr comp)
{
//modified by jxh 03/22
//runningComponentsPool_ -> addComponent(compRepId_,comp);
runningComponentsPool_ -> addComponent(comp);
passivator_->onCreate();
if( passivator_->canPassiavte() )
{
//how to passivate?
}
}
void
ContainerRunTime::onRemoveComponent(const PortableServer::ObjectId* oid)
{
//deleted by wsf
//runningComponentsPool_ -> removeComponent(oid);
//passivator_->onRemove();
//end by wsf
//add by wsf
//To delete the according archcomponent info
deleteArchComponent(oid);
//end by wsf
}
CIFHook_ptr
ContainerRunTime::getCifHook()
{
if( cifHook_ == NULL)
{
cifHook_ = new CIFHook(this);
}
return OBJDUPLICATE(CIFHook_ptr,cifHook_);
}
void
ContainerRunTime::startup()
{
homePoa_ -> the_POAManager() -> activate();
componentPoa_ -> the_POAManager() -> activate();
}
void
ContainerRunTime::initialize(/*int isMultiThread*/)
{
TRACE0(LEVEL6,"Begin to initialize container runtime\n");
ConfigFile_var configFile = new ConfigFile();
/*
uuidtype uid;
uuid_create(&uid);
ConfigFile_var configFile = new ConfigFile();
//
//transfer the UUID to the string type
//
char *str =( char *)(malloc(37));
int j=sprintf(str,"%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", uid.time_low, uid.time_mid,
uid.time_hi_and_version, uid.clock_seq_hi_and_reserved,
uid.clock_seq_low);
for (int i = 0; i < 6; i++)
{
j+=sprintf(str+j,"%2.2x", uid.node[i]);
}
uuid_ = CORBA::string_dup(str);
free(str);
*/
uuid_ = ::Components::UuidGenerator::generateUuid();
TRACE0(LEVEL6,"Create runtime working directory\n");
CORBA::String_var workingDir = configFile->getRepositoryLocation();
#ifdef STARCCMSTRINGADD
workingDir = HelpFun::CORBA_string_add(workingDir.in(), PATH_DELILIMITOR);
workingDir = HelpFun::CORBA_string_add(workingDir.in(), uuid_.in());
#else
workingDir += CORBA::string_dup(PATH_DELILIMITOR);
workingDir += CORBA::string_dup(uuid_);
#endif
#ifdef WIN32
if( _mkdir(workingDir.in()) != 0)
#else
if( mkdir(workingDir.in(), 0775) != 0 )
#endif
{
TRACE0(LEVEL1,"FATAL ERROR: create directory error\n");
}
#ifdef _DEBUG
CORBA::String_var debugFile;
debugFile = workingDir;
#ifdef STARCCMSTRINGADD
debugFile = HelpFun::CORBA_string_add(debugFile.in(), PATH_DELILIMITOR);
debugFile = HelpFun::CORBA_string_add(debugFile.in(), "DebugConfig.ini");
#else
debugFile += CORBA::string_dup(PATH_DELILIMITOR);
debugFile += CORBA::string_dup("DebugConfig.ini");
#endif
CORBA::String_var targetFile = CORBA::string_dup(".");
targetFile += CORBA::string_dup(PATH_DELILIMITOR);
targetFile += CORBA::string_dup("DebugConfig.ini");
#ifdef WIN32
::CopyFile(targetFile,debugFile.in(),TRUE);
#else
HelpFun::copyFile(targetFile,debugFile.in());
#endif
#endif
//modified by xiao heping 2004/04/04
// homePOAName_ = CORBA::string_dup(::Components::UuidGenerator::generateUuid());
// componentPOAName_ = CORBA::string_dup(::Components::UuidGenerator::generateUuid());
homePOAName_ =::Components::UuidGenerator::generateUuid();
componentPOAName_ =::Components::UuidGenerator::generateUuid();
//end modified xiao heping 2004/04/04
//modified by xiao heping
#if defined(STARCCM_MTL)
threadPool_=new CustomThreadPool(1000);
//?????????????
threadPool_->createThreads(8);
//????????????????
CustomDispatchThreadPool* dsp_cus=new CustomDispatchThreadPool(threadPool_);
homePoa_ = container_->createHomePOA(/*isMultiThread,*/ homePOAName_,dsp_cus);
componentPoa_ = container_->createComponentPOA(/*isMultiThread, */componentPOAName_, homePoa_,dsp_cus);
dsp_cus->_remove_ref();
#else
homePoa_ = container_->createHomePOA(/*isMultiThread,*/ homePOAName_);
componentPoa_ = container_->createComponentPOA(/*isMultiThread,*/ componentPOAName_, homePoa_);
#endif
executorInvoker_ = new ::Container::ExecutorInvoker(this);
homeExecutorInvoker_ = new ::Container::ExecutorInvoker(this);
homePoa_->set_servant_manager(homeExecutorInvoker_);
componentPoa_->set_servant_manager(executorInvoker_);
//end modify
}
void
ContainerRunTime::setContainer(ContainerBase_ptr container)
{
container_ = OBJDUPLICATE(ContainerBase_ptr,container);
}
ContainerBase_ptr
ContainerRunTime::getContainer()
{
return OBJDUPLICATE(ContainerBase_ptr,container_);
}
//void
//ContainerRunTime::setCcmHome(::Components::CCMHome_ptr ccmHome)
//{
// ccmHome_ = ::Components::CCMHome::_duplicate(ccmHome);
//}
::Components::CCMHome_ptr
ContainerRunTime::getCcmHome()
{
//modified by xiao heping 2004/03/12
if(CORBA::is_nil (ccmHome_) )
{
PortableServer::ObjectId_var oid = homeComposition_ -> getObjectId();
CORBA::String_var repId = homeComposition_ -> getRepId();
CORBA::Object_var homeObj = homePoa_ -> create_reference_with_id(oid.in(),repId.in());
ccmHome_ = ::Components::CCMHome::_narrow(homeObj);
}
return ::Components::CCMHome::_duplicate(ccmHome_);
//end modify
}
PortableServer::ObjectId*
ContainerRunTime::getHomeObjectId()
{
PortableServer::ObjectId_var oid = homeComposition_->getObjectId();
PortableServer::ObjectId* ret = new PortableServer::ObjectId(oid.in());
return ret;
}
void
ContainerRunTime::setHomeComposition(HomeComposition_ptr homeComposition)
{
homeComposition_ = OBJDUPLICATE(HomeComposition_ptr,homeComposition);
}
PortableServer::Servant
ContainerRunTime::preinvoke(const PortableServer::ObjectId& oid,
PortableServer::POA_ptr adapter,
const char* operation,
PortableServer::ServantLocator::Cookie& the_cookie)
{
TRACE0(LEVEL5,"ContainerRunTime preinvoke\n");
if (destroy_)
return 0;
//add by wsf 2004.6.30
CORBA::String_var str = PortableServer::ObjectId_to_string(oid);
//to reject request if needed
{
STARCCM_SYNCHRONIZED(sync_,rejectReqMapMonitor)
if (!RejectReqMap.empty())
{
MapRejectReq::iterator iter = RejectReqMap.find(string(str.in()));
if (iter != RejectReqMap.end())
throw CORBA::OBJECT_NOT_EXIST();
}
}
//to redirecte request if needed
{
STARCCM_SYNCHRONIZED(sync_,redirectReqMapMonitor)
if (!redirectReqMap.empty())
{
MapRedirectReq::iterator iter = redirectReqMap.find(string(str.in()));
if (iter != redirectReqMap.end())
{
CORBA::Object_var obj = CORBA::Object::_duplicate((*iter).second);
throw PortableServer::ForwardRequest(obj);
}
}
}
//end by wsf 2004.6.30
//
//get servant
//
PortableServer::ObjectId* objectId = new PortableServer::ObjectId(oid);
PortableServer::Servant servant = getServant(objectId,the_cookie,operation);
delete objectId;
//added by xiao heping 2004/03/25
if(servant != 0)
{
::Container::Cookie* cookie = static_cast<Container::Cookie*>(the_cookie);
CompositionManager* compositionManager = cookie->getCompositionManager();
// CompositionManager* compositionManager = static_cast<CompositionManager*>(the_cookie);
#if (defined(StarBus) || defined(ORBacus)) && defined(STARCCM_MTL)
if(!isMultiThread_)
{
if((strcmp(operation,"_is_a") != 0 ) && (strcmp(operation,"_non_existent") != 0 ) && (strcmp(operation,"_is_equivalent") != 0 ))
compositionManager -> lock();
}
#endif
}
//end add
return servant;
}
void
ContainerRunTime::postinvoke(const PortableServer::ObjectId& oid,
PortableServer::POA_ptr adapter,
const char* operation,
PortableServer::ServantLocator::Cookie the_cookie,
PortableServer::Servant the_servant)
{
//added by xiao heping 2004/03/04
TRACE0(LEVEL5,"ContainerRunTime postinvoke\n");
::Container::Cookie* cookie = static_cast<Container::Cookie*>(the_cookie);
CompositionManager* compositionManager = cookie->getCompositionManager();
// CompositionManager* compositionManager = static_cast<CompositionManager*>(the_cookie);
#if (defined(StarBus) || defined(ORBacus)) && defined(STARCCM_MTL)
if(!isMultiThread_)
{
if((strcmp(operation,"_is_a") != 0 ) && (strcmp(operation,"_non_existent") != 0 ) && (strcmp(operation,"_is_equivalent") != 0 ))
compositionManager -> unlock();
}
#endif
the_servant -> _remove_ref();
try
{
compositionManager -> _remove_ref();
}
catch(...)
{
TRACE0(LEVEL1,"\n^^^^^^^^^^^^^^^^ContainerRunTime::postinvoke^^^^^^^^^^^^^^^^^^\n");
}//end add
//deleted by xiao heping 2004/03/18
// if((strcmp(operation,"remove") == 0)||(strcmp(operation,"remove_component") == 0))
// {
// the_servant -> _remove_ref();
// }
//end delete xiao heping 2004/03/18
}
/*
ExecutorInvoker_ptr
ContainerRunTime::getExecutorInvoker()
{
return executorInvoker_;
}
ExecutorInvoker_ptr
ContainerRunTime::getHomeExecutorInvoker()
{
return homeExecutorInvoker_;
}
*/
//
//The install_home operation installs and returns a new CCMHome object. The id and
//entrypt parameters are used by the container to locate an implementation file and
//instantiate a new home object. The config parameter represents a sequence of
//ConfigValue objects that provide name value pairs used to configure the installation
//of the new home instance; for example, provide persistency source, transaction, and
//security policies that must be applied to the home and its components. The operation
//raises an UnknownImplId exception if the id parameter does not correspond to any
//component packages installed using the ComponentInstallation object. The
//operation raises an ImplEntryPointNotFound exception if the entrypt parameter
//cannot be found in the implementation returned from ComponentInstallation. The
//operation raises an InstallationFailure exception if the home could not be installed
//in the container for internal reasons such as insufficient resources or inadequate
//implementation for this container; for example, installing a C++ home implementation
//in a Java container. The operation raises an InvalidConfiguration exception if the
//config parameter does not contain valid configuration name value pairs.
//
Components::CCMHome_ptr
ContainerRunTime::install_home(const char* id,const char* entrypt,
const Components::ConfigValues& config)
throw(Components::Deployment::UnknownImplId,
Components::Deployment::ImplEntryPointNotFound,
Components::Deployment::InstallationFailure,
Components::Deployment::InvalidConfiguration,
CORBA::SystemException)
{
int len = config.length();
// int isMultiThread;
CORBA::String_var homeServantEntry;
CORBA::String_var contextEntry;
CORBA::String_var homeServantDll;
// CORBA::String_var homeRepId;
// CORBA::String_var componentRepId;
//added by xiao heping 2004/03/28
// ServantLoader_var servantsLoader;
// ExecutorLoader_var executorsLoader;
//end add xiao heping 2004/03/28
CORBA::String_var homeExecutorEntry;
CORBA::String_var homeExecutorDll;
CORBA::StringSeq_var valueFactoryEntries;
CORBA::StringSeq_var valueFactoryRepIds;
int hasValueFactory = 0;
CORBA::String_var storageHomeEntry;
CORBA::String_var storageHomeDll;
int componentKind;
int configurationCompleted = 0;
CORBA::String_var componentTxnPolicy = CORBA::string_dup("");
CORBA::StringSeq_var homeRepIds;
CORBA::StringSeq_var homeTxnPolicies;
CORBA::StringSeq_var homeMethods;
int hasHomeMethodTxnPolicy = 0;
CORBA::StringSeq_var componentRepIds;
CORBA::StringSeq_var componentTxnPolicies;
CORBA::StringSeq_var componentMethods;
int hasComponentMethodTxnPolicy = 0;
FileAccessorFactory_var fileaccessorfactory;
// CORBA service initial references
CORBA::String_var nameService = CORBA::string_dup("");
CORBA::String_var homeFinder = CORBA::string_dup("");
homeRegistration_ = CORBA::string_dup("");
CORBA::String_var transactionService = CORBA::string_dup("");
CORBA::String_var notificationService = CORBA::string_dup("");
//persistent policies
int isCmp = 0;
int isTransactional = 0;
int accessMode = 1;
int isolationLevel = 3;
CORBA::String_var storageHomeId = CORBA::string_dup("");
CORBA::String_var pssFileName = CORBA::string_dup("");
//resourcepool
CORBA::StringSeq_var resources;
int hasToCreateResources = 0;
//jxh 06/22
//CORBA::String_var resourceName;
ConfigFile_var configFile = new ConfigFile();
for(int i = 0;i<len;i++)
{
if( config[i] != NULL )
{
if( config[i]->name() != NULL )
{
if( strcmp(config[i]->name(),"ServantDllName") ==0 )
{
const char *msg;
config[i]->value() >>= msg;
homeServantDll = msg;
TRACE1(LEVEL6,"Seravnt DLL name is %s\n",homeServantDll);
}
else if( strcmp(config[i]->name(),"FileAccessorFactory") ==0 )
{
// CORBA::Object_var factoryObj;
// TRACE0(LEVEL6,"File accessor process begin.\n");
// config[i]->value() >>= CORBA::Any::to_object(factoryObj);
// TRACE0(LEVEL6,"File accessor got from the any.\n");
//
// fileaccessorfactory = STARCCM::Deployment::FileAccessorFactory::_narrow(factoryObj);
//
// TRACE0(LEVEL6,"File Accessor Factory \n");
STARCCM::Deployment::FileAccessorFactory_ptr factoryObj;
TRACE0(LEVEL6,"File accessor process begin.\n");
config[i]->value() >>= factoryObj;
TRACE0(LEVEL6,"File accessor got from the any.\n");
fileaccessorfactory = STARCCM::Deployment::FileAccessorFactory::_duplicate(factoryObj);
// CORBA::ORB_var orb = container_ -> getOrb();
// CORBA::String_var s1 = orb -> object_to_string(fileaccessorfactory);
//
//
// const char* refFile1 = "C:\\ccm\\File.ref";
// ofstream out1(refFile1);
// if(out1.fail())
// {
// TRACE0(LEVEL3,"Can NOT create reference files\n");
// }
//
// out1 << s1 << endl;
// out1.close();
TRACE0(LEVEL6,"File Accessor Factory \n");
}
else if( strcmp(config[i]->name(),"HomeServantEntryPoint") ==0 )
{
const char *msg;
config[i]->value() >>= msg;
homeServantEntry = msg;
TRACE1(LEVEL6,"Home seravnt entry point is %s\n",homeServantEntry);
}
else if( strcmp(config[i]->name(),"ContextEntryPoint") ==0 )
{
const char *msg;
config[i]->value() >>= msg;
contextEntry = msg;
TRACE1(LEVEL6,"Context entry point is %s\n",contextEntry);
}
else if( strcmp(config[i]->name(),"ExecutorDllName") ==0 )
{
const char *msg;
config[i]->value() >>= msg;
homeExecutorDll = msg;
TRACE1(LEVEL6,"Home executor DLL name is %s\n",homeExecutorDll);
}
else if( strcmp(config[i]->name(),"HomeExecutorEntryPoint") ==0 )
{
const char *msg;
config[i]->value() >>= msg;
homeExecutorEntry = msg;
TRACE1(LEVEL6,"Home executor entry point is %s\n",homeExecutorEntry);
}
else if( strcmp(config[i]->name(),"ValueFactoryEntryPoints") ==0 )
{
const CORBA::StringSeq* msg;
config[i]->value() >>= msg;
valueFactoryEntries = new CORBA::StringSeq(*msg);
hasValueFactory = 1;
for(int j = 0 ; j < valueFactoryEntries->length() ; j++)
{
TRACE1(LEVEL6,"ValueFactory entry name is %s\n",valueFactoryEntries[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"ValueFactoryRepIds") ==0 )
{
const CORBA::StringSeq* msg;
config[i]->value() >>= msg;
valueFactoryRepIds =new CORBA::StringSeq(*msg);
hasValueFactory = 1;
for(int j = 0 ; j < valueFactoryRepIds->length() ; j++)
{
TRACE1(LEVEL6,"Value Factory repository id is %s\n",valueFactoryRepIds[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"HomeRepositoryId") ==0 )
{
const char* msg;
config[i]->value() >>= msg;
// homeRepId = msg;
homeRepId_ = msg;
TRACE1(LEVEL6,"Home Repository ID is %s\n",homeRepId_);
}
else if( strcmp(config[i]->name(),"ComponentRepositoryId") ==0 )
{
const char* msg;
config[i]->value() >>= msg;
// componentRepId = msg;
compRepId_ = msg;
TRACE1(LEVEL6,"Component Repository ID is %s\n",compRepId_);
}
else if( strcmp(config[i]->name(),"ComponentKind") ==0 )
{
ContainerType type;
CORBA::String_var kind;
const char* msg;
config[i]->value() >>= msg;
kind = msg;
if( strcmp(kind,"service" ) ==0 )
{
type = SERVICECONTAINER;
componentKind = 0;
TRACE0(LEVEL6,"component kind : service\n");
}
else if( strcmp(kind,"session" ) ==0 )
{
type = SESSIONCONTAINER;
componentKind = 1;
TRACE0(LEVEL6,"component kind : session\n");
}
else if( strcmp(kind,"entity" ) ==0 )
{
type = ENTITYCONTAINER;
componentKind = 2;
TRACE0(LEVEL6,"component kind : entity\n");
}
else if( strcmp(kind,"process" ) ==0 )
{
type = PROCESSCONTAINER;
componentKind = 3;
TRACE0(LEVEL6,"component kind : process\n");
}
else
{
TRACE0(LEVEL1,"Wrong component kind\n");
//added by xiao heping 2004/03/23
throw new Components::Deployment::InvalidConfiguration;
//end add xiao heping 2004/03/23
}
//added by xiao heping 2004/02/13
if(!container_->isContainerTypeSetted())
container_->setContainerType(type) ;
else
{
if( type != container_->getContainerType() )
{
TRACE0(LEVEL1,"FATAL ERROR : Container type and cmponent kind NOT match\n");
throw new Components::Deployment::InvalidConfiguration;
}
}
//added by xiao heping 2004/02/13
}
else if( strcmp(config[i]->name(),"HomeTxnRepId") ==0 )
{
const CORBA::StringSeq* msg;
hasHomeMethodTxnPolicy = 1;
config[i]->value() >>= msg;
homeRepIds = new CORBA::StringSeq(*msg);
for(int j = 0 ; j < homeRepIds->length() ; j++)
{
TRACE1(LEVEL6,"Home repository id is %s\n",homeRepIds[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"HomeMethodTxnNames") ==0 )
{
const CORBA::StringSeq* msg;
hasHomeMethodTxnPolicy = 1;
config[i]->value() >>= msg;
homeMethods = new CORBA::StringSeq(*msg);
for(int j = 0 ; j < homeMethods->length() ; j++)
{
TRACE1(LEVEL6,"Home Mothod name is %s\n",homeMethods[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"HomeMethodTxnPolicies") ==0 )
{
const CORBA::StringSeq* msg;
hasHomeMethodTxnPolicy = 1;
config[i]->value() >>= msg;
homeTxnPolicies = new CORBA::StringSeq(*msg);
for(int j = 0 ; j < homeTxnPolicies->length() ; j++)
{
TRACE1(LEVEL6,"Home Mothod policy is %s\n",homeTxnPolicies[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"ComponentTxnRepId") ==0 )
{
const CORBA::StringSeq* msg;
hasComponentMethodTxnPolicy = 1;
config[i]->value() >>= msg;
componentRepIds = new CORBA::StringSeq(*msg);
for(int j = 0 ; j < componentRepIds->length() ; j++)
{
TRACE1(LEVEL6,"Component repository id is %s\n",componentRepIds[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"ComponentMethodTxnNames") ==0 )
{
const CORBA::StringSeq* msg;
hasComponentMethodTxnPolicy = 1;
config[i]->value() >>= msg;
componentMethods = new CORBA::StringSeq(*msg);
for(int j = 0 ; j < componentMethods->length() ; j++)
{
TRACE1(LEVEL6,"Component Mothod name is %s\n",componentMethods[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"ComponentMethodTxnPolicies") ==0 )
{
const CORBA::StringSeq* msg;
hasComponentMethodTxnPolicy = 1;
config[i]->value() >>= msg;
componentTxnPolicies = new CORBA::StringSeq(*msg);
for(int j = 0 ; j < componentTxnPolicies->length() ; j++)
{
TRACE1(LEVEL6,"Component Mothod policy is %s\n",componentTxnPolicies[(CORBA::ULong)j].in());
}
}
else if( strcmp(config[i]->name(),"Threading") ==0 )
{
const char* msg;
config[i]->value() >>= msg;
if( strcmp(msg,"multithread") == 0 )
{
isMultiThread_ = 1;
}
else
{
isMultiThread_ = 0;
}
}
else if( strcmp(config[i]->name(),"ComponentTxnPolicy") ==0 )
{
const char* msg;
hasComponentMethodTxnPolicy = 1;
config[i]->value() >>= msg;
componentTxnPolicy = msg;
}
else if( strcmp(config[i]->name(),"ConfigurationComplete") ==0 )
{
const char* msg;
config[i]->value() >>= msg;
if( strcmp(msg,"true") == 0 )
{
configurationCompleted = 1;
}
else
{
configurationCompleted = 0;
}
}
else if( strcmp(config[i]->name(),"NameService") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
nameService = msg;
TRACE0(LEVEL6,"NameService resolved\n");
}
else if( strcmp(config[i]->name(),"HomeFinder") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
homeFinder = msg;
TRACE0(LEVEL6,"HomeFinder resolved\n");
}
else if( strcmp(config[i]->name(),"TransactionService") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
transactionService = msg;
TRACE0(LEVEL6,"TransactionService resolved\n");
}
else if( strcmp(config[i]->name(),"HomeRegistration") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
homeRegistration_ = msg;
TRACE0(LEVEL6,"HomeRegistration resolved\n");
}
else if( strcmp(config[i]->name(),"NotificationService") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
notificationService = msg;
TRACE0(LEVEL6,"NotificationService resolved\n");
}
else if( strcmp(config[i]->name(),"PSSFileName") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
pssFileName = msg;
}
else if( strcmp(config[i]->name(),"StorageHomeId") == 0 )
{
const char* obj;
config[i]->value() >>= obj;
storageHomeId = obj;
}
else if( strcmp(config[i]->name(),"PSSAccessMode") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
if( strcmp(msg, "ReadOnly") )
{
accessMode = 0;
}
else
{
accessMode = 1;
}
}
else if( strcmp(config[i]->name(),"PSSCMP") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
if( strcmp(msg, "Container") )
{
isCmp = 1;
}
else
{
isCmp = 0;
}
}
else if( strcmp(config[i]->name(),"PSSTxnPolicy") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
if( strcmp(msg, "Transactional") )
{
isTransactional = 1;
}
else
{
isTransactional = 0;
}
}
else if( strcmp(config[i]->name(),"PSSTxnIsolationLevel") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
if( strcmp(msg, "ReadUncommitted") )
{
isolationLevel = 0;
}
else if( strcmp(msg, "ReadCommitted") )
{
isolationLevel = 1;
}
else if( strcmp(msg, "RepeatableRead") )
{
isolationLevel = 2;
}
else
{
isolationLevel = 3;
}
}
else if( strcmp(config[i]->name(),"CreateResourcePool") == 0 )
{
const CORBA::StringSeq* msg;
config[i]->value() >>= msg;
resources = new CORBA::StringSeq(*msg);
hasToCreateResources = 1;
}
else if( strcmp(config[i]->name(),"ResourcePoolName") == 0 )
{
const char* msg;
config[i]->value() >>= msg;
resourceName = msg;
}
else
{
TRACE1(LEVEL1,"Unknow config value : %s\n",config[i]->name());
}
}
else
{
TRACE0(LEVEL6,"NULL config value name\n");
}
}
else
{
TRACE0(LEVEL6,"NULL config value\n");
}
}
TRACE0(LEVEL6,"All of the config values have been saved\n");
TRACE0(LEVEL6,"Out of the iteration\n");
//End of saving
initialize(/*isMultiThread*/);
//Load dlls
assert(!(homeServantDll.in() == NULL));
assert(!(homeExecutorDll.in() == NULL));
assert(!(homeExecutorEntry.in() == NULL));
assert(!(homeServantEntry.in() == NULL));
//Download the component implementation from the ComponentInstallation
CORBA::String_var servantLocation;
CORBA::String_var executorLocation;
CORBA::String_var persistenterLocation;
STARCCM::Deployment::DeployDomainMgr_var manager = container_ -> getDomainManager();
try
{
CORBA::String_var objLoc;
objLoc = manager -> getObject(STARCCM::Deployment::COMPONENTINSTALLATION,"");
CORBA::ORB_var orb = container_ -> getOrb();
CORBA::Object_var obj = orb -> string_to_object(objLoc.in());
locator_ = Components::Deployment::ComponentInstallation::_narrow(obj);
servantLocation = locator_ -> get_implementation(id);
executorLocation = locator_ -> get_implementation(id);
persistenterLocation = locator_ -> get_implementation(id);
}
catch(Components::Deployment::UnknownImplId&)
{
TRACE1(LEVEL2,"Unknow component package UUID:%s\n",id);
throw;
}
catch(Components::Deployment::InstallationFailure&)
{
TRACE1(LEVEL2,"Unknow component package UUID:%s\n",id);
throw;
}
#ifdef STARCCMSTRINGADD
servantLocation = HelpFun::CORBA_string_add(servantLocation.in(), PATH_DELILIMITOR);
servantLocation= HelpFun::CORBA_string_add(servantLocation.in(), homeServantDll.in());
executorLocation = HelpFun::CORBA_string_add(executorLocation.in(), PATH_DELILIMITOR);
executorLocation= HelpFun::CORBA_string_add(executorLocation.in(), homeExecutorDll.in());
persistenterLocation = HelpFun::CORBA_string_add(persistenterLocation.in(), PATH_DELILIMITOR);
persistenterLocation= HelpFun::CORBA_string_add(persistenterLocation.in(), pssFileName.in());
CORBA::String_var servantPath = configFile->getRepositoryLocation();
servantPath = HelpFun::CORBA_string_add(servantPath.in(), PATH_DELILIMITOR);
CORBA::String_var executorPath = configFile->getRepositoryLocation();
executorPath = HelpFun::CORBA_string_add(executorPath.in(), PATH_DELILIMITOR);
CORBA::String_var persistenterPath = configFile->getRepositoryLocation();
persistenterPath = HelpFun::CORBA_string_add(persistenterPath.in(), PATH_DELILIMITOR);
servantPath = HelpFun::CORBA_string_add(servantPath.in(), uuid_.in());
executorPath = HelpFun::CORBA_string_add(executorPath.in(), uuid_.in());
persistenterPath = HelpFun::CORBA_string_add(persistenterPath.in(), uuid_.in());
servantPath = HelpFun::CORBA_string_add(servantPath.in(), PATH_DELILIMITOR);
executorPath = HelpFun::CORBA_string_add(executorPath.in(), PATH_DELILIMITOR);
persistenterPath = HelpFun::CORBA_string_add(persistenterPath.in(), PATH_DELILIMITOR);
servantPath = HelpFun::CORBA_string_add(servantPath.in(), homeServantDll.in());
executorPath = HelpFun::CORBA_string_add(executorPath.in(), homeExecutorDll.in());
persistenterPath = HelpFun::CORBA_string_add(executorPath.in(), pssFileName.in());
#else
servantLocation += CORBA::string_dup(PATH_DELILIMITOR);
servantLocation += CORBA::string_dup(homeServantDll);
executorLocation += CORBA::string_dup(PATH_DELILIMITOR);
executorLocation += CORBA::string_dup(homeExecutorDll);
persistenterLocation += CORBA::string_dup(PATH_DELILIMITOR);
persistenterLocation += CORBA::string_dup(pssFileName);
CORBA::String_var servantPath = configFile->getRepositoryLocation();
servantPath += CORBA::string_dup(PATH_DELILIMITOR);
CORBA::String_var executorPath = configFile->getRepositoryLocation();
executorPath += CORBA::string_dup(PATH_DELILIMITOR);
CORBA::String_var persistenterPath = configFile->getRepositoryLocation();
persistenterPath += CORBA::string_dup(PATH_DELILIMITOR);
servantPath += uuid_;
executorPath += uuid_;
persistenterPath += uuid_;
servantPath += CORBA::string_dup(PATH_DELILIMITOR);
executorPath += CORBA::string_dup(PATH_DELILIMITOR);
persistenterPath += CORBA::string_dup(PATH_DELILIMITOR);
servantPath += homeServantDll;
executorPath += homeExecutorDll;
persistenterPath += pssFileName;
#endif
assert(!CORBA::is_nil(fileaccessorfactory));
FileAccessor_var fileaccessor = fileaccessorfactory->createFileAccessor();
assert( !CORBA::is_nil(fileaccessor) );
FILE *fileWriteStream;
CORBA::String_var workingDir = configFile->getRepositoryLocation();
#ifdef STARCCMSTRINGADD
workingDir = HelpFun::CORBA_string_add(workingDir.in(), PATH_DELILIMITOR);
workingDir = HelpFun::CORBA_string_add(workingDir.in(), uuid_.in());
#else
workingDir += CORBA::string_dup(PATH_DELILIMITOR);
workingDir += uuid_;
#endif
//Download the servant dll
try
{
fileaccessor -> locate_file( servantLocation.in() );
TRACE1(LEVEL6,"donwload servant dll from directory of %s. \n",workingDir.in());
#ifdef WIN32
if( _chdir(workingDir.in()))
{
TRACE0(LEVEL1,"Unable to locate the directory\n");
throw Components::Deployment::InstallationFailure();
}
#else
if( chdir(workingDir.in()))
{
TRACE0(LEVEL1,"Unable to locate the directory\n");
throw Components::Deployment::InstallationFailure();
}
#endif
TRACE1(LEVEL6,"save servant in local file %s\n", servantPath.in());
if( (fileWriteStream = fopen( servantPath.in(), "wb" )) == NULL )
{
TRACE0(LEVEL1,"Unable to locate the file\n");
fclose(fileWriteStream);
throw Components::Deployment::InstallationFailure();
}
int from_octet=0;
int max_octets=1024000;
int writeSize;
FileOctetSeq_var writeBuffer;
do
{
writeBuffer=fileaccessor -> get_octet_seq(from_octet,max_octets);
writeSize=writeBuffer -> length();
if(fseek( fileWriteStream, from_octet , SEEK_SET)!=0)
{
TRACE0(LEVEL1,"File seek error\n");
throw Components::Deployment::InstallationFailure();
}
fwrite(writeBuffer -> get_buffer(), 1, writeSize, fileWriteStream);
from_octet += writeSize;
}
while(writeSize == max_octets);
}
catch(const FileSystemError &e)
{
TRACE1(LEVEL3,"File system error:%s\n",e.desc);
fclose(fileWriteStream);
throw Components::Deployment::InstallationFailure();
}
catch(...)
{
TRACE0(LEVEL1,"Other Non Corba Exception happened\n");
fclose(fileWriteStream);
throw Components::Deployment::InstallationFailure();
};
fclose(fileWriteStream);
TRACE0(LEVEL6,"File transfer succeed\n");
//Download the executor dll
try
{
fileaccessor -> locate_file(executorLocation.in());
#ifdef WIN32
if( _chdir(workingDir.in()))
{
TRACE0(LEVEL1,"Unable to locate the directory\n");
throw Components::Deployment::InstallationFailure();
}
#else
if( chdir(workingDir.in()))
{
TRACE0(LEVEL1,"Unable to locate the directory\n");
throw Components::Deployment::InstallationFailure();
}
#endif
if( (fileWriteStream = fopen( homeExecutorDll.in(), "wb" )) == NULL )
{
TRACE0(LEVEL1,"Unable to locate the file\n");
fclose(fileWriteStream);
throw Components::Deployment::InstallationFailure();
}
int from_octet=0;
int max_octets=1024000;
int writeSize;
FileOctetSeq_var writeBuffer;
do
{
writeBuffer=fileaccessor -> get_octet_seq(from_octet,max_octets);
writeSize=writeBuffer -> length();
if(fseek( fileWriteStream, from_octet , SEEK_SET)!=0)
{
TRACE0(LEVEL1,"File seek error\n");
fclose(fileWriteStream);
throw Components::Deployment::InstallationFailure();
}
fwrite(writeBuffer -> get_buffer(), 1, writeSize, fileWriteStream);
from_octet += writeSize;
}
while(writeSize == max_octets);
}
catch(const FileSystemError &e)
{
TRACE1(LEVEL3,"File system error:%s\n",e.desc);
fclose(fileWriteStream);
throw Components::Deployment::InstallationFailure();
}
catch(...)
{
TRACE0(LEVEL1,"Other Non Corba Exception happened\n");
fclose(fileWriteStream);
throw Components::Deployment::InstallationFailure();
};
fclose(fileWriteStream);
TRACE0(LEVEL6,"File transfer succeed\n");
servantsLoader_ = new ServantLoader(servantPath, this);
executorsLoader_ = new ExecutorLoader(executorPath, this);
//
//construct HomeComposition object
//
HomeComposition_var homeComposition = new HomeComposition();
Components::HomeExecutorBase_ptr homeExecutor = executorsLoader_->loadHomeExecutor(homeExecutorEntry);
if(homeExecutor == NULL)
{
TRACE0(LEVEL1,"Load Home Executor from dll failed\n");
throw Components::Deployment::InstallationFailure();
}
homeComposition->registerHomeExecutor(homeExecutor);
setHomeComposition(homeComposition);
Components::UuidGenerator_var gen = new Components::UuidGenerator();
homeCompositionUUID_ = gen -> generateUuid();
PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId(homeCompositionUUID_.in());
PortableServer::Servant homeServant = servantsLoader_->loadHomeServant(homeServantEntry);
if(homeServant == NULL)
{
TRACE0(LEVEL1,"Load Home servant from dll failed\n");
throw Components::Deployment::InstallationFailure();
}
homeComposition->registerHomeServant(oid,homeServant);
homeComposition->setRepId(homeRepId_);
//load if there is any value factory
if( hasValueFactory && ( valueFactoryEntries->length() != 0 ) )
{
if( valueFactoryEntries->length() != valueFactoryRepIds->length() )
{
throw new Components::Deployment::InvalidConfiguration();
}
for(int k = 0 ; k < valueFactoryEntries->length() ; k++)
{
//modified by xiao heping 2004/03/23
//in order to release memory space
CORBA::ValueFactoryBase_var valuefactory = executorsLoader_
-> loadValueFactory(valueFactoryEntries[(CORBA::ULong)k],valueFactoryRepIds[(CORBA::ULong)k]);
}
}
#ifdef WITH_OTS
//set home transaction policy if there is any
if( hasHomeMethodTxnPolicy && ( homeTxnPolicies->length() != 0 ) )
{
if( homeTxnPolicies->length() != homeMethods->length() )
{
throw new Components::Deployment::InvalidConfiguration();
}
for(int k = 0 ; k < homeTxnPolicies->length() ; k++)
{
homeExecutorInvoker_-> setTxnPolicy((char*)homeRepIds[(CORBA::ULong)k].in(),
(char*)homeMethods[(CORBA::ULong)k].in(),
(char*)homeTxnPolicies[(CORBA::ULong)k].in());
}
}
//set component transaction policy if there is any
if( hasComponentMethodTxnPolicy && ( componentTxnPolicies->length() != 0 ) )
{
if( componentTxnPolicies->length() != componentMethods->length() )
{
throw new Components::Deployment::InvalidConfiguration();
}
//component policy is set to all operations.
if (!strcmp(componentTxnPolicy,"*"))
executorInvoker_-> setTxnPolicy((char*)compRepId_.in(),
(char*)"*",
(char*)componentTxnPolicy.in());
//component policy is "self-managed",and the length of componentTxnPolicies must be 1.
if (!strcmp(componentTxnPolicy,"self-managed"))
{
// if(componentTxnPolicies->length() == 0)
executorInvoker_-> setTxnPolicy((char*)compRepId_.in(),
(char*)"self-managed",
(char*)componentTxnPolicy.in());
// else
// {
// throw new Components::Deployment::InvalidConfiguration();
// }
}
for(int k = 0 ; k < componentTxnPolicies->length() ; k++)
{
executorInvoker_-> setTxnPolicy((char*)componentRepIds[(CORBA::ULong)k].in(),
(char*)componentMethods[(CORBA::ULong)k].in(),
(char*)componentTxnPolicies[(CORBA::ULong)k].in());
}
}
#endif
TRACE0(LEVEL6, "preparing for loading PSS\n");
//Download the PSS dll
// if( strcmp(pssFileName.in(), "") != 0 )
// {
// try
// {
// fileaccessor -> locate_file(persistenterLocation.in());
//
//#ifdef WIN32
// if( _chdir(workingDir.in()))
// {
// TRACE0(LEVEL1,"Unable to locate the directory\n");
// throw Components::Deployment::InstallationFailure();
// }
//#else
//#endif
//
// if( (fileWriteStream = fopen( persistenterPath.in(), "wb" )) == NULL )
// {
// TRACE0(LEVEL1,"Unable to locate the file\n");
// fclose(fileWriteStream);
// throw Components::Deployment::InstallationFailure();
// }
//
//
// int from_octet=0;
// int max_octets=1024000;
// int writeSize;
//
// FileOctetSeq_var writeBuffer;
//
// do
// {
//
// writeBuffer=fileaccessor -> get_octet_seq(from_octet,max_octets);
// writeSize=writeBuffer -> length();
//
// if(fseek( fileWriteStream, from_octet , SEEK_SET)!=0)
// {
// TRACE0(LEVEL1,"File seek error\n");
// fclose(fileWriteStream);
// throw Components::Deployment::InstallationFailure();
// }
//
// fwrite(writeBuffer -> get_buffer(), 1, writeSize, fileWriteStream);
//
// from_octet += writeSize;
//
// }
// while(writeSize == max_octets);
// }
// catch(const FileSystemError &e)
// {
// TRACE1(LEVEL3,"File system error:%s\n",e.desc);
// fclose(fileWriteStream);
// throw Components::Deployment::InstallationFailure();
// }
// catch(...)
// {
// TRACE0(LEVEL1,"Other Non Corba Exception happened\n");
// fclose(fileWriteStream);
// throw Components::Deployment::InstallationFailure();
// };
//
// fclose(fileWriteStream);
// TRACE0(LEVEL6,"File transfer succeed\n");
//
// //load persistenter
// storageLoader_ = new StorageObjectLoader(pssFileName, this);
// storageLoader_->loadPSS();
// }
Components::CCMHome_var home;
TRACE0(LEVEL6,"installation complete\n");
//
//activate POAManager
//
startup();
TRACE0(LEVEL6,"Container Runtime is ready\n");
//
//get CCMHome object reference
//
home = getCcmHome();
//
//save installed componet configuration into configfile
//
configFile->addInstalledComponent(container_->getUUID(), id);
configFile->addExecutorFile(id, homeExecutorEntry, homeRepId_, compRepId_, homeExecutorDll);
configFile->addServantFile(id, homeServantEntry, contextEntry, homeServantDll);
TRACE0(LEVEL6, "store value type configs to config file\n");
if( hasValueFactory && ( valueFactoryEntries->length() != 0 ) )
{
if( valueFactoryEntries->length() != valueFactoryRepIds->length() )
{
throw new Components::Deployment::InvalidConfiguration();
}
for(int k = 0 ; k < valueFactoryEntries->length() ; k++)
{
configFile->addValueTypeFile(id, "null", valueFactoryEntries[(CORBA::ULong)k], valueFactoryRepIds[(CORBA::ULong)k], homeExecutorDll);
}
}
TRACE0(LEVEL6, "store home transaction policies configs to config file\n");
if( hasHomeMethodTxnPolicy && ( homeMethods->length() != 0 ) )
{
if( homeMethods->length() != homeTxnPolicies->length() )
{
throw new Components::Deployment::InvalidConfiguration();
}
TRACE0(LEVEL6,"storing ...\n");
for(int k = 0; k < homeMethods->length(); k++)
{
TRACE1(LEVEL6, "iterator %d\n", k);
TRACE1(LEVEL6, "home mothod name : %s\n", homeMethods[(CORBA::ULong)k].in());
TRACE1(LEVEL6, "home repository id : %s\n", homeRepIds[(CORBA::ULong)k].in());
TRACE1(LEVEL6, "home mothod policy : %s\n", homeTxnPolicies[(CORBA::ULong)k].in());
configFile->addHomeTransactionPolicy(id,homeMethods[(CORBA::ULong)k].in(), homeRepIds[(CORBA::ULong)k].in(), homeTxnPolicies[(CORBA::ULong)k].in());
}
}
TRACE0(LEVEL6, "store component transaction policies configs to config file\n");
if( hasComponentMethodTxnPolicy && ( componentMethods->length() != 0 ) )
{
if( componentMethods->length() != componentTxnPolicies->length() )
{
throw new Components::Deployment::InvalidConfiguration();
}
TRACE0(LEVEL6,"storing ...\n");
for(int k = 0; k < componentMethods->length(); k++)
{
TRACE1(LEVEL6, "iterator %d\n", k);
TRACE1(LEVEL6, "component mothod name : %s\n", componentMethods[(CORBA::ULong)k].in());
TRACE1(LEVEL6, "component repository id : %s\n", componentRepIds[(CORBA::ULong)k].in());
TRACE1(LEVEL6, "component mothod policy : %s\n", componentTxnPolicies[(CORBA::ULong)k].in());
configFile->addCompTransactionPolicy(id,componentMethods[(CORBA::ULong)k].in(), componentRepIds[(CORBA::ULong)k].in(), componentTxnPolicies[(CORBA::ULong)k].in());
}
}
configFile->addComponentKind(id, componentKind);
configFile->addComponentThreading(id, isMultiThread_);
configFile->addConfigurationComplete(id, configurationCompleted);
configFile->setPersistentPolicy(id, isCmp);
configFile->setPersistentTxnPolicy(id, isTransactional);
configFile->setAccessMode(id, accessMode);
configFile->setIsolationLevel(id, isolationLevel);
configFile->setStorageHomeId(id, storageHomeId.in());
configFile->setPersistentFile(id, pssFileName.in());
CORBA::String_var serverId = container_->getComponentServerUuid();
CORBA::StringSeq_var myResources;
CosPersistentState::ParameterList_var parameters;
if( hasToCreateResources )
{
configFile->addReourcePool(serverId.in(), resources);
myResources = configFile->getResourcePoolProperties(serverId.in(), resourceName);
#ifndef LITE_VERSION
parameters = new CosPersistentState::ParameterList();
parameters->length(4);
parameters[0].name = CORBA::string_dup("host");
parameters[0].val <<= CORBA::string_dup(myResources[0]);
parameters[1].name = CORBA::string_dup("database");
parameters[1].val <<= CORBA::string_dup(myResources[1]);
parameters[2].name = CORBA::string_dup("user");
parameters[2].val <<= CORBA::string_dup(myResources[2]);
parameters[3].name = CORBA::string_dup("password");
parameters[3].val <<= CORBA::string_dup(myResources[3]);
pssInitializer_ = new PSSInitializer("PSS:connector:database:postgresql:1.0", (short)accessMode, parameters);
#endif
}
#ifndef LITE_VERSION
if( strcmp(pssFileName.in(), "") != 0 )
{
storageLoader_ = new StorageObjectLoader(persistenterPath, this);
storageLoader_->loadPSS();
}
#endif
//
//set HomeExecutor context
//
TRACE0(LEVEL6, "setting context for home executor\n");
CCM2Context_impl* ctxPtr = new CCM2Context_impl();
ctxPtr -> setContainerRunTime(this);
CORBA::String_var initialconnections;
CORBA::String_var maxconnections;
CORBA::String_var increment;
#ifdef WITH_OTS
if( hasToCreateResources )
{
initialconnections = CORBA::string_dup(myResources[4]);
maxconnections = CORBA::string_dup(myResources[5]);
increment = CORBA::string_dup(myResources[6]);
CORBA::ULong _initialCon;
CORBA::ULong _maxCon;
CORBA::ULong _inc;
_initialCon = atoi(initialconnections.in());
_maxCon = atoi(maxconnections.in());
_inc = atoi(increment.in());
resPool_ = ::STARCCM::ResourcePool_impl::getResPoolInstance(this,_initialCon,_maxCon,_inc);
ctxPtr -> setResourcePool(resPool_);
}
#endif
Components::CCM2Context_var ctx = ctxPtr;
homeExecutor->set_context( ctx );
TRACE0(LEVEL6, "end of setting context for home executor\n");
//register initial reference
CORBA::ORB_var orb = container_->getOrb();
CORBA::Object_var initial;
if( strcmp(nameService, "") != 0 )
{
TRACE0(LEVEL6, "register NameService\n");
configFile->addCosRef(serverId.in(), "NameService", nameService);
try
{
initial = orb->string_to_object(nameService);
if( (CORBA::is_nil(initial)) )
{
orb->register_initial_reference("NameService", initial);
}
}
catch(CORBA::ORB::InvalidName&)
{
TRACE0(LEVEL1, "Invalid service name : NameService\n");
}
catch(CORBA::BAD_PARAM&)
{
TRACE1(LEVEL1, "Bad NameService object reference : %s\n", nameService);
}
}
if( strcmp(homeFinder, "") != 0 )
{
TRACE0(LEVEL6, "register HomeFinder\n");
configFile->addCosRef(serverId.in(), "HomeFinder", homeFinder);
try
{
initial = orb->string_to_object(homeFinder);
if( (CORBA::is_nil(initial)) )
{
orb->register_initial_reference("HomeFinder", initial);
}
}
catch(CORBA::ORB::InvalidName&)
{
TRACE0(LEVEL1, "Invalid service name : HomeFinder\n");
}
catch(CORBA::BAD_PARAM&)
{
TRACE1(LEVEL1, "Bad HomeFinder object reference : %s\n", homeFinder);
}
}
if( strcmp(homeRegistration_, "") != 0 )
{
TRACE0(LEVEL6, "register HomeRegistration\n");
configFile->addCosRef(serverId.in(), "HomeRegistration", homeRegistration_);
try
{
initial = orb->string_to_object(homeRegistration_);
if( (CORBA::is_nil(initial)) )
{
orb->register_initial_reference("HomeRegistration", initial);
}
}
catch(CORBA::ORB::InvalidName&)
{
TRACE0(LEVEL1, "Invalid service name : HomeRegistration\n");
}
catch(CORBA::BAD_PARAM&)
{
TRACE1(LEVEL1, "Bad HomeRegistration object reference : %s\n", homeRegistration_);
}
}
if( strcmp(transactionService, "") != 0 )
{
TRACE0(LEVEL6, "register TransactionService\n");
configFile->addCosRef(serverId.in(), "TransactionService", transactionService);
try
{
initial = orb->string_to_object(transactionService);
if( (CORBA::is_nil(initial)) )
{
orb->register_initial_reference("TransactionService", initial);
}
}
catch(CORBA::ORB::InvalidName&)
{
TRACE0(LEVEL1, "Invalid service name : TransactionService\n");
}
catch(CORBA::BAD_PARAM&)
{
TRACE1(LEVEL1, "Bad TransactionService object reference : %s\n", transactionService);
}
}
if( strcmp(notificationService, "") != 0 )
{
TRACE0(LEVEL6, "register NotificationService\n");
configFile->addCosRef(serverId.in(), "NotificationService", notificationService);
try
{
initial = orb->string_to_object(notificationService);
if( (CORBA::is_nil(initial)) )
{
orb->register_initial_reference("NotificationService", initial);
}
}
catch(CORBA::ORB::InvalidName&)
{
TRACE0(LEVEL1, "Invalid service name : NotificationService\n");
}
catch(CORBA::BAD_PARAM&)
{
TRACE1(LEVEL1, "Bad NotificationService object reference : %s\n", notificationService);
}
}
//add by wsf
//to recorde the according archhome info
STARCCM::ArchHome ahome;
ahome.id = homeCompositionUUID_;
ahome.uuid = homeCompositionUUID_;
switch (componentKind)
{
case 0 : ahome.type = CORBA::string_dup("service");
break;
case 1 : ahome.type = CORBA::string_dup("session");
break;
case 2 : ahome.type = CORBA::string_dup("entity");
break;
case 3 : ahome.type = CORBA::string_dup("process");
break;
}
ahome.homeref = CORBA::Object::_duplicate(home);
ahome.homerepid = homeRepId_;
ahome.componentrepid = compRepId_;
/*
ahome.serveractivatorid = NULL;
ahome.serveractivatorref = NULL;
ahome.componentserverid = NULL;
ahome.componentserverref = NULL;
*/
ahome.containerid = container_->getUUID();
ahome.containerref = CORBA::Object::_duplicate(container_->getReference());
ahome.coms.length(0);
ahome.links.length(0);
container_ -> setArchHome(ahome);
//end by wsf
return home._retn();
}
ContainerType
ContainerRunTime::getContainerType()
{
return container_ -> getContainerType();
}
#ifndef LITE_VERSION
PSSInitializer_ptr
ContainerRunTime::getPssInitializer()
{
return OBJDUPLICATE(PSSInitializer_ptr, pssInitializer_);
}
#endif
//void
//ContainerRunTime::setResourcePool(::STARCCM::ResourcePool_ptr res)
//{
//#ifndef LITE_VERSION
// resPool_ = STARCCM::ResourcePool::_duplicate(res);
//#endif
//}
//added by xiao heping 2004/03/16
::GreenThread::CustomThreadPool_ptr
ContainerRunTime::GetCustomThreadPool()
{
#if defined(STARCCM_MTL)
return ::GreenThread::CustomThreadPool::_duplicate (threadPool_);
#else
return 0;
#endif
}
//end added xiao heping 2004/03/16
//to get the archcomponent infomation for the component just been created.
//wsf
void
ContainerRunTime::setArchComp(ComponentComposition_ptr comp)
{
//To add the according archcomponent info
STARCCM::ArchComponent acom;
PortableServer::ObjectId_var oid = comp->getObjectId();
acom.id = PortableServer::ObjectId_to_string(oid.in());
acom.uuid = PortableServer::ObjectId_to_string(oid.in());
acom.comref = CORBA::Object::_duplicate(comp->getComponentRef());
PortableServer::ObjectId_var hoid = getHomeObjectId();
acom.homeuuid = PortableServer::ObjectId_to_string(hoid.in());
acom.ports.length(0);
//get providesports info
int plen;
CORBA::Object_var obj= comp->getComponentRef();
Components::CCMObject_var ccmobj = Components::CCMObject::_narrow(obj);
Components::FacetDescriptions_var facets = ccmobj->get_all_facets();
int flen = facets->length();
STARCCM::Port port;
port.type = CORBA::string_dup("providesport");
int i = 0;
for (i=0; i<flen; i++)
{
port.name = facets[i]->name();
port.reference = CORBA::Object::_duplicate(facets[i]->facet_ref());
plen = acom.ports.length();
acom.ports.length(plen+1);
acom.ports[plen] = port;
}
//get consumesport info
Components::ConsumerDescriptions_var consumers = ccmobj->get_all_consumers();
int clen = consumers->length();
port.type = CORBA::string_dup("consumesport");
for (i=0; i<clen; i++)
{
port.name = consumers[i]->name();
port.reference = CORBA::Object::_duplicate(consumers[i]->consumer());
plen = acom.ports.length();
acom.ports.length(plen+1);
acom.ports[plen] = port;
}
acom.links.length(0);
addArchComponent(acom);
}
//wsf
void
ContainerRunTime::onConnect(STARCCM::ArchConnection& acon)
{
addArchConnection(acon);
}
//wsf
void
ContainerRunTime::onDisconnect(PortableServer::ObjectId* srcoid,
const char* featurename,
const char* ck)
{
deleteArchConnection(srcoid, featurename, ck);
}
//wsf
void
ContainerRunTime::addArchComponent(STARCCM::ArchComponent& archcom)
{
int len = aComponents.length();
aComponents.length(len+1);
aComponents[len] = archcom;
container_ -> setArchCom(archcom);
}
//wsf
void
ContainerRunTime::deleteArchComponent(const PortableServer::ObjectId* oid)
{
CORBA::String_var s = PortableServer::ObjectId_to_string(*oid);
int len = aComponents.length();
int i = 0;
for (i=0; i<len; i++)
if (strcmp(s.in(),aComponents[i].uuid) ==0 )
break;
if (i == len)
{
//add the component uuid to deletedcomslist
int dlen = deletedComslist.length();
deletedComslist.length(dlen+1);
deletedComslist[dlen] = s;
}
else
{
//To delete the component in aComponents
for (int j=i; j<len-1; j++)
aComponents[j] = aComponents[j+1];
aComponents.length(len-1);
}
}
//wsf
void
ContainerRunTime::addArchConnection(STARCCM::ArchConnection& connect)
{
int len = aConnections.length();
aConnections.length(len+1);
aConnections[len] = connect;
container_ -> setArchConn(connect);
}
//wsf
void
ContainerRunTime::deleteArchConnection(PortableServer::ObjectId* srcoid, const char* featurename, const char* cookie)
{
CORBA::String_var s = PortableServer::ObjectId_to_string(*srcoid);
int len = aConnections.length();
int i = 0;
for (i=0; i<len; i++)
{
if (cookie == NULL)
{
if ((strcmp(s.in(),aConnections[i].srccomuuid) ==0)&&(strcmp(featurename, aConnections[i].srcport) == 0))
break;
}
else
{
if (strcmp(cookie,aConnections[i].cookie) ==0)
break;
}
}
if (i == len)
{
//add connection info to deletedConnslist
STARCCM::ArchConnection dcon;
dcon.srccomuuid = s;
dcon.srcport = CORBA::string_dup(featurename);
dcon.cookie = CORBA::string_dup(cookie);
int dlen = deletedConnslist.length();
deletedConnslist.length(dlen+1);
deletedConnslist[dlen] = dcon;
}
else
{
//To delete the connection in aConnections
for (int j=i; j<len-1; j++)
aConnections[j] = aConnections[j+1];
aConnections.length(len-1);
}
}
//wsf
void
ContainerRunTime::updateArchitecture(STARCCM::ArchComponents_out addedcoms,
STARCCM::DeletedComs_out dcomslist,
STARCCM::ArchConnections_out addedconns,
STARCCM::ArchConnections_out dconnslist)
throw(CORBA::SystemException)
{
addedcoms = new STARCCM::ArchComponents(aComponents);
dcomslist = new STARCCM::DeletedComs(deletedComslist);
addedconns = new STARCCM::ArchConnections(aConnections);
dconnslist = new STARCCM::ArchConnections(deletedConnslist);
cleanArchObjects();
}
//wsf
void
ContainerRunTime::cleanArchObjects()
throw(CORBA::SystemException)
{
aComponents.length(0);
deletedComslist.length(0);
aConnections.length(0);
deletedConnslist.length(0);
}
::STARCCM::ResourcePool_ptr
ContainerRunTime::getResourcePool()
{
#ifndef LITE_VERSION
return ::STARCCM::ResourcePool::_duplicate(resPool_);
#else
return NULL;
#endif
}
//add by jxh 06/22
char* ContainerRunTime::getResourceName()
{
return CORBA::string_dup(resourceName.in());
}
//add by wsf 2004.6.30
void
ContainerRunTime::setRedirectReqInfo(const CORBA::StringSeq& oidList,
const Components::ObjectSeq& newObjList,
CORBA::Long timeout)
throw(CORBA::SystemException)
{
STARCCM_SYNCHRONIZED(sync_,redirectReqMapMonitor)
int len = oidList.length();
for (int i=0; i<len; i++)
{
CORBA::Object_var obj = CORBA::Object::_duplicate(newObjList[i]);
redirectReqMap.insert(MapRedirectReq::value_type(string(oidList[i]),obj));
}
STARCCM_THREAD_HANDLE(thread)
thread = new InfoDeleter(this,oidList,timeout);
thread->start();
}
void
ContainerRunTime::delRedirectReqInfo(const CORBA::StringSeq& oidList)
{
STARCCM_SYNCHRONIZED(sync_,redirectReqMapMonitor)
int len = oidList.length();
MapRedirectReq::iterator iter;
for (int i=0; i<len; i++)
{
iter = redirectReqMap.find(string(oidList[i]));
if (iter != redirectReqMap.end())
{
redirectReqMap.erase(iter);
}
}
}
void
ContainerRunTime::setRejectReqInfo(const CORBA::StringSeq& oidList)
{
STARCCM_SYNCHRONIZED(sync_,rejectReqMapMonitor)
int len = oidList.length();
for (int i=0; i<len; i++)
{
RejectReqMap.insert(MapRejectReq::value_type(string(oidList[i]),string(oidList[i])));
}
}
void
ContainerRunTime::removeRejectReqInfo(const CORBA::StringSeq& oidList)
{
STARCCM_SYNCHRONIZED(sync_,rejectReqMapMonitor)
int len = oidList.length();
MapRejectReq::iterator iter;
for (int i=0; i<len; i++)
{
iter = RejectReqMap.find(string(oidList[i]));
if (iter != RejectReqMap.end())
RejectReqMap.erase(iter);
}
}
void
ContainerRunTime::passivateClient(const CORBA::StringSeq& oidList,
const Components::Deployment::PassivateClientTypeSeq& typeList)
throw(CORBA::SystemException)
{
CORBA::StringSeq_var rejectList;
CORBA::StringSeq_var holdList;
int len = typeList.length();
int r=0;
int h=0;
for (int i=0; i<len; i++)
{
switch (typeList[i])
{
case Components::Deployment::REJECTREQUEST:
rejectList[r++] = oidList[i];
break;
case Components::Deployment::HOLDREQUEST:
holdList[h++] = oidList[i];
break;
}
}
setRejectReqInfo(rejectList);
// threadPool_->setHoldClientReqInfo(holdList);
// noRespReq(oidList);
}
void
ContainerRunTime::activateClient(const CORBA::StringSeq& oidList)
throw(CORBA::SystemException)
{
// threadPool_->removeHoldClientReqInfo(oidList);
removeRejectReqInfo(oidList);
}
//end by wsf 2004.6.30 | 28.506078 | 169 | 0.671784 | [
"object"
] |
6f267d3d4c14a70508d861c98b415cef4b407109 | 1,937 | cpp | C++ | neopg/openpgp/trust_packet.cpp | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 224 | 2017-10-29T09:48:00.000Z | 2021-07-21T10:27:14.000Z | neopg/openpgp/trust_packet.cpp | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 66 | 2017-10-29T16:17:55.000Z | 2020-11-30T18:53:40.000Z | neopg/openpgp/trust_packet.cpp | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 22 | 2017-10-29T19:55:45.000Z | 2020-01-04T13:25:50.000Z | // OpenPGP trust packet (implementation)
// Copyright 2017-2018 The NeoPG developers
//
// NeoPG is released under the Simplified BSD License (see license.txt)
#include <neopg/openpgp/packet_header.h>
#include <neopg/openpgp/trust_packet.h>
#include <neopg/intern/cplusplus.h>
#include <neopg/intern/pegtl.h>
using namespace NeoPG;
namespace NeoPG {
namespace trust_packet {
using namespace pegtl;
// Grammar
struct content : rep_max_any<TrustPacket::MAX_LENGTH> {};
struct grammar : must<content, eof> {};
// Action
template <typename Rule>
struct action : nothing<Rule> {};
template <>
struct action<content>
: bind<TrustPacket, std::vector<uint8_t>, &TrustPacket::m_data> {};
// Control
template <typename Rule>
struct control : pegtl::normal<Rule> {
static const std::string error_message;
template <typename Input, typename... States>
static void raise(const Input& in, States&&...) {
throw parser_error(error_message, in);
}
};
// Unreachable, because rep_max_any always succeeds. But pegtl does not know
// that, so add an error message to silence a compiler warning/error.
template <>
const std::string control<content>::error_message = "trust packet is invalid";
template <>
const std::string control<eof>::error_message = "trust packet is too large";
} // namespace trust_packet
} // namespace NeoPG
std::unique_ptr<TrustPacket> TrustPacket::create(ParserInput& in) {
try {
return TrustPacket::create_or_throw(in);
} catch (const ParserError&) {
return nullptr;
}
}
std::unique_ptr<TrustPacket> TrustPacket::create_or_throw(ParserInput& in) {
auto packet = NeoPG::make_unique<TrustPacket>();
pegtl::parse<trust_packet::grammar, trust_packet::action,
trust_packet::control>(in.m_impl->m_input, *packet.get());
return packet;
}
void TrustPacket::write_body(std::ostream& out) const {
out.write(reinterpret_cast<const char*>(m_data.data()), m_data.size());
}
| 27.28169 | 78 | 0.728962 | [
"vector"
] |
6f2da191ac98c52db33117d48e066371b8d08089 | 7,756 | cpp | C++ | openstudiocore/src/runmanager/app/FileSystemSearch.cpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/runmanager/app/FileSystemSearch.cpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/runmanager/app/FileSystemSearch.cpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | #include "FileSystemSearch.hpp"
#include <utilities/core/Application.hpp>
namespace openstudio {
namespace runmanager {
namespace detail {
void FileSystemSearchThread::run()
{
m_fileBuilder();
}
}
FileSystemSearch::FileSystemSearch(const openstudio::path &t_rootPath, bool t_recursive,
const std::string &t_fileExtension,
const QRegExp &t_regex)
: m_rootPath(t_rootPath), m_recursive(t_recursive), m_fileExtension(t_fileExtension),
m_regex(t_regex), m_header(new QStandardItem())
{
updateModel();
m_header->setEditable(true);
m_header->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled);
m_model.setHorizontalHeaderItem(0, m_header);
}
bool FileSystemSearch::recursive() const
{
return m_recursive;
}
void FileSystemSearch::setRecursive(bool t_recursive)
{
if (m_recursive != t_recursive)
{
m_recursive = t_recursive;
updateModel();
}
}
openstudio::path FileSystemSearch::rootPath() const
{
return m_rootPath;
}
void FileSystemSearch::setRootPath(const openstudio::path &t_rootPath)
{
if (m_rootPath != t_rootPath)
{
m_rootPath = t_rootPath;
emit rootPathChanged(m_rootPath);
updateModel();
}
}
QRegExp FileSystemSearch::regex() const
{
return m_regex;
}
void FileSystemSearch::setRegex(const QRegExp &t_regex)
{
if (m_regex != t_regex)
{
m_regex = t_regex;
LOG(Debug, "New regex " << toString(m_regex.pattern()));
updateModel();
}
}
std::string FileSystemSearch::fileExtension() const
{
return m_fileExtension;
}
void FileSystemSearch::threadFinished()
{
emit searchComplete();
}
void FileSystemSearch::setFileExtension(const std::string &t_fileExtension)
{
if (m_fileExtension != t_fileExtension)
{
m_fileExtension = t_fileExtension;
updateModel();
}
}
void FileSystemSearch::fileFoundSlot(const QString &filestring)
{
//LOG(Debug, "FileFoundSlot " << toString(filestring) << " thread: " << QThread::currentThreadId());
if (sender() && sender() == m_thread.get())
{
if (m_model.findItems(filestring).empty())
{
// Make sure the signal is coming from the thread we expect it to, and it's not just queued up
QStandardItem *qsi = new QStandardItem(filestring);
qsi->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsEnabled);
qsi->setCheckable(true);
qsi->setCheckState(Qt::Unchecked);
m_model.appendRow(qsi);
m_model.sort(0);
}
}
}
void FileSystemSearch::selectAll()
{
for (int i = 0; i < m_model.rowCount(); ++i)
{
m_model.item(i)->setCheckState(Qt::Checked);
}
}
void FileSystemSearch::select(const QModelIndexList &qmi)
{
for (QModelIndexList::const_iterator itr = qmi.begin();
itr != qmi.end();
++itr)
{
m_model.itemFromIndex(*itr)->setCheckState(Qt::Checked);
}
}
void FileSystemSearch::selectNone()
{
for (int i = 0; i < m_model.rowCount(); ++i)
{
m_model.item(i)->setCheckState(Qt::Unchecked);
}
}
void FileSystemSearch::invertSelection()
{
for (int i = 0; i < m_model.rowCount(); ++i)
{
QStandardItem *item = m_model.item(i);
item->setCheckState(item->checkState()==Qt::Checked?Qt::Unchecked:Qt::Checked);
}
}
void FileSystemSearch::updateModel()
{
openstudio::path root(m_rootPath);
if (!root.empty())
{
openstudio::path::const_iterator itr = root.end();
--itr;
if (itr != root.begin() && (itr->empty() || *itr == toPath(".")))
{
root = root.parent_path();
}
}
if (m_thread)
{
if (m_thread->isRunning())
{
LOG(Info, "FileSystemSearchThread is running, interrupting");
}
m_thread->disconnect();
m_thread->cancel();
m_thread->quit();
m_thread->wait();
//Can we eat all of the pending messages from the thread before we continue??
// openstudio::Application::instance().processEvents();
m_thread.reset();
LOG(Info, "FileSystemSearchThread completed");
}
if (!m_regex.isValid())
{
m_header->setText("Error in search pattern");
emit errorInRegex(m_regex.errorString());
} else {
emit errorInRegex("");
QString p = toQString(m_rootPath.external_file_string());
if (!p.endsWith(boost::filesystem::slash<openstudio::path>::value))
{
p += boost::filesystem::slash<openstudio::path>::value;
}
m_header->setText(p);
}
try {
if (m_rootPath.empty() || !boost::filesystem::exists(m_rootPath) || !boost::filesystem::is_directory(m_rootPath))
{
return;
}
} catch (const std::exception &) {
m_model.removeRows(0, m_model.rowCount());
return;
}
if (!m_regex.isValid())
{
return;
}
if (m_recursive)
{
typedef boost::filesystem::basic_recursive_directory_iterator<openstudio::path> diritr;
try {
diritr begin(root);
diritr end;
m_thread = boost::shared_ptr<detail::FileSystemSearchThread>(new detail::FileSystemSearchThread(
root, begin, end, m_regex, m_fileExtension));
} catch (const boost::filesystem::basic_filesystem_error<openstudio::path> &e) {
LOG(Info, "Error browsing path: " << toString(root) << ": " << e.what());
return;
}
} else {
typedef boost::filesystem::basic_directory_iterator<openstudio::path> diritr;
try {
diritr begin(root);
diritr end;
m_thread = boost::shared_ptr<detail::FileSystemSearchThread>(new detail::FileSystemSearchThread(
root, begin, end, m_regex, m_fileExtension));
} catch (const boost::filesystem::basic_filesystem_error<openstudio::path> &e) {
LOG(Info, "Error browsing path: " << toString(root) << ": " << e.what());
return;
}
}
connect(m_thread.get(), SIGNAL(fileFound(const QString &)), this, SLOT(fileFoundSlot(const QString &)));
connect(m_thread.get(), SIGNAL(finished()), this, SLOT(threadFinished()));
emit searchStarted();
m_model.removeRows(0, m_model.rowCount());
m_thread->start();
}
std::vector<openstudio::path> FileSystemSearch::selectedFiles()
{
std::vector<openstudio::path> results;
int rowCount = m_model.rowCount();
for (int i = 0; i < rowCount; ++i)
{
QStandardItem *qsi = m_model.item(i);
if (qsi->checkState() == Qt::Checked)
{
results.push_back(m_rootPath / toPath(qsi->text()));
}
}
return results;
}
std::vector<openstudio::path> FileSystemSearch::foundFiles()
{
std::vector<openstudio::path> results;
int rowCount = m_model.rowCount();
for (int i = 0; i < rowCount; ++i)
{
QStandardItem *qsi = m_model.item(i);
results.push_back(m_rootPath / toPath(qsi->text()));
}
return results;
}
QAbstractItemModel *FileSystemSearch::getQItemModel()
{
return &m_model;
}
openstudio::path FileSystemSearch::getFile(const QModelIndex &idx)
{
QStandardItem *qsi = m_model.itemFromIndex(idx);
if (qsi)
{
return m_rootPath / toPath(qsi->text());
}
throw std::out_of_range("Not a valid item");
}
}
}
| 24.779553 | 120 | 0.59541 | [
"vector"
] |
6f2e8f62137dce9154cf12fc7673b4a77a40fd92 | 14,590 | cpp | C++ | modules/unzip/classes/lua_unzip.cpp | xxzhushou/CExt_Android | de5a752f52d71b5d6dc1f2e12a7f2ac58704c44a | [
"MIT"
] | 9 | 2018-10-11T09:55:57.000Z | 2018-10-11T10:54:21.000Z | modules/unzip/classes/lua_unzip.cpp | xxzhushou/CExt_Android | de5a752f52d71b5d6dc1f2e12a7f2ac58704c44a | [
"MIT"
] | 1 | 2020-07-31T07:39:06.000Z | 2020-07-31T07:39:06.000Z | modules/unzip/classes/lua_unzip.cpp | xxzhushou/CExt_Android | de5a752f52d71b5d6dc1f2e12a7f2ac58704c44a | [
"MIT"
] | 9 | 2018-12-26T13:13:36.000Z | 2022-03-27T10:26:27.000Z |
#include <time.h>
#include <string.h>
#include "XModExtSupport.h"
#include "unzip.h"
#define MAXFILENAME (256)
#define BUFFER_SIZE 1024
typedef struct {
int zipref; // userdata
int nameref;
int pos, end;
char buffer[BUFFER_SIZE];
} t_zipentry, *p_zipentry;
typedef struct {
unzFile uf;
int current_nameref;
} t_zipfile, *p_zipfile;
int zipfile_close(lua_State* L)
{
p_zipfile zip = (p_zipfile)luaL_checkudata(L, 1, "LuaZ:UnZip");
if (zip->uf) {
if (zip->current_nameref != LUA_NOREF) {
unzCloseCurrentFile(zip->uf);
zip->current_nameref = LUA_NOREF;
}
unzClose(zip->uf);
zip->uf = NULL;
}
return 0;
}
int zipentry_close(lua_State *L)
{
p_zipentry zent = (p_zipentry)luaL_checkudata(L, 1, "LuaZ:UnZip:Entry");
// release zip file
if (zent->zipref != LUA_NOREF) {
p_zipfile zip;
lua_rawgeti(L, LUA_REGISTRYINDEX, zent->zipref);
zip = (p_zipfile)luaL_checkudata(L, -1, "LuaZ:UnZip");
if (zip->uf != NULL && zip->current_nameref == zent->nameref) {
unzCloseCurrentFile(zip->uf);
zip->current_nameref = LUA_NOREF;
}
}
if (zent->zipref != LUA_NOREF) {
luaL_unref(L, LUA_REGISTRYINDEX, zent->zipref);
zent->zipref = LUA_NOREF;
luaL_unref(L, LUA_REGISTRYINDEX, zent->nameref);
zent->nameref = LUA_NOREF;
}
return 0;
}
int zipfile_open(lua_State* L)
{
unzFile uf=NULL;
p_zipfile zip=NULL;
const char *zipname = luaL_checkstring(L, 1);
printf("reading %s\n", zipname);
uf = unzOpen(zipname);
if (uf == NULL) {
lua_pushnil(L);
lua_pushstring(L, "notfound");
return 2;
}
zip = (p_zipfile)lua_newuserdata(L, sizeof(t_zipfile));
if (!zip) {
lua_pushnil(L);
lua_pushstring(L, "error creating ZIP object");
unzClose(uf);
return 2;
}
// initialize it!
zip->uf = uf;
zip->current_nameref = LUA_NOREF;
luaL_getmetatable(L, "LuaZ:UnZip");
lua_setmetatable(L, -2);
return 1;
}
static int zipfile_tostring(lua_State* L)
{
p_zipfile zip = (p_zipfile)luaL_checkudata(L, 1, "LuaZ:UnZip");
lua_pushfstring(L, "ZipFile %p, open=%s",
zip,
(zip->uf ? "true" : "false"));
return 1;
}
static void stackDump (lua_State *L) {
int i;
int top = lua_gettop(L);
for(i=1;i<=top;i++){ /*repeatforeachlevel*/
int t = lua_type(L, i);
switch (t) {
case LUA_TSTRING: { /* strings */
printf("’%s’", lua_tostring(L, i));
break;
}
case LUA_TBOOLEAN: { /* booleans */
printf(lua_toboolean(L, i) ? "true" : "false");
break; }
case LUA_TNUMBER: { /* numbers */
printf("%g", lua_tonumber(L, i));
break;
}
default: { /* other values */
printf("%s", lua_typename(L, t));
break; }
}
printf(" "); /* put a separator */
}
printf("\n"); /* end the listing */
}
int zipentry_open(lua_State* L)
{
p_zipfile zip = (p_zipfile)luaL_checkudata(L, 1, "LuaZ:UnZip");
const char* filename = luaL_checkstring(L, 2);
int ignorecase = luaL_optint(L, 3, 0);
p_zipentry zent;
int err;
if (zip->uf == NULL) {
lua_pushnil(L);
lua_pushstring(L, "closed");
return 2;
}
// there can only be one open at a time...
if (zip->current_nameref != LUA_NOREF) {
err = unzCloseCurrentFile(zip->uf);
if (err != UNZ_OK) { lua_pushnil(L); lua_pushfstring(L, "zerror:close (%d)", err); return 2; }
zip->current_nameref = LUA_NOREF;
}
err = unzLocateFile(zip->uf, filename, ignorecase);
if (err != UNZ_OK) {
lua_pushnil(L);
lua_pushstring(L, "notfound");
return 2;
}
err = unzOpenCurrentFile(zip->uf);
if (err != UNZ_OK) { lua_pushnil(L); lua_pushfstring(L, "zerror:open (%d)", err); return 2; }
zent = (p_zipentry) lua_newuserdata(L, sizeof(t_zipentry));
luaL_getmetatable(L, "LuaZ:UnZip:Entry");
lua_setmetatable(L, -2);
// keep a reference to the ZipFile so it doesn't get GC'd
lua_pushvalue(L, 1);
zent->zipref = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushvalue(L, 2);
zent->nameref = luaL_ref(L, LUA_REGISTRYINDEX);
zent->pos = 0;
zent->end = 0;
zip->current_nameref = zent->nameref;
printf ("/** STACK **/\n");
stackDump(L);
return 1;
}
static int zipentry_tostring(lua_State* L)
{
const char *name = "<none>";
p_zipentry zent = (p_zipentry)luaL_checkudata(L, 1, "LuaZ:UnZip:Entry");
p_zipfile zip = NULL;
if (zent->nameref != LUA_NOREF) {
lua_rawgeti(L, LUA_REGISTRYINDEX, zent->nameref);
name = luaL_checkstring(L, -1);
}
if (zent->zipref != LUA_NOREF) {
lua_rawgeti(L, LUA_REGISTRYINDEX, zent->zipref);
zip = (p_zipfile)luaL_checkudata(L, -1, "LuaZ:UnZip");
}
lua_pushfstring(L, "ZipEntry %p name=%s (of %p)", zent, name, zip);
return 1;
}
#ifndef min
#define min(X,Y) ((X)<(Y)?(X):(Y))
#endif
int
zipentry_read(lua_State* L)
{
int read_all = 0;
int read_N = 0;
int read_some = 0;
int read_line = 0;
int top = lua_gettop(L);
p_zipentry zent = (p_zipentry)luaL_checkudata(L, 1, "LuaZ:UnZip:Entry");
p_zipfile zip;
if (!lua_isnumber(L, 2)) {
const char *p= luaL_optstring(L, 2, "*l");
if (p[0] == '*' && p[1] == 'l') {
read_line = 1;
} else if (p[0] == '*' && p[1] == 'a') {
read_all = 1;
} else if (p[0] == '*' && p[1] == 'b') {
read_some = 1;
} else {
luaL_argcheck(L, 0, 2, "invalid read pattern");
}
} else {
double n = lua_tonumber(L, 2);
read_N = (size_t)n;
luaL_argcheck(L, n >= 0, 2, "invalid read pattern");
}
if(zent->zipref == LUA_NOREF)
{
lua_pushnil(L);
lua_pushstring(L, "closed");
return 2;
}
lua_rawgeti(L, LUA_REGISTRYINDEX, zent->zipref);
zip = (p_zipfile)luaL_checkudata(L, -1, "LuaZ:UnZip");
if (zip->uf == NULL)
{
lua_pushnil(L);
lua_pushstring(L, "closed");
return 2;
}
if (zip->current_nameref == zent->nameref)
{
/* we're good */
}
else
{
int err;
const char *filename;
if (zip->current_nameref != LUA_NOREF) {
err = unzCloseCurrentFile(zip->uf);
if (err != UNZ_OK) { lua_pushnil(L); lua_pushfstring(L, "zerror (%d)", err); return 2; }
zip->current_nameref = LUA_NOREF;
}
lua_rawgeti(L, LUA_REGISTRYINDEX, zent->nameref);
filename = luaL_checkstring(L, -1);
err = unzLocateFile(zip->uf, filename, 0);
if (err != UNZ_OK) {
lua_pushnil(L);
lua_pushstring(L, "notfound");
return 2;
}
err = unzOpenCurrentFile(zip->uf);
if (err != UNZ_OK) { lua_pushnil(L); lua_pushfstring(L, "zerror:ocf (%d)", err); return 2; }
zip->current_nameref = zent->nameref;
/* skip to offset? */
}
if (read_some)
{
long n;
luaL_Buffer buf;
char *raw;
luaL_buffinit(L, &buf);
luaL_addlstring(&buf, &zent->buffer[zent->pos], zent->end - zent->pos);
zent->end = zent->pos = 0;
raw = luaL_prepbuffer(&buf);
n = unzReadCurrentFile(zip->uf, raw, LUAL_BUFFERSIZE);
if (n >= 0) {
luaL_addsize(&buf, n);
} else {
lua_pushnil(L);
lua_pushfstring(L, "readerror (%d)", n);
return 2;
}
if (n == 0) {
lua_pushnil(L);
lua_pushstring(L, "eof");
return 2;
} else {
luaL_pushresult(&buf);
return 1;
}
} else if (read_line) {
int err = 0;
luaL_Buffer buf;
luaL_buffinit(L, &buf);
do {
/*scan for newline*/
while (zent->pos < zent->end) {
char ch = zent->buffer[zent->pos];
if (ch == '\n') {
zent->pos += 1;
luaL_pushresult(&buf);
return 1;
} else if (ch == '\r') {
continue;
} else {
luaL_addchar(&buf, ch);
zent->pos += 1;
}
}
/*fill input*/
err = unzReadCurrentFile(zip->uf, zent->buffer, BUFFER_SIZE);
zent->pos = 0;
if (err >= 0)
zent->end = err;
else
{
lua_pushnil(L);
lua_pushstring(L, "readerror");
return 2;
}
} while (err > 0);
if (err == 0) {
lua_pushnil(L);
lua_pushstring(L, "eof");
return 2;
} else {
luaL_pushresult(&buf);
return 1;
}
} else if (read_N > 0) {
int err = 0;
size_t n;
luaL_Buffer buf;
luaL_buffinit(L, &buf);
do {
n = min(zent->end-zent->pos, read_N);
if (n > 0) {
luaL_addlstring(&buf, &zent->buffer[zent->pos], n);
zent->pos += n;
luaL_addsize(&buf, n);
read_N -= n;
}
if (read_N > 0) {
err = unzReadCurrentFile(zip->uf, zent->buffer, BUFFER_SIZE);
zent->pos = 0;
if (err >= 0)
zent->end = err;
}
} while (read_N > 0 && err > 0);
luaL_pushresult(&buf);
return 1;
} else {
lua_pushnil(L);
lua_pushstring(L, "badarg");
return 2;
}
}
int push_fileinfo(lua_State* L, const char *name, unz_file_info *file_info)
{
lua_newtable(L);
lua_pushstring(L, name);
lua_setfield(L, -2, "filename");
lua_pushnumber(L, file_info->compressed_size);
lua_setfield(L, -2, "compressed_size");
lua_pushnumber(L, file_info->uncompressed_size);
lua_setfield(L, -2, "uncompressed_size");
{
struct tm newdate;
time_t t;
tm_unz *date = &file_info->tmu_date;
newdate.tm_sec = date->tm_sec;
newdate.tm_min=date->tm_min;
newdate.tm_hour=date->tm_hour;
newdate.tm_mday=date->tm_mday;
newdate.tm_mon=date->tm_mon;
if (date->tm_year > 1900)
newdate.tm_year=date->tm_year - 1900;
else
newdate.tm_year=date->tm_year ;
newdate.tm_isdst=-1;
t = mktime(&newdate);
lua_pushnumber(L, t);
lua_setfield(L, -2, "time");
}
return 0;
}
int
zipfile_list(lua_State* L)
{
p_zipfile zip = (p_zipfile)luaL_checkudata(L, 1, "LuaZ:UnZip");
uLong i;
unz_global_info gi;
int err;
if (zip->uf == NULL) {
lua_pushnil(L);
lua_pushstring(L, "closed");
return 2;
}
if (zip->current_nameref != LUA_NOREF) {
err = unzCloseCurrentFile(zip->uf);
zip->current_nameref = LUA_NOREF;
}
err = unzGetGlobalInfo(zip->uf,&gi);
if (err != UNZ_OK) {
lua_pushnil(L);
lua_pushstring(L, "error in GetGlobalInfo");
return 2;
}
err = unzGoToFirstFile(zip->uf);
if (err != UNZ_OK) {
lua_pushnil(L);
lua_pushstring(L, "error in GoToFirstFile");
return 2;
}
lua_newtable(L);
for (i=0;i<gi.number_entry;i++)
{
char filename_inzip[256];
unz_file_info file_info;
uLong ratio=0;
char charCrypt=' ';
err = unzGetCurrentFileInfo(zip->uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK) {
char buffer[256];
sprintf(buffer, "error %d in GetCurrentFileInfo", err);
lua_pushnil(L);
lua_pushstring(L, buffer);
return 2;
}
push_fileinfo(L, filename_inzip, &file_info);
lua_rawseti(L, -2, i+1);
if ((i+1)<gi.number_entry) {
err = unzGoToNextFile(zip->uf);
if (err!=UNZ_OK) {
char buffer[256];
sprintf(buffer, "error %d in GoToNextFile", err);
lua_pushnil(L);
lua_pushstring(L, buffer);
return 2;
}
}
}
return 1;
}
static int file_iter(lua_State* L)
{
int idx = lua_tointeger(L, lua_upvalueindex(2));
idx += 1;
lua_pushinteger(L, idx);
lua_replace(L, lua_upvalueindex(2));
lua_rawgeti(L, lua_upvalueindex(1), idx);
return 1;
}
int
zipfile_files(lua_State* L)
{
int num = zipfile_list(L);
if (num != 1) return num;
lua_pushinteger(L, 0);
lua_pushcclosure(L, &file_iter, 2);
return 1;
}
int
zipfile_read(lua_State* L)
{
p_zipfile zip = (p_zipfile)luaL_checkudata(L, 1, "LuaZ:UnZip");
const char* filename = luaL_checkstring(L, 2);
int ignorecase = luaL_optint(L, 3, 0);
int is_open = 0;
char *content = NULL;
int err;
if (zip->uf == NULL) {
lua_pushnil(L);
lua_pushstring(L, "closed");
return 2;
}
if (zip->current_nameref != LUA_NOREF) {
unzCloseCurrentFile(zip->uf);
zip->current_nameref = LUA_NOREF;
}
err = unzLocateFile(zip->uf, filename, ignorecase);
if (err != UNZ_OK) { goto error; }
{
char filename_inzip[256];
unz_file_info file_info;
err = unzGetCurrentFileInfo(zip->uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err != UNZ_OK) goto error;
content = (char*)malloc ( file_info.uncompressed_size );
if (content == NULL) {
lua_pushnil(L);
lua_pushstring(L, "malloc");
return 2;
}
err = unzOpenCurrentFile(zip->uf);
if (err != UNZ_OK) { free (content); content=NULL; goto error; }
is_open = 1;
{
int n;
int pos = 0;
do {
n = unzReadCurrentFile(zip->uf, content+pos, 1024);
if (n>0) pos += n;
} while (n > 0);
lua_pushlstring(L, content, file_info.uncompressed_size);
free (content);
unzCloseCurrentFile(zip->uf);
return 1;
}
}
error:
if (is_open) {
unzCloseCurrentFile(zip->uf);
}
if (content) {
free (content);
}
lua_pushnil(L);
lua_pushstring(L, "notfound");
return 2;
}
static luaL_Reg core_funcs[] = {
{"open", zipfile_open},
{NULL, NULL}
};
static luaL_Reg zipfile_meta[] = {
{"__gc", zipfile_close},
{"__tostring", zipfile_tostring},
{NULL, NULL}
};
static luaL_Reg zipfile_methods[] = {
{"files", zipfile_files},
{"list", zipfile_list},
{"read", zipfile_read},
{"close", zipfile_close},
{"open", zipentry_open},
{NULL, NULL}
};
static luaL_Reg zipentry_meta[] = {
{"__gc", zipentry_close},
{"__tostring", zipentry_tostring},
{NULL, NULL}
};
static luaL_Reg zipentry_methods[] = {
{"close", zipentry_close},
{"read", zipentry_read},
{NULL, NULL}
};
extern "C" __attribute__((visibility("default")))
int luaopen_unzip(lua_State *L)
{
/* Register the functions and tables */
luaL_newmetatable(L, "LuaZ:UnZip");
luaL_register(L, NULL, zipfile_meta);
lua_newtable(L);
luaL_register(L, NULL, zipfile_methods);
lua_setfield(L, -2, "__index");
lua_pop(L, 1);
/* Register the functions and tables */
luaL_newmetatable(L, "LuaZ:UnZip:Entry");
luaL_register(L, NULL, zipentry_meta);
lua_newtable(L);
luaL_register(L, NULL, zipentry_methods);
lua_setfield(L, -2, "__index");
lua_pop(L, 1);
lua_newtable(L);
luaL_register(L, "unzip", core_funcs);
return 1;
}
| 22.207002 | 106 | 0.589034 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.