hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
22041b9172a3b515906ba2e835c0b5fa2a8b79b4
4,016
cpp
C++
src/main.cpp
JWhitleyWork/ffree
bb0d32f42e3b8a7dd4378a903f1de2887ed94846
[ "Apache-2.0" ]
1
2022-03-01T22:55:59.000Z
2022-03-01T22:55:59.000Z
src/main.cpp
JWhitleyWork/ffree
bb0d32f42e3b8a7dd4378a903f1de2887ed94846
[ "Apache-2.0" ]
null
null
null
src/main.cpp
JWhitleyWork/ffree
bb0d32f42e3b8a7dd4378a903f1de2887ed94846
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Whitley Software Services, LLC // // 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. /// \copyright Copyright 2020 Whitley Software Services, LLC /// All rights reserved. /// \file /// \brief This file is the main entrypoint for the ffree command-line application #include <cstdlib> #include <filesystem> #include <iostream> #include <memory> #include <string> #include <cxxopts.hpp> #include <logging.hpp> using namespace ffree::logging; namespace fs = std::filesystem; void print_help(cxxopts::Options & opts, uint32_t ret_code) { std::cout << "\n"; std::cout << opts.help() << std::endl; exit(ret_code); } int32_t main(int32_t argc, char ** argv) { cxxopts::Options opts(argv[0], "The Files and Folders Rules Evaluation Engine"); opts.positional_help("<rules file path> <base folder path>"); opts.add_options() ("h,help", "Print help and exit") ("l,log-level", "Logging level", cxxopts::value<std::string>()->default_value("warn")) ("r,rules", "Rules XML file", cxxopts::value<std::string>()) ("p,path", "Path to folder where rules should be executed", cxxopts::value<std::string>()); opts.parse_positional({"rules", "path"}); auto logger = Logger(LogLevel::DEBUG); LogLevel logging_level; std::string rules_path_string; std::string folder_path_string; try { const auto parse_result = opts.parse(argc, argv); // Handle parse_result if (parse_result.count("help") > 0) { print_help(opts, 0); } if (parse_result.count("rules") > 0 && parse_result.count("path") > 0) { rules_path_string = parse_result["rules"].as<std::string>(); folder_path_string = parse_result["path"].as<std::string>(); } else { LOG_ERROR(logger, "Rules XML file and folder path are required parse_result."); print_help(opts, 1); } std::string log_level_string = parse_result["log-level"].as<std::string>(); if (log_level_string == "debug") { logging_level = LogLevel::DEBUG; } else if (log_level_string == "info") { logging_level = LogLevel::INFO; } else if (log_level_string == "warn") { // This is the default log level; logging_level = LogLevel::WARN; } else if (log_level_string == "error") { logging_level = LogLevel::ERROR; } else if (log_level_string == "none") { logging_level = LogLevel::NONE; } else { LOG_ERROR(logger, "Valid logging levels are none, error, warn (default), info, and debug."); print_help(opts, 1); } } catch (cxxopts::OptionParseException ex) { LOG_ERROR(logger, "Error parsing options: " << ex.what()); print_help(opts, 1); } logger.set_level(logging_level); auto rules_path = fs::path(rules_path_string); auto folder_path = fs::path(folder_path_string); // Normalize paths try { LOG_DEBUG(logger, "Rules file path provided as " << rules_path.string()); rules_path = fs::canonical(rules_path); LOG_DEBUG(logger, "Rules file path parsed as " << rules_path.string()); } catch (fs::filesystem_error ex) { LOG_ERROR(logger, "Rules file path does not exist or is not accessible."); exit(3); } try { LOG_DEBUG(logger, "Base folder path provided as " << folder_path.string()); folder_path = fs::canonical(folder_path); LOG_DEBUG(logger, "Base folder path parsed as " << folder_path.string()); } catch (fs::filesystem_error ex) { LOG_ERROR(logger, "Base folder path does not exist or is not accessible."); exit(4); } return 0; }
32.918033
98
0.676544
JWhitleyWork
220e212eb0d699a0d8f86461454b89dbb0ddc22f
452
cpp
C++
zero-para-cancelar/index.cpp
tiago-rodrigues1/questoes-Neps
e1fbeffac1a51d396e7b7770135b4b2f0515af5c
[ "MIT" ]
2
2020-10-14T19:40:42.000Z
2020-10-21T21:35:19.000Z
zero-para-cancelar/index.cpp
tiago-rodrigues1/questoes-Neps
e1fbeffac1a51d396e7b7770135b4b2f0515af5c
[ "MIT" ]
null
null
null
zero-para-cancelar/index.cpp
tiago-rodrigues1/questoes-Neps
e1fbeffac1a51d396e7b7770135b4b2f0515af5c
[ "MIT" ]
1
2020-10-14T19:40:56.000Z
2020-10-14T19:40:56.000Z
#include <bits/stdc++.h> using namespace std; int main() { stack<int> nums; int n, soma = 0; cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; if (x == 0) { nums.pop(); } else { nums.push(x); } } while (!nums.empty()) { soma += nums.top(); nums.pop(); } cout << soma << endl; return 0; }
11.894737
31
0.35177
tiago-rodrigues1
c300782df7efba0e00f703054f85fb02ca7e50d7
2,064
cpp
C++
tests/rect_clipping.cpp
kayabe/deadfrog-lib
824bd9451e44b593343031c02a4fd79b292db1a9
[ "MIT" ]
7
2016-07-06T14:20:00.000Z
2021-02-26T02:31:27.000Z
tests/rect_clipping.cpp
kayabe/deadfrog-lib
824bd9451e44b593343031c02a4fd79b292db1a9
[ "MIT" ]
1
2021-04-19T09:47:38.000Z
2021-04-19T14:17:29.000Z
tests/rect_clipping.cpp
kayabe/deadfrog-lib
824bd9451e44b593343031c02a4fd79b292db1a9
[ "MIT" ]
1
2020-07-11T14:13:55.000Z
2020-07-11T14:13:55.000Z
#include "df_bitmap.h" #include "df_window.h" int main() { CreateWin(800, 600, WT_WINDOWED, "Clipping test"); BitmapClear(g_window->bmp, g_colourBlack); // Set clip rect as 100,150 -> 700,450 RectOutline(g_window->bmp, 100, 150, 600, 300, Colour(255, 50, 50)); SetClipRect(g_window->bmp, 100, 150, 600, 300); // // Y first // Entirely above and below. Shouldn't draw any pixels. RectFill(g_window->bmp, 150, -10, 50, 160, g_colourWhite); RectFill(g_window->bmp, 150, 450, 50, 160, g_colourWhite); // Overlapping top. Should be clipped. RectFill(g_window->bmp, 250, 10, 50, 200, g_colourWhite); // Overlapping bottom. Should be clipped. RectFill(g_window->bmp, 250, 390, 50, 200, g_colourWhite); // Overlapping top and bottom. Should be clipped. RectFill(g_window->bmp, 350, 10, 50, 500, g_colourWhite); // Not clipped RectFill(g_window->bmp, 450, 200, 50, 200, g_colourWhite); while (1) { InputPoll(); UpdateWin(); WaitVsync(); if (g_window->windowClosed) return; if (g_input.numKeyDowns > 0) break; } // // Now X BitmapClear(g_window->bmp, g_colourBlack); RectOutline(g_window->bmp, 100, 150, 600, 300, Colour(255, 50, 50)); // Entirely to left and entirely right. RectFill(g_window->bmp, 10, 180, 80, 50, g_colourWhite); RectFill(g_window->bmp, 710, 180, 130, 50, g_colourWhite); // Overlapping left. RectFill(g_window->bmp, 10, 270, 130, 50, g_colourWhite); // Overlapping right. RectFill(g_window->bmp, 660, 270, 130, 50, g_colourWhite); // Overlapping left and right. RectFill(g_window->bmp, 10, 360, 750, 50, g_colourWhite); // Not clipped. RectFill(g_window->bmp, 350, 180, 100, 50, g_colourWhite); while (1) { InputPoll(); UpdateWin(); WaitVsync(); if (g_window->windowClosed) return; if (g_input.numKeyDowns > 0) break; } }
27.52
73
0.600775
kayabe
c306e9a157712ad3bf6e29adefaf72eb7c4ab6c7
684
hpp
C++
include/ecs/PointLightComponent.hpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
null
null
null
include/ecs/PointLightComponent.hpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
null
null
null
include/ecs/PointLightComponent.hpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
1
2019-06-11T03:41:48.000Z
2019-06-11T03:41:48.000Z
#ifndef POINTLIGHTCOMPONENT_H_ #define POINTLIGHTCOMPONENT_H_ #include "graphics/PointLightHandle.hpp" #include "ecs/Serialization.hpp" namespace ice_engine { namespace ecs { struct PointLightComponent { PointLightComponent() = default; PointLightComponent(graphics::PointLightHandle pointLightHandle) : pointLightHandle(pointLightHandle) { }; static uint8 id() { return 9; } graphics::PointLightHandle pointLightHandle; }; } } namespace boost { namespace serialization { template<class Archive> void serialize(Archive& ar, ice_engine::ecs::PointLightComponent& c, const unsigned int version) { ar & c.pointLightHandle; } } } #endif /* POINTLIGHTCOMPONENT_H_ */
15.545455
102
0.773392
icebreakersentertainment
c307d022ce3cf615d1a42b5c55b49fcd1dcd518b
2,457
hpp
C++
src/GameC/src/Util.hpp
cs3238-tsuzu/AIShoot
7c3dbb6e3b49f7d0ae1efe7ca69251ad50477647
[ "MIT" ]
1
2018-05-23T10:57:32.000Z
2018-05-23T10:57:32.000Z
src/GameC/src/Util.hpp
cs3238-tsuzu/AIShoot
7c3dbb6e3b49f7d0ae1efe7ca69251ad50477647
[ "MIT" ]
null
null
null
src/GameC/src/Util.hpp
cs3238-tsuzu/AIShoot
7c3dbb6e3b49f7d0ae1efe7ca69251ad50477647
[ "MIT" ]
null
null
null
#pragma once namespace Util { Vec2 unitVector(const Vec2& v) { double len = sqrt(v.x * v.x + v.y * v.y); return Vec2{v.x / len, v.y / len}; } template<typename T> std::function<T(double)> EasingFunction(T (*easeFunc)(double f(double), const T& , const T& , const double), double (*f)(double), T from, T to) { return [=](double t) { return easeFunc(f, from, to, t); }; } template<typename T> std::function<std::pair<T, bool>()> EasingFunctionWithTime( T (*easeFunc)(double f(double), const T& , const T& , const double), double (*f)(double), T from, T to, Milliseconds ms, bool backToFrom = false ) { auto ef = EasingFunction(easeFunc, f, from, to); Stopwatch watch; return [=, watch = std::move(watch)]() mutable { if(!watch.isRunning()) { watch.start(); } if(ms.count() == 0) { return std::make_pair(to, true); } double t = Min(static_cast<double>(watch.ms()) / static_cast<double>(ms.count()), 1.); auto res = ef(backToFrom ? Abs(t * 2 - 1.0) : t); return std::make_pair(res, t >= 1.0); }; } constexpr double Unspecified = std::numeric_limits<double>::max(); TextureRegion Fit(const TextureRegion& texture, double width, double height, bool scaleUp = true) { if (!scaleUp) { width = std::min<double>(width, texture.size.x); height = std::min<double>(height, texture.size.y); } const double w = texture.size.x; const double h = texture.size.y; double ws = width / w; // 何% scalingするか double hs = height / h; double targetWidth, targetHeight; if (ws < hs) { targetWidth = width; targetHeight = h * ws; } else { targetWidth = w * hs; targetHeight = height; } TextureRegion result = texture; result.size = Float2(targetWidth, targetHeight); return result; } }
29.60241
150
0.457875
cs3238-tsuzu
c309db8c95080cfdb1fae4b86159bd896941f456
81
hpp
C++
NWNXLib/API/Mac/API/unknown_z_free_func.hpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
NWNXLib/API/Mac/API/unknown_z_free_func.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/unknown_z_free_func.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#pragma once namespace NWNXLib { namespace API { class z_free_func { }; } }
6.75
22
0.666667
acaos
c3201a16b03b17297369d5bf235a4aa6e51f4ffc
2,167
cpp
C++
Chapter2_linkedLists/question4.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
Chapter2_linkedLists/question4.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
Chapter2_linkedLists/question4.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
//question 4; redo //quick sort a linked list (partitian around value x) /* * Write code to partition linked list around a value x, such that * nodes less than x come before all the nodes greater than or equal to x. * If x is in the list, the values of x only need to be after the elements less * than x. * Example * 3-->5-->8-->5-->10-->2-->1 (x = 5) * 3-->1-->2-->10-->5-->5-->8 * Approach: * Start with first node, and add every thing bigger or equal to x at tail * and smaller values at head. * */ #include<bits/stdc++.h> class Node { public: int data; Node *next = nullptr;//you do not need it here }; void push(Node **n, int data) { Node *new_node = new Node; new_node->data = data; new_node->next = (*n); (*n) = new_node; } void printList(Node *n) { while (n!=NULL) { std::cout<< (n->data)<<"-->"; n = n->next; } std::cout<<"null"; } Node * partition( Node *n , int value ) { //initialize all variables Node *head = nullptr; Node *head_initial = nullptr; Node *tail = nullptr; Node *tail_initial = nullptr; Node *curr = n; while (curr != nullptr) { Node *next_node = curr->next; if (curr->data<value) { if (head == nullptr) { head = curr; head_initial = head; } head->next = curr; head = curr; } else { if (tail == nullptr) { tail = curr; tail_initial = tail; } tail->next = curr; tail = curr; } curr = next_node; } head->next = tail_initial; /*Now, we connect the head list to tail list.*/ tail->next = nullptr; return head_initial; } int main() { Node *head = nullptr; for (int i =1;i<=10;i++) { push(&head, rand()%9); } std::cout << "List before partition around 3:\n"; printList(head); std::cout << "\nList after partition around 3:\n"; printList(partition(head, 3)); return 0; }
23.813187
81
0.507614
kgajwan1
c32200cde0d232285fb96b51716a7712689c9e18
820
cpp
C++
hashing/double-hashing/Hashtable.cpp
justanindieguy/algorithms-in-c
ad4e88062dbf78ce4966be3497d44aea23bbb2dd
[ "MIT" ]
null
null
null
hashing/double-hashing/Hashtable.cpp
justanindieguy/algorithms-in-c
ad4e88062dbf78ce4966be3497d44aea23bbb2dd
[ "MIT" ]
null
null
null
hashing/double-hashing/Hashtable.cpp
justanindieguy/algorithms-in-c
ad4e88062dbf78ce4966be3497d44aea23bbb2dd
[ "MIT" ]
null
null
null
#include "Hashtable.h" #define SIZE 10 #define PRIME 7 int HashTable::hash(int key) { return key % SIZE; } int HashTable::primeHash(int key) { return PRIME - (key % PRIME); } int HashTable::doubleHash(int key) { int idx = hash(key); int i = 0; while (ht[(hash(idx) + i * primeHash(key)) % SIZE] != 0) i++; return (idx + i * primeHash(key)) % SIZE; } void HashTable::insert(int key) { int idx = hash(key); if (ht[idx] != 0) idx = doubleHash(key); ht[idx] = key; } int HashTable::search(int key) { int idx = hash(key); int i = 0; while (ht[(hash(idx) + i * primeHash(key)) % SIZE] != key) { i++; if (ht[(hash(idx) + i * primeHash(key)) % SIZE] == 0) return -1; } return (idx + i * primeHash(key)) % SIZE; }
16.4
62
0.531707
justanindieguy
c3220f6ddf60694b9b83a77a1d49ba0c7968633c
658
hpp
C++
QNXIPCUnServer/QNXIPCUnServer.hpp
SKART1/QNXIPCUnProg
0316cbbb0c0486ee9dd6d70bb1ac19f1cf622f4c
[ "MIT" ]
1
2016-10-11T11:46:44.000Z
2016-10-11T11:46:44.000Z
QNXIPCUnServer/QNXIPCUnServer.hpp
SKART1/QNXIPCUnProg
0316cbbb0c0486ee9dd6d70bb1ac19f1cf622f4c
[ "MIT" ]
null
null
null
QNXIPCUnServer/QNXIPCUnServer.hpp
SKART1/QNXIPCUnProg
0316cbbb0c0486ee9dd6d70bb1ac19f1cf622f4c
[ "MIT" ]
1
2021-08-12T07:56:48.000Z
2021-08-12T07:56:48.000Z
/* * QNXIPCUnServer.hpp * * Created on: 10.05.2014 * Author: Art */ #ifndef QNXIPCUNSERVER_HPP_ #define QNXIPCUNSERVER_HPP_ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <iostream> #include <errno.h> #include <string.h> #include <string> #include <sys/neutrino.h> #include <sys/trace.h> #include <pthread.h> #include <semaphore.h> #include <fcntl.h> //for shared memory #include <sys/mman.h> //for shared memory #include <sys/netmgr.h> //for node name resolving #endif /* QNXIPCUNSERVER_HPP_ */
18.277778
50
0.658055
SKART1
c322730a0f7abfc245f70857fb60697a6f79a040
4,584
cpp
C++
visualExamples/ch4/trajectoryError/trajectoryError.cpp
kiorisyshen/learning_slambook
9f47cca96b5c555ac854d08f05f5ebefe3d78cc8
[ "MIT" ]
1
2021-11-08T23:02:22.000Z
2021-11-08T23:02:22.000Z
visualExamples/ch4/trajectoryError/trajectoryError.cpp
kiorisyshen/learning_slambook
9f47cca96b5c555ac854d08f05f5ebefe3d78cc8
[ "MIT" ]
null
null
null
visualExamples/ch4/trajectoryError/trajectoryError.cpp
kiorisyshen/learning_slambook
9f47cca96b5c555ac854d08f05f5ebefe3d78cc8
[ "MIT" ]
1
2021-11-08T23:02:29.000Z
2021-11-08T23:02:29.000Z
/** * @file trajectoryError.cpp * @author Sijie Shen (kiorisyshen@gmail.com) * @brief * @version 0.1 * @date 2020-10-29 * * @copyright Copyright (c) 2020 * */ #include "config.hpp" #include "common/glfwEntry.hpp" #include <sophus/se3.hpp> #include <iostream> #include <fstream> using namespace Sophus; using namespace std; string groundtruth_file = string(CURREXAMPLE_ROOT) + string("/groundtruth.txt"); string estimated_file = string(CURREXAMPLE_ROOT) + string("/estimated.txt"); typedef vector<Sophus::SE3d, Eigen::aligned_allocator<Sophus::SE3d>> TrajectoryType; TrajectoryType ReadTrajectory(const string &path); // drawing with x3d X3D::X3DGate x3dGate; void DrawTrajectory(const TrajectoryType &gt, const TrajectoryType &esti); int main() { TrajectoryType groundtruth = ReadTrajectory(groundtruth_file); TrajectoryType estimated = ReadTrajectory(estimated_file); assert(!groundtruth.empty() && !estimated.empty()); assert(groundtruth.size() == estimated.size()); // compute rmse double rmse = 0; for (size_t i = 0; i < estimated.size(); i++) { Sophus::SE3d p1 = estimated[i], p2 = groundtruth[i]; double error = (p2.inverse() * p1).log().norm(); rmse += error * error; } rmse = rmse / double(estimated.size()); rmse = sqrt(rmse); cout << "RMSE = " << rmse << endl; DrawTrajectory(groundtruth, estimated); return 0; } /*******************************************************************************************/ TrajectoryType ReadTrajectory(const string &path) { ifstream fin(path); TrajectoryType trajectory; if (!fin) { cerr << "trajectory " << path << " not found." << endl; return trajectory; } while (!fin.eof()) { double time, tx, ty, tz, qx, qy, qz, qw; fin >> time >> tx >> ty >> tz >> qx >> qy >> qz >> qw; Sophus::SE3d p1(Eigen::Quaterniond(qw, qx, qy, qz), Eigen::Vector3d(tx, ty, tz)); trajectory.push_back(p1); } return trajectory; } void DrawTrajectory(const TrajectoryType &gt, const TrajectoryType &esti) { GLFWwindow *win = glfwEntry::initialize("trajectoryError", 1024, 768, 0, 0, 0, &x3dGate); vector<float> vertPos; vector<float> vertColor; uint32_t trajObjID = 0; uint32_t esti_offset = (gt.size() - 1) * 6; vertPos.resize(esti_offset + (esti.size() - 1) * 6); vertColor.resize(vertPos.size()); fill(vertColor.begin(), vertColor.end(), 0.0); for (size_t i = 0; i < gt.size() - 1; i++) { auto p1 = gt[i], p2 = gt[i + 1]; vertPos[i * 6] = p1.translation()[0]; vertPos[i * 6 + 1] = p1.translation()[1]; vertPos[i * 6 + 2] = p1.translation()[2]; vertPos[i * 6 + 3] = p2.translation()[0]; vertPos[i * 6 + 4] = p2.translation()[1]; vertPos[i * 6 + 5] = p2.translation()[2]; vertColor[i * 6 + 2] = 1.0; // blue for ground truth vertColor[i * 6 + 5] = 1.0; } for (size_t i = 0; i < esti.size() - 1; i++) { auto p1 = esti[i], p2 = esti[i + 1]; vertPos[esti_offset + i * 6] = p1.translation()[0]; vertPos[esti_offset + i * 6 + 1] = p1.translation()[1]; vertPos[esti_offset + i * 6 + 2] = p1.translation()[2]; vertPos[esti_offset + i * 6 + 3] = p2.translation()[0]; vertPos[esti_offset + i * 6 + 4] = p2.translation()[1]; vertPos[esti_offset + i * 6 + 5] = p2.translation()[2]; vertColor[esti_offset + i * 6] = 1.0; // red for ground truth vertColor[esti_offset + i * 6 + 3] = 1.0; } x3dGate.AddLines("gt_and_esti", vertPos, vertColor, {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, [&](uint32_t objID) { if (trajObjID == 0) { trajObjID = objID; } }); bool show_debug = false; while (!glfwWindowShouldClose(win)) { glfwEntry::beginFrame(win); { ImGui::Begin("Test info"); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); if (ImGui::Button("Toggle debug")) { x3dGate.ToggleDebug(); show_debug = !show_debug; } ImGui::End(); } glfwEntry::endFrame(win); } x3dGate.DeleteObject(trajObjID, [](bool ret) {}); glfwEntry::finalize(); }
32.510638
134
0.552356
kiorisyshen
c32cba259a53fa074573c971503934a64a51331a
1,446
cc
C++
main.cc
rtpax/redblack
6fcf09afb1ec7cae43adc7dfe28ccd0ad8cace78
[ "MIT" ]
null
null
null
main.cc
rtpax/redblack
6fcf09afb1ec7cae43adc7dfe28ccd0ad8cace78
[ "MIT" ]
null
null
null
main.cc
rtpax/redblack
6fcf09afb1ec7cae43adc7dfe28ccd0ad8cace78
[ "MIT" ]
null
null
null
#include "rb_tree.hh" #include <iostream> #include <string> #include <vector> #include <random> #include <chrono> #include <set> int main(int argc, char ** argv) { rb_tree<int> a = { 9,8,7,6,5,4,3,2,1,10 }; char break_char = '/'; int i = 1; for(; i < argc && argv[i][0] != break_char; ++i) { a.insert(std::stoi(argv[i])); } for(int i : a) { std::cout << i << ", "; } std::cout << "\n"; for(i = i + 1; i < argc; ++i) { auto it = a.find(std::stoi(argv[i])); if(it != a.end()) a.erase(it); } for(int i : a) { std::cout << i << ", "; } std::cout << "\n\n"; //compare insertion speeds auto now = [](){ return std::chrono::high_resolution_clock::now().time_since_epoch().count(); }; std::vector<int> base; std::mt19937 rng(now()); for(int i = 0; i < 100000; ++i) { base.push_back(rng()); } auto rb_start = now(); rb_tree<int> rb_tmp(base.begin(), base.end()); auto rb_end = now(); std::cout << "rb_tree<int>:\n" << " time: " << (rb_end - rb_start) << "\n" << " size: " << rb_tmp.size() << "\n"; auto set_start = now(); std::set<int> set_tmp(base.begin(), base.end()); auto set_end = now(); std::cout << "std::set<int>:\n" << " time: " << (set_end - set_start) << "\n" << " size: " << set_tmp.size() << "\n"; }
21.909091
100
0.470954
rtpax
c33662713fcaca261702640c6f7aee9e808fdc48
13,633
hpp
C++
idlib-math-geometry/library/src/idlib/math_geometry/plane.hpp
egoboo/idlib
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
[ "MIT" ]
1
2021-07-30T14:02:43.000Z
2021-07-30T14:02:43.000Z
idlib-math-geometry/library/src/idlib/math_geometry/plane.hpp
egoboo/idlib
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
[ "MIT" ]
null
null
null
idlib-math-geometry/library/src/idlib/math_geometry/plane.hpp
egoboo/idlib
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
[ "MIT" ]
2
2017-01-27T16:53:08.000Z
2017-08-27T07:28:43.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////// // // Idlib: A C++ utility library // Copyright (C) 2017-2018 Michael Heilmann // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // /////////////////////////////////////////////////////////////////////////////////////////////////// /// @file idlib/math_geometry/plane.hpp /// @brief Planes in three-dimensional space. /// @author Michael Heilmann #pragma once #include "idlib/math/point.hpp" #include "idlib/crtp.hpp" namespace idlib { template <typename P> struct plane; /// @brief A plane. /// @detail A plane can be defined in terms of a unit normal vector \f$\hat{n}\f$ and a distance from the origin. /// The set of points of the plane is then defined as /// \f$\{ X | \hat{n} \cdot X + d = 0 \}\f$ /// which is called the normal-distance form of a plane. template <typename S> struct plane<point<vector<S,3>>> : public equal_to_expr<plane<point<vector<S,3>>>> { public: /// @brief The point type of this plane type. using point_type = point<vector<S,3>>; /// @brief The vector type of this plane type. using vector_type = typename point_type::vector_type; /// @brief The scalar type of this plane type. using scalar_type = typename point_type::scalar_type; /// @brief The dimensionality of this point type. /// @return the dimensionality static constexpr size_t dimensionality() { return vector_type::dimensionality(); } /// @brief Construct this plane with the default values of a plane. /// @remark The default values of a plane are a normal \f$\hat{n} = \left(0,0,1\right)\f$ and,0,1) and a distance from the origin \f$d = 0\f$. plane() : m_normal(zero<scalar_type>(), zero<scalar_type>(), one<scalar_type>()), m_distance(zero<scalar_type>()) {} /** * @brief Create a plane from a plane equation \f$a + b + c + d = 0\f$. * @param a, b, c, d the plane equation * @remark * Given a plane equation \f$a + b + c + d = 0\f$, the normal-distance form * \f$(\hat{n}',d')\f$ is defined as \f$\hat{n}' = \frac{\vec{n}}{|\vec{n}'|}\f$ * and \f$d' = \frac{d}{|\vec{n}'|}\f$ where \f$\vec{n}' = (a,b,c)\f$. */ plane(const scalar_type& a, const scalar_type& b, const scalar_type& c, const scalar_type& d) : m_normal(a, b, c), m_distance(d) { auto l = euclidean_norm(m_normal); if (zero<scalar_type>() == l) { throw std::domain_error("normal vector is zero vector"); } auto j = one<scalar_type>() / l; m_normal *= j; m_distance *= j; } /** * @brief Construct a plane from three non-collinear points. * @param a, b, c the points * @throw std::domain_error the points are collinear * @remark * Assume \f$a\f$, \f$b\f$ and \f$c\f$ are not collinear. Let \f$u = b - a\f$, * \f$v = c - a\f$, \f$n = u \times v\f$, \f$\hat{n} = \frac{n}{|n|}\f$ and * \f$d = -\left(\hat{n} \cdot a\right)\f$. * We show that \f$a\f$, \f$b\f$ and \f$c\f$ are on the plane given by the * equation \f$\hat{n} \cdot p + d = 0\f$. To show this for \f$a\f$, * rewrite the plane equation to * \f{eqnarray*}{ * \hat{n} \cdot p + -(\hat{n} \cdot a) = 0\\ * \f} * shows for \f$p=a\f$ immediatly that \f$a\f$ is on the plane. * @remark * To show that \f$b\f$ and \f$c\f$ are on the plane, * the plane equation is rewritten yet another time using * the bilinearity property of the dot product and * the definitions of \f$d\f$ and \f$\hat{n}\f$: * \f{align*}{ * &\hat{n} \cdot p + -(\hat{n} \cdot a) \;\;\text{Def. of } d\\ * =&\hat{n} \cdot p + \hat{n} \cdot (-a) \;\;\text{Bilinearity of the dot product}\\ * =&\hat{n} \cdot (p - a) \;\;\text{Bilinearity of the dot product}\\ * =&\frac{n}{|n|} \cdot (p - a) \;\;\text{Def. of } \hat{n}\\ * =&(\frac{1}{|n|}n) \cdot (p - a) \;\;\\ * =&\frac{1}{|n|}(n \cdot (p - a)) \;\;\text{Compatibility of the dot product w. scalar multiplication}\\ * =&n \cdot (p - a) \;\;\\ * =&(u \times v) \cdot (p - a) \;\;\text{Def. of } n * \f} * Let \f$p = b\f$ then * \f{align*}{ * &(u \times v) \cdot (b - a) \;\text{Def. of } u\\ * =&(u \times v) \cdot u\\ * =&0 * \f} * or let \f$p = c\f$ then * \f{align*}{ * &(u \times v) \cdot (c - a) \;\text{Def. of } u\\ * =&(u \times v) \cdot v\\ * =&0 * \f} * as \f$u \times v\f$ is orthogonal to both \f$u\f$ and \f$v\f$. * This shows that \f$b\f$ and \f$c\f$ are on the plane. */ plane(const point_type& a, const point_type& b, const point_type& c) { auto u = b - a; if (u == zero<vector_type>()) { throw std::domain_error("b = a"); } auto v = c - a; if (u == zero<vector_type>()) { throw std::domain_error("c = a"); } m_normal = cross_product(u, v); auto r = normalize(m_normal, euclidean_norm_functor<vector_type>{}); if (r.get_length() == zero<scalar_type>()) { /* u x v = 0 is only possible for u, v != 0 if u = v and thus b = c. */ throw std::domain_error("b = c"); } m_normal = r.get_vector(); m_distance = -dot_product(m_normal, semantic_cast<vector_type>(a)); } /** * @brief Construct a plane with a point and a normal. * @param p the point * @param n the normal * @throw std::domain_error the normal vector is the zero vector * @remark The plane normal is normalized if necessary. * @remark * Let \f$X\f$ be the point and \f$\vec{n}\f$ the unnormalized plane normal, then the plane equation is given by * \f{align*}{ * \hat{n} \cdot P + d = 0, \hat{n} = \frac{\vec{n}}{|\vec{n}|}, d = -\left(\hat{n} \cdot X\right) * \f} * \f$X\f$ is on the plane as * \f{align*}{ * & \hat{n} \cdot X + d\\ * =& \hat{n} \cdot X + -(\hat{n} \cdot X)\\ * =& \hat{n} \cdot X - \hat{n} \cdot X\\ * =& 0 * \f} */ plane(const point_type& p, const vector_type& n) : m_normal(n), m_distance(zero<scalar_type>()) { auto r = normalize(m_normal, euclidean_norm_functor<vector_type>{}); if (r.get_length() == zero<scalar_type>()) { throw std::domain_error("normal vector is zero vector"); } m_normal = r.get_vector(); m_distance = -dot_product(m_normal, semantic_cast<vector_type>(p)); } /** * @brief Construct a plane from a direction vector and a distance from the origin. * @param the direction vector * @param d the distance from the origin * @post * Given an axis \f$\vec{t}\f$ and a distance from the origin \f$d\f$ * the plane equation is given by * \f{align*}{ * \hat{n} \cdot p + d = 0, \hat{n} = \frac{\vec{t}}{|\vec{t}|} * \f} * @throw std::domain_error the translation axis is the zero vector */ plane(const vector_type& t, const scalar_type& d) : m_normal(t), m_distance(d) { auto x = normalize(t, euclidean_norm_functor<vector_type>{}); if (x.get_length() == zero<scalar_type>()) { throw std::domain_error("axis vector is zero vector"); } m_normal = x.get_vector(); } plane(const plane&) = default; plane& operator=(const plane&) = default; /// @brief Get the plane normal of this plane. /// @return the plane normal of this plane const vector_type& get_normal() const { return m_normal; } /// @brief Get the distance of this plane from the origin. /// @return the distance of this plane from the origin const scalar_type& get_distance() const { return m_distance; } /** * @brief Get the distance of a point from this plane. * @param point the point * @return the distance of the point from the plane. * The point is in the positive (negative) half-space of the plane if the distance is positive (negative). * Otherwise the point is on the plane. * @remark * Let \f$\hat{n} \cdot P + d = 0\f$ be a plane and \f$v\f$ be some point. * We claim that \f$d'=\hat{n} \cdot v + d\f$ is the signed distance of the point \f$v\f$ from the plane. * To show this, assume \f$v\f$ is not in the plane. * Then there exists a single point \f$u\f$ on the plane which is closest to \f$v\f$ such that \f$v\f$ can * be expressed by translating \f$u\f$ along the plane normal by the signed distance \f$d'\f$ from * \f$u\f$ to \f$v\f$ i.e. \f$v = u + d' \hat{n}\f$. Obviously, * if \f$v\f$ is in the positive (negative) half-space of the plane, then * \f$d'>0\f$ (\f$d' < 0\f$). We obtain now * \f{align*}{ * & \hat{n} \cdot v + d\\ * =& \hat{n} \cdot (u + d' \hat{n}) + d\\ * =& \hat{n} \cdot u + d' (\hat{n} \cdot \hat{n}) + d\\ * =& \hat{n} \cdot u + d' + d\\ * =& \hat{n} \cdot u + d + d'\\ * \f} * However, as \f$u\f$ is on the plane * \f{align*}{ * =& \hat{n} \cdot u + d + d'\\ * =& d' * \f} */ scalar_type distance(const point_type& point) const { return dot_product(get_normal(), semantic_cast<vector_type>(point)) + get_distance(); } /** * @brief Get a point on this plane. * @return a point on this plane * @remark * The point \f$X = (-d) \hat{n}\f$ is guaranteed to be on the plane. * To see that, insert \f$X\f$ into the plane equation: * \f{align*}{ * \hat{n} \cdot X + d = \hat{n} \cdot \left[(-d) \hat{n}\right] + d * = (-d) \left(\hat{n} \cdot \hat{n}\right] + d * \f} * As \f$\hat{n}\f$ is a unit vector * \f{align*}{ * &(-d) \left[\hat{n} \cdot \hat{n}\right] + d\\ * =&-d + d\\ * =&0 * \f} */ vector_type get_point() const { return get_normal() * (-get_distance()); } // CRTP bool equal_to(const plane& other) const { return get_distance() == other.get_distance() && get_normal() == other.get_normal(); } protected: struct cookie {}; friend struct translate_functor<plane, vector_type>; plane(cookie cookie, const vector_type& n, const scalar_type& d) : m_normal(n), m_distance(d) {} private: /// @brief The plane normal. /// @invariant The plane normal is a unit vector. vector_type m_normal; /// @brief The distance of the plane from the origin. scalar_type m_distance; }; // struct plane /// @brief Specialization of idlib::enclose_functor enclosing a plane in a plane. /// @detail The plane \f$b\f$ enclosing a plane \f$a\f$ is \f$a\f$ itself i.e. \f$b = a\f$. /// @tparam P the point type of this plane template <typename P> struct enclose_functor<plane<P>, plane<P>> { auto operator()(const plane<typename P::scalar_type>& source) const { return source; } }; // struct enclose_functor /** * @brief Specialization of idlib::translate_functor. * Translates a plane. * @remark * The first (slow) method to compute the translation of a plane \f$\hat{n} \cdot P + d = 0\f$ * is to compute a point on the plane, translate the point, and compute from the new point and * and the old plane normal the new plane: * To translate a plane \f$\hat{n} \cdot P + d = 0\f$, compute a point on the plane * \f$X\f$ (i.e. a point \f$\hat{n} \cdot X + d = 0\f$) by * \f{align*}{ * X = (-d) \cdot \hat{n} * \f} * Translate the point \f$X\f$ by \f$\vec{t}\f$ into a new point \f$X'\f$: * \f{align*}{ * X' = X + \vec{t} * \f} * and compute the new plane * \f{align*}{ * \hat{n} \cdot P + d' = 0, d' = -\left(\hat{n} \cdot X'\right) * \f} * @remark * The above method is not the fastest method. Observing that the old and the new plane equation only * differ by \f$d\f$ and \f$d'\f$, a faster method of translating a plane can be devised by computing * \f$d'\f$ directly. Expanding \f$d'\f$ gives * \f{align*}{ * d' =& -\left(\hat{n} \cdot X'\right)\\ * =& -\left[\hat{n} \cdot \left((-d) \cdot \hat{n} + \vec{t}\right)\right]\\ * =& -\left[(-d) \cdot \hat{n} \cdot \hat{n} + \hat{n} \cdot \vec{t}\right]\\ * =& -\left[-d + \hat{n} \cdot \vec{t}\right]\\ * =& d - \hat{n} \cdot \vec{t} * \f} * The new plane can then be computed by * \f{align*}{ * \hat{n} \cdot P + d' = 0, d' = d - \hat{n} \cdot \vec{t} * \f} * @tparam P the point type of the plane */ template <typename P> struct translate_functor<plane<P>, typename P::vector_type> { auto operator()(const plane<P>& x, const typename P::vector_type& t) const { return plane<P>(x.get_normal(), x.get_distance() - dot_product(x.get_normal(), t)); } }; // struct translate_functor } // namespace idlib
39.515942
146
0.570527
egoboo
c33cd058c67c3ab6cef9bf4871158ee48e0ebe88
3,387
cpp
C++
src/layers/CvoltonOptionsLayer.cpp
Cvolton/best-epic-gd-mods
fb997b3ba0af5507e7f0f869af975025aba0eb61
[ "MIT" ]
5
2022-02-18T17:08:28.000Z
2022-02-26T15:51:49.000Z
src/layers/CvoltonOptionsLayer.cpp
Cvolton/best-epic-gd-mods
fb997b3ba0af5507e7f0f869af975025aba0eb61
[ "MIT" ]
null
null
null
src/layers/CvoltonOptionsLayer.cpp
Cvolton/best-epic-gd-mods
fb997b3ba0af5507e7f0f869af975025aba0eb61
[ "MIT" ]
null
null
null
#include "CvoltonOptionsLayer.h" #include "../managers/CvoltonManager.h" #include <cocos2d.h> #include <gd.h> using namespace cocos2d; using namespace gd; CvoltonOptionsLayer* CvoltonOptionsLayer::create(){ auto ret = new CvoltonOptionsLayer(); if (ret && ret->init()) { //robert 1 :D ret->autorelease(); } else { //robert -1 delete ret; ret = nullptr; } return ret; } void CvoltonOptionsLayer::onClose(cocos2d::CCObject* sender) { auto CM = CvoltonManager::sharedState(); CM->save(); destroyToggles(); setKeypadEnabled(false); removeFromParentAndCleanup(true); } bool CvoltonOptionsLayer::init(){ bool init = createBasics({300.0f, 200.0f}, menu_selector(CvoltonOptionsLayer::onClose), 0.8f); if(!init) return false; auto winSize = CCDirector::sharedDirector()->getWinSize(); createTextLabel("Mod Settings", {(winSize.width / 2),(winSize.height / 2) + 78}, 0.7f, m_pLayer, "goldFont.fnt"); drawToggles(); return true; } CCLabelBMFont* CvoltonOptionsLayer::createTextLabel(const std::string text, const CCPoint& position, const float scale, CCNode* menu, const char* font){ CCLabelBMFont* bmFont = CCLabelBMFont::create(text.c_str(), font); bmFont->setPosition(position); bmFont->setScale(scale); menu->addChild(bmFont); return bmFont; } void CvoltonOptionsLayer::onToggle(cocos2d::CCObject* sender) { sender->retain(); auto button = static_cast<CCMenuItemSpriteExtra*>(sender); auto CM = CvoltonManager::sharedState(); CM->toggleOption(static_cast<CCString*>(button->getUserData())->getCString()); destroyToggles(); drawToggles(); sender->release(); } void CvoltonOptionsLayer::createToggle(const char* option, const char* name){ auto CM = CvoltonManager::sharedState(); auto buttonSprite = CCSprite::createWithSpriteFrameName(CM->getOption(option) ? "GJ_checkOn_001.png" : "GJ_checkOff_001.png"); buttonSprite->setScale(0.8f); auto button = gd::CCMenuItemSpriteExtra::create( buttonSprite, this, menu_selector(CvoltonOptionsLayer::onToggle) ); m_pButtonMenu->addChild(button); float y = 45.f - (toggleCount++ * 40.f); button->setPosition({-127, y}); auto optionString = CCString::create(option); optionString->retain(); button->setUserData(optionString); button->setSizeMult(1.2f); auto label = createTextLabel(name, {-107, y}, 0.5f, m_pButtonMenu); label->setAnchorPoint({0,0.5f}); } void CvoltonOptionsLayer::destroyToggles(){ //starting at 1 because 0 is the close button unsigned int totalMembers = m_pButtonMenu->getChildrenCount(); for(unsigned int i = 1; i < totalMembers; i++){ //static index 1 because we're actively moving the elements auto object = static_cast<CCNode*>(m_pButtonMenu->getChildren()->objectAtIndex(1)); auto userData = object->getUserData(); if(userData != nullptr) static_cast<CCString*>(userData)->release(); //m_pButtonMenu->removeChild(object, false); object->removeFromParent(); } toggleCount = 0; } void CvoltonOptionsLayer::drawToggles(){ createToggle("no_update_check", "Disable Update Check"); createToggle("no_green_user", "Disable Green Username Fix"); createToggle("no_level_info", "Disable Extended Level Info"); }
32.257143
152
0.683791
Cvolton
c34ec6a6828b95af6ec55993e26e860b2442fe57
1,329
cpp
C++
SVEngine/src/mtl/SVMtlBillboard.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/mtl/SVMtlBillboard.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/mtl/SVMtlBillboard.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVMtlBillboard.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVMtlBillboard.h" #include "../mtl/SVTexture.h" #include "../rendercore/SVRenderer.h" #include "../basesys/SVCameraMgr.h" #include "../node/SVCameraNode.h" SVMtlBillboard::SVMtlBillboard(SVInst *_app) :SVMtlCore(_app,"normal3d_billboard") { m_objPos.set(0, 0, 0); m_viewPos.set(0, 0, 0); m_up.set(0, 0, 0); } SVMtlBillboard::SVMtlBillboard(SVMtlBillboard *_mtl) :SVMtlCore(_mtl){ m_objPos = _mtl->m_objPos; m_viewPos = _mtl->m_viewPos; m_up = _mtl->m_up; } SVMtlBillboard::~SVMtlBillboard() { } SVMtlCorePtr SVMtlBillboard::clone() { return PointerSharedPtr<SVMtlBillboard>(new SVMtlBillboard(this)); } void SVMtlBillboard::reset() { SVMtlCore::reset(); } void SVMtlBillboard::setObjectPos(FVec3 &_pos){ m_objPos.set(_pos); } void SVMtlBillboard::setViewPos(FVec3 &_viewPos){ m_viewPos.set(_viewPos); } void SVMtlBillboard::setUp(FVec3 &_up){ m_up.set(_up); } void SVMtlBillboard::_submitUniform(SVRendererPtr _render) { SVMtlCore::_submitUniform(_render); _render->submitUniformf3v("u_up", m_up.get()); _render->submitUniformf3v("u_viewPos", m_viewPos.get()); _render->submitUniformf3v("u_objPos", m_objPos.get()); }
22.913793
70
0.708804
SVEChina
c34fda69b78394c1a198ecd33a3406d798f19404
5,625
cpp
C++
Source/CADialogue/Private/CADialogueInstanceComponent.cpp
cmacnair/Catch-All-Dialogue-UE4
f2cf5b5b658471ab47afeb047dbe25f6100c3bf7
[ "MIT" ]
1
2020-05-28T07:04:17.000Z
2020-05-28T07:04:17.000Z
Source/CADialogue/Private/CADialogueInstanceComponent.cpp
cmacnair/Catch-All-Dialogue-UE4
f2cf5b5b658471ab47afeb047dbe25f6100c3bf7
[ "MIT" ]
null
null
null
Source/CADialogue/Private/CADialogueInstanceComponent.cpp
cmacnair/Catch-All-Dialogue-UE4
f2cf5b5b658471ab47afeb047dbe25f6100c3bf7
[ "MIT" ]
null
null
null
#include "CADialogueInstanceComponent.h" #include <Stats/Stats.h> #include "CADialogueSubsystem.h" #include "CADialogueSpeakerDataAsset.h" UCADialogueInstanceComponent::UCADialogueInstanceComponent() : bRegisterOnBeginPlay(true) , bDeregisterOnEndPlay(true) , bCheckQueueDuringTick(true) { SetTickGroup(TG_PostUpdateWork); PrimaryComponentTick.bCanEverTick = true; } bool UCADialogueInstanceComponent::HasRule(FGameplayTag RequiredRule) { return RulesTags.HasTag(RequiredRule); } bool UCADialogueInstanceComponent::HasRules(FGameplayTagContainer RequiredRulesContianer) { return RulesTags.HasAll(RequiredRulesContianer); } void UCADialogueInstanceComponent::ReceiveEvent(FCADialogueEvent Event) { DialogueEventReceivedEvent.Broadcast(); } bool UCADialogueInstanceComponent::FilterEvent(FCADialogueEvent Event) { UCADialogueSubsystem* DialogueSubsystem = UCADialogueSubsystem::GetDialogueSubsystem(this); ensure(DialogueSubsystem); return DialogueSubsystem->CanSpeakerPlayForInstance(Event.SpeakerTag, InstanceTag); } void UCADialogueInstanceComponent::AddEventToQueue(FCADialogueEvent Event) { Event.SetTimeStamp(UCADialogueSubsystem::GetCurrentTime(this)); EventQueue.Add(Event); } void UCADialogueInstanceComponent::ClearExpiredEventsInQueue() { DECLARE_SCOPE_CYCLE_COUNTER(TEXT("ClearExpiredEvents"), STAT_CADialogueClearExpiredEvents, STATGROUP_CADialogue); if (!EventQueue.Num()) return; float CurrentTime = UCADialogueSubsystem::GetCurrentTime(this); for (uint8 EventQueueIter = EventQueue.Num() - 1; EventQueueIter >= 0; --EventQueueIter) { float ElapsedTimeSinceEnteredQueue = CurrentTime - EventQueue[EventQueueIter].GetTimeStamp(); if (ElapsedTimeSinceEnteredQueue > EventQueue[EventQueueIter].QueueWaitTime) { EventQueue.RemoveAt(EventQueueIter); } } } void UCADialogueInstanceComponent::AddRule(FGameplayTag InRuleTag) { RulesTags.AddTag(InRuleTag); } void UCADialogueInstanceComponent::AddRules(FGameplayTagContainer InRulesContainer) { RulesTags.AppendTags(InRulesContainer); } void UCADialogueInstanceComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if (bCheckQueueDuringTick) { ClearExpiredEventsInQueue(); } } void UCADialogueInstanceComponent::BeginPlay() { Super::BeginPlay(); if (bRegisterOnBeginPlay) RegisterInstance(); } void UCADialogueInstanceComponent::EndPlay(const EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); DeregisterInstance(); } const TArray<class USoundBase*> UCADialogueInstanceComponent::GetListOfAllSounds() const { TArray<class USoundBase*> SoundsFound; if (SpeakerAudioData) { for (auto& AudioBucketsIter : SpeakerAudioData->SpeakerAudioData) { for (auto& AudioBucketIter : AudioBucketsIter.Value.EventAudioBucketMap) { for (auto& SoundIter : AudioBucketIter.Value.Sounds) { SoundsFound.Add(SoundIter.Sound); } } } } return SoundsFound; } #if CADIALOGUE_DEBUG void UCADialogueInstanceComponent::MakeDebugReport() { /* const FString PathName = FPaths::ProfilingDir() + TEXT("dir/") + DirectoryName; IFileManager::Get().MakeDirectory(*PathName); const FString FileName = TEXT("dump.txt"); const FString FilenameFull = PathName + FileName; FFileHelper::SaveStringToFile(FileContainer.FileContents, *FilenameFull); UE_LOG(dump, Log, TEXT("SVRStats Dump: Saved file to: %s"), *FilenameFull); */ } #endif void UCADialogueInstanceComponent::RegisterInstance() { //QUICK_SCOPE_CYCLE_COUNTER(TEXT("CADialogue::RegisterInstance")); DECLARE_SCOPE_CYCLE_COUNTER(TEXT("RegisterInstance"), STAT_CADialogueRegisterInstance, STATGROUP_CADialogue); UCADialogueSubsystem* DialogueSubsystem = UCADialogueSubsystem::GetDialogueSubsystem(this); ensure(DialogueSubsystem); DialogueSubsystem->RegisterInstance(this); } void UCADialogueInstanceComponent::DeregisterInstance() { UCADialogueSubsystem* DialogueSubsystem = UCADialogueSubsystem::GetDialogueSubsystem(this); ensure(DialogueSubsystem); DialogueSubsystem->DeregisterInstance(InstanceTag); } class USoundBase* UCADialogueInstanceComponent::GetSoundForSpeakerWithEvent(FGameplayTag SpeakerTag, FGameplayTag EventTag) { DECLARE_SCOPE_CYCLE_COUNTER(TEXT("GetSoundForEvent"), STAT_CADialogueGetSoundForEvent, STATGROUP_CADialogue); if (!SpeakerAudioData) return nullptr; if (!SpeakerAudioData->SpeakerAudioData.Contains(SpeakerTag)) return nullptr; FCADialogueSpeakerAudioBuckets& SpeakerBuckets = SpeakerAudioData->SpeakerAudioData[SpeakerTag]; FCADialogueAudioBucket EventBucket; bool bFoundBucketForEvent = SpeakerBuckets.GetBucketForEvent(EventTag, EventBucket); if (!bFoundBucketForEvent) return nullptr; return EventBucket.GetSound(); } void UCADialogueInstanceComponent::BroadcastSoundToSpeakers(FGameplayTag SpeakerTag, FGameplayTag EventTag, class USoundBase* SoundToPlay) { UCADialogueSubsystem* DialogueSubsystem = UCADialogueSubsystem::GetDialogueSubsystem(this); FCADialogueSpeakerCollection Speakers; DialogueSubsystem->GetSpeakersForTag(SpeakerTag, Speakers); FCADialogueSpeakerParams SpeakerParams(SoundToPlay, InstanceTag, EventTag); SpeakerParams.DialogueFinishedCallback = [this](FGameplayTag EventTag, FGameplayTag SpeakerTag) { DialogueFinishedCallbackFunc(EventTag, SpeakerTag); }; Speakers.PlaySoundOnAllSpeakers(SpeakerParams); }
30.241935
139
0.7888
cmacnair
c358ba043b1e7e9d30ea0243fb7949c1615cb752
5,634
hpp
C++
src/ZerEngine/Logic/Query.hpp
ZerethjiN/ZerEngine-ECS
1766b70042076cbc7899e5b2261588c6e3b34729
[ "MIT" ]
1
2022-02-22T12:22:11.000Z
2022-02-22T12:22:11.000Z
src/ZerEngine/Logic/Query.hpp
ZerethjiN/ZerEngine-ECS
1766b70042076cbc7899e5b2261588c6e3b34729
[ "MIT" ]
null
null
null
src/ZerEngine/Logic/Query.hpp
ZerethjiN/ZerEngine-ECS
1766b70042076cbc7899e5b2261588c6e3b34729
[ "MIT" ]
null
null
null
/** * @file Query.hpp * @author ZerethjiN * @brief Get and iterate queries by necessary Component, * Filter and Exclusion Type. * @version 0.1 * @date 2022-02-22 * * @copyright Copyright (c) 2022 - ZerethjiN * */ #ifndef ZERENGINE_VIEW_HPP #define ZERENGINE_VIEW_HPP #include <vector> #include <algorithm> #include <functional> #include <iterator> #include "TypeUtilities.hpp" #include "CompPool.hpp" namespace zre { template <typename, typename, typename, typename, typename> class Query; template <typename Comp, typename... Comps, typename... Filters, typename... Excludes, typename... Optionnals> class Query<Comp, priv::comp_t<Comps...>, priv::With<Filters...>, priv::Without<Excludes...>, priv::OrWith<Optionnals...>> { public: constexpr Query(priv::CompPool<Comp>& comp, priv::CompPool<Comps>&... comps, priv::CompPool<Filters>&... fltrs, priv::CompPool<Excludes>&... excls, priv::CompPool<Optionnals>&... options) noexcept: pools(comp, comps...) { genEnts(comp); if constexpr (sizeof...(comps) > 0) intersectRec(comps...); if constexpr (sizeof...(fltrs) > 0) intersectRec(fltrs...); if constexpr (sizeof...(options) > 0) intersectWith(unionRec(std::vector<Ent>(), options...)); if constexpr (sizeof...(excls) > 0) differenceRec(excls...); } [[nodiscard]] constexpr size_t size() const noexcept { return ents.size(); } [[nodiscard]] constexpr const std::vector<Ent>::iterator begin() noexcept { return ents.begin(); } [[nodiscard]] constexpr const std::vector<Ent>::iterator end() noexcept { return ents.end(); } template <typename Func> constexpr void each(const Func& func) const noexcept { for ([[maybe_unused]] const auto ent: ents) { if constexpr (std::is_invocable<Func, Ent, Comp&, Comps&...>::value) { std::apply(func, std::tuple_cat(std::make_tuple(ent), genTuple<std::tuple<>, decltype(pools)>(ent, std::tuple<>()))); } else if constexpr (std::is_invocable<Func, Comp&, Comps&...>::value) { std::apply(func, genTuple<std::tuple<>, decltype(pools)>(ent, std::tuple<>())); } else if constexpr (std::is_invocable<Func, Ent>::value) { std::apply(func, std::make_tuple(ent)); } else { func(); } } } private: template <typename Tup, typename Pools, size_t Index = 0> [[nodiscard]] constexpr decltype(auto) genTuple(Ent ent, Tup tup) const noexcept { auto newTup = std::tuple_cat(tup, std::make_tuple(std::ref(std::get<Index>(pools).get(ent)))); if constexpr (Index < std::tuple_size<Pools>::value - 1) return genTuple<decltype(newTup), Pools, Index + 1>(ent, newTup); else return newTup; } template <typename Pool> constexpr void genEnts(Pool& comp) { ents = comp.getEnts(); } template <typename CompPool, typename... CompPools> constexpr void intersectRec(CompPool& comp, CompPools&... compPools) noexcept { intersectWith(comp.getEnts()); if constexpr (sizeof...(CompPools) > 0) intersectRec(compPools...); } template <typename OrPool, typename... OrPools> constexpr const std::vector<Ent> unionRec(const std::vector<Ent> oldEnts, OrPool& orPool, OrPools&... orPools) noexcept { auto newEnts = unionWith(oldEnts, orPool.getEnts()); if constexpr (sizeof...(OrPools) > 0) return unionRec(newEnts, orPools...); else return newEnts; } template <typename ExclPool, typename... ExclPools> constexpr void differenceRec(ExclPool& excl, ExclPools&... exclPools) noexcept { differenceWith(excl.getEnts()); if constexpr (sizeof...(ExclPools) > 0) differenceRec(exclPools...); } constexpr void intersectWith(const std::vector<Ent>& other) noexcept { std::vector<Ent> tmpEnts; std::set_intersection( ents.begin(), ents.end(), other.begin(), other.end(), std::back_inserter(tmpEnts) ); ents.swap(tmpEnts); } constexpr const std::vector<Ent> unionWith(const std::vector<Ent>& entA, const std::vector<Ent>& entB) noexcept { std::vector<Ent> tmpEnts; std::set_union( entA.begin(), entA.end(), entB.begin(), entB.end(), std::back_inserter(tmpEnts) ); return tmpEnts; } constexpr void differenceWith(const std::vector<Ent>& other) noexcept { std::vector<Ent> tmpEnts; std::set_difference( ents.begin(), ents.end(), other.begin(), other.end(), std::back_inserter(tmpEnts) ); ents.swap(tmpEnts); } private: const std::tuple<priv::CompPool<Comp>&, priv::CompPool<Comps>&...> pools; std::vector<Ent> ents; }; } #endif // ZERENGINE_VIEW_HPP
37.56
206
0.538871
ZerethjiN
c35a99931796bf519defa205d44427c647516e33
928
cpp
C++
example/example.cpp
yhirose/cpp-zipper
865ae774f28e7675e01821fd554235f38c1fc79d
[ "MIT" ]
5
2021-11-19T03:23:54.000Z
2022-03-10T11:39:39.000Z
example/example.cpp
yhirose/cpp-zipper
865ae774f28e7675e01821fd554235f38c1fc79d
[ "MIT" ]
null
null
null
example/example.cpp
yhirose/cpp-zipper
865ae774f28e7675e01821fd554235f38c1fc79d
[ "MIT" ]
null
null
null
#include <filesystem> #include <iostream> #include "zipper.h" namespace fs = std::filesystem; int main() { { zipper::Zip zip("test_copy.zip"); zipper::enumerate("test.zip", [&zip](auto &unzip) { if (unzip.is_dir()) { zip.add_dir(unzip.file_path()); } else { std::string buf; if (unzip.read(buf)) { zip.add_file(unzip.file_path(), buf); } } }); } { zipper::UnZip zip0("test.zip"); zipper::UnZip zip1("test_copy.zip"); do { assert(zip0.is_dir() == zip1.is_dir()); assert(zip0.is_file() == zip1.is_file()); assert(zip0.file_path() == zip1.file_path()); assert(zip0.file_size() == zip1.file_size()); if (zip0.is_file()) { std::string buf0, buf1; assert(zip0.read(buf0) == zip1.read(buf1)); assert(buf0 == buf1); } } while (zip0.next() && zip1.next()); } return 0; }
21.090909
55
0.539871
yhirose
c37116e69d9b05bdeb8af656b9608d5b9d667512
20,878
cpp
C++
bin/test-libsept/test_serialization.cpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
bin/test-libsept/test_serialization.cpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
bin/test-libsept/test_serialization.cpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
// 2020.08.03 - Victor Dods #include <iomanip> #include <iostream> #include <limits> #include <lvd/req.hpp> #include <lvd/test.hpp> #include "sept/ArrayTerm.hpp" #include "sept/ctl/ClearOutput.hpp" #include "sept/ctl/EndOfFile.hpp" #include "sept/ctl/Output.hpp" #include "sept/ctl/RequestSyncInput.hpp" #include "sept/OrderedMapTerm.hpp" #include <sstream> class AsHex { public: AsHex () = delete; AsHex (std::string const &str) : m_str(str) { } AsHex (std::string &&str) : m_str(std::move(str)) { } template <typename... Args_> explicit AsHex (Args_&&... args) : m_str(std::forward<Args_>(args)...) { } std::string const &str () const { return m_str; } private: std::string m_str; }; std::ostream &operator << (std::ostream &out, AsHex const &a) { std::ostringstream s_out; s_out << std::hex; size_t i = 0; for (uint8_t c : a.str()) { if (i > 0) { if (i % 0x10 == 0) s_out << '\n'; else s_out << ' '; } s_out << std::setw(2) << std::setfill('0') << int(c); ++i; } s_out << '\n'; return out << s_out.str(); } template <typename T_> void test_serialization_roundtrip (lvd::Log &test_log, lvd::req::Context &req_context, T_ const &t) { // There are two kinds of serialization to test: // - Direct type serialization (e.g. sept::serialize(sept::ArrayTerm_c const &, std::ostream &out)) // - sept::Data serialization (i.e. sept::serialize_data(sept::Data const &, std::ostream &out)) using DecayedT_ = std::decay_t<T_>; // test_log << lvd::Log::dbg() << "test_serialization_roundtrip;\n value is " << LVD_REFLECT(t) << "\n " << LVD_REFLECT(typeid(T_)) << "\n " << LVD_REFLECT(typeid(DecayedT_)) << '\n'; sept::Data expected_data{t}; // Direct type serialization { std::ostringstream out; sept::serialize(t, out); test_log << lvd::Log::dbg() << "Raw-typed value " << LVD_REFLECT(t) << " serializes as:\n" << lvd::IndentGuard() << AsHex(out.str()); std::istringstream in(out.str()); auto actual_data = sept::deserialize_data(in); // test_log << lvd::Log::dbg() << "Actual, deserialized data:\n value is " << actual_data << "\n " << LVD_REFLECT(actual_data.type()) << '\n'; in.peek(); // To ensure we arrive at EOF if it's there. LVD_TEST_REQ_IS_TRUE(in.eof()); // LVD_TEST_REQ_IS_TRUE(actual_data.can_cast<DecayedT_>()); if (actual_data.can_cast<DecayedT_>()) LVD_TEST_REQ_EQ(actual_data.cast<DecayedT_ const &>(), t); LVD_TEST_REQ_EQ(actual_data, expected_data); } // sept::Data serialization { // Make sure the round trip preserves the data. std::ostringstream out; sept::serialize_data(expected_data, out); test_log << lvd::Log::dbg() << "Data " << LVD_REFLECT(expected_data) << " serializes as:\n" << lvd::IndentGuard() << AsHex(out.str()); std::istringstream in(out.str()); auto actual_data = sept::deserialize_data(in); // test_log << lvd::Log::dbg() << "Actual, deserialized data:\n value is " << actual_data << "\n " << LVD_REFLECT(actual_data.type()) << '\n'; in.peek(); // To ensure we arrive at EOF if it's there. LVD_TEST_REQ_IS_TRUE(in.eof()); // LVD_TEST_REQ_IS_TRUE(actual_data.can_cast<DecayedT_>()); if (actual_data.can_cast<DecayedT_>()) LVD_TEST_REQ_EQ(actual_data.cast<DecayedT_ const &>(), t); LVD_TEST_REQ_EQ(actual_data, expected_data); } } #define TEST_SERIALIZATION_ROUNDTRIP(t) test_serialization_roundtrip(test_log, req_context, t) LVD_TEST_BEGIN(595__serialization__000__NonParametricTerm) TEST_SERIALIZATION_ROUNDTRIP(sept::Term); TEST_SERIALIZATION_ROUNDTRIP(sept::NonParametricTerm); // TEST_SERIALIZATION_ROUNDTRIP(sept::ParametricTerm); auto term = sept::Term; TEST_SERIALIZATION_ROUNDTRIP(term); auto non_parametric_term = sept::NonParametricTerm; TEST_SERIALIZATION_ROUNDTRIP(non_parametric_term); // auto parametric_term = sept::ParametricTerm; // TEST_SERIALIZATION_ROUNDTRIP(parametric_term); TEST_SERIALIZATION_ROUNDTRIP(sept::Type); TEST_SERIALIZATION_ROUNDTRIP(sept::NonType); TEST_SERIALIZATION_ROUNDTRIP(sept::NonParametricType); // TEST_SERIALIZATION_ROUNDTRIP(sept::ParametricType); TEST_SERIALIZATION_ROUNDTRIP(sept::Void); TEST_SERIALIZATION_ROUNDTRIP(sept::True); TEST_SERIALIZATION_ROUNDTRIP(sept::False); TEST_SERIALIZATION_ROUNDTRIP(sept::VoidType); TEST_SERIALIZATION_ROUNDTRIP(sept::TrueType); TEST_SERIALIZATION_ROUNDTRIP(sept::FalseType); TEST_SERIALIZATION_ROUNDTRIP(sept::EmptyType); TEST_SERIALIZATION_ROUNDTRIP(sept::Bool); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint8); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint16); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint32); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint64); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint8); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint16); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint32); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint64); TEST_SERIALIZATION_ROUNDTRIP(sept::Float32); TEST_SERIALIZATION_ROUNDTRIP(sept::Float64); TEST_SERIALIZATION_ROUNDTRIP(sept::BoolType); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint8Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint16Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint32Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Sint64Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint8Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint16Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint32Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Uint64Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Float32Type); TEST_SERIALIZATION_ROUNDTRIP(sept::Float64Type); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayType); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS); TEST_SERIALIZATION_ROUNDTRIP(sept::Array); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapType); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMap); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::OutputType); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::Output); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::ClearOutputType); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::ClearOutput); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::EndOfFileType); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::EndOfFile); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInputType); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInput); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__100__ParametricTerm__POD) TEST_SERIALIZATION_ROUNDTRIP(true); TEST_SERIALIZATION_ROUNDTRIP(false); // BoolTerm_c and bool are in conflict. Probably don't bother with BoolTerm_c. // TEST_SERIALIZATION_ROUNDTRIP(sept::Bool(true)); // TEST_SERIALIZATION_ROUNDTRIP(sept::Bool(false)); TEST_SERIALIZATION_ROUNDTRIP(int8_t(0)); TEST_SERIALIZATION_ROUNDTRIP(int8_t(1)); TEST_SERIALIZATION_ROUNDTRIP(int8_t(2)); TEST_SERIALIZATION_ROUNDTRIP(int8_t(-1)); TEST_SERIALIZATION_ROUNDTRIP(int8_t(-2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int8_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int8_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(int16_t(0)); TEST_SERIALIZATION_ROUNDTRIP(int16_t(1)); TEST_SERIALIZATION_ROUNDTRIP(int16_t(2)); TEST_SERIALIZATION_ROUNDTRIP(int16_t(-1)); TEST_SERIALIZATION_ROUNDTRIP(int16_t(-2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int16_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int16_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(int32_t(0)); TEST_SERIALIZATION_ROUNDTRIP(int32_t(1)); TEST_SERIALIZATION_ROUNDTRIP(int32_t(2)); TEST_SERIALIZATION_ROUNDTRIP(int32_t(-1)); TEST_SERIALIZATION_ROUNDTRIP(int32_t(-2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int32_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int32_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(int64_t(0)); TEST_SERIALIZATION_ROUNDTRIP(int64_t(1)); TEST_SERIALIZATION_ROUNDTRIP(int64_t(2)); TEST_SERIALIZATION_ROUNDTRIP(int64_t(-1)); TEST_SERIALIZATION_ROUNDTRIP(int64_t(-2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int64_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<int64_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(uint8_t(0)); TEST_SERIALIZATION_ROUNDTRIP(uint8_t(1)); TEST_SERIALIZATION_ROUNDTRIP(uint8_t(2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint8_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint8_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(uint16_t(0)); TEST_SERIALIZATION_ROUNDTRIP(uint16_t(1)); TEST_SERIALIZATION_ROUNDTRIP(uint16_t(2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint16_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint16_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(uint32_t(0)); TEST_SERIALIZATION_ROUNDTRIP(uint32_t(1)); TEST_SERIALIZATION_ROUNDTRIP(uint32_t(2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint32_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint32_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(uint64_t(0)); TEST_SERIALIZATION_ROUNDTRIP(uint64_t(1)); TEST_SERIALIZATION_ROUNDTRIP(uint64_t(2)); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint64_t>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<uint64_t>::min()); TEST_SERIALIZATION_ROUNDTRIP(0.0f); TEST_SERIALIZATION_ROUNDTRIP(1.0f); TEST_SERIALIZATION_ROUNDTRIP(-1.0f); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::min()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::lowest()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::epsilon()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::round_error()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::infinity()); // TODO: Have to test NaN separately, since `NaN == NaN` is false. // TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::quiet_NaN()); // TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::signaling_NaN()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<float>::denorm_min()); TEST_SERIALIZATION_ROUNDTRIP(0.0); TEST_SERIALIZATION_ROUNDTRIP(1.0); TEST_SERIALIZATION_ROUNDTRIP(-1.0); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::min()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::max()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::lowest()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::epsilon()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::round_error()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::infinity()); // TODO: Have to test NaN separately, since `NaN == NaN` is false. // TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::quiet_NaN()); // TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::signaling_NaN()); TEST_SERIALIZATION_ROUNDTRIP(std::numeric_limits<double>::denorm_min()); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__200__Array) TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayType); TEST_SERIALIZATION_ROUNDTRIP(sept::Array); auto a = sept::Array(); TEST_SERIALIZATION_ROUNDTRIP(a); TEST_SERIALIZATION_ROUNDTRIP(sept::Array()); TEST_SERIALIZATION_ROUNDTRIP(sept::Array()); TEST_SERIALIZATION_ROUNDTRIP(sept::Array(1)); TEST_SERIALIZATION_ROUNDTRIP(sept::Array(1,2)); TEST_SERIALIZATION_ROUNDTRIP(sept::Array(1,2,3)); TEST_SERIALIZATION_ROUNDTRIP(sept::Array(1,2.0,true)); TEST_SERIALIZATION_ROUNDTRIP(sept::Array(sept::Array(10,20),sept::Array(55.55,66.66,77.77),sept::Array(sept::True,sept::False,sept::Void))); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__300__ArrayES) TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Bool,3)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Sint8,2)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::VoidType,10)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::EmptyType,10)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Float32,0)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Array,4)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Float32,2)(0.0f, 1.0f)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Bool,3)(sept::True, sept::False, true)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Sint16,2)(int16_t(888), int16_t(20202))); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::VoidType,4)(sept::Void, sept::Void, sept::Void, sept::Void)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::EmptyType,0)()); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayES(sept::Array,3)(sept::Array(), sept::Array(true, 3, 4.4), sept::Array(sept::Term))); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__400__ArrayE) TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Bool)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Sint8)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::VoidType)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::EmptyType)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Float32)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Array)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Float32)(0.0f, 1.0f)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Bool)(sept::True, sept::False, true)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Sint16)(int16_t(888), int16_t(20202))); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::VoidType)(sept::Void, sept::Void, sept::Void, sept::Void)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::EmptyType)()); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayE(sept::Array)(sept::Array(), sept::Array(true, 3, 4.4), sept::Array(sept::Term))); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__500__ArrayS) TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(0)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(1)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(2)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(3)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(4)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(10)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(100)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(100000000)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(2)(0.0f, 1.0f)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(3)(sept::True, sept::False, true)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(2)(int16_t(888), int16_t(20202))); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(4)(sept::Void, sept::Void, sept::Void, sept::Void)); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(0)()); TEST_SERIALIZATION_ROUNDTRIP(sept::ArrayS(3)(sept::Array(), sept::Array(true, 3, 4.4), sept::Array(sept::Term))); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__600__OrderedMap) TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapType); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMap); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMap()); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMap(std::pair(10,123))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMap(std::pair(10,123), std::pair(20,246))); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__700__OrderedMapDC) TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::Sint32,sept::Bool)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::Bool,sept::Float32)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::VoidType,sept::Term)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::Array,sept::Uint64)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::OrderedMap,sept::ArrayE(sept::ArrayS(2)))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::Sint32,sept::Bool)(std::pair(123,true), std::pair(400,false))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::Bool,sept::Float32)(std::pair(true,1.0f), std::pair(false,0.0f))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapDC(sept::VoidType,sept::Term)(std::pair(sept::Void,56.89))); TEST_SERIALIZATION_ROUNDTRIP( sept::OrderedMapDC(sept::Array,sept::Uint64)( std::pair(sept::Array(false,true,false),uint64_t(3)), std::pair(sept::Array(true,true,true,false,false),uint64_t(5)) ) ); TEST_SERIALIZATION_ROUNDTRIP( sept::OrderedMapDC(sept::OrderedMap,sept::ArrayE(sept::ArrayS(2)))( std::pair( sept::OrderedMap(std::pair(123,4), std::pair(369,12), std::pair(40404,0)), sept::ArrayE(sept::ArrayS(2))(sept::ArrayS(2)(123,4), sept::ArrayS(2)(369,12), sept::ArrayS(2)(40404,0)) ) ) ); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__800__OrderedMapD) TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::Sint32)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::Bool)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::VoidType)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::Array)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::OrderedMap)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::Sint32)(std::pair(123,true), std::pair(400,false))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::Bool)(std::pair(true,1.0f), std::pair(false,0.0f))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapD(sept::VoidType)(std::pair(sept::Void,56.89))); TEST_SERIALIZATION_ROUNDTRIP( sept::OrderedMapD(sept::Array)( std::pair(sept::Array(false,true,false),uint64_t(3)), std::pair(sept::Array(true,true,true,false,false),uint64_t(5)) ) ); TEST_SERIALIZATION_ROUNDTRIP( sept::OrderedMapD(sept::OrderedMap)( std::pair( sept::OrderedMap(std::pair(123,4), std::pair(369,12), std::pair(40404,0)), sept::ArrayE(sept::ArrayS(2))(sept::ArrayS(2)(123,4), sept::ArrayS(2)(369,12), sept::ArrayS(2)(40404,0)) ) ) ); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__800__OrderedMapC) TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::Bool)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::Float32)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::Term)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::Uint64)); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::ArrayE(sept::ArrayS(2)))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::Bool)(std::pair(123,true), std::pair(400,false))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::Float32)(std::pair(true,1.0f), std::pair(false,0.0f))); TEST_SERIALIZATION_ROUNDTRIP(sept::OrderedMapC(sept::Term)(std::pair(sept::Void,56.89))); TEST_SERIALIZATION_ROUNDTRIP( sept::OrderedMapC(sept::Uint64)( std::pair(sept::Array(false,true,false),uint64_t(3)), std::pair(sept::Array(true,true,true,false,false),uint64_t(5)) ) ); TEST_SERIALIZATION_ROUNDTRIP( sept::OrderedMapC(sept::ArrayE(sept::ArrayS(2)))( std::pair( sept::OrderedMap(std::pair(123,4), std::pair(369,12), std::pair(40404,0)), sept::ArrayE(sept::ArrayS(2))(sept::ArrayS(2)(123,4), sept::ArrayS(2)(369,12), sept::ArrayS(2)(40404,0)) ) ) ); LVD_TEST_END LVD_TEST_BEGIN(595__serialization__900__control) TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::OutputType); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::Output); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::Output(123)); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::ClearOutputType); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::ClearOutput); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInputType); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInput); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInput(sept::Void)); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInput(sept::Sint32)); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInput(sept::VoidType)); TEST_SERIALIZATION_ROUNDTRIP(sept::ctl::RequestSyncInput(sept::Array)); LVD_TEST_END
46.190265
196
0.727991
vdods
c37e5885f4473f9993d4de42ebb9c546a2d82948
1,451
cpp
C++
src/snabl/run.cpp
ricelang/snabl
488591099faf089d4deba30f90017305ff31598c
[ "MIT" ]
1
2021-10-20T07:44:36.000Z
2021-10-20T07:44:36.000Z
src/snabl/run.cpp
ricelang/snabl
488591099faf089d4deba30f90017305ff31598c
[ "MIT" ]
null
null
null
src/snabl/run.cpp
ricelang/snabl
488591099faf089d4deba30f90017305ff31598c
[ "MIT" ]
null
null
null
#include "snabl/call.hpp" #include "snabl/env.hpp" #include "snabl/parser.hpp" #include "snabl/run.hpp" namespace snabl { void Env::run(string_view in) { const string s(in); istringstream ss(s); run(ss); } void Env::run(istream &in) { Forms fs; Parser(*this).parse(in, fs); const auto start_pc(_ops.size()); compile(fs.begin(), fs.end()); if (!_ops.empty()) { jump(start_pc); run(); } } void Env::run() { enter: try { while (_task->_pc) { (*_task->_pc)(); } } catch (const UserError &e) { if (!_task->_tries.size()) { throw e; } auto t(_task->_tries.back()); auto &s(get_reg<State>(t->state_reg)); s.restore_lib(*this); s.restore_scope(*this); s.restore_calls(*this); s.restore_stack(*this); s.restore_splits(*this); clear_reg(t->state_reg); end_try(); push(error_type, make_shared<UserError>(e)); jump(t->handler_pc); goto enter; } } RuntimeError::RuntimeError(Env &env, Pos pos, const string &msg) { stringstream buf; buf << env._stack << endl << "Error in row " << pos.row << ", col " << pos.col << ":\n" << msg; _what = buf.str(); } const char *RuntimeError::what() const noexcept { return _what.c_str(); } static string val_str(const Box &val) { stringstream buf; buf << val; return buf.str(); } UserError::UserError(Env &env, Pos pos, const Box &_val): RuntimeError(env, pos, val_str(_val)), val(_val) { } }
21.028986
74
0.607857
ricelang
c380295cbd43ceb7225b5d3f146080d2d90d3a16
1,737
cpp
C++
src/Target_Crystal.cpp
temken/DM_Detection
bc3db0bd8e0293659c216d2a47af0217224d87c5
[ "MIT" ]
2
2021-02-04T08:37:57.000Z
2021-12-03T16:02:52.000Z
src/Target_Crystal.cpp
temken/DM_Detection
bc3db0bd8e0293659c216d2a47af0217224d87c5
[ "MIT" ]
21
2020-05-06T12:52:11.000Z
2022-03-31T13:11:23.000Z
src/Target_Crystal.cpp
temken/DM_Detection
bc3db0bd8e0293659c216d2a47af0217224d87c5
[ "MIT" ]
1
2022-01-03T03:53:50.000Z
2022-01-03T03:53:50.000Z
#include "obscura/Target_Crystal.hpp" #include <cmath> #include "libphysica/Natural_Units.hpp" #include "libphysica/Utilities.hpp" #include "version.hpp" namespace obscura { using namespace libphysica::natural_units; Crystal::Crystal(std::string target) : name(target), dE(0.1 * eV), dq(0.02 * aEM * mElectron) { double prefactor; if(name == "Si") { energy_gap = 1.11 * eV; epsilon = 3.6 * eV; M_cell = 2.0 * 28.08 * mNucleon; prefactor = 2.0 * eV; Q_max = std::floor((50 * eV - energy_gap + epsilon) / epsilon); } else if(name == "Ge") { energy_gap = 0.67 * eV; epsilon = 2.9 * eV; M_cell = 2.0 * 72.6 * mNucleon; prefactor = 1.8 * eV; Q_max = std::floor((50 * eV - energy_gap + epsilon) / epsilon); } else { std::cerr << "Error in obscura::Crystal::Crystal(): target " << target << " not recognized." << std::endl; std::exit(EXIT_FAILURE); } //Import the form factor std::string path = PROJECT_DIR "data/Semiconductors/C." + target + "137.dat"; std::vector<double> aux_list = libphysica::Import_List(path); std::vector<std::vector<double>> form_factor_table(900, std::vector<double>(500, 0.0)); double wk = 2.0 / 137.0; unsigned int i = 0; for(int Ei = 0; Ei < 500; Ei++) for(int qi = 0; qi < 900; qi++) form_factor_table[qi][Ei] = prefactor * (qi + 1) / dE * wk / 4.0 * aux_list[i++]; std::vector<double> q_grid = libphysica::Linear_Space(dq, 900 * dq, 900); std::vector<double> E_grid = libphysica::Linear_Space(dE, 500 * dE, 500); form_factor_interpolation = libphysica::Interpolation_2D(q_grid, E_grid, form_factor_table); } double Crystal::Crystal_Form_Factor(double q, double E) { return form_factor_interpolation(q, E); } } // namespace obscura
29.948276
108
0.653425
temken
c380ec117a6bb44fd41cceb31bbbdf7a78c79257
1,263
cpp
C++
libs/fontdraw/src/font/draw/simple.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/fontdraw/src/font/draw/simple.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/fontdraw/src/font/draw/simple.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 <sge/font/object_fwd.hpp> #include <sge/font/string.hpp> #include <sge/font/text_parameters_fwd.hpp> #include <sge/font/vector_fwd.hpp> #include <sge/font/draw/simple.hpp> #include <sge/font/draw/static_text.hpp> #include <sge/image/color/any/object_fwd.hpp> #include <sge/renderer/context/ffp_fwd.hpp> #include <sge/renderer/device/ffp_fwd.hpp> #include <sge/renderer/texture/emulate_srgb.hpp> #include <fcppt/make_ref.hpp> void sge::font::draw::simple( sge::renderer::device::ffp &_renderer, sge::renderer::context::ffp &_render_context, sge::font::object &_font, sge::font::string const &_string, sge::font::text_parameters const &_parameters, sge::font::vector const &_pos, sge::image::color::any::object const &_color, sge::renderer::texture::emulate_srgb const _emulate_srgb) { sge::font::draw::static_text text( fcppt::make_ref(_renderer), fcppt::make_ref(_font), _string, _parameters, _pos, _color, _emulate_srgb); text.draw(_render_context); }
32.384615
61
0.70388
cpreh
c38336fdb4fd6bbc709fc4823139cac01261e7da
1,605
cpp
C++
leetcode-cpp/src/p2/p2_solution.cpp
ch200c/leetcode-cpp
7293c8ca2f8a2cf8ced56ef60461da4706e4630b
[ "MIT" ]
null
null
null
leetcode-cpp/src/p2/p2_solution.cpp
ch200c/leetcode-cpp
7293c8ca2f8a2cf8ced56ef60461da4706e4630b
[ "MIT" ]
null
null
null
leetcode-cpp/src/p2/p2_solution.cpp
ch200c/leetcode-cpp
7293c8ca2f8a2cf8ced56ef60461da4706e4630b
[ "MIT" ]
null
null
null
#include "pch.h" #include "leetcode-cpp/p2/p2_list_node.h" // ListNode #include "leetcode-cpp/p2/p2_solution.h" namespace leetcode { namespace p2 { ListNode *Solution::to_list(const std::vector<int> &digits) noexcept { ListNode *root_node{nullptr}; ListNode *previous_node{nullptr}; for (const auto &digit : digits) { auto new_node{new ListNode(digit)}; if (previous_node) { previous_node->next = new_node; } else { root_node = new_node; } previous_node = new_node; } return root_node; } void Solution::delete_list(ListNode *root) noexcept { auto current_node{root}; while (current_node) { auto next{current_node->next}; delete current_node; current_node = next; } } // Runtime: 20 ms (98.02%) // Memory Usage: 11.6 MB (5.14%) ListNode *Solution::addTwoNumbers(ListNode *l1, ListNode *l2) const noexcept { std::vector<int> result_digits; ListNode *current_node1{l1}; ListNode *current_node2{l2}; auto carry{0}; while (current_node1 || current_node2) { auto value1{current_node1 ? current_node1->val : 0}; auto value2{current_node2 ? current_node2->val : 0}; auto sum{value1 + value2 + carry}; auto division_result{std::div(sum, 10)}; result_digits.push_back(division_result.rem); carry = division_result.quot; if (current_node1) { current_node1 = current_node1->next; } if (current_node2) { current_node2 = current_node2->next; } } if (carry) { result_digits.push_back(carry); } return to_list(result_digits); } } // namespace p2 } // namespace leetcode
21.986301
78
0.677882
ch200c
c384afa3273c20a22e23627549d07bfcd06ed238
3,127
cpp
C++
xs/src/libslic3r/PlaceholderParser.cpp
hroncok/Slic3r
321b70115b60df786fe74d376c3f67b1f7076fc0
[ "CC-BY-3.0" ]
null
null
null
xs/src/libslic3r/PlaceholderParser.cpp
hroncok/Slic3r
321b70115b60df786fe74d376c3f67b1f7076fc0
[ "CC-BY-3.0" ]
null
null
null
xs/src/libslic3r/PlaceholderParser.cpp
hroncok/Slic3r
321b70115b60df786fe74d376c3f67b1f7076fc0
[ "CC-BY-3.0" ]
null
null
null
#include "PlaceholderParser.hpp" namespace Slic3r { PlaceholderParser::PlaceholderParser() { // TODO: port these methods to C++, then call them here // this->apply_env_variables(); // this->update_timestamp(); } PlaceholderParser::~PlaceholderParser() { } void PlaceholderParser::apply_config(DynamicPrintConfig &config) { // options that are set and aren't text-boxes t_config_option_keys opt_keys; for (t_optiondef_map::iterator i = config.def->begin(); i != config.def->end(); ++i) { const t_config_option_key &key = i->first; const ConfigOptionDef &def = i->second; if (config.has(key) && !def.multiline) { opt_keys.push_back(key); } } for (t_config_option_keys::iterator i = opt_keys.begin(); i != opt_keys.end(); ++i) { const t_config_option_key &key = *i; // set placeholders for options with multiple values const ConfigOptionDef &def = (*config.def)[key]; switch (def.type) { case coFloats: this->set_multiple_from_vector(key, *(ConfigOptionFloats*)config.option(key)); break; case coInts: this->set_multiple_from_vector(key, *(ConfigOptionInts*)config.option(key)); break; case coStrings: this->set_multiple_from_vector(key, *(ConfigOptionStrings*)config.option(key)); break; case coPoints: this->set_multiple_from_vector(key, *(ConfigOptionPoints*)config.option(key)); break; case coBools: this->set_multiple_from_vector(key, *(ConfigOptionBools*)config.option(key)); break; case coPoint: { const ConfigOptionPoint &opt = *(ConfigOptionPoint*)config.option(key); this->_single[key] = opt.serialize(); Pointf val = opt; this->_multiple[key + "_X"] = val.x; this->_multiple[key + "_Y"] = val.y; } break; default: // set single-value placeholders this->_single[key] = config.serialize(key); break; } } } std::ostream& operator<<(std::ostream &stm, const Pointf &pointf) { return stm << pointf.x << "," << pointf.y; } template<class T> void PlaceholderParser::set_multiple_from_vector(const std::string &key, ConfigOptionVector<T> &opt) { const std::vector<T> &vals = opt.values; for (size_t i = 0; i < vals.size(); ++i) { std::stringstream multikey_stm; multikey_stm << key << "_" << i; std::stringstream val_stm; val_stm << vals[i]; this->_multiple[multikey_stm.str()] = val_stm.str(); } if (vals.size() > 0) { std::stringstream val_stm; val_stm << vals[0]; this->_multiple[key] = val_stm.str(); } } #ifdef SLIC3RXS REGISTER_CLASS(PlaceholderParser, "GCode::PlaceholderParser"); #endif }
25.842975
72
0.560921
hroncok
c38f497f127a3abcfcec78484fa01201ebd286b0
24,200
cpp
C++
src/fluids/main.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
23
2019-07-11T14:47:39.000Z
2021-12-24T09:56:24.000Z
src/fluids/main.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
null
null
null
src/fluids/main.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
4
2021-04-06T18:20:43.000Z
2022-01-15T09:20:45.000Z
// TODO/current state: // - pressure correction seems not to work for larger dt (it at least // seems like that is the problem. Maybe we can't just move dt out // of the linear system?) // - also for smaller dt: density can just vanish which should // not happen (mass preservation). only approximation errors? // - diffusion currently completely disabled (diffuse.comp broken and // disabled needs correct boundary conditions. But probably not // really worth it anyways?) // - not 100% sure about the other boundary conditions // - make various things (such as grid size and number of iterations // configurable via command line options) #include <tkn/singlePassApp.hpp> #include <tkn/bits.hpp> #include <vpp/sharedBuffer.hpp> #include <vpp/vk.hpp> #include <vpp/trackedDescriptor.hpp> #include <vpp/pipeline.hpp> #include <vpp/formats.hpp> #include <vpp/image.hpp> #include <vpp/imageOps.hpp> #include <vpp/pipeline.hpp> #include <vpp/commandAllocator.hpp> #include <vpp/submit.hpp> #include <nytl/vec.hpp> #include <nytl/vecOps.hpp> #include <dlg/dlg.hpp> #include <argagg.hpp> #include <cstring> #include <random> #include <shaders/tkn.fullscreen.vert.h> #include <shaders/fluids.fluid_texture.frag.h> #include <shaders/fluids.advect.vel.comp.h> #include <shaders/fluids.advect.dens.comp.h> #include <shaders/fluids.divergence.comp.h> #include <shaders/fluids.pressure.comp.h> #include <shaders/fluids.project.comp.h> #include <shaders/fluids.diffuse.dens.comp.h> // == FluidSystem == class FluidSystem { public: unsigned pressureIterations; // intialized by App::pressureIterations_ // static constexpr auto diffuseDensIterations = 0u; float velocityFac {0.0}; float densityFac {0.0}; float radius {10.f}; public: FluidSystem(vpp::Device& dev, nytl::Vec2ui size); void updateDevice(float dt, nytl::Vec2f mp0, nytl::Vec2f mp1); void compute(vk::CommandBuffer); const auto& density() const { return density_; } const auto& velocity() const { return velocity_; } const auto& pressure() const { return pressure_; } const auto& divergence() const { return divergence_; } auto size() const { return size_; } protected: nytl::Vec2ui size_; vpp::Sampler sampler_; vpp::SubBuffer ubo_; vpp::TrDsLayout dsLayout_; vpp::PipelineLayout pipeLayout_; vpp::Pipeline advectVel_; vpp::TrDs advectVelocityDs_; vpp::Pipeline advectDens_; vpp::TrDs advectDensityDs_; vpp::Pipeline divergencePipe_; vpp::TrDs divergenceDs_; vpp::Pipeline pressureIteration_; vpp::TrDs pressureDs0_; vpp::TrDs pressureDs1_; vpp::Pipeline project_; vpp::TrDs projectDs_; vpp::Pipeline diffuseDens_; vpp::TrDs diffuseDens0_; vpp::TrDs diffuseDens1_; vpp::ViewableImage velocity_; vpp::ViewableImage velocity0_; vpp::ViewableImage density_; vpp::ViewableImage density0_; vpp::ViewableImage divergence_; vpp::ViewableImage pressure_; vpp::ViewableImage pressure0_; }; FluidSystem::FluidSystem(vpp::Device& dev, nytl::Vec2ui size) { size_ = size; // sampler auto info = vk::SamplerCreateInfo {}; info.maxAnisotropy = 1.0; info.magFilter = vk::Filter::linear; info.minFilter = vk::Filter::linear; info.minLod = 0; info.maxLod = 0; info.mipmapMode = vk::SamplerMipmapMode::nearest; // velocity border condition: 0 info.addressModeU = vk::SamplerAddressMode::clampToBorder; info.addressModeV = vk::SamplerAddressMode::clampToBorder; info.borderColor = vk::BorderColor::floatTransparentBlack; sampler_ = vpp::Sampler(dev, info); // pipe auto advectBindings = std::array { vpp::descriptorBinding(vk::DescriptorType::storageImage, vk::ShaderStageBits::compute), vpp::descriptorBinding(vk::DescriptorType::storageImage, vk::ShaderStageBits::compute), vpp::descriptorBinding(vk::DescriptorType::storageImage, vk::ShaderStageBits::compute), vpp::descriptorBinding(vk::DescriptorType::combinedImageSampler, vk::ShaderStageBits::compute, &sampler_.vkHandle()), vpp::descriptorBinding(vk::DescriptorType::uniformBuffer, vk::ShaderStageBits::compute) }; dsLayout_.init(dev, advectBindings); pipeLayout_ = {dev, {{dsLayout_.vkHandle()}}, {}}; auto advectVelShader = vpp::ShaderModule(dev, fluids_advect_vel_comp_data); auto advectDensShader = vpp::ShaderModule(dev, fluids_advect_dens_comp_data); auto divergenceShader = vpp::ShaderModule(dev, fluids_divergence_comp_data); auto pressureShader = vpp::ShaderModule(dev, fluids_pressure_comp_data); auto projectShader = vpp::ShaderModule(dev, fluids_project_comp_data); auto diffuseDensShader = vpp::ShaderModule(dev, fluids_diffuse_dens_comp_data); vk::ComputePipelineCreateInfo advectInfoVel; advectInfoVel.layout = pipeLayout_; advectInfoVel.stage.module = advectVelShader; advectInfoVel.stage.pName = "main"; advectInfoVel.stage.stage = vk::ShaderStageBits::compute; auto advectInfoDens = advectInfoVel; advectInfoDens.stage.module = advectDensShader; auto divergenceInfo = advectInfoVel; divergenceInfo.stage.module = divergenceShader; auto pressureInfo = advectInfoVel; pressureInfo.stage.module = pressureShader; auto projectInfo = advectInfoVel; projectInfo.stage.module = projectShader; auto diffuseDensInfo = advectInfoVel; diffuseDensInfo.stage.module = diffuseDensShader; auto pipes = vk::createComputePipelines(dev, {}, {{ advectInfoVel, advectInfoDens, divergenceInfo, pressureInfo, projectInfo, diffuseDensInfo}}); advectVel_ = {dev, pipes[0]}; advectDens_ = {dev, pipes[1]}; divergencePipe_ = {dev, pipes[2]}; pressureIteration_ = {dev, pipes[3]}; project_ = {dev, pipes[4]}; diffuseDens_ = {dev, pipes[5]}; // images auto usage = vk::ImageUsageBits::sampled | vk::ImageUsageBits::storage | vk::ImageUsageBits::transferSrc | // TODO vk::ImageUsageBits::transferDst; auto velInfo = vpp::ViewableImageCreateInfo(vk::Format::r16g16b16a16Sfloat, vk::ImageAspectBits::color, {size.x, size.y}, usage); dlg_assert(vpp::supported(dev, velInfo.img)); velocity_ = {dev.devMemAllocator(), velInfo}; velocity0_ = {dev.devMemAllocator(), velInfo}; // constexpr auto csz = vk::ComponentSwizzle::zero; constexpr auto csr = vk::ComponentSwizzle::r; // constexpr auto csg = vk::ComponentSwizzle::g; // constexpr auto csb = vk::ComponentSwizzle::b; // constexpr auto csa = vk::ComponentSwizzle::a; constexpr auto cso = vk::ComponentSwizzle::one; // constexpr auto csi = vk::ComponentSwizzle::identity; auto scalarInfo = vpp::ViewableImageCreateInfo(vk::Format::r32Sfloat, vk::ImageAspectBits::color, {size.x, size.y}, usage); scalarInfo.view.components = {csr, csr, csr, cso}; dlg_assert(vpp::supported(dev, velInfo.img)); density_ = {dev.devMemAllocator(), scalarInfo}; density0_ = {dev.devMemAllocator(), scalarInfo}; pressure_ = {dev.devMemAllocator(), scalarInfo}; pressure0_ = {dev.devMemAllocator(), scalarInfo}; divergence_ = {dev.devMemAllocator(), scalarInfo}; auto fam = dev.queueSubmitter().queue().family(); auto cmdBuf = dev.commandAllocator().get(fam); auto layout = vk::ImageLayout::undefined; vk::beginCommandBuffer(cmdBuf, {}); auto images = {&density_, &density0_, &velocity_, &velocity0_, &pressure_, &pressure0_, &divergence_}; for(auto img : images) { vk::ImageMemoryBarrier barrier; barrier.image = img->image(); barrier.oldLayout = layout; barrier.srcAccessMask = {}; barrier.newLayout = vk::ImageLayout::general; barrier.dstAccessMask = vk::AccessBits::transferWrite; barrier.subresourceRange = {vk::ImageAspectBits::color, 0, 1, 0, 1}; vk::cmdPipelineBarrier(cmdBuf, vk::PipelineStageBits::topOfPipe, vk::PipelineStageBits::transfer, {}, {}, {}, {{barrier}}); auto color = vk::ClearColorValue {{0.f, 0.f, 0.f, 0.f}}; vk::cmdClearColorImage(cmdBuf, img->vkImage(), vk::ImageLayout::general, color, {{{vk::ImageAspectBits::color, 0, 1, 0, 1}}}); } vk::endCommandBuffer(cmdBuf); vk::SubmitInfo subInfo; subInfo.commandBufferCount = 1; subInfo.pCommandBuffers = &cmdBuf.vkHandle(); dev.queueSubmitter().add(subInfo); dev.queueSubmitter().submit(); vk::deviceWaitIdle(dev); // ds & stuff constexpr auto uboSize = sizeof(float) * 8; ubo_ = {dev.bufferAllocator(), uboSize, vk::BufferUsageBits::uniformBuffer, dev.hostMemoryTypes()}; advectDensityDs_ = {dev.descriptorAllocator(), dsLayout_}; advectVelocityDs_ = {dev.descriptorAllocator(), dsLayout_}; divergenceDs_ = {dev.descriptorAllocator(), dsLayout_}; pressureDs0_ = {dev.descriptorAllocator(), dsLayout_}; pressureDs1_ = {dev.descriptorAllocator(), dsLayout_}; projectDs_ = {dev.descriptorAllocator(), dsLayout_}; diffuseDens0_ = {dev.descriptorAllocator(), dsLayout_}; diffuseDens1_ = {dev.descriptorAllocator(), dsLayout_}; using VI = const vpp::ViewableImage; auto updateDs = [&](auto& ds, VI* a, VI* b, VI* c, VI* d) { constexpr auto layout = vk::ImageLayout::general; vpp::DescriptorSetUpdate update(ds); for(auto& l : {a, b, c}) { if(l) { update.storage({{{}, l->vkImageView(), layout}}); } else { update.skip(); } } if(d) { update.imageSampler({{{}, d->vkImageView(), layout}}); } else { update.skip(); } update.uniform(ubo_); }; // == naming and swapping convention == // the first pass should always read from the not 0 texture // the last pass should always render to the not 0 texture // the 0 texture is seen as temporary storage // advect velocity: vel, vel -> vel0 // divergence: vel0 -> div // project: div, vel0 -> vel // advect density: dens, vel -> dens0 // diffuse density loop: dens0 -> dens; dens -> dens0 // final diffuse density: dens0 -> dens // the 0,1 ds's should be named in the order in that they appear updateDs(advectVelocityDs_, &velocity0_, nullptr, &velocity_, &velocity_); updateDs(divergenceDs_, &divergence_, &velocity0_, nullptr, nullptr); updateDs(pressureDs0_, &pressure0_, &pressure_, &divergence_, nullptr); updateDs(pressureDs1_, &pressure_, &pressure0_, &divergence_, nullptr); updateDs(projectDs_, &velocity_, &velocity0_, &pressure_, nullptr); updateDs(advectDensityDs_, &density0_, nullptr, &velocity_, &density_); updateDs(diffuseDens0_, &density_, &density0_, nullptr, nullptr); updateDs(diffuseDens1_, &density0_, &density_, nullptr, nullptr); } void FluidSystem::updateDevice(float dt, nytl::Vec2f mp0, nytl::Vec2f mp1) { auto map = ubo_.memoryMap(); auto data = map.span(); tkn::write(data, mp0); tkn::write(data, mp1); tkn::write(data, dt); tkn::write(data, velocityFac); tkn::write(data, densityFac); tkn::write(data, radius); } void FluidSystem::compute(vk::CommandBuffer cb) { // dispatch sizes auto dx = size_.x / 16; auto dy = size_.y / 16; // sync util // we actually need a lot of synchronization here since we swap reading/ // writing from/to images all the time and have to make sure the previous // command finished // NOTE: the sync in this proc is probably not fully correct... constexpr vk::ImageLayout general = vk::ImageLayout::general; using PSB = vk::PipelineStageBits; using AB = vk::AccessBits; auto readWrite = AB::shaderRead | AB::shaderWrite; auto barrier = [&](auto& img, auto srca, auto dsta) { vk::ImageMemoryBarrier barrier; barrier.oldLayout = general; barrier.newLayout = general; barrier.image = img.vkImage(); barrier.subresourceRange = {vk::ImageAspectBits::color, 0, 1, 0, 1}; barrier.srcAccessMask = srca; barrier.dstAccessMask = dsta; return barrier; }; auto insertBarrier = [&](auto srcs, auto dsts, std::initializer_list<vk::ImageMemoryBarrier> barriers) { vk::cmdPipelineBarrier(cb, srcs, dsts, {}, {}, {}, barriers); // nytl::unused(srcs, dsts, barriers); }; // when adding additional passes we might need one additional // copy image at the beginning/end to make sure the number of // swaps comes out even // vk::ImageCopy full; // full.dstSubresource = {vk::ImageAspectBits::color, 0, 0, 1}; // full.srcSubresource = {vk::ImageAspectBits::color, 0, 0, 1}; // full.extent = {size_.x, size_.y, 1u}; // vk::cmdCopyImage(cb, velocity0_.image(), vk::ImageLayout::general, // velocity_.image(), vk::ImageLayout::general, {full}); // insertBarrier(PSB::transfer, PSB::computeShader, { // barrier(velocity_, AB::transferWrite, readWrite), // }); // make sure reading the images is finished insertBarrier(PSB::fragmentShader, PSB::computeShader | PSB::transfer, { barrier(velocity_, AB::shaderRead, AB::shaderWrite), barrier(density_, AB::shaderRead, AB::shaderWrite), barrier(divergence_, AB::shaderRead, AB::shaderWrite), barrier(pressure_, AB::shaderRead, AB::shaderWrite | AB::transferWrite), }); // we clear pressure since we want to use vec4(0) as initial guess // for pressure (to get better approximations) // might also work if we don't do this // NOTE: seems to works better if we don't do this, seems like the // pressure from the previous frame is a way better guess than just 0 /* auto color = vk::ClearColorValue {{0.f, 0.f, 0.f, 0.f}}; vk::cmdClearColorImage(cb, pressure_.vkImage(), vk::ImageLayout::general, color, {{{vk::ImageAspectBits::color, 0, 1, 0, 1}}}); insertBarrier(PSB::transfer, PSB::computeShader, { barrier(pressure_, AB::transferWrite, readWrite), }); */ // == velocity == // advect velocity (also applies external forces after advection) vk::cmdBindPipeline(cb, vk::PipelineBindPoint::compute, advectVel_); vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {{advectVelocityDs_.vkHandle()}}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader, { barrier(velocity0_, readWrite, readWrite), }); // compute divergence vk::cmdBindPipeline(cb, vk::PipelineBindPoint::compute, divergencePipe_); vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {{divergenceDs_.vkHandle()}}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader, { barrier(divergence_, AB::shaderWrite, AB::shaderRead), }); // iterate pressure vk::cmdBindPipeline(cb, vk::PipelineBindPoint::compute, pressureIteration_); for(auto i = 0u; i < pressureIterations / 2; ++i) { vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {{pressureDs0_.vkHandle()}}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader, { barrier(pressure0_, readWrite, readWrite), }); vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {{pressureDs1_.vkHandle()}}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader, { barrier(pressure_, readWrite, readWrite), }); } // project velocity vk::cmdBindPipeline(cb, vk::PipelineBindPoint::compute, project_); vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {{projectDs_.vkHandle()}}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader | PSB::fragmentShader, { barrier(velocity_, readWrite, readWrite), }); // == density == // TODO: should be at end otherwise density texture read is out of date // vk::cmdCopyImage(cb, density0_.image(), vk::ImageLayout::general, // density_.image(), vk::ImageLayout::general, {full}); // insertBarrier(PSB::transfer, PSB::computeShader, { // barrier(density0_, AB::transferWrite, AB::shaderRead), // }); // advect vk::cmdBindPipeline(cb, vk::PipelineBindPoint::compute, advectDens_); vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {{advectDensityDs_.vkHandle()}}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader, { barrier(density0_, readWrite, readWrite), }); // diffuse vk::cmdBindPipeline(cb, vk::PipelineBindPoint::compute, diffuseDens_); /* for(auto i = 0u; i < diffuseDensIterations / 2; ++i) { vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {diffuseDens0_}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader, { barrier(density_, readWrite, readWrite), }); vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {diffuseDens1_}, {}); vk::cmdDispatch(cb, dx, dy, 1); insertBarrier(PSB::computeShader, PSB::computeShader, { barrier(density0_, readWrite, readWrite), }); } */ // one final iterations for even swap count (taking the initial // advection into account) vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::compute, pipeLayout_, 0, {{diffuseDens0_.vkHandle()}}, {}); vk::cmdDispatch(cb, dx, dy, 1); // make sure writing has finished before reading insertBarrier(PSB::computeShader, PSB::fragmentShader, { barrier(density_, AB::shaderWrite, AB::shaderRead), barrier(velocity_, AB::shaderWrite, AB::shaderRead), barrier(pressure_, AB::shaderWrite, AB::shaderRead), barrier(divergence_, AB::shaderWrite, AB::shaderRead), }); } // == FluidApp == class FluidApp : public tkn::SinglePassApp { public: static constexpr auto defaultGridWidth = 1024; using Base = tkn::SinglePassApp; public: bool init(const nytl::Span<const char*> args) override { if(!Base::init(args)) { return false; } auto& dev = vkDevice(); // own pipe auto info = vk::SamplerCreateInfo {}; info.maxAnisotropy = 1.0; info.magFilter = vk::Filter::linear; info.minFilter = vk::Filter::linear; info.minLod = 0; info.maxLod = 0.25; info.mipmapMode = vk::SamplerMipmapMode::nearest; sampler_ = vpp::Sampler(dev, info); auto renderBindings = std::array { vpp::descriptorBinding(vk::DescriptorType::combinedImageSampler, vk::ShaderStageBits::fragment, &sampler_.vkHandle()), vpp::descriptorBinding(vk::DescriptorType::uniformBuffer, vk::ShaderStageBits::fragment), }; dsLayout_.init(dev, renderBindings); auto pipeSets = {dsLayout_.vkHandle()}; vk::PipelineLayoutCreateInfo plInfo; plInfo.setLayoutCount = 1; plInfo.pSetLayouts = pipeSets.begin(); pipeLayout_ = {dev, {{dsLayout_.vkHandle()}}, {{{vk::ShaderStageBits::fragment, 0, 4u}}}}; vpp::ShaderModule fullscreenShader(dev, tkn_fullscreen_vert_data); vpp::ShaderModule textureShader(dev, fluids_fluid_texture_frag_data); vpp::GraphicsPipelineInfo pipeInfo(renderPass(), pipeLayout_, {{{ {fullscreenShader, vk::ShaderStageBits::vertex}, {textureShader, vk::ShaderStageBits::fragment} }}}); pipe_ = {dev, pipeInfo.info()}; // mouse ubo mouseUbo_ = {dev.bufferAllocator(), sizeof(nytl::Vec2f), vk::BufferUsageBits::uniformBuffer, dev.hostMemoryTypes()}; // ds ds_ = {dev.descriptorAllocator(), dsLayout_}; return true; } void initBuffers(const vk::Extent2D& size, nytl::Span<RenderBuffer> bufs) override { Base::initBuffers(size, bufs); auto fac = size.height / float(size.width); // NOTE: must both be multiples of 16 due to group size // TODO: fix with standard ceil rounding in dispatch count // and compute shader check unsigned width = gridWidth_; unsigned height = vpp::align((unsigned)(fac * width), 16u); system_.emplace(vkDevice(), nytl::Vec2ui {width, height}); system_->pressureIterations = pressureIterations_; if(viewType_ == 1) { changeView_ = system_->density().vkImageView(); } else { changeView_ = system_->velocity().vkImageView(); } } argagg::parser argParser() const override { auto res = Base::argParser(); res.definitions.push_back({ "size", {"--size", "-s"}, "Size (width) of the simulation grid", 1, }); res.definitions.push_back({ "pressure-iterations", {"--pressure-iterations", "-p"}, "Number of pressure solver iterations", 1, }); return res; } bool handleArgs(const argagg::parser_results& res, Base::Args& args) override { if(!Base::handleArgs(res, args)) { return false; } if(auto& pi = res["pressure-iterations"]; pi) { pressureIterations_ = pi.as<unsigned>(); } if(auto& s = res["size"]; s) { gridWidth_ = s.as<unsigned>(); } return true; } bool key(const swa_key_event& ev) override { if(Base::key(ev)) { return true; } if(!ev.pressed) { return false; } if(ev.keycode == swa_key_d) { changeView_ = system_->density().vkImageView(); viewType_ = 1; } else if(ev.keycode == swa_key_f) { changeView_ = system_->density().vkImageView(); viewType_ = 3; } else if(ev.keycode == swa_key_v) { changeView_ = system_->velocity().vkImageView(); viewType_ = 2; } else if(ev.keycode == swa_key_q) { changeView_ = system_->divergence().vkImageView(); viewType_ = 4; } else if(ev.keycode == swa_key_p) { changeView_ = system_->pressure().vkImageView(); viewType_ = 1; } else if(ev.keycode == swa_key_l) { changeView_ = system_->velocity().vkImageView(); viewType_ = 5; } else { return false; } return true; } void update(double dt) override { Base::scheduleRedraw(); Base::update(dt); dt_ = dt; } void updateDevice() override { Base::updateDevice(); using namespace nytl::vec::cw::operators; system_->updateDevice(dt_, system_->size() * prevPos_, system_->size() * mpos_); prevPos_ = mpos_; auto map = mouseUbo_.memoryMap(); auto span = map.span(); tkn::write(span, mpos_); if(changeView_) { vpp::DescriptorSetUpdate update(ds_); update.imageSampler({{{}, changeView_, vk::ImageLayout::general}}); update.uniform(mouseUbo_); changeView_ = {}; Base::scheduleRerecord(); } } void mouseMove(const swa_mouse_move_event& ev) override { Base::mouseMove(ev); using namespace nytl::vec::cw::operators; mpos_ = nytl::Vec2f{float(ev.x), float(ev.y)} / windowSize(); } bool mouseButton(const swa_mouse_button_event& ev) override { if(Base::mouseButton(ev)) { return true; } bool shift = swa_display_active_keyboard_mods(swaDisplay()) & swa_keyboard_mod_shift; if(ev.button == swa_mouse_button_left && !shift) { system_->densityFac = ev.pressed * 0.01; system_->velocityFac = 0.f; } else if(ev.button == swa_mouse_button_right || shift) { system_->velocityFac = ev.pressed * 10.f; } else { return false; } return true; } bool touchBegin(const swa_touch_event& ev) override { if(Base::touchBegin(ev)) { return true; } using namespace nytl::vec::cw::operators; mpos_ = nytl::Vec2f{float(ev.x), float(ev.y)} / windowSize(); prevPos_ = mpos_; if(mpos_.x > 0.9 && mpos_.y > 0.95) { if(viewType_ == 1) { changeView_ = system_->velocity().vkImageView(); viewType_ = 2; } else if(viewType_ == 2) { changeView_ = system_->density().vkImageView(); viewType_ = 1; } } else { system_->velocityFac = 5.f * (viewType_ == 2); system_->densityFac = 0.02 * (viewType_ == 1); } return true; } void touchUpdate(const swa_touch_event& ev) override { using namespace nytl::vec::cw::operators; mpos_ = nytl::Vec2f{float(ev.x), float(ev.y)} / windowSize(); } bool touchEnd(unsigned id) override { if(Base::touchEnd(id)) { return true; } system_->velocityFac = 0.f; system_->densityFac = 0.f; return true; } bool mouseWheel(float dx, float dy) override { if(Base::mouseWheel(dx, dy)) { return true; } system_->radius *= std::pow(1.05, dy); return true; } void beforeRender(vk::CommandBuffer cb) override { system_->compute(cb); } void render(vk::CommandBuffer cb) override { vk::cmdPushConstants(cb, pipeLayout_, vk::ShaderStageBits::fragment, 0u, 4u, &viewType_); vk::cmdBindPipeline(cb, vk::PipelineBindPoint::graphics, pipe_); vk::cmdBindDescriptorSets(cb, vk::PipelineBindPoint::graphics, pipeLayout_, 0, {{ds_.vkHandle()}}, {}); vk::cmdDraw(cb, 6, 1, 0, 0); } const char* name() const override { return "Fluids"; } protected: std::optional<FluidSystem> system_; float dt_ {}; nytl::Vec2f mpos_ {}; nytl::Vec2f prevPos_ {}; vk::ImageView changeView_ {}; unsigned viewType_ {1}; vpp::SubBuffer mouseUbo_; vpp::Sampler sampler_; vpp::TrDsLayout dsLayout_; vpp::TrDs ds_; vpp::PipelineLayout pipeLayout_; vpp::Pipeline pipe_; unsigned gridWidth_ {defaultGridWidth}; unsigned pressureIterations_ {20}; }; // main int main(int argc, const char** argv) { return tkn::appMain<FluidApp>(argc, argv); }
31.387808
80
0.707893
nyorain
c3932da7c1f71fdb243944622036a2fc4d6631cc
119
cpp
C++
test/once_test.cpp
iwongdotcn/juliet
661cbf0fca06542a4f3a55d8c5a36af0f1613905
[ "BSL-1.0" ]
null
null
null
test/once_test.cpp
iwongdotcn/juliet
661cbf0fca06542a4f3a55d8c5a36af0f1613905
[ "BSL-1.0" ]
null
null
null
test/once_test.cpp
iwongdotcn/juliet
661cbf0fca06542a4f3a55d8c5a36af0f1613905
[ "BSL-1.0" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" #include "sync/once.hpp" TEST_CASE("sync.Once", "[Once]") { }
13.222222
34
0.697479
iwongdotcn
c39f2dc62a78c88a57d3b3bda9002bb44f134ea5
2,824
inl
C++
Base/PLMath/include/PLMath/Line.inl
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLMath/include/PLMath/Line.inl
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLMath/include/PLMath/Line.inl
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: Line.inl * * Line inline implementation * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLMath { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Default constructor setting all start- and end-position components to 0 */ inline Line::Line() { } /** * @brief * Copy constructor */ inline Line::Line(const Line &cSource) : vStart(cSource.vStart), vEnd(cSource.vEnd) { } /** * @brief * Copy constructor */ inline Line::Line(const Vector3 &vStartPoint, const Vector3 &vEndPoint) : vStart(vStartPoint), vEnd(vEndPoint) { } /** * @brief * Destructor */ inline Line::~Line() { } /** * @brief * Copy operator */ inline Line &Line::operator =(const Line &cSource) { // Copy data vStart = cSource.vStart; vEnd = cSource.vEnd; // Return this return *this; } /** * @brief * Sets the start and end position of the line */ inline void Line::Set(const Vector3 &vStart, const Vector3 &vEnd) { this->vStart = vStart; this->vEnd = vEnd; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLMath
28.24
97
0.542493
ktotheoz
c39fc99068f583dd0bacff691c637fbb6eef291b
315
cpp
C++
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/InstancedPlugin.cpp
redcatbox/Instanced
347790e8ade0c6e6fb9b742afc78c764414ed36a
[ "MIT" ]
1
2022-02-03T17:10:29.000Z
2022-02-03T17:10:29.000Z
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/InstancedPlugin.cpp
redcatbox/Instanced
347790e8ade0c6e6fb9b742afc78c764414ed36a
[ "MIT" ]
null
null
null
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/InstancedPlugin.cpp
redcatbox/Instanced
347790e8ade0c6e6fb9b742afc78c764414ed36a
[ "MIT" ]
null
null
null
// redbox, 2021 #include "InstancedPlugin.h" #define LOCTEXT_NAMESPACE "FInstancedPluginModule" DEFINE_LOG_CATEGORY(IPLog); void FInstancedPluginModule::StartupModule() { } void FInstancedPluginModule::ShutdownModule() { } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FInstancedPluginModule, InstancedPlugin)
14.318182
57
0.812698
redcatbox
c3a15e53f26e01e9197c5eec46f350229140ff1e
1,591
cpp
C++
newstacktemp.cpp
compliment/cpp-tasks
31c5771e97c319860a1b546c68d92601b77e0223
[ "Unlicense" ]
null
null
null
newstacktemp.cpp
compliment/cpp-tasks
31c5771e97c319860a1b546c68d92601b77e0223
[ "Unlicense" ]
null
null
null
newstacktemp.cpp
compliment/cpp-tasks
31c5771e97c319860a1b546c68d92601b77e0223
[ "Unlicense" ]
null
null
null
#include<iostream> using namespace std; template <class T,int Maxsize> class Stack { T arr[Maxsize]; int top; public: Stack(){top=-1;} bool IsEmpty(){ return top==-1;} bool IsFull(){return top==Maxsize-1;} void Push(T item){ if (IsFull()) {cout<<"Stack Overflow";return;} arr[++top]=item; } T Pop(){ if (IsEmpty()){ cout<<"Stack Underflow";return NULL;} return (arr[top--]); } }; int main(){ Stack<int, 5> intStk; cout<<"Inserting elements ..."<<endl; intStk.Push(10); intStk.Push(20); intStk.Push(30); intStk.Push(40); intStk.Push(50); intStk.Push(10); cout<<"\nElement Popped : " << intStk.Pop()<<endl; cout<<"\nElement Popped : " << intStk.Pop()<<endl; cout<<"\nElement Popped : " << intStk.Pop()<<endl; cout<<"\nElement Popped : " << intStk.Pop()<<endl; cout<<"\nElement Popped : " << intStk.Pop()<<endl; cout<<"\nElement Popped : " << intStk.Pop()<<endl; Stack<char, 5> chrStk; chrStk.Push('A'); chrStk.Push('B'); chrStk.Push('C'); chrStk.Push('D'); chrStk.Push('E'); chrStk.Push('F'); cout<<"\nElement Popped : " << chrStk.Pop()<<endl; cout<<"\nElement Popped : " << chrStk.Pop()<<endl; cout<<"\nElement Popped : " << chrStk.Pop()<<endl; cout<<"\nElement Popped : " << chrStk.Pop()<<endl; cout<<"\nElement Popped : " << chrStk.Pop()<<endl; cout<<"\nElement Popped : " << chrStk.Pop()<<endl; }
25.66129
62
0.51917
compliment
c3ac989045af53b11b8ba10c22de21f57b09a634
2,828
cpp
C++
Source/UMGIntro/REST/RestCaller.cpp
jgnoel86/unreal-test
47f70a95cf9c8217c72094bbcb2cf2a6bd5d5a31
[ "MIT" ]
null
null
null
Source/UMGIntro/REST/RestCaller.cpp
jgnoel86/unreal-test
47f70a95cf9c8217c72094bbcb2cf2a6bd5d5a31
[ "MIT" ]
null
null
null
Source/UMGIntro/REST/RestCaller.cpp
jgnoel86/unreal-test
47f70a95cf9c8217c72094bbcb2cf2a6bd5d5a31
[ "MIT" ]
null
null
null
/** * @author Justin Noel * @file RestCaller.cpp */ #include "RestCaller.h" #include "EnumRequestVerbs.h" #include "Http.h" /** * @brief Helper macro to perform a bool to string conversion. * @param b bool to convert to True or False */ #define BOOL_TO_STRING(b) b ? TEXT("True") : TEXT("False") namespace { /** * @brief Request map allows Enum selection to be used at the blue print level, and converted to the required * string for use with the Request object. */ const TMap<ERequestVerbs, FString> ERequestVerbNameMap = { { ERequestVerbs::GET, "GET" }, { ERequestVerbs::POST, "POST" }, { ERequestVerbs::PUT, "PUT" }, { ERequestVerbs::DELETE, "DELETE" } }; } /** * @brief Callback triggered by IHTTPRequest OnProcessRequestComplete * @param Request Original request that ultimately triggered this callback. * @param Response Response object after the request has completed. * @param bWasSuccessful If the call was successful. * @param OnComplete OnComplete callback delegate that was originally passed into the MakeRestCall. */ void OnResponseReceived( FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, FOnCallComplete OnComplete) { UE_LOG(LogTemp, Log, TEXT("OnResponseReceived")); FString responseContent; if(!Response.IsValid()) { responseContent = "Unable to process request."; return; } const int responseCode = Response->GetResponseCode(); if (bWasSuccessful && EHttpResponseCodes::IsOk(responseCode)) { responseContent = Response->GetContentAsString(); } else { responseContent = FString::Printf(TEXT("Http Error occured code: %d"), responseCode); } // ReSharper disable once CppExpressionWithoutSideEffects OnComplete.ExecuteIfBound(responseContent); } /** * @brief Triggers a basic REST call. Right now this is a non-body call. But it would * be easy to extend this library to have support for others. * @param Url Destination url to invoke a REST call on. * @param RequestVerb Request type, GET, PUT, POST, DELETE * @param OnComplete Callback delegate to trigger when the call has completed. */ void URestCaller::MakeRestCall(const FString& Url, ERequestVerbs RequestVerb, FOnCallComplete OnComplete) { const FString verbName = ERequestVerbNameMap[RequestVerb]; UE_LOG(LogTemp, Warning, TEXT("%s Request to: %s"), *verbName, *Url); const TSharedRef<IHttpRequest> request = FHttpModule::Get().CreateRequest(); request->OnProcessRequestComplete().BindStatic(&OnResponseReceived, OnComplete); request->SetURL(Url); request->SetVerb(verbName); request->SetHeader(TEXT("User-Agent"), "X-UnrealEngine-Agent"); request->ProcessRequest(); }
30.73913
113
0.696252
jgnoel86
ce7b97b5606f0062fc0bd13488a29b0339e81e5e
1,023
cpp
C++
codeforces/G - University Classes/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/G - University Classes/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/G - University Classes/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: JU_AAA: aniks2645, kzvd4729, prdx9_abir created: Sep/18/2017 19:11 * solution_verdict: Accepted language: GNU C++14 * run_time: 15 ms memory_used: 1900 KB * problem: https://codeforces.com/contest/847/problem/G ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long n,ans,cnt; string s[1003]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>n; for(long i=0;i<n;i++) { cin>>s[i]; } for(long j=0;j<8;j++) { cnt=0; for(long i=0;i<n;i++) { if(s[i][j]=='1')cnt++; } ans=max(ans,cnt); } cout<<ans<<endl; return 0; }
31
111
0.367546
kzvd4729
ce83158233b8e50e505e6793dd28e467e0563501
320
cpp
C++
src/VoxerEngine/VoxerEngine.cpp
cLazyZombie/wasmgl
68f7cab5bab01d8f00a73c5d32d2d2f9ba6185a9
[ "MIT" ]
null
null
null
src/VoxerEngine/VoxerEngine.cpp
cLazyZombie/wasmgl
68f7cab5bab01d8f00a73c5d32d2d2f9ba6185a9
[ "MIT" ]
null
null
null
src/VoxerEngine/VoxerEngine.cpp
cLazyZombie/wasmgl
68f7cab5bab01d8f00a73c5d32d2d2f9ba6185a9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "VoxerEngine.h" const int32 VOXEL_IN_CHUNK_XY = 32; const int32 VOXEL_IN_CHUNK_Z = 128; const float VOXEL_SIZE = 100.0f; const float CHUNK_SIZE_XY = VOXEL_IN_CHUNK_XY * VOXEL_SIZE; const float CHUNK_SIZE_Z = VOXEL_IN_CHUNK_Z * VOXEL_SIZE; const float CHUNK_LOADING_RADIUS = 300.0f * 100.0f;
35.555556
59
0.79375
cLazyZombie
ce92b226bd83633d208f299a00e4799d860fd19f
6,021
cpp
C++
raptor/gallery/par_matrix_IO.cpp
lwhZJU/raptor
cc8a68f1998c180dd696cb4c6b5fb18987fa60df
[ "BSD-2-Clause" ]
1
2019-03-28T08:05:11.000Z
2019-03-28T08:05:11.000Z
raptor/gallery/par_matrix_IO.cpp
lwhZJU/raptor
cc8a68f1998c180dd696cb4c6b5fb18987fa60df
[ "BSD-2-Clause" ]
null
null
null
raptor/gallery/par_matrix_IO.cpp
lwhZJU/raptor
cc8a68f1998c180dd696cb4c6b5fb18987fa60df
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2015-2017, RAPtor Developer Team // License: Simplified BSD, http://opensource.org/licenses/BSD-2-Clause #include "par_matrix_IO.hpp" #include "matrix_IO.hpp" #include <float.h> #include <stdio.h> bool little_endian() { int num = 1; return (*(char *)&num == 1); } template <class T> void endian_swap(T *objp) { unsigned char *memp = reinterpret_cast<unsigned char*>(objp); std::reverse(memp, memp + sizeof(T)); } ParCSRMatrix* readParMatrix(const char* filename, int local_num_rows, int local_num_cols, int first_local_row, int first_local_col, MPI_Comm comm) { int rank, num_procs; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &num_procs); ParCSRMatrix* A; uint32_t code; uint32_t global_num_rows; uint32_t global_num_cols; uint32_t global_nnz; uint32_t idx; double val; int ctr, size; int sizeof_dbl = sizeof(val); int sizeof_int32 = sizeof(code); bool is_little_endian = little_endian(); std::ifstream ifs (filename, std::ifstream::binary); ifs.read(reinterpret_cast<char *>(&code), sizeof_int32); ifs.read(reinterpret_cast<char *>(&global_num_rows), sizeof_int32); ifs.read(reinterpret_cast<char *>(&global_num_cols), sizeof_int32); ifs.read(reinterpret_cast<char *>(&global_nnz), sizeof_int32); if (is_little_endian) { endian_swap(&code); endian_swap(&global_num_rows); endian_swap(&global_num_cols); endian_swap(&global_nnz); } assert(code == PETSC_MAT_CODE); if (first_local_col >= 0) { A = new ParCSRMatrix(global_num_rows, global_num_cols, local_num_rows, local_num_cols, first_local_row, first_local_col); } else { A = new ParCSRMatrix(global_num_rows, global_num_cols); } aligned_vector<int> proc_nnz(num_procs); aligned_vector<int> row_sizes; aligned_vector<int> col_indices; aligned_vector<double> vals; int nnz = 0; if (A->local_num_rows) row_sizes.resize(A->local_num_rows); if (is_little_endian) { // Find row sizes ifs.seekg(A->partition->first_local_row * sizeof_int32, ifs.cur); for (int i = 0; i < A->local_num_rows; i++) { ifs.read(reinterpret_cast<char *>(&idx), sizeof_int32); endian_swap(&idx); row_sizes[i] = idx; nnz += idx; } ifs.seekg((A->global_num_rows - A->partition->last_local_row - 1) * sizeof_int32, ifs.cur); // Find nnz per proc (to find first_nnz) MPI_Allgather(&nnz, 1, MPI_INT, proc_nnz.data(), 1, MPI_INT, comm); int first_nnz = 0; for (int i = 0; i < rank; i++) { first_nnz += proc_nnz[i]; } int remaining_nnz = global_nnz - first_nnz - nnz; // Resize variables if (nnz) { col_indices.resize(nnz); vals.resize(nnz); } // Read in col_indices ifs.seekg(first_nnz * sizeof_int32, ifs.cur); for (int i = 0; i < nnz; i++) { ifs.read(reinterpret_cast<char *>(&idx), sizeof_int32); endian_swap(&idx); col_indices[i] = idx; } ifs.seekg(remaining_nnz * sizeof_int32, ifs.cur); ifs.seekg(first_nnz * sizeof_dbl, ifs.cur); for (int i = 0; i < nnz; i++) { ifs.read(reinterpret_cast<char *>(&val), sizeof_dbl); endian_swap(&val); vals[i] = val; } ifs.seekg(remaining_nnz * sizeof_dbl, ifs.cur); } else { // Find row sizes ifs.seekg(A->partition->first_local_row * sizeof_int32, ifs.cur); for (int i = 0; i < A->local_num_rows; i++) { ifs.read(reinterpret_cast<char *>(&idx), sizeof_int32); row_sizes[i] = idx; nnz += idx; } ifs.seekg((A->global_num_rows - A->partition->last_local_row - 1) * sizeof_int32, ifs.cur); // Find nnz per proc (to find first_nnz) MPI_Allgather(&nnz, 1, MPI_INT, proc_nnz.data(), 1, MPI_INT, comm); int first_nnz = 0; for (int i = 0; i < rank; i++) { first_nnz += proc_nnz[i]; } int remaining_nnz = global_nnz - first_nnz - nnz; // Resize variables if (nnz) { col_indices.resize(nnz); vals.resize(nnz); } // Read in col_indices ifs.seekg(first_nnz * sizeof_int32, ifs.cur); for (int i = 0; i < nnz; i++) { ifs.read(reinterpret_cast<char *>(&idx), sizeof_int32); col_indices[i] = idx; } ifs.seekg(remaining_nnz * sizeof_int32, ifs.cur); ifs.seekg(first_nnz * sizeof_dbl, ifs.cur); for (int i = 0; i < nnz; i++) { ifs.read(reinterpret_cast<char *>(&val), sizeof_dbl); vals[i] = val; } ifs.seekg(remaining_nnz * sizeof_dbl, ifs.cur); } A->on_proc->idx1[0] = 0; A->off_proc->idx1[0] = 0; ctr = 0; for (int i = 0; i < A->local_num_rows; i++) { size = row_sizes[i]; for (int j = 0; j < size; j++) { idx = col_indices[ctr]; val = vals[ctr++]; if ((int) idx >= A->partition->first_local_col && (int) idx <= A->partition->last_local_col) { A->on_proc->idx2.emplace_back(idx - A->partition->first_local_col); A->on_proc->vals.emplace_back(val); } else { A->off_proc->idx2.emplace_back(idx); A->off_proc->vals.emplace_back(val); } } A->on_proc->idx1[i+1] = A->on_proc->idx2.size(); A->off_proc->idx1[i+1] = A->off_proc->idx2.size(); } A->on_proc->nnz = A->on_proc->idx2.size(); A->off_proc->nnz = A->off_proc->idx2.size(); A->finalize(); return A; }
29.228155
99
0.556884
lwhZJU
ce9a7783cfc131e34abe6d5a90009f4e96e5d442
182
cpp
C++
VR Engine/src/CompanionWindowShader.cpp
jeroennelis/VR_engine
80a8cfd26181b8060c6a36f107beaa160c370a23
[ "Apache-2.0" ]
null
null
null
VR Engine/src/CompanionWindowShader.cpp
jeroennelis/VR_engine
80a8cfd26181b8060c6a36f107beaa160c370a23
[ "Apache-2.0" ]
null
null
null
VR Engine/src/CompanionWindowShader.cpp
jeroennelis/VR_engine
80a8cfd26181b8060c6a36f107beaa160c370a23
[ "Apache-2.0" ]
null
null
null
#include "CompanionWindowShader.h" CompanionWindowShader::CompanionWindowShader(const std::string & path) :Shader(path) { } CompanionWindowShader::~CompanionWindowShader() { }
13
70
0.774725
jeroennelis
ce9cd661c526fc2cd1cac19b1bd9ab0d5a3e514c
4,329
cpp
C++
gwen/Util/ControlFactory/PageControl_Factory.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/Util/ControlFactory/PageControl_Factory.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/Util/ControlFactory/PageControl_Factory.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
#include "Gwen/Util/ControlFactory.h" #include "Gwen/Controls.h" namespace Gwen { namespace ControlFactory { using namespace Gwen; namespace Properties { class NumPages : public ControlFactory::Property { GWEN_CONTROL_FACTORY_PROPERTY(NumPages, "The number of pages we have"); String GetValue(Controls::Base* ctrl) { return Utility::Format("%i", (int)gwen_cast<Controls::PageControl>( ctrl)->GetPageCount()); } void SetValue(Controls::Base* ctrl, const String& str) { int num; if (sscanf(str.c_str(), "%i", &num) != 1) return; gwen_cast<Controls::PageControl>(ctrl)->SetPageCount(num); } }; class FinishName : public ControlFactory::Property { GWEN_CONTROL_FACTORY_PROPERTY(FinishName, "The name of the finish button"); String GetValue(Controls::Base* ctrl) { Gwen::Controls::PageControl* pControl = gwen_cast<Gwen::Controls::PageControl>(ctrl); return pControl->FinishButton()->GetName(); } void SetValue(Controls::Base* ctrl, const String& str) { Gwen::Controls::PageControl* pControl = gwen_cast<Gwen::Controls::PageControl>(ctrl); pControl->FinishButton()->SetName(str); } }; } class PageControl_Factory : public Gwen::ControlFactory::Base { public: GWEN_CONTROL_FACTORY_CONSTRUCTOR(PageControl_Factory, Gwen::ControlFactory::Base) { AddProperty(new Properties::NumPages()); AddProperty(new Properties::FinishName()); } virtual Gwen::String Name() { return "PageControl"; } virtual Gwen::String BaseName() { return "Base"; } virtual Gwen::Controls::Base* CreateInstance(Gwen::Controls::Base* parent) { Gwen::Controls::PageControl* pControl = new Gwen::Controls::PageControl(parent); pControl->SetSize(300, 300); pControl->SetPageCount(1); return pControl; } // // Called when a child is clicked on in the editor // virtual bool ChildTouched(Gwen::Controls::Base* ctrl, Gwen::Controls::Base* pChildControl) { Gwen::Controls::PageControl* pControl = gwen_cast<Gwen::Controls::PageControl>( ctrl); if (pChildControl == pControl->NextButton()) { pControl->NextButton()->DoAction(); return true; } if (pChildControl == pControl->BackButton()) { pControl->BackButton()->DoAction(); return true; } return false; } // // A child is being dropped on this position.. set the parent // properly // void AddChild(Gwen::Controls::Base* ctrl, Gwen::Controls::Base* child, const Gwen::Point& pos) { Gwen::Controls::PageControl* pControl = gwen_cast<Gwen::Controls::PageControl>( ctrl); AddChild(ctrl, child, pControl->GetPageNumber()); } void AddChild(Gwen::Controls::Base* ctrl, Gwen::Controls::Base* child, int iPage) { Gwen::Controls::PageControl* pControl = gwen_cast<Gwen::Controls::PageControl>( ctrl); if (!pControl->GetPage(iPage)) iPage = 0; SetParentPage(child, iPage); child->SetParent(pControl->GetPage(iPage)); } }; GWEN_CONTROL_FACTORY(PageControl_Factory); } }
30.702128
96
0.478632
Oipo
ce9dff368a7649c3796f8f77a41fa1500dbd6de4
1,803
cpp
C++
tests/tree-postorder.cpp
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
1
2020-05-08T08:55:55.000Z
2020-05-08T08:55:55.000Z
tests/tree-postorder.cpp
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
1
2020-01-16T23:22:52.000Z
2020-01-16T23:22:52.000Z
tests/tree-postorder.cpp
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
2
2020-07-01T01:35:55.000Z
2022-03-09T14:58:27.000Z
// #include <iostream> // #include <vector> // #include "../include/pruner.hpp" // For creating the MAIN // #define CATCH_CONFIG_MAIN // #include "catch.hpp" // int main () { TEST_CASE("Post order sequences respects all", "[postorder]") { // Tree 1 {1-0, 3-1, 2-1} : Multiple parents -------------------------------- std::vector< unsigned int > source = {1u, 2u, 3u}; std::vector< unsigned int > target = {0u, 1u, 1u}; // Initialization of a tree object unsigned int res; pruner::Tree<> tree1(source, target, res); // Looking at the data tree1.print(false); std::vector< unsigned int > po = tree1.get_postorder(); print(po); // Tree 2 {1-0, 3-1, 2-1} : Multiple parents --------------------------------- source = {2u, 2u, 3u}; target = {0u, 1u, 2u}; // Initialization of a tree object pruner::Tree<> tree2(source, target, res); // Looking at the data tree2.print(false); po = tree2.get_postorder(); print(po); // Tree 3 {1-0, 3-1, 2-1} : Multiple parents --------------------------------- source = {2u, 2u, 3u, 4u}; target = {0u, 1u, 2u, 2u}; // Initialization of a tree object pruner::Tree<> tree3(source, target, res); // Looking at the data tree3.print(false); po = tree3.get_postorder(); print(po); // Tree 4 {1-0, 3-1, 2-1} : Multiple parents --------------------------------- source = {2u, 2u, 3u, 4u, 5u, 5u}; target = {0u, 1u, 2u, 2u, 3u, 4u}; // Initialization of a tree object pruner::Tree<> tree4(source, target, res); // Looking at the data tree4.print(false); po = tree4.get_postorder(); print(po); REQUIRE(tree1.get_postorder().size() == 4u); // return 0; pruner::TreeIterator<> myiter(&tree1); myiter.top(); REQUIRE(myiter.id() == *myiter); // } }
25.757143
80
0.559068
USCbiostats
ce9f1d3a59ee2159f318d1b1705ababd3e587557
741
hpp
C++
include/scenes/TestScene.hpp
Hello56721/wars
d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026
[ "MIT" ]
1
2021-09-29T14:33:37.000Z
2021-09-29T14:33:37.000Z
include/scenes/TestScene.hpp
Hello56721/wars
d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026
[ "MIT" ]
null
null
null
include/scenes/TestScene.hpp
Hello56721/wars
d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026
[ "MIT" ]
null
null
null
#ifndef C32DE65B_193C_4675_A77E_2D558E3B681D #define C32DE65B_193C_4675_A77E_2D558E3B681D #include <Scene.hpp> #include <graphics/Shaders.hpp> #include <graphics/Sprite.hpp> namespace wars::scenes { // A Scene that was created merely for testing purposes. It will be removed // once I am done testing the engine (though it's source files will stay in // the repository). class TestScene: public Scene { public: TestScene(); virtual void update() override; virtual void render() override; virtual ~TestScene(); private: graphics::Shaders& m_shaders; graphics::Sprite m_hello; }; } #endif /* C32DE65B_193C_4675_A77E_2D558E3B681D */
23.903226
79
0.668016
Hello56721
cea5b7267975300c33b63905a2300402c09f7a1d
4,585
cpp
C++
matog/db-tool/matog/db/XAnalyse.cpp
mergian/matog
d03de27b92a0772ceac1c556293217ff91d405eb
[ "BSD-3-Clause" ]
1
2021-06-10T13:09:57.000Z
2021-06-10T13:09:57.000Z
matog/db-tool/matog/db/XAnalyse.cpp
mergian/matog
d03de27b92a0772ceac1c556293217ff91d405eb
[ "BSD-3-Clause" ]
null
null
null
matog/db-tool/matog/db/XAnalyse.cpp
mergian/matog
d03de27b92a0772ceac1c556293217ff91d405eb
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015 Nicolas Weber / GCC / TU-Darmstadt. All rights reserved. // Use of this source code is governed by the BSD 3-Clause license that can be // found in the LICENSE file. #include <matog/shared.h> #include <matog/log.h> #include <matog/util.h> #include <matog/cuda.h> #include "../db.h" namespace matog { namespace db { //------------------------------------------------------------------- XAnalyse::XAnalyse(int argc, char** argv) : m_db (DB::getInstance()), m_gpuName (0), m_benchmarkName (0) { if(argc < 3) { L_ERROR("usage: GPU BENCHMARK [ALGORITHM ...]"); exit(1); } m_gpuName = argv[0]; m_benchmarkName = argv[1]; CHECK(loadAllDurations()); // TODO: analyse brute force results aswell!!! for(int i = 2; i < argc; i++) { CHECK(attach(argv[i])); CHECK(analyse(argv[i])); CHECK(detach()); L_INFO(" "); } } //------------------------------------------------------------------- Result XAnalyse::analyse(const char* algorithm) { // get duration sqlite3_stmt* stmt; double duration = 0.0; RCHECK(m_db.prepare(stmt, "SELECT SUM(duration) FROM tmp." DB_PROFILINGS ";")); RCHECK(m_db.exec(stmt, &DB::getDoubleCallback, &duration)); L_INFO("%s (%fs)", algorithm, duration); // get other sqlite3_stmt* kernels, *calls, *runs, *runs2; RCHECK(m_db.prepare(kernels, "SELECT id, name FROM main." DB_KERNELS " ORDER BY name;")); RCHECK(m_db.prepare(calls, "SELECT id FROM main." DB_CALLS " WHERE kernel_id = ?;")); RCHECK(m_db.prepare(runs, "SELECT hash, duration, COUNT(*) FROM tmp." DB_RUNS " WHERE duration != 0 AND call_id = ? GROUP BY call_id HAVING MIN(duration);")); RCHECK(m_db.prepare(runs2, "SELECT COUNT(*) FROM tmp." DB_RUNS " WHERE call_id = ?;")); SQL_LOOP(kernels) const uint32_t kernelId = sqlite3_column_int(kernels, 0); const char* kernelName = (const char*)sqlite3_column_text(kernels, 1); uint32_t runCount = 0; uint32_t notKilledCount = 0; double measuredTime = 0.0; double realTime = 0.0; RCHECK(sqlite3_reset(calls)); RCHECK(sqlite3_bind_int(calls, 1, kernelId)); SQL_LOOP(calls) const uint32_t callId = sqlite3_column_int(calls, 0); // DURATIONS RCHECK(sqlite3_reset(runs)); RCHECK(sqlite3_bind_int(runs, 1, callId)); CallMap::const_iterator it = m_durations.find(callId); if(it == m_durations.end()) RCHECK(MatogResult::UNKNOWN_ERROR); const DurationMap& map = it->second; SQL_LOOP(runs) const uint64_t hash = sqlite3_column_int64(runs, 0); const uint64_t measured = sqlite3_column_int64(runs, 1); notKilledCount += sqlite3_column_int(runs, 2); DurationMap::const_iterator it = map.find(hash); if(it == map.end()) { L_ERROR("Unable to find duration from %016llX", (unsigned long long int)hash); RCHECK(MatogResult::UNKNOWN_ERROR); } const uint64_t real = it->second; measuredTime += measured / 1000000.0; realTime += real / 1000000.0; SQL_LEND() // RUN COUNT RCHECK(sqlite3_reset(runs2)); RCHECK(sqlite3_bind_int(runs2, 1, callId)); RCHECK(sqlite3_step(runs2)); runCount += sqlite3_column_int(runs2, 0); SQL_LEND() L_INFO("%s: %f %f %u/%u", kernelName, measuredTime, realTime, notKilledCount, runCount); SQL_LEND() RCHECK(m_db.finalize(kernels)); RCHECK(m_db.finalize(calls)); RCHECK(m_db.finalize(runs)); RCHECK(m_db.finalize(runs2)); return MatogResult::SUCCESS; } //------------------------------------------------------------------- Result XAnalyse::attach(const char* algorithm) { std::ostringstream ss; ss << m_gpuName << "-" << m_benchmarkName << "-" << algorithm << ".db"; const std::string str = ss.str(); return m_db.attach(str.c_str(), "tmp"); } //------------------------------------------------------------------- Result XAnalyse::detach(void) { return m_db.detach("tmp"); } //------------------------------------------------------------------- Result XAnalyse::loadAllDurations(void) { L_INFO("loading durations..."); sqlite3_stmt* stmt; uint32_t lastCallId = 0; DurationMap* map; RCHECK(m_db.prepare(stmt, "SELECT call_id, hash, duration FROM " DB_RUNS " ORDER BY call_id;")); SQL_LOOP(stmt) uint32_t callId = sqlite3_column_int(stmt, 0); // get correct map if(callId != lastCallId) { map = &m_durations[callId]; lastCallId = callId; } // insert map->emplace(MAP_EMPLACE(sqlite3_column_int64(stmt, 1), sqlite3_column_int64(stmt, 2))); SQL_LEND() RCHECK(m_db.finalize(stmt)); L_INFO("done"); return MatogResult::SUCCESS; } //------------------------------------------------------------------- } }
27.45509
159
0.620938
mergian
cea66dafe7fe4922f0779bc38f1c1edffcfc88d1
906
cpp
C++
src/theory/builtin/theory_builtin.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
src/theory/builtin/theory_builtin.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
src/theory/builtin/theory_builtin.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file theory_builtin.cpp ** \verbatim ** Top contributors (to current version): ** Morgan Deters, Tim King ** This file is part of the CVC4 project. ** Copyright (c) 2009-2016 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. ** All rights reserved. See the file COPYING in the top-level source ** directory for licensing information.\endverbatim ** ** \brief Implementation of the builtin theory. ** ** Implementation of the builtin theory. **/ #include "theory/builtin/theory_builtin.h" #include "theory/valuation.h" #include "expr/kind.h" #include "theory/theory_model.h" using namespace std; namespace CVC4 { namespace theory { namespace builtin { }/* CVC4::theory::builtin namespace */ }/* CVC4::theory */ }/* CVC4 namespace */
29.225806
80
0.65894
guykatzz
cea6a4131c4624c35d0beac5401a138d23e1b28e
104
cpp
C++
src/control/Signal.cpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
10
2015-02-17T15:27:50.000Z
2021-12-10T08:34:13.000Z
src/control/Signal.cpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
6
2016-05-10T17:11:09.000Z
2022-03-31T07:52:11.000Z
src/control/Signal.cpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
13
2016-05-01T09:56:51.000Z
2022-03-28T09:27:49.000Z
#include <eeros/types.hpp> namespace eeros { namespace control { uint16_t signalCounter = 1; }; };
13
29
0.692308
ClaudiaVisentin
cea7481197caf24e8155c88a1911c8ddde1f3f6b
5,023
cpp
C++
inf8601-lab1-2.1.0/src/dragon_tbb.cpp
oliviercotte/Parallel-system
c24155f7302218c0547ba5c33de48098ed441bec
[ "MIT" ]
null
null
null
inf8601-lab1-2.1.0/src/dragon_tbb.cpp
oliviercotte/Parallel-system
c24155f7302218c0547ba5c33de48098ed441bec
[ "MIT" ]
null
null
null
inf8601-lab1-2.1.0/src/dragon_tbb.cpp
oliviercotte/Parallel-system
c24155f7302218c0547ba5c33de48098ed441bec
[ "MIT" ]
null
null
null
/* * dragon_tbb.c * * Created on: 2011-08-17 * Author: Francis Giraldeau <francis.giraldeau@gmail.com> */ #include <iostream> extern "C" { #include "dragon.h" #include "color.h" #include "utils.h" } #include "dragon_tbb.h" #include "tbb/tbb.h" #include "TidMap.h" using namespace std; using namespace tbb; class DragonLimits { public: DragonLimits() { piece_init(&aPiece); } DragonLimits(const DragonLimits& dl, split) { piece_init(&aPiece); } void operator()(const blocked_range<uint64_t>& range) { piece_limit(range.begin(), range.end(), &aPiece); } void join(const DragonLimits& dl) { piece_merge(&aPiece, dl.mGetPiece()); } piece_t mGetPiece() const { return aPiece; } private: piece_t aPiece; }; class DragonDraw { public: DragonDraw(struct draw_data *draw) { aDrawData = draw; aTidMap = new TidMap(aDrawData->nb_thread); } DragonDraw(const DragonDraw& dd, split) { aDrawData = dd.mGetDrawData(); aTidMap = new TidMap(aDrawData->nb_thread); } void operator()(const blocked_range<uint64_t>& range) const { printf("DragonDraw id := %i, tid := %i , begin := %lu, end := %lu\n", aDrawData->id, aTidMap->getIdFromTid(gettid()), range.begin(), range.end()); dragon_draw_raw(range.begin(), range.end(), aDrawData->dragon, aDrawData->dragon_width, aDrawData->dragon_height, aDrawData->limits, aDrawData->id); } struct draw_data* mGetDrawData() const { return aDrawData; } private: TidMap* aTidMap; struct draw_data *aDrawData; }; class DragonRender { public: DragonRender(struct draw_data *data) { aDrawData = data; } DragonRender(const DragonRender& dr, split) { aDrawData = dr.mGetDrawData(); } void operator()(const blocked_range<int>& r) const { scale_dragon(r.begin(), r.end(), aDrawData->image, aDrawData->image_width, aDrawData->image_height, aDrawData->dragon, aDrawData->dragon_width, aDrawData->dragon_height, aDrawData->palette); } struct draw_data* mGetDrawData() const { return aDrawData; } private: struct draw_data *aDrawData; }; class DragonClear { public: DragonClear(struct draw_data *data) { aDrawData = data; } DragonClear(DragonClear& dc, split) { aDrawData = dc.mGetDrawData(); } void operator()(const blocked_range<int>& range) const { init_canvas(range.begin(), range.end(), aDrawData->dragon, -1); } struct draw_data* mGetDrawData() const { return aDrawData; } private: struct draw_data *aDrawData; }; int dragon_draw_tbb(char **canvas, struct rgb *image, int width, int height, uint64_t size, int nb_thread) { struct draw_data data; limits_t limits; char *dragon = NULL; int dragon_width; int dragon_height; int dragon_surface; int scale_x; int scale_y; int scale; int deltaJ; int deltaI; struct palette *palette = init_palette(nb_thread); if (palette == NULL) return -1; /* 1. Calculer les limites du dragon */ dragon_limits_tbb(&limits, size, nb_thread); dragon_width = limits.maximums.x - limits.minimums.x; dragon_height = limits.maximums.y - limits.minimums.y; dragon_surface = dragon_width * dragon_height; scale_x = dragon_width / width + 1; scale_y = dragon_height / height + 1; scale = (scale_x > scale_y ? scale_x : scale_y); deltaJ = (scale * width - dragon_width) / 2; deltaI = (scale * height - dragon_height) / 2; dragon = (char *) malloc(dragon_surface); if (dragon == NULL) { free_palette(palette); *canvas = NULL; return -1; } data.nb_thread = nb_thread; data.dragon = dragon; data.image = image; data.size = size; data.image_height = height; data.image_width = width; data.dragon_width = dragon_width; data.dragon_height = dragon_height; data.limits = limits; data.scale = scale; data.deltaI = deltaI; data.deltaJ = deltaJ; data.palette = palette; task_scheduler_init init(nb_thread); /* 2. Initialiser la surface : DragonClear */ size_t grainsize = dragon_surface / nb_thread; DragonClear dc(&data); parallel_for(blocked_range<int>(0, dragon_surface, grainsize), dc); /* 3. Dessiner le dragon : DragonDraw */ grainsize = data.size / (nb_thread * nb_thread); DragonDraw dd(&data); for (int i = 0; i < nb_thread; ++i) { data.id = i; uint64_t start = i * data.size / nb_thread; uint64_t end = (i + 1) * data.size / nb_thread; parallel_for(blocked_range<uint64_t>(start, end, grainsize), dd); } /* 4. Effectuer le rendu final : DragonRender */ grainsize = data.image_height / nb_thread; DragonRender dr(&data); parallel_for(blocked_range<int>(0, data.image_height, grainsize), dr); init.terminate(); free_palette(palette); *canvas = dragon; return 0; } /* * Calcule les limites en terme de largeur et de hauteur de * la forme du dragon. Requis pour allouer la matrice de dessin. */ int dragon_limits_tbb(limits_t *limits, uint64_t size, int nb_thread) { DragonLimits lim; size_t grainsize = size / nb_thread; parallel_reduce(blocked_range<uint64_t>(0, size, grainsize), lim); piece_t piece = lim.mGetPiece(); *limits = piece.limits; return 0; }
23.147465
76
0.703365
oliviercotte
cebbee5c13026874a2f1cf8930de0f557e8bfb6e
646
cpp
C++
variateArray1.cpp
maxerin/GitTest
e2cb5bc62ff55923e8f2845ce24b47cce83acc3c
[ "Apache-2.0" ]
null
null
null
variateArray1.cpp
maxerin/GitTest
e2cb5bc62ff55923e8f2845ce24b47cce83acc3c
[ "Apache-2.0" ]
null
null
null
variateArray1.cpp
maxerin/GitTest
e2cb5bc62ff55923e8f2845ce24b47cce83acc3c
[ "Apache-2.0" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <sstream> using namespace std; /* Test cases 2 2 3 1 5 4 5 1 2 8 9 3 0 1 1 3 */ int main() { int n, q; cin >> n >> q; int** v = new int*[n]; int sz = 0; for (int i = 0; i < n; ++i) { cin >> sz; v[i] = new int[sz]; for (int j = 0; j < sz; ++j) { cin >> v[i][j]; }; }; int* re = new int[q]; for (int i = 0; i < q; ++i) { int first, second; cin >> first >> second; re[i] = v[first][second]; }; for (int i = 0; i < q; i++) cout<<re[i]<<endl; return 0; }
14.355556
34
0.4613
maxerin
cec08afa5d27601d3ba6d21c7d42a13ad1df4d37
2,612
hpp
C++
NumberWithUnits.hpp
AndreyFriedman/num-with-units
007030e5353402a6739d3c8b8be871ee37ffc259
[ "MIT" ]
null
null
null
NumberWithUnits.hpp
AndreyFriedman/num-with-units
007030e5353402a6739d3c8b8be871ee37ffc259
[ "MIT" ]
null
null
null
NumberWithUnits.hpp
AndreyFriedman/num-with-units
007030e5353402a6739d3c8b8be871ee37ffc259
[ "MIT" ]
null
null
null
#ifndef NUMBERWITHUNITS_ #define NUMBERWITHUNITS_ #include <iostream> #include <string> #include <unordered_map> #include <exception> namespace ariel { typedef struct unit{ std::string s; double value; } unit; class NumberWithUnits{ private: double value; std::string unit; bool checkKey(std::string key) const; NumberWithUnits convert (std::string u1,std::string u2, double v) const; bool way(std::string t1, std::string t2) const; static std::unordered_map<std::string,ariel::unit> map; public: NumberWithUnits(){} NumberWithUnits(const NumberWithUnits & other){ this->value =other.value; this->unit =other.unit; } NumberWithUnits(double value,std::string unit){ if(unit == "") throw std::invalid_argument(""); if (checkKey(unit)){ this->value = value; this->unit = unit; } else throw std::invalid_argument(""); } static void read_units(std::ifstream & stream); NumberWithUnits operator+ (const NumberWithUnits &other)const; NumberWithUnits operator+= (const NumberWithUnits& other); NumberWithUnits operator+ ()const; NumberWithUnits operator- (const NumberWithUnits &other)const; NumberWithUnits operator-= (const NumberWithUnits& other); NumberWithUnits operator- ()const; NumberWithUnits & operator++ (); NumberWithUnits operator++( int dummy); NumberWithUnits & operator-- (); NumberWithUnits operator-- (int dummy); bool operator< (const NumberWithUnits & other)const; bool operator<= (const NumberWithUnits & other)const; bool operator> (const NumberWithUnits & other)const; bool operator>= (const NumberWithUnits & other)const; bool operator== (const NumberWithUnits & other)const; bool operator!= (const NumberWithUnits & other)const; friend std::ostream & operator<< (std::ostream & os, const NumberWithUnits & other); friend std::istream & operator>> (std::istream & is, NumberWithUnits & other); friend NumberWithUnits operator* (double bap,const NumberWithUnits & n); NumberWithUnits operator* ( double v); std::string getunit()const{ return unit; } double getvalue()const{ return value; } void setvalue(double value){ this->value = value; } }; } #endif
34.368421
92
0.602986
AndreyFriedman
cecfb3edf1a044fa934c6b6bd761a0db6bf9eea9
334
cpp
C++
leetcode/dp/easy/509.fibonacci-number.cpp
saurabhraj042/dsaPrep
0973a03bc565a2850003c7e48d99b97ff83b1d01
[ "MIT" ]
23
2021-10-30T04:11:52.000Z
2021-11-27T09:16:18.000Z
leetcode/dp/easy/509.fibonacci-number.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
null
null
null
leetcode/dp/easy/509.fibonacci-number.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
4
2021-10-30T03:26:05.000Z
2021-11-14T12:15:04.000Z
// https://leetcode.com/problems/fibonacci-number/ class Solution { public: int fib(int n) { // Optimal DP soluchan ^_^ int dp[31] = {0}; dp[0] = 0; dp[1] = 1; for(int i= 2;i<=n;i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp[n]; } };
19.647059
50
0.398204
saurabhraj042
ced149eae597bd1145e9c123ff34805727b4e06a
154
cpp
C++
cppcheck/data/c_files/224.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
2
2022-03-23T12:16:20.000Z
2022-03-31T06:19:40.000Z
cppcheck/data/c_files/224.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
cppcheck/data/c_files/224.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
void RTCSessionDescriptionRequestImpl::requestFailed(const String& error) { if (m_errorCallback) m_errorCallback->handleEvent(error); clear(); }
19.25
73
0.766234
awsm-research
cedf5b2d27c672cbed92dc6d3755136d04d3bc7d
3,242
cpp
C++
CaWE/MapEditor/Commands/ModifyModel.cpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
CaWE/MapEditor/Commands/ModifyModel.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
CaWE/MapEditor/Commands/ModifyModel.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #include "ModifyModel.hpp" #include "../MapModel.hpp" #include "../MapDocument.hpp" #include "../../GameConfig.hpp" #include "ClipSys/CollisionModelMan.hpp" #include "ClipSys/CollisionModel_base.hpp" CommandModifyModelT::CommandModifyModelT(MapDocumentT& MapDoc, MapModelT* Model, const wxString& ModelFileName, const wxString& CollisionModelFileName, const wxString& Label, float Scale, IntrusivePtrT<AnimExprStandardT> AnimExpr, float FrameTimeOff, float FrameTimeScale, bool Animated) : m_MapDoc(MapDoc), m_Model(Model), m_NewModelFileName(ModelFileName), m_OldModelFileName(Model->m_ModelFileName), m_NewCollModelFileName(CollisionModelFileName), m_OldCollModelFileName(Model->m_CollModelFileName), m_NewLabel(Label), m_OldLabel(Model->m_Label), m_NewScale(Scale), m_OldScale(Model->m_Scale), m_NewAnimExpr(AnimExpr), m_OldAnimExpr(Model->m_AnimExpr), m_NewFrameTimeOff(FrameTimeOff), m_OldFrameTimeOff(Model->m_FrameOffset), m_NewFrameTimeScale(FrameTimeScale), m_OldFrameTimeScale(Model->m_FrameTimeScale), m_NewAnimated(Animated), m_OldAnimated(Model->m_Animated) { } bool CommandModifyModelT::Do() { wxASSERT(!m_Done); if (m_Done) return false; // Build observer notification parameters. ArrayT<MapElementT*> MapElements; ArrayT<BoundingBox3fT> OldBounds; MapElements.PushBack(m_Model); OldBounds.PushBack(m_Model->GetBB()); m_Model->m_ModelFileName =m_NewModelFileName; m_Model->m_Model =m_MapDoc.GetGameConfig()->GetModel(m_NewModelFileName); m_Model->m_CollModelFileName=m_NewCollModelFileName; m_Model->m_Label =m_NewLabel; m_Model->m_Scale =m_NewScale; m_Model->m_AnimExpr =m_NewAnimExpr; m_Model->m_FrameOffset =m_NewFrameTimeOff, m_Model->m_FrameTimeScale =m_NewFrameTimeScale, m_Model->m_Animated =m_NewAnimated; m_MapDoc.UpdateAllObservers_Modified(MapElements, MEMD_PRIMITIVE_PROPS_CHANGED, OldBounds); m_Done=true; return true; } void CommandModifyModelT::Undo() { wxASSERT(m_Done); if (!m_Done) return; // Build observer notification parameters. ArrayT<MapElementT*> MapElements; ArrayT<BoundingBox3fT> OldBounds; MapElements.PushBack(m_Model); OldBounds.PushBack(m_Model->GetBB()); m_Model->m_ModelFileName =m_OldModelFileName; m_Model->m_Model =m_MapDoc.GetGameConfig()->GetModel(m_OldModelFileName); m_Model->m_CollModelFileName=m_OldCollModelFileName; m_Model->m_Label =m_OldLabel; m_Model->m_Scale =m_OldScale; m_Model->m_AnimExpr =m_OldAnimExpr; m_Model->m_FrameOffset =m_OldFrameTimeOff, m_Model->m_FrameTimeScale =m_OldFrameTimeScale, m_Model->m_Animated =m_OldAnimated; m_MapDoc.UpdateAllObservers_Modified(MapElements, MEMD_PRIMITIVE_PROPS_CHANGED, OldBounds); m_Done=false; } wxString CommandModifyModelT::GetName() const { return "Modify model"; }
31.173077
111
0.720234
dns
cedff17fe333b554e3f64e5aef703ec7d0492757
1,597
hpp
C++
Server/Server/Network.hpp
pablotomico/ProjectMORPG
3dd5c7d001cd5f59bd6fafd310d4eb1c51ae3089
[ "MIT" ]
2
2021-05-30T16:34:26.000Z
2021-08-03T11:37:37.000Z
Server/Server/Network.hpp
pablotomico/ProjectMORPG
3dd5c7d001cd5f59bd6fafd310d4eb1c51ae3089
[ "MIT" ]
null
null
null
Server/Server/Network.hpp
pablotomico/ProjectMORPG
3dd5c7d001cd5f59bd6fafd310d4eb1c51ae3089
[ "MIT" ]
null
null
null
#pragma once #define _WINSOCK_DEPRECATED_NO_WARNINGS // for WSAAsyncSelect #include <WinSock2.h> #include <WS2tcpip.h> #include <list> #include <unordered_map> #include <queue> #include <SFML/System.hpp> #include "Client.hpp" #pragma comment(lib, "ws2_32.lib") #define WM_SOCKET (WM_USER + 1) #define SERVERIP "127.0.0.1" #define SERVERPORT "5555" #define TIMESTEP 50 class Network { public: Network(HWND l_window); ~Network(); Client* RegisterClient(SOCKET l_clientSocket, sockaddr_in l_address); void RemoveClient(ClientID l_clientID, SOCKET l_clientSocket); ClientID GetClientID(SOCKET l_clientSocket); Client* GetClient(ClientID l_clientID); std::unordered_map<SOCKET, ClientID>* GetClientSocket(); bool ReadUDP(); bool WriteUDP(); bool ReadTCP(SOCKET l_tcpSocket); bool WriteTCP(ClientID l_client); void QueueTCPMessage(NetMessage l_message, ClientID l_client); void NotifyDisconnection(ClientID l_client); private: void StartWinSock(); void ProcessMessage(const NetMessage* l_message); public: int m_tick; float m_timestep; sf::Clock m_clock; sf::Time m_netTime; SOCKET m_serverTCPSocket; SOCKET m_serverUDPSocket; bool m_TCPWriteReady; bool m_UDPWriteReady; private: HWND m_window; int m_clientCount; std::unordered_map<SOCKET, ClientID> m_clientSocket; std::unordered_map<ClientID, Client*> m_clients; ClientID m_availableID; char m_udpReadBuffer[sizeof NetMessage]; char m_tcpReadBuffer[sizeof NetMessage]; std::queue<NetMessage> m_udpMsgQueue; int m_udpReadCount; int m_tcpReadCount; // TODO: Maybe a queue with available ids };
20.74026
70
0.77583
pablotomico
cee1b328714115caaae03c466d11e2b9bfbbad75
565
hpp
C++
libs/input/include/sge/input/joypad/ff/type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/input/include/sge/input/joypad/ff/type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/input/include/sge/input/joypad/ff/type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 SGE_INPUT_JOYPAD_FF_TYPE_HPP_INCLUDED #define SGE_INPUT_JOYPAD_FF_TYPE_HPP_INCLUDED #include <sge/input/joypad/ff/type_fwd.hpp> namespace sge::input::joypad::ff { enum class type { constant, spring, friction, damper, inertia, ramp, square, sine, saw_up, saw_down, custom, fcppt_maximum = custom }; } #endif
17.121212
61
0.707965
cpreh
cee2e5dacc70cacb04f9d72dba7983963af2225d
4,643
cpp
C++
test.cpp
michibo/sprpwr
a1ec573d78edf44e68d517fe2b836abaf9e7f628
[ "MIT" ]
null
null
null
test.cpp
michibo/sprpwr
a1ec573d78edf44e68d517fe2b836abaf9e7f628
[ "MIT" ]
null
null
null
test.cpp
michibo/sprpwr
a1ec573d78edf44e68d517fe2b836abaf9e7f628
[ "MIT" ]
null
null
null
// This C++ header is part of the sprpwr library. // With this library multivariate formal power // series can be expanded. // // Author: Michael Borinsky // License: MIT // Copyright 2019 #include <iostream> #include <iterator> #include <algorithm> #include <chrono> #include <functional> #include <cmath> #include <gmpxx.h> #include "powerseries.hpp" using namespace std; template<class T1, class T2> void check( T1 entry1, T2 entry2, int n ) { if(Equal(entry1, entry2, n)) cout << "CHECK PASSED" << endl; else cout << "CHECK FAILED" << endl; } template<class Func> double time( Func&& func ) { auto start = chrono::high_resolution_clock::now(); func(); auto end = chrono::high_resolution_clock::now(); auto diff = end - start; return chrono::duration <double> (diff).count(); } template<class Func> void benchmark(Func func, int multiplier) { int n = 100; int total = 0; double sum_logd = 0.0; double sum_logt = 0.0; double sum_logdlogd = 0.0; double sum_logdlogt = 0.0; double sum_logtlogt = 0.0; auto start = chrono::high_resolution_clock::now(); for(int i=0;i<n;i++) { int d = i*multiplier; double t = time([=]() { func(d); } ); total += d; cout << "." << flush; if (i!= 0) { sum_logd += log(d); sum_logdlogd += log(d)*log(d); sum_logt += log(t); sum_logdlogt += log(t)*log(d); sum_logtlogt += log(t)*log(t); } } cout << endl; double gamma = (n*sum_logdlogt - sum_logd*sum_logt)/(n*sum_logdlogd - sum_logd*sum_logd); double beta = sum_logt/n - gamma*sum_logd/n; double e_error_sqr = 1.0/(n*(n-2))*(n*sum_logtlogt - sum_logt*sum_logt- gamma*(n*sum_logdlogd - sum_logd*sum_logd)); double gamma_error_sqr = n*e_error_sqr/(n*sum_logdlogd- sum_logd*sum_logd); auto end = chrono::high_resolution_clock::now(); auto diff = end - start; cout << "Total time: " << chrono::duration <double> (diff).count() << "s" << endl; cout << "Total compute: " << total << endl; cout << "Max compute: " << (n-1)*multiplier << endl; cout << "exp " << gamma << " +/- " << sqrt(gamma_error_sqr) << endl; cout << "C (" << exp(beta) << " +/- " << exp(beta)*sqrt(gamma_error_sqr) << ") s" << endl; } template<class T> void check_1d() { using namespace sprpwr; auto ONE = PowerSeries<T>{1}; auto X = PowerSeries<T>{0,1}; cout << T(1)/T(10) << endl; cout << ONE << endl; cout << X << endl; cout << (1+X)*(1+X) << endl; cout << 1/(1-X-X*X) << endl; cout << 1/(1-X)*(1-X) << endl; cout << diffo(1/(1-X)) << endl; cout << inteo(1/(1-X)) << endl; cout << log(1/(1-X)) << endl; cout << exp(X) << endl; cout << X/(exp(X)-1) << endl; check(1+2*X+X*X, (1+X)*(1+X), 50 ); check(1-2*X+X*X, (1-X)*(1-X), 50 ); check(1-X*X, (1-X)*(1+X), 50); check(1/(1-X)*(1-X), ONE, 50); cout << "Polynom:" << endl; benchmark([&](int n) { Eval(1+X, n); }, 1000); cout << "Polynom squared:" << endl; benchmark([&](int n) { Eval((1+X)*(1+X), n); }, 1000); cout << "Geometric series:" << endl; benchmark([&](int n) { Eval(1/(1-X), n); }, 10); cout << "Geometric series diffo:" << endl; benchmark([&](int n) { Eval(diffo(1/(1-X)), n); }, 10); cout << "Geometric series squared:" << endl; auto geo = 1/(1-X); benchmark([&](int n) { Eval(geo*geo, n); }, 5); cout << "Geometric series squared2:" << endl; benchmark([&](int n) { Eval(geo/(1-X), n); }, 50); cout << "Fibonacci:" << endl; benchmark([&](int n) { Eval(1/(1-X-X*X), n); }, 50); } template<class T> void check_2d() { using namespace sprpwr; auto Z0 = PowerSeries<T>{0}; auto O0 = PowerSeries<T>{1}; auto X0 = PowerSeries<T>{0,1}; auto ONE = PowerSeries<PowerSeries<T>>(1); auto X = PowerSeries<PowerSeries<T>>{X0}; auto Y = PowerSeries<PowerSeries<T>>{Z0, O0}; cout << X*X << endl; cout << 1/(1-Y-X*Y) << endl; cout << exp(X*log(1+Y)) << endl; cout << exp(X*(exp(Y)-1)) << endl; check(1/(1-X-X*Y)*(1-X*(1+Y)), ONE, 50); cout << "Polynom squared:" << endl; benchmark([&](int n) { Eval((1+X)*(1+X), n); }, 10); cout << "Polynom product:" << endl; benchmark([&](int n) { Eval((1-Y-X*Y)*(1-Y*(1+Y)), n); }, 2); cout << "Binomial:" << endl; benchmark([&](int n) { Eval(1/(1-Y-X*Y), n); }, 2); } int main() { cout << "Check 1d" << endl; check_1d<mpq_class>(); cout << "Check 2d" << endl; check_2d<mpq_class>(); }
25.097297
120
0.539953
michibo
cee8037d931c29951736acde86b76fabda6f5f5d
2,391
cpp
C++
sources/Skybox.cpp
HamilcarR/Se-Hara
8b9168978f5b38e470945e0b74499b0664d52212
[ "MIT" ]
2
2016-11-29T04:32:32.000Z
2017-10-14T06:21:09.000Z
sources/Skybox.cpp
HamilcarR/ZeEngine
8b9168978f5b38e470945e0b74499b0664d52212
[ "MIT" ]
1
2016-11-24T04:38:42.000Z
2016-11-24T04:38:42.000Z
sources/Skybox.cpp
HamilcarR/Sahara
8b9168978f5b38e470945e0b74499b0664d52212
[ "MIT" ]
null
null
null
#include "../includes/Skybox.h" using namespace std; using namespace glm; float SIZE = 500.f; GLfloat VERTICES[] = { -SIZE, SIZE, -SIZE, -SIZE, -SIZE, -SIZE, SIZE, -SIZE, -SIZE, SIZE, -SIZE, -SIZE, SIZE, SIZE, -SIZE, -SIZE, SIZE, -SIZE, -SIZE, -SIZE, SIZE, -SIZE, -SIZE, -SIZE, -SIZE, SIZE, -SIZE, -SIZE, SIZE, -SIZE, -SIZE, SIZE, SIZE, -SIZE, -SIZE, SIZE, SIZE, -SIZE, -SIZE, SIZE, -SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, -SIZE, SIZE, -SIZE, -SIZE, -SIZE, -SIZE, SIZE, -SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, -SIZE, SIZE, -SIZE, -SIZE, SIZE, -SIZE, SIZE, -SIZE, SIZE, SIZE, -SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, SIZE, -SIZE, SIZE, SIZE, -SIZE, SIZE, -SIZE, -SIZE, -SIZE, -SIZE, -SIZE, -SIZE, SIZE, SIZE, -SIZE, -SIZE, SIZE, -SIZE, -SIZE, -SIZE, -SIZE, SIZE, SIZE, -SIZE, SIZE }; Skybox::Skybox(string vertex,string fragment) { shader = ShaderReader(vertex, fragment); string a(""); texture = new Texture(a,true); projectionMatrix = glGetUniformLocation(shader.getProgram(), "projection"); viewMatrix = glGetUniformLocation(shader.getProgram(), "view"); modelMatrix = glGetUniformLocation(shader.getProgram(), "model"); vec3 A(0,0,0); model = translate(model, A); glGenBuffers(1, &buf); glBindBuffer(GL_ARRAY_BUFFER, buf); glBufferData(GL_ARRAY_BUFFER, 36*3 * sizeof(float), VERTICES, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } Skybox::~Skybox() { } void Skybox::render(const mat4 projection,const mat4 vview) { angle += 0.000001F; shader.useProgram(true); texture->BindCubeMap(); mat4 view = vview; model = rotate(angle, vec3(0, 1, 0)); glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, value_ptr(projection)); glUniformMatrix4fv(viewMatrix, 1, GL_FALSE, value_ptr(view)); glUniformMatrix4fv(modelMatrix, 1, GL_FALSE, value_ptr(model)); glBindBuffer(GL_ARRAY_BUFFER, buf); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_TRIANGLES, 0, 36); glDisableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); texture->UnBindCubeMap(); shader.useProgram(false); } void Skybox::setScale(vec3 sc) { scaleSkybox = sc; }
19.128
80
0.63279
HamilcarR
ceeb473dc546c400b5feb251ced2cb73385ea080
204
cpp
C++
pass/fplan/node_hier_floorp.cpp
arikyueh/livehd
cbbf13e77359cf135638b3710fd3ea4a6c895b68
[ "BSD-3-Clause" ]
1
2021-01-07T00:15:00.000Z
2021-01-07T00:15:00.000Z
pass/fplan/node_hier_floorp.cpp
arikyueh/livehd
cbbf13e77359cf135638b3710fd3ea4a6c895b68
[ "BSD-3-Clause" ]
null
null
null
pass/fplan/node_hier_floorp.cpp
arikyueh/livehd
cbbf13e77359cf135638b3710fd3ea4a6c895b68
[ "BSD-3-Clause" ]
null
null
null
#include "node_hier_floorp.hpp" void Node_hier_floorp::load_lg(LGraph* root, const std::string_view lgdb_path) { (void)root; (void)lgdb_path; // TODO: write this when traversal bug gets fixed }
22.666667
80
0.735294
arikyueh
ceee55d92cbb828f4f7ffcb10c7b3cd8427ee1ec
437,222
cpp
C++
Project1/leetcode.cpp
guannan-he/cppLearning
8fe3ff661afe1c814dbf44fc1ebfd9998f51eac6
[ "WTFPL" ]
null
null
null
Project1/leetcode.cpp
guannan-he/cppLearning
8fe3ff661afe1c814dbf44fc1ebfd9998f51eac6
[ "WTFPL" ]
null
null
null
Project1/leetcode.cpp
guannan-he/cppLearning
8fe3ff661afe1c814dbf44fc1ebfd9998f51eac6
[ "WTFPL" ]
null
null
null
#define NULL 0 #include <string> #include <vector> #include <queue> #include <unordered_set> #include <unordered_map> #include <map> #include <math.h> #include <stack> #include <list> #include <iostream> #include <set> #include <numeric> #include <algorithm> #include <sstream> using namespace std; //链表 #if 0 //Definition for singly-linked list. struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool isPalindrome(ListNode* head) { if (!head) { return true; } ListNode* fast, * slow, * tmp; fast = slow = head; while (fast && fast->next) {//找到前半部分尾巴 if (fast = fast->next->next) { slow = slow->next; } else { //fast = fast->next->next; break; }//slow变成前半部分尾巴 } fast = slow->next; while (fast && fast->next) {//反转后半部分链表 tmp = fast->next; fast->next = tmp->next; tmp->next = slow->next; slow->next = tmp; } fast = slow->next; slow = head; while (fast && fast->val == slow->val) { fast = fast->next; slow = slow->next; } if (fast) { return false; } else { return true; } } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* tmpA, * tmpB, * lastA, * tmp, * rootNode; rootNode = new ListNode(0); rootNode->next = l1; tmpA = l1; tmpB = l2; lastA = rootNode; while (tmpA && tmpB) { if (tmpA->val >= tmpB->val) { tmp = tmpB; tmpB = tmpB->next; tmp->next = tmpA; lastA->next = tmp; lastA = lastA->next; } else { lastA = tmpA; tmpA = tmpA->next; } } tmp = rootNode->next; delete rootNode; return tmp; } }; ListNode* listGen(string& str) { ListNode* tmp; ListNode* rootNode = new ListNode(0); tmp = rootNode; for (int i = 0; i < str.length(); i++) { tmp->next = new ListNode(str[i] - '0'); tmp = tmp->next; } tmp = rootNode->next; delete rootNode; return tmp; } int main(int argc, char* argv[]) { string str1("124"); string str2("134"); ListNode* newList1 = listGen(str1); ListNode* newList2 = listGen(str2); Solution newSolution; ListNode* res = newSolution.mergeTwoLists(newList1, newList2); return 0; } #endif //数组和字符串 #if 0 class Solution { public: int pivotIndex(vector<int>& nums) { int sum, leftSum; sum = leftSum = 0; int cnt = nums.size(); if (cnt < 3) { return -1; } for (int i = 0; i < cnt; i++) { sum += nums[i]; } //sum += nums[0]; for (int i = 0; i < cnt; i++) { sum -= nums[i]; if (leftSum == sum) { return i; } leftSum += nums[i]; } return -1; } int searchInsert(vector<int>& nums, int target) { int i = 0; int len = nums.size(); while (i < len && nums[i] < target) { i++; } if (i == len) { nums.push_back(target); return i; } if (nums[i] == target) { return i; } nums.insert(nums.begin() + i, target); return i; } int strStr(string haystack, string needle) { int needleLen = needle.size(); if (!needleLen) { return 0; } int haystackLen = haystack.size(); vector<int>* next = getNext(needle); int i, j, total; i = 0; j = 0; //total = haystackLen - needleLen; while (i < haystackLen && j < needleLen) { if (j == -1 || haystack[i] == needle[j]) { i++; j++; } else { j = (*next)[j]; } } if (j == needleLen) { return i - j; } else { return -1; } } vector<int>* getNext(string& str) { int strLen = str.size(); //int* res = new int(strLen); vector<int>* res = new vector<int>; //res[0] = -1; res->push_back(-1); int pos = 0; int cnt = -1; while (pos < strLen - 1) { if (cnt == -1 || str[pos] == str[cnt]) { ++cnt; ++pos; res->push_back(cnt); //res[pos] = cnt; } else { cnt = (*res)[cnt]; } } return res; } }; int main(int argc, char* argv[]) { Solution mysolution; //vector<int> inpt = {-1, -1, 0, -1, -1, 0}; //vector<int> inpt = {1, 7, 3, 6, 5, 6}; //vector<int> inpt = { 1, 3, 5, 6 }; //string str("cock"); //int i = str.size(); //int** pos = new int* [i]; //for (int j = 0; j < 9; j++) { // pos[j] = new int[i]; //} //int res = mysolution.searchInsert(inpt, 7); //int res = mysolution.pivotIndex(inpt); //string str = "abab"; //string str = "ABCDABD"; //vector<int> res = mysolution.getNext(str); string str1 = "aabaaabaaac"; string str2 = "aabaaac"; int res = mysolution.strStr(str1, str2); return 0; } #endif //队列 #if 0 struct node { int val = 0; node* next = 0; }; class MyCircularQueue { public: /** Initialize your data structure here. Set the size of the queue to be k. */ MyCircularQueue(int k) { size = k; rootNode = new node[k]; currentNode = rootNode; return; } /** Insert an element into the circular queue. Return true if the operation is successful. */ bool enQueue(int value) { if (isFull()) { return false; } currentNode->next = new node; currentNode = currentNode->next; currentNode->val = value; member++; return true; } /** Delete an element from the circular queue. Return true if the operation is successful. */ bool deQueue() { if (isEmpty()) { return false; } node* tmp = rootNode->next; rootNode->next = tmp->next; delete tmp; member--; if (isEmpty()) { currentNode = rootNode; } return true; } /** Get the front item from the queue. */ int Front() { if (isEmpty()) { return -1; } return rootNode->next->val; } /** Get the last item from the queue. */ int Rear() { if (isEmpty()) { return -1; } return currentNode->val; } /** Checks whether the circular queue is empty or not. */ bool isEmpty() { return member == 0; } /** Checks whether the circular queue is full or not. */ bool isFull() { return member == size; } private: node* rootNode, * currentNode; int size = 0; int member = 0; }; /** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue* obj = new MyCircularQueue(k); * bool param_1 = obj->enQueue(value); * bool param_2 = obj->deQueue(); * int param_3 = obj->Front(); * int param_4 = obj->Rear(); * bool param_5 = obj->isEmpty(); * bool param_6 = obj->isFull(); */ /////////////////////////////////////////////////////////////////////////////////////////////////////////// class Solution { public: int numIslands(vector<vector<char>>& grid) { int colSize = grid.size(); if (!colSize) {//无元素则返回 return 0; } int rolSize = grid[0].size(); int total = colSize * rolSize; char** visited = visitedGen(colSize, rolSize); char** gridCopy = gridCopyFunc(grid, colSize, rolSize); queue<vector<int>> q;//队列保存下标向量 int cur = 0;//下标计数 int c, r;//下标 int cnt = 0;//陆地计数 int queueSize; vector<int> pos; pos.push_back(c); pos.push_back(r); while (cur < total) { //未访问过的压入队列 c = cur / rolSize; r = cur % rolSize; cur++; //获取下标 if (visited[c][r] == '1') { continue;//访问过跳过 } visited[c][r] = '1';//根节点标记为访问过 if (gridCopy[c][r] == '0') { continue;//跳过陆地 } pos[0] = c; pos[1] = r;//保存陆地下标 q.push(pos);//压入根节点 while (!q.empty()) { queueSize = q.size(); while (queueSize) { pos = q.front();//读取头节点 c = pos[0]; r = pos[1]; if (c > 0 && visited[c - 1][r] == '0') {//上方节点 visited[c - 1][r] = '1'; if (gridCopy[c - 1][r] == '1') { pos[0] = c - 1; pos[1] = r; q.push(pos); } } if (r < rolSize - 1 && visited[c][r + 1] == '0') {//右方节点 visited[c][r + 1] = '1'; if (gridCopy[c][r + 1] == '1') { pos[0] = c; pos[1] = r + 1; q.push(pos); } } if (c < colSize - 1 && visited[c + 1][r] == '0') {//下方节点 visited[c + 1][r] = '1'; if (gridCopy[c + 1][r] == '1') { pos[0] = c + 1; pos[1] = r; q.push(pos); } } if (r > 0 && visited[c][r - 1] == '0') {//左方节点 visited[c][r - 1] = '1'; if (gridCopy[c][r - 1] == '1') { pos[0] = c; pos[1] = r - 1; q.push(pos); } } q.pop();//弹出头节点 queueSize--; } } cnt++; } visitedDelete(visited, colSize); visitedDelete(gridCopy, colSize); return cnt; } char** visitedGen(int colSize, int rolSize) {//生成访问标记矩阵 char** visited = new char* [colSize]; for (int i = 0; i < colSize; i++) { visited[i] = new char[rolSize]; } for (int i = 0; i < colSize; i++) { for (int j = 0; j < rolSize; j++) { visited[i][j] = '0';//标记为为访问 } } return visited; } void visitedDelete(char** visited, int colSize) {//删除标记矩阵 for (int i = 0; i < colSize; i++) { delete[] visited[i]; } delete[] visited; return; } char** gridCopyFunc(vector<vector<char>>& grid, int colSize, int rolSize) { char** visited = visitedGen(colSize, rolSize); for (int i = 0; i < colSize; i++) { for (int j = 0; j < rolSize; j++) { visited[i][j] = grid[i][j]; } } return visited; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// int openLock(vector<string>& deadends, string target) { int deadEndCnt = deadends.size(); int totalCnt = 0; int cur; int inVisit = 0; int tmpNum; queue<string> q; string current = "0000"; string tmp = "0000"; unordered_set<string> vist; vist.insert(deadends.begin(), deadends.end()); q.push(current);//压入根节点 vist.emplace(current); while (!q.empty()) {//队列里还有元素 int queueLen = q.size(); while (queueLen) {//出队列入队列 current = q.front(); if (vist.count(current)) { return -1;//不该出现的出现了 } if (current == target) { return totalCnt;//找到目标 } //要修改,分为两个方向,现在会数量几何增长 for (cur = 0; cur < 4; cur++) { tmp = current; tmpNum = current[cur] - '0'; tmpNum = tmpNum < 9 ? (tmpNum + 1) : 0; tmp[cur] = (tmpNum + '0'); if (!vist.count(tmp)) { q.push(tmp); vist.emplace(tmp); } tmp = current; tmpNum = current[cur] - '0'; tmpNum = tmpNum > 0 ? (tmpNum - 1) : 9; tmp[cur] = (tmpNum + '0'); if (!vist.count(tmp)) { q.push(tmp); vist.emplace(tmp); } } q.pop(); queueLen--; } totalCnt++; } return -1; } bool inDeadend(vector<string>& deadends, string current) { int deadEndCnt = deadends.size(); for (int i = 0; i < deadEndCnt; i++) { if (current == deadends[i]) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// int numSquares(int n) { queue<int> q; unordered_set<int> calculated; q.push(n); calculated.emplace(n); int qLen = 0; int current = 0; int res = 0; int max = 0; int tmp; while (!q.empty()) { qLen = q.size(); while (qLen) {//出队列入队列 current = q.front(); if (current == 0) { return res; } max = int(sqrt(current)); while (max >= 0) { tmp = current - max * max; if (!calculated.count(tmp)) { q.push(tmp); calculated.emplace(tmp); } max--; } q.pop(); qLen--; } res++; } return -1; } }; void inptGen(vector<vector<char>>& inpt) { vector<char> tmp; //string s = "11000 11000 00100 00011 "; //string s = "11110 11010 11000 00000 "; string s = "8888"; int sLen = s.size(); int cur = 0; while (cur < sLen) { if (s[cur] == ' ') { inpt.push_back(tmp); tmp.clear(); } else { tmp.push_back(s[cur]); } cur++; } return; } void deadEndGen(vector<string>& inpt) { string s = "0201 0101 0102 1212 2002 "; //string s = "8887 8889 8878 8898 8788 8988 7888 9888 "; int sLen = s.size(); int cur = 0; string tmp; while (cur < sLen) { if (s[cur] == ' ') { inpt.push_back(tmp); tmp.clear(); } else { tmp.push_back(s[cur]); } cur++; } return; } int main(int argc, char* argv[]) { /*MyCircularQueue* obj = new MyCircularQueue(6); obj->enQueue(6); obj->deQueue(); obj->enQueue(5);*/ Solution mySolution; //vector<vector<char>> inpt; vector<string> inpt; //inptGen(inpt); //mySolution.numIslands(inpt); deadEndGen(inpt); string target = "0009"; //mySolution.openLock(inpt, target); mySolution.numSquares(8935); return 0; } #endif //栈 #if 0 class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int colSize = matrix.size(); if (!colSize) {//无元素则返回 return matrix; } int rolSize = matrix[0].size(); //可释放变量 char** visited = visitedGen(colSize, rolSize);//访问标记 queue<pair<int, int>>* q = new queue<pair<int, int>>;//下标队列 //将所有零纳入到当问过数组中 int c, r; for (c = 0; c < colSize; c++) { for (r = 0; r < rolSize; r++) { if (matrix[c][r] == 0) { q->emplace(c, r); visited[c][r] = '1'; } } } //DFS int tmpC, tmpR; int dirs[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; while (!q->empty()) { c = q->front().first; r = q->front().second; for (int i = 0; i < 4; i++) { tmpC = c + dirs[i][0]; tmpR = r + dirs[i][1]; if (tmpC >= 0 && tmpC < colSize && tmpR >= 0 && tmpR < rolSize && visited[tmpC][tmpR] == '0') { matrix[tmpC][tmpR] = matrix[c][r] + 1; q->emplace(tmpC, tmpR); visited[tmpC][tmpR] = '1'; } } q->pop(); } //后处理,释放 visitedDelete(visited, colSize); delete q; return matrix; } char** visitedGen(int colSize, int rolSize) {//生成访问标记矩阵 char** visited = new char* [colSize]; for (int i = 0; i < colSize; i++) { visited[i] = new char[rolSize]; } for (int i = 0; i < colSize; i++) { for (int j = 0; j < rolSize; j++) { visited[i][j] = '0';//标记为为访问 } } return visited; } void visitedDelete(char** visited, int colSize) {//删除标记矩阵 for (int i = 0; i < colSize; i++) { delete[] visited[i]; } delete[] visited; return; } }; void inptGen(vector<vector<int>>& inpt) { vector<int> tmp; //string s = "11000 11000 00100 00011 "; //string s = "11110 11010 11000 00000 "; //string s = "000 010 000 "; string s = "01011 11001 00010 10111 10001 "; //string s = "000 010 111 "; //string s = "8888"; int sLen = s.size(); int cur = 0; while (cur < sLen) { if (s[cur] == ' ') { inpt.push_back(tmp); tmp.clear(); } else { tmp.push_back(s[cur] - '0'); } cur++; } return; } int main(int argc, char* argv[]) { Solution mySolution; vector<vector<int>> inpt; inptGen(inpt); mySolution.updateMatrix(inpt); return 0; } #endif //二叉树 #if 0 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string res; queue<TreeNode*> que; que.push(root); while (!que.empty()) { int siz = que.size(); while (siz--) { TreeNode* cur = que.front(); que.pop(); if (cur == nullptr) { res += "null,"; } else { string str_val = to_string(cur->val) + ","; res += str_val; que.push(cur->left); que.push(cur->right); } } } return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { queue<int>* valStack = pushStrVal(data); if (!valStack->size()) { return nullptr; } TreeNode* currentNode; int currentVal = valStack->front(); if (currentVal == -888) { return nullptr; } valStack->pop(); TreeNode* root = new TreeNode(currentVal); queue<TreeNode*> q; q.push(root); while (!q.empty()) { int qLen = q.size(); while (qLen) { currentNode = q.front(); q.pop(); qLen--; if (currentNode == nullptr) { continue; } currentVal = -888; if (!valStack->empty()) { currentVal = valStack->front(); valStack->pop(); } if (currentVal != -888) { currentNode->left = new TreeNode(currentVal); } q.push(currentNode->left); currentVal = -888; if (!valStack->empty()) { currentVal = valStack->front(); valStack->pop(); } if (currentVal != -888) { currentNode->right = new TreeNode(currentVal); } q.push(currentNode->right); } } return root; } queue<int>* pushStrVal(string& data) { queue<int>* valStack = new queue<int>; int dataLen = data.size(); int cur = 0; int tmpVal; int sign; while (cur < dataLen) { if (data[cur] == '[') { cur++; continue; } if (data[cur] == ']') { cur++; continue; } if (data[cur] == ',') { cur++; continue; } if (data[cur] == 'n') { valStack->push(-888); cur += 4; continue; } sign = 1; tmpVal = 0; while (data[cur] != ',' && data[cur] != ']') { if (data[cur] == '-') { sign = -1; cur++; continue; } tmpVal = tmpVal * 10 + data[cur] - '0'; cur++; } tmpVal *= sign; valStack->push(tmpVal); } return valStack; } }; // Your Codec object will be instantiated and called as such: // Codec ser, deser; // TreeNode* ans = deser.deserialize(ser.serialize(root)); // Your Codec object will be instantiated and called as such: // Codec ser, deser; // TreeNode* ans = deser.deserialize(ser.serialize(root)); int main(int argc, char* argv[]) { Codec myCodec; string str = "[4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2]"; TreeNode* root = myCodec.deserialize(str); string res = myCodec.serialize(root); return 0; } #endif //二叉搜索树 #if 0 class KthLargest { public: KthLargest(int k, vector<int>& nums) { target = k; int numsLen = nums.size(); int cur; for (cur = 0; cur < numsLen; cur++) { root = addToTree(root, nums[cur]); } return; } int add(int val) { root = addToTree(root, val); return getThLarge(); } private: struct treeNode { int val = 0; int cnt = 0; treeNode* left = nullptr; treeNode* right = nullptr; }; int target = 0; treeNode* root = nullptr; treeNode* addToTree(treeNode* root, int val) {//递归二叉搜索树向添加 if (root == nullptr) { treeNode* ans = new treeNode; ans->val = val; ans->cnt += 1; return ans; } int nodeVal = root->val; root->cnt += 1; if (val < nodeVal) { root->left = addToTree(root->left, val); } if (val > nodeVal) { root->right = addToTree(root->right, val); } return root; } int getThLarge() {//返回第几大的元素 treeNode* cur = root; int k = target; int lCnt, rCnt, curCnt; while (1) { rCnt = (cur->right != nullptr) ? cur->right->cnt : 0; lCnt = (cur->left != nullptr) ? cur->left->cnt : 0; curCnt = cur->cnt - lCnt - rCnt; if (k > rCnt + curCnt) { k = k - curCnt - rCnt; cur = cur->left; } else if (k <= rCnt) { cur = cur->right; } else { return cur->val; } } return -1; } }; /** * Your KthLargest object will be instantiated and called as such: * KthLargest* obj = new KthLargest(k, nums); * int param_1 = obj->add(val); */ int main(int argc, char* argv[]) { int val = 2; vector<int> nums = { 0 }; KthLargest kthLargest(val, nums); kthLargest.add(-1); kthLargest.add(1); kthLargest.add(-2); kthLargest.add(-4); kthLargest.add(3); return 0; } #endif //前缀树Trie #if false class Trie { public: /** Initialize your data structure here. */ Trie() { rootNode = new node; } /** Inserts a word into the trie. */ void insert(string word) { int wordLen = word.size(); node* cur = rootNode; char currentChar; for (int i = 0; i < wordLen; i++) { currentChar = word[i]; if (!cur->children.count(currentChar)) { node* tmp = new node; tmp->val = currentChar; if (i == wordLen - 1) { tmp->isWord = true; } cur->children.emplace(currentChar, tmp); cur = tmp; } else { cur = cur->children.find(currentChar)->second; if (i == wordLen - 1) { cur->isWord = true; } } } return; } /** Returns if the word is in the trie. */ bool search(string word) { node* cur = rootNode; int wordLen = word.size(); for (int i = 0; i < wordLen; i++) { if (!cur->children.count(word[i])) { return false; } cur = cur->children.find(word[i])->second; } return cur->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { node* cur = rootNode; int wordLen = prefix.size(); for (int i = 0; i < wordLen; i++) { if (!cur->children.count(prefix[i])) { return false; } cur = cur->children.find(prefix[i])->second; } return true; } private: struct node { char val; bool isWord = false; unordered_map<char, node*> children; }; node* rootNode; }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */ class Solution { public: string replaceWords(vector<string>& dictionary, string sentence) { rootNode = new node; pushIntoTrie(dictionary); string ans; string inptTmp, ouptTmp; int sentenceLen = sentence.size(); int i, j; i = j = 0; while (i < sentenceLen && j < sentenceLen) { while (j < sentenceLen && sentence[j] != ' ') { j++; } inptTmp = sentence.substr(i, j - i); ouptTmp = longToShort(inptTmp); if (!ouptTmp.size()) { ans = ans + inptTmp; } else { ans = ans + ouptTmp; } ans.push_back(' '); j++; i = j; } ans.pop_back(); return ans; } private: struct node { char val; bool isEnd = false; node* next[26] = { nullptr }; }; node* rootNode; void pushIntoTrie(vector<string>& dictionary) {//添加到前缀树 string tmpStr; int dictLen = dictionary.size(); int i, j, tmpStrLen; node* cur, * tmpNode; char currentChar; for (j = 0; j < dictLen; j++) { cur = rootNode; tmpStr = dictionary[j]; tmpStrLen = tmpStr.size(); for (i = 0; i < tmpStrLen; i++) { currentChar = tmpStr[i]; if (!cur->next[currentChar - 'a']) { tmpNode = new node; tmpNode->val = currentChar; if (i == tmpStrLen - 1) { tmpNode->isEnd = true; } cur->next[currentChar - 'a'] = tmpNode; cur = tmpNode; } else { cur = cur->next[currentChar - 'a']; if (i == tmpStrLen - 1) { cur->isEnd = true; } } } } return; } string longToShort(string& str) { string ans; int strLen = str.size(); node* cur = rootNode; char currentChar; int i; for (i = 0; i < strLen; i++) { currentChar = str[i]; if (!cur->next[currentChar - 'a']) { string nullstr; return nullstr; } cur = cur->next[currentChar - 'a']; ans = ans + cur->val; if (cur->isEnd) { break; } } return ans; } }; class WordDictionary { public: /** Initialize your data structure here. */ WordDictionary() { rootNode = new node; } /** Adds a word into the data structure. */ void addWord(string word) { int wordLen = word.size(); node* cur = rootNode; node* tmp; char currentChar; for (int i = 0; i < wordLen; i++) { currentChar = word[i]; if (!cur->next[currentChar - 'a']) { tmp = new node; tmp->val = word[i]; if (i == wordLen - 1) { tmp->isEnd = true; } cur->next[currentChar - 'a'] = tmp; cur = tmp; } else { cur = cur->next[currentChar - 'a']; if (i == wordLen - 1) { cur->isEnd = true; } } } return; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ bool search(string word) { bool status = findSub(rootNode, word); return status; } private: struct node { char val; bool isEnd = false; node* next[26] = { nullptr }; }; node* rootNode; bool findSub(node* root, string& str) { int strLen = str.size(); if (strLen == 0) { if (root->isEnd) { return true; } else { return false; } } char currentChar = str[0]; string nextStr = str.substr(1); if (currentChar == '.') { bool status = false; for (int i = 0; i < 26; i++) { if (root->next[i]) { status = status || findSub(root->next[i], nextStr); } } return status; } else if (root->next[currentChar - 'a']) { return findSub(root->next[currentChar - 'a'], nextStr); } else { return false; } return false; } }; /** * Your WordDictionary object will be instantiated and called as such: * WordDictionary* obj = new WordDictionary(); * obj->addWord(word); * bool param_2 = obj->search(word); */ int main(int argc, char* argv[]) { //Solution mySolution; //string inpt = "the cattle was rattled by the battery"; //vector<string> dict = { "cat","bat","rat" }; //mySolution.replaceWords(dict, inpt); WordDictionary myWordDictionary; myWordDictionary.addWord("bad"); myWordDictionary.addWord("dad"); myWordDictionary.addWord("mad"); myWordDictionary.search(".ad"); return 0; } #endif #if false class Solution { public: Solution() { rootNode = new node; return; } int findMaximumXOR(vector<int>& nums) { int numsLen = nums.size(); for (int i = 0; i < numsLen; i++) { pushIntoBinaryTree(nums[i]); } node* cur, * curL, * curR; cur = rootNode; while (!cur->left || !cur->right) { if (cur->left) { cur = cur->left; } else if (cur->right) { cur = cur->right; } else { return 0; } }//修剪主干,直到第一个分岔 curL = cur->left; curR = cur->right; unsigned int ans = 1; searchMax(curL, curR, ans); return ans; } private: struct node { node* left = nullptr;//0 node* right = nullptr;//1 }; node* rootNode; void pushIntoBinaryTree(unsigned int num) { node* cur = rootNode; for (int i = 0; i < 32; i++) { int tmp = num & 0x80000000; num = num << 1; if (tmp == 0) { if (!cur->left) { cur->left = new node; } cur = cur->left; } else { if (!cur->right) { cur->right = new node; } cur = cur->right; } } return; } void searchMax(node* curL, node* curR, unsigned int& ans) { if (!curL->left && !curL->right && !curR->left && !curR->right) { return; } int r1 = 0, r2 = 0, r3 = 0; int tmp = ans; //异或右侧添加1 if (curL->left && curR->right) {//01 ans = ans << 1; ans++; searchMax(curL->left, curR->right, ans); r1 = ans; ans = tmp; } if (curL->right && curR->left) {//10 ans = ans << 1; ans++; searchMax(curL->right, curR->left, ans); r2 = ans; ans = tmp; } //否则添加0 if (!((curL->left && curR->right) || (curL->right && curR->left))) {//00 if (curL->left && curR->left) { ans = ans << 1; searchMax(curL->left, curR->left, ans); r3 = ans; ans = tmp; } if (curL->right && curR->right) {//11 ans = ans << 1; searchMax(curL->right, curR->right, ans); } } if (r1 > ans) { ans = r1; } if (r2 > ans) { ans = r2; } if (r3 > ans) { ans = r3; } return; } }; int main(int argc, char* argv[]) { vector<int> nums = { 3, 10, 5, 25, 2, 8 }; //vector<int> nums = { 2, 4 }; Solution mySolution; int res = mySolution.findMaximumXOR(nums); return 0; } #endif #if false class Solution { public: Solution() { rootNode = new node; return; } vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { int wordsNum = words.size(); colSize = board.size(); rolSize = colSize ? board[0].size() : 0; if (colSize == 0 || rolSize == 0) { return ans; } for (int i = 0; i < wordsNum; i++) { pushIntoTrie(words[i]); } for (int i = 0; i < colSize; i++) { for (int j = 0; j < rolSize; j++) { dfs(board, rootNode, i, j); } } return ans; } private: struct node { string word; bool isWord = false; node* next[26] = { nullptr }; }; node* rootNode; int colSize = 0; int rolSize = 0; vector<string> ans; void pushIntoTrie(string& str) { int strLen = str.size(); node* cur = rootNode; int nextCur; for (int i = 0; i < strLen; i++) { nextCur = str[i] - 'a'; if (!cur->next[nextCur]) { cur->next[nextCur] = new node; } cur = cur->next[nextCur]; } cur->isWord = true; cur->word = str; return; } void dfs(vector<vector<char>>& board, node* root, int c, int r) { char currentChar = board[c][r]; if (currentChar == '-' || root->next[currentChar - 'a'] == nullptr) {//访问过或者不存在子节点 return; } root = root->next[currentChar - 'a']; if (root->isWord) { ans.push_back(root->word); root->isWord = false; } board[c][r] = '-';//同一个单词内不能重复使用 if (c > 0) { dfs(board, root, c - 1, r); } if (r > 0) { dfs(board, root, c, r - 1); } if (c + 1 < colSize) { dfs(board, root, c + 1, r); } if (r + 1 < rolSize) { dfs(board, root, c, r + 1); } board[c][r] = currentChar; return; } }; int main(int argc, char* argv[]) { Solution mySolution; string str1 = "cock"; string str2 = "cocks"; //mySolution.pushIntoTrie(str1); //mySolution.pushIntoTrie(str2); return 0; } #endif #if false class Solution { public: vector<vector<int>> palindromePairs(vector<string>& words) { int wordsNum = words.size(); int i, j; vector<vector<int>> res; vector<int> tmp = { 0, 0 }; for (i = 0; i < wordsNum; i++) { for (j = 0; j < wordsNum; j++) { if (i == j) { continue; } bool push = false; int iLen = words[i].size(); int jLen = words[j].size(); if (iLen == jLen) { int iCur = 0; int jCur = jLen - 1; while (iCur < iLen) { if (words[i][iCur] != words[j][jCur]) { break; } iCur++; jCur--; } if (iCur == iLen) { push = true; } } else if (iLen > jLen) { int iCur = 0; int jCur = jLen - 1; while (jCur >= 0) { if (words[i][iCur] != words[j][jCur]) { break; } iCur++; jCur--; } if (jCur < 0) { jCur = iLen - 1; while (iCur < jCur) { if (words[i][iCur] != words[i][jCur]) { break; } iCur++; jCur--; } if (iCur >= jCur) { push = true; } } } else { int iCur = 0; int jCur = jLen - 1; while (iCur < iLen) { if (words[i][iCur] != words[j][jCur]) { break; } iCur++; jCur--; } if (iCur == iLen) { iCur = 0; while (iCur < jCur) { if (words[j][jCur] != words[j][iCur]) { break; } iCur++; jCur--; } if (jCur <= iCur) { push = true; } } } if (push) { tmp[0] = i; tmp[1] = j; res.emplace_back(tmp); } } } return res; } }; int main(int argc, char* argv[]) { vector<string> inpt = { "a","b","c","ab","ac","aa" }; Solution mySolution; mySolution.palindromePairs(inpt); return 0; } #endif //hash 哈希表 #if false class MyHashSet { public: struct node { node* left = 0; node* right = 0; int val = 0; bool isDeleted = false; }; /** Initialize your data structure here. */ MyHashSet() { rootNode = nullptr; } void add(int key) { rootNode = addToTree(rootNode, key); } void remove(int key) { deleteElement(rootNode, key); } /** Returns true if this set contains the specified element */ bool contains(int key) { return quary(rootNode, key); } private: node* rootNode; node* addToTree(node* currentNode, int val) { if (currentNode == nullptr) { currentNode = new node; currentNode->val = val; return currentNode; } int nodeVal = currentNode->val; if (val < nodeVal) { currentNode->left = addToTree(currentNode->left, val); } if (val > nodeVal) { currentNode->right = addToTree(currentNode->right, val); } if (val == nodeVal) { currentNode->isDeleted = false; } return currentNode; } bool quary(node* currentNode, int val) { if (currentNode == nullptr) { return false; } if (currentNode->val == val) { if (currentNode->isDeleted) { return false; } else { return true; } } if (val < currentNode->val) { return quary(currentNode->left, val); } else { return quary(currentNode->right, val); } } void deleteElement(node* currentNode, int val) { if (currentNode == nullptr) { return; } if (currentNode->val == val) { currentNode->isDeleted = true; } if (val < currentNode->val) { deleteElement(currentNode->left, val); } else { deleteElement(currentNode->right, val); } } }; class MyHashMap { public: struct node { node* left = 0; node* right = 0; int key = -1; int val = -1; bool isDeleted = false; }; /** Initialize your data structure here. */ MyHashMap() { rootNode = nullptr; } /** value will always be non-negative. */ void put(int key, int value) { rootNode = addToTree(rootNode, key, value); } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ int get(int key) { return getFromTree(rootNode, key); } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ void remove(int key) { removeFromTree(rootNode, key); } private: node* rootNode; node* addToTree(node* currentNode, int key, int val) { if (currentNode == nullptr) { currentNode = new node; currentNode->key = key; currentNode->val = val; return currentNode; } int currentKey = currentNode->key; if (key < currentKey) { currentNode->left = addToTree(currentNode->left, key, val); } else if (key > currentKey) { currentNode->right = addToTree(currentNode->right, key, val); } else { currentNode->val = val; currentNode->isDeleted = false; } return currentNode; } int getFromTree(node* currentNode, int key) { if (currentNode == nullptr) { return -1; } int currentKey = currentNode->key; if (key < currentKey) { return getFromTree(currentNode->left, key); } else if (key > currentKey) { return getFromTree(currentNode->right, key); } else { if (currentNode->isDeleted) { return -1; } else { return currentNode->val; } } } void removeFromTree(node* currentNode, int key) { if (currentNode == nullptr) { return; } int currentKey = currentNode->key; if (key == currentKey) { currentNode->isDeleted = true; } else if (key < currentKey) { removeFromTree(currentNode->left, key); } else { removeFromTree(currentNode->right, key); } return; } }; //class Solution { //重复数 //public: // bool containsDuplicate(vector<int>& nums) { // unordered_set<int> hashSet; // for (auto num : nums) { // if (hashSet.count(num) > 0) { // return true; // } // hashSet.insert(num); // } // return false; // } //}; //class Solution { //单一数 //public: // int singleNumber(vector<int>& nums) { // unordered_set<int> hashSet; // for (auto num : nums) { // if (hashSet.count(num) > 0) { // hashSet.erase(num); // continue; // } // hashSet.emplace(num); // } // return *(hashSet.begin()); // } //}; //class Solution { //快乐数 //public: // bool isHappy(int n) { // string tmp; // unordered_set<string> history; // while (true) { // tmp.clear(); // while (n != 0) { // tmp.push_back(n % 10); // n /= 10; // } // for (auto bit : tmp) { // n += bit * bit; // } // if (n == 1) { // return true; // } // if (history.count(tmp) > 0) { // return false; // } // history.insert(tmp); // } // } //}; //class Solution { //两数之和 //public: // vector<int> twoSum(vector<int>& nums, int target) { // unordered_map<int, int> numsMap; // vector<int> res; // for (int i = 0; i < nums.size(); i++) { // if (numsMap.count(target - nums[i]) > 0) { // res.push_back(i); // res.push_back(numsMap[target - nums[i]]); // return res; // } // numsMap.emplace(make_pair(nums[i], i)); // } // return res; // } //}; //class Solution { //判断字符串结构(abb, cdd) //public: // bool isIsomorphic(string s, string t) { // unordered_map<char, int> str1Map, str2Map; // vector<int> str1Key, str2Key; // for (int i = 0; i < s.size(); i++) { // if (str1Map.count(s[i]) > 0) { // str1Key.emplace_back(str1Map[s[i]]); // } // else { // str1Map.emplace(make_pair(s[i], i)); // str1Key.emplace_back(i); // } // if (str2Map.count(t[i]) > 0) { // str2Key.emplace_back(str2Map[t[i]]); // } // else { // str2Map.emplace(make_pair(t[i], i)); // str2Key.emplace_back(i); // } // } // return str1Key == str2Key; // } //}; //class Solution { //最小索引和 //public: // vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { // vector<string> res; // int lsit1Len = list1.size(); // int lsit2Len = list2.size(); // int total = 32767; // int tmp = 0; // unordered_map<string, int> list1Map, resultMap; // for (int i = 0; i < lsit1Len; i++) { //压入hash图 // list1Map.emplace(make_pair(list1[i], i)); // } // for (int i = 0; i < lsit2Len; i++) { //求最小索引和,并把符合要求的压入hash图 // if (list1Map.count(list2[i]) > 0) { // tmp = list1Map[list2[i]] + i; // total = (tmp < total) ? tmp : total; // resultMap.emplace(make_pair(list2[i], tmp)); // } // } // for (auto resItem : resultMap) { // if (resItem.second == total) { // res.push_back(resItem.first); // } // } // // return res; // } //}; //class Solution { //public: // int firstUniqChar(string s) { // int res = 32768; // int sLen = s.size(); // unordered_map<char, int> content; // for (int i = 0; i < sLen; i++) { // if (content.count(s[i]) < 1) { // content[s[i]] = 1; // continue; // } // content[s[i]] += 1; // } // for (auto contentItem : content) { // res = contentItem.second < res ? contentItem.second : res; // } // if (res != 1) { // return -1; // } // for (int i = 0; i < sLen; i++) { // if (content[s[i]] == 1) { // return i; // } // } // return -1; // } //}; //class Solution { //public: // vector<vector<string>> groupAnagrams(vector<string>& strs) { // vector<vector<string>> res; // vector<string> tmp; // unordered_map<string, vector<string>> strsMap; // string strCopy; // for (auto str : strs) { // strCopy = sortString(str); // if (strsMap.count(strCopy) < 1) { // strsMap[strCopy] = tmp; // } // strsMap[strCopy].emplace_back(str); // } // for (auto it = strsMap.begin(); it != strsMap.end(); it++) { // res.emplace_back((*it).second); // } // return res; // } //private: // string sortString(string s) { // sort(s.begin(), s.end()); // return s; // } //}; //class Solution { //不重复字符字串 //public: // int lengthOfLongestSubstring(string s) { // int sLen = s.size(); // char currentChar; // int setSize; // int maxLen = 0; // unordered_set<char> charSet; // int cur = 0; //字符串开始地方 // for (int i = 0; i < sLen; i++) { // currentChar = s[i]; // if (charSet.count(currentChar) < 1) { // charSet.emplace(currentChar); // continue; // } // setSize = charSet.size(); // maxLen = setSize > maxLen ? setSize : maxLen; // while (cur < sLen && s[cur] != currentChar) { // charSet.erase(s[cur]); // cur++; // } // if (s[cur] == currentChar) { // cur++; // continue; // } // charSet.emplace(currentChar); // } // setSize = charSet.size(); // maxLen = setSize > maxLen ? setSize : maxLen; // return maxLen; // } //}; class Solution {//前k个高频词 public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> numsMap; unordered_map<int, vector<int>> freqMap; int maxFreq = 0; vector<int> res(k); for (auto num : nums) { numsMap[num]++; } for (auto it = numsMap.begin(); it != numsMap.end(); it++) { freqMap[(*it).second].emplace_back((*it).first); maxFreq = (*it).second > maxFreq ? (*it).second : maxFreq; } while (k > 0) { if (freqMap.count(maxFreq)) { int len = freqMap[maxFreq].size() - 1; while (len > -1) { res[k - 1] = freqMap[maxFreq][len]; k--; len--; } } maxFreq--; } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<int> input = { 1, 2 }; mySolution.topKFrequent(input, 2); return 0; } #endif //图解数据结构 #if false //字符串替换 //class Solution { //public: // string replaceSpace(string s) { // int slowCur = 0, fastCur = 0; // int sLen = s.size(); // string res; // while (fastCur < sLen) { // while (fastCur < sLen && s[fastCur] != ' ') { // fastCur++; // } // res += s.substr(slowCur, fastCur - slowCur); // if (s[fastCur] == ' ') { // res += +"%20"; // } // fastCur++; // slowCur = fastCur; // } // return res; // } //}; //有限状态自动机 //class Solution {//判断数字是否合法, 确定有限状态自动机 //public: // bool isNumber(string s) { // int len = s.length(); // State st = STATE_INITIAL; // for (int i = 0; i < len; i++) { // CharType typ = toCharType(s[i]); // if (transfer[st].find(typ) == transfer[st].end()) { // return false; // } // else { // st = transfer[st][typ]; // } // } // return st == STATE_INTEGER || st == STATE_POINT || st == STATE_FRACTION || st == STATE_EXP_NUMBER || st == STATE_END; // } //private: // enum State { // STATE_INITIAL, // STATE_INT_SIGN, // STATE_INTEGER, // STATE_POINT, // STATE_POINT_WITHOUT_INT, // STATE_FRACTION, // STATE_EXP, // STATE_EXP_SIGN, // STATE_EXP_NUMBER, // STATE_END, // }; // // enum CharType { // CHAR_NUMBER, // CHAR_EXP, // CHAR_POINT, // CHAR_SIGN, // CHAR_SPACE, // CHAR_ILLEGAL, // }; // // unordered_map<State, unordered_map<CharType, State>> transfer{ // { // STATE_INITIAL, { // {CHAR_SPACE, STATE_INITIAL}, // {CHAR_NUMBER, STATE_INTEGER}, // {CHAR_POINT, STATE_POINT_WITHOUT_INT}, // {CHAR_SIGN, STATE_INT_SIGN}, // } // }, { // STATE_INT_SIGN, { // {CHAR_NUMBER, STATE_INTEGER}, // {CHAR_POINT, STATE_POINT_WITHOUT_INT}, // } // }, { // STATE_INTEGER, { // {CHAR_NUMBER, STATE_INTEGER}, // {CHAR_EXP, STATE_EXP}, // {CHAR_POINT, STATE_POINT}, // {CHAR_SPACE, STATE_END}, // } // }, { // STATE_POINT, { // {CHAR_NUMBER, STATE_FRACTION}, // {CHAR_EXP, STATE_EXP}, // {CHAR_SPACE, STATE_END}, // } // }, { // STATE_POINT_WITHOUT_INT, { // {CHAR_NUMBER, STATE_FRACTION}, // } // }, { // STATE_FRACTION, // { // {CHAR_NUMBER, STATE_FRACTION}, // {CHAR_EXP, STATE_EXP}, // {CHAR_SPACE, STATE_END}, // } // }, { // STATE_EXP, // { // {CHAR_NUMBER, STATE_EXP_NUMBER}, // {CHAR_SIGN, STATE_EXP_SIGN}, // } // }, { // STATE_EXP_SIGN, { // {CHAR_NUMBER, STATE_EXP_NUMBER}, // } // }, { // STATE_EXP_NUMBER, { // {CHAR_NUMBER, STATE_EXP_NUMBER}, // {CHAR_SPACE, STATE_END}, // } // }, { // STATE_END, { // {CHAR_SPACE, STATE_END}, // } // } // }; // // CharType toCharType(char ch) { // if (ch >= '0' && ch <= '9') { // return CHAR_NUMBER; // } // else if (ch == 'e' || ch == 'E') { // return CHAR_EXP; // } // else if (ch == '.') { // return CHAR_POINT; // } // else if (ch == '+' || ch == '-') { // return CHAR_SIGN; // } // else if (ch == ' ') { // return CHAR_SPACE; // } // else { // return CHAR_ILLEGAL; // } // } //}; class MinStack { public: /** initialize your data structure here. */ MinStack() { return; } void push(int x) { if (x < minVal) { minVal = x; minHist.push(minVal); } data.push(x); return; } void pop() { if (minHist.top() == data.top()) { minHist.pop(); minVal = minHist.top(); } data.pop(); return; } int top() { return data.top(); } int min() { return minVal; } private: stack<int> data, minHist; int minVal = 2147483647; }; class Solution { public: int strToInt(string str) { int strLen = str.size(); int cur = 0; while (str[cur] == ' ') { cur++; } bool neg = false; if (str[cur] == '+') { cur++; } else if (str[cur] == '-') { neg = true; cur++; } while (str[cur] == '0') { cur++; } int lim = cur + 8; long res = 0; while (cur < strLen) { char currentChar = str[cur]; if (currentChar > '9' || currentChar < '0') { break; } currentChar -= '0'; if (cur > lim) { if (res > 214748364) { if (neg) { return -2147483648; } else { return 2147483647; } } else if (res == 214748364) { if (neg && currentChar > 8) { return -2147483648; } if (!neg && currentChar > 7) { return 2147483647; } } } res = res * 10 + currentChar; cur++; } if (neg && res > 0) { res *= -1; } return res; } }; int main(int argc, char* argv[]) { Solution mySoltuion; mySoltuion.strToInt("2147483648"); return 0; } #endif //初级算法 #if false class Solution { public: int removeDuplicates(vector<int>& nums) {//去除重复 int numsLen = nums.size(); if (numsLen < 2) { return numsLen; } sort(nums.begin(), nums.end()); int slowCur = 0, fastCur = 1; while (fastCur < numsLen) { if (nums[slowCur] != nums[fastCur]) { slowCur++; nums[slowCur] = nums[fastCur]; } } return slowCur + 1; } int maxProfit(vector<int>& prices) {//股票交易 size_t priceLen = prices.size(); int res = 0; for (size_t cur = 0; cur < priceLen - 1; cur++) { if (prices[cur + 1] > prices[cur]) { res += prices[cur + 1] - prices[cur]; } } return res; } void rotate(vector<int>& nums, int k) {//旋转数组 size_t numsLen = nums.size(); k = k % numsLen; vector <int> tmp1(nums.end() - k, nums.end()); vector <int> tmp2(nums.begin(), nums.end() - k); tmp1.insert(tmp1.end(), tmp2.begin(), tmp2.end()); nums = tmp1; return; } vector<int> plusOne(vector<int>& digits) { size_t digitLen = digits.size(); int aux = 1; vector<int> res(digits.begin(), digits.end()); for (int i = digitLen - 1; i > -1; i--) { res[i] += aux; aux = 0; if (res[i] > 9) { res[i] %= 10; aux = 1; } } if (aux == 1) { vector<int> tmp = { 1 }; res.insert(res.begin(), tmp.begin(), tmp.end()); } return res; } int reverse(int x) { int res = 0; bool isNeg = false; if (x < 0) { isNeg = true; if (x == -2147483648) { return 0; } x = 0 - x; } int tmp = 0; while (x != 0) { tmp = x % 10; if (res > 214748364) { return 0; } else if (res == 214748364) { if (isNeg) { if (tmp > 7) { return 0; } } else if (tmp > 8) { return 0; } } x /= 10; res = res * 10 + tmp; } if (isNeg) { res = -res; } return res; } bool isPalindrome(string s) { int sLen = s.size(); int frontCur = 0, rearCur = sLen - 1; while (frontCur < rearCur) { char front = s[frontCur], rear = s[rearCur]; if (!isalnum(front)) { frontCur++; continue; } if (!isalnum(rear)) { rearCur--; continue; } front = isupper(front) ? front + 32 : front; rear = isupper(rear) ? rear + 32 : rear; if (front != rear) { return false; } frontCur++; rearCur--; } return true; } int myAtoi(string s) { int sLen = s.size(); int cur = 0; while (cur < sLen && s[cur] == ' ') { cur++; } bool isNeg = false; if (s[cur] == '-') { isNeg = true; cur++; } else if (s[cur] == '+') { cur++; } if (s[cur] > '9' || s[cur] < '0') { return 0; } int res = 0; while (cur < sLen) { char tmp = s[cur]; if (tmp > '9' || tmp < '0') { break; } tmp -= '0'; if (res > 214748364) { if (isNeg) { return -2147483648; } return 2147483647; } if (res == 214748364) { if (isNeg) { if (tmp > 7) { return -2147483648; } } if (!isNeg) { if (tmp > 7) { return 2147483647; } } } res = res * 10 + tmp; cur++; } if (isNeg) { res *= -1; } return res; } int strStr(string haystack, string needle) { int needleLen = needle.size(); if (needleLen == 0) { return 0; } int hayLen = haystack.size(); vector<int>* next = getNext(haystack); int hCur = 0, nCur = 0; while (hCur < hayLen && nCur < needleLen) { if (nCur == -1 || haystack[hCur] == needle[nCur]) { hCur++; nCur++; } else { nCur = (*next)[nCur]; } } if (nCur == needleLen) { return hCur - nCur; } return -1; } vector<int>* getNext(string s) { int sLen = s.size(); vector<int>* next = new vector<int>(sLen); (*next)[0] = -1; int pos = 0, cnt = -1; while (pos < sLen - 1) { if (cnt == -1 || s[pos] == s[cnt]) { cnt++; pos++; (*next)[pos] = cnt; } else { cnt = (*next)[cnt];//回到-1 } } return next; } string countAndSay(int n) { string res = "1"; while (n > 1) { res = describeStr(res); n--; } return res; } string describeStr(string str) { string res; int strLen = str.size(); int slowCur = 0, fastCur = 0; while (fastCur < strLen) { if (str[fastCur] == str[slowCur]) { fastCur++; continue; } res.push_back(fastCur - slowCur + '0'); res.push_back(str[slowCur]); slowCur = fastCur; fastCur++; } res.push_back(fastCur - slowCur + '0'); res.push_back(str[slowCur]); return res; } void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { stack<int> resStack; size_t cur1 = 0, cur2 = 0; int tmp = 0; while (cur1 < m && cur2 < n) { if (nums1[cur1] < nums2[cur2]) { tmp = nums1[cur1]; cur1++; } else { tmp = nums2[cur2]; cur2++; } resStack.push(tmp); } while (cur1 < m) { tmp = nums1[cur1]; resStack.push(tmp); cur1++; } while (cur2 < n) { tmp = nums2[cur2]; resStack.push(tmp); cur2++; } for (int i = n + m - 1; i > -1; i--) { nums1[i] = resStack.top(); resStack.pop(); } return; } }; int main(int argc, char* argv[]) { vector<int> nums1 = { 1 }, nums2; Solution mySolution; mySolution.merge(nums1, 1, nums2, 0); return 0; } #endif //初级算法-动态规划 #if fasle class Solution { public: int climbStairs(int n) {//爬楼梯 if (n < 4) { return n; } int n_2 = 1, n_1 = 2; int current = 3, tmp = 0; for (int i = 3; i < n; i++) { tmp = current + n_1; n_1 = current; n_2 = n_1; current = tmp; } return current; } int maxSubArray(vector<int>& nums) {//返回最大子数组之和 int numsLen = nums.size(); if (numsLen == 0) { return 0; } if (numsLen == 1) { return nums[0]; } int pre = nums[0]; int maxVal = pre; for (size_t i = 1; i < numsLen; i++) { pre = max(pre + nums[i], nums[i]);//前面元素对数列起到负作用 maxVal = pre > maxVal ? pre : maxVal; } return maxVal; } int rob(vector<int>& nums) { //打家劫舍 size_t numsLen = nums.size(); switch (numsLen) { case 0: return 0; case 1: return nums[0]; case 2: return max(nums[0], nums[1]); default: break; } //偷或不偷 int n_1 = nums[1]; int n_2 = nums[0]; int tmp = 0; for (size_t i = 2; i < numsLen; i++) { tmp = n_1 > n_2 ? n_1 : n_2; n_1 = nums[i] + n_2; n_2 = tmp; } return n_1 > n_2 ? n_1 : n_2; } }; int main(int argc, char* argv[]) { vector<int> nums = { 2, 1, 1, 2 }; Solution mySolution; mySolution.rob(nums); return 0; } #endif //初级算法-设计问题 #if false class Solution { public: Solution(vector<int>& nums) { org = new vector<int>(nums); numsLen = nums.size(); return; } /** Resets the array to its original configuration and return it. */ vector<int> reset() { return *org; } /** Returns a random shuffling of the array. */ vector<int> shuffle() { vector<int> res(numsLen, -1); for (size_t i = numsLen; i > 0; i--) { size_t cur = rand() % (numsLen); while (res[cur] != -1) { cur = rand() % (numsLen); } res[cur] = (*org)[i - 1]; } return res; } private: vector<int>* org; size_t numsLen; }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(nums); * vector<int> param_1 = obj->reset(); * vector<int> param_2 = obj->shuffle(); */ int main(int argc, char* argv[]) { vector<int> inpt = { 1, 2, 3 }; Solution mySolution(inpt); mySolution.reset(); mySolution.shuffle(); return 0; } #endif //初级算法-其他 #if false class Solution { public: int countPrimes(int n) { vector<bool> bitMap(n, true); int res = 0; for (size_t i = 2; i < n; i++) { if (bitMap[i]) { res++; for (size_t cur = i + i; cur < n; cur += i) { bitMap[cur] = false; } } } return res; } bool isPowerOfThree(int n) { if (n < 1) { return false; } while (n != 0) { if (n % 3 != 0 && n != 1) { return false; } n /= 3; } return true; } //转罗马数字 //有限状态机解法 //FSM enum type { TYPE_I, TYPE_V, TYPE_X, TYPE_L, TYPE_C, TYPE_D, TYPE_M }; enum state { STA_START = 0, STA_1 = 1, STA_5 = 5, STA_10 = 10, STA_50 = 50, STA_100 = 100, STA_500 = 500, STA_1000 = 1000, STA_4 = 4, STA_9 = 9, STA_40 = 40, STA_90 = 90, STA_400 = 400, STA_900 = 900 }; unordered_map<state, unordered_map<type, state>> transfer = { { STA_START, { {TYPE_I, STA_1}, {TYPE_V, STA_5}, {TYPE_X, STA_10}, {TYPE_L, STA_50}, {TYPE_C, STA_100}, {TYPE_D, STA_500}, {TYPE_M, STA_1000} } }, { STA_1, { {TYPE_V, STA_4}, {TYPE_X, STA_9} } }, { STA_10, { {TYPE_L, STA_40}, {TYPE_C, STA_90} } }, { STA_100, { {TYPE_D, STA_400}, {TYPE_M, STA_900} } } }; unordered_map<char, type> getType = { {'I', TYPE_I}, {'V', TYPE_V}, {'X', TYPE_X}, {'L', TYPE_L}, {'C', TYPE_C}, {'D', TYPE_D}, {'M', TYPE_M} }; int romanToInt(string s) { int numsLen = s.size(); int res = 0, tmp = 0; state currentState = STA_START; type currentType; for (int i = 0; i < numsLen; i++) { currentType = getType[s[i]]; if (transfer[currentState][currentType] < 1) { currentState = STA_START; res += tmp; tmp = 0; } currentState = transfer[currentState][currentType]; tmp = currentState; } res += tmp; return res; } bool isValid(string s) { int sLen = s.size(); stack<char> columStack; for (int i = 0; i < sLen; i++) { char tmp = s[i]; if (tmp == '{' || tmp == '[' || tmp == '(') { columStack.push(tmp); continue; } if (tmp == '}' || tmp == ']' || tmp == ')') { if (columStack.empty()) { return false; } char stackTopDiff = tmp - columStack.top(); if (stackTopDiff == 1 || stackTopDiff == 2) { columStack.pop(); continue; } return false; } } if (!columStack.empty()) { return false; } return true; } }; int main(int argc, char* argv[]) { Solution mySolution; mySolution.isValid("()"); return 0; } #endif //数组类算法 #if false class Solution { public: int removeDuplicates(vector<int>& nums) {//去除重复项2 size_t numsLen = nums.size(), slowCur = 0, fastCur = 1; if (numsLen < 2) { return numsLen; } while (fastCur < numsLen) { if (nums[slowCur] == nums[fastCur]) { if (slowCur > 0 && nums[slowCur - 1] == nums[fastCur]) { fastCur++; continue; } } slowCur++; nums[slowCur] = nums[fastCur]; fastCur++; } return slowCur + 1; } void quickSort(vector<int>& inptArray, size_t left, size_t right) {//递归快速排列 if (left < right) { size_t mid = partition(inptArray, left, right); if (mid > 1) { quickSort(inptArray, left, mid - 1); } quickSort(inptArray, mid + 1, right); } return; } size_t partition(vector<int>& inptArray, size_t left, size_t right) { int pivot = inptArray[left]; size_t i = left + 1, j = right; while (i < j) { if (inptArray[i] <= pivot) {//找左面第一个大于锚点的坐标 i++; continue; } if (inptArray[j] >= pivot) {//找右面第一个小于锚点的坐标 j--; continue; } //交换 int tmp = inptArray[i]; inptArray[i] = inptArray[j]; inptArray[j] = tmp; } j--; inptArray[left] = inptArray[j]; inptArray[j] = pivot; return j; } int maxArea(vector<int>& height) {//最大容量 size_t heightLen = height.size(), frontCur = 0, rearCur = heightLen - 1; int res = 0, tmpArea; while (frontCur < rearCur) { tmpArea = (rearCur - frontCur) * min(height[frontCur], height[rearCur]); res = tmpArea > res ? tmpArea : res; if (height[frontCur] < height[rearCur]) { frontCur++; } else { rearCur--; } } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<int> inpt = { 1,8,6,2,5,4,8,3,7 }; vector<int> inptSort = { 8, 4, 6, 3, 5, 234, 456, 3, 45, 645, 75, 678, 857 }; //mySolution.quickSort(inptSort, 0, inptSort.size() - 1); //mySolution.removeDuplicates(inpt); //priority_queue<int> inptHeap; mySolution.maxArea(inpt); return 0; } #endif //查找表类算法 #if false class Solution { public: string frequencySort(string s) {//根据字符出现频率排序 string res; int sLen = s.size(); unordered_map<char, int> freqCnt; unordered_map<int, vector<char>> freqMap; priority_queue<int> freqHeap; vector<char> tmp; for (int i = 0; i < sLen; i++) { freqCnt[s[i]]++; } for (auto it = freqCnt.begin(); it != freqCnt.end(); it++) { if (freqMap.count(it->second) < 1) { freqMap.emplace(make_pair(it->second, tmp)); } freqMap[it->second].emplace_back(it->first); freqHeap.push(it->second); } while (!freqHeap.empty()) { int cnt = freqHeap.top(); char toAdd = freqMap[cnt].back(); freqMap[cnt].pop_back(); freqHeap.pop(); while (cnt) { res.push_back(toAdd); cnt--; } } return res; } vector<vector<int>> threeSum(vector<int>& nums) { size_t numsLen = nums.size(); vector<vector<int>> res; vector<int> tmp(3); sort(nums.begin(), nums.end()); for (size_t i = 0; i < numsLen; i++) { if (i > 0 && nums[i] == nums[i - 1]) {//排序过后,所以能确保枚举不同 continue; } size_t k = numsLen - 1; for (size_t j = i + 1; j < numsLen; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } while (k > j && nums[i] + nums[j] + nums[k] > 0) { k--; } if (j == k) { break; } if (nums[i] + nums[j] + nums[k] == 0) { tmp[0] = nums[i]; tmp[1] = nums[j]; tmp[2] = nums[k]; res.emplace_back(tmp); } } } return res; } vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> res; size_t numsLen = nums.size(); if (numsLen < 4) { return res; } sort(nums.begin(), nums.end()); int sum; for (size_t i = 0; i < numsLen - 3; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } //适当的剪枝操作使得运行事件从~120ms降到~16ms if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {//剪枝 break; } if (nums[i] + nums[numsLen - 1] + nums[numsLen - 2] + nums[numsLen - 3] < target) {//剪枝 continue; } for (size_t j = i + 1; j < numsLen - 2; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {//剪枝 break; } if (nums[i] + nums[j] + nums[numsLen - 1] + nums[numsLen - 2] < target) {//剪枝 continue; } size_t l = numsLen - 1; size_t k = j + 1; while (k < l) { if (l < numsLen - 1 && nums[l] == nums[l + 1]) { l--; continue; } if (k > j + 1 && nums[k] == nums[k - 1]) { k++; continue; } sum = nums[i] + nums[j] + nums[k] + nums[l]; if (sum > target) { l--; continue; } if (sum < target) { k++; continue; } res.push_back({ nums[i], nums[j], nums[k], nums[l] }); l--; } } } return res; } int numberOfBoomerangs(vector<vector<int>>& points) { size_t pointLen = points.size(); unordered_map<int, int> dist; int res = 0; vector<vector<int>> distMap(pointLen, vector<int>(pointLen)); for (size_t i = 0; i < pointLen; i++) { dist.clear(); for (size_t j = 0; j < pointLen; j++) { if (j == i) { continue; } if (j > i) { int distance = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]); distMap[i][j] = distance; distMap[j][i] = distMap[i][j]; } dist[distMap[i][j]]++; } for (auto it = dist.begin(); it != dist.end(); it++) { int cnt = (*it).second; res += cnt * (cnt - 1); } } return res; } int maxPoints(vector<vector<int>>& points) {//最多点在线上 size_t pointLen = points.size(); int res = 0; if (pointLen < 3) { return pointLen; } unordered_map<string, unordered_set<int>> lineMap; for (size_t i = 0; i < pointLen; i++) { for (size_t j = i + 1; j < pointLen; j++) { string* cur = getID(points[i], points[j]); lineMap[*cur].emplace(i); lineMap[*cur].emplace(j); } } for (auto it = lineMap.begin(); it != lineMap.end(); it++) { res = (*it).second.size() > res ? (*it).second.size() : res; } return res; } inline string* getID(vector<int>& p1, vector<int>& p2) {//求线ID double_t k = 0, b; string* res = new string; int x1 = p1[0], x2 = p2[0], y1 = p1[1], y2 = p2[1], dy = y2 - y1, dx = x2 - x1; if (dx < 0) { dx = -dx; dy = -dy; } int tmp = gcd(dx, dy); if (tmp != 0) { dx /= tmp; dy /= tmp; } if (dx == 0) { b = x1; } else { b = y1 - 1.0 * dy / dx * x1; } *res = to_string(dy) + '/' + to_string(dx) + '@' + to_string(b); return res; } inline int gcd(int a, int b) {//辗转相除求最大公约数 if (b == 0) { return a; } return gcd(b, a % b); } }; vector<vector<int>> strToMatrix(string s) { int sLen = s.size(); vector<int> tmp; vector<vector<int>> res; for (int i = 0; i < sLen; i++) { if (s[i] == '[' || s[i] == ']' || s[i] == ',') { continue; } tmp.emplace_back(s[i] - '0'); if (tmp.size() == 2) { res.emplace_back(tmp); tmp.clear(); } } return res; } int main(int argc, char* argv[]) { Solution mySolution; vector<int> inpt = { 1, 3 }; //vector<vector<int>> inptBoom = { {0,0},{1,0},{-1,0}, {0, 1}, {0, -1} }; //mySolution.frequencySort("tree"); //mySolution.numberOfBoomerangs(inptBoom); //mySolution.mySqrt(46339); //vector<vector<int>> linePoint = { {0,0 }, {1, 1},{1, -1} }; //mySolution.maxPoints(linePoint); //vector<int> p1 = { 1,1 }; //vector<int> p2 = { 1,2 }; //mySolution.getKB(p1, p2); return 0; } #endif //二分法 #if false class Solution { public: //int search(vector<int>& nums, int target) {//二分查找 // int frontCur = 0, rearCur = nums.size() - 1, currentCur = (frontCur + rearCur) / 2; // while (frontCur <= rearCur) { // currentCur = (frontCur + rearCur) / 2; // if (nums[currentCur] > target) { // rearCur = currentCur - 1; // continue; // } // if (nums[currentCur] < target) { // frontCur = currentCur + 1; // continue; // } // return currentCur; // } // if (nums[currentCur] == target) { // return currentCur; // } // return -1; //} int mySqrt(int x) {//二分查平方根 int left = 0, right = x < 46339 ? x : 46339, current = 0; while (left <= right) { current = left + (right - left) / 2; int tmp = current * current; if (tmp == x) { break; } else if (tmp > x) { right = current - 1; } else { left = current + 1; } } if (current * current > x) { return current - 1; } return current; } int search(vector<int>& nums, int target) { size_t numsLen = nums.size(), i; int left, right, mid = 0; for (i = 1; i < numsLen; i++) { if (nums[i] < nums[i - 1]) { break; } } if (i != numsLen) { if (nums[numsLen - 1] < target) { left = 0; right = i - 1; } else { left = i; right = numsLen - 1; } } else { left = 0; right = numsLen - 1; } while (left <= right) { mid = left + (right - left) / 2; if (nums[mid] < target) { left = mid + 1; } else if (nums[mid] > target) { right = mid - 1; } else { return mid; } } if (nums[mid] == target) { return mid; } return -1; } vector<int> searchRange(vector<int>& nums, int target) {//右点难,注意结束条件 int left = 0, right = nums.size() - 1, mid; vector<int> res(2, -1); if (right == -1) { return res; } if (nums[0] == target) { res[0] = 0; } if (nums[right] == target) { res[1] = right; } if (res[0] == -1) { while (left < right) { mid = left + (right - left) / 2; if (nums[mid] >= target) { right = mid; } else { left = mid + 1; } } if (nums[left] == target) { res[0] = left; } } if (res[0] == -1) { return res; } if (res[1] == -1) { left = res[0]; right = nums.size() - 1; while (left < right) { mid = left + (right - left) / 2; if (nums[mid] > target) { right = mid; } else { left = mid + 1; } } res[1] = left - 1; } return res; } vector<int> findClosestElements(vector<int>& arr, int k, int x) { //https://leetcode-cn.com/problems/find-k-closest-elements/solution/658-zhao-dao-k-ge-zui-jie-jin-de-yuan-su-cer-fen-s/ size_t left = 0, right = arr.size() - k, mid; //mid是数组起点 while (left < right) { mid = left + (right - left) / 2; if (x - arr[mid] > arr[mid + k] - x) { //增序数组,两边界差相差不大 left = mid + 1; } else { right = mid; } } return vector<int>(arr.begin() + left, arr.begin() + left + k); } int findPeakElement(vector<int>& nums) {//求极大值 size_t numsLen = nums.size(); if (numsLen == 1 || nums[0] > nums[1]) { return 0; } if (nums[numsLen - 1] > nums[numsLen - 2]) { return numsLen - 1; } size_t left = 0, right = numsLen - 1, mid; while (left < right) { mid = left + (right - left) / 2; if (nums[mid] < nums[mid + 1]) { left = mid + 1; } else { right = mid; } } if (nums[mid] < nums[mid + 1]) { return mid + 1; } return mid; } int getKthLarg(vector<int>& nums1, vector<int>& nums2, int k) {//双数组求第几大 int cur1 = 0, cur2 = 0, nums1Len = nums1.size(), nums2Len = nums2.size(); while (true) { //退出机制 if (cur1 == nums1Len) { return nums2[cur2 + k - 1]; } if (cur2 == nums2Len) { return nums1[cur1 + k - 1]; } if (k == 1) { return min(nums1[cur1], nums2[cur2]); } //防止访问越界 int cur1Tmp = min(cur1 + k / 2 - 1, nums1Len - 1); int cur2Tmp = min(cur2 + k / 2 - 1, nums2Len - 1); int nums1Tmp = nums1[cur1Tmp], nums2Tmp = nums2[cur2Tmp]; //扣除真实偏移 if (nums1Tmp <= nums2Tmp) { k -= cur1Tmp - cur1 + 1; cur1 = cur1Tmp + 1; } else { k -= cur2Tmp - cur2 + 1; cur2 = cur2Tmp + 1; } } return 0; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {//双数组求中值 size_t totalLen = nums1.size() + nums2.size(); if (totalLen % 2 == 1) { return getKthLarg(nums1, nums2, (totalLen + 1) / 2); } else { return (getKthLarg(nums1, nums2, totalLen / 2) + getKthLarg(nums1, nums2, totalLen / 2 + 1)) / 2.0; } } double myPow(double x, int n) {//二分法幂函数 if (n == 0) { return 1.0; } bool xIsNeg = x < 0 ? true : false; bool nIsNeg = n < 0 ? true : false; double nCopy; if (xIsNeg) { x = -x; if (n % 2 == 0) { xIsNeg = false; } } if (nIsNeg) { nCopy = -1.0 * n; } else { nCopy = n; } unsigned long powTime = 1; double res = x; while (powTime * 2 < nCopy) { powTime *= 2; res *= res; } if (powTime * 2 - nCopy < nCopy - powTime) { powTime *= 2; res *= res; } while (powTime < nCopy) { powTime++; res *= x; } while (powTime > nCopy) { powTime--; res /= x; } if (nIsNeg) { res = 1 / res; } if (xIsNeg) { res = -res; } return res; } bool isPerfectSquare(int num) { int left = 0, right = num < 46340 ? num : 46340, mid; while (left <= right) { mid = left + (right - left) / 2; int tmp = mid * mid; if (tmp == num) { return true; } else if (tmp > num) { right = mid - 1; } else { left = mid + 1; } } return false; } char nextGreatestLetter(vector<char>& letters, char target) { int left = 0, right = letters.size() - 1, mid; while (left < right) { mid = left + (right - left) / 2; if (letters[mid] <= target) { left = mid + 1; } else { right = mid; } } if (left == letters.size() - 1 && letters[left] <= target) { return letters[0]; } if (left < letters.size() - 1 && letters[left] <= target) { return letters[left + 1]; } return letters[left]; } //int smallestDistancePair(vector<int>& nums, int k) {//找出第 k 小的距离对, 暴力算法超时 // sort(nums.begin(), nums.end()); // size_t numsLen = nums.size(); // priority_queue<int, vector<int>, greater<int>> distQue; // for (size_t i = 0; i < numsLen; i++) { // for (size_t j = i + 1; j < numsLen; j++) { // distQue.push(nums[j] - nums[i]); // } // } // while (k > 1) { // distQue.pop(); // k--; // } // return distQue.top(); //} unordered_map<int, int>* kthMap; int smallestDistancePair(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); int left = 0, right = nums[nums.size() - 1] - nums[0], mid; kthMap = new unordered_map<int, int>; while (left < right) { mid = left + (right - left) / 2; if (getCount(nums, mid) >= k) { right = mid; } else { left = mid + 1; } } delete kthMap; return left; } int getCount(vector<int>& nums, int val) { //统计差小于k的对数,双指针思想 //nums[j] - nums[i] < val, 那么i, j之间所有差都小于val if (kthMap->count(val) > 0) { return (*kthMap)[val]; } size_t left = 0, right, res = 0, numsLen = nums.size(); for (right = 1; right < numsLen; right++) { while (nums[right] - nums[left] > val) { left++; } res += right - left; } (*kthMap)[val] = res; return res; } int splitArray(vector<int>& nums, int m) { int left = 0, right = 0, mid; size_t numsLen = nums.size(); for (size_t i = 0; i < numsLen; i++) { right += nums[i]; if (left < nums[i]) { left = nums[i]; } } while (left < right) { mid = left + (right - left) / 2; if (check(nums, mid, m)) { //能分割,进一步压缩最大值限制 right = mid; } else { left = mid + 1; } } return left; } bool check(vector<int>& nums, int val, int m) { //检查能不能以val为最大值,将数组分割成m段 long sum = 0; int cnt = 1; size_t numsLen = nums.size(); for (size_t i = 0; i < numsLen; i++) { //存在性 if (sum + nums[i] > val) { cnt++; sum = nums[i]; } else { sum += nums[i]; } } return cnt <= m; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<int> inpt = { 7, 2, 5, 10, 8 }; vector<char> inpt2 = { 'e', 'e', 'e', 'e', 'n', 'n' }; mySolution.splitArray(inpt, 2); return 0; } #endif //递归 #if false class Solution { public: //递归杨辉三角,使用map降低重复计算 unordered_map<int, unordered_map<int, int>> dpRes; vector<vector<int>> generate(int numRows) { vector<vector<int>> res; vector<int> tmp; for (size_t i = 0; i < numRows; i++) { tmp.clear(); for (size_t j = 0; j < i + 1; j++) { tmp.push_back(pascalNumber(i + 1, j + 1)); } res.push_back(tmp); } return res; } int pascalNumber(int i, int j) { if (dpRes.count(i) > 0 && (dpRes[i].count(j) > 0 || dpRes[i].count(i + 1 - j) > 0)) { return dpRes[i][j]; } if (i <= 1 || j <= 1 || i == j) { return 1; } int tmp = pascalNumber(i - 1, j - 1) + pascalNumber(i - 1, j); dpRes[i][j] = tmp; dpRes[i][i + 1 - j] = tmp; return tmp; } //递归生成杨辉三角特定行, 直接返回向量 vector<int> getRow(int rowIndex) { if (rowIndex == 0) { return vector<int>(1, 1); } vector<int> res = getRow(rowIndex - 1); for (size_t i = rowIndex - 1; i > 0; i--) { res[i] = res[i] + res[i - 1]; } res.push_back(1); return res; } //斐波那契数列,带记忆递归 unordered_map<int, int> fibMap; int fib(int N) { if (fibMap.count(N) > 0) { return fibMap[N]; } if (N < 2) { fibMap[N] = N; return N; } int res = fib(N - 1) + fib(N - 2); fibMap[N] = res; return res; } //尾递归,xor int kthGrammar(int N, int K) { if (N == 1) { return 0; } int bitCnt = 1 << (N - 1); if (K > bitCnt / 2) { return kthGrammar(N - 1, K - bitCnt / 2) ^ 1; } return kthGrammar(N - 1, K); } //生成所有搜索二叉树 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} }; vector<TreeNode*> generateTrees(int n) { if (n == 0) { return {}; } return generateSubTree(1, n); } vector<TreeNode*> generateSubTree(int start, int end) { if (start > end) { return { nullptr }; } vector<TreeNode*> allTree; for (int i = start; i <= end; i++) { vector<TreeNode*> leftTree = generateSubTree(start, i - 1); vector<TreeNode*> rightTree = generateSubTree(i + 1, end); for (auto& left : leftTree) { for (auto& right : rightTree) { TreeNode* currentTree = new TreeNode(i, left, right); allTree.emplace_back(currentTree); } } } return allTree; } }; int main(int argc, char* argv[]) { Solution mySolution; mySolution.generateTrees(3); return 0; } #endif //中级算法 #if false struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution { public: //三数之和 vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; sort(nums.begin(), nums.end()); size_t numsLen = nums.size(); for (size_t i = 0; i < numsLen; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } size_t k = numsLen - 1; for (size_t j = i + 1; j < numsLen; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } while (k > j && nums[i] + nums[j] + nums[k] > 0) { k--; } if (j == k) { break; } if (nums[i] + nums[j] + nums[k] == 0) { res.emplace_back(vector<int>({ nums[i], nums[j], nums[k] })); } } } return res; } //长度为 3 的递增子序列 bool increasingTriplet(vector<int>& nums) { size_t numsLen = nums.size(); if (numsLen < 3) { return false; } int small = 65535, mid = 65535; for (auto num : nums) { if (num <= small) { small = num; } else if (num <= mid) { mid = num; } else if (num > mid) { return true; } } return false; } //中序和前序构造二叉树 /*TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { size_t nodeCnt = preorder.size(); if (nodeCnt == 0) { return nullptr; } TreeNode* res = new TreeNode(preorder[0]); if (nodeCnt == 1) { return res; } size_t i; for (i = 0; i < nodeCnt; i++) { if (inorder[i] == preorder[0]) { break; } } vector<int> preleft(preorder.begin() + 1, preorder.begin() + i + 1); vector<int> inleft(inorder.begin(), inorder.begin() + i); vector<int> preright(preorder.begin() + i + 1, preorder.end()); vector<int> inright(inorder.begin() + i + 1, inorder.end()); res->left = buildTree(preleft, inleft); res->right = buildTree(preright, inright); return res; }*/ //中序和前序构造二叉树--优化 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { size_t nodeCnt = preorder.size(); return buildSubTree(preorder, 0, nodeCnt - 1, inorder, 0, nodeCnt - 1); } TreeNode* buildSubTree(vector<int>& preorder, int preLeft, int preRight, vector<int>& inorder, int inLeft, int inRight) { if (preLeft > preRight) { return nullptr; } TreeNode* res = new TreeNode(preorder[preLeft]); if (preLeft == preRight) { return res; } size_t i; for (i = 0; i + inLeft < inRight; i++) { if (inorder[i + inLeft] == preorder[preLeft]) { break; } } res->left = buildSubTree(preorder, preLeft + 1, preLeft + i, inorder, inLeft, inLeft + i - 1); res->right = buildSubTree(preorder, preLeft + i + 1, preRight, inorder, inLeft + i + 1, inRight); return res; } //电话号码字母组合 vector<string> letterCombinations(string digits) { vector<string> res; int digitLen = digits.size(); if (digitLen < 1) { return res; } unordered_map<char, string> dialMap = { {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"} }; for (char ch : digits) { string tmp = dialMap[ch]; if (res.size() == 0) { for (size_t i = 0; i < tmp.size(); i++) { res.push_back({ tmp[i] }); } continue; } vector<string> resCopy = res; res.clear(); for (string str : resCopy) { for (char tmpCh : tmp) { res.push_back(str + tmpCh); } } } return res; } //有效括号组合 vector<string> generateParenthesis(int n) { vector<string> res; if (n < 1) { return res; } unordered_set<string> resCand; res.push_back("()"); resCand.insert("()"); while (n > 1) { vector<string> resCopy = res; res.clear(); for (string tmp : resCopy) { int tmpLen = tmp.size(); for (int i = 1; i < tmpLen + 1; i++) { string tmpRes = tmp.substr(0, i) + "()" + tmp.substr(i, tmpLen - 1); if (resCand.count(tmpRes) > 0) { continue; } resCand.emplace(tmpRes); res.emplace_back(tmpRes); } } n--; } return res; } //没有重复 数字的序列 vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> res; size_t numsLen = nums.size(); if (numsLen < 1) { return res; } res.emplace_back(vector<int>{nums[0]}); for (size_t i = 1; i < numsLen; i++) { vector<vector<int>> resCopy = res; res.clear(); int tmpInt = nums[i]; for (vector<int> tmp : resCopy) { size_t tmpLen = tmp.size(); for (size_t j = 0; j <= tmpLen; j++) { vector<int> tmpAdd = tmp; tmpAdd.insert(tmpAdd.begin() + j, tmpInt); res.emplace_back(tmpAdd); } } } return res; } //给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集) vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res = { {} }; size_t numsLen = nums.size(); if (numsLen < 1) { return res; } int bitPos = pow(2, numsLen) - 1; vector<int> tmp; while (bitPos > 0) { tmp.clear(); int bitPosCopy = bitPos; for (size_t i = 0; i < numsLen; i++) { if (bitPosCopy & 0x1) { tmp.emplace_back(nums[i]); } bitPosCopy /= 2; } res.emplace_back(tmp); bitPos--; } return res; } //单词搜索 这个方法效率太低,虽然可行 vector<vector<bool>>* vist; bool exist(vector<vector<char>>& board, string word) { size_t colLen = board.size(); if (colLen < 1) { return false; } size_t rolLen = board[0].size(); if (rolLen < 1) { return false; } vist = new vector<vector<bool>>(colLen, vector<bool>(rolLen, false)); for (size_t i = 0; i < colLen; i++) { for (size_t j = 0; j < rolLen; j++) { if (exploreGrid(board, word, 0, i, j)) { delete vist; return true; } } } delete vist; return false; } // 原先版本, 未剪枝,超时 /*bool exploreGrid(vector<vector<char>>& board, string word, int n, int col, int rol) { size_t colLen = board.size(), rolLen = board[0].size(); int wordLen = word.size(); if (col < 0 || col >= colLen || rol < 0 || rol >= rolLen || board[col][rol] != word[n]) { return false; } if ((*vist)[col][rol]) { return false; } (*vist)[col][rol] = true; if (n == wordLen - 1) { return true; } bool upper = exploreGrid(board, word, n + 1, col - 1, rol); bool lower = exploreGrid(board, word, n + 1, col + 1, rol); bool left = exploreGrid(board, word, n + 1, col, rol - 1); bool right = exploreGrid(board, word, n + 1, col, rol + 1); (*vist)[col][rol] = false; return upper || lower || left || right; }*/ // 新版本,找到后立即返回,剪枝,且只有匹配成功的会被标记 bool exploreGrid(vector<vector<char>>& board, string& word, int n, int col, int rol) { size_t colLen = board.size(), rolLen = board[0].size(); int wordLen = word.size(); if (board[col][rol] != word[n]) { return false; } if (n == wordLen - 1) { return true; } (*vist)[col][rol] = true; vector<pair<int, int>> directions{ {0, 1}, {0, -1}, {1, 0}, {-1, 0} }; for (pair<int, int> dir : directions) { int newCol = col + dir.first, newRol = rol + dir.second; if (newCol >= 0 && newCol < colLen && newRol >= 0 && newRol < rolLen) { if (!(*vist)[newCol][newRol]) { if (exploreGrid(board, word, n + 1, newCol, newRol)) { (*vist)[col][rol] = false; return true; } } } } (*vist)[col][rol] = false; return false; } //三种颜色分类 void sortColors(vector<int>& nums) { size_t numsLen = nums.size(); if (numsLen < 2) { return; } size_t frontCur = 0, currentCur = 0, rearCur = numsLen - 1; for (currentCur = 0; currentCur <= rearCur; currentCur++) { while (currentCur <= rearCur && nums[currentCur] == 2) { swapElem(nums, rearCur, currentCur); rearCur--; if (rearCur == 0) { break; } } if (nums[currentCur] == 0) { swapElem(nums, frontCur, currentCur); frontCur++; } } return; } inline void swapElem(vector<int>& nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; return; } //在未排序的数组中找到第 k 个最大的元素 int findKthLargest(vector<int>& nums, int k) { size_t numsLen = nums.size(); quickSort(nums, 0, numsLen - 1); return nums[numsLen - k]; } void quickSort(vector<int>& nums, int front, int rear) { if (front >= rear) { return; } int pivot = nums[rear]; int cur = front; for (int i = front; i < rear; i++) { if (nums[i] <= pivot) { swapElem(nums, cur, i); cur++; } } swapElem(nums, cur, rear); quickSort(nums, front, cur - 1); quickSort(nums, cur + 1, rear); return; } //搜索二维矩阵 II bool searchMatrix(vector<vector<int>>& matrix, int target) { size_t colSize = matrix.size(); if (colSize == 0) { return false; } size_t rolSize = matrix[0].size(); if (rolSize == 0) { return false; } size_t col = colSize - 1, rol = 0; while (col >= 0 && rol <= rolSize - 1) { if (target == matrix[col][rol]) { return true; } else if (target < matrix[col][rol]) { col--; } else { rol++; } } return false; } //跳跃游戏--贪心 bool canJump(vector<int>& nums) { size_t numsLen = nums.size(); if (numsLen < 2) { return true; } size_t maxPos = 0; for (size_t i = 0; i < numsLen; i++) { size_t tmp = i + nums[i]; if (i > maxPos) { return false; } maxPos = tmp > maxPos ? tmp : maxPos; if (maxPos >= numsLen - 1) { return true; } } return false; } //不同路径--递归动态规划 //机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角 //问总共有多少条不同的路径 /*unordered_map<int, unordered_map<int, int>> pathVal; int uniquePaths(int m, int n) { if (m == 1 || n == 1) { return 1; } size_t val1, val2; if (pathVal.count(m - 1) > 0 && pathVal[m - 1].count(n) > 0) { val1 = pathVal[m - 1][n]; } else if (pathVal.count(n) > 0 && pathVal[n].count(m - 1) > 0) { val1 = pathVal[n][m - 1]; } else { val1 = uniquePaths(m - 1, n); pathVal[m - 1][n] = val1; } if (pathVal.count(m) > 0 && pathVal[m].count(n - 1) > 0) { val2 = pathVal[m][n - 1]; } else if (pathVal.count(n - 1) > 0 && pathVal[n - 1].count(m) > 0) { val2 = pathVal[n - 1][m]; } else { val2 = uniquePaths(m, n - 1); pathVal[m][n - 1] = val2; } return val1 + val2; }*/ //不同路径--迭代动态规划 //机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角 //问总共有多少条不同的路径 int uniquePaths(int m, int n) { vector<vector<int>> dp = vector<vector<int>>(m, vector<int>(n, 0)); for (size_t i = 0; i < m; i++) { for (size_t j = 0; j < n; j++) { if (i == 0 || j == 0) { dp[i][j] = 1; } else { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } //零钱兑换 int coinChange(vector<int>& coins, int amount) { vector<int> dp(amount + 1, amount + 1); dp[0] = 0; for (int i = 0; i <= amount; i++) { for (int coin : coins) { if (coin <= i) { dp[i] = min(dp[i], dp[i - coin] + 1); } } } return dp[amount] > amount ? -1 : dp[amount]; } //最长上升子序列 int lengthOfLIS(vector<int>& nums) { size_t numsLen = nums.size(); if (numsLen < 2) { return numsLen; } vector<int> dp(numsLen); int res = 0; for (size_t i = 0; i < numsLen; i++) { dp[i] = 1; for (size_t j = 0; j < i; j++) { if (nums[j] < nums[i]) { dp[i] = max(dp[i], dp[j] + 1); } } res = dp[i] > res ? dp[i] : res; } return res; } //阶乘后的零 int trailingZeroes(int n) { int res = 0; int tmp = 5; while (n >= tmp) { res += n / tmp; tmp *= 5; } return res; } //Excel表列序号 int titleToNumber(string s) { int sLen = s.size(); int res = 0; for (int i = 0; i < sLen; i++) { res *= 26; res += s[i] - 'A' + 1; } return res; } //快速幂 double myPow(double x, int n) { bool isNeg = n < 0 ? true : false; if (n == 0x7fffffff) { if (x == 1.0 || x == 1.0) { return x; } } int i = 31; double res = 1.0, tmp = x; while (n != 0) { if (n % 2) { res *= tmp; } tmp *= tmp; n = n / 2; } if (isNeg) { res = 1 / res; } return res; } //二分法除法,要求不使用乘法、除法和 mod 运算符 int divide(int dividend, int divisor) { long long res = 0; if (divisor == 0) { return 0x7fffffff; } if (dividend == 0) { return 0; } bool isNeg = false; if (dividend < 0 && divisor > 0 || dividend > 0 && divisor < 0) { isNeg = true; } long long dividendCopy = abs(dividend); long long divisorCopy = abs(divisor); while (dividendCopy >= divisorCopy) { long long tmp = divisorCopy; long long cnt = 1; while (tmp << 1 < dividendCopy) { cnt += cnt; tmp = tmp << 1; } dividendCopy -= tmp; res += cnt; } if (isNeg) { if (-res < INT_MIN) { return INT_MIN; } else { return -res; } } if (res > INT_MAX) { return INT_MAX; } return res; } //分数到小数 string fractionToDecimal(int numerator, int denominator) { if (denominator == 0) { return ""; } if (numerator == 0) { return "0"; } string res; if ((numerator > 0) ^ (denominator > 0)) { res.push_back('-'); } long long numCopy = abs(numerator), denCopy = abs(denominator); res.append(to_string(numCopy / denCopy)); numCopy %= denCopy; if (numCopy == 0) { return res; } res.push_back('.'); unordered_map<int, int> fracMap; int index = res.size(); while (numCopy != 0 && fracMap.count(numCopy) == 0) { fracMap[numCopy] = index; index++; numCopy *= 10; res += to_string(numCopy / denCopy); numCopy %= denCopy; } if (fracMap.count(numCopy) > 0) { res.insert(fracMap[numCopy], "("); res += ')'; } return res; } int getSum(int a, int b) { while (b) { auto carry = ((unsigned int)(a & b)) << 1;//进位 a ^= b;//不进位的结果 b = carry; } return a; } int evalRPN(vector<string>& tokens) { stack<int> op; for (auto token : tokens) { if (token.size() == 1 && (token[0] < '0' || token[0] > '9')) { int op1 = op.top(); op.pop(); int op2 = op.top(); op.pop(); if (token[0] == '+') { op1 = op1 + op2; } else if (token[0] == '-') { op1 = op2 - op1; } else if (token[0] == '*') { op1 = op1 * op2; } else { op1 = op2 / op1; } op.push(op1); } else { op.push(atoi(token.c_str())); } } return op.top(); } //多数元素:Boyer–Moore majority vote algorithm //如果候选人不是maj 则 maj,会和其他非候选人一起反对 会反对候选人,所以候选人一定会下台(maj==0时发生换届选举) //如果候选人是maj, 则maj 会支持自己,其他候选人会反对,同样因为maj 票数超过一半,所以maj 一定会成功当选 int majorityElement(vector<int>& nums) { int cand = -1, cnt = 0; for (int num : nums) { if (num == cand) { cnt++; } else if (--cnt < 0) { cand = num; cnt = 1; } } return cand; } //任务调度器 int leastInterval(vector<char>& tasks, int n) { unordered_map<char, int> freq; for (char ch : tasks) { freq[ch]++; } int maxExec = 0, maxCnt = 0; for (auto it = freq.begin(); it != freq.end(); it++) { if (it->second > maxExec) { maxExec = it->second; maxCnt = 1; } else if (it->second == maxExec) { maxCnt++; } } return max((maxExec - 1) * (n + 1) + maxCnt, int(tasks.size())); } }; class Codec { //二叉树的序列化与反序列化 public: string serialize(TreeNode* root) { string res; queue<TreeNode*> que; que.push(root); while (!que.empty()) { int siz = que.size(); while (siz--) { TreeNode* cur = que.front(); que.pop(); if (cur == nullptr) { res += "null,"; } else { string str_val = to_string(cur->val) + ","; res += str_val; que.push(cur->left); que.push(cur->right); } } } return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { queue<int>* valStack = pushStrVal(data); if (!valStack->size()) { return nullptr; } TreeNode* currentNode; int currentVal = valStack->front(); if (currentVal == -888) { return nullptr; } valStack->pop(); TreeNode* root = new TreeNode(currentVal); queue<TreeNode*> q; q.push(root); while (!q.empty()) { int qLen = q.size(); while (qLen) { currentNode = q.front(); q.pop(); qLen--; if (currentNode == nullptr) { continue; } currentVal = -888; if (!valStack->empty()) { currentVal = valStack->front(); valStack->pop(); } if (currentVal != -888) { currentNode->left = new TreeNode(currentVal); } q.push(currentNode->left); currentVal = -888; if (!valStack->empty()) { currentVal = valStack->front(); valStack->pop(); } if (currentVal != -888) { currentNode->right = new TreeNode(currentVal); } q.push(currentNode->right); } } return root; } queue<int>* pushStrVal(string& data) { queue<int>* valStack = new queue<int>; int dataLen = data.size(); int cur = 0; int tmpVal; int sign; while (cur < dataLen) { char tmp = data[cur]; if (tmp == '[' || tmp == ']' || tmp == ',') { cur++; continue; } if (data[cur] == 'n') { valStack->push(-888); cur += 4; continue; } sign = 1; tmpVal = 0; while (data[cur] != ',' && data[cur] != ']') { if (data[cur] == '-') { sign = -1; cur++; continue; } tmpVal = tmpVal * 10 + data[cur] - '0'; cur++; } tmpVal *= sign; valStack->push(tmpVal); } return valStack; } }; int main(int argc, char* argv[]) { vector<int> inptF = { 3,2,3,1,2,4,5,5,6 }, inptM = { 3, 2, 1 }; vector<int> nums = { 2,2,1,1,1,2,2 }; Solution mySolution; string digits = "ASF"; vector<vector<int>> matrix = { {1,4,7,11,15}, {2,5,8,12,19}, {3,6,9,16,22}, {10,13,14,17,24}, {18,21,23,26,30} }; Codec myCodec; string s = "AB"; vector<string> polInpt = { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" }; vector<char> tasks = { 'A','A','A','B','B','B' }; mySolution.leastInterval(tasks, 2); return 0; } #endif //高级算法--字符串数组 #if false class Solution { public: //除自身以外数组的乘积 vector<int> productExceptSelf(vector<int>& nums) { size_t numsLen = nums.size(); vector<int> res(numsLen); res[0] = 1; for (size_t i = 1; i < numsLen; i++) { res[i] = res[i - 1] * nums[i - 1]; } int tmp = 1; for (int i = numsLen - 1; i > -1; i--) { res[i] *= tmp; tmp *= nums[i]; } return res; } //螺旋矩阵 vector<int> spiralOrder(vector<vector<int>>& matrix) { size_t colSize = matrix.size(); if (colSize == 0) { return {}; } size_t rolSize = matrix[0].size(); size_t lim = min(colSize, rolSize); if (lim == 1) { lim = 1; } else if (lim % 2 == 1) { lim = lim / 2 + 1; } else { lim = lim / 2; } vector<int> res; for (size_t i = 0; i < lim; i++) { vector<int> tmp = getSub(matrix, i, colSize, rolSize); res.insert(res.end(), tmp.begin(), tmp.end()); } return res; } vector<int> getSub(vector<vector<int>>& matrix, size_t nth, size_t col, size_t rol) { vector<int> res; for (size_t i = nth; i < rol - nth; i++) { res.emplace_back(matrix[nth][i]); } if (nth + 1 == col - nth) {//只有一行,剪枝 return res; } for (size_t i = nth + 1; i < col - nth; i++) { res.emplace_back(matrix[i][rol - nth - 1]); } if (nth + 1 == rol - nth) {//只有一列,剪枝 return res; } for (size_t i = nth + 2; i < rol - nth; i++) { res.push_back(matrix[col - nth - 1][rol - i]); } for (size_t i = nth + 1; i < col - nth; i++) { res.push_back(matrix[col - i][nth]); } return res; } //生命游戏 void gameOfLife(vector<vector<int>>& board) { size_t colSize = board.size(); if (colSize == 0) { return; } size_t rolSize = board[0].size(); vector<vector<int>> boardCopy(board); for (size_t i = 0; i < colSize; i++) { for (size_t j = 0; j < rolSize; j++) { int convRes = conv(boardCopy, i, j, colSize, rolSize); if (convRes > 3 || convRes < 2) {//死亡 board[i][j] = 0; } else if (convRes == 3) {//复活 board[i][j] = 1; } } } return; } vector<vector<int>> directions = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} }; int conv(vector<vector<int>>& boardCopy, size_t col, size_t rol, size_t colSize, size_t rolSize) {//卷积 int res = 0; for (vector<int>& dir : directions) { int colCur = col + dir[0], rolCur = rol + dir[1]; if (colCur < 0 || colCur >= colSize || rolCur < 0 || rolCur >= rolSize) { continue; } res += boardCopy[colCur][rolCur]; } return res; } //缺失的第一个正数 //自定义哈希表 int firstMissingPositive(vector<int>& nums) { size_t numsLen = nums.size(); for (size_t i = 0; i < numsLen; i++) { if (nums[i] <= 0) { nums[i] = numsLen + 1; } } for (size_t i = 0; i < numsLen; i++) { int tmp = abs(nums[i]); if (tmp <= numsLen) { nums[tmp - 1] = -abs(nums[tmp - 1]); } } for (size_t i = 0; i < numsLen; i++) { if (nums[i] > 0) { return i + 1; } } return numsLen + 1; } int longestConsecutive(vector<int>& nums) { size_t numsLen = nums.size(); unordered_set<int> numsSet; for (int num : nums) { numsSet.emplace(num); } int res = 0; for (auto numElem : numsSet) { if (numsSet.count(numElem - 1) > 0) { continue; } int current = numElem; while (numsSet.count(current + 1) > 0) { current++; } res = (current - numElem + 1) > res ? (current - numElem + 1) : res; } return res; } void myQuickSort(vector<int>& nums, int left, int right) { if (left >= right) { return; } int pivot = nums[right]; int cur = left; for (int i = left; i <= right; i++) { if (nums[i] <= pivot) { int tmp = nums[cur]; nums[cur] = nums[i]; nums[i] = tmp; cur++; } } cur--; myQuickSort(nums, left, cur - 1); myQuickSort(nums, cur + 1, right); return; } //基本计算器 //这种垃圾算法还真是第一次遇到(没错,是我写的!) int calculate(string s) { int sLen = s.size(); stack<int> opNum; stack<char> oper; for (int i = 0; i < sLen; i++) {//提取操作数和操作符 if (s[i] == ' ') { continue; } if (s[i] > '9' || s[i] < '0') { oper.push(s[i]); continue; } int tmp = 0; while (s[i] >= '0' && s[i] <= '9') { tmp *= 10; tmp += s[i] - '0'; i++; } i--; opNum.push(tmp); } int res = 0; stack<int> opNumPN; stack<char> operPN; int tmp; //逆序栈 while (!oper.empty()) { operPN.push(oper.top()); oper.pop(); } while (!opNum.empty()) { opNumPN.push(opNum.top()); opNum.pop(); } while (!operPN.empty()) {//处理乘除法 char op = operPN.top(); operPN.pop(); tmp = opNumPN.top(); opNumPN.pop(); if (op == '*') { tmp *= opNumPN.top(); opNumPN.pop(); } else if (op == '/') { tmp /= opNumPN.top(); opNumPN.pop(); } else { oper.push(op); opNum.push(tmp); continue; } opNumPN.push(tmp); } if (!opNumPN.empty()) { opNum.push(opNumPN.top()); } //逆序栈 while (!oper.empty()) { operPN.push(oper.top()); oper.pop(); } while (!opNum.empty()) { opNumPN.push(opNum.top()); opNum.pop(); } res = opNumPN.top(); opNumPN.pop(); while (!operPN.empty()) { char op = operPN.top(); operPN.pop(); tmp = opNumPN.top(); opNumPN.pop(); if (op == '+') { res += tmp; } else { res -= tmp; } } return res; } //滑动窗口最大值 //动态规划 vector<int> maxSlidingWindow(vector<int>& nums, int k) { size_t numsLen = nums.size(); vector<int> res(numsLen - k + 1), left(numsLen), right(numsLen); int tmpL, tmpR; for (size_t i = 0; i < numsLen; i++) { if (i % k == 0) { tmpL = nums[i]; } else { tmpL = nums[i] > tmpL ? nums[i] : tmpL; } left[i] = tmpL;//左侧滑动窗口 if (i % k == numsLen % k || i == 0) { tmpR = nums[numsLen - 1 - i]; } else { tmpR = nums[numsLen - 1 - i] > tmpR ? nums[numsLen - 1 - i] : tmpR; } right[numsLen - 1 - i] = tmpR;//右侧滑动窗口 } for (size_t i = 0; i < numsLen - k + 1; i++) { res[i] = max(right[i], left[i + k - 1]);//到当前窗口结尾,下一个窗口开始到下一个窗口长度 } return res; } //最小覆盖子串 unordered_map<char, int> tMap, cntMap; bool check(void) {//检查是否包含 for (const auto& p : tMap) { if (cntMap[p.first] < p.second) { return false; } } return true; } string minWindow(string s, string t) { int sLen = s.size(); for (const char& tCh : t) { tMap[tCh]++; } int lCur = 0, rCur = 0, ansL = -1, ansR = -1, len = sLen + 1; while (rCur < sLen) { if (tMap.count(s[rCur]) > 0) {//是单词中的字母 cntMap[s[rCur]]++; } while (check()) {//左侧缩短字符串 if (rCur - lCur + 1 < len) { len = rCur - lCur + 1; ansL = lCur; } if (tMap.count(s[lCur]) > 0 && cntMap[s[lCur]] != 0) {//如果是单词中的话就排除 cntMap[s[lCur]]--; } lCur++; } rCur++; } if (ansL == -1) { return ""; } string res = s.substr(ansL, len); return res; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<int>nums = { 1,3,-1,-3,5,3,6,7 }; vector<vector<int>> matrix = { {1,4,7,11,15}, {2,5,8,12,19}, {3,6,9,16,22}, {10,13,14,17,24}, {18,21,23,26,30} }; vector<vector<int>> matrix2 = { {3}, {2} }; vector<vector<int>> matrixlive = { {0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0} }; string inpt = " 1-1+1 "; string s = "A"; string t = "AA"; mySolution.minWindow(s, t); return 0; } #endif //高级算法--链表 #if false class Solution { struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; public: ////合并K个排序链表 暴力算法~800ms ////新建节点版本,效率低(构造函数调用过多) //bool check(vector<ListNode*>& lists) { // for (const ListNode* listHead : lists) {//换成序列访问,能快10% // if (listHead != nullptr) { // return true; // } // } // return false; //} //ListNode* mergeKLists(vector<ListNode*>& lists) { // ListNode* root, * current; // root = new ListNode; // current = root; // size_t listLen = lists.size(); // while (check(lists)) { // int minVal = INT_MAX, pos = -1; // for (size_t i = 0; i < listLen; i++) { // if (lists[i] == nullptr) { // continue; // } // if (lists[i]->val < minVal) { // pos = i; // minVal = lists[i]->val; // } // } // lists[pos] = lists[pos]->next; // current->next = new ListNode(minVal); // current = current->next; // //连接节点版本,内存占用下降 // /*current->next = lists[pos]; // lists[pos] = lists[pos]->next; // current = current->next;*/ // } // return root->next; //} //分治法~80ms //合并两个链表 ListNode* mergeTwoLists(ListNode* a, ListNode* b) { if (a == nullptr || b == nullptr) { return a == nullptr ? b : a; } ListNode* root = new ListNode; ListNode* current = root; while (a != nullptr && b != nullptr) { if (a->val < b->val) { current->next = a; a = a->next; } else { current->next = b; b = b->next; } current = current->next; } current->next = a == nullptr ? b : a; return root->next; } ListNode* merge(vector<ListNode*>& lists, int left, int right) { if (left == right) { return lists[left]; } if (left > right) { return nullptr; } int mid = (left + right) / 2; return mergeTwoLists(merge(lists, left, mid), merge(lists, mid + 1, right)); } ListNode* mergeKLists(vector<ListNode*>& lists) { return merge(lists, 0, lists.size() - 1); } //排序链表--快速排序 //超出时间限制 void listQuickSort(vector<ListNode*>& lists, int left, int right) { if (left >= right) { return; } int pivot = lists[left]->val; int frontCur = left, rearCur = right; while (frontCur != rearCur) { while (frontCur != rearCur && lists[rearCur]->val >= pivot) { rearCur--; } while (frontCur != rearCur && lists[frontCur]->val <= pivot) { frontCur++; } if (frontCur < rearCur) { ListNode* tmp = lists[frontCur]; lists[frontCur] = lists[rearCur]; lists[rearCur] = tmp; } } ListNode* tmp = lists[left]; lists[left] = lists[frontCur]; lists[frontCur] = tmp; listQuickSort(lists, left, frontCur - 1); listQuickSort(lists, frontCur + 1, right); return; } /*ListNode* sortList(ListNode* head) { vector<ListNode*> lists; while (head != nullptr) { lists.emplace_back(head); head = head->next; } size_t listLen = lists.size(); listQuickSort(lists, 0, listLen - 1); lists.emplace_back(nullptr); for (size_t i = 0; i < listLen; i++) { lists[i]->next = lists[i + 1]; } return lists[0]; }*/ //分治 ListNode* sortList(ListNode* head) { vector<ListNode*> lists; while (head != nullptr) { ListNode* tmp = head; lists.emplace_back(head); head = head->next; tmp->next = nullptr; } return merge(lists, 0, lists.size() - 1); } }; int main(int argc, char* argv[]) { Solution mySolution; mySolution.sortList(nullptr); return 0; } #endif //高级算法--树和图 #if false class Solution { struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} }; public: //单词接龙 unordered_map<string, int> wordID; vector<vector<int>> edge; int nodeCnt = 0; void addWord(string& word) { if (wordID.count(word) < 1) { wordID[word] = nodeCnt; edge.emplace_back(); nodeCnt++; } return; } void addEdge(string& word) { addWord(word); int id1 = wordID[word]; for (char& ch : word) { char tmp = ch; //替换状态,新建虚拟节点,虚拟节点之间相连,单词之间不直接相连 ch = '*'; addWord(word); int id2 = wordID[word]; edge[id1].emplace_back(id2); edge[id2].emplace_back(id1); //结束替换状态 ch = tmp; } return; } //双向搜索平均时间降低25% int ladderLength(string beginWord, string endWord, vector<string>& wordList) { for (string& word : wordList) { addEdge(word); } addEdge(beginWord); if (wordID.count(endWord) < 1) {//list 中没有endword return 0; } //前向搜索 int beginID = wordID[beginWord]; vector<int> disBegin(nodeCnt, INT_MAX); disBegin[beginID] = 0;//记录边数量 queue<int> queBegin; queBegin.push(beginID); //反向搜索 int endID = wordID[endWord]; vector<int> disEnd(nodeCnt, INT_MAX); disEnd[endID] = 0; queue<int> queEnd; queEnd.push(endID); //开始搜索 while (!queBegin.empty() && !queEnd.empty()) { //前向搜索 int queBeginLen = queBegin.size(); for (int i = 0; i < queBeginLen; i++) { int curBegin = queBegin.front(); queBegin.pop(); if (disEnd[curBegin] != INT_MAX) {//后向搜索到了该点 return (disBegin[curBegin] + disEnd[curBegin]) / 2 + 1; } for (int& it : edge[curBegin]) { if (disBegin[it] == INT_MAX) { disBegin[it] = disBegin[curBegin] + 1; queBegin.push(it); } } } //反向搜索 int queEndLen = queEnd.size(); for (int i = 0; i < queEndLen; i++) { int curEnd = queEnd.front(); queEnd.pop(); if (disBegin[curEnd] != INT_MAX) {//前向搜索到了该点 return (disBegin[curEnd] + disEnd[curEnd]) / 2 + 1; } for (int& it : edge[curEnd]) { if (disEnd[it] == INT_MAX) { disEnd[it] = disEnd[curEnd] + 1; queEnd.push(it); } } } } return 0; } //被围绕的区域 //内存占用可以优化:不用vist矩阵,将board修改为其他值 /*vector<vector<int>> direction = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };*/ void solve(vector<vector<char>>& board) { int colSize = board.size(); if (colSize == 0) { return; } int rolSize = board[0].size(); vector<vector<bool>> vist(colSize, vector<bool>(rolSize, false)); //标记靠边区块 for (int i = 0; i < colSize; i++) { for (int j = 0; j < rolSize; j++) { //不是边缘跳过 if (i != 0 && j != 0 && i != colSize - 1 && j != rolSize - 1) { continue; } //未访问过的白块,BFS if (board[i][j] == 'O' && vist[i][j] == false) { vist[i][j] = true; queue<pair<int, int>> que; que.push(make_pair(i, j)); while (!que.empty()) { int qLen = que.size(); while (qLen != 0) { int colCurBase = que.front().first; int rolCurBase = que.front().second; que.pop(); qLen--; for (int dirCnt = 0; dirCnt < 4; dirCnt++) { int colCur = colCurBase + direction[dirCnt][0]; int rolCur = rolCurBase + direction[dirCnt][1]; if (colCur < 0 || rolCur < 0 || colCur >= colSize || rolCur >= rolSize) { continue; } if (vist[colCur][rolCur] == true || board[colCur][rolCur] == 'X') { continue; } vist[colCur][rolCur] = true; que.push(make_pair(colCur, rolCur)); } } } } } } //根据vist 标记 for (int i = 0; i < colSize; i++) { for (int j = 0; j < rolSize; j++) { if (vist[i][j] == false && board[i][j] == 'O') { board[i][j] = 'X'; } } } return; } //二叉树中的最大路径和 int maxPathVal = INT_MIN; int maxPathSum(TreeNode* root) { maxGain(root); return maxPathVal; } int maxGain(TreeNode* root) { if (root == nullptr) { return 0; } int leftGain = max(maxGain(root->left), 0); int rightGain = max(maxGain(root->right), 0); int currentGain = leftGain + rightGain + root->val; if (currentGain > maxPathVal) { maxPathVal = currentGain; } return root->val + max(rightGain, leftGain); } //朋友圈 //BFS效率稍低,128ms,时间复杂度0(n^2),空间复杂度0(n) int findCircleNum(vector<vector<int>>& M) { int mSize = M.size(); if (mSize < 2) { return mSize; } int res = 0; queue<int> q; for (int i = 0; i < mSize; i++) { for (int j = 0; j < mSize; j++) { if (M[i][j] == 0 || M[i][j] == 2) { continue; } M[i][j] = 2; q.push(j); while (!q.empty()) { int cur = q.front(); q.pop(); for (int k = 0; k < mSize; k++) { if (M[cur][k] == 0 || M[cur][k] == 2) { continue; } M[cur][k] = 2; q.push(k); } } res++; } } return res; } //课程表 //拓扑排序,判断是否存在环:排序后结点数量大于源节点数量 bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { vector<int> inDegree(numCourses, false); vector<vector<int>> edges(numCourses); for (vector<int>& req : prerequisites) { //0:子节点 //1:父节点 edges[req[1]].push_back(req[0]); inDegree[req[0]]++; } queue<int> q; for (size_t i = 0; i < numCourses; i++) { if (inDegree[i] == 0) { q.push(i); } } int vistCnt = 0; while (!q.empty()) { int u = q.front(); vistCnt++;//模拟出队列 q.pop(); for (int i : edges[u]) { inDegree[i]--; if (inDegree[i] == 0) { q.push(i); } } } return vistCnt == numCourses; } //课程表 II //靠入度决定顺序 vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<int> inDegree(numCourses, false); vector<vector<int>> edges(numCourses); for (vector<int>& req : prerequisites) { //0:子节点 //1:父节点 edges[req[1]].push_back(req[0]); inDegree[req[0]]++; } queue<int> q; for (size_t i = 0; i < numCourses; i++) { if (inDegree[i] == 0) { q.push(i); } } vector<int> res; int vistCnt = 0; while (!q.empty()) { int u = q.front(); res.push_back(u); vistCnt++; q.pop(); for (int i : edges[u]) { inDegree[i]--; if (inDegree[i] == 0) { q.push(i); } } } return vistCnt == numCourses ? res : vector<int>{}; } //矩阵中的最长递增路径 //DFS,回溯 //超出时间限制 //加上memo记忆矩阵,完成 vector<vector<int>> direction = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; int longestIncreasingPath(vector<vector<int>>& matrix) { int colSize = matrix.size(); if (colSize == 0) { return 0; } int rolSize = matrix[0].size(); unordered_set<int> numbers; vector<vector<bool>> vist(colSize, vector<bool>(rolSize, false)); vector<vector<int>> memo(colSize, vector<int>(rolSize, 0)); int res = 0; for (int i = 0; i < colSize; i++) { for (int j = 0; j < rolSize; j++) { res = max(lipDFS(matrix, vist, colSize, rolSize, i, j, memo), res); } } return res + 1; } int lipDFS(vector<vector<int>>& matrix, vector<vector<bool>>& vist, int colSize, int rolSize, int colCur, int rolCur, vector<vector<int>>& memo) { vist[colCur][rolCur] = true; int current = matrix[colCur][rolCur]; int res = -1; for (size_t i = 0; i < 4; i++) { int col = colCur + direction[i][0]; int rol = rolCur + direction[i][1]; if (col < 0 || rol < 0 || col >= colSize || rol >= rolSize) { continue; } if (vist[col][rol] == true) { continue; } int tmp = matrix[col][rol]; if (tmp > current) { if (memo[col][rol] == 0) { memo[col][rol] = lipDFS(matrix, vist, colSize, rolSize, col, rol, memo); } res = max(memo[col][rol], res); } } vist[colCur][rolCur] = false; return res + 1; } //计算右侧小于当前元素的个数 //计算节点出度 //时间复杂度0(n^2),超时 /*vector<int> countSmaller(vector<int>& nums) { size_t numslen = nums.size(); vector<int> res(numslen, 0); for (size_t i = 0; i < numslen; i++) { int tmp = nums[i]; for (size_t j = 0; j < i; j++) { if (tmp < nums[j]) { res[j]++; } } } return res; }*/ //离散化树状数组 //超时而且答案看不懂 //vector<int> countSmaller(vector<int>& nums) { // size_t numslen = nums.size(); // vector<int> res(numslen, 0); // unordered_map<int, int> numCnt; // for (int i = numslen - 1; i > -1; i--) { // numCnt[nums[i]]++; // for (auto& it : numCnt) {//主要是这里费时间 // if (it.first < nums[i]) { // res[i] += it.second; // } // } // } // return res; //} //抄的答案 //树状数组计算浅醉和,区间和 //原数组为nums, //将nums离散化,此处是排序+去重,转化为数组a vector<int> a; //将nums对应a的元素update到树状数组c vector<int> c; //resize树状数组大小 void init(int len) { c.resize(len); } //lowbit为二进制中最低位的1的值 int lowbit(int x) { return x & (-x); } //单点更新,从子节点更新到所有父节点(祖父节点等一直往上到上限c.size()) void update(int pos) { while (pos < c.size()) { c[pos] += 1; pos += lowbit(pos); } } //查询,实际是求和[0,...,pos],即求1~pos的元素数量 //如c[8],在update时,a[1],a[2],a[3],...,a[8]都会使c[8]增加一个value(该题中我们设置为1) //res += c[8],然后8减去lowbit为0。 //也可以拿c[6]举例,c[6] =a[5]+a[6],lowbit后,c[4] = a[1]+a[2]+a[3]+a[4] int query(int pos) { int res = 0; while (pos) { res += c[pos]; pos -= lowbit(pos); } return res; } //离散化处理 void Discretization(vector<int>& nums) { //拷贝数组 [5,4,5,3,2,1,1,1,1,1] a.assign(nums.begin(), nums.end()); //排序[1,1,1,1,1,2,3,4,5,5] sort(a.begin(), a.end()); //去重[1,2,3,4,5] a.erase(unique(a.begin(), a.end()), a.end()); } int getId(int x) { //lower_bound返回第一个不小于x的迭代器 //[1,2,3,4,5]中1,减去begin()再加1,得到id(1-5) return lower_bound(a.begin(), a.end(), x) - a.begin() + 1; } vector<int> countSmaller(vector<int>& nums) { vector<int> res; int n = nums.size(); //题解是+5,其实+1就够了,树状数组中我们不使用0下标,所以需扩展1位空间 //当然直接用n结果也是对的。这里再推敲推敲 init(n + 1); //将nums转化为a Discretization(nums); for (int i = n - 1; i >= 0; --i) { //倒序处理 int id = getId(nums[i]); //查询严格小于id的元素数量,所以使用id-1 res.push_back(query(id - 1)); //更新id,其实更新也可以提前,因为查询是id-1,所以更新操作不影响当前结果 update(id); } //倒序处理再倒序回来。如果不是用push_back,直接用下标可以不用在这里再倒序 reverse(res.begin(), res.end()); return res; } }; int main(int argc, char* argv[]) { vector<string> wordList = { "bit" }; string beginWord = "hit", endWord = "bit"; Solution mySolution; vector<vector<char>> matrix = { {'X', 'X', 'X', 'X'}, {'X', 'O', 'O', 'X'}, {'X', 'X', 'O', 'X'}, {'X', 'O', 'X', 'X'} }; vector<vector<int>> M = {//2 {1, 1, 0}, {1, 1, 0}, {0, 0, 1} }; vector<vector<int>> M2 = {//1 {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 1}, {1, 0, 1, 1} }; vector<vector<int>> course = { {0, 1}, {1, 0}, {1, 2} }; vector<vector<int>> nums = { {9, 9, 4}, {6, 6, 8}, {2, 1, 1} }; vector<int> inptNums = { 5,2,6,1 }; mySolution.countSmaller(inptNums); return 0; } #endif //高级算法-回溯 #if false class Solution { public: //分割回文串 //最耗时地方是判断回文 vector<vector<string>> res; vector<string> path; vector<vector<string>> partition(string s) { cutString(s, 0, s.size()); return res; } void cutString(string& s, int startIndex, int sLen) { if (startIndex == sLen) { res.push_back(path); return; } for (int i = startIndex; i < sLen; i++) { if (isPalindrome(s, startIndex, i)) { string str = s.substr(startIndex, i - startIndex + 1); path.push_back(str); cutString(s, i + 1, sLen); path.pop_back(); } } return; } bool isPalindrome(string& s, int left, int right) { while (left < right) { if (s[left] != s[right]) { return false; } left++; right--; } return true; } //删除无效的括号 //去重靠跳过相等字符 vector<string> removeInvalidParentheses(string s) { int left = 0, right = 0; vector<string> res; int sLen = 0; for (char& ch : s) { if (ch == '(') { left++; } else if (ch == ')') { if (left > 0) { left--; } else { right++; } } sLen++; } dfs(s, 0, left, right, res); return res; } void dfs(string s, int start, int l, int r, vector<string>& res) { if (l == 0 && r == 0) {//不需要删除的括号为零 if (isValid(s)) { res.push_back(s); } return; } size_t sLen = s.size(); for (size_t i = start; i < sLen; i++) { if (i != start && s[i] == s[i - 1]) {//去重 continue; } if (s[i] == '(' && l > 0) { dfs(s.substr(0, i) + s.substr(i + 1, sLen - i - 1), i, l - 1, r, res); } if (s[i] == ')' && r > 0) { dfs(s.substr(0, i) + s.substr(i + 1, sLen - i - 1), i, l, r - 1, res); } } return; } bool isValid(string& s) {//判断字符串是否有效 int cnt = 0; for (char& c : s) { if (c == '(') { cnt++; } else if (c == ')') { cnt--; if (cnt < 0) { return false; } } } return cnt == 0; } //通配符匹配 //动态规划 //bool isMatch(string s, string p) { // size_t sLen = s.size(), pLen = p.size(); // vector<vector<bool>> dp(sLen + 1, vector<bool>(pLen + 1, false)); // dp[0][0] = true;//dp[i][j] 表示字符串 s 的前 i 个字符和模式 p 的前 j 个字符是否能匹配 // for (size_t i = 1; i <= pLen; i++) { // if (p[i - 1] == '*') { // dp[0][i] = true; // } // else { // break;//找到第一个不是*的p[i] // } // } // for (size_t i = 1; i <= sLen; i++) { // for (size_t j = 1; j <= pLen; j++) { // if (p[j - 1] == '*') { // dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; // } // else if (p[j - 1] == '?' || s[i - 1] == p[j - 1]) { // dp[i][j] = dp[i - 1][j - 1]; // } // } // } // return dp[sLen][pLen]; //} //正则表达式匹配 bool isMatch(string s, string p) { size_t sLen = s.size(), pLen = p.size(); vector<vector<bool>> dp(sLen + 1, vector<bool>(pLen + 1, false)); dp[0][0] = true; for (size_t i = 1; i <= pLen; i++) { if (i >= 2 && p[i - 1] == '*' && dp[0][i - 2]) // 记得加 i >= 2的判断 dp[0][i] = true; } for (size_t i = 1; i < sLen + 1; i++) { for (size_t j = 1; j < pLen + 1; j++) { if (p[j - 1] == '*' && j > 1) { if (p[j - 2] != s[i - 1] && p[j - 2] != '.') dp[i][j] = dp[i][j - 2]; else dp[i][j] = dp[i][j - 2] || dp[i][j - 1] || dp[i - 1][j]; } else if (p[j - 1] == '.' || s[i - 1] == p[j - 1]) {//全字符匹配 dp[i][j] = dp[i - 1][j - 1]; } } } return dp[sLen][pLen]; } }; int main(int argc, char* argv[]) { string s = "aa"; string p = "a*"; Solution mySolution; mySolution.isMatch(s, p); return 0; } #endif //高级算法-搜索和排序 #if false class Solution { public: //摆动排序 II //其实就是找中位数 //抄代码真香 void wiggleSort(vector<int>& nums) { size_t numsLen = nums.size(); auto midPtr = nums.begin() + numsLen / 2; nth_element(nums.begin(), midPtr, nums.end()); int mid = *midPtr; size_t i = 0, j = 0, k = numsLen - 1; while (j < k) { if (nums[j] > mid) { swap(nums[j], nums[k]); k--; } else if (nums[j] < mid) { swap(nums[j], nums[i]); i++; j++; } else { j++; } } if (numsLen % 2 == 1) { midPtr++; } vector<int> tmpL(nums.begin(), midPtr); vector<int> tmpU(midPtr, nums.end()); size_t tmpLLen = tmpL.size(); size_t tmpULen = tmpU.size(); for (size_t i = 0; i < tmpLLen; i++) { nums[2 * i] = tmpL[tmpLLen - 1 - i]; } for (size_t i = 0; i < tmpULen; i++) { nums[2 * i + 1] = tmpU[tmpULen - 1 - i]; } return; } //有序矩阵中第K小的元素 //矩阵行列递增 //用二分查找 int kthSmallest(vector<vector<int>>& matrix, int k) { int matrixDegree = matrix.size(); int lwr = matrix[0][0], upr = matrix[matrixDegree - 1][matrixDegree - 1]; while (lwr < upr) { int mid = lwr + (upr - lwr) / 2; if (check(matrix, matrixDegree, mid, k)) { upr = mid; } else { lwr = mid + 1; } } return lwr; } bool check(vector<vector<int>>& matrix, int matrixDegree, int mid, int k) { int colCur = matrixDegree - 1, rolCur = 0, res = 0; while (colCur > -1 && rolCur < matrixDegree) { if (matrix[colCur][rolCur] <= mid) { res += colCur + 1; rolCur++; } else { colCur--; } } return res >= k; } }; int main(int argc, char* argv[]) { string s = "aa"; string p = "a*"; Solution mySolution; vector<int> nums1 = { 1, 5, 1, 1, 6, 4 }; vector<int> nums2 = { 1, 3, 2, 2, 3, 1 }; vector<vector<int>> marrix = { {1, 5, 9}, {10, 11, 13}, {12, 13, 15} }; mySolution.kthSmallest(marrix, 8); return 0; } #endif //高级算法-动态规划 #if false class Solution { public: //乘积最大子数组 int maxProduct(vector<int>& nums) { size_t numsLen = nums.size(); int maxVal = nums[0], minVal = nums[0], res = nums[0]; for (size_t i = 1; i < numsLen; i++) { int maxTmp = maxVal, minTmp = minVal; maxVal = max(maxTmp * nums[i], max(nums[i], minTmp * nums[i])); minVal = min(minTmp * nums[i], min(nums[i], maxTmp * nums[i])); res = max(maxVal, res); } return res; } //最佳买卖股票时机含冷冻期 int maxProfit(vector<int>& nums) { size_t numsLen = nums.size(); if (numsLen < 1) { return 0; } //vector<vector<int>> dp(3, vector<int>(numsLen)); int dp0 = -nums[0], dp1 = 0, dp2 = 0; //dp[0][0] = -nums[0];//买入负收益,持有状态 //dp[1][0] = 0;//冷却期累计收益,非持有 //dp[2][0] = 0;//非冷却期累计收益,非持有 for (size_t i = 1; i < numsLen; i++) { //dp[0][i] = max(dp[0][i - 1], dp[2][i - 1] - nums[i]);//今天结束时持有,可能是昨天持有或者今天买入的 //dp[1][i] = dp[0][i - 1] + nums[i];//今天结束时在冷静期,肯定是今天卖了 //dp[2][i] = max(dp[1][i - 1], dp[2][i - 1]);//今天结束时没持有且不在冷静期,昨天可能是冷静期或者不是冷静期 int dp0n = max(dp0, dp2 - nums[i]); int dp1n = dp0 + nums[i]; int dp2n = max(dp1, dp2); dp0 = dp0n, dp1 = dp1n, dp2 = dp2n; } //return max(dp[1][numsLen - 1], dp[2][numsLen - 1]); return max(dp1, dp2); } //完全平方数 //动态规划,转移方程:dp[i] = min(dp[i - k^2]) + 1, 其中i >= k^2 int numSquares(int n) { vector<int> dp(n + 1); dp[0] = 0; dp[1] = 1; for (size_t i = 2; i <= n; i++) { int minCnt = 5; size_t tmp = 1; for (tmp = 1; i >= tmp * tmp; tmp++) { minCnt = min(minCnt, dp[i - tmp * tmp]); } dp[i] = minCnt + 1; } return dp[n]; } //单词拆分 //能拆分的单词总是等于前一个已拆分的加上一个在词典中的单词 //如果改成从后往前推可能会更快一些 /*bool wordBreak(string s, vector<string>& wordDict) { size_t sLen = s.size(); unordered_set<string> dictSet; for (string& str : wordDict) { dictSet.emplace(str); } vector<bool> dp(sLen + 1, false); dp[0] = true; string tmp; for (size_t i = 0; i < sLen; i++) { for (size_t j = 0; j <= i; j++) { if (dp[j]) { tmp = s.substr(j, i + 1 - j); if (dictSet.count(tmp) > 0) { dp[i + 1] = true; break; } } } } return dp[sLen]; }*/ //单词拆分 II //递归没剪枝 /*unordered_set<string>* dictSet; size_t sLen; vector<string> res; string tmp; vector<string> wordBreak(string s, vector<string>& wordDict) { sLen = s.size(); dictSet = new unordered_set<string>(wordDict.begin(), wordDict.end()); sliceString(s, 0); return res; } void sliceString(string& s, size_t cur) { if (cur >= sLen) { tmp.pop_back(); res.emplace_back(tmp); return; } string local; for (size_t i = cur; i <= sLen; i++) { local = s.substr(cur, i - cur); if (dictSet->count(local) > 0) { size_t tmpLen = tmp.size(); tmp.append(local); tmp.push_back(' '); sliceString(s, i); tmp = tmp.substr(0, tmpLen); } } return; }*/ //优化递归 vector<string> wordBreak(string s, vector<string>& wordDict) { unordered_set<string> dict(wordDict.begin(), wordDict.end()); vector<string> res; return backtrack(s, 0, dict); } unordered_map<int, vector<string>> memo;//记忆化 vector<string> backtrack(string& s, int start, unordered_set<string>& dict) { if (start == s.size()) { return { "" }; } if (memo.count(start)) {//这个位置以后的所有单词排列组合 return memo[start]; } vector<string> res; for (size_t i = start; i < s.size(); i++) { auto prefix = s.substr(start, i - start + 1);//前缀单词 if (dict.count(prefix)) { auto suffixes = backtrack(s, i + 1, dict);//后缀单词表排列组合 for (const auto& suffix : suffixes) { auto str = prefix;//新建一个排列 if (!suffix.empty()) { str += ' ' + suffix; } res.push_back(str); } } } memo[start] = res;//储存后缀排列组合并返回 return memo[start]; } //戳气球 //关键点在于最后一个戳破的气球,开区间中任意一个戳破的气球 int maxCoins(vector<int>& nums) { if (nums.size() == 0) { return 0; } vector<int> numsCopy(1, 1); numsCopy.insert(numsCopy.end(), nums.begin(), nums.end()); numsCopy.push_back(1); size_t numsLen = numsCopy.size(); vector<vector<int>> dp(numsLen, vector<int>(numsLen, 0));//头尾各一个1 size_t lenUb = numsLen + 1; for (size_t len = 3; len < lenUb; len++) {//区间长度循环 size_t curUb = numsLen - len + 1; for (size_t cur = 0; cur < curUb; cur++) {//起始位置循环 size_t posUb = cur + len - 1; int maxVal = -1; for (size_t j = cur + 1; j < posUb; j++) {//区间内循环 int left = dp[cur][j]; int right = dp[j][posUb]; int sum = left + right + numsCopy[cur] * numsCopy[j] * numsCopy[posUb]; if (sum > maxVal) { maxVal = sum; } } dp[cur][posUb] = maxVal; } } return dp[0][numsLen - 1]; } }; int main(int argc, char* argv[]) { string s = "aa"; string p = "a*"; string word = "catsanddog"; string word2 = "a"; vector<string> dict = { "cat", "cats", "and", "sand", "dog" }; vector<string> dict2 = { "a" }; Solution mySolution; vector<int> nums1 = { 1, 5, 1, 1, 6, 4 }; vector<int> nums2 = { 1, 3, 2, 2, 3, 1 }; vector<int> nums = { 3,1,5,8 }; vector<vector<int>> marrix = { {1, 5, 9}, {10, 11, 13}, {12, 13, 15} }; mySolution.maxCoins(nums); return 0; } #endif //高级算法-设计问题 #if false class LRUCache {//LRU缓存机制 public: //读取写入都算一次访问 LRUCache(int capacity) {//设置缓存容量 capLim = capacity; map = new unordered_map<int, node*>; head = new node; tail = new node; head->rear = tail; tail->front = head; return; } int get(int key) { if (map->count(key) < 1) { return -1; } moveToFront((*map)[key]); return (*map)[key]->val; } void put(int key, int value) { int cnt = map->size(); if (map->count(key) < 1) {//添加元素 addFront(key, value); if (cnt == capLim) { deleteTail(); } (*map)[key] = head->rear; } else {//更新元素 (*map)[key]->val = value; moveToFront((*map)[key]); } return; } private: struct node {//双向链表,高频访问在前 node* front = nullptr, * rear = nullptr; int key = -1; int val = -1; }; int capLim = -1; //两个假节点 node* head = nullptr; node* tail = nullptr; unordered_map<int, node*>* map;//加速缓存 void moveToFront(node* cur) {//访问过就提到最前 if (cur == head->rear) { return; } cur->front->rear = cur->rear; cur->rear->front = cur->front; cur->rear = head->rear; head->rear->front = cur; cur->front = head; head->rear = cur; return; } void deleteTail() {//删除最低频访问数据 node* tmp = tail->front; tail->front = tmp->front; tmp->front->rear = tail; map->erase(tmp->key);//注意删除节点 delete tmp; return; } void addFront(int key, int val) {//添加一个新元素 node* tmp = new node; tmp->key = key; tmp->val = val; tmp->rear = head->rear; head->rear->front = tmp; tmp->front = head; head->rear = tmp; return; } }; class Trie {//实现 Trie (前缀树) public: /** Initialize your data structure here. */ Trie() { root = new treeNode; return; } /** Inserts a word into the trie. */ void insert(string word) { treeNode* current = root; for (char& ch : word) { if (current->next.count(ch) < 1) { current->next[ch] = new treeNode; current->next[ch]->val = ch; } current = current->next[ch]; } current->isWord = true; } /** Returns if the word is in the trie. */ bool search(string word) { treeNode* current = root; for (char& ch : word) { if (current->next.count(ch) > 0) { current = current->next[ch]; } else { return false; } } return current->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { treeNode* current = root; for (char& ch : prefix) { if (current->next.count(ch) > 0) { current = current->next[ch]; } else { return false; } } return current->isWord || current->next.size() != 0; } private: struct treeNode { char val = '*'; bool isWord = false; unordered_map<char, treeNode*> next; }; treeNode* root; }; class MedianFinder {//数据流的中位数 public: /** initialize your data structure here. */ MedianFinder() { return; } void addNum(int num) { lo.push(num); hi.push(lo.top()); lo.pop(); if (lo.size() < hi.size()) {//只有一个元素的时候 lo.push(hi.top()); hi.pop(); } return; } double findMedian() { return lo.size() > hi.size() ? lo.top() : (lo.top() + hi.top()) * 0.5; } private: priority_queue<int> lo; //大顶 小数 priority_queue<int, vector<int>, greater<int>> hi;//小顶 大数 }; int main(int argc, char* argv[]) { LRUCache cacheDesign(2); Trie myTrie; myTrie.insert("apple"); myTrie.search("apple"); myTrie.search("app"); myTrie.startsWith("app"); myTrie.insert("app"); myTrie.search("app"); return 0; } #endif //高级算法-数学 #if false int Larger(int a, int b) { string s1 = to_string(a); string s2 = to_string(b); return (s1 + s2) > (s2 + s1); } class Solution { public: string largestNumber(vector<int>& nums) {//最大数 size_t numsLen = nums.size(); string res; if (numsLen == 0) { return res; } if (numsLen == 1) { return to_string(nums[0]); } sort(nums.begin(), nums.end(), Larger);//将函数作为参数 if (nums[0] == 0) { return "0"; } for (size_t i = 0; i < numsLen; i++) { res += to_string(nums[i]); } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<int> nums = { 3,30,34,5,9 }; mySolution.largestNumber(nums); return 0; } #endif //高级算法-其他 #if false int compare(vector<int>& a, vector<int>& b) { return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]); } class Solution { public: vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { size_t peopleCnt = people.size(); sort(people.begin(), people.end(), compare); vector<vector<int>> res(peopleCnt); for (auto& it : people) { int blnk = it[1] + 1; for (size_t i = 0; i < peopleCnt; i++) { if (res[i].empty()) { blnk--; if (blnk == 0) { res[i] = it; break; } } } } return res; } int trapBrutal(vector<int>& height) {//从低到高灌水超时 size_t heitCnt = height.size(); if (heitCnt < 3) { return 0; } int res = 0; int currentHeit = height[0]; int maxVal = -1, minVal = 65535; for (size_t i = 0; i < heitCnt; i++) { maxVal = max(height[i], maxVal); minVal = min(height[i], minVal); } size_t left = 0, right = heitCnt - 1; for (size_t i = minVal; i <= maxVal; i++) { while (height[left] < i) { left++; } while (height[right] < i) { right--; } for (size_t j = left; j <= right; j++) { if (height[j] < i) { height[j]++; res++; } } } return res; } int trapDualPointer(vector<int>& height) {//双指针 size_t heitCnt = height.size(); if (heitCnt < 3) { return 0; } int res = 0; size_t leftCur = 0, rightCur = heitCnt - 1; while (leftCur < rightCur) { int heit = min(height[leftCur], height[rightCur]); for (size_t i = leftCur + 1; i < rightCur; i++) { if (height[i] < heit) { res += heit - height[i]; height[i] = heit; } } if (height[leftCur] <= height[rightCur]) { leftCur++; } else { rightCur--; } } return res; } int trap(vector<int>& height) {//动态规划接雨水 size_t heitCnt = height.size(); if (heitCnt < 3) { return 0; } int res = 0; vector<int> left(heitCnt), right(heitCnt); int currentLeft = height[0], currentRight = height[heitCnt - 1]; for (size_t i = 0; i < heitCnt; i++) { if (height[i] > currentLeft) { currentLeft = height[i]; } left[i] = currentLeft; if (height[heitCnt - i - 1] > currentRight) { currentRight = height[heitCnt - i - 1]; } right[heitCnt - i - 1] = currentRight; } for (size_t i = 0; i < heitCnt; i++) { res += min(left[i], right[i]) - height[i]; } return res; } vector<vector<int>> getSkyline(vector<vector<int>>& buildings) { vector<vector<int>> res; multiset<pair<int, int>> all;//自动排序可重复 for (vector<int>& building : buildings) { all.insert(make_pair(building[0], -building[2])); all.insert(make_pair(building[1], building[2])); } multiset<int> height({ 0 });//保持一个默认值,防止暴雷 vector<int> last(2); for (auto& it : all) { if (it.second < 0) { height.insert(-it.second); } else { height.erase(height.find(it.second)); } auto maxHeight = *height.rbegin(); if (last[1] != maxHeight) { last[0] = it.first; last[1] = maxHeight; res.push_back(last); } } return res; } int largestRectangleArea(vector<int>& heights) { size_t heitCnt = heights.size(); if (heitCnt == 1) { return heights[0]; } stack<int> stk; int res = 0; for (size_t i = 0; i < heitCnt; i++) { while (!stk.empty() && heights[stk.top()] > heights[i]) { int ht = heights[stk.top()]; stk.pop(); int len = i; if (!stk.empty()) { len = i - stk.top() - 1; } res = max(res, len * ht); } stk.push(i); } while (!stk.empty()) { int ht = heights[stk.top()]; stk.pop(); int len = heitCnt; if (!stk.empty()) { len = heitCnt - stk.top() - 1; } res = max(res, len * ht); } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<vector<int>> buildings = { {2,9,10}, {3,7,15}, {5,12,12}, {15,20,10}, {19,24,8} }; vector<int> heit1 = { 2,1,5,6,2,3 }; vector<int> heit2 = { 0,1,0,2,1,0,1,3,2,1,2,1 }; mySolution.largestRectangleArea(heit1); return 0; } #endif //目标和-补充 #if false class Solution { public: int findTargetSumWays(vector<int>& nums, int S) {//目标和--动态规划 size_t numsLen = nums.size(); vector<vector<int>> dp(numsLen, vector<int>(2001));//dp[i][j]:前i个数和为j的方案数 dp[0][1000 + nums[0]] = 1; dp[0][1000 - nums[0]] += 1; for (size_t i = 1; i < numsLen; i++) { for (int j = 0; j < 2001; j++) { int tmpMinus = j - nums[i] >= 0 ? dp[i - 1][j - nums[i]] : 0; int tmpPosit = j + nums[i] < 2001 ? dp[i - 1][j + nums[i]] : 0; dp[i][j] = tmpMinus + tmpPosit; } } return S > 1000 || S < -1000 ? 0 : dp[numsLen - 1][S + 1000]; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<int> nums = { 1, 999 }; mySolution.findTargetSumWays(nums, 998); return 0; } #endif //面试问题 #if false class Solution { public: int superEggDrop(int K, int N) {//鸡蛋掉落 if (N == 1) { return 1; } vector<vector<int>> dp(N + 1, vector<int>(K + 1));//抛i次, j个鸡蛋能确定的最高楼层 for (size_t i = 1; i <= K; i++) { dp[1][i] = 1; } int ans = -1; for (size_t i = 2; i <= N; i++) { for (size_t j = 1; j <= K; j++) { dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] + 1; } if (dp[i][K] >= N) { ans = i; break; } } return ans; } int longestSubstring(string s, int k) { size_t sLen = s.size(); unordered_map<char, int> sMap; for (char& ch : s) { sMap[ch]++; } vector<int> split; for (size_t i = 0; i < sLen; i++) { if (sMap[s[i]] < k) { split.push_back(i); } } split.push_back(sLen); size_t splitLen = split.size(); if (splitLen == 1) { return sLen; } int ans = 0, left = 0; for (size_t i = 0; i < splitLen; i++) { int len = split[i] - left; if (len > ans) { ans = max(ans, longestSubstring(s.substr(left, len), k)); } left = split[i] + 1; } return ans; } int longestSubstring2(string s, int k) { unordered_map<char, int> umap; for (auto c : s) umap[c]++; vector<int> split; for (int i = 0; i < s.size(); i++) { if (umap[s[i]] < k) split.push_back(i); } if (split.size() == 0) return s.length(); int ans = 0, left = 0; split.push_back(s.length()); for (int i = 0; i < split.size(); i++) { int len = split[i] - left; if (len > ans) ans = max(ans, longestSubstring2(s.substr(left, len), k)); left = split[i] + 1; } return ans; } int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {//加油站-贪心 size_t gasCnt = gas.size(); int minVal = INT_MAX; int res = 0; int spareGas = 0; for (size_t i = 0; i < gasCnt; i++) {//剩余油量折线图在平面上下左右平移 spareGas += gas[i] - cost[i]; if (spareGas < minVal) { res = i; minVal = spareGas; } } return spareGas < 0 ? -1 : (res + 1) % gasCnt; } }; int main(int argc, char* argv[]) { Solution mySolution; string s = "weitong"; vector<int> gas = { 1,2,3,4,5 }; vector<int> cost = { 3,4,5,1,2 }; mySolution.canCompleteCircuit(gas, cost); return 0; } #endif //cookBook-数组 #if false class Solution { public: int threeSumClosest(vector<int>& nums, int target) {//最接近的三数之和 size_t numsLen = nums.size(); sort(nums.begin(), nums.end()); int diff = INT_MAX; int res = -1; for (size_t i = 0; i < numsLen; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } size_t leftCur = i + 1, rightCur = numsLen - 1; while (leftCur < rightCur) { int sum = nums[i] + nums[leftCur] + nums[rightCur]; if (sum == target) { return target; } if (abs(sum - target) < diff) { diff = abs(sum - target); res = sum; } if (sum > target) { size_t rightCurBak = rightCur - 1; while (rightCurBak > leftCur && nums[rightCur] == nums[rightCurBak]) { rightCurBak--; } rightCur = rightCurBak; } else { size_t leftCurBak = leftCur + 1; while (leftCurBak < rightCur && nums[leftCur] == nums[leftCurBak]) { leftCurBak++; } leftCur = leftCurBak; } } } return res; } vector<vector<int>> combinationSum(vector<int>& candidates, int target) {//组合总和--回溯 sort(candidates.begin(), candidates.end()); size_t candLen = candidates.size(); vector<int> tmp; vector<vector<int>> res; dfs1(res, candidates, 0, tmp, target, candLen); return res; } void dfs1(vector<vector<int>>& res, vector<int>& candidates, int cur, vector<int>& combine, int target, size_t candLen) { if (cur == candLen) { return; } if (target == 0) { res.emplace_back(combine); return; } dfs1(res, candidates, cur + 1, combine, target, candLen);//不取当前的 if (target - candidates[cur] >= 0) { combine.emplace_back(candidates[cur]); dfs1(res, candidates, cur, combine, target - candidates[cur], candLen); combine.pop_back(); } return; } //与上一题一样,有重复元素, 结果不允许重复 vector<pair<int, int>> freq; vector<vector<int>> res; vector<int> tmp; vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); for (int& num : candidates) { if (freq.empty() || freq.back().first != num) { freq.push_back(make_pair(num, 1)); } else { freq.back().second++; } } size_t freqLen = freq.size(); dfs2(0, freqLen, target); return res; } void dfs2(size_t pos, size_t freqLen, int target) { if (target == 0) { res.push_back(tmp); return; } if (pos == freqLen || freq[pos].first > target) { return; } dfs2(pos + 1, freqLen, target); int most = min(target / freq[pos].first, freq[pos].second) + 1;//重复数量上限 for (size_t i = 1; i < most; i++) { tmp.push_back(freq[pos].first); dfs2(pos + 1, freqLen, target - i * freq[pos].first); } for (size_t i = 1; i < most; i++) { tmp.pop_back(); } return; } vector<vector<int>> generateMatrix(int n) {//螺旋矩阵输出 vector<vector<int>> res(n, vector<int>(n)); int start = 1; for (size_t i = 0; i < n / 2; i++) { start = buildMatrix(i, n, start, res); } if (n % 2 == 1) { res[n / 2][n / 2] = start; } return res; } int buildMatrix(size_t cur, size_t dim, int begin, vector<vector<int>>& res) { for (size_t i = cur; i < dim - cur - 1; i++) { res[cur][i] = begin++; } for (size_t i = cur; i < dim - cur - 1; i++) { res[i][dim - cur - 1] = begin++; } for (size_t i = dim - cur - 1; i > cur; i--) { res[dim - cur - 1][i] = begin++; } for (size_t i = dim - cur - 1; i > cur; i--) { res[i][cur] = begin++; } return begin; } int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {//不同路径 II--动态规划 size_t col = obstacleGrid.size(), rol = obstacleGrid[0].size(); for (size_t i = 0; i < col; i++) { for (size_t j = 0; j < rol; j++) { if (obstacleGrid[i][j] == 1) { obstacleGrid[i][j] = -1; } } } for (size_t i = 0; i < col; i++) { if (obstacleGrid[i][0] == -1) { break; } obstacleGrid[i][0] = 1; } for (size_t j = 0; j < rol; j++) { if (obstacleGrid[0][j] == -1) { break; } obstacleGrid[0][j] = 1; } for (size_t i = 1; i < col; i++) { for (size_t j = 1; j < rol; j++) { if (obstacleGrid[i][j] == -1) { continue; } int op1 = obstacleGrid[i - 1][j] == -1 ? 0 : obstacleGrid[i - 1][j]; int op2 = obstacleGrid[i][j - 1] == -1 ? 0 : obstacleGrid[i][j - 1]; obstacleGrid[i][j] = op1 + op2; } } return obstacleGrid[col - 1][rol - 1] == -1 ? 0 : obstacleGrid[col - 1][rol - 1]; } int minPathSum(vector<vector<int>>& grid) {//最小路径和 size_t col = grid.size(), rol = grid[0].size(); for (size_t i = 1; i < col; i++) { grid[i][0] += grid[i - 1][0]; } for (size_t i = 1; i < rol; i++) { grid[0][i] += grid[0][i - 1]; } for (size_t i = 1; i < col; i++) { for (size_t j = 1; j < rol; j++) { grid[i][j] += min(grid[i][j - 1], grid[i - 1][j]); } } return grid[col - 1][rol - 1]; } bool searchMatrix(vector<vector<int>>& matrix, int target) {//搜索二维矩阵, 二分法 size_t col = matrix.size(); if (col == 0) { return false; } size_t rol = matrix[0].size(); int left = 0, right = col * rol - 1; while (left <= right) { int mid = left + (right - left) / 2; int val = matrix[mid / rol][mid % rol]; if (val == target) { return true; } else if (val > target) { right = mid - 1; } else { left = mid + 1; } } return false; } bool search(vector<int>& nums, int target) {//搜索旋转排序数组 II--二分法 int numsLen = nums.size(); int pivot = 0; for (int i = 1; i < numsLen; i++) { if (nums[i - 1] > nums[i]) { pivot = i - 1; break; } } int left = 0, right = pivot; while (left <= right) { int mid = left + (right - left) / 2; int val = nums[mid]; if (val == target) { return true; } else if (val > target) { right = mid - 1; } else { left = mid + 1; } } left = pivot + 1; right = numsLen - 1; while (left <= right) { int mid = left + (right - left) / 2; int val = nums[mid]; if (val == target) { return true; } else if (val > target) { right = mid - 1; } else { left = mid + 1; } } return false; } vector<vector<int>> subsetsWithDup(vector<int>& nums) {//子集 II--位操作 sort(nums.begin(), nums.end()); size_t numsLen = nums.size(); size_t curReg = 1 << numsLen;//表 vector<int> tmp; vector<vector<int>> res; for (size_t i = 0; i < curReg; i++) { tmp.clear(); bool flag = true; for (size_t j = 0; j < numsLen; j++) { if (i & (1 << j)) {//取每一位 if (j != 0 && nums[j] == nums[j - 1] && ((i & (1 << (j - 1))) == 0)) {//确保取的是100,110,111这种 flag = false; break; } tmp.push_back(nums[j]); } } if (flag) { res.push_back(tmp); } } return res; } int minimumTotal(vector<vector<int>>& triangle) {//三角形最小路径和--dp size_t triStep = triangle.size(); for (size_t i = 1; i < triStep; i++) { triangle[i][0] += triangle[i - 1][0]; triangle[i][i] += triangle[i - 1][i - 1]; for (size_t j = 1; j < i; j++) { triangle[i][j] += min(triangle[i - 1][j], triangle[i - 1][j - 1]); } } int res = INT_MAX; for (size_t i = 0; i < triStep; i++) { res = min(res, triangle[triStep - 1][i]); } return res; } vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {//单词接龙 II--BFS int id = 0; size_t sLen = wordList[0].size(); size_t wordCnt = wordList.size(); for (string& str : wordList) { if (nodeMap.count(str) < 1) {//入库并分配ID nodeMap[str] = id++; idWord.push_back(str); } } if (nodeMap.count(endWord) < 1) { return {}; } if (nodeMap.count(beginWord) < 1) { nodeMap[beginWord] = id++; idWord.push_back(beginWord); } //添加边 edges.resize(idWord.size()); for (size_t i = 0; i < id; i++) { for (size_t j = i + 1; j < id; j++) { if (checkSibil(idWord[i], idWord[j], sLen)) { edges[i].push_back(j); edges[j].push_back(i); } } } int endID = nodeMap[endWord]; vector<vector<string>> res; queue<vector<int>> q; vector<int> cost(id, 1 << 10); q.push(vector<int>{nodeMap[beginWord]});//挤一个进去,开始ID cost[nodeMap[beginWord]] = 0;//储存begin变换到位所需次数 while (!q.empty()) { vector<int> current = q.front(); q.pop(); int last = current.back(); if (last == endID) {//跳到了就没必要往下跳了 vector<string> tmp;//结果 for (int index : current) { tmp.push_back(idWord[index]); } res.push_back(tmp); } else { size_t lastSize = edges[last].size(); for (size_t i = 0; i < lastSize; i++) {//只有找到了更近的距离,cost才会更新 int to = edges[last][i]; if (cost[last] + 1 <= cost[to]) { cost[to] = cost[last] + 1; vector<int> tmp(current);//保存整个过程ID tmp.push_back(to); q.push(tmp); } } } } return res; } bool checkSibil(string& str1, string& str2, size_t sLen) { int diff = 0; for (size_t i = 0; i < sLen && diff < 2; i++) { if (str1[i] != str2[i]) { diff++; } } return diff == 1; } unordered_map<string, int> nodeMap; vector<string> idWord; vector<vector<int>> edges; vector<vector<int>> combinationSum3(int k, int n) {//组合总和 III vector<vector<int>> res; vector<int> tmp; combinationSum3DFS(1, 9, k, n, res, tmp);//当前枚举,枚举上限,数量,总和 return res; } void combinationSum3DFS(int cur, int n, int k, int sum, vector<vector<int>>& res, vector<int>& tmp) { if (tmp.size() + (n - cur + 1) < k || tmp.size() > k) {//数量不够或数量多了 return; } if (tmp.size() == k && accumulate(tmp.begin(), tmp.end(), 0) == sum) { res.push_back(tmp); return; } tmp.push_back(cur); combinationSum3DFS(cur + 1, n, k, sum, res, tmp); tmp.pop_back(); combinationSum3DFS(cur + 1, n, k, sum, res, tmp); return; } vector<int> majorityElement(vector<int>& nums) {//求众数 II--投票法 int num1 = -1, num2 = -1; int num1Cnt = 0, num2Cnt = 0; for (int& num : nums) { if (num == num1) { num1Cnt++; } else if (num == num2) { num2Cnt++; } else if (num1Cnt == 0) { num1 = num; num1Cnt++; } else if (num2Cnt == 0) { num2 = num; num2Cnt++; } else { num1Cnt--; num2Cnt--; } } vector<int> res; num1Cnt = 0; num2Cnt = 0; for (int& num : nums) { if (num == num1) { num1Cnt++; } else if (num == num2) { num2Cnt++; } } if (num1Cnt > nums.size() / 3) { res.push_back(num1); } if (num2Cnt > nums.size() / 3) { res.push_back(num2); } return res; } int thirdMax(vector<int>& nums) {//第三大的数 int max3 = INT_MIN, max2 = INT_MIN, max1 = INT_MIN; int tmp1 = nums[0], tmp2 = nums[0], tmp3 = nums[0]; for (int& num : nums) { if (num != tmp1) {//得到3个不同的数 if (tmp1 != tmp2) { tmp3 = num; } else { tmp2 = num; } } if (num == max1 || num == max2 || num == max3) { continue; } if (num > max1) { max3 = max2; max2 = max1; max1 = num; } else if (num > max2) { max3 = max2; max2 = num; } else if (num > max3) { max3 = num; } } if (tmp1 == tmp2 || tmp2 == tmp3 || tmp1 == tmp3) { return max1; } return max3; } vector<int> findDisappearedNumbers(vector<int>& nums) {//找到所有数组中消失的数字 size_t numsLen = nums.size(); for (size_t i = 0; i < numsLen; i++) { int cur = abs(nums[i]) - 1; nums[cur] = -abs(nums[cur]); } vector<int> res; for (int i = 0; i < numsLen; i++) { if (nums[i] > 0) { res.push_back(i + 1); } } return res; } bool circularArrayLoop(vector<int>& nums) {//环形数组循环 const size_t numsLen = nums.size(); for (int i = 0; i < numsLen; i++) { if (nums[i] == 0) { continue; } int dir = nums[i] > 0 ? 1 : -1; if (circularArrayLoopDFS(nums, i, numsLen, dir)) { return true; } } return false; } bool circularArrayLoopDFS(vector<int>& nums, int i, int numsLen, int dir) { if (nums[i] == 0) {// return false; } if (nums[i] == INT_MAX) {//形成闭环 return true; } int ndir = nums[i] > 0 ? 1 : -1; if (ndir == dir) { int j = (numsLen + (nums[i] + i) % numsLen) % numsLen; nums[i] = INT_MAX;//考察过程中 if (j != i && circularArrayLoopDFS(nums, j, numsLen, dir)) { return true; } else { nums[i] = 0;//确定不符合条件不能成环 return false; } } return false; } int islandPerimeterBFS(vector<vector<int>>& grid) {//岛屿的周长--BFS size_t col = grid.size(); if (col == 0) { return 0; } size_t rol = grid[0].size(); queue<pair<int, int>> q; for (size_t i = 0; i < col; i++) { for (size_t j = 0; j < rol; j++) { if (grid[i][j] == 1) { q.push(make_pair(i, j));//从一个角开始 break; } } if (!q.empty()) { break; } } int res = 0; vector<vector<int>> dir = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; while (!q.empty()) { int colCur = q.front().first; int rolCur = q.front().second; q.pop(); int remain = 4; if (grid[colCur][rolCur] == 2) { continue; } grid[colCur][rolCur] = 2; for (size_t i = 0; i < 4; i++) { int tmpCol = colCur + dir[i][0]; int tmpRol = rolCur + dir[i][1]; if (tmpCol < 0 || tmpCol >= col || tmpRol < 0 || tmpRol >= rol) { continue; } if (grid[tmpCol][tmpRol] == 2) { remain--; continue; } if (grid[tmpCol][tmpRol] == 1) { remain--; q.push(make_pair(tmpCol, tmpRol)); } } res += remain; } return res; } int islandPerimeter(vector<vector<int>>& grid) {//岛屿的周长--暴力法 size_t col = grid.size(); if (col == 0) { return 0; } size_t rol = grid[0].size(); int res = 0; vector<vector<int>> dir = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; for (int i = 0; i < col; i++) { for (int j = 0; j < rol; j++) { if (grid[i][j] == 1) { int remain = 4; for (size_t k = 0; k < 4; k++) { int tmpCol = i + dir[k][0]; int tmpRol = j + dir[k][1]; if (tmpCol < 0 || tmpCol >= col || tmpRol < 0 || tmpRol >= rol) { continue; } if (grid[tmpCol][tmpRol] == 2) { remain--; continue; } if (grid[tmpCol][tmpRol] == 1) { remain--; } } res += remain; } } } return res; } int findPairs(vector<int>& nums, int k) {//数组中的 k-diff 数对 unordered_map<int, int> numMap; for (int& num : nums) { numMap[num]++; } int res = 0; if (k != 0) { for (auto& it : numMap) { if (numMap.count(it.first + k) > 0) { res++; } } } else { for (auto& it : numMap) { if (it.second > 1) { res++; } } } return res; } vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {//重塑矩阵 size_t rol = nums.size(); if (rol == 0) { return nums; } size_t col = nums[0].size(); if (c >= col && r >= rol) { return nums; } vector<vector<int>> res(r, vector<int>(c)); size_t total = col * rol; for (size_t i = 0; i < total; i++) { res[i / c][i % c] = nums[i / col][i % col]; } return res; } int maximumProductBak(vector<int>& nums) {//三个数的最大乘积--暴力排序 sort(nums.begin(), nums.end()); size_t numsLen = nums.size(); return max(nums[0] * nums[1] * nums[numsLen - 1], nums[numsLen - 1] * nums[numsLen - 2] * nums[numsLen - 3]); } int maximumProduct(vector<int>& nums) {//三个数的最大乘积--维护3个最大值和两个最小值 int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; int min1 = INT_MAX, min2 = INT_MAX; for (int& num : nums) { if (num > max1) { max3 = max2; max2 = max1; max1 = num; } else if (num > max2) { max3 = max2; max2 = num; } else if (num > max3) { max3 = num; } if (num < min1) { min2 = min1; min1 = num; } else if (num < min2) { min2 = num; } } return max(max1 * max2 * max3, max1 * min1 * min2); } vector<vector<int>> imageSmoother(vector<vector<int>>& M) {//图片平滑器(卷积核)--可以优化,分区处理,不处理了 size_t rol = M.size(); if (rol == 0) { return M; } size_t col = M[0].size(); vector<vector<int>> res(M); for (int i = 0; i < rol; i++) { for (int j = 0; j < col; j++) { int core = 0; int cnt = 0; for (int tmpRol = i - 1; tmpRol < i + 2; tmpRol++) { for (int tmpCol = j - 1; tmpCol < j + 2; tmpCol++) { if (tmpRol < 0 || tmpRol >= rol || tmpCol < 0 || tmpCol >= col) { continue; } core += M[tmpRol][tmpCol]; cnt++; } } res[i][j] = core / cnt; } } return res; } int maxAreaOfIsland(vector<vector<int>>& grid) { int rol = grid.size(); if (rol == 0) { return 0; } int col = grid[0].size(); int res = 0; for (size_t i = 0; i < rol; i++) { for (size_t j = 0; j < col; j++) { res = max(res, maxAreaOfIslandBFS(grid, i, j, rol, col)); } } return res; } vector<vector<int>> dir = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; int maxAreaOfIslandBFS(vector<vector<int>>& grid, int rolCur, int colCur, int rol, int col) { if (grid[rolCur][colCur] == 2 || grid[rolCur][colCur] == 0) { return 0; } int res = 0; queue<pair<int, int>> q; q.push(make_pair(rolCur, colCur)); while (!q.empty()) { rolCur = q.front().first; colCur = q.front().second; q.pop(); if (grid[rolCur][colCur] == 2) {//有可能在入队列过程中被其他人访问 continue; } res++; grid[rolCur][colCur] = 2; for (size_t i = 0; i < 4; i++) { int tmpRol = rolCur + dir[i][0]; int tmpCol = colCur + dir[i][1]; if (tmpRol < 0 || tmpRol >= rol || tmpCol < 0 || tmpCol >= col) { continue; } if (grid[tmpRol][tmpCol] == 1) { q.push(make_pair(tmpRol, tmpCol)); } } } return res; } int findShortestSubArray(vector<int>& nums) {//数组的度 unordered_map<int, int> numMap; for (int& num : nums) { numMap[num]++; } int cnt = 0; vector<int> cand; for (auto& it : numMap) { if (it.second > cnt) { cand.clear(); cnt = it.second; } if (it.second == cnt) { cand.push_back(it.first); } } int res = INT_MAX; size_t numsLenLim = nums.size() - 1; for (int& it : cand) { size_t left = 0, right = numsLenLim; while (nums[left] != it) { left++; } while (nums[right] != it) { right--; } int current = right - left + 1; res = min(res, current); } return res; } int numSubarrayProductLessThanKBAK(vector<int>& nums, int k) {//乘积小于K的子数组--动态规划n^2 size_t numsLen = nums.size(); vector<vector<int>> dp(numsLen, vector<int>(numsLen, k)); for (size_t i = 0; i < numsLen; i++) { if (nums[i] < k) { dp[i][i] = nums[i]; } } for (size_t i = 0; i < numsLen; i++) { for (size_t j = i + 1; j < numsLen; j++) { if (dp[i][j - 1] > k) {//剪枝 break; } dp[i][j] = dp[i][j - 1] * dp[j][j]; } } int res = 0; for (size_t i = 0; i < numsLen; i++) { for (size_t j = i; j < numsLen; j++) { res += dp[i][j] < k ? 1 : 0; } } return res; } int numSubarrayProductLessThanK(vector<int>& nums, int k) {//双指针 if (k < 2) { return 0; } size_t numsLen = nums.size(); int tmp = 1, res = 0; size_t left = 0; for (size_t right = 0; right < numsLen; right++) { tmp *= nums[right]; while (tmp >= k) { tmp /= nums[left++]; } res += right - left + 1;//右到左相乘的都小于 } return res; } int maxProfitBAK(vector<int>& prices, int fee) {//买卖股票的最佳时机含手续费--动态规划 size_t pricesCnt = prices.size(); vector<vector<int>> dp(2, vector<int>(pricesCnt));//当天只有两种操作,买入和卖出 //只有交易时才会计算价值变动 dp[0][0] = 0;//没有股票收益 dp[1][0] = -prices[0];//持有股票收益 for (size_t i = 1; i < pricesCnt; i++) { dp[0][i] = max(dp[0][i - 1], dp[1][i - 1] + prices[i] - fee); dp[1][i] = max(dp[0][i - 1] - prices[i], dp[1][i - 1]); } return dp[0][pricesCnt - 1]; } int maxProfit(vector<int>& prices, int fee) {//买卖股票的最佳时机含手续费--动态规划--空间优化 size_t pricesCnt = prices.size(); //当天只有两种操作,买入和卖出 //只有交易时才会计算价值变动 int noStock = 0;//没有股票收益 int haveStock = -prices[0];//持有股票收益 for (size_t i = 1; i < pricesCnt; i++) { int noStockBak = noStock; int haveStockBak = haveStock; noStock = max(noStockBak, haveStockBak + prices[i] - fee); haveStock = max(noStockBak - prices[i], haveStockBak); } return noStock; } bool isOneBitCharacter(vector<int>& bits) {//1比特与2比特字符,跳位 size_t bitsCnt = bits.size(); size_t cur = 0; while (cur < bitsCnt - 1) { if (bits[cur] == 1) { cur++; } cur++; } return cur == bitsCnt - 1; } int minCostClimbingStairs(vector<int>& cost) {//使用最小花费爬楼梯--动态规划 size_t costCnt = cost.size(); int dp_1 = 0; int dp_2 = 0; int dp = 0; for (size_t i = 2; i <= costCnt; i++) { dp = min(dp_1 + cost[i - 1], dp_2 + cost[i - 2]); dp_2 = dp_1; dp_1 = dp; } return dp; } bool isToeplitzMatrix(vector<vector<int>>& matrix) {//托普利茨矩阵 size_t rol = matrix.size(); size_t col = matrix[0].size(); size_t limL = min(rol, col); size_t limU = max(rol, col); for (size_t i = 0; i < rol; i++) { if (!exploreThis(matrix, i, 0, rol, col)) {//验证竖着的 return false; } } for (size_t i = 1; i < col; i++) { if (!exploreThis(matrix, 0, i, rol, col)) {//验证横着的 return false; } } return true; } bool exploreThis(vector<vector<int>>& matrix, size_t rolCur, size_t colCur, size_t rol, size_t col) { int target = matrix[rolCur][colCur]; while (rolCur < rol && colCur < col) { if (matrix[rolCur][colCur] != target) { return false; } rolCur++; colCur++; } return true; } vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {//翻转图像 int rol = A.size(); int col = A[0].size(); for (int i = 0; i < rol; i++) { int left = 0, right = col - 1; while (left <= right) { if (A[i][left] == A[i][right]) { A[i][left] = A[i][left] == 0; A[i][right] = A[i][left]; } left++; right--; } } return A; } vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {//公平的糖果交换 unordered_set<int> ASet, BSet; int ASum = 0, BSum = 0; for (int& num : A) { ASet.emplace(num); ASum += num; } for (int& num : B) { BSet.emplace(num); BSum += num; } int target = (ASum - BSum) / 2; vector<int> res(2); for (const int& num : ASet) { if (BSet.count(num - target)) { res[0] = num; res[1] = num - target; break; } } return res; } int sumSubseqWidths(vector<int>& nums) {//子序列宽度之和 sort(nums.begin(), nums.end());//排序不改变结果 //A[i]是左侧2^i个区间的右边界,右侧2^N-i-1个左边界,右边界贡献为正,左边界贡献为负 size_t numsLen = nums.size(); size_t left = 0, right = 1; int res = 0; vector<long> pow2(numsLen); pow2[0] = 1; for (size_t i = 1; i < numsLen; i++) { pow2[i] = pow2[i - 1] * 2 % 1000000007; } for (size_t i = 0; i < numsLen; i++) { res = (res + nums[i] * (pow2[i] - pow2[numsLen - i - 1])) % 1000000007; } return res; } bool isMonotonic(vector<int>& nums) {//单调数列 size_t numsLen = nums.size(); if (numsLen < 2) {//单个元素 return true; } size_t i = 1; while (i < numsLen&& nums[i] == nums[i - 1]) {//去除开头重复 i++; } if (i == numsLen) {//全相等 return true; } bool grater = nums[i] > nums[i - 1]; while (i < numsLen) {//主业务 if (nums[i] == nums[i - 1]) { i++; continue; } if (grater ^ (nums[i] > nums[i - 1])) { return false; } i++; } return true; } int sumSubarrayMins(vector<int>& nums) {//子数组的最小值之和 int numsLen = nums.size(); vector<int> left(numsLen), right(numsLen);//最小值区间下标 for (int i = 0; i < numsLen; i++) { left[i] = right[i] = i; } stack<int> stk; for (int i = numsLen - 1; i > -1; i--) { while (!stk.empty() && nums[stk.top()] >= nums[i]) { right[i] = right[stk.top()]; stk.pop(); } stk.push(i); } while (!stk.empty()) { stk.pop(); } for (int i = 0; i < numsLen; i++) { while (!stk.empty() && nums[stk.top()] > nums[i]) { left[i] = left[stk.top()]; stk.pop(); } stk.push(i); } int res = 0; for (int i = 0; i < numsLen; i++) { res = (res + 1LL * (i - left[i] + 1) * (right[i] - i + 1) * nums[i]) % 1000000007; } return res; } bool hasGroupsSizeX(vector<int>& deck) { unordered_map<int, int> cardSet; int minCnt = INT_MAX; for (int& card : deck) { cardSet[card]++; } int g = 0; for (auto& it : cardSet) { if (g != 0) { g = gcd(g, it.second); } else { g = it.second; } } return g > 1; } inline int gcd(int a, int b) {//求最大公约数 int r; while (b > 0) { r = a % b; a = b; b = r; } return a; } int maxSubarraySumCircularBAK(vector<int>& A) {//环形子数组的最大和--暴力动态规划--超时 vector<int> B(A); vector<int> dp(A); size_t numsLen = A.size(); A.insert(A.end(), B.begin(), B.end()); int res = INT_MIN; for (size_t i = 0; i < numsLen; i++) { size_t lim = i + numsLen; int current = A[i]; int last = A[i]; for (size_t cur = i + 1; cur < lim; cur++) { current = max(A[cur], A[cur] + current); last = max(last, current); } dp[i] = max(current, last); } for (int& num : dp) { res = max(res, num); } return res; } int maxSubarraySumCircular(vector<int>& A) {//环形子数组的最大和 int maxVal = A.front(), currentMax = A.front(), minVal = A.front(), currentMin = A.front(), sum = A.front(); size_t numsLen = A.size(); for (size_t i = 1; i < numsLen; i++) {//最大和最小子列和 currentMax = max(A[i], currentMax + A[i]); maxVal = max(maxVal, currentMax); currentMin = min(A[i], currentMin + A[i]); minVal = min(minVal, currentMin); sum += A[i]; } if (sum == minVal) { return maxVal; } return max(maxVal, sum - minVal); } vector<int> sortArrayByParityII(vector<int>& nums) {//按奇偶排序数组 II size_t numsLen = nums.size(); size_t eveCur = 0, oddCur = 1; vector<int> res(nums); for (size_t i = 0; i < numsLen; i++) { if (nums[i] % 2 == 0) { res[eveCur] = nums[i]; eveCur += 2; } else { res[oddCur] = nums[i]; oddCur += 2; } } return res; } vector<int> sortedSquares(vector<int>& nums) {//有序数组的平方 vector<int> res; int aproixZeroCur = 0; int numsLen = nums.size(); for (int i = 0; i < numsLen; i++) { if (abs(nums[i]) > abs(nums[aproixZeroCur])) { break; } else { aproixZeroCur = i; } } res.push_back(nums[aproixZeroCur] * nums[aproixZeroCur]); int left = aproixZeroCur - 1, right = aproixZeroCur + 1; while (left > -1 || right < numsLen) { if (left == -1) { res.push_back(nums[right] * nums[right]); right++; continue; } if (right == numsLen) { res.push_back(nums[left] * nums[left]); left--; continue; } int minVal; if (abs(nums[left]) < abs(nums[right])) { minVal = abs(nums[left]); left--; } else { minVal = abs(nums[right]); right++; } res.push_back(minVal * minVal); } return res; } vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) {//查询后的偶数和 int sum = 0; for (int& num : A) { if (num % 2 == 0) { sum += num; } } vector<int> res; for (vector<int>& qur : queries) { int val = qur[0]; size_t index = qur[1]; if (A[index] % 2 != 0) {//未改变前为奇数 if (val % 2 != 0) {//改完变成偶数 A[index] += val; sum += A[index]; } else {//改完还是奇数 A[index] += val; } } else {//未改变前是偶数 if (val % 2 != 0) {//改完变奇数了 sum -= A[index]; A[index] += val; } else {//改完还是偶数 sum += val; A[index] += val; } } res.push_back(sum); } return res; } int numRookCaptures(vector<vector<char>>& board) {//可以被一步捕获的棋子数 int res = 0; int rol = 0, col = 0; bool done = false; for (int i = 0; i < 8; i++) {//找车 for (int j = 0; j < 8; j++) { if (board[i][j] == 'R') { done = true; rol = i; col = j; break; } } if (done) { break; } } int tmpRol = rol; while (tmpRol < 8) { if (board[tmpRol][col] == 'B') { break; } if (board[tmpRol][col] == 'p') { res++; break; } tmpRol++; } tmpRol = rol; while (tmpRol > -1) { if (board[tmpRol][col] == 'B') { break; } if (board[tmpRol][col] == 'p') { res++; break; } tmpRol--; } int tmpCol = col; while (tmpCol < 8) { if (board[rol][tmpCol] == 'B') { break; } if (board[rol][tmpCol] == 'p') { res++; break; } tmpCol++; } tmpCol = col; while (tmpCol > -1) { if (board[rol][tmpCol] == 'B') { break; } if (board[rol][tmpCol] == 'p') { res++; break; } tmpCol--; } return res; } int maxTurbulenceSize(vector<int>& nums) {//最长湍流子数组 size_t numsLen = nums.size(); vector<int> dp(numsLen); dp[0] = 0; for (size_t i = 1; i < numsLen; i++) { if (nums[i - 1] < nums[i]) { dp[i] = 1; } if (nums[i - 1] > nums[i]) { dp[i] = -1; } } int res = 0; int current = 0; for (size_t i = 0; i < numsLen; i++) { if (dp[i] == 0) { current = 1; } else if (dp[i] == -dp[i - 1] || dp[i - 1] == 0) { current++; } else { current = 2; } res = max(res, current); } return res; } int threeSumMulti(vector<int>& nums, int target) {//三数之和的多种可能--三指针 sort(nums.begin(), nums.end()); int mod = 1000000007; int res = 0; int numsLen = nums.size(); for (int i = 0; i < numsLen - 2 && nums[i] <= target; i++) { int left = i + 1, right = numsLen - 1; while (nums[left] < nums[right]) {//left,right数不相等 if (nums[i] + nums[left] + nums[right] == target) { int leftBak = left, rightBak = right; while (nums[left] == nums[leftBak]) { left++; } while (nums[right] == nums[rightBak]) { right--; } res += (left - leftBak) * (rightBak - right); res %= mod; } else if (nums[i] + nums[left] + nums[right] < target) { left++; } else { right--; } } if (nums[left] == nums[right] && nums[i] + nums[left] + nums[right] == target) { int d = right - left + 1; res += d * (d - 1) / 2; res %= mod; } } return res; } vector<string> commonChars(vector<string>& A) {//查找常用字符 unordered_map<char, int> charMapA, charMapB; for (char& ch : A[0]) { charMapA[ch]++; } size_t wordCnt = A.size(); for (string& str : A) { charMapB = charMapA; charMapA.clear(); for (char& ch : str) { if (charMapB[ch] > 0) { charMapA[ch]++; charMapB[ch]--; } } } vector<string> res; string tmp; for (auto& it : charMapA) { tmp.clear(); tmp += it.first; while (it.second > 0) { it.second--; res.emplace_back(tmp); } } return res; } int shipWithinDays(vector<int>& weights, int D) {//在 D 天内送达包裹的能力--二分法 //货物必须按照给定的顺序装运 int minLim = 0; int maxLim = 0; for (int& weight : weights) { maxLim += weight; minLim = max(minLim, weight); } int left = minLim, right = maxLim; while (left < right) { int mid = left + (right - left) / 2; if (canShip(weights, D, mid)) { right = mid; } else { left = mid + 1; } } return left; } inline bool canShip(vector<int>& weights, int D, int wLim) { int tmp = 0; for (int& wt : weights) { if (tmp + wt > wLim) { tmp = 0; D--; } if (D == 0) { return false; } tmp += wt; } return true; } int heightChecker(vector<int>& heights) {//高度检查器--桶n,如果使用排序的话是nlogn vector<int> bucket(101, 0); for (int& height : heights) { bucket[height]++;//有序的 } int res = 0; int cnt = 0; for (size_t i = 1; i < 101; i++) { while (bucket[i] > 0) { if (heights[cnt] != i) { res++; } bucket[i]--; cnt++; } } return res; } void duplicateZeros(vector<int>& nums) { size_t numsLen = nums.size(); int cnt = 0; for (size_t i = 0; i < numsLen; i++) { if (nums[i] == 0) { nums.insert(nums.begin() + i, 0); cnt++; i++; } } while (cnt > 0) { nums.pop_back(); cnt--; } return; } int numEquivDominoPairs(vector<vector<int>>& dominoes) {//等价多米诺骨牌对的数量 vector<vector<int>> dominoeMap(11, vector<int>(11, 0)); int res = 0; for (vector<int>& dominoe : dominoes) { if (dominoe[0] <= dominoe[1]) { res += dominoeMap[dominoe[0]][dominoe[1]]++; } else { res += dominoeMap[dominoe[1]][dominoe[0]]++; } } return res; } string dayOfTheWeek(int day, int month, int year) {//一周中的第几天 //首先我们知道1971.1.1是Friday vector<string> weekDayRes = { "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday" }; vector<int> monthDatCnt = { 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; int dayCnt = 0; for (int i = 1971; i < year; i++) { dayCnt += 365; if (isLapYear(i)) { dayCnt++; } } dayCnt += monthDatCnt[month]; if (isLapYear(year) && month > 2) { dayCnt++; } dayCnt += day - 1; return weekDayRes[dayCnt % 7]; } inline bool isLapYear(int year) { if (year % 400 == 0) { return true; } if (year % 100 == 0) { return false; } if (year % 4 == 0) { return true; } return false; } int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {//公交站间的距离 int sum1 = 0; int sum2 = 0; size_t distCnt = distance.size(); size_t lb = min(start, destination); size_t ub = max(start, destination); for (int i = 0; i < distCnt; i++) { sum1 += distance[i]; } for (int i = lb; i < ub; i++) { sum2 += distance[i]; } return min(sum2, sum1 - sum2); } vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {//比较字符串最小字母出现频次 unordered_map<int, int> wordMap; for (string& word : words) { wordMap[getNum(word)]++; } vector<int> res; for (string& qury : queries) { int quryNum = getNum(qury); int cnt = 0; for (auto& it : wordMap) { if (quryNum < it.first) { cnt += it.second; } } res.push_back(cnt); } return res; } inline int getNum(string& str) { char chCur = 'z'; int cnt = 0; for (char& ch : str) { if (ch < chCur) { chCur = ch; cnt = 0; } if (ch == chCur) { cnt++; } } return cnt; } int countCharacters(vector<string>& words, string chars) {//拼写单词 unordered_map<char, int> charMap; for (char& ch : chars) { charMap[ch]++; } int res = 0; for (string& word : words) { unordered_map<char, int> tmp = charMap; bool isCap = true; for (char& ch : word) { if (tmp.count(ch)) { if (tmp[ch] == 0) { isCap = false; break; } tmp[ch]--; } else { isCap = false; break; } } if (isCap) { res += word.size(); } } return res; } vector<vector<int>> minimumAbsDifference(vector<int>& arr) {//最小绝对差 sort(arr.begin(), arr.end()); size_t numsLen = arr.size(); vector<int> arrCopy(numsLen); vector<vector<int>> res; int val = INT_MAX; for (size_t i = 1; i < numsLen; i++) { arrCopy[i] = arr[i] - arr[i - 1]; val = min(val, arrCopy[i]); } for (size_t i = 1; i < numsLen; i++) { if (arrCopy[i] == val) { res.push_back({ arr[i - 1] , arr[i] }); } } return res; } int minCostToMoveChips(vector<int>& position) {//玩筹码 int numsLen = position.size(); int cnt = 0; for (int& num : position) { if (num % 2 != 0) { cnt++; } } return min(cnt, numsLen - cnt); } bool checkStraightLine(vector<vector<int>>& coordinates) {//缀点成线 int paraA = coordinates[1][1] - coordinates[0][1]; int paraB = coordinates[0][0] - coordinates[1][0]; int paraComp = coordinates[0][0] * coordinates[1][1] - coordinates[1][0] * coordinates[0][1]; size_t coordCnt = coordinates.size(); for (size_t i = 2; i < coordCnt; i++) { if (paraA * coordinates[i][0] + paraB * coordinates[i][1] != paraComp) { return false; } } return true; } int oddCells(int n, int m, vector<vector<int>>& indices) {//奇数值单元格的数目 vector<int> rol(n), col(m); for (vector<int>& indc : indices) { rol[indc[0]]++; col[indc[1]]++; } int res = 0; for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < m; j++) { if ((rol[i] + col[j]) % 2 != 0) { res++; } } } return res; } vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {//二维网格迁移 vector<vector<int>> res(grid); size_t rol = grid.size(); size_t col = grid[0].size(); for (size_t i = 0; i < rol; i++) { for (size_t j = 0; j < col; j++) { size_t newRol = (i + (k + j) / col) % rol; size_t newCol = (j + k) % col; res[newRol][newCol] = grid[i][j]; } } return res; } int minTimeToVisitAllPoints(vector<vector<int>>& points) {//访问所有点的最小时间 int currentX = points[0][0]; int currentY = points[0][1]; int res = 0; for (vector<int>& point : points) { res += max(abs(point[1] - currentY), abs(point[0] - currentX)); currentX = point[0]; currentY = point[1]; } return res; } string tictactoe(vector<vector<int>>& moves) { vector<string> res = { "A", "B", "Draw", "Pending" }; size_t moveCnt = moves.size(); vector<vector<int>> grid(3, vector<int>(3, 0)); //下棋 for (size_t i = 0; i < moveCnt; i++) { if (i % 2 == 0) { grid[moves[i][0]][moves[i][1]] = 1; } else { grid[moves[i][0]][moves[i][1]] = 2; } } //检查赢家 for (size_t i = 0; i < 3; i++) { if (grid[i][0] == grid[i][1] && grid[i][1] == grid[i][2]) { if (grid[i][0] == 0) { continue; } if (grid[i][0] == 1) { return res[0]; } if (grid[i][0] == 2) { return res[1]; } } if (grid[0][i] == grid[1][i] && grid[1][i] == grid[2][i]) { if (grid[0][i] == 0) { continue; } if (grid[0][i] == 1) { return res[0]; } if (grid[0][i] == 2) { return res[1]; } } } if (grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2]) { if (grid[1][1] == 1) { return res[0]; } if (grid[1][1] == 2) { return res[1]; } } if (grid[2][0] == grid[1][1] && grid[1][1] == grid[0][2]) { if (grid[1][1] == 1) { return res[0]; } if (grid[1][1] == 2) { return res[1]; } } if (moveCnt == 9) { return res[2]; } return (res[3]); } int findSpecialInteger(vector<int>& arr) {//有序数组中出现次数超过25%的元素 size_t targetLen = arr.size() / 4; int target = arr[0]; int cnt = 0; for (int& num : arr) { if (num == target) { cnt++; } else { target = num; cnt = 1; } if (cnt > targetLen) { return target; } } return -1; } int findNumbers(vector<int>& nums) {//统计位数为偶数的数字 int res = 0; for (int& num : nums) { int cnt = 0; while (num != 0) { num /= 10; cnt++; } if (cnt % 2 == 0) { res++; } } return res; } vector<int> replaceElements(vector<int>& arr) {//将每个元素替换为右侧最大元素 vector<int> res(arr); int numsLen = arr.size(); res[numsLen - 1] = -1; for (int i = numsLen - 2; i > -1; i--) { res[i] = max(res[i + 1], arr[i + 1]); } return res; } int findBestValue(vector<int>& arr, int target) {//转变数组后最接近目标值的数组和 int numsLen = arr.size(); if (numsLen == 0) { return 0; } sort(arr.begin(), arr.end()); for (int i = 0; i < numsLen; i++) { double tmp = 1.0 * target / (numsLen - i); int mean = tmp; if (tmp - mean - 0.5 >= 0) { mean++; } if (arr[i] >= mean) { if (abs(target - (mean - 1) * (numsLen - i)) <= abs(target - mean * (numsLen - i))) { return mean - 1; } return mean; } target -= arr[i]; } return arr[numsLen - 1]; } vector<int> sumZero(int n) {//和为零的N个唯一整数 vector<int> res(n); int lim = n / 2; for (int i = 1; i <= lim; i++) { res[i - 1] = -i; res[n - i] = i; } return res; } bool canReach(vector<int>& arr, int start) {//跳跃游戏 III--回溯 if (start < 0 || start >= arr.size()) { return false; } if (arr[start] == 0) { return true; } if (arr[start] == -1) { return false; } int arrCopy = arr[start]; arr[start] = -1; bool left = canReach(arr, start + arrCopy); bool right = canReach(arr, start - arrCopy); arr[start] = arrCopy; return left || right; } vector<int> decompressRLElist(vector<int>& nums) {//解压缩编码列表 int numsLen = nums.size(); vector<int> res; int cur = 0; while (cur < numsLen) { int freq = nums[cur]; int val = nums[cur + 1]; while (freq > 0) { res.push_back(val); freq--; } cur += 2; } return res; } vector<int> getNoZeroIntegers(int n) {//将整数转换为两个无零整数的和 vector<int> res(2); int part1 = n; int part2 = 0; while (part2 < n) { part1 = n - part2; if ((to_string(part1) + to_string(part2)).find('0') == string::npos) { res[0] = part1; res[1] = part2; break; } part2++; } return res; } vector<int> luckyNumbers(vector<vector<int>>& matrix) {//矩阵中的幸运数 size_t rol = matrix.size(); size_t col = matrix[0].size(); vector<int> res; vector<int> rolMem(rol), colMem(col); for (size_t i = 0; i < rol; i++) { int target = INT_MAX; for (size_t j = 0; j < col; j++) { target = min(target, matrix[i][j]); } rolMem[i] = target; } for (size_t i = 0; i < col; i++) { int target = INT_MIN; for (size_t j = 0; j < rol; j++) { target = max(target, matrix[j][i]); } colMem[i] = target; } for (size_t i = 0; i < rol; i++) { for (size_t j = 0; j < col; j++) { if (rolMem[i] == colMem[j]) { res.push_back(rolMem[i]); } } } return res; } int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {//两个数组间的距离值 int res = 0; for (int& num1 : arr1) { bool isOK = true; for (int& num2 : arr2) { if (abs(num1 - num2) <= d) { isOK = false; break; } } if (isOK) { res++; } } return res; } vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {//按既定顺序创建目标数组 vector<int> res; size_t numsLen = nums.size(); for (size_t i = 0; i < numsLen; i++) { res.insert(res.begin() + index[i], nums[i]); } return res; } int maxProduct(vector<int>& nums) {//数组中两元素的最大乘积 sort(nums.begin(), nums.end()); return max((nums[0] - 1) * (nums[1] - 1), (nums[nums.size() - 1] - 1) * (nums[nums.size() - 2] - 1)); } vector<int> shuffle(vector<int>& nums, int n) {//重新排列数组 vector<int> res(nums); size_t gap = nums.size() / 2; for (size_t i = 0; i < gap; i++) { res[2 * i] = nums[i]; res[2 * i + 1] = nums[gap + i]; } return res; } }; class MyCalendar { public: MyCalendar() { return; } bool book(int start, int end) { auto it = timeMap.lower_bound(start);//k <= ?的迭代器,迭代器指向->? if (it != timeMap.end() && it->first < end) { return false; } if (it != timeMap.begin() && (--it)->second > start) { return false; } timeMap[start] = end;//添加或更新 return true; } private: map<int, int> timeMap;//红黑树 }; class MajorityChecker {//子数组中占绝大多数的元素--摩尔投票+线段树,赞数超时 //解答思路: //线段树是把一个大的区间拆分成很多个小区间 //每个小区间内使用摩尔投票,最终把所有小区间合并起来再用一次摩尔投票 public: MajorityChecker(vector<int>& arr) { nums = arr; numsLen = nums.size(); for (size_t i = 0; i < numsLen; i++) { curMap[arr[i]].push_back(i); } root = buildTree(0, numsLen - 1); return; } int query(int left, int right, int threshold) {//线段树 //vector<int> tmp = queryTree(left, right, root); int key = 0; int count = 0; queryTree(left, right, root, key, count); if (key == 0 || curMap[key].size() < threshold) { return -1; } auto it_l = lower_bound(curMap[key].begin(), curMap[key].end(), left); auto it_r = upper_bound(curMap[key].begin(), curMap[key].end(), right); int cnt = it_r - it_l; return cnt >= threshold ? key : -1; } private: struct node { int val = -1;//胜选者ID int cnt = -1;//胜选票数 int leftCur = -1;//区间开始小标 int rightCur = -1;//区间结束下标 node* left = nullptr; node* right = nullptr; }; vector<int> nums; unordered_map<int, vector<int>> curMap; size_t numsLen; node* root = nullptr; node* buildTree(int left, int right) {//递归构造线段树 if (left > right) { return nullptr; } if (left == right) { node* retNode = new node; retNode->cnt = 1; retNode->val = nums[left]; retNode->leftCur = left; retNode->rightCur = right; return retNode; } node* retNode = new node; int mid = (left + right) / 2; retNode->left = buildTree(left, mid); retNode->right = buildTree(mid + 1, right); retNode->leftCur = left; retNode->rightCur = right; //存在单边没有 if (retNode->left == nullptr) {//右侧获胜,左侧没人 retNode->val = retNode->right->val; retNode->cnt = retNode->right->cnt; } else if (retNode->right == nullptr) {//左侧获胜,右侧没人 retNode->val = retNode->left->val; retNode->cnt = retNode->left->cnt; } //两边都有 else if (retNode->left->val == retNode->right->val) {//两侧胜选者相同 retNode->val = retNode->left->val; retNode->cnt = retNode->left->cnt + retNode->right->cnt; } else if (retNode->left->cnt > retNode->right->cnt) {//左侧获胜 retNode->val = retNode->left->val; retNode->cnt = retNode->left->cnt - retNode->right->cnt; } else {//左侧没获胜 retNode->val = retNode->right->val; retNode->cnt = retNode->right->cnt - retNode->left->cnt; } return retNode; } bool queryTree(int left, int right, node* root, int& key, int& count) {//查询线段树 if (root == nullptr || left > right) { return false; } if (root->rightCur < left || root->leftCur > right) {//完全不重合区间 return false; } int mid = (root->leftCur + root->rightCur) / 2; if (root->leftCur >= left && root->rightCur <= right) {//节点区间是所求区间的子空间 if (root->val == key) { count += root->cnt; } else if (root->cnt > count) { key = root->val; count = root->cnt; } else if (root->cnt <= count) { count -= root->cnt; } return true;//不用将节点区间向下分解了 } if (mid >= left) {//不是子空间的话就掰开节点 queryTree(left, right, root->left, key, count); } if (right > mid) { queryTree(left, right, root->right, key, count); } return true; } }; int main(int argc, char* argv[]) { Solution mySolution; vector<int> nums = { 3, 0, 2, 1, 2 }; vector<vector<int>> grid = { {0, 1}, {1, 1} }; vector<vector<int>> matrix = { {} }; vector<string> wordList = { "bba","abaaaaaa","aaaaaa","bbabbabaab","aba","aa","baab","bbbbbb","aab","bbabbaabb" }; vector<string> wdLst2 = { "aaabbb","aab","babbab","babbbb","b","bbbbbbbbab","a","bbbbbbbbbb","baaabbaab","aa" }; mySolution.canReach(nums, 2); return 0; } #endif //cookBook-字符串 #if false class Solution { public: string addBinary(string a, string b) {//二进制求和 //注意长度 int aCur = a.size() - 1, bCur = b.size() - 1; string res; int sign = 0; while (aCur > -1 || bCur > -1) { int intA = aCur > -1 ? a[aCur] - '0' : 0; int intB = bCur > -1 ? b[bCur] - '0' : 0; int signCopy = (intA + intB + sign) / 2; int remain = (intA + intB + sign) % 2; sign = signCopy; res.insert(res.begin(), '0' + remain); aCur--; bCur--; } if (sign == 1) { res.insert(res.begin(), '1'); } return res; } int numDecodings(string s) {//解码方法 size_t sLen = s.size(); if (sLen == 0 || s[0] == '0') { return 0; } int pre = 1, current = 1; for (size_t i = 1; i < sLen; i++) { int tmp = current; if (s[i] == '0') { if (s[i - 1] == '1' || s[i - 1] == '2') { current = pre; } else {//以 0 开头的数字不合规则,0 必须是结尾 return 0; } } else if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '7' && s[i] > '0')) { current += pre; } pre = tmp; } return current; } int longestPalindrome(string s) {//最长回文串 unordered_map<char, int> chMap; for (char& ch : s) { chMap[ch]++; } int res = 0; bool odd = false; for (auto& it : chMap) { res += it.second; if (it.second % 2 == 1) { res--; odd = true; } } if (odd) { res++; } return res; } vector<string> findWords(vector<string>& words) {//键盘行 int charMap[] = { 2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3 }; vector<string> res; for (string& word : words) { int target = charMap[tolower(word[0]) - 'a']; bool add = true; for (char& ch : word) { if (charMap[tolower(ch) - 'a'] != target) { add = false; break; } } if (add) { res.push_back(word); } } return res; } string complexNumberMultiply(string a, string b) {//复数乘法 int re1 = 0, im1 = 0, re2 = 0, im2 = 0; imgStr2Int(a, re1, im1); imgStr2Int(b, re2, im2); return to_string(re1 * re2 - im1 * im2) + '+' + to_string(re1 * im2 + re2 * im1) + 'i'; } inline void imgStr2Int(string& str, int& real, int& imag) { bool realSignNeg = false; bool imagSignNeg = false; size_t cur = 0; if (str[cur] == '-') { realSignNeg = true; cur++; } while (str[cur] != '+') { real *= 10; real += str[cur] - '0'; cur++; } cur++; if (str[cur] == '-') { imagSignNeg = true; cur++; } while (str[cur] != 'i') { imag *= 10; imag += str[cur] - '0'; cur++; } if (realSignNeg) { real = -real; } if (imagSignNeg) { imag = -imag; } return; } string reverseStr(string s, int k) {//反转字符串 II //通俗一点说,每隔k个反转k个,末尾不够k个时全部反转 size_t sLen = s.size(); size_t processTime = sLen / k; for (size_t i = 0; i < processTime; i++) { if (i % 2 == 0) { int front = k * i; int rear = front + k - 1; while (front < rear) { swap(s[front], s[rear]); front++; rear--; } } } if (processTime % 2 == 0) { processTime *= k; int front = processTime; int rear = sLen - 1; while (front < rear) { swap(s[front], s[rear]); front++; rear--; } } return s; } string shortestCompletingWord(string licensePlate, vector<string>& words) {//最短补全词 unordered_map<char, int> plateMap; for (char& ch : licensePlate) { if (isalpha(ch)) { plateMap[tolower(ch)]++; } } string res; for (string& word : words) { if (word.size() < res.size() || res == "") {//剪枝 unordered_map<char, int> tmp(plateMap); for (char& ch : word) { char cur = tolower(ch); if (tmp.count(cur) > 0) { tmp[cur]--; if (tmp[cur] == 0) { tmp.erase(cur); } } } if (tmp.empty()) { res = word; } } } return res; } vector<int> smallestRange(vector<vector<int>>& nums) {//最小区间 //滑动窗口 unordered_map<int, vector<int>> indicator; int minVal = INT_MAX, maxVal = INT_MIN; size_t numsCnt = nums.size(); for (size_t i = 0; i < numsCnt; i++) { for (int& num : nums[i]) { indicator[num].push_back(i); } minVal = min(nums[i][0], minVal); maxVal = max(nums[i][nums[i].size() - 1], maxVal); } vector<int> freq(numsCnt); int inside = 0;//窗口内!数组!数量 int left = minVal, right = minVal - 1; int bestLeft = minVal, bestRight = maxVal; while (right < maxVal) { right++; if (indicator.count(right) > 0) {//有效数值 for (int& numSer : indicator[right]) {//增加窗口内!数字!数量 freq[numSer]++; if (freq[numSer] == 1) { inside++; } } while (inside == numsCnt) {//窗口包含数组达到要求后缩小宽度,减少数字数量 if (right - left < bestRight - bestLeft) { bestLeft = left; bestRight = right; } if (indicator.count(left)) { for (const int& x : indicator[left]) { freq[x]--; if (freq[x] == 0) { inside--; } } } left++; } } } return { bestLeft, bestRight }; } string mostCommonWord(string paragraph, vector<string>& banned) {//最常见的单词 size_t sLen = paragraph.size(); unordered_map<string, int> freq; unordered_set<string> bannedList(banned.begin(), banned.end()); for (string& str : banned) { for (char& ch : str) { ch = tolower(ch); } } size_t cur = 0; size_t last = 0; while (cur < sLen) { while (cur < sLen && isalpha(paragraph[cur])) { cur++; } string tmp(paragraph.begin() + last, paragraph.begin() + cur); for (char& ch : tmp) { ch = tolower(ch); } if (bannedList.count(tmp) < 1) { freq[tmp]++; } while (cur < sLen && !isalpha(paragraph[cur])) { cur++; } last = cur; } string res; int cnt = 0; for (auto& it : freq) { if (it.second > cnt) { res = it.first; cnt = it.second; } } return res; } bool isLongPressedName(string name, string typed) {//长按键入 size_t typeLen = typed.size(); size_t nameLen = name.size(); size_t typeCur = 0, nameCur = 0; while (typeCur < typeLen) { if (nameCur < nameLen && name[nameCur] == typed[typeCur]) { nameCur++; typeCur++; } else if (typeCur > 0 && typed[typeCur] == typed[typeCur - 1]) { typeCur++; } else { return false; } } return nameCur == nameLen; } vector<int> diStringMatch(string S) {//增减字符串匹配 size_t sLen = S.size(); int left = 0, right = sLen; vector<int> res(sLen + 1); for (size_t i = 0; i < sLen; i++) { if (S[i] == 'I') { res[i] = left++; } else { res[i] = right--; } } res[sLen] = left; return res; } string strWithout3a3b(int a, int b) {//不含 AAA 或 BBB 的字符串 string res; int aCnt = 0, bCnt = 0; while (a > 0 || b > 0) { if (a > b) { if (aCnt < 2) { res.push_back('a'); aCnt++; a--; bCnt = 0; } else { res.push_back('b'); bCnt++; b--; aCnt = 0; } } else { if (bCnt < 2) { res.push_back('b'); bCnt++; b--; aCnt = 0; } else { res.push_back('a'); aCnt++; a--; bCnt = 0; } } } return res; } string decodeAtIndex(string S, int K) {//索引处的解码字符串 string res; long size = 0; size_t sLen = S.size(); for (int i = 0; i < sLen; i++) { if (isdigit(S[i])) size *= S[i] - '0'; else size++; } for (int i = sLen - 1; i > -1; i--) { K %= size; if (K == 0 && isalpha(S[i])) { res += S[i]; break; } if (isdigit(S[i])) { size /= S[i] - '0'; } else { size--; } } return res; } int uniqueLetterString(string s) {//统计子串中的唯一字符 //和之前一道题比较像,统计每一个单独字符的贡献,向两侧拓展 size_t sLen = s.size(); vector<int> left(sLen), right(sLen), prev(26, -1); for (size_t i = 0; i < sLen; i++) { left[i] = prev[s[i] - 'A']; prev[s[i] - 'A'] = i; } prev = vector<int>(26, sLen); for (int i = sLen - 1; i > -1; i--) { right[i] = prev[s[i] - 'A']; prev[s[i] - 'A'] = i; } int mod = 1000000007; long long res = 0; for (size_t i = 0; i < sLen; i++) { res = (res + (right[i] - i) * (i - left[i])) % mod; } return res; } vector<string> findOcurrences(string text, string first, string second) {//Bigram 分词 vector<string> res, textMap; int last = 0, current = 0; for (char& ch : text) { if (ch == ' ') { textMap.push_back(text.substr(last, current - last)); last = current + 1;//注意单词前空格 } current++; } textMap.push_back(text.substr(last, current - last)); int textCnt = textMap.size(); for (int i = 2; i < textCnt; i++) { if (second == textMap[i - 1] && first == textMap[i - 2]) { res.push_back(textMap[i]); } } return res; } string defangIPaddr(string s) {//IP 地址无效化 string res; for (char& ch : s) { if (ch == '.') { res += "[.]"; } else { res += ch; } } return res; } int maxNumberOfBalloons(string text) {//“气球” 的最大数量 balloon vector<int> charCnt(26); for (char& ch : text) { charCnt[ch - 'a']++; } return min(min(min(min(charCnt[1], charCnt[0]), charCnt[11] / 2), charCnt[14] / 2), charCnt[13]); } int balancedStringSplit(string s) {//分割平衡字符串 int cnt = 0, res = 0; for (char& ch : s) { if (ch == 'L') { cnt++; } else { cnt--; } if (cnt == 0) { res++; } } return res; } int isPrefixOfWord(string sentence, string searchWord) {//检查单词是否为句中其他单词的前缀 vector<string> textMap; int last = 0, current = 0; for (char& ch : sentence) { if (ch == ' ') { textMap.push_back(sentence.substr(last, current - last)); last = current + 1;//注意单词前空格 } current++; } textMap.push_back(sentence.substr(last, current - last)); int textCnt = textMap.size(); size_t wordLen = searchWord.size(); for (int i = 0; i < textCnt; i++) { int textCur = 0, wordCur = 0, textLen = textMap[i].size(); while (textCur < textLen && wordCur < wordLen && searchWord[wordCur] == textMap[i][textCur]) { textCur++; wordCur++; } if (wordCur == wordLen) { return i + 1; } } return -1; } int balancedString(string s) { int sLen = s.size(), k = sLen / 4, res = sLen; unordered_map<char, int> chMap;//窗口外字符计数 for (char& ch : s) { chMap[ch]++; } int leftCur = 0, rightCur = 0; while (rightCur < sLen) { chMap[s[rightCur]]--; while (leftCur <= rightCur + 1 && chMap['Q'] <= k && chMap['W'] <= k && chMap['E'] <= k && chMap['R'] <= k) { //窗口外都小于1/4可以替换当前窗口 //缺少部分可以用窗口内替换的补偿 res = min(res, rightCur - leftCur + 1); chMap[s[leftCur]]++; leftCur++; } rightCur++; } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "1s3 PSt"; string b = "1+1i"; vector<string> inpt = { "hit" }; vector<vector<int>> nums = { {4,10,15,24,26 }, { 0,9,12,20 }, { 5,18,22,30 } }; mySolution.maxNumberOfBalloons("loonbalxballpoon"); return 0; } #endif //cookBook-滑动窗口与双指针 #if false class Solution { public: int characterReplacement(string s, int k) {//替换后的最长重复字符 int cnt = 0;//最多字母计数 size_t sLen = s.size(); vector<int> charCnt(26);//窗口内字母计数 size_t rightCur = 0, leftCur = 0; while (rightCur < sLen) { cnt = max(cnt, ++charCnt[s[rightCur] - 'A']); if (rightCur - leftCur + 1 - cnt > k) { charCnt[s[leftCur] - 'A']--; leftCur++; //不满足条件的情况下,left和right一起移动,len不变的 } rightCur++; } return rightCur - leftCur; } unordered_map<char, int> pMap, tmpMap; vector<int> findAnagrams(string s, string p) {//找到字符串中所有字母异位词 for (char& ch : p) { pMap[ch]++; } size_t sLen = s.size(), pLen = p.size(); vector<int> res; int cur = 0; while (cur < pLen) { tmpMap[s[cur]]++; cur++; } while (cur < sLen) { if (findAnagramsCheck()) { res.push_back(cur - pLen); } --tmpMap[s[cur - pLen]]; tmpMap[s[cur++]]++; } if (findAnagramsCheck()) { res.push_back(cur - pLen); } return res; } bool findAnagramsCheck() { for (auto& it : pMap) { if (tmpMap.count(it.first) < 1 || tmpMap[it.first] != it.second) { return false; } } return true; } bool checkInclusion(string p, string s) {//字符串的排列 for (char& ch : p) { pMap[ch]++; } size_t sLen = s.size(), pLen = p.size(); if (sLen < pLen) { return false; } vector<int> res; int cur = 0; while (cur < pLen) { tmpMap[s[cur]]++; cur++; } while (cur < sLen) { if (checkInclusionCheck()) { return true; } --tmpMap[s[cur - pLen]]; tmpMap[s[cur++]]++; } if (checkInclusionCheck()) { return true; } return false; } bool checkInclusionCheck() { for (auto& it : pMap) { if (tmpMap.count(it.first) < 1 || tmpMap[it.first] != it.second) { return false; } } return true; } vector<int> partitionLabels(string s) {//划分字母区间 vector<int> endPos(26), res; size_t sLen = s.size(); for (size_t i = 0; i < sLen; i++) { endPos[s[i] - 'a'] = i; } int startCur = 0, endCur = 0; for (size_t i = 0; i < sLen; i++) { endCur = max(endCur, endPos[s[i] - 'a']);//尽可能把区间向右扩 if (i == endCur) { res.push_back(endCur - startCur + 1); startCur = endCur + 1; } } return res; } vector<double> medianSlidingWindowBAK(vector<int>& nums, int k) {//滑动窗口中位数--暴力法超时 vector<double> res; size_t numsLen = nums.size(); bool isOdd = k % 2 == 1; size_t cur = k / 2; for (size_t i = 0; i < numsLen - k + 1; i++) { vector<double> tmp(nums.begin() + i, nums.begin() + i + k); sort(tmp.begin(), tmp.end()); if (isOdd) { res.push_back(tmp[cur]); } else { res.push_back((tmp[cur] + tmp[cur - 1] + 0.0) / 2); } } return res; } vector<double> medianSlidingWindow(vector<int>& nums, int k) {//滑动窗口中位数--使用STL multiset //multiset默认从小到大排序,红黑树 size_t numsLen = nums.size(); vector<double> res(numsLen - k + 1); multiset<int> window(nums.begin(), nums.begin() + k); auto mid = next(window.begin(), k / 2);//向后移动迭代器,类似prev() for (size_t i = k; i < numsLen; i++) { res[i - k] = (0.0 + *mid + *next(mid, k % 2 - 1)) * 0.5; window.insert(nums[i]); // 5 / 2 == 2, 4 / 2 == 2. 故只考虑在前插入和移除的情况 if (nums[i] < *mid) {//入窗口元素,位置在mid之前 mid--; } if (nums[i - k] <= *mid) {//出窗口元素,位置在mid之前 mid++; } window.erase(window.lower_bound(nums[i - k])); } res[numsLen - k] = (0.0 + *mid + *next(mid, k % 2 - 1)) * 0.5; return res; } int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {//安排工作以达到最大收益 //哈希映射+动态规划 size_t diffLen = difficulty.size(); vector<vector<int>> dp(diffLen + 1, vector<int>(2)); for (size_t i = 0; i < diffLen; i++) { dp[i][0] = difficulty[i]; dp[i][1] = profit[i]; } dp[diffLen][0] = 0; dp[diffLen][1] = 0; sort(dp.begin(), dp.end()); for (size_t i = 1; i <= diffLen; i++) { dp[i][1] = max(dp[i][1], dp[i - 1][1]); } map<int, int> dpMap; for (vector<int>& it : dp) { dpMap[it[0]] = it[1]; } int res = 0; for (int& num : worker) { auto it = dpMap.lower_bound(num); if (it == dpMap.end() || num != it->first) { it--; } res += it->second; } return res; } int longestMountain(vector<int>& arr) {//数组中的最长山脉 size_t arrLen = arr.size(); //起始与终点 vector<int> left(arrLen, 0), right(arrLen, arrLen), climax(arrLen, 0); for (size_t i = 1; i < arrLen; i++) { if (arr[i] > arr[i - 1]) { left[i] = left[i - 1]; } else { left[i] = i; } if (arr[arrLen - i - 1] > arr[arrLen - i]) { right[arrLen - i - 1] = right[arrLen - i]; } else { right[arrLen - i - 1] = arrLen - i; } } for (size_t i = 2; i < arrLen; i++) { if (arr[i - 2] < arr[i - 1] && arr[i - 1] > arr[i]) { climax[i - 1] = 1; } } int res = 0; for (size_t i = 0; i < arrLen; i++) { if (climax[i] == 1) { res = max(right[i] - left[i], res); } } return res > 2 ? res : 0; } string pushDominoes(string s) {//推多米诺 //受力计算 size_t sLen = s.size(); vector<int> left(sLen, 0), right(sLen, 0); int force = 0;//最大力 for (size_t i = 0; i < sLen; i++) { if (s[i] == 'R') { force = sLen; } else if (s[i] == 'L') { force = 0; } else { force = max(force - 1, 0); } right[i] += force; } force = 0; for (int i = sLen - 1; i > -1; i--) { if (s[i] == 'L') { force = sLen; } else if (s[i] == 'R') { force = 0; } else { force = max(0, force - 1); } left[i] += force; } for (size_t i = 0; i < sLen; i++) { if (left[i] > right[i]) { s[i] = 'L'; } else if (left[i] < right[i]) { s[i] = 'R'; } } return s; } int numRescueBoats(vector<int>& people, int limit) {//救生艇 sort(people.begin(), people.end()); size_t numsLen = people.size(); int leftCur = 0, rightCur = numsLen - 1; int res = 0; while (leftCur < numsLen && rightCur > -1 && leftCur < rightCur) { if (people[leftCur] + people[rightCur] <= limit) { leftCur++; } rightCur--; res++; } if (leftCur == rightCur) { res++; } return res; } int totalFruit(vector<int>& tree) {//水果成篮,用map比用set简单 unordered_map<int, int> fruits; int res = 0; int left = 0; for (int i = 0; i < tree.size(); i++) { fruits[tree[i]]++;//入窗口 while (fruits.size() > 2) {//出窗口 fruits[tree[left]]--; if (fruits[tree[left]] == 0) { fruits.erase(tree[left]); } left++; } res = max(res, i - left + 1); } return res; } int numSubarraysWithSum(vector<int>& nums, int target) {//和相同的二元子数组 unordered_map<int, int> prefixMap; int res = 0, prefix = 0; prefixMap[0] = 1; for (int& num : nums) { prefix += num; if (prefixMap.count(prefix - target) > 0) { //存在 prefix2 - prefix1 == target 的情况 res += prefixMap[prefix - target]; } prefixMap[prefix]++; } return res; } vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {//区间列表的交集 size_t flistLen = firstList.size(), slistLen = secondList.size(), fCur = 0, sCur = 0; vector<vector<int>> res; while (fCur < flistLen && sCur < slistLen) { int leftEnd = max(firstList[fCur][0], secondList[sCur][0]); int rightEnd = min(firstList[fCur][1], secondList[sCur][1]); if (leftEnd <= rightEnd) {//合法区间 res.push_back({ leftEnd, rightEnd }); } //将靠前的区间向后移 if (firstList[fCur][1] < secondList[sCur][1]) { fCur++; } else { sCur++; } } return res; } int subarraysWithKDistinct(vector<int>& nums, int cnt) {//K 个不同整数的子数组 //将“恰好问题”转换为至多相减 return subarraysWithKDistinctMax(nums, cnt) - subarraysWithKDistinctMax(nums, cnt - 1); } int subarraysWithKDistinctMax(vector<int>& nums, int cnt) { //窗口里至多有k种元素 int numsLen = nums.size(); unordered_map<int, int> numsMap; int left = 0, res = 0; for (int i = 0; i < numsLen; i++) { numsMap[nums[i]]++; while (numsMap.size() > cnt) { numsMap[nums[left]]--; if (numsMap[nums[left]] == 0) { numsMap.erase(nums[left]); } left++; } //以右侧为头向左拓展的子数组数量 res += i - left + 1; } return res; } int minKBitFlipsBAK(vector<int>& nums, int wide) {//K 连续位的最小翻转次数 //暴力算法超时 size_t numsLen = nums.size(); int res = 0; for (size_t i = 0; i <= numsLen - wide; i++) { if (nums[i] == 0) { int lim = i + wide; for (int j = i; j < lim; j++) { nums[j] = nums[j] == 0 ? 1 : 0; } res++; } } for (size_t i = numsLen - wide; i < numsLen; i++) { if (nums[i] == 0) { return -1; } } return res; } int minKBitFlips(vector<int>& nums, int k) {//K 连续位的最小翻转次数 size_t numsLen = nums.size(); int res = 0, flipTime = 0;//窗口内累计翻转次数 for (size_t i = 0; i < numsLen; i++) { if (i >= k && nums[i - k] == 2) {//超出上一个窗口翻转范围 flipTime--; } if (flipTime % 2 == nums[i]) {//需要翻转(累积影响) if (i + k > numsLen) { return -1; } flipTime++; nums[i] = 2; res++; } } return res; } int longestOnes(vector<int>& nums, int K) {//最大连续1的个数 III int numsLen = nums.size(), left = 0, res = 0, right = 0; while (left < numsLen) { if (right < numsLen && ((K > 0 && nums[right] == 0) || nums[right] == 1)) { if (nums[right++] == 0) {//先把K分配 K--; } } else { if (K == 0 || (right == numsLen && K > 0)) {//异常判断 res = max(res, right - left); } if (nums[left] == 0) {//移动安插位置 K++; } left++; } } return res; } vector<int> numMovesStonesII(vector<int>& stones) {//移动石子直到连续 II sort(stones.begin(), stones.end()); int stoneCnt = stones.size(); int minStep = INT_MAX, maxStep = 0, s1 = 0, s2 = 0; s1 = stones[stoneCnt - 1] - stones[0] + 1 - stoneCnt;//可移动空位 s2 = min(stones[1] - stones[0] - 1, stones[stoneCnt - 1] - stones[stoneCnt - 2] - 1);//不可利用空位 maxStep = s1 - s2; int right = 0; for (int left = 0; left < stoneCnt; left++) { while (right + 1 < stoneCnt && stones[right + 1] - stones[left] < stoneCnt) { //找到窗口 right++; } int cost = stoneCnt - (right - left + 1);//窗口内缺失的石头数量 if ((right - left + 1 == stoneCnt - 1) && (stones[right] - stones[left] + 1 == stoneCnt - 1)) { cost = 2; } minStep = min(minStep, cost); } return { minStep, maxStep }; } int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {//爱生气的书店老板 size_t numsLen = customers.size(); int res = 0; for (size_t i = 0; i < numsLen; i++) { res += grumpy[i] == 0 ? customers[i] : 0; } int left = 0, right = X; for (size_t i = 0; i < right; i++) { res += grumpy[i] == 1 ? customers[i] : 0; } int newRes = res; while (right < numsLen) { newRes = newRes + (grumpy[right] == 1 ? customers[right] : 0) - (grumpy[left] == 1 ? customers[left] : 0); res = max(res, newRes); left++; right++; } return res; } vector<double> sampleStats(vector<int>& count) {//大样本统计 //最小值、最大值、平均值、中位数和众数 vector<double> res(5, 0.0); int minVal = -1, maxVal = 0; int cand = 0, cnt = 0; int totalCnt = 0, currentCnt = 0, lastCnt = 0; for (int& num : count) {//有效样本数量 totalCnt += num; } int lim = totalCnt / 2; bool isOdd = totalCnt % 2 == 1; for (size_t val = 0; val < 256; val++) { int valCnt = count[val]; if (valCnt == 0) { continue; } //求平均 res[2] += 1.0 * valCnt * val / totalCnt; //最小值 if (minVal == -1) { minVal = val; } //最大值 maxVal = val; //众数 if (valCnt > cnt) { cand = val; cnt = valCnt; } } int lastVal = 0; for (size_t val = 0; val < 256; val++) { int valCnt = count[val]; if (valCnt == 0) { continue; } //中位数,三种情况,奇数,偶数非跨区,偶数跨区 lastCnt = currentCnt; currentCnt += valCnt; if (isOdd && lastCnt < lim && lim <= currentCnt) {//奇数 res[3] = val + 0.0; break; } else if (!isOdd && lastCnt < lim && lim + 1 <= currentCnt) {//偶数非跨区 res[3] = val + 0.0; break; } else if (!isOdd && lastCnt == lim && lim + 1 <= currentCnt) { res[3] = (lastVal + val) / 2.0; break; } lastVal = val; } res[0] = minVal + 0.0; res[1] = maxVal + 0.0; res[4] = cand + 0.0; return res; } int equalSubstring(string s, string t, int maxCost) {//尽可能使字符串相等 int res = 0; int sLen = s.size(), left = 0; for (int i = 0; i < sLen; i++) { maxCost -= abs(s[i] - t[i]); while (left <= i && maxCost < 0) { maxCost += abs(s[left] - t[left]); left++; } res = max(res, i - left + 1); } return res; } //int prefix[300][300]; int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {//元素和为目标值的子矩阵数量 size_t rol = matrix.size(), col = matrix[0].size(); //求累加矩阵 int** prefix = new int* [rol + 1]; for (int i = 0; i <= rol; i++) { prefix[i] = new int[col + 1]; for (int j = 0; j <= col; j++) { prefix[i][j] = 0; } } for (size_t i = 1; i <= rol; i++) { for (size_t j = 1; j <= col; j++) { prefix[i][j] = prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1] + matrix[i - 1][j - 1]; } } int res = 0; for (size_t r1 = 1; r1 <= rol; r1++) { for (size_t c1 = 1; c1 <= col; c1++) { for (size_t r2 = r1; r2 <= rol; r2++) { for (size_t c2 = c1; c2 <= col; c2++) { if (prefix[r2][c2] - prefix[r2][c1 - 1] - prefix[r1 - 1][c2] + prefix[r1 - 1][c1 - 1] == target) { res++; } } } } } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = ".L.R...LR..L.."; string b = "abc"; vector<int> inpt1 = { 1,0,1,2,1,1,7,5 }; vector<int> inpt2 = { 0,1,0,1,0,1,0,1 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { { 0, 1, 1, 1, 0, 1 }, { 0, 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1, 0 }, { 1, 0, 0, 1, 0, 0 }, }; mySolution.numSubmatrixSumTarget(nums, 0); return 0; } #endif //cookBook-链表 #if false class Solution { public: struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; ListNode* myBuildList(vector<int>& nums) { ListNode* rootNode = new ListNode; ListNode* currentNode = rootNode; for (int& num : nums) { currentNode->next = new ListNode; currentNode = currentNode->next; currentNode->val = num; } return rootNode->next; } ListNode* deleteDuplicatesMKI(ListNode* head) {//删除排序链表中的重复元素 if (head == nullptr) { return head; } ListNode* currentNode = head, * nextNode = head; while (nextNode != nullptr) { if (currentNode->val != nextNode->val) { currentNode->next = nextNode; currentNode = currentNode->next; } nextNode = nextNode->next; } currentNode->next = nextNode; return head; } ListNode* deleteDuplicates(ListNode* head) {//删除排序链表中的重复元素 II if (head == nullptr || head->next == nullptr) { return head; } ListNode* currentNode, * leftNode, * rightNode; ListNode* rootNode = new ListNode; rootNode->next = head; currentNode = rootNode, leftNode = head, rightNode = head; while (rightNode != nullptr) { if (leftNode->val == rightNode->val) { rightNode = rightNode->next; } else if (leftNode->next == rightNode) { currentNode->next = leftNode; currentNode = currentNode->next; leftNode = rightNode; } else { leftNode = rightNode; } } currentNode->next = leftNode->next == nullptr ? leftNode : nullptr; return rootNode->next; } ListNode* partition(ListNode* head, int x) {//分隔链表 ListNode* sortNode = new ListNode; ListNode* rminNode = new ListNode; ListNode* sortCur = sortNode, * rminCur = rminNode; sortNode->next = head, rminNode->next = head; while (rminCur != nullptr && rminCur->next != nullptr) { if (rminCur->next->val < x) { sortCur->next = rminCur->next; rminCur->next = rminCur->next->next; sortCur = sortCur->next; } else { rminCur = rminCur->next; } } if (rminCur != nullptr) { rminCur->next = nullptr; } sortCur->next = rminNode->next; return sortNode->next; } ListNode* reverseBetween(ListNode* head, int m, int n) {//反转链表 II //反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 ListNode* root = new ListNode; root->next = head; ListNode* last = root; stack<ListNode*> stk; int cnt = 1; while (cnt < m) { last = head; head = head->next; cnt++; } while (cnt <= n) { stk.push(head); head = head->next; cnt++; } while (!stk.empty()) { last->next = stk.top(); stk.pop(); last = last->next; } last->next = head; return root->next; } ListNode* reverseKGroupBAK(ListNode* head, int k) {//K 个一组翻转链表 //只使用常数空间 //栈版本 ListNode* rootNode = new ListNode; rootNode->next = head; ListNode* slowCur = rootNode, * fastCur = rootNode; stack<ListNode*> stk; int cnt = 0; while (fastCur->next != nullptr) { fastCur = fastCur->next; cnt++; if (cnt == k) { ListNode* front = slowCur, * rear = fastCur->next; while (cnt > 0) { stk.push(slowCur->next); slowCur = slowCur->next; cnt--; } while (!stk.empty()) { front->next = stk.top(); stk.pop(); front = front->next; } front->next = rear; slowCur = front; fastCur = front; } } return rootNode->next; } ListNode* reverseKGroup(ListNode* head, int k) {//K 个一组翻转链表 //只使用常数空间 //不移动头节点固定位置插入就可以实现反序 ListNode* rootNode = new ListNode; rootNode->next = head; ListNode* slowCur = rootNode, * fastCur = rootNode; int cnt = 0; while (fastCur->next != nullptr) { fastCur = fastCur->next; cnt++; if (cnt == k) { ListNode* nextNode = slowCur->next; while (cnt > 1) { ListNode* copy = slowCur->next; slowCur->next = copy->next; copy->next = fastCur->next; fastCur->next = copy; cnt--; } cnt = 0; fastCur = nextNode; slowCur = nextNode; } } return rootNode->next; } void reorderList(ListNode* head) {//重排链表 vector<ListNode*> nodeVtr; ListNode* current = head; while (current != nullptr) { nodeVtr.push_back(current); current = current->next; } int leftCur = 0, rightCur = nodeVtr.size() - 1; head = new ListNode; current = head; while (leftCur < rightCur) { current->next = nodeVtr[leftCur++]; current = current->next; current->next = nodeVtr[rightCur--]; current = current->next; } if (leftCur == rightCur) { current->next = nodeVtr[leftCur]; current = current->next; } current->next = nullptr; head = head->next; return; } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {//两数相加 II stack<ListNode*> stk1, stk2; while (l1 != nullptr) { stk1.push(l1); l1 = l1->next; } while (l2 != nullptr) { stk2.push(l2); l2 = l2->next; } int aux = 0; ListNode* root = new ListNode; while (!stk1.empty() || !stk2.empty() || aux == 1) { int cand1 = 0, cand2 = 0; if (!stk1.empty()) { cand1 = stk1.top()->val; stk1.pop(); } if (!stk2.empty()) { cand2 = stk2.top()->val; stk2.pop(); } ListNode* tmp = new ListNode; tmp->val = (cand1 + cand2 + aux) % 10; tmp->next = root->next; root->next = tmp; aux = (cand1 + cand2 + aux) / 10; } return root->next; } vector<ListNode*> splitListToParts(ListNode* root, int k) {//分隔链表 ListNode* current = root; int cnt = 0; while (current != nullptr) { current = current->next; cnt++; } int lim = cnt / k; int gap = cnt % k; vector<ListNode*> res(k); current = root; ListNode* tmp = new ListNode; for (int i = 0; i < k; i++) { int currentCnt = 0; int currentLim = lim; if (i < gap) { currentLim++; } res[i] = current; ListNode* cur = tmp; cur->next = current; while (current != nullptr && currentCnt++ < currentLim) { current = current->next; cur = cur->next; } if (cur != nullptr) { cur->next = nullptr; } } return res; } ListNode* middleNode(ListNode* head) {//链表的中间结点 ListNode* root = new ListNode; root->next = head; ListNode* slowCur = root, * fastCur = root; int cnt = 0; while (fastCur != nullptr && fastCur->next != nullptr) { slowCur = slowCur->next; fastCur = fastCur->next->next; cnt += 2; } if (fastCur == nullptr) { cnt++; } if (cnt % 2 == 0) { slowCur = slowCur->next; } return slowCur; } int getDecimalValue(ListNode* head) {//二进制链表转整数 int res = 0; while (head != nullptr) { res *= 2; res += head->val; head = head->next; } return res; } ListNode* removeZeroSumSublists(ListNode* head) {//从链表中删去总和值为零的连续节点 unordered_map<int, ListNode*> prefixMap; int sum = 0; ListNode* root = new ListNode; root->next = head, root->val = 0; ListNode* cur = root; while (cur != nullptr) { sum += cur->val; prefixMap[sum] = cur; cur = cur->next; } cur = root, sum = 0; while (cur != nullptr) { sum += cur->val; cur->next = prefixMap[sum]->next; cur = cur->next; } return root->next; } vector<int> nextLargerNodes(ListNode* head) {//链表中的下一个更大节点 vector<int> nums; for (ListNode* cur = head; cur != nullptr; cur = cur->next) { nums.push_back(cur->val); } vector<int> res(nums); stack<int> stk; for (int i = nums.size() - 1; i > -1; i--) { while (!stk.empty() && stk.top() <= nums[i]) { stk.pop(); } res[i] = stk.empty() ? 0 : stk.top(); stk.push(nums[i]); } return res; } int numComponents(ListNode* head, vector<int>& G) {//链表组件 unordered_set<int> gSet; for (int& num : G) { gSet.emplace(num); } for (ListNode* cur = head; cur != nullptr; cur = cur->next) { cur->val = gSet.count(cur->val) > 0 ? 1 : 0; } int res = 0; ListNode* cur = head; while (cur != nullptr) { if (cur->val == 1) { res++; while (cur != nullptr && cur->val == 1) { cur = cur->next; } } else { cur = cur->next; } } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = ".L.R...LR..L.."; string b = "abc"; vector<int> inpt1 = { 1, 2, 3, 4, 5, 6 }; vector<int> inpt2 = { 0,1,0,1,0,1,0,1 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { { 0, 1, 1, 1, 0, 1 }, { 0, 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1, 0 }, { 1, 0, 0, 1, 0, 0 }, }; mySolution.middleNode(mySolution.myBuildList(inpt1)); return 0; } #endif //cookBook-栈和队列 #if false class FreqStack {//最大频率栈 public: FreqStack() { } void push(int x) { freq[x]++; maxFreq = max(maxFreq, freq[x]); stkVtr[freq[x]].push(x); return; } int pop() { int res = stkVtr[maxFreq].top(); stkVtr[maxFreq].pop(); freq[res]--; if (stkVtr[maxFreq].size() == 0) { maxFreq--; } return res; } private: unordered_map<int, int> freq; unordered_map<int, stack<int>> stkVtr; int maxFreq = 0; }; class StockSpanner {//股票价格跨度 public: StockSpanner() { return; } int next(int price) { int tmp = 1; while (!pri.empty() && pri.top() <= price) { tmp += day.top(); day.pop(); pri.pop(); } pri.push(price); day.push(tmp); return day.top(); } private: stack<int> day, pri; }; class NestedInteger { public: // Constructor initializes an empty nested list. NestedInteger(); // Constructor initializes a single integer. NestedInteger(int value); // Return true if this NestedInteger holds a single integer, rather than a nested list. bool isInteger() const; // Return the single integer that this NestedInteger holds, if it holds a single integer // The result is undefined if this NestedInteger holds a nested list int getInteger() const; // Set this NestedInteger to hold a single integer. void setInteger(int value); // Set this NestedInteger to hold a nested list and adds a nested integer to it. void add(const NestedInteger& ni); // Return the nested list that this NestedInteger holds, if it holds a nested list // The result is undefined if this NestedInteger holds a single integer const vector<NestedInteger>& getList() const; }; class Solution { public: string simplifyPath(string path) {//简化路径 path.push_back('/'); stack<string> pathStack; string current; for (char& ch : path) { if (ch == '/') { if (current == ".") { current.clear(); } else if (current == "..") { if (!pathStack.empty()) { pathStack.pop(); } } else if (current.size() > 0) { pathStack.push(current); } current.clear(); } else { current.push_back(ch); } } string res = "/"; while (!pathStack.empty()) { res = '/' + pathStack.top() + res; pathStack.pop(); } if (res.size() != 1) { res.pop_back(); } return res; } int calculate(string s) {//基本计算器 int res = 0, sym = 1, tmp = 0; stack<int> numStack; //假设只有两个操作数,A - (B - C) = A + (-1)* (B - C) for (char& ch : s) { if (ch == ' ') { continue; } else if (ch >= '0' && ch <= '9') { tmp *= 10; tmp += ch - '0'; } else if (ch == '+') { res += tmp * sym; tmp = 0; sym = 1; } else if (ch == '-') { res += tmp * sym; tmp = 0; sym = -1; } else if (ch == '(') { numStack.push(res); numStack.push(sym); sym = 1; res = 0; } else if (ch == ')') { res += tmp * sym; res *= numStack.top(); numStack.pop(); res += numStack.top(); numStack.pop(); tmp = 0; } } return res + tmp * sym; } bool isValidSerialization(string preorder) {//验证二叉树的前序序列化 int cur = 0, sLen = preorder.size(); bool isLeave = false; while (cur < sLen) {//先转换为节点标记 if (preorder[cur] <= '9' && preorder[cur] >= '0') { if (isLeave == false) { isLeave = true; } else { preorder[cur] = ','; } } else { isLeave = false; } cur++; } int diff = 1;//出度 - 入度 for (char& ch : preorder) { if (ch == ',') { continue; } diff--; if (diff < 0) { return false; } if (ch != '#') { diff += 2; } } return diff == 0; } NestedInteger deserialize(string s) {//迷你语法分析器 //整数也需要创建容器 int n = s.size(); if (n == 0)return NestedInteger(); if (s[0] != '[')return NestedInteger(stoi(s)); string num; stack<NestedInteger> st; for (int i = 0; i < n; i++) { //cout << i << " " << st.size() << "\n"; if (s[i] == '[') { st.push(NestedInteger()); } else if (s[i] == ',') { if (!num.empty())st.top().add(NestedInteger(stoi(num))); num.clear(); } else if (s[i] == ']') { if (!num.empty()) { st.top().add(NestedInteger(stoi(num))); num.clear(); } if (st.size() > 1) { auto now = st.top(); st.pop(); st.top().add(now); } } else num += s[i]; } return st.top(); } string removeKdigits(string num, int k) {//移掉K位数字 stack<char> stk; for (char& ch : num) {//单调不减栈 while (stk.size() > 0 && stk.top() > ch && k > 0) { stk.pop(); --k; } stk.push(ch); } while (k-- > 0) {//尾部弹出 stk.pop(); } string res = ""; while (!stk.empty()) {//倒叙生成 res = stk.top() + res; stk.pop(); } size_t resLen = res.size(), cur = 0; while (cur < resLen) {//去零 if (res[cur] != '0') { break; } cur++; } res = res.substr(cur, resLen - cur); return res == "" ? "0" : res; } bool find132pattern(vector<int>& nums) {//132模式 //贪心+递减栈 size_t numsLen = nums.size(); if (numsLen < 3) { return false; } vector<int> left(nums); for (size_t i = 1; i < numsLen; i++) { left[i] = min(left[i], left[i - 1]); } stack<int> stk; for (int i = numsLen - 1; i > -1; i--) { if (left[i] < nums[i]) { while (!stk.empty() && stk.top() <= left[i]) {//递减栈,从1向上找 stk.pop(); } if (!stk.empty() && stk.top() < nums[i]) {//找到满足<3的就行 return true; } stk.push(nums[i]); } } return false; } vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {//下一个更大元素 I stack<int> stk; vector<int> res; unordered_map<int, int> resMap; for (int& num : nums2) { while (!stk.empty() && stk.top() < num) {//带入栈元素大于栈顶元素,证明找到了右侧更大的 resMap[stk.top()] = num; stk.pop(); } stk.push(num); } while (!stk.empty()) { resMap[stk.top()] = -1; stk.pop(); } for (int& num : nums1) { res.push_back(resMap[num]); } return res; } vector<int> nextGreaterElements(vector<int>& nums) {//下一个更大元素 II int numnsLen = nums.size(); vector<int> res(numnsLen, -1); for (int i = 0; i < numnsLen; i++) { nums.push_back(nums[i]); } stack<int> stk; for (int i = 0; i < 2 * numnsLen; i++) { while (!stk.empty() && nums[i] > nums[stk.top()]) { int id = stk.top(); stk.pop(); if (id < numnsLen) { res[id] = nums[i]; } } stk.push(i); } return res; } vector<int> exclusiveTime(int n, vector<string>& logs) {//函数的独占时间 //关键点:栈顶元素抢占cpu vector<int> res(n, 0); stack<int> stk;//记录id int prev = 0;//上次刷新时间戳 for (string& str : logs) { int cur = 0; int sLen = str.size(); int id = 0, time = 0; string flag; while (cur < sLen) {//获取ID if (str[cur] == ':') { break; } id *= 10; id += str[cur] - '0'; cur++; } cur++; while (cur < sLen) {//获取状态 if (str[cur] == ':') { break; } flag.push_back(str[cur]); cur++; } cur++; while (cur < sLen) {//获取时间 time *= 10; time += str[cur] - '0'; cur++; } if (stk.empty()) { stk.push(id); prev = time; continue; } if (flag == "start") { res[stk.top()] += time - prev; stk.push(id); prev = time; } else { res[id] += time - prev + 1; stk.pop(); prev = time + 1; } } return res; } int calPoints(vector<string>& ops) {//棒球比赛 stack<int> stk; for (string& op : ops) { if (op == "+") { int tmp = stk.top(); stk.pop(); int current = tmp + stk.top(); stk.push(tmp); stk.push(current); } else if (op == "D") { stk.push(2 * stk.top()); } else if (op == "C") { stk.pop(); } else { stk.push(stoi(op)); } } int res = 0; while (!stk.empty()) { res += stk.top(); stk.pop(); } return res; } bool backspaceCompare(string S, string T) {//比较含退格的字符串 stack<char> stkS, stkT; for (char& ch : S) { if (ch == '#') { if (!stkS.empty()) { stkS.pop(); } } else { stkS.push(ch); } } for (char& ch : T) { if (ch == '#') { if (!stkT.empty()) { stkT.pop(); } } else { stkT.push(ch); } } if (stkS.size() != stkT.size()) { return false; } while (!stkS.empty()) { if (stkS.top() != stkT.top()) { return false; } stkS.pop(); stkT.pop(); } return true; } vector<int> asteroidCollision(vector<int>& asteroids) {//行星碰撞 stack<int> stk; int asteroidsCnt = asteroids.size(); int cur = 0; while (cur < asteroidsCnt) { int num = asteroids[cur]; if (stk.empty() || (!stk.empty() && stk.top() * num > 0) || (!stk.empty() && stk.top() < 0 && num > 0)) {//新行星入栈 stk.push(num); } else if (abs(stk.top()) == abs(num)) {//新行星和栈顶行星湮灭 stk.pop(); } else if (abs(stk.top()) < abs(num)) {//栈顶行星消灭 stk.pop(); continue; } cur++; } vector<int> res; while (!stk.empty()) { res.insert(res.begin(), stk.top()); stk.pop(); } return res; } bool isUpper(char c) { return c >= 'A' && c <= 'Z'; } bool isLower(char c) { return c >= 'a' && c <= 'z'; } bool isDigit(char c) { return c >= '0' && c <= '9'; } map<string, int> atomSplit(const string str, int leftCur, int rightCur) { map<string, int> atomMap; string atomName; int cnt = 0, cur = leftCur; while (cur <= rightCur) { char ch = str[cur]; if (isUpper(ch)) { if (!atomName.empty()) {//正常元素 atomMap[atomName] += max(cnt, 1); atomName.clear(); cnt = 0; } atomName += ch; } else if (isLower(ch)) { atomName += ch; } else if (isDigit(ch)) { cnt *= 10; cnt += ch - '0'; } else if (ch == '(') { if (!atomName.empty()) {//括号前元素 atomMap[atomName] += max(cnt, 1); atomName.clear(); cnt = 0; } int newCur = ++cur;//括号内第一个元素头 int bracket = 1; while (cur <= rightCur) { if (str[cur] == '(') { bracket++; } else if (str[cur] == ')') { bracket--; } if (bracket == 0) { break; } cur++; } map<string, int> newAtomMap = atomSplit(str, newCur, cur - 1);//处理括号内 cnt = 0; while (cur + 1 <= rightCur && isDigit(str[cur + 1])) { cnt *= 10; cnt += str[cur + 1] - '0'; cur++; } cnt = max(1, cnt); for (auto& it : newAtomMap) { atomMap[it.first] += it.second * cnt; } cnt = 0; } cur++; } if (!atomName.empty()) { atomMap[atomName] += max(cnt, 1); } return atomMap; } string countOfAtoms(string formula) {//原子的数量 map<string, int> atomMap = atomSplit(formula, 0, formula.size() - 1); //后处理 string res; for (auto& it : atomMap) { res += it.first; if (it.second > 1) { res += to_string(it.second); } } return res; } int scoreOfParentheses(string S) {//括号的分数 stack<int> stk; for (char& ch : S) { if (ch == '(') { stk.push(0); } else { if (stk.top() == 0) { stk.pop(); stk.push(1); } else { int tmp = 0; while (!stk.empty() && stk.top() != 0) { tmp += stk.top(); stk.pop(); } stk.pop(); stk.push(2 * tmp); } } } int res = 0; while (!stk.empty()) { res += stk.top(); stk.pop(); } return res; } int shortestSubarray(vector<int>& nums, int K) {//和至少为 K 的最短子数组 size_t numsLen = nums.size(); vector<int> prefix(numsLen + 1); for (size_t i = 0; i < numsLen; i++) { prefix[i + 1] = prefix[i] + nums[i]; } deque<int> dq; int res = INT_MAX; for (int i = 0; i <= numsLen; i++) { while (!dq.empty() && prefix[i] <= prefix[dq.back()]) { dq.pop_back(); } while (!dq.empty() && prefix[i] >= prefix[dq.front()] + K) { res = min(res, i - dq.front()); dq.pop_front(); } dq.push_back(i); } return res == INT_MAX ? -1 : res; } string removeOuterParentheses(string S) {//删除最外层的括号 stack<int> stk; int sLen = S.size(); int cur = 0; int bracket = 0; while (cur < sLen) { if (bracket == 0) { stk.push(cur - 1); stk.push(cur); } if (S[cur] == '(') { bracket++; } else { bracket--; } cur++; } stk.push(sLen - 1); string res; for (int i = sLen - 1; i > -1; i--) { if (!stk.empty() && i == stk.top()) { stk.pop(); continue; } res = S[i] + res; } return res; } string removeDuplicates(string S) {//删除字符串中的所有相邻重复项 string res; for (char& ch : S) { if (!res.empty() && ch == res.back()) { while (!res.empty() && ch == res.back()) { res.pop_back(); } continue; } res.push_back(ch); } return res; } bool isValid(string s) {//检查替换后的词是否有效 stack<char> stk; for (char& ch : s) { if (ch == 'c') { if (stk.empty() || stk.top() != 'b') { return false; } stk.pop(); if (stk.empty() || stk.top() != 'a') { return false; } stk.pop(); continue; } stk.push(ch); } return stk.empty(); } bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {//验证栈序列 int totalCnt = pushed.size(); int pushCur = 0, popCur = 0; stack<int> stk; while (pushCur < totalCnt) { if (stk.empty() || stk.top() != popped[popCur]) { stk.push(pushed[pushCur++]); } else if (stk.top() == popped[popCur]) { stk.pop(); popCur++; } } while (!stk.empty()) { if (stk.top() != popped[popCur]) { return false; } stk.pop(); popCur++; } return popCur == totalCnt; } int minAddToMakeValid(string S) {//使括号有效的最少添加 stack<char> stk; for (char& ch : S) { if (!stk.empty() && ch == ')' && stk.top() == '(') { stk.pop(); } else { stk.push(ch); } } return stk.size(); } }; int main(int argc, char* argv[]) { Solution mySolution; string a = ".L.R...LR..L.."; string b = "(()())(())"; vector<int> inpt1 = { 1 }; vector<int> inpt2 = { 1, 3, 4, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { { 0, 1, 1, 1, 0, 1 }, { 0, 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1, 0 }, { 1, 0, 0, 1, 0, 0 }, }; mySolution.removeOuterParentheses(b); return 0; } #endif //cookBook-树 #if false class Solution { public: struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} }; int numTrees(int n) {//不同的二叉搜索树 vector<int> dp(n + 1, 0); dp[0] = 1, dp[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { dp[i] += dp[j - 1] * dp[i - j]; } } return dp[n]; } bool isSameTree(TreeNode* p, TreeNode* q) {//相同的树 if (p == nullptr && q == nullptr) { return true; } if ((p == nullptr) ^ (q == nullptr)) { return false; } if (p->val == q->val) { return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } return false; } void recoverTree(TreeNode* root) {//恢复二叉搜索树 vector<int> nums; recoverTreeSubFunc(root, nums); size_t numsLen = nums.size(); int x = -1, y = -1; for (size_t i = 1; i < numsLen; i++) { if (nums[i] < nums[i - 1]) { y = nums[i]; if (x == -1) { x = nums[i - 1]; } else { break; } } } recoverTreeSubFuncRec(root, x, y, 2); return; } void recoverTreeSubFunc(TreeNode* root, vector<int>& nums) {//中序遍历获取 if (root == nullptr) { return; } recoverTreeSubFunc(root->left, nums); nums.push_back(root->val); recoverTreeSubFunc(root->right, nums); return; } void recoverTreeSubFuncRec(TreeNode* root, int x, int y, int cnt) {//中序遍历恢复 if (root == nullptr) { return; } if (root->val == x || root->val == y) { root->val = root->val == x ? y : x; cnt--; if (cnt == 0) { return; } } recoverTreeSubFuncRec(root->left, x, y, cnt); recoverTreeSubFuncRec(root->right, x, y, cnt); return; } bool isSymmetric(TreeNode* root) {//对称二叉树 return isSymmetricCheck(root, root); } bool isSymmetricCheck(TreeNode* leftCur, TreeNode* rightCur) { if (leftCur == nullptr && rightCur == nullptr) { return true; } if ((leftCur == nullptr) ^ (rightCur == nullptr)) { return false; } return leftCur->val == rightCur->val && isSymmetricCheck(leftCur->left, rightCur->right) && isSymmetricCheck(leftCur->right, rightCur->left); } int maxDepth(TreeNode* root) {//二叉树的最大深度 if (root == nullptr) { return 0; } return max(maxDepth(root->left), maxDepth(root->right)) + 1; } vector<vector<int>> levelOrderBottom(TreeNode* root) {//二叉树的层序遍历 II vector<vector<int>> res; if (root == nullptr) { return res; } queue<TreeNode*> que; que.push(root); while (!que.empty()) { size_t queLen = que.size(); vector<int> tmp; while (queLen != 0) { TreeNode* cur = que.front(); que.pop(); queLen--; tmp.push_back(cur->val); if (cur->left != nullptr) { que.push(cur->left); } if (cur->right != nullptr) { que.push(cur->right); } } res.insert(res.begin(), tmp); } return res; } TreeNode* sortedListToBST(ListNode* head) {//有序链表转换二叉搜索树 vector<int> nums; while (head != nullptr) { nums.push_back(head->val); head = head->next; } int numsLen = nums.size(); return sortedListToBSTSub(nums, 0, numsLen); } TreeNode* sortedListToBSTSub(vector<int>& nums, int left, int right) { if (left >= right) { return nullptr; } int mid = left + (right - left) / 2; TreeNode* current = new TreeNode; current->val = nums[mid]; current->left = sortedListToBSTSub(nums, left, mid); current->right = sortedListToBSTSub(nums, mid + 1, right); return current; } int minDepth(TreeNode* root) {//二叉树的最小深度 if (root == nullptr) { return 0; } if (root->left == nullptr && root->right == nullptr) { return 1; } int left = INT_MAX, right = INT_MAX; if (root->left != nullptr) { left = minDepth(root->left); } if (root->right != nullptr) { right = minDepth(root->right); } return min(left, right) + 1; } vector<vector<int>> pathSumBAK(TreeNode* root, int targetSum) {//路径总和 II vector<vector<int>> res; vector<int> tmp; pathSumSubBAK(root, targetSum, res, tmp); return res; } void pathSumSubBAK(TreeNode* root, int targetSum, vector<vector<int>>& res, vector<int>& tmp) { if (root == nullptr) { return; } targetSum -= root->val; tmp.push_back(root->val); if (targetSum == 0 && root->left == nullptr && root->right == nullptr) { res.push_back(tmp); } pathSumSubBAK(root->left, targetSum, res, tmp); pathSumSubBAK(root->right, targetSum, res, tmp); tmp.pop_back(); return; } void flatten(TreeNode* root) {//二叉树展开为链表 if (root == nullptr) { return; } //从后到前的先序遍历 flatten(root->right); if (root->left == nullptr) { return; } flatten(root->left); TreeNode* cur = root->left; while (cur->right != nullptr) { cur = cur->right; } cur->right = root->right; root->right = root->left; root->left = nullptr; return; } vector<int> rightSideView(TreeNode* root) {//二叉树的右视图 vector<int> res; if (root == nullptr) { return res; } queue<TreeNode*> que; que.push(root); while (!que.empty()) { size_t queLen = que.size(); TreeNode* cur = que.back(); res.push_back(cur->val); while (queLen != 0) { cur = que.front(); que.pop(); queLen--; if (cur->left != nullptr) { que.push(cur->left); } if (cur->right != nullptr) { que.push(cur->right); } } } return res; } int sumNumbers(TreeNode* root) {//求根到叶子节点数字之和 int res = 0, tmp = 0; sumNumbersSub(root, tmp, res); return res; } void sumNumbersSub(TreeNode* root, int& tmp, int& res) { if (root == nullptr) { return; } tmp *= 10; tmp += root->val; if (root->left == nullptr && root->right == nullptr) { res += tmp; } sumNumbersSub(root->left, tmp, res); sumNumbersSub(root->right, tmp, res); tmp /= 10; return; } class BSTIterator {//二叉搜索树迭代器 public: BSTIterator(TreeNode* root) { serialize(root); numsLen = nums.size(); } int next() { if (hasNext()) { return nums[cur++]; } return -1; } bool hasNext() { return cur < numsLen; } private: size_t numsLen = 0, cur = 0; vector<int> nums; void serialize(TreeNode* root) { if (root == nullptr) { return; } serialize(root->left); nums.push_back(root->val); serialize(root->right); return; } }; TreeNode* invertTree(TreeNode* root) {//翻转二叉树 if (root == nullptr) { return nullptr; } root->left = invertTree(root->left); root->right = invertTree(root->right); swap(root->left, root->right); return root; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {//二叉搜索树的最近公共祖先 TreeNode* res = root; while (res != nullptr) { if ((p->val < res->val) && (q->val < res->val)) { res = res->left; } else if ((p->val > res->val) && (q->val > res->val)) { res = res->right; } else { break; } } return res; } vector<string> binaryTreePaths(TreeNode* root) {//二叉树的所有路径 vector<string> res; string tmp; binaryTreePathsSub(root, res, tmp); return res; } void binaryTreePathsSub(TreeNode* root, vector<string>& res, string& tmp) { if (root == nullptr) { return; } string tmpCopy = tmp; tmp += "->" + to_string(root->val); if (root->left == nullptr && root->right == nullptr) { res.push_back(tmp.substr(2, tmp.size() - 2)); } binaryTreePathsSub(root->left, res, tmp); binaryTreePathsSub(root->right, res, tmp); tmp = tmpCopy; return; } int rob(TreeNode* root) {//打家劫舍 III unordered_map<TreeNode*, int> nodeMapY, nodeMapN; nodeMapY[nullptr] = 0, nodeMapN[nullptr] = 0; robSub(root, nodeMapY, nodeMapN); return max(nodeMapY[root], nodeMapN[root]); } void robSub(TreeNode* root, unordered_map<TreeNode*, int>& nodeMapY, unordered_map<TreeNode*, int>& nodeMapN) { if (root == nullptr) { return; } robSub(root->left, nodeMapY, nodeMapN); robSub(root->right, nodeMapY, nodeMapN); nodeMapY[root] = nodeMapN[root->left] + nodeMapN[root->right] + root->val; nodeMapN[root] = max(nodeMapN[root->left], nodeMapY[root->left]) + max(nodeMapN[root->right], nodeMapY[root->right]); return; } int sumOfLeftLeaves(TreeNode* root) {//左叶子之和 if (root == nullptr) { return 0; } queue<TreeNode*> que; que.push(root); int res = 0; while (!que.empty()) { TreeNode* cur = que.front(); que.pop(); if (cur->left != nullptr) { if (cur->left->left == nullptr && cur->left->right == nullptr) { res += cur->left->val; } else { que.push(cur->left); } } if (cur->right != nullptr) { if (cur->right->left != nullptr || cur->right->right != nullptr) { que.push(cur->right); } } } return res; } int pathSum(TreeNode* root, int sum) {//路径总和 III int res = 0; unordered_map<int, int> prefix; prefix[0] = 1; pathSumSub(root, sum, res, prefix, 0); return res; } void pathSumSub(TreeNode* root, int sum, int& res, unordered_map<int, int>& prefix, int last) { if (root == nullptr) { return; } int current = last + root->val; if (prefix.count(current - sum) > 0) { res += prefix[current - sum]; } prefix[current]++; pathSumSub(root->left, sum, res, prefix, current); pathSumSub(root->right, sum, res, prefix, current); prefix[current]--; return; } vector<int> findFrequentTreeSum(TreeNode* root) {//出现次数最多的子树元素和 unordered_map<int, int> sumMap; findFrequentTreeSumSub(root, sumMap); int maxCnt = 0; vector<int> res; for (auto& it : sumMap) { if (it.second > maxCnt) { res.clear(); res.push_back(it.first); maxCnt = it.second; } else if (it.second == maxCnt) { res.push_back(it.first); } } return res; } int findFrequentTreeSumSub(TreeNode* root, unordered_map<int, int>& sumMap) { if (root == nullptr) { return 0; } int left = findFrequentTreeSumSub(root->left, sumMap); int right = findFrequentTreeSumSub(root->right, sumMap); int res = left + right + root->val; sumMap[res]++; return res; } int findBottomLeftValue(TreeNode* root) {//找树左下角的值 if (root == nullptr) { return 0; } queue<TreeNode*> que; int res = 0; que.push(root); while (!que.empty()) { int qLen = que.size(); res = que.front()->val; while (qLen > 0) { TreeNode* cur = que.front(); que.pop(); qLen--; if (cur->left != nullptr) { que.push(cur->left); } if (cur->right != nullptr) { que.push(cur->right); } } } return res; } vector<int> largestValues(TreeNode* root) {//在每个树行中找最大值 vector<int> res; if (root == nullptr) { return res; } queue<TreeNode*> que; que.push(root); while (!que.empty()) { int qLen = que.size(); int tmp = que.front()->val; while (qLen > 0) { TreeNode* cur = que.front(); que.pop(); qLen--; tmp = max(tmp, cur->val); if (cur->left != nullptr) { que.push(cur->left); } if (cur->right != nullptr) { que.push(cur->right); } } res.push_back(tmp); } return res; } int findTilt(TreeNode* root) {//二叉树的坡度 int res = 0; findTiltSub(root, res); return res; } int findTiltSub(TreeNode* root, int& res) { if (root == nullptr) { return 0; } int left = findTiltSub(root->left, res); int right = findTiltSub(root->right, res); res += abs(left - right); int sum = root->val + left + right; return sum; } bool isSubtree(TreeNode* s, TreeNode* t) {//另一个树的子树 if (s == nullptr) { return false; } if (isSameTree(s, t)) { return true; } return isSubtree(s->left, t) || isSubtree(s->right, t); } vector<double> averageOfLevels(TreeNode* root) {//二叉树的层平均值 vector<double> res; if (root == nullptr) { return res; } queue<TreeNode*> que; que.push(root); while (!que.empty()) { int qLen = que.size(), qLenBak = qLen; double tmp = 0; while (qLen > 0) { TreeNode* cur = que.front(); que.pop(); qLen--; tmp += cur->val; if (cur->left != nullptr) { que.push(cur->left); } if (cur->right != nullptr) { que.push(cur->right); } } res.push_back(1.0 * tmp / qLenBak); } return res; } int widthOfBinaryTree(TreeNode* root) {//二叉树最大宽度 if (root == nullptr) { return 0; } queue<pair<TreeNode*, unsigned long long>> que; unsigned long long res = 0; que.push(make_pair(root, 1)); while (!que.empty()) { int qLen = que.size(); unsigned long long frontPos = que.front().second, pos = 0; while (qLen > 0) { TreeNode* cur = que.front().first; pos = que.front().second; que.pop(); qLen--; //二叉树子节点编号 if (cur->left) { que.push(make_pair(cur->left, pos * 2)); } if (cur->right) { que.push(make_pair(cur->right, pos * 2 + 1)); } } res = max(pos - frontPos + 1, res); } return (int)res; } bool findTarget(TreeNode* root, int k) {//两数之和 IV - 输入 BST bool res = false; unordered_set<int> valSet; findTargetSub(root, k, valSet, res); return res; } void findTargetSub(TreeNode* root, int k, unordered_set<int>& valSet, bool& res) { if (root == nullptr || res) { return; } if (valSet.count(k - root->val) > 0) { res = true; } valSet.insert(root->val); findTargetSub(root->left, k, valSet, res); findTargetSub(root->right, k, valSet, res); return; } bool leafSimilar(TreeNode* root1, TreeNode* root2) {//叶子相似的树 vector<int> nums1, nums2; leafSimilarSub(root1, nums1); leafSimilarSub(root2, nums2); return nums1 == nums2; } void leafSimilarSub(TreeNode* root, vector<int>& res) { if (root == nullptr) { return; } leafSimilarSub(root->left, res); leafSimilarSub(root->right, res); if (root->left == nullptr && root->right == nullptr) { res.push_back(root->val); } return; } TreeNode* increasingBST(TreeNode* root) {//递增顺序查找树 stack<TreeNode*> stk; increasingBSTSub(root, stk); TreeNode* res = nullptr; while (!stk.empty()) { stk.top()->right = res; stk.top()->left = nullptr; res = stk.top(); stk.pop(); } return res; } void increasingBSTSub(TreeNode* root, stack<TreeNode*>& stk) { if (root == nullptr) { return; } increasingBSTSub(root->left, stk); stk.push(root); increasingBSTSub(root->right, stk); return; } bool isCousins(TreeNode* root, int x, int y) {//二叉树的堂兄弟节点 queue<TreeNode*> que; que.push(root); int level = 0, xLev = -1, yLev = -1; TreeNode* fx = nullptr, * fy = nullptr; while (!que.empty() && (xLev == -1 || yLev == -1)) { int qLen = que.size(); while (qLen > 0 && (xLev == -1 || yLev == -1)) { TreeNode* cur = que.front(); que.pop(); qLen--; if (cur->val == x) { xLev = level; } else if (cur->val == y) { yLev = level; } if (cur->left != nullptr) { que.push(cur->left); if (cur->left->val == x) { fx = cur; } if (cur->left->val == y) { fy = cur; } } if (cur->right != nullptr) { que.push(cur->right); if (cur->right->val == x) { fx = cur; } if (cur->right->val == y) { fy = cur; } } } level++; } return xLev == yLev && fx != fy; } int distributeCoins(TreeNode* root) {//在二叉树中分配硬币 int res = 0; distributeCoinsSub(root, res); return res; } int distributeCoinsSub(TreeNode* root, int& res) { if (root == nullptr) { return 0; } //两侧需要移动步数 int left = distributeCoinsSub(root->left, res); int right = distributeCoinsSub(root->right, res); res += abs(left) + abs(right); return left + right + root->val - 1; } vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {//二叉树中所有距离为 K 的结点 unordered_map<TreeNode*, TreeNode*> parent; distanceKSub(root, nullptr, parent); queue<TreeNode*> que; unordered_set<TreeNode*> vist; vector<int> res; int dist = 0; que.push(target); while (!que.empty() && dist <= k) { int qLen = que.size(); while (qLen--) { TreeNode* cur = que.front(); que.pop(); if (vist.count(cur) > 0) { continue; } vist.insert(cur); if (dist == k) { res.push_back(cur->val); } if (cur->left != nullptr) { que.push(cur->left); } if (cur->right != nullptr) { que.push(cur->right); } if (parent[cur] != nullptr) { que.push(parent[cur]); } } dist++; } return res; } void distanceKSub(TreeNode* root, TreeNode* par, unordered_map<TreeNode*, TreeNode*>& parent) { //转换为图计算 if (root == nullptr) { return; } parent[root] = par; distanceKSub(root->left, root, parent); distanceKSub(root->right, root, parent); return; } int deepestLeavesSum(TreeNode* root) {//层数最深叶子节点的和 int res = 0, maxDepth = 0, currentDepth = 0; deepestLeavesSumSub(root, maxDepth, currentDepth, res); return res; } void deepestLeavesSumSub(TreeNode* root, int& maxDepth, int& currentDepth, int& res) { if (root == nullptr) { return; } currentDepth++; if (currentDepth > maxDepth) { maxDepth = currentDepth; res = 0; } if (currentDepth == maxDepth && root->left == nullptr && root->right == nullptr) { res += root->val; } deepestLeavesSumSub(root->left, maxDepth, currentDepth, res); deepestLeavesSumSub(root->right, maxDepth, currentDepth, res); currentDepth--; return; } TreeNode* lcaDeepestLeaves(TreeNode* root) {//最深叶节点的最近公共祖先 int maxDepth = 0; return lcaDeepestLeavesSub(root, maxDepth); } TreeNode* lcaDeepestLeavesSub(TreeNode* root, int& maxDepth) { if (root == nullptr) { maxDepth = 0; return nullptr; } int leftHt = 0, rightHt = 0; TreeNode* leftNode = lcaDeepestLeavesSub(root->left, leftHt); TreeNode* rightNode = lcaDeepestLeavesSub(root->right, rightHt); maxDepth = max(leftHt, rightHt) + 1; if (leftHt == rightHt) { return root; } if (leftHt > rightHt) { return leftNode; } return rightNode; } int maxAncestorDiff(TreeNode* root) {//节点与其祖先之间的最大差值 int res = 0; maxAncestorDiffSub(root, root->val, root->val, res); return res; } void maxAncestorDiffSub(TreeNode* root, int hi, int lo, int& res) { if (root == nullptr) { return; } res = max(max(abs(hi - root->val), abs(lo - root->val)), res); hi = max(hi, root->val); lo = min(lo, root->val); maxAncestorDiffSub(root->left, hi, lo, res); maxAncestorDiffSub(root->right, hi, lo, res); return; } vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {//删点成林 vector<TreeNode*> res; unordered_set<int> delSet(to_delete.begin(), to_delete.end()); if (delNodesSub(root, delSet, res) != nullptr) { res.push_back(root); } return res; } TreeNode* delNodesSub(TreeNode* root, unordered_set<int>& delSet, vector<TreeNode*>& res) { if (root == nullptr) { return nullptr; } root->left = delNodesSub(root->left, delSet, res); root->right = delNodesSub(root->right, delSet, res); if (delSet.count(root->val) > 0) { if (root->left != nullptr) { res.push_back(root->left); } if (root->right != nullptr) { res.push_back(root->right); } return nullptr; } return root; } bool btreeGameWinningMove(TreeNode* root, int n, int x) {//二叉树着色游戏 int leftCon = 0, rightCon = 0; btreeGameWinningMoveSub(root, x, leftCon, rightCon); int parent = n - leftCon - rightCon - 1; n /= 2; return parent > n || leftCon > n || rightCon > n; } int btreeGameWinningMoveSub(TreeNode* root, int val, int& leftCon, int& rightCon) { if (root == nullptr) { return 0; } int leftCnt = btreeGameWinningMoveSub(root->left, val, leftCon, rightCon); int rightCnt = btreeGameWinningMoveSub(root->right, val, leftCon, rightCon); if (root->val == val) { leftCon = leftCnt; rightCon = rightCnt; } return leftCnt + rightCnt + 1; } TreeNode* recoverFromPreorder(string s) {//从先序遍历还原二叉树 stack<pair<TreeNode*, int>> stk; TreeNode* tmp = new TreeNode; stk.push(make_pair(tmp, -1)); size_t sLen = s.size(); size_t cur = 0; while (cur < sLen) { int level = 0; int nodeVal = 0; while (s[cur] == '-') { level++; cur++; } while (s[cur] <= '9' && s[cur] >= '0') { nodeVal *= 10; nodeVal += s[cur] - '0'; cur++; } tmp = new TreeNode(nodeVal); while (stk.top().second >= level) { stk.pop(); } if (stk.top().first->left == nullptr) { stk.top().first->left = tmp; } else { stk.top().first->right = tmp; } stk.push(make_pair(tmp, level)); } while (!stk.empty()) { tmp = stk.top().first; stk.pop(); } return tmp->left; } int minCameraCover(TreeNode* root) {//监控二叉树 int res = 0; if (minCameraCoverSub(root, res) == 0) { res++; } return res; } int minCameraCoverSub(TreeNode* root, int& res) { //0: 无覆盖, 1: 有摄像头, 2: 覆盖 if (root == nullptr) { return 2; } int leftStat = minCameraCoverSub(root->left, res); int rightStat = minCameraCoverSub(root->right, res); if (leftStat == 2 && rightStat == 2) { return 0; } if (leftStat == 0 || rightStat == 0) { res++; return 1; } if (leftStat == 1 || rightStat == 1) { return 2; } return -1; } vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) {//树中距离之和 if (N == 0 || edges.empty()) { return { 0 }; } vector<int> cnt(N, 1); vector<int> res(N); vector<vector<int>> graph(N); for (vector<int>& edge : edges) { graph[edge[0]].push_back(edge[1]); graph[edge[1]].push_back(edge[0]); } sumOfDistancesInTreeSub1(0, -1, graph, cnt, res); sumOfDistancesInTreeSub2(0, -1, graph, cnt, res); return res; } void sumOfDistancesInTreeSub1(int child, int parent, vector<vector<int>>& graph, vector<int>& cnt, vector<int>& res) { for (int i = 0; i < graph[child].size(); i++) { if (graph[child][i] != parent) { sumOfDistancesInTreeSub1(graph[child][i], child, graph, cnt, res); cnt[child] += cnt[graph[child][i]]; res[child] += res[graph[child][i]] + cnt[graph[child][i]]; } } return; } void sumOfDistancesInTreeSub2(int child, int parent, vector<vector<int>>& graph, vector<int>& cnt, vector<int>& res) { for (int i = 0; i < graph[child].size(); i++) { if (parent != graph[child][i]) { res[graph[child][i]] = res[child] - cnt[graph[child][i]] + res.size() - cnt[graph[child][i]];//先计算出根节点的子节点,然后再递归去算子节点的子节点 sumOfDistancesInTreeSub2(graph[child][i], child, graph, cnt, res); } } return; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "1-2--3--4-5--6--7"; string b = "(()())(())"; vector<int> inpt1 = { 1 }; vector<int> inpt2 = { 1, 3, 4, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { { 0, 1, 1, 1, 0, 1 }, { 0, 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1, 0 }, { 1, 0, 0, 1, 0, 0 }, }; mySolution.recoverFromPreorder(a); return 0; } #endif //cookBook-动态规划 #if false class Solution { public: int integerBreak(int n) {//整数拆分 vector<int> dp(n + 1, 0); for (int i = 2; i <= n; i++) { int tmp = 0; for (int j = 1; j < i; j++) { tmp = max(tmp, max(j * (i - j), j * dp[i - j])); } dp[i] = tmp; } return dp[n]; } bool canPartition(vector<int>& nums) {//分割等和子集 size_t numsLen = nums.size(); if (numsLen < 2) { return false; } int target = 0, maxVal = 0; for (int& num : nums) { target += num; maxVal = max(maxVal, num); } if (target % 2 == 1 || maxVal > target / 2) { return false; } target /= 2; vector<vector<bool>> dp(numsLen, vector<bool>(target + 1, false)); //dp[i][j]: 截止到下标i,是否有恰好等于j的和 for (int i = 0; i < numsLen; i++) { dp[i][0] = true; } dp[0][nums[0]] = true; for (int i = 1; i < numsLen; i++) { int cur = nums[i]; for (int j = 0; j < cur; j++) { dp[i][j] = dp[i - 1][j]; } for (int j = cur; j <= target; j++) { dp[i][j] = dp[i - 1][j] | dp[i - 1][j - cur]; } } return dp[numsLen - 1][target]; } int eraseOverlapIntervals(vector<vector<int>>& intervals) {//无重叠区间 size_t intvCnt = intervals.size(); if (intvCnt < 2) { return 0; } sort(intervals.begin(), intervals.end()); vector<int> dp(intvCnt, 1); for (int i = 1; i < intvCnt; i++) { for (int j = 0; j < i; j++) { if (intervals[j][1] <= intervals[i][0]) { dp[i] = max(dp[i], dp[j] + 1); } } } return intvCnt - *max_element(dp.begin(), dp.end()); } int findMaxForm(vector<string>& strs, int m, int n) {//一和零 vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (string& str : strs) { pair<int, int> cnt = findMaxFormSub(str); int zeros = cnt.first, ones = cnt.second; for (int i = m; i >= zeros; i--) { for (int j = n; j >= ones; j--) { dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1); } } } return dp[m][n]; } pair<int, int> findMaxFormSub(string& str) { int zero = 0, one = 0; for (char& ch : str) { if (ch == '0') { zero++; } else { one++; } } return { zero, one }; } int minHeightShelves(vector<vector<int>>& books, int shelf_width) {//填充书架 int bookCnt = books.size(); vector<int> dp(bookCnt + 1, INT_MAX); dp[books.size()] = 0; for (int i = bookCnt - 1; i > -1; i--) { int maxHeight = 0; int leftWt = shelf_width; for (int j = i; j < bookCnt && leftWt >= books[j][0]; j++) { maxHeight = max(maxHeight, books[j][1]); dp[i] = min(dp[i], dp[j + 1] + maxHeight); leftWt -= books[j][0]; } } return dp[0]; } int lastStoneWeightII(vector<int>& stones) {//最后一块石头的重量 II int stoneCnt = stones.size(); int target = 0, sum = 0; for (int& stone : stones) { sum += stone; } target = sum / 2; vector<int> dp(target + 1); for (int& stone : stones) { for (int j = target; j >= stone; j--) { dp[j] = max(dp[j], dp[j - stone] + stone); } } return sum - dp[target] * 2; } int numMusicPlaylists(int N, int L, int K) {//播放列表的数量 const int divider = 1000000007; //令 dp[i][j] 为播放列表长度为 i 包含恰好 j 首不同歌曲的数量 vector<vector<long long>> dp(L + 1, vector<long long>(N + 1, 0)); dp[0][0] = 1; for (int i = 1; i <= L; i++) { for (int j = 1; j <= N; j++) { dp[i][j] += dp[i - 1][j - 1] * (N - j + 1); dp[i][j] += max(0, j - K) * dp[i - 1][j]; dp[i][j] %= divider; } } return (int)dp[L][N]; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "1-2--3--4-5--6--7"; string b = "(()())(())"; vector<int> inpt1 = { 1 }; vector<int> inpt2 = { 1, 3, 4, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { { 0, 1, 1, 1, 0, 1 }, { 0, 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1, 0 }, { 1, 0, 0, 1, 0, 0 }, }; mySolution; return 0; } #endif //cookBook-DFS, BFS #if false class Solution { public: vector<string> restoreIpAddresses(string s) {//复原 IP 地址 int sLen = s.size(); vector<string> res; if (sLen < 4) { return res; } vector<int> ipAddr; restoreIpAddressesSub(res, ipAddr, s, 0, sLen); return res; } void restoreIpAddressesSub(vector<string>& res, vector<int>& ipAddr, string& s, int cur, int sLen) { if (ipAddr.size() == 4) { if (cur == sLen) { res.push_back(restoreIpAddressesSub2(ipAddr)); } return; } if (cur == sLen) { return; } int tmp = 0; if (s[cur] == '0') { ipAddr.push_back(0); restoreIpAddressesSub(res, ipAddr, s, cur + 1, sLen); ipAddr.pop_back(); return; } while (cur < sLen) { tmp *= 10; tmp += s[cur] - '0'; if (tmp < 256) { ipAddr.push_back(tmp); restoreIpAddressesSub(res, ipAddr, s, cur + 1, sLen); ipAddr.pop_back(); } else { break; } cur++; } return; } string restoreIpAddressesSub2(vector<int>& ipAddr) { string res; for (int& num : ipAddr) { res += to_string(num) + '.'; } res.pop_back(); return res; } vector<vector<int>> combine(int n, int k) {//组合 vector<vector<int>> res; vector<int> tmp; combineSub(res, tmp, k, 1, n); return res; } void combineSub(vector<vector<int>>& res, vector<int>& tmp, int k, int cur, int n) { if (tmp.size() + (n - cur + 1) < k) { return; } if (tmp.size() == k) { res.push_back(tmp); return; } if (cur == n + 1) { return; } tmp.push_back(cur); combineSub(res, tmp, k, cur + 1, n); tmp.pop_back(); combineSub(res, tmp, k, cur + 1, n); return; } vector<int> grayCode(int n) {//格雷编码 vector<int> res(1, 0); int cnt = pow(2, n); for (int i = 1; i < cnt; i++) { res.push_back(i ^ (i >> 1)); } return res; } vector<vector<int>> permuteUnique(vector<int>& nums) {//全排列 II vector<vector<int>> res; vector<int> tmp; vector<bool> vist(nums.size(), false); sort(nums.begin(), nums.end()); permuteUniqueSub(res, nums, tmp, 0, nums.size(), vist); return res; } void permuteUniqueSub(vector<vector<int>>& res, vector<int>& nums, vector<int>& tmp, int cur, int numCnt, vector<bool>& vist) { if (cur == numCnt) { res.push_back(tmp); return; } for (int i = 0; i < numCnt; i++) { if (vist[i] || (i > 0 && nums[i] == nums[i - 1] && !vist[i - 1])) {//最后一个是剪枝 continue; } vist[i] = true; tmp.push_back(nums[i]); permuteUniqueSub(res, nums, tmp, cur + 1, nums.size(), vist); vist[i] = false; tmp.pop_back(); } return; } void solveSudoku(vector<vector<char>>& board) {//解数独 //记录某个数字是否存在 vector<vector<bool>> rolExist(9, vector<bool>(9, false)); vector<vector<bool>> colExist(9, vector<bool>(9, false)); vector<vector<vector<bool>>> blockExist(3, vector<vector<bool>>(3, vector<bool>(9, false))); vector<pair<int, int>> pos; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') { pos.push_back(make_pair(i, j)); } else { int tmp = board[i][j] - '0' - 1;//范围:1-9 rolExist[i][tmp] = true; colExist[j][tmp] = true; blockExist[i / 3][j / 3][tmp] = true; } } } bool valid = false; solveSudokuSub(board, rolExist, colExist, blockExist, pos, 0, valid); } void solveSudokuSub(vector<vector<char>>& board, vector<vector<bool>>& rolExist, vector<vector<bool>>& colExist, vector<vector<vector<bool>>>& blockExist, vector<pair<int, int>>& pos, int cur, bool& valid) { if (cur == pos.size()) { valid = true; return; } int rol = pos[cur].first, col = pos[cur].second; for (int i = 0; i < 9 && !valid; i++) { if (!rolExist[rol][i] && !colExist[col][i] && !blockExist[rol / 3][col / 3][i]) { rolExist[rol][i] = true; colExist[col][i] = true; blockExist[rol / 3][col / 3][i] = true; board[rol][col] = i + 1 + '0';//直接改棋盘,不用回溯,因为已经保存在三个bool数组中 solveSudokuSub(board, rolExist, colExist, blockExist, pos, cur + 1, valid); rolExist[rol][i] = false; colExist[col][i] = false; blockExist[rol / 3][col / 3][i] = false; } } return; } vector<vector<string>> solveNQueens(int n) {//N 皇后 vector<string> tmp(n, string(n, '.')); vector<vector<string>> res; vector<bool> colExist(n, false), LLExist(2 * n - 1, false), LRExist(2 * n - 1, false); solveNQueensSub(res, tmp, colExist, LLExist, LRExist, n, 0); return res; } void solveNQueensSub(vector<vector<string>>& res, vector<string>& tmp, vector<bool>& colExist, vector<bool>& LLExist, vector<bool>& LRExist, int n, int pos) { if (pos == n) {//在第i行安置皇后,试探皇后在j列 res.push_back(tmp); return; } for (int i = 0; i < n; i++) { if (!colExist[i] && !LRExist[i + pos] && !LLExist[n - 1 - i + pos]) { colExist[i] = true; LRExist[i + pos] = true; LLExist[n - 1 - i + pos] = true; tmp[i][pos] = 'Q'; solveNQueensSub(res, tmp, colExist, LLExist, LRExist, n, pos + 1); tmp[i][pos] = '.'; colExist[i] = false; LRExist[i + pos] = false; LLExist[n - 1 - i + pos] = false; } } return; } int totalNQueens(int n) {//N皇后 II int res = 0; vector<bool> colExist(n, false), LLExist(2 * n - 1, false), LRExist(2 * n - 1, false); totalNQueensSub(res, colExist, LLExist, LRExist, n, 0); return res; } void totalNQueensSub(int& res, vector<bool>& colExist, vector<bool>& LLExist, vector<bool>& LRExist, int n, int pos) { if (pos == n) { res++; return; } for (int i = 0; i < n; i++) { if (!colExist[i] && !LRExist[pos + i] && !LLExist[n - 1 - i + pos]) { colExist[i] = true; LRExist[pos + i] = true; LLExist[n - 1 - i + pos] = true; totalNQueensSub(res, colExist, LLExist, LRExist, n, pos + 1); colExist[i] = false; LRExist[pos + i] = false; LLExist[n - 1 - i + pos] = false; } } } //string getPermutation(int n, int k) {//排列序列 // //DFS暴力超时 // vector<bool> vist(n, false); // vector<string> strSet; // string tmp; // getPermutationSub(strSet, tmp, vist, 0, n); // return strSet[k - 1]; //} //void getPermutationSub(vector<string>& strSet, string& tmp, vector<bool>& vist, int pos, int n) { // if (pos == n) { // strSet.push_back(tmp); // } // for (int i = 0; i < n; i++) { // if (!vist[i]) { // tmp.push_back(i + 1 + '0'); // vist[i] = true; // getPermutationSub(strSet, tmp, vist, pos + 1, n); // vist[i] = false; // tmp.pop_back(); // } // } // return; //} string getPermutation(int n, int k) {//排列序列 vector<int> frac(n); frac[0] = 1; for (int i = 1; i < n; i++) { frac[i] = i * frac[i - 1]; } k--; vector<int> valid(n + 1, 1); string res; for (int i = 1; i <= n; i++) { int order = k / frac[n - i] + 1; for (int j = 1; j <= n; j++) { order -= valid[j]; if (!order) { res += '0' + j; valid[j] = 0; break; } } k %= frac[n - i]; } return res; } bool isAdditiveNumber(string str) {//累加数 //依次取一个数 vector<long double> tmp; return isAdditiveNumberSub(str, tmp); } bool isAdditiveNumberSub(string str, vector<long double>& tmp) { int cnt = tmp.size(); if (cnt >= 3 && tmp[cnt - 1] != tmp[cnt - 2] + tmp[cnt - 3]) { return false; } int strLen = str.size(); if (strLen == 0 && cnt >= 3) { return true; } for (int i = 0; i < strLen; i++) { string cur = str.substr(0, i + 1); if (cur[0] == '0' && cur.size() != 1) { break; } tmp.push_back(stold(cur)); if (isAdditiveNumberSub(str.substr(i + 1), tmp)) { return true; } tmp.pop_back(); } return false; } int countNumbersWithUniqueDigits(int n) {//计算各个位数不同的数字个数 if (n == 0) { return 1; } int res = 10, uniq = 9, avail = 9; while (n > 1 && avail > 0) { uniq *= avail; res += uniq; avail--; n--; } return res; } vector<int> lexicalOrder(int n) {//字典序排数 vector<int> res; for (int i = 1; i <= 9; i++) { lexicalOrderSub(res, i, n); } return res; } void lexicalOrderSub(vector<int>& res, int current, int n) { if (current > n) { return; } res.push_back(current); for (int i = 0; i <= 9; i++) { lexicalOrderSub(res, current * 10 + i, n); } return; } int findTargetSumWays(vector<int>& nums, int target) {//目标和--暴力DFS int res = 0; int numsLen = nums.size(); findTargetSumWaysSub(nums, target, 0, numsLen, 0, res); return res; } void findTargetSumWaysSub(vector<int>& nums, int& target, int cur, int& numsLen, int acc, int& res) { if (cur == numsLen) { if (acc == target) { res++; } return; } findTargetSumWaysSub(nums, target, cur + 1, numsLen, acc + nums[cur], res); findTargetSumWaysSub(nums, target, cur + 1, numsLen, acc - nums[cur], res); return; } int minMutation(string start, string end, vector<string>& bank) {//最小基因变化 unordered_map<string, bool> vist; string current = start; for (string& str : bank) { vist[str] = false; } vist[current] = true; int res = INT_MAX; minMutationSub(bank, vist, current, end, res, 0); return res == INT_MAX ? -1 : res; } void minMutationSub(vector<string>& bank, unordered_map<string, bool>& vist, string current, string& end, int& res, int tmp) { if (current == end) { res = min(res, tmp); return; } for (string& str : bank) { if (!vist[str]) { if (minMutationCheck(current, str) == 1) { vist[str] = true; minMutationSub(bank, vist, str, end, res, tmp + 1); vist[str] = false; } } } return; } int minMutationCheck(string& str1, string& str2) { int res = 0; int sLen = str1.size(); for (int i = 0; i < sLen; i++) { if (str1[i] != str2[i]) { res++; } } return res; } vector<vector<int>> findSubsequences(vector<int>& nums) {//递增子序列 vector<vector<int>> res; vector<int> tmp; findSubsequencesSub(res, tmp, nums, 0, INT_MIN); return res; } void findSubsequencesSub(vector<vector<int>>& res, vector<int>& tmp, vector<int>& nums, int cur, int last) { if (cur == nums.size()) { if (tmp.size() > 1) { res.push_back(tmp); } return; } if (nums[cur] >= last) { tmp.push_back(nums[cur]); findSubsequencesSub(res, tmp, nums, cur + 1, nums[cur]); tmp.pop_back(); } if (nums[cur] != last) { findSubsequencesSub(res, tmp, nums, cur + 1, last); } return; } int countArrangement(int n) {//优美的排列 vector<bool> vist(n + 1, false); int res = 0; countArrangementSub(vist, res, 1, n); return res; } void countArrangementSub(vector<bool>& vist, int& res, int cur, int n) { if (cur > n) { res++; return; } for (int i = 1; i <= n; i++) { if (!vist[i] && (cur % i == 0 || i % cur == 0)) { vist[i] = true; countArrangementSub(vist, res, cur + 1, n); vist[i] = false; } } return; } vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {//扫雷游戏 size_t rol = board.size(), col = board[0].size(); vector<vector<bool>> vist(rol, vector<bool>(col, false)); queue<pair<int, int>> que; vector<vector<int>> dir = { {-1, 0}, {0, 1}, {1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1} }; que.push(make_pair(click[0], click[1])); while (!que.empty()) { int rolCur = que.front().first, colCur = que.front().second; que.pop(); if (vist[rolCur][colCur]) { continue; } vist[rolCur][colCur] = true; if (board[rolCur][colCur] == 'M') { board[rolCur][colCur] = 'X'; return board; } int mineCnt = 0; for (int i = 0; i < 8; i++) {//确定地雷数目 int tmpRol = rolCur + dir[i][0]; int tmpCol = colCur + dir[i][1]; if (tmpRol < 0 || tmpRol >= rol || tmpCol < 0 || tmpCol >= col) { continue; } if (board[tmpRol][tmpCol] == 'M') { mineCnt++; continue; } } board[rolCur][colCur] = mineCnt == 0 ? 'B' : mineCnt + '0'; if (board[rolCur][colCur] != 'B') { //只有周边没有地雷的情况下,周围的方块才会被添加 continue; } for (int i = 0; i < 8; i++) {//添加周围方块 int tmpRol = rolCur + dir[i][0]; int tmpCol = colCur + dir[i][1]; if (tmpRol < 0 || tmpRol >= rol || tmpCol < 0 || tmpCol >= col) { continue; } que.push(make_pair(tmpRol, tmpCol)); } } return board; } bool pyramidTransition(string bottom, vector<string>& allowed) {//金字塔转换矩阵 int heit = bottom.size(); //构建金字塔 string str; vector<string> tower; for (int i = 1; i < heit; i++) { str.push_back('.'); tower.push_back(str); } tower.push_back(bottom); int total = (heit - 1) * heit / 2; bool res = false; //构建坐标哈希表 unordered_map<int, pair<int, int>> curMap; heit--; int cur = 0; while (heit > -1) { for (int i = 0; i < heit; i++) { curMap[cur] = make_pair(heit - 1, i); cur++; } heit--; } pyramidTransitionSub(allowed, tower, res, 0, total, curMap, allowed.size()); return res; } void pyramidTransitionSub(vector<string>& allowed, vector<string>& tower, bool& res, int cur, int total, unordered_map<int, pair<int, int>>& curMap, int listCnt) { if (cur == total) { res = true; return; } int rolCur = curMap[cur].first, colCur = curMap[cur].second; char targetL = tower[rolCur + 1][colCur], targetR = tower[rolCur + 1][colCur + 1]; for (int i = 0; i < listCnt && !res; i++) {//剪枝,找到答案就返回 if (allowed[i][0] == targetL && allowed[i][1] == targetR) { tower[rolCur][colCur] = allowed[i][2]; pyramidTransitionSub(allowed, tower, res, cur + 1, total, curMap, listCnt); tower[rolCur][colCur] = '.'; } } return; } vector<string> letterCasePermutation(string s) {//字母大小写全排列 int cur = s.size() - 1; vector<string> res; res.push_back(""); string tmp; while (cur >= 0) { if (isalpha(s[cur])) { vector<string> resCopy = res; res.clear(); for (string& str : resCopy) { res.push_back((char)toupper(s[cur]) + tmp + str); res.push_back((char)tolower(s[cur]) + tmp + str); } tmp.clear(); } else { tmp = s[cur] + tmp; } cur--; } for (string& str : res) { str = tmp + str; } return res; } int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {//大礼包 int res = INT_MAX; int initCost = 0; for (int i = 0; i < price.size(); i++) { initCost += price[i] * needs[i]; } shoppingOffersSub(price, special, needs, res, initCost, 0); return res; } void shoppingOffersSub(vector<int>& price, vector<vector<int>>& special, vector<int> needs, int& res, int cost, int cur) { if (cur == special.size()) { res = min(res, cost); return; } //选择当前的 vector<int> needsCopy(needs); bool chose = true; int currentCost = cost; for (int i = 0; i < needs.size(); i++) { if (needs[i] < special[cur][i]) { chose = false; break; } needsCopy[i] -= special[cur][i]; currentCost -= special[cur][i] * price[i]; } currentCost += special[cur][needs.size()]; if (chose) { shoppingOffersSub(price, special, needsCopy, res, currentCost, cur); } //不选择当前的 shoppingOffersSub(price, special, needs, res, cost, cur + 1); return; } string crackSafe(int n, int k) { int kn = pow(k, n), kn_1 = pow(k, n - 1);//将所有n-1位数作为节点的节点个数 vector<int> num(kn_1, k - 1);//表示k^(n-1)个节点的下一位可以从k-1选到0,当前索引处对应的元素值表示该节点已经把比元素值大的值都作为下一数字添加过了 string s(kn + (n - 1), '0');//字符串初始化,(结果一定是kn+n-1位) for (int i = n - 1, node = 0; i < s.size(); ++i) {//i从n-1开始递增 (第一个密码是n-1个0(00...为起始点)) s[i] = num[node]-- + '0';//更新字符串。先运算 再--,表示下一次该节点要选的下一数字 node = node * k - (s[i - (n - 1)] - '0') * kn_1 + num[node] + 1;//更新当前节点。 //左移操作:1.*k,2.减去左侧超出的一位代表的数字(这位数字已经到了k^(n-1)上,所以后面×一个k(n-1)),3.加上右边进来的新数字(刚才-1用于下次的选路径,但这次的节点还没更新呢,要把这个1加回来) } return s; } vector<int> splitIntoFibonacci(string s) {//将数组拆分成斐波那契序列 vector<int> res; bool done = false; splitIntoFibonacciSub(res, s, 0, s.size(), done); return res; } void splitIntoFibonacciSub(vector<int>& res, string& s, int cur, int sLen, bool& done) { if (cur == sLen && res.size() > 2) { done = true; } int tmp = 0; for (int i = cur; i < sLen && !done; i++) { tmp *= 10; tmp += s[i] - '0'; if (res.size() < 2 || (long(res[res.size() - 2]) + long(res[res.size() - 1]) < INT_MAX && res[res.size() - 2] + res[res.size() - 1] == tmp)) { res.push_back(tmp); splitIntoFibonacciSub(res, s, i + 1, sLen, done); if (done) { break; } res.pop_back(); } if (tmp == 0 || tmp > INT_MAX / 10) { break; } } } vector<int> eventualSafeNodes(vector<vector<int>>& graph) {//找到最终的安全状态 vector<int> res; int nodeCnt = graph.size(); vector<int> memo(nodeCnt, 0);//记忆节点状态0 : 未知, 1 : 有环, 2 : 无环 for (int i = 0; i < nodeCnt; i++) { vector<bool> vist(nodeCnt, false); vist[i] = true; if (!eventualSafeNodesSub(graph, vist, memo, i)) {//是否有环 res.push_back(i); } } return res; } bool eventualSafeNodesSub(vector<vector<int>>& graph, vector<bool>& vist, vector<int>& memo, int cur) { if (graph[cur].size() == 0) { memo[cur] = 2; return false; } for (int& i : graph[cur]) { if (vist[i]) {//访问过,有环 memo[i] = 1; return true; } if (memo[i] == 2) {//待访问节点确定无环 continue; } vist[i] = true; if (memo[i] == 1 || eventualSafeNodesSub(graph, vist, memo, i)) { memo[i] = 1; return true; } vist[i] = false; } memo[cur] = 2; return false; } vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {//喧闹和富有 int peopleCnt = quiet.size(); vector<int> res(peopleCnt, -1), inDegree(peopleCnt, 0); vector<vector<int>> inferiorGraph(peopleCnt); for (vector<int>& rich : richer) {//比较穷的邻居 inferiorGraph[rich[0]].push_back(rich[1]); inDegree[rich[1]]++;//比这个邻居更富的人数 } queue<int> que; for (int i = 0; i < peopleCnt; i++) { if (inDegree[i] == 0) {//最富的 que.push(i); } res[i] = i; } while (!que.empty()) { int cur = que.front(); que.pop(); for (int& neigh : inferiorGraph[cur]) { if (quiet[res[cur]] < quiet[res[neigh]]) {//更新更安静的 res[neigh] = res[cur]; } inDegree[neigh]--; if (inDegree[neigh] == 0) { que.push(neigh); } } } return res; } int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {//公交路线 if (source == target) { return 0; } int busCnt = routes.size(); unordered_map<int, unordered_set<int>> graph; for (int i = routes.size() - 1; i > -1; i--) {//站为节点 for (int& j : routes[i]) { graph[j].insert(i); } } queue<int> que; int level = 0; vector<bool> vist(busCnt, false); que.push(source); while (!que.empty()) { level++; for (int i = que.size(); i > 0; i--) { int cur = que.front(); que.pop(); for (const int& bus : graph[cur]) { if (vist[bus]) { continue; } vist[bus] = true; for (int& stop : routes[bus]) { if (stop == target) { return level; } que.push(stop); } } } } return -1; } int numEnclaves(vector<vector<int>>& grid) {//飞地的数量 int rolSize = grid.size(), colSize = grid[0].size(); if (rolSize == 1 || colSize == 1) { return 0; } int res = 0; vector<vector<bool>> vist(rolSize, vector<bool>(colSize, false)); vector<vector<int>> dir = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; queue<pair<int, int>> que; for (int i = 0; i < rolSize; i++) { if (grid[i][0] == 1) { que.push(make_pair(i, 0)); } if (grid[i][colSize - 1] == 1) { que.push(make_pair(i, colSize - 1)); } } for (int i = 0; i < colSize; i++) { if (grid[0][i] == 1) { que.push(make_pair(0, i)); } if (grid[rolSize - 1][i] == 1) { que.push(make_pair(rolSize - 1, i)); } } while (!que.empty()) { int rolCur = que.front().first, colCur = que.front().second; que.pop(); if (vist[rolCur][colCur]) { continue; } vist[rolCur][colCur] = true; grid[rolCur][colCur] = 0; for (int i = 0; i < 4; i++) { int tmpRol = rolCur + dir[i][0], tmpCol = colCur + dir[i][1]; if (tmpRol < 0 || tmpRol == rolSize || tmpCol < 0 || tmpCol == colSize) { continue; } if (grid[tmpRol][tmpCol] == 1) { que.push(make_pair(tmpRol, tmpCol)); } } } for (int i = 0; i < rolSize; i++) { for (int j = 0; j < colSize; j++) { res += grid[i][j]; } } return res; } int closedIsland(vector<vector<int>>& grid) {//统计封闭岛屿的数目 int rolSize = grid.size(), colSize = grid[0].size(); if (rolSize == 1 || colSize == 1) { return 0; } int res = 0; vector<vector<bool>> vist(rolSize, vector<bool>(colSize, false)); vector<vector<int>> dir = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; queue<pair<int, int>> que; //消除地图周围的陆地 for (int i = 0; i < rolSize; i++) { if (grid[i][0] == 0) { closedIslandSub(grid, vist, i, 0, rolSize, colSize); } if (grid[i][colSize - 1] == 0) { closedIslandSub(grid, vist, i, colSize - 1, rolSize, colSize); } } for (int i = 0; i < colSize; i++) { if (grid[0][i] == 0) { closedIslandSub(grid, vist, 0, i, rolSize, colSize); } if (grid[rolSize - 1][i] == 0) { closedIslandSub(grid, vist, rolSize - 1, i, rolSize, colSize); } } //统计陆地数量 for (int i = 0; i < rolSize; i++) { for (int j = 0; j < colSize; j++) { if (grid[i][j] == 0) { res++; closedIslandSub(grid, vist, i, j, rolSize, colSize); } } } return res; } inline void closedIslandSub(vector<vector<int>>& grid, vector<vector<bool>>& vist, int rolCur, int colCur, int rolSize, int colSize) { vector<vector<int>> dir = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; queue<pair<int, int>> que; que.push(make_pair(rolCur, colCur)); while (!que.empty()) { int rolCur = que.front().first, colCur = que.front().second; que.pop(); if (vist[rolCur][colCur]) { continue; } vist[rolCur][colCur] = true; grid[rolCur][colCur] = 1; for (int i = 0; i < 4; i++) { int tmpRol = rolCur + dir[i][0], tmpCol = colCur + dir[i][1]; if (tmpRol < 0 || tmpRol == rolSize || tmpCol < 0 || tmpCol == colSize) { continue; } if (grid[tmpRol][tmpCol] == 0) { que.push(make_pair(tmpRol, tmpCol)); } } } return; } int numTilePossibilities(string str) {//活字印刷 int sLen = str.size(); vector<bool> vist(sLen, false); sort(str.begin(), str.end()); int res = 0; numTilePossibilitiesSub(str, vist, res, sLen); return res; } void numTilePossibilitiesSub(string& str, vector<bool>& vist, int& res, int& sLen) { for (int i = 0; i < sLen; i++) { if (i > 0 && str[i - 1] == str[i] && !vist[i - 1]) {//排序后剪枝 continue; } if (!vist[i]) { vist[i] = true; res++; numTilePossibilitiesSub(str, vist, res, sLen); vist[i] = false; } } return; } int uniquePathsIII(vector<vector<int>>& grid) {//不同路径 III int rolSize = grid.size(), colSize = grid[0].size(); vector<vector<int>> dir = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; pair<int, int> startPoint, endPoint; int blankCnt = 0; for (int i = 0; i < rolSize; i++) { for (int j = 0; j < colSize; j++) { if (grid[i][j] == 1) { startPoint = make_pair(i, j); } if (grid[i][j] == 2) { endPoint = make_pair(i, j); } if (grid[i][j] == 0) { blankCnt++; } } } int res = 0; vector<vector<bool>> vist(rolSize, vector<bool>(colSize, false)); uniquePathsIIISub(grid, vist, dir, res, rolSize, colSize, endPoint, startPoint, blankCnt); return res; } void uniquePathsIIISub(vector<vector<int>>& grid, vector<vector<bool>>& vist, vector<vector<int>>& dir, int& res, int& rolSize, int& colSize, pair<int, int>& endPoint, pair<int, int> startPoint, int blankCnt) { if (startPoint.first == endPoint.first && startPoint.second == endPoint.second) { if (blankCnt == -1) { res++; } return; } for (int i = 0; i < 4; i++) { int tmpRol = startPoint.first + dir[i][0], tmpCol = startPoint.second + dir[i][1]; if (tmpRol < 0 || tmpRol == rolSize || tmpCol < 0 || tmpCol == colSize) { continue; } if (vist[tmpRol][tmpCol]) { continue; } vist[tmpRol][tmpCol] = true; if (grid[tmpRol][tmpCol] == 0 || grid[tmpRol][tmpCol] == 2) { uniquePathsIIISub(grid, vist, dir, res, rolSize, colSize, endPoint, make_pair(tmpRol, tmpCol), blankCnt - 1); } vist[tmpRol][tmpCol] = false; } return; } int numSquarefulPerms(vector<int>& nums) {//正方形数组的数目 vector<bool> vist(nums.size(), false); int res = 0; vector<int> tmp; sort(nums.begin(), nums.end()); numSquarefulPermsSub(nums, tmp, res, vist); return res; } void numSquarefulPermsSub(vector<int>& nums, vector<int>& tmp, int& res, vector<bool>& vist) { if (tmp.size() == nums.size()) { res++; return; } for (int i = 0; i < nums.size(); i++) { if (vist[i] || i > 0 && nums[i] == nums[i - 1] && !vist[i - 1]) { continue; } vist[i] = true; if (tmp.size() < 1 || (tmp[tmp.size() - 1] + nums[i] == (int)sqrt(tmp[tmp.size() - 1] + nums[i]) * (int)sqrt(tmp[tmp.size() - 1] + nums[i]))) { tmp.push_back(nums[i]); numSquarefulPermsSub(nums, tmp, res, vist); tmp.pop_back(); } vist[i] = false; } return; } int shortestPathAllKeys(vector<string>& grid) {//获取所有钥匙的最短路径 int rolSize = grid.size(), colSize = grid[0].size(); vector<vector<int>> dir = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; int keyCnt = 0; queue<vector<int>> que; for (int i = 0; i < rolSize; i++) { for (int j = 0; j < colSize; j++) { if (grid[i][j] >= 'a' && grid[i][j] <= 'z') { keyCnt++; } else if (grid[i][j] == '@') { que.push({ i, j, 0 }); } } } int target = (1 << keyCnt) - 1; vector<vector<vector<int>>> distance(rolSize, vector<vector<int>>(colSize, vector<int>(target, -1))); distance[que.front()[0]][que.front()[1]][0] = 0; while (!que.empty()) { vector<int> cur = que.front(); que.pop(); for (int i = 0; i < 4; i++) { int tmpRol = cur[0] + dir[i][0], tmpCol = cur[1] + dir[i][1]; if (tmpRol < 0 || tmpRol == rolSize || tmpCol < 0 || tmpCol == colSize || grid[tmpRol][tmpCol] == '#') { //越界或者是墙 continue; } if (grid[tmpRol][tmpCol] >= 'A' && grid[tmpRol][tmpCol] <= 'Z' && !(cur[2] & (1 << (grid[tmpRol][tmpCol] - 'A')))) { //有锁没钥匙 continue; } int keyStat = cur[2]; if (grid[tmpRol][tmpCol] >= 'a' && grid[tmpRol][tmpCol] <= 'z') { //当前是钥匙就新增钥匙状态 keyStat |= 1 << (grid[tmpRol][tmpCol] - 'a'); if (keyStat == target) { return distance[cur[0]][cur[1]][cur[2]] + 1; } } if (distance[tmpRol][tmpCol][keyStat] == -1) { distance[tmpRol][tmpCol][keyStat] = distance[cur[0]][cur[1]][cur[2]] + 1; que.push({ tmpRol, tmpCol, keyStat }); } } } return -1; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "1-2--3--4-5--6--7"; string b = "(()())(())"; vector<int> inpt1 = { 64, 44, 5, 11 }; vector<int> inpt2 = { 3, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 2, -1} }; vector<vector<char>> board = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, }; unordered_set<int> r1Set(inpt1.begin(), inpt1.end()); vector<string> tmp = { "ACC","ACB","ABD","DAA","BDC","BDB","DBC","BBD","BBC","DBD","BCC","CDD","ABA","BAB","DDC","CCD","DDA","CCA","DDD" }; mySolution.numSquarefulPerms(inpt1); return 0; } #endif //cookBook-二分搜索 #if false class Solution { public: struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} }; int countNodes(TreeNode* root) {//完全二叉树的节点个数 if (root == nullptr) { return 0; } int depth = -1; TreeNode* cur = root; while (cur != nullptr) { depth++; cur = cur->left; } int low = 1 << depth, high = (1 << (depth + 1)) - 1; while (low < high) { int mid = low + (high - low + 1) / 2; if (countNodesSub(root, depth, mid)) { low = mid; } else { high = mid - 1; } } return low; } bool countNodesSub(TreeNode* root, int level, int k) { int bit = 1 << (level - 1); while (root != nullptr && bit > 0) { if (!(bit & k)) { root = root->left; } else { root = root->right; } bit >>= 1; } return root != nullptr; } bool isSubsequence(string s, string t) {//判断子序列 size_t sLen = s.size(), tLen = t.size(), sCur = 0, tCur = 0; while (sCur < sLen && tCur < tLen) { if (s[sCur] == t[tCur]) { sCur++; } tCur++; } return sCur == sLen; } int hIndex(vector<int>& nums) {//H 指数 II int numsLen = nums.size(); int left = 0, right = numsLen; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] < numsLen - mid) { left = mid + 1; } else { right = mid; } } return numsLen - left; } int calculateMinimumHP(vector<vector<int>>& grid) {//地下城游戏 int rolSize = grid.size(), colSize = grid[0].size(); vector<vector<int>> dp(rolSize + 1, vector<int>(colSize + 1, INT_MAX)); dp[rolSize][colSize - 1] = 1, dp[rolSize - 1][colSize] = 1; for (int i = rolSize - 1; i > -1; i--) { for (int j = colSize - 1; j > -1; j--) { int tmp = min(dp[i + 1][j], dp[i][j + 1]); dp[i][j] = max(tmp - grid[i][j], 1); } } return dp[0][0]; } int maxEnvelopes(vector<vector<int>>& envelopes) {//俄罗斯套娃信封问题 sort(envelopes.begin(), envelopes.end(), [](vector<int>& v1, vector<int>& v2) { return v1[0] < v2[0] || (v1[0] == v2[0] && v1[1] < v2[1]); }); int enveCnt = envelopes.size(); vector<int> dp(enveCnt, 1); for (int i = 1; i < enveCnt; i++) { for (int j = 0; j < i; j++) { if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1]) { dp[i] = max(dp[i], dp[j] + 1); } } } return *max_element(dp.begin(), dp.end()); } int arrangeCoins(int n) {//排列硬币 if (n <= 0) { return 0; } int res = 1; while (n >= res) { n -= res; res++; } return res - 1; } int findRadius(vector<int>& houses, vector<int>& heaters) {//供暖器 sort(houses.begin(), houses.end()); sort(heaters.begin(), heaters.end()); int left = 0; int right = max(abs(heaters[heaters.size() - 1] - houses[0]), abs(heaters[0] - houses[houses.size() - 1])); while (left < right) { int mid = left + (right - left) / 2; if (findRadiusSub(houses, heaters, mid)) { //能覆盖 right = mid; } else { //mid确定不能覆盖,所以+1 left = mid + 1; } } return left; } bool findRadiusSub(vector<int>& houses, vector<int>& heaters, int radius) { int houseCnt = houses.size(), heaterCnt = heaters.size(), houseCur = 0, heaterCur = 0; while (houseCur < houseCnt && heaterCur < heaterCnt) { int house = houses[houseCur], heater = heaters[heaterCur]; if (abs(heater - house) <= radius) { houseCur++; } else { heaterCur++; } } return houseCur == houseCnt; } vector<int> findRightInterval(vector<vector<int>>& intervals) {//寻找右区间 vector<pair<int, int>> curMap; int intervalCnt = intervals.size(); for (int i = 0; i < intervalCnt; i++) { curMap.push_back(make_pair(intervals[i][0], i)); } sort(curMap.begin(), curMap.end()); vector<int> res; for (int i = 0; i < intervalCnt; i++) { res.push_back(findRightIntervalSub(curMap, intervals[i][1])); } return res; } int findRightIntervalSub(vector<pair<int, int>>& curMap, int num) { int left = 0, right = curMap.size(); while (left < right) { int mid = left + (right - left) / 2; if (curMap[mid].first < num) { left = mid + 1; } else { right = mid; } } return left == curMap.size() ? -1 : curMap[left].second; } string smallestGoodBase(string n) {//最小好进制 long long num = stol(n); long long res = num - 1;//默认答案 for (int base = 59; base > 1; base--) { int k = pow(num, 1.0 / base); if (k > 1) { long long sum = 1, mul = 1; for (int i = 1; i <= base; i++) { mul *= k; sum += mul; if (sum == num) { res = k; break; } } } } return to_string(res); } bool judgeSquareSum(int c) {//平方数之和 int left = 0, right = sqrt(c); while (left <= right) { long long tmp = (long long)left * left + right * right; if (tmp == c) { return true; } else if (tmp > c) { right--; } else { left++; } } return false; } int findKthNumber(int m, int n, int k) {//乘法表中第k小的数 int lo = 1, hi = m * n; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (!findKthNumberSub(m, n, mid, k)) { lo = mid + 1; } else { ; hi = mid; } } return lo; } bool findKthNumberSub(int m, int n, int mid, int k) { int cnt = 0; for (int i = 1; i <= m; i++) { cnt += min(n, mid / i); } return cnt >= k; } vector<int> kthSmallestPrimeFraction(vector<int>& nums, int k) {//第 K 个最小的素数分数 double lo = 0.0, hi = 1.0; int numsLen = nums.size(); while (lo < hi) { double mid = (lo + hi) / 2; int cnt = 0; vector<int> res = { 0, 1 }; int j = 0; for (int i = 0; i < numsLen; i++) { while (j < numsLen && nums[i] >= mid * nums[j]) { j++; } cnt += numsLen - j; if (j < numsLen && res[0] * nums[j] < res[1] * nums[i]) { res = { nums[i], nums[j] }; } } if (cnt == k) { return res; } else if (cnt < k) { lo = mid; } else { hi = mid; } } return {}; } int peakIndexInMountainArray(vector<int>& arr) {//山脉数组的峰顶索引 int left = 1, right = arr.size() - 2; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else if (arr[mid] < arr[mid + 1]) { left = mid + 1; } else { right = mid - 1; } } return 0; } class RecentCounter {//最近的请求次数 public: RecentCounter() { return; } int ping(int t) { time[0] = t - 3000; time[1] = t; int cnt = 0; log.push_back(t); cnt = log.end() - lower_bound(log.begin(), log.end(), time[0]); return cnt; } private: vector<int> time = { -3000, 0 }; vector<int> log; }; int minEatingSpeed(vector<int>& nums, int h) {//爱吃香蕉的珂珂 sort(nums.begin(), nums.end()); int left = 1, right = nums[nums.size() - 1]; while (left < right) { int mid = left + (right - left) / 2; if (!minEatingSpeedSub(nums, h, mid)) { left = mid + 1; } else { right = mid; } } return left; } bool minEatingSpeedSub(vector<int>& nums, int h, int spd) { //能不能在规定时间吃完 int cnt = 0; for (int& num : nums) { cnt += num / spd; if (num % spd != 0) { cnt++; } } return cnt <= h; } class TimeMap {//基于时间的键值存储 public: /** Initialize your data structure here. */ TimeMap() { } void set(string key, string value, int timestamp) { keyMap[key][timestamp] = value; return; } string get(string key, int timestamp) { if (keyMap.count(key) < 1) { return ""; } auto it = keyMap[key].upper_bound(timestamp); if (it == keyMap[key].begin()) { return ""; } return (--it)->second; } private: unordered_map<string, map<int, string>> keyMap; }; class TopVotedCandidate {////在线选举 public: TopVotedCandidate(vector<int>& persons, vector<int>& times) { int N = persons.size(); int lead = 0; vector<int> count(N, 0); for (int i = 0; i < N; i++) { count[persons[i]]++; // Note: use >= to include case tie case, choose the latest voted candidate if (count[persons[i]] >= count[lead]) { lead = persons[i]; } mp[times[i]] = lead; } } int q(int t) { auto iter = mp.upper_bound(t); auto last = prev(iter); // floor key return last->second; } private: map<int, int> mp; // time stamp to lead }; int preimageSizeFZF(int K) {//阶乘函数后 K 个零 long long left = 0, right = 5l * K; while (left <= right) { long long mid = left + (right - left) / 2; int zeroCnt = preimageSizeFZFSub(mid); if (zeroCnt == K) { return 5; } else if (zeroCnt > K) { right = mid - 1; } else { left = mid + 1; } } return 0; } int preimageSizeFZFSub(long long num) { int res = 0; while (num != 0) { res += num / 5; num /= 5; } return res; } int nthMagicalNumber(int n, int a, int b) {//第 N 个神奇数字 const int mod = 1000000007; int L = a * b / gcd(a, b);//最小公倍数 long long left = min(a, b), right = 1e15; while (left < right) { long long mid = left + (right - left) / 2; if (mid / a + mid / b - mid / L < n) { left = mid + 1; } else { right = mid; } } return (int)(left % mod); } int gcd(int x, int y) { if (x == 0) return y; return gcd(y % x, x); } vector<int> maxDepthAfterSplit(string seq) {//有效括号的嵌套深度 vector<int> res; int cnt = 0; for (char& ch : seq) { if (ch == '(') { cnt++; res.push_back(cnt % 2); } else { res.push_back(cnt % 2); cnt--; } } return res; } int nthUglyNumber(int n, int a, int b, int c) {//丑数 III long long ab = 1l * a * b / gcd(a, b), ac = 1l * a * c / gcd(a, c), bc = 1l * b * c / gcd(b, c); long long abc = 1l * a * bc / gcd(a, bc); long long left = min(min(a, b), c), right = n * left; while (left < right) { long long mid = left + (right - left) / 2; if (mid / a + mid / b + mid / c + mid / abc - mid / ab - mid / ac - mid / bc < n) { left = mid + 1; } else { right = mid; } } return (int)left; } int smallestDivisor(vector<int>& nums, int threshold) {//使结果不超过阈值的最小除数 int left = 1, right = *max_element(nums.begin(), nums.end()); while (left < right) { int mid = left + (right - left) / 2; if (smallestDivisorSub(nums, mid) > threshold) { left = mid + 1; } else { right = mid; } } return left; } int smallestDivisorSub(vector<int>& nums, int mid) { int res = 0; for (int& num : nums) { res += num / mid; if (num % mid != 0) { res++; } } return res; } vector<int> threeEqualParts(vector<int>& arr) {//三等分 vector<int> bits; int arrLen = arr.size(); for (int i = 0; i < arrLen; i++) { if (arr[i] == 1) { bits.push_back(i); } } if (bits.size() % 3 != 0) { return { -1, -1 }; } if (bits.empty()) { return { 0, 2 }; } int oneCnt = bits.size() / 3; int backZero = arrLen - 1 - bits.back(); if (backZero > bits[2 * oneCnt] - bits[2 * oneCnt - 1] - 1 || backZero > bits[oneCnt] - bits[oneCnt - 1] - 1) { return { -1, -1 }; } vector<int> fst(bits.begin(), bits.begin() + oneCnt); vector<int> sec(bits.begin() + oneCnt, bits.begin() + 2 * oneCnt); vector<int> trd(bits.begin() + 2 * oneCnt, bits.end()); for (int i = oneCnt - 1; i > 0; i--) { ; if (fst[i] - fst[i - 1] != sec[i] - sec[i - 1] || fst[i] - fst[i - 1] != trd[i] - trd[i - 1]) { return { -1, -1 }; } } int i = bits[oneCnt - 1] + backZero; int j = bits[2 * oneCnt - 1] + backZero + 1; return { i, j }; } }; //class Solution { //public: // Solution(vector<int>& w) {//按权重随机选择 // nums = w; // int numsLen = nums.size(); // for (int i = 1; i < numsLen; i++) { // nums[i] += nums[i - 1]; // } // lo = 0, hi = nums[numsLen - 1]; // return; // } // // int pickIndex() { // int r = rand() % (hi - lo) + 1; // return lower_bound(nums.begin(), nums.end(), r) - nums.begin(); // } //private: // vector<int> nums; // int lo, hi; //}; //class Solution {//非重叠矩形中的随机点 //public: // Solution(vector<vector<int>>& rects) { // int rectCnt = rects.size(); // rectBackup = rects; // int last = 0; // for (vector<int>& rect : rects) { // last += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1); // cur.push_back(last); // } // hi = cur[rectCnt - 1]; // return; // } // // vector<int> pick() { // int r = rand() % hi + 1; // int rect = lower_bound(cur.begin(), cur.end(), r) - cur.begin(); // int x = rand() % (rectBackup[rect][2] - rectBackup[rect][0] + 1) + rectBackup[rect][0]; // int y = rand() % (rectBackup[rect][3] - rectBackup[rect][1] + 1) + rectBackup[rect][1]; // return { x, y }; // } //private: // vector<int> cur; // vector<vector<int>> rectBackup; // int hi; //}; int main(int argc, char* argv[]) { Solution mySolution; string a = "1-2--3--4-5--6--7"; string b = "(()())(())"; vector<int> inpt1 = { 1, 2, 3 }; vector<int> inpt2 = { 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {82918473, -57180867, 82918476, -57180863}, {83793579, 18088559, 83793580, 18088560}, {66574245, 26243152, 66574246, 26243153}, {72983930, 11921716, 72983934, 11921720} }; vector<vector<char>> board = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, }; unordered_set<int> r1Set(inpt1.begin(), inpt1.end()); vector<string> tmp = { "ACC","ACB","ABD","DAA","BDC","BDB","DBC","BBD","BBC","DBD","BCC","CDD","ABA","BAB","DDC","CCD","DDA","CCA","DDD" }; mySolution.preimageSizeFZF(3); return 0; } #endif //cookBook-数学 #if false class Solution { public: bool isPalindrome(int x) {//回文数 if (x == 0) { return true; } if (x < 0 || x % 10 == 0) { return false; } long long xCopy = x, tmp = 0; while (x != 0) { tmp *= 10; tmp += x % 10; x /= 10; } return tmp == xCopy; } string convertToTitle(int columnNumber) {//Excel表列名称 string res; while (columnNumber != 0) { res.insert(res.begin(), (columnNumber - 1) % 26 + 'A'); columnNumber = (columnNumber - 1) / 26; } return res; } int titleToNumber(string columnTitle) {//Excel表列序号 int res = 0; for (char& ch : columnTitle) { res *= 26; res += ch - 'A' + 1; } return res; } int trailingZeroes(int n) {//阶乘后的零 int res = 0; while (n != 0) { res += n / 5; n /= 5; } return res; } int addDigits(int num) {//各位相加 return (num - 1) % 9 + 1; } bool isUgly(int n) {//丑数 if (n == 0) { return false; } while (n % 2 == 0) { n /= 2; } while (n % 3 == 0) { n /= 3; } while (n % 5 == 0) { n /= 5; } return n == 1; } bool isPowerOfThree(int n) {//3的幂 if (n == 0) { return false; } while (n % 3 == 0) { n /= 3; } return n == 1; } int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {//矩形面积 int x = max(A, E), y = max(B, F); int z = min(C, G), w = min(D, H); return (int)(computeAreaSub(A, B, C, D) + computeAreaSub(E, F, G, H) - computeAreaSub(x, y, z, w)); } long long computeAreaSub(int x, int y, int z, int w) { long long l = 0l + z - x, h = 0l + w - y; if (l <= 0 || h <= 0) { return 0; } return h * l; } int superPow(int a, vector<int>& b) {//超级次方 if (a < 2) { return a; } vector<long long> baseList(10, 1); int moder = 1337; for (int i = 1; i < 10; i++) { baseList[i] = baseList[i - 1] * a % moder; } long long res = 1l; for (int& num : b) { long long tmp = res; for (int i = 1; i < 10; i++) { res = res * tmp % moder; } res = res * baseList[num] % moder; } return res % moder; } int maxCount(int m, int n, vector<vector<int>>& ops) {//范围求和 II for (vector<int>& lim : ops) { m = min(lim[0], m); n = min(lim[1], n); } return m * n; } bool checkPerfectNumber(int num) {//完美数 if (num < 2) { return false; } int res = 1; int ub = sqrt(num) + 1; for (int i = 2; i < ub; i++) { if (num % i == 0) { res += i; res += num / i; } } return res == num; } int minMoves(vector<int>& nums) {//最小操作次数使数组元素相等 int sum = 0, minVal = INT_MAX; for (int& num : nums) { minVal = min(minVal, num); sum += num; } return sum - minVal * nums.size(); } vector<int> findErrorNums(vector<int>& nums) {//错误的集合 unordered_set<int> numSet; vector<int> res(2, 0); int sum = (nums.size() + 1) * nums.size() / 2; for (int& num : nums) { if (numSet.count(num) > 0) { res[0] = num; } numSet.insert(num); sum -= num; } res[1] = res[0] + sum; return res; } int numRabbits(vector<int>& answers) {//森林中的兔子 unordered_map<int, int> rabbits; int res = 0; for (int& num : answers) { rabbits[num]++; if (rabbits[num] == num + 1) { res += rabbits[num]; rabbits[num] = 0; } } for (auto& it : rabbits) { if (it.second != 0) { res += it.first + 1; } } return res; } double largestTriangleArea(vector<vector<int>>& points) {//最大三角形面积 double res = 0.0; int pointCnt = points.size(); for (int i = 0; i < pointCnt; i++) { for (int j = i + 1; j < pointCnt; j++) { for (int k = j + 1; k < pointCnt; k++) { res = max(res, largestTriangleAreaSub(points[i], points[j], points[k])); } } } return res; } double largestTriangleAreaSub(vector<int>& p, vector<int>& q, vector<int>& r) { return 0.5 * abs(p[0] * q[1] + q[0] * r[1] + r[0] * p[1] - p[1] * q[0] - q[1] * r[0] - r[1] * p[0]); } bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {//矩形重叠 int x = max(rec1[0], rec2[0]), y = max(rec1[1], rec2[1]); int z = min(rec1[2], rec2[2]), w = min(rec1[3], rec2[3]); if (z - x <= 0 || w - y <= 0) { return false; } return true; } vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {//螺旋矩阵 III vector<vector<int>> copy; copy.push_back({ r0, c0 }); int last = 2; int radius = 1; while (last <= R * C) { last = spiralMatrixIIISub(R, C, r0, c0, radius, last, copy); radius++; } return copy; } int spiralMatrixIIISub(int rolSize, int colSize, int r0, int c0, int radius, int start, vector<vector<int>>& copy) { for (int i = r0 - radius + 1; i <= r0 + radius; i++) { if (i < 0 || i >= rolSize || c0 + radius >= colSize) {//右 continue; } start++; copy.push_back({ i, c0 + radius }); } for (int i = c0 + radius - 1; i >= c0 - radius; i--) { if (i < 0 || i >= colSize || r0 + radius >= rolSize) {//下 continue; } start++; copy.push_back({ r0 + radius, i }); } for (int i = r0 + radius - 1; i >= r0 - radius; i--) { if (i < 0 || i >= rolSize || c0 - radius < 0) {//左 continue; } start++; copy.push_back({ i, c0 - radius }); } for (int i = c0 - radius + 1; i <= c0 + radius; i++) { if (r0 - radius < 0 || i < 0 || i >= colSize) {//上 continue; } start++; copy.push_back({ r0 - radius, i }); } return start; } int surfaceArea(vector<vector<int>>& grid) {//三维形体的表面积 int gridLen = grid.size(); vector<vector<int>> dir = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} }; int res = 0; for (int i = 0; i < gridLen; i++) { for (int j = 0; j < gridLen; j++) { if (grid[i][j] > 0) { res += grid[i][j] * 4 + 2; for (int k = 0; k < 4; k++) { int tmpRol = i + dir[k][0], tmpCol = j + dir[k][1]; if (tmpRol < 0 || tmpRol >= gridLen || tmpCol < 0 || tmpCol >= gridLen) { continue; } res -= min(grid[i][j], grid[tmpRol][tmpCol]); } } } } return res; } string largestTimeFromDigits(vector<int>& arr) {//给定数字能组成的最大时间--回溯 vector<bool> vist(4, false); int hourTmp = 0, minTmp = 0; int res = -1; for (int i = 0; i < 4; i++) { if (arr[i] > 2) { continue; } vist[i] = true; for (int j = 0; j < 4; j++) { if (vist[j]) { continue; } if (arr[i] * 10 + arr[j] > 23) { continue; } hourTmp = arr[i] * 10 + arr[j]; vist[j] = true; for (int k = 0; k < 4; k++) { if (vist[k] || arr[k] > 5) { continue; } vist[k] = true; for (int w = 0; w < 4; w++) { if (vist[w]) { continue; } minTmp = arr[k] * 10 + arr[w]; res = max(res, hourTmp * 100 + minTmp); } vist[k] = false; } vist[j] = false; } vist[i] = false; } if (res == -1) { return ""; } string str1 = to_string(res / 100), str2 = to_string(res % 100); if (str1.size() == 1) { str1.insert(str1.begin(), '0'); } if (str2.size() == 1) { str2.insert(str2.begin(), '0'); } return str1 + ':' + str2; } vector<int> powerfulIntegers(int x, int y, int bound) {//强整数 unordered_set<int> resSet; int tmpX = 1; while (tmpX < bound) { int tmpY = 1; while (tmpX + tmpY <= bound) { resSet.insert(tmpX + tmpY); if (y == 1) { break; } tmpY *= y; } if (x == 1) { break; } tmpX *= x; } vector<int> res; for (auto& it : resSet) { res.push_back(it); } return res; } int tribonacci(int n) {//第 N 个泰波那契数 if (n == 0) { return 0; } else if (n < 3) { return 1; } int n_3 = 0, n_2 = 1, n_1 = 1; int res = 0; while (n > 2) { res = n_3 + n_2 + n_1; n_3 = n_2; n_2 = n_1; n_1 = res; n--; } return res; } int dayOfYear(string date) {//一年中的第几天 int year = stoi(date.substr(0, 4)), month = stoi(date.substr(5, 2)), day = stoi(date.substr(8, 2)); int res = 0; vector<int> prefix = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; res = prefix[month - 1] + day; if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { if (month > 2) { res++; } } return res; } int numPrimeArrangements(int n) {//质数排列 if (n < 2) { return n; } vector<bool> dp(n + 1, true); dp[0] = false; dp[1] = false; int cnt = 0; for (int i = 2; i <= n; i++) { if (dp[i]) { cnt++; int j = i + i; while (j <= n) { dp[j] = false; j += i; } } } long long res = 1l; int moder = 1000000007; n -= cnt; while (cnt > 0) { res *= cnt--; res %= moder; } while (n > 0) { res *= n--; res %= moder; } return (int)res; } int subtractProductAndSum(int n) {//整数的各位积和之差 int tmp1 = 1, tmp2 = 0; while (n != 0) { tmp1 *= n % 10; tmp2 += n % 10; n /= 10; } return tmp1 - tmp2; } bool divisorGame(int N) {//除数博弈 return N % 2 == 0; } bool isBoomerang(vector<vector<int>>& points) {//有效的回旋镖 return(points[0][0] * points[1][1] + points[2][0] * points[0][1] + points[1][0] * points[2][1] != points[1][0] * points[0][1] + points[2][0] * points[1][1] + points[0][0] * points[2][1]); } string baseNeg2(int N) {//负二进制转换 if (N == 0) { return "0"; } string res; while (N != 0) { int tmp = N % -2; N /= -2; if (tmp < 0) { tmp += 2; N++; } res = to_string(tmp) + res; } return res; } vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) {//负二进制数相加 reverse(arr1.begin(), arr1.end()); reverse(arr2.begin(), arr2.end()); int arr1Len = arr1.size(), arr2Len = arr2.size(); if (arr1Len < arr2Len) { for (int i = 0; i < arr2Len - arr1Len; i++) { arr1.push_back(0); } } else if (arr2Len < arr1Len) { for (int i = 0; i < arr1Len - arr2Len; i++) { arr2.push_back(0); } } vector<int> res; int arrLen = max(arr1Len, arr2Len); int carry = 0; for (int i = 0; i < arrLen; i++) { int tmp = arr1[i] + arr2[i] + carry; if (tmp == 0 || tmp == 1) { res.push_back(tmp); carry = 0; } else if (tmp == -1) { res.push_back(1); carry = 1; } else if (tmp == 2) { res.push_back(0); carry = -1; } else if (tmp == 3) { res.push_back(1); carry = -1; } } if (carry == 1) { res.push_back(1); } else if (carry == -1) { res.push_back(1); res.push_back(1); } while (res.size() > 1 && res.back() == 0) { res.pop_back(); } reverse(res.begin(), res.end()); return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "1-2--3--4-5--6--7"; string b = "(()())(())"; vector<int> inpt1 = { 1, 1 }; vector<int> inpt2 = { 0 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {1, 0}, {0, 2} }; vector<vector<char>> board = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, }; unordered_set<int> r1Set(inpt1.begin(), inpt1.end()); vector<string> tmp = { "ACC","ACB","ABD","DAA","BDC","BDB","DBC","BBD","BBC","DBD","BCC","CDD","ABA","BAB","DDC","CCD","DDA","CCA","DDD" }; mySolution.addNegabinary(inpt1, inpt2); return 0; } #endif //cookBook-哈希表 #if false class Solution { public: int repeatedNTimes(vector<int>& nums) {//重复 N 次的元素 int target = nums.size() / 2; unordered_map<int, int> numMap; for (int& num : nums) { if (++numMap[num] == target) { return num; } } return -1; } bool uniqueOccurrences(vector<int>& arr) {//独一无二的出现次数 unordered_map<int, int> arrMap; for (int& num : arr) { ++arrMap[num]; } unordered_set<int> freqSet; for (auto& it : arrMap) { if (freqSet.count(it.second) > 0) { return false; } freqSet.insert(it.second); } return true; } bool wordPattern(string pattern, string s) {//单词规律 unordered_map<char, string> chMap; unordered_map<string, char> strMap; int cur = 0, sLen = s.size(); for (char& ch : pattern) { int curLast = cur; if (cur >= sLen) { return false; } while (cur < sLen && s[cur] != ' ') { cur++; } string tmp = s.substr(curLast, cur - curLast); cur++; if (chMap.count(ch) < 1 && strMap.count(tmp) < 1) { chMap[ch] = tmp; strMap[tmp] = ch; } else if (chMap.count(ch) < 1 || strMap.count(tmp) < 1 || chMap[ch] != tmp || strMap[tmp] != ch) { return false; } } return cur == sLen + 1; } int distributeCandies(vector<int>& candyType) {//分糖果 unordered_map<int, int> candyMap; for (int& candy : candyType) { candyMap[candy]++; } return min(candyMap.size(), candyType.size() / 2); } int findLHS(vector<int>& nums) {//最长和谐子序列 unordered_map<int, int> numMap; int res = 0; for (int& num : nums) { numMap[num]++; } for (auto& it : numMap) { if (numMap.count(it.first + 1)) { res = max(res, it.second + numMap[it.first + 1]); } if (numMap.count(it.first - 1)) { res = max(res, it.second + numMap[it.first - 1]); } } return res; } vector<string> uncommonFromSentences(string A, string B) {//两句话中的不常见单词 unordered_map<string, int> strMap; A = A + ' ' + B + ' '; int sLen = A.size(), cur = 0, last = 0; while (cur < sLen) { if (A[cur] != ' ') { cur++; continue; } strMap[A.substr(last, cur - last)]++; last = cur + 1; cur++; } vector<string> res; for (auto& it : strMap) { if (it.second == 1) { res.push_back(it.first); } } return res; } vector<string> subdomainVisits(vector<string>& cpdomains) {//子域名访问计数 unordered_map<string, int> urlCnt; for (string& s : cpdomains) { int sLen = s.size(), cur = 0, cnt = 0; while (s[cur] != ' ') { cur++; } cnt = stoi(s.substr(0, cur)); s = '.' + s.substr(cur + 1, sLen - cur); sLen = s.size(), cur = 0; while (cur < sLen) { if (s[cur] != '.') { cur++; continue; } string tmp = s.substr(cur + 1, sLen - cur); cur++; urlCnt[tmp] += cnt; } } vector<string> res; for (auto& it : urlCnt) { res.push_back(to_string(it.second) + ' ' + it.first); } return res; } class MagicDictionary {//实现一个魔法字典 public: /** Initialize your data structure here. */ MagicDictionary() { return; } void buildDict(vector<string> dictionary) { for (string& s : dictionary) { int sLen = s.size(); for (int i = 0; i < sLen; i++) { string sCopy = s; sCopy[i] = '*'; wordDict[sCopy].insert(s); } } return; } bool search(string s) { if (wordDict.count(s) > 0) { return false; } int sLen = s.size(); for (int i = 0; i < sLen; i++) { string sCopy = s; sCopy[i] = '*'; if (wordDict.count(sCopy) > 0) { if (wordDict[sCopy].size() > 1 || wordDict[sCopy].count(s) < 1) { return true; } } } return false; } private: unordered_map<string, unordered_set<string>> wordDict; }; vector<int> findSubstring(string s, vector<string>& words) {//串联所有单词的子串 vector<int> res; int sLen = s.size(); if (sLen == 0 || words.empty()) { return res; } int wordCnt = words.size(), wordLen = words[0].size(); if (wordCnt * wordLen > sLen) { return res; } unordered_map<string, int> wordMap; for (string& word : words) { ++wordMap[word]; } for (int i = 0; i < wordLen; i++) { int left = i, right = i, cnt = 0; unordered_map<string, int> currMap; while (right + wordLen <= sLen) { string tmp = s.substr(right, wordLen); right += wordLen; if (wordMap.count(tmp) > 0) { ++currMap[tmp]; ++cnt; while (currMap[tmp] > wordMap[tmp]) { string ts = s.substr(left, wordLen); left += wordLen; --cnt; --currMap[ts]; } if (cnt == wordCnt) { res.push_back(left); } } else { left = right; currMap.clear(); cnt = 0; } } } return res; } class WordFilter {//前缀和后缀搜索 public: WordFilter(vector<string>& words) { int wordCnt = words.size(); for (int i = 0; i < wordCnt; i++) { vector<string> prefix, suffix; string prefixTmp = "**********", suffixTmp = "**********"; int wordLen = words[i].size(); for (int j = 0; j < wordLen; j++) { prefixTmp[j] = words[i][j]; suffixTmp[9 - j] = words[i][wordLen - 1 - j]; prefix.push_back(prefixTmp); suffix.push_back(suffixTmp); } for (int j = 0; j < wordLen; j++) { for (int k = 0; k < wordLen; k++) { wordWt[prefix[j]][suffix[k]] = i; } } } return; } int f(string prefix, string suffix) { while (prefix.size() < 10) { prefix.push_back('*'); } while (suffix.size() < 10) { suffix = '*' + suffix; } if (wordWt.count(prefix) < 1 || wordWt[prefix].count(suffix) < 1) { return -1; } return wordWt[prefix][suffix]; } private: unordered_map<string, unordered_map<string, int>> wordWt; }; }; int main(int argc, char* argv[]) { Solution mySolution; string a = "this apple is sweet"; string b = "this apple is sour"; vector<int> inpt1 = { 1, 1 }; vector<int> inpt2 = { 0 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {1, 0}, {0, 2} }; vector<vector<char>> board = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, }; unordered_set<int> r1Set(inpt1.begin(), inpt1.end()); vector<string> tmp = { "apple" }; mySolution.findSubstring("wordgoodgoodgoodbestword", tmp); return 0; } #endif //cookBook-排序 #if false class Solution { public: struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {//插入区间 int intervalCnt = intervals.size(); int cur = 0; vector<vector<int>> res; bool placed = false; for (vector<int>& intv : intervals) { if (intv[1] < newInterval[0]) { res.push_back(intv); } else if (intv[0] > newInterval[1]) { if (!placed) { res.push_back(newInterval); placed = true; } res.push_back(intv); } else { newInterval[0] = min(newInterval[0], intv[0]); newInterval[1] = max(newInterval[1], intv[1]); } } if (!placed) { res.push_back(newInterval); } return res; } void sortColors(vector<int>& nums) {//颜色分类 sortColorsSub(nums, 0, nums.size() - 1); return; } void sortColorsSub(vector<int>& nums, int left, int right) { if (left >= right) { return; } int pivot = nums[left]; int i = left, j = right; while (i < j) { while (i < j && nums[j] >= pivot) { j--; } if (i < j) { nums[i++] = nums[j]; } while (i < j && nums[i] <= pivot) { i++; } if (i < j) { nums[j--] = nums[i]; } } nums[i] = pivot; sortColorsSub(nums, left, i - 1); sortColorsSub(nums, i + 1, right); return; } ListNode* myBuildList(vector<int>& nums) { ListNode* rootNode = new ListNode; ListNode* currentNode = rootNode; for (int& num : nums) { currentNode->next = new ListNode; currentNode = currentNode->next; currentNode->val = num; } return rootNode->next; } ListNode* insertionSortList(ListNode* head) {//对链表进行插入排序 if (head == nullptr || head->next == nullptr) { return head; } ListNode* root = new ListNode; root->next = head; ListNode* cur = head->next, * prev = head; while (cur != nullptr) { if (cur->val >= prev->val) { cur = cur->next; prev = prev->next; } else { ListNode* tmp = root; while (tmp->next->val <= cur->val) { tmp = tmp->next; } prev->next = cur->next; cur->next = tmp->next; tmp->next = cur; cur = prev->next; } } return root->next; } int findKthLargest(vector<int>& nums, int k) {//数组中的第K个最大元素 findKthLargestSub(nums, 0, nums.size() - 1); return nums[nums.size() - k]; } void findKthLargestSub(vector<int>& nums, int left, int right) { if (left >= right) { return; } int i = left, j = right, pivot = nums[left]; while (i < j) { while (i < j && nums[j] >= pivot) { j--; } if (i < j) { nums[i++] = nums[j]; } while (i < j && nums[i] < pivot) { i++; } if (i < j) { nums[j--] = nums[i]; } } nums[i] = pivot; findKthLargestSub(nums, left, i - 1); findKthLargestSub(nums, i + 1, right); return; } bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {//存在重复元素 III if (t < 0) { return false; } long long wt = 1ll + t; unordered_map<long long, long long> numMap; int numsLen = nums.size(); for (int i = 0; i < numsLen; i++) { long long tmp = containsNearbyAlmostDuplicateID(nums[i], wt); if (numMap.count(tmp) > 0) { return true; } if (numMap.count(tmp - 1) > 0 && abs(nums[i] - numMap[tmp - 1]) < wt) { return true; } if (numMap.count(tmp + 1) > 0 && abs(nums[i] - numMap[tmp + 1]) < wt) { return true; } numMap[tmp] = (long long)nums[i]; if (i >= k) { numMap.erase(containsNearbyAlmostDuplicateID(nums[i - k], wt)); } } return false; } long long containsNearbyAlmostDuplicateID(long long x, long long wt) { return x < 0 ? (x + 1) / wt - 1 : x / wt; } int hIndex(vector<int>& citations) {//H 指数 int citationsCnt = citations.size(); hIndexSub(citations, 0, citationsCnt - 1); int left = 0, right = citationsCnt; while (left < right) { int mid = left + (right - left) / 2; if (citations[mid] < citationsCnt - mid) { left = mid + 1; } else { right = mid; } } return citationsCnt - left; } void hIndexSub(vector<int>& nums, int left, int right) { if (left >= right) { return; } int i = left, j = right, pivot = nums[left]; while (i < j) { while (i < j && nums[j] >= pivot) { j--; } if (i < j) { nums[i++] = nums[j]; } while (i < j && nums[i] < pivot) { i++; } if (i < j) { nums[j--] = nums[i]; } } nums[i] = pivot; hIndexSub(nums, left, i - 1); hIndexSub(nums, i + 1, right); return; } //int maximumGap(vector<int>& nums) {//最大间距 // int numsLen = nums.size(); // if (numsLen < 2) { // return 0; // } // int res = 0; // maximumGapSub(nums, 0, numsLen - 1); // for (int i = 1; i < numsLen; i++) { // res = max(res, nums[i] - nums[i - 1]); // } // return res; //} //void maximumGapSub(vector<int>& nums, int left, int right) { // if (left >= right) { // return; // } // int i = left, j = right, pivot = nums[left]; // while (i < j) { // while(i < j && nums[j] >= pivot) { // j-- ; // } // if (i < j) { // nums[i++] = nums[j]; // } // while (i < j && nums[i] < pivot) { // i++; // } // if (i < j) { // nums[j--] = nums[i]; // } // } // nums[i] = pivot; // maximumGapSub(nums, left, i - 1); // maximumGapSub(nums, i + 1, right); // return; //} int maximumGap(vector<int>& nums) {//最大间距 //采用基数排序法 int numsLen = nums.size(); if (numsLen < 2) { return 0; } int exp = 1, maxElem = *max_element(nums.begin(), nums.end()); vector<int> buffer(numsLen); while (exp <= maxElem) { vector<int> digitCnt(10, 0); for (int i = 0; i < numsLen; i++) {//求同一数位上相同数值元素数量 digitCnt[(nums[i] / exp) % 10]++; } for (int i = 1; i < 10; i++) { digitCnt[i] += digitCnt[i - 1]; } for (int i = numsLen - 1; i > -1; i--) { //怎么这么神奇? int digit = (nums[i] / exp) % 10; buffer[--digitCnt[digit]] = nums[i]; } copy(buffer.begin(), buffer.end(), nums.begin()); exp *= 10; } int res = 0; for (int i = 1; i < numsLen; i++) { res = max(res, nums[i] - nums[i - 1]); } return res; } vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {//查找和最小的K对数字 vector<vector<int>> res; int nums1Len = nums1.size(), nums2Len = nums2.size(); int cnt = nums1Len * nums2Len; vector<pair<int, int>> tmp; for (int i = 0; i < nums1Len; i++) { for (int j = 0; j < nums2Len; j++) { tmp.push_back(make_pair(nums1[i], nums2[j])); } } sort(tmp.begin(), tmp.end(), [](pair<int, int> pr1, pair<int, int> pr2) { return pr1.first + pr1.second < pr2.first + pr2.second; }); int cur = 0; k = min(k, cnt); while (cur < k) { res.push_back({ tmp[cur].first, tmp[cur].second }); cur++; } return res; } int findContentChildren(vector<int>& nums1, vector<int>& nums2) {//分发饼干 int res = 0, nums1Len = nums1.size(), nums2Len = nums2.size(), cur1 = 0, cur2 = 0; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); while (cur1 < nums1Len && cur2 < nums2Len) { if (nums1[cur1] <= nums2[cur2]) { cur1++; cur2++; res++; } else { cur2++; } } return res; } string findLongestWord(string s, vector<string>& dictionary) {//通过删除字母匹配到字典里最长单词 string res; sort(dictionary.begin(), dictionary.end()); for (string& str : dictionary) { if (findLongestWordSub(s, str) && str.size() > res.size()) { res = str; } } return res; } bool findLongestWordSub(string& str1, string& str2) { int str1Len = str1.size(), str2Len = str2.size(); int cur1 = 0, cur2 = 0; while (cur1 < str1Len && cur2 < str2Len) { if (str1[cur1] == str2[cur2]) { cur2++; } cur1++; } return cur2 == str2Len; } string reorganizeString(string S) {//重构字符串 if (S.length() < 2) { return S; } vector<int> counts(26, 0); int maxCount = 0; int length = S.length(); for (int i = 0; i < length; i++) { char c = S[i]; counts[c - 'a']++; maxCount = max(maxCount, counts[c - 'a']); } if (maxCount > (length + 1) / 2) { return ""; } string reorganizeArray(length, ' '); int evenIndex = 0, oddIndex = 1; int halfLength = length / 2; for (int i = 0; i < 26; i++) { char c = 'a' + i; while (counts[i] > 0 && counts[i] <= halfLength && oddIndex < length) { reorganizeArray[oddIndex] = c; counts[i]--; oddIndex += 2; } while (counts[i] > 0) { reorganizeArray[evenIndex] = c; counts[i]--; evenIndex += 2; } } return reorganizeArray; } bool isAlienSorted(vector<string>& words, string order) {//验证外星语词典 if (words.size() < 2) { return true; } int charCnt = order.size(); unordered_map<char, int> newOrder; for (int i = 0; i < charCnt; i++) { newOrder[order[i]] = i; } string last = words[0]; for (string& str : words) { if (!isAlienSortedSub(last, str, newOrder)) { return false; } last = str; } return true; } bool isAlienSortedSub(string& str1, string& str2, unordered_map<char, int>& newOrder) { int cur1 = 0, cur2 = 0, str1Len = str1.size(), str2Len = str2.size(); while (cur1 < str1Len && cur2 < str2Len) { if (newOrder[str1[cur1]] < newOrder[str2[cur2]]) { return true; } else if (newOrder[str1[cur1]] == newOrder[str2[cur2]]) { cur1++; cur2++; } else { return false; } } return cur1 == str1Len; } int largestPerimeter(vector<int>& nums) {//三角形的最大周长 int numsLen = nums.size(); if (numsLen < 3) { return 0; } sort(nums.begin(), nums.end()); for (int i = numsLen - 1; i > 1; i--) { int a = nums[i], b = nums[i - 1], c = nums[i - 2]; if (a + b > c && a + c > b && b + c > a) { return a + b + c; } } return 0; } int largestSumAfterKNegations(vector<int>& nums, int k) {//K 次取反后最大化的数组和 sort(nums.begin(), nums.end()); int cur = 0, numsLen = nums.size(); while (cur < numsLen && nums[cur] < 0 && k > 0) { nums[cur] = -nums[cur]; cur++; k--; } sort(nums.begin(), nums.end()); int res = 0; for (int& num : nums) { res += num; } if (k % 2 == 1) { return res - 2 * nums[0]; } return res; } vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {//距离顺序排列矩阵单元格 vector<vector<int>> tmp; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { tmp.push_back({ i, j , r0, c0}); } } sort(tmp.begin(), tmp.end(), [](vector<int>& vtr1, vector<int>& vtr2) { int r0 = vtr1[2], c0 = vtr1[3]; return abs(vtr1[0] - r0) + abs(vtr1[1] - c0) < abs(vtr2[0] - r0) + abs(vtr2[1] - c0); }); vector<vector<int>> res; for (vector<int>& vtr : tmp) { res.push_back({ vtr[0], vtr[1] }); } return res; } vector<int> rearrangeBarcodes(vector<int>& nums) {//距离相等的条形码 int numsLen = nums.size(); if (numsLen < 3) { return nums; } vector<int> res(numsLen); vector<int> numMap(*max_element(nums.begin(), nums.end()) + 1); for (int& num : nums) { numMap[num]++; } //sort(numMap.begin(), numMap.end()); int oddCur = 1, evenCur = 0; for (int i = 0; i < numMap.size(); i++) { //先填入奇数,后填入偶数 while (numMap[i] > 0 && numMap[i] <= numsLen / 2 && oddCur < numsLen) { res[oddCur] = i; numMap[i]--; oddCur += 2; } while (numMap[i] > 0) { res[evenCur] = i; numMap[i]--; evenCur += 2; } } return res; } vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {//最接近原点的 K 个点 sort(points.begin(), points.end(), [](vector<int>& vtr1, vector<int>& vtr2) { double d1 = 0.0 + sqrt(vtr1[0] * vtr1[0] + vtr1[1] * vtr1[1]); double d2 = 0.0 + sqrt(vtr2[0] * vtr2[0] + vtr2[1] * vtr2[1]); return d1 < d2; }); vector<vector<int>> res(points.begin(), points.begin() + k); return res; } vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {//两棵二叉搜索树中的所有元素 vector<int> res; stack<TreeNode*> stk1, stk2; while ((root1 != nullptr || !stk1.empty()) && (root2 != nullptr || !stk2.empty())) { if (root1 != nullptr || root2 != nullptr) { if (root1 != nullptr) { stk1.push(root1); root1 = root1->left; } if (root2 != nullptr) { stk2.push(root2); root2 = root2->left; } } else { TreeNode* tmp1 = stk1.top(); TreeNode* tmp2 = stk2.top(); if (tmp1->val < tmp2->val) { res.push_back(tmp1->val); stk1.pop(); root1 = tmp1->right; } else { res.push_back(tmp2->val); stk2.pop(); root2 = tmp2->right; } } } while ((root1 != nullptr || !stk1.empty())) { if (root1 != nullptr) { stk1.push(root1); root1 = root1->left; } else { TreeNode* tmp1 = stk1.top(); res.push_back(tmp1->val); stk1.pop(); root1 = tmp1->right; } } while ((root2 != nullptr || !stk2.empty())) { if (root2 != nullptr) { stk2.push(root2); root2 = root2->left; } else { TreeNode* tmp2 = stk2.top(); res.push_back(tmp2->val); stk2.pop(); root2 = tmp2->right; } } return res; } int carFleet(int target, vector<int>& position, vector<int>& speed) {//车队 int res = 0; if (position.empty() || speed.empty()) { return res; } int carCnt = speed.size(); map<int, double> reachTime; for (int i = 0; i < carCnt; i++) { reachTime[-position[i]] = (0.0 + target - position[i]) / speed[i];//最先到的排前面 } double time = 0.0; for (auto& it : reachTime) { if (it.second <= time) { continue; } time = it.second; res++; } return res; } vector<int> pancakeSort(vector<int>& nums) {//煎饼排序 vector<int> res; int numsLen = nums.size(); for (int i = numsLen; i > 0; i--) { if (nums[i - 1] != i) { int cur = 0; while (nums[cur] != i) { cur++; } res.push_back(cur + 1); pancakeSortSub(nums, 0, cur); res.push_back(i); pancakeSortSub(nums, 0, i - 1); } } return res; } void pancakeSortSub(vector<int>& nums, int left, int right) { while (left < right) { swap(nums[left++], nums[right--]); } return; } int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {//规划兼职工作 int jobCnt = startTime.size(); vector<int> job(jobCnt + 1); iota(job.begin(), job.end(), 0); sort(job.begin() + 1, job.end(), [&](int& a, int& b) { return endTime[a - 1] < endTime[b - 1]; }); vector<int> prev(jobCnt + 1); for (int i = 1; i <= jobCnt; i++) { for (int j = i - 1; j > 0; j--) { if (endTime[job[j] - 1] <= startTime[job[i] - 1]) { prev[i] = j; break; } } } vector<int> dp(jobCnt + 1); dp[1] = profit[job[1] - 1]; for (int i = 1; i <= jobCnt; i++) { dp[i] = max(dp[i - 1], profit[job[i] - 1] + dp[prev[i]]); } return dp[jobCnt]; } }; class Solution1 {//黑名单中的随机数 public: unordered_map<int, int> m; int wlen; Solution1(int n, vector<int> b) { wlen = n - b.size(); unordered_set<int> w; for (int i = wlen; i < n; i++) w.insert(i); for (int x : b) w.erase(x); auto wi = w.begin(); for (int x : b) if (x < wlen) m[x] = *wi++; } int pick() { int k = rand() % wlen; return m.count(k) ? m[k] : k; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "hlabcdefgijkmnopqrstuvwxyz"; string b = "this apple is sour"; vector<int> inpt1 = { 3, 2, 4, 1 }; vector<int> inpt2 = { 2,4,1,1,3 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {1, 0}, {0, 2} }; vector<vector<char>> board = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, }; unordered_set<int> r1Set(inpt1.begin(), inpt1.end()); vector<string> tmp = { "hello","leetcode" }; mySolution.pancakeSort(inpt1); return 0; } #endif //cookBook-位运算 #if false class Solution { public: struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int singleNumberII(vector<int>& nums) {//只出现一次的数字 II int lowBit = 0, highBit = 0; for (int& num : nums) { lowBit = lowBit ^ num & ~highBit; highBit = highBit ^ num & ~lowBit; } return lowBit; } int rangeBitwiseAnd(int left, int right) {//数字范围按位与 if (left == 0) { return 0; } int res = 0; while (left != right) { left >>= 1; right >>= 1; res++; } res = left << res; return res; } bool isPowerOfTwo(int n) {//2的幂 return n > 0 && ((n & (n - 1)) == 0); } bool isPowerOfFour(int n) {//4的幂 if (n < 1) { return false; } while (n > 0 && (n & 1) == 0) { n >>= 1; if ((n & 1) == 1) { return false; } n >>= 1; } return n == 1; } int getSum(int a, int b) {//两整数之和 while (b != 0) { int tmp = a ^ b; b = ((unsigned int)(a & b)) << 1; a = tmp; } return a; } char findTheDifference(string s, string t) {//找不同 char res = 0; for (char& ch : s) { res ^= ch; } for (char& ch : t) { res ^= ch; } return res; } int integerReplacement(int n) {//整数替换 int res = 0; unsigned long long tmp = n; while (tmp > 1) { if ((tmp & 1) == 0) { tmp >>= 1; } else if ((tmp + 1) % 4 == 0 && tmp != 3) { tmp++; } else { tmp--; } res++; } return res; } vector<int> countBits(int num) {//比特位计数 vector<int> res(num + 1, 0); int highBit = 0; for (int i = 1; i <= num; i++) { if ((i & (i - 1)) == 0) { highBit = i; } res[i] = res[i - highBit] + 1; } return res; } vector<string> findRepeatedDnaSequences(string s) {//重复的DNA序列 unordered_map<long long, int> dnaMap; unordered_map<char, int> base = { {'A', 1 }, {'C', 2 }, {'G', 3 }, {'T', 4 } }; unordered_map<int, char> baseInv = { {1, 'A' }, {2, 'C'}, {3, 'G'}, {4, 'T'} }; long long tmp = 0; for (char& ch : s) { if (tmp > 999999999) { dnaMap[tmp]++; tmp %= 1000000000; } tmp *= 10; tmp += base[ch]; } dnaMap[tmp]++; vector<string> res; for (auto& it : dnaMap) { if (it.second < 2) { continue; } tmp = it.first; string curr; while (tmp > 0) { curr = baseInv[(int)(tmp % 10)] + curr; tmp /= 10; } res.push_back(curr); } return res; } vector<int> singleNumber(vector<int>& nums) {//只出现一次的数字 III int res = 0; for (int& num : nums) { res ^= num; } int div = 1; while ((div & res) == 0) { div <<= 1; } int a = 0, b = 0; for (int& num : nums) { if (div & num) { a ^= num; } else { b ^= num; } } return { a, b }; } int maxProduct(vector<string>& words) {//最大单词长度乘积 int res = 0; int wordCnt = words.size(); vector<int> tmp(wordCnt); for (int i = 0; i < wordCnt; i++) { string& str = words[i]; int strVal = 0; for (char& ch : str) { strVal |= (1 << (ch - 'a')); } tmp[i] = strVal; } for (int i = 0; i < wordCnt; i++) { for (int j = i + 1; j < wordCnt; j++) { if ((tmp[i] & tmp[j]) == 0) { int tmpVal = words[i].size() * words[j].size(); res = max(res, tmpVal); } } } return res; } bool validUtf8(vector<int>& data) {//UTF-8 编码验证 int availCnt = 0; for (int& num : data) { if (availCnt == 0) {//没有待处理的字节 if (num < 128) {//当前字节为单字节 continue; } if (num < 192) {//多余字节 return false; } int cur = 255; availCnt = 7; while ((cur & num) != cur) { cur = (cur << 1) & 255; availCnt--; } if (availCnt > 3) {//过长字节 return false; } } else if ((num & 192) == 128) { availCnt--; } else { return false; } } return availCnt == 0; } vector<string> readBinaryWatch(int num) {//二进制手表 vector<string> res; for (int i = 0; i < 1024; i++) { if (readBinaryWatchSub(i, num)) { int hour = (i & 960) >> 6; int mint = i & 63; if (hour < 12 && mint < 10) { res.push_back(to_string(hour) + ':' + '0' + to_string(mint)); } else if (hour < 12 && mint < 60) { res.push_back(to_string(hour) + ':' + to_string(mint)); } } } return res; } inline bool readBinaryWatchSub(int num, int target) { int cur = 1, cnt = 0; for (int i = 0; i < 10; i++) { if (num & cur) { cnt++; } cur <<= 1; } return target == cnt; } string toHex(int num) {//数字转换为十六进制数 if (num == 0) { return "0"; } unsigned int curr = (unsigned int)num; string res; while (curr != 0) { int tmp = curr & 15; if (tmp < 10) { res = (char)(tmp + '0') + res; } else { res = (char)(tmp + 'a' - 10) + res; } curr >>= 4; } return res; } int findComplement(int num) {//数字的补数 unsigned int cur = 1; unsigned int curr = (unsigned int)num; while (cur <= curr) { cur <<= 1; } cur -= curr + 1; return cur; } int totalHammingDistance(vector<int>& nums) {//汉明距离总和 int numsLen = nums.size(), res = 0; if (numsLen == 0) { return 0; } vector<int> cnt(32); for (int& num : nums) { int i = 0; while (num != 0) { cnt[i] += num & 1; num >>= 1; i++; } } for (int& val : cnt) { res += val * (numsLen - val); } return res; } bool hasAlternatingBits(int n) {//交替位二进制数 bool status = (n & 1) != 0; n >>= 1; while (n != 0) { if (((n & 1) != 0) == status) { return false; } status = !status; n >>= 1; } return true; } int countPrimeSetBits(int L, int R) {//二进制表示中质数个计算置位 unordered_set<int> uniq = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; int res = 0; for (int i = L; i <= R; i++) { int cur = 1; int cnt = 0; while (cur <= i) { if (cur & i) { cnt++; } cur <<= 1; } if (uniq.count(cnt) > 0) { res++; } } return res; } int subarrayBitwiseORs(vector<int>& nums) {//子数组按位或操作 int numsLen = nums.size(); unordered_set<int> res; vector<int> dp(nums); for (int r = 0; r < numsLen; r++) { res.insert(dp[r]); for (int l = r - 1; l > -1; l--) { if ((dp[l] | dp[r]) == dp[l]) { break; } dp[l] |= dp[r]; res.insert(dp[l]); } } return res.size(); } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "AAGATCCGTCCCCCCAAGATCCGTC"; string b = "this apple is sour"; vector<int> inpt1 = { 250,145,145,145,145 }; vector<int> inpt2 = { 2,4,1,1,3 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {1, 0}, {0, 2} }; vector<vector<char>> board = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, }; unordered_set<int> r1Set(inpt1.begin(), inpt1.end()); vector<string> tmp = { "abcw","baz","foo","bar","xtfn","abcdef" }; mySolution.toHex(-1); return 0; } #endif //cookBook-并查集 #if false class Solution { public: struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int longestConsecutive(vector<int>& nums) {//最长连续序列 unordered_set<int> numSet; for (int& num : nums) { numSet.insert(num); } int current = 0, res = 0; for (int& num : nums) { if (numSet.count(num - 1) > 0) { continue; } current = 1; while (numSet.count(num + current) > 0) { current++; } res = max(res, current); } return res; } class UnionFind { public: //自己的父节点是自己 UnionFind(int num) { for (int i = 0; i < num; i++) { parent.push_back(i); weight.push_back(1.0); } return; } int find(int x) { if (x != parent[x]) { int ori = parent[x]; parent[x] = find(ori); weight[x] *= weight[ori]; } return parent[x]; } double isConnected(int x, int y) { int rootX = find(x), rootY = find(y); if (rootX == rootY) { return weight[x] / weight[y]; } return -1.0; } void nyUnion(int x, int y, double val) { int rootX = find(x), rootY = find(y); if (rootX == rootY) { return; } parent[rootX] = rootY; weight[rootX] = weight[y] * val / weight[x]; return; } private: vector<int> parent; vector<double> weight; }; vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {//除法求值 int eqCnt = equations.size(); UnionFind myUnion(2 * eqCnt); //获取节点--id对应 unordered_map<string, int> curMap; int id = 0; for (int i = 0; i < eqCnt; i++) { string& str1 = equations[i][0]; string& str2 = equations[i][1]; if (curMap.count(str1) < 1) { curMap[str1] = id++; } if (curMap.count(str2) < 1) { curMap[str2] = id++; } //连接有向图 myUnion.nyUnion(curMap[str1], curMap[str2], values[i]); } //查询 int irqCnt = queries.size(); vector<double> res(irqCnt, -1); for (int i = 0; i < irqCnt; i++) { string& str1 = queries[i][0]; string& str2 = queries[i][1]; if (curMap.count(str1) > 0 && curMap.count(str2) > 0) { int id1 = curMap[str1], id2 = curMap[str2]; res[i] = myUnion.isConnected(id1, id2); } } return res; } class findRedundantConnectionSub { public: findRedundantConnectionSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void addToTree(int x, int y) { parent[findParent(x)] = findParent(y); return; } bool check(int x, int y) {//是否具有相同连接分量 int rootX = findParent(x), rootY = findParent(y); if (rootX == rootY) { return true; } return false; } private: vector<int> parent; }; vector<int> findRedundantConnection(vector<vector<int>>& edges) {//冗余连接 unordered_map<int, int> curMap; int id = 0; for (vector<int>& edge : edges) { if (curMap.count(edge[0]) < 1) { curMap[edge[0]] = id++; } if (curMap.count(edge[1]) < 1) { curMap[edge[1]] = id++; } } int edgeCnt = edges.size(); findRedundantConnectionSub mySub(2 * edgeCnt); for (vector<int>& edge : edges) { int x = curMap[edge[0]], y = curMap[edge[1]]; if (mySub.check(x, y)) { return edge; } mySub.addToTree(x, y); } return{}; } class findRedundantDirectedConnectionSub { public: findRedundantDirectedConnectionSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } } int findPatent(int x) { if (x != parent[x]) { parent[x] = findPatent(parent[x]); } return parent[x]; } bool checkPatent(int x, int y) { if (findPatent(x) == findPatent(y)) { return true; } return false; } void addToTree(int x, int y) { parent[findPatent(x)] = findPatent(y); return; } private: vector<int> parent; }; vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {//冗余连接 II int edgeCnt = edges.size(); findRedundantDirectedConnectionSub mySub(edgeCnt + 1); vector<int> parent(edgeCnt + 1);//最后一次刷新的父节点 for (int i = 0; i <= edgeCnt; i++) { parent[i] = i; } int conflict = -1, cycle = -1; for (int i = 0; i < edgeCnt; i++) { vector<int>& edge = edges[i]; int node1 = edge[0], node2 = edge[1]; if (parent[node2] != node2) {//再次连接已连接节点(不一定有环) conflict = i; } else { parent[node2] = node1; if (mySub.checkPatent(node1, node2)) {//连接出现环 cycle = i; } else { mySub.addToTree(node1, node2); } } } if (conflict < 0) {//环连接到根节点 return edges[cycle]; } else if (cycle >= 0) {//有环出现,删除环节点的父节点和环节点 return{parent[edges[conflict][1]], edges[conflict][1] }; } return edges[conflict];//无环出现 } class findCircleNumSub { public: findCircleNumSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void addToTree(int x, int y) {//把x添加到y parent[findParent(x)] = findParent(y); return; } int getRes(void) { unordered_set<int> capCnt; for (int i = 0; i < parent.size(); i++) { int tmp = findParent(i); capCnt.insert(tmp); } return capCnt.size(); } private: vector<int> parent; }; int findCircleNum(vector<vector<int>>& isConnected) {//省份数量 int itemCnt = isConnected.size(); if (itemCnt < 2) { return itemCnt; } findCircleNumSub mySub(itemCnt); for (int i = 0; i < itemCnt; i++) { for (int j = i + 1; j < itemCnt; j++) { if (isConnected[i][j] == 0) { continue; } mySub.addToTree(i, j); } } return mySub.getRes(); } class accountsMergeSub { public: accountsMergeSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void merge(int x, int y) { parent[findParent(y)] = findParent(x); return; } private: vector<int> parent; }; vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {//账户合并 unordered_map<string, int> mailID; unordered_map<string, string> mailName; //分配ID int id = 0; for (vector<string>& mail : accounts) { int mailCnt = mail.size(); string& name = mail[0]; for (int i = 1; i < mailCnt; i++) { if (mailID.count(mail[i]) < 1) { mailID[mail[i]] = id++; mailName[mail[i]] = name; } } } //归并 accountsMergeSub mySub(id); for (vector<string>& account : accounts) { string& firstMail = account[1]; int mailCnt = account.size(); for (int i = 2; i < mailCnt; i++) { mySub.merge(mailID[firstMail], mailID[account[i]]); } } vector<vector<string>> res; map<int, unordered_set<string>> mailCluster; for (auto& it : mailID) { int rootMail = mySub.findParent(mailID[it.first]); mailCluster[rootMail].insert(it.first); } //生成答案 for (auto& it : mailCluster) { string& name = mailName[*it.second.begin()]; vector<string> tmp = { name }; for (auto& mail : it.second) { tmp.push_back(mail); } sort(tmp.begin() + 1, tmp.end()); res.push_back(tmp); } return res; } class minSwapsCouplesSub { public: minSwapsCouplesSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void merge(int x, int y) { parent[findParent(y)] = findParent(x); return; } private: vector<int> parent; }; int minSwapsCouples(vector<int>& row) {//情侣牵手 int peopleCnt = row.size(), coupleCnt = peopleCnt / 2; //添加 minSwapsCouplesSub uf(coupleCnt); for (int i = 0; i < peopleCnt; i += 2) { //情侣编号 int left = row[i] / 2; int right = row[i + 1] / 2; uf.merge(left, right); } unordered_map<int, int> curMap; for (int i = 0; i < coupleCnt; i++) { int tmp = uf.findParent(i); curMap[tmp]++; } int res = 0; for (auto& it : curMap) { res += it.second - 1; } return res; } class swimInWaterSub { public: swimInWaterSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void merge(int x, int y) { parent[findParent(y)] = findParent(x); return; } private: vector<int> parent; }; int swimInWater(vector<vector<int>>& grid) {//水位上升的泳池中游泳 int gridDim = grid.size(); swimInWaterSub uf(gridDim * gridDim); vector<pair<int, int>> curMap(gridDim * gridDim); for (int i = 0; i < gridDim; i++) { for (int j = 0; j < gridDim; j++) { curMap[grid[i][j]] = make_pair(i, j); } } vector<vector<int>> dir = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} }; for (int i = 0; i < gridDim * gridDim; i++) { int rolCur = curMap[i].first, colCur = curMap[i].second; for (int j = 0; j < 4; j++) { int tmpRol = rolCur + dir[j][0], tmpCol = colCur + dir[j][1]; if (tmpRol < 0 || tmpRol == gridDim || tmpCol < 0 || tmpCol == gridDim) { continue; } if (grid[tmpRol][tmpCol] <= i) { uf.merge(rolCur * gridDim + colCur, tmpRol * gridDim + tmpCol); } } if (uf.findParent(0) == uf.findParent(gridDim * gridDim - 1)) { return i; } } return -1; } class hitBricksSub { public: hitBricksSub(int n) { parent.resize(n); nodeCnt.resize(n, 1); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = findParent(x), rootY = findParent(y); if (rootX == rootY) { return; } parent[rootY] = rootX; nodeCnt[rootX] += nodeCnt[rootY]; return; } int retNodeCnt(int x) { return nodeCnt[findParent(x)]; } private: vector<int> parent, nodeCnt; }; vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {//打砖块 int rolSize = grid.size(), colSize = grid[0].size(); int hitCnt = hits.size(); hitBricksSub uf(rolSize * colSize + 1); //标记要敲掉的转 for (vector<int>& hit : hits) { if (grid[hit[0]][hit[1]] == 1) { grid[hit[0]][hit[1]] = 2; } } //添加各个簇到并查集 for (int i = 0; i < rolSize; i++) { for (int j = 0; j < colSize; j++) { if (grid[i][j] != 1) { continue; } if (i == 0) {//墙上的 uf.merge(rolSize * colSize, i * colSize + j); } if (i > 0 && grid[i - 1][j] == 1) {//上面有转 uf.merge((i - 1) * colSize + j, i * colSize + j); } if (j > 0 && grid[i][j - 1] == 1) {//左面有砖 uf.merge(i * colSize + j - 1, i * colSize + j); } } } vector<vector<int>> dir = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} }; vector<int> res(hitCnt); for (int i = hitCnt - 1; i > -1; i--) { int rolCur = hits[i][0], colCur = hits[i][1]; if (grid[rolCur][colCur] == 0) {//剩下的全是2 res[i] = 0; continue; } int prev = uf.retNodeCnt(rolSize * colSize); if (rolCur == 0) { uf.merge(rolSize * colSize, colCur);//以防倒三角类型 } for (int j = 0; j < 4; j++) { int tmpRol = rolCur + dir[j][0], tmpCol = colCur + dir[j][1]; if (tmpRol < 0 || tmpRol >= rolSize || tmpCol < 0 || tmpCol >= colSize) { continue; } if (grid[tmpRol][tmpCol] == 1) { uf.merge(rolCur * colSize + colCur, tmpRol * colSize + tmpCol); } } int curr = uf.retNodeCnt(rolSize * colSize); res[i] = max(0, curr - prev - 1); grid[rolCur][colCur] = 1; } return res; } class numSimilarGroupsSub { public: numSimilarGroupsSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = findParent(x), rootY = findParent(y); parent[rootY] = rootX; return; } int clusterCnt() { unordered_set<int> clusterSet; int parentCnt = parent.size(); for (int i = 0; i < parentCnt; i++) { clusterSet.emplace(findParent(i)); } return clusterSet.size(); } private: vector<int> parent; }; int numSimilarGroups(vector<string>& strs) {//相似字符串组 unordered_map<string, int> strMap; int strCnt = strs.size(); int id = 0; for (string& str : strs) { if (strMap.count(str) < 1) { strMap[str] = id++; } } numSimilarGroupsSub uf(id); for (int i = 0; i < strCnt; i++) { for (int j = i + 1; j < strCnt; j++) { if (numSimilarGroupsSililar(strs[i], strs[j])) { uf.merge(strMap[strs[i]], strMap[strs[j]]); } } } int res = uf.clusterCnt(); return res; } bool numSimilarGroupsSililar(string& str1, string& str2) { int strLen = str1.size(); string tmp; for (int i = 0; i < strLen; i++) { if (str1[i] != str2[i]) { tmp.push_back(abs(str1[i] - str2[i])); } } if (tmp.size() != 2) { return false; } for (int i = 1; i < tmp.size(); i++) { if (tmp[i] != tmp[0]) { return false; } } return true; } class minMalwareSpreadISub { public: minMalwareSpreadISub(int n) { parent.resize(n); clusterCnt.resize(n, 1); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = findParent(x), rootY = findParent(y); if (rootX == rootY) { return; } parent[rootY] = rootX; clusterCnt[rootX] += clusterCnt[rootY]; return; } int retClusterNode(int x) { return clusterCnt[findParent(x)]; } private: vector<int> parent; vector<int> clusterCnt; }; int minMalwareSpreadI(vector<vector<int>>& grid, vector<int>& initial) {//尽量减少恶意软件的传播 int gridDim = grid.size(); minMalwareSpreadISub uf(gridDim); for(int i = 0; i < gridDim; i++) { for (int j = i + 1; j < gridDim; j++) { if (grid[i][j] == 0) { continue; } uf.merge(i, j); } } int initialCnt = initial.size(); vector<int> infected(gridDim); for (int& num : initial) { //保存这一个簇由几个节点感染; infected[uf.findParent(num)]++; } sort(initial.begin(), initial.end()); int maxCnt = INT_MIN, res = initial[0]; for (int& num : initial) { int rootNum = uf.findParent(num); if (infected[rootNum] != 1) { continue; } int tmp = uf.retClusterNode(num); if (tmp > maxCnt) { maxCnt = tmp; res = num; } } return res; } class minMalwareSpreadSub { public: minMalwareSpreadSub(int n) { parent.resize(n); clusterCnt.resize(n, 1); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int findParent(int x) { if (x != parent[x]) { parent[x] = findParent(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = findParent(x), rootY = findParent(y); if (rootX == rootY) { return; } parent[rootY] = rootX; clusterCnt[rootX] += clusterCnt[rootY]; return; } int retClusterNode(int x) { return clusterCnt[findParent(x)]; } private: vector<int> parent; vector<int> clusterCnt; }; int minMalwareSpread(vector<vector<int>>& grid, vector<int>& initial) {//尽量减少恶意软件的传播 II int gridDim = grid.size(); sort(initial.begin(), initial.end()); int maxCnt = INT_MAX, res = initial[0]; for (int& node : initial) { minMalwareSpreadSub uf(gridDim); for (int i = 0; i < gridDim; i++) { if (i == node) { continue; } for (int j = i + 1; j < gridDim; j++) { if (j == node) { continue; } if (grid[i][j] == 1) { uf.merge(i, j); } } } unordered_set<int> rootSet; for (int& infectNode : initial) { rootSet.insert(uf.findParent(infectNode)); } int nodeCnt = 0; for (auto& rootNode : rootSet) { nodeCnt += uf.retClusterNode(rootNode); } if (nodeCnt < maxCnt) { maxCnt = nodeCnt; res = node; } } return res; } class removeStonesSub { public: removeStonesSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int find(int x) { if (x != parent[x]) { parent[x] = find(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = find(x), rootY = find(y); if (rootX == rootY) { return; } parent[rootY] = rootX; return; } int connectNodeCnt() { int res = 0, n = parent.size(); for (int i = 0; i < n; i++) { if (i == parent[i]) { res++; } } return res; } private: vector<int> parent; }; int removeStones(vector<vector<int>>& stones) {//移除最多的同行或同列石头 int stoneCnt = stones.size(); if (stoneCnt < 2) { return 0; } removeStonesSub uf(stoneCnt); for (int i = 0; i < stoneCnt; i++) { for (int j = i + 1; j < stoneCnt; j++) { if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) { uf.merge(i, j); } } } return stoneCnt - uf.connectNodeCnt(); } class largestComponentSizeSub { public: largestComponentSizeSub(int n) { parent.resize(n); nodeCnt.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } for (int i = 100001; i < n; i++) { nodeCnt[i] = 1; } return; } int find(int x) { if (x != parent[x]) { parent[x] = find(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = find(x), rootY = find(y); if (rootX == rootY) { return; } parent[rootY] = rootX; nodeCnt[rootX] += nodeCnt[rootY]; return; } int maxConnected(int start) { int res = 0, n = parent.size(); for (int i = start; i < n; i++) { int tmp = find(i); res = max(res, nodeCnt[tmp]); } return res; } private: vector<int> parent; vector<int> nodeCnt; }; int largestComponentSize(vector<int>& nums) {//按公因数计算最大组件大小 //sort(nums.begin(), nums.end()); int numsLen = nums.size(); largestComponentSizeSub uf(numsLen + 100001); for (int i = 0; i < numsLen; i++) { for (int j = 1; j * j <= nums[i]; j++) { if (nums[i] % j == 0) { if (j != 1) { uf.merge(j, i + 100001); } uf.merge(nums[i] / j, i + 100001); } } } int res = 0; return uf.maxConnected(100001); } class regionsBySlashesSub { public: regionsBySlashesSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int find(int x) { if (x != parent[x]) { parent[x] = find(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = find(x), rootY = find(y); if (rootX == rootY) { return; } parent[rootY] = rootX; return; } int countCluster() { int n = parent.size(); int res = 0; for (int i = 0; i < n; i++) { if (parent[i] == i){ res++; } } return res; } private: vector<int> parent; }; int regionsBySlashes(vector<string>& grid) {//由斜杠划分区域 int gridDim = grid.size(), totalGrid = gridDim * gridDim; //每一个方块最多有两种分割方式,按照上右下左编号为1234 regionsBySlashesSub uf(totalGrid * 4); vector<vector<int>> dir = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} }; for (int i = 0; i < gridDim; i++) { for (int j = 0; j < gridDim; j++) { int base = i * gridDim + j; if (grid[i][j] == ' ') { for (int k = 1; k < 4; k++) { uf.merge(base, k * totalGrid + base); } } else if (grid[i][j] == '/') { uf.merge(base, 3 * totalGrid + base); uf.merge(2 * totalGrid + base, totalGrid + base); } else { uf.merge(base, totalGrid + base); uf.merge(2 * totalGrid + base, 3 * totalGrid + base); } if (i > 0) { uf.merge((i - 1) * gridDim + j + totalGrid * 2, base); } if (j > 0) { uf.merge(i * gridDim + j - 1 + totalGrid, totalGrid * 3 + base); } } } return uf.countCluster(); } class equationsPossibleSub { public: equationsPossibleSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int find(int x) { if (x != parent[x]) { parent[x] = find(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = find(x), rootY = find(y); if (rootX == rootY) { return; } parent[rootY] = rootX; return; } int countCluster() { int n = parent.size(); int res = 0; for (int i = 0; i < n; i++) { if (parent[i] == i) { res++; } } return res; } private: vector<int> parent; }; bool equationsPossible(vector<string>& equations) {//等式方程的可满足性 equationsPossibleSub uf(26); int id = 0; unordered_map<char, int> curMap; for (string& eq : equations) { if (curMap.count(eq[0]) < 1) { curMap[eq[0]] = id++; } if (curMap.count(eq[3]) < 1) { curMap[eq[3]] = id++; } } for (string& eq : equations) { if (eq[1] == '=') { uf.merge(curMap[eq[0]], curMap[eq[3]]); } } for (string& eq : equations) { if (eq[1] == '!') { int rootX = uf.find(curMap[eq[0]]), rootY = uf.find(curMap[eq[3]]); if (rootX == rootY) { return false; } } } return true; } class smallestStringWithSwapsSub { public: smallestStringWithSwapsSub(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } return; } int find(int x) { if (x != parent[x]) { parent[x] = find(parent[x]); } return parent[x]; } void merge(int x, int y) { int rootX = find(x), rootY = find(y); if (rootX == rootY) { return; } parent[rootY] = rootX; return; } int countCluster() { int n = parent.size(); int res = 0; for (int i = 0; i < n; i++) { if (parent[i] == i) { res++; } } return res; } private: vector<int> parent; }; string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {//交换字符串中的元素 int sLen = s.size(); smallestStringWithSwapsSub uf(sLen); for (vector<int>& pair : pairs) { uf.merge(pair[0], pair[1]); } unordered_map<int, vector<char>> charMap; for (int i = 0; i < sLen; i++) { charMap[uf.find(i)].push_back(s[i]); } for (auto& it : charMap) { sort(it.second.begin(), it.second.end()); } string res(sLen, ' '); for (int i = sLen - 1; i > -1; i--) { int cur = uf.find(i); res[i] = *(charMap[cur].end() - 1); charMap[cur].pop_back(); } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "dcab"; string b = "this apple is sour"; vector<int> inpt1 = { 4, 6, 15, 35 }; vector<int> inpt2 = { 2,4,1,1,3 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {1, 1, 0}, {1, 1, 0}, {0, 0, 1} }; vector<vector<int>> board = { {1,0,0,0,1,0,0,0,0,0,1}, {0,1,0,1,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,1,0,0,0}, {0,1,0,1,0,1,0,0,0,0,0}, {1,0,0,0,1,0,0,0,0,0,0}, {0,0,0,1,0,1,0,0,1,1,0}, {0,0,0,0,0,0,1,1,0,0,0}, {0,0,1,0,0,0,1,1,0,0,0}, {0,0,0,0,0,1,0,0,1,0,0}, {0,0,0,0,0,1,0,0,0,1,0}, {1,0,0,0,0,0,0,0,0,0,1} }; vector<vector<int>> equations = { {0, 3}, {1, 2} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution.smallestStringWithSwaps(a, equations); return 0; } #endif //cookBook-线段树 #if false class Solution { public: struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class getSkylineSub { public: getSkylineSub(int n) { d.resize(n * 4 + 5, 0); lazy.resize(n * 4 + 5, 0); return; } void update(int nodeLeft, int nodeRight, int left, int right, int val, int id) { //更新区间最大值,节点左右范围,查询区间范围,更新值,节点id(1开始) if (nodeLeft >= left && nodeRight <= right) {//查询区间完全覆盖节点 lazy[id] = max(val, lazy[id]); d[id] = max(lazy[id], d[id]); return; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int sonLeft = id * 2, sonRight = id * 2 + 1; if (lazy[id] && nodeLeft != nodeRight) {//后半句判断是不是叶子节点,由于只考虑最大值,只有更新 lazy[sonLeft] = max(lazy[sonLeft], lazy[id]); lazy[sonRight] = max(lazy[sonRight], lazy[id]); d[sonLeft] = max(d[sonLeft], lazy[sonLeft]); d[sonRight] = max(d[sonRight], lazy[sonRight]); lazy[id] = 0; } if (left <= nodeMid) {//跨区间向左更新 update(nodeLeft, nodeMid, left, right, val, sonLeft); } if (right > nodeMid) {//跨期间向右更新 update(nodeMid + 1, nodeRight, left, right, val, sonRight); } d[id] = max(d[sonLeft], d[sonRight]); return; } int qury(int nodeLeft, int nodeRight, int left, int right, int id) { if (nodeLeft >= left && nodeRight <= right) { return d[id]; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int sonLeft = id * 2, sonRight = id * 2 + 1; if (lazy[id] && nodeLeft != nodeRight) { lazy[sonLeft] = max(lazy[sonLeft], lazy[id]); lazy[sonRight] = max(lazy[sonRight], lazy[id]); d[sonLeft] = max(d[sonLeft], lazy[sonLeft]); d[sonRight] = max(d[sonRight], lazy[sonRight]); lazy[id] = 0; } int res = 0; if (left <= nodeMid) { res = max(res, qury(nodeLeft, nodeMid, left, right, sonLeft)); } if (right > nodeMid) { res = max(res, qury(nodeMid + 1, nodeRight, left, right, sonRight)); } return res; } private: vector<int> d, lazy; }; vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {//天际线问题 unordered_map<int, int> curMap, reverseCurMap; set<int> curSet; for (auto& it : buildings) { curSet.insert(it[0]); curSet.insert(it[1]); curSet.insert(it[1] - 1); } int id = 1; for (auto& it : curSet) { curMap[it] = id; reverseCurMap[id] = it; id++; } getSkylineSub segTree(id--); for (auto& it : buildings) { segTree.update(1, id, curMap[it[0]], curMap[it[1] - 1], it[2], 1); } vector<vector<int>> res; int last = -1; for (int i = 1; i <= id; i++) { int tmp = segTree.qury(1, id, i, i, 1); if (tmp != last) { res.push_back({ reverseCurMap[i], tmp }); } last = tmp; } return res; } class NumArrayI {//区域和检索 - 数组不可变 public: NumArrayI(vector<int>& nums) { int numsLen = nums.size(); data = nums; data.insert(data.begin(), 0); for (int i = 1; i <= numsLen; i++) { data[i] += data[i - 1]; } return; } int sumRange(int left, int right) { return data[right + 1] - data[left]; } private: vector<int> data; }; class NumArray {//区域和检索 - 数组可修改 public: NumArray(vector<int>& nums) { numsLen = nums.size(); data.resize(numsLen * 4, 0); lazy.resize(numsLen * 4, 0); for (int i = 0; i < numsLen; i++) { update(i + 1, nums[i]); } return; } void update(int index, int val) { update(1, numsLen, index, index, val, 1); return; } int sumRange(int left, int right) { return qury(1, numsLen, left + 1, right + 1, 1); } private: vector<int> data, lazy; int numsLen; void update(int nodeLeft, int nodeRight, int segLeft, int segRight, int val, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) {//更改整个区间内容 data[nodeID] = (nodeRight - nodeLeft + 1) * val;//和 lazy[nodeID] = val;//单点 return; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] = lazy[nodeID] * (nodeMid - nodeLeft + 1); data[rightSon] = lazy[nodeID] * (nodeRight - nodeMid); lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] == 0; } if (segLeft <= nodeMid) { update(nodeLeft, nodeMid, segLeft, segRight, val, leftSon); } if (segRight > nodeMid) { update(nodeMid + 1, nodeRight, segLeft, segRight, val, rightSon); } data[nodeID] = data[leftSon] + data[rightSon]; return; } int qury(int nodeLeft, int nodeRight, int segLeft, int segRight, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { return data[nodeID]; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] = lazy[nodeID] * (nodeMid - nodeLeft + 1); data[rightSon] = lazy[nodeID] * (nodeRight - nodeMid); lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] == 0; } int res = 0; if (segLeft <= nodeMid) { res += qury(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { res += qury(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } return res; } }; class countSmallerSub { public: countSmallerSub(int n) { data.resize(4 * n); lazy.resize(4 * n); numsLen = n; return; } void updateTick(int nodeLeft, int nodeRight, int segLeft, int segRight, int rootID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { data[rootID] += nodeRight - nodeLeft + 1; lazy[rootID] = 1; return; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = rootID * 2, rightSon = rootID * 2 + 1; if (lazy[rootID] != 0) { data[leftSon] += nodeMid - nodeLeft + 1; data[rightSon] += nodeRight - nodeMid; lazy[leftSon] = lazy[rightSon] = lazy[rootID]; lazy[rootID] = 0; } if (segLeft <= nodeMid) { updateTick(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { updateTick(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } data[rootID] = data[leftSon] + data[rightSon]; return; } int qury(int nodeLeft, int nodeRight, int segLeft, int segRight, int rootID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { return data[rootID]; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = rootID * 2, rightSon = rootID * 2 + 1; if (lazy[rootID] != 0) { data[leftSon] += nodeMid - nodeLeft + 1; data[rightSon] += nodeRight - nodeMid; lazy[leftSon] = lazy[rightSon] = lazy[rootID]; lazy[rootID] = 0; } int res = 0; if (segLeft <= nodeMid) { res += qury(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { res += qury(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } return res; } private: int numsLen; vector<int> data, lazy; }; vector<int> countSmaller(vector<int>& nums) {//计算右侧小于当前元素的个数 map<int, int> numMap; int id = 1; vector<int> numsCopy(nums); sort(numsCopy.begin(), numsCopy.end()); for (int& num : numsCopy) { if (numMap.count(num) < 1) { numMap[num] = id++; } } countSmallerSub segTree(--id); int numsLen = nums.size(); vector<int> res(numsLen); for (int i = numsLen - 1; i > -1; i--) { int tmp = numMap[nums[i]]; segTree.updateTick(1, id, tmp, tmp, 1); if (tmp > 1) { res[i] = segTree.qury(1, id, 1, tmp - 1, 1); } else { res[i] = 0; } } return res; } class countRangeSumSub { public: countRangeSumSub(int n) { data.resize(4 * n); lazy.resize(4 * n); numsLen = n; return; } void update(int nodeLeft, int nodeRight, int segLeft, int segRight, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { data[nodeID] += nodeRight - nodeLeft + 1; lazy[nodeID] = 1; return; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] += nodeMid - nodeLeft + 1; data[rightSon] += nodeRight - nodeMid; lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] = 0; } if (segLeft <= nodeMid) { update(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { update(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } data[nodeID] = data[leftSon] + data[rightSon]; return; } int qury(int nodeLeft, int nodeRight, int segLeft, int segRight, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { return data[nodeID]; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] += nodeMid - nodeLeft + 1; data[rightSon] += nodeRight - nodeMid; lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] = 0; } int res = 0; if (segLeft <= nodeMid) { res += qury(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { res += qury(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } return res; } private: vector<int> data, lazy; int numsLen; }; int countRangeSum(vector<int>& nums, int lower, int upper) {//区间和的个数 long long sum = 0; vector<long long> prefix = { 0 }; for (int& num : nums) { sum += num; prefix.push_back(sum); } set<long long> numSet; for (long long& num : prefix) { numSet.insert(num); numSet.insert(num - lower); numSet.insert(num - upper); } int id = 1; unordered_map<long long, int> numMap; for (auto& num : numSet) { numMap[num] = id++; } countRangeSumSub segTree(--id); int res = 0; for (auto& num : prefix) { res += segTree.qury(1, id, numMap[num - upper], numMap[num - lower], 1); segTree.update(1, id, numMap[num], numMap[num], 1); } return res; } class reversePairsSub { public: reversePairsSub(int n) { data.resize(4 * n); lazy.resize(4 * n); numsLen = n; return; } void update(int nodeLeft, int nodeRight, int segLeft, int segRight, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { data[nodeID] += nodeRight - nodeLeft + 1; lazy[nodeID] = 1; return; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] += nodeMid - nodeLeft + 1; data[rightSon] += nodeRight - nodeMid; lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] = 0; } if (segLeft <= nodeMid) { update(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { update(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } data[nodeID] = data[leftSon] + data[rightSon]; return; } int qury(int nodeLeft, int nodeRight, int segLeft, int segRight, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { return data[nodeID]; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] += nodeMid - nodeLeft + 1; data[rightSon] += nodeRight - nodeMid; lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] = 0; } int res = 0; if (segLeft <= nodeMid) { res += qury(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { res += qury(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } return res; } private: vector<int> data, lazy; int numsLen; }; int reversePairs(vector<int>& nums) {//翻转对 vector<long long> numsCopy; for (int& num : nums) { numsCopy.push_back(num); numsCopy.push_back(1l + 2l * num); } sort(numsCopy.begin(), numsCopy.end()); unordered_map<long long, int> numsMap; int id = 1; for (long long& num : numsCopy) { if (numsMap.count(num) < 1) { numsMap[num] = id++; } } reversePairsSub segTree(--id); int res = 0; for (int& num : nums) { res += segTree.qury(1, id, numsMap[2l * num + 1l], id, 1); segTree.update(1, id, numsMap[num], numsMap[num], 1); } return res; } class fallingSquaresSub {//线段树时间常数大一些 public: fallingSquaresSub(int n) { data.resize(4 * n); lazy.resize(4 * n); numsLen = n; return; } void update(int nodeLeft, int nodeRight, int segLeft, int segRight, int val, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { data[nodeID] = (nodeRight - nodeLeft + 1) * val; lazy[nodeID] = val; return; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] = (nodeMid - nodeLeft + 1) * val; data[rightSon] = (nodeRight - nodeMid) * val; lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] = 0; } if (segLeft <= nodeMid) { update(nodeLeft, nodeMid, segLeft, segRight, val, leftSon); } if (segRight > nodeMid) { update(nodeMid + 1, nodeRight, segLeft, segRight, val, rightSon); } data[nodeID] = data[leftSon] + data[rightSon]; return; } long long qury(int nodeLeft, int nodeRight, int segLeft, int segRight, int nodeID) { if (segLeft <= nodeLeft && nodeRight <= segRight) { return data[nodeID]; } int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; int leftSon = nodeID * 2, rightSon = nodeID * 2 + 1; if (lazy[nodeID] != 0) { data[leftSon] = (nodeMid - nodeLeft + 1) * lazy[nodeID]; data[rightSon] = (nodeRight - nodeMid) * lazy[nodeID]; lazy[leftSon] = lazy[rightSon] = lazy[nodeID]; lazy[nodeID] = 0; } long long res = 0; if (segLeft <= nodeMid) { res += qury(nodeLeft, nodeMid, segLeft, segRight, leftSon); } if (segRight > nodeMid) { res += qury(nodeMid + 1, nodeRight, segLeft, segRight, rightSon); } return res; } private: vector<long long> data, lazy; int numsLen; }; vector<int> fallingSquares(vector<vector<int>>& positions) {//掉落的方块 vector<int> pos; for (vector<int>& square : positions) { pos.push_back(square[0]); pos.push_back(square[0] + square[1] - 1); } sort(pos.begin(), pos.end()); unordered_map<int, int> posMap; int id = 1; for (int& num : pos) { if (posMap.count(num) < 1) { posMap[num] = id++; } } fallingSquaresSub segTree(--id); vector<int> res; long long tmp = 0; for (vector<int>& square : positions) { long long segMax = 0; for (int i = 0; i < square[1]; i++) { if (posMap.count(square[0] + i) > 0) { segMax = max(segMax, segTree.qury(1, id, posMap[square[0] + i], posMap[square[0] + i], 1)); } } segTree.update(1, id, posMap[square[0]], posMap[square[0] + square[1] - 1], segMax + square[1], 1); tmp = max(tmp, segMax + square[1]); res.push_back((int)tmp); } return res; } class RangeModule {//Range 模块 public://可以实现树的动态扩展,非固定节点数量 RangeModule() { segment.clear(); return; } void addRange(int left, int right) { auto a = segment.lower_bound(left); auto b = segment.lower_bound(right); if (a == segment.end()) { segment[right] = left; } else { int start = a->second; auto p = a; while (p != b) { a++; segment.erase(p); p = a; } if (b == segment.end() || b->second > right) { segment[right] = min(start, left); } else { b->second = min(start, left); } } return; } bool queryRange(int left, int right) { auto p = segment.lower_bound(right); if (p == segment.end() || p->second > left) { return false; } return true; } void removeRange(int left, int right) { auto a = segment.lower_bound(left); auto b = segment.lower_bound(right); if (a == segment.end() || right <= segment.begin()->second) { return; } else { int x = a->second; auto p = a; while (p != b) { a++; segment.erase(p); p = a; } if (b != segment.end()) { int y = b->first; if (b->second < right) { segment.erase(b); if (right < y) { segment[y] = right; } } } if (x < left) { segment[left] = x; } } return; } private: map<int, int> segment;//右-左 }; class MyCalendarThree {//我的日程安排表 III //需要动态增加节点的线段树 public: MyCalendarThree() { rootNode = new segTreeNode(0, 1e9); return; } int book(int start, int end) { return insert(start, end, rootNode); } private: struct segTreeNode { int nodeLeft = -1, nodeRight = -1; int val = 0; int lazy = 0; segTreeNode* leftSon = nullptr; segTreeNode* rightSon = nullptr; segTreeNode(int start, int end) { nodeLeft = start, nodeRight = end; return; } }; segTreeNode* rootNode; int insert(int segLeft, int segRight, segTreeNode* root) { if (segLeft <= root->nodeLeft && root->nodeRight <= segRight) {//节点范围是插入范围的子集 //欠债阶段,这种情况是完全确定的,可以确定债权 root->val++; root->lazy++; } else if (root->nodeLeft < segRight && segLeft < root->nodeRight) {//待插入区间与节点范围有重叠 int nodeMid = root->nodeLeft + (root->nodeRight - root->nodeLeft) / 2; if (root->leftSon == nullptr) { root->leftSon = new segTreeNode(root->nodeLeft, nodeMid); } if (root->rightSon == nullptr) { root->rightSon = new segTreeNode(nodeMid, root->nodeRight); } //还债阶段,因为债务是在完全包含的情况下欠的,所以可以下放 root->leftSon->val += root->lazy; root->rightSon->val += root->lazy; root->leftSon->lazy += root->lazy; root->rightSon->lazy += root->lazy; root->lazy = 0; int leftVal = insert(segLeft, segRight, root->leftSon); int rightVal = insert(segLeft, segRight, root->rightSon); root->val = max(leftVal, rightVal); } return root->val; } }; //class rectangleAreaSub {//紧贴坐标轴的,实际应该使用单轴扫掠 //public: // rectangleAreaSub(int n) { // data.resize(4 * n); // lazy.resize(4 * n); // return; // } // void update(int nodeLeft, int nodeRight, int segLeft, int segRight, int val, int id) { // if (segLeft <= nodeLeft && nodeRight <= segRight) { // lazy[id] = max(lazy[id], val); // data[id] = max(data[id], lazy[id]); // return; // } // int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; // int leftSon = id * 2, rightSon = id * 2 + 1; // if (lazy[id] != 0) { // lazy[leftSon] = max(lazy[leftSon], lazy[id]); // lazy[rightSon] = max(lazy[rightSon], lazy[id]); // data[leftSon] = max(data[leftSon], lazy[leftSon]); // data[rightSon] = max(data[rightSon], lazy[rightSon]); // lazy[id] = 0; // } // if (segLeft <= nodeMid) { // update(nodeLeft, nodeMid, segLeft, segRight, val, leftSon); // } // if (segRight > nodeMid) { // update(nodeMid + 1, nodeRight, segLeft, segRight, val, rightSon); // } // data[id] = max(data[leftSon], data[rightSon]); // return; // } // int qury(int nodeLeft, int nodeRight, int segLeft, int segRight, int id) { // if (segLeft <= nodeLeft && nodeRight <= segRight) { // data[id] = max(data[id], lazy[id]); // return data[id]; // } // int nodeMid = nodeLeft + (nodeRight - nodeLeft) / 2; // int leftSon = id * 2, rightSon = id * 2 + 1; // if (lazy[id] != 0) { // lazy[leftSon] = max(lazy[leftSon], lazy[id]); // lazy[rightSon] = max(lazy[rightSon], lazy[id]); // data[leftSon] = max(data[leftSon], lazy[leftSon]); // data[rightSon] = max(data[rightSon], lazy[rightSon]); // lazy[id] = 0; // } // int res = 0; // if (segLeft <= nodeMid) { // res = max(qury(nodeLeft, nodeMid, segLeft, segRight, leftSon), res); // } // if (segRight > nodeMid) { // res = max(qury(nodeMid + 1, nodeRight, segLeft, segRight, rightSon), res); // } // return res; // } //private: // vector<int> data, lazy; //}; //int rectangleArea(vector<vector<int>>& rectangles) {//矩形面积 II // vector<int> pos, resPos; // for (vector<int>& rect : rectangles) { // pos.push_back(rect[0]); // pos.push_back(rect[0] - 1); // pos.push_back(rect[2] - 1); // pos.push_back(rect[2]); // resPos.push_back(rect[0]); // resPos.push_back(rect[2]); // } // sort(pos.begin(), pos.end()); // sort(resPos.begin(), resPos.end()); // unordered_map<int, int> posMap; // int id = 1; // for (int& pt : pos) { // if (posMap.count(pt) < 1) { // posMap[pt] = id++; // } // } // rectangleAreaSub segTree(--id); // long long res = 0; // for (vector<int>& rect : rectangles) { // segTree.update(1, id, posMap[rect[0]], posMap[rect[2] - 1], rect[3], 1); // } // int mod = 1e9 + 7, lastPoint = resPos[0]; // for (int& currentPoint : resPos) { // if (currentPoint == lastPoint) { // continue; // } // res = (res + 1l * (currentPoint - lastPoint) * segTree.qury(1, id, posMap[lastPoint], posMap[currentPoint - 1], 1)) % mod; // lastPoint = currentPoint; // } // return (int)(res % mod); //} }; int main(int argc, char* argv[]) { Solution mySolution; string a = "dcab"; string b = "this apple is sour"; vector<int> inpt1 = { 2, 4, 3, 5, 1 }; vector<int> inpt2 = { 2,4,1,1,3 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<int>> board = { {1,0,0,0,1,0,0,0,0,0,1}, {0,1,0,1,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,1,0,0,0}, {0,1,0,1,0,1,0,0,0,0,0}, {1,0,0,0,1,0,0,0,0,0,0}, {0,0,0,1,0,1,0,0,1,1,0}, {0,0,0,0,0,0,1,1,0,0,0}, {0,0,1,0,0,0,1,1,0,0,0}, {0,0,0,0,0,1,0,0,1,0,0}, {0,0,0,0,0,1,0,0,0,1,0}, {1,0,0,0,0,0,0,0,0,0,1} }; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution; return 0; } #endif // 图解算法数据结构--动态规划 #if false class Solution { public: int fib(int n) { if (n < 2){ return n; } int n_2 = 0, n_1 = 1, n_0 = 0; while (--n > 0){ n_0 = (n_2 + n_1) % 1000000007; n_2 = n_1; n_1 = n_0; } return n_0; } int numWays(int n) { n++; if (n < 2){ return n; } int n_2 = 0, n_1 = 1, n_0 = 0; while (--n > 0){ n_0 = (n_2 + n_1) % 1000000007; n_2 = n_1; n_1 = n_0; } return n_0; } bool isMatch(string s, string p) { size_t sLen = s.size(), pLen = p.size(), sCur = 0, pCur = 0; vector<vector<int>> dp(sLen + 1, vector<int>(pLen + 1, 0)); dp[0][0] = 1; auto isMatch = [&](int i, int j){// 当前字符是否匹配 if (i == 0){ return false; } if (p[j - 1] == '.'){ return true; } return s[i - 1] == p[j - 1]; }; for (int i = 0; i <= sLen; i++){ for (int j = 1; j <= pLen; j++){ if (p[j - 1] == '*'){//任意数量匹配 dp[i][j] |= dp[i][j - 2];//数量为 0 匹配 if (isMatch(i, j - 1)){// 当前字符匹配 dp[i][j] |= dp[i - 1][j]; } } else { if (isMatch(i, j)){// 当前字符匹配 dp[i][j] |= dp[i - 1][j - 1]; } } } } return dp[sLen][pLen] == 1; } int maxSubArray(vector<int>& nums) { size_t numsLen = nums.size(); int res = nums[0], pre = 0; for (int& num : nums){ pre = max(pre + num, num);//对于单独数列 res = max(res, pre);//对于所有数列 } return res; } int translateNum(int num) { int n_1 = 1, n_2 = 1, x = 0, y = num % 10, res = 1; while (num > 9){ num /= 10; x = num % 10; int tmp = x * 10 + y; res = tmp > 9 && tmp < 26 ? n_1 + n_2 : n_1; n_2 = n_1; n_1 = res; y = x; } return res; } int maxValue(vector<vector<int>>& grid) { size_t rolSize = grid.size(), colSize = grid[0].size(); for (int i = 1; i < rolSize; i++){ grid[i][0] += grid[i - 1][0]; } for (int i = 1; i < colSize; i++){ grid[0][i] += grid[0][i - 1]; } for (int i = 1; i < rolSize; i++){ for (int j = 1; j < colSize; j++){ grid[i][j] += max(grid[i - 1][j], grid[i][j - 1]); } } return grid[rolSize - 1][colSize - 1]; } int lengthOfLongestSubstring(string s) { unordered_map<char, int> chMap; size_t sLen = s.size(); int curLeft = 0, curRight = 0; int res = 0; while (curRight < sLen){ char& ch = s[curRight]; if (chMap.count(ch) && chMap[ch] > 0){ chMap[s[curLeft++]]--; } else{ chMap[s[curRight++]]++; } res = max(res, curRight - curLeft); } res = max(res, curRight - curLeft); return res; } int nthUglyNumber(int n) { vector<int> dp(n + 1, 0); dp[1] = 1; int cur2 = 1, cur3 = 1, cur5 = 1; for (int i = 2; i <= n; i++){ int num2 = dp[cur2] * 2; int num3 = dp[cur3] * 3; int num5 = dp[cur5] * 5; dp[i] = min(min(num2, num3), num5); if (dp[i] == num2){ cur2++; } if (dp[i] == num3){ cur3++; } if (dp[i] == num5){ cur5++; } } return dp[n]; } vector<double> dicesProbability(int n) { vector<vector<int>> dp(n + 1, vector<int>(6 * n + 1, 0)); for (int i = 1; i <= 6; i++){ dp[1][i] = 1; } for (int i = 2; i <= n; i++){ for (int j = i; j <= 6 * i; j++){ for (int cur = 1; cur <= 6; cur++){ if (j - cur < 1){//最小面值 break; } dp[i][j] += dp[i - 1][j - cur]; } } } double base = 1.0 / pow(6, n); vector<double> res(5 * n + 1, 0.0); for (int i = n; i <= 6 * n; i++){ res[i - n] = dp[n][i] * base; } return res; } int maxProfit(vector<int>& prices) { int cost = INT32_MAX, profit = 0; for (int & price : prices){ cost = min(cost, price); profit = max(profit, price - cost); } return profit; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "dcab"; string b = "this apple is sour"; vector<int> inpt1 = { 7,1,5,3,6,4 }; vector<int> inpt2 = { 2,4,1,1,3 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<int>> board = { {1,0,0,0,1,0,0,0,0,0,1}, {0,1,0,1,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,1,0,0,0}, {0,1,0,1,0,1,0,0,0,0,0}, {1,0,0,0,1,0,0,0,0,0,0}, {0,0,0,1,0,1,0,0,1,1,0}, {0,0,0,0,0,0,1,1,0,0,0}, {0,0,1,0,0,0,1,1,0,0,0}, {0,0,0,0,0,1,0,0,1,0,0}, {0,0,0,0,0,1,0,0,0,1,0}, {1,0,0,0,0,0,0,0,0,0,1} }; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution; mySolution.maxProfit(inpt1); return 0; } #endif // 图解算法数据结构--搜索与回溯算法 #if false class Solution { public: struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; bool exist(vector<vector<char>>& board, string word) { int rolSize = board.size(), colSize = board[0].size(); vector<vector<bool>> vist(rolSize, vector<bool>(colSize, false)); vector<vector<int>> dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; for (int i = 0; i < rolSize; i++){ for (int j = 0; j < colSize; j++){ if (existSub(board, vist, i, j, word, 0, rolSize, colSize, dir)){ return true; } } } return false; } bool existSub(vector<vector<char>>& board, vector<vector<bool>>& vist, int rolCur, int colCur, string& word, int cur, int& rolSize, int& colSize, vector<vector<int>>& dir){ if (cur == word.size()){ return true; } if (word[cur] != board[rolCur][colCur]){ return false; } if (cur == word.size() - 1){ return true; } vist[rolCur][colCur] = true; for (int i = 0; i < 4; i++){ int tmpRol = rolCur + dir[i][0], tmpCol = colCur + dir[i][1]; if (tmpCol < 0 || tmpCol >= colSize || tmpRol < 0 || tmpRol >= rolSize || vist[tmpRol][tmpCol]){ continue; } if (existSub(board, vist, tmpRol, tmpCol, word, cur + 1, rolSize, colSize, dir)){ return true; } } vist[rolCur][colCur] = false; return false; } int movingCount(int m, int n, int k) { vector<vector<int>> dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; vector<vector<bool>> vist(m, vector<bool>(n, false)); int res = movingCountSub(vist, 0, 0, m, n, dir, k); return res; } int movingCountSub(vector<vector<bool>>& vist, int rolCur, int colCur, int rolSize, int colSize, vector<vector<int>>& dir, int lim){ if (rolCur < 0 || rolCur >= rolSize || colCur < 0 || colCur >= colSize || vist[rolCur][colCur]){ return 0; } int sum = 0, rolCopy = rolCur, colCopy = colCur; while (rolCopy){ sum += rolCopy % 10; rolCopy /= 10; } while (colCopy){ sum += colCopy % 10; colCopy /= 10; } if (sum > lim){ return 0; } vist[rolCur][colCur] = true; int res = 1; for (int i = 0; i < 4; i++){ int tmpRol = rolCur + dir[i][0], tmpCol = colCur + dir[i][1]; res += movingCountSub(vist, tmpRol, tmpCol, rolSize, colSize, dir, lim); } // vist[rolCur][colCur] = false; return res; } bool isSubStructure(TreeNode* A, TreeNode* B) { return (A != nullptr && B != nullptr) && (isSubStructureSub(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B)); } bool isSubStructureSub(TreeNode* A, TreeNode* B){ if (B == nullptr){ return true; } if (A == nullptr || A->val != B->val){ return false; } return isSubStructureSub(A->left, B->left) && isSubStructureSub(A->right, B->right); } TreeNode* mirrorTree(TreeNode* root) { if (root == nullptr){ return nullptr; } TreeNode* tmp = mirrorTree(root->left); root->left = mirrorTree(root->right); root->right = tmp; return root; } bool isSymmetric(TreeNode* root) { return root == nullptr || isSymmetricSub(root->left, root->right); } bool isSymmetricSub(TreeNode* left, TreeNode* right){ if (left == nullptr && right == nullptr){ return true; } if (left == nullptr || right == nullptr || left->val != right->val){ return false; } return isSymmetricSub(left->left, right->right) && isSymmetricSub(left->right, right->left); } vector<int> levelOrderI(TreeNode* root) { queue<TreeNode*> que; que.push(root); vector<int> res; while (!que.empty()){ root = que.front(); que.pop(); if (root == nullptr){ continue; } res.push_back(root->val); que.push(root->left); que.push(root->right); } return res; } vector<vector<int>> levelOrderII(TreeNode* root) { vector<vector<int>> res; if (root == nullptr){ return res; } queue<TreeNode*> que; que.push(root); while (!que.empty()){ int queLen = que.size(); vector<int> tmp; while (queLen--){ root = que.front(); que.pop(); tmp.push_back(root->val); if (root->left){ que.push(root->left); } if (root->right){ que.push(root->right); } } res.push_back(tmp); } return res; } vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if (root == nullptr){ return res; } queue<TreeNode*> que; que.push(root); bool needReverse = false; while (!que.empty()){ int queLen = que.size(); vector<int> tmp; while (queLen--){ root = que.front(); que.pop(); tmp.push_back(root->val); if (root->left){ que.push(root->left); } if (root->right){ que.push(root->right); } } if (needReverse){ reverse(tmp.begin(), tmp.end()); } needReverse = !needReverse; res.push_back(tmp); } return res; } vector<vector<int>> pathSum(TreeNode* root, int target) { vector<int> tmp; vector<vector<int>> res; pathSumSub(root, 0, target, tmp, res); return res; } void pathSumSub(TreeNode* root, int sum, int target, vector<int>& tmp, vector<vector<int>>& res){ if (root == nullptr){ return; } tmp.push_back(root->val); sum += root->val; if (root->left == nullptr && root->right == nullptr && sum == target){ res.push_back(tmp); } pathSumSub(root->left, sum, target, tmp, res); pathSumSub(root->right, sum, target, tmp, res); tmp.pop_back(); return; } Node* treeToDoublyListI(Node* root) { if (root == nullptr){ return nullptr; } queue<Node*> que; treeToDoublyListDFSI(root, que); Node* head = que.front(); Node* cur = head; while (!que.empty()){ cur->right = que.front(); que.front()->left = cur; cur = que.front(); que.pop(); } cur->right = head; head->left = cur; return head; } void treeToDoublyListDFSI(Node* root, queue<Node*>& que){ if (root == nullptr){ return; } treeToDoublyListDFSI(root->left, que); que.push(root); treeToDoublyListDFSI(root->right, que); return; } Node* treeToDoublyList(Node* root) { if (root == nullptr) { return nullptr; } Node* head = nullptr; Node* pre = nullptr; treeToDoublyListDFS(root, head, pre); head->left = pre; pre->right = head; return head; } void treeToDoublyListDFS(Node* root, Node*& head, Node*& pre){ if (root == nullptr){ return; } treeToDoublyListDFS(root->left, head, pre); if (pre != nullptr){ pre->right = root; } else { head = root; } root->left = pre; pre = root; treeToDoublyListDFS(root->right, head, pre); return; } string serialize(TreeNode* root) { string res; queue<TreeNode*> que; que.push(root); while (!que.empty()){ int queLen = que.size(); while(queLen--){ TreeNode* cur = que.front(); que.pop(); if (cur == nullptr){ res += "null,"; } else { res = res + to_string(cur->val) + ","; que.push(cur->left); que.push(cur->right); } } } return res; } TreeNode* deserialize(string data) { queue<int>* que = dataStrDecode(data); if (que->size() == 0 || que->front() == -8964){ return nullptr; } queue<TreeNode*> nodeQue; TreeNode* head = new TreeNode(que->front()); TreeNode* cur = nullptr; que->pop(); nodeQue.push(head); while (!nodeQue.empty()){ int queLen = nodeQue.size(); while (queLen--){ cur = nodeQue.front(); nodeQue.pop(); if (cur == nullptr){ continue; } int val = -8964; if (!que->empty()){ val = que->front(); que->pop(); } if (val != -8964){ cur->left = new TreeNode(val); } nodeQue.push(cur->left); val = -8964; if (!que->empty()){ val = que->front(); que->pop(); } if (val != -8964){ cur->right = new TreeNode(val); } nodeQue.push(cur->right); } } delete que; return head; } queue<int>* dataStrDecode(string& data){ queue<int>* que = new queue<int>; int dataLen = data.size(), cur = 0; while (cur < dataLen){ if (data[cur] == ',' || data[cur] == '[' || data[cur] == ']'){ cur++; continue; } if (data[cur] == 'n'){ que->push(-8964); cur += 4; continue; } int sign = 1, tmpVal = 0; while (cur < dataLen && data[cur] != ',' && data[cur] != ']'){ if (data[cur] == '-'){ sign = -1; cur++; continue; } tmpVal = tmpVal * 10 + data[cur] - '0'; cur++; } que->push(tmpVal * sign); } return que; } vector<string> permutation(string s) { string tmp; unordered_set<string> stringSet; int sLen = s.size(); vector<bool> vist(sLen, false); permutationSub(s, tmp, stringSet, vist, sLen); vector<string> res; for (auto& it : stringSet){ res.push_back(it); } return res; } void permutationSub(string& s, string& tmp, unordered_set<string>& stringSet, vector<bool>& vist, int sLen){ if (tmp.size() == sLen){ stringSet.emplace(tmp); return; } for (int i = 0; i < sLen; i++){ if (vist[i]){ continue; } vist[i] = true; tmp.push_back(s[i]); permutationSub(s, tmp, stringSet, vist, sLen); tmp.pop_back(); vist[i] = false; } return; } int kthLargest(TreeNode* root, int k) { int res = 0; kthLargestSub(root, res, k); return res; } void kthLargestSub(TreeNode* root, int& res, int& k){ if (root == nullptr){ return; } kthLargestSub(root->right, res, k); if (k == 0){ return; } if (--k == 0){ res = root->val; return; } kthLargestSub(root->left, res, k); } int maxDepth(TreeNode* root) { if (root == nullptr){ return 0; } return max(maxDepth(root->left), maxDepth(root->right)) + 1; } bool isBalanced(TreeNode* root) { bool valid = true; isBalanced(root, valid); return valid; } int isBalanced(TreeNode* root, bool& valid){ if (root == nullptr || !valid){ return 0; } int left = isBalanced(root->left, valid); int right = isBalanced(root->right, valid); if (abs(left - right) > 1){ valid = false; return 0; } return max(left, right) + 1; } int sumNums(int n) { n && (n += sumNums(n - 1)); return n; } TreeNode* lowestCommonAncestorI(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr){ return nullptr; } if (p->val < root->val && q->val < root->val){ return lowestCommonAncestorI(root->left, p, q); } else if (p->val > root->val && q->val > root->val){ return lowestCommonAncestorI(root->right, p, q); } return root; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* res = nullptr; lowestCommonAncestorSub(root, p, q, res); return res; } bool lowestCommonAncestorSub(TreeNode* root, TreeNode* p, TreeNode* q, TreeNode*& res){ if (root == nullptr || res != nullptr){ return false; } bool inLeft = lowestCommonAncestorSub(root->left, p, q, res); bool inRight = lowestCommonAncestorSub(root->right, p, q, res); if (inLeft && inRight || ((root->val == p->val || root->val == q->val) && (inLeft || inRight))){ res = root; } return inLeft || inRight || (root->val == p->val || root->val == q->val); } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { 7,1,5,3,6,4 }; vector<int> inpt2 = { 2,4,1,1,3 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution.permutation(a); return 0; } #endif // 图解算法数据结构--分治 #if false class Solution { public: struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int curPos = preorder.size() - 1; return buildTreeSub(preorder, inorder, 0, curPos, 0, curPos); } TreeNode* buildTreeSub(vector<int>& preorder, vector<int>& inorder, int preLeft, int preRight, int inLeft, int inRight){ if (preLeft > preRight){ return nullptr; } TreeNode* root = new TreeNode(preorder[preLeft]); int i = 0; for (i = 0; i < inRight - inLeft; i++){ if (inorder[i + inLeft] == preorder[preLeft]){ break; } } root->left = buildTreeSub(preorder, inorder, preLeft + 1, preLeft + i, inLeft, inLeft + i - 1); root->right = buildTreeSub(preorder, inorder, preLeft + i + 1, preRight, inLeft + i + 1, inRight); return root; } double myPow(double x, int n) { bool isNeg = n < 0 ? true : false; if (n == 0x7fffffff) { if (x == 1.0 || x == -1.0) { return x; } } int i = 31; double res = 1.0, tmp = x; while (n != 0) { if (n % 2) { res *= tmp; } tmp *= tmp; n = n / 2; } if (isNeg) { res = 1 / res; } return res; } vector<int> printNumbers(int n) { int hi = pow(10, n) - 1; int lo = 1; vector<int> res(hi - lo + 1); for (int i = lo; i <= hi; i++){ res[i - lo] = i; } return res; } bool verifyPostorderI(vector<int>& postorder) { return verifyPostorderSub(postorder, 0, postorder.size() - 1); } bool verifyPostorderSub(vector<int>& postorder, int leftCur, int rightCur){ if (leftCur >= rightCur){ return true; } int cur = leftCur; while (cur < rightCur && postorder[cur] < postorder[rightCur]){ cur++; } for (int i = cur; i < rightCur; i++){ if (postorder[i] < postorder[rightCur]){ return false; } } return verifyPostorderSub(postorder, leftCur, cur - 1) && verifyPostorderSub(postorder, cur, rightCur - 1); } bool verifyPostorder(vector<int>& postorder) { stack<int> stk; int root = INT32_MAX; for (int i = postorder.size() - 1; i >= 0; i--){ if (postorder[i] > root){ return false; } while (!stk.empty() && stk.top() > postorder[i]){ root = stk.top(); stk.pop(); } stk.push(postorder[i]); } return true; } int reversePairs(vector<int>& nums) { vector<int> tmp(nums); return reversePairsSub(nums, tmp, 0, nums.size() - 1); } int reversePairsSub(vector<int>& nums, vector<int>& tmp, int leftCur, int rightCur){ if (leftCur >= rightCur){ return 0; } int mid = (leftCur + rightCur) / 2; int res = reversePairsSub(nums, tmp, leftCur, mid) + reversePairsSub(nums, tmp, mid + 1, rightCur); // 合并阶段 int i = leftCur, j = mid + 1; for (int k = leftCur; k <= rightCur; k++) tmp[k] = nums[k]; for (int k = leftCur; k <= rightCur; k++) { if (i == mid + 1) nums[k] = tmp[j++]; else if (j == rightCur + 1 || tmp[i] <= tmp[j]) nums[k] = tmp[i++]; else { nums[k] = tmp[j++]; res += mid - i + 1; // 统计逆序对 } } return res; } vector<int> getLeastNumbers(vector<int>& arr, int k) { vector<int> res(k, 0); getLeastNumbersSub(arr, 0, arr.size() - 1); for (int i = 0; i < k; i++){ res[i] = arr[i]; } return res; } void getLeastNumbersSub(vector<int>& arr, int leftCur, int rightCur){ if (leftCur >= rightCur){ return; } int pivot = arr[leftCur]; int left = leftCur, right = rightCur; while (left < right){ while (left < right && arr[right] >= pivot){ right--; } while (left < right && arr[left] <= pivot){ left++; } swap(arr[left], arr[right]); } swap(arr[leftCur], arr[left]); getLeastNumbersSub(arr, leftCur, left - 1); getLeastNumbersSub(arr, left + 1, rightCur); return; } string minNumber(vector<int>& nums) { minNumberSub(nums, 0, nums.size() - 1); string res; for (int& num : nums){ res += to_string(num); } return res; } bool minNumberSub1(int num1, int num2){ string str1 = to_string(num1) + to_string(num2); string str2 = to_string(num2) + to_string(num1); return str1 <= str2; } void minNumberSub(vector<int>& nums, int leftCur, int rightCur){ if (leftCur >= rightCur){ return; } int pivot = nums[leftCur]; int left = leftCur, right = rightCur; while (left < right){ while (left < right && minNumberSub1(pivot, nums[right])){ right--; } while (left < right && minNumberSub1(nums[left], pivot)){ left++; } swap(nums[left], nums[right]); } swap(nums[leftCur], nums[left]); minNumberSub(nums, leftCur, left - 1); minNumberSub(nums, left + 1, rightCur); return; } bool isStraight(vector<int>& nums) { isStraightSub(nums, 0, nums.size() - 1); int zeroCnt = 0; for (int i = 0; i < 4; i++){ if (nums[i] == 0){ zeroCnt++; continue; } int diff = nums[i + 1] - nums[i] - 1; if (diff < 0){ return false; } zeroCnt -= diff; } return zeroCnt >= 0; } void isStraightSub(vector<int>& nums, int leftCur, int rightCur){ if (leftCur >= rightCur){ return; } int pivot = nums[leftCur]; int left = leftCur, right = rightCur; while (left < right){ while (left < right && nums[right] >= pivot){ right--; } while (left < right && nums[left] <= pivot){ left++; } swap(nums[left], nums[right]); } swap(nums[left], nums[leftCur]); isStraightSub(nums, leftCur, left - 1); isStraightSub(nums, left + 1, rightCur); return; } }; class MedianFinder { public: /** initialize your data structure here. */ MedianFinder() { } priority_queue<int, vector<int>, less<int>> maxHeap;//栈顶元素大, 所以叫大顶堆 priority_queue<int, vector<int>, greater<int>> minHeap;//栈顶元素小, 所以叫小顶堆 void addNum(int num) { if (minHeap.size() == maxHeap.size()){ minHeap.push(num); maxHeap.push(minHeap.top()); minHeap.pop(); } else{ maxHeap.push(num); minHeap.push(maxHeap.top()); maxHeap.pop(); } } double findMedian() { if (maxHeap.size() == minHeap.size()){ return 0.5 * (maxHeap.top() + minHeap.top()); } return 1.0 * maxHeap.top(); } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { 11, 8, 12, 8, 10 }; vector<int> inpt2 = { 2,4,1,1,3 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution.isStraight(inpt1); return 0; } #endif // 图解算法数据结构--查找算法 #if false class Solution { public: struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; int findRepeatNumber(vector<int>& nums) { unordered_set<int> numSet; for (int& num : nums){ if (numSet.count(num)){ return num; } numSet.emplace(num); } return -1; } bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) { if (matrix.size() == 0 || matrix[0].size() == 0){ return false; } int rolSize = matrix.size(), colSize = matrix[0].size(); int rolCur = rolSize - 1, colCur = 0; while (rolCur >= 0 && rolCur < rolSize && colCur >= 0 && colCur < colSize){ if (matrix[rolCur][colCur] == target){ return true; } else if (matrix[rolCur][colCur] < target){ colCur++; } else { rolCur--; } } return false; } int minArray(vector<int>& nums) { int left = 0, right = nums.size() - 1, mid = 0; while (left < right){ mid = left + (right - left) / 2; if (nums[mid] > nums[right]){ left = mid + 1; } else if (nums[mid] < nums[right]){ right = mid; } else { right--; } } return nums[left]; } char firstUniqChar(string s) { unordered_map<char, int> chMap; for (char& ch : s){ chMap[ch]++; } for (char& ch : s){ if (chMap[ch] == 1){ return ch; } } return ' '; } int search(vector<int>& nums, int target) { if (nums.size() == 0){ return 0; } int left = 0, right = nums.size() - 1, lo = 0, hi = 0; while (left <= right){ hi = left + (right - left) / 2; if (nums[hi] <= target){ left = hi + 1; } else { right = hi - 1; } } hi = left; if (right >= 0 && nums[right] != target){ return 0; } left = 0, right = nums.size() - 1; while (left <= right){ lo = left + (right - left) / 2; if (nums[lo] >= target){ right = lo - 1; } else { left = lo + 1; } } lo = right; return hi - lo - 1; } int missingNumber(vector<int>& nums) { int res = 0, numsLen = nums.size(); for (int i = 0; i < numsLen; i++){ res ^= nums[i]; res ^= i; } res ^= numsLen; return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { 0,1,2,3,4,5,6,7,9 }; vector<int> inpt2 = { 2, 2, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution.missingNumber(inpt1); return 0; } #endif // 图解算法数据结构--双指针 #if false class Solution { public: struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; ListNode* deleteNode(ListNode* head, int val) { ListNode* root = new ListNode(-1); root->next = head; ListNode* cur = root; while (cur->next != nullptr){ if (cur->next->val == val){ cur->next = cur->next->next; break; } cur = cur->next; } cur = root->next; delete root; return cur; } vector<int> exchange(vector<int>& nums) { vector<int> res(nums); int leftCur = 0, rightCur = nums.size() - 1, numsLen = nums.size(); for (int i = 0; i < numsLen; i++){ if (nums[i] & 1){ res[leftCur++] = nums[i]; } else { res[rightCur--] = nums[i]; } } return res; } ListNode* getKthFromEnd(ListNode* head, int k) { ListNode* root = new ListNode(-1); root->next = head; ListNode* fastCur = root; ListNode* slowCur = head; while (k--){ fastCur = fastCur->next; } while (fastCur->next != nullptr){ slowCur = slowCur->next; fastCur = fastCur->next; } return slowCur; } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* root = new ListNode(-1); ListNode* cur = root; while (l1 != nullptr || l2 != nullptr){ if (l1 == nullptr){ cur->next = l2; cur = cur->next; l2 = l2->next; } else if (l2 == nullptr){ cur->next = l1; cur = cur->next; l1 = l1->next; } else if (l1->val <= l2->val){ cur->next = l1; cur = cur->next; l1 = l1->next; } else { cur->next = l2; cur = cur->next; l2 = l2->next; } } return root->next; } ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode* aCur = headA; ListNode* bCur = headB; while (aCur != bCur){ aCur = aCur == nullptr ? headB : aCur->next; bCur = bCur == nullptr ? headA : bCur->next; } return aCur; } vector<int> twoSum(vector<int>& nums, int target) { int numsLen = nums.size(); int leftCur = 0, rightCur = numsLen - 1; while (leftCur < rightCur){ int sum = nums[leftCur] + nums[rightCur]; if (sum > target){ rightCur--; } else if (sum < target){ leftCur++; } else { return {nums[leftCur], nums[rightCur]}; } } return {}; } string reverseWords(string s) { string res; int sLen = s.size(); int left = 0, right = 0; while (sLen > 0 && s[sLen - 1] == ' '){ sLen--; } while (right < sLen){ while (right < sLen && s[right] == ' '){ right++; } left = right; while (right < sLen && s[right] != ' '){ right++; } res = s.substr(left, right - left) + ' ' + res; } res.pop_back(); return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { 0,1,2,3,4,5,6,7,9 }; vector<int> inpt2 = { 2, 2, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution.reverseWords(" "); return 0; } #endif // 图解算法数据结构--位运算 #if false class Solution { public: struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; int hammingWeight(uint32_t n) { int res = 0; uint32_t cur = 1; for (int i = 0; i < 32; i++){ if (cur & n){ res++; } cur <<= 1; } return res; } vector<int> singleNumbers(vector<int>& nums) { int tmp = 0; for (int& num : nums){ tmp ^= num; } int x = 0, y = 0; int cur = 1; while ((cur & tmp) == 0){ cur <<= 1; } for (int& num : nums){ if (num & cur){ x ^= num; } else{ y ^= num; } } return {x, y}; } int singleNumber(vector<int>& nums) { int lo = 0, hi = 0; for (int& num : nums){ lo = lo ^ num & ~hi; hi = hi ^ num & ~lo; } return lo; } int add(int a, int b) { while (b != 0){ int c = (unsigned int)(a & b) << 1; a ^= b; b = c; } return a; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { 0,1,2,3,4,5,6,7,9 }; vector<int> inpt2 = { 2, 2, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution; return 0; } #endif // 图解算法数据结构--数学 #if false class Solution { public: struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; int cuttingRopeI(int n) { vector<int> dp(n + 1, 0); dp[1] = 1; for (int i = 2; i <= n; i++){ for (int j = 1; j < i; j++){ dp[i] = max(max(dp[i], dp[j] * (i - j)), (i - j) * j); } } return dp[n]; } int cuttingRope(int n) { if (n < 4){ return n - 1; } int b = n % 3, mod = 1000000007; long rem = 1, x = 3; for (int a = n / 3 - 1; a > 0; a /= 2){ if (a & 1){ rem = (rem * x) % mod; } x = x * x % mod; } if (b == 0){ return (int)(rem * 3 % mod); } if (b == 1){ return (int)(rem * 4 % mod); } return (int)(rem * 6 % mod); } int majorityElement(vector<int>& nums) { int cnt = 0, res = -1; for (int& num : nums){ if (cnt == 0 || res == num){ res = num; cnt++; } else{ cnt--; } } return res; } int countDigitOne(int n) { int countr = 0; for (long long i = 1; i <= n; i *= 10) { long long divider = i * 10; countr += (n / divider) * i + min(max(n % divider - i + 1, 0LL), i); } return countr; } int findNthDigit(int n) { int digit = 1; long start = 1, cnt = 9; while (n > cnt){ n -= cnt; start *= 10; digit++; cnt = digit * start * 9; } long num = start + (n - 1) / digit; return to_string(num)[(n - 1) % digit] - '0'; } vector<vector<int>> findContinuousSequence(int target) { int leftCur = 1, rightCur = 1, sum = 0; vector<vector<int>> res; while (leftCur + rightCur <= target + 1){ if (sum < target){ sum += rightCur++; } else if (sum > target){ sum -= leftCur++; } else { vector<int> tmp(rightCur - leftCur, 0); for (int i = leftCur; i < rightCur; i++){ tmp[i - leftCur] = i; } res.push_back(tmp); sum += rightCur++; } } return res; } int lastRemaining(int n, int m) { int x = 0; for (int i = 2; i <= n; i++) { x = (x + m) % i; } return x; } vector<int> constructArr(vector<int>& nums) { int numsLen = nums.size(); if (numsLen == 1){ return {0}; } if (numsLen == 0){ return {}; } vector<int> res(numsLen, 0); vector<int> left(nums), right(nums); for (int i = 1; i < numsLen; i++){ left[i] *= left[i - 1]; right[numsLen - i - 1] *= right[numsLen - i]; } for (int i = 0; i < numsLen; i++){ int leftVal = i == 0 ? 1 : left[i - 1]; int rightVal = i == numsLen - 1 ? 1 : right[i + 1]; res[i] = leftVal * rightVal; } return res; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { 1, 2, 3, 4, 5 }; vector<int> inpt2 = { 2, 2, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution.constructArr(inpt1); return 0; } #endif // 图解算法数据结构--模拟 #if false class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int rolSize = matrix.size(); if (rolSize == 0){ return {}; } int colSize = matrix[0].size(); if (colSize == 0){ return {}; } int cnt = rolSize * colSize; int rolZero = 0, colZero = 0, rolCur = 0, colCur = 0; vector<int> res(cnt, 0); int cur = 0; while (cur < cnt){ while (cur < cnt && colCur < colSize){ res[cur++] = matrix[rolCur][colCur++]; } rolZero++; rolCur = rolZero; colCur = colSize - 1; while (cur < cnt && rolCur < rolSize){ res[cur++] = matrix[rolCur++][colCur]; } colSize--; rolCur = rolSize - 1; colCur = colSize - 1; while (cur < cnt && colCur >= colZero){ res[cur++] = matrix[rolCur][colCur--]; } rolSize--; rolCur = rolSize - 1; colCur = colZero; while (cur < cnt && rolCur >= rolZero){ res[cur++] = matrix[rolCur--][colCur]; } colZero++; rolCur = rolZero; colCur = colZero; } return res; } bool validateStackSequences(vector<int>& pushed, vector<int>& popped) { int numsLen = pushed.size(); if (numsLen == 0){ return true; } stack<int> stk; int pushCur = 0, popCur = 0; while (popCur < numsLen){ while (stk.empty() || (pushCur < numsLen && stk.top() != popped[popCur])){ stk.push(pushed[pushCur++]); } while (!stk.empty() && stk.top() == popped[popCur]){ stk.pop(); popCur++; } if (!stk.empty() && pushCur == numsLen && popCur != numsLen){ return false; } } return true; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; void destoryList(ListNode*& root){ if (root == nullptr){ return; } destoryList(root->next); delete root; root = nullptr; return; } ListNode* vectorToListNode(std::vector<int>& nums){ ListNode* head = new ListNode(0); ListNode* cur = head; for (int& num : nums){ cur->next = new ListNode(num); cur = cur->next; } cur = head->next; delete head; head = nullptr; return cur; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { 0, 2, 5, 7, 9 }; vector<int> inpt2 = { 4, 3, 5, 1, 2 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; Solution::ListNode* node = mySolution.vectorToListNode(inpt1); mySolution.destoryList(node); try { mySolution.validateStackSequences(inpt1, inpt2); } catch (int err){ ; } return 0; } #endif // 腾讯 #if true class Solution { public: struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; vector<int> twoSum(vector<int>& nums, int target) { vector<int> res(2); unordered_map<int, int> numSet; for (int i = 0; i < nums.size(); i++){ int& it = nums[i]; if (numSet.count(target - it)){ res[0] = i; res[1] = numSet[target - it]; return res; } numSet[it] = i; } return {}; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int numsLen1 = nums1.size(), numsLen2 = nums2.size(); int cnt = (numsLen1 + numsLen2) / 2; int nums1Cur = 0, nums2Cur = 0; int tmp = 0; while (nums1Cur + nums2Cur < cnt){ if (nums1Cur == numsLen1){ tmp = nums2[nums2Cur++]; } else if (nums2Cur == numsLen2){ tmp = nums1[nums1Cur++]; } else{ if (nums1[nums1Cur] <= nums2[nums2Cur]){ tmp = nums1[nums1Cur++]; } else{ tmp = nums2[nums2Cur++]; } } } int tmp2 = 0; if (nums1Cur == numsLen1){ tmp2 = nums2[nums2Cur++]; } else if (nums2Cur == numsLen2){ tmp2 = nums1[nums1Cur++]; } else{ if (nums1[nums1Cur] <= nums2[nums2Cur]){ tmp2 = nums1[nums1Cur++]; } else{ tmp2 = nums2[nums2Cur++]; } } if ((numsLen1 + numsLen2) % 2 == 1){ return (double)tmp2; } return 0.5 * (tmp + tmp2); } string longestPalindrome(string s) { int sLen = s.size(); int begin = 0, end = 0; for (int i = 0; i < sLen; i++){ pair<int, int> tmp = longestPalindromeSub(s, i, i); if (tmp.second - tmp.first > end - begin){ begin = tmp.first; end = tmp.second; } tmp = longestPalindromeSub(s, i, i + 1); if (tmp.second - tmp.first > end - begin){ begin = tmp.first; end = tmp.second; } } return s.substr(begin, end - begin + 1); } pair<int, int> longestPalindromeSub(string& s, int left, int right){ while (left >= 0 && right < s.size() && s[left] == s[right]){ left--; right++; } return {left + 1, right - 1}; } int myAtoi(string s) { int sLen = s.size(); bool init = false; long long res = 0; int sign = 1; for(char& ch : s){ if(!init){ if (ch == ' '){ continue; } if (ch == '-'){ sign = -1; } else if (isalpha(ch)){ return 0; } else if (isdigit(ch)){ res = ch - '0'; } else if (ch == '+'){ sign = 1; } else { return 0; } init = true; continue; } if(!isdigit(ch)){ break; } res *= 10; res += ch - '0'; if (sign > 0 && res > INT32_MAX){ return INT32_MAX; } if (sign < 0 && res - 1 > INT32_MAX){ return INT32_MIN; } } return sign * res; } string longestCommonPrefix(vector<string>& strs) { if (strs.size() == 0){ return ""; } int lim = INT32_MAX; int cur = 0; for (int i = 0; i < strs.size(); i++){ string& str = strs[i]; if (str.size() < lim){ lim = str.size(); cur = i; } } string res; for (int i = 0; i < lim; i++){ char ch = strs[cur][i]; res.push_back(ch); for (string& str : strs){ if (str[i] != ch){ res.pop_back(); return res; } } } return res; } vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; sort(nums.begin(), nums.end()); size_t numsLen = nums.size(); if (numsLen < 3){ return res; } for (size_t i = 0; i < numsLen - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } size_t k = numsLen - 1; for (size_t j = i + 1; j < numsLen - 1; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } while (k > j && nums[i] + nums[j] + nums[k] > 0) { k--; } if (j == k) { break; } if (nums[i] + nums[j] + nums[k] == 0) { res.emplace_back(vector<int>({ nums[i], nums[j], nums[k] })); } } } return res; } int threeSumClosest(vector<int>& nums, int target) {//最接近的三数之和 size_t numsLen = nums.size(); sort(nums.begin(), nums.end()); int diff = INT32_MAX; int res = -1; for (size_t i = 0; i < numsLen; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } size_t leftCur = i + 1, rightCur = numsLen - 1; while (leftCur < rightCur) { int sum = nums[i] + nums[leftCur] + nums[rightCur]; if (sum == target) { return target; } if (abs(sum - target) < diff) { diff = abs(sum - target); res = sum; } if (sum > target) { size_t rightCurBak = rightCur - 1; while (rightCurBak > leftCur && nums[rightCur] == nums[rightCurBak]) { rightCurBak--; } rightCur = rightCurBak; } else { size_t leftCurBak = leftCur + 1; while (leftCurBak < rightCur && nums[leftCur] == nums[leftCurBak]) { leftCurBak++; } leftCur = leftCurBak; } } } return res; } bool isValid(string s) { stack<char> stk; for (char& ch : s){ if (ch == '(' || ch == '[' || ch == '{'){ stk.push(ch); continue; } if (stk.empty()){ return false; } char top = stk.top(); if (top == '[' && ch == ']'){ stk.pop(); continue; } if (top == '(' && ch == ')'){ stk.pop(); continue; } if (top == '{' && ch == '}'){ stk.pop(); continue; } return false; } return stk.empty(); } int removeDuplicates(vector<int>& nums) { if (nums.empty()){ return 0; } sort(nums.begin(), nums.end()); size_t left = 1, right = 1; while (right < nums.size()){ if (nums[right] == nums[right - 1]){ right++; continue; } nums[left++] = nums[right++]; } nums = vector<int>(nums.begin(), nums.begin() + left); return left; } int maxArea(vector<int>& height) { int left = 0, right = height.size() - 1; int res = 0; while (left < right){ res = max(res, (right - left) * min(height[left], height[right])); if (height[left] < height[right]){ left++; } else{ right--; } } return res; } string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0"){ return "0"; } int cur1 = num1.size() - 1, cur2 = num2.size() - 1; unordered_map<int, string> chMap; for (char& ch : num2){ int num = ch - '0'; if (chMap.count(num) < 1 && num != 0 && num != 1){ chMap[num] = multiplyMUL(num1, num); } } string subfix = "", res; while(cur2 > -1){ string tmp; if (chMap.count(num2[cur2] - '0') > 0){ tmp = chMap[num2[cur2] - '0'] + subfix; } else if (num2[cur2] == '0'){ subfix.push_back('0'); cur2--; continue; } else{ tmp = num1 + subfix; } res = multiplyADD(res, tmp); subfix.push_back('0'); cur2--; } return res.size() == 0 ? "0" : res; } string multiplyADD(string& str1, string& str2){ string res; int cur1 = str1.size() - 1, cur2 = str2.size() - 1; int remain = 0; while (cur1 > -1 || cur2 > -1){ int digit1 = cur1 < 0 ? 0 : str1[cur1] - '0'; int digit2 = cur2 < 0 ? 0 : str2[cur2] - '0'; res.push_back((digit1 + digit2 + remain) % 10 + '0'); remain = (digit1 + digit2 + remain) / 10; cur1--; cur2--; } if (remain != 0){ res.push_back('0' + remain); } // reverse(res.begin(), res.end()); return res; } string multiplyMUL(string str, int n){ int cur = str.size() - 1; int remain = 0; while (cur > -1){ int digit = str[cur] - '0'; str[cur] = '0' + (digit * n + remain) % 10; remain = (digit * n + remain) / 10; cur--; } if (remain != 0){ str.insert(str.begin(), '0' + remain); } return str; } void reverseString(vector<char>& s) { int left = 0, right = s.size() - 1; while(left < right){ swap(s[left++], s[right--]); } return; } string reverseWords(string s) { stringstream ss(s); string res, tmp; while(ss >> tmp){ reverseWordsSub(tmp); res = res + tmp + ' '; } res.pop_back(); return res; } void reverseWordsSub(string& s) { int left = 0, right = s.size() - 1; while(left < right){ swap(s[left++], s[right--]); } return; } vector<int> productExceptSelf(vector<int>& nums) { int numsLen = nums.size(); vector<int> left(numsLen, 1), right(numsLen, 1), res(numsLen, 0); for (int i = 1; i < numsLen; i++){ left[i] = left[i - 1] * nums[i - 1]; right[numsLen - i - 1] = right[numsLen - i] * nums[numsLen - i]; } for (int i = 0; i < numsLen; i++){ res[i] = left[i] * right[i]; } return res; } bool containsDuplicate(vector<int>& nums) { unordered_set<int> numSet; for (int& num : nums){ if (numSet.count(num) > 0){ return true; } numSet.emplace(num); } return false; } vector<int> spiralOrder(vector<vector<int>>& matrix) { int rolSize = matrix.size(); if (rolSize == 0){ return {}; } int colSize = matrix[0].size(); if (colSize == 0){ return {}; } int cnt = rolSize * colSize; int rolZero = 0, colZero = 0, rolCur = 0, colCur = 0; vector<int> res(cnt, 0); int cur = 0; while (cur < cnt){ while (cur < cnt && colCur < colSize){ res[cur++] = matrix[rolCur][colCur++]; } rolZero++; rolCur = rolZero; colCur = colSize - 1; while (cur < cnt && rolCur < rolSize){ res[cur++] = matrix[rolCur++][colCur]; } colSize--; rolCur = rolSize - 1; colCur = colSize - 1; while (cur < cnt && colCur >= colZero){ res[cur++] = matrix[rolCur][colCur--]; } rolSize--; rolCur = rolSize - 1; colCur = colZero; while (cur < cnt && rolCur >= rolZero){ res[cur++] = matrix[rolCur--][colCur]; } colZero++; rolCur = rolZero; colCur = colZero; } return res; } vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n, 0)); int rolSize = n, colSize = n, rolZero = 0, colZero = 0; int rolCur = 0, colCur = 0; int num = 0; while (num < n * n){ while (num < n * n && colCur < colSize){ res[rolCur][colCur++] = ++num; } rolZero++; rolCur = rolZero; colCur = colSize - 1; while (num < n * n && rolCur < rolSize){ res[rolCur++][colCur] = ++num; } colSize--; rolCur = rolSize - 1; colCur = colSize - 1; while (num < n * n && colCur >= colZero){ res[rolCur][colCur--] = ++num; } rolSize--; rolCur = rolSize - 1; colCur = colZero; while (num < n * n && rolCur >= rolZero){ res[rolCur--][colCur] = ++num; } colZero++; rolCur = rolZero; colCur = colZero; } return res; } void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { vector<int> res(nums1); int cur1 = 0, cur2 = 0, cur = 0; while (cur1 < m || cur2 < n){ if (cur1 == m){ res[cur++] = nums2[cur2++]; } else if (cur2 == n){ res[cur++] = nums1[cur1++]; } else if (nums1[cur1] < nums2[cur2]){ res[cur++] = nums1[cur1++]; } else{ res[cur++] = nums2[cur2++]; } } nums1 = res; return; } ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr){ return head; } ListNode* newHead = reverseList(head->next); head->next->next = head; head->next = nullptr; return newHead; } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* head = new ListNode; ListNode* cur = head; int remain = 0; while (l1 != nullptr || l2 != nullptr || remain != 0){ int num1 = l1 == nullptr ? 0 : l1->val; int num2 = l2 == nullptr ? 0 : l2->val; l1 = l1 == nullptr ? nullptr : l1->next; l2 = l2 == nullptr ? nullptr : l2->next; cur->next = new ListNode; cur = cur->next; cur->val = (num1 + num2 + remain) % 10; remain = (num1 + num2 + remain) / 10; } return head->next; } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head = new ListNode; ListNode* cur = head; while (l1 !=nullptr || l2 != nullptr){ if (l1 == nullptr){ cur->next = l2; l2 = l2->next; break; } else if(l2 == nullptr){ cur->next = l1; l1 = l1->next; break; } else if (l1->val < l2->val){ cur->next = l1; l1 = l1->next; } else{ cur->next = l2; l2 = l2->next; } cur = cur->next; cur->next = nullptr; } return head->next; } ListNode* mergeKLists(vector<ListNode*>& lists) { if (lists.size() == 0){ return nullptr; } vector<ListNode*> tmp; while(lists.size() > 1){ tmp.clear(); for (int i = 0; i < lists.size(); i += 2){ ListNode* l1 = lists[i]; ListNode* l2 = i + 1 < lists.size() ? lists[i + 1] : nullptr; tmp.emplace_back(mergeTwoLists(l1, l2)); } lists = tmp; } return lists[0]; } ListNode* rotateRight(ListNode* head, int k) { if (!head || !k){ return head; } int cnt = 0; ListNode* cur = head; ListNode* tail = head; while(cur){//找结点数量 cnt++; tail = cur; cur = cur->next; } if (cnt == 1){ return head; } k = k % cnt; if (k == 0){ return head; } cnt = cnt - k; cur = head; ListNode* last = cur; for(int i = 0; i<cnt; i++){ last = cur; cur = cur->next; } last->next = 0; tail->next = head; return cur; } bool hasCycle(ListNode *head) { ListNode* slowCur = head; ListNode* fastCur = head; while (fastCur != nullptr && fastCur->next != nullptr){ slowCur = slowCur->next; fastCur = fastCur->next->next; if (slowCur == fastCur){ return true; } } return false; } ListNode *detectCycle(ListNode *head) { ListNode* slow, * fast; slow = fast = head; int num = 0; while(slow&&fast&&fast->next){ slow = slow->next; fast = fast->next->next; num++; if (slow == fast){//获取到了链长 slow = fast = head; for(int i = 0; i<num; i++){ fast = fast->next; } while(1){ if(slow == fast){ break; } slow = slow->next; fast = fast->next; } return slow; } } return NULL; } ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode* curA = headA; ListNode* curB = headB; while (curA != curB){ curA = curA == nullptr ? headB : curA->next; curB = curB == nullptr ? headA : curB->next; } return curA; } void deleteNode(ListNode* node) { ListNode* cur = node; ListNode* last = node; while (cur->next != nullptr){ cur->val = cur->next->val; last = cur; cur = cur->next; } last->next = nullptr; delete cur; return; } bool canWinNim(int n) {//Nim 游戏 return n % 4 != 0; } }; int main(int argc, char* argv[]) { Solution mySolution; string a = "abs"; string b = "this apple is sour"; vector<int> inpt1 = { -1, 0, 1, 2, -1, -4 }; vector<int> inpt2 = { 2, 4 }; vector<int> inpt3 = { 1, 2, 1 }; vector<vector<int>> nums = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; vector<vector<char>> board = {{'a'}}; vector<vector<int>> equations = { {9, 7}, {1, 9}, {3, 1} }; vector<double> val = { 2.0, 3.0 }; vector<string> qur = { " /","/ " }; mySolution; return 0; } #endif
23.31975
211
0.542102
guannan-he
cef67be72fa3ceccb42d3c937a91de6e9aec4f2b
1,698
cpp
C++
src/Dungeon/Dungeon.cpp
zachtepper/project-awful
59e2e9261100a2b4449022725435d21b17c6f5b4
[ "MIT" ]
null
null
null
src/Dungeon/Dungeon.cpp
zachtepper/project-awful
59e2e9261100a2b4449022725435d21b17c6f5b4
[ "MIT" ]
null
null
null
src/Dungeon/Dungeon.cpp
zachtepper/project-awful
59e2e9261100a2b4449022725435d21b17c6f5b4
[ "MIT" ]
null
null
null
#include "Dungeon.hpp" // Room Dungeon::Room::Room(int id, int top, int left, int width, int height) { this->id = id; this->top = top; this->left = left; this->width = width; this->height = height; this->parent = NULL; this->leftChild = NULL; this->rightChild = NULL; this->dungeon = NULL; this->minimumRoomSize = 5; cout << this->id << " " << this->top << " " << this->left << " " << this->width << " " << this->height << endl; } Dungeon::Room::~Room() { if ( this->dungeon != NULL ) { delete this->dungeon; this->dungeon = NULL; } } void Dungeon::Room::setParent( Room *parent ) { this->parent = parent; } void Dungeon::Room::setDungeon( Room *dungeon ) { this->dungeon = dungeon; } void Dungeon::Room::setLeftChild( Room *leftChild ) { this->leftChild = leftChild; } void Dungeon::Room::setRightChild( Room *rightChild ) { this->rightChild = rightChild; } void Dungeon::Room::drawRoom( sf::RenderTarget& target ) { if ( this->leftChild != NULL && this->dungeon == NULL ) { this->leftChild->drawRoom( target ); this->rightChild->drawRoom( target ); } else { sf::RectangleShape roomRect; roomRect.setPosition( sf::Vector2f( this->top, this->left ) ) ; roomRect.setSize( sf::Vector2f( this->height, this->width ) ); roomRect.setFillColor( sf::Color::Black ); roomRect.setFillColor( sf::Color( 200, 200, 200, 150 ) ); roomRect.setOutlineThickness(3); roomRect.setOutlineColor( sf::Color::Red ); target.draw(roomRect); } } // Door Dungeon::Door::Door() { } Dungeon::Door::~Door() { }
21.493671
116
0.583628
zachtepper
cefd3d0c435444051e3a9fb124dedee33ac2f932
2,389
cpp
C++
assignment07/assignment7-1.cpp
qpakzk/SSU-CSE-Problem-Solving
44cc6b913d86008c2f23536ed0c395115b6ccef6
[ "MIT" ]
null
null
null
assignment07/assignment7-1.cpp
qpakzk/SSU-CSE-Problem-Solving
44cc6b913d86008c2f23536ed0c395115b6ccef6
[ "MIT" ]
null
null
null
assignment07/assignment7-1.cpp
qpakzk/SSU-CSE-Problem-Solving
44cc6b913d86008c2f23536ed0c395115b6ccef6
[ "MIT" ]
null
null
null
/* * Problem Solving Assignment7-1 : DSLR * https://www.acmicpc.net/problem/9019 */ #include <cstdio> #include <cstring> #include <queue> #include <stack> #define MAXLEN 10000 using namespace std; int before[MAXLEN]; bool visited[MAXLEN]; char op[MAXLEN]; int D(int n) { n *= 2; n %= 10000; return n; } int S(int n) { if(n == 0) n = 9999; else n -= 1; return n; } int L(int n) { int h = n / 1000; n %= 1000; n *= 10; n += h; return n; } int R(int n) { int h = n % 10; n /= 10; n += h * 1000; return n; } int main(void) { int T; int start, end, cal, tmp; queue<int> q; stack<int> s; scanf("%d", &T); while(T--) { scanf("%d%d", &start, &end); memset(before, 0, sizeof(before)); memset(visited, 0, sizeof(visited)); memset(op, 0, sizeof(op)); q.push(start); visited[start] = true; while(!q.empty()) { cal = q.front(); q.pop(); if(cal == end) { while(!q.empty()) q.pop(); break; } tmp = cal; tmp = D(tmp); if(!visited[tmp]) { before[tmp] = cal; op[tmp] = 'D'; q.push(tmp); visited[tmp] = true; } tmp = cal; tmp = S(tmp); if(!visited[tmp]) { before[tmp] = cal; op[tmp] = 'S'; q.push(tmp); visited[tmp] = true; } tmp = cal; tmp = L(tmp); if(!visited[tmp]) { before[tmp] = cal; op[tmp] = 'L'; q.push(tmp); visited[tmp] = true; } tmp = cal; tmp = R(tmp); if(!visited[tmp]) { before[tmp] = cal; op[tmp] = 'R'; q.push(tmp); visited[tmp] = true; } } tmp = end; while(1) { s.push(tmp); if(tmp == start) break; tmp = before[tmp]; } s.pop(); while(!s.empty()) { printf("%c", op[s.top()]); s.pop(); } printf("\n"); } return 0; }
18.51938
44
0.370029
qpakzk
ceff2abe0573eddfb56c19026a47125bba22e751
2,025
cpp
C++
src/common/vector_operations/gather.cpp
dfooz/duckdb
6978d121bcaf5d56f35be51caef6d7662ef3c1c4
[ "MIT" ]
9
2021-09-08T13:13:03.000Z
2022-03-11T21:18:05.000Z
src/common/vector_operations/gather.cpp
dfooz/duckdb
6978d121bcaf5d56f35be51caef6d7662ef3c1c4
[ "MIT" ]
1
2021-12-12T03:36:02.000Z
2021-12-12T03:36:02.000Z
src/common/vector_operations/gather.cpp
dfooz/duckdb
6978d121bcaf5d56f35be51caef6d7662ef3c1c4
[ "MIT" ]
1
2022-01-18T09:38:19.000Z
2022-01-18T09:38:19.000Z
//===--------------------------------------------------------------------===// // gather.cpp // Description: This file contains the implementation of the gather operators //===--------------------------------------------------------------------===// #include "duckdb/common/exception.hpp" #include "duckdb/common/operator/constant_operators.hpp" #include "duckdb/common/types/null_value.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" using namespace duckdb; using namespace std; template <class T> static void templated_gather_loop(Vector &source, Vector &dest, idx_t count) { auto addresses = FlatVector::GetData<uintptr_t>(source); auto data = FlatVector::GetData<T>(dest); auto &nullmask = FlatVector::Nullmask(dest); for (idx_t i = 0; i < count; i++) { auto dataptr = (T *)addresses[i]; if (IsNullValue<T>(*dataptr)) { nullmask[i] = true; } else { data[i] = *dataptr; } addresses[i] += sizeof(T); } } void VectorOperations::Gather::Set(Vector &source, Vector &dest, idx_t count) { assert(source.vector_type == VectorType::FLAT_VECTOR); assert(source.type == TypeId::POINTER); // "Cannot gather from non-pointer type!" dest.vector_type = VectorType::FLAT_VECTOR; switch (dest.type) { case TypeId::BOOL: case TypeId::INT8: templated_gather_loop<int8_t>(source, dest, count); break; case TypeId::INT16: templated_gather_loop<int16_t>(source, dest, count); break; case TypeId::INT32: templated_gather_loop<int32_t>(source, dest, count); break; case TypeId::INT64: templated_gather_loop<int64_t>(source, dest, count); break; case TypeId::FLOAT: templated_gather_loop<float>(source, dest, count); break; case TypeId::DOUBLE: templated_gather_loop<double>(source, dest, count); break; case TypeId::POINTER: templated_gather_loop<uintptr_t>(source, dest, count); break; case TypeId::VARCHAR: templated_gather_loop<string_t>(source, dest, count); break; default: throw NotImplementedException("Unimplemented type for gather"); } }
31.153846
97
0.676543
dfooz
3000c6f5a082aae1cfc4c5eb8e05840395347e89
7,294
cpp
C++
VK9-Library/CIndexBuffer9.cpp
raj347/VK9
31ae780b64525d185284a5ff4564bf72d17fc310
[ "Zlib" ]
null
null
null
VK9-Library/CIndexBuffer9.cpp
raj347/VK9
31ae780b64525d185284a5ff4564bf72d17fc310
[ "Zlib" ]
null
null
null
VK9-Library/CIndexBuffer9.cpp
raj347/VK9
31ae780b64525d185284a5ff4564bf72d17fc310
[ "Zlib" ]
1
2022-03-30T00:44:51.000Z
2022-03-30T00:44:51.000Z
/* Copyright(c) 2016 Christopher Joseph Dean Schaefer This software is provided 'as-is', without any express or implied warranty.In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions : 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "CIndexBuffer9.h" #include "CDevice9.h" #include "Utilities.h" CIndexBuffer9::CIndexBuffer9(CDevice9* device, UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, HANDLE* pSharedHandle) : mReferenceCount(1), mDevice(device), mLength(Length), mUsage(Usage), mFormat(Format), mPool(Pool), mSharedHandle(pSharedHandle), mResult(VK_SUCCESS), mData(nullptr), mSize(0), mCapacity(0), mIsDirty(true), mLockCount(0), mBuffer(VK_NULL_HANDLE), mMemory(VK_NULL_HANDLE), mIndexType(VK_INDEX_TYPE_UINT32) { VkBufferCreateInfo bufferCreateInfo = {}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.pNext = NULL; bufferCreateInfo.size = mLength; bufferCreateInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; bufferCreateInfo.flags = 0; VkMemoryAllocateInfo memoryAllocateInfo = {}; memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memoryAllocateInfo.pNext = NULL; memoryAllocateInfo.allocationSize = 0; memoryAllocateInfo.memoryTypeIndex = 0; mMemoryRequirements = {}; mResult = vkCreateBuffer(mDevice->mDevice, &bufferCreateInfo, NULL, &mBuffer); if (mResult != VK_SUCCESS) { BOOST_LOG_TRIVIAL(fatal) << "CIndexBuffer9::CIndexBuffer9 vkCreateBuffer failed with return code of " << mResult; return; } vkGetBufferMemoryRequirements(mDevice->mDevice, mBuffer, &mMemoryRequirements); memoryAllocateInfo.allocationSize = mMemoryRequirements.size; GetMemoryTypeFromProperties(mDevice->mDeviceMemoryProperties, mMemoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &memoryAllocateInfo.memoryTypeIndex); mResult = vkAllocateMemory(mDevice->mDevice, &memoryAllocateInfo, NULL, &mMemory); if (mResult != VK_SUCCESS) { BOOST_LOG_TRIVIAL(fatal) << "CIndexBuffer9::CIndexBuffer9 vkAllocateMemory failed with return code of " << mResult; return; } mResult = vkBindBufferMemory(mDevice->mDevice, mBuffer, mMemory, 0); if (mResult != VK_SUCCESS) { BOOST_LOG_TRIVIAL(fatal) << "CIndexBuffer9::CIndexBuffer9 vkBindBufferMemory failed with return code of " << mResult; return; } switch (Format) { case D3DFMT_INDEX16: mIndexType = VK_INDEX_TYPE_UINT16; mSize = mLength / sizeof(uint16_t); //WORD break; case D3DFMT_INDEX32: mIndexType = VK_INDEX_TYPE_UINT32; mSize = mLength / sizeof(uint32_t); break; default: BOOST_LOG_TRIVIAL(fatal) << "CIndexBuffer9::CIndexBuffer9 invalid D3DFORMAT of " << Format; break; } } CIndexBuffer9::~CIndexBuffer9() { if (mBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(mDevice->mDevice, mBuffer, NULL); } if (mMemory != VK_NULL_HANDLE) { vkFreeMemory(mDevice->mDevice, mMemory, NULL); } } ULONG STDMETHODCALLTYPE CIndexBuffer9::AddRef(void) { return InterlockedIncrement(&mReferenceCount); } HRESULT STDMETHODCALLTYPE CIndexBuffer9::QueryInterface(REFIID riid,void **ppv) { if (ppv == nullptr) { return E_POINTER; } if (IsEqualGUID(riid, IID_IDirect3DIndexBuffer9)) { (*ppv) = this; this->AddRef(); return S_OK; } if (IsEqualGUID(riid, IID_IDirect3DResource9)) { (*ppv) = this; this->AddRef(); return S_OK; } if (IsEqualGUID(riid, IID_IUnknown)) { (*ppv) = this; this->AddRef(); return S_OK; } return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE CIndexBuffer9::Release(void) { ULONG ref = InterlockedDecrement(&mReferenceCount); if (ref == 0) { delete this; } return ref; } HRESULT STDMETHODCALLTYPE CIndexBuffer9::GetDevice(IDirect3DDevice9** ppDevice) { mDevice->AddRef(); (*ppDevice) = (IDirect3DDevice9*)mDevice; return S_OK; } HRESULT STDMETHODCALLTYPE CIndexBuffer9::FreePrivateData(REFGUID refguid) { //TODO: Implement. BOOST_LOG_TRIVIAL(warning) << "CIndexBuffer9::FreePrivateData is not implemented!"; return E_NOTIMPL; } DWORD STDMETHODCALLTYPE CIndexBuffer9::GetPriority() { //TODO: Implement. BOOST_LOG_TRIVIAL(warning) << "CIndexBuffer9::GetPriority is not implemented!"; return 1; } HRESULT STDMETHODCALLTYPE CIndexBuffer9::GetPrivateData(REFGUID refguid, void* pData, DWORD* pSizeOfData) { //TODO: Implement. BOOST_LOG_TRIVIAL(warning) << "CIndexBuffer9::GetPrivateData is not implemented!"; return E_NOTIMPL; } D3DRESOURCETYPE STDMETHODCALLTYPE CIndexBuffer9::GetType() { //return D3DRTYPE_SURFACE; //return D3DRTYPE_VOLUME; //return D3DRTYPE_TEXTURE; //return D3DRTYPE_VOLUMETEXTURE; //return D3DRTYPE_CUBETEXTURE; //return D3DRTYPE_VERTEXBUFFER; return D3DRTYPE_INDEXBUFFER; } void STDMETHODCALLTYPE CIndexBuffer9::PreLoad() { //TODO: Implement. BOOST_LOG_TRIVIAL(warning) << "CIndexBuffer9::PreLoad is not implemented!"; return; } DWORD STDMETHODCALLTYPE CIndexBuffer9::SetPriority(DWORD PriorityNew) { //TODO: Implement. BOOST_LOG_TRIVIAL(warning) << "CIndexBuffer9::SetPriority is not implemented!"; return 1; } HRESULT STDMETHODCALLTYPE CIndexBuffer9::SetPrivateData(REFGUID refguid, const void* pData, DWORD SizeOfData, DWORD Flags) { //TODO: Implement. BOOST_LOG_TRIVIAL(warning) << "CIndexBuffer9::SetPrivateData is not implemented!"; return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CIndexBuffer9::GetDesc(D3DINDEXBUFFER_DESC* pDesc) { //TODO: Implement. BOOST_LOG_TRIVIAL(warning) << "CIndexBuffer9::GetDesc is not implemented!"; return S_OK; } HRESULT STDMETHODCALLTYPE CIndexBuffer9::Lock(UINT OffsetToLock, UINT SizeToLock, VOID** ppbData, DWORD Flags) { VkResult result = VK_SUCCESS; if (mPool == D3DPOOL_MANAGED) { if (!(Flags & D3DLOCK_READONLY)) { //If the lock allows write mark the buffer as dirty. mIsDirty = true; } } result = vkMapMemory(mDevice->mDevice, mMemory, 0, mMemoryRequirements.size, 0, &mData); if (result != VK_SUCCESS) { BOOST_LOG_TRIVIAL(fatal) << "CIndexBuffer9::Lock vkMapMemory failed with return code of " << result; *ppbData = nullptr; return D3DERR_INVALIDCALL; } *ppbData = (char *)mData + OffsetToLock; InterlockedIncrement(&mLockCount); return S_OK; } HRESULT STDMETHODCALLTYPE CIndexBuffer9::Unlock() { VkResult result = VK_SUCCESS; vkUnmapMemory(mDevice->mDevice, mMemory); InterlockedDecrement(&mLockCount); return S_OK; }
25.865248
213
0.734439
raj347
300336a329a3de7f27ef9e392894338c4e59a024
410
hpp
C++
library/ATF/_pvppointlimit_info.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/_pvppointlimit_info.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/_pvppointlimit_info.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct _pvppointlimit_info { __int64 tUpdatedate; bool bUseUp; char byLimitRate; long double dOriginalPoint; long double dLimitPoint; long double dUsePoint; }; END_ATF_NAMESPACE
22.777778
108
0.690244
lemkova
30089700ff87b8feee2dc698e20246679e10b6d6
3,285
cpp
C++
Dev04_Handout/Motor2D/Enemy.cpp
bottzo/Platformer-Espriu_Bach
17931969900221ad9041e1bf0979d385c8ecf03c
[ "Apache-2.0" ]
null
null
null
Dev04_Handout/Motor2D/Enemy.cpp
bottzo/Platformer-Espriu_Bach
17931969900221ad9041e1bf0979d385c8ecf03c
[ "Apache-2.0" ]
null
null
null
Dev04_Handout/Motor2D/Enemy.cpp
bottzo/Platformer-Espriu_Bach
17931969900221ad9041e1bf0979d385c8ecf03c
[ "Apache-2.0" ]
null
null
null
#include "Enemy.h" #include "player.h" #include "j1Map.h" #include "j1App.h" #include "j1Collisions.h" #include "p2Log.h" #include "Entity.h" #include "p2DynArray.h" #include "j1Pathfinding.h" enemy::enemy() {} enemy::~enemy() {} ground_enemy::ground_enemy() { Load_Entity(App->entities->ground_enemy_sprite.GetString()); this->kind = Enemies::ground; this->type = Entity::Types::ground_enemy; on_the_ground = false; } flying_enemy::flying_enemy() { Load_Entity(App->entities->flying_enemy_sprite.GetString()); this->kind = Enemies::air; this->type = Entity::Types::flying_enemy; } void enemy::Draw_Enemy(float dt) { switch (kind) { case Enemies::ground: if (App->entities->GetPlayer()->position.x > this->position.x) App->render->Blit(Animations.start->data->texture, position.x, position.y, &Animations.start->data->GetCurrentFrame(dt), SDL_FLIP_NONE, this); else { App->render->Blit(Animations.start->data->texture, position.x, position.y, &Animations.start->data->GetCurrentFrame(dt), SDL_FLIP_HORIZONTAL, this); } break; case Enemies::air: if (App->entities->GetPlayer()->position.x > this->position.x) App->render->Blit(Animations.start->data->texture, position.x, position.y, &Animations.start->data->GetCurrentFrame(dt), SDL_FLIP_HORIZONTAL, this); else { App->render->Blit(Animations.start->data->texture, position.x, position.y, &Animations.start->data->GetCurrentFrame(dt), SDL_FLIP_NONE, this); } break; } } void ground_enemy::move() { if (count == 4) { App->pathfinding->CreatePath(App->map->WorldToMap((int)position.x, (int)position.y), App->map->WorldToMap((int)App->entities->GetPlayer()->position.x + (int)App->entities->GetPlayer()->player_collider->rect.w, (int)App->entities->GetPlayer()->position.y)); const iPoint* destination_ptr = App->pathfinding->GetLastPath()->At(1); iPoint destination(destination_ptr->x, destination_ptr->y); destination = App->map->MapToWorld(destination.x, destination.y); position.x = destination.x; enemy_collider->SetPos(position.x+App->entities->ground_texture_offset, position.y); count = 0; } count++; } void flying_enemy::move() { if (count == 4) { App->pathfinding->CreatePath(App->map->WorldToMap((int)position.x, (int)position.y), App->map->WorldToMap((int)App->entities->GetPlayer()->position.x + (int)App->entities->GetPlayer()->player_collider->rect.w, (int)App->entities->GetPlayer()->position.y)); const iPoint* destination_ptr = App->pathfinding->GetLastPath()->At(1); iPoint destination(destination_ptr->x, destination_ptr->y); destination = App->map->MapToWorld(destination.x, destination.y); position.x = destination.x; position.y = destination.y; enemy_collider->SetPos(position.x, position.y); count = 0; } count++; } /*#include "Application.h" #include "Enemy.h" #include "ModuleCollision.h" #include "ModuleRender.h" Enemy::Enemy(int x, int y) : position(x, y), collider(nullptr) {} Enemy::~Enemy() { if (collider != nullptr) collider->to_delete = true; } const Collider* Enemy::GetCollider() const { return collider; } void Enemy::Draw(SDL_Texture* sprites) { if(collider != nullptr) collider->SetPos(position.x, position.y); App->render->Blit(sprites, position.x, position.y, &(animation->GetCurrentFrame())); }**/
32.85
258
0.71172
bottzo
300aaf079fb3a3fe5585dfa1db30dee6a5726ca9
2,627
cpp
C++
retrace/daemon/glframe_os_linux.cpp
austriancoder/apitrace
5919778f7bcba82433f80bda4fb225e43183a62f
[ "MIT" ]
1
2021-03-05T10:49:37.000Z
2021-03-05T10:49:37.000Z
retrace/daemon/glframe_os_linux.cpp
austriancoder/apitrace
5919778f7bcba82433f80bda4fb225e43183a62f
[ "MIT" ]
null
null
null
retrace/daemon/glframe_os_linux.cpp
austriancoder/apitrace
5919778f7bcba82433f80bda4fb225e43183a62f
[ "MIT" ]
1
2018-10-05T03:09:13.000Z
2018-10-05T03:09:13.000Z
// Copyright (C) Intel Corp. 2015. All Rights Reserved. // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice (including the // next paragraph) shall be included in all copies or substantial // portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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. // **********************************************************************/ // * Authors: // * Mark Janes <mark.a.janes@intel.com> // **********************************************************************/ #include <pwd.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <string> #include <sstream> namespace glretrace { int fork_execv(const char *path, const char *const argv[]) { pid_t pid = fork(); if (pid == -1) { // When fork() returns -1, an error happened. perror("fork failed"); exit(-1); } if (pid == 0) { return ::execvp(path, (char *const*) argv); } return 0; } struct tm * glretrace_localtime(const time_t *timep, struct tm *result) { return localtime_r(timep, result); } int glretrace_rand(unsigned int *seedp) { return rand_r(seedp); } void glretrace_delay(unsigned int ms) { usleep(1000 * ms); } std::string application_cache_directory() { const char *homedir = "/tmp"; struct passwd pwd, *result; char buf[16384]; if ((homedir = getenv("HOME")) == NULL) { getpwuid_r(getuid(), &pwd, buf, 16384, &result); homedir = pwd.pw_dir; } std::stringstream cache_path; cache_path << homedir; cache_path << "/.frameretrace"; mkdir(cache_path.str().c_str(), S_IRWXU); cache_path << "/"; return cache_path.str(); } } // namespace glretrace
28.868132
75
0.661211
austriancoder
300c46c2b995bf412507af1244702bc7d6633c99
710
cpp
C++
test/hdf5.cpp
uos/hatsdf_slam
f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682
[ "BSD-3-Clause" ]
5
2021-05-21T07:52:50.000Z
2022-02-09T04:26:31.000Z
test/hdf5.cpp
uos/hatsdf_slam
f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682
[ "BSD-3-Clause" ]
null
null
null
test/hdf5.cpp
uos/hatsdf_slam
f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682
[ "BSD-3-Clause" ]
1
2022-02-09T04:26:33.000Z
2022-02-09T04:26:33.000Z
#include <highfive/H5File.hpp> #include <vector> #include "catch2_config.h" using namespace HighFive; TEST_CASE("HighFive/HDF5 working", "[hdf5][HighFive]") { std::cout << "Testing 'HighFive/HDF5 working'" << std::endl; // we create a new hdf5 file File file("/tmp/HighFiveTest.h5", File::ReadWrite | File::Create | File::Truncate); std::vector<int> data(50, 1); // let's create a dataset of native integer with the size of the vector 'data' DataSet dataset = file.createDataSet<int>("/dataset_one", DataSpace::From(data)); // let's write our vector of int to the HDF5 dataset dataset.write(data); // read back std::vector<int> result; dataset.read(result); }
29.583333
87
0.673239
uos
3019da15bce57f21959d018c7bf6cb617dc32780
902
cpp
C++
Shape/Vertex.cpp
SatoshiMabuchi/Crystal
91b2d72e5544cf86183587d2cfea48ca7f390dd4
[ "MIT" ]
null
null
null
Shape/Vertex.cpp
SatoshiMabuchi/Crystal
91b2d72e5544cf86183587d2cfea48ca7f390dd4
[ "MIT" ]
null
null
null
Shape/Vertex.cpp
SatoshiMabuchi/Crystal
91b2d72e5544cf86183587d2cfea48ca7f390dd4
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Vertex.h" using namespace Crystal::Math; using namespace Crystal::Shape; Vertex::Vertex(const Vector3df& position, const unsigned int id) : position(position), id(id) {} Vertex::Vertex(const Vector3df& position, const Vector3df& normal, const unsigned int id) : position(position), normal(normal), id(id) {} Vertex::Vertex(const Vector3df& position, const Vector3df& normal, const Vector2df& texCoord, const unsigned int id) : position(position), normal(normal), texCoord(texCoord), id(id) {} Vertex* Vertex::clone() { return new Vertex(getPosition(), getNormal(), id); } void Vertex::reverse() { this->normal = (-getNormal()); } Box3d Util::getBoundingBox(const std::list<Vertex*>& vertices) { Box3d box(vertices.front()->getPosition()); for (auto v : vertices) { box.add(v->getPosition()); } return box; }
21.47619
119
0.677384
SatoshiMabuchi
301a7a007dc41be799b1a078bcf2c7dabd901ac7
1,664
cpp
C++
frameworks/native/services/opersysnativeservice/OpersysNativeService.cpp
opersys/native-service
40968e4b88cd88974f011c8da21240c45c8595d3
[ "BSD-3-Clause" ]
19
2016-02-11T02:38:53.000Z
2021-05-17T22:51:22.000Z
frameworks/native/services/opersysnativeservice/OpersysNativeService.cpp
opersys/native-service
40968e4b88cd88974f011c8da21240c45c8595d3
[ "BSD-3-Clause" ]
null
null
null
frameworks/native/services/opersysnativeservice/OpersysNativeService.cpp
opersys/native-service
40968e4b88cd88974f011c8da21240c45c8595d3
[ "BSD-3-Clause" ]
7
2016-07-07T18:31:41.000Z
2019-09-10T06:30:09.000Z
/* * Copyright 2013-2016, Opersys 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 <stdint.h> #include <math.h> #include <sys/types.h> #include <utils/Errors.h> #include <utils/RefBase.h> #include <utils/Singleton.h> #include <utils/String16.h> #include <binder/BinderService.h> #include <binder/IServiceManager.h> #include <opersys/IOpersysNativeService.h> #include "OpersysNativeService.h" namespace android { // --------------------------------------------------------------------------- OpersysNativeService::OpersysNativeService() { } int OpersysNativeService::readValue(int myvalue) { ALOGD("*************** readValue() called with value %d *******************", myvalue); return 'a'; } int OpersysNativeService::writeValue(int myvalue) { ALOGD("*************** writeValue() called with value %d *******************", myvalue); return '5'; } status_t OpersysNativeService::dump(int fd, const Vector<String16>& args) { ALOGD("*************** dump() called *******************"); return NO_ERROR; } // --------------------------------------------------------------------------- }; // namespace android
25.6
90
0.614183
opersys
3021cabc59d3442e0834a1c91b3b67d92944bd63
914
cpp
C++
game/src/Game/SplashScene.cpp
emilhornlund/DV1537Project-AlienAdventure
b370e49d259ee722edd6f39c979824280522076a
[ "MIT" ]
null
null
null
game/src/Game/SplashScene.cpp
emilhornlund/DV1537Project-AlienAdventure
b370e49d259ee722edd6f39c979824280522076a
[ "MIT" ]
null
null
null
game/src/Game/SplashScene.cpp
emilhornlund/DV1537Project-AlienAdventure
b370e49d259ee722edd6f39c979824280522076a
[ "MIT" ]
null
null
null
// // Created by Emil Hörnlund on 2018-09-14. // #include <Core/ObjectHandler.hpp> #include <Core/SceneHandler.hpp> #include <Game/Game.hpp> #include <Game/SplashObject.hpp> #include <Game/SplashScene.hpp> #include <iostream> AA::SplashScene::SplashScene(CGL::IGame *game) : CGL::IScene(game) { auto obj = std::make_shared<SplashObject>(game); this->getObjectHandler().addObject(obj); } AA::SplashScene::~SplashScene() = default; void AA::SplashScene::performInit() { } void AA::SplashScene::performDeinit() { } void AA::SplashScene::cleanup() { } void AA::SplashScene::processExtraEvents() { } void AA::SplashScene::performExtraUpdates(const float dt) { if (this->getElapsedTime() > 2) { this->getGame()->getSceneHandler().dropActiveScene(); } } void AA::SplashScene::performExtraDrawing() { } void AA::SplashScene::didPause() { } void AA::SplashScene::didResume() { }
16.925926
68
0.690372
emilhornlund
6f73f8c42f10a41960a49982ef7c5273d5b70d5f
428
cpp
C++
cses/sorting-and-searching/ferris-wheel.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
cses/sorting-and-searching/ferris-wheel.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
cses/sorting-and-searching/ferris-wheel.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> int32_t main(){ // https://cses.fi/problemset/task/1090 desync(); int n, x; cin >> n >> x; vi v(n); for(int &i:v) cin >> i; sort(v.begin(), v.end()); int i=0, j=n-1, ans = 0; while(i <= j){ ans++; int a = v[i], b = v[j]; if(i != j and v[i] + v[j] <= x) i++; j--; } cout << ans << endl; return 0; }
18.608696
43
0.399533
tysm
6f75c98de32d59e74f05f354dc34eb3264c0fdf0
7,787
hpp
C++
gpcl/intrusive_list.hpp
Chingyat/gpcl
c2702b8b13fa948f6753285ba62455ddf9413578
[ "BSL-1.0" ]
2
2021-02-10T11:51:25.000Z
2021-12-20T12:35:36.000Z
gpcl/intrusive_list.hpp
Chingyat/gpcl
de4157a2bab07640539d9051fc7bb66c9c82eaf4
[ "BSL-1.0" ]
2
2021-11-28T03:09:15.000Z
2021-11-29T15:08:43.000Z
gpcl/intrusive_list.hpp
Chingyat/gpcl
c2702b8b13fa948f6753285ba62455ddf9413578
[ "BSL-1.0" ]
null
null
null
// // intrusive_list.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2020 Zhengyi Fu (tsingyat at outlook 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) // #ifndef GPCL_INTRUSIVE_LIST_HPP #define GPCL_INTRUSIVE_LIST_HPP #include <gpcl/detail/config.hpp> #include <gpcl/detail/type_traits.hpp> #include <gpcl/swap.hpp> namespace gpcl { template <typename T, typename Tag = class default_tag> class intrusive_list; template <typename T, typename Tag> class intrusive_list_iterator; class intrusive_list_node_base { public: constexpr intrusive_list_node_base() noexcept : prev(this), next(this) {} intrusive_list_node_base(const intrusive_list_node_base &) = delete; intrusive_list_node_base & operator=(const intrusive_list_node_base &) = delete; void init() noexcept { prev = this; next = this; } ~intrusive_list_node_base() noexcept { GPCL_ASSERT(prev == this); GPCL_ASSERT(next == this); } void swap(intrusive_list_node_base &other) noexcept { gpcl::swap(prev, other.prev); gpcl::swap(next, other.next); } intrusive_list_node_base *prev; intrusive_list_node_base *next; }; namespace swap_detail { inline void swap(intrusive_list_node_base &x, intrusive_list_node_base &y) noexcept { x.swap(y); } } inline void insert_between(intrusive_list_node_base *node, intrusive_list_node_base *prev, intrusive_list_node_base *next) noexcept { next->prev = node; node->next = next; node->prev = prev; prev->next = node; } inline void delete_between(intrusive_list_node_base *prev, intrusive_list_node_base *next) noexcept { next->prev = prev; prev->next = next; } inline void delete_entry(intrusive_list_node_base *entry) noexcept { delete_between(entry->prev, entry->next); } inline void replace_entry(intrusive_list_node_base *old, intrusive_list_node_base *node) noexcept { node->next = old->next; node->next->prev = node; node->prev = old->prev; node->prev->next = node; old->init(); } template <typename T, typename Tag = class default_tag> class intrusive_list_node : public intrusive_list_node_base { friend class intrusive_list<T, Tag>; friend class intrusive_list_iterator<T, Tag>; }; template <typename T, typename Tag> class intrusive_list_iterator { public: using value_type = T; using reference = T &; using pointer = T *; using difference_type = std::ptrdiff_t; using iterator_category = std::bidirectional_iterator_tag; constexpr intrusive_list_iterator() noexcept : data_() {} explicit constexpr intrusive_list_iterator( intrusive_list_node<T, Tag> *p) noexcept : data_(p) { } intrusive_list_iterator(const intrusive_list_iterator &) = default; intrusive_list_iterator &operator=(const intrusive_list_iterator &) = default; reference operator*() const { return static_cast<reference>(*data_); } pointer operator->() const { return static_cast<pointer>(data_); } intrusive_list_iterator &operator++() { data_ = data_->next; return *this; } intrusive_list_iterator &operator--() { data_ = data_->prev; return *this; } intrusive_list_iterator operator++(int) { auto ret = *this; ++*this; return ret; } intrusive_list_iterator operator--(int) { auto ret = *this; --*this; return ret; } friend bool operator==(const intrusive_list_iterator<T, Tag> &x, const intrusive_list_iterator<T, Tag> &y) noexcept { return x.data_ == y.data_; } friend bool operator!=(const intrusive_list_iterator<T, Tag> &x, const intrusive_list_iterator<T, Tag> &y) noexcept { return x.data_ != y.data_; } private: intrusive_list_node<T, Tag> *data_; }; template <typename T, typename Tag> class intrusive_list { public: using value_type = std::decay_t<T>; using reference = T &; using node_type = intrusive_list_node<T, Tag>; using pointer = T *; using iterator = intrusive_list_iterator<T, Tag>; using const_iterator = intrusive_list_iterator<std::add_const_t<T>, Tag>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; constexpr intrusive_list() noexcept = default; intrusive_list(const intrusive_list &&) = delete; ~intrusive_list() noexcept { clear(); } intrusive_list &operator=(const intrusive_list &) = delete; iterator begin() noexcept { return iterator{head_.next}; } iterator end() noexcept { return iterator{&head_}; } const_iterator begin() const noexcept { return const_iterator{head_.next}; } const_iterator end() const noexcept { return const_iterator{&head_}; } const_iterator cbegin() const noexcept { return begin(); } const_iterator cend() const noexcept { return end(); } reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } reverse_iterator rend() noexcept { return reverse_iterator(begin()); } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crbegin() const noexcept { return rbegin(); } const_reverse_iterator crend() const noexcept { return rend(); } /// Indicates whether the list is empty. /// Complexity: constant. bool empty() const noexcept { return head_.next == &head_; } void push_front(reference node) noexcept { delete_entry(static_cast<node_type *>(&node)); insert_between(static_cast<node_type *>(&node), &head_, head_.next); } void push_back(reference node) noexcept { delete_entry(static_cast<node_type *>(&node)); insert_between(static_cast<node_type *>(&node), head_.prev, &head_); } void pop_front() noexcept { GPCL_ASSERT(!empty()); erase(front()); } void pop_back() noexcept { GPCL_ASSERT(!empty()); erase(back()); } void replace(reference old, reference new_) { replace_entry(static_cast<node_type *>(&old), static_cast<node_type *>(&new_)); } void replace(iterator old, reference new_) { replace_entry(*old, new_); } void erase(reference node) noexcept { delete_entry(static_cast<node_type *>(&node)); node.node_type::init(); } void erase(iterator pos) { erase(*pos); } reference back() const noexcept { GPCL_ASSERT(!empty()); return *pointer(static_cast<node_type *>(head_.prev)); } reference front() const noexcept { GPCL_ASSERT(!empty()); return *pointer(static_cast<node_type *>(head_.next)); } /// Tests whether the list has exactly one elements. /// Complexity: constant. bool is_singular() const noexcept { return !empty() && (head_.next == head_.prev); } void clear() noexcept { while (!empty()) { pop_back(); } } void reverse() noexcept { // todo: simplify the code intrusive_list stack; while (!empty()) { auto &entry = front(); erase(entry); stack.push_back(entry); } while (!stack.empty()) { auto &entry = stack.back(); stack.erase(entry); push_back(entry); } } void exchange(reference x, reference y) noexcept { gpcl::swap(static_cast<node_type &>(x), static_cast<node_type &>(y)); } void exchange(iterator x, iterator y) noexcept { exchange(*x, *y); } private: // Use next as the head and prev as the tail. mutable intrusive_list_node<T, Tag> head_; }; } // namespace gpcl #endif // GPCL_INTRUSIVE_LIST_HPP
23.454819
80
0.678952
Chingyat
6f76bd6a9da234b1616213d9337e64bb7a2b1147
10,006
cpp
C++
libredex/MethodDevirtualizer.cpp
thezhangwei/redex
d2da16dcda0ca8a52d3de16456531dfc7793c7b5
[ "BSD-3-Clause" ]
null
null
null
libredex/MethodDevirtualizer.cpp
thezhangwei/redex
d2da16dcda0ca8a52d3de16456531dfc7793c7b5
[ "BSD-3-Clause" ]
null
null
null
libredex/MethodDevirtualizer.cpp
thezhangwei/redex
d2da16dcda0ca8a52d3de16456531dfc7793c7b5
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "MethodDevirtualizer.h" #include "Mutators.h" #include "Resolver.h" #include "VirtualScope.h" #include "Walkers.h" namespace { using CallSiteReferences = std::map<const DexMethod*, std::vector<IRInstruction*>>; DexOpcode invoke_virtual_to_static(DexOpcode op) { switch (op) { case OPCODE_INVOKE_VIRTUAL: return OPCODE_INVOKE_STATIC; case OPCODE_INVOKE_VIRTUAL_RANGE: return OPCODE_INVOKE_STATIC_RANGE; default: always_assert(false); } } DexOpcode invoke_super_to_static(DexOpcode op) { switch (op) { case OPCODE_INVOKE_SUPER: return OPCODE_INVOKE_STATIC; case OPCODE_INVOKE_SUPER_RANGE: return OPCODE_INVOKE_STATIC_RANGE; default: always_assert(false); } } DexOpcode invoke_direct_to_static(DexOpcode op) { switch (op) { case OPCODE_INVOKE_DIRECT: return OPCODE_INVOKE_STATIC; case OPCODE_INVOKE_DIRECT_RANGE: return OPCODE_INVOKE_STATIC_RANGE; default: always_assert(false); } } void patch_call_site(DexMethod* callee, IRInstruction* method_inst, DevirtualizerMetrics& metrics) { auto op = method_inst->opcode(); if (is_invoke_virtual(op)) { method_inst->set_opcode(invoke_virtual_to_static(op)); metrics.num_virtual_calls++; } else if (is_invoke_super(op)) { method_inst->set_opcode(invoke_super_to_static(op)); metrics.num_super_calls++; } else if (is_invoke_direct(op)) { method_inst->set_opcode(invoke_direct_to_static(op)); metrics.num_direct_calls++; } else { always_assert_log(false, SHOW(op)); } method_inst->set_method(callee); } void fix_call_sites_and_drop_this_arg( const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& statics, DevirtualizerMetrics& metrics) { const auto fixer = [&](DexMethod*, IRCode& code) { std::vector<std::pair<IRInstruction*, IRInstruction*>> replacements; for (auto& mie : InstructionIterable(&code)) { auto inst = mie.insn; if (!inst->has_method()) { continue; } auto method = inst->get_method(); if (!method->is_concrete()) { method = resolve_method(method, MethodSearch::Any); } if (!statics.count(method)) { continue; } patch_call_site(method, inst, metrics); if (is_invoke_range(inst->opcode())) { if (inst->range_size() == 1) { auto repl = new IRInstruction(OPCODE_INVOKE_STATIC); repl->set_method(method)->set_arg_word_count(0); replacements.emplace_back(inst, repl); } else { inst->set_range_base(inst->range_base() + 1); inst->set_range_size(inst->range_size() - 1); } } else { auto nargs = inst->arg_word_count(); for (uint16_t i = 0; i < nargs - 1; i++) { inst->set_src(i, inst->src(i + 1)); } inst->set_arg_word_count(nargs - 1); } } for (auto& pair : replacements) { code.replace_opcode(pair.first, pair.second); } }; walk_code(scope, [](DexMethod*) { return true; }, fixer); } void fix_call_sites(const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& target_methods, DevirtualizerMetrics& metrics) { const auto fixer = [&](DexMethod*, IRInstruction* opcode) { if (!opcode->has_method()) { return; } auto method = opcode->get_method(); if (!method->is_concrete()) { method = resolve_method(method, MethodSearch::Virtual); } if (!target_methods.count(method)) { return; } always_assert(!is_invoke_static(opcode->opcode())); patch_call_site(method, opcode, metrics); }; walk_opcodes(scope, [](DexMethod*) { return true; }, fixer); } void make_methods_static(const std::unordered_set<DexMethod*>& methods, bool keep_this) { for (auto method : methods) { TRACE(VIRT, 2, "Staticized method: %s, keep this: %d\n", SHOW(method), keep_this); mutators::make_static( method, keep_this ? mutators::KeepThis::Yes : mutators::KeepThis::No); } } bool uses_this(const DexMethod* method) { auto const* code = method->get_code(); always_assert(!is_static(method) && code != nullptr); auto const this_insn = InstructionIterable(code).begin()->insn; always_assert(this_insn->opcode() == IOPCODE_LOAD_PARAM_OBJECT); auto const this_reg = this_insn->dest(); for (auto& mie : InstructionIterable(code)) { auto insn = mie.insn; if (opcode::has_range(insn->opcode())) { if (this_reg >= insn->range_base() && this_reg < (insn->range_base() + insn->range_size())) { return true; } } for (unsigned i = 0; i < insn->srcs_size(); i++) { if (this_reg == insn->src(i)) { return true; } } } return false; } std::vector<DexMethod*> get_devirtualizable_vmethods( const std::vector<DexClass*>& scope, const std::vector<DexClass*>& targets) { std::vector<DexMethod*> ret; auto vmethods = devirtualize(scope); auto targets_set = std::unordered_set<DexClass*>(targets.begin(), targets.end()); for (auto m : vmethods) { auto cls = type_class(m->get_class()); if (targets_set.count(cls) > 0) { ret.push_back(m); } } return ret; } std::vector<DexMethod*> get_devirtualizable_vmethods( const std::vector<DexClass*>& scope, const std::vector<DexMethod*>& targets) { ClassHierarchy class_hierarchy = build_type_hierarchy(scope); auto signature_map = build_signature_map(class_hierarchy); std::vector<DexMethod*> res; for (const auto m : targets) { always_assert(!is_static(m) && !is_private(m) && !is_any_init(m)); if (can_devirtualize(signature_map, m)) { res.push_back(m); } } return res; } std::vector<DexMethod*> get_devirtualizable_dmethods( const std::vector<DexClass*>& scope, const std::vector<DexClass*>& targets) { std::vector<DexMethod*> ret; auto targets_set = std::unordered_set<DexClass*>(targets.begin(), targets.end()); for (auto cls : scope) { if (targets_set.count(cls) == 0) { continue; } for (auto m : cls->get_dmethods()) { if (is_any_init(m) || is_static(m)) { continue; } ret.push_back(m); } } return ret; } } // namespace void MethodDevirtualizer::verify_and_split( const std::vector<DexMethod*>& candidates, std::unordered_set<DexMethod*>& using_this, std::unordered_set<DexMethod*>& not_using_this) { for (const auto m : candidates) { if (!m_config.ignore_keep && keep(m)) { TRACE(VIRT, 2, "failed to devirt method %s: keep %d\n", SHOW(m), keep(m)); continue; } if (m->is_external() || is_abstract(m)) { TRACE(VIRT, 2, "failed to devirt method %s: external %d abstract %d\n", SHOW(m), m->is_external(), is_abstract(m)); continue; } if (uses_this(m)) { using_this.insert(m); } else { not_using_this.insert(m); } } } void MethodDevirtualizer::staticize_methods_not_using_this( const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& methods) { fix_call_sites_and_drop_this_arg(scope, methods, m_metrics); make_methods_static(methods, false); TRACE(VIRT, 1, "Staticized %lu methods not using this\n", methods.size()); m_metrics.num_methods_not_using_this += methods.size(); } void MethodDevirtualizer::staticize_methods_using_this( const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& methods) { fix_call_sites(scope, methods, m_metrics); make_methods_static(methods, true); TRACE(VIRT, 1, "Staticized %lu methods using this\n", methods.size()); m_metrics.num_methods_using_this += methods.size(); } DevirtualizerMetrics MethodDevirtualizer::devirtualize_methods( const Scope& scope, const std::vector<DexClass*>& target_classes) { reset_metrics(); auto vmethods = get_devirtualizable_vmethods(scope, target_classes); std::unordered_set<DexMethod*> using_this, not_using_this; verify_and_split(vmethods, using_this, not_using_this); TRACE(VIRT, 2, " VIRT to devirt vmethods using this %lu, not using this %lu\n", using_this.size(), not_using_this.size()); if (m_config.vmethods_not_using_this) { staticize_methods_not_using_this(scope, not_using_this); } if (m_config.vmethods_using_this) { staticize_methods_using_this(scope, using_this); } auto dmethods = get_devirtualizable_dmethods(scope, target_classes); using_this.clear(); not_using_this.clear(); verify_and_split(dmethods, using_this, not_using_this); TRACE(VIRT, 2, " VIRT to devirt dmethods using this %lu, not using this %lu\n", using_this.size(), not_using_this.size()); if (m_config.dmethods_not_using_this) { staticize_methods_not_using_this(scope, not_using_this); } if (m_config.dmethods_using_this) { staticize_methods_using_this(scope, using_this); } return m_metrics; } DevirtualizerMetrics MethodDevirtualizer::devirtualize_vmethods( const Scope& scope, const std::vector<DexMethod*>& methods) { reset_metrics(); const auto candidates = get_devirtualizable_vmethods(scope, methods); std::unordered_set<DexMethod*> using_this, not_using_this; verify_and_split(candidates, using_this, not_using_this); if (m_config.vmethods_using_this) { staticize_methods_using_this(scope, using_this); } if (m_config.vmethods_not_using_this) { staticize_methods_not_using_this(scope, not_using_this); } return m_metrics; }
29.779762
80
0.6664
thezhangwei
6f7752ba6e4f4b31a44b6d9c531217d493ba3a45
2,156
cpp
C++
nimbro_topic_transport/test/test_bidirectional.cpp
lsolanka-flya/nimbro_network
13768a9971ea91ce081c4774fb7fecfc4c323912
[ "BSD-3-Clause" ]
105
2015-09-22T14:36:32.000Z
2022-03-09T08:51:43.000Z
nimbro_topic_transport/test/test_bidirectional.cpp
tradr-project/nimbro_network
97e15d7d4c0d1a56fa85cdc62da13b00ef5275a9
[ "BSD-3-Clause" ]
19
2015-09-25T23:23:39.000Z
2021-11-04T16:59:49.000Z
nimbro_topic_transport/test/test_bidirectional.cpp
tradr-project/nimbro_network
97e15d7d4c0d1a56fa85cdc62da13b00ef5275a9
[ "BSD-3-Clause" ]
33
2015-09-25T18:11:31.000Z
2022-03-23T06:55:28.000Z
// Unit tests for nimbro_topic_transport // Author: Max Schwarz <max.schwarz@uni-bonn.de> #include <catch_ros/catch.hpp> #include <ros/package.h> #include <ros/param.h> #include <ros/node_handle.h> #include <std_msgs/Int64.h> int g_counter = 0; void handleMessageLocal(const std_msgs::Int64 &msg) { //REQUIRE(g_counter == msg.data); g_counter++; } void testOneDirection(ros::NodeHandle &nh, bool allow_bidirectional, std::string source_topic, std::string sink_topic) { ros::Publisher pub = nh.advertise<std_msgs::Int64>(source_topic, 2); ros::Subscriber sub = nh.subscribe(sink_topic, 2, &handleMessageLocal); int timeout = 50; while(pub.getNumSubscribers() == 0) { ros::spinOnce(); if(--timeout == 0) { CAPTURE(pub.getNumSubscribers()); FAIL("sender did not subscribe on our topic"); return; } usleep(20 * 1000); } g_counter = 0; std_msgs::Int64 msg; msg.data = 0; pub.publish(msg); ROS_INFO("Sent first message, waiting for 5 seconds to receive it."); for(int i = 0; i < 5000; ++i) { ros::spinOnce(); usleep(1000); } msg.data = 1; pub.publish(msg); ROS_INFO("Sent second message, waiting for 5 seconds to receive it."); for(int i = 0; i < 5000; ++i) { ros::spinOnce(); usleep(1000); } if (allow_bidirectional) { if (g_counter == 2) { ROS_INFO("With bidirectional support, each message was received " "exactly once."); return; } } else { if (g_counter > 10) { ROS_INFO_STREAM("Without bidirectional support, the relay entered " "an infinite loop; the messsages were received " << g_counter << " times."); CAPTURE(g_counter); return; } } CAPTURE(allow_bidirectional); CAPTURE(g_counter); FAIL(); } TEST_CASE("bidirectional_communication", "[topic]") { ros::NodeHandle nh("~"); bool allow_bidirectional; nh.getParam("allow_bidirectional", allow_bidirectional); ROS_INFO("Testing machine1 to machine2 direction."); testOneDirection(nh, allow_bidirectional, "/my_first_topic", "/recv/my_first_topic"); ROS_INFO("Testing machine2 to machine1 direction."); testOneDirection(nh, allow_bidirectional, "/recv/my_first_topic", "/my_first_topic"); }
22.458333
115
0.693414
lsolanka-flya
6f819dd8cc9a224e5416edd92d32920583f64f2b
4,165
cpp
C++
Game/OGRE/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/OGRE/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/OGRE/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://ogre.sourceforge.net/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #include "OgreGLHardwareOcclusionQuery.h" #include "OgreException.h" namespace Ogre { /** * This is a class that is the base class of the query class for * hardware occlusion testing. * * @author Lee Sandberg email: lee@abcmedia.se * * Updated on 12/7/2004 by Chris McGuirk * - Implemented ARB_occlusion_query * Updated on 13/9/2005 by Tuan Kuranes email: tuan.kuranes@free.fr */ //------------------------------------------------------------------ /** * Default object constructor * */ GLHardwareOcclusionQuery::GLHardwareOcclusionQuery() { // Check for hardware occlusion support if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query) { glGenQueriesARB(1, &mQueryID ); } else if (GLEW_NV_occlusion_query) { glGenOcclusionQueriesNV(1, &mQueryID); } else { OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Cannot allocate a Hardware query. This video card doesn't supports it, sorry.", "GLHardwareOcclusionQuery::GLHardwareOcclusionQuery" ); } } //------------------------------------------------------------------ /** * Object destructor */ GLHardwareOcclusionQuery::~GLHardwareOcclusionQuery() { if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query) { glDeleteQueriesARB(1, &mQueryID); } else if (GLEW_NV_occlusion_query) { glDeleteOcclusionQueriesNV(1, &mQueryID); } } //------------------------------------------------------------------ void GLHardwareOcclusionQuery::beginOcclusionQuery() { if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query) { glBeginQueryARB(GL_SAMPLES_PASSED_ARB, mQueryID); } else if (GLEW_NV_occlusion_query) { glBeginOcclusionQueryNV(mQueryID); } } //------------------------------------------------------------------ void GLHardwareOcclusionQuery::endOcclusionQuery() { if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query) { glEndQueryARB(GL_SAMPLES_PASSED_ARB); } else if (GLEW_NV_occlusion_query) { glEndOcclusionQueryNV(); } } //------------------------------------------------------------------ bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments ) { if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query) { glGetQueryObjectuivARB(mQueryID, GL_QUERY_RESULT_ARB, (GLuint*)NumOfFragments); mPixelCount = *NumOfFragments; return true; } else if (GLEW_NV_occlusion_query) { glGetOcclusionQueryuivNV(mQueryID, GL_PIXEL_COUNT_NV, (GLuint*)NumOfFragments); mPixelCount = *NumOfFragments; return true; } return false; } //------------------------------------------------------------------ bool GLHardwareOcclusionQuery::isStillOutstanding(void) { GLuint available; if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query) { glGetQueryObjectuivARB(mQueryID, GL_QUERY_RESULT_AVAILABLE_ARB, &available); } else if (GLEW_NV_occlusion_query) { glGetOcclusionQueryuivNV(mQueryID, GL_PIXEL_COUNT_AVAILABLE_NV, &available); } // GL_TRUE means a wait would occur return !(available == GL_TRUE); } }
28.923611
101
0.642017
hackerlank
6f8adec5b33b6eaea56c23867a485f750db6f26d
235
hpp
C++
include/CountNumbersWithUniqueDigits.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/CountNumbersWithUniqueDigits.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/CountNumbersWithUniqueDigits.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef COUNT_NUMBERS_WITH_UNIQUE_DIGITS_HPP_ #define COUNT_NUMBERS_WITH_UNIQUE_DIGITS_HPP_ class CountNumbersWithUniqueDigits { public: int countNumbersWithUniqueDigits(int n); }; #endif // COUNT_NUMBERS_WITH_UNIQUE_DIGITS_HPP_
23.5
47
0.859574
yanzhe-chen
6f9209c85d7bf2531257f3cd4c6956969e814762
715
hpp
C++
Include/Game/Scene.hpp
igorlev91/DemoEngine
8aaef0d3504826c9dcabe0a826a54613fca81c87
[ "Apache-2.0" ]
null
null
null
Include/Game/Scene.hpp
igorlev91/DemoEngine
8aaef0d3504826c9dcabe0a826a54613fca81c87
[ "Apache-2.0" ]
null
null
null
Include/Game/Scene.hpp
igorlev91/DemoEngine
8aaef0d3504826c9dcabe0a826a54613fca81c87
[ "Apache-2.0" ]
null
null
null
#pragma once /* Scene */ namespace Game { // Scene base class. class Scene { protected: // Protected constructor. Scene() = default; public: // Virtual destructor. virtual ~Scene() = default; // Called when the scene is about to enter. virtual void OnSceneEnter() { } // Called when the scene is about to exit. virtual void OnSceneExit() { } // Called when the scene need to be updated. virtual void OnUpdate(float timeDelta) { } // Called when the scene needs to be drawn. virtual void OnDraw(float timeAlpha) { } }; }
17.439024
52
0.52028
igorlev91
6f9a36efbd782aa8b8dc0daff0a448f1d4813842
3,035
cpp
C++
debugger/src/debugger.cpp
emrsmsrli/gameboi
6448722529bc64184e30a945f0e5ec4203265e10
[ "MIT" ]
23
2019-08-27T13:54:27.000Z
2022-01-21T08:38:14.000Z
debugger/src/debugger.cpp
emrsmsrli/gameboi
6448722529bc64184e30a945f0e5ec4203265e10
[ "MIT" ]
21
2020-02-22T20:37:16.000Z
2020-08-30T14:52:48.000Z
debugger/src/debugger.cpp
emrsmsrli/gameboi
6448722529bc64184e30a945f0e5ec4203265e10
[ "MIT" ]
null
null
null
#include "debugger/debugger.h" #include <spdlog/sinks/stdout_color_sinks.h> #include "gameboy/gameboy.h" #include "imgui-SFML.h" namespace gameboy { debugger::debugger(const observer<gameboy> gb) : gb_{gb}, bus_{gb_->get_bus()}, apu_debugger_{bus_->get_apu()}, cpu_debugger_{bus_->get_cpu()}, cartridge_debugger_{bus_->get_cartridge()}, ppu_debugger_{bus_->get_ppu()}, timer_debugger_{bus_->get_timer()}, joypad_debugger_{bus_->get_joypad()}, link_debugger_{bus_->get_link()}, disassembly_view_{bus_, make_observer(cpu_debugger_)}, memory_bank_debugger_{bus_}, logger_{spdlog::stdout_color_st("debugger")}, window_{ sf::VideoMode{1600, 1200}, "Debugger" } { bus_->get_cpu()->on_instruction({connect_arg<&debugger::on_instruction>, this}); bus_->get_mmu()->on_read_access({connect_arg<&debugger::on_read_access>, this}); bus_->get_mmu()->on_write_access({connect_arg<&debugger::on_write_access>, this}); window_.resetGLStates(); logger_->info("debugger initialized"); ImGui::SFML::Init(window_); } debugger::~debugger() { ImGui::SFML::Shutdown(window_); } void debugger::tick() { ImGui::SFML::SetCurrentWindow(window_); sf::Event event{}; while(window_.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); } const auto delta = delta_clock_.restart(); const auto delta_secs = delta.asSeconds(); ImGui::SFML::Update(window_, delta); last_frame_times_[last_frame_time_idx_] = delta_secs; if(++last_frame_time_idx_ == 100u) { last_frame_time_idx_ = 0u; } if(ImGui::Begin("Performance")) { ImGui::Text("FPS %.3f", 1.f / delta_secs); ImGui::Text("Frame time %.3f", delta_secs); ImGui::PlotLines("", last_frame_times_.data(), last_frame_times_.size(), last_frame_time_idx_, "", 0.f, .1f, ImVec2(250.f, 100.f)); ImGui::End(); } apu_debugger_.draw(); cpu_debugger_.draw(); ppu_debugger_.draw(); timer_debugger_.draw(); memory_bank_debugger_.draw(); joypad_debugger_.draw(); link_debugger_.draw(); cartridge_debugger_.draw(); disassembly_view_.draw(); window_.clear(sf::Color::Black); ImGui::SFML::Render(window_); window_.display(); } void debugger::on_instruction(const address16& addr, const instruction::info& info, const uint16_t data) noexcept { cpu_debugger_.on_instruction(addr, info, data); if(has_execution_breakpoint()) { gb_->tick_enabled = false; } } void debugger::on_write_access(const address16& addr, uint8_t data) noexcept { disassembly_view_.on_write_access(addr, data); if(has_write_access_breakpoint(addr, data)) { gb_->tick_enabled = false; } } void debugger::on_read_access(const address16& addr) noexcept { if(has_read_access_breakpoint(addr)) { gb_->tick_enabled = false; } } } // namespace gameboy
26.622807
113
0.653048
emrsmsrli
6f9bffab5eba3929a4165c9e5baf1fff8d0665f0
25,614
cpp
C++
RegExApiEndpoint.cpp
ziloka/regex101
aabb53c1f763af2c6915e22bb5b0c007a4622300
[ "MIT" ]
33
2021-02-25T02:00:26.000Z
2022-03-21T17:26:24.000Z
RegExApiEndpoint.cpp
ziloka/regex101
aabb53c1f763af2c6915e22bb5b0c007a4622300
[ "MIT" ]
3
2021-02-24T22:40:55.000Z
2022-01-25T08:06:13.000Z
RegExApiEndpoint.cpp
ziloka/regex101
aabb53c1f763af2c6915e22bb5b0c007a4622300
[ "MIT" ]
9
2021-04-10T02:37:13.000Z
2022-03-22T06:43:31.000Z
/* * Copyright (C) 2020 Adrian Carpenter * * This file is part of a regex101.com offline application. * * https://github.com/fizzyade/regex101 * * ===================================================================== * The regex101 web content is owned and used with permission from * Firas Dib at regex101.com. This application is an unofficial * tool to provide an offline application version of the website. * ===================================================================== * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "RegExApiEndpoint.h" #include "RegExDatabase.h" #include <QDateTime> #include <QDebug> #include <QDir> #include <QFile> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QRandomGenerator> #include <QRegularExpression> #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> #include <QSqlRecord> #include <QStandardPaths> constexpr auto permalinkStringLength=6; constexpr auto deleteCodeStringLength=24; Nedrysoft::RegExApiEndpoint::RegExApiEndpoint() { m_settings = new QSettings("nedrysoft", "regex101"); m_database = RegExDatabase::getInstance(); m_librarySearchSortMap[""] = "dateModified DESC"; m_librarySearchSortMap["MOST_RECENT"] = "dateModified DESC"; m_librarySearchSortMap["MOST_POINTS"] = "userVote DESC"; m_librarySearchSortMap["LEAST_POINTS"] = "userVote ASC"; m_librarySearchSortMap["RELEVANCE"] = "upVotes"; } Nedrysoft::RegExApiEndpoint *Nedrysoft::RegExApiEndpoint::getInstance() { static RegExApiEndpoint *instance = new RegExApiEndpoint(); return instance; } QVariant Nedrysoft::RegExApiEndpoint::localStorageSetItem(const QVariant &key, const QVariant &value) { m_settings->setValue(key.toString(), value); return QVariant::Map; } QVariant Nedrysoft::RegExApiEndpoint::localStorageGetItem(const QVariant &key) { if (m_settings->contains(key.toString())) { return m_settings->value(key.toString()); } else { return QVariant::Map; } } QVariant Nedrysoft::RegExApiEndpoint::localStorageRemoveItem(const QVariant &key) { m_settings->remove(key.toString()); return QVariant::Map; } QVariant Nedrysoft::RegExApiEndpoint::localStorageClear() { m_settings->clear(); return QVariant::Map; } QVariant Nedrysoft::RegExApiEndpoint::fetch(const QVariant &pathParameter, const QVariant &requestParameter) const { auto valueMap = requestParameter.toMap(); auto method = valueMap["method"].toString(); if (method=="PUT") { return processPutRequest(pathParameter, requestParameter); } else if (method=="POST") { return processPostRequest(pathParameter, requestParameter); } else if (method=="DELETE") { return processDeleteRequest(pathParameter, requestParameter); } return processGetRequest(pathParameter, requestParameter); } bool Nedrysoft::RegExApiEndpoint::regex(QJsonObject &stateObject, QString permalinkFragment, int version) { QSqlQuery query; QJsonObject general, matchResult, regexEditor, resultMap, libraryEntry; bool didLoadRegEx = false; query = m_database->prepareQuery("getStoredExpression"); query.bindValue(":permalinkFragment", permalinkFragment); query.bindValue(":version", version); matchResult["data"] = QJsonArray(); matchResult["time"] = 0; if (stateObject.contains("general")) { general = stateObject["general"].toObject(); } if (stateObject.contains("regexEditor")) { regexEditor = stateObject["regexEditor"].toObject(); } if (stateObject.contains("libraryEntry")) { libraryEntry = stateObject["libraryEntry"].toObject(); } if (query.exec()) { if (query.first()) { if (query.value("title").isNull()) { regexEditor["title"] = permalinkFragment+"/"+query.value("version").toString(); } else { regexEditor["title"] = query.value("title").toString(); } regexEditor["description"] = query.value("description").toString(); regexEditor["dateModified"] = QDateTime::fromTime_t(query.value("dateModified").toInt()).toString(); regexEditor["author"] = query.value("author").toString(); regexEditor["flavor"] = query.value("flavor").toString(); regexEditor["regex"] = query.value("regex").toString(); regexEditor["delimeter"] = query.value("delimeter").toString(); regexEditor["version"] = version; regexEditor["permalinkFragment"] = permalinkFragment; regexEditor["flags"] = query.value("flags").toString(); regexEditor["testString"] = query.value("testString").toString(); regexEditor["matchResult"] = matchResult; regexEditor["error"] = query.value("error").toString(); regexEditor["substString"] = query.value("substString").toString(); regexEditor["hasUnsavedData"] = false; regexEditor["regexVersions"] = query.value("versionCount").toInt(); regexEditor["showMatchArea"] = false; regexEditor["showSubstitutionArea"] = true; regexEditor["showUnitTestArea"] = false; general["permalinkFragment"] = regexEditor["permalinkFragment"]; general["version"] = regexEditor["version"]; general["isLibraryEntry"] = query.value("isLibraryEntry").toBool(); general["isFavourite"] = false; libraryEntry["title"] = regexEditor["title"]; libraryEntry["description"] = regexEditor["description"]; libraryEntry["author"] = regexEditor["author"]; didLoadRegEx = true; } } stateObject["regexEditor"] = regexEditor; stateObject["general"] = general; stateObject["libraryEntry"] = libraryEntry; return didLoadRegEx; } QVariant Nedrysoft::RegExApiEndpoint::processGetRequest(const QVariant &pathParameter, const QVariant &requestParameter) const { QJsonObject jsonResponse; auto path = pathParameter.toString(); auto staticMatch = QRegularExpression(R"(^\/static\/?)").match(path); auto detailsMatch = QRegularExpression(R"(\/api\/library\/details\/(?P<permalinkFragment>.*))").match(path); auto libraryMatch = QRegularExpression(R"(\/api\/library\/\d*\/\?orderBy=(?P<orderBy>.*)\&search=(?P<search>.*))").match(path); auto regexMatch = QRegularExpression(R"(\/api\/regex\/(?P<permalinkFragment>.*))").match(path); auto historyMatch = QRegularExpression(R"(^\/api\/user\/history\/(?P<owner>.*)\/(?P<page>\d+)\/(?P<unknown>.*))").match(path); if (staticMatch.hasMatch()) { return processGetStatic(pathParameter, requestParameter, staticMatch); } else if (detailsMatch.hasMatch()) { return processGetItemDetails(pathParameter, requestParameter, detailsMatch); } else if (libraryMatch.hasMatch()) { return processGetLibraryItems(pathParameter, requestParameter, libraryMatch); } else if (regexMatch.hasMatch()) { return processGetRegEx(pathParameter, requestParameter, libraryMatch); } else if (historyMatch.hasMatch()) { return processGetHistory(pathParameter, requestParameter, historyMatch); } return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processPutRequest(const QVariant &pathParameter, const QVariant &requestParameter) const { QJsonObject jsonResponse; auto path = pathParameter.toString(); auto historyMatch = QRegularExpression(R"(\/api\/user\/history\/(?P<permalinkFragment>[A-Z|a-z|0-9]*)\/(?P<version>\d*)\/(?P<action>([a-z|A-Z|0-9]*))$)").match(path); auto userOperationMatch = QRegularExpression(R"(\/api\/user\/(?P<operation>.*)\/(?P<permalinkFragment>[A-Z|a-z|0-9]*)\/(?P<version>\d*)$)").match(path); if (historyMatch.hasMatch()) { return processPutHistoryRequest(pathParameter, requestParameter, historyMatch); } else if (userOperationMatch.hasMatch()) { if (userOperationMatch.captured("operation")=="favorite") { return processSetFavorite(pathParameter, requestParameter, userOperationMatch); } } return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processPostRequest(const QVariant &pathParameter, const QVariant &requestParameter) const { QJsonObject jsonResponse; auto path = pathParameter.toString(); if (QRegularExpression(R"(^\/api\/regex\/fork)").match(path).hasMatch()) { return processForkRequest(pathParameter, requestParameter); } else if (QRegularExpression(R"(^\/api\/regex\/?)").match(path).hasMatch()) { return processSaveRequest(pathParameter, requestParameter); } else if (QRegularExpression(R"(^\/api\/library\/?)").match(path).hasMatch()) { return processUploadToLibraryRequest(pathParameter, requestParameter); } return QVariantMap(); } QVariant Nedrysoft::RegExApiEndpoint::processDeleteRequest(const QVariant &pathParameter, const QVariant &requestParameter) const { Q_UNUSED(pathParameter); Q_UNUSED(requestParameter); QJsonObject jsonResponse; jsonResponse["message"] = "Your regex has been deleted."; return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processSaveRequest(const QVariant &pathParameter, const QVariant &requestParameter) const { Q_UNUSED(pathParameter); QJsonObject jsonResponse; QJsonObject bodyObject = QJsonDocument::fromJson(requestParameter.toMap()["body"].toByteArray()).object(); QString permalinkFragment = createPermalinkFragment(); QString deleteCode = createDeleteCode(); QSqlQuery query; qDebug() << requestParameter; if (bodyObject["permalinkFragment"].isNull()) { query = m_database->prepareQuery("insertExpression"); query.bindValue(":permalinkFragment", permalinkFragment); query.bindValue(":deleteCode", deleteCode); query.bindValue(":dateModified", QDateTime::currentDateTime().toTime_t()); query.bindValue(":author", "adrian"); if (!query.exec()) { // return some error } auto expressionId = query.lastInsertId().toInt(); query = m_database->prepareQuery("insertFirstVersion"); query.bindValue(":expressionId", expressionId); query.bindValue(":regex", bodyObject["regex"].toString()); query.bindValue(":testString", bodyObject["testString"].toString()); query.bindValue(":flags", bodyObject["flags"].toString()); query.bindValue(":delimeter", bodyObject["delimiter"].toString()); query.bindValue(":flavor", bodyObject["flavor"].toString()); query.bindValue(":substitution", bodyObject["substitution"].toString()); query.bindValue(":version", 1); if (query.exec()) { jsonResponse["deleteCode"] = deleteCode; jsonResponse["permalinkFragment"] = permalinkFragment; jsonResponse["version"] = 1; jsonResponse["isLibraryEntry"] = false; } else { // SQL insert failed } } else { query = m_database->prepareQuery("insertNewVersion"); query.bindValue(":permalinkFragment", bodyObject["permalinkFragment"].toString()); query.bindValue(":regex", bodyObject["regex"].toString()); query.bindValue(":testString", bodyObject["testString"].toString()); query.bindValue(":flags", bodyObject["flags"].toString()); query.bindValue(":delimeter", bodyObject["delimiter"].toString()); query.bindValue(":flavor", bodyObject["flavor"].toString()); query.bindValue(":substits ution", bodyObject["substitution"].toString()); if (query.exec()) { jsonResponse["deleteCode"] = deleteCode; jsonResponse["permalinkFragment"] = permalinkFragment; jsonResponse["version"] = 1; jsonResponse["isLibraryEntry"] = false; } else { // SQL insert failed } } return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processForkRequest(const QVariant &pathParameter, const QVariant &requestParameter) const { Q_UNUSED(pathParameter); QJsonObject jsonResponse; QJsonObject bodyObject = QJsonDocument::fromJson(requestParameter.toMap()["body"].toByteArray()).object(); QString permalinkFragment = createPermalinkFragment(); QString deleteCode = createDeleteCode(); auto query = m_database->prepareQuery("insertExpression"); query.bindValue(":permalinkFragment", permalinkFragment); query.bindValue(":deleteCode", deleteCode); query.bindValue(":dateModified", QDateTime::currentDateTime().toTime_t()); query.bindValue(":author", "adrian"); if (!query.exec()) { // return some error } auto expressionId = query.lastInsertId().toInt(); query = m_database->prepareQuery("insertFirstVersion"); query.bindValue(":expressionId", expressionId); query.bindValue(":regex", bodyObject["regex"].toString()); query.bindValue(":testString", bodyObject["testString"].toString()); query.bindValue(":flags", bodyObject["flags"].toString()); query.bindValue(":delimeter", bodyObject["delimiter"].toString()); query.bindValue(":flavor", bodyObject["flavor"].toString()); query.bindValue(":substitution", bodyObject["substitution"].toString()); query.bindValue(":version", 1); if (query.exec()) { jsonResponse["deleteCode"] = deleteCode; jsonResponse["permalinkFragment"] = permalinkFragment; jsonResponse["version"] = 1; jsonResponse["isLibraryEntry"] = false; } else { // SQL insert failed } return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processGetLibraryItems(const QVariant &pathParameter, const QVariant &requestParameter, const QRegularExpressionMatch &match) const { Q_UNUSED(pathParameter); Q_UNUSED(requestParameter); QJsonArray jsonResultArray; QJsonObject jsonResponse, jsonResult; QSqlQuery query = m_database->prepareQuery("getLibraryItems"); query.bindValue(":search", QString("%%1%").arg(match.captured("search"))); query.bindValue(":orderBy", m_librarySearchSortMap[match.captured("orderBy")]); if (query.exec()) { if (query.first()) { do { if (query.value("title").isNull()) { jsonResult["title"] = query.value("permalinkFragment").toString()+"/"+ query.value("version").toString(); } else { jsonResult["title"] = query.value("title").toString(); } jsonResult["description"] = query.value("description").toString(); jsonResult["dateModified"] = QDateTime::fromTime_t(query.value("dateModified").toInt()).toString(); jsonResult["author"] = query.value("author").toString(); jsonResult["flavor"] = query.value("flavor").toString(); jsonResult["version"] = query.value("version").toInt(); jsonResult["permalinkFragment"] = query.value("permalinkFragment").toString(); jsonResult["upvotes"] = query.value("upVotes").toInt(); jsonResult["downvotes"] = query.value("downVotes").toInt(); jsonResult["regex"] = query.value("regex").toString(); jsonResult["uservotes"] = query.value("userVotes").toInt(); jsonResultArray.append(jsonResult); } while(query.next()); } } jsonResponse["data"] = jsonResultArray; return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processGetItemDetails(const QVariant &pathParameter, const QVariant &requestParameter, const QRegularExpressionMatch &match) const { Q_UNUSED(requestParameter); QJsonObject jsonResponse; QSqlQuery query; auto path = pathParameter.toString(); query = m_database->prepareQuery("getItemDetails"); query.bindValue(":permalinkFragment", match.captured("permalinkFragment")); if (query.exec()) { if (query.first()) { jsonResponse["title"] = query.value("title").toString(); jsonResponse["description"] = query.value("description").toString(); jsonResponse["dateModified"] = QDateTime::fromTime_t(query.value("dateModified").toInt()).toString(); jsonResponse["author"] = query.value("author").toString(); jsonResponse["flavor"] = query.value("flavor").toString(); jsonResponse["regex"] = query.value("regex").toString(); jsonResponse["delimeter"] = query.value("delimeter").toString(); jsonResponse["version"] = query.value("version").toInt(); jsonResponse["permalinkFragment"] = query.value("permalinkFragment").toString(); jsonResponse["flags"] = query.value("flags").toString(); } } return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processGetStatic(const QVariant &pathParameter, const QVariant &requestParameter, const QRegularExpressionMatch &match) const { Q_UNUSED(requestParameter); Q_UNUSED(match); auto path = pathParameter.toString(); QFile file(QDir::cleanPath(":/regex101/"+path)); if (file.open(QFile::ReadOnly)) { return file.readAll(); } return QString(); } QString Nedrysoft::RegExApiEndpoint::createRandomString(int numberOfCharacters) const { QVector<char> characterMap; QString permalinkFragment; for (char currentCharacter='A';currentCharacter<='Z';currentCharacter++) { characterMap.append(currentCharacter); characterMap.append(tolower(currentCharacter)); } for (char currentCharacter='0';currentCharacter<='9';currentCharacter++) { characterMap.append(currentCharacter); } for (int currentCharacter=0;currentCharacter<numberOfCharacters;currentCharacter++) { permalinkFragment = permalinkFragment.append(characterMap.at(QRandomGenerator::global()->bounded(characterMap.count()))); } return permalinkFragment; } QString Nedrysoft::RegExApiEndpoint::createPermalinkFragment() const { return createRandomString(permalinkStringLength); } QString Nedrysoft::RegExApiEndpoint::createDeleteCode() const { return createRandomString(deleteCodeStringLength); } QVariant Nedrysoft::RegExApiEndpoint::processPutHistoryRequest(const QVariant &pathParameter, const QVariant &requestParameter, const QRegularExpressionMatch &match) const { Q_UNUSED(pathParameter); QSqlQuery query; auto bodyObject = QJsonDocument::fromJson(requestParameter.toMap()["body"].toByteArray()).object(); auto permalinkFragment = match.captured("permalinkFragment"); auto version = match.captured("version"); auto action = match.captured("action"); if (action=="tags") { auto tags = bodyObject["tags"].toArray(); query = m_database->prepareQuery("deleteTags"); query.bindValue(":permalinkFragment", permalinkFragment); if (query.exec()) { for(auto tag: tags) { query = m_database->prepareQuery("insertTag"); query.bindValue(":tag", tag.toString()); query.bindValue(":permalinkFragment", permalinkFragment); if (query.exec()) { // success } } } } else if (action=="title") { query = m_database->prepareQuery("updateTitle"); query.bindValue(":title", bodyObject["title"].toString()); query.bindValue(":permalinkFragment", permalinkFragment); if (query.exec()) { // success } } return QString(); } void Nedrysoft::RegExApiEndpoint::notifyApplication(QVariant message) const { Q_UNUSED(message); } QVariant Nedrysoft::RegExApiEndpoint::processGetRegEx(const QVariant &pathParameter, const QVariant &requestParameter, const QRegularExpressionMatch &match) const { Q_UNUSED(pathParameter); Q_UNUSED(requestParameter); QSqlQuery query; QJsonObject jsonResponse; query = m_database->prepareQuery("getStoredExpression"); query.bindValue(":permalinkFragment", match.captured("permalinkFragment")); query.bindValue(":version", 1); if (query.exec()) { if (query.first()) { jsonResponse["permalinkFragment"] = match.captured("permalinkFragment"); jsonResponse["versions"] = query.value("versionCount").toInt(); } } return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processUploadToLibraryRequest(const QVariant &pathParameter, const QVariant &requestParameter) const { Q_UNUSED(pathParameter); QJsonObject jsonResponse; QJsonObject bodyObject = QJsonDocument::fromJson(requestParameter.toMap()["body"].toByteArray()).object(); QString permalinkFragment = createPermalinkFragment(); QString deleteCode = createDeleteCode(); QSqlQuery query; /* if (bodyObject["isFavorite"].toBool()) { query = m_database->prepareQuery("setFavorite"); query.bindValue("userId", ) if (query.exec()) { } } qDebug() << requestParameter; */ /* QSqlQuery query; if (bodyObject["permalinkFragment"].isNull()) { query = m_database->prepareQuery("insertExpression"); query.bindValue(":permalinkFragment", permalinkFragment); query.bindValue(":deleteCode", deleteCode); query.bindValue(":upvote", 0); query.bindValue(":downvote", 0); query.bindValue(":userVote", 0); query.bindValue(":dateModified", QDateTime::currentDateTime().toTime_t()); query.bindValue(":author", "adrian"); if (!query.exec()) { // return some error } query = m_database->prepareQuery("insertFirstVersion"); query.bindValue(":permalinkFragment", permalinkFragment); query.bindValue(":regex", bodyObject["regex"].toString()); query.bindValue(":testString", bodyObject["testString"].toString()); query.bindValue(":flags", bodyObject["flags"].toString()); query.bindValue(":delimeter", bodyObject["delimiter"].toString()); query.bindValue(":flavor", bodyObject["flavor"].toString()); query.bindValue(":substitution", bodyObject["substitution"].toString()); query.bindValue(":version", 1); if (query.exec()) { jsonResponse["deleteCode"] = deleteCode; jsonResponse["permalinkFragment"] = permalinkFragment; jsonResponse["version"] = 1; jsonResponse["isLibraryEntry"] = false; } else { // SQL insert failed } } else { query = m_database->prepareQuery("insertNewVersion"); query.bindValue(":permalinkFragment", bodyObject["permalinkFragment"].toString()); query.bindValue(":regex", bodyObject["regex"].toString()); query.bindValue(":testString", bodyObject["testString"].toString()); query.bindValue(":flags", bodyObject["flags"].toString()); query.bindValue(":delimeter", bodyObject["delimiter"].toString()); query.bindValue(":flavor", bodyObject["flavor"].toString()); query.bindValue(":substitution", bodyObject["substitution"].toString()); if (query.exec()) { jsonResponse["deleteCode"] = deleteCode; jsonResponse["permalinkFragment"] = permalinkFragment; jsonResponse["version"] = 1; jsonResponse["isLibraryEntry"] = false; } else { // SQL insert failed } } */ return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processSetFavorite(const QVariant &pathParameter, const QVariant &requestParameter, const QRegularExpressionMatch &match) const { Q_UNUSED(pathParameter); QJsonObject jsonResponse; QJsonObject bodyObject = QJsonDocument::fromJson(requestParameter.toMap()["body"].toByteArray()).object(); QSqlQuery query; if (bodyObject["isFavorite"].toBool()) { query = m_database->prepareQuery("setFavorite"); query.bindValue(":permalinkFragment", match.captured("permalinkFragment")); query.bindValue(":userId", 1); } else { query = m_database->prepareQuery("deleteFavorite"); query.bindValue(":permalinkFragment", match.captured("permalinkFragment")); query.bindValue(":userId", 1); } if (query.exec()) { // success } return QJsonDocument(jsonResponse).toJson(); } QVariant Nedrysoft::RegExApiEndpoint::processGetHistory(const QVariant &pathParameter, const QVariant &requestParameter, const QRegularExpressionMatch &match) const { Q_UNUSED(pathParameter); Q_UNUSED(requestParameter); Q_UNUSED(match); return QVariant(); }
37.283843
171
0.66612
ziloka
6f9dcf49f5ae8acce8a042c37ee69da1baf0abea
926
cpp
C++
Dynamic Programming/Coin Change/C++/coin_change.cpp
LuisMBaezCo/AlgorithmNotebook
43479e4331143987e627d222c9a65ed9d23d6c8f
[ "MIT" ]
16
2020-03-02T20:03:28.000Z
2021-06-15T05:02:59.000Z
Dynamic Programming/Coin Change/C++/coin_change.cpp
LuisMBaezCo/AlgorithmNotebook
43479e4331143987e627d222c9a65ed9d23d6c8f
[ "MIT" ]
null
null
null
Dynamic Programming/Coin Change/C++/coin_change.cpp
LuisMBaezCo/AlgorithmNotebook
43479e4331143987e627d222c9a65ed9d23d6c8f
[ "MIT" ]
4
2020-09-15T07:47:38.000Z
2021-10-31T01:25:02.000Z
#include <bits/stdc++.h> using namespace std; class CoinChange { public: vector<int> memo; int coinChange(vector<int>& coins, int amount) { memo.resize(amount+1, -1); int answer = solve(coins, amount); return (answer==INT_MAX)?-1:answer; } int solve(vector<int>& coins, int amount) { if(amount < 0) return INT_MAX; if(amount == 0) return 0; if(memo[amount] != -1) return memo[amount]; int minimum = INT_MAX; int curr; for(int coin: coins) { curr = solve(coins, amount - coin); minimum = min(minimum, ((curr==INT_MAX)?INT_MAX:curr+1)); } memo[amount] = minimum; return memo[amount]; } }; int main() { CoinChange cc; vector<int> coins{1, 2, 5}; int amount = 11; cout<<cc.coinChange(coins, amount)<<endl; // 3 return 0; }
21.534884
69
0.531317
LuisMBaezCo
6fa06f4cc91f29adcc15c3a5cd97e5384f99a2d1
2,185
hpp
C++
src/Distribution_Hot_O.hpp
bethang/corona3d_2020
868dcea42dbcc04c49b8fbe3635f2a2fbd8c9d6f
[ "MIT" ]
null
null
null
src/Distribution_Hot_O.hpp
bethang/corona3d_2020
868dcea42dbcc04c49b8fbe3635f2a2fbd8c9d6f
[ "MIT" ]
null
null
null
src/Distribution_Hot_O.hpp
bethang/corona3d_2020
868dcea42dbcc04c49b8fbe3635f2a2fbd8c9d6f
[ "MIT" ]
2
2021-05-26T18:22:15.000Z
2022-01-27T17:31:00.000Z
/* * Distribution_Hot_O.hpp * * Created on: Jul 22, 2020 * Author: rodney */ #ifndef DISTRIBUTION_HOT_O_HPP_ #define DISTRIBUTION_HOT_O_HPP_ #include "Distribution.hpp" class Distribution_Hot_O: public Distribution { public: Distribution_Hot_O(Planet my_p, double ref_h, double ref_T); virtual ~Distribution_Hot_O(); void init(shared_ptr<Particle> p); double get_global_rate(); private: // these 4 are from Justin's original Fortran code; may still need at some point double DR160; // [cm^3/s] dissociative recombination rate at 200km double H_DR; // [cm] dissociative recombination scale height double T_ion; // [K] ion temperature double T_e; // [K] electron temperature // everything below here is needed for the new process double m_O2plus; // [g] O2+ ion mass double m_O; // [g] neutral O mass double O2plus_DR_rate_coeff; // [cm^3/s] rate coefficient for O2+ + e -> O* + O* double global_rate; // [s^-1] set by chosen production method; calling function needs to divide this by 2 to get hemispherical rate string source; // which source to use when initializing particles (currently 'O2plus_DR' is only option) vector<vector<double>> O2plus_profile; // stores the imported O2plus density profile vector<vector<double>> electron_profile; // stores the imported electron density profile vector<vector<double>> temp_profile; // stores the imported temperature profiles (4-column csv expected: altitude(cm), neutral_temp(K), ion_temp(K), electron_temp(K)) vector<vector<double>> O2plus_DR_CDF; // stores an inverse CDF made using the O2plus_DR production rate profile // scans O2plus_DR_CDF for new particle radius double get_new_radius_O2plus_DR(); // init particle using O2plus_DR mechanism void init_O2plus_DR_particle(shared_ptr<Particle> p); // init particle using Justin's original method void init_old_way(shared_ptr<Particle> p); // generate O2plus_DR_CDF for given altitude range using imported density/temp profiles void make_O2plus_DR_CDF(double lower_alt, double upper_alt); // calculate rotational energy of O2plus ion double E_rot(double B, double T); }; #endif /* DISTRIBUTION_HOT_O_HPP_ */
39.017857
168
0.756064
bethang
6fa3e23b90e16b84bc8c6edab0d618ba2e9d5f0f
1,889
hpp
C++
explainer/languageCheck.hpp
luosiwei-cmd/Maticpouse
382c45e030b3e944607249fea730558d061a6f03
[ "MIT" ]
1
2020-08-03T07:20:07.000Z
2020-08-03T07:20:07.000Z
explainer/languageCheck.hpp
luosiwei-cmd/Maticpouse
382c45e030b3e944607249fea730558d061a6f03
[ "MIT" ]
null
null
null
explainer/languageCheck.hpp
luosiwei-cmd/Maticpouse
382c45e030b3e944607249fea730558d061a6f03
[ "MIT" ]
1
2021-07-11T03:02:48.000Z
2021-07-11T03:02:48.000Z
#ifndef languageCheck_hpp #define languageCheck_hpp #include<bits/stdc++.h> class languageCheck{ public: languageCheck(); void outputMarkdown(std::vector<std::string> & dests); void setTitle(std::string title); int run(std::vector<std::string>& content); int getContent(std::vector<std::string>& content); void printContent(); int translate(); private: std::string ContentTitle; enum All_Statue{ INCODE, NORMAL, INBLOCK, INTABLE, TABLE_FMT } status; std::string preReplace(std::string s); std::string getTime(); std::vector<std::string> content; size_t contentLength; std::vector<std::string> output; int isToc(std::string s); std::string TocContent; struct Toc{int deep; std::string name;}; bool needToc = 0; int TocNumber = 0; std::vector<struct Toc> Tocs; std::vector<std::string> TocString; void handleToc(); bool needMathjax = 0; int isTitle(std::string s); int isHorizon(std::string s); std::string handleTitle(std::string s,int titleLevel); std::string handleHorizon(); void handleUnList(); int isUnList(std::string s); void handleList(); int isList(std::string s); int BlockNumber = 0; int isBlock(std::string s); std::string handleBlock(std::string s,int number); int handleBlock_S(std::string s); int isBr(std::string s); int isCode(std::string s); void handletoken(); int handleCode(std::string s); int TableNumber = 0; std::vector<std::string> aligns; int handleTable(std::string s); std::vector<std::string> getTableElem(std::string s); void handleFlow(); }; #endif /* languageCheck_hpp */
23.320988
59
0.591848
luosiwei-cmd
6faf9b1b42cf908812d74c36f3f38f2c94193655
132
cpp
C++
src/CueTransformable.cpp
sebleedelisle/ofxTimely
4546f66431580a3b66363182f12ed3d9c741ad10
[ "MIT" ]
null
null
null
src/CueTransformable.cpp
sebleedelisle/ofxTimely
4546f66431580a3b66363182f12ed3d9c741ad10
[ "MIT" ]
null
null
null
src/CueTransformable.cpp
sebleedelisle/ofxTimely
4546f66431580a3b66363182f12ed3d9c741ad10
[ "MIT" ]
null
null
null
// // CueTransformable.cpp // BecHillLasers // // Created by Seb Lee-Delisle on 30/07/2018. // // #include "CueTransformable.h"
13.2
45
0.666667
sebleedelisle
6fb4d2aae35d0cc21879ad2c0841a807f209693f
35,152
cpp
C++
ESP32/TinyMCUMEesp81ttgovga32/MECUMEesp81/emuapi.cpp
rpsubc8/ESP32TinyMCUMEesp81
3b96e6a0e0a0d753bf22ed14c76959fc83ad57d2
[ "WTFPL" ]
3
2021-11-01T13:59:41.000Z
2022-01-20T17:59:24.000Z
ESP32/TinyMCUMEesp81ttgovga32/MECUMEesp81/emuapi.cpp
rpsubc8/ESP32TinyMCUMEesp81
3b96e6a0e0a0d753bf22ed14c76959fc83ad57d2
[ "WTFPL" ]
null
null
null
ESP32/TinyMCUMEesp81ttgovga32/MECUMEesp81/emuapi.cpp
rpsubc8/ESP32TinyMCUMEesp81
3b96e6a0e0a0d753bf22ed14c76959fc83ad57d2
[ "WTFPL" ]
null
null
null
//#define KEYMAP_PRESENT 1 #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include "emuapi.h" #include "gbConfig.h" #include "gbGlobals.h" #include "Arduino.h" //JJ extern "C" { //JJ #include "emuapi.h" //JJ #include "iopins.h" //JJ} //JJ #include "ili9341_t3dma.h" //#include "logozx80kbd.h" //#include "logozx81kbd.h" //JJ #include "bmpjoy.h" //JJ #include "bmpvbar.h" //JJ #include "esp_event.h" //JJ #include "esp_vfs_fat.h" //JJ #include "driver/sdspi_host.h" #include <dirent.h> #include <sys/stat.h> //JJ #include <driver/adc.h> //JJ #ifdef HAS_I2CKBD //JJ #ifdef USE_WIRE //JJ #include "Wire.h" //JJ #else //JJ #include <driver/i2c.h> //JJ #define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/ //JJ #define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */ //JJ #define ACK_VAL 0x0 /*!< I2C ack value */ //JJ #define NACK_VAL 0x1 /*!< I2C nack value */ //JJ #endif //JJ #define I2C_FREQ_HZ 400000 /*!< I2C master clock frequency */ //JJ static bool i2cKeyboardPresent = false; //JJ #endif //JJ extern ILI9341_t3DMA tft; static char romspath[64]; //JJ static int calMinX=-1,calMinY=-1,calMaxX=-1,calMaxY=-1; //JJ static sdmmc_card_t* card; //JJ const uint16_t deflogo[] = { //JJ 0x0000,0x0000 //JJ }; //JJ static const uint16_t * logo = deflogo; //JJ static const unsigned short * keysw = keyswzx80; //JJ #define CALIBRATION_FILE "/sdcard/cal.cfg" //JJ #define MAX_FILENAME_SIZE 28 //JJ #define MAX_MENULINES (MKEY_L9) //JJ #define TEXT_HEIGHT 16 //JJ #define TEXT_WIDTH 8 //JJ #define MENU_FILE_XOFFSET (6*TEXT_WIDTH) //JJ #define MENU_FILE_YOFFSET (2*TEXT_HEIGHT) //JJ #define MENU_FILE_W (MAX_FILENAME_SIZE*TEXT_WIDTH) //JJ #define MENU_FILE_H (MAX_MENULINES*TEXT_HEIGHT) //JJ #define MENU_FILE_FGCOLOR RGBVAL16(0xff,0xff,0xff) //JJ #define MENU_FILE_BGCOLOR RGBVAL16(0x00,0x00,0x20) //JJ #define MENU_JOYS_YOFFSET (12*TEXT_HEIGHT) //JJ #define MENU_VBAR_XOFFSET (0*TEXT_WIDTH) //JJ #define MENU_VBAR_YOFFSET (MENU_FILE_YOFFSET) //JJ #define MKEY_L1 1 //JJ #define MKEY_L2 2 //JJ #define MKEY_L3 3 //JJ #define MKEY_L4 4 //JJ #define MKEY_L5 5 //JJ #define MKEY_L6 6 //JJ #define MKEY_L7 7 //JJ #define MKEY_L8 8 //JJ #define MKEY_L9 9 //JJ #define MKEY_UP 20 //JJ #define MKEY_DOWN 21 //JJ #define MKEY_JOY 22 //JJ const unsigned short menutouchareas[] = { //JJ TAREA_XY,MENU_FILE_XOFFSET,MENU_FILE_YOFFSET, //JJ TAREA_WH,MENU_FILE_W, TEXT_HEIGHT, //JJ TAREA_NEW_COL,TEXT_HEIGHT,TEXT_HEIGHT,TEXT_HEIGHT,TEXT_HEIGHT,TEXT_HEIGHT,TEXT_HEIGHT,TEXT_HEIGHT,TEXT_HEIGHT,TEXT_HEIGHT, //JJ //JJ TAREA_XY,MENU_VBAR_XOFFSET,MENU_VBAR_YOFFSET, //JJ TAREA_WH,32,48, //JJ TAREA_NEW_COL, 72,72,8,40, //JJ //JJ TAREA_END}; //JJ const unsigned short menutouchactions[] = { //JJ MKEY_L1,MKEY_L2,MKEY_L3,MKEY_L4,MKEY_L5,MKEY_L6,MKEY_L7,MKEY_L8,MKEY_L9, //JJ MKEY_UP,MKEY_DOWN,ACTION_NONE,MKEY_JOY}; //JJ static bool menuOn=true; //JJ static bool callibrationOn=false; //JJ static int callibrationStep=0; //JJ static bool menuRedraw=true; //JJ static int nbFiles=0; //JJ static int curFile=0; //JJ static int topFile=0; //JJ static char selection[MAX_FILENAME_SIZE+1]=""; //JJ static uint8_t prev_zt=0; //JJ static int readNbFiles(void) { //JJ int totalFiles = 0; //JJ //JJ DIR* dir = opendir(romspath); //JJ while (true) { //JJ struct dirent* de = readdir(dir); //JJ if (!de) { //JJ // no more files //JJ break; //JJ } //JJ if (de->d_type == DT_REG) { //JJ totalFiles++; //JJ } //JJ else if (de->d_type == DT_DIR) { //JJ if ( (strcmp(de->d_name,".")) && (strcmp(de->d_name,"..")) ) { //JJ totalFiles++; //JJ } //JJ } //JJ } //JJ closedir(dir); //JJ printf("Directory read: %d files",totalFiles); //JJ return totalFiles; //JJ } //JJ static char captureTouchZone(const unsigned short * areas, const unsigned short * actions, int *rx, int *ry, int *rw, int * rh) { //JJ uint16_t xt=0; //JJ uint16_t yt=0; //JJ uint16_t zt=0; //JJ bool hDir=true; //JJ /*JJ if (tft.isTouching()) { if (prev_zt == 0) { prev_zt =1; tft.readCal(&xt,&yt,&zt); if (zt<1000) { prev_zt=0; return ACTION_NONE; } int i=0; int k=0; int y2=0, y1=0; int x2=0, x1=0; int x=KEYBOARD_X,y=KEYBOARD_Y; int w=TAREA_W_DEF,h=TAREA_H_DEF; uint8_t s; while ( (s=areas[i++]) != TAREA_END ) { if (s == TAREA_XY) { x = areas[i++]; y = areas[i++]; x2 = x; y2 = y; } else if (s == TAREA_WH) { w = areas[i++]; h = areas[i++]; } else if (s == TAREA_NEW_ROW) { hDir = true; y1 = y2; y2 = y1 + h; x2 = x; } else if (s == TAREA_NEW_COL) { hDir = false; x1 = x2; x2 = x1 + w; y2 = y; } else { if (hDir) { x1 = x2; x2 = x1+s; } else { y1 = y2; y2 = y1+s; } if ( (yt >= y1) && (yt < y2) && (xt >= x1) && (xt < x2) ) { *rx = x1; *ry = y1; *rw = x2-x1; *rh = y2-y1; return (actions[k]); } k++; } } } prev_zt =1; } else { prev_zt=0; } */ //JJ //JJ return ACTION_NONE; //JJ } //JJ void toggleMenu(bool on) { //JJ if (on) { //JJ callibrationOn=false; //JJ menuOn=true; //JJ menuRedraw=true; //JJ tft.fillScreenNoDma(RGBVAL16(0x00,0x00,0x00)); //JJ tft.drawTextNoDma(0,0, TITLE, RGBVAL16(0x00,0xff,0xff), RGBVAL16(0x00,0x00,0xff), true); //JJ tft.drawSpriteNoDma(MENU_VBAR_XOFFSET,MENU_VBAR_YOFFSET,(uint16_t*)bmpvbar); //JJ } else { //JJ menuOn = false; //JJ } //JJ } //JJ static void callibrationInit(void) //JJ { //JJ callibrationOn=true; //JJ menuOn=false; //JJ callibrationStep = 0; //JJ calMinX=0,calMinY=0,calMaxX=0,calMaxY=0; //JJ tft.fillScreenNoDma(RGBVAL16(0xff,0xff,0xff)); //JJ tft.drawTextNoDma(0,100, " Callibration process:", RGBVAL16(0x00,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); //JJ tft.drawTextNoDma(0,116, " Hit the red cross at each corner", RGBVAL16(0x00,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); //JJ tft.drawTextNoDma(0,0, "+", RGBVAL16(0xff,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); //JJ prev_zt = 1; //JJ } //JJ static void readCallibration(void) //JJ { //JJ FILE * file = fopen(CALIBRATION_FILE, "rb"); //JJ if (file) { //JJ fscanf(file,"%d %d %d %d\n",&calMinX,&calMinY,&calMaxX,&calMaxY); //JJ fclose(file); //JJ printf("Current callibration params: %d %d %d %d\n",calMinX,calMinY,calMaxX,calMaxY); //JJ } //JJ else { //JJ printf("Callibration read error\n"); //JJ } //JJ tft.callibrateTouch(calMinX,calMinY,calMaxX,calMaxY); //JJ } //JJ static void writeCallibration(void) //JJ { //JJ //JJ tft.callibrateTouch(calMinX,calMinY,calMaxX,calMaxY); //JJ FILE * file = fopen(CALIBRATION_FILE, "wb"); //JJ if (file) { //JJ fprintf(file,"%d %d %d %d\n",calMinX,calMinY,calMaxX,calMaxY); //JJ fclose(file); //JJ } //JJ else { //JJ printf("Callibration write error\n"); //JJ } //JJ } //JJ bool callibrationActive(void) //JJ { //JJ return (callibrationOn); //JJ } //JJ int handleCallibration(uint16_t bClick) { //JJ uint16_t xt=0; //JJ uint16_t yt=0; //JJ uint16_t zt=0; /*JJ if (tft.isTouching()) { if (prev_zt == 0) { prev_zt = 1; tft.readRaw(&xt,&yt,&zt); if (zt < 1000) { return 0; } switch (callibrationStep) { case 0: callibrationStep++; tft.drawTextNoDma(0,0, " ", RGBVAL16(0xff,0xff,0xff), RGBVAL16(0xff,0xff,0xff), true); tft.drawTextNoDma(ILI9341_TFTREALWIDTH-8,0, "+", RGBVAL16(0xff,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); calMinX += xt; calMinY += yt; break; case 1: callibrationStep++; tft.drawTextNoDma(ILI9341_TFTREALWIDTH-8,0, " ", RGBVAL16(0xff,0xff,0xff), RGBVAL16(0xff,0xff,0xff), true); tft.drawTextNoDma(ILI9341_TFTREALWIDTH-8,ILI9341_TFTREALHEIGHT-16, "+", RGBVAL16(0xff,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); calMaxX += xt; calMinY += yt; break; case 2: callibrationStep++; tft.drawTextNoDma(ILI9341_TFTREALWIDTH-8,ILI9341_TFTREALHEIGHT-16, " ", RGBVAL16(0xff,0xff,0xff), RGBVAL16(0xff,0xff,0xff), true); tft.drawTextNoDma(0,ILI9341_TFTREALHEIGHT-16, "+", RGBVAL16(0xff,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); calMaxX += xt; calMaxY += yt; break; case 3: tft.fillScreenNoDma(RGBVAL16(0xff,0xff,0xff)); tft.drawTextNoDma(0,100, " Callibration done!", RGBVAL16(0x00,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); tft.drawTextNoDma(0,116, " (Click center to exit)", RGBVAL16(0xff,0x00,0x00), RGBVAL16(0xff,0xff,0xff), true); callibrationStep++; calMinX += xt; calMaxY += yt; break; case 4: if ( (xt > (ILI9341_TFTREALWIDTH/4)) && (xt < (ILI9341_TFTREALWIDTH*3)/4) && (yt > (ILI9341_TFTREALHEIGHT/4)) && (yt < (ILI9341_TFTREALHEIGHT*3)/4) ) { calMinX /= 2; calMinY /= 2; calMaxX /= 2; calMaxY /= 2; writeCallibration(); toggleMenu(true); } else { callibrationInit(); } break; } vTaskDelay(100 / portTICK_PERIOD_MS); } } else { prev_zt = 0; } */ //JJ return 1; //JJ } //JJ bool menuActive(void) //JJ { //JJ return (menuOn); //JJ } //JJ int handleMenu(uint16_t bClick) //JJ { //JJ int action = ACTION_NONE; /*JJ char newpath[80]; strcpy(newpath, romspath); strcat(newpath, "/"); strcat(newpath, selection); struct stat st; bool newPathIsDir = false; if(stat(newpath,&st) == 0) if((st.st_mode & S_IFDIR) != 0) newPathIsDir = true; int rx=0,ry=0,rw=0,rh=0; char c = captureTouchZone(menutouchareas, menutouchactions, &rx,&ry,&rw,&rh); if ( ( (bClick & MASK_JOY2_BTN) || (bClick & MASK_KEY_USER1) ) && (newPathIsDir) ) { menuRedraw=true; strcpy(romspath,newpath); curFile = 0; nbFiles = readNbFiles(); } else if ( (c >= MKEY_L1) && (c <= MKEY_L9) ) { if ( (topFile+(int)c-1) <= (nbFiles-1) ) { curFile = topFile + (int)c -1; menuRedraw=true; //tft.drawRectNoDma( rx,ry,rw,rh, KEYBOARD_HIT_COLOR ); } } else if ( (bClick & MASK_JOY2_BTN) ) { menuRedraw=true; action = ACTION_RUNTFT; } else if (bClick & MASK_JOY2_UP) { if (curFile!=0) { menuRedraw=true; curFile--; } } else if ( (bClick & MASK_JOY2_RIGHT) || (c == MKEY_UP) ) { if ((curFile-9)>=0) { menuRedraw=true; curFile -= 9; } else if (curFile!=0) { menuRedraw=true; curFile--; } } else if (bClick & MASK_JOY2_DOWN) { if ((curFile<(nbFiles-1)) && (nbFiles)) { curFile++; menuRedraw=true; } } else if ( (bClick & MASK_JOY2_LEFT) || (c == MKEY_DOWN) ) { if ((curFile<(nbFiles-9)) && (nbFiles)) { curFile += 9; menuRedraw=true; } else if ((curFile<(nbFiles-1)) && (nbFiles)) { curFile++; menuRedraw=true; } } else if ( (bClick & MASK_KEY_USER1) || (c == MKEY_JOY) ) { emu_SwapJoysticks(0); menuRedraw=true; } if (menuRedraw && nbFiles) { int fileIndex = 0; DIR* dir = opendir(romspath); //JJ tft.drawRectNoDma(MENU_FILE_XOFFSET,MENU_FILE_YOFFSET, MENU_FILE_W, MENU_FILE_H, MENU_FILE_BGCOLOR); // if (curFile <= (MAX_MENULINES/2-1)) topFile=0; // else topFile=curFile-(MAX_MENULINES/2); if (curFile <= (MAX_MENULINES-1)) topFile=0; else topFile=curFile-(MAX_MENULINES/2); int i=0; while (i<MAX_MENULINES) { struct dirent* de = readdir(dir); if (!de) { break; } if ( (de->d_type == DT_REG) || ((de->d_type == DT_DIR) && (strcmp(de->d_name,".")) && (strcmp(de->d_name,"..")) ) ) { if (fileIndex >= topFile) { if ((i+topFile) < nbFiles ) { if ((i+topFile)==curFile) { tft.drawTextNoDma(MENU_FILE_XOFFSET,i*TEXT_HEIGHT+MENU_FILE_YOFFSET, de->d_name, RGBVAL16(0xff,0xff,0x00), RGBVAL16(0xff,0x00,0x00), true); strcpy(selection,de->d_name); } else { tft.drawTextNoDma(MENU_FILE_XOFFSET,i*TEXT_HEIGHT+MENU_FILE_YOFFSET, de->d_name, MENU_FILE_FGCOLOR, MENU_FILE_BGCOLOR, true); } } i++; } fileIndex++; } } closedir(dir); tft.drawSpriteNoDma(0,MENU_JOYS_YOFFSET,(uint16_t*)bmpjoy); tft.drawTextNoDma(48,MENU_JOYS_YOFFSET+8, (emu_SwapJoysticks(1)?(char*)"SWAP=1":(char*)"SWAP=0"), RGBVAL16(0x00,0xff,0xff), RGBVAL16(0xff,0x00,0x00), false); menuRedraw=false; } */ //JJ return (action); //JJ } //JJ char * menuSelection(void) //JJ { //JJ return (selection); //JJ } //JJ #ifdef HAS_I2CKBD //JJ #ifdef USE_WIRE //JJ #else //JJ static esp_err_t i2c_master_read_slave_reg(i2c_port_t i2c_num, uint8_t i2c_addr, uint8_t* data_rd, size_t size) //JJ { //JJ if (size == 0) { //JJ return ESP_OK; //JJ } //JJ i2c_cmd_handle_t cmd = i2c_cmd_link_create(); //JJ i2c_master_start(cmd); //JJ i2c_master_write_byte(cmd, ( i2c_addr << 1 ) | I2C_MASTER_READ, ACK_CHECK_EN); //JJ if (size > 1) { //JJ i2c_master_read(cmd, data_rd, size - 1, (i2c_ack_type_t)ACK_VAL); //JJ } //JJ i2c_master_read_byte(cmd, data_rd + size - 1, (i2c_ack_type_t)NACK_VAL); //JJ i2c_master_stop(cmd); //JJ esp_err_t ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS); //JJ i2c_cmd_link_delete(cmd); //JJ return ret; //JJ } //JJ #endif //JJ #endif //JJ void emu_init(void) //JJ { //JJ printf("emu_init\n"); //JJ fflush(stdout); /*JJ esp_err_t ret = 0; printf("mounting sd...\n"); sdmmc_host_t host = SDSPI_HOST_DEFAULT(); host.max_freq_khz = 10000; //host.slot = HSPI_HOST; sdspi_slot_config_t slot_config = SDSPI_SLOT_CONFIG_DEFAULT(); slot_config.gpio_miso = SPIN_NUM_MISO; slot_config.gpio_mosi = SPIN_NUM_MOSI; slot_config.gpio_sck = SPIN_NUM_CLK; slot_config.gpio_cs = SPIN_NUM_CS; slot_config.dma_channel = 2; esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = false, .max_files = 5, .allocation_unit_size = 16 * 1024 }; while((ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card)) != ESP_OK) { printf("retrying\n"); vTaskDelay(500 / portTICK_PERIOD_MS); } strcpy(romspath,"/sdcard/"); strcat(romspath,ROMSDIR); printf("dir is : %s\n",romspath); nbFiles = readNbFiles(); printf("SD initialized, files found: %d\n",nbFiles); tft.touchBegin(); //uint16_t xt=0; //uint16_t yt=0; //uint16_t zt=0; //tft.readRo(&xt,&yt,&zt); emu_InitJoysticks(); readCallibration(); if ((tft.isTouching()) || (emu_ReadKeys() & MASK_JOY2_BTN) ) { callibrationInit(); } else { toggleMenu(true); } #ifdef HAS_I2CKBD uint8_t msg[7]={0,0,0,0,0,0,0}; #ifdef USE_WIRE Wire.begin(I2C_SDA_IO, I2C_SCL_IO); Wire.requestFrom(8, 7, I2C_FREQ_HZ); // request 5 bytes from slave device #8 int i = 0; int hitindex=-1; while (Wire.available() && (i<7) ) { // slave may send less than requested uint8_t b = Wire.read(); // receive a byte if (b != 0xff) hitindex=i; msg[i++] = b; } #else int i2c_master_port = I2C_NUM_1; i2c_config_t conf; conf.mode = I2C_MODE_MASTER; conf.sda_io_num = I2C_SDA_IO; conf.sda_pullup_en = GPIO_PULLUP_ENABLE; conf.scl_io_num = I2C_SCL_IO; conf.scl_pullup_en = GPIO_PULLUP_ENABLE; conf.master.clk_speed = I2C_FREQ_HZ; i2c_param_config((i2c_port_t)i2c_master_port, &conf); if (i2c_driver_install((i2c_port_t)i2c_master_port, conf.mode,0, 0, 0) != ESP_OK) printf("I2C Failed initialized\n"); if (i2c_master_read_slave_reg( I2C_NUM_1, 8, &msg[0], 7 ) != ESP_OK) printf("I2C Failed \n"); #endif if ( (msg[0] == 0xff) && (msg[1] == 0xff) && (msg[2] == 0xff) && (msg[3] == 0xff) && (msg[4] == 0xff) && (msg[5] == 0xff) && (msg[6] == 0xff)) { i2cKeyboardPresent = true; printf("i2C keyboard found\n"); } #endif */ //JJ //JJ } void emu_printf(char * text) { #ifdef use_lib_log_serial Serial.printf("%s\n",text); //fflush(stdout); #endif } void emu_printi(int val) { #ifdef use_lib_log_serial Serial.printf("%d\n",val); #endif } //void emu_Init(char *ROM) //{ // autoload=1; // zx80=0; // ramsize=48; // // z81_Start(ROM); // // autoload=1; // zx80=0; // ramsize=48; // // z81_Init(); //} //********************************************* void emu_Init_Flash(unsigned char id) { autoload=1; zx80=0; ramsize=48; z81_Start_Flash(id); //autoload=1; autoload=1; zx80=0; ramsize=48; z81_Init_Flash(id); } //JJ void * emu_Malloc(int size) //JJ { //JJ void * retval = malloc(size); //JJ if (!retval) { //JJ printf("failled to allocate %d\n",size); //JJ } //JJ else { //JJ printf("could allocate %d\n",size); //JJ } //JJ //JJ return retval; //JJ } //JJ void emu_Free(void * pt) //JJ { //JJ free(pt); //JJ } static FILE * lastfileOpened; //int emu_FileOpen(char * filename) //{ // int retval = 0; // // char filepath[80]; ////JJ strcpy(filepath, romspath); ////JJ strcat(filepath, "/"); ////JJ strcat(filepath, filename); // //printf("FileOpen...%s\n",filepath); // // strcpy(filepath,filename); // #ifdef use_lib_log_serial // Serial.printf("romspath %s\n",romspath); // //fflush(stdout); // #endif // // lastfileOpened = fopen(filepath, "rb"); // if (lastfileOpened) { // retval = 1; // #ifdef use_lib_log_serial // Serial.printf("lastfileOpened\n"); // //fflush(stdout); // #endif // } // else { // #ifdef use_lib_log_serial // Serial.printf("FileOpen failed %s\n",filepath); // //fflush(stdout); // #endif // } // return (retval); //} int emu_FileRead(char * buf, int size) { int retval = fread(buf, 1, size, lastfileOpened); if (retval != size) { #ifdef use_lib_log_serial Serial.printf("FileRead failed\n"); //fflush(stdout); #endif } #ifdef use_lib_log_serial Serial.printf("FileRead size:%d %d\n",retval,size); //fflush(stdout); #endif return (retval); } unsigned char emu_FileGetc(void) { unsigned char c; int retval = fread(&c, 1, 1, lastfileOpened); if (retval != 1) { #ifdef use_lib_log_serial Serial.printf("emu_FileGetc failed\n"); #endif } return c; } void emu_FileClose(void) { fclose(lastfileOpened); } int emu_FileSize(char * filename) { int filesize=0; char filepath[80]; //JJ strcpy(filepath, romspath); //JJ strcat(filepath, "/"); strcat(filepath, filename); #ifdef use_lib_log_serial Serial.printf("FileSize...%s\n",filepath); //fflush(stdout); #endif FILE * file = fopen(filepath, "rb"); if (file) { fseek(file, 0L, SEEK_END); filesize = ftell(file); //fseek(file, 0L, SEEK_SET); #ifdef use_lib_log_serial Serial.printf("filesize is...%d\n",filesize); //fflush(stdout); #endif fclose(file); } return(filesize); } int emu_FileSeek(int seek) { fseek(lastfileOpened, seek, SEEK_SET); return (seek); } int emu_LoadFile(char * filename, char * buf, int size) { int filesize = 0; char filepath[80]; strcpy(filepath, romspath); strcat(filepath, "/"); strcat(filepath, filename); #ifdef use_lib_log_serial Serial.printf("LoadFile...%s\n",filepath); #endif filesize = emu_FileSize(filename); FILE * file = fopen(filepath, "rb"); if (file) { if (size >= filesize) { if (fread(buf, 1, filesize, file) != filesize) { #ifdef use_lib_log_serial Serial.printf("File read failed\n"); #endif } } fclose(file); } return(filesize); } int emu_LoadFileSeek(char * filename, char * buf, int size, int seek) { int filesize = 0; char filepath[80]; strcpy(filepath, romspath); strcat(filepath, "/"); strcat(filepath, filename); #ifdef use_lib_log_serial Serial.printf("LoadFileSeek...%d bytes at %d from %s\n",size,seek,filepath); #endif FILE * file = fopen(filepath, "rb"); if (file) { fseek(file, seek, SEEK_SET); if (fread(buf, size, 1, file) != size) { #ifdef use_lib_log_serial Serial.printf("File read failed\n"); #endif } fclose(file); } return(filesize); } //JJ static int keypadval=0; //JJ static bool joySwapped = false; //JJ static uint16_t bLastState; //JJ static int xRef; //JJ static int yRef; //JJ int emu_ReadAnalogJoyX(int min, int max) //JJ { //JJ int val; //adc1_get_raw((adc1_channel_t)PIN_JOY2_A1X); /*JJ adc2_get_raw((adc2_channel_t)PIN_JOY2_A1X, ADC_WIDTH_BIT_12,&val); //printf("refX:%d X:%d\n",xRef,val); val = val-xRef; //val = ((val*140)/100); if ( (val > -xRef/4) && (val < xRef/4) ) val = 0; #if INVX val = xRef-val; #else val = val+xRef; #endif */ //JJ return (val*(max-min))/(xRef*2); //JJ } //JJ int emu_ReadAnalogJoyY(int min, int max) //JJ { //JJ int val; //= adc1_get_raw((adc1_channel_t)PIN_JOY2_A2Y); /*JJ adc2_get_raw((adc2_channel_t)PIN_JOY2_A2Y, ADC_WIDTH_BIT_12,&val); //printf("refY:%d Y:%d\n",yRef,val); val = val-yRef; //val = ((val*120)/100); if ( (val > -yRef/4) && (val < yRef/4) ) val = 0; #if INVY val = yRef-val; #else val = val+yRef; #endif */ //JJ return (val*(max-min))/(yRef*2); //JJ } //JJ static uint16_t readAnalogJoystick(void) //JJ { //JJ uint16_t joysval = 0; /*JJ int xReading = emu_ReadAnalogJoyX(0,256); if (xReading > 128) joysval |= MASK_JOY2_LEFT; else if (xReading < 128) joysval |= MASK_JOY2_RIGHT; int yReading = emu_ReadAnalogJoyY(0,256); if (yReading < 128) joysval |= MASK_JOY2_UP; else if (yReading > 128) joysval |= MASK_JOY2_DOWN; joysval |= ((gpio_get_level((gpio_num_t)PIN_JOY2_BTN) == 1) ? 0 : MASK_JOY2_BTN); */ //JJ return (joysval); //JJ } //JJ int emu_SwapJoysticks(int statusOnly) { //JJ if (!statusOnly) { //JJ if (joySwapped) { //JJ joySwapped = false; //JJ } //JJ else { //JJ joySwapped = true; //JJ } //JJ } //JJ return(joySwapped?1:0); //JJ } //JJ int emu_GetPad(void) //JJ { //JJ return(keypadval|((joySwapped?1:0)<<7)); //JJ } //JJ int emu_ReadKeys(void) //JJ { //JJ uint16_t retval; /*JJ uint16_t j1 = readAnalogJoystick(); uint16_t j2 = 0; if (joySwapped) { retval = ((j1 << 8) | j2); } else { retval = ((j2 << 8) | j1); } if (gpio_get_level((gpio_num_t)PIN_KEY_USER1) == 0 ) retval |= MASK_KEY_USER1; if (gpio_get_level((gpio_num_t)PIN_KEY_USER2) == 0 ) retval |= MASK_KEY_USER2; if (gpio_get_level((gpio_num_t)PIN_KEY_USER3) == 0 ) retval |= MASK_KEY_USER3; if (gpio_get_level((gpio_num_t)PIN_KEY_USER4) == 0 ) retval |= MASK_KEY_USER4; //printf("%d\n",retval); */ //JJ return (retval); //JJ } //JJ unsigned short emu_DebounceLocalKeys(void) //JJ { //JJ uint16_t bCurState = emu_ReadKeys(); //JJ uint16_t bClick = bCurState & ~bLastState; //JJ bLastState = bCurState; //JJ //JJ return (bClick); //JJ } //JJ int emu_ReadI2CKeyboard(void) { //JJ int retval=0; /*JJ #ifdef HAS_I2CKBD if (i2cKeyboardPresent) { uint8_t msg[7]; #ifdef USE_WIRE Wire.requestFrom(8, 7, I2C_FREQ_HZ); // request 5 bytes from slave device #8 int i = 0; int hitindex=-1; while (Wire.available() && (i<7) ) { // slave may send less than requested uint8_t b = Wire.read(); // receive a byte if (b != 0xff) hitindex=i; msg[i++] = b; } #else if (i2c_master_read_slave_reg( I2C_NUM_1, 8, &msg[0], 7 ) != ESP_OK) printf("I2C Failed \n"); int hitindex=-1; int i = 0; while (i<7) { if (msg[i] != 0xff) hitindex=i; i++; } #endif //printf("I2C 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n", // msg[0],msg[1],msg[2],msg[3],msg[4],msg[5],msg[6]); if ((hitindex >=0 ) && (hitindex <=6 )) { unsigned short match = ((~msg[hitindex])&0x00FF) | (hitindex<<8); for (i=0; i<sizeof(i2ckeys); i++) { if (match == i2ckeys[i]) { //printf("I2C %d\n",keys[i]); return (keys[i]); } } } } #endif */ //JJ return(retval); //JJ} //JJ void emu_InitJoysticks(void) { /*JJ gpio_set_direction((gpio_num_t)PIN_JOY2_BTN, GPIO_MODE_INPUT); gpio_set_pull_mode((gpio_num_t)PIN_JOY2_BTN, GPIO_PULLUP_ONLY); gpio_set_direction((gpio_num_t)PIN_KEY_USER1, GPIO_MODE_INPUT); gpio_set_pull_mode((gpio_num_t)PIN_KEY_USER1, GPIO_PULLUP_ONLY); gpio_set_direction((gpio_num_t)PIN_KEY_USER2, GPIO_MODE_INPUT); gpio_set_pull_mode((gpio_num_t)PIN_KEY_USER2, GPIO_PULLUP_ONLY); gpio_set_direction((gpio_num_t)PIN_KEY_USER3, GPIO_MODE_INPUT); gpio_set_pull_mode((gpio_num_t)PIN_KEY_USER3, GPIO_PULLUP_ONLY); gpio_set_direction((gpio_num_t)PIN_KEY_USER4, GPIO_MODE_INPUT); gpio_set_pull_mode((gpio_num_t)PIN_KEY_USER4, GPIO_PULLUP_ONLY); //adc1_config_channel_atten((adc1_channel_t)PIN_JOY2_A1X,ADC_ATTEN_DB_11); //adc1_config_channel_atten((adc1_channel_t)PIN_JOY2_A2Y,ADC_ATTEN_DB_11); adc2_config_channel_atten((adc2_channel_t)PIN_JOY2_A1X,ADC_ATTEN_DB_11); adc2_config_channel_atten((adc2_channel_t)PIN_JOY2_A2Y,ADC_ATTEN_DB_11); xRef=0; yRef=0; for (int i=0; i<10; i++) { int val; adc2_get_raw((adc2_channel_t)PIN_JOY2_A1X, ADC_WIDTH_BIT_12, &val); //val = adc1_get_raw((adc1_channel_t)PIN_JOY2_A1X); xRef += val; adc2_get_raw((adc2_channel_t)PIN_JOY2_A2Y,ADC_WIDTH_BIT_12, &val); //val = adc1_get_raw((adc1_channel_t)PIN_JOY2_A2Y); yRef += val; vTaskDelay(20 / portTICK_PERIOD_MS); } xRef /= 10; yRef /= 10; printf("refs: %d %d\n",xRef,yRef); */ //JJ } //JJ static bool vkbKeepOn = false; //JJ static bool vkbActive = false; //JJ static bool vkeyRefresh=false; //JJ static bool exitVkbd = false; //JJ static uint8_t keyPressCount=0; //JJ bool virtualkeyboardIsActive(void) { //JJ return (vkbActive); //JJ} //JJ void toggleVirtualkeyboard(bool keepOn) { /*JJ if (keepOn) { tft.drawSpriteNoDma(0,0,(uint16_t*)logo); //prev_zt = 0; vkbKeepOn = true; vkbActive = true; exitVkbd = false; } else { vkbKeepOn = false; if ( (vkbActive) ) { tft.fillScreenNoDma( RGBVAL16(0x00,0x00,0x00) ); #ifdef DMA_FULLgpio_get_level tft.begin(); tft.refresh(); #endif //prev_zt = 0; vkbActive = false; exitVkbd = false; } else { #ifdef DMA_FULL tft.stop(); tft.begin(); tft.start(); #endif tft.drawSpriteNoDma(0,0,(uint16_t*)logo); //prev_zt = 0; vkbActive = true; exitVkbd = false; } } */ //JJ } //JJ void handleVirtualkeyboard() { //JJ int rx=0,ry=0,rw=0,rh=0; /*JJ if (keyPressCount == 0) { keypadval = 0; } else { keyPressCount--; } if ( (!virtualkeyboardIsActive()) && (tft.isTouching()) && (!keyPressCount) ) { toggleVirtualkeyboard(false); return; } if ( ( (vkbKeepOn) || (virtualkeyboardIsActive()) ) ) { char c = captureTouchZone(keysw, keys, &rx,&ry,&rw,&rh); if (c) { tft.drawRectNoDma( rx,ry,rw,rh, KEYBOARD_HIT_COLOR ); if ( (c >=1) && (c <= ACTION_MAXKBDVAL) ) { keypadval = c; keyPressCount = 10; vTaskDelay(50 / portTICK_PERIOD_MS); vkeyRefresh = true; exitVkbd = true; } else if (c == ACTION_EXITKBD) { vkeyRefresh = true; exitVkbd = true; } } } if (vkeyRefresh) { vkeyRefresh = false; tft.drawSpriteNoDma(0,0,(uint16_t*)logo, rx, ry, rw, rh); } if ( (exitVkbd) && (vkbActive) ) { if (!vkbKeepOn) { toggleVirtualkeyboard(false); } else { toggleVirtualkeyboard(true); } } */ //JJ } //JJ int emu_setKeymap(int index) { //JJ if (index) { //JJ //logo = logozx81kbd; //JJ keysw = keyswzx81; //JJ } //JJ else { //JJ //logo = logozx80kbd; //JJ keysw = keyswzx80; //JJ } //JJ return 0; //JJ } //JJ static unsigned short palette16[PALETTE_SIZE]; static int fskip=0; //JJ void emu_SetPaletteEntry(unsigned char r, unsigned char g, unsigned char b, int index) //JJ{ /*JJ if (index<PALETTE_SIZE) { //printf("%d: %d %d %d\n", index, r,g,b); palette16[index] = RGBVAL16(r,g,b); } */ //JJ} void emu_DrawVsync(void) { //printf("sync %d\n",skip); //printf("vsync\n"); //fflush(stdout); fskip += 1; fskip &= VID_FRAME_SKIP; } //*************************************************************************** void jj_fast_putpixel(short int x,short int y,unsigned char c) { //if ((x<0)||(y<0)||(x >= 320) || (y >= 200)) //{ // //printf("Clip x:%d y:%d\n",x,y); // //fflush(stdout); // return; //} gb_buffer_vga[y][x^2]= gb_color_vga[c]; //Uint8* p = (Uint8*)screen->pixels + (y * screen->pitch) + x; //*p= c; } //JJ int fb_width = 320; //JJ int fb_height = 240; short int fb_width = 320; short int fb_height = 200; //JJ int fb_stride = fb_width+16; //unsigned char framebuffer[100000]; //******************************************************************* //void jj_writeLine(int width, int height, int y, unsigned char *buf) { // if ( (height<fb_height) && (height > 2) ) y += (fb_height-height)/2; // uint8_t * dst=&framebuffer[y*fb_stride]; // if (width > fb_width) { // int step = ((width << 8)/fb_width); // int pos = 0; // for (int i=0; i<fb_width; i++) // { // *dst++ = buf[pos >> 8]; // pos +=step; // } // } // else if ((width*2) == fb_width) { // for (int i=0; i<width; i++) // { // *dst++=*buf; // *dst++=*buf++; // } // } // else { // if (width <= fb_width) { // dst += (fb_width-width)/2; // } // for (int i=0; i<width; i++) // { // *dst++=*buf++; // } // } //} //******************************************************************* void jj_direct_writeLine(int width, int height, int y, unsigned char *buf) { int auxY,auxX; unsigned char aColor; if ( (height<fb_height) && (height > 2) ) y += (fb_height-height)/2; //uint8_t * dst=&framebuffer[y*fb_stride]; auxY= y; auxX= 0; if (width > fb_width) { int step = ((width << 8)/fb_width); int pos = 0; for (int i=0; i<fb_width; i++) { //*dst++ = buf[pos >> 8]; aColor= buf[pos >> 8]; if (gb_invert_color == 1){ aColor= (~aColor)&0x01; } //jj_fast_putpixel(auxX,auxY,(aColor==0)?0:7); gb_buffer_vga[auxY][auxX^2]= gb_color_vga[((aColor==0)?0:7)]; auxX++; pos +=step; } } else if ((width*2) == fb_width) { for (int i=0; i<width; i++) { //*dst++=*buf; //*dst++=*buf++; aColor= *buf; if (gb_invert_color == 1){ aColor= (~aColor)&0x01; } //jj_fast_putpixel(auxX,auxY,(aColor==0)?0:7); gb_buffer_vga[auxY][auxX^2]= gb_color_vga[((aColor==0)?0:7)]; auxX++; aColor= *buf++; //jj_fast_putpixel(auxX,auxY,(aColor==0)?0:7); if (gb_invert_color == 1){ aColor= (~aColor)&0x01; } gb_buffer_vga[auxY][auxX^2]= gb_color_vga[((aColor==0)?0:7)]; auxX++; } } else { if (width <= fb_width) { //dst += (fb_width-width)/2; auxX += (fb_width-width)/2; } for (int i=0; i<width; i++) { //*dst++=*buf++; aColor= *buf++; if (gb_invert_color == 1){ aColor= (~aColor)&0x01; } //jj_fast_putpixel(auxX,auxY,(aColor==0)?0:7); gb_buffer_vga[auxY][auxX^2]= gb_color_vga[((aColor==0)?0:7)]; auxX++; } } } //************************************************************************* void emu_DrawLine(unsigned char * VBuf, int width, int height, int line) { /*JJ if (fskip==0) { tft.writeLine(width,height,line, VBuf, palette16); } */ if (fskip==0) { //jj_writeLine(width,height,line,VBuf); jj_direct_writeLine(width,height,line,VBuf); } } //JJ void emu_DrawScreen(unsigned char * VBuf, int width, int height, int stride) //JJ { /*JJ if (fskip==0) { tft.writeScreen(width,height-TFT_VBUFFER_YCROP,stride, VBuf+(TFT_VBUFFER_YCROP/2)*stride, palette16); } */ //JJ } //JJ int emu_FrameSkip(void) //JJ{ //JJ return fskip; //JJ} //JJ void * emu_LineBuffer(int line) //JJ { //JJ /*JJ //JJ return (void*)tft.getLineBuffer(line); //JJ */ //JJ return NULL; //JJ } //JJ #ifdef HAS_SND //JJ #include "AudioPlaySystem.h" //JJ extern AudioPlaySystem audio; //JJ void emu_sndInit() { //JJ } //JJ void emu_sndPlaySound(int chan, int volume, int freq) //JJ { /*JJ if (chan < 6) { audio.sound(chan, freq, volume); } */ //JJ } //JJ void emu_sndPlayBuzz(int size, int val) { //JJ //mymixer.buzz(size,val); //JJ } //JJ #endif
26.154762
161
0.563325
rpsubc8
6fb72a19f553e3404065084b840218d3b4ce796d
3,549
cpp
C++
src/Collision.cpp
AnyTimeTraveler/CppRobots
c7d2df9ac8272136f9cc958e0c874e58cfbca585
[ "MIT" ]
4
2016-06-23T08:46:43.000Z
2020-05-05T17:28:29.000Z
src/Collision.cpp
AnyTimeTraveler/CppRobots
c7d2df9ac8272136f9cc958e0c874e58cfbca585
[ "MIT" ]
2
2015-09-29T09:24:39.000Z
2015-12-09T15:10:00.000Z
src/Collision.cpp
AnyTimeTraveler/CppRobots
c7d2df9ac8272136f9cc958e0c874e58cfbca585
[ "MIT" ]
2
2019-05-21T18:56:57.000Z
2019-06-06T11:12:18.000Z
/** * \copyright Copyright 2016 Hochschule Emden/Leer. This project is released * under * the MIT License, see the file LICENSE.md for rights and limitations. * \file Collision.cpp * \author Jan-Niklas Braak */ #include "Collision.hpp" bool Collision::Projection::overlap(const Projection &proj2) { /* There are two cases where the projections don't overlarp: 1. The first projection is completely to the left of the second 2. The first projection is completely to the right of the second If neither is true the Projections overlap. In that way projections are similar to ranges. */ return !(proj2.min > max || min > proj2.max); } Collision::Collision() : collision(false) {} Collision::Projection Collision::project(const Rectangle &rect, const Vector_d &axis) { auto vertices = rect.vertices(); double min = axis.dot(vertices[0]); double max = min; for (const auto &vertex : vertices) { // The projection of a vertix on an axis is the dot product of the two. double p = axis.dot(vertex); // remember the minimal and maximal projection. if (p < min) { min = p; } else if (p > max) { max = p; } } return {min, max}; } std::vector<Vector_d> Collision::getAxes(const Rectangle &rect) { // the first axis is a unit vector in the direction of the Rectangle const auto axis0 = Vector_d::polar(rect.getRotation()); // the second axis is perpendicular to the first const auto axis1 = axis0.perp(); // the other two axes are parallel to the first two, so we don't need them. return {axis0, axis1}; } Collision::Collision(const Rectangle &rect1, const Rectangle &rect2) { // NOTE: we could calculate the MTV by finding the axis with the bigest // overlap, and the coresponding overlap amount. /* NOTE: For other convex polygonal shapes this function is identical if * getAxes() and project() is defined for them. This could be unified by * having a "Collider" parent class. Collision with a circle is a special * case. collision of two circles is trivial. Concave polygons have to be * seperated into convex shapes. */ collision = true; const auto axes1 = getAxes(rect1); const auto axes2 = getAxes(rect2); /* This collision test uses the separating axis theorem (SAT). In short the * SAT says that if two _convex_ objects don't overlap there is a axis * seperating them. That means if we find an axis that seperates the * rectangles we have no collision. On the other hand we have to test all * possible axes to verify a collision. Fortunatly the axes we only have to * test the axes that are perpendicular to one of the sides of the object. */ for (const auto &axis : axes1) { // Project both Rectangles onto the axis Projection p1 = project(rect1, axis); Projection p2 = project(rect2, axis); if (!p1.overlap(p2)) { // if the Projections don't overlap we have a seperating axis, the // Rectangles don't collide. collision = false; return; } } for (const auto &axis : axes2) { // Project both Rectangles onto the axis Projection p1 = project(rect1, axis); Projection p2 = project(rect2, axis); if (!p1.overlap(p2)) { // if the Projections don't overlap we have a seperating axis, the // Rectangles don't collide. collision = false; return; } } // No seperating axis was found, the Rectangles collide. } Collision::operator bool() const { return collision; }
35.49
78
0.677937
AnyTimeTraveler
6fb8fa3a7b09d502327e176a9a17a92c4e48fbd4
3,186
cpp
C++
source/textelement.cpp
yurablok/lunasvg
ec5373150f01b059d7c65956b1c52a95bc8e00c3
[ "MIT" ]
null
null
null
source/textelement.cpp
yurablok/lunasvg
ec5373150f01b059d7c65956b1c52a95bc8e00c3
[ "MIT" ]
null
null
null
source/textelement.cpp
yurablok/lunasvg
ec5373150f01b059d7c65956b1c52a95bc8e00c3
[ "MIT" ]
1
2021-09-24T15:39:59.000Z
2021-09-24T15:39:59.000Z
#include "textelement.h" #include "layoutcontext.h" #include "parser.h" namespace lunasvg { TextElement::TextElement() : StyledElement(ElementId::Text) { } void TextElement::layout(LayoutContext* context, LayoutContainer* current) const { if (isDisplayNone()) return; //auto shape = std::make_unique<LayoutShape>(); //shape->path = std::move(path); //shape->transform = transform(); //shape->fillData = context->fillData(this); //shape->strokeData = context->strokeData(this); //shape->markerData = context->markerData(this, shape->path); //shape->visibility = visibility(); //shape->clipRule = clip_rule(); //shape->masker = context->getMasker(mask()); //shape->clipper = context->getClipper(clip_path()); //current->addChild(std::move(shape)); auto text = std::make_unique<LayoutText>(); text->pos_px.x = Parser::parseLength( get(PropertyId::X), AllowNegativeLengths, Length::Zero ).value(100.0); text->pos_px.y = Parser::parseLength( get(PropertyId::Y), AllowNegativeLengths, Length::Zero ).value(100.0); text->pos_px.y -= text->size_px; text->family = get(PropertyId::Font_Family); text->color = Parser::parseColor(get(PropertyId::Fill), this, Color::Black); text->size_px = Parser::parseLength( get(PropertyId::Font_Size), ForbidNegativeLengths, Length::Zero ).value(100.0); auto sizeAdjust = Parser::parseLength( get(PropertyId::Font_Size_Adjust), ForbidNegativeLengths, Length::Zero ); auto stretch = get(PropertyId::Font_Stretch); auto style = get(PropertyId::Font_Style); if (style == "normal") { text->style = FontStyle::Normal; } else if (style == "italic") { text->style = FontStyle::Italic; } else if (style == "oblique") { text->style = FontStyle::Oblique; } else { assert(style.empty()); } auto variant = get(PropertyId::Font_Variant); auto weight = get(PropertyId::Font_Weight); if (weight == "normal") { text->weight = FontWeight::Normal; } else if (weight == "bold") { text->weight = FontWeight::Bold; } else if (weight == "bolder") { text->weight = FontWeight::Bolder; } else if (weight == "lighter") { text->weight = FontWeight::Lighter; } else if (!weight.empty()) { auto w = Parser::parseLength(weight, ForbidNegativeLengths, Length::Zero); if (w.isValid()) { // uint8_t overflow not checked text->weight = static_cast<FontWeight>(w.value(100.0)); } } text->transform = Parser::parseTransform(get(PropertyId::Transform)); auto prText = properties.get(PropertyId::Text); if (prText != nullptr) { // move or copy? text->textBuffer = std::move(prText->value); text->text.buffer = &text->textBuffer; text->text.size = static_cast<uint32_t>(text->textBuffer.size()); } layoutChildren(context, text.get()); current->addChild(std::move(text)); } std::unique_ptr<Node> TextElement::clone() const { return cloneElement<TextElement>(); } } // namespace lunasvg
30.634615
82
0.624922
yurablok
6fd4061dd4640b8e989bef6f1a2e0e27a5296792
5,312
cpp
C++
fileclient/src/user_tasks.cpp
agandzyuk/fmultitransfer
0b92cee70f7831fc8598fb3d5cf816bcece6261f
[ "MIT" ]
null
null
null
fileclient/src/user_tasks.cpp
agandzyuk/fmultitransfer
0b92cee70f7831fc8598fb3d5cf816bcece6261f
[ "MIT" ]
null
null
null
fileclient/src/user_tasks.cpp
agandzyuk/fmultitransfer
0b92cee70f7831fc8598fb3d5cf816bcece6261f
[ "MIT" ]
null
null
null
#include "user_tasks.h" #include "notify_base.h" using namespace std; /****************************************************************/ ConnectionTask::ConnectionTask(const std::string& name, const IPAddress& addr, u16 port, TaskFactory* factory, NotifyBase* notifyMgr, TCPSockClient* connection) : Task(name), addr_(addr), port_(port), factory_(factory), notifyMgr_(notifyMgr) { if( connection ) connection_.reset(connection); } ConnectionTask::~ConnectionTask() { } void ConnectionTask::run() { MGuard g( lock_ ); std::string host_name = addr_.getHostAddress(); TCPSockClient* s = connection_.get(); if( s && !s->is_open() ) // reconnecting { try { connection_->connect(addr_, port_); } catch(const Exception& ex) { notifyMgr_->warning(get_name() + " - WARNING: " + ex.what()); notifyMgr_->debug(get_name() + " - WARNING: " + ex.what()); } factory_->destroy_task(this); } else if( s == NULL ) // first connect { std::string except_txt; notifyMgr_->notify("Connecting to FileServer...\n"); try { s = new TCPSockClient(addr_, port_); } catch( const Exception& ex ) { except_txt = ex.what(); } if( s == NULL ) { string msg = get_name() + " - WARNING: Failed to connect to FileServer on " + host_name + ":" + tostring(port_) + " - " + except_txt; notifyMgr_->warning( msg ); notifyMgr_->debug( msg ); return; } } connection_.reset(s); connection_->add_ref(); factory_->newlink_task(connect_TaskSpec,s); g.release(); string msg = get_name() + " - NOTE: We have connection #" + tostring(s->get_fd()) + " with FileServer on " + host_name + ":" + tostring(port_); notifyMgr_->notify(msg); notifyMgr_->debug(msg); // set connection alive factory_->destroy_task(this); } /**************************************************************/ SendingTask::SendingTask( const std::string& name, File* sendingFile, TaskFactory* factory, NotifyBase* notifyMgr, TCPSockClient* connection, u32 packages_size) : Task(name), sendingFile_(sendingFile), factory_(factory), notifyMgr_(notifyMgr), shutdown_(false), packages_size_(packages_size) { connection_.reset( connection ); } SendingTask::~SendingTask() { MGuard g( lock_ ); shutdown_ = true; } void SendingTask::run() { MGuard g( lock_ ); if( connection_.get() && !connection_->is_open() ) { notifyMgr_->debug( get_name() + " - WARNING: session was closed. Kill me, please!" ); notifyMgr_->warning( get_name() + " - WARNING: session was closed. Kill me, please!" ); factory_->destroy_task( this ); return; } u8* buf = NULL; i32 read = 0; string tag_inside; static bool filePartSent = false; // sending last tag if( sendingFile_->eof() && filePartSent ) { filePartSent = false; tag_inside = TAG_FINISH_CONTENT; connection_->send(tag_inside.c_str(), tag_inside.length()+1); string msg = get_name() + " - INFO: \"" + sendingFile_->path() + "\" is sucesfully sent to host " + connection_->getTarget(); notifyMgr_->notify(msg); // stop the sending tasks chain return; } // sending first tag if( !filePartSent && (filePartSent = true)) { string newfile = sendingFile_->path(); tag_inside = TAG_START_CONTENT; tag_inside += newfile + "/>"; tag_inside += TAG_CONTENT_SIZE; tag_inside += tostring(sendingFile_->size()) + "/>"; } // sending on any case buf = new u8[packages_size_+tag_inside.length()+1]; if( !tag_inside.empty() ) memcpy(buf, tag_inside.c_str(), tag_inside.length() ); try { read = fread(buf+tag_inside.length(), 1, packages_size_, sendingFile_->handle()); } catch(...){} g.release(); string exc; if( read > 0 ) { try { i32 write = read + tag_inside.length(); read = connection_->send(buf, write); if( read > 0 ){ notifyMgr_->debug( get_name() + " - NOTE: sent " + tostring(read) + " bytes."); notifyMgr_->notify( get_name() + " - NOTE: sent " + tostring(read) + " bytes."); } else if( write > 0 ) sendingFile_->seek( -write, SEEK_CUR ); } catch(const Exception& ex) { exc = get_name() + " - ERROR: " + ex.what(); } } if( buf ) delete[] buf; if( exc.empty() ) { // activate the next sending tasks Task* task = factory_->create_task(send_TaskSpec, connection_.get()); if( task == NULL ) connection_.abandon(); } else { notifyMgr_->debug( exc ); notifyMgr_->error( exc ); } }
28.55914
113
0.519955
agandzyuk
6fde0264c55c10befe05b09d8f6dd6ae2261f380
4,527
cpp
C++
src/core/Palette.cpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
60
2019-11-30T00:30:33.000Z
2022-03-26T03:44:53.000Z
src/core/Palette.cpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
8
2019-12-16T07:55:54.000Z
2022-03-09T21:01:02.000Z
src/core/Palette.cpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
3
2021-08-06T07:17:15.000Z
2022-03-08T03:39:06.000Z
#include "core/Palette.hpp" #include "core/config/keys.hpp" #include <QtDebug> Palette::Palette() : mData{ QColor( 24, 24, 24), // ColorBackground QColor( 32, 32, 32), // ColorBackgroundHighlight1 QColor( 48, 48, 48), // ColorBackgroundHighlight2 QColor(192, 192, 192), // ColorForeground QColor(240, 240, 240), // ColorForegroundHighlight1 QColor(255, 255, 255), // ColorForegroundHighlight2 QColor( 32, 48, 128), // ColorRow QColor(128, 48, 48), // ColorRowEdit QColor(128, 32, 128), // ColorRowPlayer QColor(128, 128, 255), // ColorEffectType QColor(128, 255, 128), // ColorInstrument QColor( 69, 69, 80), // ColorSelection QColor(192, 192, 192), // ColorCursor QColor( 64, 64, 64), // ColorLine QColor( 48, 48, 48), // ColorHeaderBackground1 QColor( 40, 40, 40), // ColorHeaderBackground2 QColor(240, 240, 240), // ColorHeaderForeground1 QColor(192, 192, 192), // ColorHeaderForeground2 QColor(153, 229, 80), // ColorHeaderEnabled QColor(217, 87, 99), // ColorHeaderDisabled QColor( 0, 0, 0), // ColorGraphBackground QColor( 32, 32, 32), // ColorGraphAlternate QColor( 64, 64, 64), // ColorGraphLines QColor(224, 224, 224), // ColorGraphSamples QColor( 0, 0, 0), // ColorScopeBackground QColor( 0, 255, 68), // ColorScopeLine }, mDefault(true) { } QColor const& Palette::operator[](Color color) const { return mData[color]; } bool Palette::isDefault() const { return mDefault; } void Palette::setColor(Color color, QColor value) { mData[color] = value; mDefault = false; } // // QString interning for QSettings, QMetaEnum was not used because: // * requires QString conversion // * enum names are not human friendly (background vs ColorBackground) // * requires MOC // // downside to this is that we need a matching key string for each Color enum // static std::array const ColorKeys = { QStringLiteral("background"), QStringLiteral("backgroundHighlight1"), QStringLiteral("backgroundHighlight2"), QStringLiteral("foreground"), QStringLiteral("foregroundHighlight1"), QStringLiteral("foregroundHighlight2"), QStringLiteral("row"), QStringLiteral("rowEdit"), QStringLiteral("rowPlayer"), QStringLiteral("effectType"), QStringLiteral("instrument"), QStringLiteral("selection"), QStringLiteral("cursor"), QStringLiteral("line"), QStringLiteral("headerBackground1"), QStringLiteral("headerBackground2"), QStringLiteral("headerForeground1"), QStringLiteral("headerForeground2"), QStringLiteral("headerEnabled"), QStringLiteral("headerDisabled"), QStringLiteral("graphBackground"), QStringLiteral("graphAlternate"), QStringLiteral("graphLines"), QStringLiteral("graphSamples"), QStringLiteral("scopeBackground"), QStringLiteral("scopeLine") }; // If this fails you forgot to remove/add a key to the array static_assert(ColorKeys.size() == Palette::ColorCount, "ColorKeys.size() does not match enum count!"); void Palette::readSettings(QSettings &settings) { // QSettings has no way of checking if a group exists, so we have to read // all color keys even if the user is using the default :( settings.beginGroup(Keys::Palette); for (int i = 0; i < ColorCount; ++i) { if (settings.contains(ColorKeys[i])) { QColor color(settings.value(ColorKeys[i]).toString()); if (color.isValid()) { color.setAlpha(255); // sanitize setColor((Color)i, color); } } } settings.endGroup(); } void Palette::writeSettings(QSettings &settings, bool saveOnDefault) const { settings.beginGroup(Keys::Palette); settings.remove(QString()); // remove everything if (saveOnDefault || !mDefault) { for (int i = 0; i < ColorCount; ++i) { QString color = mData[i].name(); settings.setValue(ColorKeys[i], color); } } settings.endGroup(); } bool operator==(Palette const& lhs, Palette const& rhs) noexcept { if (lhs.mDefault == rhs.mDefault) { if (lhs.mDefault) { return true; } else { return lhs.mData == rhs.mData; } } return false; } bool operator!=(Palette const& lhs, Palette const& rhs) noexcept { return !(lhs == rhs); }
31.006849
102
0.632869
stoneface86
6fdfc6038c8ce21c78367295e8ae109ea2bd203d
7,393
hpp
C++
dart/utils/detail/XmlHelpers-impl.hpp
ibrahiminfinite/dart
495c82120c836005f2d136d4a50c8cc997fb879b
[ "BSD-2-Clause" ]
null
null
null
dart/utils/detail/XmlHelpers-impl.hpp
ibrahiminfinite/dart
495c82120c836005f2d136d4a50c8cc997fb879b
[ "BSD-2-Clause" ]
null
null
null
dart/utils/detail/XmlHelpers-impl.hpp
ibrahiminfinite/dart
495c82120c836005f2d136d4a50c8cc997fb879b
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2011-2022, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DART_UTILS_DETAIL_XMLHELPERS_IMPL_HPP_ #define DART_UTILS_DETAIL_XMLHELPERS_IMPL_HPP_ #include "dart/common/String.hpp" #include "dart/utils/XmlHelpers.hpp" namespace dart::utils { //============================================================================== template <typename S, int N> std::string toString(const Eigen::Matrix<S, N, 1>& v) { std::stringstream ss; ss << v.transpose(); return ss.str(); } //============================================================================== template <typename S> std::string toString( const Eigen::Transform<S, 3, Eigen::Isometry>& v, const std::string& rotationType) { Eigen::Matrix<S, 3, 1> angles; if (rotationType == "intrinsic") { angles = math::matrixToEulerXYZ(v.rotation()); } else if (rotationType == "extrinsic") { angles = math::matrixToEulerZYX(v.rotation()).reverse(); } else { DART_ERROR( "Unsupported rotation type [{}]. Assuming intrinsic.", rotationType); angles = math::matrixToEulerXYZ(v.rotation()); } std::stringstream ss; ss.precision(6); ss << v.translation().transpose() << " "; ss << angles; return ss.str(); } //============================================================================== template <std::size_t N> Eigen::Matrix<double, N, 1> toVectorNd(const std::string& str) { const std::vector<std::string> pieces = common::split(common::trim(str)); const std::size_t sizeToRead = std::min(N, pieces.size()); if (pieces.size() < N) { dterr << "Failed to read a vector because the dimension '" << pieces.size() << "' is less than the expectation '" << N << "'.\n"; } else if (pieces.size() > N) { dterr << "Failed to read a vector because the dimension '" << pieces.size() << "' is greater than the expectation '" << N << "'.\n"; } Eigen::Matrix<double, N, 1> ret = Eigen::Matrix<double, N, 1>::Zero(); for (std::size_t i = 0; i < sizeToRead; ++i) { if (pieces[i] != "") { try { ret[i] = toDouble(pieces[i]); } catch (std::exception& e) { dterr << "value [" << pieces[i] << "] is not a valid double for Eigen::Vector" << N << "d[" << i << "]: " << e.what() << "\n"; } } } return ret; } //============================================================================== template <std::size_t N> Eigen::Matrix<double, N, 1> getAttributeVectorNd( const tinyxml2::XMLElement* element, const std::string& attributeName) { const std::string val = getAttributeString(element, attributeName); return toVectorNd<N>(val); } //============================================================================== template <typename ElementType> TemplatedElementEnumerator<ElementType>::TemplatedElementEnumerator( ElementPtr parentElement, const std::string& childElementName) : mParentElement(parentElement), mChildElementName(childElementName), mCurrentElement(nullptr) { // Do nothing } //============================================================================== template <typename ElementType> TemplatedElementEnumerator<ElementType>::~TemplatedElementEnumerator() { // Do nothing } //============================================================================== template <typename ElementType> bool TemplatedElementEnumerator<ElementType>::next() { if (!mParentElement) return false; if (mCurrentElement) { mCurrentElement = mCurrentElement->NextSiblingElement(mChildElementName.c_str()); } else { mCurrentElement = mParentElement->FirstChildElement(mChildElementName.c_str()); } if (!valid()) mParentElement = nullptr; return valid(); } //============================================================================== template <typename ElementType> typename TemplatedElementEnumerator<ElementType>::ElementPtr TemplatedElementEnumerator<ElementType>::get() const { return mCurrentElement; } //============================================================================== template <typename ElementType> typename TemplatedElementEnumerator<ElementType>::ElementPtr TemplatedElementEnumerator<ElementType>::operator->() const { return mCurrentElement; } //============================================================================== template <typename ElementType> typename TemplatedElementEnumerator<ElementType>::ElementRef TemplatedElementEnumerator<ElementType>::operator*() const { return *mCurrentElement; } //============================================================================== template <typename ElementType> bool TemplatedElementEnumerator<ElementType>::operator==( const TemplatedElementEnumerator<ElementType>& rhs) const { // If they point at the same node, then the names must match return (this->mParentElement == rhs.mParentElement) && (this->mCurrentElement == rhs.mCurrentElement) && (this->mCurrentElement != nullptr || (this->mChildElementName == rhs.mChildElementName)); } //============================================================================== template <typename ElementType> TemplatedElementEnumerator<ElementType>& TemplatedElementEnumerator<ElementType>::operator=( const TemplatedElementEnumerator<ElementType>& rhs) { this->mParentElement = rhs.mParentElement; this->mChildElementName = rhs.mChildElementName; this->mCurrentElement = rhs.mCurrentElement; return *this; } //============================================================================== template <typename ElementType> bool TemplatedElementEnumerator<ElementType>::valid() const { return mCurrentElement != nullptr; } } // namespace dart::utils #endif // #ifndef DART_UTILS_DETAIL_XMLHELPERS_IMPL_HPP_
32.283843
80
0.601515
ibrahiminfinite
6fe3231a26ac4f6032f77ecc1bdc782e8fda1148
2,052
cpp
C++
native/test/test_main.cpp
kaloianm/rural-pipe
7bdae362f360da3114282512ef2c0d01e621a4c1
[ "Unlicense" ]
null
null
null
native/test/test_main.cpp
kaloianm/rural-pipe
7bdae362f360da3114282512ef2c0d01e621a4c1
[ "Unlicense" ]
1
2021-02-18T18:35:46.000Z
2021-02-18T18:35:46.000Z
native/test/test_main.cpp
kaloianm/rural-pipe
7bdae362f360da3114282512ef2c0d01e621a4c1
[ "Unlicense" ]
null
null
null
/** * Copyright 2021 Kaloian Manassiev * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "common/base.h" #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE Main #include "test/test.h" #include <boost/log/attributes/named_scope.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> namespace ruralpi { namespace test { namespace { namespace logging = boost::log; class LoggingInitialisation { public: LoggingInitialisation() { logging::add_console_log(std::cout, boost::log::keywords::format = "[%ThreadID% (%Scope%)] %Message%"); logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::debug); logging::add_common_attributes(); logging::core::get()->add_global_attribute("Scope", boost::log::attributes::named_scope()); } }; BOOST_GLOBAL_FIXTURE(LoggingInitialisation); } // namespace } // namespace test } // namespace ruralpi
38
100
0.736355
kaloianm
6fe4ac1b2d1f92f467c00718a1a00535d72c01e9
1,848
hpp
C++
Library/Source/EnergyManager/Utility/CachedValue.hpp
NB4444/BachelorProjectEnergyManager
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
[ "MIT" ]
null
null
null
Library/Source/EnergyManager/Utility/CachedValue.hpp
NB4444/BachelorProjectEnergyManager
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
[ "MIT" ]
null
null
null
Library/Source/EnergyManager/Utility/CachedValue.hpp
NB4444/BachelorProjectEnergyManager
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
[ "MIT" ]
null
null
null
#pragma once #include <chrono> #include <functional> namespace EnergyManager { namespace Utility { /** * Caches a value for a certain amount of time. * @tparam Value The value type. */ template<typename Value> class CachedValue { /** * The cached value. */ Value value_; /** * Whether the value has been initialized. */ bool valueInitialized_ = false; /** * The amount of time to cache the value. */ std::chrono::system_clock::duration cachePeriod_; /** * When the value was last updated. */ std::chrono::system_clock::time_point lastUpdate_ = std::chrono::system_clock::now(); /** * Mutex to prevent multiple threads from updating and reading the value. */ std::mutex mutex_; public: /** * Creates a new cached value. * @param producer Generates a new value when needed. * @param cachePeriod The amount of time to cache the value. */ CachedValue(const std::chrono::system_clock::duration& cachePeriod = std::chrono::system_clock::duration(0)) : cachePeriod_(cachePeriod) { } /** * Gets the value that is currently cached. * @param producer Generates the new value when needed. * @return The current value. */ const Value& getValue(const std::function<Value(const Value& currentValue, const std::chrono::system_clock::duration& timeSinceLastUpdate)>& producer) { std::lock_guard<std::mutex> guard(mutex_); // Get current timestamp const auto now = std::chrono::system_clock::now(); // Update the value if necessary const auto timeSinceLastUpdate = now - lastUpdate_; if(!valueInitialized_ || timeSinceLastUpdate >= cachePeriod_) { lastUpdate_ = now; value_ = producer(value_, timeSinceLastUpdate); valueInitialized_ = true; } return value_; } }; } }
26.028169
155
0.66342
NB4444
6fe5354d460e717e146261598ca25d96f0a7c148
178
cpp
C++
tests/test_definition/hello.cpp
inlinechan/stags
9c1ce3ad4bf5d387c0b41482192d3d05ee96ef3a
[ "BSD-2-Clause" ]
null
null
null
tests/test_definition/hello.cpp
inlinechan/stags
9c1ce3ad4bf5d387c0b41482192d3d05ee96ef3a
[ "BSD-2-Clause" ]
1
2016-01-08T08:12:19.000Z
2016-01-08T08:12:19.000Z
tests/test_definition/hello.cpp
inlinechan/stags
9c1ce3ad4bf5d387c0b41482192d3d05ee96ef3a
[ "BSD-2-Clause" ]
null
null
null
#include "hello.h" #include "world.h" void say_hello(const char* name) { } int main(int argc, char *argv[]) { say_hello("Jack"); say_world("Dorothy"); return 0; }
11.866667
32
0.617978
inlinechan
6fe8e7e3ac317a14b86d35a1c44531c950a0a9d5
1,760
cpp
C++
test/unit/access.cpp
jfalcou/kumi
09116696274bd38254d89636ea3d0d4b5eb43103
[ "MIT" ]
14
2021-11-20T15:21:08.000Z
2022-03-14T21:47:22.000Z
test/unit/access.cpp
jfalcou/kumi
09116696274bd38254d89636ea3d0d4b5eb43103
[ "MIT" ]
6
2021-11-27T17:50:48.000Z
2022-02-01T18:17:38.000Z
test/unit/access.cpp
jfalcou/kumi
09116696274bd38254d89636ea3d0d4b5eb43103
[ "MIT" ]
1
2022-02-21T23:06:03.000Z
2022-02-21T23:06:03.000Z
//================================================================================================== /* KUMI - Compact Tuple Tools Copyright : KUMI Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #define TTS_MAIN #include <kumi/tuple.hpp> #include <tts/tts.hpp> TTS_CASE("Check access to kumi::tuple via indexing") { using namespace kumi::literals; kumi::tuple t1 = {1}; kumi::tuple t2 = {1.f, 2}; kumi::tuple t3 = {1., 2.f, 3}; kumi::tuple t4 = {'1', 2., 3.f, 4}; t1[0_c] = 42; TTS_EQUAL(t1[0_c], 42); t2[0_c] = 4.2f; t2[1_c] = 69; TTS_EQUAL(t2[0_c], 4.2f); TTS_EQUAL(t2[1_c], 69); t3[0_c] = 13.37; t3[1_c] = 4.2f; t3[2_c] = 40; TTS_EQUAL(t3[0_c], 13.37); TTS_EQUAL(t3[1_c], 4.2f); TTS_EQUAL(t3[2_c], 40); t4[0_c] = 'z'; t4[1_c] = 6.9; t4[2_c] = 4.2f; t4[3_c] = 1337; TTS_EQUAL(t4[0_c], 'z'); TTS_EQUAL(t4[1_c], 6.9); TTS_EQUAL(t4[2_c], 4.2f); TTS_EQUAL(t4[3_c], 1337); }; TTS_CASE("Check constexpr access to kumi::tuple via indexing") { using namespace kumi::literals; constexpr kumi::tuple t1 = {1}; constexpr kumi::tuple t2 = {1.f, 2}; constexpr kumi::tuple t3 = {1., 2.f, 3}; constexpr kumi::tuple t4 = {'1', 2., 3.f, 4}; TTS_CONSTEXPR_EQUAL(get<0>(t1), t1[0_c]); TTS_CONSTEXPR_EQUAL(get<0>(t2), t2[0_c]); TTS_CONSTEXPR_EQUAL(get<1>(t2), t2[1_c]); TTS_CONSTEXPR_EQUAL(get<0>(t3), t3[0_c]); TTS_CONSTEXPR_EQUAL(get<1>(t3), t3[1_c]); TTS_CONSTEXPR_EQUAL(get<2>(t3), t3[2_c]); TTS_CONSTEXPR_EQUAL(get<0>(t4), t4[0_c]); TTS_CONSTEXPR_EQUAL(get<1>(t4), t4[1_c]); TTS_CONSTEXPR_EQUAL(get<2>(t4), t4[2_c]); TTS_CONSTEXPR_EQUAL(get<3>(t4), t4[3_c]); };
25.507246
100
0.548295
jfalcou
6feaf3d59265df2d1b97ad4ebc786769c49c9a41
193,762
cc
C++
protocal/drivers/gnss/config.pb.cc
racestart/g2r
d115ebaab13829d716750eab2ebdcc51d79ff32e
[ "Apache-2.0" ]
1
2020-03-05T12:49:21.000Z
2020-03-05T12:49:21.000Z
protocal/drivers/gnss/config.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
null
null
null
protocal/drivers/gnss/config.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
1
2020-03-25T15:06:39.000Z
2020-03-25T15:06:39.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: drivers/gnss/config.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "drivers/gnss/config.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace apollo { namespace drivers { namespace gnss { namespace config { namespace { const ::google::protobuf::Descriptor* Stream_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Stream_reflection_ = NULL; struct StreamOneofInstance { const ::apollo::drivers::gnss::config::Stream_Serial* serial_; const ::apollo::drivers::gnss::config::Stream_Tcp* tcp_; const ::apollo::drivers::gnss::config::Stream_Udp* udp_; const ::apollo::drivers::gnss::config::Stream_Ntrip* ntrip_; }* Stream_default_oneof_instance_ = NULL; const ::google::protobuf::Descriptor* Stream_Serial_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Stream_Serial_reflection_ = NULL; const ::google::protobuf::Descriptor* Stream_Tcp_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Stream_Tcp_reflection_ = NULL; const ::google::protobuf::Descriptor* Stream_Udp_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Stream_Udp_reflection_ = NULL; const ::google::protobuf::Descriptor* Stream_Ntrip_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Stream_Ntrip_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* Stream_Format_descriptor_ = NULL; const ::google::protobuf::Descriptor* NovatelConfig_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* NovatelConfig_reflection_ = NULL; const ::google::protobuf::Descriptor* UbloxConfig_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* UbloxConfig_reflection_ = NULL; const ::google::protobuf::Descriptor* TF_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* TF_reflection_ = NULL; const ::google::protobuf::Descriptor* Config_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Config_reflection_ = NULL; struct ConfigOneofInstance { const ::apollo::drivers::gnss::config::NovatelConfig* novatel_config_; const ::apollo::drivers::gnss::config::UbloxConfig* ublox_config_; }* Config_default_oneof_instance_ = NULL; const ::google::protobuf::EnumDescriptor* Config_RtkSolutionType_descriptor_ = NULL; const ::google::protobuf::EnumDescriptor* ImuType_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_drivers_2fgnss_2fconfig_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_drivers_2fgnss_2fconfig_2eproto() { protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "drivers/gnss/config.proto"); GOOGLE_CHECK(file != NULL); Stream_descriptor_ = file->message_type(0); static const int Stream_offsets_[7] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream, format_), PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(Stream_default_oneof_instance_, serial_), PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(Stream_default_oneof_instance_, tcp_), PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(Stream_default_oneof_instance_, udp_), PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(Stream_default_oneof_instance_, ntrip_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream, push_location_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream, type_), }; Stream_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Stream_descriptor_, Stream::default_instance_, Stream_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream, _has_bits_[0]), -1, -1, Stream_default_oneof_instance_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream, _oneof_case_[0]), sizeof(Stream), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream, _internal_metadata_), -1); Stream_Serial_descriptor_ = Stream_descriptor_->nested_type(0); static const int Stream_Serial_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Serial, device_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Serial, baud_rate_), }; Stream_Serial_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Stream_Serial_descriptor_, Stream_Serial::default_instance_, Stream_Serial_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Serial, _has_bits_[0]), -1, -1, sizeof(Stream_Serial), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Serial, _internal_metadata_), -1); Stream_Tcp_descriptor_ = Stream_descriptor_->nested_type(1); static const int Stream_Tcp_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Tcp, address_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Tcp, port_), }; Stream_Tcp_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Stream_Tcp_descriptor_, Stream_Tcp::default_instance_, Stream_Tcp_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Tcp, _has_bits_[0]), -1, -1, sizeof(Stream_Tcp), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Tcp, _internal_metadata_), -1); Stream_Udp_descriptor_ = Stream_descriptor_->nested_type(2); static const int Stream_Udp_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Udp, address_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Udp, port_), }; Stream_Udp_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Stream_Udp_descriptor_, Stream_Udp::default_instance_, Stream_Udp_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Udp, _has_bits_[0]), -1, -1, sizeof(Stream_Udp), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Udp, _internal_metadata_), -1); Stream_Ntrip_descriptor_ = Stream_descriptor_->nested_type(3); static const int Stream_Ntrip_offsets_[6] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, address_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, port_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, mount_point_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, user_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, password_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, timeout_s_), }; Stream_Ntrip_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Stream_Ntrip_descriptor_, Stream_Ntrip::default_instance_, Stream_Ntrip_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, _has_bits_[0]), -1, -1, sizeof(Stream_Ntrip), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Stream_Ntrip, _internal_metadata_), -1); Stream_Format_descriptor_ = Stream_descriptor_->enum_type(0); NovatelConfig_descriptor_ = file->message_type(1); static const int NovatelConfig_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NovatelConfig, imu_orientation_), }; NovatelConfig_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( NovatelConfig_descriptor_, NovatelConfig::default_instance_, NovatelConfig_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NovatelConfig, _has_bits_[0]), -1, -1, sizeof(NovatelConfig), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NovatelConfig, _internal_metadata_), -1); UbloxConfig_descriptor_ = file->message_type(2); static const int UbloxConfig_offsets_[1] = { }; UbloxConfig_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( UbloxConfig_descriptor_, UbloxConfig::default_instance_, UbloxConfig_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UbloxConfig, _has_bits_[0]), -1, -1, sizeof(UbloxConfig), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UbloxConfig, _internal_metadata_), -1); TF_descriptor_ = file->message_type(3); static const int TF_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TF, frame_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TF, child_frame_id_), }; TF_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( TF_descriptor_, TF::default_instance_, TF_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TF, _has_bits_[0]), -1, -1, sizeof(TF), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TF, _internal_metadata_), -1); Config_descriptor_ = file->message_type(4); static const int Config_offsets_[14] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, data_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, command_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, rtk_from_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, rtk_to_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, login_commands_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, logout_commands_), PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(Config_default_oneof_instance_, novatel_config_), PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(Config_default_oneof_instance_, ublox_config_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, rtk_solution_type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, imu_type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, proj4_text_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, tf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, wheel_parameters_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, device_config_), }; Config_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Config_descriptor_, Config::default_instance_, Config_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, _has_bits_[0]), -1, -1, Config_default_oneof_instance_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, _oneof_case_[0]), sizeof(Config), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Config, _internal_metadata_), -1); Config_RtkSolutionType_descriptor_ = Config_descriptor_->enum_type(0); ImuType_descriptor_ = file->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_drivers_2fgnss_2fconfig_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Stream_descriptor_, &Stream::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Stream_Serial_descriptor_, &Stream_Serial::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Stream_Tcp_descriptor_, &Stream_Tcp::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Stream_Udp_descriptor_, &Stream_Udp::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Stream_Ntrip_descriptor_, &Stream_Ntrip::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( NovatelConfig_descriptor_, &NovatelConfig::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( UbloxConfig_descriptor_, &UbloxConfig::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( TF_descriptor_, &TF::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Config_descriptor_, &Config::default_instance()); } } // namespace void protobuf_ShutdownFile_drivers_2fgnss_2fconfig_2eproto() { delete Stream::default_instance_; delete Stream_default_oneof_instance_; delete Stream_reflection_; delete Stream_Serial::default_instance_; delete Stream_Serial_reflection_; delete Stream_Tcp::default_instance_; delete Stream_Tcp_reflection_; delete Stream_Udp::default_instance_; delete Stream_Udp_reflection_; delete Stream_Ntrip::default_instance_; delete Stream_Ntrip_reflection_; delete NovatelConfig::default_instance_; delete NovatelConfig_reflection_; delete UbloxConfig::default_instance_; delete UbloxConfig_reflection_; delete TF::default_instance_; delete TF_reflection_; delete TF::_default_frame_id_; delete TF::_default_child_frame_id_; delete Config::default_instance_; delete Config_default_oneof_instance_; delete Config_reflection_; } void protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\031drivers/gnss/config.proto\022\032apollo.driv" "ers.gnss.config\"\321\005\n\006Stream\0229\n\006format\030\001 \001" "(\0162).apollo.drivers.gnss.config.Stream.F" "ormat\022;\n\006serial\030\002 \001(\0132).apollo.drivers.g" "nss.config.Stream.SerialH\000\0225\n\003tcp\030\003 \001(\0132" "&.apollo.drivers.gnss.config.Stream.TcpH" "\000\0225\n\003udp\030\004 \001(\0132&.apollo.drivers.gnss.con" "fig.Stream.UdpH\000\0229\n\005ntrip\030\005 \001(\0132(.apollo" ".drivers.gnss.config.Stream.NtripH\000\022\025\n\rp" "ush_location\030\006 \001(\010\0321\n\006Serial\022\016\n\006device\030\001" " \001(\014\022\027\n\tbaud_rate\030\002 \001(\005:\0049600\032*\n\003Tcp\022\017\n\007" "address\030\001 \001(\014\022\022\n\004port\030\002 \001(\005:\0043001\032*\n\003Udp" "\022\017\n\007address\030\001 \001(\014\022\022\n\004port\030\002 \001(\005:\0043001\032x\n" "\005Ntrip\022\017\n\007address\030\001 \001(\014\022\022\n\004port\030\002 \001(\005:\0042" "101\022\023\n\013mount_point\030\003 \001(\014\022\014\n\004user\030\004 \001(\014\022\020" "\n\010password\030\005 \001(\014\022\025\n\ttimeout_s\030\006 \001(\r:\00230\"" "\201\001\n\006Format\022\013\n\007UNKNOWN\020\000\022\010\n\004NMEA\020\001\022\013\n\007RTC" "M_V2\020\002\022\013\n\007RTCM_V3\020\003\022\020\n\014NOVATEL_TEXT\020\n\022\022\n" "\016NOVATEL_BINARY\020\013\022\016\n\nUBLOX_TEXT\020\024\022\020\n\014UBL" "OX_BINARY\020\025B\006\n\004type\"+\n\rNovatelConfig\022\032\n\017" "imu_orientation\030\001 \001(\005:\0015\"\r\n\013UbloxConfig\"" ">\n\002TF\022\027\n\010frame_id\030\001 \001(\t:\005world\022\037\n\016child_" "frame_id\030\002 \001(\t:\007novatel\"\312\005\n\006Config\0220\n\004da" "ta\030\001 \001(\0132\".apollo.drivers.gnss.config.St" "ream\0223\n\007command\030\002 \001(\0132\".apollo.drivers.g" "nss.config.Stream\0224\n\010rtk_from\030\003 \001(\0132\".ap" "ollo.drivers.gnss.config.Stream\0222\n\006rtk_t" "o\030\004 \001(\0132\".apollo.drivers.gnss.config.Str" "eam\022\026\n\016login_commands\030\005 \003(\014\022\027\n\017logout_co" "mmands\030\006 \003(\014\022C\n\016novatel_config\030\007 \001(\0132).a" "pollo.drivers.gnss.config.NovatelConfigH" "\000\022\?\n\014ublox_config\030\010 \001(\0132\'.apollo.drivers" ".gnss.config.UbloxConfigH\000\022M\n\021rtk_soluti" "on_type\030\t \001(\01622.apollo.drivers.gnss.conf" "ig.Config.RtkSolutionType\0225\n\010imu_type\030\n " "\001(\0162#.apollo.drivers.gnss.config.ImuType" "\022\022\n\nproj4_text\030\013 \001(\t\022*\n\002tf\030\014 \001(\0132\036.apoll" "o.drivers.gnss.config.TF\022\030\n\020wheel_parame" "ters\030\r \001(\t\"G\n\017RtkSolutionType\022\031\n\025RTK_REC" "EIVER_SOLUTION\020\001\022\031\n\025RTK_SOFTWARE_SOLUTIO" "N\020\002B\017\n\rdevice_config*\230\001\n\007ImuType\022\r\n\tIMAR" "_FSAS\020\r\022\013\n\007ISA100C\020\032\022\r\n\tADIS16488\020\037\022\013\n\007S" "TIM300\020 \022\n\n\006ISA100\020\"\022\020\n\014ISA100_400HZ\020&\022\021" "\n\rISA100C_400HZ\020\'\022\t\n\005G320N\020(\022\016\n\nCPT_XW56" "51\020)\022\t\n\005UM442\020*", 1775); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "drivers/gnss/config.proto", &protobuf_RegisterTypes); Stream::default_instance_ = new Stream(); Stream_default_oneof_instance_ = new StreamOneofInstance(); Stream_Serial::default_instance_ = new Stream_Serial(); Stream_Tcp::default_instance_ = new Stream_Tcp(); Stream_Udp::default_instance_ = new Stream_Udp(); Stream_Ntrip::default_instance_ = new Stream_Ntrip(); NovatelConfig::default_instance_ = new NovatelConfig(); UbloxConfig::default_instance_ = new UbloxConfig(); TF::_default_frame_id_ = new ::std::string("world", 5); TF::_default_child_frame_id_ = new ::std::string("novatel", 7); TF::default_instance_ = new TF(); Config::default_instance_ = new Config(); Config_default_oneof_instance_ = new ConfigOneofInstance(); Stream::default_instance_->InitAsDefaultInstance(); Stream_Serial::default_instance_->InitAsDefaultInstance(); Stream_Tcp::default_instance_->InitAsDefaultInstance(); Stream_Udp::default_instance_->InitAsDefaultInstance(); Stream_Ntrip::default_instance_->InitAsDefaultInstance(); NovatelConfig::default_instance_->InitAsDefaultInstance(); UbloxConfig::default_instance_->InitAsDefaultInstance(); TF::default_instance_->InitAsDefaultInstance(); Config::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_drivers_2fgnss_2fconfig_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_drivers_2fgnss_2fconfig_2eproto { StaticDescriptorInitializer_drivers_2fgnss_2fconfig_2eproto() { protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); } } static_descriptor_initializer_drivers_2fgnss_2fconfig_2eproto_; const ::google::protobuf::EnumDescriptor* ImuType_descriptor() { protobuf_AssignDescriptorsOnce(); return ImuType_descriptor_; } bool ImuType_IsValid(int value) { switch(value) { case 13: case 26: case 31: case 32: case 34: case 38: case 39: case 40: case 41: case 42: return true; default: return false; } } // =================================================================== const ::google::protobuf::EnumDescriptor* Stream_Format_descriptor() { protobuf_AssignDescriptorsOnce(); return Stream_Format_descriptor_; } bool Stream_Format_IsValid(int value) { switch(value) { case 0: case 1: case 2: case 3: case 10: case 11: case 20: case 21: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const Stream_Format Stream::UNKNOWN; const Stream_Format Stream::NMEA; const Stream_Format Stream::RTCM_V2; const Stream_Format Stream::RTCM_V3; const Stream_Format Stream::NOVATEL_TEXT; const Stream_Format Stream::NOVATEL_BINARY; const Stream_Format Stream::UBLOX_TEXT; const Stream_Format Stream::UBLOX_BINARY; const Stream_Format Stream::Format_MIN; const Stream_Format Stream::Format_MAX; const int Stream::Format_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Stream_Serial::kDeviceFieldNumber; const int Stream_Serial::kBaudRateFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Stream_Serial::Stream_Serial() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.Stream.Serial) } void Stream_Serial::InitAsDefaultInstance() { } Stream_Serial::Stream_Serial(const Stream_Serial& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.Stream.Serial) } void Stream_Serial::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; device_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); baud_rate_ = 9600; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Stream_Serial::~Stream_Serial() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.Stream.Serial) SharedDtor(); } void Stream_Serial::SharedDtor() { device_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != default_instance_) { } } void Stream_Serial::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Stream_Serial::descriptor() { protobuf_AssignDescriptorsOnce(); return Stream_Serial_descriptor_; } const Stream_Serial& Stream_Serial::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } Stream_Serial* Stream_Serial::default_instance_ = NULL; Stream_Serial* Stream_Serial::New(::google::protobuf::Arena* arena) const { Stream_Serial* n = new Stream_Serial; if (arena != NULL) { arena->Own(n); } return n; } void Stream_Serial::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.Stream.Serial) if (_has_bits_[0 / 32] & 3u) { if (has_device()) { device_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } baud_rate_ = 9600; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool Stream_Serial::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.Stream.Serial) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bytes device = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_device())); } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_baud_rate; break; } // optional int32 baud_rate = 2 [default = 9600]; case 2: { if (tag == 16) { parse_baud_rate: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &baud_rate_))); set_has_baud_rate(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.Stream.Serial) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.Stream.Serial) return false; #undef DO_ } void Stream_Serial::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.Stream.Serial) // optional bytes device = 1; if (has_device()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 1, this->device(), output); } // optional int32 baud_rate = 2 [default = 9600]; if (has_baud_rate()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->baud_rate(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.Stream.Serial) } ::google::protobuf::uint8* Stream_Serial::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.Stream.Serial) // optional bytes device = 1; if (has_device()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->device(), target); } // optional int32 baud_rate = 2 [default = 9600]; if (has_baud_rate()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->baud_rate(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.Stream.Serial) return target; } int Stream_Serial::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.Stream.Serial) int total_size = 0; if (_has_bits_[0 / 32] & 3u) { // optional bytes device = 1; if (has_device()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->device()); } // optional int32 baud_rate = 2 [default = 9600]; if (has_baud_rate()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->baud_rate()); } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Stream_Serial::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.Stream.Serial) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const Stream_Serial* source = ::google::protobuf::internal::DynamicCastToGenerated<const Stream_Serial>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.Stream.Serial) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.Stream.Serial) MergeFrom(*source); } } void Stream_Serial::MergeFrom(const Stream_Serial& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.Stream.Serial) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_device()) { set_has_device(); device_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.device_); } if (from.has_baud_rate()) { set_baud_rate(from.baud_rate()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void Stream_Serial::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.Stream.Serial) if (&from == this) return; Clear(); MergeFrom(from); } void Stream_Serial::CopyFrom(const Stream_Serial& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.Stream.Serial) if (&from == this) return; Clear(); MergeFrom(from); } bool Stream_Serial::IsInitialized() const { return true; } void Stream_Serial::Swap(Stream_Serial* other) { if (other == this) return; InternalSwap(other); } void Stream_Serial::InternalSwap(Stream_Serial* other) { device_.Swap(&other->device_); std::swap(baud_rate_, other->baud_rate_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Stream_Serial::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Stream_Serial_descriptor_; metadata.reflection = Stream_Serial_reflection_; return metadata; } // ------------------------------------------------------------------- #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Stream_Tcp::kAddressFieldNumber; const int Stream_Tcp::kPortFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Stream_Tcp::Stream_Tcp() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.Stream.Tcp) } void Stream_Tcp::InitAsDefaultInstance() { } Stream_Tcp::Stream_Tcp(const Stream_Tcp& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.Stream.Tcp) } void Stream_Tcp::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; address_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); port_ = 3001; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Stream_Tcp::~Stream_Tcp() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.Stream.Tcp) SharedDtor(); } void Stream_Tcp::SharedDtor() { address_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != default_instance_) { } } void Stream_Tcp::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Stream_Tcp::descriptor() { protobuf_AssignDescriptorsOnce(); return Stream_Tcp_descriptor_; } const Stream_Tcp& Stream_Tcp::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } Stream_Tcp* Stream_Tcp::default_instance_ = NULL; Stream_Tcp* Stream_Tcp::New(::google::protobuf::Arena* arena) const { Stream_Tcp* n = new Stream_Tcp; if (arena != NULL) { arena->Own(n); } return n; } void Stream_Tcp::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.Stream.Tcp) if (_has_bits_[0 / 32] & 3u) { if (has_address()) { address_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } port_ = 3001; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool Stream_Tcp::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.Stream.Tcp) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bytes address = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_address())); } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_port; break; } // optional int32 port = 2 [default = 3001]; case 2: { if (tag == 16) { parse_port: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &port_))); set_has_port(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.Stream.Tcp) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.Stream.Tcp) return false; #undef DO_ } void Stream_Tcp::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.Stream.Tcp) // optional bytes address = 1; if (has_address()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 1, this->address(), output); } // optional int32 port = 2 [default = 3001]; if (has_port()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->port(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.Stream.Tcp) } ::google::protobuf::uint8* Stream_Tcp::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.Stream.Tcp) // optional bytes address = 1; if (has_address()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->address(), target); } // optional int32 port = 2 [default = 3001]; if (has_port()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->port(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.Stream.Tcp) return target; } int Stream_Tcp::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.Stream.Tcp) int total_size = 0; if (_has_bits_[0 / 32] & 3u) { // optional bytes address = 1; if (has_address()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->address()); } // optional int32 port = 2 [default = 3001]; if (has_port()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->port()); } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Stream_Tcp::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.Stream.Tcp) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const Stream_Tcp* source = ::google::protobuf::internal::DynamicCastToGenerated<const Stream_Tcp>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.Stream.Tcp) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.Stream.Tcp) MergeFrom(*source); } } void Stream_Tcp::MergeFrom(const Stream_Tcp& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.Stream.Tcp) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_address()) { set_has_address(); address_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.address_); } if (from.has_port()) { set_port(from.port()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void Stream_Tcp::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.Stream.Tcp) if (&from == this) return; Clear(); MergeFrom(from); } void Stream_Tcp::CopyFrom(const Stream_Tcp& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.Stream.Tcp) if (&from == this) return; Clear(); MergeFrom(from); } bool Stream_Tcp::IsInitialized() const { return true; } void Stream_Tcp::Swap(Stream_Tcp* other) { if (other == this) return; InternalSwap(other); } void Stream_Tcp::InternalSwap(Stream_Tcp* other) { address_.Swap(&other->address_); std::swap(port_, other->port_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Stream_Tcp::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Stream_Tcp_descriptor_; metadata.reflection = Stream_Tcp_reflection_; return metadata; } // ------------------------------------------------------------------- #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Stream_Udp::kAddressFieldNumber; const int Stream_Udp::kPortFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Stream_Udp::Stream_Udp() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.Stream.Udp) } void Stream_Udp::InitAsDefaultInstance() { } Stream_Udp::Stream_Udp(const Stream_Udp& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.Stream.Udp) } void Stream_Udp::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; address_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); port_ = 3001; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Stream_Udp::~Stream_Udp() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.Stream.Udp) SharedDtor(); } void Stream_Udp::SharedDtor() { address_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != default_instance_) { } } void Stream_Udp::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Stream_Udp::descriptor() { protobuf_AssignDescriptorsOnce(); return Stream_Udp_descriptor_; } const Stream_Udp& Stream_Udp::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } Stream_Udp* Stream_Udp::default_instance_ = NULL; Stream_Udp* Stream_Udp::New(::google::protobuf::Arena* arena) const { Stream_Udp* n = new Stream_Udp; if (arena != NULL) { arena->Own(n); } return n; } void Stream_Udp::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.Stream.Udp) if (_has_bits_[0 / 32] & 3u) { if (has_address()) { address_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } port_ = 3001; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool Stream_Udp::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.Stream.Udp) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bytes address = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_address())); } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_port; break; } // optional int32 port = 2 [default = 3001]; case 2: { if (tag == 16) { parse_port: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &port_))); set_has_port(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.Stream.Udp) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.Stream.Udp) return false; #undef DO_ } void Stream_Udp::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.Stream.Udp) // optional bytes address = 1; if (has_address()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 1, this->address(), output); } // optional int32 port = 2 [default = 3001]; if (has_port()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->port(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.Stream.Udp) } ::google::protobuf::uint8* Stream_Udp::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.Stream.Udp) // optional bytes address = 1; if (has_address()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->address(), target); } // optional int32 port = 2 [default = 3001]; if (has_port()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->port(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.Stream.Udp) return target; } int Stream_Udp::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.Stream.Udp) int total_size = 0; if (_has_bits_[0 / 32] & 3u) { // optional bytes address = 1; if (has_address()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->address()); } // optional int32 port = 2 [default = 3001]; if (has_port()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->port()); } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Stream_Udp::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.Stream.Udp) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const Stream_Udp* source = ::google::protobuf::internal::DynamicCastToGenerated<const Stream_Udp>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.Stream.Udp) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.Stream.Udp) MergeFrom(*source); } } void Stream_Udp::MergeFrom(const Stream_Udp& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.Stream.Udp) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_address()) { set_has_address(); address_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.address_); } if (from.has_port()) { set_port(from.port()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void Stream_Udp::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.Stream.Udp) if (&from == this) return; Clear(); MergeFrom(from); } void Stream_Udp::CopyFrom(const Stream_Udp& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.Stream.Udp) if (&from == this) return; Clear(); MergeFrom(from); } bool Stream_Udp::IsInitialized() const { return true; } void Stream_Udp::Swap(Stream_Udp* other) { if (other == this) return; InternalSwap(other); } void Stream_Udp::InternalSwap(Stream_Udp* other) { address_.Swap(&other->address_); std::swap(port_, other->port_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Stream_Udp::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Stream_Udp_descriptor_; metadata.reflection = Stream_Udp_reflection_; return metadata; } // ------------------------------------------------------------------- #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Stream_Ntrip::kAddressFieldNumber; const int Stream_Ntrip::kPortFieldNumber; const int Stream_Ntrip::kMountPointFieldNumber; const int Stream_Ntrip::kUserFieldNumber; const int Stream_Ntrip::kPasswordFieldNumber; const int Stream_Ntrip::kTimeoutSFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Stream_Ntrip::Stream_Ntrip() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.Stream.Ntrip) } void Stream_Ntrip::InitAsDefaultInstance() { } Stream_Ntrip::Stream_Ntrip(const Stream_Ntrip& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.Stream.Ntrip) } void Stream_Ntrip::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; address_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); port_ = 2101; mount_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); user_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); password_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); timeout_s_ = 30u; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Stream_Ntrip::~Stream_Ntrip() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.Stream.Ntrip) SharedDtor(); } void Stream_Ntrip::SharedDtor() { address_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); mount_point_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); user_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); password_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != default_instance_) { } } void Stream_Ntrip::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Stream_Ntrip::descriptor() { protobuf_AssignDescriptorsOnce(); return Stream_Ntrip_descriptor_; } const Stream_Ntrip& Stream_Ntrip::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } Stream_Ntrip* Stream_Ntrip::default_instance_ = NULL; Stream_Ntrip* Stream_Ntrip::New(::google::protobuf::Arena* arena) const { Stream_Ntrip* n = new Stream_Ntrip; if (arena != NULL) { arena->Own(n); } return n; } void Stream_Ntrip::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.Stream.Ntrip) if (_has_bits_[0 / 32] & 63u) { if (has_address()) { address_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } port_ = 2101; if (has_mount_point()) { mount_point_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } if (has_user()) { user_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } if (has_password()) { password_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } timeout_s_ = 30u; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool Stream_Ntrip::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.Stream.Ntrip) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bytes address = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_address())); } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_port; break; } // optional int32 port = 2 [default = 2101]; case 2: { if (tag == 16) { parse_port: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &port_))); set_has_port(); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_mount_point; break; } // optional bytes mount_point = 3; case 3: { if (tag == 26) { parse_mount_point: DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_mount_point())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_user; break; } // optional bytes user = 4; case 4: { if (tag == 34) { parse_user: DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_user())); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_password; break; } // optional bytes password = 5; case 5: { if (tag == 42) { parse_password: DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_password())); } else { goto handle_unusual; } if (input->ExpectTag(48)) goto parse_timeout_s; break; } // optional uint32 timeout_s = 6 [default = 30]; case 6: { if (tag == 48) { parse_timeout_s: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &timeout_s_))); set_has_timeout_s(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.Stream.Ntrip) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.Stream.Ntrip) return false; #undef DO_ } void Stream_Ntrip::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.Stream.Ntrip) // optional bytes address = 1; if (has_address()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 1, this->address(), output); } // optional int32 port = 2 [default = 2101]; if (has_port()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->port(), output); } // optional bytes mount_point = 3; if (has_mount_point()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 3, this->mount_point(), output); } // optional bytes user = 4; if (has_user()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 4, this->user(), output); } // optional bytes password = 5; if (has_password()) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 5, this->password(), output); } // optional uint32 timeout_s = 6 [default = 30]; if (has_timeout_s()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->timeout_s(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.Stream.Ntrip) } ::google::protobuf::uint8* Stream_Ntrip::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.Stream.Ntrip) // optional bytes address = 1; if (has_address()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->address(), target); } // optional int32 port = 2 [default = 2101]; if (has_port()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->port(), target); } // optional bytes mount_point = 3; if (has_mount_point()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 3, this->mount_point(), target); } // optional bytes user = 4; if (has_user()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 4, this->user(), target); } // optional bytes password = 5; if (has_password()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 5, this->password(), target); } // optional uint32 timeout_s = 6 [default = 30]; if (has_timeout_s()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(6, this->timeout_s(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.Stream.Ntrip) return target; } int Stream_Ntrip::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.Stream.Ntrip) int total_size = 0; if (_has_bits_[0 / 32] & 63u) { // optional bytes address = 1; if (has_address()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->address()); } // optional int32 port = 2 [default = 2101]; if (has_port()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->port()); } // optional bytes mount_point = 3; if (has_mount_point()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->mount_point()); } // optional bytes user = 4; if (has_user()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->user()); } // optional bytes password = 5; if (has_password()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->password()); } // optional uint32 timeout_s = 6 [default = 30]; if (has_timeout_s()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->timeout_s()); } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Stream_Ntrip::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.Stream.Ntrip) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const Stream_Ntrip* source = ::google::protobuf::internal::DynamicCastToGenerated<const Stream_Ntrip>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.Stream.Ntrip) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.Stream.Ntrip) MergeFrom(*source); } } void Stream_Ntrip::MergeFrom(const Stream_Ntrip& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.Stream.Ntrip) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_address()) { set_has_address(); address_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.address_); } if (from.has_port()) { set_port(from.port()); } if (from.has_mount_point()) { set_has_mount_point(); mount_point_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.mount_point_); } if (from.has_user()) { set_has_user(); user_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.user_); } if (from.has_password()) { set_has_password(); password_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.password_); } if (from.has_timeout_s()) { set_timeout_s(from.timeout_s()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void Stream_Ntrip::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.Stream.Ntrip) if (&from == this) return; Clear(); MergeFrom(from); } void Stream_Ntrip::CopyFrom(const Stream_Ntrip& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.Stream.Ntrip) if (&from == this) return; Clear(); MergeFrom(from); } bool Stream_Ntrip::IsInitialized() const { return true; } void Stream_Ntrip::Swap(Stream_Ntrip* other) { if (other == this) return; InternalSwap(other); } void Stream_Ntrip::InternalSwap(Stream_Ntrip* other) { address_.Swap(&other->address_); std::swap(port_, other->port_); mount_point_.Swap(&other->mount_point_); user_.Swap(&other->user_); password_.Swap(&other->password_); std::swap(timeout_s_, other->timeout_s_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Stream_Ntrip::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Stream_Ntrip_descriptor_; metadata.reflection = Stream_Ntrip_reflection_; return metadata; } // ------------------------------------------------------------------- #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Stream::kFormatFieldNumber; const int Stream::kSerialFieldNumber; const int Stream::kTcpFieldNumber; const int Stream::kUdpFieldNumber; const int Stream::kNtripFieldNumber; const int Stream::kPushLocationFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Stream::Stream() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.Stream) } void Stream::InitAsDefaultInstance() { Stream_default_oneof_instance_->serial_ = const_cast< ::apollo::drivers::gnss::config::Stream_Serial*>(&::apollo::drivers::gnss::config::Stream_Serial::default_instance()); Stream_default_oneof_instance_->tcp_ = const_cast< ::apollo::drivers::gnss::config::Stream_Tcp*>(&::apollo::drivers::gnss::config::Stream_Tcp::default_instance()); Stream_default_oneof_instance_->udp_ = const_cast< ::apollo::drivers::gnss::config::Stream_Udp*>(&::apollo::drivers::gnss::config::Stream_Udp::default_instance()); Stream_default_oneof_instance_->ntrip_ = const_cast< ::apollo::drivers::gnss::config::Stream_Ntrip*>(&::apollo::drivers::gnss::config::Stream_Ntrip::default_instance()); } Stream::Stream(const Stream& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.Stream) } void Stream::SharedCtor() { _cached_size_ = 0; format_ = 0; push_location_ = false; ::memset(_has_bits_, 0, sizeof(_has_bits_)); clear_has_type(); } Stream::~Stream() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.Stream) SharedDtor(); } void Stream::SharedDtor() { if (has_type()) { clear_type(); } if (this != default_instance_) { } } void Stream::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Stream::descriptor() { protobuf_AssignDescriptorsOnce(); return Stream_descriptor_; } const Stream& Stream::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } Stream* Stream::default_instance_ = NULL; Stream* Stream::New(::google::protobuf::Arena* arena) const { Stream* n = new Stream; if (arena != NULL) { arena->Own(n); } return n; } void Stream::clear_type() { // @@protoc_insertion_point(one_of_clear_start:apollo.drivers.gnss.config.Stream) switch(type_case()) { case kSerial: { delete type_.serial_; break; } case kTcp: { delete type_.tcp_; break; } case kUdp: { delete type_.udp_; break; } case kNtrip: { delete type_.ntrip_; break; } case TYPE_NOT_SET: { break; } } _oneof_case_[0] = TYPE_NOT_SET; } void Stream::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.Stream) #if defined(__clang__) #define ZR_HELPER_(f) \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \ __builtin_offsetof(Stream, f) \ _Pragma("clang diagnostic pop") #else #define ZR_HELPER_(f) reinterpret_cast<char*>(\ &reinterpret_cast<Stream*>(16)->f) #endif #define ZR_(first, last) do {\ ::memset(&first, 0,\ ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\ } while (0) ZR_(format_, push_location_); #undef ZR_HELPER_ #undef ZR_ clear_type(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool Stream::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.Stream) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .apollo.drivers.gnss.config.Stream.Format format = 1; case 1: { if (tag == 8) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::drivers::gnss::config::Stream_Format_IsValid(value)) { set_format(static_cast< ::apollo::drivers::gnss::config::Stream_Format >(value)); } else { mutable_unknown_fields()->AddVarint(1, value); } } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_serial; break; } // optional .apollo.drivers.gnss.config.Stream.Serial serial = 2; case 2: { if (tag == 18) { parse_serial: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_serial())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_tcp; break; } // optional .apollo.drivers.gnss.config.Stream.Tcp tcp = 3; case 3: { if (tag == 26) { parse_tcp: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_tcp())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_udp; break; } // optional .apollo.drivers.gnss.config.Stream.Udp udp = 4; case 4: { if (tag == 34) { parse_udp: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_udp())); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_ntrip; break; } // optional .apollo.drivers.gnss.config.Stream.Ntrip ntrip = 5; case 5: { if (tag == 42) { parse_ntrip: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_ntrip())); } else { goto handle_unusual; } if (input->ExpectTag(48)) goto parse_push_location; break; } // optional bool push_location = 6; case 6: { if (tag == 48) { parse_push_location: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &push_location_))); set_has_push_location(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.Stream) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.Stream) return false; #undef DO_ } void Stream::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.Stream) // optional .apollo.drivers.gnss.config.Stream.Format format = 1; if (has_format()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->format(), output); } // optional .apollo.drivers.gnss.config.Stream.Serial serial = 2; if (has_serial()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *type_.serial_, output); } // optional .apollo.drivers.gnss.config.Stream.Tcp tcp = 3; if (has_tcp()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, *type_.tcp_, output); } // optional .apollo.drivers.gnss.config.Stream.Udp udp = 4; if (has_udp()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *type_.udp_, output); } // optional .apollo.drivers.gnss.config.Stream.Ntrip ntrip = 5; if (has_ntrip()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, *type_.ntrip_, output); } // optional bool push_location = 6; if (has_push_location()) { ::google::protobuf::internal::WireFormatLite::WriteBool(6, this->push_location(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.Stream) } ::google::protobuf::uint8* Stream::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.Stream) // optional .apollo.drivers.gnss.config.Stream.Format format = 1; if (has_format()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->format(), target); } // optional .apollo.drivers.gnss.config.Stream.Serial serial = 2; if (has_serial()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *type_.serial_, false, target); } // optional .apollo.drivers.gnss.config.Stream.Tcp tcp = 3; if (has_tcp()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 3, *type_.tcp_, false, target); } // optional .apollo.drivers.gnss.config.Stream.Udp udp = 4; if (has_udp()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *type_.udp_, false, target); } // optional .apollo.drivers.gnss.config.Stream.Ntrip ntrip = 5; if (has_ntrip()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 5, *type_.ntrip_, false, target); } // optional bool push_location = 6; if (has_push_location()) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(6, this->push_location(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.Stream) return target; } int Stream::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.Stream) int total_size = 0; if (_has_bits_[0 / 32] & 33u) { // optional .apollo.drivers.gnss.config.Stream.Format format = 1; if (has_format()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->format()); } // optional bool push_location = 6; if (has_push_location()) { total_size += 1 + 1; } } switch (type_case()) { // optional .apollo.drivers.gnss.config.Stream.Serial serial = 2; case kSerial: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *type_.serial_); break; } // optional .apollo.drivers.gnss.config.Stream.Tcp tcp = 3; case kTcp: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *type_.tcp_); break; } // optional .apollo.drivers.gnss.config.Stream.Udp udp = 4; case kUdp: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *type_.udp_); break; } // optional .apollo.drivers.gnss.config.Stream.Ntrip ntrip = 5; case kNtrip: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *type_.ntrip_); break; } case TYPE_NOT_SET: { break; } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Stream::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.Stream) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const Stream* source = ::google::protobuf::internal::DynamicCastToGenerated<const Stream>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.Stream) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.Stream) MergeFrom(*source); } } void Stream::MergeFrom(const Stream& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.Stream) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } switch (from.type_case()) { case kSerial: { mutable_serial()->::apollo::drivers::gnss::config::Stream_Serial::MergeFrom(from.serial()); break; } case kTcp: { mutable_tcp()->::apollo::drivers::gnss::config::Stream_Tcp::MergeFrom(from.tcp()); break; } case kUdp: { mutable_udp()->::apollo::drivers::gnss::config::Stream_Udp::MergeFrom(from.udp()); break; } case kNtrip: { mutable_ntrip()->::apollo::drivers::gnss::config::Stream_Ntrip::MergeFrom(from.ntrip()); break; } case TYPE_NOT_SET: { break; } } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_format()) { set_format(from.format()); } if (from.has_push_location()) { set_push_location(from.push_location()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void Stream::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.Stream) if (&from == this) return; Clear(); MergeFrom(from); } void Stream::CopyFrom(const Stream& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.Stream) if (&from == this) return; Clear(); MergeFrom(from); } bool Stream::IsInitialized() const { return true; } void Stream::Swap(Stream* other) { if (other == this) return; InternalSwap(other); } void Stream::InternalSwap(Stream* other) { std::swap(format_, other->format_); std::swap(push_location_, other->push_location_); std::swap(type_, other->type_); std::swap(_oneof_case_[0], other->_oneof_case_[0]); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Stream::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Stream_descriptor_; metadata.reflection = Stream_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Stream_Serial // optional bytes device = 1; bool Stream_Serial::has_device() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Stream_Serial::set_has_device() { _has_bits_[0] |= 0x00000001u; } void Stream_Serial::clear_has_device() { _has_bits_[0] &= ~0x00000001u; } void Stream_Serial::clear_device() { device_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_device(); } const ::std::string& Stream_Serial::device() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Serial.device) return device_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Serial::set_device(const ::std::string& value) { set_has_device(); device_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Serial.device) } void Stream_Serial::set_device(const char* value) { set_has_device(); device_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Stream.Serial.device) } void Stream_Serial::set_device(const void* value, size_t size) { set_has_device(); device_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Stream.Serial.device) } ::std::string* Stream_Serial::mutable_device() { set_has_device(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.Serial.device) return device_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Stream_Serial::release_device() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.Serial.device) clear_has_device(); return device_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Serial::set_allocated_device(::std::string* device) { if (device != NULL) { set_has_device(); } else { clear_has_device(); } device_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), device); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.Serial.device) } // optional int32 baud_rate = 2 [default = 9600]; bool Stream_Serial::has_baud_rate() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Stream_Serial::set_has_baud_rate() { _has_bits_[0] |= 0x00000002u; } void Stream_Serial::clear_has_baud_rate() { _has_bits_[0] &= ~0x00000002u; } void Stream_Serial::clear_baud_rate() { baud_rate_ = 9600; clear_has_baud_rate(); } ::google::protobuf::int32 Stream_Serial::baud_rate() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Serial.baud_rate) return baud_rate_; } void Stream_Serial::set_baud_rate(::google::protobuf::int32 value) { set_has_baud_rate(); baud_rate_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Serial.baud_rate) } // ------------------------------------------------------------------- // Stream_Tcp // optional bytes address = 1; bool Stream_Tcp::has_address() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Stream_Tcp::set_has_address() { _has_bits_[0] |= 0x00000001u; } void Stream_Tcp::clear_has_address() { _has_bits_[0] &= ~0x00000001u; } void Stream_Tcp::clear_address() { address_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_address(); } const ::std::string& Stream_Tcp::address() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Tcp.address) return address_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Tcp::set_address(const ::std::string& value) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Tcp.address) } void Stream_Tcp::set_address(const char* value) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Stream.Tcp.address) } void Stream_Tcp::set_address(const void* value, size_t size) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Stream.Tcp.address) } ::std::string* Stream_Tcp::mutable_address() { set_has_address(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.Tcp.address) return address_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Stream_Tcp::release_address() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.Tcp.address) clear_has_address(); return address_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Tcp::set_allocated_address(::std::string* address) { if (address != NULL) { set_has_address(); } else { clear_has_address(); } address_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), address); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.Tcp.address) } // optional int32 port = 2 [default = 3001]; bool Stream_Tcp::has_port() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Stream_Tcp::set_has_port() { _has_bits_[0] |= 0x00000002u; } void Stream_Tcp::clear_has_port() { _has_bits_[0] &= ~0x00000002u; } void Stream_Tcp::clear_port() { port_ = 3001; clear_has_port(); } ::google::protobuf::int32 Stream_Tcp::port() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Tcp.port) return port_; } void Stream_Tcp::set_port(::google::protobuf::int32 value) { set_has_port(); port_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Tcp.port) } // ------------------------------------------------------------------- // Stream_Udp // optional bytes address = 1; bool Stream_Udp::has_address() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Stream_Udp::set_has_address() { _has_bits_[0] |= 0x00000001u; } void Stream_Udp::clear_has_address() { _has_bits_[0] &= ~0x00000001u; } void Stream_Udp::clear_address() { address_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_address(); } const ::std::string& Stream_Udp::address() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Udp.address) return address_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Udp::set_address(const ::std::string& value) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Udp.address) } void Stream_Udp::set_address(const char* value) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Stream.Udp.address) } void Stream_Udp::set_address(const void* value, size_t size) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Stream.Udp.address) } ::std::string* Stream_Udp::mutable_address() { set_has_address(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.Udp.address) return address_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Stream_Udp::release_address() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.Udp.address) clear_has_address(); return address_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Udp::set_allocated_address(::std::string* address) { if (address != NULL) { set_has_address(); } else { clear_has_address(); } address_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), address); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.Udp.address) } // optional int32 port = 2 [default = 3001]; bool Stream_Udp::has_port() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Stream_Udp::set_has_port() { _has_bits_[0] |= 0x00000002u; } void Stream_Udp::clear_has_port() { _has_bits_[0] &= ~0x00000002u; } void Stream_Udp::clear_port() { port_ = 3001; clear_has_port(); } ::google::protobuf::int32 Stream_Udp::port() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Udp.port) return port_; } void Stream_Udp::set_port(::google::protobuf::int32 value) { set_has_port(); port_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Udp.port) } // ------------------------------------------------------------------- // Stream_Ntrip // optional bytes address = 1; bool Stream_Ntrip::has_address() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Stream_Ntrip::set_has_address() { _has_bits_[0] |= 0x00000001u; } void Stream_Ntrip::clear_has_address() { _has_bits_[0] &= ~0x00000001u; } void Stream_Ntrip::clear_address() { address_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_address(); } const ::std::string& Stream_Ntrip::address() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Ntrip.address) return address_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_address(const ::std::string& value) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Ntrip.address) } void Stream_Ntrip::set_address(const char* value) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Stream.Ntrip.address) } void Stream_Ntrip::set_address(const void* value, size_t size) { set_has_address(); address_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Stream.Ntrip.address) } ::std::string* Stream_Ntrip::mutable_address() { set_has_address(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.Ntrip.address) return address_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Stream_Ntrip::release_address() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.Ntrip.address) clear_has_address(); return address_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_allocated_address(::std::string* address) { if (address != NULL) { set_has_address(); } else { clear_has_address(); } address_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), address); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.Ntrip.address) } // optional int32 port = 2 [default = 2101]; bool Stream_Ntrip::has_port() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Stream_Ntrip::set_has_port() { _has_bits_[0] |= 0x00000002u; } void Stream_Ntrip::clear_has_port() { _has_bits_[0] &= ~0x00000002u; } void Stream_Ntrip::clear_port() { port_ = 2101; clear_has_port(); } ::google::protobuf::int32 Stream_Ntrip::port() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Ntrip.port) return port_; } void Stream_Ntrip::set_port(::google::protobuf::int32 value) { set_has_port(); port_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Ntrip.port) } // optional bytes mount_point = 3; bool Stream_Ntrip::has_mount_point() const { return (_has_bits_[0] & 0x00000004u) != 0; } void Stream_Ntrip::set_has_mount_point() { _has_bits_[0] |= 0x00000004u; } void Stream_Ntrip::clear_has_mount_point() { _has_bits_[0] &= ~0x00000004u; } void Stream_Ntrip::clear_mount_point() { mount_point_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_mount_point(); } const ::std::string& Stream_Ntrip::mount_point() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Ntrip.mount_point) return mount_point_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_mount_point(const ::std::string& value) { set_has_mount_point(); mount_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Ntrip.mount_point) } void Stream_Ntrip::set_mount_point(const char* value) { set_has_mount_point(); mount_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Stream.Ntrip.mount_point) } void Stream_Ntrip::set_mount_point(const void* value, size_t size) { set_has_mount_point(); mount_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Stream.Ntrip.mount_point) } ::std::string* Stream_Ntrip::mutable_mount_point() { set_has_mount_point(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.Ntrip.mount_point) return mount_point_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Stream_Ntrip::release_mount_point() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.Ntrip.mount_point) clear_has_mount_point(); return mount_point_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_allocated_mount_point(::std::string* mount_point) { if (mount_point != NULL) { set_has_mount_point(); } else { clear_has_mount_point(); } mount_point_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), mount_point); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.Ntrip.mount_point) } // optional bytes user = 4; bool Stream_Ntrip::has_user() const { return (_has_bits_[0] & 0x00000008u) != 0; } void Stream_Ntrip::set_has_user() { _has_bits_[0] |= 0x00000008u; } void Stream_Ntrip::clear_has_user() { _has_bits_[0] &= ~0x00000008u; } void Stream_Ntrip::clear_user() { user_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_user(); } const ::std::string& Stream_Ntrip::user() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Ntrip.user) return user_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_user(const ::std::string& value) { set_has_user(); user_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Ntrip.user) } void Stream_Ntrip::set_user(const char* value) { set_has_user(); user_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Stream.Ntrip.user) } void Stream_Ntrip::set_user(const void* value, size_t size) { set_has_user(); user_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Stream.Ntrip.user) } ::std::string* Stream_Ntrip::mutable_user() { set_has_user(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.Ntrip.user) return user_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Stream_Ntrip::release_user() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.Ntrip.user) clear_has_user(); return user_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_allocated_user(::std::string* user) { if (user != NULL) { set_has_user(); } else { clear_has_user(); } user_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), user); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.Ntrip.user) } // optional bytes password = 5; bool Stream_Ntrip::has_password() const { return (_has_bits_[0] & 0x00000010u) != 0; } void Stream_Ntrip::set_has_password() { _has_bits_[0] |= 0x00000010u; } void Stream_Ntrip::clear_has_password() { _has_bits_[0] &= ~0x00000010u; } void Stream_Ntrip::clear_password() { password_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_password(); } const ::std::string& Stream_Ntrip::password() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Ntrip.password) return password_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_password(const ::std::string& value) { set_has_password(); password_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Ntrip.password) } void Stream_Ntrip::set_password(const char* value) { set_has_password(); password_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Stream.Ntrip.password) } void Stream_Ntrip::set_password(const void* value, size_t size) { set_has_password(); password_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Stream.Ntrip.password) } ::std::string* Stream_Ntrip::mutable_password() { set_has_password(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.Ntrip.password) return password_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Stream_Ntrip::release_password() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.Ntrip.password) clear_has_password(); return password_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Stream_Ntrip::set_allocated_password(::std::string* password) { if (password != NULL) { set_has_password(); } else { clear_has_password(); } password_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), password); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.Ntrip.password) } // optional uint32 timeout_s = 6 [default = 30]; bool Stream_Ntrip::has_timeout_s() const { return (_has_bits_[0] & 0x00000020u) != 0; } void Stream_Ntrip::set_has_timeout_s() { _has_bits_[0] |= 0x00000020u; } void Stream_Ntrip::clear_has_timeout_s() { _has_bits_[0] &= ~0x00000020u; } void Stream_Ntrip::clear_timeout_s() { timeout_s_ = 30u; clear_has_timeout_s(); } ::google::protobuf::uint32 Stream_Ntrip::timeout_s() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.Ntrip.timeout_s) return timeout_s_; } void Stream_Ntrip::set_timeout_s(::google::protobuf::uint32 value) { set_has_timeout_s(); timeout_s_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.Ntrip.timeout_s) } // ------------------------------------------------------------------- // Stream // optional .apollo.drivers.gnss.config.Stream.Format format = 1; bool Stream::has_format() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Stream::set_has_format() { _has_bits_[0] |= 0x00000001u; } void Stream::clear_has_format() { _has_bits_[0] &= ~0x00000001u; } void Stream::clear_format() { format_ = 0; clear_has_format(); } ::apollo::drivers::gnss::config::Stream_Format Stream::format() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.format) return static_cast< ::apollo::drivers::gnss::config::Stream_Format >(format_); } void Stream::set_format(::apollo::drivers::gnss::config::Stream_Format value) { assert(::apollo::drivers::gnss::config::Stream_Format_IsValid(value)); set_has_format(); format_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.format) } // optional .apollo.drivers.gnss.config.Stream.Serial serial = 2; bool Stream::has_serial() const { return type_case() == kSerial; } void Stream::set_has_serial() { _oneof_case_[0] = kSerial; } void Stream::clear_serial() { if (has_serial()) { delete type_.serial_; clear_has_type(); } } const ::apollo::drivers::gnss::config::Stream_Serial& Stream::serial() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.serial) return has_serial() ? *type_.serial_ : ::apollo::drivers::gnss::config::Stream_Serial::default_instance(); } ::apollo::drivers::gnss::config::Stream_Serial* Stream::mutable_serial() { if (!has_serial()) { clear_type(); set_has_serial(); type_.serial_ = new ::apollo::drivers::gnss::config::Stream_Serial; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.serial) return type_.serial_; } ::apollo::drivers::gnss::config::Stream_Serial* Stream::release_serial() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.serial) if (has_serial()) { clear_has_type(); ::apollo::drivers::gnss::config::Stream_Serial* temp = type_.serial_; type_.serial_ = NULL; return temp; } else { return NULL; } } void Stream::set_allocated_serial(::apollo::drivers::gnss::config::Stream_Serial* serial) { clear_type(); if (serial) { set_has_serial(); type_.serial_ = serial; } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.serial) } // optional .apollo.drivers.gnss.config.Stream.Tcp tcp = 3; bool Stream::has_tcp() const { return type_case() == kTcp; } void Stream::set_has_tcp() { _oneof_case_[0] = kTcp; } void Stream::clear_tcp() { if (has_tcp()) { delete type_.tcp_; clear_has_type(); } } const ::apollo::drivers::gnss::config::Stream_Tcp& Stream::tcp() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.tcp) return has_tcp() ? *type_.tcp_ : ::apollo::drivers::gnss::config::Stream_Tcp::default_instance(); } ::apollo::drivers::gnss::config::Stream_Tcp* Stream::mutable_tcp() { if (!has_tcp()) { clear_type(); set_has_tcp(); type_.tcp_ = new ::apollo::drivers::gnss::config::Stream_Tcp; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.tcp) return type_.tcp_; } ::apollo::drivers::gnss::config::Stream_Tcp* Stream::release_tcp() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.tcp) if (has_tcp()) { clear_has_type(); ::apollo::drivers::gnss::config::Stream_Tcp* temp = type_.tcp_; type_.tcp_ = NULL; return temp; } else { return NULL; } } void Stream::set_allocated_tcp(::apollo::drivers::gnss::config::Stream_Tcp* tcp) { clear_type(); if (tcp) { set_has_tcp(); type_.tcp_ = tcp; } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.tcp) } // optional .apollo.drivers.gnss.config.Stream.Udp udp = 4; bool Stream::has_udp() const { return type_case() == kUdp; } void Stream::set_has_udp() { _oneof_case_[0] = kUdp; } void Stream::clear_udp() { if (has_udp()) { delete type_.udp_; clear_has_type(); } } const ::apollo::drivers::gnss::config::Stream_Udp& Stream::udp() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.udp) return has_udp() ? *type_.udp_ : ::apollo::drivers::gnss::config::Stream_Udp::default_instance(); } ::apollo::drivers::gnss::config::Stream_Udp* Stream::mutable_udp() { if (!has_udp()) { clear_type(); set_has_udp(); type_.udp_ = new ::apollo::drivers::gnss::config::Stream_Udp; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.udp) return type_.udp_; } ::apollo::drivers::gnss::config::Stream_Udp* Stream::release_udp() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.udp) if (has_udp()) { clear_has_type(); ::apollo::drivers::gnss::config::Stream_Udp* temp = type_.udp_; type_.udp_ = NULL; return temp; } else { return NULL; } } void Stream::set_allocated_udp(::apollo::drivers::gnss::config::Stream_Udp* udp) { clear_type(); if (udp) { set_has_udp(); type_.udp_ = udp; } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.udp) } // optional .apollo.drivers.gnss.config.Stream.Ntrip ntrip = 5; bool Stream::has_ntrip() const { return type_case() == kNtrip; } void Stream::set_has_ntrip() { _oneof_case_[0] = kNtrip; } void Stream::clear_ntrip() { if (has_ntrip()) { delete type_.ntrip_; clear_has_type(); } } const ::apollo::drivers::gnss::config::Stream_Ntrip& Stream::ntrip() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.ntrip) return has_ntrip() ? *type_.ntrip_ : ::apollo::drivers::gnss::config::Stream_Ntrip::default_instance(); } ::apollo::drivers::gnss::config::Stream_Ntrip* Stream::mutable_ntrip() { if (!has_ntrip()) { clear_type(); set_has_ntrip(); type_.ntrip_ = new ::apollo::drivers::gnss::config::Stream_Ntrip; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Stream.ntrip) return type_.ntrip_; } ::apollo::drivers::gnss::config::Stream_Ntrip* Stream::release_ntrip() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Stream.ntrip) if (has_ntrip()) { clear_has_type(); ::apollo::drivers::gnss::config::Stream_Ntrip* temp = type_.ntrip_; type_.ntrip_ = NULL; return temp; } else { return NULL; } } void Stream::set_allocated_ntrip(::apollo::drivers::gnss::config::Stream_Ntrip* ntrip) { clear_type(); if (ntrip) { set_has_ntrip(); type_.ntrip_ = ntrip; } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Stream.ntrip) } // optional bool push_location = 6; bool Stream::has_push_location() const { return (_has_bits_[0] & 0x00000020u) != 0; } void Stream::set_has_push_location() { _has_bits_[0] |= 0x00000020u; } void Stream::clear_has_push_location() { _has_bits_[0] &= ~0x00000020u; } void Stream::clear_push_location() { push_location_ = false; clear_has_push_location(); } bool Stream::push_location() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Stream.push_location) return push_location_; } void Stream::set_push_location(bool value) { set_has_push_location(); push_location_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Stream.push_location) } bool Stream::has_type() const { return type_case() != TYPE_NOT_SET; } void Stream::clear_has_type() { _oneof_case_[0] = TYPE_NOT_SET; } Stream::TypeCase Stream::type_case() const { return Stream::TypeCase(_oneof_case_[0]); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int NovatelConfig::kImuOrientationFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 NovatelConfig::NovatelConfig() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.NovatelConfig) } void NovatelConfig::InitAsDefaultInstance() { } NovatelConfig::NovatelConfig(const NovatelConfig& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.NovatelConfig) } void NovatelConfig::SharedCtor() { _cached_size_ = 0; imu_orientation_ = 5; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } NovatelConfig::~NovatelConfig() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.NovatelConfig) SharedDtor(); } void NovatelConfig::SharedDtor() { if (this != default_instance_) { } } void NovatelConfig::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* NovatelConfig::descriptor() { protobuf_AssignDescriptorsOnce(); return NovatelConfig_descriptor_; } const NovatelConfig& NovatelConfig::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } NovatelConfig* NovatelConfig::default_instance_ = NULL; NovatelConfig* NovatelConfig::New(::google::protobuf::Arena* arena) const { NovatelConfig* n = new NovatelConfig; if (arena != NULL) { arena->Own(n); } return n; } void NovatelConfig::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.NovatelConfig) imu_orientation_ = 5; ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool NovatelConfig::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.NovatelConfig) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 imu_orientation = 1 [default = 5]; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &imu_orientation_))); set_has_imu_orientation(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.NovatelConfig) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.NovatelConfig) return false; #undef DO_ } void NovatelConfig::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.NovatelConfig) // optional int32 imu_orientation = 1 [default = 5]; if (has_imu_orientation()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->imu_orientation(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.NovatelConfig) } ::google::protobuf::uint8* NovatelConfig::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.NovatelConfig) // optional int32 imu_orientation = 1 [default = 5]; if (has_imu_orientation()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->imu_orientation(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.NovatelConfig) return target; } int NovatelConfig::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.NovatelConfig) int total_size = 0; // optional int32 imu_orientation = 1 [default = 5]; if (has_imu_orientation()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->imu_orientation()); } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void NovatelConfig::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.NovatelConfig) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const NovatelConfig* source = ::google::protobuf::internal::DynamicCastToGenerated<const NovatelConfig>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.NovatelConfig) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.NovatelConfig) MergeFrom(*source); } } void NovatelConfig::MergeFrom(const NovatelConfig& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.NovatelConfig) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_imu_orientation()) { set_imu_orientation(from.imu_orientation()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void NovatelConfig::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.NovatelConfig) if (&from == this) return; Clear(); MergeFrom(from); } void NovatelConfig::CopyFrom(const NovatelConfig& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.NovatelConfig) if (&from == this) return; Clear(); MergeFrom(from); } bool NovatelConfig::IsInitialized() const { return true; } void NovatelConfig::Swap(NovatelConfig* other) { if (other == this) return; InternalSwap(other); } void NovatelConfig::InternalSwap(NovatelConfig* other) { std::swap(imu_orientation_, other->imu_orientation_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata NovatelConfig::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = NovatelConfig_descriptor_; metadata.reflection = NovatelConfig_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // NovatelConfig // optional int32 imu_orientation = 1 [default = 5]; bool NovatelConfig::has_imu_orientation() const { return (_has_bits_[0] & 0x00000001u) != 0; } void NovatelConfig::set_has_imu_orientation() { _has_bits_[0] |= 0x00000001u; } void NovatelConfig::clear_has_imu_orientation() { _has_bits_[0] &= ~0x00000001u; } void NovatelConfig::clear_imu_orientation() { imu_orientation_ = 5; clear_has_imu_orientation(); } ::google::protobuf::int32 NovatelConfig::imu_orientation() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.NovatelConfig.imu_orientation) return imu_orientation_; } void NovatelConfig::set_imu_orientation(::google::protobuf::int32 value) { set_has_imu_orientation(); imu_orientation_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.NovatelConfig.imu_orientation) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 UbloxConfig::UbloxConfig() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.UbloxConfig) } void UbloxConfig::InitAsDefaultInstance() { } UbloxConfig::UbloxConfig(const UbloxConfig& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.UbloxConfig) } void UbloxConfig::SharedCtor() { _cached_size_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } UbloxConfig::~UbloxConfig() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.UbloxConfig) SharedDtor(); } void UbloxConfig::SharedDtor() { if (this != default_instance_) { } } void UbloxConfig::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* UbloxConfig::descriptor() { protobuf_AssignDescriptorsOnce(); return UbloxConfig_descriptor_; } const UbloxConfig& UbloxConfig::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } UbloxConfig* UbloxConfig::default_instance_ = NULL; UbloxConfig* UbloxConfig::New(::google::protobuf::Arena* arena) const { UbloxConfig* n = new UbloxConfig; if (arena != NULL) { arena->Own(n); } return n; } void UbloxConfig::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.UbloxConfig) ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool UbloxConfig::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.UbloxConfig) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.UbloxConfig) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.UbloxConfig) return false; #undef DO_ } void UbloxConfig::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.UbloxConfig) if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.UbloxConfig) } ::google::protobuf::uint8* UbloxConfig::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.UbloxConfig) if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.UbloxConfig) return target; } int UbloxConfig::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.UbloxConfig) int total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void UbloxConfig::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.UbloxConfig) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const UbloxConfig* source = ::google::protobuf::internal::DynamicCastToGenerated<const UbloxConfig>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.UbloxConfig) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.UbloxConfig) MergeFrom(*source); } } void UbloxConfig::MergeFrom(const UbloxConfig& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.UbloxConfig) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void UbloxConfig::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.UbloxConfig) if (&from == this) return; Clear(); MergeFrom(from); } void UbloxConfig::CopyFrom(const UbloxConfig& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.UbloxConfig) if (&from == this) return; Clear(); MergeFrom(from); } bool UbloxConfig::IsInitialized() const { return true; } void UbloxConfig::Swap(UbloxConfig* other) { if (other == this) return; InternalSwap(other); } void UbloxConfig::InternalSwap(UbloxConfig* other) { _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata UbloxConfig::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = UbloxConfig_descriptor_; metadata.reflection = UbloxConfig_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // UbloxConfig #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== ::std::string* TF::_default_frame_id_ = NULL; ::std::string* TF::_default_child_frame_id_ = NULL; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int TF::kFrameIdFieldNumber; const int TF::kChildFrameIdFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 TF::TF() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.TF) } void TF::InitAsDefaultInstance() { } TF::TF(const TF& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.TF) } void TF::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; frame_id_.UnsafeSetDefault(_default_frame_id_); child_frame_id_.UnsafeSetDefault(_default_child_frame_id_); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } TF::~TF() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.TF) SharedDtor(); } void TF::SharedDtor() { frame_id_.DestroyNoArena(_default_frame_id_); child_frame_id_.DestroyNoArena(_default_child_frame_id_); if (this != default_instance_) { } } void TF::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* TF::descriptor() { protobuf_AssignDescriptorsOnce(); return TF_descriptor_; } const TF& TF::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } TF* TF::default_instance_ = NULL; TF* TF::New(::google::protobuf::Arena* arena) const { TF* n = new TF; if (arena != NULL) { arena->Own(n); } return n; } void TF::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.TF) if (_has_bits_[0 / 32] & 3u) { if (has_frame_id()) { frame_id_.ClearToDefaultNoArena(_default_frame_id_); } if (has_child_frame_id()) { child_frame_id_.ClearToDefaultNoArena(_default_child_frame_id_); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool TF::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.TF) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string frame_id = 1 [default = "world"]; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_frame_id())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->frame_id().data(), this->frame_id().length(), ::google::protobuf::internal::WireFormat::PARSE, "apollo.drivers.gnss.config.TF.frame_id"); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_child_frame_id; break; } // optional string child_frame_id = 2 [default = "novatel"]; case 2: { if (tag == 18) { parse_child_frame_id: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_child_frame_id())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->child_frame_id().data(), this->child_frame_id().length(), ::google::protobuf::internal::WireFormat::PARSE, "apollo.drivers.gnss.config.TF.child_frame_id"); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.TF) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.TF) return false; #undef DO_ } void TF::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.TF) // optional string frame_id = 1 [default = "world"]; if (has_frame_id()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->frame_id().data(), this->frame_id().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.TF.frame_id"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->frame_id(), output); } // optional string child_frame_id = 2 [default = "novatel"]; if (has_child_frame_id()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->child_frame_id().data(), this->child_frame_id().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.TF.child_frame_id"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->child_frame_id(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.TF) } ::google::protobuf::uint8* TF::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.TF) // optional string frame_id = 1 [default = "world"]; if (has_frame_id()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->frame_id().data(), this->frame_id().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.TF.frame_id"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->frame_id(), target); } // optional string child_frame_id = 2 [default = "novatel"]; if (has_child_frame_id()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->child_frame_id().data(), this->child_frame_id().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.TF.child_frame_id"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->child_frame_id(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.TF) return target; } int TF::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.TF) int total_size = 0; if (_has_bits_[0 / 32] & 3u) { // optional string frame_id = 1 [default = "world"]; if (has_frame_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->frame_id()); } // optional string child_frame_id = 2 [default = "novatel"]; if (has_child_frame_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->child_frame_id()); } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void TF::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.TF) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const TF* source = ::google::protobuf::internal::DynamicCastToGenerated<const TF>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.TF) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.TF) MergeFrom(*source); } } void TF::MergeFrom(const TF& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.TF) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_frame_id()) { set_has_frame_id(); frame_id_.AssignWithDefault(_default_frame_id_, from.frame_id_); } if (from.has_child_frame_id()) { set_has_child_frame_id(); child_frame_id_.AssignWithDefault(_default_child_frame_id_, from.child_frame_id_); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void TF::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.TF) if (&from == this) return; Clear(); MergeFrom(from); } void TF::CopyFrom(const TF& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.TF) if (&from == this) return; Clear(); MergeFrom(from); } bool TF::IsInitialized() const { return true; } void TF::Swap(TF* other) { if (other == this) return; InternalSwap(other); } void TF::InternalSwap(TF* other) { frame_id_.Swap(&other->frame_id_); child_frame_id_.Swap(&other->child_frame_id_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata TF::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = TF_descriptor_; metadata.reflection = TF_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // TF // optional string frame_id = 1 [default = "world"]; bool TF::has_frame_id() const { return (_has_bits_[0] & 0x00000001u) != 0; } void TF::set_has_frame_id() { _has_bits_[0] |= 0x00000001u; } void TF::clear_has_frame_id() { _has_bits_[0] &= ~0x00000001u; } void TF::clear_frame_id() { frame_id_.ClearToDefaultNoArena(_default_frame_id_); clear_has_frame_id(); } const ::std::string& TF::frame_id() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.TF.frame_id) return frame_id_.GetNoArena(_default_frame_id_); } void TF::set_frame_id(const ::std::string& value) { set_has_frame_id(); frame_id_.SetNoArena(_default_frame_id_, value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.TF.frame_id) } void TF::set_frame_id(const char* value) { set_has_frame_id(); frame_id_.SetNoArena(_default_frame_id_, ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.TF.frame_id) } void TF::set_frame_id(const char* value, size_t size) { set_has_frame_id(); frame_id_.SetNoArena(_default_frame_id_, ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.TF.frame_id) } ::std::string* TF::mutable_frame_id() { set_has_frame_id(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.TF.frame_id) return frame_id_.MutableNoArena(_default_frame_id_); } ::std::string* TF::release_frame_id() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.TF.frame_id) clear_has_frame_id(); return frame_id_.ReleaseNoArena(_default_frame_id_); } void TF::set_allocated_frame_id(::std::string* frame_id) { if (frame_id != NULL) { set_has_frame_id(); } else { clear_has_frame_id(); } frame_id_.SetAllocatedNoArena(_default_frame_id_, frame_id); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.TF.frame_id) } // optional string child_frame_id = 2 [default = "novatel"]; bool TF::has_child_frame_id() const { return (_has_bits_[0] & 0x00000002u) != 0; } void TF::set_has_child_frame_id() { _has_bits_[0] |= 0x00000002u; } void TF::clear_has_child_frame_id() { _has_bits_[0] &= ~0x00000002u; } void TF::clear_child_frame_id() { child_frame_id_.ClearToDefaultNoArena(_default_child_frame_id_); clear_has_child_frame_id(); } const ::std::string& TF::child_frame_id() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.TF.child_frame_id) return child_frame_id_.GetNoArena(_default_child_frame_id_); } void TF::set_child_frame_id(const ::std::string& value) { set_has_child_frame_id(); child_frame_id_.SetNoArena(_default_child_frame_id_, value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.TF.child_frame_id) } void TF::set_child_frame_id(const char* value) { set_has_child_frame_id(); child_frame_id_.SetNoArena(_default_child_frame_id_, ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.TF.child_frame_id) } void TF::set_child_frame_id(const char* value, size_t size) { set_has_child_frame_id(); child_frame_id_.SetNoArena(_default_child_frame_id_, ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.TF.child_frame_id) } ::std::string* TF::mutable_child_frame_id() { set_has_child_frame_id(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.TF.child_frame_id) return child_frame_id_.MutableNoArena(_default_child_frame_id_); } ::std::string* TF::release_child_frame_id() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.TF.child_frame_id) clear_has_child_frame_id(); return child_frame_id_.ReleaseNoArena(_default_child_frame_id_); } void TF::set_allocated_child_frame_id(::std::string* child_frame_id) { if (child_frame_id != NULL) { set_has_child_frame_id(); } else { clear_has_child_frame_id(); } child_frame_id_.SetAllocatedNoArena(_default_child_frame_id_, child_frame_id); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.TF.child_frame_id) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== const ::google::protobuf::EnumDescriptor* Config_RtkSolutionType_descriptor() { protobuf_AssignDescriptorsOnce(); return Config_RtkSolutionType_descriptor_; } bool Config_RtkSolutionType_IsValid(int value) { switch(value) { case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const Config_RtkSolutionType Config::RTK_RECEIVER_SOLUTION; const Config_RtkSolutionType Config::RTK_SOFTWARE_SOLUTION; const Config_RtkSolutionType Config::RtkSolutionType_MIN; const Config_RtkSolutionType Config::RtkSolutionType_MAX; const int Config::RtkSolutionType_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Config::kDataFieldNumber; const int Config::kCommandFieldNumber; const int Config::kRtkFromFieldNumber; const int Config::kRtkToFieldNumber; const int Config::kLoginCommandsFieldNumber; const int Config::kLogoutCommandsFieldNumber; const int Config::kNovatelConfigFieldNumber; const int Config::kUbloxConfigFieldNumber; const int Config::kRtkSolutionTypeFieldNumber; const int Config::kImuTypeFieldNumber; const int Config::kProj4TextFieldNumber; const int Config::kTfFieldNumber; const int Config::kWheelParametersFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Config::Config() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.drivers.gnss.config.Config) } void Config::InitAsDefaultInstance() { data_ = const_cast< ::apollo::drivers::gnss::config::Stream*>(&::apollo::drivers::gnss::config::Stream::default_instance()); command_ = const_cast< ::apollo::drivers::gnss::config::Stream*>(&::apollo::drivers::gnss::config::Stream::default_instance()); rtk_from_ = const_cast< ::apollo::drivers::gnss::config::Stream*>(&::apollo::drivers::gnss::config::Stream::default_instance()); rtk_to_ = const_cast< ::apollo::drivers::gnss::config::Stream*>(&::apollo::drivers::gnss::config::Stream::default_instance()); Config_default_oneof_instance_->novatel_config_ = const_cast< ::apollo::drivers::gnss::config::NovatelConfig*>(&::apollo::drivers::gnss::config::NovatelConfig::default_instance()); Config_default_oneof_instance_->ublox_config_ = const_cast< ::apollo::drivers::gnss::config::UbloxConfig*>(&::apollo::drivers::gnss::config::UbloxConfig::default_instance()); tf_ = const_cast< ::apollo::drivers::gnss::config::TF*>(&::apollo::drivers::gnss::config::TF::default_instance()); } Config::Config(const Config& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.drivers.gnss.config.Config) } void Config::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; data_ = NULL; command_ = NULL; rtk_from_ = NULL; rtk_to_ = NULL; rtk_solution_type_ = 1; imu_type_ = 13; proj4_text_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); tf_ = NULL; wheel_parameters_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(_has_bits_, 0, sizeof(_has_bits_)); clear_has_device_config(); } Config::~Config() { // @@protoc_insertion_point(destructor:apollo.drivers.gnss.config.Config) SharedDtor(); } void Config::SharedDtor() { proj4_text_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); wheel_parameters_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (has_device_config()) { clear_device_config(); } if (this != default_instance_) { delete data_; delete command_; delete rtk_from_; delete rtk_to_; delete tf_; } } void Config::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Config::descriptor() { protobuf_AssignDescriptorsOnce(); return Config_descriptor_; } const Config& Config::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_drivers_2fgnss_2fconfig_2eproto(); return *default_instance_; } Config* Config::default_instance_ = NULL; Config* Config::New(::google::protobuf::Arena* arena) const { Config* n = new Config; if (arena != NULL) { arena->Own(n); } return n; } void Config::clear_device_config() { // @@protoc_insertion_point(one_of_clear_start:apollo.drivers.gnss.config.Config) switch(device_config_case()) { case kNovatelConfig: { delete device_config_.novatel_config_; break; } case kUbloxConfig: { delete device_config_.ublox_config_; break; } case DEVICE_CONFIG_NOT_SET: { break; } } _oneof_case_[0] = DEVICE_CONFIG_NOT_SET; } void Config::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.drivers.gnss.config.Config) if (_has_bits_[0 / 32] & 15u) { if (has_data()) { if (data_ != NULL) data_->::apollo::drivers::gnss::config::Stream::Clear(); } if (has_command()) { if (command_ != NULL) command_->::apollo::drivers::gnss::config::Stream::Clear(); } if (has_rtk_from()) { if (rtk_from_ != NULL) rtk_from_->::apollo::drivers::gnss::config::Stream::Clear(); } if (has_rtk_to()) { if (rtk_to_ != NULL) rtk_to_->::apollo::drivers::gnss::config::Stream::Clear(); } } if (_has_bits_[8 / 32] & 7936u) { rtk_solution_type_ = 1; imu_type_ = 13; if (has_proj4_text()) { proj4_text_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } if (has_tf()) { if (tf_ != NULL) tf_->::apollo::drivers::gnss::config::TF::Clear(); } if (has_wheel_parameters()) { wheel_parameters_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } } login_commands_.Clear(); logout_commands_.Clear(); clear_device_config(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool Config::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.drivers.gnss.config.Config) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .apollo.drivers.gnss.config.Stream data = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_data())); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_command; break; } // optional .apollo.drivers.gnss.config.Stream command = 2; case 2: { if (tag == 18) { parse_command: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_command())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_rtk_from; break; } // optional .apollo.drivers.gnss.config.Stream rtk_from = 3; case 3: { if (tag == 26) { parse_rtk_from: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_rtk_from())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_rtk_to; break; } // optional .apollo.drivers.gnss.config.Stream rtk_to = 4; case 4: { if (tag == 34) { parse_rtk_to: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_rtk_to())); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_login_commands; break; } // repeated bytes login_commands = 5; case 5: { if (tag == 42) { parse_login_commands: DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->add_login_commands())); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_login_commands; if (input->ExpectTag(50)) goto parse_logout_commands; break; } // repeated bytes logout_commands = 6; case 6: { if (tag == 50) { parse_logout_commands: DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->add_logout_commands())); } else { goto handle_unusual; } if (input->ExpectTag(50)) goto parse_logout_commands; if (input->ExpectTag(58)) goto parse_novatel_config; break; } // optional .apollo.drivers.gnss.config.NovatelConfig novatel_config = 7; case 7: { if (tag == 58) { parse_novatel_config: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_novatel_config())); } else { goto handle_unusual; } if (input->ExpectTag(66)) goto parse_ublox_config; break; } // optional .apollo.drivers.gnss.config.UbloxConfig ublox_config = 8; case 8: { if (tag == 66) { parse_ublox_config: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_ublox_config())); } else { goto handle_unusual; } if (input->ExpectTag(72)) goto parse_rtk_solution_type; break; } // optional .apollo.drivers.gnss.config.Config.RtkSolutionType rtk_solution_type = 9; case 9: { if (tag == 72) { parse_rtk_solution_type: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::drivers::gnss::config::Config_RtkSolutionType_IsValid(value)) { set_rtk_solution_type(static_cast< ::apollo::drivers::gnss::config::Config_RtkSolutionType >(value)); } else { mutable_unknown_fields()->AddVarint(9, value); } } else { goto handle_unusual; } if (input->ExpectTag(80)) goto parse_imu_type; break; } // optional .apollo.drivers.gnss.config.ImuType imu_type = 10; case 10: { if (tag == 80) { parse_imu_type: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::drivers::gnss::config::ImuType_IsValid(value)) { set_imu_type(static_cast< ::apollo::drivers::gnss::config::ImuType >(value)); } else { mutable_unknown_fields()->AddVarint(10, value); } } else { goto handle_unusual; } if (input->ExpectTag(90)) goto parse_proj4_text; break; } // optional string proj4_text = 11; case 11: { if (tag == 90) { parse_proj4_text: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_proj4_text())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->proj4_text().data(), this->proj4_text().length(), ::google::protobuf::internal::WireFormat::PARSE, "apollo.drivers.gnss.config.Config.proj4_text"); } else { goto handle_unusual; } if (input->ExpectTag(98)) goto parse_tf; break; } // optional .apollo.drivers.gnss.config.TF tf = 12; case 12: { if (tag == 98) { parse_tf: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_tf())); } else { goto handle_unusual; } if (input->ExpectTag(106)) goto parse_wheel_parameters; break; } // optional string wheel_parameters = 13; case 13: { if (tag == 106) { parse_wheel_parameters: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_wheel_parameters())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->wheel_parameters().data(), this->wheel_parameters().length(), ::google::protobuf::internal::WireFormat::PARSE, "apollo.drivers.gnss.config.Config.wheel_parameters"); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.drivers.gnss.config.Config) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.drivers.gnss.config.Config) return false; #undef DO_ } void Config::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.drivers.gnss.config.Config) // optional .apollo.drivers.gnss.config.Stream data = 1; if (has_data()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->data_, output); } // optional .apollo.drivers.gnss.config.Stream command = 2; if (has_command()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->command_, output); } // optional .apollo.drivers.gnss.config.Stream rtk_from = 3; if (has_rtk_from()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, *this->rtk_from_, output); } // optional .apollo.drivers.gnss.config.Stream rtk_to = 4; if (has_rtk_to()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->rtk_to_, output); } // repeated bytes login_commands = 5; for (int i = 0; i < this->login_commands_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 5, this->login_commands(i), output); } // repeated bytes logout_commands = 6; for (int i = 0; i < this->logout_commands_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 6, this->logout_commands(i), output); } // optional .apollo.drivers.gnss.config.NovatelConfig novatel_config = 7; if (has_novatel_config()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 7, *device_config_.novatel_config_, output); } // optional .apollo.drivers.gnss.config.UbloxConfig ublox_config = 8; if (has_ublox_config()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 8, *device_config_.ublox_config_, output); } // optional .apollo.drivers.gnss.config.Config.RtkSolutionType rtk_solution_type = 9; if (has_rtk_solution_type()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 9, this->rtk_solution_type(), output); } // optional .apollo.drivers.gnss.config.ImuType imu_type = 10; if (has_imu_type()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 10, this->imu_type(), output); } // optional string proj4_text = 11; if (has_proj4_text()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->proj4_text().data(), this->proj4_text().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.Config.proj4_text"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 11, this->proj4_text(), output); } // optional .apollo.drivers.gnss.config.TF tf = 12; if (has_tf()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 12, *this->tf_, output); } // optional string wheel_parameters = 13; if (has_wheel_parameters()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->wheel_parameters().data(), this->wheel_parameters().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.Config.wheel_parameters"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 13, this->wheel_parameters(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.drivers.gnss.config.Config) } ::google::protobuf::uint8* Config::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.drivers.gnss.config.Config) // optional .apollo.drivers.gnss.config.Stream data = 1; if (has_data()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *this->data_, false, target); } // optional .apollo.drivers.gnss.config.Stream command = 2; if (has_command()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->command_, false, target); } // optional .apollo.drivers.gnss.config.Stream rtk_from = 3; if (has_rtk_from()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 3, *this->rtk_from_, false, target); } // optional .apollo.drivers.gnss.config.Stream rtk_to = 4; if (has_rtk_to()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *this->rtk_to_, false, target); } // repeated bytes login_commands = 5; for (int i = 0; i < this->login_commands_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteBytesToArray(5, this->login_commands(i), target); } // repeated bytes logout_commands = 6; for (int i = 0; i < this->logout_commands_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteBytesToArray(6, this->logout_commands(i), target); } // optional .apollo.drivers.gnss.config.NovatelConfig novatel_config = 7; if (has_novatel_config()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 7, *device_config_.novatel_config_, false, target); } // optional .apollo.drivers.gnss.config.UbloxConfig ublox_config = 8; if (has_ublox_config()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 8, *device_config_.ublox_config_, false, target); } // optional .apollo.drivers.gnss.config.Config.RtkSolutionType rtk_solution_type = 9; if (has_rtk_solution_type()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 9, this->rtk_solution_type(), target); } // optional .apollo.drivers.gnss.config.ImuType imu_type = 10; if (has_imu_type()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 10, this->imu_type(), target); } // optional string proj4_text = 11; if (has_proj4_text()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->proj4_text().data(), this->proj4_text().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.Config.proj4_text"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 11, this->proj4_text(), target); } // optional .apollo.drivers.gnss.config.TF tf = 12; if (has_tf()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 12, *this->tf_, false, target); } // optional string wheel_parameters = 13; if (has_wheel_parameters()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->wheel_parameters().data(), this->wheel_parameters().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "apollo.drivers.gnss.config.Config.wheel_parameters"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 13, this->wheel_parameters(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.drivers.gnss.config.Config) return target; } int Config::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.drivers.gnss.config.Config) int total_size = 0; if (_has_bits_[0 / 32] & 15u) { // optional .apollo.drivers.gnss.config.Stream data = 1; if (has_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->data_); } // optional .apollo.drivers.gnss.config.Stream command = 2; if (has_command()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->command_); } // optional .apollo.drivers.gnss.config.Stream rtk_from = 3; if (has_rtk_from()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->rtk_from_); } // optional .apollo.drivers.gnss.config.Stream rtk_to = 4; if (has_rtk_to()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->rtk_to_); } } if (_has_bits_[8 / 32] & 7936u) { // optional .apollo.drivers.gnss.config.Config.RtkSolutionType rtk_solution_type = 9; if (has_rtk_solution_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->rtk_solution_type()); } // optional .apollo.drivers.gnss.config.ImuType imu_type = 10; if (has_imu_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->imu_type()); } // optional string proj4_text = 11; if (has_proj4_text()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->proj4_text()); } // optional .apollo.drivers.gnss.config.TF tf = 12; if (has_tf()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->tf_); } // optional string wheel_parameters = 13; if (has_wheel_parameters()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->wheel_parameters()); } } // repeated bytes login_commands = 5; total_size += 1 * this->login_commands_size(); for (int i = 0; i < this->login_commands_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::BytesSize( this->login_commands(i)); } // repeated bytes logout_commands = 6; total_size += 1 * this->logout_commands_size(); for (int i = 0; i < this->logout_commands_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::BytesSize( this->logout_commands(i)); } switch (device_config_case()) { // optional .apollo.drivers.gnss.config.NovatelConfig novatel_config = 7; case kNovatelConfig: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *device_config_.novatel_config_); break; } // optional .apollo.drivers.gnss.config.UbloxConfig ublox_config = 8; case kUbloxConfig: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *device_config_.ublox_config_); break; } case DEVICE_CONFIG_NOT_SET: { break; } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Config::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.drivers.gnss.config.Config) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const Config* source = ::google::protobuf::internal::DynamicCastToGenerated<const Config>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.drivers.gnss.config.Config) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.drivers.gnss.config.Config) MergeFrom(*source); } } void Config::MergeFrom(const Config& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.drivers.gnss.config.Config) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } login_commands_.MergeFrom(from.login_commands_); logout_commands_.MergeFrom(from.logout_commands_); switch (from.device_config_case()) { case kNovatelConfig: { mutable_novatel_config()->::apollo::drivers::gnss::config::NovatelConfig::MergeFrom(from.novatel_config()); break; } case kUbloxConfig: { mutable_ublox_config()->::apollo::drivers::gnss::config::UbloxConfig::MergeFrom(from.ublox_config()); break; } case DEVICE_CONFIG_NOT_SET: { break; } } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_data()) { mutable_data()->::apollo::drivers::gnss::config::Stream::MergeFrom(from.data()); } if (from.has_command()) { mutable_command()->::apollo::drivers::gnss::config::Stream::MergeFrom(from.command()); } if (from.has_rtk_from()) { mutable_rtk_from()->::apollo::drivers::gnss::config::Stream::MergeFrom(from.rtk_from()); } if (from.has_rtk_to()) { mutable_rtk_to()->::apollo::drivers::gnss::config::Stream::MergeFrom(from.rtk_to()); } } if (from._has_bits_[8 / 32] & (0xffu << (8 % 32))) { if (from.has_rtk_solution_type()) { set_rtk_solution_type(from.rtk_solution_type()); } if (from.has_imu_type()) { set_imu_type(from.imu_type()); } if (from.has_proj4_text()) { set_has_proj4_text(); proj4_text_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.proj4_text_); } if (from.has_tf()) { mutable_tf()->::apollo::drivers::gnss::config::TF::MergeFrom(from.tf()); } if (from.has_wheel_parameters()) { set_has_wheel_parameters(); wheel_parameters_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.wheel_parameters_); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void Config::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.drivers.gnss.config.Config) if (&from == this) return; Clear(); MergeFrom(from); } void Config::CopyFrom(const Config& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.drivers.gnss.config.Config) if (&from == this) return; Clear(); MergeFrom(from); } bool Config::IsInitialized() const { return true; } void Config::Swap(Config* other) { if (other == this) return; InternalSwap(other); } void Config::InternalSwap(Config* other) { std::swap(data_, other->data_); std::swap(command_, other->command_); std::swap(rtk_from_, other->rtk_from_); std::swap(rtk_to_, other->rtk_to_); login_commands_.UnsafeArenaSwap(&other->login_commands_); logout_commands_.UnsafeArenaSwap(&other->logout_commands_); std::swap(rtk_solution_type_, other->rtk_solution_type_); std::swap(imu_type_, other->imu_type_); proj4_text_.Swap(&other->proj4_text_); std::swap(tf_, other->tf_); wheel_parameters_.Swap(&other->wheel_parameters_); std::swap(device_config_, other->device_config_); std::swap(_oneof_case_[0], other->_oneof_case_[0]); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Config::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Config_descriptor_; metadata.reflection = Config_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Config // optional .apollo.drivers.gnss.config.Stream data = 1; bool Config::has_data() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Config::set_has_data() { _has_bits_[0] |= 0x00000001u; } void Config::clear_has_data() { _has_bits_[0] &= ~0x00000001u; } void Config::clear_data() { if (data_ != NULL) data_->::apollo::drivers::gnss::config::Stream::Clear(); clear_has_data(); } const ::apollo::drivers::gnss::config::Stream& Config::data() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.data) return data_ != NULL ? *data_ : *default_instance_->data_; } ::apollo::drivers::gnss::config::Stream* Config::mutable_data() { set_has_data(); if (data_ == NULL) { data_ = new ::apollo::drivers::gnss::config::Stream; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.data) return data_; } ::apollo::drivers::gnss::config::Stream* Config::release_data() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.data) clear_has_data(); ::apollo::drivers::gnss::config::Stream* temp = data_; data_ = NULL; return temp; } void Config::set_allocated_data(::apollo::drivers::gnss::config::Stream* data) { delete data_; data_ = data; if (data) { set_has_data(); } else { clear_has_data(); } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.data) } // optional .apollo.drivers.gnss.config.Stream command = 2; bool Config::has_command() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Config::set_has_command() { _has_bits_[0] |= 0x00000002u; } void Config::clear_has_command() { _has_bits_[0] &= ~0x00000002u; } void Config::clear_command() { if (command_ != NULL) command_->::apollo::drivers::gnss::config::Stream::Clear(); clear_has_command(); } const ::apollo::drivers::gnss::config::Stream& Config::command() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.command) return command_ != NULL ? *command_ : *default_instance_->command_; } ::apollo::drivers::gnss::config::Stream* Config::mutable_command() { set_has_command(); if (command_ == NULL) { command_ = new ::apollo::drivers::gnss::config::Stream; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.command) return command_; } ::apollo::drivers::gnss::config::Stream* Config::release_command() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.command) clear_has_command(); ::apollo::drivers::gnss::config::Stream* temp = command_; command_ = NULL; return temp; } void Config::set_allocated_command(::apollo::drivers::gnss::config::Stream* command) { delete command_; command_ = command; if (command) { set_has_command(); } else { clear_has_command(); } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.command) } // optional .apollo.drivers.gnss.config.Stream rtk_from = 3; bool Config::has_rtk_from() const { return (_has_bits_[0] & 0x00000004u) != 0; } void Config::set_has_rtk_from() { _has_bits_[0] |= 0x00000004u; } void Config::clear_has_rtk_from() { _has_bits_[0] &= ~0x00000004u; } void Config::clear_rtk_from() { if (rtk_from_ != NULL) rtk_from_->::apollo::drivers::gnss::config::Stream::Clear(); clear_has_rtk_from(); } const ::apollo::drivers::gnss::config::Stream& Config::rtk_from() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.rtk_from) return rtk_from_ != NULL ? *rtk_from_ : *default_instance_->rtk_from_; } ::apollo::drivers::gnss::config::Stream* Config::mutable_rtk_from() { set_has_rtk_from(); if (rtk_from_ == NULL) { rtk_from_ = new ::apollo::drivers::gnss::config::Stream; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.rtk_from) return rtk_from_; } ::apollo::drivers::gnss::config::Stream* Config::release_rtk_from() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.rtk_from) clear_has_rtk_from(); ::apollo::drivers::gnss::config::Stream* temp = rtk_from_; rtk_from_ = NULL; return temp; } void Config::set_allocated_rtk_from(::apollo::drivers::gnss::config::Stream* rtk_from) { delete rtk_from_; rtk_from_ = rtk_from; if (rtk_from) { set_has_rtk_from(); } else { clear_has_rtk_from(); } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.rtk_from) } // optional .apollo.drivers.gnss.config.Stream rtk_to = 4; bool Config::has_rtk_to() const { return (_has_bits_[0] & 0x00000008u) != 0; } void Config::set_has_rtk_to() { _has_bits_[0] |= 0x00000008u; } void Config::clear_has_rtk_to() { _has_bits_[0] &= ~0x00000008u; } void Config::clear_rtk_to() { if (rtk_to_ != NULL) rtk_to_->::apollo::drivers::gnss::config::Stream::Clear(); clear_has_rtk_to(); } const ::apollo::drivers::gnss::config::Stream& Config::rtk_to() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.rtk_to) return rtk_to_ != NULL ? *rtk_to_ : *default_instance_->rtk_to_; } ::apollo::drivers::gnss::config::Stream* Config::mutable_rtk_to() { set_has_rtk_to(); if (rtk_to_ == NULL) { rtk_to_ = new ::apollo::drivers::gnss::config::Stream; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.rtk_to) return rtk_to_; } ::apollo::drivers::gnss::config::Stream* Config::release_rtk_to() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.rtk_to) clear_has_rtk_to(); ::apollo::drivers::gnss::config::Stream* temp = rtk_to_; rtk_to_ = NULL; return temp; } void Config::set_allocated_rtk_to(::apollo::drivers::gnss::config::Stream* rtk_to) { delete rtk_to_; rtk_to_ = rtk_to; if (rtk_to) { set_has_rtk_to(); } else { clear_has_rtk_to(); } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.rtk_to) } // repeated bytes login_commands = 5; int Config::login_commands_size() const { return login_commands_.size(); } void Config::clear_login_commands() { login_commands_.Clear(); } const ::std::string& Config::login_commands(int index) const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.login_commands) return login_commands_.Get(index); } ::std::string* Config::mutable_login_commands(int index) { // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.login_commands) return login_commands_.Mutable(index); } void Config::set_login_commands(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Config.login_commands) login_commands_.Mutable(index)->assign(value); } void Config::set_login_commands(int index, const char* value) { login_commands_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Config.login_commands) } void Config::set_login_commands(int index, const void* value, size_t size) { login_commands_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Config.login_commands) } ::std::string* Config::add_login_commands() { // @@protoc_insertion_point(field_add_mutable:apollo.drivers.gnss.config.Config.login_commands) return login_commands_.Add(); } void Config::add_login_commands(const ::std::string& value) { login_commands_.Add()->assign(value); // @@protoc_insertion_point(field_add:apollo.drivers.gnss.config.Config.login_commands) } void Config::add_login_commands(const char* value) { login_commands_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:apollo.drivers.gnss.config.Config.login_commands) } void Config::add_login_commands(const void* value, size_t size) { login_commands_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:apollo.drivers.gnss.config.Config.login_commands) } const ::google::protobuf::RepeatedPtrField< ::std::string>& Config::login_commands() const { // @@protoc_insertion_point(field_list:apollo.drivers.gnss.config.Config.login_commands) return login_commands_; } ::google::protobuf::RepeatedPtrField< ::std::string>* Config::mutable_login_commands() { // @@protoc_insertion_point(field_mutable_list:apollo.drivers.gnss.config.Config.login_commands) return &login_commands_; } // repeated bytes logout_commands = 6; int Config::logout_commands_size() const { return logout_commands_.size(); } void Config::clear_logout_commands() { logout_commands_.Clear(); } const ::std::string& Config::logout_commands(int index) const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.logout_commands) return logout_commands_.Get(index); } ::std::string* Config::mutable_logout_commands(int index) { // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.logout_commands) return logout_commands_.Mutable(index); } void Config::set_logout_commands(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Config.logout_commands) logout_commands_.Mutable(index)->assign(value); } void Config::set_logout_commands(int index, const char* value) { logout_commands_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Config.logout_commands) } void Config::set_logout_commands(int index, const void* value, size_t size) { logout_commands_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Config.logout_commands) } ::std::string* Config::add_logout_commands() { // @@protoc_insertion_point(field_add_mutable:apollo.drivers.gnss.config.Config.logout_commands) return logout_commands_.Add(); } void Config::add_logout_commands(const ::std::string& value) { logout_commands_.Add()->assign(value); // @@protoc_insertion_point(field_add:apollo.drivers.gnss.config.Config.logout_commands) } void Config::add_logout_commands(const char* value) { logout_commands_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:apollo.drivers.gnss.config.Config.logout_commands) } void Config::add_logout_commands(const void* value, size_t size) { logout_commands_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:apollo.drivers.gnss.config.Config.logout_commands) } const ::google::protobuf::RepeatedPtrField< ::std::string>& Config::logout_commands() const { // @@protoc_insertion_point(field_list:apollo.drivers.gnss.config.Config.logout_commands) return logout_commands_; } ::google::protobuf::RepeatedPtrField< ::std::string>* Config::mutable_logout_commands() { // @@protoc_insertion_point(field_mutable_list:apollo.drivers.gnss.config.Config.logout_commands) return &logout_commands_; } // optional .apollo.drivers.gnss.config.NovatelConfig novatel_config = 7; bool Config::has_novatel_config() const { return device_config_case() == kNovatelConfig; } void Config::set_has_novatel_config() { _oneof_case_[0] = kNovatelConfig; } void Config::clear_novatel_config() { if (has_novatel_config()) { delete device_config_.novatel_config_; clear_has_device_config(); } } const ::apollo::drivers::gnss::config::NovatelConfig& Config::novatel_config() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.novatel_config) return has_novatel_config() ? *device_config_.novatel_config_ : ::apollo::drivers::gnss::config::NovatelConfig::default_instance(); } ::apollo::drivers::gnss::config::NovatelConfig* Config::mutable_novatel_config() { if (!has_novatel_config()) { clear_device_config(); set_has_novatel_config(); device_config_.novatel_config_ = new ::apollo::drivers::gnss::config::NovatelConfig; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.novatel_config) return device_config_.novatel_config_; } ::apollo::drivers::gnss::config::NovatelConfig* Config::release_novatel_config() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.novatel_config) if (has_novatel_config()) { clear_has_device_config(); ::apollo::drivers::gnss::config::NovatelConfig* temp = device_config_.novatel_config_; device_config_.novatel_config_ = NULL; return temp; } else { return NULL; } } void Config::set_allocated_novatel_config(::apollo::drivers::gnss::config::NovatelConfig* novatel_config) { clear_device_config(); if (novatel_config) { set_has_novatel_config(); device_config_.novatel_config_ = novatel_config; } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.novatel_config) } // optional .apollo.drivers.gnss.config.UbloxConfig ublox_config = 8; bool Config::has_ublox_config() const { return device_config_case() == kUbloxConfig; } void Config::set_has_ublox_config() { _oneof_case_[0] = kUbloxConfig; } void Config::clear_ublox_config() { if (has_ublox_config()) { delete device_config_.ublox_config_; clear_has_device_config(); } } const ::apollo::drivers::gnss::config::UbloxConfig& Config::ublox_config() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.ublox_config) return has_ublox_config() ? *device_config_.ublox_config_ : ::apollo::drivers::gnss::config::UbloxConfig::default_instance(); } ::apollo::drivers::gnss::config::UbloxConfig* Config::mutable_ublox_config() { if (!has_ublox_config()) { clear_device_config(); set_has_ublox_config(); device_config_.ublox_config_ = new ::apollo::drivers::gnss::config::UbloxConfig; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.ublox_config) return device_config_.ublox_config_; } ::apollo::drivers::gnss::config::UbloxConfig* Config::release_ublox_config() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.ublox_config) if (has_ublox_config()) { clear_has_device_config(); ::apollo::drivers::gnss::config::UbloxConfig* temp = device_config_.ublox_config_; device_config_.ublox_config_ = NULL; return temp; } else { return NULL; } } void Config::set_allocated_ublox_config(::apollo::drivers::gnss::config::UbloxConfig* ublox_config) { clear_device_config(); if (ublox_config) { set_has_ublox_config(); device_config_.ublox_config_ = ublox_config; } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.ublox_config) } // optional .apollo.drivers.gnss.config.Config.RtkSolutionType rtk_solution_type = 9; bool Config::has_rtk_solution_type() const { return (_has_bits_[0] & 0x00000100u) != 0; } void Config::set_has_rtk_solution_type() { _has_bits_[0] |= 0x00000100u; } void Config::clear_has_rtk_solution_type() { _has_bits_[0] &= ~0x00000100u; } void Config::clear_rtk_solution_type() { rtk_solution_type_ = 1; clear_has_rtk_solution_type(); } ::apollo::drivers::gnss::config::Config_RtkSolutionType Config::rtk_solution_type() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.rtk_solution_type) return static_cast< ::apollo::drivers::gnss::config::Config_RtkSolutionType >(rtk_solution_type_); } void Config::set_rtk_solution_type(::apollo::drivers::gnss::config::Config_RtkSolutionType value) { assert(::apollo::drivers::gnss::config::Config_RtkSolutionType_IsValid(value)); set_has_rtk_solution_type(); rtk_solution_type_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Config.rtk_solution_type) } // optional .apollo.drivers.gnss.config.ImuType imu_type = 10; bool Config::has_imu_type() const { return (_has_bits_[0] & 0x00000200u) != 0; } void Config::set_has_imu_type() { _has_bits_[0] |= 0x00000200u; } void Config::clear_has_imu_type() { _has_bits_[0] &= ~0x00000200u; } void Config::clear_imu_type() { imu_type_ = 13; clear_has_imu_type(); } ::apollo::drivers::gnss::config::ImuType Config::imu_type() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.imu_type) return static_cast< ::apollo::drivers::gnss::config::ImuType >(imu_type_); } void Config::set_imu_type(::apollo::drivers::gnss::config::ImuType value) { assert(::apollo::drivers::gnss::config::ImuType_IsValid(value)); set_has_imu_type(); imu_type_ = value; // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Config.imu_type) } // optional string proj4_text = 11; bool Config::has_proj4_text() const { return (_has_bits_[0] & 0x00000400u) != 0; } void Config::set_has_proj4_text() { _has_bits_[0] |= 0x00000400u; } void Config::clear_has_proj4_text() { _has_bits_[0] &= ~0x00000400u; } void Config::clear_proj4_text() { proj4_text_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_proj4_text(); } const ::std::string& Config::proj4_text() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.proj4_text) return proj4_text_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Config::set_proj4_text(const ::std::string& value) { set_has_proj4_text(); proj4_text_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Config.proj4_text) } void Config::set_proj4_text(const char* value) { set_has_proj4_text(); proj4_text_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Config.proj4_text) } void Config::set_proj4_text(const char* value, size_t size) { set_has_proj4_text(); proj4_text_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Config.proj4_text) } ::std::string* Config::mutable_proj4_text() { set_has_proj4_text(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.proj4_text) return proj4_text_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Config::release_proj4_text() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.proj4_text) clear_has_proj4_text(); return proj4_text_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Config::set_allocated_proj4_text(::std::string* proj4_text) { if (proj4_text != NULL) { set_has_proj4_text(); } else { clear_has_proj4_text(); } proj4_text_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), proj4_text); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.proj4_text) } // optional .apollo.drivers.gnss.config.TF tf = 12; bool Config::has_tf() const { return (_has_bits_[0] & 0x00000800u) != 0; } void Config::set_has_tf() { _has_bits_[0] |= 0x00000800u; } void Config::clear_has_tf() { _has_bits_[0] &= ~0x00000800u; } void Config::clear_tf() { if (tf_ != NULL) tf_->::apollo::drivers::gnss::config::TF::Clear(); clear_has_tf(); } const ::apollo::drivers::gnss::config::TF& Config::tf() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.tf) return tf_ != NULL ? *tf_ : *default_instance_->tf_; } ::apollo::drivers::gnss::config::TF* Config::mutable_tf() { set_has_tf(); if (tf_ == NULL) { tf_ = new ::apollo::drivers::gnss::config::TF; } // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.tf) return tf_; } ::apollo::drivers::gnss::config::TF* Config::release_tf() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.tf) clear_has_tf(); ::apollo::drivers::gnss::config::TF* temp = tf_; tf_ = NULL; return temp; } void Config::set_allocated_tf(::apollo::drivers::gnss::config::TF* tf) { delete tf_; tf_ = tf; if (tf) { set_has_tf(); } else { clear_has_tf(); } // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.tf) } // optional string wheel_parameters = 13; bool Config::has_wheel_parameters() const { return (_has_bits_[0] & 0x00001000u) != 0; } void Config::set_has_wheel_parameters() { _has_bits_[0] |= 0x00001000u; } void Config::clear_has_wheel_parameters() { _has_bits_[0] &= ~0x00001000u; } void Config::clear_wheel_parameters() { wheel_parameters_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_wheel_parameters(); } const ::std::string& Config::wheel_parameters() const { // @@protoc_insertion_point(field_get:apollo.drivers.gnss.config.Config.wheel_parameters) return wheel_parameters_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Config::set_wheel_parameters(const ::std::string& value) { set_has_wheel_parameters(); wheel_parameters_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.drivers.gnss.config.Config.wheel_parameters) } void Config::set_wheel_parameters(const char* value) { set_has_wheel_parameters(); wheel_parameters_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.drivers.gnss.config.Config.wheel_parameters) } void Config::set_wheel_parameters(const char* value, size_t size) { set_has_wheel_parameters(); wheel_parameters_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.drivers.gnss.config.Config.wheel_parameters) } ::std::string* Config::mutable_wheel_parameters() { set_has_wheel_parameters(); // @@protoc_insertion_point(field_mutable:apollo.drivers.gnss.config.Config.wheel_parameters) return wheel_parameters_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* Config::release_wheel_parameters() { // @@protoc_insertion_point(field_release:apollo.drivers.gnss.config.Config.wheel_parameters) clear_has_wheel_parameters(); return wheel_parameters_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Config::set_allocated_wheel_parameters(::std::string* wheel_parameters) { if (wheel_parameters != NULL) { set_has_wheel_parameters(); } else { clear_has_wheel_parameters(); } wheel_parameters_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), wheel_parameters); // @@protoc_insertion_point(field_set_allocated:apollo.drivers.gnss.config.Config.wheel_parameters) } bool Config::has_device_config() const { return device_config_case() != DEVICE_CONFIG_NOT_SET; } void Config::clear_has_device_config() { _oneof_case_[0] = DEVICE_CONFIG_NOT_SET; } Config::DeviceConfigCase Config::device_config_case() const { return Config::DeviceConfigCase(_oneof_case_[0]); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace config } // namespace gnss } // namespace drivers } // namespace apollo // @@protoc_insertion_point(global_scope)
35.72967
182
0.708632
racestart
6febb90829bd8b8634c9783659e63bd7cc044f65
8,968
cpp
C++
Synergy Editor TGC/Synergy Editor/CompileSupport.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
231
2018-01-28T00:06:56.000Z
2022-03-31T21:39:56.000Z
Synergy Editor TGC/Synergy Editor/CompileSupport.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
9
2016-02-10T10:46:16.000Z
2017-12-06T17:27:51.000Z
Synergy Editor TGC/Synergy Editor/CompileSupport.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
66
2018-01-28T21:54:52.000Z
2022-02-16T22:50:57.000Z
#include "StdAfx.h" #include "CompileSupport.h" #include "WriteProject.h" #include "WriteFiles.h" #include "Variables.h" #include "Utilities.h" #include "ReadError.h" #include "MainFrm.h" #include "Settings.h" bool CompileSupport::m_run; bool CompileSupport::m_IsCompiling; CString CompileSupport::m_strHelpFile; void CompileSupport::Compile(bool run) { m_IsCompiling = true; m_run = run; if(Variables::m_IncludeFiles.size() == 0) { AfxMessageBox(_T("There are no files in your project, add a file to your project before attempting to compile")); m_IsCompiling = false; return; } MainFrame* pMainWnd = (MainFrame*)AfxGetMainWnd(); if(Settings::ClearOutputOnCompile) { pMainWnd->ClearOutputText(); } // IRM 20090910 - Give feedback for compilation start. CString str(_T("Compiling project...")); int size = str.GetLength() + 1; TCHAR* msg = new TCHAR[size]; wcscpy_s(msg, size, str); pMainWnd->SendMessage(WM_USER + 3, (WPARAM)msg); pMainWnd->ShowOutput(); #ifndef NONVERBOSEOUTPUTMODE pMainWnd->AddOutputText(_T("------------")); #endif if(!WriteProject::Write(true)) { m_IsCompiling = false; return; } if(!WriteFiles::Write()) { m_IsCompiling = false; return; } if(!Utilities::CheckFileExists(Settings::DBPLocation + L"Compiler\\DBPCompiler.exe")) { AfxMessageBox(_T("Could not find DBPCompiler.exe, the path stored in your registry or settings file is invalid. Please locate the DarkBASIC Professional compiler in the options and ensure DarkBASIC Professional is correctly installed.")); m_IsCompiling = false; return; } // Clean up compiler report file ReadError::CleanUp(); // Construct project execution path CString output = L"Executing " + Settings::DBPLocation + L"Compiler\\DBPCompiler.exe " + Utilities::GetTemporaryPath() + L"Temp.dbpro"; #ifndef NONVERBOSEOUTPUTMODE pMainWnd->AddOutputText(output); #endif AfxBeginThread(CompileThread, pMainWnd); } void CompileSupport::CompileHelp(bool run) { m_IsCompiling = true; m_run = run; MainFrame* pMainWnd = (MainFrame*)AfxGetMainWnd(); if(Settings::ClearOutputOnCompile) { pMainWnd->ClearOutputText(); } pMainWnd->ShowOutput(); #ifndef NONVERBOSEOUTPUTMODE pMainWnd->AddOutputText(_T("------------")); #endif if(!WriteProject::WriteHelp()) { m_IsCompiling = false; return; } if(!WriteFiles::WriteHelp()) { m_IsCompiling = false; return; } if(!Utilities::CheckFileExists(Settings::DBPLocation + L"Compiler\\DBPCompiler.exe")) { AfxMessageBox(_T("Could not find DBPCompiler.exe, the path stored in your registry or settings file is invalid. Please locate the DarkBASIC Professional compiler in the options and ensure DarkBASIC Professional is correctly installed.")); m_IsCompiling = false; return; } // Clean up compiler report file ReadError::CleanUp(); // Construct project execution path CString output = L"Executing " + Settings::DBPLocation + L"Compiler\\DBPCompiler.exe " + Utilities::GetTemporaryPath() + L"Temp.dbpro"; #ifndef NONVERBOSEOUTPUTMODE pMainWnd->AddOutputText(output); #endif AfxBeginThread(CompileThread, pMainWnd); } UINT CompileSupport::CompileThread(LPVOID pParam) { MainFrame* pMainWnd = (MainFrame*)pParam; // Tell status bar the number of lines in the project (max value) pMainWnd->SendMessage(WM_USER + 1, Variables::m_NumberOfLines, 0); // Execute structures STARTUPINFO siStartupInfo; PROCESS_INFORMATION piProcessInfo; // File to run at each stage CString runExe; TCHAR exeAr[MAX_PATH]; // Accelerator flags DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE; if(Settings::AllowCompilerAccelerator) { dwCreationFlags = dwCreationFlags | ABOVE_NORMAL_PRIORITY_CLASS; } // Clear memory ZeroMemory( &siStartupInfo, sizeof(siStartupInfo) ); siStartupInfo.cb = sizeof(siStartupInfo); ZeroMemory( &piProcessInfo, sizeof(piProcessInfo) ); ZeroMemory( &exeAr, sizeof(exeAr) ); // Prepare path runExe = Settings::DBPLocation + L"Compiler\\DBPCompiler.exe Temp.dbpro"; wcscpy_s(exeAr, MAX_PATH, runExe); // leefix - 300908 - ensure compiler does not wipe out HelpFile string CString StoreHelpFileString = m_strHelpFile; // U75 - 231009 - delete EXE if exists before compile // Run if asked and no error (copied from below) if(1) { CString pathRun; if(m_strHelpFile == "") { if(Utilities::ExtractFilename(Variables::m_DBPropertyExe) == Variables::m_DBPropertyExe) { pathRun = Variables::m_ProjectPath; // Exe is in the same location as the project runExe = Variables::m_ProjectPath + Variables::m_DBPropertyExe; } else { if(Utilities::ExtractPath(Variables::m_DBPropertyExe) == Utilities::GetTemporaryPath() ) { char pCurrDir[512]; GetCurrentDirectoryA(512,pCurrDir); pathRun = CString(pCurrDir); runExe = Variables::m_DBPropertyExe; } else { pathRun = Utilities::ExtractPath(Variables::m_DBPropertyExe); runExe = Variables::m_DBPropertyExe; } } } else { pathRun = Utilities::ExtractPath(m_strHelpFile); runExe = Utilities::GetTemporaryPath() + _T("Temp.exe"); } ::DeleteFile ( runExe ); } // Run compiler CreateProcess(NULL, exeAr, 0, 0, FALSE, dwCreationFlags, 0, Utilities::GetTemporaryPath(), &siStartupInfo, &piProcessInfo); if(Settings::AllowReadCompilerStatus) { HANDLE fileMap = NULL; int* fileView = NULL; int lastR = 0; DWORD retVal; while(GetExitCodeProcess(piProcessInfo.hProcess, &retVal) && retVal == STILL_ACTIVE) { if(fileMap == NULL) { fileMap = OpenFileMapping(0x0004, true, _T("DBPROEDITORMESSAGE")); } if(fileMap != NULL) { if(fileView == NULL) { fileView = (int*)MapViewOfFile(fileMap, SECTION_MAP_READ, 0, 0, 16); } if(fileView != NULL) { if(fileView[0] != lastR) { pMainWnd->SendMessage(WM_USER + 2, fileView[0], 0); lastR = fileView[0]; } } } Sleep(10); // Don't overwhelm the system } if(fileView != NULL) { UnmapViewOfFile(fileView); } if(fileMap != NULL) { CloseHandle(fileMap); } } else { WaitForSingleObject(piProcessInfo.hProcess, INFINITE); } pMainWnd->SendMessage(WM_USER + 2, -1, 0); // Reset status bar // Close process and thread handles CloseHandle(piProcessInfo.hThread); CloseHandle(piProcessInfo.hProcess); m_IsCompiling = false; // leefix - 300908 - ensure compiler does not wipe out HelpFile string (stored from above) m_strHelpFile = StoreHelpFileString; // Clean up #ifndef NONVERBOSEOUTPUTMODE CString strCleanUp = _T("Cleaning up"); TCHAR* msgCleanUp = new TCHAR[strCleanUp.GetLength() + 1]; wcscpy_s(msgCleanUp, strCleanUp.GetLength() + 1, strCleanUp); pMainWnd->SendMessage(WM_USER + 3, (WPARAM)msgCleanUp); #endif #ifndef _DEBUG ::DeleteFile(Utilities::GetTemporaryPath() + _T("Temp.dbpro")); ::DeleteFile(Utilities::GetTemporaryPath() + _T("_Temp.dbsource")); #endif // Get error bool result = ReadError::Read(); // Run if asked and no error if(result && m_run) { CString pathRun; if(m_strHelpFile == "") { if(Utilities::ExtractFilename(Variables::m_DBPropertyExe) == Variables::m_DBPropertyExe) { pathRun = Variables::m_ProjectPath; // Exe is in the same location as the project runExe = Variables::m_ProjectPath + Variables::m_DBPropertyExe; } else { // leefix - 300908 - when run TEMP.EXE in TEMP folder, should use CURRENT FOLDER not TEMP FOLDER as CWD if(Utilities::ExtractPath(Variables::m_DBPropertyExe) == Utilities::GetTemporaryPath() ) { char pCurrDir[512]; GetCurrentDirectoryA(512,pCurrDir); pathRun = CString(pCurrDir); runExe = Variables::m_DBPropertyExe; } else { // leenote - not sure what scenario for this might be? pathRun = Utilities::ExtractPath(Variables::m_DBPropertyExe); // Exe path contains the path runExe = Variables::m_DBPropertyExe; } } } else { pathRun = Utilities::ExtractPath(m_strHelpFile); runExe = Utilities::GetTemporaryPath() + _T("Temp.exe"); } if(Variables::m_CommandLineArgs != L"") { runExe += _T(" ") + Variables::m_CommandLineArgs; } ZeroMemory( &siStartupInfo, sizeof(siStartupInfo) ); siStartupInfo.cb = sizeof(siStartupInfo); ZeroMemory( &piProcessInfo, sizeof(piProcessInfo) ); ZeroMemory( &exeAr, sizeof(exeAr) ); wcscpy_s(exeAr, MAX_PATH, runExe); CreateProcess(NULL, exeAr, 0, 0, FALSE, CREATE_DEFAULT_ERROR_MODE, 0, pathRun, &siStartupInfo, &piProcessInfo); WaitForSingleObject(piProcessInfo.hProcess, INFINITE); // Close process and thread handles CloseHandle(piProcessInfo.hThread); CloseHandle(piProcessInfo.hProcess); } #ifndef NONVERBOSEOUTPUTMODE CString strDots = _T("------------"); TCHAR* msgDots = new TCHAR[strDots.GetLength() + 1]; wcscpy_s(msgDots, strDots.GetLength() + 1, strDots); pMainWnd->SendMessage(WM_USER + 3, (WPARAM)msgDots); #endif return 0; }
27.258359
240
0.705174
domydev
6fed420cdcd1d52d007d74fb115e67dcbd478129
979
cpp
C++
String_CL/EraseAndReplace.cpp
rsghotra/AbdulBari
2d2845608840ddda6e5153ec91966110ca7e25f5
[ "Apache-2.0" ]
1
2020-12-02T09:21:52.000Z
2020-12-02T09:21:52.000Z
String_CL/EraseAndReplace.cpp
rsghotra/AbdulBari
2d2845608840ddda6e5153ec91966110ca7e25f5
[ "Apache-2.0" ]
null
null
null
String_CL/EraseAndReplace.cpp
rsghotra/AbdulBari
2d2845608840ddda6e5153ec91966110ca7e25f5
[ "Apache-2.0" ]
null
null
null
/* 8. Replace and Erase */ #include<iostream> #include<string> using namespace std; int main() { string string1{"The values in any left subtree" "\nare less than the value in the" "\nparent node and the values in" "\nany right subtree are greater" "\nthan the value in the parent node"}; cout << "Original string:\n" << string1 << endl << endl; string1.erase(62); cout << "Original string after erase:\n" << string1 << "\nAfter first replacement:\n"; size_t position = string1.find(" "); //find first space while(position != string::npos) { string1.replace(position, 1, "."); position= string1.find(" ", position + 1); } cout << string1 << "\nAfter second replacement:\n"; position = string1.find("."); while(position != string::npos) { string1.replace(position, 2, "xxxxx;;yyy", 5, 2); position = string1.find(".", position + 1); } cout << string1 << endl; }
25.763158
59
0.595506
rsghotra
6ff033f2ba462b47014b9e5b751a093f3a394886
12,395
hpp
C++
libcamsim/scene.hpp
Tetsu5902/camsim
bcf995bb30e44792414ca2afd30a2869030b1f92
[ "MIT" ]
5
2020-02-19T14:03:35.000Z
2021-05-05T08:26:01.000Z
libcamsim/scene.hpp
Tetsu5902/camsim
bcf995bb30e44792414ca2afd30a2869030b1f92
[ "MIT" ]
null
null
null
libcamsim/scene.hpp
Tetsu5902/camsim
bcf995bb30e44792414ca2afd30a2869030b1f92
[ "MIT" ]
3
2020-02-25T22:51:36.000Z
2021-05-05T08:26:05.000Z
/* * Copyright (C) 2016, 2017, 2018 * Computer Graphics Group, University of Siegen * Written by Martin Lambers <martin.lambers@uni-siegen.de> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef CAMSIM_SCENE_HPP #define CAMSIM_SCENE_HPP #include <QList> #include <QVector3D> #include "animation.hpp" /* A scene description suitable for OpenGL-based rendering */ namespace CamSim { /*! * \brief Light source type. */ typedef enum { /*! \brief A point light source. */ PointLight = 0, /*! \brief A spot light source. */ SpotLight = 1, /*! \brief A directional light source. */ DirectionalLight = 2 } LightType; // do not change these values; they are reused in shaders! /** * \brief The Light class. * * This describes a light source for OpenGL-based rendering. */ class Light { public: /** * \name Type */ /*@{*/ /*! \brief Light source type */ LightType type; /*! \brief For spot lights: inner cone angle in degrees */ float innerConeAngle; /*! \brief For spot lights: outer cone angle in degrees */ float outerConeAngle; /*@}*/ /** * \name Geometry */ /*@{*/ /*! \brief Flag: does this light source move with the camera? */ bool isRelativeToCamera; /*! \brief Position */ QVector3D position; /*! \brief Direction (for spot lights and directional lights) */ QVector3D direction; /*! \brief "Up vector" (for shadow mapping and power factor maps). Must be perpendicular to \a direction. */ QVector3D up; /*@}*/ /** * \name Basic simulation parameters */ /*@{*/ /*! \brief Light color, for classic OpenGL cameras. */ QVector3D color; /*! \brief Power in Watt, for PMD cameras. */ float power; /*! \brief Constant attenuation coefficient. Should be 1 for physically plausible lights. */ float attenuationConstant; /*! \brief Linear attenuation coefficient. Should be 0 for physically plausible lights. */ float attenuationLinear; /*! \brief Quadratic attenuation coefficient. Should be 1 for physically plausible lights. */ float attenuationQuadratic; /*@}*/ /** * \name Shadows and reflective shadow maps */ /*@{*/ /*! \brief Flag: does this light source create a shadow map? (Used if shadow maps are active in the simulator pipeline.) */ bool shadowMap; /*! \brief Width and height of shadow map (only used if \a shadowMap is true) */ unsigned int shadowMapSize; /*! \brief Bias for comparison with shadow map depths. Value should be greater than or equal to zero. */ float shadowMapDepthBias; /*! \brief Flag: does this light source create reflective shadow maps? (Used if reflective shadow maps are active in the simulator pipeline.) */ bool reflectiveShadowMap; /*! \brief Width and height of reflective shadow map (only used if \a reflectiveShadowMap is true) */ unsigned int reflectiveShadowMapSize; /*@}*/ /** * \name Advanced simulation parameters */ /*@{*/ /*! \brief Texture containing power factor map (or 0 if unavailable). * This will be created and updated automatically by the simulator; you only * have to care about the parameters defined below. * * Each texel corresponds to an outgoing angle (horizontally and vertically) and * contains a floating point value in [0,1] that is multiplied * with the light source power value ('color' for classic OpenGL cameras; * 'power' for PMD cameras). */ unsigned int powerFactorTex; /*! \brief Width of the power factor map */ int powerFactorMapWidth; /*! \brief Height of the power factor map */ int powerFactorMapHeight; /*! \brief Angle in degrees at left border of power distribution map (seen from light source) */ float powerFactorMapAngleLeft; /*! \brief Angle in degrees at right border of power distribution map (seen from light source) */ float powerFactorMapAngleRight; /*! \brief Angle in degrees at bottom border of power distribution map (seen from light source) */ float powerFactorMapAngleBottom; /*! \brief Angle in degrees at top border of power distribution map (seen from light source) */ float powerFactorMapAngleTop; /*! \brief Vector containing power factor map values (or empty). */ QVector<float> powerFactors; /*! \brief Callback function that allows dynamically changing power factor maps. * \param callbackData User defined pointer, see \a powerFactorMapCallbackData * \param timestamp Time stamp for which to generate the map * \param mapWidth Width of the generated map * \param mapHeight Height of the generated map * \param angleLeft Horizontal angle corresponding to left border of map * \param angleRight Horizontal angle corresponding to right border of map * \param angleBottom Vertical angle corresponding to bottom border of map * \param angleTop Vertical angle corresponding to top border of map * \param factors The map; this vector should be resized and filled with values * \return Whether any of the values changed compared to the last version */ bool (*powerFactorMapCallback)( void* callbackData, long long timestamp, int* mapWidth, int* mapHeight, float* angleLeft, float* angleRight, float* angleBottom, float* angleTop, QVector<float>& factors); /*! \brief Pointer to user-defined data fed into the power factor map callback */ void* powerFactorMapCallbackData; /*@}*/ /*! \brief Constructor */ Light(); /*! \brief Update a power factor texture from the values given. This function * is used by the simulator; do not call it in your own code. */ void updatePowerFactorTex(unsigned int pbo, long long timestamp); }; /*! * \brief Material type. */ typedef enum { /*! \brief A BRDF model based on modified Phong lighting */ Phong = 0, /*! \brief TODO: A BRDF model based on a microfacet model */ Microfacets = 1, /*! \brief TODO: A BRDF model based on a measurements of a real material */ Measured = 2 } MaterialType; // do not change these values, they a reused in shaders /** * \brief The Material class * * Describes a material suitable for OpenGL-based rendering */ class Material { public: /** * \name Constructors for basic materials */ /*@{*/ /*! \brief Default material (phong, greyish, with diffuse and specular components) */ Material(); /*! \brief Construct a phong-type material with the given diffuse and specular colors. * If the specular color is 0 (the default), then the material will be lambertian. */ Material(const QVector3D& diffuse, const QVector3D& specular = QVector3D(0.0f, 0.0f, 0.0f), float shininess = 100.0f); /*@}*/ /** * \name Type description */ /*@{*/ /*! \brief Material type */ MaterialType type; /*! \brief Flag: is this material two-sided? */ bool isTwoSided; /*@}*/ /** * \name Simulated geometric detail */ /*@{*/ /*! \brief Texture containing a bump map, or 0. */ unsigned int bumpTex; /*! \brief Scaling factor for the bump map */ float bumpScaling; /*! \brief Texture containing a normal map (overrides \a bumpTex), or 0 */ unsigned int normalTex; /*@}*/ /** * \name Opacity */ /*@{*/ /*! \brief Opacity value in [0,1] */ float opacity; /*! \brief Texture containing an opacity map (overrides \a opacity) */ unsigned int opacityTex; /*@}*/ /** * \name Simulation parameters (depend on material type) */ /*@{*/ /*! \brief Ambient color (for Phong) */ QVector3D ambient; /*! \brief Diffuse color (for Phong) */ QVector3D diffuse; /*! \brief Specular color (for Phong) */ QVector3D specular; /*! \brief Emissive color (for Phong) */ QVector3D emissive; /*! \brief Shininess parameter (for Phong) */ float shininess; /*! \brief Texture containing ambient color map (overrides \a ambient), or 0 (for Phong) */ unsigned int ambientTex; /*! \brief Texture containing diffuse color map (overrides \a diffuse), or 0 (for Phong) */ unsigned int diffuseTex; /*! \brief Texture containing specular color map (overrides \a specular), or 0 (for Phong) */ unsigned int specularTex; /*! \brief Texture containing emissive color map (overrides \a emissive), or 0 (for Phong) */ unsigned int emissiveTex; /*! \brief Texture containing shininess map (overrides \a shininess), or 0 (for Phong) */ unsigned int shininessTex; /*! \brief Texture containing lightness map, or 0 (for Phong) */ unsigned int lightnessTex; /*@}*/ }; /** * \brief The Shape class * * Describes a geometric shape suitable for OpenGL-based rendering */ class Shape { public: /*! \brief Index of the material description for this shape; see global \a Scene data */ unsigned int materialIndex; /*! \brief Vertex array object containing the vertex data for this shape */ unsigned int vao; /*! \brief Number of indices to render in GL_TRIANGLES mode */ unsigned int indices; /*! \brief Constructor */ Shape(); }; /** * \brief The Object class * * Describes an object, consisting of one or more shapes, suitable for OpenGL-based rendering */ class Object { public: /*! \brief The list of shapes that form this object */ QList<Shape> shapes; /*! \brief Constructor for an empty object */ Object(); /*! \brief Constructor for an object with a single shape */ Object(const Shape& shape); }; /** * \brief The Scene class * * Describes a scene to render (light sources and objects), suitable for OpenGL-based rendering */ class Scene { public: /** * \name Global scene data: materials */ /*@{*/ /*! \brief Global list of materials used in the scene */ QList<Material> materials; /*! \brief Convenience function to add a material. Returns its index. */ int addMaterial(const Material& material) { materials.append(material); return materials.size() - 1; } /*@}*/ /** * \name Scene contents: light sources and objects */ /*@{*/ /*! \brief Light sources */ QList<Light> lights; /*! \brief Light source animations (list must have same size as \a lights list) */ QList<Animation> lightAnimations; /*! \brief Objects */ QList<Object> objects; /*! \brief Object animations (list must have same size as \a objects list) */ QList<Animation> objectAnimations; /*! \brief Convenience function to add a light source and its animation */ void addLight(const Light& light, const Animation& animation = Animation()) { lights.append(light); lightAnimations.append(animation); } /*! \brief Convenience function to add an object and its animation */ void addObject(const Object& object, const Animation& animation = Animation()) { objects.append(object); objectAnimations.append(animation); } /*@}*/ /*! \brief Constructor */ Scene(); }; } #endif
32.362924
148
0.658169
Tetsu5902
6ff45014780795ff22a84811db6906aa131c285a
39,583
hh
C++
dune/fem/oseen/oemsolver/oemsolver.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/oemsolver/oemsolver.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/oemsolver/oemsolver.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
#ifndef DUNE_OSEEN_DUNE_StokesOEMSolver_HH #define DUNE_OSEEN_DUNE_StokesOEMSolver_HH //- system includes #include <utility> #include <cmake_config.h> #include <dune/stuff/common/debug.hh> //- Dune includes #include <dune/common/typetraits.hh> #include <dune/fem/operator/common/operator.hh> //- local includes #include "preconditioning.hh" #include <dune/fem/solver/pardg.hh> // include BLAS implementation #include "cblas.h" #undef USE_PARDG_ODE_SOLVER namespace StokesOEMSolver { ////////////////////////////////////////////////////////// // // Operator Interface to use linear solvers from pardg // ////////////////////////////////////////////////////////// template <class OperatorImp> class SolverInterfaceImpl #ifdef USE_PARDG_ODE_SOLVER : public pardg::Function #endif { const OperatorImp & op_; int size_; public: SolverInterfaceImpl(const OperatorImp & op, int size = 0) : op_(op), size_(size) {} void setSize( int size ) { size_ = size; } void operator () (const double *arg, double * dest, int /*i*/ = 0 ) { op_.multOEM(arg,dest); } void mult(const double *arg, double * dest) const { op_.multOEM(arg,dest); } int dim_of_argument(int i = 0) const { assert( i == 0 ); return size_; } int dim_of_value(int i = 0) const { assert( i == 0 ); return size_; } }; ////////////////////////////////////////////////////////// // // Preconditioner Interface to use linear solvers from pardg // ////////////////////////////////////////////////////////// template <class PreconditionerImp> class PreconditionerImpl #ifdef USE_PARDG_ODE_SOLVER : public pardg::Function #endif { const PreconditionerImp& pre_; int size_; public: PreconditionerImpl(const PreconditionerImp& pre, int size = 0) : pre_(pre), size_(size) {} void setSize( int size ) { size_ = size; } void operator () (const double *arg, double * dest, int /*i*/ = 0 ) { pre_.precondition(arg,dest); } void mult(const double *arg, double * dest) const { pre_.precondition(arg,dest); } int dim_of_argument(int i = 0) const { assert( i == 0 ); return size_; } int dim_of_value(int i = 0) const { assert( i == 0 ); return size_; } }; // use cblas implementations using namespace DuneCBlas; using DuneCBlas :: daxpy; using DuneCBlas :: dcopy; using DuneCBlas :: ddot; using DuneCBlas :: dnrm2; using DuneCBlas :: dscal; //! this method is called from all solvers and is only a wrapper //! this method is mainly from SparseRowMatrix template <class MatrixImp, class VectorType> void mult(const MatrixImp & m, const VectorType * x, VectorType * ret, const IterationInfo& info ) { // call multOEM of the matrix m.multOEM(x,ret, info ); } template <class MatrixImp, class VectorType> void mult(const MatrixImp & m, const VectorType * x, VectorType * ret ) { IterationInfo dummy; // call multOEM of the matrix m.multOEM(x,ret ); } //! mult method when given pre conditioning matrix template <class Matrix , class PC_Matrix , bool use_pc > struct Mult { static inline double ddot( const Matrix& A, const double *x, const double *y) { return A.ddotOEM(x,y); } typedef void mult_t(const Matrix &A, const PC_Matrix & C, const double *arg, double *dest , double * tmp, const IterationInfo& info ); static bool first_mult(const Matrix &A, const PC_Matrix & C, const double *arg, double *dest , double * tmp) { assert( tmp ); bool rightPreCon = C.rightPrecondition(); // check type of preconditioning if( rightPreCon ) { // call mult of Matrix A mult(A,arg,dest); } else { // call mult of Matrix A mult(A,arg,tmp); // call precondition of Matrix PC C.precondition(tmp,dest); } return rightPreCon; } static void back_solve(const int size, const PC_Matrix & C, double* solution, double* tmp) { assert( tmp ); if( C.rightPrecondition() ) { C.precondition(solution,tmp); // copy modified solution std::memcpy(solution,tmp, size * sizeof(double)); } } static void mult_pc (const Matrix &A, const PC_Matrix & C, const double *arg, double *dest , double * tmp, const IterationInfo& info ) { assert( tmp ); // check type of preconditioning if( C.rightPrecondition() ) { // call precondition of Matrix PC C.precondition(arg,tmp); // call mult of Matrix A mult(A,tmp,dest, info ); } else { // call mult of Matrix A mult(A,arg,tmp, info ); // call precondition of Matrix PC C.precondition(tmp,dest); } } }; //! mult method when no pre conditioning matrix template <class Matrix> struct Mult<Matrix,Matrix,false> { static inline double ddot( const Matrix& A, const double *x, const double *y) { return A.ddotOEM(x,y); } typedef void mult_t(const Matrix &A, const Matrix &C, const double *arg, double *dest , const IterationInfo& info ); static bool first_mult(const Matrix &A, const Matrix & UNUSED_UNLESS_DEBUG(C), const double *arg, double *dest , double * UNUSED_UNLESS_DEBUG(tmp) ) { // tmp has to be 0 assert( tmp == 0 ); // C is just a fake assert( &A == &C ); // call mult of Matrix A IterationInfo dummy; mult(A,arg,dest,dummy); // first mult like right precon return true; } static void back_solve(const int /*size*/, const Matrix & /*C*/, double* /*solution*/, double* /*tmp*/) { // do nothing here } static void mult_pc(const Matrix &A, const Matrix & UNUSED_UNLESS_DEBUG(C), const double *arg , double *dest , double * UNUSED_UNLESS_DEBUG(tmp), const IterationInfo& info ) { // tmp has to be 0 assert( tmp == 0 ); // C is just a fake assert( &A == &C ); // call mult of Matrix A mult(A,arg,dest,info); } }; //#define USE_MEMPROVIDER #include "bicgstab.h" #include "cghs.h" #include "gmres.h" #include "bicgsq.h" #undef USE_MEMPROVIDER //! fake conditioner which just is id for internal parts of vector and zero //! for other parts, needed by parallel gmres class FakeConditioner { // size of vectors const int size_; // indices of external values std::vector<int> indices_; public: // use with care, not sure that working correctly already template <class SolverOperatorImp> FakeConditioner(int size, SolverOperatorImp& op) : size_(size) { assert( size_ > 0 ); double * diag = new double [size_]; double * tmp = new double [size_]; assert( diag ); assert( tmp ); for(int i=0; i<size_; ++i) tmp[i] = i; op(tmp,diag); int newSize = (int) 0.25 * size_; indices_.reserve( newSize ); indices_.resize( 0 ); // now diag contains only non-zeros for all internal entries // these are set to 1.0 to be the id mapping for(int i=0; i<size_; ++i) { if( ! (std::abs (diag[i]) > 0.0) ) { indices_.push_back( i ); } } delete [] diag; delete [] tmp; } bool rightPrecondition() const { return false; } //! only keep internal parts of arg void precondition(const double * arg, double * dest) const { multOEM(arg,dest); } //! only keep internal parts of arg void multOEM(const double * arg, double * dest) const { std::memcpy( dest, arg , size_ * sizeof(double) ); const int s = indices_.size(); for(int i=0; i<s; ++i) { dest[indices_[i]] = 0.0; } } }; } // end namespace StokesOEMSolver namespace DuneStokes { using namespace Dune; /** @addtogroup StokesOEMSolver In this section implementations of Orthogonal Error Methods (OEM) for solving linear systems of the from \f$A x = b\f$, where \f$A\f$ is a Mapping or Operator and \f$x\f$ and \f$b\f$ are discrete functions (see DiscreteFunctionInterface) can be found. @{ **/ /** \brief OEM-CG scheme after Hestenes and Stiefel */ template <class DiscreteFunctionType, class OperatorType > class OEMCGOp : public Operator< typename DiscreteFunctionType::DomainFieldType, typename DiscreteFunctionType::RangeFieldType, DiscreteFunctionType,DiscreteFunctionType> { public: typedef std::pair < int , double > ReturnValueType; private: // no const reference, we make const later OperatorType &op_; typename DiscreteFunctionType::RangeFieldType epsilon_; int maxIter_; bool verbose_ ; template <class OperatorImp, bool hasPreconditioning> struct SolverCaller { template <class DiscreteFunctionImp> static ReturnValueType call(OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest, double eps, bool verbose) { // use communication class of grid // see dune-common/common/collectivecommunication.hh // for interface int size = arg.space().size(); if(op.hasPreconditionMatrix()) { if( !op.preconditionMatrix().rightPrecondition() ) { DiscreteFunctionImp precond_arg( "precond_arg", arg.space() ); op.preconditionMatrix().precondition( arg.leakPointer(), precond_arg.leakPointer() ); return StokesOEMSolver::cghs(arg.space().grid().comm(), size,op.systemMatrix(),op.preconditionMatrix(), precond_arg.leakPointer(),dest.leakPointer(),eps,verbose ); } else return StokesOEMSolver::cghs(arg.space().grid().comm(), size,op.systemMatrix(),op.preconditionMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose ); } else { return StokesOEMSolver::cghs(arg.space().grid().comm(), size,op.systemMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose ); } } }; //! without any preconditioning template <class OperatorImp> struct SolverCaller<OperatorImp,false> { template <class DiscreteFunctionImp> static ReturnValueType call(OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest, double eps, bool verbose) { // use communication class of grid // see dune-common/common/collectivecommunication.hh // for interface int size = arg.space().size(); return StokesOEMSolver::cghs (arg.space().grid().comm(), size,op.systemMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose ); } }; public: /** \brief constructor of OEM-CG \param[in] op Operator to invert \param[in] redEps realative tolerance for residual \param[in] absLimit absolut solving tolerance for residual \param[in] maxIter maximal number of iterations performed \param[in] verbose verbosity */ OEMCGOp( OperatorType & op , double /*redEps*/ , double absLimit , int maxIter , bool verbose ) : op_(op), epsilon_ ( absLimit ) , maxIter_ (maxIter ) , verbose_ ( verbose ) { } void prepare (const DiscreteFunctionType& /*Arg*/, DiscreteFunctionType& /*Dest*/) const { } void finalize () const { } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { // prepare operator prepare ( arg, dest ); ReturnValueType val = SolverCaller<OperatorType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(op_,arg,dest,epsilon_,verbose_); if( verbose_ && arg.space().grid().comm().rank() == 0 ) { std::cout << "OEM-CG: " << val.first << " iterations! Error: " << val.second << "\n"; } // finalize operator finalize (); } void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest, ReturnValueType& ret) const { // prepare operator prepare ( arg, dest ); ReturnValueType val = SolverCaller<OperatorType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(op_,arg,dest,epsilon_,verbose_); if( verbose_ && arg.space().grid().comm().rank() == 0 ) { std::cout << "OEM-CG: " << val.first << " iterations! Error: " << val.second << "\n"; } // finalize operator finalize (); ret = val; } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void operator ()( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { apply(arg,dest); } void setAbsoluteLimit( const typename DiscreteFunctionType::RangeFieldType abs ) { epsilon_ = abs; } }; /** \brief BiCG-stab solver */ template <class DiscreteFunctionType, class OperatorType > class OEMBICGSTABOp : public Operator< typename DiscreteFunctionType::DomainFieldType, typename DiscreteFunctionType::RangeFieldType, DiscreteFunctionType,DiscreteFunctionType> { public: typedef std::pair < int , double > ReturnValueType; private: // no const reference, we make const later OperatorType &op_; typename DiscreteFunctionType::RangeFieldType epsilon_; int maxIter_; bool verbose_ ; template <class OperatorImp, bool hasPreconditioning> struct SolverCaller { template <class DiscreteFunctionImp> static ReturnValueType call(OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest, double eps, bool verbose) { int size = arg.space().size(); if(op.hasPreconditionMatrix()) { return StokesOEMSolver::bicgstab(arg.space().grid().comm(), size,op.systemMatrix(),op.preconditionMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose ); } else { return StokesOEMSolver::bicgstab(arg.space().grid().comm(), size,op.systemMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose ); } } }; //! without any preconditioning template <class OperatorImp> struct SolverCaller<OperatorImp,false> { template <class DiscreteFunctionImp> static ReturnValueType call(OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest, double eps, bool verbose) { int size = arg.space().size(); return StokesOEMSolver::bicgstab(arg.space().grid().comm(), size,op.systemMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose ); } }; public: /** \brief constructor of OEM-BiCG-stab \param[in] op Operator to invert \param[in] redEps realative tolerance for residual \param[in] absLimit absolut solving tolerance for residual \param[in] maxIter maximal number of iterations performed \param[in] verbose verbosity */ OEMBICGSTABOp( OperatorType & op , double /*redEps*/ , double absLimit , int maxIter , bool verbose ) : op_(op), epsilon_ ( absLimit ) , maxIter_ (maxIter ) , verbose_ ( verbose ) { } void prepare (const DiscreteFunctionType& /*Arg*/, DiscreteFunctionType& /*Dest*/) const { } void finalize () const { } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { typedef typename DiscreteFunctionType::FunctionSpaceType FunctionSpaceType; // prepare operator prepare ( arg, dest ); ReturnValueType val = SolverCaller<OperatorType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(op_,arg,dest,epsilon_,verbose_); if( verbose_ && arg.space().grid().comm().rank() == 0) { std::cout << "OEM-BICGstab: " << val.first << " iterations! Error: " << val.second << "\n"; } // finalize operator finalize (); } void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest, ReturnValueType& ret ) const { typedef typename DiscreteFunctionType::FunctionSpaceType FunctionSpaceType; // prepare operator prepare ( arg, dest ); ReturnValueType val = SolverCaller<OperatorType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(op_,arg,dest,epsilon_,verbose_); if( verbose_ && arg.space().grid().comm().rank() == 0) { std::cout << "OEM-BICGstab: " << val.first << " iterations! Error: " << val.second << "\n"; } // finalize operator finalize (); ret = val; } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void operator ()( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { apply(arg,dest); } void setAbsoluteLimit( const typename DiscreteFunctionType::RangeFieldType abs ) { epsilon_ = abs; } }; //////////////////////////////// // BICG SQ scheme //////////////////////////////// /** \brief BiCG-SQ method */ template <class DiscreteFunctionType, class OperatorType> class OEMBICGSQOp : public Operator< typename DiscreteFunctionType::DomainFieldType, typename DiscreteFunctionType::RangeFieldType, DiscreteFunctionType,DiscreteFunctionType> { private: // no const reference, we make const later OperatorType &op_; typename DiscreteFunctionType::RangeFieldType epsilon_; int maxIter_; bool verbose_ ; public: /** \brief constructor of OEM-BiCG-SQ \param[in] op Operator to invert \param[in] redEps realative tolerance for residual \param[in] absLimit absolut solving tolerance for residual \param[in] maxIter maximal number of iterations performed \param[in] verbose verbosity */ OEMBICGSQOp( OperatorType & op , double /*redEps*/ , double absLimit , int maxIter , bool verbose ) : op_(op), epsilon_ ( absLimit ) , maxIter_ (maxIter ) , verbose_ ( verbose ) { } void prepare (const DiscreteFunctionType& /*Arg*/, DiscreteFunctionType& /*Dest*/) const { } void finalize () const { } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { typedef typename DiscreteFunctionType::FunctionSpaceType FunctionSpaceType; // prepare operator prepare ( arg, dest ); int size = arg.space().size(); int iter = StokesOEMSolver::bicgsq(size,op_.systemMatrix(), arg.leakPointer(),dest.leakPointer(),epsilon_,verbose_); std::cout << "OEM-BICGGsq: " << iter << " iterations!\n"; // finalize operator finalize (); } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void operator ()( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { apply(arg,dest); } }; /** \brief GMRES solver */ template <class DiscreteFunctionType, class OperatorType> class OEMGMRESOp : public Operator< typename DiscreteFunctionType::DomainFieldType, typename DiscreteFunctionType::RangeFieldType, DiscreteFunctionType,DiscreteFunctionType> { public: typedef std::pair < int , double > ReturnValueType; private: // type of internal projector if no preconditioner given typedef StokesOEMSolver :: FakeConditioner FakeConditionerType; // no const reference, we make const later OperatorType &op_; typename DiscreteFunctionType::RangeFieldType epsilon_; int maxIter_; bool verbose_ ; template <class OperatorImp, bool hasPreconditioning> struct SolverCaller { template <class DiscreteFunctionImp> static ReturnValueType call(OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest, int inner, double eps, bool verbose) { int size = arg.space().size(); if(op.hasPreconditionMatrix()) { return StokesOEMSolver::gmres(arg.space().grid().comm(), inner, size,op.systemMatrix(),op.preconditionMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose ); } // in parallel case we need special treatment, if no preconditoner exist else if( arg.space().grid().comm().size() > 1 ) { StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op); FakeConditionerType preConditioner(size,opSolve); return StokesOEMSolver::gmres(arg.space().grid().comm(), inner,size,op.systemMatrix(),preConditioner, arg.leakPointer(),dest.leakPointer(),eps,verbose); } else { return StokesOEMSolver::gmres(arg.space().grid().comm(), inner,size,op.systemMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose); } } }; // without any preconditioning template <class OperatorImp> struct SolverCaller<OperatorImp,false> { template <class DiscreteFunctionImp> static ReturnValueType call(OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest, int inner, double eps, bool verbose) { int size = arg.space().size(); if( arg.space().grid().comm().size() > 1 ) { StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op); FakeConditionerType preConditioner(size,opSolve); return StokesOEMSolver::gmres(arg.space().grid().comm(), inner,size,op.systemMatrix(),preConditioner, arg.leakPointer(),dest.leakPointer(),eps,verbose); } else { return StokesOEMSolver::gmres(arg.space().grid().comm(), inner,size,op.systemMatrix(), arg.leakPointer(),dest.leakPointer(),eps,verbose); } } }; public: /** \brief constructor of OEM-GMRES \param[in] op Operator to invert \param[in] redEps realative tolerance for residual \param[in] absLimit absolut solving tolerance for residual \param[in] maxIter maximal number of iterations performed \param[in] verbose verbosity */ OEMGMRESOp( OperatorType & op , double /*redEps*/ , double absLimit , int maxIter , bool verbose ) : op_(op), epsilon_ ( absLimit ) , maxIter_ (maxIter ) , verbose_ ( verbose ) { } void prepare (const DiscreteFunctionType& /*Arg*/, DiscreteFunctionType& /*Dest*/) const { } void finalize () const { } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { // prepare operator prepare ( arg, dest ); int size = arg.space().size(); int inner = (size > 20) ? 20 : size; ReturnValueType val = SolverCaller<OperatorType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(op_,arg,dest,inner,epsilon_,verbose_); if( verbose_ && arg.space().grid().comm().rank() == 0) { std::cout << "OEM-GMRES: " << val.first << " iterations! Error: " << val.second << "\n"; } // finalize operator finalize (); } void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest, ReturnValueType& ret ) const { // prepare operator prepare ( arg, dest ); int size = arg.space().size(); int inner = (size > 20) ? 20 : size; ReturnValueType val = SolverCaller<OperatorType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(op_,arg,dest,inner,epsilon_,verbose_); if( verbose_ && arg.space().grid().comm().rank() == 0) { std::cout << "OEM-GMRES: " << val.first << " iterations! Error: " << val.second << "\n"; } // finalize operator finalize (); ret = val; } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void operator ()( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { apply(arg,dest); } void setAbsoluteLimit( const typename DiscreteFunctionType::RangeFieldType abs ) { epsilon_ = abs; } }; /** @} **/ #ifdef USE_PARDG_ODE_SOLVER ///////////////////////////////////////////////////////////////// // // GMRES Version of Dennis code // ///////////////////////////////////////////////////////////////// // \brief GMRES implementation from Dennis D. template <class DiscreteFunctionType, class OperatorType> class GMRESOp : public Operator< typename DiscreteFunctionType::DomainFieldType, typename DiscreteFunctionType::RangeFieldType, DiscreteFunctionType,DiscreteFunctionType> { private: typedef StokesOEMSolver :: FakeConditioner FakeConditioner; template <class SolverType, bool hasPreconditioning> struct SolverCaller { template <class OperatorImp, class PreConMatrix, class DiscreteFunctionImp> static void solve(SolverType & solver, OperatorImp & op, const PreConMatrix & pm, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { int size = arg.space().size(); solver.set_max_number_of_iterations(size); StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op,size); // in parallel runs we need fake pre conditioner to // project vectors onto interior if(op.hasPreconditionMatrix()) { StokesOEMSolver::PreconditionerImpl<PreConMatrix> pre(pm,size); solver.set_preconditioner(pre); // note argument and destination are toggled solver.solve(opSolve, dest.leakPointer() , arg.leakPointer() ); solver.unset_preconditioner(); } else { // note argument and destination are toggled solver.solve(opSolve, dest.leakPointer() , arg.leakPointer() ); } } template <class OperatorImp, class DiscreteFunctionImp> static void call(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { solve(solver,op,op.preconditionMatrix(),arg,dest); } }; // without any preconditioning template <class SolverType> struct SolverCaller<SolverType,false> { template <class OperatorImp, class DiscreteFunctionImp> static void call(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { int size = arg.space().size(); StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op,size); solver.set_max_number_of_iterations(size); // in parallel runs we need fake pre conditioner to // project vectors onto interior if(arg.space().grid().comm().size() > 1) { FakeConditioner fake(size,opSolve); StokesOEMSolver::SolverInterfaceImpl<FakeConditioner> pre(fake); solver.set_preconditioner(pre); // note argument and destination are toggled solver.solve(opSolve, dest.leakPointer() , arg.leakPointer() ); solver.unset_preconditioner(); } else { // note argument and destination are toggled solver.solve(opSolve, dest.leakPointer() , arg.leakPointer() ); } } }; // solver typedef pardg::GMRES SolverType; mutable SolverType solver_; // wrapper to fit interface of FGMRES operator mutable OperatorType & op_; typename DiscreteFunctionType::RangeFieldType epsilon_; int maxIter_; bool verbose_ ; typedef std::pair < int , double > ReturnValueType; public: GMRESOp( OperatorType & op , double redEps , double absLimit , int maxIter , bool verbose ) : solver_(pardg::Communicator::instance(),20) , op_(op) , epsilon_ ( absLimit ) , maxIter_ (maxIter ) , verbose_ ( verbose ) { } void prepare (const DiscreteFunctionType& Arg, DiscreteFunctionType& Dest) const { } void finalize () const { } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { // prepare operator prepare ( arg, dest ); solver_.set_tolerance(epsilon_); if(verbose_) { solver_.IterativeSolver::set_output(std::cout); solver_.DynamicalObject::set_output(std::cout); } SolverCaller<SolverType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(solver_,op_.systemMatrix(),arg,dest); // finalize operator finalize (); } /** \brief solve the system \param[in] arg right hand side \param[out] dest solution */ void operator ()( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { apply(arg,dest); } }; template <class DiscreteFunctionType, class OperatorType> class FGMRESOp : public Operator< typename DiscreteFunctionType::DomainFieldType, typename DiscreteFunctionType::RangeFieldType, DiscreteFunctionType,DiscreteFunctionType> { private: typedef StokesOEMSolver :: FakeConditioner FakeConditionerType; template <class SolverType, bool hasPreconditioning> struct SolverCaller { template <class OperatorImp, class PreConMatrix, class DiscreteFunctionImp> static void solve(SolverType & solver, OperatorImp & op, const PreConMatrix & pm, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { int size = arg.space().size(); StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op,size); StokesOEMSolver::PreconditionerImpl<PreConMatrix> pre(pm,size); solver.set_preconditioner(pre); solver.set_max_number_of_iterations(size); // note argument and destination are toggled solver.solve(opSolve, dest.leakPointer() , arg.leakPointer() ); solver.unset_preconditioner(); } template <class OperatorImp, class DiscreteFunctionImp> static void call(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { if(op.hasPreconditionMatrix() ) { solve(solver,op.systemMatrix(),op.preconditionMatrix(),arg,dest); } else { SolverCaller<SolverType,false>::call(solver,op,arg,dest); } } }; // without any preconditioning template <class SolverType> struct SolverCaller<SolverType,false> { template <class OperatorImp, class DiscreteFunctionImp> static void solve(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { int size = arg.space().size(); StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op,size); FakeConditionerType fake(size,opSolve); SolverCaller<SolverType,true>::solve(solver,op,fake,arg,dest); } template <class OperatorImp, class DiscreteFunctionImp> static void call(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { // not working yet assert( false ); solve(solver,op.systemMatrix(),arg,dest); } }; // solver typedef pardg::FGMRES SolverType; mutable SolverType solver_; // wrapper to fit interface of FGMRES operator mutable OperatorType & op_; typename DiscreteFunctionType::RangeFieldType epsilon_; int maxIter_; bool verbose_ ; typedef std::pair < int , double > ReturnValueType; public: FGMRESOp( OperatorType & op , double redEps , double absLimit , int maxIter , bool verbose ) : solver_(pardg::Communicator::instance(),20) , op_(op) , epsilon_ ( absLimit ) , maxIter_ (maxIter ) , verbose_ ( verbose ) { } void prepare (const DiscreteFunctionType& Arg, DiscreteFunctionType& Dest) const { } void finalize () const { } //! solve the system void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { // prepare operator prepare ( arg, dest ); solver_.set_tolerance(epsilon_); if(verbose_) { solver_.IterativeSolver::set_output(std::cout); solver_.DynamicalObject::set_output(std::cout); } SolverCaller<SolverType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(solver_,op_,arg,dest); // finalize operator finalize (); } //! solve the system void operator ()( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { apply(arg,dest); } }; ///////////////////////////////////////////////////////////////// // // BICGstab Version of Dennis code // ///////////////////////////////////////////////////////////////// /* \interface \brief BICG-stab implementation from Dennis D. */ template <class DiscreteFunctionType, class OperatorType> class BICGSTABOp : public Operator< typename DiscreteFunctionType::DomainFieldType, typename DiscreteFunctionType::RangeFieldType, DiscreteFunctionType,DiscreteFunctionType> { private: template <class SolverType, bool hasPreconditioning> struct SolverCaller { template <class OperatorImp, class PreConMatrix, class DiscreteFunctionImp> static void solve(SolverType & solver, OperatorImp & op, const PreConMatrix & pm, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { int size = arg.space().size(); StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op,size); solver.set_max_number_of_iterations(size); StokesOEMSolver::PreconditionerImpl<PreConMatrix> pre(pm,size); solver.set_preconditioner(pre); // note argument and destination are toggled solver.solve(opSolve, dest.leakPointer() , arg.leakPointer() ); solver.unset_preconditioner(); } template <class OperatorImp, class DiscreteFunctionImp> static void call(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { if(op.hasPreconditionMatrix()) { solve(solver,op.systemMatrix(),op.preconditionMatrix(),arg,dest); } else { SolverCaller<SolverType,false>::call(solver,op,arg,dest); } } }; // without any preconditioning template <class SolverType> struct SolverCaller<SolverType,false> { template <class OperatorImp, class DiscreteFunctionImp> static void solve(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { int size = arg.space().size(); StokesOEMSolver::SolverInterfaceImpl<OperatorImp> opSolve(op,size); solver.set_max_number_of_iterations(size); // note argument and destination are toggled solver.solve(opSolve, dest.leakPointer() , arg.leakPointer() ); } template <class OperatorImp, class DiscreteFunctionImp> static void call(SolverType & solver, OperatorImp & op, const DiscreteFunctionImp & arg, DiscreteFunctionImp & dest) { solve(solver,op.systemMatrix(),arg,dest); } }; // solver typedef pardg::BICGSTAB SolverType; mutable SolverType solver_; // wrapper to fit interface of GMRES operator mutable OperatorType & op_; typename DiscreteFunctionType::RangeFieldType epsilon_; int maxIter_; bool verbose_ ; typedef std::pair < int , double > ReturnValueType; public: BICGSTABOp( OperatorType & op , double redEps , double absLimit , int maxIter , bool verbose ) : solver_(pardg::Communicator::instance()) , op_(op), epsilon_ ( absLimit ) , maxIter_ (maxIter ) , verbose_ ( verbose ) { } void prepare (const DiscreteFunctionType& Arg, DiscreteFunctionType& Dest) const { } void finalize () const { } //! solve the system void apply( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { // prepare operator prepare ( arg, dest ); solver_.set_tolerance(epsilon_); if(verbose_) { solver_.IterativeSolver::set_output(std::cout); solver_.DynamicalObject::set_output(std::cout); } SolverCaller<SolverType, // check wheter operator has precondition methods // to enable preconditioning derive your operator from // StokesOEMSolver::PreconditionInterface Conversion<OperatorType, StokesOEMSolver::PreconditionInterface > ::exists >:: // call solver, see above call(solver_,op_,arg,dest); // finalize operator finalize (); } //! solve the system void operator ()( const DiscreteFunctionType& arg, DiscreteFunctionType& dest ) const { apply(arg,dest); } }; #endif } // end namespace Dune #endif //DUNE_OSEEN_
29.041086
106
0.631458
renemilk
6ffcdee1180f490b523788245395144a96e019eb
21,684
hpp
C++
include/CPPResult.hpp
stephanfr/CppResult
4f1c3aa3f1e5fd4e5a04504935a2f82880489994
[ "MIT" ]
null
null
null
include/CPPResult.hpp
stephanfr/CppResult
4f1c3aa3f1e5fd4e5a04504935a2f82880489994
[ "MIT" ]
null
null
null
include/CPPResult.hpp
stephanfr/CppResult
4f1c3aa3f1e5fd4e5a04504935a2f82880489994
[ "MIT" ]
null
null
null
#pragma once #include <assert.h> #include <memory> #include <optional> #include <string> #include <fmt/format.h> namespace SEFUtility { enum class BaseResultCodes { SUCCESS = 0, FAILURE }; // // Base Class needed primarily for passing inner errors // class ResultBase { protected: ResultBase(BaseResultCodes success_or_failure, const std::string& message) : success_or_failure_(success_or_failure), message_(message) { } ResultBase(BaseResultCodes success_or_failure, const ResultBase& inner_error, const std::string& message) : success_or_failure_(success_or_failure), message_(message), inner_error_(inner_error.shallow_copy()) { } public: virtual ~ResultBase(){}; virtual std::unique_ptr<const ResultBase> shallow_copy() const = 0; bool succeeded() const { return (success_or_failure_ == BaseResultCodes::SUCCESS); } bool failed() const { return (success_or_failure_ == BaseResultCodes::FAILURE); } const std::string&message() const { return (message_); } const std::unique_ptr<const ResultBase>& inner_error() const { return (inner_error_); } virtual const std::type_info& error_code_type() const = 0; virtual int error_code_value() const = 0; protected: BaseResultCodes success_or_failure_; std::string message_; std::unique_ptr<const ResultBase> inner_error_; }; template <typename TErrorCodeEnum> class Result : public ResultBase { protected: typedef TErrorCodeEnum ErrorCodeType; Result(BaseResultCodes success_or_failure, TErrorCodeEnum error_code, const std::string& message) : ResultBase(success_or_failure, message), error_code_(error_code) { assert((success_or_failure == BaseResultCodes::SUCCESS) || ((success_or_failure == BaseResultCodes::FAILURE) && (error_code != TErrorCodeEnum::SUCCESS))); } template <typename TInnerErrorCodeEnum> Result(BaseResultCodes success_or_failure, const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) : ResultBase(success_or_failure, inner_error, message), error_code_(error_code) { assert((success_or_failure == BaseResultCodes::SUCCESS) || ((success_or_failure == BaseResultCodes::FAILURE) && (error_code != TErrorCodeEnum::SUCCESS))); } std::unique_ptr<const ResultBase> shallow_copy() const { return (std::unique_ptr<const ResultBase>(new Result<TErrorCodeEnum>(*this))); } public: Result(const Result<TErrorCodeEnum>& result_to_copy) : ResultBase(result_to_copy.success_or_failure_, result_to_copy.message_), error_code_(result_to_copy.error_code_) { inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); } virtual ~Result(){}; const Result<TErrorCodeEnum>& operator=(const Result<TErrorCodeEnum>& result_to_copy) { success_or_failure_ = result_to_copy.success_or_failure_; message_ = result_to_copy.message_; error_code_ = result_to_copy.error_code_; inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); return (*this); } static Result<TErrorCodeEnum> success() { return (Result(BaseResultCodes::SUCCESS, TErrorCodeEnum::SUCCESS, "Success")); }; static Result<TErrorCodeEnum> failure(TErrorCodeEnum error_code, const std::string& message) { return (Result(BaseResultCodes::FAILURE, error_code, message)); } template <typename... Args> static Result<TErrorCodeEnum> failure(TErrorCodeEnum error_code, const std::string& format, Args... args) { return (Result(BaseResultCodes::FAILURE, error_code, fmt::format(format, args...))); } template <typename TInnerErrorCodeEnum> static Result<TErrorCodeEnum> failure(const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) { return (Result(BaseResultCodes::FAILURE, inner_error, error_code, message)); } template <typename TInnerErrorCodeEnum, typename... Args> static Result<TErrorCodeEnum> failure(const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& format, Args... args) { return (Result(BaseResultCodes::FAILURE, inner_error, error_code, fmt::format(format, args...))); } TErrorCodeEnum error_code() const { return (error_code_); } const std::type_info& error_code_type() const { return (typeid(ErrorCodeType)); } int error_code_value() const { return ((int)error_code_); } protected: TErrorCodeEnum error_code_; }; template <typename TErrorCodeEnum, typename TResultType> class ResultWithReturnValue : public Result<TErrorCodeEnum> { protected: ResultWithReturnValue(BaseResultCodes success_or_failure, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, error_code, message) { } template <typename TInnerErrorCodeEnum> ResultWithReturnValue(BaseResultCodes success_or_failure, const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, inner_error, error_code, message) { } public: ResultWithReturnValue(TResultType return_value) : Result<TErrorCodeEnum>(BaseResultCodes::SUCCESS, TErrorCodeEnum::SUCCESS, "Success"), return_value_(return_value) { } ResultWithReturnValue(const ResultWithReturnValue& result_to_copy) : Result<TErrorCodeEnum>(result_to_copy.success_or_failure_, result_to_copy.error_code_, result_to_copy.message_), return_value_(result_to_copy.return_value_) { this->inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); } virtual ~ResultWithReturnValue(){}; operator const Result<TErrorCodeEnum>&() const { return (Result<TErrorCodeEnum>(this->success_or_failure_, this->error_code_, this->message_)); } const ResultWithReturnValue<TErrorCodeEnum, TResultType>& operator=( const ResultWithReturnValue<TErrorCodeEnum, TResultType>& result_to_copy) { ResultBase::success_or_failure_ = result_to_copy.success_or_failure_; ResultBase::message_ = result_to_copy.message_; Result<TErrorCodeEnum>::error_code_ = result_to_copy.error_code_; return_value_ = result_to_copy.return_value_; this->inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); return (*this); } static ResultWithReturnValue<TErrorCodeEnum, TResultType> success(const TResultType& return_value) { return (ResultWithReturnValue(return_value)); }; static ResultWithReturnValue<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnValue(BaseResultCodes::FAILURE, error_code, message)); } template <typename... Args> static ResultWithReturnValue<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& format, Args... args) { return (ResultWithReturnValue(BaseResultCodes::FAILURE, error_code, fmt::format(format, args...))); } template <typename TInnerErrorCodeEnum> static ResultWithReturnValue<TErrorCodeEnum, TResultType> failure(const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnValue(BaseResultCodes::FAILURE, inner_error, error_code, message)); } template <typename TInnerErrorCodeEnum, typename... Args> static ResultWithReturnValue<TErrorCodeEnum, TResultType> failure(const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& format, Args... args) { return ( ResultWithReturnValue(BaseResultCodes::FAILURE, inner_error, error_code, fmt::format(format, args...))); } TResultType& return_value() { assert(return_value_); return (*return_value_); } protected: std::optional<TResultType> return_value_; }; template <typename TErrorCodeEnum, typename TResultType> class ResultWithReturnRef : public Result<TErrorCodeEnum> { protected: ResultWithReturnRef(BaseResultCodes success_or_failure, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, error_code, message) { } template <typename TInnerErrorCodeEnum> ResultWithReturnRef(BaseResultCodes success_or_failure, const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, inner_error, error_code, message) { } public: ResultWithReturnRef(TResultType& return_ref) : Result<TErrorCodeEnum>(BaseResultCodes::SUCCESS, TErrorCodeEnum::SUCCESS, "Success"), return_ref_(return_ref) { } ResultWithReturnRef(const ResultWithReturnRef& result_to_copy) : Result<TErrorCodeEnum>(result_to_copy.success_or_failure_, result_to_copy.error_code_, result_to_copy.message_), return_ref_(result_to_copy.return_ref_) { this->inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); } virtual ~ResultWithReturnRef(){}; operator const Result<TErrorCodeEnum>&() const { return (Result<TErrorCodeEnum>(this->success_or_failure_, this->error_code_, this->message_)); } const ResultWithReturnRef<TErrorCodeEnum, TResultType>& operator=( const ResultWithReturnRef<TErrorCodeEnum, TResultType>& result_to_copy) { ResultBase::success_or_failure_ = result_to_copy.success_or_failure_; ResultBase::message_ = result_to_copy.message_; Result<TErrorCodeEnum>::error_code_ = result_to_copy.error_code_; return_ref_ = result_to_copy.return_ref_; this->inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); return (*this); } static ResultWithReturnRef<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnRef(BaseResultCodes::FAILURE, error_code, message)); } template <typename... Args> static ResultWithReturnRef<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& format, Args... args) { return (ResultWithReturnRef(BaseResultCodes::FAILURE, error_code, fmt::format(format, args...))); } template <typename TInnerErrorCodeEnum> static ResultWithReturnRef<TErrorCodeEnum, TResultType> failure(const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnRef(BaseResultCodes::FAILURE, inner_error, error_code, message)); } template <typename TInnerErrorCodeEnum, typename... Args> static ResultWithReturnRef<TErrorCodeEnum, TResultType> failure(const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& format, Args... args) { return (ResultWithReturnRef(BaseResultCodes::FAILURE, inner_error, error_code, fmt::format(format, args...))); } TResultType& return_ref() { assert(return_ref_); return (*return_ref_); } protected: std::optional<std::reference_wrapper<TResultType>> return_ref_; }; template <typename TErrorCodeEnum, typename TResultType> class ResultWithReturnUniquePtr : public Result<TErrorCodeEnum> { private: ResultWithReturnUniquePtr(BaseResultCodes success_or_failure, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, error_code, message) { } template <typename TInnerErrorCodeEnum> ResultWithReturnUniquePtr(BaseResultCodes success_or_failure, const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, inner_error, error_code, message) { } public: explicit ResultWithReturnUniquePtr(std::unique_ptr<TResultType>&& return_ptr) : Result<TErrorCodeEnum>(BaseResultCodes::SUCCESS, TErrorCodeEnum::SUCCESS, "Success"), return_ptr_(std::move(return_ptr)) { } ResultWithReturnUniquePtr(ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType>& result_to_copy) : Result<TErrorCodeEnum>(result_to_copy.success_or_failure_, result_to_copy.error_code_, result_to_copy.message_), return_ptr_(std::move(result_to_copy.return_ptr_)) { this->inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); } virtual ~ResultWithReturnUniquePtr(){}; operator const Result<TErrorCodeEnum>&() const { return (Result<TErrorCodeEnum>(this->success_or_failure_, this->error_code_, this->message_)); } const ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType>& operator=( const ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType>& result_to_copy) = delete; static ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType> success(std::unique_ptr<TResultType>&& return_value) { return (ResultWithReturnUniquePtr(std::move(return_value))); } static ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnUniquePtr(BaseResultCodes::FAILURE, error_code, message)); } template <typename... Args> static ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& format, Args... args) { return (ResultWithReturnUniquePtr(BaseResultCodes::FAILURE, error_code, fmt::format(format, args...))); } template <typename TInnerErrorCodeEnum> static ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType> failure( const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnUniquePtr(BaseResultCodes::FAILURE, inner_error, error_code, message)); } template <typename TInnerErrorCodeEnum, typename... Args> static ResultWithReturnUniquePtr<TErrorCodeEnum, TResultType> failure( const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& format, Args... args) { return (ResultWithReturnUniquePtr(BaseResultCodes::FAILURE, inner_error, error_code, fmt::format(format, args...))); } std::unique_ptr<TResultType>& return_ptr() { return (return_ptr_); } private: std::unique_ptr<TResultType> return_ptr_; }; template <typename TErrorCodeEnum, typename TResultType> class ResultWithReturnSharedPtr : public Result<TErrorCodeEnum> { private: ResultWithReturnSharedPtr(BaseResultCodes success_or_failure, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, error_code, message) { } template <typename TInnerErrorCodeEnum> ResultWithReturnSharedPtr(BaseResultCodes success_or_failure, const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) : Result<TErrorCodeEnum>(success_or_failure, inner_error, error_code, message) { } public: ResultWithReturnSharedPtr(std::shared_ptr<TResultType>& return_ptr) : Result<TErrorCodeEnum>(BaseResultCodes::SUCCESS, TErrorCodeEnum::SUCCESS, "Success"), return_ptr_(return_ptr) { } ResultWithReturnSharedPtr(const ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType>& result_to_copy) : Result<TErrorCodeEnum>(result_to_copy.success_or_failure_, result_to_copy.error_code_, result_to_copy.message_), return_ptr_(result_to_copy.return_ptr_) { this->inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); } virtual ~ResultWithReturnSharedPtr(){}; operator const Result<TErrorCodeEnum>&() const { return (Result<TErrorCodeEnum>(this->success_or_failure_, this->error_code_, this->message_)); } const ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType>& operator=( const ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType>& result_to_copy) { ResultBase::success_or_failure_ = result_to_copy.success_or_failure_; ResultBase::message_ = result_to_copy.message_; Result<TErrorCodeEnum>::error_code_ = result_to_copy.error_code_; return_ptr_ = result_to_copy.return_ptr_; this->inner_error_ = (result_to_copy.inner_error_ ? result_to_copy.inner_error_->shallow_copy() : nullptr); return (*this); } static ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType> success( std::shared_ptr<TResultType>& return_value) = delete; static ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnSharedPtr(BaseResultCodes::FAILURE, error_code, message)); } template <typename... Args> static ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType> failure(TErrorCodeEnum error_code, const std::string& format, Args... args) { return (ResultWithReturnSharedPtr(BaseResultCodes::FAILURE, error_code, fmt::format(format, args...))); } template <typename TInnerErrorCodeEnum> static ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType> failure( const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& message) { return (ResultWithReturnSharedPtr(BaseResultCodes::FAILURE, inner_error, error_code, message)); } template <typename TInnerErrorCodeEnum, typename... Args> static ResultWithReturnSharedPtr<TErrorCodeEnum, TResultType> failure( const Result<TInnerErrorCodeEnum>& inner_error, TErrorCodeEnum error_code, const std::string& format, Args... args) { return (ResultWithReturnSharedPtr(BaseResultCodes::FAILURE, inner_error, error_code, fmt::format(format, args...))); } std::shared_ptr<TResultType>& return_ptr() { return (return_ptr_); } private: std::shared_ptr<TResultType> return_ptr_; }; } // namespace SEFUtility
43.542169
126
0.633232
stephanfr
6ffd0f0757b63f95f1370ff8029595cb9fa3bfe9
140,462
cpp
C++
src/extra/imgui.cpp
fragcolor-xyz/chainblocks
bf83f8dc8f46637bc42713d1fa77e81228ddfccf
[ "BSD-3-Clause" ]
12
2021-07-11T11:14:14.000Z
2022-03-28T11:37:29.000Z
src/extra/imgui.cpp
fragcolor-xyz/chainblocks
bf83f8dc8f46637bc42713d1fa77e81228ddfccf
[ "BSD-3-Clause" ]
103
2021-06-26T17:09:43.000Z
2022-03-30T12:05:18.000Z
src/extra/imgui.cpp
fragcolor-xyz/chainblocks
bf83f8dc8f46637bc42713d1fa77e81228ddfccf
[ "BSD-3-Clause" ]
8
2021-07-27T14:45:26.000Z
2022-03-01T08:07:18.000Z
/* SPDX-License-Identifier: BSD-3-Clause */ /* Copyright © 2019 Fragcolor Pte. Ltd. */ #include "imgui.hpp" #include "bgfx.hpp" #include "blocks/shared.hpp" #include "runtime.hpp" #include <implot.h> using namespace chainblocks; namespace chainblocks { namespace ImGui { struct Base { static inline CBExposedTypeInfo ContextInfo = ExposedInfo::Variable( "GUI.Context", CBCCSTR("The ImGui Context."), Context::Info); static inline ExposedInfo requiredInfo = ExposedInfo(ContextInfo); CBExposedTypesInfo requiredVariables() { return CBExposedTypesInfo(requiredInfo); } static CBTypesInfo inputTypes() { return CoreInfo::AnyType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is not used and will pass through."); } static CBTypesInfo outputTypes() { return CoreInfo::AnyType; } static CBOptionalString outputHelp() { return CBCCSTR("The output of this block will be its input."); } }; struct IDContext { IDContext(void *ptr) { ::ImGui::PushID(ptr); } ~IDContext() { ::ImGui::PopID(); } }; struct Style : public Base { enum GuiStyle { Alpha, WindowPadding, WindowRounding, WindowBorderSize, WindowMinSize, WindowTitleAlign, WindowMenuButtonPosition, ChildRounding, ChildBorderSize, PopupRounding, PopupBorderSize, FramePadding, FrameRounding, FrameBorderSize, ItemSpacing, ItemInnerSpacing, TouchExtraPadding, IndentSpacing, ColumnsMinSpacing, ScrollbarSize, ScrollbarRounding, GrabMinSize, GrabRounding, TabRounding, TabBorderSize, ColorButtonPosition, ButtonTextAlign, SelectableTextAlign, DisplayWindowPadding, DisplaySafeAreaPadding, MouseCursorScale, AntiAliasedLines, AntiAliasedFill, CurveTessellationTol, TextColor, TextDisabledColor, WindowBgColor, ChildBgColor, PopupBgColor, BorderColor, BorderShadowColor, FrameBgColor, FrameBgHoveredColor, FrameBgActiveColor, TitleBgColor, TitleBgActiveColor, TitleBgCollapsedColor, MenuBarBgColor, ScrollbarBgColor, ScrollbarGrabColor, ScrollbarGrabHoveredColor, ScrollbarGrabActiveColor, CheckMarkColor, SliderGrabColor, SliderGrabActiveColor, ButtonColor, ButtonHoveredColor, ButtonActiveColor, HeaderColor, HeaderHoveredColor, HeaderActiveColor, SeparatorColor, SeparatorHoveredColor, SeparatorActiveColor, ResizeGripColor, ResizeGripHoveredColor, ResizeGripActiveColor, TabColor, TabHoveredColor, TabActiveColor, TabUnfocusedColor, TabUnfocusedActiveColor, PlotLinesColor, PlotLinesHoveredColor, PlotHistogramColor, PlotHistogramHoveredColor, TextSelectedBgColor, DragDropTargetColor, NavHighlightColor, NavWindowingHighlightColor, NavWindowingDimBgColor, ModalWindowDimBgColor, }; REGISTER_ENUM(GuiStyle, 'guiS'); // FourCC = 0x67756953 GuiStyle _key{}; static inline ParamsInfo paramsInfo = ParamsInfo( ParamsInfo::Param("Style", CBCCSTR("A style key to set."), GuiStyleType)); static CBParametersInfo parameters() { return CBParametersInfo(paramsInfo); } void setParam(int index, const CBVar &value) { switch (index) { case 0: _key = GuiStyle(value.payload.enumValue); break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var::Enum(_key, CoreCC, 'guiS'); default: return Var::Empty; } } CBTypeInfo compose(const CBInstanceData &data) { switch (_key) { case WindowRounding: case WindowBorderSize: case WindowMenuButtonPosition: case ChildRounding: case ChildBorderSize: case PopupRounding: case PopupBorderSize: case FrameRounding: case FrameBorderSize: case IndentSpacing: case ColumnsMinSpacing: case ScrollbarSize: case ScrollbarRounding: case GrabMinSize: case GrabRounding: case TabRounding: case TabBorderSize: case ColorButtonPosition: case MouseCursorScale: case AntiAliasedLines: case AntiAliasedFill: case CurveTessellationTol: case Alpha: if (data.inputType.basicType != Float) { throw CBException( "this GUI Style block expected a Float variable as input!"); } break; case WindowPadding: case WindowMinSize: case WindowTitleAlign: case FramePadding: case ItemSpacing: case ItemInnerSpacing: case TouchExtraPadding: case ButtonTextAlign: case SelectableTextAlign: case DisplayWindowPadding: case DisplaySafeAreaPadding: if (data.inputType.basicType != Float2) { throw CBException( "this GUI Style block expected a Float2 variable as input!"); } break; case TextColor: case TextDisabledColor: case WindowBgColor: case ChildBgColor: case PopupBgColor: case BorderColor: case BorderShadowColor: case FrameBgColor: case FrameBgHoveredColor: case FrameBgActiveColor: case TitleBgColor: case TitleBgActiveColor: case TitleBgCollapsedColor: case MenuBarBgColor: case ScrollbarBgColor: case ScrollbarGrabColor: case ScrollbarGrabHoveredColor: case ScrollbarGrabActiveColor: case CheckMarkColor: case SliderGrabColor: case SliderGrabActiveColor: case ButtonColor: case ButtonHoveredColor: case ButtonActiveColor: case HeaderColor: case HeaderHoveredColor: case HeaderActiveColor: case SeparatorColor: case SeparatorHoveredColor: case SeparatorActiveColor: case ResizeGripColor: case ResizeGripHoveredColor: case ResizeGripActiveColor: case TabColor: case TabHoveredColor: case TabActiveColor: case TabUnfocusedColor: case TabUnfocusedActiveColor: case PlotLinesColor: case PlotLinesHoveredColor: case PlotHistogramColor: case PlotHistogramHoveredColor: case TextSelectedBgColor: case DragDropTargetColor: case NavHighlightColor: case NavWindowingHighlightColor: case NavWindowingDimBgColor: case ModalWindowDimBgColor: if (data.inputType.basicType != Color) { throw CBException( "this GUI Style block expected a Color variable as input!"); } break; } return data.inputType; } static ImVec2 var2Vec2(const CBVar &input) { ImVec2 res; res.x = input.payload.float2Value[0]; res.y = input.payload.float2Value[1]; return res; } static ImVec4 color2Vec4(const CBColor &color) { ImVec4 res; res.x = color.r / 255.0f; res.y = color.g / 255.0f; res.z = color.b / 255.0f; res.w = color.a / 255.0f; return res; } static ImVec4 color2Vec4(const CBVar &input) { return color2Vec4(input.payload.colorValue); } static CBColor vec42Color(const ImVec4 &color) { CBColor res; res.r = roundf(color.x * 255.0f); res.g = roundf(color.y * 255.0f); res.b = roundf(color.z * 255.0f); res.a = roundf(color.w * 255.0f); return res; } CBVar activate(CBContext *context, const CBVar &input) { auto &style = ::ImGui::GetStyle(); switch (_key) { case Alpha: style.Alpha = input.payload.floatValue; break; case WindowPadding: style.WindowPadding = var2Vec2(input); break; case WindowRounding: style.WindowRounding = input.payload.floatValue; break; case WindowBorderSize: style.WindowBorderSize = input.payload.floatValue; break; case WindowMinSize: style.WindowMinSize = var2Vec2(input); break; case WindowTitleAlign: style.WindowTitleAlign = var2Vec2(input); break; case WindowMenuButtonPosition: style.WindowMenuButtonPosition = input.payload.floatValue; break; case ChildRounding: style.ChildRounding = input.payload.floatValue; break; case ChildBorderSize: style.ChildBorderSize = input.payload.floatValue; break; case PopupRounding: style.PopupRounding = input.payload.floatValue; break; case PopupBorderSize: style.PopupBorderSize = input.payload.floatValue; break; case FramePadding: style.FramePadding = var2Vec2(input); break; case FrameRounding: style.FrameRounding = input.payload.floatValue; break; case FrameBorderSize: style.FrameBorderSize = input.payload.floatValue; break; case ItemSpacing: style.ItemSpacing = var2Vec2(input); break; case ItemInnerSpacing: style.ItemInnerSpacing = var2Vec2(input); break; case TouchExtraPadding: style.TouchExtraPadding = var2Vec2(input); break; case IndentSpacing: style.IndentSpacing = input.payload.floatValue; break; case ColumnsMinSpacing: style.ColumnsMinSpacing = input.payload.floatValue; break; case ScrollbarSize: style.ScrollbarSize = input.payload.floatValue; break; case ScrollbarRounding: style.ScrollbarRounding = input.payload.floatValue; break; case GrabMinSize: style.GrabMinSize = input.payload.floatValue; break; case GrabRounding: style.GrabRounding = input.payload.floatValue; break; case TabRounding: style.TabRounding = input.payload.floatValue; break; case TabBorderSize: style.TabBorderSize = input.payload.floatValue; break; case ColorButtonPosition: style.ColorButtonPosition = input.payload.floatValue; break; case ButtonTextAlign: style.ButtonTextAlign = var2Vec2(input); break; case SelectableTextAlign: style.SelectableTextAlign = var2Vec2(input); break; case DisplayWindowPadding: style.DisplayWindowPadding = var2Vec2(input); break; case DisplaySafeAreaPadding: style.DisplaySafeAreaPadding = var2Vec2(input); break; case MouseCursorScale: style.MouseCursorScale = input.payload.floatValue; break; case AntiAliasedLines: style.AntiAliasedLines = input.payload.floatValue; break; case AntiAliasedFill: style.AntiAliasedFill = input.payload.floatValue; break; case CurveTessellationTol: style.CurveTessellationTol = input.payload.floatValue; break; case TextColor: style.Colors[ImGuiCol_Text] = color2Vec4(input); break; case TextDisabledColor: style.Colors[ImGuiCol_TextDisabled] = color2Vec4(input); break; case WindowBgColor: style.Colors[ImGuiCol_WindowBg] = color2Vec4(input); break; case ChildBgColor: style.Colors[ImGuiCol_ChildBg] = color2Vec4(input); break; case PopupBgColor: style.Colors[ImGuiCol_PopupBg] = color2Vec4(input); break; case BorderColor: style.Colors[ImGuiCol_Border] = color2Vec4(input); break; case BorderShadowColor: style.Colors[ImGuiCol_BorderShadow] = color2Vec4(input); break; case FrameBgColor: style.Colors[ImGuiCol_FrameBg] = color2Vec4(input); break; case FrameBgHoveredColor: style.Colors[ImGuiCol_FrameBgHovered] = color2Vec4(input); break; case FrameBgActiveColor: style.Colors[ImGuiCol_FrameBgActive] = color2Vec4(input); break; case TitleBgColor: style.Colors[ImGuiCol_TitleBg] = color2Vec4(input); break; case TitleBgActiveColor: style.Colors[ImGuiCol_TitleBgActive] = color2Vec4(input); break; case TitleBgCollapsedColor: style.Colors[ImGuiCol_TitleBgCollapsed] = color2Vec4(input); break; case MenuBarBgColor: style.Colors[ImGuiCol_MenuBarBg] = color2Vec4(input); break; case ScrollbarBgColor: style.Colors[ImGuiCol_ScrollbarBg] = color2Vec4(input); break; case ScrollbarGrabColor: style.Colors[ImGuiCol_ScrollbarGrab] = color2Vec4(input); break; case ScrollbarGrabHoveredColor: style.Colors[ImGuiCol_ScrollbarGrabHovered] = color2Vec4(input); break; case ScrollbarGrabActiveColor: style.Colors[ImGuiCol_ScrollbarGrabActive] = color2Vec4(input); break; case CheckMarkColor: style.Colors[ImGuiCol_CheckMark] = color2Vec4(input); break; case SliderGrabColor: style.Colors[ImGuiCol_SliderGrab] = color2Vec4(input); break; case SliderGrabActiveColor: style.Colors[ImGuiCol_SliderGrabActive] = color2Vec4(input); break; case ButtonColor: style.Colors[ImGuiCol_Button] = color2Vec4(input); break; case ButtonHoveredColor: style.Colors[ImGuiCol_ButtonHovered] = color2Vec4(input); break; case ButtonActiveColor: style.Colors[ImGuiCol_ButtonActive] = color2Vec4(input); break; case HeaderColor: style.Colors[ImGuiCol_Header] = color2Vec4(input); break; case HeaderHoveredColor: style.Colors[ImGuiCol_HeaderHovered] = color2Vec4(input); break; case HeaderActiveColor: style.Colors[ImGuiCol_HeaderActive] = color2Vec4(input); break; case SeparatorColor: style.Colors[ImGuiCol_Separator] = color2Vec4(input); break; case SeparatorHoveredColor: style.Colors[ImGuiCol_SeparatorHovered] = color2Vec4(input); break; case SeparatorActiveColor: style.Colors[ImGuiCol_SeparatorActive] = color2Vec4(input); break; case ResizeGripColor: style.Colors[ImGuiCol_ResizeGrip] = color2Vec4(input); break; case ResizeGripHoveredColor: style.Colors[ImGuiCol_ResizeGripHovered] = color2Vec4(input); break; case ResizeGripActiveColor: style.Colors[ImGuiCol_ResizeGripActive] = color2Vec4(input); break; case TabColor: style.Colors[ImGuiCol_Tab] = color2Vec4(input); break; case TabHoveredColor: style.Colors[ImGuiCol_TabHovered] = color2Vec4(input); break; case TabActiveColor: style.Colors[ImGuiCol_TabActive] = color2Vec4(input); break; case TabUnfocusedColor: style.Colors[ImGuiCol_TabUnfocused] = color2Vec4(input); break; case TabUnfocusedActiveColor: style.Colors[ImGuiCol_TabUnfocusedActive] = color2Vec4(input); break; case PlotLinesColor: style.Colors[ImGuiCol_PlotLines] = color2Vec4(input); break; case PlotLinesHoveredColor: style.Colors[ImGuiCol_PlotLinesHovered] = color2Vec4(input); break; case PlotHistogramColor: style.Colors[ImGuiCol_PlotHistogram] = color2Vec4(input); break; case PlotHistogramHoveredColor: style.Colors[ImGuiCol_PlotHistogramHovered] = color2Vec4(input); break; case TextSelectedBgColor: style.Colors[ImGuiCol_TextSelectedBg] = color2Vec4(input); break; case DragDropTargetColor: style.Colors[ImGuiCol_DragDropTarget] = color2Vec4(input); break; case NavHighlightColor: style.Colors[ImGuiCol_NavHighlight] = color2Vec4(input); break; case NavWindowingHighlightColor: style.Colors[ImGuiCol_NavWindowingHighlight] = color2Vec4(input); break; case NavWindowingDimBgColor: style.Colors[ImGuiCol_NavWindowingDimBg] = color2Vec4(input); break; case ModalWindowDimBgColor: style.Colors[ImGuiCol_ModalWindowDimBg] = color2Vec4(input); break; } return input; } }; struct Window : public Base { chainblocks::BlocksVar _blks{}; std::string _title; bool firstActivation{true}; Var _pos{}, _width{}, _height{}; ParamVar _flags{Var::Enum((int(Enums::GuiWindowFlags::NoResize) | int(Enums::GuiWindowFlags::NoMove) | int(Enums::GuiWindowFlags::NoCollapse)), CoreCC, Enums::GuiWindowFlagsCC)}; ParamVar _notClosed{Var::True}; std::array<CBExposedTypeInfo, 2> _required; static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static inline Parameters _params{ {"Title", CBCCSTR("The title of the window to create."), {CoreInfo::StringType}}, {"Pos", CBCCSTR("The x/y position of the window to create. If the value is a " "Float2, it will be interpreted as relative to the container " "window size."), {CoreInfo::Int2Type, CoreInfo::Float2Type, CoreInfo::NoneType}}, {"Width", CBCCSTR("The width of the window to create. If the value is a Float, it " "will be interpreted as relative to the container window size."), {CoreInfo::IntType, CoreInfo::FloatType, CoreInfo::NoneType}}, {"Height", CBCCSTR( "The height of the window to create. If the value is a Float, it " "will be interpreted as relative to the container window size."), {CoreInfo::IntType, CoreInfo::FloatType, CoreInfo::NoneType}}, {"Contents", CBCCSTR("The inner contents blocks."), CoreInfo::BlocksOrNone}, {"Flags", CBCCSTR("Flags to enable window options. The defaults are NoResize | " "NoMove | NoCollapse."), {Enums::GuiWindowFlagsType, Enums::GuiWindowFlagsVarType, Enums::GuiWindowFlagsSeqType, Enums::GuiWindowFlagsVarSeqType, CoreInfo::NoneType}}, {"OnClose", CBCCSTR("Passing a variable will display a close button in the " "upper-right corner. Clicking will set the variable to false " "and hide the window."), {CoreInfo::BoolVarType}}, }; static CBParametersInfo parameters() { return _params; } CBTypeInfo compose(const CBInstanceData &data) { _blks.compose(data); return data.inputType; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _title = value.payload.stringValue; break; case 1: _pos = Var(value); break; case 2: _width = Var(value); break; case 3: _height = Var(value); break; case 4: _blks = value; break; case 5: _flags = value; break; case 6: _notClosed = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_title); case 1: return _pos; case 2: return _width; case 3: return _height; case 4: return _blks; case 5: return _flags; case 6: return _notClosed; default: return Var::Empty; } } void cleanup() { _blks.cleanup(); _flags.cleanup(); _notClosed.cleanup(); } void warmup(CBContext *context) { _blks.warmup(context); _flags.warmup(context); _notClosed.warmup(context); firstActivation = true; } CBExposedTypesInfo requiredVariables() { int idx = 0; _required[idx] = Base::ContextInfo; idx++; if (_notClosed.isVariable()) { _required[idx].name = _notClosed.variableName(); _required[idx].help = CBCCSTR("The required OnClose."); _required[idx].exposedType = CoreInfo::BoolType; idx++; } return {_required.data(), uint32_t(idx), 0}; } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); if (!_blks) return input; auto flags = ::ImGuiWindowFlags_NoSavedSettings | ::ImGuiWindowFlags( chainblocks::getFlags<Enums::GuiWindowFlags>(_flags)); if (firstActivation) { const ImGuiIO &io = ::ImGui::GetIO(); if (_pos.valueType == Int2) { ImVec2 pos = {float(_pos.payload.int2Value[0]), float(_pos.payload.int2Value[1])}; ::ImGui::SetNextWindowPos(pos, ImGuiCond_Always); } else if (_pos.valueType == Float2) { const auto x = double(io.DisplaySize.x) * _pos.payload.float2Value[0]; const auto y = double(io.DisplaySize.y) * _pos.payload.float2Value[1]; ImVec2 pos = {float(x), float(y)}; ::ImGui::SetNextWindowPos(pos, ImGuiCond_Always); } ImVec2 size; if (_width.valueType == Int) { size.x = float(_width.payload.intValue); } else if (_width.valueType == Float) { size.x = io.DisplaySize.x * float(_width.payload.floatValue); } else { size.x = 0.f; } if (_height.valueType == Int) { size.y = float(_height.payload.intValue); } else if (_height.valueType == Float) { size.y = io.DisplaySize.y * float(_height.payload.floatValue); } else { size.y = 0.f; } ::ImGui::SetNextWindowSize(size, ImGuiCond_Always); firstActivation = false; } auto active = ::ImGui::Begin( _title.c_str(), _notClosed.isVariable() ? &_notClosed.get().payload.boolValue : nullptr, flags); DEFER(::ImGui::End()); if (active) { CBVar output{}; _blks.activate(context, input, output); } return input; } }; struct ChildWindow : public Base { chainblocks::BlocksVar _blks{}; CBVar _width{}, _height{}; bool _border = false; static inline ImGuiID windowIds{0}; ImGuiID _wndId = ++windowIds; static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static inline ParamsInfo paramsInfo = ParamsInfo( ParamsInfo::Param("Width", CBCCSTR("The width of the child window to create"), CoreInfo::IntOrNone), ParamsInfo::Param("Height", CBCCSTR("The height of the child window to create."), CoreInfo::IntOrNone), ParamsInfo::Param( "Border", CBCCSTR("If we want to draw a border frame around the child window."), CoreInfo::BoolType), ParamsInfo::Param("Contents", CBCCSTR("The inner contents blocks."), CoreInfo::BlocksOrNone)); static CBParametersInfo parameters() { return CBParametersInfo(paramsInfo); } CBTypeInfo compose(const CBInstanceData &data) { _blks.compose(data); return data.inputType; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _width = value; break; case 1: _height = value; break; case 2: _border = value.payload.boolValue; break; case 3: _blks = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _width; case 1: return _height; case 2: return Var(_border); case 3: return _blks; default: return Var::Empty; } } void cleanup() { _blks.cleanup(); } void warmup(CBContext *context) { _blks.warmup(context); } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); if (!_blks) return input; ImVec2 size{0, 0}; if (_width.valueType == Int) { size.x = float(_width.payload.intValue); } if (_height.valueType == Int) { size.y = float(_height.payload.intValue); } auto visible = ::ImGui::BeginChild(_wndId, size, _border); DEFER(::ImGui::EndChild()); if (visible) { CBVar output{}; _blks.activate(context, input, output); } return input; } }; Parameters &VariableParamsInfo() { static Parameters params{ {"Label", CBCCSTR("The label for this widget."), CoreInfo::StringOrNone}, {"Variable", CBCCSTR("The variable that holds the input value."), {CoreInfo::AnyVarType, CoreInfo::NoneType}}, }; return params; } template <CBType CT> struct Variable : public Base { static inline Type varType{{CT}}; std::string _label; ParamVar _variable{}; ExposedInfo _expInfo{}; bool _exposing = false; void cleanup() { _variable.cleanup(); } void warmup(CBContext *context) { _variable.warmup(context); } CBTypeInfo compose(const CBInstanceData &data) { if (_variable.isVariable()) { _exposing = true; // assume we expose a new variable // search for a possible existing variable and ensure it's the right type for (auto &var : data.shared) { if (strcmp(var.name, _variable.variableName()) == 0) { // we found a variable, make sure it's the right type and mark // exposing off _exposing = false; if (CT != CBType::Any && var.exposedType.basicType != CT) { throw CBException("GUI - Variable: Existing variable type not " "matching the input."); } // also make sure it's mutable! if (!var.isMutable) { throw CBException( "GUI - Variable: Existing variable is not mutable."); } break; } } } return varType; } CBExposedTypesInfo requiredVariables() { if (_variable.isVariable() && !_exposing) { _expInfo = ExposedInfo( requiredInfo, ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The required input variable."), CBTypeInfo(varType))); return CBExposedTypesInfo(_expInfo); } else { return {}; } } CBExposedTypesInfo exposedVariables() { if (_variable.isVariable() > 0 && _exposing) { _expInfo = ExposedInfo( requiredInfo, ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The exposed input variable."), CBTypeInfo(varType), true)); return CBExposedTypesInfo(_expInfo); } else { return {}; } } static CBParametersInfo parameters() { static CBParametersInfo info = VariableParamsInfo(); return info; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _label.clear(); } else { _label = value.payload.stringValue; } } break; case 1: _variable = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _label.size() == 0 ? Var::Empty : Var(_label); case 1: return _variable; default: return Var::Empty; } } }; template <CBType CT1, CBType CT2> struct Variable2 : public Base { static inline Type varType1{{CT1}}; static inline Type varType2{{CT2}}; std::string _label; ParamVar _variable{}; ExposedInfo _expInfo{}; bool _exposing = false; void cleanup() { _variable.cleanup(); } void warmup(CBContext *context) { _variable.warmup(context); } CBTypeInfo compose(const CBInstanceData &data) { if (_variable.isVariable()) { _exposing = true; // assume we expose a new variable // search for a possible existing variable and ensure it's the right type for (auto &var : data.shared) { if (strcmp(var.name, _variable.variableName()) == 0) { // we found a variable, make sure it's the right type and mark // exposing off _exposing = false; if (var.exposedType.basicType != CT1 && var.exposedType.basicType != CT2) { throw CBException("GUI - Variable: Existing variable type not " "matching the input."); } // also make sure it's mutable! if (!var.isMutable) { throw CBException( "GUI - Variable: Existing variable is not mutable."); } break; } } } return CoreInfo::AnyType; } CBExposedTypesInfo requiredVariables() { if (_variable.isVariable() && !_exposing) { _expInfo = ExposedInfo( requiredInfo, ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The required input variable."), CBTypeInfo(varType1)), ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The required input variable."), CBTypeInfo(varType2))); return CBExposedTypesInfo(_expInfo); } else { return {}; } } CBExposedTypesInfo exposedVariables() { if (_variable.isVariable() && _exposing) { _expInfo = ExposedInfo( requiredInfo, ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The exposed input variable."), CBTypeInfo(varType1), true), ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The exposed input variable."), CBTypeInfo(varType2), true)); return CBExposedTypesInfo(_expInfo); } else { return {}; } } static CBParametersInfo parameters() { static CBParametersInfo info = VariableParamsInfo(); return info; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _label.clear(); } else { _label = value.payload.stringValue; } } break; case 1: _variable = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _label.size() == 0 ? Var::Empty : Var(_label); case 1: return _variable; default: return Var::Empty; } } }; struct Checkbox : public Variable<CBType::Bool> { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the checkbox changed state " "during that frame."); } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); auto result = Var::False; if (_variable.isVariable()) { _variable.get().valueType = CBType::Bool; if (::ImGui::Checkbox(_label.c_str(), &_variable.get().payload.boolValue)) { result = Var::True; } } else { // HACK kinda... we recycle _exposing since we are not using it in this // branch if (::ImGui::Checkbox(_label.c_str(), &_exposing)) { result = Var::True; } } return result; } }; struct CheckboxFlags : public Variable2<CBType::Int, CBType::Enum> { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the checkbox changed state " "during that frame."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { if (index < 2) Variable2<CBType::Int, CBType::Enum>::setParam(index, value); else _value = value; } CBVar getParam(int index) { if (index < 2) return Variable2<CBType::Int, CBType::Enum>::getParam(index); else return _value; } CBTypeInfo compose(const CBInstanceData &data) { Variable2<CBType::Int, CBType::Enum>::compose(data); // ideally here we should check that the type of _value is the same as // _variable. return CoreInfo::BoolType; } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); auto result = Var::False; switch (_value.valueType) { case CBType::Int: { int *flags; if (_variable.isVariable()) { _variable.get().valueType = CBType::Int; flags = reinterpret_cast<int *>(&_variable.get().payload.intValue); } else { flags = reinterpret_cast<int *>(&_tmp.payload.intValue); } if (::ImGui::CheckboxFlags(_label.c_str(), flags, int(_value.payload.intValue))) { result = Var::True; } } break; case CBType::Enum: { int *flags; if (_variable.isVariable()) { _variable.get().valueType = CBType::Enum; flags = reinterpret_cast<int *>(&_variable.get().payload.enumValue); } else { flags = reinterpret_cast<int *>(&_tmp.payload.enumValue); } if (::ImGui::CheckboxFlags(_label.c_str(), flags, int(_value.payload.enumValue))) { result = Var::True; } } break; default: break; } return result; } private: static inline Parameters _params{ VariableParamsInfo(), {{"Value", CBCCSTR("The flag value to set or unset."), {CoreInfo::IntType, CoreInfo::AnyEnumType}}}}; CBVar _value{}; CBVar _tmp{}; }; struct RadioButton : public Variable<CBType::Any> { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the radio button changed " "state during that frame."); } static CBParametersInfo parameters() { return paramsInfo; } void setParam(int index, const CBVar &value) { if (index < 2) Variable<CBType::Any>::setParam(index, value); else _value = value; } CBVar getParam(int index) { if (index < 2) return Variable<CBType::Any>::getParam(index); else return _value; } CBExposedTypesInfo requiredVariables() { if (_variable.isVariable() && !_exposing) { _expInfo = ExposedInfo( requiredInfo, ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The required input variable."), CBTypeInfo({_value.valueType}))); return CBExposedTypesInfo(_expInfo); } else { return {}; } } CBExposedTypesInfo exposedVariables() { if (_variable.isVariable() > 0 && _exposing) { _expInfo = ExposedInfo( requiredInfo, ExposedInfo::Variable(_variable.variableName(), CBCCSTR("The exposed input variable."), CBTypeInfo({_value.valueType}), true)); return CBExposedTypesInfo(_expInfo); } else { return {}; } } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); auto result = Var::False; if (_variable.isVariable()) { auto &var = _variable.get(); if (::ImGui::RadioButton(_label.c_str(), var == _value)) { chainblocks::cloneVar(var, _value); result = Var::True; } } else { // HACK kinda... we recycle _exposing since we are not using it in this // branch if (::ImGui::RadioButton(_label.c_str(), _exposing)) { result = Var::True; } } return result; } private: static inline Parameters paramsInfo{ VariableParamsInfo(), {{"Value", CBCCSTR("The value to compare with."), {CoreInfo::AnyType}}}}; CBVar _value{}; }; struct Text : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value to display."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _label.clear(); } else { _label = value.payload.stringValue; } } break; case 1: _color = value; break; case 2: { if (value.valueType == None) { _format.clear(); } else { _format = value.payload.stringValue; } } break; case 3: _wrap = value.payload.boolValue; break; case 4: _bullet = value.payload.boolValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _label.size() == 0 ? Var::Empty : Var(_label); case 1: return _color; case 2: return _format.size() == 0 ? Var::Empty : Var(_format); case 3: return Var(_wrap); case 4: return Var(_bullet); default: return Var::Empty; } } VarStringStream _text; CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); _text.write(input); if (_color.valueType == Color) ::ImGui::PushStyleColor(ImGuiCol_Text, Style::color2Vec4(_color)); auto format = "%s"; if (_format.size() > 0) { auto pos = _format.find("{}"); // while (pos != std::string::npos) { if (pos != std::string::npos) { _format.replace(pos, 2, format); // pos = _format.find("{}", pos + 2); // TODO support multiple args } format = _format.c_str(); } if (_wrap) ::ImGui::PushTextWrapPos(0.0f); if (_bullet) ::ImGui::Bullet(); if (_label.size() > 0) { ::ImGui::LabelText(_label.c_str(), format, _text.str()); } else { ::ImGui::Text(format, _text.str()); } if (_wrap) ::ImGui::PopTextWrapPos(); if (_color.valueType == Color) ::ImGui::PopStyleColor(); return input; } private: static inline Parameters _params = { {"Label", CBCCSTR("An optional label for the value."), {CoreInfo::StringOrNone}}, {"Color", CBCCSTR("The optional color of the text."), {CoreInfo::ColorOrNone}}, {"Format", CBCCSTR("An optional format for the text."), {CoreInfo::StringOrNone}}, {"Wrap", CBCCSTR("Whether to wrap the text to the next line if it doesn't fit " "horizontally."), {CoreInfo::BoolType}}, {"Bullet", CBCCSTR("Display a small circle before the text."), {CoreInfo::BoolType}}, }; std::string _label; CBVar _color{}; std::string _format; bool _wrap{false}; bool _bullet{false}; }; struct Bullet : public Base { static CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::Bullet(); return input; } }; struct Button : public Base { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the button was clicked during " "that frame."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _label = value.payload.stringValue; break; case 1: _blocks = value; break; case 2: _type = Enums::GuiButton(value.payload.enumValue); break; case 3: _size.x = value.payload.float2Value[0]; _size.y = value.payload.float2Value[1]; break; case 4: _repeat = value.payload.boolValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_label); case 1: return _blocks; case 2: return Var::Enum(_type, CoreCC, Enums::GuiButtonCC); case 3: return Var(_size.x, _size.x); case 4: return Var(_repeat); default: return Var::Empty; } } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return CoreInfo::BoolType; } void cleanup() { _blocks.cleanup(); } void warmup(CBContext *ctx) { _blocks.warmup(ctx); } #define IMBTN_RUN_ACTION \ { \ CBVar output = Var::Empty; \ _blocks.activate(context, input, output); \ } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); ::ImGui::PushButtonRepeat(_repeat); DEFER(::ImGui::PopButtonRepeat()); auto result = Var::False; ImVec2 size; switch (_type) { case Enums::GuiButton::Normal: if (::ImGui::Button(_label.c_str(), _size)) { IMBTN_RUN_ACTION; result = Var::True; } break; case Enums::GuiButton::Small: if (::ImGui::SmallButton(_label.c_str())) { IMBTN_RUN_ACTION; result = Var::True; } break; case Enums::GuiButton::Invisible: if (::ImGui::InvisibleButton(_label.c_str(), _size)) { IMBTN_RUN_ACTION; result = Var::True; } break; case Enums::GuiButton::ArrowLeft: if (::ImGui::ArrowButton(_label.c_str(), ImGuiDir_Left)) { IMBTN_RUN_ACTION; result = Var::True; } break; case Enums::GuiButton::ArrowRight: if (::ImGui::ArrowButton(_label.c_str(), ImGuiDir_Right)) { IMBTN_RUN_ACTION; result = Var::True; } break; case Enums::GuiButton::ArrowUp: if (::ImGui::ArrowButton(_label.c_str(), ImGuiDir_Up)) { IMBTN_RUN_ACTION; result = Var::True; } break; case Enums::GuiButton::ArrowDown: if (::ImGui::ArrowButton(_label.c_str(), ImGuiDir_Down)) { IMBTN_RUN_ACTION; result = Var::True; } break; } return result; } private: static inline Parameters _params = { {"Label", CBCCSTR("The text label of this button."), {CoreInfo::StringType}}, {"Action", CBCCSTR("The blocks to execute when the button is pressed."), CoreInfo::BlocksOrNone}, {"Type", CBCCSTR("The button type."), {Enums::GuiButtonType}}, {"Size", CBCCSTR("The optional size override."), {CoreInfo::Float2Type}}, {"Repeat", CBCCSTR("Whether to repeat the action while the button is pressed."), {CoreInfo::BoolType}}, }; std::string _label; BlocksVar _blocks{}; Enums::GuiButton _type{}; ImVec2 _size = {0, 0}; bool _repeat{false}; }; struct HexViewer : public Base { // TODO use a variable so edits are possible and easy static CBTypesInfo inputTypes() { return CoreInfo::BytesType; } static CBOptionalString inputHelp() { return CBCCSTR("The value to display in the viewer."); } static CBTypesInfo outputTypes() { return CoreInfo::BytesType; } ImGuiExtra::MemoryEditor _editor{}; // HexViewer() { _editor.ReadOnly = true; } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); _editor.DrawContents(input.payload.bytesValue, input.payload.bytesSize); return input; } }; struct Dummy : public Base { static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _width = value; break; case 1: _height = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _width; case 1: return _height; default: return Var::Empty; } } void cleanup() { _width.cleanup(); _height.cleanup(); } void warmup(CBContext *ctx) { _width.warmup(ctx); _height.warmup(ctx); } CBVar activate(CBContext *context, const CBVar &input) { auto width = float(_width.get().payload.intValue); auto height = float(_height.get().payload.intValue); ::ImGui::Dummy({width, height}); return input; } private: static inline Parameters _params = { {"Width", CBCCSTR("The width of the item."), CoreInfo::IntOrIntVar}, {"Height", CBCCSTR("The height of the item."), CoreInfo::IntOrIntVar}, }; ParamVar _width{Var(0)}; ParamVar _height{Var(0)}; }; struct NewLine : public Base { CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::NewLine(); return input; } }; struct SameLine : public Base { // TODO add offsets and spacing CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::SameLine(); return input; } }; struct Separator : public Base { static CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::Separator(); return input; } }; struct Spacing : public Base { static CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::Spacing(); return input; } }; struct Indent : public Base { static CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::Indent(); return input; } }; struct Unindent : public Base { static CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::Unindent(); return input; } }; struct GetClipboard : public Base { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::StringType; } static CBOptionalString outputHelp() { return CBCCSTR("The content of the clipboard."); } static CBVar activate(CBContext *context, const CBVar &input) { auto contents = ::ImGui::GetClipboardText(); if (contents) return Var(contents); else return Var(""); } }; struct SetClipboard : public Base { static CBTypesInfo inputTypes() { return CoreInfo::StringType; } static CBOptionalString inputHelp() { return CBCCSTR("The value to set in the clipboard."); } static CBTypesInfo outputTypes() { return CoreInfo::StringType; } static CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::SetClipboardText(input.payload.stringValue); return input; } }; struct TreeNode : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the tree node is open."); } static CBParametersInfo parameters() { return _params; } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return CoreInfo::BoolType; } void cleanup() { _blocks.cleanup(); _flags.cleanup(); } void warmup(CBContext *context) { _blocks.warmup(context); _flags.warmup(context); } void setParam(int index, const CBVar &value) { switch (index) { case 0: _label = value.payload.stringValue; break; case 1: _blocks = value; break; case 2: _defaultOpen = value.payload.boolValue; break; case 3: _flags = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_label); case 1: return _blocks; case 2: return Var(_defaultOpen); case 3: return _flags; default: return CBVar(); } } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); auto flags = ::ImGuiTreeNodeFlags( chainblocks::getFlags<Enums::GuiTreeNodeFlags>(_flags.get())); if (_defaultOpen) { flags |= ::ImGuiTreeNodeFlags_DefaultOpen; } auto visible = ::ImGui::TreeNodeEx(_label.c_str(), flags); if (visible) { CBVar output{}; // run inner blocks _blocks.activate(context, input, output); // pop the node if was visible ::ImGui::TreePop(); } return Var(visible); } private: static inline Parameters _params = { {"Label", CBCCSTR("The label of this node."), {CoreInfo::StringType}}, {"Contents", CBCCSTR("The contents of this node."), CoreInfo::BlocksOrNone}, {"StartOpen", CBCCSTR("If this node should start in the open state."), {CoreInfo::BoolType}}, {"Flags", CBCCSTR("Flags to enable tree node options."), {Enums::GuiTreeNodeFlagsType, Enums::GuiTreeNodeFlagsVarType, Enums::GuiTreeNodeFlagsSeqType, Enums::GuiTreeNodeFlagsVarSeqType, CoreInfo::NoneType}}, }; std::string _label; bool _defaultOpen = false; BlocksVar _blocks; ParamVar _flags{}; }; struct CollapsingHeader : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the header is open."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _label = value.payload.stringValue; break; case 1: _blocks = value; break; case 2: _defaultOpen = value.payload.boolValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_label); case 1: return _blocks; case 2: return Var(_defaultOpen); default: return Var::Empty; } } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return CoreInfo::BoolType; } void cleanup() { _blocks.cleanup(); } void warmup(CBContext *ctx) { _blocks.warmup(ctx); } CBVar activate(CBContext *context, const CBVar &input) { if (_defaultOpen) { ::ImGui::SetNextItemOpen(true); _defaultOpen = false; } auto active = ::ImGui::CollapsingHeader(_label.c_str()); if (active) { CBVar output{}; _blocks.activate(context, input, output); } return Var(active); } private: static inline Parameters _params = { {"Label", CBCCSTR("The label of this node."), {CoreInfo::StringType}}, {"Contents", CBCCSTR("The contents under this header."), {CoreInfo::BlocksOrNone}}, {"StartOpen", CBCCSTR("If this header should start in the open state."), {CoreInfo::BoolType}}, }; std::string _label; BlocksVar _blocks{}; bool _defaultOpen = false; }; template <CBType CBT> struct DragBase : public Variable<CBT> { float _speed{1.0}; static inline Parameters paramsInfo{ VariableParamsInfo(), {{"Speed", CBCCSTR("The speed multiplier for this drag widget."), CoreInfo::StringOrNone}}}; static CBParametersInfo parameters() { return paramsInfo; } void setParam(int index, const CBVar &value) { if (index < 2) Variable<CBT>::setParam(index, value); else _speed = value.payload.floatValue; } CBVar getParam(int index) { if (index < 2) return Variable<CBT>::getParam(index); else return Var(_speed); } }; #define IMGUIDRAG(_CBT_, _T_, _INFO_, _IMT_, _VAL_) \ struct _CBT_##Drag : public DragBase<CBType::_CBT_> { \ _T_ _tmp; \ \ static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } \ static CBOptionalString inputHelp() { \ return CBCCSTR("The input value is ignored."); \ } \ \ static CBTypesInfo outputTypes() { return CoreInfo::_INFO_; } \ static CBOptionalString outputHelp() { \ return CBCCSTR("The value produced by this block."); \ } \ \ CBVar activate(CBContext *context, const CBVar &input) { \ IDContext idCtx(this); \ \ if (_variable.isVariable()) { \ auto &var = _variable.get(); \ ::ImGui::DragScalar(_label.c_str(), _IMT_, (void *)&var.payload._VAL_, \ _speed); \ \ var.valueType = CBType::_CBT_; \ return var; \ } else { \ ::ImGui::DragScalar(_label.c_str(), _IMT_, (void *)&_tmp, _speed); \ return Var(_tmp); \ } \ } \ } IMGUIDRAG(Int, int64_t, IntType, ImGuiDataType_S64, intValue); IMGUIDRAG(Float, double, FloatType, ImGuiDataType_Double, floatValue); #define IMGUIDRAG2(_CBT_, _T_, _INFO_, _IMT_, _VAL_, _CMP_) \ struct _CBT_##Drag : public DragBase<CBType::_CBT_> { \ CBVar _tmp; \ \ static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } \ static CBOptionalString inputHelp() { \ return CBCCSTR("The input value is ignored."); \ } \ \ static CBTypesInfo outputTypes() { return CoreInfo::_INFO_; } \ static CBOptionalString outputHelp() { \ return CBCCSTR("The value produced by this block."); \ } \ \ CBVar activate(CBContext *context, const CBVar &input) { \ IDContext idCtx(this); \ \ if (_variable.isVariable()) { \ auto &var = _variable.get(); \ ::ImGui::DragScalarN(_label.c_str(), _IMT_, \ (void *)&var.payload._VAL_, _CMP_, _speed); \ \ var.valueType = CBType::_CBT_; \ return var; \ } else { \ _tmp.valueType = CBType::_CBT_; \ ::ImGui::DragScalarN(_label.c_str(), _IMT_, \ (void *)&_tmp.payload._VAL_, _CMP_, _speed); \ return _tmp; \ } \ } \ } IMGUIDRAG2(Int2, int64_t, Int2Type, ImGuiDataType_S64, int2Value, 2); IMGUIDRAG2(Int3, int32_t, Int3Type, ImGuiDataType_S32, int3Value, 3); IMGUIDRAG2(Int4, int32_t, Int4Type, ImGuiDataType_S32, int4Value, 4); IMGUIDRAG2(Float2, double, Float2Type, ImGuiDataType_Double, float2Value, 2); IMGUIDRAG2(Float3, float, Float3Type, ImGuiDataType_Float, float3Value, 3); IMGUIDRAG2(Float4, float, Float4Type, ImGuiDataType_Float, float4Value, 4); #define IMGUIINPUT(_CBT_, _T_, _IMT_, _VAL_, _FMT_) \ struct _CBT_##Input : public Variable<CBType::_CBT_> { \ _T_ _tmp; \ \ static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } \ static CBOptionalString inputHelp() { \ return CBCCSTR("The input value is ignored."); \ } \ \ static CBTypesInfo outputTypes() { return CoreInfo::_CBT_##Type; } \ static CBOptionalString outputHelp() { \ return CBCCSTR("The value that was input."); \ } \ \ static CBParametersInfo parameters() { return paramsInfo; } \ \ void cleanup() { \ _step.cleanup(); \ _stepFast.cleanup(); \ Variable<CBType::_CBT_>::cleanup(); \ } \ \ void warmup(CBContext *context) { \ Variable<CBType::_CBT_>::warmup(context); \ _step.warmup(context); \ _stepFast.warmup(context); \ } \ \ void setParam(int index, const CBVar &value) { \ switch (index) { \ case 0: \ case 1: \ Variable<CBType::_CBT_>::setParam(index, value); \ break; \ case 2: \ _step = value; \ break; \ case 3: \ _stepFast = value; \ break; \ default: \ break; \ } \ } \ \ CBVar getParam(int index) { \ switch (index) { \ case 0: \ case 1: \ return Variable<CBType::_CBT_>::getParam(index); \ case 2: \ return _step; \ case 3: \ return _stepFast; \ default: \ return Var::Empty; \ } \ } \ \ CBVar activate(CBContext *context, const CBVar &input) { \ IDContext idCtx(this); \ \ _T_ step = _step.get().payload._VAL_##Value; \ _T_ step_fast = _stepFast.get().payload._VAL_##Value; \ if (_variable.isVariable()) { \ auto &var = _variable.get(); \ ::ImGui::InputScalar(_label.c_str(), _IMT_, \ (void *)&var.payload._VAL_##Value, \ step > 0 ? &step : nullptr, \ step_fast > 0 ? &step_fast : nullptr, _FMT_, 0); \ \ var.valueType = CBType::_CBT_; \ return var; \ } else { \ ::ImGui::InputScalar(_label.c_str(), _IMT_, (void *)&_tmp, \ step > 0 ? &step : nullptr, \ step_fast > 0 ? &step_fast : nullptr, _FMT_, 0); \ return Var(_tmp); \ } \ } \ \ private: \ static inline Parameters paramsInfo{ \ VariableParamsInfo(), \ {{"Step", \ CBCCSTR("The value of a single increment."), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}, \ {"StepFast", \ CBCCSTR("The value of a single increment, when holding Ctrl"), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}}, \ }; \ \ ParamVar _step{Var((_T_)0)}; \ ParamVar _stepFast{Var((_T_)0)}; \ } IMGUIINPUT(Int, int64_t, ImGuiDataType_S64, int, "%lld"); IMGUIINPUT(Float, double, ImGuiDataType_Double, float, "%.3f"); #define IMGUIINPUT2(_CBT_, _CMP_, _T_, _IMT_, _VAL_, _FMT_) \ struct _CBT_##_CMP_##Input : public Variable<CBType::_CBT_##_CMP_> { \ CBVar _tmp; \ \ static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } \ static CBOptionalString inputHelp() { \ return CBCCSTR("The input value is ignored."); \ } \ \ static CBTypesInfo outputTypes() { return CoreInfo::_CBT_##_CMP_##Type; } \ static CBOptionalString outputHelp() { \ return CBCCSTR("The value that was input."); \ } \ \ static CBParametersInfo parameters() { return paramsInfo; } \ \ void cleanup() { \ _step.cleanup(); \ _stepFast.cleanup(); \ Variable<CBType::_CBT_##_CMP_>::cleanup(); \ } \ \ void warmup(CBContext *context) { \ Variable<CBType::_CBT_##_CMP_>::warmup(context); \ _step.warmup(context); \ _stepFast.warmup(context); \ } \ \ void setParam(int index, const CBVar &value) { \ switch (index) { \ case 0: \ case 1: \ Variable<CBType::_CBT_##_CMP_>::setParam(index, value); \ break; \ case 2: \ _step = value; \ break; \ case 3: \ _stepFast = value; \ break; \ default: \ break; \ } \ } \ \ CBVar getParam(int index) { \ switch (index) { \ case 0: \ case 1: \ return Variable<CBType::_CBT_##_CMP_>::getParam(index); \ case 2: \ return _step; \ case 3: \ return _stepFast; \ default: \ return Var::Empty; \ } \ } \ \ CBVar activate(CBContext *context, const CBVar &input) { \ IDContext idCtx(this); \ \ _T_ step = _step.get().payload._VAL_##Value; \ _T_ step_fast = _stepFast.get().payload._VAL_##Value; \ if (_variable.isVariable()) { \ auto &var = _variable.get(); \ ::ImGui::InputScalarN(_label.c_str(), _IMT_, \ (void *)&var.payload._VAL_##_CMP_##Value, _CMP_, \ step > 0 ? &step : nullptr, \ step_fast > 0 ? &step_fast : nullptr, _FMT_, 0); \ \ var.valueType = CBType::_CBT_; \ return var; \ } else { \ _tmp.valueType = CBType::_CBT_; \ ::ImGui::InputScalarN(_label.c_str(), _IMT_, \ (void *)&_tmp.payload._VAL_##_CMP_##Value, \ _CMP_, step > 0 ? &step : nullptr, \ step_fast > 0 ? &step_fast : nullptr, _FMT_, 0); \ return _tmp; \ } \ } \ \ private: \ static inline Parameters paramsInfo{ \ VariableParamsInfo(), \ {{"Step", \ CBCCSTR("The value of a single increment."), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}, \ {"StepFast", \ CBCCSTR("The value of a single increment, when holding Ctrl"), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}}, \ }; \ \ ParamVar _step{Var((_T_)0)}; \ ParamVar _stepFast{Var((_T_)0)}; \ } IMGUIINPUT2(Int, 2, int64_t, ImGuiDataType_S64, int, "%lld"); IMGUIINPUT2(Int, 3, int32_t, ImGuiDataType_S32, int, "%d"); IMGUIINPUT2(Int, 4, int32_t, ImGuiDataType_S32, int, "%d"); IMGUIINPUT2(Float, 2, double, ImGuiDataType_Double, float, "%.3f"); IMGUIINPUT2(Float, 3, float, ImGuiDataType_Float, float, "%.3f"); IMGUIINPUT2(Float, 4, float, ImGuiDataType_Float, float, "%.3f"); #define IMGUISLIDER(_CBT_, _T_, _IMT_, _VAL_, _FMT_) \ struct _CBT_##Slider : public Variable<CBType::_CBT_> { \ \ static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } \ static CBOptionalString inputHelp() { \ return CBCCSTR("The input value is ignored."); \ } \ \ static CBTypesInfo outputTypes() { return CoreInfo::_CBT_##Type; } \ static CBOptionalString outputHelp() { \ return CBCCSTR("The value produced by this block."); \ } \ \ static CBParametersInfo parameters() { return paramsInfo; } \ \ void cleanup() { \ _min.cleanup(); \ _max.cleanup(); \ Variable<CBType::_CBT_>::cleanup(); \ } \ \ void warmup(CBContext *context) { \ Variable<CBType::_CBT_>::warmup(context); \ _min.warmup(context); \ _max.warmup(context); \ } \ \ void setParam(int index, const CBVar &value) { \ switch (index) { \ case 0: \ case 1: \ Variable<CBType::_CBT_>::setParam(index, value); \ break; \ case 2: \ _min = value; \ break; \ case 3: \ _max = value; \ break; \ default: \ break; \ } \ } \ \ CBVar getParam(int index) { \ switch (index) { \ case 0: \ case 1: \ return Variable<CBType::_CBT_>::getParam(index); \ case 2: \ return _min; \ case 3: \ return _max; \ default: \ return Var::Empty; \ } \ } \ \ CBVar activate(CBContext *context, const CBVar &input) { \ IDContext idCtx(this); \ \ _T_ min = _min.get().payload._VAL_##Value; \ _T_ max = _max.get().payload._VAL_##Value; \ if (_variable.isVariable()) { \ auto &var = _variable.get(); \ ::ImGui::SliderScalar(_label.c_str(), _IMT_, \ (void *)&var.payload._VAL_##Value, &min, &max, \ _FMT_, 0); \ \ var.valueType = CBType::_CBT_; \ return var; \ } else { \ ::ImGui::SliderScalar(_label.c_str(), _IMT_, (void *)&_tmp, &min, \ &max, _FMT_, 0); \ return Var(_tmp); \ } \ } \ \ private: \ static inline Parameters paramsInfo{ \ VariableParamsInfo(), \ {{"Min", \ CBCCSTR("The minimum value."), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}, \ {"Max", \ CBCCSTR("The maximum value."), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}}, \ }; \ \ ParamVar _min{Var((_T_)0)}; \ ParamVar _max{Var((_T_)100)}; \ _T_ _tmp; \ } IMGUISLIDER(Int, int64_t, ImGuiDataType_S64, int, "%lld"); IMGUISLIDER(Float, double, ImGuiDataType_Double, float, "%.3f"); #define IMGUISLIDER2(_CBT_, _CMP_, _T_, _IMT_, _VAL_, _FMT_) \ struct _CBT_##_CMP_##Slider : public Variable<CBType::_CBT_##_CMP_> { \ \ static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } \ static CBOptionalString inputHelp() { \ return CBCCSTR("The input value is ignored."); \ } \ \ static CBTypesInfo outputTypes() { return CoreInfo::_CBT_##_CMP_##Type; } \ static CBOptionalString outputHelp() { \ return CBCCSTR("The value produced by this block."); \ } \ \ static CBParametersInfo parameters() { return paramsInfo; } \ \ void cleanup() { \ _min.cleanup(); \ _max.cleanup(); \ Variable<CBType::_CBT_##_CMP_>::cleanup(); \ } \ \ void warmup(CBContext *context) { \ Variable<CBType::_CBT_##_CMP_>::warmup(context); \ _min.warmup(context); \ _max.warmup(context); \ } \ \ void setParam(int index, const CBVar &value) { \ switch (index) { \ case 0: \ case 1: \ Variable<CBType::_CBT_##_CMP_>::setParam(index, value); \ break; \ case 2: \ _min = value; \ break; \ case 3: \ _max = value; \ break; \ default: \ break; \ } \ } \ \ CBVar getParam(int index) { \ switch (index) { \ case 0: \ case 1: \ return Variable<CBType::_CBT_##_CMP_>::getParam(index); \ case 2: \ return _min; \ case 3: \ return _max; \ default: \ return Var::Empty; \ } \ } \ \ CBVar activate(CBContext *context, const CBVar &input) { \ IDContext idCtx(this); \ \ _T_ min = _min.get().payload._VAL_##Value; \ _T_ max = _max.get().payload._VAL_##Value; \ if (_variable.isVariable()) { \ auto &var = _variable.get(); \ ::ImGui::SliderScalarN(_label.c_str(), _IMT_, \ (void *)&var.payload._VAL_##_CMP_##Value, \ _CMP_, &min, &max, _FMT_, 0); \ \ var.valueType = CBType::_CBT_; \ return var; \ } else { \ ::ImGui::SliderScalarN(_label.c_str(), _IMT_, (void *)&_tmp, _CMP_, \ &min, &max, _FMT_, 0); \ return Var(_tmp); \ } \ } \ \ private: \ static inline Parameters paramsInfo{ \ VariableParamsInfo(), \ {{"Min", \ CBCCSTR("The minimum value."), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}, \ {"Max", \ CBCCSTR("The maximum value."), \ {CoreInfo::_CBT_##Type, CoreInfo::_CBT_##VarType}}}, \ }; \ \ ParamVar _min{Var((_T_)0)}; \ ParamVar _max{Var((_T_)100)}; \ _T_ _tmp; \ } IMGUISLIDER2(Int, 2, int64_t, ImGuiDataType_S64, int, "%lld"); IMGUISLIDER2(Int, 3, int32_t, ImGuiDataType_S32, int, "%lld"); IMGUISLIDER2(Int, 4, int32_t, ImGuiDataType_S32, int, "%lld"); IMGUISLIDER2(Float, 2, double, ImGuiDataType_Double, float, "%.3f"); IMGUISLIDER2(Float, 3, float, ImGuiDataType_Float, float, "%.3f"); IMGUISLIDER2(Float, 4, float, ImGuiDataType_Float, float, "%.3f"); struct TextInput : public Variable<CBType::String> { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::StringType; } static CBOptionalString outputHelp() { return CBCCSTR("The string that was input."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: case 1: Variable<CBType::String>::setParam(index, value); break; case 2: { if (value.valueType == None) { _hint.clear(); } else { _hint = value.payload.stringValue; } } break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: case 1: return Variable<CBType::String>::getParam(index); case 2: return Var(_hint); default: return Var::Empty; } } static int InputTextCallback(ImGuiInputTextCallbackData *data) { TextInput *it = (TextInput *)data->UserData; if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) { // Resize string callback if (it->_variable.isVariable()) { auto &var = it->_variable.get(); delete[] var.payload.stringValue; var.payload.stringCapacity = data->BufTextLen * 2; var.payload.stringValue = new char[var.payload.stringCapacity]; data->Buf = (char *)var.payload.stringValue; } else { it->_buffer.resize(data->BufTextLen * 2); data->Buf = (char *)it->_buffer.c_str(); } } return 0; } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); if (_exposing && _init) { _init = false; auto &var = _variable.get(); // we own the variable so let's run some init var.valueType = CBType::String; var.payload.stringValue = new char[32]; var.payload.stringCapacity = 32; memset((void *)var.payload.stringValue, 0x0, 32); } auto *hint = _hint.size() > 0 ? _hint.c_str() : nullptr; if (_variable.isVariable()) { auto &var = _variable.get(); ::ImGui::InputTextWithHint( _label.c_str(), hint, (char *)var.payload.stringValue, var.payload.stringCapacity, ImGuiInputTextFlags_CallbackResize, &InputTextCallback, this); return var; } else { ::ImGui::InputTextWithHint( _label.c_str(), hint, (char *)_buffer.c_str(), _buffer.capacity() + 1, ImGuiInputTextFlags_CallbackResize, &InputTextCallback, this); return Var(_buffer); } } private: static inline Parameters _params{ VariableParamsInfo(), {{"Hint", CBCCSTR("A hint text displayed when the control is empty."), {CoreInfo::StringType}}}, }; // fallback, used only when no variable name is set std::string _buffer; std::string _hint; bool _init{true}; }; struct ColorInput : public Variable<CBType::Color> { ImVec4 _lcolor{0.0, 0.0, 0.0, 1.0}; static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::ColorType; } static CBOptionalString outputHelp() { return CBCCSTR("The color that was input."); } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); if (_exposing && _init) { _init = false; auto &var = _variable.get(); // we own the variable so let's run some init var.valueType = CBType::Color; var.payload.colorValue.r = 0; var.payload.colorValue.g = 0; var.payload.colorValue.b = 0; var.payload.colorValue.a = 255; } if (_variable.isVariable()) { auto &var = _variable.get(); auto fc = Style::color2Vec4(var); ::ImGui::ColorEdit4(_label.c_str(), &fc.x); var.payload.colorValue = Style::vec42Color(fc); return var; } else { ::ImGui::ColorEdit4(_label.c_str(), &_lcolor.x); return Var(Style::vec42Color(_lcolor)); } } private: bool _init{true}; }; struct Image : public Base { ImVec2 _size{1.0, 1.0}; bool _trueSize = false; static CBTypesInfo inputTypes() { return BGFX::Texture::ObjType; } static CBOptionalString inputHelp() { return CBCCSTR("A texture object."); } static CBTypesInfo outputTypes() { return BGFX::Texture::ObjType; } static inline ParamsInfo paramsInfo = ParamsInfo( ParamsInfo::Param("Size", CBCCSTR("The drawing size of the image."), CoreInfo::Float2Type), ParamsInfo::Param("TrueSize", CBCCSTR("If the given size is in true image pixels."), CoreInfo::BoolType)); static CBParametersInfo parameters() { return CBParametersInfo(paramsInfo); } void setParam(int index, const CBVar &value) { switch (index) { case 0: _size.x = value.payload.float2Value[0]; _size.y = value.payload.float2Value[1]; break; case 1: _trueSize = value.payload.boolValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_size.x, _size.y); case 1: return Var(_trueSize); default: return Var::Empty; } } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); auto texture = reinterpret_cast<BGFX::Texture *>(input.payload.objectValue); if (!_trueSize) { ImVec2 size = _size; size.x *= texture->width; size.y *= texture->height; ::ImGui::Image(reinterpret_cast<ImTextureID>(texture->handle.idx), size); } else { ::ImGui::Image(reinterpret_cast<ImTextureID>(texture->handle.idx), _size); } return input; } }; struct PlotContext { PlotContext() { context = ImPlot::CreateContext(); ImPlot::SetCurrentContext(context); } ~PlotContext() { ImPlot::SetCurrentContext(nullptr); ImPlot::DestroyContext(context); } private: ImPlotContext *context{nullptr}; }; struct Plot : public Base { Shared<PlotContext> _context{}; static inline Types Plottable{ {CoreInfo::FloatSeqType, CoreInfo::Float2SeqType}}; BlocksVar _blocks; CBVar _width{}, _height{}; std::string _title; std::string _fullTitle{"##" + std::to_string(reinterpret_cast<uintptr_t>(this))}; std::string _xlabel; std::string _ylabel; ParamVar _xlimits{}, _ylimits{}; ParamVar _lockx{Var::False}, _locky{Var::False}; std::array<CBExposedTypeInfo, 5> _required; static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static inline Parameters params{ {"Title", CBCCSTR("The title of the plot to create."), {CoreInfo::StringType}}, {"Contents", CBCCSTR("The blocks describing this plot."), {CoreInfo::BlocksOrNone}}, {"Width", CBCCSTR("The width of the plot area to create."), {CoreInfo::IntOrNone}}, {"Height", CBCCSTR("The height of the plot area to create."), {CoreInfo::IntOrNone}}, {"X_Label", CBCCSTR("The X axis label."), {CoreInfo::StringType}}, {"Y_Label", CBCCSTR("The Y axis label."), {CoreInfo::StringType}}, {"X_Limits", CBCCSTR("The X axis limits."), {CoreInfo::NoneType, CoreInfo::Float2Type, CoreInfo::Float2VarType}}, {"Y_Limits", CBCCSTR("The Y axis limits."), {CoreInfo::NoneType, CoreInfo::Float2Type, CoreInfo::Float2VarType}}, {"Lock_X", CBCCSTR("If the X axis should be locked into its limits."), {CoreInfo::BoolType, CoreInfo::BoolVarType}}, {"Lock_Y", CBCCSTR("If the Y axis should be locked into its limits."), {CoreInfo::BoolType, CoreInfo::BoolVarType}}}; static CBParametersInfo parameters() { return params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _title = value.payload.stringValue; _fullTitle = _title + "##" + std::to_string(reinterpret_cast<uintptr_t>(this)); break; case 1: _blocks = value; break; case 2: _width = value; break; case 3: _height = value; break; case 4: _xlabel = value.payload.stringValue; break; case 5: _ylabel = value.payload.stringValue; break; case 6: _xlimits = value; break; case 7: _ylimits = value; break; case 8: _lockx = value; break; case 9: _locky = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_title); case 1: return _blocks; case 2: return _width; case 3: return _height; case 4: return Var(_xlabel); case 5: return Var(_ylabel); case 6: return _xlimits; case 7: return _ylimits; case 8: return _lockx; case 9: return _locky; default: return Var::Empty; } } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return data.inputType; } void cleanup() { _blocks.cleanup(); _xlimits.cleanup(); _ylimits.cleanup(); _lockx.cleanup(); _locky.cleanup(); } void warmup(CBContext *context) { _context(); _blocks.warmup(context); _xlimits.warmup(context); _ylimits.warmup(context); _lockx.warmup(context); _locky.warmup(context); } CBExposedTypesInfo requiredVariables() { int idx = 0; _required[idx] = Base::ContextInfo; idx++; if (_xlimits.isVariable()) { _required[idx].name = _xlimits.variableName(); _required[idx].help = CBCCSTR("The required X axis limits."); _required[idx].exposedType = CoreInfo::Float2Type; idx++; } if (_ylimits.isVariable()) { _required[idx].name = _ylimits.variableName(); _required[idx].help = CBCCSTR("The required Y axis limits."); _required[idx].exposedType = CoreInfo::Float2Type; idx++; } if (_lockx.isVariable()) { _required[idx].name = _lockx.variableName(); _required[idx].help = CBCCSTR("The required X axis locking."); _required[idx].exposedType = CoreInfo::BoolType; idx++; } if (_locky.isVariable()) { _required[idx].name = _locky.variableName(); _required[idx].help = CBCCSTR("The required Y axis locking."); _required[idx].exposedType = CoreInfo::BoolType; idx++; } return {_required.data(), uint32_t(idx), 0}; } CBVar activate(CBContext *context, const CBVar &input) { if (_xlimits.get().valueType == Float2) { auto limitx = _xlimits.get().payload.float2Value[0]; auto limity = _xlimits.get().payload.float2Value[1]; auto locked = _lockx.get().payload.boolValue; ImPlot::SetNextPlotLimitsX(limitx, limity, locked ? ImGuiCond_Always : ImGuiCond_Once); } if (_ylimits.get().valueType == Float2) { auto limitx = _ylimits.get().payload.float2Value[0]; auto limity = _ylimits.get().payload.float2Value[1]; auto locked = _locky.get().payload.boolValue; ImPlot::SetNextPlotLimitsY(limitx, limity, locked ? ImGuiCond_Always : ImGuiCond_Once); } ImVec2 size{0, 0}; if (_width.valueType == Int) { size.x = float(_width.payload.intValue); } if (_height.valueType == Int) { size.y = float(_height.payload.intValue); } if (ImPlot::BeginPlot( _fullTitle.c_str(), _xlabel.size() > 0 ? _xlabel.c_str() : nullptr, _ylabel.size() > 0 ? _ylabel.c_str() : nullptr, size)) { DEFER(ImPlot::EndPlot()); CBVar output{}; _blocks.activate(context, input, output); } return input; } }; struct PlottableBase : public Base { std::string _label; std::string _fullLabel{"##" + std::to_string(reinterpret_cast<uintptr_t>(this))}; enum class Kind { unknown, xAndIndex, xAndY }; Kind _kind{}; CBVar _color{}; static CBTypesInfo inputTypes() { return Plot::Plottable; } static CBOptionalString inputHelp() { return CBCCSTR("A sequence of values."); } static CBTypesInfo outputTypes() { return Plot::Plottable; } static constexpr int nparams = 2; static inline Parameters params{ {"Label", CBCCSTR("The plot's label."), {CoreInfo::StringType}}, {"Color", CBCCSTR("The plot's color."), {CoreInfo::NoneType, CoreInfo::ColorType}}}; static CBParametersInfo parameters() { return params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _label = value.payload.stringValue; _fullLabel = _label + "##" + std::to_string(reinterpret_cast<uintptr_t>(this)); break; case 1: _color = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_label); case 1: return _color; default: return Var::Empty; } } CBTypeInfo compose(const CBInstanceData &data) { assert(data.inputType.basicType == Seq); if (data.inputType.seqTypes.len != 1 || (data.inputType.seqTypes.elements[0].basicType != Float && data.inputType.seqTypes.elements[0].basicType != Float2)) { throw ComposeError("Expected either a Float or Float2 sequence."); } if (data.inputType.seqTypes.elements[0].basicType == Float) _kind = Kind::xAndIndex; else _kind = Kind::xAndY; return data.inputType; } void applyModifiers() { if (_color.valueType == CBType::Color) { ImPlot::PushStyleColor(ImPlotCol_Line, Style::color2Vec4(_color.payload.colorValue)); ImPlot::PushStyleColor(ImPlotCol_Fill, Style::color2Vec4(_color.payload.colorValue)); } } void popModifiers() { if (_color.valueType == CBType::Color) { ImPlot::PopStyleColor(2); } } static bool isInputValid(const CBVar &input) { // prevent division by zero return !(input.valueType == Seq && input.payload.seqValue.len == 0); } }; struct PlotLine : public PlottableBase { CBVar activate(CBContext *context, const CBVar &input) { if (!isInputValid(input)) return input; PlottableBase::applyModifiers(); DEFER(PlottableBase::popModifiers()); if (_kind == Kind::xAndY) { ImPlot::PlotLineG( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(seq.elements[idx].payload.float2Value[0], seq.elements[idx].payload.float2Value[1]); }, (void *)&input, int(input.payload.seqValue.len), 0); } else if (_kind == Kind::xAndIndex) { ImPlot::PlotLineG( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(double(idx), seq.elements[idx].payload.floatValue); }, (void *)&input, int(input.payload.seqValue.len), 0); } return input; } }; struct PlotDigital : public PlottableBase { CBVar activate(CBContext *context, const CBVar &input) { if (!isInputValid(input)) return input; PlottableBase::applyModifiers(); DEFER(PlottableBase::popModifiers()); if (_kind == Kind::xAndY) { ImPlot::PlotDigitalG( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(seq.elements[idx].payload.float2Value[0], seq.elements[idx].payload.float2Value[1]); }, (void *)&input, int(input.payload.seqValue.len), 0); } else if (_kind == Kind::xAndIndex) { ImPlot::PlotDigitalG( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(double(idx), seq.elements[idx].payload.floatValue); }, (void *)&input, int(input.payload.seqValue.len), 0); } return input; } }; struct PlotScatter : public PlottableBase { CBVar activate(CBContext *context, const CBVar &input) { if (!isInputValid(input)) return input; PlottableBase::applyModifiers(); DEFER(PlottableBase::popModifiers()); if (_kind == Kind::xAndY) { ImPlot::PlotScatterG( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(seq.elements[idx].payload.float2Value[0], seq.elements[idx].payload.float2Value[1]); }, (void *)&input, int(input.payload.seqValue.len), 0); } else if (_kind == Kind::xAndIndex) { ImPlot::PlotScatterG( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(double(idx), seq.elements[idx].payload.floatValue); }, (void *)&input, int(input.payload.seqValue.len), 0); } return input; } }; struct PlotBars : public PlottableBase { typedef void (*PlotBarsProc)(const char *label_id, ImPlotPoint (*getter)(void *data, int idx), void *data, int count, double width, int offset); double _width = 0.67; bool _horizontal = false; PlotBarsProc _plot = &ImPlot::PlotBarsG; static inline Parameters params{ PlottableBase::params, {{"Width", CBCCSTR("The width of each bar"), {CoreInfo::FloatType}}, {"Horizontal", CBCCSTR("If the bar should be horiziontal rather than vertical"), {CoreInfo::BoolType}}}, }; static CBParametersInfo parameters() { return params; } void setParam(int index, const CBVar &value) { switch (index) { case PlottableBase::nparams + 1: _width = value.payload.floatValue; break; case PlottableBase::nparams + 2: _horizontal = value.payload.boolValue; if (_horizontal) { _plot = &ImPlot::PlotBarsHG; } else { _plot = &ImPlot::PlotBarsG; } break; default: PlottableBase::setParam(index, value); } } CBVar getParam(int index) { switch (index) { case PlottableBase::nparams + 1: return Var(_width); case PlottableBase::nparams + 2: return Var(_horizontal); break; default: return PlottableBase::getParam(index); } } CBVar activate(CBContext *context, const CBVar &input) { if (!isInputValid(input)) return input; PlottableBase::applyModifiers(); DEFER(PlottableBase::popModifiers()); if (_kind == Kind::xAndY) { _plot( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(seq.elements[idx].payload.float2Value[0], seq.elements[idx].payload.float2Value[1]); }, (void *)&input, int(input.payload.seqValue.len), _width, 0); } else if (_kind == Kind::xAndIndex) { _plot( _fullLabel.c_str(), [](void *data, int idx) { auto input = reinterpret_cast<CBVar *>(data); auto seq = input->payload.seqValue; return ImPlotPoint(double(idx), seq.elements[idx].payload.floatValue); }, (void *)&input, int(input.payload.seqValue.len), _width, 0); } return input; } }; struct HasPointer : public Base { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean."); } static CBVar activate(CBContext *context, const CBVar &input) { return Var(::ImGui::IsAnyItemHovered()); } }; struct FPS : public Base { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::FloatType; } static CBOptionalString outputHelp() { return CBCCSTR("The current framerate."); } CBVar activate(CBContext *context, const CBVar &input) { ImGuiIO &io = ::ImGui::GetIO(); return Var(io.Framerate); } }; struct Tooltip : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _blocks = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _blocks; default: break; } return Var::Empty; } void cleanup() { _blocks.cleanup(); } void warmup(CBContext *context) { _blocks.warmup(context); } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return data.inputType; } CBVar activate(CBContext *context, const CBVar &input) { if (::ImGui::IsItemHovered()) { ::ImGui::BeginTooltip(); DEFER(::ImGui::EndTooltip()); CBVar output{}; _blocks.activate(context, input, output); } return input; } private: static inline Parameters _params = { {"Contents", CBCCSTR("The inner contents blocks."), {CoreInfo::BlocksOrNone}}, }; BlocksVar _blocks{}; }; struct HelpMarker : public Base { static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _desc.clear(); } else { _desc = value.payload.stringValue; } } break; case 1: _isInline = value.payload.boolValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _desc.size() == 0 ? Var::Empty : Var(_desc); case 1: return Var(_isInline); default: return Var::Empty; } } CBVar activate(CBContext *context, const CBVar &input) { if (_isInline) ::ImGui::SameLine(); ::ImGui::TextDisabled("(?)"); if (::ImGui::IsItemHovered()) { ::ImGui::BeginTooltip(); ::ImGui::PushTextWrapPos(::ImGui::GetFontSize() * 35.0f); ::ImGui::TextUnformatted(_desc.c_str()); ::ImGui::PopTextWrapPos(); ::ImGui::EndTooltip(); } return input; } private: static inline Parameters _params = { {"Description", CBCCSTR("The text displayed in a popup."), {CoreInfo::StringType}}, {"Inline", CBCCSTR("Display on the same line."), {CoreInfo::BoolType}}, }; std::string _desc; bool _isInline{true}; }; struct ProgressBar : public Base { static CBTypesInfo inputTypes() { return CoreInfo::FloatType; } static CBOptionalString inputHelp() { return CBCCSTR("The value to display."); } static CBTypesInfo outputTypes() { return CoreInfo::FloatType; } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _overlay.clear(); } else { _overlay = value.payload.stringValue; } } break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _overlay.size() == 0 ? Var::Empty : Var(_overlay); default: return Var::Empty; } } CBVar activate(CBContext *context, const CBVar &input) { auto buf = _overlay.size() > 0 ? _overlay.c_str() : nullptr; ::ImGui::ProgressBar(input.payload.floatValue, ImVec2(0.f, 0.f), buf); return input; } private: static inline Parameters _params = { {"Overlay", CBCCSTR("The text displayed inside the progress bar."), {CoreInfo::StringType}}, }; std::string _overlay; }; struct MenuBase : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the menu is visible."); } static CBParametersInfo parameters() { return params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: blocks = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return blocks; default: break; } return Var::Empty; } void cleanup() { blocks.cleanup(); } void warmup(CBContext *context) { blocks.warmup(context); } CBTypeInfo compose(const CBInstanceData &data) { blocks.compose(data); return CoreInfo::BoolType; } protected: static inline Parameters params = { {"Contents", CBCCSTR("The inner contents blocks."), CoreInfo::BlocksOrNone}, }; BlocksVar blocks{}; }; struct MainMenuBar : public MenuBase { CBVar activate(CBContext *context, const CBVar &input) { auto active = ::ImGui::BeginMainMenuBar(); if (active) { DEFER(::ImGui::EndMainMenuBar()); CBVar output{}; blocks.activate(context, input, output); } return Var(active); } }; struct MenuBar : public MenuBase { CBVar activate(CBContext *context, const CBVar &input) { auto active = ::ImGui::BeginMenuBar(); if (active) { DEFER(::ImGui::EndMenuBar()); CBVar output{}; blocks.activate(context, input, output); } return Var(active); } }; struct Menu : public MenuBase { static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _label.clear(); } else { _label = value.payload.stringValue; } } break; case 1: _isEnabled = value; break; default: MenuBase::setParam(index - 2, value); break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_label); case 1: return _isEnabled; default: return MenuBase::getParam(index - 2); } } void cleanup() { _isEnabled.cleanup(); MenuBase::cleanup(); } void warmup(CBContext *context) { MenuBase::warmup(context); _isEnabled.warmup(context); } CBExposedTypesInfo requiredVariables() { int idx = 0; _required[idx] = Base::ContextInfo; idx++; if (_isEnabled.isVariable()) { _required[idx].name = _isEnabled.variableName(); _required[idx].help = CBCCSTR("The required IsEnabled."); _required[idx].exposedType = CoreInfo::BoolType; idx++; } return {_required.data(), uint32_t(idx), 0}; } CBVar activate(CBContext *context, const CBVar &input) { auto active = ::ImGui::BeginMenu(_label.c_str(), _isEnabled.get().payload.boolValue); if (active) { DEFER(::ImGui::EndMenu()); CBVar output{}; blocks.activate(context, input, output); } return Var(active); } private: static inline Parameters _params{ {{"Label", CBCCSTR("The label of the menu"), {CoreInfo::StringType}}, {"IsEnabled", CBCCSTR("Sets whether this menu is enabled. A disabled item cannot be " "selected or clicked."), {CoreInfo::BoolType, CoreInfo::BoolVarType}}}, MenuBase::params}; std::string _label; ParamVar _isEnabled{Var::True}; std::array<CBExposedTypeInfo, 2> _required; }; struct MenuItem : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Action blocks."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _label.clear(); } else { _label = value.payload.stringValue; } } break; case 1: _isChecked = value; break; case 2: _action = value; break; case 3: { if (value.valueType == None) { _shortcut.clear(); } else { _shortcut = value.payload.stringValue; } } break; case 4: _isEnabled = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _label.size() == 0 ? Var::Empty : Var(_label); case 1: return _isChecked; case 2: return _action; case 3: return _shortcut.size() == 0 ? Var::Empty : Var(_shortcut); case 4: return _isEnabled; default: return Var::Empty; } } void cleanup() { _action.cleanup(); _isEnabled.cleanup(); _isChecked.cleanup(); } void warmup(CBContext *context) { _action.warmup(context); _isEnabled.warmup(context); _isChecked.warmup(context); } CBExposedTypesInfo requiredVariables() { int idx = 0; _required[idx] = Base::ContextInfo; idx++; if (_isChecked.isVariable()) { _required[idx].name = _isChecked.variableName(); _required[idx].help = CBCCSTR("The required IsChecked."); _required[idx].exposedType = CoreInfo::BoolType; idx++; } if (_isEnabled.isVariable()) { _required[idx].name = _isEnabled.variableName(); _required[idx].help = CBCCSTR("The required IsEnabled."); _required[idx].exposedType = CoreInfo::BoolType; idx++; } return {_required.data(), uint32_t(idx), 0}; } CBTypeInfo compose(const CBInstanceData &data) { _action.compose(data); if (_isChecked.isVariable()) { // search for an existing variable and ensure it's the right type auto found = false; for (auto &var : data.shared) { if (strcmp(var.name, _isChecked.variableName()) == 0) { // we found a variable, make sure it's the right type and mark if (var.exposedType.basicType != CBType::Bool) { throw CBException("GUI - MenuItem: Existing variable type not " "matching the input."); } // also make sure it's mutable! if (!var.isMutable) { throw CBException( "GUI - MenuItem: Existing variable is not mutable."); } found = true; break; } } if (!found) // we didn't find a variable throw CBException("GUI - MenuItem: Missing mutable variable."); } return CoreInfo::BoolType; } CBVar activate(CBContext *context, const CBVar &input) { bool active; if (_isChecked.isVariable()) { active = ::ImGui::MenuItem(_label.c_str(), _shortcut.c_str(), &_isChecked.get().payload.boolValue, _isEnabled.get().payload.boolValue); } else { active = ::ImGui::MenuItem(_label.c_str(), _shortcut.c_str(), _isChecked.get().payload.boolValue, _isEnabled.get().payload.boolValue); } if (active) { CBVar output{}; _action.activate(context, input, output); } return Var(active); } private: static inline Parameters _params{ {"Label", CBCCSTR("The label of the menu item"), {CoreInfo::StringType}}, {"IsChecked", CBCCSTR("Sets whether this menu item is checked. A checked item " "displays a check mark on the side."), {CoreInfo::BoolType, CoreInfo::BoolVarType}}, {"Action", CBCCSTR(""), {CoreInfo::BlocksOrNone}}, {"Shortcut", CBCCSTR("A keyboard shortcut to activate that item"), {CoreInfo::StringType}}, {"IsEnabled", CBCCSTR("Sets whether this menu item is enabled. A disabled item cannot " "be selected or clicked."), {CoreInfo::BoolType, CoreInfo::BoolVarType}}, }; std::string _label; ParamVar _isChecked{Var::False}; BlocksVar _action{}; std::string _shortcut; ParamVar _isEnabled{Var::True}; std::array<CBExposedTypeInfo, 3> _required; }; struct Combo : public Variable<CBType::Int> { static CBTypesInfo inputTypes() { return CoreInfo::AnySeqType; } static CBOptionalString inputHelp() { return CBCCSTR("A sequence of values."); } static CBTypesInfo outputTypes() { return CoreInfo::AnyType; } static CBOptionalString outputHelp() { return CBCCSTR("The selected value."); } CBVar activate(CBContext *context, const CBVar &input) { auto count = input.payload.seqValue.len; if (count == 0) { if (_variable.isVariable()) _variable.get().payload.intValue = -1; return Var::Empty; } std::vector<std::string> vec; for (uint32_t i = 0; i < count; i++) { std::ostringstream stream; stream << input.payload.seqValue.elements[i]; vec.push_back(stream.str()); } const char *items[count]; for (size_t i = 0; i < vec.size(); i++) { items[i] = vec[i].c_str(); } if (_variable.isVariable()) { _n = _variable.get().payload.intValue; ::ImGui::Combo(_label.c_str(), &_n, items, count); _variable.get().payload.intValue = _n; } else { ::ImGui::Combo(_label.c_str(), &_n, items, count); } CBVar output{}; ::chainblocks::cloneVar(output, input.payload.seqValue.elements[_n]); return output; } private: int _n{0}; }; struct ListBox : public Variable<CBType::Int> { static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: case 1: Variable<CBType::Int>::setParam(index, value); break; case 2: _height = value.payload.intValue; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: case 1: return Variable<CBType::Int>::getParam(index); case 2: return Var(_height); default: break; } return Var::Empty; } static CBTypesInfo inputTypes() { return CoreInfo::AnySeqType; } static CBOptionalString inputHelp() { return CBCCSTR("A sequence of values."); } static CBTypesInfo outputTypes() { return CoreInfo::AnyType; } static CBOptionalString outputHelp() { return CBCCSTR("The currently selected value."); } CBVar activate(CBContext *context, const CBVar &input) { auto count = input.payload.seqValue.len; if (count == 0) { if (_variable.isVariable()) _variable.get().payload.intValue = -1; return Var::Empty; } std::vector<std::string> vec; for (uint32_t i = 0; i < count; i++) { std::ostringstream stream; stream << input.payload.seqValue.elements[i]; vec.push_back(stream.str()); } const char *items[count]; for (size_t i = 0; i < vec.size(); i++) { items[i] = vec[i].c_str(); } if (_variable.isVariable()) { _n = _variable.get().payload.intValue; ::ImGui::ListBox(_label.c_str(), &_n, items, count, _height); _variable.get().payload.intValue = _n; } else { ::ImGui::ListBox(_label.c_str(), &_n, items, count, _height); } CBVar output{}; ::chainblocks::cloneVar(output, input.payload.seqValue.elements[_n]); return output; } private: static inline Parameters _params = { VariableParamsInfo(), {{"ItemsHeight", CBCCSTR("Height of the list in number of items"), {CoreInfo::IntType}}}, }; int _n{0}; int _height{-1}; }; struct Selectable : public Variable<CBType::Bool> { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR( "A boolean indicating whether this item is currently selected."); } CBVar activate(CBContext *context, const CBVar &input) { IDContext idCtx(this); auto result = Var::False; if (_variable.isVariable()) { if (::ImGui::Selectable(_label.c_str(), &_variable.get().payload.boolValue)) { _variable.get().valueType = CBType::Bool; result = Var::True; } } else { // HACK kinda... we recycle _exposing since we are not using it in this // branch if (::ImGui::Selectable(_label.c_str(), &_exposing)) { result = Var::True; } } return result; } }; struct TabBase : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the tab is visible."); } static CBParametersInfo parameters() { return params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: blocks = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return blocks; default: break; } return Var::Empty; } void cleanup() { blocks.cleanup(); } void warmup(CBContext *context) { blocks.warmup(context); } CBTypeInfo compose(const CBInstanceData &data) { blocks.compose(data); return CoreInfo::BoolType; } protected: static inline Parameters params = { {"Contents", CBCCSTR("The inner contents blocks."), CoreInfo::BlocksOrNone}, }; BlocksVar blocks{}; }; struct TabBar : public TabBase { static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _name.clear(); } else { _name = value.payload.stringValue; } } break; case 1: TabBase::setParam(index - 1, value); break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_name); case 1: return TabBase::getParam(index - 1); default: break; } return Var::Empty; } CBVar activate(CBContext *context, const CBVar &input) { auto str_id = _name.size() > 0 ? _name.c_str() : "DefaultTabBar"; auto active = ::ImGui::BeginTabBar(str_id); if (active) { DEFER(::ImGui::EndTabBar()); CBVar output{}; blocks.activate(context, input, output); } return Var(active); } private: static inline Parameters _params = { {{"Name", CBCCSTR("A unique name for this tab bar."), {CoreInfo::StringType}}}, TabBase::params, }; std::string _name; }; struct TabItem : public TabBase { static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _label.clear(); } else { _label = value.payload.stringValue; } } break; case 1: TabBase::setParam(index - 1, value); break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_label); case 1: return TabBase::getParam(index - 1); default: break; } return Var::Empty; } CBVar activate(CBContext *context, const CBVar &input) { auto active = ::ImGui::BeginTabItem(_label.c_str()); if (active) { DEFER(::ImGui::EndTabItem()); CBVar output{}; blocks.activate(context, input, output); } return Var(active); } private: static inline Parameters _params = { {{"Label", CBCCSTR("The label of the tab"), {CoreInfo::StringType}}}, TabBase::params, }; std::string _label; }; struct Group : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _blocks = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _blocks; default: break; } return Var::Empty; } void cleanup() { _blocks.cleanup(); } void warmup(CBContext *context) { _blocks.warmup(context); } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return CoreInfo::BoolType; } CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::BeginGroup(); DEFER(::ImGui::EndGroup()); CBVar output{}; _blocks.activate(context, input, output); return input; } private: static inline Parameters _params = { {"Contents", CBCCSTR("The inner contents blocks."), CoreInfo::BlocksOrNone}, }; BlocksVar _blocks{}; }; struct Disable : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: _blocks = value; break; case 1: _disable = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return _blocks; case 1: return _disable; default: break; } return Var::Empty; } void cleanup() { _disable.cleanup(); _blocks.cleanup(); } void warmup(CBContext *context) { _disable.warmup(context); _blocks.warmup(context); } CBExposedTypesInfo requiredVariables() { int idx = 0; _required[idx] = Base::ContextInfo; idx++; if (_disable.isVariable()) { _required[idx].name = _disable.variableName(); _required[idx].help = CBCCSTR("The required Disable."); _required[idx].exposedType = CoreInfo::BoolType; idx++; } return {_required.data(), uint32_t(idx), 0}; } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return data.inputType; } CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::BeginDisabled(_disable.get().payload.boolValue); DEFER(::ImGui::EndDisabled()); CBVar output{}; _blocks.activate(context, input, output); return input; } private: static inline Parameters _params = { {"Contents", CBCCSTR("The inner contents blocks."), {CoreInfo::BlocksOrNone}}, {"Disable", CBCCSTR("Sets whether the contents should be disabled."), {CoreInfo::BoolType, CoreInfo::BoolVarType}}, }; ParamVar _disable{Var::True}; BlocksVar _blocks{}; std::array<CBExposedTypeInfo, 2> _required; }; struct Table : public Base { static CBOptionalString inputHelp() { return CBCCSTR("The value will be passed to the Contents blocks."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the table is visible."); } static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _name.clear(); } else { _name = value.payload.stringValue; } } break; case 1: _columns = value.payload.intValue; break; case 2: _blocks = value; break; case 3: _flags = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_name); case 1: return Var(_columns); case 2: return _blocks; case 3: return _flags; default: break; } return Var::Empty; } void cleanup() { _blocks.cleanup(); _flags.cleanup(); } void warmup(CBContext *context) { _blocks.warmup(context); _flags.warmup(context); } CBTypeInfo compose(const CBInstanceData &data) { _blocks.compose(data); return CoreInfo::BoolType; } CBVar activate(CBContext *context, const CBVar &input) { auto flags = ::ImGuiTableFlags( chainblocks::getFlags<Enums::GuiTableFlags>(_flags.get())); auto str_id = _name.size() > 0 ? _name.c_str() : "DefaultTable"; auto active = ::ImGui::BeginTable(str_id, _columns, flags); if (active) { DEFER(::ImGui::EndTable()); CBVar output{}; _blocks.activate(context, input, output); } return Var(active); } private: static inline Parameters _params = { {"Name", CBCCSTR("A unique name for this table."), {CoreInfo::StringType}}, {"Columns", CBCCSTR("The number of columns."), {CoreInfo::IntType}}, {"Contents", CBCCSTR("The inner contents blocks."), CoreInfo::BlocksOrNone}, {"Flags", CBCCSTR("Flags to enable table options."), {Enums::GuiTableFlagsType, Enums::GuiTableFlagsVarType, Enums::GuiTableFlagsSeqType, Enums::GuiTableFlagsVarSeqType, CoreInfo::NoneType}}, }; std::string _name; int _columns; BlocksVar _blocks{}; ParamVar _flags{}; }; struct TableHeadersRow : public Base { CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::TableHeadersRow(); return input; } }; struct TableNextColumn : public Base { static CBTypesInfo inputTypes() { return CoreInfo::NoneType; } static CBOptionalString inputHelp() { return CBCCSTR("The input value is ignored."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the table column is visible."); } CBVar activate(CBContext *context, const CBVar &input) { auto active = ::ImGui::TableNextColumn(); return Var(active); } }; struct TableNextRow : public Base { CBVar activate(CBContext *context, const CBVar &input) { ::ImGui::TableNextRow(); return input; } }; struct TableSetColumnIndex : public Base { static CBTypesInfo inputTypes() { return CoreInfo::IntType; } static CBOptionalString inputHelp() { return CBCCSTR("The table index."); } static CBTypesInfo outputTypes() { return CoreInfo::BoolType; } static CBOptionalString outputHelp() { return CBCCSTR("A boolean indicating whether the table column is visible."); } CBVar activate(CBContext *context, const CBVar &input) { auto &index = input.payload.intValue; auto active = ::ImGui::TableSetColumnIndex(index); return Var(active); } }; struct TableSetupColumn : public Base { static CBParametersInfo parameters() { return _params; } void setParam(int index, const CBVar &value) { switch (index) { case 0: { if (value.valueType == None) { _label.clear(); } else { _label = value.payload.stringValue; } } break; case 1: _flags = value; break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_label); case 1: return _flags; default: break; } return Var::Empty; } void cleanup() { _flags.cleanup(); } void warmup(CBContext *context) { _flags.warmup(context); } CBVar activate(CBContext *context, const CBVar &input) { auto flags = ::ImGuiTableColumnFlags( chainblocks::getFlags<Enums::GuiTableColumnFlags>(_flags.get())); ::ImGui::TableSetupColumn(_label.c_str(), flags); return input; } private: static inline Parameters _params = { {"Label", CBCCSTR("Column header"), {CoreInfo::StringType}}, {"Flags", CBCCSTR("Flags to enable column options."), {Enums::GuiTableColumnFlagsType, Enums::GuiTableColumnFlagsVarType, Enums::GuiTableColumnFlagsSeqType, Enums::GuiTableColumnFlagsVarSeqType, CoreInfo::NoneType}}, }; std::string _label; ParamVar _flags{}; }; void registerImGuiBlocks() { REGISTER_CBLOCK("GUI.Style", Style); REGISTER_CBLOCK("GUI.Window", Window); REGISTER_CBLOCK("GUI.ChildWindow", ChildWindow); REGISTER_CBLOCK("GUI.Checkbox", Checkbox); REGISTER_CBLOCK("GUI.CheckboxFlags", CheckboxFlags); REGISTER_CBLOCK("GUI.RadioButton", RadioButton); REGISTER_CBLOCK("GUI.Text", Text); REGISTER_CBLOCK("GUI.Bullet", Bullet); REGISTER_CBLOCK("GUI.Button", Button); REGISTER_CBLOCK("GUI.HexViewer", HexViewer); REGISTER_CBLOCK("GUI.Dummy", Dummy); REGISTER_CBLOCK("GUI.NewLine", NewLine); REGISTER_CBLOCK("GUI.SameLine", SameLine); REGISTER_CBLOCK("GUI.Separator", Separator); REGISTER_CBLOCK("GUI.Spacing", Spacing); REGISTER_CBLOCK("GUI.Indent", Indent); REGISTER_CBLOCK("GUI.Unindent", Unindent); REGISTER_CBLOCK("GUI.TreeNode", TreeNode); REGISTER_CBLOCK("GUI.CollapsingHeader", CollapsingHeader); REGISTER_CBLOCK("GUI.IntInput", IntInput); REGISTER_CBLOCK("GUI.FloatInput", FloatInput); REGISTER_CBLOCK("GUI.Int2Input", Int2Input); REGISTER_CBLOCK("GUI.Int3Input", Int3Input); REGISTER_CBLOCK("GUI.Int4Input", Int4Input); REGISTER_CBLOCK("GUI.Float2Input", Float2Input); REGISTER_CBLOCK("GUI.Float3Input", Float3Input); REGISTER_CBLOCK("GUI.Float4Input", Float4Input); REGISTER_CBLOCK("GUI.IntDrag", IntDrag); REGISTER_CBLOCK("GUI.FloatDrag", FloatDrag); REGISTER_CBLOCK("GUI.Int2Drag", Int2Drag); REGISTER_CBLOCK("GUI.Int3Drag", Int3Drag); REGISTER_CBLOCK("GUI.Int4Drag", Int4Drag); REGISTER_CBLOCK("GUI.Float2Drag", Float2Drag); REGISTER_CBLOCK("GUI.Float3Drag", Float3Drag); REGISTER_CBLOCK("GUI.Float4Drag", Float4Drag); REGISTER_CBLOCK("GUI.IntSlider", IntSlider); REGISTER_CBLOCK("GUI.FloatSlider", FloatSlider); REGISTER_CBLOCK("GUI.Int2Slider", Int2Slider); REGISTER_CBLOCK("GUI.Int3Slider", Int3Slider); REGISTER_CBLOCK("GUI.Int4Slider", Int4Slider); REGISTER_CBLOCK("GUI.Float2Slider", Float2Slider); REGISTER_CBLOCK("GUI.Float3Slider", Float3Slider); REGISTER_CBLOCK("GUI.Float4Slider", Float4Slider); REGISTER_CBLOCK("GUI.TextInput", TextInput); REGISTER_CBLOCK("GUI.Image", Image); REGISTER_CBLOCK("GUI.Plot", Plot); REGISTER_CBLOCK("GUI.PlotLine", PlotLine); REGISTER_CBLOCK("GUI.PlotDigital", PlotDigital); REGISTER_CBLOCK("GUI.PlotScatter", PlotScatter); REGISTER_CBLOCK("GUI.PlotBars", PlotBars); REGISTER_CBLOCK("GUI.GetClipboard", GetClipboard); REGISTER_CBLOCK("GUI.SetClipboard", SetClipboard); REGISTER_CBLOCK("GUI.ColorInput", ColorInput); REGISTER_CBLOCK("GUI.HasPointer", HasPointer); REGISTER_CBLOCK("GUI.FPS", FPS); REGISTER_CBLOCK("GUI.Tooltip", Tooltip); REGISTER_CBLOCK("GUI.HelpMarker", HelpMarker); REGISTER_CBLOCK("GUI.ProgressBar", ProgressBar); REGISTER_CBLOCK("GUI.MainMenuBar", MainMenuBar); REGISTER_CBLOCK("GUI.MenuBar", MenuBar); REGISTER_CBLOCK("GUI.Menu", Menu); REGISTER_CBLOCK("GUI.MenuItem", MenuItem); REGISTER_CBLOCK("GUI.Combo", Combo); REGISTER_CBLOCK("GUI.ListBox", ListBox); REGISTER_CBLOCK("GUI.Selectable", Selectable); REGISTER_CBLOCK("GUI.TabBar", TabBar); REGISTER_CBLOCK("GUI.TabItem", TabItem); REGISTER_CBLOCK("GUI.Group", Group); REGISTER_CBLOCK("GUI.Disable", Disable); REGISTER_CBLOCK("GUI.Table", Table); REGISTER_CBLOCK("GUI.HeadersRow", TableHeadersRow); REGISTER_CBLOCK("GUI.NextColumn", TableNextColumn); REGISTER_CBLOCK("GUI.NextRow", TableNextRow); REGISTER_CBLOCK("GUI.SetColumnIndex", TableSetColumnIndex); REGISTER_CBLOCK("GUI.SetupColumn", TableSetupColumn); } }; // namespace ImGui }; // namespace chainblocks
32.604921
80
0.520183
fragcolor-xyz
b5027f31b229ef8ee98224b05a12be7c25c66746
38,724
cpp
C++
main/irrigationController.cpp
mwick83/irrigation_ctrl
90f53f25f3a670193157e580acbd0c7b69b7f206
[ "BSD-3-Clause" ]
5
2018-02-26T21:33:41.000Z
2022-03-02T11:29:08.000Z
main/irrigationController.cpp
mwick83/irrigation_ctrl
90f53f25f3a670193157e580acbd0c7b69b7f206
[ "BSD-3-Clause" ]
null
null
null
main/irrigationController.cpp
mwick83/irrigation_ctrl
90f53f25f3a670193157e580acbd0c7b69b7f206
[ "BSD-3-Clause" ]
1
2019-12-31T03:47:58.000Z
2019-12-31T03:47:58.000Z
#include "irrigationController.h" extern "C" { void esp_restart_noos() __attribute__ ((noreturn)); } // TBD: encapsulate RTC_DATA_ATTR static IrrigationController::peristent_data_t irrigCtrlPersistentData = { .lastIrrigEvent = 0, .reservoirState = IrrigationController::RESERVOIR_OK }; /** * @brief Default constructor, which performs basic initialization, * but doesn't start processing. */ IrrigationController::IrrigationController(void) { size_t len = strlen(mqttTopicPre) + strlen(mqttStateTopicPost) + 12 + 1; mqttStateTopic = (char*) calloc(len, sizeof(char)); // Format string length + 5 digits voltage in mV + 1 digit batt state + 8 digits for battery state string + // 4 digits (fillLevel * 10) + 1 digit for reservoir state, // 8 digits for reservoir state string, // 2 digits per active output + ', ' as seperator // 6 digits per active output string + ', ' as seperator // 19 digits for the next event datetime // 19 digits for the last SNTP sync datetime // 19 digits for the next SNTP sync datetime. // Format string is a bit too long, but don't care too mich about those few bytes mqttStateDataMaxLen = strlen(mqttStateDataFmt) + 5 + 1 + 8 + 4 + 1 + 8 + (4+8)*(OutputController::intChannels+OutputController::extChannels) + 19 + 19 + 19 + 1; mqttStateData = (char*) calloc(mqttStateDataMaxLen, sizeof(char)); // Reserve space for active outputs state.activeOutputs.clear(); state.activeOutputs.reserve(OutputController::intChannels+OutputController::extChannels); // prepare empty last state memset(&lastState, 0, sizeof(state_t)); lastState.activeOutputs.clear(); lastState.activeOutputs.reserve(OutputController::intChannels+OutputController::extChannels); // Prepare time system event hook to react properly on time changes // Note: hook registration will be performed by the main thread, because the // IrrigationPlanner instance will be created before the TimeSystem is initialized. extEvents = xEventGroupCreate(); if (nullptr == extEvents) { ESP_LOGE(logTag, "extEvents event group couldn't be created."); } } /** * @brief Default destructor, which cleans up allocated data. */ IrrigationController::~IrrigationController(void) { // TBD: graceful shutdown of task if(mqttStateTopic) free(mqttStateTopic); if(mqttStateData) free(mqttStateData); } /** * @brief Start the IrrigationController processing task. */ void IrrigationController::start(void) { if (nullptr == extEvents) { ESP_LOGE(logTag, "Needed resources haven't been allocated. Not starting the task."); } else { // initially signalize a hardware config change, so it gets immediatly processed in the task function hardwareConfigUpdatedEventHandler(); taskHandle = xTaskCreateStatic(taskFuncDispatch, "irrig_ctrl_task", taskStackSize, (void*) this, taskPrio, taskStack, &taskBuf); if (nullptr != taskHandle) { ESP_LOGI(logTag, "IrrigationController task created. Starting."); } else { ESP_LOGE(logTag, "IrrigationController task creation failed!"); } } } /** * @brief This is the IrrigationController processing task dispatcher. * * @param params Task parameters. Used to pass in the actual IrrigationController * instance the task function is running for. */ void IrrigationController::taskFuncDispatch(void* params) { IrrigationController* caller = (IrrigationController*) params; caller->taskFunc(); } /** * @brief This is the IrrigationController processing task. * * It implements the control logic of the class. For details see the class description. */ void IrrigationController::taskFunc() { EventBits_t events; TickType_t wait, loopStartTicks, nowTicks; time_t now, nextIrrigEvent, sntpNextSync; IrrigationPlanner::err_t plannerErr; bool irrigOk; bool firstRun = true; emergencyTimerHandle = xTimerCreateStatic("Emergency reboot timer", emergencyTimerTicks, pdFALSE, (void*) 0, emergencyTimerCb, &emergencyTimerBuf); if((NULL == emergencyTimerHandle) || (pdPASS != xTimerStart(emergencyTimerHandle, 0))) { ESP_LOGE(logTag, "Emergency reboot timer couldn't be setup. Doing our best without it ..."); } // Wait for WiFi to come up. TBD: make configurable (globally), implement WiFiManager for that wait = portMAX_DELAY; if(wifiConnectedWaitMillis >= 0) { wait = pdMS_TO_TICKS(wifiConnectedWaitMillis); } events = xEventGroupWaitBits(wifiEvents, wifiEventConnected, pdFALSE, pdTRUE, wait); if(0 != (events & wifiEventConnected)) { ESP_LOGD(logTag, "WiFi connected."); } else { ESP_LOGE(logTag, "WiFi didn't come up within timeout!"); } // Check if we have a valid time if(!TimeSystem_TimeIsSet()) { // Time hasen't been, so assume something to get operating somehow. // After setting it here, it will be stored in the RTC, so next time we come up it // will not be set to the default again. TimeSystem_SetTime(01, 01, 2018, 06, 00, 00); ESP_LOGW(logTag, "Time hasn't been set yet. Setting default time: 2018-01-01, 06:00:00."); } else { ESP_LOGD(logTag, "Time is already set."); } // Properly initialize some time vars { now = time(nullptr); if(irrigCtrlPersistentData.lastIrrigEvent == 0) { struct tm nowTm; localtime_r(&now, &nowTm); nowTm.tm_sec--; irrigCtrlPersistentData.lastIrrigEvent = mktime(&nowTm); } } // Register event hooks TimeSystem_RegisterHook(timeSytemEventsHookDispatch, this); irrigPlanner.registerIrrigPlanUpdatedHook(irrigConfigUpdatedHookDispatch, this); settingsMgr.registerHardwareConfigUpdatedHook(hardwareConfigUpdatedHookDispatch, this); while(1) { loopStartTicks = xTaskGetTickCount(); // feed the emergency timer if(pdPASS != xTimerReset(emergencyTimerHandle, 10)) { ESP_LOGW(logTag, "Couldn't feed the emergency timer."); } // check for hardware config changes events = xEventGroupClearBits(extEvents, extEventHardwareConfigUpdated); if(0 != (events & extEventHardwareConfigUpdated)) { ESP_LOGI(logTag, "Hardware config update detected."); SettingsManager::battery_config_t batConf; SettingsManager::reservoir_config_t reservoirConf; settingsMgr.copyBatteryConfig(&batConf); settingsMgr.copyReservoirConfig(&reservoirConf); disableBatteryCheck = batConf.disableBatteryCheck; disableReservoirCheck = reservoirConf.disableReservoirCheck; fillLevelMaxVal = reservoirConf.fillLevelMaxVal; fillLevelMinVal = reservoirConf.fillLevelMinVal; fillLevelCriticalThresholdPercent10 = reservoirConf.fillLevelCriticalThresholdPercent10; fillLevelLowThresholdPercent10 = reservoirConf.fillLevelLowThresholdPercent10; fillLevelHysteresisPercent10 = reservoirConf.fillLevelHysteresisPercent10; } // ********************* // Power up needed peripherals, DCDC, ... // ********************* // Peripheral enable will power up the DCDC as well as the RS232 driver if(!pwrMgr.getPeripheralEnable()) { ESP_LOGD(logTag, "Bringing up DCDC + RS232 driver."); pwrMgr.setPeripheralEnable(true); // Wait for stable onboard peripherals vTaskDelay(pdMS_TO_TICKS(peripheralEnStartupMillis)); } // Enable external sensor power if((!disableReservoirCheck) && (!pwrMgr.getPeripheralExtSupply())) { ESP_LOGD(logTag, "Powering external sensors."); pwrMgr.setPeripheralExtSupply(true); // Wait for external sensors to power up properly vTaskDelay(pdMS_TO_TICKS(peripheralExtSupplyMillis)); } // ********************* // Fetch sensor data // ********************* // Battery voltage state.battVoltage = pwrMgr.getSupplyVoltageMilli(); if(disableBatteryCheck) { state.battState = PowerManager::BATT_DISABLED; } else { state.battState = pwrMgr.getBatteryState(state.battVoltage); } ESP_LOGD(logTag, "Battery voltage: %02.2f V (%s)", roundf(state.battVoltage * 0.1f) * 0.01f, BATT_STATE_TO_STR(state.battState)); // Get fill level of the reservoir, if not disabled. if(!disableReservoirCheck) { int fillLevelMm = fillSensor.getFillLevel(); int fillLevel = 0; if(fillLevel < fillLevelMinVal) fillLevel = fillLevelMinVal; if(fillLevel > fillLevelMaxVal) fillLevel = fillLevelMaxVal; fillLevel = (fillLevelMm - fillLevelMinVal); fillLevel = fillLevel * 1000 / fillLevelMaxVal; if(fillLevel > 1000) fillLevel = 1000; if(fillLevel < 0) fillLevel = 0; state.fillLevel = fillLevel; state.reservoirState = irrigCtrlPersistentData.reservoirState; // keep previous state by default if ((irrigCtrlPersistentData.reservoirState == RESERVOIR_OK) || (irrigCtrlPersistentData.reservoirState == RESERVOIR_DISABLED)) { // state was okay or disabled before -> update it with the absolute values if(state.fillLevel >= fillLevelLowThresholdPercent10) { state.reservoirState = RESERVOIR_OK; } else if (state.fillLevel >= fillLevelCriticalThresholdPercent10) { state.reservoirState = RESERVOIR_LOW; } else { state.reservoirState = RESERVOIR_CRITICAL; } } else { // apply appropriate hysteresis if we were critical or low before if (irrigCtrlPersistentData.reservoirState == RESERVOIR_CRITICAL) { if(state.fillLevel >= (fillLevelLowThresholdPercent10 + fillLevelHysteresisPercent10)) { state.reservoirState = RESERVOIR_OK; } else if (state.fillLevel >= (fillLevelCriticalThresholdPercent10 + fillLevelHysteresisPercent10)) { state.reservoirState = RESERVOIR_LOW; } } else { if(state.fillLevel >= (fillLevelLowThresholdPercent10 + fillLevelHysteresisPercent10)) { state.reservoirState = RESERVOIR_OK; } else if (state.fillLevel < fillLevelCriticalThresholdPercent10) { state.reservoirState = RESERVOIR_CRITICAL; } } } } else { state.fillLevel = -2; state.reservoirState = RESERVOIR_DISABLED; } ESP_LOGD(logTag, "Reservoir fill level: %d (%s)", state.fillLevel, RESERVOIR_STATE_TO_STR(state.reservoirState)); // Store updated fill values in persitent data storage irrigCtrlPersistentData.reservoirState = state.reservoirState; // Power down external supply already. Not needed anymore. if(pwrMgr.getPeripheralExtSupply()) { pwrMgr.setPeripheralExtSupply(false); ESP_LOGD(logTag, "Sensors powered down."); } // TBD: Get weather forecast // TBD: Get local weather data // Check system preconditions for the irrigation, i.e. battery state and reservoir fill level irrigOk = true; if(state.battState == PowerManager::BATT_CRITICAL) { irrigOk = false; } if(state.reservoirState == RESERVOIR_CRITICAL) { irrigOk = false; } // Check if system conditions got critical and outputs are active if(outputCtrl.anyOutputsActive() && !irrigOk) { ESP_LOGW(logTag, "Active outputs detected, but system conditions critical! Disabling them for safety."); outputCtrl.disableAllOutputs(); } // ********************* // Irrigation // ********************* int millisTillNextEvent; bool eventsToProcess = true; while(eventsToProcess) { now = time(nullptr); // Check if the system time has been (re)set events = xEventGroupClearBits(extEvents, extEventTimeSet | extEventTimeSetSntp | extEventIrrigConfigUpdated); if(0 != (events & extEventTimeSet)) { ESP_LOGI(logTag, "Time set detected. Resetting event processing."); // Recalculate lastIrrigEvent to not process events that haven't really // happend in-between last time and now. struct tm nowTm; localtime_r(&now, &nowTm); nowTm.tm_sec--; irrigCtrlPersistentData.lastIrrigEvent = mktime(&nowTm); // Calculate the next SNTP sync only if this was a manual time set event, otherwise // the next sync time has already been set above if(0 == (events & extEventTimeSetSntp)) { struct tm sntpNextSyncTm; localtime_r(&now, &sntpNextSyncTm); sntpNextSyncTm.tm_hour += sntpResyncIntervalHours; sntpNextSync = mktime(&sntpNextSyncTm); TimeSystem_SetNextSntpSync(sntpNextSync); } // Disable all outputs to abort any irrigations that may have been started. outputCtrl.disableAllOutputs(); } if (0 != (events & extEventIrrigConfigUpdated)) { ESP_LOGI(logTag, "Irrigation config update detected."); // Note: Special handling of extEventIrrigConfigUpdated not needed, because getNextEventTime is done unconditionally } nextIrrigEvent = irrigPlanner.getNextEventTime(irrigCtrlPersistentData.lastIrrigEvent, true); state.nextIrrigEvent = nextIrrigEvent; millisTillNextEvent = (int) round(difftime(nextIrrigEvent, now) * 1000.0); // lock the configuration before an event starts (incl. some guard time) if ((nextIrrigEvent != 0) && (millisTillNextEvent <= preEventMillis)) { ESP_LOGD(logTag, "Event is approaching. Locking config."); irrigPlanner.setConfigLock(true); } else if (!outputCtrl.anyOutputsActive() && irrigPlanner.getConfigLock()) { ESP_LOGD(logTag, "Releasing config lock, because no events are near."); irrigPlanner.setConfigLock(false); } // // Publish state with the updated next event time // publishStateUpdate(); // Perform event actions if it is time now now = time(nullptr); double diffTime = difftime(nextIrrigEvent, now); // Event within delta or have we even overshot the target? if((nextIrrigEvent != 0) && ((fabs(diffTime) < 1.0) || (diffTime <= -1.0))) { TimeSystem_LogTime(); if(!irrigOk) { ESP_LOGE(logTag, "Critical system conditions detected! Dropping irrigation."); } struct tm eventTm; localtime_r(&nextIrrigEvent, &eventTm); ESP_LOGI(logTag, "Actions to perform for events at %02d.%02d.%04d %02d:%02d:%02d", eventTm.tm_mday, eventTm.tm_mon+1, 1900+eventTm.tm_year, eventTm.tm_hour, eventTm.tm_min, eventTm.tm_sec); constexpr int maxEventHandles = 8; // TBD: config parameter IrrigationPlanner::event_handle_t eventHandles[maxEventHandles]; plannerErr = irrigPlanner.getEventHandles(nextIrrigEvent, eventHandles, maxEventHandles); if(IrrigationPlanner::ERR_OK != plannerErr) { ESP_LOGW(logTag, "Error getting event handles: %d. Trying our best anyway...", plannerErr); } for(int cnt=0; cnt < maxEventHandles; cnt++) { IrrigationEvent::irrigation_event_data_t eventData; if(eventHandles[cnt].idx >= 0) { plannerErr = irrigPlanner.getEventData(eventHandles[cnt], &eventData); if(IrrigationPlanner::ERR_OK != plannerErr) { ESP_LOGE(logTag, "Error getting event data: %d. No actions available!", plannerErr); } else { static irrigation_zone_cfg_t zoneCfg; plannerErr = irrigPlanner.getZoneConfig(eventData.zoneIdx, &zoneCfg); bool zoneCfgIsValid = true; if(IrrigationPlanner::ERR_OK != plannerErr) { ESP_LOGE(logTag, "Error getting zone config: %d. No actions available!", plannerErr); zoneCfgIsValid = false; } bool isStartEvent = eventData.isStart; unsigned int durationSecs = isStartEvent ? eventData.durationSecs : 0; if(zoneCfgIsValid) { for(int i=0; i < irrigationZoneCfgElements; i++) { if(zoneCfg.chEnabled[i]) { ESP_LOGI(logTag, "* Channel: %s, state: %s, duration: %d s, start: %d", CH_MAP_TO_STR(zoneCfg.chNum[i]), isStartEvent ? (zoneCfg.chStateStart[i] ? "ON" : "OFF") : (zoneCfg.chStateStop[i] ? "ON" : "OFF"), durationSecs, isStartEvent); } } } plannerErr = irrigPlanner.confirmEvent(eventHandles[cnt]); if(IrrigationPlanner::ERR_OK != plannerErr) { ESP_LOGE(logTag, "Error confirming event: %d. Not performing its actions!", plannerErr); } if((zoneCfgIsValid) && (IrrigationPlanner::ERR_OK == plannerErr)) { setZoneOutputs(irrigOk, &zoneCfg, isStartEvent); } } } else { break; } } irrigCtrlPersistentData.lastIrrigEvent = nextIrrigEvent; } else { eventsToProcess = false; } // Publish state with the updated next event time + active outputs state.sntpLastSync = TimeSystem_GetLastSntpSync(); state.sntpNextSync = TimeSystem_GetNextSntpSync(); publishStateUpdate(); } // ********************* // SNTP resync // ********************* // Request an SNTP resync if it hasn't happend at all or the next scheduled sync is due sntpNextSync = TimeSystem_GetNextSntpSync(); if((sntpNextSync == 0) || (difftime(sntpNextSync, time(nullptr)) <= 0.0f)) { bool skipSntpResync = false; // Skip resync in case an upcoming event is close millisTillNextEvent = (int) round(difftime(nextIrrigEvent, time(nullptr)) * 1000.0); if((nextIrrigEvent != 0) && (millisTillNextEvent <= noSntpResyncRangeMillis)) { skipSntpResync = true; ESP_LOGD(logTag, "Skipping SNTP (re)sync, because next upcoming event is too close."); } // Skip rsync if we are offline events = xEventGroupWaitBits(wifiEvents, wifiEventConnected, pdFALSE, pdTRUE, 0); if (0 == (events & wifiEventConnected)) { skipSntpResync = true; ESP_LOGD(logTag, "Skipping SNTP (re)sync, because we are offline."); } // Skip resync if outputs are active, because the new time being set would disable // all outputs and they would be turned back on again if(outputCtrl.anyOutputsActive()) { skipSntpResync = true; ESP_LOGD(logTag, "Skipping SNTP (re)sync, because outputs are active."); } if(!skipSntpResync) { ESP_LOGI(logTag, "Requesting an SNTP time (re)sync."); TimeSystem_SntpRequest(); // Wait for the sync events = xEventGroupWaitBits(extEvents, extEventTimeSetSntp, pdTRUE, pdTRUE, pdMS_TO_TICKS(timeResyncWaitMillis)); // Stop the SNTP background process, so it won't intefere with running irrigations TimeSystem_SntpStop(); // Calculate the next SNTP sync struct tm sntpNextSyncTm; sntpNextSync = time(nullptr); localtime_r(&sntpNextSync, &sntpNextSyncTm); // Check status of sync to determine the next sync time if(0 != (events & extEventTimeSetSntp)) { ESP_LOGI(logTag, "SNTP time (re)sync was successful."); sntpNextSyncTm.tm_hour += sntpResyncIntervalHours; } else { ESP_LOGW(logTag, "SNTP time (re)sync wasn't successful within timeout."); sntpNextSyncTm.tm_min += sntpResyncIntervalFailMinutes; } sntpNextSync = mktime(&sntpNextSyncTm); TimeSystem_SetNextSntpSync(sntpNextSync); // Update SNTP info state.sntpLastSync = TimeSystem_GetLastSntpSync(); state.sntpNextSync = TimeSystem_GetNextSntpSync(); } } // ********************* // Sleep preparation // ********************* // Get current time again for sleep calculation now = time(nullptr); // Check if the system time has been (re)set events = xEventGroupClearBits(extEvents, extEventTimeSet | extEventTimeSetSntp | extEventIrrigConfigUpdated); if (0 != (events & extEventTimeSet)) { // Recalculate lastIrrigEvent and nextIrrig to not process events that haven't really // happend in-between last time and now. ESP_LOGI(logTag, "Time set detected. Resetting event processing."); struct tm nowTm; localtime_r(&now, &nowTm); nowTm.tm_sec--; irrigCtrlPersistentData.lastIrrigEvent = mktime(&nowTm); nextIrrigEvent = irrigPlanner.getNextEventTime(irrigCtrlPersistentData.lastIrrigEvent, true); // Calculate the next SNTP sync only if this was a manual time set event, otherwise // the next sync time has already been set above if(0 == (events & extEventTimeSetSntp)) { struct tm sntpNextSyncTm; localtime_r(&now, &sntpNextSyncTm); sntpNextSyncTm.tm_hour += sntpResyncIntervalHours; sntpNextSync = mktime(&sntpNextSyncTm); TimeSystem_SetNextSntpSync(sntpNextSync); } // Disable all outputs to abort any irrigations that may have been started. outputCtrl.disableAllOutputs(); // Update next irrigation event and publish (also the new SNTP info set above) state.nextIrrigEvent = nextIrrigEvent; publishStateUpdate(); } // update the next event time if the schedule has been updated if (0 != (events & extEventIrrigConfigUpdated)) { ESP_LOGI(logTag, "Irrigation configuration update detected. Recalculating next event time."); nextIrrigEvent = irrigPlanner.getNextEventTime(irrigCtrlPersistentData.lastIrrigEvent, true); } millisTillNextEvent = (int) round(difftime(nextIrrigEvent, now) * 1000.0); // Power down the DCDC if no outputs are active. if(!outputCtrl.anyOutputsActive()) { pwrMgr.setPeripheralEnable(false); ESP_LOGD(logTag, "DCDC + RS232 driver powered down."); } if(pwrMgr.getKeepAwake()) { // Calculate loop runtime and compensate the sleep time with it nowTicks = xTaskGetTickCount(); int loopRunTimeMillis = portTICK_RATE_MS * ((nowTicks > loopStartTicks) ? (nowTicks - loopStartTicks) : (portMAX_DELAY - loopStartTicks + nowTicks + 1)); ESP_LOGD(logTag, "Loop runtime %d ms.", loopRunTimeMillis); firstRun = false; int sleepMillis = wakeupIntervalKeepAwakeMillis - loopRunTimeMillis; if ((nextIrrigEvent != 0) && (sleepMillis > millisTillNextEvent)) sleepMillis = millisTillNextEvent - preEventMillis; if (sleepMillis < 500) sleepMillis = 500; ESP_LOGD(logTag, "Task is going to sleep for %d ms.", sleepMillis); if(sleepMillis > taskMaxSleepTimeMillis) { sleepMillis = taskMaxSleepTimeMillis; ESP_LOGD(logTag, "Task sleep time longer than maximum allowed. " "Task is going to sleep for %d ms insted.", sleepMillis); } vTaskDelay(pdMS_TO_TICKS(sleepMillis)); } else { // Wait to get all updates through if(!mqttMgr.waitAllPublished(mqttAllPublishedWaitMillis)) { ESP_LOGW(logTag, "Waiting for MQTT to publish all messages didn't complete within timeout."); } // TBD: stop webserver, mqtt and other stuff // Calculate loop runtime and compensate the sleep time with it int loopRunTimeMillis; if(firstRun) { // This is the normal case for deep sleep: Compensate also for the // boot time. loopRunTimeMillis = portTICK_RATE_MS * xTaskGetTickCount(); firstRun = false; ESP_LOGD(logTag, "Loop runtime (incl. boot) %d ms.", loopRunTimeMillis); } else { // This is the case when the system was in keep awake, previously. So, // compensate for the loop time only. nowTicks = xTaskGetTickCount(); loopRunTimeMillis = portTICK_RATE_MS * ((nowTicks > loopStartTicks) ? (nowTicks - loopStartTicks) : (portMAX_DELAY - loopStartTicks + nowTicks + 1)); ESP_LOGD(logTag, "Loop runtime %d ms.", loopRunTimeMillis); } int millisTillNextEventCompensated = millisTillNextEvent - preEventMillisDeepSleep - mqttAllPublishedWaitMillis; int sleepMillis = wakeupIntervalMillis - loopRunTimeMillis; if((nextIrrigEvent != 0) && (sleepMillis > millisTillNextEventCompensated)) sleepMillis = millisTillNextEventCompensated; if(sleepMillis < 500) sleepMillis = 500; // Check if there is enough wakeup time if( (sleepMillis < noDeepSleepRangeMillis) && (millisTillNextEvent <= noDeepSleepRangeMillis) ) { ESP_LOGD(logTag, "Event coming up sooner than deep sleep wakeup time. " "Task is going to sleep for %d ms insted of deep sleep.", sleepMillis); if(sleepMillis > taskMaxSleepTimeMillis) { sleepMillis = taskMaxSleepTimeMillis; ESP_LOGD(logTag, "Task sleep time is bigger than maximum allowed. " "Task is going to sleep for %d ms insted.", sleepMillis); } vTaskDelay(pdMS_TO_TICKS(sleepMillis)); } // Check if any outputs are active, deep sleep would kill them! else if(outputCtrl.anyOutputsActive()) { ESP_LOGD(logTag, "Outputs active. Task is going to sleep for %d ms insted of deep sleep.", sleepMillis); if(sleepMillis > taskMaxSleepTimeMillis) { sleepMillis = taskMaxSleepTimeMillis; ESP_LOGD(logTag, "Task sleep time is bigger than maximum allowed. " "Task is going to sleep for %d ms insted.", sleepMillis); } vTaskDelay(pdMS_TO_TICKS(sleepMillis)); } else { TickType_t killStartTicks = xTaskGetTickCount(); ESP_LOGD(logTag, "About to deep sleep. Killing MQTT and WiFi."); mqttMgr.stop(); // don't stop WiFi explicitly, because this seemed to hang sometimes. nowTicks = xTaskGetTickCount(); loopRunTimeMillis = portTICK_RATE_MS * ((nowTicks > killStartTicks) ? (nowTicks - killStartTicks) : (portMAX_DELAY - killStartTicks + nowTicks + 1)); sleepMillis -= loopRunTimeMillis; ESP_LOGD(logTag, "Kill compensation time %d ms; new deep sleep time %d ms.", \ loopRunTimeMillis, sleepMillis); if(sleepMillis < noDeepSleepRangeMillis) { ESP_LOGW(logTag, "Compensating deep sleep time got too near to next event. Rebooting."); pwrMgr.reboot(); } else { ESP_LOGD(logTag, "Preparing deep sleep for %d ms.", sleepMillis); pwrMgr.gotoSleep(sleepMillis); } } } } vTaskDelete(NULL); ESP_LOGE(logTag, "Task unexpectetly exited! Performing reboot."); //pwrMgr->reboot(); } void IrrigationController::setZoneOutputs(bool irrigOk, irrigation_zone_cfg_t* zoneCfg, bool start) { for(int i=0; i < irrigationZoneCfgElements; i++) { if(zoneCfg->chEnabled[i]) { bool switchOn = start ? zoneCfg->chStateStart[i] : zoneCfg->chStateStop[i]; OutputController::ch_map_t chNum = zoneCfg->chNum[i]; // Only enable outputs when preconditions are met; disabling is always okay. if(irrigOk || !switchOn) { outputCtrl.setOutput(chNum, switchOn); updateStateActiveOutputs(chNum, switchOn); } } } } /** * @brief Update active outputs list in internal state structure. * * @param chNum Output channel to update * @param active Wether or not the channel is now active. */ void IrrigationController::updateStateActiveOutputs(uint32_t chNum, bool active) { bool inserted = false; for(std::vector<uint32_t>::iterator it = state.activeOutputs.begin(); it != state.activeOutputs.end(); it++) { if(!active) { if(*it == chNum) { state.activeOutputs.erase(it); break; } } else { if(*it > chNum) { it = state.activeOutputs.insert(it, chNum); inserted = true; break; } else if(*it == chNum) { inserted = true; break; } } } if(active && !inserted) { state.activeOutputs.push_back(chNum); } } /** * @brief Publish currently stored state via MQTT. */ void IrrigationController::publishStateUpdate() { static uint8_t mac_addr[6]; static char timeStr[20]; static char sntpLastSyncTimeStr[20]; static char sntpNextSyncTimeStr[20]; static char activeOutputs[4*(OutputController::intChannels+OutputController::extChannels)+1]; static char activeOutputsStr[8*(OutputController::intChannels+OutputController::extChannels)+1]; size_t preLen; size_t postLen; // TBD: Compare more lax, i.e. allow little differences in batt voltage, etc. int stateCmp = memcmp(&state, &lastState, sizeof(state_t)); if(0 != stateCmp) { if(false == mqttMgr.waitConnected(mqttConnectedWaitMillis)) { ESP_LOGW(logTag, "MQTT manager has no connection after timeout."); } else { if(!mqttPrepared) { if(ESP_OK == esp_wifi_get_mac(ESP_IF_WIFI_STA, mac_addr)) { preLen = strlen(mqttTopicPre); postLen = strlen(mqttStateTopicPost); memcpy(mqttStateTopic, mqttTopicPre, preLen); for(int i=0; i<6; i++) { sprintf(&mqttStateTopic[preLen+i*2], "%02x", mac_addr[i]); } memcpy(&mqttStateTopic[preLen+12], mqttStateTopicPost, postLen); mqttStateTopic[preLen+12+postLen] = 0; mqttPrepared = true; } else { ESP_LOGE(logTag, "Getting MAC address failed!"); } } if(mqttPrepared) { // Prepare next irrigation string struct tm nextIrrigEventTm; localtime_r(&state.nextIrrigEvent, &nextIrrigEventTm); strftime(timeStr, 20, "%Y-%m-%d %H:%M:%S", &nextIrrigEventTm); // Prepare next+last SNTP sync strings struct tm sntpLastSyncTm; localtime_r(&state.sntpLastSync, &sntpLastSyncTm); strftime(sntpLastSyncTimeStr, 20, "%Y-%m-%d %H:%M:%S", &sntpLastSyncTm); struct tm sntpNextSyncTm; localtime_r(&state.sntpNextSync, &sntpNextSyncTm); strftime(sntpNextSyncTimeStr, 20, "%Y-%m-%d %H:%M:%S", &sntpNextSyncTm); // Prepare active outputs strings activeOutputs[0] = '\0'; activeOutputsStr[0] = '\0'; for(std::vector<uint32_t>::iterator it = state.activeOutputs.begin(); it != state.activeOutputs.end(); it++) { snprintf(activeOutputs, sizeof(activeOutputs) / sizeof(activeOutputs[0]), "%s%s%d", activeOutputs, (it==state.activeOutputs.begin()) ? "" : ", ", *it); snprintf(activeOutputsStr, sizeof(activeOutputsStr) / sizeof(activeOutputsStr[0]), "%s%s\"%s\"", activeOutputsStr, (it==state.activeOutputs.begin()) ? "" : ", ", CH_MAP_TO_STR(*it)); } // Build the string to be send size_t actualLen = snprintf(mqttStateData, mqttStateDataMaxLen, mqttStateDataFmt, state.battVoltage, state.battState, BATT_STATE_TO_STR(state.battState), state.fillLevel, state.reservoirState, RESERVOIR_STATE_TO_STR(state.reservoirState), activeOutputs, activeOutputsStr, timeStr, sntpLastSyncTimeStr, sntpNextSyncTimeStr); mqttMgr.publish(mqttStateTopic, mqttStateData, actualLen, MqttManager::QOS_EXACTLY_ONCE, true); // Copy the sent state over to lastState, but only if we actually sent it and not in the other cases memcpy(&lastState, &state, sizeof(state_t)); } } } } /** * @brief This function handles events when a new time has been set. * * This is important for the main processing thread to properly react to discontinuous * time changes. * */ void IrrigationController::timeSytemEventHandler(time_system_event_t events) { // set an event group bit for the processing task if(0 != (events & TimeSystem_timeEventTimeSet)) { xEventGroupSetBits(extEvents, extEventTimeSet); } if(0 != (events & TimeSystem_timeEventTimeSetSntp)) { xEventGroupSetBits(extEvents, extEventTimeSetSntp); } } /** * @brief Static hook dispatcher, which delegates time events to the correct IrrigationController * instance. * * Currently, only 'time set' events are handled and relevant. * * @param param Pointer to the actual IrrigationController instance * @param event Concrete event from the TimeSystem. */ void IrrigationController::timeSytemEventsHookDispatch(void* param, time_system_event_t events) { IrrigationController* controller = (IrrigationController*) param; if(nullptr == controller) { ESP_LOGE("unkown", "No valid IrrigationController available to dispatch time system events to!"); } else { if(0 != events) { controller->timeSytemEventHandler(events); } } } /** * @brief Static hook dispatcher, which delegates irrigation config update events to the correct IrrigationController * instance. * * @param param Pointer to the actual IrrigationController instance */ void IrrigationController::irrigConfigUpdatedHookDispatch(void* param) { IrrigationController* controller = (IrrigationController*) param; if(nullptr == controller) { ESP_LOGE("unkown", "No valid IrrigationController available to dispatch irrigation config events to!"); } else { controller->irrigConfigUpdatedEventHandler(); } } /** * @brief This function handles events when a irrigation config update has been received. * * This is important for the main processing thread to properly react to schedule * updates. * */ void IrrigationController::irrigConfigUpdatedEventHandler() { // set an event group bit for the processing task xEventGroupSetBits(extEvents, extEventIrrigConfigUpdated); } /** * @brief Static hook dispatcher, which delegates hardware config update events to the correct IrrigationController * instance. * * @param param Pointer to the actual IrrigationController instance */ void IrrigationController::hardwareConfigUpdatedHookDispatch(void* param) { IrrigationController* controller = (IrrigationController*) param; if(nullptr == controller) { ESP_LOGE("unkown", "No valid IrrigationController available to dispatch hardware config events to!"); } else { controller->hardwareConfigUpdatedEventHandler(); } } /** * @brief This function handles events when a hardware config update has been received. */ void IrrigationController::hardwareConfigUpdatedEventHandler() { // set an event group bit for the processing task xEventGroupSetBits(extEvents, extEventHardwareConfigUpdated); } /** * @brief Emergency reboot timer callback, which will simply reset the device * to get back up in operational state. * * @param timerHandle Timer handle for identification, unused */ void IrrigationController::emergencyTimerCb(TimerHandle_t timerHandle) { // hardcore reboot, without accessing the power manager in case something // really bad happend. esp_restart_noos(); }
44.459242
136
0.605826
mwick83
b5066f39fa613e422c5e9d3b3fd97f8ae3cea362
1,391
hpp
C++
include/build_info/private/compilers/mingw.hpp
Kartonagnick/build_info
581d7f8114e91142a46639412e3e716c33868c14
[ "MIT" ]
null
null
null
include/build_info/private/compilers/mingw.hpp
Kartonagnick/build_info
581d7f8114e91142a46639412e3e716c33868c14
[ "MIT" ]
19
2021-06-08T19:59:49.000Z
2021-07-04T19:32:47.000Z
include/tools/build_info/private/compilers/mingw.hpp
Kartonagnick/tools-features
a3662f165f796751cabe1f0703f0f0316cace647
[ "MIT" ]
null
null
null
// [2021y-06m-18d][22:50:00] Idrisov Denis R. 001 // [2021y-06m-15d][00:05:00] Idrisov Denis R. 001 PRE #pragma once #ifndef dTOOLS_BI_MINGW_USED_ #define dTOOLS_BI_MINGW_USED_ 001 //============================================================================== //============================================================================== #if !defined(dX64) && !defined(dX32) #error unknown address-model #endif #if !defined(dCRT_VAL) #error unknown runtime-c++ #endif #ifndef __GNUC__ #error not specified: __GNUC__ #endif // __GNUC__ - MAJOR // __GNUC_MINOR__ - MINOR // __GNUC_PATCHLEVEL__ - PATCH #define dCOMPILER_INT (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #define dCOMPILER_VER __GNUC__.__GNUC_MINOR__.__GNUC_PATCHLEVEL__ #define dCOMPILER_TAG mingw // example: #if dCOMPILER_INT > 30200 // 3.2.X #endif //============================================================================== //=== SHOW CONFIG-DATA ========================================================= #ifndef dHIDE_MINGW_MESSAGE #include "../../dmessage.hpp" #pragma message("mingw: " dSSTRINGIZE(dCOMPILER_VER)) #endif // !dHIDE_MINGW_MESSAGE //============================================================================== //============================================================================== #endif // !dTOOLS_BI_MINGW_USE
29.595745
87
0.478073
Kartonagnick
b509922a4da416dd999fcc26cf9b622b1b49d710
6,569
cpp
C++
Visual C++/CD Label/TextObject.cpp
manimanis/Intranet
9cd4da01641212f18c710ae721bc48c8eadc4a28
[ "MIT" ]
null
null
null
Visual C++/CD Label/TextObject.cpp
manimanis/Intranet
9cd4da01641212f18c710ae721bc48c8eadc4a28
[ "MIT" ]
null
null
null
Visual C++/CD Label/TextObject.cpp
manimanis/Intranet
9cd4da01641212f18c710ae721bc48c8eadc4a28
[ "MIT" ]
null
null
null
// TextObject.cpp: implementation of the CTextObject class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CD Label.h" #include "TextObject.h" #include <math.h> #include "ProprieteTexte.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define PI 3.141596 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CTextObject::CTextObject() { CClientDC dc(AfxGetMainWnd()); dc.SetMapMode(MM_HIMETRIC); m_szStr = "Modifier ce texte"; memset(&m_lfFont, 0, sizeof(m_lfFont)); m_nHeight = 12; m_devCaps = dc.GetDeviceCaps(LOGPIXELSY); m_lfFont.lfHeight = -MulDiv(m_nHeight, m_devCaps, 2540); m_lfFont.lfWeight = 12; strcpy(m_lfFont.lfFaceName, "Times New Roman"); m_ftFont.CreateFontIndirect(&m_lfFont); CFont *pFont; pFont = (CFont *)dc.SelectObject(&m_ftFont); CSize size = dc.GetTextExtent(m_szStr); //dc.LPtoDP(&size); m_rcPos.right = size.cx + m_rcPos.left; m_rcPos.bottom = -size.cy + m_rcPos.top; dc.SelectObject(pFont); m_textColor = 0; m_typeObject = OBJECT_TYPE_TEXT; m_align = 0; m_rotation = 0; RecalcRect(); } CTextObject::~CTextObject() { m_ftFont.DeleteObject(); } void CTextObject::DrawObject(CDC *pDC) { CRect tempRc = m_rcPos; CFont *pFont; int align; pDC->SetTextColor(m_textColor); pFont = (CFont *)pDC->SelectObject(&m_ftFont); switch(m_align) { case 0 : align = TA_LEFT; break; case 1 : align = TA_CENTER;break; case 2 : align = TA_RIGHT; break; } pDC->SetBkMode(TRANSPARENT); pDC->SetTextAlign(align); CalculateBorderingRect(pDC, m_szStr); if (!pDC->IsPrinting() && m_nState == OBJECT_STATE_SELECTED) { CBrush *pOldBrush; m_blackBrush.CreateSolidBrush(RGB(0, 0, 0)); pOldBrush = (CBrush *)pDC->SelectObject(&m_blackBrush); pDC->Rectangle(m_rcPos.left, m_rcPos.top, m_rcPos.left + 200, m_rcPos.top - 200); pDC->Rectangle(m_rcPos.CenterPoint().x - 100, m_rcPos.top, m_rcPos.CenterPoint().x + 100, m_rcPos.top - 200); pDC->Rectangle(m_rcPos.right, m_rcPos.top, m_rcPos.right - 200, m_rcPos.top - 200); pDC->Rectangle(m_rcPos.right, m_rcPos.CenterPoint().y + 100, m_rcPos.right - 200, m_rcPos.CenterPoint().y - 100); pDC->Rectangle(m_rcPos.right, m_rcPos.bottom, m_rcPos.right - 200, m_rcPos.bottom + 200); pDC->Rectangle(m_rcPos.CenterPoint().x - 100, m_rcPos.bottom, m_rcPos.CenterPoint().x + 100, m_rcPos.bottom + 200); pDC->Rectangle(m_rcPos.left, m_rcPos.bottom, m_rcPos.left + 200, m_rcPos.bottom + 200); pDC->Rectangle(m_rcPos.left, m_rcPos.CenterPoint().y + 100, m_rcPos.left + 200, m_rcPos.CenterPoint().y - 100); pDC->SelectObject(pOldBrush); m_blackBrush.DeleteObject(); } pDC->SelectObject(pFont); } void CTextObject::Properties() { CProprieteTexte pDlg; pDlg.m_szText = m_szStr; m_lfFont.lfHeight = m_nHeight; memcpy(&pDlg.m_logFont, &m_lfFont, sizeof(LOGFONT)); pDlg.m_textColor = m_textColor; pDlg.m_align = m_align; pDlg.m_rotationVal = pDlg.m_rotation = m_rotation; if (pDlg.DoModal() == IDCANCEL) return; m_textColor = pDlg.m_textColor; m_szStr = pDlg.m_szText; m_align = pDlg.m_align; m_rotation = pDlg.m_rotation; if (pDlg.m_bFontChanged) { m_nHeight = pDlg.m_logFont.lfHeight; pDlg.m_logFont.lfHeight = -MulDiv(m_nHeight, m_devCaps * 1000, 2540); memcpy(&m_lfFont, &pDlg.m_logFont, sizeof(LOGFONT)); m_lfFont.lfEscapement = m_rotation * 10; m_ftFont.Detach(); m_ftFont.CreateFontIndirect(&m_lfFont); } } void CTextObject::CalculateBorderingRect(CDC *pDC, CString str) { int from = 0, pos; CSize sz, sz1= CSize(0, 0); int lineCount = 0, i; CString s; double cos_a, sin_a, cos_b, sin_b; double d; double cos_apb, sin_apb, cos_amb, sin_amb; CPoint pt[4]; CRect oldPos; do { pos = str.Find("\015\012", from); if (pos >= 0) sz = pDC->GetOutputTextExtent(m_szStr.Mid(from, pos - from)); else sz = pDC->GetOutputTextExtent(m_szStr.Mid(from)); if (sz.cx > sz1.cx) sz1.cx = sz.cx; sz1.cy += sz.cy; from = pos + 1; lineCount++; } while (pos >= 0); sz1.cx = abs(sz1.cx); sz1.cy = abs(sz1.cy); d = sqrt(sz1.cx * sz1.cx + sz1.cy * sz1.cy); cos_a = (double)sz1.cx / d; sin_a = (double)sz1.cy / d; cos_b = cos((double)m_rotation * PI / 180.0); sin_b = -sin((double)m_rotation * PI / 180.0); cos_apb = cos_a * cos_b - sin_a * sin_b; sin_apb = sin_a * cos_b + cos_a * sin_b; cos_amb = cos_a * cos_b + sin_a * sin_b; sin_amb = sin_a * cos_b - cos_a * sin_b; RecalcRect(); CPoint midPoint = m_rcPos.CenterPoint(); pt[0].x = (int)(-d * cos_amb / 2.0) + midPoint.x; pt[0].y = (int)(d * sin_amb / 2.0) + midPoint.y; pt[1].x = (int)(d * cos_apb / 2.0) + midPoint.x; pt[1].y = (int)(d * sin_apb / 2.0) + midPoint.y; pt[2].x = (int)(d * cos_amb / 2.0) + midPoint.x; pt[2].y = (int)(-d * sin_amb / 2.0) + midPoint.y; pt[3].x = (int)(-d * cos_apb / 2.0) + midPoint.x; pt[3].y = (int)(-d * sin_apb / 2.0) + midPoint.y; m_rcPos.left = pt[0].x; m_rcPos.right = pt[0].x; m_rcPos.top = pt[0].y; m_rcPos.bottom = pt[0].y; for (i = 0 ; i < 4 ; i++) { if (m_rcPos.left > pt[i].x) m_rcPos.left = pt[i].x; if (m_rcPos.right < pt[i].x) m_rcPos.right = pt[i].x; if (m_rcPos.top > pt[i].y) m_rcPos.top = pt[i].y; if (m_rcPos.bottom < pt[i].y) m_rcPos.bottom = pt[i].y; } int ofx = 0, ofy = 0; for (from = 0, i = 0 ; i < lineCount ; i++) { pos = str.Find("\015\012", from); if (pos >= 0) s = m_szStr.Mid(from, pos - from); else s = m_szStr.Mid(from); if (m_align == 0) ofx = pt[0].x, ofy = pt[0].y; else if (m_align == 1) ofx = (pt[1].x - pt[0].x) / 2 + pt[0].x, ofy = (pt[1].y - pt[0].y) / 2 + pt[0].y; else if (m_align == 2) ofx = pt[1].x, ofy = pt[1].y; pDC->TextOut(i * (pt[3].x - pt[0].x) / lineCount + ofx, i * (pt[3].y - pt[0].y) / lineCount + ofy, s); from = pos + 2; } } void CTextObject::Copie(CObjetsVisuels *pCopie) { m_align = ((CTextObject *)pCopie)->m_align; m_nHeight = ((CTextObject *)pCopie)->m_nHeight; m_rotation = ((CTextObject *)pCopie)->m_rotation; m_szStr = ((CTextObject *)pCopie)->m_szStr; m_textColor = ((CTextObject *)pCopie)->m_textColor; memcpy(&m_lfFont, &(((CTextObject *)pCopie)->m_lfFont), sizeof(LOGFONT)); m_lfFont.lfHeight = -MulDiv(m_nHeight, m_devCaps * 1000, 2540); m_ftFont.Detach(); m_ftFont.CreateFontIndirect(&m_lfFont); memcpy(&m_lfFont, &(((CTextObject *)pCopie)->m_lfFont), sizeof(LOGFONT)); CObjetsVisuels::Copie(pCopie); }
25.46124
117
0.638453
manimanis
b50f9a9db531c495bc3330e09cd6ba9ccd182ab5
1,585
hpp
C++
src/thread/adapter_disk.hpp
huangqundl/af_stream
178d98feaf403b6947fb0fae3c2bbaedd91f9ab8
[ "Apache-2.0" ]
15
2017-03-28T13:15:53.000Z
2022-03-01T08:16:48.000Z
src/thread/adapter_disk.hpp
huangqundl/af_stream
178d98feaf403b6947fb0fae3c2bbaedd91f9ab8
[ "Apache-2.0" ]
null
null
null
src/thread/adapter_disk.hpp
huangqundl/af_stream
178d98feaf403b6947fb0fae3c2bbaedd91f9ab8
[ "Apache-2.0" ]
6
2017-10-17T14:10:23.000Z
2022-03-01T08:16:29.000Z
#ifndef __AFS_ADAPTER_DISK_HPP_INCLUDED__ #define __AFS_ADAPTER_DISK_HPP_INCLUDED__ #include "adapter_base.hpp" #include <stdio.h> #include <string> #include "../config.hpp" #include "../util.hpp" namespace afs { class AdapterDisk : public AdapterBase { public: // derived from AdapterBase void Init(); void Clean(); void AddSource(const char* source); AdapterDisk(); private: FILE* file_; char buf[MAX_RECORD_LENGTH]; unsigned long long int max; unsigned long long int cnt; // derived from AdapterBase void ReadRecord(void** data, uint32_t *data_len); }; AdapterDisk::AdapterDisk() : file_(NULL) { } void AdapterDisk::Init() { Config* config = Config::getInstance(); max = config->get_ull("adapter.max_data", 0); char* filename = config->getstring("trace_file", NULL); afs_assert(filename, "[trace_file] must be specified in the config file\n"); file_ = fopen(filename, "r"); afs_assert(file_, "Input file %s not found, exit\n", filename); } void AdapterDisk::Clean() { fclose(file_); } /* void AdapterDisk::AddSource(const char* source) { LOG_ERR("We only consider single file for adapter_disk\n"); } */ // assume each record is a one-line, readable string void AdapterDisk::ReadRecord(void** data, uint32_t *data_len) { if (fgets(buf, MAX_RECORD_LENGTH, file_) == NULL) { *data = NULL; //*len = 0; } if (max && cnt==max) { *data = NULL; } else { *data = buf; cnt++; //*len = strlen(buf); } } } #endif
19.096386
80
0.636593
huangqundl
b51b887759c33d89f47e961414789c525e29b1c9
1,296
cpp
C++
Algorithms/Easy/404.sum-of-left-leaves.cpp
jtcheng/leetcode
db58973894757789d060301b589735b5985fe102
[ "MIT" ]
null
null
null
Algorithms/Easy/404.sum-of-left-leaves.cpp
jtcheng/leetcode
db58973894757789d060301b589735b5985fe102
[ "MIT" ]
null
null
null
Algorithms/Easy/404.sum-of-left-leaves.cpp
jtcheng/leetcode
db58973894757789d060301b589735b5985fe102
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=404 lang=cpp * * [404] Sum of Left Leaves * * https://leetcode.com/problems/sum-of-left-leaves/description/ * * algorithms * Easy (48.71%) * Total Accepted: 117.6K * Total Submissions: 241.3K * Testcase Example: '[3,9,20,null,null,15,7]' * * Find the sum of all left leaves in a given binary tree. * * Example: * * ⁠ 3 * ⁠ / \ * ⁠ 9 20 * ⁠ / \ * ⁠ 15 7 * * There are two left leaves in the binary tree, with values 9 and 15 * respectively. Return 24. * * */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sumOfLeftLeaves(TreeNode* root) { int sum = 0; if (root == NULL) { return sum; } vector<TreeNode*> nodes; nodes.push_back(root); int currLevel = 0; while (!nodes.empty()) { ++currLevel; vector<TreeNode*> tnodes; for (TreeNode* node : nodes) { if (node->left) { tnodes.push_back(node->left); if (!node->left->left && !node->left->right) { sum += node->left->val; } } if (node->right) { tnodes.push_back(node->right); } } nodes = move(tnodes); } return sum; } };
19.058824
69
0.568673
jtcheng
b5222a01505dfa13ac24d8522ad728cdefd25bdf
756
cpp
C++
A. Watermelon.cpp
Samim-Arefin/Codeforce-Problem-Solution
7219ee6173faaa9e06231d4cd3e9ba292ae27ce3
[ "MIT" ]
null
null
null
A. Watermelon.cpp
Samim-Arefin/Codeforce-Problem-Solution
7219ee6173faaa9e06231d4cd3e9ba292ae27ce3
[ "MIT" ]
null
null
null
A. Watermelon.cpp
Samim-Arefin/Codeforce-Problem-Solution
7219ee6173faaa9e06231d4cd3e9ba292ae27ce3
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int num; while(cin>>num) { int flag=0; if(num%2==0 && num!=2) { int diff=2; while(num>0) { num-=diff; if(num%2==0 && diff%2==0) { flag=1; break; } else { flag=0; } diff+=diff; } if(flag==0) { cout<<"NO"<<endl; } else { cout<<"YES"<<endl; } } else { cout<<"NO"<<endl; } } }
18
41
0.246032
Samim-Arefin
dddff1b1d319fa7e071049dd9fb36a59d99dadce
1,767
cpp
C++
my_vulkan/debug_callback.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
my_vulkan/debug_callback.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
3
2019-02-25T10:13:57.000Z
2020-11-11T14:46:14.000Z
my_vulkan/debug_callback.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
#include "debug_callback.hpp" #include "utils.hpp" #include <cassert> namespace my_vulkan { debug_callback_t::debug_callback_t( VkInstance instance, PFN_vkDebugReportCallbackEXT callback ) : _instance{instance} { VkDebugReportCallbackCreateInfoEXT debugReportCreateInfo = {}; debugReportCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debugReportCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT; debugReportCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)callback; // We have to explicitly load this function. PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>( vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT") ); assert(vkCreateDebugReportCallbackEXT); VkDebugReportCallbackEXT debugReportCallback; vk_require( vkCreateDebugReportCallbackEXT( instance, &debugReportCreateInfo, nullptr, &debugReportCallback ), "installing debug callback" ); _callback = debugReportCallback; } debug_callback_t::~debug_callback_t() { PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>( vkGetInstanceProcAddr(_instance, "vkDestroyDebugReportCallbackEXT") ); assert(vkDestroyDebugReportCallbackEXT); vkDestroyDebugReportCallbackEXT( _instance, _callback, 0 ); } }
33.339623
83
0.657612
pixelwise
dded06cb52cfd7864589f18a641cbdaee8e4ec7c
1,118
cpp
C++
src/Exciton/PaintingSecrets/PaintingFilesTool.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
src/Exciton/PaintingSecrets/PaintingFilesTool.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
src/Exciton/PaintingSecrets/PaintingFilesTool.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
#include <exciton.h> #include "ui_PaintingFilesTool.h" N::PaintingFilesTool:: PaintingFilesTool (QWidget * parent,Plan * p) : Widget ( parent, p) , ui (new Ui::PaintingFilesTool) { ui -> setupUi ( this ) ; nConnect ( ui->Back , SIGNAL(clicked ()) , this , SIGNAL(Back ()) ) ; nConnect ( ui->New , SIGNAL(clicked ()) , this , SIGNAL(New ()) ) ; nConnect ( ui->Add , SIGNAL(clicked ()) , this , SIGNAL(Add ()) ) ; nConnect ( ui->Remove , SIGNAL(clicked ()) , this , SIGNAL(Remove ()) ) ; nConnect ( ui->Packaging , SIGNAL(clicked ()) , this , SIGNAL(Packaging()) ) ; } N::PaintingFilesTool::~PaintingFilesTool(void) { delete ui ; } void N::PaintingFilesTool::setDeletion(bool enable) { ui -> Remove -> setEnabled ( enable ) ; } void N::PaintingFilesTool::setPackaging(bool enable) { ui -> Packaging -> setEnabled ( enable ) ; }
31.942857
68
0.488372
Vladimir-Lin