hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
28d64eea4e63951387dac634b5f96eeae38f0569
1,753
cpp
C++
hash table/36 Valid Sudoku.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
hash table/36 Valid Sudoku.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
hash table/36 Valid Sudoku.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
// // 36 Valid Sudoku.cpp // Leetcode // // Created by Quinn on 2020/8/12. // Copyright © 2020 Quinn. All rights reserved. // #include <vector> #include <unordered_map> using namespace std; class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { bool state[10]; for(int i = 0; i < 9; i++) // 行 { memset(state, 0, sizeof state); for(int j = 0; j < 9; j++) { if(board[i][j] != '.') { int t = board[i][j] - '0'; if(state[t]) return false; state[t] = true; } } } for(int i = 0; i < 9; i++) // 列 { memset(state, 0, sizeof state); for(int j = 0; j < 9; j++) { if(board[j][i] != '.') { int t = board[j][i] - '0'; if(state[t]) return false; state[t] = true; } } } for(int i = 0; i < 9; i += 3) // 扫描小方格 { for(int j = 0; j < 9; j += 3) { memset(state, 0, sizeof state); for(int x = 0; x < 3; x++) { for(int y = 0; y < 3; y++) { if(board[i + x][j + y] != '.') { int t = board[i + x][j + y] - '0'; if(state[t]) return false; state[t] = true; } } } } } return true; } };
25.042857
62
0.302339
CoderQuinnYoung
28d77e9564225e08a0bc5085c7bc8bd52f15bbb5
508
cpp
C++
Framerate.cpp
Mac21/pillpopper
6941d0a5cb32e326da2ecf47dc3b9a1e4272af59
[ "MIT" ]
null
null
null
Framerate.cpp
Mac21/pillpopper
6941d0a5cb32e326da2ecf47dc3b9a1e4272af59
[ "MIT" ]
null
null
null
Framerate.cpp
Mac21/pillpopper
6941d0a5cb32e326da2ecf47dc3b9a1e4272af59
[ "MIT" ]
null
null
null
#include "Framerate.hpp" Framerate::Framerate() { sf::Font f; if (!f.loadFromFile("assets/Ubuntu-R.ttf")) { std::cout << "Failed to load font file\n"; exit(EXIT_FAILURE); } font = f; sf::Text t; t.setFont(font); t.setString("Framerate: 0"); fontText = t; } void Framerate::update(sf::Time interpolation, sf::Time t, sf::Time dt) { } void Framerate::setText(std::string s) { fontText.setString("Framerate: "+s); } sf::Text Framerate::getText() { return fontText; }
18.142857
73
0.625984
Mac21
28da08917b6d6495624924bd1d887fe6279b86f5
16,177
cpp
C++
components/ESC/src/FuelGauge.cpp
xmrhaelan/turpial-firmware
1ac3fd01448e2bf1061cb67f47d20d12d9b2e13c
[ "Apache-2.0" ]
null
null
null
components/ESC/src/FuelGauge.cpp
xmrhaelan/turpial-firmware
1ac3fd01448e2bf1061cb67f47d20d12d9b2e13c
[ "Apache-2.0" ]
null
null
null
components/ESC/src/FuelGauge.cpp
xmrhaelan/turpial-firmware
1ac3fd01448e2bf1061cb67f47d20d12d9b2e13c
[ "Apache-2.0" ]
null
null
null
/** * @file FuelGauge.cpp * @author Locha Mesh project developers (locha.io) * @brief * @version 0.1 * @date 2019-12-17 * * @copyright Copyright (c) 2019 Locha Mesh project * */ #include "FuelGauge.h" #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <esp_err.h> #include <esp_log.h> #include <esp_system.h> #include <ErrUtil.h> #include "BQ27441_Constants.h" namespace esc { static const char* TAG = "ESC"; static const i2c_port_t I2C_PORT = I2C_NUM_0; static const int I2C_FREQUENCY = 100000; static const gpio_num_t I2C_SDA_PIN = GPIO_NUM_23; static const gpio_num_t I2C_SCL_PIN = GPIO_NUM_22; static const TickType_t I2C_TIMEOUT = 2000; template <typename T> static T constrain(T value, T min, T max) { if (value < min) { return min; } if (value > max) { return max; } return value; } FuelGauge::FuelGauge() : m_conf{}, m_seal_again(false), m_manual_config(false) { m_conf.mode = I2C_MODE_MASTER; m_conf.sda_io_num = I2C_SDA_PIN; m_conf.sda_pullup_en = GPIO_PULLUP_DISABLE; m_conf.scl_io_num = I2C_SCL_PIN; m_conf.scl_pullup_en = GPIO_PULLUP_DISABLE; m_conf.master.clk_speed = I2C_FREQUENCY; } esp_err_t FuelGauge::temperature(TempMeasure type, std::uint16_t* temp) { switch (type) { case TempMeasure::Battery: ESP_ERR_TRY(readWord(TEMP, temp)); break; case TempMeasure::Internal: ESP_ERR_TRY(readWord(INT_TEMP, temp)); break; } return ESP_OK; } esp_err_t FuelGauge::voltage(std::uint16_t* voltage) { return readWord(VOLTAGE, voltage); } esp_err_t FuelGauge::avgCurrent(std::int16_t* avg_current) { return readWord(AVG_CURRENT, reinterpret_cast<std::uint16_t*>(avg_current)); } esp_err_t FuelGauge::avgPower(std::int16_t* avg_power) { return readWord(AVG_POWER, reinterpret_cast<std::uint16_t*>(avg_power)); } esp_err_t FuelGauge::soc(SocMeasure type, std::uint16_t* soc) { switch (type) { case SocMeasure::Filtered: return readWord(SOC, soc); break; case SocMeasure::Unfiltered: return readWord(SOC_UNFL, soc); break; default: return ESP_FAIL; break; } return ESP_OK; } esp_err_t FuelGauge::setCapacity(std::uint16_t capacity) { // Write to STATE subclass (82) of FuelGauge extended memory. // Offset 0x0A (10) // Design capacity is a 2-byte piece of data - MSB first std::uint8_t cap_msb = capacity >> 8; std::uint8_t cap_lsb = capacity & 0x00FF; std::uint8_t capacity_data[2] = {cap_msb, cap_lsb}; return writeExtendedData(ID_STATE, 10, capacity_data, 2); } esp_err_t FuelGauge::status(std::uint16_t* result) { return readControlWord(STATUS, result); } esp_err_t FuelGauge::flags(std::uint16_t* result) { return readWord(FLAGS, result); } esp_err_t FuelGauge::GPOUTPolarity(bool* value) { if (value == nullptr) return ESP_FAIL; std::uint16_t opconfig = 0; ESP_ERR_TRY(opConfig(&opconfig)); *value = (opconfig & OPCONFIG_GPIOPOL) == OPCONFIG_GPIOPOL; return ESP_OK; } esp_err_t FuelGauge::setGPOUTPolarity(bool active_high) { std::uint16_t old_opconfig = 0; ESP_ERR_TRY(opConfig(&old_opconfig)); bool already_high = (active_high && (old_opconfig & OPCONFIG_GPIOPOL)); bool already_low = (!active_high && !(old_opconfig & OPCONFIG_GPIOPOL)); if (already_high || already_low) return ESP_OK; uint16_t new_opconfig = old_opconfig; if (active_high) { new_opconfig |= OPCONFIG_GPIOPOL; } else { new_opconfig &= ~(OPCONFIG_GPIOPOL); } ESP_ERR_TRY(writeOpConfig(new_opconfig)); return ESP_OK; } esp_err_t FuelGauge::GPOUTFunction(bool* function) { if (function == nullptr) return ESP_FAIL; std::uint16_t opconfig = 0; ESP_ERR_TRY(opConfig(&opconfig)); *function = ((opconfig & OPCONFIG_BATLOWEN) == OPCONFIG_BATLOWEN); return ESP_OK; } esp_err_t FuelGauge::setGPOUTFunction(bool function) { std::uint16_t old_opconfig = 0; ESP_ERR_TRY(opConfig(&old_opconfig)); bool is_bat_low = (function && (old_opconfig & OPCONFIG_BATLOWEN)); bool is_soc_int = (!function && !(old_opconfig & OPCONFIG_BATLOWEN)); if (is_bat_low || is_soc_int) return ESP_OK; std::uint16_t new_opconfig = old_opconfig; if (function == BAT_LOW) { new_opconfig |= OPCONFIG_BATLOWEN; } else { new_opconfig &= ~(OPCONFIG_BATLOWEN); } ESP_ERR_TRY(writeOpConfig(new_opconfig)); return ESP_OK; } esp_err_t FuelGauge::sociDelta(std::uint8_t* value) { if (value == nullptr) return ESP_FAIL; std::uint8_t soci = 0; ESP_ERR_TRY(readExtendedData(ID_STATE, 26, &soci)); return ESP_OK; } esp_err_t FuelGauge::setSOCIDelta(std::uint8_t delta) { std::uint8_t soci = constrain<std::uint8_t>(delta, 0, 100); return writeExtendedData(ID_STATE, 26, &soci, 1); } esp_err_t FuelGauge::pulseGPOUT() { return executeControlWord(PULSE_SOC_INT); } esp_err_t FuelGauge::sealed(bool* is_sealed) { std::uint16_t stat = 0; ESP_ERR_TRY(status(&stat)); *is_sealed = (stat & STATUS_SS) == STATUS_SS; return ESP_OK; } esp_err_t FuelGauge::seal(std::uint16_t* result) { return readControlWord(SEALED, result); } esp_err_t FuelGauge::unseal(std::uint16_t* result) { // To unseal the FuelGauge, write the key to the control // command. Then immediately write the same key to control again. ESP_ERR_TRY(readControlWord(UNSEAL_KEY, result)); return readControlWord(UNSEAL_KEY, result); } esp_err_t FuelGauge::enterConfig(bool manual_config) { bool is_sealed = false; ESP_ERR_TRY(sealed(&is_sealed)); if (is_sealed) { // Must be unsealed before making changes std::uint16_t res = 0; ESP_ERR_TRY(unseal(&res)); m_seal_again = true; // Wait 2 s to get values updated. vTaskDelay(pdMS_TO_TICKS(2000)); } ESP_ERR_TRY(executeControlWord(SET_CFG_UPDATE)); std::int16_t timeout = I2C_TIMEOUT; while (timeout != 0) { vTaskDelay(1); std::uint16_t flags_res = 0; ESP_ERR_TRY(flags(&flags_res)); if (flags_res & FLAG_CFGUPMODE) { // We are now in CFG update mode. m_manual_config = manual_config; return ESP_OK; } timeout -= 1; } // Timeout reached, no change in mode. return ESP_FAIL; } esp_err_t FuelGauge::exitConfig(bool resim) { // There are two methods for exiting config mode: // 1. Execute the EXIT_CFGUPDATE command // 2. Execute the SOFT_RESET command // EXIT_CFGUPDATE exits config mode _without_ an OCV (open-circuit voltage) // measurement, and without resimulating to update unfiltered-SoC and SoC. // If a new OCV measurement or resimulation is desired, SOFT_RESET or // EXIT_RESIM should be used to exit config mode. esp_err_t err = ESP_FAIL; if (resim) { err = softReset(); if (err != ESP_OK) return err; std::int16_t timeout = I2C_TIMEOUT; while (timeout != 0) { vTaskDelay(1); std::uint16_t flags_res = 0; err = flags(&flags_res); if (err != ESP_OK) return err; if (!(flags_res & FLAG_CFGUPMODE)) { if (m_seal_again) { // Seal back up if we IC was sealed coming in std::uint16_t seal_res = 0; err = seal(&seal_res); if (err != ESP_OK) return err; // Wait 2 s to get values updated. vTaskDelay(pdMS_TO_TICKS(2000)); } m_manual_config = false; return ESP_OK; } timeout -= 1; } } else { m_manual_config = false; err = executeControlWord(EXIT_CFGUPDATE); if (err != ESP_OK) return err; return ESP_OK; } return ESP_FAIL; } esp_err_t FuelGauge::opConfig(std::uint16_t* result) { return readWord(EXTENDED_OPCONFIG, result); } esp_err_t FuelGauge::writeOpConfig(std::uint16_t value) { std::uint8_t op_config_msb = value >> 8; std::uint8_t op_config_lsb = value & 0x00FF; std::uint8_t op_config_data[2] = {op_config_msb, op_config_lsb}; // OpConfig register location: ID_REGISTERS id, offset 0 return writeExtendedData(ID_REGISTERS, 0, op_config_data, 2); } esp_err_t FuelGauge::blockDataControl() { std::uint8_t enable_byte = 0x00; return i2cWriteBytes(EXTENDED_CONTROL, &enable_byte, 1); } esp_err_t FuelGauge::blockDataClass(std::uint8_t id) { return i2cWriteBytes(EXTENDED_DATACLASS, &id, 1); } esp_err_t FuelGauge::blockDataOffset(std::uint8_t offset) { return i2cWriteBytes(EXTENDED_DATABLOCK, &offset, 1); } esp_err_t FuelGauge::blockDataChecksum(std::uint8_t* csum) { if (csum == nullptr) return ESP_FAIL; std::uint8_t new_csum = 0; ESP_ERR_TRY(i2cReadBytes(EXTENDED_CHECKSUM, &new_csum, 1)); *csum = new_csum; return ESP_OK; } esp_err_t FuelGauge::readBlockData(std::uint8_t offset, std::uint8_t* result) { if (result == nullptr) return ESP_FAIL; std::uint8_t ret = 0; std::uint8_t address = EXTENDED_BLOCKDATA + offset; ESP_ERR_TRY(i2cReadBytes(address, &ret, 1)); *result = ret; return ESP_OK; } esp_err_t FuelGauge::writeBlockData(std::uint8_t offset, std::uint8_t data) { std::uint8_t address = EXTENDED_BLOCKDATA + offset; return i2cWriteBytes(address, &data, 1); } esp_err_t FuelGauge::computeBlockChecksum(std::uint8_t* checksum) { if (checksum == nullptr) return ESP_FAIL; std::uint8_t data[32] = {0}; ESP_ERR_TRY(i2cReadBytes(EXTENDED_BLOCKDATA, data, 32)); std::uint8_t ret = 0; for (int i = 0; i < 32; i++) { ret += data[i]; } *checksum = 255 - ret; return ESP_OK; } esp_err_t FuelGauge::writeBlockChecksum(std::uint8_t csum) { return i2cWriteBytes(EXTENDED_CHECKSUM, &csum, 1); } esp_err_t FuelGauge::readExtendedData(std::uint8_t class_id, std::uint8_t offset, std::uint8_t* result) { if (!m_manual_config) ESP_ERR_TRY(enterConfig(false)); // Enable block data memory control ESP_ERR_TRY(blockDataControl()); // Write class ID using DataBlockClass() ESP_ERR_TRY(blockDataClass(class_id)); // Write 32-bit block offset (usually 0) ESP_ERR_TRY(blockDataOffset(offset / 32)); std::uint8_t new_csum = 0; // Compute checksum going in ESP_ERR_TRY(computeBlockChecksum(&new_csum)); std::uint8_t old_csum = 0; ESP_ERR_TRY(blockDataChecksum(&old_csum)); // Read from offset (limit to 0-31) ESP_ERR_TRY(readBlockData(offset % 32, result)); if (!m_manual_config) ESP_ERR_TRY(exitConfig(false)); return ESP_OK; } esp_err_t FuelGauge::writeExtendedData(std::uint8_t class_id, std::uint8_t offset, std::uint8_t* data, std::uint8_t len) { if (len == 0) return ESP_FAIL; if (len > 32) { ESP_LOGE(TAG, "max write length is 32"); return ESP_FAIL; } if (data == nullptr) return ESP_FAIL; if (!m_manual_config) ESP_ERR_TRY(enterConfig(false)); // Enable block data memory control ESP_ERR_TRY(blockDataControl()); // Write class ID using DataBlockClass() ESP_ERR_TRY(blockDataClass(class_id)); // Write 32-bit block offset (usually 0) ESP_ERR_TRY(blockDataOffset(offset / 32)); /// Wait 2s to get values updated. vTaskDelay(pdMS_TO_TICKS(2000)); // Compute checksum going in std::uint8_t computed_csum = 0; ESP_ERR_TRY(computeBlockChecksum(&computed_csum)); std::uint8_t old_csum = 0; ESP_ERR_TRY(blockDataChecksum(&old_csum)); // Write data bytes: for (int i = 0; i < len; i++) { // Write to offset, mod 32 if offset is greater than 32 // The blockDataOffset above sets the 32-bit block ESP_ERR_TRY(writeBlockData((offset % 32) + i, data[i])); } /// Wait 2s to get values updated. vTaskDelay(pdMS_TO_TICKS(2000)); // Write new checksum using BlockDataChecksum (0x60) std::uint8_t new_csum = 0; ESP_ERR_TRY(computeBlockChecksum(&new_csum)); ESP_ERR_TRY(writeBlockChecksum(new_csum)); /// Wait 2s to get values updated. vTaskDelay(pdMS_TO_TICKS(2000)); if (!m_manual_config) ESP_ERR_TRY(exitConfig(false)); return ESP_OK; } esp_err_t FuelGauge::softReset() { return executeControlWord(SOFT_RESET); } esp_err_t FuelGauge::readControlWord(std::uint16_t function, std::uint16_t* result) { std::uint8_t sub_command_msb = static_cast<std::uint8_t>(function >> 8); std::uint8_t sub_command_lsb = static_cast<std::uint8_t>(function & 0x00FF); std::uint8_t command[2] = {sub_command_lsb, sub_command_msb}; std::uint8_t data[2] = {0}; if (result == nullptr) return ESP_FAIL; ESP_ERR_TRY(i2cWriteBytes(0, command, 2)); ESP_ERR_TRY(i2cReadBytes(0, data, 2)); std::uint16_t d0 = static_cast<std::uint16_t>(data[1]) << 8; std::uint16_t d1 = static_cast<std::uint16_t>(data[0]); *result = (d1 | d0); return ESP_OK; } esp_err_t FuelGauge::executeControlWord(std::uint16_t function) { std::uint8_t sub_command_msb = (function >> 8); std::uint8_t sub_command_lsb = (function & 0x00FF); std::uint8_t command[2] = {sub_command_lsb, sub_command_msb}; ESP_ERR_TRY(i2cWriteBytes(0, command, 2)); return ESP_OK; } esp_err_t FuelGauge::readWord(std::uint8_t command, std::uint16_t* word) { std::uint8_t data[2] = {0}; if (word == nullptr) return ESP_FAIL; ESP_ERR_TRY(i2cReadBytes(command, data, 2)); std::uint16_t d0 = static_cast<std::uint16_t>(data[1]) << 8; std::uint16_t d1 = static_cast<std::uint16_t>(data[0]); *word = (d1 | d0); return ESP_OK; } esp_err_t FuelGauge::i2cWriteBytes(std::uint8_t sub_address, std::uint8_t* bytes, std::size_t count) { if (bytes == nullptr) return ESP_FAIL; if (count == 0) return ESP_FAIL; ESP_ERR_TRY(i2cInit()); ESP_ERR_TRY(i2c_set_timeout(I2C_PORT, 14000)); i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, (FUELGAUGE_ADDRESS << 1) | I2C_MASTER_WRITE, I2C_MASTER_ACK); i2c_master_write_byte(cmd, sub_address, I2C_MASTER_ACK); i2c_master_write(cmd, bytes, count, I2C_MASTER_ACK); i2c_master_stop(cmd); ESP_ERR_TRY(i2c_master_cmd_begin(I2C_PORT, cmd, I2C_TIMEOUT)); i2c_cmd_link_delete(cmd); ESP_ERR_TRY(i2cDelete()); return ESP_OK; } esp_err_t FuelGauge::i2cReadBytes(std::uint8_t sub_address, std::uint8_t* bytes, std::size_t count) { if (bytes == nullptr) return ESP_FAIL; if (count == 0) return ESP_FAIL; ESP_ERR_TRY(i2cInit()); ESP_ERR_TRY(i2c_set_timeout(I2C_PORT, 14000)); i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, (FUELGAUGE_ADDRESS << 1) | I2C_MASTER_WRITE, I2C_MASTER_ACK); i2c_master_write_byte(cmd, sub_address, I2C_MASTER_ACK); i2c_master_start(cmd); i2c_master_write_byte(cmd, (FUELGAUGE_ADDRESS << 1) | I2C_MASTER_READ, I2C_MASTER_ACK); i2c_master_read(cmd, bytes, count, I2C_MASTER_LAST_NACK); i2c_master_stop(cmd); ESP_ERR_TRY(i2c_master_cmd_begin(I2C_PORT, cmd, I2C_TIMEOUT)); i2c_cmd_link_delete(cmd); ESP_ERR_TRY(i2cDelete()); return ESP_OK; } esp_err_t FuelGauge::i2cInit() { ESP_ERR_TRY(i2c_param_config(I2C_PORT, &m_conf)); ESP_ERR_TRY(i2c_driver_install(I2C_PORT, m_conf.mode, 0, 0, 0)); return ESP_OK; } esp_err_t FuelGauge::i2cDelete() { ESP_ERR_TRY(i2c_driver_delete(I2C_PORT)); return ESP_OK; } } // namespace esc
25.718601
80
0.653706
xmrhaelan
28e2d2bced7f8c72830745b9c24350a9c874dccd
14,709
cpp
C++
Dependencies/Angelscript/source/as_callfunc_x64_gcc.cpp
CyberSys/ogitor
ef907e1cec77c397f809fa31b2a83cca733108e9
[ "MIT" ]
303
2015-07-11T17:12:55.000Z
2018-01-08T03:02:37.000Z
Dependencies/Angelscript/source/as_callfunc_x64_gcc.cpp
CyberSys/ogitor
ef907e1cec77c397f809fa31b2a83cca733108e9
[ "MIT" ]
39
2017-04-08T09:01:47.000Z
2021-10-10T12:15:57.000Z
Dependencies/Angelscript/source/as_callfunc_x64_gcc.cpp
CyberSys/ogitor
ef907e1cec77c397f809fa31b2a83cca733108e9
[ "MIT" ]
45
2017-01-07T08:25:29.000Z
2021-11-03T08:44:07.000Z
/* AngelCode Scripting Library Copyright (c) 2003-2014 Andreas Jonsson 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. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson andreas@angelcode.com */ /* * Implements the AMD64 calling convention for gcc-based 64bit Unices * * Author: Ionut "gargltk" Leonte <ileonte@bitdefender.com> * * Initial author: niteice * * Added support for functor methods by Jordi Oliveras Rovira in April, 2014. */ // Useful references for the System V AMD64 ABI: // http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/ // http://math-atlas.sourceforge.net/devel/assembly/abi_sysV_amd64.pdf #include "as_config.h" #ifndef AS_MAX_PORTABILITY #ifdef AS_X64_GCC #include "as_scriptengine.h" #include "as_texts.h" #include "as_context.h" BEGIN_AS_NAMESPACE enum argTypes { x64INTARG = 0, x64FLOATARG = 1 }; typedef asQWORD ( *funcptr_t )( void ); #define X64_MAX_ARGS 32 #define MAX_CALL_INT_REGISTERS 6 #define MAX_CALL_SSE_REGISTERS 8 #define X64_CALLSTACK_SIZE ( X64_MAX_ARGS + MAX_CALL_SSE_REGISTERS + 3 ) // Note to self: Always remember to inform the used registers on the clobber line, // so that the gcc optimizer doesn't try to use them for other things static asQWORD __attribute__((noinline)) X64_CallFunction(const asQWORD *args, int cnt, funcptr_t func, asQWORD &retQW2, bool returnFloat) { // Need to flag the variable as volatile so the compiler doesn't optimize out the variable volatile asQWORD retQW1 = 0; // Reference: http://www.x86-64.org/documentation/abi.pdf __asm__ __volatile__ ( " movq %0, %%rcx \n" // rcx = cnt " movq %1, %%r10 \n" // r10 = args " movq %2, %%r11 \n" // r11 = func // Backup stack pointer in R15 that is guaranteed to maintain its value over function calls " movq %%rsp, %%r15 \n" // Make sure the stack unwind logic knows we've backed up the stack pointer in register r15 " .cfi_def_cfa_register r15 \n" // Skip the first 128 bytes on the stack frame, called "red zone", // that might be used by the compiler to store temporary values " sub $128, %%rsp \n" // Make sure the stack pointer will be aligned to 16 bytes when the function is called " movq %%rcx, %%rdx \n" " salq $3, %%rdx \n" " movq %%rsp, %%rax \n" " sub %%rdx, %%rax \n" " and $15, %%rax \n" " sub %%rax, %%rsp \n" // Push the stack parameters, i.e. the arguments that won't be loaded into registers " movq %%rcx, %%rsi \n" " testl %%esi, %%esi \n" " jle endstack \n" " subl $1, %%esi \n" " xorl %%edx, %%edx \n" " leaq 8(, %%rsi, 8), %%rcx \n" "loopstack: \n" " movq 112(%%r10, %%rdx), %%rax \n" " pushq %%rax \n" " addq $8, %%rdx \n" " cmpq %%rcx, %%rdx \n" " jne loopstack \n" "endstack: \n" // Populate integer and floating point parameters " movq %%r10, %%rax \n" " mov (%%rax), %%rdi \n" " mov 8(%%rax), %%rsi \n" " mov 16(%%rax), %%rdx \n" " mov 24(%%rax), %%rcx \n" " mov 32(%%rax), %%r8 \n" " mov 40(%%rax), %%r9 \n" " add $48, %%rax \n" " movsd (%%rax), %%xmm0 \n" " movsd 8(%%rax), %%xmm1 \n" " movsd 16(%%rax), %%xmm2 \n" " movsd 24(%%rax), %%xmm3 \n" " movsd 32(%%rax), %%xmm4 \n" " movsd 40(%%rax), %%xmm5 \n" " movsd 48(%%rax), %%xmm6 \n" " movsd 56(%%rax), %%xmm7 \n" // Call the function " call *%%r11 \n" // Restore stack pointer " mov %%r15, %%rsp \n" // Inform the stack unwind logic that the stack pointer has been restored " .cfi_def_cfa_register rsp \n" // Put return value in retQW1 and retQW2, using either RAX:RDX or XMM0:XMM1 depending on type of return value " movl %5, %%ecx \n" " testb %%cl, %%cl \n" " je intret \n" " lea %3, %%rax \n" " movq %%xmm0, (%%rax) \n" " lea %4, %%rdx \n" " movq %%xmm1, (%%rdx) \n" " jmp endcall \n" "intret: \n" " movq %%rax, %3 \n" " movq %%rdx, %4 \n" "endcall: \n" : : "r" ((asQWORD)cnt), "r" (args), "r" (func), "m" (retQW1), "m" (retQW2), "m" (returnFloat) : "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7", "%rdi", "%rsi", "%rax", "%rdx", "%rcx", "%r8", "%r9", "%r10", "%r11", "%r15"); return retQW1; } // returns true if the given parameter is a 'variable argument' static inline bool IsVariableArgument( asCDataType type ) { return ( type.GetTokenType() == ttQuestion ) ? true : false; } asQWORD CallSystemFunctionNative(asCContext *context, asCScriptFunction *descr, void *obj, asDWORD *args, void *retPointer, asQWORD &retQW2) { asCScriptEngine *engine = context->m_engine; asSSystemFunctionInterface *sysFunc = descr->sysFuncIntf; int callConv = sysFunc->callConv; asQWORD retQW = 0; asDWORD *stack_pointer = args; funcptr_t *vftable = NULL; int totalArgumentCount = 0; int n = 0; int param_post = 0; int argIndex = 0; funcptr_t func = (funcptr_t)sysFunc->func; if( sysFunc->hostReturnInMemory ) { // The return is made in memory callConv++; } #ifndef AS_NO_THISCALL_FUNCTOR_METHOD // Unpack the two object pointers void **objectsPtrs = (void**)obj; void *secondObject = objectsPtrs[1]; obj = objectsPtrs[0]; // param_post has value 2 if is an THISCALL_OBJLAST #endif #ifdef AS_NO_THISCALL_FUNCTOR_METHOD // Determine the real function pointer in case of virtual method if ( obj && ( callConv == ICC_VIRTUAL_THISCALL || callConv == ICC_VIRTUAL_THISCALL_RETURNINMEM ) ) #else if ( obj && ( callConv == ICC_VIRTUAL_THISCALL || callConv == ICC_VIRTUAL_THISCALL_RETURNINMEM || callConv == ICC_VIRTUAL_THISCALL_OBJFIRST || callConv == ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM || callConv == ICC_VIRTUAL_THISCALL_OBJLAST || callConv == ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM) ) #endif { vftable = *((funcptr_t**)obj); func = vftable[FuncPtrToUInt(asFUNCTION_t(func)) >> 3]; } // Determine the type of the arguments, and prepare the input array for the X64_CallFunction asQWORD paramBuffer[X64_CALLSTACK_SIZE] = { 0 }; asBYTE argsType[X64_CALLSTACK_SIZE] = { 0 }; switch ( callConv ) { case ICC_CDECL_RETURNINMEM: case ICC_STDCALL_RETURNINMEM: { paramBuffer[0] = (asPWORD)retPointer; argsType[0] = x64INTARG; argIndex = 1; break; } #ifndef AS_NO_THISCALL_FUNCTOR_METHOD case ICC_THISCALL_OBJLAST: case ICC_VIRTUAL_THISCALL_OBJLAST: param_post = 2; #endif case ICC_THISCALL: case ICC_VIRTUAL_THISCALL: case ICC_CDECL_OBJFIRST: { paramBuffer[0] = (asPWORD)obj; argsType[0] = x64INTARG; argIndex = 1; break; } #ifndef AS_NO_THISCALL_FUNCTOR_METHOD case ICC_THISCALL_OBJLAST_RETURNINMEM: case ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM: param_post = 2; #endif case ICC_THISCALL_RETURNINMEM: case ICC_VIRTUAL_THISCALL_RETURNINMEM: case ICC_CDECL_OBJFIRST_RETURNINMEM: { paramBuffer[0] = (asPWORD)retPointer; paramBuffer[1] = (asPWORD)obj; argsType[0] = x64INTARG; argsType[1] = x64INTARG; argIndex = 2; break; } #ifndef AS_NO_THISCALL_FUNCTOR_METHOD case ICC_THISCALL_OBJFIRST: case ICC_VIRTUAL_THISCALL_OBJFIRST: { paramBuffer[0] = (asPWORD)obj; paramBuffer[1] = (asPWORD)secondObject; argsType[0] = x64INTARG; argsType[1] = x64INTARG; argIndex = 2; break; } case ICC_THISCALL_OBJFIRST_RETURNINMEM: case ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM: { paramBuffer[0] = (asPWORD)retPointer; paramBuffer[1] = (asPWORD)obj; paramBuffer[2] = (asPWORD)secondObject; argsType[0] = x64INTARG; argsType[1] = x64INTARG; argsType[2] = x64INTARG; argIndex = 3; break; } #endif case ICC_CDECL_OBJLAST: param_post = 1; break; case ICC_CDECL_OBJLAST_RETURNINMEM: { paramBuffer[0] = (asPWORD)retPointer; argsType[0] = x64INTARG; argIndex = 1; param_post = 1; break; } } int argumentCount = ( int )descr->parameterTypes.GetLength(); for( int a = 0; a < argumentCount; ++a ) { const asCDataType &parmType = descr->parameterTypes[a]; if( parmType.IsFloatType() && !parmType.IsReference() ) { argsType[argIndex] = x64FLOATARG; memcpy(paramBuffer + argIndex, stack_pointer, sizeof(float)); argIndex++; stack_pointer++; } else if( parmType.IsDoubleType() && !parmType.IsReference() ) { argsType[argIndex] = x64FLOATARG; memcpy(paramBuffer + argIndex, stack_pointer, sizeof(double)); argIndex++; stack_pointer += 2; } else if( IsVariableArgument( parmType ) ) { // The variable args are really two, one pointer and one type id argsType[argIndex] = x64INTARG; argsType[argIndex+1] = x64INTARG; memcpy(paramBuffer + argIndex, stack_pointer, sizeof(void*)); memcpy(paramBuffer + argIndex + 1, stack_pointer + 2, sizeof(asDWORD)); argIndex += 2; stack_pointer += 3; } else if( parmType.IsPrimitive() || parmType.IsReference() || parmType.IsObjectHandle() ) { argsType[argIndex] = x64INTARG; if( parmType.GetSizeOnStackDWords() == 1 ) { memcpy(paramBuffer + argIndex, stack_pointer, sizeof(asDWORD)); stack_pointer++; } else { memcpy(paramBuffer + argIndex, stack_pointer, sizeof(asQWORD)); stack_pointer += 2; } argIndex++; } else { // An object is being passed by value if( (parmType.GetObjectType()->flags & COMPLEX_MASK) || parmType.GetSizeInMemoryDWords() > 4 ) { // Copy the address of the object argsType[argIndex] = x64INTARG; memcpy(paramBuffer + argIndex, stack_pointer, sizeof(asQWORD)); argIndex++; } else if( (parmType.GetObjectType()->flags & asOBJ_APP_CLASS_ALLINTS) || (parmType.GetObjectType()->flags & asOBJ_APP_PRIMITIVE) ) { // Copy the value of the object if( parmType.GetSizeInMemoryDWords() > 2 ) { argsType[argIndex] = x64INTARG; argsType[argIndex+1] = x64INTARG; memcpy(paramBuffer + argIndex, *(asDWORD**)stack_pointer, parmType.GetSizeInMemoryBytes()); argIndex += 2; } else { argsType[argIndex] = x64INTARG; memcpy(paramBuffer + argIndex, *(asDWORD**)stack_pointer, parmType.GetSizeInMemoryBytes()); argIndex++; } // Delete the original memory engine->CallFree(*(void**)stack_pointer); } else if( (parmType.GetObjectType()->flags & asOBJ_APP_CLASS_ALLFLOATS) || (parmType.GetObjectType()->flags & asOBJ_APP_FLOAT) ) { // Copy the value of the object if( parmType.GetSizeInMemoryDWords() > 2 ) { argsType[argIndex] = x64FLOATARG; argsType[argIndex+1] = x64FLOATARG; memcpy(paramBuffer + argIndex, *(asDWORD**)stack_pointer, parmType.GetSizeInMemoryBytes()); argIndex += 2; } else { argsType[argIndex] = x64FLOATARG; memcpy(paramBuffer + argIndex, *(asDWORD**)stack_pointer, parmType.GetSizeInMemoryBytes()); argIndex++; } // Delete the original memory engine->CallFree(*(void**)stack_pointer); } stack_pointer += 2; } } // For the CDECL_OBJ_LAST calling convention we need to add the object pointer as the last argument if( param_post ) { #ifdef AS_NO_THISCALL_FUNCTOR_METHOD paramBuffer[argIndex] = (asPWORD)obj; #else paramBuffer[argIndex] = (asPWORD)(param_post > 1 ? secondObject : obj); #endif argsType[argIndex] = x64INTARG; argIndex++; } totalArgumentCount = argIndex; /* * Q: WTF is going on here !? * * A: The idea is to pre-arange the parameters so that X64_CallFunction() can do * it's little magic which must work regardless of how the compiler decides to * allocate registers. Basically: * - the first MAX_CALL_INT_REGISTERS entries in tempBuff will * contain the values/types of the x64INTARG parameters - that is the ones who * go into the registers. If the function has less then MAX_CALL_INT_REGISTERS * integer parameters then the last entries will be set to 0 * - the next MAX_CALL_SSE_REGISTERS entries will contain the float/double arguments * that go into the floating point registers. If the function has less than * MAX_CALL_SSE_REGISTERS floating point parameters then the last entries will * be set to 0 * - index MAX_CALL_INT_REGISTERS + MAX_CALL_SSE_REGISTERS marks the start of the * parameters which will get passed on the stack. These are added to the array * in reverse order so that X64_CallFunction() can simply push them to the stack * without the need to perform further tests */ asQWORD tempBuff[X64_CALLSTACK_SIZE] = { 0 }; asBYTE argsSet[X64_CALLSTACK_SIZE] = { 0 }; int used_int_regs = 0; int used_sse_regs = 0; int used_stack_args = 0; int idx = 0; for ( n = 0; ( n < totalArgumentCount ) && ( used_int_regs < MAX_CALL_INT_REGISTERS ); n++ ) { if ( argsType[n] == x64INTARG ) { argsSet[n] = 1; tempBuff[idx++] = paramBuffer[n]; used_int_regs++; } } idx = MAX_CALL_INT_REGISTERS; for ( n = 0; ( n < totalArgumentCount ) && ( used_sse_regs < MAX_CALL_SSE_REGISTERS ); n++ ) { if ( argsType[n] == x64FLOATARG ) { argsSet[n] = 1; tempBuff[idx++] = paramBuffer[n]; used_sse_regs++; } } idx = MAX_CALL_INT_REGISTERS + MAX_CALL_SSE_REGISTERS; for ( n = totalArgumentCount - 1; n >= 0; n-- ) { if ( !argsSet[n] ) { tempBuff[idx++] = paramBuffer[n]; used_stack_args++; } } retQW = X64_CallFunction( tempBuff, used_stack_args, func, retQW2, sysFunc->hostReturnFloat ); return retQW; } END_AS_NAMESPACE #endif // AS_X64_GCC #endif // AS_MAX_PORTABILITY
30.64375
140
0.656129
CyberSys
28e3e755cd2fa347658d818599f0150fdd64f942
1,071
cpp
C++
Source/Common/Android/utils_android.cpp
marswe/libHttpClient
c027c9a5f4babef09d5670a1ec00f2c197adb7db
[ "MIT" ]
2
2018-12-25T03:09:22.000Z
2021-04-08T13:43:46.000Z
Source/Common/Android/utils_android.cpp
marswe/libHttpClient
c027c9a5f4babef09d5670a1ec00f2c197adb7db
[ "MIT" ]
null
null
null
Source/Common/Android/utils_android.cpp
marswe/libHttpClient
c027c9a5f4babef09d5670a1ec00f2c197adb7db
[ "MIT" ]
2
2020-12-21T09:05:10.000Z
2021-07-20T01:22:34.000Z
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "utils_android.h" #include "../HTTP/Android/android_platform_context.h" NAMESPACE_XBOX_HTTP_CLIENT_BEGIN JNIEnv* get_jvm_env() { auto httpSingleton = xbox::httpclient::get_http_singleton(true); HC_PERFORM_ENV* platformContext = httpSingleton->m_performEnv.get(); JavaVM* javaVm = platformContext->GetJavaVm(); if (javaVm == nullptr) { HC_TRACE_ERROR(HTTPCLIENT, "javaVm is null"); throw std::runtime_error("JavaVm is null"); } JNIEnv* jniEnv = nullptr; jint jniResult = javaVm->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6); if (jniResult != JNI_OK) { HC_TRACE_ERROR(HTTPCLIENT, "Could not initialize HTTP request object, JavaVM is not attached to a java thread. %d", jniResult); throw std::runtime_error("This thread is not attached to a the JavaVm"); } return jniEnv; } NAMESPACE_XBOX_HTTP_CLIENT_END
30.6
135
0.715219
marswe
28e5e070f347193bfa1429bad87a6a9d7bbed87d
13,344
cpp
C++
lsteamclient/cppISteamFriends_SteamFriends012.cpp
Miouyouyou/Proton
72499898a7da4b3d17c748e308b50d9347f4b370
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-09-29T02:03:45.000Z
2019-09-29T02:03:45.000Z
lsteamclient/cppISteamFriends_SteamFriends012.cpp
Miouyouyou/Proton
72499898a7da4b3d17c748e308b50d9347f4b370
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
lsteamclient/cppISteamFriends_SteamFriends012.cpp
Miouyouyou/Proton
72499898a7da4b3d17c748e308b50d9347f4b370
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
#include "steam_defs.h" #include "steamworks_sdk_119x/steam_api.h" #include "steamclient_private.h" #include "cppISteamFriends_SteamFriends012.h" #ifdef __cplusplus extern "C" { #endif #include "struct_converters_119x.h" const char * cppISteamFriends_SteamFriends012_GetPersonaName(void *linux_side) { return ((ISteamFriends*)linux_side)->GetPersonaName(); } SteamAPICall_t cppISteamFriends_SteamFriends012_SetPersonaName(void *linux_side, const char * pchPersonaName) { return ((ISteamFriends*)linux_side)->SetPersonaName((const char *)pchPersonaName); } EPersonaState cppISteamFriends_SteamFriends012_GetPersonaState(void *linux_side) { return ((ISteamFriends*)linux_side)->GetPersonaState(); } int cppISteamFriends_SteamFriends012_GetFriendCount(void *linux_side, int iFriendFlags) { return ((ISteamFriends*)linux_side)->GetFriendCount((int)iFriendFlags); } CSteamID cppISteamFriends_SteamFriends012_GetFriendByIndex(void *linux_side, int iFriend, int iFriendFlags) { return ((ISteamFriends*)linux_side)->GetFriendByIndex((int)iFriend, (int)iFriendFlags); } EFriendRelationship cppISteamFriends_SteamFriends012_GetFriendRelationship(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetFriendRelationship((CSteamID)steamIDFriend); } EPersonaState cppISteamFriends_SteamFriends012_GetFriendPersonaState(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetFriendPersonaState((CSteamID)steamIDFriend); } const char * cppISteamFriends_SteamFriends012_GetFriendPersonaName(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetFriendPersonaName((CSteamID)steamIDFriend); } bool cppISteamFriends_SteamFriends012_GetFriendGamePlayed(void *linux_side, CSteamID steamIDFriend, FriendGameInfo_t * pFriendGameInfo) { return ((ISteamFriends*)linux_side)->GetFriendGamePlayed((CSteamID)steamIDFriend, (FriendGameInfo_t *)pFriendGameInfo); } const char * cppISteamFriends_SteamFriends012_GetFriendPersonaNameHistory(void *linux_side, CSteamID steamIDFriend, int iPersonaName) { return ((ISteamFriends*)linux_side)->GetFriendPersonaNameHistory((CSteamID)steamIDFriend, (int)iPersonaName); } bool cppISteamFriends_SteamFriends012_HasFriend(void *linux_side, CSteamID steamIDFriend, int iFriendFlags) { return ((ISteamFriends*)linux_side)->HasFriend((CSteamID)steamIDFriend, (int)iFriendFlags); } int cppISteamFriends_SteamFriends012_GetClanCount(void *linux_side) { return ((ISteamFriends*)linux_side)->GetClanCount(); } CSteamID cppISteamFriends_SteamFriends012_GetClanByIndex(void *linux_side, int iClan) { return ((ISteamFriends*)linux_side)->GetClanByIndex((int)iClan); } const char * cppISteamFriends_SteamFriends012_GetClanName(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->GetClanName((CSteamID)steamIDClan); } const char * cppISteamFriends_SteamFriends012_GetClanTag(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->GetClanTag((CSteamID)steamIDClan); } bool cppISteamFriends_SteamFriends012_GetClanActivityCounts(void *linux_side, CSteamID steamIDClan, int * pnOnline, int * pnInGame, int * pnChatting) { return ((ISteamFriends*)linux_side)->GetClanActivityCounts((CSteamID)steamIDClan, (int *)pnOnline, (int *)pnInGame, (int *)pnChatting); } SteamAPICall_t cppISteamFriends_SteamFriends012_DownloadClanActivityCounts(void *linux_side, CSteamID * psteamIDClans, int cClansToRequest) { return ((ISteamFriends*)linux_side)->DownloadClanActivityCounts((CSteamID *)psteamIDClans, (int)cClansToRequest); } int cppISteamFriends_SteamFriends012_GetFriendCountFromSource(void *linux_side, CSteamID steamIDSource) { return ((ISteamFriends*)linux_side)->GetFriendCountFromSource((CSteamID)steamIDSource); } CSteamID cppISteamFriends_SteamFriends012_GetFriendFromSourceByIndex(void *linux_side, CSteamID steamIDSource, int iFriend) { return ((ISteamFriends*)linux_side)->GetFriendFromSourceByIndex((CSteamID)steamIDSource, (int)iFriend); } bool cppISteamFriends_SteamFriends012_IsUserInSource(void *linux_side, CSteamID steamIDUser, CSteamID steamIDSource) { return ((ISteamFriends*)linux_side)->IsUserInSource((CSteamID)steamIDUser, (CSteamID)steamIDSource); } void cppISteamFriends_SteamFriends012_SetInGameVoiceSpeaking(void *linux_side, CSteamID steamIDUser, bool bSpeaking) { ((ISteamFriends*)linux_side)->SetInGameVoiceSpeaking((CSteamID)steamIDUser, (bool)bSpeaking); } void cppISteamFriends_SteamFriends012_ActivateGameOverlay(void *linux_side, const char * pchDialog) { ((ISteamFriends*)linux_side)->ActivateGameOverlay((const char *)pchDialog); } void cppISteamFriends_SteamFriends012_ActivateGameOverlayToUser(void *linux_side, const char * pchDialog, CSteamID steamID) { ((ISteamFriends*)linux_side)->ActivateGameOverlayToUser((const char *)pchDialog, (CSteamID)steamID); } void cppISteamFriends_SteamFriends012_ActivateGameOverlayToWebPage(void *linux_side, const char * pchURL) { ((ISteamFriends*)linux_side)->ActivateGameOverlayToWebPage((const char *)pchURL); } void cppISteamFriends_SteamFriends012_ActivateGameOverlayToStore(void *linux_side, AppId_t nAppID) { ((ISteamFriends*)linux_side)->ActivateGameOverlayToStore((AppId_t)nAppID); } void cppISteamFriends_SteamFriends012_SetPlayedWith(void *linux_side, CSteamID steamIDUserPlayedWith) { ((ISteamFriends*)linux_side)->SetPlayedWith((CSteamID)steamIDUserPlayedWith); } void cppISteamFriends_SteamFriends012_ActivateGameOverlayInviteDialog(void *linux_side, CSteamID steamIDLobby) { ((ISteamFriends*)linux_side)->ActivateGameOverlayInviteDialog((CSteamID)steamIDLobby); } int cppISteamFriends_SteamFriends012_GetSmallFriendAvatar(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetSmallFriendAvatar((CSteamID)steamIDFriend); } int cppISteamFriends_SteamFriends012_GetMediumFriendAvatar(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetMediumFriendAvatar((CSteamID)steamIDFriend); } int cppISteamFriends_SteamFriends012_GetLargeFriendAvatar(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetLargeFriendAvatar((CSteamID)steamIDFriend); } bool cppISteamFriends_SteamFriends012_RequestUserInformation(void *linux_side, CSteamID steamIDUser, bool bRequireNameOnly) { return ((ISteamFriends*)linux_side)->RequestUserInformation((CSteamID)steamIDUser, (bool)bRequireNameOnly); } SteamAPICall_t cppISteamFriends_SteamFriends012_RequestClanOfficerList(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->RequestClanOfficerList((CSteamID)steamIDClan); } CSteamID cppISteamFriends_SteamFriends012_GetClanOwner(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->GetClanOwner((CSteamID)steamIDClan); } int cppISteamFriends_SteamFriends012_GetClanOfficerCount(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->GetClanOfficerCount((CSteamID)steamIDClan); } CSteamID cppISteamFriends_SteamFriends012_GetClanOfficerByIndex(void *linux_side, CSteamID steamIDClan, int iOfficer) { return ((ISteamFriends*)linux_side)->GetClanOfficerByIndex((CSteamID)steamIDClan, (int)iOfficer); } uint32 cppISteamFriends_SteamFriends012_GetUserRestrictions(void *linux_side) { return ((ISteamFriends*)linux_side)->GetUserRestrictions(); } bool cppISteamFriends_SteamFriends012_SetRichPresence(void *linux_side, const char * pchKey, const char * pchValue) { return ((ISteamFriends*)linux_side)->SetRichPresence((const char *)pchKey, (const char *)pchValue); } void cppISteamFriends_SteamFriends012_ClearRichPresence(void *linux_side) { ((ISteamFriends*)linux_side)->ClearRichPresence(); } const char * cppISteamFriends_SteamFriends012_GetFriendRichPresence(void *linux_side, CSteamID steamIDFriend, const char * pchKey) { return ((ISteamFriends*)linux_side)->GetFriendRichPresence((CSteamID)steamIDFriend, (const char *)pchKey); } int cppISteamFriends_SteamFriends012_GetFriendRichPresenceKeyCount(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetFriendRichPresenceKeyCount((CSteamID)steamIDFriend); } const char * cppISteamFriends_SteamFriends012_GetFriendRichPresenceKeyByIndex(void *linux_side, CSteamID steamIDFriend, int iKey) { return ((ISteamFriends*)linux_side)->GetFriendRichPresenceKeyByIndex((CSteamID)steamIDFriend, (int)iKey); } void cppISteamFriends_SteamFriends012_RequestFriendRichPresence(void *linux_side, CSteamID steamIDFriend) { ((ISteamFriends*)linux_side)->RequestFriendRichPresence((CSteamID)steamIDFriend); } bool cppISteamFriends_SteamFriends012_InviteUserToGame(void *linux_side, CSteamID steamIDFriend, const char * pchConnectString) { return ((ISteamFriends*)linux_side)->InviteUserToGame((CSteamID)steamIDFriend, (const char *)pchConnectString); } int cppISteamFriends_SteamFriends012_GetCoplayFriendCount(void *linux_side) { return ((ISteamFriends*)linux_side)->GetCoplayFriendCount(); } CSteamID cppISteamFriends_SteamFriends012_GetCoplayFriend(void *linux_side, int iCoplayFriend) { return ((ISteamFriends*)linux_side)->GetCoplayFriend((int)iCoplayFriend); } int cppISteamFriends_SteamFriends012_GetFriendCoplayTime(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetFriendCoplayTime((CSteamID)steamIDFriend); } AppId_t cppISteamFriends_SteamFriends012_GetFriendCoplayGame(void *linux_side, CSteamID steamIDFriend) { return ((ISteamFriends*)linux_side)->GetFriendCoplayGame((CSteamID)steamIDFriend); } SteamAPICall_t cppISteamFriends_SteamFriends012_JoinClanChatRoom(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->JoinClanChatRoom((CSteamID)steamIDClan); } bool cppISteamFriends_SteamFriends012_LeaveClanChatRoom(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->LeaveClanChatRoom((CSteamID)steamIDClan); } int cppISteamFriends_SteamFriends012_GetClanChatMemberCount(void *linux_side, CSteamID steamIDClan) { return ((ISteamFriends*)linux_side)->GetClanChatMemberCount((CSteamID)steamIDClan); } CSteamID cppISteamFriends_SteamFriends012_GetChatMemberByIndex(void *linux_side, CSteamID steamIDClan, int iUser) { return ((ISteamFriends*)linux_side)->GetChatMemberByIndex((CSteamID)steamIDClan, (int)iUser); } bool cppISteamFriends_SteamFriends012_SendClanChatMessage(void *linux_side, CSteamID steamIDClanChat, const char * pchText) { return ((ISteamFriends*)linux_side)->SendClanChatMessage((CSteamID)steamIDClanChat, (const char *)pchText); } int cppISteamFriends_SteamFriends012_GetClanChatMessage(void *linux_side, CSteamID steamIDClanChat, int iMessage, void * prgchText, int cchTextMax, EChatEntryType * _a, CSteamID * _b) { return ((ISteamFriends*)linux_side)->GetClanChatMessage((CSteamID)steamIDClanChat, (int)iMessage, (void *)prgchText, (int)cchTextMax, (EChatEntryType *)_a, (CSteamID *)_b); } bool cppISteamFriends_SteamFriends012_IsClanChatAdmin(void *linux_side, CSteamID steamIDClanChat, CSteamID steamIDUser) { return ((ISteamFriends*)linux_side)->IsClanChatAdmin((CSteamID)steamIDClanChat, (CSteamID)steamIDUser); } bool cppISteamFriends_SteamFriends012_IsClanChatWindowOpenInSteam(void *linux_side, CSteamID steamIDClanChat) { return ((ISteamFriends*)linux_side)->IsClanChatWindowOpenInSteam((CSteamID)steamIDClanChat); } bool cppISteamFriends_SteamFriends012_OpenClanChatWindowInSteam(void *linux_side, CSteamID steamIDClanChat) { return ((ISteamFriends*)linux_side)->OpenClanChatWindowInSteam((CSteamID)steamIDClanChat); } bool cppISteamFriends_SteamFriends012_CloseClanChatWindowInSteam(void *linux_side, CSteamID steamIDClanChat) { return ((ISteamFriends*)linux_side)->CloseClanChatWindowInSteam((CSteamID)steamIDClanChat); } bool cppISteamFriends_SteamFriends012_SetListenForFriendsMessages(void *linux_side, bool bInterceptEnabled) { return ((ISteamFriends*)linux_side)->SetListenForFriendsMessages((bool)bInterceptEnabled); } bool cppISteamFriends_SteamFriends012_ReplyToFriendMessage(void *linux_side, CSteamID steamIDFriend, const char * pchMsgToSend) { return ((ISteamFriends*)linux_side)->ReplyToFriendMessage((CSteamID)steamIDFriend, (const char *)pchMsgToSend); } int cppISteamFriends_SteamFriends012_GetFriendMessage(void *linux_side, CSteamID steamIDFriend, int iMessageID, void * pvData, int cubData, EChatEntryType * peChatEntryType) { return ((ISteamFriends*)linux_side)->GetFriendMessage((CSteamID)steamIDFriend, (int)iMessageID, (void *)pvData, (int)cubData, (EChatEntryType *)peChatEntryType); } SteamAPICall_t cppISteamFriends_SteamFriends012_GetFollowerCount(void *linux_side, CSteamID steamID) { return ((ISteamFriends*)linux_side)->GetFollowerCount((CSteamID)steamID); } SteamAPICall_t cppISteamFriends_SteamFriends012_IsFollowing(void *linux_side, CSteamID steamID) { return ((ISteamFriends*)linux_side)->IsFollowing((CSteamID)steamID); } SteamAPICall_t cppISteamFriends_SteamFriends012_EnumerateFollowingList(void *linux_side, uint32 unStartIndex) { return ((ISteamFriends*)linux_side)->EnumerateFollowingList((uint32)unStartIndex); } #ifdef __cplusplus } #endif
40.807339
183
0.822842
Miouyouyou
28e98636a33b89d3480185b66511584b7bd2475e
1,782
cpp
C++
implementations/Segtree2.cpp
LeoRiether/Competicao-Programativa
ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e
[ "MIT" ]
1
2019-12-15T22:23:20.000Z
2019-12-15T22:23:20.000Z
implementations/Segtree2.cpp
LeoRiether/Competicao-Programativa
ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e
[ "MIT" ]
null
null
null
implementations/Segtree2.cpp
LeoRiether/Competicao-Programativa
ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> using namespace std; using vi = vector<int>; #define LEFT(i) 2*i+1 #define RIGHT(i) 2*i+2 int getSTSize(int x) { return 1<<int(ceil(log2(x))+1); } struct Segtree { int n; vi data, lazy; Segtree(int n) : n(n) { int s = getSTSize(n); data.resize(s,0); lazy.resize(s,0); } int query(int l, int r, int i, int nl, int nr) { if (nr < l || nl > r) return 0; if (nl >= l && nr <= r) { return data[i] + lazy[i]*(nr-nl+1); } int mid = (nl+nr)/2; lazy[LEFT(i)] += lazy[i]; lazy[RIGHT(i)] += lazy[i]; lazy[i] = 0; return query(l, r, LEFT(i), nl, mid) + query(l, r, RIGHT(i), mid+1, nr); } int query(int l, int r) { return query(l, r, 0, 0, n-1); } void update(int l, int r, int i, int nl, int nr, int delta) { if (nr < l || nl > r) return; if (nl >= l && nr <= r) { lazy[i] += delta; return; } data[i] += delta*(r-l+1); int mid = (nl+nr)/2; update(l, r, LEFT(i), nl, mid, delta); update(l, r, RIGHT(i), mid+1, nr, delta); } void update(int l, int r, int delta) { update(l, r, 0, 0, n-1, delta); } }; int main() { int n; cin >> n; Segtree st(n); for (int i = 0; i < n; i++) { int x; cin >> x; st.update(i, i, x); } int q; cin >> q; for (int i = 0; i < q; i++) { char t; cin >> t; if (t == 'U') { int l, r, x; cin >> l >> r >> x; st.update(l, r, x); } else if (t == 'Q') { int l, r; cin >> l >> r; cout << st.query(l, r) << endl; } else { cout << "Tipo da query não foi reconhecido" << endl; } } return 0; }
19.582418
64
0.446689
LeoRiether
28ea2b0d11dbb9467d83fc08a5e444619dcd0edc
12,899
cc
C++
test/t_api.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
test/t_api.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
test/t_api.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
/// \file /// Unit test for c++ API #include "unit-include/config.h" #include "unit-include/eq_ilas.h" #include "unit-include/simple_cpu.h" #include "unit-include/util.h" #include <ilang/ilang++.h> #include <vector> #define REG_NUM 16 #define REG_SIZE 8 namespace ilang { TEST(TestApi, LogicShift) { auto c = BvConst(0xFFFFFFFE, 32); // 01234567 8*4 = 32 // there is no guarantee that >> is logic shift // although it is usually implemented as such for // unsigned vars } TEST(TestApi, Construct) { Ila ila("top"); // state auto flag = ila.NewBoolState("flag"); std::vector<ExprRef> regs; for (auto i = 0; i != REG_NUM; i++) { std::string reg_name = "reg" + std::to_string(i); regs.push_back(ila.NewBvState(reg_name, REG_SIZE)); } auto mem = ila.NewMemState("mem", REG_SIZE, REG_SIZE); // input auto bool_in = ila.NewBoolInput("bool_in"); auto bv_in = ila.NewBvInput("bv_in", REG_SIZE); EXPECT_EQ(2, ila.input_num()); EXPECT_EQ(bool_in.get(), ila.input(0).get()); EXPECT_EQ(bv_in.get(), ila.input("bv_in").get()); // init auto flag_init = (flag == BoolConst(true)); auto regs_init = (regs[0] != BvConst(0, REG_SIZE)); auto mem_init = (mem == MemConst(0, {}, REG_SIZE, REG_SIZE)); ila.AddInit(flag_init); ila.AddInit(regs_init); ila.AddInit(mem_init); // fetch auto fetch = mem.Load(regs[0]); ila.SetFetch(fetch); EXPECT_EQ(fetch.get(), ila.fetch().get()); // valid auto valid = (regs[0] == regs[1]); ila.SetValid(valid); EXPECT_EQ(valid.get(), ila.valid().get()); // instr and ast { auto instr = ila.NewInstr("instr_0"); auto decode = (regs[1] < regs[2]); instr.SetDecode(decode); instr.SetUpdate(regs[0], bv_in); instr.SetUpdate(flag, (regs[1] < regs[2])); instr.SetUpdate(mem, mem.Store(regs[2], regs[3])); EXPECT_EQ(1, ila.instr_num()); EXPECT_EQ(instr.get(), ila.instr(0).get()); } // child auto child = ila.NewChild("child"); EXPECT_EQ(1, ila.child_num()); EXPECT_EQ(child.get(), ila.child(0).get()); EXPECT_EQ(child.get(), ila.child("child").get()); } /// helper function bool SameOp(const ExprRef& l, const ExprRef& r) { std::shared_ptr<ExprOp> lp = std::dynamic_pointer_cast<ExprOp>(l.get()); std::shared_ptr<ExprOp> rp = std::dynamic_pointer_cast<ExprOp>(r.get()); ILA_NOT_NULL(lp); ILA_NOT_NULL(rp); return lp->op_name() == rp->op_name(); } TEST(TestApi, ExprOps) { Ila ila("host"); auto v_bool = ila.NewBoolState("v_bool"); auto v_bv = ila.NewBvState("v_bv", REG_SIZE); auto v_mem = ila.NewMemState("v_mem", REG_SIZE, REG_SIZE); auto i_bool = ila.NewBoolInput("i_bool"); auto i_bv = ila.NewBvInput("i_bv", REG_SIZE); EXPECT_EQ(-1, v_bool.bit_width()); EXPECT_EQ(REG_SIZE, v_bv.bit_width()); EXPECT_EQ(-1, v_mem.bit_width()); EXPECT_EQ(-1, v_bool.addr_width()); EXPECT_EQ(-1, v_bv.addr_width()); EXPECT_EQ(REG_SIZE, v_mem.addr_width()); EXPECT_EQ(-1, v_bool.data_width()); EXPECT_EQ(-1, v_bv.data_width()); EXPECT_EQ(REG_SIZE, v_mem.data_width()); // test auto n_negate = -v_bv; auto n_not = !v_bool; auto n_cmpl = ~n_negate; auto n_and_bv = n_negate & n_cmpl; auto n_and_bool = n_not & i_bool; auto n_and_bool_c = n_and_bool & true; auto n_or_bv = n_and_bv | n_cmpl; auto n_or_bool = n_and_bool | i_bool; auto n_or_bool_c = n_or_bool | false; auto n_xor_bv = n_or_bv ^ n_and_bv; auto n_xor_bool = n_or_bool ^ n_and_bool; auto n_xor_bool_c = n_xor_bool ^ true; auto n_shl_bv = n_or_bv << n_and_bv; auto n_shl_int = n_or_bv << 2; auto n_ashr_bv = n_or_bv >> n_and_bv; auto n_ashr_int = n_or_bv >> 3; auto n_lshr_bv = Lshr(n_or_bv, n_and_bv); auto n_lshr_int = Lshr(n_or_bv, 4); auto n_add_bv = n_xor_bv + n_or_bv; auto n_sub_bv = n_add_bv - n_xor_bv; auto n_add_bv_c = n_add_bv + 1; auto n_sub_bv_c = n_sub_bv - 5; auto n_div_bv = n_add_bv / n_sub_bv; auto n_mul_bv = n_sub_bv_c * n_add_bv_c; auto n_srem_bv = SRem(n_div_bv, n_mul_bv); auto n_urem_bv = URem(n_div_bv, n_mul_bv); auto n_smod_bv = SMod(n_div_bv, n_mul_bv); auto n_eq_bv = n_add_bv == n_sub_bv; auto n_eq_bool = n_xor_bool == n_eq_bv; auto n_eq_bv_c = n_add_bv == 3; auto n_eq_bool_c = n_eq_bool == false; auto n_ne_bv = n_add_bv != n_sub_bv; auto n_ne_bool = n_ne_bv != n_eq_bool; auto n_ne_bv_c = n_add_bv != 4; auto n_lt_bv = n_add_bv < n_sub_bv; auto n_gt_bv = n_add_bv > n_sub_bv; auto n_le_bv = n_add_bv <= n_sub_bv; auto n_ge_bv = n_add_bv >= n_sub_bv; auto n_lt_bv_c = n_add_bv < 2; auto n_gt_bv_c = n_add_bv > 1; auto n_le_bv_c = n_add_bv <= 3; auto n_ge_bv_c = n_add_bv >= 0; SetUnsignedComparison(true); auto n_unsigned_lt_bv = n_add_bv < n_sub_bv; auto n_unsigned_gt_bv = n_add_bv > n_sub_bv; auto n_unsigned_le_bv = n_add_bv <= n_sub_bv; auto n_unsigned_ge_bv = n_add_bv >= n_sub_bv; auto n_unsigned_lt_bv_c = n_add_bv < 2; auto n_unsigned_gt_bv_c = n_add_bv > 1; auto n_unsigned_le_bv_c = n_add_bv <= 3; auto n_unsigned_ge_bv_c = n_add_bv >= 0; SetUnsignedComparison(false); auto n_ult_bv = Ult(n_add_bv, n_sub_bv); auto n_ugt_bv = Ugt(n_add_bv, n_sub_bv); auto n_ule_bv = Ule(n_add_bv, n_sub_bv); auto n_uge_bv = Uge(n_add_bv, n_sub_bv); auto n_slt_bv = Slt(n_add_bv, n_sub_bv); auto n_sgt_bv = Sgt(n_add_bv, n_sub_bv); auto n_sle_bv = Sle(n_add_bv, n_sub_bv); auto n_sge_bv = Sge(n_add_bv, n_sub_bv); auto n_ult_bv_c = Ult(n_add_bv, 1); auto n_ugt_bv_c = Ugt(n_add_bv, 2); auto n_ule_bv_c = Ule(n_add_bv, 3); auto n_uge_bv_c = Uge(n_add_bv, 4); auto n_slt_bv_c = Slt(n_add_bv, 1); auto n_sgt_bv_c = Sgt(n_add_bv, 2); auto n_sle_bv_c = Sle(n_add_bv, 3); auto n_sge_bv_c = Sge(n_add_bv, 4); EXPECT_TRUE(SameOp(n_lt_bv, n_slt_bv)); EXPECT_TRUE(SameOp(n_gt_bv, n_sgt_bv)); EXPECT_TRUE(SameOp(n_le_bv, n_sle_bv)); EXPECT_TRUE(SameOp(n_ge_bv, n_sge_bv)); EXPECT_TRUE(SameOp(n_unsigned_lt_bv, n_ult_bv)); EXPECT_TRUE(SameOp(n_unsigned_gt_bv, n_ugt_bv)); EXPECT_TRUE(SameOp(n_unsigned_le_bv, n_ule_bv)); EXPECT_TRUE(SameOp(n_unsigned_ge_bv, n_uge_bv)); EXPECT_TRUE(SameOp(n_lt_bv_c, n_slt_bv_c)); EXPECT_TRUE(SameOp(n_gt_bv_c, n_sgt_bv_c)); EXPECT_TRUE(SameOp(n_le_bv_c, n_sle_bv_c)); EXPECT_TRUE(SameOp(n_ge_bv_c, n_sge_bv_c)); EXPECT_TRUE(SameOp(n_unsigned_lt_bv_c, n_ult_bv_c)); EXPECT_TRUE(SameOp(n_unsigned_gt_bv_c, n_ugt_bv_c)); EXPECT_TRUE(SameOp(n_unsigned_le_bv_c, n_ule_bv_c)); EXPECT_TRUE(SameOp(n_unsigned_ge_bv_c, n_uge_bv_c)); auto n_load_bv = v_mem.Load(n_add_bv); auto n_load_bv_static = Load(v_mem, n_add_bv); auto n_store_mem = v_mem.Store(n_add_bv, n_load_bv); auto n_store_mem_static = Store(v_mem, n_add_bv, n_load_bv); auto n_extract_bv = n_load_bv(4, 0); auto n_append_bv = n_extract_bv.Append(n_load_bv); auto n_extract_static = Extract(n_load_bv, 4, 0); auto n_select_bv = SelectBit(n_load_bv, 0); auto n_extract_single_bv = n_extract_bv(1); auto n_zext_bv = n_extract_single_bv.ZExt(REG_SIZE); auto n_zext_static = ZExt(n_extract_single_bv, REG_SIZE); auto n_sext_bv = n_extract_single_bv.SExt(REG_SIZE); auto n_sext_static = SExt(n_extract_single_bv, REG_SIZE); auto n_concat_bv = Concat(n_append_bv, n_extract_bv); auto n_lrotate_bv = LRotate(n_concat_bv, REG_SIZE); auto n_rrotate_bv = RRotate(n_concat_bv, REG_SIZE); auto n_imply_bool = Imply(n_ne_bool, n_xor_bool); auto n_ite_bool = Ite(n_imply_bool, n_ne_bool, n_xor_bool); auto n_ite_bv = Ite(n_ite_bool, n_load_bv, n_sub_bv); auto tmp = n_ite_bv; } TEST(TestApi, Function) { auto s_out = SortRef::BOOL(); auto s_arg0 = SortRef::BOOL(); auto s_arg1 = SortRef::BV(8); auto s_arg2 = SortRef::MEM(8, 32); FuncRef f0("f0", s_out); FuncRef f1("f1", s_out, s_arg0); FuncRef f2("f2", s_out, s_arg0, s_arg1); FuncRef f3("f3", s_out, {s_arg0, s_arg1, s_arg2}); Ila ila("host"); auto i0 = BoolConst(true); auto i1 = BvConst(0, 8); auto i2 = ila.NewMemState("i2", 8, 32); auto n0 = f0(); auto n1 = f1(i0); auto n2 = f2(i0, i1); auto n3 = f3({i0, i1, i2}); } TEST(TestApi, NonConstruct) { Ila ila("host"); auto v_bool = ila.NewBoolState("v_bool"); auto c_bool = BoolConst(true); auto a = v_bool | c_bool; auto b = a & v_bool; auto c = a & v_bool; EXPECT_TRUE(TopEqual(b, c)); } TEST(TestApi, ReplaceArg) { Ila ila("host"); auto v_bool = ila.NewBoolState("v_bool"); auto c_bool = BoolConst(true); auto a = v_bool | c_bool; auto b = a & v_bool; auto c = a | v_bool; auto x = a ^ b; auto y = b ^ c; y.ReplaceArg(b, a); y.ReplaceArg(1, b); EXPECT_TRUE(TopEqual(x, y)); } TEST(TestApi, EntryNum) { Ila ila("hots"); auto mem = ila.NewMemState("mem", 16, 32); EXPECT_EQ(0, mem.GetEntryNum()); #ifndef NDEBUG EXPECT_DEATH(mem.SetEntryNum(-1), ".*"); #endif EXPECT_TRUE(mem.SetEntryNum(8)); EXPECT_FALSE(mem.SetEntryNum(16)); EXPECT_EQ(8, mem.GetEntryNum()); auto bl = ila.NewBoolState("bl"); #ifndef NDEBUG EXPECT_DEATH(bl.SetEntryNum(8), ".*"); EXPECT_DEATH(bl.GetEntryNum(), ".*"); #endif } TEST(TestApi, Unroll) { z3::context c; auto unroller = IlaZ3Unroller(c); auto m0 = SimpleCpuRef("m0"); auto m1 = SimpleCpuRef("m1"); std::map<NumericType, NumericType> init_mem_val; { init_mem_val[0] = GenLoad(0, 0); init_mem_val[1] = GenLoad(1, 1); init_mem_val[2] = GenAdd(2, 0, 1); init_mem_val[3] = GenStore(2, 2); } auto init_mem = MemConst(0, init_mem_val, 8, 8); // dummy predicates unroller.AddGlobPred(BoolConst(true)); unroller.AddStepPred(0, BoolConst(true)); unroller.AddStepPred(1, BoolConst(true)); unroller.AddStepPred(5, BoolConst(true)); // m0 for (size_t i = 0; i != m0.init_num(); i++) { unroller.AddInitPred(m0.init(i)); } unroller.AddInitPred(init_mem == m0.state("ir")); auto cstr00 = unroller.UnrollMonoConn(m0, 4); auto cstr01 = unroller.UnrollMonoFree(m0, 4); for (auto i = 0; i != 4; i++) { for (size_t si = 0; si != m0.state_num(); si++) { auto var = m0.state(si); auto next_val = unroller.NextState(var, i); auto next_var = unroller.CurrState(var, i + 1); cstr01 = cstr01 && (next_val == next_var); } } unroller.ClearInitPred(); unroller.ClearGlobPred(); unroller.ClearStepPred(); auto suff_unroller = IlaZ3Unroller(c, "path"); // m1 for (size_t i = 0; i != m1.init_num(); i++) { suff_unroller.AddInitPred(m1.init(i)); } suff_unroller.AddInitPred(init_mem == m1.state("ir")); std::vector<InstrRef> path = {m1.instr("Load"), m1.instr("Load"), m1.instr("Add"), m1.instr("Store")}; auto cstr10 = suff_unroller.UnrollPathConn(path); for (size_t i = 0; i != m1.init_num(); i++) { unroller.AddInitPred(m1.init(i)); } unroller.AddInitPred(init_mem == m1.state("ir")); auto cstr11 = unroller.UnrollPathConn(path); z3::solver s(c); s.add(cstr00); s.add(cstr10); EXPECT_EQ(z3::sat, s.check()); s.reset(); s.add(cstr01); s.add(cstr10); // connect initial value ASSERT_EQ(m0.state_num(), m1.state_num()); for (size_t i = 0; i != m0.state_num(); i++) { auto var0 = m0.state(i); auto var1 = m1.state(i); auto eq = unroller.Equal(var0, 0, var1, 0); s.add(eq); } // assert end value equal auto mem0 = m0.state("mem"); auto mem1 = m1.state("mem"); auto prop = unroller.Equal(mem0, 4, mem1, 4); s.add(!prop); // should not be equal due to extra suffix EXPECT_EQ(z3::sat, s.check()); // check two unrolling are equal s.reset(); s.add(cstr00); s.add(cstr11); for (size_t i = 0; i != m0.state_num(); i++) { auto var0 = m0.state(i); auto var1 = m1.state(i); auto eq = unroller.Equal(var0, 0, var1, 0); s.add(eq); } s.add(!prop); EXPECT_EQ(z3::unsat, s.check()); // check the sequence can reach the end s.reset(); s.add(cstr01); s.add(cstr11); for (size_t i = 0; i != m0.state_num(); i++) { auto var0 = m0.state(i); auto var1 = m1.state(i); auto eq = unroller.Equal(var0, 0, var1, 0); s.add(eq); } s.add(prop); EXPECT_EQ(z3::sat, s.check()); } TEST(TestApi, Log) { LogLevel(0); LogPath(""); EnableDebug("API_INFO"); std::string msg = ""; GET_STDERR_MSG(LogToErr(true), msg); #ifndef NDEBUG EXPECT_FALSE(msg.empty()); #endif DisableDebug("API_INFO"); LogPath(""); GET_STDERR_MSG(LogToErr(false), msg); #ifndef NDEBUG EXPECT_TRUE(msg.empty()); #endif } TEST(TestApi, Portable) { // SetToStdErr(1); EnableDebug("Portable"); auto example = EqIlaGen(); auto buff_spec = example.GetIlaFlat1("flat1"); auto portable_file_name = std::string(ILANG_TEST_BIN_ROOT) + "/tmp_portable.json"; auto res = ExportIlaPortable(Ila(buff_spec), portable_file_name); EXPECT_TRUE(res); auto read_ila = ImportIlaPortable(portable_file_name); DisableDebug("Portable"); } } // namespace ilang
27.503198
74
0.667726
yuex1994
28eb79f9570331643522c81991e661346f6a2414
996
hpp
C++
include/roq/utils/number.hpp
roq-trading/api
a5910c88df3759496957d7b9748cf6c1364e8bec
[ "MIT" ]
null
null
null
include/roq/utils/number.hpp
roq-trading/api
a5910c88df3759496957d7b9748cf6c1364e8bec
[ "MIT" ]
null
null
null
include/roq/utils/number.hpp
roq-trading/api
a5910c88df3759496957d7b9748cf6c1364e8bec
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2022, Hans Erik Thrane */ #pragma once #include <fmt/format.h> #include "roq/decimals.hpp" #include "roq/utils/common.hpp" namespace roq { namespace utils { struct Number final { Number() = default; Number(double value, Decimals decimals) : value(value), decimals(decimals) {} const double value = NaN; const Decimals decimals = {}; }; } // namespace utils } // namespace roq template <> struct fmt::formatter<roq::utils::Number> { template <typename Context> constexpr auto parse(Context &context) { return std::begin(context); } template <typename Context> auto format(const roq::utils::Number &value, Context &context) { using namespace std::literals; auto decimal_digits = roq::utils::decimal_digits(value.decimals); if (decimal_digits < 0) return fmt::format_to(context.out(), "{}"sv, value.value); return fmt::format_to(context.out(), "{:.{}f}"sv, value.value, roq::utils::decimal_digits(value.decimals)); } };
24.9
111
0.685743
roq-trading
28ecf97b9bd3d3b084553cd98643e3b25c4d6f87
1,128
hpp
C++
src/pipemode_op/test/testRecordReader/TestTFRecordReader.hpp
laurenyu/sagemaker-tensorflow-extensions
14d15e7a292926a69aa590cad3fd2c9d68bd7df5
[ "Apache-2.0" ]
43
2018-07-18T20:07:11.000Z
2022-02-19T20:38:58.000Z
src/pipemode_op/test/testRecordReader/TestTFRecordReader.hpp
laurenyu/sagemaker-tensorflow-extensions
14d15e7a292926a69aa590cad3fd2c9d68bd7df5
[ "Apache-2.0" ]
91
2018-07-28T17:55:08.000Z
2022-02-23T22:09:14.000Z
src/pipemode_op/test/testRecordReader/TestTFRecordReader.hpp
laurenyu/sagemaker-tensorflow-extensions
14d15e7a292926a69aa590cad3fd2c9d68bd7df5
[ "Apache-2.0" ]
53
2018-07-18T20:07:15.000Z
2022-02-07T22:47:06.000Z
#ifndef SRC_PIPEMODE_OP_TEST_TESTRECORDREADER_TESTTFRECORDREADER_HPP_ #define SRC_PIPEMODE_OP_TEST_TESTRECORDREADER_TESTTFRECORDREADER_HPP_ // Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of // the License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 "gtest/gtest.h" #include "gmock/gmock.h" namespace sagemaker { namespace tensorflow { class TFRecordReaderTest : public ::testing::Test { protected: TFRecordReaderTest(); virtual ~TFRecordReaderTest(); virtual void SetUp(); virtual void TearDown(); }; } // namespace tensorflow } // namespace sagemaker #endif // SRC_PIPEMODE_OP_TEST_TESTRECORDREADER_TESTTFRECORDREADER_HPP_
31.333333
74
0.764184
laurenyu
28eff6aa924b1ece0bf63d7e5b958956e467cee4
7,812
cpp
C++
IvyProjects/GLTestApp/Particles.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/GLTestApp/Particles.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/GLTestApp/Particles.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////// /// /// Ivy Engine - Generic OpenGL Test App /// /// Copyright 2010-2012, Brandon Light /// All rights reserved. /// /////////////////////////////////////////////////////////////////////////////////////////////////// #include "GLTestApp.h" #include "IvyUtils.h" #include "IvyImporter.h" #include "IvyCamera.h" #include "IvyWindow.h" #include "GLTexture.h" #include "IvyGL.h" #include "GLShader.h" using namespace Ivy; inline float IvyMax(float a, float b) { return (a > b) ? a : b; } inline float IvyMin(float a, float b) { return (a < b) ? a : b; } inline float IvyClamp(float minClamp, float maxClamp, float value) { return IvyMax(IvyMin(value, maxClamp), minClamp); } struct Particles { int count; Point3* pPositions; Point2* pTexCoords; Point3* pVelocity; }; ///@todo get rid of these globals Particles* pParticles = NULL; int width = 100, height = 100; void InitParticles2DArray(Particles* pParticles, int width, int height) { for (int w = 0; w < width; ++w) { for (int h = 0; h < height; ++h) { int index = (h * width) + w; float posx = -1.0f + ((2.0f / width) * w); float posy = -1.0f + ((2.0f / height) * h); pParticles->pPositions[index].x = posx; pParticles->pPositions[index].y = posy; pParticles->pPositions[index].z = 0.5; pParticles->pTexCoords[index].x = w / (float)width; pParticles->pTexCoords[index].y = 1.0f - h / (float)height; float magnitude = sqrt(posx*posx + posy*posy); pParticles->pVelocity[index].x = posx / magnitude; pParticles->pVelocity[index].y = posy / magnitude; pParticles->pVelocity[index].z = 0; } } } void UpdateParticles(Particles* particles, float timestep) { float bounds = 3.0f; timestep *= 1; // calculate new velocity with x/'friction' or y/'gravity' constants float gravityDecel = 4 * timestep; float xFriction = 3.0f * timestep; for(int i = 0; i < particles->count; ++i) { // particles->pVelocity[i].x *= (particles->pVelocity[i].x > 0) ? -xFriction : xFriction; particles->pVelocity[i].y -= gravityDecel; // gravity is always negative // update position particles->pPositions[i].x = IvyClamp(-bounds, bounds, particles->pPositions[i].x + (particles->pVelocity[i].x * timestep)); if ((particles->pPositions[i].x <= -bounds) || (particles->pPositions[i].x >= bounds)) { particles->pVelocity[i].x *= -0.25f; } particles->pPositions[i].y = IvyClamp(-bounds, bounds, particles->pPositions[i].y + (particles->pVelocity[i].y * timestep)); // change direction if ((particles->pPositions[i].y <= -bounds) || (particles->pPositions[i].y >= bounds)) { particles->pVelocity[i].y *= -0.8f; } } } void GLTestApp::ParticlesTest() { #if IVY_GL_ES InitGLES2(); #else InitGL2(); #endif // IVY_GL_ES m_pWindow->Show(); GLShader* pVSShader = GLShader::CreateFromFile(IvyVertexShader, "ParticleVS", "Content/shaders/particles.vert"); GLShader* pFSShader = GLShader::CreateFromFile(IvyFragmentShader, "ParticlesFS", "Content/shaders/particles.frag"); GLProgram* pProgram = GLProgram::Create(); pProgram->AttachShader(pVSShader); pProgram->AttachShader(pFSShader); pProgram->Link(); pProgram->Bind(); #if XNA_MATH struct CameraBufferData { XMMATRIX worldMatrix; XMMATRIX viewMatrix; XMMATRIX projectionMatrix; }; CameraBufferData cameraBufferData; cameraBufferData.worldMatrix = XMMatrixScaling(1.0, 1.0, 1); //XMMatrixIdentity(); //XMMatrixRotationX(-3.14f/2.0f) * XMMatrixScaling(2, 2, 1); //XMMatrixIdentity(); cameraBufferData.viewMatrix = XMMatrixTranslation(0, 0, 3.0f) * m_pCamera->W2C(); cameraBufferData.projectionMatrix = m_pCamera->C2S(); UINT worldMatrixAttribLoc = glGetUniformLocation(pProgram->ProgramId(), "worldMatrix"); UINT viewMatrixAttribLoc = glGetUniformLocation(pProgram->ProgramId(), "viewMatrix"); UINT projMatrixAttribLoc = glGetUniformLocation(pProgram->ProgramId(), "projectionMatrix"); glUniformMatrix4fv(worldMatrixAttribLoc, 1, GL_FALSE, reinterpret_cast<GLfloat*>(&cameraBufferData.worldMatrix)); glUniformMatrix4fv(viewMatrixAttribLoc, 1, GL_FALSE, reinterpret_cast<GLfloat*>(&cameraBufferData.viewMatrix)); glUniformMatrix4fv(projMatrixAttribLoc, 1, GL_FALSE, reinterpret_cast<GLfloat*>(&cameraBufferData.projectionMatrix)); #endif pParticles = new Particles(); pParticles->count = width * height; pParticles->pPositions = new Point3[pParticles->count]; pParticles->pTexCoords = new Point2[pParticles->count]; pParticles->pVelocity = new Point3[pParticles->count]; InitParticles2DArray(pParticles, width, height); GLint positionAttribLoc = glGetAttribLocation(pProgram->ProgramId(), "in_Position"); GLint texAttribLoc = glGetAttribLocation(pProgram->ProgramId(), "in_TexCoord"); glBindAttribLocation(pProgram->ProgramId(), positionAttribLoc, "in_Position"); glBindAttribLocation(pProgram->ProgramId(), texAttribLoc, "in_TexCoord"); glVertexAttribPointer(positionAttribLoc, 3, GL_FLOAT, FALSE, 3*4, pParticles->pPositions); glEnableVertexAttribArray(positionAttribLoc); glVertexAttribPointer(texAttribLoc, 2, GL_FLOAT, FALSE, 2*4, pParticles->pTexCoords); glEnableVertexAttribArray(texAttribLoc); GLenum error = glGetError(); // Setup Textures GLint textureAttribLoc = 0; glActiveTexture(GL_TEXTURE0); GLTexture* pTexture = GLTexture::CreateFromFile(IvyTexture2D, "Content/kitten_rgb.png"); textureAttribLoc = glGetUniformLocation(pProgram->ProgramId(), "s_tex0"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); error = glGetError(); glActiveTexture(GL_TEXTURE1); GLTexture* pFirefleaTex = GLTexture::CreateFromFile(IvyTexture2D, "Content/fireflea.png"); textureAttribLoc = glGetUniformLocation(pProgram->ProgramId(), "s_tex1"); // pTexture->Bind(0, textureAttribLoc); pFirefleaTex->Bind(1, textureAttribLoc); error = glGetError(); ///@todo Migrate settings into texture object? Or have separate sampler that is attached to texture? glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glViewport(0, 0, m_pWindow->GetDrawableArea().right, m_pWindow->GetDrawableArea().bottom); BOOL quit = false; GLubyte* pIndices = NULL; #if !(IVY_GL_ES) glEnable(GL_PROGRAM_POINT_SIZE); #endif // !(IVY_GL_ES) GLubyte* pIndicies = new GLubyte[width*height]; for (int i = 0; i < width * height; ++i) { pIndicies[i] = i; } KeyboardState lastKeyboardState; while (!quit) { ProcessUpdates(); BeginFrame(); error = glGetError(); const KeyboardState* pKeys = GetKeyboardState(); if (pKeys->Pressed[Key_R] && !lastKeyboardState.Pressed[Key_R]) { InitParticles2DArray(pParticles, width, height); } glClearColor(0.0f,0.4,0.4,1.0f); glClear(GL_COLOR_BUFFER_BIT); UpdateParticles(pParticles, 0.005f); glDrawArrays(GL_POINTS, 0, width * height); IvySwapBuffers(); memcpy(&lastKeyboardState, pKeys, sizeof(KeyboardState)); EndFrame(); } pTexture->Destroy(); pProgram->Destroy(); pFSShader->Destroy(); pVSShader->Destroy(); }
32.686192
132
0.64913
endy
28f250ef07d37c533c06837ed623cf5f50961916
574
hpp
C++
cpp/StringTokenize.hpp
sigurdstorve/supersplines
a49cac9f7e166b660fb1da688f9bf5d90f05dcdb
[ "BSL-1.0" ]
2
2020-01-07T02:40:42.000Z
2022-03-21T07:09:08.000Z
cpp/StringTokenize.hpp
sigurdstorve/supersplines
a49cac9f7e166b660fb1da688f9bf5d90f05dcdb
[ "BSL-1.0" ]
null
null
null
cpp/StringTokenize.hpp
sigurdstorve/supersplines
a49cac9f7e166b660fb1da688f9bf5d90f05dcdb
[ "BSL-1.0" ]
null
null
null
// RealtimeCppAV - Developed by Sigurd Storve (sigurd.storve@ntnu.no) // This file contains convenience code to split ut a string. #include <iostream> #include <string> #include <vector> #include <boost/tokenizer.hpp> inline std::vector<std::string> StringTokenize(const std::string& str, const std::string& separators) { boost::char_separator<char> sep(separators.c_str()); boost::tokenizer<boost::char_separator<char> > tokens(str, sep); std::vector<std::string> res; for (const auto& t : tokens) { res.push_back(t); } return res; }
31.888889
103
0.691638
sigurdstorve
28f274927c371865b88c1547e9958a961eb18f79
900
cpp
C++
SurfaceReconstruction/SurfaceReconstruction/Refinement/RangedVertexIdx.cpp
pavelsevecek/TSR
ca411dedf178e5830f0536e361136f1e16751bc8
[ "BSD-3-Clause" ]
102
2017-10-17T10:10:59.000Z
2022-01-19T02:10:29.000Z
SurfaceReconstruction/SurfaceReconstruction/Refinement/RangedVertexIdx.cpp
pavelsevecek/TSR
ca411dedf178e5830f0536e361136f1e16751bc8
[ "BSD-3-Clause" ]
2
2019-12-21T11:59:15.000Z
2020-09-08T11:38:36.000Z
SurfaceReconstruction/SurfaceReconstruction/Refinement/RangedVertexIdx.cpp
pavelsevecek/TSR
ca411dedf178e5830f0536e361136f1e16751bc8
[ "BSD-3-Clause" ]
27
2017-10-18T09:37:34.000Z
2022-03-22T01:30:51.000Z
/* * Copyright (C) 2018 by Author: Aroudj, Samir * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the License.txt file for details. */ #include "SurfaceReconstruction/Refinement/FSSFRefiner.h" #include "SurfaceReconstruction/Refinement/RangedVertexIdx.h" #include "SurfaceReconstruction/Scene/Scene.h" using namespace Math; using namespace SurfaceReconstruction; using namespace std; ostream &SurfaceReconstruction::operator <<(std::ostream &out, const RangedVertexIdx &rangedVertexIdx) { out << "RangedVertexIdx"; out << ", global vertex index " << rangedVertexIdx.getGlobalVertexIdx(); out << ", local predecessor " << rangedVertexIdx.getLocalPredecessorIdx(); out << ", costs " << rangedVertexIdx.getCosts(); out << "\n"; return out; }
31.034483
102
0.752222
pavelsevecek
28f6077f0621e0f3888722288ef6893897f254dc
4,587
cpp
C++
src/tracer/raytracer.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
src/tracer/raytracer.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
src/tracer/raytracer.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
#include "raytracer.hpp" #include "../material/material.hpp" #include <thread> #include <atomic> #include <vector> namespace tracer { inline int colorFloatToInt(floating color) { return (int)(255.99f * color); } void raytraceSimple(output::ImageOutput* imageOut, world::WorldData* world, int width, int height, int samples, int depth) { for (int y = height - 1; y >= 0; y--) { for (int x = 0; x < width; x++) { math::Vector3 color(0, 0, 0); for (int sample = 0; sample < samples; sample++) { floating u = ((floating)(x) + drand48()) / (floating)(width); floating v = ((floating)(y) + drand48()) / (floating)(height); math::Ray ray = world->getCamera()->getRay(u, v); color += tracer::traceColor(ray, world->getWorld(), world->getSky(), depth); } color /= (floating) samples; color = math::Vector3(sqrt(color.r()), sqrt(color.g()), sqrt(color.b())); int r = colorFloatToInt(color.r()); int g = colorFloatToInt(color.g()); int b = colorFloatToInt(color.b()); imageOut->write(r, g, b); } } } void raytraceMultithreaded(output::BufferedOutput& buffer, world::WorldData* world, int width, int height, int samples, int depth, int threadCount, int blockSize) { std::atomic_int count(0); std::vector<std::thread> threadPool; threadPool.reserve(threadCount); uint8_t* dataBuffer = buffer.getData(); const int blockCountH = 1 + ((width - 1) / blockSize); const int blockCountV = 1 + ((height - 1) / blockSize); const int blockMax = blockCountH * blockCountV; for (int i = 0; i < threadCount; i++) { threadPool.emplace_back([=, &count](){ while (true) { const int index = count++; if (index >= blockMax) { break; } const int xStart = (index % blockCountH) * blockSize; const int yStart = (index / blockCountH) * blockSize; const int xEnd = MIN(width, xStart + blockSize); const int yEnd = MIN(height, yStart + blockSize); for (int y = yStart; y < yEnd; y++) { for (int x = xStart; x < xEnd; x++) { math::Vector3 color(0, 0, 0); for (int sample = 0; sample < samples; sample++) { floating u = ((floating)(x) + drand48()) / (floating)(width); floating v = ((floating)(y) + drand48()) / (floating)(height); math::Ray ray = world->getCamera()->getRay(u, v); color += tracer::traceColor(ray, world->getWorld(), world->getSky(), depth); } color /= (floating) samples; color = math::Vector3(sqrt(color.r()), sqrt(color.g()), sqrt(color.b())); int idx = (((height - 1) - y) * width + x) * 3; dataBuffer[idx + 0] = colorFloatToInt(color.r()); dataBuffer[idx + 1] = colorFloatToInt(color.g()); dataBuffer[idx + 2] = colorFloatToInt(color.b()); } } } }); } for (auto& thread : threadPool) { if (thread.joinable()) { thread.join(); } } } math::Vector3 traceColor(const math::Ray& ray, scene::Hitable *world, sky::Sky *sky, int depth) { scene::HitRecord rec; if (world->hit(ray, 0.001, MAX_FLOATING, rec)) { math::Ray scattered; math::Vector3 attenuation; if (depth > 0 && rec.matPtr->scatter(ray, rec, attenuation, scattered)) { return attenuation * traceColor(scattered, world, sky, depth - 1); } else { return math::Vector3(0, 0, 0); } } else { return sky->skyColor(ray); } } }
35.55814
166
0.444953
NHollmann
28f7e38cdf423e4f4d40939d4cd0281c3ab77f91
743
hpp
C++
cudamapper/include/claragenomics/cudamapper/cudamapper.hpp
billchenxi/ClaraGenomicsAnalysis
544effc5881560de6d316f39c47c87014da14d70
[ "Apache-2.0" ]
1
2020-01-21T09:07:02.000Z
2020-01-21T09:07:02.000Z
cudamapper/include/claragenomics/cudamapper/cudamapper.hpp
billchenxi/ClaraGenomicsAnalysis
544effc5881560de6d316f39c47c87014da14d70
[ "Apache-2.0" ]
1
2020-12-04T06:24:05.000Z
2020-12-04T06:24:05.000Z
cudamapper/include/claragenomics/cudamapper/cudamapper.hpp
billchenxi/ClaraGenomicsAnalysis
544effc5881560de6d316f39c47c87014da14d70
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once /// \defgroup cudamapper CUDA mapper package /// Base docs for the cudamapper package (tbd) /// \{ namespace claragenomics { namespace cudamapper { enum class StatusType { success = 0, generic_error }; StatusType Init(); }; // namespace cudamapper }; // namespace claragenomics /// \}
23.21875
76
0.755047
billchenxi
28f9b9e02926d532e3f2f23ef65d52ad52ce8c44
4,673
cpp
C++
C++/Read_from_file/is_palindromic.cpp
juliafeingold/My-Cpp-programs
cbc7095082da25ce2a4f66d711d77af8d794206c
[ "Apache-2.0" ]
null
null
null
C++/Read_from_file/is_palindromic.cpp
juliafeingold/My-Cpp-programs
cbc7095082da25ce2a4f66d711d77af8d794206c
[ "Apache-2.0" ]
null
null
null
C++/Read_from_file/is_palindromic.cpp
juliafeingold/My-Cpp-programs
cbc7095082da25ce2a4f66d711d77af8d794206c
[ "Apache-2.0" ]
null
null
null
//libraries #include <iostream> #include <cstring> #include <string> using namespace std; //Programmer defined functions int myStrlen (char *s1); void myStrcat (char *s1, char *s2); void myStrcpy (char *s1, char *s2); void myStrcat_BC (char *s1, char *s2, int SIZE); bool isPalindromic (char *s1); //main program int main() { //Data const int SIZE = 11; char s1[SIZE] = "Hello "; char s2[SIZE] = "World"; //output the C string and the length of the C string cout << "s1: " << " " << s1 << endl; /// Should display "Hello " cout << "The length of s1: " << myStrlen(s1) << endl << endl; //output the concatenation of the C-strings and the length of the C string cout << "Doing strcat(s1, s2) " << endl; myStrcat(s1, s2); cout << "s1: " << " " << s1 << endl; /// Should display "Hello World" cout << "The length of s1: " << myStrlen(s1) << endl << endl; //copy the content of the second string to the first cout << "Doing strcpy(s1, s2) " << endl; myStrcpy(s1, s2); cout << "s2: " << " " << s1 << endl; // Should display "World" cout << "The length of s1: " << myStrlen(s1) << endl << endl; // Test myStrcat_BC() and isPalindromic() in the following ways: // // myStrcat with bounds checking cout << "Doing myStrcat_BC(s1, s2, SIZE) " << endl; myStrcat_BC(s1, s2, SIZE); /// Should display "WorldWorld" cout << "s1: " << " " << s1 << endl; cout << "The length of s1: " << myStrlen(s1) << endl << endl; // // In case “out of bound” occurs, output an error message on computer screen cout << "Doing myStrcat_BC(s1, s2, SIZE) again" << endl; myStrcat_BC(s1, s2, SIZE); /// Out of bound, prompt an error message cout << "s1: " << " " << s1 << endl; cout << "The length of s1: " << myStrlen(s1) << endl << endl; char s3[SIZE] = "World"; cout << "Doing isPalindromic(s3)" << endl; if (isPalindromic(s3)) cout << s3 << " is a palindromic word." << endl << endl; else cout << s3 << " is not a palindromic word." << endl << endl; char s4[SIZE] = "I"; cout << "Doing isPalindromic(s4)" << endl; if (isPalindromic(s4)) cout << s4 << " is a palindromic word." << endl << endl; else cout << s4 << " is not a palindromic word." << endl << endl; char s5[SIZE] = "Radar"; cout << "Doing isPalindromic(s5)" << endl; if (isPalindromic(s5)) cout << s5 << " is a palindromic word." << endl << endl; else cout << s5 << " is not a palindromic word." << endl << endl; cout << "Doing isPalindromic(s6)" << endl; char s6[SIZE] = "eye"; if (isPalindromic(s6)) cout << s6 << " is a palindromic word." << endl << endl; else cout << s6 << " is not a palindromic word." << endl << endl; }//main // Function to check the length of the C string int myStrlen(char *s1) { //Data int result = 0;//the length of the string //get length of the string while(*s1 != '\0') { result++; s1++; }//while *s1 = '\0'; return result; }//myStrlen // Function to return the concatenation of C-strings void myStrcat (char *s1, char *s2) { //Data int i = 0; //index loop int j = 0; //index loop //concatenate C-strings for (i = 0; s1[i] != '\0'; i++) { i++; }//for // Remove null character i--; for (j = 0; s2[j] != '\0'; j++, i++) { s1[i] = s2[j]; }//for //assign null char to the end of the C-string s1[i] = '\0'; }//myStrcat // Function copy the content of the second string to the first void myStrcpy (char *s1, char *s2) { //Data int i = 0;//index loop //copy the content of the second string to the first for (i = 0; s1[i] != '\0'; i++) { s1[i] = s2[i]; }//for //assign null char to the end of the C-string s1[i] = '\0'; }//myStrcpy void myStrcat_BC (char *s1, char *s2, int SIZE) { //Data int i = 0; //index loop int j = 0; //index loop if ( (myStrlen(s1) + myStrlen(s2)) < SIZE ){ //concatenate C-strings for (i = 0; s1[i] != '\0'; i++) { i++; }//for // Remove null character i--; for (j = 0; s2[j] != '\0'; j++, i++) { s1[i] = s2[j]; }//for //assign null char to the end of the C-string s1[i] = '\0'; } else { cout << "Error: Out of bounds" << endl; } } //convert to lower case char toLower(char c) { if(c >= 'A' && c <= 'Z') { return char(c + 32); } return c; } //check Palindromic bool isPalindromic (char *s1) { int i; int end; end = myStrlen(s1) - 1; for (i = 0; i < end; i++, end--) { if( toLower(s1[i]) != toLower(s1[end]) ) { return false; } } return true; }
22.906863
81
0.55168
juliafeingold
28fb599ed55c4df97dc288785db3a5542b41d361
227
hpp
C++
tutorials/SkipGram/TextDataSet_utils.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
tutorials/SkipGram/TextDataSet_utils.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
tutorials/SkipGram/TextDataSet_utils.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
#ifndef __TEXT_DATA_SET_UTILS_HPP__ #define __TEXT_DATA_SET_UTILS_HPP__ #include "TextDataSet/ParalleledCorpusDataset.hpp" #include "TextDataSet/SkipGramDataset.hpp" #include "TextDataSet/FourTermAnalogyDataset.hpp" #endif
20.636364
50
0.854626
ChanhyoLee
28fd9919f861eea6a1677447dc099d344721ee2f
123
cpp
C++
triangle.cpp
Piain/GeoShapeCalculator
a102b2b3a1776c92b7220e4bedee733b954394f1
[ "MIT" ]
2
2021-11-27T17:40:05.000Z
2021-11-28T07:22:36.000Z
triangle.cpp
Piain/GeoShapeCalculator
a102b2b3a1776c92b7220e4bedee733b954394f1
[ "MIT" ]
null
null
null
triangle.cpp
Piain/GeoShapeCalculator
a102b2b3a1776c92b7220e4bedee733b954394f1
[ "MIT" ]
null
null
null
#include "triangle.h" float Triangle::Area() { return 0.5 * dim1 * dim2; } char Triangle::Type() { return 't'; }
10.25
29
0.585366
Piain
28fe3a0a51aaeea36b871c3a6099665a365a0e82
14,596
hpp
C++
Lib/Chip/CM4/STMicro/STM32L4x6/FLASH.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/CM4/STMicro/STM32L4x6/FLASH.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/CM4/STMicro/STM32L4x6/FLASH.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Flash namespace FlashAcr{ ///<Access control register using Addr = Register::Address<0x40022000,0xffff80f8,0x00000000,std::uint32_t>; ///Latency constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> latency{}; ///Prefetch enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> prften{}; ///Instruction cache enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> icen{}; ///Data cache enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> dcen{}; ///Instruction cache reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> icrst{}; ///Data cache reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> dcrst{}; ///Flash Power-down mode during Low-power run mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> runPd{}; ///Flash Power-down mode during Low-power sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> sleepPd{}; } namespace FlashPdkeyr{ ///<Power down key register using Addr = Register::Address<0x40022004,0x00000000,0x00000000,std::uint32_t>; ///RUN_PD in FLASH_ACR key constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pdkeyr{}; } namespace FlashKeyr{ ///<Flash key register using Addr = Register::Address<0x40022008,0x00000000,0x00000000,std::uint32_t>; ///KEYR constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> keyr{}; } namespace FlashOptkeyr{ ///<Option byte key register using Addr = Register::Address<0x4002200c,0x00000000,0x00000000,std::uint32_t>; ///Option byte key constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> optkeyr{}; } namespace FlashSr{ ///<Status register using Addr = Register::Address<0x40022010,0xfffe3c04,0x00000000,std::uint32_t>; ///End of operation constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eop{}; ///Operation error constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> operr{}; ///Programming error constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> progerr{}; ///Write protected error constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> wrperr{}; ///Programming alignment error constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pgaerr{}; ///Size error constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> sizerr{}; ///Programming sequence error constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> pgserr{}; ///Fast programming data miss error constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> miserr{}; ///Fast programming error constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> fasterr{}; ///PCROP read error constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rderr{}; ///Option validity error constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> optverr{}; ///Busy constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> bsy{}; } namespace FlashCr{ ///<Flash control register using Addr = Register::Address<0x40022014,0x30f87000,0x00000000,std::uint32_t>; ///Programming constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> pg{}; ///Page erase constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> per{}; ///Bank 1 Mass erase constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> mer1{}; ///Page number constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,3),Register::ReadWriteAccess,unsigned> pnb{}; ///Bank erase constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> bker{}; ///Bank 2 Mass erase constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> mer2{}; ///Start constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> start{}; ///Options modification start constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> optstrt{}; ///Fast programming constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> fstpg{}; ///End of operation interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eopie{}; ///Error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> errie{}; ///PCROP read error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> rderrie{}; ///Force the option byte loading constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> oblLaunch{}; ///Options Lock constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> optlock{}; ///FLASH_CR Lock constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> lock{}; } namespace FlashEccr{ ///<Flash ECC register using Addr = Register::Address<0x40022018,0x3ee00000,0x00000000,std::uint32_t>; ///ECC fail address constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> addrEcc{}; ///ECC fail bank constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> bkEcc{}; ///System Flash ECC fail constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> sysfEcc{}; ///ECC correction interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eccie{}; ///ECC correction constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eccc{}; ///ECC detection constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eccd{}; } namespace FlashOptr{ ///<Flash option register using Addr = Register::Address<0x40022020,0xfc40c800,0x00000000,std::uint32_t>; ///Read protection level constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> rdp{}; ///BOR reset Level constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,unsigned> borLev{}; ///nRST_STOP constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> nrstStop{}; ///nRST_STDBY constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> nrstStdby{}; ///Independent watchdog selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> idwgSw{}; ///Independent watchdog counter freeze in Stop mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> iwdgStop{}; ///Independent watchdog counter freeze in Standby mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> iwdgStdby{}; ///Window watchdog selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> wwdgSw{}; ///Dual-bank boot constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> bfb2{}; ///Dual-Bank on 512 KB or 256 KB Flash memory devices constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> dualbank{}; ///Boot configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> nboot1{}; ///SRAM2 parity check enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> sram2Pe{}; ///SRAM2 Erase when system reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> sram2Rst{}; } namespace FlashPcrop1sr{ ///<Flash Bank 1 PCROP Start address register using Addr = Register::Address<0x40022024,0xffff0000,0x00000000,std::uint32_t>; ///Bank 1 PCROP area start offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> pcrop1Strt{}; } namespace FlashPcrop1er{ ///<Flash Bank 1 PCROP End address register using Addr = Register::Address<0x40022028,0x7fff0000,0x00000000,std::uint32_t>; ///Bank 1 PCROP area end offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> pcrop1End{}; ///PCROP area preserved when RDP level decreased constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> pcropRdp{}; } namespace FlashWrp1ar{ ///<Flash Bank 1 WRP area A address register using Addr = Register::Address<0x4002202c,0xff00ff00,0x00000000,std::uint32_t>; ///Bank 1 WRP first area start offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> wrp1aStrt{}; ///Bank 1 WRP first area A end offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> wrp1aEnd{}; } namespace FlashWrp1br{ ///<Flash Bank 1 WRP area B address register using Addr = Register::Address<0x40022030,0xff00ff00,0x00000000,std::uint32_t>; ///Bank 1 WRP second area B end offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> wrp1bStrt{}; ///Bank 1 WRP second area B start offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> wrp1bEnd{}; } namespace FlashPcrop2sr{ ///<Flash Bank 2 PCROP Start address register using Addr = Register::Address<0x40022044,0xffff0000,0x00000000,std::uint32_t>; ///Bank 2 PCROP area start offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> pcrop2Strt{}; } namespace FlashPcrop2er{ ///<Flash Bank 2 PCROP End address register using Addr = Register::Address<0x40022048,0xffff0000,0x00000000,std::uint32_t>; ///Bank 2 PCROP area end offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> pcrop2End{}; } namespace FlashWrp2ar{ ///<Flash Bank 2 WRP area A address register using Addr = Register::Address<0x4002204c,0xff00ff00,0x00000000,std::uint32_t>; ///Bank 2 WRP first area A start offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> wrp2aStrt{}; ///Bank 2 WRP first area A end offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> wrp2aEnd{}; } namespace FlashWrp2br{ ///<Flash Bank 2 WRP area B address register using Addr = Register::Address<0x40022050,0xff00ff00,0x00000000,std::uint32_t>; ///Bank 2 WRP second area B start offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> wrp2bStrt{}; ///Bank 2 WRP second area B end offset constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> wrp2bEnd{}; } }
75.237113
222
0.702042
operativeF
e90390da38c32e8c601412c45fe0b2b171107b1c
1,161
cpp
C++
KMPSearch/main.cpp
Kapil706/GeeksForGeeks.Cpp-
3251fe2caf29e485656626d758058bd968e50ae1
[ "MIT" ]
1
2019-07-31T16:47:51.000Z
2019-07-31T16:47:51.000Z
KMPSearch/main.cpp
Kapil706/GeeksForGeeks.Cpp-
3251fe2caf29e485656626d758058bd968e50ae1
[ "MIT" ]
null
null
null
KMPSearch/main.cpp
Kapil706/GeeksForGeeks.Cpp-
3251fe2caf29e485656626d758058bd968e50ae1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void ComputeLpsArray(string pat, int m, int*lps){ lps[0]=0; int i=1; int len=0; while (i<m){ if(pat[i]==pat[len]){ len++; lps[i]=len; i++; } else{ if(len!=0){ len=lps[len-1]; } else{ lps[i]=0; i++; } } } } bool KMPsearch(string pat, string txt){ int i=0,j=0; int m=pat.length(); int n=txt.length(); int lps[m]; ComputeLpsArray(pat,m,lps); while(i<n && j<m){ if(pat[j]==txt[i]){ i++; j++; } else if(i<n && pat[j]!=txt[i]){ if(j!=0){ j=lps[j-1]; } else{ i++; } } } return (j==m)?true: false; } int main() { int t; cin>>t; while(t--){ string pat; string txt; cin>>pat>>txt; if(KMPsearch(pat,txt)){ cout<<"Yes"; } else{ cout<<"No"; } } return 0; }
13.5
49
0.342808
Kapil706
e905bd6971c4717a7cd38b8b99a598ae100833b8
390
hpp
C++
src/widgets/settingspages/AccountsPage.hpp
devolution2409/chatterino2
978931bcfc40bae63f65c18e7a3274c77c0f45ca
[ "MIT" ]
null
null
null
src/widgets/settingspages/AccountsPage.hpp
devolution2409/chatterino2
978931bcfc40bae63f65c18e7a3274c77c0f45ca
[ "MIT" ]
null
null
null
src/widgets/settingspages/AccountsPage.hpp
devolution2409/chatterino2
978931bcfc40bae63f65c18e7a3274c77c0f45ca
[ "MIT" ]
null
null
null
#pragma once #include "widgets/AccountSwitchWidget.hpp" #include "widgets/settingspages/SettingsPage.hpp" #include <QPushButton> namespace chatterino { class AccountsPage : public SettingsPage { public: AccountsPage(); private: QPushButton *addButton; QPushButton *removeButton; AccountSwitchWidget *accSwitchWidget; }; } // namespace chatterino
17.727273
50
0.720513
devolution2409
e905e9b07d91960f9659ef9fe7291a47d8ede80e
424
cpp
C++
1100/90/1196.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
1100/90/1196.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
1100/90/1196.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
#include <iostream> #include <unordered_set> int main() { unsigned n; std::cin >> n; std::unordered_set<unsigned> s; while (n-- > 0) { unsigned x; std::cin >> x; s.insert(x); } unsigned m; std::cin >> m; unsigned q = 0; while (m-- > 0) { unsigned x; std::cin >> x; q += s.count(x); } std::cout << q << '\n'; return 0; }
13.25
35
0.441038
actium
e90a396e37cf316b800bb1638a672768528671b4
1,285
hpp
C++
hpx/traits/has_xxx.hpp
bremerm31/hpx
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
[ "BSL-1.0" ]
1
2019-07-04T10:18:01.000Z
2019-07-04T10:18:01.000Z
hpx/traits/has_xxx.hpp
bremerm31/hpx
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
[ "BSL-1.0" ]
1
2018-04-20T14:17:33.000Z
2018-04-20T14:17:33.000Z
hpx/traits/has_xxx.hpp
bremerm31/hpx
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
[ "BSL-1.0" ]
1
2019-03-13T04:53:43.000Z
2019-03-13T04:53:43.000Z
// Copyright (c) 2016 Agustin Berge // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef HPX_TRAITS_HAS_XXX_HPP #define HPX_TRAITS_HAS_XXX_HPP #include <hpx/util/always_void.hpp> #include <hpx/util/detail/pp/cat.hpp> #include <type_traits> // This macro creates a boolean unary metafunction such that for // any type X, has_name<X>::value == true if and only if X is a // class type and has a nested type member x::name. The generated // trait ends up in a namespace where the macro itself has been // placed. #define HPX_HAS_XXX_TRAIT_DEF(Name) \ template <typename T, typename Enable = void> \ struct HPX_PP_CAT(has_, Name) : std::false_type {}; \ \ template <typename T> \ struct HPX_PP_CAT(has_, Name)<T, \ typename hpx::util::always_void<typename T::Name>::type> \ : std::true_type {} \ /**/ #endif
40.15625
79
0.52607
bremerm31
e90d6270cb1a7c77a3e59e11f2183b4f5a2aaeb8
2,237
cc
C++
tensorflow/compiler/mlir/lite/utils/variables_utils.cc
weikhor/tensorflow
ce047fc05c7b5ff54868ba53d724d9c171c4adbb
[ "Apache-2.0" ]
10
2021-05-25T17:43:04.000Z
2022-03-08T10:46:09.000Z
tensorflow/compiler/mlir/lite/utils/variables_utils.cc
CaptainGizzy21/tensorflow
3457a2b122e50b4d44ceaaed5a663d635e5c22df
[ "Apache-2.0" ]
1,056
2019-12-15T01:20:31.000Z
2022-02-10T02:06:28.000Z
tensorflow/compiler/mlir/lite/utils/variables_utils.cc
CaptainGizzy21/tensorflow
3457a2b122e50b4d44ceaaed5a663d635e5c22df
[ "Apache-2.0" ]
6
2016-09-07T04:00:15.000Z
2022-01-12T01:47:38.000Z
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/lite/utils/variables_utils.h" #include "mlir/Dialect/Quant/QuantTypes.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" namespace mlir { namespace TFL { namespace utils { bool IsSupportedVariableType(Operation* op) { ShapedType type; if (llvm::isa<TF::ReadVariableOp>(op)) { type = op->getResult(0).getType().cast<ShapedType>(); } else if (llvm::isa<TF::AssignVariableOp>(op)) { type = op->getOperand(1).getType().cast<ShapedType>(); } auto element_type = type.getElementType(); // Check complex types. if (auto complex_type = element_type.dyn_cast<mlir::ComplexType>()) { auto complex_element_type = complex_type.getElementType(); if (complex_element_type.isF32() || complex_element_type.isF64()) return true; } // Check quantized types. if (auto quant_type = element_type.dyn_cast<mlir::quant::QuantizedType>()) { // TFLite supports QI16, QI32, QI8, and QUI8 if ((quant_type.getStorageTypeIntegralWidth() == 16 && quant_type.isSigned()) || quant_type.getStorageTypeIntegralWidth() == 8 || (quant_type.getStorageTypeIntegralWidth() == 32 && quant_type.isSigned())) return true; } return element_type.isF32() || element_type.isF64() || element_type.isInteger(1) || element_type.isInteger(8) || element_type.isInteger(32) || element_type.isSignlessInteger(64); } } // namespace utils } // namespace TFL } // namespace mlir
39.245614
80
0.692892
weikhor
e90ded7a67d3e0d2b70ea29f3c88c62f3096cdb4
13,040
cpp
C++
tests/gtests/test_reorder.cpp
yzhliu/mkl-dnn
3e1f8f53f6845dce23abf8089501c2eb45420b9e
[ "Apache-2.0" ]
1
2021-04-05T19:16:20.000Z
2021-04-05T19:16:20.000Z
tests/gtests/test_reorder.cpp
yzhliu/mkl-dnn
3e1f8f53f6845dce23abf8089501c2eb45420b9e
[ "Apache-2.0" ]
null
null
null
tests/gtests/test_reorder.cpp
yzhliu/mkl-dnn
3e1f8f53f6845dce23abf8089501c2eb45420b9e
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2016-2017 Intel Corporation * * 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 <utility> #include <numeric> #include "gtest/gtest.h" #include "mkldnn_test_common.hpp" #include "mkldnn.hpp" namespace mkldnn { template <typename data_i_t, typename data_o_t> inline void check_reorder(const memory::desc &md_i, const memory::desc &md_o, const data_i_t *src, const data_o_t *dst) { const int ndims = md_i.data.ndims; const int *dims = md_i.data.dims; const size_t nelems = std::accumulate( dims, dims + ndims, size_t(1), std::multiplies<size_t>()); for (size_t i = 0; i < nelems; ++i) { data_i_t s_raw = src[map_index(md_i, i)]; data_o_t s = static_cast<data_o_t>(s_raw); data_o_t d = dst[map_index(md_o, i)]; ASSERT_EQ(s, d) << "mismatch at position " << i; } } template <typename reorder_types> struct test_simple_params { engine::kind engine_kind; memory::format fmt_i; memory::format fmt_o; memory::dims dims; bool expect_to_fail; mkldnn_status_t expected_status; }; template <typename reorder_types> class reorder_simple_test: public ::testing::TestWithParam<test_simple_params<reorder_types>> { protected: virtual void SetUp() { using data_i_t = typename reorder_types::first_type; using data_o_t = typename reorder_types::second_type; test_simple_params<reorder_types> p = ::testing::TestWithParam<decltype(p)>::GetParam(); ASSERT_TRUE(p.engine_kind == engine::kind::cpu); auto eng = engine(p.engine_kind, 0); const size_t nelems_i = std::accumulate(p.dims.begin(), p.dims.end(), size_t(1), std::multiplies<size_t>()); const size_t nelems_o = std::accumulate(p.dims.begin(), p.dims.end(), size_t(1), std::multiplies<size_t>()); ASSERT_EQ(nelems_i, nelems_o); auto src_data = new data_i_t[nelems_i]; auto dst_data = new data_o_t[nelems_o]; memory::data_type prec_i = data_traits<data_i_t>::data_type; memory::data_type prec_o = data_traits<data_o_t>::data_type; auto mpd_i = memory::primitive_desc({p.dims, prec_i, p.fmt_i}, eng); auto mpd_o = memory::primitive_desc({p.dims, prec_o, p.fmt_o}, eng); /* initialize input data */ for (size_t i = 0; i < nelems_i; ++i) src_data[map_index(mpd_i.desc(), i)] = data_i_t(i); auto src = memory(mpd_i, src_data); auto dst = memory(mpd_o, dst_data); auto test = [&]() { auto r = reorder(src, dst); stream(stream::kind::lazy).submit({r}).wait(); }; if (catch_expected_failures(test, p.expect_to_fail, p.expected_status)) return; check_reorder(mpd_i.desc(), mpd_o.desc(), src_data, dst_data); delete[] src_data; delete[] dst_data; } }; using f32_f32 = std::pair<float, float>; using s32_s32 = std::pair<int32_t, int32_t>; using s16_s16 = std::pair<int16_t, int16_t>; using reorder_simple_expected_fail_f32_f32 = reorder_simple_test<f32_f32>; using reorder_simple_test_data_f32_f32 = reorder_simple_test<f32_f32>; using reorder_simple_test_weights_f32_f32 = reorder_simple_test<f32_f32>; using reorder_simple_test_weights_f32_f32_IOhw16o16i = reorder_simple_test<f32_f32>; using reorder_simple_test_s32_s32 = reorder_simple_test<s32_s32>; using reorder_simple_test_s16_s16 = reorder_simple_test<s16_s16>; using eng = engine::kind; using fmt = memory::format; using test_simple_params_s32_s32 = test_simple_params<s32_s32>; using test_simple_params_f32_f32 = test_simple_params<f32_f32>; using test_simple_params_s16_s16 = test_simple_params<s16_s16>; using cfg_f32= test_simple_params_f32_f32; using cfg_s32= test_simple_params_s32_s32; using cfg_s16= test_simple_params_s16_s16; TEST_P(reorder_simple_expected_fail_f32_f32, TestsReorder) { } INSTANTIATE_TEST_CASE_P(TestReorder, reorder_simple_expected_fail_f32_f32, ::testing::Values( cfg_f32{eng::cpu, fmt::nchw, fmt::nchw, {0, 16, 8, 8}, true, mkldnn_invalid_arguments}, cfg_f32{eng::cpu, fmt::nchw, fmt::nChw8c, {0, 16, 8, 8}, true, mkldnn_invalid_arguments}, cfg_f32{eng::cpu, fmt::nchw, fmt::nChw16c, {0, 16, 8, 8}, true, mkldnn_invalid_arguments}, cfg_f32{eng::cpu, fmt::OIhw8o8i, fmt::oihw, {32, 0, 3, 3}, true, mkldnn_invalid_arguments}, cfg_f32{eng::cpu, fmt::OIhw8i8o, fmt::OIhw8o8i, {0, 32, 3, 3}, true, mkldnn_invalid_arguments}, cfg_f32{eng::cpu, fmt::OIhw16o16i, fmt::oihw, {32, 32, 0, 3}, true, mkldnn_invalid_arguments}, cfg_f32{eng::cpu, fmt::OIhw16i16o, fmt::OIhw16o16i, {32, 32, 3, 0}, true, mkldnn_invalid_arguments} ) ); TEST_P(reorder_simple_test_data_f32_f32, TestsReorder) { } INSTANTIATE_TEST_CASE_P(TestReorder, reorder_simple_test_data_f32_f32, ::testing::Values( cfg_f32{eng::cpu, fmt::nchw, fmt::nchw, {10, 10, 13, 13}}, cfg_f32{eng::cpu, fmt::nchw, fmt::nhwc, {10, 10, 10, 10}}, cfg_f32{eng::cpu, fmt::nhwc, fmt::nchw, {10, 10, 10, 10}}, cfg_f32{eng::cpu, fmt::nchw, fmt::chwn, {28, 3, 10, 10}}, cfg_f32{eng::cpu, fmt::chwn, fmt::nchw, {28, 3, 10, 10}}, cfg_f32{eng::cpu, fmt::nhwc, fmt::nhwc, {10, 10, 13, 13}}, cfg_f32{eng::cpu, fmt::nchw, fmt::nChw8c, {2, 32, 4, 4}}, cfg_f32{eng::cpu, fmt::nChw8c, fmt::nchw, {2, 32, 4, 4}}, cfg_f32{eng::cpu, fmt::chwn, fmt::nChw8c, {28, 96, 10, 10}}, cfg_f32{eng::cpu, fmt::nChw8c, fmt::chwn, {28, 96, 10, 10}}, cfg_f32{eng::cpu, fmt::nhwc, fmt::nChw8c, {3, 64, 16, 16}}, cfg_f32{eng::cpu, fmt::nChw8c, fmt::nhwc, {3, 64, 16, 16}}, cfg_f32{eng::cpu, fmt::nChw8c, fmt::nChw16c, {10, 96, 27, 27}}, cfg_f32{eng::cpu, fmt::nChw16c, fmt::nChw8c, {10, 96, 27, 27}}, cfg_f32{eng::cpu, fmt::nchw, fmt::nChw16c, {2, 64, 4, 4}}, cfg_f32{eng::cpu, fmt::nChw16c, fmt::nchw, {2, 64, 4, 4}}, cfg_f32{eng::cpu, fmt::chwn, fmt::nChw16c, {28, 96, 10, 10}}, cfg_f32{eng::cpu, fmt::nChw16c, fmt::chwn, {28, 96, 10, 10}}, cfg_f32{eng::cpu, fmt::nhwc, fmt::nChw16c, {2, 64, 4, 4}}, cfg_f32{eng::cpu, fmt::nChw16c, fmt::nhwc, {2, 64, 4, 4}} ) ); TEST_P(reorder_simple_test_weights_f32_f32, TestsReorder) { } INSTANTIATE_TEST_CASE_P(TestReorder, reorder_simple_test_weights_f32_f32, ::testing::Values( cfg_f32{eng::cpu, fmt::hwio, fmt::oihw, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::oihw, fmt::hwio, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::hwio, fmt::Ohwi8o, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::Ohwi8o, fmt::hwio, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::hwio, fmt::Ohwi16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::Ohwi16o, fmt::hwio, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::oihw, fmt::OIhw8i8o, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw8i8o, fmt::oihw, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::ihwo, fmt::OIhw8i8o, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw8i8o, fmt::ihwo, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::oihw, fmt::OIhw8o8i, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw8o8i, fmt::oihw, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw8i8o, fmt::OIhw8o8i, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw8o8i, fmt::OIhw8i8o, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::hwio, fmt::OIhw8i8o, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw8i8o, fmt::hwio, {32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::goihw, fmt::hwigo, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::hwigo, fmt::goihw, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::goihw, fmt::gOIhw8i8o, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw8i8o, fmt::goihw, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::goihw, fmt::gOIhw8o8i, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw8o8i, fmt::goihw, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw8i8o, fmt::gOIhw8o8i, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw8o8i, fmt::gOIhw8i8o, {2, 32, 32, 3, 3}}, cfg_f32{eng::cpu, fmt::oihw, fmt::OIhw16i16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw16i16o, fmt::oihw, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::ihwo, fmt::OIhw16i16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw16i16o, fmt::ihwo, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::oihw, fmt::OIhw16o16i, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw16o16i, fmt::oihw, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::hwio, fmt::OIhw16i16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw16i16o, fmt::hwio, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::goihw, fmt::gOIhw16i16o, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw16i16o, fmt::goihw, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::goihw, fmt::gOIhw16o16i, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw16o16i, fmt::goihw, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw16i16o, fmt::OIhw16o16i, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw16o16i, fmt::OIhw16i16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw16i16o, fmt::gOIhw16o16i, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw16o16i, fmt::gOIhw16i16o, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::oihw, fmt::Oihw16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::Oihw16o, fmt::oihw, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::goihw, fmt::gOihw16o, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOihw16o, fmt::goihw, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::Ohwi16o, fmt::Oihw16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::Oihw16o, fmt::Ohwi16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOhwi16o, fmt::gOihw16o, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOihw16o, fmt::gOhwi16o, {2, 64, 64, 3, 3}} ) ); TEST_P(reorder_simple_test_weights_f32_f32_IOhw16o16i, TestsReorder) { } INSTANTIATE_TEST_CASE_P(TestReorder, reorder_simple_test_weights_f32_f32_IOhw16o16i, ::testing::Values( cfg_f32{eng::cpu, fmt::oihw, fmt::IOhw16o16i, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::IOhw16o16i, fmt::oihw, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::OIhw16i16o, fmt::IOhw16o16i, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::IOhw16o16i, fmt::OIhw16i16o, {64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::goihw, fmt::gOIhw16o16i, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gIOhw16o16i, fmt::goihw, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gOIhw16i16o, fmt::gIOhw16o16i, {2, 64, 64, 3, 3}}, cfg_f32{eng::cpu, fmt::gIOhw16o16i, fmt::gOIhw16i16o, {2, 64, 64, 3, 3}} ) ); TEST_P(reorder_simple_test_s32_s32, TestsReorder) { } INSTANTIATE_TEST_CASE_P(TestReorder, reorder_simple_test_s32_s32, ::testing::Values( cfg_s32{eng::cpu, fmt::nchw, fmt::nChw16c, {2, 64, 4, 4}}, cfg_s32{eng::cpu, fmt::nChw16c, fmt::nchw, {2, 64, 4, 4}} ) ); TEST_P(reorder_simple_test_s16_s16, TestsReorder) { } INSTANTIATE_TEST_CASE_P(TestReorder, reorder_simple_test_s16_s16, ::testing::Values( cfg_s16{eng::cpu, fmt::oihw, fmt::OIhw8i16o2i, {64, 64, 3, 3}}, cfg_s16{eng::cpu, fmt::OIhw8i16o2i, fmt::oihw, {64, 64, 3, 3}}, cfg_s16{eng::cpu, fmt::goihw, fmt::gOIhw8i16o2i, {2, 64, 64, 3, 3}}, cfg_s16{eng::cpu, fmt::gOIhw8i16o2i, fmt::goihw, {2, 64, 64, 3, 3}}, cfg_s16{eng::cpu, fmt::OIhw8i16o2i, fmt::OIhw8o16i2o, {64, 64, 3, 3}}, cfg_s16{eng::cpu, fmt::OIhw8o16i2o, fmt::OIhw8i16o2i, {64, 64, 3, 3}}, cfg_s16{eng::cpu, fmt::gOIhw8i16o2i, fmt::gOIhw8o16i2o, {2, 64, 64, 3, 3}}, cfg_s16{eng::cpu, fmt::gOIhw8o16i2o, fmt::gOIhw8i16o2i, {2, 64, 64, 3, 3}} ) ); }
48.838951
87
0.58796
yzhliu
e90e2e5d2bbae2764a68b6f7df88deb4231acee8
5,579
cpp
C++
Tudat/SimulationSetup/PropagationSetup/createStateDerivativeModel.cpp
different91988/tudat
97b287fe759979cf2028c9180f0abafa2487dde4
[ "BSD-3-Clause" ]
null
null
null
Tudat/SimulationSetup/PropagationSetup/createStateDerivativeModel.cpp
different91988/tudat
97b287fe759979cf2028c9180f0abafa2487dde4
[ "BSD-3-Clause" ]
null
null
null
Tudat/SimulationSetup/PropagationSetup/createStateDerivativeModel.cpp
different91988/tudat
97b287fe759979cf2028c9180f0abafa2487dde4
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2018, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #include "Tudat/SimulationSetup/PropagationSetup/createStateDerivativeModel.h" namespace tudat { namespace propagators { //! Function to create an integrator to propagate the dynamics (in normalized units) in CR3BP std::shared_ptr< numerical_integrators::NumericalIntegrator< double, Eigen::Vector6d > > createCR3BPIntegrator( const std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings, const double massParameter, const Eigen::Vector6d& initialState ) { // Create state derivative model std::shared_ptr< StateDerivativeCircularRestrictedThreeBodyProblem > stateDerivativeModel = std::make_shared< StateDerivativeCircularRestrictedThreeBodyProblem >( massParameter ); std::function< Eigen::Vector6d( const double, const Eigen::Vector6d& ) > stateDerivativeFunction = std::bind( &StateDerivativeCircularRestrictedThreeBodyProblem::computeStateDerivative, stateDerivativeModel, std::placeholders::_1, std::placeholders::_2 ); // Create integrator object return numerical_integrators::createIntegrator< double, Eigen::Vector6d >( stateDerivativeFunction, initialState, integratorSettings ); } //! Function to propagate the dynamics (in normalized units) in CR3BP std::map< double, Eigen::Vector6d > performCR3BPIntegration( const std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings, const double massParameter, const Eigen::Vector6d& initialState, const double finalTime ) { // Create integrator object std::shared_ptr< numerical_integrators::NumericalIntegrator< double, Eigen::Vector6d > > integrator = createCR3BPIntegrator( integratorSettings, massParameter, initialState ); // Initialize return data map std::map< double, Eigen::Vector6d > stateHistory; // Store initial state and time double currentTime = integratorSettings->initialTime_; Eigen::Vector6d currentState = initialState; stateHistory[ currentTime ] = currentState; // Integrate to final time double timeStep = integratorSettings->initialTimeStep_; while( currentTime <= finalTime ) { currentState = integrator->performIntegrationStep( timeStep ); currentTime = integrator->getCurrentIndependentVariable( ); timeStep = integrator->getNextStepSize( ); stateHistory[ currentTime ] = currentState; } return stateHistory; } template std::vector< std::shared_ptr< SingleStateTypeDerivative< double, double > > > createStateDerivativeModels< double, double >( const std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const double propagationStartTime ); template std::shared_ptr< SingleStateTypeDerivative< double, double > > createStateDerivativeModel< double, double >( const std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const double propagationStartTime ); #if( BUILD_EXTENDED_PRECISION_PROPAGATION_TOOLS ) template std::vector< std::shared_ptr< SingleStateTypeDerivative< long double, double > > > createStateDerivativeModels< long double, double >( const std::shared_ptr< SingleArcPropagatorSettings< long double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const double propagationStartTime ); template std::vector< std::shared_ptr< SingleStateTypeDerivative< double, Time > > > createStateDerivativeModels< double, Time >( const std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const Time propagationStartTime ); template std::vector< std::shared_ptr< SingleStateTypeDerivative< long double, Time > > > createStateDerivativeModels< long double, Time >( const std::shared_ptr< SingleArcPropagatorSettings< long double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const Time propagationStartTime ); template std::shared_ptr< SingleStateTypeDerivative< long double, double > > createStateDerivativeModel< long double, double >( const std::shared_ptr< SingleArcPropagatorSettings< long double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const double propagationStartTime ); template std::shared_ptr< SingleStateTypeDerivative< double, Time > > createStateDerivativeModel< double, Time >( const std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const Time propagationStartTime ); template std::shared_ptr< SingleStateTypeDerivative< long double, Time > > createStateDerivativeModel< long double, Time >( const std::shared_ptr< SingleArcPropagatorSettings< long double > > propagatorSettings, const simulation_setup::NamedBodyMap& bodyMap, const Time propagationStartTime ); #endif } }
51.183486
143
0.743861
different91988
e912754c7a362cbcfffacfd153478740497bd4e7
210
cpp
C++
cpp_primer/01/1.4/printIntNumber_for.cpp
jo-ny/cplusplus_learn
d1a126b2d7efd0c7599785c14a25b6c7e1b19c73
[ "Apache-2.0" ]
null
null
null
cpp_primer/01/1.4/printIntNumber_for.cpp
jo-ny/cplusplus_learn
d1a126b2d7efd0c7599785c14a25b6c7e1b19c73
[ "Apache-2.0" ]
null
null
null
cpp_primer/01/1.4/printIntNumber_for.cpp
jo-ny/cplusplus_learn
d1a126b2d7efd0c7599785c14a25b6c7e1b19c73
[ "Apache-2.0" ]
null
null
null
#include<iostream> int main(){ int start,end; std::cout << "Enter start and end number:"; std::cin >> start >> end; for (; start <= end; ++start){ std::cout << start << " "; } std::cout << std::endl; }
19.090909
44
0.561905
jo-ny
e912d79a48ed51f65a29fc19c25ce0ebb7737135
10,434
cpp
C++
Level_9_HW/F_FiniteDifferenceMethods/F_FiniteDifferenceMethods/main.cpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_9_HW/F_FiniteDifferenceMethods/F_FiniteDifferenceMethods/main.cpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_9_HW/F_FiniteDifferenceMethods/F_FiniteDifferenceMethods/main.cpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
// // main.cpp // F_FiniteDifferenceMethods // // Created by Zhehao Li on 2020/5/27. // Copyright © 2020 Zhehao Li. All rights reserved. // // F. Finite Difference Methods (Introduction) #include "FDMDirector.hpp" #include <iostream> #include <string> #include <cmath> using namespace std; // Black Scholes namespace namespace BS{ double sig = 0.3; // Volaitility double K = 65.0; // Strike double r = 0.08; // Risk-free rate double D = 0.0; // Dividend double Tmax = 0.25; // Max Time double Smax = 3.0 * K; // Max price int NS = static_cast<int>(Smax); // Length of price space int NT = 10000 - 1; // Length of time space double mySigma (double x, double t){ double sigmaS = sig * sig; return 0.5 * sigmaS * x * x; } double myMu (double x, double t){ return (r - D) * x; } double myB (double x, double t){ return -r; } double myF (double x, double t){ return 0.0; } // Boundary condition at the bottom of matrix, S = 0 double myBCL (double t, string optType){ if (optType == "C") { return 0.0; // Call } else{ return K * exp(-r * t); // Put } } // Boundary condition at the top of matrix, S = Smax double myBCR (double t, string optType){ if (optType == "C") { return (Smax - K) * exp(-r * t); // Call } else{ return 0.0; // Put } } // Payoff at t = T double myIC (double x, string optType){ if (optType == "C") { return fmax(x - K, 0.0); // Call } else{ return fmax(K - x, 0.0); // Put } } } int main(int argc, const char * argv[]) { // 0. Assignment of functions ParabolicIBVP::sigma = BS::mySigma; ParabolicIBVP::mu = BS::myMu; ParabolicIBVP::bb = BS::myB; ParabolicIBVP::ff = BS::myF; ParabolicIBVP::BCL = BS::myBCL; ParabolicIBVP::BCR = BS::myBCR; ParabolicIBVP::IC = BS::myIC; // Test Examples: // Batch 1: T = 0.25, K = 65, sig = 0.30, r = 0.08, S = 60 (C = 2.13337, P = 5.84628) // ------------------------------------- // ------------- Batch 1 --------------- // ------------------------------------- // 1. Initialize parameters BS::sig = 0.4; // Volatility BS::K = 120.0; // Strike BS::r = 0.04; // Risk-free rate BS::D = 0.0; // Dividend BS::Tmax = 1.00; // Max time BS::Smax = 3.0 * BS::K; // Max price BS::NS = static_cast<int>(BS::Smax); // Length of price space BS::NT = 100000 - 1; // Length of time space // 2.0 Call option double S0 = 100.0; // Initial Price string optionType = "C"; // Option Type // 2.1 Implement the Finite Different Methods (Explicit Euler) FDMDirector fdir(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 2.2 Get the option price vector at t = 0 std::vector<double> currArray = fdir.current(); // 2.3 Output the result at t = 0 cout << "Stock Price | Call Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 1: " << S0 << " | " << currArray[int(S0)] << endl; // 3.0 Put option optionType = "P"; // 3.1 Implement the Finite Different Methods (Explicit Euler) fdir = FDMDirector(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 3.2 Get the option price vector at t = 0 currArray = fdir.current(); // 3.3 Output the result at t = 0 cout << "Stock Price | Put Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 1: " << S0 << " | " << currArray[int(S0)] << "\n\n"; // Batch 2: T = 1.0, K = 100, sig = 0.2, r = 0.0, S = 100 (C = 7.96557, P = 7.96557) // ------------------------------------- // ------------- Batch 2 --------------- // ------------------------------------- // 1. Initialize parameters BS::sig = 0.2; // Volatility BS::K = 100.0; // Strike BS::r = 0.00; // Risk-free rate BS::D = 0.0; // Dividend BS::Tmax = 1.0; // Max time BS::Smax = 3.0 * BS::K; // Max price BS::NS = static_cast<int>(BS::Smax); // Length of price space BS::NT = 10000 - 1; // Length of time space // 2.0 Call option S0 = 100.0; // Initial Price optionType = "C"; // Option Type // 2.1 Implement the Finite Different Methods (Explicit Euler) fdir = FDMDirector(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 2.2 Get the option price vector at t = 0 currArray = fdir.current(); // 2.3 Output the result at t = 0 cout << "Stock Price | Call Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 2: " << S0 << " | " << currArray[int(S0)] << endl; // 3.0 Put option optionType = "P"; // 3.1 Implement the Finite Different Methods (Explicit Euler) fdir = FDMDirector(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 3.2 Get the option price vector at t = 0 currArray = fdir.current(); // 3.3 Output the result at t = 0 cout << "Stock Price | Put Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 2: " << S0 << " | " << currArray[int(S0)] << "\n\n"; // Batch 3: T = 1.0, K = 10, sig = 0.50, r = 0.12, S = 5 (C = 0.204058, P = 4.07326) // ------------------------------------- // ------------- Batch 3 --------------- // ------------------------------------- // 1. Initialize parameters BS::sig = 0.50; // Volatility BS::K = 10.0; // Strike BS::r = 0.12; // Risk-free rate BS::D = 0.0; // Dividend BS::Tmax = 1.0; // Max time BS::Smax = 3.0 * BS::K; // Max price BS::NS = static_cast<int>(BS::Smax); // Length of price space BS::NT = 10000 - 1; // Length of time space // 2.0 Call option S0 = 5.0; // Initial Price optionType = "C"; // Option Type // 2.1 Implement the Finite Different Methods (Explicit Euler) fdir = FDMDirector(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 2.2 Get the option price vector at t = 0 currArray = fdir.current(); // 2.3 Output the result at t = 0 cout << "Stock Price | Call Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 3: " << S0 << " | " << currArray[int(S0)] << endl; // 3.0 Put option optionType = "P"; // 3.1 Implement the Finite Different Methods (Explicit Euler) fdir = FDMDirector(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 3.2 Get the option price vector at t = 0 currArray = fdir.current(); // 3.3 Output the result at t = 0 cout << "Stock Price | Put Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 3: " << S0 << " | " << currArray[int(S0)] << "\n\n"; // Batch 4: T = 30.0, K = 100.0, sig = 0.30, r = 0.08, S = 100.0 (C = 92.17570, P = 1.24750) // ------------------------------------- // ------------- Batch 4 --------------- // ------------------------------------- // 1. Initialize parameters BS::sig = 0.30; // Volatility BS::K = 100.0; // Strike BS::r = 0.08; // Risk-free rate BS::D = 0.0; // Dividend BS::Tmax = 30.0; // Max time BS::Smax = 6.0 * BS::K; // Max price BS::NS = static_cast<int>(BS::Smax); // Length of price space BS::NT = 1000000; // Length of time space // 2.0 Call option S0 = 100.0; // Initial Price optionType = "C"; // Option Type // 2.1 Implement the Finite Different Methods (Explicit Euler) fdir = FDMDirector(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 2.2 Get the option price vector at t = 0 currArray = fdir.current(); // 2.3 Output the result at t = 0 cout << "Stock Price | Call Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 4: " << S0 << " | " << currArray[int(S0)] << endl; // 3.0 Put option optionType = "P"; // 3.1 Implement the Finite Different Methods (Explicit Euler) fdir = FDMDirector(BS::Smax, BS::Tmax, BS::NS, BS::NT, optionType); fdir.doIt(); // 3.2 Get the option price vector at t = 0 currArray = fdir.current(); // 3.3 Output the result at t = 0 cout << "Stock Price | Put Price \n"; // for (int i = 0; i < currArray.size(); i++) { // cout << fdir.sarr[i] << " | " << currArray[i] << endl; // } cout << "Batch 4: " << S0 << " | " << currArray[int(S0)] << "\n\n"; return 0; }
33.549839
99
0.437512
ZhehaoLi9705
e914b0504a4a37f31875d012cb9980fd92d63821
988
hpp
C++
engine/runtime/rendering/generator/axis_swap_shape.hpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
791
2016-11-04T14:13:41.000Z
2022-03-20T20:47:31.000Z
engine/runtime/rendering/generator/axis_swap_shape.hpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
28
2016-12-01T05:59:30.000Z
2021-03-20T09:49:26.000Z
engine/runtime/rendering/generator/axis_swap_shape.hpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
151
2016-12-21T09:44:43.000Z
2022-03-31T13:42:18.000Z
#ifndef GENERATOR_AXISSWAPSHAPE_HPP #define GENERATOR_AXISSWAPSHAPE_HPP #include "transform_shape.hpp" namespace generator { /// Swaps the x and y axis. template <typename shape_t> class axis_swap_shape_t { private: using impl_t = transform_shape_t<shape_t>; impl_t transform_shape_; public: /// @param shape Source data shape. axis_swap_shape_t(shape_t shape) : transform_shape_{std::move(shape), [](shape_vertex_t& vertex) { std::swap(vertex.position[0u], vertex.position[1u]); std::swap(vertex.tangent[0u], vertex.tangent[1u]); }} { } using edges_t = typename impl_t::edges_t; edges_t edges() const noexcept { return transform_shape_.edges(); } using vertices_t = typename impl_t::vertices_t; vertices_t vertices() const noexcept { return transform_shape_.vertices(); } }; template <typename shape_t> axis_swap_shape_t<shape_t> axis_swap_shape(shape_t shape) { return axis_swap_shape_t<shape_t>{std::move(shape)}; } } #endif
19.76
67
0.733806
ValtoForks
e914c30bd57cf84a2460967272810126e63625c0
5,990
cpp
C++
NoFTL_v1.0/shoreMT/src/sm/pax-tests/sm_hash.cpp
DBlabRT/NoFTL
cba8b5a6d9c422bdd39b01575244e557cbd12e43
[ "Unlicense" ]
4
2019-01-24T02:00:23.000Z
2021-03-17T11:56:59.000Z
NoFTL_v1.0/shoreMT/src/sm/pax-tests/sm_hash.cpp
DBlabRT/NoFTL
cba8b5a6d9c422bdd39b01575244e557cbd12e43
[ "Unlicense" ]
null
null
null
NoFTL_v1.0/shoreMT/src/sm/pax-tests/sm_hash.cpp
DBlabRT/NoFTL
cba8b5a6d9c422bdd39b01575244e557cbd12e43
[ "Unlicense" ]
4
2019-01-22T10:35:55.000Z
2021-03-17T11:57:23.000Z
///////////////////////////////////////////////////////// // memory hash table to be used in hash join. /////////////////////////////////////////////////////// #include "sm_hash.h" // import the hash function from stringhash.C w_base_t::uint4_t hash(const char *p) { //FUNC(hash(char *)); const char *c=p; int len; int i; int b; int m=1 ; unsigned long sum = 0; c++; len = strlen(c); for(i=0; i<len; i++) { // compute push-button signature // of a sort (has to include the rest of the // ascii characters switch(*c) { #define CASES(a,b,c,d,e,f) case a: case b: case c: case d: case e: case f: CASES('a','b','c','A','B','C') b = 2; break; CASES('d','e','f','D','E','F') b = 3; break; CASES('g','h','i','G','H','I') b = 4; break; CASES('j','k','l','J','K','L') b = 5; break; CASES('m','n','o','M','N','O') b = 6; break; CASES('p','r','s','P','R','S') b = 7; break; CASES('t','u','v','T','U','V') b = 8; break; CASES('w','x','y','W','X','Y') b = 9; break; default: b = 1; break; } sum += (unsigned) (b * m); m = m * 10; } //DUMP(end of hash(char *)); return sum; } hash_table_t::hash_table_t (uint4_t size) { m_size = size; m_table = new table_entry_t [m_size]; } hash_table_t::~hash_table_t() { this->reset(); delete [] m_table; } uint4_t hash_table_t::hash_val(const char* key) //hash was defined in stringhash.C { return hash(key) % m_size; } void hash_table_t::add(const char * key, void* val) { uint4_t hval = hash_val(key); table_entry_t* bucket = &m_table[hval]; // see if the key is already in the table. table_entry_t* entry = NULL; for (entry=bucket->next; entry!=bucket; entry = entry->next) if (strcmp(key, entry->key) == 0) break; if (entry == bucket) { // the key is not in the bucket. entry = new table_entry_t; int len = strlen(key); entry->key = new char[len+1]; strncpy(entry->key, key,len); entry->key[len] = '\0'; entry->next = bucket->next; entry->prev = bucket; bucket->next->prev = entry; bucket->next= entry; } entry->val_array.push_back(val); } hash_table_t::val_array_t* hash_table_t::find_match(const char* key) { uint4_t hval = hash_val(key); table_entry_t* bucket = &m_table[hval]; table_entry_t* entry; for (entry = bucket->next; entry!=bucket; entry = entry->next) if (strcmp(key, entry->key) == 0) break; // find the match if (entry != bucket) return &entry->val_array; else // not found return NULL; } void hash_table_t::reset() { table_entry_t* entry; uint4_t bukInx; for (bukInx =0; bukInx < m_size; bukInx++) { for (entry = m_table[bukInx].next; entry != &m_table[bukInx]; entry=entry->next) { w_assert3(entry!=NULL); /* I don't think this does anything and I am not sure why it's here anyway for (i=0; i < entry->val_array.getsize(); i++) delete entry->val_array[i]; entry->val_array.reset(); */ delete [] entry->key; entry->prev->next = entry->next; entry->next->prev = entry->prev; delete entry; } } } uint4_t hash_func_c::operator()(const file_info_t& finfo, const char* frec, int col) { const char* field_ptr = FIELD_START(finfo,frec,col); switch(finfo.field_type[col]) { case SM_INTEGER: return this->operator()(*(int*)field_ptr); case SM_DATE8: case SM_FLOAT: return this->operator()(*(double*)field_ptr); case SM_DATE: case SM_CHAR: case SM_VARCHAR: // string is terminated return this->operator()(field_ptr); default: cerr << "Bad type found in column " << col << endl; w_assert3(0); return 0; } } uint4_t hash_func_c::operator()(const file_info_t& finfo, const precord_t& prec, int col) { switch(finfo.field_type[col]) { case SM_INTEGER: return this->operator()(*(int*) prec.data[col]); case SM_DATE8: case SM_FLOAT: return this->operator()(*(double*) prec.data[col]); case SM_DATE: case SM_CHAR: case SM_VARCHAR: return this->operator()(prec.data[col]) ; default: cerr << "Bad type found in column " << col << endl; w_assert3(0) ; return 0 ; } } uint4_t hash_func_c::operator()(const file_info_t& finfo, const hpl_record_t& hpl_rec, int col) { switch(finfo.field_type[col]) { case SM_INTEGER: return this->operator()(*(int*) hpl_rec.data[col]); case SM_DATE8: case SM_FLOAT: return this->operator()(*(double*) hpl_rec.data[col]); case SM_DATE: case SM_CHAR: case SM_VARCHAR: return this->operator()(hpl_rec.data[col]) ; default: cerr << "Bad type found in column " << col << endl; w_assert3(0) ; return 0 ; } } uint4_t hash_func_c::operator()(int int_val) { sprintf(buf, "%d", int_val) ; return this->operator()(buf) ; } uint4_t hash_func_c::operator()(double double_val) { sprintf(buf, "%f", double_val); return this->operator()(buf) ; } uint4_t hash_func_c::operator()(const char* str_val) { uint4_t h = 0; // HPL: //for ( ; *str_val; ++str_val) h = 5*h + *str_val; for (int counter=0 ; (*str_val) && (counter < 2); ++str_val, counter++) h = 5*h + *str_val; return h % ht_size ; } uint4_t hash_func_c::operator()(char* str_val) { uint4_t h = 0; // HPL: //for ( ; *str_val; ++str_val) h = 5*h + *str_val; for (int counter=0 ; (*str_val) && (counter < 2); ++str_val, counter++) h = 5*h + *str_val; return h % ht_size ; } #ifdef __GNUG__ template class dynarray<void*>; #endif
24.54918
96
0.546912
DBlabRT
e915a52d0863d1963ed11820027f9e01f5e1a972
8,424
cpp
C++
Libraries/Editor/ColorScheme.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
1
2019-07-13T03:36:11.000Z
2019-07-13T03:36:11.000Z
Libraries/Editor/ColorScheme.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Editor/ColorScheme.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Zero { namespace Events { DefineEvent(ColorSchemeChanged); } void GetStringsTextConfig(HandleParam instance, Property* property, Array<String>& strings) { ColorScheme* colorScheme = instance.Get<ColorScheme*>(); forRange (auto& scheme, colorScheme->mAvailableSchemes.All()) strings.PushBack(scheme.first); } ZilchDefineType(ColorScheme, builder, type) { type->HandleManager = ZilchManagerId(PointerManager); type->Add(new MetaOperations()); ZilchBindGetterSetterProperty(ActiveScheme)->Add(new EditorIndexedStringArray(GetStringsTextConfig)); ZilchBindFieldProperty(Default); ZilchBindFieldProperty(Background); ZilchBindFieldProperty(Selection); ZilchBindFieldProperty(LineSelection); ZilchBindFieldProperty(Comment); ZilchBindFieldProperty(StringLiteral); ZilchBindFieldProperty(Number); ZilchBindFieldProperty(Keyword); ZilchBindFieldProperty(Operator); // until we have a zilch lexer setup that colors the class/function names // these fields should not be exposed as a property since they currently have // no effect ZilchBindField(ClassName); ZilchBindField(FunctionName); ZilchBindFieldProperty(SpecialWords); ZilchBindFieldProperty(Error); ZilchBindFieldProperty(Whitespace); ZilchBindFieldProperty(Gutter); ZilchBindFieldProperty(GutterText); ZilchBindFieldProperty(Link); ZilchBindFieldProperty(TextMatchIndicator); ZilchBindFieldProperty(TextMatchHighlight); ZilchBindFieldProperty(TextMatchOutlineAlpha)->Add(new EditorSlider()); ZilchBindGetterSetterProperty(SaveName); ZilchBindMethodProperty(Save)->AddAttribute(FunctionAttributes::cInvalidatesObject); } void ColorPropertyChanged(BoundType* meta, Property* property, ObjPtr instance, AnyParam oldValue, AnyParam newValue) { ColorScheme* colorScheme = (ColorScheme*)instance; colorScheme->Modified(); } ColorScheme::ColorScheme() { Default = FloatColorRGBA(0xDA, 0xDA, 0xDA, 0xFF); Background = FloatColorRGBA(0x21, 0x1E, 0x1E, 0xFF); Selection = FloatColorRGBA(0x45, 0x40, 0x40, 0xFF); LineSelection = FloatColorRGBA(0x35, 0x30, 0x30, 0xFF); Comment = FloatColorRGBA(0x00, 0x80, 0x00, 0xFF); StringLiteral = FloatColorRGBA(0xAD, 0x93, 0x61, 0xFF); Number = FloatColorRGBA(0xDA, 0xDA, 0xDA, 0xFF); Keyword = FloatColorRGBA(0x69, 0x69, 0xFA, 0xFF); Operator = FloatColorRGBA(0xDA, 0xDA, 0xDA, 0xFF); ClassName = FloatColorRGBA(0x98, 0x4A, 0x4A, 0xFF); FunctionName = FloatColorRGBA(0x98, 0x4A, 0x4A, 0xFF); SpecialWords = FloatColorRGBA(0xC1, 0xC1, 0x44, 0xFF); Error = FloatColorRGBA(0xC8, 0x00, 0x00, 0xFF); Whitespace = FloatColorRGBA(0x60, 0x60, 0x60, 0xFF); Gutter = FloatColorRGBA(0x21, 0x1E, 0x1E, 0xFF); GutterText = FloatColorRGBA(0x90, 0x90, 0x90, 0xFF); Link = FloatColorRGBA(0x64, 0x64, 0xFA, 0xFF); TextMatchIndicator = FloatColorRGBA(0x40, 0xE0, 0xD0, 0xBF); TextMatchHighlight = FloatColorRGBA(0x40, 0xE0, 0xD0, 0x32); TextMatchOutlineAlpha = 0x69; } ColorScheme::~ColorScheme() { } // Hex order of RGB is different from the order of the // ByteColor so swap the order for saving / loading uint ConvertByteColorHexOrder(const uint& inputColor) { return ByteColorRGBA(((byte*)&inputColor)[2], ((byte*)&inputColor)[1], ((byte*)&inputColor)[0], 0xFF); } void SerializeRGBColor(Serializer& stream, cstr fieldName, uint& colorValue) { if (stream.GetMode() == SerializerMode::Loading) { StringRange stringRange; bool serialized = stream.StringField("Color", fieldName, stringRange); if (serialized) { u64 fullInt = (u64)ReadHexString(stringRange); colorValue = ConvertByteColorHexOrder((uint)fullInt); } } else { const uint colorTripleSize = 6; char texBuffer[colorTripleSize + 1]; WriteToHexSize(texBuffer, colorTripleSize + 1, colorTripleSize, ConvertByteColorHexOrder(colorValue), true); StringRange stringRange = texBuffer; stream.StringField("Color", fieldName, stringRange); } } #define SerializeRGBColorName(fieldName) SerializeRGBColor(stream, #fieldName, fieldName) void ColorScheme::Serialize(Serializer& stream) { SerializeNameDefault(Default, Vec4::cZero); SerializeNameDefault(Background, Vec4::cZero); SerializeNameDefault(Selection, Vec4::cZero); SerializeNameDefault(LineSelection, Vec4::cZero); SerializeNameDefault(Comment, Vec4::cZero); SerializeNameDefault(StringLiteral, Vec4::cZero); SerializeNameDefault(Number, Vec4::cZero); SerializeNameDefault(Keyword, Vec4::cZero); SerializeNameDefault(Operator, Vec4::cZero); SerializeNameDefault(ClassName, Vec4::cZero); SerializeNameDefault(FunctionName, Vec4::cZero); SerializeNameDefault(SpecialWords, Vec4::cZero); SerializeNameDefault(Error, Vec4::cZero); SerializeNameDefault(Whitespace, Vec4::cZero); SerializeNameDefault(Directive, Vec4::cZero); SerializeNameDefault(Gutter, Vec4::cZero); SerializeNameDefault(GutterText, Vec4::cZero); SerializeNameDefault(Link, Vec4::cZero); SerializeNameDefault(TextMatchIndicator, Vec4::cZero); SerializeNameDefault(TextMatchHighlight, Vec4::cZero); SerializeNameDefault(TextMatchOutlineAlpha, 0.0f); } String ColorScheme::GetActiveScheme() { return mActiveName; } void ColorScheme::SetActiveScheme(StringParam name) { Load(name); UpdateConfig(); // If they are not a developer they can not // edit the built in color schemes if (Z::gEngine->GetConfigCog()->has(DeveloperConfig) == NULL) mFilePath = String(); Modified(); } void ColorScheme::SetSaveName(StringParam name) { // Clear location for custom mFilePath = String(); mSaveName = name; } void ColorScheme::UpdateConfig() { TextEditorConfig* textConfig = Z::gEngine->GetConfigCog()->has(TextEditorConfig); textConfig->ColorScheme = mActiveName; SaveConfig(); } void ColorScheme::Modified() { ObjectEvent e(this); this->DispatchEvent(Events::ColorSchemeChanged, &e); } void ColorScheme::Save() { if (mSaveName.Empty()) { DoNotifyWarning("Invalid Name", "Please set a name for the color scheme"); return; } if (mFilePath.Empty()) mFilePath = FilePath::Combine(GetUserDocumentsDirectory(), "ZeroEditor", "ColorSchemes"); CreateDirectoryAndParents(mFilePath); String filename = BuildString(mSaveName, ".data"); String fullPath = FilePath::Combine(mFilePath, filename); SaveToDataFile(*this, fullPath, DataFileFormat::Text); UpdateConfig(); // After saving a color scheme we need enumerate and add the new user color // schemes String userSchemeDirectory = FilePath::Combine(GetUserDocumentsDirectory(), "ZeroEditor", "ColorSchemes"); Enumerate(userSchemeDirectory); // Set our active scheme to the new saved scheme SetActiveScheme(mSaveName); } void ColorScheme::Load(StringParam name) { if (mActiveName == name) return; String path = mAvailableSchemes.FindValue(name, String()); if (!path.Empty()) { mFilePath = FilePath::GetDirectoryPath(path); mActiveName = FilePath::GetFileNameWithoutExtension(path); LoadFromDataFile(*this, path); } } ColorScheme* GetColorScheme() { ColorScheme* colorScheme = ColorScheme::GetInstance(); if (colorScheme->mAvailableSchemes.Empty()) colorScheme->LoadSchemes(); return colorScheme; } void ColorScheme::LoadSchemes() { // Load schemes in data directory and user directory Cog* configCog = Z::gEngine->GetConfigCog(); MainConfig* mainConfig = configCog->has(MainConfig); TextEditorConfig* textConfig = configCog->has(TextEditorConfig); String userColorSchemeDirectory = FilePath::Combine(GetUserDocumentsDirectory(), "ZeroEditor", "ColorSchemes"); Enumerate(userColorSchemeDirectory); // Default color schemes are loaded second to overwrite user schemes using the // same name String defaultColorSchemeDirectory = FilePath::Combine(mainConfig->DataDirectory, "ColorSchemes"); Enumerate(defaultColorSchemeDirectory); Load(textConfig->ColorScheme); } void ColorScheme::Enumerate(StringParam directoryPath) { // Add color scheme files in directory FileRange filesInDirectory(directoryPath); for (; !filesInDirectory.Empty(); filesInDirectory.PopFront()) { String filename = FilePath::Combine(directoryPath, filesInDirectory.Front()); String name = FilePath::GetFileNameWithoutExtension(filename); mAvailableSchemes.SortedInsertOrOverride(name, filename); } } } // namespace Zero
32.152672
117
0.757597
RyanTylerRae
e915d58ddc52be378b67ad716cf8dfdf39d03f45
641
cpp
C++
lab_01/month.cpp
srafi1/csci13600-labs-1
60081dced2c237f6843b28f335db9a4ed56a8ac2
[ "BSD-3-Clause" ]
null
null
null
lab_01/month.cpp
srafi1/csci13600-labs-1
60081dced2c237f6843b28f335db9a4ed56a8ac2
[ "BSD-3-Clause" ]
2
2018-11-15T17:15:08.000Z
2018-11-20T18:14:33.000Z
lab_01/month.cpp
srafi1/csci13600-labs-1
60081dced2c237f6843b28f335db9a4ed56a8ac2
[ "BSD-3-Clause" ]
4
2018-11-08T15:05:15.000Z
2018-12-14T04:08:49.000Z
#include <iostream> [[noreturn]] void myexit(unsigned int val) { std::cout << val; std::cout << " days"; std::cout << std::endl; exit(0); } int main() { std::cout << "Enter year: "; int year; std::cin >> year; std::cout << "Enter month: "; int month; std::cin >> month; std::cout << std::endl; if (month == 2) { if (year % 4 != 0) { myexit(28); } if (year % 100 != 0) { myexit(29); } if (year % 400 != 0) { myexit(28); } myexit(29); } if (month < 8) { myexit(month % 2 == 0 ? 30 : 31); } else { myexit(month % 2 == 0 ? 31 : 30); } return 0; }
14.244444
44
0.464899
srafi1
e918c2ab70f3b76deb17239e7b39c7c72a5553ae
51,260
cc
C++
talk/owt/sdk/p2p/p2ppeerconnectionchannel.cc
JamesTerm/owt-client-native
91eff5607438690c88e01b718c1fd5441e89e1f7
[ "Apache-2.0" ]
1
2021-01-26T07:57:43.000Z
2021-01-26T07:57:43.000Z
talk/owt/sdk/p2p/p2ppeerconnectionchannel.cc
JamesTerm/owt-client-native
91eff5607438690c88e01b718c1fd5441e89e1f7
[ "Apache-2.0" ]
null
null
null
talk/owt/sdk/p2p/p2ppeerconnectionchannel.cc
JamesTerm/owt-client-native
91eff5607438690c88e01b718c1fd5441e89e1f7
[ "Apache-2.0" ]
null
null
null
// Copyright (C) <2018> Intel Corporation // // SPDX-License-Identifier: Apache-2.0 #include <thread> #include <vector> #include "talk/owt/sdk/base/eventtrigger.h" #include "talk/owt/sdk/base/functionalobserver.h" #include "talk/owt/sdk/base/sdputils.h" #include "talk/owt/sdk/base/sysinfo.h" #include "talk/owt/sdk/p2p/p2ppeerconnectionchannel.h" #include "webrtc/rtc_base/logging.h" #include "webrtc/api/task_queue/default_task_queue_factory.h" using namespace rtc; namespace owt { namespace p2p { using std::string; enum P2PPeerConnectionChannel::SessionState : int { kSessionStateReady = 1, // Indicate the channel is ready. This is the initial state. kSessionStateOffered, // Indicates local client has sent a user agent and // waiting for an remote SDP. kSessionStatePending, // Indicates local client received an user agent and // waiting for user's response. kSessionStateMatched, // Indicates both sides agreed to start a WebRTC // session. One of them will send an offer soon. kSessionStateConnecting, // Indicates both sides are trying to connect to the // other side. kSessionStateConnected, // Indicates PeerConnection has been established. }; // Signaling message type const string kMessageTypeKey = "type"; const string kMessageDataKey = "data"; const string kChatClosed = "chat-closed"; const string kChatSignal = "chat-signal"; const string kChatTrackSources = "chat-track-sources"; const string kChatStreamInfo = "chat-stream-info"; const string kChatTracksAdded = "chat-tracks-added"; const string kChatTracksRemoved = "chat-tracks-removed"; const string kChatDataReceived = "chat-data-received"; const string kChatUserAgent = "chat-ua"; // Track information member key const string kTrackIdKey = "id"; const string kTrackSourceKey = "source"; // Stream information member key const string kStreamIdKey = "id"; const string kStreamTracksKey = "tracks"; const string kStreamAudioSourceKey = "audio"; const string kStreamVideoSourceKey = "video"; const string kStreamSourceKey = "source"; // Session description member key const string kSessionDescriptionTypeKey = "type"; const string kSessionDescriptionSdpKey = "sdp"; // ICE candidate member key const string kIceCandidateSdpNameKey = "candidate"; const string kIceCandidateSdpMidKey = "sdpMid"; const string kIceCandidateSdpMLineIndexKey = "sdpMLineIndex"; // UA member keys // SDK section const string kUaSdkKey = "sdk"; const string kUaSdkTypeKey = "type"; const string kUaSdkVersionKey = "version"; // Runtime section const string kUaRuntimeKey = "runtime"; const string kUaRuntimeNameKey = "name"; const string kUaRuntimeVersionKey = "version"; // OS section const string kUaOsKey = "os"; const string kUaOsNameKey = "name"; const string kUaOsVersionKey = "version"; // Capabilities section const string kUaCapabilitiesKey = "capabilities"; const string kUaContinualGatheringKey = "continualIceGathering"; const string kUaUnifiedPlanKey = "unifiedPlan"; const string kUaStreamRemovableKey = "streamRemovable"; const string kUaIgnoresDataChannelAcksKey = "ignoreDataChannelAcks"; // Text message sent through data channel const string kDataChannelLabelForTextMessage = "message"; const string kTextMessageDataKey = "data"; const string kTextMessageIdKey = "id"; P2PPeerConnectionChannel::P2PPeerConnectionChannel( PeerConnectionChannelConfiguration configuration, const std::string& local_id, const std::string& remote_id, P2PSignalingSenderInterface* sender, std::shared_ptr<rtc::TaskQueue> event_queue) : PeerConnectionChannel(configuration), signaling_sender_(sender), local_id_(local_id), remote_id_(remote_id), session_state_(kSessionStateReady), negotiation_needed_(false), pending_remote_sdp_(nullptr), last_disconnect_( std::chrono::time_point<std::chrono::system_clock>::max()), reconnect_timeout_(10), message_seq_num_(0), remote_side_supports_plan_b_(false), remote_side_supports_remove_stream_(false), remote_side_supports_unified_plan_(true), is_creating_offer_(false), remote_side_supports_continual_ice_gathering_(true), remote_side_ignores_datachannel_acks_(false), ua_sent_(false), stop_send_needed_(true), remote_side_offline_(false), ended_(false) { RTC_CHECK(signaling_sender_); InitializePeerConnection(); if (event_queue) { event_queue_ = event_queue; } else { auto task_queue_factory_ = webrtc::CreateDefaultTaskQueueFactory(); event_queue_ = std::make_unique<rtc::TaskQueue>(task_queue_factory_->CreateTaskQueue( "P2PClientEventQueue", webrtc::TaskQueueFactory::Priority::NORMAL)); } } P2PPeerConnectionChannel::P2PPeerConnectionChannel( PeerConnectionChannelConfiguration configuration, const std::string& local_id, const std::string& remote_id, P2PSignalingSenderInterface* sender) : P2PPeerConnectionChannel(configuration, local_id, remote_id, sender, nullptr) {} P2PPeerConnectionChannel::~P2PPeerConnectionChannel() { if (signaling_sender_) delete signaling_sender_; ended_ = true; ClosePeerConnection(); } void P2PPeerConnectionChannel::Publish( std::shared_ptr<LocalStream> stream, std::function<void()> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { RTC_LOG(LS_INFO) << "Publishing a local stream."; if (!CheckNullPointer((uintptr_t)stream.get(), on_failure)) { RTC_LOG(LS_INFO) << "Local stream cannot be nullptr."; return; } RTC_CHECK(stream->MediaStream()); std::string stream_label = stream->MediaStream()->id(); if (published_streams_.find(stream_label) != published_streams_.end() || publishing_streams_.find(stream_label) != publishing_streams_.end()) { if (on_failure) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "The stream is already published.")); on_failure(std::move(e)); }); } return; } latest_local_stream_ = stream; latest_publish_success_callback_ = on_success; latest_publish_failure_callback_ = on_failure; // Send chat-closed to workaround known browser bugs, together with // user agent information once and once only. if (stop_send_needed_) { SendStop(nullptr, nullptr); stop_send_needed_ = false; } if (!ua_sent_) { SendUaInfo(); ua_sent_ = true; } scoped_refptr<webrtc::MediaStreamInterface> media_stream = stream->MediaStream(); std::pair<std::string, std::string> stream_track_info; for (const auto& track : media_stream->GetAudioTracks()) { std::lock_guard<std::mutex> lock(local_stream_tracks_info_mutex_); if (local_stream_tracks_info_.find(track->id()) == local_stream_tracks_info_.end()) { stream_track_info = std::make_pair(track->id(), media_stream->id()); local_stream_tracks_info_.insert(stream_track_info); } } for (const auto& track : media_stream->GetVideoTracks()) { std::lock_guard<std::mutex> lock(local_stream_tracks_info_mutex_); if (local_stream_tracks_info_.find(track->id()) == local_stream_tracks_info_.end()) { stream_track_info = std::make_pair(track->id(), media_stream->id()); local_stream_tracks_info_.insert(stream_track_info); } } { std::lock_guard<std::mutex> lock(pending_publish_streams_mutex_); pending_publish_streams_.push_back(stream); } { std::lock_guard<std::mutex> lock(published_streams_mutex_); publishing_streams_.insert(stream_label); } RTC_LOG(LS_INFO) << "Session state: " << session_state_; if (on_success) { // TODO: Here to directly call on_success on publication // publish_success_callbacks_[stream_label] = on_success; event_queue_->PostTask([on_success] { on_success(); }); } if (on_failure) { std::lock_guard<std::mutex> lock(failure_callbacks_mutex_); failure_callbacks_[stream_label] = on_failure; } if (SignalingState() == PeerConnectionInterface::SignalingState::kStable) DrainPendingStreams(); } void P2PPeerConnectionChannel::Send( const std::string& message, std::function<void()> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { // Send chat-closed to workaround known browser bugs, together with // user agent information once and once only. if (stop_send_needed_) { SendStop(nullptr, nullptr); stop_send_needed_ = false; } if (!ua_sent_) { SendUaInfo(); ua_sent_ = true; } // Try to send the text message. Json::Value content; if (message_seq_num_ == INT_MAX) { message_seq_num_ = 0; } int message_id = message_seq_num_++; content[kTextMessageIdKey] = std::to_string(message_id); content[kTextMessageDataKey] = message; std::string data = rtc::JsonValueToString(content); if (data_channel_ != nullptr && data_channel_->state() == webrtc::DataChannelInterface::DataState::kOpen) { data_channel_->Send(CreateDataBuffer(data)); if (on_success) { on_success(); } } else { { std::lock_guard<std::mutex> lock(pending_messages_mutex_); std::shared_ptr<std::string> data_copy( std::make_shared<std::string>(data)); pending_messages_.push_back(std::tuple<std::shared_ptr<std::string>, std::function<void()>, std::function<void(std::unique_ptr<Exception>)>>{data_copy, on_success, on_failure}); } if (data_channel_ == nullptr) // Otherwise, wait for data channel ready. CreateDataChannel(kDataChannelLabelForTextMessage); } } void P2PPeerConnectionChannel::ChangeSessionState(SessionState state) { RTC_LOG(LS_INFO) << "PeerConnectionChannel change session state : " << state; session_state_ = state; } void P2PPeerConnectionChannel::AddObserver( P2PPeerConnectionChannelObserver* observer) { observers_.push_back(observer); } void P2PPeerConnectionChannel::RemoveObserver( P2PPeerConnectionChannelObserver* observer) { observers_.erase(std::remove(observers_.begin(), observers_.end(), observer), observers_.end()); } void P2PPeerConnectionChannel::CreateOffer() { { std::lock_guard<std::mutex> lock(is_creating_offer_mutex_); if (is_creating_offer_) { // Store creating offer request. negotiation_needed_ = true; return; } else { is_creating_offer_ = true; } } RTC_LOG(LS_INFO) << "Create offer."; negotiation_needed_ = false; scoped_refptr<FunctionalCreateSessionDescriptionObserver> observer = FunctionalCreateSessionDescriptionObserver::Create( std::bind( &P2PPeerConnectionChannel::OnCreateSessionDescriptionSuccess, this, std::placeholders::_1), std::bind( &P2PPeerConnectionChannel::OnCreateSessionDescriptionFailure, this, std::placeholders::_1)); peer_connection_->CreateOffer( observer, webrtc::PeerConnectionInterface::RTCOfferAnswerOptions()); } void P2PPeerConnectionChannel::CreateAnswer() { RTC_LOG(LS_INFO) << "Create answer."; scoped_refptr<FunctionalCreateSessionDescriptionObserver> observer = FunctionalCreateSessionDescriptionObserver::Create( std::bind( &P2PPeerConnectionChannel::OnCreateSessionDescriptionSuccess, this, std::placeholders::_1), std::bind( &P2PPeerConnectionChannel::OnCreateSessionDescriptionFailure, this, std::placeholders::_1)); peer_connection_->CreateAnswer( observer, webrtc::PeerConnectionInterface::RTCOfferAnswerOptions()); } void P2PPeerConnectionChannel::SendSignalingMessage( const Json::Value& data, std::function<void()> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { RTC_CHECK(signaling_sender_); std::string json_string = rtc::JsonValueToString(data); signaling_sender_->SendSignalingMessage( json_string, remote_id_, on_success, [=](std::unique_ptr<Exception> exception) { if (exception->Type() == ExceptionType::kP2PMessageTargetUnreachable) { remote_side_offline_ = true; ExceptionType type = exception->Type(); std::string msg = exception->Message(); std::lock_guard<std::mutex> lock(failure_callbacks_mutex_); for (std::unordered_map< std::string, std::function<void(std::unique_ptr<Exception>)>>::iterator it = failure_callbacks_.begin(); it != failure_callbacks_.end(); it++) { std::function<void(std::unique_ptr<Exception>)> failure_callback = it->second; event_queue_->PostTask([failure_callback, type, msg] { std::unique_ptr<Exception> e(new Exception(type, msg)); failure_callback(std::move(e)); }); } failure_callbacks_.clear(); } if (on_failure) on_failure(std::move(exception)); }); } void P2PPeerConnectionChannel::OnIncomingSignalingMessage( const std::string& message) { if (ended_) return; RTC_LOG(LS_INFO) << "OnIncomingMessage: " << message; RTC_DCHECK(!message.empty()); Json::Reader reader; Json::Value json_message; if (!reader.parse(message, json_message)) { RTC_LOG(LS_WARNING) << "Cannot parse incoming message."; return; } std::string message_type; rtc::GetStringFromJsonObject(json_message, kMessageTypeKey, &message_type); if (message_type.empty()) { RTC_LOG(LS_WARNING) << "Cannot get type from incoming message."; return; } if (message_type == kChatUserAgent) { // Send back user agent info once and only once. if (!ua_sent_) { SendUaInfo(); ua_sent_ = true; stop_send_needed_ = false; } Json::Value ua; rtc::GetValueFromJsonObject(json_message, kMessageDataKey, &ua); OnMessageUserAgent(ua); } else if (message_type == kChatTrackSources) { Json::Value track_sources; rtc::GetValueFromJsonObject(json_message, kMessageDataKey, &track_sources); OnMessageTrackSources(track_sources); } else if (message_type == kChatStreamInfo) { Json::Value stream_info; rtc::GetValueFromJsonObject(json_message, kMessageDataKey, &stream_info); OnMessageStreamInfo(stream_info); } else if (message_type == kChatSignal) { Json::Value signal; rtc::GetValueFromJsonObject(json_message, kMessageDataKey, &signal); OnMessageSignal(signal); } else if (message_type == kChatTracksAdded) { Json::Value tracks; rtc::GetValueFromJsonObject(json_message, kMessageDataKey, &tracks); OnMessageTracksAdded(tracks); } else if (message_type == kChatClosed) { OnMessageStop(); } else { RTC_LOG(LS_WARNING) << "Received unknown message type : " << message_type; return; } } void P2PPeerConnectionChannel::OnMessageUserAgent(Json::Value& ua) { HandleRemoteCapability(ua); switch (session_state_) { case kSessionStateReady: case kSessionStatePending: ChangeSessionState(kSessionStateMatched); break; default: RTC_LOG(LS_INFO) << "Ignore user agent information because already connected."; } } void P2PPeerConnectionChannel::OnMessageStop() { RTC_LOG(LS_INFO) << "Remote user stopped."; { { std::lock_guard<std::mutex> lock(failure_callbacks_mutex_); for (std::unordered_map< std::string, std::function<void(std::unique_ptr<Exception>)>>::iterator it = failure_callbacks_.begin(); it != failure_callbacks_.end(); it++) { std::function<void(std::unique_ptr<Exception>)> failure_callback = it->second; event_queue_->PostTask([failure_callback] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "Stop message received.")); failure_callback(std::move(e)); }); } failure_callbacks_.clear(); } } { std::lock_guard<std::mutex> lock(pending_messages_mutex_); for (auto it = pending_messages_.begin(); it != pending_messages_.end(); ++it) { std::function<void(std::unique_ptr<Exception>)> on_failure; std::tie(std::ignore, std::ignore, on_failure) = *it; if (on_failure) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "Stop message received.")); on_failure(std::move(e)); }); } } pending_messages_.clear(); } ClosePeerConnection(); ChangeSessionState(kSessionStateReady); TriggerOnStopped(); } void P2PPeerConnectionChannel::OnMessageSignal(Json::Value& message) { RTC_LOG(LS_INFO) << "OnMessageSignal"; string type; string desc; rtc::GetStringFromJsonObject(message, kSessionDescriptionTypeKey, &type); RTC_LOG(LS_INFO) << "Received message type: " << type; if (type == "offer" || type == "answer") { if (type == "offer" && session_state_ == kSessionStateMatched) { ChangeSessionState(kSessionStateConnecting); } string sdp; if (!rtc::GetStringFromJsonObject(message, kSessionDescriptionSdpKey, &sdp)) { RTC_LOG(LS_WARNING) << "Cannot parse received sdp."; return; } std::unique_ptr<webrtc::SessionDescriptionInterface> desc( webrtc::CreateSessionDescription(type, sdp, nullptr)); if (!desc) { RTC_LOG(LS_ERROR) << "Failed to create session description."; return; } if (type == "offer" && SignalingState() != webrtc::PeerConnectionInterface::kStable) { RTC_LOG(LS_INFO) << "Signaling state is " << SignalingState() << ", set SDP later."; pending_remote_sdp_ = std::move(desc); } else { scoped_refptr<FunctionalSetRemoteDescriptionObserver> observer = FunctionalSetRemoteDescriptionObserver::Create(std::bind( &P2PPeerConnectionChannel::OnSetRemoteDescriptionComplete, this, std::placeholders::_1)); std::string sdp_string; if (!desc->ToString(&sdp_string)) { RTC_LOG(LS_ERROR) << "Error parsing local description."; RTC_DCHECK(false); } std::vector<AudioCodec> audio_codecs; for (auto& audio_enc_param : configuration_.audio) { audio_codecs.push_back(audio_enc_param.codec.name); } sdp_string = SdpUtils::SetPreferAudioCodecs(sdp_string, audio_codecs); std::vector<VideoCodec> video_codecs; for (auto& video_enc_param : configuration_.video) { video_codecs.push_back(video_enc_param.codec.name); } sdp_string = SdpUtils::SetPreferVideoCodecs(sdp_string, video_codecs); std::unique_ptr<webrtc::SessionDescriptionInterface> new_desc( webrtc::CreateSessionDescription(desc->type(), sdp_string, nullptr)); // Sychronous call. After done, will invoke OnSetRemoteDescription. If // remote sent an offer, we create answer for it. RTC_LOG(LS_WARNING) << "SetRemoteSdp:" << sdp_string; peer_connection_->SetRemoteDescription(std::move(new_desc), observer); pending_remote_sdp_.reset(); } } else if (type == "candidates") { string sdp_mid; string candidate; int sdp_mline_index; rtc::GetStringFromJsonObject(message, kIceCandidateSdpMidKey, &sdp_mid); rtc::GetStringFromJsonObject(message, kIceCandidateSdpNameKey, &candidate); rtc::GetIntFromJsonObject(message, kIceCandidateSdpMLineIndexKey, &sdp_mline_index); webrtc::IceCandidateInterface* ice_candidate = webrtc::CreateIceCandidate( sdp_mid, sdp_mline_index, candidate, nullptr); peer_connection_->AddIceCandidate(ice_candidate); } } void P2PPeerConnectionChannel::OnMessageTracksAdded( Json::Value& stream_tracks) { // Find the streams with track information, and add them to published stream // list. for (Json::Value::ArrayIndex idx = 0; idx != stream_tracks.size(); idx++) { std::string track_id = stream_tracks[idx].asString(); std::lock_guard<std::mutex> lock(local_stream_tracks_info_mutex_); if (local_stream_tracks_info_.find(track_id) != local_stream_tracks_info_.end()) { std::string stream_label = local_stream_tracks_info_[track_id]; { std::lock_guard<std::mutex> lock(published_streams_mutex_); auto it = published_streams_.find(stream_label); if (it == published_streams_.end()) published_streams_.insert(stream_label); auto it_publishing = publishing_streams_.find(stream_label); if (it_publishing != publishing_streams_.end()) publishing_streams_.erase(it_publishing); } // Trigger the successful callback of publish. if (publish_success_callbacks_.find(stream_label) == publish_success_callbacks_.end()) { RTC_LOG(LS_WARNING) << "No callback available for publishing stream with track id: " << track_id; return; } std::function<void()> callback = publish_success_callbacks_[stream_label]; event_queue_->PostTask([callback] { callback(); }); publish_success_callbacks_.erase(stream_label); // Remove the failure callback accordingly std::lock_guard<std::mutex> lock(failure_callbacks_mutex_); if (failure_callbacks_.find(stream_label) != failure_callbacks_.end()) failure_callbacks_.erase(stream_label); } } } void P2PPeerConnectionChannel::OnMessageTrackSources( Json::Value& track_sources) { string id; string source; for (Json::Value::ArrayIndex idx = 0; idx != track_sources.size(); idx++) { rtc::GetStringFromJsonObject(track_sources[idx], kTrackIdKey, &id); rtc::GetStringFromJsonObject(track_sources[idx], kTrackSourceKey, &source); // Track source information collect. std::pair<std::string, std::string> track_source_info; track_source_info = std::make_pair(id, source); rtc::CritScope cs(&remote_track_source_info_crit_); remote_track_source_info_.insert(track_source_info); } } void P2PPeerConnectionChannel::OnMessageStreamInfo(Json::Value& stream_info) { // Stream information is useless in native layer. } void P2PPeerConnectionChannel::OnSignalingChange( PeerConnectionInterface::SignalingState new_state) { RTC_LOG(LS_INFO) << "Signaling state changed: " << new_state; switch (new_state) { case PeerConnectionInterface::SignalingState::kStable: if (pending_remote_sdp_) { scoped_refptr<FunctionalSetRemoteDescriptionObserver> observer = FunctionalSetRemoteDescriptionObserver::Create(std::bind( &P2PPeerConnectionChannel::OnSetRemoteDescriptionComplete, this, std::placeholders::_1)); std::string sdp_string; if (!pending_remote_sdp_->ToString(&sdp_string)) { RTC_LOG(LS_ERROR) << "Error parsing local description."; RTC_DCHECK(false); } std::vector<AudioCodec> audio_codecs; for (auto& audio_enc_param : configuration_.audio) { audio_codecs.push_back(audio_enc_param.codec.name); } sdp_string = SdpUtils::SetPreferAudioCodecs(sdp_string, audio_codecs); std::vector<VideoCodec> video_codecs; for (auto& video_enc_param : configuration_.video) { video_codecs.push_back(video_enc_param.codec.name); } sdp_string = SdpUtils::SetPreferVideoCodecs(sdp_string, video_codecs); std::unique_ptr<webrtc::SessionDescriptionInterface> new_desc( webrtc::CreateSessionDescription(pending_remote_sdp_->type(), sdp_string, nullptr)); pending_remote_sdp_.reset(); peer_connection_->SetRemoteDescription(std::move(new_desc), observer); } else { CheckWaitedList(); } break; default: break; } } void P2PPeerConnectionChannel::OnAddStream( rtc::scoped_refptr<MediaStreamInterface> stream) { Json::Value stream_tracks; { rtc::CritScope cs(&remote_track_source_info_crit_); for (const auto& track : stream->GetAudioTracks()) { stream_tracks.append(track->id()); } for (const auto& track : stream->GetVideoTracks()) { stream_tracks.append(track->id()); } } std::shared_ptr<RemoteStream> remote_stream( new RemoteStream(stream, remote_id_)); EventTrigger::OnEvent1<P2PPeerConnectionChannelObserver*, std::allocator<P2PPeerConnectionChannelObserver*>, void (owt::p2p::P2PPeerConnectionChannelObserver::*)( std::shared_ptr<RemoteStream>), std::shared_ptr<RemoteStream>>( observers_, event_queue_, &P2PPeerConnectionChannelObserver::OnStreamAdded, remote_stream); remote_streams_[stream->id()] = remote_stream; // Send the ack for the newly added stream tracks. Json::Value json_tracks; json_tracks[kMessageTypeKey] = kChatTracksAdded; json_tracks[kMessageDataKey] = stream_tracks; SendSignalingMessage(json_tracks); } void P2PPeerConnectionChannel::OnRemoveStream( rtc::scoped_refptr<MediaStreamInterface> stream) { if (remote_streams_.find(stream->id()) == remote_streams_.end()) { RTC_LOG(LS_WARNING) << "Remove an invalid stream."; RTC_DCHECK(false); return; } std::shared_ptr<RemoteStream> remote_stream = remote_streams_[stream->id()]; remote_stream->TriggerOnStreamEnded(); remote_streams_.erase(stream->id()); rtc::CritScope cs(&remote_track_source_info_crit_); for (const auto& track : stream->GetAudioTracks()) remote_track_source_info_.erase(track->id()); for (const auto& track : stream->GetVideoTracks()) remote_track_source_info_.erase(track->id()); } void P2PPeerConnectionChannel::OnDataChannel( rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) { // If a new data channel is create, delete the old one to save resource. // Currently only one data channel for one connection. If we are going to // support multiple data channels(one for text, one for large files), replace // |data_channel_| with a map. if (data_channel_) data_channel_ = nullptr; data_channel_ = data_channel; data_channel_->RegisterObserver(this); DrainPendingMessages(); } void P2PPeerConnectionChannel::OnNegotiationNeeded() { if (ended_) return; RTC_LOG(LS_INFO) << "On negotiation needed."; if (SignalingState() == PeerConnectionInterface::SignalingState::kStable) { CreateOffer(); } else { negotiation_needed_ = true; } } void P2PPeerConnectionChannel::OnIceConnectionChange( PeerConnectionInterface::IceConnectionState new_state) { RTC_LOG(LS_INFO) << "Ice connection state changed: " << new_state; switch (new_state) { case webrtc::PeerConnectionInterface::kIceConnectionConnected: case webrtc::PeerConnectionInterface::kIceConnectionCompleted: ChangeSessionState(kSessionStateConnected); CheckWaitedList(); // reset |last_disconnect_|. last_disconnect_ = std::chrono::time_point<std::chrono::system_clock>::max(); break; case webrtc::PeerConnectionInterface::kIceConnectionDisconnected: last_disconnect_ = std::chrono::system_clock::now(); // Check state after a period of time. std::thread([this]() { std::this_thread::sleep_for(std::chrono::seconds(reconnect_timeout_)); if (std::chrono::system_clock::now() - last_disconnect_ >= std::chrono::seconds(reconnect_timeout_)) { RTC_LOG(LS_INFO) << "Detect reconnection failed, stop this session."; Stop(nullptr, nullptr); } else { RTC_LOG(LS_INFO) << "Detect reconnection succeed."; } }).detach(); break; case webrtc::PeerConnectionInterface::kIceConnectionClosed: TriggerOnStopped(); CleanLastPeerConnection(); break; case webrtc::PeerConnectionInterface::kIceConnectionFailed: for (std::unordered_map<std::string, std::shared_ptr<RemoteStream>>::iterator it = remote_streams_.begin(); it != remote_streams_.end(); it++) it->second->TriggerOnStreamEnded(); remote_streams_.clear(); { rtc::CritScope cs(&remote_track_source_info_crit_); remote_track_source_info_.clear(); } break; default: break; } } void P2PPeerConnectionChannel::OnIceGatheringChange( PeerConnectionInterface::IceGatheringState new_state) { RTC_LOG(LS_INFO) << "Ice gathering state changed: " << new_state; } void P2PPeerConnectionChannel::OnIceCandidate( const webrtc::IceCandidateInterface* candidate) { RTC_LOG(LS_INFO) << "On ice candidate"; Json::Value signal; signal[kSessionDescriptionTypeKey] = "candidates"; signal[kIceCandidateSdpMLineIndexKey] = candidate->sdp_mline_index(); signal[kIceCandidateSdpMidKey] = candidate->sdp_mid(); string sdp; if (!candidate->ToString(&sdp)) { RTC_LOG(LS_ERROR) << "Failed to serialize candidate"; return; } signal[kIceCandidateSdpNameKey] = sdp; Json::Value json; json[kMessageTypeKey] = kChatSignal; json[kMessageDataKey] = signal; SendSignalingMessage(json); } void P2PPeerConnectionChannel::OnCreateSessionDescriptionSuccess( webrtc::SessionDescriptionInterface* desc) { RTC_LOG(LS_INFO) << "Create sdp success."; scoped_refptr<FunctionalSetSessionDescriptionObserver> observer = FunctionalSetSessionDescriptionObserver::Create( std::bind( &P2PPeerConnectionChannel::OnSetLocalSessionDescriptionSuccess, this), std::bind( &P2PPeerConnectionChannel::OnSetLocalSessionDescriptionFailure, this, std::placeholders::_1)); peer_connection_->SetLocalDescription(observer, desc); } void P2PPeerConnectionChannel::OnCreateSessionDescriptionFailure( const std::string& error) { RTC_LOG(LS_INFO) << "Create sdp failed."; { std::lock_guard<std::mutex> lock(failure_callbacks_mutex_); for (std::unordered_map< std::string, std::function<void(std::unique_ptr<Exception>)>>::iterator it = failure_callbacks_.begin(); it != failure_callbacks_.end(); it++) { std::function<void(std::unique_ptr<Exception>)> failure_callback = it->second; event_queue_->PostTask([failure_callback] { std::unique_ptr<Exception> e(new Exception( ExceptionType::kP2PClientInvalidArgument, "Failed to create SDP.")); failure_callback(std::move(e)); }); } failure_callbacks_.clear(); } Stop(nullptr, nullptr); } void P2PPeerConnectionChannel::OnSetLocalSessionDescriptionSuccess() { RTC_LOG(LS_INFO) << "Set local sdp success."; { std::lock_guard<std::mutex> lock(is_creating_offer_mutex_); if (is_creating_offer_) { is_creating_offer_ = false; } } // Setting maximum bandwidth here. ApplyBitrateSettings(); auto desc = LocalDescription(); string sdp; desc->ToString(&sdp); Json::Value signal; signal[kSessionDescriptionTypeKey] = desc->type(); signal[kSessionDescriptionSdpKey] = sdp; Json::Value json; json[kMessageTypeKey] = kChatSignal; json[kMessageDataKey] = signal; // The fourth signaling message of SDP to remote peer. SendSignalingMessage(json); } void P2PPeerConnectionChannel::OnSetLocalSessionDescriptionFailure( const std::string& error) { RTC_LOG(LS_INFO) << "Set local sdp failed."; { std::lock_guard<std::mutex> lock(failure_callbacks_mutex_); for (std::unordered_map< std::string, std::function<void(std::unique_ptr<Exception>)>>::iterator it = failure_callbacks_.begin(); it != failure_callbacks_.end(); it++) { std::function<void(std::unique_ptr<Exception>)> failure_callback = it->second; event_queue_->PostTask([failure_callback] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "Failed to set local SDP.")); failure_callback(std::move(e)); }); } failure_callbacks_.clear(); } Stop(nullptr, nullptr); } void P2PPeerConnectionChannel::OnSetRemoteSessionDescriptionSuccess() { PeerConnectionChannel::OnSetRemoteSessionDescriptionSuccess(); } void P2PPeerConnectionChannel::OnSetRemoteSessionDescriptionFailure( const std::string& error) { RTC_LOG(LS_INFO) << "Set remote sdp failed."; { std::lock_guard<std::mutex> lock(failure_callbacks_mutex_); for (std::unordered_map< std::string, std::function<void(std::unique_ptr<Exception>)>>::iterator it = failure_callbacks_.begin(); it != failure_callbacks_.end(); it++) { std::function<void(std::unique_ptr<Exception>)> failure_callback = it->second; event_queue_->PostTask([failure_callback] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "Failed to set remote SDP.")); failure_callback(std::move(e)); }); } failure_callbacks_.clear(); } Stop(nullptr, nullptr); } bool P2PPeerConnectionChannel::CheckNullPointer( uintptr_t pointer, std::function<void(std::unique_ptr<Exception>)> on_failure) { if (pointer) return true; if (on_failure != nullptr) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e(new Exception( ExceptionType::kP2PClientInvalidArgument, "Nullptr is not allowed.")); on_failure(std::move(e)); }); } return false; } void P2PPeerConnectionChannel::TriggerOnStopped() { for (std::vector<P2PPeerConnectionChannelObserver*>::iterator it = observers_.begin(); it != observers_.end(); it++) { (*it)->OnStopped(remote_id_); } } void P2PPeerConnectionChannel::CleanLastPeerConnection() { pending_remote_sdp_.reset(); negotiation_needed_ = false; last_disconnect_ = std::chrono::time_point<std::chrono::system_clock>::max(); } void P2PPeerConnectionChannel::Unpublish( std::shared_ptr<LocalStream> stream, std::function<void()> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { if (!CheckNullPointer((uintptr_t)stream.get(), on_failure)) { RTC_LOG(LS_WARNING) << "Local stream cannot be nullptr."; return; } if (!remote_side_supports_remove_stream_) { if (on_failure != nullptr) { RTC_LOG(LS_WARNING) << "Remote side does not support removeStream."; event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientUnsupportedMethod, "Remote side does not support unpublish.")); on_failure(std::move(e)); }); } return; } RTC_CHECK(stream->MediaStream()); { std::lock_guard<std::mutex> lock(published_streams_mutex_); auto it = published_streams_.find(stream->MediaStream()->id()); if (it == published_streams_.end()) { if (on_failure) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "The stream is not published.")); on_failure(std::move(e)); }); } return; } published_streams_.erase(it); } { std::lock_guard<std::mutex> lock(pending_unpublish_streams_mutex_); pending_unpublish_streams_.push_back(stream); } if (on_success) { event_queue_->PostTask([on_success] { on_success(); }); } if (SignalingState() == PeerConnectionInterface::SignalingState::kStable) DrainPendingStreams(); } void P2PPeerConnectionChannel::Stop( std::function<void()> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { RTC_LOG(LS_INFO) << "Stop session."; switch (session_state_) { case kSessionStateConnecting: case kSessionStateConnected: ClosePeerConnection(); SendStop(nullptr, nullptr); stop_send_needed_ = false; ChangeSessionState(kSessionStateReady); break; case kSessionStateMatched: SendStop(nullptr, nullptr); stop_send_needed_ = false; ChangeSessionState(kSessionStateReady); break; case kSessionStateOffered: SendStop(nullptr, nullptr); stop_send_needed_ = false; ChangeSessionState(kSessionStateReady); TriggerOnStopped(); break; default: if (on_failure != nullptr) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidState, "Cannot stop a session haven't started.")); on_failure(std::move(e)); }); } return; } if (on_success != nullptr) { event_queue_->PostTask([on_success] { on_success(); }); } } void P2PPeerConnectionChannel::GetConnectionStats( std::function<void(std::shared_ptr<ConnectionStats>)> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { if (on_success == nullptr) { if (on_failure != nullptr) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "on_success cannot be nullptr. Please provide " "on_success to get connection stats data.")); on_failure(std::move(e)); }); } return; } rtc::scoped_refptr<FunctionalStatsObserver> observer = FunctionalStatsObserver::Create(std::move(on_success)); peer_connection_->GetStats( observer, nullptr, webrtc::PeerConnectionInterface::kStatsOutputLevelStandard); } void P2PPeerConnectionChannel::GetConnectionStats( std::function<void(std::shared_ptr<RTCStatsReport>)> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { if (on_success == nullptr) { if (on_failure != nullptr) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "on_success cannot be nullptr. Please provide " "on_success to get connection stats data.")); on_failure(std::move(e)); }); } return; } rtc::scoped_refptr<FunctionalStandardRTCStatsCollectorCallback> observer = FunctionalStandardRTCStatsCollectorCallback::Create( std::move(on_success)); peer_connection_->GetStats(observer); } void P2PPeerConnectionChannel::GetStats( std::function<void(const webrtc::StatsReports& reports)> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { if (on_success == nullptr) { if (on_failure != nullptr) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidArgument, "on_success cannot be nullptr. Please provide " "on_success to get connection stats data.")); on_failure(std::move(e)); }); } return; } if (session_state_ != kSessionStateConnected) { if (on_failure != nullptr) { event_queue_->PostTask([on_failure] { std::unique_ptr<Exception> e( new Exception(ExceptionType::kP2PClientInvalidState, "Cannot get connection stats in this state. Please " "try it after connection is established.")); on_failure(std::move(e)); }); } return; } RTC_LOG(LS_INFO) << "Get native stats"; rtc::scoped_refptr<FunctionalNativeStatsObserver> observer = FunctionalNativeStatsObserver::Create(std::move(on_success)); peer_connection_->GetStats( observer, nullptr, webrtc::PeerConnectionInterface::kStatsOutputLevelStandard); } bool P2PPeerConnectionChannel::HaveLocalOffer() { return SignalingState() == webrtc::PeerConnectionInterface::kHaveLocalOffer; } std::shared_ptr<LocalStream> P2PPeerConnectionChannel::GetLatestLocalStream() { return latest_local_stream_; } std::function<void()> P2PPeerConnectionChannel::GetLatestPublishSuccessCallback() { return latest_publish_success_callback_; } std::function<void(std::unique_ptr<Exception>)> P2PPeerConnectionChannel::GetLatestPublishFailureCallback() { return latest_publish_failure_callback_; } bool P2PPeerConnectionChannel::IsAbandoned() { return remote_side_offline_; } void P2PPeerConnectionChannel::DrainPendingStreams() { RTC_LOG(LS_INFO) << "Draining pending stream"; ChangeSessionState(kSessionStateConnecting); bool negotiation_needed = false; // First to publish the pending_publish_streams_ list. { std::lock_guard<std::mutex> lock(pending_publish_streams_mutex_); for (auto it = pending_publish_streams_.begin(); it != pending_publish_streams_.end(); ++it) { std::shared_ptr<LocalStream> stream = *it; std::string audio_track_source = "mic"; std::string video_track_source = "camera"; if (stream->Source().audio == owt::base::AudioSourceInfo::kScreenCast) { audio_track_source = "screen-cast"; } if (stream->Source().video == owt::base::VideoSourceInfo::kScreenCast) { video_track_source = "screen-cast"; } // Collect stream and tracks information. scoped_refptr<webrtc::MediaStreamInterface> media_stream = stream->MediaStream(); Json::Value track_info; Json::Value track_sources; Json::Value stream_tracks; Json::Value stream_sources; for (const auto& track : media_stream->GetAudioTracks()) { // Signaling. stream_tracks.append(track->id()); stream_sources[kStreamAudioSourceKey] = audio_track_source; track_info[kTrackIdKey] = track->id(); track_info[kTrackSourceKey] = audio_track_source; track_sources.append(track_info); peer_connection_->AddTrack(track, {media_stream->id()}); } for (const auto& track : media_stream->GetVideoTracks()) { // Signaling. stream_tracks.append(track->id()); stream_sources[kStreamVideoSourceKey] = video_track_source; track_info[kTrackIdKey] = track->id(); track_info[kTrackSourceKey] = video_track_source; track_sources.append(track_info); peer_connection_->AddTrack(track, {media_stream->id()}); } // The second signaling message of track sources to remote peer. Json::Value json_track_sources; json_track_sources[kMessageTypeKey] = kChatTrackSources; json_track_sources[kMessageDataKey] = track_sources; SendSignalingMessage(json_track_sources); // The third signaling message of stream information to remote peer. Json::Value json_stream_info; json_stream_info[kMessageTypeKey] = kChatStreamInfo; Json::Value stream_info; stream_info[kStreamIdKey] = media_stream->id(); stream_info[kStreamTracksKey] = stream_tracks; stream_info[kStreamSourceKey] = stream_sources; json_stream_info[kMessageDataKey] = stream_info; SendSignalingMessage(json_stream_info); negotiation_needed = true; } pending_publish_streams_.clear(); } // Then to unpublish the pending_unpublish_streams_ list. { std::lock_guard<std::mutex> lock(pending_unpublish_streams_mutex_); for (auto it = pending_unpublish_streams_.begin(); it != pending_unpublish_streams_.end(); ++it) { std::shared_ptr<LocalStream> stream = *it; scoped_refptr<webrtc::MediaStreamInterface> media_stream = stream->MediaStream(); RTC_CHECK(peer_connection_); for (const auto& track : media_stream->GetAudioTracks()) { const auto& senders = peer_connection_->GetSenders(); for (auto& s : senders) { const auto& t = s->track(); if (t != nullptr && t->id() == track->id()) { peer_connection_->RemoveTrack(s); break; } } } for (const auto& track : media_stream->GetVideoTracks()) { const auto& senders = peer_connection_->GetSenders(); for (auto& s : senders) { const auto& t = s->track(); if (t != nullptr && t->id() == track->id()) { peer_connection_->RemoveTrack(s); break; } } } negotiation_needed = true; } pending_unpublish_streams_.clear(); } if (negotiation_needed) { OnNegotiationNeeded(); } } void P2PPeerConnectionChannel::SendStop( std::function<void()> on_success, std::function<void(std::unique_ptr<Exception>)> on_failure) { RTC_LOG(LS_INFO) << "Send stop."; Json::Value json; json[kMessageTypeKey] = kChatClosed; SendSignalingMessage(json, on_success, on_failure); } void P2PPeerConnectionChannel::ClosePeerConnection() { RTC_LOG(LS_INFO) << "Close peer connection."; if (peer_connection_) { peer_connection_->Close(); peer_connection_ = nullptr; } } void P2PPeerConnectionChannel::CheckWaitedList() { RTC_LOG(LS_INFO) << "CheckWaitedList"; if (!pending_publish_streams_.empty() || !pending_unpublish_streams_.empty()) { DrainPendingStreams(); } else if (negotiation_needed_) { CreateOffer(); } } void P2PPeerConnectionChannel::OnDataChannelStateChange() { RTC_CHECK(data_channel_); if (data_channel_->state() == webrtc::DataChannelInterface::DataState::kOpen) { DrainPendingMessages(); } } void P2PPeerConnectionChannel::OnDataChannelMessage( const webrtc::DataBuffer& buffer) { if (buffer.binary) { RTC_LOG(LS_WARNING) << "Binary data is not supported."; return; } std::string data = std::string(buffer.data.data<char>(), buffer.data.size()); // Parse the received message with its id and data. Json::Reader reader; Json::Value json_data; if (!reader.parse(data, json_data)) { RTC_LOG(LS_WARNING) << "Cannot parse incoming text message."; return; } std::string message_id; rtc::GetStringFromJsonObject(json_data, kTextMessageIdKey, &message_id); if (message_id.empty()) { RTC_LOG(LS_WARNING) << "Cannot get id from incoming text message."; return; } std::string message; rtc::GetStringFromJsonObject(json_data, kTextMessageDataKey, &message); if (message.empty()) { RTC_LOG(LS_WARNING) << "Cannot get content from incoming text message."; return; } // Send the ack for text message. if (!remote_side_ignores_datachannel_acks_) { Json::Value ack; ack[kMessageTypeKey] = kChatDataReceived; ack[kMessageDataKey] = message_id; SendSignalingMessage(ack); } // Deal with the received text message. for (std::vector<P2PPeerConnectionChannelObserver*>::iterator it = observers_.begin(); it != observers_.end(); ++it) { (*it)->OnMessageReceived(remote_id_, message); } } void P2PPeerConnectionChannel::CreateDataChannel(const std::string& label) { webrtc::DataChannelInit config; data_channel_ = peer_connection_->CreateDataChannel(label, &config); if (data_channel_) data_channel_->RegisterObserver(this); OnNegotiationNeeded(); } webrtc::DataBuffer P2PPeerConnectionChannel::CreateDataBuffer( const std::string& data) { rtc::CopyOnWriteBuffer buffer(data.c_str(), data.length()); webrtc::DataBuffer data_buffer(buffer, false); return data_buffer; } void P2PPeerConnectionChannel::DrainPendingMessages() { RTC_LOG(LS_INFO) << "Draining pending messages. Message queue size: " << pending_messages_.size(); RTC_CHECK(data_channel_); { std::lock_guard<std::mutex> lock(pending_messages_mutex_); for (auto it = pending_messages_.begin(); it != pending_messages_.end(); ++it) { std::shared_ptr<std::string> message; std::function<void()> on_success; std::tie(message, on_success, std::ignore)=*it; data_channel_->Send(CreateDataBuffer(*message)); if (on_success) { event_queue_->PostTask([on_success] { on_success(); }); } } pending_messages_.clear(); } } Json::Value P2PPeerConnectionChannel::UaInfo() { Json::Value ua; // SDK info includes verison and type. Json::Value sdk; SysInfo sys_info = SysInfo::GetInstance(); sdk[kUaSdkVersionKey] = sys_info.sdk.version; sdk[kUaSdkTypeKey] = sys_info.sdk.type; // Runtime values with system information. Json::Value runtime; runtime[kUaRuntimeNameKey] = sys_info.runtime.name; runtime[kUaRuntimeVersionKey] = sys_info.runtime.version; // OS info includes OS name and OS version. Json::Value os; os[kUaOsNameKey] = sys_info.os.name; os[kUaOsVersionKey] = sys_info.os.version; // Capabilities and customized configuration // TODO: currently default to support continual ICE gathering, // Plan-B, and stream removable. Json::Value capabilities; capabilities[kUaContinualGatheringKey] = true; capabilities[kUaUnifiedPlanKey] = true; capabilities[kUaStreamRemovableKey] = true; capabilities[kUaIgnoresDataChannelAcksKey] = true; ua[kUaSdkKey] = sdk; ua[kUaRuntimeKey] = runtime; ua[kUaOsKey] = os; ua[kUaCapabilitiesKey] = capabilities; return ua; } void P2PPeerConnectionChannel::HandleRemoteCapability(Json::Value& ua) { Json::Value capabilities; rtc::GetValueFromJsonObject(ua, kUaCapabilitiesKey, &capabilities); rtc::GetBoolFromJsonObject(capabilities, kUaContinualGatheringKey, &remote_side_supports_continual_ice_gathering_); rtc::GetBoolFromJsonObject(capabilities, kUaUnifiedPlanKey, &remote_side_supports_unified_plan_); remote_side_supports_plan_b_ = !remote_side_supports_unified_plan_; rtc::GetBoolFromJsonObject(capabilities, kUaStreamRemovableKey, &remote_side_supports_remove_stream_); rtc::GetBoolFromJsonObject(capabilities, kUaIgnoresDataChannelAcksKey, &remote_side_ignores_datachannel_acks_); RTC_LOG(LS_INFO) << "Remote side supports removing stream? " << remote_side_supports_remove_stream_; RTC_LOG(LS_INFO) << "Remote side supports WebRTC Plan B? " << remote_side_supports_plan_b_; RTC_LOG(LS_INFO) << "Remote side supports WebRTC Unified Plan?" << remote_side_supports_unified_plan_; RTC_LOG(LS_INFO) << "Remote side ignores data channel acks?" << remote_side_ignores_datachannel_acks_; } void P2PPeerConnectionChannel::SendUaInfo() { Json::Value json; json[kMessageTypeKey] = kChatUserAgent; Json::Value ua = UaInfo(); json[kMessageDataKey] = ua; SendSignalingMessage(json); } } // namespace p2p } // namespace owt
39.159664
99
0.686208
JamesTerm
e919f6adf3e97dbd17434dee435304c8044efaf5
991
cpp
C++
Nov2020/29Nov/KKAndCrush.cpp
shivanisbp/2monthsOfCoding
26dc53e3160c7b313dff974b957c81350bf9f1a1
[ "MIT" ]
null
null
null
Nov2020/29Nov/KKAndCrush.cpp
shivanisbp/2monthsOfCoding
26dc53e3160c7b313dff974b957c81350bf9f1a1
[ "MIT" ]
null
null
null
Nov2020/29Nov/KKAndCrush.cpp
shivanisbp/2monthsOfCoding
26dc53e3160c7b313dff974b957c81350bf9f1a1
[ "MIT" ]
null
null
null
/* Problem Name: KK and crush Problem Link: https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/exists/ */ #include<bits/stdc++.h> using namespace std; #define test(t) int t; cin>>t; while(t--) int main(){ ios::sync_with_stdio(0); cin.tie(0); test(t){ int n,k; cin>>n; int val, pos[100001]={0}, neg[100001]={0}; for(int i=0;i<n;++i){ cin>>val; if(val>=0) pos[val]=1; else neg[-1*val]=1; } cin>>k; for(int i=0;i<k;++i){ int q; cin>>q; if(q >= 0) if(pos[q]) cout<<"Yes\n"; else cout<<"No\n"; else if(neg[-1*q]) cout<<"Yes\n"; else cout<<"No\n"; } } return 0; }
22.022222
136
0.400605
shivanisbp
e91bd998f0b8dd5bb328ede2d5c32564c80a5fae
14,978
hpp
C++
library/src/auxiliary/rocauxiliary_stein.hpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
null
null
null
library/src/auxiliary/rocauxiliary_stein.hpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
null
null
null
library/src/auxiliary/rocauxiliary_stein.hpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
null
null
null
/************************************************************************ * Derived from the BSD3-licensed * LAPACK routine (version 3.7.0) -- * Univ. of Tennessee, Univ. of California Berkeley, * Univ. of Colorado Denver and NAG Ltd.. * December 2016 * Copyright (c) 2019-2022 Advanced Micro Devices, Inc. * ***********************************************************************/ #pragma once #include "lapack_device_functions.hpp" #include "rocblas.hpp" #include "rocsolver.h" /** thread-block size for calling the stein kernel. (MAX_THDS sizes must be one of 128, 256, 512, or 1024) **/ #define STEIN_MAX_THDS 256 #define STEIN_MAX_ITERS 5 #define STEIN_MAX_NRMCHK 2 template <typename T, typename S, std::enable_if_t<!is_complex<T>, int> = 0> __device__ void stein_reorthogonalize(rocblas_int i, const rocblas_int j, const rocblas_int n, const rocblas_int b1, S* work, T* Z, const rocblas_int ldz) { S ztr; rocblas_int jr; for(; i <= j - 1; i++) { ztr = 0; for(jr = 0; jr < n; jr++) ztr = ztr + work[jr] * Z[(b1 + jr) + i * ldz]; for(jr = 0; jr < n; jr++) work[jr] = work[jr] - ztr * Z[(b1 + jr) + i * ldz]; } } template <typename T, typename S, std::enable_if_t<is_complex<T>, int> = 0> __device__ void stein_reorthogonalize(rocblas_int i, const rocblas_int j, const rocblas_int n, const rocblas_int b1, S* work, T* Z, const rocblas_int ldz) { S ztr; rocblas_int jr; for(; i <= j - 1; i++) { ztr = 0; for(jr = 0; jr < n; jr++) ztr = ztr + work[jr] * Z[(b1 + jr) + i * ldz].real(); for(jr = 0; jr < n; jr++) work[jr] = work[jr] - ztr * Z[(b1 + jr) + i * ldz].real(); } } template <int MAX_THDS, typename T, typename S> __device__ void run_stein(const int tid, const rocblas_int n, S* D, S* E, const rocblas_int nev, S* W, rocblas_int* iblock, rocblas_int* isplit, T* Z, const rocblas_int ldz, rocblas_int* ifail, rocblas_int* info, S* work, rocblas_int* iwork, S* sval1, S* sval2, rocblas_int* sidx, S eps, S ssfmin) { __shared__ rocblas_int _info; rocblas_int i, j, j1 = 0, b1, bn, blksize, gpind; S scl, onenrm, ortol, stpcrt, xj, xjm; // zero info and ifail if(tid == 0) _info = 0; for(i = tid; i < nev; i += MAX_THDS) ifail[i] = 0; // iterate over submatrix blocks for(rocblas_int nblk = 0; nblk < iblock[nev - 1]; nblk++) { // start and end indices of the submatrix b1 = (nblk == 0 ? 0 : isplit[nblk - 1]); bn = isplit[nblk] - 1; blksize = bn - b1 + 1; if(blksize > 1) { gpind = j1; // compute reorthogonalization criterion and stopping criterion onenrm = abs(D[b1]) + abs(E[b1]); onenrm = max(onenrm, abs(D[bn]) + abs(E[bn - 1])); for(j = b1 + 1; j <= bn - 1; j++) onenrm = max(onenrm, abs(D[j]) + abs(E[j - 1]) + abs(E[j])); // <- parallelize? ortol = S(0.001) * onenrm; stpcrt = sqrt(0.1 / blksize); } // loop through eigenvalues for current block rocblas_int jblk = 0; for(j = j1; j < nev; j++) { if(iblock[j] - 1 != nblk) { j1 = j; break; } jblk++; xj = W[j]; if(blksize > 1) { // if eigenvalues j and j-1 are too close, add a perturbation if(jblk > 1) { S pertol = 10 * abs(eps * xj); if(xj - xjm < pertol) xj = xjm + pertol; } rocblas_int iters = 0; rocblas_int nrmchk = 0; // initialize starting eigenvector // TODO: how to make it random? for(i = tid; i < blksize; i += MAX_THDS) work[i] = (i == j - j1 ? S(1) : S(-1) / (blksize - 1)); // copy the matrix so it won't be destroyed by factorization for(i = tid; i < blksize - 1; i += MAX_THDS) { work[3 * n + i] = D[b1 + i]; work[2 * n + i] = E[b1 + i]; work[n + i + 1] = E[b1 + i]; } if(tid == 0) work[3 * n + blksize - 1] = D[bn]; __syncthreads(); // compute LU factors with partial pivoting if(tid == 0) lagtf<S>(blksize, work + 3 * n, xj, work + n + 1, work + 2 * n, 0, work + 4 * n, iwork, eps); while(iters < STEIN_MAX_ITERS && nrmchk < STEIN_MAX_NRMCHK) { // normalize and scale righthand side vector iamax<MAX_THDS, S>(tid, blksize, work, 1, sval1, sidx); __syncthreads(); scl = blksize * onenrm * max(eps, abs(work[3 * n + blksize - 1])) / sval1[0]; for(i = tid; i < blksize; i += MAX_THDS) // <- scal work[i] = work[i] * scl; __syncthreads(); // solve the system if(tid == 0) lagts_type1_perturb<S>(blksize, work + 3 * n, work + n + 1, work + 2 * n, work + 4 * n, iwork, work, 0, eps, ssfmin); __syncthreads(); // reorthogonalize by modified Gram-Schmidt if eigenvalues are close enough if(jblk > 1) { if(abs(xj - xjm) > ortol) gpind = j; if(gpind != j) { if(tid == 0) stein_reorthogonalize<T>(gpind, j, blksize, b1, work, Z, ldz); __syncthreads(); } } // check the infinity norm of the iterate against stopping condition iamax<MAX_THDS, S>(tid, blksize, work, 1, sval1, sidx); __syncthreads(); if(sval1[0] >= stpcrt) nrmchk++; iters++; } if(tid == 0 && nrmchk < STEIN_MAX_NRMCHK) { ifail[_info] = j + 1; _info++; } iamax<MAX_THDS, S>(tid, blksize, work, 1, sval1, sidx); nrm2<MAX_THDS, S>(tid, blksize, work, 1, sval2); __syncthreads(); scl = (work[sidx[0]] >= 0 ? S(1) / sval2[0] : S(-1) / sval2[0]); for(i = tid; i < blksize; i += MAX_THDS) // <- scal work[i] = work[i] * scl; __syncthreads(); } else { if(tid == 0) work[0] = S(1); __syncthreads(); } for(i = tid; i < n; i += MAX_THDS) Z[i + j * ldz] = (i >= b1 && i <= bn ? work[i - b1] : T(0)); __syncthreads(); xjm = xj; } } if(tid == 0) *info = _info; } template <typename T, typename S, typename U> ROCSOLVER_KERNEL void __launch_bounds__(STEIN_MAX_THDS) stein_kernel(const rocblas_int n, S* D, const rocblas_stride strideD, S* E, const rocblas_stride strideE, rocblas_int* nev, S* W, const rocblas_stride strideW, rocblas_int* iblock, const rocblas_stride strideIblock, rocblas_int* isplit, const rocblas_stride strideIsplit, U ZZ, const rocblas_int shiftZ, const rocblas_int ldz, const rocblas_stride strideZ, rocblas_int* ifail, const rocblas_stride strideIfail, rocblas_int* info, S* work, rocblas_int* iwork, S eps, S ssfmin) { // select batch instance rocblas_int bid = hipBlockIdx_y; rocblas_int tid = hipThreadIdx_x; rocblas_stride stride_work = 5 * n; rocblas_stride stride_iwork = n; T* Z = load_ptr_batch<T>(ZZ, bid, shiftZ, strideZ); // shared mem for temporary values extern __shared__ double lmem[]; S* sval1 = reinterpret_cast<S*>(lmem); S* sval2 = reinterpret_cast<S*>(sval1 + STEIN_MAX_THDS); rocblas_int* sidx = reinterpret_cast<rocblas_int*>(sval2 + STEIN_MAX_THDS); // execute run_stein<STEIN_MAX_THDS, T>(tid, n, D + (bid * strideD), E + (bid * strideE), nev[bid], W + (bid * strideW), iblock + (bid * strideIblock), isplit + (bid * strideIsplit), Z, ldz, ifail + (bid * strideIfail), info + bid, work + (bid * stride_work), iwork + (bid * stride_iwork), sval1, sval2, sidx, eps, ssfmin); } template <typename T, typename S> void rocsolver_stein_getMemorySize(const rocblas_int n, const rocblas_int batch_count, size_t* size_work, size_t* size_iwork) { // if quick return no workspace needed if(n == 0 || !batch_count) { *size_work = 0; *size_iwork = 0; return; } // size of workspace *size_work = sizeof(S) * 5 * n * batch_count; // size of integer workspace *size_iwork = sizeof(rocblas_int) * n * batch_count; } template <typename T, typename S> rocblas_status rocsolver_stein_argCheck(rocblas_handle handle, const rocblas_int n, S* D, S* E, rocblas_int* nev, S* W, rocblas_int* iblock, rocblas_int* isplit, T* Z, const rocblas_int ldz, rocblas_int* ifail, rocblas_int* info) { // order is important for unit tests: // 1. invalid/non-supported values // N/A // 2. invalid size if(n < 0 || ldz < n) return rocblas_status_invalid_size; // skip pointer check if querying memory size if(rocblas_is_device_memory_size_query(handle)) return rocblas_status_continue; // 3. invalid pointers if((n && !D) || (n && !E) || !nev || (n && !W) || (n && !iblock) || (n && !isplit) || (n && !Z) || (n && !ifail) || !info) return rocblas_status_invalid_pointer; return rocblas_status_continue; } template <typename T, typename S, typename U> rocblas_status rocsolver_stein_template(rocblas_handle handle, const rocblas_int n, S* D, const rocblas_int shiftD, const rocblas_stride strideD, S* E, const rocblas_int shiftE, const rocblas_stride strideE, rocblas_int* nev, S* W, const rocblas_int shiftW, const rocblas_stride strideW, rocblas_int* iblock, const rocblas_stride strideIblock, rocblas_int* isplit, const rocblas_stride strideIsplit, U Z, const rocblas_int shiftZ, const rocblas_int ldz, const rocblas_stride strideZ, rocblas_int* ifail, const rocblas_stride strideIfail, rocblas_int* info, const rocblas_int batch_count, S* work, rocblas_int* iwork) { ROCSOLVER_ENTER("stein", "n:", n, "shiftD:", shiftD, "shiftE:", shiftE, "shiftW:", shiftW, "shiftZ:", shiftZ, "ldz:", ldz, "bc:", batch_count); // quick return if(batch_count == 0) return rocblas_status_success; hipStream_t stream; rocblas_get_stream(handle, &stream); rocblas_int blocksReset = (batch_count - 1) / BS1 + 1; dim3 gridReset(blocksReset, 1, 1); dim3 threadsReset(BS1, 1, 1); // info = 0 ROCSOLVER_LAUNCH_KERNEL(reset_info, gridReset, threadsReset, 0, stream, info, batch_count, 0); // quick return if(n == 0) return rocblas_status_success; S eps = get_epsilon<T>(); S ssfmin = get_safemin<T>(); dim3 grid(1, batch_count, 1); dim3 threads(STEIN_MAX_THDS, 1, 1); size_t lmemsize = STEIN_MAX_THDS * (2 * sizeof(S) + sizeof(rocblas_int)); ROCSOLVER_LAUNCH_KERNEL(stein_kernel<T>, grid, threads, lmemsize, stream, n, D + shiftD, strideD, E + shiftE, strideE, nev, W + shiftW, strideW, iblock, strideIblock, isplit, strideIsplit, Z, shiftZ, ldz, strideZ, ifail, strideIfail, info, work, iwork, eps, ssfmin); return rocblas_status_success; }
37.074257
100
0.426225
rkamd
11ead98b728074eba9901c432769b0091275c0a5
972
hpp
C++
include/tao/json/external/pegtl/internal/require.hpp
ClausKlein/json
eeabe4bdef13ccba985b4423ce558438fd2f5497
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
include/tao/json/external/pegtl/internal/require.hpp
ClausKlein/json
eeabe4bdef13ccba985b4423ce558438fd2f5497
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
include/tao/json/external/pegtl/internal/require.hpp
ClausKlein/json
eeabe4bdef13ccba985b4423ce558438fd2f5497
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (c) 2016-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_JSON_PEGTL_INTERNAL_REQUIRE_HPP #define TAO_JSON_PEGTL_INTERNAL_REQUIRE_HPP #include "../config.hpp" #include "enable_control.hpp" #include "success.hpp" #include "../type_list.hpp" namespace TAO_JSON_PEGTL_NAMESPACE::internal { template< unsigned Amount > struct require; template<> struct require< 0 > : success {}; template< unsigned Amount > struct require { using rule_t = require; using subs_t = empty_list; template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( in.size( 0 ) ) ) { return in.size( Amount ) >= Amount; } }; template< unsigned Amount > inline constexpr bool enable_control< require< Amount > > = false; } // namespace TAO_JSON_PEGTL_NAMESPACE::internal #endif
22.604651
92
0.686214
ClausKlein
11eb95469c375c969c97813e8bea43a3ba8adcda
7,517
cpp
C++
examples/strings_example.cpp
Ptomaine/nstd
72daa4abab97dc82b407c774b00476459df0730b
[ "MIT" ]
31
2017-06-28T09:50:03.000Z
2021-08-11T14:09:35.000Z
examples/strings_example.cpp
Ptomaine/nstd
72daa4abab97dc82b407c774b00476459df0730b
[ "MIT" ]
null
null
null
examples/strings_example.cpp
Ptomaine/nstd
72daa4abab97dc82b407c774b00476459df0730b
[ "MIT" ]
5
2017-06-29T13:43:23.000Z
2020-09-01T02:47:11.000Z
/* MIT License Copyright (c) 2017 Arlen Keshabyan (arlen.albert@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 <iostream> #include "strings.hpp" #include "string_id.hpp" #include "platform_utilities.hpp" int main() { nstd::platform::utilities::scoped_console_utf8 set_console_utf8; using namespace std::string_literals; using namespace nstd::str; using namespace nstd::str::sid::literals; auto u8_to_str = [](const std::u8string &str) { return std::string(std::begin(str), std::end(str)); }; std::u16string u16str(trim(u" Hello World! ")); std::cout << u8_to_str(u8"Всем привет :)") << std::endl; std::cout << trim(" Hello World! ") << std::endl; std::wcout << trim(L" Hello World! ") << std::endl; std::cout << u8_to_str(from_utf16_to_utf8(u16str)) << std::endl; std::cout << u8_to_str(from_utf32_to_utf8(std::u32string(trim(U" Hello World! ")))) << std::endl; std::cout << u8_to_str(from_utf32_to_utf8(replace_all(U"good strings (UTF-32)"s, U"o"s, U"OO"s))) << std::endl; std::cout << replace_regex("good strings (string)"s, "o"s, "[$&]"s) << std::endl; std::wcout << replace_regex(L"good strings (wstring)"s, L"o"s, L"[$&]"s) << std::endl; auto str_container = { 1, 2, 3 }; std::wcout << L"{" << join(str_container, L"}{"s) << L"}" << std::endl; auto str_to_split { L"let's split every word "s }; std::wcout << "to split: '" << str_to_split << "'" << std::endl; auto splitted { split_regex(str_to_split, LR"(\s+)"s) }; for (auto &&str : splitted) std::wcout << str << std::endl; std::wcout << "joined: '" << replace_all(join(splitted, L" "s), L"split"s, L"join"s) << "'" << std::endl; std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(""s)] << std::endl; std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(std::wstring{})] << std::endl; std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(" \n\t "s)] << std::endl; std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(L" \n\t "s)] << std::endl; std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(" \n\t ABC "s)] << std::endl; std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(L" \n\t ABC "s)] << std::endl; auto nr { 3 }; auto s { "'a const char array'" }; auto true_val { true }; std::cout << compose_string("\n", "The value is ", nr, " and another value is ", 8, "; string value is:\t", s, ";\nmax long double precision: ", std::numeric_limits<long double>::max_digits10, "; double: ", numeric_to_string(123.56789012L, std::numeric_limits<long double>::max_digits10), "\ninfinity: ", numeric_to_string(-std::numeric_limits<double>::infinity()), "\n", "\n", boolalpha[true_val], ", ", boolalpha[false]) << std::endl; std::cout << std::setprecision(std::numeric_limits<long double>::max_digits10) << wstring_to_numeric<long double>(L"123.56789012") << std::endl; // create database to store the strings in // it must stay valid as long as each string_id using it sid::default_database database; //=== string_id usage ===// // create an id sid::string_id sid("Test0815", database); std::cout << "Hash code " << sid.hash_code() << " belongs to string \"" << sid.string() << "\"\n"; // Output (Database supports retrieving): Hash code 16741300784925887095 belongs to string "Test0815" // Output (Database doesn't): Hash code 16741300784925887095 belongs to string "string_id database disabled" sid::string_id a("Hello", database), b("World", database); // compare two ids std::cout << std::boolalpha << (a == b) << '\n'; // Output: false // compare id with constant std::cout << (a == "Hello"_id) << '\n'; // Output: true // literal is compile-time switch (b.hash_code()) { case "Hello"_id: std::cout << "Hello\n"; break; case "world"_id: // case-sensitive std::cout << "world\n"; break; case "World"_id: std::cout << "World\n"; break; } //=== generation ===// // the prefix for all generated ids sid::string_id prefix("entity-", database); try { // a generator type appending 8 random characters to the prefix // it uses the std::mt19937 generator for the actual generation typedef sid::random_generator<std::mt19937, 8> generator_t; // create a generator, seed the random number generator with the current time generator_t generator(prefix, std::mt19937(std::int_fast32_t(std::time(nullptr)))); std::vector<sid::string_id> ids; for (auto i = 0; i != 10; ++i) // generate new identifier // it is guaranteed unique and will be stored in the database of the prefix ids.push_back(generator()); // print the name of all the ids for (auto &id : ids) std::cout << id.string() << '\n'; // possible generated name: entity-jXRnZAVG } catch (sid::generation_error &ex) { // the generator was unable to generate a new unique identifier (very unlikely) std::cerr << "[ERROR] " << ex.what() << '\n'; } try { // a generator appending an increasing number to the prefix typedef sid::counter_generator generator_t; // create a generator starting with 0, each number will be 4 digits long generator_t generator(prefix, 0, 4); std::vector<sid::string_id> ids; for (auto i = 0; i != 10; ++i) // generate new identifier // it is guaranteed unique and will be stored in the database of the prefix ids.push_back(generator()); // print the name of all the ids for (auto &id : ids) std::cout << id.string() << '\n'; // possible generated name: entity-0006 } catch (sid::generation_error &ex) { // the generator was unable to generate a new unique identifier (very unlikely) std::cerr << "[ERROR] " << ex.what() << '\n'; } std::cout << "exitting..." << std::endl; return 0; }
44.217647
197
0.603698
Ptomaine
11ed1b9e0328f4afa71af4d18c3da6b495dd25ef
77,919
cpp
C++
src/ast/simplifier/bv_simplifier_plugin.cpp
ezulkosk/z3
1361340d553f67d86bd373e73c64876015a508f8
[ "MIT" ]
1
2018-06-15T00:27:24.000Z
2018-06-15T00:27:24.000Z
src/ast/simplifier/bv_simplifier_plugin.cpp
smt-js/z3
f54a7db1086b8151d42315ae7e2d96efa8ebdbd0
[ "MIT" ]
null
null
null
src/ast/simplifier/bv_simplifier_plugin.cpp
smt-js/z3
f54a7db1086b8151d42315ae7e2d96efa8ebdbd0
[ "MIT" ]
null
null
null
/*++ Copyright (c) 2007 Microsoft Corporation Module Name: bv_simplifier_plugin.cpp Abstract: Simplifier for the bv family. Author: Leonardo (leonardo) 2008-01-08 Nikolaj Bjorner (nbjorner) 2008-01-05 --*/ #include"bv_simplifier_plugin.h" #include"ast_ll_pp.h" #include"ast_pp.h" #include"arith_decl_plugin.h" #include"obj_hashtable.h" #include"ast_util.h" bv_simplifier_plugin::~bv_simplifier_plugin() { flush_caches(); } bv_simplifier_plugin::bv_simplifier_plugin(ast_manager & m, basic_simplifier_plugin & b, bv_simplifier_params & p): poly_simplifier_plugin(symbol("bv"), m, OP_BADD, OP_BMUL, OP_BNEG, OP_BSUB, OP_BV_NUM), m_manager(m), m_util(m), m_arith(m), m_bsimp(b), m_params(p), m_zeros(m) { } rational bv_simplifier_plugin::norm(const numeral & n) { unsigned bv_size = get_bv_size(m_curr_sort); return norm(n, bv_size, false); } bool bv_simplifier_plugin::is_numeral(expr * n, rational & val) const { unsigned bv_size; return m_util.is_numeral(n, val, bv_size); } expr * bv_simplifier_plugin::get_zero(sort * s) const { bv_simplifier_plugin * _this = const_cast<bv_simplifier_plugin*>(this); unsigned bv_size = _this->get_bv_size(s); if (bv_size >= m_zeros.size()) _this->m_zeros.resize(bv_size+1); if (m_zeros.get(bv_size) == 0) _this->m_zeros.set(bv_size, _this->m_util.mk_numeral(rational(0), s)); return m_zeros.get(bv_size); } bool bv_simplifier_plugin::are_numerals(unsigned num_args, expr * const* args, unsigned& bv_size) { numeral r; if (num_args == 0) { return false; } for (unsigned i = 0; i < num_args; ++i) { if (!m_util.is_numeral(args[i], r, bv_size)) { return false; } } return true; } app * bv_simplifier_plugin::mk_numeral(numeral const & n) { unsigned bv_size = get_bv_size(m_curr_sort); return mk_numeral(n, bv_size); } app * bv_simplifier_plugin::mk_numeral(numeral const& n, unsigned bv_size) { numeral r = mod(n, rational::power_of_two(bv_size)); SASSERT(!r.is_neg()); SASSERT(r < rational::power_of_two(bv_size)); return m_util.mk_numeral(r, bv_size); } bool bv_simplifier_plugin::reduce(func_decl * f, unsigned num_args, expr * const * args, expr_ref & result) { set_reduce_invoked(); SASSERT(f->get_family_id() == m_fid); bv_op_kind k = static_cast<bv_op_kind>(f->get_decl_kind()); switch (k) { case OP_BV_NUM: SASSERT(num_args == 0); result = mk_numeral(f->get_parameter(0).get_rational(), f->get_parameter(1).get_int()); break; case OP_BIT0: SASSERT(num_args == 0); result = mk_numeral(0, 1); break; case OP_BIT1: SASSERT(num_args == 0); result = mk_numeral(1, 1); break; case OP_BADD: SASSERT(num_args > 0); mk_add(num_args, args, result); TRACE("bv_add_bug", for (unsigned i = 0; i < num_args; i++) tout << mk_bounded_pp(args[i], m_manager, 10) << "\n"; tout << mk_bounded_pp(result, m_manager, 10) << "\n";); mk_add_concat(result); break; case OP_BSUB: SASSERT(num_args > 0); mk_sub(num_args, args, result); break; case OP_BNEG: SASSERT(num_args == 1); mk_uminus(args[0], result); break; case OP_BMUL: SASSERT(num_args > 0); mk_mul(num_args, args, result); break; case OP_ULEQ: if (m_presimp) return false; SASSERT(num_args == 2); mk_ule(args[0], args[1], result); break; case OP_UGEQ: if (m_presimp) return false; SASSERT(num_args == 2); mk_ule(args[1], args[0], result); break; case OP_ULT: if (m_presimp) return false; SASSERT(num_args == 2); mk_ult(args[0], args[1], result); break; case OP_UGT: if (m_presimp) return false; SASSERT(num_args == 2); mk_ult(args[1], args[0], result); break; case OP_SLEQ: if (m_presimp) return false; SASSERT(num_args == 2); mk_sle(args[0], args[1], result); break; case OP_SGEQ: if (m_presimp) return false; SASSERT(num_args == 2); mk_sle(args[1], args[0], result); break; case OP_SLT: if (m_presimp) return false; SASSERT(num_args == 2); mk_slt(args[0], args[1], result); break; case OP_SGT: if (m_presimp) return false; SASSERT(num_args == 2); mk_slt(args[1], args[0], result); break; case OP_BAND: SASSERT(num_args > 0); mk_bv_and(num_args, args, result); break; case OP_BOR: SASSERT(num_args > 0); mk_bv_or(num_args, args, result); break; case OP_BNOT: SASSERT(num_args == 1); mk_bv_not(args[0], result); break; case OP_BXOR: SASSERT(num_args > 0); mk_bv_xor(num_args, args, result); break; case OP_CONCAT: SASSERT(num_args > 0); mk_concat(num_args, args, result); break; case OP_ZERO_EXT: SASSERT(num_args == 1); SASSERT(f->get_num_parameters() == 1); mk_zeroext(f->get_parameter(0).get_int(), args[0], result); break; case OP_EXTRACT: SASSERT(num_args == 1); SASSERT(f->get_num_parameters() == 2); mk_extract(f->get_parameter(0).get_int(), f->get_parameter(1).get_int(), args[0], result); break; case OP_REPEAT: SASSERT(num_args == 1); SASSERT(f->get_num_parameters() == 1); mk_repeat(f->get_parameter(0).get_int(), args[0], result); break; case OP_BUREM: SASSERT(num_args == 2); mk_bv_urem(args[0], args[1], result); break; case OP_SIGN_EXT: SASSERT(num_args == 1); SASSERT(f->get_num_parameters() == 1); mk_sign_extend(f->get_parameter(0).get_int(), args[0], result); break; case OP_BSHL: SASSERT(num_args == 2); mk_bv_shl(args[0], args[1], result); break; case OP_BLSHR: SASSERT(num_args == 2); mk_bv_lshr(args[0], args[1], result); break; case OP_INT2BV: SASSERT(num_args == 1); mk_int2bv(args[0], f->get_range(), result); break; case OP_BV2INT: SASSERT(num_args == 1); mk_bv2int(args[0], f->get_range(), result); break; case OP_BSDIV: SASSERT(num_args == 2); mk_bv_sdiv(args[0], args[1], result); break; case OP_BUDIV: SASSERT(num_args == 2); mk_bv_udiv(args[0], args[1], result); break; case OP_BSREM: SASSERT(num_args == 2); mk_bv_srem(args[0], args[1], result); break; case OP_BSMOD: SASSERT(num_args == 2); mk_bv_smod(args[0], args[1], result); break; case OP_BNAND: SASSERT(num_args > 0); mk_bv_nand(num_args, args, result); break; case OP_BNOR: SASSERT(num_args > 0); mk_bv_nor(num_args, args, result); break; case OP_BXNOR: SASSERT(num_args > 0); mk_bv_xnor(num_args, args, result); break; case OP_ROTATE_LEFT: SASSERT(num_args == 1); mk_bv_rotate_left(f, args[0], result); break; case OP_ROTATE_RIGHT: SASSERT(num_args == 1); mk_bv_rotate_right(f, args[0], result); break; case OP_EXT_ROTATE_LEFT: SASSERT(num_args == 2); mk_bv_ext_rotate_left(args[0], args[1], result); break; case OP_EXT_ROTATE_RIGHT: SASSERT(num_args == 2); mk_bv_ext_rotate_right(args[0], args[1], result); break; case OP_BREDOR: SASSERT(num_args == 1); mk_bv_redor(args[0], result); break; case OP_BREDAND: SASSERT(num_args == 1); mk_bv_redand(args[0], result); break; case OP_BCOMP: SASSERT(num_args == 2); mk_bv_comp(args[0], args[1], result); break; case OP_BASHR: SASSERT(num_args == 2); mk_bv_ashr(args[0], args[1], result); break; case OP_BSDIV_I: SASSERT(num_args == 2); mk_bv_sdiv_i(args[0], args[1], result); break; case OP_BUDIV_I: SASSERT(num_args == 2); mk_bv_udiv_i(args[0], args[1], result); break; case OP_BSREM_I: SASSERT(num_args == 2); mk_bv_srem_i(args[0], args[1], result); break; case OP_BUREM_I: SASSERT(num_args == 2); mk_bv_urem_i(args[0], args[1], result); break; case OP_BSMOD_I: SASSERT(num_args == 2); mk_bv_smod_i(args[0], args[1], result); break; case OP_BSDIV0: case OP_BUDIV0: case OP_BSREM0: case OP_BUREM0: case OP_BSMOD0: case OP_BIT2BOOL: case OP_CARRY: case OP_XOR3: case OP_MKBV: case OP_BUMUL_NO_OVFL: case OP_BSMUL_NO_OVFL: case OP_BSMUL_NO_UDFL: result = m_manager.mk_app(f, num_args, args); break; default: UNREACHABLE(); break; } SASSERT(result.get()); TRACE("bv_simplifier", tout << mk_pp(f, m_manager) << "\n"; for (unsigned i = 0; i < num_args; ++i) { tout << mk_pp(args[i], m_manager) << " "; } tout << "\n"; tout << mk_pp(result.get(), m_manager) << "\n"; ); return true; } bool bv_simplifier_plugin::reduce_eq(expr * lhs, expr * rhs, expr_ref & result) { set_reduce_invoked(); if (m_presimp) return false; expr_ref tmp(m_manager); tmp = m_manager.mk_eq(lhs,rhs); mk_bv_eq(lhs, rhs, result); return result.get() != tmp.get(); } bool bv_simplifier_plugin::reduce_distinct(unsigned num_args, expr * const * args, expr_ref & result) { set_reduce_invoked(); return false; } void bv_simplifier_plugin::flush_caches() { TRACE("extract_cache", tout << "flushing extract cache...\n";); extract_cache::iterator it = m_extract_cache.begin(); extract_cache::iterator end = m_extract_cache.end(); for (; it != end; ++it) { extract_entry & e = (*it).m_key; m_manager.dec_ref(e.m_arg); m_manager.dec_ref((*it).m_value); } m_extract_cache.reset(); } inline uint64 bv_simplifier_plugin::to_uint64(const numeral & n, unsigned bv_size) { SASSERT(bv_size <= 64); numeral tmp = n; if (tmp.is_neg()) { tmp = mod(tmp, rational::power_of_two(bv_size)); } SASSERT(tmp.is_nonneg()); SASSERT(tmp.is_uint64()); return tmp.get_uint64(); } #define MK_BV_OP(_oper_,_binop_) \ rational bv_simplifier_plugin::mk_bv_ ## _oper_(numeral const& a0, numeral const& b0, unsigned sz) { \ rational r(0), a(a0), b(b0); \ numeral p64 = rational::power_of_two(64); \ numeral mul(1); \ while (sz > 0) { \ numeral a1 = a % p64; \ numeral b1 = b % p64; \ uint64 u = a1.get_uint64() _binop_ b1.get_uint64(); \ if (sz < 64) { \ uint64 mask = shift_left(1ull,(uint64)sz) - 1ull; \ u = mask & u; \ } \ r += mul*rational(u,rational::ui64()); \ mul *= p64; \ a = div(a, p64); \ b = div(b, p64); \ sz -= (sz<64)?sz:64; \ } \ return r; \ } MK_BV_OP(and,&) MK_BV_OP(or,|) MK_BV_OP(xor,^) rational bv_simplifier_plugin::mk_bv_not(numeral const& a0, unsigned sz) { rational r(0), a(a0), mul(1); numeral p64 = rational::power_of_two(64); while (sz > 0) { numeral a1 = a % p64; uint64 u = ~a1.get_uint64(); if (sz < 64) { uint64 mask = shift_left(1ull,(uint64)sz) - 1ull; u = mask & u; } r += mul*rational(u,rational::ui64()); mul *= p64; a = div(a, p64); sz -= (64<sz)?64:sz; } return r; } void bv_simplifier_plugin::mk_ule(expr* a, expr* b, expr_ref& result) { mk_leq_core(false, a, b, result); } void bv_simplifier_plugin::mk_ult(expr* a, expr* b, expr_ref& result) { expr_ref tmp(m_manager); mk_leq_core(false, b, a, tmp); m_bsimp.mk_not(tmp.get(), result); } void bv_simplifier_plugin::mk_sle(expr* a, expr* b, expr_ref& result) { mk_leq_core(true, a, b, result); } void bv_simplifier_plugin::mk_slt(expr* a, expr* b, expr_ref& result) { expr_ref tmp(m_manager); mk_leq_core(true, b, a, tmp); m_bsimp.mk_not(tmp.get(), result); } void bv_simplifier_plugin::mk_leq_core(bool is_signed, expr * arg1, expr * arg2, expr_ref & result) { numeral r1, r2, r3; bool is_num1 = is_numeral(arg1, r1); bool is_num2 = is_numeral(arg2, r2); decl_kind k = is_signed ? OP_SLEQ : OP_ULEQ; unsigned bv_size = get_bv_size(arg1); if (is_num1) { r1 = norm(r1, bv_size, is_signed); } if (is_num2) { r2 = norm(r2, bv_size, is_signed); } if (is_num1 && is_num2) { result = r1 <= r2 ? m_manager.mk_true() : m_manager.mk_false(); return; } numeral lower, upper; if (is_num1 || is_num2) { if (is_signed) { lower = - rational::power_of_two(bv_size - 1); upper = rational::power_of_two(bv_size - 1) - numeral(1); } else { lower = numeral(0); upper = rational::power_of_two(bv_size) - numeral(1); } } if (is_num2) { if (r2 == lower) { m_bsimp.mk_eq(arg1, arg2, result); return; } if (r2 == upper) { result = m_manager.mk_true(); return; } } if (is_num1) { // 0 <= arg2 is true if (r1 == lower) { result = m_manager.mk_true(); return; } // 2^n-1 <= arg2 is arg1 = arg2 if (r1 == upper) { m_bsimp.mk_eq(arg1, arg2, result); return; } } // // In general, we can use lexicographic extensions of concat. // But this does not always turn into savings. // Only apply the simplification if arg1 is a numeral. // if (is_num1 && !is_signed && m_util.is_concat(arg2) && to_app(arg2)->get_num_args() == 2) { // // c <=_u (concat 0 a) <=> c[u:l] = 0 && c[l-1:0] <=_u a // app* app = to_app(arg2); expr * arg2_1 = app->get_arg(0); expr * arg2_2 = app->get_arg(1); if (m_util.is_zero(arg2_1)) { unsigned sz1 = get_bv_size(arg2_1); unsigned sz2 = get_bv_size(arg2_2); expr_ref tmp1(m_manager); expr_ref tmp2(m_manager); mk_extract(sz2 + sz1 - 1, sz2, arg1, tmp1); mk_extract(sz2 - 1, 0, arg1, tmp2); expr_ref eq(m_manager); expr_ref zero(m_manager); zero = mk_bv0(sz1); mk_bv_eq(tmp1.get(), zero, eq); expr_ref ineq(m_manager); ineq = m_util.mk_ule(tmp2.get(), arg2_2); m_bsimp.mk_and(eq.get(), ineq.get(), result); return; } } // // TODO: // Others: // // k <=_s (concat 0 a) <=> (k[u:l] = 0 && k[l-1:0] <=_u a) || k[u:u] = bv1 // // (concat 0 a) <=_s k <=> k[u:u] = bv0 && (k[u:l] != 0 || a <=_u k[l-1:0]) // // (concat 0 a) <=_u k <=> k[u:l] != 0 || a <=_u k[l-1:0] // result = m_manager.mk_app(m_fid, k, arg1, arg2); } void bv_simplifier_plugin::mk_extract(unsigned high, unsigned low, expr* arg, expr_ref& result) { unsigned arg_sz = get_bv_size(arg); unsigned sz = high - low + 1; TRACE("bv_simplifier_plugin", tout << "mk_extract [" << high << ":" << low << "]\n"; tout << "arg_sz: " << arg_sz << " sz: " << sz << "\n"; tout << "arg:\n"; ast_ll_pp(tout, m_manager, arg);); if (arg_sz == sz) { result = arg; } else { mk_extract_core(high, low, arg, result); } if (m_extract_cache.size() > (1 << 12)) { flush_caches(); } TRACE("bv_simplifier_plugin", tout << "mk_extract [" << high << ":" << low << "]\n"; tout << "arg_sz: " << arg_sz << " sz: " << sz << "\n"; tout << "arg:\n"; ast_ll_pp(tout, m_manager, arg); tout << "=====================>\n"; ast_ll_pp(tout, m_manager, result.get());); } void bv_simplifier_plugin::cache_extract(unsigned h, unsigned l, expr * arg, expr * result) { m_manager.inc_ref(arg); m_manager.inc_ref(result); m_extract_cache.insert(extract_entry(h, l, arg), result); } expr* bv_simplifier_plugin::get_cached_extract(unsigned h, unsigned l, expr * arg) { expr * result = 0; if (m_extract_cache.find(extract_entry(h, l, arg), result)) { return result; } return 0; } void bv_simplifier_plugin::mk_extract_core(unsigned high, unsigned low, expr * arg, expr_ref& result) { if (!lookup_mk_extract(high, low, arg, result)) { while (!m_extract_args.empty()) { unsigned low2 = m_lows.back(); unsigned high2 = m_highs.back(); expr* arg2 = m_extract_args.back(); if (try_mk_extract(high2, low2, arg2, result)) { if (!m_extract_cache.contains(extract_entry(high2, low2, arg2))) { cache_extract(high2, low2, arg2, result.get()); } m_lows.pop_back(); m_highs.pop_back(); m_extract_args.pop_back(); } } if (!lookup_mk_extract(high, low, arg, result)) { UNREACHABLE(); } } } bool bv_simplifier_plugin::lookup_mk_extract(unsigned high, unsigned low, expr * arg, expr_ref& result) { expr* cached_result = get_cached_extract(high, low, arg); if (cached_result) { result = cached_result; return true; } m_extract_args.push_back(arg); m_lows.push_back(low); m_highs.push_back(high); return false; } bool bv_simplifier_plugin::try_mk_extract(unsigned high, unsigned low, expr * arg, expr_ref& result) { SASSERT(low <= high); unsigned arg_sz = get_bv_size(arg); unsigned sz = high - low + 1; numeral r; unsigned num_bits; if (arg_sz == sz) { result = arg; return true; } expr* cached_result = get_cached_extract(high, low, arg); if (cached_result) { result = cached_result; return true; } if (!is_app(arg)) { result = m_util.mk_extract(high, low, arg); return true; } app* a = to_app(arg); if (m_util.is_numeral(a, r, num_bits)) { if (r.is_neg()) { r = mod(r, rational::power_of_two(sz)); } SASSERT(r.is_nonneg()); if (r.is_uint64()) { uint64 u = r.get_uint64(); uint64 e = shift_right(u, low) & (shift_left(1ull, sz) - 1ull); TRACE("mk_extract_bug", tout << u << "[" << high << ":" << low << "] " << e << " (u >> low): " << shift_right(u, low) << " (1ull << sz): " << shift_left(1ull, sz) << " ((1ull << sz) - 1ull)" << (shift_left(1ull, sz) - 1ull) << "\n";); result = mk_numeral(numeral(e, numeral::ui64()), sz); return true; } result = mk_numeral(div(r, rational::power_of_two(low)), sz); return true; } // (extract[high:low] (extract[high2:low2] x)) == (extract[high+low2 : low+low2] x) else if (is_app_of(a, m_fid, OP_EXTRACT)) { expr * x = a->get_arg(0); unsigned low2 = a->get_decl()->get_parameter(1).get_int(); return lookup_mk_extract(high + low2, low + low2, x, result); } // // (extract[hi:lo] (bvXshr A c:bv[n])) -> (extract[hi+c:lo+c] A) // if c < n, c <= lo <= hi < n - c // else if ((is_app_of(a, m_fid, OP_BASHR) || is_app_of(a, m_fid, OP_BLSHR)) && is_numeral(a->get_arg(1), r) && r.is_unsigned()) { unsigned c = r.get_unsigned(); unsigned bv_size = get_bv_size(a); if (c < bv_size && c <= low && high < bv_size - c) { return lookup_mk_extract(high+c, low+c, a->get_arg(0), result); } } // (concat a_0 ... a_{n-1}) // Remark: the least significant bits are stored in a_{n-1} else if (is_app_of(a, m_fid, OP_CONCAT)) { expr_ref_buffer new_args(m_manager); unsigned i = a->get_num_args(); // look for first argument while (i > 0) { --i; expr * a_i = a->get_arg(i); unsigned a_sz = get_bv_size(a_i); TRACE("extract_bug", tout << "FIRST a_sz: " << a_sz << " high: " << high << " low: " << low << "\n" << mk_pp(a_i, m_manager) << "\n";); if (a_sz <= low) { low -= a_sz; high -= a_sz; } else { // found first argument if (a_sz <= high) { expr_ref new_arg(m_manager); if (!lookup_mk_extract(a_sz - 1, low, a_i, new_arg)) { return false; } new_args.push_back(new_arg.get()); unsigned num_consumed_bytes = a_sz - low; // I have to apply extract[sz - num_consumed_bytes - 1, 0] on the rest of concat high = (sz - num_consumed_bytes - 1); break; } else { return lookup_mk_extract(high, low, a_i, result); } } } TRACE("extract_bug", tout << " high: " << high << " low: " << low << "\n";); // look for remaining arguments while (i > 0) { --i; expr * a_i = a->get_arg(i); unsigned a_sz = get_bv_size(a_i); TRACE("extract_bug", tout << "SECOND a_sz: " << a_sz << " high: " << high << " " << mk_pp( a_i, m_manager) << "\n";); if (a_sz <= high) { high -= a_sz; new_args.push_back(a_i); } else { // found last argument expr_ref new_arg(m_manager); if (!lookup_mk_extract(high, 0, a_i, new_arg)) { return false; } new_args.push_back(new_arg.get()); // The arguments in new_args are in reverse order. ptr_buffer<expr> rev_new_args; unsigned i = new_args.size(); while (i > 0) { --i; rev_new_args.push_back(new_args[i]); } mk_concat(rev_new_args.size(), rev_new_args.c_ptr(), result); return true; } } UNREACHABLE(); } else if (is_app_of(a, m_fid, OP_SIGN_EXT)) { SASSERT(a->get_num_args() == 1); unsigned bv_size = get_bv_size(a->get_arg(0)); if (high < bv_size) { return lookup_mk_extract(high, low, a->get_arg(0), result); } } else if (is_app_of(a, m_fid, OP_BAND) || is_app_of(a, m_fid, OP_BOR) || is_app_of(a, m_fid, OP_BXOR) || is_app_of(a, m_fid, OP_BNOR) || is_app_of(a, m_fid, OP_BNAND) || is_app_of(a, m_fid, OP_BNOT) || (low == 0 && is_app_of(a, m_fid, OP_BADD)) || (low == 0 && is_app_of(a, m_fid, OP_BMUL)) || (low == 0 && is_app_of(a, m_fid, OP_BSUB))) { expr_ref_buffer new_args(m_manager); bool all_found = true; for (unsigned i = 0; i < a->get_num_args(); ++i) { expr_ref new_arg(m_manager); if (!lookup_mk_extract(high, low, a->get_arg(i), new_arg)) { all_found = false; } new_args.push_back(new_arg.get()); } if (!all_found) { return false; } // We should not use mk_app because it does not guarantee that the result would be in simplified form. // result = m_manager.mk_app(m_fid, a->get_decl_kind(), new_args.size(), new_args.c_ptr()); if (is_app_of(a, m_fid, OP_BAND)) mk_bv_and(new_args.size(), new_args.c_ptr(), result); else if (is_app_of(a, m_fid, OP_BOR)) mk_bv_or(new_args.size(), new_args.c_ptr(), result); else if (is_app_of(a, m_fid, OP_BXOR)) mk_bv_xor(new_args.size(), new_args.c_ptr(), result); else if (is_app_of(a, m_fid, OP_BNOR)) mk_bv_nor(new_args.size(), new_args.c_ptr(), result); else if (is_app_of(a, m_fid, OP_BNAND)) mk_bv_nand(new_args.size(), new_args.c_ptr(), result); else if (is_app_of(a, m_fid, OP_BNOT)) { SASSERT(new_args.size() == 1); mk_bv_not(new_args[0], result); } else if (is_app_of(a, m_fid, OP_BADD)) mk_add(new_args.size(), new_args.c_ptr(), result); else if (is_app_of(a, m_fid, OP_BMUL)) mk_mul(new_args.size(), new_args.c_ptr(), result); else if (is_app_of(a, m_fid, OP_BSUB)) mk_sub(new_args.size(), new_args.c_ptr(), result); else { UNREACHABLE(); } return true; } else if (m_manager.is_ite(a)) { expr_ref then_b(m_manager), else_b(m_manager); bool ok = lookup_mk_extract(high, low, a->get_arg(1), then_b); ok = lookup_mk_extract(high, low, a->get_arg(2), else_b) && ok; if (ok) { m_bsimp.mk_ite(a->get_arg(0), then_b.get(), else_b.get(), result); } return ok; } result = m_util.mk_extract(high, low, arg); return true; } /** \brief Let f be the operator fid:k. Then, this function store in result the flat args of n. If n is not an f application, then store n in result. Example: if n is (f (f a b) (f c (f d e))), then a b c d e are stored in result. */ template<typename T> void get_assoc_args(family_id fid, decl_kind k, expr * n, T & result) { ptr_buffer<expr> todo; todo.push_back(n); while (!todo.empty()) { expr * n = todo.back(); todo.pop_back(); if (is_app_of(n, fid, k)) { app * app = to_app(n); unsigned i = app->get_num_args(); while (i > 0) { --i; todo.push_back(app->get_arg(i)); } } else { result.push_back(n); } } } /** \brief Similar to get_assoc_args, but the arguments are stored in reverse other in result. */ template<typename T> void get_inv_assoc_args(family_id fid, decl_kind k, expr * n, T & result) { ptr_buffer<expr> todo; todo.push_back(n); while (!todo.empty()) { expr * n = todo.back(); todo.pop_back(); if (is_app_of(n, fid, k)) { app * app = to_app(n); unsigned num = app->get_num_args(); for (unsigned i = 0; i < num; i++) todo.push_back(app->get_arg(i)); } else { result.push_back(n); } } } void bv_simplifier_plugin::mk_bv_eq(expr* a1, expr* a2, expr_ref& result) { rational val1; rational val2; bool is_num1 = is_numeral(a1, val1); bool is_num2 = is_numeral(a2, val2); if (is_num1 && is_num2 && val1 != val2) { result = m_manager.mk_false(); return; } if (!m_util.is_concat(a1) && !is_num1) { mk_eq_core(a1, a2, result); return; } if (!m_util.is_concat(a2) && !is_num2) { mk_eq_core(a1, a2, result); return; } ptr_buffer<expr> args1, args2; get_inv_assoc_args(m_fid, OP_CONCAT, a1, args1); get_inv_assoc_args(m_fid, OP_CONCAT, a2, args2); TRACE("mk_bv_eq_concat", tout << mk_ll_pp(a1, m_manager) << "\n" << mk_ll_pp(a2, m_manager) << "\n"; tout << "args1:\n"; for (unsigned i = 0; i < args1.size(); i++) tout << mk_ll_pp(args1[i], m_manager) << "\n"; tout << "args2:\n"; for (unsigned i = 0; i < args2.size(); i++) tout << mk_ll_pp(args2[i], m_manager) << "\n";); expr_ref lhs(m_manager), rhs(m_manager), eq(m_manager); expr_ref_buffer eqs(m_manager); unsigned low1 = 0, low2 = 0; ptr_buffer<expr>::iterator it1 = args1.begin(); ptr_buffer<expr>::iterator end1 = args1.end(); ptr_buffer<expr>::iterator it2 = args2.begin(); ptr_buffer<expr>::iterator end2 = args2.end(); while (it1 != end1 && it2 != end2) { SASSERT(it1 != end1); SASSERT(it2 != end2); expr * arg1 = *it1; expr * arg2 = *it2; TRACE("expr_bv_util", tout << "low1: " << low1 << " low2: " << low2 << "\n"; tout << mk_pp(arg1, m_manager) << "\n"; tout << mk_pp(arg2, m_manager) << "\n";); unsigned sz1 = get_bv_size(arg1); unsigned sz2 = get_bv_size(arg2); SASSERT(low1 < sz1 && low2 < sz2); unsigned rsz1 = sz1 - low1; unsigned rsz2 = sz2 - low2; TRACE("expr_bv_util", tout << "rsz1: " << rsz1 << " rsz2: " << rsz2 << "\n"; tout << mk_pp(arg1, m_manager) << "\n"; tout << mk_pp(arg2, m_manager) << "\n";); if (rsz1 == rsz2) { mk_extract(sz1 - 1, low1, arg1, lhs); mk_extract(sz2 - 1, low2, arg2, rhs); low1 = 0; low2 = 0; ++it1; ++it2; } else if (rsz1 < rsz2) { mk_extract(sz1 - 1, low1, arg1, lhs); mk_extract(rsz1 + low2 - 1, low2, arg2, rhs); low1 = 0; low2 += rsz1; ++it1; } else { mk_extract(rsz2 + low1 - 1, low1, arg1, lhs); mk_extract(sz2 - 1, low2, arg2, rhs); low1 += rsz2; low2 = 0; ++it2; } mk_eq_core(lhs.get(), rhs.get(), eq); eqs.push_back(eq.get()); } m_bsimp.mk_and(eqs.size(), eqs.c_ptr(), result); } void bv_simplifier_plugin::mk_eq_core(expr * arg1, expr * arg2, expr_ref & result) { TRACE("mk_eq_core", ast_ll_pp(tout, m_manager, arg1 ); ast_ll_pp(tout, m_manager, arg2);); if (arg1 == arg2) { result = m_manager.mk_true(); return; } if ((m_util.is_bv_and(arg1) && m_util.is_allone(arg2)) || (m_util.is_bv_or(arg1) && m_util.is_zero(arg2))) { mk_args_eq_numeral(to_app(arg1), arg2, result); return; } if ((m_util.is_bv_and(arg2) && m_util.is_allone(arg1)) || (m_util.is_bv_or(arg2) && m_util.is_zero(arg1))) { mk_args_eq_numeral(to_app(arg2), arg1, result); return; } #if 1 rational r; unsigned num_bits = 0; if (m_util.is_numeral(arg2, r, num_bits)) { std::swap(arg1, arg2); } if (m_util.is_numeral(arg1, r, num_bits) && (m_util.is_bv_and(arg2) || m_util.is_bv_or(arg2) || m_util.is_bv_not(arg2))) { rational two(2); expr_ref tmp(m_manager); expr_ref_vector tmps(m_manager); for (unsigned i = 0; i < num_bits; ++i) { bool is_neg = (r % two).is_zero(); bit2bool_simplify(i, arg2, tmp); if (is_neg) { expr_ref tmp2(m_manager); m_bsimp.mk_not(tmp, tmp2); tmp = tmp2; } tmps.push_back(tmp); r = div(r, two); } m_bsimp.mk_and(tmps.size(), tmps.c_ptr(), result); TRACE("mk_eq_bb", tout << mk_pp(arg1, m_manager) << "\n"; tout << mk_pp(arg2, m_manager) << "\n"; tout << mk_pp(result, m_manager) << "\n";); return; } #endif if (!m_util.is_bv_add(arg1) && !m_util.is_bv_add(arg2) && !m_util.is_bv_mul(arg1) && !m_util.is_bv_mul(arg2)) { m_bsimp.mk_eq(arg1, arg2, result); return; } set_curr_sort(arg1); expr_ref_vector args1(m_manager); expr_ref_vector args2(m_manager); get_assoc_args(m_fid, OP_BADD, arg1, args1); get_assoc_args(m_fid, OP_BADD, arg2, args2); TRACE("mk_eq_core", tout << mk_pp(arg1, m_manager) << "\n" << mk_pp(arg2, m_manager) << "\n"; tout << args1.size() << " " << args2.size() << "\n";); unsigned idx2 = 0; while (idx2 < args2.size()) { expr * m2 = args2.get(idx2); unsigned sz1 = args1.size(); unsigned idx1 = 0; for (; idx1 < sz1; ++idx1) { expr * m1 = args1.get(idx1); if (eq_monomials_modulo_k(m1, m2)) { expr_ref tmp(m_manager); if (merge_monomials(true, m1, m2, tmp)) { args1.set(idx1, tmp.get()); } else { // the monomial cancelled each other. args1.erase(idx1); } break; } } if (idx1 == sz1) { ++idx2; } else { args2.erase(idx2); } } expr_ref lhs(m_manager); expr_ref rhs(m_manager); mk_sum_of_monomials(args1, lhs); mk_sum_of_monomials(args2, rhs); m_bsimp.mk_eq(lhs.get(), rhs.get(), result); } void bv_simplifier_plugin::mk_args_eq_numeral(app * app, expr * n, expr_ref & result) { expr_ref_buffer eqs(m_manager); expr_ref eq(m_manager); unsigned num = app->get_num_args(); for (unsigned i = 0; i < num; i++) { mk_bv_eq(app->get_arg(i), n, eq); eqs.push_back(eq.get()); } m_bsimp.mk_and(eqs.size(), eqs.c_ptr(), result); } void bv_simplifier_plugin::mk_concat(unsigned num_args, expr * const * args, expr_ref & result) { TRACE("bv_simplifier_plugin", tout << "mk_concat:\n"; for (unsigned i = 0; i < num_args; i++) ast_ll_pp(tout, m_manager, args[i]);); unsigned shift = 0; numeral val(0), arg_val; for (unsigned i = num_args; i > 0; ) { --i; expr * arg = args[i]; if (is_numeral(arg, arg_val)) { arg_val *= rational::power_of_two(shift); val += arg_val; shift += get_bv_size(arg); TRACE("bv_simplifier_plugin", tout << "val: " << val << " arg_val: " << arg_val << " shift: " << shift << "\n";); } else { // one of the arguments is not a number result = m_manager.mk_app(m_fid, OP_CONCAT, num_args, args); return; } } // all arguments are numerals result = mk_numeral(val, shift); } void bv_simplifier_plugin::mk_bv_and(unsigned num_args, expr * const* args, expr_ref & result) { ptr_buffer<expr> flat_args; for (unsigned i = 0; i < num_args; ++i) { flat_args.push_back(args[i]); } // expr_lt_proc is a total order on expressions. std::sort(flat_args.begin(), flat_args.end(), expr_lt_proc(m_fid, OP_BNOT)); SASSERT(num_args > 0); unsigned bv_size = get_bv_size(args[0]); numeral allone = mk_allone(bv_size); numeral val; uint64 unit = bv_size <= 64 ? to_uint64(numeral(-1), bv_size) : 0; numeral n_unit(allone); expr * prev = 0; ptr_buffer<expr>::iterator it = flat_args.begin(); ptr_buffer<expr>::iterator it2 = it; ptr_buffer<expr>::iterator end = flat_args.end(); for (; it != end; ++it) { expr* n = *it; if (prev && ((is_app_of(n, m_fid, OP_BNOT) && to_app(n)->get_arg(0) == prev) || (is_app_of(prev, m_fid, OP_BNOT) && to_app(prev)->get_arg(0) == n))) { result = mk_bv0(bv_size); return; } else if (bv_size <= 64 && is_numeral(n, val)) { unit &= to_uint64(val, bv_size); if (unit == 0) { result = mk_bv0(bv_size); return; } } else if (bv_size > 64 && is_numeral(n, val)) { n_unit = mk_bv_and(val, n_unit, bv_size); if (n_unit.is_zero()) { result = mk_bv0(bv_size); return; } } else if (!prev || prev != n) { *it2 = n; prev = *it2; ++it2; } } if (bv_size <= 64) { n_unit = numeral(unit, numeral::ui64()); } flat_args.set_end(it2); if (n_unit != allone) { flat_args.push_back(mk_numeral(n_unit, bv_size)); } unsigned sz = flat_args.size(); switch(sz) { case 0: result = mk_numeral(n_unit, bv_size); break; case 1: result = flat_args.back(); break; default: result = mk_list_assoc_app(m_manager, m_fid, OP_BAND, sz, flat_args.c_ptr()); break; } } void bv_simplifier_plugin::mk_bv_or(unsigned num_args, expr * const* args, expr_ref & result) { #if 0 // Transformations for SAGE // (bvor (concat 0 x) (concat y 0)) ==> (concat y x) // (bvor (concat x 0) (concat 0 y)) ==> (concat x y) if (num_args == 2 && m_util.is_concat(args[0]) && m_util.is_concat(args[1]) && to_app(args[0])->get_num_args() == 2 && to_app(args[1])->get_num_args() == 2) { expr * x1 = to_app(args[0])->get_arg(0); expr * x2 = to_app(args[0])->get_arg(1); expr * y1 = to_app(args[1])->get_arg(0); expr * y2 = to_app(args[1])->get_arg(1); if (get_bv_size(x1) == get_bv_size(y1) && get_bv_size(x2) == get_bv_size(y2)) { if (m_util.is_zero(x1) && m_util.is_zero(y2)) { // (bvor (concat 0 x) (concat y 0)) ==> (concat y x) mk_concat(y1, x2, result); return; } if (m_util.is_zero(x2) && m_util.is_zero(y1)) { // (bvor (concat x 0) (concat 0 y)) ==> (concat x y) mk_concat(x1, y2, result); return; } } } // Investigate why it did not work. #endif ptr_buffer<expr> flat_args; for (unsigned i = 0; i < num_args; ++i) { flat_args.push_back(args[i]); } std::sort(flat_args.begin(), flat_args.end(), expr_lt_proc(m_fid, OP_BNOT)); SASSERT(num_args > 0); unsigned bv_size = get_bv_size(args[0]), sz; numeral allone = mk_allone(bv_size); numeral val; uint64 unit = 0; numeral n_unit(0); expr * prev = 0; ptr_buffer<expr>::iterator it = flat_args.begin(); ptr_buffer<expr>::iterator it2 = it; ptr_buffer<expr>::iterator end = flat_args.end(); for (; it != end; ++it) { expr* n = *it; if (prev && ((is_app_of(n, m_fid, OP_BNOT) && to_app(n)->get_arg(0) == prev) || (is_app_of(prev, m_fid, OP_BNOT) && to_app(prev)->get_arg(0) == n))) { result = mk_numeral(allone, bv_size); return; } else if (bv_size <= 64 && is_numeral(n, val)) { unit |= to_uint64(val, bv_size); } else if (bv_size > 64 && is_numeral(n, val)) { n_unit = mk_bv_or(val, n_unit, bv_size); } else if (!prev || prev != n) { *it2 = n; prev = *it2; ++it2; } } if (bv_size <= 64) { n_unit = numeral(unit, numeral::ui64()); } if (allone == n_unit) { result = mk_numeral(allone, bv_size); return; } flat_args.set_end(it2); if (!n_unit.is_zero()) { flat_args.push_back(mk_numeral(n_unit, bv_size)); } sz = flat_args.size(); switch(sz) { case 0: result = mk_numeral(n_unit, bv_size); break; case 1: result = flat_args.back(); break; default: result = mk_list_assoc_app(m_manager, m_fid, OP_BOR, sz, flat_args.c_ptr()); break; } } void bv_simplifier_plugin::mk_bv_xor(unsigned num_args, expr * const * args, expr_ref & result) { ptr_buffer<expr> flat_args; for (unsigned i = 0; i < num_args; ++i) { flat_args.push_back(args[i]); } std::sort(flat_args.begin(), flat_args.end(), expr_lt_proc()); SASSERT(num_args > 0); unsigned bv_size = get_bv_size(args[0]); numeral val; uint64 unit = 0; numeral n_unit(0); expr * prev = 0; ptr_buffer<expr>::iterator it = flat_args.begin(); ptr_buffer<expr>::iterator it2 = it; ptr_buffer<expr>::iterator end = flat_args.end(); for (; it != end; ++it) { if (bv_size <= 64 && is_numeral(*it, val)) { uint64 u = to_uint64(val, bv_size); unit = u ^ unit; } else if (bv_size > 64 && is_numeral(*it, val)) { n_unit = mk_bv_xor(n_unit, val, bv_size); } else if (prev != 0 && prev == *it) { --it2; // remove prev prev = 0; } else { *it2 = *it; prev = *it2; ++it2; } } flat_args.set_end(it2); if (bv_size <= 64) { n_unit = numeral(numeral(unit,numeral::ui64())); } if (!n_unit.is_zero()) { flat_args.push_back(mk_numeral(n_unit, bv_size)); } unsigned sz = flat_args.size(); switch(sz) { case 0: result = mk_numeral(n_unit, bv_size); break; case 1: result = flat_args.back(); break; default: result = mk_list_assoc_app(m_manager, m_fid, OP_BXOR, flat_args.size(), flat_args.c_ptr()); break; } } void bv_simplifier_plugin::mk_bv_not(expr * arg, expr_ref & result) { numeral val; unsigned bv_size; if (m_util.is_numeral(arg, val, bv_size)) { if (bv_size <= 64) { uint64 l = bv_size; uint64 mask = shift_left(1ull,l) - 1ull; uint64 u = val.get_uint64(); u = mask & (~u); result = mk_numeral(numeral(u, numeral::ui64()), bv_size); TRACE("bv_not_bug", tout << l << " " << mask << " " << u << "\n"; tout << mk_pp(arg, m_manager) << "\n" << mk_pp(result, m_manager) << "\n";); } else { numeral r = mk_bv_not(val, bv_size); result = mk_numeral(r, bv_size); TRACE("bv_not_bug", tout << mk_pp(arg, m_manager) << "\n" << mk_pp(result, m_manager) << "\n";); } } else if (is_app_of(arg, m_fid, OP_BNOT)) { result = to_app(arg)->get_arg(0); } else { result = m_manager.mk_app(m_fid, OP_BNOT, arg); } } void bv_simplifier_plugin::mk_zeroext(unsigned n, expr * arg, expr_ref & result) { if (n == 0) { result = arg; } else { expr_ref zero(m_manager); zero = mk_bv0(n); mk_concat(zero.get(), arg, result); } } void bv_simplifier_plugin::mk_repeat(unsigned n, expr * arg, expr_ref & result) { ptr_buffer<expr> args; for (unsigned i = 0; i < n; i++) { args.push_back(arg); } mk_concat(args.size(), args.c_ptr(), result); } bool bv_simplifier_plugin::is_minus_one_core(expr * arg) const { numeral r; unsigned bv_size; if (m_util.is_numeral(arg, r, bv_size)) { numeral minus_one(-1); minus_one = mod(minus_one, rational::power_of_two(bv_size)); return r == minus_one; } return false; } bool bv_simplifier_plugin::is_x_minus_one(expr * arg, expr * & x) { if (is_add(arg) && to_app(arg)->get_num_args() == 2) { if (is_minus_one_core(to_app(arg)->get_arg(0))) { x = to_app(arg)->get_arg(1); return true; } if (is_minus_one_core(to_app(arg)->get_arg(1))) { x = to_app(arg)->get_arg(0); return true; } } return false; } void bv_simplifier_plugin::mk_bv_urem(expr * arg1, expr * arg2, expr_ref & result) { numeral r1, r2; unsigned bv_size; bool is_num1 = m_util.is_numeral(arg1, r1, bv_size); bool is_num2 = m_util.is_numeral(arg2, r2, bv_size); bv_size = get_bv_size(arg1); if (is_num2 && r2.is_zero() && !m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BUREM0, arg1); return; } if (is_num1 && is_num2 && !r2.is_zero()) { SASSERT(r1.is_nonneg() && r2.is_pos()); r1 %= r2; result = mk_numeral(r1, bv_size); return; } if (!m_params.m_hi_div0) { // TODO: implement the optimization in this branch for the case the hardware interpretation is used for (x urem 0) // urem(0, x) ==> ite(x = 0, urem0(x), 0) if (is_num1 && r1.is_zero()) { expr * zero = arg1; expr_ref urem0(m_manager), eq0(m_manager); urem0 = m_manager.mk_app(m_fid, OP_BUREM0, 1, &zero); m_bsimp.mk_eq(arg2, zero, eq0); m_bsimp.mk_ite(eq0.get(), urem0.get(), zero, result); TRACE("urem", tout << "urem:\n"; ast_ll_pp(tout, m_manager, arg1); ast_ll_pp(tout, m_manager, arg2); tout << "result:\n"; ast_ll_pp(tout, m_manager, result.get());); return; } // urem(x - 1, x) ==> ite(x = 0, urem0(x-1), x - 1) ==> ite(x = 0, urem0(-1), x - 1) expr * x; if (is_x_minus_one(arg1, x) && x == arg2) { expr * x_minus_1 = arg1; expr_ref zero(m_manager); zero = mk_bv0(bv_size); expr_ref minus_one(m_manager), urem0(m_manager), eq0(m_manager); minus_one = mk_numeral(numeral::minus_one(), bv_size); expr * minus_1 = minus_one.get(); urem0 = m_manager.mk_app(m_fid, OP_BUREM0, 1, &minus_1); m_bsimp.mk_eq(arg2, zero.get(), eq0); m_bsimp.mk_ite(eq0.get(), urem0.get(), x_minus_1, result); TRACE("urem", tout << "urem:\n"; ast_ll_pp(tout, m_manager, arg1); ast_ll_pp(tout, m_manager, arg2); tout << "result:\n"; ast_ll_pp(tout, m_manager, result.get());); return; } } if (is_num2 || m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BUREM_I, arg1, arg2); } else { bv_size = get_bv_size(arg2); result = m_manager.mk_ite(m_manager.mk_eq(arg2, mk_numeral(0, bv_size)), m_manager.mk_app(m_fid, OP_BUREM0, arg1), m_manager.mk_app(m_fid, OP_BUREM_I, arg1, arg2)); } } void bv_simplifier_plugin::mk_sign_extend(unsigned n, expr * arg, expr_ref & result) { numeral r; unsigned bv_size; if (m_util.is_numeral(arg, r, bv_size)) { unsigned result_bv_size = bv_size + n; r = norm(r, bv_size, true); r = mod(r, rational::power_of_two(result_bv_size)); result = mk_numeral(r, result_bv_size); TRACE("mk_sign_extend", tout << "n: " << n << "\n"; ast_ll_pp(tout, m_manager, arg); tout << "====>\n"; ast_ll_pp(tout, m_manager, result.get());); return; } parameter param(n); result = m_manager.mk_app(m_fid, OP_SIGN_EXT, 1, &param, 1, &arg); } /** Implement the following reductions (bvashr (bvashr a n1) n2) ==> (bvashr a (+ n1 n2)) (bvlshr (bvlshr a n1) n2) ==> (bvlshr a (+ n1 n2)) (bvshl (bvshl a n1) n2) ==> (bvshl a (+ n1 n2)) when n1 and n2 are numerals. Remark if (+ n1 n2) is greater than bv_size, we set (+ n1 n2) to bv_size Return true if the transformation was applied and the result stored in 'result'. Return false otherwise. */ bool bv_simplifier_plugin::shift_shift(bv_op_kind k, expr* arg1, expr* arg2, expr_ref& result) { SASSERT(k == OP_BASHR || k == OP_BSHL || k == OP_BLSHR); if (!is_app_of(arg1, m_fid, k)) return false; expr * a = to_app(arg1)->get_arg(0); expr * n1 = to_app(arg1)->get_arg(1); expr * n2 = arg2; numeral r1, r2; unsigned bv_size = UINT_MAX; bool is_num1 = m_util.is_numeral(n1, r1, bv_size); bool is_num2 = m_util.is_numeral(n2, r2, bv_size); if (!is_num1 || !is_num2) return false; SASSERT(bv_size != UINT_MAX); numeral r = r1 + r2; if (r > numeral(bv_size)) r = numeral(bv_size); switch (k) { case OP_BASHR: mk_bv_ashr(a, m_util.mk_numeral(r, bv_size), result); break; case OP_BLSHR: mk_bv_lshr(a, m_util.mk_numeral(r, bv_size), result); break; default: SASSERT(k == OP_BSHL); mk_bv_shl(a, m_util.mk_numeral(r, bv_size), result); break; } return true; } void bv_simplifier_plugin::mk_bv_shl(expr * arg1, expr * arg2, expr_ref & result) { // x << 0 == x numeral r1, r2; unsigned bv_size = get_bv_size(arg1); bool is_num1 = is_numeral(arg1, r1); bool is_num2 = is_numeral(arg2, r2); if (is_num2 && r2.is_zero()) { result = arg1; } else if (is_num2 && r2 >= rational(bv_size)) { result = mk_numeral(0, bv_size); } else if (is_num2 && is_num1 && bv_size <= 64) { SASSERT(r1.is_uint64() && r2.is_uint64()); SASSERT(r2.get_uint64() < bv_size); uint64 r = shift_left(r1.get_uint64(), r2.get_uint64()); result = mk_numeral(r, bv_size); } else if (is_num1 && is_num2) { SASSERT(r2 < rational(bv_size)); SASSERT(r2.is_unsigned()); result = mk_numeral(r1 * rational::power_of_two(r2.get_unsigned()), bv_size); } // // (bvshl x k) -> (concat (extract [n-1-k:0] x) bv0:k) // else if (is_num2 && r2.is_pos() && r2 < numeral(bv_size)) { SASSERT(r2.is_unsigned()); unsigned r = r2.get_unsigned(); expr_ref tmp1(m_manager); mk_extract(bv_size - r - 1, 0, arg1, tmp1); expr_ref zero(m_manager); zero = mk_bv0(r); expr* args[2] = { tmp1.get(), zero.get() }; mk_concat(2, args, result); } else if (shift_shift(OP_BSHL, arg1, arg2, result)) { // done } else { result = m_manager.mk_app(m_fid, OP_BSHL, arg1, arg2); } TRACE("mk_bv_shl", tout << mk_pp(arg1, m_manager) << " << " << mk_pp(arg2, m_manager) << " = " << mk_pp(result.get(), m_manager) << "\n";); } void bv_simplifier_plugin::mk_bv_lshr(expr * arg1, expr * arg2, expr_ref & result) { // x >> 0 == x numeral r1, r2; unsigned bv_size = get_bv_size(arg1); bool is_num1 = is_numeral(arg1, r1); bool is_num2 = is_numeral(arg2, r2); if (is_num2 && r2.is_zero()) { result = arg1; } else if (is_num2 && r2 >= rational(bv_size)) { result = mk_numeral(rational(0), bv_size); } else if (is_num1 && is_num2 && bv_size <= 64) { SASSERT(r1.is_uint64()); SASSERT(r2.is_uint64()); uint64 r = shift_right(r1.get_uint64(), r2.get_uint64()); result = mk_numeral(r, bv_size); } else if (is_num1 && is_num2) { SASSERT(r2.is_unsigned()); unsigned sh = r2.get_unsigned(); r1 = div(r1, rational::power_of_two(sh)); result = mk_numeral(r1, bv_size); } // // (bvlshr x k) -> (concat bv0:k (extract [n-1:k] x)) // else if (is_num2 && r2.is_pos() && r2 < numeral(bv_size)) { SASSERT(r2.is_unsigned()); unsigned r = r2.get_unsigned(); expr_ref tmp1(m_manager); mk_extract(bv_size - 1, r, arg1, tmp1); expr_ref zero(m_manager); zero = mk_bv0(r); expr* args[2] = { zero.get(), tmp1.get() }; mk_concat(2, args, result); } else if (shift_shift(OP_BLSHR, arg1, arg2, result)) { // done } else { result = m_manager.mk_app(m_fid, OP_BLSHR, arg1, arg2); } TRACE("mk_bv_lshr", tout << mk_pp(arg1, m_manager) << " >> " << mk_pp(arg2, m_manager) << " = " << mk_pp(result.get(), m_manager) << "\n";); } void bv_simplifier_plugin::mk_int2bv(expr * arg, sort* range, expr_ref & result) { numeral val; bool is_int; unsigned bv_size = get_bv_size(range); if (m_arith.is_numeral(arg, val, is_int)) { result = mk_numeral(val, bv_size); } // (int2bv (bv2int x)) == x else if (is_app_of(arg, m_fid, OP_BV2INT) && bv_size == get_bv_size(to_app(arg)->get_arg(0))) { result = to_app(arg)->get_arg(0); } else { parameter parameter(bv_size); result = m_manager.mk_app(m_fid, OP_INT2BV, 1, &parameter, 1, &arg); SASSERT(result.get()); } } void bv_simplifier_plugin::mk_bv2int(expr * arg, sort* range, expr_ref & result) { if (!m_params.m_bv2int_distribute) { parameter parameter(range); result = m_manager.mk_app(m_fid, OP_BV2INT, 1, &parameter, 1, &arg); return; } numeral v; if (is_numeral(arg, v)) { result = m_arith.mk_numeral(v, true); } else if (is_mul_no_overflow(arg)) { expr_ref tmp1(m_manager), tmp2(m_manager); mk_bv2int(to_app(arg)->get_arg(0), range, tmp1); mk_bv2int(to_app(arg)->get_arg(1), range, tmp2); result = m_arith.mk_mul(tmp1, tmp2); } else if (is_add_no_overflow(arg)) { expr_ref tmp1(m_manager), tmp2(m_manager); mk_bv2int(to_app(arg)->get_arg(0), range, tmp1); mk_bv2int(to_app(arg)->get_arg(1), range, tmp2); result = m_arith.mk_add(tmp1, tmp2); } // commented out to reproduce bug in reduction of int2bv/bv2int else if (m_util.is_concat(arg)) { expr_ref tmp1(m_manager), tmp2(m_manager); unsigned sz2 = get_bv_size(to_app(arg)->get_arg(1)); mk_bv2int(to_app(arg)->get_arg(0), range, tmp1); mk_bv2int(to_app(arg)->get_arg(1), range, tmp2); tmp1 = m_arith.mk_mul(m_arith.mk_numeral(power(numeral(2), sz2), true), tmp1); result = m_arith.mk_add(tmp1, tmp2); } else { parameter parameter(range); result = m_manager.mk_app(m_fid, OP_BV2INT, 1, &parameter, 1, &arg); } SASSERT(m_arith.is_int(m_manager.get_sort(result.get()))); } unsigned bv_simplifier_plugin::num_leading_zero_bits(expr* e) { numeral v; unsigned sz = get_bv_size(e); if (is_numeral(e, v)) { while (v.is_pos()) { SASSERT(sz > 0); --sz; v = div(v, numeral(2)); } return sz; } else if (m_util.is_concat(e)) { app* a = to_app(e); unsigned sz1 = get_bv_size(a->get_arg(0)); unsigned nb1 = num_leading_zero_bits(a->get_arg(0)); if (sz1 == nb1) { nb1 += num_leading_zero_bits(a->get_arg(1)); } return nb1; } return 0; } bool bv_simplifier_plugin::is_mul_no_overflow(expr* e) { if (!is_mul(e)) { return false; } expr* e1 = to_app(e)->get_arg(0); expr* e2 = to_app(e)->get_arg(1); unsigned sz = get_bv_size(e1); unsigned nb1 = num_leading_zero_bits(e1); unsigned nb2 = num_leading_zero_bits(e2); return nb1 + nb2 >= sz; } bool bv_simplifier_plugin::is_add_no_overflow(expr* e) { if (!is_add(e)) { return false; } expr* e1 = to_app(e)->get_arg(0); expr* e2 = to_app(e)->get_arg(1); unsigned nb1 = num_leading_zero_bits(e1); unsigned nb2 = num_leading_zero_bits(e2); return nb1 > 0 && nb2 > 0; } // Macro for generating mk_bv_sdiv_i, mk_bv_udiv_i, mk_bv_srem_i, mk_bv_urem_i and mk_bv_smod_i. // These are essentially evaluators for the arg1 and arg2 are numerals. // Q: Why do we need them? // A: A constant may be eliminated using substitution. Its value is computed using the evaluator. // Example: Suppose we have the top-level atom (= x (bvsrem_i a b)), and x is eliminated. #define MK_FIXED_DIV_I(NAME, OP) \ void bv_simplifier_plugin::NAME##_i(expr * arg1, expr * arg2, expr_ref & result) { \ numeral r1, r2; \ unsigned bv_size; \ bool is_num1 = m_util.is_numeral(arg1, r1, bv_size); \ bool is_num2 = m_util.is_numeral(arg2, r2, bv_size); \ if (is_num1 && is_num2 && !r2.is_zero()) { \ NAME(arg1, arg2, result); \ } \ else { \ result = m_manager.mk_app(m_fid, OP, arg1, arg2); \ } \ } MK_FIXED_DIV_I(mk_bv_sdiv, OP_BSDIV_I) MK_FIXED_DIV_I(mk_bv_udiv, OP_BUDIV_I) MK_FIXED_DIV_I(mk_bv_srem, OP_BSREM_I) MK_FIXED_DIV_I(mk_bv_urem, OP_BUREM_I) MK_FIXED_DIV_I(mk_bv_smod, OP_BSMOD_I) void bv_simplifier_plugin::mk_bv_sdiv(expr* arg1, expr* arg2, expr_ref& result) { numeral r1, r2; unsigned bv_size; bool is_num1 = m_util.is_numeral(arg1, r1, bv_size); bool is_num2 = m_util.is_numeral(arg2, r2, bv_size); if (is_num2 && r2.is_zero() && !m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BSDIV0, arg1); } else if (is_num1 && is_num2 && !r2.is_zero()) { r1 = norm(r1, bv_size, true); r2 = norm(r2, bv_size, true); result = mk_numeral(machine_div(r1, r2), bv_size); } else if (is_num2 || m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BSDIV_I, arg1, arg2); } else { bv_size = get_bv_size(arg2); result = m_manager.mk_ite(m_manager.mk_eq(arg2, mk_numeral(0, bv_size)), m_manager.mk_app(m_fid, OP_BSDIV0, arg1), m_manager.mk_app(m_fid, OP_BSDIV_I, arg1, arg2)); } } void bv_simplifier_plugin::mk_bv_udiv(expr* arg1, expr* arg2, expr_ref& result) { numeral r1, r2; unsigned bv_size; bool is_num1 = m_util.is_numeral(arg1, r1, bv_size); bool is_num2 = m_util.is_numeral(arg2, r2, bv_size); if (is_num2 && r2.is_zero() && !m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BUDIV0, arg1); } else if (is_num1 && is_num2 && !r2.is_zero()) { SASSERT(r1.is_nonneg()); SASSERT(r2.is_nonneg()); result = mk_numeral(machine_div(r1, r2), bv_size); } else if (is_num2 || m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BUDIV_I, arg1, arg2); } else { bv_size = get_bv_size(arg2); result = m_manager.mk_ite(m_manager.mk_eq(arg2, mk_numeral(0, bv_size)), m_manager.mk_app(m_fid, OP_BUDIV0, arg1), m_manager.mk_app(m_fid, OP_BUDIV_I, arg1, arg2)); } } void bv_simplifier_plugin::mk_bv_srem(expr* arg1, expr* arg2, expr_ref& result) { numeral r1, r2; unsigned bv_size; bool is_num1 = m_util.is_numeral(arg1, r1, bv_size); bool is_num2 = m_util.is_numeral(arg2, r2, bv_size); if (is_num2 && r2.is_zero() && !m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BSREM0, arg1); } else if (is_num1 && is_num2 && !r2.is_zero()) { r1 = norm(r1, bv_size, true); r2 = norm(r2, bv_size, true); result = mk_numeral(r1 % r2, bv_size); } else if (is_num2 || m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BSREM_I, arg1, arg2); } else { bv_size = get_bv_size(arg2); result = m_manager.mk_ite(m_manager.mk_eq(arg2, mk_numeral(0, bv_size)), m_manager.mk_app(m_fid, OP_BSREM0, arg1), m_manager.mk_app(m_fid, OP_BSREM_I, arg1, arg2)); } } void bv_simplifier_plugin::mk_bv_smod(expr* arg1, expr* arg2, expr_ref& result) { numeral r1, r2; unsigned bv_size; bool is_num1 = m_util.is_numeral(arg1, r1, bv_size); bool is_num2 = m_util.is_numeral(arg2, r2, bv_size); if (is_num1) r1 = m_util.norm(r1, bv_size, true); if (is_num2) r2 = m_util.norm(r2, bv_size, true); TRACE("bv_simplifier", tout << mk_pp(arg1, m_manager) << " smod " << mk_pp(arg2, m_manager) << "\n"; ); if (is_num2 && r2.is_zero()) { if (!m_params.m_hi_div0) result = m_manager.mk_app(m_fid, OP_BSMOD0, arg1); else result = arg1; } else if (is_num1 && is_num2) { SASSERT(!r2.is_zero()); numeral abs_r1 = m_util.norm(abs(r1), bv_size); numeral abs_r2 = m_util.norm(abs(r2), bv_size); numeral u = m_util.norm(abs_r1 % abs_r2, bv_size); numeral r; if (u.is_zero()) r = u; else if (r1.is_pos() && r2.is_pos()) r = u; else if (r1.is_neg() && r2.is_pos()) r = m_util.norm(-u + r2, bv_size); else if (r1.is_pos() && r2.is_neg()) r = m_util.norm(u + r2, bv_size); else r = m_util.norm(-u, bv_size); result = mk_numeral(r, bv_size); } else if (is_num2 || m_params.m_hi_div0) { result = m_manager.mk_app(m_fid, OP_BSMOD_I, arg1, arg2); } else { bv_size = get_bv_size(arg2); result = m_manager.mk_ite(m_manager.mk_eq(arg2, mk_numeral(0, bv_size)), m_manager.mk_app(m_fid, OP_BSMOD0, arg1), m_manager.mk_app(m_fid, OP_BSMOD_I, arg1, arg2)); } } uint64 bv_simplifier_plugin::n64(expr* e) { numeral r; unsigned bv_size; if (m_util.is_numeral(e, r, bv_size) && bv_size <= 64) { return r.get_uint64(); } UNREACHABLE(); return 0; } rational bv_simplifier_plugin::num(expr* e) { numeral r; unsigned bv_size; if (!m_util.is_numeral(e, r, bv_size)) { UNREACHABLE(); } return r; } void bv_simplifier_plugin::mk_bv_nand(unsigned num_args, expr* const* args, expr_ref& result) { unsigned bv_size; if (are_numerals(num_args, args, bv_size)) { if (bv_size <= 64) { uint64 r = n64(args[0]); for (unsigned i = 1; i < num_args; i++) { r &= n64(args[i]); } result = mk_numeral(~r, bv_size); } else { numeral r = num(args[0]); for (unsigned i = 1; i < num_args; i++) { r = mk_bv_and(r, num(args[i]), bv_size); } result = mk_numeral(mk_bv_not(r, bv_size), bv_size); } } else { result = m_manager.mk_app(m_fid, OP_BNAND, num_args, args); } } void bv_simplifier_plugin::mk_bv_nor(unsigned num_args, expr* const* args, expr_ref& result) { unsigned bv_size; if (are_numerals(num_args, args, bv_size)) { if (bv_size <= 64) { uint64 r = n64(args[0]); for (unsigned i = 1; i < num_args; i++) { r |= n64(args[i]); } result = mk_numeral(~r, bv_size); } else { numeral r = num(args[0]); for (unsigned i = 1; i < num_args; i++) { r = mk_bv_or(r, num(args[i]), bv_size); } result = mk_numeral(mk_bv_not(r, bv_size), bv_size); } } else { result = m_manager.mk_app(m_fid, OP_BNOR, num_args, args); } } void bv_simplifier_plugin::mk_bv_xnor(unsigned num_args, expr* const* args, expr_ref& result) { unsigned bv_size; if (are_numerals(num_args, args, bv_size)) { if (bv_size <= 64) { uint64 r = n64(args[0]); for (unsigned i = 1; i < num_args; i++) { r ^= n64(args[i]); } result = mk_numeral(~r, bv_size); } else { numeral r = num(args[0]); for (unsigned i = 1; i < num_args; i++) { r = mk_bv_xor(r, num(args[i]), bv_size); } result = mk_numeral(mk_bv_not(r, bv_size), bv_size); } } else { result = m_manager.mk_app(m_fid, OP_BXNOR, num_args, args); } } void bv_simplifier_plugin::mk_bv_rotate_left_core(unsigned shift, numeral r, unsigned bv_size, expr_ref& result) { SASSERT(shift < bv_size); if (bv_size <= 64) { uint64 a = r.get_uint64(); uint64 r = shift_left(a, shift) | shift_right(a, bv_size - shift); result = mk_numeral(r, bv_size); } else { rational r1 = div(r, rational::power_of_two(bv_size - shift)); // shift right rational r2 = (r * rational::power_of_two(shift)) % rational::power_of_two(bv_size); // shift left result = mk_numeral(r1 + r2, bv_size); } } void bv_simplifier_plugin::mk_bv_rotate_left(func_decl* f, expr* arg, expr_ref& result) { numeral r; unsigned bv_size; SASSERT(f->get_decl_kind() == OP_ROTATE_LEFT); if (m_util.is_numeral(arg, r, bv_size)) { unsigned shift = f->get_parameter(0).get_int() % bv_size; mk_bv_rotate_left_core(shift, r, bv_size, result); } else { result = m_manager.mk_app(f, arg); } } void bv_simplifier_plugin::mk_bv_rotate_right_core(unsigned shift, numeral r, unsigned bv_size, expr_ref& result) { SASSERT(shift < bv_size); if (bv_size <= 64) { uint64 a = r.get_uint64(); uint64 r = shift_right(a, shift) | shift_left(a, bv_size - shift); result = mk_numeral(r, bv_size); } else { rational r1 = div(r, rational::power_of_two(shift)); // shift right rational r2 = (r * rational::power_of_two(bv_size - shift)) % rational::power_of_two(bv_size); // shift left result = mk_numeral(r1 + r2, bv_size); } } void bv_simplifier_plugin::mk_bv_rotate_right(func_decl* f, expr* arg, expr_ref& result) { numeral r; unsigned bv_size; SASSERT(f->get_decl_kind() == OP_ROTATE_RIGHT); if (m_util.is_numeral(arg, r, bv_size)) { unsigned shift = f->get_parameter(0).get_int() % bv_size; mk_bv_rotate_right_core(shift, r, bv_size, result); } else { result = m_manager.mk_app(f, arg); } } void bv_simplifier_plugin::mk_bv_redor(expr* arg, expr_ref& result) { if (is_numeral(arg)) { result = m_util.is_zero(arg)?mk_numeral(0, 1):mk_numeral(1,1); } else { result = m_manager.mk_app(m_fid, OP_BREDOR, arg); } } void bv_simplifier_plugin::mk_bv_redand(expr* arg, expr_ref& result) { numeral r; unsigned bv_size; if (m_util.is_numeral(arg, r, bv_size)) { numeral allone = mk_allone(bv_size); result = mk_numeral((r == allone)?1:0, 1); } else { result = m_manager.mk_app(m_fid, OP_BREDAND, arg); } } void bv_simplifier_plugin::mk_bv_comp(expr* arg1, expr* arg2, expr_ref& result) { numeral r1, r2; if (arg1 == arg2) { result = mk_numeral(1,1); } else if (is_numeral(arg1, r1) && is_numeral(arg2, r2)) { result = mk_numeral((r1 == r2)?1:0, 1); } else { result = m_manager.mk_app(m_fid, OP_BCOMP, arg1, arg2); } } void bv_simplifier_plugin::mk_bv_ashr(expr* arg1, expr* arg2, expr_ref& result) { numeral r1, r2; unsigned bv_size = get_bv_size(arg1); bool is_num1 = m_util.is_numeral(arg1, r1, bv_size); bool is_num2 = m_util.is_numeral(arg2, r2, bv_size); if (bv_size == 0) { result = mk_numeral(rational(0), bv_size); } else if (is_num2 && r2.is_zero()) { result = arg1; } else if (bv_size <= 64 && is_num1 && is_num2) { uint64 n1 = n64(arg1); uint64 n2_orig = n64(arg2); uint64 n2 = n2_orig % bv_size; SASSERT(n2 < bv_size); uint64 r = shift_right(n1, n2); bool sign = (n1 & shift_left(1ull, bv_size - 1ull)) != 0; if (n2_orig > n2) { if (sign) { r = shift_left(1ull, bv_size) - 1ull; } else { r = 0; } } else if (sign) { uint64 allone = shift_left(1ull, bv_size) - 1ull; uint64 mask = ~(shift_left(1ull, bv_size - n2) - 1ull); mask &= allone; r |= mask; } result = mk_numeral(r, bv_size); TRACE("bv", tout << mk_pp(arg1, m_manager) << " >> " << mk_pp(arg2, m_manager) << " = " << mk_pp(result.get(), m_manager) << "\n"; tout << n1 << " >> " << n2 << " = " << r << "\n"; ); } else if (is_num1 && is_num2 && rational(bv_size) <= r2) { if (has_sign_bit(r1, bv_size)) { result = mk_numeral(mk_allone(bv_size), bv_size); } else { result = mk_bv0(bv_size); } } else if (is_num1 && is_num2) { SASSERT(r2 < rational(bv_size)); bool sign = has_sign_bit(r1, bv_size); r1 = div(r1, rational::power_of_two(r2.get_unsigned())); if (sign) { // pad ones. rational p(1); for (unsigned i = 0; i < bv_size; ++i) { if (r1 < p) { r1 += p; } p *= rational(2); } } result = mk_numeral(r1, bv_size); } else if (shift_shift(OP_BASHR, arg1, arg2, result)) { // done } else { result = m_manager.mk_app(m_fid, OP_BASHR, arg1, arg2); } } void bv_simplifier_plugin::mk_bv_ext_rotate_right(expr* arg1, expr* arg2, expr_ref& result) { numeral r2; unsigned bv_size; if (m_util.is_numeral(arg2, r2, bv_size)) { unsigned shift = static_cast<unsigned>((r2 % numeral(bv_size)).get_uint64() % static_cast<uint64>(bv_size)); numeral r1; if (is_numeral(arg1, r1)) { mk_bv_rotate_right_core(shift, r1, bv_size, result); } else { parameter p(shift); result = m_manager.mk_app(m_fid, OP_ROTATE_RIGHT, 1, &p, 1, &arg1); } } else { result = m_manager.mk_app(m_fid, OP_EXT_ROTATE_RIGHT, arg1, arg2); } } void bv_simplifier_plugin::mk_bv_ext_rotate_left(expr* arg1, expr* arg2, expr_ref& result) { numeral r2; unsigned bv_size; if (m_util.is_numeral(arg2, r2, bv_size)) { unsigned shift = static_cast<unsigned>((r2 % numeral(bv_size)).get_uint64() % static_cast<uint64>(bv_size)); numeral r1; if (is_numeral(arg1, r1)) { mk_bv_rotate_left_core(shift, r1, bv_size, result); } else { parameter p(shift); result = m_manager.mk_app(m_fid, OP_ROTATE_LEFT, 1, &p, 1, &arg1); } } else { result = m_manager.mk_app(m_fid, OP_EXT_ROTATE_LEFT, arg1, arg2); } } void bv_simplifier_plugin::bit2bool_simplify(unsigned idx, expr* e, expr_ref& result) { parameter p(idx); ptr_vector<expr> todo; expr_ref_vector pinned(m_manager); ptr_vector<app> cache; todo.push_back(e); expr* e0 = e; ptr_vector<expr> argv; expr_ref tmp(m_manager); while (!todo.empty()) { e = todo.back(); unsigned e_id = e->get_id(); if (e_id >= cache.size()) { cache.resize(e_id+1,0); } if (cache[e_id]) { todo.pop_back(); continue; } if (!m_util.is_numeral(e) && !m_util.is_bv_and(e) && !m_util.is_bv_or(e) && !(is_app_of(e, m_fid, OP_BXOR) && to_app(e)->get_num_args() == 2) && !m_manager.is_ite(e) && !m_util.is_concat(e) && !m_util.is_bv_not(e)) { expr_ref extr(m_manager); extr = m_util.mk_extract(idx, idx, e); cache[e_id] = m_manager.mk_eq(m_util.mk_numeral(1, 1), extr); pinned.push_back(cache[e_id]); todo.pop_back(); continue; } app* a = to_app(e); unsigned sz = a->get_num_args(); if (m_util.is_concat(e)) { // look for first argument unsigned idx1 = idx; while (sz > 0) { --sz; expr * a_i = a->get_arg(sz); unsigned a_sz = get_bv_size(a_i); if (a_sz <= idx1) { idx1 -= a_sz; } else { // idx < a_sz; bit2bool_simplify(idx1, a_i, tmp); pinned.push_back(tmp); cache[e_id] = to_app(tmp); break; } } todo.pop_back(); continue; } argv.reset(); for (unsigned i = 0; i < sz; ++i) { expr* arg_i = a->get_arg(i); if (i == 0 && m_manager.is_ite(e)) { argv.push_back(arg_i); } else if (cache.size() > arg_i->get_id() && cache[arg_i->get_id()]) { argv.push_back(cache[arg_i->get_id()]); } else { todo.push_back(arg_i); } } if (sz != argv.size()) { continue; } todo.pop_back(); rational val; unsigned num_bits; if (m_util.is_numeral(e, val, num_bits)) { rational two(2); for (unsigned i = 0; i < idx; ++i) { val = div(val, two); } bool is_pos = !(val % two).is_zero(); tmp = is_pos?m_manager.mk_true():m_manager.mk_false(); } else if (m_util.is_bv_and(e)) { //tmp = m_manager.mk_and(sz, argv.c_ptr()); m_bsimp.mk_and(sz, argv.c_ptr(), tmp); pinned.push_back(tmp); } else if (m_util.is_bv_or(e)) { //tmp = m_manager.mk_or(sz, argv.c_ptr()); m_bsimp.mk_or(sz, argv.c_ptr(), tmp); pinned.push_back(tmp); } else if (m_util.is_bv_not(e)) { //tmp = m_manager.mk_not(argv[0]); m_bsimp.mk_not(argv[0], tmp); pinned.push_back(tmp); } else if (is_app_of(e, m_fid, OP_BXOR)) { SASSERT(argv.size() == 2); m_bsimp.mk_xor(argv[0], argv[1], tmp); pinned.push_back(tmp); } else if (m_manager.is_ite(e)) { //tmp = m_manager.mk_ite(argv[0], argv[1], argv[2]); m_bsimp.mk_ite(argv[0], argv[1], argv[2], tmp); pinned.push_back(tmp); } else { UNREACHABLE(); } cache[e_id] = to_app(tmp); } result = cache[e0->get_id()]; } // replace addition by concatenation. void bv_simplifier_plugin::mk_add_concat(expr_ref& result) { if (!m_util.is_bv_add(result)) { return; } app* a = to_app(result); if (a->get_num_args() != 2) { return; } expr* x = a->get_arg(0); expr* y = a->get_arg(1); if (!m_util.is_concat(x)) { std::swap(x, y); } if (!m_util.is_concat(x)) { return; } unsigned sz = m_util.get_bv_size(x); #if 0 // optimzied version. Seems not worth it.. #define UPDATE_CURR(_curr1, _idx1,_x,_is_num, _i) \ if (_idx1 >= m_util.get_bv_size(_curr1)) { \ _curr1 = _x; \ _idx1 = _i; \ _is_num = false; \ } \ while (m_util.is_concat(_curr1)) { \ _is_num = false; \ unsigned num_args = to_app(_curr1)->get_num_args(); \ while (true) { \ --num_args; \ expr* c1 = to_app(_curr1)->get_arg(num_args); \ unsigned sz1 = m_util.get_bv_size(c1); \ if (sz1 < _idx1) { \ _idx1 -= sz1; \ } \ else { \ _curr1 = c1; \ break; \ } \ } \ } unsigned idx1 = 0, idx2 = 0; expr* curr1 = x, *curr2 = y; bool is_num1 = false, is_num2 = false; rational val1, val2; rational two(2); for (unsigned i = 0; i < sz; ++i, ++idx1, ++idx2) { UPDATE_CURR(curr1, idx1, x, is_num1, i); UPDATE_CURR(curr2, idx2, y, is_num2, i); if (idx1 == 0 && m_util.is_numeral(curr1, val1, bv_size)) { is_num1 = true; } if (idx2 == 0 && m_util.is_numeral(curr2, val2, bv_size)) { is_num2 = true; } if ((is_num1 && (val1 % two).is_zero()) || (is_num2 && (val2 % two).is_zero())) { val1 = div(val1, two); val2 = div(val2, two); continue; } return; } mk_bv_or(2, a->get_args(), result); #endif for (unsigned i = 0; i < sz; ++i) { if (!is_zero_bit(x,i) && !is_zero_bit(y,i)) { return; } } mk_bv_or(2, a->get_args(), result); } bool bv_simplifier_plugin::is_zero_bit(expr* x, unsigned idx) { rational val; unsigned bv_size; if (m_util.is_numeral(x, val, bv_size)) { if (val.is_zero()) { return true; } rational two(2); while (idx > 0) { val = div(val, two); idx--; } return (val % two).is_zero(); } if (m_util.is_concat(x)) { unsigned num_args = to_app(x)->get_num_args(); while (num_args > 0) { --num_args; expr* y = to_app(x)->get_arg(num_args); bv_size = m_util.get_bv_size(y); if (bv_size <= idx) { idx -= bv_size; } else { return is_zero_bit(y, idx); } } UNREACHABLE(); } return false; }
34.615282
151
0.534029
ezulkosk
11eee67e9cd88a25428e83e5c2c896d6ce908252
5,818
cpp
C++
examples/vectoradd.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
14
2018-08-08T19:02:21.000Z
2022-01-07T14:42:43.000Z
examples/vectoradd.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
null
null
null
examples/vectoradd.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
3
2020-04-20T20:58:34.000Z
2021-11-23T14:50:14.000Z
#include <core.h> #include <htl/fixed.h> #include <eda/altera/avalon.h> #include <eda/altera/avalon_sim.h> #include "common.h" using namespace ch::core; using namespace ch::htl; using namespace eda::altera::avalon; template <typename T> class vectoradd { public: __io ( __in (ch_uint<avm_v0::AddrW>) dst, __in (ch_uint<avm_v0::AddrW>) src0, __in (ch_uint<avm_v0::AddrW>) src1, __in (ch_uint32) count, (avalon_st_io) avs, (avalon_mm_io<avm_v0>) avm_dst, (avalon_mm_io<avm_v0>) avm_src0, (avalon_mm_io<avm_v0>) avm_src1 ); __enum (ctrl_state, (idle, running, done)); vectoradd(int delay) : delay_(delay) {} void describe() { ch_reg<ctrl_state> state(ctrl_state::idle); ch_reg<ch_uint32> remaining(0); __switch (state) __case (ctrl_state::idle) { __if (io.avs.valid_in) { state->next = ctrl_state::running; }; } __case (ctrl_state::running) { __if (0 == remaining) { state->next = ctrl_state::done; }; } __case (ctrl_state::done) { __if (!avm_writer_.io.busy && io.avs.ready_in) { state->next = ctrl_state::idle; }; }; auto start = io.avs.valid_in && (state == ctrl_state::idle); __if (start) { remaining->next = io.count; }__elif (avm_writer_.io.enq.ready && avm_writer_.io.enq.valid) { remaining->next = remaining - 1; }; auto enable = avm_writer_.io.enq.ready || !avm_writer_.io.enq.valid; auto sum = ch_delayEn(avm_reader0_.io.deq.data + avm_reader1_.io.deq.data, enable, delay_); auto src0_ready = enable && !(avm_reader0_.io.deq.valid && !avm_reader1_.io.deq.valid); auto src1_ready = enable && !(avm_reader1_.io.deq.valid && !avm_reader0_.io.deq.valid); auto dst_valid = ch_delayEn(avm_reader0_.io.deq.valid & avm_reader1_.io.deq.valid, enable, delay_, false); avm_reader0_.io.deq.ready = src0_ready; avm_reader0_.io.base_addr = io.src0; avm_reader0_.io.count = io.count; avm_reader0_.io.start = start; avm_reader0_.io.avm(io.avm_src0); avm_reader1_.io.deq.ready = src1_ready; avm_reader1_.io.base_addr = io.src1; avm_reader1_.io.start = start; avm_reader1_.io.count = io.count; avm_reader1_.io.avm(io.avm_src1); avm_writer_.io.enq.data = sum; avm_writer_.io.enq.valid = dst_valid; avm_writer_.io.base_addr = io.dst; avm_writer_.io.start = start; avm_writer_.io.done = (state == ctrl_state::done); avm_writer_.io.avm(io.avm_dst); io.avs.ready_out = (state == ctrl_state::idle); io.avs.valid_out = (state == ctrl_state::done) && !avm_writer_.io.busy; } private: ch_module<avm_reader<T>> avm_reader0_; ch_module<avm_reader<T>> avm_reader1_; ch_module<avm_writer<T>> avm_writer_; int delay_; }; using data_type = ch::htl::ch_fixed<32, 16>; static bool verify(const std::vector<ch_system_t<data_type>>& output) { int errors = 0; for (unsigned i = 0; i < output.size(); ++i) { auto value = static_cast<float>(output[i]); auto refvalue = static_cast<float>(2*(i & 0xff)); bool test = (value != refvalue); if (test) { std::cout << "error: value[" << i << "]=" << value << ", gold " << refvalue << std::endl; } errors += test; } if (errors != 0) { std::cout << "\tFound " << errors << " errors: FAILED!" << std::endl; } return (0 == errors); } int main() { unsigned count = 256; // create FFT device ch_device<vectoradd<data_type>> device(2); std::cout << "hardware stats:" << std::endl; ch_stats(std::cout, device); // allocate test buffers auto alloc_size = 64 * ceildiv<uint32_t>(count * (ch_width_v<data_type>/8), 64); std::vector<uint8_t> buffer_in0(alloc_size); std::vector<uint8_t> buffer_in1(alloc_size); std::vector<uint8_t> buffer_out(alloc_size + 64); // setup Avalon slave driver avm_slave_driver<avm_v0> avm_driver(3, 128, 84); avm_driver.bind(0, device.io.avm_src0, buffer_in0.data(), buffer_in0.size()); avm_driver.bind(1, device.io.avm_src1, buffer_in1.data(), buffer_in1.size()); avm_driver.bind(2, device.io.avm_dst, buffer_out.data(), buffer_out.size()); // copy input data for (unsigned i = 0; i < count; ++i) { ch_system_t<data_type> value((float)(i & 0xff)); ch_read(value, 0, buffer_in0.data(), i * ch_width_v<data_type>, ch_width_v<data_type>); ch_read(value, 0, buffer_in1.data(), i * ch_width_v<data_type>, ch_width_v<data_type>); } // run simulation ch_tracer tracer(device); device.io.avs.valid_in = false; device.io.avs.ready_in = false; auto ticks = tracer.run([&](ch_tick t)->bool { if (2 == t) { // start simulation device.io.dst = 0; device.io.src0 = 0; device.io.src1 = 0; device.io.count = count; device.io.avs.valid_in = true; device.io.avs.ready_in = true; } // tick avm driver avm_driver.tick(); // stop when device done return (!device.io.avs.valid_out && (t < MAX_TICKS)); }, 2); std::cout << "Simulation run time: " << std::dec << ticks/2 << " cycles" << std::endl; // flush pending requests avm_driver.flush(); // copy output data std::vector<ch_system_t<data_type>> test_result(count); for (unsigned i = 0; i < count; ++i) { auto& value = test_result[i]; ch_write(value, 0, buffer_out.data(), i * ch_width_v<data_type>, ch_width_v<data_type>); } ch_toVerilog("vectoradd.v", device); // verify output CHECK(verify(test_result)); ch_toFIRRTL("vectoradd.fir", device); tracer.toText("vectoradd.log"); tracer.toVCD("vectoradd.vcd"); tracer.toVerilog("vectoradd_tb.v", "vectoradd.v"); int ret = !system("iverilog vectoradd_tb.v -o vectoradd_tb.iv") & !system("! vvp vectoradd_tb.iv | grep 'ERROR' || false"); return (0 == ret); }
29.989691
111
0.64438
JackWolfard
11f0946859c9ce8aacbbb58e7668aefeb92b4579
1,384
cpp
C++
tests/music/playMusic/mp3.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
8
2018-04-21T07:49:58.000Z
2019-02-21T15:04:28.000Z
tests/music/playMusic/mp3.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
null
null
null
tests/music/playMusic/mp3.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
2
2018-04-21T02:25:47.000Z
2018-04-21T15:03:15.000Z
/* SDL C++ Classes Copyright (C) 2017-2018 Mateus Carmo M. de F. Barbosa 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 <SDL.h> #include <SDL_mixer.h> #include "common.hpp" const char *filename = "song.mp3"; const int ERR_SDL_INIT = -1; int main(int argc, char **argv) { Uint32 sdlFlags = SDL_INIT_VIDEO | SDL_INIT_AUDIO; int mixerFlags = MIX_INIT_MP3; if(!init(sdlFlags, mixerFlags)) { SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "couldn't initialize SDL: %s\n", SDL_GetError()); return ERR_SDL_INIT; } test(filename, MUS_MP3_MAD); quit(); return 0; }
32.952381
76
0.742775
jamesl-github
11f10517359204a8ecccfb6213b897b4d94e0573
705
cpp
C++
LeetCode/530.Minimum_Absolute_Difference_in_BST.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
LeetCode/530.Minimum_Absolute_Difference_in_BST.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
LeetCode/530.Minimum_Absolute_Difference_in_BST.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
// 即中序相鄰最小絕對差值 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int getMinimumDifference(TreeNode* root) { vector<int> arr; dfs(root, arr); int ans = 1e8; for(int i = 1; i < arr.size(); ++i) if(abs(arr[i] - arr[i - 1]) < ans) ans = abs(arr[i] - arr[i - 1]); return ans; } void dfs(TreeNode* root, vector<int>& arr) { if(!root) return; dfs(root->left, arr); arr.push_back(root->val); dfs(root->right, arr); } };
22.741935
59
0.497872
w181496
11f3e133b0853a2119c6b848c70e9bbee788a674
2,792
cc
C++
gcc-gcc-7_3_0-release/libstdc++-v3/libsupc++/eh_exception.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libstdc++-v3/libsupc++/eh_exception.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libstdc++-v3/libsupc++/eh_exception.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// -*- C++ -*- std::exception implementation. // Copyright (C) 1994-2017 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC 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. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. #include "typeinfo" #include "exception" #include <cxxabi.h> std::exception::~exception() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT { } std::bad_exception::~bad_exception() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT { } abi::__forced_unwind::~__forced_unwind() throw() { } abi::__foreign_exception::~__foreign_exception() throw() { } const char* std::exception::what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT { // NB: Another elegant option would be returning typeid(*this).name() // and not overriding what() in bad_exception, bad_alloc, etc. In // that case, however, mangled names would be returned, PR 14493. return "std::exception"; } const char* std::bad_exception::what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT { return "std::bad_exception"; } // Transactional clones for the destructors and what(). // what() is effectively transaction_pure, but we do not want to annotate it // as such; thus, we call exactly the respective nontransactional function. extern "C" { void _ZGTtNKSt9exceptionD1Ev(const std::exception*) { } const char* _ZGTtNKSt9exception4whatEv(const std::exception* that) { // We really want the non-virtual call here. We already executed the // indirect call representing the virtual call, and the TM runtime or the // compiler resolved it to this transactional clone. In the clone, we want // to do the same as for the nontransactional original, so we just call it. return that->std::exception::what(); } void _ZGTtNKSt13bad_exceptionD1Ev( const std::bad_exception*) { } const char* _ZGTtNKSt13bad_exception4whatEv( const std::bad_exception* that) { // Also see _ZGTtNKSt9exception4whatEv. return that->std::bad_exception::what(); } }
32.091954
77
0.746418
best08618
11fa84e0e6ed2b4b1950cdb19b4b651fe4292f1c
9,074
cpp
C++
net.cpp
yibopi/latency-imbalance
2a5836bdbcf197d3373d1478b27c0ffcc8bd8a77
[ "BSD-3-Clause" ]
5
2020-06-24T21:42:41.000Z
2021-09-15T12:27:30.000Z
net.cpp
yibopi/latency-imbalance
2a5836bdbcf197d3373d1478b27c0ffcc8bd8a77
[ "BSD-3-Clause" ]
null
null
null
net.cpp
yibopi/latency-imbalance
2a5836bdbcf197d3373d1478b27c0ffcc8bd8a77
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** Program: $Id: net.cpp 14 2014-12-30 02:33:44Z laalt $ Date: $Date: 2014-12-29 18:33:44 -0800 (Mon, 29 Dec 2014) $ Description: networking routines ****************************************************************************/ #include "flipr.h" /** * Prints a range of data in hex. * * @param buf Start of the data range * @param len Length of the data range * @param brk Number of bytes to print per line * @param tabs Number of tabs to insert at the beginning of each new line */ void print_binary(const unsigned char *buf, int len, int brk, int tabs) { int i, j; for (i = 0; i < len; i++) { if ((i > 0) && (i % brk == 0)) { printf("\n"); for (j = 0; j < tabs; j++) printf("\t"); } printf("%02X ", buf[i]); } printf("\n"); } /** * Prints each header (net, trnspt, data) of a packet in hex. * * @param packet Start of the buffer containing the packet * @param tot_len Total length of the packet buffer */ void print_packet(const unsigned char *packet, int tot_len) { struct ip *ip; struct tcphdr *tcp; int iph_len, tcph_len, hdrs_len; ip = (struct ip *)packet; iph_len = ip->ip_hl << 2; tcp = (struct tcphdr *)(packet + iph_len); tcph_len = tcp->th_off << 2; hdrs_len = iph_len + tcph_len; printf("\tIP Header:\t"); print_binary((unsigned char *)ip, iph_len, 10, 3); printf("\tTCP Header:\t"); print_binary((unsigned char *)tcp, tcph_len, 10, 3); /* only print a data header if the packet has data */ if (tot_len > hdrs_len) { printf("\tData:\t\t"); print_binary(packet + hdrs_len, tot_len - hdrs_len, 10, 3); } } /** * Create a new raw IPv4 socket. * * @param sin_orig Source port and address family (only used on PlanetLab) * @return Descriptor for the newly created socket */ int raw_sock(struct sockaddr_in *sin_orig) { int sock, one = 1; struct sockaddr_in sin; /* create a new sin without the address */ memset(&sin, 0, sizeof sin); sin.sin_family = sin_orig->sin_family; sin.sin_port = sin_orig->sin_port; /* establish raw socket */ if ((sock = socket(PF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) fatal("Create socket failed: %s", strerror(errno)); if (setsockopt(sock, 0, IP_HDRINCL, &one, sizeof one) < 0) warn("setsockopt failed: %s", strerror(errno)); return sock; } /** * Determine our public-facing IPv4 address. * * @param mei Where to save the address we find * @return 1 for success, -1 for failure */ int infer_my_ip(struct sockaddr_in *mei) { struct sockaddr_in me, serv; socklen_t len = sizeof me; int sock, err; memset(&serv, 0, sizeof serv); serv.sin_family = AF_INET; serv.sin_addr.s_addr = inet_addr("8.8.8.8"); serv.sin_port = htons(53); sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) return -1; err = connect(sock, (const struct sockaddr *)&serv, sizeof serv); if (err == -1) return -1; err = getsockname(sock, (struct sockaddr *)&me, &len); if (err == -1) return -1; mei->sin_addr = me.sin_addr; return 1; } /** * Determine our public-facing IPv6 address. * * @param mei6 Where to save the address we find * @return 1 for success, -1 for failure */ int infer_my_ip6(struct sockaddr_in6 *mei6) { struct sockaddr_in6 me6, serv6; socklen_t len = sizeof me6; int sock6, err; memset(&serv6, 0, sizeof serv6); serv6.sin6_family = AF_INET6; inet_pton(AF_INET6, "2001:4860:4860::8888", &serv6.sin6_addr.s6_addr); serv6.sin6_port = htons(53); sock6 = socket(AF_INET6, SOCK_DGRAM, 0); if (sock6 == -1) return -1; err = connect(sock6, (const struct sockaddr *)&serv6, sizeof serv6); if (err == -1) return -1; err = getsockname(sock6, (struct sockaddr *)&me6, &len); if (err == -1) return -1; mei6->sin6_addr = me6.sin6_addr; return 1; } /** * Lookup the given address in DNS. * * @param url DNS or IPv4 address in string form * @param target Where to save the IPv4 address we find */ void resolve_target_ip(char *url, struct sockaddr_in *target) { int error; struct addrinfo hints, *result; /* hints allows us to tell getaddrinfo what kind of answer we want */ memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; /* we want IPv4 addresses only */ /* * we use getaddrinfo() because it can handle either DNS addresses or IPs * as strings */ error = getaddrinfo(url, NULL, &hints, &result); if (error) fatal("Error in getaddrinfo: %s", gai_strerror(error)); /* just grab the first address in the linked list */ target->sin_addr = ((struct sockaddr_in *)result->ai_addr)->sin_addr; freeaddrinfo(result); } /** * Compute an IP checksum. * * @param addr Start of the data range * @param len Length of the data range * @return 2-byte long IP checksum value */ unsigned short in_cksum(unsigned short *addr, int len) { int nleft = len; int sum = 0; unsigned short *w = addr; unsigned short answer = 0; /* * Our algorithm is simple, using a 32 bit accumulator (sum), we add * sequential 16 bit words to it, and at the end, fold back all the carry * bits from the top 16 bits into the lower 16 bits. */ assert(addr); while (nleft > 1) { sum += *w++; nleft -= 2; } /* 4mop up an odd byte, if necessary */ if (nleft == 1) { *(unsigned char *)(&answer) = *(unsigned char *)w; sum += answer; } /* 4add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = ~sum; /* truncate to 16 bits */ return answer; } /* * struct ipovly seems to be a BSD only item... Defining it here for now, but * there should be a better, more cross-platform way of doing this. */ #ifndef _BSD struct ipovly { u_char ih_x1; u_char ih_pr; u_short ih_len; struct in_addr ih_src; struct in_addr ih_dst; }; #endif struct ip6ovly { struct in6_addr ip6_src; struct in6_addr ip6_dst; uint32_t ip6_len; u_char ip6_zeros[3]; u_char ip6_pr; }; /* * Checksum routine for UDP and TCP headers. */ u_short p_cksum(struct ip *ip, u_short * data, int len) { static struct ipovly ipo; u_short sumh, sumd; u_long sumt; ipo.ih_pr = ip->ip_p; ipo.ih_len = htons(len); ipo.ih_src = ip->ip_src; ipo.ih_dst = ip->ip_dst; sumh = in_cksum((u_short *) & ipo, sizeof(ipo)); /* pseudo ip hdr cksum */ sumd = in_cksum((u_short *) data, len); /* payload data cksum */ sumt = (sumh << 16) | (sumd); return ~in_cksum((u_short *) & sumt, sizeof(sumt)); } /* * IPv6 checksum routine for UDP/TCP/ICMP (Section 8.1 of RFC 2460). */ u_short p_cksum(struct ip6_hdr *ip6, u_short * data, int len) { static struct ip6ovly ipo; u_short sumh, sumd; u_long sumt; ipo.ip6_pr = ip6->ip6_nxt; ipo.ip6_len = htons(len); ipo.ip6_src = ip6->ip6_src; ipo.ip6_dst = ip6->ip6_dst; sumh = in_cksum((u_short *) & ipo, sizeof(ipo)); /* pseudo ip hdr cksum */ sumd = in_cksum((u_short *) data, len); /* payload data cksum */ sumt = (sumh << 16) | (sumd); return ~in_cksum((u_short *) & sumt, sizeof(sumt)); } /* * Compute packet payload needed to make UDP checksum correct * (Used to ensure Paris-style load balancing */ unsigned short compute_data(unsigned short start_cksum, unsigned short target_cksum) { unsigned short answer = 0x0000; /* per RFC, if computed checksum is 0, the value 0xFFFF is transmitted */ if (target_cksum == 0xFFFF) target_cksum = 0x0000; /* if the ones' complement of the target checksum is greater than * the ones' complement of the starting checksum, use the overflow * in the computation of IP/UDP checksum to keep result positive */ if (~target_cksum > ~start_cksum) answer = ~target_cksum - (~start_cksum); else answer = 0xFFFF - (~start_cksum) + (~target_cksum); return answer; } /* @@ RB: Gaston v6 code only supports Linux */ #ifdef _LINUX /** * Create a new raw IPv6 socket. * * @param sin_orig Source port and address family * @return Descriptor for the newly created socket */ int raw_sock6(struct sockaddr_in6 *sin6_orig) { int sock, one = 1; struct sockaddr_in6 sin6; /* create a new sin without the address */ memset(&sin6, 0, sizeof sin6); sin6.sin6_family = sin6_orig->sin6_family; sin6.sin6_port = sin6_orig->sin6_port; /* establish raw socket */ if ((sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) fatal("Create socket failed: %s", strerror(errno)); return sock; } #endif
27.413897
86
0.606789
yibopi
11ff047791d9e44ef03347df805f7aac43d6faea
13,374
cpp
C++
FindMeSAT_SW/amateurfunk-funkrufmaster_19862/src/astronom.cpp
DF4IAH/GPS-TrackMe
600511a41c995e98ec6e06a9e5bb1b64cce9b7a6
[ "MIT" ]
2
2018-01-18T16:03:41.000Z
2018-04-01T15:55:59.000Z
FindMeSAT_SW/amateurfunk-funkrufmaster_19862/src/astronom.cpp
DF4IAH/GPS-TrackMe
600511a41c995e98ec6e06a9e5bb1b64cce9b7a6
[ "MIT" ]
null
null
null
FindMeSAT_SW/amateurfunk-funkrufmaster_19862/src/astronom.cpp
DF4IAH/GPS-TrackMe
600511a41c995e98ec6e06a9e5bb1b64cce9b7a6
[ "MIT" ]
2
2020-05-22T17:01:24.000Z
2021-10-08T15:53:01.000Z
/**************************************************************************** * * * * * Copyright (C) 2002-2004 by Holger Flemming * * * * This Program is free software; you can redistribute ist 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 versions. * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRENTY; 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 receved 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. * * * **************************************************************************** * * * Author: * * Holger Flemming, DH4DAI email : dh4dai@amsat.org * * PR : dh4dai@db0wts.#nrw.deu.eu * * * * List of other authors: * * * ****************************************************************************/ /* Modelle und Gleichungen zur Berechnung der Erd- und Mondbahn aus dem de.sci.astronomie-NRFAQ 2.3 Wie kan man Sonnenauf- und Untergaenge berechnen? von Hartmut Rick http://dsa-faq.berlios.de und Manfred Maday, DC9ZP, Satelliten, Sonne, Mond http://manfred.maday.bei.t-online.de/page6_7.htm */ #include "astronom.h" #include "autoconf.h" #include "config.h" #include "callsign.h" #ifdef COMPILE_SLAVES #include "spoolfiles.h" #endif extern callsign G_mycall; extern config_file configuration; #ifdef COMPILE_SLAVES extern spoolfiles spool; #endif /* Geplante Aenderung: =================== Festlegung der Astrodaten nach Slots: Slot 0 naechsten drei Auf- bzw. Untergaenge der Sonne, dazu Datums- und Positionsangabe 11111111112 12345678901234567890 Sonne ##.##. ###### Aufgang ##:##:## Untergang ##:##:## Aufgang ##:##:## Slot 1 Fuer den heutigen und den naechsten Tag die Tageslaenge, sowie zeit der groessten Elevation mit Elevation 11111111112 12345678901234567890 ##.##. Tgsl. ##:## # Max. Elv. ## ##:## ##.##. Tgsl. ##:## # Max. Elv. ## ##:## Slot 2 naechsten drei Auf- bzw. Untergaenge des Mondes, dazu Datums- und Positionsangabe 11111111112 12345678901234567890 Mond ##.##. ###### Aufgang ##:##:## Untergang ##:##:## Aufgang ##:##:## Slot 3 Aktuelle Mondphase in %, sowie naechste Voll- und Neumond 11111111112 12345678901234567890 Zunehmend ##% NM ##.##. ##:## VM ##.##. ##:## */ double astro_daten::periode( double phi ) { double d; double x = phi / ( 2 * PI ); double x2 = modf(x,&d); return 2 * PI * x2; } astro_daten::astro_daten( void ) : logf(configuration) { neigung_erdach = 0.40910518; t_umlauf_sonne = 31556926.; exentr = 0.0167; gamma = 1.7976891; bezug = zeit(962730000); const double b1 = 0.751213; const double a1 = 0.036601102; const double b2 = 0.822513; const double a2 = 0.0362916457; const double b3 = 0.995766; const double a3 = 0.00273777852; const double b4 = 0.974271; const double a4 = 0.0338631922; const double b5 = 0.0312525; const double a5 = 0.0367481957; const double epoche = 25567.5; double d; // Umrechnung der Mondbahnkonstanten auf Epoche 1.1.1970 und // Zeiteinheit Sekunden: ma1 = a1 / 86400.; ma2 = a2 / 86400.; ma3 = a3 / 86400.; ma4 = a4 / 86400.; ma5 = a5 / 86400.; mb1 = modf(b1 + a1 * epoche,&d); mb2 = modf(b2 + a2 * epoche,&d); mb3 = modf(b3 + a3 * epoche,&d); mb4 = modf(b4 + a4 * epoche,&d); mb5 = modf(b5 + a5 * epoche,&d); try { loc = locator(configuration.find("LOCATOR")); activ = configuration.find("ASTRODATEN") == String("JA"); } catch( Error_parameter_not_defined ) { logf.eintrag("Parameter LOCATOR oder ASTRODATEN nicht definiert",LOGMASK_PRGRMERR); } } void astro_daten::spool_msg( const String& msg , int slot) { #ifdef COMPILE_SLAVES try { // Das entsprechende Board oeffnen und die Nachricht // abschicken board brd(RUB_ASTRO,configuration); int board_id = brd.get_brd_id(); destin ds = get_default_destin(); brd.set_msg(msg,slot,ds); // Nachricht ins Spoolverzeichnis schreiben spool.spool_bul(G_mycall,zeit(),board_id,slot,msg,false,ds,128); } // Moegliche Fehler-Exceptions abfangen catch( Error_could_not_open_file ) { logf.eintrag("Nicht moeglich, Datei im Spoolverzeichnis zu oeffnen",LOGMASK_PRGRMERR); } catch( Error_could_not_open_boardfile ) { logf.eintrag("Astrodaten Boarddatei nicht angelegt.",LOGMASK_PRGRMERR); } catch( Error_boarddirectory_not_defined ) { logf.eintrag("Rubrikenverzeichnis nicht definiert.",LOGMASK_PRGRMERR); } catch( Error_could_not_create_boardfile ) { logf.eintrag("Nicht moeglich, Astrodaten Boarddatei zu speichern.",LOGMASK_PRGRMERR); } #endif } double astro_daten::deklination( double laenge, double breite, double ekl ) { double tm = cos(breite) * sin(laenge) * sin(ekl) + sin(breite) * cos(ekl); return asin(tm); } double astro_daten::rektaszension( double laenge, double breite, double dekl, double ekl ) { double a2 = cos(breite) * cos(laenge) / cos(dekl); double a1 = (cos(breite) * sin(laenge) * cos(ekl) - sin(breite) * sin(ekl))/ cos(dekl); return atan2(a1,a2); } void astro_daten::sonne_pos(zeit t, double &laenge, double &breite ) { double x = 2 * PI / t_umlauf_sonne * (t - bezug); laenge = periode(gamma + x - 2 * exentr * sin( x )); breite = 0.; } void astro_daten::mond_pos( zeit t, double &laenge, double &breite ) { double dummy; double c1 = modf(ma1 * (double) t.get_systime() + mb1,&dummy) * 2 * PI; double c2 = modf(ma2 * (double) t.get_systime() + mb2,&dummy) * 2 * PI; double c3 = modf(ma3 * (double) t.get_systime() + mb3,&dummy) * 2 * PI; double c4 = modf(ma4 * (double) t.get_systime() + mb4,&dummy) * 2 * PI; double c5 = modf(ma5 * (double) t.get_systime() + mb5,&dummy) * 2 * PI; // Mondlaenge auf der Ekliptik berechnen laenge = c1 +0.0114842 * sin(2 * c4) + 0.1097637 * sin(c2); laenge -= 0.02223544 * sin( c2 - 2 * c4) - 0.0032986 * sin(c3); laenge += 0.003735 * sin( 2 * c2) - 0.0019697 * sin( 2 * c5); laenge -= 0.0010298 * sin(2 * c2 - 2 * c4) - 0.0009948 * sin( c2 + c3 - 2 * c4); double c6 = c5 + 0.011507 * sin( 2 * c4) + 0.108739 * sin(c2) - 0.0222 * sin(c2 - 2 * c4); breite = 0.08978 * sin(c6) - 0.0025482 * sin(c5 - 2 * c4 ); laenge = periode(laenge); breite = periode(breite); } zeit astro_daten::aufgang( int &st , zeit tages_anfang, double rek, double dekl, double hoehe) { double x = 2 * PI / t_umlauf_sonne * (tages_anfang - bezug); double b = loc.get_breite().rad(); double l = loc.get_laenge().rad(); double costau = ( sin (hoehe) - sin(dekl) * sin(b) ) / ( cos(dekl) * cos(b) ); if (costau > 1) st = +1; else if (costau < -1) st = -1; else { st = 0; double tau = -acos( costau ); int u = (int) (86400. / (2 * PI) * (tau + rek - gamma - x - l ) + 43200 ); u = u % 86400; return tages_anfang + u; } return zeit(); } zeit astro_daten::untergang( int &st , zeit tages_anfang, double rek, double dekl, double hoehe) { double x = 2 * PI / t_umlauf_sonne * (tages_anfang - bezug); double b = loc.get_breite().rad(); double l = loc.get_laenge().rad(); double costau = ( sin (hoehe) - sin(dekl) * sin(b) ) / ( cos(dekl) * cos(b) ); if (costau > 1) st = +1; else if (costau < -1) st = -1; else { st = 0; double tau = acos( costau ); int u = (int) (86400. / (2 * PI) * (tau + rek - gamma - x - l ) + 43200 ); u = u % 86400; return tages_anfang + u; } return zeit(); } void astro_daten::sonne( zeit tn, int slot ) { const double hoehe = -0.014660744; zeit t = tn + 86400; zeit tages_anfang = t - (t.get_systime() % 86400); t = tages_anfang; zeit t_auf = t; zeit t_unter = t; int st; for (int cnt = 0; cnt < 5; cnt++) { double laenge, breite; double rek_auf, rek_unter; double dekl_auf, dekl_unter; sonne_pos(t_auf,laenge,breite); dekl_auf = deklination(laenge,breite,neigung_erdach); rek_auf = rektaszension(laenge,breite,dekl_auf,neigung_erdach); sonne_pos(t_unter,laenge,breite); dekl_unter = deklination(laenge,breite,neigung_erdach); rek_unter = rektaszension(laenge,breite,dekl_unter,neigung_erdach); t_auf = aufgang(st,tages_anfang,rek_auf,dekl_auf,hoehe); if (st != 0) break; t_unter = untergang(st,tages_anfang,rek_unter,dekl_unter,hoehe); if (st != 0) break; } // Erzeugung des Funkrufes: // 12345678901234567890 // Sonne ##.##. ###### // Aufgang : ##:## z // Untergang : ##:## z // Tagesl. : ##:## # String msg = "Sonne "; zeit jetzt = tn; jetzt.set_darstellung(zeit::f_datum); msg = msg + jetzt.get_zeit_string() + " "; msg = msg + loc.str(); if (st < 0) msg = msg + "staendig sichtbar"; else if (st > 0) msg = msg + "nie sichtbar"; else { t_auf.set_darstellung(zeit::f_zeit_s); t_unter.set_darstellung(zeit::f_zeit_s); msg = msg + "Aufgang : "+t_auf.get_zeit_string()+" z"; msg = msg + "Untergang : "+t_unter.get_zeit_string()+" z"; delta_t dt(t_unter-t_auf); msg = msg + "Tagesl. : "+dt.get_string(); } spool_msg(msg,slot); } void astro_daten::mond( zeit tn, int slot ) { const double hoehe = -0.014660744; zeit t = tn + 86400; zeit tages_anfang = t - (t.get_systime() % 86400); t = tages_anfang; zeit t_auf = t; zeit t_unter = t; int st; for (int cnt = 0; cnt < 5; cnt++) { double laenge, breite; double rek_auf, rek_unter; double dekl_auf, dekl_unter; mond_pos(t_auf,laenge,breite); dekl_auf = deklination(laenge,breite,neigung_erdach); rek_auf = rektaszension(laenge,breite,dekl_auf,neigung_erdach); mond_pos(t_unter,laenge,breite); dekl_unter = deklination(laenge,breite,neigung_erdach); rek_unter = rektaszension(laenge,breite,dekl_unter,neigung_erdach); t_auf = aufgang(st,tages_anfang,rek_auf,dekl_auf,hoehe); if (st != 0) break; t_unter = untergang(st,tages_anfang,rek_unter,dekl_unter,hoehe); if (st != 0) break; } double l_sonne,l_mond,breite; mond_pos(tn,l_mond,breite); sonne_pos(tn,l_sonne,breite); double ldiff = (l_mond - l_sonne) / 2; double si = sin(ldiff); int ph = (int) (si * si * 100 ); // Erzeugung des Funkrufes: // 12345678901234567890 // Mond ##.##. ###### // Aufgang : ##:## z // Untergang : ##:## z // Zunehmend ##% String msg = "Mond "; zeit jetzt = tn; jetzt.set_darstellung(zeit::f_datum); msg = msg + jetzt.get_zeit_string() + " "; msg = msg + loc.str(); if (st < 0) msg = msg + "staendig sichtbar "; else if (st > 0) msg = msg + "nie sichtbar "; else { t_auf.set_darstellung(zeit::f_zeit_s); t_unter.set_darstellung(zeit::f_zeit_s); msg = msg + "Aufgang : " + t_auf.get_zeit_string() + " z"; msg = msg + "Untergang : " + t_unter.get_zeit_string() + " z"; if ((-PI < ldiff && ldiff < -(PI/2)) || (0 < ldiff && ldiff < PI/2)) msg = msg + "Zunehmend "; else msg = msg + "Abnehmend "; msg = msg + itoS(ph,2,false) + "%"; } spool_msg(msg,slot); } void astro_daten::process( void ) { if (activ) { sonne(zeit(),1); sonne(zeit()+86400,3); sonne(zeit()+2*86400,5); mond(zeit(),2); mond(zeit()+86400,4); mond(zeit()+2*86400,6); } }
29.137255
96
0.53761
DF4IAH
f50080b795108d17c462e85194a9d1350fe17c9e
69
cpp
C++
test/clustering_coef_wd_cpp.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
test/clustering_coef_wd_cpp.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
test/clustering_coef_wd_cpp.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
#include "bct_test.h" MATRIX_TO_VECTOR_FUNCTION(clustering_coef_wd)
17.25
45
0.855072
devuci
f50bb88e714b2c3badf2d3383a1472ce553182eb
962
cpp
C++
contest/C181/Q2/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:13.000Z
2021-11-26T14:34:34.000Z
contest/C181/Q2/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:49.000Z
2021-11-28T11:28:49.000Z
contest/C181/Q2/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
null
null
null
// URL : https://leetcode-cn.com/contest/weekly-contest-181/problems/four-divisors/ // Author : Modnar // Date : 2020/03/22 #include <bits/stdc++.h> /* ************************* */ class Solution { public: int sumFourDivisors(std::vector<int> &nums) { int ans = 0; for (int i = 0; i != nums.size(); ++i) ans += sumFourFactors(nums[i]); return ans; } private: int sumFourFactors(int val) { int count = 0, ans = 0; for (int i = 2; i <= val/2; ++i) { if (val % i == 0) { ++count; ans += i; } if (count > 2) break; } ans += 1 + val; return (count == 2) ? ans : 0; } }; /* ************************* */ int main(int argc, const char *argv[]) { std::vector<int> nums = {21, 4, 7}; std::cout << (new Solution())->sumFourDivisors(nums) << std::endl; // Ans: 32 return EXIT_SUCCESS; }
23.463415
86
0.453222
Modnars
f50d9fec2a8298fe7643c856e87b779af2eae057
1,964
cpp
C++
src/mongo/db/audit/audit_file.cpp
wangke1020/percona-server-mongodb
5008975f1ac220fdb82ea85c85f2794f554ce3d9
[ "Apache-2.0" ]
1
2019-01-16T12:59:12.000Z
2019-01-16T12:59:12.000Z
src/mongo/db/audit/audit_file.cpp
wangke1020/percona-server-mongodb
5008975f1ac220fdb82ea85c85f2794f554ce3d9
[ "Apache-2.0" ]
4
2019-02-22T10:05:59.000Z
2021-03-26T00:20:23.000Z
src/mongo/db/audit/audit_file.cpp
wangke1020/percona-server-mongodb
5008975f1ac220fdb82ea85c85f2794f554ce3d9
[ "Apache-2.0" ]
10
2018-11-29T07:17:30.000Z
2022-03-07T01:33:41.000Z
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: /*====== This file is part of Percona Server for MongoDB. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. Percona Server for MongoDB is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Percona Server for MongoDB 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Percona Server for MongoDB. If not, see <http://www.gnu.org/licenses/>. ======= */ #include <iostream> #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault #include "mongo/util/log.h" #include "audit_file.h" namespace mongo { namespace audit { int AuditFile::fsyncReturningError() const { if (::fsync(_fd)) { int _errno = errno; log() << "In File::fsync(), ::fsync for '" << _name << "' failed with " << errnoWithDescription() << std::endl; return _errno; } return 0; } int AuditFile::writeReturningError(fileofs o, const char *data, unsigned len) { ssize_t bytesWritten = ::pwrite(_fd, data, len, o); if (bytesWritten != static_cast<ssize_t>(len)) { _bad = true; int _errno = errno; log() << "In File::write(), ::pwrite for '" << _name << "' tried to write " << len << " bytes but only wrote " << bytesWritten << " bytes, failing with " << errnoWithDescription() << std::endl; return _errno; } return 0; } } // namespace audit } // namespace mongo
31.677419
80
0.645621
wangke1020
f50f5dbfc2ea160a169c5329b660927ede48004e
2,841
cpp
C++
modules/tracktion_engine/tracktion_engine_model_1.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/tracktion_engine_model_1.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/tracktion_engine_model_1.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ #if ! JUCE_PROJUCER_LIVE_BUILD #include <future> #include "../../modules/tracktion_graph/tracktion_graph.h" #include "tracktion_engine.h" #include "timestretch/tracktion_TempoDetect.h" #include "model/automation/modifiers/tracktion_ModifierInternal.h" #include "utilities/tracktion_Benchmark.h" #include "model/edit/tracktion_OldEditConversion.h" #include "model/edit/tracktion_EditItem.cpp" #include "model/edit/tracktion_Edit.cpp" #include "model/edit/tracktion_Edit.test.cpp" #include "model/edit/tracktion_EditUtilities.cpp" #include "model/edit/tracktion_SourceFileReference.cpp" #include "model/clips/tracktion_Clip.cpp" #include "model/automation/tracktion_AutomatableEditItem.cpp" #include "model/automation/tracktion_AutomatableParameter.cpp" #include "model/automation/tracktion_MacroParameter.cpp" #include "model/automation/tracktion_AutomationCurve.cpp" #include "model/automation/tracktion_AutomationRecordManager.cpp" #include "model/automation/tracktion_MidiLearn.cpp" #include "model/automation/tracktion_ParameterChangeHandler.cpp" #include "model/automation/tracktion_ParameterControlMappings.cpp" #include "model/automation/tracktion_Modifier.cpp" #include "model/automation/modifiers/tracktion_ModifierCommon.cpp" #include "model/automation/modifiers/tracktion_BreakpointOscillatorModifier.cpp" #include "model/automation/modifiers/tracktion_EnvelopeFollowerModifier.cpp" #include "model/automation/modifiers/tracktion_LFOModifier.cpp" #include "model/automation/modifiers/tracktion_MIDITrackerModifier.cpp" #include "model/automation/modifiers/tracktion_RandomModifier.cpp" #include "model/automation/modifiers/tracktion_StepModifier.cpp" #include "model/clips/tracktion_ArrangerClip.cpp" #include "model/clips/tracktion_AudioClipBase.cpp" #include "model/clips/tracktion_CompManager.cpp" #include "model/clips/tracktion_WaveAudioClip.cpp" #include "model/clips/tracktion_ChordClip.cpp" #include "model/clips/tracktion_EditClip.cpp" #include "model/clips/tracktion_MarkerClip.cpp" #include "model/clips/tracktion_CollectionClip.cpp" #include "model/clips/tracktion_MidiClip.cpp" #include "model/clips/tracktion_StepClipChannel.cpp" #include "model/clips/tracktion_StepClipPattern.cpp" #include "model/clips/tracktion_StepClip.cpp" #include "model/clips/tracktion_ClipEffects.cpp" #include "model/clips/tracktion_WarpTimeManager.cpp" #endif
45.822581
84
0.746568
jbloit
f510e4cf79ef1b6762759fccac213ba0854dcc1a
984
hpp
C++
src/includes/Module_interface.hpp
Exus1/eBot
f39a967de5207d81f4ee3671c23dd98b932a2cb6
[ "MIT" ]
null
null
null
src/includes/Module_interface.hpp
Exus1/eBot
f39a967de5207d81f4ee3671c23dd98b932a2cb6
[ "MIT" ]
null
null
null
src/includes/Module_interface.hpp
Exus1/eBot
f39a967de5207d81f4ee3671c23dd98b932a2cb6
[ "MIT" ]
null
null
null
#ifndef _MODULE_INTEFACE__HPP #define _MODULE_INTEFACE__HPP #include <iostream> #include <map> #include <string> #include <Ts3Api/Server.hpp> #include <ConfigFile.hpp> using namespace std; class Module_interface { friend class Modules_manager; friend class Module_thread; protected: struct module_informations { string module_name = "New module"; string module_prefix = "nw"; string module_version = "0.1a"; float minimum_api_version = 0.1; float minimum_ebot_version = 0.1; } _module_informations; struct callback_function_return { string message = "Error"; bool success = false; }; protected: Ts3Api::Server *server = NULL; ConfigFile* config_file = NULL; map<string, map<string, string>> default_config; void set_server_object(Ts3Api::Server* server) { this->server = server; }; public: callback_function_return _callback(string command, map<string, string> args) { return callback_function_return(); }; virtual void module_loop()=0; }; #endif
20.5
117
0.753049
Exus1
f5135ce80e758c114faab4c6abf99c7a7be23b12
5,608
cpp
C++
apps/openmw/mwgui/itemmodel.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/itemmodel.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/itemmodel.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#include "itemmodel.hpp" #include "../mwworld/class.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/store.hpp" #include "../mwworld/esmstore.hpp" #include "../mwbase/world.hpp" #include "../mwbase/environment.hpp" namespace MWGui { ItemStack::ItemStack(const MWWorld::Ptr &base, ItemModel *creator, size_t count) : mCreator(creator) , mCount(count) , mFlags(0) , mType(Type_Normal) , mBase(base) { if (base.getClass().getEnchantment(base) != "") mFlags |= Flag_Enchanted; static std::set<std::string> boundItemIDCache; // If this is empty then we haven't executed the GMST cache logic yet; or there isn't any sMagicBound* GMST's for some reason if (boundItemIDCache.empty()) { // Build a list of known bound item ID's const MWWorld::Store<ESM::GameSetting> &gameSettings = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>(); for (MWWorld::Store<ESM::GameSetting>::iterator currentIteration = gameSettings.begin(); currentIteration != gameSettings.end(); ++currentIteration) { const ESM::GameSetting &currentSetting = *currentIteration; std::string currentGMSTID = currentSetting.mId; Misc::StringUtils::toLower(currentGMSTID); // Don't bother checking this GMST if it's not a sMagicBound* one. const std::string& toFind = "smagicbound"; if (currentGMSTID.compare(0, toFind.length(), toFind) != 0) continue; // All sMagicBound* GMST's should be of type string std::string currentGMSTValue = currentSetting.getString(); Misc::StringUtils::toLower(currentGMSTValue); boundItemIDCache.insert(currentGMSTValue); } } // Perform bound item check and assign the Flag_Bound bit if it passes std::string tempItemID = base.getCellRef().getRefId(); Misc::StringUtils::toLower(tempItemID); if (boundItemIDCache.count(tempItemID) != 0) mFlags |= Flag_Bound; } ItemStack::ItemStack() : mCreator(NULL) , mCount(0) , mFlags(0) , mType(Type_Normal) { } bool ItemStack::stacks(const ItemStack &other) { if(mBase == other.mBase) return true; // If one of the items is in an inventory and currently equipped, we need to check stacking both ways to be sure if (mBase.getContainerStore() && other.mBase.getContainerStore()) return mBase.getContainerStore()->stacks(mBase, other.mBase) && other.mBase.getContainerStore()->stacks(mBase, other.mBase); if (mBase.getContainerStore()) return mBase.getContainerStore()->stacks(mBase, other.mBase); if (other.mBase.getContainerStore()) return other.mBase.getContainerStore()->stacks(mBase, other.mBase); MWWorld::ContainerStore store; return store.stacks(mBase, other.mBase); } bool operator == (const ItemStack& left, const ItemStack& right) { if (left.mType != right.mType) return false; if(left.mBase == right.mBase) return true; // If one of the items is in an inventory and currently equipped, we need to check stacking both ways to be sure if (left.mBase.getContainerStore() && right.mBase.getContainerStore()) return left.mBase.getContainerStore()->stacks(left.mBase, right.mBase) && right.mBase.getContainerStore()->stacks(left.mBase, right.mBase); if (left.mBase.getContainerStore()) return left.mBase.getContainerStore()->stacks(left.mBase, right.mBase); if (right.mBase.getContainerStore()) return right.mBase.getContainerStore()->stacks(left.mBase, right.mBase); MWWorld::ContainerStore store; return store.stacks(left.mBase, right.mBase); } ItemModel::ItemModel() { } MWWorld::Ptr ItemModel::moveItem(const ItemStack &item, size_t count, ItemModel *otherModel) { MWWorld::Ptr ret = otherModel->copyItem(item, count); removeItem(item, count); return ret; } ProxyItemModel::~ProxyItemModel() { delete mSourceModel; } MWWorld::Ptr ProxyItemModel::copyItem (const ItemStack& item, size_t count, bool setNewOwner) { return mSourceModel->copyItem (item, count, setNewOwner); } void ProxyItemModel::removeItem (const ItemStack& item, size_t count) { mSourceModel->removeItem (item, count); } ItemModel::ModelIndex ProxyItemModel::mapToSource (ModelIndex index) { const ItemStack& itemToSearch = getItem(index); for (size_t i=0; i<mSourceModel->getItemCount(); ++i) { const ItemStack& item = mSourceModel->getItem(i); if (item.mBase == itemToSearch.mBase) return i; } return -1; } ItemModel::ModelIndex ProxyItemModel::mapFromSource (ModelIndex index) { const ItemStack& itemToSearch = mSourceModel->getItem(index); for (size_t i=0; i<getItemCount(); ++i) { const ItemStack& item = getItem(i); if (item.mBase == itemToSearch.mBase) return i; } return -1; } ItemModel::ModelIndex ProxyItemModel::getIndex (ItemStack item) { return mSourceModel->getIndex(item); } }
33.783133
160
0.613053
Bodillium
f516e5001905ce67efe58e80aa9a09a220fe6391
2,221
cc
C++
DreamDaq/codeBackup/DreamDaq.101104/decode_tb2008/MCommon/mhistof.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
3
2021-07-22T12:17:48.000Z
2021-07-27T07:22:54.000Z
DreamDaq/codeBackup/DreamDaq.101104/decode_tb2008/MCommon/mhistof.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
38
2021-07-14T15:41:04.000Z
2022-03-29T14:18:20.000Z
DreamDaq/codeBackup/DreamDaq.101104/decode_tb2008/MCommon/mhistof.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
7
2021-07-21T12:00:33.000Z
2021-11-13T10:45:30.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "mhistof.h" mhistof::mhistof(char *Name, int aSize) { name = (char *) calloc(strlen(Name)+1, sizeof *name); sprintf(name, "%s", Name); asize = aSize; n = (int *) calloc(asize, sizeof *n); sum = (float *) calloc(asize, sizeof *sum); sum2 = (float *) calloc(asize, sizeof *sum2); reset(); } mhistof::~mhistof() { free(name); free(n); free(sum); free(sum2); } void mhistof::reset(char *Name) { if (Name != NULL) { name = (char *)realloc(name, (strlen(Name)+1) * sizeof *name); sprintf(name, "%s", Name); } for (int i=0; i<asize; i++) { sum[i] = sum2[i] = 0; n[i] = 0; } } void mhistof::fill(float *vals) { for (int i=0; i<asize; i++) { n[i]++; sum[i] += vals[i]; sum2[i] += vals[i]*vals[i]; } } void mhistof::fill(int i, float val) { n[i]++; sum[i] += val; sum2[i] += val*val; } float mhistof::mean(int i) { if (n[i] > 0) { return sum[i]/n[i]; } else { return 0; } } float mhistof::rms(int i) { if (n[i] > 0) { float val = sum2[i]/n[i] - sum[i]*sum[i]/n[i]/n[i]; if (val>0) { return sqrt(val); } else { return 0; } } else { return 0; } } void mhistof::means(float *means) { for (int i=0; i<asize; i++) { if (n[i] > 0) { means[i] += sum[i]/n[i]; } else { means[i] = 0; } } } void mhistof::rmss(float *rms) { for (int i=0; i<asize; i++) { if (n[i] > 0) { float val = sum2[i]/n[i] - sum[i]*sum[i]/n[i]/n[i]; if (val>0) { rms[i] = sqrt(val); } else { rms[i] = 0; } } else { rms[i] = 0; } } } int mhistof::print(FILE *fptr, int option) { fprintf(fptr, "%s\n", name); if (option == 0) {// profile option for (int i=0; i<asize; i++) { fprintf(fptr, "%3d %7.2f %7.2f\n", i+1, mean(i), rms(i)); } } else if (option == 1) { // also print entries for (int i=0; i<asize; i++) { fprintf(fptr, "%3d %7.2f %7.2f %5d\n", i+1, mean(i), rms(i), n[i]); } } else { // counting option for (int i=0; i<asize; i++) { fprintf(fptr, "%3d %5d\n", i+1, n[i]); } } return 0; }
17.217054
74
0.488969
ivivarel
f51bed92cb87d2a564142c6c39f3dea330c6fcb9
2,626
ipp
C++
windows/include/boost/archive/impl/archive_pointer_iserializer.ipp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
6
2015-12-29T07:21:01.000Z
2020-05-29T10:47:38.000Z
windows/include/boost/archive/impl/archive_pointer_iserializer.ipp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
windows/include/boost/archive/impl/archive_pointer_iserializer.ipp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // pointer_iserializer.ipp: // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to 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) // See http://www.boost.org for updates, documentation, and revision history. #include <utility> #include <cassert> #include <cstddef> #include <boost/config.hpp> // msvc 6.0 needs this for warning suppression #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::size_t; } // namespace std #endif #include <boost/serialization/singleton.hpp> #include <boost/archive/detail/basic_serializer_map.hpp> #include <boost/archive/detail/archive_pointer_iserializer.hpp> namespace boost { namespace archive { namespace detail { namespace { // anon template<class Archive> class iserializer_map : public basic_serializer_map { }; } template<class Archive> BOOST_ARCHIVE_OR_WARCHIVE_DECL(BOOST_PP_EMPTY()) archive_pointer_iserializer<Archive>::archive_pointer_iserializer( const boost::serialization::extended_type_info & eti ) : basic_pointer_iserializer(eti) { std::pair<BOOST_DEDUCED_TYPENAME iserializer_map<Archive>::iterator, bool> result; result = serialization::singleton< iserializer_map<Archive> >::get_mutable_instance().insert(this); assert(result.second); } template<class Archive> BOOST_ARCHIVE_OR_WARCHIVE_DECL(const basic_pointer_iserializer *) archive_pointer_iserializer<Archive>::find( const boost::serialization::extended_type_info & eti ){ const basic_serializer_arg bs(eti); BOOST_DEDUCED_TYPENAME iserializer_map<Archive>::const_iterator it; it = boost::serialization::singleton< iserializer_map<Archive> >::get_const_instance().find(& bs); assert( it != boost::serialization::singleton< iserializer_map<Archive> >::get_const_instance().end() ); return static_cast<const basic_pointer_iserializer *>(*it); } template<class Archive> BOOST_ARCHIVE_OR_WARCHIVE_DECL(BOOST_PP_EMPTY()) archive_pointer_iserializer<Archive>::~archive_pointer_iserializer(){ std::size_t count; count = serialization::singleton< iserializer_map<Archive> >::get_mutable_instance().erase(this); assert(count); } } // namespace detail } // namespace archive } // namespace boost
31.638554
88
0.684311
jaredhoberock
f51cadb9a52acebd4a9905ca5bebbb3dd40b99c2
315
hpp
C++
rtos/Source/taskertimerservice.hpp
ntsiopliakis/CortexLib
da33b8312de4d3547b28458b8e9c896c72211ed0
[ "MIT" ]
null
null
null
rtos/Source/taskertimerservice.hpp
ntsiopliakis/CortexLib
da33b8312de4d3547b28458b8e9c896c72211ed0
[ "MIT" ]
null
null
null
rtos/Source/taskertimerservice.hpp
ntsiopliakis/CortexLib
da33b8312de4d3547b28458b8e9c896c72211ed0
[ "MIT" ]
null
null
null
// Filename: taskertypes.hpp // Created by by Sergey Kolody aka Lamerok on 29.03.2020. #pragma once template <typename Tasker, typename ...Timers> struct TaskerTimerService { static void OnSystemTick() { Tasker::IsrEntry() ; (Timers::OnTick(), ...) ; Tasker::IsrExit() ; } } ;
21
57
0.622222
ntsiopliakis
f5234a324d231047108a168dcd6d4e8808c38ad4
3,369
cpp
C++
android-project/jni/libtesseract/src/ccstruct/ocrpara.cpp
pixelsquare/tesseract-ocr-unity
f5f16c3d77cb4898f3fa96aed4abd82817de39fd
[ "MIT" ]
6
2019-08-22T11:42:27.000Z
2021-12-24T09:23:23.000Z
android-project/jni/libtesseract/src/ccstruct/ocrpara.cpp
pixelsquare/tesseract-ocr-unity
f5f16c3d77cb4898f3fa96aed4abd82817de39fd
[ "MIT" ]
1
2018-11-30T15:53:24.000Z
2020-01-23T16:46:24.000Z
android-project/jni/libtesseract/src/ccstruct/ocrpara.cpp
pixelsquare/tesseract-ocr-unity
f5f16c3d77cb4898f3fa96aed4abd82817de39fd
[ "MIT" ]
3
2019-05-30T04:13:56.000Z
2021-12-24T09:23:26.000Z
///////////////////////////////////////////////////////////////////// // File: ocrpara.cpp // Description: OCR Paragraph Output Type // Author: David Eger // // (C) Copyright 2010, Google Inc. // 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 "ocrpara.h" #include "host.h" // For NearlyEqual() #include <cstdio> namespace tesseract { using tesseract::JUSTIFICATION_CENTER; using tesseract::JUSTIFICATION_LEFT; using tesseract::JUSTIFICATION_RIGHT; using tesseract::JUSTIFICATION_UNKNOWN; static const char *ParagraphJustificationToString(tesseract::ParagraphJustification justification) { switch (justification) { case JUSTIFICATION_LEFT: return "LEFT"; case JUSTIFICATION_RIGHT: return "RIGHT"; case JUSTIFICATION_CENTER: return "CENTER"; default: return "UNKNOWN"; } } bool ParagraphModel::ValidFirstLine(int lmargin, int lindent, int rindent, int rmargin) const { switch (justification_) { case JUSTIFICATION_LEFT: return NearlyEqual(lmargin + lindent, margin_ + first_indent_, tolerance_); case JUSTIFICATION_RIGHT: return NearlyEqual(rmargin + rindent, margin_ + first_indent_, tolerance_); case JUSTIFICATION_CENTER: return NearlyEqual(lindent, rindent, tolerance_ * 2); default: // shouldn't happen return false; } } bool ParagraphModel::ValidBodyLine(int lmargin, int lindent, int rindent, int rmargin) const { switch (justification_) { case JUSTIFICATION_LEFT: return NearlyEqual(lmargin + lindent, margin_ + body_indent_, tolerance_); case JUSTIFICATION_RIGHT: return NearlyEqual(rmargin + rindent, margin_ + body_indent_, tolerance_); case JUSTIFICATION_CENTER: return NearlyEqual(lindent, rindent, tolerance_ * 2); default: // shouldn't happen return false; } } bool ParagraphModel::Comparable(const ParagraphModel &other) const { if (justification_ != other.justification_) { return false; } if (justification_ == JUSTIFICATION_CENTER || justification_ == JUSTIFICATION_UNKNOWN) { return true; } int tolerance = (tolerance_ + other.tolerance_) / 4; return NearlyEqual(margin_ + first_indent_, other.margin_ + other.first_indent_, tolerance) && NearlyEqual(margin_ + body_indent_, other.margin_ + other.body_indent_, tolerance); } std::string ParagraphModel::ToString() const { char buffer[200]; const char *alignment = ParagraphJustificationToString(justification_); snprintf(buffer, sizeof(buffer), "margin: %d, first_indent: %d, body_indent: %d, alignment: %s", margin_, first_indent_, body_indent_, alignment); return std::string(buffer); } } // namespace tesseract
35.840426
101
0.677649
pixelsquare
f527efe3d0d2e041fb32fa2cc6f40baf71a5efff
1,259
hpp
C++
include/TreeDS/policy/siblings.hpp
barsan-ds/generic-tree
a01ff9dc0a0e0e6dd9d380cf2469d7ea0cc86c60
[ "MIT" ]
3
2018-10-02T20:18:52.000Z
2018-10-04T20:16:45.000Z
include/TreeDS/policy/siblings.hpp
barsan-ds/tree-ds
a01ff9dc0a0e0e6dd9d380cf2469d7ea0cc86c60
[ "MIT" ]
null
null
null
include/TreeDS/policy/siblings.hpp
barsan-ds/tree-ds
a01ff9dc0a0e0e6dd9d380cf2469d7ea0cc86c60
[ "MIT" ]
null
null
null
#pragma once #include <TreeDS/policy/policy_base.hpp> namespace md::detail { template <typename NodePtr, typename NodeNavigator, typename Allocator> class siblings_impl final : public policy_base<siblings_impl<NodePtr, NodeNavigator, Allocator>, NodePtr, NodeNavigator, Allocator> { public: using policy_base<siblings_impl, NodePtr, NodeNavigator, Allocator>::policy_base; constexpr void fix_navigator_root() { if (this->current && !this->navigator.get_root()) { NodePtr parent = this->navigator.get_parent(this->current); this->navigator.set_root(parent ? parent : this->current); } } NodePtr increment_impl() { return this->navigator.get_next_sibling(this->current); } NodePtr decrement_impl() { return this->navigator.get_prev_sibling(this->current); } NodePtr go_first_impl() { return this->navigator.get_first_child(this->navigator.get_root()); } NodePtr go_last_impl() { return this->navigator.get_last_child(this->navigator.get_root()); } }; } // namespace md::detail namespace md::policy { struct siblings : detail::policy_tag<detail::siblings_impl> { // What needed is inherited }; } // namespace md::policy
28.613636
115
0.687847
barsan-ds
f52858a7b4eca2ae55b22f3d6864140a6191a4c7
265
hpp
C++
tests/headers/class_with_dtor.hpp
pcwalton/rust-bindgen
fae3dc180fef48cb806b4953bceffd7d15efe587
[ "BSD-3-Clause" ]
1,848
2018-11-22T06:08:21.000Z
2022-03-31T10:54:10.000Z
tests/headers/class_with_dtor.hpp
pcwalton/rust-bindgen
fae3dc180fef48cb806b4953bceffd7d15efe587
[ "BSD-3-Clause" ]
845
2016-06-22T21:55:20.000Z
2018-10-31T15:50:10.000Z
tests/headers/class_with_dtor.hpp
pcwalton/rust-bindgen
fae3dc180fef48cb806b4953bceffd7d15efe587
[ "BSD-3-Clause" ]
274
2018-11-23T17:46:29.000Z
2022-03-27T04:52:37.000Z
// bindgen-flags: --with-derive-hash --with-derive-partialeq --with-derive-eq template <typename T> class HandleWithDtor { T* ptr; ~HandleWithDtor() {} }; typedef HandleWithDtor<int> HandleValue; class WithoutDtor { HandleValue shouldBeWithDtor; };
17.666667
77
0.713208
pcwalton
f52ef911dad5bd6ddceed4935a551136e99cebe9
7,579
cpp
C++
data/converted/busy_0_svg.cpp
mdubb2341/EmulationStationGV
8e7ee6c93190bc8ca1879f3877184cffff530496
[ "Apache-2.0", "MIT" ]
30
2015-12-13T18:25:04.000Z
2021-03-07T11:24:31.000Z
data/converted/busy_0_svg.cpp
mdubb2341/EmulationStationGV
8e7ee6c93190bc8ca1879f3877184cffff530496
[ "Apache-2.0", "MIT" ]
46
2015-12-17T09:00:15.000Z
2018-08-27T21:02:58.000Z
data/converted/busy_0_svg.cpp
mdubb2341/EmulationStationGV
8e7ee6c93190bc8ca1879f3877184cffff530496
[ "Apache-2.0", "MIT" ]
14
2016-03-17T19:19:34.000Z
2017-06-01T03:47:21.000Z
// this file was auto-generated from "busy_0.svg" by res2h #include "../Resources.h" const uint16_t busy_0_svg_size = 1347; const uint8_t busy_0_svg_data[1347] = { 0x3c,0x3f,0x78,0x6d,0x6c,0x20,0x76,0x65,0x72,0x73, 0x69,0x6f,0x6e,0x3d,0x22,0x31,0x2e,0x30,0x22,0x20, 0x65,0x6e,0x63,0x6f,0x64,0x69,0x6e,0x67,0x3d,0x22, 0x75,0x74,0x66,0x2d,0x38,0x22,0x3f,0x3e,0x0a,0x3c, 0x21,0x2d,0x2d,0x20,0x47,0x65,0x6e,0x65,0x72,0x61, 0x74,0x6f,0x72,0x3a,0x20,0x41,0x64,0x6f,0x62,0x65, 0x20,0x49,0x6c,0x6c,0x75,0x73,0x74,0x72,0x61,0x74, 0x6f,0x72,0x20,0x31,0x36,0x2e,0x30,0x2e,0x33,0x2c, 0x20,0x53,0x56,0x47,0x20,0x45,0x78,0x70,0x6f,0x72, 0x74,0x20,0x50,0x6c,0x75,0x67,0x2d,0x49,0x6e,0x20, 0x2e,0x20,0x53,0x56,0x47,0x20,0x56,0x65,0x72,0x73, 0x69,0x6f,0x6e,0x3a,0x20,0x36,0x2e,0x30,0x30,0x20, 0x42,0x75,0x69,0x6c,0x64,0x20,0x30,0x29,0x20,0x20, 0x2d,0x2d,0x3e,0x0a,0x3c,0x21,0x44,0x4f,0x43,0x54, 0x59,0x50,0x45,0x20,0x73,0x76,0x67,0x20,0x50,0x55, 0x42,0x4c,0x49,0x43,0x20,0x22,0x2d,0x2f,0x2f,0x57, 0x33,0x43,0x2f,0x2f,0x44,0x54,0x44,0x20,0x53,0x56, 0x47,0x20,0x31,0x2e,0x31,0x2f,0x2f,0x45,0x4e,0x22, 0x20,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77, 0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,0x72,0x67,0x2f, 0x47,0x72,0x61,0x70,0x68,0x69,0x63,0x73,0x2f,0x53, 0x56,0x47,0x2f,0x31,0x2e,0x31,0x2f,0x44,0x54,0x44, 0x2f,0x73,0x76,0x67,0x31,0x31,0x2e,0x64,0x74,0x64, 0x22,0x3e,0x0a,0x3c,0x73,0x76,0x67,0x20,0x76,0x65, 0x72,0x73,0x69,0x6f,0x6e,0x3d,0x22,0x31,0x2e,0x31, 0x22,0x20,0x69,0x64,0x3d,0x22,0x45,0x62,0x65,0x6e, 0x65,0x5f,0x31,0x22,0x20,0x78,0x6d,0x6c,0x6e,0x73, 0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77, 0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,0x72,0x67,0x2f, 0x32,0x30,0x30,0x30,0x2f,0x73,0x76,0x67,0x22,0x20, 0x78,0x6d,0x6c,0x6e,0x73,0x3a,0x78,0x6c,0x69,0x6e, 0x6b,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f, 0x77,0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,0x72,0x67, 0x2f,0x31,0x39,0x39,0x39,0x2f,0x78,0x6c,0x69,0x6e, 0x6b,0x22,0x20,0x78,0x3d,0x22,0x30,0x70,0x78,0x22, 0x20,0x79,0x3d,0x22,0x30,0x70,0x78,0x22,0x0a,0x09, 0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22,0x32,0x31, 0x2e,0x30,0x30,0x32,0x70,0x78,0x22,0x20,0x68,0x65, 0x69,0x67,0x68,0x74,0x3d,0x22,0x32,0x32,0x2e,0x30, 0x30,0x32,0x70,0x78,0x22,0x20,0x76,0x69,0x65,0x77, 0x42,0x6f,0x78,0x3d,0x22,0x30,0x20,0x30,0x20,0x32, 0x31,0x2e,0x30,0x30,0x32,0x20,0x32,0x32,0x2e,0x30, 0x30,0x32,0x22,0x20,0x65,0x6e,0x61,0x62,0x6c,0x65, 0x2d,0x62,0x61,0x63,0x6b,0x67,0x72,0x6f,0x75,0x6e, 0x64,0x3d,0x22,0x6e,0x65,0x77,0x20,0x30,0x20,0x30, 0x20,0x32,0x31,0x2e,0x30,0x30,0x32,0x20,0x32,0x32, 0x2e,0x30,0x30,0x32,0x22,0x20,0x78,0x6d,0x6c,0x3a, 0x73,0x70,0x61,0x63,0x65,0x3d,0x22,0x70,0x72,0x65, 0x73,0x65,0x72,0x76,0x65,0x22,0x3e,0x0a,0x3c,0x67, 0x20,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3d,0x22, 0x30,0x2e,0x35,0x22,0x3e,0x0a,0x09,0x3c,0x70,0x61, 0x74,0x68,0x20,0x66,0x69,0x6c,0x6c,0x3d,0x22,0x23, 0x37,0x37,0x37,0x37,0x37,0x37,0x22,0x20,0x64,0x3d, 0x22,0x4d,0x32,0x31,0x2e,0x30,0x30,0x32,0x2c,0x32, 0x31,0x2e,0x32,0x39,0x33,0x63,0x30,0x2c,0x30,0x2e, 0x33,0x39,0x2d,0x30,0x2e,0x33,0x31,0x39,0x2c,0x30, 0x2e,0x37,0x30,0x39,0x2d,0x30,0x2e,0x37,0x30,0x39, 0x2c,0x30,0x2e,0x37,0x30,0x39,0x68,0x2d,0x37,0x2e, 0x39,0x33,0x37,0x63,0x2d,0x30,0x2e,0x33,0x39,0x2c, 0x30,0x2d,0x30,0x2e,0x37,0x30,0x39,0x2d,0x30,0x2e, 0x33,0x31,0x39,0x2d,0x30,0x2e,0x37,0x30,0x39,0x2d, 0x30,0x2e,0x37,0x30,0x39,0x76,0x2d,0x38,0x2e,0x33, 0x37,0x39,0x0a,0x09,0x09,0x63,0x30,0x2d,0x30,0x2e, 0x33,0x39,0x2c,0x30,0x2e,0x33,0x31,0x39,0x2d,0x30, 0x2e,0x37,0x30,0x39,0x2c,0x30,0x2e,0x37,0x30,0x39, 0x2d,0x30,0x2e,0x37,0x30,0x39,0x68,0x37,0x2e,0x39, 0x33,0x37,0x63,0x30,0x2e,0x33,0x39,0x2c,0x30,0x2c, 0x30,0x2e,0x37,0x30,0x39,0x2c,0x30,0x2e,0x33,0x31, 0x39,0x2c,0x30,0x2e,0x37,0x30,0x39,0x2c,0x30,0x2e, 0x37,0x30,0x39,0x56,0x32,0x31,0x2e,0x32,0x39,0x33, 0x7a,0x22,0x2f,0x3e,0x0a,0x3c,0x2f,0x67,0x3e,0x0a, 0x3c,0x67,0x20,0x6f,0x70,0x61,0x63,0x69,0x74,0x79, 0x3d,0x22,0x30,0x2e,0x35,0x22,0x3e,0x0a,0x09,0x3c, 0x70,0x61,0x74,0x68,0x20,0x66,0x69,0x6c,0x6c,0x3d, 0x22,0x23,0x37,0x37,0x37,0x37,0x37,0x37,0x22,0x20, 0x64,0x3d,0x22,0x4d,0x32,0x31,0x2e,0x30,0x30,0x32, 0x2c,0x39,0x2e,0x30,0x38,0x38,0x63,0x30,0x2c,0x30, 0x2e,0x33,0x39,0x2d,0x30,0x2e,0x33,0x31,0x39,0x2c, 0x30,0x2e,0x37,0x30,0x38,0x2d,0x30,0x2e,0x37,0x30, 0x39,0x2c,0x30,0x2e,0x37,0x30,0x38,0x68,0x2d,0x37, 0x2e,0x39,0x33,0x37,0x63,0x2d,0x30,0x2e,0x33,0x39, 0x2c,0x30,0x2d,0x30,0x2e,0x37,0x30,0x39,0x2d,0x30, 0x2e,0x33,0x31,0x39,0x2d,0x30,0x2e,0x37,0x30,0x39, 0x2d,0x30,0x2e,0x37,0x30,0x38,0x56,0x30,0x2e,0x37, 0x30,0x38,0x0a,0x09,0x09,0x63,0x30,0x2d,0x30,0x2e, 0x33,0x39,0x2c,0x30,0x2e,0x33,0x31,0x39,0x2d,0x30, 0x2e,0x37,0x30,0x38,0x2c,0x30,0x2e,0x37,0x30,0x39, 0x2d,0x30,0x2e,0x37,0x30,0x38,0x68,0x37,0x2e,0x39, 0x33,0x37,0x63,0x30,0x2e,0x33,0x39,0x2c,0x30,0x2c, 0x30,0x2e,0x37,0x30,0x39,0x2c,0x30,0x2e,0x33,0x31, 0x39,0x2c,0x30,0x2e,0x37,0x30,0x39,0x2c,0x30,0x2e, 0x37,0x30,0x38,0x56,0x39,0x2e,0x30,0x38,0x38,0x7a, 0x22,0x2f,0x3e,0x0a,0x3c,0x2f,0x67,0x3e,0x0a,0x3c, 0x67,0x20,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3d, 0x22,0x30,0x2e,0x35,0x22,0x3e,0x0a,0x09,0x3c,0x70, 0x61,0x74,0x68,0x20,0x66,0x69,0x6c,0x6c,0x3d,0x22, 0x23,0x37,0x37,0x37,0x37,0x37,0x37,0x22,0x20,0x64, 0x3d,0x22,0x4d,0x39,0x2e,0x33,0x35,0x34,0x2c,0x32, 0x31,0x2e,0x32,0x39,0x33,0x63,0x30,0x2c,0x30,0x2e, 0x33,0x39,0x2d,0x30,0x2e,0x33,0x31,0x39,0x2c,0x30, 0x2e,0x37,0x30,0x39,0x2d,0x30,0x2e,0x37,0x30,0x38, 0x2c,0x30,0x2e,0x37,0x30,0x39,0x48,0x30,0x2e,0x37, 0x30,0x38,0x43,0x30,0x2e,0x33,0x31,0x39,0x2c,0x32, 0x32,0x2e,0x30,0x30,0x32,0x2c,0x30,0x2c,0x32,0x31, 0x2e,0x36,0x38,0x33,0x2c,0x30,0x2c,0x32,0x31,0x2e, 0x32,0x39,0x33,0x76,0x2d,0x38,0x2e,0x33,0x37,0x39, 0x0a,0x09,0x09,0x63,0x30,0x2d,0x30,0x2e,0x33,0x39, 0x2c,0x30,0x2e,0x33,0x31,0x39,0x2d,0x30,0x2e,0x37, 0x30,0x39,0x2c,0x30,0x2e,0x37,0x30,0x38,0x2d,0x30, 0x2e,0x37,0x30,0x39,0x68,0x37,0x2e,0x39,0x33,0x38, 0x63,0x30,0x2e,0x33,0x39,0x2c,0x30,0x2c,0x30,0x2e, 0x37,0x30,0x38,0x2c,0x30,0x2e,0x33,0x31,0x39,0x2c, 0x30,0x2e,0x37,0x30,0x38,0x2c,0x30,0x2e,0x37,0x30, 0x39,0x56,0x32,0x31,0x2e,0x32,0x39,0x33,0x7a,0x22, 0x2f,0x3e,0x0a,0x3c,0x2f,0x67,0x3e,0x0a,0x3c,0x67, 0x3e,0x0a,0x09,0x3c,0x70,0x61,0x74,0x68,0x20,0x66, 0x69,0x6c,0x6c,0x3d,0x22,0x23,0x37,0x37,0x37,0x37, 0x37,0x37,0x22,0x20,0x64,0x3d,0x22,0x4d,0x39,0x2e, 0x33,0x35,0x34,0x2c,0x39,0x2e,0x30,0x38,0x37,0x63, 0x30,0x2c,0x30,0x2e,0x33,0x39,0x2d,0x30,0x2e,0x33, 0x31,0x39,0x2c,0x30,0x2e,0x37,0x30,0x38,0x2d,0x30, 0x2e,0x37,0x30,0x38,0x2c,0x30,0x2e,0x37,0x30,0x38, 0x48,0x30,0x2e,0x37,0x30,0x38,0x43,0x30,0x2e,0x33, 0x31,0x39,0x2c,0x39,0x2e,0x37,0x39,0x36,0x2c,0x30, 0x2c,0x39,0x2e,0x34,0x37,0x37,0x2c,0x30,0x2c,0x39, 0x2e,0x30,0x38,0x37,0x56,0x30,0x2e,0x37,0x30,0x38, 0x0a,0x09,0x09,0x43,0x30,0x2c,0x30,0x2e,0x33,0x31, 0x39,0x2c,0x30,0x2e,0x33,0x31,0x39,0x2c,0x30,0x2c, 0x30,0x2e,0x37,0x30,0x38,0x2c,0x30,0x68,0x37,0x2e, 0x39,0x33,0x38,0x63,0x30,0x2e,0x33,0x39,0x2c,0x30, 0x2c,0x30,0x2e,0x37,0x30,0x38,0x2c,0x30,0x2e,0x33, 0x31,0x39,0x2c,0x30,0x2e,0x37,0x30,0x38,0x2c,0x30, 0x2e,0x37,0x30,0x38,0x56,0x39,0x2e,0x30,0x38,0x37, 0x7a,0x22,0x2f,0x3e,0x0a,0x3c,0x2f,0x67,0x3e,0x0a, 0x3c,0x2f,0x73,0x76,0x67,0x3e,0x0a };
52.631944
58
0.727273
mdubb2341
f5316e58bab4b97f023c9871b45ecc5d281d685a
2,273
cpp
C++
Frontend/GItems/Mini/RUKeyUp.cpp
Gattic/gfxplusplus
f0c05a0f424fd65c8f7fd26ee0dee1802a033336
[ "MIT" ]
3
2020-02-12T23:22:45.000Z
2020-02-19T01:03:07.000Z
Frontend/GItems/Mini/RUKeyUp.cpp
MeeseeksLookAtMe/gfxplusplus
f0c05a0f424fd65c8f7fd26ee0dee1802a033336
[ "MIT" ]
null
null
null
Frontend/GItems/Mini/RUKeyUp.cpp
MeeseeksLookAtMe/gfxplusplus
f0c05a0f424fd65c8f7fd26ee0dee1802a033336
[ "MIT" ]
null
null
null
// Copyright 2020 Robert Carneiro, Derek Meer, Matthew Tabak, Eric Lujan // // 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 "RUKeyUp.h" #include "../../GFXUtilities/EventTracker.h" #include "../../GUI/Text/RUTextComponent.h" #include "../../Graphics/graphics.h" #include "../GItem.h" RUKeyUp::RUKeyUp() { // event listeners KeyUpListener = GeneralListener(); } RUKeyUp::~RUKeyUp() { // event listeners KeyUpListener = GeneralListener(); } void RUKeyUp::setKeyUpListener(GeneralListener f) { KeyUpListener = f; } void RUKeyUp::onKeyUpHelper(gfxpp* cGfx, EventTracker* eventsStatus, GPanel* cPanel, SDL_Keycode keyPressed, Uint16 keyModPressed) { if (!cGfx) return; if (!eventsStatus) return; if (!cPanel) return; if (!visible) return; GItem* cItem = dynamic_cast<GItem*>(this); if (!(cGfx->focusedItem == cItem)) return; // Render the GUI object drawUpdate = true; // pass on the event onKeyUp(cGfx, cPanel, keyPressed, keyModPressed); // Call the callback we saved KeyUpListener.call(cItem->getName()); } void RUKeyUp::onKeyUp(gfxpp* cGfx, GPanel* cPanel, SDL_Keycode keyPressed, Uint16 keyModPressed) { // printf("RUKeyUp: "); }
31.136986
101
0.714474
Gattic
f532819a10ab366e07177a187bed928822559df6
1,200
cpp
C++
demo/tuple.cpp
divad1196/CPPTools
9526708469ed899fd8f73dc8ad32eeb4bee8e05c
[ "MIT" ]
1
2021-06-15T09:25:31.000Z
2021-06-15T09:25:31.000Z
demo/tuple.cpp
divad1196/CPPTools
9526708469ed899fd8f73dc8ad32eeb4bee8e05c
[ "MIT" ]
null
null
null
demo/tuple.cpp
divad1196/CPPTools
9526708469ed899fd8f73dc8ad32eeb4bee8e05c
[ "MIT" ]
1
2022-01-07T19:09:55.000Z
2022-01-07T19:09:55.000Z
#include <cstdlib> #include <iostream> #include "../src/tuple.h" int main(int argc, char* argv[]) { auto a = std::index_sequence<1,4,5>(); auto b = cond_extends<true, 3>(a); auto c = cond_extends<false, 3>(a); std::tuple<int, int> d{}; auto e = extends(d, std::string("hello"), 5.6); auto f = cond_extends<true>(d, std::string("hello"), 5.6); auto g = cond_extends<false>(d, std::string("hello"), 5.6); print_tuple(d); print_tuple(e); print_tuple(f); print_tuple(g); auto x = std::make_tuple(3, 4, std::string("foo"), 5, 6, std::string("bar")); auto seq = cond_index_seq<std::is_integral>(x); auto sub = extract(x, seq); auto sub2 = cond_extract<std::is_integral>(x); print_tuple(x); print_tuple(sub); print_tuple(sub2); const auto& [i, j, k] = extract<1, 2, 5>(x); std::cout << i << " - " << j << " + " << k << std::endl; std::get<1>(x) += 3; std::cout << i << " - " << j << " + " << k << std::endl; auto m = extract<1, 2, 5>(x); auto n = slice<1, 2, 5>(x); print_tuple(m); print_tuple(n); std::get<1>(x) += 3; print_tuple(m); print_tuple(n); return EXIT_SUCCESS; }
24.489796
81
0.545833
divad1196
f536953e03a417a52b8bef7a7e4bfbbc47c393c6
605
cpp
C++
VosVideo.Common/AutoResetEvent.cpp
atelyshev/vosvideoserver
689e6b2a49ee253528903b93011e3d16af1fa74b
[ "MIT" ]
19
2017-11-24T05:18:27.000Z
2021-06-25T19:34:17.000Z
VosVideo.Common/AutoResetEvent.cpp
atelyshev/vosvideoserver
689e6b2a49ee253528903b93011e3d16af1fa74b
[ "MIT" ]
null
null
null
VosVideo.Common/AutoResetEvent.cpp
atelyshev/vosvideoserver
689e6b2a49ee253528903b93011e3d16af1fa74b
[ "MIT" ]
9
2017-10-02T03:42:49.000Z
2020-09-17T07:59:04.000Z
#include "stdafx.h" #include "AutoResetEvent.h" using namespace threading; AutoResetEvent::AutoResetEvent(bool initial) : flag_(initial) { } void AutoResetEvent::Set() { std::lock_guard<std::mutex> _(protect_); flag_ = true; signal_.notify_one(); } void AutoResetEvent::Reset() { std::lock_guard<std::mutex> _(protect_); flag_ = false; } bool AutoResetEvent::WaitOne() { std::unique_lock<std::mutex> lk(protect_); while( !flag_ ) // prevent spurious wakeups from doing harm { signal_.wait(lk); } flag_ = false; // waiting resets the flag return true; }
17.794118
61
0.669421
atelyshev
f53a2d93891ac72d7feeda17a9666e5e6ee613b0
22,088
cpp
C++
src/libshit/options.cpp
u3shit/libshit
8ab8f12b4068edc269356debef78cd04de67edb4
[ "WTFPL", "BSD-3-Clause" ]
null
null
null
src/libshit/options.cpp
u3shit/libshit
8ab8f12b4068edc269356debef78cd04de67edb4
[ "WTFPL", "BSD-3-Clause" ]
null
null
null
src/libshit/options.cpp
u3shit/libshit
8ab8f12b4068edc269356debef78cd04de67edb4
[ "WTFPL", "BSD-3-Clause" ]
null
null
null
#include "libshit/options.hpp" #include <algorithm> #include <array> #include <climits> #include <cstring> #include <iostream> #include <iterator> #include <map> #include <string> #include <type_traits> #include "libshit/doctest.hpp" namespace Libshit { TEST_SUITE_BEGIN("Libshit::Options"); namespace { struct TestFixture { std::stringstream ss; OptionParser parser; TestFixture() { parser.SetOstream(ss); } void Run(int& argc, const char** argv, bool val) { try { parser.Run(argc, argv); FAIL("Expected parser to throw Exit, but didn't throw anything"); } catch (const Exit& exit) { CHECK(exit.success == val); } } }; } #define CHECK_STREQ(a_, b_) \ do \ { \ const char* a = a_, * b = b_; \ if (a == nullptr || b == nullptr) \ CHECK(a == b); \ else \ { \ CAPTURE(a); CAPTURE(b); \ FAST_CHECK_EQ(strcmp(a, b), 0); \ } \ } \ while (0) OptionGroup::OptionGroup( OptionParser& parser, const char* name, const char* help) : name{name}, help{help} { parser.AddOptionGroup(*this); } OptionGroup& OptionGroup::GetCommands() { static OptionGroup inst{OptionParser::GetGlobal(), "Commands", "You can only specify one of these. " "Run \"--<command> --help\" for details\n"}; return inst; } OptionGroup& OptionGroup::GetTesting() { static OptionGroup inst{OptionParser::GetGlobal(), "Testing options"}; return inst; } Option::ArgVector ArgsToVector(int argc, const char** argv) { std::vector<const char*> res; res.reserve(argc); for (int i = 0; i < argc; ++i) res.push_back(argv[i]); return res; } TEST_CASE("ArgsToVector") { const char* argv[] = { "foo", "bar", "asd", nullptr }; auto v = ArgsToVector(3, argv); REQUIRE(v.size() == 3); CHECK_STREQ(v[0], "foo"); CHECK_STREQ(v[1], "bar"); CHECK_STREQ(v[2], "asd"); } OptionParser::OptionParser() : help_version{*this, "General options"}, help_option{ help_version, "help", 'h', 0, nullptr, "Show this help message", [this](auto&, auto&&) { this->ShowHelp(); throw Exit{true}; }}, version_option{ help_version, "version", 0, nullptr, "Show program version", [this](auto&, auto&&) { *os << version << std::endl; throw Exit{true}; }}, os{&std::clog} { version_option.enabled = false; } void OptionParser::SetVersion(const char* version_str) { version = version_str; version_option.enabled = true; } TEST_CASE_FIXTURE(TestFixture, "version displaying") { parser.SetVersion("Foo program bar"); int argc = 2; const char* argv[] = { "foo", "--help", nullptr }; SUBCASE("help message") { Run(argc, argv, true); CHECK(ss.str() == "Foo program bar\n" "\n" "General options:\n" " -h --help\n" "\tShow this help message\n" " --version\n" "\tShow program version\n"); } SUBCASE("version display") { argv[1] = "--ver"; Run(argc, argv, true); CHECK(ss.str() == "Foo program bar\n"); } } TEST_CASE_FIXTURE(TestFixture, "usage displaying") { parser.SetUsage("[--options] [bar...]"); int argc = 2; const char* argv[] = { "foo", "--help", nullptr }; Run(argc, argv, true); CHECK(ss.str() == "Usage:\n" "\tfoo [--options] [bar...]\n" "\n" "General options:\n" " -h --help\n" "\tShow this help message\n"); } void OptionParser::FailOnNonArg() { non_arg_fun = [](auto) { throw InvalidParam{"Invalid option"}; }; } namespace { struct OptCmp { bool operator()(const char* a, const char* b) const { while (*a && *a == *b) ++a, ++b; if (*a == '=' || *b == '=') return false; return *reinterpret_cast<const unsigned char*>(a) < *reinterpret_cast<const unsigned char*>(b); } }; } static size_t ParseShort( OptionParser& parser, const std::array<Option*, 256>& short_opts, size_t argc, size_t i, const char** argv) { auto ptr = argv[i]; return AddInfo([&]() -> size_t { while (*++ptr) { auto opt = short_opts[static_cast<unsigned char>(*ptr)]; if (!opt) throw InvalidParam{"Unknown option"}; std::vector<const char*> args; if (opt->args_count == Option::ALL_ARGS) { args.reserve(argc-i); if (ptr[1]) args.push_back(ptr+1); std::copy(argv+i+1, argv+argc, std::back_inserter(args)); opt->func(parser, Move(args)); return argc - i - 1; } if (opt->args_count) { auto count = opt->args_count; args.reserve(count); if (ptr[1]) { args.push_back(ptr+1); --count; } ++i; for (size_t j = 0; j < count; ++j) { if (i+j >= argc) throw InvalidParam{"Not enough arguments"}; args.push_back(argv[i+j]); } opt->func(parser, Move(args)); return count; } opt->func(parser, Move(args)); } return 0; }, [&](auto& e) { AddInfos(e, "Processed option", std::string{'-', *ptr}); }); } static size_t ParseLong( OptionParser& parser, const std::map<const char*, Option*, OptCmp>& long_opts, size_t argc, size_t i, const char** argv) { auto arg = strchr(argv[i]+2, '='); auto len = arg ? arg - argv[i] - 2 : strlen(argv[i]+2); auto it = long_opts.lower_bound(argv[i]+2); if (it == long_opts.end() || strncmp(argv[i]+2, it->first, len)) throw InvalidParam{"Unknown option"}; if (std::next(it) != long_opts.end() && it->first[len] != '\0' && // exact matches are non ambiguous strncmp(argv[i]+2, std::next(it)->first, len) == 0) { std::stringstream ss; ss << "Ambiguous option (candidates:"; for (; it != long_opts.end() && strncmp(argv[i]+2, it->first, len) == 0; ++it) ss << " --" << it->first; ss << ")"; throw InvalidParam{ss.str()}; } auto opt = it->second; auto count = opt->args_count; std::vector<const char*> args; if (count == Option::ALL_ARGS) { args.reserve(argc-i); if (arg) args.push_back(arg+1); std::copy(argv+i+1, argv+argc, std::back_inserter(args)); opt->func(parser, Move(args)); return argc - i - 1; } args.reserve(count); if (arg) if (opt->args_count == 0) throw InvalidParam{"Option doesn't take arguments"}; else { args.push_back(arg+1); --count; } ++i; for (size_t j = 0; j < count; ++j) { if (i+j >= argc) throw InvalidParam{"Not enough arguments"}; args.push_back(argv[i+j]); } opt->func(parser, Move(args)); return count; } void OptionParser::Run_(int& argc, const char** argv, bool has_argv0) { if (has_argv0) argv0 = argv[0]; int endp = has_argv0; if (argc == has_argv0) { if (no_opts_help || (validate_fun && !validate_fun(argc, argv))) { ShowHelp(); throw Exit{false}; } else return; } std::array<Option*, 256> short_opts; static_assert(CHAR_BIT == 8); std::map<const char*, Option*, OptCmp> long_opts; std::size_t old_len = 0; auto gen_opts = [&]() { if (old_len == groups.size()) return; old_len = groups.size(); short_opts = {}; long_opts.clear(); for (auto g : groups) for (auto o : g->GetOptions()) { if (!o->enabled) continue; if (o->short_name) { if (short_opts[static_cast<unsigned char>(o->short_name)]) LIBSHIT_THROW(std::logic_error, "Duplicate short option"); short_opts[static_cast<unsigned char>(o->short_name)] = o; } auto x = long_opts.emplace(o->name, o); if (!x.second) LIBSHIT_THROW(std::logic_error, "Duplicate long option"); } }; for (int i = has_argv0; i < argc; ++i) { // option: "--"something, "-"something // non option: something, "-" // special: "--" // non option if (argv[i][0] != '-' || (argv[i][0] == '-' && argv[i][1] == '\0')) { if (non_arg_fun) non_arg_fun(argv[i]); else argv[endp++] = argv[i]; } else { gen_opts(); if (argv[i][1] != '-') // short i += ParseShort(*this, short_opts, argc, i, argv); else if (argv[i][1] == '-' && argv[i][2] != '\0') // long i += AddInfo( [&] { return ParseLong(*this, long_opts, argc, i, argv); }, [=](auto& e) { AddInfos(e, "Processed option", argv[i]); }); else // --: end of args { if (non_arg_fun) for (++i; i < argc; ++i) non_arg_fun(argv[i]); else for (++i; i < argc; ++i) argv[endp++] = argv[i]; break; } } } argc = endp; argv[argc] = nullptr; if (validate_fun && !validate_fun(argc, argv)) { ShowHelp(); throw Exit{false}; } } void OptionParser::Run(int& argc, const char** argv, bool has_argv0) { try { Run_(argc, argv, has_argv0); } catch (const InvalidParam& p) { *os << p["Processed option"] << ": " << p.what() << std::endl; throw Exit{false}; } } void OptionParser::Run(Option::ArgVector& args, bool has_argv0) { int size = args.size(); AtScopeExit x{[&]() { args.resize(size); }}; args.push_back(nullptr); try { Run_(size, args.data(), has_argv0); } catch (const InvalidParam& p) { *os << p["Processed option"] << ": " << p.what() << std::endl; throw Exit{false}; } } void OptionParser::ShowHelp() const { if (version) *os << version << "\n\n"; if (usage) *os << "Usage:\n\t" << argv0 << " " << usage << "\n\n"; for (auto g : groups) { if (g != groups[0]) *os << '\n'; *os << g->GetName() << ":\n"; if (g->GetHelp()) *os << g->GetHelp() << '\n'; for (auto o : g->GetOptions()) { if (!o->enabled) continue; if (o->short_name) *os << " -" << o->short_name; else *os << " "; *os << " --" << o->name; if (o->args_help) *os << '=' << o->args_help; *os << '\n'; if (o->help) *os << '\t' << o->help << '\n'; } } } void OptionParser::CommandTriggered() { if (was_command) throw InvalidParam{"Multiple commands specified"}; was_command = true; } TEST_CASE_FIXTURE(TestFixture, "basic option parsing") { OptionGroup grp{parser, "Foo", "Description of foo"}; bool b1 = false, b2 = false; const char* b3 = nullptr, *b40 = nullptr, *b41 = nullptr; Option test1{grp, "test-1", 't', 0, nullptr, "foo", [&](auto&, auto&&){ b1 = true; }}; Option test2{grp, "test-2", 'T', 0, nullptr, "bar", [&](auto&, auto&&){ b2 = true; }}; Option test3{grp, "test-3", 1, "STRING", "Blahblah", [&](auto&, auto&& v){ REQUIRE(v.size() == 1); b3 = v[0]; }}; Option test4{grp, "test-4", 'c', 2, "FOO BAR", nullptr, [&](auto&, auto&& v){ REQUIRE(v.size() == 2); b40 = v[0]; b41 = v[1]; }}; bool e1 = false, e2 = false; const char* e3 = nullptr, *e40 = nullptr, *e41 = nullptr; const char* help_text = "General options:\n" " -h --help\n" "\tShow this help message\n" "\n" "Foo:\n" "Description of foo\n" " -t --test-1\n" "\tfoo\n" " -T --test-2\n" "\tbar\n" " --test-3=STRING\n" "\tBlahblah\n" " -c --test-4=FOO BAR\n"; int argc = 2; const char* argv[10] = { "foo" }; SUBCASE("success") { SUBCASE("single option") { argv[1] = "--test-2"; parser.Run(argc, argv); e2 = true; } SUBCASE("multiple options") { argc = 4; argv[1] = "--test-2"; argv[2] = "--test-1"; argv[3] = "--test-2"; parser.Run(argc, argv); e1 = e2 = true; } SUBCASE("argument options") { SUBCASE("= arguments") { argc = 4; argv[1] = "--test-4=xx"; argv[2] = "yy"; argv[3] = "--test-3=foo"; } SUBCASE("separate argument options") { argc = 6; argv[1] = "--test-4"; argv[2] = "xx"; argv[3] = "yy"; argv[4] = "--test-3"; argv[5] = "foo"; } parser.Run(argc, argv); e3 = "foo"; e40 = "xx"; e41 = "yy"; } SUBCASE("short argument") { argv[1] = "-t"; parser.Run(argc, argv); e1 = true; } SUBCASE("short arguments concat") { argv[1] = "-tT"; parser.Run(argc, argv); e1 = e2 = true; } SUBCASE("short arguments parameter") { SUBCASE("normal") { argc = 4; argv[1] = "-tc"; argv[2] = "abc"; argv[3] = "def"; } SUBCASE("concat") { argc = 3; argv[1] = "-tcabc"; argv[2] = "def"; } parser.Run(argc, argv); e1 = true; e40 = "abc"; e41 = "def"; } REQUIRE(argc == 1); CHECK_STREQ(argv[0], "foo"); CHECK_STREQ(argv[1], nullptr); } SUBCASE("unused args") { argc = 5; argv[1] = "--test-1"; argv[2] = "foopar"; argv[3] = "barpar"; argv[4] = "-T"; parser.Run(argc, argv); e1 = e2 = true; REQUIRE(argc == 3); CHECK_STREQ(argv[0], "foo"); CHECK_STREQ(argv[1], "foopar"); CHECK_STREQ(argv[2], "barpar"); } SUBCASE("unused -- teminating") { argc = 4; argv[1] = "-t"; argv[2] = "--"; argv[3] = "-T"; parser.Run(argc, argv); e1 = true; REQUIRE(argc == 2); CHECK_STREQ(argv[0], "foo"); CHECK_STREQ(argv[1], "-T"); CHECK_STREQ(argv[2], nullptr); } SUBCASE("unused handler") { argc = 6; argv[1] = "-t"; argv[2] = "foopar"; argv[3] = "-T"; argv[4] = "--"; argv[5] = "--help"; std::vector<const char*> vec; parser.SetNonArgHandler([&](auto x) { vec.push_back(x); }); parser.Run(argc, argv); e1 = e2 = true; CHECK(vec == (std::vector<const char*>{"foopar", "--help"})); REQUIRE(argc == 1); CHECK_STREQ(argv[0], "foo"); CHECK_STREQ(argv[1], nullptr); } SUBCASE("validator") { argc = 6; argv[1] = "foo"; argv[2] = "-t"; argv[3] = "bar"; argv[4] = "--"; argv[5] = "-t"; e1 = true; bool valid; SUBCASE("valid") { valid = true; } SUBCASE("invalid") { valid = false; } parser.SetValidateFun( [valid](int argc, const char** argv) { REQUIRE(argc == 4); CHECK_STREQ(argv[0], "foo"); CHECK_STREQ(argv[1], "foo"); CHECK_STREQ(argv[2], "bar"); CHECK_STREQ(argv[3], "-t"); return valid; }); if (valid) { parser.Run(argc, argv); CHECK(ss.str() == ""); } else { Run(argc, argv, false); CHECK(ss.str() == help_text); } } SUBCASE("empty args") { argc = 1; parser.Run(argc, argv); REQUIRE(argc == 1); CHECK_STREQ(argv[0], "foo"); CHECK_STREQ(argv[1], nullptr); } SUBCASE("empty show help") { argc = 1; parser.SetShowHelpOnNoOptions(); Run(argc, argv, false); CHECK(ss.str() == help_text); } SUBCASE("show help") { SUBCASE("normal") { argv[1] = "--help"; } SUBCASE("abbrev") { argv[1] = "--he"; } Run(argc, argv, true); CHECK(ss.str() == help_text); } SUBCASE("ambiguous option") { argv[1] = "--test"; Run(argc, argv, false); CHECK(ss.str() == "--test: Ambiguous option (candidates: --test-1 --test-2 --test-3 --test-4)\n"); } SUBCASE("ambiguous option with params") { argv[1] = "--test=foo"; Run(argc, argv, false); CHECK(ss.str() == "--test=foo: Ambiguous option (candidates: --test-1 --test-2 --test-3 --test-4)\n"); } SUBCASE("unknown option") { argv[1] = "--foo"; Run(argc, argv, false); CHECK(ss.str() == "--foo: Unknown option\n"); } SUBCASE("unknown short option") { argv[1] = "-x"; Run(argc, argv, false); CHECK(ss.str() == "-x: Unknown option\n"); } CHECK(b1 == e1); CHECK(b2 == e2); CHECK_STREQ(b3, e3); CHECK_STREQ(b40, e40); CHECK_STREQ(b41, e41); } TEST_CASE_FIXTURE(TestFixture, "non-unique prefix") { OptionGroup grp{parser, "Foo", "Description of foo"}; bool b1 = false, b2 = false; Option test1{grp, "foo", 0, nullptr, "foo", [&](auto&, auto&&){ b1 = true; }}; Option test2{grp, "foo-bar", 0, nullptr, "bar", [&](auto&, auto&&){ b2 = true; }}; int argc = 2; const char* argv[] = { "foo", "--foo", nullptr }; parser.Run(argc, argv); CHECK(ss.str() == ""); CHECK(b1 == true); CHECK(b2 == false); } TEST_CASE_FIXTURE(TestFixture, "non-unique prefix with options") { OptionGroup grp{parser, "Foo", "Description of foo"}; const char* b1 = nullptr; bool b2 = false; Option test1{grp, "foo", 1, nullptr, "foo", [&](auto&, auto&& a){ b1 = a.front(); }}; Option test2{grp, "foo-bar", 0, nullptr, "bar", [&](auto&, auto&&){ b2 = true; }}; int argc; const char* argv[4] = {"foo"}; SUBCASE("space separated") { argc = 3; argv[1] = "--foo"; argv[2] = "bar"; } SUBCASE("= separated") { argc = 2; argv[1] = "--foo=bar"; } parser.Run(argc, argv); CHECK(ss.str() == ""); CHECK_STREQ(b1, "bar"); CHECK(b2 == false); } TEST_CASE_FIXTURE(TestFixture, "command like usage") { parser.FailOnNonArg(); OptionGroup grp{parser, "Commands"}; bool b1x = false, b1y = false, b2x = false; OptionGroup cmd1_grp{"Command 1 shit"}; Option cmd1_x{cmd1_grp, "foo", 0, nullptr, "foo", [&](auto&, auto&&) { b1x = true; }}; Option cmd1_y{cmd1_grp, "bar", 0, nullptr, "baz", [&](auto&, auto&&) { b1y = true; }}; Option cmd1{grp, "cmd1", 0, nullptr, "cmd1", [&](OptionParser& p, auto&& args) { CHECK(&p == &parser); CHECK(args.size() == 0); p.CommandTriggered(); p.AddOptionGroup(cmd1_grp); }}; OptionGroup cmd2_grp{"Command 2 shit"}; Option cmd2_x{cmd2_grp, "foo", 0, nullptr, "foo2", [&](auto&, auto&&) { b2x = true; }}; bool was_validator = false; Option cmd2{grp, "cmd2", 0, nullptr, "cmd2", [&](OptionParser& p, auto&&) { p.CommandTriggered(); p.AddOptionGroup(cmd2_grp); p.SetNonArgHandler({}); p.SetValidateFun([&](int argc, const char** argv) { was_validator = true; CHECK(argc == 2); CHECK_STREQ(argv[0], "cmd_name"); CHECK_STREQ(argv[1], "booboo"); return true; }); }}; int argc = 1; const char* argv[4] = {"cmd_name"}; std::string base_help_text = "General options:\n" " -h --help\n" "\tShow this help message\n\n" "Commands:\n" " --cmd1\n\tcmd1\n" " --cmd2\n\tcmd2\n"; SUBCASE("normal help") { argv[argc++] = "--help"; argv[argc++] = "--cmd1"; // ignored Run(argc, argv, true); CHECK(ss.str() == base_help_text); } SUBCASE("help inside cmd1") { argv[argc++] = "--cmd1"; argv[argc++] = "--help"; Run(argc, argv, true); CHECK(ss.str() == base_help_text + "\n" "Command 1 shit:\n" " --foo\n\tfoo\n" " --bar\n\tbaz\n"); } SUBCASE("help inside cmd2") { argv[argc++] = "--cmd2"; argv[argc++] = "--help"; Run(argc, argv, true); CHECK(ss.str() == base_help_text + "\n" "Command 2 shit:\n" " --foo\n\tfoo2\n"); } SUBCASE("foo") { bool b1x_exp = false, b2x_exp = false; SUBCASE("cmd1") { argv[argc++] = "--cmd1"; b1x_exp = true; } SUBCASE("cmd2") { argv[argc++] = "--cmd2"; b2x_exp = true; } argv[argc++] = "--foo"; if (b2x_exp) argv[argc++] = "booboo"; parser.Run(argc, argv); CHECK(ss.str() == ""); CHECK(b1x == b1x_exp); CHECK(b1y == false); CHECK(b2x == b2x_exp); } SUBCASE("bar in cmd1") { argv[argc++] = "--cmd1"; argv[argc++] = "--bar"; parser.Run(argc, argv); CHECK(ss.str() == ""); CHECK(b1x == false); CHECK(b1y == true); CHECK(b2x == false); } SUBCASE("foo in cmd2") { argv[argc++] = "--cmd2"; argv[argc++] = "--bar"; argv[argc++] = "booboo"; Run(argc, argv, false); CHECK(ss.str() == "--bar: Unknown option\n"); } SUBCASE("dup command invalid") { SUBCASE("cmd1") argv[argc++] = "--cmd1"; SUBCASE("cmd2") argv[argc++] = "--cmd2"; argv[argc++] = "--cmd2"; Run(argc, argv, false); CHECK(ss.str() == "--cmd2: Multiple commands specified\n"); } } TEST_SUITE_END(); }
25.185861
96
0.48592
u3shit
f53c207ca9546b7be5a530108a6007ce8489e003
4,212
cpp
C++
test/test_lexer.cpp
miccol/derplanner
cd5d15acb741f027807796af9a12ed8968b4a91e
[ "Zlib" ]
37
2015-05-02T20:26:49.000Z
2022-01-19T01:28:38.000Z
test/test_lexer.cpp
BantamJoe/derplanner
d1042ba74eea856891132e1dc51cbcad6662f8c3
[ "Zlib" ]
3
2015-01-03T12:46:49.000Z
2021-10-04T00:55:17.000Z
test/test_lexer.cpp
BantamJoe/derplanner
d1042ba74eea856891132e1dc51cbcad6662f8c3
[ "Zlib" ]
12
2015-01-05T12:08:49.000Z
2022-01-19T01:28:39.000Z
// // Copyright (c) 2015 Alexander Shafranov shafranov@gmail.com // // 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 <stdlib.h> #include "unittestpp.h" #include "derplanner/compiler/array.h" #include "derplanner/compiler/lexer.h" namespace { struct Test_Lexer { ~Test_Lexer() { plnnrc::Memory_Stack::destroy(mem_scratch); memset(this, 0, sizeof(Test_Lexer)); } plnnrc::Lexer state; plnnrc::Memory_Stack* mem_scratch; }; void init(Test_Lexer& lexer, const char* input) { lexer.mem_scratch = plnnrc::Memory_Stack::create(1024); init(&lexer.state, input, lexer.mem_scratch); } TEST(ids_and_keywords) { Test_Lexer lexer; init(lexer, "id1 id2 domain id3"); plnnrc::Token_Type expected_types[] = { plnnrc::Token_Id, plnnrc::Token_Id, plnnrc::Token_Domain, plnnrc::Token_Id, plnnrc::Token_Eos }; const char* expected_strings[] = { "id1", "id2", "domain", "id3", 0 }; for (unsigned i = 0; i < sizeof(expected_types)/sizeof(expected_types[0]); ++i) { plnnrc::Token actual = plnnrc::lex(&lexer.state); CHECK_EQUAL(expected_types[i], actual.type); if (expected_strings[i] != 0) { CHECK_ARRAY_EQUAL(expected_strings[i], actual.value.str, actual.value.length); } } } TEST(location) { Test_Lexer lexer; init(lexer, "id1 \n id2"); plnnrc::Token tok1 = plnnrc::lex(&lexer.state); plnnrc::Token tok2 = plnnrc::lex(&lexer.state); CHECK_EQUAL(1u, tok1.loc.line); CHECK_EQUAL(1u, tok1.loc.column); CHECK_EQUAL(2u, tok2.loc.line); CHECK_EQUAL(2u, tok2.loc.column); } TEST(unknown_token) { Test_Lexer lexer; init(lexer, "$"); plnnrc::Token tok = plnnrc::lex(&lexer.state); CHECK_EQUAL(plnnrc::Token_Unknown, tok.type); } void check_number(const char* str, plnnrc::Token_Type expected) { Test_Lexer lexer; init(lexer, str); plnnrc::Token tok = plnnrc::lex(&lexer.state); CHECK_EQUAL(expected, tok.type); } void check_number(const char* str, float expected) { Test_Lexer lexer; init(lexer, str); plnnrc::Token tok = plnnrc::lex(&lexer.state); float actual = (float)strtod(tok.value.str, 0); CHECK_EQUAL(expected, actual); } void check_number(const char* str, int expected) { Test_Lexer lexer; init(lexer, str); plnnrc::Token tok = plnnrc::lex(&lexer.state); int actual = (int)strtol(tok.value.str, 0, 10); CHECK_EQUAL(expected, actual); } TEST(numeric_literals) { check_number("123", plnnrc::Token_Literal_Integer); check_number("123.", plnnrc::Token_Literal_Float); check_number("1.23", plnnrc::Token_Literal_Float); check_number("0.1e+23", plnnrc::Token_Literal_Float); check_number("0.1e+23", plnnrc::Token_Literal_Float); check_number("0.1e+23", plnnrc::Token_Literal_Float); check_number("1e23", plnnrc::Token_Literal_Float); check_number("1e-23", plnnrc::Token_Literal_Float); check_number("1e+23", plnnrc::Token_Literal_Float); check_number("123", 123); check_number("1.23", 1.23f); } }
33.428571
144
0.635328
miccol
f5425b355df028bb6007d937c62bf374bd879944
6,989
cpp
C++
dlib/dlib/test/matrix_lu.cpp
mohitjain4395/mosip
20ee978dc539be42c8b79cd4b604fdf681e7b672
[ "MIT" ]
11,719
2015-01-03T22:38:57.000Z
2022-03-30T21:45:04.000Z
dlib/test/matrix_lu.cpp
KiLJ4EdeN/dlib
eb1f08ce6ab3ca6f9d10425d899103de3c0df56c
[ "BSL-1.0" ]
2,518
2015-01-04T04:38:06.000Z
2022-03-31T11:55:43.000Z
dlib/test/matrix_lu.cpp
KiLJ4EdeN/dlib
eb1f08ce6ab3ca6f9d10425d899103de3c0df56c
[ "BSL-1.0" ]
3,308
2015-01-01T14:34:16.000Z
2022-03-31T07:20:07.000Z
// Copyright (C) 2009 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #include <dlib/matrix.h> #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <vector> #include "../stl_checked.h" #include "../array.h" #include "../rand.h" #include <dlib/string.h> #include "tester.h" namespace { using namespace test; using namespace dlib; using namespace std; logger dlog("test.matrix_lu"); dlib::rand rnd; // ---------------------------------------------------------------------------------------- template <typename mat_type> const matrix<typename mat_type::type> symm(const mat_type& m) { return m*trans(m); } // ---------------------------------------------------------------------------------------- template <typename type> const matrix<type> randmat(long r, long c) { matrix<type> m(r,c); for (long row = 0; row < m.nr(); ++row) { for (long col = 0; col < m.nc(); ++col) { m(row,col) = static_cast<type>(rnd.get_random_double()); } } return m; } template <typename type, long NR, long NC> const matrix<type,NR,NC> randmat() { matrix<type,NR,NC> m; for (long row = 0; row < m.nr(); ++row) { for (long col = 0; col < m.nc(); ++col) { m(row,col) = static_cast<type>(rnd.get_random_double()); } } return m; } // ---------------------------------------------------------------------------------------- template <typename matrix_type> void test_lu ( const matrix_type& m) { typedef typename matrix_type::type type; const type eps = 10*max(abs(m))*sqrt(std::numeric_limits<type>::epsilon()); dlog << LDEBUG << "test_lu(): " << m.nr() << " x " << m.nc() << " eps: " << eps; print_spinner(); lu_decomposition<matrix_type> test(m); DLIB_TEST(test.is_square() == (m.nr() == m.nc())); DLIB_TEST(test.nr() == m.nr()); DLIB_TEST(test.nc() == m.nc()); dlog << LDEBUG << "m.nr(): " << m.nr() << " m.nc(): " << m.nc(); type temp; DLIB_TEST_MSG( (temp= max(abs(test.get_l()*test.get_u() - rowm(m,test.get_pivot())))) < eps,temp); if (test.is_square()) { // none of the matrices we should be passing in to test_lu() should be singular. DLIB_TEST_MSG (abs(test.det()) > eps/100, "det: " << test.det() ); dlog << LDEBUG << "big det: " << test.det(); DLIB_TEST(test.is_singular() == false); matrix<type> m2; matrix<type,0,1> col; m2 = identity_matrix<type>(m.nr()); DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2))); m2 = randmat<type>(m.nr(),5); DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2))); m2 = randmat<type>(m.nr(),1); DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2))); col = randmat<type>(m.nr(),1); DLIB_TEST_MSG(equal(m*test.solve(col), col,eps),max(abs(m*test.solve(m2)- m2))); // now make us a singular matrix if (m.nr() > 1) { matrix<type> sm(m); set_colm(sm,0) = colm(sm,1); lu_decomposition<matrix_type> test2(sm); DLIB_TEST_MSG( (temp= max(abs(test2.get_l()*test2.get_u() - rowm(sm,test2.get_pivot())))) < eps,temp); // these checks are only accurate for small matrices if (test2.nr() < 100) { DLIB_TEST_MSG(test2.is_singular() == true,"det: " << test2.det()); DLIB_TEST_MSG(abs(test2.det()) < eps,"det: " << test2.det()); } } } } // ---------------------------------------------------------------------------------------- void matrix_test_double() { test_lu(10*randmat<double>(2,2)); test_lu(10*randmat<double>(1,1)); test_lu(10*symm(randmat<double>(2,2))); test_lu(10*randmat<double>(4,4)); test_lu(10*randmat<double>(9,4)); test_lu(10*randmat<double>(3,8)); test_lu(10*randmat<double>(15,15)); test_lu(2*symm(randmat<double>(15,15))); test_lu(10*randmat<double>(100,100)); test_lu(10*randmat<double>(137,200)); test_lu(10*randmat<double>(200,101)); test_lu(10*randmat<double,2,2>()); test_lu(10*randmat<double,1,1>()); test_lu(10*randmat<double,4,3>()); test_lu(10*randmat<double,4,4>()); test_lu(10*randmat<double,9,4>()); test_lu(10*randmat<double,3,8>()); test_lu(10*randmat<double,15,15>()); test_lu(10*randmat<double,100,100>()); test_lu(10*randmat<double,137,200>()); test_lu(10*randmat<double,200,101>()); typedef matrix<double,0,0,default_memory_manager, column_major_layout> mat; test_lu(mat(3*randmat<double>(4,4))); test_lu(mat(3*randmat<double>(9,4))); test_lu(mat(3*randmat<double>(3,8))); } // ---------------------------------------------------------------------------------------- void matrix_test_float() { // ------------------------------- test_lu(3*randmat<float>(1,1)); test_lu(3*randmat<float>(2,2)); test_lu(3*randmat<float>(4,4)); test_lu(3*randmat<float>(9,4)); test_lu(3*randmat<float>(3,8)); test_lu(3*randmat<float>(137,200)); test_lu(3*randmat<float>(200,101)); test_lu(3*randmat<float,1,1>()); test_lu(3*randmat<float,2,2>()); test_lu(3*randmat<float,4,3>()); test_lu(3*randmat<float,4,4>()); test_lu(3*randmat<float,9,4>()); test_lu(3*randmat<float,3,8>()); test_lu(3*randmat<float,137,200>()); test_lu(3*randmat<float,200,101>()); typedef matrix<float,0,0,default_memory_manager, column_major_layout> mat; test_lu(mat(3*randmat<float>(4,4))); test_lu(mat(3*randmat<float>(9,4))); test_lu(mat(3*randmat<float>(3,8))); } // ---------------------------------------------------------------------------------------- class matrix_tester : public tester { public: matrix_tester ( ) : tester ("test_matrix_lu", "Runs tests on the matrix LU component.") { //rnd.set_seed(cast_to_string(time(0))); } void perform_test ( ) { dlog << LINFO << "seed string: " << rnd.get_seed(); dlog << LINFO << "begin testing with double"; matrix_test_double(); dlog << LINFO << "begin testing with float"; matrix_test_float(); } } a; }
31.200893
118
0.487337
mohitjain4395
f5490eebdba9af20fab2a8198521554d85b5272e
733
hpp
C++
test/unittests/lib/core/runtime/f32_neg_unittest.hpp
yuhao-kuo/WasmVM
b4dcd4f752f07ba4180dc275d47764c363776301
[ "BSD-3-Clause" ]
125
2018-10-22T19:00:25.000Z
2022-03-14T06:33:25.000Z
test/unittests/lib/core/runtime/f32_neg_unittest.hpp
yuhao-kuo/WasmVM
b4dcd4f752f07ba4180dc275d47764c363776301
[ "BSD-3-Clause" ]
80
2018-10-18T06:35:07.000Z
2020-04-20T02:40:22.000Z
test/unittests/lib/core/runtime/f32_neg_unittest.hpp
yuhao-kuo/WasmVM
b4dcd4f752f07ba4180dc275d47764c363776301
[ "BSD-3-Clause" ]
27
2018-11-04T12:05:35.000Z
2021-09-06T05:11:50.000Z
#include <skypat/skypat.h> #define _Bool bool extern "C" { #include <dataTypes/Value.h> #include <core/Runtime.h> } #undef _Bool SKYPAT_F(Runtime_f32_neg, regular) { // prepare Stack stack = new_Stack(); Value *val1 = new_f32Value(5), *val2 = new_f32Value(-3); push_Value(stack, val1); push_Value(stack, val2); // run negative runtime_f32_neg(stack); // check Value *check1 = NULL; pop_Value(stack,&check1); EXPECT_EQ(check1->value.f32, 3); // run positive runtime_f32_neg(stack); // check Value *check2 = NULL; pop_Value(stack,&check2); EXPECT_EQ(check2->value.f32, -5); // clean free_Value(check1); free_Value(check2); free_Stack(stack); }
18.794872
60
0.638472
yuhao-kuo
f549cf951f6391a1292dd4aa2591a6da6f49f7ad
3,030
cpp
C++
engine/src/Object.cpp
EvilPyro/2D_Game_Framework
b3b8538354a65288bdbfb9d787086038dbb57785
[ "Zlib" ]
null
null
null
engine/src/Object.cpp
EvilPyro/2D_Game_Framework
b3b8538354a65288bdbfb9d787086038dbb57785
[ "Zlib" ]
null
null
null
engine/src/Object.cpp
EvilPyro/2D_Game_Framework
b3b8538354a65288bdbfb9d787086038dbb57785
[ "Zlib" ]
null
null
null
#include "Object.h" #include "Engine.h" #include <iostream> #include <cassert> #include <limits> std::map<std::string,ObjectFactory*>& Object::getFactories() { //Singleton static std::map<std::string,ObjectFactory*> factories; return factories; } void Object::registerType(const std::string& name, ObjectFactory* factory) { getFactories()[name] = factory; } std::weak_ptr<Object> Object::create(const std::string& name, Position Pos) { auto gPTR = EngineUtils::getGame().lock(); assert(gPTR && "Maybe you are creating an object before a game or in its contructor?"); int uuid = 0; if (! gPTR->Objects.empty()) uuid = (gPTR->Objects).rbegin()->first + 1; return create(name, Pos, uuid); } std::weak_ptr<Object> Object::create(const std::string& name, Position Pos, int uuid) { auto gPTR = EngineUtils::getGame().lock(); assert(gPTR && "Maybe you are creating an object before a game or in its contructor?"); auto it = getFactories().find(name); assert(it != getFactories().end() && "Requested invalid Object name"); b2BodyDef* BodyDef = new b2BodyDef(); BodyDef->position.Set(std::get<0>(Pos), std::get<1>(Pos)); auto Body = gPTR->getWorldFromLevel(std::get<2>(Pos))->CreateBody(BodyDef); auto ptr = it->second->create(Body); ptr->LevelZCoordinate = std::get<2>(Pos); auto insertion = (gPTR->Objects).insert(std::make_pair(uuid, ptr)); assert(insertion.second); //ensure that the UUID was unique auto Wptr = std::weak_ptr<Object>(ptr); if (name == "Player") (gPTR->Players).push_back(Wptr); return Wptr; } Position Object::getPosition() const { assert(Body); // this not ensures Body validity auto pos2D = Body->GetPosition(); Position Pos = {pos2D.x, pos2D.y, LevelZCoordinate}; return Pos; } Rotation Object::getRotation() const { assert(Body); // this not ensures Body validity Rotation Rot; Rot = Body->GetAngle(); return Rot; } void Object::setPosition(Position P) { //WIP, IF Z CHANGES WE ARE FKED assert(Body); // this not ensures Body validity if (std::get<2>(P) == LevelZCoordinate) { b2Vec2 pos = {std::get<0>(P), std::get<1>(P)}; Body->SetTransform(pos, Body->GetAngle()); } else { b2BodyDef BodyDef; BodyDef.position.Set(std::get<0>(P), std::get<1>(P)); LevelZCoordinate = std::get<2>(P); BodyDef.angle = Body->GetAngle(); BodyDef.type = Body->GetType(); auto NewBody = EngineUtils::getGame().lock()->getWorldFromLevel(std::get<2>(P))->CreateBody(&BodyDef); auto fixtureList = Body->GetFixtureList(); while(fixtureList) { b2FixtureDef FixtureDef; FixtureDef.density = fixtureList->GetDensity(); FixtureDef.friction = fixtureList->GetFriction(); FixtureDef.restitution = fixtureList->GetRestitution(); FixtureDef.shape = fixtureList->GetShape(); NewBody->CreateFixture(&FixtureDef); fixtureList = fixtureList->GetNext(); } Body->GetWorld()->DestroyBody(Body); Body = NewBody; } } void Object::setRotation(Rotation R) { assert(Body); // this not ensures Body validity Body->SetTransform(Body->GetPosition(), R.get()); }
32.234043
104
0.6967
EvilPyro
f54a1f3a13f712eff13d7cd6639319cf570e70f3
2,956
cxx
C++
src/mlio/shuffled_instance_reader.cxx
laurencer/ml-io
b40a88f0b61f7dfd2b74897a9b2385539d5796aa
[ "Apache-2.0" ]
null
null
null
src/mlio/shuffled_instance_reader.cxx
laurencer/ml-io
b40a88f0b61f7dfd2b74897a9b2385539d5796aa
[ "Apache-2.0" ]
2
2020-04-08T01:37:44.000Z
2020-04-14T20:14:07.000Z
src/mlio/shuffled_instance_reader.cxx
laurencer/ml-io
b40a88f0b61f7dfd2b74897a9b2385539d5796aa
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "mlio/shuffled_instance_reader.h" #include <algorithm> #include <limits> #include <utility> #include "mlio/data_reader.h" namespace mlio { inline namespace v1 { namespace detail { shuffled_instance_reader::shuffled_instance_reader( data_reader_params const &prm, std::unique_ptr<instance_reader> &&inner) : params_{&prm} , inner_{std::move(inner)} , shuffle_window_{params_->shuffle_window} , dist_{0, shuffle_window_ - 1} { if (shuffle_window_ == 1) { return; } if (shuffle_window_ == 0) { shuffle_window_ = std::numeric_limits<std::size_t>::max(); } else { buffer_.reserve(shuffle_window_); } if (params_->shuffle_seed != std::nullopt) { seed_ = *params_->shuffle_seed; mt_.seed(seed_); } } std::optional<instance> shuffled_instance_reader::read_instance_core() { if (shuffle_window_ == 1) { return inner_->read_instance(); } buffer_instances(); if (buffer_.empty()) { return {}; } if (inner_has_instances_) { return pop_random_instance_from_buffer(); } instance ins = std::move(buffer_.back()); buffer_.pop_back(); return std::move(ins); } void shuffled_instance_reader::buffer_instances() { while (inner_has_instances_ && buffer_.size() < shuffle_window_) { std::optional<instance> ins = inner_->read_instance(); if (ins == std::nullopt) { inner_has_instances_ = false; std::shuffle(buffer_.begin(), buffer_.end(), mt_); break; } buffer_.emplace_back(std::move(*ins)); } } std::optional<instance> shuffled_instance_reader::pop_random_instance_from_buffer() { std::size_t random_idx = dist_(mt_); instance ins = std::move(buffer_[random_idx]); if (random_idx != buffer_.size() - 1) { buffer_[random_idx] = std::move(buffer_.back()); } buffer_.pop_back(); return std::move(ins); } void shuffled_instance_reader::reset() noexcept { inner_->reset(); buffer_.clear(); inner_has_instances_ = true; // Make sure that we reset the random number generator engine to // its initial state if reshuffling is not desired. if (!params_->reshuffle_each_epoch) { mt_.seed(seed_); } } } // namespace detail } // namespace v1 } // namespace mlio
23.275591
76
0.656292
laurencer
f54c49e33f370b3af445d43201765aa3ef4fbd95
3,006
cpp
C++
src/d3d11/d3d11_interop.cpp
archfan/dxvk
91c82f17cc34a2410191f15c8d66fb6fa9b927c2
[ "Zlib" ]
7
2019-03-31T15:44:23.000Z
2021-07-15T23:34:11.000Z
src/d3d11/d3d11_interop.cpp
archfan/dxvk
91c82f17cc34a2410191f15c8d66fb6fa9b927c2
[ "Zlib" ]
null
null
null
src/d3d11/d3d11_interop.cpp
archfan/dxvk
91c82f17cc34a2410191f15c8d66fb6fa9b927c2
[ "Zlib" ]
1
2019-11-04T07:48:24.000Z
2019-11-04T07:48:24.000Z
#include "d3d11_context_imm.h" #include "d3d11_interop.h" #include "d3d11_device.h" #include "../dxvk/dxvk_adapter.h" #include "../dxvk/dxvk_device.h" #include "../dxvk/dxvk_instance.h" namespace dxvk { D3D11VkInterop::D3D11VkInterop( IDXGIObject* pContainer, D3D11Device* pDevice) : m_container (pContainer), m_device (pDevice) { } D3D11VkInterop::~D3D11VkInterop() { } ULONG STDMETHODCALLTYPE D3D11VkInterop::AddRef() { return m_container->AddRef(); } ULONG STDMETHODCALLTYPE D3D11VkInterop::Release() { return m_container->Release(); } HRESULT STDMETHODCALLTYPE D3D11VkInterop::QueryInterface( REFIID riid, void** ppvObject) { return m_container->QueryInterface(riid, ppvObject); } void STDMETHODCALLTYPE D3D11VkInterop::GetVulkanHandles( VkInstance* pInstance, VkPhysicalDevice* pPhysDev, VkDevice* pDevice) { auto device = m_device->GetDXVKDevice(); auto adapter = device->adapter(); auto instance = adapter->instance(); if (pDevice != nullptr) *pDevice = device->handle(); if (pPhysDev != nullptr) *pPhysDev = adapter->handle(); if (pInstance != nullptr) *pInstance = instance->handle(); } void STDMETHODCALLTYPE D3D11VkInterop::GetSubmissionQueue( VkQueue* pQueue, uint32_t* pQueueFamilyIndex) { auto device = static_cast<D3D11Device*>(m_device)->GetDXVKDevice(); DxvkDeviceQueue queue = device->graphicsQueue(); if (pQueue != nullptr) *pQueue = queue.queueHandle; if (pQueueFamilyIndex != nullptr) *pQueueFamilyIndex = queue.queueFamily; } void STDMETHODCALLTYPE D3D11VkInterop::TransitionSurfaceLayout( IDXGIVkInteropSurface* pSurface, const VkImageSubresourceRange* pSubresources, VkImageLayout OldLayout, VkImageLayout NewLayout) { Com<ID3D11DeviceContext> deviceContext = nullptr; m_device->GetImmediateContext(&deviceContext); auto immediateContext = static_cast<D3D11ImmediateContext*>(deviceContext.ptr()); immediateContext->TransitionSurfaceLayout( pSurface, pSubresources, OldLayout, NewLayout); } void STDMETHODCALLTYPE D3D11VkInterop::FlushRenderingCommands() { Com<ID3D11DeviceContext> deviceContext = nullptr; m_device->GetImmediateContext(&deviceContext); auto immediateContext = static_cast<D3D11ImmediateContext*>(deviceContext.ptr()); immediateContext->Flush(); immediateContext->SynchronizeCsThread(); } void STDMETHODCALLTYPE D3D11VkInterop::LockSubmissionQueue() { m_device->GetDXVKDevice()->lockSubmission(); } void STDMETHODCALLTYPE D3D11VkInterop::ReleaseSubmissionQueue() { m_device->GetDXVKDevice()->unlockSubmission(); } }
28.093458
85
0.653027
archfan
f54e973b502816b39cdadf58abe3251542b12ee7
6,271
cpp
C++
SRC/symbolic.cpp
anastasiiakim/ranked_probs
be6248b57e033e39f9db133a88fb68993ac7dc99
[ "MIT" ]
5
2020-07-03T04:21:39.000Z
2021-04-01T20:25:50.000Z
SRC/symbolic.cpp
anastasiiakim/ranked_probs
be6248b57e033e39f9db133a88fb68993ac7dc99
[ "MIT" ]
1
2020-02-06T19:52:46.000Z
2020-02-06T19:52:54.000Z
SRC/symbolic.cpp
anastasiiakim/ranked_probs
be6248b57e033e39f9db133a88fb68993ac7dc99
[ "MIT" ]
1
2020-07-08T02:40:17.000Z
2020-07-08T02:40:17.000Z
#include <string> #include <fstream> #include <iostream> #include <stack> #include <cmath> #include <algorithm> #include <iomanip> // output more decimals #define EPS 1e-8 #include "string_manipulations.h" #include "node.h" #include "queue.h" #include "probs_calculation.h" #include "symbolic.h" using namespace std; double symbolicIntervalProbability(int i, int * m_i, int *** array_k, double * s, ofstream & fout) { double res = 0.; double prod; double m = m_i[i-1]; for(int j = 0; j < m + 1; ++j) { prod = 1.; for(int k = 0; k < m + 1; ++k) { if(k != j) { prod *= lambda_ij(i, k, array_k) - lambda_ij(i, j, array_k); } } if(j == 0 && i == 2) fout << " + "; if(j == 0) fout << "("; fout << "exp(" << -lambda_ij(i, j, array_k) << "*(s" << i-1 << "-s" << i << "))*1/(" << prod << ")"; if (j < m) fout << " + "; if (j == m) fout << ") "; res += (double) exp(-lambda_ij(i, j, array_k)*s[i-2])/prod; } fout << " * " << endl; return res; } double symbolicGeneTreeProbability(int * m, int *** k, double * s, double * coal, int n, ofstream & fout) { double res = 1.; for(int i = 2; i < n; ++i) { res *= symbolicIntervalProbability(i, m, k, s, fout); } fout << pow(2, m[0]) << "/" << factorial(m[0])*factorial(m[0]+1) << endl; return res*coal[m[0] - 1]; } double getOneSymbolicGeneTreeProb(int N, double * s, vector <Node *> v, Node * newnodeGT, int ** ar_y, double * array_invcoal, Node ** arMrca, int ** ar_rankns, int ***k, ofstream & fout, ofstream & histprobs_file) { returnMrca(v, newnodeGT, N, arMrca); int * arRankHistory = new int [N-1]; get_hseq(arRankHistory, newnodeGT, v, N); reverseArraySort(arRankHistory, N); int * arRankHistoryCopy = new int[N-1]; for(int i = 0; i < N-1; ++i) { arRankHistoryCopy[i] = arRankHistory[i]; } int * m_i = new int[N-1]; arrayFreq(arRankHistoryCopy, m_i, N-1); int max_m_i = *max_element(m_i, m_i+N-1); get_node(arRankHistory, ar_rankns, N, arMrca); for(int i = 0; i < N+1; i++) for(int j = 0; j < N; ++j) for(int z = 0; z < N+1 ; ++z) { k[i][j][z] = 0; } calc_k_ijz(k, N, m_i, ar_y, ar_rankns); double onehistprob = symbolicGeneTreeProbability(m_i, k, s, array_invcoal, N, fout); double prob_val = onehistprob; for(int i = 0; i < N-1; ++i) histprobs_file << arRankHistory[i]; histprobs_file << '\t'; histprobs_file << onehistprob << endl; int * arRHcopy = new int[N-1]; for(int i = 0; i < N - 1; ++i) arRHcopy[i] = arRankHistory[i]; int history_counter = 1; int numb = 0; int * next_history; while(*(arRHcopy + N - 2) != 1) { next_history = getNextHistory (arRHcopy, arRankHistory, N, history_counter, numb); fout << endl; for(int i = 0; i < N-1; ++i) arRankHistoryCopy[i] = next_history[i]; arrayFreq(arRankHistoryCopy, m_i, N-1); max_m_i = *max_element(m_i, m_i+N-1); get_node(next_history, ar_rankns, N, arMrca); for(int i = 0; i < N+1; i++) { for(int j = 0; j <= max_m_i ; ++j) { for(int z = 0; z < N+1 ; ++z) { k[i][j][z] = 0; } } } calc_k_ijz(k, N, m_i, ar_y, ar_rankns); onehistprob = symbolicGeneTreeProbability(m_i, k, s, array_invcoal, N, fout); prob_val += onehistprob; cout << "---------------------" << endl; for(int i = 0; i < N-1; ++i) histprobs_file << next_history[i]; histprobs_file << '\t'; histprobs_file << onehistprob << endl; history_counter++; } delete[] arRankHistory; delete[] arRHcopy; delete[] arRankHistoryCopy; delete[] m_i; return prob_val; } double getSymbolicGeneTreeProb(int & arg_counter, char* argv[], int & N, vector <Node *> v, double* s, int** ar_y) { string strGT=""; ifstream finGT(argv[arg_counter]); ++arg_counter; ofstream fout("outSymbolic.txt"); ofstream histprobs_file("outHistProbs.txt"); double total = 0.; Node ** arMrca = new Node * [N-1]; int ** ar_rankns = new int * [N-1]; for (int i = 0; i < N-1; i++) ar_rankns[i] = new int [N-1]; for(int i = 0; i < N-1; ++i) { for(int j = 0; j < N - 1; ++j) { ar_rankns[i][j] = 0; } } int ***k; k = new int **[N+1]; for(int i = 0; i < N+1; i++) { k[i] = new int *[N]; for(int j = 0; j < N; ++j) k[i][j] = new int[N+1]; } double * array_invcoal = new double[N-1]; getInvPartialCoal(array_invcoal, N); Node * newnodeGT; while(getline(finGT, strGT, ';')) { if(strGT.size() < 3) break; removeSpaces(strGT); std::stack <Node *> stkGT; int lblGT = 0; Node **arGT = new Node * [N]; pushNodes(lblGT, stkGT , strGT); newnodeGT = stkGT.top(); newnodeGT -> distFrRoot = 0.; int tailGT = 0; distFromRoot(newnodeGT); pushToArray(newnodeGT, tailGT, arGT); getRanks(newnodeGT, tailGT, arGT); getDescTaxa(newnodeGT, N); total += getOneSymbolicGeneTreeProb(N, s, v, newnodeGT, ar_y, array_invcoal, arMrca, ar_rankns, k, fout, histprobs_file); delete [] arGT; deleteTree(newnodeGT); deleteStack(stkGT); } delete [] array_invcoal; for(int i = 0; i < N-1; ++i) delete[] ar_rankns[i]; delete [] ar_rankns; delete[] arMrca; for(int i = 0; i < N+1; ++i) { for(int j = 0; j < N; ++j) delete [] k[i][j]; delete [] k[i]; } delete [] k; finGT.close(); histprobs_file.close(); fout.close(); return total; } void symbolicProbsRankedGtInput(int & arg_counter, char* argv[]) { Node * newnode; int N = getNumberOfTaxa(arg_counter, argv, newnode); double * s_times = new double [N-1]; double * s = new double [N-2]; vector <Node *> v; int ** ar_y = new int * [N]; for (int i = 0; i < N; i++) ar_y[i] = new int [N]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) { ar_y[i][j] = 0; } speciesTreeProcessing(newnode, N, s_times, s, v, ar_y); cout << "Total: " << getSymbolicGeneTreeProb(arg_counter, argv, N, v, s, ar_y) << endl; for(int i = 0; i < N; ++i) { delete[] ar_y[i]; } delete[] ar_y; delete[] s_times; delete[] s; deleteTree(newnode); }
23.664151
215
0.556052
anastasiiakim
f55272e08aaea75186312ad68e602b586a63e5ff
4,808
cc
C++
proxy/EventName.cc
garfieldonly/ats_git
940ff5c56bebabb96130a55c2a17212c5c518138
[ "Apache-2.0" ]
1
2022-01-19T14:34:34.000Z
2022-01-19T14:34:34.000Z
proxy/EventName.cc
mingzym/trafficserver
a01c3a357b4ff9193f2e2a8aee48e3751ef2177a
[ "Apache-2.0" ]
2
2017-12-05T23:48:37.000Z
2017-12-20T01:22:07.000Z
proxy/EventName.cc
maskit/trafficserver
3ffa19873f7cd7ced2fbdfed5a0ac8ddbbe70a68
[ "Apache-2.0" ]
null
null
null
/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ts/ink_config.h" #include <stdio.h> #include <string.h> #include "P_EventSystem.h" // #include "I_Disk.h" unused #include "I_Cache.h" #include "I_Net.h" //#include "P_Cluster.h" #include "I_HostDB.h" #include "BaseManager.h" #include "P_MultiCache.h" /*------------------------------------------------------------------------- event_int_to_string This routine will translate an integer event number to a string identifier based on a brute-force search of a switch tag. If the event cannot be located in the switch table, the routine will construct and return a string of the integer identifier. -------------------------------------------------------------------------*/ const char * event_int_to_string(int event, int blen, char *buffer) { switch (event) { case -1: return "<no event>"; case VC_EVENT_READ_READY: return "VC_EVENT_READ_READY"; case VC_EVENT_WRITE_READY: return "VC_EVENT_WRITE_READY"; case VC_EVENT_READ_COMPLETE: return "VC_EVENT_READ_COMPLETE"; case VC_EVENT_WRITE_COMPLETE: return "VC_EVENT_WRITE_COMPLETE"; case VC_EVENT_EOS: return "VC_EVENT_EOS"; case VC_EVENT_INACTIVITY_TIMEOUT: return "VC_EVENT_INACTIVITY_TIMEOUT"; case VC_EVENT_ACTIVE_TIMEOUT: return "VC_EVENT_ACTIVE_TIMEOUT"; case NET_EVENT_OPEN: return "NET_EVENT_OPEN"; case NET_EVENT_OPEN_FAILED: return "NET_EVENT_OPEN_FAILED"; case NET_EVENT_ACCEPT: return "NET_EVENT_ACCEPT"; case NET_EVENT_ACCEPT_SUCCEED: return "NET_EVENT_ACCEPT_SUCCEED"; case NET_EVENT_ACCEPT_FAILED: return "NET_EVENT_ACCEPT_FAILED"; #ifdef CLUSTER_CACHE case CLUSTER_EVENT_CHANGE: return "CLUSTER_EVENT_CHANGE"; case CLUSTER_EVENT_CONFIGURATION: return "CLUSTER_EVENT_CONFIGURATION"; case CLUSTER_EVENT_OPEN: return "CLUSTER_EVENT_OPEN"; case CLUSTER_EVENT_OPEN_FAILED: return "CLUSTER_EVENT_OPEN_FAILED"; case CLUSTER_EVENT_STEAL_THREAD: return "CLUSTER_EVENT_STEAL_THREAD"; #endif case EVENT_HOST_DB_LOOKUP: return "EVENT_HOST_DB_LOOKUP"; case EVENT_HOST_DB_GET_RESPONSE: return "EVENT_HOST_DB_GET_RESPONSE"; case DNS_EVENT_EVENTS_START: return "DNS_EVENT_EVENTS_START"; case MULTI_CACHE_EVENT_SYNC: return "MULTI_CACHE_EVENT_SYNC"; case CACHE_EVENT_LOOKUP: return "CACHE_EVENT_LOOKUP"; case CACHE_EVENT_LOOKUP_FAILED: return "CACHE_EVENT_LOOKUP_FAILED"; case CACHE_EVENT_OPEN_READ: return "CACHE_EVENT_OPEN_READ"; case CACHE_EVENT_OPEN_READ_FAILED: return "CACHE_EVENT_OPEN_READ_FAILED"; case CACHE_EVENT_OPEN_WRITE: return "CACHE_EVENT_OPEN_WRITE"; case CACHE_EVENT_OPEN_WRITE_FAILED: return "CACHE_EVENT_OPEN_WRITE_FAILED"; case CACHE_EVENT_REMOVE: return "CACHE_EVENT_REMOVE"; case CACHE_EVENT_REMOVE_FAILED: return "CACHE_EVENT_REMOVE_FAILED"; case CACHE_EVENT_UPDATE: return "CACHE_EVENT_UPDATE"; case CACHE_EVENT_UPDATE_FAILED: return "CACHE_EVENT_UPDATE_FAILED"; case CACHE_EVENT_LINK: return "CACHE_EVENT_LINK"; case CACHE_EVENT_LINK_FAILED: return "CACHE_EVENT_LINK_FAILED"; case CACHE_EVENT_DEREF: return "CACHE_EVENT_DEREF"; case CACHE_EVENT_DEREF_FAILED: return "CACHE_EVENT_DEREF_FAILED"; case CACHE_EVENT_RESPONSE: return "CACHE_EVENT_RESPONSE"; case CACHE_EVENT_RESPONSE_MSG: return "CACHE_EVENT_RESPONSE_MSG"; case MGMT_EVENT_SHUTDOWN: return "MGMT_EVENT_SHUTDOWN"; case MGMT_EVENT_RESTART: return "MGMT_EVENT_RESTART"; case MGMT_EVENT_BOUNCE: return "MGMT_EVENT_BOUNCE"; case MGMT_EVENT_CONFIG_FILE_UPDATE: return "MGMT_EVENT_CONFIG_FILE_UPDATE"; case MGMT_EVENT_CONFIG_FILE_UPDATE_NO_INC_VERSION: return "MGMT_EVENT_CONFIG_FILE_UPDATE_NO_INC_VERSION"; case MGMT_EVENT_CLEAR_STATS: return "MGMT_EVENT_CLEAR_STATS"; default: if (buffer != NULL) { snprintf(buffer, blen, "%d", event); return buffer; } else { return "UNKNOWN_EVENT"; } } }
30.05
77
0.744176
garfieldonly
f55290f6493eb9b106cbbbf3b995e695a1b2ff68
13,668
cc
C++
src/rocksdb2/java/rocksjni/rocksjni.cc
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
89
2015-04-23T20:24:58.000Z
2022-03-20T12:35:30.000Z
src/rocksdb2/java/rocksjni/rocksjni.cc
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
14
2020-05-25T15:42:18.000Z
2022-03-20T12:44:56.000Z
src/rocksdb2/java/rocksjni/rocksjni.cc
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
41
2015-01-19T05:26:34.000Z
2022-02-23T03:47:39.000Z
// Copyright (c) 2014, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // This file implements the "bridge" between Java and C++ and enables // calling c++ rocksdb::DB methods from Java side. #include <stdio.h> #include <stdlib.h> #include <jni.h> #include <string> #include <vector> #include "include/org_rocksdb_RocksDB.h" #include "rocksjni/portal.h" #include "rocksdb/db.h" #include "rocksdb/cache.h" ////////////////////////////////////////////////////////////////////////////// // rocksdb::DB::Open /* * Class: org_rocksdb_RocksDB * Method: open * Signature: (JLjava/lang/String;)V */ void Java_org_rocksdb_RocksDB_open( JNIEnv* env, jobject jdb, jlong jopt_handle, jstring jdb_path) { auto opt = reinterpret_cast<rocksdb::Options*>(jopt_handle); rocksdb::DB* db = nullptr; const char* db_path = env->GetStringUTFChars(jdb_path, 0); rocksdb::Status s = rocksdb::DB::Open(*opt, db_path, &db); env->ReleaseStringUTFChars(jdb_path, db_path); if (s.ok()) { rocksdb::RocksDBJni::setHandle(env, jdb, db); return; } rocksdb::RocksDBExceptionJni::ThrowNew(env, s); } ////////////////////////////////////////////////////////////////////////////// // rocksdb::DB::Put void rocksdb_put_helper( JNIEnv* env, rocksdb::DB* db, const rocksdb::WriteOptions& write_options, jbyteArray jkey, jint jkey_len, jbyteArray jvalue, jint jvalue_len) { jbyte* key = env->GetByteArrayElements(jkey, 0); jbyte* value = env->GetByteArrayElements(jvalue, 0); rocksdb::Slice key_slice(reinterpret_cast<char*>(key), jkey_len); rocksdb::Slice value_slice(reinterpret_cast<char*>(value), jvalue_len); rocksdb::Status s = db->Put(write_options, key_slice, value_slice); // trigger java unref on key and value. // by passing JNI_ABORT, it will simply release the reference without // copying the result back to the java byte array. env->ReleaseByteArrayElements(jkey, key, JNI_ABORT); env->ReleaseByteArrayElements(jvalue, value, JNI_ABORT); if (s.ok()) { return; } rocksdb::RocksDBExceptionJni::ThrowNew(env, s); } /* * Class: org_rocksdb_RocksDB * Method: put * Signature: (J[BI[BI)V */ void Java_org_rocksdb_RocksDB_put__J_3BI_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jbyteArray jkey, jint jkey_len, jbyteArray jvalue, jint jvalue_len) { auto db = reinterpret_cast<rocksdb::DB*>(jdb_handle); static const rocksdb::WriteOptions default_write_options = rocksdb::WriteOptions(); rocksdb_put_helper(env, db, default_write_options, jkey, jkey_len, jvalue, jvalue_len); } /* * Class: org_rocksdb_RocksDB * Method: put * Signature: (JJ[BI[BI)V */ void Java_org_rocksdb_RocksDB_put__JJ_3BI_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jlong jwrite_options_handle, jbyteArray jkey, jint jkey_len, jbyteArray jvalue, jint jvalue_len) { auto db = reinterpret_cast<rocksdb::DB*>(jdb_handle); auto write_options = reinterpret_cast<rocksdb::WriteOptions*>( jwrite_options_handle); rocksdb_put_helper(env, db, *write_options, jkey, jkey_len, jvalue, jvalue_len); } ////////////////////////////////////////////////////////////////////////////// // rocksdb::DB::Write /* * Class: org_rocksdb_RocksDB * Method: write * Signature: (JJ)V */ void Java_org_rocksdb_RocksDB_write( JNIEnv* env, jobject jdb, jlong jwrite_options_handle, jlong jbatch_handle) { rocksdb::DB* db = rocksdb::RocksDBJni::getHandle(env, jdb); auto write_options = reinterpret_cast<rocksdb::WriteOptions*>( jwrite_options_handle); auto batch = reinterpret_cast<rocksdb::WriteBatch*>(jbatch_handle); rocksdb::Status s = db->Write(*write_options, batch); if (!s.ok()) { rocksdb::RocksDBExceptionJni::ThrowNew(env, s); } } ////////////////////////////////////////////////////////////////////////////// // rocksdb::DB::Get jbyteArray rocksdb_get_helper( JNIEnv* env, rocksdb::DB* db, const rocksdb::ReadOptions& read_opt, jbyteArray jkey, jint jkey_len) { jboolean isCopy; jbyte* key = env->GetByteArrayElements(jkey, &isCopy); rocksdb::Slice key_slice( reinterpret_cast<char*>(key), jkey_len); std::string value; rocksdb::Status s = db->Get( read_opt, key_slice, &value); // trigger java unref on key. // by passing JNI_ABORT, it will simply release the reference without // copying the result back to the java byte array. env->ReleaseByteArrayElements(jkey, key, JNI_ABORT); if (s.IsNotFound()) { return nullptr; } if (s.ok()) { jbyteArray jvalue = env->NewByteArray(value.size()); env->SetByteArrayRegion( jvalue, 0, value.size(), reinterpret_cast<const jbyte*>(value.c_str())); return jvalue; } rocksdb::RocksDBExceptionJni::ThrowNew(env, s); return nullptr; } /* * Class: org_rocksdb_RocksDB * Method: get * Signature: (J[BI)[B */ jbyteArray Java_org_rocksdb_RocksDB_get__J_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jbyteArray jkey, jint jkey_len) { return rocksdb_get_helper(env, reinterpret_cast<rocksdb::DB*>(jdb_handle), rocksdb::ReadOptions(), jkey, jkey_len); } /* * Class: org_rocksdb_RocksDB * Method: get * Signature: (JJ[BI)[B */ jbyteArray Java_org_rocksdb_RocksDB_get__JJ_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jlong jropt_handle, jbyteArray jkey, jint jkey_len) { return rocksdb_get_helper(env, reinterpret_cast<rocksdb::DB*>(jdb_handle), *reinterpret_cast<rocksdb::ReadOptions*>(jropt_handle), jkey, jkey_len); } jint rocksdb_get_helper( JNIEnv* env, rocksdb::DB* db, const rocksdb::ReadOptions& read_options, jbyteArray jkey, jint jkey_len, jbyteArray jvalue, jint jvalue_len) { static const int kNotFound = -1; static const int kStatusError = -2; jbyte* key = env->GetByteArrayElements(jkey, 0); rocksdb::Slice key_slice( reinterpret_cast<char*>(key), jkey_len); // TODO(yhchiang): we might save one memory allocation here by adding // a DB::Get() function which takes preallocated jbyte* as input. std::string cvalue; rocksdb::Status s = db->Get( read_options, key_slice, &cvalue); // trigger java unref on key. // by passing JNI_ABORT, it will simply release the reference without // copying the result back to the java byte array. env->ReleaseByteArrayElements(jkey, key, JNI_ABORT); if (s.IsNotFound()) { return kNotFound; } else if (!s.ok()) { // Here since we are throwing a Java exception from c++ side. // As a result, c++ does not know calling this function will in fact // throwing an exception. As a result, the execution flow will // not stop here, and codes after this throw will still be // executed. rocksdb::RocksDBExceptionJni::ThrowNew(env, s); // Return a dummy const value to avoid compilation error, although // java side might not have a chance to get the return value :) return kStatusError; } int cvalue_len = static_cast<int>(cvalue.size()); int length = std::min(jvalue_len, cvalue_len); env->SetByteArrayRegion( jvalue, 0, length, reinterpret_cast<const jbyte*>(cvalue.c_str())); return cvalue_len; } jobject multi_get_helper(JNIEnv* env, jobject jdb, rocksdb::DB* db, const rocksdb::ReadOptions& rOpt, jobject jkey_list, jint jkeys_count) { std::vector<rocksdb::Slice> keys; std::vector<jbyte*> keys_to_free; // get iterator jobject iteratorObj = env->CallObjectMethod( jkey_list, rocksdb::ListJni::getIteratorMethod(env)); // iterate over keys and convert java byte array to slice while(env->CallBooleanMethod( iteratorObj, rocksdb::ListJni::getHasNextMethod(env)) == JNI_TRUE) { jbyteArray jkey = (jbyteArray) env->CallObjectMethod( iteratorObj, rocksdb::ListJni::getNextMethod(env)); jint key_length = env->GetArrayLength(jkey); jbyte* key = new jbyte[key_length]; env->GetByteArrayRegion(jkey, 0, key_length, key); // store allocated jbyte to free it after multiGet call keys_to_free.push_back(key); rocksdb::Slice key_slice( reinterpret_cast<char*>(key), key_length); keys.push_back(key_slice); } std::vector<std::string> values; std::vector<rocksdb::Status> s = db->MultiGet(rOpt, keys, &values); // Don't reuse class pointer jclass jclazz = env->FindClass("java/util/ArrayList"); jmethodID mid = rocksdb::ListJni::getArrayListConstructorMethodId( env, jclazz); jobject jvalue_list = env->NewObject(jclazz, mid, jkeys_count); // insert in java list for(std::vector<rocksdb::Status>::size_type i = 0; i != s.size(); i++) { if(s[i].ok()) { jbyteArray jvalue = env->NewByteArray(values[i].size()); env->SetByteArrayRegion( jvalue, 0, values[i].size(), reinterpret_cast<const jbyte*>(values[i].c_str())); env->CallBooleanMethod( jvalue_list, rocksdb::ListJni::getListAddMethodId(env), jvalue); } else { env->CallBooleanMethod( jvalue_list, rocksdb::ListJni::getListAddMethodId(env), nullptr); } } // free up allocated byte arrays for(std::vector<jbyte*>::size_type i = 0; i != keys_to_free.size(); i++) { delete[] keys_to_free[i]; } keys_to_free.clear(); return jvalue_list; } /* * Class: org_rocksdb_RocksDB * Method: multiGet * Signature: (JLjava/util/List;I)Ljava/util/List; */ jobject Java_org_rocksdb_RocksDB_multiGet__JLjava_util_List_2I( JNIEnv* env, jobject jdb, jlong jdb_handle, jobject jkey_list, jint jkeys_count) { return multi_get_helper(env, jdb, reinterpret_cast<rocksdb::DB*>(jdb_handle), rocksdb::ReadOptions(), jkey_list, jkeys_count); } /* * Class: org_rocksdb_RocksDB * Method: multiGet * Signature: (JJLjava/util/List;I)Ljava/util/List; */ jobject Java_org_rocksdb_RocksDB_multiGet__JJLjava_util_List_2I( JNIEnv* env, jobject jdb, jlong jdb_handle, jlong jropt_handle, jobject jkey_list, jint jkeys_count) { return multi_get_helper(env, jdb, reinterpret_cast<rocksdb::DB*>(jdb_handle), *reinterpret_cast<rocksdb::ReadOptions*>(jropt_handle), jkey_list, jkeys_count); } /* * Class: org_rocksdb_RocksDB * Method: get * Signature: (J[BI[BI)I */ jint Java_org_rocksdb_RocksDB_get__J_3BI_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jbyteArray jkey, jint jkey_len, jbyteArray jvalue, jint jvalue_len) { return rocksdb_get_helper(env, reinterpret_cast<rocksdb::DB*>(jdb_handle), rocksdb::ReadOptions(), jkey, jkey_len, jvalue, jvalue_len); } /* * Class: org_rocksdb_RocksDB * Method: get * Signature: (JJ[BI[BI)I */ jint Java_org_rocksdb_RocksDB_get__JJ_3BI_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jlong jropt_handle, jbyteArray jkey, jint jkey_len, jbyteArray jvalue, jint jvalue_len) { return rocksdb_get_helper(env, reinterpret_cast<rocksdb::DB*>(jdb_handle), *reinterpret_cast<rocksdb::ReadOptions*>(jropt_handle), jkey, jkey_len, jvalue, jvalue_len); } ////////////////////////////////////////////////////////////////////////////// // rocksdb::DB::Delete() void rocksdb_remove_helper( JNIEnv* env, rocksdb::DB* db, const rocksdb::WriteOptions& write_options, jbyteArray jkey, jint jkey_len) { jbyte* key = env->GetByteArrayElements(jkey, 0); rocksdb::Slice key_slice(reinterpret_cast<char*>(key), jkey_len); rocksdb::Status s = db->Delete(write_options, key_slice); // trigger java unref on key and value. // by passing JNI_ABORT, it will simply release the reference without // copying the result back to the java byte array. env->ReleaseByteArrayElements(jkey, key, JNI_ABORT); if (!s.ok()) { rocksdb::RocksDBExceptionJni::ThrowNew(env, s); } return; } /* * Class: org_rocksdb_RocksDB * Method: remove * Signature: (J[BI)V */ void Java_org_rocksdb_RocksDB_remove__J_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jbyteArray jkey, jint jkey_len) { auto db = reinterpret_cast<rocksdb::DB*>(jdb_handle); static const rocksdb::WriteOptions default_write_options = rocksdb::WriteOptions(); rocksdb_remove_helper(env, db, default_write_options, jkey, jkey_len); } /* * Class: org_rocksdb_RocksDB * Method: remove * Signature: (JJ[BI)V */ void Java_org_rocksdb_RocksDB_remove__JJ_3BI( JNIEnv* env, jobject jdb, jlong jdb_handle, jlong jwrite_options, jbyteArray jkey, jint jkey_len) { auto db = reinterpret_cast<rocksdb::DB*>(jdb_handle); auto write_options = reinterpret_cast<rocksdb::WriteOptions*>(jwrite_options); rocksdb_remove_helper(env, db, *write_options, jkey, jkey_len); } ////////////////////////////////////////////////////////////////////////////// // rocksdb::DB::~DB() /* * Class: org_rocksdb_RocksDB * Method: disposeInternal * Signature: (J)V */ void Java_org_rocksdb_RocksDB_disposeInternal( JNIEnv* env, jobject java_db, jlong jhandle) { delete reinterpret_cast<rocksdb::DB*>(jhandle); } /* * Class: org_rocksdb_RocksDB * Method: iterator0 * Signature: (J)J */ jlong Java_org_rocksdb_RocksDB_iterator0( JNIEnv* env, jobject jdb, jlong db_handle) { auto db = reinterpret_cast<rocksdb::DB*>(db_handle); rocksdb::Iterator* iterator = db->NewIterator(rocksdb::ReadOptions()); return reinterpret_cast<jlong>(iterator); }
31.934579
80
0.677349
Py9595
f553f5efe7d4e0ff79f30408953876cb3c400939
3,924
cpp
C++
WonderBrush/src/tools/transform/ObjectSelection.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
11
2018-11-10T11:14:11.000Z
2021-12-27T17:17:08.000Z
WonderBrush/src/tools/transform/ObjectSelection.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
27
2018-11-11T00:06:25.000Z
2021-06-24T06:43:38.000Z
WonderBrush/src/tools/transform/ObjectSelection.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
7
2018-11-10T20:32:49.000Z
2021-03-15T18:03:42.000Z
// ObjectSelection.cpp #include <stdio.h> #include <string.h> #include "Stroke.h" #include "TransformState.h" #include "TransformAction.h" #include "ObjectSelection.h" // constructor ObjectSelection::ObjectSelection(CanvasView* view, TransformState* state, Stroke** objects, int32 count) : TransformBox(view, BRect(0.0, 0.0, 1.0, 1.0)), fTransformState(state), fObjects(objects && count > 0 ? new Stroke*[count] : NULL), fCount(count), fOriginals(NULL) { BRect box(0.0, 0.0, -1.0, -1.0); if (fObjects) { // allocate storage for the current transformations // of each object fOriginals = new double[fCount * 9]; // figure out bounds and init transformations for (int32 i = 0; i < fCount; i++) { fObjects[i] = objects[i]; if (fObjects[i]) { fObjects[i]->AddObserver(this); box = !box.IsValid() ? objects[i]->Bounds() : box | objects[i]->Bounds(); fObjects[i]->StoreTo(&fOriginals[i * 9]); } } } // offset box to middle of pixels // box.OffsetBy(0.5, 0.5); SetBox(box); } // copy constructor ObjectSelection::ObjectSelection(const ObjectSelection& other) : TransformBox(other), fTransformState(other.fTransformState), fObjects(other.fCount > 0 ? new Stroke*[other.fCount] : NULL), fCount(other.fCount), fOriginals(fCount > 0 ? new double[fCount * 9] : NULL) { if (fObjects) { memcpy(fObjects, other.fObjects, fCount * sizeof(Stroke*)); for (int32 i = 0; i < fCount; i++) { if (fObjects[i]) { fObjects[i]->AddObserver(this); } } } if (fOriginals) { memcpy(fOriginals, other.fOriginals, fCount * sizeof(double) * 9); } } // destructor ObjectSelection::~ObjectSelection() { for (int32 i = 0; i < fCount; i++) { if (fObjects[i]) { fObjects[i]->RemoveObserver(this); } } delete[] fObjects; delete[] fOriginals; } // Bounds BRect ObjectSelection::Bounds() const { return TransformBox::Bounds(); } // Update void ObjectSelection::Update(bool deep) { // remember current bounds BRect r = Bounds(); TransformBox::Update(deep); if (deep) { BRect rebuildArea = r; if (fObjects) { for (int32 i = 0; i < fCount; i++) { if (fObjects[i]) { // reset the objects transformation to the saved state fObjects[i]->RemoveObserver(this); fObjects[i]->LoadFrom(&fOriginals[i * 9]); // combined with the current transformation fObjects[i]->Multiply(*this); fObjects[i]->AddObserver(this); rebuildArea = rebuildArea | fObjects[i]->Bounds(); } } } fTransformState->_RebuildLayer(rebuildArea); } r = r | Bounds(); fTransformState->_InvalidateCanvasRect(r); } // ObjectChanged void ObjectSelection::ObjectChanged(const Observable* object) { printf("ObjectSelection::ObjectChanged()\n"); // recalc bounds BRect box(0.0, 0.0, -1.0, -1.0); // figure out bounds and init transformations for (int32 i = 0; i < fCount; i++) { if (fObjects[i]) { // reset the objects transformation to the saved state fObjects[i]->RemoveObserver(this); fObjects[i]->LoadFrom(&fOriginals[i * 9]); box = !box.IsValid() ? fObjects[i]->Bounds() : box | fObjects[i]->Bounds(); // combined with the current transformation fObjects[i]->Multiply(*this); fObjects[i]->AddObserver(this); } } // update with the changed box SetBox(box); } // Perform Action* ObjectSelection::Perform() { return NULL; } // Cancel Action* ObjectSelection::Cancel() { SetTransformation(BPoint(0.0, 0.0), 0.0, 1.0, 1.0); return NULL; } // MakeAction TransformAction* ObjectSelection::MakeAction(const char* actionName, uint32 nameIndex) const { TransformAction* action = // fTransformState->ChangeTransformation(Translation(),LocalRotation(), // LocalXScale(),LocalYScale(), fTransformState->ChangeTransformation(*this, CenterOffset(), true); if (action) action->SetName(actionName, nameIndex); return action; }
22.422857
75
0.657492
waddlesplash
f554b74cb93f2e31cd0f27cb323cc21fa402db5a
505
cpp
C++
InterviewBit/ValidBinarySearchTree.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
InterviewBit/ValidBinarySearchTree.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
null
null
null
InterviewBit/ValidBinarySearchTree.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
2
2021-01-23T14:35:48.000Z
2021-03-15T05:04:24.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ int isBST(TreeNode *root, int min, int max) { if (root == NULL) { return 1; } if (root->val < min || root->val > max) { return 0; } return isBST(root->left, min, root->val - 1) && isBST(root->right, root->val + 1, max); } int Solution::isValidBST(TreeNode *root) { return isBST(root, INT_MIN, INT_MAX); }
21.041667
88
0.586139
Code-With-Aagam
f556a8b4605b18d3341f0a8ef4cb758604d7d134
56,427
hpp
C++
yactfr/internal/proc.hpp
eepp/yactfr
5cec5680d025d82a4f175ffc19c0704b32ef529f
[ "MIT" ]
7
2016-08-26T14:20:06.000Z
2022-02-03T21:17:25.000Z
yactfr/internal/proc.hpp
eepp/yactfr
5cec5680d025d82a4f175ffc19c0704b32ef529f
[ "MIT" ]
2
2018-05-29T17:43:37.000Z
2018-05-30T18:38:39.000Z
yactfr/internal/proc.hpp
eepp/yactfr
5cec5680d025d82a4f175ffc19c0704b32ef529f
[ "MIT" ]
null
null
null
/* * Copyright (C) 2016-2022 Philippe Proulx <eepp.ca> * * This software may be modified and distributed under the terms of the * MIT license. See the LICENSE file for details. */ /* * Here are the possible instructions for the yactfr VM. * * No numeric bytecode is involved here: the VM deals with a sequence of * procedure instruction objects, some of them also containing a * subprocedure, and so on. * * Some definitions: * * Procedure: * A sequence of procedure instructions. * * Subprocedure: * A procedure contained in a procedure instruction. * * Procedure instruction: * An instruction for the yactfr VM, possibly containing one or * more subprocedures. * * The top-level procedure is a `PktProc`. A `PktProc` object contains * all the instructions to apply for a whole packet. * * At the beginning of a packet: * * * Execute the preamble procedure of the packet procedure. * * A `DsPktProc` object contains the instructions to execute after the * preamble procedure of the packet procedure for any data stream of a * specific type. * * To execute a data stream packet procedure: * * 1. Execute the per-packet preamble procedure. * * 2. Until the end of the packet, repeat: * * a) Execute the common event record preamble procedure. * * b) Depending on the chosen event record type, execute the * corresponding event record procedure (`ErProc`). * * An `ErProc` object contains a single procedure, that is, the * instructions to execute after the common event record preamble * procedure of its parent `DsPktProc`. * * Details such as how to choose the current data stream and event * record types, and how to determine the end of the packet, are left to * the implementation of the VM. */ #ifndef _YACTFR_INTERNAL_PROC_HPP #define _YACTFR_INTERNAL_PROC_HPP #include <cstdlib> #include <cassert> #include <sstream> #include <list> #include <vector> #include <utility> #include <functional> #include <type_traits> #include <boost/optional/optional.hpp> #include <yactfr/aliases.hpp> #include <yactfr/metadata/dt.hpp> #include <yactfr/metadata/fl-bit-array-type.hpp> #include <yactfr/metadata/fl-bool-type.hpp> #include <yactfr/metadata/fl-int-type.hpp> #include <yactfr/metadata/fl-float-type.hpp> #include <yactfr/metadata/fl-enum-type.hpp> #include <yactfr/metadata/nt-str-type.hpp> #include <yactfr/metadata/struct-type.hpp> #include <yactfr/metadata/sl-array-type.hpp> #include <yactfr/metadata/dl-array-type.hpp> #include <yactfr/metadata/sl-str-type.hpp> #include <yactfr/metadata/dl-str-type.hpp> #include <yactfr/metadata/sl-blob-type.hpp> #include <yactfr/metadata/dl-blob-type.hpp> #include <yactfr/metadata/var-type.hpp> #include <yactfr/metadata/opt-type.hpp> #include <yactfr/metadata/clk-type.hpp> #include <yactfr/metadata/ert.hpp> #include <yactfr/metadata/dst.hpp> #include <yactfr/metadata/trace-type.hpp> #include "utils.hpp" namespace yactfr { namespace internal { class BeginReadDlArrayInstr; class BeginReadDlStrInstr; class BeginReadScopeInstr; class BeginReadSlArrayInstr; class BeginReadSlStrInstr; class BeginReadSlUuidArrayInstr; class BeginReadDlBlobInstr; class BeginReadSlBlobInstr; class BeginReadSlUuidBlobInstr; class BeginReadStructInstr; class BeginReadVarSIntSelInstr; class BeginReadVarUIntSelInstr; class BeginReadOptBoolSelInstr; class BeginReadOptUIntSelInstr; class BeginReadOptSIntSelInstr; class DecrRemainingElemsInstr; class EndDsErPreambleProcInstr; class EndDsPktPreambleProcInstr; class EndErProcInstr; class EndPktPreambleProcInstr; class EndReadDataInstr; class EndReadScopeInstr; class Instr; class ReadDataInstr; class ReadFlBitArrayInstr; class ReadFlBoolInstr; class ReadFlFloatInstr; class ReadFlSEnumInstr; class ReadFlSIntInstr; class ReadNtStrInstr; class ReadFlUEnumInstr; class ReadFlUIntInstr; class ReadVlBitArrayInstr; class SaveValInstr; class SetCurIdInstr; class SetDsIdInstr; class SetDstInstr; class SetDsInfoInstr; class SetErtInstr; class SetErInfoInstr; class SetExpectedPktContentLenInstr; class SetPktEndDefClkValInstr; class SetPktMagicNumberInstr; class SetPktSeqNumInstr; class SetPktDiscErCounterSnapInstr; class SetExpectedPktTotalLenInstr; class SetPktInfoInstr; class UpdateDefClkValInstr; /* * A classic abstract visitor class for procedure instructions. * * Used by `PktProcBuilder`, NOT by the VM. */ class InstrVisitor { protected: explicit InstrVisitor() = default; public: virtual ~InstrVisitor() = default; virtual void visit(ReadFlBitArrayInstr&) { } virtual void visit(ReadFlBoolInstr&) { } virtual void visit(ReadFlSIntInstr&) { } virtual void visit(ReadFlUIntInstr&) { } virtual void visit(ReadFlFloatInstr&) { } virtual void visit(ReadFlSEnumInstr&) { } virtual void visit(ReadFlUEnumInstr&) { } virtual void visit(ReadVlBitArrayInstr&) { } virtual void visit(ReadNtStrInstr&) { } virtual void visit(BeginReadScopeInstr&) { } virtual void visit(EndReadScopeInstr&) { } virtual void visit(BeginReadStructInstr&) { } virtual void visit(BeginReadSlArrayInstr&) { } virtual void visit(BeginReadSlUuidArrayInstr&) { } virtual void visit(BeginReadDlArrayInstr&) { } virtual void visit(BeginReadSlStrInstr&) { } virtual void visit(BeginReadDlStrInstr&) { } virtual void visit(BeginReadSlBlobInstr&) { } virtual void visit(BeginReadSlUuidBlobInstr&) { } virtual void visit(BeginReadDlBlobInstr&) { } virtual void visit(BeginReadVarUIntSelInstr&) { } virtual void visit(BeginReadVarSIntSelInstr&) { } virtual void visit(BeginReadOptBoolSelInstr&) { } virtual void visit(BeginReadOptUIntSelInstr&) { } virtual void visit(BeginReadOptSIntSelInstr&) { } virtual void visit(EndReadDataInstr&) { } virtual void visit(UpdateDefClkValInstr&) { } virtual void visit(SetCurIdInstr&) { } virtual void visit(SetDstInstr&) { } virtual void visit(SetErtInstr&) { } virtual void visit(SetErInfoInstr&) { } virtual void visit(SetDsIdInstr&) { } virtual void visit(SetDsInfoInstr&) { } virtual void visit(SetPktSeqNumInstr&) { } virtual void visit(SetPktDiscErCounterSnapInstr&) { } virtual void visit(SetExpectedPktTotalLenInstr&) { } virtual void visit(SetExpectedPktContentLenInstr&) { } virtual void visit(SaveValInstr&) { } virtual void visit(SetPktEndDefClkValInstr&) { } virtual void visit(SetPktInfoInstr&) { } virtual void visit(SetPktMagicNumberInstr&) { } virtual void visit(EndPktPreambleProcInstr&) { } virtual void visit(EndDsPktPreambleProcInstr&) { } virtual void visit(EndDsErPreambleProcInstr&) { } virtual void visit(EndErProcInstr&) { } virtual void visit(DecrRemainingElemsInstr&) { } }; /* * A procedure, that is, a sequence of instructions. * * The procedure is first built as a list of shared pointers because the * build process needs to insert and replace instructions and it's * easier with a linked list. * * Then, when the build is complete, we call buildRawProcFromShared() * which builds a vector of raw instruction object (weak) pointers from * the list of shared pointers. The list must remain alive as it keeps * the instructions alive. Going from raw pointer to raw pointer in a * vector seems more efficient than going from shared pointer to shared * pointer in a linked list. I did not measure the difference yet * however. * * Instructions are shared because sometimes they are reused, for * example multiple range procedures of a `BeginReadVarInstr` * instruction can refer to the exact same instructions. */ class Proc final { public: using Raw = std::vector<const Instr *>; using Shared = std::list<std::shared_ptr<Instr>>; using RawIt = Raw::const_iterator; using SharedIt = Shared::iterator; public: void buildRawProcFromShared(); std::string toStr(Size indent = 0) const; void pushBack(std::shared_ptr<Instr> instr); SharedIt insert(SharedIt it, std::shared_ptr<Instr> instr); Shared& sharedProc() noexcept { return _sharedProc; } const Shared& sharedProc() const noexcept { return _sharedProc; } const Raw& rawProc() const noexcept { return _rawProc; } SharedIt begin() noexcept { return _sharedProc.begin(); } SharedIt end() noexcept { return _sharedProc.end(); } private: Raw _rawProc; Shared _sharedProc; }; /* * A pair of procedure and instruction iterator. */ struct InstrLoc final { Proc::Shared *proc = nullptr; Proc::Shared::iterator it; }; /* * List of instruction locations. */ using InstrLocs = std::vector<InstrLoc>; /* * Procedure instruction abstract class. */ class Instr { public: // kind of instruction (opcode) enum class Kind : unsigned int { UNSET, BEGIN_READ_DL_ARRAY, BEGIN_READ_DL_STR, BEGIN_READ_DL_BLOB, BEGIN_READ_SCOPE, BEGIN_READ_SL_ARRAY, BEGIN_READ_SL_STR, BEGIN_READ_SL_UUID_ARRAY, BEGIN_READ_SL_BLOB, BEGIN_READ_SL_UUID_BLOB, BEGIN_READ_STRUCT, BEGIN_READ_VAR_SINT_SEL, BEGIN_READ_VAR_UINT_SEL, BEGIN_READ_OPT_BOOL_SEL, BEGIN_READ_OPT_SINT_SEL, BEGIN_READ_OPT_UINT_SEL, DECR_REMAINING_ELEMS, END_DS_ER_PREAMBLE_PROC, END_DS_PKT_PREAMBLE_PROC, END_ER_PROC, END_PKT_PREAMBLE_PROC, END_READ_SL_ARRAY, END_READ_DL_ARRAY, END_READ_SCOPE, END_READ_SL_STR, END_READ_DL_STR, END_READ_SL_BLOB, END_READ_DL_BLOB, END_READ_STRUCT, END_READ_VAR_SINT_SEL, END_READ_VAR_UINT_SEL, END_READ_OPT_BOOL_SEL, END_READ_OPT_SINT_SEL, END_READ_OPT_UINT_SEL, READ_FL_BIT_ARRAY_A16_BE, READ_FL_BIT_ARRAY_A16_LE, READ_FL_BIT_ARRAY_A32_BE, READ_FL_BIT_ARRAY_A32_LE, READ_FL_BIT_ARRAY_A64_BE, READ_FL_BIT_ARRAY_A64_LE, READ_FL_BIT_ARRAY_A8, READ_FL_BIT_ARRAY_BE, READ_FL_BIT_ARRAY_LE, READ_FL_FLOAT_32_BE, READ_FL_FLOAT_32_LE, READ_FL_FLOAT_64_BE, READ_FL_FLOAT_64_LE, READ_FL_FLOAT_A32_BE, READ_FL_FLOAT_A32_LE, READ_FL_FLOAT_A64_BE, READ_FL_FLOAT_A64_LE, READ_FL_SENUM_A16_BE, READ_FL_SENUM_A16_LE, READ_FL_SENUM_A32_BE, READ_FL_SENUM_A32_LE, READ_FL_SENUM_A64_BE, READ_FL_SENUM_A64_LE, READ_FL_SENUM_A8, READ_FL_SENUM_BE, READ_FL_SENUM_LE, READ_FL_SINT_A16_BE, READ_FL_SINT_A16_LE, READ_FL_SINT_A32_BE, READ_FL_SINT_A32_LE, READ_FL_SINT_A64_BE, READ_FL_SINT_A64_LE, READ_FL_SINT_A8, READ_FL_SINT_BE, READ_FL_SINT_LE, READ_NT_STR, READ_FL_UENUM_A16_BE, READ_FL_UENUM_A16_LE, READ_FL_UENUM_A32_BE, READ_FL_UENUM_A32_LE, READ_FL_UENUM_A64_BE, READ_FL_UENUM_A64_LE, READ_FL_UENUM_A8, READ_FL_UENUM_BE, READ_FL_UENUM_LE, READ_FL_UINT_A16_BE, READ_FL_UINT_A16_LE, READ_FL_UINT_A32_BE, READ_FL_UINT_A32_LE, READ_FL_UINT_A64_BE, READ_FL_UINT_A64_LE, READ_FL_UINT_A8, READ_FL_UINT_BE, READ_FL_UINT_LE, READ_FL_BOOL_A16_BE, READ_FL_BOOL_A16_LE, READ_FL_BOOL_A32_BE, READ_FL_BOOL_A32_LE, READ_FL_BOOL_A64_BE, READ_FL_BOOL_A64_LE, READ_FL_BOOL_A8, READ_FL_BOOL_BE, READ_FL_BOOL_LE, READ_VL_BIT_ARRAY, READ_VL_UINT, READ_VL_SINT, READ_VL_UENUM, READ_VL_SENUM, SAVE_VAL, SET_CUR_ID, SET_DS_ID, SET_DS_INFO, SET_DST, SET_ERT, SET_ER_INFO, SET_PKT_CONTENT_LEN, SET_PKT_END_DEF_CLK_VAL, SET_PKT_MAGIC_NUMBER, SET_PKT_SEQ_NUM, SET_PKT_DISC_ER_COUNTER_SNAP, SET_PKT_TOTAL_LEN, SET_PKT_INFO, UPDATE_DEF_CLK_VAL, UPDATE_DEF_CLK_VAL_FL, }; public: using SP = std::shared_ptr<Instr>; using FindInstrsCurrent = std::unordered_map<const Instr *, Index>; protected: explicit Instr() noexcept = default; explicit Instr(Kind kind) noexcept; public: virtual ~Instr() = default; virtual void accept(InstrVisitor& visitor) = 0; virtual void buildRawProcFromShared(); // only used for debugging purposes std::string toStr(Size indent = 0) const; // only used to debug and for assertions bool isBeginReadData() const noexcept { switch (_theKind) { case Instr::Kind::BEGIN_READ_DL_ARRAY: case Instr::Kind::BEGIN_READ_DL_STR: case Instr::Kind::BEGIN_READ_DL_BLOB: case Instr::Kind::BEGIN_READ_SCOPE: case Instr::Kind::BEGIN_READ_SL_ARRAY: case Instr::Kind::BEGIN_READ_SL_STR: case Instr::Kind::BEGIN_READ_SL_UUID_ARRAY: case Instr::Kind::BEGIN_READ_SL_BLOB: case Instr::Kind::BEGIN_READ_SL_UUID_BLOB: case Instr::Kind::BEGIN_READ_STRUCT: case Instr::Kind::BEGIN_READ_VAR_SINT_SEL: case Instr::Kind::BEGIN_READ_VAR_UINT_SEL: case Instr::Kind::BEGIN_READ_OPT_BOOL_SEL: case Instr::Kind::BEGIN_READ_OPT_SINT_SEL: case Instr::Kind::BEGIN_READ_OPT_UINT_SEL: case Instr::Kind::READ_FL_BIT_ARRAY_A16_BE: case Instr::Kind::READ_FL_BIT_ARRAY_A16_LE: case Instr::Kind::READ_FL_BIT_ARRAY_A32_BE: case Instr::Kind::READ_FL_BIT_ARRAY_A32_LE: case Instr::Kind::READ_FL_BIT_ARRAY_A64_BE: case Instr::Kind::READ_FL_BIT_ARRAY_A64_LE: case Instr::Kind::READ_FL_BIT_ARRAY_A8: case Instr::Kind::READ_FL_BIT_ARRAY_BE: case Instr::Kind::READ_FL_BIT_ARRAY_LE: case Instr::Kind::READ_FL_FLOAT_32_BE: case Instr::Kind::READ_FL_FLOAT_32_LE: case Instr::Kind::READ_FL_FLOAT_64_BE: case Instr::Kind::READ_FL_FLOAT_64_LE: case Instr::Kind::READ_FL_FLOAT_A32_BE: case Instr::Kind::READ_FL_FLOAT_A32_LE: case Instr::Kind::READ_FL_FLOAT_A64_BE: case Instr::Kind::READ_FL_FLOAT_A64_LE: case Instr::Kind::READ_FL_SENUM_A16_BE: case Instr::Kind::READ_FL_SENUM_A16_LE: case Instr::Kind::READ_FL_SENUM_A32_BE: case Instr::Kind::READ_FL_SENUM_A32_LE: case Instr::Kind::READ_FL_SENUM_A64_BE: case Instr::Kind::READ_FL_SENUM_A64_LE: case Instr::Kind::READ_FL_SENUM_A8: case Instr::Kind::READ_FL_SENUM_BE: case Instr::Kind::READ_FL_SENUM_LE: case Instr::Kind::READ_FL_SINT_A16_BE: case Instr::Kind::READ_FL_SINT_A16_LE: case Instr::Kind::READ_FL_SINT_A32_BE: case Instr::Kind::READ_FL_SINT_A32_LE: case Instr::Kind::READ_FL_SINT_A64_BE: case Instr::Kind::READ_FL_SINT_A64_LE: case Instr::Kind::READ_FL_SINT_A8: case Instr::Kind::READ_FL_SINT_BE: case Instr::Kind::READ_FL_SINT_LE: case Instr::Kind::READ_NT_STR: case Instr::Kind::READ_FL_UENUM_A16_BE: case Instr::Kind::READ_FL_UENUM_A16_LE: case Instr::Kind::READ_FL_UENUM_A32_BE: case Instr::Kind::READ_FL_UENUM_A32_LE: case Instr::Kind::READ_FL_UENUM_A64_BE: case Instr::Kind::READ_FL_UENUM_A64_LE: case Instr::Kind::READ_FL_UENUM_A8: case Instr::Kind::READ_FL_UENUM_BE: case Instr::Kind::READ_FL_UENUM_LE: case Instr::Kind::READ_FL_UINT_A16_BE: case Instr::Kind::READ_FL_UINT_A16_LE: case Instr::Kind::READ_FL_UINT_A32_BE: case Instr::Kind::READ_FL_UINT_A32_LE: case Instr::Kind::READ_FL_UINT_A64_BE: case Instr::Kind::READ_FL_UINT_A64_LE: case Instr::Kind::READ_FL_UINT_A8: case Instr::Kind::READ_FL_UINT_BE: case Instr::Kind::READ_FL_UINT_LE: case Instr::Kind::READ_FL_BOOL_A16_BE: case Instr::Kind::READ_FL_BOOL_A16_LE: case Instr::Kind::READ_FL_BOOL_A32_BE: case Instr::Kind::READ_FL_BOOL_A32_LE: case Instr::Kind::READ_FL_BOOL_A64_BE: case Instr::Kind::READ_FL_BOOL_A64_LE: case Instr::Kind::READ_FL_BOOL_A8: case Instr::Kind::READ_FL_BOOL_BE: case Instr::Kind::READ_FL_BOOL_LE: case Instr::Kind::READ_VL_BIT_ARRAY: case Instr::Kind::READ_VL_UINT: case Instr::Kind::READ_VL_SINT: case Instr::Kind::READ_VL_UENUM: case Instr::Kind::READ_VL_SENUM: return true; default: return false; } } // only used to debug and for assertions bool isEndReadData() const noexcept { switch (_theKind) { case Instr::Kind::END_READ_SL_ARRAY: case Instr::Kind::END_READ_DL_ARRAY: case Instr::Kind::END_READ_SL_STR: case Instr::Kind::END_READ_DL_STR: case Instr::Kind::END_READ_SL_BLOB: case Instr::Kind::END_READ_DL_BLOB: case Instr::Kind::END_READ_STRUCT: case Instr::Kind::END_READ_VAR_SINT_SEL: case Instr::Kind::END_READ_VAR_UINT_SEL: case Instr::Kind::END_READ_OPT_BOOL_SEL: case Instr::Kind::END_READ_OPT_SINT_SEL: case Instr::Kind::END_READ_OPT_UINT_SEL: return true; default: return false; } } Kind kind() const noexcept { assert(_theKind != Kind::UNSET); return _theKind; } private: virtual std::string _toStr(Size indent = 0) const; private: const Kind _theKind = Kind::UNSET; }; /* * "Read data" procedure instruction abstract class. */ class ReadDataInstr : public Instr { protected: explicit ReadDataInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: /* * `memberType` can be `nullptr` if this is the scope's root read * instruction. */ explicit ReadDataInstr(const StructureMemberType *memberType, const DataType& dt); const DataType& dt() const noexcept { return *_dt; } const StructureMemberType *memberType() const noexcept { return _memberType; } unsigned int align() const noexcept { return _align; } protected: std::string _commonToStr() const; private: const StructureMemberType * const _memberType; const DataType * const _dt; const unsigned int _align; }; /* * "Save value" procedure instruction. * * This instruction requires the VM to save the last decoded integer * value to a position (index) in its saved value vector so that it can * be used later (for the length of a dynamic-length array/string/BLOB * or for the selector of a variant/optional). */ class SaveValInstr final : public Instr { public: explicit SaveValInstr(Index pos); Index pos() const noexcept { return _pos; } void pos(const Index pos) noexcept { _pos = pos; } void accept(InstrVisitor& visitor) override { visitor.visit(*this); } private: std::string _toStr(Size indent = 0) const override; private: Index _pos; }; /* * "Set packet end clock value" procedure instruction. * * This instruction indicates to the VM that the last decoded integer * value is the packet end clock value. */ class SetPktEndDefClkValInstr final : public Instr { public: explicit SetPktEndDefClkValInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Read fixed-length bit array" procedure instruction. */ class ReadFlBitArrayInstr : public ReadDataInstr { protected: explicit ReadFlBitArrayInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: explicit ReadFlBitArrayInstr(const StructureMemberType *memberType, const DataType& dt); unsigned int len() const noexcept { return _len; } ByteOrder bo() const noexcept { return _bo; } void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const FixedLengthBitArrayType& flBitArrayType() const noexcept { return static_cast<const FixedLengthBitArrayType&>(this->dt()); } protected: std::string _commonToStr() const; private: std::string _toStr(const Size indent = 0) const override; private: const unsigned int _len; const ByteOrder _bo; }; /* * "Read fixed-length boolean" procedure instruction. */ class ReadFlBoolInstr : public ReadFlBitArrayInstr { public: explicit ReadFlBoolInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const FixedLengthBooleanType& boolType() const noexcept { return static_cast<const FixedLengthBooleanType&>(this->dt()); } }; /* * "Read fixed-length integer" procedure instruction. */ class ReadFlIntInstr : public ReadFlBitArrayInstr { protected: explicit ReadFlIntInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: explicit ReadFlIntInstr(const StructureMemberType *memberType, const DataType& dt); const FixedLengthIntegerType& intType() const noexcept { return static_cast<const FixedLengthIntegerType&>(this->dt()); } }; /* * "Read fixed-length signed integer" procedure instruction. */ class ReadFlSIntInstr : public ReadFlIntInstr { protected: explicit ReadFlSIntInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: explicit ReadFlSIntInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const FixedLengthSignedIntegerType& sIntType() const noexcept { return static_cast<const FixedLengthSignedIntegerType&>(this->dt()); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Read fixed-length unsigned integer" procedure instruction. */ class ReadFlUIntInstr : public ReadFlIntInstr { protected: explicit ReadFlUIntInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: explicit ReadFlUIntInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const FixedLengthUnsignedIntegerType& uIntType() const noexcept { return static_cast<const FixedLengthUnsignedIntegerType&>(this->dt()); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Read fixed-length floating point number" procedure instruction. */ class ReadFlFloatInstr final : public ReadFlBitArrayInstr { public: explicit ReadFlFloatInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const FixedLengthFloatingPointNumberType& floatType() const noexcept { return static_cast<const FixedLengthFloatingPointNumberType&>(this->dt()); } }; /* * "Read fixed-length signed enumeration" procedure instruction. */ class ReadFlSEnumInstr final : public ReadFlSIntInstr { public: explicit ReadFlSEnumInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const FixedLengthSignedEnumerationType& sEnumType() const noexcept { return static_cast<const FixedLengthSignedEnumerationType&>(this->dt()); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Read fixed-length unsigned enumeration" procedure instruction. */ class ReadFlUEnumInstr final : public ReadFlUIntInstr { public: explicit ReadFlUEnumInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const FixedLengthUnsignedEnumerationType& uEnumType() const noexcept { return static_cast<const FixedLengthUnsignedEnumerationType&>(this->dt()); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Read variable-length bit array" procedure instruction. */ class ReadVlBitArrayInstr : public ReadDataInstr { public: explicit ReadVlBitArrayInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const VariableLengthBitArrayType& vlBitArrayType() const noexcept { return static_cast<const VariableLengthBitArrayType&>(this->dt()); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Read null-terminated string" procedure instruction. */ class ReadNtStrInstr final : public ReadDataInstr { public: explicit ReadNtStrInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const NullTerminatedStringType& strType() const noexcept { return static_cast<const NullTerminatedStringType&>(this->dt()); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Begin reading compound data" procedure instruction abstract class. * * This instruction contains a subprocedure to execute. */ class BeginReadCompoundInstr : public ReadDataInstr { protected: explicit BeginReadCompoundInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: const Proc& proc() const noexcept { return _proc; } Proc& proc() noexcept { return _proc; } void buildRawProcFromShared() override; protected: std::string _procToStr(const Size indent) const { return _proc.toStr(indent); } private: Proc _proc; }; /* * "End reading data" procedure instruction. * * If the kind of this instruction is `END_READ_STRUCT`, then the VM * must stop executing the current procedure and continue executing the * parent procedure. * * For all instruction kinds, this instruction requires the VM to set an * `EndElement` as the current element. */ class EndReadDataInstr : public ReadDataInstr { public: explicit EndReadDataInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Begin reading structure" procedure instruction. */ class BeginReadStructInstr final : public BeginReadCompoundInstr { public: explicit BeginReadStructInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const StructureType& structType() const noexcept { return static_cast<const StructureType&>(this->dt()); } private: std::string _toStr(Size indent = 0) const override; }; /* * "Begin reading scope" procedure instruction. * * This is the top-level instruction to start reading a whole scope * (packet header, packet context, event record payload, etc.). */ class BeginReadScopeInstr final : public Instr { public: explicit BeginReadScopeInstr(Scope scope, unsigned int align); void buildRawProcFromShared() override; void accept(InstrVisitor& visitor) override { visitor.visit(*this); } Scope scope() const noexcept { return _scope; } const Proc& proc() const noexcept { return _proc; } Proc& proc() noexcept { return _proc; } unsigned int align() const noexcept { return _align; } private: std::string _toStr(Size indent = 0) const override; private: const Scope _scope; const unsigned int _align = 1; Proc _proc; }; /* * "End reading scope" procedure instruction. * * This requires the VM to stop executing the current procedure and * continue executing the parent procedure. */ class EndReadScopeInstr final : public Instr { public: explicit EndReadScopeInstr(Scope scope); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } Scope scope() const noexcept { return _scope; } private: std::string _toStr(Size indent = 0) const override; private: const Scope _scope; }; /* * "Begin reading static-length array" procedure instruction. * * The VM must execute the subprocedure `len()` times. */ class BeginReadSlArrayInstr : public BeginReadCompoundInstr { protected: explicit BeginReadSlArrayInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: explicit BeginReadSlArrayInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const StaticLengthArrayType& slArrayType() const noexcept { return static_cast<const StaticLengthArrayType&>(this->dt()); } Size len() const noexcept { return _len; } private: std::string _toStr(Size indent = 0) const override; private: const Size _len; }; /* * "Begin reading static-length string" procedure instruction. * * maxLen() indicates the maximum length (bytes) of the static-length * string to read. */ class BeginReadSlStrInstr final : public ReadDataInstr { public: explicit BeginReadSlStrInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const StaticLengthStringType& slStrType() const noexcept { return static_cast<const StaticLengthStringType&>(this->dt()); } Size maxLen() const noexcept { return _maxLen; } private: std::string _toStr(Size indent = 0) const override; private: const Size _maxLen; }; /* * "Begin reading static-length UUID array" procedure instruction. * * This is a specialized instruction to read the 16 trace type UUID * bytes of a packet header to emit `TraceTypeUuidElement`. */ class BeginReadSlUuidArrayInstr final : public BeginReadSlArrayInstr { public: explicit BeginReadSlUuidArrayInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Begin reading dynamic-length array" procedure instruction. * * The VM must use lenPos() to retrieve the saved value which contains * the length of the dynamic-length array, and then execute the * subprocedure this number of times. */ class BeginReadDlArrayInstr final : public BeginReadCompoundInstr { public: explicit BeginReadDlArrayInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const DynamicLengthArrayType& dlArrayType() const noexcept { return static_cast<const DynamicLengthArrayType&>(this->dt()); } Index lenPos() const noexcept { return _lenPos; } void lenPos(const Index lenPos) noexcept { _lenPos = lenPos; } private: std::string _toStr(Size indent = 0) const override; private: Index _lenPos = UINT64_C(-1); }; /* * "Begin reading dynamic-length string" procedure instruction. * * The VM must use maxLenPos() to retrieve the saved value which * contains the maximum length (bytes) of the dynamic-length string. */ class BeginReadDlStrInstr final : public ReadDataInstr { public: explicit BeginReadDlStrInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const DynamicLengthStringType& dlStrType() const noexcept { return static_cast<const DynamicLengthStringType&>(this->dt()); } Index maxLenPos() const noexcept { return _maxLenPos; } void maxLenPos(const Index maxLenPos) noexcept { _maxLenPos = maxLenPos; } private: std::string _toStr(Size indent = 0) const override; private: Index _maxLenPos = UINT64_C(-1); }; /* * "Begin reading static-length BLOB" procedure instruction. * * len() indicates the length (bytes) of the static-length BLOB to read. */ class BeginReadSlBlobInstr : public ReadDataInstr { protected: explicit BeginReadSlBlobInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: explicit BeginReadSlBlobInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const StaticLengthBlobType& slBlobType() const noexcept { return static_cast<const StaticLengthBlobType&>(this->dt()); } Size len() const noexcept { return _len; } private: std::string _toStr(Size indent = 0) const override; private: const Size _len; }; /* * "Begin reading static-length UUID BLOB" procedure instruction. * * This is a specialized instruction to read the 16 UUID bytes of a * packet header to emit `TraceTypeUuidElement`. */ class BeginReadSlUuidBlobInstr final : public BeginReadSlBlobInstr { public: explicit BeginReadSlUuidBlobInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Begin reading dynamic-length BLOB" procedure instruction. * * The VM must use lenPos() to retrieve the saved value which contains * the length (bytes) of the dynamic-length BLOB. */ class BeginReadDlBlobInstr final : public ReadDataInstr { public: explicit BeginReadDlBlobInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } const DynamicLengthBlobType& dlBlobType() const noexcept { return static_cast<const DynamicLengthBlobType&>(this->dt()); } Index lenPos() const noexcept { return _lenPos; } void lenPos(const Index lenPos) noexcept { _lenPos = lenPos; } private: std::string _toStr(Size indent = 0) const override; private: Index _lenPos = UINT64_C(-1); }; /* * Option of a "read variant" procedure instruction. */ template <typename VarTypeOptT> class ReadVarInstrOpt final { public: using Opt = VarTypeOptT; using SelRangeSet = typename Opt::SelectorRangeSet; using Val = typename SelRangeSet::Value; public: explicit ReadVarInstrOpt() = default; ReadVarInstrOpt(const ReadVarInstrOpt<VarTypeOptT>& opt) = default; ReadVarInstrOpt(ReadVarInstrOpt<VarTypeOptT>&& opt) = default; ReadVarInstrOpt<VarTypeOptT>& operator=(const ReadVarInstrOpt<VarTypeOptT>& opt) = default; ReadVarInstrOpt<VarTypeOptT>& operator=(ReadVarInstrOpt<VarTypeOptT>&& opt) = default; explicit ReadVarInstrOpt(const VarTypeOptT& opt) : _opt {&opt} { } void buildRawProcFromShared() { _proc.buildRawProcFromShared(); } bool contains(const Val val) const noexcept { return _opt->selectorRanges().contains(val); } const Opt& opt() const noexcept { return *_opt; } const SelRangeSet& selRanges() const noexcept { return _opt->selectorRanges(); } const Proc& proc() const noexcept { return _proc; } Proc& proc() noexcept { return _proc; } std::string toStr(const Size indent = 0) const { std::ostringstream ss; ss << internal::indent(indent) << "<var opt>"; for (const auto& range : _opt->selectorRanges()) { ss << " [" << range.lower() << ", " << range.upper() << "]"; } ss << std::endl << _proc.toStr(indent + 1); return ss.str(); } private: const Opt *_opt; /* * Contained pointers are not owned by this object: they are owned * by the variant instruction object which contains the options. */ Proc _proc; }; static inline std::string _strProp(const std::string& prop) { std::string rProp; rProp = "\033[1m"; rProp += prop; rProp += "\033[0m="; return rProp; } /* * "Begin reading variant" procedure instruction template. * * The VM must use selPos() to retrieve the saved value which is the * selector of the variant, find the corresponding option for this * selector value, and then execute the subprocedure of the option. */ template <typename VarTypeT, Instr::Kind SelfKindV> class BeginReadVarInstr : public ReadDataInstr { public: using Opt = ReadVarInstrOpt<typename VarTypeT::Option>; using Opts = std::vector<Opt>; protected: explicit BeginReadVarInstr(const StructureMemberType * const memberType, const DataType& dt) : ReadDataInstr {SelfKindV, memberType, dt} { auto& varType = static_cast<const VarTypeT&>(dt); for (auto& opt : varType.options()) { _opts.emplace_back(*opt); } } public: void buildRawProcFromShared() override { for (auto& opt : _opts) { opt.buildRawProcFromShared(); } } const VarTypeT& varType() const noexcept { return static_cast<const VarTypeT&>(this->dt()); } const Opts& opts() const noexcept { return _opts; } Opts& opts() noexcept { return _opts; } const Proc *procForSelVal(const typename Opt::Val selVal) const noexcept { for (auto& opt : _opts) { if (opt.contains(selVal)) { return &opt.proc(); } } return nullptr; } Index selPos() const noexcept { return _selPos; } void selPos(const Index pos) noexcept { _selPos = pos; } private: std::string _toStr(const Size indent = 0) const override { std::ostringstream ss; ss << this->_commonToStr() << " " << _strProp("sel-pos") << _selPos << std::endl; for (const auto& opt : _opts) { ss << opt.toStr(indent + 1); } return ss.str(); } private: Opts _opts; Index _selPos; }; class BeginReadVarUIntSelInstr final : public BeginReadVarInstr<VariantWithUnsignedIntegerSelectorType, Instr::Kind::BEGIN_READ_VAR_UINT_SEL> { public: explicit BeginReadVarUIntSelInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; class BeginReadVarSIntSelInstr final : public BeginReadVarInstr<VariantWithSignedIntegerSelectorType, Instr::Kind::BEGIN_READ_VAR_SINT_SEL> { public: explicit BeginReadVarSIntSelInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Begin reading optional" abstract procedure instruction class. * * The VM must use selPos() to retrieve the saved value which is the * selector of the optional, and, depending on the value and the type of * optional, execute its subprocedure. */ class BeginReadOptInstr : public BeginReadCompoundInstr { protected: explicit BeginReadOptInstr(Kind kind, const StructureMemberType *memberType, const DataType& dt); public: const OptionalType& optType() const noexcept { return static_cast<const OptionalType&>(this->dt()); } Index selPos() const noexcept { return _selPos; } void selPos(const Index pos) noexcept { _selPos = pos; } private: std::string _toStr(Size indent = 0) const override; private: Index _selPos = UINT64_C(-1); }; /* * "Begin reading optional with boolean selector" procedure instruction. */ class BeginReadOptBoolSelInstr : public BeginReadOptInstr { public: explicit BeginReadOptBoolSelInstr(const StructureMemberType *memberType, const DataType& dt); const OptionalWithBooleanSelectorType& optType() const noexcept { return static_cast<const OptionalWithBooleanSelectorType&>(this->dt()); } bool isEnabled(const bool selVal) const noexcept { return selVal; } void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Begin reading optional with integer selector" procedure instruction * template. */ template <typename OptTypeT, Instr::Kind SelfKindV> class BeginReadOptIntSelInstr : public BeginReadOptInstr { public: using SelRanges = typename OptTypeT::SelectorRangeSet; protected: explicit BeginReadOptIntSelInstr(const StructureMemberType * const memberType, const DataType& dt) : BeginReadOptInstr {SelfKindV, memberType, dt}, _selRanges {static_cast<const OptTypeT&>(dt).selectorRanges()} { } public: const OptTypeT& optType() const noexcept { return static_cast<const OptTypeT&>(this->dt()); } const SelRanges& selRanges() const noexcept { return _selRanges; } bool isEnabled(const typename SelRanges::Value selVal) const noexcept { return _selRanges.contains(selVal); } private: SelRanges _selRanges; }; /* * "Begin reading optional with unsigned integer selector" procedure * instruction. */ class BeginReadOptUIntSelInstr : public BeginReadOptIntSelInstr<OptionalWithUnsignedIntegerSelectorType, Instr::Kind::BEGIN_READ_OPT_UINT_SEL> { public: explicit BeginReadOptUIntSelInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Begin reading optional with signed integer selector" procedure * instruction. */ class BeginReadOptSIntSelInstr : public BeginReadOptIntSelInstr<OptionalWithSignedIntegerSelectorType, Instr::Kind::BEGIN_READ_OPT_SINT_SEL> { public: explicit BeginReadOptSIntSelInstr(const StructureMemberType *memberType, const DataType& dt); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set current ID" procedure instruction. * * This instruction requires the VM to set the current ID to the last * decoded value. This is either the current data stream type ID or the * current event record type ID. */ class SetCurIdInstr final : public Instr { public: explicit SetCurIdInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set current type" procedure instruction abstract class. * * This instruction asks the VM to set the current data stream or event * record type using the current ID, or using `fixedId()` if it exists. * * TODO: This ☝ doesn't seem like the correct approach. */ class SetTypeInstr : public Instr { protected: explicit SetTypeInstr(Kind kind, boost::optional<TypeId> fixedId); public: const boost::optional<TypeId>& fixedId() const noexcept { return _fixedId; } private: std::string _toStr(Size indent = 0) const override; private: const boost::optional<TypeId> _fixedId; }; /* * "Set current data stream type" procedure instruction. */ class SetDstInstr final : public SetTypeInstr { public: explicit SetDstInstr(boost::optional<TypeId> fixedId = boost::none); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set current event record type" procedure instruction. */ class SetErtInstr final : public SetTypeInstr { public: explicit SetErtInstr(boost::optional<TypeId> fixedId = boost::none); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set packet sequence number" procedure instruction. * * This instruction requires the VM to set the packet sequence number to * the last decoded value. */ class SetPktSeqNumInstr final : public Instr { public: explicit SetPktSeqNumInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set packet discarded event record counter snapshot" procedure * instruction. * * This instruction requires the VM to set the packet discarded event * record counter snapshot to the last decoded value. */ class SetPktDiscErCounterSnapInstr final : public Instr { public: explicit SetPktDiscErCounterSnapInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set data stream ID" procedure instruction. * * This instruction requires the VM to set the data stream ID to the * last decoded value. * * This is NOT the current data stream _type_ ID. It's sometimes called * the "data stream instance ID". */ class SetDsIdInstr final : public Instr { public: explicit SetDsIdInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set data stream info" procedure instruction. * * This instruction requires the VM to set and emit the data stream * info element. */ class SetDsInfoInstr final : public Instr { public: explicit SetDsInfoInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set packet info" procedure instruction. * * This instruction requires the VM to set and emit the packet info * element. */ class SetPktInfoInstr final : public Instr { public: explicit SetPktInfoInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set event record info" procedure instruction. * * This instruction requires the VM to set and emit the event record * info element. */ class SetErInfoInstr final : public Instr { public: explicit SetErInfoInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set expected packet total length" procedure instruction. * * This instruction requires the VM to set the expected packet total * length (bits) to the last decoded value. */ class SetExpectedPktTotalLenInstr final : public Instr { public: explicit SetExpectedPktTotalLenInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Set expected packet content length" procedure instruction. * * This instruction requires the VM to set the expected packet content * length (bits) to the last decoded value. */ class SetExpectedPktContentLenInstr final : public Instr { public: explicit SetExpectedPktContentLenInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Update clock value" procedure instruction. * * This instruction requires the VM to update the value of the default * clock from the last decoded unsigned integer value. */ class UpdateDefClkValInstr : public Instr { protected: explicit UpdateDefClkValInstr(Instr::Kind kind); public: explicit UpdateDefClkValInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Update clock value from fixed-length unsigned integer" procedure * instruction. * * This instruction requires the VM to update the value of the default * clock from the last decoded fixed-length unsigned integer value. */ class UpdateDefClkValFlInstr final : public UpdateDefClkValInstr { public: explicit UpdateDefClkValFlInstr(Size len); Size len() const noexcept { return _len; } void accept(InstrVisitor& visitor) override { visitor.visit(*this); } private: std::string _toStr(Size indent = 0) const override; private: const Size _len; }; /* * "Set packet magic number" procedure instruction. * * This instruction requires the VM to use the last decoded value as the * packet magic number. */ class SetPktMagicNumberInstr final : public Instr { public: explicit SetPktMagicNumberInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "End packet preamble procedure" procedure instruction. * * This instruction indicates that the packet preamble procedure * containing it has no more instructions. */ class EndPktPreambleProcInstr final : public Instr { public: explicit EndPktPreambleProcInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "End data stream packet preamble procedure" procedure instruction. * * This instruction indicates that the data stream packet preamble * procedure containing it has no more instructions. */ class EndDsPktPreambleProcInstr final : public Instr { public: explicit EndDsPktPreambleProcInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "End data stream event record preamble procedure" procedure * instruction. * * This instruction indicates that the data stream event record preamble * procedure containing it has no more instructions. */ class EndDsErPreambleProcInstr final : public Instr { public: explicit EndDsErPreambleProcInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "End event record type procedure" procedure instruction. * * This instruction indicates that the event record type procedure * containing it has no more instructions. */ class EndErProcInstr final : public Instr { public: explicit EndErProcInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * "Decrement remaining elements" procedure instruction. * * When reading an array, this instruction requires the VM to decrement * the number of remaining elements to read. * * It's placed just before an "end read compound data" instruction as a * trade-off between checking if we're in an array every time we end a * compound data, or having this decrementation instruction even for * simple arrays of scalar elements. */ class DecrRemainingElemsInstr final : public Instr { public: explicit DecrRemainingElemsInstr(); void accept(InstrVisitor& visitor) override { visitor.visit(*this); } }; /* * Event record procedure. */ class ErProc final { public: explicit ErProc(const EventRecordType& ert); std::string toStr(Size indent) const; void buildRawProcFromShared(); Proc& proc() noexcept { return _proc; } const Proc& proc() const noexcept { return _proc; } const EventRecordType& ert() const noexcept { return *_ert; } private: const EventRecordType * const _ert; Proc _proc; }; /* * Packet procedure for any data stream of a given type. */ class DsPktProc final { public: using ErProcsMap = std::unordered_map<TypeId, std::unique_ptr<ErProc>>; using ErProcsVec = std::vector<std::unique_ptr<ErProc>>; using ForEachErProcFunc = std::function<void (ErProc&)>; public: explicit DsPktProc(const DataStreamType& dst); const ErProc *operator[](TypeId id) const noexcept; const ErProc *singleErProc() const noexcept; void addErProc(std::unique_ptr<ErProc> erProc); std::string toStr(Size indent) const; void buildRawProcFromShared(); void setErAlign(); template <typename FuncT> void forEachErProc(FuncT&& func) { for (auto& erProc : _erProcsVec) { if (erProc) { std::forward<FuncT>(func)(*erProc); } } for (auto& idErProcUpPair : _erProcsMap) { std::forward<FuncT>(func)(*idErProcUpPair.second); } } Proc& pktPreambleProc() noexcept { return _pktPreambleProc; } const Proc& pktPreambleProc() const noexcept { return _pktPreambleProc; } Proc& erPreambleProc() noexcept { return _erPreambleProc; } const Proc& erPreambleProc() const noexcept { return _erPreambleProc; } ErProcsMap& erProcsMap() noexcept { return _erProcsMap; } ErProcsVec& erProcsVec() noexcept { return _erProcsVec; } Size erProcsCount() const noexcept { return _erProcsMap.size() + _erProcsVec.size(); } const DataStreamType& dst() const noexcept { return *_dst; } unsigned int erAlign() const noexcept { return _erAlign; } private: const DataStreamType * const _dst; Proc _pktPreambleProc; Proc _erPreambleProc; unsigned int _erAlign = 1; /* * We have both a vector and a map here to store event record * procedures. Typically, event record type IDs are contiguous * within a given trace; storing them in the vector makes a more * efficient lookup afterwards if this is possible. For outliers, we * use the (slower) map. * * _erProcsVec can contain both event record procedures and null * pointers. _erProcsMap contains only event record procedures. */ ErProcsVec _erProcsVec; ErProcsMap _erProcsMap; }; /* * Packet procedure. * * Such an object is owned by a `TraceType` object, and it's not public. * This means that all the pointers to anything inside the owning * `TraceType` object are always safe to use. * * Any object which needs to access a `PktProc` object must own its * owning `TraceType` object. For example (ownership tree): * * User * Element sequence iterator * VM * Trace type * Packet procedure */ class PktProc final { public: using DsPktProcs = std::unordered_map<TypeId, std::unique_ptr<DsPktProc>>; public: explicit PktProc(const TraceType &traceType); const DsPktProc *operator[](TypeId id) const noexcept; const DsPktProc *singleDsPktProc() const noexcept; std::string toStr(Size indent) const; void buildRawProcFromShared(); const TraceType& traceType() const noexcept { return *_traceType; } DsPktProcs& dsPktProcs() noexcept { return _dsPktProcs; } Size dsPktProcsCount() const noexcept { return _dsPktProcs.size(); } Proc& preambleProc() noexcept { return _preambleProc; } const Proc& preambleProc() const noexcept { return _preambleProc; } Size savedValsCount() const noexcept { return _savedValsCount; } void savedValsCount(const Size savedValsCount) { _savedValsCount = savedValsCount; } private: const TraceType * const _traceType; DsPktProcs _dsPktProcs; Size _savedValsCount = 0; Proc _preambleProc; }; static inline ReadDataInstr& instrAsReadData(Instr& instr) noexcept { return static_cast<ReadDataInstr&>(instr); } static inline BeginReadScopeInstr& instrAsBeginReadScope(Instr& instr) noexcept { return static_cast<BeginReadScopeInstr&>(instr); } static inline BeginReadStructInstr& instrAsBeginReadStruct(Instr& instr) noexcept { return static_cast<BeginReadStructInstr&>(instr); } } // namespace internal } // namespace yactfr #endif // _YACTFR_INTERNAL_PROC_HPP
23.501458
100
0.677849
eepp
f556b5e2a660e342dd95b2f11d1e7a91d39772d2
10,728
cpp
C++
ext/RadioHead/STM32ArduinoCompat/HardwareSerial.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
null
null
null
ext/RadioHead/STM32ArduinoCompat/HardwareSerial.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
null
null
null
ext/RadioHead/STM32ArduinoCompat/HardwareSerial.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
null
null
null
// ArduinoCompat/HardwareSerial.cpp // // Author: mikem@airspayce.com #include "HardwareSerial.h" #include <stm32f4xx_usart.h> // Preinstantiated Serial objects HardwareSerial Serial1(USART1); HardwareSerial Serial2(USART2); HardwareSerial Serial3(USART3); HardwareSerial Serial4(UART4); HardwareSerial Serial5(UART5); HardwareSerial Serial6(USART6); /////////////////////////////////////////////////////////////// // RingBuffer /////////////////////////////////////////////////////////////// RingBuffer::RingBuffer() : _head(0), _tail(0), _overruns(0), _underruns(0) { } bool RingBuffer::isEmpty() { return _head == _tail; } bool RingBuffer::isFull() { return ((_head + 1) % ARDUINO_RINGBUFFER_SIZE) == _tail; } bool RingBuffer::write(uint8_t ch) { if (isFull()) { _overruns++; return false; } _buffer[_head] = ch; if (++_head >= ARDUINO_RINGBUFFER_SIZE) _head = 0; return true; } uint8_t RingBuffer::read() { if (isEmpty()) { _underruns++; return 0; // What else can we do? } uint8_t ret = _buffer[_tail]; if (++_tail >= ARDUINO_RINGBUFFER_SIZE) _tail = 0; return ret; } /////////////////////////////////////////////////////////////// // HardwareSerial /////////////////////////////////////////////////////////////// // On STM32F4 Discovery, USART 1 is not very useful conflicts with the Green lED HardwareSerial::HardwareSerial(USART_TypeDef* usart) : _usart(usart) { } void HardwareSerial::begin(unsigned long baud) { USART_InitTypeDef USART_InitStructure; GPIO_InitTypeDef GPIO_InitStructure_TX; GPIO_InitTypeDef GPIO_InitStructure_RX; // Common GPIO structure init: GPIO_InitStructure_TX.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure_TX.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure_TX.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure_TX.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure_RX.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure_RX.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure_RX.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure_RX.GPIO_PuPd = GPIO_PuPd_UP; // CTS or SCLK outputs are not supported. USART_InitStructure.USART_BaudRate = baud * 25/8; // Why? // Only 8N1 is currently supported USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; // Different for each USART: if (_usart == USART1) { // Initialise the clocks for this USART and its RX, TX pins port RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1); GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1); GPIO_InitStructure_TX.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure_RX.GPIO_Pin = GPIO_Pin_10; GPIO_Init(GPIOA, &GPIO_InitStructure_TX); GPIO_Init(GPIOA, &GPIO_InitStructure_RX); // Initialise the USART USART_Init(USART1, &USART_InitStructure); // Enable the RXNE interrupt USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); // Enable global interrupt NVIC_EnableIRQ(USART1_IRQn); } else if (_usart == USART2) { // Initialise the clocks for this USART and its RX, TX pins port RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2); GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2); GPIO_InitStructure_TX.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure_RX.GPIO_Pin = GPIO_Pin_3; GPIO_Init(GPIOA, &GPIO_InitStructure_TX); GPIO_Init(GPIOA, &GPIO_InitStructure_RX); // Initialise the USART USART_Init(USART2, &USART_InitStructure); // Enable the RXNE interrupt USART_ITConfig(USART2, USART_IT_RXNE, ENABLE); // Enable global interrupt NVIC_EnableIRQ(USART2_IRQn); } else if (_usart == USART3) { // Initialise the clocks for this USART and its RX, TX pins port RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); GPIO_PinAFConfig(GPIOD, GPIO_PinSource8, GPIO_AF_USART3); GPIO_PinAFConfig(GPIOD, GPIO_PinSource9, GPIO_AF_USART3); GPIO_InitStructure_TX.GPIO_Pin = GPIO_Pin_8; GPIO_InitStructure_RX.GPIO_Pin = GPIO_Pin_9; GPIO_Init(GPIOD, &GPIO_InitStructure_TX); GPIO_Init(GPIOD, &GPIO_InitStructure_RX); // Initialise the USART USART_Init(USART3, &USART_InitStructure); // Enable the RXNE interrupt USART_ITConfig(USART3, USART_IT_RXNE, ENABLE); // Enable global interrupt NVIC_EnableIRQ(USART3_IRQn); } else if (_usart == UART4) { // Initialise the clocks for this USART and its RX, TX pins port RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_UART4); GPIO_PinAFConfig(GPIOA, GPIO_PinSource1, GPIO_AF_UART4); GPIO_InitStructure_TX.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure_RX.GPIO_Pin = GPIO_Pin_1; GPIO_Init(GPIOA, &GPIO_InitStructure_TX); GPIO_Init(GPIOA, &GPIO_InitStructure_RX); // Initialise the USART USART_Init(UART4, &USART_InitStructure); // Enable the RXNE interrupt USART_ITConfig(UART4, USART_IT_RXNE, ENABLE); // Enable global interrupt NVIC_EnableIRQ(UART4_IRQn); } else if (_usart == UART5) { // Initialise the clocks for this USART and its RX, TX pins port RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART5, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC | RCC_AHB1Periph_GPIOD, ENABLE); GPIO_PinAFConfig(GPIOC, GPIO_PinSource12, GPIO_AF_UART5); GPIO_PinAFConfig(GPIOD, GPIO_PinSource2, GPIO_AF_UART5); GPIO_InitStructure_TX.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure_RX.GPIO_Pin = GPIO_Pin_2; GPIO_Init(GPIOC, &GPIO_InitStructure_TX); GPIO_Init(GPIOD, &GPIO_InitStructure_RX); // Initialise the USART USART_Init(UART5, &USART_InitStructure); // Enable the RXNE interrupt USART_ITConfig(UART5, USART_IT_RXNE, ENABLE); // Enable global interrupt NVIC_EnableIRQ(UART5_IRQn); } else if (_usart == USART6) { // Initialise the clocks for this USART and its RX, TX pins port RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_USART6); GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_USART6); GPIO_InitStructure_TX.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure_RX.GPIO_Pin = GPIO_Pin_7; GPIO_Init(GPIOC, &GPIO_InitStructure_TX); GPIO_Init(GPIOC, &GPIO_InitStructure_RX); // Initialise the USART USART_Init(USART6, &USART_InitStructure); // Enable the RXNE interrupt USART_ITConfig(USART6, USART_IT_RXNE, ENABLE); // Enable global interrupt NVIC_EnableIRQ(USART6_IRQn); } USART_Cmd(_usart, ENABLE); } void HardwareSerial::end() { USART_Cmd(_usart, DISABLE); USART_DeInit(_usart); } int HardwareSerial::available(void) { return !_rxRingBuffer.isEmpty(); } int HardwareSerial::read(void) { return _rxRingBuffer.read(); } size_t HardwareSerial::write(uint8_t ch) { _txRingBuffer.write(ch); // Queue it USART_ITConfig(_usart, USART_IT_TXE, ENABLE); // Enable the TX interrupt return 1; } extern "C" { void USART1_IRQHandler(void) { if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) { Serial1._rxRingBuffer.write(USART_ReceiveData(USART1)); } if (USART_GetITStatus(USART1, USART_IT_TXE) != RESET) { // Transmitter is empty, maybe send another char? if (Serial1._txRingBuffer.isEmpty()) USART_ITConfig(USART1, USART_IT_TXE, DISABLE); // No more to send, disable the TX interrupt else USART_SendData(USART1, Serial1._txRingBuffer.read()); } } void USART2_IRQHandler(void) { if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) { // Newly received char, try to put it in our rx buffer Serial2._rxRingBuffer.write(USART_ReceiveData(USART2)); } if (USART_GetITStatus(USART2, USART_IT_TXE) != RESET) { // Transmitter is empty, maybe send another char? if (Serial2._txRingBuffer.isEmpty()) USART_ITConfig(USART2, USART_IT_TXE, DISABLE); // No more to send, disable the TX interrupt else USART_SendData(USART2, Serial2._txRingBuffer.read()); } } void USART3_IRQHandler(void) { if (USART_GetITStatus(USART3, USART_IT_RXNE) != RESET) { // Newly received char, try to put it in our rx buffer Serial3._rxRingBuffer.write(USART_ReceiveData(USART3)); } if (USART_GetITStatus(USART3, USART_IT_TXE) != RESET) { // Transmitter is empty, maybe send another char? if (Serial3._txRingBuffer.isEmpty()) USART_ITConfig(USART3, USART_IT_TXE, DISABLE); // No more to send, disable the TX interrupt else USART_SendData(USART3, Serial3._txRingBuffer.read()); } } void UART4_IRQHandler(void) { if (USART_GetITStatus(UART4, USART_IT_RXNE) != RESET) { // Newly received char, try to put it in our rx buffer Serial4._rxRingBuffer.write(USART_ReceiveData(UART4)); } if (USART_GetITStatus(UART4, USART_IT_TXE) != RESET) { // Transmitter is empty, maybe send another char? if (Serial4._txRingBuffer.isEmpty()) USART_ITConfig(UART4, USART_IT_TXE, DISABLE); // No more to send, disable the TX interrupt else USART_SendData(UART4, Serial4._txRingBuffer.read()); } } void UART5_IRQHandler(void) { if (USART_GetITStatus(UART5, USART_IT_RXNE) != RESET) { // Newly received char, try to put it in our rx buffer Serial5._rxRingBuffer.write(USART_ReceiveData(UART5)); } if (USART_GetITStatus(UART5, USART_IT_TXE) != RESET) { // Transmitter is empty, maybe send another char? if (Serial5._txRingBuffer.isEmpty()) USART_ITConfig(UART5, USART_IT_TXE, DISABLE); // No more to send, disable the TX interrupt else USART_SendData(UART5, Serial5._txRingBuffer.read()); } } void USART6_IRQHandler(void) { if (USART_GetITStatus(USART6, USART_IT_RXNE) != RESET) { // Newly received char, try to put it in our rx buffer Serial6._rxRingBuffer.write(USART_ReceiveData(USART6)); } if (USART_GetITStatus(USART6, USART_IT_TXE) != RESET) { // Transmitter is empty, maybe send another char? if (Serial6._txRingBuffer.isEmpty()) USART_ITConfig(USART6, USART_IT_TXE, DISABLE); // No more to send, disable the TX interrupt else USART_SendData(USART6, Serial6._txRingBuffer.read()); } } }
30.916427
93
0.723527
walmis
f5577de6da973e2043752baef0fd29205c64a734
2,808
cc
C++
src/cobalt/bin/app/logger_factory_impl.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
src/cobalt/bin/app/logger_factory_impl.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
src/cobalt/bin/app/logger_factory_impl.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Fuchsia 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 "src/cobalt/bin/app/logger_factory_impl.h" #include "src/cobalt/bin/app/utils.h" #include "src/lib/fsl/vmo/strings.h" namespace cobalt { using cobalt::TimerManager; using cobalt::logger::ProjectContextFactory; using config::ProjectConfigs; using fuchsia::cobalt::Status; constexpr uint32_t kFuchsiaCustomerId = 1; LoggerFactoryImpl::LoggerFactoryImpl( std::shared_ptr<cobalt::logger::ProjectContextFactory> global_project_context_factory, TimerManager* timer_manager, CobaltServiceInterface* cobalt_service) : global_project_context_factory_(std::move(global_project_context_factory)), timer_manager_(timer_manager), cobalt_service_(cobalt_service) {} template <typename LoggerInterface> void LoggerFactoryImpl::BindNewLogger( std::unique_ptr<logger::ProjectContext> project_context, fidl::InterfaceRequest<LoggerInterface> request, fidl::BindingSet<LoggerInterface, std::unique_ptr<LoggerInterface>>* binding_set) { binding_set->AddBinding( std::make_unique<LoggerImpl>(cobalt_service_->NewLogger(std::move(project_context)), timer_manager_), std::move(request)); } template <typename LoggerInterface, typename Callback> void LoggerFactoryImpl::CreateAndBindLoggerFromProjectId( uint32_t project_id, fidl::InterfaceRequest<LoggerInterface> request, Callback callback, fidl::BindingSet<LoggerInterface, std::unique_ptr<LoggerInterface>>* binding_set) { auto project_context = global_project_context_factory_->NewProjectContext(kFuchsiaCustomerId, project_id); if (!project_context) { FX_LOGS(ERROR) << "The CobaltRegistry bundled with this release does not " "include a Fuchsia project with ID " << project_id; callback(Status::INVALID_ARGUMENTS); return; } BindNewLogger(std::move(project_context), std::move(request), binding_set); callback(Status::OK); } void LoggerFactoryImpl::CreateLoggerFromProjectId( uint32_t project_id, fidl::InterfaceRequest<fuchsia::cobalt::Logger> request, CreateLoggerFromProjectIdCallback callback) { CreateAndBindLoggerFromProjectId(project_id, std::move(request), std::move(callback), &logger_bindings_); } void LoggerFactoryImpl::CreateLoggerSimpleFromProjectId( uint32_t project_id, fidl::InterfaceRequest<fuchsia::cobalt::LoggerSimple> request, CreateLoggerSimpleFromProjectIdCallback callback) { CreateAndBindLoggerFromProjectId(project_id, std::move(request), std::move(callback), &logger_simple_bindings_); } } // namespace cobalt
40.695652
92
0.747863
zarelaky
f559e212f5fc8d585fd435ccaf42db72d8ba4d50
2,431
cpp
C++
Actor/Characters/Enemy/GBoxEnemy_Close/StateAI/States/StateAI_GBEC_Combat.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/GBoxEnemy_Close/StateAI/States/StateAI_GBEC_Combat.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/GBoxEnemy_Close/StateAI/States/StateAI_GBEC_Combat.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "StateAI_GBEC_Combat.h" void UStateAI_GBEC_Combat::Init(class UStateMng_AI* pMng) { Super::Init(pMng); m_pStateClass.Add(static_cast<int32>(E_StateAI_GBEC_Combat::E_Combat_Attack), NewObject<UStateAI_GBEC_Combat_Attack>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_GBEC_Combat::E_Combat_DistMove), NewObject<UStateAI_GBEC_Combat_DistMove>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_GBEC_Combat::E_Combat_JumpAttack), NewObject<UUStateAI_GBEC_Combat_JumpAttack>()); for (TMap<int32, class UStateRootAI_GBEClose*>::TIterator it = m_pStateClass.CreateIterator(); it; ++it) { it->Value->Init(pMng); } } void UStateAI_GBEC_Combat::Enter() { Super::Enter(); float fRand = FMath::RandRange(0.0f, 100.0f); if (fRand < 85.0f) { AActor* pTarget = GetRootAI()->DetectInPerception(); if (pTarget == nullptr) { ULOG(TEXT("Combat Attack DetectIn is nullptr")); return; } FVector vEnemyPos = GetRootAI()->GetRootChar()->GetActorLocation(); FVector vTargetPos = pTarget->GetActorLocation(); float fDistance = FVector::Distance(vEnemyPos, vTargetPos); if (fDistance <= 1800.0f) { fRand = FMath::RandRange(0.0f, 100.0f); if (fRand < 80) { ChangeCombatState(static_cast<int32>(E_StateAI_GBEC_Combat::E_Combat_Attack)); } else { ChangeCombatState(static_cast<int32>(E_StateAI_GBEC_Combat::E_Combat_DistMove)); } } else { ChangeCombatState(static_cast<int32>(E_StateAI_GBEC_Combat::E_Combat_JumpAttack)); } } else { ChangeCombatState(static_cast<int32>(E_StateAI_GBEC_Combat::E_Combat_DistMove)); } } void UStateAI_GBEC_Combat::Exit() { Super::Exit(); } void UStateAI_GBEC_Combat::Update(float fDeltaTime) { Super::Update(fDeltaTime); if (m_pCurrentState != nullptr) m_pCurrentState->Update(fDeltaTime); } void UStateAI_GBEC_Combat::StateMessage(FString StateMessage) { Super::StateMessage(StateMessage); if (m_pCurrentState != nullptr) m_pCurrentState->StateMessage(StateMessage); } void UStateAI_GBEC_Combat::ChangeCombatState(int32 eState) { m_eState = eState; if (m_pCurrentState != nullptr) m_pCurrentState->Exit(); for (TMap<int32, class UStateRootAI_GBEClose*>::TIterator it = m_pStateClass.CreateIterator(); it; ++it) { if (it->Key == eState) { m_pCurrentState = it->Value; m_pCurrentState->Enter(); } } }
24.069307
130
0.736734
Bornsoul
f55ea5477a5f21d56e55a862c7e6a9e68b8a07e1
6,176
cc
C++
gazebo/gui/building/LineSegmentItem.cc
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
8
2015-07-02T08:23:30.000Z
2020-11-17T19:00:38.000Z
gazebo/gui/building/LineSegmentItem.cc
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/gui/building/LineSegmentItem.cc
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
10
2015-04-22T18:33:15.000Z
2021-11-16T10:17:45.000Z
/* * Copyright 2012 Open Source Robotics Foundation * * 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 "gazebo/gui/building/WallInspectorDialog.hh" #include "gazebo/gui/building/EditorItem.hh" #include "gazebo/gui/building/LineSegmentItem.hh" using namespace gazebo; using namespace gui; ///////////////////////////////////////////////// LineSegmentItem::LineSegmentItem(QGraphicsItem *_parent, int _index) : EditorItem(), QGraphicsLineItem(_parent), index(_index), start(0, 0), end(0, 0) { this->editorType = "Line"; if (_parent) this->setParentItem(_parent); this->setFlag(QGraphicsItem::ItemIsSelectable, true); this->setAcceptHoverEvents(true); this->setZValue(0); } ///////////////////////////////////////////////// LineSegmentItem::~LineSegmentItem() { } ///////////////////////////////////////////////// void LineSegmentItem::SetLine(const QPointF &_start, const QPointF &_end) { this->start = _start; this->end = _end; this->setLine(this->start.x(), this->start.y(), this->end.x(), this->end.y()); LineChanged(); } ///////////////////////////////////////////////// void LineSegmentItem::SetStartPoint(const QPointF &_start) { this->start = _start; this->setLine(this->start.x(), this->start.y(), this->end.x(), this->end.y()); LineChanged(); } ///////////////////////////////////////////////// void LineSegmentItem::SetEndPoint(const QPointF &_end) { this->end = _end; this->setLine(this->start.x(), this->start.y(), this->end.x(), this->end.y()); LineChanged(); } ///////////////////////////////////////////////// int LineSegmentItem::GetIndex() const { return index; } ///////////////////////////////////////////////// void LineSegmentItem::SetMouseState(int _state) { this->mouseButtonState = _state; } ///////////////////////////////////////////////// int LineSegmentItem::GetMouseState() const { return this->mouseButtonState; } ///////////////////////////////////////////////// void LineSegmentItem::SetMouseDownX(double _x) { this->mouseDownX = _x; } ///////////////////////////////////////////////// void LineSegmentItem::SetMouseDownY(double _y) { this->mouseDownY = _y; } ///////////////////////////////////////////////// double LineSegmentItem::GetMouseDownX() const { return this->mouseDownX; } ///////////////////////////////////////////////// double LineSegmentItem::GetMouseDownY() const { return this->mouseDownY; } ///////////////////////////////////////////////// void LineSegmentItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *_event) { _event->setAccepted(true); } ///////////////////////////////////////////////// void LineSegmentItem::mousePressEvent(QGraphicsSceneMouseEvent *_event) { _event->setAccepted(true); } ///////////////////////////////////////////////// void LineSegmentItem::mouseMoveEvent(QGraphicsSceneMouseEvent *_event) { _event->setAccepted(true); } ///////////////////////////////////////////////// void LineSegmentItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *_event) { if (!this->isSelected()) { _event->ignore(); return; } QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor)); } ///////////////////////////////////////////////// void LineSegmentItem::hoverMoveEvent(QGraphicsSceneHoverEvent *_event) { if (!this->isSelected()) { _event->ignore(); return; } QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor)); } ///////////////////////////////////////////////// void LineSegmentItem::hoverEnterEvent(QGraphicsSceneHoverEvent *_event) { if (!this->isSelected()) { _event->ignore(); return; } QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor)); } ///////////////////////////////////////////////// QVariant LineSegmentItem::itemChange(GraphicsItemChange _change, const QVariant &_value) { if (_change == QGraphicsItem::ItemSelectedChange && this->scene()) { if (_value.toBool()) { QColor lineColor(247, 142, 30); QPen linePen = this->pen(); linePen.setColor(lineColor); this->setPen(linePen); } else { QColor lineColor = Qt::black; QPen linePen = this->pen(); linePen.setColor(lineColor); this->setPen(linePen); } } return QGraphicsItem::itemChange(_change, _value); } ///////////////////////////////////////////////// QVector3D LineSegmentItem::GetSize() const { return QVector3D(this->line().length() + this->pen().width(), this->pen().width(), 0); } ///////////////////////////////////////////////// QVector3D LineSegmentItem::GetScenePosition() const { QPointF centerPos = this->mapToScene(this->start + (this->end - this->start)/2.0); return QVector3D(centerPos.x(), centerPos.y(), 0); } ///////////////////////////////////////////////// double LineSegmentItem::GetSceneRotation() const { return -this->line().angle(); } ///////////////////////////////////////////////// void LineSegmentItem::paint(QPainter *_painter, const QStyleOptionGraphicsItem */*_option*/, QWidget */*_widget*/) { _painter->save(); _painter->setPen(this->pen()); _painter->drawLine(this->line()); _painter->restore(); } ///////////////////////////////////////////////// void LineSegmentItem::LineChanged() { emit WidthChanged(this->line().length() + this->pen().width()); emit DepthChanged(this->pen().width()); QPointF centerPos = this->mapToScene(this->start + (this->end - this->start)/2.0); emit PosXChanged(centerPos.x()); emit PosYChanged(centerPos.y()); emit RotationChanged(0, 0, -this->line().angle()); } ///////////////////////////////////////////////// void LineSegmentItem::Update() { this->LineChanged(); }
25.841004
80
0.560719
thomas-moulard
f55ec82fd546cce41ca632498d164f023ada7ae6
605
hpp
C++
math/famous_sequence/Bernoulli_numbers.hpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
7
2021-07-20T15:25:00.000Z
2022-03-13T11:58:25.000Z
math/famous_sequence/Bernoulli_numbers.hpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
10
2021-03-11T16:08:22.000Z
2022-03-13T08:40:36.000Z
math/famous_sequence/Bernoulli_numbers.hpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
null
null
null
#ifndef BERNOULLI_NUMBERS_HEADER_HPP #define BERNOULLI_NUMBERS_HEADER_HPP /** * @brief Bernoulli number * @docs docs/math/famous_sequence/Bernoulli_numbers.md */ #include "../formal_power_series/prime_binomial.hpp" namespace lib { template <typename PolyType> void Bernoulli_numbers(int n, PolyType &res) { using mod_t = typename PolyType::value_type; res.resize(n); PrimeBinomial<mod_t> bi(n + 1); for (int i = 0; i < n; ++i) res[i] = bi.ifac_unsafe(i + 1); res = res.inv(n); for (int i = 0; i < n; ++i) res[i] *= bi.fac_unsafe(i); } } // namespace lib #endif
24.2
62
0.664463
hly1204
f5641dbeb6088106ed581fa624e36d01f00209e5
350
cpp
C++
id1026/main.cpp
adogadaev/timus
eeadeb3ac60b7259988fe579422d386b95c4ca9d
[ "Apache-2.0" ]
null
null
null
id1026/main.cpp
adogadaev/timus
eeadeb3ac60b7259988fe579422d386b95c4ca9d
[ "Apache-2.0" ]
null
null
null
id1026/main.cpp
adogadaev/timus
eeadeb3ac60b7259988fe579422d386b95c4ca9d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { int n; int aNum[100000]; cin >> n; for (int i = 0; i < n; i++) cin >> aNum[i]; sort(aNum, aNum+n); int k; int idx; string str; cin >> str; cin >> k; for (int i = 0; i < k; i++) { cin >> idx; cout << aNum[idx-1] << endl; } return 0; }
12.962963
30
0.542857
adogadaev
f564adaea88496b092c7dcd43290303ea37b6cb8
2,919
cpp
C++
test/localization/locale.categories/category.collate/locale.collate.byname/compare.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
187
2015-02-28T11:50:45.000Z
2022-02-20T12:51:00.000Z
test/localization/locale.categories/category.collate/locale.collate.byname/compare.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
2
2019-06-24T20:44:59.000Z
2020-06-17T18:41:35.000Z
test/localization/locale.categories/category.collate/locale.collate.byname/compare.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
80
2015-01-02T12:44:41.000Z
2022-01-20T15:37:54.000Z
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <locale> // template <class charT> class collate_byname // int compare(const charT* low1, const charT* high1, // const charT* low2, const charT* high2) const; // I'm currently unable to confirm that collation based on named locales // has any difference from "C" collation. But I do believe I'm picking // up the OS's collation files. #include <locale> #include <string> #include <cassert> #include <stdio.h> #include "../../../../platform_support.h" // locale name macros int main() { { std::locale l(LOCALE_en_US_UTF_8); { const std::collate<char>& f = std::use_facet<std::collate<char> >(l); std::string s2("aaaaaaA"); std::string s3("BaaaaaA"); assert(f.compare(s2.data(), s2.data() + s2.size(), s3.data(), s3.data() + s3.size()) == 1); } { const std::collate<wchar_t>& f = std::use_facet<std::collate<wchar_t> >(l); std::wstring s2(L"aaaaaaA"); std::wstring s3(L"BaaaaaA"); assert(f.compare(s2.data(), s2.data() + s2.size(), s3.data(), s3.data() + s3.size()) == 1); } } { std::locale l(""); { const std::collate<char>& f = std::use_facet<std::collate<char> >(l); std::string s2("aaaaaaA"); std::string s3("BaaaaaA"); assert(f.compare(s2.data(), s2.data() + s2.size(), s3.data(), s3.data() + s3.size()) == 1); } { const std::collate<wchar_t>& f = std::use_facet<std::collate<wchar_t> >(l); std::wstring s2(L"aaaaaaA"); std::wstring s3(L"BaaaaaA"); assert(f.compare(s2.data(), s2.data() + s2.size(), s3.data(), s3.data() + s3.size()) == 1); } } { std::locale l("C"); { const std::collate<char>& f = std::use_facet<std::collate<char> >(l); std::string s2("aaaaaaA"); std::string s3("BaaaaaA"); assert(f.compare(s2.data(), s2.data() + s2.size(), s3.data(), s3.data() + s3.size()) == 1); } { const std::collate<wchar_t>& f = std::use_facet<std::collate<wchar_t> >(l); std::wstring s2(L"aaaaaaA"); std::wstring s3(L"BaaaaaA"); assert(f.compare(s2.data(), s2.data() + s2.size(), s3.data(), s3.data() + s3.size()) == 1); } } }
35.168675
87
0.465913
caiohamamura
f56573316115cbb38dff79e0207857936c77fad1
3,828
hpp
C++
include/xul/posix/daemon_controller.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/posix/daemon_controller.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/posix/daemon_controller.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include <xul/net/message_socket.hpp> #include <xul/lang/object_ptr.hpp> #include <xul/util/singleton.hpp> #include <xul/net/io_service.hpp> #include <vector> #include <assert.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> namespace xul { class daemon_controller; class daemon_controller_listener { public: virtual void on_daemon_fork_succeeded(daemon_controller* sender, int index, pid_t pid) = 0; virtual void on_daemon_fork_failed(daemon_controller* sender, int index, int errcode) = 0; virtual void on_daemon_child_forked(daemon_controller* sender, int index) = 0; }; class dummy_daemon_controller_listener : public daemon_controller_listener, public singleton<dummy_daemon_controller_listener> { public: virtual void on_daemon_fork_succeeded(daemon_controller* sender, int index, pid_t pid) { } virtual void on_daemon_fork_failed(daemon_controller* sender, int index, int errcode) { } virtual void on_daemon_child_forked(daemon_controller* sender, int index) { } }; class daemon_controller { public: class daemon_worker_info { public: int pid; boost::intrusive_ptr<message_socket> socket; daemon_worker_info() { pid = 0; } }; typedef boost::shared_ptr<daemon_worker_info> daemon_worker_info_ptr; explicit daemon_controller(io_service* ios) { m_ios = ios; set_listener(NULL); init(); } message_socket* get_socket() { return m_socket.get(); } void set_listener(daemon_controller_listener* listener) { m_listener = listener ? listener : &dummy_daemon_controller_listener::instance(); } bool fork_children(int count) { assert(count > 0 && count < 100); m_children_pids.resize(count, 0); for (int i = 0; i < count; ++i) { printf("fork %d\n", getpid()); int socks[2] = { -1, -1 }; int ret = ::socketpair(AF_INET, SOCK_DGRAM, 0, socks); if (ret < 0) { printf("socketpair failed %d %d\n", ret, errno); continue; } pid_t pid = fork(); if (pid < 0) { m_listener->on_daemon_fork_failed(this, i, pid); } else if (0 == pid) { m_socket = m_ios->recreate_message_socket(socks[1]); m_listener->on_daemon_child_forked(this, i); return false; } else { m_children_pids[i] = pid; m_socket = m_ios->recreate_message_socket(socks[0]); m_listener->on_daemon_fork_succeeded(this, i, pid); } } return true; } private: void init() { //signal(SIGCHLD, &daemon_controller::handle_signal_child_die); struct sigaction sig, oldsig; memset(&sig, 0, sizeof(sig)); memset(&oldsig, 0, sizeof(oldsig)); sig.sa_sigaction = &daemon_controller::handle_sigaction_child_die; sigaction(SIGCHLD, &sig, &oldsig); } static void handle_signal_child_die(int x) { printf("handle_signal_child_die %d %d\n", getpid(), x); } static void handle_sigaction_child_die(int signum, siginfo_t* info, void* context) { printf("handle_sigaction_child_die %d %d %d %d\n", getpid(), signum, info->si_errno, info->si_code); } private: daemon_controller_listener* m_listener; std::vector<daemon_worker_info_ptr> m_workers; daemon_worker_info m_worker; //boost::intrusive_ptr<message_socket> m_socket; boost::intrusive_ptr<io_service> m_ios; }; }
27.342857
126
0.621996
hindsights
f57a7df454a16465cbc646589405653915111427
316
hpp
C++
Plugins/Animation/src/AnimationPluginMacros.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
Plugins/Animation/src/AnimationPluginMacros.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
Plugins/Animation/src/AnimationPluginMacros.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
#ifndef ANIMATIONPLUGINMACROS_HPP_ #define ANIMATIONPLUGINMACROS_HPP_ #include <Core/CoreMacros.hpp> /// Defines the correct macro to export dll symbols. #if defined Animation_EXPORTS #define ANIM_PLUGIN_API DLL_EXPORT #else #define ANIM_PLUGIN_API DLL_IMPORT #endif #endif // ANIMATIONPLUGINMACROS_HPP_
22.571429
52
0.810127
nmellado
f57ae066c42d93ac79a304371105ecc923a49ae0
15,019
cpp
C++
Operations/mafOpDecomposeTimeVarVME.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
1
2021-05-10T19:01:10.000Z
2021-05-10T19:01:10.000Z
Operations/mafOpDecomposeTimeVarVME.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
Operations/mafOpDecomposeTimeVarVME.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Program: MAF2 Module: mafOpDecomposeTimeVarVME Authors: Roberto Mucci Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "mafDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the MAF must include "mafDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "mafOpDecomposeTimeVarVME.h" #include "mafDecl.h" #include "mafEvent.h" #include "mafGUI.h" #include "mafGUIRollOut.h" #include "mafGUIListBox.h" #include "mafNodeIterator.h" #include "mafTagArray.h" #include "mafSmartPointer.h" #include "mafMatrixVector.h" #include "mafDataVector.h" #include "mafStorageElement.h" #include "mafMatrix.h" #include "mafVMEFactory.h" #include "mafVMEItem.h" #include "mafVME.h" #include "mafVMEGroup.h" #include "mafVMELandmarkCloud.h" //---------------------------------------------------------------------------- mafOpDecomposeTimeVarVME::mafOpDecomposeTimeVarVME(const wxString& label) : mafOp(label) //---------------------------------------------------------------------------- { m_OpType = OPTYPE_OP; m_Canundo = true; m_InsertMode = MODE_NONE; m_IntervalFrom = 0; m_IntervalTo = 0; m_FramesListBox = NULL; m_Frame = 0; m_Group = NULL; m_Cloud = NULL; m_VectorVME.clear(); m_VectorCloud.clear(); } //---------------------------------------------------------------------------- mafOpDecomposeTimeVarVME::~mafOpDecomposeTimeVarVME() //---------------------------------------------------------------------------- { if (m_Group != NULL) { for (int i = 0; i < m_VectorCloud.size(); i++) { m_VectorCloud[i]->RemoveLandmark(0); mafDEL(m_VectorCloud[i]); } for (int i = 0; i < m_VectorVME.size(); i++) { mafDEL(m_VectorVME[i]); } m_Group->ReparentTo(NULL); mafDEL(m_Group); } } //---------------------------------------------------------------------------- mafOp* mafOpDecomposeTimeVarVME::Copy() //---------------------------------------------------------------------------- { return (new mafOpDecomposeTimeVarVME(m_Label)); } //---------------------------------------------------------------------------- bool mafOpDecomposeTimeVarVME::Accept(mafNode* node) //---------------------------------------------------------------------------- { if(mafVMELandmarkCloud::SafeDownCast(node) != NULL) { if(mafVMELandmarkCloud::SafeDownCast(node)->IsOpen()) return false; } //Until VMEAnalog is non time varying if (node->IsA("mafVMEScalarMatrix")) { return false; } return (node && ((mafVME *)node)->IsAnimated()); } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::OpRun() //---------------------------------------------------------------------------- { m_Gui = new mafGUI(this); m_Gui->SetListener(this); char string[100]; m_NumberFrames = mafVMEGenericAbstract::SafeDownCast(m_Input)->GetNumberOfLocalTimeStamps(); sprintf(string, "Node has %d timestamps", m_NumberFrames); m_Gui->Label(string); ModeGui(); m_Gui->Divider(); ShowGui(); } //------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::ModeGui() //------------------------------------------------------------------------- { if(m_Gui) { m_GuiFrames = new mafGUI(this); m_GuiInterval = new mafGUI(this); m_GuiPeriodicity = new mafGUI(this); m_GuiFrames->Button(ID_INSERT_FRAME, _("Add timestamp"), "", _("Add a timestamp")); m_GuiFrames->Button(ID_REMOVE_FRAME, _("Remove timestamp"), "", _("Remove a timestamp")); double min = 0; m_GuiFrames->Double(ID_FRAME, _("Timestamp"), &m_Frame, min); m_FramesListBox = m_GuiFrames->ListBox(ID_LIST_FRAMES,_("List"),60,_("Chose label to visualize")); m_GuiInterval->Double(CHANGE_VALUE_INTERVAL, _("From"), &m_IntervalFrom, min ); m_GuiInterval->Double(CHANGE_VALUE_INTERVAL, _("To"), &m_IntervalTo, min, m_NumberFrames); m_GuiPeriodicity->Integer(CHANGE_VALUE_PERIODICITY, _("Period"), &m_Periodicity, min, m_NumberFrames); m_RollOutFrames = m_Gui->RollOut(ID_ROLLOUT_FRAMES,_("Timestamps mode"), m_GuiFrames, false); m_RollOutInterval = m_Gui->RollOut(ID_ROLLOUT_INTERVAL,_("Interval mode"), m_GuiInterval, false); m_RollOutPeriodicity = m_Gui->RollOut(ID_ROLLOUT_PERIODICITY,_("Periodicity mode"), m_GuiPeriodicity, false); m_Gui->OkCancel(); m_Gui->Divider(); EnableWidget(false); m_Gui->Update(); } } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::OnEvent(mafEventBase *maf_event) //---------------------------------------------------------------------------- { if (mafEvent *e = mafEvent::SafeDownCast(maf_event)) { switch(e->GetId()) { case wxOK: { if (UpdateFrames() == MAF_OK) { OpStop(OP_RUN_OK); } else { OpStop(OP_RUN_CANCEL); } break; } case wxCANCEL: { OpStop(OP_RUN_CANCEL); break; } case ID_INSERT_FRAME: { char frameStr[50]; int n; n = sprintf(frameStr, "%f", m_Frame); //Check if the label already exists int pos = m_FramesListBox->FindString(frameStr); if (pos == -1) { AppendFrame(frameStr); } else { wxMessageBox( _("Frame already inserted"), _("Error"), wxOK | wxICON_ERROR ); return; } } break; case ID_REMOVE_FRAME: { DeleteFrame(m_ItemId); break; } case ID_LIST_FRAMES: { m_ItemId = e->GetArg(); break; } default: { mafEventMacro(*maf_event); } break; } } if (maf_event->GetSender() == m_RollOutFrames) // from this operation gui { mafEvent *e = mafEvent::SafeDownCast(maf_event); if (e->GetBool()) { m_InsertMode = MODE_FRAMES; m_RollOutInterval->RollOut(false); m_RollOutPeriodicity->RollOut(false); EnableWidget(true); } else { m_InsertMode = MODE_NONE; EnableWidget(false); } } else if (maf_event->GetSender() == m_RollOutInterval) // from this operation gui { mafEvent *e = mafEvent::SafeDownCast(maf_event); if (e->GetBool()) { m_InsertMode = MODE_INTERVAL; m_RollOutFrames->RollOut(false); m_RollOutPeriodicity->RollOut(false); EnableWidget(true); } else { m_InsertMode = MODE_NONE; EnableWidget(false); } } else if (maf_event->GetSender() == m_RollOutPeriodicity) // from this operation gui { mafEvent *e = mafEvent::SafeDownCast(maf_event); if (e->GetBool()) { m_InsertMode = MODE_PERIODICITY; m_RollOutFrames->RollOut(false); m_RollOutInterval->RollOut(false); EnableWidget(true); } else { m_InsertMode = MODE_NONE; EnableWidget(false); } } } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::AppendFrame(char *string) //---------------------------------------------------------------------------- { if (m_FramesListBox) { m_FramesListBox->Append(string); } m_FrameLabel.push_back(string); } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::DeleteFrame(int frameId) //---------------------------------------------------------------------------- { if (m_FramesListBox) { m_FramesListBox->Delete(m_ItemId); } m_FrameLabel.erase(m_FrameLabel.begin() + frameId); } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::SelectMode(int mode) //---------------------------------------------------------------------------- { if (mode < MODE_NONE || mode > MODE_PERIODICITY) return; m_InsertMode = mode; } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::SetInterval(double from, double to) //---------------------------------------------------------------------------- { if (from >= to) return; m_IntervalFrom = from; m_IntervalTo = to; } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::SetPeriodicity(int period) //---------------------------------------------------------------------------- { m_Periodicity = period; } //---------------------------------------------------------------------------- int mafOpDecomposeTimeVarVME::UpdateFrames() //---------------------------------------------------------------------------- { //wxBusyInfo wait("Please wait, working..."); std::vector<mafTimeStamp> kframes; mafVMEGenericAbstract *vme = mafVMEGenericAbstract::SafeDownCast(m_Input); vme->GetLocalTimeStamps(kframes); mafString name = vme->GetName(); mafString groupName = "Decomposed from "; groupName << name; mafNEW(m_Group); m_Group->SetName(groupName); mafTimeStamp timeSt; switch(m_InsertMode) { case MODE_FRAMES: { int framesNummber = m_FrameLabel.size(); if (framesNummber > 0) { mafString timeStr; for (int f = 0; f < framesNummber; f++) { mafString frame = m_FrameLabel.at(f); timeSt = atof(frame.GetCStr()); //check if the inserted frame is inside the timestamps bounds if (timeSt < kframes[0] || timeSt > kframes[kframes.size()-1]) { char errorMessage[50]; sprintf(errorMessage, "Frame %s is outside timestamps bounds!", frame); wxMessageBox( errorMessage, _("Warning"), wxOK | wxICON_ERROR ); } CreateStaticVME(timeSt); } } else { return MAF_ERROR; } } break; case MODE_INTERVAL: { if (m_IntervalTo < m_IntervalFrom) { wxMessageBox( _("Not valid interval"), _("Error"), wxOK | wxICON_ERROR ); return MAF_ERROR; } int start, end; bool startFound = false; bool endFound = false; for (int n = 0; n < kframes.size(); n++) { if (m_IntervalFrom == kframes[n]) { start = n; startFound = true; } if (m_IntervalTo == kframes[n]) { end = n; endFound = true; break; } } if (!startFound) { if (m_IntervalFrom < kframes[0]) start = 0; } if (!endFound) { if (m_IntervalTo > kframes[kframes.size()-1]) end = (kframes.size()-1); } for (int n = start; n <= end; n++) { CreateStaticVME(kframes[n]); } } break; case MODE_PERIODICITY: { vme->GetLocalTimeStamps(kframes); //Check if period is valid if(m_Periodicity == 0 || m_Periodicity == kframes.size()) { wxMessageBox( _("Not valid period"), _("Error"), wxOK | wxICON_ERROR ); return MAF_ERROR; } int pCounter = 0; for (int n = 0; n <= kframes.size(); n++) { pCounter++; if (pCounter == m_Periodicity) { timeSt = kframes[n]; //Create new static VME with var "time" CreateStaticVME(timeSt); pCounter = 0; } } } break; } m_Output = m_Group; return MAF_OK; } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::CreateStaticVME(mafTimeStamp timeSt) //---------------------------------------------------------------------------- { mafMatrix *matrix; mafMatrix *matrixCopy; mafVMEItem *vmeItem; mafVMEItem *vmeItemCopy; mafTimeStamp oldTime; std::vector<mafTimeStamp> kframes; mafVMEGenericAbstract *oldVme = mafVMEGenericAbstract::SafeDownCast(m_Input); // restore due attributes mafString typeVme; typeVme = m_Input->GetTypeName(); mafSmartPointer<mafVMEFactory> factory; mafVME *newVme = factory->CreateVMEInstance(typeVme); if (!newVme) return; //If VME is a landmark, a landmark cloud must be created if (typeVme.Equals("mafVMELandmark")) { mafNEW(m_Cloud); if (m_TestMode == true) { m_Cloud->TestModeOn(); } m_Cloud->Open(); m_VectorCloud.push_back(m_Cloud); } else { m_VectorVME.push_back(newVme); } newVme->GetTagArray()->DeepCopy(oldVme->GetTagArray()); mafVMEGenericAbstract *vmeGeneric = mafVMEGenericAbstract::SafeDownCast(newVme); mafMatrixVector *mv = oldVme->GetMatrixVector(); if (mv) { matrix = mv->GetNearestMatrix(timeSt); if (matrix) { mafNEW(matrixCopy); matrixCopy->DeepCopy(matrix); vmeGeneric->GetMatrixVector()->SetMatrix(matrixCopy); oldTime = matrix->GetTimeStamp(); mafDEL(matrixCopy); } } mafDataVector *dv = oldVme->GetDataVector(); if (dv) { vmeItem = dv->GetNearestItem(timeSt); if (vmeItem) { vmeItemCopy = (mafVMEItem*)factory->CreateInstance(vmeItem->GetTypeName()); vmeItemCopy->DeepCopy(vmeItem); vmeGeneric->GetDataVector()->AppendItem(vmeItemCopy); oldTime = vmeItem->GetTimeStamp(); } } mafString newName; mafString timeStr; mafString vme_name; //Add the timestamp information to the name vme_name = oldVme->GetName(); timeStr = wxString::Format("_%.3f", oldTime); newName = vme_name; newName << timeStr; newVme->SetName(newName.GetCStr()); //If VME is a landmark, the new landmark must be added to the landmark cloud created if (m_Cloud != NULL) { mafString cloudName = "cloud_"; cloudName << newName; m_Cloud->SetName(cloudName.GetCStr()); m_Cloud->AddChild(newVme); m_Cloud->ReparentTo(m_Group); m_Group->Update(); } else { m_Group->AddChild(newVme); m_Group->Update(); } } //---------------------------------------------------------------------------- void mafOpDecomposeTimeVarVME::EnableWidget(bool enable) //---------------------------------------------------------------------------- { m_Gui->Enable(wxOK, enable); }
27.608456
113
0.51881
gradicosmo
f57b8727750a198e0a1502f24d0edbd886da32e4
432
cpp
C++
source/signalzeug/source/ScopedConnection.cpp
kateyy/libzeug
ffb697721cd8ef7d6e685fd5e2c655d711565634
[ "MIT" ]
null
null
null
source/signalzeug/source/ScopedConnection.cpp
kateyy/libzeug
ffb697721cd8ef7d6e685fd5e2c655d711565634
[ "MIT" ]
null
null
null
source/signalzeug/source/ScopedConnection.cpp
kateyy/libzeug
ffb697721cd8ef7d6e685fd5e2c655d711565634
[ "MIT" ]
null
null
null
#include <signalzeug/ScopedConnection.h> namespace signalzeug { ScopedConnection::ScopedConnection() { } ScopedConnection::ScopedConnection(const Connection & connection) : m_connection(connection) { } ScopedConnection::~ScopedConnection() { m_connection.disconnect(); } void ScopedConnection::operator=(const Connection & connection) { m_connection.disconnect(); m_connection = connection; } } // namespace signalzeug
14.896552
65
0.773148
kateyy
f583ea1463abd5da636caf8e2ca724603832cdf3
627
cpp
C++
examples/filesystem_symlink.cpp
GheisMohammadi/CppCommon
8785825f1f6a38f52ba2b5ecbd25ab0e550e897a
[ "MIT" ]
211
2016-10-09T04:10:21.000Z
2022-03-22T19:46:55.000Z
examples/filesystem_symlink.cpp
GheisMohammadi/CppCommon
8785825f1f6a38f52ba2b5ecbd25ab0e550e897a
[ "MIT" ]
26
2019-04-15T09:04:06.000Z
2022-02-18T10:52:44.000Z
examples/filesystem_symlink.cpp
GheisMohammadi/CppCommon
8785825f1f6a38f52ba2b5ecbd25ab0e550e897a
[ "MIT" ]
87
2018-12-28T14:01:03.000Z
2022-03-29T09:14:48.000Z
/*! \file filesystem_symlink.cpp \brief Filesystem symlink example \author Ivan Shynkarenka \date 04.09.2016 \copyright MIT License */ #include "filesystem/symlink.h" #include <iostream> int main(int argc, char** argv) { CppCommon::Symlink symlink("example.lnk"); // Create a new symbolic link from the executable path CppCommon::Symlink::CreateSymlink(CppCommon::Path::executable(), symlink); // Read symbolic link target std::cout << "Symbolic link target: " << symlink.target() << std::endl; // Remove symbolic link CppCommon::Symlink::Remove(symlink); return 0; }
22.392857
78
0.676236
GheisMohammadi
f5889140110839388281084925b1664fd3e98579
92,347
cc
C++
test/aarch32/test-simulator-cond-rdlow-rnlow-operand-immediate-t32.cc
Componolit/android_external_vixl
0cc1043fc66e89d6f0d538a10668a7b3bb1a372b
[ "BSD-3-Clause" ]
null
null
null
test/aarch32/test-simulator-cond-rdlow-rnlow-operand-immediate-t32.cc
Componolit/android_external_vixl
0cc1043fc66e89d6f0d538a10668a7b3bb1a372b
[ "BSD-3-Clause" ]
null
null
null
test/aarch32/test-simulator-cond-rdlow-rnlow-operand-immediate-t32.cc
Componolit/android_external_vixl
0cc1043fc66e89d6f0d538a10668a7b3bb1a372b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016, VIXL authors // 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 ARM Limited 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 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. // ----------------------------------------------------------------------------- // This file is auto generated from the // test/aarch32/config/template-simulator-aarch32.cc.in template file using // tools/generate_tests.py. // // PLEASE DO NOT EDIT. // ----------------------------------------------------------------------------- #include "test-runner.h" #include "test-utils.h" #include "test-utils-aarch32.h" #include "aarch32/assembler-aarch32.h" #include "aarch32/macro-assembler-aarch32.h" #include "aarch32/disasm-aarch32.h" #define __ masm. #define BUF_SIZE (4096) #ifdef VIXL_INCLUDE_SIMULATOR_AARCH32 // Run tests with the simulator. #define SETUP() MacroAssembler masm(BUF_SIZE) #define START() masm.GetBuffer()->Reset() #define END() \ __ Hlt(0); \ __ FinalizeCode(); // TODO: Run the tests in the simulator. #define RUN() #define TEARDOWN() #else // ifdef VIXL_INCLUDE_SIMULATOR_AARCH32. #define SETUP() \ MacroAssembler masm(BUF_SIZE); \ UseScratchRegisterScope harness_scratch(&masm); \ harness_scratch.ExcludeAll(); #define START() \ masm.GetBuffer()->Reset(); \ __ Push(r4); \ __ Push(r5); \ __ Push(r6); \ __ Push(r7); \ __ Push(r8); \ __ Push(r9); \ __ Push(r10); \ __ Push(r11); \ __ Push(lr); \ harness_scratch.Include(ip); #define END() \ harness_scratch.Exclude(ip); \ __ Pop(lr); \ __ Pop(r11); \ __ Pop(r10); \ __ Pop(r9); \ __ Pop(r8); \ __ Pop(r7); \ __ Pop(r6); \ __ Pop(r5); \ __ Pop(r4); \ __ Bx(lr); \ __ FinalizeCode(); #define RUN() \ { \ int pcs_offset = masm.IsUsingT32() ? 1 : 0; \ masm.GetBuffer()->SetExecutable(); \ ExecuteMemory(masm.GetBuffer()->GetStartAddress<byte*>(), \ masm.GetSizeOfCodeGenerated(), \ pcs_offset); \ masm.GetBuffer()->SetWritable(); \ } #define TEARDOWN() harness_scratch.Close(); #endif // ifdef VIXL_INCLUDE_SIMULATOR_AARCH32 namespace vixl { namespace aarch32 { // List of instruction encodings: #define FOREACH_INSTRUCTION(M) \ M(Add) \ M(Adds) \ M(Rsb) \ M(Rsbs) \ M(Sub) \ M(Subs) // The following definitions are defined again in each generated test, therefore // we need to place them in an anomymous namespace. It expresses that they are // local to this file only, and the compiler is not allowed to share these types // across test files during template instantiation. Specifically, `Operands` and // `Inputs` have various layouts across generated tests so they absolutely // cannot be shared. #ifdef VIXL_INCLUDE_TARGET_T32 namespace { // Values to be passed to the assembler to produce the instruction under test. struct Operands { Condition cond; Register rd; Register rn; int32_t immediate; }; // Input data to feed to the instruction. struct Inputs { uint32_t apsr; uint32_t rd; uint32_t rn; }; // This structure contains all input data needed to test one specific encoding. // It used to generate a loop over an instruction. struct TestLoopData { // The `operands` fields represents the values to pass to the assembler to // produce the instruction. Operands operands; // Description of the operands, used for error reporting. const char* operands_description; // Unique identifier, used for generating traces. const char* identifier; // Array of values to be fed to the instruction. size_t input_size; const Inputs* inputs; }; static const Inputs kRdIsRn[] = {{ZFlag, 0x00007fff, 0x00007fff}, {CFlag, 0xffffff83, 0xffffff83}, {NCFlag, 0x00000000, 0x00000000}, {NCVFlag, 0x00000000, 0x00000000}, {NZFlag, 0x00000000, 0x00000000}, {VFlag, 0x00000002, 0x00000002}, {NCFlag, 0xfffffffe, 0xfffffffe}, {NCVFlag, 0x00007ffd, 0x00007ffd}, {NZCVFlag, 0xffffffff, 0xffffffff}, {ZVFlag, 0xffffffff, 0xffffffff}, {CFlag, 0x00000002, 0x00000002}, {ZFlag, 0x80000001, 0x80000001}, {ZCFlag, 0x00007ffe, 0x00007ffe}, {ZVFlag, 0xffff8000, 0xffff8000}, {CFlag, 0x0000007e, 0x0000007e}, {ZFlag, 0xcccccccc, 0xcccccccc}, {NVFlag, 0xffff8000, 0xffff8000}, {CFlag, 0x00000001, 0x00000001}, {NFlag, 0x00000001, 0x00000001}, {NZFlag, 0xffffffe0, 0xffffffe0}, {CVFlag, 0xfffffffd, 0xfffffffd}, {ZVFlag, 0x00007ffe, 0x00007ffe}, {ZCVFlag, 0x55555555, 0x55555555}, {NCFlag, 0x00000020, 0x00000020}, {ZCFlag, 0xffffff81, 0xffffff81}, {ZCFlag, 0xcccccccc, 0xcccccccc}, {ZCFlag, 0x00000020, 0x00000020}, {NCVFlag, 0xffff8000, 0xffff8000}, {NZVFlag, 0xffff8001, 0xffff8001}, {ZVFlag, 0xffffff81, 0xffffff81}, {NZVFlag, 0xffffff81, 0xffffff81}, {NZVFlag, 0x00000000, 0x00000000}, {NVFlag, 0x00000001, 0x00000001}, {NCVFlag, 0x33333333, 0x33333333}, {NZCVFlag, 0xffff8001, 0xffff8001}, {NZCFlag, 0xffffffff, 0xffffffff}, {NCVFlag, 0x80000000, 0x80000000}, {ZCFlag, 0x00000001, 0x00000001}, {CVFlag, 0x00000020, 0x00000020}, {NCFlag, 0xffff8003, 0xffff8003}, {CVFlag, 0x00000002, 0x00000002}, {NZCFlag, 0x80000000, 0x80000000}, {VFlag, 0xffffff83, 0xffffff83}, {NZFlag, 0x33333333, 0x33333333}, {NCVFlag, 0x00007ffe, 0x00007ffe}, {NFlag, 0xffffff81, 0xffffff81}, {NZVFlag, 0x00000020, 0x00000020}, {CVFlag, 0x00007fff, 0x00007fff}, {NZCFlag, 0xffff8003, 0xffff8003}, {ZCFlag, 0xfffffffd, 0xfffffffd}, {NZFlag, 0xcccccccc, 0xcccccccc}, {ZCFlag, 0xffffffff, 0xffffffff}, {ZVFlag, 0xffffffe0, 0xffffffe0}, {ZCFlag, 0x55555555, 0x55555555}, {NVFlag, 0x00000020, 0x00000020}, {NFlag, 0xffff8000, 0xffff8000}, {ZFlag, 0x00000000, 0x00000000}, {VFlag, 0xffffffe0, 0xffffffe0}, {CFlag, 0xffff8001, 0xffff8001}, {NZCVFlag, 0xfffffffd, 0xfffffffd}, {NCVFlag, 0x0000007d, 0x0000007d}, {NCVFlag, 0x0000007f, 0x0000007f}, {NZFlag, 0xffff8003, 0xffff8003}, {ZCFlag, 0xffffff82, 0xffffff82}, {ZFlag, 0xffff8001, 0xffff8001}, {NZFlag, 0xffff8002, 0xffff8002}, {NZFlag, 0x00000020, 0x00000020}, {NCFlag, 0x33333333, 0x33333333}, {ZCVFlag, 0x80000000, 0x80000000}, {NZCFlag, 0xffffffe0, 0xffffffe0}, {NZFlag, 0x00007fff, 0x00007fff}, {NZVFlag, 0x00000002, 0x00000002}, {NFlag, 0x55555555, 0x55555555}, {NVFlag, 0xffffffff, 0xffffffff}, {NCFlag, 0x00007fff, 0x00007fff}, {NZCVFlag, 0xffffff81, 0xffffff81}, {ZCVFlag, 0x00007fff, 0x00007fff}, {NZFlag, 0x0000007d, 0x0000007d}, {VFlag, 0x00007ffe, 0x00007ffe}, {CVFlag, 0xffffff83, 0xffffff83}, {NZFlag, 0x80000000, 0x80000000}, {ZCFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NCFlag, 0x0000007f, 0x0000007f}, {CFlag, 0x00000020, 0x00000020}, {NZCFlag, 0x00000001, 0x00000001}, {NZCFlag, 0xcccccccc, 0xcccccccc}, {NZCFlag, 0xffffff80, 0xffffff80}, {NCVFlag, 0xffff8003, 0xffff8003}, {NFlag, 0x0000007d, 0x0000007d}, {NZVFlag, 0x55555555, 0x55555555}, {NZCVFlag, 0xfffffffe, 0xfffffffe}, {NCFlag, 0xffff8000, 0xffff8000}, {CFlag, 0x80000001, 0x80000001}, {NVFlag, 0xffffffe0, 0xffffffe0}, {CFlag, 0xffffff82, 0xffffff82}, {NZCVFlag, 0x00007ffd, 0x00007ffd}, {CFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NZCFlag, 0xffffff81, 0xffffff81}, {ZFlag, 0x00007ffd, 0x00007ffd}, {NZVFlag, 0xffffffe0, 0xffffffe0}, {NZVFlag, 0x00007ffe, 0x00007ffe}, {NZFlag, 0x7ffffffd, 0x7ffffffd}, {NZCFlag, 0xfffffffe, 0xfffffffe}, {NZCVFlag, 0x7ffffffd, 0x7ffffffd}, {ZVFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {CFlag, 0x00000000, 0x00000000}, {ZCVFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NZFlag, 0x00007ffd, 0x00007ffd}, {VFlag, 0xffff8000, 0xffff8000}, {CVFlag, 0xcccccccc, 0xcccccccc}, {NZCVFlag, 0xffff8003, 0xffff8003}, {NVFlag, 0x00007ffe, 0x00007ffe}, {ZVFlag, 0xfffffffd, 0xfffffffd}, {NZCFlag, 0x0000007e, 0x0000007e}, {VFlag, 0x00000000, 0x00000000}, {NZFlag, 0x00000002, 0x00000002}, {ZCFlag, 0x7fffffff, 0x7fffffff}, {ZFlag, 0x0000007e, 0x0000007e}, {NZCFlag, 0x7fffffff, 0x7fffffff}, {ZVFlag, 0xffff8002, 0xffff8002}, {ZFlag, 0x00000020, 0x00000020}, {NZFlag, 0xffffff81, 0xffffff81}, {ZCVFlag, 0x00000000, 0x00000000}, {CFlag, 0xffffff81, 0xffffff81}, {NVFlag, 0x0000007e, 0x0000007e}, {NZFlag, 0x55555555, 0x55555555}, {CFlag, 0x0000007d, 0x0000007d}, {NCFlag, 0x7fffffff, 0x7fffffff}, {NCFlag, 0xffff8001, 0xffff8001}, {CFlag, 0xffffffe0, 0xffffffe0}, {ZVFlag, 0x7ffffffe, 0x7ffffffe}, {VFlag, 0x7ffffffd, 0x7ffffffd}, {CFlag, 0xffffffff, 0xffffffff}, {ZCFlag, 0xffff8000, 0xffff8000}, {NZVFlag, 0xffff8003, 0xffff8003}, {NCFlag, 0x0000007d, 0x0000007d}, {NZVFlag, 0x0000007f, 0x0000007f}, {CFlag, 0xcccccccc, 0xcccccccc}, {CVFlag, 0x00000001, 0x00000001}, {NZCFlag, 0xffff8001, 0xffff8001}, {NCVFlag, 0x00000020, 0x00000020}, {NZVFlag, 0xffffff82, 0xffffff82}, {NCFlag, 0x00007ffd, 0x00007ffd}, {ZVFlag, 0x0000007e, 0x0000007e}, {NZFlag, 0x80000001, 0x80000001}, {NVFlag, 0x7ffffffe, 0x7ffffffe}, {NZCVFlag, 0x00000000, 0x00000000}, {CVFlag, 0x55555555, 0x55555555}, {ZVFlag, 0x00000020, 0x00000020}, {VFlag, 0x00000020, 0x00000020}, {NFlag, 0xcccccccc, 0xcccccccc}, {NVFlag, 0x0000007d, 0x0000007d}, {CVFlag, 0x0000007f, 0x0000007f}, {NZCFlag, 0x00000002, 0x00000002}, {NZCFlag, 0x00007fff, 0x00007fff}, {NZVFlag, 0x0000007d, 0x0000007d}, {NZVFlag, 0xfffffffd, 0xfffffffd}, {NFlag, 0x00000002, 0x00000002}, {NZCVFlag, 0x0000007d, 0x0000007d}, {NVFlag, 0xffffff82, 0xffffff82}, {VFlag, 0x00007fff, 0x00007fff}, {NZCVFlag, 0x00000001, 0x00000001}, {ZFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {CVFlag, 0xffff8002, 0xffff8002}, {NFlag, 0x7fffffff, 0x7fffffff}, {NCVFlag, 0xffffff80, 0xffffff80}, {ZFlag, 0x33333333, 0x33333333}, {NZFlag, 0x00000001, 0x00000001}, {NCVFlag, 0x7ffffffe, 0x7ffffffe}, {VFlag, 0x00000001, 0x00000001}, {ZCFlag, 0x0000007f, 0x0000007f}, {ZVFlag, 0x80000001, 0x80000001}, {ZVFlag, 0xffff8003, 0xffff8003}, {NCVFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NZCVFlag, 0xffffffe0, 0xffffffe0}, {VFlag, 0x33333333, 0x33333333}, {NCFlag, 0xffffff80, 0xffffff80}, {ZFlag, 0x00007ffe, 0x00007ffe}, {NVFlag, 0x00000000, 0x00000000}, {NZCFlag, 0x00007ffd, 0x00007ffd}, {NZFlag, 0xfffffffd, 0xfffffffd}, {VFlag, 0xffffffff, 0xffffffff}, {NZCFlag, 0xffffff83, 0xffffff83}, {NZVFlag, 0xffff8002, 0xffff8002}, {NZCVFlag, 0x33333333, 0x33333333}, {ZCVFlag, 0xfffffffd, 0xfffffffd}, {ZCFlag, 0x80000001, 0x80000001}, {NCFlag, 0x00007ffe, 0x00007ffe}, {NFlag, 0xfffffffd, 0xfffffffd}, {NZCVFlag, 0x7fffffff, 0x7fffffff}, {VFlag, 0xffff8001, 0xffff8001}, {NZVFlag, 0xffff8000, 0xffff8000}, {ZCVFlag, 0xcccccccc, 0xcccccccc}, {VFlag, 0x7ffffffe, 0x7ffffffe}, {ZFlag, 0xffff8002, 0xffff8002}, {ZCFlag, 0x0000007d, 0x0000007d}, {NZCVFlag, 0xffffff83, 0xffffff83}, {ZVFlag, 0x00000001, 0x00000001}, {NZCVFlag, 0xffff8002, 0xffff8002}, {ZCFlag, 0xffffff83, 0xffffff83}, {CFlag, 0xffff8003, 0xffff8003}, {NCVFlag, 0xffffffff, 0xffffffff}, {CFlag, 0xfffffffe, 0xfffffffe}, {NZFlag, 0xffffff80, 0xffffff80}, {CVFlag, 0x00007ffd, 0x00007ffd}, {ZCVFlag, 0x0000007d, 0x0000007d}, {ZVFlag, 0xcccccccc, 0xcccccccc}, {NVFlag, 0x00007ffd, 0x00007ffd}, {NZFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {ZFlag, 0x0000007f, 0x0000007f}, {CVFlag, 0xffff8003, 0xffff8003}, {ZFlag, 0xffffffe0, 0xffffffe0}, {NZVFlag, 0xcccccccc, 0xcccccccc}, {NFlag, 0x00007ffe, 0x00007ffe}, {NFlag, 0xffff8003, 0xffff8003}, {NZVFlag, 0xffffffff, 0xffffffff}, {CFlag, 0x00007fff, 0x00007fff}, {NCVFlag, 0x7fffffff, 0x7fffffff}, {CFlag, 0x33333333, 0x33333333}, {ZCFlag, 0x80000000, 0x80000000}, {ZCFlag, 0x0000007e, 0x0000007e}, {NVFlag, 0x7fffffff, 0x7fffffff}, {NZFlag, 0x7ffffffe, 0x7ffffffe}, {CFlag, 0xffff8002, 0xffff8002}, {NCFlag, 0x80000000, 0x80000000}, {VFlag, 0x7fffffff, 0x7fffffff}, {NZFlag, 0xffffffff, 0xffffffff}, {NFlag, 0x7ffffffd, 0x7ffffffd}, {ZFlag, 0x00000002, 0x00000002}, {ZCVFlag, 0xffff8003, 0xffff8003}, {CFlag, 0x7fffffff, 0x7fffffff}, {CFlag, 0x0000007f, 0x0000007f}, {VFlag, 0x80000001, 0x80000001}, {ZCFlag, 0x00007fff, 0x00007fff}, {CFlag, 0xfffffffd, 0xfffffffd}, {NZFlag, 0x7fffffff, 0x7fffffff}, {CVFlag, 0xffff8001, 0xffff8001}, {NZVFlag, 0x00007fff, 0x00007fff}, {NZVFlag, 0x7ffffffe, 0x7ffffffe}, {ZCVFlag, 0x0000007e, 0x0000007e}, {NZVFlag, 0x00000001, 0x00000001}, {ZFlag, 0xffffffff, 0xffffffff}, {NZFlag, 0xfffffffe, 0xfffffffe}, {NZCVFlag, 0x0000007f, 0x0000007f}, {NZCVFlag, 0x80000000, 0x80000000}, {VFlag, 0x55555555, 0x55555555}, {NVFlag, 0xffff8001, 0xffff8001}, {NFlag, 0xffffff83, 0xffffff83}, {NZVFlag, 0x7ffffffd, 0x7ffffffd}, {ZVFlag, 0x00000000, 0x00000000}, {NCVFlag, 0xfffffffd, 0xfffffffd}, {CFlag, 0x00007ffe, 0x00007ffe}, {NVFlag, 0xffffff83, 0xffffff83}, {NZFlag, 0x0000007e, 0x0000007e}, {VFlag, 0x80000000, 0x80000000}, {NZCFlag, 0xffff8000, 0xffff8000}, {ZCFlag, 0xffff8001, 0xffff8001}, {NVFlag, 0x00007fff, 0x00007fff}, {ZCVFlag, 0xffffff81, 0xffffff81}, {NZVFlag, 0x0000007e, 0x0000007e}, {CVFlag, 0xffff8000, 0xffff8000}, {VFlag, 0xffffff82, 0xffffff82}, {VFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NZCVFlag, 0xcccccccc, 0xcccccccc}, {CVFlag, 0x33333333, 0x33333333}, {NCFlag, 0xffffffff, 0xffffffff}, {VFlag, 0xffffff80, 0xffffff80}, {NVFlag, 0xffff8002, 0xffff8002}, {ZCFlag, 0x00000000, 0x00000000}, {ZCVFlag, 0x80000001, 0x80000001}, {NZCVFlag, 0x80000001, 0x80000001}, {NCFlag, 0x55555555, 0x55555555}, {CVFlag, 0x7ffffffe, 0x7ffffffe}, {ZVFlag, 0x7ffffffd, 0x7ffffffd}, {ZCVFlag, 0xffff8000, 0xffff8000}, {ZCFlag, 0xffff8002, 0xffff8002}, {NFlag, 0xfffffffe, 0xfffffffe}, {ZCVFlag, 0x0000007f, 0x0000007f}, {NCVFlag, 0xfffffffe, 0xfffffffe}, {ZCVFlag, 0x7fffffff, 0x7fffffff}, {CVFlag, 0x0000007e, 0x0000007e}, {NZCVFlag, 0x7ffffffe, 0x7ffffffe}, {CFlag, 0xffffff80, 0xffffff80}, {VFlag, 0x00007ffd, 0x00007ffd}, {CVFlag, 0xffffffe0, 0xffffffe0}, {CFlag, 0x7ffffffe, 0x7ffffffe}, {CFlag, 0x80000000, 0x80000000}, {CVFlag, 0xfffffffe, 0xfffffffe}, {NCVFlag, 0xffff8002, 0xffff8002}, {ZCVFlag, 0x33333333, 0x33333333}, {NZCFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NVFlag, 0x55555555, 0x55555555}, {NVFlag, 0x80000000, 0x80000000}, {NZCVFlag, 0x00007ffe, 0x00007ffe}, {ZFlag, 0xffffff83, 0xffffff83}, {NCFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NZVFlag, 0xfffffffe, 0xfffffffe}, {CVFlag, 0xaaaaaaaa, 0xaaaaaaaa}, {NZCFlag, 0xffff8002, 0xffff8002}, {VFlag, 0x0000007d, 0x0000007d}}; static const Inputs kRdIsNotRn[] = {{NZCVFlag, 0xffff8000, 0xffffffff}, {CVFlag, 0xcccccccc, 0xffffff80}, {NCFlag, 0xfffffffe, 0xfffffffd}, {NCFlag, 0xcccccccc, 0xcccccccc}, {ZFlag, 0x80000001, 0xffffffff}, {NCFlag, 0xffffff82, 0x0000007d}, {NCVFlag, 0x0000007d, 0xffff8001}, {NVFlag, 0x00007fff, 0x7fffffff}, {NVFlag, 0x80000001, 0xffffff82}, {ZCVFlag, 0xffffffff, 0x0000007e}, {ZCVFlag, 0xffffff80, 0x0000007d}, {ZCVFlag, 0x00000020, 0xaaaaaaaa}, {CVFlag, 0x00007fff, 0x00000020}, {NVFlag, 0xffff8000, 0xffffff82}, {NZFlag, 0xffffff82, 0x7ffffffe}, {NZVFlag, 0xffff8003, 0x33333333}, {ZCVFlag, 0x00007ffe, 0x7ffffffe}, {NFlag, 0x0000007f, 0xffffffff}, {NZCFlag, 0x33333333, 0x80000000}, {ZCFlag, 0x80000001, 0xffffffff}, {VFlag, 0x00007ffd, 0x00000001}, {ZVFlag, 0xffffffff, 0x0000007e}, {NZFlag, 0x00000001, 0xcccccccc}, {NZVFlag, 0x00000020, 0xffff8001}, {NCVFlag, 0x7ffffffe, 0xffffff80}, {ZCFlag, 0x33333333, 0x00007fff}, {CFlag, 0xffffff82, 0x0000007e}, {ZCFlag, 0x55555555, 0xffff8003}, {NFlag, 0x0000007f, 0x00000001}, {ZCVFlag, 0x00000020, 0xfffffffd}, {ZVFlag, 0x0000007e, 0xffff8003}, {ZCVFlag, 0x00000020, 0x80000001}, {ZCFlag, 0xfffffffe, 0x55555555}, {NFlag, 0xfffffffd, 0xfffffffe}, {VFlag, 0xffffff82, 0x7ffffffe}, {CVFlag, 0xffffff80, 0x0000007f}, {NVFlag, 0x00000020, 0xffff8001}, {NCFlag, 0x0000007d, 0x80000000}, {CVFlag, 0x00000020, 0xffffff83}, {NZCVFlag, 0x0000007f, 0x00000000}, {ZVFlag, 0xffffff82, 0x7ffffffd}, {ZVFlag, 0xffff8000, 0x80000001}, {NFlag, 0xcccccccc, 0x0000007e}, {NFlag, 0x55555555, 0xffffff80}, {NCFlag, 0x80000000, 0x00007ffd}, {ZVFlag, 0x00007ffd, 0x00007ffe}, {ZCVFlag, 0x00000000, 0x7ffffffe}, {ZFlag, 0xffff8001, 0xffffffff}, {NCFlag, 0xfffffffe, 0x55555555}, {VFlag, 0x7ffffffd, 0x80000001}, {VFlag, 0x80000000, 0xffffffff}, {CFlag, 0xffffff82, 0xffffff80}, {NZCFlag, 0xffff8003, 0xfffffffd}, {CFlag, 0x00000020, 0x00007fff}, {NZVFlag, 0xffff8002, 0xfffffffe}, {NVFlag, 0xffffff80, 0x0000007e}, {NVFlag, 0xcccccccc, 0x0000007d}, {CFlag, 0x0000007f, 0x00000001}, {ZVFlag, 0xffff8002, 0xffffff81}, {NZVFlag, 0x80000000, 0x00007ffe}, {NZCVFlag, 0x80000000, 0x7ffffffe}, {ZVFlag, 0x7ffffffe, 0x80000000}, {ZFlag, 0xffff8000, 0xffffff80}, {VFlag, 0x00007ffd, 0x00007ffd}, {ZCFlag, 0x0000007d, 0x0000007e}, {NCFlag, 0x00000000, 0x7ffffffe}, {NVFlag, 0x00000020, 0xaaaaaaaa}, {NVFlag, 0xffffff83, 0x0000007e}, {NZFlag, 0xffff8002, 0x7ffffffd}, {CVFlag, 0xcccccccc, 0x00000001}, {NZFlag, 0x33333333, 0x0000007e}, {NZCFlag, 0x00000002, 0x7ffffffd}, {NZFlag, 0x00007ffd, 0xffffff80}, {ZVFlag, 0x00007ffd, 0xfffffffe}, {NZCVFlag, 0xffff8000, 0x80000000}, {NZFlag, 0xffff8002, 0xffffffff}, {CFlag, 0x00000002, 0xffff8000}, {NZCFlag, 0x0000007d, 0xffffff80}, {ZVFlag, 0x0000007d, 0xffff8003}, {VFlag, 0x55555555, 0xffff8000}, {CFlag, 0x00007fff, 0x00000001}, {VFlag, 0x80000001, 0x33333333}, {ZCFlag, 0xaaaaaaaa, 0xffffff82}, {VFlag, 0x00000002, 0x00007ffd}, {ZVFlag, 0x7ffffffe, 0xffff8001}, {ZCFlag, 0x7fffffff, 0x00000000}, {CVFlag, 0x55555555, 0x0000007e}, {VFlag, 0x55555555, 0x0000007e}, {NZCVFlag, 0x80000000, 0x7ffffffd}, {ZFlag, 0x0000007d, 0x00000000}, {NZVFlag, 0xffffff80, 0x00000002}, {NVFlag, 0xfffffffd, 0x00000001}, {ZVFlag, 0x7ffffffd, 0xfffffffd}, {VFlag, 0xffff8002, 0x55555555}, {ZCVFlag, 0x00000001, 0xffff8002}, {NVFlag, 0xffff8002, 0x00000020}, {ZFlag, 0x33333333, 0xffff8002}, {ZCVFlag, 0x55555555, 0xffffff82}, {CVFlag, 0x7ffffffe, 0xffffffe0}, {NVFlag, 0xcccccccc, 0x00007ffd}, {NZFlag, 0x00000001, 0x0000007f}, {ZFlag, 0xfffffffe, 0x00007fff}, {NCVFlag, 0x80000001, 0xffffff83}, {NCVFlag, 0xaaaaaaaa, 0xffff8002}, {ZVFlag, 0x00007fff, 0xffff8000}, {ZFlag, 0xffff8001, 0xfffffffd}, {CFlag, 0x55555555, 0x80000000}, {ZCVFlag, 0xcccccccc, 0xfffffffe}, {NZCVFlag, 0xffff8003, 0x7fffffff}, {NZCVFlag, 0x00007ffe, 0xffffff81}, {NZCFlag, 0xfffffffd, 0xaaaaaaaa}, {NVFlag, 0x00000002, 0x00000020}, {ZCVFlag, 0xffff8003, 0xfffffffd}, {NFlag, 0xffff8001, 0x00007ffe}, {ZCFlag, 0xaaaaaaaa, 0x00000002}, {NCVFlag, 0xffff8000, 0xfffffffe}, {CFlag, 0x00000020, 0x00000000}, {NZVFlag, 0x00007ffd, 0xffffff81}, {NVFlag, 0x00007fff, 0x00000020}, {ZFlag, 0x0000007e, 0x80000001}, {CVFlag, 0x0000007d, 0xaaaaaaaa}, {NZVFlag, 0x7fffffff, 0x55555555}, {VFlag, 0xffffffff, 0x00007ffd}, {NFlag, 0x80000000, 0xffffffe0}, {ZVFlag, 0xffffff82, 0xfffffffe}, {CVFlag, 0x0000007d, 0x00007fff}, {CFlag, 0x7ffffffe, 0x55555555}, {ZFlag, 0xffffff82, 0x7fffffff}, {NZCFlag, 0xfffffffd, 0xffffff83}, {CVFlag, 0x80000001, 0x80000000}, {ZVFlag, 0x00000001, 0xfffffffe}, {CVFlag, 0x00000001, 0x33333333}, {NZFlag, 0x7ffffffd, 0x80000000}, {NZVFlag, 0x00007ffd, 0xaaaaaaaa}, {CVFlag, 0x0000007e, 0xffffff82}, {CVFlag, 0x7ffffffe, 0xffff8002}, {NVFlag, 0xfffffffe, 0xffff8003}, {NFlag, 0x7fffffff, 0x80000001}, {CFlag, 0xffffff82, 0x00000002}, {CVFlag, 0xcccccccc, 0x0000007e}, {NZCVFlag, 0x00000001, 0x7ffffffe}, {NFlag, 0x00000000, 0x55555555}, {NZFlag, 0xffffff81, 0x00000000}, {NZVFlag, 0xffffffe0, 0x0000007e}, {ZCFlag, 0xffff8002, 0xaaaaaaaa}, {NZVFlag, 0x7fffffff, 0x0000007d}, {ZVFlag, 0x0000007e, 0xffff8001}, {NCVFlag, 0xffffff83, 0xaaaaaaaa}, {ZFlag, 0xffffff82, 0xffffff83}, {VFlag, 0x00000001, 0x55555555}, {NFlag, 0x00000020, 0x80000000}, {NZFlag, 0x00000000, 0xfffffffe}, {VFlag, 0xffffff83, 0xaaaaaaaa}, {ZFlag, 0xffff8002, 0xffffff83}, {NZVFlag, 0xcccccccc, 0x7ffffffe}, {ZVFlag, 0x00000000, 0x55555555}, {NCFlag, 0x33333333, 0xffff8003}, {NZCVFlag, 0xfffffffd, 0x00000000}, {NZCVFlag, 0x00000020, 0xffff8000}, {CVFlag, 0xffff8001, 0xffffff83}, {CFlag, 0xffffff83, 0x33333333}, {CVFlag, 0x7ffffffd, 0x00000020}, {NCVFlag, 0xffffffe0, 0x80000000}, {NCVFlag, 0xffffff82, 0xcccccccc}, {NZCVFlag, 0xaaaaaaaa, 0x00007fff}, {VFlag, 0xcccccccc, 0xffff8003}, {ZCVFlag, 0x55555555, 0xffffffe0}, {NZCFlag, 0xffffff83, 0xffff8000}, {ZVFlag, 0xffff8001, 0x0000007d}, {CVFlag, 0xffffff83, 0x00000002}, {NVFlag, 0x7fffffff, 0x0000007d}, {VFlag, 0x55555555, 0x33333333}, {NCVFlag, 0x00000002, 0xffffff80}, {ZFlag, 0xfffffffd, 0x00007fff}, {ZCFlag, 0xffff8003, 0x0000007d}, {NZCFlag, 0xffff8002, 0xffff8000}, {NCVFlag, 0x00000020, 0xffff8002}, {ZVFlag, 0xffff8000, 0x00000020}, {ZCVFlag, 0x0000007f, 0xffffffe0}, {NZCFlag, 0xffffff80, 0x33333333}, {NCVFlag, 0x00007fff, 0xaaaaaaaa}, {ZCVFlag, 0x00000020, 0xffffff82}, {NFlag, 0x00000000, 0x0000007d}, {NCVFlag, 0x00000001, 0x00007ffe}, {ZFlag, 0x80000001, 0x00000002}, {NZVFlag, 0xffff8000, 0x00000020}, {CVFlag, 0xffff8002, 0xcccccccc}, {NVFlag, 0xffffff83, 0x80000000}, {ZCFlag, 0x0000007f, 0xffffff80}, {NZFlag, 0xcccccccc, 0xffffffff}, {NZFlag, 0x00007fff, 0x0000007f}, {NZFlag, 0xfffffffd, 0xffff8001}, {CFlag, 0x0000007d, 0x7ffffffd}, {ZCFlag, 0xffff8000, 0xffff8003}, {ZVFlag, 0xffffffff, 0xffffffe0}, {NZCFlag, 0x00007ffd, 0xcccccccc}, {NCVFlag, 0x0000007d, 0x00000020}, {ZCFlag, 0xaaaaaaaa, 0x80000000}, {ZCVFlag, 0xfffffffd, 0x0000007d}, {ZFlag, 0xffffffe0, 0xfffffffe}, {VFlag, 0xffff8003, 0x80000000}, {NZCFlag, 0x00007fff, 0xffffff82}, {NCVFlag, 0x00000002, 0x33333333}, {NZCVFlag, 0x00000000, 0xffffff82}, {VFlag, 0x80000000, 0x80000000}, {ZVFlag, 0x80000001, 0x33333333}, {ZFlag, 0x7ffffffe, 0x00007fff}, {NZCVFlag, 0x7fffffff, 0x00007fff}, {ZCFlag, 0xffffff83, 0xaaaaaaaa}, {NZVFlag, 0xffff8002, 0xffffffe0}, {VFlag, 0xfffffffd, 0xffffff81}, {NZFlag, 0x7fffffff, 0x7ffffffd}, {NZCVFlag, 0x0000007f, 0xcccccccc}, {NZCFlag, 0xffff8001, 0x00000020}, {ZFlag, 0x00000020, 0xffff8002}, {ZVFlag, 0x55555555, 0x00007ffd}, {NZVFlag, 0xcccccccc, 0x33333333}, {CFlag, 0x80000000, 0x80000000}, {ZCVFlag, 0xcccccccc, 0x00007ffd}, {ZFlag, 0xffff8002, 0xffffff80}, {CVFlag, 0x7ffffffd, 0xffffff80}, {NZCVFlag, 0x00000001, 0x00000001}, {NFlag, 0xfffffffe, 0xffffffe0}, {ZVFlag, 0x0000007e, 0x0000007f}, {NCVFlag, 0xffff8002, 0xffff8002}, {ZCVFlag, 0xffffff82, 0x80000001}, {CVFlag, 0x0000007d, 0x0000007d}, {NZVFlag, 0xcccccccc, 0xffffff83}, {VFlag, 0xffffff82, 0xfffffffd}, {CFlag, 0x0000007d, 0x0000007f}, {NFlag, 0x0000007d, 0x00000001}, {NVFlag, 0x00007ffd, 0xfffffffe}, {NZVFlag, 0x33333333, 0xffffff80}, {NVFlag, 0x0000007e, 0x00007ffe}, {ZFlag, 0xffff8001, 0x0000007e}, {VFlag, 0x80000000, 0x00000002}, {NVFlag, 0x00000020, 0x00007ffe}, {CFlag, 0x00007ffe, 0x0000007f}, {ZCFlag, 0xffff8002, 0x00000020}, {NCVFlag, 0x00000001, 0xffff8000}, {NZCVFlag, 0x0000007e, 0xffff8001}, {ZCFlag, 0x0000007f, 0xffffff81}, {ZVFlag, 0xfffffffd, 0x00007ffd}, {NCFlag, 0x0000007d, 0xcccccccc}, {NZFlag, 0xfffffffd, 0xfffffffe}, {ZCFlag, 0xffff8003, 0x80000000}, {CFlag, 0x0000007d, 0xffff8002}, {ZVFlag, 0x0000007f, 0x00007ffe}, {NCVFlag, 0xffff8002, 0x00000001}, {ZCFlag, 0x80000001, 0x0000007e}, {NCFlag, 0x00000000, 0xaaaaaaaa}, {ZCVFlag, 0x33333333, 0x80000001}, {CFlag, 0x80000000, 0x0000007d}, {NCVFlag, 0x80000001, 0x80000000}, {ZCVFlag, 0x7ffffffe, 0xffffff82}, {ZCFlag, 0xfffffffd, 0xffff8000}, {ZFlag, 0x80000000, 0x55555555}, {ZVFlag, 0x0000007d, 0xffff8000}, {ZCFlag, 0x80000001, 0xffff8001}, {NVFlag, 0xffff8002, 0x00007ffe}, {ZCFlag, 0x00000000, 0xffff8000}, {CFlag, 0xffffff81, 0xffffffff}, {CFlag, 0xffffffff, 0x80000001}, {CFlag, 0x80000001, 0x7ffffffd}, {ZFlag, 0x80000001, 0x00007fff}, {ZVFlag, 0xffff8002, 0xffff8001}, {NZFlag, 0x80000000, 0x00007ffd}, {NZCFlag, 0x33333333, 0xcccccccc}, {ZCFlag, 0xffffffff, 0x33333333}, {VFlag, 0x80000001, 0x55555555}, {CFlag, 0xffffff82, 0x00000001}, {ZVFlag, 0xffff8003, 0xffff8001}, {NCVFlag, 0xffff8003, 0xffffffe0}, {ZCVFlag, 0xffffffe0, 0x7ffffffd}, {NFlag, 0xffff8003, 0x7ffffffe}, {VFlag, 0xffffffff, 0x00000001}, {CVFlag, 0xcccccccc, 0xfffffffe}, {NZVFlag, 0xffff8003, 0x0000007f}, {NZVFlag, 0x0000007d, 0x00000002}, {NVFlag, 0x0000007d, 0x00000000}, {NVFlag, 0x00000002, 0xffff8002}, {ZCVFlag, 0xffff8001, 0xfffffffd}, {CVFlag, 0x00007fff, 0x0000007d}, {NCFlag, 0x33333333, 0x00000002}, {NCVFlag, 0xcccccccc, 0xaaaaaaaa}, {CVFlag, 0x80000000, 0x00007ffd}, {NZFlag, 0xffffff81, 0x55555555}, {CFlag, 0xffff8003, 0x33333333}, {NZCVFlag, 0xffffffe0, 0xffffff82}, {NVFlag, 0x80000001, 0xfffffffd}, {CFlag, 0xffff8000, 0x33333333}, {NCVFlag, 0xffff8003, 0x0000007f}, {CFlag, 0x00000000, 0x0000007d}, {NVFlag, 0x0000007e, 0xcccccccc}, {NZFlag, 0x7ffffffe, 0xffffffe0}, {ZVFlag, 0xffffffe0, 0xffffff82}, {ZCVFlag, 0x80000001, 0x55555555}, {NZFlag, 0xcccccccc, 0xffff8001}, {NFlag, 0x55555555, 0x00000020}, {ZVFlag, 0x00007ffd, 0xffffff83}}; static const Inputs kImmediate[] = {{CFlag, 0xabababab, 0xffffff82}, {CVFlag, 0xabababab, 0x0000007f}, {NFlag, 0xabababab, 0x80000001}, {NZFlag, 0xabababab, 0xfffffffd}, {VFlag, 0xabababab, 0x7ffffffd}, {CFlag, 0xabababab, 0x7ffffffe}, {ZFlag, 0xabababab, 0xaaaaaaaa}, {NZVFlag, 0xabababab, 0x0000007e}, {NZVFlag, 0xabababab, 0x80000001}, {CFlag, 0xabababab, 0xffffff81}, {NZVFlag, 0xabababab, 0xfffffffd}, {NZFlag, 0xabababab, 0x00007fff}, {VFlag, 0xabababab, 0x00000001}, {CVFlag, 0xabababab, 0xffffffff}, {NZCVFlag, 0xabababab, 0xffffffff}, {CFlag, 0xabababab, 0x00000000}, {NZFlag, 0xabababab, 0xffffff83}, {NCFlag, 0xabababab, 0x0000007e}, {NZCVFlag, 0xabababab, 0x7fffffff}, {ZCVFlag, 0xabababab, 0x00000002}, {CFlag, 0xabababab, 0x80000000}, {NZCFlag, 0xabababab, 0x7ffffffd}, {ZFlag, 0xabababab, 0xffff8000}, {CFlag, 0xabababab, 0x7ffffffd}, {NVFlag, 0xabababab, 0x55555555}, {NZCFlag, 0xabababab, 0xfffffffd}, {CVFlag, 0xabababab, 0xaaaaaaaa}, {NZCVFlag, 0xabababab, 0xffff8003}, {NZFlag, 0xabababab, 0xffffffe0}, {NZCFlag, 0xabababab, 0x00007ffd}, {ZCVFlag, 0xabababab, 0xffffff80}, {NZFlag, 0xabababab, 0x7ffffffd}, {ZCFlag, 0xabababab, 0x7fffffff}, {ZVFlag, 0xabababab, 0xffffff81}, {VFlag, 0xabababab, 0x7fffffff}, {NCVFlag, 0xabababab, 0xcccccccc}, {ZVFlag, 0xabababab, 0x00007fff}, {NZFlag, 0xabababab, 0x00000002}, {NVFlag, 0xabababab, 0x00000002}, {ZVFlag, 0xabababab, 0xffff8002}, {NZVFlag, 0xabababab, 0x00000020}, {ZCVFlag, 0xabababab, 0xaaaaaaaa}, {ZCFlag, 0xabababab, 0x00000000}, {NZCVFlag, 0xabababab, 0xaaaaaaaa}, {NZFlag, 0xabababab, 0xfffffffe}, {NZCFlag, 0xabababab, 0xffffffe0}, {NFlag, 0xabababab, 0xaaaaaaaa}, {ZVFlag, 0xabababab, 0xffffff80}, {VFlag, 0xabababab, 0x0000007f}, {ZVFlag, 0xabababab, 0x33333333}, {NZFlag, 0xabababab, 0x00007ffd}, {NCFlag, 0xabababab, 0x00000002}, {NVFlag, 0xabababab, 0x00007ffd}, {ZFlag, 0xabababab, 0x00000001}, {CVFlag, 0xabababab, 0x7fffffff}, {CFlag, 0xabababab, 0xaaaaaaaa}, {NZCVFlag, 0xabababab, 0x80000001}, {CVFlag, 0xabababab, 0x00000002}, {ZVFlag, 0xabababab, 0x0000007e}, {VFlag, 0xabababab, 0xffffffff}, {NCFlag, 0xabababab, 0x00000001}, {NZCFlag, 0xabababab, 0xcccccccc}, {CVFlag, 0xabababab, 0x80000001}, {NVFlag, 0xabababab, 0xffffff82}, {NZCVFlag, 0xabababab, 0x0000007e}, {CFlag, 0xabababab, 0xffffffe0}, {ZCFlag, 0xabababab, 0xffff8002}, {NZVFlag, 0xabababab, 0x7fffffff}, {NZVFlag, 0xabababab, 0x33333333}, {NZCFlag, 0xabababab, 0x0000007d}, {NFlag, 0xabababab, 0x7ffffffe}, {ZCVFlag, 0xabababab, 0xcccccccc}, {ZCFlag, 0xabababab, 0xfffffffe}, {NVFlag, 0xabababab, 0x00007ffe}, {NZFlag, 0xabababab, 0x00007ffe}, {NCVFlag, 0xabababab, 0xffffff82}, {NZVFlag, 0xabababab, 0x00000002}, {ZVFlag, 0xabababab, 0x7fffffff}, {NZCFlag, 0xabababab, 0xffff8001}, {VFlag, 0xabababab, 0xffffff83}, {ZCVFlag, 0xabababab, 0x0000007e}, {NZCFlag, 0xabababab, 0xffffff83}, {NCFlag, 0xabababab, 0x00007fff}, {NCVFlag, 0xabababab, 0x7ffffffe}, {CFlag, 0xabababab, 0x00000020}, {NFlag, 0xabababab, 0x00007ffd}, {NZFlag, 0xabababab, 0x7fffffff}, {NZCFlag, 0xabababab, 0xffff8002}, {ZVFlag, 0xabababab, 0x0000007f}, {NZVFlag, 0xabababab, 0xffffff83}, {NZVFlag, 0xabababab, 0xffffffff}, {ZFlag, 0xabababab, 0x80000000}, {ZVFlag, 0xabababab, 0xffffff82}, {ZVFlag, 0xabababab, 0x80000000}, {NZFlag, 0xabababab, 0xaaaaaaaa}, {CFlag, 0xabababab, 0xfffffffe}, {NZCVFlag, 0xabababab, 0x00000000}, {VFlag, 0xabababab, 0x80000001}, {ZCVFlag, 0xabababab, 0xfffffffd}, {NFlag, 0xabababab, 0xffffffff}, {VFlag, 0xabababab, 0xcccccccc}, {NFlag, 0xabababab, 0xffff8003}, {NZVFlag, 0xabababab, 0xfffffffe}, {CVFlag, 0xabababab, 0xffff8001}, {NZVFlag, 0xabababab, 0x00007fff}, {VFlag, 0xabababab, 0x33333333}, {ZCVFlag, 0xabababab, 0x00007ffd}, {NCFlag, 0xabababab, 0xfffffffe}, {ZVFlag, 0xabababab, 0xffffff83}, {NFlag, 0xabababab, 0x00007fff}, {NVFlag, 0xabababab, 0x80000000}, {NCVFlag, 0xabababab, 0xffffff80}, {ZFlag, 0xabababab, 0x7fffffff}, {NFlag, 0xabababab, 0x00000020}, {NFlag, 0xabababab, 0x7ffffffd}, {NFlag, 0xabababab, 0x0000007f}, {NZCVFlag, 0xabababab, 0x00000020}, {NCVFlag, 0xabababab, 0xfffffffe}, {ZVFlag, 0xabababab, 0xcccccccc}, {NCFlag, 0xabababab, 0xffffffe0}, {CVFlag, 0xabababab, 0xffffff82}, {NCFlag, 0xabababab, 0x00000000}, {VFlag, 0xabababab, 0xffff8000}, {VFlag, 0xabababab, 0xffff8003}, {NCFlag, 0xabababab, 0xffffffff}, {NZCFlag, 0xabababab, 0x55555555}, {ZVFlag, 0xabababab, 0xfffffffe}, {NZFlag, 0xabababab, 0x7ffffffe}, {ZCVFlag, 0xabababab, 0x7ffffffe}, {ZVFlag, 0xabababab, 0xffffffe0}, {NZCFlag, 0xabababab, 0x0000007e}, {CFlag, 0xabababab, 0x7fffffff}, {NZVFlag, 0xabababab, 0x55555555}, {NZCVFlag, 0xabababab, 0xcccccccc}, {ZCVFlag, 0xabababab, 0x80000000}, {NFlag, 0xabababab, 0x55555555}, {ZCVFlag, 0xabababab, 0xffffffe0}, {NCFlag, 0xabababab, 0xffff8000}, {NCFlag, 0xabababab, 0xffff8001}, {NVFlag, 0xabababab, 0x7ffffffe}, {ZVFlag, 0xabababab, 0x00007ffe}, {NVFlag, 0xabababab, 0x00000020}, {NFlag, 0xabababab, 0x7fffffff}, {NZFlag, 0xabababab, 0x33333333}, {ZCFlag, 0xabababab, 0xffff8001}, {ZFlag, 0xabababab, 0xffffffe0}, {VFlag, 0xabababab, 0xffffffe0}, {VFlag, 0xabababab, 0xffffff80}, {NCVFlag, 0xabababab, 0x80000000}, {ZCFlag, 0xabababab, 0x55555555}, {CFlag, 0xabababab, 0xffff8001}, {CFlag, 0xabababab, 0xffff8002}, {ZVFlag, 0xabababab, 0xffff8000}, {CFlag, 0xabababab, 0x80000001}, {NZCVFlag, 0xabababab, 0x0000007d}, {NZCVFlag, 0xabababab, 0xfffffffd}, {CVFlag, 0xabababab, 0xffffff81}, {NVFlag, 0xabababab, 0xffff8002}, {ZCFlag, 0xabababab, 0x7ffffffe}, {ZCVFlag, 0xabababab, 0xffffff82}, {ZCVFlag, 0xabababab, 0x33333333}, {NCFlag, 0xabababab, 0x33333333}, {NZCVFlag, 0xabababab, 0x00000002}, {NFlag, 0xabababab, 0x00000001}, {NVFlag, 0xabababab, 0xffff8003}, {NZCVFlag, 0xabababab, 0x00000001}, {CFlag, 0xabababab, 0xffff8003}, {NVFlag, 0xabababab, 0x0000007e}, {CVFlag, 0xabababab, 0x80000000}, {ZFlag, 0xabababab, 0xffffffff}, {NFlag, 0xabababab, 0xfffffffd}, {NVFlag, 0xabababab, 0x00007fff}, {NZCVFlag, 0xabababab, 0x7ffffffd}, {NZVFlag, 0xabababab, 0x00000000}, {NZCFlag, 0xabababab, 0xfffffffe}, {ZVFlag, 0xabababab, 0x7ffffffe}, {CFlag, 0xabababab, 0xffffffff}, {ZCFlag, 0xabababab, 0xffffff82}, {ZCFlag, 0xabababab, 0xffffff83}, {ZCFlag, 0xabababab, 0x00000002}, {NZFlag, 0xabababab, 0x0000007e}, {NZCVFlag, 0xabababab, 0xffffffe0}, {NZFlag, 0xabababab, 0x00000001}, {ZVFlag, 0xabababab, 0x55555555}, {ZCVFlag, 0xabababab, 0x00007fff}, {NFlag, 0xabababab, 0x33333333}, {ZFlag, 0xabababab, 0x00000000}, {NVFlag, 0xabababab, 0x7fffffff}, {ZVFlag, 0xabababab, 0xfffffffd}, {ZFlag, 0xabababab, 0x00000020}, {NCVFlag, 0xabababab, 0xfffffffd}, {NZCFlag, 0xabababab, 0x80000000}, {NVFlag, 0xabababab, 0x80000001}, {ZFlag, 0xabababab, 0xffff8002}, {NZCVFlag, 0xabababab, 0xffff8001}, {NFlag, 0xabababab, 0xfffffffe}, {ZVFlag, 0xabababab, 0x0000007d}, {NCFlag, 0xabababab, 0x00007ffd}, {NFlag, 0xabababab, 0xffff8001}, {NZCFlag, 0xabababab, 0xaaaaaaaa}, {NZCFlag, 0xabababab, 0x00000020}, {ZCVFlag, 0xabababab, 0x7fffffff}, {ZCVFlag, 0xabababab, 0x00000001}, {NVFlag, 0xabababab, 0xcccccccc}, {NFlag, 0xabababab, 0x80000000}, {NFlag, 0xabababab, 0xffffffe0}, {ZCFlag, 0xabababab, 0xffffffff}, {CVFlag, 0xabababab, 0x00000000}, {ZCFlag, 0xabababab, 0xffff8000}, {ZCFlag, 0xabababab, 0x00007ffd}, {NCFlag, 0xabababab, 0x0000007f}, {ZVFlag, 0xabababab, 0x00000020}, {VFlag, 0xabababab, 0xffff8002}, {ZFlag, 0xabababab, 0xffffff81}, {CVFlag, 0xabababab, 0xffff8003}, {NFlag, 0xabababab, 0xffffff80}, {NVFlag, 0xabababab, 0xaaaaaaaa}, {CFlag, 0xabababab, 0x00000001}, {ZCVFlag, 0xabababab, 0xffff8003}, {NCFlag, 0xabababab, 0xfffffffd}, {CVFlag, 0xabababab, 0xffffff83}, {ZCFlag, 0xabababab, 0xfffffffd}, {CVFlag, 0xabababab, 0x0000007d}, {ZCVFlag, 0xabababab, 0xffffff83}, {NCFlag, 0xabababab, 0xffffff81}, {NFlag, 0xabababab, 0xffff8000}, {NZFlag, 0xabababab, 0x80000001}, {NCFlag, 0xabababab, 0x55555555}, {NCVFlag, 0xabababab, 0xaaaaaaaa}, {NZCFlag, 0xabababab, 0xffffffff}, {ZFlag, 0xabababab, 0x33333333}, {NCFlag, 0xabababab, 0xffffff82}, {NZFlag, 0xabababab, 0xffff8001}, {VFlag, 0xabababab, 0x7ffffffe}, {NZCVFlag, 0xabababab, 0x7ffffffe}, {ZFlag, 0xabababab, 0x80000001}, {NVFlag, 0xabababab, 0xffffff80}, {NFlag, 0xabababab, 0x0000007e}, {NCVFlag, 0xabababab, 0x00007ffd}, {CFlag, 0xabababab, 0x0000007e}, {NZVFlag, 0xabababab, 0xcccccccc}, {NZVFlag, 0xabababab, 0x0000007f}, {ZFlag, 0xabababab, 0xffffff83}, {VFlag, 0xabababab, 0xaaaaaaaa}, {ZVFlag, 0xabababab, 0x7ffffffd}, {ZVFlag, 0xabababab, 0xffffffff}, {NZCVFlag, 0xabababab, 0x0000007f}, {NCVFlag, 0xabababab, 0x0000007e}, {NZVFlag, 0xabababab, 0xffffff82}, {CFlag, 0xabababab, 0xffffff80}, {NZCVFlag, 0xabababab, 0x80000000}, {NZVFlag, 0xabababab, 0x7ffffffe}, {NZFlag, 0xabababab, 0xffffff80}, {NZFlag, 0xabababab, 0xffff8000}, {NCFlag, 0xabababab, 0xaaaaaaaa}, {NFlag, 0xabababab, 0x00000000}, {NZFlag, 0xabababab, 0xcccccccc}, {ZCFlag, 0xabababab, 0xffffffe0}, {CVFlag, 0xabababab, 0xcccccccc}, {VFlag, 0xabababab, 0xfffffffd}, {CVFlag, 0xabababab, 0x7ffffffd}, {ZCFlag, 0xabababab, 0x00000020}, {CVFlag, 0xabababab, 0x00007ffe}, {ZCFlag, 0xabababab, 0xffffff80}, {NVFlag, 0xabababab, 0xfffffffd}, {NZCFlag, 0xabababab, 0x00000001}, {CVFlag, 0xabababab, 0x00000001}, {NVFlag, 0xabababab, 0xffffff83}, {ZCVFlag, 0xabababab, 0x7ffffffd}, {NZVFlag, 0xabababab, 0xffff8000}, {CVFlag, 0xabababab, 0xffffffe0}, {NCFlag, 0xabababab, 0x0000007d}, {VFlag, 0xabababab, 0x00007ffd}, {NZCFlag, 0xabababab, 0xffffff81}, {NCVFlag, 0xabababab, 0x00007fff}, {NVFlag, 0xabababab, 0x0000007f}, {CFlag, 0xabababab, 0xcccccccc}, {ZFlag, 0xabababab, 0xcccccccc}, {ZCFlag, 0xabababab, 0x80000000}, {VFlag, 0xabababab, 0x0000007d}, {NFlag, 0xabababab, 0xcccccccc}, {NCFlag, 0xabababab, 0x7fffffff}, {VFlag, 0xabababab, 0xffffff81}, {NCVFlag, 0xabababab, 0xffffffff}, {NZFlag, 0xabababab, 0xffff8002}, {NZVFlag, 0xabababab, 0x80000000}, {ZCVFlag, 0xabababab, 0x0000007f}, {ZFlag, 0xabababab, 0x0000007f}, {VFlag, 0xabababab, 0xffff8001}, {NVFlag, 0xabababab, 0x00000000}, {ZFlag, 0xabababab, 0x00007ffd}, {NCVFlag, 0xabababab, 0x80000001}, {NCVFlag, 0xabababab, 0xffff8002}, {NCFlag, 0xabababab, 0x7ffffffe}, {ZCFlag, 0xabababab, 0x7ffffffd}, {NZCFlag, 0xabababab, 0x80000001}, {ZCFlag, 0xabababab, 0x0000007f}, {VFlag, 0xabababab, 0x80000000}, {NCFlag, 0xabababab, 0x80000001}, {NVFlag, 0xabababab, 0xffffff81}}; // A loop will be generated for each element of this array. const TestLoopData kTests[] = {{{ne, r2, r2, 45}, "ne r2 r2 45", "RdIsRn_ne_r2_r2_45", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{cs, r6, r6, 59}, "cs r6 r6 59", "RdIsRn_cs_r6_r6_59", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{mi, r6, r6, 211}, "mi r6 r6 211", "RdIsRn_mi_r6_r6_211", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{lt, r5, r5, 36}, "lt r5 r5 36", "RdIsRn_lt_r5_r5_36", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{cc, r7, r7, 7}, "cc r7 r7 7", "RdIsRn_cc_r7_r7_7", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{cs, r7, r7, 215}, "cs r7 r7 215", "RdIsRn_cs_r7_r7_215", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{pl, r6, r6, 54}, "pl r6 r6 54", "RdIsRn_pl_r6_r6_54", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{lt, r6, r6, 221}, "lt r6 r6 221", "RdIsRn_lt_r6_r6_221", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{ne, r2, r2, 40}, "ne r2 r2 40", "RdIsRn_ne_r2_r2_40", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{hi, r5, r5, 158}, "hi r5 r5 158", "RdIsRn_hi_r5_r5_158", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{cs, r0, r0, 18}, "cs r0 r0 18", "RdIsRn_cs_r0_r0_18", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{ne, r3, r3, 205}, "ne r3 r3 205", "RdIsRn_ne_r3_r3_205", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{vc, r0, r0, 97}, "vc r0 r0 97", "RdIsRn_vc_r0_r0_97", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{hi, r2, r2, 197}, "hi r2 r2 197", "RdIsRn_hi_r2_r2_197", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{cs, r0, r0, 248}, "cs r0 r0 248", "RdIsRn_cs_r0_r0_248", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{ne, r4, r4, 108}, "ne r4 r4 108", "RdIsRn_ne_r4_r4_108", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{vs, r3, r3, 73}, "vs r3 r3 73", "RdIsRn_vs_r3_r3_73", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{ne, r7, r7, 230}, "ne r7 r7 230", "RdIsRn_ne_r7_r7_230", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{eq, r0, r0, 100}, "eq r0 r0 100", "RdIsRn_eq_r0_r0_100", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{mi, r5, r5, 211}, "mi r5 r5 211", "RdIsRn_mi_r5_r5_211", ARRAY_SIZE(kRdIsRn), kRdIsRn}, {{ge, r2, r3, 225}, "ge r2 r3 225", "RdIsNotRn_ge_r2_r3_225", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{vs, r3, r1, 64}, "vs r3 r1 64", "RdIsNotRn_vs_r3_r1_64", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{vs, r0, r1, 93}, "vs r0 r1 93", "RdIsNotRn_vs_r0_r1_93", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{ne, r5, r1, 247}, "ne r5 r1 247", "RdIsNotRn_ne_r5_r1_247", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{vs, r1, r7, 9}, "vs r1 r7 9", "RdIsNotRn_vs_r1_r7_9", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{le, r0, r2, 201}, "le r0 r2 201", "RdIsNotRn_le_r0_r2_201", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{vs, r6, r0, 176}, "vs r6 r0 176", "RdIsNotRn_vs_r6_r0_176", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{vc, r0, r1, 248}, "vc r0 r1 248", "RdIsNotRn_vc_r0_r1_248", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{al, r7, r6, 64}, "al r7 r6 64", "RdIsNotRn_al_r7_r6_64", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{al, r5, r7, 175}, "al r5 r7 175", "RdIsNotRn_al_r5_r7_175", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{al, r0, r4, 182}, "al r0 r4 182", "RdIsNotRn_al_r0_r4_182", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{ls, r7, r5, 58}, "ls r7 r5 58", "RdIsNotRn_ls_r7_r5_58", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{vc, r0, r7, 205}, "vc r0 r7 205", "RdIsNotRn_vc_r0_r7_205", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{pl, r1, r3, 135}, "pl r1 r3 135", "RdIsNotRn_pl_r1_r3_135", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{gt, r4, r3, 253}, "gt r4 r3 253", "RdIsNotRn_gt_r4_r3_253", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{al, r1, r7, 32}, "al r1 r7 32", "RdIsNotRn_al_r1_r7_32", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{eq, r1, r7, 139}, "eq r1 r7 139", "RdIsNotRn_eq_r1_r7_139", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{lt, r0, r5, 248}, "lt r0 r5 248", "RdIsNotRn_lt_r0_r5_248", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{hi, r0, r6, 89}, "hi r0 r6 89", "RdIsNotRn_hi_r0_r6_89", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{cc, r3, r5, 210}, "cc r3 r5 210", "RdIsNotRn_cc_r3_r5_210", ARRAY_SIZE(kRdIsNotRn), kRdIsNotRn}, {{cs, r0, r0, 187}, "cs r0 r0 187", "Immediate_cs_r0_r0_187", ARRAY_SIZE(kImmediate), kImmediate}, {{hi, r0, r0, 236}, "hi r0 r0 236", "Immediate_hi_r0_r0_236", ARRAY_SIZE(kImmediate), kImmediate}, {{eq, r0, r0, 133}, "eq r0 r0 133", "Immediate_eq_r0_r0_133", ARRAY_SIZE(kImmediate), kImmediate}, {{mi, r0, r0, 193}, "mi r0 r0 193", "Immediate_mi_r0_r0_193", ARRAY_SIZE(kImmediate), kImmediate}, {{cc, r0, r0, 73}, "cc r0 r0 73", "Immediate_cc_r0_r0_73", ARRAY_SIZE(kImmediate), kImmediate}, {{cs, r0, r0, 93}, "cs r0 r0 93", "Immediate_cs_r0_r0_93", ARRAY_SIZE(kImmediate), kImmediate}, {{ne, r0, r0, 130}, "ne r0 r0 130", "Immediate_ne_r0_r0_130", ARRAY_SIZE(kImmediate), kImmediate}, {{ge, r0, r0, 209}, "ge r0 r0 209", "Immediate_ge_r0_r0_209", ARRAY_SIZE(kImmediate), kImmediate}, {{lt, r0, r0, 42}, "lt r0 r0 42", "Immediate_lt_r0_r0_42", ARRAY_SIZE(kImmediate), kImmediate}, {{cs, r0, r0, 177}, "cs r0 r0 177", "Immediate_cs_r0_r0_177", ARRAY_SIZE(kImmediate), kImmediate}, {{lt, r0, r0, 139}, "lt r0 r0 139", "Immediate_lt_r0_r0_139", ARRAY_SIZE(kImmediate), kImmediate}, {{mi, r0, r0, 43}, "mi r0 r0 43", "Immediate_mi_r0_r0_43", ARRAY_SIZE(kImmediate), kImmediate}, {{cs, r0, r0, 247}, "cs r0 r0 247", "Immediate_cs_r0_r0_247", ARRAY_SIZE(kImmediate), kImmediate}, {{ls, r0, r0, 170}, "ls r0 r0 170", "Immediate_ls_r0_r0_170", ARRAY_SIZE(kImmediate), kImmediate}, {{cs, r0, r0, 185}, "cs r0 r0 185", "Immediate_cs_r0_r0_185", ARRAY_SIZE(kImmediate), kImmediate}, {{ne, r0, r0, 246}, "ne r0 r0 246", "Immediate_ne_r0_r0_246", ARRAY_SIZE(kImmediate), kImmediate}, {{mi, r0, r0, 179}, "mi r0 r0 179", "Immediate_mi_r0_r0_179", ARRAY_SIZE(kImmediate), kImmediate}, {{pl, r0, r0, 7}, "pl r0 r0 7", "Immediate_pl_r0_r0_7", ARRAY_SIZE(kImmediate), kImmediate}, {{mi, r0, r0, 177}, "mi r0 r0 177", "Immediate_mi_r0_r0_177", ARRAY_SIZE(kImmediate), kImmediate}, {{gt, r0, r0, 175}, "gt r0 r0 175", "Immediate_gt_r0_r0_175", ARRAY_SIZE(kImmediate), kImmediate}}; // We record all inputs to the instructions as outputs. This way, we also check // that what shouldn't change didn't change. struct TestResult { size_t output_size; const Inputs* outputs; }; // These headers each contain an array of `TestResult` with the reference output // values. The reference arrays are names `kReference{mnemonic}`. #include "aarch32/traces/simulator-cond-rdlow-rnlow-operand-immediate-t32-add.h" #include "aarch32/traces/simulator-cond-rdlow-rnlow-operand-immediate-t32-adds.h" #include "aarch32/traces/simulator-cond-rdlow-rnlow-operand-immediate-t32-rsb.h" #include "aarch32/traces/simulator-cond-rdlow-rnlow-operand-immediate-t32-rsbs.h" #include "aarch32/traces/simulator-cond-rdlow-rnlow-operand-immediate-t32-sub.h" #include "aarch32/traces/simulator-cond-rdlow-rnlow-operand-immediate-t32-subs.h" // The maximum number of errors to report in detail for each test. const unsigned kErrorReportLimit = 8; typedef void (MacroAssembler::*Fn)(Condition cond, Register rd, Register rn, const Operand& op); void TestHelper(Fn instruction, const char* mnemonic, const TestResult reference[]) { SETUP(); masm.UseT32(); START(); // Data to compare to `reference`. TestResult* results[ARRAY_SIZE(kTests)]; // Test cases for memory bound instructions may allocate a buffer and save its // address in this array. byte* scratch_memory_buffers[ARRAY_SIZE(kTests)]; // Generate a loop for each element in `kTests`. Each loop tests one specific // instruction. for (unsigned i = 0; i < ARRAY_SIZE(kTests); i++) { // Allocate results on the heap for this test. results[i] = new TestResult; results[i]->outputs = new Inputs[kTests[i].input_size]; results[i]->output_size = kTests[i].input_size; size_t input_stride = sizeof(kTests[i].inputs[0]) * kTests[i].input_size; VIXL_ASSERT(IsUint32(input_stride)); scratch_memory_buffers[i] = NULL; Label loop; UseScratchRegisterScope scratch_registers(&masm); // Include all registers from r0 ro r12. scratch_registers.Include(RegisterList(0x1fff)); // Values to pass to the macro-assembler. Condition cond = kTests[i].operands.cond; Register rd = kTests[i].operands.rd; Register rn = kTests[i].operands.rn; int32_t immediate = kTests[i].operands.immediate; Operand op(immediate); scratch_registers.Exclude(rd); scratch_registers.Exclude(rn); // Allocate reserved registers for our own use. Register input_ptr = scratch_registers.Acquire(); Register input_end = scratch_registers.Acquire(); Register result_ptr = scratch_registers.Acquire(); // Initialize `input_ptr` to the first element and `input_end` the address // after the array. __ Mov(input_ptr, Operand::From(kTests[i].inputs)); __ Add(input_end, input_ptr, static_cast<uint32_t>(input_stride)); __ Mov(result_ptr, Operand::From(results[i]->outputs)); __ Bind(&loop); { UseScratchRegisterScope temp_registers(&masm); Register nzcv_bits = temp_registers.Acquire(); Register saved_q_bit = temp_registers.Acquire(); // Save the `Q` bit flag. __ Mrs(saved_q_bit, APSR); __ And(saved_q_bit, saved_q_bit, QFlag); // Set the `NZCV` and `Q` flags together. __ Ldr(nzcv_bits, MemOperand(input_ptr, offsetof(Inputs, apsr))); __ Orr(nzcv_bits, nzcv_bits, saved_q_bit); __ Msr(APSR_nzcvq, nzcv_bits); } __ Ldr(rd, MemOperand(input_ptr, offsetof(Inputs, rd))); __ Ldr(rn, MemOperand(input_ptr, offsetof(Inputs, rn))); (masm.*instruction)(cond, rd, rn, op); { UseScratchRegisterScope temp_registers(&masm); Register nzcv_bits = temp_registers.Acquire(); __ Mrs(nzcv_bits, APSR); // Only record the NZCV bits. __ And(nzcv_bits, nzcv_bits, NZCVFlag); __ Str(nzcv_bits, MemOperand(result_ptr, offsetof(Inputs, apsr))); } __ Str(rd, MemOperand(result_ptr, offsetof(Inputs, rd))); __ Str(rn, MemOperand(result_ptr, offsetof(Inputs, rn))); // Advance the result pointer. __ Add(result_ptr, result_ptr, Operand::From(sizeof(kTests[i].inputs[0]))); // Loop back until `input_ptr` is lower than `input_base`. __ Add(input_ptr, input_ptr, Operand::From(sizeof(kTests[i].inputs[0]))); __ Cmp(input_ptr, input_end); __ B(ne, &loop); } END(); RUN(); if (Test::generate_test_trace()) { // Print the results. for (size_t i = 0; i < ARRAY_SIZE(kTests); i++) { printf("const Inputs kOutputs_%s_%s[] = {\n", mnemonic, kTests[i].identifier); for (size_t j = 0; j < results[i]->output_size; j++) { printf(" { "); printf("0x%08" PRIx32, results[i]->outputs[j].apsr); printf(", "); printf("0x%08" PRIx32, results[i]->outputs[j].rd); printf(", "); printf("0x%08" PRIx32, results[i]->outputs[j].rn); printf(" },\n"); } printf("};\n"); } printf("const TestResult kReference%s[] = {\n", mnemonic); for (size_t i = 0; i < ARRAY_SIZE(kTests); i++) { printf(" {\n"); printf(" ARRAY_SIZE(kOutputs_%s_%s),\n", mnemonic, kTests[i].identifier); printf(" kOutputs_%s_%s,\n", mnemonic, kTests[i].identifier); printf(" },\n"); } printf("};\n"); } else if (kCheckSimulatorTestResults) { // Check the results. unsigned total_error_count = 0; for (size_t i = 0; i < ARRAY_SIZE(kTests); i++) { bool instruction_has_errors = false; for (size_t j = 0; j < kTests[i].input_size; j++) { uint32_t apsr = results[i]->outputs[j].apsr; uint32_t rd = results[i]->outputs[j].rd; uint32_t rn = results[i]->outputs[j].rn; uint32_t apsr_input = kTests[i].inputs[j].apsr; uint32_t rd_input = kTests[i].inputs[j].rd; uint32_t rn_input = kTests[i].inputs[j].rn; uint32_t apsr_ref = reference[i].outputs[j].apsr; uint32_t rd_ref = reference[i].outputs[j].rd; uint32_t rn_ref = reference[i].outputs[j].rn; if (((apsr != apsr_ref) || (rd != rd_ref) || (rn != rn_ref)) && (++total_error_count <= kErrorReportLimit)) { // Print the instruction once even if it triggered multiple failures. if (!instruction_has_errors) { printf("Error(s) when testing \"%s %s\":\n", mnemonic, kTests[i].operands_description); instruction_has_errors = true; } // Print subsequent errors. printf(" Input: "); printf("0x%08" PRIx32, apsr_input); printf(", "); printf("0x%08" PRIx32, rd_input); printf(", "); printf("0x%08" PRIx32, rn_input); printf("\n"); printf(" Expected: "); printf("0x%08" PRIx32, apsr_ref); printf(", "); printf("0x%08" PRIx32, rd_ref); printf(", "); printf("0x%08" PRIx32, rn_ref); printf("\n"); printf(" Found: "); printf("0x%08" PRIx32, apsr); printf(", "); printf("0x%08" PRIx32, rd); printf(", "); printf("0x%08" PRIx32, rn); printf("\n\n"); } } } if (total_error_count > kErrorReportLimit) { printf("%u other errors follow.\n", total_error_count - kErrorReportLimit); } VIXL_CHECK(total_error_count == 0); } else { VIXL_WARNING("Assembled the code, but did not run anything.\n"); } for (size_t i = 0; i < ARRAY_SIZE(kTests); i++) { delete[] results[i]->outputs; delete results[i]; delete[] scratch_memory_buffers[i]; } TEARDOWN(); } // Instantiate tests for each instruction in the list. // TODO: Remove this limitation by having a sandboxing mechanism. #if defined(VIXL_HOST_POINTER_32) #define TEST(mnemonic) \ void Test_##mnemonic() { \ TestHelper(&MacroAssembler::mnemonic, #mnemonic, kReference##mnemonic); \ } \ Test test_##mnemonic( \ "AARCH32_SIMULATOR_COND_RDLOW_RNLOW_OPERAND_IMMEDIATE_T32_" #mnemonic, \ &Test_##mnemonic); #else #define TEST(mnemonic) \ void Test_##mnemonic() { \ VIXL_WARNING("This test can only run on a 32-bit host.\n"); \ USE(TestHelper); \ } \ Test test_##mnemonic( \ "AARCH32_SIMULATOR_COND_RDLOW_RNLOW_OPERAND_IMMEDIATE_T32_" #mnemonic, \ &Test_##mnemonic); #endif FOREACH_INSTRUCTION(TEST) #undef TEST } // namespace #endif } // namespace aarch32 } // namespace vixl
57.180805
81
0.394696
Componolit
f588a2ea22778a6a8a78380301933ddbd2ddf6d4
1,079
hpp
C++
addons/common/script_component.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
addons/common/script_component.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
addons/common/script_component.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
#define COMPONENT common #include "\z\tfd\addons\main\script_mod.hpp" #include "\a3\ui_f\hpp\defineCommonGrids.inc" #include "\a3\ui_f\hpp\defineResincl.inc" #include "\a3\ui_f\hpp\defineResinclDesign.inc" // #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE #ifdef DEBUG_ENABLED_COMMON #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_COMMON #define DEBUG_SETTINGS DEBUG_SETTINGS_COMMON #endif #include "\z\tfd\addons\main\script_macros.hpp" #define POS_X(N) ((N) * GUI_GRID_W + GUI_GRID_CENTER_X) #define POS_Y(N) ((N) * GUI_GRID_H + GUI_GRID_CENTER_Y) #define POS_W(N) ((N) * GUI_GRID_W) #define POS_H(N) ((N) * GUI_GRID_H) #define COLOR_BCG { \ "(profilenamespace getVariable ['GUI_BCG_RGB_R',0.13])", \ "(profilenamespace getVariable ['GUI_BCG_RGB_G',0.54])", \ "(profilenamespace getVariable ['GUI_BCG_RGB_B',0.21])", \ "(profilenamespace getVariable ['GUI_BCG_RGB_A',0.8])" \ } #define IDC_MODAL_TITLE_L 1000 #define IDC_MODAL_TITLE_R 1001 #define IDC_MODAL_GROUP_CONTENT 2000 #define IDC_MODAL_CONTENT_TEXT 2001
29.972222
62
0.741427
Task-Force-Dagger
f58b4926d6c493a53ef80f4ba139bc6102c1b583
9,595
cpp
C++
opencl/test/unit_test/api/cl_create_program_with_built_in_kernels_tests.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
1
2020-04-17T05:46:04.000Z
2020-04-17T05:46:04.000Z
opencl/test/unit_test/api/cl_create_program_with_built_in_kernels_tests.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
null
null
null
opencl/test/unit_test/api/cl_create_program_with_built_in_kernels_tests.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/built_ins/built_ins.h" #include "shared/source/compiler_interface/compiler_interface.h" #include "shared/source/device/device.h" #include "opencl/source/built_ins/built_in_ops_vme.h" #include "opencl/source/built_ins/vme_builtin.h" #include "opencl/source/cl_device/cl_device.h" #include "opencl/source/context/context.h" #include "opencl/source/helpers/base_object.h" #include "opencl/source/kernel/kernel.h" #include "opencl/source/program/program.h" #include "opencl/test/unit_test/fixtures/run_kernel_fixture.h" #include "cl_api_tests.h" using namespace NEO; typedef api_tests clCreateProgramWithBuiltInKernelsTests; struct clCreateProgramWithBuiltInVmeKernelsTests : clCreateProgramWithBuiltInKernelsTests { void SetUp() override { clCreateProgramWithBuiltInKernelsTests::SetUp(); if (!castToObject<ClDevice>(devices[testedRootDeviceIndex])->getHardwareInfo().capabilityTable.supportsVme) { GTEST_SKIP(); } pDev = &pContext->getDevice(0)->getDevice(); } Device *pDev; }; namespace ULT { TEST_F(clCreateProgramWithBuiltInKernelsTests, GivenInvalidContextWhenCreatingProgramWithBuiltInKernelsThenInvalidContextErrorIsReturned) { cl_int retVal = CL_SUCCESS; auto program = clCreateProgramWithBuiltInKernels( nullptr, // context 1, // num_devices nullptr, // device_list nullptr, // kernel_names &retVal); EXPECT_EQ(nullptr, program); EXPECT_EQ(CL_INVALID_CONTEXT, retVal); } TEST_F(clCreateProgramWithBuiltInKernelsTests, GivenNoKernelsWhenCreatingProgramWithBuiltInKernelsThenInvalidValueErrorIsReturned) { cl_int retVal = CL_SUCCESS; auto program = clCreateProgramWithBuiltInKernels( pContext, // context 1, // num_devices &testedClDevice, // device_list "", // kernel_names &retVal); EXPECT_EQ(nullptr, program); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_F(clCreateProgramWithBuiltInKernelsTests, GivenNoDeviceWhenCreatingProgramWithBuiltInKernelsThenInvalidValueErrorIsReturned) { cl_int retVal = CL_SUCCESS; auto program = clCreateProgramWithBuiltInKernels( pContext, // context 0, // num_devices &testedClDevice, // device_list "", // kernel_names &retVal); EXPECT_EQ(nullptr, program); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_F(clCreateProgramWithBuiltInKernelsTests, GivenNoKernelsAndNoReturnWhenCreatingProgramWithBuiltInKernelsThenProgramIsNotCreated) { auto program = clCreateProgramWithBuiltInKernels( pContext, // context 1, // num_devices &testedClDevice, // device_list "", // kernel_names nullptr); EXPECT_EQ(nullptr, program); } TEST_F(clCreateProgramWithBuiltInVmeKernelsTests, GivenValidMediaKernelsWhenCreatingProgramWithBuiltInKernelsThenProgramIsSuccessfullyCreated) { cl_int retVal = CL_SUCCESS; overwriteBuiltInBinaryName(pDev, "media_kernels_frontend"); const char *kernelNamesString = { "block_advanced_motion_estimate_bidirectional_check_intel;" "block_motion_estimate_intel;" "block_advanced_motion_estimate_check_intel;"}; const char *kernelNames[] = { "block_motion_estimate_intel", "block_advanced_motion_estimate_check_intel", "block_advanced_motion_estimate_bidirectional_check_intel", }; cl_program program = clCreateProgramWithBuiltInKernels( pContext, // context 1, // num_devices &testedClDevice, // device_list kernelNamesString, // kernel_names &retVal); restoreBuiltInBinaryName(pDev); EXPECT_NE(nullptr, program); EXPECT_EQ(CL_SUCCESS, retVal); for (auto &kernelName : kernelNames) { cl_kernel kernel = clCreateKernel( program, kernelName, &retVal); ASSERT_EQ(CL_SUCCESS, retVal); ASSERT_NE(nullptr, kernel); retVal = clReleaseKernel(kernel); EXPECT_EQ(CL_SUCCESS, retVal); } retVal = clReleaseProgram(program); EXPECT_EQ(CL_SUCCESS, retVal); } TEST_F(clCreateProgramWithBuiltInVmeKernelsTests, GivenValidMediaKernelsWithOptionsWhenCreatingProgramWithBuiltInKernelsThenProgramIsSuccessfullyCreatedWithThoseOptions) { cl_int retVal = CL_SUCCESS; overwriteBuiltInBinaryName(pDev, "media_kernels_frontend"); const char *kernelNamesString = { "block_motion_estimate_intel;"}; cl_program program = clCreateProgramWithBuiltInKernels( pContext, // context 1, // num_devices &testedClDevice, // device_list kernelNamesString, // kernel_names &retVal); restoreBuiltInBinaryName(pDev); auto neoProgram = castToObject<Program>(program); auto builtinOptions = neoProgram->getOptions(); auto it = builtinOptions.find("HW_NULL_CHECK"); EXPECT_EQ(std::string::npos, it); clReleaseProgram(program); } TEST_F(clCreateProgramWithBuiltInVmeKernelsTests, GivenVmeBlockMotionEstimateKernelWhenCreatingProgramWithBuiltInKernelsThenCorrectDispatchBuilderAndFrontendKernelIsCreated) { cl_int retVal = CL_SUCCESS; overwriteBuiltInBinaryName(pDev, "media_kernels_backend"); Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockMotionEstimateIntel, *pDev); restoreBuiltInBinaryName(pDev); overwriteBuiltInBinaryName(pDev, "media_kernels_frontend"); const char *kernelNamesString = { "block_motion_estimate_intel;"}; cl_program program = clCreateProgramWithBuiltInKernels( pContext, // context 1, // num_devices &testedClDevice, // device_list kernelNamesString, // kernel_names &retVal); restoreBuiltInBinaryName(pDev); cl_kernel kernel = clCreateKernel( program, "block_motion_estimate_intel", &retVal); auto kernNeo = castToObject<Kernel>(kernel); EXPECT_NE(nullptr, kernNeo->getKernelInfo().builtinDispatchBuilder); EXPECT_EQ(6U, kernNeo->getKernelArgsNumber()); auto &vmeBuilder = Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockMotionEstimateIntel, *pDev); EXPECT_EQ(&vmeBuilder, kernNeo->getKernelInfo().builtinDispatchBuilder); clReleaseKernel(kernel); clReleaseProgram(program); } TEST_F(clCreateProgramWithBuiltInVmeKernelsTests, GivenVmeBlockAdvancedMotionEstimateKernelWhenCreatingProgramWithBuiltInKernelsThenCorrectDispatchBuilderAndFrontendKernelIsCreated) { cl_int retVal = CL_SUCCESS; overwriteBuiltInBinaryName(pDev, "media_kernels_backend"); Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockAdvancedMotionEstimateCheckIntel, *pDev); restoreBuiltInBinaryName(pDev); overwriteBuiltInBinaryName(pDev, "media_kernels_frontend"); const char *kernelNamesString = { "block_advanced_motion_estimate_check_intel;"}; cl_program program = clCreateProgramWithBuiltInKernels( pContext, // context 1, // num_devices &testedClDevice, // device_list kernelNamesString, // kernel_names &retVal); restoreBuiltInBinaryName(pDev); cl_kernel kernel = clCreateKernel( program, "block_advanced_motion_estimate_check_intel", &retVal); auto kernNeo = castToObject<Kernel>(kernel); EXPECT_NE(nullptr, kernNeo->getKernelInfo().builtinDispatchBuilder); EXPECT_EQ(15U, kernNeo->getKernelArgsNumber()); auto &vmeBuilder = Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockAdvancedMotionEstimateCheckIntel, *pDev); EXPECT_EQ(&vmeBuilder, kernNeo->getKernelInfo().builtinDispatchBuilder); clReleaseKernel(kernel); clReleaseProgram(program); } TEST_F(clCreateProgramWithBuiltInVmeKernelsTests, GivenVmeBlockAdvancedMotionEstimateBidirectionalCheckKernelWhenCreatingProgramWithBuiltInKernelsThenCorrectDispatchBuilderAndFrontendKernelIsCreated) { cl_int retVal = CL_SUCCESS; overwriteBuiltInBinaryName(pDev, "media_kernels_backend"); Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockAdvancedMotionEstimateBidirectionalCheckIntel, *pDev); restoreBuiltInBinaryName(pDev); overwriteBuiltInBinaryName(pDev, "media_kernels_frontend"); const char *kernelNamesString = { "block_advanced_motion_estimate_bidirectional_check_intel;"}; cl_program program = clCreateProgramWithBuiltInKernels( pContext, // context 1, // num_devices &testedClDevice, // device_list kernelNamesString, // kernel_names &retVal); restoreBuiltInBinaryName(pDev); cl_kernel kernel = clCreateKernel( program, "block_advanced_motion_estimate_bidirectional_check_intel", &retVal); auto kernNeo = castToObject<Kernel>(kernel); EXPECT_NE(nullptr, kernNeo->getKernelInfo().builtinDispatchBuilder); EXPECT_EQ(20U, kernNeo->getKernelArgsNumber()); auto ctxNeo = castToObject<Context>(pContext); auto &vmeBuilder = Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockAdvancedMotionEstimateBidirectionalCheckIntel, ctxNeo->getDevice(0)->getDevice()); EXPECT_EQ(&vmeBuilder, kernNeo->getKernelInfo().builtinDispatchBuilder); clReleaseKernel(kernel); clReleaseProgram(program); } } // namespace ULT
36.207547
201
0.726733
dkjiang2018
f58d7a49622539388f0cd229f37cb285f99c8b16
7,014
cpp
C++
kcfi/llvm-kcfi/tools/clang/test/SemaTemplate/instantiate-local-class.cpp
IntelSTORM/Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
1
2022-01-11T11:12:00.000Z
2022-01-11T11:12:00.000Z
kcfi/llvm-kcfi/tools/clang/test/SemaTemplate/instantiate-local-class.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
kcfi/llvm-kcfi/tools/clang/test/SemaTemplate/instantiate-local-class.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
// RUN: %clang_cc1 -verify -std=c++11 %s // RUN: %clang_cc1 -verify -std=c++11 -fdelayed-template-parsing %s template<typename T> void f0() { struct X; typedef struct Y { T (X::* f1())(int) { return 0; } } Y2; Y2 y = Y(); } template void f0<int>(); // PR5764 namespace PR5764 { struct X { template <typename T> void Bar() { typedef T ValueType; struct Y { Y() { V = ValueType(); } ValueType V; }; Y y; } }; void test(X x) { x.Bar<int>(); } } // Instantiation of local classes with virtual functions. namespace local_class_with_virtual_functions { template <typename T> struct X { }; template <typename T> struct Y { }; template <typename T> void f() { struct Z : public X<Y<T>*> { virtual void g(Y<T>* y) { } void g2(int x) {(void)x;} }; Z z; (void)z; } struct S { }; void test() { f<S>(); } } namespace PR8801 { template<typename T> void foo() { class X; typedef int (X::*pmf_type)(); class X : public T { }; pmf_type pmf = &T::foo; } struct Y { int foo(); }; template void foo<Y>(); } namespace TemplatePacksAndLambdas { template <typename ...T> int g(T...); struct S { template <typename ...T> static void f(int f = g([]{ static T t; return ++t; }()...)) {} }; void h() { S::f<int, int, int>(); } } namespace PR9685 { template <class Thing> void forEach(Thing t) { t.func(); } template <typename T> void doIt() { struct Functor { void func() { (void)i; } int i; }; forEach(Functor()); } void call() { doIt<int>(); } } namespace PR12702 { struct S { template <typename F> bool apply(F f) { return f(); } }; template <typename> struct T { void foo() { struct F { int x; bool operator()() { return x == 0; } }; S().apply(F()); } }; void call() { T<int>().foo(); } } namespace PR17139 { template <class T> void foo(const T &t) { t.foo(); } template <class F> void bar(F *f) { struct B { F *fn; void foo() const { fn(); } } b = { f }; foo(b); } void go() {} void test() { bar(go); } } namespace PR17740 { class C { public: template <typename T> static void foo(T function); template <typename T> static void bar(T function); template <typename T> static void func(T function); }; template <typename T> void C::foo(T function) { function(); } template <typename T> void C::bar(T function) { foo([&function]() { function(); }); } template <typename T> void C::func(T function) { struct Struct { T mFunction; Struct(T function) : mFunction(function) {}; void operator()() { mFunction(); }; }; bar(Struct(function)); } void call() { C::func([]() {}); } } namespace PR14373 { struct function { template <typename _Functor> function(_Functor __f) { __f(); } }; template <typename Func> function exec_func(Func f) { struct functor { functor(Func f) : func(f) {} void operator()() const { func(); } Func func; }; return functor(f); } struct Type { void operator()() const {} }; int call() { exec_func(Type()); return 0; } } namespace PR18907 { template <typename> class C : public C<int> {}; // expected-error{{within its own definition}} template <typename X> void F() { struct A : C<X> {}; } struct B { void f() { F<int>(); } }; } namespace PR23194 { struct X { int operator()() const { return 0; } }; struct Y { Y(int) {} }; template <bool = true> int make_seed_pair() noexcept { struct state_t { X x; Y y{x()}; }; return 0; } int func() { return make_seed_pair(); } } namespace PR18653 { // Forward declarations template<typename T> void f1() { void g1(struct x1); struct x1 {}; } template void f1<int>(); template<typename T> void f1a() { void g1(union x1); union x1 {}; } template void f1a<int>(); template<typename T> void f2() { void g2(enum x2); // expected-error{{ISO C++ forbids forward references to 'enum' types}} enum x2 { nothing }; } template void f2<int>(); template<typename T> void f3() { void g3(enum class x3); enum class x3 { nothing }; } template void f3<int>(); template<typename T> void f4() { void g4(struct x4 {} x); // expected-error{{'x4' cannot be defined in a parameter type}} } template void f4<int>(); template<typename T> void f4a() { void g4(union x4 {} x); // expected-error{{'x4' cannot be defined in a parameter type}} } template void f4a<int>(); template <class T> void f(); template <class T> struct S1 { void m() { f<class newclass>(); f<union newunion>(); } }; template struct S1<int>; template <class T> struct S2 { void m() { f<enum new_enum>(); // expected-error{{ISO C++ forbids forward references to 'enum' types}} } }; template struct S2<int>; template <class T> struct S3 { void m() { f<enum class new_enum>(); } }; template struct S3<int>; template <class T> struct S4 { struct local {}; void m() { f<local>(); } }; template struct S4<int>; template <class T> struct S4a { union local {}; void m() { f<local>(); } }; template struct S4a<int>; template <class T> struct S5 { enum local { nothing }; void m() { f<local>(); } }; template struct S5<int>; template <class T> struct S7 { enum class local { nothing }; void m() { f<local>(); } }; template struct S7<int>; template <class T> void fff(T *x); template <class T> struct S01 { struct local { }; void m() { local x; fff(&x); } }; template struct S01<int>; template <class T> struct S01a { union local { }; void m() { local x; fff(&x); } }; template struct S01a<int>; template <class T> struct S02 { enum local { nothing }; void m() { local x; fff(&x); } }; template struct S02<int>; template <class T> struct S03 { enum class local { nothing }; void m() { local x; fff(&x); } }; template struct S03<int>; template <class T> struct S04 { void m() { struct { } x; fff(&x); } }; template struct S04<int>; template <class T> struct S04a { void m() { union { } x; fff(&x); } }; template struct S04a<int>; template <class T> struct S05 { void m() { enum { nothing } x; fff(&x); } }; template struct S05<int>; template <class T> struct S06 { void m() { class { virtual void mmm() {} } x; fff(&x); } }; template struct S06<int>; } namespace PR20625 { template <typename T> void f() { struct N { static constexpr int get() { return 42; } }; constexpr int n = N::get(); static_assert(n == 42, "n == 42"); } void g() { f<void>(); } }
17.667506
98
0.546336
IntelSTORM
f58ed89cdf2bfd321a1e18b6f6f97985171e7f8a
365
cpp
C++
mod.cpp
M3ales/ACE-Grenade-Select-Interaction
793bfcdf223f6c680efa557a959a6a2cee10e692
[ "Apache-2.0", "MIT" ]
null
null
null
mod.cpp
M3ales/ACE-Grenade-Select-Interaction
793bfcdf223f6c680efa557a959a6a2cee10e692
[ "Apache-2.0", "MIT" ]
null
null
null
mod.cpp
M3ales/ACE-Grenade-Select-Interaction
793bfcdf223f6c680efa557a959a6a2cee10e692
[ "Apache-2.0", "MIT" ]
null
null
null
name = "ACE Vehicle Medical"; tooltipOwned="ACE Vehicle Medical"; picture = ""; logoSmall = ""; logo = ""; logoOver = ""; hideName = 0; hidePicture = 0; actionName = "Github"; action = "https://github.com/M3ales/MIRA_Vehicle_Medical"; description = "Adds ACE medical menu showing wounded to vehicles"; overview = "Adds ACE medical menu showing wounded to vehicles";
30.416667
66
0.723288
M3ales
f590210649af57877b138696f4dae9488a1056d2
2,378
hpp
C++
vvvcfg/cfg_node_value.hpp
VyacheslavVanin/vvvcfg
59c0974e3514087cc7c5a2dcd4851593343e8f06
[ "MIT" ]
null
null
null
vvvcfg/cfg_node_value.hpp
VyacheslavVanin/vvvcfg
59c0974e3514087cc7c5a2dcd4851593343e8f06
[ "MIT" ]
1
2018-01-02T10:23:33.000Z
2018-01-02T10:23:33.000Z
vvvcfg/cfg_node_value.hpp
VyacheslavVanin/vvvcfg
59c0974e3514087cc7c5a2dcd4851593343e8f06
[ "MIT" ]
null
null
null
#pragma once #include <ostream> #include <string> #include <unordered_map> #include <vector> #include "any.hpp" namespace vvv { struct Value { using list_type = std::vector<Value>; using dict_type = std::unordered_map<std::string, Value>; enum class DATA_TYPE { STRING, LIST, DICT }; Value(); explicit Value(DATA_TYPE type); explicit Value(const char* data); explicit Value(const std::string& data); DATA_TYPE getType() const { return type; } Value& operator=(const std::string& value); template <typename T> Value& operator=(const std::vector<T>& value) { type = DATA_TYPE::LIST; data = list_type(); auto& list = asList(); const auto s = value.size(); list.resize(s); for (size_t i = 0; i < s; ++i) list[i] = value[i]; return *this; } template <typename T> Value& operator=(const std::unordered_map<std::string, T>& value) { type = DATA_TYPE::DICT; data = dict_type(); auto& dict = asDict(); for (const auto& i : value) dict[i.first] = i.second; return *this; } Value& append(const Value& value); size_t size() const; bool empty() const; Value& operator[](size_t i); const Value& operator[](size_t i) const; Value& operator[](const std::string& key); const Value& operator[](const std::string& key) const; bool isString() const { return type == DATA_TYPE::STRING; } bool isList() const { return type == DATA_TYPE::LIST; } bool isDict() const { return type == DATA_TYPE::DICT; } const std::string& asString() const; std::string& asString(); const list_type& asList() const; list_type& asList(); const dict_type& asDict() const; dict_type& asDict(); std::vector<std::string> asStringList() const; double asDouble() const; int asInt() const; long long asLong() const; bool operator==(const Value& other) const; private: void assert_list() const; void assert_dict() const; void assert_string() const; vvv::Any data; DATA_TYPE type; }; } // namespace vvv std::ostream& operator<<(std::ostream& str, const vvv::Value& n); std::ostream& operator<<(std::ostream& str, const vvv::Value::list_type& n); std::ostream& operator<<(std::ostream& str, const vvv::Value::dict_type& n);
27.333333
76
0.616905
VyacheslavVanin
60d0415c1430e91e140bfc42645ff75f6934a80f
1,026
cpp
C++
Source/Clem/Rendering_/Shader.cpp
ShenMian/Clementine
a4d733e5f89141a7f00a043c73f0819eb3e277a8
[ "Apache-2.0" ]
46
2020-08-27T14:30:50.000Z
2021-12-10T05:45:07.000Z
Source/Clem/Rendering_/Shader.cpp
ShenMian/Clementine
a4d733e5f89141a7f00a043c73f0819eb3e277a8
[ "Apache-2.0" ]
2
2021-10-08T01:04:56.000Z
2021-12-10T08:20:08.000Z
Source/Clem/Rendering_/Shader.cpp
ShenMian/Clementine
a4d733e5f89141a7f00a043c73f0819eb3e277a8
[ "Apache-2.0" ]
6
2020-09-05T08:41:13.000Z
2022-03-26T02:31:26.000Z
// Copyright 2021 SMS // License(Apache-2.0) #include "Shader.h" #include "Renderer.h" #include <cassert> #include "OpenGL/GLShader.h" #include "Vulkan/VKShader.h" namespace clem { std::unordered_map<Shader_::Stage, const char*> Shader_::extension = { {Shader_::Stage::Vertex, "vert"}, {Shader_::Stage::Geometry, "geom"}, {Shader_::Stage::Fragment, "frag"}, {Shader_::Stage::Compute, "comp"}}; std::shared_ptr<Shader_> Shader_::create(const std::string& name, Stage stage) { switch(Renderer_::getAPI()) { using enum Renderer_::API; case OpenGL: return std::make_shared<GLShader_>(name, stage); case Vulkan: return std::make_shared<VKShader_>(name, stage); default: assert(false); } return nullptr; } Shader_::Shader_(const std::string& name, Stage stage) : name(name), stage(stage) { } const std::string& Shader_::getName() const { return name; } Shader_::Stage Shader_::getStage() const { return stage; } } // namespace clem
19.358491
78
0.650097
ShenMian
60d07608348e19c3b01bbea9fc16084afb6a0496
4,880
cpp
C++
geos/src/Distance.cpp
jusirkka/qopencpn
5e514ae8f43199c4d52278df6e4df85c46bd1ddc
[ "ISC", "X11", "MIT" ]
2
2021-07-09T14:13:55.000Z
2022-02-11T06:41:03.000Z
geos/src/Distance.cpp
jusirkka/qopencpn
5e514ae8f43199c4d52278df6e4df85c46bd1ddc
[ "ISC", "X11", "MIT" ]
null
null
null
geos/src/Distance.cpp
jusirkka/qopencpn
5e514ae8f43199c4d52278df6e4df85c46bd1ddc
[ "ISC", "X11", "MIT" ]
2
2022-02-11T06:41:05.000Z
2022-03-17T09:29:46.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2018 Paul Ramsey <pramsey@cleverlephant.ca> * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: algorithm/Distance.java @ 2017-09-04 * ********************************************************************* Adapted for QuteNav (c) 2021 Jukka Sirkka */ #include <cmath> #include <vector> #include <algorithm> #include "Distance.h" namespace geos { namespace algorithm { // geos.algorithm /*public static*/ double Distance::pointToSegment(const geom::Coordinate& p, const geom::Coordinate& A, const geom::Coordinate& B) { /* if start==end, then use pt distance */ if (A == B) { return glm::distance(A, p); } /* otherwise use comp.graphics.algorithms method: (1) AC dot AB r = --------- ||AB||^2 r has the following meaning: r=0 P = A r=1 P = B r<0 P is on the backward extension of AB r>1 P is on the forward extension of AB 0<r<1 P is interior to AB */ double r = ((p.x - A.x) * (B.x - A.x) + (p.y - A.y) * (B.y - A.y)) / ((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y)); if (r <= 0.0) { return glm::distance(p, A); } if (r >= 1.0) { return glm::distance(p, B); } /* (2) (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay) s = ----------------------------- L^2 Then the distance from C to P = |s|*L. */ double s = ((A.y - p.y) * (B.x - A.x) - (A.x - p.x) * (B.y - A.y)) / ((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y)); return fabs(s) * sqrt(((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y))); } /*public static*/ double Distance::pointToLinePerpendicular(const geom::Coordinate& p, const geom::Coordinate& A, const geom::Coordinate& B) { /* use comp.graphics.algorithms method (2) (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay) s = ----------------------------- L^2 Then the distance from C to P = |s|*L. */ double s = ((A.y - p.y) * (B.x - A.x) - (A.x - p.x) * (B.y - A.y)) / ((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y)); return fabs(s) * sqrt(((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y))); } /*public static*/ double Distance::segmentToSegment(const geom::Coordinate& A, const geom::Coordinate& B, const geom::Coordinate& C, const geom::Coordinate& D) { /* Check for zero-length segments */ if (A == B) { return pointToSegment(A, C, D); } if (C == D) { return pointToSegment(D, A, B); } /* AB and CD are line segments */ /* From comp.graphics.algo Solving the above for r and s yields (Ay-Cy)(Dx-Cx)-(Ax-Cx)(Dy-Cy) r = ----------------------------- (eqn 1) (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx) (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay) s = ----------------------------- (eqn 2) (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx) Let P be the position vector of the intersection point, then P=A+r(B-A) or Px=Ax+r(Bx-Ax) Py=Ay+r(By-Ay) By examining the values of r & s, you can also determine some other limiting conditions: If 0<=r<=1 & 0<=s<=1, intersection exists; If r<0 or r>1 or s<0 or s>1, line segments do not intersect; If the denominator in eqn 1 is zero, AB & CD are parallel; If the numerator in eqn 1 is also zero, AB & CD are collinear. */ bool noIntersection = false; double denom = (B.x - A.x) * (D.y - C.y) - (B.y - A.y) * (D.x - C.x); if (denom == 0) { noIntersection = true; } else { double r_num = (A.y - C.y) * (D.x - C.x) - (A.x - C.x) * (D.y - C.y); double s_num = (A.y - C.y) * (B.x - A.x) - (A.x - C.x) * (B.y - A.y); double s = s_num / denom; double r = r_num / denom; if ((r < 0) || (r > 1) || (s < 0) || (s > 1)) { noIntersection = true; } } if (noIntersection) { /* no intersection */ return std::min(pointToSegment(A, C, D), std::min(pointToSegment(B, C, D), std::min(pointToSegment(C, A, B), pointToSegment(D, A, B)))); } return 0.0; /* intersection exists */ } } // namespace geos.algorithm } //namespace geos
27.111111
90
0.456352
jusirkka
60d21cac90d8c3de34318a088425a3b62007b34f
7,541
hpp
C++
debug/tracing.hpp
v1ne/v1util
8c70d7b7517b90d62f3adf3a64df213e45818fbe
[ "BSD-2-Clause" ]
null
null
null
debug/tracing.hpp
v1ne/v1util
8c70d7b7517b90d62f3adf3a64df213e45818fbe
[ "BSD-2-Clause" ]
null
null
null
debug/tracing.hpp
v1ne/v1util
8c70d7b7517b90d62f3adf3a64df213e45818fbe
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "v1util/base/macromagic.hpp" #include "v1util/base/platform.hpp" #include "v1util/stl-plus/filesystem-fwd.hpp" #include <stddef.h> #include <cstdint> namespace v1util::tracing { V1_PUBLIC void init(size_t bufferCapacityB); V1_PUBLIC void destroy(); V1_PUBLIC void setStarted(bool started); V1_PUBLIC bool started(); V1_PUBLIC std::filesystem::path finishAndWriteToPathPrefix(const std::filesystem::path& pathPrefix); struct Status { bool initialized : 1; bool started : 1; size_t capacity; size_t used; }; V1_PUBLIC Status status(); //! Create a trace entry for when this object created and destroyed, defining a scope. #define V1_TRACING_SCOPE(category, name) \ const auto V1_PP_UNQIUE_NAME(v1TracingScope) = v1util::tracing::detail::TracingScope { \ V1_PP_STR(category), V1_PP_STR(name) \ } #define V1_TRACING_SCOPE1(category, name, var0) \ const auto V1_PP_UNQIUE_NAME(v1TracingScope) = v1util::tracing::detail::TracingScope { \ V1_PP_STR(category), V1_PP_STR(name), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0) \ } #define V1_TRACING_SCOPE2(category, name, var0, var1) \ const auto V1_PP_UNQIUE_NAME(v1TracingScope) = v1util::tracing::detail::TracingScope { \ V1_PP_STR(category), V1_PP_STR(name), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var1), var1) \ } #define V1_TRACING_SCOPE3(category, name, var0, var1, var2) \ const auto V1_PP_UNQIUE_NAME(v1TracingScope) = v1util::tracing::detail::TracingScope { \ V1_PP_STR(category), V1_PP_STR(name), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var1), var1), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var2), var2) \ } //! Create a tracing scope around the statement, returning the value of the statement #define V1_TRACING_STMT(category, name, Statement) \ [&]() { \ const auto V1_PP_UNQIUE_NAME(v1TracingScope) = \ v1util::tracing::detail::TracingScope{V1_PP_STR(category), V1_PP_STR(name)}; \ return Statement; \ }() //! Trace the value of a variable #define V1_TRACING_VARRIABLE1(category, name, var0) \ v1util::tracing::detail::track_variable(V1_PP_STR(category), V1_PP_STR(name), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0)) #define V1_TRACING_VARRIABLE2(category, name, var0, var1) \ v1util::tracing::detail::track_variable(V1_PP_STR(category), V1_PP_STR(name), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var1), var1)) #define V1_TRACING_VARRIABLE3(category, name, var0, var1, var2) \ v1util::tracing::detail::track_variable(V1_PP_STR(category), V1_PP_STR(name), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var1), var1), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var2), var2)) //! Trace an asynchronous event #define V1_TRACING_ASYNC_BEGIN(category, name, id) \ v1util::tracing::detail::begin_async_event(V1_PP_STR(category), V1_PP_STR(name), id) #define V1_TRACING_ASYNC_BEGIN1(category, name, id, var0) \ v1util::tracing::detail::begin_async_event(V1_PP_STR(category), V1_PP_STR(name), id, \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0)) #define V1_TRACING_ASYNC_BEGIN2(category, name, id, var0, var1) \ v1util::tracing::detail::begin_async_event(V1_PP_STR(category), V1_PP_STR(name), id, \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var0), var0), \ v1util::tracing::detail::toTraceArg(V1_PP_STR(var1), var1)) #define V1_TRACING_ASYNC_END(category, name, id) \ v1util::tracing::detail::end_async_event(V1_PP_STR(category), V1_PP_STR(name), id) namespace detail { struct TraceArg { const char* pKey; union { const char* pDynamicString; int64_t intNumber; double fpNumber; }; enum { kStaticString, kInt64, kDouble } Type; }; inline TraceArg toTraceArg(const char* pKey, const char* pDynamicString) { TraceArg Arg; Arg.pKey = pKey; Arg.pDynamicString = pDynamicString; Arg.Type = TraceArg::kStaticString; return Arg; } inline TraceArg toTraceArg(const char* pKey, int intNumber) { TraceArg Arg; Arg.pKey = pKey; Arg.intNumber = int64_t(intNumber); Arg.Type = TraceArg::kInt64; return Arg; } inline TraceArg toTraceArg(const char* pKey, unsigned int intNumber) { TraceArg Arg; Arg.pKey = pKey; Arg.intNumber = int64_t(intNumber); Arg.Type = TraceArg::kInt64; return Arg; } inline TraceArg toTraceArg(const char* pKey, int64_t intNumber) { TraceArg Arg; Arg.pKey = pKey; Arg.intNumber = intNumber; Arg.Type = TraceArg::kInt64; return Arg; } inline TraceArg toTraceArg(const char* pKey, uint64_t intNumber) { TraceArg Arg; Arg.pKey = pKey; Arg.intNumber = int64_t(intNumber); Arg.Type = TraceArg::kInt64; return Arg; } inline TraceArg toTraceArg(const char* pKey, float fpNumber) { TraceArg Arg; Arg.pKey = pKey; Arg.fpNumber = double(fpNumber); Arg.Type = TraceArg::kDouble; return Arg; } inline TraceArg toTraceArg(const char* pKey, double fpNumber) { TraceArg Arg; Arg.pKey = pKey; Arg.fpNumber = fpNumber; Arg.Type = TraceArg::kDouble; return Arg; } class V1_PUBLIC TracingScope { public: TracingScope(const char* pCategory, const char* pName); TracingScope(const char* pCategory, const char* pName, const TraceArg& arg0); TracingScope( const char* pCategory, const char* pName, const TraceArg& arg0, const TraceArg& arg1); TracingScope(const char* pCategory, const char* pName, const TraceArg& arg0, const TraceArg& arg1, const TraceArg& arg2); ~TracingScope(); private: const char* mpCategory; const char* mpName; }; V1_PUBLIC void track_variable(const char* pCategory, const char* pName, const TraceArg& arg0); V1_PUBLIC void track_variable( const char* pCategory, const char* pName, const TraceArg& arg0, const TraceArg& arg1); V1_PUBLIC void track_variable(const char* pCategory, const char* pName, const TraceArg& arg0, const TraceArg& arg1, const TraceArg& arg2); V1_PUBLIC void begin_async_event(const char* pCategory, const char* pName, int64_t id); V1_PUBLIC void begin_async_event( const char* pCategory, const char* pName, int64_t id, const TraceArg& arg0); V1_PUBLIC void begin_async_event(const char* pCategory, const char* pName, int64_t id, const TraceArg& arg0, const TraceArg& arg1); V1_PUBLIC void end_async_event(const char* pCategory, const char* pName, int64_t id); } // namespace detail } // namespace v1util::tracing
40.983696
100
0.647925
v1ne
60d44ad99b9ab40dc39befd9c83450e025e6d713
449
hpp
C++
src/ember/config.hpp
apples/ember_engine
26ddb8947a32e42fafc5c2c0b404f3f407c1dd95
[ "MIT" ]
null
null
null
src/ember/config.hpp
apples/ember_engine
26ddb8947a32e42fafc5c2c0b404f3f407c1dd95
[ "MIT" ]
1
2020-10-03T03:47:09.000Z
2020-10-03T03:47:09.000Z
src/ember/config.hpp
apples/ld47
660ae705a7315ee438d5f509e44d94ff1c16409a
[ "MIT" ]
null
null
null
#pragma once #include "json.hpp" #include "json_serializers.hpp" #include <string> #include "reflection_start.hpp" namespace ember::config { using json_serializers::basic::from_json; using json_serializers::basic::to_json; struct display_t { int width; int height; }; REFLECT(display_t, (width)(height)) struct config { display_t display; }; REFLECT(config, (display)) } // namespace ember::config #include "reflection_end.hpp"
15.482759
41
0.730512
apples
60d485362c536a851936422ba30f21ac2b3f4947
37
hpp
C++
src/boost_range_functions.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_range_functions.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_range_functions.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/range/functions.hpp>
18.5
36
0.783784
miathedev
60d4fc88ce739737a3dd5ec3d6900c457f2e6851
6,638
cpp
C++
hiro/windows/widget/hex-edit.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
10
2019-12-19T01:19:41.000Z
2021-02-18T16:30:29.000Z
hiro/windows/widget/hex-edit.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
hiro/windows/widget/hex-edit.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
#if defined(Hiro_HexEdit) namespace hiro { auto pHexEdit::construct() -> void { hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, L"EDIT", L"", WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL | ES_READONLY | ES_MULTILINE | ES_WANTRETURN, 0, 0, 0, 0, _parentHandle(), nullptr, GetModuleHandle(0), 0 ); scrollBar = CreateWindowEx( 0, L"SCROLLBAR", L"", WS_VISIBLE | WS_CHILD | SBS_VERT, 0, 0, 0, 0, hwnd, nullptr, GetModuleHandle(0), 0 ); SetWindowLongPtr(scrollBar, GWLP_USERDATA, (LONG_PTR)&reference); pWidget::construct(); setAddress(state().address); setBackgroundColor(state().backgroundColor); setLength(state().length); update(); PostMessage(hwnd, EM_SETSEL, 10, 10); } auto pHexEdit::destruct() -> void { DestroyWindow(hwnd); } auto pHexEdit::setAddress(unsigned address) -> void { SetScrollPos(scrollBar, SB_CTL, address / state().columns, true); update(); } auto pHexEdit::setBackgroundColor(Color color) -> void { if(backgroundBrush) DeleteObject(backgroundBrush); backgroundBrush = CreateSolidBrush(color ? CreateRGB(color) : GetSysColor(COLOR_WINDOW)); } auto pHexEdit::setColumns(unsigned columns) -> void { update(); } auto pHexEdit::setForegroundColor(Color color) -> void { } auto pHexEdit::setLength(unsigned length) -> void { SetScrollRange(scrollBar, SB_CTL, 0, rowsScrollable(), true); EnableWindow(scrollBar, rowsScrollable() > 0); update(); } auto pHexEdit::setRows(unsigned rows) -> void { update(); } auto pHexEdit::update() -> void { if(!state().onRead) { SetWindowText(hwnd, L""); return; } unsigned cursorPosition = Edit_GetSel(hwnd); string output; unsigned address = state().address; for(auto row : range(state().rows)) { output.append(hex(address, 8L)); output.append(" "); string hexdata; string ansidata = " "; for(auto column : range(state().columns)) { if(address < state().length) { uint8_t data = self().doRead(address++); hexdata.append(hex(data, 2L)); hexdata.append(" "); ansidata.append(data >= 0x20 && data <= 0x7e ? (char)data : '.'); } else { hexdata.append(" "); ansidata.append(" "); } } output.append(hexdata); output.append(ansidata); if(address >= state().length) break; if(row != state().rows - 1) output.append("\r\n"); } SetWindowText(hwnd, utf16_t(output)); Edit_SetSel(hwnd, LOWORD(cursorPosition), HIWORD(cursorPosition)); } auto pHexEdit::keyPress(unsigned scancode) -> bool { if(!state().onRead) return false; signed position = LOWORD(Edit_GetSel(hwnd)); signed lineWidth = 10 + (state().columns * 3) + 1 + state().columns + 2; signed cursorY = position / lineWidth; signed cursorX = position % lineWidth; if(scancode == VK_HOME) { signed offset = cursorY * lineWidth + 10; Edit_SetSel(hwnd, offset, offset); return true; } if(scancode == VK_END) { signed offset = cursorY * lineWidth + 57; Edit_SetSel(hwnd, offset, offset); return true; } if(scancode == VK_UP) { if(cursorY > 0) return false; scrollTo(scrollPosition() - 1); return true; } if(scancode == VK_DOWN) { if(cursorY >= rows() - 1) return true; if(cursorY < state().rows - 1) return false; scrollTo(scrollPosition() + 1); return true; } if(scancode == VK_PRIOR) { scrollTo(scrollPosition() - state().rows); return true; } if(scancode == VK_NEXT) { scrollTo(scrollPosition() + state().rows); return true; } //convert scancode to hex nibble if(scancode >= '0' && scancode <= '9') scancode = scancode - '0'; else if(scancode >= 'A' && scancode <= 'F') scancode = scancode - 'A' + 10; else if(scancode >= 'a' && scancode <= 'f') scancode = scancode - 'a' + 10; else return false; if(cursorX >= 10) { //not on an address cursorX -= 10; if((cursorX % 3) != 2) { //not on a space bool cursorNibble = (cursorX % 3) == 1; //0 = high, 1 = low cursorX /= 3; if(cursorX < state().columns) { //not in ANSI region unsigned address = state().address + (cursorY * state().columns + cursorX); if(address >= state().length) return false; //do not edit past end of data uint8_t data = self().doRead(address); //write modified value if(cursorNibble == 1) { data = (data & 0xf0) | (scancode << 0); } else { data = (data & 0x0f) | (scancode << 4); } self().doWrite(address, data); //auto-advance cursor to next nibble or byte position++; if(cursorNibble && cursorX != state().columns - 1) position++; Edit_SetSel(hwnd, position, position); //refresh output to reflect modified data update(); } } } return true; } auto pHexEdit::rows() -> int { return (max(1u, state().length) + state().columns - 1) / state().columns; } auto pHexEdit::rowsScrollable() -> int { return max(0u, rows() - state().rows); } auto pHexEdit::scrollPosition() -> int { return state().address / state().columns; } auto pHexEdit::scrollTo(signed position) -> void { if(position > rowsScrollable()) position = rowsScrollable(); if(position < 0) position = 0; if(position == scrollPosition()) return; self().setAddress(position * state().columns); } auto pHexEdit::windowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) -> maybe<LRESULT> { if(msg == WM_KEYDOWN) { if(keyPress(wparam)) return 0; } if(msg == WM_MOUSEWHEEL) { int offset = -((int16_t)HIWORD(wparam) / WHEEL_DELTA); scrollTo(scrollPosition() + offset); return true; } if(msg == WM_SIZE) { RECT rc; GetClientRect(hwnd, &rc); SetWindowPos(scrollBar, HWND_TOP, rc.right - 18, 0, 18, rc.bottom, SWP_SHOWWINDOW); } if(msg == WM_VSCROLL) { SCROLLINFO info{sizeof(SCROLLINFO)}; info.fMask = SIF_ALL; GetScrollInfo((HWND)lparam, SB_CTL, &info); switch(LOWORD(wparam)) { case SB_LEFT: info.nPos = info.nMin; break; case SB_RIGHT: info.nPos = info.nMax; break; case SB_LINELEFT: info.nPos--; break; case SB_LINERIGHT: info.nPos++; break; case SB_PAGELEFT: info.nPos -= info.nMax >> 3; break; case SB_PAGERIGHT: info.nPos += info.nMax >> 3; break; case SB_THUMBTRACK: info.nPos = info.nTrackPos; break; } info.fMask = SIF_POS; SetScrollInfo((HWND)lparam, SB_CTL, &info, TRUE); GetScrollInfo((HWND)lparam, SB_CTL, &info); //get clamped position scrollTo(info.nPos); return true; } return pWidget::windowProc(hwnd, msg, wparam, lparam); } } #endif
27.204918
96
0.6279
13824125580
60d7bf333581bafe4235fb73564f7a93cc894c25
750
cc
C++
洛谷/省选-/P2657-tle.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
67
2019-07-14T05:38:41.000Z
2021-12-23T11:52:51.000Z
洛谷/省选-/P2657-tle.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
null
null
null
洛谷/省选-/P2657-tle.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
12
2020-01-16T10:48:01.000Z
2021-06-11T16:49:04.000Z
/* * Author : OFShare * E-mail : OFShare@outlook.com * Created Time : 2020-04-27 13:32:23 PM * File Name : P2657.cc */ #include <bits/stdc++.h> #define ll long long void debug() { #ifdef Acui freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif } ll A, B, cnt; // 判断x是否是题目所说的wendy数 bool check(ll x) { std::vector<int> vec; int n = 0; while (x) { vec.push_back(x % 10); x /= 10; ++n; } if (n <= 1) return true; for (int i = 0; i < n - 1; ++i) { if (std::abs(vec[i] - vec[i + 1]) < 2) return false; } return true; } int main() { scanf("%lld %lld", &A, &B); for (int i = A; i <= B; ++i) { if (check(i)) ++cnt; } printf("%lld\n", cnt); return 0; }
17.44186
56
0.506667
OFShare
60d8fdec5b66c7acfe793f5dabf11b7f4d525193
589
hpp
C++
include/forecast_io/parsers/ForecastAttribute.hpp
Crystalix007/DarkSky-CPP
10497ff292efdc460a67bc5dc44811b3a1459beb
[ "Apache-2.0" ]
null
null
null
include/forecast_io/parsers/ForecastAttribute.hpp
Crystalix007/DarkSky-CPP
10497ff292efdc460a67bc5dc44811b3a1459beb
[ "Apache-2.0" ]
null
null
null
include/forecast_io/parsers/ForecastAttribute.hpp
Crystalix007/DarkSky-CPP
10497ff292efdc460a67bc5dc44811b3a1459beb
[ "Apache-2.0" ]
null
null
null
#ifndef FORECASTATTRIBUTE_HPP #define FORECASTATTRIBUTE_HPP #include <string> namespace forecast_io { namespace parsers { const std::string ForecastAttribute_NAME = "ForecastAttribute"; enum ForecastAttribute { ALERTS, CURRENTLY, DAILY, FLAGS, HOURLY, LATITUDE, LONGITUDE, MINUTELY, OFFSET, TIMEZONE, ForecastAttribute_MAX = TIMEZONE, ForecastAttribute_COUNT = ForecastAttribute_MAX + 1 }; // Typedefs typedef std::unordered_map<std::string, ForecastAttribute> ForecastAttributeNameMap; } // namespace parsers } // namespace forecast_io #endif // FORECASTATTRIBUTE_HPP
15.918919
84
0.787776
Crystalix007
60d9e10be68d34cbbcd6a42014c56814187a2eae
4,474
cpp
C++
source/logging/processors/async_wait_processor.cpp
pthis/CppLogging
5c76bceef12eec705bf07b28c09d74023c1c3bb0
[ "MIT" ]
97
2016-10-09T04:10:25.000Z
2022-03-30T21:23:25.000Z
source/logging/processors/async_wait_processor.cpp
pthis/CppLogging
5c76bceef12eec705bf07b28c09d74023c1c3bb0
[ "MIT" ]
4
2019-10-25T01:45:13.000Z
2021-12-15T04:09:58.000Z
source/logging/processors/async_wait_processor.cpp
pthis/CppLogging
5c76bceef12eec705bf07b28c09d74023c1c3bb0
[ "MIT" ]
34
2018-12-28T14:01:46.000Z
2021-11-24T17:22:09.000Z
/*! \file async_wait_processor.cpp \brief Asynchronous wait logging processor implementation \author Ivan Shynkarenka \date 01.08.2016 \copyright MIT License */ #include "logging/processors/async_wait_processor.h" #include "errors/fatal.h" #include "threads/thread.h" #include <cassert> namespace CppLogging { AsyncWaitProcessor::AsyncWaitProcessor(const std::shared_ptr<Layout>& layout, bool auto_start, size_t capacity, size_t initial, const std::function<void ()>& on_thread_initialize, const std::function<void ()>& on_thread_clenup) : Processor(layout), _queue(capacity, initial), _on_thread_initialize(on_thread_initialize), _on_thread_clenup(on_thread_clenup) { _started = false; // Start the logging processor if (auto_start) Start(); } AsyncWaitProcessor::~AsyncWaitProcessor() { // Stop the logging processor if (IsStarted()) Stop(); } bool AsyncWaitProcessor::Start() { bool started = IsStarted(); if (!Processor::Start()) return false; if (!started) { // Start processing thread _thread = CppCommon::Thread::Start([this]() { ProcessThread(_on_thread_initialize, _on_thread_clenup); }); } return true; } bool AsyncWaitProcessor::Stop() { if (IsStarted()) { // Thread local stop operation record thread_local Record stop; // Enqueue stop operation record stop.timestamp = 0; EnqueueRecord(stop); // Wait for processing thread _thread.join(); } return Processor::Stop(); } bool AsyncWaitProcessor::ProcessRecord(Record& record) { // Check if the logging processor started if (!IsStarted()) return true; // Enqueue the given logger record return EnqueueRecord(record); } bool AsyncWaitProcessor::EnqueueRecord(Record& record) { // Try to enqueue the given logger record return _queue.Enqueue(record); } void AsyncWaitProcessor::ProcessThread(const std::function<void ()>& on_thread_initialize, const std::function<void ()>& on_thread_clenup) { // Call the thread initialize handler assert((on_thread_initialize) && "Thread initialize handler must be valid!"); if (on_thread_initialize) on_thread_initialize(); try { // Thread local logger records to process thread_local std::vector<Record> records; thread_local uint64_t previous = 0; // Reserve initial space for logging records records.reserve(_queue.capacity()); while (_started) { // Dequeue the next logging record if (!_queue.Dequeue(records)) return; // Current timestamp uint64_t current = 0; // Process all logging records for (auto& record : records) { // Handle stop operation record if (record.timestamp == 0) return; // Handle flush operation record if (record.timestamp == 1) { // Flush the logging processor Processor::Flush(); continue; } // Process logging record Processor::ProcessRecord(record); // Find the latest record timestamp if (record.timestamp > current) current = record.timestamp; } // Handle auto-flush period if (CppCommon::Timespan((int64_t)(current - previous)).seconds() > 1) { // Flush the logging processor Processor::Flush(); // Update the previous timestamp previous = current; } } } catch (const std::exception& ex) { fatality(ex); } catch (...) { fatality("Asynchronous wait logging processor terminated!"); } // Call the thread cleanup handler assert((on_thread_clenup) && "Thread cleanup handler must be valid!"); if (on_thread_clenup) on_thread_clenup(); } void AsyncWaitProcessor::Flush() { // Check if the logging processor started if (!IsStarted()) return; // Thread local flush operation record thread_local Record flush; // Enqueue flush operation record flush.timestamp = 1; EnqueueRecord(flush); } } // namespace CppLogging
25.276836
227
0.602146
pthis