blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3f15045628f3a1f44d97a88b4a577aadbece5f3c | b95d26916dcc2c9e99395eaa02387447f402f069 | /OperatorOverload/IntArray.cpp | 813b4d2c0196f53b89247b6ca3c6247fea568640 | [] | no_license | zhmhClark/cplusplus | 2b4cd80f4a865366b6ac57dfb1ebb7476bb3c062 | a82dbe92fc6b9a8a98008b0805791ec9da9b5558 | refs/heads/master | 2020-05-05T09:51:48.551812 | 2019-04-07T05:02:33 | 2019-04-07T05:02:33 | 179,920,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | #include "IntArray.h"
IntArray::IntArray(int n)
{
arr = new int[n];
size = n;
}
IntArray::~IntArray()
{
}
IntArray & IntArray::operator=(IntArray & ar)
{
size = ar.size;
delete []arr;
arr = new int[ar.size];
for (int i = 0; i < size; i++)
arr[i] = ar.arr[i];
return *this;
}
| [
"778970072@qq.com"
] | 778970072@qq.com |
8395f55a2870413c9ac218f1f72f09c0eeaadf13 | b2263008c8d6159b3a2253ec237eb7dc71e2e4b2 | /libs/Flow/test/Flow/Components/TestConstant.cpp | 07f403b7dbe9e9e9435bb47d09fabc392a14dd0c | [] | no_license | mckelley3v/BlackBox | 32daa66cbccd2b47577854b887bf51af8a5bbab9 | 005339363962347c6aa484403db04c08fe0469c7 | refs/heads/master | 2021-01-23T14:03:45.035245 | 2017-08-27T19:26:21 | 2017-08-27T19:26:21 | 23,777,405 | 0 | 0 | null | 2014-11-06T16:20:07 | 2014-09-08T02:51:51 | C++ | UTF-8 | C++ | false | false | 738 | cpp | #include "Flow/Components/Constant.hpp"
#include "Flow/TypeManager.hpp"
#include "catch.hpp"
TEST_CASE("Test Flow::Components::Constant", "[Flow]")
{
using namespace Flow;
using namespace Flow::Components;
TypeManager const type_manager
{{
// ComponentTypes
{
Constant<float>::GetComponentTypeEntry(),
},
// ConnectionTypes
{
// Name BaseNames
{ "bool", {}},
{ "int", {}},
{ "float", {}},
},
}};
Constant<float> const_one(type_manager, "one", {}, 1.0f);
CHECK(GetOutputConnectionPtr<float>(const_one, "Value") == &const_one.GetValue());
CHECK(const_one.GetValue() == 1.0f);
}
| [
"mckelley3v@gmail.com"
] | mckelley3v@gmail.com |
b0a7a3ca256640f55f5ac6e25c16e046ca072467 | 4c10cf68de9f75dbee15f23dc612996c73c02e6c | /Ch8/build-8_4-Desktop_Qt_6_1_3_MinGW_64_bit-Debug/debug/moc_mainwindow.cpp | a818bb0a9b349c77670cb1fe08682fb6340031cc | [] | no_license | Frollerman/QtBook | 784d6f79267744e9583999779f3f990bdd0df4c2 | c71c1884343955e9c33590a4547aa6f2daa35e18 | refs/heads/master | 2023-08-30T18:13:37.363513 | 2021-11-07T20:58:16 | 2021-11-07T20:58:16 | 408,225,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,579 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 68 (Qt 6.1.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../8_4/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 68
#error "This file was generated using the moc from 6.1.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
const uint offsetsAndSize[2];
char stringdata0[11];
};
#define QT_MOC_LITERAL(ofs, len) \
uint(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs), len
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 10) // "MainWindow"
},
"MainWindow"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
9, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
(void)_o;
(void)_id;
(void)_c;
(void)_a;
}
const QMetaObject MainWindow::staticMetaObject = { {
QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(),
qt_meta_stringdata_MainWindow.offsetsAndSize,
qt_meta_data_MainWindow,
qt_static_metacall,
nullptr,
nullptr,
nullptr
} };
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"frollerman@yandex.ru"
] | frollerman@yandex.ru |
99f08d3c31e2c8dc4d68f8a038a7c3e96c89d9b9 | ac2f2a6b74b380a7b727c73072534c1a64ab0310 | /WiFiConnector.h | 071c49f21bd995e966b9ea65755dd7dfba6186ba | [] | no_license | JuanParker1/HODLHUD | 9f6e3a44f6e2aac95868bb9b110cf108827a3262 | 418b91d156428dabee474e1895443eb4d5a1e8a6 | refs/heads/master | 2023-08-26T23:10:32.909057 | 2021-10-20T15:14:15 | 2021-10-20T15:14:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,737 | h | // Third party libraries#include <WiFi.h>
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiMulti.h>
#include <WiFiUdp.h>
#include <WiFiScan.h>
#include <ETH.h>
#include <WiFiClient.h>
#include <WiFiSTA.h>
#include <WiFiServer.h>
#include <WiFiType.h>
#include <WiFiGeneric.h>
class WiFiConnector {
private:
// Properties
char* ssid; // Name of the network
char* password; // Password used to connect to the network
String deviceHostName; // Name the device uses to idenify itself on the network/modem
uint32_t connectionAttemptCount; // Tracker of current connection attempts
uint32_t maxConnectionAttempts; // Amount of times a WiFi connection attempt must be made before the device is reboot
uint32_t connectionAttemptDelay; // Time between each connection attempt in ms
uint32_t notConnectedCounter; // Time between each connection attempt in ms
// Services
Logger* logger = new Logger("WiFiConnector");
public:
WiFiConnector(char* Ssid, char* Password, String DeviceHostName = "HODL-HUD", uint32_t ConnectionAttemptCount = 1, uint32_t MaxConnectionAttempts = 5, uint32_t ConnectionAttemptDelay = 2500) {
ssid = Ssid;
password = Password;
connectionAttemptCount = ConnectionAttemptCount;
maxConnectionAttempts = MaxConnectionAttempts;
connectionAttemptDelay = ConnectionAttemptDelay;
logger->print("New WiFi connection configured: " + String(ssid) + "");
}
/* Connect to the network using the configured credentials */
void connect() {
// Set hostname of the device & connect to the WiFi
WiFi.hostname(deviceHostName);
WiFi.begin(ssid, password);
logger->print("Connecting to WiFi (" + String(ssid) + ")");
logger->print("Using MAC address: " + WiFi.macAddress());
notConnectedCounter = 1;
while (WiFi.status() != WL_CONNECTED) {
reconnect();
}
logger->print("WiFi connected");
}
void reconnect() {
delay(connectionAttemptDelay);
// Report how many times a connection has been attempted
logger->print("Connection attempt " + String(notConnectedCounter) + "/" + String(maxConnectionAttempts));
// Reset board if not connected after max attempts
notConnectedCounter++;
if(notConnectedCounter > maxConnectionAttempts) {
logger->print("Resetting " + deviceHostName + " due to Wifi not connecting...");
logger->print("Is your mobile hotspot, WiFi or ssid/password setup correctly & online?");
delay(1000);
ESP.restart();
}
}
};
| [
"teijevhemert@gmail.com"
] | teijevhemert@gmail.com |
fbc4115be6c49b658fc6606714b82a7109185555 | e3a01923d5067768b2fb59f902a5ef821cbb56fc | /src/masternodeconfig.cpp | 36a23214be072c4f6f82e1dc736c10425bae3ff9 | [
"MIT"
] | permissive | c0de0x/hoolibet | 7687c18ea17368c7ffcdfc00ee11bde7ab2a3bb5 | 29cf960a23c83958f76cc6a5bd87e9ce5370215e | refs/heads/master | 2020-06-13T00:33:54.222219 | 2019-06-28T21:19:21 | 2019-06-28T21:19:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,879 | cpp | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "masternodeconfig.h"
#include "util.h"
#include "ui_interface.h"
#include <base58.h>
CMasternodeConfig masternodeConfig;
void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex)
{
CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
entries.push_back(cme);
}
bool CMasternodeConfig::read(std::string& strErr)
{
int linenumber = 1;
boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);
if (!streamConfig.good()) {
FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a");
if (configFile != NULL) {
std::string strHeader = "# Masternode config file\n"
"# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
"# Example: mn1 127.0.0.2:21340 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n";
fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
fclose(configFile);
}
return true; // Nothing to read, so just return
}
for (std::string line; std::getline(streamConfig, line); linenumber++) {
if (line.empty()) continue;
std::istringstream iss(line);
std::string comment, alias, ip, privKey, txHash, outputIndex;
if (iss >> comment) {
if (comment.at(0) == '#') continue;
iss.str(line);
iss.clear();
}
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
iss.str(line);
iss.clear();
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
strErr = _("Could not parse masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
streamConfig.close();
return false;
}
}
int port = 0;
std::string hostname = "";
SplitHostPort(ip, port, hostname);
if(port == 0 || hostname == "") {
strErr = _("Failed to parse host:port string") + "\n"+
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
streamConfig.close();
return false;
}
if (Params().NetworkID() == CBaseChainParams::MAIN) {
if (port != 21340) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
_("(must be 21340 for mainnet)");
streamConfig.close();
return false;
}
} else if (port == 21340) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
_("(21340 could be used only on mainnet)");
streamConfig.close();
return false;
}
add(alias, ip, privKey, txHash, outputIndex);
}
streamConfig.close();
return true;
}
bool CMasternodeConfig::CMasternodeEntry::castOutputIndex(int &n)
{
try {
n = std::stoi(outputIndex);
} catch (const std::exception e) {
LogPrintf("%s: %s on getOutputIndex\n", __func__, e.what());
return false;
}
return true;
}
| [
"hoolibets@gmail.com"
] | hoolibets@gmail.com |
dde7416137dc0f3a7d306ff7216d510daf7a30a6 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14263/function14263_schedule_0/function14263_schedule_0_wrapper.cpp | 19669df35b78773e9ef3c1ef58f354097cf73a8a | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | #include "Halide.h"
#include "function14263_schedule_0_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){Halide::Buffer<int32_t> buf0(512, 1024, 128);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14263_schedule_0(buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14263/function14263_schedule_0/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
3ceee8ac6ad837503b5c9b5c9df07cc290b34ea1 | b06a69fcf18bed324fddead29c0104a3c5047d5f | /lab5/main.cpp | e5685707dc87e5bda1eec77d056dd026f17c249a | [] | no_license | devepodete/oop_labs | 61c566a89e4207e4211ccc79a67a9d9a9693031d | 2b8cbd30b259589b5c743c625a2ac4975704bbae | refs/heads/main | 2022-12-25T15:00:46.110987 | 2020-10-07T16:13:45 | 2020-10-07T16:13:45 | 302,085,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,675 | cpp | /*
Добавление пятиугольников в стек на умных указателях с использованием итераторов.
Черемисинов Максим
М8О-201Б-18
*/
#include <iostream>
#include <string>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <memory>
#include <exception>
#include "stack.hpp"
const double PI = 3.14159265358;
void print_actions(){
std::cout << "0. \"exit\" - exit\n";
std::cout << "1. \"push\" - push figure to stack\n";
std::cout << "2. \"pop\" - pop figure from stack\n";
std::cout << "3. \"print\" - print stack\n";
std::cout << "4. \"random N\" - push to stack N automatically generated figures\n";
std::cout << "5. \"insert N\" - insert item to pos N\n";
std::cout << "6. \"erase N\" - delete item from pos N\n";
std::cout << "7. \"count AREA\" - count figures with area less then AREA\n";
}
int main(){
std::srand(std::time(NULL));
stack<pentagon<double>> st;
print_actions();
std::string action(" ");
std::cout << "> ";
std::cin >> action;
while(action != "exit"){
if(action == "push"){
std::cout << "figure cords: ";
pentagon<double> temp;
std::cin >> temp;
st.push(temp);
goto end;
}
if(action == "pop"){
try{
st.pop();
}catch(std::exception &ex){
std::cout << "Exception with pop(): " << ex.what() << "\n";
}
goto end;
}
if(action == "print"){
st.print();
goto end;
}
if(action == "random"){
int k;
std::cin >> k;
for(int i = 0; i < k; i++){
double x0 = rand()%100;
double y0 = rand()%100;
double r = rand()%10+1;
std::pair<double, double> c[5];
for(int j = 0; j < 5; j++){
c[j].first = x0 + r*cos(2*PI*j/5);
c[j].second = y0 + r*sin(2*PI*j/5);
}
pentagon<double> temp(c[0], c[1], c[2], c[3], c[4]);
st.push(temp);
}
goto end;
}
if(action == "insert"){
int k;
std::cin >> k;
try{
auto it = st.at(k);
std::cout << "figure cords: ";
pentagon<double> temp;
std::cin >> temp;
st.insert(it, temp);
}catch(std::exception &ex){
std::cout << "Exception with insert(): " << ex.what() << "\n";
}
goto end;
}
if(action == "erase"){
int k;
std::cin >> k;
try{
auto it = st.at(k);
st.erase(it);
}catch(std::exception &ex){
std::cout << "Exception with erase(): " << ex.what() << "\n";
}
goto end;
}
if(action == "count"){
double k;
std::cin >> k;
int ans = std::count_if(st.begin(), st.end(), [&, k](pentagon<double> pd){return pd.area() < k;});
std::cout << "res = " << ans << "\n";
goto end;
}
end:
std::cout << "> ";
std::cin >> action;
}
}
| [
"noreply@github.com"
] | devepodete.noreply@github.com |
b25da851800216dda7b029cfe174519c684169f6 | a3a3183bc3ae9d3d4bad2f4923e8297bce0ff7d3 | /final/Python-3.9.0/Modules/_decimal/libmpdec/mpdecimal.h | 2815a8cde31db886b66b6fcab45bb62e41422e39 | [] | no_license | Nuitka/Nuitka-references | 4b78831e6947f1c4b32ef034435a88ecfd27f701 | f20d1b5728ec00cf8a5b23d650101c288b2594e9 | refs/heads/main | 2023-08-06T19:12:11.795836 | 2023-08-03T14:54:16 | 2023-08-03T14:55:22 | 169,884,560 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 41,084 | h | /*
* Copyright (c) 2008-2020 Stefan Krah. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef LIBMPDEC_MPDECIMAL_H_
#define LIBMPDEC_MPDECIMAL_H_
#ifndef _MSC_VER
#include "pyconfig.h"
#endif
#ifdef __cplusplus
#include <cinttypes>
#include <climits>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
extern "C" {
#else
#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#endif
#if (defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)) && \
defined(__GNUC__) && __GNUC__ >= 4 && !defined(__INTEL_COMPILER)
#define MPD_PRAGMA(x) _Pragma(x)
#define MPD_HIDE_SYMBOLS_START "GCC visibility push(hidden)"
#define MPD_HIDE_SYMBOLS_END "GCC visibility pop"
#else
#define MPD_PRAGMA(x)
#define MPD_HIDE_SYMBOLS_START
#define MPD_HIDE_SYMBOLS_END
#endif
#if defined(_MSC_VER)
#include "vccompat.h"
#define EXTINLINE extern inline
#else
#define EXTINLINE
#endif
/* This header file is internal for the purpose of building _decimal.so.
* All symbols should have local scope in the DSO. */
MPD_PRAGMA(MPD_HIDE_SYMBOLS_START)
#if !defined(LEGACY_COMPILER)
#if !defined(UINT64_MAX)
/* The following #error is just a warning. If the compiler indeed does
* not have uint64_t, it is perfectly safe to comment out the #error. */
#error "Warning: Compiler without uint64_t. Comment out this line."
#define LEGACY_COMPILER
#endif
#endif
/******************************************************************************/
/* Version */
/******************************************************************************/
#define MPD_MAJOR_VERSION 2
#define MPD_MINOR_VERSION 5
#define MPD_MICRO_VERSION 0
#define MPD_VERSION "2.5.0"
#define MPD_VERSION_HEX ((MPD_MAJOR_VERSION << 24) | \
(MPD_MINOR_VERSION << 16) | \
(MPD_MICRO_VERSION << 8))
const char *mpd_version(void);
/******************************************************************************/
/* Configuration */
/******************************************************************************/
#if defined(UNIVERSAL)
#if defined(CONFIG_64) || defined(CONFIG_32)
#error "cannot use CONFIG_64 or CONFIG_32 with UNIVERSAL."
#endif
#if defined(__ppc__)
#define CONFIG_32
#define ANSI
#elif defined(__ppc64__)
#define CONFIG_64
#define ANSI
#elif defined(__i386__)
#define CONFIG_32
#define ANSI
#elif defined(__x86_64__)
#define CONFIG_64
#define ASM
#else
#error "unknown architecture for universal build."
#endif
#endif
/* BEGIN CONFIG_64 */
#if defined(CONFIG_64)
/* types for modular and base arithmetic */
#define MPD_UINT_MAX UINT64_MAX
#define MPD_BITS_PER_UINT 64
typedef uint64_t mpd_uint_t; /* unsigned mod type */
#define MPD_SIZE_MAX SIZE_MAX
typedef size_t mpd_size_t; /* unsigned size type */
/* type for exp, digits, len, prec */
#define MPD_SSIZE_MAX INT64_MAX
#define MPD_SSIZE_MIN INT64_MIN
typedef int64_t mpd_ssize_t;
#define _mpd_strtossize strtoll
/* decimal arithmetic */
#define MPD_RADIX 10000000000000000000ULL /* 10**19 */
#define MPD_RDIGITS 19
#define MPD_MAX_POW10 19
#define MPD_EXPDIGITS 19 /* MPD_EXPDIGITS <= MPD_RDIGITS+1 */
#define MPD_MAXTRANSFORM_2N 4294967296ULL /* 2**32 */
#define MPD_MAX_PREC 999999999999999999LL
#define MPD_MAX_PREC_LOG2 64
#define MPD_ELIMIT 1000000000000000000LL
#define MPD_MAX_EMAX 999999999999999999LL /* ELIMIT-1 */
#define MPD_MIN_EMIN (-999999999999999999LL) /* -EMAX */
#define MPD_MIN_ETINY (MPD_MIN_EMIN-(MPD_MAX_PREC-1))
#define MPD_EXP_INF 2000000000000000001LL
#define MPD_EXP_CLAMP (-4000000000000000001LL)
#define MPD_MAXIMPORT 105263157894736842L /* ceil((2*MPD_MAX_PREC)/MPD_RDIGITS) */
/* conversion specifiers */
#define PRI_mpd_uint_t PRIu64
#define PRI_mpd_ssize_t PRIi64
/* END CONFIG_64 */
/* BEGIN CONFIG_32 */
#elif defined(CONFIG_32)
/* types for modular and base arithmetic */
#define MPD_UINT_MAX UINT32_MAX
#define MPD_BITS_PER_UINT 32
typedef uint32_t mpd_uint_t; /* unsigned mod type */
#ifndef LEGACY_COMPILER
#define MPD_UUINT_MAX UINT64_MAX
typedef uint64_t mpd_uuint_t; /* double width unsigned mod type */
#endif
#define MPD_SIZE_MAX SIZE_MAX
typedef size_t mpd_size_t; /* unsigned size type */
/* type for dec->len, dec->exp, ctx->prec */
#define MPD_SSIZE_MAX INT32_MAX
#define MPD_SSIZE_MIN INT32_MIN
typedef int32_t mpd_ssize_t;
#define _mpd_strtossize strtol
/* decimal arithmetic */
#define MPD_RADIX 1000000000UL /* 10**9 */
#define MPD_RDIGITS 9
#define MPD_MAX_POW10 9
#define MPD_EXPDIGITS 10 /* MPD_EXPDIGITS <= MPD_RDIGITS+1 */
#define MPD_MAXTRANSFORM_2N 33554432UL /* 2**25 */
#define MPD_MAX_PREC 425000000L
#define MPD_MAX_PREC_LOG2 32
#define MPD_ELIMIT 425000001L
#define MPD_MAX_EMAX 425000000L /* ELIMIT-1 */
#define MPD_MIN_EMIN (-425000000L) /* -EMAX */
#define MPD_MIN_ETINY (MPD_MIN_EMIN-(MPD_MAX_PREC-1))
#define MPD_EXP_INF 1000000001L /* allows for emax=999999999 in the tests */
#define MPD_EXP_CLAMP (-2000000001L) /* allows for emin=-999999999 in the tests */
#define MPD_MAXIMPORT 94444445L /* ceil((2*MPD_MAX_PREC)/MPD_RDIGITS) */
/* conversion specifiers */
#define PRI_mpd_uint_t PRIu32
#define PRI_mpd_ssize_t PRIi32
/* END CONFIG_32 */
#else
#error "define CONFIG_64 or CONFIG_32"
#endif
/* END CONFIG */
#if MPD_SIZE_MAX != MPD_UINT_MAX
#error "unsupported platform: need mpd_size_t == mpd_uint_t"
#endif
/******************************************************************************/
/* Context */
/******************************************************************************/
enum {
MPD_ROUND_UP, /* round away from 0 */
MPD_ROUND_DOWN, /* round toward 0 (truncate) */
MPD_ROUND_CEILING, /* round toward +infinity */
MPD_ROUND_FLOOR, /* round toward -infinity */
MPD_ROUND_HALF_UP, /* 0.5 is rounded up */
MPD_ROUND_HALF_DOWN, /* 0.5 is rounded down */
MPD_ROUND_HALF_EVEN, /* 0.5 is rounded to even */
MPD_ROUND_05UP, /* round zero or five away from 0 */
MPD_ROUND_TRUNC, /* truncate, but set infinity */
MPD_ROUND_GUARD
};
enum { MPD_CLAMP_DEFAULT, MPD_CLAMP_IEEE_754, MPD_CLAMP_GUARD };
extern const char *mpd_round_string[MPD_ROUND_GUARD];
extern const char *mpd_clamp_string[MPD_CLAMP_GUARD];
typedef struct mpd_context_t {
mpd_ssize_t prec; /* precision */
mpd_ssize_t emax; /* max positive exp */
mpd_ssize_t emin; /* min negative exp */
uint32_t traps; /* status events that should be trapped */
uint32_t status; /* status flags */
uint32_t newtrap; /* set by mpd_addstatus_raise() */
int round; /* rounding mode */
int clamp; /* clamp mode */
int allcr; /* all functions correctly rounded */
} mpd_context_t;
/* Status flags */
#define MPD_Clamped 0x00000001U
#define MPD_Conversion_syntax 0x00000002U
#define MPD_Division_by_zero 0x00000004U
#define MPD_Division_impossible 0x00000008U
#define MPD_Division_undefined 0x00000010U
#define MPD_Fpu_error 0x00000020U
#define MPD_Inexact 0x00000040U
#define MPD_Invalid_context 0x00000080U
#define MPD_Invalid_operation 0x00000100U
#define MPD_Malloc_error 0x00000200U
#define MPD_Not_implemented 0x00000400U
#define MPD_Overflow 0x00000800U
#define MPD_Rounded 0x00001000U
#define MPD_Subnormal 0x00002000U
#define MPD_Underflow 0x00004000U
#define MPD_Max_status (0x00008000U-1U)
/* Conditions that result in an IEEE 754 exception */
#define MPD_IEEE_Invalid_operation (MPD_Conversion_syntax | \
MPD_Division_impossible | \
MPD_Division_undefined | \
MPD_Fpu_error | \
MPD_Invalid_context | \
MPD_Invalid_operation | \
MPD_Malloc_error) \
/* Errors that require the result of an operation to be set to NaN */
#define MPD_Errors (MPD_IEEE_Invalid_operation | \
MPD_Division_by_zero)
/* Default traps */
#define MPD_Traps (MPD_IEEE_Invalid_operation | \
MPD_Division_by_zero | \
MPD_Overflow | \
MPD_Underflow)
/* Official name */
#define MPD_Insufficient_storage MPD_Malloc_error
/* IEEE 754 interchange format contexts */
#define MPD_IEEE_CONTEXT_MAX_BITS 512 /* 16*(log2(MPD_MAX_EMAX / 3)-3) */
#define MPD_DECIMAL32 32
#define MPD_DECIMAL64 64
#define MPD_DECIMAL128 128
#define MPD_MINALLOC_MIN 2
#define MPD_MINALLOC_MAX 64
extern mpd_ssize_t MPD_MINALLOC;
extern void (* mpd_traphandler)(mpd_context_t *);
void mpd_dflt_traphandler(mpd_context_t *);
void mpd_setminalloc(mpd_ssize_t n);
void mpd_init(mpd_context_t *ctx, mpd_ssize_t prec);
void mpd_maxcontext(mpd_context_t *ctx);
void mpd_defaultcontext(mpd_context_t *ctx);
void mpd_basiccontext(mpd_context_t *ctx);
int mpd_ieee_context(mpd_context_t *ctx, int bits);
mpd_ssize_t mpd_getprec(const mpd_context_t *ctx);
mpd_ssize_t mpd_getemax(const mpd_context_t *ctx);
mpd_ssize_t mpd_getemin(const mpd_context_t *ctx);
int mpd_getround(const mpd_context_t *ctx);
uint32_t mpd_gettraps(const mpd_context_t *ctx);
uint32_t mpd_getstatus(const mpd_context_t *ctx);
int mpd_getclamp(const mpd_context_t *ctx);
int mpd_getcr(const mpd_context_t *ctx);
int mpd_qsetprec(mpd_context_t *ctx, mpd_ssize_t prec);
int mpd_qsetemax(mpd_context_t *ctx, mpd_ssize_t emax);
int mpd_qsetemin(mpd_context_t *ctx, mpd_ssize_t emin);
int mpd_qsetround(mpd_context_t *ctx, int newround);
int mpd_qsettraps(mpd_context_t *ctx, uint32_t flags);
int mpd_qsetstatus(mpd_context_t *ctx, uint32_t flags);
int mpd_qsetclamp(mpd_context_t *ctx, int c);
int mpd_qsetcr(mpd_context_t *ctx, int c);
void mpd_addstatus_raise(mpd_context_t *ctx, uint32_t flags);
/******************************************************************************/
/* Decimal Arithmetic */
/******************************************************************************/
/* mpd_t flags */
#define MPD_POS ((uint8_t)0)
#define MPD_NEG ((uint8_t)1)
#define MPD_INF ((uint8_t)2)
#define MPD_NAN ((uint8_t)4)
#define MPD_SNAN ((uint8_t)8)
#define MPD_SPECIAL (MPD_INF|MPD_NAN|MPD_SNAN)
#define MPD_STATIC ((uint8_t)16)
#define MPD_STATIC_DATA ((uint8_t)32)
#define MPD_SHARED_DATA ((uint8_t)64)
#define MPD_CONST_DATA ((uint8_t)128)
#define MPD_DATAFLAGS (MPD_STATIC_DATA|MPD_SHARED_DATA|MPD_CONST_DATA)
/* mpd_t */
typedef struct mpd_t {
uint8_t flags;
mpd_ssize_t exp;
mpd_ssize_t digits;
mpd_ssize_t len;
mpd_ssize_t alloc;
mpd_uint_t *data;
} mpd_t;
typedef unsigned char uchar;
/******************************************************************************/
/* Quiet, thread-safe functions */
/******************************************************************************/
/* format specification */
typedef struct mpd_spec_t {
mpd_ssize_t min_width; /* minimum field width */
mpd_ssize_t prec; /* fraction digits or significant digits */
char type; /* conversion specifier */
char align; /* alignment */
char sign; /* sign printing/alignment */
char fill[5]; /* fill character */
const char *dot; /* decimal point */
const char *sep; /* thousands separator */
const char *grouping; /* grouping of digits */
} mpd_spec_t;
/* output to a string */
char *mpd_to_sci(const mpd_t *dec, int fmt);
char *mpd_to_eng(const mpd_t *dec, int fmt);
mpd_ssize_t mpd_to_sci_size(char **res, const mpd_t *dec, int fmt);
mpd_ssize_t mpd_to_eng_size(char **res, const mpd_t *dec, int fmt);
int mpd_validate_lconv(mpd_spec_t *spec);
int mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt, int caps);
char *mpd_qformat_spec(const mpd_t *dec, const mpd_spec_t *spec, const mpd_context_t *ctx, uint32_t *status);
char *mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx, uint32_t *status);
#define MPD_NUM_FLAGS 15
#define MPD_MAX_FLAG_STRING 208
#define MPD_MAX_FLAG_LIST (MPD_MAX_FLAG_STRING+18)
#define MPD_MAX_SIGNAL_LIST 121
int mpd_snprint_flags(char *dest, int nmemb, uint32_t flags);
int mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[]);
int mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[]);
/* output to a file */
void mpd_fprint(FILE *file, const mpd_t *dec);
void mpd_print(const mpd_t *dec);
/* assignment from a string */
void mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx, uint32_t *status);
void mpd_qset_string_exact(mpd_t *dec, const char *s, uint32_t *status);
/* set to NaN with error flags */
void mpd_seterror(mpd_t *result, uint32_t flags, uint32_t *status);
/* set a special with sign and type */
void mpd_setspecial(mpd_t *dec, uint8_t sign, uint8_t type);
/* set coefficient to zero or all nines */
void mpd_zerocoeff(mpd_t *result);
void mpd_qmaxcoeff(mpd_t *result, const mpd_context_t *ctx, uint32_t *status);
/* quietly assign a C integer type to an mpd_t */
void mpd_qset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status);
#ifndef LEGACY_COMPILER
void mpd_qset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qset_i64_exact(mpd_t *result, int64_t a, uint32_t *status);
void mpd_qset_u64_exact(mpd_t *result, uint64_t a, uint32_t *status);
#endif
/* quietly assign a C integer type to an mpd_t with a static coefficient */
void mpd_qsset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status);
/* quietly get a C integer type from an mpd_t */
mpd_ssize_t mpd_qget_ssize(const mpd_t *dec, uint32_t *status);
mpd_uint_t mpd_qget_uint(const mpd_t *dec, uint32_t *status);
mpd_uint_t mpd_qabs_uint(const mpd_t *dec, uint32_t *status);
int32_t mpd_qget_i32(const mpd_t *dec, uint32_t *status);
uint32_t mpd_qget_u32(const mpd_t *dec, uint32_t *status);
#ifndef LEGACY_COMPILER
int64_t mpd_qget_i64(const mpd_t *dec, uint32_t *status);
uint64_t mpd_qget_u64(const mpd_t *dec, uint32_t *status);
#endif
/* quiet functions */
int mpd_qcheck_nan(mpd_t *nanresult, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
int mpd_qcheck_nans(mpd_t *nanresult, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qfinalize(mpd_t *result, const mpd_context_t *ctx, uint32_t *status);
const char *mpd_class(const mpd_t *a, const mpd_context_t *ctx);
int mpd_qcopy(mpd_t *result, const mpd_t *a, uint32_t *status);
int mpd_qcopy_cxx(mpd_t *result, const mpd_t *a);
mpd_t *mpd_qncopy(const mpd_t *a);
int mpd_qcopy_abs(mpd_t *result, const mpd_t *a, uint32_t *status);
int mpd_qcopy_negate(mpd_t *result, const mpd_t *a, uint32_t *status);
int mpd_qcopy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status);
void mpd_qand(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qinvert(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qlogb(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qscaleb(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qxor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
int mpd_same_quantum(const mpd_t *a, const mpd_t *b);
void mpd_qrotate(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
int mpd_qshiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status);
mpd_uint_t mpd_qshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status);
mpd_uint_t mpd_qshiftr_inplace(mpd_t *result, mpd_ssize_t n);
void mpd_qshift(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qshiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, const mpd_context_t *ctx, uint32_t *status);
int mpd_qcmp(const mpd_t *a, const mpd_t *b, uint32_t *status);
int mpd_qcompare(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
int mpd_qcompare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
int mpd_cmp_total(const mpd_t *a, const mpd_t *b);
int mpd_cmp_total_mag(const mpd_t *a, const mpd_t *b);
int mpd_compare_total(mpd_t *result, const mpd_t *a, const mpd_t *b);
int mpd_compare_total_mag(mpd_t *result, const mpd_t *a, const mpd_t *b);
void mpd_qround_to_intx(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qround_to_int(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qtrunc(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qfloor(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qceil(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qabs(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmax(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmax_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmin(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmin_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qminus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qplus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qnext_minus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qnext_plus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qnext_toward(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qquantize(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status);
void mpd_qrescale_fmt(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status);
void mpd_qreduce(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qadd_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qadd_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qadd_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qadd_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsub_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsub_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmul_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmul_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qfma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdiv(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdiv_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdiv_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdiv_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdiv_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdivint(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qrem(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qrem_near(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qpow(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_context_t *ctx, uint32_t *status);
void mpd_qpowmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod, const mpd_context_t *ctx, uint32_t *status);
void mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qln10(mpd_t *result, mpd_ssize_t prec, uint32_t *status);
void mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
#ifndef LEGACY_COMPILER
void mpd_qadd_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qadd_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsub_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsub_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmul_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qmul_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdiv_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
void mpd_qdiv_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
#endif
size_t mpd_sizeinbase(const mpd_t *a, uint32_t base);
void mpd_qimport_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen,
uint8_t srcsign, uint32_t srcbase,
const mpd_context_t *ctx, uint32_t *status);
void mpd_qimport_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen,
uint8_t srcsign, uint32_t srcbase,
const mpd_context_t *ctx, uint32_t *status);
size_t mpd_qexport_u16(uint16_t **rdata, size_t rlen, uint32_t base,
const mpd_t *src, uint32_t *status);
size_t mpd_qexport_u32(uint32_t **rdata, size_t rlen, uint32_t base,
const mpd_t *src, uint32_t *status);
/******************************************************************************/
/* Signalling functions */
/******************************************************************************/
char *mpd_format(const mpd_t *dec, const char *fmt, mpd_context_t *ctx);
void mpd_import_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t base, mpd_context_t *ctx);
void mpd_import_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t base, mpd_context_t *ctx);
size_t mpd_export_u16(uint16_t **rdata, size_t rlen, uint32_t base, const mpd_t *src, mpd_context_t *ctx);
size_t mpd_export_u32(uint32_t **rdata, size_t rlen, uint32_t base, const mpd_t *src, mpd_context_t *ctx);
void mpd_finalize(mpd_t *result, mpd_context_t *ctx);
int mpd_check_nan(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
int mpd_check_nans(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_set_string(mpd_t *result, const char *s, mpd_context_t *ctx);
void mpd_maxcoeff(mpd_t *result, mpd_context_t *ctx);
void mpd_sset_ssize(mpd_t *result, mpd_ssize_t a, mpd_context_t *ctx);
void mpd_sset_i32(mpd_t *result, int32_t a, mpd_context_t *ctx);
void mpd_sset_uint(mpd_t *result, mpd_uint_t a, mpd_context_t *ctx);
void mpd_sset_u32(mpd_t *result, uint32_t a, mpd_context_t *ctx);
void mpd_set_ssize(mpd_t *result, mpd_ssize_t a, mpd_context_t *ctx);
void mpd_set_i32(mpd_t *result, int32_t a, mpd_context_t *ctx);
void mpd_set_uint(mpd_t *result, mpd_uint_t a, mpd_context_t *ctx);
void mpd_set_u32(mpd_t *result, uint32_t a, mpd_context_t *ctx);
#ifndef LEGACY_COMPILER
void mpd_set_i64(mpd_t *result, int64_t a, mpd_context_t *ctx);
void mpd_set_u64(mpd_t *result, uint64_t a, mpd_context_t *ctx);
#endif
mpd_ssize_t mpd_get_ssize(const mpd_t *a, mpd_context_t *ctx);
mpd_uint_t mpd_get_uint(const mpd_t *a, mpd_context_t *ctx);
mpd_uint_t mpd_abs_uint(const mpd_t *a, mpd_context_t *ctx);
int32_t mpd_get_i32(const mpd_t *a, mpd_context_t *ctx);
uint32_t mpd_get_u32(const mpd_t *a, mpd_context_t *ctx);
#ifndef LEGACY_COMPILER
int64_t mpd_get_i64(const mpd_t *a, mpd_context_t *ctx);
uint64_t mpd_get_u64(const mpd_t *a, mpd_context_t *ctx);
#endif
void mpd_and(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_copy(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_canonical(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_copy_abs(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_copy_negate(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_copy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_invert(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_logb(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_or(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_rotate(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_scaleb(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_shiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, mpd_context_t *ctx);
mpd_uint_t mpd_shiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, mpd_context_t *ctx);
void mpd_shiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, mpd_context_t *ctx);
void mpd_shift(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_xor(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_abs(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
int mpd_cmp(const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
int mpd_compare(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
int mpd_compare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_add(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_add_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx);
void mpd_add_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx);
void mpd_add_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx);
void mpd_add_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx);
void mpd_sub(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_sub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx);
void mpd_sub_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx);
void mpd_sub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx);
void mpd_sub_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx);
void mpd_div(mpd_t *q, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_div_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx);
void mpd_div_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx);
void mpd_div_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx);
void mpd_div_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx);
void mpd_divmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_divint(mpd_t *q, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_exp(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_fma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, mpd_context_t *ctx);
void mpd_ln(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_log10(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_max(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_max_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_min(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_min_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_minus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_mul(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_mul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, mpd_context_t *ctx);
void mpd_mul_i32(mpd_t *result, const mpd_t *a, int32_t b, mpd_context_t *ctx);
void mpd_mul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, mpd_context_t *ctx);
void mpd_mul_u32(mpd_t *result, const mpd_t *a, uint32_t b, mpd_context_t *ctx);
void mpd_next_minus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_next_plus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_next_toward(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_plus(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_pow(mpd_t *result, const mpd_t *base, const mpd_t *exp, mpd_context_t *ctx);
void mpd_powmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod, mpd_context_t *ctx);
void mpd_quantize(mpd_t *result, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_rescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, mpd_context_t *ctx);
void mpd_reduce(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_rem(mpd_t *r, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_rem_near(mpd_t *r, const mpd_t *a, const mpd_t *b, mpd_context_t *ctx);
void mpd_round_to_intx(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_round_to_int(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_trunc(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_floor(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_ceil(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_sqrt(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
void mpd_invroot(mpd_t *result, const mpd_t *a, mpd_context_t *ctx);
#ifndef LEGACY_COMPILER
void mpd_add_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx);
void mpd_add_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx);
void mpd_sub_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx);
void mpd_sub_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx);
void mpd_div_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx);
void mpd_div_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx);
void mpd_mul_i64(mpd_t *result, const mpd_t *a, int64_t b, mpd_context_t *ctx);
void mpd_mul_u64(mpd_t *result, const mpd_t *a, uint64_t b, mpd_context_t *ctx);
#endif
/******************************************************************************/
/* Configuration specific */
/******************************************************************************/
#ifdef CONFIG_64
void mpd_qsset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_qsset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status);
void mpd_sset_i64(mpd_t *result, int64_t a, mpd_context_t *ctx);
void mpd_sset_u64(mpd_t *result, uint64_t a, mpd_context_t *ctx);
#endif
/******************************************************************************/
/* Get attributes of a decimal */
/******************************************************************************/
EXTINLINE mpd_ssize_t mpd_adjexp(const mpd_t *dec);
EXTINLINE mpd_ssize_t mpd_etiny(const mpd_context_t *ctx);
EXTINLINE mpd_ssize_t mpd_etop(const mpd_context_t *ctx);
EXTINLINE mpd_uint_t mpd_msword(const mpd_t *dec);
EXTINLINE int mpd_word_digits(mpd_uint_t word);
/* most significant digit of a word */
EXTINLINE mpd_uint_t mpd_msd(mpd_uint_t word);
/* least significant digit of a word */
EXTINLINE mpd_uint_t mpd_lsd(mpd_uint_t word);
/* coefficient size needed to store 'digits' */
EXTINLINE mpd_ssize_t mpd_digits_to_size(mpd_ssize_t digits);
/* number of digits in the exponent, undefined for MPD_SSIZE_MIN */
EXTINLINE int mpd_exp_digits(mpd_ssize_t exp);
EXTINLINE int mpd_iscanonical(const mpd_t *dec);
EXTINLINE int mpd_isfinite(const mpd_t *dec);
EXTINLINE int mpd_isinfinite(const mpd_t *dec);
EXTINLINE int mpd_isinteger(const mpd_t *dec);
EXTINLINE int mpd_isnan(const mpd_t *dec);
EXTINLINE int mpd_isnegative(const mpd_t *dec);
EXTINLINE int mpd_ispositive(const mpd_t *dec);
EXTINLINE int mpd_isqnan(const mpd_t *dec);
EXTINLINE int mpd_issigned(const mpd_t *dec);
EXTINLINE int mpd_issnan(const mpd_t *dec);
EXTINLINE int mpd_isspecial(const mpd_t *dec);
EXTINLINE int mpd_iszero(const mpd_t *dec);
/* undefined for special numbers */
EXTINLINE int mpd_iszerocoeff(const mpd_t *dec);
EXTINLINE int mpd_isnormal(const mpd_t *dec, const mpd_context_t *ctx);
EXTINLINE int mpd_issubnormal(const mpd_t *dec, const mpd_context_t *ctx);
/* odd word */
EXTINLINE int mpd_isoddword(mpd_uint_t word);
/* odd coefficient */
EXTINLINE int mpd_isoddcoeff(const mpd_t *dec);
/* odd decimal, only defined for integers */
int mpd_isodd(const mpd_t *dec);
/* even decimal, only defined for integers */
int mpd_iseven(const mpd_t *dec);
/* 0 if dec is positive, 1 if dec is negative */
EXTINLINE uint8_t mpd_sign(const mpd_t *dec);
/* 1 if dec is positive, -1 if dec is negative */
EXTINLINE int mpd_arith_sign(const mpd_t *dec);
EXTINLINE long mpd_radix(void);
EXTINLINE int mpd_isdynamic(const mpd_t *dec);
EXTINLINE int mpd_isstatic(const mpd_t *dec);
EXTINLINE int mpd_isdynamic_data(const mpd_t *dec);
EXTINLINE int mpd_isstatic_data(const mpd_t *dec);
EXTINLINE int mpd_isshared_data(const mpd_t *dec);
EXTINLINE int mpd_isconst_data(const mpd_t *dec);
EXTINLINE mpd_ssize_t mpd_trail_zeros(const mpd_t *dec);
/******************************************************************************/
/* Set attributes of a decimal */
/******************************************************************************/
/* set number of decimal digits in the coefficient */
EXTINLINE void mpd_setdigits(mpd_t *result);
EXTINLINE void mpd_set_sign(mpd_t *result, uint8_t sign);
/* copy sign from another decimal */
EXTINLINE void mpd_signcpy(mpd_t *result, const mpd_t *a);
EXTINLINE void mpd_set_infinity(mpd_t *result);
EXTINLINE void mpd_set_qnan(mpd_t *result);
EXTINLINE void mpd_set_snan(mpd_t *result);
EXTINLINE void mpd_set_negative(mpd_t *result);
EXTINLINE void mpd_set_positive(mpd_t *result);
EXTINLINE void mpd_set_dynamic(mpd_t *result);
EXTINLINE void mpd_set_static(mpd_t *result);
EXTINLINE void mpd_set_dynamic_data(mpd_t *result);
EXTINLINE void mpd_set_static_data(mpd_t *result);
EXTINLINE void mpd_set_shared_data(mpd_t *result);
EXTINLINE void mpd_set_const_data(mpd_t *result);
EXTINLINE void mpd_clear_flags(mpd_t *result);
EXTINLINE void mpd_set_flags(mpd_t *result, uint8_t flags);
EXTINLINE void mpd_copy_flags(mpd_t *result, const mpd_t *a);
/******************************************************************************/
/* Error Macros */
/******************************************************************************/
#define mpd_err_fatal(...) \
do {fprintf(stderr, "%s:%d: error: ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); \
abort(); \
} while (0)
#define mpd_err_warn(...) \
do {fprintf(stderr, "%s:%d: warning: ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); \
} while (0)
/******************************************************************************/
/* Memory handling */
/******************************************************************************/
extern void *(* mpd_mallocfunc)(size_t size);
extern void *(* mpd_callocfunc)(size_t nmemb, size_t size);
extern void *(* mpd_reallocfunc)(void *ptr, size_t size);
extern void (* mpd_free)(void *ptr);
void *mpd_callocfunc_em(size_t nmemb, size_t size);
void *mpd_alloc(mpd_size_t nmemb, mpd_size_t size);
void *mpd_calloc(mpd_size_t nmemb, mpd_size_t size);
void *mpd_realloc(void *ptr, mpd_size_t nmemb, mpd_size_t size, uint8_t *err);
void *mpd_sh_alloc(mpd_size_t struct_size, mpd_size_t nmemb, mpd_size_t size);
mpd_t *mpd_qnew(void);
mpd_t *mpd_new(mpd_context_t *ctx);
mpd_t *mpd_qnew_size(mpd_ssize_t size);
EXTINLINE void mpd_del(mpd_t *dec);
EXTINLINE void mpd_uint_zero(mpd_uint_t *dest, mpd_size_t len);
EXTINLINE int mpd_qresize(mpd_t *result, mpd_ssize_t size, uint32_t *status);
EXTINLINE int mpd_qresize_zero(mpd_t *result, mpd_ssize_t size, uint32_t *status);
EXTINLINE void mpd_minalloc(mpd_t *result);
int mpd_resize(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx);
int mpd_resize_zero(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx);
MPD_PRAGMA(MPD_HIDE_SYMBOLS_END) /* restore previous scope rules */
#ifdef __cplusplus
} /* END extern "C" */
#endif
#endif /* LIBMPDEC_MPDECIMAL_H_ */
| [
"kay.hayen@gmail.com"
] | kay.hayen@gmail.com |
c2a8af785003fd39daa334200a804f4776c4286f | b0ed979f05c8c1abae214753790602acb3ce1f97 | /CSES/Road Construction.cpp | ecc159c6f9d3291d01f270bfa56c53cfb606ad94 | [] | no_license | r-d-s-l-w/competitive-programming | 1304d591b9c28390fcf2ceaa5f86aa8274efb41c | 21322d69ceed314135aeb6bbf3ec91ee70bc4f5b | refs/heads/master | 2022-11-24T10:07:06.720420 | 2020-08-06T11:25:58 | 2020-08-06T11:25:58 | 238,414,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,462 | cpp | /// Radoslaw Mysliwiec 2020
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define F first
#define S second
#define PB push_back
#define ALL(x) (x).begin(),(x).end()
#define endl '\n'
using ll = long long;
using ld = long double;
using vi = vector<int>;
using vll = vector<ll>;
using pi = pair<int,int>;
using pll = pair<ll,ll>;
using matrix = vector<vi>;
using ordered_set = tree<pi, null_type, less<pi>, rb_tree_tag, tree_order_statistics_node_update>;\
vi parent, indeks;
int n, m, ctr, res = 1;
void build_set(int x){
parent[x] = x;
indeks[x] = 1;
}
int find_set(int x){
if (x == parent[x])
return x;
return parent[x] = find_set(parent[x]);
}
void union_sets(int a, int b){
a = find_set(a);
b = find_set(b);
if (a != b){
if (indeks[a] < indeks[b])
swap(a, b);
parent[b] = a;
indeks[a] += indeks[b];
res = max(res, indeks[a]);
}
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m;
parent.resize(n+1);
indeks.resize(n+1);
for (int i=1; i<=n; ++i)
build_set(i);
for (int i=0; i<m; ++i){
int a, b;
cin >> a >> b;
if (find_set(a) != find_set(b)){
--n;
union_sets(a, b);
}
cout << n << ' ' << res << endl;
}
}
| [
"noreply@github.com"
] | r-d-s-l-w.noreply@github.com |
6389084c022e7b41a83f27e727628624d197003d | c1d8cefebd8f85fe9a70ae18d6726e8e42a6fe3a | /07_学习笔记/HPLSP/csdn_select实现的聊天服务器/MessageBuffer.h | 5b4c5a9dba15b883997818575373f2f2d5c33a7b | [] | no_license | leomaokai/MyCpp | 7df0b4097561774c9050e9eed27134202b011c3a | e81b0ba50c7de046ee63af47accd2897b5e289ee | refs/heads/master | 2023-02-19T11:14:58.697566 | 2021-01-22T16:50:13 | 2021-01-22T16:50:13 | 289,039,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 826 | h | //MessageBuffer.h
#ifndef _MESSAGE_BUF_INCLUDE_
#define _MESSAGE_BUF_INCLUDE_
#include <pthread.h>
#define MESSAGE_COUNT 16
#define MESSAGE_LENGTH 2048
class MessageBuffer{
private:
pthread_mutex_t mutex;//访问缓冲的互斥量
pthread_cond_t condition;//访问缓冲区的条件变量
//消息缓冲区,循环队列
char buf[MESSAGE_COUNT][MESSAGE_LENGTH];
int rear; //循环队列的队尾
int front; //循环队列的队首
public:
bool toStop;
//构造函数
MessageBuffer();
//析构函数
virtual ~MessageBuffer();
//将消息放入消息缓冲区,当缓冲区满时阻塞,toStop=true时返回-1
int PutMessage(const char *message);
//从消息缓冲区中获得消息,当缓冲区空时阻塞,toStop=true时返回-1
int GetMessage(char *mbuf, int buflen);
};
#endif
| [
"leomaokai@163.com"
] | leomaokai@163.com |
d8dbd33c5b6bdc600e7e0664e1d9f24b47ddb43d | 15e22c9e2989e1ebe5bff262ca21016d75bb715a | /external/asio/src/examples/cpp03/socks4/sync_client.cpp | fceaf5072930cb76229856f3f3650a9951641f3a | [
"BSD-3-Clause"
] | permissive | iridinite/wirefox | 83ba9af447e3eec7d7639240e8d643619ad2e751 | 0897fcf5f9167ce41e75a3a5074d4b701cc0a203 | refs/heads/master | 2020-05-07T18:36:14.842619 | 2019-05-29T14:52:55 | 2019-05-29T14:52:55 | 180,773,327 | 5 | 0 | BSD-3-Clause | 2019-05-06T11:04:28 | 2019-04-11T10:57:37 | C++ | UTF-8 | C++ | false | false | 2,896 | cpp | //
// sync_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <iomanip>
#include <ostream>
#include <string>
#include <asio.hpp>
#include <boost/array.hpp>
#include "socks4.hpp"
using asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 4)
{
std::cout << "Usage: sync_client <socks4server> <socks4port> <user>\n";
std::cout << "Examples:\n";
std::cout << " sync_client 127.0.0.1 1080 chris\n";
std::cout << " sync_client localhost socks chris\n";
return 1;
}
asio::io_context io_context;
// Get a list of endpoints corresponding to the SOCKS 4 server name.
tcp::resolver resolver(io_context);
tcp::resolver::results_type endpoints = resolver.resolve(argv[1], argv[2]);
// Try each endpoint until we successfully establish a connection to the
// SOCKS 4 server.
tcp::socket socket(io_context);
asio::connect(socket, endpoints);
// Get an endpoint for the Boost website. This will be passed to the SOCKS
// 4 server. Explicitly specify IPv4 since SOCKS 4 does not support IPv6.
tcp::endpoint http_endpoint =
*resolver.resolve(tcp::v4(), "www.boost.org", "http").begin();
// Send the request to the SOCKS 4 server.
socks4::request socks_request(
socks4::request::connect, http_endpoint, argv[3]);
asio::write(socket, socks_request.buffers());
// Receive a response from the SOCKS 4 server.
socks4::reply socks_reply;
asio::read(socket, socks_reply.buffers());
// Check whether we successfully negotiated with the SOCKS 4 server.
if (!socks_reply.success())
{
std::cout << "Connection failed.\n";
std::cout << "status = 0x" << std::hex << socks_reply.status();
return 1;
}
// Form the HTTP request. We specify the "Connection: close" header so that
// the server will close the socket after transmitting the response. This
// will allow us to treat all data up until the EOF as the response.
std::string request =
"GET / HTTP/1.0\r\n"
"Host: www.boost.org\r\n"
"Accept: */*\r\n"
"Connection: close\r\n\r\n";
// Send the HTTP request.
asio::write(socket, asio::buffer(request));
// Read until EOF, writing data to output as we go.
boost::array<char, 512> response;
asio::error_code error;
while (std::size_t s = socket.read_some(
asio::buffer(response), error))
std::cout.write(response.data(), s);
if (error != asio::error::eof)
throw asio::system_error(error);
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return 0;
}
| [
"codingcuddlewolf@gmail.com"
] | codingcuddlewolf@gmail.com |
6f04fd3c54ef23648cc7760a798534d3cc65e074 | 2770c087a6652df95f1963b74d4911e0659105de | /RiskGameProjectLocal/Driver/Reinforcement.h | 8c8d218eb77bdb78731b387d45dac3780ed9ec73 | [] | no_license | CaptnJunks/RiskGameC- | 61917548103f3eb6ef581cc61e55b27fdf78dc14 | 76aaa5445edd82d86f9c3fd8eb9198080bde0fa6 | refs/heads/master | 2021-01-17T23:00:23.711922 | 2015-04-07T23:04:30 | 2015-04-07T23:04:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | #include <math.h>
#include "../Cards/Card.h"
#include "../Player/Player.h"
#include "../Map/Map.h"
class Reinforcement
{
public:
Reinforcement();
Reinforcement(Player *p, int *cardBonusCt);
void checkCards();
void exchangeSet();
void territoryBonus();
void continentBonus();
void reinforce();
void chooseTerritory(std::string s);
int* updateCardBonus();
private:
Map *map;
Player *mCurrent;
/* int cArtillery;
int cCavalry;
int cInfantry; */
int numOfR;
int *cardBonusCt;
bool useCard;
};
| [
"mateus.m.luna@gmail.com"
] | mateus.m.luna@gmail.com |
9a079a2af486341781eae682690ecc252c53e189 | d96220913a02117754c0e5b6e89b62f63a0a36d1 | /ejercicio 3.cpp | be22ae57f1f9941be0875264954ac6ddedb68a11 | [] | no_license | Sebasdev20/FP_Laboratorio_05_-00373119- | b8d67b20de0042b3549096271544d8b3cd10e922 | 2e0bb458576b6940eeb2723f1fa17a7617cdd8e8 | refs/heads/master | 2022-02-23T00:37:21.014028 | 2019-10-06T01:02:12 | 2019-10-06T01:02:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | cpp | #include<iostream>
using namespace std;
int main(){
float a,b,c,media;
cout<<"ingrese el valor de a: "<<endl;
cin>>a;
cout<<"ingrese el valor de b: "<<endl;
cin>>b;
cout<<"ingrese el valor de c: "<<endl;
cin>>c;
media = (a+b+c)/3 ;
cout.precision(4);
cout<<"la media aritmetica es: "<<media;
return 0;
}
| [
"00373119uca.edu.sv"
] | 00373119uca.edu.sv |
72e6a9ca15f4d405bb4252750fdc2daf72dda07c | cabf3a3aa51c98c774f3efaea2f9e43dae2cdebb | /Source.cpp | 566ed8736717ef6ce1a91fb223d64696f8d1da53 | [] | no_license | 26zet/LZW | 43b348d26593e8708a6c6f8621e635cd72676dc7 | b3c43f759a6feff39877d377a5dc34361043902f | refs/heads/master | 2021-01-17T08:26:13.572339 | 2017-03-04T18:10:21 | 2017-03-04T18:10:21 | 83,914,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,075 | cpp | #include <iostream>
#include "LZW.h"
#include "DecompressionLZW.h"
#include <algorithm>
#include <fstream>
using namespace std;
int main(){
int s;
cin >> s;
if(s == 1){
LZW *l = new LZW("pdf.pdf","przyklad2");
sort(l->Storage->Repeat,l->Storage->Repeat + l->Storage->LengthOfDict);
ofstream *ofs;
ofs = new ofstream("statystyka.txt",ofstream::trunc);
for(int i = 0; i < l->Storage->LengthOfDict;i++)
*ofs << (int)(l->Storage->Repeat[i]) << " ";
} else if(s == 0)
{
DLZW *l = new DLZW("przyklad2","FPI1.pdf");
}
else if(s == 2){
ofstream *ofs = new ofstream("np",ofstream::trunc | ofstream::binary);
int t = 5;
ofs->write((char *)(&t),4);
t = 10;
ofs->close();
ifstream *ifs = new ifstream("np",ifstream::binary);
ifs->read((char *)(&t),4);
cout << t;
system("pause");
}
else if(s == 3)
{
unsigned short *R = new unsigned short[10];
for (int i = 0; i < 10; i++)
{
R[i] = 500 - i;
}
sort(R,R + 10);
for (int i = 0; i < 10; i++)
{
cout << R[i] << " ";
}
}
return 0;
} | [
"noreply@github.com"
] | 26zet.noreply@github.com |
25f440cf6ff525ac683b76117b76c76829cc11dd | 72a7d6af316a2f7bfd3c05dd8df5b43100b2692d | /MyQueue/MyQueue/MyQueue.h | 6edc074a8b9f3603841532f13e228db492ec446f | [] | no_license | SplendidSky/Visual-Studio-2015 | 5b561a5204ce1ef3f3ea2631f478275339517b64 | c062d70c026a63ec603b3af0f59129b01ce4947c | refs/heads/master | 2021-01-22T18:15:44.206538 | 2016-09-08T10:43:26 | 2016-09-08T10:43:26 | 49,563,611 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,168 | h | #include <iostream>
using namespace std;
const int maxQueue = 101;
template <class QueueEntry>
class MyQueue {
public:
MyQueue();
// 判断队列是否为空
bool empty() const;
// 入队操作
int append(const QueueEntry &item);
// 出队操作
int serve();
// 获取队头元素
int retrieve(QueueEntry &item) const;
// 判断队列是否已满
bool full() const;
// 获取队列已有元素个数
int size() const;
// 清除队列所有元素
void clear();
// 获取队头元素并出队
int retrieve_and_serve(QueueEntry &item);
void print();
private:
int front; // 队头下标
int rear; // 队尾下标
QueueEntry entry[100]; // 队列容器
};
template<class QueueEntry>
MyQueue<QueueEntry>::MyQueue() {
front = rear = 0;
}
template<class QueueEntry>
int MyQueue<QueueEntry>::append(const QueueEntry &item) {
if (full())
return 2;
entry[rear] = item;
rear = (rear + 1 == maxQueue) ? 0 : rear + 1;
return 0;
}
template<class QueueEntry>
inline bool MyQueue<QueueEntry>::empty() const {
return front == rear;
}
template<class QueueEntry>
inline int MyQueue<QueueEntry>::serve() {
if (empty())
return 1;
front = (front + 1 == maxQueue) ? 0 : front + 1;
return 0;
}
template<class QueueEntry>
inline int MyQueue<QueueEntry>::retrieve(QueueEntry & item) const {
if (empty())
return 1;
item = entry[front];
return 0;
}
template<class QueueEntry>
inline bool MyQueue<QueueEntry>::full() const {
return front == rear + 1 || (rear == maxQueue - 1 && front == 0);
}
template<class QueueEntry>
inline int MyQueue<QueueEntry>::size() const {
int sz = 0;
for (int temp = front; temp != rear; temp = (temp + 1 == maxQueue) ? 0 : temp + 1)
sz++;
return sz;
}
template<class QueueEntry>
inline void MyQueue<QueueEntry>::clear() {
front = rear = 0;
}
template<class QueueEntry>
inline int MyQueue<QueueEntry>::retrieve_and_serve(QueueEntry & item) {
retrieve(item);
return serve();
}
template<class QueueEntry>
inline void MyQueue<QueueEntry>::print()
{
for (int temp = front; temp < rear; temp++)
cout << entry[temp] << " ";
cout << endl;
}
| [
"530415489@qq.com"
] | 530415489@qq.com |
42c879d5a149fc006e8a46a4270f59d3d6be9c0c | 7d35506b3047353e5169a74e9324358f55e2845c | /chap14/Sales_data.h | c74bdd38157191663a05a38ce74abab99d8bc2e5 | [] | no_license | weimch/cpp-primer | 6f74741e3223a4a6021fec799ac16e11e639486e | 13c6f415eca21170ced859ccbc232bc670ca977a | refs/heads/master | 2023-05-25T16:58:50.423816 | 2021-06-06T05:32:38 | 2021-06-06T05:32:38 | 295,981,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,473 | h | #pragma once
#include <string>
#include <iostream>
class Sales_data {
friend std::istream& operator>>(std::istream&, Sales_data&);
friend std::ostream& operator<<(std::ostream&, const Sales_data&);
friend Sales_data operator+(const Sales_data&, const Sales_data&);
public:
Sales_data(const std::string &s, unsigned n, double p)
: bookNo(s), units_sold(n), revenue(n*p) {}
Sales_data() : Sales_data("", 0, 0.0f) {}
Sales_data(const std::string &s) : Sales_data(s, 0, 0.0f) {}
Sales_data(std::istream &is) : Sales_data() {
is >> *this;
}
Sales_data& operator+=(const Sales_data &rhs) {
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
std::string isbn() const { return bookNo; }
private:
double avg_price() const {
return units_sold ? revenue / units_sold : 0;
}
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
std::istream& operator>>(std::istream &is, Sales_data &item) {
double price = 0.0;
is >> item.bookNo >> item.units_sold >> price;
if (is) {
item.revenue = price * item.units_sold;
} else {
item = Sales_data();
}
return is;
}
std::ostream& operator<<(std::ostream &os, const Sales_data &item) {
os << item.isbn() << " " << item.units_sold << " " <<
item.revenue << " " << item.avg_price();
return os;
}
Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) {
Sales_data sum = lhs;
sum += rhs;
return sum;
}
| [
"weimch3@qq.com"
] | weimch3@qq.com |
1f26b068834d3255b2db9ba68ef92484aa886879 | 607829232b9ec8d6733fb67be85e8555d19e1ee0 | /libs/core/include/fcppt/math/dim/map.hpp | 11312cfb24934a19b5ce420bfe2c3def39a48f9d | [
"BSL-1.0"
] | permissive | cnsuhao/fcppt | 3b917196d5faf477d769b8f04e0001361a857776 | 104c035118a04011c5fd9574cc78b2889550ea65 | refs/heads/master | 2021-01-13T06:30:29.527419 | 2016-11-05T13:33:41 | 2016-11-05T13:33:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,150 | hpp | // Copyright Carl Philipp Reh 2009 - 2016.
// 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 FCPPT_MATH_DIM_MAP_HPP_INCLUDED
#define FCPPT_MATH_DIM_MAP_HPP_INCLUDED
#include <fcppt/math/map.hpp>
#include <fcppt/math/size_type.hpp>
#include <fcppt/math/dim/object_impl.hpp>
#include <fcppt/math/dim/static.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace math
{
namespace dim
{
/**
\brief Maps over the elements of a dim
\ingroup fcpptmathdim
*/
template<
typename T,
fcppt::math::size_type N,
typename S,
typename Function
>
inline
fcppt::math::dim::static_<
typename
std::result_of<
Function(
T
)
>::type,
N
>
map(
fcppt::math::dim::object<
T,
N,
S
> const &_value,
Function const &_function
)
{
return
fcppt::math::map<
fcppt::math::dim::static_<
typename
std::result_of<
Function(
T
)
>::type,
N
>
>(
_value,
_function
);
}
}
}
}
#endif
| [
"carlphilippreh@gmail.com"
] | carlphilippreh@gmail.com |
0d860c819b03c7cebf17e58728a29215d2af9c73 | aa3d6a8a6e8e75d968786ed1900564baaad1bb62 | /AOJ/V2/WA/test.cpp | ec7c48a8ad4c2e44a09692a99d9f8ff75d9fa5d2 | [] | no_license | Halksel/Competition | 418b18981d4eb30572e6f24401f53968c5e9c354 | ce9ea74410a63ad2c4de23dee33698d23afb01b1 | refs/heads/master | 2021-01-23T21:46:52.925976 | 2019-08-25T13:07:44 | 2019-08-25T13:07:44 | 59,487,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,211 | cpp | #include <bits/stdc++.h>
using namespace std ;
#define pb(n) push_back(n)
#define fi first
#define se second
#define all(r) begin(r),end(r)
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)
#define vvl(v,w,h,init) vector<vector<ll>> v(w,vector<ll>(h,init))
#define mp(a,b) make_pair(a,b)
#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))
using ll = long long;
using pii = pair<int,int> ;
using pll = pair<ll,ll> ;
const int mod = 1000000007;
constexpr int inf = ((1<<30)-1)*2+1 ;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0,1,-1,1,-1};
const int dx[] = {0,-1,0,1,1,-1,-1,1};
namespace RMQ{
const int MAX_N = 1 << 10;
int n, dat[2*MAX_N - 1];
void init(int n_){
n = 1;
while(n < n_){
n *= 2;
}
for(int i =0; i < 2*n-1;++i){
dat[i] = INT_MAX;
}
}
void update(int k, int a){
k += n-1;
dat[k] = a;
while(k>0){
k = (k-1)/2;
dat[k] = min(dat[k*2+1],dat[k*2+2]);
}
}
//min = query(a,b,0,0,n)
int rec(int a,int b,int k,int l, int r){
cout << a << ',' << b << ',' << l << ',' << r << endl;
int vl,vr;
if(r <= a || b <= l){
return INT_MAX;
}
if(a <= l && r <= b){
return dat[k];
}
else{
vl = rec(a,b,k*2+1,l,(l+r)/2);
vr = rec(a,b,k*2+2,(l+r)/2,r);
}
return min(vl,vr);
}
int query(int a,int b){
return rec(a,b+1,0,0,n);
}
}
using namespace RMQ;
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
ll n;
cin >> n;
vector<ll> v(n);
rep(i,n){
cin >> v[i];
}
sort(all(v));
init(n);
rep(i,n){
update(i,v[i]);
}
rep(i,n){
scout(4) << i;
}
cout << endl;
rep(i,n){
scout(4) << v[i];
}
cout << endl;
ll a,b;
while(cin >> a >> b){
cout << query(a,b) << endl;
}
return 0;
}
| [
"whentheycry0708@gmail.com"
] | whentheycry0708@gmail.com |
29f702462204fe58c410e5b376a4e827df9c77ca | 47e458101f543cecee59b27d27f67e8944930d3a | /Chapter_09/Task_10/Task_10.cpp | 85cb919a5e868b54743028659555a61c80ce9e05 | [] | no_license | callmeFilip/Thinking-in-CPP-Volume-1-2nd-Edition | f1bb1c9e7edef1e9ca4eadb7758f80e08ee68bba | 95db8120d67423c35728bd8b216393e9e869371d | refs/heads/master | 2023-03-27T00:31:56.940278 | 2021-03-25T17:12:34 | 2021-03-25T17:12:34 | 312,387,460 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 229 | cpp | #include <iostream>
#include "Color.h"
int main()
{
Color ledColor(RED);
std::cout << ledColor.getColor() << std::endl;
ledColor.setColor(BLUE);
std::cout << ledColor.getColor() << std::endl;
return 0;
}
| [
"filip_andonow@abv.bg"
] | filip_andonow@abv.bg |
114e4b53edd2d3e9787e81c0675d3aa7e5bfbb82 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5706278382862336_1/C++/prims/q14.cpp | 324bec358ce73ccd8fdadfae795a5886d486a224 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 909 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
long long int gcd(long long int a, long long int b)
{
if (a%b == 0)
return b;
else return gcd(b,a%b);
}
int main()
{
long long int t;
long long int p,q,g;
long long temp,ans;
scanf("%lld",&t);
for (long long i = 1; i <= t; i++) {
ans = 0;
scanf("%lld/%lld",&p,&q);
g = gcd(p,q);
p = p/g;
q = q/g;
temp = q;
while (temp!= 0) {
if (temp % 2 == 1 && temp != 1)
break;
temp = temp/2;
}
if (temp != 0) {
printf("Case #%lld: impossible\n",i);
continue;
}
while (q > p) {
q = q/2;
ans++;
}
printf("Case #%lld: %lld\n",i,ans);
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
2dc4601df1bc37e155c8a6f9be134bb60c17c92e | ecf155e7be0734fcc5d8df37b19389f97984736b | /opengl-tutorial-6/src/main.cpp | f467731f3e24a5e817b0b0b0e9b05b7bd8a021a6 | [] | no_license | PurujeetPatil/opengl-tutorial | 10f09d86b01eebb371ad324266cedae88b8b47b6 | 80f4a39f911d7d4b109b2a2ed45dbeab4c6ff6de | refs/heads/master | 2023-08-30T13:52:44.581873 | 2021-11-03T04:32:09 | 2021-11-03T04:32:09 | 382,231,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,767 | cpp | #include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
#include "fileutil.h"
#include "errorHandler.h"
static unsigned int compileShader(unsigned int type, const std::string& src)
{
// Create a shader ID
unsigned int id = glCreateShader(type);
// openGL likes NULL terminated string and its pointer for some reason
const char* s_src = src.c_str();
// Pass the id for shader, number of shaders, reference to pointer to src of shader (wtf?) and length of shader(we are passing null, as null terminated)
glShaderSource(id, 1, &s_src, nullptr);
// Compile the shader by the id
glCompileShader(id);
//-------------------Error Handling---------------------
int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
int length;
// i specifies that we are giving an integer and v specifies it wants a vector
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
// Create a message buffer of that length
char* message = (char*)_malloca(length * sizeof(char));
// Pass the message buffer
glGetShaderInfoLog(id, length, &length, message);
std::cout << "Failed to compile shader! : " << (type == GL_VERTEX_SHADER ? "|Vertex|" : "|Fragment|");
std::cout << message << std::endl;
glDeleteShader(id);
return 0;
}
return id;
}
static unsigned int getShader(const std::string& vertexShader, const std::string& fragmentShader)
{
// Create a program to run on GPU
unsigned int program = glCreateProgram();
//------------------------Vertex Shader-------------------------
// Create a shader ID
unsigned int v_id = compileShader(GL_VERTEX_SHADER, vertexShader);
//-----------------------Fragment Shader------------------------
// Same shit below, expect for target that is GL_FRAGMENT_SHADER
unsigned int f_id = compileShader(GL_FRAGMENT_SHADER, fragmentShader);
// attach the shader to the program by id
glAttachShader(program, v_id);
glAttachShader(program, f_id);
// link the two shader .obj(s) in the program
glLinkProgram(program);
// validate if successfully linked
glValidateProgram(program);
// delete the intermediates like .obj(s)
glDeleteShader(v_id);
glDeleteShader(f_id);
return program;
}
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Match the framerate of monitor */
glfwSwapInterval(1);
if (glewInit() != GLEW_OK) {
std::cout << "Error!" << std::endl;
}
std::cout << glGetString(GL_VERSION) << std::endl;
float positions[] = {
-0.5f, -0.5f, // 0
0.5f, -0.5f, // 1
0.5f, 0.5f, // 2
-0.5f, 0.5f // 3
};
unsigned int indices[] = {
0, 1, 2,
2, 3, 0
};
unsigned int vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Vertex buffer
unsigned int buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(float), positions, GL_STATIC_DRAW);
GLCall(glEnableVertexAttribArray(0));
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
// index buffer
unsigned int ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW);
ShaderSource source = getShaderSource("res/shader/basic.shader");
unsigned int shader = getShader(source.vertexSrc, source.fragmentSrc);
glUseProgram(shader);
unsigned int uniform_location = glGetUniformLocation(shader, "u_color");
// some fancy animated color shifts
float red = 0.0f, inc = 0.01f;
/* Unbinding everything */
glBindVertexArray(0);
glUseProgram(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/*
Instead of glDrawArrays we use glDrawELements
params:
mode: GL_TRIANGLES
count: number of indices
type: data type of indices, it has to be GL_UNSIGNED_INT
indexBuffer: nullptr as we have already bind'ed the buffer to GL_ELEMENT_ARRAY_BUFFER targe
*/
// An openGL error that got handled
//GLCall(glDrawElements(GL_TRIANGLES, 6, GL_INT, nullptr));
/* Binding Shader program and just VAO as vao stores vb and ibo */
glUseProgram(shader);
glUniform4f(uniform_location, red, 0.5f, 0.5f, 0.5f);
glBindVertexArray(vao);
GLCall(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr));
if (red > 1.0f)
inc = -0.01f;
else if (red < 0.0f)
inc = 0.01f;
red += inc;
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glDeleteProgram(shader);
glfwTerminate();
return 0;
} | [
"patilpurujeet@gmail.com"
] | patilpurujeet@gmail.com |
368af9d48889dd99e5ffca23775612ec1e57d090 | 98b63e3dc79c75048163512c3d1b71d4b6987493 | /tensorflow/lite/delegates/gpu/java/src/main/native/gpu_delegate_jni.cc | d31d058b796e8746fccba74803320e7e256e40ff | [
"Apache-2.0"
] | permissive | galeone/tensorflow | 11a4e4a3f42f4f61a65b432c429ace00401c9cc4 | 1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206 | refs/heads/master | 2022-11-13T11:56:56.143276 | 2020-11-10T14:35:01 | 2020-11-10T14:35:01 | 310,642,488 | 21 | 12 | Apache-2.0 | 2020-11-06T16:01:03 | 2020-11-06T16:01:02 | null | UTF-8 | C++ | false | false | 4,661 | cc | /* Copyright 2019 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 <jni.h>
#include "absl/status/status.h"
#include "tensorflow/lite/delegates/gpu/common/gpu_info.h"
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/delegates/gpu/gl/egl_environment.h"
#include "tensorflow/lite/delegates/gpu/gl/request_gpu_info.h"
#include "tensorflow/lite/experimental/acceleration/compatibility/android_info.h"
#include "tensorflow/lite/experimental/acceleration/compatibility/gpu_compatibility.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
JNIEXPORT jlong JNICALL Java_org_tensorflow_lite_gpu_GpuDelegate_createDelegate(
JNIEnv* env, jclass clazz, jboolean precision_loss_allowed,
jboolean quantized_models_allowed, jint inference_preference) {
TfLiteGpuDelegateOptionsV2 options = TfLiteGpuDelegateOptionsV2Default();
if (precision_loss_allowed == JNI_TRUE) {
options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_LATENCY;
options.inference_priority2 =
TFLITE_GPU_INFERENCE_PRIORITY_MIN_MEMORY_USAGE;
options.inference_priority3 = TFLITE_GPU_INFERENCE_PRIORITY_MAX_PRECISION;
}
options.experimental_flags = TFLITE_GPU_EXPERIMENTAL_FLAGS_NONE;
if (quantized_models_allowed) {
options.experimental_flags |= TFLITE_GPU_EXPERIMENTAL_FLAGS_ENABLE_QUANT;
}
options.inference_preference = static_cast<int32_t>(inference_preference);
return reinterpret_cast<jlong>(TfLiteGpuDelegateV2Create(&options));
}
JNIEXPORT void JNICALL Java_org_tensorflow_lite_gpu_GpuDelegate_deleteDelegate(
JNIEnv* env, jclass clazz, jlong delegate) {
TfLiteGpuDelegateV2Delete(reinterpret_cast<TfLiteDelegate*>(delegate));
}
namespace {
class CompatibilityListHelper {
public:
absl::Status ReadInfo() {
auto status = tflite::acceleration::RequestAndroidInfo(&android_info_);
if (!status.ok()) return status;
if (android_info_.android_sdk_version < "21") {
// Weakly linked symbols may not be available on pre-21, and the GPU is
// not supported anyway so return early.
return absl::OkStatus();
}
std::unique_ptr<tflite::gpu::gl::EglEnvironment> env;
status = tflite::gpu::gl::EglEnvironment::NewEglEnvironment(&env);
if (!status.ok()) return status;
status = tflite::gpu::gl::RequestGpuInfo(&gpu_info_);
if (!status.ok()) return status;
return absl::OkStatus();
}
bool IsDelegateSupportedOnThisDevice() {
return compatibility_list_.Includes(android_info_, gpu_info_);
}
private:
tflite::acceleration::AndroidInfo android_info_;
tflite::gpu::GpuInfo gpu_info_;
tflite::acceleration::GPUCompatibilityList compatibility_list_;
};
} // namespace
JNIEXPORT jlong JNICALL
Java_org_tensorflow_lite_gpu_CompatibilityList_createCompatibilityList(
JNIEnv* env, jclass clazz) {
CompatibilityListHelper* compatibility_list = new CompatibilityListHelper;
auto status = compatibility_list->ReadInfo();
// Errors in ReadInfo should almost always be failures to construct the OpenGL
// environment. Treating that as "GPU unsupported" is reasonable, and we can
// swallow the error.
status.IgnoreError();
return reinterpret_cast<jlong>(compatibility_list);
}
JNIEXPORT jboolean JNICALL
Java_org_tensorflow_lite_gpu_CompatibilityList_nativeIsDelegateSupportedOnThisDevice(
JNIEnv* env, jclass clazz, jlong compatibility_list_handle) {
CompatibilityListHelper* compatibility_list =
reinterpret_cast<CompatibilityListHelper*>(compatibility_list_handle);
return compatibility_list->IsDelegateSupportedOnThisDevice() ? JNI_TRUE
: JNI_FALSE;
}
JNIEXPORT void JNICALL
Java_org_tensorflow_lite_gpu_CompatibilityList_deleteCompatibilityList(
JNIEnv* env, jclass clazz, jlong compatibility_list_handle) {
CompatibilityListHelper* compatibility_list =
reinterpret_cast<CompatibilityListHelper*>(compatibility_list_handle);
delete compatibility_list;
}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
93a216007ed49660281de4c6255a250376e5077d | 150eb8eadd14fa0dcfd14a632beaa339e9343c43 | /ANTs/ImageSegmentation/itkWeightedVotingFusionImageFilter.h | b5607587664829fc2462314f1dd85d19e41c4796 | [
"BSD-2-Clause"
] | permissive | rshiradkar/cppLibraries | b1c1c0fc850ec4ccbadbee98bba89ebc34d35904 | 004359ee4640ad2d5b740d716bc3b41e831e6398 | refs/heads/master | 2022-12-07T00:02:03.500679 | 2020-08-26T16:47:23 | 2020-08-26T16:47:23 | 290,552,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,763 | h | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkWeightedVotingFusionImageFilter_h
#define __itkWeightedVotingFusionImageFilter_h
#include "itkImageToImageFilter.h"
#include "itkConstNeighborhoodIterator.h"
#include <vnl/vnl_matrix.h>
#include <vnl/vnl_vector.h>
#include <vector>
#include <map>
#include <set>
namespace itk
{
/** \class WeightedVotingFusionImageFilter
* \brief Implementation of the joint label fusion and joint intensity fusion algorithm
*
* \author Paul Yushkevich with modifications by Brian Avants and Nick Tustison
*
* \par REFERENCE
*
* H. Wang, J. W. Suh, S. Das, J. Pluta, C. Craige, P. Yushkevich,
* "Multi-atlas segmentation with joint label fusion," IEEE Trans.
* on Pattern Analysis and Machine Intelligence, 35(3), 611-623, 2013.
*
* H. Wang and P. A. Yushkevich, "Multi-atlas segmentation with joint
* label fusion and corrective learning--an open source implementation,"
* Front. Neuroinform., 2013.
*
* \ingroup ImageSegmentation
*/
template <class TInputImage, class TOutputImage>
class WeightedVotingFusionImageFilter
: public ImageToImageFilter<TInputImage, TOutputImage>
{
public:
/** Standard class typedefs. */
typedef WeightedVotingFusionImageFilter Self;
typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Run-time type information (and related methods). */
itkTypeMacro( WeightedVotingFusionImageFilter, ImageToImageFilter );
itkNewMacro( Self );
/** ImageDimension constants */
itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension );
/** Some convenient typedefs. */
typedef TInputImage InputImageType;
typedef typename InputImageType::Pointer InputImagePointer;
typedef typename InputImageType::ConstPointer InputImageConstPointer;
typedef typename InputImageType::PixelType InputImagePixelType;
typedef std::vector<InputImagePointer> InputImageList;
typedef std::vector<InputImageList> InputImageSetList;
typedef std::vector<InputImagePixelType> InputImagePixelVectorType;
typedef TOutputImage OutputImageType;
typedef typename OutputImageType::PixelType LabelType;
typedef std::set<LabelType> LabelSetType;
typedef Image<LabelType, ImageDimension> LabelImageType;
typedef typename LabelImageType::Pointer LabelImagePointer;
typedef std::vector<LabelImagePointer> LabelImageList;
typedef Image<unsigned int, ImageDimension> CountImageType;
typedef LabelImageType MaskImageType;
typedef typename MaskImageType::Pointer MaskImagePointer;
typedef typename InputImageType::RegionType RegionType;
typedef typename InputImageType::SizeType SizeType;
typedef typename InputImageType::IndexType IndexType;
typedef Image<float, ImageDimension> ProbabilityImageType;
typedef typename ProbabilityImageType::Pointer ProbabilityImagePointer;
typedef double RealType;
typedef std::vector<int> OffsetList;
typedef vnl_matrix<RealType> MatrixType;
typedef vnl_vector<RealType> VectorType;
typedef std::map<LabelType, ProbabilityImagePointer> LabelPosteriorProbabilityMap;
typedef std::map<LabelType, LabelImagePointer> LabelExclusionMap;
typedef std::vector<ProbabilityImagePointer> VotingWeightImageList;
typedef ConstNeighborhoodIterator<InputImageType> ConstNeighborhoodIteratorType;
typedef typename ConstNeighborhoodIteratorType::RadiusType NeighborhoodRadiusType;
typedef typename ConstNeighborhoodIteratorType::OffsetType NeighborhoodOffsetType;
typedef typename SizeType::SizeValueType RadiusValueType;
typedef Image<RadiusValueType, ImageDimension> RadiusImageType;
typedef typename RadiusImageType::Pointer RadiusImagePointer;
/**
* Neighborhood patch similarity metric enumerated type
*/
enum SimilarityMetricType {
PEARSON_CORRELATION,
MEAN_SQUARES
};
/**
* Set the multimodal target image
*/
void SetTargetImage( InputImageList imageList )
{
this->m_TargetImage = imageList;
this->UpdateInputs();
}
/**
* Add an atlas (multi-modal image + segmentation)
*/
void AddAtlas( InputImageList imageList, LabelImageType *segmentation = ITK_NULLPTR )
{
for( unsigned int i = 0; i < imageList.size(); i++ )
{
this->m_AtlasImages.push_back( imageList );
}
if( this->m_NumberOfAtlasModalities == 0 )
{
itkDebugMacro( "Setting the number of modalities to " << this->m_NumberOfAtlasModalities );
this->m_NumberOfAtlasModalities = imageList.size();
}
else if( this->m_NumberOfAtlasModalities != imageList.size() )
{
itkExceptionMacro( "The number of atlas multimodal images is not equal to " << this->m_NumberOfAtlasModalities );
}
this->m_NumberOfAtlases++;
if( segmentation != ITK_NULLPTR )
{
this->m_AtlasSegmentations.push_back( segmentation );
this->m_NumberOfAtlasSegmentations++;
}
this->UpdateInputs();
}
/**
* Set mask image function. If a binary mask image is specified, only
* those input image voxels corresponding with mask image values equal
* to one are used.
*/
void SetMaskImage( MaskImageType *mask )
{
this->m_MaskImage = mask;
this->UpdateInputs();
}
/**
* Add a label exclusion map
*/
void AddLabelExclusionImage( LabelType label, LabelImageType *exclusionImage )
{
this->m_LabelExclusionImages[label] = exclusionImage;
this->UpdateInputs();
}
/**
* Get the number of modalities used in determining the optimal label fusion
* or optimal fused image.
*/
itkGetConstMacro( NumberOfAtlasModalities, unsigned int );
/**
* Get the label set.
*/
itkGetConstMacro( LabelSet, LabelSetType );
/**
* Set/Get the local search neighborhood for minimizing potential registration error.
* Default = 3x3x3.
*/
itkSetMacro( SearchNeighborhoodRadius, NeighborhoodRadiusType );
itkGetConstMacro( SearchNeighborhoodRadius, NeighborhoodRadiusType );
/**
* Set/Get the local search neighborhood radius image.
*/
void SetSearchNeighborhoodRadiusImage( RadiusImageType *image )
{
this->m_SearchNeighborhoodRadiusImage = image;
}
/**
* Set/Get the patch neighborhood for calculating the similarity measures.
* Default = 2x2x2.
*/
itkSetMacro( PatchNeighborhoodRadius, NeighborhoodRadiusType );
itkGetConstMacro( PatchNeighborhoodRadius, NeighborhoodRadiusType );
/**
* Set/Get the Alpha parameter---the regularization weight added to the matrix Mx for
* the inverse. Default = 0.1.
*/
itkSetMacro( Alpha, RealType );
itkGetConstMacro( Alpha, RealType );
/**
* Set/Get the Beta parameter---exponent for mapping intensity difference to joint error.
* Default = 2.0.
*/
itkSetMacro( Beta, RealType );
itkGetConstMacro( Beta, RealType );
/** Set the requested region */
void GenerateInputRequestedRegion() ITK_OVERRIDE;
/**
* Boolean for retaining the posterior images. This can have a negative effect
* on memory use, so it should only be done if one wishes to save the posterior
* maps. The posterior maps (n = number of labels) give the probability of each
* voxel in the target image belonging to each label. Default = false.
*/
itkSetMacro( RetainLabelPosteriorProbabilityImages, bool );
itkGetConstMacro( RetainLabelPosteriorProbabilityImages, bool );
itkBooleanMacro( RetainLabelPosteriorProbabilityImages );
/**
* Boolean for retaining the voting weights images. This can have a negative effect
* on memory use, so it should only be done if one wishes to save the voting weight
* maps. The voting weight maps (n = number of atlases) gives the contribution of
* a particular atlas to the final label/intensity fusion.
*/
itkSetMacro( RetainAtlasVotingWeightImages, bool );
itkGetConstMacro( RetainAtlasVotingWeightImages, bool );
itkBooleanMacro( RetainAtlasVotingWeightImages );
/**
* Boolean for constraining the weights to be positive and sum to 1. We use
* an implementation of the algorithm based on the algorithm by Lawson, Charles L.;
* Hanson, Richard J. (1995). Solving Least Squares Problems. SIAM.
*/
itkSetMacro( ConstrainSolutionToNonnegativeWeights, bool );
itkGetConstMacro( ConstrainSolutionToNonnegativeWeights, bool );
itkBooleanMacro( ConstrainSolutionToNonnegativeWeights );
/**
* Measurement of neighborhood similarity.
*/
itkSetMacro( SimilarityMetric, SimilarityMetricType );
itkGetConstMacro( SimilarityMetric, SimilarityMetricType );
/**
* Get the posterior probability image corresponding to a label.
*/
const ProbabilityImagePointer GetLabelPosteriorProbabilityImage( LabelType label )
{
if( this->m_RetainLabelPosteriorProbabilityImages )
{
if( std::find( this->m_LabelSet.begin(), this->m_LabelSet.end(), label ) != this->m_LabelSet.end() )
{
return this->m_LabelPosteriorProbabilityImages[label];
}
else
{
itkDebugMacro( "Not returning a label posterior probability image. Requested label not found." );
return ITK_NULLPTR;
}
}
else
{
itkDebugMacro( "Not returning a label posterior probability image. These images were not saved." );
return ITK_NULLPTR;
}
}
/**
* Get the voting weight image corresponding to an atlas.
*/
const ProbabilityImagePointer GetAtlasVotingWeightImage( unsigned int n )
{
if( this->m_RetainAtlasVotingWeightImages )
{
if( n < this->m_NumberOfAtlases )
{
return this->m_AtlasVotingWeightImages[n];
}
else
{
itkDebugMacro( "Not returning a voting weight image. Requested index is greater than the number of atlases." );
return ITK_NULLPTR;
}
}
else
{
itkDebugMacro( "Not returning a voting weight image. These images were not saved." );
return ITK_NULLPTR;
}
}
/**
* Get the joint intensity fusion output image
*/
const ProbabilityImagePointer GetJointIntensityFusionImage( unsigned int n )
{
if( n < this->m_NumberOfAtlasModalities )
{
return this->m_JointIntensityFusionImage[n];
}
else
{
itkDebugMacro( "Not returning a joint intensity fusion image. Requested index is greater than the number of modalities." );
return ITK_NULLPTR;
}
}
protected:
WeightedVotingFusionImageFilter();
~WeightedVotingFusionImageFilter() {}
void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE;
void ThreadedGenerateData( const RegionType &, ThreadIdType ) ITK_OVERRIDE;
void BeforeThreadedGenerateData() ITK_OVERRIDE;
void AfterThreadedGenerateData() ITK_OVERRIDE;
void GenerateData() ITK_OVERRIDE;
private:
void ThreadedGenerateDataForWeightedAveraging( const RegionType &, ThreadIdType );
void ThreadedGenerateDataForReconstruction( const RegionType &, ThreadIdType );
RealType ComputeNeighborhoodPatchSimilarity( const InputImageList &, const IndexType, const InputImagePixelVectorType &, const bool );
InputImagePixelVectorType VectorizeImageListPatch( const InputImageList &, const IndexType, const bool );
InputImagePixelVectorType VectorizeImagePatch( const InputImagePointer, const IndexType, const bool );
void GetMeanAndStandardDeviationOfVectorizedImagePatch( const InputImagePixelVectorType &, RealType &, RealType & );
VectorType NonNegativeLeastSquares( const MatrixType, const VectorType, const RealType );
void UpdateInputs();
typedef std::pair<unsigned int, RealType> DistanceIndexType;
typedef std::vector<DistanceIndexType> DistanceIndexVectorType;
struct DistanceIndexComparator
{
bool operator () ( const DistanceIndexType& left, const DistanceIndexType& right )
{
return left.second < right.second;
}
};
bool m_IsWeightedAveragingComplete;
/** Input variables */
InputImageList m_TargetImage;
InputImageSetList m_AtlasImages;
LabelImageList m_AtlasSegmentations;
LabelExclusionMap m_LabelExclusionImages;
MaskImagePointer m_MaskImage;
LabelType m_MaskLabel;
typename CountImageType::Pointer m_CountImage;
LabelSetType m_LabelSet;
SizeValueType m_NumberOfAtlases;
SizeValueType m_NumberOfAtlasSegmentations;
SizeValueType m_NumberOfAtlasModalities;
NeighborhoodRadiusType m_SearchNeighborhoodRadius;
NeighborhoodRadiusType m_PatchNeighborhoodRadius;
SizeValueType m_PatchNeighborhoodSize;
std::vector<NeighborhoodOffsetType> m_SearchNeighborhoodOffsetList;
std::map<RadiusValueType,
std::vector<NeighborhoodOffsetType> > m_SearchNeighborhoodOffsetSetsMap;
std::vector<NeighborhoodOffsetType> m_PatchNeighborhoodOffsetList;
RealType m_Alpha;
RealType m_Beta;
bool m_RetainLabelPosteriorProbabilityImages;
bool m_RetainAtlasVotingWeightImages;
bool m_ConstrainSolutionToNonnegativeWeights;
SimilarityMetricType m_SimilarityMetric;
ProbabilityImagePointer m_WeightSumImage;
RadiusImagePointer m_SearchNeighborhoodRadiusImage;
/** Output variables */
LabelPosteriorProbabilityMap m_LabelPosteriorProbabilityImages;
VotingWeightImageList m_AtlasVotingWeightImages;
InputImageList m_JointIntensityFusionImage;
};
} // namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkWeightedVotingFusionImageFilter.hxx"
#endif
#endif
| [
"68760842+rshiradkar@users.noreply.github.com"
] | 68760842+rshiradkar@users.noreply.github.com |
ebb0b7f8c9cd3645f43b303072705d04c3f78ec8 | 762d0e6bd7e743024231c64068c8de8d4ad74046 | /laba25.cpp | f92a98bfa9a927d38c488522bd57d80ae7a4a3d4 | [] | no_license | Sistemnoe-programmirovanie/SPbCT_ManinaAS | d7b96df4f0257b2093935a450680441cf1801339 | ddaded1fdc9ec09fa1da3390977c7fa6cb10a6e8 | refs/heads/main | 2023-01-31T12:31:31.294068 | 2020-12-15T21:43:43 | 2020-12-15T21:43:43 | 308,622,164 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,250 | cpp | /*
процесс 1 открывает файл и после этого порождает потомка 2,
который в свою очередь порождает потомка 3.
Процесс 2 пишет N байт в общий файл, посылает сигнал процессу 3,
который тоже пишет N байт в файл и посылает сигнал процессу 1,
который считывает данные из файла и выводит их на экран.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#define fatal(msg) ({fprintf(stderr, "Fatal <%ld> %s: %m\n", (long)getpid(), (msg)); exit(-1);})
void
fhand (int sig)
{
// printf ("pid: %ld catch: %d\n", (long)getpid(), sig);
}
FILE *f;
sigset_t mask;
pid_t
proc3 (pid_t p1)
{
pid_t p = fork();
if (p)
return p;
// код процесса 3
sigsuspend(&mask); // ждем команды продолжить работу
fseek(f, 0, SEEK_END);
fprintf (f, "Proc3 <%ld> started...\n", (long)getpid());
fflush(f);
kill(p1, SIGUSR1); // даем команду процессу 1 продолжить работу
exit (0);
}
pid_t
proc2 ()
{
pid_t p = fork(), p3;
if (p)
return p;
// код процесса 2
p3 = proc3(getppid()); // запускаем процесс 3, сообщим ему PID процесса 1
fprintf (f, "Proc2 <%ld> started...\n", (long)getpid());
fflush(f);
kill(p3, SIGUSR1); // даем команду процессу 3 продолжить работу
exit (0);
}
int
main (int ac, char *av[])
{
char *fname = av[1] ? av[1] : (char *)"3proc.dat";
if (!(f = fopen(fname, "w+")))
fatal(fname);
sigset_t bmask;
sigemptyset(&bmask);
sigaddset(&bmask, SIGUSR1);
sigprocmask(SIG_BLOCK, &bmask, &mask);
signal(SIGUSR1, fhand);
proc2(); // запускаем процесс 2
sigsuspend(&mask); // ждем команды продолжить от процесса 3
rewind(f);
int c;
while ((c = fgetc(f)) != EOF)
putchar(c);
int st;
printf ("Parent: <%ld> exits\n", (long)wait(&st));
exit (WEXITSTATUS(st));
}
| [
"noreply@github.com"
] | Sistemnoe-programmirovanie.noreply@github.com |
9843d511e4a96210e574bdc2a67f044c15d2f74f | 5ed83cb27ebe868f61b2854a60075aef788f2721 | /HelloWorld/HelloWorld.hpp | 7af4442e935eadafcc0deff050e425ad5ee03324 | [] | no_license | MechaDragonX/CPlusPlusExperiments | 98f6cd23013ffbbc8134d3381cb219c686181363 | eabf483781f5ce4d204f8d561d66706c40c529ec | refs/heads/master | 2020-08-06T07:56:05.369794 | 2019-10-06T03:09:13 | 2019-10-06T03:09:13 | 212,899,126 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | hpp | #pragma once
#include <iostream>
// TODO: Reference additional headers your program requires here.
| [
"sonicraghav@gmail.com"
] | sonicraghav@gmail.com |
b5e42820d423ebb425c055b94880817bdd4ed5db | af3c0f1b1d3e704563c1992b3bcda0611ac21ef4 | /css/src/ModuleConfigCollection.cpp | 0b59a7b8cbbf9befa94469f51b505b88d73d8404 | [] | no_license | BallMIllsap/frame | 56bbbef303d31b4ba48fd07a8b3d1bf0b1f88146 | b0ca45ccd4b3865519cce7d189050a18f0b697e9 | refs/heads/master | 2021-05-30T22:07:01.726029 | 2015-10-13T01:39:15 | 2015-10-13T01:39:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,864 | cpp | #include "ModuleConfigCollection.h"
CModuleConfigCollection::CModuleConfigCollection(void)
{
}
CModuleConfigCollection::~CModuleConfigCollection(void)
{
}
CModuleConfigCollection* CModuleConfigCollection::get_instance ()
{
static CModuleConfigCollection *_instance = NULL;
if (NULL == _instance)
{
_instance = new(std::nothrow) CModuleConfigCollection;
}
return _instance;
}
int CModuleConfigCollection::dump(const char* first_param /* = NULL */,
const char* second_param /* = NULL */)
{
CSystemConfigCollection::dump ();
// 实现模块私有的dump信息
return 0;
}
int CModuleConfigCollection::load_module_file_config (CIniFile &ini_reader)
{
if (FUNC_SUCCESS != load_string_item (ini_reader,
"BSS_SVR_INFO",
"BSS_SVR_IP",
m_net_srv_config.bss_service_listen_ip))
{
return FUNC_FAILED;
}
if (FUNC_SUCCESS != load_int_item(ini_reader,
"BSS_SVR_INFO",
"BSS_SVR_PORT",
m_net_srv_config.bss_service_listen_port,
1024,
65523))
{
return FUNC_FAILED;
}
if (FUNC_SUCCESS != load_int_item(ini_reader,
"BSS_SVR_INFO",
"BSS_HEARTBEAT_TIME",
m_net_srv_config.bss_service_heartbeat_detection,
5,
6000))
{
return FUNC_FAILED;
}
return FUNC_SUCCESS;
}
| [
"chenjianjun571@gmail.com"
] | chenjianjun571@gmail.com |
2fbd913f2e4e28557fb2633e5da4776f543b2b51 | fd9db286217f551a2377f5b79c86d9735b0c09b7 | /Final/Hand.cpp | d270221fe0607dd9a890106a02994adf932087f5 | [] | no_license | Golan1/Malbot | d13a06e343055901bcf73826c9c05e6a65149a8f | bb40eea7fd5b4b95592533d12b989f7c659e7d82 | refs/heads/master | 2020-04-06T07:17:38.723248 | 2016-09-03T18:08:23 | 2016-09-03T18:08:23 | 64,696,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,497 | cpp | #include "Hand.h"
Hand::Hand()
{
phalanx = new Rect({ FINGER_SPACE * 2.0f, PHALANX_SPACE * 5.0f, FINGER_SPACE * 2.0f });
palm = new Rect({ 14.0f * FINGER_SPACE, PHALANX_SPACE * 15.0f, FINGER_SPACE * 3.5f });
}
Hand::~Hand()
{
delete phalanx;
delete palm;
}
void Hand::Init()
{
phalanx->Init();
palm->Init();
}
void Hand::Draw()
{
palm->Draw();
// Move to the end of the palm
glTranslatef((-palm->size[0] + phalanx->size[0]) / 2, palm->size[1] + PHALANX_SPACE, 0);
// Rotate the phalanx row
glRotatef(fistAngle, 1, 0, 0);
drawPhalanxRow();
// Move to the next row
glTranslatef(0, phalanx->size[1] + PHALANX_SPACE, 0);
// Rotate the phalanx row
glRotatef(fistAngle, 1, 0, 0);
drawPhalanxRow();
// Move to the next row
glTranslatef(0, phalanx->size[1] + PHALANX_SPACE, 0);
// Rotate the phalanx row
glRotatef(fistAngle, 1, 0, 0);
drawPhalanxRow(true);
}
void Hand::drawPhalanxRow(bool isFirstRow) {
glPushMatrix();
size_t numOfFingers;
if (isFirstRow)
{
numOfFingers = 3;
glTranslatef(phalanx->size[0] + FINGER_SPACE, 0, 0);
}
else
{
numOfFingers = 5;
}
for (size_t i = 0; i < numOfFingers; i++)
{
phalanx->Draw();
glTranslatef(phalanx->size[0] + FINGER_SPACE, 0, 0);
}
glPopMatrix();
}
void Hand::ControlFist(int direction) {
fistAngle -= direction;
SetFist(fistAngle);
}
void Hand::SetFist(GLfloat angle) {
if (angle < 0.0f) fistAngle = 0.0f;
else if (angle > MAX_FIST_ANGLE) fistAngle = MAX_FIST_ANGLE;
else fistAngle = angle;
} | [
"golanlevi1@gmail.com"
] | golanlevi1@gmail.com |
d4f628abf0e6d3dc22824aff68ec568e4fcc760b | e27d9e460c374473e692f58013ca692934347ef1 | /drafts/quickSpectrogram_2/libraries/liblsl/external/lslboost/fusion/sequence/intrinsic/front.hpp | 40ae2acc06f3107ed780e70aabd6d05f10c4975e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | thoughtworksarts/Dual_Brains | 84a0edf69d95299021daf4af9311aed5724a2e84 | a7a6586b91a280950693b427d8269bd68bf8a7ab | refs/heads/master | 2021-09-18T15:50:51.397078 | 2018-07-16T23:20:18 | 2018-07-16T23:20:18 | 119,759,649 | 3 | 0 | null | 2018-07-16T23:14:34 | 2018-02-01T00:09:16 | HTML | UTF-8 | C++ | false | false | 1,273 | hpp | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_FRONT_09162005_0343)
#define FUSION_FRONT_09162005_0343
#include <lslboost/fusion/sequence/intrinsic_fwd.hpp>
#include <lslboost/fusion/sequence/intrinsic/begin.hpp>
#include <lslboost/fusion/iterator/deref.hpp>
#include <lslboost/mpl/bool.hpp>
namespace lslboost { namespace fusion
{
struct fusion_sequence_tag;
namespace result_of
{
template <typename Sequence>
struct front
: result_of::deref<typename result_of::begin<Sequence>::type>
{};
}
template <typename Sequence>
inline typename result_of::front<Sequence>::type
front(Sequence& seq)
{
return *fusion::begin(seq);
}
template <typename Sequence>
inline typename result_of::front<Sequence const>::type
front(Sequence const& seq)
{
return *fusion::begin(seq);
}
}}
#endif
| [
"gabriel.ibagon@gmail.com"
] | gabriel.ibagon@gmail.com |
fa1b3d632567fa2b2d778cfd30b7d7005ba522a7 | c3efa7c046ef2ab497f4a22fe69c892579bc428a | /Example_Touchpads/KB_TP_Stream_mode.ino | b310a8b2954e7bb112fb93a90ad8f627dd203f3e | [
"Apache-2.0"
] | permissive | thedalles77/USB_Laptop_Keyboard_Controller | c6c72134970ebad2a33e6b572869949456b812d4 | ec29edd1ba8b04e975836527b03f4b5ec75bcba9 | refs/heads/master | 2023-08-16T15:56:23.673910 | 2023-02-11T01:15:13 | 2023-02-11T01:15:13 | 153,025,155 | 321 | 64 | NOASSERTION | 2023-08-05T14:40:56 | 2018-10-14T22:34:02 | C++ | UTF-8 | C++ | false | false | 40,335 | ino | /* Copyright 2022 Frank Adams
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.
*/
// This software creates a USB keyboard and touchpad.
// The touchpad is PS/2 and the code uses "stream mode" instead of "remote mode".
//
// define the pins on the Teensy used for the touchpad ps2 bus
#define TP_DATA 11 // Touchpad ps/2 data connected to Teensy I/O pin
#define TP_CLK 12 // Touchpad ps/2 clock connected to Teensy I/O pin
#define CAPS_LOCK_N 8 // driven low to turn on the CAPS LED
#define NUM_LOCK_N 13 // driven low to turn on the NUM LED (Note the LED on the Teensy 3.2 is also connected to this I/O and has opposite polarity)
//
#define MODIFIERKEY_FN 0x8f // give the Fn key a HID code so it can be handled like any other key
//
const byte rows_max = 15; // sets the number of rows in the keyboard matrix
const byte cols_max = 8; // sets the number of columns in the keyboard matrix
//
// Load the normal key matrix with the Teensyduino key names described at www.pjrc.com/teensy/td_keyboard.html
// A zero indicates no normal key at that location.
//
int normal[rows_max][cols_max] = {
{KEY_END,KEY_RIGHT,0,KEY_PRINTSCREEN,KEY_DELETE,KEY_HOME,KEY_PAGE_UP,KEY_PAGE_DOWN},
{KEY_QUOTE,KEY_ENTER,KEY_PAUSE,0,KEY_EQUAL,KEY_BACKSPACE,KEY_RIGHT_BRACE,KEY_BACKSLASH},
{KEY_SLASH,KEY_UP,KEY_MINUS,KEY_F12,KEY_0,KEY_P,KEY_LEFT_BRACE,KEY_SEMICOLON},
{0,0,0,0,0,0,0,0},
{0,0,KEY_F8,KEY_F9,0,0,KEY_MENU,KEY_LEFT},
{KEY_COMMA,KEY_INSERT,KEY_F7,KEY_F6,KEY_F5,KEY_8,KEY_I,KEY_K},
{0,0,0,0,0,0,0,0},
{KEY_PERIOD,KEY_DOWN,0,KEY_F11,KEY_F10,KEY_9,KEY_O,KEY_L},
{KEY_M,KEY_N,KEY_H,KEY_Y,KEY_6,KEY_7,KEY_U,KEY_J},
{KEY_V,KEY_B,KEY_G,KEY_T,KEY_5,KEY_4,KEY_R,KEY_F},
{KEY_X,KEY_Z,KEY_F2,KEY_F1,KEY_ESC,KEY_2,KEY_W,KEY_S},
{KEY_C,KEY_SPACE,KEY_F3,KEY_F4,KEY_CAPS_LOCK,KEY_3,KEY_E,KEY_D},
{0,0,0,0,0,0,0,0},
{0,0,0,KEY_TAB,KEY_TILDE,KEY_1,KEY_Q,KEY_A},
{0,0,0,0,0,0,0,0}
};
// Load the numlock key matrix with key names at the correct row-column location.
// This matrix is the same as the normal matrix except for the number pad keys
// A zero indicates no numlock key at that location.
int numlock[rows_max][cols_max] = {
{KEY_END,KEY_RIGHT,0,KEY_PRINTSCREEN,KEY_DELETE,KEY_HOME,KEY_PAGE_UP,KEY_PAGE_DOWN},
{KEY_QUOTE,KEY_ENTER,KEY_PAUSE,0,KEY_EQUAL,KEY_BACKSPACE,KEY_RIGHT_BRACE,KEY_BACKSLASH},
{KEYPAD_SLASH,KEY_UP,KEY_MINUS,KEY_F12,KEYPAD_ASTERIX,KEYPAD_MINUS,KEY_LEFT_BRACE,KEYPAD_PLUS},
{0,0,0,0,0,0,0,0},
{0,0,KEY_F8,KEY_F9,0,0,KEY_MENU,KEY_LEFT},
{KEY_COMMA,KEY_INSERT,KEY_F7,KEY_F6,KEY_F5,KEYPAD_8,KEYPAD_5,KEYPAD_2},
{0,0,0,0,0,0,0,0},
{KEYPAD_PERIOD,KEY_DOWN,0,KEY_F11,KEY_F10,KEYPAD_9,KEYPAD_6,KEYPAD_3},
{KEYPAD_0,KEY_N,KEY_H,KEY_Y,KEY_6,KEYPAD_7,KEYPAD_4,KEYPAD_1},
{KEY_V,KEY_B,KEY_G,KEY_T,KEY_5,KEY_4,KEY_R,KEY_F},
{KEY_X,KEY_Z,KEY_F2,KEY_F1,KEY_ESC,KEY_2,KEY_W,KEY_S},
{KEY_C,KEY_SPACE,KEY_F3,KEY_F4,KEY_CAPS_LOCK,KEY_3,KEY_E,KEY_D},
{0,0,0,0,0,0,0,0},
{0,0,0,KEY_TAB,KEY_TILDE,KEY_1,KEY_Q,KEY_A},
{0,0,0,0,0,0,0,0}
};
// Load the modifier key matrix with key names at the correct row-column location.
// A zero indicates no modifier key at that location.
int modifier[rows_max][cols_max] = {
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,MODIFIERKEY_LEFT_CTRL,0,0,MODIFIERKEY_RIGHT_CTRL,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{MODIFIERKEY_RIGHT_SHIFT,MODIFIERKEY_LEFT_SHIFT,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{MODIFIERKEY_RIGHT_ALT,MODIFIERKEY_LEFT_ALT,0,0,0,0,0,0},
{0,0,MODIFIERKEY_FN,0,0,0,0,0},
{0,MODIFIERKEY_GUI,0,0,0,0,0,0}
};
// Load the media key matrix with Fn key names at the correct row-column location.
// A zero indicates no media key at that location.
int media[rows_max][cols_max] = {
{0,0,0,0,KEY_SCROLL_LOCK,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,KEY_NUM_LOCK,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,KEY_MEDIA_MUTE,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,KEY_MEDIA_VOLUME_DEC,KEY_MEDIA_VOLUME_INC,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}
};
// Initialize the old_key matrix with one's (no keys pressed).
// 1 = key not pressed, 0 = key is pressed
boolean old_key[rows_max][cols_max] = {
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1}
};
//
// Define the Teensy 3.2 I/O numbers that are connected to the keyboard FPC connector pins
// Row FPC pin # 09,10,11,12,13,14,15,16,17,18,19,20,21,22,23
// Teensy I/O # 18,33,19,20,21,22,23,24,25,26,27,28,07,06,05
int Row_IO[rows_max] = {18,33,19,20,21,22,23,24,25,26,27,28,7,6,5}; // Teensy 3.2 I/O numbers for rows 0 thru 14
//
// Column FPC pin # 01,02,03,04,05,06,07,08
// Teensy I/O # 14,29,15,30,16,31,17,32
int Col_IO[cols_max] = {14,29,15,30,16,31,17,32}; // Teensy 3.2 I/O numbers for columns 0 thru 7
//
// Declare global variables that will be used by functions
//
boolean slots_full = LOW; // Goes high when USB slots 1 thru 6 contain normal keys
boolean touchpad_error = LOW; // set high if the touchpad fails to give the correct power-up response
char mstat; // touchpad status 8 bit register = Y overflow, X overflow, Y sign bit, X sign bit, Always 1, Middle Btn, Right Btn, Left Btn
char mx; // touchpad x movement = 8 data bits. The sign bit is in the status register to
// make a 9 bit 2's complement value. Left to right on the touchpad gives a positive value.
char my; // touchpad y movement also 8 bits plus sign bit in status reg. Touchpad movement away from the user gives a positive value.
//
// slot 1 thru slot 6 hold the normal key values to be sent over USB.
int slot1 = 0; //value of 0 means the slot is empty and can be used.
int slot2 = 0;
int slot3 = 0;
int slot4 = 0;
int slot5 = 0;
int slot6 = 0;
//
int mod_shift_l = 0; // These variables are sent over USB as modifier keys.
int mod_shift_r = 0; // Each is either set to 0 or MODIFIER_ ...
int mod_ctrl_l = 0;
int mod_ctrl_r = 0;
int mod_alt_l = 0;
int mod_alt_r = 0;
int mod_gui = 0;
//
// ********************Common Functions**********************************************
//
// Function to set a pin to high impedance (acts like open drain output)
void go_z(int pin)
{
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);
}
//
// Function to set a pin as an input with a pullup
void go_pu(int pin)
{
pinMode(pin, INPUT_PULLUP);
digitalWrite(pin, HIGH);
}
//
// Function to send a pin to a logic low
void go_0(int pin)
{
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
//
// Function to send a pin to a logic high
void go_1(int pin)
{
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
}
//
// ********************Functions for keyboard scanning*******************************
//
// Function to load the key name into the first available slot
void load_slot(int key) {
if (!slot1) { // check if slot 1 is empty
slot1 = key; // and load it with the key name
}
else if (!slot2) { // otherwise go thru all the other slots looking for an empty to load
slot2 = key;
}
else if (!slot3) {
slot3 = key;
}
else if (!slot4) {
slot4 = key;
}
else if (!slot5) {
slot5 = key;
}
else if (!slot6) {
slot6 = key;
}
if (!slot1 || !slot2 || !slot3 || !slot4 || !slot5 || !slot6) { // are any slots empty?
slots_full = LOW; // slots are not full
}
else {
slots_full = HIGH; // slots are full
}
}
//
// Function to clear the slot that contains the key name
void clear_slot(int key) {
if (slot1 == key) { // check if slot 1 contains the key that needs to be cleared
slot1 = 0; // and clear it
}
else if (slot2 == key) { // otherwise keep checking the other slots for a match
slot2 = 0;
}
else if (slot3 == key) {
slot3 = 0;
}
else if (slot4 == key) {
slot4 = 0;
}
else if (slot5 == key) {
slot5 = 0;
}
else if (slot6 == key) {
slot6 = 0;
}
if (!slot1 || !slot2 || !slot3 || !slot4 || !slot5 || !slot6) { // are any slots empty?
slots_full = LOW; // slots are not full
}
else {
slots_full = HIGH; // slots are full
}
}
//
// Function to load the modifier key name into the appropriate mod variable
void load_mod(int m_key) {
if (m_key == MODIFIERKEY_LEFT_SHIFT) { // Figure out which modifier key was pushed
mod_shift_l = m_key; // and load it into 1 of 7 possible variables
}
else if (m_key == MODIFIERKEY_RIGHT_SHIFT) {
mod_shift_r = m_key;
}
else if (m_key == MODIFIERKEY_LEFT_CTRL) {
mod_ctrl_l = m_key;
}
else if (m_key == MODIFIERKEY_RIGHT_CTRL) {
mod_ctrl_r = m_key;
}
else if (m_key == MODIFIERKEY_LEFT_ALT) {
mod_alt_l = m_key;
}
else if (m_key == MODIFIERKEY_RIGHT_ALT) {
mod_alt_r = m_key;
}
else if (m_key == MODIFIERKEY_GUI) {
mod_gui = m_key;
}
}
//
// Function to load 0 into the appropriate mod variable
void clear_mod(int m_key) {
if (m_key == MODIFIERKEY_LEFT_SHIFT) { // Figure out which modifier key was released
mod_shift_l = 0; // and clear the matching variable
}
else if (m_key == MODIFIERKEY_RIGHT_SHIFT) {
mod_shift_r = 0;
}
else if (m_key == MODIFIERKEY_LEFT_CTRL) {
mod_ctrl_l = 0;
}
else if (m_key == MODIFIERKEY_RIGHT_CTRL) {
mod_ctrl_r = 0;
}
else if (m_key == MODIFIERKEY_LEFT_ALT) {
mod_alt_l = 0;
}
else if (m_key == MODIFIERKEY_RIGHT_ALT) {
mod_alt_r = 0;
}
else if (m_key == MODIFIERKEY_GUI) {
mod_gui = 0;
}
}
//
// Function to send the modifier keys over usb
void send_mod() {
Keyboard.set_modifier(mod_shift_l | mod_shift_r | mod_ctrl_l | mod_ctrl_r | mod_alt_l | mod_alt_r | mod_gui);
Keyboard.send_now(); // sends all modifier values including the one that just changed (and all normal slots)
}
//
// Function to send the normal keys in the 6 slots over usb
void send_normals() {
Keyboard.set_key1(slot1); // load each slot into the cooresponding key number
Keyboard.set_key2(slot2);
Keyboard.set_key3(slot3);
Keyboard.set_key4(slot4);
Keyboard.set_key5(slot5);
Keyboard.set_key6(slot6);
Keyboard.send_now(); // sends all slots including the one that just changed (and all modifier values)
}
//
// *****************Functions for Touchpad***************************
//
// Function to send the touchpad a byte of data (command)
//
void tp_write(char send_data)
{
unsigned int timeout = 200; // break out of loop if watchdog over this value in msec
elapsedMillis watchdog; // zero the watchdog timer clock
char odd_parity = 0; // clear parity bit count
// Enable the PS/2 bus by floating the clock and data
go_pu(TP_CLK); //
go_pu(TP_DATA); //
delayMicroseconds(250); // wait before requesting the bus
go_0(TP_CLK); // Send the Clock line low to request to transmit data
delayMicroseconds(100); // wait for 100 microseconds per bus spec
go_0(TP_DATA); // Send the Data line low (the start bit)
delayMicroseconds(1); //
go_pu(TP_CLK); // Release the Clock line so it is pulled high
delayMicroseconds(1); // give some time to let the clock line go high
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop because tp did not respond
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
// send the 8 bits of send_data
for (int j=0; j<8; j++) {
if (send_data & 1) { //check if lsb is set
go_pu(TP_DATA); // send a 1 to TP
odd_parity = odd_parity + 1; // keep running total of 1's sent
}
else {
go_0(TP_DATA); // send a 0 to TP
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
send_data = send_data >> 1; // shift data right by 1 to prepare for next loop
}
// send the parity bit
if (odd_parity & 1) { //check if lsb of parity is set
go_0(TP_DATA); // already odd so send a 0 to TP
}
else {
go_pu(TP_DATA); // send a 1 to TP to make parity odd
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
go_pu(TP_DATA); // Release the Data line so it goes high as the stop bit
delayMicroseconds(80); // testing shows delay at least 40us
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
delayMicroseconds(1); // wait to let the data settle
if (digitalRead(TP_DATA)) { // Ack bit s/b low if good transfer
}
while ((digitalRead(TP_CLK) == LOW) || (digitalRead(TP_DATA) == LOW)) { // loop if clock or data are low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
// Inhibit the bus so the tp only talks when the Teensy is listening
go_0(TP_CLK);
}
//
// Function to get a byte of data from the touchpad
//
char tp_read(void)
{
unsigned int timeout = 200; // break out of loop if over this value in msec
elapsedMillis watchdog; // zero the watchdog timer clock
char rcv_data = 0; // initialize to zero
char mask = 1; // shift a 1 across the 8 bits to select where to load the data
char rcv_parity = 0; // count the ones received
go_pu(TP_CLK); // release the clock
go_pu(TP_DATA); // release the data
delayMicroseconds(5); // delay to let clock go high
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
if (digitalRead(TP_DATA)) { // Start bit s/b low from tp
// start bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
for (int k=0; k<8; k++) {
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
if (digitalRead(TP_DATA)) { // check if data is high
rcv_data = rcv_data | mask; // set the appropriate bit in the rcv data
rcv_parity++; // increment the parity bit counter
}
mask = mask << 1;
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
}
// receive parity
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
if (digitalRead(TP_DATA)) { // check if received parity is high
rcv_parity++; // increment the parity bit counter
}
rcv_parity = rcv_parity & 1; // mask off all bits except the lsb
if (rcv_parity == 0) { // check for bad (even) parity
touchpad_error = HIGH;
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
// stop bit
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
if (digitalRead(TP_DATA) == LOW) { // check if stop bit is bad (low)
// send bad stop bit to future error handler
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
if (watchdog >= timeout) { //check for infinite loop
touchpad_error = HIGH;
break; // break out of infinite loop
}
}
// Inhibit the bus so the tp only talks when the Teensy is listening
go_0(TP_CLK);
return rcv_data; // pass the received data back
}
//
// Function to decode 3 bytes of data from the touchpad = status, X Delta, Y Delta
//
char tp_packet(void)
{
// ******************************Receive Byte 0 = Status***********************
char rcv_data = 0; // initialize to zero
char mask = 1; // shift a 1 across the 8 bits to select where to load the data
char rcv_parity = 0; // count the ones received
//
unsigned int time_leftover = 24; // breakout of tp loop if timer is over this value in msec
elapsedMillis tp_timer; // zero the tp timer clock
//
go_pu(TP_CLK); // release the clock
go_pu(TP_DATA); // release the data
delayMicroseconds(5); // delay to let clock go high
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
if (tp_timer >= time_leftover) { //check if ready for next keyboard scan due to no tp activity
go_0(TP_CLK); // Inhibit the bus so the tp won't try to send data
return 1; // go back to main routine with a 1 signifying no tp data was received
}
}
if (digitalRead(TP_DATA)) { // Start bit s/b low from tp
// start bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
for (int k=0; k<8; k++) {
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // check if data is high
rcv_data = rcv_data | mask; // set the appropriate bit in the rcv data
rcv_parity++; // increment the parity bit counter
}
mask = mask << 1;
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
}
// receive parity
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // check if received parity is high
rcv_parity++; // increment the parity bit counter
}
rcv_parity = rcv_parity & 1; // mask off all bits except the lsb
if (rcv_parity == 0) { // check for bad (even) parity
// parity bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
// stop bit
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA) == LOW) { // check if stop bit is bad (low)
// stop bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
mstat = rcv_data; // save data result in status byte
// ******************************Receive Byte 1 = Delta X**************************
rcv_data = 0; // initialize to zero
mask = 1; // shift a 1 across the 8 bits to select where to load the data
rcv_parity = 0; // count the ones received
delayMicroseconds(5); // delay to let the clock stop ringing
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // Start bit s/b low from tp
// start bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
for (int k=0; k<8; k++) {
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // check if data is high
rcv_data = rcv_data | mask; // set the appropriate bit in the rcv data
rcv_parity++; // increment the parity bit counter
}
mask = mask << 1;
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
}
// receive parity
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // check if received parity is high
rcv_parity++; // increment the parity bit counter
}
rcv_parity = rcv_parity & 1; // mask off all bits except the lsb
if (rcv_parity == 0) { // check for bad (even) parity
// parity bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
// stop bit
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA) == LOW) { // check if stop bit is bad (low)
// stop bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
mx = rcv_data; // save data result in delta x byte
// Receive Byte 1 = Delta Y
// ******************************Receive Byte 2 = Delta Y**************************
rcv_data = 0; // initialize to zero
mask = 1; // shift a 1 across the 8 bits to select where to load the data
rcv_parity = 0; // count the ones received
delayMicroseconds(5); // delay to let the clock stop ringing
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // Start bit s/b low from tp
// start bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
for (int k=0; k<8; k++) {
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // check if data is high
rcv_data = rcv_data | mask; // set the appropriate bit in the rcv data
rcv_parity++; // increment the parity bit counter
}
mask = mask << 1;
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
}
// receive parity
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA)) { // check if received parity is high
rcv_parity++; // increment the parity bit counter
}
rcv_parity = rcv_parity & 1; // mask off all bits except the lsb
if (rcv_parity == 0) { // check for bad (even) parity
// parity bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
// stop bit
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == HIGH) { // loop until the clock goes low
}
if (digitalRead(TP_DATA) == LOW) { // check if stop bit is bad (low)
// stop bit not correct - put error handler here if desired
}
delayMicroseconds(1); // delay to let the clock settle out
while (digitalRead(TP_CLK) == LOW) { // loop until the clock goes high
}
my = rcv_data; // save data result in delta y byte
//
// Inhibit the bus so the tp only talks when we're listening
go_0(TP_CLK);
return 0;
}
//
void touchpad_init()
{
touchpad_error = LOW; // start with no error
go_pu(TP_CLK); // float the clock and data to touchpad
go_pu(TP_DATA);
// Sending reset command to touchpad
tp_write(0xff);
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
delay(1000); // wait 1 second so tp can run its self diagnostic
// verify proper response from tp
if (tp_read() != 0xaa) { // verify basic assurance test passed
touchpad_error = HIGH;
}
if (tp_read() != 0x00) { // verify basic assurance test passed
touchpad_error = HIGH;
}
// Send touchpad disable code so that the mode byte can be loaded next
tp_write(0xf5); // tp disable
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// Load Mode Byte with 00 using the following special sequence from page 38 of Synaptics Interfaceing Guide.
// Send set resolution to 0 four times followed by a set sample rate to 0x14
// The resolution and sample rate are not actually changed but instead it loads the mode byte.
// #1 set resolution
tp_write(0xe8); // set resolution (actually part of setting mode byte)
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
tp_write(0x00); // to zero
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// #2 set resolution (actually part of setting mode byte)
tp_write(0xe8); // set resolution
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
tp_write(0x00); // to zero
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// #3 set resolution
tp_write(0xe8); // set resolution
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
tp_write(0x00); // to zero
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// #4 set resolution (actually part of setting mode byte)
tp_write(0xe8); // set resolution
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
tp_write(0x00); // to zero
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// Set sample rate (actually part of setting mode byte)
tp_write(0xf3); // set sample rate
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
tp_write(0x14); // to 14 hex
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// This completes the mode byte load
// set the resolution for real
tp_write(0xe8); // Sending resolution command
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
tp_write(0x03); // value of 0x03 = 8 counts/mm resolution (default is 4 counts/mm)
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// set the sample rate for real
tp_write(0xf3); // Sending sample rate command
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
tp_write(0x28); // 0x28 = 40 samples per second, the default value used for Synaptics TP
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// Load stream mode command so tp will send data whenever it's available
tp_write(0xea); // stream mode
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
// Send touchpad enable code
tp_write(0xf4); // tp enable
if (tp_read() != 0xfa) { // verify correct ack byte
touchpad_error = HIGH;
}
}
//
//----------------------------------Setup before main loop-------------------------------------------
//
void setup() {
for (int a = 0; a < cols_max; a++) { // loop thru all keyboard column pins
go_pu(Col_IO[a]); // set each column pin as an input with a pullup
}
//
for (int b = 0; b < rows_max; b++) { // loop thru all keyboard row pins
go_z(Row_IO[b]); // set each row pin as a floating output
}
touchpad_init(); // reset tp and check that self diagnostic passed. Put tp in stream mode and enable it
//
}
//
boolean Fn_pressed = HIGH; // Active low, shows when the Fn key is pressed
extern volatile uint8_t keyboard_leds; // 8 bits sent from Host to Teensy that give keyboard LED status.
// declare and initialize touchpad variables
boolean over_flow; // Active high, set if x or y movement values are bad due to overflow
boolean left_button = 0; // Active high, on/off variable for left button is set if bit 0 of mstat is set
boolean right_button = 0; // Active high, on/off variable for right button is set if bit 1 of mstat is set
boolean old_left_button = 0; // Active high, on/off variable for left button status from the previous polling cycle
boolean old_right_button = 0; // Active high, on/off variable for right button status from the previous polling cycle
boolean button_change = 0; // Active high, shows when a touchpad left or right button has changed since the last polling cycle
//
//---------------------------------Main Loop---------------------------------------------
//
void loop() {
// Scan keyboard matrix with an outer loop that drives each row low and an inner loop that reads every column (with pull ups).
// The routine looks at each key's present state (by reading the column input pin) and also the previous state from the last scan
// that was 30msec ago. The status of a key that was just pressed or just released is sent over USB and the state is saved in the old_key matrix.
// The keyboard keys will read as logic low if they are pressed (negative logic).
// The old_key matrix also uses negative logic (low=pressed).
//
for (int x = 0; x < rows_max; x++) { // loop thru the rows
go_0(Row_IO[x]); // Activate Row (send it low)
delayMicroseconds(10); // give the row time to go low and settle out
for (int y = 0; y < cols_max; y++) { // loop thru the columns
//
// **********Modifier keys including the Fn special case
if (modifier[x][y] != 0) { // check if modifier key exists at this location in the array (a non-zero value)
if (!digitalRead(Col_IO[y]) && (old_key[x][y])) { // Read column to see if key is low (pressed) and was previously not pressed
if (modifier[x][y] != MODIFIERKEY_FN) { // Exclude Fn modifier key because Fn is not sent to USB host
load_mod(modifier[x][y]); // function reads which modifier key is pressed and loads it into the appropriate mod_... variable
send_mod(); // function sends the state of all modifier keys over usb including the one that just got pressed
old_key[x][y] = LOW; // Save state of key as "pressed"
}
else { // keep track of Fn key being pressed
Fn_pressed = LOW; // Fn status variable is active low
old_key[x][y] = LOW; // old_key state is "pressed" (active low)
}
}
else if (digitalRead(Col_IO[y]) && (!old_key[x][y])) { //check if key is not pressed and was previously pressed
if (modifier[x][y] != MODIFIERKEY_FN) { // Exclude Fn modifier key
clear_mod(modifier[x][y]); // function reads which modifier key was released and loads 0 into the appropriate mod_... variable
send_mod(); // function sends all mod's over usb including the one that was just released
old_key[x][y] = HIGH; // Save state of key as "not pressed"
}
else { // keep track of Fn key being released
Fn_pressed = HIGH; // Fn is no longer active
old_key[x][y] = HIGH; // old_key state is "not pressed"
}
}
}
// ***********end of modifier section
//
// ***********Normal keys, num lock, and media keys in this section
else if ((normal[x][y] != 0) || (media[x][y] != 0)) { // check if normal or media key exists at this location in the array
if (!digitalRead(Col_IO[y]) && (old_key[x][y]) && (!slots_full)) { // check if key pressed and not previously pressed and slots not full
old_key[x][y] = LOW; // Save state of key as "pressed"
if (Fn_pressed) { // Fn is not pressed and normal or num lock key needs to be sent
if (keyboard_leds & 1) { // test if Num Lock is turned on
load_slot(numlock[x][y]); //update first available slot with key name from numlock matrix
send_normals(); // send all slots over USB including the key that just got pressed
}
else { // Num Lock is not turned on so send normal key
load_slot(normal[x][y]); //update first available slot with normal key name
send_normals(); // send all slots over USB including the key that just got pressed
}
}
else if (media[x][y] != 0) { // Fn is pressed so send media if a key exists in the matrix
Keyboard.press(media[x][y]); // media key is sent using keyboard.press function per PJRC instructions
delay(5); // delay 5 milliseconds before releasing to make sure it gets sent over USB
Keyboard.release(media[x][y]); // send media key release
}
}
// Key release
else if (digitalRead(Col_IO[y]) && (!old_key[x][y])) { //check if key is not pressed, but was previously pressed
old_key[x][y] = HIGH; // Save state of key as "not pressed"
if (Fn_pressed) { // only clear the slot if the Fn key is not pressed
if (keyboard_leds & 1) { // test if Num Lock is turned on
clear_slot(numlock[x][y]); //clear slot with key name from numlock matrix
send_normals(); // send all slots over USB including the key that just got released
}
else {
clear_slot(normal[x][y]); //clear the slot that contains the normal key name
send_normals(); // send all slots over USB including the key that was just released
}
}
}
}
// **************end of normal, media, and backlight section
//
} // end of column loop
go_z(Row_IO[x]); // De-activate the current Row (send it to hi-z) so the next row can be activated
} // end of row loop
//
// **********Keyboard scan complete
//
// ***********Touchpad Section
//
if (touchpad_error == LOW) { // Only proceed if the touchpad was initialized correctly and passed its self test
//
if (tp_packet() == 0x00) { // tp_packet returned zero so data was received in mstat, mx, and my variables
if (((0x80 & mstat) == 0x80) || ((0x40 & mstat) == 0x40)) { // x or y overflow bits set?
over_flow = 1; // set the overflow flag
}
// change the x data from 9 bit to 8 bit 2's complement
mx = mx & 0x7f; // mask off 8th bit
if ((0x10 & mstat) == 0x10) { // move the sign into
mx = 0x80 | mx; // the 8th bit position
}
// change the y data from 9 bit to 8 bit 2's complement and then take the 2's complement
// because y movement on ps/2 format is opposite of touchpad.move function
my = my & 0x7f; // mask off 8th bit
if ((0x20 & mstat) == 0x20) { // move the sign into
my = 0x80 | my; // the 8th bit position
}
my = (~my + 0x01); // change the sign of y data by taking the 2's complement (invert and add 1)
// zero out mx and my if over_flow is set
if (over_flow) {
mx = 0x00; // data is bad due to the overflow so zero it out
my = 0x00;
}
// send the x and y data back via usb if either one is non-zero
if ((mx != 0x00) || (my != 0x00)) {
Mouse.move(mx,my);
}
//
// read the left and right button bits in the PS/2 status byte from the touchpad
if ((0x01 & mstat) == 0x01) { // if left button is set in the status byte
left_button = 1; // set the left button variable
}
else { // otherwise clear the left button variable
left_button = 0;
}
if ((0x02 & mstat) == 0x02) { // if right button is set in the status byte
right_button = 1; // set the right button variable
}
else { // otherwise clear right button variable
right_button = 0;
}
// Determine if the left or right touchpad buttons have changed since last polling cycle using xor
button_change = (left_button ^ old_left_button) | (right_button ^ old_right_button);
// Don't send button status if there's no change since last time.
if (button_change){
Mouse.set_buttons(left_button, 0, right_button); // send left, middle, and right button status
}
old_left_button = left_button; // remember button status for next polling cycle
old_right_button = right_button;
}
}
//
// End of touchpad routine
//
// Turn on or off the LEDs for Num Lock and Caps Lock based on bits 0 and 1 from the
// keyboard_leds variable returned by the host computer over USB. Sending the I/O pin low turns on the
// LED.
//
if (keyboard_leds & 1) { // mask off all bits but D0 and test if set
go_0(NUM_LOCK_N); // turn on the Num Lock LED
}
else {
go_1(NUM_LOCK_N); // turn off the Num Lock LED
}
//
//
if (keyboard_leds & 1<<1) { // mask off all bits but D1 and test if set
go_0(CAPS_LOCK_N); // turn on the Caps Lock LED
}
else {
go_1(CAPS_LOCK_N); // turn off the Caps Lock LED
}
//
// repeat loop at 30msec scan rate
}
| [
"noreply@github.com"
] | thedalles77.noreply@github.com |
39d8058d6647e407439fbdf9fe14e70517ba947d | 011913764ed71352da425f4864cf9d14132d4f36 | /sources/test-core/collider.cpp | 87e8f0ce0453e18366798639df607910f104b480 | [
"MIT"
] | permissive | iomeone/cage | 172f64a281b5818bf827518cec08b9ddca714cf4 | c8c34364ca19fc63b3572da73116cc175efa1a8d | refs/heads/master | 2023-03-25T16:38:51.323832 | 2021-03-25T02:37:53 | 2021-03-25T02:37:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,418 | cpp | #include "main.h"
#include <cage-core/geometry.h>
#include <cage-core/collider.h>
#include <cage-core/memoryBuffer.h>
void testColliders()
{
CAGE_TESTCASE("colliders");
{
CAGE_TESTCASE("basic collisions");
{
CAGE_TESTCASE("empty colliders");
Holder<Collider> c1 = newCollider();
Holder<Collider> c2 = newCollider();
CollisionDetectionParams p(c1.get(), c2.get());
CAGE_TEST(!collisionDetection(p));
}
{
CAGE_TESTCASE("no collision");
Holder<Collider> c1 = newCollider();
Holder<Collider> c2 = newCollider();
c1->addTriangle(triangle(vec3(-1, 0, 0), vec3(1, 0, 0), vec3(0, 2, 0)));
c2->addTriangle(triangle(vec3(-2, 0, 1), vec3(2, 0, 1), vec3(0, 3, 1)));
c1->rebuild();
c2->rebuild();
CollisionDetectionParams p(c1.get(), c2.get());
CAGE_TEST(!collisionDetection(p));
}
{
CAGE_TESTCASE("one collision");
Holder<Collider> c1 = newCollider();
Holder<Collider> c2 = newCollider();
c1->addTriangle(triangle(vec3(-1, 0, 0), vec3(1, 0, 0), vec3(0, 2, 0)));
c2->addTriangle(triangle(vec3(-2, 1, -5), vec3(0, 1, 5), vec3(2, 1, 0)));
c1->rebuild();
c2->rebuild();
CollisionDetectionParams p(c1.get(), c2.get());
CAGE_TEST(collisionDetection(p));
CAGE_TEST(p.collisionPairs.size() == 1);
CAGE_TEST(p.collisionPairs[0].a == 0);
CAGE_TEST(p.collisionPairs[0].b == 0);
}
{
CAGE_TESTCASE("self collision");
Holder<Collider> c1 = newCollider();
c1->addTriangle(triangle(vec3(-1, 0, 0), vec3(1, 0, 0), vec3(0, 2, 0)));
c1->addTriangle(triangle(vec3(-2, 0, 1), vec3(2, 0, 1), vec3(0, 3, 1)));
c1->addTriangle(triangle(vec3(-2, 1, -5), vec3(0, 1, 5), vec3(2, 1, 0)));
c1->rebuild();
CollisionDetectionParams p(c1.get(), c1.get());
CAGE_TEST(collisionDetection(p));
}
{
CAGE_TESTCASE("with transformation (no collision)");
Holder<Collider> c1 = newCollider();
c1->addTriangle(triangle(vec3(-1, 0, 0), vec3(1, 0, 0), vec3(0, 2, 0)));
c1->addTriangle(triangle(vec3(-2, 0, 1), vec3(2, 0, 1), vec3(0, 3, 1)));
c1->addTriangle(triangle(vec3(-2, 1, -5), vec3(0, 1, 5), vec3(2, 1, 0)));
c1->rebuild();
CollisionDetectionParams p(c1.get(), c1.get(), transform(), transform(vec3(20, 0, 0)));
CAGE_TEST(!collisionDetection(p));
}
{
CAGE_TESTCASE("with transformation (one collision)");
Holder<Collider> c1 = newCollider();
Holder<Collider> c2 = newCollider();
c1->addTriangle(triangle(vec3(-1, 0, 0), vec3(1, 0, 0), vec3(0, 2, 0)));
c2->addTriangle(triangle(vec3(-2, 0, 1), vec3(2, 0, 1), vec3(0, 3, 1)));
c1->rebuild();
c2->rebuild();
CollisionDetectionParams p(c1.get(), c2.get(), transform(), transform(vec3(), quat(degs(), degs(90), degs())));
CAGE_TEST(collisionDetection(p));
}
{
CAGE_TESTCASE("serialization");
Holder<Collider> c1 = newCollider();
c1->addTriangle(triangle(vec3(-1, 0, 0), vec3(1, 0, 0), vec3(0, 2, 0)));
c1->addTriangle(triangle(vec3(-2, 0, 1), vec3(2, 0, 1), vec3(0, 3, 1)));
c1->addTriangle(triangle(vec3(-2, 1, -5), vec3(0, 1, 5), vec3(2, 1, 0)));
Holder<PointerRange<char>> buff = c1->serialize();
Holder<Collider> c2 = newCollider();
c2->deserialize(buff);
CAGE_TEST(c2->triangles().size() == 3);
CAGE_TEST(c2->triangles()[2] == c1->triangles()[2]);
}
{
CAGE_TESTCASE("forgot rebuilt");
Holder<Collider> c1 = newCollider();
c1->addTriangle(triangle(vec3(-1, 0, 0), vec3(1, 0, 0), vec3(0, 2, 0)));
c1->addTriangle(triangle(vec3(-2, 0, 1), vec3(2, 0, 1), vec3(0, 3, 1)));
c1->addTriangle(triangle(vec3(-2, 1, -5), vec3(0, 1, 5), vec3(2, 1, 0)));
CollisionDetectionParams p(c1.get(), c1.get());
CAGE_TEST_ASSERTED(collisionDetection(p));
}
}
{
CAGE_TESTCASE("dynamic collisions");
Holder<Collider> c1 = newCollider();
{ // tetrahedron
const vec3 a(0, -0.7, 1);
const vec3 b(+0.86603, -0.7, -0.5);
const vec3 c(-0.86603, -0.7, -0.5);
const vec3 d(0, 0.7, 0);
c1->addTriangle(triangle(c, b, a));
c1->addTriangle(triangle(a, b, d));
c1->addTriangle(triangle(b, c, d));
c1->addTriangle(triangle(c, a, d));
c1->rebuild();
}
{
CAGE_TESTCASE("ensure static collision");
CollisionDetectionParams p(c1.get(), c1.get(), transform(vec3(-5, 0, 0), quat(), 7), transform(vec3(5, 0, 0), quat(), 7));
CAGE_TEST(collisionDetection(p));
}
{
CAGE_TESTCASE("tetrahedrons meet in the middle");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-5, 0, 0));
p.bt1 = transform(vec3(5, 0, 0));
p.at2 = transform();
p.bt2 = transform();
CAGE_TEST(collisionDetection(p));
CAGE_TEST(p.fractionBefore > 0 && p.fractionBefore < 1);
CAGE_TEST(p.fractionContact > 0 && p.fractionContact < 1);
CAGE_TEST(p.fractionBefore < p.fractionContact);
CAGE_TEST(!p.collisionPairs.empty());
}
{
CAGE_TESTCASE("tetrahedrons do not meet");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-5, 0, 0));
p.bt1 = transform(vec3(5, 0, 0));
p.at2 = transform(vec3(-5, 10, 0));
p.bt2 = transform(vec3(-5, 0, 0));
CAGE_TEST(!collisionDetection(p));
CAGE_TEST(!p.fractionBefore.valid());
CAGE_TEST(!p.fractionContact.valid());
CAGE_TEST(p.collisionPairs.empty());
}
{
CAGE_TESTCASE("tetrahedrons are very close");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-1, 0, 0));
p.bt1 = transform(vec3(1, 0, 0));
p.at2 = transform();
p.bt2 = transform();
CAGE_TEST(collisionDetection(p));
CAGE_TEST(p.fractionBefore > 0 && p.fractionBefore < 1);
CAGE_TEST(p.fractionContact > 0 && p.fractionContact < 1);
CAGE_TEST(p.fractionBefore < p.fractionContact);
CAGE_TEST(!p.collisionPairs.empty());
}
{
CAGE_TESTCASE("tetrahedrons are far apart");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-500, 0, 0));
p.bt1 = transform(vec3(500, 0, 0));
p.at2 = transform();
p.bt2 = transform();
CAGE_TEST(collisionDetection(p));
CAGE_TEST(p.fractionBefore > 0 && p.fractionBefore < 1);
CAGE_TEST(p.fractionContact > 0 && p.fractionContact < 1);
CAGE_TEST(p.fractionBefore < p.fractionContact);
CAGE_TEST(!p.collisionPairs.empty());
}
{
CAGE_TESTCASE("one tetrahedron is very large");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-500, 0, 0), quat(), 50);
p.bt1 = transform(vec3(5, 0, 0));
p.at2 = transform(vec3(), quat(), 50);
p.bt2 = transform();
CAGE_TEST(collisionDetection(p));
CAGE_TEST(p.fractionBefore > 0 && p.fractionBefore < 1);
CAGE_TEST(p.fractionContact > 0 && p.fractionContact < 1);
CAGE_TEST(p.fractionBefore < p.fractionContact);
CAGE_TEST(!p.collisionPairs.empty());
}
{
CAGE_TESTCASE("one tetrahedron is very small");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-5, 0, 0), quat(), 0.01);
p.bt1 = transform(vec3(5, 0, 0));
p.at2 = transform(vec3(), quat(), 0.01);
p.bt2 = transform();
CAGE_TEST(collisionDetection(p));
CAGE_TEST(p.fractionBefore > 0 && p.fractionBefore < 1);
CAGE_TEST(p.fractionContact > 0 && p.fractionContact < 1);
CAGE_TEST(p.fractionBefore < p.fractionContact);
CAGE_TEST(!p.collisionPairs.empty());
}
{
CAGE_TESTCASE("no dynamic change (no collision)");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-5, 0, 0));
p.bt1 = transform(vec3(5, 0, 0));
p.at2 = transform(vec3(-5, 0, 0));
p.bt2 = transform(vec3(5, 0, 0));
CAGE_TEST(!collisionDetection(p));
}
{
CAGE_TESTCASE("no dynamic change (with collision)");
CollisionDetectionParams p(c1.get(), c1.get());
p.at1 = transform(vec3(-0.5001, 0, 0));
p.bt1 = transform(vec3(0.5, 0, 0));
p.at2 = transform(vec3(-0.5, 0, 0));
p.bt2 = transform(vec3(0.5001, 0, 0));
CAGE_TEST(collisionDetection(p));
}
}
{
CAGE_TESTCASE("more collisions");
Holder<Collider> c1 = newCollider();
{ // tetrahedron 1
const vec3 a(0, -0.7, 1);
const vec3 b(+0.86603, -0.7, -0.5);
const vec3 c(-0.86603, -0.7, -0.5);
const vec3 d(0, 0.7, 0);
const mat4 off = mat4(vec3(10, 0, 0));
c1->addTriangle(triangle(c, b, a) * off);
c1->addTriangle(triangle(a, b, d) * off);
c1->addTriangle(triangle(b, c, d) * off);
c1->addTriangle(triangle(c, a, d) * off);
c1->rebuild();
}
Holder<Collider> c2 = newCollider();
{ // tetrahedron 2
const vec3 a(0, -0.7, 1);
const vec3 b(+0.86603, -0.7, -0.5);
const vec3 c(-0.86603, -0.7, -0.5);
const vec3 d(0, 0.7, 0);
const mat4 off = mat4(vec3(0, 10, 0));
c2->addTriangle(triangle(c, b, a) * off);
c2->addTriangle(triangle(a, b, d) * off);
c2->addTriangle(triangle(b, c, d) * off);
c2->addTriangle(triangle(c, a, d) * off);
c2->rebuild();
}
{
CAGE_TESTCASE("ensure static collision");
{
CollisionDetectionParams p(c1.get(), c2.get());
CAGE_TEST(!collisionDetection(p));
}
{
CollisionDetectionParams p(c1.get(), c2.get(), transform(vec3(-10, 9.5, 0)), transform());
CAGE_TEST(collisionDetection(p));
}
{
CollisionDetectionParams p(c1.get(), c2.get(), transform(), transform(vec3(), quat(degs(), degs(), degs(-90))));
CAGE_TEST(collisionDetection(p));
}
}
{
CAGE_TESTCASE("rotations");
{
CollisionDetectionParams p(c1.get(), c2.get());
p.bt1 = transform(vec3(), quat(degs(), degs(), degs(-100)));
p.bt2 = transform(vec3(), quat(degs(), degs(), degs(-80)));
CAGE_TEST(collisionDetection(p));
}
{
CollisionDetectionParams p(c1.get(), c2.get());
p.bt1 = transform(vec3(0.01, 0, 0), quat(degs(), degs(), degs(-80)));
p.bt2 = transform(vec3(), quat(degs(), degs(), degs(-100)));
CAGE_TEST(collisionDetection(p));
}
}
}
{
CAGE_TESTCASE("randomized tests with triangles");
Holder<Collider> tet = newCollider();
{
const vec3 a(0, -0.7, 1);
const vec3 b(+0.86603, -0.7, -0.5);
const vec3 c(-0.86603, -0.7, -0.5);
const vec3 d(0, 0.7, 0);
tet->addTriangle(triangle(c, b, a));
tet->addTriangle(triangle(a, b, d));
tet->addTriangle(triangle(b, c, d));
tet->addTriangle(triangle(c, a, d));
tet->rebuild();
}
uint32 attemptsA = 0, attemptsB = 0;
while (attemptsA < 5 || attemptsB < 5)
{
if (attemptsA + attemptsB > 1000)
{
CAGE_LOG_THROW(stringizer() + "A: " + attemptsA + ", B: " + attemptsB);
CAGE_THROW_ERROR(Exception, "too many test attempts");
}
const transform t1 = transform(randomDirection3() * randomChance() * 10, randomDirectionQuat(), randomChance() * 10 + 1);
const auto &trisTest = [&](const triangle &l)
{
bool res = false;
for (const triangle t : tet->triangles())
res = res || intersects(l, t * t1);
return res;
};
for (uint32 round = 0; round < 10; round++)
{
const triangle l = triangle(randomDirection3() * 10, randomDirection3() * 10, randomDirection3() * 10);
const bool whole = intersects(l, tet.get(), t1);
const bool individual = trisTest(l);
CAGE_TEST(whole == individual);
if (whole)
attemptsA++;
else
attemptsB++;
}
}
}
{
CAGE_TESTCASE("randomized tests with lines");
Holder<Collider> tet = newCollider();
{
const vec3 a(0, -0.7, 1);
const vec3 b(+0.86603, -0.7, -0.5);
const vec3 c(-0.86603, -0.7, -0.5);
const vec3 d(0, 0.7, 0);
tet->addTriangle(triangle(c, b, a));
tet->addTriangle(triangle(a, b, d));
tet->addTriangle(triangle(b, c, d));
tet->addTriangle(triangle(c, a, d));
tet->rebuild();
}
uint32 attemptsA = 0, attemptsB = 0;
while (attemptsA < 5 || attemptsB < 5)
{
if (attemptsA + attemptsB > 1000)
{
CAGE_LOG_THROW(stringizer() + "A: " + attemptsA + ", B: " + attemptsB);
CAGE_THROW_ERROR(Exception, "too many test attempts");
}
const transform t1 = transform(randomDirection3() * randomChance() * 10, randomDirectionQuat(), randomChance() * 10 + 1);
const auto &trisTest = [&](const line &l)
{
bool res = false;
for (const triangle t : tet->triangles())
res = res || intersects(l, t * t1);
return res;
};
for (uint32 round = 0; round < 10; round++)
{
const line l = makeLine(randomDirection3() * 10, randomDirection3() * 10);
const bool whole = intersects(l, tet.get(), t1);
const bool individual = trisTest(l);
CAGE_TEST(whole == individual);
if (whole)
attemptsA++;
else
attemptsB++;
}
}
}
}
| [
"malytomas@ucpu.cz"
] | malytomas@ucpu.cz |
9b0a96f2549700c3b40cc3e4be926a89892927c6 | e8a55a62158278b4f806e72207c3178c1d0c36e8 | /tools.h | 49e7e15c410d27e79e7f27900bb21b673b8668a4 | [] | no_license | jayshah19949596/Telenav-Sensor-Fusion | 18d0963a361519d7571d0182f5f7494bade91061 | 5c369db042ea4b3376d3492991b950206b39298b | refs/heads/master | 2020-03-14T10:06:44.175369 | 2018-05-12T22:24:10 | 2018-05-12T22:24:10 | 131,559,442 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,055 | h | #ifndef TOOLS_H_
#define TOOLS_H_
#include <vector>
// #include "Eigen"
#include "Eigen/Dense"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using namespace std;
class Tools {
public:
/**
* Constructor.
*/
Tools();
/**
* Destructor.
*/
virtual ~Tools();
vector<string> split(const string &s, char delim);
/**
* Generic function to display vector holding any data type
*/
template <typename T>
void disp_vect(const vector<T> & vect)
{
typename vector<T>::const_iterator it;
for (it = vect.begin() ; it != vect.end(); ++it)
{
std::cout << ' ' << *it;
}
std::cout << '\n';
}
void prepare_data(float &x, float &y, float &velocity, float &sensor, float &time, const vector<string> &data_vector);
/**
* Prepare Lidar and Radar Matrix for one iteration
* @param state_mat: Lidar Measurement Matrix or Radar Measurement matrix
* @param data_vector: line element of data txt file
*/
void prepare_mat(MatrixXd &state_mat,const vector<string> &data_vector);
};
#endif /* TOOLS_H_ */
| [
"jai.s@somaiya.edu"
] | jai.s@somaiya.edu |
971a1e1d1f5aacebae494b8f7203510f219b7b2e | 3b6054a8c8447ad7b658c3ad98d95aa2d5277008 | /start_project/Laghaim_Client/LetterBox.h | f7b1930b03b9015a6be4899557fc4285aaaac884 | [] | no_license | Topstack-first/20210521_directx_laghaim | 80261e1d25ade898ab18c878e46f8f922d62031f | 7f92bd76fb5e10af43cd26f6e23ae8781a29632c | refs/heads/main | 2023-05-09T14:19:52.082370 | 2021-05-25T22:22:16 | 2021-05-25T22:22:16 | 369,423,057 | 2 | 4 | null | null | null | null | UHC | C++ | false | false | 3,023 | h | #ifndef _LETTER_BOX_H_
#define _LETTER_BOX_H_
#include "Config.h"
#include "L_MultiEditBox.h"
#include "HanIme.h"
#define PROMPT_STRING "|"
#define PROMPT_TIME 800
#define CANDYFONT_SIZE 11
class CSurface;
typedef enum n_CandidatePos1
{
LETTER=0
} n_CandidatePos1;
class CLetterBox :public CHanIme
{
public:
CLetterBox();
virtual ~CLetterBox();
L_MultiEditBox m_MEBox;
bool m_read_only ;
int m_row;
int m_column;
void Init_MEBox(bool read_only, int row, int column);
HRESULT RestoreSurfaces();
void SetLetterFlag(bool flag);
void OnChar(UINT nChar);
bool OnKeyDown(CHAR cChar);
bool delChar();
void CursLMove(INT iState); //커서 왼쪽 이동
void CursRMove(INT iState); //커서 오른쪽이동
void CursUMove(INT iState); //커서 위로이동
void CursDMove(INT iState); //커서 아래이동
void LetterTableUpdate();//문자 테이블 업데이트
void GetLetterCursor(int cursor);//문자 테이블 커서위치
void LetterTableReset();
void Init(int x, int y, int len, COLORREF backColor, COLORREF foreColor,
BOOL nPassword = FALSE, n_CandidatePos1 n_candyPos = LETTER);
void SetFontSize(int fontSize = 9);
void DeleteRes();
void Draw();
void Draw(int, int, int);
void SetFont (int f_w, int f_h, char *fontname);
void DrawText();
void SetPos(int x, int y);
void SetSize(int width, int height);
void SetColor(COLORREF backColor, COLORREF foreColor);
void SetStringLength(int len);
BOOL IsInside(int x, int y);
void SetEnable(BOOL bEnable);
void ChangeColor(DWORD color);
//...........................수정부분
int GetEnable()
{
return m_bEnabled;
}
void ClearText();
char* GetStrBuf()
{
return m_pszStr;
}
//...................................
void SetText(char *str);
char* _StrDup();
// 메시지 처리 루틴
LRESULT MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
CSurface *m_pSurf;
CSurface *m_pPromptSurf;
// For Candidate
CSurface *m_pCandidateSurf;
CSurface *m_pBack_CandidateSurf;
CHAR m_cBuff[9][512];
INT m_iCandidateIndex;
INT m_iCandidateStart;
INT m_iCandidateEnd;
INT m_heightCandidate;
CSurface *m_pStatusSurf;
char *m_SpaceStr;
// char *m_MulLetterText[MaxRow];
int m_X;
int m_X2;
int m_Y;
int m_Width;
int m_Height;
HFONT m_Font;
HFONT m_CandyFont;
int m_FontSize;
int m_FontWidth;
int m_FontHeight;
COLORREF m_BackColor;
COLORREF m_ForeColor;
DWORD m_LastTime;
BOOL m_bShowPrompt;
BOOL m_bEnabled;
BOOL m_bDImeEnable;
void SetDImeEnable(BOOL bDImeEnable)
{
m_bDImeEnable = bDImeEnable;
};
BOOL GetDImeEnable()
{
return m_bDImeEnable;
};
// DIme
POINT m_po_ime, m_po_edit;
// For Japanese
void drawIMEString();
// bool getFontSize(LPSIZE pSize, HFONT hFont, LPCTSTR pText,INT iLength);
void drawCandidate();
void SetCandidatePos(int* x_pos, int* y_pos);
n_CandidatePos1 m_nCandidatePos;
void drawConversionStatus();
void CloseIMC();
bool getFontSize(LPSIZE pSize,HFONT hFont,LPCTSTR pText,INT iLength);
};
#endif // _LETTER_BOX_H_
| [
"topstack2020+first@gmail.com"
] | topstack2020+first@gmail.com |
3f8edde51509321eeb3a496edfbe06bfdf7cdd3a | a2d7649a795eaa6e212767c92b335838ddf2d80d | /kavya3.cpp | 5e286dd70a6425918485a4f4978cea96f0c2c383 | [] | no_license | kavyasuggala2424/kavya24 | 447c51788271c7e61977f3c661829f928e9f1e45 | 5a8eb7c476e7fdf1ed99ea7474a054532ae3dd5b | refs/heads/master | 2020-08-03T17:36:58.830196 | 2019-09-30T10:06:03 | 2019-09-30T10:06:03 | 211,830,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,420 | cpp | #include<iostream>
#include<conio.h>
using namespace std;
class student
{
public:
virtual void getdata()=0;
virtual void display()=0;
};
class engineering:public student
{
int r;
char n[10];
public:
void getdata()
{
cout<<"faculty->Engineering"<<endl;
cout<<"enter name";
cin>>n;
cout<<"enter roll";
cin>>r;
}
void display()
{
cout<<endl<<"name="<<n;
cout<<endl<<"roll="<<r<<endl<<endl;
}
};
class medicine:public student
{
int r;
char n[10];
public:
void getdata()
{ cout<<"Faculty->Medicine";
cout<<endl<<"enter name";
cin>>n;
cout<<"enter roll";
cin>>r;
}
void display()
{
cout<<endl<<"name="<<n;
cout<<endl<<"roll="<<r<<endl<<endl;
}
};
class science:public student
{
int r;
char n[10];
public:
void getdata()
{ cout<<"Faculty->Science";
cout<<endl<<"enter name";
cin>>n;
cout<<"enter roll";
cin>>r;
}
void display()
{
cout<<endl<<"name="<<n;
cout<<endl<<"roll="<<r<<endl<<endl;
}
};
void main()
{
clrscr();
student *ptr[3];
engineering e;
medicine m;
science s;
ptr[0]=&e;
ptr[0]->getdata();
ptr[0]->display();
ptr[1]=&m;
ptr[1]->getdata();
ptr[1]->display();
ptr[2]=&s;
ptr[2]->getdata();
ptr[2]->display();
getch();
}
| [
"noreply@github.com"
] | kavyasuggala2424.noreply@github.com |
ae59df5baad76175d8495c9edf1ef955b00f3e9f | ba6a494d2e0cb473044e1ca9fb12bd93f55b90c6 | /XmWarn.cc | bc8267f158f4b21716a78f75dfcce1d490dea639 | [
"Apache-2.0"
] | permissive | NCAR/libraf | c1f1edc8464c70b21e9291a8b1d668aba521d0ed | 6ace16509d323146a40f246a8fd726ff211640cb | refs/heads/master | 2023-08-03T23:15:43.772913 | 2023-08-01T19:52:22 | 2023-08-01T19:52:22 | 85,247,844 | 0 | 2 | null | 2022-05-20T21:15:32 | 2017-03-16T22:39:53 | C++ | UTF-8 | C++ | false | false | 1,598 | cc | /*
-------------------------------------------------------------------------
OBJECT NAME: XmWarn.c
FULL NAME: Show Warning Box with Message
DESCRIPTION: CreateWarn should be called once where you initialize
your X stuff. To use just call WarnUser(ErrMsg, callBack)
INPUT: String to Display. Callback to call if user hits OK.
OUTPUT: Warning message in its own tidy little window.
AUTHOR: websterc@ncar
-------------------------------------------------------------------------
*/
#include "XmWarn.h"
/* -------------------------------------------------------------------- */
XmWarn::XmWarn(Widget parent, const char warning[], XtCallbackProc okCB, XtCallbackProc cancelCB)
{
Widget label;
Arg args[5];
XmString xStr;
warnBox = XmCreateWarningDialog(parent, const_cast<char *>("warnBox"), NULL, 0);
XtSetSensitive(XmMessageBoxGetChild(warnBox, XmDIALOG_HELP_BUTTON), false);
label = XmMessageBoxGetChild(warnBox, XmDIALOG_MESSAGE_LABEL);
xStr = XmStringCreateLtoR(const_cast<char *>(warning), XmSTRING_DEFAULT_CHARSET);
XtSetArg(args[0], XmNlabelString, xStr);
XtSetValues(label, args, 1);
XmStringFree(xStr);
if (okCB)
XtAddCallback(warnBox, XmNokCallback, (XtCallbackProc)okCB, NULL);
if (cancelCB)
XtAddCallback(warnBox, XmNcancelCallback, (XtCallbackProc)cancelCB, NULL);
XtAddCallback(warnBox,XmNokCallback,(XtCallbackProc)XtDestroyWidget, NULL);
XtAddCallback(warnBox,XmNcancelCallback,(XtCallbackProc)XtDestroyWidget,NULL);
XtManageChild(warnBox);
XtPopup(XtParent(warnBox), XtGrabNone);
} /* END CONTRUCTOR */
/* END XMWARN.C */
| [
"cjw@ucar.edu"
] | cjw@ucar.edu |
94411dcfea298353ef843484a0bfb4fb1a35a6eb | 8a738b641e73ad5a7c51859a798c6d1c9a57d00c | /Converter/Converter.cpp | f7ec758fb51b01b4576588f7b0a9d019f2ae4625 | [] | no_license | guri0631/Remote-Code-Project-Management | 9e3b3657c0f00a65f5de72b830b33d61c120d53c | add419721bae9c47ff1be9369c7ce9c1a795d358 | refs/heads/master | 2020-08-18T23:50:16.620641 | 2019-10-17T17:49:10 | 2019-10-17T17:49:10 | 215,843,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,119 | cpp | ///////////////////////////////////////////////////////////////////////////
// Converter.cpp : implements and provides test stub for Converter.h //
// ver 2.0 //
// //
// Application : OOD-S19 Instructor Solution //
// Platform : Visual Studio Community 2017, Windows 10 Pro x64 //
// Author : Ammar Salman, Syracuse University //
// 313/788-4694, assalman@syr.edu //
///////////////////////////////////////////////////////////////////////////
#include "Converter.h"
#include "../Logger/Logger.h"
#include "../FileSystem/FileSystem.h"
using namespace FileSystem;
using namespace LoggingNew;
// -----< default ctor >--------------------------------------------------
CodeConverter::CodeConverter()
{
}
// -----< ctor to set dep table >-----------------------------------------
CodeConverter::CodeConverter(const DependencyTable & dt) : dt_(dt)
{
LoggerDebug::write("\n CodeConverter initialized with DependencyTable\n");
}
// -----< set dependency table function >---------------------------------
void CodeConverter::setDepTable(const DependencyTable & dt)
{
dt_ = dt;
}
void CodeConverter::setFileLineInfo(const FileLineInfo & info)
{
fileLineInfo_ = info;
}
// -----< convert pre-set dependency table >------------------------------
std::vector<std::string> CodeConverter::convert()
{
if (!createOutpurDir()) {
LoggerDebug::write("\n\n Failed to start conversion due to inability to create output directory");
LoggerDebug::write("\n -- Output Directory: " + Path::getFullFileSpec(outputDir_));
return std::vector<std::string>();
}
LoggerDemo::write("\n\n Converting files to webpages");
LoggerDebug::write("\n\n Converting files to webpages");
LoggerDebug::write("\n Output directory: " + Path::getFullFileSpec(outputDir_));
LoggerDemo::write("\n Output directory: " + Path::getFullFileSpec(outputDir_));
for (auto entry : dt_) {
if (convertFile(entry.first)) {
LoggerDemo::write("\n -- Converted: ");
LoggerDebug::write("\n -- Converted: ");
}
else {
LoggerDemo::write("\n -- Failed: ");
LoggerDebug::write("\n -- Failed: ");
}
std::string filename = Path::getName(entry.first);
LoggerDebug::write(filename);
LoggerDemo::write(filename);
}
LoggerDebug::write("\n");
LoggerDemo::write("\n");
return convertedFiles_;
}
// -----< convert single file given path >----------------------------------
std::string CodeConverter::convert(const std::string & filepath)
{
if (!createOutpurDir()) {
LoggerDebug::write("\n\n Failed to start conversion due to inability to create output directory");
LoggerDebug::write("\n -- Output Directory: " + Path::getFullFileSpec(outputDir_));
return "";
}
LoggerDemo::write("\n\n Converting files to webpages");
LoggerDebug::write("\n\n Converting files to webpages");
LoggerDebug::write("\n Output directory: " + Path::getFullFileSpec(outputDir_));
LoggerDemo::write("\n Output directory: " + Path::getFullFileSpec(outputDir_));
if (convertFile(filepath)) {
LoggerDemo::write("\n -- Converted: ");
LoggerDebug::write("\n -- Converted: ");
}
else {
LoggerDemo::write("\n -- Failed: ");
LoggerDebug::write("\n -- Failed: ");
}
std::string filename = Path::getName(filepath);
LoggerDebug::write(filename);
LoggerDemo::write(filename);
return filename + ".html";
}
std::vector<std::string> CodeConverter::convert(const std::vector<std::string>& files)
{
clear();
//dt_ = DependencyTable(files);
return convert();
}
// -----< get set output directory >----------------------------------------
const std::string & CodeConverter::outputDir() const
{
return outputDir_;
}
// -----< set output directory >--------------------------------------------
void CodeConverter::outputDir(const std::string & dir)
{
outputDir_ = dir;
}
// -----< create output directory >-----------------------------------------
/* returns success of creation. it could fail if dir is sys protected */
bool CodeConverter::createOutpurDir()
{
if (!Directory::exists(outputDir_)) {
LoggerDebug::write("\n Creating output directory. Path: " + Path::getFullFileSpec(outputDir_));
return Directory::create(outputDir_);
}
LoggerDebug::write("\n Output directory already exists. Proceeding...");
return true;
}
// -----< get list of converted files >-------------------------------------
const std::vector<std::string> CodeConverter::convertedFiles() const
{
return convertedFiles_;
}
void CodeConverter::clear()
{
convertedFiles_.clear();
//dt_.clear();
}
// -----< private - read file and create webpage >--------------------------
bool CodeConverter::convertFile(std::string file)
{
std::ifstream in(file);
if (!in.is_open() || !in.good()) {
LoggerDebug::write("Error -- unable to read file, path may be invalid.");
in.close();
return false;
}
std::string filename = Path::getName(file);
std::string outputPath = outputDir_ + filename + ".html";
out_.open(outputPath, std::ofstream::out);
if (!out_.is_open() || !out_.good()) {
LoggerDebug::write("Error -- unable to open output file for writing.");
in.close();
return false;
}
// write everything to file
addPreCodeHTML(filename);
addDependencyLinks(file);
addPreTag();
size_t lineCount = 1;
while (in.good()) {
std::string line;
while (std::getline(in, line)) {
skipSpecialChars(line);
handleSLComment(line);
handleMLComment(line);
handleScopeInfo(file, lineCount, line);
out_ << line << std::endl;
lineCount++;
}
}
addClosingTags();
out_.close();
convertedFiles_.push_back(outputPath);
return true;
}
// -----< private - add generic HTML preliminary markup >-------------------
void CodeConverter::addPreCodeHTML(const std::string& title)
{
out_ << "<DOCTYPE !HTML>" << std::endl;
out_ << "<html>" << std::endl;
out_ << " <head>" << std::endl;
out_ << " <Title>" << title << "</Title>" << std::endl;
out_ << " <script src=\"script.js\"></script>" << std::endl;
out_ << " <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">" << std::endl;
out_ << " </head>" << std::endl << std::endl;
out_ << " <body>" << std::endl;
out_ << " <span class=\"absolute\">" << std::endl;
out_ << " <label><input type=\"checkbox\" id =\"hideF\" value=\"hidefuncs\" checked=\"true\" onclick=\"toggleVisibility('function')\">Functions</label><br>" << std::endl;
out_ << " <label><input type=\"checkbox\" id =\"hideC\" value=\"hideclass\" checked=\"true\" onclick=\"toggleVisibility('class')\">Classes</label><br>" << std::endl;
out_ << " <label><input type=\"checkbox\" id =\"hidec\" value=\"hidecomms\" checked=\"true\" onclick=\"toggleVisibility('comment')\">Comments</label><br>" << std::endl;
out_ << " </span>" << std::endl;
}
// -----< private - add pre tag >------------------------------------------
/* seperated into seperate function to allow for dependencies addition
* before the actual code of the file */
void CodeConverter::addPreTag()
{
out_ << " <pre>" << std::endl;
}
// -----< private - add depedency links markup code >----------------------
void CodeConverter::addDependencyLinks(std::string file)
{
std::string filename = Path::getName(file);
if (!dt_.has(file)) { // in case of single file conversion
LoggerDebug::write("\n No entry found in DependencyTable for [" + filename + "]. Skipping dependency links..");
return;
}
if (dt_[file].size() == 0) { // in case the file has no dependencies
LoggerDebug::write("\n No dependencies found for [" + filename + "]. Skipping dependency links..");
return;
}
out_ << " <h3>Dependencies: " << std::endl;
for (auto dep : dt_[file]) {
out_ << " <a href=\"" << Path::getName(dep) << ".html\">" << Path::getName(dep) << "</a>" << std::endl;
}
out_ << " </h3>";
}
// -----< private - add generic HTML markup closing tags >-----------------
void CodeConverter::addClosingTags()
{
out_ << " </pre>" << std::endl;
out_ << " </body>" << std::endl;
out_ << "</html>" << std::endl;
}
// -----< private - replace HTML special chars >---------------------------
/* note: the function uses while loop to make sure ALL special characters
* are replaced instead of just the first encounter. */
void CodeConverter::skipSpecialChars(std::string & line)
{
size_t pos = line.npos;
while((pos = line.find('<')) != line.npos)
line.replace(pos, 1, "<");
while ((pos = line.find('>')) != line.npos)
line.replace(pos, 1, ">");
}
// -----< private - wrap single line comments with span tag >--------------
/* wraps multiple single-line comments into one tag with 'comments' class*/
void CodeConverter::handleSLComment(std::string & line)
{
static bool ongoing = false; // to wrap continious SL comments in a single tag
size_t pos = line.npos;
pos = line.find('/');
if (pos == line.npos || pos == line.size() - 1) {
if (ongoing) { // if the wrap is already started, end the tag
line = "</span>" + line;
}
ongoing = false;
return;
}
// if it's the first comment in the sequence, add the tag
if (line[pos + 1] == '/' && !ongoing) {
line.insert(pos, "<span class=\"comment\">");
ongoing = true;
}
}
// -----< private - handle multi-line comments >---------------------------
/* wraps slash-star to star-slash comments in comment tag
* while loops are used for output correctness */
void CodeConverter::handleMLComment(std::string & line)
{
std::string commentTag = "<span class=\"comment\">";
std::string cTagEnd = "</span>";
size_t pos = 0;
pos = line.find("/*");
while (pos != line.npos) {
line.insert(pos, commentTag);
pos = line.find("/*", pos + 2 + commentTag.size());
}
pos = 0;
pos = line.find("*/");
while (pos != line.npos) {
if (pos + 2 == line.size()) line += cTagEnd;
else line.insert(pos + 2, cTagEnd);
pos = line.find("*/", pos + 2 + cTagEnd.size());
}
}
// ------< private - handle scope info >-----------------------------------
/* marks the begginings and endings of classes and functions with tags*/
void CodeConverter::handleScopeInfo(std::string filepath, size_t lineCount, std::string & line)
{
if (fileLineInfo_.find(filepath) == fileLineInfo_.end()) return;
LineInfo& info = fileLineInfo_[filepath];
if (info.find(lineCount) == info.end()) return;
size_t pos = 0;
for (auto scopeInfo : info[lineCount]) {
if (scopeInfo == LineIndentifier::classBegin) {
pos = line.find('{', pos);
if (pos != line.npos)
line.insert(pos, "<span class=\"class\">");
else pos = 0;
}
if (scopeInfo == LineIndentifier::functionBegin) {
pos = line.find('{', pos);
if (pos != line.npos)
line.insert(pos, "<span class=\"function\">");
else pos = 0;
}
if (scopeInfo == LineIndentifier::scopeEnd) {
pos = line.find('}', pos);
if (pos != line.npos) {
if (pos + 1 == line.size()) line += "</span>";
else line.insert(pos, "</span>");
}
else pos = 0;
}
}
}
#ifdef TEST_CONVERTER
// -----< test stub for converter class >-----------------------------------
int main() {
LoggerDebug::attach(&std::cout);
LoggerDebug::start();
LoggerDebug::title("Testing CodeConverter functions");
LoggerDebug::stop(); // do not log DependencyTable logs
DependencyTable dt;
dt.addDependency("Converter.h", "Converter.cpp");
dt.addDependency("Converter.cpp", "Converter.h");
dt.addDependency("A.h", "A.h");
LoggerDebug::start(); // log from now on
CodeConverter cc(dt);
dt.display();
LoggerDebug::write("\n");
//cc.outputDir("C:\\windows\\system32\\"); // will trigger errors which are handled
cc.convert();
LoggerDebug::stop();
return 0;
}
#endif | [
"noreply@github.com"
] | guri0631.noreply@github.com |
a3e009ce0ee894f8f943a205e24cec706e4f9c0f | 43eac29d84044cd6642c3e493746c2419ed0d8cf | /src/yb/client/snapshot_test_base.cc | 211187872da022cf747bebd7f97d9439633f2c04 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"OpenSSL"
] | permissive | alekseiko97/yugabyte-db | f5f109c171933ee08180a9e3a9259e7005ba7271 | 932cf02761e35b3e1b5a5dcbcf9bfe11d5ed61b3 | refs/heads/master | 2023-04-05T03:13:36.845465 | 2021-04-10T09:21:09 | 2021-04-10T09:21:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,952 | cc | // Copyright (c) YugaByte, 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 "yb/client/snapshot_test_base.h"
using namespace std::literals;
namespace yb {
namespace client {
master::MasterBackupServiceProxy SnapshotTestBase::MakeBackupServiceProxy() {
return master::MasterBackupServiceProxy(
&client_->proxy_cache(), cluster_->leader_mini_master()->bound_rpc_addr());
}
Result<master::SysSnapshotEntryPB::State> SnapshotTestBase::SnapshotState(
const TxnSnapshotId& snapshot_id) {
auto snapshots = VERIFY_RESULT(ListSnapshots(snapshot_id));
if (snapshots.size() != 1) {
return STATUS_FORMAT(RuntimeError, "Wrong number of snapshots, one expected but $0 found",
snapshots.size());
}
LOG(INFO) << "Snapshot state: " << snapshots[0].ShortDebugString();
return snapshots[0].entry().state();
}
Result<bool> SnapshotTestBase::IsSnapshotDone(const TxnSnapshotId& snapshot_id) {
return VERIFY_RESULT(SnapshotState(snapshot_id)) == master::SysSnapshotEntryPB::COMPLETE;
}
Result<Snapshots> SnapshotTestBase::ListSnapshots(
const TxnSnapshotId& snapshot_id, bool list_deleted) {
master::ListSnapshotsRequestPB req;
master::ListSnapshotsResponsePB resp;
req.set_list_deleted_snapshots(list_deleted);
if (!snapshot_id.IsNil()) {
req.set_snapshot_id(snapshot_id.data(), snapshot_id.size());
}
rpc::RpcController controller;
controller.set_timeout(60s);
RETURN_NOT_OK(MakeBackupServiceProxy().ListSnapshots(req, &resp, &controller));
if (resp.has_error()) {
return StatusFromPB(resp.error().status());
}
LOG(INFO) << "Snapshots: " << resp.ShortDebugString();
return std::move(resp.snapshots());
}
CHECKED_STATUS SnapshotTestBase::VerifySnapshot(
const TxnSnapshotId& snapshot_id, master::SysSnapshotEntryPB::State state) {
auto snapshots = VERIFY_RESULT(ListSnapshots());
SCHECK_EQ(snapshots.size(), 1, IllegalState, "Wrong number of snapshots");
const auto& snapshot = snapshots[0];
auto listed_snapshot_id = VERIFY_RESULT(FullyDecodeTxnSnapshotId(snapshot.id()));
if (listed_snapshot_id != snapshot_id) {
return STATUS_FORMAT(
IllegalState, "Wrong snapshot id returned $0, expected $1", listed_snapshot_id,
snapshot_id);
}
if (snapshot.entry().state() != state) {
return STATUS_FORMAT(
IllegalState, "Wrong snapshot state: $0 vs $1",
master::SysSnapshotEntryPB::State_Name(snapshot.entry().state()),
master::SysSnapshotEntryPB::State_Name(state));
}
size_t num_namespaces = 0, num_tables = 0, num_tablets = 0;
for (const auto& entry : snapshot.entry().entries()) {
switch (entry.type()) {
case master::SysRowEntry::TABLET:
++num_tablets;
break;
case master::SysRowEntry::TABLE:
++num_tables;
break;
case master::SysRowEntry::NAMESPACE:
++num_namespaces;
break;
default:
return STATUS_FORMAT(
IllegalState, "Unexpected entry type: $0",
master::SysRowEntry::Type_Name(entry.type()));
}
}
SCHECK_EQ(num_namespaces, 1, IllegalState, "Wrong number of namespaces");
SCHECK_EQ(num_tables, 1, IllegalState, "Wrong number of tables");
SCHECK_EQ(num_tablets, table_.table()->GetPartitionCount(), IllegalState,
"Wrong number of tablets");
return Status::OK();
}
CHECKED_STATUS SnapshotTestBase::WaitSnapshotInState(
const TxnSnapshotId& snapshot_id, master::SysSnapshotEntryPB::State state,
MonoDelta duration) {
auto state_name = master::SysSnapshotEntryPB::State_Name(state);
master::SysSnapshotEntryPB::State last_state = master::SysSnapshotEntryPB::UNKNOWN;
auto status = WaitFor([this, &snapshot_id, state, &last_state]() -> Result<bool> {
last_state = VERIFY_RESULT(SnapshotState(snapshot_id));
return last_state == state;
}, duration * kTimeMultiplier, "Snapshot in state " + state_name);
if (!status.ok() && status.IsTimedOut()) {
return STATUS_FORMAT(
IllegalState, "Wrong snapshot state: $0, while $1 expected",
master::SysSnapshotEntryPB::State_Name(last_state), state_name);
}
return status;
}
CHECKED_STATUS SnapshotTestBase::WaitSnapshotDone(
const TxnSnapshotId& snapshot_id, MonoDelta duration) {
return WaitSnapshotInState(snapshot_id, master::SysSnapshotEntryPB::COMPLETE, duration);
}
Result<TxnSnapshotRestorationId> SnapshotTestBase::StartRestoration(
const TxnSnapshotId& snapshot_id, HybridTime restore_at,
int64_t interval) {
master::RestoreSnapshotRequestPB req;
master::RestoreSnapshotResponsePB resp;
rpc::RpcController controller;
controller.set_timeout(60s);
req.set_snapshot_id(snapshot_id.data(), snapshot_id.size());
if (interval != 0) {
req.set_restore_interval(interval);
} else if (restore_at) {
req.set_restore_ht(restore_at.ToUint64());
}
RETURN_NOT_OK(MakeBackupServiceProxy().RestoreSnapshot(req, &resp, &controller));
return FullyDecodeTxnSnapshotRestorationId(resp.restoration_id());
}
Result<bool> SnapshotTestBase::IsRestorationDone(const TxnSnapshotRestorationId& restoration_id) {
master::ListSnapshotRestorationsRequestPB req;
master::ListSnapshotRestorationsResponsePB resp;
req.set_restoration_id(restoration_id.data(), restoration_id.size());
auto deadline = CoarseMonoClock::now() + 60s;
for (;;) {
rpc::RpcController controller;
controller.set_deadline(deadline);
RETURN_NOT_OK(MakeBackupServiceProxy().ListSnapshotRestorations(req, &resp, &controller));
LOG(INFO) << "Restoration: " << resp.ShortDebugString();
if (!resp.has_status()) {
break;
}
auto status = StatusFromPB(resp.status());
if (!status.IsServiceUnavailable()) {
return status;
}
}
if (resp.restorations().size() != 1) {
return STATUS_FORMAT(RuntimeError, "Wrong number of restorations, one expected but $0 found",
resp.restorations().size());
}
return resp.restorations(0).entry().state() == master::SysSnapshotEntryPB::RESTORED;
}
Status SnapshotTestBase::RestoreSnapshot(
const TxnSnapshotId& snapshot_id, HybridTime restore_at,
int64_t interval) {
auto restoration_id = VERIFY_RESULT(StartRestoration(snapshot_id, restore_at, interval));
return WaitFor([this, &restoration_id] {
return IsRestorationDone(restoration_id);
}, kWaitTimeout * kTimeMultiplier, "Restoration done");
}
} // namespace client
} // namespace yb
| [
"spolitov@gmail.com"
] | spolitov@gmail.com |
7164074b8d136762b25abdcc8c623a18fba2316e | 82b0bd2ce7a71a0bd023faf859c5daf46612460f | /fibo_huge/main.cpp | 9dfe64ec0dbf68e506b9d556e02dbaa9439a4311 | [] | no_license | kushagrasgupta/Algorithm.Toolbox-Submissions | 11530a475133c0e0038637174f5181db19069bdb | 5af87bbadc2cfc7caf4f25a0e90a505fc9b0bf82 | refs/heads/master | 2022-12-27T15:42:05.489990 | 2020-09-14T18:45:34 | 2020-09-14T18:45:34 | 293,044,265 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | #include <iostream>
using namespace std;
typedef long long int ll;
ll get_pisano_period(ll m) {
ll a = 0, b = 1, c = 0;
for (int i = 0; i < m * m; i++) {
c = (a + b) % m;
a = b;
b = c;
if (a == 0 && b == 1) return i + 1;
}
}
ll get_fibonacci_huge(ll n, ll m) {
ll r=n%(get_pisano_period( m));
ll f[r]={0};
f[0]=0;
f[1]=1;
for(int i=2;i<=r;i++)
{
f[i]=(f[i-1]+f[i-2])%m;
}
ll res=f[r];
return res;
}
int main() {
ll n, m;
cin >> n >> m;
cout << get_fibonacci_huge(n, m) << '\n';
}
| [
"kushagrasgupta@gmail.com"
] | kushagrasgupta@gmail.com |
3219afe0219e976518cf633e6d4912b34e78c2b9 | 4a0b46be4c27d82423b692cb90065a16ee0c4bcb | /admin/winning_teams/strongAccept/code/impl/sparsehash/internal/densehashtable.h | 597fce7409980a58b0f930971085a86da61a8918 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | isj/sigmod | 099fb53086833481ad4a74e4182fb6ec450ce8f4 | 8ffd3c50ac288aa12c05218d52b1f05eeb23a085 | refs/heads/master | 2016-09-06T17:17:13.729937 | 2013-12-14T12:57:50 | 2013-12-14T12:57:50 | 13,883,231 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,223 | h | // Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
//
// A dense hashtable is a particular implementation of
// a hashtable: one that is meant to minimize memory allocation.
// It does this by using an array to store all the data. We
// steal a value from the key space to indicate "empty" array
// elements (ie indices where no item lives) and another to indicate
// "deleted" elements.
//
// (Note it is possible to change the value of the delete key
// on the fly; you can even remove it, though after that point
// the hashtable is insert_only until you set it again. The empty
// value however can't be changed.)
//
// To minimize allocation and pointer overhead, we use internal
// probing, in which the hashtable is a single table, and collisions
// are resolved by trying to insert again in another bucket. The
// most cache-efficient internal probing schemes are linear probing
// (which suffers, alas, from clumping) and quadratic probing, which
// is what we implement by default.
//
// Type requirements: value_type is required to be Copy Constructible
// and Default Constructible. It is not required to be (and commonly
// isn't) Assignable.
//
// You probably shouldn't use this code directly. Use dense_hash_map<>
// or dense_hash_set<> instead.
// You can change the following below:
// HT_OCCUPANCY_PCT -- how full before we double size
// HT_EMPTY_PCT -- how empty before we halve size
// HT_MIN_BUCKETS -- default smallest bucket size
//
// You can also change enlarge_factor (which defaults to
// HT_OCCUPANCY_PCT), and shrink_factor (which defaults to
// HT_EMPTY_PCT) with set_resizing_parameters().
//
// How to decide what values to use?
// shrink_factor's default of .4 * OCCUPANCY_PCT, is probably good.
// HT_MIN_BUCKETS is probably unnecessary since you can specify
// (indirectly) the starting number of buckets at construct-time.
// For enlarge_factor, you can use this chart to try to trade-off
// expected lookup time to the space taken up. By default, this
// code uses quadratic probing, though you can change it to linear
// via JUMP_ below if you really want to.
//
// From http://www.augustana.ca/~mohrj/courses/1999.fall/csc210/lecture_notes/hashing.html
// NUMBER OF PROBES / LOOKUP Successful Unsuccessful
// Quadratic collision resolution 1 - ln(1-L) - L/2 1/(1-L) - L - ln(1-L)
// Linear collision resolution [1+1/(1-L)]/2 [1+1/(1-L)2]/2
//
// -- enlarge_factor -- 0.10 0.50 0.60 0.75 0.80 0.90 0.99
// QUADRATIC COLLISION RES.
// probes/successful lookup 1.05 1.44 1.62 2.01 2.21 2.85 5.11
// probes/unsuccessful lookup 1.11 2.19 2.82 4.64 5.81 11.4 103.6
// LINEAR COLLISION RES.
// probes/successful lookup 1.06 1.5 1.75 2.5 3.0 5.5 50.5
// probes/unsuccessful lookup 1.12 2.5 3.6 8.5 13.0 50.0 5000.0
#ifndef _DENSEHASHTABLE_H_
#define _DENSEHASHTABLE_H_
#include <sparsehash/internal/sparseconfig.h>
#include <assert.h>
#include <stdio.h> // for FILE, fwrite, fread
#include <algorithm> // For swap(), eg
#include <iterator> // For iterator tags
#include <limits> // for numeric_limits
#include <memory> // For uninitialized_fill
#include <utility> // for pair
#include <sparsehash/internal/hashtable-common.h>
#include <sparsehash/internal/libc_allocator_with_realloc.h>
#include <sparsehash/type_traits.h>
#include <stdexcept> // For length_error
_START_GOOGLE_NAMESPACE_
namespace base { // just to make google->opensource transition easier
using GOOGLE_NAMESPACE::true_type;
using GOOGLE_NAMESPACE::false_type;
using GOOGLE_NAMESPACE::integral_constant;
using GOOGLE_NAMESPACE::is_same;
using GOOGLE_NAMESPACE::remove_const;
}
// The probing method
// Linear probing
// #define JUMP_(key, num_probes) ( 1 )
// Quadratic probing
#define JUMP_(key, num_probes) ( num_probes )
// Hashtable class, used to implement the hashed associative containers
// hash_set and hash_map.
// Value: what is stored in the table (each bucket is a Value).
// Key: something in a 1-to-1 correspondence to a Value, that can be used
// to search for a Value in the table (find() takes a Key).
// HashFcn: Takes a Key and returns an integer, the more unique the better.
// ExtractKey: given a Value, returns the unique Key associated with it.
// Must inherit from unary_function, or at least have a
// result_type enum indicating the return type of operator().
// SetKey: given a Value* and a Key, modifies the value such that
// ExtractKey(value) == key. We guarantee this is only called
// with key == deleted_key or key == empty_key.
// EqualKey: Given two Keys, says whether they are the same (that is,
// if they are both associated with the same Value).
// Alloc: STL allocator to use to allocate memory.
template <class Value, class Key, class HashFcn,
class ExtractKey, class SetKey, class EqualKey, class Alloc>
class dense_hashtable;
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
struct dense_hashtable_iterator;
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
struct dense_hashtable_const_iterator;
// We're just an array, but we need to skip over empty and deleted elements
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
struct dense_hashtable_iterator {
private:
typedef typename A::template rebind<V>::other value_alloc_type;
public:
typedef dense_hashtable_iterator<V,K,HF,ExK,SetK,EqK,A> iterator;
typedef dense_hashtable_const_iterator<V,K,HF,ExK,SetK,EqK,A> const_iterator;
typedef std::forward_iterator_tag iterator_category; // very little defined!
typedef V value_type;
typedef typename value_alloc_type::difference_type difference_type;
typedef typename value_alloc_type::size_type size_type;
typedef typename value_alloc_type::reference reference;
typedef typename value_alloc_type::pointer pointer;
// "Real" constructor and default constructor
dense_hashtable_iterator(const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *h,
pointer it, pointer it_end, bool advance)
: ht(h), pos(it), end(it_end) {
if (advance) advance_past_empty_and_deleted();
}
dense_hashtable_iterator() { }
// The default destructor is fine; we don't define one
// The default operator= is fine; we don't define one
// Happy dereferencer
reference operator*() const { return *pos; }
pointer operator->() const { return &(operator*()); }
// Arithmetic. The only hard part is making sure that
// we're not on an empty or marked-deleted array element
void advance_past_empty_and_deleted() {
while ( pos != end && (ht->test_empty(*this) || ht->test_deleted(*this)) )
++pos;
}
iterator& operator++() {
assert(pos != end); ++pos; advance_past_empty_and_deleted(); return *this;
}
iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
// Comparison.
bool operator==(const iterator& it) const { return pos == it.pos; }
bool operator!=(const iterator& it) const { return pos != it.pos; }
// The actual data
const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *ht;
pointer pos, end;
};
// Now do it all again, but with const-ness!
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
struct dense_hashtable_const_iterator {
private:
typedef typename A::template rebind<V>::other value_alloc_type;
public:
typedef dense_hashtable_iterator<V,K,HF,ExK,SetK,EqK,A> iterator;
typedef dense_hashtable_const_iterator<V,K,HF,ExK,SetK,EqK,A> const_iterator;
typedef std::forward_iterator_tag iterator_category; // very little defined!
typedef V value_type;
typedef typename value_alloc_type::difference_type difference_type;
typedef typename value_alloc_type::size_type size_type;
typedef typename value_alloc_type::const_reference reference;
typedef typename value_alloc_type::const_pointer pointer;
// "Real" constructor and default constructor
dense_hashtable_const_iterator(
const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *h,
pointer it, pointer it_end, bool advance)
: ht(h), pos(it), end(it_end) {
if (advance) advance_past_empty_and_deleted();
}
dense_hashtable_const_iterator()
: ht(NULL), pos(pointer()), end(pointer()) { }
// This lets us convert regular iterators to const iterators
dense_hashtable_const_iterator(const iterator &it)
: ht(it.ht), pos(it.pos), end(it.end) { }
// The default destructor is fine; we don't define one
// The default operator= is fine; we don't define one
// Happy dereferencer
reference operator*() const { return *pos; }
pointer operator->() const { return &(operator*()); }
// Arithmetic. The only hard part is making sure that
// we're not on an empty or marked-deleted array element
void advance_past_empty_and_deleted() {
while ( pos != end && (ht->test_empty(*this) || ht->test_deleted(*this)) )
++pos;
}
const_iterator& operator++() {
assert(pos != end); ++pos; advance_past_empty_and_deleted(); return *this;
}
const_iterator operator++(int) { const_iterator tmp(*this); ++*this; return tmp; }
// Comparison.
bool operator==(const const_iterator& it) const { return pos == it.pos; }
bool operator!=(const const_iterator& it) const { return pos != it.pos; }
// The actual data
const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *ht;
pointer pos, end;
};
template <class Value, class Key, class HashFcn,
class ExtractKey, class SetKey, class EqualKey, class Alloc>
class dense_hashtable {
private:
typedef typename Alloc::template rebind<Value>::other value_alloc_type;
public:
typedef Key key_type;
typedef Value value_type;
typedef HashFcn hasher;
typedef EqualKey key_equal;
typedef Alloc allocator_type;
typedef typename value_alloc_type::size_type size_type;
typedef typename value_alloc_type::difference_type difference_type;
typedef typename value_alloc_type::reference reference;
typedef typename value_alloc_type::const_reference const_reference;
typedef typename value_alloc_type::pointer pointer;
typedef typename value_alloc_type::const_pointer const_pointer;
typedef dense_hashtable_iterator<Value, Key, HashFcn,
ExtractKey, SetKey, EqualKey, Alloc>
iterator;
typedef dense_hashtable_const_iterator<Value, Key, HashFcn,
ExtractKey, SetKey, EqualKey, Alloc>
const_iterator;
// These come from tr1. For us they're the same as regular iterators.
typedef iterator local_iterator;
typedef const_iterator const_local_iterator;
// How full we let the table get before we resize, by default.
// Knuth says .8 is good -- higher causes us to probe too much,
// though it saves memory.
static const int HT_OCCUPANCY_PCT; // defined at the bottom of this file
// How empty we let the table get before we resize lower, by default.
// (0.0 means never resize lower.)
// It should be less than OCCUPANCY_PCT / 2 or we thrash resizing
static const int HT_EMPTY_PCT; // defined at the bottom of this file
// Minimum size we're willing to let hashtables be.
// Must be a power of two, and at least 4.
// Note, however, that for a given hashtable, the initial size is a
// function of the first constructor arg, and may be >HT_MIN_BUCKETS.
static const size_type HT_MIN_BUCKETS = 4;
// By default, if you don't specify a hashtable size at
// construction-time, we use this size. Must be a power of two, and
// at least HT_MIN_BUCKETS.
static const size_type HT_DEFAULT_STARTING_BUCKETS = 32;
// ITERATOR FUNCTIONS
iterator begin() { return iterator(this, table,
table + num_buckets, true); }
iterator end() { return iterator(this, table + num_buckets,
table + num_buckets, true); }
const_iterator begin() const { return const_iterator(this, table,
table+num_buckets,true);}
const_iterator end() const { return const_iterator(this, table + num_buckets,
table+num_buckets,true);}
// These come from tr1 unordered_map. They iterate over 'bucket' n.
// We'll just consider bucket n to be the n-th element of the table.
local_iterator begin(size_type i) {
return local_iterator(this, table + i, table + i+1, false);
}
local_iterator end(size_type i) {
local_iterator it = begin(i);
if (!test_empty(i) && !test_deleted(i))
++it;
return it;
}
const_local_iterator begin(size_type i) const {
return const_local_iterator(this, table + i, table + i+1, false);
}
const_local_iterator end(size_type i) const {
const_local_iterator it = begin(i);
if (!test_empty(i) && !test_deleted(i))
++it;
return it;
}
// ACCESSOR FUNCTIONS for the things we templatize on, basically
hasher hash_funct() const { return settings; }
key_equal key_eq() const { return key_info; }
allocator_type get_allocator() const {
return allocator_type(val_info);
}
// Accessor function for statistics gathering.
int num_table_copies() const { return settings.num_ht_copies(); }
private:
// Annoyingly, we can't copy values around, because they might have
// const components (they're probably pair<const X, Y>). We use
// explicit destructor invocation and placement new to get around
// this. Arg.
void set_value(pointer dst, const_reference src) {
dst->~value_type(); // delete the old value, if any
new(dst) value_type(src);
}
void destroy_buckets(size_type first, size_type last) {
for ( ; first != last; ++first)
table[first].~value_type();
}
// DELETE HELPER FUNCTIONS
// This lets the user describe a key that will indicate deleted
// table entries. This key should be an "impossible" entry --
// if you try to insert it for real, you won't be able to retrieve it!
// (NB: while you pass in an entire value, only the key part is looked
// at. This is just because I don't know how to assign just a key.)
private:
void squash_deleted() { // gets rid of any deleted entries we have
if ( num_deleted ) { // get rid of deleted before writing
dense_hashtable tmp(*this); // copying will get rid of deleted
swap(tmp); // now we are tmp
}
assert(num_deleted == 0);
}
// Test if the given key is the deleted indicator. Requires
// num_deleted > 0, for correctness of read(), and because that
// guarantees that key_info.delkey is valid.
bool test_deleted_key(const key_type& key) const {
return false;
assert(num_deleted > 0);
return equals(key_info.delkey, key);
}
public:
void set_deleted_key(const key_type &key) {
// the empty indicator (if specified) and the deleted indicator
// must be different
assert((!settings.use_empty() || !equals(key, get_key(val_info.emptyval)))
&& "Passed the empty-key to set_deleted_key");
// It's only safe to change what "deleted" means if we purge deleted guys
squash_deleted();
settings.set_use_deleted(true);
key_info.delkey = key;
}
void clear_deleted_key() {
squash_deleted();
settings.set_use_deleted(false);
}
key_type deleted_key() const {
assert(settings.use_deleted()
&& "Must set deleted key before calling deleted_key");
return key_info.delkey;
}
// These are public so the iterators can use them
// True if the item at position bucknum is "deleted" marker
bool test_deleted(size_type bucknum) const {
return false;
// Invariant: !use_deleted() implies num_deleted is 0.
assert(settings.use_deleted() || num_deleted == 0);
return num_deleted > 0 && test_deleted_key(get_key(table[bucknum]));
}
bool test_deleted(const iterator &it) const {
return false;
// Invariant: !use_deleted() implies num_deleted is 0.
assert(settings.use_deleted() || num_deleted == 0);
return num_deleted > 0 && test_deleted_key(get_key(*it));
}
bool test_deleted(const const_iterator &it) const {
return false;
// Invariant: !use_deleted() implies num_deleted is 0.
assert(settings.use_deleted() || num_deleted == 0);
return num_deleted > 0 && test_deleted_key(get_key(*it));
}
private:
void check_use_deleted(const char* caller) {
(void)caller; // could log it if the assert failed
assert(settings.use_deleted());
}
// Set it so test_deleted is true. true if object didn't used to be deleted.
bool set_deleted(iterator &it) {
check_use_deleted("set_deleted()");
bool retval = !test_deleted(it);
// &* converts from iterator to value-type.
set_key(&(*it), key_info.delkey);
return retval;
}
// Set it so test_deleted is false. true if object used to be deleted.
bool clear_deleted(iterator &it) {
check_use_deleted("clear_deleted()");
// Happens automatically when we assign something else in its place.
return test_deleted(it);
}
// We also allow to set/clear the deleted bit on a const iterator.
// We allow a const_iterator for the same reason you can delete a
// const pointer: it's convenient, and semantically you can't use
// 'it' after it's been deleted anyway, so its const-ness doesn't
// really matter.
bool set_deleted(const_iterator &it) {
check_use_deleted("set_deleted()");
bool retval = !test_deleted(it);
set_key(const_cast<pointer>(&(*it)), key_info.delkey);
return retval;
}
// Set it so test_deleted is false. true if object used to be deleted.
bool clear_deleted(const_iterator &it) {
check_use_deleted("clear_deleted()");
return test_deleted(it);
}
// EMPTY HELPER FUNCTIONS
// This lets the user describe a key that will indicate empty (unused)
// table entries. This key should be an "impossible" entry --
// if you try to insert it for real, you won't be able to retrieve it!
// (NB: while you pass in an entire value, only the key part is looked
// at. This is just because I don't know how to assign just a key.)
public:
// These are public so the iterators can use them
// True if the item at position bucknum is "empty" marker
bool test_empty(size_type bucknum) const {
assert(settings.use_empty()); // we always need to know what's empty!
return equals(get_key(val_info.emptyval), get_key(table[bucknum]));
}
bool test_empty(const iterator &it) const {
assert(settings.use_empty()); // we always need to know what's empty!
return equals(get_key(val_info.emptyval), get_key(*it));
}
bool test_empty(const const_iterator &it) const {
assert(settings.use_empty()); // we always need to know what's empty!
return equals(get_key(val_info.emptyval), get_key(*it));
}
private:
void fill_range_with_empty(pointer table_start, pointer table_end) {
std::uninitialized_fill(table_start, table_end, val_info.emptyval);
}
public:
// TODO(csilvers): change all callers of this to pass in a key instead,
// and take a const key_type instead of const value_type.
void set_empty_key(const_reference val) {
// Once you set the empty key, you can't change it
assert(!settings.use_empty() && "Calling set_empty_key multiple times");
// The deleted indicator (if specified) and the empty indicator
// must be different.
assert((!settings.use_deleted() || !equals(get_key(val), key_info.delkey))
&& "Setting the empty key the same as the deleted key");
settings.set_use_empty(true);
set_value(&val_info.emptyval, val);
assert(!table); // must set before first use
// num_buckets was set in constructor even though table was NULL
table = val_info.allocate(num_buckets);
assert(table);
fill_range_with_empty(table, table + num_buckets);
}
// TODO(user): return a key_type rather than a value_type
value_type empty_key() const {
assert(settings.use_empty());
return val_info.emptyval;
}
// FUNCTIONS CONCERNING SIZE
public:
size_type size() const { return num_elements - num_deleted; }
size_type max_size() const { return val_info.max_size(); }
bool empty() const { return size() == 0; }
size_type bucket_count() const { return num_buckets; }
size_type max_bucket_count() const { return max_size(); }
size_type nonempty_bucket_count() const { return num_elements; }
// These are tr1 methods. Their idea of 'bucket' doesn't map well to
// what we do. We just say every bucket has 0 or 1 items in it.
size_type bucket_size(size_type i) const {
return begin(i) == end(i) ? 0 : 1;
}
private:
// Because of the above, size_type(-1) is never legal; use it for errors
static const size_type ILLEGAL_BUCKET = size_type(-1);
// Used after a string of deletes. Returns true if we actually shrunk.
// TODO(csilvers): take a delta so we can take into account inserts
// done after shrinking. Maybe make part of the Settings class?
bool maybe_shrink() {
assert(num_elements >= num_deleted);
assert((bucket_count() & (bucket_count()-1)) == 0); // is a power of two
assert(bucket_count() >= HT_MIN_BUCKETS);
bool retval = false;
// If you construct a hashtable with < HT_DEFAULT_STARTING_BUCKETS,
// we'll never shrink until you get relatively big, and we'll never
// shrink below HT_DEFAULT_STARTING_BUCKETS. Otherwise, something
// like "dense_hash_set<int> x; x.insert(4); x.erase(4);" will
// shrink us down to HT_MIN_BUCKETS buckets, which is too small.
const size_type num_remain = num_elements - num_deleted;
const size_type shrink_threshold = settings.shrink_threshold();
if (shrink_threshold > 0 && num_remain < shrink_threshold &&
bucket_count() > HT_DEFAULT_STARTING_BUCKETS) {
const float shrink_factor = settings.shrink_factor();
size_type sz = bucket_count() / 2; // find how much we should shrink
while (sz > HT_DEFAULT_STARTING_BUCKETS &&
num_remain < sz * shrink_factor) {
sz /= 2; // stay a power of 2
}
dense_hashtable tmp(*this, sz); // Do the actual resizing
swap(tmp); // now we are tmp
retval = true;
}
settings.set_consider_shrink(false); // because we just considered it
return retval;
}
// We'll let you resize a hashtable -- though this makes us copy all!
// When you resize, you say, "make it big enough for this many more elements"
// Returns true if we actually resized, false if size was already ok.
bool resize_delta(size_type delta) {
bool did_resize = false;
if ( settings.consider_shrink() ) { // see if lots of deletes happened
if ( maybe_shrink() )
did_resize = true;
}
if (num_elements >=
(std::numeric_limits<size_type>::max)() - delta) {
throw std::length_error("resize overflow");
}
if ( bucket_count() >= HT_MIN_BUCKETS &&
(num_elements + delta) <= settings.enlarge_threshold() )
return did_resize; // we're ok as we are
// Sometimes, we need to resize just to get rid of all the
// "deleted" buckets that are clogging up the hashtable. So when
// deciding whether to resize, count the deleted buckets (which
// are currently taking up room). But later, when we decide what
// size to resize to, *don't* count deleted buckets, since they
// get discarded during the resize.
const size_type needed_size = settings.min_buckets(num_elements + delta, 0);
if ( needed_size <= bucket_count() ) // we have enough buckets
return did_resize;
size_type resize_to =
settings.min_buckets(num_elements - num_deleted + delta, bucket_count());
if (resize_to < needed_size && // may double resize_to
resize_to < (std::numeric_limits<size_type>::max)() / 2) {
// This situation means that we have enough deleted elements,
// that once we purge them, we won't actually have needed to
// grow. But we may want to grow anyway: if we just purge one
// element, say, we'll have to grow anyway next time we
// insert. Might as well grow now, since we're already going
// through the trouble of copying (in order to purge the
// deleted elements).
const size_type target =
static_cast<size_type>(settings.shrink_size(resize_to*2));
if (num_elements - num_deleted + delta >= target) {
// Good, we won't be below the shrink threshhold even if we double.
resize_to *= 2;
}
}
dense_hashtable tmp(*this, resize_to);
swap(tmp); // now we are tmp
return true;
}
// We require table be not-NULL and empty before calling this.
void resize_table(size_type /*old_size*/, size_type new_size,
base::true_type) {
table = val_info.realloc_or_die(table, new_size);
}
void resize_table(size_type old_size, size_type new_size, base::false_type) {
val_info.deallocate(table, old_size);
table = val_info.allocate(new_size);
}
// Used to actually do the rehashing when we grow/shrink a hashtable
void copy_from(const dense_hashtable &ht, size_type min_buckets_wanted) {
clear_to_size(settings.min_buckets(ht.size(), min_buckets_wanted));
// We use a normal iterator to get non-deleted bcks from ht
// We could use insert() here, but since we know there are
// no duplicates and no deleted items, we can be more efficient
assert((bucket_count() & (bucket_count()-1)) == 0); // a power of two
for ( const_iterator it = ht.begin(); it != ht.end(); ++it ) {
size_type num_probes = 0; // how many times we've probed
size_type bucknum;
const size_type bucket_count_minus_one = bucket_count() - 1;
for (bucknum = hash(get_key(*it)) & bucket_count_minus_one;
!test_empty(bucknum); // not empty
bucknum = (bucknum + JUMP_(key, num_probes)) & bucket_count_minus_one) {
++num_probes;
assert(num_probes < bucket_count()
&& "Hashtable is full: an error in key_equal<> or hash<>");
}
set_value(&table[bucknum], *it); // copies the value to here
num_elements++;
}
settings.inc_num_ht_copies();
}
// Required by the spec for hashed associative container
public:
// Though the docs say this should be num_buckets, I think it's much
// more useful as num_elements. As a special feature, calling with
// req_elements==0 will cause us to shrink if we can, saving space.
void resize(size_type req_elements) { // resize to this or larger
if ( settings.consider_shrink() || req_elements == 0 )
maybe_shrink();
if ( req_elements > num_elements )
resize_delta(req_elements - num_elements);
}
// Get and change the value of shrink_factor and enlarge_factor. The
// description at the beginning of this file explains how to choose
// the values. Setting the shrink parameter to 0.0 ensures that the
// table never shrinks.
void get_resizing_parameters(float* shrink, float* grow) const {
*shrink = settings.shrink_factor();
*grow = settings.enlarge_factor();
}
void set_resizing_parameters(float shrink, float grow) {
settings.set_resizing_parameters(shrink, grow);
settings.reset_thresholds(bucket_count());
}
// CONSTRUCTORS -- as required by the specs, we take a size,
// but also let you specify a hashfunction, key comparator,
// and key extractor. We also define a copy constructor and =.
// DESTRUCTOR -- needs to free the table
explicit dense_hashtable(size_type expected_max_items_in_table = 0,
const HashFcn& hf = HashFcn(),
const EqualKey& eql = EqualKey(),
const ExtractKey& ext = ExtractKey(),
const SetKey& set = SetKey(),
const Alloc& alloc = Alloc())
: settings(hf),
key_info(ext, set, eql),
num_deleted(0),
num_elements(0),
num_buckets(expected_max_items_in_table == 0
? HT_DEFAULT_STARTING_BUCKETS
: settings.min_buckets(expected_max_items_in_table, 0)),
val_info(alloc_impl<value_alloc_type>(alloc)),
table(NULL) {
// table is NULL until emptyval is set. However, we set num_buckets
// here so we know how much space to allocate once emptyval is set
settings.reset_thresholds(bucket_count());
}
// As a convenience for resize(), we allow an optional second argument
// which lets you make this new hashtable a different size than ht
dense_hashtable(const dense_hashtable& ht,
size_type min_buckets_wanted = HT_DEFAULT_STARTING_BUCKETS)
: settings(ht.settings),
key_info(ht.key_info),
num_deleted(0),
num_elements(0),
num_buckets(0),
val_info(ht.val_info),
table(NULL) {
if (!ht.settings.use_empty()) {
// If use_empty isn't set, copy_from will crash, so we do our own copying.
assert(ht.empty());
num_buckets = settings.min_buckets(ht.size(), min_buckets_wanted);
settings.reset_thresholds(bucket_count());
return;
}
settings.reset_thresholds(bucket_count());
copy_from(ht, min_buckets_wanted); // copy_from() ignores deleted entries
}
dense_hashtable& operator= (const dense_hashtable& ht) {
if (&ht == this) return *this; // don't copy onto ourselves
if (!ht.settings.use_empty()) {
assert(ht.empty());
dense_hashtable empty_table(ht); // empty table with ht's thresholds
this->swap(empty_table);
return *this;
}
settings = ht.settings;
key_info = ht.key_info;
set_value(&val_info.emptyval, ht.val_info.emptyval);
// copy_from() calls clear and sets num_deleted to 0 too
copy_from(ht, HT_MIN_BUCKETS);
// we purposefully don't copy the allocator, which may not be copyable
return *this;
}
~dense_hashtable() {
if (table) {
destroy_buckets(0, num_buckets);
val_info.deallocate(table, num_buckets);
}
}
// Many STL algorithms use swap instead of copy constructors
void swap(dense_hashtable& ht) {
std::swap(settings, ht.settings);
std::swap(key_info, ht.key_info);
std::swap(num_deleted, ht.num_deleted);
std::swap(num_elements, ht.num_elements);
std::swap(num_buckets, ht.num_buckets);
{ value_type tmp; // for annoying reasons, swap() doesn't work
set_value(&tmp, val_info.emptyval);
set_value(&val_info.emptyval, ht.val_info.emptyval);
set_value(&ht.val_info.emptyval, tmp);
}
std::swap(table, ht.table);
settings.reset_thresholds(bucket_count()); // also resets consider_shrink
ht.settings.reset_thresholds(ht.bucket_count());
// we purposefully don't swap the allocator, which may not be swap-able
}
private:
void clear_to_size(size_type new_num_buckets) {
if (!table) {
table = val_info.allocate(new_num_buckets);
} else {
destroy_buckets(0, num_buckets);
if (new_num_buckets != num_buckets) { // resize, if necessary
typedef base::integral_constant<bool,
base::is_same<value_alloc_type,
libc_allocator_with_realloc<value_type> >::value>
realloc_ok;
resize_table(num_buckets, new_num_buckets, realloc_ok());
}
}
assert(table);
fill_range_with_empty(table, table + new_num_buckets);
num_elements = 0;
num_deleted = 0;
num_buckets = new_num_buckets; // our new size
settings.reset_thresholds(bucket_count());
}
public:
// It's always nice to be able to clear a table without deallocating it
void clear() {
// If the table is already empty, and the number of buckets is
// already as we desire, there's nothing to do.
const size_type new_num_buckets = settings.min_buckets(0, 0);
if (num_elements == 0 && new_num_buckets == num_buckets) {
return;
}
clear_to_size(new_num_buckets);
}
// Clear the table without resizing it.
// Mimicks the stl_hashtable's behaviour when clear()-ing in that it
// does not modify the bucket count
void clear_no_resize() {
if (num_elements > 0) {
assert(table);
destroy_buckets(0, num_buckets);
fill_range_with_empty(table, table + num_buckets);
}
// don't consider to shrink before another erase()
settings.reset_thresholds(bucket_count());
num_elements = 0;
num_deleted = 0;
}
// LOOKUP ROUTINES
private:
// Returns a pair of positions: 1st where the object is, 2nd where
// it would go if you wanted to insert it. 1st is ILLEGAL_BUCKET
// if object is not found; 2nd is ILLEGAL_BUCKET if it is.
// Note: because of deletions where-to-insert is not trivial: it's the
// first deleted bucket we see, as long as we don't find the key later
std::pair<size_type, size_type> find_position(const key_type &key) const {
size_type num_probes = 0; // how many times we've probed
const size_type bucket_count_minus_one = bucket_count() - 1;
size_type bucknum = hash(key) & bucket_count_minus_one;
size_type insert_pos = ILLEGAL_BUCKET; // where we would insert
while ( 1 ) { // probe until something happens
if ( test_empty(bucknum) ) { // bucket is empty
if ( insert_pos == ILLEGAL_BUCKET ) // found no prior place to insert
return std::pair<size_type,size_type>(ILLEGAL_BUCKET, bucknum);
else
return std::pair<size_type,size_type>(ILLEGAL_BUCKET, insert_pos);
} else if ( test_deleted(bucknum) ) {// keep searching, but mark to insert
if ( insert_pos == ILLEGAL_BUCKET )
insert_pos = bucknum;
} else if ( equals(key, get_key(table[bucknum])) ) {
return std::pair<size_type,size_type>(bucknum, ILLEGAL_BUCKET);
}
++num_probes; // we're doing another probe
bucknum = (bucknum + JUMP_(key, num_probes)) & bucket_count_minus_one;
assert(num_probes < bucket_count()
&& "Hashtable is full: an error in key_equal<> or hash<>");
}
}
public:
iterator find(const key_type& key) {
if ( size() == 0 ) return end();
std::pair<size_type, size_type> pos = find_position(key);
if ( pos.first == ILLEGAL_BUCKET ) // alas, not there
return end();
else
return iterator(this, table + pos.first, table + num_buckets, false);
}
const_iterator find(const key_type& key) const {
if ( size() == 0 ) return end();
std::pair<size_type, size_type> pos = find_position(key);
if ( pos.first == ILLEGAL_BUCKET ) // alas, not there
return end();
else
return const_iterator(this, table + pos.first, table+num_buckets, false);
}
// This is a tr1 method: the bucket a given key is in, or what bucket
// it would be put in, if it were to be inserted. Shrug.
size_type bucket(const key_type& key) const {
std::pair<size_type, size_type> pos = find_position(key);
return pos.first == ILLEGAL_BUCKET ? pos.second : pos.first;
}
// Counts how many elements have key key. For maps, it's either 0 or 1.
size_type count(const key_type &key) const {
std::pair<size_type, size_type> pos = find_position(key);
return pos.first == ILLEGAL_BUCKET ? 0 : 1;
}
// Likewise, equal_range doesn't really make sense for us. Oh well.
std::pair<iterator,iterator> equal_range(const key_type& key) {
iterator pos = find(key); // either an iterator or end
if (pos == end()) {
return std::pair<iterator,iterator>(pos, pos);
} else {
const iterator startpos = pos++;
return std::pair<iterator,iterator>(startpos, pos);
}
}
std::pair<const_iterator,const_iterator> equal_range(const key_type& key)
const {
const_iterator pos = find(key); // either an iterator or end
if (pos == end()) {
return std::pair<const_iterator,const_iterator>(pos, pos);
} else {
const const_iterator startpos = pos++;
return std::pair<const_iterator,const_iterator>(startpos, pos);
}
}
// INSERTION ROUTINES
private:
// Private method used by insert_noresize and find_or_insert.
iterator insert_at(const_reference obj, size_type pos) {
if (size() >= max_size()) {
throw std::length_error("insert overflow");
}
if ( test_deleted(pos) ) { // just replace if it's been del.
// shrug: shouldn't need to be const.
const_iterator delpos(this, table + pos, table + num_buckets, false);
clear_deleted(delpos);
assert( num_deleted > 0);
--num_deleted; // used to be, now it isn't
} else {
++num_elements; // replacing an empty bucket
}
set_value(&table[pos], obj);
return iterator(this, table + pos, table + num_buckets, false);
}
// If you know *this is big enough to hold obj, use this routine
std::pair<iterator, bool> insert_noresize(const_reference obj) {
// First, double-check we're not inserting delkey or emptyval
assert((!settings.use_empty() || !equals(get_key(obj),
get_key(val_info.emptyval)))
&& "Inserting the empty key");
assert((!settings.use_deleted() || !equals(get_key(obj), key_info.delkey))
&& "Inserting the deleted key");
const std::pair<size_type,size_type> pos = find_position(get_key(obj));
if ( pos.first != ILLEGAL_BUCKET) { // object was already there
return std::pair<iterator,bool>(iterator(this, table + pos.first,
table + num_buckets, false),
false); // false: we didn't insert
} else { // pos.second says where to put it
return std::pair<iterator,bool>(insert_at(obj, pos.second), true);
}
}
// Specializations of insert(it, it) depending on the power of the iterator:
// (1) Iterator supports operator-, resize before inserting
template <class ForwardIterator>
void insert(ForwardIterator f, ForwardIterator l, std::forward_iterator_tag) {
size_t dist = std::distance(f, l);
if (dist >= (std::numeric_limits<size_type>::max)()) {
throw std::length_error("insert-range overflow");
}
resize_delta(static_cast<size_type>(dist));
for ( ; dist > 0; --dist, ++f) {
insert_noresize(*f);
}
}
// (2) Arbitrary iterator, can't tell how much to resize
template <class InputIterator>
void insert(InputIterator f, InputIterator l, std::input_iterator_tag) {
for ( ; f != l; ++f)
insert(*f);
}
public:
// This is the normal insert routine, used by the outside world
std::pair<iterator, bool> insert(const_reference obj) {
resize_delta(1); // adding an object, grow if need be
return insert_noresize(obj);
}
// When inserting a lot at a time, we specialize on the type of iterator
template <class InputIterator>
void insert(InputIterator f, InputIterator l) {
// specializes on iterator type
insert(f, l,
typename std::iterator_traits<InputIterator>::iterator_category());
}
// DefaultValue is a functor that takes a key and returns a value_type
// representing the default value to be inserted if none is found.
template <class DefaultValue>
value_type& find_or_insert(const key_type& key) {
// First, double-check we're not inserting emptykey or delkey
assert((!settings.use_empty() || !equals(key, get_key(val_info.emptyval)))
&& "Inserting the empty key");
assert((!settings.use_deleted() || !equals(key, key_info.delkey))
&& "Inserting the deleted key");
const std::pair<size_type,size_type> pos = find_position(key);
DefaultValue default_value;
if ( pos.first != ILLEGAL_BUCKET) { // object was already there
return table[pos.first];
} else if (resize_delta(1)) { // needed to rehash to make room
// Since we resized, we can't use pos, so recalculate where to insert.
return *insert_noresize(default_value(key)).first;
} else { // no need to rehash, insert right here
return *insert_at(default_value(key), pos.second);
}
}
// DELETION ROUTINES
size_type erase(const key_type& key) {
// First, double-check we're not trying to erase delkey or emptyval.
assert((!settings.use_empty() || !equals(key, get_key(val_info.emptyval)))
&& "Erasing the empty key");
assert((!settings.use_deleted() || !equals(key, key_info.delkey))
&& "Erasing the deleted key");
const_iterator pos = find(key); // shrug: shouldn't need to be const
if ( pos != end() ) {
assert(!test_deleted(pos)); // or find() shouldn't have returned it
set_deleted(pos);
++num_deleted;
settings.set_consider_shrink(true); // will think about shrink after next insert
return 1; // because we deleted one thing
} else {
return 0; // because we deleted nothing
}
}
// We return the iterator past the deleted item.
void erase(iterator pos) {
if ( pos == end() ) return; // sanity check
if ( set_deleted(pos) ) { // true if object has been newly deleted
++num_deleted;
settings.set_consider_shrink(true); // will think about shrink after next insert
}
}
void erase(iterator f, iterator l) {
for ( ; f != l; ++f) {
if ( set_deleted(f) ) // should always be true
++num_deleted;
}
settings.set_consider_shrink(true); // will think about shrink after next insert
}
// We allow you to erase a const_iterator just like we allow you to
// erase an iterator. This is in parallel to 'delete': you can delete
// a const pointer just like a non-const pointer. The logic is that
// you can't use the object after it's erased anyway, so it doesn't matter
// if it's const or not.
void erase(const_iterator pos) {
if ( pos == end() ) return; // sanity check
if ( set_deleted(pos) ) { // true if object has been newly deleted
++num_deleted;
settings.set_consider_shrink(true); // will think about shrink after next insert
}
}
void erase(const_iterator f, const_iterator l) {
for ( ; f != l; ++f) {
if ( set_deleted(f) ) // should always be true
++num_deleted;
}
settings.set_consider_shrink(true); // will think about shrink after next insert
}
// COMPARISON
bool operator==(const dense_hashtable& ht) const {
if (size() != ht.size()) {
return false;
} else if (this == &ht) {
return true;
} else {
// Iterate through the elements in "this" and see if the
// corresponding element is in ht
for ( const_iterator it = begin(); it != end(); ++it ) {
const_iterator it2 = ht.find(get_key(*it));
if ((it2 == ht.end()) || (*it != *it2)) {
return false;
}
}
return true;
}
}
bool operator!=(const dense_hashtable& ht) const {
return !(*this == ht);
}
// I/O
// We support reading and writing hashtables to disk. Alas, since
// I don't know how to write a hasher or key_equal, you have to make
// sure everything but the table is the same. We compact before writing.
private:
// Every time the disk format changes, this should probably change too
typedef unsigned long MagicNumberType;
static const MagicNumberType MAGIC_NUMBER = 0x13578642;
public:
// I/O -- this is an add-on for writing hash table to disk
//
// INPUT and OUTPUT must be either a FILE, *or* a C++ stream
// (istream, ostream, etc) *or* a class providing
// Read(void*, size_t) and Write(const void*, size_t)
// (respectively), which writes a buffer into a stream
// (which the INPUT/OUTPUT instance presumably owns).
typedef sparsehash_internal::pod_serializer<value_type> NopointerSerializer;
// ValueSerializer: a functor. operator()(OUTPUT*, const value_type&)
template <typename ValueSerializer, typename OUTPUT>
bool serialize(ValueSerializer serializer, OUTPUT *fp) {
squash_deleted(); // so we don't have to worry about delkey
if ( !sparsehash_internal::write_bigendian_number(fp, MAGIC_NUMBER, 4) )
return false;
if ( !sparsehash_internal::write_bigendian_number(fp, num_buckets, 8) )
return false;
if ( !sparsehash_internal::write_bigendian_number(fp, num_elements, 8) )
return false;
// Now write a bitmap of non-empty buckets.
for ( size_type i = 0; i < num_buckets; i += 8 ) {
unsigned char bits = 0;
for ( int bit = 0; bit < 8; ++bit ) {
if ( i + bit < num_buckets && !test_empty(i + bit) )
bits |= (1 << bit);
}
if ( !sparsehash_internal::write_data(fp, &bits, sizeof(bits)) )
return false;
for ( int bit = 0; bit < 8; ++bit ) {
if ( bits & (1 << bit) ) {
if ( !serializer(fp, table[i + bit]) ) return false;
}
}
}
return true;
}
// INPUT: anything we've written an overload of read_data() for.
// ValueSerializer: a functor. operator()(INPUT*, value_type*)
template <typename ValueSerializer, typename INPUT>
bool unserialize(ValueSerializer serializer, INPUT *fp) {
assert(settings.use_empty() && "empty_key not set for read");
clear(); // just to be consistent
MagicNumberType magic_read;
if ( !sparsehash_internal::read_bigendian_number(fp, &magic_read, 4) )
return false;
if ( magic_read != MAGIC_NUMBER ) {
return false;
}
size_type new_num_buckets;
if ( !sparsehash_internal::read_bigendian_number(fp, &new_num_buckets, 8) )
return false;
clear_to_size(new_num_buckets);
if ( !sparsehash_internal::read_bigendian_number(fp, &num_elements, 8) )
return false;
// Read the bitmap of non-empty buckets.
for (size_type i = 0; i < num_buckets; i += 8) {
unsigned char bits;
if ( !sparsehash_internal::read_data(fp, &bits, sizeof(bits)) )
return false;
for ( int bit = 0; bit < 8; ++bit ) {
if ( i + bit < num_buckets && (bits & (1 << bit)) ) { // not empty
if ( !serializer(fp, &table[i + bit]) ) return false;
}
}
}
return true;
}
private:
template <class A>
class alloc_impl : public A {
public:
typedef typename A::pointer pointer;
typedef typename A::size_type size_type;
// Convert a normal allocator to one that has realloc_or_die()
alloc_impl(const A& a) : A(a) { }
// realloc_or_die should only be used when using the default
// allocator (libc_allocator_with_realloc).
pointer realloc_or_die(pointer /*ptr*/, size_type /*n*/) {
fprintf(stderr, "realloc_or_die is only supported for "
"libc_allocator_with_realloc\n");
exit(1);
return NULL;
}
};
// A template specialization of alloc_impl for
// libc_allocator_with_realloc that can handle realloc_or_die.
template <class A>
class alloc_impl<libc_allocator_with_realloc<A> >
: public libc_allocator_with_realloc<A> {
public:
typedef typename libc_allocator_with_realloc<A>::pointer pointer;
typedef typename libc_allocator_with_realloc<A>::size_type size_type;
alloc_impl(const libc_allocator_with_realloc<A>& a)
: libc_allocator_with_realloc<A>(a) { }
pointer realloc_or_die(pointer ptr, size_type n) {
pointer retval = this->reallocate(ptr, n);
if (retval == NULL) {
fprintf(stderr, "sparsehash: FATAL ERROR: failed to reallocate "
"%lu elements for ptr %p", static_cast<unsigned long>(n), ptr);
exit(1);
}
return retval;
}
};
// Package allocator with emptyval to eliminate memory needed for
// the zero-size allocator.
// If new fields are added to this class, we should add them to
// operator= and swap.
class ValInfo : public alloc_impl<value_alloc_type> {
public:
typedef typename alloc_impl<value_alloc_type>::value_type value_type;
ValInfo(const alloc_impl<value_alloc_type>& a)
: alloc_impl<value_alloc_type>(a), emptyval() { }
ValInfo(const ValInfo& v)
: alloc_impl<value_alloc_type>(v), emptyval(v.emptyval) { }
value_type emptyval; // which key marks unused entries
};
// Package functors with another class to eliminate memory needed for
// zero-size functors. Since ExtractKey and hasher's operator() might
// have the same function signature, they must be packaged in
// different classes.
struct Settings :
sparsehash_internal::sh_hashtable_settings<key_type, hasher,
size_type, HT_MIN_BUCKETS> {
explicit Settings(const hasher& hf)
: sparsehash_internal::sh_hashtable_settings<key_type, hasher,
size_type, HT_MIN_BUCKETS>(
hf, HT_OCCUPANCY_PCT / 100.0f, HT_EMPTY_PCT / 100.0f) {}
};
// Packages ExtractKey and SetKey functors.
class KeyInfo : public ExtractKey, public SetKey, public EqualKey {
public:
KeyInfo(const ExtractKey& ek, const SetKey& sk, const EqualKey& eq)
: ExtractKey(ek),
SetKey(sk),
EqualKey(eq) {
}
// We want to return the exact same type as ExtractKey: Key or const Key&
typename ExtractKey::result_type get_key(const_reference v) const {
return ExtractKey::operator()(v);
}
void set_key(pointer v, const key_type& k) const {
SetKey::operator()(v, k);
}
bool equals(const key_type& a, const key_type& b) const {
return EqualKey::operator()(a, b);
}
// Which key marks deleted entries.
// TODO(csilvers): make a pointer, and get rid of use_deleted (benchmark!)
typename base::remove_const<key_type>::type delkey;
};
// Utility functions to access the templated operators
size_type hash(const key_type& v) const {
return settings.hash(v);
}
bool equals(const key_type& a, const key_type& b) const {
return key_info.equals(a, b);
}
typename ExtractKey::result_type get_key(const_reference v) const {
return key_info.get_key(v);
}
void set_key(pointer v, const key_type& k) const {
key_info.set_key(v, k);
}
private:
// Actual data
Settings settings;
KeyInfo key_info;
size_type num_deleted; // how many occupied buckets are marked deleted
size_type num_elements;
size_type num_buckets;
ValInfo val_info; // holds emptyval, and also the allocator
pointer table;
};
// We need a global swap as well
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
inline void swap(dense_hashtable<V,K,HF,ExK,SetK,EqK,A> &x,
dense_hashtable<V,K,HF,ExK,SetK,EqK,A> &y) {
x.swap(y);
}
#undef JUMP_
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
const typename dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::size_type
dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::ILLEGAL_BUCKET;
// How full we let the table get before we resize. Knuth says .8 is
// good -- higher causes us to probe too much, though saves memory.
// However, we go with .5, getting better performance at the cost of
// more space (a trade-off densehashtable explicitly chooses to make).
// Feel free to play around with different values, though, via
// max_load_factor() and/or set_resizing_parameters().
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
const int dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_OCCUPANCY_PCT = 50;
// How empty we let the table get before we resize lower.
// It should be less than OCCUPANCY_PCT / 2 or we thrash resizing.
template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
const int dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_EMPTY_PCT
= static_cast<int>(0.4 *
dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_OCCUPANCY_PCT);
_END_GOOGLE_NAMESPACE_
#endif /* _DENSEHASHTABLE_H_ */
| [
"foundry"
] | foundry |
b41d603407d1b56b1f61f87aefb28ed042df82d7 | 0c8c41b82105f27ee113b882cefcefa9b822512a | /Library_Management/DBHelper.h | 7aabd23bda251bf8cdf6163b7a9a9bb8384bb204 | [] | no_license | vietphu0123/Library-management | 4b3f325098ce638088c5ac4147c3ea1547758102 | 75fce2ef09213df55b8b616368febf5fefb77dd2 | refs/heads/master | 2023-06-23T12:39:05.161446 | 2021-07-25T09:17:09 | 2021-07-25T09:17:09 | 389,303,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | h | #pragma once
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>
#include"Sach.h"
#include<string.h>
#include<string>
#include"List.h"
class DBHelper
{
#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
//define handles and variables
SQLHANDLE sqlConnHandle;
SQLHANDLE sqlStmtHandle;
SQLHANDLE sqlEnvHandle;
SQLCHAR retconstring[SQL_RETURN_CODE_LEN];
SQLINTEGER ptrSqlVersion;
public:
void init();
void execute();
bool checkSQL(char*);
bool checkSQLFetch();
void getChar(int num, char* data);
void getfloat(int num, int& data);
char* convert(string);
void close();
};
| [
"vietphu0123@gmail.com"
] | vietphu0123@gmail.com |
9cb52d58dd7b322a650ad4998119f55e24165f61 | 1ba4ac1af9f95cbc6614b51577d5b44703cf4b81 | /libs/nav/src/planners/PlannerSimple2D.cpp | 46b8a15b4051b09b2e9d168e604d7d4fa73fba34 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | IcanChen/mrpt | de8a6f6f98b8fa32c1d75311703d0f28c2556f96 | 1315310054b32210c5614f9cac8780572c98e40b | refs/heads/master | 2020-04-06T06:52:31.664012 | 2016-01-10T11:05:08 | 2016-01-10T11:05:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,235 | cpp | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2015, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "nav-precomp.h" // Precompiled headers
#include <mrpt/nav/planners/PlannerSimple2D.h>
using namespace mrpt;
using namespace mrpt::maps;
using namespace mrpt::utils;
using namespace mrpt::math;
using namespace mrpt::poses;
using namespace mrpt::nav;
using namespace std;
/*---------------------------------------------------------------
Constructor
---------------------------------------------------------------*/
PlannerSimple2D::PlannerSimple2D() :
occupancyThreshold ( 0.5f ),
minStepInReturnedPath (0.4f),
robotRadius(0.35f)
{
}
/*---------------------------------------------------------------
computePath
---------------------------------------------------------------*/
void PlannerSimple2D::computePath(
const COccupancyGridMap2D &theMap,
const CPose2D &origin_,
const CPose2D &target_,
std::deque<math::TPoint2D> &path,
bool ¬Found,
float maxSearchPathLength ) const
{
#define CELL_ORIGIN 0x0000
#define CELL_EMPTY 0x8000
#define CELL_OBSTACLE 0xFFFF
#define CELL_TARGET 0xFFFE
const TPoint2D origin = TPoint2D(origin_);
const TPoint2D target = TPoint2D(target_);
std::vector<uint16_t> grid;
int size_x,size_y,i,n,m;
int x,y;
bool searching;
uint16_t minNeigh=CELL_EMPTY, maxNeigh=CELL_EMPTY, v=0, c;
int passCellFound_x = -1,
passCellFound_y = -1;
std::vector<uint16_t> pathcells_x,pathcells_y;
// Check that origin and target falls inside the grid theMap!!
// -----------------------------------------------------------
ASSERT_(origin.x>theMap.getXMin() && origin.x<theMap.getXMax() &&
origin.y>theMap.getYMin() && origin.y<theMap.getYMax());
ASSERT_(target.x>theMap.getXMin() && target.x<theMap.getXMax() &&
target.y>theMap.getYMin() && target.y<theMap.getYMax() );
// Check for the special case of origin and target in the same cell:
// -----------------------------------------------------------------
if ( theMap.x2idx(origin.x) == theMap.x2idx(target.x) &&
theMap.y2idx(origin.y) == theMap.y2idx(target.y) )
{
path.clear();
path.push_back(TPoint2D(target.x,target.y));
notFound = false;
return;
}
// Get the grid size:
// -----------------------------------------------------------
size_x = theMap.getSizeX();
size_y = theMap.getSizeY();
// Fill the grid content with free-space and obstacles:
// -----------------------------------------------------------
grid.resize( size_x * size_y );
for (y=0;y<size_y;y++)
{
int row = y*size_x;
for (x=0;x<size_x;x++)
{
grid[x+row]=(theMap.getCell(x,y)>occupancyThreshold) ? CELL_EMPTY:CELL_OBSTACLE;
}
}
// Enlarge obstacles with the robot radius:
// -----------------------------------------------------------
int obsEnlargement = (int)(ceil( robotRadius / theMap.getResolution() ));
for (int nEnlargements=0;nEnlargements<obsEnlargement;nEnlargements++)
{
// int size_y_1 = size_y-1;
// int size_x_1 = size_x-1;
// For all cells(x,y)=EMPTY:
// -----------------------------
for (y=2;y<size_y-2;y++)
{
int row = y*size_x;
int row_1 = (y+1) * size_x;
int row__1 = (y-1) * size_x;
for (x=2;x<size_x-2;x++)
{
uint16_t val = ( CELL_OBSTACLE - nEnlargements );
// A cell near an obstacle found??
// -----------------------------------------------------
if (grid[x-1+row__1]>=val ||
grid[x+row__1]>=val ||
grid[x+1+row__1]>=val ||
grid[x-1+row]>=val ||
grid[x+1+row]>=val ||
grid[x-1+row_1]>=val ||
grid[x+row_1]>=val ||
grid[x+1+row_1]>=val )
{
grid[x+row] = max((uint16_t)grid[x+row], (uint16_t)(val-1));
}
}
}
}
// Definitevely set new obstacles as obstacles
for (y=1;y<size_y-1;y++)
{
int row = y*size_x;
for (x=1;x<size_x-1;x++)
{
if (grid[x+row] > CELL_EMPTY )
grid[x+row] = CELL_OBSTACLE;
}
}
// Put the special cell codes for the origin and target:
// -----------------------------------------------------------
grid[ theMap.x2idx(origin.x) + size_x*theMap.y2idx(origin.y)] = CELL_ORIGIN;
grid[ theMap.x2idx(target.x) + size_x*theMap.y2idx(target.y)] = CELL_TARGET;
// The main path search loop:
// -----------------------------------------------------------
searching = true; // Will become false on path found.
notFound = false; // Will be set true inside the loop if a path is not found.
int range_x_min = min( theMap.x2idx(origin.x)-1,theMap.x2idx(target.x)-1 );
int range_x_max = max( theMap.x2idx(origin.x)+1,theMap.x2idx(target.x)+1 );
int range_y_min = min( theMap.y2idx(origin.y)-1,theMap.y2idx(target.y)-1 );
int range_y_max = max( theMap.y2idx(origin.y)+1,theMap.y2idx(target.y)+1 );
do
{
notFound = true;
bool wave1Found= false, wave2Found = false;
int size_y_1 = size_y-1;
int size_x_1 = size_x-1;
int longestPathInCellsMetric = 0;
range_x_min= max(1, range_x_min - 1 );
range_x_max= min(size_x_1, range_x_max + 1 );
range_y_min= max(1, range_y_min - 1 );
range_y_max= min(size_y_1, range_y_max + 1 );
// For all cells(x,y)=EMPTY:
// -----------------------------
for (y=range_y_min;y<range_y_max && passCellFound_x==-1;y++)
{
int row = y*size_x;
int row_1 = (y+1) * size_x;
int row__1 = (y-1) * size_x;
char metric; // =2 horz.vert, =3 diagonal <-- Since 3/2 ~= sqrt(2)
for (x=range_x_min;x<range_x_max;x++)
{
if (grid[x+row] == CELL_EMPTY )
{
// Look in the neighboorhood:
// -----------------------------
minNeigh = maxNeigh = CELL_EMPTY;
metric = 2;
v = grid[x+row__1]; if (v+2<minNeigh)minNeigh=v+2; if (v-2>maxNeigh && v!=CELL_OBSTACLE)maxNeigh=v-2;
v = grid[x-1+row]; if (v+2<minNeigh)minNeigh=v+2; if (v-2>maxNeigh && v!=CELL_OBSTACLE)maxNeigh=v-2;
v = grid[x+1+row]; if (v+2<minNeigh)minNeigh=v+2; if (v-2>maxNeigh && v!=CELL_OBSTACLE)maxNeigh=v-2;
v = grid[x+row_1]; if (v+2<minNeigh)minNeigh=v+2; if (v-2>maxNeigh && v!=CELL_OBSTACLE)maxNeigh=v-2;
v = grid[x-1+row__1]; if ((v+3)<minNeigh){metric=3;minNeigh=(v+3);} if ((v-3)>maxNeigh && v!=CELL_OBSTACLE) {metric=3;maxNeigh=v-3;}
v = grid[x+1+row__1]; if ((v+3)<minNeigh){metric=3;minNeigh=(v+3);} if ((v-3)>maxNeigh && v!=CELL_OBSTACLE) {metric=3;maxNeigh=v-3;}
v = grid[x-1+row_1]; if ((v+3)<minNeigh){metric=3;minNeigh=(v+3);} if ((v-3)>maxNeigh && v!=CELL_OBSTACLE) {metric=3;maxNeigh=v-3;}
v = grid[x+1+row_1]; if ((v+3)<minNeigh){metric=3;minNeigh=(v+3);} if ((v-3)>maxNeigh && v!=CELL_OBSTACLE) {metric=3;maxNeigh=v-3;}
// Convergence cell found? = The shortest path found
// -----------------------------------------------------
if ( minNeigh<CELL_EMPTY && maxNeigh>CELL_EMPTY )
{
// Stop the search:
passCellFound_x = x;
passCellFound_y = y;
searching = false;
longestPathInCellsMetric = 0;
break;
}
else if (minNeigh<CELL_EMPTY)
{
wave1Found = true;
// Cell in the expansion-wave from origin
grid[x+row] = minNeigh + metric;
ASSERT_(minNeigh+metric<CELL_EMPTY);
longestPathInCellsMetric = max( longestPathInCellsMetric, CELL_EMPTY - minNeigh );
}
else if (maxNeigh>CELL_EMPTY)
{
wave2Found = true;
// Cell in the expansion-wave from the target
grid[x+row] = maxNeigh - metric;
ASSERT_(maxNeigh-metric>CELL_EMPTY);
longestPathInCellsMetric = max( longestPathInCellsMetric, maxNeigh - CELL_EMPTY);
}
else
{ // Nothing to do: A free cell inside of all also free cells.
}
} // if cell empty
} // end for x
} // end for y
notFound = !wave1Found && !wave2Found;
// Exceeded the max. desired search length??
if (maxSearchPathLength>0)
if ( theMap.getResolution() * longestPathInCellsMetric * 0.5f > 1.5f*maxSearchPathLength )
{
// printf_debug("[PlannerSimple2D::computePath] Path exceeded desired length! (length=%f m)\n", theMap.getResolution() * longestPathInCellsMetric * 0.5f);
notFound = true;
}
} while (!notFound && searching);
// Path not found:
if (notFound)
return;
// Rebuild the optimal path from the two-waves convergence cell
// ----------------------------------------------------------------
// STEP 1: Trace-back to origin
//-------------------------------------
pathcells_x.reserve( (minNeigh+1)+(CELL_TARGET-maxNeigh) ); // An (exact?) estimation of the final vector size:
pathcells_y.reserve( (minNeigh+1)+(CELL_TARGET-maxNeigh) );
x = passCellFound_x; y = passCellFound_y;
while ( (v=grid[x+size_x*y]) != CELL_ORIGIN )
{
// Add cell to the path (in inverse order, now we go backward!!) Later is will be reversed
pathcells_x.push_back(x);
pathcells_y.push_back(y);
// Follow the "negative gradient" toward the origin:
static char dx=0,dy=0;
if ((c=grid[x-1+size_x*y])<v) { v=c; dx=-1; dy= 0; }
if ((c=grid[x+1+size_x*y])<v) { v=c; dx= 1; dy= 0; }
if ((c=grid[x+size_x*(y-1)])<v) { v=c; dx= 0; dy=-1; }
if ((c=grid[x+size_x*(y+1)])<v) { v=c; dx= 0; dy= 1; }
if ((c=grid[x-1+size_x*(y-1)])<v) { v=c; dx=-1; dy= -1; }
if ((c=grid[x+1+size_x*(y-1)])<v) { v=c; dx= 1; dy= -1; }
if ((c=grid[x-1+size_x*(y+1)])<v) { v=c; dx=-1; dy= 1; }
if ((c=grid[x+1+size_x*(y+1)])<v) { v=c; dx= 1; dy= 1; }
ASSERT_(dx!=0 || dy!=0);
x+=dx;
y+=dy;
}
// STEP 2: Reverse the path, since we want it from the origin
// toward the convergence cell
//--------------------------------------------------------------
n = pathcells_x.size(); m = n / 2;
for (i=0;i<m;i++)
{
v = pathcells_x[i];
pathcells_x[i] = pathcells_x[n-1-i];
pathcells_x[n-1-i] = v;
v = pathcells_y[i];
pathcells_y[i] = pathcells_y[n-1-i];
pathcells_y[n-1-i] = v;
}
// STEP 3: Trace-foward toward the target
//-------------------------------------
x = passCellFound_x; y = passCellFound_y;
while ( (v=grid[x+size_x*y]) != CELL_TARGET )
{
// Add cell to the path
pathcells_x.push_back(x);
pathcells_y.push_back(y);
// Follow the "positive gradient" toward the target:
static char dx=0,dy=0;
c=grid[x-1+size_x*y]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx=-1; dy= 0; }
c=grid[x+1+size_x*y]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx= 1; dy= 0; }
c=grid[x+size_x*(y-1)]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx= 0; dy=-1; }
c=grid[x+size_x*(y+1)]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx= 0; dy= 1; }
c=grid[x-1+size_x*(y-1)]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx=-1; dy= -1; }
c=grid[x+1+size_x*(y-1)]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx= 1; dy= -1; }
c=grid[x-1+size_x*(y+1)]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx=-1; dy= 1; }
c=grid[x+1+size_x*(y+1)]; if (c>v && c!=CELL_OBSTACLE) { v=c; dx= 1; dy= 1; }
ASSERT_(dx!=0 || dy!=0);
x+=dx;
y+=dy;
}
// STEP 4: Translate the path-of-cells to a path-of-2d-points with subsampling
//-------------------------------------------------------------------------------
path.clear();
n = pathcells_x.size();
float xx,yy;
float last_xx = origin.x, last_yy = origin.y;
for (i=0;i<n;i++)
{
// Get cell coordinates:
xx = theMap.idx2x( pathcells_x[i] );
yy = theMap.idx2y( pathcells_y[i] );
// Enough distance??
if (sqrt(square(xx-last_xx)+square(yy-last_yy)) > minStepInReturnedPath)
{
// Add to the path:
path.push_back(CPoint2D(xx,yy));
// For the next iteration:
last_xx = xx;
last_yy = yy;
}
}
// Add the target point:
path.push_back(CPoint2D(target.x,target.y));
// That's all!! :-)
}
| [
"joseluisblancoc@gmail.com"
] | joseluisblancoc@gmail.com |
8cc0907dc0056d26245b63c5eca78e5dff39d384 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_old_hunk_834.cpp | f5cca13850c06f512c053e4e119418b8e9858f45 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | cpp | //----------------------------------------------------------------------------
void cmComputeLinkDepends::DisplayFinalEntries()
{
fprintf(stderr, "target [%s] links to:\n", this->Target->GetName());
for(std::vector<LinkEntry>::const_iterator lei =
this->FinalLinkEntries.begin();
lei != this->FinalLinkEntries.end(); ++lei)
{
if(lei->Target)
{
fprintf(stderr, " target [%s]\n", lei->Target->GetName());
}
else
{
| [
"993273596@qq.com"
] | 993273596@qq.com |
745387a3ab2e1867ccad2f9c2180570e2c7f56c9 | a9ec153f7e79a4e08fd54bd7a0ce511a282b6e7b | /drv/EN-Network_Client_SDK_win_x32/ClientDemo/DlgRemoteShowString.cpp | a500eae0bab1033391a6de4774a7cd0de48042b8 | [] | no_license | stepabogdanov/HikvisionSDK | 5d227747127716cbfb6f4c8e721927645e0f67eb | e00da32d00d07dd64023176f11ac4f3731fd4176 | refs/heads/master | 2021-04-28T07:51:33.245528 | 2018-10-22T09:16:46 | 2018-10-22T09:16:46 | 122,234,801 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,689 | cpp | /**********************************************************
FileName: DlgRemoteShowString.cpp
Description: remote string handling
Date: 2008/05/17
Note: <Global>struct, macro refer to GeneralDef.h, global variants and API refer to ClientDemo.cpp
Modification History:
<version> <time> <desc>
<1.0 > <2008/05/17> <created>
***********************************************************/
#include "stdafx.h"
#include "ClientDemo.h"
#include "DlgRemoteShowString.h"
#include ".\dlgremoteshowstring.h"
// CDlgRemoteShowString dialog
/*********************************************************
Function: CDlgRemoteShowString
Desc: Constructor
Input:
Output:
Return:
**********************************************************/
IMPLEMENT_DYNAMIC(CDlgRemoteShowString, CDialog)
CDlgRemoteShowString::CDlgRemoteShowString(CWnd* pParent /*=NULL*/)
: CDialog(CDlgRemoteShowString::IDD, pParent)
, m_bChkShow(FALSE)
, m_iStringX(0)
, m_iStringY(0)
, m_csString(_T(""))
, m_lLoginID(-1)
, m_iChanShowNum(0)
, dwReturned(0)
{
memset(&m_struShowString, 0, sizeof(m_struShowString));
}
/*********************************************************
Function: ~CDlgRemoteShowString
Desc: destructor
Input:
Output:
Return:
**********************************************************/
CDlgRemoteShowString::~CDlgRemoteShowString()
{
}
/*********************************************************
Function: DoDataExchange
Desc: the map between control and variable
Input:
Output:
Return:
**********************************************************/
void CDlgRemoteShowString::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgRemoteShowString)
DDX_Control(pDX, IDC_COMBO_SHOW_AREA, m_comboShowArea);
DDX_Check(pDX, IDC_CHK_SHOW, m_bChkShow);
DDX_Text(pDX, IDC_EDIT_STRING_X, m_iStringX);
DDX_Text(pDX, IDC_EDIT_STRING_Y, m_iStringY);
DDX_Text(pDX, IDC_EDIT_STRING, m_csString);
//}}AFX_DATA_MAP
}
/*********************************************************
Function: BEGIN_MESSAGE_MAP
Desc: the map between control and function
Input:
Output:
Return:
**********************************************************/
BEGIN_MESSAGE_MAP(CDlgRemoteShowString, CDialog)
//{{AFX_MSG_MAP(CDlgRemoteShowString)
ON_BN_CLICKED(IDC_BTN_STRING_OK, OnBnClickedBtnStringOk)
ON_BN_CLICKED(IDC_BTN_STRING_EXIT, OnBnClickedBtnStringExit)
ON_BN_CLICKED(IDC_BTN_STRING_SET, OnBnClickedBtnStringSet)
ON_CBN_SELCHANGE(IDC_COMBO_SHOW_AREA, OnCbnSelchangeComboShowArea)
ON_BN_CLICKED(IDC_CHK_SHOW, OnBnClickedChkShow)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/*********************************************************
Function: OnInitDialog
Desc: Initialize the dialog
Input: none
Output: none
Return: none
**********************************************************/
BOOL CDlgRemoteShowString::OnInitDialog()
{
CDialog::OnInitDialog();
char szLan[128] = {0};
m_comboShowArea.SetCurSel(0);
char sStringTest[45] = {0};
if (!NET_DVR_GetDVRConfig(m_lLoginID, NET_DVR_GET_SHOWSTRING_V30, m_iChanShowNum, &m_struShowString, sizeof(NET_DVR_SHOWSTRING_V30), &dwReturned))
{
g_pMainDlg->AddLog(g_pMainDlg->m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_SHOWSTRING_V30");
GetDlgItem(IDC_BTN_STRING_OK)->EnableWindow(FALSE);
g_StringLanType(szLan, "获取字符参数失败", "Failure to obtain character parameters");
AfxMessageBox(szLan);
return FALSE;
}
else
{
m_bChkShow = m_struShowString.struStringInfo[0].wShowString;
EnableString(m_bChkShow);
strncpy(sStringTest, m_struShowString.struStringInfo[0].sString, 44);
m_csString.Format("%s", sStringTest);
m_iStringX = m_struShowString.struStringInfo[0].wShowStringTopLeftX;
m_iStringY = m_struShowString.struStringInfo[0].wShowStringTopLeftY;
}
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
/*********************************************************
Function: OnBnClickedBtnStringOk
Desc: finish text overlay settings
Input:
Output:
Return:
**********************************************************/
void CDlgRemoteShowString::OnBnClickedBtnStringOk()
{
UpdateData(TRUE);
char szLan[128] = {0};
int i = m_comboShowArea.GetCurSel();
m_struShowString.struStringInfo[i].wShowString = (WORD)m_bChkShow;
memcpy(m_struShowString.struStringInfo[i].sString, m_csString, 44);
m_struShowString.struStringInfo[i].wStringSize = (WORD)strlen(m_csString);
m_struShowString.struStringInfo[i].wShowStringTopLeftX = (WORD)m_iStringX;
m_struShowString.struStringInfo[i].wShowStringTopLeftY = (WORD)m_iStringY;
if (!NET_DVR_SetDVRConfig(m_lLoginID, NET_DVR_SET_SHOWSTRING_V30, m_iChanShowNum, &m_struShowString, sizeof(NET_DVR_SHOWSTRING_V30)))
{
g_pMainDlg->AddLog(g_pMainDlg->m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_SET_SHOWSTRING_V30");
g_StringLanType(szLan, "设置字符参数失败", "Failure to set character parameters");
AfxMessageBox(szLan);
return ;
}
g_pMainDlg->AddLog(g_pMainDlg->m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_SET_SHOWSTRING_V30");
}
/*********************************************************
Function: OnBnClickedBtnStringExit
Desc: cancel text overlay settings
Input:
Output:
Return:
**********************************************************/
void CDlgRemoteShowString::OnBnClickedBtnStringExit()
{
CDialog::OnCancel();
}
/*********************************************************
Function: OnBnClickedBtnStringSet
Desc: modify text overlay settings
Input:
Output:
Return:
**********************************************************/
void CDlgRemoteShowString::OnBnClickedBtnStringSet()
{
UpdateData(TRUE);
int i = m_comboShowArea.GetCurSel();
m_struShowString.struStringInfo[i].wShowString = (WORD)m_bChkShow;
memcpy(m_struShowString.struStringInfo[i].sString, m_csString, 44);
m_struShowString.struStringInfo[i].wStringSize = (WORD)strlen(m_csString);//m_csString.GetLength();//strlen(m_csString)
m_struShowString.struStringInfo[i].wShowStringTopLeftX = (WORD)m_iStringX;
m_struShowString.struStringInfo[i].wShowStringTopLeftY = (WORD)m_iStringY;
}
/*********************************************************
Function: OnCbnSelchangeComboShowArea
Desc: select text overlay settings
Input:
Output:
Return:
**********************************************************/
void CDlgRemoteShowString::OnCbnSelchangeComboShowArea()
{
UpdateData(TRUE);
int i = m_comboShowArea.GetCurSel();
m_bChkShow = m_struShowString.struStringInfo[i].wShowString;
EnableString(m_bChkShow);
m_csString.Format("%s", m_struShowString.struStringInfo[i].sString);
m_iStringX = m_struShowString.struStringInfo[i].wShowStringTopLeftX;
m_iStringY = m_struShowString.struStringInfo[i].wShowStringTopLeftY;
UpdateData(FALSE);
}
/*********************************************************
Function: OnBnClickedChkShow
Desc: current string display status
Input:
Output:
Return:
**********************************************************/
void CDlgRemoteShowString::OnBnClickedChkShow()
{
UpdateData(TRUE);
EnableString(m_bChkShow);
}
/*********************************************************
Function: EnableString
Desc: change current string display status
Input: bFlag,TRUE/FALSE
Output:
Return:
**********************************************************/
void CDlgRemoteShowString::EnableString(BOOL bFlag)
{
GetDlgItem(IDC_EDIT_STRING)->EnableWindow(m_bChkShow);
GetDlgItem(IDC_EDIT_STRING_X)->EnableWindow(m_bChkShow);
GetDlgItem(IDC_EDIT_STRING_Y)->EnableWindow(m_bChkShow);
}
| [
"stepabogdanov@yandex.ru"
] | stepabogdanov@yandex.ru |
9349d5b9675a33ed8e6ffd78229bd8ac593eea48 | 56ea7ffa07dd75b9eab426640494fd0dc58ea13d | /LinkedList/palindrome_linkedlist.cpp | 950f2b767aaaab79d062c946d9044104fbdce14d | [] | no_license | Zifeng-ZZF/cAlgorithm | 1deb09b24c2a14dd8e961ca0b035ee95f82738ec | c38ffc1cec927f5ce27b631c3d542b72f1ef5c94 | refs/heads/master | 2022-12-08T13:42:24.109168 | 2020-09-12T03:17:44 | 2020-09-12T03:17:44 | 234,512,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cpp | #include <vector>
using namespace std;
struct ListNode {
int val;
ListNode* next;
};
/* use an extra vector to store the elements, then validate using two pointers */
bool isPalindrome(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return true;
}
vector<int> vals;
while (head != nullptr) {
vals.push_back(head->val);
head = head->next;
}
int size = vals.size();
for (int i = 0, j = size - 1; i < j; ++i, --j) {
if (vals[i] != vals[j]) {
return false;
}
}
return true;
}
/* using a global variable to record the first, and use recursion */
ListNode* front;
bool helper(ListNode* cur) {
if (cur != nullptr) {
if (!helper(cur->next)) {
return false;
}
if (cur->val != front->val) {
return false;
}
front = front->next;
}
return true;
}
bool isPalindrone_two(ListNode* head) {
front = head;
return helper(head);
}
/* reverse the second half and compare with the first half */
/* fastest, no extra space solution */
ListNode* reverse(ListNode* head) {
ListNode* temp = nullptr, * prev = nullptr;
while (head != NULL) {
temp = head;
head = head->next;
temp->next = prev;
prev =temp;
}
return prev;
}
bool isPalindrone_three(ListNode* head) {
if (head == NULL || head->next == NULL) {
return true;
}
/* 1. find the length */
int len = 0;
ListNode* temp = head;
while (temp != nullptr) {
++len;
temp = temp->next;
}
/* 2. find the node before the start node of the second half */
len = (len + 1) / 2 - 1; //the cnt of step to move
temp = head;
while (len > 0) {
temp = temp->next;
--len;
}
/* 3. reverse the second half and store its head */
temp = reverse(temp->next);
/* 4. compare the two half */
while (temp != NULL) {
if (temp->val != head->val) {
return false;
}
temp = temp->next;
head = head->next;
}
return true;
} | [
"zhangzifeng@sensetime.com"
] | zhangzifeng@sensetime.com |
a96a78b7ffafebf9dbc1eab5c11cd30b4b4e1e2f | e297a270fb9f774e1ee14028edb4cd85b04793be | /StortSpelprojekt/CascadeShadow.cpp | ef84fee371531c7d11981dd8d4d398e558c55c7f | [] | no_license | Shada/Wanshift | c840b32767ec2d2f040643dd25c803ac34282f06 | 0885f62a361b8630270f398bdb6e4690425d60ff | refs/heads/master | 2021-07-14T02:08:54.290839 | 2021-02-28T02:53:05 | 2021-02-28T02:53:05 | 53,578,881 | 0 | 1 | null | 2016-03-10T11:22:08 | 2016-03-10T11:22:07 | null | ISO-8859-1 | C++ | false | false | 20,681 | cpp | #include "CascadeShadow.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
CascadeShadow::CascadeShadow()
{
Containers containers(std::make_pair(Containers::CONSTBUFFER, MODIFY));
cbuffers = containers.get<ConstantBufferContainer>(Containers::CONSTBUFFER);
}
CascadeShadow::~CascadeShadow()
{
}
void CascadeShadow::init(RenderInterface *_graphics)
{
graphics = _graphics;
int w = (int)graphics->getResolution().x;
int h = (int)graphics->getResolution().y;
cbLightInfoIndex = graphics->getHandleIndex("cbLightInfo", ResourceType::ConstantBuffer);
cbAnimationMatricesIndex = graphics->getHandleIndex("cbAnimationMatrices", ResourceType::ConstantBuffer);
cbWorldIndex = graphics->getHandleIndex("cbWorld", ResourceType::ConstantBuffer);
shadowmapIndex = new ShaderClass( "shadowVS",
"shadowGS",
"",
"",
"",
graphics,
(int)LayoutTypes::LAYOUT_DEFAULT,
false);
shadowcharIndex = new ShaderClass( "shadowCharVS",
"shadowCharGS",
"",
"",
"",
graphics,
(int)LayoutTypes::LAYOUT_DEFAULT,
false);
shadowmapCompileIndex = new ShaderClass("shadowCompileVS",
"shadowCompileGS",
"",
"",
"shadowCompilePS",
graphics,
(int)LayoutTypes::LAYOUT_DEFAULT,
false);
shadowTreeIndex = new ShaderClass( "treeShadowVS",
"treeShadowGS",
"",
"",
"",
graphics,
(int)LayoutTypes::LAYOUT_DEFAULT,
false);
//-----------------------------------------------------------------------------
// Create the compute shader resources
computeIndex = graphics->createComputeShader("shadowComputeCS");
computeTexture = graphics->createTexture2D((int)graphics->getResolution().x, (int)graphics->getResolution().y);
computeUAV = graphics->createUAVTextureView(computeTexture);
computeSRV = graphics->createShaderResourceView(computeTexture);
graphics->addHandle("computetexture", ResourceType::ShaderResourceView, computeSRV);
//----------------------------------------------------------------
// set container
shadowConstants.textureName = "shadowcompile";
shadowConstants.gridWidth = 45;
shadowConstants.gridHeight = 25;
//--------------------------------------------------------------
// Create depth texture for the shadowmap
shadowTextureArray = graphics->createDepthTexture2DArray(SHADOWMAPSIZE, SHADOWMAPSIZE, NROFCASCADES);
shadowDepthStencilViewArray = graphics->createDepthRenderTargetViewArray(shadowTextureArray, NROFCASCADES);
shadowShaderResourceViewArray = graphics->createDepthShaderResourceViewArray(shadowTextureArray, NROFCASCADES);
graphics->addHandle("shadowmapsrv", ResourceType::ShaderResourceViewArray, shadowShaderResourceViewArray);
//--------------------------------------------------------------------------------------------------
// Create the resources for the shadowCompile
//shadowCompileTexture = graphics->createUABuffer((void**)&glm::vec4(), graphics->getResolution().x*graphics->getResolution().y, 4);
shadowCompileTexture = graphics->createTexture2D((int)graphics->getResolution().x, (int)graphics->getResolution().y);
shadowCompileRenderTarget = graphics->createRenderTargetView(shadowCompileTexture);
shadowCompileResourceView = graphics->createShaderResourceView(shadowCompileTexture);
graphics->addHandle(shadowConstants.textureName, ResourceType::ShaderResourceView, shadowCompileResourceView);
//---------------------------------------------------------------------
//Lights initiate kanske inte ska användas senare
// TODO: Move to correct place, should not be here...
glm::mat4 rotatesun = glm::rotate(glm::mat4(), 80.0f, glm::vec3(0, 0, 1));
cbuffers->cbLight.pos[0] = cbuffers->cbLight.pos[0] * rotatesun;
glm::vec4 sunDir(0, 1, 0, 0);
sunDir = glm::normalize(sunDir);
lightDir = sunDir;
cbuffers->cbLight.lightDir = glm::vec3(lightDir);
// glm::vec3 sunUp = glm::cross(glm::cross(glm::vec3(0, 1, 0), sunDir), sunDir);
graphics->updateCBuffer(cbLightInfoIndex, &cbuffers->cbLight);
//---------------------------------------------------------------
// Init frustum scales
frustumScales[0] = 1;
frustumScales[1] = 10;
frustumScales[2] = 50;
frustumScales[3] = 100;
frustumScales[4] = 200;
//----------------------------------------------------------------
// Nulling center and scale
for (int i = 0; i < NROFCASCADES; i++)
{
cascadeSphereCenter[i] = glm::vec3(0.0f, 0.0f, 0.0f);
cascadeSphereRadie[i] = 0.0f;
}
}
void CascadeShadow::shadowing()
{
//if (timeOfDay * 24 > 4 && timeOfDay < 22) // onödigt att skugga på natten som vi har det just nu
{
update();
//******************************//
// models //
//******************************//
graphics->setRenderTargetViews(-1, 0, shadowDepthStencilViewArray);
//graphics->setViewportArray(SHADOWMAPSIZE, SHADOWMAPSIZE, NROFCASCADES);
graphics->setViewport(SHADOWMAPSIZE, SHADOWMAPSIZE);
draw();
graphics->setViewport((int)graphics->getResolution().x, (int)graphics->getResolution().y);
}
}
void CascadeShadow::updateLight(float _dt)
{
timeOfDay = cbuffers->cbEveryFrame.timeofDay;
glm::mat4 rotatesun;
if (cbuffers->cbEveryFrame.dayBool.x >= 1.0f)
rotatesun = glm::rotate(glm::mat4(), timeOfDay * 180, glm::vec3(0, 0, 1));
else
rotatesun = glm::rotate(glm::mat4(), 180 + ((1 - timeOfDay) * 180), glm::vec3(0, 0, 1));
cbuffers->cbLight.lightDir = glm::vec3(lightDir * rotatesun);
cbuffers->cbLight.lightDir = glm::normalize(cbuffers->cbLight.lightDir);
//cbuffers->cbLight.pos[0] = glm::vec4(player->position,1) - lightDir * 10000;
glm::vec3 vDirectionalDir = cbuffers->cbLight.lightDir;
// Find the view matrix
glm::vec3 vWorldCenter = glm::vec3(camera->vEye) + camera->vLookDir * frustumScales[4] * 0.5f;
glm::vec3 vPos = vWorldCenter;
glm::vec3 vLookAt = vWorldCenter + vDirectionalDir * 30.0f;
glm::vec3 vUp;
glm::vec3 vRight = glm::vec3(1.0f, 0.0f, 0.0f);
vUp = glm::cross(vDirectionalDir, vRight);
vUp = glm::normalize(vUp);
glm::mat4 mShadowView;
mShadowView = glm::lookAt(vPos, vLookAt, vUp);
cbuffers->cbLight.lightView = camera->viewMatrix;
cbuffers->cbLight.lightProj = camera->projMatrix;
cbuffers->cbLight.CascadeViewProj[0] = cbuffers->cbLight.lightProj * cbuffers->cbLight.lightView;
cbuffers->cbLight.CascadeViewProj[1] = cbuffers->cbLight.CascadeViewProj[0];
cbuffers->cbLight.CascadeViewProj[2] = cbuffers->cbLight.CascadeViewProj[0];
cbuffers->cbLight.CascadeViewProj[3] = cbuffers->cbLight.CascadeViewProj[0];
graphics->updateCBuffer(cbLightInfoIndex, &cbuffers->cbLight);
}
void CascadeShadow::draw()
{
UINT stride;
UINT offset;
glm::mat4 matrix;
CBWorldData world;
shadowcharIndex->use();
graphics->setDepthStencilState(0);
graphics->setBlendState(0);
stride = sizeof(DefaultVertex);
offset = 0;
graphics->setVertexBuffers(0, player->playerModel.getVertexBufferID(), 1, &stride, &offset);
stride = sizeof(float)* 15;
graphics->setVertexBuffers(1, player->playerModel.getAnimationAt(0).weightBufferID, 1, &stride, &offset);
graphics->setInputLayout((int)LayoutTypes::LAYOUT_ANIMATION);
graphics->setTopology(0);
graphics->setRasterState(1);
graphics->setCBuffers(5, 1, cbAnimationMatricesIndex);
CBAnimationMatrices cbanim;
for (uint i = 0; i < player->playerModel.getGroupAmount(); i++)
{
matrix = glm::translate(glm::mat4x4(), glm::vec3(player->position.x, player->position.y - 15.0f, player->position.z));
matrix = glm::rotate(matrix, player->rot * 180 / 3.14f, glm::vec3(0.f, 1.f, 0.f));
matrix = glm::scale(matrix, glm::vec3(1.5f, 1.5f, 1.5f));
world.mWorld = matrix;
world.mWorldInv = matrix;
graphics->updateCBuffer(cbWorldIndex, &world);
cbanim.interpolation[0] = player->animationInterpolation;
for(int j = 0; j < 15; j++)
{
cbanim.mat1[j] = player->playerModel.getAnimationAt(player->animationState).frameData.at(player->prevAnimationFrame).matrices[j];
cbanim.mat2[j] = player->playerModel.getAnimationAt(player->animationState).frameData.at(player->animationFrame).matrices[j];
}
graphics->updateCBuffer(cbAnimationMatricesIndex, &cbanim);
int startIndex = player->playerModel.getGroupAt(i).startIndex;
int amount = player->playerModel.getGroupAt(i).vertexAmount;
graphics->draw(amount, startIndex);
}
//**********************************//
// terrain //
//**********************************//
//stride = sizeof(DefaultVertex);
//offset = 0;
//shadowmapIndex->use();
//matrix = glm::mat4x4();
//world.mWorld = matrix;
//world.mWorldInv = matrix;
//graphics->updateCBuffer(0, &world);
//graphics->setInputLayout((int)LayoutTypes::LAYOUT_DEFAULT);
//// Set the vertex buffers
//graphics->setRasterState(0);
////// Set the vertex buffers
graphics->setVertexBuffers(0, terrain->bufferID, 1, &stride, &offset);
graphics->setIndexBuffer(terrain->indexBufferID, offset);
//// fix the shadow frustum culling later
////ExtractFrustumPoints();
//terrain->tesselationchunks.clear();
//terrain->smallNodes.at(0).draw(&camera->frustum);
////terrain->mediumNodes.at(0).draw(&camera->frustum);
////terrain->largeNodes.at(0).draw(&camera->frustum);
//for (uint i = 0; i < terrain->tesselationchunks.size(); i++)
// graphics->drawIndexed(terrain->nVerticesPerTiny / (TINYSPLITTING*TINYSPLITTING), terrain->tesselationchunks.at(i), 0);
//------------------------------------------------------
// Draw forest
//shadowTreeIndex->use();
//forest->drawShadow();
}
void CascadeShadow::ExtractFrustumPoints()
{
float clip[16];
clip[0] = globalShadowView[0].x * globalShadowProjection[0].x + globalShadowView[0].z * globalShadowProjection[2].x;
clip[1] = globalShadowView[0].y * globalShadowProjection[1].y + globalShadowView[0].z * globalShadowProjection[2].y;
clip[2] = globalShadowView[0].z * globalShadowProjection[2].z;
clip[3] = globalShadowView[0].z * globalShadowProjection[2].w;
clip[4] = globalShadowView[1].x * globalShadowProjection[0].x + globalShadowView[1].z * globalShadowProjection[2].x;
clip[5] = globalShadowView[1].y * globalShadowProjection[1].y + globalShadowView[1].z * globalShadowProjection[2].y;
clip[6] = globalShadowView[1].z * globalShadowProjection[2].z;
clip[7] = globalShadowView[1].z * globalShadowProjection[2].w;
clip[8] = globalShadowView[2].x * globalShadowProjection[0].x + globalShadowView[2].z * globalShadowProjection[2].x;
clip[9] = globalShadowView[2].y * globalShadowProjection[1].y + globalShadowView[2].z * globalShadowProjection[2].y;
clip[10] = globalShadowView[2].z * globalShadowProjection[2].z;
clip[11] = globalShadowView[2].z * globalShadowProjection[2].w;
clip[12] = globalShadowView[3].x * globalShadowProjection[0].x + globalShadowView[3].z * globalShadowProjection[2].x;
clip[13] = globalShadowView[3].y * globalShadowProjection[1].y + globalShadowView[3].z * globalShadowProjection[2].y;
clip[14] = globalShadowView[3].z * globalShadowProjection[2].z + globalShadowView[3].w * globalShadowProjection[3].z;
clip[15] = globalShadowView[3].z * globalShadowProjection[2].w;
// Left plane
frustum.leftPlane.x = clip[3] + clip[0];
frustum.leftPlane.y = clip[7] + clip[4];
frustum.leftPlane.z = clip[11] + clip[8];
frustum.leftPlane.w = clip[15] + clip[12];
// Right plane
frustum.rightPlane.x = clip[3] - clip[0];
frustum.rightPlane.y = clip[7] - clip[4];
frustum.rightPlane.z = clip[11] - clip[8];
frustum.rightPlane.w = clip[15] - clip[12];
// Bottom plane
frustum.botPlane.x = clip[3] + clip[1];
frustum.botPlane.y = clip[7] + clip[5];
frustum.botPlane.z = clip[11] + clip[9];
frustum.botPlane.w = clip[15] + clip[13];
// Top plane
frustum.topPlane.x = clip[3] - clip[1];
frustum.topPlane.y = clip[7] - clip[5];
frustum.topPlane.z = clip[11] - clip[9];
frustum.topPlane.w = clip[15] - clip[13];
// Near plane
frustum.nearPlane.x = clip[3] + clip[2];
frustum.nearPlane.y = clip[7] + clip[6];
frustum.nearPlane.z = clip[11] + clip[10];
frustum.nearPlane.w = clip[15] + clip[14];
// Far plane
frustum.farPlane.x = clip[3] - clip[2];
frustum.farPlane.y = clip[7] - clip[6];
frustum.farPlane.z = clip[11] - clip[10];
frustum.farPlane.w = clip[15] - clip[14];
//// Get the camera bases
//const glm::vec3 camPos = glm::vec3(camera->vEye);
//const glm::vec3 camUp = glm::vec3(camera->vUp);
//const glm::vec3 camForward = camera->vLookDir;
//const glm::vec3 camRight = glm::cross(glm::vec3(camUp), camForward);
//// Calculate the tangent values (this can be cached
//const float fTanFOVX = tanf(camera->aspectRatio * camera->FOV);
//const float fTanFOVY = tanf(camera->aspectRatio);
//// Calculate the points on the near plane
//arrFrustumCorners[0] = camPos + (-camRight * fTanFOVX + camUp * fTanFOVY + camForward) * frustumScales[0];
//arrFrustumCorners[1] = camPos + (camRight * fTanFOVX + camUp * fTanFOVY + camForward) * frustumScales[0];
//arrFrustumCorners[2] = camPos + (camRight * fTanFOVX - camUp * fTanFOVY + camForward) * frustumScales[0];
//arrFrustumCorners[3] = camPos + (-camRight * fTanFOVX - camUp * fTanFOVY + camForward) * frustumScales[0];
//// Calculate the points on the far plane
//arrFrustumCorners[4] = camPos + (-camRight * fTanFOVX + camUp * fTanFOVY + camForward) * frustumScales[1];
//arrFrustumCorners[5] = camPos + (camRight * fTanFOVX + camUp * fTanFOVY + camForward) * frustumScales[1];
//arrFrustumCorners[6] = camPos + (camRight * fTanFOVX - camUp * fTanFOVY + camForward) * frustumScales[1];
//arrFrustumCorners[7] = camPos + (-camRight * fTanFOVX - camUp * fTanFOVY + camForward) * frustumScales[1];
}
void CascadeShadow::ExtractFrustumBoundSphere(float fNear, float fFar, glm::vec3& vBoundCenter, float& fBoundRadius)
{
// Get the camera bases
const glm::vec3 camPos = glm::vec3(camera->vEye);
const glm::vec3 camUp = glm::vec3(camera->vUp);
const glm::vec3 camForward = camera->vLookDir;
const glm::vec3 camRight = glm::vec3(camera->vRight);
// Calculate the tangent values (this can be cached as long as the FOV doesn't change)
const float fTanFOVX = tanf(camera->aspectRatio * (camera->FOV/180 * 3.14f));
const float fTanFOVY = tanf(camera->aspectRatio);
// The center of the sphere is in the center of the frustum
vBoundCenter = camPos + camForward * (fNear + 0.5f * (fNear + fFar));
// Radius is the distance to one of the frustum far corners
glm::vec3 temp1 = -camRight * fTanFOVX;
glm::vec3 temp2 = camUp * fTanFOVY;
glm::vec3 temp3 = (temp1 + temp2 + camForward);
glm::vec3 temp4 = temp3 * fFar;
glm::vec3 tempfar = camPos + (-camRight * fTanFOVX + camUp * fTanFOVY + camForward) * fFar;
glm::vec3 tempnear = camPos + (-camRight * fTanFOVX + camUp * fTanFOVY + camForward) * fNear;
glm::vec3 vBoundSpan = camPos + temp4 - vBoundCenter;
fBoundRadius = glm::length(vBoundSpan);
}
bool CascadeShadow::cascadeNeedsUpdate(glm::mat4 mShadowView, int iCascadeIdx, glm::vec3* newCenter, glm::vec3* vOffset)
{
// Find the offset between the new and old bound ceter
glm::vec4 vOldCenterInCascade;
vOldCenterInCascade = mShadowView * glm::vec4(cascadeSphereCenter[iCascadeIdx], 1); //----------------------------------------------------------------
//vOldCenterInCascade = glm::vec4(cascadeSphereCenter[iCascadeIdx], 1) * mShadowView;
glm::vec3 vNewCenterInCascade;
vNewCenterInCascade = glm::vec3(mShadowView * glm::vec4(newCenter->x, newCenter->y, newCenter->z, 1)); //------------------------------------------------------------------------
//vNewCenterInCascade = glm::vec3( glm::vec4(newCenter, 1) * mShadowView);
glm::vec3 vCenterDiff = vNewCenterInCascade - glm::vec3(vOldCenterInCascade);
// Find the pixel size based on the diameters and map pixel size
float fPixelSize = (float)SHADOWMAPSIZE / (2.0f * cascadeSphereRadie[iCascadeIdx]);
float fPixelOffX = vCenterDiff.x * fPixelSize;
float fPixelOffY = vCenterDiff.y * fPixelSize;
//Check if the center moved at least half a pixel unit
bool bNeedUpdate = abs(fPixelOffX) > 0.5f || abs(fPixelOffY) > 0.5f;
if (bNeedUpdate)
{
// Round to the
vOffset->x = floorf(0.5f + fPixelOffX) / fPixelSize;
vOffset->y = floorf(0.5f + fPixelOffY) / fPixelSize;
vOffset->z = vCenterDiff.z;
}
return bNeedUpdate;
}
void CascadeShadow::update()
{
glm::vec3 vDirectionalDir = cbuffers->cbLight.lightDir;
// Find the view matrix
glm::vec3 vWorldCenter = glm::vec3(camera->vEye) + camera->vLookDir * (frustumScales[4] * 0.4f);
glm::vec3 vPos = player->position;
glm::vec3 vLookAt = player->position + vDirectionalDir*30.0f;
glm::vec3 vUp = glm::vec3(0,1,0);
glm::vec3 vRight = glm::vec3(camera->vRight);
vUp = glm::cross(vDirectionalDir, vUp);
vUp = glm::normalize(vRight);
glm::mat4 mShadowView;
mShadowView = glm::lookAt(vPos, vLookAt, vUp);
//mShadowView = camera->viewMatrix;
//mShadowView = lightTest.lightView;
cbuffers->cbLight.lightView = mShadowView;
globalShadowView = mShadowView;
// Get the bounds for the shadow space
float radie;
ExtractFrustumBoundSphere(frustumScales[0], frustumScales[4], shadowSphereCenter, radie);
shadowSphereRadie = glm::max(shadowSphereRadie, radie); // Expend the radius to compensate for numerical errors
// Find the projection matrix
glm::mat4 mShadowProj;
//mShadowProj = glm::ortho(-shadowSphereRadie, shadowSphereRadie, -shadowSphereRadie, shadowSphereRadie, -shadowSphereRadie, shadowSphereRadie);
mShadowProj = orthoCalc(shadowSphereRadie, shadowSphereRadie, -shadowSphereRadie, shadowSphereRadie);
globalShadowProjection = mShadowProj;
// The combined transformation from world to shadow space
worldToShadow = mShadowProj * mShadowView;
glm::mat4 shadowViewInv;
shadowViewInv = glm::inverse(mShadowView);
for (int iCascadeIdx = 0; iCascadeIdx < NROFCASCADES; iCascadeIdx++)
{
glm::mat4 cascadeTrans;
glm::mat4 cascadeScale;
// To avoid anti flickering we need to make the transformation invariant to camera rotation and translation
// By encapsulating the cascade frustum with a sphere we achive the rotation invariance
glm::vec3 vNewCenter;
ExtractFrustumBoundSphere(frustumScales[iCascadeIdx], frustumScales[iCascadeIdx + 1], vNewCenter, radie);
cascadeSphereRadie[iCascadeIdx] = glm::max(cascadeSphereRadie[iCascadeIdx], radie); // Expend the radius to compensate for numerical errors
// Only update the cascade bounds if it moved at least a full pixel unit
// This makes the transformation invariant to translation
glm::vec3 vOffset;
if (cascadeNeedsUpdate(mShadowView, iCascadeIdx, &vNewCenter, &vOffset))
{
localShadowProjection[iCascadeIdx] = orthoCalc(cascadeSphereRadie[iCascadeIdx], cascadeSphereRadie[iCascadeIdx], -cascadeSphereRadie[iCascadeIdx], cascadeSphereRadie[iCascadeIdx]);
}
}
cbuffers->cbLight.CascadeViewProj[0] = localShadowProjection[0] * mShadowView;
cbuffers->cbLight.CascadeViewProj[1] = localShadowProjection[1] * mShadowView;
cbuffers->cbLight.CascadeViewProj[2] = localShadowProjection[2] * mShadowView;
cbuffers->cbLight.CascadeViewProj[3] = localShadowProjection[3] * mShadowView;
graphics->updateCBuffer(cbLightInfoIndex, &cbuffers->cbLight);
}
glm::mat4 CascadeShadow::orthoCalc(float w, float h, float zf, float zn)
{
glm::mat4 out;
out[0][0] = 2 / w;
out[1][1] = 2 / h;
out[2][2] = 1 / (zf - zn);
out[3][2] = zn / (zn - zf);
out[3][3] = 1;
return out;
}
void CascadeShadow::compileShadow()
{
shadowmapCompileIndex->use();
glm::mat4 matrix;
CBWorldData world;
graphics->updateCBuffer(cbWorldIndex, &world);
//this is now the third time this is updated, is this necessary?
graphics->updateCBuffer(cbLightInfoIndex, &cbuffers->cbLight);
graphics->setPixelShaderResource(1, graphics->getDepthResourceView(), 1);
graphics->setPixelShaderResource(2, graphics->getHandleIndex("shadowmapsrv", ResourceType::ShaderResourceViewArray), 1);
graphics->setInputLayout((int)LayoutTypes::LAYOUT_DEFAULT);
graphics->setTopology(1);
graphics->setRasterState(0);
graphics->setRenderTargetViews(shadowCompileRenderTarget,1,-1);
graphics->draw(1, 0);
graphics->setRenderTargetViews(-1, 1, -1);
blurShadow();
}
void CascadeShadow::blurShadow()
{
graphics->CSexecDouble(computeUAV, shadowCompileResourceView, graphics->getHandleIndex("normal", ResourceType::ShaderResourceView), computeIndex, shadowConstants.gridWidth, shadowConstants.gridHeight, 1);
//graphics->CSexecSingle(computeUAV, graphics->getHandleIndex("rainnoise",ResourceType::ShaderResourceView), computeIndex, shadowConstants.gridWidth, shadowConstants.gridHeight, 1);
} | [
"limejuggler@users.noreply.github.com"
] | limejuggler@users.noreply.github.com |
b3ef7aa5ad1cdff813bb20cb4b6e401ba361ec65 | 1d9c22c19dc6fb9c0bdf0c77a3f4646f6ca64d92 | /moui/widgets/label.h | 8f5157a3319bb4347d16c5cefaa3583f8ea68f65 | [
"Apache-2.0"
] | permissive | ollix/moui | 83169723903705646175860ac7f7570a2a134358 | f6f574f3b1c45c8fb8fc7b44b4783d6c91fe49f7 | refs/heads/master | 2023-04-09T06:28:34.513187 | 2023-03-28T08:35:55 | 2023-03-28T08:35:55 | 16,637,370 | 67 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 7,577 | h | // Copyright (c) 2014 Ollix. 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.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#ifndef MOUI_WIDGETS_LABEL_H_
#define MOUI_WIDGETS_LABEL_H_
#include <string>
#include "moui/base.h"
#include "moui/nanovg_hook.h"
#include "moui/widgets/widget.h"
namespace moui {
// The `Label` widget implements a read-only text view.
class Label : public Widget {
public:
enum class Alignment {
kLeft, // aligns text along the left edge
kCenter, // aligns text equally along both sides of the center line
kRight, // aligns text along the right edge
kTop, // aligns text along the top edge
kMiddle, // aligns text equally along both sides of the middle line
kBottom, // aligns text along the bottom edge
};
Label();
explicit Label(const std::string& text);
Label(const std::string& text, const std::string& font_name);
~Label();
// Inherited from `Widget` class;
void Redraw() final;
// Sets the default font baseline.
static void SetDefaultFontBaseline(const float font_baseline);
// Sets the default font name.
static void SetDefaultFontName(const std::string& name);
// Sets the default font size.
static void SetDefaultFontSize(const float font_size);
// Sets the default font size scale.
static void SetDefaultFontSizeScale(const float font_size_scale);
// Updates the label's width to fit the text. If `max_width` is specified,
// the width will be shrunk to fit the displayed text.
void UpdateWidthToFitText(NVGcontext* context, const float max_width);
// Updates the label's width to fit the text. The width is calculated based
// on fitting all text in one line.
void UpdateWidthToFitText(NVGcontext* context);
// Accessors and setters.
bool adjusts_font_size_to_fit_width() const {
return adjusts_font_size_to_fit_width_;
}
void set_adjusts_font_size_to_fit_width(const bool value);
bool adjusts_label_height_to_fit_width() const {
return adjusts_label_height_to_fit_width_;
}
void set_adjusts_label_height_to_fit_width(const bool value);
float font_baseline() const;
void set_font_baseline(const float font_baseline);
std::string font_name() const;
void set_font_name(const std::string& name);
float font_size() const;
void set_font_size(const float font_size);
float font_size_scale() const;
void set_font_size_scale(const float font_size_scale);
float font_size_to_render() const { return font_size_to_render_; }
float line_height() const { return line_height_; }
void set_line_height(const float line_height);
float minimum_scale_factor() const { return minimum_scale_factor_; }
void set_minimum_scale_factor(const float factor);
int number_of_lines() const { return number_of_lines_; }
void set_number_of_lines(const int number);
std::string text() const { return text_; }
void set_text(const std::string& text);
NVGcolor text_color() const { return text_color_; }
void set_text_color(const NVGcolor text_color);
Alignment text_horizontal_alignment() const {
return text_horizontal_alignment_;
}
void set_text_horizontal_alignment(const Alignment alignment);
Alignment text_vertical_alignment() const { return text_vertical_alignment_; }
void set_text_vertical_alignment(const Alignment alignment);
private:
struct CachedLabelWidth {
float font_size_to_render;
std::string font_name;
std::string text;
float width;
};
// Configures text attributes through nanovg APIs.
void ConfigureTextAttributes(NVGcontext* context);
// Inherited from `Widget` class.
void Render(NVGcontext* context) final;
// Inherited from `Widget` class. The implementation prepares the rendering
// environemnt according various configurations to render expected results.
bool WidgetViewWillRender(NVGcontext* context) final;
// Indicates whether the font size should be reduced in order to fit the text
// into the label's bounding rectangle. The default value is no.
bool adjusts_font_size_to_fit_width_;
// Indicates whether the height of the label should be increased automatically
// in order to fit the text into the label's bounding rectangle. The vertical
// position of the label will also be adjusted as well to respect
// `text_vertical_alignment_`. The default value is `false`.
bool adjusts_label_height_to_fit_width_;
// Indicates the vertical offset of the font baseline. The default value is 0.
float font_baseline_;
// The font name of the font that applies to enitre string of text. Note
// that the font name must previously registered through `nvgCreateFont()`,
// or nothing will display on the screen.
std::string font_name_;
// The size of the font that applies to entire string of text. The default
// value is 12. If the value is set to 0, the font size set through
// `SetDefaultFontSize()` will be used.
float font_size_;
// Indicates the scale factor multiplied to the `font_size_` to get the final
// font size to render. The default value is 1.0.
float font_size_scale_;
// The actual font size for rendering on screen. This value is calculated
// automatically in `WidgetViewWillRender()` according to various
// configurations.
float font_size_to_render_;
// Indicates the proportional line height of current text style. The line
// height is specified as multiple of font size.
float line_height_;
// The minimum scale factor supported for the label's text. The value
// indicates the smallest multiplier for the current font size that yields
// an acceptable font size to use when rendering the label's text. If the
// value is set to 0, the font size to render can be as small as possible.
// The default value is 0.
float minimum_scale_factor_;
// The maximum number of lines to use for rendering text. The default value
// is 1. To remove any maximum limit, and use as many lines as needed, set
// the value to 0.
int number_of_lines_;
// Indicates whether the label should prepare the environment before actual
// rendering. If true, the preparation will be done in `WidgetWillRender()`.
bool should_prepare_for_rendering_;
// The text displayed by the label.
std::string text_;
// The color of the text.
NVGcolor text_color_;
// The actual text for rendering on screen. This value is populated
// automatically in `WidgetWillRender()` according to various configurations.
std::string text_to_render_;
// The technique to use for aligning the text horizontally. The value must
// be one of `Alignment::kLeft`, `Alignment::kCenter`, `Alignment::kRight`.
// The default value is `Alignment::kLeft`.
Alignment text_horizontal_alignment_;
// The technique to use for aligning the text vertically. The value must
// be one of `Alignment::kTop`, `Alignment::kMiddle`, `Alignment::kBottom`.
// The default value is `Alignment::kTop`.
Alignment text_vertical_alignment_;
DISALLOW_COPY_AND_ASSIGN(Label);
};
} // namespace moui
#endif // MOUI_WIDGETS_LABEL_H_
| [
"olliwang@ollix.com"
] | olliwang@ollix.com |
a24cf67c7795c113f9602b76c37fba334848cf10 | db0ca5bd963b200c045d7b5307823015b3914028 | /subSets.cpp | 7c6f0b017941117ccd3dac2e57c4f026bf4c1fc4 | [] | no_license | clxzz24/cpp_source | 9e452b3b9dd4fb64b561bf89502b889cb415def5 | 06184e7fc2e74cf8c7d46cc1d9bb659a37b37627 | refs/heads/master | 2020-03-22T21:23:59.611386 | 2018-07-12T08:23:08 | 2018-07-12T08:23:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include <iostream>
#include <vector>
#include <math.h>
using namespace std;
vector<vector<int>> subSets1(vector<int> nums)
{
int n = nums.size();
int m = pow(2, n);
vector<vector<int>> res(m);
for (int i = 0; i<n; i++)
{
for (int j = 0; j<m; j++)
{
if((j>>i) & 1)
{
res[j].push_back(nums[i]);
}
}
}
return res;
}
int main()
{
vector<int> nums(3);
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
vector<vector<int>> res = subSets(nums);
for (int i = 0; i < nums.size();i++)
{
cout<<res[i]<<endl;
}
} | [
"noreply@github.com"
] | clxzz24.noreply@github.com |
8cbb7f7ce4a403ca47f4d38a42d762e00d8a8d79 | 5fe1a08be4a62ff19d5d61e4716742d4fb292297 | /买卖股票的最佳时机II.cpp | c64293ba92d28e236cb7c349e6189d14d8987e37 | [] | no_license | songclei/leetcode | 85e92e1e6b456fcf686812942eb14bd393459987 | 6d33f9ee2d67408c2cff11c550ccef7f58c76369 | refs/heads/master | 2020-05-02T14:34:17.406765 | 2019-08-24T09:39:20 | 2019-08-24T09:39:20 | 178,014,665 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <math.h>
#include <algorithm>
#include <unordered_set>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if (size == 0 || size == 1)
return 0;
int max_profit = 0;
int i = 0, j = 0;
while (i < size-1 && j < size-1) {
while (i < size - 1 && prices[i+1] <= prices[i]) i++;
j = i;
while (j < size-1 && prices[j+1] >= prices[j]) j++;
max_profit += prices[j] - prices[i];
i = j;
}
return max_profit;
}
}; | [
"1500017738@pku.edu.cn"
] | 1500017738@pku.edu.cn |
f3e2ab6bbe06e4378013f10a5881364d6735049d | f3dd00b1dfd95541d2665a95e0d5c5c011170ba8 | /src/common/unbounded_blocking_queue.cc | b548cf4fc2feb3949a1a90eb44a6724d3f123895 | [] | no_license | exabytes18/kiwi | 0aebf55d312331b6912011d26258d29c179eecdc | a1736db3ffb573a8628977a0fbf4e637d77afeea | refs/heads/master | 2021-01-23T16:28:20.632923 | 2018-08-07T08:01:51 | 2018-08-07T08:04:51 | 93,299,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38 | cc | #include "unbounded_blocking_queue.h"
| [
"exabytes18@gmail.com"
] | exabytes18@gmail.com |
3e6cba56a0d13f0957a86abb8641567aac97c60f | 84897b6a25f876b21246c2c7e1404c9c411be987 | /src/include/format/rar/RCRarItem.h | 405e1ed1b4b8e0190c5ffa5968f74464e713b6cd | [] | no_license | drivestudy/HaoZip | 07718a53e38bc5893477575ddf3fccfb3b18c5fd | 9e0564b4a11870224543357004653b798fd625e0 | refs/heads/master | 2021-07-24T06:33:24.651453 | 2017-11-05T01:19:18 | 2017-11-05T01:19:18 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,899 | h | /********************************************************************************
* 版权所有(C)2008,2009,2010,好压软件工作室,保留所有权利。 *
********************************************************************************
* 作者 : HaoZip *
* 版本 : 1.7 *
* 联系方式: haozip@gmail.com *
* 官方网站: www.haozip.com *
********************************************************************************/
#ifndef __RCRarItem_h_
#define __RCRarItem_h_ 1
#include "RCRarHeader.h"
#include "base/RCString.h"
#include "base/RCSmartPtr.h"
BEGIN_NAMESPACE_RCZIP
struct RCRarTime
{
/** dos时间
*/
uint32_t m_dosTime;
/** 低位秒
*/
byte_t m_lowSecond;
/** 时间
*/
byte_t m_subTime[3];
};
struct RCRarItem
{
/** 大小
*/
uint64_t m_size;
/** 包大小
*/
uint64_t m_packSize;
/** 创建时间
*/
RCRarTime m_cTime;
/** 访问时间
*/
RCRarTime m_aTime;
/** 更改时间
*/
RCRarTime m_mTime;
/** crc
*/
uint32_t m_fileCRC;
/** 属性
*/
uint32_t m_attrib;
/** 风格
*/
uint16_t m_flags;
/** 平台系统
*/
byte_t m_hostOS;
/** 解压版本
*/
byte_t m_unPackVersion;
/** 方法
*/
byte_t m_method;
/** 是否有创建时间
*/
bool m_cTimeDefined;
/** 是否有访问时间
*/
bool m_aTimeDefined;
/** 名字
*/
RCStringA m_name;
/** unicode名字
*/
RCString m_unicodeName;
/** salt(加密用的)
*/
byte_t m_salt[8];
/** 是否加密
@return 是返回true,否咋返回false
*/
bool IsEncrypted() const { return (m_flags & RCRarHeader::NFile::kEncrypted) != 0; }
/** 是否是固实压缩
@return 是返回true,否咋返回false
*/
bool IsSolid() const { return (m_flags & RCRarHeader::NFile::kSolid) != 0; }
/** 是否有注释
@return 是返回true,否咋返回false
*/
bool IsCommented() const { return (m_flags & RCRarHeader::NFile::kComment) != 0; }
/** 之前是否有分卷包
@return 是返回true,否咋返回false
*/
bool IsSplitBefore() const { return (m_flags & RCRarHeader::NFile::kSplitBefore) != 0; }
/** 之后是否有分卷包
@return 是返回true,否咋返回false
*/
bool IsSplitAfter() const { return (m_flags & RCRarHeader::NFile::kSplitAfter) != 0; }
/** 是否有salt
@return 有返回true,否咋返回false
*/
bool HasSalt() const { return (m_flags & RCRarHeader::NFile::kSalt) != 0; }
/** 是否有扩展时间
@return 有返回true,否咋返回false
*/
bool HasExtTime() const { return (m_flags & RCRarHeader::NFile::kExtTime) != 0; }
/** 是否有unicode名字
@return 有返回true,否咋返回false
*/
bool HasUnicodeName() const { return (m_flags & RCRarHeader::NFile::kUnicodeName) != 0; }
/** 是否是老版本
@return 是返回true,否咋返回false
*/
bool IsOldVersion() const { return (m_flags & RCRarHeader::NFile::kOldVersion) != 0; }
/** 获取字典大小
@return 返回字典大小
*/
uint32_t GetDictSize() const { return (m_flags >> RCRarHeader::NFile::kDictBitStart) & RCRarHeader::NFile::kDictMask; }
/** 是否是路径
@return 是返回true,否咋返回false
*/
bool IsDir() const;
/** 是否是忽略项
@return 是返回true,否咋返回false
*/
bool IgnoreItem() const;
/** 获取windows下的属性
@return 返回属性
*/
uint32_t GetWinAttributes() const;
/** 默认构造函数
*/
RCRarItem():
m_cTimeDefined(false),
m_aTimeDefined(false) {}
};
class RCRarItemEx: public RCRarItem
{
public:
/** 获取整个大小
@return 返回整个大小
*/
uint64_t GetFullSize() const { return m_mainPartSize + m_commentSize + m_alignSize + m_packSize; };
/** 获取注释位置
@return 返回注释位置
*/
uint64_t GetCommentPosition() const { return m_position + m_mainPartSize; };
/** 获取数据位置
@return 返回数据位置
*/
uint64_t GetDataPosition() const { return GetCommentPosition() + m_commentSize + m_alignSize; };
public:
/** 位置
*/
uint64_t m_position;
/** 主断大小
*/
uint16_t m_mainPartSize;
/** 注释大小
*/
uint16_t m_commentSize;
/** 对齐大小
*/
uint16_t m_alignSize;
};
/** RCRarItemEx智能指针
*/
typedef RCSharedPtr<RCRarItemEx> RCRarItemExPtr ;
END_NAMESPACE_RCZIP
#endif //__RCRarItem_h_
| [
"zhou_jiafeng@aliyun.com"
] | zhou_jiafeng@aliyun.com |
5b16f7c3a2185b60a4c160424b1175e38720a06f | 7d298127f6c9f638420d80f01bbc3635f632b602 | /tests/3rdparty/testngpp/tests/3rdparty/testngppst/include/testngppst/TypeTraits.h | 940b214dfa3b598b9b8bd06a44cf744d0d7735e9 | [
"Apache-2.0",
"LGPL-3.0-only",
"GPL-3.0-or-later"
] | permissive | sinojelly/mockcpp | 1bbdbee7623fa51972e1f94815ffa93ef770e112 | 7b7eb8b8a7837813d91ee1ae9354f352605fc270 | refs/heads/master | 2023-09-03T04:04:32.174336 | 2022-11-08T07:15:41 | 2022-11-08T07:15:41 | 33,052,375 | 69 | 42 | Apache-2.0 | 2023-08-25T08:25:18 | 2015-03-28T22:17:23 | C++ | UTF-8 | C++ | false | false | 1,371 | h | #ifndef __TESTNGPPST_TYPE_TRAITS_H
#define __TESTNGPPST_TYPE_TRAITS_H
#include <testngppst/testngppst.h>
TESTNGPPST_NS_START
/*
* For non-reference type
*/
template <typename T>
struct TypeTraits
{
typedef T Raw;
typedef T& RefRaw;
typedef T Type;
typedef T& Ref;
};
/*
* For non-reference type
*/
template <typename T>
struct TypeTraits<const T>
{
typedef T Raw;
typedef T& RefRaw;
typedef T Type;
typedef const T& Ref;
};
/*
* For non-reference type
*/
template <typename T>
struct TypeTraits<const T*>
{
typedef T* Raw;
typedef T*& RefRaw;
typedef const T* Type;
typedef const T*& Ref;
};
/*
* For reference type
*/
template <typename T>
struct TypeTraits<T&>
{
typedef T Raw;
typedef T& RefRawx;
typedef T Type;
typedef T& Ref;
};
/*
* For reference type
*/
template <typename T>
struct TypeTraits<const T&>
{
typedef T Raw;
typedef T& RefRaw;
typedef T Type;
typedef const T& Ref;
};
/*
* For non-reference type
*/
template <>
struct TypeTraits<void>
{
typedef void Raw;
typedef void RefRaw;
typedef void Type;
typedef void Ref;
};
TESTNGPPST_NS_END
#endif // __TESTNGPPST_TYPE_TRAITS_H
| [
"sinojelly@163.com"
] | sinojelly@163.com |
d450d709825eafb2d165857e0b5a69d3dc184357 | fa2d21f6415046b8dc0461ccc944acf5d7ccca80 | /src/LLGI.Graphics.h | 72e24d011225bc9d9d85f157cdf0bb77c2d9d37c | [] | no_license | lriki/LLGI | 2727c1a75151348dc77e2cf28018d56fba83b815 | b17a7030980f641e900f02cf2593663e09e3210b | refs/heads/master | 2020-06-13T00:46:30.920583 | 2019-06-29T14:45:58 | 2019-06-29T14:45:58 | 194,478,359 | 0 | 0 | null | 2019-06-30T05:22:41 | 2019-06-30T05:22:41 | null | UTF-8 | C++ | false | false | 2,981 | h |
#pragma once
#include "LLGI.Base.h"
namespace LLGI
{
class RenderPass : public ReferenceObject
{
private:
bool isColorCleared_ = false;
bool isDepthCleared_ = false;
Color8 color_;
public:
RenderPass() = default;
virtual ~RenderPass() = default;
virtual bool GetIsColorCleared() const { return isColorCleared_; }
virtual bool GetIsDepthCleared() const { return isDepthCleared_; }
virtual Color8 GetClearColor() const { return color_; }
virtual void SetIsColorCleared(bool isColorCleared);
virtual void SetIsDepthCleared(bool isDepthCleared);
virtual void SetClearColor(const Color8& color);
/**
@brief create a RenderPassPipelineState
@note
This is a function to create an object.
But it is very fast. So it can call it in everyframe.
*/
virtual RenderPassPipelineState* CreateRenderPassPipelineState();
};
/**
@brief A class to send a data for RenderPass
*/
class RenderPassPipelineState : public ReferenceObject
{
private:
public:
RenderPassPipelineState() = default;
virtual ~RenderPassPipelineState() = default;
};
class Graphics : public ReferenceObject
{
protected:
Vec2I windowSize_;
public:
Graphics() = default;
virtual ~Graphics() = default;
/**
@brief Start new frame
*/
virtual void NewFrame();
virtual void SetWindowSize(const Vec2I& windowSize);
/**
@brief Execute commands
@note
Don't release before finish executing commands.
*/
virtual void Execute(CommandList* commandList);
/**
@brief to prevent instances to be disposed before finish rendering, finish all renderings.
*/
virtual void WaitFinish() {}
/**
@brief get render pass of screen to show on a display.
@note
Don't release and addref it.
Don't use it for the many purposes, please input Clear or SetRenderPass immediately.
*/
virtual RenderPass* GetCurrentScreen(const Color8& clearColor = Color8(), bool isColorCleared = false, bool isDepthCleared = false);
/**
@brief create a vertex buffer
@param size the size of vertex buffer
*/
virtual VertexBuffer* CreateVertexBuffer(int32_t size);
/**
@brief create an index buffer
@param stride the stride of index(2 or 4)
@param count the number of index
*/
virtual IndexBuffer* CreateIndexBuffer(int32_t stride, int32_t count);
virtual Shader* CreateShader(DataStructure* data, int32_t count);
virtual PipelineState* CreatePiplineState();
virtual CommandList* CreateCommandList();
/**
@brief create a constant buffer
@param size buffer size
@param type LongTime - exists over two frames and unchanged frequently. ShortTime exists in a frame
*/
virtual ConstantBuffer* CreateConstantBuffer(int32_t size, ConstantBufferType type = ConstantBufferType::LongTime);
virtual RenderPass* CreateRenderPass(const Texture** textures, int32_t textureCount, Texture* depthTexture) { return nullptr; }
virtual Texture* CreateTexture(const Vec2I& size, bool isRenderPass, bool isDepthBuffer);
virtual Texture* CreateTexture(uint64_t id);
};
} // namespace LLGI | [
"swda.durl@gmail.com"
] | swda.durl@gmail.com |
ccd56bb62479812644eb6336a126125fb5100dcb | cb6566906b6f48b4766506c258edf035d628dc86 | /FindDeadRegions.h | 74c96a25c8c30dae5f3ce0b32aa8bb3eda7f9c61 | [] | no_license | Wouter-VDP/UBXSec | c3f504c5b22a754bb8982216f86af0111f187a6e | c09d7d3cdb03888873d449ab726ce6eb24190839 | refs/heads/master | 2021-01-20T09:54:26.431048 | 2017-05-03T13:28:01 | 2017-05-03T13:28:01 | 90,297,356 | 0 | 1 | null | 2017-05-04T18:39:57 | 2017-05-04T18:39:57 | null | UTF-8 | C++ | false | false | 2,617 | h | /**
* \file FindDeadRegions.h
*
* \ingroup
*
* \brief Class def header for a class FindDeadRegions
*
* @author Mike Mooney, Marco Del Tutto
*/
/** \addtogroup
@{*/
#ifndef FINDDEADREGIONS_H
#define FINDDEADREGIONS_H
#include <iostream>
#include "fhiclcpp/ParameterSet.h"
#include "lardataobj/RecoBase/Track.h"
#include "lardataobj/RecoBase/Vertex.h"
#include "lardataobj/RecoBase/PFParticle.h"
#include "larpandora/LArPandoraInterface/LArPandoraHelper.h"
struct BoundaryWire {
unsigned int wire_num;
float y_start;
float z_start;
float y_end;
float z_end;
bool isLowWire;
};
class FindDeadRegions;
class FindDeadRegions {
public:
explicit FindDeadRegions();//fhicl::ParameterSet const & p, art::ActivityRegistry & areg);
// The compiler-generated destructor is fine for non-base
// classes without bare pointers or other resource use.
/// Configure function parameters
void Configure(fhicl::ParameterSet const& p);
/// Returns true if the passed point is close to a dead region given a tolerance considering two planes only
bool NearDeadReg2P(float yVal, float zVal, float tolerance);
/// Returns true if the passed point is close to a dead region given a tolerance considering all three planes
bool NearDeadReg3P(float yVal, float zVal, float tolerance);
/// Returns a root 2D histogram (y v.s. z) containing the detector dead regions considering two planes only
TH2F* GetDeadRegionHisto2P();
/// Returns a root 2D histogram (y v.s. z) containing the detector dead regions considering two planes only
void GetDeadRegionHisto2P(TH2F *);
/// Returns a root 2D histogram (y v.s. z) containing the detector dead regions considering all three planes
TH2F* GetDeadRegionHisto3P();
/// Returns a root 2D histogram (y v.s. z) containing the detector dead regions considering all three planes
void GetDeadRegionHisto3P(TH2F *);
private:
void LoadBWires();
std::vector<BoundaryWire> BWires_U; ///< Contains list of wires marking the boundaries of dead regions (U plane)
std::vector<BoundaryWire> BWires_V; ///< Contains list of wires marking the boundaries of dead regions (V plane)
std::vector<BoundaryWire> BWires_Y; ///< Contains list of wires marking the boundaries of dead regions (Y plane)
bool _use_file = false; ///< If true, uses input files instad of geometry and database
double _tolerance = 0.6; ///< Tolerance in cm to claim a point is in a dead region
int _ch_thres = 4; ///< Channels with status _less_ than threshold are considered as bad (only if using database)
};
#endif
/** @} */ // end of doxygen group
| [
"marco.deltutto@physics.ox.ac.uk"
] | marco.deltutto@physics.ox.ac.uk |
e9c59c193c011417baf0100e4598c7c40fe48d83 | 96816fec7ac7c5f3303bf425467932b86019f54e | /Include/DTV/.svn/pristine/37/37ade39558b5f5616bea2816f1ce25cd3b2b1aad.svn-base | 06f911dad248cf826ace4cfeb052bcfefebf02d9 | [] | no_license | piaoxue85/DH1551-TestApp | b4b4e0fe438165b49124f8e56bd48068c38252d5 | ba78e9a7b4af7928cc1c93a79f9ed89e989667c5 | refs/heads/master | 2022-11-27T11:00:03.945191 | 2020-07-28T04:14:52 | 2020-07-28T04:14:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,986 | /*
* ServiceInterface.h
*
* Created on: 2015-4-9
* Author: timothy.liao
*/
#ifndef SERVICEINTERFACE_H_
#define SERVICEINTERFACE_H_
#include "FreeCAMode.h"
#include "ServiceType.h"
#include "EventInfoInterface.h"
#include "ADITime.h"
class ServiceInterface
{
public:
ServiceInterface ( );
virtual ~ServiceInterface ( );
public:
virtual unsigned short GetPHYNetworkID ( ) = 0;
virtual unsigned short GetOriginalNetworkID ( ) = 0;
virtual unsigned short GetTSID ( ) = 0;
virtual unsigned short GetServiceID ( ) = 0;
virtual unsigned short GetLCN ( ) = 0;
virtual unsigned char GetVisible ( ) = 0;
virtual FreeCAMode GetFreeCAMode ( ) = 0;
virtual ServiceType GetServiceType ( ) = 0;
virtual unsigned int SetServiceType ( ServiceType ) = 0;
virtual unsigned int GetServiceName ( char aucName [ ], unsigned int unLength ) = 0;
virtual unsigned int SetServiceName(char aucName[], unsigned int unLength) = 0;
virtual EventInfoInterface* GetPresentEvent() = 0;
virtual unsigned int FreePresentEvent(EventInfoInterface * pEvent) = 0;
virtual EventInfoInterface* GetFollowingEvent() = 0;
virtual unsigned int FreeFollowingEvent(EventInfoInterface * pEvent) = 0;
virtual void* CreateEventIterator ( ADITime startTime, unsigned int unDurationInSecond, TimeZone enTimeZone ) = 0;
virtual unsigned int DeleteEventIterator ( void* hIterator ) = 0;
virtual unsigned int GetEventCount ( void* hIterator ) = 0;
virtual EventInfoInterface* GetEvent ( void* hIterator, unsigned int unIndex ) = 0;
virtual EventInfoInterface* GetEventByEventID ( unsigned short usEventID ) = 0;
virtual unsigned short GetPMTPid ( ) = 0;
virtual unsigned int IsRadioService ( ) = 0;
virtual unsigned int IsTVService ( ) = 0;
virtual unsigned int IsNVODService ( ) = 0;
virtual unsigned short GetPCRPid ( ) = 0;
virtual unsigned int GetMultiAudioTrackAttribute ( ) = 0;
};
#endif /* SERVICEINTERFACE_H_ */
| [
"1344465206@qq.com"
] | 1344465206@qq.com | |
ca68b0f56e601609114f95f7c5618bd7a1475020 | e4355967555857fd536787dce39ca30426ffa702 | /867/Game Platform/小游戏/德州扑克/游戏客户端/CardControl.h | 70fd6d587c771c3b3bab5bfca2691fb5ce61d051 | [] | no_license | herox25000/oathx-ogrex-editor | f0fd6044f8065db9cb50a80376e52f502734e877 | f645c7997f27e11a9063a0d352accd98a474cef1 | refs/heads/master | 2020-12-24T14:35:34.912603 | 2013-08-24T06:20:06 | 2013-08-24T06:20:06 | 32,935,652 | 6 | 9 | null | null | null | null | GB18030 | C++ | false | false | 3,723 | h | #ifndef CARD_CONTROL_HEAD_FILE
#define CARD_CONTROL_HEAD_FILE
#pragma once
#include "Stdafx.h"
//////////////////////////////////////////////////////////////////////////
//扑克控件
class CCardControl
{
//状态变量
protected:
bool m_bHorizontal; //显示方向
bool m_bPositively; //响应标志
bool m_bDisplayItem; //显示标志
//扑克数据
protected:
BYTE m_cbCardCount; //扑克数目
tagCardItem m_CardItemArray[MAX_CARD_COUNT]; //扑克数据
//间隔变量
protected:
UINT m_nXDistance; //横向间隔
UINT m_nYDistance; //竖向间隔
UINT m_nShootDistance; //弹起高度
//位置变量
protected:
CPoint m_BenchmarkPos; //基准位置
enXCollocateMode m_XCollocateMode; //显示模式
enYCollocateMode m_YCollocateMode; //显示模式
//资源变量
protected:
CSize m_CardSize; //扑克大小
CSkinImage m_ImageCard; //图片资源
CSkinImage m_ImageCardMask; //特效掩图
CSkinImage m_ImageWin; //胜利标志
//函数定义
public:
//构造函数
CCardControl();
//析构函数
virtual ~CCardControl();
//扑克控制
public:
//设置扑克
bool SetCardData(BYTE cbCardCount);
//设置扑克
bool SetCardData(const BYTE cbCardData[], BYTE cbCardCount);
//设置扑克
bool SetShootCard(const BYTE cbCardData[], BYTE cbCardCount);
//设置扑克
bool SetCardItem(const tagCardItem CardItemArray[], BYTE cbCardCount);
//设置特效
bool SetCardEffect(const BYTE cbCardData[],BYTE cbCardCount);
//设置标志
bool SetMyCard(const BYTE cbCardData[],BYTE cbCardCount);
//获取扑克
public:
//获取扑克
tagCardItem * GetCardFromIndex(BYTE cbIndex);
//获取扑克
tagCardItem * GetCardFromPoint(CPoint & MousePoint);
//获取扑克
public:
//扑克数码
WORD GetCardCount() { return m_cbCardCount; }
//获取扑克
WORD GetCardData(BYTE cbCardData[], BYTE cbBufferCount);
//获取扑克
WORD GetShootCard(BYTE cbCardData[], BYTE cbBufferCount);
//获取扑克
WORD GetCardData(tagCardItem CardItemArray[], BYTE wBufferCount);
//状态查询
public:
//获取大小
CSize GetCardSize() { return m_CardSize; }
//查询方向
bool GetDirection() { return m_bHorizontal; }
//查询响应
bool GetPositively() { return m_bPositively; }
//查询显示
bool GetDisplayItem() { return m_bDisplayItem; }
//状态控制
public:
//设置方向
VOID SetDirection(bool bHorizontal) { m_bHorizontal=bHorizontal; }
//设置响应
VOID SetPositively(bool bPositively) { m_bPositively=bPositively; }
//设置显示
VOID SetDisplayItem(bool bDisplayItem) { m_bDisplayItem=bDisplayItem; }
//设置距离
VOID SetCardDistance(UINT nXDistance, UINT nYDistance, UINT nShootDistance);
//控件控制
public:
//获取大小
VOID GetControlSize(CSize & ControlSize);
//获取中心
VOID GetCenterPoint(CPoint & CenterPoint);
//基准位置
VOID SetBenchmarkPos(INT nXPos, INT nYPos, enXCollocateMode XCollocateMode, enYCollocateMode YCollocateMode);
//基准位置
VOID SetBenchmarkPos(const CPoint & BenchmarkPos, enXCollocateMode XCollocateMode, enYCollocateMode YCollocateMode);
//事件控制
public:
//绘画扑克
VOID DrawCardControl(CDC * pDC,bool bEffect);
//光标消息
bool OnEventSetCursor(CPoint Point);
//内部函数
//获取原点
VOID GetOriginPoint(CPoint & OriginPoint);
//索引切换
WORD SwitchCardPoint(CPoint & MousePoint);
};
//////////////////////////////////////////////////////////////////////////
#endif | [
"mashizhou116@gmail.com@a113e17c-5e0c-ebba-c532-3ad10810a225"
] | mashizhou116@gmail.com@a113e17c-5e0c-ebba-c532-3ad10810a225 |
9411ecd0b096fb03ff61325a126daa0fc2bf0881 | 316c675e72ed9e05b73799254c724a4908caac01 | /SuperMarioBros-3/BoomerangBrother.h | 7d2f88ce89e376650c693f8002ab585237d8a7e5 | [] | no_license | Arina-LoneWolf/SuperMarioBros_3 | 2b22732d547ec5ab5fa2cb911f7d9127a220ea90 | a0aaa7b493deb6dc6ba44d3461ac2713754c09e5 | refs/heads/master | 2023-02-24T02:00:11.304007 | 2021-01-26T14:07:50 | 2021-01-26T14:07:50 | 309,241,306 | 0 | 2 | null | 2020-12-02T18:29:23 | 2020-11-02T02:53:10 | C++ | UTF-8 | C++ | false | false | 948 | h | #pragma once
#include "GameObject.h"
#include "Boomerang.h"
#include "ScoreEffect.h"
//#include "Timer.h"
class CBoomerangBrother : public CGameObject
{
static CBoomerangBrother* __instance;
public:
vector<LPGAMEOBJECT> listBoomerang;
CTimer* delayTimeToRest = new CTimer(BOOMERANG_BROTHER_REST_TIME);
CTimer* coolDown = new CTimer(BOOMERANG_COOLDOWN_TIME);
CTimer* delayToHurlSecBoomerang = new CTimer(HURLING_SEC_BOOMERANG_DELAY_TIME);
CScoreEffect* effect;
int randTurnToJump;
int turnCounter;
int playerPosition = 1;
bool isHoldingBoomerang;
bool died;
CBoomerangBrother();
virtual void Update(ULONGLONG dt, vector<LPGAMEOBJECT>* coObjects);
virtual void Render();
virtual void GetBoundingBox(float& l, float& t, float& r, float& b);
virtual void SetState(int state);
void CreateBoomerang();
void GenerateRandomTurnToJump();
int GetPlayerDirection();
static CBoomerangBrother* GetInstance();
~CBoomerangBrother();
};
| [
"petrinhtrinh182@gmail.com"
] | petrinhtrinh182@gmail.com |
1592d9a028ead735b0a2efde5a5fb0cb1fb77996 | 3fc57693e5aa610204184266f94221e8992208ab | /GondarEngine2/Math/gsTextureCoordinates.h | 95126a90afe255ebf368cec214635dbd890ca099 | [] | no_license | YvensFaos/GondarEngine2 | ae86b76c092df6a40222466de897c019714007cb | a1aff7b5feba72d1142c939845140242cd83e22b | refs/heads/master | 2021-01-18T20:01:21.130769 | 2014-02-04T11:59:53 | 2014-02-04T11:59:53 | 16,510,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | h | #ifndef __GS_TEXTURE_COORDINATES_H__
#define __GS_TEXTURE_COORDINATES_H__
#include "gsConfig.h"
#include "gsMacros.h"
#include "gsVector2.h"
class GS_DLL gsTextureCoordinates {
private:
gsVector2 coords[4];
public:
gsTextureCoordinates() {}
gsTextureCoordinates(gsVector2 c1, gsVector2 c2, gsVector2 c3, gsVector2 c4);
gsTextureCoordinates(gsVector2 *data);
gsVector2* getData() { return coords; }
void setData(gsVector2 c1, gsVector2 c2, gsVector2 c3, gsVector2 c4);
void setData(gsVector2 *data);
static gsTextureCoordinates fullImage();
};
#endif | [
"yvensre@gmail.com"
] | yvensre@gmail.com |
3e3611d2060e746e95ac39328172917229ac6fec | 25f2908cee06b7eb1eee720bef8d767d6ee10125 | /project2D/EnemyTank.cpp | 0a0fcb1cbd2dd0451f9c72a96179e4518923d0d0 | [
"MIT"
] | permissive | Sloth113/MathforGames | 8450ac342aff821173f6c90f6fbc48f50ac73903 | 2e056c827a549d8c7f9d870627b982a60b97cf75 | refs/heads/master | 2021-01-19T01:37:40.792457 | 2017-04-18T07:20:44 | 2017-04-18T07:20:44 | 87,251,744 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | cpp | #include "EnemyTank.h"
EnemyTank::EnemyTank()
{
}
EnemyTank::EnemyTank(aie::Texture * texture) :m_texture(texture)
{
tankRotateSpeed = 50; //Angle
tankChange = Vector3(0, 4, 0);
tankVel = Vector3(0, 0, 0);
shotTimer = 0;
reloadTime = 3;
}
void EnemyTank::setBullet(aie::Texture * t) {
bulletText = t;
}
void EnemyTank::update(float deltaTime)
{
tankVel = Vector3(0, 0, 0);
aie::Input* input = aie::Input::getInstance();
//Barrel 'object
Matrix3 barrelTrans = m_children[0]->getLocal();
//MAKE AI
if (input->isKeyDown(aie::INPUT_KEY_KP_2))
tankVel = tankVel + tankChange;
if (input->isKeyDown(aie::INPUT_KEY_KP_8))
tankVel = tankVel - tankChange;
if (input->isKeyDown(aie::INPUT_KEY_KP_4))
m_localTransform.setRotateZ(tankRotateSpeed * deltaTime);
if (input->isKeyDown(aie::INPUT_KEY_KP_6))
m_localTransform.setRotateZ(-tankRotateSpeed * deltaTime);
//bad but works
if (input->isKeyDown(aie::INPUT_KEY_KP_7))
barrelTrans.setRotateZ(50 * deltaTime);
if (input->isKeyDown(aie::INPUT_KEY_KP_9))
barrelTrans.setRotateZ(-50 * deltaTime);
//weapon fire
if (input->isKeyDown(aie::INPUT_KEY_KP_5) && shotTimer >= reloadTime) {
//reload time
shotTimer = 0;
//place in world (not child)
TankBullet * b;
b = new TankBullet(bulletText);
Matrix3 bPos = m_children[0]->getLocal();
bPos.translate(Vector3(0, 50, 0));
b->setLocal(bPos);
addChild(b);
//m_parent->addChild(b);
}
else if (shotTimer < reloadTime) {
shotTimer += deltaTime;
}
m_children[0]->setLocal(barrelTrans);
m_localTransform.translate(tankVel);
updateGlobalTransform();
SpriteObject::update(deltaTime);
}
void EnemyTank::draw(aie::Renderer2D * renderer)
{
renderer->drawSpriteTransformed3x3(m_texture, (float*)m_globalTransform);
SpriteObject::draw(renderer);
}
| [
"sloth.13@hotmail.com"
] | sloth.13@hotmail.com |
adb46a41190dc121c40378e4627fef934fffb69c | b9426b81e329069d6a31d53b54835cb07a723c56 | /Engine/src/GameEngine.cpp | d9c174e44dd1be2580a86a1d9a8139e14db8a720 | [] | no_license | christianpalmer/NewEngine | a6b54b867574c17dc96a3e906b87d34bedaee074 | dbf213bcad4ab8786f307253b5c428a41224f4a2 | refs/heads/master | 2021-01-18T15:12:42.487778 | 2015-03-31T20:46:59 | 2015-03-31T20:46:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | #include "GameEngine.h"
#include <SDL.h>
#include <SDL_image.h>
#include "MathUtils.h"
#include "Graphics.h"
#include "GraphicsOpenGL.h"
#include <SDL_opengl.h>
GameEngine::GameEngine()
{
}
GameEngine::~GameEngine()
{
}
SDL_GLContext gContext;
void GameEngine::Initialize()
{
SDL_Init(SDL_INIT_EVERYTHING);
_window = SDL_CreateWindow("Engine",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 640,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
_graphicsObject = new GraphicsOpenGL();
_graphicsObject->Initialize(_window);
IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF | IMG_INIT_WEBP);
InitializeImpl();
/* Get the time at the beginning of our game loop so that we can track the
* elapsed difference. */
_engineTimer.Start();
}
void GameEngine::Shutdown()
{
/* Stop the engine timer as we're shutting down. */
_engineTimer.Stop();
_graphicsObject->Shutdown();
SDL_DestroyWindow(_window);
/* Quit and clean up all libraries. */
IMG_Quit();
SDL_Quit();
}
void GameEngine::Update()
{
// Calculating the time difference since our last loop.
_engineTimer.Update();
UpdateImpl(_engineTimer.GetDeltaTime());
}
void GameEngine::Draw()
{
// Set the draw colour for screen clearing.
_graphicsObject->SetClearColour(1.0f, 1.0f, 1.0f, 1.0f);
// Clear the renderer with the current draw colour.
_graphicsObject->ClearScreen();
DrawImpl(_graphicsObject, _engineTimer.GetDeltaTime());
// Present what is in our renderer to our window.
_graphicsObject->Present();
} | [
"wilkinsense@gmail.com"
] | wilkinsense@gmail.com |
b4aa157aa6c878705863667faf5483d986052ebc | 7d92dd93197ab84610f68a4268c3b2ebf2e66c27 | /codeforces 1174C.cpp | 8d362e457bcc56974a8016b3604046ec42e5803c | [] | no_license | NiladreeDatta/Number-Theory | 5552b3db6443523faae06a65f9555a960466f854 | 98569bd31b1211a763619c8fd8c124e052fa26e5 | refs/heads/master | 2020-12-19T18:39:30.988985 | 2020-05-22T18:32:51 | 2020-05-22T18:32:51 | 235,816,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 460 | cpp | #include<bits/stdc++.h>
using namespace std;
int a[100005];
int main()
{
int n,c=1;
cin >> n;
for(int i = 2 ; i <= n ; i++)
{
if(!a[i])
{
a[i] = c++;
for(int j = i + i ; j <= n ; j += i)
{
a[j] = a[i];
}
}
//cout << a[i] << " ";
}
for(int i = 2 ; i <= n ; i++) cout << a[i] << " " ;
cout << endl;
return 0;
}
| [
"noreply@github.com"
] | NiladreeDatta.noreply@github.com |
8e05ae6bffd88733b025eae203db3404372c8b95 | 8c89782663a343f7c3d362573620f79d275a6142 | /src/10000/10818.cpp14.cpp | cc35fe3ec21b44d583eda62afd86ec2f2bda1736 | [
"MIT"
] | permissive | upple/BOJ | 14a8c8e372131b9a50ba7c1e7428ba7e57b4702d | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | refs/heads/master | 2021-06-21T07:17:57.974279 | 2019-06-28T17:56:30 | 2019-06-28T17:56:30 | 128,779,781 | 13 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | #include<cstdio>
#include<string>
int main()
{
int max=-1000001, min=1000001;
int no_data, num;
scanf("%d", &no_data);
for(int i=0; i<no_data; i++)
{
scanf("%d", &num);
max=num>max?num:max;
min=num<min?num:min;
}
printf("%d %d\n", min, max);
return 0;
}
| [
"upple_@naver.com"
] | upple_@naver.com |
8ed5c6f9f0435b23f7d969bc6d88726b2c59f75f | f9941b52dbe90f01c441c1550479b8bd13f0da0a | /Source/Laboratoare/Laborator6/Laborator6.cpp | 70177c46318479ed77dcc1a0859ac4ef6fde45d6 | [] | no_license | Longman-Stan/River_simulation | 0cab2af8e6ff964b0347ef568388777d5e41d775 | f56f58ddf6cc8b44326fb91c3da3d053628972b1 | refs/heads/main | 2023-04-14T01:47:55.328762 | 2021-04-25T16:44:35 | 2021-04-25T16:44:35 | 361,433,560 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,216 | cpp | #include "Laborator6.h"
#include <vector>
#include <iostream>
#include <Core/Engine.h>
using namespace std;
#define rand01 (rand() / static_cast<float>(RAND_MAX))
// Order of function calling can be seen in "Source/Core/World.cpp::LoopUpdate()"
// https://github.com/UPB-Graphics/SPG-Framework/blob/master/Source/Core/World.cpp
Laborator6::Laborator6()
{
}
Laborator6::~Laborator6()
{
}
void Laborator6::Init()
{
outputType = 0;
auto camera = GetSceneCamera();
camera->SetPositionAndRotation(glm::vec3(0, 2, 3.5), glm::quat(glm::vec3(-20 * TO_RADIANS, 0, 0)));
camera->Update();
TextureManager::LoadTexture(RESOURCE_PATH::TEXTURES, "ground.jpg");
// Load a mesh from file into GPU memory
{
Mesh* mesh = new Mesh("box");
mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "box.obj");
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("plane");
mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "plane50.obj");
mesh->UseMaterials(false);
meshes[mesh->GetMeshID()] = mesh;
}
// Load a mesh from file into GPU memory
{
Mesh* mesh = new Mesh("sphere");
mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "sphere.obj");
mesh->UseMaterials(false);
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("quad");
mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "quad.obj");
mesh->UseMaterials(false);
meshes[mesh->GetMeshID()] = mesh;
}
LoadShader("Render2Texture");
LoadShader("Composition");
LoadShader("LightPass");
auto resolution = window->GetResolution();
frameBuffer = new FrameBuffer();
frameBuffer->Generate(resolution.x, resolution.y, 3);
lightBuffer = new FrameBuffer();
lightBuffer->Generate(resolution.x, resolution.y, 1);
int gridSize = 3;
for (int i = -gridSize; i < gridSize; i++)
{
for (int j = -gridSize; j < gridSize; j++)
{
LightInfo L;
L.color = glm::vec3(rand01, rand01, rand01);
L.position = glm::vec3(i, rand01, j) * glm::vec3(3, 2, 3) + glm::vec3(0, 0.5, 0);
L.radius = rand01 + 3;
lights.push_back(L);
}
}
}
void Laborator6::FrameStart()
{
}
void Laborator6::Update(float deltaTimeSeconds)
{
ClearScreen();
// ------------------------------------------------------------------------
// Deferred rendering pass
{
frameBuffer->Bind();
auto shader = shaders["Render2Texture"];
TextureManager::GetTexture("default.png")->BindToTextureUnit(GL_TEXTURE0);
// render scene objects
RenderMesh(meshes["box"], shader, glm::vec3(1.5, 0.5f, 0), glm::vec3(0.5f));
RenderMesh(meshes["box"], shader, glm::vec3(0, 1.05f, 0), glm::vec3(2));
RenderMesh(meshes["box"], shader, glm::vec3(-2, 1.5f, 0));
RenderMesh(meshes["sphere"], shader, glm::vec3(-4, 1, 1));
TextureManager::GetTexture("ground.jpg")->BindToTextureUnit(GL_TEXTURE0);
RenderMesh(meshes["plane"], shader, glm::vec3(0, 0, 0), glm::vec3(0.5f));
// Render a simple point light bulb for each light (for debugging purposes)
for (auto &l : lights)
{
auto model = glm::translate(glm::mat4(1), l.position);
model = glm::scale(model, glm::vec3(0.2f));
RenderMesh(meshes["sphere"], shader, model);
}
}
// ------------------------------------------------------------------------
// Ligthing pass
{
lightBuffer->Bind();
// Enable buffer color accumulation
glDepthMask(GL_FALSE);
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);
auto shader = shaders["LightPass"];
shader->Use();
{
int texturePositionsLoc = shader->GetUniformLocation("texture_position");
glUniform1i(texturePositionsLoc, 0);
frameBuffer->BindTexture(0, GL_TEXTURE0);
}
{
int textureNormalsLoc = shader->GetUniformLocation("texture_normal");
glUniform1i(textureNormalsLoc, 1);
frameBuffer->BindTexture(1, GL_TEXTURE0 + 1);
}
auto camera = GetSceneCamera();
glm::vec3 cameraPos = camera->transform->GetWorldPosition();
int loc_eyePosition = shader->GetUniformLocation("eye_position");
glUniform3fv(loc_eyePosition, 1, glm::value_ptr(cameraPos));
auto resolution = window->GetResolution();
int loc_resolution = shader->GetUniformLocation("resolution");
glUniform2i(loc_resolution, resolution.x, resolution.y);
// Face culling for sphere ligth areas
// Test with both GL_BACK and GL_FRONT and see what's the diference when the camera goes through an area light
// When GL_BACK is culled the light area will dissapear if the camera enters the light sphere (from interior the sphere is not rendered)
// When GL_FRONT is culled the light area will always be visible. This is the desired effect.
// If no culling is active (both GL_BACK and GL_FRONT are rendered) then the light area will double the intensity for each pixel
// TODO
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
for (auto &l : lights)
{
auto model = glm::translate(glm::mat4(1), l.position);
model = glm::scale(model, glm::vec3(2 * l.radius));
glUniform1f(shader->loc_light_radius, l.radius);
glUniform3fv(shader->loc_light_color, 1, glm::value_ptr(l.color));
glUniform3fv(shader->loc_light_pos, 1, glm::value_ptr(l.position));
RenderMesh(meshes["sphere"], shader, model);
}
// TODO
glDisable(GL_CULL_FACE);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
}
// ------------------------------------------------------------------------
// Composition pass
{
FrameBuffer::BindDefault();
auto shader = shaders["Composition"];
shader->Use();
int outputTypeLoc = shader->GetUniformLocation("output_type");
glUniform1i(outputTypeLoc, outputType);
{
int texturePositionsLoc = shader->GetUniformLocation("texture_position");
glUniform1i(texturePositionsLoc, 1);
frameBuffer->BindTexture(0, GL_TEXTURE0 + 1);
}
{
int textureNormalsLoc = shader->GetUniformLocation("texture_normal");
glUniform1i(textureNormalsLoc, 2);
frameBuffer->BindTexture(1, GL_TEXTURE0 + 2);
}
{
int textureColorLoc = shader->GetUniformLocation("texture_color");
glUniform1i(textureColorLoc, 3);
frameBuffer->BindTexture(2, GL_TEXTURE0 + 3);
}
{
int textureDepthLoc = shader->GetUniformLocation("texture_depth");
glUniform1i(textureDepthLoc, 4);
frameBuffer->BindDepthTexture(GL_TEXTURE0 + 4);
}
{
int textureLightLoc = shader->GetUniformLocation("texture_light");
glUniform1i(textureLightLoc, 5);
lightBuffer->BindTexture(0, GL_TEXTURE0 + 5);
}
// render the object again but with different properties
RenderMesh(meshes["quad"], shader, glm::vec3(0, 0, 0));
}
}
void Laborator6::FrameEnd()
{
DrawCoordinatSystem();
}
void Laborator6::LoadShader(std::string name)
{
static std::string shaderPath = "Source/Laboratoare/Laborator6/Shaders/";
// Create a shader program for particle system
{
Shader *shader = new Shader(name.c_str());
shader->AddShader((shaderPath + name + ".VS.glsl").c_str(), GL_VERTEX_SHADER);
shader->AddShader((shaderPath + name + ".FS.glsl").c_str(), GL_FRAGMENT_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
}
// Read the documentation of the following functions in: "Source/Core/Window/InputController.h" or
// https://github.com/UPB-Graphics/SPG-Framework/blob/master/Source/Core/Window/InputController.h
void Laborator6::OnInputUpdate(float deltaTime, int mods)
{
// treat continuous update based on input
};
void Laborator6::OnKeyPress(int key, int mods)
{
// add key press event
int index = key - GLFW_KEY_0;
if (index >= 0 && index <= 9) {
outputType = index;
}
};
void Laborator6::OnKeyRelease(int key, int mods)
{
// add key release event
};
void Laborator6::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// add mouse move event
};
void Laborator6::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// add mouse button press event
};
void Laborator6::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// add mouse button release event
}
void Laborator6::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
// treat mouse scroll event
}
void Laborator6::OnWindowResize(int width, int height)
{
// treat window resize event
frameBuffer->Resize(width, height, 32);
lightBuffer->Resize(width, height, 32);
}
| [
"vlad.lsc2008@gmail.com"
] | vlad.lsc2008@gmail.com |
db5f6a2828e2ac6fead84b76635c9e442e6bc929 | cf6579b535e7f4fe6e2755df33fc1f0815f3322f | /imageMaker/threadPool.cpp | ce8507cea95fa262f1d3d787810fffe5de48f23e | [] | no_license | zhangcj13/imager_maker | c48ba9cf07b956c631de0a3ad880d35cfa04cf9e | de18f92f716059c2e6992d48eebf80c9ce419c8f | refs/heads/master | 2020-03-24T23:28:31.421187 | 2018-08-07T10:37:37 | 2018-08-07T10:37:37 | 143,137,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,793 | cpp |
#include "threadPool.h"
namespace imgmaker
{
ThreadPool& ThreadPool::instance()
{
static ThreadPool inst(2);
return inst;
}
// the constructor just launches some amount of workers
ThreadPool::ThreadPool(const size_t threads)
{
startup(threads);
}
// the destructor joins all threads
ThreadPool::~ThreadPool()
{
shutdown();
}
void ThreadPool::shutdown()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers)
{
if (worker.joinable())
{
worker.join();
}
}
workers.clear();
tasks = decltype(tasks)();
}
void ThreadPool::startup(const size_t threads)
{
stop = false;
for (size_t i = 0; i < threads; ++i)
workers.emplace_back(
[this]
{
for (;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
inline size_t ThreadPool::size() const
{
return workers.size();
}
void ThreadPool::resize(const size_t new_size)
{
//stop thread pool
shutdown();
//start thread pool
startup(new_size);
}
//////////////////////////////////////////////////////////////////////////
//APIs
size_t get_thread_num()
{
return ThreadPool::instance().size();
}
size_t set_thread_num(const size_t num)
{
easyAssert(num > 0, "number of thread must be larger than 0");
if (num != get_thread_num())
{
ThreadPool::instance().resize(num);
}
return get_thread_num();
}
void dispatch_worker(std::function<void(const size_t, const size_t)> func, const size_t number)
{
if (number <= 0)
{
return;
}
const size_t threads_of_pool = ThreadPool::instance().size();
if (threads_of_pool <= 1 || number <= 1)
{
func(0, number);
}
else
{
easyAssert(threads_of_pool > 1, "thread must be larger than 1");
// 1/4 2/4 /4/4 5/4 => all ok!
const size_t payload_per_thread = number / threads_of_pool;
const size_t remainder_payload = number - payload_per_thread*threads_of_pool;
const size_t remainder_proc_last_idx = remainder_payload;
size_t start = 0;
std::vector<std::future<void>> futures;
for (size_t i = 0; i < threads_of_pool; i++)
{
size_t stop = start + payload_per_thread;
if (i < remainder_proc_last_idx)
{
stop = stop + 1;
}
futures.push_back(ThreadPool::instance().enqueue(func, start, stop));
start = stop;
if (stop >= number)
{
break;
}
}
for (size_t i = 0; i < futures.size(); i++)
{
futures[i].wait();
}
}
}
}//namespace | [
"zhangcj13@126.com"
] | zhangcj13@126.com |
1660207284738d253f4dd1ace7ae786e1f141cba | dd949f215d968f2ee69bf85571fd63e4f085a869 | /subarchitectures/comsys/branches/stable-0/src/mercury-c++/abduction/server/TtyUtils.h | c2f031875a7fa7b33d37760f24120170db3c1ae4 | [] | no_license | marc-hanheide/cogx | a3fd395805f1b0ad7d713a05b9256312757b37a9 | cb9a9c9cdfeba02afac6a83d03b7c6bb778edb95 | refs/heads/master | 2022-03-16T23:36:21.951317 | 2013-12-10T23:49:07 | 2013-12-10T23:49:07 | 219,460,352 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 473 | h | #ifndef TTYUTILS_H__
#define TTYUTILS_H__ 1
#include <iostream>
namespace tty {
std::ostream & dcol(std::ostream & out);
std::ostream & black(std::ostream & out);
std::ostream & red(std::ostream & out);
std::ostream & green(std::ostream & out);
std::ostream & yellow(std::ostream & out);
std::ostream & blue(std::ostream & out);
std::ostream & magenta(std::ostream & out);
std::ostream & cyan(std::ostream & out);
std::ostream & white(std::ostream & out);
};
#endif
| [
"nickh@robots.ox.ac.uk"
] | nickh@robots.ox.ac.uk |
eb395a4c546af54f10c96d38e52ba5e7abcff889 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /third_party/blink/common/privacy_budget/identifiability_internal_templates_unittest.cc | 048b45868184b05b86cf926fc1cdb3e7261c8e92 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 4,062 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/common/privacy_budget/identifiability_internal_templates.h"
#include <cstdint>
#include <limits>
#include <type_traits>
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
namespace internal {
namespace {
struct PodType {
int x;
float y;
char c;
char g[10];
};
#if !defined(ARCH_CPU_LITTLE_ENDIAN) && !defined(ARCH_CPU_BIG_ENDIAN)
#error "What kind of CPU is this?"
#endif
} // namespace
// remove_cvref_t
static_assert(std::is_same<int, remove_cvref_t<const int>>::value, "");
static_assert(std::is_same<int, remove_cvref_t<const volatile int>>::value, "");
static_assert(std::is_same<int, remove_cvref_t<int&>>::value, "");
static_assert(std::is_same<int, remove_cvref_t<const int&>>::value, "");
static_assert(std::is_same<int, remove_cvref_t<const volatile int&>>::value,
"");
static_assert(std::is_same<int, remove_cvref_t<int&&>>::value, "");
static_assert(std::is_same<PodType, remove_cvref_t<const PodType&>>::value, "");
static_assert(std::is_same<int*, remove_cvref_t<int*>>::value, "");
// has_unique_object_representations
static_assert(has_unique_object_representations<int>::value, "");
static_assert(has_unique_object_representations<float>::value, "");
static_assert(has_unique_object_representations<double>::value, "");
// long double: check_blink_style doesn't let us use the word 'long' here.
static_assert(has_unique_object_representations<decltype(1.0l)>::value, "");
// Pointers aren't considered to have a unique representation.
static_assert(!has_unique_object_representations<int*>::value, "");
// Nor are POD types though they could be if they are dense and don't have any
// internal padding.
static_assert(!has_unique_object_representations<PodType>::value, "");
TEST(IdentifiabilityInternalTemplatesTest, DigestOfObjectRepresentation) {
const int kV = 5;
const int& kRV = kV;
const volatile int& kRVV = kV;
// Note that both little and big endian systems produce the same result from
// DigestOfObjectRepresentation();
// Positive unsigned integers.
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(UINT8_C(5)));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(UINT16_C(5)));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(UINT32_C(5)));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(UINT64_C(5)));
// Positive signed integers.
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(INT8_C(5)));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(INT16_C(5)));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(INT32_C(5)));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(INT64_C(5)));
// char
EXPECT_EQ(INT64_C(65), DigestOfObjectRepresentation('A'));
// Negative integers.
EXPECT_EQ(INT64_C(-5), DigestOfObjectRepresentation(INT8_C(-5)));
EXPECT_EQ(INT64_C(-5), DigestOfObjectRepresentation(INT16_C(-5)));
EXPECT_EQ(INT64_C(-5), DigestOfObjectRepresentation(INT32_C(-5)));
EXPECT_EQ(INT64_C(-5), DigestOfObjectRepresentation(INT64_C(-5)));
// Large unsigned integer. These wrap around for 2s complement arithmetic.
EXPECT_EQ(INT64_C(-1),
DigestOfObjectRepresentation(std::numeric_limits<uint64_t>::max()));
// CV qualified types should be unwrapped.
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(kV));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(kRV));
EXPECT_EQ(INT64_C(5), DigestOfObjectRepresentation(kRVV));
}
TEST(IdentifiabilityInternalTemplatesTest,
DigestOfObjectRepresentation_Floats) {
// IEEE 754 32-bit single precision float.
if (sizeof(float) == 4)
EXPECT_EQ(INT64_C(1069547520), DigestOfObjectRepresentation(1.5f));
// IEEE 754 64-bit double precision float.
if (sizeof(double) == 8)
EXPECT_EQ(INT64_C(4609434218613702656), DigestOfObjectRepresentation(1.5));
}
} // namespace internal
} // namespace blink
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e8f71d4fb84b759afcb0110ffc1650f58cb3df48 | e991c1acde1223f54df733d9520b8b49e227e436 | /RayTracer/src/Render/Camera.cpp | ef57702e236b5db50029497782bad85f58381220 | [] | no_license | harshit2608/Raytracer-C- | 1598500830293ccdc3b7c96f054f393417064e4d | 9ca9284723b2644404a0db7ed9664527212dccd6 | refs/heads/main | 2023-06-07T02:34:27.352686 | 2021-06-28T17:42:28 | 2021-06-28T17:42:28 | 320,901,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39 | cpp | #include "rtpch.h"
#include "Camera.h"
| [
"harshitrock111@gmail.com"
] | harshitrock111@gmail.com |
a8c788a52868fb9976b9eea19fd540eed99e05fc | 6de3456826609ee09e7d88ccbe5fa75262d1e313 | /1-algo-toolbox/3-greedy-algorithms/5_collecting_signatures/covering_segments.cpp | 27dd2e13efa63d7f9d58922d6fa3c244d961473b | [] | no_license | ballaneypranav/ucsd-dsa | c2cce3fddec4eac49ece6324aa42b87e4da76368 | ceca37ba35bbcc44e975a1dd700c3c0cdaae983a | refs/heads/master | 2020-05-24T15:26:38.309718 | 2019-06-05T16:06:28 | 2019-06-05T16:06:28 | 187,331,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,022 | cpp | #include <algorithm>
#include <iostream>
#include <climits>
#include <vector>
using namespace std;
struct Segment {
int start, end;
};
bool compareSegmentsByEnd (Segment a, Segment b)
{
if (a.end < b.end)
return true;
else
return false;
}
vector<int> optimal_points(vector<Segment> segments)
{
vector<int> points;
int n = segments.size();
sort(segments.begin(), segments.end(), compareSegmentsByEnd);
while (segments.size() > 0)
{
int end = segments[0].end;
for (int j = 0; j < segments.size(); j++)
{
if (segments[j].start <= end)
{
segments.erase(segments.begin() + j);
j--;
}
}
points.push_back(end);
}
return points;
}
int main()
{
int n;
std::cin >> n;
vector<Segment> segments(n);
for (size_t i = 0; i < n; ++i)
{
std::cin >> segments[i].start >> segments[i].end;
}
vector<int> points = optimal_points(segments);
std::cout << points.size() << "\n";
for (size_t i = 0; i < points.size(); ++i)
{
std::cout << points[i] << " ";
}
cout << endl;
}
| [
"ballaneypranav@gmail.com"
] | ballaneypranav@gmail.com |
43933daa06bb7e5c354ca30a1a9215368c10ec54 | d1e4718197ba3bddd13d6f6958e1d5a492b51af5 | /Geometry/Circle.cpp | ae3f4a10b22440ccb173903b321f6f185b075788 | [] | no_license | reisoftware/ap2d | 1f398664fdc4f8cab9479df18cd2a745f904cdff | e09732655ef66e13e98b8f3b008c91dac541e1f5 | refs/heads/master | 2022-01-22T05:36:56.295845 | 2022-01-04T05:31:57 | 2022-01-04T05:31:57 | 162,372,004 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | cpp |
#include "StdAfx.h"
#include "Circle.h"
#include "intersect.h"
namespace geo{
Circle::Circle(const Point& c, Float r, const Normal& n)
MCT_INIT1("geo:Circle")
{
set(c, r, nor);
}
void Circle::set(const Point& c, Float r, const Normal& n)
{
this->center = c;
this->radius = r;
this->nor = n;
}
void Circle::intersect2d(const LLine& rhs, std::vector<Point>& pts)const
{
Point pt1, pt2;
int num = geo::intersect2d(*this, rhs, pt1, pt2);
if(num == 1){
pts.push_back(pt1);
}
else if(num == 2){
pts.push_back(pt1);
pts.push_back(pt2);
}
else{
}
}
void Circle::intersect2d(const RLine& rhs, std::vector<Point>& pts)const
{
Point pt1, pt2;
int num = geo::intersect2d(*this, rhs, pt1, pt2);
if(num == 1){
pts.push_back(pt1);
}
else if(num == 2){
pts.push_back(pt1);
pts.push_back(pt2);
}
else{
}
}
void Circle::intersect2d(const SLine& rhs, std::vector<Point>& pts)const
{
Point pt1, pt2;
int num = geo::intersect2d(*this, rhs, pt1, pt2);
if(num == 1){
pts.push_back(pt1);
}
else if(num == 2){
pts.push_back(pt1);
pts.push_back(pt2);
}
else{
}
}
void Circle::intersect2d(const Circle& rhs, std::vector<Point>& pts)const
{
//NOOK
}
}//namespace
| [
"tian_bj@126.com"
] | tian_bj@126.com |
85a6fb9ffbc57e3564b5d4bfe6c8e2871493594a | fbe77e9e2a53a4600a1d9b00b5f2c29ee3e8c59a | /plugins/bnet_plugin/bnet_plugin.cpp | 4c919ee27ba3d6a71f32620b34ab7a0f8e415f20 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | AcuteAngleCloud/Acute-Angle-Chain | 8d4a1ad714f6de1493954326e109b6af112561b9 | 5ea50bee042212ccff797ece5018c64f3f50ceff | refs/heads/master | 2021-04-26T21:52:25.560457 | 2020-03-21T07:29:06 | 2020-03-21T07:29:06 | 124,164,376 | 10 | 5 | MIT | 2020-07-16T07:14:45 | 2018-03-07T02:03:53 | C++ | UTF-8 | C++ | false | false | 62,156 | cpp | /**
* The purpose of this protocol is to synchronize (and keep synchronized) two
* blockchains using a very simple algorithm:
*
* 1. find the last block id on our local chain that the remote peer knows about
* 2. if we have the next block send it to them
* 3. if we don't have the next block send them a the oldest unexpired transaction
*
* There are several input events:
*
* 1. new block accepted by local chain
* 2. block deemed irreversible by local chain
* 3. new block header accepted by local chain
* 4. transaction accepted by local chain
* 5. block received from remote peer
* 6. transaction received from remote peer
* 7. socket ready for next write
*
* Each session is responsible for maintaining the following
*
* 1. the most recent block on our current best chain which we know
* with certainty that the remote peer has.
* - this could be the peers last irreversible block
* - a block ID after the LIB that the peer has notified us of
* - a block which we have sent to the remote peer
* - a block which the peer has sent us
* 2. the block IDs we have received from the remote peer so that
* we can disconnect peer if one of those blocks is deemed invalid
* - we can clear these IDs once the block becomes reversible
* 3. the transactions we have received from the remote peer so that
* we do not send them something that they already know.
* - this includes transactions sent as part of blocks
* - we clear this cache after we have applied a block that
* includes the transactions because we know the controller
* should not notify us again (they would be dupe)
*
* Assumptions:
* 1. all blocks we send the peer are valid and will be held in the
* peers fork database until they become irreversible or are replaced
* by an irreversible alternative.
* 2. we don't care what fork the peer is on, so long as we know they have
* the block prior to the one we want to send. The peer will sort it out
* with its fork database and hopfully come to our conclusion.
* 3. the peer will send us blocks on the same basis
*
*/
#include <aacio/bnet_plugin/bnet_plugin.hpp>
#include <aacio/chain/controller.hpp>
#include <aacio/chain/trace.hpp>
#include <aacio/chain_plugin/chain_plugin.hpp>
#include <fc/io/json.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <aacio/chain/plugin_interface.hpp>
using tcp = boost::asio::ip::tcp;
namespace ws = boost::beast::websocket;
namespace aacio {
using namespace chain;
static appbase::abstract_plugin& _bnet_plugin = app().register_plugin<bnet_plugin>();
} /// namespace aacio
namespace fc {
extern std::unordered_map<std::string,logger>& get_logger_map();
}
const fc::string logger_name("bnet_plugin");
fc::logger plugin_logger;
std::string peer_log_format;
#define peer_dlog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( plugin_logger.is_enabled( fc::log_level::debug ) ) \
plugin_logger.log( FC_LOG_MESSAGE( debug, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant()) ) ); \
FC_MULTILINE_MACRO_END
#define peer_ilog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( plugin_logger.is_enabled( fc::log_level::info ) ) \
plugin_logger.log( FC_LOG_MESSAGE( info, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant()) ) ); \
FC_MULTILINE_MACRO_END
#define peer_wlog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( plugin_logger.is_enabled( fc::log_level::warn ) ) \
plugin_logger.log( FC_LOG_MESSAGE( warn, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant()) ) ); \
FC_MULTILINE_MACRO_END
#define peer_elog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( plugin_logger.is_enabled( fc::log_level::error ) ) \
plugin_logger.log( FC_LOG_MESSAGE( error, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant())) ); \
FC_MULTILINE_MACRO_END
using aacio::public_key_type;
using aacio::chain_id_type;
using aacio::block_id_type;
using aacio::block_timestamp_type;
using std::string;
using aacio::sha256;
using aacio::signed_block_ptr;
using aacio::packed_transaction_ptr;
using std::vector;
struct hello {
public_key_type peer_id;
string network_version;
string agent;
string protocol_version = "1.0.1";
string user;
string password;
chain_id_type chain_id;
bool request_transactions = false;
uint32_t last_irr_block_num = 0;
vector<block_id_type> pending_block_ids;
};
FC_REFLECT( hello, (peer_id)(network_version)(user)(password)(agent)(protocol_version)(chain_id)(request_transactions)(last_irr_block_num)(pending_block_ids) )
struct hello_extension_irreversible_only {};
FC_REFLECT( hello_extension_irreversible_only, BOOST_PP_SEQ_NIL )
using hello_extension = fc::static_variant<hello_extension_irreversible_only>;
/**
* This message is sent upon successful speculative application of a transaction
* and informs a peer not to send this message.
*/
struct trx_notice {
vector<sha256> signed_trx_id; ///< hash of trx + sigs
};
FC_REFLECT( trx_notice, (signed_trx_id) )
/**
* This message is sent upon successfully adding a transaction to the fork database
* and informs the remote peer that there is no need to send this block.
*/
struct block_notice {
vector<block_id_type> block_ids;
};
FC_REFLECT( block_notice, (block_ids) );
struct ping {
fc::time_point sent;
fc::sha256 code;
uint32_t lib; ///< the last irreversible block
};
FC_REFLECT( ping, (sent)(code)(lib) )
struct pong {
fc::time_point sent;
fc::sha256 code;
};
FC_REFLECT( pong, (sent)(code) )
using bnet_message = fc::static_variant<hello,
trx_notice,
block_notice,
signed_block_ptr,
packed_transaction_ptr,
ping, pong
>;
struct by_id;
struct by_num;
struct by_received;
struct by_expired;
namespace aacio {
using namespace chain::plugin_interface;
class bnet_plugin_impl;
template <typename Strand>
void verify_strand_in_this_thread(const Strand& strand, const char* func, int line) {
if( !strand.running_in_this_thread() ) {
elog( "wrong strand: ${f} : line ${n}, exiting", ("f", func)("n", line) );
app().quit();
}
}
/**
* Each session is presumed to operate in its own strand so that
* operations can execute in parallel.
*/
class session : public std::enable_shared_from_this<session>
{
public:
enum session_state {
hello_state,
sending_state,
idle_state
};
struct block_status {
block_status( block_id_type i, bool kby_peer, bool rfrom_peer)
{
known_by_peer = kby_peer;
received_from_peer = rfrom_peer;
id = i;
}
bool known_by_peer = false; ///< we sent block to peer or peer sent us notice
bool received_from_peer = false; ///< peer sent us this block and considers full block valid
block_id_type id; ///< the block id;
// block_id_type prev; ///< the prev block id
// shared_ptr< vector<char> > block_msg; ///< packed bnet_message for this block
uint32_t block_num()const { return block_header::num_from_id(id); }
};
typedef boost::multi_index_container<block_status,
indexed_by<
ordered_unique< tag<by_id>, member<block_status,block_id_type,&block_status::id> >,
ordered_non_unique< tag<by_num>, const_mem_fun<block_status,uint32_t,&block_status::block_num> >
>
> block_status_index;
struct transaction_status {
time_point received;
time_point expired; /// 5 seconds from last accepted
transaction_id_type id;
transaction_metadata_ptr trx;
void mark_known_by_peer() { received = fc::time_point::maximum(); trx.reset(); }
bool known_by_peer()const { return received == fc::time_point::maximum(); }
};
typedef boost::multi_index_container<transaction_status,
indexed_by<
ordered_unique< tag<by_id>, member<transaction_status,transaction_id_type,&transaction_status::id> >,
ordered_non_unique< tag<by_received>, member<transaction_status,time_point,&transaction_status::received> >,
ordered_non_unique< tag<by_expired>, member<transaction_status,time_point,&transaction_status::expired> >
>
> transaction_status_index;
block_status_index _block_status;
transaction_status_index _transaction_status;
const uint32_t _max_block_status_range = 2048; // limit tracked block_status known_by_peer
public_key_type _local_peer_id;
uint32_t _local_lib = 0;
block_id_type _local_lib_id;
uint32_t _local_head_block_num = 0;
block_id_type _local_head_block_id; /// the last block id received on local channel
public_key_type _remote_peer_id;
uint32_t _remote_lib = 0;
block_id_type _remote_lib_id;
bool _remote_request_trx = false;
bool _remote_request_irreversible_only = false;
uint32_t _last_sent_block_num = 0;
block_id_type _last_sent_block_id; /// the id of the last block sent
bool _recv_remote_hello = false;
bool _sent_remote_hello = false;
fc::sha256 _current_code;
fc::time_point _last_recv_ping_time = fc::time_point::now();
ping _last_recv_ping;
ping _last_sent_ping;
int _session_num = 0;
session_state _state = hello_state;
tcp::resolver _resolver;
bnet_ptr _net_plugin;
boost::asio::io_service& _ios;
unique_ptr<ws::stream<tcp::socket>> _ws;
boost::asio::strand< boost::asio::io_context::executor_type> _strand;
boost::asio::io_service& _app_ios;
methods::get_block_by_number::method_type& _get_block_by_number;
string _peer;
string _remote_host;
string _remote_port;
vector<char> _out_buffer;
//boost::beast::multi_buffer _in_buffer;
boost::beast::flat_buffer _in_buffer;
flat_set<block_id_type> _block_header_notices;
fc::optional<fc::variant_object> _logger_variant;
int next_session_id()const {
static int session_count = 0;
return ++session_count;
}
/**
* Creating session from server socket acceptance
*/
explicit session( tcp::socket socket, bnet_ptr net_plug )
:_resolver(socket.get_io_service()),
_net_plugin( std::move(net_plug) ),
_ios(socket.get_io_service()),
_ws( new ws::stream<tcp::socket>(move(socket)) ),
_strand(_ws->get_executor() ),
_app_ios( app().get_io_service() ),
_get_block_by_number( app().get_method<methods::get_block_by_number>() )
{
_session_num = next_session_id();
set_socket_options();
_ws->binary(true);
wlog( "open session ${n}",("n",_session_num) );
}
/**
* Creating outgoing session
*/
explicit session( boost::asio::io_context& ioc, bnet_ptr net_plug )
:_resolver(ioc),
_net_plugin( std::move(net_plug) ),
_ios(ioc),
_ws( new ws::stream<tcp::socket>(ioc) ),
_strand( _ws->get_executor() ),
_app_ios( app().get_io_service() ),
_get_block_by_number( app().get_method<methods::get_block_by_number>() )
{
_session_num = next_session_id();
_ws->binary(true);
wlog( "open session ${n}",("n",_session_num) );
}
~session();
void set_socket_options() {
try {
/** to minimize latency when sending short messages */
_ws->next_layer().set_option( boost::asio::ip::tcp::no_delay(true) );
/** to minimize latency when sending large 1MB blocks, the send buffer should not have to
* wait for an "ack", making this larger could result in higher latency for smaller urgent
* messages.
*/
_ws->next_layer().set_option( boost::asio::socket_base::send_buffer_size( 1024*1024 ) );
_ws->next_layer().set_option( boost::asio::socket_base::receive_buffer_size( 1024*1024 ) );
} catch ( ... ) {
elog( "uncaught exception on set socket options" );
}
}
void run() {
_ws->async_accept( boost::asio::bind_executor(
_strand,
std::bind( &session::on_accept,
shared_from_this(),
std::placeholders::_1) ) );
}
void run( const string& peer ) {
auto c = peer.find(':');
auto host = peer.substr( 0, c );
auto port = peer.substr( c+1, peer.size() );
_peer = peer;
_remote_host = host;
_remote_port = port;
_resolver.async_resolve( _remote_host, _remote_port,
boost::asio::bind_executor( _strand,
std::bind( &session::on_resolve,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2 ) ) );
}
void on_resolve( boost::system::error_code ec,
tcp::resolver::results_type results ) {
if( ec ) return on_fail( ec, "resolve" );
boost::asio::async_connect( _ws->next_layer(),
results.begin(), results.end(),
boost::asio::bind_executor( _strand,
std::bind( &session::on_connect,
shared_from_this(),
std::placeholders::_1 ) ) );
}
void on_connect( boost::system::error_code ec ) {
if( ec ) return on_fail( ec, "connect" );
set_socket_options();
_ws->async_handshake( _remote_host, "/",
boost::asio::bind_executor( _strand,
std::bind( &session::on_handshake,
shared_from_this(),
std::placeholders::_1 ) ) );
}
void on_handshake( boost::system::error_code ec ) {
if( ec ) return on_fail( ec, "handshake" );
do_hello();
do_read();
}
/**
* This will be called "every time" a the transaction is accepted which happens
* on the speculative block (potentially several such blocks) and when a block
* that contains the transaction is applied and/or when switching forks.
*
* We will add it to the transaction status table as "received now" to be the
* basis of sending it to the peer. When we send it to the peer "received now"
* will be set to the infinite future to mark it as sent so we don't resend it
* when it is accepted again.
*
* Each time the transaction is "accepted" we extend the time we cache it by
* 5 seconds from now. Every time a block is applied we purge all accepted
* transactions that have reached 5 seconds without a new "acceptance".
*/
void on_accepted_transaction( transaction_metadata_ptr t ) {
//ilog( "accepted ${t}", ("t",t->id) );
auto itr = _transaction_status.find( t->id );
if( itr != _transaction_status.end() ) {
if( !itr->known_by_peer() ) {
_transaction_status.modify( itr, [&]( auto& stat ) {
stat.expired = std::min<fc::time_point>( fc::time_point::now() + fc::seconds(5), t->trx.expiration );
});
}
return;
}
transaction_status stat;
stat.received = fc::time_point::now();
stat.expired = stat.received + fc::seconds(5);
stat.id = t->id;
stat.trx = t;
_transaction_status.insert( stat );
maybe_send_next_message();
}
/**
* Remove all transactions that expired from cache prior to now
*/
void purge_transaction_cache() {
auto& idx = _transaction_status.get<by_expired>();
auto itr = idx.begin();
auto now = fc::time_point::now();
while( itr != idx.end() && itr->expired < now ) {
idx.erase(itr);
itr = idx.begin();
}
}
/**
* When our local LIB advances we can purge our known history up to
* the LIB or up to the last block known by the remote peer.
*/
void on_new_lib( block_state_ptr s ) {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
_local_lib = s->block_num;
_local_lib_id = s->id;
auto purge_to = std::min( _local_lib, _last_sent_block_num );
auto& idx = _block_status.get<by_num>();
auto itr = idx.begin();
while( itr != idx.end() && itr->block_num() < purge_to ) {
idx.erase(itr);
itr = idx.begin();
}
if( _remote_request_irreversible_only ) {
auto bitr = _block_status.find(s->id);
if ( bitr == _block_status.end() || !bitr->received_from_peer ) {
_block_header_notices.insert(s->id);
}
}
maybe_send_next_message();
}
void on_bad_block( signed_block_ptr b ) {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
try {
auto id = b->id();
auto itr = _block_status.find( id );
if( itr == _block_status.end() ) return;
if( itr->received_from_peer ) {
peer_elog(this, "bad signed_block_ptr : unknown" );
elog( "peer sent bad block #${b} ${i}, disconnect", ("b", b->block_num())("i",b->id()) );
_ws->next_layer().close();
}
} catch ( ... ) {
elog( "uncaught exception" );
}
}
void on_accepted_block_header( const block_state_ptr& s ) {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
// ilog( "accepted block header ${n}", ("n",s->block_num) );
const auto& id = s->id;
if( fc::time_point::now() - s->block->timestamp < fc::seconds(6) ) {
// ilog( "queue notice to peer that we have this block so hopefully they don't send it to us" );
auto itr = _block_status.find( id );
if( !_remote_request_irreversible_only && ( itr == _block_status.end() || !itr->received_from_peer ) ) {
_block_header_notices.insert( id );
}
if( itr == _block_status.end() ) {
_block_status.insert( block_status(id, false, false) );
}
}
}
void on_accepted_block( const block_state_ptr& s ) {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
//idump((_block_status.size())(_transaction_status.size()));
//ilog( "accepted block ${n}", ("n",s->block_num) );
const auto& id = s->id;
_local_head_block_id = id;
_local_head_block_num = block_header::num_from_id(id);
if( _local_head_block_num < _last_sent_block_num ) {
_last_sent_block_num = _local_lib;
_last_sent_block_id = _local_lib_id;
}
purge_transaction_cache();
/** purge all transactions from cache, I will send them as part of a block
* in the future unless peer tells me they already have block.
*/
for( const auto& receipt : s->block->transactions ) {
if( receipt.trx.which() == 1 ) {
const auto& pt = receipt.trx.get<packed_transaction>();
// get id via get_uncached_id() as packed_transaction.id() mutates internal transaction state
const auto& tid = pt.get_uncached_id();
auto itr = _transaction_status.find( tid );
if( itr != _transaction_status.end() )
_transaction_status.erase(itr);
}
}
maybe_send_next_message(); /// attempt to send if we are idle
}
template<typename L>
void async_get_pending_block_ids( L&& callback ) {
/// send peer my head block status which is read from chain plugin
_app_ios.post( [self = shared_from_this(),callback]{
auto& control = app().get_plugin<chain_plugin>().chain();
auto lib = control.last_irreversible_block_num();
auto head = control.fork_db_head_block_id();
auto head_num = block_header::num_from_id(head);
std::vector<block_id_type> ids;
if( lib > 0 ) {
ids.reserve((head_num-lib)+1);
for( auto i = lib; i <= head_num; ++i ) {
ids.emplace_back(control.get_block_id_for_num(i));
}
}
self->_ios.post( boost::asio::bind_executor(
self->_strand,
[callback,ids,lib](){
callback(ids,lib);
}
));
});
}
template<typename L>
void async_get_block_num( uint32_t blocknum, L&& callback ) {
_app_ios.post( [self = shared_from_this(), blocknum, callback]{
auto& control = app().get_plugin<chain_plugin>().chain();
signed_block_ptr sblockptr;
try {
//ilog( "fetch block ${n}", ("n",blocknum) );
sblockptr = control.fetch_block_by_number( blocknum );
} catch ( const fc::exception& e ) {
edump((e.to_detail_string()));
}
self->_ios.post( boost::asio::bind_executor(
self->_strand,
[callback,sblockptr](){
callback(sblockptr);
}
));
});
}
void do_hello();
void send( const bnet_message& msg ) { try {
auto ps = fc::raw::pack_size(msg);
_out_buffer.resize(ps);
fc::datastream<char*> ds(_out_buffer.data(), ps);
fc::raw::pack(ds, msg);
send();
} FC_LOG_AND_RETHROW() }
template<class T>
void send( const bnet_message& msg, const T& ex ) { try {
auto ex_size = fc::raw::pack_size(ex);
auto ps = fc::raw::pack_size(msg) + fc::raw::pack_size(unsigned_int(ex_size)) + ex_size;
_out_buffer.resize(ps);
fc::datastream<char*> ds(_out_buffer.data(), ps);
fc::raw::pack( ds, msg );
fc::raw::pack( ds, unsigned_int(ex_size) );
fc::raw::pack( ds, ex );
send();
} FC_LOG_AND_RETHROW() }
void send() { try {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
_state = sending_state;
_ws->async_write( boost::asio::buffer(_out_buffer),
boost::asio::bind_executor(
_strand,
std::bind( &session::on_write,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2 ) ) );
} FC_LOG_AND_RETHROW() }
void mark_block_status( const block_id_type& id, bool known_by_peer, bool recv_from_peer ) {
auto itr = _block_status.find(id);
if( itr == _block_status.end() ) {
// optimization to avoid sending blocks to nodes that already know about them
// to avoid unbounded memory growth limit number tracked
const auto min_block_num = std::min( _local_lib, _last_sent_block_num );
const auto max_block_num = min_block_num + _max_block_status_range;
const auto block_num = block_header::num_from_id( id );
if( block_num > min_block_num && block_num < max_block_num && _block_status.size() < _max_block_status_range )
_block_status.insert( block_status( id, known_by_peer, recv_from_peer ) );
} else {
_block_status.modify( itr, [&]( auto& item ) {
item.known_by_peer = known_by_peer;
if (recv_from_peer) item.received_from_peer = true;
});
}
}
/**
* This method will determine whether there is a message in the
* out queue, if so it returns. Otherwise it determines the best
* message to send.
*/
void maybe_send_next_message() {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
if( _state == sending_state ) return; /// in process of sending
if( _out_buffer.size() ) return; /// in process of sending
if( !_recv_remote_hello || !_sent_remote_hello ) return;
clear_expired_trx();
if( send_block_notice() ) return;
if( send_pong() ) return;
if( send_ping() ) return;
/// we don't know where we are (waiting on accept block localhost)
if( _local_head_block_id == block_id_type() ) return ;
if( send_next_block() ) return;
if( send_next_trx() ) return;
}
bool send_block_notice() {
if( _block_header_notices.size() == 0 )
return false;
block_notice notice;
notice.block_ids.reserve( _block_header_notices.size() );
for( auto& id : _block_header_notices )
notice.block_ids.emplace_back(id);
send(notice);
_block_header_notices.clear();
return true;
}
bool send_pong() {
if( _last_recv_ping.code == fc::sha256() )
return false;
send( pong{ fc::time_point::now(), _last_recv_ping.code } );
_last_recv_ping.code = fc::sha256();
return true;
}
bool send_ping() {
auto delta_t = fc::time_point::now() - _last_sent_ping.sent;
if( delta_t < fc::seconds(3) ) return false;
if( _last_sent_ping.code == fc::sha256() ) {
_last_sent_ping.sent = fc::time_point::now();
_last_sent_ping.code = fc::sha256::hash(_last_sent_ping.sent); /// TODO: make this more random
_last_sent_ping.lib = _local_lib;
send( _last_sent_ping );
}
/// we expect the peer to send us a ping every 3 seconds, so if we haven't gotten one
/// in the past 6 seconds then the connection is likely hung. Unfortunately, we cannot
/// use the round-trip time of ping/pong to measure latency because during syncing the
/// remote peer can be stuck doing CPU intensive tasks that block its reading of the
/// buffer. This buffer gets filled with perhaps 100 blocks taking .1 seconds each for
/// a total processing time of 10+ seconds. That said, the peer should come up for air
/// every .1 seconds so should still be able to send out a ping every 3 seconds.
//
// We don't want to wait a RTT for each block because that could also slow syncing for
// empty blocks...
//
//if( fc::time_point::now() - _last_recv_ping_time > fc::seconds(6) ) {
// do_goodbye( "no ping from peer in last 6 seconds...." );
//}
return true;
}
bool is_known_by_peer( block_id_type id ) {
auto itr = _block_status.find(id);
if( itr == _block_status.end() ) return false;
return itr->known_by_peer;
}
void clear_expired_trx() {
auto& idx = _transaction_status.get<by_expired>();
auto itr = idx.begin();
while( itr != idx.end() && itr->expired < fc::time_point::now() ) {
idx.erase(itr);
itr = idx.begin();
}
}
bool send_next_trx() { try {
if( !_remote_request_trx ) return false;
auto& idx = _transaction_status.get<by_received>();
auto start = idx.begin();
if( start == idx.end() || start->known_by_peer() )
return false;
auto ptrx_ptr = std::make_shared<packed_transaction>( start->trx->packed_trx );
idx.modify( start, [&]( auto& stat ) {
stat.mark_known_by_peer();
});
// wlog("sending trx ${id}", ("id",start->id) );
send(ptrx_ptr);
return true;
} FC_LOG_AND_RETHROW() }
void on_async_get_block( const signed_block_ptr& nextblock ) {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
if( !nextblock) {
_state = idle_state;
maybe_send_next_message();
return;
}
/// if something changed, the next block doesn't link to the last
/// block we sent, local chain must have switched forks
if( nextblock->previous != _last_sent_block_id ) {
if( !is_known_by_peer( nextblock->previous ) ) {
_last_sent_block_id = _local_lib_id;
_last_sent_block_num = _local_lib;
_state = idle_state;
maybe_send_next_message();
return;
}
}
/// at this point we know the peer can link this block
auto next_id = nextblock->id();
/// if the peer already knows about this block, great no need to
/// send it, mark it as 'sent' and move on.
if( is_known_by_peer( next_id ) ) {
_last_sent_block_id = next_id;
_last_sent_block_num = nextblock->block_num();
_state = idle_state;
maybe_send_next_message();
return;
}
mark_block_status( next_id, true, false );
_last_sent_block_id = next_id;
_last_sent_block_num = nextblock->block_num();
send( nextblock );
status( "sending block " + std::to_string( block_header::num_from_id(next_id) ) );
if( nextblock->timestamp > (fc::time_point::now() - fc::seconds(5)) ) {
mark_block_transactions_known_by_peer( nextblock );
}
}
/**
* Send the next block after the last block in our current fork that
* we know the remote peer knows.
*/
bool send_next_block() {
if ( _remote_request_irreversible_only && _last_sent_block_id == _local_lib_id ) {
return false;
}
if( _last_sent_block_id == _local_head_block_id ) /// we are caught up
return false;
///< set sending state because this callback may result in sending a message
_state = sending_state;
async_get_block_num( _last_sent_block_num + 1,
[self=shared_from_this()]( auto sblockptr ) {
self->on_async_get_block( sblockptr );
});
return true;
}
void on_fail( boost::system::error_code ec, const char* what ) {
try {
verify_strand_in_this_thread(_strand, __func__, __LINE__);
elog( "${w}: ${m}", ("w", what)("m", ec.message() ) );
_ws->next_layer().close();
} catch ( ... ) {
elog( "uncaught exception on close" );
}
}
void on_accept( boost::system::error_code ec ) {
if( ec ) {
return on_fail( ec, "accept" );
}
do_hello();
do_read();
}
void do_read() {
_ws->async_read( _in_buffer,
boost::asio::bind_executor(
_strand,
std::bind( &session::on_read,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
void on_read( boost::system::error_code ec, std::size_t bytes_transferred ) {
boost::ignore_unused(bytes_transferred);
if( ec == ws::error::closed )
return on_fail( ec, "close on read" );
if( ec ) {
return on_fail( ec, "read" );;
}
try {
auto d = boost::asio::buffer_cast<char const*>(boost::beast::buffers_front(_in_buffer.data()));
auto s = boost::asio::buffer_size(_in_buffer.data());
fc::datastream<const char*> ds(d,s);
bnet_message msg;
fc::raw::unpack( ds, msg );
on_message( msg, ds );
_in_buffer.consume( ds.tellp() );
wait_on_app();
return;
} catch ( ... ) {
wlog( "close bad payload" );
}
try {
_ws->close( boost::beast::websocket::close_code::bad_payload );
} catch ( ... ) {
elog( "uncaught exception on close" );
}
}
/** if we just call do_read here then this thread might run ahead of
* the main thread, instead we post an event to main which will then
* post a new read event when ready.
*
* This also keeps the "shared pointer" alive in the callback preventing
* the connection from being closed.
*/
void wait_on_app() {
app().get_io_service().post(
boost::asio::bind_executor( _strand, [self=shared_from_this()]{ self->do_read(); } )
);
}
void on_message( const bnet_message& msg, fc::datastream<const char*>& ds ) {
try {
switch( msg.which() ) {
case bnet_message::tag<hello>::value:
on( msg.get<hello>(), ds );
break;
case bnet_message::tag<block_notice>::value:
on( msg.get<block_notice>() );
break;
case bnet_message::tag<signed_block_ptr>::value:
on( msg.get<signed_block_ptr>() );
break;
case bnet_message::tag<packed_transaction_ptr>::value:
on( msg.get<packed_transaction_ptr>() );
break;
case bnet_message::tag<ping>::value:
on( msg.get<ping>() );
break;
case bnet_message::tag<pong>::value:
on( msg.get<pong>() );
break;
default:
wlog( "bad message received" );
_ws->close( boost::beast::websocket::close_code::bad_payload );
return;
}
maybe_send_next_message();
} catch( const fc::exception& e ) {
elog( "${e}", ("e",e.to_detail_string()));
_ws->close( boost::beast::websocket::close_code::bad_payload );
}
}
void on( const block_notice& notice ) {
peer_ilog(this, "received block_notice");
for( const auto& id : notice.block_ids ) {
status( "received notice " + std::to_string( block_header::num_from_id(id) ) );
mark_block_status( id, true, false );
}
}
void on( const hello& hi, fc::datastream<const char*>& ds );
void on( const ping& p ) {
peer_ilog(this, "received ping");
_last_recv_ping = p;
_remote_lib = p.lib;
_last_recv_ping_time = fc::time_point::now();
}
void on( const pong& p ) {
peer_ilog(this, "received pong");
if( p.code != _last_sent_ping.code ) {
peer_elog(this, "bad ping : invalid pong code");
return do_goodbye( "invalid pong code" );
}
_last_sent_ping.code = fc::sha256();
}
void do_goodbye( const string& reason ) {
try {
status( "goodbye - " + reason );
_ws->next_layer().close();
} catch ( ... ) {
elog( "uncaught exception on close" );
}
}
void check_for_redundant_connection();
void on( const signed_block_ptr& b ) {
peer_ilog(this, "received signed_block_ptr");
if (!b) {
peer_elog(this, "bad signed_block_ptr : null pointer");
AAC_THROW(block_validate_exception, "bad block" );
}
status( "received block " + std::to_string(b->block_num()) );
//ilog( "recv block ${n}", ("n", b->block_num()) );
auto id = b->id();
mark_block_status( id, true, true );
app().get_channel<incoming::channels::block>().publish(b);
mark_block_transactions_known_by_peer( b );
}
void mark_block_transactions_known_by_peer( const signed_block_ptr& b ) {
for( const auto& receipt : b->transactions ) {
if( receipt.trx.which() == 1 ) {
const auto& pt = receipt.trx.get<packed_transaction>();
// get id via get_uncached_id() as packed_transaction.id() mutates internal transaction state
const auto& id = pt.get_uncached_id();
mark_transaction_known_by_peer(id);
}
}
}
/**
* @return true if trx is known by local host, false if new to this host
*/
bool mark_transaction_known_by_peer( const transaction_id_type& id ) {
auto itr = _transaction_status.find( id );
if( itr != _transaction_status.end() ) {
_transaction_status.modify( itr, [&]( auto& stat ) {
stat.mark_known_by_peer();
});
return true;
} else {
transaction_status stat;
stat.id = id;
stat.mark_known_by_peer();
stat.expired = fc::time_point::now()+fc::seconds(5);
_transaction_status.insert(stat);
}
return false;
}
void on( const packed_transaction_ptr& p ) {
peer_ilog(this, "received packed_transaction_ptr");
if (!p) {
peer_elog(this, "bad packed_transaction_ptr : null pointer");
AAC_THROW(transaction_exception, "bad transaction");
}
if( app().get_plugin<chain_plugin>().chain().get_read_mode() == chain::db_read_mode::READ_ONLY )
return;
// ilog( "recv trx ${n}", ("n", id) );
if( p->expiration() < fc::time_point::now() ) return;
// get id via get_uncached_id() as packed_transaction.id() mutates internal transaction state
const auto& id = p->get_uncached_id();
if( mark_transaction_known_by_peer( id ) )
return;
app().get_channel<incoming::channels::transaction>().publish(p);
}
void on_write( boost::system::error_code ec, std::size_t bytes_transferred ) {
boost::ignore_unused(bytes_transferred);
verify_strand_in_this_thread(_strand, __func__, __LINE__);
if( ec ) {
_ws->next_layer().close();
return on_fail( ec, "write" );
}
_state = idle_state;
_out_buffer.resize(0);
maybe_send_next_message();
}
void status( const string& msg ) {
// ilog( "${remote_peer}: ${msg}", ("remote_peer",fc::variant(_remote_peer_id).as_string().substr(3,5) )("msg",msg) );
}
const fc::variant_object& get_logger_variant() {
if (!_logger_variant) {
boost::system::error_code ec;
auto rep = _ws->lowest_layer().remote_endpoint(ec);
string ip = ec ? "<unknown>" : rep.address().to_string();
string port = ec ? "<unknown>" : std::to_string(rep.port());
auto lep = _ws->lowest_layer().local_endpoint(ec);
string lip = ec ? "<unknown>" : lep.address().to_string();
string lport = ec ? "<unknown>" : std::to_string(lep.port());
_logger_variant.emplace(fc::mutable_variant_object()
("_name", _peer)
("_id", _remote_peer_id)
("_ip", ip)
("_port", port)
("_lip", lip)
("_lport", lport)
);
}
return *_logger_variant;
}
};
/**
* Accepts incoming connections and launches the sessions
*/
class listener : public std::enable_shared_from_this<listener> {
private:
tcp::acceptor _acceptor;
tcp::socket _socket;
bnet_ptr _net_plugin;
public:
listener( boost::asio::io_context& ioc, tcp::endpoint endpoint, bnet_ptr np )
:_acceptor(ioc), _socket(ioc), _net_plugin(std::move(np))
{
boost::system::error_code ec;
_acceptor.open( endpoint.protocol(), ec );
if( ec ) { on_fail( ec, "open" ); return; }
_acceptor.set_option( boost::asio::socket_base::reuse_address(true) );
_acceptor.bind( endpoint, ec );
if( ec ) { on_fail( ec, "bind" ); return; }
_acceptor.listen( boost::asio::socket_base::max_listen_connections, ec );
if( ec ) on_fail( ec, "listen" );
}
void run() {
AAC_ASSERT( _acceptor.is_open(), plugin_exception, "unable top open listen socket" );
do_accept();
}
void do_accept() {
_acceptor.async_accept( _socket, [self=shared_from_this()]( auto ec ){ self->on_accept(ec); } );
}
void on_fail( boost::system::error_code ec, const char* what ) {
elog( "${w}: ${m}", ("w", what)("m", ec.message() ) );
}
void on_accept( boost::system::error_code ec );
};
class bnet_plugin_impl : public std::enable_shared_from_this<bnet_plugin_impl> {
public:
bnet_plugin_impl() = default;
const private_key_type _peer_pk = fc::crypto::private_key::generate(); /// one time random key to identify this process
public_key_type _peer_id = _peer_pk.get_public_key();
string _bnet_endpoint_address = "0.0.0.0";
uint16_t _bnet_endpoint_port = 4321;
bool _request_trx = true;
bool _follow_irreversible = false;
std::vector<std::string> _connect_to_peers; /// list of peers to connect to
std::vector<std::thread> _socket_threads;
int32_t _num_threads = 1;
std::unique_ptr<boost::asio::io_context> _ioc; // lifetime guarded by shared_ptr of bnet_plugin_impl
std::shared_ptr<listener> _listener;
std::shared_ptr<boost::asio::deadline_timer> _timer; // only access on app io_service
std::map<const session*, std::weak_ptr<session> > _sessions; // only access on app io_service
channels::irreversible_block::channel_type::handle _on_irb_handle;
channels::accepted_block::channel_type::handle _on_accepted_block_handle;
channels::accepted_block_header::channel_type::handle _on_accepted_block_header_handle;
channels::rejected_block::channel_type::handle _on_bad_block_handle;
channels::accepted_transaction::channel_type::handle _on_appled_trx_handle;
void async_add_session( std::weak_ptr<session> wp ) {
app().get_io_service().post( [wp,this]{
if( auto l = wp.lock() ) {
_sessions[l.get()] = wp;
}
});
}
void on_session_close( const session* s ) {
verify_strand_in_this_thread(app().get_io_service().get_executor(), __func__, __LINE__);
auto itr = _sessions.find(s);
if( _sessions.end() != itr )
_sessions.erase(itr);
}
template<typename Call>
void for_each_session( Call callback ) {
app().get_io_service().post([this, callback = callback] {
for (const auto& item : _sessions) {
if (auto ses = item.second.lock()) {
ses->_ios.post(boost::asio::bind_executor(
ses->_strand,
[ses, cb = callback]() { cb(ses); }
));
}
}
});
}
void on_accepted_transaction( transaction_metadata_ptr trx ) {
if( trx->implicit || trx->scheduled ) return;
for_each_session( [trx]( auto ses ){ ses->on_accepted_transaction( trx ); } );
}
/**
* Notify all active connection of the new irreversible block so they
* can purge their block cache
*/
void on_irreversible_block( block_state_ptr s ) {
for_each_session( [s]( auto ses ){ ses->on_new_lib( s ); } );
}
/**
* Notify all active connections of the new accepted block so
* they can relay it. This method also pre-packages the block
* as a packed bnet_message so the connections can simply relay
* it on.
*/
void on_accepted_block( block_state_ptr s ) {
_ioc->post( [s,this] { /// post this to the thread pool because packing can be intensive
for_each_session( [s]( auto ses ){ ses->on_accepted_block( s ); } );
});
}
void on_accepted_block_header( block_state_ptr s ) {
_ioc->post( [s,this] { /// post this to the thread pool because packing can be intensive
for_each_session( [s]( auto ses ){ ses->on_accepted_block_header( s ); } );
});
}
/**
* We received a bad block which either
* 1. didn't link to known chain
* 2. violated the consensus rules
*
* Any peer which sent us this block (not noticed)
* should be disconnected as they are objectively bad
*/
void on_bad_block( signed_block_ptr s ) {
for_each_session( [s]( auto ses ) { ses->on_bad_block(s); } );
};
void on_reconnect_peers() {
verify_strand_in_this_thread(app().get_io_service().get_executor(), __func__, __LINE__);
for( const auto& peer : _connect_to_peers ) {
bool found = false;
for( const auto& con : _sessions ) {
auto ses = con.second.lock();
if( ses && (ses->_peer == peer) ) {
found = true;
break;
}
}
if( !found ) {
wlog( "attempt to connect to ${p}", ("p",peer) );
auto s = std::make_shared<session>( *_ioc, shared_from_this() );
s->_local_peer_id = _peer_id;
_sessions[s.get()] = s;
s->run( peer );
}
}
start_reconnect_timer();
}
void start_reconnect_timer() {
/// add some random delay so that all my peers don't attempt to reconnect to me
/// at the same time after shutting down..
_timer->expires_from_now( boost::posix_time::microseconds( 1000000*(10+rand()%5) ) );
_timer->async_wait([=](const boost::system::error_code& ec) {
if( ec ) { return; }
on_reconnect_peers();
});
}
};
void listener::on_accept( boost::system::error_code ec ) {
if( ec ) {
if( ec == boost::system::errc::too_many_files_open )
do_accept();
return;
}
std::shared_ptr<session> newsession;
try {
newsession = std::make_shared<session>( move( _socket ), _net_plugin );
}
catch( std::exception& e ) {
//making a session creates an instance of std::random_device which may open /dev/urandom
// for example. Unfortuately the only defined error is a std::exception derivative
_socket.close();
}
if( newsession ) {
_net_plugin->async_add_session( newsession );
newsession->_local_peer_id = _net_plugin->_peer_id;
newsession->run();
}
do_accept();
}
bnet_plugin::bnet_plugin()
:my(std::make_shared<bnet_plugin_impl>()) {
}
bnet_plugin::~bnet_plugin() {
}
void bnet_plugin::set_program_options(options_description& cli, options_description& cfg) {
cfg.add_options()
("bnet-endpoint", bpo::value<string>()->default_value("0.0.0.0:4321"), "the endpoint upon which to listen for incoming connections" )
("bnet-follow-irreversible", bpo::value<bool>()->default_value(false), "this peer will request only irreversible blocks from other nodes" )
("bnet-threads", bpo::value<uint32_t>(), "the number of threads to use to process network messages" )
("bnet-connect", bpo::value<vector<string>>()->composing(), "remote endpoint of other node to connect to; Use multiple bnet-connect options as needed to compose a network" )
("bnet-no-trx", bpo::bool_switch()->default_value(false), "this peer will request no pending transactions from other nodes" )
("bnet-peer-log-format", bpo::value<string>()->default_value( "[\"${_name}\" ${_ip}:${_port}]" ),
"The string used to format peers when logging messages about them. Variables are escaped with ${<variable name>}.\n"
"Available Variables:\n"
" _name \tself-reported name\n\n"
" _id \tself-reported ID (Public Key)\n\n"
" _ip \tremote IP address of peer\n\n"
" _port \tremote port number of peer\n\n"
" _lip \tlocal IP address connected to peer\n\n"
" _lport \tlocal port number connected to peer\n\n")
;
}
void bnet_plugin::plugin_initialize(const variables_map& options) {
ilog( "Initialize bnet plugin" );
try {
peer_log_format = options.at( "bnet-peer-log-format" ).as<string>();
if( options.count( "bnet-endpoint" )) {
auto ip_port = options.at( "bnet-endpoint" ).as<string>();
//auto host = boost::asio::ip::host_name(ip_port);
auto port = ip_port.substr( ip_port.find( ':' ) + 1, ip_port.size());
auto host = ip_port.substr( 0, ip_port.find( ':' ));
my->_bnet_endpoint_address = host;
my->_bnet_endpoint_port = std::stoi( port );
idump((ip_port)( host )( port )( my->_follow_irreversible ));
}
if( options.count( "bnet-follow-irreversible" )) {
my->_follow_irreversible = options.at( "bnet-follow-irreversible" ).as<bool>();
}
if( options.count( "bnet-connect" )) {
my->_connect_to_peers = options.at( "bnet-connect" ).as<vector<string>>();
}
if( options.count( "bnet-threads" )) {
my->_num_threads = options.at( "bnet-threads" ).as<uint32_t>();
if( my->_num_threads > 8 )
my->_num_threads = 8;
}
my->_request_trx = !options.at( "bnet-no-trx" ).as<bool>();
} FC_LOG_AND_RETHROW()
}
void bnet_plugin::plugin_startup() {
if(fc::get_logger_map().find(logger_name) != fc::get_logger_map().end())
plugin_logger = fc::get_logger_map()[logger_name];
wlog( "bnet startup " );
auto& chain = app().get_plugin<chain_plugin>().chain();
FC_ASSERT ( chain.get_read_mode() != chain::db_read_mode::IRREVERSIBLE, "bnet is not compatible with \"irreversible\" read_mode");
my->_on_appled_trx_handle = app().get_channel<channels::accepted_transaction>()
.subscribe( [this]( transaction_metadata_ptr t ){
my->on_accepted_transaction(t);
});
my->_on_irb_handle = app().get_channel<channels::irreversible_block>()
.subscribe( [this]( block_state_ptr s ){
my->on_irreversible_block(s);
});
my->_on_accepted_block_handle = app().get_channel<channels::accepted_block>()
.subscribe( [this]( block_state_ptr s ){
my->on_accepted_block(s);
});
my->_on_accepted_block_header_handle = app().get_channel<channels::accepted_block_header>()
.subscribe( [this]( block_state_ptr s ){
my->on_accepted_block_header(s);
});
my->_on_bad_block_handle = app().get_channel<channels::rejected_block>()
.subscribe( [this]( signed_block_ptr b ){
my->on_bad_block(b);
});
if( app().get_plugin<chain_plugin>().chain().get_read_mode() == chain::db_read_mode::READ_ONLY ) {
my->_request_trx = false;
ilog( "setting bnet-no-trx to true since in read-only mode" );
}
const auto address = boost::asio::ip::make_address( my->_bnet_endpoint_address );
my->_ioc.reset( new boost::asio::io_context{my->_num_threads} );
auto& ioc = *my->_ioc;
my->_timer = std::make_shared<boost::asio::deadline_timer>( app().get_io_service() );
my->start_reconnect_timer();
my->_listener = std::make_shared<listener>( ioc,
tcp::endpoint{ address, my->_bnet_endpoint_port },
my );
my->_listener->run();
my->_socket_threads.reserve( my->_num_threads );
for( auto i = 0; i < my->_num_threads; ++i ) {
my->_socket_threads.emplace_back( [&ioc]{ wlog( "start thread" ); ioc.run(); wlog( "end thread" ); } );
}
for( const auto& peer : my->_connect_to_peers ) {
auto s = std::make_shared<session>( ioc, my );
s->_local_peer_id = my->_peer_id;
my->_sessions[s.get()] = s;
s->run( peer );
}
}
void bnet_plugin::plugin_shutdown() {
try {
my->_timer->cancel();
my->_timer.reset();
} catch ( ... ) {
elog( "exception thrown on timer shutdown" );
}
/// shut down all threads and close all connections
my->for_each_session([](auto ses){
ses->do_goodbye( "shutting down" );
});
my->_listener.reset();
my->_ioc->stop();
wlog( "joining bnet threads" );
for( auto& t : my->_socket_threads ) {
t.join();
}
wlog( "done joining threads" );
my->for_each_session([](auto ses){
AAC_ASSERT( false, plugin_exception, "session ${ses} still active", ("ses", ses->_session_num) );
});
// lifetime of _ioc is guarded by shared_ptr of bnet_plugin_impl
}
session::~session() {
wlog( "close session ${n}",("n",_session_num) );
std::weak_ptr<bnet_plugin_impl> netp = _net_plugin;
_app_ios.post( [netp,ses=this]{
if( auto net = netp.lock() )
net->on_session_close(ses);
});
}
void session::do_hello() {
/// TODO: find more effecient way to move large array of ids in event of fork
async_get_pending_block_ids( [self = shared_from_this() ]( const vector<block_id_type>& ids, uint32_t lib ){
hello hello_msg;
hello_msg.peer_id = self->_local_peer_id;
hello_msg.last_irr_block_num = lib;
hello_msg.pending_block_ids = ids;
hello_msg.request_transactions = self->_net_plugin->_request_trx;
hello_msg.chain_id = app().get_plugin<chain_plugin>().get_chain_id(); // TODO: Quick fix in a rush. Maybe a better solution is needed.
self->_local_lib = lib;
if ( self->_net_plugin->_follow_irreversible ) {
self->send( hello_msg, hello_extension(hello_extension_irreversible_only()) );
} else {
self->send( hello_msg );
}
self->_sent_remote_hello = true;
});
}
void session::check_for_redundant_connection() {
app().get_io_service().post( [self=shared_from_this()]{
self->_net_plugin->for_each_session( [self]( auto ses ){
if( ses != self && ses->_remote_peer_id == self->_remote_peer_id ) {
self->do_goodbye( "redundant connection" );
}
});
});
}
void session::on( const hello& hi, fc::datastream<const char*>& ds ) {
peer_ilog(this, "received hello");
_recv_remote_hello = true;
if( hi.chain_id != app().get_plugin<chain_plugin>().get_chain_id() ) { // TODO: Quick fix in a rush. Maybe a better solution is needed.
peer_elog(this, "bad hello : wrong chain id");
return do_goodbye( "disconnecting due to wrong chain id" );
}
if( hi.peer_id == _local_peer_id ) {
return do_goodbye( "connected to self" );
}
if ( _net_plugin->_follow_irreversible && hi.protocol_version <= "1.0.0") {
return do_goodbye( "need newer protocol version that supports sending only irreversible blocks" );
}
if ( hi.protocol_version >= "1.0.1" ) {
//optional extensions
while ( 0 < ds.remaining() ) {
unsigned_int size;
fc::raw::unpack( ds, size ); // next extension size
auto ex_start = ds.pos();
fc::datastream<const char*> dsw( ex_start, size );
unsigned_int wich;
fc::raw::unpack( dsw, wich );
hello_extension ex;
if ( wich < ex.count() ) { //know extension
fc::datastream<const char*> dsx( ex_start, size ); //unpack needs to read static_variant _tag again
fc::raw::unpack( dsx, ex );
if ( ex.which() == hello_extension::tag<hello_extension_irreversible_only>::value ) {
_remote_request_irreversible_only = true;
}
} else {
//unsupported extension, we just ignore it
//another side does know our protocol version, i.e. it know which extensions we support
//so, it some extensions were crucial, another side will close the connection
}
ds.skip(size); //move to next extension
}
}
_last_sent_block_num = hi.last_irr_block_num;
_remote_request_trx = hi.request_transactions;
_remote_peer_id = hi.peer_id;
_remote_lib = hi.last_irr_block_num;
for( const auto& id : hi.pending_block_ids )
mark_block_status( id, true, false );
check_for_redundant_connection();
}
} /// namespace aacio
| [
"caokun@acuteangle.cn"
] | caokun@acuteangle.cn |
4c51c4d31b096154ba34562b2564fd47283919f5 | cc6f5216f460f06bdc047fed39ac0e7cebd73cfa | /NTHU_OJ_Codes/7525_-_PF_-_Let’s_play_Igo.cpp | 61500b489c73681ab12ae18e195ae1a4725c6a51 | [] | no_license | henryyang42/C_CPP_Codes | e90d01b03f248c0fbac55542c3c39083ff8a6fe2 | 8d4a686f49f4d565427f68b46039ad5d5626dc38 | refs/heads/master | 2021-01-18T21:43:28.614381 | 2016-04-10T05:38:00 | 2016-04-10T05:38:00 | 16,172,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
char map[1011][1011];
int B[1010][1010], W[1010][1010];
int findW(int xa, int ya, int xb, int yb){
return W[xb][yb] - W[xb][ya-1] - W[xa - 1][yb] + W[xa - 1][ya -1];
}
int findB(int xa, int ya, int xb, int yb){
return B[xb][yb] - B[xb][ya-1] - B[xa - 1][yb] + B[xa - 1][ya -1];
}
int main(){
int m, n, q, casect = 0;
while(scanf("%d%d%d", &m, &n, &q) > 0, m+n+q){
int i, j;
memset(map, 0, sizeof(map));
memset(B, 0, sizeof(B));
memset(W, 0, sizeof(W));
for(i = 0; i < m; i++)
scanf("%s", map[i+1] + 1);
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++){
B[i][j] = B[i][j - 1] + (map[i][j] == 'B');
W[i][j] = W[i][j - 1] + (map[i][j] == 'W');
}
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++){
B[i][j] += B[i-1][j];
W[i][j] += W[i-1][j];
}
long long int Wct = 0, Bct = 0;
for(i = 0; i < q; i++){
int xa, ya, xb, yb, temp;
scanf("%d%d%d%d", &xa, &ya, &xb,&yb);
if(xa > xb)
temp = xa, xa = xb, xb = temp;
if(ya > yb)
temp = ya, ya = yb, yb = temp;
Wct += findW(xa, ya, xb, yb);
Bct += findB(xa, ya, xb, yb);
}
printf("Case #%d:\n", ++casect);
printf("Redline: %lldpts Cake: %lldpts\n", Bct, Wct);
if(Bct == Wct)
puts("Tie!");
if(Bct > Wct)
puts("Redline wins!");
if(Bct < Wct)
puts("Cake wins!");
}
return 0;
}
| [
"henry@HenryAlmighty.(none)"
] | henry@HenryAlmighty.(none) |
a37c5a48bdd79c437c36aba787a3dc62051b4c6b | 3ad1fef9ebfd3a5175dfda31013c6281b2824623 | /Base/Source/GameObjectIn2D.h | edb62148afd1eac71ee3d7eda3e5002b8e6762c5 | [] | no_license | BlackLotusXZ/SP3 | b9e183e37d5c747ef07ebcca84c0115c34c8809d | e0c8d98be1bfa44574ce7aee68f24a78c226876b | refs/heads/master | 2021-01-16T23:00:35.418167 | 2015-08-17T07:46:50 | 2015-08-17T07:46:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | h | #ifndef GAMEOBJECTIN2D_H
#define GAMEOBJECTIN2D_H
#include "collisionin2d.h"
class GameObjectIn2D : public CollisionIn2D
{
public:
GameObjectIn2D(void);
~GameObjectIn2D(void);
virtual void Init(Vector2 position, Vector2 scale, float mass, float tileSize);
void SetPosition(Vector2 position);
Vector2 GetPosition();
Vector2 GetScale();
protected:
Vector2 m_position;
Vector2 m_scale;
float m_mass;
};
#endif | [
"blaze-trinity@hotmail.sg"
] | blaze-trinity@hotmail.sg |
63ee49bd168086d97dd3650bce231eaebde76a14 | 4bcc9806152542ab43fc2cf47c499424f200896c | /tensorflow/core/kernels/ragged_tensor_to_variant_op_test.h | 0b71a308b2c5030cbbf7bfa0fa2755e28332d241 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | tensorflow/tensorflow | 906276dbafcc70a941026aa5dc50425ef71ee282 | a7f3934a67900720af3d3b15389551483bee50b8 | refs/heads/master | 2023-08-25T04:24:41.611870 | 2023-08-25T04:06:24 | 2023-08-25T04:14:08 | 45,717,250 | 208,740 | 109,943 | Apache-2.0 | 2023-09-14T20:55:50 | 2015-11-07T01:19:20 | C++ | UTF-8 | C++ | false | false | 5,899 | h | /* Copyright 2019 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 <vector>
#include <gtest/gtest.h>
#include "absl/strings/match.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/shape_inference_testutil.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/framework/variant_encode_decode.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/kernels/ragged_tensor_variant.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#ifndef TENSORFLOW_CORE_KERNELS_RAGGED_TENSOR_TO_VARIANT_OP_TEST_H_
#define TENSORFLOW_CORE_KERNELS_RAGGED_TENSOR_TO_VARIANT_OP_TEST_H_
namespace tensorflow {
class RaggedTensorToVariantKernelTest : public ::tensorflow::OpsTestBase {
protected:
// Builds the tensorflow test graph for the RaggedTensorToVariant op, and
// populates the `splits` input with the given values.
template <typename VALUE_TYPE, typename SPLIT_TYPE>
void BuildEncodeRaggedTensorGraph(
const std::vector<std::vector<SPLIT_TYPE>>& ragged_splits,
const TensorShape& ragged_values_shape,
const std::vector<VALUE_TYPE>& ragged_values, const bool batched) {
const auto values_dtype = DataTypeToEnum<VALUE_TYPE>::v();
const auto splits_dtype = DataTypeToEnum<SPLIT_TYPE>::v();
int64_t num_splits = ragged_splits.size();
TF_ASSERT_OK(
NodeDefBuilder("tested_op", "RaggedTensorToVariant")
.Input(FakeInput(num_splits, splits_dtype)) // ragged_splits
.Input(FakeInput(values_dtype)) // ragged_values
.Attr("RAGGED_RANK", num_splits)
.Attr("Tvalues", values_dtype)
.Attr("Tsplits", splits_dtype)
.Attr("batched_input", batched)
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
for (const auto& splits : ragged_splits) {
int64_t splits_size = splits.size();
AddInputFromArray<SPLIT_TYPE>(TensorShape({splits_size}), splits);
}
AddInputFromArray<VALUE_TYPE>(ragged_values_shape, ragged_values);
}
template <typename VALUE_TYPE, typename SPLIT_TYPE>
void BuildEncodeRaggedTensorGraph(
const std::vector<std::vector<SPLIT_TYPE>>& ragged_splits,
const TensorShape& ragged_values_shape, const VALUE_TYPE& ragged_values,
const bool batched) {
const auto values_dtype = DataTypeToEnum<VALUE_TYPE>::v();
const auto splits_dtype = DataTypeToEnum<SPLIT_TYPE>::v();
int64_t num_splits = ragged_splits.size();
TF_ASSERT_OK(
NodeDefBuilder("tested_op", "RaggedTensorToVariant")
.Input(FakeInput(num_splits, splits_dtype)) // ragged_splits
.Input(FakeInput(values_dtype)) // ragged_values
.Attr("RAGGED_RANK", num_splits)
.Attr("Tvalues", values_dtype)
.Attr("Tsplits", splits_dtype)
.Attr("batched_input", batched)
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
for (const auto& splits : ragged_splits) {
int64_t splits_size = splits.size();
AddInputFromArray<SPLIT_TYPE>(TensorShape({splits_size}), splits);
}
AddInput<VALUE_TYPE>(ragged_values_shape,
[&ragged_values](int i) { return ragged_values; });
}
template <typename VALUE_TYPE, typename SPLIT_TYPE>
RaggedTensorVariant CreateVariantFromRagged(
const std::vector<std::vector<SPLIT_TYPE>>& ragged_splits,
const TensorShape& ragged_values_shape,
const std::vector<VALUE_TYPE>& ragged_values) {
RaggedTensorVariant encoded;
for (auto ragged_split : ragged_splits) {
int splits_size = ragged_split.size();
Tensor splits(DataTypeToEnum<SPLIT_TYPE>::v(),
TensorShape({splits_size}));
test::FillValues<SPLIT_TYPE>(&splits, ragged_split);
encoded.append_splits(splits);
}
Tensor values(DataTypeToEnum<VALUE_TYPE>::v(), ragged_values_shape);
test::FillValues<VALUE_TYPE>(&values, ragged_values);
encoded.set_values(values);
return encoded;
}
template <typename VALUE_TYPE, typename SPLIT_TYPE>
RaggedTensorVariant CreateVariantFromRagged(
const std::vector<std::vector<SPLIT_TYPE>>& ragged_splits,
const std::vector<VALUE_TYPE>& ragged_values) {
int num_values = ragged_values.size();
return CreateVariantFromRagged(ragged_splits, {num_values}, ragged_values);
}
template <typename VALUE_TYPE, typename SPLIT_TYPE>
void ExpectRaggedTensorVariantEqual(const RaggedTensorVariant& expected,
const RaggedTensorVariant& actual) {
test::ExpectTensorEqual<VALUE_TYPE>(actual.values(), expected.values());
EXPECT_EQ(actual.ragged_rank(), expected.ragged_rank());
for (int i = 0; i < actual.ragged_rank(); ++i) {
test::ExpectTensorEqual<SPLIT_TYPE>(actual.splits(i), expected.splits(i));
}
}
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_KERNELS_RAGGED_TENSOR_TO_VARIANT_OP_TEST_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
3dae3145607eac39aed770047cac426cd39aaf0c | 48d5f251a8168b7e77c56f35e7c161b03315ea39 | /BOJ/16929_TwoDots.cpp | 782633f52d7137216341ea45e5f299623072fa0e | [] | no_license | dmzld/algorithm | c61f806f472921fdcf000b080349f3f6e682ee0c | 4d0fc85616522ac85f638f60ca4b6d1890035efb | refs/heads/master | 2021-07-03T23:09:57.891752 | 2020-12-06T07:54:35 | 2020-12-06T07:54:35 | 205,629,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | #include <iostream>
#include <cstring>
using namespace std;
int N, M;
char map[50][50];
bool check[50][50];
pair<int, int> dir[4] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
bool dfs(int sy, int sx, int y, int x, int cnt){
bool cycle = false;
for (int i = 0; i < 4; i++){
int ny = y + dir[i].first, nx = x + dir[i].second;
if (ny >= 0 && ny < N && nx >= 0 && nx < M){
if (ny == sy && nx == sx && cnt >= 4)
return true;
if (!check[ny][nx] && map[ny][nx] == map[sy][sx]){
check[ny][nx] = true;
cycle = dfs(sy, sx, ny, nx, cnt + 1);
check[ny][nx] = false;
if (cycle)
return true;
}
}
}
return cycle;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> N >> M;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
cin >> map[i][j];
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
memset(check, false, sizeof(check));
check[i][j] = true;
if (dfs(i, j, i, j, 1)){
cout << "Yes\n";
return 0;
}
}
}
cout << "No\n";
return 0;
}
| [
"noreply@github.com"
] | dmzld.noreply@github.com |
3fdccd3c914eb88e6a75c0f12ddcfe50091ed64d | 505b085373e70f0ab16d4c7f05bbd497f50b7e17 | /contest/contest 25-11-2011/cAPS-lOCK.cpp | fae0dd66201ac2534420f9124b4be1fa809ad385 | [] | no_license | leninhasda/competitive-programming | 7699199b26e4a80833db6631053a827831c4c0e0 | 6f3ffa51e1a16b782cdf99bfa6224f2a3510fa85 | refs/heads/master | 2022-11-05T19:12:13.197325 | 2022-10-18T07:28:23 | 2022-10-18T07:28:23 | 13,601,367 | 1 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | cpp | #include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
bool isU(char ch)
{
if(ch >= 'A' && ch <= 'Z') return true;
return false;
}
bool isL(char ch)
{
if(ch >= 'a' && ch <= 'z') return true;
return false;
}
int main()
{
char word[105];
int i, len;
bool flag;
while(scanf("%s", &word)==1)
{
len = strlen(word);
if(isL(word[0]))
{
flag = true;
for(i=1; i<len; i++)
{
if(!isU(word[i]))
{
flag = false;
true;
}
}
if(flag)
{
printf("%c", char(word[0]-32));
for(i=1; i<len; i++)
{
printf("%c", char(word[i]+32));
}
printf("\n");
}
else
{
printf("%s\n", word);
}
}
else
{
flag = true;
for(i=0; i<len; i++)
{
if(!isU(word[i]))
{
flag = false;
true;
}
}
if(flag)
{
// printf("%c", char(word[0]-32));
for(i=0; i<len; i++)
{
printf("%c", char(word[i]+32));
}
printf("\n");
}
else
{
printf("%s\n", word);
}
}
}
return 0;
}
| [
"leninhasda@gmail.com"
] | leninhasda@gmail.com |
5dfb4f09ec374333ab905d0b737ec903dc759459 | 1d1f67e1a3f98871a1b9ba100704083e426fade9 | /Leet2019/DesignCircularQueue.cpp | 155c29bbf3fbcc78fc815772e98acb40bddd9647 | [] | no_license | flameshimmer/leet2019.io | fae46200ed78fb0478db726b8c31e976e7d57001 | 47808dc97609f5a96c97a6fc703b98c75ad9a2b3 | refs/heads/master | 2022-07-22T10:51:10.651558 | 2022-07-07T18:05:48 | 2022-07-07T18:05:48 | 202,389,705 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | #include "stdafx.h"
//
namespace Solution2019
{
namespace DesignCircularQueue
{
void Main() {
string test = "tst test test";
print(test);
}
}
}
| [
"Ning@ningmadev99.redmond.corp.microsoft.com"
] | Ning@ningmadev99.redmond.corp.microsoft.com |
1d0c17cbbbe04834f104ef281d168e2cf02a5d1b | bd1e457d3bc7aba76c1200d15416fa5c1bf847de | /Lecture Codes/Lecture 19/Book.cpp | 6ff98981f3e477381d8a8a1a641a614d43b8b635 | [] | no_license | Mu-Ahmad/OOP-CMP-244-241 | 6da4f2fee88c207a688b8c70a8dd3ad8655921c3 | 3dd826fff83c9a539f89fc2483ac80c032b269dc | refs/heads/main | 2023-06-06T16:30:06.089789 | 2021-06-18T15:33:35 | 2021-06-18T15:33:35 | 303,761,272 | 17 | 6 | null | 2020-10-26T11:14:37 | 2020-10-13T16:19:04 | C++ | UTF-8 | C++ | false | false | 459 | cpp | #include <iostream>
using namespace std;
class Book{
string title, author;
int price;
public:
Book(string title, string author, int price){
this->title = title;
this->author = author;
this->price = price;
}
friend ostream& operator << (ostream &, const Book&);
};
ostream& operator << (ostream &out, const Book &b){
out << "Title: "<< b.title << '\n';
out << "Author: "<< b.author << '\n';
out << "Price: "<< b.price << '\n';
return out;
}
| [
"bcsf19m538@pucit.edu.pk"
] | bcsf19m538@pucit.edu.pk |
42375b75c201c3f19c82b24349526bd526871063 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/chrome/browser/sync_file_system/drive_backend/local_to_remote_syncer.h | ed366a5da96970624e6585b871fa4f9421e0d456 | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 4,807 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_LOCAL_TO_REMOTE_SYNCER_H_
#define CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_LOCAL_TO_REMOTE_SYNCER_H_
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/sync_file_system/drive_backend/sync_task.h"
#include "chrome/browser/sync_file_system/file_change.h"
#include "chrome/browser/sync_file_system/sync_action.h"
#include "chrome/browser/sync_file_system/sync_file_metadata.h"
#include "google_apis/drive/gdata_errorcode.h"
namespace drive {
class DriveServiceInterface;
class DriveUploaderInterface;
}
namespace google_apis {
class FileResource;
class ResourceList;
}
namespace sync_file_system {
class RemoteChangeProcessor;
namespace drive_backend {
class FileDetails;
class FileTracker;
class FolderCreator;
class MetadataDatabase;
class SyncEngineContext;
class LocalToRemoteSyncer : public SyncTask {
public:
typedef base::Callback<void(scoped_ptr<SyncTaskToken>)> Continuation;
LocalToRemoteSyncer(SyncEngineContext* sync_context,
const SyncFileMetadata& local_metadata,
const FileChange& local_change,
const base::FilePath& local_path,
const storage::FileSystemURL& url);
virtual ~LocalToRemoteSyncer();
virtual void RunPreflight(scoped_ptr<SyncTaskToken> token) OVERRIDE;
const storage::FileSystemURL& url() const { return url_; }
const base::FilePath& target_path() const { return target_path_; }
SyncAction sync_action() const { return sync_action_; }
bool needs_remote_change_listing() const {
return needs_remote_change_listing_;
}
private:
void MoveToBackground(const Continuation& continuation,
scoped_ptr<SyncTaskToken> token);
void ContinueAsBackgroundTask(const Continuation& continuation,
scoped_ptr<SyncTaskToken> token);
void SyncCompleted(scoped_ptr<SyncTaskToken> token,
SyncStatusCode status);
void HandleConflict(scoped_ptr<SyncTaskToken> token);
void HandleExistingRemoteFile(scoped_ptr<SyncTaskToken> token);
void UpdateTrackerForReusedFolder(const FileDetails& details,
scoped_ptr<SyncTaskToken> token);
void DeleteRemoteFile(scoped_ptr<SyncTaskToken> token);
void DidDeleteRemoteFile(scoped_ptr<SyncTaskToken> token,
google_apis::GDataErrorCode error);
void UploadExistingFile(scoped_ptr<SyncTaskToken> token);
void DidUploadExistingFile(scoped_ptr<SyncTaskToken> token,
google_apis::GDataErrorCode error,
const GURL&,
scoped_ptr<google_apis::FileResource>);
void UpdateRemoteMetadata(const std::string& file_id,
scoped_ptr<SyncTaskToken> token);
void DidGetRemoteMetadata(const std::string& file_id,
scoped_ptr<SyncTaskToken> token,
google_apis::GDataErrorCode error,
scoped_ptr<google_apis::FileResource> entry);
void UploadNewFile(scoped_ptr<SyncTaskToken> token);
void DidUploadNewFile(scoped_ptr<SyncTaskToken> token,
google_apis::GDataErrorCode error,
const GURL& upload_location,
scoped_ptr<google_apis::FileResource> entry);
void CreateRemoteFolder(scoped_ptr<SyncTaskToken> token);
void DidCreateRemoteFolder(scoped_ptr<SyncTaskToken> token,
const std::string& file_id,
SyncStatusCode status);
void DidDetachResourceForCreationConflict(scoped_ptr<SyncTaskToken> token,
google_apis::GDataErrorCode error);
bool IsContextReady();
drive::DriveServiceInterface* drive_service();
drive::DriveUploaderInterface* drive_uploader();
MetadataDatabase* metadata_database();
SyncEngineContext* sync_context_;
FileChange local_change_;
bool local_is_missing_;
base::FilePath local_path_;
storage::FileSystemURL url_;
SyncAction sync_action_;
scoped_ptr<FileTracker> remote_file_tracker_;
scoped_ptr<FileTracker> remote_parent_folder_tracker_;
base::FilePath target_path_;
int64 remote_file_change_id_;
bool retry_on_success_;
bool needs_remote_change_listing_;
scoped_ptr<FolderCreator> folder_creator_;
base::WeakPtrFactory<LocalToRemoteSyncer> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(LocalToRemoteSyncer);
};
}
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
0411a9b77c370dfcb612340eddffed78aa2ca211 | 2f27c9cf6adb01663c1e15f1f4751467637e7a7e | /my_idea/[NOT_WORKING_NOW]game_engine_with_concept_in_cpp_20/example_code.cpp | ecfa00538626904804d0fe0ae787733199702519 | [] | no_license | NoaLand/learn_cpp_the_hard_way | 8336c67e14d4d7974726341f6d4876e65fbcdeb8 | f7c5d434c3a917ad8b0b38f09f6a87132d27f059 | refs/heads/master | 2020-09-29T10:35:00.376034 | 2019-12-10T03:20:42 | 2019-12-10T03:20:42 | 227,019,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,916 | cpp | //#include <cstdio>
//#include <type_traits>
//#include <tuple>
////#include <concepts>
//#include <boost/hana.hpp>
//using namespace boost::hana::literals;
//namespace hana = boost::hana;
//
//template<typename T>
//concept SizeConstant = std::convertible_to<T, std::size_t> && requires (T t) {
// { T::value } -> std::convertible_to<std::size_t>;
// std::integral_constant<std::size_t, (std::size_t)T{}>{};
//};
//
//template<typename T>
//concept Node = std::is_object_v<T>;
//
//template<typename T>
//concept TreeLocation = requires (T t, const T ct) {
// { t.isRoot } -> std::convertible_to<bool>;
// t.indices;
// ct.ofChild(0_c);
// requires !T::isRoot || requires {
// { ct.head() } -> std::convertible_to<std::size_t>;
// ct.tail();
// ct.ofParent();
// };
//};
//
//template<std::size_t... indices_>
//struct tree_location {
// static constexpr const bool
// isRoot = sizeof...(indices_) == 0;
//
// std::tuple<std::integral_constant<std::size_t, indices_>...>
// indices;
//
// constexpr tree_location() { }
//
// constexpr tree_location(hana::tuple<hana::size_t<indices_>...>) { }
//
// auto ofParent() const {
// return ::tree_location{hana::drop_back(hana::tuple<hana::size_t<indices_>...>{}, 1_c)};
// }
//
// auto tail() const {
// return ::tree_location{hana::drop_front(hana::tuple<hana::size_t<indices_>...>{}, 1_c)};
// }
//
// constexpr std::size_t head() const {
// return std::get<0>(indices);
// }
//
// auto ofChild(SizeConstant auto index) const {
// return tree_location<indices_..., index>{};
// }
//};
//
//template<typename T>
//concept Tree = requires (T t, tree_location<> location) {
// { t.root } -> Node;
// { T::childCount } -> std::convertible_to<std::size_t>;
// t.subtree(location);
// requires T::childCount == 0ull || requires {
// t.template child<0>();
// t.subtree(tree_location<0>{});
// };
//};
//
//template<typename T>
//concept TreeRef = std::is_reference_v<T> && Tree<std::remove_reference_t<T>>;
//
//template<Node Root_, Tree... Children_>
//struct tree {
// Root_ root;
// std::tuple<Children_...> children;
// static constexpr const SizeConstant auto childCount = hana::size_c<sizeof...(Children_)>;
//
// Tree auto& subtree(TreeLocation auto location) {
// if constexpr (location.isRoot) {
// return *this;
// } else {
// return child<location.head()>().subtree(location.tail());
// }
// }
//
// tree() = default;
//
// tree(std::convertible_to<Root_> auto&& root)
// : root(std::forward<decltype(root)>(root)) {
// static_assert(Tree<tree>);
// }
//
// template<std::size_t index_>
// requires (index_ < sizeof...(Children_))
// Tree auto &child() {
// return std::get<index_>(children);
// }
//};
//
//template<typename T>
//concept Message = std::is_object_v<T>;
//
//template<typename T>
//concept Context = requires (T t) {
// { t.tree } -> TreeRef;
// { t.location } -> TreeLocation;
//};
//
//template<Tree Tree_, TreeLocation TreeLocation_ = tree_location<>>
//struct context {
// Tree_& tree;
// static constexpr const TreeLocation_ location;
//
// context(Tree_ &tree, TreeLocation_ location = TreeLocation_{}): tree{ tree } {
// static_assert(Context<context>);
// }
//
// void sendDown(Message auto message) {
// Tree auto &subtree = tree.subtree(location);
// subtree.childCount.times.with_index(
// [&] (SizeConstant auto index) {
// Node auto &child = subtree.template child<index>().root;
// Context auto childContext = ::context(tree, location.ofChild(index));
// if constexpr (requires { child.handle(message, childContext); }) {
// child.handle(message, childContext);
// } else if constexpr (requires { child.handle(message); }) {
// child.handle(message);
// childContext.sendDown(message);
// } else {
// childContext.sendDown(message);
// }
// }
// );
// }
//
// void sendUp(Message auto message) {
// if constexpr (!location.isRoot) {
// Node auto &parent = tree.subtree(location.ofParent()).root;
// Context auto parentContext = ::context(tree, location.ofParent());
// if constexpr (requires { parent.handle(message, parentContext); }) {
// parent.handle(message, parentContext);
// } else if constexpr (requires { parent.handle(message); }) {
// parent.handle(message);
// parentContext.sendUp(message);
// } else {
// parentContext.sendUp(message);
// }
// }
// }
//};
//
//struct start { };
//
//struct tick { };
//
//struct tock { int data; };
//
//struct idle {
// void handle(Message auto &message) {
// puts(".");
// }
//
// void handle(Message auto &message)
// requires (sizeof(message) > 1) {
// puts("!");
// }
//};
//
//struct tick_tock {
// void handle(const start& message, Context auto context) {
// puts("tick: ");
// context.sendDown(tick{});
// }
//
// void handle(const tock& message) {
// puts("tock!");
// }
//};
//
//struct responder {
// void handle(const tick& message, Context auto context) {
// context.sendUp(tock{});
// }
//};
//
//int main() {
// tree<idle,
// tree<tick_tock,
// tree<idle,
// tree<responder>,
// tree<idle,
// tree<responder>>>>>
// tr;
//
//
// context(tr).sendDown(start{});
//}
| [
""
] | |
63dac574ffa2b54c3d0af05a6d0e226d5a5afbf3 | 8aa26f17244c05ff6f6fbcd8d55eaaad6892b691 | /tensor_rg/tensor_rg.cc | 3b75b4a5d7b835652aa964d01a62224f45262b7f | [] | no_license | jiangshenghan/PEPS_ITENSOR | 6112b0b9cf3222fd4b27366906041b4d793af244 | fec2be0e2e3deee35464c4cee9ad3dee2669101d | refs/heads/master | 2021-01-21T04:47:27.100312 | 2016-05-23T18:07:18 | 2016-05-23T18:07:18 | 45,432,298 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 16,314 | cc |
#include "tensor_svd.h"
#include "tensor_rg.h"
#include <limits>
template <class TensorT>
TensorT_RG<TensorT>::TensorT_RG(const Lattice_Base &lattice, const std::vector<TensorT> &input_tensors, int maxm):
lattice_(lattice),
input_tensors_(input_tensors),
factor_input_tensors_(input_tensors.size(),std::vector<TensorT>(2)),
//factor_args_("Maxm",maxm,"ShowEigs"),
factor_args_("Maxm",maxm),
iszero_(false),
almost_zero_trg_(false)
{
N_layer_=std::round(std::log2(lattice_.n_uc()[0]*lattice_.n_uc()[1]*1./4.))+1;
//TODO: consider case where we get zero tensor
init_to_square_network();
//obtain layered trg_tensors and factor_tensors
for (int layeri=1; layeri<N_layer_; layeri++)
{
//obtain factor tensors of layeri-1
if (iszero_==true)
{
break;
Print(layeri);
}
for (int tensori=0; tensori<layered_trg_tensors_[layeri-1].size(); tensori++) obtain_factor_tensors(layeri-1,tensori);
for (int tensori=0; tensori<layered_trg_tensors_[layeri].size(); tensori++)
{
obtain_trg_tensor(layeri,tensori);
}
}
obtain_trg_result();
}
template
TensorT_RG<ITensor>::TensorT_RG(const Lattice_Base &lattice, const std::vector<ITensor> &input_tensors, int maxm);
template
TensorT_RG<IQTensor>::TensorT_RG(const Lattice_Base &lattice, const std::vector<IQTensor> &input_tensors, int maxm);
template <class TensorT>
void TensorT_RG<TensorT>::init_to_square_network()
{
std::vector<int> lattice_dim=std::vector<int>{lattice_.n_uc()[0],lattice_.n_uc()[1]};
int N_tensors=lattice_dim[0]*lattice_dim[1];
for (int layeri=0; layeri<N_layer_; layeri++)
{
layered_lattice_dim_.push_back(lattice_dim);
layered_trg_tensors_.push_back(std::vector<TensorT>(N_tensors));
layered_trg_tensors_norm_.push_back(std::vector<double>(N_tensors));
layered_factor_tensors_.push_back(std::vector<std::vector<TensorT>>(N_tensors,std::vector<TensorT>(2)));
if ((layeri+1)%2==0) { lattice_dim[0]/=2; lattice_dim[1]/=2; }
N_tensors/=2;
}
//Print(N_layer_);
//Print(layered_lattice_dim_);
//factor input tensors
for (int tensori=0; tensori<input_tensors_.size(); tensori++) obtain_factor_input_tensor(tensori);
//obtain trg tensor of the 0th layer
for (int tensori=0; tensori<layered_trg_tensors_[0].size(); tensori++) obtain_zeroth_layer_trg_tensor(tensori);
}
template
void TensorT_RG<ITensor>::init_to_square_network();
template
void TensorT_RG<IQTensor>::init_to_square_network();
template <class TensorT>
void TensorT_RG<TensorT>::obtain_factor_input_tensor(int input_tensor_no)
{
//we do not need to factor input tensor of square network
if (lattice_.name().find("square")!=std::string::npos) return;
if (lattice_.name().find("kagome normal")!=std::string::npos)
{
auto tensor_coord=lattice_.site_list_to_coord(input_tensor_no);
std::vector<int> neigh_tensors_no;
neigh_tensors_no.push_back(lattice_.site_coord_to_list(tensor_coord[0],tensor_coord[1],(tensor_coord[2]+1)%3));
neigh_tensors_no.push_back(lattice_.site_coord_to_list(tensor_coord[0],tensor_coord[1],(tensor_coord[2]+2)%3));
std::vector<IndexT> tensorA_indices;
for (auto neigh_no: neigh_tensors_no) tensorA_indices.push_back(commonIndex(input_tensors_[input_tensor_no],input_tensors_[neigh_no]));
factor_input_tensors_[input_tensor_no][0]=TensorT(tensorA_indices);
tensor_factor(input_tensors_[input_tensor_no],factor_input_tensors_[input_tensor_no][0],factor_input_tensors_[input_tensor_no][1],{factor_args_,"IndexName",nameint("leg",input_tensor_no)});
//Print(input_tensor_no);
//Print(tensor_coord);
//Print(neigh_tensors_no);
//Print(factor_input_tensors_[input_tensor_no][0].indices());
//Print(factor_input_tensors_[input_tensor_no][1].indices());
}
}
template
void TensorT_RG<ITensor>::obtain_factor_input_tensor(int input_tensor_no);
template
void TensorT_RG<IQTensor>::obtain_factor_input_tensor(int input_tensor_no);
template <class TensorT>
void TensorT_RG<TensorT>::obtain_zeroth_layer_trg_tensor(int tensor_no)
{
if (lattice_.name().find("square")!=std::string::npos)
{
layered_trg_tensors_[0][tensor_no]=input_tensors_[tensor_no];
}
if (lattice_.name().find("kagome normal")!=std::string::npos)
{
int ix=tensor_no%lattice_.n_uc()[0],
iy=tensor_no/lattice_.n_uc()[0];
std::vector<int> utensors_no, dtensors_no;
for (int subi=0; subi<lattice_.n_sites_uc(); subi++) utensors_no.push_back(lattice_.site_coord_to_list(ix,iy,subi));
dtensors_no.push_back(lattice_.site_coord_to_list(ix,iy,0));
dtensors_no.push_back(lattice_.site_coord_to_list(ix,iy-1,1));
dtensors_no.push_back(lattice_.site_coord_to_list(ix-1,iy,2));
//Print(utensors_no);
//Print(dtensors_no);
TensorT utensor=factor_input_tensors_[utensors_no[0]][0],
dtensor=factor_input_tensors_[dtensors_no[0]][1];
for (int subi=1; subi<lattice_.n_sites_uc(); subi++)
{
utensor*=factor_input_tensors_[utensors_no[subi]][0];
dtensor*=factor_input_tensors_[dtensors_no[subi]][1];
}
layered_trg_tensors_[0][tensor_no]=utensor*dtensor;
}
if (layered_trg_tensors_[0][tensor_no].norm()<std::numeric_limits<double>::min())
{
iszero_=true;
//Print(tensor_no);
//Print(layered_trg_tensors_[0][tensor_no].norm());
}
else
{
layered_trg_tensors_norm_[0][tensor_no]=layered_trg_tensors_[0][tensor_no].norm();
layered_trg_tensors_[0][tensor_no]/=layered_trg_tensors_norm_[0][tensor_no];
}
}
template
void TensorT_RG<ITensor>::obtain_zeroth_layer_trg_tensor(int tensor_no);
template
void TensorT_RG<IQTensor>::obtain_zeroth_layer_trg_tensor(int tensor_no);
//TODO: divide trg tensor by some factor to avoid too large or too small singular value
template <class TensorT>
void TensorT_RG<TensorT>::obtain_trg_tensor(int layer_no, int tensor_no)
{
const auto &factor_tensors=layered_factor_tensors_[layer_no-1];
std::vector<int> surr_tensor_inds;
//we should treat even layer and odd layer separately
//for odd layer, the lattice_dim is the same as last layer
//tensors of this layer sit at even plaquette centers of the lattice
if (layer_no%2==1)
{
for (int surri=0; surri<4; surri++) surr_tensor_inds.push_back(site_ind_surr_plaq(plaq_ind_from_odd_layer_tensor_ind(tensor_no,layer_no),surri,layer_no-1));
}
//for even dim, the lattice_dim[i] is 1/2 of the last layer
//assuming the tensor_no coord of this layer is (x,y), then it sits at plaq coord of last layer (2*x,2*y+1)
//tensors of last layer sits at plaquette center around
else
{
std::vector<int> tensor_no_coord=coord_from_ind(tensor_no,layered_lattice_dim_[layer_no]);
//plaquette coord of last layer
int plaq_ind=ind_from_coord({tensor_no_coord[0]*2,tensor_no_coord[1]*2+1},layered_lattice_dim_[layer_no-1]);
for (int surri=0; surri<4; surri++) surr_tensor_inds.push_back(plaq_ind_surr_plaq(plaq_ind,surri,layer_no-1)/2);
}
layered_trg_tensors_[layer_no][tensor_no]=factor_tensors[surr_tensor_inds[0]][1]*factor_tensors[surr_tensor_inds[1]][0]*factor_tensors[surr_tensor_inds[2]][0]*factor_tensors[surr_tensor_inds[3]][1];
if (layered_trg_tensors_[layer_no][tensor_no].norm()<std::numeric_limits<double>::min()) iszero_=true;
else
{
layered_trg_tensors_norm_[layer_no][tensor_no]=layered_trg_tensors_[layer_no][tensor_no].norm();
layered_trg_tensors_[layer_no][tensor_no]/=layered_trg_tensors_norm_[layer_no][tensor_no];
}
//Print(layer_no);
//Print(tensor_no);
//Print(layered_trg_tensors_[layer_no][tensor_no].norm());
//Print(surr_tensor_inds);
//Print(factor_tensors[surr_tensor_inds[0]][1]);
//Print(factor_tensors[surr_tensor_inds[1]][0]);
//Print(factor_tensors[surr_tensor_inds[2]][0]);
//Print(factor_tensors[surr_tensor_inds[3]][1]);
//Print(layered_trg_tensors_[layer_no][tensor_no]);
}
template
void TensorT_RG<ITensor>::obtain_trg_tensor(int layer_no, int tensor_no);
template
void TensorT_RG<IQTensor>::obtain_trg_tensor(int layer_no, int tensor_no);
template <class TensorT>
void TensorT_RG<TensorT>::obtain_factor_tensors(int layer_no, int tensor_no)
{
//we do not need factor tensor of last layer
if (layer_no==N_layer_-1) return;
//get factor inds of first factor tensor
std::vector<IndexT> factor_inds;
std::vector<int> neighs(2);
if (layer_no%2==0)
{
neighs[0]=((tensor_no/layered_lattice_dim_[layer_no][0]+tensor_no%layered_lattice_dim_[layer_no][1])%2==0)?0:2;
neighs[1]=3;
}
else
{
neighs[0]=0;
neighs[1]=(((tensor_no*2)/layered_lattice_dim_[layer_no][0])%2==0)? 3:1;
}
factor_inds.push_back(commonIndex(layered_trg_tensors_[layer_no][tensor_no],layered_trg_tensors_[layer_no][neigh_tensor_ind(tensor_no,neighs[0],layer_no)]));
factor_inds.push_back(commonIndex(layered_trg_tensors_[layer_no][tensor_no],layered_trg_tensors_[layer_no][neigh_tensor_ind(tensor_no,neighs[1],layer_no)]));
layered_factor_tensors_[layer_no][tensor_no][0]=TensorT(factor_inds[0],factor_inds[1]);
tensor_factor(layered_trg_tensors_[layer_no][tensor_no],layered_factor_tensors_[layer_no][tensor_no][0],layered_factor_tensors_[layer_no][tensor_no][1],{factor_args_,"IndexName",nameint("leg",tensor_no)});
//Print(layer_no);
//Print(tensor_no);
//Print(neighs);
//Print(factor_inds);
//Print(neigh_tensor_ind(tensor_no,0,layer_no));
//Print(neigh_tensor_ind(tensor_no,1,layer_no));
//Print(neigh_tensor_ind(tensor_no,2,layer_no));
//Print(neigh_tensor_ind(tensor_no,3,layer_no));
//Print((layered_trg_tensors_[layer_no][tensor_no]-layered_factor_tensors_[layer_no][tensor_no][0]*layered_factor_tensors_[layer_no][tensor_no][1]).norm());
}
template
void TensorT_RG<ITensor>::obtain_factor_tensors(int layer_no, int tensor_no);
template
void TensorT_RG<IQTensor>::obtain_factor_tensors(int layer_no, int tensor_no);
template <class TensorT>
void TensorT_RG<TensorT>::obtain_trg_result()
{
//Print(iszero_);
if (iszero_==true)
{
trg_result_=0;
return;
}
const auto &trg_tensors=layered_trg_tensors_.back();
auto result_tensor=(trg_tensors[0]*trg_tensors[1])*(trg_tensors[2]*trg_tensors[3]);
trg_result_=result_tensor.toComplex();
for (int layer_no=0; layer_no<layered_trg_tensors_.size(); layer_no++)
{
for (double tensor_norm: layered_trg_tensors_norm_[layer_no]) trg_result_*=tensor_norm;
}
//the case where trg_result_ is too small, we need to renormalize tensor
if (std::abs(trg_result_)<std::numeric_limits<double>::min())
{
almost_zero_trg_=true;
}
//Print(trg_result_);
}
template
void TensorT_RG<ITensor>::obtain_trg_result();
template
void TensorT_RG<IQTensor>::obtain_trg_result();
template <class TensorT>
void TensorT_RG<TensorT>::update_trg_network(const std::vector<int> &input_inds, const std::vector<TensorT> &update_input_tensors)
{
//update input tensors as well as zeroth layer
for (int inputi=0; inputi<input_inds.size(); inputi++)
{
input_tensors_[input_inds[inputi]]=update_input_tensors[inputi];
obtain_factor_input_tensor(input_inds[inputi]);
}
std::vector<int> update_inds_curr;
obtain_zeroth_layer_update_inds(update_inds_curr,input_inds);
//Print(input_inds);
//Print(update_inds_curr);
for (int tensor_no: update_inds_curr) obtain_zeroth_layer_trg_tensor(tensor_no);
//update other layers
std::vector<int> update_inds_last=update_inds_curr;
for (int layeri=1; layeri<N_layer_; layeri++)
{
if (iszero_==true) break;
//get updated factor tensors of last layer
obtain_update_inds(update_inds_curr,update_inds_last,layeri);
//Print(update_inds_last);
//Print(update_inds_curr);
for (int tensor_no: update_inds_last) obtain_factor_tensors(layeri-1,tensor_no);
for (int tensor_no: update_inds_curr) obtain_trg_tensor(layeri,tensor_no);
update_inds_last=update_inds_curr;
}
obtain_trg_result();
}
template
void TensorT_RG<ITensor>::update_trg_network(const std::vector<int> &input_inds, const std::vector<ITensor> &update_input_tensors);
template
void TensorT_RG<IQTensor>::update_trg_network(const std::vector<int> &input_inds, const std::vector<IQTensor> &update_input_tensors);
template <class TensorT>
void TensorT_RG<TensorT>::obtain_zeroth_layer_update_inds(std::vector<int> &update_inds, const std::vector<int> &input_inds)
{
if (lattice_.name().find("square")!=std::string::npos) update_inds=input_inds;
if (lattice_.name().find("kagome normal")!=std::string::npos)
{
std::vector<bool> update_status(layered_trg_tensors_[0].size(),false);
for (int ind: input_inds)
{
auto input_coord=lattice_.site_list_to_coord(ind);
std::vector<int> update_sites;
update_sites.push_back(ind_from_coord({input_coord[0],input_coord[1]},layered_lattice_dim_[0]));
if (input_coord[2]==1) update_sites.push_back(ind_from_coord({input_coord[0],input_coord[1]+1},layered_lattice_dim_[0]));
if (input_coord[2]==2) update_sites.push_back(ind_from_coord({input_coord[0]+1,input_coord[1]},layered_lattice_dim_[0]));
for (int sitei: update_sites) update_status[sitei]=true;
}
for (int ind=0; ind<update_status.size(); ind++)
{
if (update_status[ind]==true) update_inds.push_back(ind);
}
}
//Print(input_inds);
//Print(update_inds);
}
template
void TensorT_RG<ITensor>::obtain_zeroth_layer_update_inds(std::vector<int> &update_inds, const std::vector<int> &input_inds);
template
void TensorT_RG<IQTensor>::obtain_zeroth_layer_update_inds(std::vector<int> &update_inds, const std::vector<int> &input_inds);
template <class TensorT>
void TensorT_RG<TensorT>::obtain_update_inds(std::vector<int> &update_inds_curr, const std::vector<int> &update_inds_last, int layer_no)
{
update_inds_curr.clear();
std::vector<bool> update_status(layered_trg_tensors_[layer_no].size(),false);
if (layer_no%2==1)
{
for (int ind: update_inds_last)
{
std::vector<int> plaq_coord=coord_from_ind(ind,layered_lattice_dim_[layer_no-1]);
update_status[plaq_ind_surr_site(ind,(plaq_coord[0]+plaq_coord[1])%2,layer_no-1)/2]=true;
update_status[plaq_ind_surr_site(ind,(plaq_coord[0]+plaq_coord[1])%2+2,layer_no-1)/2]=true;
}
}
else
{
for (int ind : update_inds_last)
{
std::vector<int> plaq_coord=coord_from_ind(plaq_ind_from_odd_layer_tensor_ind(ind,layer_no-1),layered_lattice_dim_[layer_no-1]);
std::vector<int> update_tensor_inds;
if (plaq_coord[1]%2==0)
{
update_tensor_inds.push_back(ind_from_coord({plaq_coord[0]/2,plaq_coord[1]/2},layered_lattice_dim_[layer_no]));
update_tensor_inds.push_back(ind_from_coord({plaq_coord[0]/2,plaq_coord[1]/2-1},layered_lattice_dim_[layer_no]));
}
else
{
update_tensor_inds.push_back(ind_from_coord({plaq_coord[0]/2,plaq_coord[1]/2},layered_lattice_dim_[layer_no]));
update_tensor_inds.push_back(ind_from_coord({plaq_coord[0]/2+1,plaq_coord[1]/2},layered_lattice_dim_[layer_no]));
}
update_status[update_tensor_inds[0]]=true;
update_status[update_tensor_inds[1]]=true;
}
}
for (int ind=0; ind<update_status.size(); ind++)
{
if (update_status[ind]==true) update_inds_curr.push_back(ind);
}
}
template
void TensorT_RG<ITensor>::obtain_update_inds(std::vector<int> &update_inds_curr, const std::vector<int> &update_inds_last, int layer_no);
template
void TensorT_RG<IQTensor>::obtain_update_inds(std::vector<int> &update_inds_curr, const std::vector<int> &update_inds_last, int layer_no);
| [
"jiangshenghan@gmail.com"
] | jiangshenghan@gmail.com |
6fc40e73a2ed641a1eff9588356944289959536a | d931cf4a61277cf7d5db5556daa86358bc19d04e | /Resources/Monopoly Main.cpp | 8f72c4652f77540c13e5d520c9d714eb1102f040 | [] | no_license | Nabeegh-Ahmed/Monopoly-Cpp | e7bcd859586d055841a137a82d1f9c2ba6731d91 | 2a71c014e738c0f8ed0a25e618ac0f489f666118 | refs/heads/master | 2023-02-27T12:58:20.500086 | 2021-01-15T16:57:23 | 2021-01-15T16:57:23 | 263,248,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | cpp | #include <iostream>
#include <SFML/Graphics.hpp>
#include "Cell.h"
#include"Board.h"
#include "PrivateProperty.h"
int PrivateProperty::highestnumberofhotels[7] = {0,0,0,0,0,0,0};
int PrivateProperty::highestnumberofhouses[7] = { 0,0,0,0,0,0,0 };
int PrivateProperty::highestnumberofshops[7] = { 0,0,0,0,0,0,0 };
int main() {
Board game;
game.rungame();
return 0;
} | [
"noreply@github.com"
] | Nabeegh-Ahmed.noreply@github.com |
20d8f861e815038bcb398f625b967480da1bef69 | 8d0c93e7c8611862a1c1dd400e148b34dfbd74ba | /src/rpcprotocol.cpp | 3cf1a4c6a028fd8180a2234d0223b14d39b25517 | [
"MIT"
] | permissive | CyberSensei1/MoonDEXCoin | 2acd4b94252705613410809ebe28b05a33f778f0 | 4fecb2d5544222b46d2093fddace74e24bfe325a | refs/heads/master | 2020-03-18T17:04:47.633236 | 2018-05-20T14:51:11 | 2018-05-20T14:51:11 | 135,004,975 | 0 | 1 | null | 2018-05-27T00:51:32 | 2018-05-27T00:51:31 | null | UTF-8 | C++ | false | false | 3,880 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The MoonDEX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcprotocol.h"
#include "random.h"
#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include "version.h"
#include <stdint.h>
#include <fstream>
using namespace std;
/**
* JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
* but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
* unspecified (HTTP errors and contents of 'error').
*
* 1.0 spec: http://json-rpc.org/wiki/specification
* 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html
*/
string JSONRPCRequest(const string& strMethod, const UniValue& params, const UniValue& id)
{
UniValue request(UniValue::VOBJ);
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return request.write() + "\n";
}
UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const UniValue& id)
{
UniValue reply(UniValue::VOBJ);
if (!error.isNull())
reply.push_back(Pair("result", NullUniValue));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id)
{
UniValue reply = JSONRPCReplyObj(result, error, id);
return reply.write() + "\n";
}
UniValue JSONRPCError(int code, const string& message)
{
UniValue error(UniValue::VOBJ);
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
/** Username used when cookie authentication is in use (arbitrary, only for
* recognizability in debugging/logging purposes)
*/
static const std::string COOKIEAUTH_USER = "__cookie__";
/** Default name for auth cookie file */
static const std::string COOKIEAUTH_FILE = ".cookie";
boost::filesystem::path GetAuthCookieFile()
{
boost::filesystem::path path(GetArg("-rpccookiefile", COOKIEAUTH_FILE));
if (!path.is_complete()) path = GetDataDir() / path;
return path;
}
bool GenerateAuthCookie(std::string *cookie_out)
{
unsigned char rand_pwd[32];
GetRandBytes(rand_pwd, 32);
std::string cookie = COOKIEAUTH_USER + ":" + EncodeBase64(&rand_pwd[0],32);
/** the umask determines what permissions are used to create this file -
* these are set to 077 in init.cpp unless overridden with -sysperms.
*/
std::ofstream file;
boost::filesystem::path filepath = GetAuthCookieFile();
file.open(filepath.string().c_str());
if (!file.is_open()) {
LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath.string());
return false;
}
file << cookie;
file.close();
LogPrintf("Generated RPC authentication cookie %s\n", filepath.string());
if (cookie_out)
*cookie_out = cookie;
return true;
}
bool GetAuthCookie(std::string *cookie_out)
{
std::ifstream file;
std::string cookie;
boost::filesystem::path filepath = GetAuthCookieFile();
file.open(filepath.string().c_str());
if (!file.is_open())
return false;
std::getline(file, cookie);
file.close();
if (cookie_out)
*cookie_out = cookie;
return true;
}
void DeleteAuthCookie()
{
try {
boost::filesystem::remove(GetAuthCookieFile());
} catch (const boost::filesystem::filesystem_error& e) {
LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, e.what());
}
}
| [
""
] | |
64333e15947c5f4dce8fc9b01f2dbd72a0a52415 | 9e520130445d1a37a9ff0df2934a6d32a2d22fd0 | /lib/vortex_lite/include/cpp/mapping/SEQ.h | 0dec4f8d1616b50fc43dd1d8b0cefcc563779d36 | [] | no_license | locke12456/DDS-Sample | 53727b6a562f24d302fa2cee07b81109f312d5af | 46b776ec4ba1fd9bd6325d7e649f1c6e191636fb | refs/heads/master | 2021-01-17T16:02:29.126507 | 2016-08-08T04:13:34 | 2016-08-08T04:13:34 | 64,986,376 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,935 | h | /*
* Vortex Lite
*
* This software and documentation are Copyright 2006 to 2015 PrismTech
* Limited and its licensees. All rights reserved. See file:
*
* $LITE_HOME/LICENSE
*
* for full copyright notice and license terms.
*
*/
#ifndef SACPP_MAPPING_SEQ_H
#define SACPP_MAPPING_SEQ_H
#include "cpp_dcps_if.h"
template <class T> class DDS_DCPSSequence_var
{
public:
DDS_DCPSSequence_var () : m_ptr (NULL) {}
DDS_DCPSSequence_var (T * p) : m_ptr (p) {}
DDS_DCPSSequence_var (const DDS_DCPSSequence_var<T> & that)
{
m_ptr = (that.m_ptr) ? new T (*(that.m_ptr)) : NULL;
}
~DDS_DCPSSequence_var () { delete m_ptr; }
DDS_DCPSSequence_var<T> & operator = (T * p)
{
delete m_ptr;
m_ptr = p;
return *this;
}
DDS_DCPSSequence_var<T> & operator =
(
const DDS_DCPSSequence_var<T> & that
)
{
if (this != &that)
{
delete m_ptr;
m_ptr = (that.m_ptr) ? new T (*(that.m_ptr)) : NULL;
}
return *this;
}
typename T::_subscript_type operator [] (DDS::ULong index)
{
assert (m_ptr);
return m_ptr->operator[] (index);
}
typename T::_const_subscript_type operator [] (DDS::ULong index) const
{
assert (m_ptr);
return ((const T *)m_ptr)->operator[] (index);
}
typename T::_subscript_type operator [] (int index)
{
assert (m_ptr);
assert (index >= 0);
return m_ptr->operator[] (index);
}
T * operator -> () { return m_ptr; }
operator T & () { return *m_ptr; }
operator const T & () const { return *m_ptr; }
operator T * () { return m_ptr; }
operator const T * () const { return m_ptr; }
const T & in () const { return *m_ptr; }
T & inout () { return *m_ptr; }
T *& val () { return m_ptr; }
T *& out ()
{
delete m_ptr;
m_ptr = NULL;
return m_ptr;
}
T * _retn ()
{
T * ret = m_ptr;
m_ptr = NULL;
return ret;
}
public:
T * m_ptr;
};
template <class T> class DDS_DCPSSequence_out
{
public:
DDS_DCPSSequence_out (T *& p) : m_ptr (p) {}
DDS_DCPSSequence_out (DDS_DCPSSequence_var<T> & v)
: m_ptr (v.m_ptr)
{
delete m_ptr;
}
DDS_DCPSSequence_out (const DDS_DCPSSequence_out<T> & v)
: m_ptr (v.m_ptr)
{}
DDS_DCPSSequence_out<T>& operator=(T * p)
{
m_ptr = p;
return *this;
}
typename T::_subscript_type operator [] (DDS::ULong index)
{
assert (m_ptr);
return m_ptr->operator[] (index);
}
typename T::_subscript_type operator [] (int index)
{
assert (m_ptr);
assert (index >= 0);
return m_ptr->operator[] (index);
}
T * operator -> () { return m_ptr; }
T *& out () { return m_ptr; }
operator T * () const { return m_ptr; }
public:
T *& m_ptr;
};
#undef OS_API
#endif /* SACPP_MAPPING_SEQ_H */
| [
"locke.chen@adlinktech.com"
] | locke.chen@adlinktech.com |
7e80b3ec7df1ddbe0178aeb692bae11a46bd2954 | e6c80d747be1496b9c0ebcc8a8bc33bd64eb17dd | /Codes/C++ Programs/11Numerical_Problems/C++ Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach.cpp | 2572098935f799e778f5bec1bc8696f9341e674a | [] | no_license | developersbk/Universal_Code_Snippets | 56b25fb43cc2c67113e97e691cc48f8a0b0193f6 | 0001535476a5743c0557c5ce2c3ffc13c6ee8791 | refs/heads/master | 2023-02-24T08:16:57.240264 | 2020-02-29T01:21:46 | 2020-02-29T01:21:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,999 | cpp | /*This is a C++ Program to perform Fast Fourier Transform. A fast Fourier transform (FFT) is an algorithm to compute the discrete Fourier transform (DFT) and its inverse. Fourier analysis converts time (or space) to frequency and vice versa; an FFT rapidly computes such transformations by factorizing the DFT matrix into a product of sparse (mostly zero) factors.*/
#include <iostream>
#include <complex>
#include <cmath>
#include <iterator>
using namespace std;
unsigned int bitReverse(unsigned int x, int log2n)
{
int n = 0;
int mask = 0x1;
for (int i = 0; i < log2n; i++)
{
n <<= 1;
n |= (x & 1);
x >>= 1;
}
return n;
}
const double PI = 3.1415926536;
template<class Iter_T>
void fft(Iter_T a, Iter_T b, int log2n)
{
typedef typename iterator_traits<iter_t>::value_type complex;
const complex J(0, 1);
int n = 1 << log2n;
for (unsigned int i = 0; i < n; ++i)
{
b[bitReverse(i, log2n)] = a[i];
}
for (int s = 1; s <= log2n; ++s)
{
int m = 1 << s;
int m2 = m >> 1;
complex w(1, 0);
complex wm = exp(-J * (PI / m2));
for (int j = 0; j < m2; ++j)
{
for (int k = j; k < n; k += m)
{
complex t = w * b[k + m2];
complex u = b[k];
b[k] = u + t;
b[k + m2] = u - t;
}
w *= wm;
}
}
}
int main(int argc, char **argv)
{
typedef complex cx;
cx a[] = { cx(0, 0), cx(1, 1), cx(3, 3), cx(4, 4), cx(4, 4), cx(3, 3), cx(
1, 1), cx(0, 0)
};
cx b[8];
fft(a, b, 3);
for (int i = 0; i < 8; ++i)
cout << b[i] << "\n";
}
/*
(16,16)
(-4.82843,-11.6569)
(0,0)
(-0.343146,0.828427)
(0,0)
(0.828427,-0.343146)
(0,0)
(-11.6569,-4.82843) | [
"sbkannath1996@gmail.com"
] | sbkannath1996@gmail.com |
aafb642a3dc6b3c528caec946410526f97845bfa | 97e53e8028ffb9d3f736a0999cc470f9942ddcd0 | /10 打印与报表技术/01 基 础 打 印/003 打印对话框及其控件中的数据-例1/PrintForm/fields.h | 13194c679c77699b998054eddc157ea622e653db | [] | no_license | BambooMa/VC_openSource | 3da1612ca8285eaba9b136fdc2c2034c7b92f300 | 8c519e73ef90cdb2bad3de7ba75ec74115aab745 | refs/heads/master | 2021-05-14T15:22:10.563149 | 2017-09-11T07:59:18 | 2017-09-11T07:59:18 | 115,991,286 | 1 | 0 | null | 2018-01-02T08:12:01 | 2018-01-02T08:12:00 | null | UTF-8 | C++ | false | false | 1,302 | h | #if !defined(AFX_FIELDS_H__D70F2203_B428_4084_9256_D18D3169EEB8__INCLUDED_)
#define AFX_FIELDS_H__D70F2203_B428_4084_9256_D18D3169EEB8__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
// Dispatch interfaces referenced by this interface
class CField;
/////////////////////////////////////////////////////////////////////////////
// CFields wrapper class
class CFields : public COleDispatchDriver
{
public:
CFields() {} // Calls COleDispatchDriver default constructor
CFields(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CFields(const CFields& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Attributes
public:
// Operations
public:
long GetCount();
void Refresh();
CField GetItem(const VARIANT& Index);
void Append(LPCTSTR Name, long Type, long DefinedSize, long Attrib);
void Delete(const VARIANT& Index);
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_FIELDS_H__D70F2203_B428_4084_9256_D18D3169EEB8__INCLUDED_)
| [
"xiaohuh421@qq.com"
] | xiaohuh421@qq.com |
e9184bb19125f25e8523aface55605608f198b7c | b7fbdc757002d64012574f4fb1fb8deb5d3fed0b | /source/TestList.cpp | 62dd61d1b3cabc00b5f000176bb67c99039fdcd4 | [
"MIT"
] | permissive | Nicola20/programmiersprachen-aufgabenblatt-4 | 5dabe7a0d149ad0fb39613810481c2b7d4184d52 | 76bd288e8f476fa2db4d49055ac54a03ade8e2df | refs/heads/master | 2020-03-19T00:00:48.992616 | 2018-06-10T18:20:18 | 2018-06-10T18:20:18 | 135,446,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,589 | cpp | #define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "List.hpp"
#include <iostream>
#include <vector>
TEST_CASE ("list_default_constructor","[default]")
{
List <int> list1;
REQUIRE (list1.empty() == true);
REQUIRE (list1.size() == 0);
}
TEST_CASE ("list_push_front","[push_front]")
{
List <int> list1;
list1.push_front(6);
REQUIRE (list1.empty() == false);
REQUIRE (list1.size() == 1);
REQUIRE (list1.front() == 6);
list1.push_front(7);
REQUIRE (list1.front() == 7);
}
TEST_CASE ("list_pop_back","[pop_back]")
{
List <int> list1;
list1.push_back(6);
list1.push_front(4);
list1.push_front(1);
REQUIRE (list1.empty() == false);
REQUIRE (list1.size() == 3);
REQUIRE (list1.back() == 6);
list1.pop_back();
//std::cout<<list1.back();
REQUIRE (list1.back() == 4);
}
TEST_CASE ("list_pop_front","[pop_front]")
{
List <int> list1;
list1.push_back(6);
list1.push_front(4);
list1.push_front(1);
REQUIRE (list1.empty() == false);
REQUIRE (list1.size() == 3);
REQUIRE (list1.front() == 1);
list1.pop_front();
REQUIRE (list1.front() == 4);
}
TEST_CASE ("list_push_back","[push_back]")
{
List <int> list1;
list1.push_back(6);
REQUIRE (list1.empty() == false);
REQUIRE (list1.size() == 1);
REQUIRE (list1.back() == 6);
list1.push_back(7);
REQUIRE (list1.back() == 7);
}
TEST_CASE ("list_back()","[back]")
{
List <int> list1;
list1.push_back(6);
list1.push_back(9);
REQUIRE (list1.back() == 9);
}
TEST_CASE ("list_front()","[front]")
{
List <int> list1;
list1.push_front(9);
list1.push_front(6);
REQUIRE (list1.front() == 6);
}
TEST_CASE ("should be empty after clearing","[modifiers]")
{
List <int> list;
list.push_front(42);
list.push_front(41);
list.push_front(4);
list.push_front(1);
list.push_front(31);
list.push_front(18);
list.clear();
REQUIRE (list.size() == 0);
}
TEST_CASE ("should be an empty range after default construction","[iterators]")
{
List <int> list;
auto b = list.begin();
auto e = list.end();
REQUIRE (b == e);
}
TEST_CASE ("provide access to the first element with begin","[iterators]")
{
List <int> list;
list.push_front(42);
REQUIRE (42 == *list.begin());
}
TEST_CASE ("check if listelements are equal","[list_operator]")
{
List <int> list;
list.push_front(42);
list.push_front(41);
list.push_front(4);
list.push_front(1);
list.push_front(31);
list.push_front(18);
List <int> list2;
list2.push_front(42);
list2.push_front(41);
list2.push_front(4);
list2.push_front(1);
list2.push_front(31);
list2.push_front(18);
List <int> list3;
list3.push_front(42);
list3.push_front(41);
list3.push_front(44);
list3.push_front(1);
list3.push_front(7);
list3.push_front(18);
REQUIRE (operator==(list,list2) == true);
REQUIRE (operator==(list,list3) == false);
}
TEST_CASE ("check if listelements are unequal","[list_operator]")
{
List <int> list;
list.push_front(42);
list.push_front(41);
list.push_front(4);
list.push_front(1);
list.push_front(31);
list.push_front(18);
List <int> list2;
list2.push_front(42);
list2.push_front(41);
list2.push_front(4);
list2.push_front(1);
list2.push_front(31);
list2.push_front(18);
List <int> list3;
list3.push_front(42);
list3.push_front(41);
list3.push_front(44);
list3.push_front(1);
list3.push_front(7);
list3.push_front(18);
REQUIRE (operator!=(list,list2) == false);
REQUIRE (operator!=(list,list3) == true);
}
TEST_CASE ("copy constructor","[constructor]")
{
List <int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List <int> list2{list};
REQUIRE (list == list2);
}
TEST_CASE ("move constructor","[constructor]")
{
List <int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List <int> list2 = std::move(list);
REQUIRE (0 == list.size());
REQUIRE (list.empty());
REQUIRE (4 == list2.size());
}
TEST_CASE ("reverse list itself","[reverse]")
{
List <int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List <int> list2;
list2.push_front(4);
list2.push_front(3);
list2.push_front(2);
list2.push_front(1);
list.reverse();
REQUIRE (list2 == list);
}
TEST_CASE ("reverse list and save in new list","[reverse]")
{
List <int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List <int> list2;
list2.push_front(4);
list2.push_front(3);
list2.push_front(2);
list2.push_front(1);
reverse(list);
REQUIRE (list2 == reverse(list));
} //Funzt alles bis auf Move Constructor
TEST_CASE ("add an element with insert ", "[Aufg. 4.9]")
{
List <int> list;
list.push_front(4);
list.push_front(2);
list.push_front(6);
auto e = list.begin(); //list now: 624
REQUIRE (*e == 6);
REQUIRE (list.size() == 3);
list.insert(list.begin(),9); //Add at the front
auto h = list.begin(); //list now: 9624
REQUIRE (*h == 9);
REQUIRE (list.size() == 4);
list.insert(list.end(),1); //Add at the place of the last node
auto g = list.begin(); //list now: 96214
REQUIRE (*g == 9);
REQUIRE (list.size() == 5);
auto i = list.begin();
++i;
++i; //i = 3
list.insert(i,7);
auto k = list.begin(); //list now: 9672143
REQUIRE (*k == 9);
REQUIRE (list.size() == 6);
}
TEST_CASE ("pre- and postincrement ", "[increment]")
{
List <int> list;
list.push_front(8);
list.push_front(9);
list.push_front(5);
list.push_front(6);
auto b = list.begin();
auto e = list.end();
REQUIRE (*b == 6); //>6 5 9 8 erster Wert
REQUIRE (*(++b) == 5); // 6>5 9 8 wird erhöht und neuer Knoten wird ausgegeben
REQUIRE (*(b++) == 5); // 6 5>9 8 wird erhöht und alter Wert wird ausgegeben
REQUIRE (*(++b) == 8); // 6 5 9>8 wird erhöht und neuer Knoten wird ausgegeben
REQUIRE ((++b) == nullptr); // 6 5 9 8> wird erhöht und nullptr wird ausgegeben
REQUIRE (*e == 8); // 6 5 9 8< letzter Wert
REQUIRE (*(e++) == 8); // 6 5 9 8 < wird erhöht und alter Wert wird ausgegeben
REQUIRE (e == nullptr); // 6 5 9 8 < nullptr wird ausgegeben
} //bis hierher funzt alles
TEST_CASE ("List in Vector ", "[Aufg. 4.11]")
{
List <int> list;
list.push_front(3);
list.push_front(9);
list.push_front(7);
list.push_front(6);
std::vector<int> v (list.size());
std::copy(list.begin(), list.bend(), std::begin(v));
REQUIRE (v[0] == 6);
REQUIRE (v[1] == 7);
REQUIRE (v[2] == 9);
REQUIRE (v[3] == 3);
}
int main(int argc, char* argv[]) {
return Catch::Session().run(argc, argv);
}
| [
"nicola.lea.libera@uni-weimar.de"
] | nicola.lea.libera@uni-weimar.de |
bae539a8688c1be50fee34af40c43f96f4885460 | e765bf650d7f5795ae1af2eab5e3434cdf381b36 | /Source/Atomic/IO/Deserializer.h | 67495d7fe1567b9f0774e849e33d40e26904c349 | [
"BSD-3-Clause",
"Zlib",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-khronos",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MIT",
"NTP",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | UNIVERSAL-IT-SYSTEMS/AtomicGameEngine | 97e1619a8b98eda27c2fa064c0d8d8d07b85689f | c3378db3fb93933c46a5a9189b40d6057e210c44 | refs/heads/master | 2021-01-15T15:00:12.897967 | 2016-07-27T23:06:34 | 2016-07-27T23:06:34 | 64,393,855 | 0 | 1 | null | 2016-07-28T12:31:06 | 2016-07-28T12:31:06 | null | UTF-8 | C++ | false | false | 4,808 | h | //
// Copyright (c) 2008-2015 the Urho3D project.
//
// 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.
//
#pragma once
#include "../Core/Variant.h"
#include "../Math/BoundingBox.h"
#include "../Math/Rect.h"
namespace Atomic
{
/// Abstract stream for reading.
class ATOMIC_API Deserializer
{
public:
/// Construct with zero size.
Deserializer();
/// Construct with defined size.
Deserializer(unsigned size);
/// Destruct.
virtual ~Deserializer();
/// Read bytes from the stream. Return number of bytes actually read.
virtual unsigned Read(void* dest, unsigned size) = 0;
/// Set position from the beginning of the stream.
virtual unsigned Seek(unsigned position) = 0;
/// Return name of the stream.
virtual const String& GetName() const;
/// Return a checksum if applicable.
virtual unsigned GetChecksum();
/// Return current position.
unsigned GetPosition() const { return position_; }
/// Return size.
unsigned GetSize() const { return size_; }
/// Return whether the end of stream has been reached.
bool IsEof() const { return position_ >= size_; }
/// Read a 32-bit integer.
int ReadInt();
/// Read a 16-bit integer.
short ReadShort();
/// Read an 8-bit integer.
signed char ReadByte();
/// Read a 32-bit unsigned integer.
unsigned ReadUInt();
/// Read a 16-bit unsigned integer.
unsigned short ReadUShort();
/// Read an 8-bit unsigned integer.
unsigned char ReadUByte();
/// Read a bool.
bool ReadBool();
/// Read a float.
float ReadFloat();
/// Read a double.
double ReadDouble();
/// Read an IntRect.
IntRect ReadIntRect();
/// Read an IntVector2.
IntVector2 ReadIntVector2();
/// Read a Rect.
Rect ReadRect();
/// Read a Vector2.
Vector2 ReadVector2();
/// Read a Vector3.
Vector3 ReadVector3();
/// Read a Vector3 packed into 3 x 16 bits with the specified maximum absolute range.
Vector3 ReadPackedVector3(float maxAbsCoord);
/// Read a Vector4.
Vector4 ReadVector4();
/// Read a quaternion.
Quaternion ReadQuaternion();
/// Read a quaternion with each component packed in 16 bits.
Quaternion ReadPackedQuaternion();
/// Read a Matrix3.
Matrix3 ReadMatrix3();
/// Read a Matrix3x4.
Matrix3x4 ReadMatrix3x4();
/// Read a Matrix4.
Matrix4 ReadMatrix4();
/// Read a color.
Color ReadColor();
/// Read a bounding box.
BoundingBox ReadBoundingBox();
/// Read a null-terminated string.
String ReadString();
/// Read a four-letter file ID.
String ReadFileID();
/// Read a 32-bit StringHash.
StringHash ReadStringHash();
/// Read a buffer with size encoded as VLE.
PODVector<unsigned char> ReadBuffer();
/// Read a resource reference.
ResourceRef ReadResourceRef();
/// Read a resource reference list.
ResourceRefList ReadResourceRefList();
/// Read a variant.
Variant ReadVariant();
/// Read a variant whose type is already known.
Variant ReadVariant(VariantType type);
/// Read a variant vector.
VariantVector ReadVariantVector();
/// Read a string vector.
StringVector ReadStringVector();
/// Read a variant map.
VariantMap ReadVariantMap();
/// Read a variable-length encoded unsigned integer, which can use 29 bits maximum.
unsigned ReadVLE();
/// Read a 24-bit network object ID.
unsigned ReadNetID();
/// Read a text line.
String ReadLine();
protected:
/// Stream position.
unsigned position_;
/// Stream size.
unsigned size_;
};
}
| [
"josh@galaxyfarfaraway.com"
] | josh@galaxyfarfaraway.com |
4c5c07074f87cb79408fcbef77d99cd165a88d7e | 20d1c5315595c731a2b0e6846af068e791d0aa2e | /C++17Study/24_declaring_custom_get_n.cpp | ea361a3d0ece2407337699685dfb19c987465ec1 | [] | no_license | WhiteCri/Cpp17Study | 15b71aaad3ce91da279f8461e23e50b43b179d30 | 5d5eb259d63e239fe222a71e7d6b0390d3a2c7f7 | refs/heads/master | 2021-05-21T19:45:18.261239 | 2020-04-06T12:28:58 | 2020-04-06T12:28:58 | 252,775,022 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 784 | cpp | #include <iostream>
struct S {
int n;
std::string s;
float d;
};
class MyClass {
public:
int GetA() const { return a; }
float GetB() const { return b; }
private:
int a;
float b;
};
template <std::size_t I> auto get(MyClass& c) {
if constexpr (I == 0) return c.GetA();
else if constexpr (I == 1) return c.GetB();
}
//specialisations to support tuple-like interface
namespace std {
template <> struct tuple_size<MyClass> : integral_constant<size_t, 2> {};
template <> struct tuple_element<0, MyClass> { using type = int; };
template <> struct tuple_element<1, MyClass> { using type = float; };
}
//or do the template specialisation
//template <> auto& get<0>(MyClass &c) { return c.GetA(); }
int main() {
S s;
auto[a, b, c] = s;
} | [
"sjrnfu12@naver.com"
] | sjrnfu12@naver.com |
a6c3f3376bb5a7401e8607413c9c4bef592d9e29 | 33446d28d95d865b4612b67a6719417833504b5f | /main.cpp | b6769ca3f3e457e676843b713ac66298168f2688 | [] | no_license | AvilMP/Puzzle-game | 5f33f804d1250b06adbe47e489c98972f7279c38 | 2f20202328c56c320b00ffa05a29cad2886d678c | refs/heads/master | 2021-05-18T02:18:34.829702 | 2020-03-29T17:53:03 | 2020-03-29T17:53:03 | 251,062,675 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 2,066 | cpp | #include <iostream>
#include <windows.h>
#include <conio.h> /// getch.
#include "klasy.h"
using namespace std;
int punktacja=0;
int odpowiedz_a;
int odpowiedz_b;
int odpowiedz_c;
int punkty(int odp_a,int odp_b,int odp_c,int obr_a,int obr_b,int obr_c); /// dodaje punkt gdy prawda.
void baner(int nr_etapu); /// wyswietla nazwe programu/gry.
int main()
{
Etap e[10];
for (int i=1; i<=10; i++)
{
baner(i);
Etap e[i]; e[i].losuj();
for (int j=1; j<=3; j++)
{
cout<<" "<<j<<". "; e[i].pokaz(j);
cout<<" ";
}
cout<<endl<<endl;
for (int g=1; g<=3 ; g++)
{
string odp;
if (g==1) odp="1";
else if (g==2) odp="2";
else odp="3";
cout<<" "<<odp<<". ("; e[i].zadaj(g);
cout<<") ";
}
cout<<endl<<endl;
cout<<"Podaj rozwiazanie:"<<endl;
cout<<"Obrazek nr1: ";
cin>>odpowiedz_a;
cout<<endl;
cout<<"Obrazek nr2: ";
cin>>odpowiedz_b;
cout<<endl;
cout<<"Obrazek nr3: ";
cin>>odpowiedz_c;
cout<<endl;
punkty(odpowiedz_a, odpowiedz_b, odpowiedz_c, e[i].obrazek_a, e[i].obrazek_b, e[i].obrazek_c);
system("cls");
if (i==10) break;
}
baner(10);
cout<<" Twoje punkty to: "<<punktacja<<endl;
return 0;
}
int punkty(int odp_a,int odp_b,int odp_c,int obr_a,int obr_b,int obr_c) /// sprawdza opowiedzi i przyznaje punkty.
{
if ((odp_a==obr_a)&&(odp_b==obr_b)&&(odp_c==obr_c)) return punktacja++;
else return 0;
}
void baner(int nr_etapu)
{
cout<<"Etap "<<nr_etapu<<" z 10 "<<"~~~~Hello Puzzle~~~~"<<" Punkty: "<<punktacja<<endl<<endl;
cout<<"Podaj wartosci A,B lub C wpisujac liczby w prawidłowej kolejosci na podstawie grafik ;)";
cout<<endl<<endl;
}
| [
"noreply@github.com"
] | AvilMP.noreply@github.com |
a7c8d8270be8679c09be6a6d44ba6c8e5567526e | e814880c737bc67fb21d372b1a8aad1665e7fc4a | /data_process/Depth2HHA/utils/depth_features/rgbdutils/imagestack/src/Calculus.h | 5645dee986e1bd975d9c8727eabf91bd1eadfa08 | [
"BSD-2-Clause",
"CC0-1.0",
"LicenseRef-scancode-proprietary-license"
] | permissive | rgvillanueva28/CVPR21Chal-SLR | 8ae74aa411ac3a3ee68e049ffa7e780c4ab5b569 | 465e3df69381c5740dae8682a76bbee06de2c5f8 | refs/heads/main | 2023-04-03T13:22:54.589426 | 2021-03-29T05:26:29 | 2021-03-29T05:26:29 | 353,712,728 | 0 | 0 | CC0-1.0 | 2021-04-01T15:07:10 | 2021-04-01T13:39:43 | null | UTF-8 | C++ | false | false | 836 | h | #ifndef IMAGESTACK_CALCULUS_H
#define IMAGESTACK_CALCULUS_H
#include "header.h"
class Gradient : public Operation {
public:
void help();
void parse(vector<string> args);
static void apply(Window im, string dimensions);
static void apply(Window im, char dimension);
};
class Integrate : public Operation {
public:
void help();
void parse(vector<string> args);
static void apply(Window im, string dimensions);
static void apply(Window im, char dimension);
};
class GradMag : public Operation {
public:
void help();
void parse(vector<string> args);
static Image apply(Window im);
};
class Poisson : public Operation {
public:
void help();
void parse(vector<string> args);
static Image apply(Window dx, Window dy, float termination = 0.01);
};
#include "footer.h"
#endif
| [
"jiangsongyao@gmail.com"
] | jiangsongyao@gmail.com |
3b8d2c5befaee3951286480e4ada71bebdb640b4 | 06b79cef6b3425db3c5b39dd727f4d1a48a99efb | /74_Search_a_2D_Matrix.cpp | ab545d8fd741f085def6746ad34d119b35bb10b8 | [] | no_license | YinJingcao/lc | f05a8859a8af442a7ab2c589e4447d94894d2d8a | adc7561693c3638bb438aeb0838b4b9901abb0ef | refs/heads/master | 2021-09-14T14:34:19.850971 | 2018-05-15T05:06:17 | 2018-05-15T05:06:17 | 124,845,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,023 | cpp | /**
* @file 74_Search_a_2D_Matrix.cpp
* @author yinjingcao
* @date 2018/03/28 19:28:22
* @version $Revision$
* @brief
*
**/
class Solution {
public:
bool searchMatrix(vector<vector<int> >& matrix, int target) {
if (matrix.empty()) return false;
int xlen = matrix.size();
int ylen = matrix[0].size();
return find(matrix, xlen, ylen, 0, xlen * ylen - 1, target);
}
private:
bool find(vector<vector<int> >& matrix, int xlen, int ylen, int left, int right, int target) {
if (left > right) {
return false;
}
int mid = (left + right) / 2;
int mid_x = mid / ylen;
int mid_y = mid % ylen;
if (matrix[mid_x][mid_y] < target) {
return find(matrix, xlen, ylen, mid + 1, right, target);
} else if (matrix[mid_x][mid_y] > target) {
return find(matrix, xlen, ylen, left, mid - 1, target);
} else {
return true;
}
}
};
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| [
"yinjingcao@baidu.com"
] | yinjingcao@baidu.com |
fb7fe68232692bb14ef750748a1c3cae60f349f8 | de1acc8927bfcd72856e2d432b3cbe6ff458a62f | /HashEntry.h | d827000049b349bba09740777c92ef28be5e3b85 | [] | no_license | yoonsz25/project3 | fd7641151229d1e3158047865d3b76f953086123 | ef17bc5f87983b2a26fd97c31286e2d37983a825 | refs/heads/master | 2021-01-10T01:08:36.769046 | 2016-03-14T15:04:11 | 2016-03-14T15:04:11 | 52,417,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | h | #ifndef __HASHENTRY_H__
#define __HASHENTRY_H__
#include <string>
#include <list>
#include <vector>
class HashEntry{
friend class AdList;
private:
std::string name;
int dataPointer;
std::list<std::string> friends;
public:
HashEntry():name("!") , dataPointer(-1) {};
std::string getName(){return this->name;}
int getDataPtr(){return this->dataPointer;}
std::list<std::string> getList(){return this->friends;}
void printFriends();
std::vector<std::string> getFriends();
};
#endif
| [
"yoonsz25@yahoo.com"
] | yoonsz25@yahoo.com |
5d44bc212078f2e6e20123875bfb3590f6f6688f | 050c28c06a8475c4ff9289ee0c3b415a7576bc61 | /Runtime/RHI/D3D11/D3D11_RasterizerState.cpp | 25dc473d1b5033d5f88b12a209e07c368b5fb720 | [
"MIT"
] | permissive | Michael-Lfx/SpartanEngine | 4746b9f94c93b25858ec096dfe71746e450ec619 | 146c6f6c715f1efbbfeaf09b6e3e17067c1d911c | refs/heads/master | 2023-05-30T12:18:22.344468 | 2021-06-15T17:40:28 | 2021-06-15T17:40:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,807 | cpp | /*
Copyright(c) 2016-2021 Panos Karabelas
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.
*/
//= INCLUDES ======================
#include "Spartan.h"
#include "../RHI_Implementation.h"
#include "../RHI_RasterizerState.h"
#include "../RHI_Device.h"
//=================================
//= NAMESPACES =====
using namespace std;
//==================
namespace Spartan
{
RHI_RasterizerState::RHI_RasterizerState
(
const shared_ptr<RHI_Device>& rhi_device,
const RHI_Cull_Mode cull_mode,
const RHI_Fill_Mode fill_mode,
const bool depth_clip_enabled,
const bool scissor_enabled,
const bool antialised_line_enabled,
const float depth_bias /*= 0.0f */,
const float depth_bias_clamp /*= 0.0f */,
const float depth_bias_slope_scaled /*= 0.0f */,
const float line_width /*= 1.0f */)
{
if (!rhi_device)
{
LOG_ERROR_INVALID_INTERNALS();
return;
}
if (!rhi_device->GetContextRhi()->device)
{
LOG_ERROR_INVALID_INTERNALS();
return;
}
// Save properties
m_cull_mode = cull_mode;
m_fill_mode = fill_mode;
m_depth_clip_enabled = depth_clip_enabled;
m_scissor_enabled = scissor_enabled;
m_antialised_line_enabled = antialised_line_enabled;
m_depth_bias = depth_bias;
m_depth_bias_clamp = depth_bias_clamp;
m_depth_bias_slope_scaled = depth_bias_slope_scaled;
m_line_width = line_width;
// Create rasterizer description
D3D11_RASTERIZER_DESC desc = {};
desc.CullMode = d3d11_cull_mode[cull_mode];
desc.FillMode = d3d11_polygon_mode[fill_mode];
desc.FrontCounterClockwise = false;
desc.DepthBias = static_cast<UINT>(Math::Helper::Floor(depth_bias * (float)(1 << 24)));
desc.DepthBiasClamp = depth_bias_clamp;
desc.SlopeScaledDepthBias = depth_bias_slope_scaled;
desc.DepthClipEnable = depth_clip_enabled;
desc.MultisampleEnable = false;
desc.AntialiasedLineEnable = antialised_line_enabled;
desc.ScissorEnable = scissor_enabled;
// Create rasterizer state
auto rasterizer_state = static_cast<ID3D11RasterizerState*>(m_buffer);
m_initialized = d3d11_utility::error_check(rhi_device->GetContextRhi()->device->CreateRasterizerState(&desc, reinterpret_cast<ID3D11RasterizerState**>(&m_buffer)));
}
RHI_RasterizerState::~RHI_RasterizerState()
{
d3d11_utility::release(*reinterpret_cast<ID3D11RasterizerState**>(&m_buffer));
}
}
| [
"PanosConroe@hotmail.com"
] | PanosConroe@hotmail.com |
aa44bd552da1325dd573aed7018ce0b159817be6 | 25abd807ca135a5c268255515f6d493c229903be | /cppwinrt/impl/Windows.Media.Ocr.1.h | ecc4c60de2b5ea807356f3b5a232940dc369e2a9 | [
"Apache-2.0"
] | permissive | RakeshShrestha/C-Calendar-Library | 670924ae3204d8737d8f43c47e54fe113d202265 | 6525707089891b0710e34769f7aeaea0c79271a1 | refs/heads/master | 2022-05-16T15:26:37.102822 | 2022-04-28T08:45:58 | 2022-04-28T08:45:58 | 33,488,761 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,935 | h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200117.5
#ifndef WINRT_Windows_Media_Ocr_1_H
#define WINRT_Windows_Media_Ocr_1_H
#include "winrt/impl/Windows.Media.Ocr.0.h"
WINRT_EXPORT namespace winrt::Windows::Media::Ocr
{
struct __declspec(empty_bases) IOcrEngine :
Windows::Foundation::IInspectable,
impl::consume_t<IOcrEngine>
{
IOcrEngine(std::nullptr_t = nullptr) noexcept {}
IOcrEngine(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IOcrEngineStatics :
Windows::Foundation::IInspectable,
impl::consume_t<IOcrEngineStatics>
{
IOcrEngineStatics(std::nullptr_t = nullptr) noexcept {}
IOcrEngineStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IOcrLine :
Windows::Foundation::IInspectable,
impl::consume_t<IOcrLine>
{
IOcrLine(std::nullptr_t = nullptr) noexcept {}
IOcrLine(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IOcrResult :
Windows::Foundation::IInspectable,
impl::consume_t<IOcrResult>
{
IOcrResult(std::nullptr_t = nullptr) noexcept {}
IOcrResult(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IOcrWord :
Windows::Foundation::IInspectable,
impl::consume_t<IOcrWord>
{
IOcrWord(std::nullptr_t = nullptr) noexcept {}
IOcrWord(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
}
#endif
| [
"rakesh.shrestha@gmail.com"
] | rakesh.shrestha@gmail.com |
8a1bc23184a856f6426d70946c52a63bd1905714 | c6fdcad61d7d4fcea4a1822be3cce5c46ad2ec48 | /include/klee/Internal/Support/Timer.h | d38844beac9886fda58a998da23b1907a32a43eb | [
"NCSA",
"Apache-2.0"
] | permissive | LoongWalker/kontest | bae8daf80fd8814e98a31f6f003648c7bbd275c6 | aded3bb716d0dc7cb5b531c93b0754a2d69f2e53 | refs/heads/master | 2022-01-14T20:16:43.318133 | 2019-06-21T09:55:11 | 2019-06-21T09:55:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | h | //===-- Timer.h -------------------------------------------------*- C++ -*-===//
//
// The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef KLEE_TIMER_H
#define KLEE_TIMER_H
#include "llvm/Support/TimeValue.h"
#include <stdint.h>
namespace klee {
class WallTimer {
llvm::sys::TimeValue::SecondsType startSeconds;
int_fast32_t startNanos;
public:
WallTimer();
/// check - Return the delta since the timer was created, in microseconds.
uint64_t check();
};
}
#endif
| [
"rjoshi@rjoshi.org"
] | rjoshi@rjoshi.org |
0438dd7854bb40334407ef16a2c8cf9e610547c8 | 5988ea61f0a5b61fef8550601b983b46beba9c5d | /3rd/ACE-5.7.0/ACE_wrappers/tests/Process_Env_Test.cpp | 1a85347d986a5537595db3792c093abbdc7b615f | [
"MIT"
] | permissive | binghuo365/BaseLab | e2fd1278ee149d8819b29feaa97240dec7c8b293 | 2b7720f6173672efd9178e45c3c5a9283257732a | refs/heads/master | 2016-09-15T07:50:48.426709 | 2016-05-04T09:46:51 | 2016-05-04T09:46:51 | 38,291,364 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,592 | cpp | // $Id: Process_Env_Test.cpp 83346 2008-10-21 14:15:38Z sma $
// ============================================================================
//
// = LIBRARY
// tests
//
// = FILENAME
// Process_Env_Test.cpp
//
// = DESCRIPTION
// This program tests the limits of the Windows CreateProcess
// environment buffer.
//
// = AUTHOR
// Chad Elliott <elliott_c@ociweb.com>
//
// ============================================================================
#include "test_config.h"
#include "ace/Process.h"
#include "ace/SString.h"
ACE_RCSID(tests,
Process_Env_Test,
"$Id: Process_Env_Test.cpp 83346 2008-10-21 14:15:38Z sma $")
typedef void (*setenvfn_t) (const ACE_TCHAR *name, const ACE_TCHAR *value,
void *ctx);
#if defined (ACE_WIN32) && !defined (ACE_USES_WCHAR) && !defined (ACE_HAS_WINCE)
void create_large_env (setenvfn_t setenv, void *ctx)
{
static const size_t varsize = 1200;
for (int i = 0; i < 26; i++)
{
char name[2] = { 'A' + i, '\0' };
char value[varsize];
ACE_OS::memset (value, 'R', varsize);
value[varsize - 1] = '\0';
setenv (ACE_TEXT_CHAR_TO_TCHAR (name),
ACE_TEXT_CHAR_TO_TCHAR (value),
ctx);
}
}
void apo_setenv (const ACE_TCHAR *name, const ACE_TCHAR *value, void *ctx)
{
ACE_Process_Options *apo = static_cast<ACE_Process_Options *> (ctx);
apo->setenv (name, value);
}
void thisproc_setenv (const ACE_TCHAR *name, const ACE_TCHAR *value, void *)
{
ACE_TString putstr (name);
putstr += ACE_TEXT ('=');
putstr += value;
ACE_OS::putenv (putstr.c_str ());
}
#endif
int
run_main (int, ACE_TCHAR*[])
{
int test_status = 0;
ACE_START_TEST (ACE_TEXT ("Process_Env_Test"));
#if defined (ACE_WIN32) && !defined (ACE_USES_WCHAR) && !defined (ACE_HAS_WINCE)
ACE_Process_Options options (
0,
ACE_Process_Options::DEFAULT_COMMAND_LINE_BUF_LEN,
32 * 1024);
options.command_line (ACE_TEXT ("attrib.exe /?"));
create_large_env (apo_setenv, &options);
ACE_OS::fclose(stdout);
ACE_Process process;
if (process.spawn (options) != -1)
{
ACE_ERROR ((LM_DEBUG,
"ERROR: This should have failed due to the large "
"environment buffer\n"));
test_status = 1;
}
options.enable_unicode_environment ();
if (process.spawn (options) == -1)
{
ACE_ERROR ((LM_DEBUG,
"ERROR: This should have succeeded\n"));
test_status = 1;
}
//test inheriting a large env block with enable_unicode_environment
ACE_Process_Options opts2 (1,
ACE_Process_Options::DEFAULT_COMMAND_LINE_BUF_LEN,
128 * 1024);
create_large_env (thisproc_setenv, 0);
opts2.enable_unicode_environment ();
opts2.setenv (ACE_TEXT ("ZZ"), ACE_TEXT ("1"));
opts2.command_line (ACE_TEXT ("cmd.exe /d /c ")
ACE_TEXT ("\"if defined Z (exit 1) else (exit 2)\""));
ACE_Process process2;
if (process2.spawn (opts2) == -1)
{
ACE_ERROR ((LM_DEBUG,
"ERROR: Failed to spawn process2.\n"));
test_status = 1;
}
ACE_exitcode status;
process2.wait (&status);
if (status != 1)
{
ACE_ERROR ((LM_DEBUG,
"ERROR: process2 did not inherit env var Z.\n"));
test_status = 1;
}
#else
ACE_ERROR ((LM_INFO, "This test is for Win32 without ACE_USES_WCHAR\n"));
#endif /* ACE_WIN32 && !ACE_USES_WCHAR && !ACE_HAS_WINCE */
ACE_END_TEST;
return test_status;
}
| [
"binghuo365@hotmail.com"
] | binghuo365@hotmail.com |
d79acdcc9a963b77966ffd4841bed33bd09ae498 | 392a5f46c62500b90d37f7937ce3239561728a9f | /Source/VirtuoZoMap/mdisetcursorpage.cpp | 58b24bf0d767b7df1b7b96a8c9515d512b33e005 | [] | no_license | wangxiang5/DYM | 554dc052e61c17d3b4bfdeea7bae404e12997596 | 823d6731a16f7bf4c6d43728c8903514da31b1a1 | refs/heads/master | 2020-04-06T14:14:07.376918 | 2019-03-21T02:22:19 | 2019-03-21T02:22:19 | 157,533,033 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 7,349 | cpp | // MdiSetCursorPage.cpp : implementation file
//
#include "stdafx.h"
#include "VirtuoZoMap.h"
#include "MdiSetCursorPage.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMdiSetCursorPage property page
IMPLEMENT_DYNCREATE(CMdiSetCursorPage, CDialog)
CMdiSetCursorPage::CMdiSetCursorPage(CWnd* pParent /*=NULL*/) :
CDialog(CMdiSetCursorPage::IDD, pParent)
{
m_nItemNum = 1;
m_pCursor = NULL;
m_nCursorIndex = 0;
m_Color.SetColor(RGB(255,255,255));
//{{AFX_DATA_INIT(CMdiSetCursorPage)
m_bDiableMouseDraw = FALSE;
m_bSingleCrossSet = TRUE;
//}}AFX_DATA_INIT
for ( int i=0;i<10;i++ ) m_BmpList[i].LoadBitmap( IDB_BITMAP_CURSOR );
}
CMdiSetCursorPage::~CMdiSetCursorPage()
{
}
void CMdiSetCursorPage::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMdiSetCursorPage)
DDX_Control(pDX, IDC_CURSOR_COLOR, m_Color);
DDX_Control(pDX, IDC_CURRENT, m_Current);
DDX_Control(pDX, IDC_LIST, m_ListBox);
DDX_Check(pDX, IDC_USE_MOUSE_DRAW, m_bDiableMouseDraw);
DDX_Check(pDX, IDC_SINGLE_CROSS, m_bSingleCrossSet);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMdiSetCursorPage, CDialog)
//{{AFX_MSG_MAP(CMdiSetCursorPage)
ON_LBN_SELCHANGE(IDC_LIST, OnSelchangeList)
ON_WM_PAINT()
ON_BN_CLICKED(IDC_CURSOR_COLOR, OnCursorColor)
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_SINGLE_CROSS, &CMdiSetCursorPage::OnBnClickedSingleCross)
ON_BN_CLICKED(IDC_USE_MOUSE_DRAW, &CMdiSetCursorPage::OnBnClickedUseMouseDraw)
END_MESSAGE_MAP()
static void DrawBmp( CDC *pDC, CBitmap* pBmp,const CRect &rc,BOOL bSelect)
{
CRect rect(rc);
BITMAP bm; pBmp->GetObject(sizeof(bm),(LPVOID)&bm);
CDC dcMem; dcMem.CreateCompatibleDC(pDC);
CBitmap *pOldBMP=(CBitmap*)dcMem.SelectObject(pBmp);
pDC->FillSolidRect(rect,0);
if(bSelect)
{
pDC->BitBlt(
rect.left+1 +10,
rect.top+1 +(rect.Height()-bm.bmHeight)/2 ,
bm.bmWidth,
bm.bmHeight,
&dcMem,
0,0,
SRCCOPY);
pDC->DrawEdge(&rect,EDGE_SUNKEN,BF_RECT);
}
else
{
pDC->BitBlt( rect.left +10,
rect.top + (rect.Height()-bm.bmHeight)/2,
bm.bmWidth,
bm.bmHeight,
&dcMem,
0,0,
SRCCOPY);
}
dcMem.SelectObject(pOldBMP);
dcMem.DeleteDC();
}
/// For BmpList Box
void CMdiSetCursorPage::CBmpListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct )
{
CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
CBitmap *pBmp = (CBitmap *)(lpDrawItemStruct->itemData); ASSERT(pBmp);
CRect rect(lpDrawItemStruct->rcItem);
if (lpDrawItemStruct->itemID == LB_ERR) return;
if (lpDrawItemStruct->itemAction&(ODA_DRAWENTIRE | ODA_SELECT))
DrawBmp( pDC,pBmp,rect,lpDrawItemStruct->itemState& ODS_SELECTED );
if (lpDrawItemStruct->itemAction & ODA_FOCUS)
DrawBmp( pDC,pBmp,rect,lpDrawItemStruct->itemState&ODS_FOCUS );
}
void CMdiSetCursorPage::CBmpListBox::MeasureItem(LPMEASUREITEMSTRUCT lpDrawItemStruct )
{
lpDrawItemStruct->itemHeight = 41;
}
/////////////////////////////////////////////////////////////////////////////
// CMdiSetCursorPage message handlers
BOOL CMdiSetCursorPage::OnInitDialog()
{
CDialog::OnInitDialog();
if ( m_pCursor != NULL)
{
m_nCursorIndex = m_pCursor->GetType();
m_Color.SetColor(m_pCursor->GetColor());
BITMAP bm; CClientDC dc(this); CDC *pDC = &dc;
CDC dcMem; dcMem.CreateCompatibleDC(pDC);
float oldap = m_pCursor->GetSnapAp(); m_pCursor->SetSnapAp(0);
CBitmap *pOldBMP=(CBitmap*)dcMem.SelectObject( m_BmpList+0 );
m_nItemNum = m_pCursor->GetCursorSum();
for (int i=0;i<m_nItemNum;i++)
{
m_BmpList[i].GetObject( sizeof(bm),(LPVOID)&bm );
dcMem.SelectObject( m_BmpList+i );
dcMem.FillSolidRect(0,0,40,40,0);
m_pCursor->SetType(i);
m_pCursor->SetColor(RGB(255,255,255));// 0
CSize curSize = m_pCursor->GetCursorSize();
m_pCursor->Draw( &dcMem, 20-curSize.cx/2, 20-curSize.cy/2 );
}
dcMem.SelectObject(pOldBMP);
dcMem.DeleteDC();
m_pCursor->SetSnapAp(oldap);
pDC = m_Current.GetDC();
CRect rect; m_Current.GetClientRect(&rect);
pDC->FillSolidRect(rect,0);
m_pCursor->SetType(m_nCursorIndex);
m_pCursor->SetColor(m_Color.GetColor());
m_pCursor->Draw( pDC, rect.Width()/2, rect.Height()/2 );
m_Current.ReleaseDC(pDC);
}
m_ListBox.SetItemHeight(0,50);
m_ListBox.SetColumnWidth(100); CString str;
for(int i=0;i<m_nItemNum;i++)
{
str.Format("Cursor %d",i );
m_ListBox.SetItemData( m_ListBox.AddString( str ),DWORD(m_BmpList+i) );
}
m_ListBox.SetSel(m_nCursorIndex);
UpdateData(FALSE);
return TRUE;
// return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CMdiSetCursorPage::OnSelchangeList()
{
m_nCursorIndex = m_ListBox.GetCurSel();
if (m_pCursor == NULL) return;
CRect rect;
m_Current.GetClientRect(&rect);
CDC *pDC = m_Current.GetDC();
pDC->FillSolidRect(rect,0);
m_pCursor->SetType(m_nCursorIndex);
m_pCursor->SetColor(m_Color.GetColor());
m_pCursor->Draw(pDC, rect.Width()/2, rect.Height()/2 );
m_Current.ReleaseDC(pDC);
theApp.SendMsgToAllView(WM_OUTPUT_MSG, Msg_RefreshView, 0 );
}
void CMdiSetCursorPage::OnPaint()
{
CPaintDC dc(this); // device context for painting
if (m_pCursor != NULL)
{
CDC *pDC = m_Current.GetDC();
CRect rect; m_Current.GetClientRect(&rect);
pDC->FillSolidRect(rect,0);
int oldtype = m_pCursor->GetType(); m_pCursor->SetType(m_nCursorIndex);
COLORREF oldcolor = m_pCursor->GetColor(); m_pCursor->SetColor(m_Color.GetColor());
m_pCursor->Draw( pDC, rect.Width()/2,rect.Height()/2);
m_pCursor->SetType(oldtype);
m_pCursor->SetColor(oldcolor);
m_Current.ReleaseDC(pDC);
}
// Do not call CPropertyPage::OnPaint() for painting messages
}
void CMdiSetCursorPage::OnCursorColor()
{
if (m_pCursor != NULL)
{
CDC *pDC = m_Current.GetDC();
CRect rect; m_Current.GetClientRect(&rect);
pDC->FillSolidRect(rect,0);
m_pCursor->SetType(m_nCursorIndex);
m_pCursor->SetColor(m_Color.GetColor());
m_pCursor->Draw( pDC,rect.Width()/2,rect.Height()/2);
m_Current.ReleaseDC(pDC);
theApp.SendMsgToAllView(WM_OUTPUT_MSG, Msg_RefreshView, 0, 0);
}
}
bool CMdiSetCursorPage::Init(CIGSCursor& cursor)
{
m_pCursor = &cursor;
if (m_pCursor)
{
m_nCursorIndex = m_pCursor->GetType();
m_Color.SetColor(m_pCursor->GetColor());
}
return true;
}
void CMdiSetCursorPage::OnOK()
{
UpdateData(TRUE);
if(m_pCursor)
{
m_pCursor->SetType(m_nCursorIndex);
m_pCursor->SetColor(m_Color.GetColor());
OnPaint();
}
return CDialog::OnOK();
}
void CMdiSetCursorPage::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{ // storing code
ar << m_bSingleCrossSet;
ar << m_bDiableMouseDraw;
char *pReserve = new char[DLG_SERIALIZE_RESERVE]; ZeroMemory(pReserve, DLG_SERIALIZE_RESERVE*sizeof(char));
ar.Write(pReserve, DLG_SERIALIZE_RESERVE);
if ( pReserve ) delete[] pReserve; pReserve = NULL;
}
else
{ // loading code
ar >> m_bSingleCrossSet;
ar >> m_bDiableMouseDraw;
char *pReserve = new char[DLG_SERIALIZE_RESERVE];
ar.Read(pReserve, DLG_SERIALIZE_RESERVE);
if ( pReserve ) delete[] pReserve; pReserve = NULL;
}
}
void CMdiSetCursorPage::OnBnClickedSingleCross()
{
UpdateData(TRUE);
}
void CMdiSetCursorPage::OnBnClickedUseMouseDraw()
{
UpdateData(TRUE);
}
| [
"mld@whu.edu.cn"
] | mld@whu.edu.cn |
2d2ac45d480ae9c4cbfcd276a86350c7e04adfe7 | 30a3e10673b3244206abe0611ced13e714e1bff5 | /DesignMode/BridgeMode/Bag.h | 63c5b026e9e079e5c93d857264e68f84c1cba7a5 | [] | no_license | fhLiu/MyProject | c68f31923ee41fd797041c6e346691361c16af01 | 620730ddb9f0caf630d7a20cf6a6f6c84f96baf2 | refs/heads/master | 2021-12-23T06:57:18.769690 | 2021-12-13T11:50:55 | 2021-12-13T11:50:55 | 158,992,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222 | h | #pragma once
#include "Color.h"
#include <memory>
struct Bag
{
void SetColor(Color *color)
{
p_color.reset(color);
}
virtual void GetName() = 0;
protected:
std::shared_ptr<Color> p_color;
};
| [
"andrew2_liu@askey.com"
] | andrew2_liu@askey.com |
8265cb843c083ac6d96407eac938890ccf2c6bfb | 794c894eed9e4f33897856b29a4f5c044dbad6d1 | /book/articles/AWSReVIEW/AWSReVIEW.re | 3df33f6407cedd96494181a3e64086d4ddf0c220 | [] | no_license | nanbuwks/qiita2review | 05475372f24f8622e646820babbd5d350d5f13bd | e92f35f22c6ae7ae42c94e6b9a906e0cb9b5693c | refs/heads/master | 2021-12-26T13:13:58.510581 | 2021-12-20T20:13:36 | 2021-12-20T20:13:36 | 87,666,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,366 | re |
= AWS上にRe:VIEW環境を構築する
AWS 上に Re:VIEW 環境を構築してみました。
== 環境
* T2.micro
* Ubuntu 16.04 64bit(Ubuntu 14.04から dist-upgreadeをかけています。)既に ruby や rack は別の用事でインストール終えていました。
== インストール
//emlist{
gem install review
gem install md2review
//}
試してみます
//emlist{
review-init testwrite
cd testwrite
rake pdf
//}
エラー
//emlist{
review-pdfmaker config.yml
compiling testwrite.tex
/var/lib/gems/2.3.0/gems/review-2.2.0/lib/review/pdfmaker.rb:42:in `system_or_raise': failed to run command: ebb cover.jpg (RuntimeError)
from /var/lib/gems/2.3.0/gems/review-2.2.0/lib/review/pdfmaker.rb:276:in `block in copy_images'
from /var/lib/gems/2.3.0/gems/review-2.2.0/lib/review/pdfmaker.rb:269:in `chdir'
from /var/lib/gems/2.3.0/gems/review-2.2.0/lib/review/pdfmaker.rb:269:in `copy_images'
from /var/lib/gems/2.3.0/gems/review-2.2.0/lib/review/pdfmaker.rb:235:in `generate_pdf'
from /var/lib/gems/2.3.0/gems/review-2.2.0/lib/review/pdfmaker.rb:132:in `execute'
from /var/lib/gems/2.3.0/gems/review-2.2.0/lib/review/pdfmaker.rb:86:in `execute'
from /var/lib/gems/2.3.0/gems/review-2.2.0/bin/review-pdfmaker:18:in `<top (required)>'
from /usr/local/bin/review-pdfmaker:22:in `load'
from /usr/local/bin/review-pdfmaker:22:in `<main>'
rake aborted!
Command failed with status (1): [review-pdfmaker config.yml...]
/home/ubuntu/testwrite/Rakefile:60:in `block in <top (required)>'
/var/lib/gems/1.9.1/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'
Tasks: TOP => pdf => book.pdf
(See full trace by running task with --trace)
//}
Re:VIEWは2.0からはuplatexを使うらしいので、インストールします。
//emlist{
$ apt-cache search uplatex
texlive-lang-cjk - TeX Live: Chinese/Japanese/Korean
//}
ということなので、
//emlist{
$ sudo apt-get install texlive-lang-cjk
sudo: unable to resolve host ip-172-30-0-222
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
fontconfig-config fonts-dejavu-core fonts-ipaexfont-gothic
fonts-ipaexfont-mincho fonts-ipafont-gothic fonts-ipafont-mincho
fonts-lmodern ghostscript gsfonts ko.tex-extra-hlfont latex-beamer
latex-cjk-all latex-cjk-chinese latex-cjk-chinese-arphic-bkai00mp
latex-cjk-chinese-arphic-bsmi00lp latex-cjk-chinese-arphic-gbsn00lp
latex-cjk-chinese-arphic-gkai00mp latex-cjk-common latex-cjk-japanese
latex-cjk-japanese-wadalab latex-cjk-korean latex-cjk-thai latex-xcolor
libavahi-client3 libavahi-common-data libavahi-common3 libcairo2 libcups2
libcupsfilters1 libcupsimage2 libdatrie1 libdrm-intel1 libdrm-nouveau2
libdrm-radeon1 libfile-basedir-perl libfile-desktopentry-perl
libfile-mimeinfo-perl libfontconfig1 libfontenc1 libgl1-mesa-dri
libgl1-mesa-glx libglapi-mesa libgraphite2-3 libgs9 libgs9-common
libharfbuzz0b libice6 libijs-0.35 libjbig0 libjbig2dec0 libjpeg-turbo8
libjpeg8 libkpathsea6 liblcms2-2 libllvm3.4 libpaper-utils libpaper1
libpciaccess0 libpixman-1-0 libpoppler44 libptexenc1 libsm6 libtcl8.6
libtiff5 libtk8.6 libtxc-dxtn-s2tc0 libutempter0 libx11-xcb1 libxaw7
libxcb-dri2-0 libxcb-dri3-0 libxcb-glx0 libxcb-present0 libxcb-render0
libxcb-shape0 libxcb-shm0 libxcb-sync1 libxcomposite1 libxcursor1
libxdamage1 libxfixes3 libxft2 libxi6 libxinerama1 libxmu6 libxpm4
libxrandr2 libxrender1 libxshmfence1 libxss1 libxt6 libxtst6 libxv1
libxxf86dga1 libxxf86vm1 lmodern luatex pgf poppler-data preview-latex-style
prosper ps2eps ruby swath tcl tcl8.6 tex-common texlive-base
texlive-binaries texlive-extra-utils texlive-font-utils
texlive-generic-recommended texlive-lang-other texlive-latex-base
texlive-latex-base-doc texlive-latex-extra texlive-latex-extra-doc
texlive-latex-recommended texlive-latex-recommended-doc texlive-luatex
texlive-pictures texlive-pictures-doc texlive-pstricks texlive-pstricks-doc
tk tk8.6 x11-common x11-utils x11-xserver-utils xbitmaps xdg-utils xterm
Suggested packages:
ghostscript-x hpijs hbf-cns40-b5 hbf-jfs56 fonts-arphic-bkai00mp
fonts-arphic-bsmi00lp fonts-arphic-gbsn00lp fonts-arphic-gkai00mp
hbf-kanji48 cups-common libglide3 fonts-droid liblcms2-utils poppler-utils
fonts-arphic-ukai fonts-arphic-uming fonts-unfonts-core pdf-viewer
postscript-viewer ri ruby-dev libthai-data tcl-tclreadline debhelper perl-tk
chktex fragmaster xindy latexdiff lacheck latexmk dvidvi purifyeps dvipng
t1utils psutils latex-fonts-sipa-arundina libfile-which-perl python-pygments
dot2tex libtcltk-ruby mesa-utils nickle cairo-5c xorg-docs-core gvfs-bin
xfonts-cyrillic
Recommended packages:
wish
The following NEW packages will be installed:
fontconfig-config fonts-dejavu-core fonts-ipaexfont-gothic
fonts-ipaexfont-mincho fonts-ipafont-gothic fonts-ipafont-mincho
fonts-lmodern ghostscript gsfonts ko.tex-extra-hlfont latex-beamer
latex-cjk-all latex-cjk-chinese latex-cjk-chinese-arphic-bkai00mp
latex-cjk-chinese-arphic-bsmi00lp latex-cjk-chinese-arphic-gbsn00lp
latex-cjk-chinese-arphic-gkai00mp latex-cjk-common latex-cjk-japanese
latex-cjk-japanese-wadalab latex-cjk-korean latex-cjk-thai latex-xcolor
libavahi-client3 libavahi-common-data libavahi-common3 libcairo2 libcups2
libcupsfilters1 libcupsimage2 libdatrie1 libdrm-intel1 libdrm-nouveau2
libdrm-radeon1 libfile-basedir-perl libfile-desktopentry-perl
libfile-mimeinfo-perl libfontconfig1 libfontenc1 libgl1-mesa-dri
libgl1-mesa-glx libglapi-mesa libgraphite2-3 libgs9 libgs9-common
libharfbuzz0b libice6 libijs-0.35 libjbig0 libjbig2dec0 libjpeg-turbo8
libjpeg8 libkpathsea6 liblcms2-2 libllvm3.4 libpaper-utils libpaper1
libpciaccess0 libpixman-1-0 libpoppler44 libptexenc1 libsm6 libtcl8.6
libtiff5 libtk8.6 libtxc-dxtn-s2tc0 libutempter0 libx11-xcb1 libxaw7
libxcb-dri2-0 libxcb-dri3-0 libxcb-glx0 libxcb-present0 libxcb-render0
libxcb-shape0 libxcb-shm0 libxcb-sync1 libxcomposite1 libxcursor1
libxdamage1 libxfixes3 libxft2 libxi6 libxinerama1 libxmu6 libxpm4
libxrandr2 libxrender1 libxshmfence1 libxss1 libxt6 libxtst6 libxv1
libxxf86dga1 libxxf86vm1 lmodern luatex pgf poppler-data preview-latex-style
prosper ps2eps ruby swath tcl tcl8.6 tex-common texlive-base
texlive-binaries texlive-extra-utils texlive-font-utils
texlive-generic-recommended texlive-lang-cjk texlive-lang-other
texlive-latex-base texlive-latex-base-doc texlive-latex-extra
texlive-latex-extra-doc texlive-latex-recommended
texlive-latex-recommended-doc texlive-luatex texlive-pictures
texlive-pictures-doc texlive-pstricks texlive-pstricks-doc tk tk8.6
x11-common x11-utils x11-xserver-utils xbitmaps xdg-utils xterm
0 upgraded, 133 newly installed, 0 to remove and 0 not upgraded.
Need to get 852 MB of archives.
After this operation, 1,625 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
//}
さて、どうかな?
//emlist{
$ rake pdf
・
・
・
<to be read again>
relax
l.100 \fontencoding\encodingdefault\selectfont
?
//}
と出たので、フォントをインストール
//emlist{
$ sudo apt-get install texlive-fonts-recommended
//}
として、
@<tt>{
rake pdf
}
とすると、
book.pdfができました。
| [
"nanbuwks+github@nanbu.com"
] | nanbuwks+github@nanbu.com |
2500dff50d9a084e801549d4859381ecb6b262d9 | d659ed4230e05b75929220ac0514abf092f714ea | /implementation/cvsupervisor.cpp | 70bec340643ffe324377cfdc0d618bb3fd5841b9 | [] | no_license | VSBochkov/CVKernel | a4e04effb812b9df83c8809beb8fa7f8447aa4e3 | 58b22b8309f01dff4fc1ddbd0135dd9493704ed9 | refs/heads/master | 2021-01-12T11:31:26.528962 | 2017-06-17T10:34:02 | 2017-06-17T10:34:02 | 72,944,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,730 | cpp | #include "cvsupervisor.h" // Подключаем файл cvsupervisor.h для определения методов классов
#include "cvclient.h" // Подключаем файл cvclient.h для использования класса CVClient
#include "cvconnector.h" // Подключаем файл cvconnector.h для использования методов классов-родителей
#include "cvjsoncontroller.h" // Подключаем файл cvjsoncontroller.h для использования класса CVJsonController
#include "cvnetworkmanager.h" // Подключаем файл cvnetworkmanager.h для использования класса CVNetworkManager
#include "cvprocessmanager.h" // Подключаем файл cvprocessmanager.h для использования класса CVProcessManager
// Определение метода set_state класса CVSupervisorFactory
// Входящий параметр connector - ссылка на коннектор
// Возвращаемое значение - объект состояния коннектора унаследованный от класса CVConnectorState
CVKernel::CVConnectorState* CVKernel::CVSupervisorFactory::set_state(CVConnector& connector)
{
CVSupervisor& sup = static_cast<CVSupervisor&>(connector); // приводим ссылку на коннектора к ссылке на супервайзера
if (sup.supervision_port == 0) // Если TCP порт передачи информации не инициализирован
{
return new CVSupervisorClosed(sup); // То возвращаем объект состояния "не активен"
}
else if (sup.running) // Если супервайзер активирован
{
return new CVConnectorRun(sup); // То возвращаем объект состояния "в процессе"
}
else
{
return new CVConnectorReady(sup); // Возвращаем объект состояния "остановлен"
}
}
// Определение конструктора класса CVSupervisor
// Входящие параметры
// index - номер коннектора
// pm - ссылка на менеджер процессорных узлов
// nm - ссылка на сетевой менеджер
// sock - TCP соединение
CVKernel::CVSupervisor::CVSupervisor(unsigned int id, CVProcessManager& pm, CVNetworkManager& nm, QTcpSocket& sock)
: CVConnector(id, *CVSupervisorFactory::instance(), pm, nm, sock), // Инициализируем объект коннектора передавая входящие параметры и ссылку на конкретную фабрику супервайзера
supervision_port(0) // Установка порта передачи информации в значение 0
{
state_changed(); // Вызов метода изменения состояния супервайзера
updateSupInfoTimer = new QTimer(&sock); // Инициализация таймера в потоке родительского объекта sock
tcp_supervision = new QTcpSocket(&sock); // Инициализация TCP сокета для передачи информации в потоке родительского объекта sock
connect(updateSupInfoTimer, SIGNAL(timeout()), this, SLOT(send_supervision_info())); // Устанавливаем метод send_supervision_info как обработчик сигнала истечения времени таймера
for (QSharedPointer<CVClient> client : network_manager.get_clients()) // Организуем цикл по всем клиентам ядра
{
connect(client.data(), SIGNAL(notify_supervisors(CVConnectorState&)), this, SLOT(send_connector_state_change(CVConnectorState&))); // Устанавливаем метод send_connector_state_change как обработчик сигнала оповещения о смене статуса клиента
}
qDebug() << "added CVSupervisor id:" << id << "ip_address:" << sock.peerAddress(); // Вывод информации о добавлении нового супервайзера в интерфейс командной строки
}
// Определение деструктора класса CVSupervisor
CVKernel::CVSupervisor::~CVSupervisor()
{
for (QSharedPointer<CVClient> client : network_manager.get_clients()) // Организуем цикл по всем клиентам ядра
{
disconnect(client.data(), SIGNAL(notify_supervisors(CVConnectorState&)), this, SLOT(send_connector_state_change(CVConnectorState&))); // Деактивируем обработчик сигнала оповещения о смене статуса клиента
}
qDebug() << "deleted CVSupervisor id: " << id; // Вывод информации об удалении супервайзера в интерфейс командной строки
}
// Определение метода init_supervision класса CVSupervisor
// Входящий параметр settings - настройки режима супервайзера
void CVKernel::CVSupervisor::init_supervision(QSharedPointer<CVSupervisionSettings> settings)
{
supervision_port = settings->port; // Инициализация TCP порта передачи информации
update_timer_value = settings->update_timer_value; // Инициализация периода времени посылки информации в секундах
tcp_supervision->connectToHost(tcp_state.peerAddress(), supervision_port); // Присоединение к TCP серверу приема информации
tcp_supervision->waitForConnected(-1); // Ожидание установление соединения
send_buffer( // Отправка буфера
CVJsonController::pack_to_json<CVSupervisorStartup>( // Синхронизации статуса ядра
CVSupervisorStartup(network_manager.get_clients()) // В формате JSON
),
*tcp_supervision // По сокету передачи информации
);
}
// Определение метода run класса CVSupervisor - (Паттерн ООП "Команда")
void CVKernel::CVSupervisor::run()
{
updateSupInfoTimer->start(update_timer_value * 1000); // Заводим таймер по истечении которого передаем информацию о работе процессорных модулей
CVConnector::run(); // Вызов одноименного метода из класса-родителя
}
// Определение метода stop класса CVSupervisor - (Паттерн ООП "Команда")
void CVKernel::CVSupervisor::stop()
{
updateSupInfoTimer->stop(); // Останавливаем таймер передачи информации о работе процессорных модулей
CVConnector::stop(); // Вызов одноименного метода из класса-родителя
}
// Определение метода close класса CVSupervisor - (Паттерн ООП "Команда")
void CVKernel::CVSupervisor::close()
{
if (running) // Если супервайзер запущен
{
stop(); // То останавливаем его
}
send_buffer(QByteArray("{}"), *tcp_supervision); // Отправка буфера пустой спецификации JSON через сокет передачи информации
tcp_supervision->close(); // Закрываем сокет передачи информации
supervision_port = 0; // Сбрасываем значение порта
state_changed(); // Вызов метода изменения состояния супервайзера
}
// Определение метода handle_incomming_message класса CVSupervisorClosed (паттерн ООП "Стратегия")
// Входящий параметр buffer - массив байт входящего сообщения
void CVKernel::CVSupervisorClosed::handle_incomming_message(QByteArray &buffer)
{
QSharedPointer<CVSupervisionSettings> sup_settings = CVJsonController::get_from_json_buffer<CVSupervisionSettings>(buffer); // Разбор настроек процесса супервайзера в формате JSON
if (sup_settings->port != 0) // Если настройки корректные
{
command.reset(new CVInitSupervisionCommand(static_cast<CVSupervisor&>(connector), sup_settings)); // То устанавливаем объект команды типом инициализации параметров супервизора
}
}
// Определение метода execute класса CVInitSupervisionCommand (паттерн ООП "Стратегия")
void CVKernel::CVInitSupervisionCommand::execute()
{
supervisor.init_supervision(settings); // Вызов функции инициализации параметров супервизора для объекта собственника
}
// Определение метода send_supervision_info класса CVSupervisor
void CVKernel::CVSupervisor::send_supervision_info()
{
send_buffer( // Отправка
CVJsonController::pack_to_json<CVSupervisionInfo>( // буффера информации
CVSupervisionInfo( // о состоянии ядра
network_manager.get_clients().size(), // и процессорных
process_manager.get_average_timings() // модулей
)
),
*tcp_supervision // через сокет супервайзера
);
}
// Определение метода send_connector_state_change класса CVSupervisor
// Входящий параметр state - ссылка на объект состояния коннектора
void CVKernel::CVSupervisor::send_connector_state_change(CVConnectorState& state)
{
send_buffer(CVJsonController::pack_to_json<CVConnectorState>(&state), *tcp_supervision); // Отправка буфера состояния коннектора в формате JSON
}
// Определение конструктора класса CVSupervisionInfo
// Входящие параметры:
// clients - количество подключенных клиентов
// timings - словарь значений среднего времени выполнения работы всех процессорных узлов
CVKernel::CVSupervisionInfo::CVSupervisionInfo(int clients, QMap<QString, double> timings)
: connected_clients(clients) // Присваивание количества подключенных клиентов
{
used_process_nodes = timings.size(); // Вычисление количества процессорных узлов
average_timings = timings; // Присвоение словаря среднего времени работы узлов
}
| [
"vlbochk@mera.ru"
] | vlbochk@mera.ru |
ced783748aab6aa7309ed434535d4b72d56f062f | 5992e5d23575f22127631fbdf134ff9d2b18605c | /MAX/Editor/MAXEditor.cpp | f34c5d5fa738270233f3d080f78ba4351ffd26d5 | [] | no_license | jsj2008/MAXNew | 1f52012ba47161ac3a07c3c6b10ec4fbd567d6ef | 3a87ea933f3d66757a1d573d85bb067c1604246f | refs/heads/master | 2020-09-14T10:39:05.923680 | 2013-09-05T17:54:44 | 2013-09-05T17:54:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 215 | cpp | //
// MAXEditor.cpp
// MAX
//
// Created by Anton Katekov on 19.06.13.
// Copyright (c) 2013 AntonKatekov. All rights reserved.
//
#include "MAXEditor.h"
MAXEditor::MAXEditor()
{}
MAXEditor::~MAXEditor()
{}
| [
"void0main@gmail.com"
] | void0main@gmail.com |
c5478e2f808a9b606b3798f4bbf040929a366424 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_old_hunk_3949.cpp | 1982e7046112f5440c4c8df212eb8cc05f60ccb1 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | APR_BRIGADE_INSERT_TAIL(bb, b);
b = apr_bucket_flush_create(c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, b);
rv = ap_pass_brigade(r->output_filters, bb);
cid->response_sent = 1;
if (rv != APR_SUCCESS)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r,
"WriteClient ap_pass_brigade failed: %s",
r->filename);
}
if ((flags & HSE_IO_ASYNC) && cid->completion) {
if (rv == APR_SUCCESS) {
| [
"993273596@qq.com"
] | 993273596@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.