hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
ec9dc40a9f7f2297a974fa16c512ca298fec5278
3,975
cpp
C++
src/global.cpp
lemossilva/Corretor-Online-Python
74509b02d7b38435f7d20b0a2495c5f76d782389
[ "MIT" ]
null
null
null
src/global.cpp
lemossilva/Corretor-Online-Python
74509b02d7b38435f7d20b0a2495c5f76d782389
[ "MIT" ]
null
null
null
src/global.cpp
lemossilva/Corretor-Online-Python
74509b02d7b38435f7d20b0a2495c5f76d782389
[ "MIT" ]
null
null
null
#include <unistd.h> #include <signal.h> #include "global.hpp" #include "helper.hpp" #include "database.hpp" #include "message.hpp" #include "judge.hpp" #include "webserver.hpp" #include "contest.hpp" #include "attempt.hpp" using namespace std; static bool quit = false; class pjudge { public: pjudge() : sudden(sudden_shutdown()) { key_t key = msq.key(); FILE* fp = fopen("pjudge.bin", "wb"); fwrite(&key,sizeof key,1,fp); fclose(fp); } ~pjudge() { if (!sudden) remove("pjudge.bin"); } void update() { msq.update(); } static bool sudden_shutdown() { FILE* fp = fopen("pjudge.bin","rb"); if (!fp) return false; fclose(fp); return true; } static key_t alive() { FILE* fp = fopen("pjudge.bin", "rb"); if (!fp) return 0; key_t key; fread(&key,sizeof key,1,fp); fclose(fp); MessageQueue msq; PingMessage(msq.key()).send(key); if (msq.receive(3).mtype != IMALIVE) return 0; return key; } private: bool sudden; MessageQueue msq; }; static void term(int) { Global::shutdown(); } static key_t online() { key_t key = pjudge::alive(); if (!key) { printf("pjudge is not running: online operations can't be done.\n"); _exit(0); } return key; } static void offline() { if (pjudge::alive()) { printf("pjudge is running: offline operations can't be done.\n"); _exit(0); } } namespace Global { void install(const string& path) { FILE* fp = fopen(path.c_str(),"r"); if (fp) { fclose(fp); printf("pjudge install failed: file already exists.\n"); return; } system("mkdir -p %s",path.c_str()); system("cp -rf /usr/local/share/pjudge/* %s",path.c_str()); printf("pjudge installed at %s.\n",path.c_str()); } void start() { offline(); bool sudden = pjudge::sudden_shutdown(); if (sudden) printf( "WARNING: last pjudge[%s] execution stopped suddenly.\n" "this execution will not make database backups.\n" "\n" "FIX: 1) check your data; 2) stop pjudge; 3) manually rollback the\n" "database if necessary; 4) remove file 'pjudge.bin'.\n" "\n" "next execution will be fine.\n", getcwd().c_str() ); printf("pjudge[%s] started.\n",getcwd().c_str()); if (daemon(1,0) < 0) { // fork and redirect IO to /dev/null perror(stringf( "pjudge[%s] could not start in background", getcwd().c_str() ).c_str()); _exit(-1); } pjudge pj; // RAII signal(SIGTERM,term); // Global::shutdown(); signal(SIGPIPE,SIG_IGN); // ignore broken pipes (tcp shit) Database::init(!sudden); Contest::fix(); Attempt::fix(); Judge::init(); WebServer::init(); while (!quit) { pj.update(); usleep(25000); } WebServer::close(); Judge::close(); Database::close(); } void stop() { key_t key = online(); Message(STOP).send(key); MessageQueue msq; PingMessage ping(msq.key()); do{ ping.send(key); }while(msq.receive(1).mtype == IMALIVE); printf("pjudge[%s] stopped.\n",getcwd().c_str()); } void rerun_attempt(int id) { RerunAttMessage(id).send(online()); printf( "pjudge[%s] pushed attempt id=%d to queue.\n", getcwd().c_str(), id ); } void rerun_contest(int id){ DB(contests); JSON contest = contests.retrieve(id); JSON probs; map<int, bool> has_prob; if(contest("qnt_provas")){ for(int prova = 1; prova <= int(contest("qnt_provas")); prova++){ probs = contest("prova", tostr(prova)); for(int k : probs.arr()) has_prob[k] = true; } } else{ probs = contest("problems"); for(int k : probs.arr()) has_prob[k] = true; } DB(attempts); JSON tmp = attempts.retrieve(), ans(vector<JSON>{}), aux; for (auto& att : tmp.arr()) { int pid = att["problem"]; if(!has_prob.count(pid)) continue; int aid = att["id"]; Global::rerun_attempt(aid); } } void shutdown() { quit = true; } } // namespace Global
22.083333
73
0.596478
[ "vector" ]
eca2ecf88ecebd5db49cd13dc7a7ed317a0f2a27
3,504
cc
C++
src/mouse_controls.cc
WaldJohannaU/Classy3DViewer
2a3ccddc5f9a860a76a8293e9b2d41de72517096
[ "BSD-2-Clause" ]
9
2018-08-19T21:26:27.000Z
2022-01-24T07:19:36.000Z
src/mouse_controls.cc
WaldJohannaU/Classy3DViewer
2a3ccddc5f9a860a76a8293e9b2d41de72517096
[ "BSD-2-Clause" ]
null
null
null
src/mouse_controls.cc
WaldJohannaU/Classy3DViewer
2a3ccddc5f9a860a76a8293e9b2d41de72517096
[ "BSD-2-Clause" ]
1
2021-08-10T07:32:44.000Z
2021-08-10T07:32:44.000Z
/******************************************************* * Copyright (c) 2018, Johanna Wald * All rights reserved. * * This file is distributed under the GNU Lesser General Public License v3.0. * The complete license agreement can be obtained at: * http://www.gnu.org/licenses/lgpl-3.0.html ********************************************************/ #include "mouse_controls.h" #include "util.h" GUIMouseControls::GUIMouseControls(): eyeUp_(0,0,0) { view_.setIdentity(); } void GUIMouseControls::Update() { if (button_left_) { UpdateLeft(); } if (wheel_direction_ != 0) { wheel_distance_ += wheel_direction_; wheel_direction_ = 0; } // Direction: Spherical coordinates to Cartesian coordinates conversion Eigen::Vector3f direction(cos(vertical_angle_temp_) * sin(horizontal_angle_temp_), sin(vertical_angle_temp_), cos(vertical_angle_temp_) * cos(horizontal_angle_temp_)); Eigen::Vector3f right = Eigen::Vector3f(sin(horizontal_angle_temp_ - M_PI/2.0f), 0, cos(horizontal_angle_temp_ - M_PI/2.0f)); eyeUp_controls_ = right.cross(direction); if (button_right_) { UpdateRight(eyeUp_controls_, right); } // Right vector Eigen::Vector3f position_controls = pos_offset_control_temp_; look_at_controls_ = position_controls + 20 * direction; position_controls -= wheel_distance_ * 0.1f * direction; view_ = C3DV_camera::lookAt(position_controls, look_at_controls_, eyeUp_controls_); } void GUIMouseControls::Reset() { horizontal_angle_temp_ = horizontal_angle_; vertical_angle_temp_ = vertical_angle_; delta_pos_.setZero(); pos_offset_control_temp_ = pos_offset_control_; } void GUIMouseControls::ButtonReleased() { button_pressed_ = false; end_pos_ = current_pos_; delta_pos_.setZero(); horizontal_angle_ = horizontal_angle_temp_; vertical_angle_ = vertical_angle_temp_; pos_offset_control_ = pos_offset_control_temp_; } void GUIMouseControls::UpdateLeft() { horizontal_angle_temp_ = horizontal_angle_ + mouse_speed_ * delta_pos_.x(); vertical_angle_temp_ = vertical_angle_ + mouse_speed_ * delta_pos_.y(); } void GUIMouseControls::UpdateRight(const Eigen::Vector3f& eyeup_controls, const Eigen::Vector3f& right) { pos_offset_control_temp_ = pos_offset_control_ - delta_pos_.x() * 0.01f * right + delta_pos_.y() * 0.01f * eyeup_controls; } void GUIMouseControls::Pressed(const nanogui::Vector2i &position) { if (button_pressed_) { if (!initialized_) previous_pos_ = current_pos_; current_pos_[0] = static_cast<float>(position.x()); current_pos_[1] = static_cast<float>(position.y()); delta_pos_ = current_pos_ - previous_pos_; initialized_ = true; } } bool GUIMouseControls::ScrollCallbackEvent(double x, double y) { wheel_direction_ += y; return true; } bool GUIMouseControls::MouseButtonEvent(const nanogui::Vector2i &position, int button, bool down, int modifiers) { current_pos_[0] = static_cast<float>(position.x()); current_pos_[1] = static_cast<float>(position.y()); if (down) { button_pressed_ = true; } else { ButtonReleased(); } if (button == GLFW_MOUSE_BUTTON_1) { button_left_ = button_pressed_; } else if (button == GLFW_MOUSE_BUTTON_2) { button_right_ = button_pressed_; } previous_pos_ = current_pos_; return true; }
34.693069
129
0.673516
[ "vector" ]
ecabc15f6640df607bb1f5d343a8833590974c69
1,316
cpp
C++
algorithms/0040_CombinationSumII/0040_CombinationSumII.cpp
23468234/leetcode-question
35aad4065401018414de63d1a983ceacb51732a6
[ "MIT" ]
null
null
null
algorithms/0040_CombinationSumII/0040_CombinationSumII.cpp
23468234/leetcode-question
35aad4065401018414de63d1a983ceacb51732a6
[ "MIT" ]
null
null
null
algorithms/0040_CombinationSumII/0040_CombinationSumII.cpp
23468234/leetcode-question
35aad4065401018414de63d1a983ceacb51732a6
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { if (candidates.empty()){ return {{}}; } vector<vector<int>> rst; vector<int> tmp; vector<bool> used(candidates.size(), false); sort(candidates.begin(), candidates.end()); dfs(rst, tmp, 0, candidates, target, used); return rst; } void dfs(vector<vector<int>> &rst, vector<int>& tmp, int sum, vector<int>& nums, int target, vector<bool> &used){ if (sum == target){ rst.push_back(tmp); return; } for (int i = 0; i < nums.size(); ++i){ if (used[i]){ continue; } if (tmp.size() > 0 && tmp.at(tmp.size() - 1) > nums.at(i)){ continue; } if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]){ continue; } if (sum + nums[i] > target){ continue; } used[i] = true; sum = sum + nums[i]; tmp.push_back(nums.at(i)); dfs(rst, tmp, sum, nums, target, used); tmp.pop_back(); sum = sum - nums[i]; used[i] = false; } } };
28
124
0.430091
[ "vector" ]
ecaf46ff9cadd1cd6dc1fcc2bf0875a486865bfe
4,916
cpp
C++
fluffy/core/src/graphics/transformable.cpp
Lo-X/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2015-12-27T14:42:53.000Z
2018-04-18T07:28:05.000Z
fluffy/core/src/graphics/transformable.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2018-04-27T14:26:29.000Z
2021-01-29T16:28:18.000Z
fluffy/core/src/graphics/transformable.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
null
null
null
#include <fluffy/graphics/transformable.hpp> using namespace Fluffy; FloatRect transformRect(const glm::mat4& transform, const FloatRect& bounds) { // Transform the bounding rectangle 4 corners const Vector4f points[] = { transform * Vector4f(bounds.left, bounds.top, 1.f, 1.f), // top-left corner transform * Vector4f(bounds.left, bounds.top + bounds.height, 1.f, 1.f), // bottom-left corner transform * Vector4f(bounds.left + bounds.width, bounds.top, 1.f, 1.f), // top-right corner transform * Vector4f(bounds.left + bounds.width, bounds.top + bounds.height, 1.f, 1.f) // bottom-right corner }; // Compute the transformed bounding rectangle float left = points[0].x; float top = points[0].y; float right = points[0].x; float bottom = points[0].y; for (int i = 1; i < 4; ++i) { if (points[i].x < left) left = points[i].x; else if (points[i].x > right) right = points[i].x; if (points[i].y < top) top = points[i].y; else if (points[i].y > bottom) bottom = points[i].y; } return FloatRect(left, top, right - left, bottom - top); } /**********************************************************************************************************************/ Transformable::Transformable() : mOrigin({ 0.f, 0.f, 0.f }) , mPosition({ 0.f, 0.f, 0.f }) , mEulerAngles({ 0.f, 0.f, 0.f }) , mScale({ 1.f, 1.f, 1.f }) , mTransform(glm::mat4(1.0f)) , mInverseTransform(glm::mat4(1.0f)) { } void Transformable::setOrigin(const Vector2f& origin) { setOrigin({ origin.x, origin.y, 0.f }); } void Transformable::setOrigin(const Vector3f& origin) { mOrigin = origin; mNeedToUpdate = true; } Vector3f Transformable::getOrigin() const { return mOrigin; } void Transformable::setPosition(const Vector2f& position) { setPosition({ position.x, position.y, 0.f }); } void Transformable::setPosition(const Vector3f& position) { mPosition = position; mNeedToUpdate = true; } void Transformable::move(const Vector2f& delta) { move({ delta.x, delta.y, 0 }); } void Transformable::move(const Vector3f& delta) { mPosition += delta; mNeedToUpdate = true; } Vector3f Transformable::getPosition() const { return mPosition; } void Transformable::setScale(const Vector2f& scale) { setScale({ scale.x, scale.y, 1.f }); } void Transformable::setScale(const Vector3f& scale) { mScale = scale; mNeedToUpdate = true; } Vector3f Transformable::getScale() const { return mScale; } void Transformable::setRotation(const Vector2f& eulerAngles) { mEulerAngles.x = eulerAngles.x; mEulerAngles.y = eulerAngles.y; mNeedToUpdate = true; } void Transformable::setRotation(const Vector3f& eulerAngles) { mEulerAngles.x = eulerAngles.x; mEulerAngles.y = eulerAngles.y; mEulerAngles.z = eulerAngles.z; mNeedToUpdate = true; } void Transformable::rotateX(float degrees) { mEulerAngles.x += degrees; mNeedToUpdate = true; } void Transformable::rotateY(float degrees) { mEulerAngles.y += degrees; mNeedToUpdate = true; } void Transformable::rotateZ(float degrees) { mEulerAngles.z += degrees; mNeedToUpdate = true; } Vector3f Transformable::getEulerAngles() const { return mEulerAngles; } void Transformable::setTransformMatrix(const glm::mat4& transform) { mPosition = transform[3]; for (int i = 0; i < 3; i++) { mScale[i] = glm::length(glm::vec3(transform[i])); } const glm::mat3 rotMtx( glm::vec3(transform[0]) / mScale[0], glm::vec3(transform[1]) / mScale[1], glm::vec3(transform[2]) / mScale[2]); auto rotation = glm::conjugate(glm::quat_cast(rotMtx)); mEulerAngles = glm::eulerAngles(rotation) * 3.14159f / 180.f; FLUFFY_LOG_INFO("angles = {}", mEulerAngles); mNeedToUpdate = true; } const glm::mat4& Transformable::getTransformMatrix() const { if (mNeedToUpdate) { mTransform = glm::translate(glm::mat4(1.f), mPosition) * glm::rotate(glm::mat4(1.f), glm::radians(mEulerAngles.x), { 1, 0, 0 }) * glm::rotate(glm::mat4(1.f), glm::radians(mEulerAngles.y), { 0, -1, 0 }) * glm::rotate(glm::mat4(1.f), glm::radians(mEulerAngles.z), { 0, 0, 1 }) * glm::translate(glm::mat4(1.f), -mOrigin * mScale) * glm::scale(glm::mat4(1.f), mScale); mNeedToUpdate = false; mNeedToUpdateInverse = true; } return mTransform; } const glm::mat4& Transformable::getInverseTransform() const { if (mNeedToUpdate || mNeedToUpdateInverse) { mInverseTransform = glm::inverse(getTransformMatrix()); mNeedToUpdateInverse = false; } return mInverseTransform; }
26.148936
120
0.605574
[ "transform" ]
ecb068abc6f8a214ff589bb7ffb2c1429826d989
37,441
cc
C++
convert/texturator.cc
TyLindberg/usd_from_gltf
aaf90a29796d4eec24389dbf600edcbe225d6dec
[ "Apache-2.0" ]
1
2020-01-18T23:11:25.000Z
2020-01-18T23:11:25.000Z
convert/texturator.cc
TyLindberg/usd_from_gltf
aaf90a29796d4eec24389dbf600edcbe225d6dec
[ "Apache-2.0" ]
null
null
null
convert/texturator.cc
TyLindberg/usd_from_gltf
aaf90a29796d4eec24389dbf600edcbe225d6dec
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Google 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. */ #include "convert/texturator.h" #include "gltf/disk_util.h" #include "process/float_image.h" #include "process/math.h" namespace ufg { namespace { // Use premultiplied alpha when resizing so colors are weighted by opacity. constexpr bool kResizePremulAlpha = true; constexpr ColorChannel kChannelOcclusion = kColorChannelR; constexpr ColorChannel kChannelMetallic = kColorChannelB; constexpr ColorChannel kChannelRoughness = kColorChannelG; constexpr ColorChannel kChannelGlossiness = kColorChannelA; constexpr uint32_t kQuantizeBits = 10; constexpr uint32_t kQuantizeUnits = 1 << kQuantizeBits; const ColorI kQuantizeScaleIdentity = {kQuantizeUnits, kQuantizeUnits, kQuantizeUnits, kQuantizeUnits}; const ColorI kQuantizeBiasIdentity = {0, 0, 0, 0}; enum PassId { kPassIdRemoveAlpha, kPassIdAddAlpha, kPassIdColorSpace, kPassIdNormalizeNormals, kPassIdAlphaCutoff, kPassIdScaleBias, kPassIdSpecToMetal, kPassIdResize, }; constexpr uint32_t kPassFlagRemoveAlpha = 1 << kPassIdRemoveAlpha; constexpr uint32_t kPassFlagAddAlpha = 1 << kPassIdAddAlpha; constexpr uint32_t kPassFlagColorSpace = 1 << kPassIdColorSpace; constexpr uint32_t kPassFlagNormalizeNormals = 1 << kPassIdNormalizeNormals; constexpr uint32_t kPassFlagAlphaCutoff = 1 << kPassIdAlphaCutoff; constexpr uint32_t kPassFlagScaleBias = 1 << kPassIdScaleBias; constexpr uint32_t kPassFlagSpecToMetal = 1 << kPassIdSpecToMetal; constexpr uint32_t kPassFlagResize = 1 << kPassIdResize; constexpr uint32_t kPassMaskFloat = kPassFlagColorSpace | kPassFlagScaleBias | kPassFlagSpecToMetal | kPassFlagResize; using RelevanceMask = uint8_t; constexpr RelevanceMask kRelevanceR = 1 << kColorChannelR; constexpr RelevanceMask kRelevanceG = 1 << kColorChannelG; constexpr RelevanceMask kRelevanceB = 1 << kColorChannelB; constexpr RelevanceMask kRelevanceA = 1 << kColorChannelA; constexpr RelevanceMask kRelevanceRGB = kRelevanceR | kRelevanceG | kRelevanceB; constexpr RelevanceMask kRelevanceRGBA = kRelevanceRGB | kRelevanceA; struct UsageInfo { // Destination image name suffix. const char* dst_suffix; // Max number of color components in the destination image. uint8_t dst_component_max; // Indicates which channels in the source image are relevant to the output. RelevanceMask relevance_mask; // Color space for source and destination RGB components. A is always linear. ColorSpace src_rgb_color_space; ColorSpace dst_rgb_color_space; }; #define TEXUSG(suffix, comps, rel, src, dst) \ {suffix, comps, kRelevance##rel, kColorSpace##src, kColorSpace##dst} const UsageInfo kUsageInfos[] = { TEXUSG("" , 4, RGBA, Srgb , Srgb ), // kUsageDefault TEXUSG("_lin" , 4, RGBA, Srgb , Linear), // kUsageLinear TEXUSG("_base" , 4, RGBA, Srgb , Srgb ), // kUsageDiffToBase TEXUSG("" , 3, RGB , Linear, Linear), // kUsageNorm TEXUSG("_occl" , 1, R , Linear, Linear), // kUsageOccl TEXUSG("_metal" , 1, B , Linear, Linear), // kUsageMetal TEXUSG("_rough" , 1, G , Linear, Linear), // kUsageRough TEXUSG("_spec" , 3, RGB , Srgb , Srgb ), // kUsageSpec TEXUSG("_metal" , 3, RGB , Srgb , Linear), // kUsageSpecToMetal TEXUSG("_gloss" , 1, A , Linear, Linear), // kUsageGloss TEXUSG("_rough" , 1, A , Linear, Linear), // kUsageGlossToRough TEXUSG("_unlit_a", 4, A , Srgb , Srgb ), // kUsageUnlitA }; #undef TEXUSG static_assert(UFG_ARRAY_SIZE(kUsageInfos) == Texturator::kUsageCount, ""); struct FallbackInfo { const char* name; bool r_only; Image::Component color[3]; }; const FallbackInfo kFallbackInfos[] = { {"fallback_black.png" , false, { 0, 0, 0}}, // kFallbackBlack {"fallback_magenta.png", false, {255, 0, 255}}, // kFallbackMagenta {"fallback_r0.png" , true , { 0, 0, 0}}, // kFallbackR0 {"fallback_r1.png" , true , {255, 255, 255}}, // kFallbackR1 }; static_assert(UFG_ARRAY_SIZE(kFallbackInfos) == Texturator::kFallbackCount, ""); void SetImageExtension(Gltf::Image::MimeType mime_type, std::string* path) { if (mime_type == Gltf::Image::kMimeUnset) { return; } const char* const ext = Gltf::GetMimeTypeExtension(mime_type); const Gltf::Image::MimeType old_mime_type = Gltf::FindImageMimeTypeByPath(*path); if (old_mime_type != Gltf::Image::kMimeUnset) { // Remove the existing image type extension. This has two effects: // 1) It allows us to change the destination image type. // 2) It canonicalizes the type extension. This is important for some apps // (such as Usdview) that recognize ".jpg" but not ".jpeg". const size_t old_ext_pos = path->rfind('.'); UFG_ASSERT_LOGIC(old_ext_pos != std::string::npos); path->resize(old_ext_pos); } *path += ext; } const int Quantize(float value) { return static_cast<int>(value * kQuantizeUnits + 0.5f); } ColorI Quantize(const ColorF& f) { ColorI q; for (size_t i = 0; i != UFG_ARRAY_SIZE(f.c); ++i) { q.c[i] = Quantize(f.c[i]); } return q; } std::unique_ptr<Image> CopyImageRgb(const Image& src) { std::unique_ptr<Image> dst(new Image()); dst->CreateFromRgb(src); return dst; } std::unique_ptr<Image> CopyImageRgba(const Image& src) { std::unique_ptr<Image> dst(new Image()); dst->CreateFromRgba(src, Image::kComponentMax); return dst; } std::unique_ptr<Image> CopyImageChannel(const Image& src, ColorChannel channel, const Image::Transform& transform) { std::unique_ptr<Image> dst(new Image()); dst->CreateFromChannel(src, channel, transform); return dst; } std::unique_ptr<Image> CopyImageMasked( const Image& src, const Image::Component (&keep_mask)[kColorChannelCount], const Image::Component (&replace_value)[kColorChannelCount]) { std::unique_ptr<Image> dst(new Image()); dst->CreateFromMasked(src, keep_mask, replace_value); return dst; } std::unique_ptr<Image> CopyImageByUsage( const Image& src, Texturator::Usage usage, uint32_t pass_mask) { switch (usage) { case Texturator::kUsageDiffToBase: return CopyImageRgb(src); case Texturator::kUsageOccl: return CopyImageChannel(src, kChannelOcclusion, Image::Transform::kNone); case Texturator::kUsageMetal: return CopyImageChannel(src, kChannelMetallic, Image::Transform::kNone); case Texturator::kUsageRough: return CopyImageChannel(src, kChannelRoughness, Image::Transform::kNone); case Texturator::kUsageSpec: return CopyImageRgb(src); case Texturator::kUsageSpecToMetal: return CopyImageRgb(src); case Texturator::kUsageGloss: return CopyImageChannel(src, kChannelGlossiness, Image::Transform::kNone); case Texturator::kUsageGlossToRough: return CopyImageChannel(src, kChannelGlossiness, Image::Transform::kNone); case Texturator::kUsageUnlitA: return CopyImageMasked(src, {0, 0, 0, 0xff}, {0, 0, 0, 0}); case Texturator::kUsageDefault: case Texturator::kUsageNorm: case Texturator::kUsageLinear: default: if (pass_mask & kPassFlagRemoveAlpha) { return CopyImageRgb(src); } else if (pass_mask & kPassFlagAddAlpha) { return CopyImageRgba(src); } else { return std::unique_ptr<Image>(new Image(src)); } break; } } std::unique_ptr<Image> WhiteImageByUsage(const Image& src, Texturator::Usage usage) { const UsageInfo& usage_info = kUsageInfos[usage]; static const Image::Component kWhite[] = { Image::kComponentMax, Image::kComponentMax, Image::kComponentMax, Image::kComponentMax}; std::unique_ptr<Image> image(new Image()); const size_t channel_count = std::min(src.GetChannelCount(), static_cast<uint32_t>(usage_info.dst_component_max)); image->CreateWxH(src.GetWidth(), src.GetHeight(), kWhite, channel_count); return image; } std::string GetSrcName(const Gltf& gltf, Gltf::Id image_id, Gltf::Image::MimeType* out_mime_type) { const Gltf::Image* const gltf_image = Gltf::GetById(gltf.images, image_id); if (gltf_image) { const bool is_buffer = gltf_image->bufferView != Gltf::Id::kNull; const bool is_embedded = gltf_image->uri.data_type != Gltf::Uri::kDataTypeNone; if (is_buffer || is_embedded) { const Gltf::Image::MimeType mime_type = is_embedded ? Gltf::GetUriDataImageMimeType(gltf_image->uri.data_type) : gltf_image->mimeType; const char* const ext = mime_type == Gltf::Image::kMimeOther ? "" : Gltf::GetMimeTypeExtension(mime_type); if (ext) { *out_mime_type = mime_type; return AppendNumber("bin/image", Gltf::IdToIndex(image_id)) + ext; } } else { *out_mime_type = Gltf::FindImageMimeTypeByPath(gltf_image->uri.path); return Gltf::GetSanitizedPath(gltf_image->uri.path.c_str()); } } *out_mime_type = Gltf::Image::kMimeUnset; return std::string(); } void ApplyFloatPasses(const Texturator::Args& args, uint32_t pass_mask, size_t width, size_t height, FloatImage* image) { if (pass_mask & kPassFlagScaleBias) { if (args.usage == Texturator::kUsageNorm) { image->ScaleBiasNormals(args.scale, args.bias); } else { image->ScaleBias(args.scale, args.bias); } } if (pass_mask & kPassFlagResize) { image->Resize(width, height, kResizePremulAlpha); } } void GetDstSize(uint32_t src_width, uint32_t src_height, const ImageResizeSettings& resize, float global_scale, uint32_t* out_width, uint32_t* out_height) { UFG_ASSERT_LOGIC(resize.size_min <= resize.size_max); UFG_ASSERT_LOGIC(resize.size_min > 0); const float scale = resize.scale * global_scale; uint32_t width = std::max(1, static_cast<int>(src_width * scale + 0.5f)); uint32_t height = std::max(1, static_cast<int>(src_height * scale + 0.5f)); // TODO: These operations can change the aspect ratio, which we may // want to prevent. if (resize.force_power_of_2) { width = Power2Floor(width); height = Power2Floor(height); } width = Clamp(width, resize.size_min, resize.size_max); height = Clamp(height, resize.size_min, resize.size_max); *out_width = width; *out_height = height; } size_t EstimateDecompressedImageSize(const Image& image, const Texturator::Args& args, float global_scale) { uint32_t width, height; GetDstSize(image.GetWidth(), image.GetHeight(), args.resize, global_scale, &width, &height); const UsageInfo& usage_info = kUsageInfos[args.usage]; const size_t channel_count = std::min(image.GetChannelCount(), static_cast<uint32_t>(usage_info.dst_component_max)); // Determined experimentally, the iOS viewer uses surface formats of R8 or // RGBA8. const size_t aligned_channel_count = channel_count == 1 ? 1 : 4; // Determined experimentally, there is some texture alignment less than this // amount. const size_t kAlignSize = 64; const size_t aligned_width = AlignUp(width, kAlignSize); const size_t aligned_height = AlignUp(height, kAlignSize); // Add the base image plus 1/3 for mip maps (approximate sum of progressively // halved mips is 1/3). const size_t base_pixels = aligned_width * aligned_height; const size_t mip_pixels = base_pixels / 3; return (base_pixels + mip_pixels) * aligned_channel_count; } } // namespace void Texturator::Clear() { cc_ = nullptr; srcs_.clear(); dsts_.clear(); scale_ids_.clear(); bias_ids_.clear(); jobs_.clear(); written_.clear(); } void Texturator::Begin(ConvertContext* cc) { cc_ = cc; } void Texturator::End() { // Apply global resize scale. const float global_scale = ChooseGlobalScale(); if (global_scale != 1.0f) { for (Job& job : jobs_) { const size_t op_count = job.type == kJobAddSpecToMetal ? 2 : 1; for (size_t op_index = 0; op_index != op_count; ++op_index) { Op& op = job.ops[op_index]; if (op.src->image) { const Image& image = *op.src->image; const uint32_t src_width = image.GetWidth(); const uint32_t src_height = image.GetHeight(); GetDstSize(src_width, src_height, op.args.resize, global_scale, &op.resize_width, &op.resize_height); if (op.resize_width != src_width || op.resize_height != src_height) { op.pass_mask |= kPassFlagResize; op.direct_copy = false; } } } } } // Create directories for images up-front. bool prep_failed = false; for (const Job& job : jobs_) { const size_t op_count = job.type == kJobAddSpecToMetal ? 2 : 1; for (size_t op_index = 0; op_index != op_count; ++op_index) { const Op& op = job.ops[op_index]; if (!op.direct_copy || op.need_copy) { if (!PrepareWrite(op.dst_path)) { prep_failed = true; } } } } if (prep_failed) { return; } // Process jobs sequentially. // Note, this could be multithreaded but there are several issues that make it // impractical currently: // - The logging and IO caching are not thread-safe. // - There are a limited number of textures, so we don't get high utilization // by processing them in parallel. To get better utilization, we need to // break up the images themselves into smaller sections. // - The ufgtest.py batch conversion script already performs multithreading on // a process basis, so multithreading within each process helps very little // (and in some cases may be detrimental). for (const Job& job : jobs_) { ProcessJob(job); } } const std::string& Texturator::Add(Gltf::Id image_id, const Args& args) { Op op(image_id, args); const std::string* const dst_name = AddDst(image_id, args, &op); if (!dst_name) { return AddFallback(args.fallback); } if (!op.is_new) { // Destination image already written. Just return the name. return *dst_name; } jobs_.push_back(Job()); Job& job = jobs_.back(); job.type = kJobAdd; job.ops[0] = op; return *dst_name; } void Texturator::AddSpecToMetal(Gltf::Id spec_image_id, const Args& spec_args, Gltf::Id diff_image_id, const Args& diff_args, const std::string** out_metal_name, const std::string** out_base_name) { UFG_ASSERT_LOGIC(spec_args.usage == kUsageSpecToMetal); UFG_ASSERT_LOGIC(diff_args.usage == kUsageDiffToBase); Op spec_op(spec_image_id, spec_args); Op diff_op(diff_image_id, diff_args); const std::string* spec_dst_name = AddDst(spec_image_id, spec_args, &spec_op); const std::string* diff_dst_name = AddDst(diff_image_id, diff_args, &diff_op); if (!spec_dst_name && !diff_dst_name) { *out_metal_name = &AddFallback(spec_args.fallback); *out_base_name = &AddFallback(diff_args.fallback); return; } // If either source is absent, use the name of the other. spec_op.is_constant = !spec_dst_name; if (spec_op.is_constant) { spec_dst_name = AddDst(diff_image_id, spec_args, &spec_op); } diff_op.is_constant = !diff_dst_name; if (diff_op.is_constant) { diff_dst_name = AddDst(spec_image_id, diff_args, &diff_op); } if (!spec_op.is_new && !diff_op.is_new) { // Both destination images already written. Just return the names. *out_metal_name = spec_dst_name; *out_base_name = diff_dst_name; return; } jobs_.push_back(Job()); Job& job = jobs_.back(); job.type = kJobAddSpecToMetal; job.ops[0] = spec_op; job.ops[1] = diff_op; *out_metal_name = spec_dst_name; *out_base_name = diff_dst_name; } int Texturator::GetSolidAlpha(Gltf::Id image_id) { Src* const src = FindOrAddSrc(image_id); if (!src) { return Image::kComponentMax; } EnsureComponentContent(image_id, src); if (!Image::IsSolid(src->rgba_contents[kColorChannelA])) { return -1; } return src->solid_color[kColorChannelA]; } bool Texturator::IsAlphaOpaque(Gltf::Id image_id, float scale, float bias) { const int ia = GetSolidAlpha(image_id); if (ia < 0) { return false; } const float a = (ia * Image::kComponentToFloatScale) * scale + bias; return a >= 1.0f - kColorTol; } bool Texturator::IsAlphaFullyTransparent( Gltf::Id image_id, float scale, float bias) { const int ia = GetSolidAlpha(image_id); if (ia < 0) { return false; } const float a = (ia * Image::kComponentToFloatScale) * scale + bias; return a <= kColorTol; } Texturator::ColorId Texturator::GetColorId( const ColorF& color, const ColorI& identity, ColorIdMap* color_id_map) { const ColorI q = Quantize(color); if (q == identity) { return kColorIdIdentity; } const ColorId new_id = static_cast<ColorId>(color_id_map->size()); const auto insert_result = color_id_map->insert(std::make_pair(q, new_id)); return insert_result.first->second; } std::string Texturator::GetDstSuffix( const Texturator::Args& args, Gltf::Id image_id, Src* src, Op* op) { uint32_t pass_mask = 0; std::string suffix; const UsageInfo& usage_info = kUsageInfos[args.usage]; if (args.usage == Texturator::kUsageDefault) { const bool remove_alpha = args.alpha_mode == Gltf::Material::kAlphaModeOpaque && GetComponentContent(kColorChannelA, image_id, src) != Image::kContentSolid1; if (remove_alpha) { suffix += "_rgb"; pass_mask |= kPassFlagRemoveAlpha; } } else { suffix += usage_info.dst_suffix; } if (usage_info.src_rgb_color_space != usage_info.dst_rgb_color_space) { pass_mask |= kPassFlagColorSpace; } if (args.usage == kUsageSpecToMetal) { pass_mask |= kPassFlagSpecToMetal; } if (cc_->settings.bake_texture_color_scale_bias) { const ColorId scale_id = GetColorId(args.scale, kQuantizeScaleIdentity, &scale_ids_); if (scale_id != kColorIdIdentity) { suffix += AppendNumber("_scale", scale_id); pass_mask |= kPassFlagScaleBias; } const ColorId bias_id = GetColorId(args.bias, kQuantizeBiasIdentity, &bias_ids_); if (bias_id != kColorIdIdentity) { suffix += AppendNumber("_bias", bias_id); pass_mask |= kPassFlagScaleBias; } } // Add alpha channel if it's missing but needed for alpha scale/bias. if (args.usage == Texturator::kUsageDefault && args.alpha_mode != Gltf::Material::kAlphaModeOpaque && (pass_mask & kPassFlagScaleBias) && (args.scale.a != 1.0f || args.bias.a != 0.0f)) { LoadSrc(image_id, src); if (src->image && src->image->GetChannelCount() < kColorChannelCount) { suffix += "_rgba"; pass_mask |= kPassFlagAddAlpha; } } if (GetResizeSize(image_id, args.resize, src, &op->resize_width, &op->resize_height)) { suffix += AppendNumber("_", op->resize_width); suffix += AppendNumber("x", op->resize_height); pass_mask |= kPassFlagResize; } if (cc_->settings.normalize_normals && args.usage == kUsageNorm && ((pass_mask & kPassFlagScaleBias) || NeedNormalization(image_id, src))) { suffix += "_norm"; pass_mask |= kPassFlagNormalizeNormals; } if (cc_->settings.bake_alpha_cutoff && args.alpha_mode == Gltf::Material::kAlphaModeMask) { const Image::Content content = GetComponentContent(kColorChannelA, image_id, src); if (!Image::IsBinary(content)) { const Image::Component cutoff = Image::FloatToComponent(args.alpha_cutoff); suffix += AppendNumber("_cutoff", cutoff); pass_mask |= kPassFlagAlphaCutoff; } } op->pass_mask = pass_mask; return suffix; } const std::string& Texturator::AddFallback(Fallback fallback) { // Create the fallback on-demand, the first time it's referenced. const FallbackInfo& info = kFallbackInfos[fallback]; const auto dst_insert_result = dsts_.insert(std::string(info.name)); const std::string& dst_name = *dst_insert_result.first; if (!dst_insert_result.second) { return dst_name; } Image image; if (info.r_only) { image.CreateR1x1(info.color[0]); } else { image.Create1x1(info.color); } const std::string dst_path = Gltf::JoinPath(cc_->dst_dir, dst_name); if (PrepareWrite(dst_path)) { if (!image.Write(dst_path.c_str(), cc_->settings, cc_->logger)) { Log<UFG_ERROR_IO_WRITE_IMAGE>(dst_path.c_str()); } } return dst_name; } void Texturator::LoadSrc(Gltf::Id image_id, Src* src) const { // Load source image on-demand, the first time it is referenced. if (src->state != kStateNew) { return; } Gltf::Image::MimeType named_mime_type; src->name = GetSrcName(*cc_->gltf, image_id, &named_mime_type); UFG_ASSERT_LOGIC(!src->name.empty()); size_t size; Gltf::Image::MimeType mime_type; const uint8_t* const data = cc_->gltf_cache.GetImageData(image_id, &size, &mime_type); if (!data) { src->state = kStateMissing; return; } std::unique_ptr<Image> image(new Image()); { Logger::NameSentry name_sentry(cc_->logger, src->name); if (!image->Read(data, size, mime_type, cc_->logger)) { src->state = kStateMissing; return; } } src->image = std::move(image); src->state = kStateLoaded; } Texturator::Src* Texturator::FindOrAddSrc(Gltf::Id image_id) { const Gltf::Image* const gltf_image = Gltf::GetById(cc_->gltf->images, image_id); if (!gltf_image) { return nullptr; } const auto src_insert_result = srcs_.insert(std::make_pair(image_id, Src())); if (src_insert_result.second && !cc_->gltf_cache.ImageExists(image_id)) { Gltf::Image::MimeType mime_type; const std::string src_name = GetSrcName(*cc_->gltf, image_id, &mime_type); GltfLog<GLTF_ERROR_MISSING_IMAGE>(cc_->logger, "", src_name.c_str()); } return &src_insert_result.first->second; } const std::string* Texturator::AddDst(Gltf::Id image_id, const Args& args, Op* out_op) { out_op->is_new = false; Gltf::Image::MimeType mime_type; const std::string src_name = GetSrcName(*cc_->gltf, image_id, &mime_type); if (src_name.empty()) { return nullptr; } // Find or add the source image. const auto src_insert_result = srcs_.insert(std::make_pair(image_id, Src())); Src& src = src_insert_result.first->second; if (src_insert_result.second) { // Verify the source file exists. if (!cc_->gltf_cache.ImageExists(image_id)) { GltfLog<GLTF_ERROR_MISSING_IMAGE>(cc_->logger, "", src_name.c_str()); return nullptr; } } out_op->src = &src; // Generate a unique destination name based on conversion args. const std::string dst_suffix = GetDstSuffix(args, image_id, &src, out_op); std::string new_name = AddFileNameSuffix(src_name, dst_suffix.c_str()); // Choose image type based on the source type and presence of alpha. Gltf::Image::MimeType dst_mime_type = mime_type; const bool is_supported_output_type = (dst_mime_type != Gltf::Image::kMimeJpeg && dst_mime_type != Gltf::Image::kMimePng); const bool override_jpg = cc_->settings.prefer_jpeg && dst_mime_type != Gltf::Image::kMimeJpeg; if (!is_supported_output_type || override_jpg) { if (args.alpha_mode == Gltf::Material::kAlphaModeOpaque || GetComponentContent(kColorChannelA, image_id, &src) == Image::kContentSolid1) { dst_mime_type = Gltf::Image::kMimeJpeg; } else { dst_mime_type = Gltf::Image::kMimePng; } } if (out_op->pass_mask & kPassFlagAddAlpha) { dst_mime_type = Gltf::Image::kMimePng; } SetImageExtension(dst_mime_type, &new_name); // Find or add a destination entry keyed by its unique name. const auto dst_insert_result = dsts_.insert(new_name); const std::string& dst_name = *dst_insert_result.first; if (!dst_insert_result.second) { return &dst_name; } out_op->is_new = true; out_op->dst_path = Gltf::JoinPath(cc_->dst_dir, dst_name); if (dst_suffix.empty() && dst_mime_type == mime_type) { if (cc_->settings.limit_total_image_decompressed_size != 0) { // We need to load the source image to determine size info. // TODO: Ideally, load just the size rather than the whole file. LoadSrc(image_id, &src); } out_op->direct_copy = true; out_op->need_copy = !cc_->gltf_cache.IsImageAtPath( image_id, cc_->dst_dir.c_str(), dst_name.c_str()); return &dst_name; } LoadSrc(image_id, &src); if (src.state == kStateMissing) { return nullptr; } return &dst_name; } void Texturator::EnsureComponentContent(Gltf::Id image_id, Src* src) const { LoadSrc(image_id, src); if (src->image && src->rgba_contents[kColorChannelR] == Image::kContentCount) { src->image->GetContents(src->rgba_contents, cc_->settings.fix_accidental_alpha, src->solid_color); } } Image::Content Texturator::GetComponentContent( ColorChannel channel, Gltf::Id image_id, Src* src) const { EnsureComponentContent(image_id, src); return src->rgba_contents[channel]; } bool Texturator::NeedNormalization(Gltf::Id image_id, Src* src) const { LoadSrc(image_id, src); if (src->normal_content != kNormalUnknown) { return src->normal_content == kNormalNonNormalized; } if (!src->image) { src->normal_content = kNormalNormalized; return false; } const Image& image = *src->image; const size_t width = image.GetWidth(); const size_t height = image.GetHeight(); const size_t channel_count = image.GetChannelCount(); UFG_ASSERT_FORMAT(channel_count >= 3); // Given u8 component size, fixed-point values fit in an int. For u16, this // needs to be changed to int64_t. static_assert(sizeof(Image::Component) == sizeof(uint8_t), ""); using FpInt = int; static constexpr FpInt kOne = Image::kComponentMax; // The maximum error allowed, in squared fixed-point units. // * The effective linear tolerance is sqrt(kErrSqTol/kOne)/kOne. static constexpr FpInt kErrSqTol = 4 * kOne; // sqrt(4)/255 = ~0.008 const Image::Component* pixel = image.GetData(); const Image::Component* const pixel_end = pixel + width * height * channel_count; for (; pixel != pixel_end; pixel += channel_count) { const FpInt x = 2 * static_cast<FpInt>(pixel[0]) - kOne; const FpInt y = 2 * static_cast<FpInt>(pixel[1]) - kOne; const FpInt z = 2 * static_cast<FpInt>(pixel[2]) - kOne; const int m_sq = x * x + y * y + z * z; const int err_sq = m_sq - kOne * kOne; if (std::abs(err_sq) > kErrSqTol) { src->normal_content = kNormalNonNormalized; return true; } } src->normal_content = kNormalNormalized; return false; } uint32_t Texturator::GetSrcWidth(Gltf::Id image_id, Src* src) const { LoadSrc(image_id, src); return src->image ? src->image->GetWidth() : 0; } uint32_t Texturator::GetSrcHeight(Gltf::Id image_id, Src* src) const { LoadSrc(image_id, src); return src->image ? src->image->GetHeight() : 0; } bool Texturator::GetResizeSize( Gltf::Id image_id, const ImageResizeSettings& resize, Src* src, uint32_t* out_width, uint32_t* out_height) const { UFG_ASSERT_LOGIC(resize.size_min <= resize.size_max); UFG_ASSERT_LOGIC(resize.size_min > 0); if (resize.IsDefault()) { return false; } const uint32_t src_width = GetSrcWidth(image_id, src); if (src_width == 0) { return false; } const uint32_t src_height = GetSrcHeight(image_id, src); uint32_t dst_width, dst_height; GetDstSize(src_width, src_height, resize, 1.0f, &dst_width, &dst_height); if (dst_width == src_width && dst_height == src_height) { return false; } *out_width = dst_width; *out_height = dst_height; return true; } size_t Texturator::EstimateDecompressedJobSize(const Job& job, float global_scale) const { size_t size = 0; switch (job.type) { case kJobAdd: { const Op& op = job.ops[0]; const Image* const image = op.src->image.get(); if (image) { size += EstimateDecompressedImageSize(*image, op.args, global_scale); } break; } case kJobAddSpecToMetal: { const Op& spec_op = job.ops[0]; const Op& diff_op = job.ops[1]; const Image* const spec_image = spec_op.is_constant ? diff_op.src->image.get() : spec_op.src->image.get(); const Image* const diff_image = diff_op.is_constant ? spec_op.src->image.get() : diff_op.src->image.get(); if (spec_image) { size += EstimateDecompressedImageSize(*spec_image, spec_op.args, global_scale); } if (diff_image) { size += EstimateDecompressedImageSize(*diff_image, diff_op.args, global_scale); } break; } default: UFG_ASSERT_LOGIC(false); break; } return size; } float Texturator::ChooseGlobalScale() const { const size_t decompressed_limit = cc_->settings.limit_total_image_decompressed_size; if (decompressed_limit == 0) { return 1.0f; } // Find the first scale for which the decompressed size is not exceeded. const size_t job_count = jobs_.size(); std::vector<size_t> decompressed_sizes(job_count, 0); const float scale_step = cc_->settings.limit_total_image_scale_step; float scale_power = 1.0f; float scale_increment = 1.0f; for (;;) { const float global_scale = scale_power * scale_increment; size_t decompressed_total = 0; bool any_changed = false; for (size_t job_index = 0; job_index != job_count; ++job_index) { const size_t decompressed_size = EstimateDecompressedJobSize(jobs_[job_index], global_scale); decompressed_total += decompressed_size; if (decompressed_sizes[job_index] != decompressed_size) { decompressed_sizes[job_index] = decompressed_size; any_changed = true; } } if (decompressed_total <= decompressed_limit) { break; } if (!any_changed) { Log<UFG_WARN_TEXTURE_LIMIT>( job_count, decompressed_limit, decompressed_total); break; } // Scale linearly down to the minimum, then push that scale and start over. // E.g. with step=0.25: // 1.0, 0.75, 0.50, 0.25, 0.25*0.75, 0.25*0.50, 0.25*0.25, ... if (scale_increment < 1.5f * scale_step) { // Reached the end of the linear sequence. Push the scale and start over. scale_power = global_scale; scale_increment = 1.0f; } scale_increment -= scale_step; } return scale_power * scale_increment; } bool Texturator::PrepareWrite(const std::string& dst_path) { UFG_ASSERT_LOGIC(!dst_path.empty()); if (cc_->gltf_cache.IsSourcePath(dst_path.c_str())) { Log<UFG_ERROR_STOMP>(dst_path.c_str()); return false; } const std::vector<std::string> created_dirs = GltfDiskCreateDirectoryForFile(dst_path); written_.push_back(dst_path); created_dirs_.insert(created_dirs_.end(), created_dirs.begin(), created_dirs.end()); return true; } void Texturator::ProcessAdd(const Op& op) { // Copy the original file to the destination if it doesn't require any // processing. if (op.direct_copy) { UFG_ASSERT(op.pass_mask == 0); if (op.need_copy) { cc_->gltf_cache.CopyImage(op.image_id, op.dst_path); } return; } const uint32_t pass_mask = op.pass_mask; const Args& args = op.args; // Generating new image. Apply conversions. std::unique_ptr<Image> image = CopyImageByUsage(*op.src->image, args.usage, pass_mask); if (pass_mask & kPassMaskFloat) { const UsageInfo& usage_info = kUsageInfos[args.usage]; FloatImage float_image(*image, usage_info.src_rgb_color_space); ApplyFloatPasses(args, pass_mask, op.resize_width, op.resize_height, &float_image); float_image.CopyTo(usage_info.dst_rgb_color_space, &*image); } if (pass_mask & kPassFlagNormalizeNormals) { image->NormalizeNormals(); } if (args.usage == kUsageGlossToRough) { image->Invert(); } if (pass_mask & kPassFlagAlphaCutoff) { image->ApplyAlphaCutoff(Image::FloatToComponent(args.alpha_cutoff)); } Image::Component dst_solid_color[kColorChannelCount]; if (image->AreChannelsSolid(cc_->settings.fix_accidental_alpha, dst_solid_color)) { // Replace solid black occlusion with solid white. if (cc_->settings.black_occlusion_is_white && args.usage == kUsageOccl && dst_solid_color[kColorChannelR] == 0) { dst_solid_color[kColorChannelR] = Image::kComponentMax; } // Shrink solid textures to 1x1 to save space. image->Create1x1(dst_solid_color, image->GetChannelCount()); } const bool is_norm = args.usage == kUsageNorm; if (!image->Write(op.dst_path.c_str(), cc_->settings, cc_->logger, is_norm)) { Log<UFG_ERROR_IO_WRITE_IMAGE>(op.dst_path.c_str()); } } void Texturator::ProcessAddSpecToMetal(const Op& spec_op, const Op& diff_op) { const Args& spec_args = spec_op.args; const bool spec_is_constant = spec_op.is_constant; const Args& diff_args = diff_op.args; const bool diff_is_constant = diff_op.is_constant; // Get specular color in transformed linear space. const uint32_t spec_pass_mask = spec_op.pass_mask; std::unique_ptr<Image> spec_image = spec_is_constant ? WhiteImageByUsage(*diff_op.src->image, spec_args.usage) : CopyImageByUsage(*spec_op.src->image, spec_args.usage, spec_pass_mask); UFG_ASSERT_LOGIC(spec_image->GetChannelCount() == 3); FloatImage spec_float_image(*spec_image, kColorSpaceSrgb); ApplyFloatPasses(spec_args, spec_pass_mask, spec_op.resize_width, spec_op.resize_height, &spec_float_image); // Get diffuse color in transformed linear space. const uint32_t diff_pass_mask = diff_op.pass_mask; std::unique_ptr<Image> diff_image = diff_is_constant ? WhiteImageByUsage(*spec_op.src->image, diff_args.usage) : CopyImageByUsage(*diff_op.src->image, diff_args.usage, diff_pass_mask); FloatImage diff_float_image(*diff_image, kColorSpaceSrgb); ApplyFloatPasses(diff_args, diff_pass_mask, diff_op.resize_width, diff_op.resize_height, &diff_float_image); // Convert specular+diffuse --> metallic+base. FloatImage metal_float_image; FloatImage::ConvertSpecDiffToMetalBase( spec_float_image, &diff_float_image, &metal_float_image); // Write metallic texture. if (spec_op.is_new) { UFG_ASSERT_LOGIC(!spec_op.direct_copy); Image metal_image; // According to the spec, the metallic channel is stored as linear. However, // the SpecGlossVsMetalRough reference sample has metallic values in sRGB, // so the two models do not look quite alike. I'm assuming this is just an // error in the sample, so I'm sticking to the spec. metal_float_image.CopyTo(kColorSpaceLinear, &metal_image); Image::Component metal_dst_solid_color[kColorChannelCount]; if (metal_image.AreChannelsSolid(cc_->settings.fix_accidental_alpha, metal_dst_solid_color)) { metal_image.Create1x1(metal_dst_solid_color, 1); } if (!metal_image.Write( spec_op.dst_path.c_str(), cc_->settings, cc_->logger)) { Log<UFG_ERROR_IO_WRITE_IMAGE>(spec_op.dst_path.c_str()); return; } } // Write base texture. if (diff_op.is_new) { UFG_ASSERT_LOGIC(!diff_op.direct_copy); Image base_image; diff_float_image.CopyTo(kColorSpaceSrgb, &base_image); if (diff_pass_mask & kPassFlagAlphaCutoff) { base_image.ApplyAlphaCutoff( Image::FloatToComponent(diff_args.alpha_cutoff)); } Image::Component base_dst_solid_color[kColorChannelCount]; if (base_image.AreChannelsSolid(cc_->settings.fix_accidental_alpha, base_dst_solid_color)) { base_image.Create1x1(base_dst_solid_color, diff_image->GetChannelCount()); } if (!base_image.Write( diff_op.dst_path.c_str(), cc_->settings, cc_->logger)) { Log<UFG_ERROR_IO_WRITE_IMAGE>(diff_op.dst_path.c_str()); return; } } } void Texturator::ProcessJob(const Job& job) { switch (job.type) { case kJobAdd: ProcessAdd(job.ops[0]); break; case kJobAddSpecToMetal: ProcessAddSpecToMetal(job.ops[0], job.ops[1]); break; default: UFG_ASSERT_LOGIC(false); break; } } } // namespace ufg
35.455492
80
0.67613
[ "vector", "transform", "solid" ]
ecb49820a2cd97c665f124d6fac6eb7137c35341
3,245
cc
C++
codegen/cpp/cerata/src/cerata/parameter.cc
fnonnenmacher/fletcher
fc2098db0b84e5b3d30ad96f1bb9ae6655861811
[ "Apache-2.0" ]
3
2020-04-20T10:48:28.000Z
2022-02-08T00:31:08.000Z
codegen/cpp/cerata/src/cerata/parameter.cc
fnonnenmacher/fletcher
fc2098db0b84e5b3d30ad96f1bb9ae6655861811
[ "Apache-2.0" ]
2
2020-03-30T10:46:22.000Z
2020-07-27T12:34:50.000Z
codegen/cpp/cerata/src/cerata/parameter.cc
fnonnenmacher/fletcher
fc2098db0b84e5b3d30ad96f1bb9ae6655861811
[ "Apache-2.0" ]
1
2022-02-08T00:31:25.000Z
2022-02-08T00:31:25.000Z
// Copyright 2018-2019 Delft University of Technology // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <utility> #include <vector> #include <string> #include <memory> #include "cerata/parameter.h" #include "cerata/pool.h" #include "cerata/graph.h" #include "cerata/edge.h" namespace cerata { Parameter::Parameter(std::string name, const std::shared_ptr<Type> &type, std::shared_ptr<Literal> default_value) : NormalNode(std::move(name), Node::NodeID::PARAMETER, type), default_value_(std::move(default_value)) { if (default_value_ == nullptr) { switch (type->id()) { case Type::ID::STRING: default_value_ = strl(""); break; case Type::ID::BOOLEAN: default_value_ = booll(false); break; case Type::ID::INTEGER: default_value_ = intl(0); break; default:CERATA_LOG(ERROR, "Parameter default value can not be set implicitly."); } } else if (!default_value_->IsLiteral()) { CERATA_LOG(ERROR, "Parameter default value must be literal."); } Connect(this, default_value_); } std::shared_ptr<Parameter> parameter(const std::string &name, const std::shared_ptr<Type> &type, std::shared_ptr<Literal> default_value) { auto p = new Parameter(name, type, std::move(default_value)); return std::shared_ptr<Parameter>(p); } std::shared_ptr<Parameter> parameter(const std::string &name, int default_value) { return parameter(name, integer(), intl(default_value)); } std::shared_ptr<Parameter> parameter(const std::string &name, bool default_value) { return parameter(name, boolean(), booll(default_value)); } std::shared_ptr<Parameter> parameter(const std::string &name, std::string default_value) { return parameter(name, string(), strl(std::move(default_value))); } std::shared_ptr<Parameter> parameter(const std::string &name) { return parameter(name, 0); } Node *Parameter::value() const { if (input()) { return input().value()->src(); } else { CERATA_LOG(FATAL, "Parameter node " + name() + " lost input edge."); } } Parameter *Parameter::SetValue(const std::shared_ptr<Node> &value) { if (value->IsSignal() || value->IsPort()) { CERATA_LOG(FATAL, "Parameter value can not be or refer to signal or port nodes."); } Connect(this, value); return this; } std::shared_ptr<Object> Parameter::Copy() const { auto result = parameter(name(), type_, default_value_); result->meta = this->meta; return result; } void Parameter::TraceValue(std::vector<Node *> *trace) { trace->push_back(this); if (value()->IsParameter()) { value()->AsParameter()->TraceValue(trace); } else { trace->push_back(value()); } } } // namespace cerata
32.128713
113
0.681664
[ "object", "vector" ]
ecb4e62100a2918af127056e3a96c4343205c6ad
4,277
cpp
C++
aws-cpp-sdk-serverlessrepo/source/model/CreateCloudFormationChangeSetRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-serverlessrepo/source/model/CreateCloudFormationChangeSetRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-serverlessrepo/source/model/CreateCloudFormationChangeSetRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/serverlessrepo/model/CreateCloudFormationChangeSetRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ServerlessApplicationRepository::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateCloudFormationChangeSetRequest::CreateCloudFormationChangeSetRequest() : m_applicationIdHasBeenSet(false), m_capabilitiesHasBeenSet(false), m_changeSetNameHasBeenSet(false), m_clientTokenHasBeenSet(false), m_descriptionHasBeenSet(false), m_notificationArnsHasBeenSet(false), m_parameterOverridesHasBeenSet(false), m_resourceTypesHasBeenSet(false), m_rollbackConfigurationHasBeenSet(false), m_semanticVersionHasBeenSet(false), m_stackNameHasBeenSet(false), m_tagsHasBeenSet(false), m_templateIdHasBeenSet(false) { } Aws::String CreateCloudFormationChangeSetRequest::SerializePayload() const { JsonValue payload; if(m_capabilitiesHasBeenSet) { Array<JsonValue> capabilitiesJsonList(m_capabilities.size()); for(unsigned capabilitiesIndex = 0; capabilitiesIndex < capabilitiesJsonList.GetLength(); ++capabilitiesIndex) { capabilitiesJsonList[capabilitiesIndex].AsString(m_capabilities[capabilitiesIndex]); } payload.WithArray("capabilities", std::move(capabilitiesJsonList)); } if(m_changeSetNameHasBeenSet) { payload.WithString("changeSetName", m_changeSetName); } if(m_clientTokenHasBeenSet) { payload.WithString("clientToken", m_clientToken); } if(m_descriptionHasBeenSet) { payload.WithString("description", m_description); } if(m_notificationArnsHasBeenSet) { Array<JsonValue> notificationArnsJsonList(m_notificationArns.size()); for(unsigned notificationArnsIndex = 0; notificationArnsIndex < notificationArnsJsonList.GetLength(); ++notificationArnsIndex) { notificationArnsJsonList[notificationArnsIndex].AsString(m_notificationArns[notificationArnsIndex]); } payload.WithArray("notificationArns", std::move(notificationArnsJsonList)); } if(m_parameterOverridesHasBeenSet) { Array<JsonValue> parameterOverridesJsonList(m_parameterOverrides.size()); for(unsigned parameterOverridesIndex = 0; parameterOverridesIndex < parameterOverridesJsonList.GetLength(); ++parameterOverridesIndex) { parameterOverridesJsonList[parameterOverridesIndex].AsObject(m_parameterOverrides[parameterOverridesIndex].Jsonize()); } payload.WithArray("parameterOverrides", std::move(parameterOverridesJsonList)); } if(m_resourceTypesHasBeenSet) { Array<JsonValue> resourceTypesJsonList(m_resourceTypes.size()); for(unsigned resourceTypesIndex = 0; resourceTypesIndex < resourceTypesJsonList.GetLength(); ++resourceTypesIndex) { resourceTypesJsonList[resourceTypesIndex].AsString(m_resourceTypes[resourceTypesIndex]); } payload.WithArray("resourceTypes", std::move(resourceTypesJsonList)); } if(m_rollbackConfigurationHasBeenSet) { payload.WithObject("rollbackConfiguration", m_rollbackConfiguration.Jsonize()); } if(m_semanticVersionHasBeenSet) { payload.WithString("semanticVersion", m_semanticVersion); } if(m_stackNameHasBeenSet) { payload.WithString("stackName", m_stackName); } if(m_tagsHasBeenSet) { Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("tags", std::move(tagsJsonList)); } if(m_templateIdHasBeenSet) { payload.WithString("templateId", m_templateId); } return payload.View().WriteReadable(); }
28.704698
137
0.768062
[ "model" ]
ecb65b04f620e9f2e5e0c4a0983d7b660ba0fd10
805
cpp
C++
data/train/cpp/ecb65b04f620e9f2e5e0c4a0983d7b660ba0fd1011003.cpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/cpp/ecb65b04f620e9f2e5e0c4a0983d7b660ba0fd1011003.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/cpp/ecb65b04f620e9f2e5e0c4a0983d7b660ba0fd1011003.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#include <iostream> #include <vector> #include <algorithm> using namespace std; static const int MAX_WEIGHT = 3000, MAX_LOAD = 3000; int main() { int N; while (cin >> N, N != 0) { vector<int> W(N + 1), L(N + 1); for (int i = 1; i <= N; ++i) cin >> W[i] >> L[i]; vector<int> dp(MAX_WEIGHT + MAX_LOAD + 1, 0); for (int box = N; box >= 1; --box) { for (int load = L[box]; load >= 0; --load) { if (dp[load]) dp[load + W[box]] = max(dp[load + W[box]], dp[load] + 1); } if (dp[W[box]] == 0) dp[W[box]] = 1; } cout << *max_element(dp.begin(), dp.end()) << endl; } return 0; }
24.393939
62
0.396273
[ "vector" ]
ecc78ed2d1e3371e3b89a9804307219c3aa925dc
3,558
cpp
C++
test/performance.cpp
dsharlet/ndarray
344d75d8af2697a7704a3326751c2d68d9227270
[ "Apache-2.0" ]
148
2019-10-30T18:59:30.000Z
2022-03-30T14:46:05.000Z
test/performance.cpp
ToKiNoBug/array
41beedc5c022486dd26f66b495b995f0af47b836
[ "Apache-2.0" ]
53
2019-11-10T08:12:34.000Z
2022-03-30T05:51:17.000Z
test/performance.cpp
ToKiNoBug/array
41beedc5c022486dd26f66b495b995f0af47b836
[ "Apache-2.0" ]
8
2020-07-25T16:51:36.000Z
2022-02-22T23:52:54.000Z
// Copyright 2019 Google 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 // // https://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 "array.h" #include "test.h" #include <cstring> namespace nda { TEST(performance_dense_copy) { dense_array<int, 3> a({100, 100, 100}, 3); fill_pattern(a); dense_array<int, 3> b(a.shape()); double copy_time = benchmark([&]() { copy(a, b); }); check_pattern(b); dense_array<int, 3> c(b.shape()); double memcpy_time = benchmark( [&] { std::memcpy(&c(0, 0, 0), &a(0, 0, 0), static_cast<size_t>(a.size()) * sizeof(int)); }); check_pattern(c); // copy should be about as fast as memcpy. ASSERT_LT(copy_time, memcpy_time * 1.5); } TEST(performance_dense_cropped_copy) { dense_array<int, 3> a({100, 100, 100}); fill_pattern(a); dense_array<int, 3> b({dense_dim<>(1, 98), dim<>(1, 98), dim<>(1, 98)}); double copy_time = benchmark([&]() { copy(a, b); }); check_pattern(b); dense_array<int, 3> c(b.shape()); double memcpy_time = benchmark([&] { for (int z : c.z()) { for (int y : c.y()) { std::memcpy(&c(c.x().min(), y, z), &a(c.x().min(), y, z), static_cast<size_t>(c.x().extent()) * sizeof(int)); } } }); check_pattern(c); // copy should be about as fast as memcpy. ASSERT_LT(copy_time, memcpy_time * 1.5); } TEST(performance_chunky_cropped_copy) { array_of_rank<int, 3> a({{0, 100, 3}, {0, 100}, {0, 3, 1}}); fill_pattern(a); array_of_rank<int, 3> b({{1, 98, 3}, {1, 98}, {0, 3, 1}}); double copy_time = benchmark([&]() { copy(a, b); }); check_pattern(b); array_of_rank<int, 3> c(b.shape()); double memcpy_time = benchmark([&] { for (int y : c.y()) { std::memcpy(&c(c.x().min(), y, 0), &a(c.x().min(), y, 0), static_cast<size_t>(c.x().extent() * c.c().extent()) * sizeof(int)); } }); check_pattern(c); // copy should be about as fast as memcpy. ASSERT_LT(copy_time, memcpy_time * 1.5); } TEST(performance_copy) { array_of_rank<int, 3> a({dim<>(0, 100, 10000), dim<>(0, 100, 100), dim<>(0, 100, 1)}); fill_pattern(a); array_of_rank<int, 3> b(a.shape()); double copy_time = benchmark([&]() { copy(a, b); }); check_pattern(b); array_of_rank<int, 3> c(b.shape()); double loop_time = benchmark([&] { for (int z : c.z()) { for (int y : c.y()) { for (int x : c.x()) { c(x, y, z) = a(x, y, z); } } } }); check_pattern(c); // copy should be faster than badly ordered loops. ASSERT_LT(copy_time, loop_time * 0.5); } TEST(performance_for_each_value) { array_of_rank<int, 12> a({2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}); double loop_time = benchmark([&]() { for_each_index(a.shape(), [&](const array_of_rank<int, 12>::index_type& i) { a[i] = 3; }); }); assert_used(a); array_of_rank<int, 12> b(a.shape()); double for_each_value_time = benchmark([&]() { b.for_each_value([](int& x) { x = 3; }); }); assert_used(b); // The optimized for_each_value should be much faster. ASSERT_LT(for_each_value_time, loop_time * 0.1); } } // namespace nda
29.163934
99
0.606239
[ "shape" ]
ecc86635b669866a5bcd2a6655c60c0242ca80dd
2,336
hh
C++
neb/inc/com/centreon/delayed_delete.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/delayed_delete.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/delayed_delete.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2012-2013 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #ifndef CC_DELAYED_DELETE_HH # define CC_DELAYED_DELETE_HH # include <cstddef> # include "com/centreon/namespace.hh" CC_BEGIN() /** * @class delayed_delete delayed_delete.hh "com/centreon/delayed_delete.hh" * @brief Perform a delayed delete. * * This template is used to perfom delayed object deletion using a task * manager. The pointer will be deleted when the run() method is * called. If the run() method has not been called when delayed_delete * is destroyed, the pointer won't be deleted. * * @see task_manager */ template <typename T> class delayed_delete : public task { public: /** * Default constructor. * * @param[in] ptr Pointer to delete. */ delayed_delete(T* ptr) : _ptr(ptr) {} /** * Copy constructor. * * @param[in] dd Object to copy. */ delayed_delete(delayed_delete const& dd) : task(dd) { _internal_copy(dd); } /** * Destructor. */ ~delayed_delete() throw () {} /** * Assignment operator. * * @param[in] ptr Pointer to delete. * * @return This object. */ delayed_delete& operator=(delayed_delete const& dd) { if (this != &dd) { task::operator=(dd); _internal_copy(dd); } return (*this); } /** * Delete pointer. */ void run() { delete _ptr; _ptr = NULL; return ; } private: /** * Copy internal data members. * * @param[in] dd Object to copy. */ void _internal_copy(delayed_delete const& dd) { _ptr = dd._ptr; return ; } T* _ptr; }; CC_END() #endif // !CC_DELAYED_DELETE_HH
22.461538
76
0.622432
[ "object" ]
eccc58c3145d13b6990e41f24d7ad2100ab1dfcb
3,567
cpp
C++
src/shogun/structure/MultilabelSOLabels.cpp
srgnuclear/shogun
33c04f77a642416376521b0cd1eed29b3256ac13
[ "Ruby", "MIT" ]
1
2015-11-05T18:31:14.000Z
2015-11-05T18:31:14.000Z
src/shogun/structure/MultilabelSOLabels.cpp
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
src/shogun/structure/MultilabelSOLabels.cpp
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Written (W) 2013 Thoralf Klein * Written (W) 2014 Abinash Panda * Copyright (C) 2013 Thoralf Klein and Zuse-Institute-Berlin (ZIB) * Copyright (C) 2014 Abinash Panda */ #include <shogun/structure/MultilabelSOLabels.h> using namespace shogun; CMultilabelSOLabels::CMultilabelSOLabels() : CStructuredLabels() { init(); m_multilabel_labels = NULL; } CMultilabelSOLabels::CMultilabelSOLabels(int32_t num_classes) : CStructuredLabels() { init(); m_multilabel_labels = new CMultilabelLabels(num_classes); } CMultilabelSOLabels::CMultilabelSOLabels(int32_t num_labels, int32_t num_classes) : CStructuredLabels() { init(); m_multilabel_labels = new CMultilabelLabels(num_labels, num_classes); } CMultilabelSOLabels::CMultilabelSOLabels(CMultilabelLabels * multilabel_labels) : CStructuredLabels() { init(); SG_REF(multilabel_labels); m_multilabel_labels = multilabel_labels; } void CMultilabelSOLabels::init() { SG_ADD((CSGObject **)&m_multilabel_labels, "multilabel_labels", "multilabel labels object", MS_NOT_AVAILABLE); SG_ADD(&m_last_set_label, "last_set_label", "index of the last label added using add_label() method", MS_NOT_AVAILABLE); m_last_set_label = 0; } CMultilabelSOLabels::~CMultilabelSOLabels() { SG_UNREF(m_multilabel_labels); } void CMultilabelSOLabels::set_sparse_label(int32_t j, SGVector<int32_t> label) { if (m_sdt == SDT_UNKNOWN) { m_sdt = SDT_SPARSE_MULTILABEL; } m_multilabel_labels->set_label(j, label); } void CMultilabelSOLabels::set_sparse_labels(SGVector<int32_t> * labels) { if (m_sdt == SDT_UNKNOWN) { m_sdt = SDT_SPARSE_MULTILABEL; } m_multilabel_labels->set_labels(labels); } int32_t CMultilabelSOLabels::get_num_labels() const { if (m_multilabel_labels == NULL) { return 0; } return m_multilabel_labels->get_num_labels(); } int32_t CMultilabelSOLabels::get_num_classes() const { if (m_multilabel_labels == NULL) { return 0; } return m_multilabel_labels->get_num_classes(); } CMultilabelLabels * CMultilabelSOLabels::get_multilabel_labels() { return m_multilabel_labels; } bool CMultilabelSOLabels::set_label(int32_t j, CStructuredData * label) { if (m_sdt == SDT_UNKNOWN) { m_sdt = label->get_structured_data_type(); } CSparseMultilabel * slabel = CSparseMultilabel::obtain_from_generic(label); m_multilabel_labels->set_label(j, slabel->get_data()); return true; } CStructuredData * CMultilabelSOLabels::get_label(int32_t j) { CSparseMultilabel * slabel = new CSparseMultilabel(m_multilabel_labels->get_label(j)); SG_REF(slabel); return (CStructuredData *)slabel; } SGVector<int32_t> CMultilabelSOLabels::get_sparse_label(int32_t j) { return m_multilabel_labels->get_label(j); } void CMultilabelSOLabels::ensure_valid(const char * context) { m_multilabel_labels->ensure_valid(context); } SGVector<float64_t> CMultilabelSOLabels::to_dense(CStructuredData * label, int32_t dense_dim, float64_t d_true, float64_t d_false) { CSparseMultilabel * slabel = CSparseMultilabel::obtain_from_generic(label); SGVector<int32_t> slabel_data = slabel->get_data(); return CMultilabelLabels::to_dense<int32_t, float64_t>(&slabel_data, dense_dim, d_true, d_false); } void CMultilabelSOLabels::add_label(CStructuredData * label) { REQUIRE(m_last_set_label >= 0 && m_last_set_label < get_num_labels(), "Only %d number of labels can be added.\n", get_num_labels()); set_label(m_last_set_label, label); m_last_set_label++; }
24.101351
102
0.762826
[ "object" ]
ecd3aa46539604705c1e5bcf234d13f76d8ccbc6
1,364
cc
C++
jax/codeforces/uncategorized/global-round-15/a_subsequence_permutation.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
2
2022-01-01T16:55:02.000Z
2022-03-16T14:47:29.000Z
jax/codeforces/uncategorized/global-round-15/a_subsequence_permutation.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
null
null
null
jax/codeforces/uncategorized/global-round-15/a_subsequence_permutation.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
null
null
null
// Verbose template for CP // You can create a snippet for this in VS Code #include <iostream> #include <vector> #include <algorithm> using namespace std; using ll = long long; using ull = unsigned long long; using vi = vector<int>; using pi = pair<int, int>; #define REP(i, l, r) for (int i = l; i < r; ++i) #define F first #define S second #define PF push_fornt #define PB push_back #define MP make_pair #define Sort(v) sort(v.begin(), v.end()) #define Unique(v) unique(v.begin(), v.end()) #define Lower(v, val) lower_bound(v.begin(), v.end(), val) #define Upper(v, val) upper_bound(v.begin(), v.end(), val) #define Reverse(v) reverse(v.begin(), v.end()) const char el = '\n'; const int N = 1e6 + 10; template<typename T> void print(T &v) { for (auto val : v) cout << val << ' '; cout << el; } template<typename T> istream &operator>>(istream &in, vector<T> &v) { for (auto &each : v) in >> each; return in; } template<typename T> ostream &operator<<(ostream &out, vector<T> &v) { for (auto &each : v) out << each << ' '; return out; } void solve() { int n; cin >> n; string s; cin >> s; string t = s; sort(s.begin(), s.end()); int ans = 0; REP(i, 0, n) { if (s[i] != t[i]) ++ans; } cout << ans << el; } int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { solve(); } }
20.058824
58
0.60044
[ "vector" ]
ece2519314078eca6df9787057e66c4a69d843c7
1,053
cpp
C++
day9.cpp
Semedi/aoc_2020
30a323c7dcc2dd34a19b6e67bfbb6f9f40f168f9
[ "MIT" ]
null
null
null
day9.cpp
Semedi/aoc_2020
30a323c7dcc2dd34a19b6e67bfbb6f9f40f168f9
[ "MIT" ]
null
null
null
day9.cpp
Semedi/aoc_2020
30a323c7dcc2dd34a19b6e67bfbb6f9f40f168f9
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <vector> #include <numeric> #include <algorithm> using namespace std; int main () { std::ifstream file("input/day9.txt"); std::string str; std::vector<long> v; while (std::getline(file, str)) { v.push_back(atol(str.c_str())); } //part 1 int i; for (i = 25; i < v.size(); ++i){ auto valid = false; for (int a = 0; a < 25; ++a){ for (int b = 0; b < 25; ++b){ valid |= (*(v.begin()+(i-25)+a) + *(v.begin()+(i-25)+b) == v[i]); } } if (!valid){ cout << v[i] << endl; break; } } //part 2 for (int a = 0; a < i; ++a){ for (int b = a+2; b < i; ++b){ auto init = v.begin() + a; auto end = v.begin() + b; if (accumulate(init, end, 0) == v[i]){ cout << "weakness: " << *max_element(init, end) + *min_element(init, end) << endl; } } } return 0; }
21.9375
98
0.430199
[ "vector" ]
ece4213493c22a6aac6443ffc2cdb6eeb68fc522
2,949
cpp
C++
openbr/plugins/metadata/expandrect.cpp
wittayaatt/openbr
26cb128f740f46b7c18b346e2bcf2af7a8de29da
[ "Apache-2.0" ]
1,883
2015-01-04T07:04:24.000Z
2022-03-30T13:33:37.000Z
openbr/plugins/metadata/expandrect.cpp
wittayaatt/openbr
26cb128f740f46b7c18b346e2bcf2af7a8de29da
[ "Apache-2.0" ]
272
2015-01-02T09:53:20.000Z
2022-03-29T08:04:33.000Z
openbr/plugins/metadata/expandrect.cpp
wittayaatt/openbr
26cb128f740f46b7c18b346e2bcf2af7a8de29da
[ "Apache-2.0" ]
718
2015-01-02T18:51:07.000Z
2022-03-29T08:10:53.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 The MITRE Corporation * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <openbr/plugins/openbr_internal.h> namespace br { /*! * \ingroup transforms * \brief Expand the width and height of a Template's rects by input width and height factors. * \author Charles Otto \cite caotto * \author Brendan Klare \cite bklare */ class ExpandRectTransform : public UntrainableTransform { Q_OBJECT Q_PROPERTY(float widthExpand READ get_widthExpand WRITE set_widthExpand RESET reset_widthExpand STORED false) Q_PROPERTY(float heightExpand READ get_heightExpand WRITE set_heightExpand RESET reset_heightExpand STORED false) Q_PROPERTY(QString propName READ get_propName WRITE set_propName RESET reset_propName STORED false) BR_PROPERTY(float, widthExpand, .5) BR_PROPERTY(float, heightExpand, .5) BR_PROPERTY(QString, propName, "") void project(const Template &src, Template &dst) const { dst = src; dst.file.clearRects(); QList<QRectF> rects; if (!propName.isEmpty()) rects.append(src.file.get<QRectF>(propName)); else rects = src.file.rects(); for (int i=0;i < rects.size(); i++) { qreal widthGrowth = rects[i].width() * widthExpand; qreal heightGrowth = rects[i].height() * heightExpand; qreal x = std::max(qreal(0), rects[i].x() - widthGrowth / 2.); qreal y = std::max(qreal(0), rects[i].y() - heightGrowth / 2.); dst.file.appendRect(QRectF(x, y, std::min(src.m().cols - x - 1, rects[i].width() + widthGrowth), std::min(src.m().rows - y - 1, rects[i].height() + heightGrowth))); } } }; BR_REGISTER(Transform, ExpandRectTransform) } // namespace br #include "metadata/expandrect.moc"
43.367647
117
0.535097
[ "transform" ]
ece6850d495866266599268ff8a0a3a70f003abb
2,383
cc
C++
src/dnnl/enlarge_mkl.cc
inordeng/TASO
17a01a7fab21795d8bacfd7ba4f3ba00f11aedf3
[ "Apache-2.0" ]
529
2019-10-01T00:01:08.000Z
2022-03-17T12:56:01.000Z
src/dnnl/enlarge_mkl.cc
inordeng/TASO
17a01a7fab21795d8bacfd7ba4f3ba00f11aedf3
[ "Apache-2.0" ]
68
2019-10-10T18:41:40.000Z
2022-03-17T07:42:49.000Z
src/dnnl/enlarge_mkl.cc
inordeng/TASO
17a01a7fab21795d8bacfd7ba4f3ba00f11aedf3
[ "Apache-2.0" ]
81
2019-10-04T23:48:12.000Z
2022-03-17T13:04:25.000Z
/* Copyright 2020 Stanford, Tsinghua * * 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 "taso/ops.h" #include "taso/dnnl_helper.h" using namespace taso; using namespace dnnl; void enlarge_kernel(DATATYPE* dstPtr, const DATATYPE* srcPtr, int volume, const int dstH, const int dstW, const int srcH, const int srcW) { int offH = (dstH - srcH) / 2; int offW = (dstW - srcW) / 2; #pragma omp parallel for for (int i = 0; i < volume; i++) { int h = (i % (dstH * dstW)) / dstW - offH; int w = (i % (dstH * dstW)) % dstW - offW; if (h < 0 || h >= srcH || w < 0 || w >= srcW) dstPtr[i] = 0.0f; else { int offset = (i / (dstH * dstW)) * (srcH * srcW) + h * srcW + w; dstPtr[i] = srcPtr[offset]; } } } void Enlarge::map(void) { // allocate tensors size_t outputSize = sizeof(DATATYPE) * outputs[0].volume(); CHECK_NE(nullptr, outputs[0].data_ptr = malloc(outputSize)); } void Enlarge::unmap(void) { // clear primitives net.clear(); // free tensors free(outputs[0].data_ptr); outputs[0].data_ptr = nullptr; } void Enlarge::forward(bool block) { enlarge_kernel((DATATYPE*)outputs[0].data_ptr, (DATATYPE*)inputs[0].data_ptr, outputs[0].volume(), outputs[0].dim[2], outputs[0].dim[3], inputs[0].dim[2], inputs[0].dim[3]); } void Model::measure_enlarge_cost(Enlarge* enl) { // measure. uint64_t beg = 0; for (int i = 0; i < WARMUP_TIMES + REPEAT_TIMES; i++) { if (i == WARMUP_TIMES) { beg = microsecond_timer(); } enlarge_kernel(outputPtr, inputPtr, enl->outputs[0].volume(), enl->outputs[0].dim[2], enl->outputs[0].dim[3], enl->inputs[0].dim[2], enl->inputs[0].dim[3]); } auto end = microsecond_timer(); enl->runtime = (end - beg) / 1.e3 / REPEAT_TIMES; // milliseconds if (print_cost) printf(" measure[Enlarge]: cost(%.4lf)\n", enl->runtime); }
30.164557
100
0.644985
[ "model" ]
eced1cb5789162b73602988c0e67f167ee5a1a05
3,131
hpp
C++
include/gamelib/utils/conversions.hpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
1
2020-02-17T09:53:36.000Z
2020-02-17T09:53:36.000Z
include/gamelib/utils/conversions.hpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
null
null
null
include/gamelib/utils/conversions.hpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
null
null
null
#ifndef GAMELIB_CONVERSIONS_HPP #define GAMELIB_CONVERSIONS_HPP #include <SFML/System/Vector2.hpp> #include <SFML/Graphics/Rect.hpp> #include "math/geometry/Vector.hpp" #include "math/geometry/AABB.hpp" namespace gamelib { template <class T> math::Vec2<T>& convert(sf::Vector2<T>& vec) { return *reinterpret_cast<math::Vec2<T>*>(&vec); } template <class T> const math::Vec2<T>& convert(const sf::Vector2<T>& vec) { return *reinterpret_cast<const math::Vec2<T>*>(&vec); } template <class T> sf::Vector2<T>& convert(math::Vec2<T>& vec) { return *reinterpret_cast<sf::Vector2<T>*>(&vec); } template <class T> const sf::Vector2<T>& convert(const math::Vec2<T>& vec) { return *reinterpret_cast<const sf::Vector2<T>*>(&vec); } template <class T> sf::Vector2<T>& convert(math::Point2<T>& vec) { return convert(vec.asVector()); } template <class T> const sf::Vector2<T>& convert(const math::Point2<T>& vec) { return convert(vec.asVector()); } template <class T> math::AABB<T>& convert(sf::Rect<T>& rect) { return *reinterpret_cast<math::AABB<T>*>(&rect); } template <class T> const math::AABB<T>& convert(const sf::Rect<T>& rect) { return *reinterpret_cast<const math::AABB<T>*>(&rect); } template <class T> sf::Rect<T>& convert(math::AABB<T>& rect) { return *reinterpret_cast<sf::Rect<T>*>(&rect); } template <class T> const sf::Rect<T>& convert(const math::AABB<T>& rect) { return *reinterpret_cast<const sf::Rect<T>*>(&rect); } // template <class T> // math::Vec2<T> convert(const sf::Vector2<T>& vec) // { // return math::Vec2<T>(vec.x, vec.y); // } // // template <class T> // math::AABB<T> convert(const sf::Rect<T>& rect) // { // return math::AABB<T>(rect.left, rect.top, rect.width, rect.height); // } // // template <class T> // sf::Vector2<T> convert(const math::Vec2<T>& vec) // { // return sf::Vector2<T>(vec.x, vec.y); // } // // template <class T> // sf::Vector2<T> convert(const math::Point2<T>& p) // { // return convert(p.asVector()); // } // // template <class T> // sf::Rect<T> convert(const math::AABB<T>& rect) // { // return sf::Rect<T>(rect.pos.x, rect.pos.y, rect.size.x, rect.size.y); // } template <typename T> sf::Vector2<T> operator*(const sf::Vector2<T>& a, const math::Vec2<T>& b) { return interpret(interpret(a) * b); } template <typename T> sf::Vector2<T> operator/(const sf::Vector2<T>& a, const math::Vec2<T>& b) { return interpret(interpret(a) / b); } template <typename T> sf::Vector2<T> operator*(const sf::Vector2<T>& a, const sf::Vector2<T>& b) { return a * interpret(b); } template <typename T> sf::Vector2<T> operator/(const sf::Vector2<T>& a, const sf::Vector2<T>& b) { return a / interpret(b); } } #endif
24.271318
80
0.561163
[ "geometry", "vector" ]
eceed06e0fb574fbaa2130cb56bf88f434b812c3
3,929
hxx
C++
opencascade/Message_Printer.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
37
2020-01-20T21:50:21.000Z
2022-02-09T13:01:09.000Z
opencascade/Message_Printer.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/Message_Printer.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
22
2020-04-03T21:59:52.000Z
2022-03-06T18:43:35.000Z
// Created on: 2001-01-06 // Created by: OCC Team // Copyright (c) 2001-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Message_Printer_HeaderFile #define _Message_Printer_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Message_Gravity.hxx> #include <Standard_Transient.hxx> #include <Standard_Boolean.hxx> #include <Standard_CString.hxx> #include <Standard_SStream.hxx> class TCollection_ExtendedString; class TCollection_AsciiString; class Message_Printer; DEFINE_STANDARD_HANDLE(Message_Printer, Standard_Transient) //! Abstract interface class defining printer as output context for text messages //! //! The message, besides being text string, has associated gravity //! level, which can be used by printer to decide either to process a message or ignore it. class Message_Printer : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Message_Printer, Standard_Transient) public: //! Return trace level used for filtering messages; //! messages with lover gravity will be ignored. Message_Gravity GetTraceLevel() const { return myTraceLevel; } //! Set trace level used for filtering messages. //! By default, trace level is Message_Info, so that all messages are output void SetTraceLevel (const Message_Gravity theTraceLevel) { myTraceLevel = theTraceLevel; } //! Send a string message with specified trace level. //! The last Boolean argument is deprecated and unused. //! Default implementation redirects to send(). Standard_EXPORT virtual void Send (const TCollection_ExtendedString& theString, const Message_Gravity theGravity) const; //! Send a string message with specified trace level. //! The last Boolean argument is deprecated and unused. //! Default implementation redirects to send(). Standard_EXPORT virtual void Send (const Standard_CString theString, const Message_Gravity theGravity) const; //! Send a string message with specified trace level. //! The last Boolean argument is deprecated and unused. //! Default implementation redirects to send(). Standard_EXPORT virtual void Send (const TCollection_AsciiString& theString, const Message_Gravity theGravity) const; //! Send a string message with specified trace level. //! Stream is converted to string value. //! Default implementation calls first method Send(). Standard_EXPORT virtual void SendStringStream (const Standard_SStream& theStream, const Message_Gravity theGravity) const; //! Send a string message with specified trace level. //! The object is converted to string in format: <object kind> : <object pointer>. //! Default implementation calls first method Send(). Standard_EXPORT virtual void SendObject (const Handle(Standard_Transient)& theObject, const Message_Gravity theGravity) const; protected: //! Empty constructor with Message_Info trace level Standard_EXPORT Message_Printer(); //! Send a string message with specified trace level. //! This method must be redefined in descendant. Standard_EXPORT virtual void send (const TCollection_AsciiString& theString, const Message_Gravity theGravity) const = 0; protected: Message_Gravity myTraceLevel; }; #endif // _Message_Printer_HeaderFile
40.505155
128
0.753118
[ "object" ]
ecf5c5451afb998fdef492852c77c6a5bed84709
3,764
cpp
C++
Source/wali/lib/graph/Functional.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
null
null
null
Source/wali/lib/graph/Functional.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
null
null
null
Source/wali/lib/graph/Functional.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
null
null
null
#include "wali/graph/Functional.hpp" #include "wali/graph/IntraGraph.hpp" #include "llvm/Support/ErrorHandling.h" #include <boost/cast.hpp> using namespace wali; using namespace std; using namespace wali::graph; SemElemFunctional::SemElemFunctional() : type(TRASH), lhs(NULL), rhs(NULL), value(NULL), intra_nodeno(-1) {} SemElemFunctional::SemElemFunctional(sem_elem_tensor_t wt) : type(Constant), lhs(NULL), rhs(NULL), value(wt), intra_nodeno(-1) {} SemElemFunctional::SemElemFunctional(int n) : type(In), lhs(NULL), rhs(NULL), value(NULL), intra_nodeno(n) {} functional_t SemElemFunctional::constant(sem_elem_tensor_t wt) { return new SemElemFunctional(wt); } functional_t SemElemFunctional::in(int n) { return new SemElemFunctional(n); } functional_t SemElemFunctional::extend(functional_t lhs, functional_t rhs) { functional_t res = new SemElemFunctional(); res->type = Extend; res->lhs = lhs; res->rhs = rhs; return res; } functional_t SemElemFunctional::combine(functional_t lhs, functional_t rhs) { functional_t res = new SemElemFunctional(); res->type = Combine; res->lhs = lhs; res->rhs = rhs; return res; } functional_t SemElemFunctional::tensor(functional_t lhs, functional_t rhs) { functional_t res = new SemElemFunctional(); res->type = Tensor; res->lhs = lhs; res->rhs = rhs; return res; } functional_t SemElemFunctional::detensor(functional_t arg) { functional_t res = new SemElemFunctional(); res->type = Detensor; res->lhs = arg; return res; } functional_t SemElemFunctional::detensorTranspose(functional_t arg) { functional_t res = new SemElemFunctional(); res->type = DetensorTranspose; res->lhs = arg; return res; } functional_t SemElemFunctional::transpose(functional_t arg) { functional_t res = new SemElemFunctional(); res->type = Transpose; res->lhs = arg; return res; } sem_elem_tensor_t SemElemFunctional::evaluate(IntraGraph * const gr) { sem_elem_tensor_t lval, rval, val; switch(type){ case Constant: return value; case In: return boost::polymorphic_downcast<SemElemTensor*>(gr->getWeight(intra_nodeno).get_ptr()); case Extend: lval = lhs->evaluate(gr); rval = rhs->evaluate(gr); return boost::polymorphic_downcast<SemElemTensor*>(lval->extend(rval.get_ptr()).get_ptr()); case Combine: lval = lhs->evaluate(gr); rval = rhs->evaluate(gr); return boost::polymorphic_downcast<SemElemTensor*>(lval->combine(rval.get_ptr()).get_ptr()); case Tensor: lval = lhs->evaluate(gr); rval = rhs->evaluate(gr); return boost::polymorphic_downcast<SemElemTensor*>(lval->tensor(rval.get_ptr()).get_ptr()); case Detensor: val = lhs->evaluate(gr); return boost::polymorphic_downcast<SemElemTensor*>(val->detensor().get_ptr()); case DetensorTranspose: val = lhs->evaluate(gr); return boost::polymorphic_downcast<SemElemTensor*>(val->detensorTranspose().get_ptr()); case Transpose: val = lhs->evaluate(gr); return boost::polymorphic_downcast<SemElemTensor*>(val->transpose().get_ptr()); default: llvm_unreachable("[SemElemFunctiona::evaluate] Unknown case\n"); } } void SemElemFunctional::leafNodes(std::vector<int>& leaves) { std::vector<int> ret; switch(type){ case Constant: break; case In: leaves.push_back(intra_nodeno); break; case Extend: case Combine: case Tensor: lhs->leafNodes(leaves); rhs->leafNodes(leaves); break; case Detensor: case DetensorTranspose: case Transpose: lhs->leafNodes(leaves); break; default: assert(false && "[SemElemFunctiona::evaluate] Unknown case\n"); } }
24.128205
98
0.689426
[ "vector" ]
ecf734ee9077eab4f4f7d7b7a3b816792292bc63
5,543
cpp
C++
indra/test/llhttpdate_tut.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/test/llhttpdate_tut.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
null
null
null
indra/test/llhttpdate_tut.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llhttpdate_tut.cpp * @author Kartic Krishnamurthy * @date Wednesday, 18 Jul 2007 17:00:00 GMT :) * * $LicenseInfo:firstyear=2007&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "lltut.h" #include "lldate.h" #include "llcommon.h" #include "llframetimer.h" #include <time.h> #include <locale.h> namespace tut { struct httpdate_data { httpdate_data() { } ~httpdate_data() { } LLDate some_date; }; typedef test_group<httpdate_data> httpdate_test; typedef httpdate_test::object httpdate_object; tut::httpdate_test httpdate("httpdate"); template<> template<> void httpdate_object::test<1>() { static std::string epoch_expected = "Thursday, 01 Jan 1970 00:00:00 GMT" ; ensure("Check Epoch in RFC 1123", ( epoch_expected == some_date.asRFC1123())); } template<> template<> void httpdate_object::test<2>() { static std::string expected = "Wednesday, 18 Jul 2007 22:17:24 GMT" ; some_date = LLDate(1184797044.037586); ensure("Check some timestamp in RFC 1123", ( expected == some_date.asRFC1123())); } // This test of course most generic.. runs off current time template<> template<> void httpdate_object::test<3>() { //F64 sometime = LLFrameTimer::getTotalSeconds(); time_t sometime; time(&sometime); some_date = LLDate((F64) sometime); struct tm *result; char expected[255]; std::string actual; result = gmtime(&sometime); /* std::cout << " seconds: "<< result->tm_sec << ", minutes: " << result->tm_min << ", hours: " << result->tm_hour << ", day of the month: " << result->tm_mday << ", month: " << result->tm_mon << ", year: " << result->tm_year << ", day of the week: " << result->tm_wday << ", day in the year: " << result->tm_yday << ", DST: " << result->tm_isdst << std::endl; */ strftime(expected, 255, "%A, %d %b %Y %H:%M:%S GMT", result); actual = some_date.asRFC1123(); // probably not a good idea to use strcmp but this is just a unit test ensure("Current time in RFC 1123", (strcmp(expected, actual.c_str()) == 0)); } void test_date_string(const std::string &locale, struct tm *t, const std::string &fmt, const std::string &expected) { std::string result = LLDate::toHTTPDateString(t, fmt); LLStringUtil::toLower(result); std::string label = std::string("toHTTPDateString - ") + locale; ensure_equals(label.c_str(), result, expected); } template<> template<> void httpdate_object::test<4>() { // test localization of http dates #if LL_WINDOWS const char *en_locale = "english"; const char *fr_locale = "french"; #else const char *en_locale = "en_GB.UTF-8"; const char *fr_locale = "fr_FR.UTF-8"; #endif std::string prev_locale = LLStringUtil::getLocale(); std::string prev_clocale = std::string(setlocale(LC_TIME, NULL)); time_t test_time = 1252374030; // 8 Sep 2009 01:40:01 struct tm *t = gmtime(&test_time); setlocale(LC_TIME, en_locale); if (strcmp(setlocale(LC_TIME, NULL), en_locale) != 0) { setlocale(LC_TIME, prev_clocale.c_str()); skip("Cannot set English locale"); } LLStringUtil::setLocale(en_locale); test_date_string(en_locale, t, "%d %B %Y - %H:%M", "08 september 2009 - 01:40"); test_date_string(en_locale, t, "%H", "01"); test_date_string(en_locale, t, "%M", "40"); test_date_string(en_locale, t, "%I", "01"); test_date_string(en_locale, t, "%d", "08"); test_date_string(en_locale, t, "%Y", "2009"); test_date_string(en_locale, t, "%p", "am"); test_date_string(en_locale, t, "%A", "tuesday"); test_date_string(en_locale, t, "%B", "september"); setlocale(LC_TIME, fr_locale); if (strcmp(setlocale(LC_TIME, NULL), fr_locale) != 0) { LLStringUtil::setLocale(prev_locale); setlocale(LC_TIME, prev_clocale.c_str()); skip("Cannot set French locale"); } LLStringUtil::setLocale(fr_locale); test_date_string(fr_locale, t, "%d %B %Y - %H:%M", "08 septembre 2009 - 01:40"); test_date_string(fr_locale, t, "%H", "01"); test_date_string(fr_locale, t, "%M", "40"); test_date_string(fr_locale, t, "%I", "01"); test_date_string(fr_locale, t, "%d", "08"); test_date_string(fr_locale, t, "%Y", "2009"); test_date_string(fr_locale, t, "%A", "mardi"); test_date_string(fr_locale, t, "%B", "septembre"); LLStringUtil::setLocale(prev_locale); setlocale(LC_TIME, prev_clocale.c_str()); } }
32.994048
89
0.639365
[ "object" ]
ecfaa25dcf3a53213d623d01d31bab322ac0f7a9
982
cpp
C++
android-31/android/service/carrier/MessagePdu.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/service/carrier/MessagePdu.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/service/carrier/MessagePdu.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../os/Parcel.hpp" #include "./MessagePdu.hpp" namespace android::service::carrier { // Fields JObject MessagePdu::CREATOR() { return getStaticObjectField( "android.service.carrier.MessagePdu", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } // QJniObject forward MessagePdu::MessagePdu(QJniObject obj) : JObject(obj) {} // Constructors MessagePdu::MessagePdu(JObject arg0) : JObject( "android.service.carrier.MessagePdu", "(Ljava/util/List;)V", arg0.object() ) {} // Methods jint MessagePdu::describeContents() const { return callMethod<jint>( "describeContents", "()I" ); } JObject MessagePdu::getPdus() const { return callObjectMethod( "getPdus", "()Ljava/util/List;" ); } void MessagePdu::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::service::carrier
18.528302
74
0.663951
[ "object" ]
ecfc49e33d372fdc0e6432ad0bd2af589cd39845
5,026
cpp
C++
modules/ocl/perf/perf_split_merge.cpp
Nerei/opencv
92d5f8744c872ccf63b17334f018343973353e47
[ "BSD-3-Clause" ]
1
2015-04-22T14:10:46.000Z
2015-04-22T14:10:46.000Z
modules/ocl/perf/perf_split_merge.cpp
ameydhar/opencv
1c3bfae2121f689535ab1a17284f40f5d64e0927
[ "BSD-3-Clause" ]
null
null
null
modules/ocl/perf/perf_split_merge.cpp
ameydhar/opencv
1c3bfae2121f689535ab1a17284f40f5d64e0927
[ "BSD-3-Clause" ]
2
2018-05-03T21:08:19.000Z
2020-09-26T06:27:08.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // @Authors // Fangfang Bai, fangfang@multicorewareinc.com // Jin Ma, jin@multicorewareinc.com // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors as is and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "perf_precomp.hpp" using namespace perf; using std::tr1::tuple; using std::tr1::get; ///////////// Merge//////////////////////// typedef Size_MatType MergeFixture; PERF_TEST_P(MergeFixture, Merge, ::testing::Combine(::testing::Values(OCL_SIZE_1000, OCL_SIZE_2000), OCL_PERF_ENUM(CV_8U, CV_32F))) { const Size_MatType_t params = GetParam(); const Size srcSize = get<0>(params); const int depth = get<1>(params), channels = 3; const int dstType = CV_MAKE_TYPE(depth, channels); checkDeviceMaxMemoryAllocSize(srcSize, dstType); Mat dst(srcSize, dstType); vector<Mat> src(channels); for (vector<Mat>::iterator i = src.begin(), end = src.end(); i != end; ++i) { i->create(srcSize, CV_MAKE_TYPE(depth, 1)); declare.in(*i, WARMUP_RNG); } declare.out(dst); if (RUN_OCL_IMPL) { ocl::oclMat oclDst(srcSize, dstType); vector<ocl::oclMat> oclSrc(src.size()); for (vector<ocl::oclMat>::size_type i = 0, end = src.size(); i < end; ++i) oclSrc[i] = src[i]; OCL_TEST_CYCLE() cv::ocl::merge(oclSrc, oclDst); oclDst.download(dst); SANITY_CHECK(dst); } else if (RUN_PLAIN_IMPL) { TEST_CYCLE() cv::merge(src, dst); SANITY_CHECK(dst); } else OCL_PERF_ELSE } ///////////// Split//////////////////////// typedef Size_MatType SplitFixture; PERF_TEST_P(SplitFixture, Split, ::testing::Combine(OCL_TYPICAL_MAT_SIZES, OCL_PERF_ENUM(CV_8U, CV_32F))) { const Size_MatType_t params = GetParam(); const Size srcSize = get<0>(params); const int depth = get<1>(params), channels = 3; const int type = CV_MAKE_TYPE(depth, channels); checkDeviceMaxMemoryAllocSize(srcSize, type); Mat src(srcSize, type); declare.in(src, WARMUP_RNG); if (RUN_OCL_IMPL) { ocl::oclMat oclSrc(src); vector<ocl::oclMat> oclDst(channels, ocl::oclMat(srcSize, CV_MAKE_TYPE(depth, 1))); OCL_TEST_CYCLE() cv::ocl::split(oclSrc, oclDst); ASSERT_EQ(3, channels); Mat dst0, dst1, dst2; oclDst[0].download(dst0); oclDst[1].download(dst1); oclDst[2].download(dst2); SANITY_CHECK(dst0); SANITY_CHECK(dst1); SANITY_CHECK(dst2); } else if (RUN_PLAIN_IMPL) { vector<Mat> dst(channels, Mat(srcSize, CV_MAKE_TYPE(depth, 1))); TEST_CYCLE() cv::split(src, dst); ASSERT_EQ(3, channels); Mat & dst0 = dst[0], & dst1 = dst[1], & dst2 = dst[2]; SANITY_CHECK(dst0); SANITY_CHECK(dst1); SANITY_CHECK(dst2); } else OCL_PERF_ELSE }
34.190476
91
0.640072
[ "vector" ]
a605297a9c8918931e3dd54e375510a98f1ee852
3,787
hxx
C++
opencascade/BRepAlgo_Image.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
37
2020-01-20T21:50:21.000Z
2022-02-09T13:01:09.000Z
opencascade/BRepAlgo_Image.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/BRepAlgo_Image.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
22
2020-04-03T21:59:52.000Z
2022-03-06T18:43:35.000Z
// Created on: 1995-10-26 // Created by: Yves FRICAUD // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepAlgo_Image_HeaderFile #define _BRepAlgo_Image_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopTools_ListOfShape.hxx> #include <TopTools_DataMapOfShapeShape.hxx> #include <TopTools_DataMapOfShapeListOfShape.hxx> #include <Standard_Boolean.hxx> #include <TopAbs_ShapeEnum.hxx> class Standard_ConstructionError; class TopoDS_Shape; //! Stores link between a shape <S> and a shape <NewS> //! obtained from <S>. <NewS> is an image of <S>. class BRepAlgo_Image { public: DEFINE_STANDARD_ALLOC Standard_EXPORT BRepAlgo_Image(); Standard_EXPORT void SetRoot (const TopoDS_Shape& S); //! Links <NewS> as image of <OldS>. Standard_EXPORT void Bind (const TopoDS_Shape& OldS, const TopoDS_Shape& NewS); //! Links <NewS> as image of <OldS>. Standard_EXPORT void Bind (const TopoDS_Shape& OldS, const TopTools_ListOfShape& NewS); //! Add <NewS> to the image of <OldS>. Standard_EXPORT void Add (const TopoDS_Shape& OldS, const TopoDS_Shape& NewS); //! Add <NewS> to the image of <OldS>. Standard_EXPORT void Add (const TopoDS_Shape& OldS, const TopTools_ListOfShape& NewS); Standard_EXPORT void Clear(); //! Remove <S> to set of images. Standard_EXPORT void Remove (const TopoDS_Shape& S); //! Removes the root <theRoot> from the list of roots and up and down maps. Standard_EXPORT void RemoveRoot (const TopoDS_Shape& Root); //! Replaces the <OldRoot> with the <NewRoot>, so all images //! of the <OldRoot> become the images of the <NewRoot>. //! The <OldRoot> is removed. Standard_EXPORT void ReplaceRoot (const TopoDS_Shape& OldRoot, const TopoDS_Shape& NewRoot); Standard_EXPORT const TopTools_ListOfShape& Roots() const; Standard_EXPORT Standard_Boolean IsImage (const TopoDS_Shape& S) const; //! Returns the generator of <S> Standard_EXPORT const TopoDS_Shape& ImageFrom (const TopoDS_Shape& S) const; //! Returns the upper generator of <S> Standard_EXPORT const TopoDS_Shape& Root (const TopoDS_Shape& S) const; Standard_EXPORT Standard_Boolean HasImage (const TopoDS_Shape& S) const; //! Returns the Image of <S>. //! Returns <S> in the list if HasImage(S) is false. Standard_EXPORT const TopTools_ListOfShape& Image (const TopoDS_Shape& S) const; //! Stores in <L> the images of images of...images of <S>. //! <L> contains only <S> if HasImage(S) is false. Standard_EXPORT void LastImage (const TopoDS_Shape& S, TopTools_ListOfShape& L) const; //! Keeps only the link between roots and lastimage. Standard_EXPORT void Compact(); //! Deletes in the images the shape of type <ShapeType> //! which are not in <S>. //! Warning: Compact() must be call before. Standard_EXPORT void Filter (const TopoDS_Shape& S, const TopAbs_ShapeEnum ShapeType); protected: private: TopTools_ListOfShape roots; TopTools_DataMapOfShapeShape up; TopTools_DataMapOfShapeListOfShape down; }; #endif // _BRepAlgo_Image_HeaderFile
30.055556
94
0.742012
[ "shape" ]
a60769979b8c66653caad5c79391a7971cc0a0e2
4,106
cpp
C++
qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/gui/listbox.cpp
largeriver/twrp
767b63ed5e0763538466569984cf7930d9c59921
[ "MIT" ]
null
null
null
qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/gui/listbox.cpp
largeriver/twrp
767b63ed5e0763538466569984cf7930d9c59921
[ "MIT" ]
null
null
null
qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/gui/listbox.cpp
largeriver/twrp
767b63ed5e0763538466569984cf7930d9c59921
[ "MIT" ]
null
null
null
/* Copyright 2013 bigbiff/Dees_Troy TeamWin This file is part of TWRP/TeamWin Recovery Project. TWRP 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. TWRP 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 TWRP. If not, see <http://www.gnu.org/licenses/>. */ #include <string.h> #include <sys/stat.h> #include <dirent.h> extern "C" { #include "../twcommon.h" #include "../minuitwrp/minui.h" } #include "rapidxml.hpp" #include "objects.hpp" #include "../data.hpp" GUIListBox::GUIListBox(xml_node<>* node) : GUIScrollList(node) { xml_attribute<>* attr; xml_node<>* child; mIconSelected = mIconUnselected = NULL; mUpdate = 0; // Get the icons, if any child = FindNode(node, "icon"); if (child) { mIconSelected = LoadAttrImage(child, "selected"); mIconUnselected = LoadAttrImage(child, "unselected"); } int iconWidth = std::max(mIconSelected->GetWidth(), mIconUnselected->GetWidth()); int iconHeight = std::max(mIconSelected->GetHeight(), mIconUnselected->GetHeight()); SetMaxIconSize(iconWidth, iconHeight); // Handle the result variable child = FindNode(node, "data"); if (child) { attr = child->first_attribute("name"); if (attr) mVariable = attr->value(); attr = child->first_attribute("default"); if (attr) DataManager::SetValue(mVariable, attr->value()); // Get the currently selected value for the list DataManager::GetValue(mVariable, currentValue); } // Get the data for the list child = FindNode(node, "listitem"); if (!child) return; while (child) { ListData data; attr = child->first_attribute("name"); if (!attr) return; data.displayName = attr->value(); data.variableValue = child->value(); if (child->value() == currentValue) { data.selected = 1; } else { data.selected = 0; } mList.push_back(data); child = child->next_sibling("listitem"); } } GUIListBox::~GUIListBox() { } int GUIListBox::Update(void) { if(!isConditionTrue()) return 0; GUIScrollList::Update(); if (mUpdate) { mUpdate = 0; if (Render() == 0) return 2; } return 0; } int GUIListBox::NotifyVarChange(const std::string& varName, const std::string& value) { GUIScrollList::NotifyVarChange(varName, value); if(!isConditionTrue()) return 0; // Check to see if the variable that we are using to store the list selected value has been updated if (varName == mVariable) { int i, listSize = mList.size(); currentValue = value; for (i = 0; i < listSize; i++) { if (mList.at(i).variableValue == currentValue) { mList.at(i).selected = 1; SetVisibleListLocation(i); } else mList.at(i).selected = 0; } mUpdate = 1; return 0; } return 0; } void GUIListBox::SetPageFocus(int inFocus) { GUIScrollList::SetPageFocus(inFocus); if (inFocus) { DataManager::GetValue(mVariable, currentValue); NotifyVarChange(mVariable, currentValue); } } size_t GUIListBox::GetItemCount() { return mList.size(); } void GUIListBox::RenderItem(size_t itemindex, int yPos, bool selected) { // note: the "selected" parameter above is for the currently touched item // don't confuse it with the more persistent "selected" flag per list item used below ImageResource* icon = mList.at(itemindex).selected ? mIconSelected : mIconUnselected; const std::string& text = mList.at(itemindex).displayName; RenderStdItem(yPos, selected, icon, text.c_str()); } void GUIListBox::NotifySelect(size_t item_selected) { for (size_t i = 0; i < mList.size(); i++) { mList.at(i).selected = 0; } if (item_selected < mList.size()) { mList.at(item_selected).selected = 1; string str = mList.at(item_selected).variableValue; DataManager::SetValue(mVariable, str); } mUpdate = 1; }
24.73494
100
0.70263
[ "render" ]
a608079fc8f5a8019d9be1952aff248c4b3314c8
8,067
tcc
C++
libelement/dependencies/memorypool/MemoryPool.tcc
HarryMills-UL/Element
83e4e99cef42172f54bf7e839b37e40a4e25a6cb
[ "Apache-2.0" ]
12
2019-12-17T18:27:04.000Z
2021-06-04T08:46:05.000Z
libelement/dependencies/memorypool/MemoryPool.tcc
HarryMills-UL/Element
83e4e99cef42172f54bf7e839b37e40a4e25a6cb
[ "Apache-2.0" ]
12
2020-10-27T14:30:37.000Z
2022-01-05T16:50:53.000Z
libelement/dependencies/memorypool/MemoryPool.tcc
HarryMills-UL/Element
83e4e99cef42172f54bf7e839b37e40a4e25a6cb
[ "Apache-2.0" ]
6
2020-01-10T23:45:48.000Z
2021-07-01T22:58:01.000Z
/*- * Copyright (c) 2013 Cosku Acay, http://www.coskuacay.com * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef MEMORY_BLOCK_TCC #define MEMORY_BLOCK_TCC template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::size_type MemoryPool<T, BlockSize>::padPointer(data_pointer_ p, size_type align) const noexcept { uintptr_t result = reinterpret_cast<uintptr_t>(p); return ((align - result) % align); } template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::MemoryPool() noexcept { currentBlock_ = nullptr; currentAndLastSlots_.store({nullptr, nullptr}); freeSlots_.store(nullptr); } template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::MemoryPool(const MemoryPool& memoryPool) noexcept : MemoryPool() {} template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::MemoryPool(MemoryPool&& memoryPool) noexcept { currentBlock_ = memoryPool.currentBlock_; memoryPool.currentBlock_ = nullptr; currentAndLastSlots_.store(memoryPool.currentAndLastSlots_.load()); freeSlots_.store(memoryPool.freeSlots_.load()); } template <typename T, size_t BlockSize> template<class U> MemoryPool<T, BlockSize>::MemoryPool(const MemoryPool<U>& memoryPool) noexcept : MemoryPool() {} template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>& MemoryPool<T, BlockSize>::operator=(MemoryPool&& memoryPool) noexcept { if (this != &memoryPool) { std::swap(currentBlock_, memoryPool.currentBlock_); currentAndLastSlots_.store(memoryPool.currentAndLastSlots_.load()); freeSlots_.store(memoryPool.freeSlots_.load()); } return *this; } template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::~MemoryPool() noexcept { std::lock_guard<std::mutex> lock(blockAllocMutex_); slot_pointer_ curr = currentBlock_; while (curr != nullptr) { slot_pointer_ prev = curr->next; operator delete(reinterpret_cast<void*>(curr)); curr = prev; } } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::pointer MemoryPool<T, BlockSize>::address(reference x) const noexcept { return &x; } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::const_pointer MemoryPool<T, BlockSize>::address(const_reference x) const noexcept { return &x; } template <typename T, size_t BlockSize> void MemoryPool<T, BlockSize>::allocateBlock(slot_pointer_ currentLastSlot) { std::lock_guard<std::mutex> lock(blockAllocMutex_); // Now we are locked, check if our last slot is still the same (i.e. we haven't allocated a new block) // If it is different, we've hit this twice in succession and a new block has already been allocated // When this happens, bomb back out to allocate; this iteration will inevitably fail, but it can try again if (currentAndLastSlots_.load().last != currentLastSlot) return; // Allocate space for the new block and store a pointer to the previous one data_pointer_ newBlock = reinterpret_cast<data_pointer_> (operator new(BlockSize)); reinterpret_cast<slot_pointer_>(newBlock)->next = currentBlock_; currentBlock_ = reinterpret_cast<slot_pointer_>(newBlock); // Pad block body to staisfy the alignment requirements for elements data_pointer_ body = newBlock + sizeof(slot_pointer_); size_type bodyPadding = padPointer(body, alignof(slot_type_)); // Now store the new block into the current slot info currentAndLastSlots_.store({ reinterpret_cast<slot_pointer_>(body + bodyPadding), reinterpret_cast<slot_pointer_>(newBlock + BlockSize - sizeof(slot_type_) + 1)}); } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::pointer MemoryPool<T, BlockSize>::allocate(size_type n, const_pointer hint) { slot_pointer_ lFreeSlots = freeSlots_.load(); while (lFreeSlots != nullptr) { // If true, we successfully updated freeSlots_ and can return our new object // If false, we failed to update, but the current value of freeSlots_ is now in lFreeSlots // So, iterate until we succeed or run out of free slots if (freeSlots_.compare_exchange_weak(lFreeSlots, lFreeSlots->next)) return reinterpret_cast<pointer>(lFreeSlots); } // Get the current and last slots and see if we're out of space slot_pair_ lCurrentAndLast = currentAndLastSlots_.load(); for(;;) { // If we're out of available slots, attempt to allocate a new block // Note that this may fail (if another thread has already done it) // In this case we continue, knowing that the compare/exchange will fail // This will still result in lCurrentAndLast being updated to the new block's values if (lCurrentAndLast.current >= lCurrentAndLast.last) { allocateBlock(lCurrentAndLast.last); } // Increment the current value slot_pair_ newCurrentAndLast = {lCurrentAndLast.current + 1, lCurrentAndLast.last}; // Attempt to store the updated value back // If true, we successfully updated currentAndLastSlots_ and can return our new object // If false, we failed to update, but the new value of currentAndLastSlots_ is now in lCurrentAndLast if (currentAndLastSlots_.compare_exchange_weak(lCurrentAndLast, newCurrentAndLast)) { return reinterpret_cast<pointer>(lCurrentAndLast.current); } } } template <typename T, size_t BlockSize> inline void MemoryPool<T, BlockSize>::deallocate(pointer p, size_type n) { if (p != nullptr) { slot_pointer_ lFreeSlots = freeSlots_.load(); for (;;) { // Store this slot's next pointer as the current head reinterpret_cast<slot_pointer_>(p)->next = lFreeSlots; // If true, the head is unchanged and we are able to replace it (and thus we are done) // If false, the head has changed and we must iterate again to complete the operation if (freeSlots_.compare_exchange_weak(lFreeSlots, reinterpret_cast<slot_pointer_>(p))) return; } } } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::size_type MemoryPool<T, BlockSize>::max_size() const noexcept { const size_type maxBlocks = -1 / BlockSize; return (BlockSize - sizeof(data_pointer_)) / sizeof(slot_type_) * maxBlocks; } template <typename T, size_t BlockSize> template <class U, class... Args> inline void MemoryPool<T, BlockSize>::construct(U* p, Args&&... args) { new (p) U (std::forward<Args>(args)...); } template <typename T, size_t BlockSize> template <class U> inline void MemoryPool<T, BlockSize>::destroy(U* p) { p->~U(); } template <typename T, size_t BlockSize> template <class... Args> inline typename MemoryPool<T, BlockSize>::pointer MemoryPool<T, BlockSize>::newElement(Args&&... args) { pointer result = allocate(); construct<value_type>(result, std::forward<Args>(args)...); return result; } template <typename T, size_t BlockSize> inline void MemoryPool<T, BlockSize>::deleteElement(pointer p) { if (p != nullptr) { p->~value_type(); deallocate(p); } } #endif // MEMORY_BLOCK_TCC
30.441509
108
0.739184
[ "object" ]
a6085e7b98045714b5cf523ada2641e4e638fbd7
8,197
cpp
C++
test/unit/test_common.cpp
QuLogic/PROJ
f8438ec596cce6f4b3e0c19092df9eaf22e93cd3
[ "MIT" ]
null
null
null
test/unit/test_common.cpp
QuLogic/PROJ
f8438ec596cce6f4b3e0c19092df9eaf22e93cd3
[ "MIT" ]
null
null
null
test/unit/test_common.cpp
QuLogic/PROJ
f8438ec596cce6f4b3e0c19092df9eaf22e93cd3
[ "MIT" ]
null
null
null
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2018 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" using namespace osgeo::proj::common; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; // --------------------------------------------------------------------------- TEST(common, unit_of_measure) { EXPECT_EQ(UnitOfMeasure::METRE.name(), "metre"); EXPECT_EQ(UnitOfMeasure::METRE.conversionToSI(), 1.0); EXPECT_EQ(UnitOfMeasure::METRE.type(), UnitOfMeasure::Type::LINEAR); EXPECT_EQ(UnitOfMeasure::DEGREE.name(), "degree"); EXPECT_EQ(UnitOfMeasure::DEGREE.conversionToSI(), 0.017453292519943295); EXPECT_EQ(UnitOfMeasure::DEGREE.type(), UnitOfMeasure::Type::ANGULAR); EXPECT_EQ(UnitOfMeasure::RADIAN.name(), "radian"); EXPECT_EQ(UnitOfMeasure::RADIAN.conversionToSI(), 1.0); EXPECT_EQ(UnitOfMeasure::RADIAN.type(), UnitOfMeasure::Type::ANGULAR); EXPECT_EQ(Length(2.0, UnitOfMeasure("km", 1000.0)) .convertToUnit(UnitOfMeasure::METRE), 2000.0); EXPECT_EQ( Angle(2.0, UnitOfMeasure::DEGREE).convertToUnit(UnitOfMeasure::RADIAN), 2 * 0.017453292519943295); EXPECT_EQ(Angle(2.5969213, UnitOfMeasure::GRAD) .convertToUnit(UnitOfMeasure::DEGREE), 2.5969213 / 100.0 * 90.0); } // --------------------------------------------------------------------------- TEST(common, measure) { EXPECT_TRUE(Measure(1.0) == Measure(1.0)); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_empty) { PropertyMap properties; auto obj = OperationParameter::create(properties); EXPECT_TRUE(obj->name()->code().empty()); EXPECT_TRUE(obj->identifiers().empty()); EXPECT_TRUE(obj->aliases().empty()); EXPECT_TRUE(obj->remarks().empty()); EXPECT_TRUE(!obj->isDeprecated()); EXPECT_TRUE(obj->alias().empty()); } // --------------------------------------------------------------------------- TEST(common, identifiedobject) { PropertyMap properties; properties.set(IdentifiedObject::NAME_KEY, "name"); properties.set(IdentifiedObject::IDENTIFIERS_KEY, Identifier::create("identifier_code")); properties.set(IdentifiedObject::ALIAS_KEY, "alias"); properties.set(IdentifiedObject::REMARKS_KEY, "remarks"); properties.set(IdentifiedObject::DEPRECATED_KEY, true); auto obj = OperationParameter::create(properties); EXPECT_EQ(*(obj->name()->description()), "name"); ASSERT_EQ(obj->identifiers().size(), 1U); EXPECT_EQ(obj->identifiers()[0]->code(), "identifier_code"); ASSERT_EQ(obj->aliases().size(), 1U); EXPECT_EQ(obj->aliases()[0]->toString(), "alias"); EXPECT_EQ(obj->remarks(), "remarks"); EXPECT_TRUE(obj->isDeprecated()); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_name_invalid_type_integer) { PropertyMap properties; properties.set(IdentifiedObject::NAME_KEY, 123); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_name_invalid_type_citation) { PropertyMap properties; properties.set(IdentifiedObject::NAME_KEY, nn_make_shared<Citation>("invalid")); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_identifier_invalid_type) { PropertyMap properties; properties.set(IdentifiedObject::IDENTIFIERS_KEY, "string not allowed"); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_identifier_array_of_identifier) { PropertyMap properties; auto array = ArrayOfBaseObject::create(); array->add(Identifier::create("identifier_code1")); array->add(Identifier::create("identifier_code2")); properties.set(IdentifiedObject::IDENTIFIERS_KEY, array); auto obj = OperationParameter::create(properties); ASSERT_EQ(obj->identifiers().size(), 2U); EXPECT_EQ(obj->identifiers()[0]->code(), "identifier_code1"); EXPECT_EQ(obj->identifiers()[1]->code(), "identifier_code2"); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_identifier_array_of_invalid_type) { PropertyMap properties; auto array = ArrayOfBaseObject::create(); array->add(nn_make_shared<Citation>("unexpected type")); properties.set(IdentifiedObject::IDENTIFIERS_KEY, array); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_alias_array_of_string) { PropertyMap properties; properties.set(IdentifiedObject::ALIAS_KEY, std::vector<std::string>{"alias1", "alias2"}); auto obj = OperationParameter::create(properties); ASSERT_EQ(obj->aliases().size(), 2U); EXPECT_EQ(obj->aliases()[0]->toString(), "alias1"); EXPECT_EQ(obj->aliases()[1]->toString(), "alias2"); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_alias_invalid_type) { PropertyMap properties; properties.set(IdentifiedObject::ALIAS_KEY, nn_make_shared<Citation>("unexpected type")); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_alias_array_of_invalid_type) { PropertyMap properties; auto array = ArrayOfBaseObject::create(); array->add(nn_make_shared<Citation>("unexpected type")); properties.set(IdentifiedObject::ALIAS_KEY, array); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, DataEpoch) { DataEpoch epochSrc(Measure(2010.5, UnitOfMeasure::YEAR)); DataEpoch epoch(epochSrc); EXPECT_EQ(epoch.coordinateEpoch().value(), 2010.5); EXPECT_EQ(epoch.coordinateEpoch().unit(), UnitOfMeasure::YEAR); }
40.781095
79
0.604367
[ "vector" ]
a60b4dcee7faa50186a40b648c081cfd9fd597fb
37,447
cpp
C++
src/NumbTh.cpp
bryongloden/HElib
c13dff5ce752fb9fcec9ef81a8db1c0f146fff39
[ "Apache-2.0" ]
10
2018-03-29T17:10:51.000Z
2021-07-28T06:46:20.000Z
src/NumbTh.cpp
bryongloden/HElib
c13dff5ce752fb9fcec9ef81a8db1c0f146fff39
[ "Apache-2.0" ]
3
2017-10-17T08:04:01.000Z
2019-03-28T06:36:40.000Z
src/NumbTh.cpp
bryongloden/HElib
c13dff5ce752fb9fcec9ef81a8db1c0f146fff39
[ "Apache-2.0" ]
5
2017-10-16T09:14:52.000Z
2020-04-10T07:24:51.000Z
/* Copyright (C) 2012-2017 IBM Corp. * This program is 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. See accompanying LICENSE file. */ #include "NumbTh.h" #include "timing.h" #include <fstream> #include <cctype> #include <algorithm> // defines count(...), min(...) bool FHEglobals::dryRun = false; // Code for parsing command line bool parseArgs(int argc, char *argv[], argmap_t& argmap) { for (long i = 1; i < argc; i++) { char *x = argv[i]; long j = 0; while (x[j] != '=' && x[j] != '\0') j++; if (x[j] == '\0') return false; string arg(x, j); if (argmap[arg] == NULL) return false; argmap[arg] = x+j+1; } return true; } bool doArgProcessing(string *value, const char *s) { *value = string(s); return true; } // Mathematically correct mod and div, avoids overflow long mcMod(long a, long b) { long r = a % b; if (r != 0 && (b < 0) != (r < 0)) return r + b; else return r; } long mcDiv(long a, long b) { long r = a % b; long q = a / b; if (r != 0 && (b < 0) != (r < 0)) return q + 1; else return q; } // return multiplicative order of p modulo m, or 0 if GCD(p, m) != 1 long multOrd(long p, long m) { if (GCD(p, m) != 1) return 0; p = p % m; long ord = 1; long val = p; while (val != 1) { ord++; val = MulMod(val, p, m); } return ord; } // returns \prod_d vec[d] template<class T> static inline long computeProd(const T& vec, long k) { long prod = 1; for (long d = 0; d < k; d++) prod = prod * vec[d]; return prod; } long computeProd(const Vec<long>& vec) { return computeProd(vec, vec.length());} long computeProd(const vector<long>& vec) {return computeProd(vec, vec.size());} // return a degree-d irreducible polynomial mod p ZZX makeIrredPoly(long p, long d) { assert(d >= 1); assert(ProbPrime(p)); if (d == 1) return ZZX(1, 1); // the monomial X zz_pBak bak; bak.save(); zz_p::init(p); return to_ZZX(BuildIrred_zz_pX(d)); } // Factoring by trial division, only works for N<2^{60}. // Only the primes are recorded, not their multiplicity template<class zz> static void factorT(vector<zz> &factors, const zz &N) { factors.resize(0); // reset the factors if (N<2) return; // sanity check PrimeSeq s; zz n = N; while (true) { if (ProbPrime(n)) { // we are left with just a single prime factors.push_back(n); return; } // if n is a composite, check if the next prime divides it long p = s.next(); if ((n%p)==0) { zz pp; conv(pp,p); factors.push_back(pp); do { n /= p; } while ((n%p)==0); } if (n==1) return; } } void factorize(vector<long> &factors, long N) { factorT<long>(factors, N);} void factorize(vector<ZZ> &factors, const ZZ& N) {factorT<ZZ>(factors, N);} // Returns a list of prime factors and their multiplicity, // N = \prod_i factors[i].first^{factors[i].second} void factorize(Vec< Pair<long, long> > &factors, long N) { factors.SetLength(0); if (N < 2) return; PrimeSeq s; long n = N; while (n > 1) { if (ProbPrime(n)) { // n itself is a prime, add (n,1) to the list append(factors, cons(n, 1L)); return; } long p = s.next(); if ((n % p) == 0) { // p divides n, find its multiplicity long e = 1; n = n/p; while ((n % p) == 0) { n = n/p; e++; } append(factors, cons(p, e)); // add (p,e) to the list } } } // Prime-power factorization void pp_factorize(vector<long>& factors, long N) { Vec< Pair<long, long> > pf; factorize(pf,N); // prime factors, N = \prod_i pf[i].first^{pf[i].second} factors.resize(pf.length()); for (long i=0; i<pf.length(); i++) factors[i] = power_long(pf[i].a, pf[i].b); // p_i^e_i } template<class zz> static void phiNT(zz &phin, vector<zz> &facts, const zz &N) { if (facts.size()==0) factorize(facts,N); zz n = N; conv(phin,1); // initialize phiN=1 for (unsigned long i=0; i<facts.size(); i++) { zz p = facts[i]; phin *= (p-1); // first factor of p for (n /= p; (n%p)==0; n /= p) phin *= p; // multiple factors of p } } // Specific template instantiations for long and ZZ void phiN(long &pN, vector<long> &fs, long N) { phiNT<long>(pN,fs,N); } void phiN(ZZ &pN, vector<ZZ> &fs, const ZZ &N) { phiNT<ZZ>(pN,fs,N); } /* Compute Phi(N) */ long phi_N(long N) { long phiN=1,p,e; PrimeSeq s; while (N!=1) { p=s.next(); e=0; while ((N%p)==0) { N=N/p; e++; } if (e!=0) { phiN=phiN*(p-1)*power_long(p,e-1); } } return phiN; } /* While generating the representation of (Z/mZ)^*, we keep the elements in * equivalence classes, and each class has a representative element (called * a pivot), which is the smallest element in the class. Initialy each element * is in its own class. When we add a new generator g we unify classes if * their members are a factor of g from each other, repeating this process * until no further unification is possible. * * We begin by adding p as a generator, thus computing the equivalence * classes of (Z/mZ)^* /<p>. Then we repeatedly compute the orders of * all elements in the current quotient group, choose the highest-order * element and add it as a generator, then recompute the new quotient * group and so on, until the remaining quotient group is the trivial * one, containing just a a single element. A twist is that when choosing * the highest-order generator, we try to find one whose order in the * current quotient group is the same as in the original group (Z/mZ)^*. **/ // The function conjClasses(classes,g,m) unifies equivalence classes that // have elements which are a factor of g apart, the pivot of the unified // class is the smallest element in that class. static void conjClasses(vector<long>& classes, long g, long m) { for (long i=0; i<m; i++) { if (classes[i]==0) continue; // i \notin (Z/mZ)^* if (classes[i]<i) { // i is not a pivot, updated its pivot classes[i] = classes[classes[i]]; continue; } // If i is a pivot, update other pivots to point to it unsigned long j = MulMod(i, g, m); while (classes[j] != i) { classes[classes[j]]= i; // Merge the equivalence classes of j and i // Note: if classes[j]!=j then classes[j] will be updated later, // when we get to i=j and use the code for "i not pivot". j = MulMod(j, g, m); } } } // The function compOrder(orders, classes,flag,m) computes the order of elements // of the quotient group, relative to current equivalent classes. If flag==1 // then also check if the order is the same as in (Z/mZ)^* and store the order // with negative sign if not. static void compOrder(vector<long>& orders, vector<long>& classes, bool flag, long m) { orders[0] = 0; orders[1] = 1; for (long i=2; i<m; i++) { if (classes[i] <= 1) { // ignore i not in Z_m^* and order-0 elements orders[i] = (classes[i]==1)? 1 : 0; continue; } // If not comparing order with (Z/mZ)^*, only compute the order of pivots if (!flag && classes[i]<i){ // not a pivot orders[i] = orders[classes[i]]; continue; } // For an element i>1, the order is at least 2 long j = MulMod(i, i, m); long ord = 2; while (classes[j] != 1) { j = MulMod(j, i, m); // next element in <i> ord++; // count how many steps until we reach 1 } // When we get here we have classes[j]==1, so if j!=1 it means that the // order of i in the quotient group is smaller than its order in the // entire group Z_m^*. If the flag is set then we store orders[i] = -ord. if (flag && j != 1) ord = -ord; // order in Z_m^* is larger than ord orders[i] = ord; } } // Compare numbers based on their absolute value static bool gtAbsVal(long a, long b) { return (abs(a)>abs(b) || (abs(a)==abs(b) && a>b)); } // Returns in gens a generating set for Zm* /<p>, and in ords the // order of these generators. Return value is the order of p in Zm*. long findGenerators(vector<long>& gens, vector<long>& ords, long m, long p) { gens.clear(); ords.clear(); // Compute the generators for (Z/mZ)^* vector<long> classes(m); vector<long> orders(m); for (long i=0; i<m; i++) { // initially each element in its own class if (GCD(i,m)!=1) classes[i] = 0; // i is not in (Z/mZ)^* else classes[i] = i; } // Start building a representation of (Z/mZ)^*, first use the generator p conjClasses(classes,p % m,m); // merge classes that have a factor of p // The order of p is the size of the equivalence class of 1 #if 0 long ordP = std::count(classes.begin(), classes.end(), 1); // count(from,to,val) returns # of elements in (from,to) with value=val #else long ordP = 0; for (long i = 0; i < lsize(classes); i++) if (classes[i] == 1) ordP++; #endif // Compute orders in (Z/mZ)^*/<p> while comparing to (Z/mZ)^* while (true) { compOrder(orders,classes,true,m); // if the orders of i in Zm* /<p> and Zm* are not the same, then // order[i] contains the order in Zm* /<p> with negative sign long idx = argmax(orders, &gtAbsVal); // find the element with largest order long largest = orders[idx]; if (abs(largest) == 1) break; // Trivial group, we are done // store generator with same order as in (Z/mZ)^* gens.push_back(idx); ords.push_back(largest); conjClasses(classes,idx,m); // merge classes that have a factor of idx } return ordP; } // finding e-th root of unity modulo the current modulus // VJS: rewritten to be both faster and deterministic, // and assumes that current modulus is prime template<class zp,class zz> void FindPrimRootT(zp &root, unsigned long e) { zz qm1 = zp::modulus()-1; assert(qm1 % e == 0); vector<long> facts; factorize(facts,e); // factorization of e root = 1; for (unsigned long i = 0; i < facts.size(); i++) { long p = facts[i]; long pp = p; long ee = e/p; while (ee % p == 0) { ee = ee/p; pp = pp*p; } // so now we have e = pp * ee, where pp is // the power of p that divides e. // Our goal is to find an element of order pp PrimeSeq s; long q; zp qq, qq1; long iter = 0; do { iter++; if (iter > 1000000) Error("FindPrimitiveRoot: possible infinite loop?"); q = s.next(); conv(qq, q); power(qq1, qq, qm1/p); } while (qq1 == 1); power(qq1, qq, qm1/pp); // qq1 has order pp mul(root, root, qq1); } // independent check that we have an e-th root of unity { zp s; power(s, root, e); if (s != 1) Error("FindPrimitiveRoot: internal error (1)"); // check that s^{e/p} != 1 for any prime divisor p of e for (unsigned long i=0; i<facts.size(); i++) { long e2 = e/facts[i]; power(s, root, e2); // s = root^{e/p} if (s == 1) Error("FindPrimitiveRoot: internal error (2)"); } } } // instantiations of the template void FindPrimitiveRoot(zz_p &r, unsigned long e){FindPrimRootT<zz_p,long>(r,e);} void FindPrimitiveRoot(ZZ_p &r, unsigned long e){FindPrimRootT<ZZ_p,ZZ>(r,e);} /* Compute mobius function (naive method as n is small) */ long mobius(long n) { long p,e,arity=0; PrimeSeq s; while (n!=1) { p=s.next(); e=0; while ((n%p==0)) { n=n/p; e++; } if (e>1) { return 0; } if (e!=0) { arity^=1; } } if (arity==0) { return 1; } return -1; } /* Compute cyclotomic polynomial */ ZZX Cyclotomic(long N) { ZZX Num,Den,G,F; NTL::set(Num); NTL::set(Den); long m,d; for (d=1; d<=N; d++) { if ((N%d)==0) { clear(G); SetCoeff(G,N/d,1); SetCoeff(G,0,-1); m=mobius(d); if (m==1) { Num*=G; } else if (m==-1) { Den*=G; } } } F=Num/Den; return F; } /* Find a primitive root modulo N */ long primroot(long N,long phiN) { long g=2,p; PrimeSeq s; bool flag=false; while (flag==false) { flag=true; s.reset(1); do { p=s.next(); if ((phiN%p)==0) { if (PowerMod(g,phiN/p,N)==1) { flag=false; } } } while (p<phiN && flag); if (flag==false) { g++; } } return g; } long ord(long N,long p) { long o=0; while ((N%p)==0) { o++; N/=p; } return o; } ZZX RandPoly(long n,const ZZ& p) { ZZX F; F.SetMaxLength(n); ZZ p2; p2=p>>1; for (long i=0; i<n; i++) { SetCoeff(F,i,RandomBnd(p)-p2); } return F; } /* When q=2 maintains the same sign as the input */ void PolyRed(ZZX& out, const ZZX& in, const ZZ& q, bool abs) { // ensure that out has the same degree as in out.SetMaxLength(deg(in)+1); // allocate space if needed if (deg(out)>deg(in)) trunc(out,out,deg(in)+1); // remove high degrees ZZ q2; q2=q>>1; for (long i=0; i<=deg(in); i++) { ZZ c=coeff(in,i); c %= q; if (abs) { if (c<0) c += q; } else if (q!=2) { if (c>q2) { c=c-q; } else if (c<-q2) { c=c+q; } } else // q=2 { if (sign(coeff(in,i))!=sign(c)) { c=-c; } } SetCoeff(out,i,c); } } void PolyRed(ZZX& out, const ZZX& in, long q, bool abs) { // ensure that out has the same degree as in out.SetMaxLength(deg(in)+1); // allocate space if needed if (deg(out)>deg(in)) trunc(out,out,deg(in)+1); // remove high degrees long q2; q2=q>>1; for (long i=0; i<=deg(in); i++) { long c=coeff(in,i)%q; if (abs) { if (c<0) { c=c+q; } } else if (q==2) { if (coeff(in,i)<0) { c=-c; } } else { if (c>=q2) { c=c-q; } else if (c<-q2) { c=c+q; } } SetCoeff(out,i,c); } } void vecRed(Vec<ZZ>& out, const Vec<ZZ>& in, long q, bool abs) { out.SetLength(in.length()); // allocate space if needed for (long i=0; i<in.length(); i++) { long c = in[i]%q; if (abs) { if (c<0) c+=q; } else if (q==2) { if (in[i]<0) c = -c; } else { if (c >= q/2) c -= q; else if (c < -(q/2)) c += q; } out[i] = c; } } // multiply the polynomial f by the integer a modulo q void MulMod(ZZX& out, const ZZX& f, long a, long q, bool abs/*default=true*/) { // ensure that out has the same degree as f out.SetMaxLength(deg(f)+1); // allocate space if needed if (deg(out)>deg(f)) trunc(out,out,deg(f)+1); // remove high degrees mulmod_precon_t aqinv = PrepMulModPrecon(a, q); for (long i=0; i<=deg(f); i++) { long c = rem(coeff(f,i), q); c = MulModPrecon(c, a, q, aqinv); // returns c \in [0,q-1] if (!abs && c >= q/2) c -= q; SetCoeff(out,i,c); } } long is_in(long x,int* X,long sz) { for (long i=0; i<sz; i++) { if (x==X[i]) { return i; } } return -1; } /* Incremental integer CRT for vectors. Expects co-primes p>0,q>0 with q odd, * and such that all the entries in vp are in [-p/2,p/2) and all entries in * vq are in [0,q-1). Returns in vp the CRT of vp mod p and vq mod q, as * integers in [-pq/2, pq/2). Uses the formula: * * CRT(vp,p,vq,q) = vp + p*[ (vq-vp)*p^{-1} ]_q * * where [...]_q means reduction to the interval [-q/2,q/2). As q is odd then * this is the same as reducing to [-(q-1)/2,(q-1)/2], hence [...]_q * p is * in [-p(q-1)/2, p(q-1)/2], and since vp is in [-p/2,p/2) then the sum is * indeed in [-pq/2,pq/2). * * Returns true if both vectors are of the same length, false otherwise */ template <class zzvec> bool intVecCRT(vec_ZZ& vp, const ZZ& p, const zzvec& vq, long q) { long pInv = InvMod(rem(p,q), q); // p^{-1} mod q long n = min(vp.length(),vq.length()); long q_over_2 = q/2; ZZ tmp; long vqi; mulmod_precon_t pqInv = PrepMulModPrecon(pInv, q); for (long i=0; i<n; i++) { conv(vqi, vq[i]); // convert to single precision long vq_minus_vp_mod_q = SubMod(vqi, rem(vp[i],q), q); long delta_times_pInv = MulModPrecon(vq_minus_vp_mod_q, pInv, q, pqInv); if (delta_times_pInv > q_over_2) delta_times_pInv -= q; mul(tmp, delta_times_pInv, p); // tmp = [(vq_i-vp_i)*p^{-1}]_q * p vp[i] += tmp; } // other entries (if any) are 0 mod q for (long i=vq.length(); i<vp.length(); i++) { long minus_vp_mod_q = NegateMod(rem(vp[i],q), q); long delta_times_pInv = MulModPrecon(minus_vp_mod_q, pInv, q, pqInv); if (delta_times_pInv > q_over_2) delta_times_pInv -= q; mul(tmp, delta_times_pInv, p); // tmp = [(vq_i-vp_i)*p^{-1}]_q * p vp[i] += tmp; } return (vp.length()==vq.length()); } // specific instantiations: vq can be vec_long, vec_ZZ, or Vec<zz_p> template bool intVecCRT(vec_ZZ&, const ZZ&, const vec_ZZ&, long); template bool intVecCRT(vec_ZZ&, const ZZ&, const vec_long&, long); template bool intVecCRT(vec_ZZ&, const ZZ&, const Vec<zz_p>&, long); // MinGW hack #ifndef lrand48 #if defined(__MINGW32__) || defined(WIN32) #define drand48() (((double)rand()) / RAND_MAX) #define lrand48() rand() #endif #endif void sampleHWt(ZZX &poly, long Hwt, long n) { if (n<=0) n=deg(poly)+1; if (n<=0) return; clear(poly); // initialize to zero poly.SetMaxLength(n); // allocate space for degree-(n-1) polynomial long b,u,i=0; if (Hwt>n) Hwt=n; while (i<Hwt) { // continue until exactly Hwt nonzero coefficients u=lrand48()%n; // The next coefficient to choose if (IsZero(coeff(poly,u))) { // if we didn't choose it already b = lrand48()&2; // b random in {0,2} b--; // random in {-1,1} SetCoeff(poly,u,b); i++; // count another nonzero coefficient } } poly.normalize(); // need to call this after we work on the coeffs } void sampleSmall(ZZX &poly, long n) { if (n<=0) n=deg(poly)+1; if (n<=0) return; poly.SetMaxLength(n); // allocate space for degree-(n-1) polynomial for (long i=0; i<n; i++) { // Chosse coefficients, one by one long u = lrand48(); if (u&1) { // with prob. 1/2 choose between -1 and +1 u = (u & 2) -1; SetCoeff(poly, i, u); } else SetCoeff(poly, i, 0); // with ptob. 1/2 set to 0 } poly.normalize(); // need to call this after we work on the coeffs } void sampleGaussian(ZZX &poly, long n, double stdev) { static double const Pi=4.0*atan(1.0); // Pi=3.1415.. static long const bignum = 0xfffffff; // THREADS: C++11 guarantees these are initialized only once if (n<=0) n=deg(poly)+1; if (n<=0) return; poly.SetMaxLength(n); // allocate space for degree-(n-1) polynomial for (long i=0; i<n; i++) SetCoeff(poly, i, ZZ::zero()); // Uses the Box-Muller method to get two Normal(0,stdev^2) variables for (long i=0; i<n; i+=2) { double r1 = (1+RandomBnd(bignum))/((double)bignum+1); double r2 = (1+RandomBnd(bignum))/((double)bignum+1); double theta=2*Pi*r1; double rr= sqrt(-2.0*log(r2))*stdev; assert(rr < 8*stdev); // sanity-check, no more than 8 standard deviations // Generate two Gaussians RV's, rounded to integers long x = (long) floor(rr*cos(theta) +0.5); SetCoeff(poly, i, x); if (i+1 < n) { x = (long) floor(rr*sin(theta) +0.5); SetCoeff(poly, i+1, x); } } poly.normalize(); // need to call this after we work on the coeffs } void sampleUniform(ZZX& poly, const ZZ& B, long n) { if (n<=0) n=deg(poly)+1; if (n<=0) return; if (B <= 0) { clear(poly); return; } poly.SetMaxLength(n); // allocate space for degree-(n-1) polynomial ZZ UB, tmp; UB = 2*B + 1; for (long i = 0; i < n; i++) { RandomBnd(tmp, UB); tmp -= B; poly.rep[i] = tmp; } poly.normalize(); } // ModComp: a pretty lame implementation void ModComp(ZZX& res, const ZZX& g, const ZZX& h, const ZZX& f) { assert(LeadCoeff(f) == 1); ZZX hh = h % f; ZZX r = to_ZZX(0); for (long i = deg(g); i >= 0; i--) r = (r*hh + coeff(g, i)) % f; res = r; } long polyEvalMod(const ZZX& poly, long x, long p) { long ret = 0; x %= p; if (x<0) x += p; mulmod_precon_t xpinv = PrepMulModPrecon(x, p); for (long i=deg(poly); i>=0; i--) { long coeff = rem(poly[i], p); ret = AddMod(ret, coeff, p); // Add the coefficient of x^i if (i>0) ret = MulModPrecon(ret, x, p, xpinv); // then mult by x } return ret; } static void recursiveInterpolateMod(ZZX& poly, const vec_long& x, vec_long& y, const vec_zz_p& xmod, vec_zz_p& ymod, long p, long p2e) { if (p2e<=1) { // recursion edge condition, mod-1 poly = 0 clear(poly); return; } // convert y input to zz_p for (long j=0; j<y.length(); j++) ymod[j] = to_zz_p(y[j] % p); // a polynomial p_i s.t. p_i(x[j]) = i'th p-base digit of poly(x[j]) zz_pX polyMod; interpolate(polyMod, xmod, ymod); // interpolation modulo p ZZX polyTmp; conv(polyTmp, polyMod); // convert to ZZX // update ytmp by subtracting the new digit, then dividing by p for (long j=0; j<y.length(); j++) { y[j] -= polyEvalMod(polyTmp,x[j],p2e); // mod p^e if (y[j]<0) y[j] += p2e; // if (y[j] % p != 0) { // cerr << "@@error (p2^e="<<p2e<<"): y["<<j<<"] not divisible by "<<p<< endl; // exit(0); // } y[j] /= p; } // maybe it's worth optimizing above by using multi-point evaluation // recursive call to get the solution of poly'(x)=y mod p^{e-1} recursiveInterpolateMod(poly, x, y, xmod, ymod, p, p2e/p); // return poly = p*poly' + polyTmp poly *= p; poly += polyTmp; } // Interpolate the integer polynomial such that poly(x[i] mod p)=y[i] (mod p^e) // It is assumed that the points x[i] are all distinct modulo p void interpolateMod(ZZX& poly, const vec_long& x, const vec_long& y, long p, long e) { poly = ZZX::zero(); // initialize to zero long p2e = power_long(p,e); // p^e vec_long ytmp(INIT_SIZE, y.length()); // A temporary writable copy for (long j=0; j<y.length(); j++) { ytmp[j] = y[j] % p2e; if (ytmp[j] < 0) ytmp[j] += p2e; } zz_pBak bak; bak.save(); // Set the current modulus to p zz_p::init(p); vec_zz_p xmod(INIT_SIZE, x.length()); // convert to zz_p for (long j=0; j<x.length(); j++) xmod[j] = to_zz_p(x[j] % p); vec_zz_p ymod(INIT_SIZE, y.length()); // scratch space recursiveInterpolateMod(poly, x, ytmp, xmod, ymod, p, p2e); } ZZ largestCoeff(const ZZX& f) { ZZ mx = ZZ::zero(); for (long i=0; i<=deg(f); i++) { if (mx < abs(coeff(f,i))) mx = abs(coeff(f,i)); } return mx; } ZZ sumOfCoeffs(const ZZX& f) // = f(1) { ZZ sum = ZZ::zero(); for (long i=0; i<=deg(f); i++) sum += coeff(f,i); return sum; } xdouble coeffsL2Norm(const ZZX& f) // l_2 norm { xdouble s = to_xdouble(0.0); for (long i=0; i<=deg(f); i++) { xdouble coef = to_xdouble(coeff(f,i)); s += coef * coef; } return sqrt(s); } // advance the input stream beyond white spaces and a single instance of cc void seekPastChar(istream& str, int cc) { int c = str.get(); while (isspace(c)) c = str.get(); if (c != cc) { std::cerr << "Searching for cc='"<<(char)cc<<"' (ascii "<<cc<<")" << ", found c='"<<(char)c<<"' (ascii "<<c<<")\n"; exit(1); } } // stuff added relating to linearized polynomials and support routines // Builds the matrix defining the linearized polynomial transformation. // // NTL's current smallint modulus, zz_p::modulus(), is assumed to be p^r, // for p prime, r >= 1 integer. // // After calling this function, one can call ppsolve(C, L, M, p, r) to get // the coeffecients C for the linearized polynomial represented the linear // map defined by its action on the standard basis for zz_pE over zz_p: // for i = 0..zz_pE::degree()-1: x^i -> L[i], where x = (X mod zz_pE::modulus()) void buildLinPolyMatrix(mat_zz_pE& M, long p) { long d = zz_pE::degree(); M.SetDims(d, d); for (long j = 0; j < d; j++) conv(M[0][j], zz_pX(j, 1)); for (long i = 1; i < d; i++) for (long j = 0; j < d; j++) M[i][j] = power(M[i-1][j], p); } void buildLinPolyMatrix(mat_GF2E& M, long p) { assert(p == 2); long d = GF2E::degree(); M.SetDims(d, d); for (long j = 0; j < d; j++) conv(M[0][j], GF2X(j, 1)); for (long i = 1; i < d; i++) for (long j = 0; j < d; j++) M[i][j] = power(M[i-1][j], p); } // some auxilliary conversion routines void convert(vec_zz_pE& X, const vector<ZZX>& A) { long n = A.size(); zz_pX tmp; X.SetLength(n); for (long i = 0; i < n; i++) { conv(tmp, A[i]); conv(X[i], tmp); } } void convert(mat_zz_pE& X, const vector< vector<ZZX> >& A) { long n = A.size(); if (n == 0) { long m = X.NumCols(); X.SetDims(0, m); return; } long m = A[0].size(); X.SetDims(n, m); for (long i = 0; i < n; i++) convert(X[i], A[i]); } void convert(vector<ZZX>& X, const vec_zz_pE& A) { long n = A.length(); X.resize(n); for (long i = 0; i < n; i++) conv(X[i], rep(A[i])); } void convert(vector< vector<ZZX> >& X, const mat_zz_pE& A) { long n = A.NumRows(); X.resize(n); for (long i = 0; i < n; i++) convert(X[i], A[i]); } void convert(NTL::Vec<long>& out, const NTL::ZZX& in) { out.SetLength(in.rep.length()); for (long i=0; i<out.length(); i++) out[i] = conv<long>(in[i]); } void convert(NTL::Vec<long>& out, const NTL::zz_pX& in) { out.SetLength(in.rep.length()); for (long i=0; i<out.length(); i++) out[i] = conv<long>(in[i]); } void convert(NTL::Vec<long>& out, const NTL::GF2X& in) { out.SetLength(1+deg(in)); for (long i=0; i<out.length(); i++) out[i] = conv<long>(in[i]); } void convert(NTL::ZZX& out, const NTL::Vec<long>& in) { out.SetLength(in.length()); for (long i=0; i<in.length(); i++) out[i] = conv<ZZ>(in[i]); out.normalize(); } void convert(NTL::GF2X& out, const NTL::Vec<long>& in) { out.SetLength(in.length()); for (long i=0; i<in.length(); i++) out[i] = conv<GF2>(in[i]); out.normalize(); } void mul(vector<ZZX>& x, const vector<ZZX>& a, long b) { long n = a.size(); x.resize(n); for (long i = 0; i < n; i++) mul(x[i], a[i], b); } void div(vector<ZZX>& x, const vector<ZZX>& a, long b) { long n = a.size(); x.resize(n); for (long i = 0; i < n; i++) div(x[i], a[i], b); } void add(vector<ZZX>& x, const vector<ZZX>& a, const vector<ZZX>& b) { long n = a.size(); if (n != (long) b.size()) Error("add: dimension mismatch"); for (long i = 0; i < n; i++) add(x[i], a[i], b[i]); } // prime power solver // zz_p::modulus() is assumed to be p^r, for p prime, r >= 1 // A is an n x n matrix, b is a length n (row) vector, // and a solution for the matrix-vector equation x A = b is found. // If A is not inverible mod p, then error is raised. void ppsolve(vec_zz_pE& x, const mat_zz_pE& A, const vec_zz_pE& b, long p, long r) { if (r == 1) { zz_pE det; solve(det, x, A, b); if (det == 0) Error("ppsolve: matrix not invertible"); return; } long n = A.NumRows(); if (n != A.NumCols()) Error("ppsolve: matrix not square"); if (n == 0) Error("ppsolve: matrix of dimension 0"); zz_pContext pr_context; pr_context.save(); zz_pEContext prE_context; prE_context.save(); zz_pX G = zz_pE::modulus(); ZZX GG = to_ZZX(G); vector< vector<ZZX> > AA; convert(AA, A); vector<ZZX> bb; convert(bb, b); zz_pContext p_context(p); p_context.restore(); zz_pX G1 = to_zz_pX(GG); zz_pEContext pE_context(G1); pE_context.restore(); // we are now working mod p... // invert A mod p mat_zz_pE A1; convert(A1, AA); mat_zz_pE I1; zz_pE det; inv(det, I1, A1); if (det == 0) { Error("ppsolve: matrix not invertible"); } vec_zz_pE b1; convert(b1, bb); vec_zz_pE y1; y1 = b1 * I1; vector<ZZX> yy; convert(yy, y1); // yy is a solution mod p for (long k = 1; k < r; k++) { // lift solution yy mod p^k to a solution mod p^{k+1} pr_context.restore(); prE_context.restore(); // we are now working mod p^r vec_zz_pE d, y; convert(y, yy); d = b - y * A; vector<ZZX> dd; convert(dd, d); long pk = power_long(p, k); vector<ZZX> ee; div(ee, dd, pk); p_context.restore(); pE_context.restore(); // we are now working mod p vec_zz_pE e1; convert(e1, ee); vec_zz_pE z1; z1 = e1 * I1; vector<ZZX> zz, ww; convert(zz, z1); mul(ww, zz, pk); add(yy, yy, ww); } pr_context.restore(); prE_context.restore(); convert(x, yy); assert(x*A == b); } void ppsolve(vec_GF2E& x, const mat_GF2E& A, const vec_GF2E& b, long p, long r) { assert(p == 2 && r == 1); GF2E det; solve(det, x, A, b); if (det == 0) Error("ppsolve: matrix not invertible"); } // prime power solver // A is an n x n matrix, we compute its inverse mod p^r. An error is raised // if A is not inverible mod p. zz_p::modulus() is assumed to be p^r, for // p prime, r >= 1. Also zz_pE::modulus() is assumed to be initialized. void ppInvert(mat_zz_pE& X, const mat_zz_pE& A, long p, long r) { if (r == 1) { // use native inversion from NTL inv(X, A); // X = A^{-1} return; } // begin by inverting A modulo p // convert to ZZX for a safe transaltion to mod-p objects vector< vector<ZZX> > tmp; convert(tmp, A); { // open a new block for mod-p computation ZZX G; convert(G, zz_pE::modulus()); zz_pBak bak_pr; bak_pr.save(); // backup the mod-p^r moduli zz_pEBak bak_prE; bak_prE.save(); zz_p::init(p); // Set the mod-p moduli zz_pE::init(conv<zz_pX>(G)); mat_zz_pE A1, Inv1; convert(A1, tmp); // Recover A as a mat_zz_pE object modulo p inv(Inv1, A1); // Inv1 = A^{-1} (mod p) convert(tmp, Inv1); // convert to ZZX for transaltion to a mod-p^r object } // mod-p^r moduli restored on desctuction of bak_pr and bak_prE mat_zz_pE XX; convert(XX, tmp); // XX = A^{-1} (mod p) // Now lift the solution modulo p^r // Compute the "correction factor" Z, s.t. XX*A = I - p*Z (mod p^r) long n = A.NumRows(); const mat_zz_pE I = ident_mat_zz_pE(n); // identity matrix mat_zz_pE Z = I - XX*A; convert(tmp, Z); // Conver to ZZX to divide by p for (long i=0; i<n; i++) for (long j=0; j<n; j++) tmp[i][j] /= p; convert(Z, tmp); // convert back to a mod-p^r object // The inverse of A is ( I+(pZ)+(pZ)^2+...+(pZ)^{r-1} )*XX (mod p^r). We use // O(log r) products to copmute it as (I+pZ)* (I+(pZ)^2)* (I+(pZ)^4)*...* XX long e = NextPowerOfTwo(r); // 2^e is smallest power of two >= r Z *= p; // = pZ mat_zz_pE prod = I + Z; // = I + pZ for (long i=1; i<e; i++) { sqr(Z, Z); // = (pZ)^{2^i} prod *= (I+Z); // = sum_{j=0}^{2^{i+1}-1} (pZ)^j } mul(X, prod, XX); // X = A^{-1} mod p^r assert(X*A == I); } // FIXME: at some point need to make a template for these two functions // prime power solver // A is an n x n matrix, we compute its inverse mod p^r. An error is raised // if A is not inverible mod p. zz_p::modulus() is assumed to be p^r, for // p prime, r >= 1. void ppInvert(mat_zz_p& X, const mat_zz_p& A, long p, long r) { if (r == 1) { // use native inversion from NTL inv(X, A); // X = A^{-1} return; } // begin by inverting A modulo p // convert to long for a safe transaltion to mod-p objects Mat<long> tmp; conv(tmp, A); { // open a new block for mod-p computation zz_pBak bak_pr; bak_pr.save(); // backup the mod-p^r moduli zz_p::init(p); // Set the mod-p moduli mat_zz_p A1, Inv1; conv(A1, tmp); // Recover A as a mat_zz_pE object modulo p inv(Inv1, A1); // Inv1 = A^{-1} (mod p) conv(tmp, Inv1); // convert to long for transaltion to a mod-p^r object } // mod-p^r moduli restored on desctuction of bak_pr and bak_prE mat_zz_p XX; conv(XX, tmp); // XX = A^{-1} (mod p) // Now lift the solution modulo p^r // Compute the "correction factor" Z, s.t. XX*A = I - p*Z (mod p^r) long n = A.NumRows(); const mat_zz_p I = ident_mat_zz_p(n); // identity matrix mat_zz_p Z = I - XX*A; conv(tmp, Z); // Conver to long to divide by p for (long i=0; i<n; i++) for (long j=0; j<n; j++) tmp[i][j] /= p; conv(Z, tmp); // convert back to a mod-p^r object // The inverse of A is ( I+(pZ)+(pZ)^2+...+(pZ)^{r-1} )*XX (mod p^r). We use // O(log r) products to copmute it as (I+pZ)* (I+(pZ)^2)* (I+(pZ)^4)*...* XX long e = NextPowerOfTwo(r); // 2^e is smallest power of two >= r Z *= p; // = pZ mat_zz_p prod = I + Z; // = I + pZ for (long i=1; i<e; i++) { sqr(Z, Z); // = (pZ)^{2^i} prod *= (I+Z); // = sum_{j=0}^{2^{i+1}-1} (pZ)^j } mul(X, prod, XX); // X = A^{-1} mod p^r assert(X*A == I); } void buildLinPolyCoeffs(vec_zz_pE& C_out, const vec_zz_pE& L, long p, long r) { FHE_TIMER_START; mat_zz_pE M; buildLinPolyMatrix(M, p); vec_zz_pE C; ppsolve(C, M, L, p, r); C_out = C; FHE_TIMER_STOP; } void buildLinPolyCoeffs(vec_GF2E& C_out, const vec_GF2E& L, long p, long r) { FHE_TIMER_START; assert(p == 2 && r == 1); mat_GF2E M; buildLinPolyMatrix(M, p); vec_GF2E C; ppsolve(C, M, L, p, r); C_out = C; FHE_TIMER_STOP; } void applyLinPoly(zz_pE& beta, const vec_zz_pE& C, const zz_pE& alpha, long p) { long d = zz_pE::degree(); assert(d == C.length()); zz_pE gamma, res; gamma = to_zz_pE(zz_pX(1, 1)); res = C[0]*alpha; for (long i = 1; i < d; i++) { gamma = power(gamma, p); res += C[i]*to_zz_pE(CompMod(rep(alpha), rep(gamma), zz_pE::modulus())); } beta = res; } void applyLinPoly(GF2E& beta, const vec_GF2E& C, const GF2E& alpha, long p) { long d = GF2E::degree(); assert(d == C.length()); GF2E gamma, res; gamma = to_GF2E(GF2X(1, 1)); res = C[0]*alpha; for (long i = 1; i < d; i++) { gamma = power(gamma, p); res += C[i]*to_GF2E(CompMod(rep(alpha), rep(gamma), GF2E::modulus())); } beta = res; } // Auxilliary classes to facillitiate faster reduction mod Phi_m(X) // when the input has degree less than m static void LocalCopyReverse(zz_pX& x, const zz_pX& a, long lo, long hi) // x[0..hi-lo] = reverse(a[lo..hi]), with zero fill // input may not alias output { long i, j, n, m; n = hi-lo+1; m = a.rep.length(); x.rep.SetLength(n); const zz_p* ap = a.rep.elts(); zz_p* xp = x.rep.elts(); for (i = 0; i < n; i++) { j = hi-i; if (j < 0 || j >= m) clear(xp[i]); else xp[i] = ap[j]; } x.normalize(); } static void LocalCyclicReduce(zz_pX& x, const zz_pX& a, long m) // computes x = a mod X^m-1 { long n = deg(a); long i, j; zz_p accum; if (n < m) { x = a; return; } if (&x != &a) x.rep.SetLength(m); for (i = 0; i < m; i++) { accum = a.rep[i]; for (j = i + m; j <= n; j += m) add(accum, accum, a.rep[j]); x.rep[i] = accum; } if (&x == &a) x.rep.SetLength(m); x.normalize(); } zz_pXModulus1::zz_pXModulus1(long _m, const zz_pX& _f) : m(_m), f(_f), n(deg(f)) { assert(m > n); specialLogic = (m - n > 10 && m < 2*n); build(fm, f); if (specialLogic) { zz_pX P1, P2, P3; LocalCopyReverse(P3, f, 0, n); InvTrunc(P2, P3, m-n); LocalCopyReverse(P1, P2, 0, m-n-1); k = NextPowerOfTwo(2*(m-1-n)+1); k1 = NextPowerOfTwo(n); TofftRep(R0, P1, k); TofftRep(R1, f, k1); } } void rem(zz_pX& r, const zz_pX& a, const zz_pXModulus1& ff) { if (!ff.specialLogic) { rem(r, a, ff.fm); return; } long m = ff.m; long n = ff.n; long k = ff.k; long k1 = ff.k1; const fftRep& R0 = ff.R0; const fftRep& R1 = ff.R1; if (deg(a) < n) { r = a; return; } zz_pX P2, P3; fftRep R2, R3; TofftRep(R2, a, k, n, m-1); mul(R2, R2, R0); FromfftRep(P3, R2, m-1-n, 2*(m-1-n)); long l = 1L << k1; TofftRep(R3, P3, k1); mul(R3, R3, R1); FromfftRep(P3, R3, 0, n-1); LocalCyclicReduce(P2, a, l); trunc(P2, P2, n); sub(P2, P2, P3); r = P2; } // Debug printing routines for vectors, ZZX'es, print only a few entries template<class T> ostream& printVec(ostream& s, const Vec<T>& v, long nCoeffs) { long d = v.length(); if (d<nCoeffs) return s << v; // just print the whole thing // otherwise print only 1st nCoeffs coefficiants s << '['; for (long i=0; i<nCoeffs-2; i++) s << v[i] << ' '; s << "... " << v[d-2] << ' ' << v[d-1] << ']'; return s; } template ostream& printVec(ostream& s, const Vec<zz_p>& v, long nCoeffs); template ostream& printVec(ostream& s, const Vec<long>& v, long nCoeffs); template ostream& printVec(ostream& s, const Vec<ZZX>& v, long nCoeffs); ostream& printZZX(ostream& s, const ZZX& poly, long nCoeffs) { return printVec(s, poly.rep, nCoeffs); }
25.66621
80
0.575427
[ "object", "vector" ]
a60e68406423024ab905348b90f593c4d2824c75
766
hpp
C++
include/sharpen/EventLoopThread.hpp
iceBear67/Sharpen
4f00fb13a2b3e7dc26cdb34596d58f958eb341f8
[ "MIT" ]
null
null
null
include/sharpen/EventLoopThread.hpp
iceBear67/Sharpen
4f00fb13a2b3e7dc26cdb34596d58f958eb341f8
[ "MIT" ]
null
null
null
include/sharpen/EventLoopThread.hpp
iceBear67/Sharpen
4f00fb13a2b3e7dc26cdb34596d58f958eb341f8
[ "MIT" ]
null
null
null
#pragma once #ifndef _SHARPEN_EVENTLOOPTHREAD_HPP #define _SHARPEN_EVENTLOOPTHREAD_HPP #include <thread> #include "EventLoop.hpp" namespace sharpen { class EventLoopThread:public sharpen::Noncopyable,public sharpen::Nonmovable { private: sharpen::EventLoop loop_; std::thread thread_; void Entry() noexcept; public: explicit EventLoopThread(sharpen::SelectorPtr selector); EventLoopThread(sharpen::SelectorPtr selector,std::shared_ptr<std::vector<std::function<void()>>> tasks,std::shared_ptr<sharpen::SpinLock> lock); ~EventLoopThread() noexcept; void Join(); void Detach(); void Stop() noexcept; sharpen::EventLoop *GetLoop() noexcept; }; } #endif
20.702703
153
0.674935
[ "vector" ]
a60fe2381519b6638758854aa9fb41958e3e5182
12,982
hpp
C++
examples/opencl/benchmark_vector/directcl.hpp
STEllAR-GROUP/hpxcl
1d5fd791016548856d65866f64ca169778402c4f
[ "BSL-1.0" ]
30
2015-10-01T16:15:02.000Z
2022-03-17T12:21:47.000Z
examples/opencl/benchmark_vector/directcl.hpp
STEllAR-GROUP/hpxcl
1d5fd791016548856d65866f64ca169778402c4f
[ "BSL-1.0" ]
50
2015-06-21T01:05:34.000Z
2021-08-06T18:20:54.000Z
examples/opencl/benchmark_vector/directcl.hpp
STEllAR-GROUP/hpxcl
1d5fd791016548856d65866f64ca169778402c4f
[ "BSL-1.0" ]
23
2015-03-18T11:18:36.000Z
2021-12-27T16:36:32.000Z
// Copyright (c) 2014 Martin Stumpf // // 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 BENCHMARK_DIRECTCL_HPP_ #define BENCHMARK_DIRECTCL_HPP_ #include "gpu_code.hpp" #include <vector> #include <cmath> #include <memory> #include <CL/cl.h> static cl_context directcl_context; static cl_command_queue directcl_command_queue; static cl_program directcl_program; static cl_kernel directcl_exp_kernel; static cl_kernel directcl_log_kernel; static cl_kernel directcl_add_kernel; static cl_kernel directcl_mul_kernel; static cl_kernel directcl_dbl_kernel; static cl_mem directcl_buffer_a; static cl_mem directcl_buffer_b; static cl_mem directcl_buffer_c; static cl_mem directcl_buffer_m; static cl_mem directcl_buffer_n; static cl_mem directcl_buffer_o; static cl_mem directcl_buffer_p; static cl_mem directcl_buffer_z; #define directcl_check(ret) \ { \ if ((ret) != CL_SUCCESS) { \ hpx::cout << "directcl.hpp:" << __LINE__ << ": CL ERROR: " << (ret) \ << hpx::endl; \ exit(1); \ } \ } /*static void directcl_check(cl_int ret) { if(ret != CL_SUCCESS){ hpx::cout << "CL ERROR: " << ret << hpx::endl; exit(1); } }*/ static cl_device_id directcl_choose_device() { cl_int ret; // get number of platform ids cl_uint num_platforms; ret = clGetPlatformIDs(0, NULL, &num_platforms); directcl_check(ret); // get platform ids std::vector<cl_platform_id> platforms(num_platforms); ret = clGetPlatformIDs(num_platforms, platforms.data(), NULL); directcl_check(ret); /* // Print Platforms hpx::cout << "Platforms:" << hpx::endl; for(cl_uint i = 0; i < num_platforms; i++) { char platformName[100]; char platformVendor[100]; ret = clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, 100, platformName, NULL); directcl_check(ret); ret = clGetPlatformInfo(platforms[i], CL_PLATFORM_VENDOR, 100, platformVendor, NULL); directcl_check(ret); hpx::cout << i << ": " << platformName << " (" << platformVendor << ")" << hpx::endl; } // Lets you choose a platform cl_uint platform_num; hpx::cout << "Choose platform: " << hpx::endl; std::cin >> platform_num; if(platform_num < 0 || platform_num >= num_platforms) exit(0); */ // Ensure that we found a platforms if (num_platforms < 1) { hpx::cout << "No OpenCL platforms found!" << hpx::endl; exit(1); } // Select the platform cl_uint num_devices = 0; cl_platform_id platform = 0; for (auto& current_platform : platforms) { // get number of device ids ret = clGetDeviceIDs(current_platform, CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices); if (ret == CL_DEVICE_NOT_FOUND) continue; directcl_check(ret); // Print platform name hpx::cout << "Platform:" << hpx::endl; { char platformName[100]; char platformVendor[100]; ret = clGetPlatformInfo(current_platform, CL_PLATFORM_NAME, 100, platformName, NULL); directcl_check(ret); ret = clGetPlatformInfo(current_platform, CL_PLATFORM_VENDOR, 100, platformVendor, NULL); directcl_check(ret); hpx::cout << " " << platformName << " (" << platformVendor << ")" << hpx::endl; } platform = current_platform; break; } // Ensure that we found a platforms if (num_devices < 1) { hpx::cout << "No OpenCL devices found!" << hpx::endl; exit(1); } // get device ids std::vector<cl_device_id> devices(num_devices); ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, num_devices, devices.data(), NULL); // Print devices hpx::cout << "Device:" << hpx::endl; { char deviceName[100]; ret = clGetDeviceInfo(devices[0], CL_DEVICE_NAME, 100, deviceName, NULL); directcl_check(ret); hpx::cout << " " << deviceName << hpx::endl; } return devices[0]; } static void directcl_initialize(size_t vector_size) { cl_device_id device_id = directcl_choose_device(); cl_int err; // Create context directcl_context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &err); directcl_check(err); // Create command queue directcl_command_queue = clCreateCommandQueue(directcl_context, device_id, 0, &err); directcl_check(err); // Create program const char* gpu_code_ptr = gpu_code; directcl_program = clCreateProgramWithSource(directcl_context, 1, &gpu_code_ptr, NULL, &err); directcl_check(err); // Build program err = clBuildProgram(directcl_program, 1, &device_id, NULL, NULL, NULL); // Create kernels directcl_log_kernel = clCreateKernel(directcl_program, "logn", &err); directcl_check(err); directcl_exp_kernel = clCreateKernel(directcl_program, "expn", &err); directcl_check(err); directcl_mul_kernel = clCreateKernel(directcl_program, "mul", &err); directcl_check(err); directcl_add_kernel = clCreateKernel(directcl_program, "add", &err); directcl_check(err); directcl_dbl_kernel = clCreateKernel(directcl_program, "dbl", &err); directcl_check(err); // Create buffers directcl_buffer_a = clCreateBuffer(directcl_context, CL_MEM_READ_ONLY, vector_size * sizeof(float), NULL, &err); directcl_check(err); directcl_buffer_b = clCreateBuffer(directcl_context, CL_MEM_READ_ONLY, vector_size * sizeof(float), NULL, &err); directcl_check(err); directcl_buffer_c = clCreateBuffer(directcl_context, CL_MEM_READ_ONLY, vector_size * sizeof(float), NULL, &err); directcl_check(err); directcl_buffer_m = clCreateBuffer(directcl_context, CL_MEM_READ_WRITE, vector_size * sizeof(float), NULL, &err); directcl_check(err); directcl_buffer_n = clCreateBuffer(directcl_context, CL_MEM_READ_WRITE, vector_size * sizeof(float), NULL, &err); directcl_check(err); directcl_buffer_o = clCreateBuffer(directcl_context, CL_MEM_READ_WRITE, vector_size * sizeof(float), NULL, &err); directcl_check(err); directcl_buffer_p = clCreateBuffer(directcl_context, CL_MEM_READ_WRITE, vector_size * sizeof(float), NULL, &err); directcl_check(err); directcl_buffer_z = clCreateBuffer(directcl_context, CL_MEM_WRITE_ONLY, vector_size * sizeof(float), NULL, &err); directcl_check(err); // set kernel args for exp err = clSetKernelArg(directcl_exp_kernel, 0, sizeof(cl_mem), &directcl_buffer_m); directcl_check(err); err = clSetKernelArg(directcl_exp_kernel, 1, sizeof(cl_mem), &directcl_buffer_b); directcl_check(err); // set kernel args for add err = clSetKernelArg(directcl_add_kernel, 0, sizeof(cl_mem), &directcl_buffer_n); directcl_check(err); err = clSetKernelArg(directcl_add_kernel, 1, sizeof(cl_mem), &directcl_buffer_a); directcl_check(err); err = clSetKernelArg(directcl_add_kernel, 2, sizeof(cl_mem), &directcl_buffer_m); directcl_check(err); // set kernel args for dbl err = clSetKernelArg(directcl_dbl_kernel, 0, sizeof(cl_mem), &directcl_buffer_o); directcl_check(err); err = clSetKernelArg(directcl_dbl_kernel, 1, sizeof(cl_mem), &directcl_buffer_c); directcl_check(err); // set kernel args for mul err = clSetKernelArg(directcl_mul_kernel, 0, sizeof(cl_mem), &directcl_buffer_p); directcl_check(err); err = clSetKernelArg(directcl_mul_kernel, 1, sizeof(cl_mem), &directcl_buffer_n); directcl_check(err); err = clSetKernelArg(directcl_mul_kernel, 2, sizeof(cl_mem), &directcl_buffer_o); directcl_check(err); // set kernel args for log err = clSetKernelArg(directcl_log_kernel, 0, sizeof(cl_mem), &directcl_buffer_z); directcl_check(err); err = clSetKernelArg(directcl_log_kernel, 1, sizeof(cl_mem), &directcl_buffer_p); directcl_check(err); } static std::shared_ptr<std::vector<float>> directcl_calculate( hpx::serialization::serialize_buffer<float> a, hpx::serialization::serialize_buffer<float> b, hpx::serialization::serialize_buffer<float> c, double* t_nonblock, double* t_total) { // do nothing if matrices are wrong if (a.size() != b.size() || b.size() != c.size()) { return std::shared_ptr<std::vector<float>>(); } // initialize error test cl_int err; // copy data to gpu err = clEnqueueWriteBuffer(directcl_command_queue, directcl_buffer_a, CL_FALSE, 0, a.size() * sizeof(float), a.data(), 0, NULL, NULL); directcl_check(err); err = clEnqueueWriteBuffer(directcl_command_queue, directcl_buffer_b, CL_FALSE, 0, a.size() * sizeof(float), b.data(), 0, NULL, NULL); directcl_check(err); err = clEnqueueWriteBuffer(directcl_command_queue, directcl_buffer_c, CL_FALSE, 0, a.size() * sizeof(float), c.data(), 0, NULL, NULL); directcl_check(err); // wait for writes to finish err = clFinish(directcl_command_queue); directcl_check(err); // start timer timer_start(); // run kernels size_t size = a.size(); err = clEnqueueNDRangeKernel(directcl_command_queue, directcl_exp_kernel, 1, NULL, &size, NULL, 0, NULL, NULL); directcl_check(err); err = clEnqueueNDRangeKernel(directcl_command_queue, directcl_add_kernel, 1, NULL, &size, NULL, 0, NULL, NULL); directcl_check(err); err = clEnqueueNDRangeKernel(directcl_command_queue, directcl_dbl_kernel, 1, NULL, &size, NULL, 0, NULL, NULL); directcl_check(err); err = clEnqueueNDRangeKernel(directcl_command_queue, directcl_mul_kernel, 1, NULL, &size, NULL, 0, NULL, NULL); directcl_check(err); err = clEnqueueNDRangeKernel(directcl_command_queue, directcl_log_kernel, 1, NULL, &size, NULL, 0, NULL, NULL); directcl_check(err); // get time of nonblocking calls *t_nonblock = timer_stop(); // finish err = clFinish(directcl_command_queue); directcl_check(err); // get time of total calculation *t_total = timer_stop(); // allocate the result buffer std::shared_ptr<std::vector<float>> res(new std::vector<float>(a.size())); // read into result buffer err = clEnqueueReadBuffer(directcl_command_queue, directcl_buffer_z, CL_FALSE, 0, a.size() * sizeof(float), res->data(), 0, NULL, NULL); directcl_check(err); // finish err = clFinish(directcl_command_queue); directcl_check(err); return res; } static void directcl_shutdown() { cl_int err; // release buffers err = clReleaseMemObject(directcl_buffer_a); directcl_check(err); err = clReleaseMemObject(directcl_buffer_b); directcl_check(err); err = clReleaseMemObject(directcl_buffer_c); directcl_check(err); err = clReleaseMemObject(directcl_buffer_m); directcl_check(err); err = clReleaseMemObject(directcl_buffer_n); directcl_check(err); err = clReleaseMemObject(directcl_buffer_o); directcl_check(err); err = clReleaseMemObject(directcl_buffer_p); directcl_check(err); err = clReleaseMemObject(directcl_buffer_z); directcl_check(err); // release kernels err = clReleaseKernel(directcl_dbl_kernel); directcl_check(err); err = clReleaseKernel(directcl_add_kernel); directcl_check(err); err = clReleaseKernel(directcl_mul_kernel); directcl_check(err); err = clReleaseKernel(directcl_exp_kernel); directcl_check(err); err = clReleaseKernel(directcl_log_kernel); directcl_check(err); // release program err = clReleaseProgram(directcl_program); directcl_check(err); // release command queue err = clReleaseCommandQueue(directcl_command_queue); directcl_check(err); // release context err = clReleaseContext(directcl_context); directcl_check(err); } #endif // BENCHMARK_DIRECTCL_HPP_
33.372751
80
0.636112
[ "vector" ]
a6107acc87f9e6fae6769cd86d0739ac38ccd68d
913
cpp
C++
largest-rectangle-in-histogram/largest-rectangle-in-histogram.cpp
arpitkekri/My-Leetcode-Solution-In-CPP
345f1c53c627fce33ee84672c5d3661863367040
[ "MIT" ]
4
2021-06-21T04:32:12.000Z
2021-11-02T04:20:36.000Z
largest-rectangle-in-histogram/largest-rectangle-in-histogram.cpp
arpitkekri/My-Leetcode-Solution-In-CPP
345f1c53c627fce33ee84672c5d3661863367040
[ "MIT" ]
null
null
null
largest-rectangle-in-histogram/largest-rectangle-in-histogram.cpp
arpitkekri/My-Leetcode-Solution-In-CPP
345f1c53c627fce33ee84672c5d3661863367040
[ "MIT" ]
2
2021-08-19T11:27:18.000Z
2021-09-26T14:51:30.000Z
class Solution { public: int largestRectangleArea(vector<int>& heights) { int n = heights.size(); vector<int> nsl(n), nsr(n); stack<int> stk; for(int i = 0; i < n; i++) { while(!stk.empty() && heights[stk.top()] >= heights[i]) stk.pop(); if(stk.empty()) nsl[i] = -1; else nsl[i] = stk.top(); stk.push(i); } stk = stack<int>(); for(int i = n-1; i >= 0; i--) { while(!stk.empty() && heights[stk.top()] >= heights[i]) stk.pop(); if(stk.empty()) nsr[i] = n; else nsr[i] = stk.top(); stk.push(i); } int ans = 0; for(int i = 0; i < n; i++) { ans = max(ans, heights[i]*(nsr[i] - nsl[i] - 1)); } return ans; } };
28.53125
67
0.374589
[ "vector" ]
a61564c50bcb33670c74d13cb996b58a67ff0b79
1,020
cpp
C++
381-Insert_Delete_GetRandom_O(1)_-_Duplicates_allowed.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
381-Insert_Delete_GetRandom_O(1)_-_Duplicates_allowed.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
381-Insert_Delete_GetRandom_O(1)_-_Duplicates_allowed.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
class RandomizedCollection { unordered_map<int, unordered_set<int>> umap; vector<int> vec; public: RandomizedCollection() { srand(time(0)); } bool insert(int val) { if ( umap.find(val) == umap.end() ) { umap[val] = unordered_set<int>(); umap[val].insert(vec.size()); vec.push_back(val); return true; } umap[val].insert(vec.size()); vec.push_back(val); return false; } bool remove(int val) { if ( umap.find(val) == umap.end() ) return false; umap[vec.back()].insert(*umap[val].begin()); umap[vec.back()].erase(vec.size()-1); if ( vec.back() != val ) { swap(vec[*umap[val].begin()], vec.back()); umap[val].erase(umap[val].begin()); } vec.resize(vec.size() - 1); if ( umap[val].empty() ) umap.erase(val); return true; } int getRandom() { return vec[rand() % vec.size()]; } };
26.842105
57
0.496078
[ "vector" ]
a6185ab8cbd3668ae4039e18c33bb38b83a5814b
1,920
cc
C++
cpp/iteration.cc
abhineet99/pmemkv-tools
ba89d64c359dc136ca8f2304d573c0d8390d3be3
[ "Apache-2.0" ]
null
null
null
cpp/iteration.cc
abhineet99/pmemkv-tools
ba89d64c359dc136ca8f2304d573c0d8390d3be3
[ "Apache-2.0" ]
null
null
null
cpp/iteration.cc
abhineet99/pmemkv-tools
ba89d64c359dc136ca8f2304d573c0d8390d3be3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <sys/time.h> #include <vector> #include "libpmemkv.h" #define LOG(msg) std::cout << msg << "\n" using namespace pmemkv; static const int COUNT = 100000000; static const string PATH = "/dev/shm/pmemkv"; static double current_seconds() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) + (double) (tv.tv_usec) / 1000000; } struct CallbackContext { unsigned long failures; }; void test_engine(const string engine, const string value) { LOG("\nTesting " << engine << " for " + to_string(COUNT) << " keys, value size is " << value.length() << "..."); std::remove(PATH.c_str()); KVEngine* kv = KVEngine::Start(engine, "{\"path\":\"" + PATH + "\",\"size\":16106127360}"); LOG("Put (sequential series)"); auto started = current_seconds(); for (int i = 0; i < COUNT; i++) { if (kv->Put(to_string(i), value) != OK) { std::cout << "Out of space at key " << to_string(i) << "\n"; exit(-42); } } LOG(" in " << current_seconds() - started << " sec"); LOG("All (one pass)"); CallbackContext cxt = {COUNT}; auto cba = [](void* context, int keybytes, const char* key) { ((CallbackContext*) context)->failures--; }; started = current_seconds(); kv->All(&cxt, cba); LOG(" in " << current_seconds() - started << " sec, failures=" + to_string(cxt.failures)); LOG("Each (one pass)"); cxt = {COUNT}; auto cb = [](void* context, int keybytes, const char* key, int valuebytes, const char* value) { ((CallbackContext*) context)->failures--; }; started = current_seconds(); kv->Each(&cxt, cb); LOG(" in " << current_seconds() - started << " sec, failures=" + to_string(cxt.failures)); delete kv; } int main() { test_engine("tree3", std::string(64, 'A')); LOG("\nFinished!\n"); return 0; }
29.538462
99
0.576042
[ "vector" ]
a61d8ef1ba170fbe4b4aaaf966d8a25ba2d7e3b5
8,939
cpp
C++
cls/src/v20201016/model/AlarmTargetInfo.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cls/src/v20201016/model/AlarmTargetInfo.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cls/src/v20201016/model/AlarmTargetInfo.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cls/v20201016/model/AlarmTargetInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cls::V20201016::Model; using namespace std; AlarmTargetInfo::AlarmTargetInfo() : m_logsetIdHasBeenSet(false), m_logsetNameHasBeenSet(false), m_topicIdHasBeenSet(false), m_topicNameHasBeenSet(false), m_queryHasBeenSet(false), m_numberHasBeenSet(false), m_startTimeOffsetHasBeenSet(false), m_endTimeOffsetHasBeenSet(false) { } CoreInternalOutcome AlarmTargetInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("LogsetId") && !value["LogsetId"].IsNull()) { if (!value["LogsetId"].IsString()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.LogsetId` IsString=false incorrectly").SetRequestId(requestId)); } m_logsetId = string(value["LogsetId"].GetString()); m_logsetIdHasBeenSet = true; } if (value.HasMember("LogsetName") && !value["LogsetName"].IsNull()) { if (!value["LogsetName"].IsString()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.LogsetName` IsString=false incorrectly").SetRequestId(requestId)); } m_logsetName = string(value["LogsetName"].GetString()); m_logsetNameHasBeenSet = true; } if (value.HasMember("TopicId") && !value["TopicId"].IsNull()) { if (!value["TopicId"].IsString()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.TopicId` IsString=false incorrectly").SetRequestId(requestId)); } m_topicId = string(value["TopicId"].GetString()); m_topicIdHasBeenSet = true; } if (value.HasMember("TopicName") && !value["TopicName"].IsNull()) { if (!value["TopicName"].IsString()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.TopicName` IsString=false incorrectly").SetRequestId(requestId)); } m_topicName = string(value["TopicName"].GetString()); m_topicNameHasBeenSet = true; } if (value.HasMember("Query") && !value["Query"].IsNull()) { if (!value["Query"].IsString()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.Query` IsString=false incorrectly").SetRequestId(requestId)); } m_query = string(value["Query"].GetString()); m_queryHasBeenSet = true; } if (value.HasMember("Number") && !value["Number"].IsNull()) { if (!value["Number"].IsInt64()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.Number` IsInt64=false incorrectly").SetRequestId(requestId)); } m_number = value["Number"].GetInt64(); m_numberHasBeenSet = true; } if (value.HasMember("StartTimeOffset") && !value["StartTimeOffset"].IsNull()) { if (!value["StartTimeOffset"].IsInt64()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.StartTimeOffset` IsInt64=false incorrectly").SetRequestId(requestId)); } m_startTimeOffset = value["StartTimeOffset"].GetInt64(); m_startTimeOffsetHasBeenSet = true; } if (value.HasMember("EndTimeOffset") && !value["EndTimeOffset"].IsNull()) { if (!value["EndTimeOffset"].IsInt64()) { return CoreInternalOutcome(Error("response `AlarmTargetInfo.EndTimeOffset` IsInt64=false incorrectly").SetRequestId(requestId)); } m_endTimeOffset = value["EndTimeOffset"].GetInt64(); m_endTimeOffsetHasBeenSet = true; } return CoreInternalOutcome(true); } void AlarmTargetInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_logsetIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LogsetId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_logsetId.c_str(), allocator).Move(), allocator); } if (m_logsetNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LogsetName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_logsetName.c_str(), allocator).Move(), allocator); } if (m_topicIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TopicId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_topicId.c_str(), allocator).Move(), allocator); } if (m_topicNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TopicName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_topicName.c_str(), allocator).Move(), allocator); } if (m_queryHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Query"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_query.c_str(), allocator).Move(), allocator); } if (m_numberHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Number"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_number, allocator); } if (m_startTimeOffsetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StartTimeOffset"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_startTimeOffset, allocator); } if (m_endTimeOffsetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EndTimeOffset"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_endTimeOffset, allocator); } } string AlarmTargetInfo::GetLogsetId() const { return m_logsetId; } void AlarmTargetInfo::SetLogsetId(const string& _logsetId) { m_logsetId = _logsetId; m_logsetIdHasBeenSet = true; } bool AlarmTargetInfo::LogsetIdHasBeenSet() const { return m_logsetIdHasBeenSet; } string AlarmTargetInfo::GetLogsetName() const { return m_logsetName; } void AlarmTargetInfo::SetLogsetName(const string& _logsetName) { m_logsetName = _logsetName; m_logsetNameHasBeenSet = true; } bool AlarmTargetInfo::LogsetNameHasBeenSet() const { return m_logsetNameHasBeenSet; } string AlarmTargetInfo::GetTopicId() const { return m_topicId; } void AlarmTargetInfo::SetTopicId(const string& _topicId) { m_topicId = _topicId; m_topicIdHasBeenSet = true; } bool AlarmTargetInfo::TopicIdHasBeenSet() const { return m_topicIdHasBeenSet; } string AlarmTargetInfo::GetTopicName() const { return m_topicName; } void AlarmTargetInfo::SetTopicName(const string& _topicName) { m_topicName = _topicName; m_topicNameHasBeenSet = true; } bool AlarmTargetInfo::TopicNameHasBeenSet() const { return m_topicNameHasBeenSet; } string AlarmTargetInfo::GetQuery() const { return m_query; } void AlarmTargetInfo::SetQuery(const string& _query) { m_query = _query; m_queryHasBeenSet = true; } bool AlarmTargetInfo::QueryHasBeenSet() const { return m_queryHasBeenSet; } int64_t AlarmTargetInfo::GetNumber() const { return m_number; } void AlarmTargetInfo::SetNumber(const int64_t& _number) { m_number = _number; m_numberHasBeenSet = true; } bool AlarmTargetInfo::NumberHasBeenSet() const { return m_numberHasBeenSet; } int64_t AlarmTargetInfo::GetStartTimeOffset() const { return m_startTimeOffset; } void AlarmTargetInfo::SetStartTimeOffset(const int64_t& _startTimeOffset) { m_startTimeOffset = _startTimeOffset; m_startTimeOffsetHasBeenSet = true; } bool AlarmTargetInfo::StartTimeOffsetHasBeenSet() const { return m_startTimeOffsetHasBeenSet; } int64_t AlarmTargetInfo::GetEndTimeOffset() const { return m_endTimeOffset; } void AlarmTargetInfo::SetEndTimeOffset(const int64_t& _endTimeOffset) { m_endTimeOffset = _endTimeOffset; m_endTimeOffsetHasBeenSet = true; } bool AlarmTargetInfo::EndTimeOffsetHasBeenSet() const { return m_endTimeOffsetHasBeenSet; }
27.76087
142
0.684528
[ "model" ]
98aba0d7ca0c293312a86a77cacda12ad32980ad
5,868
cpp
C++
GraphView/Controller.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
GraphView/Controller.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
GraphView/Controller.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved. #include <iostream> #include <FabricUI/GraphView/Controller.h> #include <FabricUI/GraphView/Graph.h> #include <FabricUI/GraphView/Node.h> #include <FabricUI/GraphView/BackDropNode.h> #include <FabricUI/GraphView/NodeBubble.h> #include <FabricUI/GraphView/Pin.h> #include <FabricUI/GraphView/Port.h> #include <FabricUI/GraphView/Connection.h> #include <FabricUI/GraphView/ConnectionTarget.h> #include <Commands/CommandStack.h> #include <Commands/CompoundCommand.h> #include <FabricUI/GraphView/MainPanel.h> #include <FabricUI/GraphView/NodeHeader.h> #include <FabricUI/GraphView/NodeHeaderButton.h> using namespace FabricUI::GraphView; using namespace FabricServices::Commands; Controller::Controller(Graph * parent) { m_graph = parent; if(m_graph) m_graph->setController(this); m_compound = NULL; m_interactionBracket = 0; } Controller::~Controller() { if(m_compound) delete(m_compound); } Graph * Controller::graph() { return m_graph; } const Graph * Controller::graph() const { return m_graph; } void Controller::setGraph(Graph * graph) { m_graph = graph; } bool Controller::beginInteraction() { if(m_interactionBracket == 0) { if(m_compound == NULL) m_compound = new CompoundCommand(); } return m_interactionBracket++ == 0; } bool Controller::endInteraction() { if(m_interactionBracket > 0) { m_interactionBracket--; if(m_interactionBracket == 0) { if(m_compound) { delete m_compound; m_compound = NULL; } return true; } } return false; } bool Controller::selectNode(Node * node, bool state) { if(node->selected() != state) { node->setSelected(state); return true; } return false; } bool Controller::clearSelection() { if(!m_graph) return false; std::vector<Node*> nodes = m_graph->selectedNodes(); for(size_t i=0;i<nodes.size();i++) { nodes[i]->setSelected(false); } return nodes.size() > 0; } bool Controller::gvcDoRemoveConnections(const std::vector<Connection*> & conns) { std::vector<ConnectionTarget*> srcs; std::vector<ConnectionTarget*> dsts; for (size_t i=0;i<conns.size();i++) if (conns[i]) { srcs.push_back(conns[i]->src()); dsts.push_back(conns[i]->dst()); } return gvcDoRemoveConnections(srcs, dsts); } bool Controller::zoomCanvas(float zoom) { if(!m_graph) return false; m_graph->mainPanel()->setCanvasZoom(zoom, true); return true; } bool Controller::panCanvas(QPointF pan) { if(!m_graph) return false; m_graph->mainPanel()->setCanvasPan(pan, true); return true; } bool Controller::frameAndFitNodes( FTL::ArrayRef<Node *> nodes ) { if(!m_graph) return false; if(nodes.size() == 0) return false; MainPanel *mainPanel = m_graph->mainPanel(); // Get the boudingRect of the nodes QRectF nodesBoundingRect_ItemGroup; for ( size_t i = 0; i < nodes.size(); ++i ) { Node *node = nodes[i]; QRectF nodeBoundingRect = node->boundingRect(); QPointF nodeTopLeftPos = node->topLeftGraphPos(); nodesBoundingRect_ItemGroup |= nodeBoundingRect.translated( nodeTopLeftPos ); } QRectF mainPanelBoundingRect_MainPanel = mainPanel->boundingRect(); // Compute the appropriate zoom // Zoom out a bit more, otherwise nodes will lies on the panel border float zoom = std::min( mainPanelBoundingRect_MainPanel.width() / ( nodesBoundingRect_ItemGroup.width() * 1.1 ), mainPanelBoundingRect_MainPanel.height() / ( nodesBoundingRect_ItemGroup.height() * 1.1 ) ); zoomCanvas( std::max( 0.000001f, std::min( zoom, 1.0f ) ) ); panCanvas( mainPanelBoundingRect_MainPanel.center() - nodesBoundingRect_ItemGroup.center() * mainPanel->canvasZoom() ); return true; } bool Controller::frameSelectedNodes() { return frameAndFitNodes(m_graph->selectedNodes()); } bool Controller::frameAllNodes() { return frameAndFitNodes(m_graph->nodes()); } bool Controller::nodesAreVisible( FTL::ArrayRef<Node *> nodes ) { if(!m_graph) return false; if(nodes.size() == 0) return false; MainPanel *mainPanel = m_graph->mainPanel(); // get the boundingRect of the nodes. QRectF nodesBoundingRect_ItemGroup; for ( size_t i = 0; i < nodes.size(); ++i ) { Node *node = nodes[i]; QRectF nodeBoundingRect = node->boundingRect(); QPointF nodeTopLeftPos = node->topLeftGraphPos(); nodesBoundingRect_ItemGroup |= nodeBoundingRect.translated( nodeTopLeftPos ); } // consider pan and zoom. QPointF pnt1 = nodesBoundingRect_ItemGroup.topLeft(); QPointF pnt2 = nodesBoundingRect_ItemGroup.bottomRight(); pnt1 *= mainPanel->canvasZoom(); pnt1 += mainPanel->canvasPan(); pnt2 *= mainPanel->canvasZoom(); pnt2 += mainPanel->canvasPan(); nodesBoundingRect_ItemGroup.setTopLeft(pnt1); nodesBoundingRect_ItemGroup.setBottomRight(pnt2); // return true if boundingRect is fully contained in the view rect. return mainPanel->boundingRect().contains(nodesBoundingRect_ItemGroup); } bool Controller::allNodesAreVisible() { return nodesAreVisible(m_graph->nodes()); } void Controller::collapseNodes(int state, const std::vector<Node*> & nodes) { for(size_t i=0;i<nodes.size();i++) nodes[i]->setCollapsedState((Node::CollapseState)state); } void Controller::collapseSelectedNodes(int state) { collapseNodes(state, m_graph->selectedNodes()); } void Controller::onNodeHeaderButtonTriggered(FabricUI::GraphView::NodeHeaderButton * button) { if(button->name() == "node_collapse") { int state = (button->state() + 1) % Node::CollapseState_NumStates; button->header()->node()->setCollapsedState((Node::CollapseState)state); } } bool Controller::canConnectTo( char const *pathA, char const *pathB, std::string &failureReason ) const { return true; }
24.148148
92
0.702454
[ "vector" ]
98ac853687b94b4e554d0416f4230214bcbd774f
8,380
cpp
C++
CsBlockchain/Source/CsBlockchain/Blockchain/Ethereum/CsEthereumContract.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsBlockchain/Source/CsBlockchain/Blockchain/Ethereum/CsEthereumContract.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsBlockchain/Source/CsBlockchain/Blockchain/Ethereum/CsEthereumContract.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2019 Closed Sum Games, LLC. All Rights Reserved. #include "Blockchain/Ethereum/CsEthereumContract.h" #include "CsBlockchain.h" #include "Json.h" #include "JsonObjectConverter.h" #include "Runtime/Core/Public/HAL/FileManagerGeneric.h" // Web3DeployLink #pragma region FCsEthereumWeb3DeployLink::FCsEthereumWeb3DeployLink() {} FCsEthereumWeb3DeployLink::FCsEthereumWeb3DeployLink(const FECsBlockchainContract &InContract, const FString &InLink) { Contract = InContract; Link = InLink; } FCsEthereumWeb3DeployLink::~FCsEthereumWeb3DeployLink() {} FCsEthereumWeb3DeployLink& FCsEthereumWeb3DeployLink::operator=(const FCsEthereumWeb3DeployLink& B) { Contract = B.Contract; Link = B.Link; return *this; } bool FCsEthereumWeb3DeployLink::operator==(const FCsEthereumWeb3DeployLink& B) const { return Contract == B.Contract && Link == B.Link; } bool FCsEthereumWeb3DeployLink::operator!=(const FCsEthereumWeb3DeployLink& B) const { return !(*this == B); } void FCsEthereumWeb3DeployLink::Set(const FECsBlockchainContract &InContract, const FString &InLink) { Contract = InContract; Link = InLink; } #pragma endregion Web3DeployLink // Cache #pragma region namespace NCsEthereumContractCache { namespace Str { const FString Name = TEXT("Name"); const FString Address = TEXT("Address"); const FString ContractVariableName = TEXT("ContractVariableName"); const FString InstanceVariableName = TEXT("InstanceVariableName"); const FString ABI = TEXT("ABI"); const FString constant = TEXT("constant"); const FString inputs = TEXT("inputs"); const FString name = TEXT("name"); const FString outputs = TEXT("outputs"); const FString payable = TEXT("payable"); const FString stateMutability = TEXT("stateMutability"); const FString type = TEXT("type"); } } #pragma endregion Cache CsEthereumContract::CsEthereumContract() : ICsBlockchainContract() { } CsEthereumContract::CsEthereumContract(const FString &name) { Address = TEXT(""); ContractVariableName = name.ToLower() + TEXT("Contract"); InstanceVariableName = name.ToLower() + TEXT("Instance"); } CsEthereumContract::~CsEthereumContract(){} const FString& CsEthereumContract::GetName() { return Name; } bool CsEthereumContract::IsValid() { return false; } FString CsEthereumContract::ToString() { FString OutputString; TSharedRef<TJsonWriter<TCHAR>> JsonWriter = TJsonWriterFactory<>::Create(&OutputString); JsonWriter->WriteObjectStart(); // Name JsonWriter->WriteValue(NCsEthereumContractCache::Str::Name, Name); // Address JsonWriter->WriteValue(NCsEthereumContractCache::Str::Address, Address); // ContractVariableName JsonWriter->WriteValue(NCsEthereumContractCache::Str::ContractVariableName, ContractVariableName); // InstanceVariableName JsonWriter->WriteValue(NCsEthereumContractCache::Str::InstanceVariableName, InstanceVariableName); // ABI { JsonWriter->WriteArrayStart(NCsEthereumContractCache::Str::ABI); for (const FCsEthereumABI& A : ABI) { JsonWriter->WriteObjectStart(); // constant JsonWriter->WriteValue(NCsEthereumContractCache::Str::constant, A.constant); // inputs { JsonWriter->WriteArrayStart(NCsEthereumContractCache::Str::inputs); for (const FCsEthereumABIInput& Input : A.inputs) { JsonWriter->WriteObjectStart(); // name JsonWriter->WriteValue(NCsEthereumContractCache::Str::name, Input.name); // type JsonWriter->WriteValue(NCsEthereumContractCache::Str::type, Input.type); JsonWriter->WriteObjectEnd(); } JsonWriter->WriteArrayEnd(); } // name JsonWriter->WriteValue(NCsEthereumContractCache::Str::name, A.name); // outputs { JsonWriter->WriteArrayStart(NCsEthereumContractCache::Str::outputs); for (const FCsEthereumABIOutput& Output : A.outputs) { JsonWriter->WriteObjectStart(); // name JsonWriter->WriteValue(NCsEthereumContractCache::Str::name, Output.name); // type JsonWriter->WriteValue(NCsEthereumContractCache::Str::type, Output.type); JsonWriter->WriteObjectEnd(); } JsonWriter->WriteArrayEnd(); } // payable JsonWriter->WriteValue(NCsEthereumContractCache::Str::payable, A.payable); // stateMutability JsonWriter->WriteValue(NCsEthereumContractCache::Str::stateMutability, A.stateMutability); // type JsonWriter->WriteValue(NCsEthereumContractCache::Str::type, A.type); JsonWriter->WriteObjectEnd(); } JsonWriter->WriteArrayEnd(); } JsonWriter->WriteObjectEnd(); JsonWriter->Close(); return OutputString; } void CsEthereumContract::Parse(const FString &Str) { TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(Str); TSharedPtr<FJsonObject> JsonParsed; if (FJsonSerializer::Deserialize(JsonReader, JsonParsed) && JsonParsed.IsValid()) { // Name Name = JsonParsed->GetStringField(NCsEthereumContractCache::Str::Name); // Address Address = JsonParsed->GetStringField(NCsEthereumContractCache::Str::Address); AddressAsArg = TEXT("'0x") + Address + TEXT("'"); // ContractVariableName ContractVariableName = JsonParsed->GetStringField(NCsEthereumContractCache::Str::ContractVariableName); // InstanceVariableName InstanceVariableName = JsonParsed->GetStringField(NCsEthereumContractCache::Str::InstanceVariableName); // ABI { ABI.Reset(); const TArray<TSharedPtr<FJsonValue>>& JsonArray = JsonParsed->Values.Find(NCsEthereumContractCache::Str::ABI)->Get()->AsArray(); const int32 Count = JsonArray.Num(); for (int32 I = 0; I < Count; ++I) { ABI.AddDefaulted(); const TSharedPtr<FJsonValue>& JsonValue = JsonArray[I]; const TSharedPtr<FJsonObject>& JsonObject = JsonValue->AsObject(); // constant JsonObject->TryGetBoolField(NCsEthereumContractCache::Str::constant, ABI[I].constant); // inputs { ABI[I].inputs.Reset(); const TArray<TSharedPtr<FJsonValue>>* ArrayPtr; if (JsonObject->TryGetArrayField(NCsEthereumContractCache::Str::inputs, ArrayPtr)) { const TArray<TSharedPtr<FJsonValue>>& Array = *ArrayPtr; const int32 ArrayCount = Array.Num(); for (int32 J = 0; J < ArrayCount; ++J) { ABI[I].inputs.AddDefaulted(); const TSharedPtr<FJsonValue>& Value = Array[J]; const TSharedPtr<FJsonObject>& Object = Value->AsObject(); // name ABI[I].inputs[J].name = Object->GetStringField(NCsEthereumContractCache::Str::name); // type ABI[I].inputs[J].type = Object->GetStringField(NCsEthereumContractCache::Str::type); } } } // name JsonObject->TryGetStringField(NCsEthereumContractCache::Str::name, ABI[I].name); // outputs { ABI[I].outputs.Reset(); const TArray<TSharedPtr<FJsonValue>>* ArrayPtr; if (JsonObject->TryGetArrayField(NCsEthereumContractCache::Str::outputs, ArrayPtr)) { const TArray<TSharedPtr<FJsonValue>>& Array = *ArrayPtr; const int32 ArrayCount = Array.Num(); for (int32 J = 0; J < ArrayCount; ++J) { ABI[I].outputs.AddDefaulted(); const TSharedPtr<FJsonValue>& Value = Array[J]; const TSharedPtr<FJsonObject>& Object = Value->AsObject(); // name ABI[I].outputs[J].name = Object->GetStringField(NCsEthereumContractCache::Str::name); // type ABI[I].outputs[J].type = Object->GetStringField(NCsEthereumContractCache::Str::type); } } } // payable JsonObject->TryGetBoolField(NCsEthereumContractCache::Str::payable, ABI[I].payable); // stateMutability JsonObject->TryGetStringField(NCsEthereumContractCache::Str::stateMutability, ABI[I].stateMutability); // type JsonObject->TryGetStringField(NCsEthereumContractCache::Str::type, ABI[I].type); } } } else { UE_LOG(LogCsBlockchain, Warning, TEXT("CsEthereumContract::Parse: Input string is NOT a Valid Genesis string.")); } } void CsEthereumContract::ParseFromFilePath(const FString &Path) { IFileManager& FileManager = FFileManagerGeneric::Get(); if (FileManager.FileExists(*Path)) { FString Str; FFileHelper::LoadFileToString(Str, *Path); Parse(Str); } else { UE_LOG(LogCsBlockchain, Warning, TEXT("CsEthereumContract::ParseFromFilePath: Path %s does NOT Exist."), *Path); } } const FString& CsEthereumContract::GetAddressAsArg() { return AddressAsArg; }
27.933333
131
0.719451
[ "object" ]
98c0a1f2f523b33e8c99a0c0c2fa1c2d76b4ad57
492
hpp
C++
Cpp/53.hpp
FlyAndNotDown/LeetCode
889819ff7f64819e966fc6f9dd80110cf2bf6d3c
[ "MIT" ]
4
2018-06-18T05:39:25.000Z
2022-01-04T07:35:52.000Z
Cpp/53.hpp
FlyAndNotDown/LeetCode
889819ff7f64819e966fc6f9dd80110cf2bf6d3c
[ "MIT" ]
20
2019-11-30T03:42:40.000Z
2020-05-17T03:25:43.000Z
Cpp/53.hpp
FlyAndNotDown/LeetCode
889819ff7f64819e966fc6f9dd80110cf2bf6d3c
[ "MIT" ]
2
2020-02-08T14:10:42.000Z
2021-09-23T13:51:36.000Z
/** * @no 53 * @name Maximum Subarray */ class Solution { public: int maxSubArray(vector<int>& nums) { int max, temp = 0; bool inited = false; for (int i = 0; i < nums.size(); i++) { temp = temp + nums[i] > nums[i] ? temp + nums[i] : nums[i]; if (inited) { if (temp > max) { max = temp; } } else { max = temp; inited = true; } } return max; } };
23.428571
71
0.404472
[ "vector" ]
98c2d344b25187a588db8e9b741574a9da80ebcc
3,274
cpp
C++
Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/SimpleAnimGraphUIFixture.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/SimpleAnimGraphUIFixture.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/SimpleAnimGraphUIFixture.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <EMotionFX/CommandSystem/Source/AnimGraphCommands.h> #include <EMotionFX/Source/AnimGraphManager.h> #include <EMotionFX/Source/AnimGraphMotionNode.h> #include <EMotionFX/Source/Parameter/BoolParameter.h> #include <EMotionFX/Source/Parameter/FloatSliderParameter.h> #include <EMotionFX/Source/Parameter/Vector2Parameter.h> #include <QApplication> #include <Tests/ProvidesUI/AnimGraph/SimpleAnimGraphUIFixture.h> namespace EMotionFX { void SimpleAnimGraphUIFixture::SetUp() { UIFixture::SetUp(); AZStd::string commandResult; MCore::CommandGroup group; // Create empty anim graph, add a motion node and a blend tree. group.AddCommandString(AZStd::string::format("CreateAnimGraph -animGraphID %d", m_animGraphId)); group.AddCommandString(AZStd::string::format("AnimGraphCreateNode -animGraphID %d -type %s -parentName Root -xPos 100 -yPos 100 -name testMotion", m_animGraphId, azrtti_typeid<AnimGraphMotionNode>().ToString<AZStd::string>().c_str())); group.AddCommandString(AZStd::string::format("AnimGraphCreateNode -animGraphID %d -type %s -parentName Root -xPos 200 -yPos 100 -name testBlendTree", m_animGraphId, azrtti_typeid<BlendTree>().ToString<AZStd::string>().c_str())); group.AddCommandString(AZStd::string::format("AnimGraphCreateConnection -animGraphID %d -transitionType %s -sourceNode testMotion -targetNode testBlendTree", m_animGraphId, azrtti_typeid<AnimGraphStateTransition>().ToString<AZStd::string>().c_str())); // Create some paramters group.AddCommandString(AZStd::string::format("AnimGraphCreateParameter -animGraphID %i -type \"%s\" -name bool_param", m_animGraphId, azrtti_typeid<BoolParameter>().ToString<AZStd::string>().c_str())); group.AddCommandString(AZStd::string::format("AnimGraphCreateParameter -animGraphID %i -type \"%s\" -name float_param", m_animGraphId, azrtti_typeid<FloatSliderParameter>().ToString<AZStd::string>().c_str())); group.AddCommandString(AZStd::string::format("AnimGraphCreateParameter -animGraphID %i -type \"%s\" -name vec2_param", m_animGraphId, azrtti_typeid<Vector2Parameter>().ToString<AZStd::string>().c_str())); EXPECT_TRUE(CommandSystem::GetCommandManager()->ExecuteCommandGroup(group, commandResult)) << commandResult.c_str(); m_animGraph = GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); EXPECT_NE(m_animGraph, nullptr) << "Cannot find newly created anim graph."; // Cache some local poitners. m_animGraphPlugin = static_cast<EMStudio::AnimGraphPlugin*>(EMStudio::GetPluginManager()->FindActivePlugin(EMStudio::AnimGraphPlugin::CLASS_ID)); ASSERT_NE(m_animGraphPlugin, nullptr) << "Anim graph plugin not found."; } void SimpleAnimGraphUIFixture::TearDown() { QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); delete m_animGraph; UIFixture::TearDown(); } } // namespace EMotionFX
53.672131
165
0.726329
[ "3d" ]
98c97b9535cf6f4e6ee1f3535cf2b083e62a1923
480
cpp
C++
Test/Expect/test085.cpp
dMajoIT/spin2cpp
f2ee655d150c9d69042b2dfaf8cae57123b7702c
[ "MIT" ]
39
2015-02-10T13:43:24.000Z
2022-03-08T14:56:41.000Z
Test/Expect/test085.cpp
cbmeeks/spin2cpp
d1707a50ee90d944590a6e82c6227a6ff6ce1042
[ "MIT" ]
230
2015-04-12T22:04:54.000Z
2022-03-30T05:22:11.000Z
Test/Expect/test085.cpp
cbmeeks/spin2cpp
d1707a50ee90d944590a6e82c6227a6ff6ce1042
[ "MIT" ]
21
2016-03-05T05:15:06.000Z
2022-03-24T11:58:15.000Z
#define __SPIN2CPP__ #include <propeller.h> #include "test085.h" void test085::Main(void) { Fds.Start(31, 30, 0, 115200); Fds.Str("object array test\r\n"); Printn(0); Printn(1); Printn(2); Fds.Str("increment v[0]\n\r"); // should be the same as v[0].incn V[0].Incn(); Printn(0); Printn(1); Printn(2); } void test085::Printn(int32_t I) { int32_t R; Fds.Str("v["); Fds.Dec(I); Fds.Str("] = "); R = V[I].Getn(); Fds.Dec(R); Fds.Str("\n\r"); }
15.483871
36
0.575
[ "object" ]
98c9cb0b51e43ce3c1e2bdb2d308fc8ec72f2508
2,761
cpp
C++
wizards/display/displayplugintemplate.cpp
nblsyed/hobbits
3264da716743487f2ddff286122d6347b18770e2
[ "MIT" ]
null
null
null
wizards/display/displayplugintemplate.cpp
nblsyed/hobbits
3264da716743487f2ddff286122d6347b18770e2
[ "MIT" ]
null
null
null
wizards/display/displayplugintemplate.cpp
nblsyed/hobbits
3264da716743487f2ddff286122d6347b18770e2
[ "MIT" ]
null
null
null
#include "%{HeaderFileName}" #include "%{FormHeaderFileName}" %{ClassName}::%{ClassName}() : m_renderConfig(new DisplayRenderConfig()) { // TODO: set up actual render config for this display (e.g. when it updates, if it's asynchronous, etc) m_renderConfig->setFullRedrawTriggers(DisplayRenderConfig::NewBitOffset | DisplayRenderConfig::NewFrameOffset); m_renderConfig->setOverlayRedrawTriggers(DisplayRenderConfig::NewBitHover); QList<ParameterDelegate::ParameterInfo> infos = { // TODO: add parameters like {"myparametername", QJsonValue::Double} }; m_delegate = ParameterDelegate::create( infos, [this](const QJsonObject &parameters) { // TODO: use parameters to describe action better return QString("Apply %1").arg(this->name()); }, [](QSharedPointer<ParameterDelegate> delegate, QSize size) { Q_UNUSED(size) return new %{FormClassName}(delegate); }); } DisplayInterface* %{ClassName}::createDefaultDisplay() { return new %{ClassName}(); } QString %{ClassName}::name() { return "%{ClassName}"; } QString %{ClassName}::description() { // TODO: add description return "%{ClassName}"; } QStringList %{ClassName}::tags() { // TODO: make tags relevant return {"Generic"}; } QSharedPointer<DisplayRenderConfig> %{ClassName}::renderConfig() { return m_renderConfig; } void %{ClassName}::setDisplayHandle(QSharedPointer<DisplayHandle> displayHandle) { m_handle = displayHandle; } QSharedPointer<ParameterDelegate> %{ClassName}::parameterDelegate() { return m_delegate; } QSharedPointer<DisplayResult> %{ClassName}::renderDisplay(QSize viewportSize, const QJsonObject &parameters, QSharedPointer<PluginActionProgress> progress) { if (!m_delegate->validate(parameters)) { return DisplayResult::error("Invalid parameters"); } if (m_handle.isNull() || m_handle->currentContainer().isNull()) { return DisplayResult::nullResult(); } // TODO: render and return the display image return DisplayResult::nullResult(); } QSharedPointer<DisplayResult> %{ClassName}::renderOverlay(QSize viewportSize, const QJsonObject &parameters) { if (!m_delegate->validate(parameters)) { m_handle->setRenderedRange(this, Range()); return DisplayResult::error("Invalid parameters"); } if (m_handle.isNull() || m_handle->currentContainer().isNull()) { m_handle->setRenderedRange(this, Range()); return DisplayResult::nullResult(); } // TODO: render and return the overlay image return DisplayResult::nullResult(); }
30.677778
155
0.66063
[ "render" ]
98cb6537d2260b7fe8df436c97089be569fc3640
1,308
cpp
C++
Dynamic Programming/Grid_path.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
2
2021-02-05T04:21:42.000Z
2021-02-10T14:24:38.000Z
Dynamic Programming/Grid_path.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
Dynamic Programming/Grid_path.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ll long long int #define fast ios_base::sync_with_stdio(false) #define fast_input cin.tie(NULL) #define fast_output cout.tie(NULL) #define vi vector<long long int> #define pb push_back #define pa pair<long long int ,long long int> #define f(a,x,b) for(int a=x;a<b;a++) #define sort(x) sort(x.begin(),x.end()); #define siz(a) (int)a.size() #define mod 1000000007 #define F first #define S second #define um unordered_map<ll,ll> #define ordered_set tree<pa, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> void solve() { ll n; cin>>n; vector<string>v(n); vector<vector<ll>>dp(n+1,vector<ll>(n+1)); f(i,0,n) { cin>>v[i]; } f(i,1,n+1) { f(j,1,n+1) { if(i==1&&j==1&&v[i-1][j-1]=='.') { dp[i][j]=1; } else if(v[i-1][j-1]=='.') { dp[i][j]+=(dp[i-1][j]+dp[i][j-1]); dp[i][j]%=mod; } // cout<<dp[i][j]<<" "; } } cout<<dp[n][n]; } int main() { fast; fast_input; fast_output; // ll t; // cin>>t; // f(i,0,t) // { // cout<<"Case #"<<i+1<<":"<<" "; solve(); // } return 0; }
20.761905
97
0.573394
[ "vector" ]
98cc945503c4576876ff33e31fc3c91a9acb8ebc
5,136
cpp
C++
wallpaper-one-oct15/emulator/hardware.cpp
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
null
null
null
wallpaper-one-oct15/emulator/hardware.cpp
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
null
null
null
wallpaper-one-oct15/emulator/hardware.cpp
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
1
2020-01-02T13:54:19.000Z
2020-01-02T13:54:19.000Z
// ******************************************************************************************************************************* // ******************************************************************************************************************************* // // Name: hardware.c // Purpose: Hardware handling routines (C8008 specific) // Created: 22nd October 2015 // Author: Paul Robson (paul@robsons.org.uk) // // ******************************************************************************************************************************* // ******************************************************************************************************************************* #ifdef WINDOWS #include <stdio.h> #include "gfx.h" #endif #ifdef ARDUINO #include <Arduino.h> #include <PS2Keyboard.h> #include "ST7920LCDDriver.h" #endif #include "sys_processor.h" static BYTE8 videoRAM[128]; // 16 x 8 Video RAM. static BYTE8 dirtyFlag[64]; // 64 dirty flags static BYTE8 needsRepaint = 0; // Non-zero when needs repainting. static BYTE8 pendingKey = 0; // Key ready ? #ifdef ARDUINO #define SPI_MOSI A1 #define SPI_CLK A2 #define SPI_ENABLE A0 static ST7920LCDDriver lcd(SPI_CLK, SPI_MOSI, 0); #define DATA_PIN (2) // Connection to PS2 keyboard #define CLOCK_PIN (3) static PS2Keyboard keyboard; // Keyboard object #endif // ******************************************************************************************************************************* // Reset all hardware // ******************************************************************************************************************************* void HWIReset(void) { #ifdef ARDUINO pinMode(SPI_ENABLE, OUTPUT); digitalWrite(SPI_ENABLE, HIGH); lcd.begin(true); lcd.clear(); for (BYTE8 n = 0;n < 128;n++) videoRAM[n] = ' '; // VRAM mirrors. keyboard.begin(DATA_PIN,CLOCK_PIN); // Set up PS2 keyboard #endif } // ******************************************************************************************************************************* // Handle on end of frame. // ******************************************************************************************************************************* void HWIEndFrame(void) { #ifdef ARDUINO if (needsRepaint) { // Needs repainting. needsRepaint = 0; // Clear flag for (BYTE8 n = 0;n < 64;n++) { // Scan all flags if (dirtyFlag[n] != 0) { // Dirty flag set ? dirtyFlag[n] = 0; // Clear it lcd.drawText(n % 8,n / 8 * 8,videoRAM+n*2); // Update display. } } } if (keyboard.available()) { // Key available ? pendingKey = keyboard.read(); // Read it. if (pendingKey >= 0x80) pendingKey = 0; // Remove high characters if (pendingKey == PS2_BACKSPACE) pendingKey = 8; // Backspace returns chr(8) } #endif } // ******************************************************************************************************************************* // Write to video memory // ******************************************************************************************************************************* void HWIWriteVideoMemory(BYTE8 address,BYTE8 character) { address &= 0x7F; // 128 bytes VRAM if (videoRAM[address] != character) { // Changed ? videoRAM[address] = character; // Change in VRAM dirtyFlag[address >> 1] = 1; // Set dirty flag needsRepaint = 1; } } // ******************************************************************************************************************************* // Access video memory // ******************************************************************************************************************************* BYTE8 *HWIGetVideoMemory(void) { return videoRAM; } // ******************************************************************************************************************************* // Debugger key intercept handler // ******************************************************************************************************************************* #ifdef WINDOWS int HWIProcessKey(int key,int isRunTime) { if (key != 0 && isRunTime != 0) { // Running and key press BYTE8 newKey = GFXToASCII(key,1); // Convert to ASCII if (newKey != 0) pendingKey = newKey; // Put pending key in buffer } return key; } #endif // ******************************************************************************************************************************* // Read keyboard // ******************************************************************************************************************************* BYTE8 HWIReadKeyboard(void) { BYTE8 rv = 0; if (pendingKey != 0) { // Key waiting. rv = pendingKey | 0x80; // Return it with bit 7 set pendingKey = 0; // Clear buffer } return rv; }
39.813953
130
0.343653
[ "object" ]
98d111cd58d014293aed4004e3a412bb8cba897c
4,129
hpp
C++
inc/MLPModel.hpp
LorisFriedel/learning-sign-language
f87767c43a11c01885628c1de10daa9d1a58e6ad
[ "MIT" ]
null
null
null
inc/MLPModel.hpp
LorisFriedel/learning-sign-language
f87767c43a11c01885628c1de10daa9d1a58e6ad
[ "MIT" ]
null
null
null
inc/MLPModel.hpp
LorisFriedel/learning-sign-language
f87767c43a11c01885628c1de10daa9d1a58e6ad
[ "MIT" ]
null
null
null
// // @author Loris Friedel // #pragma once #include <opencv2/core/mat.hpp> #include <ml.h> #include "StatPredict.hpp" #include "LabelMap.hpp" class MLPModel { public: /** * Instantiate a MLP model. * * @param nbOfHiddenLayer Number of hidden layer for the neural network. * @param nbOfNeuron Number of neuron per layer. * @return */ MLPModel(int nbOfHiddenLayer = 0, int nbOfNeuron = 0); /** * Instantiate a MLP model. * * @param topologyPattern Pattern for layer and neuron configuration * @return */ MLPModel(const std::vector<int> topologyPattern); /** * Instantiate a MLP model. * * @param topologyPattern Pattern (string representation) for layer and neuron configuration (e.g. "8 32 16") * @return */ MLPModel(const std::string topologyPattern); /** * TODO * @param maxIteration */ void setMaxIter(int maxIteration); /** * TODO * @param method */ void setMethod(cv::ml::ANN_MLP::TrainingMethods method); /** * TODO * @param epsilon */ void setMethodEpsilon(double epsilon); /** * * @param labelMap */ void setLabelMap(LabelMap labelMap); const LabelMap &getLabelMap() const; /** * Export the training data distribution to the specified json file. * If the model is already trained, exportation is made when the method is called. * If not, the exportation is made during the training. * * If you really want to not export log when training the model a second time, you can disable this * functionality by passing an empty string to this method. * * @param jsonFilePath Path to a json file (already existing or to be created) */ void exportTrainDataDistribution(const std::string jsonFilePath); /** * Teach the model from an existing classifier. * * @param classifier_file_name Path to the classifier file. * @return true if reading succeed, false otherwise. */ int learnFrom(const std::string classifier_file_name); /** * Teach the model from a data set. * * @param trainingData Data to use for training. * @param trainingResponses Responses for the data set. * @return true if reading succeed, false otherwise. */ int learnFrom(const cv::Mat &trainingData, const cv::Mat &trainingResponses); /** * Use the current model to predict a result using the given data. * * @param input Data to use for prediction * @return A pair: <0> integer (representing a letter from 0 to 26), <1> the probability to be right */ std::pair<int, float> predict(cv::Mat &input); /** * Test the given data set on the current model. * * @param testData Data to test. * @param testResponses Responses for the data set. * @return The average of success between [0, 1]. 0 mean no prediction success, 1 mean no prediction error, * plus a map with details about the test and prediction */ std::pair<double, std::map<int, StatPredict *>> testOn(const cv::Mat &testData, const cv::Mat &testResponses); /** * Export the current model to a file. * * @param xmlFileName Path to the file where to export the data model as xml. * @return success code */ int exportModelTo(const std::string xmlFileName); /** * @return the topology of this model in string format */ std::string getTopologyStr(); /** * Return the string representation of the given label * @param label Label used in this model * @return a string representing this label */ std::string convertLabel(int label); private: std::vector<int> hiddenLayers; int inputSize; int outputSize; cv::Ptr<cv::ml::ANN_MLP> model; std::map<int, int> classesCountMap; std::string jsonDistribFilePath; LabelMap labelMap; int method = cv::ml::ANN_MLP::BACKPROP; double methodEpsilon = 0.001; int maxIter = 128; inline cv::TermCriteria TC(int iters, double eps); };
27.344371
114
0.642044
[ "vector", "model" ]
98da81784aef0696197017d6a3b2b7c36b435bd3
2,715
cpp
C++
Leetcode/practice/calcEquation.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
Leetcode/practice/calcEquation.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
Leetcode/practice/calcEquation.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
// Optimise #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "/home/shahraaz/bin/debug.h" #else #define db(...) #endif using ll = long long; #define f first #define s second #define pb push_back #define all(v) v.begin(), v.end() const int NAX = 2e5 + 5, MOD = 1000000007; class Solution { public: vector<double> calcEquation(vector<vector<string>> &equations, vector<double> &values, vector<vector<string>> &queries) { map<string, int> literals; for (auto &x : equations) for (auto &y : x) if (literals[y] == 0) literals[y] = literals.size(); int n = literals.size(); using ld = long double; vector<pair<int, ld>> adj[n]; for (size_t i = 0; i < equations.size(); i++) { adj[literals[equations[i][0]] - 1].pb({literals[equations[i][1]] - 1, values[i]}); adj[literals[equations[i][1]] - 1].pb({literals[equations[i][0]] - 1, 1 / values[i]}); } vector<double> ret; for (auto &x : queries) { int a = literals[x[0]]; int b = literals[x[1]]; if (a == 0 || b == 0) ret.pb(-1); else { if (a == b) ret.pb(1); else { queue<pair<int, ld>> Q; --a, --b; Q.push({a, 1}); set<int> vis; vis.insert(a); bool found = false; while (Q.size()) { auto top = Q.front(); if (top.s == b) { found = true; ret.pb(top.s); break; } for (auto &x : adj[top.f]) if (vis.count(x.f) == 0) { vis.insert(x.f); Q.push({x.f, top.s * x.s}); } } if (!found) ret.pb(-1); } } } return ret; } }; #ifdef LOCAL int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t = 1; // cin >> t; Solution S; for (int i = 1; i <= t; ++i) { ; #ifdef LOCAL cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n"; TimeStart = chrono::steady_clock::now(); #endif } return 0; } #endif
27.424242
131
0.387477
[ "vector" ]
98e3a53b813c84d3e040580e8344c778e6918198
6,020
cpp
C++
qtdeclarative/tests/auto/qml/qqmlconsole/tst_qqmlconsole.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtdeclarative/tests/auto/qml/qqmlconsole/tst_qqmlconsole.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtdeclarative/tests/auto/qml/qqmlconsole/tst_qqmlconsole.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QDebug> #include <QQmlEngine> #include <QQmlComponent> #include <QLoggingCategory> #include "../../shared/util.h" class tst_qqmlconsole : public QQmlDataTest { Q_OBJECT public: tst_qqmlconsole() {} private slots: void logging(); void tracing(); void profiling(); void testAssert(); void exception(); private: QQmlEngine engine; }; void tst_qqmlconsole::logging() { QUrl testUrl = testFileUrl("logging.qml"); QLoggingCategory loggingCategory("qml"); QVERIFY(loggingCategory.isDebugEnabled()); QVERIFY(loggingCategory.isWarningEnabled()); QVERIFY(loggingCategory.isCriticalEnabled()); QTest::ignoreMessage(QtDebugMsg, "console.debug"); QTest::ignoreMessage(QtDebugMsg, "console.log"); QTest::ignoreMessage(QtInfoMsg, "console.info"); QTest::ignoreMessage(QtWarningMsg, "console.warn"); QTest::ignoreMessage(QtCriticalMsg, "console.error"); QTest::ignoreMessage(QtDebugMsg, "console.count: 1"); QTest::ignoreMessage(QtDebugMsg, ": 1"); QTest::ignoreMessage(QtDebugMsg, "console.count: 2"); QTest::ignoreMessage(QtDebugMsg, ": 2"); QTest::ignoreMessage(QtDebugMsg, "[1,2]"); QTest::ignoreMessage(QtDebugMsg, "{\"a\":\"hello\",\"d\":1}"); QTest::ignoreMessage(QtDebugMsg, "undefined"); QTest::ignoreMessage(QtDebugMsg, "12"); QTest::ignoreMessage(QtDebugMsg, "function() { [code] }"); QTest::ignoreMessage(QtDebugMsg, "true"); // Printing QML object prints out the class/type of QML object with the memory address // QTest::ignoreMessage(QtDebugMsg, "QtObject_QML_0(0xABCD..)"); // QTest::ignoreMessage(QtDebugMsg, "[object Object]"); QTest::ignoreMessage(QtDebugMsg, "1 pong! [object Object]"); QTest::ignoreMessage(QtDebugMsg, "1 [ping,pong] [object Object] 2"); QQmlComponent component(&engine, testUrl); QObject *object = component.create(); QVERIFY(object != 0); delete object; } void tst_qqmlconsole::tracing() { QUrl testUrl = testFileUrl("tracing.qml"); QString traceText = QString::fromLatin1("tracing (%1:%2)\n").arg(testUrl.toString()).arg(42) + QString::fromLatin1("onCompleted (%1:%2)").arg(testUrl.toString()).arg(46); QTest::ignoreMessage(QtDebugMsg, qPrintable(traceText)); QQmlComponent component(&engine, testUrl); QObject *object = component.create(); QVERIFY(object != 0); delete object; } void tst_qqmlconsole::profiling() { QUrl testUrl = testFileUrl("profiling.qml"); // profiling() QTest::ignoreMessage(QtWarningMsg, "Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX."); QTest::ignoreMessage(QtWarningMsg, "Ignoring console.profileEnd(): the debug service is disabled."); QQmlComponent component(&engine, testUrl); QObject *object = component.create(); QVERIFY(object != 0); delete object; } void tst_qqmlconsole::testAssert() { QUrl testUrl = testFileUrl("assert.qml"); // assert() QString assert1 = "This will fail\n" + QString::fromLatin1("onCompleted (%1:%2)").arg(testUrl.toString()).arg(46); QString assert2 = "This will fail too\n" + QString::fromLatin1("assertFail (%1:%2)\n").arg(testUrl.toString()).arg(39) + QString::fromLatin1("onCompleted (%1:%2)").arg(testUrl.toString()).arg(51); QTest::ignoreMessage(QtCriticalMsg, qPrintable(assert1)); QTest::ignoreMessage(QtCriticalMsg, qPrintable(assert2)); QQmlComponent component(&engine, testUrl); QObject *object = component.create(); QVERIFY(object != 0); delete object; } void tst_qqmlconsole::exception() { QUrl testUrl = testFileUrl("exception.qml"); // exception() QString exception1 = "Exception 1\n" + QString::fromLatin1("onCompleted (%1:%2)").arg(testUrl.toString()).arg(43); QString exception2 = "Exception 2\n" + QString::fromLatin1("exceptionFail (%1:%2)\n").arg(testUrl.toString()).arg(38) + QString::fromLatin1("onCompleted (%1:%2)").arg(testUrl.toString()).arg(48); QTest::ignoreMessage(QtCriticalMsg, qPrintable(exception1)); QTest::ignoreMessage(QtCriticalMsg, qPrintable(exception2)); QQmlComponent component(&engine, testUrl); QObject *object = component.create(); QVERIFY(object != 0); delete object; } QTEST_MAIN(tst_qqmlconsole) #include "tst_qqmlconsole.moc"
35.411765
138
0.680897
[ "object" ]
98e5b6ce8d394b0f1569e0540d62a0b15a7787e4
7,955
cpp
C++
aslam_nonparametric_estimation/bsplines_python/src/BSplinePython.cpp
JzHuai0108/kalibr
32d095162408c90ebf0c49522d27732ffec8f35f
[ "BSD-4-Clause" ]
10
2021-08-20T21:12:22.000Z
2022-03-18T03:20:25.000Z
aslam_nonparametric_estimation/bsplines_python/src/BSplinePython.cpp
JzHuai0108/kalibr
32d095162408c90ebf0c49522d27732ffec8f35f
[ "BSD-4-Clause" ]
null
null
null
aslam_nonparametric_estimation/bsplines_python/src/BSplinePython.cpp
JzHuai0108/kalibr
32d095162408c90ebf0c49522d27732ffec8f35f
[ "BSD-4-Clause" ]
4
2021-08-17T12:16:25.000Z
2021-11-06T02:52:35.000Z
#include <numpy_eigen/boost_python_headers.hpp> #include <bsplines/BSpline.hpp> using namespace bsplines; using namespace boost::python; // Function wrappers turn std::pairs into tuples. boost::python::tuple timeInterval1(const bsplines::BSpline * bs) { std::pair<double,double> ti = bs->timeInterval(); return boost::python::make_tuple(ti.first,ti.second); } boost::python::tuple timeInterval2(const bsplines::BSpline * bs, int i) { std::pair<double,double> ti = bs->timeInterval(i); return boost::python::make_tuple(ti.first,ti.second); } template <class T> class BiFunction { private: T biVector_; public: BiFunction(const T & biVector): biVector_(biVector) { } double getBi(int i){ // Note this is normally a VectorXd // So dynamic rows and 1 column return biVector_.coeff(i,0); } }; boost::python::object getBiFunction(const bsplines::BSpline * bs, double t) { typedef Eigen::CwiseNullaryOp <BiVector, Eigen::VectorXd> T; return boost::python::make_function(boost::bind(&BiFunction<T>::getBi, BiFunction<T>(bs->getBiVector(t)), _1) , boost::python::default_call_policies(), boost::mpl::vector2<double,int>() ); } boost::python::object getCumulativeBiFunction(const bsplines::BSpline * bs, double t) { typedef Eigen::CwiseNullaryOp <BiVector, Eigen::VectorXd> T; return boost::python::make_function(boost::bind(&BiFunction<T>::getBi, BiFunction<T>(bs->getCumulativeBiVector(t)), _1) , boost::python::default_call_policies(), boost::mpl::vector2<double,int>() ); } void import_bspline_python() { // Function pointers are necessary for boost::python to distinguish between // overloaded functions. int (BSpline::*numValidTimeSegments1)(int) const = &BSpline::numValidTimeSegments; int (BSpline::*numValidTimeSegments2)() const = &BSpline::numValidTimeSegments; class_<BSpline>("BSpline",init<int>()) .def("splineOrder",&BSpline::splineOrder, "The order of the spline") .def("polynomialDegree", &BSpline::polynomialDegree, "The degree of the polynomial spline") .def("minimumKnotsRequired", &BSpline::minimumKnotsRequired, "The minimum number of knots required based on the spline order") .def("numCoefficientsRequired", &BSpline::numCoefficientsRequired, "The number of coefficients required for a specified number of valid time segments") .def("numKnotsRequired", &BSpline::numKnotsRequired, "The number of knots required for a target number of valid time segments") .def("numValidTimeSegments", numValidTimeSegments1, "The number of valid time segments for a given number of knots") .def("numValidTimeSegments", numValidTimeSegments2, "The number of valid time segments for the current knot sequence") .def("setKnotVectorAndCoefficients", &BSpline::setKnotVectorAndCoefficients, "Sets the knot vector and spline coefficients") .def("knots", &BSpline::knotVector, "returns the current knot sequence") .def("coefficients", &BSpline::coefficients, "returns the current coefficient matrix", return_value_policy<copy_const_reference>()) .def("t_min", &BSpline::t_min, "The minimum time that the spline is well-defined on") .def("t_max", &BSpline::t_max, "The maximum time that the spline is well-defined on") .def("eval", &BSpline::eval, "Evaluate the spline curve at a point in time") .def("evalD", &BSpline::evalD, "Evaluate a spline curve derivative at a point in time") .def("Phi", &BSpline::Phi, "Evaluate the local basis matrix at a point in time") .def("localBasisMatrix", &BSpline::localBasisMatrix, "Evaluate the local basis matrix at a point in time") .def("localCoefficientMatrix", &BSpline::localCoefficientMatrix, "Get the matrix of locally-active coefficients for a specified time in matrix form") .def("localCoefficientVector", &BSpline::localCoefficientVector, "Get the stacked vector of locally-active coefficients for a specified time.") .def("segmentCoefficientVector", &BSpline::localCoefficientVector, "Get the stacked vector of locally-active coefficients for a specified segment.") .def("initSpline", &BSpline::initSpline, "Initialize the spline to interpolate a set of points") .def("initSpline3", &BSpline::initSpline3, "Initialize the spline to interpolate a set of points") .def("initSplineSparse", &BSpline::initSplineSparse, "Initialize the spline to interpolate a set of points (Sparse Solution)") .def("initSplineSparseKnots", &BSpline::initSplineSparseKnots, "Initialize the spline to interpolate a set of points with a given knot sequence. (Sparse Solution)") .def("basisMatrix", &BSpline::basisMatrix, "Get the basis matrix active on the ith time segment.", return_value_policy<copy_const_reference>()) .def("timeInterval", &timeInterval1, "Returns a tuple with the time interval that the spline is well-defined on.") .def("timeInterval", &timeInterval2, "Returns a tuple with the time interval of the ith segment.") .def("addCurveSegment", &BSpline::addCurveSegment, "Adds a curve segment on the right that interpolates the given point at the given time.") .def("removeCurveSegment", &BSpline::removeCurveSegment, "removes a curve segment on the left") .def("setLocalCoefficientVector", &BSpline::setLocalCoefficientVector, "Sets the local coefficient vector for a specified time") .def("localVvCoefficientVectorIndices", &BSpline::localVvCoefficientVectorIndices, "") .def("localCoefficientVectorIndices", &BSpline::localCoefficientVectorIndices, "For the elements of a local coefficient vector, this gets the indices into the full coefficient vector") .def("segmentVvCoefficientVectorIndices", &BSpline::segmentVvCoefficientVectorIndices, "") .def("segmentCoefficientVectorIndices", &BSpline::segmentCoefficientVectorIndices, "For the elements of a segment coefficient vector, this gets the indices into the full coefficient vector") .def("setCoefficientVector", &BSpline::setCoefficientVector, "Sets the full stacked coefficient vector of the spline") .def("setCoefficientMatrix", &BSpline::setCoefficientMatrix, "Sets the full coefficient matrix of the spline") .def("addCurveSegment2", &BSpline::addCurveSegment2, "") .def("initSpline2", &BSpline::initSpline2, "") .def("evalI", &BSpline::evalI, "") .def("evalIntegral", &BSpline::evalIntegral, "") .def("Vi",&BSpline::Vi,"") .def("Mi", &BSpline::Mi, "") .def("Bij", &BSpline::Bij, "") .def("U", &BSpline::U, "U(time, derivativeOrder)") .def("u", &BSpline::u, "") .def("Di", &BSpline::Di, "") .def("Dii", &BSpline::Dii, "") .def("getLocalBi", &BSpline::getLocalBiVector, "getLocalBi(time)") .def("getLocalCumulativeBi", &BSpline::getLocalCumulativeBiVector, "getLocalCumulativeBi(time)") .def("getBiFunction", &getBiFunction, "getBiFunction(time)") .def("getCumulativeBiFunction", &getCumulativeBiFunction, "getBiFunction(time)") .def("segmentIndex", &BSpline::segmentIndex, "") .def("segmentQuadraticIntegral", &BSpline::segmentQuadraticIntegral, "") .def("segmentIntegral", &BSpline::segmentIntegral, "") .def("segmentQuadraticIntegralDiag", &BSpline::segmentQuadraticIntegralDiag, "") .def("curveQuadraticIntegral", &BSpline::curveQuadraticIntegral, "") .def("curveQuadraticIntegralDiag", &BSpline::curveQuadraticIntegralDiag, "") .def("curveQuadraticIntegralSparse", &BSpline::curveQuadraticIntegralSparse, "") .def("curveQuadraticIntegralDiagSparse", &BSpline::curveQuadraticIntegralDiagSparse, "") .def("coefficientVectorLength", &BSpline::coefficientVectorLength, "") .def("saveSplineToFile", &BSpline::saveSplineToFile) .def("initSplineFromFile", &BSpline::initSplineFromFile) .def("initConstantSpline", &BSpline::initConstantSpline, "initConstantSpline(double t_min, double t_max, int numSegments, const Eigen::VectorXd & constant") .def("numVvCoefficients", &BSpline::numVvCoefficients, "numVvCoefficients()"); //.def("", &BSpline::, "") }
61.192308
194
0.740541
[ "object", "vector" ]
98e631f302be80022c7656d2684267e527a7b7dd
1,774
cpp
C++
07/b.cpp
mratkovic/advent_of_code_2017
d50c49e8f2512c5a53f12e6640e5765bf7b025d0
[ "MIT" ]
null
null
null
07/b.cpp
mratkovic/advent_of_code_2017
d50c49e8f2512c5a53f12e6640e5765bf7b025d0
[ "MIT" ]
null
null
null
07/b.cpp
mratkovic/advent_of_code_2017
d50c49e8f2512c5a53f12e6640e5765bf7b025d0
[ "MIT" ]
null
null
null
#include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <unordered_map> #include <string> #include <map> #include <sstream> #include <assert.h> using namespace std; unordered_map<string, int> w; unordered_map<string, vector<string>> e; unordered_map<string, int> in_edges; unordered_map<string, int> total; void dfs(string node) { if (e[node].size() == 0) return; map<int, int> cnts; map<int, string> who; int sum = 0; for (auto& ch : e[node]) { dfs(ch); cnts[total[ch]]++; who[total[ch]] = ch; sum += total[ch]; } if (cnts.size() != 1) { auto cmp = [](auto&a, auto& b) { return a.second < b.second; }; auto mini = *min_element(cnts.begin(), cnts.end(), cmp); auto maxi = *max_element(cnts.begin(), cnts.end(), cmp); int expected = maxi.first; int got = mini.first; int diff = expected - got; string wrong_node = who[got]; cout << "ANS: " << w[wrong_node] + diff << endl; exit(0); } total[node] += sum; } int main(int argc, char* argv[]) { string s; for (int i = 0; getline(cin, s); ++i) { vector<string> in(istream_iterator<string>{istringstream(s)}, {}); string name = in[0]; w.emplace(name, stoi(in[1].substr(1, in[1].size() - 2))); total.emplace(name, w[name]); vector<string> ch; transform(in.begin() + min(int(in.size()), 3), in.end(), back_inserter(ch), [](auto& s) { if (s.back() == ',') return s.substr(0, s.size() - 1); return s; }); e.emplace(name, ch); in_edges[name] = max(in_edges[name], 0); for_each(ch.begin(), ch.end(), [](auto& child) { in_edges[child]++; }); } auto& ans = *min_element(in_edges.begin(), in_edges.end(), [](auto&a, auto& b) { return a.second < b.second; }); assert(ans.second == 0); string root = ans.first; dfs(root); return 0; }
26.477612
113
0.617813
[ "vector", "transform" ]
98ed98adc3055f700843d521267020a5611e9352
5,446
cpp
C++
cplusplus/src/util/Pathfinder.cpp
csci-599-applied-ml-for-games/DeepRTS
595ce5105cfa36030f8102d659a0d59e6f707686
[ "MIT" ]
null
null
null
cplusplus/src/util/Pathfinder.cpp
csci-599-applied-ml-for-games/DeepRTS
595ce5105cfa36030f8102d659a0d59e6f707686
[ "MIT" ]
1
2019-11-25T06:40:34.000Z
2019-12-03T03:59:13.000Z
cplusplus/src/util/Pathfinder.cpp
maswin/DeepRTS
9922078951810d65fc212a0c2ee32f75765d3cd0
[ "MIT" ]
1
2019-12-03T04:54:57.000Z
2019-12-03T04:54:57.000Z
// // Created by Per-Arne on 26.02.2017. // #include <list> #include <queue> #include <unordered_map> #include <vector> #include <map> #include <set> #include "Pathfinder.h" #include "../environment/Tile.h" #include "../util/PriorityQueue.hpp" #include "../Constants.h" #include "../environment/Tilemap.h" bool Pathfinder::aStar(std::vector<Tile *> &constructedPath, Tile *start, Tile *goal) { std::vector<Tile *> path; std::unordered_map<Tile*, Tile*> came_from; std::unordered_map<Tile*, double> cost_so_far; auto frontier = PriorityQueue<Tile*, double>(); frontier.put(start, 0); came_from[start] = NULL; cost_so_far[start] = 0; while (!frontier.empty()) { Tile *current = frontier.get(); if (current == goal) { constructedPath = reconstruct_path(start, goal, came_from); return true; } std::vector<Tile*> neighbors = current->getTilemap().neighbors(*current, Constants::Pathfinding::Walkable); for (auto next : neighbors) { double new_cost = cost_so_far.at(current) + 1; if (!cost_so_far.count(next) || new_cost < cost_so_far.at(next)) { cost_so_far[next] = new_cost; double priority = new_cost + heuristic(goal, next) + crossover(next, start, goal); frontier.put(next, priority); came_from[next] = current; } } } return false; } double Pathfinder::heuristic(Tile *goal, Tile *next) { int dx = abs(next->x - goal->x); int dy = abs(next->y - goal->y); return (dx + dy) + (1 - 2 * 1) * std::min(dx, dy); return abs(goal->x - next->y) + abs(goal->y - next->y); } double Pathfinder::crossover(Tile *current, Tile *start, Tile *goal) { int dx1 = current->x - goal->x; int dy1 = current->y - goal->y; int dx2 = start->x - goal->x; int dy2 = start->y - goal->y; int cross = abs(dx1*dy2 - dx2*dy1); return cross*0.001; } Tile* Pathfinder::find_closest_walkable_tile(Tile *start, Tile *destination, int range) { std::set<Tile *> visited; std::queue<Tile *> queue; Tile *closest = NULL; uint16_t tmpClosest = INT16_MAX; for (int dx = -1; dx <= range; dx++) { for (int dy = -1; dy <= range; dy++) { uint16_t x = destination->x + dx; uint16_t y = destination->y + dy; Tile &subject = destination->getTilemap().getTile(x, y); if (subject.getOccupant()) { continue; } uint16_t dist = start->distance(subject); if (dist < tmpClosest) { closest = &subject; tmpClosest = dist; } } } return closest; } Tile* Pathfinder::find_first_walkable_tile(Tile *start) { /** * This is a breadth-first search which looks for a walkable tile */ std::set<Tile *> visited; std::queue<Tile *> queue; queue.push(start); while(queue.size() > 0) { Tile *current = queue.front(); assert(current); queue.pop(); if (current->isWalkable()) { return current; } const bool is_in = visited.find(current) != visited.end(); if(!is_in) { visited.insert(current); std::vector<Tile*> neighbors = current->getTilemap().neighbors(*current, Constants::Pathfinding::All); for(auto &i : neighbors) { queue.push(i); } } } return NULL; assert(false); // Should not be here. this means algorithm didnt find any closest tile and there should be one } Tile *Pathfinder::find_first_harvestable_tile(Tile *start) { /** * This is a breadth-first search which looks for a walkable tile */ std::set<Tile *> visited; std::queue<Tile *> queue; queue.push(start); while(queue.size() > 0) { Tile *current = queue.front(); queue.pop(); if (current->isHarvestable()) { return current; } const bool is_in = visited.find(current) != visited.end(); if(!is_in) { visited.insert(current); std::vector<Tile*> neighbors = current->getTilemap().neighbors(*current, Constants::Pathfinding::All); for(auto &i : neighbors) { queue.push(i); } } } return NULL; } Tile *Pathfinder::find_first_attackable_tile(Tile *start) { /** * This is a breadth-first search which looks for a walkable tile */ std::set<Tile *> visited; std::queue<Tile *> queue; queue.push(start); while(queue.size() > 0) { Tile *current = queue.front(); queue.pop(); if (current->isAttackable(*start->getOccupant())) { return current; } const bool is_in = visited.find(current) != visited.end(); if(!is_in) { visited.insert(current); std::vector<Tile*> neighbors = current->getTilemap().neighbors(*current, Constants::Pathfinding::All); for(auto &i : neighbors) { queue.push(i); } } } return NULL; } std::vector<Tile*> Pathfinder::reconstruct_path(Tile * start, Tile * goal, std::unordered_map<Tile*, Tile*>& came_from) { std::vector<Tile *> path; Tile *current = goal; path.push_back(current); while (came_from.at(current) != start) { current = came_from.at(current); path.push_back(current); } //path.push_back(start); // optional //std::reverse(path.begin(), path.end()); return path; }
23.174468
119
0.585384
[ "vector" ]
98f2030600a9f614dbe6651dd60c6ffd706d7766
4,314
cpp
C++
clever_algorithms/demos/genetic_algorithm.cpp
GreatV/CleverAlgorithms
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
[ "MIT" ]
2
2021-11-08T00:26:09.000Z
2021-12-21T08:16:43.000Z
clever_algorithms/demos/genetic_algorithm.cpp
GreatV/CleverAlgorithms
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
[ "MIT" ]
null
null
null
clever_algorithms/demos/genetic_algorithm.cpp
GreatV/CleverAlgorithms
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
[ "MIT" ]
null
null
null
#include <iostream> #include <random> #include <vector> #include <string> #include <algorithm> std::random_device rd; std::mt19937 generator(rd()); std::uniform_real_distribution<> distribution(0.0, 1.0); auto random_ = []() { return distribution(generator); }; using candidate_solution = struct candidate_solution_t { std::string bit_string; double fitness = 0.0; }; double onemax(std::string& bit_string) { double sum = 0.0; for (auto& item : bit_string) { if (item == '1') { sum++; } } return sum; } void random_bit_string(std::string& bit_string, const size_t num_bits) { bit_string.clear(); for (size_t i = 0; i < num_bits; ++i) { bit_string.push_back(random_() < 0.5 ? '1' : '0'); } } void binary_tournament(candidate_solution& candidate, std::vector<candidate_solution>& pop) { const auto i = static_cast<size_t>((pop.size() - 1) * random_()); auto j = static_cast<size_t>((pop.size() - 1) * random_()); while (j == i) { j = static_cast<size_t>((pop.size() - 1) * random_()); } candidate = pop[i].fitness > pop[j].fitness ? pop[i] : pop[j]; } void point_mutation(std::string& child, std::string& bit_string, const double rate) { std::string tmp; for (auto& item : bit_string) { tmp.push_back(random_() < rate ? (item == '1' ? '0' : '1') : item); } child = tmp; } void crossover(std::string& child, std::string& parent1, std::string& parent2, const double rate) { if (random_() >= rate) { child = parent1; } const size_t point = 1 + static_cast<size_t>((parent1.size() - 3) * random_()); child.clear(); for (size_t i = 0; i < point; ++i) { child.push_back(parent1[i]); } for (size_t i = point; i < parent1.size(); ++i) { child.push_back(parent2[i]); } } void reproduce(std::vector<candidate_solution>& children, std::vector<candidate_solution>& selected, const size_t pop_size, const double p_cross, const double p_mutation) { children.clear(); for (size_t i = 0; i < selected.size(); ++i) { auto p1 = selected[i]; auto p2 = i % 2 == 0 ? (i == selected.size() - 1 ? selected[0] : selected[i + 1]) : selected[i - 1]; candidate_solution child; crossover(child.bit_string, p1.bit_string, p2.bit_string, p_cross); point_mutation(child.bit_string, child.bit_string, p_mutation); children.push_back(child); if (children.size() >= pop_size) { break; } } } bool cmp(candidate_solution& candidate1, candidate_solution& candidate2) { if (candidate1.fitness > candidate2.fitness) { return true; } return false; } void search(candidate_solution& best, const size_t max_gens, const size_t num_bits, const size_t pop_size, const double p_crossover, const double p_mutation) { std::vector<candidate_solution> population; for (size_t i = 0; i < pop_size; ++i) { candidate_solution candidate; random_bit_string(candidate.bit_string, num_bits); candidate.fitness = onemax(candidate.bit_string); population.push_back(candidate); } std::sort(population.begin(), population.end(), cmp); best = population[0]; for (size_t i = 0; i < max_gens; ++i) { std::vector<candidate_solution> selected; for (size_t j = 0; j < pop_size; ++j) { candidate_solution tmp_candidate; binary_tournament(tmp_candidate, population); selected.push_back(tmp_candidate); } std::vector<candidate_solution> children; reproduce(children, selected, pop_size, p_crossover, p_mutation); for (auto& item : children) { item.fitness = onemax(item.bit_string); } std::sort(children.begin(), children.end(), cmp); if (children[0].fitness >= best.fitness) { best = children[0]; } population = children; std::cout << " > gen " << i << ", best: " << best.fitness << ", " << best.bit_string << std::endl; if (static_cast<size_t>(best.fitness) == num_bits) break; } } int main(int argc, char* argv[]) { // problem configuration const size_t num_bits = 64; // algorithm configuration const size_t max_gens = 100; const size_t pop_size = 100; const double p_crossover = 0.98; const double p_mutation = 1.0 / num_bits; // execute the algorithm candidate_solution best; search(best, max_gens, num_bits, pop_size, p_crossover, p_mutation); std::cout << "Done. Solution: f = " << best.fitness << ", s = " << best.bit_string << std::endl; return 0; }
23.445652
106
0.668057
[ "vector" ]
98fbc794b05375a7b206c8f17eda8d0a29e7aba9
4,602
cxx
C++
MSEL_src/MSEL_core/bpro1_parameters.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
4
2020-04-23T12:28:41.000Z
2021-06-07T05:54:16.000Z
MSEL_src/MSEL_core/bpro1_parameters.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
null
null
null
MSEL_src/MSEL_core/bpro1_parameters.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
1
2017-06-05T18:00:21.000Z
2017-06-05T18:00:21.000Z
// This is brld/bpro1/bpro1_parameters.cxx //: // \file #include "bpro1_parameters.h" #include <vcl_utility.h> #include <vcl_iostream.h> #include <vcl_sstream.h> //: Output stream operator for bpro1_params vcl_ostream& operator<<(vcl_ostream& os, const bpro1_param& p) { os << "parameter{\n Description: " << p.description(); if(p.has_bounds()) os << "\n Range: " << p.min_str() << " to " << p.max_str(); os << "\n Default: " << p.default_str(); os << "\n Value: " << p.value_str() << "\n}\n"; return os; } //=========================================================================================== //: Constructor bpro1_parameters::bpro1_parameters() { } //: Destructor bpro1_parameters::~bpro1_parameters() { for( vcl_vector< bpro1_param * >::iterator it = param_list_.begin(); it != param_list_.end(); it++ ) { delete (*it); } } //: Deep copy constructor bpro1_parameters::bpro1_parameters(const bpro1_parameters_sptr& old_params) { for( vcl_vector< bpro1_param * >::iterator it = old_params->param_list_.begin(); it != old_params->param_list_.end(); it++ ) { //deep copy this param bpro1_param * new_param = (*it)->clone(); param_list_.push_back( new_param ); name_param_map_.insert( vcl_pair< vcl_string , bpro1_param* >( new_param->name() , new_param ) ); } } //: Returns true if a parameter exists with \p flag bool bpro1_parameters::valid_parameter( const vcl_string& name ) const { vcl_map< vcl_string , bpro1_param * >::const_iterator itr = name_param_map_.find( name ); return (itr != name_param_map_.end()); } //: Reset all parameters to their default values bool bpro1_parameters::reset_all() { for( vcl_vector< bpro1_param * >::iterator it = param_list_.begin(); it != param_list_.end(); it++ ) { (*it)->reset(); } return true; } //: Reset the parameter named \p name to its default value bool bpro1_parameters::reset( const vcl_string& name ) { vcl_map< vcl_string , bpro1_param * >::iterator it = name_param_map_.find( name ); if( it == name_param_map_.end() ) { return false; } it->second->reset(); return true; } //: Return a vector of base class pointers to the parameters vcl_vector< bpro1_param* > bpro1_parameters::get_param_list() const { return param_list_; } //: Return the description of the parameter named \p name vcl_string bpro1_parameters::get_desc( const vcl_string& name ) const { vcl_map< vcl_string , bpro1_param * >::const_iterator it = name_param_map_.find( name ); if( it == name_param_map_.end() ) { return ""; } return it->second->description(); } //: Print all parameters to \p os void bpro1_parameters::print_all(vcl_ostream& os) const { for( vcl_vector< bpro1_param * >::const_iterator it = param_list_.begin(); it != param_list_.end(); it++ ) { os << *(*it); } } //: Add parameter helper function bool bpro1_parameters::add( bpro1_param* param ) { if( !param ) return false; vcl_string name = param->name(); vcl_string desc = param->description(); if( name_param_map_.find( name ) != name_param_map_.end() || desc == "" || name == "" ) { delete param; return false; } param_list_.push_back( param ); name_param_map_.insert( vcl_pair< vcl_string , bpro1_param* >( name , param ) ); return true; } //: Set the value of the existing parameter named \p name bool bpro1_parameters_set_value_from_str(bpro1_parameters& pars, const vcl_string& name , const vcl_string& value_str) { vcl_map< vcl_string , bpro1_param* >::iterator it = pars.get_param_map().find(name); if (it == pars.get_param_map().end()) { return false; } bpro1_param* param = it->second; if( param ){ return param->parse_value_str(value_str); } return false; } //=========================================================================================== //: Less than operator for bpro1_filepath objects bool operator<( const bpro1_filepath& lhs, const bpro1_filepath& rhs ) { return lhs.path < rhs.path; } //: Less than or equal to operator for bpro1_filepath objects bool operator<=( const bpro1_filepath& lhs, const bpro1_filepath& rhs ) { return lhs.path <= rhs.path; } //: Output stream operator for bpro1_filepath objects vcl_ostream& operator<<( vcl_ostream& strm, const bpro1_filepath& fp ) { strm << fp.path << '\n' << fp.ext << vcl_ends; return strm; } //: Input stream operator for bpro1_filepath objects vcl_istream& operator>>( vcl_istream& strm, const bpro1_filepath& fp ) { strm >> fp.path >> fp.ext; return strm; }
23.721649
118
0.644937
[ "vector" ]
98fc1e6d174bf748046248100503cc1f97589ee4
1,028
hpp
C++
Android/source/engine/src/main/jni/face/faceLandmark.hpp
iotbo/TengineKit
b82c3758360ef37cb219d487d3858a4c1b4effe7
[ "Apache-2.0" ]
null
null
null
Android/source/engine/src/main/jni/face/faceLandmark.hpp
iotbo/TengineKit
b82c3758360ef37cb219d487d3858a4c1b4effe7
[ "Apache-2.0" ]
null
null
null
Android/source/engine/src/main/jni/face/faceLandmark.hpp
iotbo/TengineKit
b82c3758360ef37cb219d487d3858a4c1b4effe7
[ "Apache-2.0" ]
null
null
null
// // Created by zhangjun on 2020/2/12. // #ifndef FACE_LANDMARK_HPP #define FACE_LANDMARK_HPP #include "data.hpp" #include <iostream> #include <memory> #include <string.h> #include <vector> // Tengine #include "c_api.h" #include "faceDetect.hpp" typedef struct FaceLandmarkInfo { float landmarks[212 * 2]; float head_x; float head_y; float head_z; float lefteye_close_state; float righteye_close_state; float mouth_close_state; float mouth_bigopen_state; } FaceLandmarkInfo; class faceLandmark { public: faceLandmark(const std::string &modelPath, context_t context = nullptr, int numThread = 2); ~faceLandmark(); void landmark(const uint8_t *faceImage, FaceInfo &faceInfo); int landmarkW = 112; int landmarkH = 112; int landmarkBpp = 1; private: graph_t graph = nullptr; tensor_t inputTensor = nullptr; const float meanVal[3] = {127.5, 127.5, 127.5}; const float normVal[3] = {1.0 / 128.0, 1.0 / 128.0, 1.0 / 128.0}; int num_thread; }; #endif // FACE_LANDMARKS_HPP
20.56
73
0.706226
[ "vector" ]
98fc4f69f2f099ac463e8130385e6d5aa648176d
2,583
cpp
C++
2020/day15/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2020/day15/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2020/day15/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
#include <lib/file_util.hpp> #include <chain/chain.hpp> #include <lib/algorithms.hpp> #include <iostream> #include <vector> #include <string> #include <array> #include <map> #include <bitset> #include <cmath> int main(int argc, char* argv[]) { std::vector<std::string> args{argv, argv + argc}; if(args.size() != 2) { std::cout << args[0] << " <input_file>" << std::endl; return 0; } auto contents = file::read(args[1]); auto numbers_parts = chain::str::split(contents, ','); { std::map<uint64_t, uint64_t> spoken_numbers{}; bool first{true}; size_t turn{0}; uint64_t turn_seen{0}; uint64_t last{0}; for(const auto& number : numbers_parts) { auto value = chain::str::to_number<uint64_t>(number).value(); spoken_numbers.insert_or_assign(value, ++turn); last = value; } while(turn < 2020) { uint64_t next{0}; ++turn; if(!first) { next = turn - turn_seen - 1; } auto [iter, emplaced] = spoken_numbers.emplace(next, turn); first = emplaced; // If this has been seen before, update its turn seen, but cache the old turn seen. if(!first) { turn_seen = iter->second; iter->second = turn; } last = next; } std::cout << "2020th number spoke is " << last << "\n"; } { std::map<uint64_t, uint64_t> spoken_numbers{}; bool first{true}; size_t turn{0}; uint64_t turn_seen{0}; uint64_t last{0}; for(const auto& number : numbers_parts) { auto value = chain::str::to_number<uint64_t>(number).value(); spoken_numbers.insert_or_assign(value, ++turn); last = value; } while(turn < 30000000) { uint64_t next{0}; ++turn; if(!first) { next = turn - turn_seen - 1; } auto [iter, emplaced] = spoken_numbers.emplace(next, turn); first = emplaced; // If this has been seen before, update its turn seen, but cache the old turn seen. if(!first) { turn_seen = iter->second; iter->second = turn; } last = next; } std::cout << "30000000th number spoke is " << last << "\n"; } return 0; }
24.140187
95
0.492451
[ "vector" ]
98fffa8b8b0f8db8383daabf463ded9405cd97bf
11,081
cpp
C++
render/ren_aal.cpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
render/ren_aal.cpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
render/ren_aal.cpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
#include "client/resbase.hpp" #include "utils/noise.hpp" #include "vaslib/vas_cpp_utils.hpp" #include "vaslib/vas_log.hpp" #include "ren_aal.hpp" #include "camera.hpp" #include "control.hpp" #include "shader.hpp" #include "texture.hpp" struct Noise { Noise() { tex.target = GL_TEXTURE_3D; } void generate(float cell_size) { size = 32; depth = 20; ck = cell_size; std::vector<uint8_t> img_px( size * size * depth * 3 ); TimeSpan time0 = TimeSpan::current(); std::vector<float> prev_vals( size * size * 2 ); RandomGen rnd; for (int z = 0; z < depth; ++z) for (int y = 0; y < size; ++y) for (int x = 0; x < size; ++x) { float nH = rnd.range_n(); float nV = rnd.range_n(); float& pH = prev_vals[(y * size + x)*2 + 0]; float& pV = prev_vals[(y * size + x)*2 + 1]; float H, V; if (!z) { H = pH = nH; V = pV = nV; } else { auto calc = [](float& old, float cur) { float v = cur - old; float len = std::fabs(v); if (len > 0.3) v *= 0.3 / len; v += old; old = cur; return v; }; H = calc(pH, nH); V = calc(pV, nV); } H = lerp<float>(170, 210, H) / 360; V = lerp(0.15, 0.30, V); uint8_t* px = img_px.data() + (z * (size * size) + y * size + x)*3; uint32_t px_val = FColor(H, 1, V).hsv_to_rgb().to_px(); px[0] = px_val >> 24; px[1] = px_val >> 16; px[2] = px_val >> 8; } VLOGI("RenAAL generation time: {:.3f} seconds", (TimeSpan::current() - time0).seconds()); tex.bind(); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB, size, size, depth, 0, GL_RGB, GL_UNSIGNED_BYTE, img_px.data()); tex.set_byte_size( size * size * depth * 3 ); } bool check() { return true; } void setup(Shader& sh, TimeSpan passed) { glActiveTexture(GL_TEXTURE1); tex.bind(); sh.set1f("t", t / depth * 0.7); t += passed.seconds(); auto& cam = RenderControl::get().get_world_camera(); auto ssz = RenderControl::get().get_size(); vec2fp ssz_k = {float(ssz.x) / ssz.y, 1}; ssz_k /= ck; vec2fp scr_z = cam.coord_size(); vec2fp cpos = cam.get_state().pos; cpos.y = -cpos.y; cpos *= 0.8; // looks bit better for some reason sh.set2f("offset", cpos / (scr_z / ssz_k)); sh.set2f("scrk", ssz_k.x, ssz_k.y); } private: int size = 1; // x,y int depth = 1; // z (time) float ck = 1; // cell size GLA_Texture tex; float t = 0.f; }; class RenAAL_Impl : public RenAAL { public: struct Obj { size_t off, count; // Vertices in buffer uint32_t clr; float clr_mul; }; struct InstObj { Transform tr; size_t id; FColor clr; }; GLA_VertexArray vao; std::vector<float> data_f; // Buffer data to send size_t objs_off = 0; ///< Last vertex count std::vector<Obj> objs; std::unique_ptr<Shader> sh, sh_inst; uint32_t prev_clr = 0; float prev_clr_mul = 0; GLA_Texture tex; // for instanced drawing GLA_VertexArray inst_vao; std::vector<std::pair<size_t, size_t>> inst_objs; std::vector<InstObj> inst_q; bool inst_locked = false; // prevent render while building in process // for grid GLA_Framebuffer fbo; GLA_Texture fbo_clr; std::unique_ptr<Shader> fbo_sh; RAII_Guard fbo_g; Noise fbo_noi; void add_line(vec2fp p0, vec2fp p1, float width, float wpar, float aa_width) { vec2fp n; float len; if (!p0.equals(p1, 1e-5f)) { n = p1 - p0; len = n.fastlen(); vec2fp dir = n; dir *= 0.5 * aa_width / len; p0 -= dir; p1 += dir; n.rot90cw(); n /= len; } else { n = {1, 0}; len = 0.f; p0.x -= width / 2; p1.x += width / 2; n.rot90cw(); } vec2fp u = n; n *= width * 0.5f; float x0 = p0.x + n.x, y0 = p0.y + n.y, x1 = p1.x + n.x, y1 = p1.y + n.y, x2 = p0.x - n.x, y2 = p0.y - n.y, x3 = p1.x - n.x, y3 = p1.y - n.y; float endk = (len + aa_width) / aa_width; #define PF(X) data_f.push_back(X) #define PI PF // first triangle (11 - 21 - 12) PF( x0 ); PF( y0 ); PF(wpar); PF(endk); PI( u.x); PI( u.y); PI(-1); PF( x1 ); PF( y1 ); PF(wpar); PF(endk); PI( u.x); PI( u.y); PI( 1); PF( x2 ); PF( y2 ); PF(wpar); PF(endk); PI(-u.x); PI(-u.y); PI(-1); // second triangle (21 - 12 - 22) PF( x1 ); PF( y1 ); PF(wpar); PF(endk); PI( u.x); PI( u.y); PI( 1); PF( x2 ); PF( y2 ); PF(wpar); PF(endk); PI(-u.x); PI(-u.y); PI(-1); PF( x3 ); PF( y3 ); PF(wpar); PF(endk); PI(-u.x); PI(-u.y); PI( 1); } void add_objs(size_t n, uint32_t clr, float clr_mul) { n *= 6; // vertices per object if (prev_clr == clr && aequ(prev_clr_mul, clr_mul, 1.f/255)) objs.back().count += n; else { prev_clr = clr; prev_clr_mul = clr_mul; objs.push_back({ objs_off, n, clr, clr_mul }); } objs_off += n; } size_t add_chain(const std::vector<vec2fp>& ps, bool loop, float width, float aa_width) { if (aa_width < 1) aa_width = 1; width += aa_width; float wpar = width / aa_width; size_t dsz = ps.size() * 6 * 7; if (4096 > dsz) dsz = 4096; reserve_more_block(objs, 1024); reserve_more_block(data_f, dsz); size_t n = ps.size(); if (loop) ++n; for (size_t i = 1; i < n; ++i) add_line(ps[i%ps.size()], ps[i-1], width, wpar, aa_width); return n; } RenAAL_Impl() { auto buf = std::make_shared<GLA_Buffer>(0); vao.set_attribs({ {buf, 4}, {buf, 3} }); sh = Shader::load("aal", {}, true); sh_inst = Shader::load("aal_inst", {}, true); reinit_glow(); // for grid fbo_sh = Shader::load("pp/aal_grid", {[](Shader& sh){ sh.set1i("noi", 1); }}); fbo_g = RenderControl::get().add_size_cb([this]{ fbo_clr.set(GL_RGBA, RenderControl::get_size(), 0, 4); }, true); fbo.bind(); fbo.attach_tex(GL_COLOR_ATTACHMENT0, fbo_clr); } void reinit_glow() { const int n = 200; float data[n]; auto init = [&](auto f) { float x1 = f(1); for (int i=0; i<n; ++i) { float x = (i + 1); x /= n; float y = f(x) / x1; data[i] = y; } }; auto init_old = [&](float c){ float a = 1.f / (c * sqrt(2 * M_PI)); float w = 2 * c * sqrt(2 * log(2)); c = 2 * c * c; init([&](float x){ x = (1 - x) / w; return a * exp(-(x*x) / c); }); }; init_old(0.17); tex.bind(); glTexImage2D(tex.target, 0, GL_R8, n, 1, 0, GL_RED, GL_FLOAT, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Texture::debug_save(tex.tex, "test.png", Texture::FMT_SINGLE); // exit(1); } void draw_line(vec2fp p0, vec2fp p1, uint32_t clr, float width, float aa_width, float clr_mul) { if (!clr) return; if (aa_width < 1) aa_width = 1; width += aa_width; float wpar = width / aa_width; reserve_more_block(objs, 1024); reserve_more_block(data_f, 4096); add_line(p0, p1, width, wpar, aa_width); add_objs(1, clr, clr_mul); } void draw_chain(const std::vector<vec2fp>& ps, bool loop, uint32_t clr, float width, float aa_width, float clr_mul) { if (!clr || ps.size() < 2) return; size_t n = add_chain(ps, loop, width, aa_width); add_objs(n-1, clr, clr_mul); } void render() { if (inst_locked) return; // draw to buffer glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE); glBlendEquation(GL_MAX); const float *mx = RenderControl::get().get_world_camera().get_full_matrix(); const float scrmul = 1.f;//cam->get_state().mag; glActiveTexture(GL_TEXTURE0); tex.bind(); if (!objs.empty()) { vao.bufs[0]->update( data_f.size(), data_f.data() ); vao.bind(); sh->bind(); sh->set4mx("proj", mx); sh->set1f("scrmul", scrmul); for (auto& o : objs) { sh->set_rgba("clr", o.clr, o.clr_mul); glDrawArrays(GL_TRIANGLES, o.off, o.count); } data_f.clear(); objs_off = 0; objs.clear(); prev_clr = 0; prev_clr_mul = 0; } if (!inst_q.empty()) { inst_vao.bind(); sh_inst->bind(); sh_inst->set4mx("proj", mx); sh_inst->set1f("scrmul", scrmul); for (auto& o : inst_q) { auto cs = cossin_lut(o.tr.rot); sh_inst->set4f("obj_tr", o.tr.pos.x, o.tr.pos.y, cs.x, cs.y); sh_inst->set_clr("clr", o.clr); auto& p = inst_objs[o.id]; glDrawArrays(GL_TRIANGLES, p.first, p.second); } inst_q.clear(); } } void render_grid(unsigned int fbo_out) { if (!draw_grid) return; if (!fbo_noi.check()) return; if (inst_objs.empty()) return; // draw to buffer fbo.bind(); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE); glBlendEquation(GL_MAX); inst_vao.bind(); const float *mx = RenderControl::get().get_world_camera().get_full_matrix(); const float scrmul = 1.f;//cam->get_state().mag; glActiveTexture(GL_TEXTURE0); tex.bind(); sh_inst->bind(); sh_inst->set4mx("proj", mx); sh_inst->set1f("scrmul", scrmul); // FColor clr(0, 0.8, 1, 0.3); // clr *= clr.a; const FColor clr(1, 1, 1, 1); sh_inst->set4f("obj_tr", 0, 0, 1, 0); sh_inst->set_clr("clr", clr); auto& p = inst_objs[MODEL_LEVEL_GRID]; glDrawArrays(GL_TRIANGLES, p.first, p.second); // draw to screen glBindFramebuffer(GL_FRAMEBUFFER, fbo_out); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); fbo_sh->bind(); fbo_noi.setup(*fbo_sh, RenderControl::get().get_passed()); glActiveTexture(GL_TEXTURE0); fbo_clr.bind(); RenderControl::get().ndc_screen2().bind(); glDrawArrays(GL_TRIANGLES, 0, 6); } void inst_begin(float grid_cell_size) { auto buf = std::make_shared<GLA_Buffer>(0); inst_vao.set_attribs({ {buf, 4}, {buf, 3} }); inst_objs.clear(); fbo_noi.generate(grid_cell_size); inst_locked = true; } void inst_end() { inst_vao.bufs[0]->update( data_f.size(), data_f.data() ); data_f.clear(); data_f.shrink_to_fit(); inst_locked = false; } void inst_add(const std::vector<vec2fp>& ps, bool loop, float width, float aa_width) { add_chain(ps, loop, width, aa_width); } size_t inst_add_end() { size_t last = inst_objs.empty() ? 0 : inst_objs.back().first + inst_objs.back().second; size_t cur = data_f.size() / 7; size_t id = inst_objs.size(); inst_objs.emplace_back(last, cur - last); return id; } void draw_inst(const Transform& tr, FColor clr, size_t id) { reserve_more_block(inst_q, 512); inst_q.push_back({tr, id, clr}); } }; static RenAAL_Impl* rni; RenAAL& RenAAL::get() { if (!rni) LOG_THROW_X("RenAAL::get() null"); return *rni; } RenAAL* RenAAL::init() {return rni = new RenAAL_Impl;} RenAAL::~RenAAL() {rni = nullptr;}
22.800412
116
0.604729
[ "render", "object", "vector", "transform" ]
c71299041747682f1f6e257dca4d86851b303ada
17,635
cpp
C++
src/dune/assimp_mesh.cpp
yangzhengxing/GI
e27124740ceb7dac04171a9685cc3f0c7c308066
[ "MIT", "BSD-3-Clause" ]
193
2015-03-01T08:11:22.000Z
2022-03-23T16:01:25.000Z
src/dune/assimp_mesh.cpp
yangzhengxing/GI
e27124740ceb7dac04171a9685cc3f0c7c308066
[ "MIT", "BSD-3-Clause" ]
1
2018-02-18T04:23:11.000Z
2018-02-25T21:27:54.000Z
src/dune/assimp_mesh.cpp
yangzhengxing/GI
e27124740ceb7dac04171a9685cc3f0c7c308066
[ "MIT", "BSD-3-Clause" ]
30
2015-01-07T00:42:18.000Z
2021-09-22T12:43:28.000Z
/* * Dune D3D library - Tobias Alexander Franke 2011 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ #include "assimp_mesh.h" #include <string> #include <vector> #include <algorithm> #include <sstream> #include <cmath> #include <iostream> #include <CommCtrl.h> #include <assimp/ProgressHandler.hpp> #include "d3d_tools.h" #include "texture_cache.h" #include "common_tools.h" #include "exception.h" namespace dune { namespace detail { DirectX::XMFLOAT3 aivec_to_dxvec3(aiVector3D v) { return DirectX::XMFLOAT3(v.x, v.y, v.z); } DirectX::XMFLOAT4 aivec_to_dxvec4(aiColor4D v) { return DirectX::XMFLOAT4(v.r, v.g, v.b, v.a); } DirectX::XMFLOAT2 aivec_to_dxvec2(aiVector3D v) { return DirectX::XMFLOAT2(v.x, v.y); } tstring to_tstring(aiString s) { std::string xs(s.data, s.length); return dune::to_tstring(xs); } } assimp_mesh::assimp_mesh() : importer_(), mesh_infos_(), indices_(), num_faces_(0), num_vertices_(0) { } const aiScene* const assimp_mesh::assimp_scene() const { return importer_.GetScene(); } void assimp_mesh::destroy() { d3d_mesh::destroy(); mesh_infos_.clear(); indices_.clear(); num_faces_ = 0; num_vertices_ = 0; } size_t assimp_mesh::num_vertices() { size_t n = 0; for (size_t m = 0; m < assimp_scene()->mNumMeshes; ++m) n += assimp_scene()->mMeshes[m]->mNumVertices; return n; } size_t assimp_mesh::num_faces() { size_t n = 0; for (size_t m = 0; m < assimp_scene()->mNumMeshes; ++m) n += assimp_scene()->mMeshes[m]->mNumFaces; return n; } struct progress_handler : public Assimp::ProgressHandler { virtual bool Update(float percentage) { return true; } }; void assimp_mesh::load(const tstring& file) { std::string name = to_string(make_absolute_path(file)); tclog << L"Loading: " << file << std::endl; progress_handler ph; importer_.SetProgressHandler(&ph); const aiScene* scene = importer_.ReadFile(name.c_str(), aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_MakeLeftHanded | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType | aiProcess_GenSmoothNormals | //aiProcess_GenNormals | aiProcess_RemoveRedundantMaterials | aiProcess_OptimizeMeshes | aiProcess_GenUVCoords | aiProcess_TransformUVCoords); if (!scene) { std::string error = importer_.GetErrorString(); tstringstream ss; ss << L"Failed loading: " << file << std::endl; ss << error.c_str() << std::endl; throw exception(ss.str()); } aiMatrix4x4 m; load_internal(scene, scene->mRootNode, m); importer_.SetProgressHandler(nullptr); tclog << L"Mesh info: " << std::endl << L" - " << mesh_infos_.size() << L" meshes" << std::endl << L" - " << "BBOX (" << bb_max().x << L", " << bb_max().y << L", " << bb_max().z << L")" << L" - (" << bb_min().x << L", " << bb_min().y << L", " << bb_min().z << L")" << std::endl << L" - " << num_faces_ << L" faces" << std::endl << L" - " << num_vertices_ << L" vertices" << std::endl; } void assimp_mesh::load_internal(const aiScene* scene, aiNode* node, aiMatrix4x4 acc_transform) { aiMatrix4x4 transform = acc_transform * node->mTransformation; // store all meshes, one after another for(size_t a = 0; a < node->mNumMeshes; ++a) { const aiMesh* mesh = scene->mMeshes[node->mMeshes[a]]; // store current read num_vertices_ and aiMesh for potential reference mesh_info m; m.vstart_index = num_vertices_; m.istart_index = static_cast<UINT>(indices_.size()); m.num_faces = mesh->mNumFaces; m.num_vertices = mesh->mNumVertices; m.material_index = mesh->mMaterialIndex; num_vertices_ += mesh->mNumVertices; num_faces_ += mesh->mNumFaces; // store vertices for(size_t b = 0; b < mesh->mNumVertices; ++b) { assimp_mesh::vertex v; aiVector3D v_trans = transform * mesh->mVertices[b]; v.position = detail::aivec_to_dxvec3(v_trans); // if this is the very first vertex if (m.vstart_index == 0 && b == 0) init_bb(v.position); else update_bb(v.position); if (mesh->HasNormals()) v.normal = detail::aivec_to_dxvec3(mesh->mNormals[b]); if (mesh->HasTangentsAndBitangents()) v.tangent = detail::aivec_to_dxvec3(mesh->mTangents[b]); for (size_t n = 0; n < mesh->GetNumUVChannels(); ++n) { v.texcoord[n] = detail::aivec_to_dxvec2(mesh->mTextureCoords[n][b]); v.texcoord[n].y = 1.f - v.texcoord[n].y; } push_back(v); m.update(v.position, b == 0); } // store indices, corrected by startIndex, and attribute for(size_t b = 0; b < mesh->mNumFaces; ++b) { indices_.push_back(mesh->mFaces[b].mIndices[2]); indices_.push_back(mesh->mFaces[b].mIndices[1]); indices_.push_back(mesh->mFaces[b].mIndices[0]); } mesh_infos_.push_back(m); } for (size_t c = 0; c < node->mNumChildren; ++c) assimp_mesh::load_internal(scene, node->mChildren[c], transform); } void gilga_mesh::push_back(vertex v) { gilga_vertex gv; gv.normal = v.normal; gv.position = v.position; gv.texcoord = v.texcoord[0]; gv.tangent = v.tangent; vertices_.push_back(gv); } void gilga_mesh::prepare_context(ID3D11DeviceContext* context) { context->VSSetShader(vs_, nullptr, 0); context->GSSetShader(nullptr, nullptr, 0); context->PSSetShader(ps_, nullptr, 0); ss_.to_ps(context, 0); context->OMSetBlendState(nullptr, nullptr, 0xFF); } void gilga_mesh::render(ID3D11DeviceContext* context, DirectX::XMFLOAT4X4* to_clip) { prepare_context(context); render_direct(context, to_clip); } void gilga_mesh::render_direct(ID3D11DeviceContext* context, DirectX::XMFLOAT4X4* to_clip) { assert(context); context->IASetInputLayout(vertex_layout_); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); auto cbvs = &cb_mesh_data_vs_.data(); { DirectX::XMStoreFloat4x4(&cbvs->world, DirectX::XMLoadFloat4x4(&world())); } cb_mesh_data_vs_.to_vs(context, 1); mesh_data* prev = nullptr; for (size_t m = 0; m < meshes_.size(); ++m) { mesh_data* data = &meshes_[m]; mesh_info* info = &mesh_infos_[m]; if (to_clip && !is_visible(*info, *to_clip)) continue; // check if material has changed bool same = (prev && equal(prev->diffuse_color, data->diffuse_color) && equal(prev->specular_color, data->specular_color) && equal(prev->emissive_color, data->emissive_color) && prev->diffuse_tex == data->diffuse_tex && prev->specular_tex == data->specular_tex && prev->normal_tex == data->normal_tex && prev->specular_tex == data->specular_tex && prev->alpha_tex == data->alpha_tex && prev->shading_mode == data->shading_mode && prev->roughness == data->roughness ); if (!same) { const bool has_diffuse_tex = data->diffuse_tex != nullptr && diffuse_tex_slot_ != -1; const bool has_normal_tex = data->normal_tex != nullptr && normal_tex_slot_ != -1; const bool has_specular_tex = data->specular_tex != nullptr && specular_tex_slot_ != -1; const bool has_alpha_tex = data->alpha_tex != nullptr && alpha_tex_slot_ != -1; auto cbps = &cb_mesh_data_ps_.data(); { cbps->diffuse_color = data->diffuse_color; cbps->specular_color = data->specular_color; cbps->emissive_color = data->emissive_color; cbps->has_diffuse_tex = has_diffuse_tex; cbps->has_normal_tex = has_normal_tex; cbps->has_specular_tex = has_specular_tex; cbps->has_alpha_tex = has_alpha_tex; cbps->shading_mode = data->shading_mode; cbps->roughness = data->roughness; cbps->refractive_index = data->refractive_index; } cb_mesh_data_ps_.to_ps(context, 0); if (has_diffuse_tex) context->PSSetShaderResources(diffuse_tex_slot_, 1, &data->diffuse_tex); if (has_normal_tex) context->PSSetShaderResources(normal_tex_slot_, 1, &data->normal_tex); if (has_specular_tex) context->PSSetShaderResources(specular_tex_slot_, 1, &data->specular_tex); if (has_alpha_tex) context->PSSetShaderResources(alpha_tex_slot_, 1, &data->alpha_tex); } context->IASetIndexBuffer(data->index, DXGI_FORMAT_R32_UINT, 0); static const UINT stride = sizeof(gilga_vertex); static const UINT offset = 0; context->IASetVertexBuffers(0, 1, &data->vertex, &stride, &offset); context->DrawIndexed(info->num_faces * 3, 0, 0); prev = &meshes_[m]; } } gilga_mesh::gilga_mesh() : cb_mesh_data_ps_(), cb_mesh_data_vs_(), ss_(), alpha_tex_slot_(-1), vertices_(), meshes_() { } void gilga_mesh::create(ID3D11Device* device, const tstring& file) { DirectX::XMStoreFloat4x4(&world_, DirectX::XMMatrixIdentity()); load(file); cb_mesh_data_vs_.create(device); cb_mesh_data_ps_.create(device); D3D11_SAMPLER_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sd.ComparisonFunc = D3D11_COMPARISON_NEVER; sd.MaxLOD = D3D11_FLOAT32_MAX; ss_.create(device, sd); tstring path = extract_path(file); for (auto i = mesh_infos_.begin(); i != mesh_infos_.end(); ++i) { UINT num_vertices = i->num_vertices; UINT num_faces = i->num_faces; if (num_faces == 0 || num_vertices == 0) { tcout << L"Skipping invalid mesh with " << num_vertices << L" vertices and " << num_faces << L" faces" << std::endl; continue; } mesh_data mesh; ZeroMemory(&mesh, sizeof(mesh)); D3D11_BUFFER_DESC bd; D3D11_SUBRESOURCE_DATA initdata; // create vertex buffer ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(gilga_vertex) * num_vertices; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; ZeroMemory(&initdata, sizeof(initdata)); initdata.pSysMem = &vertices_[i->vstart_index]; assert_hr(device->CreateBuffer(&bd, &initdata, &mesh.vertex)); // create index buffer ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(UINT) * (num_faces * 3); bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; ZeroMemory(&initdata, sizeof(initdata)); initdata.pSysMem = &indices_[i->istart_index]; assert_hr(device->CreateBuffer(&bd, &initdata, &mesh.index)); // load material aiMaterial* mat = assimp_scene()->mMaterials[i->material_index]; aiColor4D color; // grab diffuse color mesh.diffuse_color = DirectX::XMFLOAT4(0.f, 0.f, 0.f, 0.f); if (mat->Get(AI_MATKEY_COLOR_DIFFUSE, color) == AI_SUCCESS) mesh.diffuse_color = detail::aivec_to_dxvec4(color); // grab opacity and insert into diffuse color.a float opacity = 0; if (mat->Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS) mesh.diffuse_color.w = opacity; // grab specular color mesh.specular_color = DirectX::XMFLOAT4(0.f, 0.f, 0.f, 0.f); if (mat->Get(AI_MATKEY_COLOR_SPECULAR, color) == AI_SUCCESS) mesh.specular_color = detail::aivec_to_dxvec4(color); // grab emissive color mesh.emissive_color = DirectX::XMFLOAT4(0.f, 0.f, 0.f, 0.f); if (mat->Get(AI_MATKEY_COLOR_EMISSIVE, color) == AI_SUCCESS) mesh.emissive_color = detail::aivec_to_dxvec4(color); // get the shading mode -> abuse as basic material shading map int shading_mode; mesh.shading_mode = SHADING_DEFAULT; if (mat->Get(AI_MATKEY_SHADING_MODEL, shading_mode) == AI_SUCCESS) { // convert back, don't care about the specific expected implementation switch (shading_mode) { case 9: mesh.shading_mode = SHADING_OFF; break; case 3: mesh.shading_mode = SHADING_DEFAULT; break; case 2: mesh.shading_mode = SHADING_IBL; break; default: mesh.shading_mode = SHADING_DEFAULT; break; }; if (mesh.emissive_color.x + mesh.emissive_color.y + mesh.emissive_color.z > 0) mesh.shading_mode = SHADING_AREA_LIGHT; } // get specular exponent // WARNING: OBJ specifies shininess = Ns * 4 // convert shininess to roughness first float shininess; mesh.roughness = 0.0f; if (mat->Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS) mesh.roughness = std::sqrtf(std::sqrtf(2.0f / (shininess + 2.0f))); // get refractive index float refractive_index; mesh.refractive_index = 1.5; if (mat->Get(AI_MATKEY_REFRACTI, refractive_index) == AI_SUCCESS) mesh.refractive_index = refractive_index; // get textures aiString str; str.Clear(); if (mat->Get(AI_MATKEY_TEXTURE_DIFFUSE(0), str) == AI_SUCCESS) load_texture(device, path + detail::to_tstring(str), &mesh.diffuse_tex); str.Clear(); if (mat->Get(AI_MATKEY_TEXTURE_EMISSIVE(0), str) == AI_SUCCESS) load_texture(device, path + detail::to_tstring(str), &mesh.emissive_tex); str.Clear(); if (mat->Get(AI_MATKEY_TEXTURE_SPECULAR(0), str) == AI_SUCCESS) load_texture(device, path + detail::to_tstring(str), &mesh.specular_tex); str.Clear(); //mat->Get(AI_MATKEY_TEXTURE_NORMALS(0), str); if (mat->Get(AI_MATKEY_TEXTURE_HEIGHT(0), str) == AI_SUCCESS) load_texture(device, path + detail::to_tstring(str), &mesh.normal_tex); str.Clear(); if (mat->Get(AI_MATKEY_TEXTURE_OPACITY(0), str) == AI_SUCCESS) load_texture(device, path + detail::to_tstring(str), &mesh.alpha_tex); meshes_.push_back(mesh); } importer_.FreeScene(); } void gilga_mesh::destroy() { assimp_mesh::destroy(); for (auto i = meshes_.begin(); i != meshes_.end(); ++i) { safe_release(i->index); safe_release(i->vertex); } ss_.destroy(); cb_mesh_data_vs_.destroy(); cb_mesh_data_ps_.destroy(); vertices_.clear(); meshes_.clear(); alpha_tex_slot_ = -1; } }
33.978805
105
0.530026
[ "mesh", "render", "vector", "transform" ]
c717c6721990123fd0c55600a7be6b21417162b1
7,975
cpp
C++
src/bhv_goalie_free_kick.cpp
mhauskn/hfo
b8b2a1d462823c6732f4d5581aa7fe2e371d55cb
[ "MIT" ]
216
2016-02-24T22:51:01.000Z
2022-03-28T03:13:13.000Z
HFO_mgm/src/bhv_goalie_free_kick.cpp
bcahlit/graduationMgm
d0237207dbb485611c685251f97649679a7bbc0a
[ "MIT" ]
81
2016-03-04T19:49:51.000Z
2022-01-13T12:12:28.000Z
HFO_mgm/src/bhv_goalie_free_kick.cpp
bcahlit/graduationMgm
d0237207dbb485611c685251f97649679a7bbc0a
[ "MIT" ]
99
2016-02-24T23:07:50.000Z
2022-03-15T06:22:36.000Z
// -*-c++-*- /* *Copyright: Copyright (C) Hidehisa AKIYAMA This code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This code 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 code; see the file COPYING. If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. *EndCopyright: */ ///////////////////////////////////////////////////////////////////// #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "bhv_goalie_free_kick.h" #include "bhv_goalie_basic_move.h" #include <rcsc/action/body_clear_ball.h> #include <rcsc/action/body_pass.h> #include <rcsc/action/basic_actions.h> #include <rcsc/action/body_kick_one_step.h> #include <rcsc/action/neck_scan_field.h> #include <rcsc/player/player_agent.h> #include <rcsc/player/debug_client.h> #include <rcsc/common/logger.h> #include <rcsc/common/server_param.h> #include <rcsc/geom/rect_2d.h> /*-------------------------------------------------------------------*/ /*! execute action */ bool Bhv_GoalieFreeKick::execute( rcsc::PlayerAgent * agent ) { #ifdef __APPLE__ static bool s_first_move = false; static bool s_second_move = false; static int s_second_wait_count = 0; #else static thread_local bool s_first_move = false; static thread_local bool s_second_move = false; static thread_local int s_second_wait_count = 0; #endif rcsc::dlog.addText( rcsc::Logger::TEAM, __FILE__": Bhf_GoalieFreeKick" ); if ( agent->world().gameMode().type() != rcsc::GameMode::GoalieCatch_ || agent->world().gameMode().side() != agent->world().ourSide() || ! agent->world().self().isKickable() ) { rcsc::dlog.addText( rcsc::Logger::TEAM, __FILE__": Bhv_GoalieFreeKick. Not a goalie catch mode" ); Bhv_GoalieBasicMove().execute( agent ); return true; } const long time_diff = agent->world().time().cycle() - agent->effector().getCatchTime().cycle(); //- M_catch_time.cycle(); // reset flags & wait if ( time_diff <= 2 ) { s_first_move = false; s_second_move = false; s_second_wait_count = 0; doWait( agent ); return true; } // first move if ( ! s_first_move ) { //rcsc::Vector2D move_target( rcsc::ServerParam::i().ourPenaltyAreaLine() - 0.8, 0.0 ); rcsc::Vector2D move_target( rcsc::ServerParam::i().ourPenaltyAreaLineX() - 1.5, agent->world().ball().pos().y > 0.0 ? -13.0 : 13.0 ); //rcsc::Vector2D move_target( -45.0, 0.0 ); s_first_move = true; s_second_move = false; s_second_wait_count = 0; agent->doMove( move_target.x, move_target.y ); agent->setNeckAction( new rcsc::Neck_ScanField ); return true; } // after first move // check stamina recovery or wait teammate rcsc::Rect2D our_pen( rcsc::Vector2D( -52.5, -40.0 ), rcsc::Vector2D( -36.0, 40.0 ) ); if ( time_diff < 50 || agent->world().setplayCount() < 3 || ( time_diff < rcsc::ServerParam::i().dropBallTime() - 15 && ( agent->world().self().stamina() < rcsc::ServerParam::i().staminaMax() * 0.9 || agent->world().existTeammateIn( our_pen, 20, true ) ) ) ) { doWait( agent ); return true; } // second move if ( ! s_second_move ) { rcsc::Vector2D kick_point = getKickPoint( agent ); agent->doMove( kick_point.x, kick_point.y ); agent->setNeckAction( new rcsc::Neck_ScanField ); s_second_move = true; s_second_wait_count = 0; return true; } s_second_wait_count++; // after second move // wait see info if ( s_second_wait_count < 5 || agent->world().seeTime() != agent->world().time() ) { doWait( agent ); return true; } s_first_move = false; s_second_move = false; s_second_wait_count = 0; // register kick intention doKick( agent ); return true; } /*-------------------------------------------------------------------*/ /*! */ rcsc::Vector2D Bhv_GoalieFreeKick::getKickPoint( const rcsc::PlayerAgent * agent ) { static const double base_x = -43.0; static const double base_y = 10.0; std::vector< std::pair< rcsc::Vector2D, double > > candidates; candidates.reserve( 4 ); candidates.push_back( std::make_pair( rcsc::Vector2D( base_x, base_y ), 0.0 ) ); candidates.push_back( std::make_pair( rcsc::Vector2D( base_x, -base_y ), 0.0 ) ); candidates.push_back( std::make_pair( rcsc::Vector2D( base_x, 0.0 ), 0.0 ) ); const rcsc::PlayerPtrCont::const_iterator opps_end = agent->world().opponentsFromSelf().end(); for ( rcsc::PlayerPtrCont::const_iterator o = agent->world().opponentsFromSelf().begin(); o != opps_end; ++o ) { for ( std::vector< std::pair< rcsc::Vector2D, double > >::iterator it = candidates.begin(); it != candidates.end(); ++it ) { it->second += 1.0 / (*o)->pos().dist2( it->first ); } } rcsc::Vector2D best_pos = candidates.front().first; double min_cong = 10000.0; for ( std::vector< std::pair< rcsc::Vector2D, double > >::iterator it = candidates.begin(); it != candidates.end(); ++it ) { if ( it->second < min_cong ) { best_pos = it->first; min_cong = it->second; } } return best_pos; } /*-------------------------------------------------------------------*/ /*! */ void Bhv_GoalieFreeKick::doKick( rcsc::PlayerAgent * agent ) { rcsc::Vector2D target_point; double pass_speed = 0.0; if ( rcsc::Body_Pass::get_best_pass( agent->world(), &target_point, &pass_speed, NULL ) && target_point.dist( rcsc::Vector2D( -50.0, 0.0 ) ) > 20.0 ) { double opp_dist = 100.0; const rcsc::PlayerObject * opp = agent->world().getOpponentNearestTo( target_point, 20, &opp_dist ); agent->debugClient().addMessage( "GKickOppDist%.1f", opp ? opp_dist : 1000.0 ); if ( ! opp || opp_dist > 3.0 ) { rcsc::Body_KickOneStep( target_point, pass_speed ).execute( agent ); rcsc::dlog.addText( rcsc::Logger::TEAM, __FILE__": register goalie kick intention. to (%.1f, %.1f)", target_point.x, target_point.y ); agent->setNeckAction( new rcsc::Neck_ScanField() ); return; } } rcsc::Body_ClearBall().execute( agent ); agent->setNeckAction( new rcsc::Neck_ScanField() ); } /*-------------------------------------------------------------------*/ /*! */ void Bhv_GoalieFreeKick::doWait( rcsc::PlayerAgent * agent ) { const rcsc::WorldModel & wm = agent->world(); rcsc::Vector2D face_target( 0.0, 0.0 ); if ( wm.self().pos().x > rcsc::ServerParam::i().ourPenaltyAreaLineX() - rcsc::ServerParam::i().ballSize() - wm.self().playerType().playerSize() - 0.5 ) { face_target.assign( rcsc::ServerParam::i().ourPenaltyAreaLineX() - 1.0, 0.0 ); } rcsc::Body_TurnToPoint( face_target ).execute( agent ); agent->setNeckAction( new rcsc::Neck_ScanField() ); }
30.323194
99
0.564263
[ "vector" ]
c71db0d87f5bb57054d8e2a3e5ef941fbd4611da
1,670
cpp
C++
qt-mvvm/source/libmvvm_model/mvvm/factories/modelconverterfactory.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
6
2021-12-08T03:09:47.000Z
2022-02-24T03:51:14.000Z
qt-mvvm/source/libmvvm_model/mvvm/factories/modelconverterfactory.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
qt-mvvm/source/libmvvm_model/mvvm/factories/modelconverterfactory.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
// ************************************************************************** // // // Model-view-view-model framework for large GUI applications // //! @license GNU General Public License v3 or higher (see COPYING) //! @authors see AUTHORS // // ************************************************************************** // #include "mvvm/factories/modelconverterfactory.h" #include "mvvm/factories/itemconverterfactory.h" #include "mvvm/serialization/jsonitem_types.h" #include "mvvm/serialization/jsonmodelconverter.h" //! Creates a JSON model converter intended for model cloning. //! Saves a full deep copy of model in JSON. When restoring, reconstruct full copy. //! This will lead to item ID's which are identical to original. std::unique_ptr<ModelView::JsonModelConverterInterface> ModelView::CreateModelCloneConverter() { return std::make_unique<JsonModelConverter>(ConverterMode::clone); } //! Creates a JSON model converter intended for model copying. //! Saves a full deep copy of model in JSON. When restoring, reconstruct full copy and regenerate //! item's ID to make them unique. std::unique_ptr<ModelView::JsonModelConverterInterface> ModelView::CreateModelCopyConverter() { return std::make_unique<JsonModelConverter>(ConverterMode::copy); } //! Creates a JSON model converter intended for save/load of the project on disk. //! When saving to disk, only certain data is saved. When loading from disk, items //! in memory is gently updated from JSON content. std::unique_ptr<ModelView::JsonModelConverterInterface> ModelView::CreateModelProjectConverter() { return std::make_unique<JsonModelConverter>(ConverterMode::project); }
40.731707
97
0.701796
[ "model" ]
c72504f046027c58898eb6449977719b03af2405
23,644
cpp
C++
source/tests/system/nirfsa_driver_api_tests.cpp
vvacharya/grpc-device
22326f69b83d774457c0f5409b71ce7fc66002f6
[ "MIT" ]
null
null
null
source/tests/system/nirfsa_driver_api_tests.cpp
vvacharya/grpc-device
22326f69b83d774457c0f5409b71ce7fc66002f6
[ "MIT" ]
null
null
null
source/tests/system/nirfsa_driver_api_tests.cpp
vvacharya/grpc-device
22326f69b83d774457c0f5409b71ce7fc66002f6
[ "MIT" ]
null
null
null
#include <gmock/gmock.h> #include <gtest/gtest.h> // For EXPECT matchers. #include <algorithm> #include "device_server.h" #include "niRFSAErrors.h" #include "nirfsa/nirfsa_client.h" #include "niscope/niscope_client.h" #include "nitclk/nitclk_client.h" using namespace ::testing; using namespace nirfsa_grpc; namespace client = nirfsa_grpc::experimental::client; namespace nitclk_client = nitclk_grpc::experimental::client; namespace niscope_client = niscope_grpc::experimental::client; namespace pb = google::protobuf; namespace ni { namespace tests { namespace system { namespace { const auto PXI_5663E = "5663E"; const auto PXI_5603 = "5603"; const auto IVI_ATTRIBUTE_NOT_SUPPORTED_ERROR = 0xBFFA0012; const auto REF_OUT_STR = "RefOut"; template <typename TResponse> void EXPECT_SUCCESS(const TResponse& response) { EXPECT_EQ(0, response.status()); } template <typename TResponse> void EXPECT_RFSA_ERROR(pb::int32 expected_error, const TResponse& response) { EXPECT_EQ(expected_error, response.status()); } class NiRFSADriverApiTests : public Test { protected: NiRFSADriverApiTests() : device_server_(DeviceServerInterface::Singleton()), stub_(NiRFSA::NewStub(device_server_->InProcessChannel())) { } virtual ~NiRFSADriverApiTests() {} void TearDown() override { device_server_->ResetServer(); } const std::unique_ptr<NiRFSA::Stub>& stub() const { return stub_; } std::unique_ptr<nitclk_grpc::NiTClk::Stub> create_tclk_stub() const { return nitclk_grpc::NiTClk::NewStub(device_server_->InProcessChannel()); } std::unique_ptr<niscope_grpc::NiScope::Stub> create_scope_stub() const { return niscope_grpc::NiScope::NewStub(device_server_->InProcessChannel()); } void check_error(const nidevice_grpc::Session& session) { auto response = client::get_error(stub(), session); EXPECT_EQ("", std::string(response.error_description().c_str())); } void clear_error(const nidevice_grpc::Session& session) { auto response = client::clear_error(stub(), session); ni::tests::system::EXPECT_SUCCESS(response); } template <typename TResponse> void EXPECT_SUCCESS(const nidevice_grpc::Session& session, const TResponse& response) { ni::tests::system::EXPECT_SUCCESS(response); check_error(session); } template <typename TResponse> void EXPECT_RFSA_ERROR(pb::int32 expected_error, const std::string& message_substring, const nidevice_grpc::Session& session, const TResponse& response) { ni::tests::system::EXPECT_RFSA_ERROR(expected_error, response); const auto error = client::get_error(stub(), session); EXPECT_THAT(error.error_description(), HasSubstr(message_substring)); clear_error(session); } private: DeviceServerInterface* device_server_; std::unique_ptr<NiRFSA::Stub> stub_; }; InitWithOptionsResponse init(const client::StubPtr& stub, const std::string& model) { auto options = std::string("Simulate=1, DriverSetup=Model:") + model; return client::init_with_options(stub, "FakeDevice", false, false, options); } nidevice_grpc::Session init_session(const client::StubPtr& stub, const std::string& model) { auto response = init(stub, model); auto session = response.vi(); EXPECT_SUCCESS(response); return session; } TEST_F(NiRFSADriverApiTests, Init_Close_Succeeds) { auto init_response = init(stub(), PXI_5663E); auto session = init_response.vi(); EXPECT_SUCCESS(session, init_response); auto close_response = client::close(stub(), session); EXPECT_SUCCESS(session, close_response); } TEST_F(NiRFSADriverApiTests, InitWithErrorFromDriver_ReturnsUserErrorMessage) { auto initialize_response = client::init_with_options(stub(), "", false, false, ""); EXPECT_EQ(-200220, initialize_response.status()); EXPECT_STREQ("Device identifier is invalid.", initialize_response.error_message().c_str()); } MATCHER(IsNonDefaultComplexArray, "") { return std::all_of( arg.cbegin(), arg.cend(), [](const auto& val) { return (val.real() != 0 && val.imaginary() != 0); }); } TEST_F(NiRFSADriverApiTests, ConfigureGettingStartedIQ_FetchIQSingleRecordComplexF64_ReturnsData) { const auto NUMBER_OF_SAMPLES = 1000; auto session = init_session(stub(), PXI_5663E); auto configure_clock = client::configure_ref_clock(stub(), session, RefClockSource::REF_CLOCK_SOURCE_ONBOARD_CLOCK, 10e6); auto configure_reference_level = client::configure_reference_level(stub(), session, "", 0); auto configure_acquisition_type = client::configure_acquisition_type(stub(), session, AcquisitionType::ACQUISITION_TYPE_IQ); auto configure_number_of_samples = client::configure_number_of_samples(stub(), session, "", true, 1000); auto configure_iq_rate = client::configure_iq_rate(stub(), session, "", 1e6); EXPECT_SUCCESS(session, configure_clock); EXPECT_SUCCESS(session, configure_reference_level); EXPECT_SUCCESS(session, configure_acquisition_type); EXPECT_SUCCESS(session, configure_number_of_samples); EXPECT_SUCCESS(session, configure_iq_rate); auto fetch_record = client::read_iq_single_record_complex_f64(stub(), session, "", 10.0, NUMBER_OF_SAMPLES); EXPECT_SUCCESS(session, fetch_record); EXPECT_EQ(NUMBER_OF_SAMPLES, fetch_record.data().size()); EXPECT_THAT(fetch_record.data(), IsNonDefaultComplexArray()); EXPECT_EQ(0, fetch_record.wfm_info().absolute_initial_x()); EXPECT_EQ(NUMBER_OF_SAMPLES, fetch_record.wfm_info().actual_samples()); EXPECT_EQ(1, fetch_record.wfm_info().gain()); EXPECT_NEAR(1e-06, fetch_record.wfm_info().x_increment(), 1e-08); } TEST_F(NiRFSADriverApiTests, ConfigureGettingStartedIQ_FetchIQMultiRecordComplexF32_ReturnsData) { const auto NUMBER_OF_SAMPLES = 10; const auto NUMBER_OF_RECORDS = 2; auto session = init_session(stub(), PXI_5663E); auto configure_acquisition_type = client::configure_acquisition_type(stub(), session, AcquisitionType::ACQUISITION_TYPE_IQ); auto configure_number_of_samples = client::configure_number_of_samples(stub(), session, "", true, NUMBER_OF_SAMPLES); auto configure_number_of_records = client::configure_number_of_records(stub(), session, "", true, NUMBER_OF_RECORDS); EXPECT_SUCCESS(session, configure_acquisition_type); EXPECT_SUCCESS(session, configure_number_of_samples); EXPECT_SUCCESS(session, configure_number_of_records); auto initiate = client::initiate(stub(), session); auto fetch_record = client::fetch_iq_multi_record_complex_f32(stub(), session, "", 0, NUMBER_OF_RECORDS, NUMBER_OF_SAMPLES, 10.0); EXPECT_SUCCESS(session, fetch_record); EXPECT_EQ(NUMBER_OF_SAMPLES * NUMBER_OF_RECORDS, fetch_record.data().size()); EXPECT_THAT(fetch_record.data(), IsNonDefaultComplexArray()); EXPECT_EQ(NUMBER_OF_RECORDS, fetch_record.wfm_info().size()); } TEST_F(NiRFSADriverApiTests, ConfigureGettingStartedIQ_FetchIQSingleRecordComplexI16_ReturnsData) { const auto NUMBER_OF_SAMPLES = 10; auto session = init_session(stub(), PXI_5663E); auto configure_acquisition_type = client::configure_acquisition_type(stub(), session, AcquisitionType::ACQUISITION_TYPE_IQ); auto configure_number_of_samples = client::configure_number_of_samples(stub(), session, "", true, NUMBER_OF_SAMPLES); EXPECT_SUCCESS(session, configure_acquisition_type); EXPECT_SUCCESS(session, configure_number_of_samples); auto initiate = client::initiate(stub(), session); auto fetch_record = client::fetch_iq_single_record_complex_i16(stub(), session, "", 0, NUMBER_OF_SAMPLES, 10.0); EXPECT_SUCCESS(session, fetch_record); EXPECT_EQ(NUMBER_OF_SAMPLES, fetch_record.data().size()); EXPECT_THAT(fetch_record.data(), IsNonDefaultComplexArray()); } TEST_F(NiRFSADriverApiTests, ConfigureGettingStartedSpectrum_ReadPowerSpectrumF64_ReturnsSpectrumData) { auto session = init_session(stub(), PXI_5663E); auto configure_clock = client::configure_ref_clock(stub(), session, std::string("OnboardClock"), 10e6); auto configure_reference_level = client::configure_reference_level(stub(), session, "", 0); auto configure_acquisition_type = client::configure_acquisition_type(stub(), session, AcquisitionType::ACQUISITION_TYPE_SPECTRUM); auto configure_frequency_start_stop = client::configure_spectrum_frequency_start_stop(stub(), session, "", 990e6, 1010e6); auto configure_resolution_bandwidth = client::configure_resolution_bandwidth(stub(), session, "", 10e3); auto number_of_spectral_lines = client::get_number_of_spectral_lines(stub(), session, ""); EXPECT_SUCCESS(session, configure_clock); EXPECT_SUCCESS(session, configure_reference_level); EXPECT_SUCCESS(session, configure_acquisition_type); EXPECT_SUCCESS(session, configure_frequency_start_stop); EXPECT_SUCCESS(session, configure_resolution_bandwidth); EXPECT_SUCCESS(session, number_of_spectral_lines); EXPECT_EQ(4974, number_of_spectral_lines.number_of_spectral_lines()); auto power_spectrum = client::read_power_spectrum_f64( stub(), session, "", 10.0, number_of_spectral_lines.number_of_spectral_lines()); EXPECT_SUCCESS(session, power_spectrum); auto max_power_iter = std::max_element( power_spectrum.power_spectrum_data().cbegin(), power_spectrum.power_spectrum_data().cend()); EXPECT_NE(0.0, *max_power_iter); EXPECT_THAT(power_spectrum.power_spectrum_data(), Each(Ne(0.0))); EXPECT_EQ( power_spectrum.spectrum_info().number_of_spectral_lines(), number_of_spectral_lines.number_of_spectral_lines()); EXPECT_NE(0.0, power_spectrum.spectrum_info().initial_frequency()); EXPECT_NE(0.0, power_spectrum.spectrum_info().frequency_increment()); } TEST_F(NiRFSADriverApiTests, GetDeviceResponse_ReturnsResponseData) { auto session = init_session(stub(), PXI_5663E); auto response = client::get_device_response(stub(), session, "", DeviceResponse::DEVICE_RESPONSE_DOWNCONVERTER_IF_RESPONSE); const auto EXPECTED_SIZE = 81; EXPECT_SUCCESS(session, response); EXPECT_THAT(response.frequencies(), Each(Not(Eq(0)))); EXPECT_THAT(response.phase_response(), Each(Eq(0))); EXPECT_THAT(response.magnitude_response(), Each(Eq(0))); EXPECT_EQ(EXPECTED_SIZE, response.frequencies().size()); EXPECT_EQ(EXPECTED_SIZE, response.phase_response().size()); EXPECT_EQ(EXPECTED_SIZE, response.magnitude_response().size()); } // TODO: AB#1639825. This currently fails because of an off-by-one error. TEST_F(NiRFSADriverApiTests, GetRelayName_ReturnsRelayName) { auto session = init_session(stub(), PXI_5603); auto response = client::get_relay_name(stub(), session, "", 1); EXPECT_SUCCESS(session, response); EXPECT_EQ("Cal Tone Path Switch", response.name()); } TEST_F(NiRFSADriverApiTests, GetRelayOperationsCount_ReturnsOperationCounts) { const auto EXPECTED = std::vector<pb::int32>{0, 0, 0, 0}; auto session = init_session(stub(), PXI_5603); auto response = client::get_relay_operations_count(stub(), session, ""); EXPECT_SUCCESS(session, response); EXPECT_THAT( response.operations_count(), ElementsAreArray(EXPECTED.cbegin(), EXPECTED.cend())); } TEST_F(NiRFSADriverApiTests, ConfigureDigitalEdgeRefTrigger_Succeeds) { auto session = init_session(stub(), PXI_5663E); auto response = client::configure_digital_edge_ref_trigger( stub(), session, DigitalEdgeTriggerSource::DIGITAL_EDGE_TRIGGER_SOURCE_PXI_TRIG0, DigitalEdge::DIGITAL_EDGE_RISING_EDGE, 10); EXPECT_SUCCESS(session, response); } TEST_F(NiRFSADriverApiTests, ReconfigureExportedRefClockOutTerminal_UpdatesRefClockSuccessfully) { auto session = init_session(stub(), PXI_5663E); auto initial_response = client::get_attribute_vi_string( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_EXPORTED_REF_CLOCK_OUTPUT_TERMINAL); auto set_response = client::set_attribute_vi_string( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_EXPORTED_REF_CLOCK_OUTPUT_TERMINAL, NiRFSAStringAttributeValuesMapped::NIRFSA_STRING_REF_CLOCK_OUT_TERMINAL_REF_OUT); auto get_response = client::get_attribute_vi_string( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_EXPORTED_REF_CLOCK_OUTPUT_TERMINAL); EXPECT_SUCCESS(session, initial_response); EXPECT_SUCCESS(session, set_response); EXPECT_SUCCESS(session, get_response); EXPECT_NE(initial_response.value(), get_response.value()); EXPECT_EQ(REF_OUT_STR, get_response.value()); } TEST_F(NiRFSADriverApiTests, ReconfigureFFTWindowType_UpdatesFFTWindowSuccessfully) { auto session = init_session(stub(), PXI_5663E); auto initial_response = client::get_attribute_vi_int32( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_FFT_WINDOW_TYPE); auto set_response = client::set_attribute_vi_int32( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_FFT_WINDOW_TYPE, NiRFSAInt32AttributeValues::NIRFSA_INT32_FFT_WINDOW_TYPE_GAUSSIAN); auto get_response = client::get_attribute_vi_int32( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_FFT_WINDOW_TYPE); EXPECT_SUCCESS(session, initial_response); EXPECT_SUCCESS(session, set_response); EXPECT_SUCCESS(session, get_response); EXPECT_NE(initial_response.value(), get_response.value()); EXPECT_EQ( NiRFSAInt32AttributeValues::NIRFSA_INT32_FFT_WINDOW_TYPE_GAUSSIAN, get_response.value()); } TEST_F(NiRFSADriverApiTests, ExportSignal_Succeeds) { auto session = init_session(stub(), PXI_5663E); auto response = client::export_signal( stub(), session, Signal::SIGNAL_START_TRIGGER, "", ExportTerminal::EXPORT_TERMINAL_REF_OUT); EXPECT_SUCCESS(session, response); } TEST_F(NiRFSADriverApiTests, DisableFractionalResampling_FractionalResamplingIsDisabled) { auto session = init_session(stub(), PXI_5663E); auto initial_response = client::get_attribute_vi_boolean( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_ENABLE_FRACTIONAL_RESAMPLING); auto set_response = client::set_attribute_vi_boolean( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_ENABLE_FRACTIONAL_RESAMPLING, false); auto get_response = client::get_attribute_vi_boolean( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_ENABLE_FRACTIONAL_RESAMPLING); EXPECT_SUCCESS(session, initial_response); EXPECT_SUCCESS(session, set_response); EXPECT_SUCCESS(session, get_response); EXPECT_NE(initial_response.value(), get_response.value()); EXPECT_FALSE(get_response.value()); } TEST_F(NiRFSADriverApiTests, ReconfigureIQRate_UpdatesIQRateSuccessfully) { auto NEW_RATE = 1.2e6; auto session = init_session(stub(), PXI_5663E); auto initial_response = client::get_attribute_vi_real64( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_IQ_RATE); auto set_response = client::set_attribute_vi_real64( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_IQ_RATE, NEW_RATE); auto get_response = client::get_attribute_vi_real64( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_IQ_RATE); EXPECT_SUCCESS(session, initial_response); EXPECT_SUCCESS(session, set_response); EXPECT_SUCCESS(session, get_response); EXPECT_NE(initial_response.value(), get_response.value()); EXPECT_NEAR(NEW_RATE, get_response.value(), .0001); } TEST_F(NiRFSADriverApiTests, ReconfigureFetchOffset_UpdatesFetchOffsetSuccessfully) { const auto NEW_OFFSET = 100ULL; auto session = init_session(stub(), PXI_5663E); auto initial_response = client::get_attribute_vi_int64( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_FETCH_OFFSET); auto set_response = client::set_attribute_vi_int64( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_FETCH_OFFSET, NEW_OFFSET); auto get_response = client::get_attribute_vi_int64( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_FETCH_OFFSET); EXPECT_SUCCESS(session, initial_response); EXPECT_SUCCESS(session, set_response); EXPECT_SUCCESS(session, get_response); EXPECT_NE(initial_response.value(), get_response.value()); EXPECT_EQ(NEW_OFFSET, get_response.value()); } // NOTE: disabled because this test requires a 58XX device. Simulating a 58XX hangs on shutdown. // FIXED in RFSA 21.5 (in development as of this comment). TEST_F(NiRFSADriverApiTests, DISABLED_ReconfigureDowncoverterMode_UpdatesDownconverterModeSuccessfully) { constexpr auto USER_DEFINED = NiRFSAInt32AttributeValues::NIRFSA_INT32_DOWNCONVERTER_FREQUENCY_OFFSET_MODE_USER_DEFINED; constexpr auto ENABLED = NiRFSAInt32AttributeValues::NIRFSA_INT32_DOWNCONVERTER_FREQUENCY_OFFSET_MODE_ENABLED; const auto session = init_session(stub(), "5841"); // Per nirfsa.sub: "NOTE: You must set this attribute to enable the NIRFSA_ATTR_DOWNCONVERTER_FREQUENCY_OFFSET_MODE attribute." const auto bandwidth_response = client::set_attribute_vi_real64( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_SIGNAL_BANDWIDTH, 1e4); const auto initial_response = client::get_attribute_vi_int32(stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_DOWNCONVERTER_FREQUENCY_OFFSET_MODE); // Toggle the mode since it persists between sessions. const auto new_mode = (initial_response.value() == USER_DEFINED) ? ENABLED : USER_DEFINED; const auto set_response = client::set_attribute_vi_int32( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_DOWNCONVERTER_FREQUENCY_OFFSET_MODE, new_mode); const auto get_response = client::get_attribute_vi_int32( stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_DOWNCONVERTER_FREQUENCY_OFFSET_MODE); EXPECT_SUCCESS(session, initial_response); EXPECT_SUCCESS(session, set_response); EXPECT_SUCCESS(session, get_response); EXPECT_NE(initial_response.value(), get_response.value()); EXPECT_EQ(new_mode, get_response.value()); } TEST_F(NiRFSADriverApiTests, CreateConfigurationList_Succeeds) { const auto LIST_NAME = "MyList"; auto session = init_session(stub(), PXI_5663E); auto response = client::create_configuration_list( stub(), session, LIST_NAME, {NiRFSAAttribute::NIRFSA_ATTRIBUTE_EXTERNAL_GAIN, NiRFSAAttribute::NIRFSA_ATTRIBUTE_DEVICE_INSTANTANEOUS_BANDWIDTH}, true); EXPECT_SUCCESS(session, response); } TEST_F(NiRFSADriverApiTests, CreateConfigurationListWithInvalidAttribute_ReportsError) { const auto LIST_NAME = "MyList"; auto session = init_session(stub(), PXI_5663E); auto response = client::create_configuration_list( stub(), session, LIST_NAME, {NiRFSAAttribute::NIRFSA_ATTRIBUTE_EXTERNAL_GAIN, NiRFSAAttribute::NIRFSA_ATTRIBUTE_NOTCH_FILTER_ENABLED}, true); EXPECT_RFSA_ERROR(IVI_ATTRIBUTE_NOT_SUPPORTED_ERROR, "Attribute or property not supported.", session, response); } TEST_F(NiRFSADriverApiTests, GetScalingCoefficients_ReturnsCoefficients) { auto session = init_session(stub(), PXI_5663E); auto response = client::get_scaling_coefficients( stub(), session, ""); EXPECT_SUCCESS(session, response); EXPECT_EQ(1, response.coefficient_info().size()); EXPECT_NE(0.0, response.coefficient_info()[0].gain()); EXPECT_EQ(0.0, response.coefficient_info()[0].offset()); } TEST_F(NiRFSADriverApiTests, GetNormalizationCoefficients_ReturnsCoefficients) { auto session = init_session(stub(), PXI_5663E); auto response = client::get_normalization_coefficients( stub(), session, ""); EXPECT_SUCCESS(session, response); EXPECT_EQ(1, response.coefficient_info().size()); EXPECT_NE(0.0, response.coefficient_info()[0].gain()); EXPECT_EQ(0.0, response.coefficient_info()[0].offset()); } TEST_F(NiRFSADriverApiTests, ConfiguredSpectrumAcquisition_GetSpectralInfoForSmt_ReturnsSpectralInforForSmt) { auto session = init_session(stub(), PXI_5663E); auto spectral_lines = client::get_number_of_spectral_lines(stub(), session, ""); auto configure_acquisition_type = client::configure_acquisition_type( stub(), session, AcquisitionType::ACQUISITION_TYPE_SPECTRUM); auto power_spectrum = client::read_power_spectrum_f64(stub(), session, "", 10.0, spectral_lines.number_of_spectral_lines()); auto response = client::get_spectral_info_for_smt(stub(), session); EXPECT_SUCCESS(session, response); EXPECT_EQ(312, response.spectrum_info().fft_size()); EXPECT_EQ(1, response.spectrum_info().linear_db()); EXPECT_EQ(2, response.spectrum_info().spectrum_type()); EXPECT_EQ(312, response.spectrum_info().window_size()); EXPECT_EQ(8, response.spectrum_info().window()); } TEST_F(NiRFSADriverApiTests, TwoSessions_SetupTclkSyncPulseSenderSynchronization_Succeeds) { auto first_session = init_session(stub(), PXI_5663E); auto second_session = init_session(stub(), PXI_5663E); auto tclk_stub = create_tclk_stub(); auto result = nitclk_client::setup_for_sync_pulse_sender_synchronize(tclk_stub, {first_session, second_session}, 0); EXPECT_SUCCESS(first_session, result); } TEST_F(NiRFSADriverApiTests, SelfCalibrateWithStepsToOmit_Succeeds) { auto session = init_session(stub(), PXI_5663E); const auto response = client::self_calibrate(stub(), session, SelfCalibrateSteps::SELF_CALIBRATE_STEPS_ALIGNMENT); EXPECT_SUCCESS(session, response); } TEST_F(NiRFSADriverApiTests, IsSelfCalValid) { auto session = init_session(stub(), PXI_5663E); const auto response = client::is_self_cal_valid(stub(), session); EXPECT_SUCCESS(session, response); EXPECT_THAT(response.valid_steps_array(), ElementsAre(SELF_CALIBRATE_STEPS_DIGITIZER_SELF_CAL)); EXPECT_EQ(SELF_CALIBRATE_STEPS_DIGITIZER_SELF_CAL, response.valid_steps_raw()); } TEST_F(NiRFSADriverApiTests, SelfTest_Succeeds) { auto session = init_session(stub(), PXI_5663E); const auto response = client::self_test(stub(), session); EXPECT_SUCCESS(session, response); EXPECT_EQ("PASS", response.test_message()); } TEST_F(NiRFSADriverApiTests, ErrorMessage_ReturnsErrorMessage) { auto session = init_session(stub(), PXI_5663E); const auto response = client::error_message(stub(), session, IVI_ATTRIBUTE_NOT_SUPPORTED_ERROR); EXPECT_SUCCESS(session, response); EXPECT_EQ( "IVI: (Hex 0xBFFA0012) Attribute or property not supported.", response.error_message()); } TEST_F(NiRFSADriverApiTests, GetCalUserDefinedInfo_Succeeds) { auto session = init_session(stub(), PXI_5663E); const auto response = client::get_cal_user_defined_info(stub(), session); EXPECT_SUCCESS(session, response); EXPECT_EQ( "Simulated Device", response.info()); } // NOTE: disabled because this test requires a 58XX device. Simulating a 58XX hangs on shutdown. // FIXED in RFSA 21.5 (in development as of this comment). TEST_F(NiRFSADriverApiTests, DISABLED_GetDeembeddingCompensationGain_Succeeds) { auto session = init_session(stub(), "5830"); const auto deembedding_type = client::set_attribute_vi_int32( stub(), session, "if1", NiRFSAAttribute::NIRFSA_ATTRIBUTE_DEEMBEDDING_TYPE, NiRFSAInt32AttributeValues::NIRFSA_INT32_DEEMBEDDING_TYPE_SCALAR); const auto compensation_gain = client::get_attribute_vi_real64(stub(), session, "", NiRFSAAttribute::NIRFSA_ATTRIBUTE_DEEMBEDDING_COMPENSATION_GAIN); EXPECT_NEAR(0.0, compensation_gain.value(), 1e-6); EXPECT_SUCCESS(session, compensation_gain); } } // namespace } // namespace system } // namespace tests } // namespace ni
36.94375
155
0.762942
[ "vector", "model" ]
d178cc0a8ae555742022c2415fca4cdf90d99790
7,230
cpp
C++
Source/JavaScriptCore/runtime/IntlNumberFormatConstructor.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/JavaScriptCore/runtime/IntlNumberFormatConstructor.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/JavaScriptCore/runtime/IntlNumberFormatConstructor.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2015 Andy VanWagoner (andy@vanwagoner.family) * Copyright (C) 2016-2020 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "IntlNumberFormatConstructor.h" #include "IntlNumberFormat.h" #include "IntlNumberFormatPrototype.h" #include "IntlObjectInlines.h" #include "JSCInlines.h" namespace JSC { STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(IntlNumberFormatConstructor); static EncodedJSValue JSC_HOST_CALL IntlNumberFormatConstructorFuncSupportedLocalesOf(JSGlobalObject*, CallFrame*); } #include "IntlNumberFormatConstructor.lut.h" namespace JSC { const ClassInfo IntlNumberFormatConstructor::s_info = { "Function", &Base::s_info, &numberFormatConstructorTable, nullptr, CREATE_METHOD_TABLE(IntlNumberFormatConstructor) }; /* Source for IntlNumberFormatConstructor.lut.h @begin numberFormatConstructorTable supportedLocalesOf IntlNumberFormatConstructorFuncSupportedLocalesOf DontEnum|Function 1 @end */ IntlNumberFormatConstructor* IntlNumberFormatConstructor::create(VM& vm, Structure* structure, IntlNumberFormatPrototype* numberFormatPrototype) { IntlNumberFormatConstructor* constructor = new (NotNull, allocateCell<IntlNumberFormatConstructor>(vm.heap)) IntlNumberFormatConstructor(vm, structure); constructor->finishCreation(vm, numberFormatPrototype); return constructor; } Structure* IntlNumberFormatConstructor::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype) { return Structure::create(vm, globalObject, prototype, TypeInfo(InternalFunctionType, StructureFlags), info()); } static EncodedJSValue JSC_HOST_CALL callIntlNumberFormat(JSGlobalObject*, CallFrame*); static EncodedJSValue JSC_HOST_CALL constructIntlNumberFormat(JSGlobalObject*, CallFrame*); IntlNumberFormatConstructor::IntlNumberFormatConstructor(VM& vm, Structure* structure) : InternalFunction(vm, structure, callIntlNumberFormat, constructIntlNumberFormat) { } void IntlNumberFormatConstructor::finishCreation(VM& vm, IntlNumberFormatPrototype* numberFormatPrototype) { Base::finishCreation(vm, "NumberFormat"_s, NameAdditionMode::WithoutStructureTransition); putDirectWithoutTransition(vm, vm.propertyNames->prototype, numberFormatPrototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(0), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum); numberFormatPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, this, static_cast<unsigned>(PropertyAttribute::DontEnum)); } static EncodedJSValue JSC_HOST_CALL constructIntlNumberFormat(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 11.1.2 Intl.NumberFormat ([locales [, options]]) (ECMA-402 2.0) // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. // 2. Let numberFormat be OrdinaryCreateFromConstructor(newTarget, %NumberFormatPrototype%). // 3. ReturnIfAbrupt(numberFormat). JSObject* newTarget = asObject(callFrame->newTarget()); Structure* structure = newTarget == callFrame->jsCallee() ? globalObject->numberFormatStructure() : InternalFunction::createSubclassStructure(globalObject, newTarget, getFunctionRealm(vm, newTarget)->numberFormatStructure()); RETURN_IF_EXCEPTION(scope, { }); IntlNumberFormat* numberFormat = IntlNumberFormat::create(vm, structure); ASSERT(numberFormat); // 4. Return InitializeNumberFormat(numberFormat, locales, options). scope.release(); numberFormat->initializeNumberFormat(globalObject, callFrame->argument(0), callFrame->argument(1)); return JSValue::encode(numberFormat); } static EncodedJSValue JSC_HOST_CALL callIntlNumberFormat(JSGlobalObject* globalObject, CallFrame* callFrame) { // 11.1.2 Intl.NumberFormat ([locales [, options]]) (ECMA-402 2.0) // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. // NewTarget is always undefined when called as a function. // FIXME: Workaround to provide compatibility with ECMA-402 1.0 call/apply patterns. // https://bugs.webkit.org/show_bug.cgi?id=153679 return JSValue::encode(constructIntlInstanceWithWorkaroundForLegacyIntlConstructor<IntlNumberFormat>(globalObject, callFrame->thisValue(), callFrame->jsCallee(), [&] (VM& vm) { // 2. Let numberFormat be OrdinaryCreateFromConstructor(newTarget, %NumberFormatPrototype%). // 3. ReturnIfAbrupt(numberFormat). IntlNumberFormat* numberFormat = IntlNumberFormat::create(vm, globalObject->numberFormatStructure()); ASSERT(numberFormat); // 4. Return InitializeNumberFormat(numberFormat, locales, options). numberFormat->initializeNumberFormat(globalObject, callFrame->argument(0), callFrame->argument(1)); return numberFormat; })); } EncodedJSValue JSC_HOST_CALL IntlNumberFormatConstructorFuncSupportedLocalesOf(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 11.2.2 Intl.NumberFormat.supportedLocalesOf(locales [, options]) (ECMA-402 2.0) // 1. Let availableLocales be %NumberFormat%.[[availableLocales]]. const HashSet<String>& availableLocales = intlNumberFormatAvailableLocales(); // 2. Let requestedLocales be CanonicalizeLocaleList(locales). Vector<String> requestedLocales = canonicalizeLocaleList(globalObject, callFrame->argument(0)); RETURN_IF_EXCEPTION(scope, encodedJSValue()); // 3. Return SupportedLocales(availableLocales, requestedLocales, options). RELEASE_AND_RETURN(scope, JSValue::encode(supportedLocales(globalObject, availableLocales, requestedLocales, callFrame->argument(1)))); } } // namespace JSC
50.208333
180
0.778147
[ "object", "vector" ]
d195861a3a705dbbe467264cbb1beb98a319062e
12,334
hpp
C++
examples/mantevo/miniFE-1.1/stk_mesh_utils.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
1
2019-11-26T22:24:12.000Z
2019-11-26T22:24:12.000Z
examples/mantevo/miniFE-1.1/stk_mesh_utils.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
examples/mantevo/miniFE-1.1/stk_mesh_utils.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
#ifndef _stk_mesh_utils_hpp_ #define _stk_mesh_utils_hpp_ //@HEADER // ************************************************************************ // // miniFE: simple finite-element assembly and linear-solve // Copyright (2006) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // This library 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.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // Questions? Contact Michael A. Heroux (maherou@sandia.gov) // // ************************************************************************ //@HEADER #include <stk_mesh_description.hpp> #ifdef MINIFE_HAVE_TBB #include <LockingMatrix.hpp> #include <LockingVector.hpp> #endif namespace miniFE { template<typename GlobalOrdinal, typename Scalar> void get_elem_nodes_and_coords_1(const stk_mesh_description<Scalar,GlobalOrdinal>& mesh, stk::mesh::Entity& elem, ElemData<GlobalOrdinal,Scalar>& elem_data) { stk::mesh::PairIterRelation node_rel = elem.relations(mesh.fmeta.node_rank()); double** coords_ptr = stk::mesh::field_data(mesh.coord_gather_field, elem); //Obtain the coordinates of each node that is connected to this element. //The coordinate data is needed by the functions that do the //finite-element calculations. unsigned offset = 0; for(size_t i=0; i<Hex8::numNodesPerElem; ++i) { elem_data.elem_node_ids[i] = *stk::mesh::field_data(mesh.ordinal_field, *node_rel[i].entity()); const Scalar* node_coords = *coords_ptr++; elem_data.elem_node_coords[offset++] = node_coords[0]; elem_data.elem_node_coords[offset++] = node_coords[1]; elem_data.elem_node_coords[offset++] = node_coords[2]; } } template<typename GlobalOrdinal, typename Scalar> void get_elem_nodes_and_coords_2(const stk_mesh_description<Scalar,GlobalOrdinal>& mesh, stk::mesh::Entity& elem, ElemDataPtr<GlobalOrdinal,Scalar>& elem_data) { stk::mesh::PairIterRelation node_rel = elem.relations(mesh.fmeta.node_rank()); double** coords_ptr = stk::mesh::field_data(mesh.coord_gather_field, elem); Scalar* stk_elem_data = stk::mesh::field_data(*mesh.elem_mat_field, elem); elem_data.elem_diffusion_matrix = stk_elem_data; unsigned offset = Hex8::numNodesPerElem*Hex8::numNodesPerElem; elem_data.elem_source_vector = stk_elem_data+offset; offset += Hex8::numNodesPerElem; Scalar* s_node_ids = stk_elem_data+offset; //Obtain the coordinates of each node that is connected to this element. //The coordinate data is needed by the functions that do the //finite-element calculations. offset = 0; for(size_t i=0; i<Hex8::numNodesPerElem; ++i) { elem_data.elem_node_ids[i] = *stk::mesh::field_data(mesh.ordinal_field, *node_rel[i].entity()); s_node_ids[i] = elem_data.elem_node_ids[i]; const Scalar* node_coords = *coords_ptr++; elem_data.elem_node_coords[offset++] = node_coords[0]; elem_data.elem_node_coords[offset++] = node_coords[1]; elem_data.elem_node_coords[offset++] = node_coords[2]; } } template<typename GlobalOrdinal, typename Scalar, typename MatrixType, typename VectorType> void sum_into_global_linear_system(const stk_mesh_description<Scalar,GlobalOrdinal>& mesh, stk::mesh::Entity& node, MatrixType& A, VectorType& b) { stk::mesh::PairIterRelation elem_rel = node.relations(mesh.fmeta.element_rank()); GlobalOrdinal row = *stk::mesh::field_data(mesh.ordinal_field, node); GlobalOrdinal cols[Hex8::numNodesPerElem]; for(size_t el=0; el<elem_rel.size(); ++el) { stk::mesh::Entity& elem = *elem_rel[el].entity(); Scalar* elem_data = stk::mesh::field_data(*mesh.elem_mat_field, elem); Scalar* diffusionMatrix = elem_data; unsigned offset = Hex8::numNodesPerElem*Hex8::numNodesPerElem; Scalar* sourceVector = elem_data+offset; offset += Hex8::numNodesPerElem; Scalar* scols = elem_data+offset; unsigned elem_node_index = elem_rel[el].identifier(); Scalar* row_coefs = &diffusionMatrix[elem_node_index*Hex8::numNodesPerElem]; for(size_t i=0; i<Hex8::numNodesPerElem; ++i) { cols[i] = (GlobalOrdinal)scols[i]; } size_t len = Hex8::numNodesPerElem; sum_into_row(row, len, cols, row_coefs, A); sum_into_vector(1, &row, &sourceVector[elem_node_index], b); } } #ifdef MINIFE_HAVE_TBB template<typename GlobalOrdinal, typename Scalar, typename MatrixType, typename VectorType> void sum_into_global_linear_system(const stk_mesh_description<Scalar,GlobalOrdinal>& mesh, stk::mesh::Entity& node, LockingMatrix<MatrixType>& A, LockingVector<VectorType>& b) { stk::mesh::PairIterRelation elem_rel = node.relations(mesh.fmeta.element_rank()); GlobalOrdinal row = *stk::mesh::field_data(mesh.ordinal_field, node); GlobalOrdinal cols[Hex8::numNodesPerElem]; for(size_t el=0; el<elem_rel.size(); ++el) { stk::mesh::Entity& elem = *elem_rel[el].entity(); Scalar* elem_data = stk::mesh::field_data(*mesh.elem_mat_field, elem); Scalar* diffusionMatrix = elem_data; unsigned offset = Hex8::numNodesPerElem*Hex8::numNodesPerElem; Scalar* sourceVector = elem_data+offset; offset += Hex8::numNodesPerElem; Scalar* scols = elem_data+offset; unsigned elem_node_index = elem_rel[el].identifier(); Scalar* row_coefs = &diffusionMatrix[elem_node_index*Hex8::numNodesPerElem]; for(size_t i=0; i<Hex8::numNodesPerElem; ++i) { cols[i] = (GlobalOrdinal)scols[i]; } size_t len = Hex8::numNodesPerElem; A.sum_in(row, len, cols, row_coefs); b.sum_in(1, &row, &sourceVector[elem_node_index]); } } #endif //---------------------------------------------------------------------- namespace { template<typename OrdinalType> OrdinalType global_offset( stk::ParallelMachine comm , OrdinalType local_len ) { OrdinalType local_offset = local_len ; // Inclusive scan #ifdef HAVE_MPI MPI_Datatype mpi_dtype = TypeTraits<OrdinalType>::mpi_type(); MPI_Scan( & local_len , & local_offset , 1 , mpi_dtype , MPI_SUM , comm ); #endif // Returns inclusive scan, subtract for offset to begining local_offset -= local_len ; return local_offset ; } template<typename ValueType> ValueType global_sum( stk::ParallelMachine comm , ValueType local_val ) { ValueType global_val = local_val ; #ifdef HAVE_MPI MPI_Datatype mpi_dtype = TypeTraits<ValueType>::mpi_type(); MPI_Allreduce(&local_val, &global_val, 1, mpi_dtype, MPI_SUM, comm ); #endif return global_val ; } } void communicate_field_data( const stk::mesh::BulkData & mesh , const std::vector< const stk::mesh::FieldBase * > & fields ); //---------------------------------------------------------------------- template<typename Scalar, typename GlobalOrdinal> void populate_mesh( stk_mesh_description<Scalar,GlobalOrdinal> & mesh , const int global_box_in[][2] , const int local_box_in[][2] ) { const int numprocs = mesh.bulk.parallel_size(); const int myproc = mesh.bulk.parallel_rank(); //------------------------------ // Change the mesh bulk data to the 'ok to modify' state. mesh.bulk.modification_begin(); //Global domain has num-nodes in x-, y-, and z-dimensions: int global_node_nx = global_box_in[0][1]+1; int global_node_ny = global_box_in[1][1]+1; int global_node_nz = global_box_in[2][1]+1; //work-arrays that will hold element-connectivity data: stk::mesh::EntityId elem_node_ids[Hex8::numNodesPerElem]; Scalar elem_node_coords[Hex8::numNodesPerElem*Hex8::spatialDim]; //3-D loop over the local portion of the problem domain: for(int iz=local_box_in[2][0]; iz<local_box_in[2][1]; ++iz) { for(int iy=local_box_in[1][0]; iy<local_box_in[1][1]; ++iy) { for(int ix=local_box_in[0][0]; ix<local_box_in[0][1]; ++ix) { //Each element has 8 nodes locally-numbered 0 .. 7. //We use coordinates to obtain the node-0 for an element, and then //we can find out everything else about the element from that. stk::mesh::EntityId node0ID = get_id<stk::mesh::EntityId>( global_node_nx, global_node_ny, global_node_nz, ix, iy, -iz); if (node0ID < 0) { //This should never happen... do we need this error-check? std::cerr << "ERROR, negative node0ID" << std::endl; continue; } //Get this element's connected-nodes: get_hex8_node_ids(global_node_nx, global_node_ny, node0ID, &elem_node_ids[0]); //Get the coordinates for these nodes: get_hex8_node_coords_3d(ix, iy, -iz, &elem_node_coords[0]); //convert ids from 0-based to 1-based (stk::mesh deals in 1-based ids): ++node0ID; for(int i=0; i<Hex8::numNodesPerElem; ++i) ++elem_node_ids[i]; //declare an element entity, specifying that it belongs to //the elem_block mesh-part, and set its connected-nodes: //(note that here we use node0ID as the element-ID) stk::mesh::Entity& elem = stk::mesh::fem::declare_element( mesh.bulk, mesh.elem_block, node0ID, elem_node_ids); //get iterators for the element's node relations (connected nodes): stk::mesh::PairIterRelation rel = elem.relations(mesh.fmeta.node_rank()); //set the coordinates for each node: unsigned offset = 0; for(int i=0; i<Hex8::numNodesPerElem; ++i) { stk::mesh::Entity& node = *rel[i].entity(); Scalar* data = stk::mesh::field_data(mesh.coord_field, node); data[0] = elem_node_coords[offset++]; data[1] = elem_node_coords[offset++]; data[2] = elem_node_coords[offset++]; } } } } // Finished creating mesh-entities, let the mesh resolve // parallel sharing and generate the one-layer ghosting. mesh.bulk.modification_end(); //------------------------------ //obtain all locally-owned nodes: std::vector<stk::mesh::Entity*> owned_nodes; mesh.get_owned_nodes( owned_nodes ); //we will store a global matrix row-number in the ordinal field on //each node. //First, figure out this processor's first global matrix row: GlobalOrdinal row = global_offset<GlobalOrdinal>( mesh.bulk.parallel() , owned_nodes.size() ); //now set a row-number on each node: for(std::vector<stk::mesh::Entity*>::iterator it = owned_nodes.begin(); it != owned_nodes.end(); ++it, ++row) { *stk::mesh::field_data(mesh.ordinal_field, **it) = row; } // Send the ordinal field value for matrix rows from owner to all non-owned copies std::vector<const stk::mesh::FieldBase*> fields(1, & mesh.ordinal_field); miniFE::communicate_field_data( mesh.bulk, fields); std::vector<stk::mesh::Entity*> all_nodes; stk::mesh::get_entities(mesh.bulk, mesh.fmeta.node_rank(), all_nodes); //miniFE will set a dirichlet boundary-condition on each node that lies //on the x==0 face of the global problem domain. For convenience, //store the row-numbers for those nodes in a set for access later. for(std::vector<stk::mesh::Entity*>::iterator it = all_nodes.begin(); it != all_nodes.end(); ++it) { if (std::abs(stk::mesh::field_data(mesh.coord_field, **it)[0]) < 0.01) { mesh.bc_rows.insert(*stk::mesh::field_data(mesh.ordinal_field, **it)); } } } }//namespace miniFE #endif
38.664577
99
0.66418
[ "mesh", "vector" ]
d19695ef05e9a19d56aeb4e92934c1bcc2c9cbfb
3,065
cpp
C++
src/decoder-phrasebased/src/native/suffixarray-phrasetable/util/BilingualCorpus.cpp
ugermann/MMT
715ad16b4467f44c8103e16165261d1391a69fb8
[ "Apache-2.0" ]
null
null
null
src/decoder-phrasebased/src/native/suffixarray-phrasetable/util/BilingualCorpus.cpp
ugermann/MMT
715ad16b4467f44c8103e16165261d1391a69fb8
[ "Apache-2.0" ]
null
null
null
src/decoder-phrasebased/src/native/suffixarray-phrasetable/util/BilingualCorpus.cpp
ugermann/MMT
715ad16b4467f44c8103e16165261d1391a69fb8
[ "Apache-2.0" ]
null
null
null
// // Created by Davide Caroselli on 29/09/16. // #include <sstream> #include "BilingualCorpus.h" #include <boost/filesystem.hpp> #define AlignFileExt "align" using namespace mmt; using namespace mmt::sapt; namespace fs = boost::filesystem; BilingualCorpus::BilingualCorpus(domain_t domain, const string &sourceFile, const string &targetFile, const string &alignmentFile) : domain(domain), source(sourceFile), target(targetFile), alignment(alignmentFile) { } static inline void ParseSentenceLine(const string &line, vector<wid_t> &output) { output.clear(); stringstream stream(line); wid_t word; while (stream >> word) { output.push_back(word); } } static inline void ParseAlignmentLine(const string &line, alignment_t &output) { output.clear(); stringstream stream(line); string pair; while (stream >> pair) { char dash; length_t i, j; stringstream pair_stream(pair); pair_stream >> i; pair_stream >> dash; pair_stream >> j; output.push_back(make_pair(i, j)); } } void BilingualCorpus::List(const string &path, const string &sourceLang, const string &targetLang, vector<BilingualCorpus> &list) { fs::recursive_directory_iterator endit; for (fs::recursive_directory_iterator it(path); it != endit; ++it) { fs::path file = fs::absolute(*it); if (!fs::is_regular_file(file)) continue; if (file.extension().string() == "." + sourceLang) { fs::path sourceFile = file; fs::path targetFile = file; fs::path alignmentFile = file; targetFile = targetFile.replace_extension(fs::path(targetLang)); alignmentFile = alignmentFile.replace_extension(fs::path(AlignFileExt)); if (!fs::is_regular_file(targetFile)) continue; if (!fs::is_regular_file(alignmentFile)) continue; domain_t domain = (domain_t) stoi(file.stem().string()); list.push_back(BilingualCorpus(domain, sourceFile.string(), targetFile.string(), alignmentFile.string())); } } } CorpusReader::CorpusReader(const BilingualCorpus &corpus) : drained(false), sourceStream(corpus.source), targetStream(corpus.target), alignmentStream(corpus.alignment) { } bool CorpusReader::Read(vector<wid_t> &outSource, vector<wid_t> &outTarget, alignment_t &outAlignment) { if (drained) return false; string sourceLine, targetLine, alignmentLine; if (!getline(sourceStream, sourceLine) || !getline(targetStream, targetLine) || !getline(alignmentStream, alignmentLine)) { drained = true; return false; } ParseSentenceLine(sourceLine, outSource); ParseSentenceLine(targetLine, outTarget); ParseAlignmentLine(alignmentLine, outAlignment); return true; }
29.190476
118
0.622186
[ "vector" ]
d197f21319f1cedac08c502a5d0a9b6239145943
5,817
cc
C++
trademark/src/model/QueryMaterialResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
trademark/src/model/QueryMaterialResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
trademark/src/model/QueryMaterialResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/trademark/model/QueryMaterialResult.h> #include <json/json.h> using namespace AlibabaCloud::Trademark; using namespace AlibabaCloud::Trademark::Model; QueryMaterialResult::QueryMaterialResult() : ServiceResult() {} QueryMaterialResult::QueryMaterialResult(const std::string &payload) : ServiceResult() { parse(payload); } QueryMaterialResult::~QueryMaterialResult() {} void QueryMaterialResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allReviewAdditionalFiles = value["ReviewAdditionalFiles"]["ReviewAdditionalFile"]; for (const auto &item : allReviewAdditionalFiles) reviewAdditionalFiles_.push_back(item.asString()); if(!value["Type"].isNull()) type_ = std::stoi(value["Type"].asString()); if(!value["Region"].isNull()) region_ = std::stoi(value["Region"].asString()); if(!value["ContactName"].isNull()) contactName_ = value["ContactName"].asString(); if(!value["ContactNumber"].isNull()) contactNumber_ = value["ContactNumber"].asString(); if(!value["ContactEmail"].isNull()) contactEmail_ = value["ContactEmail"].asString(); if(!value["ContactAddress"].isNull()) contactAddress_ = value["ContactAddress"].asString(); if(!value["ContactZipcode"].isNull()) contactZipcode_ = value["ContactZipcode"].asString(); if(!value["Status"].isNull()) status_ = std::stoi(value["Status"].asString()); if(!value["LoaUrl"].isNull()) loaUrl_ = value["LoaUrl"].asString(); if(!value["Name"].isNull()) name_ = value["Name"].asString(); if(!value["CardNumber"].isNull()) cardNumber_ = value["CardNumber"].asString(); if(!value["ExpirationDate"].isNull()) expirationDate_ = std::stol(value["ExpirationDate"].asString()); if(!value["Province"].isNull()) province_ = value["Province"].asString(); if(!value["City"].isNull()) city_ = value["City"].asString(); if(!value["Town"].isNull()) town_ = value["Town"].asString(); if(!value["Address"].isNull()) address_ = value["Address"].asString(); if(!value["EName"].isNull()) eName_ = value["EName"].asString(); if(!value["EAddress"].isNull()) eAddress_ = value["EAddress"].asString(); if(!value["LoaStatus"].isNull()) loaStatus_ = std::stoi(value["LoaStatus"].asString()); if(!value["IdCardUrl"].isNull()) idCardUrl_ = value["IdCardUrl"].asString(); if(!value["BusinessLicenceUrl"].isNull()) businessLicenceUrl_ = value["BusinessLicenceUrl"].asString(); if(!value["PassportUrl"].isNull()) passportUrl_ = value["PassportUrl"].asString(); if(!value["Id"].isNull()) id_ = std::stol(value["Id"].asString()); if(!value["LegalNoticeUrl"].isNull()) legalNoticeUrl_ = value["LegalNoticeUrl"].asString(); if(!value["Note"].isNull()) note_ = value["Note"].asString(); if(!value["Country"].isNull()) country_ = value["Country"].asString(); if(!value["ReviewApplicationFile"].isNull()) reviewApplicationFile_ = value["ReviewApplicationFile"].asString(); } std::string QueryMaterialResult::getCardNumber()const { return cardNumber_; } std::string QueryMaterialResult::getEName()const { return eName_; } std::string QueryMaterialResult::getAddress()const { return address_; } std::string QueryMaterialResult::getLoaUrl()const { return loaUrl_; } std::string QueryMaterialResult::getPassportUrl()const { return passportUrl_; } std::string QueryMaterialResult::getName()const { return name_; } int QueryMaterialResult::getLoaStatus()const { return loaStatus_; } std::string QueryMaterialResult::getTown()const { return town_; } std::vector<std::string> QueryMaterialResult::getReviewAdditionalFiles()const { return reviewAdditionalFiles_; } std::string QueryMaterialResult::getContactNumber()const { return contactNumber_; } std::string QueryMaterialResult::getLegalNoticeUrl()const { return legalNoticeUrl_; } std::string QueryMaterialResult::getContactAddress()const { return contactAddress_; } int QueryMaterialResult::getStatus()const { return status_; } std::string QueryMaterialResult::getReviewApplicationFile()const { return reviewApplicationFile_; } std::string QueryMaterialResult::getCity()const { return city_; } std::string QueryMaterialResult::getProvince()const { return province_; } std::string QueryMaterialResult::getEAddress()const { return eAddress_; } std::string QueryMaterialResult::getIdCardUrl()const { return idCardUrl_; } int QueryMaterialResult::getType()const { return type_; } std::string QueryMaterialResult::getBusinessLicenceUrl()const { return businessLicenceUrl_; } long QueryMaterialResult::getExpirationDate()const { return expirationDate_; } std::string QueryMaterialResult::getContactZipcode()const { return contactZipcode_; } std::string QueryMaterialResult::getNote()const { return note_; } int QueryMaterialResult::getRegion()const { return region_; } std::string QueryMaterialResult::getContactEmail()const { return contactEmail_; } std::string QueryMaterialResult::getCountry()const { return country_; } long QueryMaterialResult::getId()const { return id_; } std::string QueryMaterialResult::getContactName()const { return contactName_; }
24.03719
88
0.737322
[ "vector", "model" ]
d19cca52db7a2360b897fc8999932c21a5ad5d79
37,345
hpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_ip_static_cfg_4.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_ip_static_cfg_4.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_ip_static_cfg_4.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_IOS_XR_IP_STATIC_CFG_4_ #define _CISCO_IOS_XR_IP_STATIC_CFG_4_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> #include "Cisco_IOS_XR_ip_static_cfg_0.hpp" #include "Cisco_IOS_XR_ip_static_cfg_2.hpp" #include "Cisco_IOS_XR_ip_static_cfg_3.hpp" namespace cisco_ios_xr { namespace Cisco_IOS_XR_ip_static_cfg { class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRoute::VrfNextHopTable::VrfNextHopNextHopAddress : public ydk::Entity { public: VrfNextHopNextHopAddress(); ~VrfNextHopNextHopAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf next_hop_address; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRoute::VrfNextHopTable::VrfNextHopNextHopAddress class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRoute::VrfNextHopTable::VrfNextHopNextHopAddressExplicitPathName : public ydk::Entity { public: VrfNextHopNextHopAddressExplicitPathName(); ~VrfNextHopNextHopAddressExplicitPathName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf next_hop_address; //type: string ydk::YLeaf explicit_path_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRoute::VrfNextHopTable::VrfNextHopNextHopAddressExplicitPathName class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRoute::VrfNextHopTable::VrfNextHopExplicitPathName : public ydk::Entity { public: VrfNextHopExplicitPathName(); ~VrfNextHopExplicitPathName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf explicit_path_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRoute::VrfNextHopTable::VrfNextHopExplicitPathName class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes : public ydk::Entity { public: VrfRecurseRoutes(); ~VrfRecurseRoutes(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class VrfRecurseRoute; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute ydk::YList vrf_recurse_route; }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute : public ydk::Entity { public: VrfRecurseRoute(); ~VrfRecurseRoute(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf vrf_name; //type: string class VrfRecursiveNextHopTable; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_ip_static_cfg::RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable> vrf_recursive_next_hop_table; }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable : public ydk::Entity { public: VrfRecursiveNextHopTable(); ~VrfRecursiveNextHopTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class VrfNextHopInterfaceName; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopInterfaceName class VrfNextHopInterfaceNameNextHopAddress; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopInterfaceNameNextHopAddress class VrfNextHopNextHopAddress; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopNextHopAddress class VrfNextHopNextHopAddressExplicitPathName; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopNextHopAddressExplicitPathName class VrfNextHopExplicitPathName; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopExplicitPathName ydk::YList vrf_next_hop_interface_name; ydk::YList vrf_next_hop_interface_name_next_hop_address; ydk::YList vrf_next_hop_next_hop_address; ydk::YList vrf_next_hop_next_hop_address_explicit_path_name; ydk::YList vrf_next_hop_explicit_path_name; }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopInterfaceName : public ydk::Entity { public: VrfNextHopInterfaceName(); ~VrfNextHopInterfaceName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopInterfaceName class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopInterfaceNameNextHopAddress : public ydk::Entity { public: VrfNextHopInterfaceNameNextHopAddress(); ~VrfNextHopInterfaceNameNextHopAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_name; //type: string ydk::YLeaf next_hop_address; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopInterfaceNameNextHopAddress class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopNextHopAddress : public ydk::Entity { public: VrfNextHopNextHopAddress(); ~VrfNextHopNextHopAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf next_hop_address; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopNextHopAddress class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopNextHopAddressExplicitPathName : public ydk::Entity { public: VrfNextHopNextHopAddressExplicitPathName(); ~VrfNextHopNextHopAddressExplicitPathName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf next_hop_address; //type: string ydk::YLeaf explicit_path_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopNextHopAddressExplicitPathName class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopExplicitPathName : public ydk::Entity { public: VrfNextHopExplicitPathName(); ~VrfNextHopExplicitPathName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf explicit_path_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfRecurseRoutes::VrfRecurseRoute::VrfRecursiveNextHopTable::VrfNextHopExplicitPathName class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute : public ydk::Entity { public: VrfSegRoute(); ~VrfSegRoute(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class SegmentRouteNextHopTable; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_ip_static_cfg::RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable> segment_route_next_hop_table; }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable : public ydk::Entity { public: SegmentRouteNextHopTable(); ~SegmentRouteNextHopTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class VrfNextHopInterfaceName; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopInterfaceName class VrfNextHopInterfaceNameNextHopAddress; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopInterfaceNameNextHopAddress class VrfNextHopNextHopAddress; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopNextHopAddress class VrfNextHopNextHopAddressExplicitPathName; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopNextHopAddressExplicitPathName class VrfNextHopExplicitPathName; //type: RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopExplicitPathName ydk::YList vrf_next_hop_interface_name; ydk::YList vrf_next_hop_interface_name_next_hop_address; ydk::YList vrf_next_hop_next_hop_address; ydk::YList vrf_next_hop_next_hop_address_explicit_path_name; ydk::YList vrf_next_hop_explicit_path_name; }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopInterfaceName : public ydk::Entity { public: VrfNextHopInterfaceName(); ~VrfNextHopInterfaceName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopInterfaceName class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopInterfaceNameNextHopAddress : public ydk::Entity { public: VrfNextHopInterfaceNameNextHopAddress(); ~VrfNextHopInterfaceNameNextHopAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_name; //type: string ydk::YLeaf next_hop_address; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopInterfaceNameNextHopAddress class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopNextHopAddress : public ydk::Entity { public: VrfNextHopNextHopAddress(); ~VrfNextHopNextHopAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf next_hop_address; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopNextHopAddress class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopNextHopAddressExplicitPathName : public ydk::Entity { public: VrfNextHopNextHopAddressExplicitPathName(); ~VrfNextHopNextHopAddressExplicitPathName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf next_hop_address; //type: string ydk::YLeaf explicit_path_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopNextHopAddressExplicitPathName class RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopExplicitPathName : public ydk::Entity { public: VrfNextHopExplicitPathName(); ~VrfNextHopExplicitPathName(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf explicit_path_name; //type: string ydk::YLeaf bfd_fast_detect; //type: boolean ydk::YLeaf minimum_interval; //type: uint32 ydk::YLeaf detect_multiplier; //type: uint32 ydk::YLeaf metric; //type: uint32 ydk::YLeaf tag; //type: uint32 ydk::YLeaf permanent; //type: boolean ydk::YLeaf vrf_lable; //type: uint32 ydk::YLeaf tunnel_id; //type: uint32 ydk::YLeaf object_name; //type: string ydk::YLeaf description; //type: string ydk::YLeaf load_metric; //type: uint32 ydk::YLeaf index_; //type: string }; // RouterStatic::DefaultVrf::AddressFamily::Vrfipv6::VrfMulticast::DefaultTopology::VrfPrefixTopologies::VrfPrefixTopology::VrfSegRoute::SegmentRouteNextHopTable::VrfNextHopExplicitPathName class RouterStatic::MaximumRoutes : public ydk::Entity { public: MaximumRoutes(); ~MaximumRoutes(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ipv6_routes; //type: uint32 ydk::YLeaf ipv4_routes; //type: uint32 }; // RouterStatic::MaximumRoutes } } #endif /* _CISCO_IOS_XR_IP_STATIC_CFG_4_ */
61.021242
286
0.72904
[ "vector" ]
d1a68eaa5c8f9b305facd55d6d1c472f04f2505d
24,521
cpp
C++
src/plrsController.cpp
suerfu/polaris
055bef93bbb0fba74bcc1a53cb7d8d84d70d9b05
[ "MIT" ]
null
null
null
src/plrsController.cpp
suerfu/polaris
055bef93bbb0fba74bcc1a53cb7d8d84d70d9b05
[ "MIT" ]
null
null
null
src/plrsController.cpp
suerfu/polaris
055bef93bbb0fba74bcc1a53cb7d8d84d70d9b05
[ "MIT" ]
1
2020-08-06T22:54:26.000Z
2020-08-06T22:54:26.000Z
#include "plrsController.h" #include "plrsModuleInput.h" #include "plrsModuleInterface.h" #include <cstdlib> #include <unistd.h> #include <dlfcn.h> #include <iostream> #include <map> #include <string> using namespace std; plrsController::plrsController( ConfigParser* m) : cparser(m){ Print( "Constructing polaris controller\n", DEBUG); bool found = false; state = NUL; // initial default state pthread_mutex_init( &mux_state, 0); pthread_mutex_init( &mux_fsm, 0); pthread_mutex_init( &mux_buffer, 0); pthread_mutex_init( &mux_cmd, 0); pthread_mutex_init( &mux_time, 0); pthread_mutex_init( &mux_flag, 0); Module ctrl; //ctrl.buffer = circular_buffer< void* >(); //ctrl.buffer_cmd = circular_buffer<string>(); ctrl.fsm = 0; ctrl.thread = 0; module.push_back( ctrl); module_table[ "ctrl" ] = 0; if( !cparser->GetBool("/cmdl/disable-input", false) ){ InsModule( new plrsModuleInput( this ), "input" ); } start_time = 0; max_run_time = cparser->GetInt("/cmdl/time", &found); // obtains daq running time. if( found){ Print( "Maximum run-time is " + cparser->GetString("/cmdl/time") + " seconds\n", DEBUG); } else{ Print( "Maximum run-time is 1 week\n", DEBUG); max_run_time = 604800; } stop_flag = false; start_time_ms = std::chrono::high_resolution_clock::now(); } plrsController::~plrsController(){ if( GetState()!=ERROR ) while( !ChangeState(END) ); // wait for state to update. for( int i=module.size()-1; i>0; --i){ if( module[i].fsm != 0 ){ RmModule(i); } } Print( "Good bye!\n", INFO); } void plrsController::StateLoop(){ Print( "Loading modules...\n", INFO); LoadModules(); Print( "Modules loaded\n\n", DETAIL); DAQSTATE nxt; while( 1 ){ if( GetState()==END ) break; else if( GetState()==ERROR ){ ChangeState( ERROR ); break; } nxt = GetNextState(); switch( GetState() ){ case NUL : if( nxt==NUL ) break; else if( nxt==INIT ){ Print( "Initializing modules...\n", INFO); if ( !ChangeState( INIT ) ){ Print( "Error initializing modules\n\n", ERR); SetState( ERROR ); } else{ Print( "Modules initialized\n\n", INFO); } } else{ SetState( ERROR ); Print( "Invalid state transition from NULL to "+GetStateName( nxt )+"\n\n", ERR); } break; case INIT : if( nxt==INIT ) break; else if( nxt==CONFIG ){ Print( "Configuring modules...\n", INFO); if( !ChangeState( CONFIG ) ){ Print( "Error configuring modules\n\n", ERR); SetState( ERROR ); } else{ Print( "Modules configured\n\n", DETAIL); } } else if( nxt==END ){ Print( "Deinitializing modules...\n", INFO); if( !ChangeState( END ) ){ Print( "Error cleaning up modules\n\n", ERR); SetState( ERROR ); } else{ Print( "Modules deinitialized\n\n", DETAIL); } } else{ SetState( ERROR ); Print( "Invalid state transition from INIT to "+GetStateName( nxt )+"\n\n", ERR); } break; case CONFIG : if( nxt==CONFIG ) break; else if( nxt==RUN ){ start_time = GetTimeStamp(); Print( "Run starting...\n", INFO); if( !ChangeState( RUN ) ){ Print( "Error starting run\n\n", ERR); SetState( ERROR ); } else{ Print( "Run started\n\n", DETAIL); } } else if( nxt==INIT ){ Print( "Deconfiguring modules...\n", INFO); if( !ChangeState( INIT ) ){ Print( "Error unconfiguring modules\n\n", ERR); SetState( ERROR ); } else{ Print( "Modules deconfigured\n\n", DETAIL); } } else{ Print( "Invalid state transition from CONFIG to "+GetStateName( nxt )+"\n\n", ERR); SetState( ERROR ); } break; case RUN : if( nxt==RUN ) break; else if( nxt==RUN_PAUSE ){ Print( "Pausing...\n", INFO); if( !ChangeState( RUN_PAUSE ) ){ Print( "Error pausing...\n\n", ERR); SetState( ERROR ); } else{ Print( "Run paused\n\n", INFO); } } else if( nxt==CONFIG ){ Print( "Stopping run...\n", INFO); if( !ChangeState( CONFIG ) ){ Print( "Error stopping run\n\n", ERR); SetState( ERROR ); } else{ Print( "Run stopped\n\n", DETAIL); } } else{ Print( "Invalid state transition from RUN to "+GetStateName( nxt )+"\n\n", ERR); SetState( ERROR ); } break; case RUN_PAUSE : if( nxt==RUN_PAUSE ) break; else if( nxt==RUN ){ Print( "Resuming run...\n", INFO); if( !ChangeState( RUN ) ){ Print( "Error resuming run...\n\n", ERR); SetState( ERROR ); } else{ Print( "Run resumed\n\n", DETAIL); } } else if( nxt==CONFIG ){ Print( "Stopping run...\n", INFO); if( !ChangeState( CONFIG ) ){ Print( "Error stopping run\n\n", ERR); SetState( ERROR ); } else{ Print( "Run stopped\n\n", DETAIL); } } else{ Print( "Invalid state transition from RUN to "+GetStateName( nxt )+"\n\n", ERR); SetState( ERROR ); } break; case END : if( !ChangeState( END )){ Print( "Error cleaning up\n\n", ERR); SetState( ERROR ); } break; case ERROR: ChangeState( ERROR ); break; default: break; } sleep(1); CommandHandler(); sched_yield(); } } unsigned int plrsController::GetTimeStamp(){ unsigned int t; pthread_mutex_lock( &mux_time); t = time(0); // mark Better to use a robust and system-independent way. pthread_mutex_unlock( &mux_time); return t; } ConfigParser* plrsController::GetConfigParser(){ return cparser; } void plrsController::LoadModules(){ Print( "Searching config file for list of modules...\n", DEBUG); std::map< string, vector<string> > mdl = cparser->GetListOfParameters("/module/"); // mdl contains module names such as /module/daq/, /module/recorder/ std::map< string, vector<string> >::iterator itr; bool found, enabled; for( itr=mdl.begin(); itr!=mdl.end(); itr++){ found = enabled = false; enabled = cparser->GetBool( itr->first+"enable", &found); if( found && enabled ){ string libname = cparser->GetString( itr->first+"lib"); if( libname=="" ){ Print( "Warning: "+cparser->GetString( itr->first)+" no library name is specified. Using libpolaris as default", DETAIL); libname = "libpolaris.so"; } string fcnname = cparser->GetString( itr->first+"fcn"); if( fcnname=="" ){ Print( "Error: no function name in library " + libname + "\n", ERR); ChangeState( ERROR ); return; } size_t end = itr->first.find_last_of('/'); size_t beg = itr->first.find_last_of('/', end-1); InsModule( libname, fcnname, itr->first.substr( beg+1, end-beg-1) ); } } if( GetState()==ERROR ) return; string to_print = "Following modules are enabled :\n"; string sp = " "; for( unsigned int i=0; i<module.size(); ++i){ if( module[i].fsm!=0 ){ to_print += sp + " |-"+module[i].fsm->GetModuleName()+"\n"; } } to_print += "\n"; Print( to_print, INFO); } // Insert module from library. void plrsController::InsModule( const string& lib, const string& fcn, const string& modname ){ Module mod; char *error; // check whether a library has been opened or not. // if opened, get its handle; if not, open and insert the handle. // mod.handle = LibraryOpen( lib ); if( mod.handle==0 ){ mod.handle = dlopen( lib.c_str(), RTLD_NOW | RTLD_GLOBAL); Print( "Opening library "+lib+"...\n", DETAIL); if ( !mod.handle ) { Print( "Error: cannot open library "+lib+" - "+string(dlerror())+"\n", ERR); ChangeState(ERROR); return; } dlerror(); } typedef plrsStateMachine* (*creator) (plrsController*); typedef void (*destroyer) (plrsStateMachine*); mod.helper_creator = (creator) dlsym( mod.handle, ("create_"+fcn).c_str()); if ((error = dlerror()) != 0) { Print( "cannot find creator function create_"+fcn+'\t'+string(error)+"\n", ERR); ChangeState(ERROR); return; } mod.helper_destroyer = (destroyer) dlsym( mod.handle, ("destroy_"+fcn).c_str()); if ( (error=dlerror()) != 0 ) { Print( "cannot find destroyer function destroy_"+fcn+'\t'+string(error)+"\n", ERR); ChangeState(ERROR); return; } // initialize aspects of the module. pthread_mutex_lock( &mux_buffer); pthread_mutex_lock( &mux_cmd); pthread_mutex_lock( &mux_fsm); mod.libname = lib; mod.fcnname = fcn; mod.buffer = circular_buffer< void* >(); mod.buffer_cmd = circular_buffer< plrsCommand >(); plrsStateMachine* new_fsm = mod.helper_creator( this ); new_fsm->SetModuleName( modname ); mod.fsm = new_fsm; pthread_t* nthrd = new pthread_t; mod.thread = nthrd; module.push_back( mod ); int id = module.size()-1; new_fsm->SetID( id ); module_table[ new_fsm->GetModuleName()] = id; pthread_create( nthrd, 0, LaunchStateMachine, new_fsm ); pthread_mutex_unlock( &mux_fsm); pthread_mutex_unlock( &mux_cmd); pthread_mutex_unlock( &mux_buffer); Print( "Module "+new_fsm->GetModuleName()+" inserted\n", DETAIL); } void plrsController::InsModule( plrsStateMachine* p, const string& modname ){ Module mod; mod.handle = 0; mod.libname = mod.fcnname = ""; mod.helper_creator = 0; mod.helper_destroyer = 0; // since pointer already acquired, add dummy variable. pthread_mutex_lock( &mux_buffer); pthread_mutex_lock( &mux_cmd); pthread_mutex_lock( &mux_fsm); mod.fsm = p; p->SetModuleName( modname); mod.buffer = circular_buffer< void* >(); mod.buffer_cmd = circular_buffer<plrsCommand>(); pthread_t* new_thread = new pthread_t; mod.thread = new_thread; module.push_back( mod); int id = module.size()-1; p->SetID( id ); module_table[ p->GetModuleName()] = id; pthread_create( new_thread, 0, LaunchStateMachine, p); pthread_mutex_unlock( &mux_fsm); pthread_mutex_unlock( &mux_cmd); pthread_mutex_unlock( &mux_buffer); } void plrsController::RmModule( unsigned int ID){ string libname = ""; void* handle_to_lib = 0; pthread_mutex_lock( &mux_fsm); if( ID<module.size() ){ if( module[ID].fsm != 0 ){ Print("Terminating thread " + module[ID].fsm->GetModuleName() + "...\n", DETAIL); pthread_join( *module[ID].thread, 0); libname = module[ID].libname; handle_to_lib = module[ID].handle; if( module[ID].handle != 0 ){ module[ID].helper_destroyer( module[ID].fsm ); module[ID].handle = 0; module[ID].libname = module[ID].fcnname = ""; module[ID].helper_creator = 0; module[ID].helper_destroyer = 0; module[ID].fsm = 0; } else{ delete module[ID].fsm; module[ID].fsm = 0; } } } pthread_mutex_unlock( &mux_fsm); module_table.erase( GetNameByID(ID) ); if( handle_to_lib!=0 && libname!="" ){ if( LibraryOpen( libname )==0 ){ dlclose( handle_to_lib ); Print( "Closing library " + libname + "...\n", INFO); } } } void* LaunchStateMachine( void* p){ plrsStateMachine* ptr = (plrsStateMachine*)(p); ptr->EventLoop(); return 0; } // as soon as new thread is created, this function is called. int plrsController::GetIDByName( const string& s){ int id = 0; pthread_mutex_lock( &mux_fsm); map< string, int>::iterator itr = module_table.find( s ); if( itr==module_table.end() ){ id = -1; Print( "Failed to find module "+s+"\n", ERR); } else{ id = module_table[s]; } pthread_mutex_unlock( &mux_fsm); return id; } string plrsController::GetNameByID( const int a){ string s; pthread_mutex_lock( &mux_fsm); map< string, int>::iterator itr; for( itr = module_table.begin(); itr!=module_table.end(); ++itr){ if( itr->second==a) s = itr->first; } pthread_mutex_unlock( &mux_fsm); return s; } bool plrsController::ChangeState( DAQSTATE s, unsigned int wait_time){ if( GetState()==ERROR ) s = ERROR; stringstream strm; strm << "Controller changing state to " << GetStateName(s) << "...\n"; Print( strm.str(), DEBUG); // ask all modules to change state pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); ++i ){ if( module[i].fsm!=0 ) module[i].fsm->SetState( s ); } pthread_mutex_unlock( &mux_fsm); InitializeWDTimer(); bool consistent = true; bool error = false; while( GetWDTimer() > GetTimeStamp() ){ consistent = CheckStateConsistency(); if( consistent ){ SetState( s ); PrintState( DETAIL); Print( "Controller state successfully changed\n", DEBUG); return true; } error = CheckErrorFlag(); if( error ){ PrintState( ERR ); return false; } CommandHandler(); usleep(100000); sched_yield(); } Print( "Time out error\n", ERR); PrintState(); return false; } void plrsController::PrintState( VERBOSITY v ){ stringstream ss; int len = 4; // length of longest module name pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); i++) if( module[i].fsm!=0 ){ int l = int(module[i].fsm->GetModuleName().length()); len = len > l ? len : l; } pthread_mutex_unlock( &mux_fsm); pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); i++){ if( module[i].fsm==0 ) ss << "\n\t\t| ctrl" << string(len-4, ' ') << " | ------ | " << GetStateName( GetState() ) << " |\n"; else{ int l = module[i].fsm->GetModuleName().length(); ss << "\t\t| " << module[i].fsm->GetModuleName() << string(len-l, ' ') << " | " << GetStateName( module[i].fsm->GetStatus()); ss << " | " << GetStateName( module[i].fsm->GetState()) << " |\n"; } } pthread_mutex_unlock( &mux_fsm); ss << "\n"; Print( ss.str(), v); } void plrsController::PrintBufferStatus( VERBOSITY v ){ stringstream ss; int len = 4; // length of longest module name pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); i++) if( module[i].fsm!=0 ){ int l = int(module[i].fsm->GetModuleName().length()); len = len > l ? len : l; } pthread_mutex_unlock( &mux_fsm); pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); i++){ if( module[i].fsm==0 ) ss << "\n\t\t" << i << " ctrl" << string(len+1-4, ' ') << module[i].buffer.size() << '\n'; else{ int l = module[i].fsm->GetModuleName().length(); ss << "\t\t" << i << ' ' << module[i].fsm->GetModuleName() << string(len+1-l, ' ') << module[i].buffer.size() <<'\n'; } } pthread_mutex_unlock( &mux_fsm); ss << "\n"; Print( ss.str(), v); } // The flow of state machine is controlled here. DAQSTATE plrsController::GetNextState( ){ if( CheckErrorFlag() ) return ERROR; switch( GetState() ){ case NUL : return INIT; case INIT : if( CheckStopFlag() ) return END; else return CONFIG; case CONFIG : if( CheckStopFlag() ) return INIT; else return RUN; case RUN : if( CheckStopFlag() ) return CONFIG; else if( CheckPauseFlag() ) return RUN_PAUSE; else return RUN; case RUN_PAUSE : if( CheckStopFlag() ) return CONFIG; else if( !CheckPauseFlag() ) return RUN; else return RUN_PAUSE; case END : return END; case ERROR : return ERROR; //irrecoverable from error default : Print( "Controller unrecognized state.\n", ERR); break; } return GetState(); } void plrsController::SetState( DAQSTATE st){ if( GetState()==ERROR ) return; pthread_mutex_lock( &mux_state); state = st; pthread_mutex_unlock( &mux_state); } DAQSTATE plrsController::GetState(){ return state; } bool plrsController::CheckStateConsistency(){ bool consistent = true; pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); i++){ if( module[i].fsm!=0 ) if( module[i].fsm->GetState()!=module[i].fsm->GetStatus() ){ consistent = false; break; } } pthread_mutex_unlock( &mux_fsm); return consistent; } bool plrsController::CheckErrorFlag(){ bool error = false; if( GetState()==ERROR ) return true; pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); i++){ if( module[i].fsm!=0 ) if( module[i].fsm->GetStatus()==ERROR ){ pthread_mutex_lock( &mux_flag); error = true; pthread_mutex_unlock( &mux_flag); break; } } pthread_mutex_unlock( &mux_fsm); return error; } bool plrsController::CheckStopFlag(){ bool stop = false; // if stop flag has been set before, return it. // pthread_mutex_lock( &mux_flag); if( stop_flag ) stop = true; pthread_mutex_unlock( &mux_flag); if( stop ){ return true; } // check existing error // pthread_mutex_lock( &mux_fsm); for( unsigned int i=0; i<module.size(); i++){ if( module[i].fsm!=0 ) if( module[i].fsm->GetStatus()==ERROR ){ pthread_mutex_lock( &mux_flag); stop = stop_flag = true; pthread_mutex_unlock( &mux_flag); SetState( ERROR ); break; } } pthread_mutex_unlock( &mux_fsm); // time out only possible during run. // if( GetState()==RUN ){ if ( GetTimeStamp()-start_time > max_run_time ) { Print( "Maximum run time has passed\n", DEBUG); pthread_mutex_lock( &mux_flag); stop = stop_flag = true; pthread_mutex_unlock( &mux_flag); } } return stop; } int plrsController::PushToBuffer( unsigned int i, void* data){ int s = -1; pthread_mutex_lock( &mux_buffer); if( i<module.size() ){ module[i].buffer.push_back(data); s = module[i].buffer.size(); } pthread_mutex_unlock( &mux_buffer ); return s; } void* plrsController::PullFromBuffer( unsigned int i){ void* p = 0; pthread_mutex_lock( &mux_buffer); if( i<module.size() ){ if( (!module[i].buffer.empty()) ){ p = module[i].buffer.front(); module[i].buffer.pop_front(); } } pthread_mutex_unlock( &mux_buffer); return p; } void plrsController::PushCommand( int i, plrsCommand c){ pthread_mutex_lock( &mux_cmd ); if( i>=0 && i<int( module.size() ) ){ module[i].buffer_cmd.push_back( c ); } pthread_mutex_unlock( &mux_cmd); } plrsCommand plrsController::PullCommand( int i){ plrsCommand cmd; pthread_mutex_lock( &mux_cmd); if( i>=0 && i<int( module.size() ) ){ if( (!module[i].buffer_cmd.empty()) ){ cmd = module[i].buffer_cmd.front(); module[i].buffer_cmd.pop_front(); } else cmd.cmd = ""; } else cmd.cmd = ""; pthread_mutex_unlock( &mux_cmd); return cmd; } void plrsController::CommandHandler(){ plrsCommand command = PullCommand(0); string cmd = command.cmd; int id = command.from; if( cmd=="quit" || cmd=="q" ){ stop_flag = true; Print( "Stop signal received\n", INFO); } else if( cmd=="max-evt" && GetState()==RUN ){ stop_flag = true; Print( "Maximum number of event reached\n", INFO); } else if( cmd=="stat" ){ PrintState( INFO ); } else if( cmd=="buff" ){ PrintBufferStatus( INFO ); } else if( cmd=="pause" ){ pause_req[id]=cmd; } else if( cmd=="resume" ){ pause_req.erase( id ); } } bool plrsController::CheckPauseFlag(){ return (pause_req.size()!=0); } map< string, int > plrsController::GetModuleTable(){ map< string, int > tab; pthread_mutex_lock( &mux_fsm); tab = module_table; pthread_mutex_unlock( &mux_fsm); return tab; } void* plrsController::LibraryOpen( const string& libname ){ void* handle_return = 0; vector< Module >::iterator itr; pthread_mutex_lock( &mux_fsm); for( itr = module.begin(); itr!=module.end(); ++itr){ if( itr->libname==libname ){ if( itr->handle!=0 ){ handle_return = itr->handle; break; } } } pthread_mutex_unlock( &mux_fsm); return handle_return; }
26.281886
141
0.494882
[ "vector" ]
d1b218bcfadb3d84d8b0a9ce0f636bf9c06e5b1e
2,532
cpp
C++
src/2021/day20.cpp
BruJu/AdventOfCode
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
1
2020-12-11T13:37:06.000Z
2020-12-11T13:37:06.000Z
src/2021/day20.cpp
BruJu/AdventOfCode2020
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
null
null
null
src/2021/day20.cpp
BruJu/AdventOfCode2020
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
null
null
null
#include "../advent_of_code.hpp" #include <vector> #include <map> #include <set> #include <ostream> #include "../util/position.hpp" // Day 17 was boring, days 18 and 19 were too long, today is // "I'm very smart with my non representative only example" static std::vector<bool> compute_enchancement(const std::string & s) { std::vector<bool> r; for (const char c : s) { r.push_back(c == '#'); } return r; } struct Grid { std::map<bj::Position, bool> pixels; bool padding; const std::vector<bool> * enhancement; Grid(const std::vector<bool> * enhancement, std::set<bj::Position> lit) : padding(false), enhancement(enhancement) { for (const auto & position : lit) { pixels.emplace(position, true); } } Grid next() const { Grid n; n.enhancement = enhancement; n.padding = padding ? enhancement->back() : enhancement->front(); const auto consider = [&](bj::Position pos) { int enhance_code = 0; for (int dy = -1; dy <= 1; ++dy) { for (int dx = -1; dx <= 1; ++dx) { enhance_code = enhance_code * 2; auto it = pixels.find(bj::Position{ pos.x + dx, pos.y + dy }); bool is_lit; if (it == pixels.end()) { is_lit = padding; } else { is_lit = it->second; } if (is_lit) { enhance_code += 1; } } } bool will_be_lit = (*enhancement)[enhance_code]; if (n.padding || will_be_lit) n.pixels.emplace(pos, will_be_lit); }; for (const auto & [position, is_lit] : pixels) { consider(position); for (const auto & neighbour : position.get_8_neighbours()) { consider(neighbour); } } return n; } private: Grid() = default; }; Output day_2021_20(const std::vector<std::string> & lines, const DayExtraInfo &) { std::vector<bool> image_enhancement = compute_enchancement(lines[0]); std::set<bj::Position> origin; for (size_t line = 0; line + 2 != lines.size(); ++line) { for (size_t col = 0; col != lines[line + 2].size(); ++col) { if (lines[line + 2][col] == '#') { origin.emplace(bj::Position{ int(col), int(line) }); } } } Grid grid(&image_enhancement, origin); for (int i = 0; i != 2; ++i) { grid = grid.next(); } const long long int part_a = grid.pixels.size(); for (int i = 2; i != 50; ++i) { grid = grid.next(); } const long long int part_b = grid.pixels.size(); return Output(part_a, part_b); }
23.886792
82
0.56951
[ "vector" ]
d1b8f02205078d18a908b9babbcf279b73f9201e
1,960
cpp
C++
problems/atcoder/abc224/d---8-puzzle-on-graph/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/atcoder/abc224/d---8-puzzle-on-graph/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/atcoder/abc224/d---8-puzzle-on-graph/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #ifdef LOCAL #include "code/formatting.hpp" #else #define debug(...) (void)0 #endif using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); constexpr int N = 9; int M; cin >> M; vector<int> adj(N); for (int i = 0; i < M; i++) { int u, v; cin >> u >> v, u--, v--; adj[u] |= 1 << v; adj[v] |= 1 << u; } int64_t mask[N + 1]; for (int i = 0; i <= N; i++) { mask[i] = int64_t(0xf) << (4 * i); } // Position i holds piece x auto rem = [&](int64_t s, int i) { return s & ~mask[i]; }; auto get = [&](int64_t s, int i) { return (s & mask[i]) >> (4 * i); }; auto add = [&](int64_t s, int i, int64_t x) { return rem(s, i) | x << (4 * i); }; auto zero = [&](int64_t s) { for (int i = 0; i < N; i++) if (get(s, i) == 0) return i; assert(false); }; int64_t init = 0, goal = 0; for (int i = 0; i < N - 1; i++) { int x; cin >> x, x--; // piece i+1 is on vertex x, we want it on vertex i init = add(init, x, i + 1); goal = add(goal, i, i + 1); } if (init == goal) { cout << 0 << '\n'; return 0; } vector<int64_t> bfs = {init}; vector<int> cost = {0}; unordered_set<int64_t> vis = {init}; for (int j = 0, S = 1; j < S; j++) { auto u = bfs[j]; int z = zero(u); for (int i = 0; i < N; i++) { if (adj[z] >> i & 1) { if (auto v = add(rem(u, i), z, get(u, i)); !vis.count(v)) { bfs.push_back(v), S++; cost.push_back(cost[j] + 1); vis.insert(v); if (v == goal) { cout << cost[j] + 1 << '\n'; return 0; } } } } } cout << -1 << '\n'; return 0; }
25.128205
85
0.392857
[ "vector" ]
d1becf0048a93a272e35bac8432da80800e8239c
3,081
cpp
C++
source/Esdiel/Graphics/Transformable.cpp
MetGang/Esdiel
0b75a3e10b16291ce9055a9673a6bc3f36a224f8
[ "MIT" ]
2
2021-08-04T22:18:02.000Z
2022-01-09T21:53:49.000Z
source/Esdiel/Graphics/Transformable.cpp
MetGang/Esdiel
0b75a3e10b16291ce9055a9673a6bc3f36a224f8
[ "MIT" ]
null
null
null
source/Esdiel/Graphics/Transformable.cpp
MetGang/Esdiel
0b75a3e10b16291ce9055a9673a6bc3f36a224f8
[ "MIT" ]
null
null
null
#include <Esdiel/Graphics/Transformable.hpp> // C++ #include <string> // glm #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtc/type_ptr.hpp> namespace esd { Transformable::Transformable() : m_position { 0.0f, 0.0f, 0.0f } , m_origin { 0.0f, 0.0f, 0.0f } , m_rotation { 0.0f, 0.0f, 0.0f } , m_scale { 1.0f, 1.0f, 1.0f } , m_cachedTransform { 1.0f } , m_needsUpdate { false } { } Transformable::Transformable(Vec3f const& position, Vec3f const& origin, Vec3f const& rotation, Vec3f const& scale) : m_position { position } , m_origin { origin } , m_rotation { rotation } , m_scale { scale } , m_cachedTransform {} , m_needsUpdate { true } { } void Transformable::SetTransform(Vec3f const& position, Vec3f const& origin, Vec3f const& rotation, Vec3f const& scale) { m_position = position; m_origin = origin; m_rotation = rotation; m_scale = scale; m_needsUpdate = true; } void Transformable::TranslatePosition(Vec3f const& offset) { m_position += offset; m_needsUpdate = true; } void Transformable::SetPosition(Vec3f const& position) { m_position = position; m_needsUpdate = true; } Vec3f const& Transformable::GetPosition() const { return m_position; } void Transformable::TranslateOrigin(Vec3f const& offset) { m_origin += offset; m_needsUpdate = true; } void Transformable::SetOrigin(Vec3f const& origin) { m_origin = origin; m_needsUpdate = true; } Vec3f const& Transformable::GetOrigin() const { return m_origin; } void Transformable::Rotate(Vec3f const& angle) { m_rotation += angle; m_needsUpdate = true; } void Transformable::SetRotation(Vec3f const& rotation) { m_rotation = rotation; m_needsUpdate = true; } Vec3f const& Transformable::GetRotation() const { return m_rotation; } void Transformable::Scale(Vec3f const& factor) { m_scale *= factor; m_needsUpdate = true; } void Transformable::SetScale(Vec3f const& scale) { m_scale = scale; m_needsUpdate = true; } Vec3f const& Transformable::GetScale() const { return m_scale; } Transform const& Transformable::GetTransform() const { M_UpdateTransform(); return m_cachedTransform; } Transform Transformable::GetInverseTransform() const { M_UpdateTransform(); return m_cachedTransform.Inversed(); } void Transformable::M_UpdateTransform() const { if (m_needsUpdate) { m_cachedTransform .SetIdentity() .Translate(m_position) .Rotate(m_rotation) .Scale(m_scale) .Translate(-m_origin); m_needsUpdate = false; } } }
20.677852
123
0.575787
[ "transform" ]
d1bf590ff10088be1e82953d40f1ac2e69ae8db4
974
hpp
C++
src/common/gltf/forward.hpp
jherico/glTF
e1a6b3cee67d241894855ceeef89606ff021beb6
[ "MIT" ]
null
null
null
src/common/gltf/forward.hpp
jherico/glTF
e1a6b3cee67d241894855ceeef89606ff021beb6
[ "MIT" ]
null
null
null
src/common/gltf/forward.hpp
jherico/glTF
e1a6b3cee67d241894855ceeef89606ff021beb6
[ "MIT" ]
null
null
null
// // Created by Bradley Austin Davis on 2016/07/17 // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #pragma once #ifndef jherico_gltf_forward_hpp #define jherico_gltf_forward_hpp #include <string> #include <glm/glm.hpp> namespace gltf { using glm::ivec2; using glm::uvec2; using glm::vec2; using glm::vec3; using glm::vec4; using glm::mat3; using glm::mat4; using glm::quat; class root; namespace scenes { class scene; class node; } namespace meshes { class mesh; } namespace buffers { class buffer; class view; class accessor; } namespace shaders { class shader; class program; } namespace textures { class image; } namespace materials { class material; } namespace skins { } } #endif
15.967213
88
0.603696
[ "mesh" ]
d1c4b9e993d614012229d7e3a141c802eada4d13
3,531
cc
C++
src/devices/tests/libdriver-integration-test/device-add-tests.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
3
2021-09-02T07:21:06.000Z
2022-03-12T03:20:10.000Z
src/devices/tests/libdriver-integration-test/device-add-tests.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/devices/tests/libdriver-integration-test/device-add-tests.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
2
2022-02-25T12:22:49.000Z
2022-03-12T03:20:10.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/ddk/binding.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include <memory> #include <fbl/unique_fd.h> #include <gtest/gtest.h> #include "integration-test.h" namespace libdriver_integration_test { class DeviceAddTest : public IntegrationTest { protected: Promise<void> CreateDevice(std::initializer_list<zx_device_prop_t> props, zx_status_t expected_status, std::unique_ptr<RootMockDevice>* root_device, std::unique_ptr<MockDevice>* child_device) { // Copy from props into a vector owned by the lambda, since a capture "by // value" of props does not copy deeply. std::vector<zx_device_prop_t> properties(props); return ExpectBind(root_device, [=, properties = std::move(properties)]( HookInvocation record, Completer<void> completer) { ActionList actions; actions.AppendAddMockDevice(loop_.dispatcher(), (*root_device)->path(), "first_child", std::move(properties), expected_status, std::move(completer), child_device); actions.AppendReturnStatus(expected_status); return actions; }); } }; // This test checks what happens when only one topological properties is // specified TEST_F(DeviceAddTest, OneTopologicalProperty) { std::unique_ptr<RootMockDevice> root_device; std::unique_ptr<MockDevice> child_device; auto promise = CreateDevice( { (zx_device_prop_t){BIND_TOPO_PCI, 0, BIND_TOPO_PCI_PACK(0, 0, 0)}, (zx_device_prop_t){BIND_PCI_VID, 0, 1234}, }, ZX_OK, &root_device, &child_device) .and_then([&]() -> Promise<void> { // Destroy the test device. This should cause an unbind of the child // device. root_device.reset(); return ExpectUnbindThenRelease(child_device); }); RunPromise(std::move(promise)); } // This test checks what happens when two different topological properties are // specified TEST_F(DeviceAddTest, TooManyTopologicalProperties) { std::unique_ptr<RootMockDevice> root_device; std::unique_ptr<MockDevice> child_device; auto promise = CreateDevice( { (zx_device_prop_t){BIND_TOPO_PCI, 0, BIND_TOPO_PCI_PACK(0, 0, 0)}, (zx_device_prop_t){BIND_TOPO_I2C, 0, BIND_TOPO_I2C_PACK(1)}, (zx_device_prop_t){BIND_PCI_VID, 0, 1234}, }, ZX_ERR_INVALID_ARGS, &root_device, &child_device); RunPromise(std::move(promise)); } // This test checks what happens when the same topological property is // specified twice TEST_F(DeviceAddTest, TooManyTopologicalPropertiesDuplicated) { std::unique_ptr<RootMockDevice> root_device; std::unique_ptr<MockDevice> child_device; auto promise = CreateDevice( { (zx_device_prop_t){BIND_TOPO_PCI, 0, BIND_TOPO_PCI_PACK(0, 0, 0)}, (zx_device_prop_t){BIND_TOPO_PCI, 0, BIND_TOPO_PCI_PACK(0, 0, 1)}, (zx_device_prop_t){BIND_PCI_VID, 0, 1234}, }, ZX_ERR_INVALID_ARGS, &root_device, &child_device); RunPromise(std::move(promise)); } } // namespace libdriver_integration_test
37.56383
95
0.644293
[ "vector" ]
d1cbd7e9f5750bda3075bd2fa1b3e8d7fa785342
3,547
hpp
C++
include/demos.hpp
dyigitpolat/komposto.ai
ee610053730d59207d073da18f645c9e27725189
[ "MIT" ]
1
2021-05-11T13:42:18.000Z
2021-05-11T13:42:18.000Z
include/demos.hpp
dyigitpolat/komposto.ai
ee610053730d59207d073da18f645c9e27725189
[ "MIT" ]
13
2021-05-16T19:56:32.000Z
2022-02-09T23:46:12.000Z
include/demos.hpp
dyigitpolat/komposto.ai
ee610053730d59207d073da18f645c9e27725189
[ "MIT" ]
null
null
null
#pragma once #include "harmonizer.hpp" #include "tuning_provider.hpp" #include "palette_generator.hpp" #include "motif_generator.hpp" #include "palette_generator.hpp" #include "section_generator.hpp" #include "composition_generator.hpp" #include "pattern_mutator.hpp" #include "rhythmic_motif_generator.hpp" #include "notes_to_midi.hpp" #include <iostream> namespace komposto { static frequency_t base_test_tone{110}; //static integer_t tuning_limit_p{11}; static integer_t palette_size{5}; static integer_t motif_beats{4}; static integer_t patterns_count{4}; static integer_t patterns_motif_count{2}; static harmonic_complexity_t harmonic_complexity{1.0}; static rhythmic_complexity_t rhythmic_complexity{0.3}; static Tuning tuning = TuningProvider::get_p_limit_tuning(11); static PaletteGenerator pg{base_test_tone}; static Palette p{pg.generate(tuning, palette_size)}; static RhythmicMotifGenerator rmg{}; static DynamicsGenerator dyn_gen{}; static MotifGenerator mg{rmg, dyn_gen}; static Motif m{mg.generate(p, motif_beats)}; static NotesToMidi n2m{}; static PatternGenerator pat_gen{MotifMutator{p}, mg }; static Pattern pat{pat_gen.generate(m, patterns_count)}; void test_reinit() { pg = PaletteGenerator{base_test_tone}; p = pg.generate(tuning, palette_size); rmg = RhythmicMotifGenerator{}; mg = MotifGenerator{rmg, dyn_gen}; m = mg.generate(p, motif_beats); pat_gen = PatternGenerator{MotifMutator{p}, mg}; pat = pat_gen.generate(m, patterns_motif_count); tuning = TuningProvider::get_just_harmonic_minor_tuning(); } void test_palette() { test_reinit(); for( Tone& t : p.tones_) { std::cout << t.ratio_.numerator_ << "/" << t.ratio_.denominator_ << ", "; } std::cout << std::endl; } void test_motif() { test_reinit(); for( Note& n : m.notes_) { std::cout << "(" << n.tone_.ratio_.numerator_ << "/" << n.tone_.ratio_.denominator_ << " : "; std::cout << n.timing_.duration_ << "), "; } std::cout << std::endl; } void test_pattern_with_midi() { test_reinit(); n2m.generate_midi_file(pat.get_notes(), "test.mid"); } void test_pattern_duration() { test_reinit(); std::cout << pat.get_duration() << std::endl; } void test_section_with_midi() { test_reinit(); SectionGenerator sec_gen = SectionGenerator{PatternMutator{p}, pat_gen, mg}; Section s = sec_gen.generate( p, motif_beats, patterns_count, patterns_motif_count); n2m.generate_midi_file(s.get_notes(), "test.mid"); } void test_composition_with_midi() { test_reinit(); SectionGenerator sec_gen = SectionGenerator{PatternMutator{p}, pat_gen, mg}; Section s = sec_gen.generate( p, motif_beats, patterns_count, patterns_motif_count); CompositionGenerator comp_gen = CompositionGenerator{sec_gen, pg}; Composition comp = comp_gen.generate( harmonic_complexity, rhythmic_complexity); n2m.generate_midi_file(comp.get_notes(), "test.mid"); } void test_pythagorean_walk() { test_reinit(); Tuning pyth{TuningProvider::get_pythagorean_tuning(8)}; PaletteGenerator::sort_ratios_ascending(pyth.harmonics_); std::vector<Note> notes; Timing time{0,1}; for(auto ratio : pyth.harmonics_) { notes.emplace_back(time, Tone(base_test_tone, ratio)); std::cout << ratio.numerator_ << "/" << ratio.denominator_ << " "; time.start_ += 1; } std::cout << std::endl; n2m.generate_midi_file(notes, "test.mid"); } }
25.335714
80
0.70031
[ "vector" ]
d1d03eda94a801c6f0cfb4b8b37799f05811f7e7
6,612
cpp
C++
game_step.cpp
BariumBlue/atomic
cafcc5832882b944fba32260738e811dca175d63
[ "MIT" ]
null
null
null
game_step.cpp
BariumBlue/atomic
cafcc5832882b944fba32260738e811dca175d63
[ "MIT" ]
null
null
null
game_step.cpp
BariumBlue/atomic
cafcc5832882b944fba32260738e811dca175d63
[ "MIT" ]
null
null
null
#include <ctime> #include <cstdlib> #include <cstdio> #include <cstring> #include <math.h> #include "game_step.h" /* randomly create atoms with the given params */ void init_rand_atoms(game_state *state, int n_atoms, atom_type atype, int max_x, int max_y) { int i, j; float x, y; atomDat atom; printf("randomly creating atoms\n"); /* instantiate stuff */ time_t t; t = time(NULL); // t = 1379410662; printf("seed is %ld\n", t); srand(t); int atoms_start = 0; if (state->n_atoms==0){ printf("adding new atoms to pristine place\n"); state->n_atoms = n_atoms; state->atoms = (atomDat *) calloc(sizeof(atomDat), state->n_atoms); } else { printf("adding new atoms to existing place"); atoms_start = state->n_atoms; state->n_atoms += n_atoms; state->atoms = (atomDat *) realloc(state->atoms, sizeof(atomDat)*state->n_atoms); } /* setup atom data */ atom.type = atype; atom.xspeed = 0.0; atom.yspeed = 0.0; atom.n_bonds = 0; atom.bonds = NULL; /* create the atoms */ for (i=atoms_start; i<state->n_atoms; i++){ /* make random unique coordinates */ while (1) { x = (float) (((int) rand())%max_x); y = (float) (((int) rand())%max_y); /* check that coordinates are unique */ for (j=0; j<i; j++) if (state->atoms[j].x == x && state->atoms[j].y == y) break; if (j==i) break; } atom.x = x; atom.y = y; state->atoms[i] = atom; } printf("finished randomly creating atoms\n----\n"); } /* calculate and return the attraction force of the bond */ xy_pair getForce(atom_chars *prop1, atom_chars *prop2, float xdist, float ydist) { float dist_sqrd = xdist*xdist + ydist*ydist; /* the distance unit vector */ float xvect = (xdist*xdist) / dist_sqrd; xvect = (xdist>0)? xvect : -xvect; float yvect = (ydist*ydist) / dist_sqrd; yvect = (ydist>0)? yvect : -yvect; float tforce; xy_pair force; /* get the total force */ /* if below minimum bond, use compressibility force */ if (dist_sqrd<= prop1->min_bond_len * prop2->min_bond_len){ tforce = -prop1->compress_resistForce * prop2->compress_resistForce; } /* if below ideal bond len */ else if (dist_sqrd<= prop1->ideal_bond_len * prop2->ideal_bond_len){ tforce = -prop1->bond_strength*prop2->bond_strength; } /* if above ideal bond len */ else{ tforce = prop1->bond_strength+prop2->bond_strength; } force.x = tforce*xvect; force.y = tforce*yvect; return force; } /* update the speed of each atom */ void update_speeds(game_state *state, float dt) { int a1, a2; float xdir, ydir; xy_pair force, tforce; atomDat *atom1, *atom2; atom_chars *prop1, *prop2; for (a1=0; a1<state->n_atoms; a1++){ atom1 = state->atoms + a1; prop1 = atom_prop(state, atom1->type); /* get the cumulative force of all bonds */ tforce.x = 0; tforce.y = 0; for (a2=0; a2<atom1->n_bonds; a2++){ atom2 = state->atoms + atom1->bonds[a2]; prop2 = atom_prop(state, atom2->type); xdir = atom2->x - atom1->x; ydir = atom2->y - atom1->y; force = getForce(prop1, prop2, xdir, ydir); tforce.x += force.x; tforce.y += force.y; } tforce.x *= dt; tforce.y *= dt; /* update the speed */ atom1->xspeed += (tforce.x)/prop1->weight; atom1->yspeed += (tforce.y)/prop1->weight; atom1->xspeed -= atom1->xspeed * state->friction * dt; atom1->yspeed -= atom1->yspeed * state->friction * dt; } } /* update the positions of the atoms. For now, wrapping will be enabled */ void move_atoms(game_state *state, float dt, int frame_w, int frame_h) { int a; atomDat *atom; for (a=0; a<state->n_atoms; a++){ atom = state->atoms + a; /* update positions */ atom->x+=atom->xspeed; atom->y+=atom->yspeed; /* wrapping */ if (atom->x<0) atom->x = (float) frame_w + atom->x; else if (atom->x > frame_w) atom->x = (float) atom->x - frame_w; if (atom->y<0) atom->y = (float) frame_h + atom->y; else if (atom->y > frame_h) atom->y = (float) atom->y - frame_h; } } void bond_atoms(game_state *state) { int a1, a2, j; float xdist, ydist, tdist_sqrd; atom_chars *prop1, *prop2; /* properties */ atomDat *atom1, *atom2; /* for every atom, see if it's close enough to bond with any other one */ for (a1=0; a1<state->n_atoms; a1++){ atom1 = state->atoms + a1; prop1 = atom_prop(state, atom1->type); /* check whether it can bond with any other atoms */ for (a2=a1+1; a2<state->n_atoms; a2++){ atom2 = state->atoms + a2; prop2 = atom_prop(state, atom2->type); /* check whether already bonded */ for (j=0; j<atom1->n_bonds; j++){ if (atom1->bonds[j] == a2) break; } if (j!=atom1->n_bonds) continue; /* if close enough, bond them */ xdist = atom1->x - atom2->x; ydist = atom1->y - atom2->y; tdist_sqrd = xdist*xdist + ydist*ydist; if (tdist_sqrd <= prop1->max_bond_len * prop2->max_bond_len){ atom1->bonds = (int *) realloc( atom1->bonds, sizeof(int) * ++atom1->n_bonds); atom1->bonds[atom1->n_bonds-1] = a2; atom2->bonds= (int *) realloc( atom2->bonds, sizeof(int) * ++atom2->n_bonds); atom2->bonds[atom2->n_bonds-1]=a1; } } } } /* if bonds are too far, break them. */ void break_bonds(game_state *state) //retest bond_atoms before testing this fun { int a1, a2, i, tmp; float xdist, ydist, tdist, tdist_sqrd; atomDat *atom1, *atom2; atom_chars *prop1, *prop2; /* for every atom, break the bond with any atoms that are too far */ for (a1=0; a1<state->n_atoms; a1++){ atom1 = state->atoms + a1; prop1 = atom_prop(state, atom1->type); /* check every bonded atom */ for (a2=0; a2<atom1->n_bonds; a2++){ atom2 = state->atoms + atom1->bonds[a2]; prop2 = atom_prop(state, atom2->type); /* if too far, break the bond */ xdist = atom1->x - atom2->x; ydist = atom1->y - atom2->y; tdist_sqrd = xdist*xdist + ydist*ydist; if (tdist_sqrd > prop1->max_bond_len * prop2->max_bond_len){ tmp = atom1->bonds[atom1->n_bonds-1]; atom1->bonds[atom1->n_bonds-1] = atom1->bonds[a2]; atom1->bonds[a2] = tmp; atom1->n_bonds--; /* find where atom1 is in atom2's bonds */ for (i=0; i<atom2->n_bonds; i++){ if (a1==atom2->bonds[i]) break; } tmp = atom2->bonds[atom2->n_bonds-1]; atom2->bonds[atom2->n_bonds-1] = atom2->bonds[i]; atom2->bonds[i] = tmp; atom2->n_bonds--; } } } } /* update the speeds, positions, and bonds of the atoms */ void update_atoms(game_state *state, float dt, float frame_w, float frame_h) { update_speeds(state, dt); move_atoms(state, dt, frame_w, frame_h); bond_atoms(state); break_bonds(state); }
23.118881
91
0.629462
[ "vector" ]
d1d1486599eef1a08dae7697729c07e1a8bc6427
1,902
hpp
C++
include/Aheuiplusplus/element.hpp
kmc7468/Aheuiplusplus
4ae8dfd457d62457b781c9abbfb6ceffc0f068e2
[ "MIT" ]
21
2018-06-10T11:40:10.000Z
2021-04-20T06:47:14.000Z
include/Aheuiplusplus/element.hpp
kmc7468/Aheuiplusplus
4ae8dfd457d62457b781c9abbfb6ceffc0f068e2
[ "MIT" ]
1
2018-06-20T13:57:00.000Z
2018-06-22T16:22:02.000Z
include/Aheuiplusplus/element.hpp
kmc7468/Aheuiplusplus
4ae8dfd457d62457b781c9abbfb6ceffc0f068e2
[ "MIT" ]
2
2018-06-17T13:35:59.000Z
2018-07-16T14:02:54.000Z
#ifndef AHEUIPLUSPLUS_HEADER_ELEMENT_HPP #define AHEUIPLUSPLUS_HEADER_ELEMENT_HPP #include <Aheuiplusplus/function.hpp> #include <cstdint> #include <memory> #include <variant> #include <vector> namespace app { enum class element_type { none, array = 0b0100000, reference = 0b1000000, number = 0b0000001, pointer = 0b0000010, instance = 0b0000100, function = 0b0001000, type = 0b0010000, array_of_number = number | array, array_of_pointer = pointer | array, array_of_instance = instance | array, array_of_function = function | array, array_of_type = type | array, reference_of_number = number | reference, reference_of_pointer = pointer | reference, reference_of_instance = instance | reference, reference_of_function = function | reference, reference_of_type = type | reference, reference_of_array_of_number = array_of_number | reference, reference_of_array_of_pointer = array_of_pointer | reference, reference_of_array_of_instance = array_of_instance | reference, reference_of_array_of_function = array_of_function | reference, reference_of_array_of_type = array_of_type | reference, }; using element_element = std::variant<std::variant<long long, double>, // number std::uintptr_t, // pointer // TODO: instance function_ptr, // function element_type // type >; using element_base = std::variant<element_element, std::vector<element_element>>; using element = std::variant<element_base, element_base*>; using element_ptr = std::shared_ptr<element>; element_type get_element_type(const element_element& element) noexcept; element_type get_element_type(const element_base& element) noexcept; element_type get_element_type(const element& element) noexcept; const element_base& dereference(const element& element) noexcept; element_base& dereference(element& element) noexcept; } #endif
30.190476
82
0.759201
[ "vector" ]
d1d1b42c6f5cf6e385c0f65fa637bdfc727d1754
6,193
cpp
C++
src/main.cpp
danielsoutar/CarND-PID-Control-Project
2bbe9a42a17901d7a46f01710d8e2752e70aae71
[ "MIT" ]
null
null
null
src/main.cpp
danielsoutar/CarND-PID-Control-Project
2bbe9a42a17901d7a46f01710d8e2752e70aae71
[ "MIT" ]
null
null
null
src/main.cpp
danielsoutar/CarND-PID-Control-Project
2bbe9a42a17901d7a46f01710d8e2752e70aae71
[ "MIT" ]
null
null
null
#include <math.h> #include <uWS/uWS.h> #include <chrono> #include <iostream> #include <fstream> #include <thread> #include "json.hpp" #include "PID.h" // for convenience using json = nlohmann::json; // For converting back and forth between radians and degrees. constexpr double pi() { return M_PI; } double deg2rad(double x) { return x * pi() / 180; } double rad2deg(double x) { return x * 180 / pi(); } // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. std::string hasData(std::string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_last_of("]"); if (found_null != std::string::npos) { return ""; } else if (b1 != std::string::npos && b2 != std::string::npos) { return s.substr(b1, b2 - b1 + 1); } return ""; } int main() { uWS::Hub h; // Wanted to explore the parameter space. // Would have systematically searched it by iterating over different // combinations of Kp and Kd. Assume Ki fixed, at 0.001. // Starting from 0, 0, iterate over the combinations // in multiples of 0.1 per parameter. // int time_step = 0; // double Kp_i = 0; // double Kd_i = 0; // const double Kp_step = 0.1; // const double Kd_step = 0.1; // const int MAX_KP = 10; // const int MAX_KD = 10; // const double MAX_CTE_THRESHOLD = 3.0; // PID pid_only_proportional(0.3, 0.0, 0.0); // PID pid_only_integral(0.0, 0.0, 0.001); // PID pid_only_derivative(0.0, 5.0, 0.0); PID pid_steer(0.3, 5, 0.001); // pid_steer.RecordTotalError(); PID pid_throttle(0.45, 0.5, 0.0); bool is_initialised = false; h.onMessage([&pid_steer, &pid_throttle, &is_initialised](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(std::string(data).substr(0, length)); if (s != "") { auto j = json::parse(s); std::string event = j[0].get<std::string>(); if (event == "telemetry") { // j[1] is the data JSON object double cte = std::stod(j[1]["cte"].get<std::string>()); double steer_value; double throttle; double reference_velocity = 0.6; if(!is_initialised) { pid_steer.Init(cte); steer_value = pid_steer.Respond(cte); pid_throttle.Init(steer_value); throttle = pid_throttle.RespondThrottle(fabs(steer_value), reference_velocity); is_initialised = true; } else { steer_value = pid_steer.Respond(cte); throttle = pid_throttle.RespondThrottle(fabs(steer_value), reference_velocity); } // The below doesn't work - the simulator's latency between sending a reset message and said message // actually feeding back appears to be the reason. I would have appended the results to a log file. // I was actually just wanting to explore the parameter space. Alas, this simulator makes that // needlessly difficult. Hopefully this project is changed so that it is easier to test out in Python // before running the FINAL controller on the simulator. That would make much more sense. // time_step += 1; // if((fabs(cte) > MAX_CTE_THRESHOLD || time_step >= 24000)) { // // std::cout << ((fabs(cte) > MAX_CTE_THRESHOLD) == true) << ", " << ((time_step % 24000 == 0) == true) << std::endl; // if(fabs(cte) > MAX_CTE_THRESHOLD) { // my_logfile << pid_steer.K_coeffs[0] << ", " << pid_steer.K_coeffs[1] << ", " << 1e19 << std::endl; // } // else // my_logfile << pid_steer.K_coeffs[0] << ", " << pid_steer.K_coeffs[1] << ", " << pid_steer.GetTotalError() << std::endl; // // Need to set this so that total error is reset // is_initialised = false; // pid_steer.SetParams(0, (Kp_i++ * Kp_step)); // if(((Kp_i) * Kp_step) == MAX_KP) { // pid_steer.SetParams(0, 0.0); // pid_steer.SetParams(1, (Kd_i++ * Kd_step)); // } // Restart(ws); // } // 0.6 is about as fast as it can go before things get too... wonky. 0.5 is safer and calmer though. // DEBUG // my_logfile << cte << ", " << steer_value << std::endl; // std::cout << "CTE (Throttle): " << cte << " Throttle Value: " << throttle << std::endl; json msgJson; msgJson["steering_angle"] = steer_value; msgJson["throttle"] = throttle; auto msg = "42[\"steer\"," + msgJson.dump() + "]"; // std::cout << msg << std::endl; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); // We don't need this since we're not using HTTP but if it's removed the program // doesn't compile :-( h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) { const std::string s = "<h1>Hello world!</h1>"; if (req.getUrl().valueLength == 1) { res->end(s.data(), s.length()); } else { // i guess this should be done more gracefully? res->end(nullptr, 0); } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
36.005814
139
0.578233
[ "object" ]
d1e2223dd9f77401f44a9d2e35a2e2ee9121a796
8,349
cpp
C++
ablateLibrary/monitors/curveMonitor.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
3
2021-01-19T21:29:10.000Z
2021-08-20T19:54:49.000Z
ablateLibrary/monitors/curveMonitor.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
124
2021-01-14T15:30:48.000Z
2022-03-28T14:44:31.000Z
ablateLibrary/monitors/curveMonitor.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
17
2021-02-10T22:34:57.000Z
2022-03-21T18:46:06.000Z
#include "curveMonitor.hpp" #include <fstream> #include <iostream> #include <utilities/mpiError.hpp> #include <utilities/petscError.hpp> #include "environment/runEnvironment.hpp" ablate::monitors::CurveMonitor::CurveMonitor(int interval, std::string prefix, std::vector<double> start, std::vector<double> end, std::vector<std::string> outputFields, std::vector<std::string> outputAuxFields) : interval(interval), start(start), end(end), outputFields(outputFields), outputAuxFields(outputAuxFields), filePrefix(prefix) {} void ablate::monitors::CurveMonitor::Register(std::shared_ptr<solver::Solver> monitorableObject) { ablate::monitors::Monitor::Register(monitorableObject); // this probe will only work with fV flow and a single process flow = std::dynamic_pointer_cast<finiteVolume::FiniteVolume>(monitorableObject); if (!flow) { throw std::invalid_argument("The CurveMonitor monitor can only be used with ablate::finiteVolume::FiniteVolume"); } // check the size int size; MPI_Comm_size(flow->GetSubDomain().GetComm(), &size) >> checkMpiError; if (size != 1) { throw std::runtime_error("The IgnitionDelay monitor only works with a single mpi rank"); } // get the cell geom Vec cellGeomVec; DM dmCell; const PetscScalar* cellGeomArray; // get the min cell size PetscReal minCellRadius; DMPlexGetGeometryFVM(flow->GetSubDomain().GetDM(), NULL, &cellGeomVec, &minCellRadius) >> checkError; VecGetDM(cellGeomVec, &dmCell) >> checkError; VecGetArrayRead(cellGeomVec, &cellGeomArray) >> checkError; PetscMPIInt rank; MPI_Comm_rank(flow->GetSubDomain().GetComm(), &rank) >> checkMpiError; PetscInt dim; DMGetDimension(flow->GetSubDomain().GetDM(), &dim) >> checkError; // Now march over each sub segment int he line double ds = minCellRadius / 10.0; double s = 0.0; double L = 0.0; std::vector<double> lineVec; for (std::size_t d = 0; d < start.size(); d++) { L += PetscSqr(end[d] - start[d]); lineVec.push_back(end[d] - start[d]); } L = PetscSqrtReal(L); for (auto& c : lineVec) { c /= L; } // Create a location vector Vec locVec; VecCreateSeq(PETSC_COMM_SELF, dim, &locVec) >> checkError; VecSetBlockSize(locVec, dim) >> checkError; while (s < L) { // Compute the current location for (PetscInt d = 0; d < dim; d++) { VecSetValue(locVec, d, s * lineVec[d], INSERT_VALUES) >> checkError; } VecAssemblyBegin(locVec) >> checkError; VecAssemblyEnd(locVec) >> checkError; // find the point in the mesh PetscSF cellSF = NULL; DMLocatePoints(flow->GetSubDomain().GetDM(), locVec, DM_POINTLOCATION_NONE, &cellSF) >> checkError; const PetscSFNode* cells; PetscInt numberFound; PetscSFGetGraph(cellSF, NULL, &numberFound, NULL, &cells) >> checkError; if (cells[0].rank == rank) { // search over the history of indexes if (std::find(indexLocations.begin(), indexLocations.end(), cells[0].index) == indexLocations.end()) { // we have not counted this cell indexLocations.push_back(cells[0].index); // get the center location of this cell PetscFVCellGeom* cellGeom; DMPlexPointLocalRead(dmCell, cells[0].index, cellGeomArray, &cellGeom) >> checkError; // figure out where this cell is along the line double alongLine = 0.0; for (PetscInt d = 0; d < dim; d++) { alongLine += PetscSqr(cellGeom->centroid[d] - start[d]); } distanceAlongLine.push_back(PetscSqrtReal(alongLine)); } } PetscSFDestroy(&cellSF) >> checkError; s += ds; } VecDestroy(&locVec) >> checkError; VecRestoreArrayRead(cellGeomVec, &cellGeomArray) >> checkError; } static PetscErrorCode OutputCurveForField(std::ostream& stream, PetscInt fieldIndex, const ablate::domain::Field& fieldDescription, const std::vector<PetscInt>& indexLocations, const std::vector<PetscReal> distanceAlongLine, PetscErrorCode(plexPointRead)(DM, PetscInt, PetscInt, const PetscScalar*, void*), Vec u) { // Open the array const PetscScalar* uArray; PetscErrorCode ierr = VecGetArrayRead(u, &uArray); CHKERRQ(ierr); // Get the DM for the vec DM dm; ierr = VecGetDM(u, &dm); CHKERRQ(ierr); // Output each component for (PetscInt c = 0; c < fieldDescription.numberComponents; c++) { stream << "#" << fieldDescription.name << (fieldDescription.numberComponents > 1 ? "_" + (fieldDescription.components.empty() ? std::to_string(c) : fieldDescription.components[c]) : "") << std::endl; // Output each cell for (std::size_t i = 0; i < indexLocations.size(); i++) { stream << distanceAlongLine[i] << " "; // extract the location const PetscScalar* values; ierr = plexPointRead(dm, indexLocations[i], fieldIndex, uArray, &values); CHKERRQ(ierr); stream << values[c] << std::endl; } stream << std::endl; } ierr = VecRestoreArrayRead(u, &uArray); CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode ablate::monitors::CurveMonitor::OutputCurve(TS ts, PetscInt steps, PetscReal time, Vec u, void* mctx) { PetscFunctionBeginUser; PetscErrorCode ierr; DM dm; PetscDS ds; ierr = TSGetDM(ts, &dm); CHKERRQ(ierr); ierr = DMGetDS(dm, &ds); CHKERRQ(ierr); // Check for the number of DS, this should be relaxed PetscInt numberDS; ierr = DMGetNumDS(dm, &numberDS); CHKERRQ(ierr); if (numberDS > 1) { SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "This monitor only supports a single DS in a DM"); } auto monitor = (ablate::monitors::CurveMonitor*)mctx; auto flow = monitor->flow; if (steps == 0 || monitor->interval == 0 || (steps % monitor->interval == 0)) { // Open a new file std::filesystem::path outputFile = ablate::environment::RunEnvironment::Get().GetOutputDirectory() / (monitor->filePrefix + "." + std::to_string(monitor->outputIndex) + monitor->fileExtension); monitor->outputIndex++; std::ofstream curveFile; curveFile.open(outputFile); // March over each solution vector curveFile << "#title=" << flow->GetId() << std::endl; curveFile << "##time=" << time << std::endl << std::endl; // output each solution variable for (const auto& fieldName : monitor->outputFields) { auto fieldIndex = flow->GetSubDomain().GetField(fieldName).id; const auto& fieldDescription = flow->GetSubDomain().GetField(fieldName); ierr = OutputCurveForField(curveFile, fieldIndex, fieldDescription, monitor->indexLocations, monitor->distanceAlongLine, DMPlexPointGlobalFieldRead, u); CHKERRQ(ierr); } // output each aux variable for (const auto& fieldName : monitor->outputAuxFields) { auto fieldIndex = flow->GetSubDomain().GetField(fieldName).id; const auto& fieldDescription = flow->GetSubDomain().GetField(fieldName); ierr = OutputCurveForField(curveFile, fieldIndex, fieldDescription, monitor->indexLocations, monitor->distanceAlongLine, DMPlexPointLocalFieldRead, flow->GetSubDomain().GetAuxVector()); CHKERRQ(ierr); } curveFile.close(); } CHKERRQ(ierr); PetscFunctionReturn(0); } #include "parser/registrar.hpp" REGISTER(ablate::monitors::Monitor, ablate::monitors::CurveMonitor, "Outputs the results along a line as a curve file (beta)", ARG(int, "interval", "output interval"), ARG(std::string, "prefix", "the file prefix"), ARG(std::vector<double>, "start", "the line start location"), ARG(std::vector<double>, "end", "the line end location"), ARG(std::vector<std::string>, "outputFields", "a list of fields to write to the curve"), ARG(std::vector<std::string>, "outputAuxFields", "a list of aux fields to write to the curve "));
41.745
197
0.635645
[ "mesh", "vector" ]
d1ee15173847e2f1201b857f8efe2b2025d64e9e
1,015
cpp
C++
codes/moderncpp/stdmove/stdmove03/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
3
2022-01-25T07:33:43.000Z
2022-03-30T10:25:09.000Z
codes/moderncpp/stdmove/stdmove03/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
null
null
null
codes/moderncpp/stdmove/stdmove03/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
2
2022-01-17T13:39:12.000Z
2022-03-30T10:25:12.000Z
#include <iostream> #include <vector> int main( int argc, char **argv ) { { std::vector<int> v1(10); std::vector<int> v2(200); v1 = v2; // O(n) std::cout << "after copy:" << std::endl; std::cout << "v1 length " << v1.size() << std::endl; // 200 std::cout << "v2 length " << v2.size() << std::endl; // 200 } { std::vector<int> v1(10); std::vector<int> v2(200); v1 = std::move(v2); // O(1) std::cout << "after move:" << std::endl; std::cout << "v1 length " << v1.size() << std::endl; // 200 std::cout << "v2 length " << v2.size() << std::endl; // 0 } { std::vector<int> v1(10); std::vector<int> v2(200); std::swap(v1, v2); // O(1) std::cout << "after swap:" << std::endl; std::cout << "v1 length " << v1.size() << std::endl; // 200 std::cout << "v2 length " << v2.size() << std::endl; // 10 } return 0; }
26.710526
68
0.433498
[ "vector" ]
d1ef7b7b3bdfe54e9bf212340a23960e93f52626
3,807
cpp
C++
src/Nuz/Renderer/OpenGL/GLSLProgram.cpp
SmallLuma/NuzGameEngine
01465469bf2f5c7c2646978576280c4c464cd02a
[ "MIT" ]
null
null
null
src/Nuz/Renderer/OpenGL/GLSLProgram.cpp
SmallLuma/NuzGameEngine
01465469bf2f5c7c2646978576280c4c464cd02a
[ "MIT" ]
null
null
null
src/Nuz/Renderer/OpenGL/GLSLProgram.cpp
SmallLuma/NuzGameEngine
01465469bf2f5c7c2646978576280c4c464cd02a
[ "MIT" ]
null
null
null
#include "GLSLProgram.h" #include "../../Engine.h" using namespace std; using namespace Nuz_; using namespace Nuz_::Renderer; GLSLProgram::GLSLShader GLSLProgram::m_normalVertShader; GLuint GLSLProgram::m_normalShaderProgram = 0; GLSLProgram::GLSLProgram() { } GLSLProgram::~GLSLProgram() { Clear(); } void Nuz_::Renderer::GLSLProgram::CompileNormalShaders() { m_normalShaderProgram = glCreateProgram(); const char* vert = "#version 110\n" "attribute vec4 gl_MultiTexCoord0;" "uniform mat4 gl_TextureMatrix[1];" "varying vec4 Nuz_texCoord;" "attribute vec4 gl_Color;" "varying vec4 Nuz_Color;" "void main(){" " Nuz_texCoord = gl_MultiTexCoord0 * gl_TextureMatrix[0];" " Nuz_Color = gl_Color;" " gl_Position = ftransform();" "}"; const char* vert2 = "#version 110\n" "void main(){" " gl_Position = ftransform();" "}"; const char* frag = "#version 110\n" "varying vec4 Nuz_Color;" "varying vec4 Nuz_texCoord;" "uniform sampler2D Nuz_texture;" "void main(){\n" " gl_FragColor = texture2D(Nuz_texture,Nuz_texCoord.st);" " gl_FragColor = gl_FragColor * Nuz_Color;" " gl_FragColor[3] = Nuz_Color[3];" "}"; GLSLShader normalFragShader; normalFragShader.CompileShader(frag, GL_FRAGMENT_SHADER); m_normalVertShader.CompileShader(vert, GL_VERTEX_SHADER); glAttachShader(m_normalShaderProgram, normalFragShader); glAttachShader(m_normalShaderProgram, m_normalVertShader); glLinkProgram(m_normalShaderProgram); m_normalVertShader.CompileShader(vert2, GL_VERTEX_SHADER); glUseProgram(m_normalShaderProgram); auto pTex = glGetUniformLocation(m_normalShaderProgram, "Nuz_texture"); glProgramUniform1iEXT(m_normalShaderProgram, pTex, 0); } void Nuz_::Renderer::GLSLProgram::DestroyNormalShaders() { if(m_normalShaderProgram) glDeleteProgram(m_normalShaderProgram); } void Nuz_::Renderer::GLSLProgram::LoadShader(const Nuz::IShader::CreateConfig & c) { Clear(); m_program = glCreateProgram(); if (m_program == 0) throw Nuz::IEngine::RendererError("Can not create program object."); GLSLShader* vert = nullptr,*frag = nullptr; if (!c.vertexShader.empty()) { auto buf = Nuz::IEngine::GetGameDevice().GetFileSystem().LoadFile(c.vertexShader); buf->push_back('\0'); vert = new GLSLShader; vert->CompileShader((char*)&(*buf)[0], GL_VERTEX_SHADER); } else vert = &m_normalVertShader; if (!c.fragmentShader.empty()) { auto buf = Nuz::IEngine::GetGameDevice().GetFileSystem().LoadFile(c.fragmentShader); buf->push_back('\0'); frag = new GLSLShader; frag->CompileShader((char*)&(*buf)[0], GL_FRAGMENT_SHADER); } else throw Nuz::IEngine::RendererError("You must use a fragment shader."); glAttachShader(m_program, *vert); glAttachShader(m_program, *frag); glLinkProgram(m_program); delete frag; } void Nuz_::Renderer::GLSLProgram::Clear() { if(m_program) glDeleteProgram(m_program); m_program = 0; } void Nuz_::Renderer::GLSLProgram::GLSLShader::CompileShader(const char * source, GLenum type) { Clear(); m_type = type; m_shader = glCreateShader(type); if (m_shader == 0) throw Nuz::IEngine::RendererError("Can not create shader."); glShaderSource(m_shader, 1, &source, 0); glCompileShader(m_shader); GLint compileResult; glGetShaderiv(m_shader, GL_COMPILE_STATUS, &compileResult); if (GL_FALSE == compileResult) { GLint logLen; glGetShaderiv(m_shader, GL_INFO_LOG_LENGTH, &logLen); if (logLen > 0) { char *log = (char *)malloc(logLen); GLsizei written; glGetShaderInfoLog(m_shader, logLen, &written, log); string s(log); free(log); throw Nuz::IShader::ShaderCompileError("Shader Compile Failed:\n" + s); } } } void Nuz_::Renderer::GLSLProgram::GLSLShader::Clear() { if (m_shader) glDeleteShader(m_shader); } Nuz_::Renderer::GLSLProgram::GLSLShader::~GLSLShader() { Clear(); }
26.622378
93
0.731284
[ "object" ]
d1f1625279053b926b187cf4132d09100e497155
7,773
hpp
C++
lib/nmtools/Common.hpp
UCL/pet-rd-tools
537202f38ef120296dcab90b025aea28a30447fd
[ "Apache-2.0" ]
7
2019-03-25T15:34:09.000Z
2021-09-29T19:18:48.000Z
lib/nmtools/Common.hpp
UCL/pet-rd-tools
537202f38ef120296dcab90b025aea28a30447fd
[ "Apache-2.0" ]
23
2019-02-01T15:58:19.000Z
2021-11-15T15:10:01.000Z
lib/nmtools/Common.hpp
UCL/pet-rd-tools
537202f38ef120296dcab90b025aea28a30447fd
[ "Apache-2.0" ]
4
2019-02-01T15:06:19.000Z
2021-06-07T07:46:36.000Z
/* Common.hpp Author: Benjamin A. Thomas Author: Kris Thielemans Copyright 2017, 2020 Institute of Nuclear Medicine, University College London. 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. Common utils. DICOM reading. */ #ifndef COMMON_HPP #define COMMON_HPP #include <itkImage.h> #include <gdcmStringFilter.h> #include <exception> namespace nmtools { #ifdef __APPLE__ #define fseeko64 fseeko #define ftello64 ftello #endif #ifdef WIN32 #define fseeko64 _fseeki64 #define ftello64 _ftelli64 #endif enum class ContentType { EHEADER, ERAWDATA }; enum class FileStatusCode { EGOOD, EBAD, EIOERROR }; bool GetTagInfo(const gdcm::File &file, const gdcm::Tag tag, std::string &dst){ //Extracts information for a given DICOM tag from a gdcm file. //Tag contents are returned as a string in dst variable. //TODO: Do actual check for valid content. //Tries to read the element associated with the tag. If the read fails, the //DataElement should have a ByteValue of NULL. std::stringstream inStream; const gdcm::DataSet &ds = file.GetDataSet(); gdcm::DataElement element = ds.GetDataElement(tag); dst = ""; try { gdcm::StringFilter sf; sf.SetFile(file); if (element.GetByteValue() != NULL) { dst = sf.ToString(tag); } //else return false; } catch (std::bad_alloc){ LOG(ERROR) << "GetTagInfo : Cannot read!"; return false; } if (dst.size() == 0){ LOG(WARNING) << "GetTagInfo : Empty field - " << tag; LOG(WARNING) << "Reverting to using element.GetValue()"; inStream << std::fixed << element.GetValue(); std::string tmpDst = inStream.str(); std::string smatch = "Loaded:"; if (tmpDst.compare(0, smatch.length(), smatch ) != 0){ LOG(INFO) << "Value found via element.GetValue()"; dst = tmpDst; } } return true; } class IDicomExtractor { //Base class for extracting headers etc from a (probably DICOM) file public: IDicomExtractor(); explicit IDicomExtractor(boost::filesystem::path src); virtual bool SetInputFile ( boost::filesystem::path src ); //FileType GetFileType( boost::filesystem::path src ); virtual bool IsValid()=0; virtual bool ExtractHeader( const boost::filesystem::path dst ) = 0; virtual bool ExtractData( const boost::filesystem::path dst ) = 0; virtual boost::filesystem::path GetStdFileName( boost::filesystem::path srcFile, ContentType ctype) = 0; virtual bool ModifyHeader( const boost::filesystem::path src, const boost::filesystem::path dataFile) = 0; virtual ~IDicomExtractor(){}; protected: std::unique_ptr<gdcm::Reader> _dicomReader = nullptr; boost::filesystem::path _srcPath; }; IDicomExtractor::IDicomExtractor() { std::unique_ptr<gdcm::Reader> dcm(new gdcm::Reader); _dicomReader = std::move(dcm); } //Constructor with path. IDicomExtractor::IDicomExtractor(boost::filesystem::path src){ std::unique_ptr<gdcm::Reader> dcm(new gdcm::Reader); _dicomReader = std::move(dcm); if (! this->SetInputFile(src) ) { LOG(ERROR) << "Unable to read data in: " << src; throw std::invalid_argument("Unable to read \"" + src.string() + "\" as DICOM"); } } //On set input, try and read. bool IDicomExtractor::SetInputFile(boost::filesystem::path src){ _dicomReader->SetFileName(src.string().c_str()); if (!_dicomReader->Read()) { LOG(ERROR) << "Unable to read as DICOM file"; return false; } _srcPath = src; return true; } class IRawDataFactory { //Factory that returns suitable child for given data. public: virtual std::unique_ptr<IDicomExtractor> Create( boost::filesystem::path inFile ) { return std::unique_ptr<IDicomExtractor>(Create_ptr( inFile )); } protected: std::unique_ptr<gdcm::Reader> dicomReader; std::string manufacturerName; std::string modelName; bool Open(boost::filesystem::path inFile); virtual IDicomExtractor* Create_ptr( boost::filesystem::path inFile ) = 0; }; bool IRawDataFactory::Open(boost::filesystem::path inFile) { dicomReader = std::unique_ptr<gdcm::Reader>(new gdcm::Reader); dicomReader->SetFileName(inFile.string().c_str()); if (!dicomReader->Read()) { LOG(ERROR) << "Unable to read '" << inFile.string() << "' as DICOM file"; return false; } //Get dataset via GDCM const gdcm::File &file = dicomReader->GetFile(); //const gdcm::DataSet &ds = dicomReader->GetFile().GetDataSet(); //Read manufacturer name. const gdcm::Tag manufacturer(0x008, 0x0070); if (!GetTagInfo(file,manufacturer,manufacturerName)){ LOG(ERROR) << "Unable to manufacturer name"; return false; } LOG(INFO) << "Manufacturer: " << manufacturerName; //Read model of scanner const gdcm::Tag model(0x008, 0x1090); if (!GetTagInfo(file,model,modelName)){ LOG(ERROR) << "Unable to scanner model name"; return false; } LOG(INFO) << "Model name: " << modelName; return true; } itk::SpatialOrientation::CoordinateTerms GetOrientationCode(char &c){ c = toupper(c); const std::string validVals = "RLPAIS"; if (validVals.find(c) == std::string::npos){ LOG(ERROR) << c << " is not a valid orientation code value!"; return itk::SpatialOrientation::ITK_COORDINATE_UNKNOWN; } if (c == 'R') return itk::SpatialOrientation::ITK_COORDINATE_Right; if (c == 'L') return itk::SpatialOrientation::ITK_COORDINATE_Left; if (c == 'P') return itk::SpatialOrientation::ITK_COORDINATE_Posterior; if (c == 'A') return itk::SpatialOrientation::ITK_COORDINATE_Anterior; if (c == 'I') return itk::SpatialOrientation::ITK_COORDINATE_Inferior; if (c == 'S') return itk::SpatialOrientation::ITK_COORDINATE_Superior; return itk::SpatialOrientation::ITK_COORDINATE_UNKNOWN; } bool SetDesiredCoordinateOrientation(const std::string &target, itk::SpatialOrientation::ValidCoordinateOrientationFlags &finalOrientation){ std::vector<int> coordVals(3); std::string orient = target; //Check we have three letter code. if (orient.size() != 3){ LOG(ERROR) << "Expected three letter orientation code. Read: " << orient; return false; } //Check they are all valid identifiers for (int i = 0; i < 3; i++) { coordVals[i] = GetOrientationCode(orient[i]); if (coordVals[i] == 0){ LOG(ERROR) << "Unknown coordinate: " << orient[i]; return false; } } //See itkSpatialOrientation.h itk::SpatialOrientation::ValidCoordinateOrientationFlags o = (itk::SpatialOrientation::ValidCoordinateOrientationFlags)( ( coordVals[0] << itk::SpatialOrientation::ITK_COORDINATE_PrimaryMinor ) + ( coordVals[1] << itk::SpatialOrientation::ITK_COORDINATE_SecondaryMinor ) + ( coordVals[2] << itk::SpatialOrientation::ITK_COORDINATE_TertiaryMinor )); //Check we don't have an duplicates. std::sort(coordVals.begin(), coordVals.end()); auto last = std::unique(coordVals.begin(), coordVals.end()); coordVals.erase(last, coordVals.end()); if (coordVals.size() != 3){ LOG(ERROR) << "Duplicate coordinate codes found: " << orient; return false; } LOG(INFO) << "Using orientation code: " << orient; finalOrientation = o; return true; } } #endif
27.178322
113
0.683263
[ "vector", "model" ]
d1fafa094c46c8b95ba2327ece51b563d9c01616
1,792
cxx
C++
src/mordavokne/glue/friend_accessors.cxx
igagis/mordavokne
48baed90aff42c2ad82fb8dde6268563a21c7fde
[ "MIT" ]
1
2020-02-16T18:22:41.000Z
2020-02-16T18:22:41.000Z
src/mordavokne/glue/friend_accessors.cxx
igagis/mordavokne
48baed90aff42c2ad82fb8dde6268563a21c7fde
[ "MIT" ]
12
2016-08-04T11:08:52.000Z
2019-08-29T22:07:50.000Z
src/mordavokne/glue/friend_accessors.cxx
igagis/mordavokne
48baed90aff42c2ad82fb8dde6268563a21c7fde
[ "MIT" ]
1
2019-11-30T01:36:04.000Z
2019-11-30T01:36:04.000Z
/* mordavokne - morda GUI adaptation layer Copyright (C) 2016-2021 Ivan Gagis <igagis@gmail.com> 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/>. */ /* ================ LICENSE END ================ */ namespace mordavokne{ const decltype(application::window_pimpl)& get_window_pimpl(application& app){ return app.window_pimpl; } void render(application& app){ app.render(); } void update_window_rect(application& app, const morda::rectangle& rect){ app.update_window_rect(rect); } void handle_mouse_move(application& app, const r4::vector2<float>& pos, unsigned id){ app.handle_mouse_move(pos, id); } void handle_mouse_button(application& app, bool isDown, const r4::vector2<float>& pos, morda::mouse_button button, unsigned id){ app.handle_mouse_button(isDown, pos, button, id); } void handleMouseHover(application& app, bool isHovered, unsigned pointerID){ app.handleMouseHover(isHovered, pointerID); } void handle_character_input(application& app, const morda::gui::input_string_provider& string_provider, morda::key key_code){ app.handle_character_input(string_provider, key_code); } void handle_key_event(application& app, bool is_down, morda::key key_code){ app.handle_key_event(is_down, key_code); } }
31.438596
128
0.767299
[ "render" ]
d1fc1df88514e5a3591d108d44753f4884e9f4b3
12,994
cpp
C++
projects/final_project/helicopter.cpp
Crystallen1/CGProject
739b8ade90d9909bb225fbad040daea09aa54d55
[ "MIT" ]
null
null
null
projects/final_project/helicopter.cpp
Crystallen1/CGProject
739b8ade90d9909bb225fbad040daea09aa54d55
[ "MIT" ]
null
null
null
projects/final_project/helicopter.cpp
Crystallen1/CGProject
739b8ade90d9909bb225fbad040daea09aa54d55
[ "MIT" ]
null
null
null
#include "helicopter.h" const std::string modelPath = "../../../media/Seahawk.obj"; const std::string Seahawk = { "../../../media/Seahawk2.jpg" }; Helicopter::Helicopter() { // init model _model.reset(new Model(modelPath)); _model->scale = glm::vec3(0.02f, 0.02f, 0.02f); glm::vec3 rotationAxis = glm::vec3(0.0f, 1.0f, 0.0f); float rotationAngle = 3.14f; _rotation = glm::axisAngleMatrix(rotationAxis, rotationAngle); // init texture this->_texture.reset(new Texture2D(Seahawk)); // init shader initShader(); _Box = new AABBBox(); } Helicopter::~Helicopter() { } void Helicopter::move(glm::vec3 offset) { _position += offset; } void Helicopter::draw(Shader* _heliShader,glm::mat4 projection, glm::mat4 view) { if (_viewPattern == ViewPattern::FPS) return; // translation glm::mat4 translation = glm::mat4(1.0f); translation = glm::translate(translation, _position); // rotation glm::mat4 rotation = glm::mat4(1.0f); rotation = _rotation * _rotation2 * rotation; // scale glm::mat4 scale = glm::mat4(1.0f); scale = glm::scale(scale, _scale); glm::mat4 model = translation * rotation * scale; _heliShader->use(); _heliShader->setMat4("projection", projection); _heliShader->setMat4("view", view); _heliShader->setMat4("model", model); // glActiveTexture(GL_TEXTURE0); // _texture->bind(); glActiveTexture(GL_TEXTURE0); _texture->bind(); glActiveTexture(GL_TEXTURE1); _texture->bind(); _model->draw(); if (_firstDraw) { _Box->findMinAndMax(_model->getVertex(),model);//* projection* view); _firstDraw = false; } } void Helicopter::initShader() { const char* vertCode = "#version 330 core\n" "layout(location = 0) in vec3 aPosition;\n" "layout(location = 1) in vec3 aNormal;\n" "layout(location = 2) in vec2 aTexCoord;\n" "out vec2 TexCoord;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main() {\n" " TexCoord = aTexCoord;\n" " gl_Position = projection * view * model * vec4(aPosition, 1.0f);\n" "}\n"; const char* fragCode = "#version 330 core\n" "in vec2 TexCoord;\n" "out vec4 color;\n" "uniform sampler2D mapKd;\n" "void main() {\n" " color = texture(mapKd, TexCoord);\n" "}\n"; _shader.reset(new Shader(vertCode, fragCode)); } void Helicopter::bindPosition(glm::vec3& cameraPosition) { glm::vec3 front = glm::normalize(-cameraPosition); if (_viewPattern == ViewPattern::TPS) { _position = cameraPosition + glm::vec3(0.f, -5.f, -10.f); } else { _position = cameraPosition + glm::vec3(0.f, -0.5f, 0.f); } } void Helicopter::rotationX(glm::vec3 axis, float angle) { _rotation *= glm::axisAngleMatrix(axis, angle); } void Helicopter::tiltLeft() { glm::vec3 axis = glm::vec3(0.f, 0.f, -1.f); if (false == _left) { _rotation2 = glm::axisAngleMatrix(axis, 3.14f / 6.f); _left = true; } } void Helicopter::tiltRight() { glm::vec3 axis = glm::vec3(0.f, 0.f, 1.f); if (false == _right) { _rotation2 = glm::axisAngleMatrix(axis, 3.14f / 6.f); _right = true; } } void Helicopter::tiltFront() { glm::vec3 axis = glm::vec3(1.f, 0.f, 0.f); if (false == _front) { _rotation2 = glm::axisAngleMatrix(axis, 3.14f / 6.f); _front = true; } } void Helicopter::tiltBack() { glm::vec3 axis = glm::vec3(-1.f, 0.f, 0.f); if (false == _back) { _rotation2 = glm::axisAngleMatrix(axis, 3.14f / 6.f); _back = true; } } void Helicopter::resetTilt() { _rotation2 = glm::mat4(1.0f); _left = false; _right = false; _front = false; _back = false; } //Normal is the plane normal direction, position is the plane position, //planeposition is the aircraft position, and direction is the flight direction of the aircraft int Helicopter::collisionDetection(glm::vec3& Normal, glm::vec3& position, glm::vec3& PlanePosition, glm::vec3& direction) { double dotProduct = dot(Normal,direction);//Calculate the dot of plane and plane //If the dot is multiplied by 0, it means that it is parallel and will never collide if (dotProduct<0.0001 && dotProduct>-0.0001) { return 0; } //Calculate the distance from the aircraft point to the plane double l2 = (dot(Normal, position - PlanePosition)) / dotProduct; //If L2 is less than 0, the plane is behind the aircraft if (l2 < -0.0001) { return 0; } //If L2 is greater than 0, it means it hasn't hit else if (l2 > 0.001) { return 0; } //else means hit else { return 1; } } void Helicopter::draw(glm::mat4 projection, glm::mat4 view, glm::vec3 lightPosition, glm::vec3 lightDirection, glm::vec3 viewPos) { if (_viewPattern == ViewPattern::FPS) return; this->initShader2(); // translation glm::mat4 translation = glm::mat4(1.0f); translation = glm::translate(translation, _position); // rotation glm::mat4 rotation = glm::mat4(1.0f); rotation = _rotation * _rotation2 * rotation; // scale glm::mat4 scale = glm::mat4(1.0f); scale = glm::scale(scale, _scale); glm::mat4 model = translation * rotation * scale; _shader->use(); _shader->setMat4("projection", projection); _shader->setMat4("view", view); _shader->setMat4("model", model); _shader->setVec3("viewPos", viewPos); _shader->setFloat("spotLight.cutOff", glm::cos(glm::radians(12.5f))); _shader->setFloat("spotLight.outerCutOff", glm::cos(glm::radians(17.5f))); // light properties _shader->setVec3("spotLight.ambient", glm::vec3(0.1f, 0.1f, 0.1f)); _shader->setVec3("SpotLight.diffuse", glm::vec3(0.8f, 0.8f, 0.8f)); _shader->setVec3("spotLight.specular", glm::vec3(1.0f, 1.0f, 1.0f)); _shader->setFloat("spotLight.constant", 1.0f); _shader->setFloat("spotLight.linear", 0.09f); _shader->setFloat("spotLight.quadratic", 0.032f); _shader->setVec3("spotLight.position", lightPosition); _shader->setVec3("spotLight.direction", lightDirection); // material properties _shader->setFloat("material.shininess", 32.0f); // directional light _shader->setVec3("dirLight.direction",glm::vec3( -0.2f, -1.0f, -0.3f)); _shader->setVec3("dirLight.ambient", glm::vec3(0.05f, 0.05f, 0.05f)); _shader->setVec3("dirLight.diffuse", glm::vec3(0.4f, 0.4f, 0.4f)); _shader->setVec3("dirLight.specular",glm::vec3( 0.5f, 0.5f, 0.5f)); glActiveTexture(GL_TEXTURE0); _texture->bind(); _model->draw(); } void Helicopter::initShader2() { const char* vertCode = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aNormal;\n" "layout (location = 2) in vec2 aTexCoords;\n" "\n" "out vec3 FragPos;\n" "out vec3 Normal;\n" "out vec2 TexCoords;\n" "\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "\n" "void main()\n" "{\n" " FragPos = vec3(model * vec4(aPos, 1.0));\n" " Normal = mat3(transpose(inverse(model))) * aNormal;\n" " TexCoords = aTexCoords;\n" "\n" " gl_Position = projection * view * vec4(FragPos, 1.0);\n" "}"; const char* fragCode = "#version 330 core\n" "out vec4 FragColor;\n" "\n" "struct Material {\n" " sampler2D diffuse;\n" " sampler2D specular;\n" " float shininess;\n" "};\n" "\n" "struct DirLight {\n" " vec3 direction;\n" "\n" " vec3 ambient;\n" " vec3 diffuse;\n" " vec3 specular;\n" "};\n" "struct SpotLight {\n" " vec3 position;\n" " vec3 direction;\n" " float cutOff;\n" " float outerCutOff;\n" "\n" " float constant;\n" " float linear;\n" " float quadratic;\n" "\n" " vec3 ambient;\n" " vec3 diffuse;\n" " vec3 specular;\n" "};\n" "in vec3 FragPos;\n" "in vec3 Normal;\n" "in vec2 TexCoords;\n" "\n" "uniform vec3 viewPos;\n" "uniform DirLight dirLight;\n" "// uniform PointLight pointLights[NR_POINT_LIGHTS];\n" "uniform SpotLight spotLight;\n" "uniform Material material;\n" "\n" "// function prototypes\n" "vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir);\n" "vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir);\n" "vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir);\n" "\n" "void main()\n" "{\n" " // properties\n" " vec3 norm = normalize(Normal);\n" " vec3 viewDir = normalize(viewPos - FragPos);\n" "\n" " // phase 1: directional lighting\n" " vec3 result = CalcDirLight(dirLight, norm, viewDir);\n" "\n" " // phase 2: point lights\n" "// for(int i = 0; i < NR_POINT_LIGHTS; i++)\n" "// result += CalcPointLight(pointLights[i], norm, FragPos, viewDir);\n" "\n" " // phase 3: spot light\n" " result += CalcSpotLight(spotLight, norm, FragPos, viewDir);\n" "\n" " FragColor = vec4(result, 1.0);\n" "}\n" "\n" "// calculates the color when using a directional light.\n" "vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)\n" "{\n" " vec3 lightDir = normalize(-light.direction);\n" " // diffuse shading\n" " float diff = max(dot(normal, lightDir), 0.0);\n" " // specular shading\n" " vec3 reflectDir = reflect(-lightDir, normal);\n" " float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);\n" " // combine results\n" " vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));\n" " vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));\n" " vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));\n" " return (ambient + diffuse + specular);\n" "}\n" "\n" "// calculates the color when using a spot light.\n" "vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir)\n" "{\n" " vec3 lightDir = normalize(light.position - fragPos);\n" " // diffuse shading\n" " float diff = max(dot(normal, lightDir), 0.0);\n" " // specular shading\n" " vec3 reflectDir = reflect(-lightDir, normal);\n" " float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);\n" " // attenuation\n" " float distance = length(light.position - fragPos);\n" " float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));\n" " // spotlight intensity\n" " float theta = dot(lightDir, normalize(-light.direction));\n" " float epsilon = light.cutOff - light.outerCutOff;\n" " float intensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);\n" " // combine results\n" " vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));\n" " vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));\n" " vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));\n" " ambient *= attenuation * intensity;\n" " diffuse *= attenuation * intensity;\n" " specular *= attenuation * intensity;\n" " return (ambient + diffuse + specular);\n" "}"; _shader.reset(new Shader(vertCode, fragCode)); } void Helicopter::rotate2Front(float angle) { glm::vec3 rotationAxis = glm::vec3(0.0f, 1.0f, 0.0f); _rotation *= glm::axisAngleMatrix(rotationAxis, angle); }
34.743316
131
0.555795
[ "model" ]
d1fcf1c35b36b35fbdb66d2a933289fc24a5ca16
29,599
cpp
C++
lib/XRay/Trace.cpp
vangthao95/llvm
7161a90f679d8d52ab57a3166361a7ebd1ba5459
[ "Apache-2.0" ]
115
2018-02-01T18:56:44.000Z
2022-03-21T13:23:00.000Z
FRProtector/lib/XRay/Trace.cpp
whucs303/randomizationlib
07a1f495e1cf878ad9dd4c79b7ff1c6b48cff876
[ "MIT" ]
27
2018-09-17T17:49:49.000Z
2021-11-03T04:31:51.000Z
FRProtector/lib/XRay/Trace.cpp
whucs303/randomizationlib
07a1f495e1cf878ad9dd4c79b7ff1c6b48cff876
[ "MIT" ]
55
2018-02-01T07:11:49.000Z
2022-03-04T01:20:23.000Z
//===- Trace.cpp - XRay Trace Loading implementation. ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // XRay log reader implementation. // //===----------------------------------------------------------------------===// #include "llvm/XRay/Trace.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/DataExtractor.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/XRay/YAMLXRayRecord.h" using namespace llvm; using namespace llvm::xray; using llvm::yaml::Input; namespace { using XRayRecordStorage = std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type; // Populates the FileHeader reference by reading the first 32 bytes of the file. Error readBinaryFormatHeader(StringRef Data, XRayFileHeader &FileHeader) { // FIXME: Maybe deduce whether the data is little or big-endian using some // magic bytes in the beginning of the file? // First 32 bytes of the file will always be the header. We assume a certain // format here: // // (2) uint16 : version // (2) uint16 : type // (4) uint32 : bitfield // (8) uint64 : cycle frequency // (16) - : padding DataExtractor HeaderExtractor(Data, true, 8); uint32_t OffsetPtr = 0; FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr); FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr); uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr); FileHeader.ConstantTSC = Bitfield & 1uL; FileHeader.NonstopTSC = Bitfield & 1uL << 1; FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr); std::memcpy(&FileHeader.FreeFormData, Data.bytes_begin() + OffsetPtr, 16); if (FileHeader.Version != 1 && FileHeader.Version != 2) return make_error<StringError>( Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version), std::make_error_code(std::errc::invalid_argument)); return Error::success(); } Error loadNaiveFormatLog(StringRef Data, XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) { if (Data.size() < 32) return make_error<StringError>( "Not enough bytes for an XRay log.", std::make_error_code(std::errc::invalid_argument)); if (Data.size() - 32 == 0 || Data.size() % 32 != 0) return make_error<StringError>( "Invalid-sized XRay data.", std::make_error_code(std::errc::invalid_argument)); if (auto E = readBinaryFormatHeader(Data, FileHeader)) return E; // Each record after the header will be 32 bytes, in the following format: // // (2) uint16 : record type // (1) uint8 : cpu id // (1) uint8 : type // (4) sint32 : function id // (8) uint64 : tsc // (4) uint32 : thread id // (12) - : padding for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) { DataExtractor RecordExtractor(S, true, 8); uint32_t OffsetPtr = 0; switch (auto RecordType = RecordExtractor.getU16(&OffsetPtr)) { case 0: { // Normal records. Records.emplace_back(); auto &Record = Records.back(); Record.RecordType = RecordType; Record.CPU = RecordExtractor.getU8(&OffsetPtr); auto Type = RecordExtractor.getU8(&OffsetPtr); switch (Type) { case 0: Record.Type = RecordTypes::ENTER; break; case 1: Record.Type = RecordTypes::EXIT; break; case 2: Record.Type = RecordTypes::TAIL_EXIT; break; case 3: Record.Type = RecordTypes::ENTER_ARG; break; default: return make_error<StringError>( Twine("Unknown record type '") + Twine(int{Type}) + "'", std::make_error_code(std::errc::executable_format_error)); } Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t)); Record.TSC = RecordExtractor.getU64(&OffsetPtr); Record.TId = RecordExtractor.getU32(&OffsetPtr); break; } case 1: { // Arg payload record. auto &Record = Records.back(); // Advance two bytes to avoid padding. OffsetPtr += 2; int32_t FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t)); auto TId = RecordExtractor.getU32(&OffsetPtr); if (Record.FuncId != FuncId || Record.TId != TId) return make_error<StringError>( Twine("Corrupted log, found payload following non-matching " "function + thread record. Record for ") + Twine(Record.FuncId) + " != " + Twine(FuncId), std::make_error_code(std::errc::executable_format_error)); // Advance another four bytes to avoid padding. OffsetPtr += 4; auto Arg = RecordExtractor.getU64(&OffsetPtr); Record.CallArgs.push_back(Arg); break; } default: return make_error<StringError>( Twine("Unknown record type == ") + Twine(RecordType), std::make_error_code(std::errc::executable_format_error)); } } return Error::success(); } /// When reading from a Flight Data Recorder mode log, metadata records are /// sparse compared to packed function records, so we must maintain state as we /// read through the sequence of entries. This allows the reader to denormalize /// the CPUId and Thread Id onto each Function Record and transform delta /// encoded TSC values into absolute encodings on each record. struct FDRState { uint16_t CPUId; uint16_t ThreadId; uint64_t BaseTSC; /// Encode some of the state transitions for the FDR log reader as explicit /// checks. These are expectations for the next Record in the stream. enum class Token { NEW_BUFFER_RECORD_OR_EOF, WALLCLOCK_RECORD, NEW_CPU_ID_RECORD, FUNCTION_SEQUENCE, SCAN_TO_END_OF_THREAD_BUF, CUSTOM_EVENT_DATA, CALL_ARGUMENT, BUFFER_EXTENTS, }; Token Expects; // Each threads buffer may have trailing garbage to scan over, so we track our // progress. uint64_t CurrentBufferSize; uint64_t CurrentBufferConsumed; }; const char *fdrStateToTwine(const FDRState::Token &state) { switch (state) { case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF: return "NEW_BUFFER_RECORD_OR_EOF"; case FDRState::Token::WALLCLOCK_RECORD: return "WALLCLOCK_RECORD"; case FDRState::Token::NEW_CPU_ID_RECORD: return "NEW_CPU_ID_RECORD"; case FDRState::Token::FUNCTION_SEQUENCE: return "FUNCTION_SEQUENCE"; case FDRState::Token::SCAN_TO_END_OF_THREAD_BUF: return "SCAN_TO_END_OF_THREAD_BUF"; case FDRState::Token::CUSTOM_EVENT_DATA: return "CUSTOM_EVENT_DATA"; case FDRState::Token::CALL_ARGUMENT: return "CALL_ARGUMENT"; case FDRState::Token::BUFFER_EXTENTS: return "BUFFER_EXTENTS"; } return "UNKNOWN"; } /// State transition when a NewBufferRecord is encountered. Error processFDRNewBufferRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor) { if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF) return make_error<StringError>( Twine("Malformed log. Read New Buffer record kind out of sequence; " "expected: ") + fdrStateToTwine(State.Expects), std::make_error_code(std::errc::executable_format_error)); uint32_t OffsetPtr = 1; // 1 byte into record. State.ThreadId = RecordExtractor.getU16(&OffsetPtr); State.Expects = FDRState::Token::WALLCLOCK_RECORD; return Error::success(); } /// State transition when an EndOfBufferRecord is encountered. Error processFDREndOfBufferRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor) { if (State.Expects == FDRState::Token::NEW_BUFFER_RECORD_OR_EOF) return make_error<StringError>( Twine("Malformed log. Received EOB message without current buffer; " "expected: ") + fdrStateToTwine(State.Expects), std::make_error_code(std::errc::executable_format_error)); State.Expects = FDRState::Token::SCAN_TO_END_OF_THREAD_BUF; return Error::success(); } /// State transition when a NewCPUIdRecord is encountered. Error processFDRNewCPUIdRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor) { if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE && State.Expects != FDRState::Token::NEW_CPU_ID_RECORD) return make_error<StringError>( Twine("Malformed log. Read NewCPUId record kind out of sequence; " "expected: ") + fdrStateToTwine(State.Expects), std::make_error_code(std::errc::executable_format_error)); uint32_t OffsetPtr = 1; // Read starting after the first byte. State.CPUId = RecordExtractor.getU16(&OffsetPtr); State.BaseTSC = RecordExtractor.getU64(&OffsetPtr); State.Expects = FDRState::Token::FUNCTION_SEQUENCE; return Error::success(); } /// State transition when a TSCWrapRecord (overflow detection) is encountered. Error processFDRTSCWrapRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor) { if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE) return make_error<StringError>( Twine("Malformed log. Read TSCWrap record kind out of sequence; " "expecting: ") + fdrStateToTwine(State.Expects), std::make_error_code(std::errc::executable_format_error)); uint32_t OffsetPtr = 1; // Read starting after the first byte. State.BaseTSC = RecordExtractor.getU64(&OffsetPtr); return Error::success(); } /// State transition when a WallTimeMarkerRecord is encountered. Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor) { if (State.Expects != FDRState::Token::WALLCLOCK_RECORD) return make_error<StringError>( Twine("Malformed log. Read Wallclock record kind out of sequence; " "expecting: ") + fdrStateToTwine(State.Expects), std::make_error_code(std::errc::executable_format_error)); // TODO: Someday, reconcile the TSC ticks to wall clock time for presentation // purposes. For now, we're ignoring these records. State.Expects = FDRState::Token::NEW_CPU_ID_RECORD; return Error::success(); } /// State transition when a CustomEventMarker is encountered. Error processCustomEventMarker(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor, size_t &RecordSize) { // We can encounter a CustomEventMarker anywhere in the log, so we can handle // it regardless of the expectation. However, we do set the expectation to // read a set number of fixed bytes, as described in the metadata. uint32_t OffsetPtr = 1; // Read after the first byte. uint32_t DataSize = RecordExtractor.getU32(&OffsetPtr); uint64_t TSC = RecordExtractor.getU64(&OffsetPtr); // FIXME: Actually represent the record through the API. For now we only // skip through the data. (void)TSC; RecordSize = 16 + DataSize; return Error::success(); } /// State transition when an BufferExtents record is encountered. Error processBufferExtents(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor) { if (State.Expects != FDRState::Token::BUFFER_EXTENTS) return make_error<StringError>( Twine("Malformed log. Buffer Extents unexpected; expected: ") + fdrStateToTwine(State.Expects), std::make_error_code(std::errc::executable_format_error)); uint32_t OffsetPtr = 1; // Read after the first byte. State.CurrentBufferSize = RecordExtractor.getU64(&OffsetPtr); State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF; return Error::success(); } /// State transition when a CallArgumentRecord is encountered. Error processFDRCallArgumentRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor, std::vector<XRayRecord> &Records) { uint32_t OffsetPtr = 1; // Read starting after the first byte. auto &Enter = Records.back(); if (Enter.Type != RecordTypes::ENTER) return make_error<StringError>( "CallArgument needs to be right after a function entry", std::make_error_code(std::errc::executable_format_error)); Enter.Type = RecordTypes::ENTER_ARG; Enter.CallArgs.emplace_back(RecordExtractor.getU64(&OffsetPtr)); return Error::success(); } /// Advances the state machine for reading the FDR record type by reading one /// Metadata Record and updating the State appropriately based on the kind of /// record encountered. The RecordKind is encoded in the first byte of the /// Record, which the caller should pass in because they have already read it /// to determine that this is a metadata record as opposed to a function record. /// /// Beginning with Version 2 of the FDR log, we do not depend on the size of the /// buffer, but rather use the extents to determine how far to read in the log /// for this particular buffer. Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor, size_t &RecordSize, std::vector<XRayRecord> &Records, uint16_t Version) { // The remaining 7 bits are the RecordKind enum. uint8_t RecordKind = RecordFirstByte >> 1; switch (RecordKind) { case 0: // NewBuffer if (auto E = processFDRNewBufferRecord(State, RecordFirstByte, RecordExtractor)) return E; break; case 1: // EndOfBuffer if (Version >= 2) return make_error<StringError>( "Since Version 2 of FDR logging, we no longer support EOB records.", std::make_error_code(std::errc::executable_format_error)); if (auto E = processFDREndOfBufferRecord(State, RecordFirstByte, RecordExtractor)) return E; break; case 2: // NewCPUId if (auto E = processFDRNewCPUIdRecord(State, RecordFirstByte, RecordExtractor)) return E; break; case 3: // TSCWrap if (auto E = processFDRTSCWrapRecord(State, RecordFirstByte, RecordExtractor)) return E; break; case 4: // WallTimeMarker if (auto E = processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor)) return E; break; case 5: // CustomEventMarker if (auto E = processCustomEventMarker(State, RecordFirstByte, RecordExtractor, RecordSize)) return E; break; case 6: // CallArgument if (auto E = processFDRCallArgumentRecord(State, RecordFirstByte, RecordExtractor, Records)) return E; break; case 7: // BufferExtents if (auto E = processBufferExtents(State, RecordFirstByte, RecordExtractor)) return E; break; default: // Widen the record type to uint16_t to prevent conversion to char. return make_error<StringError>( Twine("Illegal metadata record type: ") .concat(Twine(static_cast<unsigned>(RecordKind))), std::make_error_code(std::errc::executable_format_error)); } return Error::success(); } /// Reads a function record from an FDR format log, appending a new XRayRecord /// to the vector being populated and updating the State with a new value /// reference value to interpret TSC deltas. /// /// The XRayRecord constructed includes information from the function record /// processed here as well as Thread ID and CPU ID formerly extracted into /// State. Error processFDRFunctionRecord(FDRState &State, uint8_t RecordFirstByte, DataExtractor &RecordExtractor, std::vector<XRayRecord> &Records) { switch (State.Expects) { case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF: return make_error<StringError>( "Malformed log. Received Function Record before new buffer setup.", std::make_error_code(std::errc::executable_format_error)); case FDRState::Token::WALLCLOCK_RECORD: return make_error<StringError>( "Malformed log. Received Function Record when expecting wallclock.", std::make_error_code(std::errc::executable_format_error)); case FDRState::Token::NEW_CPU_ID_RECORD: return make_error<StringError>( "Malformed log. Received Function Record before first CPU record.", std::make_error_code(std::errc::executable_format_error)); default: Records.emplace_back(); auto &Record = Records.back(); Record.RecordType = 0; // Record is type NORMAL. // Strip off record type bit and use the next three bits. uint8_t RecordType = (RecordFirstByte >> 1) & 0x07; switch (RecordType) { case static_cast<uint8_t>(RecordTypes::ENTER): Record.Type = RecordTypes::ENTER; break; case static_cast<uint8_t>(RecordTypes::EXIT): Record.Type = RecordTypes::EXIT; break; case static_cast<uint8_t>(RecordTypes::TAIL_EXIT): Record.Type = RecordTypes::TAIL_EXIT; break; default: // Cast to an unsigned integer to not interpret the record type as a char. return make_error<StringError>( Twine("Illegal function record type: ") .concat(Twine(static_cast<unsigned>(RecordType))), std::make_error_code(std::errc::executable_format_error)); } Record.CPU = State.CPUId; Record.TId = State.ThreadId; // Back up to read first 32 bits, including the 4 we pulled RecordType // and RecordKind out of. The remaining 28 are FunctionId. uint32_t OffsetPtr = 0; // Despite function Id being a signed int on XRayRecord, // when it is written to an FDR format, the top bits are truncated, // so it is effectively an unsigned value. When we shift off the // top four bits, we want the shift to be logical, so we read as // uint32_t. uint32_t FuncIdBitField = RecordExtractor.getU32(&OffsetPtr); Record.FuncId = FuncIdBitField >> 4; // FunctionRecords have a 32 bit delta from the previous absolute TSC // or TSC delta. If this would overflow, we should read a TSCWrap record // with an absolute TSC reading. uint64_t NewTSC = State.BaseTSC + RecordExtractor.getU32(&OffsetPtr); State.BaseTSC = NewTSC; Record.TSC = NewTSC; } return Error::success(); } /// Reads a log in FDR mode for version 1 of this binary format. FDR mode is /// defined as part of the compiler-rt project in xray_fdr_logging.h, and such /// a log consists of the familiar 32 bit XRayHeader, followed by sequences of /// of interspersed 16 byte Metadata Records and 8 byte Function Records. /// /// The following is an attempt to document the grammar of the format, which is /// parsed by this function for little-endian machines. Since the format makes /// use of BitFields, when we support big-endian architectures, we will need to /// adjust not only the endianness parameter to llvm's RecordExtractor, but also /// the bit twiddling logic, which is consistent with the little-endian /// convention that BitFields within a struct will first be packed into the /// least significant bits the address they belong to. /// /// We expect a format complying with the grammar in the following pseudo-EBNF /// in Version 1 of the FDR log. /// /// FDRLog: XRayFileHeader ThreadBuffer* /// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata. /// Includes BufferSize /// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB /// BufSize: 8 byte unsigned integer indicating how large the buffer is. /// NewBuffer: 16 byte metadata record with Thread Id. /// WallClockTime: 16 byte metadata record with human readable time. /// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading. /// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize. /// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord /// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading. /// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta. /// /// In Version 2, we make the following changes: /// /// ThreadBuffer: BufferExtents NewBuffer WallClockTime NewCPUId /// FunctionSequence /// BufferExtents: 16 byte metdata record describing how many usable bytes are /// in the buffer. This is measured from the start of the buffer /// and must always be at least 48 (bytes). /// EOB: *deprecated* Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) { if (Data.size() < 32) return make_error<StringError>( "Not enough bytes for an XRay log.", std::make_error_code(std::errc::invalid_argument)); // For an FDR log, there are records sized 16 and 8 bytes. // There actually may be no records if no non-trivial functions are // instrumented. if (Data.size() % 8 != 0) return make_error<StringError>( "Invalid-sized XRay data.", std::make_error_code(std::errc::invalid_argument)); if (auto E = readBinaryFormatHeader(Data, FileHeader)) return E; uint64_t BufferSize = 0; { StringRef ExtraDataRef(FileHeader.FreeFormData, 16); DataExtractor ExtraDataExtractor(ExtraDataRef, true, 8); uint32_t ExtraDataOffset = 0; BufferSize = ExtraDataExtractor.getU64(&ExtraDataOffset); } FDRState::Token InitialExpectation; switch (FileHeader.Version) { case 1: InitialExpectation = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF; break; case 2: InitialExpectation = FDRState::Token::BUFFER_EXTENTS; break; default: return make_error<StringError>( Twine("Unsupported version '") + Twine(FileHeader.Version) + "'", std::make_error_code(std::errc::executable_format_error)); } FDRState State{0, 0, 0, InitialExpectation, BufferSize, 0}; // RecordSize will tell the loop how far to seek ahead based on the record // type that we have just read. size_t RecordSize = 0; for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(RecordSize)) { DataExtractor RecordExtractor(S, true, 8); uint32_t OffsetPtr = 0; if (State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF) { RecordSize = State.CurrentBufferSize - State.CurrentBufferConsumed; if (S.size() < RecordSize) { return make_error<StringError>( Twine("Incomplete thread buffer. Expected at least ") + Twine(RecordSize) + " bytes but found " + Twine(S.size()), make_error_code(std::errc::invalid_argument)); } State.CurrentBufferConsumed = 0; State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF; continue; } uint8_t BitField = RecordExtractor.getU8(&OffsetPtr); bool isMetadataRecord = BitField & 0x01uL; bool isBufferExtents = (BitField >> 1) == 7; // BufferExtents record kind == 7 if (isMetadataRecord) { RecordSize = 16; if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor, RecordSize, Records, FileHeader.Version)) return E; } else { // Process Function Record RecordSize = 8; if (auto E = processFDRFunctionRecord(State, BitField, RecordExtractor, Records)) return E; } // The BufferExtents record is technically not part of the buffer, so we // don't count the size of that record against the buffer's actual size. if (!isBufferExtents) State.CurrentBufferConsumed += RecordSize; assert(State.CurrentBufferConsumed <= State.CurrentBufferSize); if (FileHeader.Version == 2 && State.CurrentBufferSize == State.CurrentBufferConsumed) { // In Version 2 of the log, we don't need to scan to the end of the thread // buffer if we've already consumed all the bytes we need to. State.Expects = FDRState::Token::BUFFER_EXTENTS; State.CurrentBufferSize = BufferSize; State.CurrentBufferConsumed = 0; } } // Having iterated over everything we've been given, we've either consumed // everything and ended up in the end state, or were told to skip the rest. bool Finished = State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF && State.CurrentBufferSize == State.CurrentBufferConsumed; if ((State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF && State.Expects != FDRState::Token::BUFFER_EXTENTS) && !Finished) return make_error<StringError>( Twine("Encountered EOF with unexpected state expectation ") + fdrStateToTwine(State.Expects) + ". Remaining expected bytes in thread buffer total " + Twine(State.CurrentBufferSize - State.CurrentBufferConsumed), std::make_error_code(std::errc::executable_format_error)); return Error::success(); } Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) { YAMLXRayTrace Trace; Input In(Data); In >> Trace; if (In.error()) return make_error<StringError>("Failed loading YAML Data.", In.error()); FileHeader.Version = Trace.Header.Version; FileHeader.Type = Trace.Header.Type; FileHeader.ConstantTSC = Trace.Header.ConstantTSC; FileHeader.NonstopTSC = Trace.Header.NonstopTSC; FileHeader.CycleFrequency = Trace.Header.CycleFrequency; if (FileHeader.Version != 1) return make_error<StringError>( Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version), std::make_error_code(std::errc::invalid_argument)); Records.clear(); std::transform(Trace.Records.begin(), Trace.Records.end(), std::back_inserter(Records), [&](const YAMLXRayRecord &R) { return XRayRecord{R.RecordType, R.CPU, R.Type, R.FuncId, R.TSC, R.TId, R.CallArgs}; }); return Error::success(); } } // namespace Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) { int Fd; if (auto EC = sys::fs::openFileForRead(Filename, Fd)) { return make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); } uint64_t FileSize; if (auto EC = sys::fs::file_size(Filename, FileSize)) { return make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); } if (FileSize < 4) { return make_error<StringError>( Twine("File '") + Filename + "' too small for XRay.", std::make_error_code(std::errc::executable_format_error)); } // Map the opened file into memory and use a StringRef to access it later. std::error_code EC; sys::fs::mapped_file_region MappedFile( Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC); if (EC) { return make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); } auto Data = StringRef(MappedFile.data(), MappedFile.size()); // Attempt to detect the file type using file magic. We have a slight bias // towards the binary format, and we do this by making sure that the first 4 // bytes of the binary file is some combination of the following byte // patterns: (observe the code loading them assumes they're little endian) // // 0x01 0x00 0x00 0x00 - version 1, "naive" format // 0x01 0x00 0x01 0x00 - version 1, "flight data recorder" format // 0x02 0x00 0x01 0x00 - version 2, "flight data recorder" format // // YAML files don't typically have those first four bytes as valid text so we // try loading assuming YAML if we don't find these bytes. // // Only if we can't load either the binary or the YAML format will we yield an // error. StringRef Magic(MappedFile.data(), 4); DataExtractor HeaderExtractor(Magic, true, 8); uint32_t OffsetPtr = 0; uint16_t Version = HeaderExtractor.getU16(&OffsetPtr); uint16_t Type = HeaderExtractor.getU16(&OffsetPtr); enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 }; Trace T; switch (Type) { case NAIVE_FORMAT: if (Version == 1 || Version == 2) { if (auto E = loadNaiveFormatLog(Data, T.FileHeader, T.Records)) return std::move(E); } else { return make_error<StringError>( Twine("Unsupported version for Basic/Naive Mode logging: ") + Twine(Version), std::make_error_code(std::errc::executable_format_error)); } break; case FLIGHT_DATA_RECORDER_FORMAT: if (Version == 1 || Version == 2) { if (auto E = loadFDRLog(Data, T.FileHeader, T.Records)) return std::move(E); } else { return make_error<StringError>( Twine("Unsupported version for FDR Mode logging: ") + Twine(Version), std::make_error_code(std::errc::executable_format_error)); } break; default: if (auto E = loadYAMLLog(Data, T.FileHeader, T.Records)) return std::move(E); } if (Sort) std::stable_sort(T.Records.begin(), T.Records.end(), [&](const XRayRecord &L, const XRayRecord &R) { return L.TSC < R.TSC; }); return std::move(T); }
41.339385
80
0.672219
[ "vector", "transform" ]
d1fd47fc4173cf5808fc461d0ba52a0ef628e029
984
cpp
C++
LeetCode/787_Cheapest_Flights_Within_K_Stops/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-07-08T23:16:19.000Z
2020-07-08T23:16:19.000Z
LeetCode/787_Cheapest_Flights_Within_K_Stops/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-05-16T03:12:24.000Z
2020-05-16T03:14:42.000Z
LeetCode/787_Cheapest_Flights_Within_K_Stops/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
2
2020-05-16T03:25:16.000Z
2021-02-10T16:51:25.000Z
class Solution { private: vector<vector<int>> v[101]; public: int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) { vector<int> dist(n, INT_MAX); vector<bool> chk(n, false); for(auto flight : flights) { v[flight[0]].push_back({flight[1], flight[2]}); } queue<pair<int, int>> q; q.push({0, src}); dist[src] = 0; ++k; while (!q.empty()) { int si = q.size(); if (--k < 0) break; for (int i = 0; i < si; ++i) { pair<int, int> cur = q.front(); q.pop(); for (auto j : v[cur.second]) { if (j[1] + cur.first < dist[j[0]]) { dist[j[0]] = j[1] + cur.first; q.push({dist[j[0]], j[0]}); } } } } return (dist[dst] == INT_MAX ? -1 : dist[dst]); } };
30.75
89
0.396341
[ "vector" ]
d1fd54c7b6514f80338882f4e1daaf00c07962b1
68,775
cpp
C++
indra/llappearance/llavatarappearance.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/llappearance/llavatarappearance.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/llappearance/llavatarappearance.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @File llavatarappearance.cpp * @brief Implementation of LLAvatarAppearance class * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #if LL_MSVC // disable warning about boost::lexical_cast returning uninitialized data // when it fails to parse the string #pragma warning (disable:4701) #endif #include "linden_common.h" #include "llavatarappearance.h" #include "llavatarappearancedefines.h" #include "llavatarjointmesh.h" #include "llstl.h" #include "lldir.h" #include "llpolymorph.h" #include "llpolymesh.h" #include "llpolyskeletaldistortion.h" #include "llstl.h" #include "lltexglobalcolor.h" #include "llwearabledata.h" #include "boost/bind.hpp" #include "boost/tokenizer.hpp" #if LL_MSVC // disable boost::lexical_cast warning #pragma warning (disable:4702) #endif #include <boost/lexical_cast.hpp> using namespace LLAvatarAppearanceDefines; //----------------------------------------------------------------------------- // Constants //----------------------------------------------------------------------------- const std::string AVATAR_DEFAULT_CHAR = "avatar"; const LLColor4 DUMMY_COLOR = LLColor4(0.5,0.5,0.5,1.0); /********************************************************************************* ** ** ** Begin private LLAvatarAppearance Support classes ** **/ //------------------------------------------------------------------------ // LLAvatarBoneInfo // Trans/Scale/Rot etc. info about each avatar bone. Used by LLVOAvatarSkeleton. //------------------------------------------------------------------------ class LLAvatarBoneInfo { friend class LLAvatarAppearance; friend class LLAvatarSkeletonInfo; public: LLAvatarBoneInfo() : mIsJoint(FALSE) {} ~LLAvatarBoneInfo() { std::for_each(mChildren.begin(), mChildren.end(), DeletePointer()); mChildren.clear(); } BOOL parseXml(LLXmlTreeNode* node); private: std::string mName; std::string mSupport; std::string mAliases; BOOL mIsJoint; LLVector3 mPos; LLVector3 mEnd; LLVector3 mRot; LLVector3 mScale; LLVector3 mPivot; typedef std::vector<LLAvatarBoneInfo*> bones_t; bones_t mChildren; }; //------------------------------------------------------------------------ // LLAvatarSkeletonInfo // Overall avatar skeleton //------------------------------------------------------------------------ class LLAvatarSkeletonInfo { friend class LLAvatarAppearance; public: LLAvatarSkeletonInfo() : mNumBones(0), mNumCollisionVolumes(0) {} ~LLAvatarSkeletonInfo() { std::for_each(mBoneInfoList.begin(), mBoneInfoList.end(), DeletePointer()); mBoneInfoList.clear(); } BOOL parseXml(LLXmlTreeNode* node); S32 getNumBones() const { return mNumBones; } S32 getNumCollisionVolumes() const { return mNumCollisionVolumes; } private: S32 mNumBones; S32 mNumCollisionVolumes; LLAvatarAppearance::joint_alias_map_t mJointAliasMap; typedef std::vector<LLAvatarBoneInfo*> bone_info_list_t; bone_info_list_t mBoneInfoList; }; //----------------------------------------------------------------------------- // LLAvatarXmlInfo //----------------------------------------------------------------------------- LLAvatarAppearance::LLAvatarXmlInfo::LLAvatarXmlInfo() : mTexSkinColorInfo(0), mTexHairColorInfo(0), mTexEyeColorInfo(0) { } LLAvatarAppearance::LLAvatarXmlInfo::~LLAvatarXmlInfo() { std::for_each(mMeshInfoList.begin(), mMeshInfoList.end(), DeletePointer()); mMeshInfoList.clear(); std::for_each(mSkeletalDistortionInfoList.begin(), mSkeletalDistortionInfoList.end(), DeletePointer()); mSkeletalDistortionInfoList.clear(); std::for_each(mAttachmentInfoList.begin(), mAttachmentInfoList.end(), DeletePointer()); mAttachmentInfoList.clear(); delete_and_clear(mTexSkinColorInfo); delete_and_clear(mTexHairColorInfo); delete_and_clear(mTexEyeColorInfo); std::for_each(mLayerInfoList.begin(), mLayerInfoList.end(), DeletePointer()); mLayerInfoList.clear(); std::for_each(mDriverInfoList.begin(), mDriverInfoList.end(), DeletePointer()); mDriverInfoList.clear(); std::for_each(mMorphMaskInfoList.begin(), mMorphMaskInfoList.end(), DeletePointer()); mMorphMaskInfoList.clear(); } /** ** ** End LLAvatarAppearance Support classes ** ** *********************************************************************************/ //----------------------------------------------------------------------------- // Static Data //----------------------------------------------------------------------------- LLAvatarSkeletonInfo* LLAvatarAppearance::sAvatarSkeletonInfo = NULL; LLAvatarAppearance::LLAvatarXmlInfo* LLAvatarAppearance::sAvatarXmlInfo = NULL; LLAvatarAppearanceDefines::LLAvatarAppearanceDictionary* LLAvatarAppearance::sAvatarDictionary = NULL; LLAvatarAppearance::LLAvatarAppearance(LLWearableData* wearable_data) : LLCharacter(), mIsDummy(FALSE), mTexSkinColor( NULL ), mTexHairColor( NULL ), mTexEyeColor( NULL ), mPelvisToFoot(0.f), mHeadOffset(), mRoot(NULL), mWearableData(wearable_data), mNumBones(0), mNumCollisionVolumes(0), mCollisionVolumes(NULL), mIsBuilt(FALSE), mInitFlags(0) { llassert_always(mWearableData); mBakedTextureDatas.resize(LLAvatarAppearanceDefines::BAKED_NUM_INDICES); for (U32 i = 0; i < mBakedTextureDatas.size(); i++ ) { mBakedTextureDatas[i].mLastTextureID = IMG_DEFAULT_AVATAR; mBakedTextureDatas[i].mTexLayerSet = NULL; mBakedTextureDatas[i].mIsLoaded = false; mBakedTextureDatas[i].mIsUsed = false; mBakedTextureDatas[i].mMaskTexName = 0; mBakedTextureDatas[i].mTextureIndex = sAvatarDictionary->bakedToLocalTextureIndex((LLAvatarAppearanceDefines::EBakedTextureIndex)i); } } // virtual void LLAvatarAppearance::initInstance() { //------------------------------------------------------------------------- // initialize joint, mesh and shape members //------------------------------------------------------------------------- mRoot = createAvatarJoint(); mRoot->setName( "mRoot" ); for (LLAvatarAppearanceDictionary::MeshEntries::const_iterator iter = sAvatarDictionary->getMeshEntries().begin(); iter != sAvatarDictionary->getMeshEntries().end(); ++iter) { const EMeshIndex mesh_index = iter->first; const LLAvatarAppearanceDictionary::MeshEntry *mesh_dict = iter->second; LLAvatarJoint* joint = createAvatarJoint(); joint->setName(mesh_dict->mName); joint->setMeshID(mesh_index); mMeshLOD.push_back(joint); /* mHairLOD.setName("mHairLOD"); mHairMesh0.setName("mHairMesh0"); mHairMesh0.setMeshID(MESH_ID_HAIR); mHairMesh1.setName("mHairMesh1"); */ for (U32 lod = 0; lod < mesh_dict->mLOD; lod++) { LLAvatarJointMesh* mesh = createAvatarJointMesh(); std::string mesh_name = "m" + mesh_dict->mName + boost::lexical_cast<std::string>(lod); // We pre-pended an m - need to capitalize first character for camelCase mesh_name[1] = toupper(mesh_name[1]); mesh->setName(mesh_name); mesh->setMeshID(mesh_index); mesh->setPickName(mesh_dict->mPickName); mesh->setIsTransparent(FALSE); switch((S32)mesh_index) { case MESH_ID_HAIR: mesh->setIsTransparent(TRUE); break; case MESH_ID_SKIRT: mesh->setIsTransparent(TRUE); break; case MESH_ID_EYEBALL_LEFT: case MESH_ID_EYEBALL_RIGHT: mesh->setSpecular( LLColor4( 1.0f, 1.0f, 1.0f, 1.0f ), 1.f ); break; } joint->mMeshParts.push_back(mesh); } } //------------------------------------------------------------------------- // associate baked textures with meshes //------------------------------------------------------------------------- for (LLAvatarAppearanceDictionary::MeshEntries::const_iterator iter = sAvatarDictionary->getMeshEntries().begin(); iter != sAvatarDictionary->getMeshEntries().end(); ++iter) { const EMeshIndex mesh_index = iter->first; const LLAvatarAppearanceDictionary::MeshEntry *mesh_dict = iter->second; const EBakedTextureIndex baked_texture_index = mesh_dict->mBakedID; // Skip it if there's no associated baked texture. if (baked_texture_index == BAKED_NUM_INDICES) continue; // <FS:Ansariel> FIRE-11915: Variable redefinition //for (avatar_joint_mesh_list_t::iterator iter = mMeshLOD[mesh_index]->mMeshParts.begin(); // iter != mMeshLOD[mesh_index]->mMeshParts.end(); // ++iter) //{ // LLAvatarJointMesh* mesh = (*iter); // mBakedTextureDatas[(int)baked_texture_index].mJointMeshes.push_back(mesh); for (avatar_joint_mesh_list_t::iterator ajm_iter = mMeshLOD[mesh_index]->mMeshParts.begin(); ajm_iter != mMeshLOD[mesh_index]->mMeshParts.end(); ++ajm_iter) { LLAvatarJointMesh* mesh = (*ajm_iter); mBakedTextureDatas[(S32)baked_texture_index].mJointMeshes.push_back(mesh); // </FS:Ansariel> FIRE-11915: Variable redefinition } } buildCharacter(); mInitFlags |= 1<<0; } // virtual LLAvatarAppearance::~LLAvatarAppearance() { delete_and_clear(mTexSkinColor); delete_and_clear(mTexHairColor); delete_and_clear(mTexEyeColor); for (U32 i = 0; i < mBakedTextureDatas.size(); i++) { delete_and_clear(mBakedTextureDatas[i].mTexLayerSet); mBakedTextureDatas[i].mJointMeshes.clear(); for (morph_list_t::iterator iter2 = mBakedTextureDatas[i].mMaskedMorphs.begin(); iter2 != mBakedTextureDatas[i].mMaskedMorphs.end(); iter2++) { LLMaskedMorph* masked_morph = (*iter2); delete masked_morph; } } if (mRoot) mRoot->removeAllChildren(); mJointMap.clear(); clearSkeleton(); delete_and_clear_array(mCollisionVolumes); std::for_each(mPolyMeshes.begin(), mPolyMeshes.end(), DeletePairedPointer()); mPolyMeshes.clear(); for (avatar_joint_list_t::iterator jointIter = mMeshLOD.begin(); jointIter != mMeshLOD.end(); ++jointIter) { LLAvatarJoint* joint = *jointIter; std::for_each(joint->mMeshParts.begin(), joint->mMeshParts.end(), DeletePointer()); joint->mMeshParts.clear(); } std::for_each(mMeshLOD.begin(), mMeshLOD.end(), DeletePointer()); mMeshLOD.clear(); delete mRoot; } //static void LLAvatarAppearance::initClass() { initClass("",""); } //static void LLAvatarAppearance::initClass(const std::string& avatar_file_name_arg, const std::string& skeleton_file_name_arg) { // init dictionary (don't repeat on second login attempt) if (!sAvatarDictionary) { sAvatarDictionary = new LLAvatarAppearanceDefines::LLAvatarAppearanceDictionary(); } std::string avatar_file_name; if (!avatar_file_name_arg.empty()) { avatar_file_name = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,avatar_file_name_arg); } else { avatar_file_name = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,AVATAR_DEFAULT_CHAR + "_lad.xml"); } LLXmlTree xml_tree; BOOL success = xml_tree.parseFile( avatar_file_name, FALSE ); if (!success) { LL_ERRS() << "Problem reading avatar configuration file:" << avatar_file_name << LL_ENDL; } // now sanity check xml file LLXmlTreeNode* root = xml_tree.getRoot(); if (!root) { LL_ERRS() << "No root node found in avatar configuration file: " << avatar_file_name << LL_ENDL; return; } //------------------------------------------------------------------------- // <linden_avatar version="2.0"> (root) //------------------------------------------------------------------------- if( !root->hasName( "linden_avatar" ) ) { LL_ERRS() << "Invalid avatar file header: " << avatar_file_name << LL_ENDL; } std::string version; static LLStdStringHandle version_string = LLXmlTree::addAttributeString("version"); if( !root->getFastAttributeString( version_string, version ) || ((version != "1.0") && (version != "2.0"))) { LL_ERRS() << "Invalid avatar file version: " << version << " in file: " << avatar_file_name << LL_ENDL; } S32 wearable_def_version = 1; static LLStdStringHandle wearable_definition_version_string = LLXmlTree::addAttributeString("wearable_definition_version"); root->getFastAttributeS32( wearable_definition_version_string, wearable_def_version ); LLWearable::setCurrentDefinitionVersion( wearable_def_version ); std::string mesh_file_name; LLXmlTreeNode* skeleton_node = root->getChildByName( "skeleton" ); if (!skeleton_node) { LL_ERRS() << "No skeleton in avatar configuration file: " << avatar_file_name << LL_ENDL; return; } std::string skeleton_file_name = skeleton_file_name_arg; if (skeleton_file_name.empty()) { static LLStdStringHandle file_name_string = LLXmlTree::addAttributeString("file_name"); if (!skeleton_node->getFastAttributeString(file_name_string, skeleton_file_name)) { LL_ERRS() << "No file name in skeleton node in avatar config file: " << avatar_file_name << LL_ENDL; } } std::string skeleton_path; LLXmlTree skeleton_xml_tree; skeleton_path = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,skeleton_file_name); if (!parseSkeletonFile(skeleton_path, skeleton_xml_tree)) { LL_ERRS() << "Error parsing skeleton file: " << skeleton_path << LL_ENDL; } // Process XML data // avatar_skeleton.xml if (sAvatarSkeletonInfo) { //this can happen if a login attempt failed delete sAvatarSkeletonInfo; } sAvatarSkeletonInfo = new LLAvatarSkeletonInfo; if (!sAvatarSkeletonInfo->parseXml(skeleton_xml_tree.getRoot())) { LL_ERRS() << "Error parsing skeleton XML file: " << skeleton_path << LL_ENDL; } // parse avatar_lad.xml if (sAvatarXmlInfo) { //this can happen if a login attempt failed delete_and_clear(sAvatarXmlInfo); } sAvatarXmlInfo = new LLAvatarXmlInfo; if (!sAvatarXmlInfo->parseXmlSkeletonNode(root)) { LL_ERRS() << "Error parsing skeleton node in avatar XML file: " << skeleton_path << LL_ENDL; } if (!sAvatarXmlInfo->parseXmlMeshNodes(root)) { LL_ERRS() << "Error parsing skeleton node in avatar XML file: " << skeleton_path << LL_ENDL; } if (!sAvatarXmlInfo->parseXmlColorNodes(root)) { LL_ERRS() << "Error parsing skeleton node in avatar XML file: " << skeleton_path << LL_ENDL; } if (!sAvatarXmlInfo->parseXmlLayerNodes(root)) { LL_ERRS() << "Error parsing skeleton node in avatar XML file: " << skeleton_path << LL_ENDL; } if (!sAvatarXmlInfo->parseXmlDriverNodes(root)) { LL_ERRS() << "Error parsing skeleton node in avatar XML file: " << skeleton_path << LL_ENDL; } if (!sAvatarXmlInfo->parseXmlMorphNodes(root)) { LL_ERRS() << "Error parsing skeleton node in avatar XML file: " << skeleton_path << LL_ENDL; } } void LLAvatarAppearance::cleanupClass() { delete_and_clear(sAvatarXmlInfo); delete_and_clear(sAvatarDictionary); delete_and_clear(sAvatarSkeletonInfo); } using namespace LLAvatarAppearanceDefines; void LLAvatarAppearance::compareJointStateMaps(joint_state_map_t& last_state, joint_state_map_t& curr_state) { if (!last_state.empty() && (last_state != curr_state)) { S32 diff_count = 0; joint_state_map_t::iterator it; for (it=last_state.begin(); it != last_state.end(); ++it) { const std::string& key = it->first; if (last_state[key] != curr_state[key]) { LL_DEBUGS("AvatarBodySize") << "BodySize change " << key << " " << last_state[key] << "->" << curr_state[key] << LL_ENDL; diff_count++; } } if (diff_count > 0) { LL_DEBUGS("AvatarBodySize") << "Total of BodySize changes " << diff_count << LL_ENDL; } } } //------------------------------------------------------------------------ // The viewer can only suggest a good size for the agent, // the simulator will keep it inside a reasonable range. void LLAvatarAppearance::computeBodySize() { mLastBodySizeState = mCurrBodySizeState; mCurrBodySizeState["mPelvis scale"] = mPelvisp->getScale(); mCurrBodySizeState["mSkull pos"] = mSkullp->getPosition(); mCurrBodySizeState["mSkull scale"] = mSkullp->getScale(); mCurrBodySizeState["mNeck pos"] = mNeckp->getPosition(); mCurrBodySizeState["mNeck scale"] = mNeckp->getScale(); mCurrBodySizeState["mChest pos"] = mChestp->getPosition(); mCurrBodySizeState["mChest scale"] = mChestp->getScale(); mCurrBodySizeState["mHead pos"] = mHeadp->getPosition(); mCurrBodySizeState["mHead scale"] = mHeadp->getScale(); mCurrBodySizeState["mTorso pos"] = mTorsop->getPosition(); mCurrBodySizeState["mTorso scale"] = mTorsop->getScale(); mCurrBodySizeState["mHipLeft pos"] = mHipLeftp->getPosition(); mCurrBodySizeState["mHipLeft scale"] = mHipLeftp->getScale(); mCurrBodySizeState["mKneeLeft pos"] = mKneeLeftp->getPosition(); mCurrBodySizeState["mKneeLeft scale"] = mKneeLeftp->getScale(); mCurrBodySizeState["mAnkleLeft pos"] = mAnkleLeftp->getPosition(); mCurrBodySizeState["mAnkleLeft scale"] = mAnkleLeftp->getScale(); mCurrBodySizeState["mFootLeft pos"] = mFootLeftp->getPosition(); LLVector3 pelvis_scale = mPelvisp->getScale(); // some of the joints have not been cached LLVector3 skull = mSkullp->getPosition(); //LLVector3 skull_scale = mSkullp->getScale(); LLVector3 neck = mNeckp->getPosition(); LLVector3 neck_scale = mNeckp->getScale(); LLVector3 chest = mChestp->getPosition(); LLVector3 chest_scale = mChestp->getScale(); // the rest of the joints have been cached LLVector3 head = mHeadp->getPosition(); LLVector3 head_scale = mHeadp->getScale(); LLVector3 torso = mTorsop->getPosition(); LLVector3 torso_scale = mTorsop->getScale(); LLVector3 hip = mHipLeftp->getPosition(); LLVector3 hip_scale = mHipLeftp->getScale(); LLVector3 knee = mKneeLeftp->getPosition(); LLVector3 knee_scale = mKneeLeftp->getScale(); LLVector3 ankle = mAnkleLeftp->getPosition(); LLVector3 ankle_scale = mAnkleLeftp->getScale(); LLVector3 foot = mFootLeftp->getPosition(); F32 old_offset = mAvatarOffset.mV[VZ]; // [RLVa:KB] - Checked: 2013-03-03 (RLVa-1.4.8) mAvatarOffset.mV[VZ] = getAvatarOffset(); // [/RLVa:KB] // mAvatarOffset.mV[VZ] = getVisualParamWeight(AVATAR_HOVER); mPelvisToFoot = hip.mV[VZ] * pelvis_scale.mV[VZ] - knee.mV[VZ] * hip_scale.mV[VZ] - ankle.mV[VZ] * knee_scale.mV[VZ] - foot.mV[VZ] * ankle_scale.mV[VZ]; LLVector3 new_body_size; new_body_size.mV[VZ] = mPelvisToFoot + // the sqrt(2) correction below is an approximate // correction to get to the top of the head F_SQRT2 * (skull.mV[VZ] * head_scale.mV[VZ]) + head.mV[VZ] * neck_scale.mV[VZ] + neck.mV[VZ] * chest_scale.mV[VZ] + chest.mV[VZ] * torso_scale.mV[VZ] + torso.mV[VZ] * pelvis_scale.mV[VZ]; // TODO -- measure the real depth and width new_body_size.mV[VX] = DEFAULT_AGENT_DEPTH; new_body_size.mV[VY] = DEFAULT_AGENT_WIDTH; mAvatarOffset.mV[VX] = 0.0f; mAvatarOffset.mV[VY] = 0.0f; if (new_body_size != mBodySize || old_offset != mAvatarOffset.mV[VZ]) { mBodySize = new_body_size; // <FS:Ansariel> [Legacy Bake] bodySizeChanged(); compareJointStateMaps(mLastBodySizeState, mCurrBodySizeState); } } // [RLVa:KB] - Checked: 2013-03-03 (RLVa-1.4.8) F32 LLAvatarAppearance::getAvatarOffset() /*const*/ { return getVisualParamWeight(AVATAR_HOVER); } // [/RLVa:KB] //----------------------------------------------------------------------------- // parseSkeletonFile() //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::parseSkeletonFile(const std::string& filename, LLXmlTree& skeleton_xml_tree) { //------------------------------------------------------------------------- // parse the file //------------------------------------------------------------------------- BOOL parsesuccess = skeleton_xml_tree.parseFile( filename, FALSE ); if (!parsesuccess) { LL_ERRS() << "Can't parse skeleton file: " << filename << LL_ENDL; return FALSE; } // now sanity check xml file LLXmlTreeNode* root = skeleton_xml_tree.getRoot(); if (!root) { LL_ERRS() << "No root node found in avatar skeleton file: " << filename << LL_ENDL; return FALSE; } if( !root->hasName( "linden_skeleton" ) ) { LL_ERRS() << "Invalid avatar skeleton file header: " << filename << LL_ENDL; return FALSE; } std::string version; static LLStdStringHandle version_string = LLXmlTree::addAttributeString("version"); if( !root->getFastAttributeString( version_string, version ) || ((version != "1.0") && (version != "2.0"))) { LL_ERRS() << "Invalid avatar skeleton file version: " << version << " in file: " << filename << LL_ENDL; return FALSE; } return TRUE; } //----------------------------------------------------------------------------- // setupBone() //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::setupBone(const LLAvatarBoneInfo* info, LLJoint* parent, S32 &volume_num, S32 &joint_num) { LLJoint* joint = NULL; LL_DEBUGS("BVH") << "bone info: name " << info->mName << " isJoint " << info->mIsJoint << " volume_num " << volume_num << " joint_num " << joint_num << LL_ENDL; if (info->mIsJoint) { joint = getCharacterJoint(joint_num); if (!joint) { LL_WARNS() << "Too many bones" << LL_ENDL; return FALSE; } joint->setName( info->mName ); } else // collision volume { if (volume_num >= (S32)mNumCollisionVolumes) { LL_WARNS() << "Too many collision volumes" << LL_ENDL; return FALSE; } joint = (&mCollisionVolumes[volume_num]); joint->setName( info->mName ); } // add to parent if (parent && (joint->getParent()!=parent)) { parent->addChild( joint ); } // SL-315 joint->setPosition(info->mPos); joint->setDefaultPosition(info->mPos); joint->setRotation(mayaQ(info->mRot.mV[VX], info->mRot.mV[VY], info->mRot.mV[VZ], LLQuaternion::XYZ)); joint->setScale(info->mScale); joint->setDefaultScale(info->mScale); joint->setSupport(info->mSupport); joint->setEnd(info->mEnd); if (info->mIsJoint) { joint->setSkinOffset( info->mPivot ); joint->setJointNum(joint_num); joint_num++; } else // collision volume { joint->setJointNum(mNumBones+volume_num); volume_num++; } // setup children LLAvatarBoneInfo::bones_t::const_iterator iter; for (iter = info->mChildren.begin(); iter != info->mChildren.end(); ++iter) { LLAvatarBoneInfo *child_info = *iter; if (!setupBone(child_info, joint, volume_num, joint_num)) { return FALSE; } } return TRUE; } //----------------------------------------------------------------------------- // allocateCharacterJoints() //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::allocateCharacterJoints( S32 num ) { if (mSkeleton.size() != num) { clearSkeleton(); // mSkeleton = avatar_joint_list_t(num,NULL); mSkeleton = avatar_joint_list_t(num, static_cast< LLAvatarJoint*>( NULL )); mNumBones = num; } return TRUE; } //----------------------------------------------------------------------------- // buildSkeleton() //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::buildSkeleton(const LLAvatarSkeletonInfo *info) { LL_DEBUGS("BVH") << "numBones " << info->mNumBones << " numCollisionVolumes " << info->mNumCollisionVolumes << LL_ENDL; // allocate joints if (!allocateCharacterJoints(info->mNumBones)) { LL_ERRS() << "Can't allocate " << info->mNumBones << " joints" << LL_ENDL; return FALSE; } // allocate volumes if (info->mNumCollisionVolumes) { if (!allocateCollisionVolumes(info->mNumCollisionVolumes)) { LL_ERRS() << "Can't allocate " << info->mNumCollisionVolumes << " collision volumes" << LL_ENDL; return FALSE; } } S32 current_joint_num = 0; S32 current_volume_num = 0; LLAvatarSkeletonInfo::bone_info_list_t::const_iterator iter; for (iter = info->mBoneInfoList.begin(); iter != info->mBoneInfoList.end(); ++iter) { LLAvatarBoneInfo *bone_info = *iter; if (!setupBone(bone_info, NULL, current_volume_num, current_joint_num)) { LL_ERRS() << "Error parsing bone in skeleton file" << LL_ENDL; return FALSE; } } return TRUE; } //----------------------------------------------------------------------------- // clearSkeleton() //----------------------------------------------------------------------------- void LLAvatarAppearance::clearSkeleton() { std::for_each(mSkeleton.begin(), mSkeleton.end(), DeletePointer()); mSkeleton.clear(); } //------------------------------------------------------------------------ // addPelvisFixup //------------------------------------------------------------------------ void LLAvatarAppearance::addPelvisFixup( F32 fixup, const LLUUID& mesh_id ) { LLVector3 pos(0.0,0.0,fixup); mPelvisFixups.add(mesh_id,pos); } //------------------------------------------------------------------------ // addPelvisFixup //------------------------------------------------------------------------ void LLAvatarAppearance::removePelvisFixup( const LLUUID& mesh_id ) { mPelvisFixups.remove(mesh_id); } //------------------------------------------------------------------------ // hasPelvisFixup //------------------------------------------------------------------------ bool LLAvatarAppearance::hasPelvisFixup( F32& fixup, LLUUID& mesh_id ) const { LLVector3 pos; if (mPelvisFixups.findActiveOverride(mesh_id,pos)) { fixup = pos[2]; return true; } return false; } bool LLAvatarAppearance::hasPelvisFixup( F32& fixup ) const { LLUUID mesh_id; return hasPelvisFixup( fixup, mesh_id ); } //----------------------------------------------------------------------------- // LLAvatarAppearance::buildCharacter() // Deferred initialization and rebuild of the avatar. //----------------------------------------------------------------------------- void LLAvatarAppearance::buildCharacter() { //------------------------------------------------------------------------- // remove all references to our existing skeleton // so we can rebuild it //------------------------------------------------------------------------- flushAllMotions(); //------------------------------------------------------------------------- // remove all of mRoot's children //------------------------------------------------------------------------- mRoot->removeAllChildren(); mJointMap.clear(); mIsBuilt = FALSE; //------------------------------------------------------------------------- // clear mesh data //------------------------------------------------------------------------- for (avatar_joint_list_t::iterator jointIter = mMeshLOD.begin(); jointIter != mMeshLOD.end(); ++jointIter) { LLAvatarJoint* joint = *jointIter; for (avatar_joint_mesh_list_t::iterator meshIter = joint->mMeshParts.begin(); meshIter != joint->mMeshParts.end(); ++meshIter) { LLAvatarJointMesh * mesh = *meshIter; mesh->setMesh(NULL); } } //------------------------------------------------------------------------- // (re)load our skeleton and meshes //------------------------------------------------------------------------- LLTimer timer; BOOL status = loadAvatar(); stop_glerror(); // gPrintMessagesThisFrame = TRUE; LL_DEBUGS() << "Avatar load took " << timer.getElapsedTimeF32() << " seconds." << LL_ENDL; if (!status) { if (isSelf()) { LL_ERRS() << "Unable to load user's avatar" << LL_ENDL; } else { LL_WARNS() << "Unable to load other's avatar" << LL_ENDL; } return; } //------------------------------------------------------------------------- // initialize "well known" joint pointers //------------------------------------------------------------------------- mPelvisp = mRoot->findJoint("mPelvis"); mTorsop = mRoot->findJoint("mTorso"); mChestp = mRoot->findJoint("mChest"); mNeckp = mRoot->findJoint("mNeck"); mHeadp = mRoot->findJoint("mHead"); mSkullp = mRoot->findJoint("mSkull"); mHipLeftp = mRoot->findJoint("mHipLeft"); mHipRightp = mRoot->findJoint("mHipRight"); mKneeLeftp = mRoot->findJoint("mKneeLeft"); mKneeRightp = mRoot->findJoint("mKneeRight"); mAnkleLeftp = mRoot->findJoint("mAnkleLeft"); mAnkleRightp = mRoot->findJoint("mAnkleRight"); mFootLeftp = mRoot->findJoint("mFootLeft"); mFootRightp = mRoot->findJoint("mFootRight"); mWristLeftp = mRoot->findJoint("mWristLeft"); mWristRightp = mRoot->findJoint("mWristRight"); mEyeLeftp = mRoot->findJoint("mEyeLeft"); mEyeRightp = mRoot->findJoint("mEyeRight"); //------------------------------------------------------------------------- // Make sure "well known" pointers exist //------------------------------------------------------------------------- if (!(mPelvisp && mTorsop && mChestp && mNeckp && mHeadp && mSkullp && mHipLeftp && mHipRightp && mKneeLeftp && mKneeRightp && mAnkleLeftp && mAnkleRightp && mFootLeftp && mFootRightp && mWristLeftp && mWristRightp && mEyeLeftp && mEyeRightp)) { LL_ERRS() << "Failed to create avatar." << LL_ENDL; return; } //------------------------------------------------------------------------- // initialize the pelvis //------------------------------------------------------------------------- // SL-315 mPelvisp->setPosition( LLVector3(0.0f, 0.0f, 0.0f) ); mIsBuilt = TRUE; stop_glerror(); } BOOL LLAvatarAppearance::loadAvatar() { // LL_RECORD_BLOCK_TIME(FTM_LOAD_AVATAR); // avatar_skeleton.xml if( !buildSkeleton(sAvatarSkeletonInfo) ) { LL_ERRS() << "avatar file: buildSkeleton() failed" << LL_ENDL; return FALSE; } // avatar_lad.xml : <skeleton> if( !loadSkeletonNode() ) { LL_ERRS() << "avatar file: loadNodeSkeleton() failed" << LL_ENDL; return FALSE; } // avatar_lad.xml : <mesh> if( !loadMeshNodes() ) { LL_ERRS() << "avatar file: loadNodeMesh() failed" << LL_ENDL; return FALSE; } // avatar_lad.xml : <global_color> if( sAvatarXmlInfo->mTexSkinColorInfo ) { mTexSkinColor = new LLTexGlobalColor( this ); if( !mTexSkinColor->setInfo( sAvatarXmlInfo->mTexSkinColorInfo ) ) { LL_ERRS() << "avatar file: mTexSkinColor->setInfo() failed" << LL_ENDL; return FALSE; } } else { LL_ERRS() << "<global_color> name=\"skin_color\" not found" << LL_ENDL; return FALSE; } if( sAvatarXmlInfo->mTexHairColorInfo ) { mTexHairColor = new LLTexGlobalColor( this ); if( !mTexHairColor->setInfo( sAvatarXmlInfo->mTexHairColorInfo ) ) { LL_ERRS() << "avatar file: mTexHairColor->setInfo() failed" << LL_ENDL; return FALSE; } } else { LL_ERRS() << "<global_color> name=\"hair_color\" not found" << LL_ENDL; return FALSE; } if( sAvatarXmlInfo->mTexEyeColorInfo ) { mTexEyeColor = new LLTexGlobalColor( this ); if( !mTexEyeColor->setInfo( sAvatarXmlInfo->mTexEyeColorInfo ) ) { LL_ERRS() << "avatar file: mTexEyeColor->setInfo() failed" << LL_ENDL; return FALSE; } } else { LL_ERRS() << "<global_color> name=\"eye_color\" not found" << LL_ENDL; return FALSE; } // avatar_lad.xml : <layer_set> if (sAvatarXmlInfo->mLayerInfoList.empty()) { LL_ERRS() << "avatar file: missing <layer_set> node" << LL_ENDL; return FALSE; } if (sAvatarXmlInfo->mMorphMaskInfoList.empty()) { LL_ERRS() << "avatar file: missing <morph_masks> node" << LL_ENDL; return FALSE; } // avatar_lad.xml : <morph_masks> for (LLAvatarXmlInfo::morph_info_list_t::iterator iter = sAvatarXmlInfo->mMorphMaskInfoList.begin(); iter != sAvatarXmlInfo->mMorphMaskInfoList.end(); ++iter) { LLAvatarXmlInfo::LLAvatarMorphInfo *info = *iter; EBakedTextureIndex baked = sAvatarDictionary->findBakedByRegionName(info->mRegion); if (baked != BAKED_NUM_INDICES) { LLVisualParam* morph_param; const std::string *name = &info->mName; morph_param = getVisualParam(name->c_str()); if (morph_param) { BOOL invert = info->mInvert; addMaskedMorph(baked, morph_param, invert, info->mLayer); } } } loadLayersets(); // avatar_lad.xml : <driver_parameters> for (LLAvatarXmlInfo::driver_info_list_t::iterator iter = sAvatarXmlInfo->mDriverInfoList.begin(); iter != sAvatarXmlInfo->mDriverInfoList.end(); ++iter) { LLDriverParamInfo *info = *iter; LLDriverParam* driver_param = new LLDriverParam( this ); if (driver_param->setInfo(info)) { addVisualParam( driver_param ); driver_param->setParamLocation(isSelf() ? LOC_AV_SELF : LOC_AV_OTHER); LLVisualParam*(LLAvatarAppearance::*avatar_function)(S32)const = &LLAvatarAppearance::getVisualParam; if( !driver_param->linkDrivenParams(boost::bind(avatar_function,(LLAvatarAppearance*)this,_1 ), false)) { LL_WARNS() << "could not link driven params for avatar " << getID().asString() << " param id: " << driver_param->getID() << LL_ENDL; continue; } } else { delete driver_param; LL_WARNS() << "avatar file: driver_param->parseData() failed" << LL_ENDL; return FALSE; } } return TRUE; } //----------------------------------------------------------------------------- // loadSkeletonNode(): loads <skeleton> node from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::loadSkeletonNode () { mRoot->addChild( mSkeleton[0] ); // make meshes children before calling parent version of the function for (avatar_joint_list_t::iterator iter = mMeshLOD.begin(); iter != mMeshLOD.end(); ++iter) { LLAvatarJoint *joint = *iter; joint->mUpdateXform = FALSE; joint->setMeshesToChildren(); } mRoot->addChild(mMeshLOD[MESH_ID_HEAD]); mRoot->addChild(mMeshLOD[MESH_ID_EYELASH]); mRoot->addChild(mMeshLOD[MESH_ID_UPPER_BODY]); mRoot->addChild(mMeshLOD[MESH_ID_LOWER_BODY]); mRoot->addChild(mMeshLOD[MESH_ID_SKIRT]); mRoot->addChild(mMeshLOD[MESH_ID_HEAD]); LLAvatarJoint *skull = (LLAvatarJoint*)mRoot->findJoint("mSkull"); if (skull) { skull->addChild(mMeshLOD[MESH_ID_HAIR] ); } LLAvatarJoint *eyeL = (LLAvatarJoint*)mRoot->findJoint("mEyeLeft"); if (eyeL) { eyeL->addChild( mMeshLOD[MESH_ID_EYEBALL_LEFT] ); } LLAvatarJoint *eyeR = (LLAvatarJoint*)mRoot->findJoint("mEyeRight"); if (eyeR) { eyeR->addChild( mMeshLOD[MESH_ID_EYEBALL_RIGHT] ); } // SKELETAL DISTORTIONS { LLAvatarXmlInfo::skeletal_distortion_info_list_t::iterator iter; for (iter = sAvatarXmlInfo->mSkeletalDistortionInfoList.begin(); iter != sAvatarXmlInfo->mSkeletalDistortionInfoList.end(); ++iter) { LLPolySkeletalDistortionInfo *info = (LLPolySkeletalDistortionInfo*)*iter; LLPolySkeletalDistortion *param = new LLPolySkeletalDistortion(this); if (!param->setInfo(info)) { delete param; return FALSE; } else { addVisualParam(param); param->setParamLocation(isSelf() ? LOC_AV_SELF : LOC_AV_OTHER); } } } return TRUE; } //----------------------------------------------------------------------------- // loadMeshNodes(): loads <mesh> nodes from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::loadMeshNodes() { for (LLAvatarXmlInfo::mesh_info_list_t::const_iterator meshinfo_iter = sAvatarXmlInfo->mMeshInfoList.begin(); meshinfo_iter != sAvatarXmlInfo->mMeshInfoList.end(); ++meshinfo_iter) { const LLAvatarXmlInfo::LLAvatarMeshInfo *info = *meshinfo_iter; const std::string &type = info->mType; S32 lod = info->mLOD; LLAvatarJointMesh* mesh = NULL; U8 mesh_id = 0; BOOL found_mesh_id = FALSE; /* if (type == "hairMesh") switch(lod) case 0: mesh = &mHairMesh0; */ for (LLAvatarAppearanceDictionary::MeshEntries::const_iterator mesh_iter = sAvatarDictionary->getMeshEntries().begin(); mesh_iter != sAvatarDictionary->getMeshEntries().end(); ++mesh_iter) { const EMeshIndex mesh_index = mesh_iter->first; const LLAvatarAppearanceDictionary::MeshEntry *mesh_dict = mesh_iter->second; if (type.compare(mesh_dict->mName) == 0) { mesh_id = mesh_index; found_mesh_id = TRUE; break; } } if (found_mesh_id) { if (lod < (S32)mMeshLOD[mesh_id]->mMeshParts.size()) { mesh = mMeshLOD[mesh_id]->mMeshParts[lod]; } else { LL_WARNS() << "Avatar file: <mesh> has invalid lod setting " << lod << LL_ENDL; return FALSE; } } else { LL_WARNS() << "Ignoring unrecognized mesh type: " << type << LL_ENDL; return FALSE; } // LL_INFOS() << "Parsing mesh data for " << type << "..." << LL_ENDL; // If this isn't set to white (1.0), avatars will *ALWAYS* be darker than their surroundings. // Do not touch!!! mesh->setColor( LLColor4::white ); LLPolyMesh *poly_mesh = NULL; if (!info->mReferenceMeshName.empty()) { polymesh_map_t::const_iterator polymesh_iter = mPolyMeshes.find(info->mReferenceMeshName); if (polymesh_iter != mPolyMeshes.end()) { poly_mesh = LLPolyMesh::getMesh(info->mMeshFileName, polymesh_iter->second); poly_mesh->setAvatar(this); } else { // This should never happen LL_WARNS("Avatar") << "Could not find avatar mesh: " << info->mReferenceMeshName << LL_ENDL; return FALSE; } } else { poly_mesh = LLPolyMesh::getMesh(info->mMeshFileName); poly_mesh->setAvatar(this); } if( !poly_mesh ) { LL_WARNS() << "Failed to load mesh of type " << type << LL_ENDL; return FALSE; } // Multimap insert mPolyMeshes.insert(std::make_pair(info->mMeshFileName, poly_mesh)); mesh->setMesh( poly_mesh ); mesh->setLOD( info->mMinPixelArea ); for (LLAvatarXmlInfo::LLAvatarMeshInfo::morph_info_list_t::const_iterator xmlinfo_iter = info->mPolyMorphTargetInfoList.begin(); xmlinfo_iter != info->mPolyMorphTargetInfoList.end(); ++xmlinfo_iter) { const LLAvatarXmlInfo::LLAvatarMeshInfo::morph_info_pair_t *info_pair = &(*xmlinfo_iter); LLPolyMorphTarget *param = new LLPolyMorphTarget(mesh->getMesh()); if (!param->setInfo((LLPolyMorphTargetInfo*)info_pair->first)) { delete param; return FALSE; } else { if (info_pair->second) { addSharedVisualParam(param); param->setParamLocation(isSelf() ? LOC_AV_SELF : LOC_AV_OTHER); } else { addVisualParam(param); param->setParamLocation(isSelf() ? LOC_AV_SELF : LOC_AV_OTHER); } } } } return TRUE; } //----------------------------------------------------------------------------- // loadLayerSets() //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::loadLayersets() { BOOL success = TRUE; for (LLAvatarXmlInfo::layer_info_list_t::const_iterator layerset_iter = sAvatarXmlInfo->mLayerInfoList.begin(); layerset_iter != sAvatarXmlInfo->mLayerInfoList.end(); ++layerset_iter) { LLTexLayerSetInfo *layerset_info = *layerset_iter; if (isSelf()) { // Construct a layerset for each one specified in avatar_lad.xml and initialize it as such. LLTexLayerSet* layer_set = createTexLayerSet(); if (!layer_set->setInfo(layerset_info)) { stop_glerror(); delete layer_set; LL_WARNS() << "avatar file: layer_set->setInfo() failed" << LL_ENDL; return FALSE; } // scan baked textures and associate the layerset with the appropriate one EBakedTextureIndex baked_index = BAKED_NUM_INDICES; for (LLAvatarAppearanceDictionary::BakedTextures::const_iterator baked_iter = sAvatarDictionary->getBakedTextures().begin(); baked_iter != sAvatarDictionary->getBakedTextures().end(); ++baked_iter) { const LLAvatarAppearanceDictionary::BakedEntry *baked_dict = baked_iter->second; if (layer_set->isBodyRegion(baked_dict->mName)) { baked_index = baked_iter->first; // ensure both structures are aware of each other mBakedTextureDatas[baked_index].mTexLayerSet = layer_set; layer_set->setBakedTexIndex(baked_index); break; } } // if no baked texture was found, warn and cleanup if (baked_index == BAKED_NUM_INDICES) { LL_WARNS() << "<layer_set> has invalid body_region attribute" << LL_ENDL; delete layer_set; return FALSE; } // scan morph masks and let any affected layers know they have an associated morph for (LLAvatarAppearance::morph_list_t::const_iterator morph_iter = mBakedTextureDatas[baked_index].mMaskedMorphs.begin(); morph_iter != mBakedTextureDatas[baked_index].mMaskedMorphs.end(); ++morph_iter) { LLMaskedMorph *morph = *morph_iter; LLTexLayerInterface* layer = layer_set->findLayerByName(morph->mLayer); if (layer) { layer->setHasMorph(TRUE); } else { LL_WARNS() << "Could not find layer named " << morph->mLayer << " to set morph flag" << LL_ENDL; success = FALSE; } } } else // !isSelf() { // Construct a layerset for each one specified in avatar_lad.xml and initialize it as such. LLTexLayerSetInfo *layerset_info = *layerset_iter; layerset_info->createVisualParams(this); } } return success; } //----------------------------------------------------------------------------- // getCharacterJoint() //----------------------------------------------------------------------------- LLJoint *LLAvatarAppearance::getCharacterJoint( U32 num ) { if ((S32)num >= mSkeleton.size() || (S32)num < 0) { return NULL; } if (!mSkeleton[num]) { mSkeleton[num] = createAvatarJoint(); } return mSkeleton[num]; } //----------------------------------------------------------------------------- // getVolumePos() //----------------------------------------------------------------------------- LLVector3 LLAvatarAppearance::getVolumePos(S32 joint_index, LLVector3& volume_offset) { if (joint_index > mNumCollisionVolumes) { return LLVector3::zero; } return mCollisionVolumes[joint_index].getVolumePos(volume_offset); } //----------------------------------------------------------------------------- // findCollisionVolume() //----------------------------------------------------------------------------- LLJoint* LLAvatarAppearance::findCollisionVolume(S32 volume_id) { if ((volume_id < 0) || (volume_id >= mNumCollisionVolumes)) { return NULL; } return &mCollisionVolumes[volume_id]; } //----------------------------------------------------------------------------- // findCollisionVolume() //----------------------------------------------------------------------------- S32 LLAvatarAppearance::getCollisionVolumeID(std::string &name) { for (S32 i = 0; i < mNumCollisionVolumes; i++) { if (mCollisionVolumes[i].getName() == name) { return i; } } return -1; } //----------------------------------------------------------------------------- // LLAvatarAppearance::getHeadMesh() //----------------------------------------------------------------------------- LLPolyMesh* LLAvatarAppearance::getHeadMesh() { return mMeshLOD[MESH_ID_HEAD]->mMeshParts[0]->getMesh(); } //----------------------------------------------------------------------------- // LLAvatarAppearance::getUpperBodyMesh() //----------------------------------------------------------------------------- LLPolyMesh* LLAvatarAppearance::getUpperBodyMesh() { return mMeshLOD[MESH_ID_UPPER_BODY]->mMeshParts[0]->getMesh(); } // virtual BOOL LLAvatarAppearance::isValid() const { // This should only be called on ourself. if (!isSelf()) { LL_ERRS() << "Called LLAvatarAppearance::isValid() on when isSelf() == false" << LL_ENDL; } return TRUE; } // adds a morph mask to the appropriate baked texture structure void LLAvatarAppearance::addMaskedMorph(EBakedTextureIndex index, LLVisualParam* morph_target, BOOL invert, std::string layer) { if (index < BAKED_NUM_INDICES) { LLMaskedMorph *morph = new LLMaskedMorph(morph_target, invert, layer); mBakedTextureDatas[index].mMaskedMorphs.push_front(morph); } } //static BOOL LLAvatarAppearance::teToColorParams( ETextureIndex te, U32 *param_name ) { switch( te ) { case TEX_UPPER_SHIRT: param_name[0] = 803; //"shirt_red"; param_name[1] = 804; //"shirt_green"; param_name[2] = 805; //"shirt_blue"; break; case TEX_LOWER_PANTS: param_name[0] = 806; //"pants_red"; param_name[1] = 807; //"pants_green"; param_name[2] = 808; //"pants_blue"; break; case TEX_LOWER_SHOES: param_name[0] = 812; //"shoes_red"; param_name[1] = 813; //"shoes_green"; param_name[2] = 817; //"shoes_blue"; break; case TEX_LOWER_SOCKS: param_name[0] = 818; //"socks_red"; param_name[1] = 819; //"socks_green"; param_name[2] = 820; //"socks_blue"; break; case TEX_UPPER_JACKET: case TEX_LOWER_JACKET: param_name[0] = 834; //"jacket_red"; param_name[1] = 835; //"jacket_green"; param_name[2] = 836; //"jacket_blue"; break; case TEX_UPPER_GLOVES: param_name[0] = 827; //"gloves_red"; param_name[1] = 829; //"gloves_green"; param_name[2] = 830; //"gloves_blue"; break; case TEX_UPPER_UNDERSHIRT: param_name[0] = 821; //"undershirt_red"; param_name[1] = 822; //"undershirt_green"; param_name[2] = 823; //"undershirt_blue"; break; case TEX_LOWER_UNDERPANTS: param_name[0] = 824; //"underpants_red"; param_name[1] = 825; //"underpants_green"; param_name[2] = 826; //"underpants_blue"; break; case TEX_SKIRT: param_name[0] = 921; //"skirt_red"; param_name[1] = 922; //"skirt_green"; param_name[2] = 923; //"skirt_blue"; break; case TEX_HEAD_TATTOO: case TEX_LOWER_TATTOO: case TEX_UPPER_TATTOO: param_name[0] = 1071; //"tattoo_red"; param_name[1] = 1072; //"tattoo_green"; param_name[2] = 1073; //"tattoo_blue"; break; case TEX_HEAD_UNIVERSAL_TATTOO: case TEX_UPPER_UNIVERSAL_TATTOO: case TEX_LOWER_UNIVERSAL_TATTOO: case TEX_SKIRT_TATTOO: case TEX_HAIR_TATTOO: case TEX_EYES_TATTOO: case TEX_LEFT_ARM_TATTOO: case TEX_LEFT_LEG_TATTOO: case TEX_AUX1_TATTOO: case TEX_AUX2_TATTOO: case TEX_AUX3_TATTOO: param_name[0] = 1238; //"tattoo_universal_red"; param_name[1] = 1239; //"tattoo_universal_green"; param_name[2] = 1240; //"tattoo_universal_blue"; break; default: llassert(0); return FALSE; } return TRUE; } // <FS:Ansariel> [Legacy Bake] //void LLAvatarAppearance::setClothesColor( ETextureIndex te, const LLColor4& new_color) void LLAvatarAppearance::setClothesColor( ETextureIndex te, const LLColor4& new_color, BOOL upload_bake) // </FS:Ansariel> [Legacy Bake] { U32 param_name[3]; if( teToColorParams( te, param_name ) ) { // <FS:Ansariel> [Legacy Bake] //setVisualParamWeight( param_name[0], new_color.mV[VX]); //setVisualParamWeight( param_name[1], new_color.mV[VY]); //setVisualParamWeight( param_name[2], new_color.mV[VZ]); setVisualParamWeight( param_name[0], new_color.mV[VX], upload_bake); setVisualParamWeight( param_name[1], new_color.mV[VY], upload_bake); setVisualParamWeight( param_name[2], new_color.mV[VZ], upload_bake); // </FS:Ansariel> [Legacy Bake] } } LLColor4 LLAvatarAppearance::getClothesColor( ETextureIndex te ) { LLColor4 color; U32 param_name[3]; if( teToColorParams( te, param_name ) ) { color.mV[VX] = getVisualParamWeight( param_name[0] ); color.mV[VY] = getVisualParamWeight( param_name[1] ); color.mV[VZ] = getVisualParamWeight( param_name[2] ); } return color; } // static LLColor4 LLAvatarAppearance::getDummyColor() { return DUMMY_COLOR; } LLColor4 LLAvatarAppearance::getGlobalColor( const std::string& color_name ) const { if (color_name=="skin_color" && mTexSkinColor) { return mTexSkinColor->getColor(); } else if(color_name=="hair_color" && mTexHairColor) { return mTexHairColor->getColor(); } if(color_name=="eye_color" && mTexEyeColor) { return mTexEyeColor->getColor(); } else { // return LLColor4( .5f, .5f, .5f, .5f ); return LLColor4( 0.f, 1.f, 1.f, 1.f ); // good debugging color } } // Unlike most wearable functions, this works for both self and other. // virtual BOOL LLAvatarAppearance::isWearingWearableType(LLWearableType::EType type) const { return mWearableData->getWearableCount(type) > 0; } LLTexLayerSet* LLAvatarAppearance::getAvatarLayerSet(EBakedTextureIndex baked_index) const { /* switch(index) case TEX_HEAD_BAKED: case TEX_HEAD_BODYPAINT: return mHeadLayerSet; */ return mBakedTextureDatas[baked_index].mTexLayerSet; } //----------------------------------------------------------------------------- // allocateCollisionVolumes() //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::allocateCollisionVolumes( U32 num ) { if (mNumCollisionVolumes !=num) { delete_and_clear_array(mCollisionVolumes); mNumCollisionVolumes = 0; mCollisionVolumes = new(std::nothrow) LLAvatarJointCollisionVolume[num]; if (!mCollisionVolumes) { LL_WARNS() << "Failed to allocate collision volumes" << LL_ENDL; return FALSE; } mNumCollisionVolumes = num; } return TRUE; } //----------------------------------------------------------------------------- // LLAvatarBoneInfo::parseXml() //----------------------------------------------------------------------------- BOOL LLAvatarBoneInfo::parseXml(LLXmlTreeNode* node) { if (node->hasName("bone")) { mIsJoint = TRUE; static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name"); if (!node->getFastAttributeString(name_string, mName)) { LL_WARNS() << "Bone without name" << LL_ENDL; return FALSE; } static LLStdStringHandle aliases_string = LLXmlTree::addAttributeString("aliases"); node->getFastAttributeString(aliases_string, mAliases ); //Aliases are not required. } else if (node->hasName("collision_volume")) { mIsJoint = FALSE; static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name"); if (!node->getFastAttributeString(name_string, mName)) { mName = "Collision Volume"; } } else { LL_WARNS() << "Invalid node " << node->getName() << LL_ENDL; return FALSE; } static LLStdStringHandle pos_string = LLXmlTree::addAttributeString("pos"); if (!node->getFastAttributeVector3(pos_string, mPos)) { LL_WARNS() << "Bone without position" << LL_ENDL; return FALSE; } static LLStdStringHandle rot_string = LLXmlTree::addAttributeString("rot"); if (!node->getFastAttributeVector3(rot_string, mRot)) { LL_WARNS() << "Bone without rotation" << LL_ENDL; return FALSE; } static LLStdStringHandle scale_string = LLXmlTree::addAttributeString("scale"); if (!node->getFastAttributeVector3(scale_string, mScale)) { LL_WARNS() << "Bone without scale" << LL_ENDL; return FALSE; } static LLStdStringHandle end_string = LLXmlTree::addAttributeString("end"); if (!node->getFastAttributeVector3(end_string, mEnd)) { LL_WARNS() << "Bone without end " << mName << LL_ENDL; mEnd = LLVector3(0.0f, 0.0f, 0.0f); } static LLStdStringHandle support_string = LLXmlTree::addAttributeString("support"); if (!node->getFastAttributeString(support_string,mSupport)) { LL_WARNS() << "Bone without support " << mName << LL_ENDL; mSupport = "base"; } if (mIsJoint) { static LLStdStringHandle pivot_string = LLXmlTree::addAttributeString("pivot"); if (!node->getFastAttributeVector3(pivot_string, mPivot)) { LL_WARNS() << "Bone without pivot" << LL_ENDL; return FALSE; } } // parse children LLXmlTreeNode* child; for( child = node->getFirstChild(); child; child = node->getNextChild() ) { LLAvatarBoneInfo *child_info = new LLAvatarBoneInfo; if (!child_info->parseXml(child)) { delete child_info; return FALSE; } mChildren.push_back(child_info); } return TRUE; } //----------------------------------------------------------------------------- // LLAvatarSkeletonInfo::parseXml() //----------------------------------------------------------------------------- BOOL LLAvatarSkeletonInfo::parseXml(LLXmlTreeNode* node) { static LLStdStringHandle num_bones_string = LLXmlTree::addAttributeString("num_bones"); if (!node->getFastAttributeS32(num_bones_string, mNumBones)) { LL_WARNS() << "Couldn't find number of bones." << LL_ENDL; return FALSE; } static LLStdStringHandle num_collision_volumes_string = LLXmlTree::addAttributeString("num_collision_volumes"); node->getFastAttributeS32(num_collision_volumes_string, mNumCollisionVolumes); LLXmlTreeNode* child; for( child = node->getFirstChild(); child; child = node->getNextChild() ) { LLAvatarBoneInfo *info = new LLAvatarBoneInfo; if (!info->parseXml(child)) { delete info; LL_WARNS() << "Error parsing bone in skeleton file" << LL_ENDL; return FALSE; } mBoneInfoList.push_back(info); } return TRUE; } //Make aliases for joint and push to map. void LLAvatarAppearance::makeJointAliases(LLAvatarBoneInfo *bone_info) { if (! bone_info->mIsJoint ) { return; } std::string bone_name = bone_info->mName; mJointAliasMap[bone_name] = bone_name; //Actual name is a valid alias. std::string aliases = bone_info->mAliases; boost::char_separator<char> sep(" "); boost::tokenizer<boost::char_separator<char> > tok(aliases, sep); for(boost::tokenizer<boost::char_separator<char> >::iterator i = tok.begin(); i != tok.end(); ++i) { if ( mJointAliasMap.find(*i) != mJointAliasMap.end() ) { LL_WARNS() << "avatar skeleton: Joint alias \"" << *i << "\" remapped from " << mJointAliasMap[*i] << " to " << bone_name << LL_ENDL; } mJointAliasMap[*i] = bone_name; } for (LLAvatarBoneInfo* bone : bone_info->mChildren) { makeJointAliases(bone); } } const LLAvatarAppearance::joint_alias_map_t& LLAvatarAppearance::getJointAliases () { LLAvatarAppearance::joint_alias_map_t alias_map; if (mJointAliasMap.empty()) { LLAvatarSkeletonInfo::bone_info_list_t::const_iterator iter; for (iter = sAvatarSkeletonInfo->mBoneInfoList.begin(); iter != sAvatarSkeletonInfo->mBoneInfoList.end(); ++iter) { //LLAvatarBoneInfo *bone_info = *iter; makeJointAliases( *iter ); } LLAvatarXmlInfo::attachment_info_list_t::iterator attach_iter; for (attach_iter = sAvatarXmlInfo->mAttachmentInfoList.begin(); attach_iter != sAvatarXmlInfo->mAttachmentInfoList.end(); ++attach_iter) { LLAvatarXmlInfo::LLAvatarAttachmentInfo *info = *attach_iter; std::string bone_name = info->mName; // Also accept the name with spaces substituted with // underscores. This gives a mechanism for referencing such joints // in daes, which don't allow spaces. std::string sub_space_to_underscore = bone_name; LLStringUtil::replaceChar(sub_space_to_underscore, ' ', '_'); if (sub_space_to_underscore != bone_name) { mJointAliasMap[sub_space_to_underscore] = bone_name; } } } return mJointAliasMap; } //----------------------------------------------------------------------------- // parseXmlSkeletonNode(): parses <skeleton> nodes from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::LLAvatarXmlInfo::parseXmlSkeletonNode(LLXmlTreeNode* root) { LLXmlTreeNode* node = root->getChildByName( "skeleton" ); if( !node ) { LL_WARNS() << "avatar file: missing <skeleton>" << LL_ENDL; return FALSE; } LLXmlTreeNode* child; // SKELETON DISTORTIONS for (child = node->getChildByName( "param" ); child; child = node->getNextNamedChild()) { if (!child->getChildByName("param_skeleton")) { if (child->getChildByName("param_morph")) { LL_WARNS() << "Can't specify morph param in skeleton definition." << LL_ENDL; } else { LL_WARNS() << "Unknown param type." << LL_ENDL; } return FALSE; } LLPolySkeletalDistortionInfo *info = new LLPolySkeletalDistortionInfo; if (!info->parseXml(child)) { delete info; return FALSE; } mSkeletalDistortionInfoList.push_back(info); } // ATTACHMENT POINTS for (child = node->getChildByName( "attachment_point" ); child; child = node->getNextNamedChild()) { LLAvatarAttachmentInfo* info = new LLAvatarAttachmentInfo(); static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name"); if (!child->getFastAttributeString(name_string, info->mName)) { LL_WARNS() << "No name supplied for attachment point." << LL_ENDL; delete info; return FALSE; } static LLStdStringHandle joint_string = LLXmlTree::addAttributeString("joint"); if (!child->getFastAttributeString(joint_string, info->mJointName)) { LL_WARNS() << "No bone declared in attachment point " << info->mName << LL_ENDL; delete info; return FALSE; } static LLStdStringHandle position_string = LLXmlTree::addAttributeString("position"); if (child->getFastAttributeVector3(position_string, info->mPosition)) { info->mHasPosition = TRUE; } static LLStdStringHandle rotation_string = LLXmlTree::addAttributeString("rotation"); if (child->getFastAttributeVector3(rotation_string, info->mRotationEuler)) { info->mHasRotation = TRUE; } static LLStdStringHandle group_string = LLXmlTree::addAttributeString("group"); if (child->getFastAttributeS32(group_string, info->mGroup)) { if (info->mGroup == -1) info->mGroup = -1111; // -1 = none parsed, < -1 = bad value } static LLStdStringHandle id_string = LLXmlTree::addAttributeString("id"); if (!child->getFastAttributeS32(id_string, info->mAttachmentID)) { LL_WARNS() << "No id supplied for attachment point " << info->mName << LL_ENDL; delete info; return FALSE; } static LLStdStringHandle slot_string = LLXmlTree::addAttributeString("pie_slice"); child->getFastAttributeS32(slot_string, info->mPieMenuSlice); static LLStdStringHandle visible_in_first_person_string = LLXmlTree::addAttributeString("visible_in_first_person"); child->getFastAttributeBOOL(visible_in_first_person_string, info->mVisibleFirstPerson); static LLStdStringHandle hud_attachment_string = LLXmlTree::addAttributeString("hud"); child->getFastAttributeBOOL(hud_attachment_string, info->mIsHUDAttachment); mAttachmentInfoList.push_back(info); } return TRUE; } //----------------------------------------------------------------------------- // parseXmlMeshNodes(): parses <mesh> nodes from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::LLAvatarXmlInfo::parseXmlMeshNodes(LLXmlTreeNode* root) { for (LLXmlTreeNode* node = root->getChildByName( "mesh" ); node; node = root->getNextNamedChild()) { LLAvatarMeshInfo *info = new LLAvatarMeshInfo; // attribute: type static LLStdStringHandle type_string = LLXmlTree::addAttributeString("type"); if( !node->getFastAttributeString( type_string, info->mType ) ) { LL_WARNS() << "Avatar file: <mesh> is missing type attribute. Ignoring element. " << LL_ENDL; delete info; return FALSE; // Ignore this element } static LLStdStringHandle lod_string = LLXmlTree::addAttributeString("lod"); if (!node->getFastAttributeS32( lod_string, info->mLOD )) { LL_WARNS() << "Avatar file: <mesh> is missing lod attribute. Ignoring element. " << LL_ENDL; delete info; return FALSE; // Ignore this element } static LLStdStringHandle file_name_string = LLXmlTree::addAttributeString("file_name"); if( !node->getFastAttributeString( file_name_string, info->mMeshFileName ) ) { LL_WARNS() << "Avatar file: <mesh> is missing file_name attribute. Ignoring: " << info->mType << LL_ENDL; delete info; return FALSE; // Ignore this element } static LLStdStringHandle reference_string = LLXmlTree::addAttributeString("reference"); node->getFastAttributeString( reference_string, info->mReferenceMeshName ); // attribute: min_pixel_area static LLStdStringHandle min_pixel_area_string = LLXmlTree::addAttributeString("min_pixel_area"); static LLStdStringHandle min_pixel_width_string = LLXmlTree::addAttributeString("min_pixel_width"); if (!node->getFastAttributeF32( min_pixel_area_string, info->mMinPixelArea )) { F32 min_pixel_area = 0.1f; if (node->getFastAttributeF32( min_pixel_width_string, min_pixel_area )) { // this is square root of pixel area (sensible to use linear space in defining lods) min_pixel_area = min_pixel_area * min_pixel_area; } info->mMinPixelArea = min_pixel_area; } // Parse visual params for this node only if we haven't already for (LLXmlTreeNode* child = node->getChildByName( "param" ); child; child = node->getNextNamedChild()) { if (!child->getChildByName("param_morph")) { if (child->getChildByName("param_skeleton")) { LL_WARNS() << "Can't specify skeleton param in a mesh definition." << LL_ENDL; } else { LL_WARNS() << "Unknown param type." << LL_ENDL; } return FALSE; } LLPolyMorphTargetInfo *morphinfo = new LLPolyMorphTargetInfo(); if (!morphinfo->parseXml(child)) { delete morphinfo; delete info; return -1; } BOOL shared = FALSE; static LLStdStringHandle shared_string = LLXmlTree::addAttributeString("shared"); child->getFastAttributeBOOL(shared_string, shared); info->mPolyMorphTargetInfoList.push_back(LLAvatarMeshInfo::morph_info_pair_t(morphinfo, shared)); } mMeshInfoList.push_back(info); } return TRUE; } //----------------------------------------------------------------------------- // parseXmlColorNodes(): parses <global_color> nodes from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::LLAvatarXmlInfo::parseXmlColorNodes(LLXmlTreeNode* root) { for (LLXmlTreeNode* color_node = root->getChildByName( "global_color" ); color_node; color_node = root->getNextNamedChild()) { std::string global_color_name; static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name"); if (color_node->getFastAttributeString( name_string, global_color_name ) ) { if( global_color_name == "skin_color" ) { if (mTexSkinColorInfo) { LL_WARNS() << "avatar file: multiple instances of skin_color" << LL_ENDL; return FALSE; } mTexSkinColorInfo = new LLTexGlobalColorInfo; if( !mTexSkinColorInfo->parseXml( color_node ) ) { delete_and_clear(mTexSkinColorInfo); LL_WARNS() << "avatar file: mTexSkinColor->parseXml() failed" << LL_ENDL; return FALSE; } } else if( global_color_name == "hair_color" ) { if (mTexHairColorInfo) { LL_WARNS() << "avatar file: multiple instances of hair_color" << LL_ENDL; return FALSE; } mTexHairColorInfo = new LLTexGlobalColorInfo; if( !mTexHairColorInfo->parseXml( color_node ) ) { delete_and_clear(mTexHairColorInfo); LL_WARNS() << "avatar file: mTexHairColor->parseXml() failed" << LL_ENDL; return FALSE; } } else if( global_color_name == "eye_color" ) { if (mTexEyeColorInfo) { LL_WARNS() << "avatar file: multiple instances of eye_color" << LL_ENDL; return FALSE; } mTexEyeColorInfo = new LLTexGlobalColorInfo; if( !mTexEyeColorInfo->parseXml( color_node ) ) { LL_WARNS() << "avatar file: mTexEyeColor->parseXml() failed" << LL_ENDL; return FALSE; } } } } return TRUE; } //----------------------------------------------------------------------------- // parseXmlLayerNodes(): parses <layer_set> nodes from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::LLAvatarXmlInfo::parseXmlLayerNodes(LLXmlTreeNode* root) { for (LLXmlTreeNode* layer_node = root->getChildByName( "layer_set" ); layer_node; layer_node = root->getNextNamedChild()) { LLTexLayerSetInfo* layer_info = new LLTexLayerSetInfo(); if( layer_info->parseXml( layer_node ) ) { mLayerInfoList.push_back(layer_info); } else { delete layer_info; LL_WARNS() << "avatar file: layer_set->parseXml() failed" << LL_ENDL; return FALSE; } } return TRUE; } //----------------------------------------------------------------------------- // parseXmlDriverNodes(): parses <driver_parameters> nodes from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::LLAvatarXmlInfo::parseXmlDriverNodes(LLXmlTreeNode* root) { LLXmlTreeNode* driver = root->getChildByName( "driver_parameters" ); if( driver ) { for (LLXmlTreeNode* grand_child = driver->getChildByName( "param" ); grand_child; grand_child = driver->getNextNamedChild()) { if( grand_child->getChildByName( "param_driver" ) ) { LLDriverParamInfo* driver_info = new LLDriverParamInfo(); if( driver_info->parseXml( grand_child ) ) { mDriverInfoList.push_back(driver_info); } else { delete driver_info; LL_WARNS() << "avatar file: driver_param->parseXml() failed" << LL_ENDL; return FALSE; } } } } return TRUE; } //----------------------------------------------------------------------------- // parseXmlDriverNodes(): parses <driver_parameters> nodes from XML tree //----------------------------------------------------------------------------- BOOL LLAvatarAppearance::LLAvatarXmlInfo::parseXmlMorphNodes(LLXmlTreeNode* root) { LLXmlTreeNode* masks = root->getChildByName( "morph_masks" ); if( !masks ) { return FALSE; } for (LLXmlTreeNode* grand_child = masks->getChildByName( "mask" ); grand_child; grand_child = masks->getNextNamedChild()) { LLAvatarMorphInfo* info = new LLAvatarMorphInfo(); static LLStdStringHandle name_string = LLXmlTree::addAttributeString("morph_name"); if (!grand_child->getFastAttributeString(name_string, info->mName)) { LL_WARNS() << "No name supplied for morph mask." << LL_ENDL; delete info; return FALSE; } static LLStdStringHandle region_string = LLXmlTree::addAttributeString("body_region"); if (!grand_child->getFastAttributeString(region_string, info->mRegion)) { LL_WARNS() << "No region supplied for morph mask." << LL_ENDL; delete info; return FALSE; } static LLStdStringHandle layer_string = LLXmlTree::addAttributeString("layer"); if (!grand_child->getFastAttributeString(layer_string, info->mLayer)) { LL_WARNS() << "No layer supplied for morph mask." << LL_ENDL; delete info; return FALSE; } // optional parameter. don't throw a warning if not present. static LLStdStringHandle invert_string = LLXmlTree::addAttributeString("invert"); grand_child->getFastAttributeBOOL(invert_string, info->mInvert); mMorphMaskInfoList.push_back(info); } return TRUE; } //virtual LLAvatarAppearance::LLMaskedMorph::LLMaskedMorph(LLVisualParam *morph_target, BOOL invert, std::string layer) : mMorphTarget(morph_target), mInvert(invert), mLayer(layer) { LLPolyMorphTarget *target = dynamic_cast<LLPolyMorphTarget*>(morph_target); if (target) { target->addPendingMorphMask(); } } // <FS:Ansariel> Get attachment point name from ID //static std::string LLAvatarAppearance::getAttachmentPointName(S32 attachmentPointId) { for (auto attachmentPoint : sAvatarXmlInfo->mAttachmentInfoList) { if (attachmentPoint->mAttachmentID == attachmentPointId) { return attachmentPoint->mName; } } return std::string(); } // </FS:Ansariel>
30.993691
146
0.627248
[ "mesh", "shape", "vector" ]
d1fffb1451f5dace5bf8dc695916cf45315637a5
12,618
cpp
C++
src/solvers/gecode/procedures/commonprocedures.cpp
matsc-at-sics-se/unison
8d23b73aaf8f3af5c4d86f26e0e4432d70bab564
[ "BSD-3-Clause" ]
6
2018-03-01T19:12:07.000Z
2018-09-10T15:52:14.000Z
src/solvers/gecode/procedures/commonprocedures.cpp
matsc-at-sics-se/unison
8d23b73aaf8f3af5c4d86f26e0e4432d70bab564
[ "BSD-3-Clause" ]
56
2018-02-26T16:44:15.000Z
2019-02-23T17:07:32.000Z
src/solvers/gecode/procedures/commonprocedures.cpp
matsc-at-sics-se/unison
8d23b73aaf8f3af5c4d86f26e0e4432d70bab564
[ "BSD-3-Clause" ]
null
null
null
/* * Main authors: * Mats Carlsson <mats.carlsson@ri.se> * Roberto Castaneda Lozano <roberto.castaneda@ri.se> * * This file is part of Unison, see http://unison-code.github.io * * Copyright (c) 2016, RISE SICS AB * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "commonprocedures.hpp" void IterationState::next(ModelOptions * options) { if (cf || !options->global_connection_iterations()) { a += options->step_aggressiveness(); cf = false; } else { cf = true; } } bool IterationState::stop(ModelOptions * options) { return a > options->final_aggressiveness(); } ostream& operator<<(ostream& os, const IterationState & state) { os << state.a << (state.cf ? "(c)" : ""); return os; } Search::Stop * new_stop(double limit, ModelOptions * options) { if (options->limit_unit() == "time") return new Search::TimeStop(limit); else if (options->limit_unit() == "fails") return new Search::FailStop(limit); else GECODE_NEVER; return NULL; } vector<block> sorted_blocks(Parameters * input, map<block, SolverResult> & latest_result) { vector<block> blocks(input->B); std::stable_sort(blocks.begin(), blocks.end(), [&] (const block b1, const block b2) -> bool { return make_tuple(score(latest_result[b1]), input->freq[b1]) > make_tuple(score(latest_result[b2]), input->freq[b2]); }); return blocks; } int score(SolverResult r) { switch(r) { case OPTIMAL_SOLUTION: case CACHED_SOLUTION: return 0; case UNKNOWN: return 1; case SOME_SOLUTION: return 2; case LIMIT: return 3; case UNSATISFIABLE: return 4; case SHAVING_FAILURE: return 5; default: GECODE_NEVER; } } vector<InstructionAssignment> shave_instructions(Model * base, Search::Stop * stop, Search::Statistics & stats) { Search::Options dummyOpts; vector<InstructionAssignment> forbidden; for (operation o : base->O()) { for (IntVarValues iit(base->i(o)); iit(); ++iit) { int ii = iit.val(); Model * g = (Model*) base->clone(); g->assign_instruction(o, ii); if (g->status() == SS_FAILED) forbidden.push_back(make_pair(o, ii)); stats.fail++; delete g; if (stop->stop(stats, dummyOpts)) break; } if (stop->stop(stats, dummyOpts)) break; } return forbidden; } Gecode::SpaceStatus status_lb(GlobalModel * base) { SpaceStatus ss = base->status(); emit_lower_bound(base); return ss; } void emit_lower_bound(const GlobalModel * base, bool proven) { if (base->options->lower_bound_file().empty()) return; vector<int> lbs; for (unsigned int n = 0; n < base->input->N; n++) { lbs.push_back(proven ? -1 : base->cost()[n].min()); } ofstream fout; fout.open(base->options->lower_bound_file()); fout << "{\"lower_bound\":" << show(lbs, ", ", "", "[]") << "}" << endl; fout.close(); } LocalModel * make_local(const GlobalModel * gs, block b) { return make_local(gs, b, gs->ipl); } LocalModel * make_local(const GlobalModel * gs, block b, IntPropLevel p_ipl) { return new LocalModel(gs->input, gs->options, p_ipl, gs, b); } bool infinite_register_atom(Parameters & input, register_atom ra) { for (register_space rs : input.RS) if (input.infinite[rs] && ra >= input.range[rs][0] && ra <= input.range[rs][1]) return true; return false; } // Idea: values v1, v2 are symmetric iff they are _covered_ by identical sets of register classes + preassignments // Value v is covered by register class rc of width w iff (e <= v < e+w) where e is in rc // Value v is preassignment p:ra of width w iff (ra <= v < ra+w) // Preassigned (kill) operands and pressigned callee-saved (in)/(out) operands are clumped per operation // All other preassignments are counted individually // Temps defined preassigned are not subject to symmetry breaking // Temps defined by reassignment, in (pack), or in exrelated operands, are not subject to symmetry breaking // Temps defined by callee-saved-load are not subject to symmetry breaking, maybe because they get reloaded in reverse order // Temps not defined by (linear) or (copy) are not subject to symmetry breaking vector<PresolverValuePrecedeChain> value_precede_chains(Parameters & input, Model * m, bool global, block b) { vector<PresolverValuePrecedeChain> chains; map<vector<temporary>,vector<vector<register_atom>>> SymChainsOfTemps; map<register_atom,vector<register_class>> CoveringClassesOfReg; set<temporary> PreT; set<operand> PreP; vector<block> B(global ? input.B : vector<block>({b})); vector<temporary> T(global ? input.T : input.tmp[b]); // collect register classes and their sizes map<register_class,int> C2W; for (block b : B) { for (operation o : input.ops[b]) { for (unsigned int ii = 0; ii < input.instructions[o].size(); ii++) { for (unsigned pi = 0; pi < input.operands[o].size(); pi++) { operand p = input.operands[o][pi]; if (input.instructions[o][ii] != NULL_INSTRUCTION) { register_class rc = input.rclass[o][ii][pi]; C2W[rc] = input.operand_width[p]; } } } } } for(const pair<register_class,int>& CW : C2W) { register_class C = CW.first; int w = CW.second; vector<register_atom> ras = input.atoms[C]; if (!infinite_register_atom(input, max_of(ras))) for (register_atom r : ras) for (int d=0; d<w; d++) CoveringClassesOfReg[r+d].push_back(C); } register_class C = input.atoms.size(); // more register classes from preassignments map<operation,vector<vector<int>>> defer; for(const vector<int>& pr : input.preassign) { operand p = pr[0]; register_atom r = pr[1]; if (global || input.pb[p] == b) { temporary t = input.temps[p][0]; if (t != NULL_TEMPORARY) { vector<operand> us = input.users[t]; operation o = input.oper[p]; int ty = input.type[o]; PreP.insert(p); if (!input.use[p]) PreT.insert(t); if (!input.use[p] && us.size() == 1 && input.type[input.oper[us[0]]] == KILL) { defer[o].push_back(pr); } else if (binary_search(input.calleesaved.begin(), input.calleesaved.end(), r) && (ty == IN || ty == OUT)) { defer[o].push_back(pr); } else { int w = input.operand_width[p]; C2W[C] = w; for (int d=0; d<w; d++) CoveringClassesOfReg[r+d].push_back(C); C++; } } } } // deferred caller-saved that are dead upon funcall, grouped per call // deferred callee-saved preassignments in (in), (out) for (const pair<operation,vector<vector<int>>>& percall : defer) { for (const vector<int>& pr : percall.second) { operand p = pr[0]; register_atom r = pr[1]; int w = input.operand_width[p]; C2W[C] = w; for (int d=0; d<w; d++) CoveringClassesOfReg[r+d].push_back(C); } C++; } // prevent redefined temporaries from occurring in symmetry chains for (block b : B) for (operation o : input.ops[b]) for (const pair<operand,operand>& pp : input.redefined[o]) for (temporary t : input.temps[pp.second]) if (t != NULL_TEMPORARY) PreT.insert(t); // prevent (pack) operand temporaries from occurring in symmetry chains for (block b : B) for (vector<operand> ps : input.bpacked[b]) for (operand p : ps) for (temporary t : input.temps[p]) if (t != NULL_TEMPORARY) PreT.insert(t); // prevent ext. related operand temporaries from occurring in symmetry chains for (vector<operand> ps : input.exrelated) for (operand p : ps) for (temporary t : input.temps[p]) if (t != NULL_TEMPORARY) PreT.insert(t); // FIXME: this check is added temporarily, needs investigation // prevent temps defined by callee-saved-load from occurring in symmetry chains for (operation o : input.callee_saved_loads) if (global || input.oblock[o]==b) for (operand p : input.operands[o]) if (!input.use[p]) PreT.insert(input.single_temp[p]); // more register classes from fixed (in), (out), except preassigned if (!global) { operation inop = input.ops[b][0]; operation outop = max_of(input.ops[b]); for (operand p : input.operands[inop]) { if (!m->ry(p).assigned()) return chains; } for (operand p : input.operands[outop]) { if (!m->ry(p).assigned()) return chains; } for (operand p : input.operands[inop]) { int r = m->ry(p).val(); if (r >= 0 && !infinite_register_atom(input, m->ry(p).val()) && !PreP.count(p)) { int w = input.operand_width[p]; C2W[C] = w; for (int d=0; d<w; d++) CoveringClassesOfReg[r+d].push_back(C); C++; } } for (operand p : input.operands[outop]) { int r = m->ry(p).val(); if (r >= 0 && !infinite_register_atom(input, m->ry(p).val()) && !PreP.count(p)) { int w = input.operand_width[p]; C2W[C] = w; for (int d=0; d<w; d++) CoveringClassesOfReg[r+d].push_back(C); C++; } } } map<vector<register_class>,vector<register_atom>> RegsOfClasses; // regroup by set of covering register class for(const pair<register_atom,vector<register_class>>& RCs : CoveringClassesOfReg) RegsOfClasses[RCs.second].push_back(RCs.first); // build the chains for(const pair<vector<register_class>,vector<register_atom>>& CsRs : RegsOfClasses) { vector<register_class> Cs = CsRs.first; vector<register_atom> Rs = CsRs.second; if ((int)Rs.size()>1) { vector<temporary> Ts; for(temporary t : T) { int ty = input.type[input.def_opr[t]]; if ((ty == LINEAR || ty == COPY) && !PreT.count(t)) { operand p = input.definer[t]; operation o = input.oper[p]; unsigned pi = p - input.operands[o][0]; for (unsigned int ii = 0; ii < input.instructions[o].size(); ii++) { register_class rc = input.rclass[o][ii][pi]; if (binary_search(Cs.begin(), Cs.end(), rc)) { Ts.push_back(t); goto nextt; } } } nextt: ; } if (!Ts.empty()) SymChainsOfTemps[Ts].push_back(Rs); } } for(const pair<vector<temporary>,vector<vector<register_atom>>>& TsRs : SymChainsOfTemps) { PresolverValuePrecedeChain vpc; map<int,vector<temporary>> w2ts; vector<temporary> ts; int minwidth = 1; for (temporary t : TsRs.first) // sort temps by decreasing width w2ts[-input.width[t]].push_back(t); for (auto wts : w2ts) { ts.insert(ts.end(), wts.second.begin(), wts.second.end()); minwidth = -wts.first; } for (auto ras1 : TsRs.second) { vector<register_atom> ras2; for (register_atom a : ras1) if ((a % minwidth) == 0) ras2.push_back(a); if (ras2.size()>1) vpc.rss.push_back(ras2); } if (!vpc.rss.empty()) { sort(vpc.rss.begin(), vpc.rss.end()); // canonicalize vpc.ts = ts; // cerr << "SYMMETRY " << show(vpc) << endl; chains.push_back(vpc); } } return chains; }
33.648
124
0.63877
[ "vector", "model" ]
060bb9b1f39b79432be132baadae97157ff2ace3
10,357
cc
C++
pc/peer_connection_header_extension_unittest.cc
shishuo365/webrtc
96e60852faaa8ab4cf6477fa92c80a434921625d
[ "BSD-3-Clause" ]
1
2016-06-23T01:26:53.000Z
2016-06-23T01:26:53.000Z
pc/peer_connection_header_extension_unittest.cc
shishuo365/webrtc
96e60852faaa8ab4cf6477fa92c80a434921625d
[ "BSD-3-Clause" ]
null
null
null
pc/peer_connection_header_extension_unittest.cc
shishuo365/webrtc
96e60852faaa8ab4cf6477fa92c80a434921625d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "api/call/call_factory_interface.h" #include "api/jsep.h" #include "api/media_types.h" #include "api/peer_connection_interface.h" #include "api/rtc_error.h" #include "api/rtc_event_log/rtc_event_log_factory.h" #include "api/rtc_event_log/rtc_event_log_factory_interface.h" #include "api/rtp_parameters.h" #include "api/rtp_transceiver_direction.h" #include "api/rtp_transceiver_interface.h" #include "api/scoped_refptr.h" #include "api/task_queue/default_task_queue_factory.h" #include "api/task_queue/task_queue_factory.h" #include "media/base/fake_media_engine.h" #include "media/base/media_engine.h" #include "p2p/base/fake_port_allocator.h" #include "p2p/base/port_allocator.h" #include "pc/peer_connection_wrapper.h" #include "pc/session_description.h" #include "pc/test/mock_peer_connection_observers.h" #include "rtc_base/rtc_certificate_generator.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/thread.h" #include "test/gmock.h" #include "test/gtest.h" namespace webrtc { using ::testing::Combine; using ::testing::ElementsAre; using ::testing::Field; using ::testing::Return; using ::testing::Values; class PeerConnectionHeaderExtensionTest : public ::testing::TestWithParam< std::tuple<cricket::MediaType, SdpSemantics>> { protected: PeerConnectionHeaderExtensionTest() : extensions_( {RtpHeaderExtensionCapability("uri1", 1, RtpTransceiverDirection::kStopped), RtpHeaderExtensionCapability("uri2", 2, RtpTransceiverDirection::kSendOnly), RtpHeaderExtensionCapability("uri3", 3, RtpTransceiverDirection::kRecvOnly), RtpHeaderExtensionCapability( "uri4", 4, RtpTransceiverDirection::kSendRecv)}) {} std::unique_ptr<PeerConnectionWrapper> CreatePeerConnection( cricket::MediaType media_type, absl::optional<SdpSemantics> semantics) { auto voice = std::make_unique<cricket::FakeVoiceEngine>(); auto video = std::make_unique<cricket::FakeVideoEngine>(); if (media_type == cricket::MediaType::MEDIA_TYPE_AUDIO) voice->SetRtpHeaderExtensions(extensions_); else video->SetRtpHeaderExtensions(extensions_); auto media_engine = std::make_unique<cricket::CompositeMediaEngine>( std::move(voice), std::move(video)); PeerConnectionFactoryDependencies factory_dependencies; factory_dependencies.network_thread = rtc::Thread::Current(); factory_dependencies.worker_thread = rtc::Thread::Current(); factory_dependencies.signaling_thread = rtc::Thread::Current(); factory_dependencies.task_queue_factory = CreateDefaultTaskQueueFactory(); factory_dependencies.media_engine = std::move(media_engine); factory_dependencies.call_factory = CreateCallFactory(); factory_dependencies.event_log_factory = std::make_unique<RtcEventLogFactory>( factory_dependencies.task_queue_factory.get()); auto pc_factory = CreateModularPeerConnectionFactory(std::move(factory_dependencies)); auto fake_port_allocator = std::make_unique<cricket::FakePortAllocator>( rtc::Thread::Current(), nullptr); auto observer = std::make_unique<MockPeerConnectionObserver>(); PeerConnectionInterface::RTCConfiguration config; if (semantics) config.sdp_semantics = *semantics; PeerConnectionDependencies pc_dependencies(observer.get()); pc_dependencies.allocator = std::move(fake_port_allocator); auto result = pc_factory->CreatePeerConnectionOrError( config, std::move(pc_dependencies)); EXPECT_TRUE(result.ok()); observer->SetPeerConnectionInterface(result.value().get()); return std::make_unique<PeerConnectionWrapper>( pc_factory, result.MoveValue(), std::move(observer)); } rtc::AutoThread main_thread_; std::vector<RtpHeaderExtensionCapability> extensions_; }; TEST_P(PeerConnectionHeaderExtensionTest, TransceiverOffersHeaderExtensions) { cricket::MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) return; std::unique_ptr<PeerConnectionWrapper> wrapper = CreatePeerConnection(media_type, semantics); auto transceiver = wrapper->AddTransceiver(media_type); EXPECT_EQ(transceiver->HeaderExtensionsToOffer(), extensions_); } TEST_P(PeerConnectionHeaderExtensionTest, SenderReceiverCapabilitiesReturnNotStoppedExtensions) { cricket::MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); std::unique_ptr<PeerConnectionWrapper> wrapper = CreatePeerConnection(media_type, semantics); EXPECT_THAT(wrapper->pc_factory() ->GetRtpSenderCapabilities(media_type) .header_extensions, ElementsAre(Field(&RtpHeaderExtensionCapability::uri, "uri2"), Field(&RtpHeaderExtensionCapability::uri, "uri3"), Field(&RtpHeaderExtensionCapability::uri, "uri4"))); EXPECT_EQ(wrapper->pc_factory() ->GetRtpReceiverCapabilities(media_type) .header_extensions, wrapper->pc_factory() ->GetRtpSenderCapabilities(media_type) .header_extensions); } TEST_P(PeerConnectionHeaderExtensionTest, OffersUnstoppedDefaultExtensions) { cricket::MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) return; std::unique_ptr<PeerConnectionWrapper> wrapper = CreatePeerConnection(media_type, semantics); auto transceiver = wrapper->AddTransceiver(media_type); auto session_description = wrapper->CreateOffer(); EXPECT_THAT(session_description->description() ->contents()[0] .media_description() ->rtp_header_extensions(), ElementsAre(Field(&RtpExtension::uri, "uri2"), Field(&RtpExtension::uri, "uri3"), Field(&RtpExtension::uri, "uri4"))); } TEST_P(PeerConnectionHeaderExtensionTest, OffersUnstoppedModifiedExtensions) { cricket::MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) return; std::unique_ptr<PeerConnectionWrapper> wrapper = CreatePeerConnection(media_type, semantics); auto transceiver = wrapper->AddTransceiver(media_type); auto modified_extensions = transceiver->HeaderExtensionsToOffer(); modified_extensions[0].direction = RtpTransceiverDirection::kSendRecv; modified_extensions[3].direction = RtpTransceiverDirection::kStopped; EXPECT_TRUE( transceiver->SetOfferedRtpHeaderExtensions(modified_extensions).ok()); auto session_description = wrapper->CreateOffer(); EXPECT_THAT(session_description->description() ->contents()[0] .media_description() ->rtp_header_extensions(), ElementsAre(Field(&RtpExtension::uri, "uri1"), Field(&RtpExtension::uri, "uri2"), Field(&RtpExtension::uri, "uri3"))); } TEST_P(PeerConnectionHeaderExtensionTest, NegotiatedExtensionsAreAccessible) { cricket::MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) return; std::unique_ptr<PeerConnectionWrapper> pc1 = CreatePeerConnection(media_type, semantics); auto transceiver1 = pc1->AddTransceiver(media_type); auto modified_extensions = transceiver1->HeaderExtensionsToOffer(); modified_extensions[3].direction = RtpTransceiverDirection::kStopped; transceiver1->SetOfferedRtpHeaderExtensions(modified_extensions); auto offer = pc1->CreateOfferAndSetAsLocal( PeerConnectionInterface::RTCOfferAnswerOptions()); std::unique_ptr<PeerConnectionWrapper> pc2 = CreatePeerConnection(media_type, semantics); auto transceiver2 = pc2->AddTransceiver(media_type); pc2->SetRemoteDescription(std::move(offer)); auto answer = pc2->CreateAnswerAndSetAsLocal( PeerConnectionInterface::RTCOfferAnswerOptions()); pc1->SetRemoteDescription(std::move(answer)); // PC1 has exts 2-4 unstopped and PC2 has exts 1-3 unstopped -> ext 2, 3 // survives. EXPECT_THAT(transceiver1->HeaderExtensionsNegotiated(), ElementsAre(Field(&RtpHeaderExtensionCapability::uri, "uri2"), Field(&RtpHeaderExtensionCapability::uri, "uri3"))); } INSTANTIATE_TEST_SUITE_P( , PeerConnectionHeaderExtensionTest, Combine(Values(SdpSemantics::kPlanB_DEPRECATED, SdpSemantics::kUnifiedPlan), Values(cricket::MediaType::MEDIA_TYPE_AUDIO, cricket::MediaType::MEDIA_TYPE_VIDEO)), [](const testing::TestParamInfo< PeerConnectionHeaderExtensionTest::ParamType>& info) { cricket::MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = info.param; return (rtc::StringBuilder("With") << (semantics == SdpSemantics::kPlanB_DEPRECATED ? "PlanB" : "UnifiedPlan") << "And" << (media_type == cricket::MediaType::MEDIA_TYPE_AUDIO ? "Voice" : "Video") << "Engine") .str(); }); } // namespace webrtc
42.101626
80
0.691803
[ "vector" ]
0617c21c936b2ca9473c857f2797696d9ff2214c
1,845
cpp
C++
leetcode/Algorithms/DifferentWaysToAddParentheses/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
2
2015-07-03T03:05:30.000Z
2015-07-03T03:05:31.000Z
leetcode/Algorithms/DifferentWaysToAddParentheses/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
leetcode/Algorithms/DifferentWaysToAddParentheses/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
// divide and conquer solution by hxdone class Solution { public: vector<int> diffWaysToCompute(string input) { vector<int> numbers; vector<char> operators; int cur_num_val = 0; for (int i = 0; i < input.length(); ++i) { if (input[i] >= '0' && input[i] <= '9') { cur_num_val = cur_num_val*10+(input[i]-'0'); } else { numbers.push_back(cur_num_val); cur_num_val = 0; operators.push_back(input[i]); } } numbers.push_back(cur_num_val); vector<int> ret; expr(numbers, operators, 0, operators.size(), ret); return ret; } void expr(const vector<int>& numbers, const vector<char>& operators, int operator_start_idx, int operator_num, vector<int>& ret) { if (operator_num == 0) { ret.push_back(numbers[operator_start_idx]); } else if (operator_num > 0) { vector<int> left, right; for (int i = 0; i < operator_num; ++i) { left.clear(); right.clear(); expr(numbers, operators, operator_start_idx, i, left); expr(numbers, operators, operator_start_idx+i+1, operator_num-i-1, right); for (int j = 0; j < left.size(); ++j) for (int k = 0; k < right.size(); ++k) { switch(operators[operator_start_idx+i]) { case '+': { ret.push_back(left[j] + right[k]); break;} case '-': { ret.push_back(left[j] - right[k]); break;} case '*': { ret.push_back(left[j] * right[k]); break;} default: {break;} } } } } } };
39.255319
134
0.471545
[ "vector" ]
061ef8550b17a7732949bd779b404ad80560ec35
472
cpp
C++
Segunda Unidad/Ejercicios 04-11-2021/grid.cpp
LuisSante/Programacion-Competitiva
c263521e4b7326bb61a9026bf989cb9fea946217
[ "BSD-3-Clause" ]
null
null
null
Segunda Unidad/Ejercicios 04-11-2021/grid.cpp
LuisSante/Programacion-Competitiva
c263521e4b7326bb61a9026bf989cb9fea946217
[ "BSD-3-Clause" ]
null
null
null
Segunda Unidad/Ejercicios 04-11-2021/grid.cpp
LuisSante/Programacion-Competitiva
c263521e4b7326bb61a9026bf989cb9fea946217
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) { int n = grid.size(), m = grid[0].size(); k = k % (n * m); vector<vector<int>> res(n, vector<int>(m)); for(int i = 0; i < n; i ++) for(int j = 0; j < m; j ++){ int index = (i * m + j + k) % (n * m); res[index / m][index % m] = grid[i][j]; } return res; } int main() { return 0; }
21.454545
65
0.480932
[ "vector" ]
164b63bafde0d212c56265d3553fb6bc509d0624
1,901
hpp
C++
include/vktiny/Swapchain.hpp
nishidate-yuki/vktiny
d33332d87700578283edb3a069522220493eed8d
[ "MIT" ]
2
2021-08-19T13:46:18.000Z
2021-08-21T08:44:37.000Z
include/vktiny/Swapchain.hpp
nishidate-yuki/vktiny
d33332d87700578283edb3a069522220493eed8d
[ "MIT" ]
null
null
null
include/vktiny/Swapchain.hpp
nishidate-yuki/vktiny
d33332d87700578283edb3a069522220493eed8d
[ "MIT" ]
1
2021-08-21T07:42:08.000Z
2021-08-21T07:42:08.000Z
#pragma once #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1 #include <vulkan/vulkan.hpp> #include <GLFW/glfw3.h> #include <utility> #include "Context.hpp" namespace vkt { struct FrameInfo { uint32_t imageIndex; uint32_t currentFrame; vk::Semaphore imageAvailableSemaphore; vk::Semaphore renderFinishedSemaphore; vk::Fence inFlightFence; }; class Swapchain { public: Swapchain(const Context& context, int width, int height); Swapchain(const Swapchain&) = delete; Swapchain(Swapchain&&) = default; Swapchain& operator=(const Swapchain&) = delete; Swapchain& operator=(Swapchain&&) = default; ~Swapchain(); std::vector<vk::UniqueCommandBuffer> allocateDrawComamndBuffers() const; uint32_t acquireNextImageIndex() const; FrameInfo beginFrame(); void endFrame(uint32_t imageIndex); vk::SwapchainKHR get() const { return swapchain.get(); } auto getExtent() const { return imageExtent; } auto getFormat() const { return imageFormat; } auto getImagesSize() const { return images.size(); } const auto& getImages() const { return images; } private: void createViews(); void createSyncObjects(); const Context* context; vk::UniqueSwapchainKHR swapchain; std::vector<vk::Image> images; vk::Format imageFormat; vk::Extent2D imageExtent; std::vector<vk::UniqueImageView> imageViews; std::vector<vk::UniqueFramebuffer> framebuffers; size_t currentFrame = 0; const int maxFramesInFlight = 2; std::vector<vk::UniqueSemaphore> imageAvailableSemaphores; std::vector<vk::UniqueSemaphore> renderFinishedSemaphores; std::vector<vk::Fence> inFlightFences; std::vector<vk::Fence> imagesInFlight; }; }
28.373134
80
0.648606
[ "vector" ]
164ddf785105f305d4a21b25d9b4f2f87b6d4c45
1,166
cpp
C++
xarm_vision/d435i_xarm_setup/src/tf_object_to_base.cpp
Permobil-Senior-Design/xarm_ros
3d82a29e462e0c26598f20222cb5d3d372de02f7
[ "BSD-3-Clause" ]
null
null
null
xarm_vision/d435i_xarm_setup/src/tf_object_to_base.cpp
Permobil-Senior-Design/xarm_ros
3d82a29e462e0c26598f20222cb5d3d372de02f7
[ "BSD-3-Clause" ]
null
null
null
xarm_vision/d435i_xarm_setup/src/tf_object_to_base.cpp
Permobil-Senior-Design/xarm_ros
3d82a29e462e0c26598f20222cb5d3d372de02f7
[ "BSD-3-Clause" ]
1
2022-02-11T22:27:35.000Z
2022-02-11T22:27:35.000Z
#include "ros/ros.h" #include <tf/transform_broadcaster.h> #include <object_recognition_msgs/RecognizedObjectArray.h> void poseCallback(const object_recognition_msgs::RecognizedObjectArrayConstPtr& msg){ if(msg->objects.empty()) return; if(msg->objects.size()>1) ROS_WARN("Detected Multiple objects, only broadcasting the first one .."); static tf::TransformBroadcaster br; tf::Transform transform; transform.setOrigin( tf::Vector3(msg->objects.at(0).pose.pose.pose.position.x, msg->objects.at(0).pose.pose.pose.position.y, msg->objects.at(0).pose.pose.pose.position.z) ); transform.setRotation(tf::Quaternion(msg->objects.at(0).pose.pose.pose.orientation.x, msg->objects.at(0).pose.pose.pose.orientation.y, msg->objects.at(0).pose.pose.pose.orientation.z, msg->objects.at(0).pose.pose.pose.orientation.w)); br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/camera_color_optical_frame", "coke_can")); } int main(int argc, char** argv){ ros::init(argc, argv, "tf_obj_to_base"); ros::NodeHandle node; ros::Subscriber sub = node.subscribe("/recognized_object_array", 10, &poseCallback); ros::spin(); return 0; };
43.185185
236
0.740995
[ "transform" ]
164f58769bcad387092bec46df3cb27b27082a9a
5,967
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/CActivityManagerMemoryInfo.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/CActivityManagerMemoryInfo.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/CActivityManagerMemoryInfo.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/ext/frameworkext.h" #include "elastos/droid/app/CActivityManagerMemoryInfo.h" namespace Elastos { namespace Droid { namespace App { CAR_INTERFACE_IMPL_2(CActivityManagerMemoryInfo, Object, IActivityManagerMemoryInfo, IParcelable) CAR_OBJECT_IMPL(CActivityManagerMemoryInfo) CActivityManagerMemoryInfo::CActivityManagerMemoryInfo() : mAvailMem(0) , mTotalMem(0) , mThreshold(0) , mLowMemory(FALSE) , mHiddenAppThreshold(0) , mSecondaryServerThreshold(0) , mVisibleAppThreshold(0) , mForegroundAppThreshold(0) { } ECode CActivityManagerMemoryInfo::constructor() { return NOERROR; } ECode CActivityManagerMemoryInfo::WriteToParcel( /* [in] */ IParcel* dest) { VALIDATE_NOT_NULL(dest); FAIL_RETURN(dest->WriteInt64(mAvailMem)); FAIL_RETURN(dest->WriteInt64(mTotalMem)); FAIL_RETURN(dest->WriteInt64(mThreshold)); FAIL_RETURN(dest->WriteBoolean(mLowMemory)); FAIL_RETURN(dest->WriteInt64(mHiddenAppThreshold)); FAIL_RETURN(dest->WriteInt64(mSecondaryServerThreshold)); FAIL_RETURN(dest->WriteInt64(mVisibleAppThreshold)); FAIL_RETURN(dest->WriteInt64(mForegroundAppThreshold)); return NOERROR; } ECode CActivityManagerMemoryInfo::ReadFromParcel( /* [in] */ IParcel* source) { VALIDATE_NOT_NULL(source); FAIL_RETURN(source->ReadInt64(&mAvailMem)); FAIL_RETURN(source->ReadInt64(&mTotalMem)); FAIL_RETURN(source->ReadInt64(&mThreshold)); FAIL_RETURN(source->ReadBoolean(&mLowMemory)); FAIL_RETURN(source->ReadInt64(&mHiddenAppThreshold)); FAIL_RETURN(source->ReadInt64(&mSecondaryServerThreshold)); FAIL_RETURN(source->ReadInt64(&mVisibleAppThreshold)); FAIL_RETURN(source->ReadInt64(&mForegroundAppThreshold)); return NOERROR; } /** * The available memory on the system. This number should not * be considered absolute: due to the nature of the kernel, a significant * portion of this memory is actually in use and needed for the overall * system to run well. */ ECode CActivityManagerMemoryInfo::GetAvailMem( /* [out] */ Int64* availMem) { VALIDATE_NOT_NULL(availMem); *availMem = mAvailMem; return NOERROR; } ECode CActivityManagerMemoryInfo::SetAvailMem( /* [in] */ Int64 availMem) { mAvailMem = availMem; return NOERROR; } /** * The total memory accessible by the kernel. This is basically the * RAM size of the device, not including below-kernel fixed allocations * like DMA buffers, RAM for the baseband CPU, etc. */ ECode CActivityManagerMemoryInfo::GetTotalMem( /* [out] */ Int64* totalMem) { VALIDATE_NOT_NULL(totalMem); *totalMem = mTotalMem; return NOERROR; } ECode CActivityManagerMemoryInfo::SetTotalMem( /* [in] */ Int64 totalMem) { mTotalMem = totalMem; return NOERROR; } /** * The threshold of {@link #availMem} at which we consider memory to be * low and start killing background services and other non-extraneous * processes. */ ECode CActivityManagerMemoryInfo::GetThreshold( /* [out] */ Int64* threshold) { VALIDATE_NOT_NULL(threshold); *threshold = mThreshold; return NOERROR; } ECode CActivityManagerMemoryInfo::SetThreshold( /* [in] */ Int64 threshold) { mThreshold = threshold; return NOERROR; } /** * Set to true if the system considers itself to currently be in a low * memory situation. */ ECode CActivityManagerMemoryInfo::GetLowMemory( /* [out] */ Boolean* lowMemory) { VALIDATE_NOT_NULL(lowMemory); *lowMemory = mLowMemory; return NOERROR; } ECode CActivityManagerMemoryInfo::SetLowMemory( /* [in] */ Boolean lowMemory) { mLowMemory = lowMemory; return NOERROR; } /** @hide */ ECode CActivityManagerMemoryInfo::GetHiddenAppThreshold( /* [out] */ Int64* threshold) { VALIDATE_NOT_NULL(threshold); *threshold = mHiddenAppThreshold; return NOERROR; } ECode CActivityManagerMemoryInfo::SetHiddenAppThreshold( /* [in] */ Int64 threshold) { mHiddenAppThreshold = threshold; return NOERROR; } /** @hide */ ECode CActivityManagerMemoryInfo::GetSecondaryServerThreshold( /* [out] */ Int64* threshold) { VALIDATE_NOT_NULL(threshold); *threshold = mSecondaryServerThreshold; return NOERROR; } ECode CActivityManagerMemoryInfo::SetSecondaryServerThreshold( /* [in] */ Int64 threshold) { mSecondaryServerThreshold = threshold; return NOERROR; } /** @hide */ ECode CActivityManagerMemoryInfo::GetVisibleAppThreshold( /* [out] */ Int64* threshold) { VALIDATE_NOT_NULL(threshold); *threshold = mVisibleAppThreshold; return NOERROR; } ECode CActivityManagerMemoryInfo::SetVisibleAppThreshold( /* [in] */ Int64 threshold) { mVisibleAppThreshold = threshold; return NOERROR; } /** @hide */ ECode CActivityManagerMemoryInfo::GetForegroundAppThreshold( /* [out] */ Int64* threshold) { VALIDATE_NOT_NULL(threshold); *threshold = mForegroundAppThreshold; return NOERROR; } ECode CActivityManagerMemoryInfo::SetForegroundAppThreshold( /* [in] */ Int64 threshold) { mForegroundAppThreshold = threshold; return NOERROR; } } // namespace App } // namespace Droid } // namespace Elastos
26.402655
97
0.707391
[ "object" ]
1652063ce49727f1c48a9512142fdb5ae40285f4
1,456
cpp
C++
Leetcode/1000-2000/1444. Number of Ways of Cutting a Pizza/1444.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1444. Number of Ways of Cutting a Pizza/1444.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1444. Number of Ways of Cutting a Pizza/1444.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int ways(vector<string>& pizza, int k) { const int M = pizza.size(); const int N = pizza[0].size(); // dp[m][n][k] := # of ways to cut pizza[m:M][n:N] w/ k cuts dp.resize(M, vector<vector<int>>(N, vector<int>(k, -1))); prefix.resize(M + 1, vector<int>(N + 1)); for (int i = 0; i < M; ++i) for (int j = 0; j < N; ++j) prefix[i + 1][j + 1] = (pizza[i][j] == 'A') + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]; return ways(0, 0, k - 1, M, N); } private: constexpr static int kMod = 1e9 + 7; vector<vector<vector<int>>> dp; vector<vector<int>> prefix; // hasApple of pizza[row1..row2)[col1..col2) bool hasApple(int row1, int row2, int col1, int col2) { return (prefix[row2][col2] - prefix[row1][col2] - prefix[row2][col1] + prefix[row1][col1]) > 0; }; int ways(int m, int n, int k, const int M, const int N) { if (k == 0) return 1; if (dp[m][n][k] >= 0) return dp[m][n][k]; dp[m][n][k] = 0; for (int i = m + 1; i < M; ++i) // cut horizontally if (hasApple(m, i, n, N) && hasApple(i, M, n, N)) dp[m][n][k] = (dp[m][n][k] + ways(i, n, k - 1, M, N)) % kMod; for (int j = n + 1; j < N; ++j) // cut vertically if (hasApple(m, M, n, j) && hasApple(m, M, j, N)) dp[m][n][k] = (dp[m][n][k] + ways(m, j, k - 1, M, N)) % kMod; return dp[m][n][k]; } };
30.333333
72
0.484203
[ "vector" ]
16533a51d94aa05e64c8454b48beef2bdbd5740f
2,199
cpp
C++
Pong/main.cpp
peeet/Pong
094816b49f88328dabc3718ceb16d1672a259c73
[ "MIT" ]
null
null
null
Pong/main.cpp
peeet/Pong
094816b49f88328dabc3718ceb16d1672a259c73
[ "MIT" ]
null
null
null
Pong/main.cpp
peeet/Pong
094816b49f88328dabc3718ceb16d1672a259c73
[ "MIT" ]
null
null
null
/** * @author Peter Hansen * @copyright p3337.de All rights reserved. */ #undef UNICODE #define UNICODE #include <SFML/Graphics.hpp> #include <windows.h> #include "Board.h" #include "Variables.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) //int main() { sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT, 32), TITLE, sf::Style::Titlebar | sf::Style::Close); window.setVerticalSyncEnabled(true); // Load the text font sf::Font font; if (!font.loadFromFile(FONT_PATH)) __nop(); // Initialize the start / end message sf::Text msgStart; msgStart.setFont(font); msgStart.setCharacterSize(40); msgStart.setPosition((float) WIDTH / 6.0f, (float) HEIGHT / 4.0f); msgStart.setColor(sf::Color::Red); msgStart.setString(MSG_START); // create both players Player playerLeft = Player(sf::Keyboard::Key::A, sf::Keyboard::Key::Y, sf::Color::Blue, Player::Side::LEFT); Player playerRight = Player(sf::Keyboard::Key::K, sf::Keyboard::Key::M, sf::Color::Red, Player::Side::RIGHT); std::vector<Player*> players = { &playerLeft, &playerRight }; // create board Board board = Board(&players); // start main loop bool isPlaying = false; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { // Window closed or escape key pressed: exit if ((event.type == sf::Event::Closed) || ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) { window.close(); break; } // Space key pressed: play if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space)) { if (!isPlaying) { // (re)start the game isPlaying = true; } } } window.clear(sf::Color(33, 33, 33)); if (isPlaying) { // check if game has ended and reset it if (!board.update(&window)) { isPlaying = false; char buff[100]; snprintf(buff, sizeof(buff), MSG_END.toAnsiString().c_str(), playerLeft.getScore() >= WIN_POINTS ? 0 : 1); std::string buffAsStdStr = buff; msgStart.setString(buffAsStdStr); board.reset(); } } else { window.draw(msgStart); } window.display(); } return 0; }
24.433333
110
0.654388
[ "vector" ]
1654e1059ecff36494b26f30d77dec41fc92332a
6,697
cpp
C++
pgprogram.cpp
kiennguyenchi/potato-generator
4ff3de7f55e0960ca1a5bddb6c3891bfa8b795ac
[ "MIT" ]
null
null
null
pgprogram.cpp
kiennguyenchi/potato-generator
4ff3de7f55e0960ca1a5bddb6c3891bfa8b795ac
[ "MIT" ]
12
2021-09-17T16:06:51.000Z
2021-10-08T21:31:37.000Z
pgprogram.cpp
kiennguyenchi/potato-generator
4ff3de7f55e0960ca1a5bddb6c3891bfa8b795ac
[ "MIT" ]
3
2021-09-17T13:33:49.000Z
2021-11-18T22:12:18.000Z
/* * This program is A Static Site Generator (SSG) Tool coded in C++ language. * Author: Chi Kien Nguyen * Git Hub: https://github.com/kiennguyenchi/potato-generator */ /* This is the file containing main function to run the program */ #include "MainPage.h" #include <filesystem> #include <iostream> #include <string> #include <vector> using namespace std; using std::filesystem::directory_iterator; namespace fs = std::filesystem; void createHTMLFile(string filename, string outPath, string lang); void createMainPageWithHTMLs(string folderName, string outPath, string lang); string checkArguments(int argc, char** argv); string checkLanguage(int argc, char** argv); bool checkIfConfig(int argc, char** argv); void makeDir(string outputDir); string readConfig(string fileName); string getOutputArgument(int argc, char** argv); string getLangArgument(int argc, char** argv); int main(int argc, char** argv) { if (argc >= 2) { string name = checkArguments(argc, argv); if (name != "terminate") { bool configFlag = checkIfConfig(argc, argv); string outFolder = "./dist"; string language = checkLanguage(argc, argv); bool valid = true; if (configFlag) { string temp = readConfig(name); if (temp.find("\"") == string::npos) { cout << "Empty config file. Please try again." << endl; valid = false; } else { //get input from config file if (temp.find("input") != string::npos) { size_t start = temp.find("input") + 9; size_t end = temp.find("\"", start + 2); name = temp.substr(start, (end - start)); } else { valid = false; cout << "There is no input file" << endl; } //if output folder is specified in config file if (temp.find("output") != string::npos) { size_t start = temp.find("output") + 12; size_t end = temp.find("\"", start - 1); outFolder = temp.substr(start, (end - start)); } if (temp.find("lang") != string::npos) { size_t start = temp.find("lang") + 8; size_t end = temp.find("\"", start - 1); language = temp.substr(start, (end - start)); } } } else { if (getOutputArgument(argc, argv) != "") outFolder = getOutputArgument(argc, argv); if (getLangArgument(argc, argv) != "") language = getLangArgument(argc, argv); } if (valid) { makeDir(outFolder); if (name.find(".txt") != string::npos || name.find(".md") != string::npos) { createHTMLFile(name, outFolder, language); } else { createMainPageWithHTMLs(name, outFolder, language); } } } } else { cout << "Failed arguments provided"; } } //this function creates a single HTML page void createHTMLFile(string filename, string outPath, string lang) { HTMLFile newFile; newFile.openFile(filename, lang); newFile.setHtmlFile(); newFile.writeHTML(outPath); } //this function creates multiple HTML page void createMainPageWithHTMLs(string folderName, string outPath, string lang) { vector<string> fileNames; for (const auto& file : directory_iterator(folderName)) { fileNames.push_back(file.path().string()); MainPage newPage; newPage.setMainPage(outPath, fileNames, lang); newPage.writeHTML(outPath); } } //this function checks for arguments input string checkArguments(int argc, char** argv) { string fileName = ""; for (int i = 1; i < argc; i++) { if (string(argv[i]) == "--version" || string(argv[i]) == "-v") { cout << "Potato Generator - Version 0.1"; fileName = "terminate"; break; } else if (string(argv[i]) == "--help" || string(argv[i]) == "-h") { cout << "*Run the program with command: ./pgprogram inputName\n"; cout << "The inputName is a text file name or a folder name\n"; cout << "*To include a input file/folder, include --input or -i before the file/folder name in the arguments.\n"; cout << "*To specify an config file, use --config or -c before the config filename.\n"; cout << "*To see the version of the program, include --version or -v in the arguments.\n"; cout << "*To need help, include --help or -h in the arguments.\n"; fileName = "terminate"; break; } else if (string(argv[i]) == "--input" || string(argv[i]) == "-i") { fileName = argv[i + 1]; break; } else if (string(argv[i]) == "--config" || string(argv[i]) == "-c") { fileName = argv[i + 1]; break; } } return fileName; } //this function checks for language specified string checkLanguage(int argc, char** argv) { string language = ""; for (int i = 1; i < argc; i++) { if (string(argv[i]) == "--lang" || string(argv[i]) == "-l") { language = argv[i + 1]; } } return language; } bool checkIfConfig(int argc, char** argv) { bool config = false; for (int i = 1; i < argc; i++) { if (string(argv[i]) == "--config" || string(argv[i]) == "-c") { config = true; } } return config; } void makeDir(string outputDir) { fs::remove_all(outputDir); fs::create_directory(outputDir); } string readConfig(string fileName) { string storeConfig = ""; ifstream configFile; configFile.open(fileName, ios::in); if (configFile.is_open()) { getline(configFile, storeConfig, '}'); configFile.close(); } return storeConfig; } string getOutputArgument(int argc, char** argv) { string value = ""; for (int i = 1; i < argc; i++) { if (string(argv[i]) == "--output" || string(argv[i]) == "-o") { value = argv[i + 1]; break; } } return value; } string getLangArgument(int argc, char** argv) { string value = ""; for (int i = 1; i < argc; i++) { if (string(argv[i]) == "--lang" || string(argv[i]) == "-l") { value = argv[i + 1]; break; } } return value; }
33.653266
125
0.532776
[ "vector" ]
16557d972519433e9cdce997c20bbbf40baef9a3
1,224
hpp
C++
third_party/boost/simd/function/prev.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
5
2018-02-20T11:21:12.000Z
2019-11-12T13:45:09.000Z
third_party/boost/simd/function/prev.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/prev.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
2
2017-11-17T15:30:36.000Z
2018-03-01T02:06:25.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_PREV_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_PREV_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-ieee Function object implementing prev capabilities Returns if it exists the greatest representable value strictly less than the parameter @par Semantic: @code auto r = prev(x); @endcode @par Note - for entries of floating types - prev(Valmin) is Minf - prev(Inf) is Valmax - prev(Minf) is Minf - prev(Nan) is Nan - for entries of integral type - prev(Valmin) is Valmax @see prev, nextafter, successor, predecessor **/ Value prev(Value const & v0); } } #endif #include <boost/simd/function/scalar/prev.hpp> #include <boost/simd/function/simd/prev.hpp> #endif
21.103448
100
0.576797
[ "object" ]
1655a3ab15cb72a5c693bbbff979d0cd84895d7c
1,557
hpp
C++
iceoryx_hoofs/include/iceoryx_hoofs/cxx/scoped_static.hpp
FerdinandSpitzschnueffler/iceoryx
d193464922a3314323f4e03c4733d60143dde2f6
[ "Apache-2.0" ]
1
2022-03-11T10:48:23.000Z
2022-03-11T10:48:23.000Z
iceoryx_hoofs/include/iceoryx_hoofs/cxx/scoped_static.hpp
FerdinandSpitzschnueffler/iceoryx
d193464922a3314323f4e03c4733d60143dde2f6
[ "Apache-2.0" ]
5
2020-11-05T17:05:42.000Z
2022-02-11T08:35:46.000Z
iceoryx_hoofs/include/iceoryx_hoofs/cxx/scoped_static.hpp
boschglobal/iceoryx
eb0256407e3cf0baed1efdee6f8eeacf4d3514da
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_CXX_SCOPED_STATIC_HPP #define IOX_HOOFS_CXX_SCOPED_STATIC_HPP #include "iceoryx_hoofs/cxx/generic_raii.hpp" namespace iox { namespace cxx { /// @todo better name /// create a GenericRAII object to cleanup a static optional object at the end of the scope /// @tparam [in] T memory container which has emplace(...) and reset /// @tparam [in] CTorArgs ctor types for the object to construct /// @param [in] memory is a reference to a memory container, e.g. cxx::optional /// @param [in] ctorArgs ctor arguments for the object to construct /// @return cxx::GenericRAII template <typename T, typename... CTorArgs> GenericRAII makeScopedStatic(T& memory, CTorArgs&&... ctorArgs); } // namespace cxx } // namespace iox #include "iceoryx_hoofs/internal/cxx/scoped_static.inl" #endif // IOX_HOOFS_CXX_SCOPED_STATIC_HPP
37.071429
91
0.750803
[ "object" ]
165d7974adc67b403dbde0e176dcce5d1bf26529
3,224
cc
C++
mediapipe/framework/profiler/circular_buffer_test.cc
dwayne45/mediapipe
731d2b95363d58f12acb29a6f8435ec33fe548d9
[ "Apache-2.0" ]
47
2019-12-29T02:52:48.000Z
2022-02-21T08:39:14.000Z
mediapipe/framework/profiler/circular_buffer_test.cc
xellnaga/mediapipe
1722d4b8a25ad7c919576f9b1bab4ffa7a9299bc
[ "Apache-2.0" ]
5
2020-07-28T14:11:21.000Z
2021-05-02T10:11:29.000Z
mediapipe/framework/profiler/circular_buffer_test.cc
xellnaga/mediapipe
1722d4b8a25ad7c919576f9b1bab4ffa7a9299bc
[ "Apache-2.0" ]
41
2020-01-27T00:30:43.000Z
2022-03-24T01:35:19.000Z
// Copyright 2018 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mediapipe/framework/profiler/circular_buffer.h" #include "absl/time/time.h" #include "mediapipe/framework/port/gtest.h" #include "mediapipe/framework/port/threadpool.h" namespace { class CircularBufferTest : public ::testing::Test { protected: // Called before every TEST_F using this fixture. CircularBufferTest() {} }; TEST_F(CircularBufferTest, SequentialWriteAndRead) { mediapipe::CircularBuffer<std::string> my_buffer(100); my_buffer.push_back("one"); my_buffer.push_back("two"); my_buffer.push_back("three"); std::vector<std::string> snapshot; auto begin = my_buffer.begin(); auto end = my_buffer.end(); for (auto iter = begin; iter < end; ++iter) { snapshot.push_back(*iter); } std::vector<std::string> expected = {"one", "two", "three"}; EXPECT_EQ(snapshot, expected); begin = end; end = my_buffer.end(); for (auto iter = begin; iter < end; ++iter) { snapshot.push_back(*iter); } EXPECT_EQ(snapshot, expected); } TEST_F(CircularBufferTest, ParallelWriteAndRead) { mediapipe::CircularBuffer<std::string> buffer(100); auto first = buffer.begin(); std::atomic_int read_sum(0); std::atomic_int read_count(0); { ::mediapipe::ThreadPool pool(12); pool.StartWorkers(); // Start 6 writers. for (int w = 0; w < 6; ++w) { pool.Schedule([&]() { for (int i = 0; i < 300; ++i) { buffer.push_back("w5"); absl::SleepFor(absl::Microseconds(1)); } }); } // Start 6 readers. for (int w = 0; w < 6; ++w) { pool.Schedule([&]() { for (int t = 0; t < 10; ++t) { while (buffer.end() - buffer.begin() < 50) { } auto end = buffer.end(); for (auto it = buffer.begin(); it < end; ++it) { read_sum += (*it).size(); read_count++; } } }); } } // Validate the total number of writes including failed writes. EXPECT_EQ(1800, buffer.end() - first); // Validate that every read succeeds. EXPECT_LT(2000, read_count); EXPECT_EQ(read_sum, read_count * 2); } TEST_F(CircularBufferTest, SequentialGetWraps) { mediapipe::CircularBuffer<int> buffer(3); buffer.push_back(2); ASSERT_EQ(2, buffer.Get(0)); ASSERT_EQ(*buffer.begin(), buffer.Get(0)); buffer.push_back(3); ASSERT_EQ(2, buffer.Get(0)); ASSERT_EQ(3, buffer.Get(1)); ASSERT_EQ(*buffer.begin(), buffer.Get(0)); for (int i = 2; i < 100; ++i) { buffer.push_back(i + 2); ASSERT_EQ(i + 2, buffer.Get(2)); ASSERT_EQ(i, buffer.Get(0)); ASSERT_EQ(*buffer.begin(), buffer.Get(0)); } } } // namespace
29.309091
75
0.638958
[ "vector" ]
16635890f281f423ebf0f520ef76e1dc01d8ebe1
1,718
cpp
C++
demos/test5/test5.cpp
poluyan/PEPSGO
d1039bf0362bddca6247ffadf7b2124e6cfb64cf
[ "Apache-2.0" ]
1
2021-06-07T16:07:04.000Z
2021-06-07T16:07:04.000Z
demos/test5/test5.cpp
poluyan/PEPSGO
d1039bf0362bddca6247ffadf7b2124e6cfb64cf
[ "Apache-2.0" ]
null
null
null
demos/test5/test5.cpp
poluyan/PEPSGO
d1039bf0362bddca6247ffadf7b2124e6cfb64cf
[ "Apache-2.0" ]
null
null
null
#include <devel/init.hh> #include <pepsgo.hh> struct Example { std::function<core::Real(const std::vector<double>&)> FitnessFunction; std::function<core::Real(const std::vector<double>&, int)> FitnessFunctionMultiThread; }; int main(int argc, char *argv[]) { std::cout << "Start..." << std::endl; size_t thread_num = 4; pepsgo::PEPSGO obj(argc, argv); obj.set_number_of_threads(thread_num); obj.set_peptide_from_file(); obj.set_task(5); obj.fill_opt_vector(); obj.optimize_native(); obj.set_multithread(); std::cout << obj.get_problem_dimension() << std::endl; std::function<core::Real(const std::vector<double>&)> f = std::bind(&pepsgo::PEPSGO::objective, obj, std::placeholders::_1); std::function<core::Real(const std::vector<double>&, int)> f_mt = std::bind(&pepsgo::PEPSGO::objective_mt, obj, std::placeholders::_1, std::placeholders::_2); std::cout << f(std::vector<core::Real>(obj.get_problem_dimension(),0.4)) << std::endl; std::cout << f_mt(std::vector<core::Real>(obj.get_problem_dimension(),0.4),thread_num-1) << std::endl; std::cout << obj.get_AA_rmsd(std::vector<core::Real>(obj.get_problem_dimension(),0.4)) << std::endl; std::cout << obj.get_CA_rmsd(std::vector<core::Real>(obj.get_problem_dimension(),0.4)) << std::endl; Example fObj; fObj.FitnessFunction = std::bind(&pepsgo::PEPSGO::objective, obj, std::placeholders::_1); fObj.FitnessFunctionMultiThread = std::bind(&pepsgo::PEPSGO::objective_mt, obj, std::placeholders::_1, std::placeholders::_2); obj.append_to_native_and_superpose_AA(std::vector<core::Real>(obj.get_problem_dimension(),0.4)); obj.append_to_native_and_superpose_CA(std::vector<core::Real>(obj.get_problem_dimension(),0.4)); obj.dumb_superposed(); }
42.95
159
0.720023
[ "vector" ]
1663ce3c27d116ac660eec6ae0644b8ad23a3f49
525
cpp
C++
algos/alphabeta.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
31
2015-11-15T19:24:17.000Z
2018-09-27T01:45:24.000Z
algos/alphabeta.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
23
2015-09-23T15:56:32.000Z
2016-05-04T02:48:16.000Z
algos/alphabeta.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
7
2016-08-25T21:29:56.000Z
2018-07-22T03:39:51.000Z
ll alphabeta(State &s, bool player = true, int depth = 1e9, ll alpha = -INF, ll beta = INF) { //player = true -> Maximiza if(s.isFinal()) return s.score; //~ if (!depth) return s.heuristic(); vector<State> children; s.expand(player, children); int n = children.size(); forn(i, n) { ll v = alphabeta(children[i], !player, depth-1, alpha, beta); if(!player) alpha = max(alpha, v); else beta = min(beta, v); if(beta <= alpha) break; } return !player ? alpha : beta;}
37.5
121
0.577143
[ "vector" ]
1670055a9e50076836d68a01f21b5380869953ef
6,265
cpp
C++
src/backend/dnnl/passes/fusion_info.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/dnnl/passes/fusion_info.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/dnnl/passes/fusion_info.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <algorithm> #include <functional> #include <map> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include <unordered_map> #include "interface/c_types_map.hpp" #include "interface/op.hpp" #include "interface/value.hpp" #include "utils/utils.hpp" #include "backend/dnnl/internal_ops.hpp" #include "backend/dnnl/passes/fusion_info.hpp" #include "backend/dnnl/utils.hpp" #include "dnnl.hpp" namespace dnnl { namespace graph { namespace impl { namespace dnnl_impl { dnnl::primitive_attr make_dnnl_primitive_attr( const std::shared_ptr<impl::op_t> &op, const fusion_info_t &fusion_info) { dnnl::primitive_attr attr; // convert output scales if (fusion_info.output_scales_) { const impl::op_t *oscales_op = fusion_info.output_scales_->get_op(); auto oscales = oscales_op->get_attr<std::vector<float>>("scales"); int oscales_mask = oscales.size() == 1 ? 0 : 1 << oscales_op->get_attr<int64_t>("axis"); attr.set_output_scales(oscales_mask, oscales); } // convert input zps if (!fusion_info.input_zps_.empty()) { for (const auto &in_zps : fusion_info.input_zps_) { size_t in_zps_indice = in_zps.first; const impl::op_t *in_zps_op = in_zps.second->get_op(); auto zps = in_zps_op->get_attr<std::vector<int64_t>>("zps"); int mask = zps.size() == 1 ? 0 : 1 << in_zps_op->get_attr<int64_t>("axis"); std::vector<int32_t> neg_int32_zps = dnnl_impl::utils::fmap( zps, [](int64_t zp) { return static_cast<int32_t>(-zp); }); attr.set_zero_points( in_zps_indice == 0 ? DNNL_ARG_SRC : DNNL_ARG_WEIGHTS, mask, neg_int32_zps); } } // convert output zps if (fusion_info.output_zps_) { const impl::op_t *out_zps_op = fusion_info.output_zps_->get_op(); auto zps = out_zps_op->get_attr<std::vector<int64_t>>("zps"); int mask = zps.size() == 1 ? 0 : 1 << out_zps_op->get_attr<int64_t>("axis"); std::vector<int32_t> int32_zps = dnnl_impl::utils::fmap( zps, [](int64_t zp) { return static_cast<int32_t>(zp); }); attr.set_zero_points(DNNL_ARG_DST, mask, int32_zps); } // convert post ops dnnl::post_ops dnnl_pops; for (auto &pop : fusion_info.get_post_ops()) { const impl::op_t *fused_op = pop->get_op(); const auto fused_op_kind = fused_op->get_kind(); if (fused_op_kind == op_kind::dnnl_eltwise) { float scale = pop->get_scale(); float alpha = 0.f; float beta = 0.f; if (fused_op->has_attr("alpha")) { alpha = fused_op->get_attr<float>("alpha"); } if (fused_op->has_attr("beta")) { beta = fused_op->get_attr<float>("beta"); } const auto alg = static_cast<dnnl::algorithm>( fused_op->get_attr<int64_t>("alg_kind")); dnnl_pops.append_eltwise(scale, alg, alpha, beta); } else if (fused_op_kind == op_kind::dnnl_binary) { const auto &extra_inputs = pop->get_unfused_input_indices(); if (extra_inputs.empty()) { // post-sum float scale = pop->get_scale(); int32_t zp = pop->get_zp(); dnnl_pops.append_sum(scale, zp); } else { // post-binary assertm(extra_inputs.size() == 1, "post-binary only has 1 extra input"); size_t src1_idx = extra_inputs[0]; auto input = op->get_input_value(src1_idx); auto md = make_dnnl_memory_desc(input->get_logical_tensor()); const auto alg = static_cast<dnnl::algorithm>( fused_op->get_attr<int64_t>("alg_kind")); dnnl_pops.append_binary(alg, md); } } else if (fused_op_kind == op_kind::dnnl_convolution) { const auto &extra_input_indices = pop->get_unfused_input_indices(); assertm(extra_input_indices.size() == 1, "post-conv dosen't support extra bias inputs now"); auto get_dnn_dt = [](const std::shared_ptr<impl::value_t> &val) { using ltw = impl::logical_tensor_wrapper_t; auto graph_dt = ltw(val->get_logical_tensor()).data_type(); return static_cast<dnnl::memory::data_type>(graph_dt); }; const size_t wei_idx = extra_input_indices[0]; const auto wei_dt = get_dnn_dt(op->get_input_value(wei_idx)); const auto dst_dt = get_dnn_dt(op->get_output_value(0)); const auto bia_dt = dnnl::memory::data_type::undef; const int mask = 0; const bool is_k3s1p1 = fused_op->get_attr<std::vector<int64_t>>("strides")[0] == 1; if (is_k3s1p1) { dnnl_pops.append_dw_k3s1p1(wei_dt, bia_dt, dst_dt, mask, {}); } else { dnnl_pops.append_dw_k3s2p1(wei_dt, bia_dt, dst_dt, mask, {}); } } else { // not reachable } } attr.set_post_ops(dnnl_pops); return attr; } } // namespace dnnl_impl } // namespace impl } // namespace graph } // namespace dnnl
39.402516
81
0.572546
[ "vector" ]
1678b754beeedc90e8cb3c6b3f04ae76388bb533
371
cc
C++
Question/最大步长可达性判断.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/最大步长可达性判断.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/最大步长可达性判断.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
//2 1 0 1 2 3 不能到达 //2 1 1 1 2 3 可以到达 bool CanGet(vector<int>& array){ int n = array.size(); vector<int> dp(n, 0); dp[0] = 1; for (int i = 0; i < n; i++){ if (dp[i] == 0){ continue; } for (int j = 1; j <= array[i]; j++){ int temp = i + j; if (temp < n){ dp[temp] = 1; } } } if (dp[n - 1]){ return true; } else{ return false; } }
12.366667
38
0.455526
[ "vector" ]
167ca79cb80e37557ab43ce3e89f38baf1ad5a07
1,702
cpp
C++
src/process.cpp
FrancoisSestier/CppND-System-Monitor-Project-Updated
44ea19e791b9924d671abd585085a685264af11c
[ "MIT" ]
null
null
null
src/process.cpp
FrancoisSestier/CppND-System-Monitor-Project-Updated
44ea19e791b9924d671abd585085a685264af11c
[ "MIT" ]
null
null
null
src/process.cpp
FrancoisSestier/CppND-System-Monitor-Project-Updated
44ea19e791b9924d671abd585085a685264af11c
[ "MIT" ]
null
null
null
#include "process.h" #include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "linux_parser.h" using std::string; using std::to_string; using std::vector; // TODO: Return this process's ID int Process::Pid() const { return pid_; } // TODO: Return this process's CPU utilization float Process::CpuUtilization() const { auto cpuStat = LinuxParser::CpuUtilization(pid_); float totalTime = cpuStat[LinuxParser::PidCPUStats::utime_] + cpuStat[LinuxParser::PidCPUStats::stime_] + cpuStat[LinuxParser::PidCPUStats::cstime_] + cpuStat[LinuxParser::PidCPUStats::cutime_]; auto cpuTime = totalTime / static_cast<float>(sysconf(_SC_CLK_TCK)); auto upTime = UpTime(); if (upTime == 0) { upTime = 1; }; auto cpuPercentage = 100.f * (cpuTime / upTime); return cpuPercentage; } // TODO: Return the command that generated this process string Process::Command() const { return command_; } // TODO: Return this process's memory utilization string Process::Ram() const { return LinuxParser::Ram(pid_); } // TODO: Return the user (name) that generated this process string Process::User() const { return user_; } // TODO: Return the age of this process (in seconds) long int Process::UpTime() const { return LinuxParser::UpTime() - startTime_; } // TODO: Overload the "less than" comparison operator for Process objects // REMOVE: [[maybe_unused]] once you define the function bool Process::operator<(const Process& other) const { return this->CpuUtilization() > other.CpuUtilization(); } bool Process::operator==(const Process& other) const { return this->Pid() == other.Pid(); };
30.392857
79
0.698002
[ "vector" ]
1682abf314bd87b36724ae2a8cf1f4ff1b7cd8f5
4,004
cpp
C++
src/utils/Buffer.cpp
xDimon/primitive
092e9158444710cdde45c57c4115efa06c85e161
[ "Apache-2.0" ]
12
2017-09-12T20:47:16.000Z
2019-04-05T11:39:40.000Z
src/utils/Buffer.cpp
xDimon/primitive
092e9158444710cdde45c57c4115efa06c85e161
[ "Apache-2.0" ]
null
null
null
src/utils/Buffer.cpp
xDimon/primitive
092e9158444710cdde45c57c4115efa06c85e161
[ "Apache-2.0" ]
1
2018-11-23T16:51:55.000Z
2018-11-23T16:51:55.000Z
// Copyright © 2017-2019 Dmitriy Khaustov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: Dmitriy Khaustov aka xDimon // Contacts: khaustov.dm@gmail.com // File created on: 2017.02.28 // Buffer.cpp #include "Buffer.hpp" #include <algorithm> #include <cstring> Buffer::Buffer() : _getPosition(0) , _putPosition(0) { } const std::vector<char>& Buffer::data() { std::lock_guard<std::recursive_mutex> guard(_mutex); // Если есть прочитанные данные в начале буффера if (_getPosition > 0) { // Смещаем непрочитанные данные в начало буффера std::copy_n(_data.cbegin() + _getPosition, _putPosition - _getPosition, _data.begin()); _putPosition -= _getPosition; _getPosition = 0; // Отбрасываем неиспользуемое пространство _data.resize(_putPosition); } return _data; } const char *Buffer::dataPtr() const { std::lock_guard<std::recursive_mutex> guard(_mutex); return _data.data() + _getPosition; } size_t Buffer::dataLen() const { std::lock_guard<std::recursive_mutex> guard(_mutex); return _putPosition - _getPosition; } char *Buffer::spacePtr() const { std::lock_guard<std::recursive_mutex> guard(_mutex); return const_cast<char *>(_data.data()) + _putPosition; } size_t Buffer::spaceLen() const { std::lock_guard<std::recursive_mutex> guard(_mutex); return _data.size() - _putPosition; } size_t Buffer::size() const { std::lock_guard<std::recursive_mutex> guard(_mutex); return _data.size(); } bool Buffer::show(void *data, size_t length) const { if (length == 0) { return true; } std::lock_guard<std::recursive_mutex> guard(_mutex); if (_putPosition - _getPosition < length) { return false; } memcpy(data, _data.data() + _getPosition, length); return true; } bool Buffer::skip(size_t length) { if (length == 0) { return true; } std::lock_guard<std::recursive_mutex> guard(_mutex); if (_putPosition - _getPosition < length) { return false; } _getPosition += length; return true; } bool Buffer::read(void *data_, size_t length) { if (length == 0) { return true; } std::lock_guard<std::recursive_mutex> guard(_mutex); if (_putPosition - _getPosition < length) { return false; } auto data = static_cast<char *>(data_); while (length-- > 0) { *data++ = _data[_getPosition++]; } return true; } bool Buffer::prepare(size_t length) { if (length == 0) { return true; } std::lock_guard<std::recursive_mutex> guard(_mutex); // Недостаточно места в конце буффера if (_putPosition + length > _data.size()) { // Если есть прочитанные данные в начале буффера if (_getPosition > 0) { // Смещаем непрочитанные данные в начало буффера std::copy_n(_data.cbegin() + _getPosition, _putPosition - _getPosition, _data.begin()); _putPosition -= _getPosition; _getPosition = 0; } } // Все еще недостаточно места в конце буффера if (_putPosition + length > _data.size()) { _data.resize(((_putPosition + length) / (1ull<<12) + 1) * (1ull<<12)); } return true; } bool Buffer::forward(size_t length) { if (length == 0) { return true; } std::lock_guard<std::recursive_mutex> guard(_mutex); if (length > spaceLen()) { return false; } _putPosition += length; return true; } bool Buffer::write(const void *data_, size_t length) { if (length == 0) { return true; } std::lock_guard<std::recursive_mutex> guard(_mutex); prepare(length); auto data = static_cast<const char *>(data_); while (length-- > 0) { _data[_putPosition++] = *data++; } return true; }
20.222222
90
0.695055
[ "vector" ]
168614d8ad8215248fcfa6334cc57640c9a798df
2,216
cpp
C++
deps/CoinQ/src/CoinQ_jsonrpc.cpp
anypath/CoinVault
ec9fb9bdf557086b8bcad273c232319ed04442b9
[ "Unlicense", "OpenSSL", "MIT" ]
null
null
null
deps/CoinQ/src/CoinQ_jsonrpc.cpp
anypath/CoinVault
ec9fb9bdf557086b8bcad273c232319ed04442b9
[ "Unlicense", "OpenSSL", "MIT" ]
null
null
null
deps/CoinQ/src/CoinQ_jsonrpc.cpp
anypath/CoinVault
ec9fb9bdf557086b8bcad273c232319ed04442b9
[ "Unlicense", "OpenSSL", "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // CoinQ_jsonrpc.cpp // // Copyright (c) 2013 Eric Lombrozo // // All Rights Reserved. #include "CoinQ_jsonrpc.h" using namespace CoinQ::JsonRpc; void Request::setJson(const std::string& json) { json_spirit::Value value; json_spirit::read_string(json, value); if (value.type() != json_spirit::obj_type) { throw std::runtime_error("Invalid JSON."); } const json_spirit::Object& obj = value.get_obj(); const json_spirit::Value& method = json_spirit::find_value(obj, "method"); if (method.type() != json_spirit::str_type) { throw std::runtime_error("Missing method."); } m_method = method.get_str(); m_params = json_spirit::find_value(obj, "params"); m_id = json_spirit::find_value(obj, "id"); } std::string Request::getJson() const { json_spirit::Object req; req.push_back(json_spirit::Pair("method", m_method)); req.push_back(json_spirit::Pair("params", m_params)); req.push_back(json_spirit::Pair("id", m_id)); return json_spirit::write_string<json_spirit::Value>(req); } void Response::setJson(const std::string& json) { json_spirit::Value value; json_spirit::read_string(json, value); if (value.type() != json_spirit::obj_type) { throw std::runtime_error("Invalid JSON."); } const json_spirit::Object& obj = value.get_obj(); m_result = json_spirit::find_value(obj, "result"); m_error = json_spirit::find_value(obj, "error"); m_id = json_spirit::find_value(obj, "id"); } std::string Response::getJson() const { json_spirit::Object res; res.push_back(json_spirit::Pair("result", m_result)); res.push_back(json_spirit::Pair("error", m_error)); res.push_back(json_spirit::Pair("id", m_id)); return json_spirit::write_string<json_spirit::Value>(res); } void Response::setResult(const json_spirit::Value& result, const json_spirit::Value& id) { m_result = result; m_error = json_spirit::Value(); m_id = id; } void Response::setError(const json_spirit::Value& error, const json_spirit::Value& id) { m_result = json_spirit::Value(); m_error = error; m_id = id; }
28.410256
88
0.650722
[ "object" ]
1692f3d52572b45e010d2d51edcf7436f6d5ded9
6,127
hpp
C++
include/workload/workload.hpp
tanner-andrulis/timeloop
acf4dc7fa0e34ff2fa788ba20a0842d1b5b97951
[ "BSD-3-Clause" ]
1
2022-03-05T03:07:51.000Z
2022-03-05T03:07:51.000Z
include/workload/workload.hpp
tanner-andrulis/timeloop
acf4dc7fa0e34ff2fa788ba20a0842d1b5b97951
[ "BSD-3-Clause" ]
null
null
null
include/workload/workload.hpp
tanner-andrulis/timeloop
acf4dc7fa0e34ff2fa788ba20a0842d1b5b97951
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include "loop-analysis/point-set.hpp" #include "compound-config/compound-config.hpp" #include "shape-models/problem-shape.hpp" #include "density-models/density-distribution.hpp" #include "density-models/density-distribution-factory.hpp" namespace problem { // ======================================== // // Shape instance // // ======================================== // // Sadly, this has to be a static instance outside Workload for now // because a large section of the codebase was written assuming there would // only be one active shape instance. To fix this, we need to make the shape // instance a member of Workload, and pass pointers to the Workload // object *everywhere*. The most problematic classes are PerDataSpace and // PerFlattenedDimension. If we can figure out a clean implementation of these // classes that does not require querying Shape::NumDimensions or // Shape::NumDataSpaces then most of the problem is possibly solved. const Shape* GetShape(); // ======================================== // // Workload // // ======================================== // class Workload { public: typedef std::map<Shape::FactorizedDimensionID, Coordinate> FactorizedBounds; typedef std::map<Shape::FlattenedDimensionID, Coordinate> FlattenedBounds; typedef std::map<Shape::CoefficientID, int> Coefficients; typedef std::map<Shape::DataSpaceID, std::shared_ptr<DensityDistribution>> Densities; protected: FactorizedBounds factorized_bounds_; FlattenedBounds flattened_bounds_; Coefficients coefficients_; Densities densities_; bool workload_tensor_size_set_ = false; bool default_dense_ = true; public: Workload() {} const Shape* GetShape() const { // Just a trampolene to the global function at the moment. return problem::GetShape(); } int GetFactorizedBound(Shape::FactorizedDimensionID dim) const { return factorized_bounds_.at(dim); } int GetFlattenedBound(Shape::FlattenedDimensionID dim) const { return flattened_bounds_.at(dim); } Point GetFactorizedBounds() const { // Pack all bounds into a point representation. auto num_dimensions = GetShape()->NumFactorizedDimensions; Point bounds(num_dimensions); for (unsigned dim = 0; dim < num_dimensions; dim++) { bounds[dim] = factorized_bounds_.at(dim); } return bounds; } int GetCoefficient(Shape::CoefficientID p) const { return coefficients_.at(p); } std::shared_ptr<DensityDistribution> GetDensity(Shape::DataSpaceID pv) const { return densities_.at(pv); } bool GetDenseDefaultTensor() const { return default_dense_; } void DeriveFlattenedBounds() { for (unsigned i = 0; i < GetShape()->NumFlattenedDimensions; i++) { auto& factorized_dimensions = GetShape()->FlattenedToFactorized.at(i); flattened_bounds_[i] = 1; for (auto factorized_dim: factorized_dimensions) flattened_bounds_[i] *= factorized_bounds_.at(factorized_dim); } } void SetFactorizedBounds(const FactorizedBounds& factorized_bounds) { factorized_bounds_ = factorized_bounds; DeriveFlattenedBounds(); } // void SetFlattenedBounds(const FlattenedBounds& flattened_bounds) // { // flattened_bounds_ = flattened_bounds; // } void SetCoefficients(const Coefficients& coefficients) { coefficients_ = coefficients; } void SetDensities(const Densities& densities) { densities_ = densities; } void SetWorkloadTensorSize(problem::Shape::DataSpaceID id, problem::DataSpace& point_set) { densities_.at(id)->SetWorkloadTensorSize(point_set); } bool IsWorkloadTensorSizesSet() { return workload_tensor_size_set_; } void AllTensorsSet() { workload_tensor_size_set_ = true; } void SetDefaultDenseTensorFlag(const bool flag) { default_dense_ = flag; } private: // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int version = 0) { if (version == 0) { ar& BOOST_SERIALIZATION_NVP(factorized_bounds_); ar& BOOST_SERIALIZATION_NVP(coefficients_); ar& BOOST_SERIALIZATION_NVP(densities_); } } }; void ParseWorkload(config::CompoundConfigNode config, Workload& workload); void ParseWorkloadInstance(config::CompoundConfigNode config, Workload& workload); } // namespace problem
31.582474
91
0.711768
[ "object", "shape" ]