hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
225cbc1165f4d8ebe4aad018a0bded7ee16a7ee4
8,733
cpp
C++
iotcloud/src/v20210408/model/CertInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
iotcloud/src/v20210408/model/CertInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
iotcloud/src/v20210408/model/CertInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * 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/iotcloud/v20210408/model/CertInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Iotcloud::V20210408::Model; using namespace std; CertInfo::CertInfo() : m_certNameHasBeenSet(false), m_certSNHasBeenSet(false), m_issuerNameHasBeenSet(false), m_subjectHasBeenSet(false), m_createTimeHasBeenSet(false), m_effectiveTimeHasBeenSet(false), m_expireTimeHasBeenSet(false), m_certTextHasBeenSet(false) { } CoreInternalOutcome CertInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("CertName") && !value["CertName"].IsNull()) { if (!value["CertName"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CertName` IsString=false incorrectly").SetRequestId(requestId)); } m_certName = string(value["CertName"].GetString()); m_certNameHasBeenSet = true; } if (value.HasMember("CertSN") && !value["CertSN"].IsNull()) { if (!value["CertSN"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CertSN` IsString=false incorrectly").SetRequestId(requestId)); } m_certSN = string(value["CertSN"].GetString()); m_certSNHasBeenSet = true; } if (value.HasMember("IssuerName") && !value["IssuerName"].IsNull()) { if (!value["IssuerName"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.IssuerName` IsString=false incorrectly").SetRequestId(requestId)); } m_issuerName = string(value["IssuerName"].GetString()); m_issuerNameHasBeenSet = true; } if (value.HasMember("Subject") && !value["Subject"].IsNull()) { if (!value["Subject"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.Subject` IsString=false incorrectly").SetRequestId(requestId)); } m_subject = string(value["Subject"].GetString()); m_subjectHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CreateTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_createTime = value["CreateTime"].GetUint64(); m_createTimeHasBeenSet = true; } if (value.HasMember("EffectiveTime") && !value["EffectiveTime"].IsNull()) { if (!value["EffectiveTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `CertInfo.EffectiveTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_effectiveTime = value["EffectiveTime"].GetUint64(); m_effectiveTimeHasBeenSet = true; } if (value.HasMember("ExpireTime") && !value["ExpireTime"].IsNull()) { if (!value["ExpireTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `CertInfo.ExpireTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_expireTime = value["ExpireTime"].GetUint64(); m_expireTimeHasBeenSet = true; } if (value.HasMember("CertText") && !value["CertText"].IsNull()) { if (!value["CertText"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CertText` IsString=false incorrectly").SetRequestId(requestId)); } m_certText = string(value["CertText"].GetString()); m_certTextHasBeenSet = true; } return CoreInternalOutcome(true); } void CertInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_certNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_certName.c_str(), allocator).Move(), allocator); } if (m_certSNHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertSN"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_certSN.c_str(), allocator).Move(), allocator); } if (m_issuerNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "IssuerName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_issuerName.c_str(), allocator).Move(), allocator); } if (m_subjectHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Subject"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_subject.c_str(), allocator).Move(), allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_createTime, allocator); } if (m_effectiveTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EffectiveTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_effectiveTime, allocator); } if (m_expireTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExpireTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_expireTime, allocator); } if (m_certTextHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertText"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_certText.c_str(), allocator).Move(), allocator); } } string CertInfo::GetCertName() const { return m_certName; } void CertInfo::SetCertName(const string& _certName) { m_certName = _certName; m_certNameHasBeenSet = true; } bool CertInfo::CertNameHasBeenSet() const { return m_certNameHasBeenSet; } string CertInfo::GetCertSN() const { return m_certSN; } void CertInfo::SetCertSN(const string& _certSN) { m_certSN = _certSN; m_certSNHasBeenSet = true; } bool CertInfo::CertSNHasBeenSet() const { return m_certSNHasBeenSet; } string CertInfo::GetIssuerName() const { return m_issuerName; } void CertInfo::SetIssuerName(const string& _issuerName) { m_issuerName = _issuerName; m_issuerNameHasBeenSet = true; } bool CertInfo::IssuerNameHasBeenSet() const { return m_issuerNameHasBeenSet; } string CertInfo::GetSubject() const { return m_subject; } void CertInfo::SetSubject(const string& _subject) { m_subject = _subject; m_subjectHasBeenSet = true; } bool CertInfo::SubjectHasBeenSet() const { return m_subjectHasBeenSet; } uint64_t CertInfo::GetCreateTime() const { return m_createTime; } void CertInfo::SetCreateTime(const uint64_t& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool CertInfo::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } uint64_t CertInfo::GetEffectiveTime() const { return m_effectiveTime; } void CertInfo::SetEffectiveTime(const uint64_t& _effectiveTime) { m_effectiveTime = _effectiveTime; m_effectiveTimeHasBeenSet = true; } bool CertInfo::EffectiveTimeHasBeenSet() const { return m_effectiveTimeHasBeenSet; } uint64_t CertInfo::GetExpireTime() const { return m_expireTime; } void CertInfo::SetExpireTime(const uint64_t& _expireTime) { m_expireTime = _expireTime; m_expireTimeHasBeenSet = true; } bool CertInfo::ExpireTimeHasBeenSet() const { return m_expireTimeHasBeenSet; } string CertInfo::GetCertText() const { return m_certText; } void CertInfo::SetCertText(const string& _certText) { m_certText = _certText; m_certTextHasBeenSet = true; } bool CertInfo::CertTextHasBeenSet() const { return m_certTextHasBeenSet; }
27.121118
140
0.675255
suluner
225d27d248e883e0c054df3a946207a9526d4dc9
4,619
cpp
C++
Source/CheatSheetUI/Private/UI/UI_CheatView.cpp
tomshinton/CheatSheetPlugin
2d2f8d7b7b6370a2815315c0bb21c613a915ee39
[ "MIT" ]
8
2022-02-03T18:09:23.000Z
2022-02-09T16:05:28.000Z
Source/CheatSheetUI/Private/UI/UI_CheatView.cpp
tomshinton/CheatSheetPlugin
2d2f8d7b7b6370a2815315c0bb21c613a915ee39
[ "MIT" ]
null
null
null
Source/CheatSheetUI/Private/UI/UI_CheatView.cpp
tomshinton/CheatSheetPlugin
2d2f8d7b7b6370a2815315c0bb21c613a915ee39
[ "MIT" ]
null
null
null
// CheatSheet Plugin - Tom Shinton 2019 #include "CheatSheetUI/Public/UI/UI_CheatView.h" #include "CheatSheetUI/Public/UI/Entries/UI_CategoryEntry.h" #include "CheatSheetUI/Public/UI/Entries/UI_CheatEntry.h" #include <Runtime/UMG/Public/Components/ScrollBox.h> #include <Runtime/UMG/Public/Components/VerticalBox.h> DEFINE_LOG_CATEGORY_STATIC(CheatViewLog, Log, Log); UUI_CheatView::UUI_CheatView(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , CategoryBox(nullptr) , CheatBox(nullptr) , CheatScrollBox(nullptr) , CheatCategoryClass(nullptr) , CheatEntryClass(nullptr) , Categories() , OnNewCategoryRequested() , OnNewSelection() , RequestCallback(nullptr) , Entries() , CurrentSelection() , CurrentSelectionIndex(0) , TotalEntries(0) {} void UUI_CheatView::NativeConstruct() { Super::NativeConstruct(); RequestCallback = [WeakThis = TWeakObjectPtr<UUI_CheatView>(this), this](const FCheatCategory& InRequestingCategory) { if (WeakThis.IsValid()) { RequestViewForCategory(InRequestingCategory); } }; } void UUI_CheatView::RequestViewForCategory(const FCheatCategory& InCheatCategory) { TotalEntries = 0; CurrentSelectionIndex = 0; if (CategoryBox != nullptr && CheatBox != nullptr) { if (CheatCategoryClass != nullptr && CheatEntryClass != nullptr) { CategoryBox->ClearChildren(); CheatBox->ClearChildren(); const TArray<FCheatCategory> CachedCategories = InCheatCategory.GetSubCategories(); for (const FCheatCategory& Category : CachedCategories) { UUI_CategoryEntry* NewCategory = CreateWidget<UUI_CategoryEntry>(this, CheatCategoryClass); NewCategory->SetCategory(Category); NewCategory->SetRequestCallback(RequestCallback); CategoryBox->AddChild(NewCategory); } const TArray<FCachedCheat> CachedCheats = InCheatCategory.GetCheats(); for (const FCachedCheat& Cheat : CachedCheats) { UUI_CheatEntry* NewCheat = CreateWidget<UUI_CheatEntry>(this, CheatEntryClass); NewCheat->SetCheat(Cheat); CheatBox->AddChild(NewCheat); } } } OnNewCategoryRequested.Broadcast(InCheatCategory); ApplyEntryNumbers(); ApplyNewSelectionIndex(); } void UUI_CheatView::RequestHomeView(const TArray<FCheatCategory>& InCheatCategories) { TotalEntries = 0; CurrentSelectionIndex = 0; if (CheatCategoryClass != nullptr) { if (CheatCategoryClass != nullptr && CheatEntryClass != nullptr) { CategoryBox->ClearChildren(); CheatBox->ClearChildren(); for (const FCheatCategory& Category : InCheatCategories) { UUI_CategoryEntry* NewCategory = CreateWidget<UUI_CategoryEntry>(this, CheatCategoryClass); NewCategory->SetCategory(Category); NewCategory->SetRequestCallback(RequestCallback); CategoryBox->AddChild(NewCategory); } } } ApplyEntryNumbers(); ApplyNewSelectionIndex(); } void UUI_CheatView::SynchronizeProperties() { Super::SynchronizeProperties(); RequestHomeView(Categories); } void UUI_CheatView::ConfirmSelection() { if (CurrentSelection.IsValid()) { CurrentSelection->ExecuteEntry(); } } void UUI_CheatView::UpSelection() { CurrentSelectionIndex == 0 ? CurrentSelectionIndex = TotalEntries - 1 : CurrentSelectionIndex--; ApplyNewSelectionIndex(); } void UUI_CheatView::DownSelection() { CurrentSelectionIndex == TotalEntries - 1 ? CurrentSelectionIndex = 0 : CurrentSelectionIndex++; ApplyNewSelectionIndex(); } void UUI_CheatView::ApplyEntryNumbers() { if (CheatBox != nullptr && CategoryBox != nullptr) { for (int32 i = 0; i < CategoryBox->GetChildrenCount(); ++i) { UWidget* Child = CategoryBox->GetChildAt(i); if (ICheatEntryInterface* Entry = Cast<ICheatEntryInterface>(Child)) { Entry->SetEntryNumber(TotalEntries); Entries.Add(TotalEntries, Entry); TotalEntries++; } } for (int32 i = 0; i < CheatBox->GetChildrenCount(); ++i) { UWidget* Child = CheatBox->GetChildAt(i); if (ICheatEntryInterface* Entry = Cast<ICheatEntryInterface>(Child)) { Entry->SetEntryNumber(TotalEntries); Entries.Add(TotalEntries, Entry); TotalEntries++; } } } } void UUI_CheatView::ApplyNewSelectionIndex() { const TWeakInterfacePtr<ICheatEntryInterface> OldSelection = CurrentSelection; if (CurrentSelection.IsValid()) { CurrentSelection->SetIsSelected(false); } CurrentSelection = Entries[CurrentSelectionIndex]; if (CurrentSelection.IsValid()) { CurrentSelection->SetIsSelected(true); OnNewSelection.Broadcast(OldSelection, CurrentSelection); if(CheatScrollBox != nullptr) { CheatScrollBox->ScrollWidgetIntoView(&CurrentSelection->GetWidget()); } } }
24.833333
117
0.746698
tomshinton
2262f39071bd2012923504ddb5dbbab5aed024f3
2,102
cpp
C++
0rgb/example_2/src/inversecolorpsaceadjustement.cpp
Enkelena/oRGB
c7e250f0a28b8db073d60c05f693ad15489e271e
[ "MIT" ]
null
null
null
0rgb/example_2/src/inversecolorpsaceadjustement.cpp
Enkelena/oRGB
c7e250f0a28b8db073d60c05f693ad15489e271e
[ "MIT" ]
null
null
null
0rgb/example_2/src/inversecolorpsaceadjustement.cpp
Enkelena/oRGB
c7e250f0a28b8db073d60c05f693ad15489e271e
[ "MIT" ]
null
null
null
#include "inversecolorpsaceadjustement.hpp" Eigen::Matrix3d Inverse::rotatePoint(double angle) { Eigen::Matrix3d _matrix; _matrix << 1, 0, 0, 0, 1, 0, 0, 0, 1; _matrix(1,1) = cos(angle * M_PI / 180); _matrix(1,2) = -sin(angle * M_PI / 180); _matrix(2,1) = sin(angle * M_PI / 180); _matrix(2,2) = cos(angle * M_PI / 180); return _matrix; } cv::Mat Inverse::fullRotation(cv::Mat img1) { double thetaAngle=0; double r{0},b{0},g{0}; cv::MatIterator_<cv::Vec3d> itd, end; for( itd=img1.begin<cv::Vec3d>(); itd!= img1.end<cv::Vec3d>();++itd) { r = (*itd)[0]; g = (*itd)[1]; b = (*itd)[2]; double theta = atan2(b, g); double newTheta=0; if (theta< M_PI / 2) { newTheta = (2/3)*theta; } if((theta>= (M_PI /3)) && (theta <=(5*M_PI/3))) { newTheta = M_PI/3 + 4/3*(theta-M_PI/2); } if((theta> 5*M_PI / 3) && (theta <(2*M_PI)) ) { newTheta = (2/3)*theta; } thetaAngle=(newTheta-theta); Eigen::Vector3d _local {r,g,b}; _local = rotatePoint(thetaAngle) * _local; (*itd)[0]=(_local[0]); (*itd)[1]=(_local[1]); (*itd)[2]=(_local[2]); } return img1; } cv::Mat Inverse::setlinearImage(cv::Mat img1) { Eigen::Matrix3d linear_matrix; linear_matrix << 1.0000, 0.1140, 0.7436, 1.0000, 0.1140, -0.4111, 1.0000, -0.8860,0.1663; double gamma = 2.2f; cv::MatIterator_<cv::Vec3d> itd, end; for( itd=img1.begin<cv::Vec3d>(); itd!= img1.end<cv::Vec3d>();++itd) { Eigen::Vector3d _local {(*itd)[0], (*itd)[1], (*itd)[2]}; _local = linear_matrix * _local; (*itd)[0]=(_local(0))*255; (*itd)[1]=(_local(1))*255; (*itd)[2]=(_local(2))*255; (*itd)[0] = pow((static_cast <double>((*itd)[0]) / 255.0 ),gamma)*255; (*itd)[1] = pow((static_cast <double>((*itd)[1]) / 255.0 ),gamma)*255; (*itd)[2] = pow((static_cast <double>((*itd)[2]) / 255.0 ),gamma)*255; } return img1; }
25.02381
77
0.508088
Enkelena
22656c72129a8c5d4c88865731b72bc0ae5aa42b
3,060
cpp
C++
placement/idea_place/cpp/main.cpp
rbarzic/MAGICAL
0510550b263913f8c62f46662a9dfa2ae94d2386
[ "BSD-3-Clause" ]
null
null
null
placement/idea_place/cpp/main.cpp
rbarzic/MAGICAL
0510550b263913f8c62f46662a9dfa2ae94d2386
[ "BSD-3-Clause" ]
null
null
null
placement/idea_place/cpp/main.cpp
rbarzic/MAGICAL
0510550b263913f8c62f46662a9dfa2ae94d2386
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************* > File Name: main.cpp > Author: Biying Xu > Mail: biying@utexas.edu > Created Time: Mon 04 Jun 2018 05:27:08 PM CDT ************************************************************************/ #include <iostream> #include <limbo/programoptions/ProgramOptions.h> #include <limbo/string/String.h> #include "nlp.h" using std::cout; using std::endl; int main(int argc, char** argv) { char buf[256]; sprintf(buf, "idea_place takes %%t seconds CPU, %%w seconds real\n"); boost::timer::auto_cpu_timer t (buf); // append options here typedef limbo::programoptions::ProgramOptions po_type; using limbo::programoptions::Value; bool help = false; std::string files_path; std::string techfile_path; std::string spacing_rules_path; std::string width_area_rules_path; std::string results_dir; std::string optimizer_type_str = "GUROBI"; OptimizerType optimizer_type = OptimizerType::GUROBI; po_type desc (std::string("Available options")); desc.add_option(Value<bool>("--help", &help, "print help message").default_value(help).help(true)) .add_option(Value<std::string>("--input", &files_path, "input files directory")) .add_option(Value<std::string>("--techfile", &techfile_path, "input technology file")) .add_option(Value<std::string>("--spacing", &spacing_rules_path, "input spacing rule file")) .add_option(Value<std::string>("--width_area", &width_area_rules_path, "input width and area rule file")) .add_option(Value<std::string>("--result", &results_dir, "output result directory")) .add_option(Value<std::string>("--optimizer", &optimizer_type_str, "optimization solver GUROBI|LPSOLVE").default_value(optimizer_type_str)) ; try { desc.parse(argc, argv); // print help message if (help) { cout << desc << "\n"; exit(1); } // post processing fileFormat if (limbo::iequals(optimizer_type_str, "GUROBI")) optimizer_type = OptimizerType::GUROBI; else if (limbo::iequals(optimizer_type_str, "LPSOLVE")) optimizer_type = OptimizerType::LPSOLVE; else { assert(0); } } catch (std::exception& e) { // print help message and error message cout << desc << "\n"; cout << e.what() << "\n"; return false; } cout<<"***** debugging parameters *****"<<endl; cout<<"techfile_path: "<<techfile_path<<endl; cout<<"spacing_rules_path: "<<spacing_rules_path<<endl; cout<<"width_area_rules_path: "<<width_area_rules_path<<endl; cout<<"files_path: "<<files_path<<endl; cout<<"results_dir: "<<results_dir<<endl; cout<<"optimizer_type: "<<optimizer_type_str<<endl; NLPlace placer(techfile_path, spacing_rules_path, width_area_rules_path, files_path, results_dir, optimizer_type); placer.run(); // placer.solve(); // placer.solve_unconstrained(); return 0; }
34.772727
147
0.616667
rbarzic
2268b62366ab8f11a3b140845f84a8b213ca6626
1,158
cpp
C++
recommender-systems/final-project/stringMethods.cpp
ramongonze/ufmg-practical-assignments
d85821e330a0f089a7601168bbbf8b4aef174f27
[ "MIT" ]
null
null
null
recommender-systems/final-project/stringMethods.cpp
ramongonze/ufmg-practical-assignments
d85821e330a0f089a7601168bbbf8b4aef174f27
[ "MIT" ]
null
null
null
recommender-systems/final-project/stringMethods.cpp
ramongonze/ufmg-practical-assignments
d85821e330a0f089a7601168bbbf8b4aef174f27
[ "MIT" ]
null
null
null
#ifndef _STRING_ #include "stringMethods.hpp" #endif using namespace std; string fixString(string s){ while(s.size() > 0 && s[0] == ' ') s = s.substr(1,s.size()); for(unsigned int i = 0; i < s.size(); i++) if(ispunct(s[i]) || (i < s.size()-1 && s[i] == ' ' && s[i+1] == ' ')) s.erase(i--, 1); else s[i] = tolower(s[i]); if(s[s.size()-1] == ' ') s.erase(s.size()-1, 1); return s; } Vs split(const string &s, char delimiter){ Vs tokens; string token; istringstream tokenStream(s); while (getline(tokenStream, token, delimiter)){ tokens.push_back(fixString(token)); } return tokens; } Vs split(string s, char delimiter, char delimiterIgnore){ Vs tokens; string word = ""; bool beginDelimiterIgnore = false; for(char& c : s){ if((c != delimiter && c != delimiterIgnore) || (c == delimiter && beginDelimiterIgnore == true)){ word += c; }else if(c == delimiter && beginDelimiterIgnore == false){ tokens.push_back(word); word = ""; }else if(c == delimiterIgnore){ if(beginDelimiterIgnore == true){ beginDelimiterIgnore = false; }else{ beginDelimiterIgnore = true; } } } return tokens; }
20.678571
99
0.609672
ramongonze
226903335861ddb3d4794320113d40a0e01ad7ba
548
cpp
C++
Development/Src/ALAudio/Src/ALAudio.cpp
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/Src/ALAudio/Src/ALAudio.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/Src/ALAudio/Src/ALAudio.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
/*============================================================================= ALAudio.cpp: Unreal OpenAL Audio package. Copyright 1999-2001 Epic Games, Inc. All Rights Reserved. Revision history: * Created by Daniel Vogel. * Ported to Linux by Ryan C. Gordon. =============================================================================*/ #include "ALAudioPrivate.h" /*----------------------------------------------------------------------------- The end. -----------------------------------------------------------------------------*/
34.25
79
0.308394
addstone
226c7b014b66da63b49119fed307734bbcca44b8
5,462
cpp
C++
src/component/renderer.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
2
2021-04-28T20:51:25.000Z
2021-04-28T20:51:38.000Z
src/component/renderer.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
src/component/renderer.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
#include "renderer.hpp" #include "../io/io.hpp" #include "transform.hpp" #include "../object/camera.hpp" Renderer::Renderer(std::shared_ptr<Model> model, std::shared_ptr<Material> material, GLenum render_mode) : Component("Renderer"), model(model), material(material), render_mode(render_mode), receive_shadow(true), display_texture(true) {} Renderer::Renderer(const Renderer& renderer) : Component(renderer), model(renderer.model->clone2()), material(renderer.material->clone()), render_mode(renderer.render_mode), receive_shadow(renderer.receive_shadow), display_texture(renderer.display_texture) {} std::shared_ptr<Renderer> Renderer::make_renderer(std::shared_ptr<Model> model, std::shared_ptr<Material> material, GLenum render_mode) { std::shared_ptr<Renderer> renderer(new Renderer(model, material, render_mode)); return renderer; } std::shared_ptr<Renderer> pepng::make_renderer(std::shared_ptr<Model> model, std::shared_ptr<Material> material, GLenum render_mode) { return Renderer::make_renderer(model, material, render_mode); } Renderer* Renderer::clone_implementation() { return new Renderer(*this); } void Renderer::init(std::shared_ptr<WithComponents> parent) { this->__transform = parent->get_component<Transform>(); if (this->__transform == nullptr) { std::stringstream ss; ss << *parent << " has no transform." << std::endl; std::cout << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void Renderer::render(std::shared_ptr<WithComponents> parent, GLuint shaderProgram) { if(!this->model->is_init()) this->model->delayed_init(); if(this->model->vao() == -1 || !this->active()) return; glUseProgram(shaderProgram); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, this->material->texture->gl_index()); glUniform1i( glGetUniformLocation(shaderProgram, "u_texture"), 1 ); GLuint uWorld = glGetUniformLocation(shaderProgram, "u_world"); if (uWorld >= 0) { auto worldMatrix = this->__transform->parent_matrix * glm::translate(glm::mat4(1.0f), this->model->offset()) * this->__transform->world_matrix() * glm::translate(glm::mat4(1.0f), -this->model->offset()); glUniformMatrix4fv( uWorld, 1, GL_FALSE, glm::value_ptr(worldMatrix) ); } GLuint uReceiveShadow = glGetUniformLocation(shaderProgram, "u_receive_shadow"); if(uReceiveShadow >= 0) { glUniform1f( uReceiveShadow, this->receive_shadow ); } GLuint uDisplayTexture = glGetUniformLocation(shaderProgram, "u_display_texture"); if(uDisplayTexture >= 0) { glUniform1f( uDisplayTexture, this->display_texture ); } glBindVertexArray(this->model->vao()); if(this->model->has_element_array()) { glDrawElements( this->render_mode, this->model->count(), GL_UNSIGNED_INT, 0 ); } else { glDrawArrays( this->render_mode, 0, this->model->count() ); } } void Renderer::render(std::shared_ptr<WithComponents> parent) { auto shaderProgram = this->material->shader_program(); glUseProgram(shaderProgram); if(Camera::current_camera == nullptr) { std::cout << "No current camera set." << std::endl; throw std::runtime_error("No current camera set."); } Camera::current_camera->render(shaderProgram); for(auto light : Light::lights) { light->render(shaderProgram); } this->render(parent, shaderProgram); } #ifdef IMGUI void Renderer::imgui() { Component::imgui(); ImGui::LabelText("Name", this->model->name().c_str()); std::stringstream ss; ss << this->model->count(); ImGui::LabelText("Index Count", ss.str().c_str()); const char* items[] = { "Lines", "Points", "Triangles" }; static int item_current_idx = -1; if (item_current_idx == -1) { switch(this->render_mode) { case GL_TRIANGLES: item_current_idx = 2; break; case GL_POINTS: item_current_idx = 1; break; case GL_LINES: item_current_idx = 0; } } const char* combo_label = items[item_current_idx]; if (ImGui::BeginCombo("Mode", combo_label)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { const bool is_selected = (item_current_idx == n); if (ImGui::Selectable(items[n], is_selected)) { item_current_idx = n; switch(item_current_idx) { case 2: this->render_mode = GL_TRIANGLES; break; case 1: this->render_mode = GL_POINTS; break; case 0: this->render_mode = GL_LINES; break; } } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } ImGui::Checkbox("Texture", &this->display_texture); ImGui::Checkbox("Shadow", &this->receive_shadow); } #endif
27.174129
137
0.584401
pepng-CU
226e61ddb34305690040a52e48dc35f82d3e7422
42
cpp
C++
lab3/smarttree/main.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
lab3/smarttree/main.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
lab3/smarttree/main.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
// // Created by adrja on 22.03.2018. //
8.4
34
0.571429
Adrjanjan
227142a71df76ed4b47ffc680d9db3ce94ea0582
3,803
cpp
C++
src/serac/physics/utilities/state_manager.cpp
jamiebramwell/serac
a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962
[ "BSD-3-Clause" ]
1
2021-07-21T05:34:18.000Z
2021-07-21T05:34:18.000Z
src/serac/physics/utilities/state_manager.cpp
jamiebramwell/serac
a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962
[ "BSD-3-Clause" ]
null
null
null
src/serac/physics/utilities/state_manager.cpp
jamiebramwell/serac
a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019-2021, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "serac/physics/utilities/state_manager.hpp" namespace serac { // Definition of extern variable QuadratureData<void> dummy_qdata; // Initialize StateManager's static members - both of these will be fully initialized in StateManager::initialize std::optional<axom::sidre::MFEMSidreDataCollection> StateManager::datacoll_; bool StateManager::is_restart_ = false; std::string StateManager::collection_name_ = ""; std::vector<std::unique_ptr<SyncableData>> StateManager::syncable_data_; void StateManager::initialize(axom::sidre::DataStore& ds, const std::string& collection_name_prefix, const std::optional<int> cycle_to_load) { // If the global object has already been initialized, clear it out if (datacoll_) { reset(); } collection_name_ = collection_name_prefix + "_datacoll"; auto global_grp = ds.getRoot()->createGroup(collection_name_ + "_global"); auto bp_index_grp = global_grp->createGroup("blueprint_index/" + collection_name_); auto domain_grp = ds.getRoot()->createGroup(collection_name_); // Needs to be configured to own the mesh data so all mesh data is saved to datastore/output file const bool owns_mesh_data = true; datacoll_.emplace(collection_name_, bp_index_grp, domain_grp, owns_mesh_data); datacoll_->SetComm(MPI_COMM_WORLD); if (cycle_to_load) { is_restart_ = true; // NOTE: Load invalidates previous Sidre pointers datacoll_->Load(*cycle_to_load); datacoll_->SetGroupPointers( ds.getRoot()->getGroup(collection_name_ + "_global/blueprint_index/" + collection_name_), ds.getRoot()->getGroup(collection_name_)); SLIC_ERROR_ROOT_IF(datacoll_->GetBPGroup()->getNumGroups() == 0, "Loaded datastore is empty, was the datastore created on a " "different number of nodes?"); datacoll_->UpdateStateFromDS(); datacoll_->UpdateMeshAndFieldsFromDS(); } else { datacoll_->SetCycle(0); // Iteration counter datacoll_->SetTime(0.0); // Simulation time } } FiniteElementState StateManager::newState(FiniteElementState::Options&& options) { SLIC_ERROR_ROOT_IF(!datacoll_, "Serac's datacollection was not initialized - call StateManager::initialize first"); const std::string name = options.name; if (is_restart_) { auto field = datacoll_->GetParField(name); return {mesh(), *field, name}; } else { SLIC_ERROR_ROOT_IF(datacoll_->HasField(name), fmt::format("Serac's datacollection was already given a field named '{0}'", name)); options.alloc_gf = false; FiniteElementState state(mesh(), std::move(options)); datacoll_->RegisterField(name, &(state.gridFunc())); // Now that it's been allocated, we can set it to zero state.gridFunc() = 0.0; return state; } } void StateManager::save(const double t, const int cycle) { SLIC_ERROR_ROOT_IF(!datacoll_, "Serac's datacollection was not initialized - call StateManager::initialize first"); for (const auto& data : syncable_data_) { data->sync(); } datacoll_->SetTime(t); datacoll_->SetCycle(cycle); datacoll_->Save(); } void StateManager::setMesh(std::unique_ptr<mfem::ParMesh> mesh) { datacoll_->SetMesh(mesh.release()); datacoll_->SetOwnData(true); } mfem::ParMesh& StateManager::mesh() { auto mesh = datacoll_->GetMesh(); SLIC_ERROR_ROOT_IF(!mesh, "The datastore does not contain a mesh object"); return static_cast<mfem::ParMesh&>(*mesh); } } // namespace serac
37.653465
117
0.694715
jamiebramwell
2273033cd933efe7c3bf84b88d905cdd3636dda4
2,582
cpp
C++
DAA Lab/krus.cpp
mayank-kumar-giri/Competitive-Coding
4cd26ede051bad15bf25cfd037317c313b607507
[ "MIT" ]
null
null
null
DAA Lab/krus.cpp
mayank-kumar-giri/Competitive-Coding
4cd26ede051bad15bf25cfd037317c313b607507
[ "MIT" ]
null
null
null
DAA Lab/krus.cpp
mayank-kumar-giri/Competitive-Coding
4cd26ede051bad15bf25cfd037317c313b607507
[ "MIT" ]
null
null
null
#include<iostream> #include"merge.c" #include"bs.cpp" #include<cstdlib> #define maxim 1000000 using namespace std; int main() { int n; cout<<"\nEnter no. of vertices "; cin>>n; char v[n]; int ad[n][n],org[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { ad[i][j]=maxim; } } int min_i=0,min_j=0; cout<<"\nEnter the name of vertices(1 char only)\n"; for(int i=0;i<n;i++) cin>>v[i]; cout<<"\nEnter the name of vertices between which there is an edge along with its weight\n"; char r='y',s,e; int w=0,is,ie,f=0,g=0; while(r!='n') { cin>>s>>e>>w; f=0; g=0; for(int i=0;i<n;i++) { if(f==1 && g==1) break; if(s==v[i]) { is=i; f=1; } if(e==v[i]) { ie=i; g=1; } } if(f==1 &&g==1) { if(ad[is][ie]>w) { ad[is][ie]=w; org[is][ie]=w; } } else cout<<"\nThere are no such vertices! :-("; cout<<"\nWanna continue(y/n)??"; cin>>r; } const int z=(n*(n+1)); int cis[z],mcost=0,temp,k=0; for(int i=0;i<z;i++) cis[i]=-1; for(int i=0;i<n;i++) { f=0; g=0; min_i=0; min_j=0; int mini=ad[0][0]; ad[0][0]=maxim; for(int m=0;m<n;m++) { for(int j=1+m;j<n;j++) { if(ad[m][j]<mini) { mini=ad[m][j]; min_i=m; min_j=j; } } } int x=ad[min_i][min_j]; ad[min_i][min_j]=maxim; temp=x; if(i>=1) { for(int l=0;l<k;l++) { if(f==1 & g==1) break; if(min_i==cis[l]) { f=1; } if(min_j==cis[l]) { g=1; } } } if(f==1&&g==1) continue; cis[k]=min_i; cis[k+1]=min_j; k=k+2; mcost=mcost+temp; } cout<<"\nThe Minimal Spanning Tree of the I/P graph by Kruskal's contains following edges: \n"; for(int i=0;i<(2*n - 2);i+=2) { cout<<endl<<v[cis[i]]<<v[cis[i+1]]<<" with weight "<<org[cis[i]][cis[i+1]]<<"\n"; } cout<<"\nAnd the cost of this MST is "<<mcost<<"!\n"; }
22.258621
99
0.358637
mayank-kumar-giri
2274b38223ec0101805591c9d00f091faada64f5
148
cpp
C++
src/chess/tweenable.cpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
null
null
null
src/chess/tweenable.cpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
1
2021-07-25T15:54:27.000Z
2021-07-25T15:54:27.000Z
src/chess/tweenable.cpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
null
null
null
#include "tweenable.hpp" void Tweenable::update(float delta_time) { if (done()) { return; } m_t += delta_time / m_duration; }
13.454545
40
0.594595
delveam
22768f05debe929a3112e1e8c69e158092ec23f2
2,536
cpp
C++
Source/MapGenerator/Utils/MapEditorUtils.cpp
benoitestival/MapModuleEditor
3a7d72d0dc3761bd61f19df1e5af46081a791356
[ "MIT" ]
null
null
null
Source/MapGenerator/Utils/MapEditorUtils.cpp
benoitestival/MapModuleEditor
3a7d72d0dc3761bd61f19df1e5af46081a791356
[ "MIT" ]
null
null
null
Source/MapGenerator/Utils/MapEditorUtils.cpp
benoitestival/MapModuleEditor
3a7d72d0dc3761bd61f19df1e5af46081a791356
[ "MIT" ]
1
2021-07-07T09:22:28.000Z
2021-07-07T09:22:28.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "MapEditorUtils.h" #include "MapGenerator/GameMode/EditorGameMode.h" #include "MapGenerator/MapActor.h" #include "MapGenerator/Objects/BaseMapManager.h" #include "MapGenerator/HeightMapLandscape/LandscapeManager.h" #include "MapGenerator/Volumetric3DTerrain/Volumetric3DTerrainManager.h" #include "MapGenerator/HeightMapPlanet/HeightMapPlanetManager.h" TEnumAsByte<EMapType> UMapEditorUtils::DefaultMapType = EMapType::ProceduralLandscape; TEnumAsByte<EMapType> UMapEditorUtils::ActualMapType = UMapEditorUtils::DefaultMapType; TMap<EMapType, UClass*> UMapEditorUtils::ManagerRegistry = TMap<EMapType, UClass*>(); TMap<EMapType, FString> UMapEditorUtils::ModeName = TMap<EMapType, FString>(); bool UMapEditorUtils::IsRunning = false; void UMapEditorUtils::InitMapEditor() { ManagerRegistry.Empty();//Just in case ManagerRegistry.Add({EMapType::ProceduralLandscape}, {ULandscapeManager::StaticClass()}); ManagerRegistry.Add({EMapType::ProceduralHMPlanet}, {UHeightMapPlanetManager::StaticClass()}); ManagerRegistry.Add({EMapType::Volumetric3DLandscape}, {UVolumetric3DTerrainManager::StaticClass()}); ModeName.Add({ EMapType::ProceduralLandscape }, { "Landscape procedural" }); ModeName.Add({ EMapType::ProceduralHMPlanet }, { "HM Planet procedural" }); ModeName.Add({ EMapType::Volumetric3DLandscape }, { "Terrain Volumetric" }); IsRunning = true; UEditorGameMode::Get(); } void UMapEditorUtils::DestroyMapEditor() { UEditorGameMode::Destroy(); ManagerRegistry.Empty(); IsRunning = false; } bool UMapEditorUtils::IsEditorRunning() { return IsRunning; } AMapActor* UMapEditorUtils::GetMapActor() { return UMapEditorUtils::GetMapGameMode()->GetMapActor(); } UBaseMapManager* UMapEditorUtils::GetActualMapManager() { return UMapEditorUtils::GetMapActor()->MapManager; } ULandscapeManager* UMapEditorUtils::TryGetLandscapeManager() { return Cast<ULandscapeManager>(UMapEditorUtils::GetActualMapManager()); } UVolumetric3DTerrainManager* UMapEditorUtils::tryGetVolumetricTerrainManager() { return Cast<UVolumetric3DTerrainManager>(UMapEditorUtils::GetActualMapManager()); } UHeightMapPlanetManager * UMapEditorUtils::TryGetHeightMapPlanetManager() { return Cast<UHeightMapPlanetManager>(UMapEditorUtils::GetActualMapManager()); } UWorld* UMapEditorUtils::GetActualWorld() { return UMapEditorUtils::GetMapGameMode()->GetWorld(); } UEditorGameMode* UMapEditorUtils::GetMapGameMode() { return UEditorGameMode::Get(); }
35.71831
102
0.800473
benoitestival
22827a71da757c0d7d34edb96ca7818e35355799
2,849
hpp
C++
src/Magma/Window/GLFWWindow.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
3
2017-11-01T21:47:57.000Z
2022-01-07T03:50:58.000Z
src/Magma/Window/GLFWWindow.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
src/Magma/Window/GLFWWindow.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
#pragma once #include "Window.hpp" #include <atomic> #include <queue> struct GLFWwindow; namespace Magma { /// <summary> /// Implements Window abstract interface class using GLFW /// </summary> class GLFWWindow : public Window { public: GLFWWindow(); virtual ~GLFWWindow() final; /// <summary> /// Gets this window GLFW handle /// </summary> /// <returns>This window GLFW handle</returns> inline GLFWwindow* GetGLFWWindow() { return m_glfwWindow; } /// <summary> /// Converts a GLFW mouse button to an Magma mouse button /// </summary> /// <param name="button">GLFW Mouse button to be converted</param> /// <returns>Corresponding Magma mouse button</returns> static Mouse::Button GLFWMButtonToMagma(int button); /// <summary> /// Converts a GLFW keyboard key to an Magma keyboard key /// </summary> /// <param name="key">GLFW keyboard ey to be converted</param> /// <returns>Corresponding Magma keyboard key</returns> static Keyboard::Key GLFWKeyToMagma(int key); protected: // Inherited via Window virtual bool DerivedIsOpen() final; virtual void DerivedOpen() final; virtual void DerivedClose() final; virtual void DerivedResize() final; virtual void DerivedSetTitle() final; virtual void DerivedSetMode() final; virtual void SetVSyncEnabled(bool vsyncEnabled) final; virtual bool DerivedPollEvent(Magma::UIEvent& event) final; virtual void DerivedDisplay() final; virtual glm::vec2 GetMousePosition() final; virtual void SetMousePosition(glm::vec2 mousePosition) final; virtual bool IsKeyboardKeyPressed(Keyboard::Key key) override; virtual bool IsMouseCursorVisible() override; virtual bool IsMouseButtonPressed(Mouse::Button button) override; virtual void SetMouseCursorVisible(bool visible) override; virtual void DerivedMakeActive() override; private: static void GLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); static void GLFWMouseButtonCallback(GLFWwindow* window, int button, int action, int mods); static void GLFWMouseScrollCallback(GLFWwindow* window, double x, double y); static void GLFWCursorPosCallback(GLFWwindow* window, double xpos, double ypos); static void GLFWCursorEnterCallback(GLFWwindow* window, int entered); static void GLFWCharCallback(GLFWwindow* window, unsigned int codePoint); static void GLFWResizeCallback(GLFWwindow* window, int width, int height); static void GLFWFocusCallback(GLFWwindow* window, int focused); static void GLFWCloseCallback(GLFWwindow* window); static std::atomic<int> s_windowNumber; GLFWwindow* m_glfwWindow; bool m_mouseButtonStates[static_cast<size_t>(Mouse::Button::Count)]; bool m_keyboardKeyStates[static_cast<size_t>(Keyboard::Key::Count)]; bool m_mouseCursorVisible = true; std::queue<Magma::UIEvent> m_eventQueue; }; }
34.325301
95
0.75079
RiscadoA
22839d29257f3790c1872f3f32c065b3689ba351
3,320
cpp
C++
src/eepp/graphics/ctexturefontloader.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/graphics/ctexturefontloader.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/graphics/ctexturefontloader.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#include <eepp/graphics/ctexturefontloader.hpp> #include <eepp/graphics/cfontmanager.hpp> namespace EE { namespace Graphics { cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, const eeUint& StartChar, const eeUint& Spacing, const eeUint& TexColumns, const eeUint& TexRows, const Uint16& NumChars ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_TEX ), mFontName( FontName ), mStartChar( StartChar ), mSpacing( Spacing ), mTexColumns( TexColumns ), mTexRows( TexRows ), mNumChars( NumChars ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, const std::string& CoordinatesDatPath ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_PATH ), mFontName( FontName ), mFilepath( CoordinatesDatPath ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, cPack * Pack, const std::string& FilePackPath ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_PACK ), mFontName( FontName ), mFilepath( FilePackPath ), mPack( Pack ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, const char* CoordData, const Uint32& CoordDataSize ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_MEM ), mFontName( FontName ), mData( CoordData ), mDataSize( CoordDataSize ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::~cTextureFontLoader() { eeSAFE_DELETE( mTexLoader ); } void cTextureFontLoader::Start() { cObjectLoader::Start(); mTexLoader->Threaded( false ); if ( !mThreaded ) { Update(); } } void cTextureFontLoader::Update() { if ( !mLoaded ) { if ( !mTexLoaded ) { mTexLoader->Load(); mTexLoader->Update(); mTexLoaded = mTexLoader->IsLoaded(); } if ( mTexLoaded && !mFontLoaded ) { LoadFont(); } if ( mFontLoaded ) { SetLoaded(); } } } const std::string& cTextureFontLoader::Id() const { return mFontName; } void cTextureFontLoader::LoadFromPath() { mFont->Load( mTexLoader->Id(), mFilepath ); } void cTextureFontLoader::LoadFromMemory() { mFont->LoadFromMemory( mTexLoader->Id(), mData, mDataSize ); } void cTextureFontLoader::LoadFromPack() { mFont->LoadFromPack( mTexLoader->Id(), mPack, mFilepath ); } void cTextureFontLoader::LoadFromTex() { mFont->Load( mTexLoader->Id(), mStartChar, mSpacing, mTexColumns, mTexRows, mNumChars ); } void cTextureFontLoader::LoadFont() { mFont = cTextureFont::New( mFontName ); if ( TEF_LT_PATH == mLoadType ) LoadFromPath(); else if ( TEF_LT_MEM == mLoadType ) LoadFromMemory(); else if ( TEF_LT_PACK == mLoadType ) LoadFromPack(); else if ( TEF_LT_TEX == mLoadType ) LoadFromTex(); mFontLoaded = true; } cFont * cTextureFontLoader::Font() const { return mFont; } void cTextureFontLoader::Unload() { if ( mLoaded ) { mTexLoader->Unload(); cFontManager::instance()->Remove( mFont ); Reset(); } } void cTextureFontLoader::Reset() { cObjectLoader::Reset(); mFont = NULL; mTexLoaded = false; mFontLoaded = false; } }}
22.432432
219
0.716566
dogtwelve
2285ef05a4bee2ac69dd0545677fe1b1304e5cdb
33,821
cpp
C++
tests/storeTests/TestHMStorageHostGroup.cpp
tkraiser/NetCHASM
6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4
[ "Apache-2.0" ]
null
null
null
tests/storeTests/TestHMStorageHostGroup.cpp
tkraiser/NetCHASM
6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4
[ "Apache-2.0" ]
null
null
null
tests/storeTests/TestHMStorageHostGroup.cpp
tkraiser/NetCHASM
6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4
[ "Apache-2.0" ]
null
null
null
// Copyright 2019, Oath Inc. // Licensed under the terms of the Apache 2.0 license. See LICENSE file in the root of the distribution for licensing details. #include "TestHMStorageHostGroup.h" #include "common.h" #include "TestStorageHostGroup.h" using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION(TESTNAME); void TESTNAME::setUp() { setupCommon(); } void TESTNAME::tearDown() { teardownCommon(); } void TESTNAME::test_HMStorageHostGroup_ReadOnly() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; HMIPAddress missingAddress; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMGroupCheckUpdate update1(hostGroup1, hostname1_1, address1_1_1, result1_1_1); HMGroupCheckUpdate update2(hostGroup1, hostname1_1, address1_1_2, result1_1_2); HMGroupCheckUpdate update3(hostGroup1, hostname1_2, address1_2_1, result1_2_1); HMGroupCheckUpdate update4(hostGroup1, hostname1_2, address1_2_2, result1_2_2); HMGroupCheckUpdate update5(hostGroup2, hostname2_1, address2_1_1, result2_1_1); HMGroupCheckUpdate update6(hostGroup2, hostname2_1, address2_1_2, result2_1_2); HMGroupCheckUpdate update7(hostGroup2, hostname2_2, address2_2_1, result2_2_1); HMGroupCheckUpdate update8(hostGroup2, hostname2_2, address2_2_2, result2_2_2); HMDataCheckResult testresult; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(true); // A store request should fail CPPUNIT_ASSERT(!storageHost->storeCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_2); // Missing entries CPPUNIT_ASSERT(!storageHost->getCheckResult("missing.hm.com", address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, missingAddress, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParamsMissing, testresult)); storageHost->closeStore(); delete storageHost; } void TESTNAME::test_HMStorageHostGroup_ReadWrite() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; dataHostGroup1.addHost(hostname1_1); dataHostGroup1.addHost(hostname1_2); dataHostGroup2.addHost(hostname2_1); dataHostGroup2.addHost(hostname2_2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; HMIPAddress missingAddress; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMDataCheckResult testresult; vector<HMGroupCheckResult> results; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); storageHost->openStore(false); // A store request should fail CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, result1_1_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_1, address1_1_2, hostCheck, checkParams1, result1_1_2)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_2, address1_2_1, hostCheck, checkParams1, result1_2_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_2, address1_2_2, hostCheck, checkParams1, result1_2_2)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_1, address2_1_1, hostCheck, checkParams2, result2_1_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_1, address2_1_2, hostCheck, checkParams2, result2_1_2)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_2, address2_2_1, hostCheck, checkParams2, result2_2_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_2, address2_2_2, hostCheck, checkParams2, result2_2_2)); std::this_thread::sleep_for(10ms); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_2); storageHost->populateHostGroup(true); CPPUNIT_ASSERT(storageHost->getGroupCheckResults(hostGroup1, true, false ,results)); CPPUNIT_ASSERT_EQUAL(4, (int)results.size()); // Note in the multimap, we don't have any strong guarentee of the oredering bool entry1, entry2, entry3, entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname1_1) { if(it->m_address == address1_1_1) { CPPUNIT_ASSERT(it->m_result == result1_1_1); entry1 = true; } else if(it->m_address == address1_1_2) { CPPUNIT_ASSERT(it->m_result == result1_1_2); entry2 = true; } } else if(it->m_hostName == hostname1_2) { if(it->m_address == address1_2_1) { CPPUNIT_ASSERT(it->m_result == result1_2_1); entry3 = true; } else if(it->m_address == address1_2_2) { CPPUNIT_ASSERT(it->m_result == result1_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); CPPUNIT_ASSERT(storageHost->getGroupCheckResults(hostGroup2, true, false, results)); CPPUNIT_ASSERT(results.size() == 4); entry1 = entry2 = entry3 = entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname2_1) { if(it->m_address == address2_1_1) { CPPUNIT_ASSERT(it->m_result == result2_1_1); entry1 = true; } else if(it->m_address == address2_1_2) { CPPUNIT_ASSERT(it->m_result == result2_1_2); entry2 = true; } } else if(it->m_hostName == hostname2_2) { if(it->m_address == address2_2_1) { CPPUNIT_ASSERT(it->m_result == result2_2_1); entry3 = true; } else if(it->m_address == address2_2_2) { CPPUNIT_ASSERT(it->m_result == result2_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); // Missing entries CPPUNIT_ASSERT(!storageHost->getCheckResult("missing.hm.com", address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, missingAddress, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParamsMissing, testresult)); CPPUNIT_ASSERT(!storageHost->getGroupCheckResults("missingGroup",true, false, results)); storageHost->closeStore(); delete storageHost; } void TESTNAME::test_HMStorageHostGroup_Restore() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); dataHostGroup1.addHost(hostname1_1); dataHostGroup1.addHost(hostname1_2); dataHostGroup2.addHost(hostname2_1); dataHostGroup2.addHost(hostname2_2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); set<HMIPAddress> ips1_1; ips1_1.insert(address1_1_1); ips1_1.insert(address1_1_2); set<HMIPAddress> ips1_2; ips1_2.insert(address1_2_1); ips1_2.insert(address1_2_2); set<HMIPAddress> ips2_1; ips2_1.insert(address2_1_1); ips2_1.insert(address2_1_2); set<HMIPAddress> ips2_2; ips2_2.insert(address2_2_1); ips2_2.insert(address2_2_2); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMGroupCheckUpdate update1(hostGroup1, hostname1_1, address1_1_1, result1_1_1); HMGroupCheckUpdate update2(hostGroup1, hostname1_1, address1_1_2, result1_1_2); HMGroupCheckUpdate update3(hostGroup1, hostname1_2, address1_2_1, result1_2_1); HMGroupCheckUpdate update4(hostGroup1, hostname1_2, address1_2_2, result1_2_2); HMGroupCheckUpdate update5(hostGroup2, hostname2_1, address2_1_1, result2_1_1); HMGroupCheckUpdate update6(hostGroup2, hostname2_1, address2_1_2, result2_1_2); HMGroupCheckUpdate update7(hostGroup2, hostname2_2, address2_2_1, result2_2_1); HMGroupCheckUpdate update8(hostGroup2, hostname2_2, address2_2_2, result2_2_2); HMDataCheckResult testresult; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); HMDataCheckList* checkList = new HMDataCheckList(); checkList->insertCheck(hostGroup1, hostname1_1, hostCheck, checkParams1, ips1_1); checkList->insertCheck(hostGroup1, hostname1_2, hostCheck, checkParams1, ips1_2); checkList->insertCheck(hostGroup2, hostname2_1, hostCheck, checkParams2, ips2_1); checkList->insertCheck(hostGroup2, hostname2_2, hostCheck, checkParams2, ips2_2); HMDNSCache* dnsCache = new HMDNSCache(); HMAuxCache auxCache; storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(false); storageHost->initResultsFromBackend(*checkList, *dnsCache, auxCache); set<HMIPAddress> vip_ret; CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_2) != vip_ret.end());; std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> results; CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_1, hostCheck, address1_1_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_1_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_1, hostCheck, address1_1_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_1_2); CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_2, hostCheck, address1_2_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_2_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_2, hostCheck, address1_2_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_2_2); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_1, hostCheck, address2_1_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_1_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_1, hostCheck, address2_1_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_1_2); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_2, hostCheck, address2_2_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_2_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_2, hostCheck, address2_2_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_2_2); storageHost->closeStore(); delete storageHost; delete checkList; delete dnsCache; // Test an empty hostGroup list HMDataHostGroupMap emptyHostGroupMap; storageHost = new TestStorageHostGroup(&emptyHostGroupMap); checkList = new HMDataCheckList(); dnsCache = new HMDNSCache(); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(false); // TODO fix the initResultsFromBackend //CPPUNIT_ASSERT(storageHost->restoreResults(*checkList, *dnsCache)); // Now nothing should be restored vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_1, hostCheck, address1_1_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_1, hostCheck, address1_1_2, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_2, hostCheck, address1_2_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_2, hostCheck, address1_2_2, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_1, hostCheck, address2_1_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_1, hostCheck, address2_1_2, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_2, hostCheck, address2_2_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_2, hostCheck, address2_2_2, results)); storageHost->closeStore(); delete storageHost; delete checkList; delete dnsCache; storageHost = new TestStorageHostGroup(&hostGroupMap); checkList = new HMDataCheckList(); dnsCache = new HMDNSCache(); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(true); // TODO fix initResultsFromBackend //CPPUNIT_ASSERT(!storageHost->restoreResults(*checkList, *dnsCache)); storageHost->closeStore(); delete storageHost; delete checkList; delete dnsCache; } void TESTNAME::test_HMStorageHostGroup_InternalFunctions() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; HMIPAddress testAddress; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMGroupCheckUpdate update1(hostGroup1, hostname1_1, address1_1_1, result1_1_1); HMGroupCheckUpdate update2(hostGroup1, hostname1_1, address1_1_2, result1_1_2); HMGroupCheckUpdate update3(hostGroup1, hostname1_2, address1_2_1, result1_2_1); HMGroupCheckUpdate update4(hostGroup1, hostname1_2, address1_2_2, result1_2_2); HMGroupCheckUpdate update5(hostGroup2, hostname2_1, address2_1_1, result2_1_1); HMGroupCheckUpdate update6(hostGroup2, hostname2_1, address2_1_2, result2_1_2); HMGroupCheckUpdate update7(hostGroup2, hostname2_2, address2_2_1, result2_2_1); HMGroupCheckUpdate update8(hostGroup2, hostname2_2, address2_2_2, result2_2_2); HMDataCheckResult testresult; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); std::vector<HMGroupCheckResult> results; HMDataHostGroup updateHostGroupTest1(hostGroup1); HMDataHostGroup updateHostGroupTest2(hostGroup2); const HMDataHostGroup* hostGroupTest1; const HMDataHostGroup* hostGroupTest2; string missingGroup = "missingGroup"; // Test retrieving group names CPPUNIT_ASSERT(!storageHost->test_getInternalHostGroupInfo(missingGroup, hostGroupTest1)); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupInfo(hostGroup1, hostGroupTest1)); CPPUNIT_ASSERT(hostGroupTest1->getName() == hostGroup1); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupInfo(hostGroup2, hostGroupTest2)); CPPUNIT_ASSERT(hostGroupTest2->getName() == hostGroup2); updateHostGroupTest1 = *hostGroupTest1; updateHostGroupTest2 = *hostGroupTest2; storageHost->populateHostGroup(false); // Test retrieving the health check results CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(hostGroup1, results) == 4); CPPUNIT_ASSERT(results.size() == 4); bool entry1, entry2, entry3, entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname1_1) { if(it->m_address == address1_1_1) { CPPUNIT_ASSERT(it->m_result == result1_1_1); entry1 = true; } else if(it->m_address == address1_1_2) { CPPUNIT_ASSERT(it->m_result == result1_1_2); entry2 = true; } } else if(it->m_hostName == hostname1_2) { if(it->m_address == address1_2_1) { CPPUNIT_ASSERT(it->m_result == result1_2_1); entry3 = true; } else if(it->m_address == address1_2_2) { CPPUNIT_ASSERT(it->m_result == result1_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); // Check for missing health check results CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(missingGroup, results) == 0); CPPUNIT_ASSERT(results.size() == 0); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(hostGroup2, results) == 4); CPPUNIT_ASSERT(results.size() == 4); entry1 = entry2 = entry3 = entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname2_1) { if(it->m_address == address2_1_1) { CPPUNIT_ASSERT(it->m_result == result2_1_1); entry1 = true; } else if(it->m_address == address2_1_2) { CPPUNIT_ASSERT(it->m_result == result2_1_2); entry2 = true; } } else if(it->m_hostName == hostname2_2) { if(it->m_address == address2_2_1) { CPPUNIT_ASSERT(it->m_result == result2_2_1); entry3 = true; } else if(it->m_address == address2_2_2) { CPPUNIT_ASSERT(it->m_result == result2_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(hostGroup1, results) == 4); CPPUNIT_ASSERT(results.size() == 4); for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname2_1) { if(it->m_address == address2_1_1) { CPPUNIT_ASSERT(it->m_result == result2_1_1); entry1 = true; } else if(it->m_address == address2_1_2) { CPPUNIT_ASSERT(it->m_result == result2_1_2); entry2 = true; } } else if(it->m_hostName == hostname2_2) { if(it->m_address == address2_2_1) { CPPUNIT_ASSERT(it->m_result == result2_2_1); entry3 = true; } else if(it->m_address == address2_2_2) { CPPUNIT_ASSERT(it->m_result == result2_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); delete storageHost; }
39.556725
126
0.717838
tkraiser
228724da71b641d8d9a08f27b639cbde44a77aec
2,997
cpp
C++
examples/accumulator_example/accumulator_example.cpp
alexsr/bachelorthesis-vup
d6a870bbde0cdd7275cbe785e6ef024b48f7687b
[ "MIT" ]
null
null
null
examples/accumulator_example/accumulator_example.cpp
alexsr/bachelorthesis-vup
d6a870bbde0cdd7275cbe785e6ef024b48f7687b
[ "MIT" ]
null
null
null
examples/accumulator_example/accumulator_example.cpp
alexsr/bachelorthesis-vup
d6a870bbde0cdd7275cbe785e6ef024b48f7687b
[ "MIT" ]
null
null
null
// Bachelor thesis Particleframework // Author: Alexander Scheid-Rehder // Email: alexsr@uni-koblenz.de #include "vup/Core/defs.h" #include "vup/Core/utils.h" #include "vup/Rendering/ShaderProgram.h" #include "vup/Rendering/TrackballCam.h" #include "vup/Rendering/RenderData/SphereData.h" #include "vup/Rendering/ParticleRenderer.h" #include "vup/Core/ParticleSimulation.h" #include <string> #include <ctime> #define WIDTH 1920 #define HEIGHT 1080 int main(int argc, char* argv[]) { int platformID = 0; int deviceID = 0; if (argc == 3) { platformID = atoi(argv[1]); deviceID = atoi(argv[2]); } GLFWwindow* window = vup::createWindow(WIDTH, HEIGHT, "Instanced Rendering", nullptr, nullptr); glfwSetKeyCallback(window, vup::closeWindowCallback); vup::initGLEW(); glViewport(0, 0, WIDTH, HEIGHT); vup::TrackballCam cam(WIDTH, HEIGHT, 1.0f, 10.0f, 10.0f, glm::vec3(0.0f, 0.0f, 0.0f)); vup::ShaderProgram simpleShader(SHADERS_PATH "/instancedPhong.vert", SHADERS_PATH "/instancedPhong.frag"); simpleShader.updateUniform("proj", cam.getProjection()); vup::ParticleSimulation ps(RESOURCES_PATH "/config.txt", platformID, CL_DEVICE_TYPE_GPU, deviceID); vup::SphereData* sphere = new vup::SphereData(ps.getSize(), 10, 10); vup::ParticleRenderer* renderer = new vup::ParticleRenderer(*sphere, ps.getInteropVBOs()); double dt = 0.01f; glfwSetTime(0.0); double currentTime = glfwGetTime(); double lastTime = glfwGetTime(); double frameTime = lastTime; double accumulator = 0.0; double renderAccumulator = 0.0; double iterCount = 0; // Main loop glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); while (!glfwWindowShouldClose(window)) { vup::clearGL(); lastTime = currentTime; currentTime = glfwGetTime(); accumulator += currentTime - lastTime; if (currentTime - frameTime > 1) { vup::updateFramerate(currentTime, frameTime, iterCount, window); frameTime = currentTime; std::cout << iterCount << std::endl; iterCount = 0; } iterCount += 1; std::pair<double, double> iterCountandAcc = ps.runAccumulated(iterCount, accumulator, dt); accumulator = iterCountandAcc.second; iterCount = iterCountandAcc.first; cam.update(window, dt); simpleShader.updateUniform("view", cam.getView()); simpleShader.use(); renderer->execute(ps.getParticleCount()); if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) { ps.reload(); ps.init(); sphere = new vup::SphereData(ps.getSize(), 10, 10); renderer = new vup::ParticleRenderer(*sphere, ps.getInteropVBOs()); currentTime = glfwGetTime(); } if (glfwGetKey(window, GLFW_KEY_T) == GLFW_PRESS) { ps.reloadKernel(); currentTime = glfwGetTime(); } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { accumulator = 0.0; currentTime = glfwGetTime(); } glfwPollEvents(); glfwSwapBuffers(window); } glfwTerminate(); return 0; }
32.225806
108
0.688689
alexsr
228770341eaf4887a11b131dce6cda60ad4e53fa
4,833
cpp
C++
src/nnfusion/core/graph/graph_util.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/graph/graph_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/graph/graph_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "graph_util.hpp" #include <queue> void nnfusion::graph::ReverseDFS(const Graph* graph, const GNodeVector& start, const std::function<void(std::shared_ptr<GNode>)>& enter, const std::function<void(std::shared_ptr<GNode>)>& leave, const NodeComparator& stable_comparator) { // Stack of work to do. struct Work { std::shared_ptr<GNode> node; bool leave; // Are we entering or leaving node? }; std::vector<Work> stack(start.size()); for (int i = 0; i < start.size(); ++i) { stack[i] = Work{start[i], false}; } std::vector<bool> visited(graph->get_max_node_id(), false); while (!stack.empty()) { Work w = stack.back(); stack.pop_back(); std::shared_ptr<GNode> node = w.node; if (w.leave) { leave(node); continue; } if (visited[node->get_id()]) { continue; } visited[node->get_id()] = true; if (enter) { enter(node); } // Arrange to call leave(node) when all done with descendants. if (leave) { stack.push_back(Work{node, true}); } auto add_work = [&visited, &stack](std::shared_ptr<GNode> in_node) { if (!visited[in_node->get_id()]) { // Note; we must not mark as visited until we actually process it. stack.push_back(Work{in_node, false}); } }; if (stable_comparator) { GNodeVector in_nodes_sorted; for (auto in_edge : node->get_in_edges()) { in_nodes_sorted.emplace_back(in_edge->get_src()); } std::sort(in_nodes_sorted.begin(), in_nodes_sorted.end(), stable_comparator); for (auto in_node : in_nodes_sorted) { add_work(in_node); } } else { for (auto in_edge : node->get_in_edges()) { add_work(in_edge->get_src()); } } } } void nnfusion::graph::BFS(const Graph* graph, const GNodeVector& start, const std::function<void(std::shared_ptr<GNode>)>& enter, const std::function<void(std::shared_ptr<GNode>)>& leave, const NodeComparator& stable_comparator) { // Stack of work to do. struct Work { std::shared_ptr<GNode> node; bool leave; // Are we entering or leaving node? }; std::queue<Work> queue; for (int i = 0; i < start.size(); ++i) { queue.push(Work{start[i], false}); } std::vector<bool> visited(graph->get_max_node_id(), false); while (!queue.empty()) { Work w = queue.front(); queue.pop(); std::shared_ptr<GNode> node = w.node; if (w.leave) { leave(node); continue; } if (visited[node->get_id()]) { continue; } visited[node->get_id()] = true; if (enter) { enter(node); } if (leave) { queue.push(Work{node, true}); } auto add_work = [&visited, &queue](std::shared_ptr<GNode> out_node) { if (!visited[out_node->get_id()]) { // Note; we must not mark as visited until we actually process it. bool all_input_visited = true; for (auto& edge : out_node->get_in_edges()) { auto input_node = edge->get_src(); if (!visited[input_node->get_id()]) { all_input_visited = false; break; } } if (all_input_visited) queue.push(Work{out_node, false}); } }; if (stable_comparator) { GNodeVector out_nodes_sorted; for (auto out_edge : node->get_out_edges()) { out_nodes_sorted.emplace_back(out_edge->get_dst()); } std::sort(out_nodes_sorted.begin(), out_nodes_sorted.end(), stable_comparator); for (auto out_node : out_nodes_sorted) { add_work(out_node); } } else { for (auto out_edge : node->get_out_edges()) { add_work(out_edge->get_dst()); } } } }
28.263158
91
0.470515
lynex
22888136451d7d988fa8cc94016c41d942d399cf
2,720
cpp
C++
worker/src/Master/RtcMaster.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
worker/src/Master/RtcMaster.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
worker/src/Master/RtcMaster.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
#define PMS_CLASS "pingos::RtcMaster" #define MS_CLASS "pingos::RtcMaster" #include "Master/Defines.hpp" #include "Master/RtcMaster.hpp" #include "Master/Log.hpp" #include "Master/RtcWorker.hpp" #include "MediaSoupErrors.hpp" namespace pingos { RtcMaster::RtcMaster() { } RtcMaster::~RtcMaster() { } RtcWorker* RtcMaster::FindWorker(std::string streamId) { size_t hashVal = std::hash<std::string>()(streamId); size_t slot = hashVal % this->GetWorkerCount(); return this->FindWorker(slot); } RtcSession* RtcMaster::CreateSession(std::string streamId, RtcSession::Role role) { auto worker = this->FindWorker(streamId); if (!worker) { PMS_ERROR("StreamId[{}], Worker not found", streamId); MS_THROW_ERROR("Worker not found"); return nullptr; } auto sessionId = this->SpellSessionId(); RtcSession *rtcSession = worker->CreateSession(streamId, sessionId, role); if (!rtcSession) { PMS_ERROR("SessionId[{}] StreamId[{}] create session failed.", sessionId, streamId); return nullptr; } PMS_INFO("SessionId[{}] StreamId[{}], RTC Session creation success, session ptr[{}].", sessionId, streamId, (void *)rtcSession); return rtcSession; } RtcWorker* RtcMaster::FindWorker(uint32_t slot) { auto it = m_slotWorkerMap.find(slot); if (it != m_slotWorkerMap.end()) { return (RtcWorker*) it->second; } return nullptr; } Worker* RtcMaster::NewWorker(uv_loop_t *loop) { return new RtcWorker(loop); } void RtcMaster::DeleteWorker(Worker *worker) { delete (RtcWorker*)worker; } std::string RtcMaster::SpellSessionId() { static uint64_t id = 0; std::string sessionId = std::string("sid") + std::to_string(id); id++; return sessionId; } RtcSession* RtcMaster::FindPublisher(std::string streamId) { auto worker = this->FindWorker(streamId); if (worker == nullptr) { return nullptr; } return worker->FindPublisher(streamId); } RtcSession* RtcMaster::FindSession(std::string streamId, std::string sessionId) { auto worker = this->FindWorker(streamId); if (!worker) { PMS_ERROR("SessionId[{}] StreamId[{}] Failed to find worker", sessionId, streamId); return nullptr; } return worker->FindSession(streamId, sessionId); } void RtcMaster::DeleteSession(std::string streamId, std::string sessionId) { auto worker = this->FindWorker(streamId); if (!worker) { PMS_ERROR("SessionId[{}] StreamId[{}], Worker not found", sessionId, streamId); return; } PMS_INFO("SessionId[{}] StreamId[{}], RTC Session deleted.", sessionId, streamId); worker->DeleteSession(streamId, sessionId); } }
22.666667
92
0.666912
idarkblue
228a1f7e09f9a0015524cf5801846fb76324f36d
1,097
cpp
C++
p_euler_102.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
p_euler_102.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
p_euler_102.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long #define pll pair<ll,ll> #define mp make_pair #define pb push_back ll dist(pll a,pll b){ return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second)); } ll area(ll a,ll b, ll c){ ll s = (a+b+c); return (s)*(a+b-c)*(a+c-b)*(b+c-a); } ll area1(pll a,pll b,pll c){ return abs((a.first*(b.second-c.second)+b.first*(c.second-a.second)+c.first*(a.second-b.second))); } int main(int argc, char const *argv[]) { int n = 1000; int cnt=0; while(n--){ string s; getline(cin,s); pll x,y,z; std::vector<ll> v; stringstream ss(s); for(int i;ss>>i;){ v.pb(i); if(ss.peek() == ','){ ss.ignore(); } } //cout<<v.size()<<" "; //int cnt=0; x.first = v[0]; x.second = v[1]; y.first = v[2]; y.second = v[3]; z.first = v[4]; z.second = v[5]; //cout<<x.first<<" "; pll o = mp(0LL,0LL); cout<<area1(x,y,z)<<endl; if(area1(x,y,z)==area1(x,y,o)+area1(x,z,o)+area1(y,z,o)) cnt++; } cout<<cnt; return 0; }
19.245614
100
0.534184
Krshivam
228c325c39695039d7ee268d2b8eec42e2962d24
6,775
cpp
C++
source/examples/ex20_scene_graphs.cpp
3a2l/OpenGL-Examples
a7284a0fc596898188f53671dac36ae60da62408
[ "MIT" ]
null
null
null
source/examples/ex20_scene_graphs.cpp
3a2l/OpenGL-Examples
a7284a0fc596898188f53671dac36ae60da62408
[ "MIT" ]
null
null
null
source/examples/ex20_scene_graphs.cpp
3a2l/OpenGL-Examples
a7284a0fc596898188f53671dac36ae60da62408
[ "MIT" ]
null
null
null
#include <application.hpp> #include <shader.hpp> #include <imgui-utils/utils.hpp> #include <mesh/mesh.hpp> #include <mesh/mesh-utils.hpp> #include <camera/camera.hpp> #include <camera/controllers/fly_camera_controller.hpp> #include <glm/gtx/euler_angles.hpp> #include <json/json.hpp> #include <fstream> #include <string> #include <unordered_map> #include <optional> namespace glm { template<length_t L, typename T, qualifier Q> void from_json(const nlohmann::json& j, vec<L, T, Q>& v){ for(length_t index = 0; index < L; ++index) v[index] = j[index].get<T>(); } } struct Transform { glm::vec4 tint; glm::vec3 translation, rotation, scale; std::optional<std::string> mesh; std::unordered_map<std::string, std::shared_ptr<Transform>> children; Transform( const glm::vec4& tint = {1,1,1,1}, const glm::vec3& translation = {0,0,0}, const glm::vec3& rotation = {0,0,0}, const glm::vec3& scale = {1,1,1}, const std::optional<std::string>& mesh = std::nullopt ): tint(tint), translation(translation), rotation(rotation), scale(scale), mesh(mesh) {} [[nodiscard]] glm::mat4 to_mat4() const { return glm::translate(glm::mat4(1.0f), translation) * glm::yawPitchRoll(rotation.y, rotation.x, rotation.z) * glm::scale(glm::mat4(1.0f), scale); } }; class SceneGraphApplication : public our::Application { our::ShaderProgram program; std::unordered_map<std::string, std::unique_ptr<our::Mesh>> meshes; std::unordered_map<std::string, std::shared_ptr<Transform>> roots; std::string current_root_name; our::Camera camera; our::FlyCameraController controller; our::WindowConfiguration getWindowConfiguration() override { return { "Scene Graphs", {1280, 720}, false }; } void onInitialize() override { program.create(); program.attach("assets/shaders/ex11_transformation/transform.vert", GL_VERTEX_SHADER); program.attach("assets/shaders/ex11_transformation/tint.frag", GL_FRAGMENT_SHADER); program.link(); meshes["cube"] = std::make_unique<our::Mesh>(); our::mesh_utils::Cuboid(*(meshes["cube"]), true); meshes["rod"] = std::make_unique<our::Mesh>(); our::mesh_utils::Cuboid(*(meshes["rod"]), true, {0, 0, 0.5}); meshes["sphere"] = std::make_unique<our::Mesh>(); our::mesh_utils::Sphere(*(meshes["sphere"]), {32, 16}, true); int width, height; glfwGetFramebufferSize(window, &width, &height); camera.setEyePosition({10, 10, 10}); camera.setTarget({0, 0, 0}); camera.setUp({0, 1, 0}); camera.setupPerspective(glm::pi<float>()/2, static_cast<float>(width)/height, 0.1f, 100.0f); controller.initialize(this, &camera); roots["simple"] = loadSceneGraph("assets/data/ex20_scene_graphs/simple.json"); roots["solar-system"] = loadSceneGraph("assets/data/ex20_scene_graphs/solar-system.json"); roots["human"] = loadSceneGraph("assets/data/ex20_scene_graphs/human.json"); current_root_name = "simple"; glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); glClearColor(0, 0, 0, 1); } std::shared_ptr<Transform> loadNode(const nlohmann::json& json){ auto node = std::make_shared<Transform>( json.value<glm::vec4>("tint", {1,1,1,1}), json.value<glm::vec3>("translation", {0, 0, 0}), json.value<glm::vec3>("rotation", {0, 0, 0}), json.value<glm::vec3>("scale", {1, 1, 1}) ); if(json.contains("mesh")){ node->mesh = json["mesh"].get<std::string>(); } if(json.contains("children")){ for(auto& [name, child]: json["children"].items()){ node->children[name] = loadNode(child); } } return node; } std::shared_ptr<Transform> loadSceneGraph(const std::string& scene_file){ std::ifstream file_in(scene_file); nlohmann::json json; file_in >> json; file_in.close(); return loadNode(json); } void drawNode(const std::shared_ptr<Transform>& node, const glm::mat4& parent_transform_matrix){ glm::mat4 transform_matrix = parent_transform_matrix * node->to_mat4(); if(node->mesh.has_value()){ auto it = meshes.find(node->mesh.value()); if(it != meshes.end()) { program.set("tint", node->tint); program.set("transform", transform_matrix); it->second->draw(); } } for(auto& [name, child]: node->children){ drawNode(child, transform_matrix); } } void onDraw(double deltaTime) override { controller.update(deltaTime); glUseProgram(program); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawNode(roots[current_root_name], camera.getVPMatrix()); } void onDestroy() override { program.destroy(); for(auto& [name, mesh] : meshes){ mesh->destroy(); } meshes.clear(); } void displayNodeGui(const std::shared_ptr<Transform>& node, const std::string& node_name){ if(ImGui::TreeNode(node_name.c_str())){ if(node->mesh.has_value()) { our::PairIteratorCombo("Mesh", node->mesh.value(), meshes.begin(), meshes.end()); ImGui::ColorEdit4("Tint", glm::value_ptr(node->tint)); } ImGui::DragFloat3("Translation", glm::value_ptr(node->translation), 0.1f); ImGui::DragFloat3("Rotation", glm::value_ptr(node->rotation), 0.01f); ImGui::DragFloat3("Scale", glm::value_ptr(node->scale), 0.1f); for(auto& [name, child]: node->children){ displayNodeGui(child, name); } ImGui::TreePop(); } } void onImmediateGui(ImGuiIO &io) override { ImGui::Begin("Scene Graph"); if(ImGui::BeginCombo("Scene", current_root_name.c_str())){ for(auto& [name, root] : roots){ bool selected = current_root_name == name; if(ImGui::Selectable(name.c_str(), selected)) current_root_name = name; if(selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } displayNodeGui(roots[current_root_name], current_root_name); ImGui::End(); } }; int main(int argc, char** argv) { return SceneGraphApplication().run(); }
33.539604
108
0.586863
3a2l
229221a6fc2d1ae4e85587370531bb8684636e29
11,693
cpp
C++
src/xmppserveroutput.cpp
WST/mawar
8a603f31869d8b31f60b782e5aa0342082874f9e
[ "MIT" ]
1
2019-08-16T18:07:43.000Z
2019-08-16T18:07:43.000Z
src/xmppserveroutput.cpp
WST/mawar
8a603f31869d8b31f60b782e5aa0342082874f9e
[ "MIT" ]
null
null
null
src/xmppserveroutput.cpp
WST/mawar
8a603f31869d8b31f60b782e5aa0342082874f9e
[ "MIT" ]
null
null
null
#include <xmppserveroutput.h> #include <xmppserverinput.h> #include <s2slistener.h> #include <xmppserver.h> #include <xmppdomain.h> #include <virtualhost.h> #include <functions.h> #include <logs.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <xml-parser.h> #include <string> using namespace std; /** * Конструктор s2s-домена */ XMPPServerOutput::XMPPServerOutput(XMPPServer *srv, const char *host): XMPPDomain(srv, host), XMPPStream(srv, 0) { sprintf(key, "%06lX-%06lX-%06lX-%06lX", random() % 0x1000000, random() % 0x1000000, random() % 0x1000000, random() % 0x1000000); lock(); // Резолвим DNS записи сервера state = RESOLVING; XMPPDomain::server->adns->srv(host, "xmpp-server", "tcp", on_s2s_output_xmpp_server, this); } /** * Деструктор потока */ XMPPServerOutput::~XMPPServerOutput() { printf("%s s2s-output(%s) delete\n", logtime().c_str(), hostname().c_str()); for(vhosts_t::iterator iter = vhosts.begin(); iter != vhosts.end(); ++iter) { delete iter->second; } vhosts.clear(); } /** * Обработчик готовности подключения */ void XMPPServerOutput::onConnect() { mutex.lock(); printf("%s s2s-output(%s): connected\n", logtime().c_str(), hostname().c_str()); // поздоровайся с дядей initXML(); startElement("stream:stream"); setAttribute("xmlns:stream", "http://etherx.jabber.org/streams"); setAttribute("xmlns", "jabber:server"); setAttribute("xmlns:db", "jabber:server:dialback"); setAttribute("xml:lang", "en"); flush(); for(vhosts_t::iterator iter = vhosts.begin(); iter != vhosts.end(); ++iter) { vhost_t *vhost = iter->second; sendDBRequest(iter->first, hostname()); printf("%s s2s-output(%s): flush connected to %s\n", logtime().c_str(), hostname().c_str(), iter->first.c_str()); for(buffer_t::iterator bi = vhost->connbuffer.begin(); bi != vhost->connbuffer.end(); bi++) { Stanza stanza = parse_xml_string(*bi); sendStanza(stanza); delete stanza; } } mutex.unlock(); } /** * Резолвер s2s хоста, запись A (IPv4) */ void XMPPServerOutput::on_s2s_output_a4(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { char buf[40]; struct sockaddr_in target; XMPPServerOutput *p = static_cast<XMPPServerOutput *>(data); if ( result && result->dnsa4_nrr >= 1 ) { p->state = CONNECTING; p->setFd( ::socket(PF_INET, SOCK_STREAM, 0) ); printf("%s s2s-output(%s): connect to %s:%d, sock: %d\n", logtime().c_str(), p->hostname().c_str(), dns_ntop(AF_INET, &result->dnsa4_addr[0], buf, sizeof(buf)), p->port, p->getFd()); target.sin_family = AF_INET; target.sin_port = htons(p->port); memcpy(&target.sin_addr, &result->dnsa4_addr[0], sizeof(result->dnsa4_addr[0])); memset(target.sin_zero, 0, 8); // принудительно выставить O_NONBLOCK int flags = fcntl(p->getFd(), F_GETFL, 0); if ( flags >= 0 ) { fcntl(p->getFd(), F_SETFL, flags | O_NONBLOCK); } if ( ::connect(p->getFd(), (struct sockaddr *)&target, sizeof( struct sockaddr )) == 0 || errno == EINPROGRESS || errno == EALREADY ) { p->state = CONNECTED; p->XMPPDomain::server->daemon->addObject(p); p->onConnect(); return; } printf("%s s2s-output(%s): connect to %s:%d fault\n", logtime().c_str(), p->hostname().c_str(), dns_ntop(AF_INET, &result->dnsa4_addr[0], buf, sizeof(buf)), p->port); } else { printf("%s s2s-output(%s): connect failed: no IP address\n", logtime().c_str(), p->hostname().c_str()); } p->XMPPDomain::server->removeDomain(p); p->XMPPDomain::server->daemon->removeObject(p); p->release(); } /** * Резолвер s2s хоста, запись SRV (_jabber._tcp) */ void XMPPServerOutput::on_s2s_output_jabber(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { XMPPServerOutput *p = static_cast<XMPPServerOutput *>(data); if ( result && result->dnssrv_nrr > 0 ) { for(int i = 0; i < result->dnssrv_nrr; i++) { //char buf[40]; printf("%s SRV(%s) priority: %d, weight: %d, port: %d, name: %s\n", logtime().c_str(), p->hostname().c_str(), result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } p->port = result->dnssrv_srv[0].port; p->XMPPDomain::server->adns->a4(result->dnssrv_srv[0].name, on_s2s_output_a4, p); return; } p->port = 5269; p->XMPPDomain::server->adns->a4(p->hostname().c_str(), on_s2s_output_a4, p); } /** * Резолвер s2s хоста, запись SRV (_xmpp-server._tcp) */ void XMPPServerOutput::on_s2s_output_xmpp_server(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { XMPPServerOutput *p = static_cast<XMPPServerOutput *>(data); if ( result && result->dnssrv_nrr > 0 ) { for(int i = 0; i < result->dnssrv_nrr; i++) { //char buf[40]; printf("%s SRV(%s) priority: %d, weight: %d, port: %d, name: %s\n", logtime().c_str(), p->hostname().c_str(), result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } p->port = result->dnssrv_srv[0].port; p->XMPPDomain::server->adns->a4(result->dnssrv_srv[0].name, on_s2s_output_a4, p); return; } p->XMPPDomain::server->adns->srv(p->hostname().c_str(), "jabber", "tcp", on_s2s_output_jabber, p); } /** * 2.1.1 Originating Server Generates Outbound Request for Authorization by Receiving Server * * XEP-0220: Server Dialback */ void XMPPServerOutput::sendDBRequest(const std::string &from, const std::string &to) { Stanza dbresult = new XmlTag("db:result"); dbresult->setAttribute("from", from); dbresult->setAttribute("to", to); dbresult += sha1(from + ":" + to + ":" + key); sendStanza(dbresult); delete dbresult; } /** * Событие: начало потока */ void XMPPServerOutput::onStartStream(const std::string &name, const attributes_t &attributes) { } /** * Событие: конец потока */ void XMPPServerOutput::onEndStream() { printf("%s s2s-output(%s): end of stream\n", logtime().c_str(), hostname().c_str()); terminate(); } /** * Обработчик станзы */ void XMPPServerOutput::onStanza(Stanza stanza) { // Шаг 1. проверка: "to" должен быть нашим хостом string to = stanza.to().hostname(); if ( ! XMPPStream::server->isOurHost(to) ) { Stanza stanza = Stanza::streamError("improper-addressing"); sendStanza(stanza); delete stanza; terminate(); return; } // Шаг 2. проверка: "from" должен быть НЕ нашим хостом string from = stanza.from().hostname(); if ( XMPPStream::server->isOurHost(from) ) { Stanza stanza = Stanza::streamError("improper-addressing"); sendStanza(stanza); delete stanza; terminate(); return; } if ( stanza->name() == "verify" ) onDBVerifyStanza(stanza); else if ( stanza->name() == "result" ) onDBResultStanza(stanza); else { printf("%s s2s-output(%s): unexpected stanza arrived: %s\n", logtime().c_str(), hostname().c_str(), stanza->name().c_str()); Stanza error = Stanza::streamError("not-authoized"); sendStanza(error); delete error; terminate(); } } /** * RFC 3920 (8.3.9) - анализируем результат проверки ключа */ void XMPPServerOutput::onDBVerifyStanza(Stanza stanza) { printf("%s s2s-output(%s): db:verify to %s from %s type %s\n", logtime().c_str(), hostname().c_str(), stanza.to().hostname().c_str(), stanza.from().hostname().c_str(), stanza->getAttribute("type").c_str()); // Шаг 1. проверка: "id" должен совпадать тем, что мы давали (id s2s-input'а) // TODO std::string id = stanza->getAttribute("id"); XMPPServerInput *input = XMPPDomain::server->s2s->getInput(id); if ( ! input ) { Stanza stanza = Stanza::streamError("invalid-id"); sendStanza(stanza); delete stanza; terminate(); return; } std::string to = stanza.to().hostname(); std::string from = stanza.from().hostname(); if ( stanza->getAttribute("type") == "valid" || stanza->getAttribute("type") == "invalid" ) { // Шаг 4. вернуть результат в s2s-input input->authorize(from, to, stanza->getAttribute("type") == "valid"); Stanza result = new XmlTag("db:result"); result->setAttribute("to", from); result->setAttribute("from", to); result->setAttribute("type", stanza->getAttribute("type")); input->sendStanza(result); delete result; } } /** * RFC 3920 (8.3.10) */ void XMPPServerOutput::onDBResultStanza(Stanza stanza) { printf("%s s2s-output(%s): db:result to %s from %s type %s\n", logtime().c_str(), hostname().c_str(), stanza.to().hostname().c_str(), stanza.from().hostname().c_str(), stanza->getAttribute("type").c_str()); if ( stanza->getAttribute("type") != "valid" ) { terminate(); } else { std::string vhostname = stanza.to().hostname(); vhosts_t::const_iterator iter = vhosts.find(vhostname); vhost_t *vhost = iter != vhosts.end() ? iter->second : 0; if ( vhost ) { vhost->authorized = true; printf("%s s2s-output(%s): flush authorized to %s\n", logtime().c_str(), hostname().c_str(), vhostname.c_str()); for(buffer_t::iterator bi = vhost->buffer.begin(); bi != vhost->buffer.end(); bi++) { Stanza stanza = parse_xml_string(*bi); sendStanza(stanza); delete stanza; } vhost->buffer.clear(); } } } /** * Пир (peer) закрыл поток. * * Мы уже ничего не можем отправить в ответ, * можем только корректно закрыть соединение с нашей стороны. */ void XMPPServerOutput::onPeerDown() { printf("%s s2s-output(%s): peer down\n", logtime().c_str(), hostname().c_str()); terminate(); } /** * Сигнал завершения работы * * Сервер решил закрыть соединение, здесь ещё есть время * корректно попрощаться с пиром (peer). */ void XMPPServerOutput::onTerminate() { printf("%s s2s-output(%s): terminate\n", logtime().c_str(), hostname().c_str()); mutex.lock(); endElement("stream:stream"); flush(); XMPPDomain::server->removeDomain(this); XMPPDomain::server->daemon->removeObject(this); mutex.unlock(); release(); } /** * Роутер исходящих станз (thread-safe) * * Роутер передает станзу нужному потоку. * * @note Данная функция отвечает только за маршрутизацию, она не сохраняет офлайновые сообщения: * если адресат online, то пересылает ему станзу, * если offline, то вернет FALSE и вызывающая сторона должна сама сохранить офлайновое сообщение. * * @note Данный метод вызывается из глобального маршрутизатора станз XMPPServer::routeStanza() * вызывать его напрямую из других мест не рекомендуется - используйте XMPPServer::routeStanza() * * @note Данный метод в будущем станет виртуальным и будет перенесен в специальный * базовый класс, от которого будут наследовать VirtualHost (виртуальные узлы) * и, к примеру, MUC. Виртуальые узлы и MUC имеют общие черты, оба адресуются * доменом, оба принимают входящие станзы, но обрабатывают их по разному, * VirtualHost доставляет сообщения своим пользователям, а MUC доставляет * сообщения участникам комнат. * * @param to адресат которому надо направить станзу * @param stanza станза * @return TRUE - станза была отправлена, FALSE - станзу отправить не удалось */ bool XMPPServerOutput::routeStanza(Stanza stanza) { lock(); mutex.lock(); std::string vhostname = stanza.from().hostname(); vhosts_t::const_iterator iter = vhosts.find(vhostname); vhost_t *vhost = iter != vhosts.end() ? iter->second : 0; if ( ! vhost ) { vhost = new vhost_t; vhost->authorized = false; vhosts[vhostname] = vhost; if ( state == CONNECTED ) { sendDBRequest(vhostname, hostname()); } } mutex.unlock(); if ( vhost->authorized ) { sendStanza(stanza); } else if ( stanza->name() == "db:verify" ) { mutex.lock(); if ( state == CONNECTED ) sendStanza(stanza); else vhost->connbuffer.push_back(stanza->asString()); mutex.unlock(); } else { vhost->buffer.push_back(stanza->asString()); } release(); return true; }
27.643026
207
0.67194
WST
2299990e2d751cca8994ce5a32b56a4d91bb1734
5,399
cc
C++
chrome/browser/ssl/ssl_client_auth_handler.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/ssl/ssl_client_auth_handler.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/ssl/ssl_client_auth_handler.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2020-01-12T00:55:53.000Z
2020-11-04T06:36:41.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ssl/ssl_client_auth_handler.h" #include "chrome/browser/ssl/ssl_client_auth_notification_details.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/render_view_host_delegate.h" #include "content/browser/renderer_host/render_view_host_notification_task.h" #include "content/browser/renderer_host/resource_dispatcher_host.h" #include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" #include "content/common/notification_service.h" #include "net/url_request/url_request.h" SSLClientAuthHandler::SSLClientAuthHandler( net::URLRequest* request, net::SSLCertRequestInfo* cert_request_info) : request_(request), cert_request_info_(cert_request_info) { } SSLClientAuthHandler::~SSLClientAuthHandler() { // If we were simply dropped, then act as if we selected no certificate. DoCertificateSelected(NULL); } void SSLClientAuthHandler::OnRequestCancelled() { request_ = NULL; } void SSLClientAuthHandler::SelectCertificate() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); int render_process_host_id; int render_view_host_id; if (!ResourceDispatcherHost::RenderViewForRequest(request_, &render_process_host_id, &render_view_host_id)) NOTREACHED(); // If the RVH does not exist by the time this task gets run, then the task // will be dropped and the scoped_refptr to SSLClientAuthHandler will go // away, so we do not leak anything. The destructor takes care of ensuring // the net::URLRequest always gets a response. CallRenderViewHostSSLDelegate( render_process_host_id, render_view_host_id, &RenderViewHostDelegate::SSL::ShowClientCertificateRequestDialog, scoped_refptr<SSLClientAuthHandler>(this)); } // Sends an SSL_CLIENT_AUTH_CERT_SELECTED notification and notifies the IO // thread that we have selected a cert. void SSLClientAuthHandler::CertificateSelected(net::X509Certificate* cert) { VLOG(1) << this << " CertificateSelected " << cert; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); SSLClientAuthNotificationDetails details(cert_request_info_, cert); NotificationService* service = NotificationService::current(); service->Notify(NotificationType::SSL_CLIENT_AUTH_CERT_SELECTED, Source<SSLClientAuthHandler>(this), Details<SSLClientAuthNotificationDetails>(&details)); CertificateSelectedNoNotify(cert); } // Notifies the IO thread that we have selected a cert. void SSLClientAuthHandler::CertificateSelectedNoNotify( net::X509Certificate* cert) { VLOG(1) << this << " CertificateSelectedNoNotify " << cert; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( this, &SSLClientAuthHandler::DoCertificateSelected, cert)); } void SSLClientAuthHandler::DoCertificateSelected(net::X509Certificate* cert) { VLOG(1) << this << " DoCertificateSelected " << cert; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // request_ could have been NULLed if the request was cancelled while the // user was choosing a cert, or because we have already responded to the // certificate. if (request_) { request_->ContinueWithCertificate(cert); ResourceDispatcherHostRequestInfo* info = ResourceDispatcherHost::InfoForRequest(request_); if (info) info->set_ssl_client_auth_handler(NULL); request_ = NULL; } } SSLClientAuthObserver::SSLClientAuthObserver( net::SSLCertRequestInfo* cert_request_info, SSLClientAuthHandler* handler) : cert_request_info_(cert_request_info), handler_(handler) { } SSLClientAuthObserver::~SSLClientAuthObserver() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); } void SSLClientAuthObserver::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { VLOG(1) << "SSLClientAuthObserver::Observe " << this << " " << handler_.get(); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(type == NotificationType::SSL_CLIENT_AUTH_CERT_SELECTED); if (Source<SSLClientAuthHandler>(source).ptr() == handler_.get()) { VLOG(1) << "got notification from ourself " << handler_.get(); return; } SSLClientAuthNotificationDetails* auth_details = Details<SSLClientAuthNotificationDetails>(details).ptr(); if (!auth_details->IsSameHost(cert_request_info_)) return; VLOG(1) << this << " got matching notification for " << handler_.get() << ", selecting cert " << auth_details->selected_cert(); StopObserving(); handler_->CertificateSelectedNoNotify(auth_details->selected_cert()); OnCertSelectedByNotification(); } void SSLClientAuthObserver::StartObserving() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); notification_registrar_.Add(this, NotificationType::SSL_CLIENT_AUTH_CERT_SELECTED, NotificationService::AllSources()); } void SSLClientAuthObserver::StopObserving() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); notification_registrar_.RemoveAll(); }
38.021127
80
0.739581
SlimKatLegacy
229ab0e7949131966932572a17990d829807197d
8,714
cpp
C++
Blizzlike/ArcEmu/C++/QuestScripts/Quest_UnGoro.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/QuestScripts/Quest_UnGoro.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/QuestScripts/Quest_UnGoro.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/> * * 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 * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" /*--------------------------------------------------------------------------------------------------------*/ class RingoDeadNPC : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(RingoDeadNPC); RingoDeadNPC(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnLoad() { _unit->SetStandState(7); _unit->setDeathState(CORPSE); _unit->GetAIInterface()->m_canMove = false; } }; /*--------------------------------------------------------------------------------------------------------*/ // The Northern Pylon class NorthernPylon : public GameObjectAIScript { public: NorthernPylon(GameObject* goinstance) : GameObjectAIScript(goinstance) {} static GameObjectAIScript* Create(GameObject* GO) { return new NorthernPylon(GO); } void OnActivate(Player* pPlayer) { if(pPlayer->HasFinishedQuest(4284)) { QuestLogEntry* en = pPlayer->GetQuestLogForEntry(4285); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { uint32 newcount = en->GetMobCount(0) + 1; en->SetMobCount(0, newcount); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); return; } } else if(pPlayer->HasFinishedQuest(4284) == false) { pPlayer->BroadcastMessage("You need to have completed the quest : Crystals of Power"); } } }; /*--------------------------------------------------------------------------------------------------------*/ // The Eastern Pylon class EasternPylon : public GameObjectAIScript { public: EasternPylon(GameObject* goinstance) : GameObjectAIScript(goinstance) {} static GameObjectAIScript* Create(GameObject* GO) { return new EasternPylon(GO); } void OnActivate(Player* pPlayer) { if(pPlayer->HasFinishedQuest(4284)) { QuestLogEntry* en = pPlayer->GetQuestLogForEntry(4287); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { uint32 newcount = en->GetMobCount(0) + 1; en->SetMobCount(0, newcount); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); return; } } else if(pPlayer->HasFinishedQuest(4284) == false) { pPlayer->BroadcastMessage("You need to have completed the quest : Crystals of Power"); } } }; /*--------------------------------------------------------------------------------------------------------*/ //The Western Pylon class WesternPylon : public GameObjectAIScript { public: WesternPylon(GameObject* goinstance) : GameObjectAIScript(goinstance) {} static GameObjectAIScript* Create(GameObject* GO) { return new WesternPylon(GO); } void OnActivate(Player* pPlayer) { if(pPlayer->HasFinishedQuest(4284)) { QuestLogEntry* en = pPlayer->GetQuestLogForEntry(4288); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { uint32 newcount = en->GetMobCount(0) + 1; en->SetMobCount(0, newcount); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); return; } } else if(pPlayer->HasFinishedQuest(4284) == false) { pPlayer->BroadcastMessage("You need to have completed the quest : Crystals of Power"); } } }; /*--------------------------------------------------------------------------------------------------------*/ class ChasingAMe01 : public QuestScript { public: void OnQuestStart(Player* mTarget, QuestLogEntry* qLogEntry) { float SSX = mTarget->GetPositionX(); float SSY = mTarget->GetPositionY(); float SSZ = mTarget->GetPositionZ(); Creature* creat = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 9623); if(creat == NULL) return; creat->m_escorter = mTarget; creat->GetAIInterface()->setMoveType(11); creat->GetAIInterface()->StopMovement(3000); creat->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "He-l-p Me... ts.. ts..."); creat->SetUInt32Value(UNIT_NPC_FLAGS, 0); sEAS.CreateCustomWaypointMap(creat); sEAS.WaypointCreate(creat, -6305.657715f, -1977.757080f, -268.076447f, 5.564124f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6292.354492f, -1988.233032f, -265.271667f, 4.821922f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6296.333984f, -2004.225342f, -268.766388f, 3.337522f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6329.421387f, -2007.737549f, -258.587250f, 3.769490f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6343.778809f, -2017.559204f, -256.952026f, 3.577064f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6360.504883f, -2030.157959f, -261.204926f, 3.526014f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6381.367676f, -2038.451904f, -262.319946f, 2.713128f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6404.608398f, -2028.813721f, -262.817230f, 1.146257f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6399.632813f, -2018.668091f, -263.569824f, 0.800682f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6383.180664f, -2003.231689f, -270.639984f, 0.631821f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6351.983887f, -1976.397827f, -276.039001f, 1.138403f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6342.651855f, -1958.451050f, -274.056122f, 1.805992f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6353.083008f, -1918.406006f, -264.135101f, 1.515395f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6350.737305f, -1900.465942f, -258.695831f, 2.677785f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6366.535645f, -1892.092651f, -256.424347f, 2.025904f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6378.548828f, -1866.535278f, -260.363281f, 1.154112f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6370.422852f, -1842.526978f, -259.409515f, 1.711744f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6374.264648f, -1825.782349f, -260.584442f, 1.955218f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6382.359375f, -1811.540527f, -266.374359f, 2.901623f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6383.307129f, -1794.137207f, -267.334686f, 1.821700f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6399.292980f, -1710.144897f, -273.734283f, 1.252285f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6361.579102f, -1582.413574f, -272.221008f, 1.798137f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6391.618652f, -1409.568237f, -272.190521f, 1.711742f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6407.588867f, -1305.676880f, -271.632935f, 0.553279f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6349.980469f, -1276.069580f, -266.971375f, 1.236575f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6324.551758f, -1233.252441f, -267.178619f, 0.451176f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6288.604492f, -1215.046265f, -267.426117f, 2.177482f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6298.290039f, -1182.650024f, -269.101013f, 3.211410f, 1, 256, 8841); sEAS.EnableWaypoints(creat); } }; class A_Me01 : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(A_Me01); A_Me01(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnReachWP(uint32 iWaypointId, bool bForwards) { if(iWaypointId == 28) { _unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Tr.........."); _unit->Despawn(5000, 1000); sEAS.DeleteWaypoints(_unit); if(_unit->m_escorter == NULL) return; Player* plr = _unit->m_escorter; _unit->m_escorter = NULL; plr->GetQuestLogForEntry(4245)->SendQuestComplete(); } } }; void SetupUnGoro(ScriptMgr* mgr) { mgr->register_creature_script(9999, &RingoDeadNPC::Create); mgr->register_gameobject_script(164955, &NorthernPylon::Create); mgr->register_gameobject_script(164957, &EasternPylon::Create); mgr->register_gameobject_script(164956, &WesternPylon::Create); /*mgr->register_quest_script(4245, new ChasingAMe01());*/ mgr->register_creature_script(9623, &A_Me01::Create); }
38.728889
108
0.660431
499453466
229acf34e1869f8476a505292837124d6e7d76a8
336
cpp
C++
1487/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1487/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1487/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int get_cnt_skip(int n, int k) { if (n % 2 == 0) { return 0; } return k / ((n - 1) / 2); } void solve() { int n, k; scanf("%d%d", &n, &k); printf("%d\n", (k - 1 + get_cnt_skip(n, k - 1)) % n + 1); } int main() { int t; scanf("%d", &t); while (t--) { solve(); } }
13.44
59
0.464286
vladshablinsky
229b827ce6b20a59b9ea173b296a814a2ed3293f
4,606
cpp
C++
src/net/dns/client.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
3,673
2015-12-01T22:14:02.000Z
2019-03-22T03:07:20.000Z
src/net/dns/client.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
960
2015-12-01T20:40:36.000Z
2019-03-22T13:21:21.000Z
src/net/dns/client.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
357
2015-12-02T09:32:50.000Z
2019-03-22T09:32:34.000Z
#include <net/dns/client.hpp> #include <net/inet> namespace net::dns { #ifdef LIBFUZZER_ENABLED Timer::duration_t Client::DEFAULT_RESOLVE_TIMEOUT{std::chrono::seconds(9999)}; uint16_t g_last_xid = 0; #else Timer::duration_t Client::DEFAULT_RESOLVE_TIMEOUT{std::chrono::seconds(5)}; #endif Timer::duration_t Client::DEFAULT_FLUSH_INTERVAL{std::chrono::seconds(30)}; std::chrono::seconds Client::DEFAULT_CACHE_TTL{std::chrono::seconds(60)}; Client::Client(Stack& stack) : stack_{stack}, cache_ttl_{DEFAULT_CACHE_TTL}, flush_timer_{{this, &Client::flush_expired}} { } void Client::resolve(Address dns_server, Hostname hostname, Resolve_handler func, Timer::duration_t timeout, bool force) { Expects(not hostname.empty()); if(not is_FQDN(hostname) and not stack_.domain_name().empty()) { hostname.append(".").append(stack_.domain_name()); } if(not force) { auto it = cache_.find(hostname); if(it != cache_.end()) { Error err; func(nullptr, err); // fix return; } } // Make sure we actually can bind to a socket auto& socket = (dns_server.is_v6()) ? stack_.udp().bind6() : stack_.udp().bind(); // Create our query Query query{std::move(hostname), (dns_server.is_v6() ? Record_type::AAAA : Record_type::A)}; #ifdef LIBFUZZER_ENABLED g_last_xid = query.id; #endif // store the request for later match auto emp = requests_.emplace(std::piecewise_construct, std::forward_as_tuple(query.id), std::forward_as_tuple(*this, socket, std::move(query), std::move(func))); Ensures(emp.second && "Unable to insert"); auto& req = emp.first->second; req.resolve(dns_server, timeout); } Client::Request::Request(Client& cli, udp::Socket& sock, dns::Query q, Resolve_handler cb) : client{cli}, query{std::move(q)}, response{nullptr}, socket{sock}, callback{std::move(cb)}, timer({this, &Request::timeout}) { socket.on_read({this, &Client::Request::parse_response}); } void Client::Request::resolve(net::Addr server, Timer::duration_t timeout) { std::array<char, 256> buf; size_t len = query.write(buf.data()); socket.sendto(server, dns::SERVICE_PORT, buf.data(), len, nullptr, {this, &Client::Request::handle_error}); timer.start(timeout); } void Client::Request::parse_response(Addr, UDP::port_t, const char* data, size_t len) { if(UNLIKELY(len < sizeof(dns::Header))) return; const auto& reply = *(dns::Header*) data; // this is a response to our query if(query.id == ntohs(reply.id)) { auto res = std::make_unique<dns::Response>(); // TODO: Validate res->parse(data, len); this->response = std::move(res); // TODO: Cache /*if(client.cache_ttl_ > std::chrono::seconds::zero()) { add_cache_entry(...); }*/ finish({}); } else { debug("<dns::Client::Request> Cannot find matching DNS Request with transid=%u\n", ntohs(reply.id)); } } void Client::Request::finish(const Error& err) { callback(std::move(response), err); auto erased = client.requests_.erase(query.id); Ensures(erased == 1); } void Client::Request::timeout() { finish({Error::Type::timeout, "Request timed out"}); } void Client::Request::handle_error(const Error& err) { // This will call the user callback - do we want that? finish(err); } Client::Request::~Request() { socket.close(); } void Client::flush_cache() { cache_.clear(); flush_timer_.stop(); } void Client::add_cache_entry(const Hostname& hostname, Address addr, std::chrono::seconds ttl) { // cache the address cache_.emplace(std::piecewise_construct, std::forward_as_tuple(hostname), std::forward_as_tuple(addr, timestamp() + ttl.count())); debug("<DNSClient> Cache entry added: [%s] %s (%lld)\n", hostname.c_str(), addr.to_string().c_str(), ttl.count()); // start the timer if not already active if(not flush_timer_.is_running()) flush_timer_.start(DEFAULT_FLUSH_INTERVAL); } void Client::flush_expired() { const auto now = timestamp(); for(auto it = cache_.begin(); it != cache_.end();) { if(it->second.expires > now) it++; else it = cache_.erase(it); } if(not cache_.empty()) flush_timer_.start(DEFAULT_FLUSH_INTERVAL); } }
25.876404
96
0.616804
jaeh
22a07304a934c770fb3bd6377c38064a2a8ddfb4
5,841
cpp
C++
tools/signer/lc7signertask.cpp
phixion/l0phtcrack
48ee2f711134e178dbedbd925640f6b3b663fbb5
[ "Apache-2.0", "MIT" ]
2
2021-10-20T00:25:39.000Z
2021-11-08T12:52:42.000Z
tools/signer/lc7signertask.cpp
Brute-f0rce/l0phtcrack
25f681c07828e5e68e0dd788d84cc13c154aed3d
[ "Apache-2.0", "MIT" ]
null
null
null
tools/signer/lc7signertask.cpp
Brute-f0rce/l0phtcrack
25f681c07828e5e68e0dd788d84cc13c154aed3d
[ "Apache-2.0", "MIT" ]
1
2022-03-14T06:41:16.000Z
2022-03-14T06:41:16.000Z
#include "lc7signertask.h" #include "qcommandline.h" #include "CkPrivateKey.h" #include "CkPublicKey.h" #include "CkRsa.h" #define MAGIC (0xCDC31337) void print(QString out) { printf("%s",out.toLatin1().constData()); } LC7SignerTask::LC7SignerTask(QObject *parent) : QObject(parent) { m_app=QCoreApplication::instance(); m_cmdline=new QCommandLine(*m_app); m_verify=false; m_key_file=""; m_in_file=""; m_out_file=""; if(!m_rsa.UnlockComponent("NOCTEMRSA_7oMoLJcX3RsG")) { Q_ASSERT(false); } } LC7SignerTask::~LC7SignerTask() { delete m_cmdline; } void LC7SignerTask::switchFound(const QString & name) { if(name=="verify") { m_verify=true; } } void LC7SignerTask::optionFound(const QString & name, const QVariant & value) { if(name=="key") { m_key_file = value.toString(); } } void LC7SignerTask::paramFound(const QString & name, const QVariant & value) { if(name=="infile") { m_in_file=value.toString(); } else if(name=="outfile") { m_out_file=value.toString(); } } void LC7SignerTask::parseError(const QString & error) { print(QString("Error: ") + error + "\n"); m_cmdline->showHelp(true, -1); m_app->exit(1); } void LC7SignerTask::run() { m_cmdline->addSwitch('v', "verify", "Verify the infile as signed correctly instead of signing"); m_cmdline->addOption('k',"key", "Path to private key to sign file with. Defaults to lc7.key in the working directory when signing, and lc7.pub when verifying."); m_cmdline->addParam("infile", "Path to file to sign or verify", QCommandLine::Mandatory); m_cmdline->addParam("outfile", "Path for signed output file when signing. Defaults to <infile>.signed", QCommandLine::Optional); m_cmdline->enableVersion(true); m_cmdline->enableHelp(true); connect(m_cmdline, SIGNAL(switchFound(const QString &)), this, SLOT(switchFound(const QString &))); connect(m_cmdline, SIGNAL(optionFound(const QString &, const QVariant &)), this, SLOT(optionFound(const QString &, const QVariant &))); connect(m_cmdline, SIGNAL(paramFound(const QString &, const QVariant &)), this, SLOT(paramFound(const QString &, const QVariant &))); connect(m_cmdline, SIGNAL(parseError(const QString &)), this, SLOT(parseError(const QString &))); m_cmdline->parse(); if(m_key_file.isEmpty()) { if(m_verify) { m_key_file="lc7.pub"; } else { m_key_file="lc7.key"; } } if(m_verify) { do_verify(); } else { do_sign(); } m_app->exit(0); //emit finished(); } void LC7SignerTask::do_verify() { QByteArray indata; QByteArray sig; if(!ReadSignedFile(m_in_file, indata, sig)) { m_app->exit(6); return; } CkPublicKey pkey; if(!pkey.LoadOpenSslPemFile(m_key_file.toLatin1())) { print(QString("Could not load pem file: %1\n").arg(m_key_file)); m_app->exit(7); return; } m_rsa.ImportPublicKeyObj(pkey); m_rsa.put_LittleEndian(false); CkByteData ckdata; ckdata.append2(indata.constData(),indata.size()); CkByteData cksig; cksig.append2(sig.constData(),sig.size()); if(!m_rsa.VerifyBytes(ckdata,"SHA-512",cksig)) { print("Signature is NOT VALID.\n"); m_app->exit(8); return; } print("Signature is valid.\n"); m_app->exit(0); return; } void LC7SignerTask::do_sign() { QFile in(m_in_file); if(!in.open(QIODevice::ReadOnly)) { print(QString("Could not open input file: %1\n").arg(m_in_file)); m_app->exit(4); return; } QByteArray indata = in.readAll(); CkPrivateKey pkey; if(!pkey.LoadPemFile(m_key_file.toLatin1())) { print(QString("Could not load pem file: %1\n").arg(m_key_file)); m_app->exit(2); return; } if(!m_rsa.ImportPrivateKeyObj(pkey)) { print("Could not import private key, invalid format.\n"); m_app->exit(3); return; } m_rsa.put_LittleEndian(false); CkByteData data; data.append2(indata.constData(),indata.size()); CkByteData sigout; m_rsa.SignBytes(data,"SHA-512",sigout); QByteArray sig((const char *)sigout.getData(),sigout.getSize()); if(m_out_file.isEmpty()) { m_out_file=m_in_file+".signed"; } if(!WriteSignedFile(m_out_file, indata, sig)) { m_app->exit(5); return; } } bool LC7SignerTask::WriteSignedFile(QString out_file, QByteArray outdata, QByteArray sig) { QFile out(out_file); if(!out.open(QIODevice::WriteOnly)) { print(QString("Could not open output file: %1\n").arg(out_file)); return false; } // Define header quint32 magic=qToLittleEndian(MAGIC); quint32 siglen=qToLittleEndian(sig.size()); // Write header out.write((const char *)&magic,sizeof(magic)); out.write((const char *)&siglen,sizeof(siglen)); // Write signature out.write(sig); // Write signed data out.write(outdata); return true; } bool LC7SignerTask::ReadSignedFile(QString in_file, QByteArray &indata, QByteArray &sig) { QFile in(in_file); if(!in.open(QIODevice::ReadOnly)) { print(QString("Could not open input file: %1\n").arg(in_file)); return false; } // Define header quint32 magic; quint32 siglen; // Read header if(in.read((char *)&magic,sizeof(magic))!=sizeof(magic)) { print("Invalid header length.\n"); return false; } magic=qFromLittleEndian(magic); if(magic!=MAGIC) { print("Invalid header. Not an LC7 Signed Package.\n"); return false; } if(in.read((char *)&siglen,sizeof(siglen))!=sizeof(siglen)) { print("Invalid header length.\n"); return false; } siglen=qFromLittleEndian(siglen); // Read signature sig=in.read(siglen); if(sig.size()!=siglen) { print("Invalid signature, incorrect size.\n"); return false; } // Write signed data indata=in.readAll(); return true; }
21.086643
163
0.659305
phixion
22a08cf80db06465c549cf747068f85c5fde7287
896
hpp
C++
src/sdk/rules/LimitedTupleTrimmer.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
1
2020-10-11T06:54:04.000Z
2020-10-11T06:54:04.000Z
src/sdk/rules/LimitedTupleTrimmer.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
null
null
null
src/sdk/rules/LimitedTupleTrimmer.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
null
null
null
/** * LimitedTupleTrimmer.hpp - Limited Tuple Trimmer * * Check for limited tuples that have been resolved and delete them. */ #ifndef _SDK_LIMITEDTUPLETRIMMER #define _SDK_LIMITEDTUPLETRIMMER #include "sdk/data/LimitedTupleDatabase.hpp" #include "sdk/interfaces/ILimitedTupleObserver.hpp" #include "sdk/interfaces/IRule.hpp" namespace sdk { namespace rules { class LimitedTupleTrimmer : public interfaces::IRule { public: virtual ~LimitedTupleTrimmer() {} LimitedTupleTrimmer(data::LimitedTupleDatabase* database); void SetObserver(interfaces::ILimitedTupleObserver* observer); bool Apply() override; private: void SendProgress(data::LimitedTuple const& tuple, data::Cell const& breaking_member) const; data::LimitedTupleDatabase* database_; interfaces::ILimitedTupleObserver* observer_; }; } // namespace rules } // namespace sdk #endif /* _SDK_LIMITEDTUPLETRIMMER */
28.903226
94
0.780134
psettle
22a6c28912f0c699bf66157eefc0977754af59f6
2,231
cpp
C++
src/HttpCacheMetadata.cpp
commshare/easyhttpcpp
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
[ "MIT" ]
147
2017-10-05T01:42:02.000Z
2022-01-21T08:15:05.000Z
src/HttpCacheMetadata.cpp
commshare/easyhttpcpp
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
[ "MIT" ]
20
2018-05-17T01:55:16.000Z
2021-04-20T07:27:00.000Z
src/HttpCacheMetadata.cpp
commshare/easyhttpcpp
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
[ "MIT" ]
32
2018-05-05T13:04:34.000Z
2022-03-25T16:57:11.000Z
/* * Copyright 2017 Sony Corporation */ #include "HttpCacheMetadata.h" namespace easyhttpcpp { HttpCacheMetadata::HttpCacheMetadata() : m_httpMethod(Request::HttpMethodGet), m_statusCode(-1), m_responseBodySize(0), m_sentRequestAtEpoch(0), m_receivedResponseAtEpoch(0), m_createdAtEpoch(0) { } HttpCacheMetadata::~HttpCacheMetadata() { } void HttpCacheMetadata::setUrl(const std::string& url) { m_url = url; } const std::string& HttpCacheMetadata::getUrl() const { return m_url; } void HttpCacheMetadata::setHttpMethod(Request::HttpMethod httpMethod) { m_httpMethod = httpMethod; } Request::HttpMethod HttpCacheMetadata::getHttpMethod() const { return m_httpMethod; } void HttpCacheMetadata::setStatusCode(int statusCode) { m_statusCode = statusCode; } int HttpCacheMetadata::getStatusCode() const { return m_statusCode; } void HttpCacheMetadata::setStatusMessage(const std::string& statusMessage) { m_statusMessage = statusMessage; } const std::string& HttpCacheMetadata::getStatusMessage() const { return m_statusMessage; } void HttpCacheMetadata::setResponseHeaders(Headers::Ptr pResponseHeaders) { m_pResponseHeaders = pResponseHeaders; } Headers::Ptr HttpCacheMetadata::getResponseHeaders() const { return m_pResponseHeaders; } void HttpCacheMetadata::setResponseBodySize(size_t responseBodySize) { m_responseBodySize = responseBodySize; } size_t HttpCacheMetadata::getResponseBodySize() const { return m_responseBodySize; } void HttpCacheMetadata::setSentRequestAtEpoch(std::time_t sentRequestAtEpoch) { m_sentRequestAtEpoch = sentRequestAtEpoch; } std::time_t HttpCacheMetadata::getSentRequestAtEpoch() const { return m_sentRequestAtEpoch; } void HttpCacheMetadata::setReceivedResponseAtEpoch(std::time_t receivedResponseAtEpoch) { m_receivedResponseAtEpoch = receivedResponseAtEpoch; } std::time_t HttpCacheMetadata::getReceivedResponseAtEpoch() const { return m_receivedResponseAtEpoch; } void HttpCacheMetadata::setCreatedAtEpoch(std::time_t createdAtEpoch) { m_createdAtEpoch = createdAtEpoch; } std::time_t HttpCacheMetadata::getCreatedAtEpoch() const { return m_createdAtEpoch; } } /* namespace easyhttpcpp */
19.919643
119
0.779023
commshare
22a7a56ac931e31adf1102ab56942347c6f443b4
5,938
cpp
C++
es-core/src/TextToSpeech.cpp
brooksytech/emulationstation
67f12cb26127ff4f46966ea3735308ee4fd4e1ed
[ "Apache-2.0", "MIT" ]
139
2017-10-30T13:19:56.000Z
2022-03-27T05:43:17.000Z
es-core/src/TextToSpeech.cpp
brooksytech/emulationstation
67f12cb26127ff4f46966ea3735308ee4fd4e1ed
[ "Apache-2.0", "MIT" ]
273
2018-03-05T13:09:48.000Z
2022-03-30T11:44:06.000Z
es-core/src/TextToSpeech.cpp
brooksytech/emulationstation
67f12cb26127ff4f46966ea3735308ee4fd4e1ed
[ "Apache-2.0", "MIT" ]
193
2017-10-29T18:59:54.000Z
2022-03-27T16:15:58.000Z
#include "TextToSpeech.h" #include "Log.h" #include "LocaleES.h" #if WIN32 #include "SystemConf.h" #include <sapi.h> #include <sphelper.h> #include <thread> #pragma comment(lib, "sapi.lib") void TextToSpeech::SpeakThread() { if (FAILED(::CoInitializeEx(NULL, COINITBASE_MULTITHREADED))) return; ISpVoice* pVoice = NULL; HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice); if (!SUCCEEDED(hr)) return; m_isAvailable = true; while (true) { std::unique_lock<std::mutex> lock(mMutex); mEvent.wait(lock, [this]() { return mShouldTerminate || !mSpeechQueue.empty(); }); if (mShouldTerminate) break; SpeakItem* item = nullptr; if (!mSpeechQueue.empty()) { item = mSpeechQueue.front(); mSpeechQueue.pop_front(); } lock.unlock(); if (item != nullptr) { pVoice->Speak(Utils::String::convertToWideString(item->text).c_str(), SPF_ASYNC | SPF_IS_XML | (item->expand ? 0 : SPF_PURGEBEFORESPEAK), NULL); delete item; } } pVoice->Pause(); pVoice->Release(); } #elif defined(_ENABLE_TTS_) #include <espeak/speak_lib.h> #endif std::weak_ptr<TextToSpeech> TextToSpeech::sInstance; TextToSpeech::TextToSpeech() { m_isAvailable = false; m_enabled = false; init(); } TextToSpeech::~TextToSpeech() { deinit(); } std::shared_ptr<TextToSpeech> & TextToSpeech::getInstance() { //check if an TextToSpeech instance is already created, if not create one static std::shared_ptr<TextToSpeech> sharedInstance = sInstance.lock(); if (sharedInstance == nullptr) { sharedInstance.reset(new TextToSpeech); sInstance = sharedInstance; } return sharedInstance; } void TextToSpeech::init() { if (m_isAvailable) return; #if WIN32 m_isAvailable = false; mShouldTerminate = false; mSpeakThread = new std::thread(&TextToSpeech::SpeakThread, this); #elif defined(_ENABLE_TTS_) m_isAvailable = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK, 0, NULL, 0) != EE_INTERNAL_ERROR; if (!m_isAvailable) return; char* envv = getenv("LANGUAGE"); if (envv != nullptr && std::string(envv).length() >= 4) setLanguage(envv); else { envv = getenv("LANG"); if (envv != nullptr && std::string(envv).length() >= 4) setLanguage(envv); } #endif } void TextToSpeech::deinit() { if (!m_isAvailable) return; m_isAvailable = false; m_enabled = false; #if WIN32 if (mSpeakThread != nullptr) { mShouldTerminate = true; mEvent.notify_all(); mSpeakThread->join(); delete mSpeakThread; mSpeakThread = nullptr; } #elif defined(_ENABLE_TTS_) if (espeak_Terminate() != EE_OK) { LOG(LogError) << "TTS::deinit() - Failed to terminate"; } #endif } bool TextToSpeech::isAvailable() { return m_isAvailable; } bool TextToSpeech::isEnabled() { return m_enabled; } void TextToSpeech::enable(bool v, bool playSay) { if (v == m_enabled) return; if (m_isAvailable && playSay) { m_enabled = true; // Force say(v ? _("SCREEN READER ENABLED") : _("SCREEN READER DISABLED")); } m_enabled = v; } bool TextToSpeech::toogle() { enable(!m_enabled); return m_enabled; } void TextToSpeech::setLanguage(const std::string language) { if (m_isAvailable == false) return; #ifdef _ENABLE_TTS_ std::string voice = "default"; std::string language_part1 = language.substr(0, 5); // espeak --voices //if(language_part1 == "ar_YE") voice = ""; if (language_part1 == "ca_ES") voice = "catalan"; if (language_part1 == "cy_GB") voice = "welsh"; if (language_part1 == "de_DE") voice = "german"; if (language_part1 == "el_GR") voice = "greek"; if (language_part1 == "es_ES") voice = "spanish"; if (language_part1 == "es_MX") voice = "spanish-latin-am"; //if(language_part1 == "eu_ES") voice = ""; if (language_part1 == "fr_FR") voice = "french"; if (language_part1 == "hu_HU") voice = "hungarian"; if (language_part1 == "it_IT") voice = "italian"; //if(language_part1 == "ja_JP") voice = ""; //if(language_part1 == "ko_KR") voice = ""; if (language_part1 == "nb_NO") voice = "norwegian"; if (language_part1 == "nl_NL") voice = "dutch"; if (language_part1 == "nn_NO") voice = "norwegian"; //if(language_part1 == "oc_FR") voice = ""; if (language_part1 == "pl_PL") voice = "polish"; if (language_part1 == "pt_BR") voice = "brazil"; if (language_part1 == "pt_PT") voice = "portugal"; if (language_part1 == "ru_RU") voice = "russian"; if (language_part1 == "sv_SE") voice = "swedish"; if (language_part1 == "tr_TR") voice = "turkish"; //if(language_part1 == "uk_UA") voice = ""; if (language_part1 == "zh_CN") voice = "Mandarin"; // or cantonese ? if (language_part1 == "zh_TW") voice = "Mandarin"; // or cantonese ? if (espeak_SetVoiceByName(voice.c_str()) == EE_OK) { LOG(LogInfo) << "TTS::setLanguage() - set to " << language_part1 << " (" << voice << ")"; } else { LOG(LogError) << "TTS::setLanguage() - Failed with " << language_part1 << " (" << voice << ")"; } #endif } void TextToSpeech::say(const std::string text, bool expand, const std::string lang) { if (!m_isAvailable || !m_enabled || text.empty()) return; #if WIN32 std::string language = lang; if (language.empty()) language = SystemConf::getInstance()->get("system.language"); if (language.empty() || language == "en") language = "en-US"; std::string full = "<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='" + language + "'>" + text + "</speak>"; std::unique_lock<std::mutex> lock(mMutex); if (!expand) mSpeechQueue.clear(); SpeakItem* item = new SpeakItem(); item->text = full; item->expand = expand; mSpeechQueue.push_back(item); mEvent.notify_one(); #elif defined(_ENABLE_TTS_) if (expand == false && espeak_IsPlaying() == 1) espeak_Cancel(); if (espeak_Synth(text.c_str(), text.length() * 4 /* potentially 4 bytes by char */, 0, POS_CHARACTER, 0, espeakCHARS_UTF8, NULL, NULL) != EE_OK) { LOG(LogError) << "TTS::say() - Failed"; } #endif }
23.105058
147
0.664534
brooksytech
22ad28df7094ac0534375bb2bcb3b6c19876399d
139
cpp
C++
ByteCat/src/byteCat/lua/LuaFunction.cpp
CodingWithMenno/ByteCat
0fd19aa6781a5c28c6ff5e6f66c9624ace860de7
[ "Apache-2.0" ]
2
2021-04-07T11:39:24.000Z
2022-03-02T11:24:58.000Z
ByteCat/src/byteCat/lua/LuaFunction.cpp
CodingWithMenno/ByteCat
0fd19aa6781a5c28c6ff5e6f66c9624ace860de7
[ "Apache-2.0" ]
null
null
null
ByteCat/src/byteCat/lua/LuaFunction.cpp
CodingWithMenno/ByteCat
0fd19aa6781a5c28c6ff5e6f66c9624ace860de7
[ "Apache-2.0" ]
null
null
null
#include "bcpch.h" #include "byteCat/lua/LuaFunction.h" namespace BC { void LuaAPI::LOG(std::string string) { LOG_ERROR(string); } }
12.636364
37
0.690647
CodingWithMenno
22ae0f1e9ce554ddebc3a5e15413125dcde28723
3,187
cpp
C++
components/scene_graph/tests/screen/viewport.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/scene_graph/tests/screen/viewport.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/scene_graph/tests/screen/viewport.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include "shared.h" ///Слушатель событий области вывода class MyViewportListener: public IViewportListener { public: void OnViewportChangeName (const char* new_name) { printf ("OnChangeName(%s)\n", new_name); } void OnViewportChangeArea (const Rect& new_area, float min_depth, float max_depth) { printf ("OnChangeArea(%d, %d, %u, %u, %.2f, %.2f)\n", new_area.x, new_area.y, new_area.width, new_area.height, min_depth, max_depth); } void OnViewportChangeCamera (scene_graph::Camera* new_camera) { printf ("OnChangeCamera(%s)\n", new_camera ? new_camera->Name () : "null"); } void OnViewportChangeZOrder (int new_z_order) { printf ("OnChangeZOrder(%d)\n", new_z_order); } void OnViewportChangeActive (bool new_state) { printf ("OnChangeActive(%s)\n", new_state ? "true" : "false"); } void OnViewportChangeBackground (bool new_state, const math::vec4f& new_color) { printf ("OnChangeBackground(%s, %.2f, %.2f, %.2f, %.2f)\n", new_state ? "true" : "false", new_color.x, new_color.y, new_color.z, new_color.w); } void OnViewportChangeTechnique (const char* new_technique) { printf ("OnChangeTechnique(%s)\n", new_technique); } void OnViewportChangeProperties (const common::PropertyMap&) { printf ("OnChangeProperties()\n"); } void OnViewportDestroy () { printf ("OnDestroy()\n"); } }; int main () { printf ("Results of viewport_test:\n"); try { MyViewportListener listener; //создание камеры и области вывода Viewport viewport; Camera::Pointer camera = OrthoCamera::Create (); //присоединение слушателя к области вывода viewport.AttachListener (&listener); //изменение параметров области вывода viewport.SetName ("viewport1"); viewport.SetZOrder (12); viewport.SetTechnique ("RenderPath1"); viewport.SetArea (0, 0, 100, 200); viewport.Deactivate (); viewport.SetCamera (camera.get ()); viewport.SetBackgroundColor (1, 1, 0, 1); viewport.EnableBackground (); viewport.SetMinDepth (0.5f); viewport.SetMaxDepth (0.75f); //удаление камеры (проверка weak-reference области вывода) printf ("Delete camera\n"); camera = 0; //изменение свойств viewport.SetProperties (common::PropertyMap ()); //печать свойств области вывода printf ("Viewport '%s':\n", viewport.Name ()); printf (" z-order: %d\n", viewport.ZOrder ()); printf (" technique: '%s'\n", viewport.Technique ()); const Rect& vp_rect = viewport.Area (); printf (" area: (%d, %d, %u, %u)\n", vp_rect.x, vp_rect.y, vp_rect.width, vp_rect.height); printf (" state: %s\n", viewport.IsActive () ? "on" : "off"); printf (" camera: '%s'\n", viewport.Camera () ? viewport.Camera ()->Name () : "null"); } catch (std::exception& exception) { printf ("exception: %s\n", exception.what ()); } return 0; }
28.455357
149
0.595231
untgames
22b32ed752e2ce78c767cb3c241707c2c2cd6c19
3,063
cpp
C++
cobs/file/ranfold_index_header.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
cobs/file/ranfold_index_header.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
cobs/file/ranfold_index_header.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
/******************************************************************************* * cobs/file/ranfold_index_header.cpp * * Copyright (c) 2018 Florian Gauger * Copyright (c) 2018 Timo Bingmann * * All rights reserved. Published under the MIT License in the LICENSE file. ******************************************************************************/ #include <cobs/file/ranfold_index_header.hpp> #include <cobs/util/file.hpp> namespace cobs { const std::string RanfoldIndexHeader::magic_word = "RANFOLD_INDEX"; const uint32_t RanfoldIndexHeader::version = 1; const std::string RanfoldIndexHeader::file_extension = ".rfd_idx.cobs"; void RanfoldIndexHeader::serialize(std::ofstream& ofs) const { serialize_magic_begin(ofs, magic_word, version); stream_put(ofs, m_term_space, m_term_hashes, m_doc_space_bytes, m_doc_hashes, (uint32_t)m_file_names.size(), (uint32_t)m_doc_array.size()); for (const auto& file_name : m_file_names) { ofs << file_name << std::endl; } // for (const auto& d : m_doc_array) { // cobs::serialize(ofs, d); // } serialize_magic_begin(ofs, magic_word, version); } void RanfoldIndexHeader::deserialize(std::ifstream& ifs) { deserialize_magic_begin(ifs, magic_word, version); uint32_t file_names_size, doc_array_size; stream_get(ifs, m_term_space, m_term_hashes, m_doc_space_bytes, m_doc_hashes, file_names_size, doc_array_size); m_file_names.resize(file_names_size); for (auto& file_name : m_file_names) { std::getline(ifs, file_name); } m_doc_array.resize(doc_array_size); for (auto& d : m_doc_array) { stream_get(ifs, d); } deserialize_magic_end(ifs, magic_word); } void RanfoldIndexHeader::write_file(std::ofstream& ofs, const std::vector<uint8_t>& data) { ofs.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit); serialize(ofs); ofs.write(reinterpret_cast<const char*>(data.data()), data.size()); } void RanfoldIndexHeader::write_file(const fs::path& p, const std::vector<uint8_t>& data) { if (!p.parent_path().empty()) fs::create_directories(p.parent_path()); std::ofstream ofs(p.string(), std::ios::out | std::ios::binary); write_file(ofs, data); } void RanfoldIndexHeader::read_file(std::ifstream& ifs, std::vector<uint8_t>& data) { ifs.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit); deserialize(ifs); size_t size = get_stream_size(ifs); data.resize(size); ifs.read(reinterpret_cast<char*>(data.data()), size); } void RanfoldIndexHeader::read_file(const fs::path& p, std::vector<uint8_t>& data) { std::ifstream ifs(p.string(), std::ios::in | std::ios::binary); read_file(ifs, data); } } // namespace cobs /******************************************************************************/
34.41573
80
0.592556
karasikov
22b636954ca7a11b897fd7d86ea09522e79bd331
775
cpp
C++
competitive-programming/codeforces/#786-Div. 3/abc_sort.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
competitive-programming/codeforces/#786-Div. 3/abc_sort.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
competitive-programming/codeforces/#786-Div. 3/abc_sort.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; struct Node { int data; Node *next = NULL; }; void insertAtMiddle(Node **head, int data,int position) { int count = 0; while (count < position) { head = head->next; count++; } struct Node *newNode = new Node(); newNode->data = data; newNode-> next = head -> next -> next; head -> next = newNode; } bool isArrSorted(vector<int> arr, int n) { if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) if (arr[i - 1] > arr[i]) return false; return true; } vector<int> handleInsert(vector<int> arr){ int mid = (arr.size() - 1)/2; arr } string solve(stack<int> arr) { return } int main() { return 0; }
14.903846
56
0.529032
dushimsam
22b7846ef3357e993329c3b5eb37391160222741
1,805
cpp
C++
Project/15-QPainter3/widget.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
Project/15-QPainter3/widget.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
Project/15-QPainter3/widget.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); } Widget::~Widget() { delete ui; } //当鼠标按下时: 创建一条新线压入vector。并且将当前鼠标位置作为新线的起点。 void Widget::mousePressEvent(QMouseEvent *event){ QVector<QPoint>line; _lines.append(line); QVector<QPoint>&last_line = _lines.last(); //注意:引用而不是新建,否则不是同一个内存 last_line.append(event->pos()); update(); //注意一定要记得update } //如果鼠标正在移动:将这些移动的点都压入最上面也就是最新的线 #include <QDebug> void Widget::mouseMoveEvent(QMouseEvent *event){ // qDebug() << "mouseMoveEvent"; if(!_lines.size()){ //保证安全 QVector<QPoint>line; _lines.append(line); } QVector<QPoint>&last_line = _lines.last(); last_line.append(event->pos()); update(); //注意一定要记得update } //如果鼠标松开,这个点就是新线的终点,只需要把此时的点压入最新线就可以了 void Widget::mouseReleaseEvent(QMouseEvent *event){ QVector<QPoint>&last_line = _lines.last(); last_line.append(event->pos()); update(); //注意一定要记得update } //在鼠标事件中记录线的轨迹,在绘画事件中绘制轨迹 void Widget::paintEvent(QPaintEvent *event){ //创建画笔 // QPainter painter(this); //vector数组中有几条线 // for(int i = 0; i < _lines.size(); ++i){ //一条条绘制 // QVector<QPoint>line = _lines.at(i); // for(int j = 0; j < line.size(); ++j){ // QPoint tj = line.at(j); // painter.drawPoint(tj); //不要画点,画线有专门的函数 // } // } QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true);//反走样 painter.setPen(QPen(QColor(0, 255, 0), 3));// 设置画笔颜色、宽度 for(int i=0; i<_lines.size(); ++i) { const QVector<QPoint>& line = _lines.at(i); for(int j=0; j<line.size()-1; ++j) { painter.drawLine(line.at(j), line.at(j+1)); } } }
25.069444
70
0.610526
liukai-tech
22c0b36cd36d5332d8cc2f2e46f2667bc6a24ea3
6,564
cpp
C++
sr_apx/vc/lift/vc_lift.cpp
TheoryInPractice/structural-rounding
0aa961b9c8ecd4fd12f65302f6e95145ccb00cb6
[ "BSD-3-Clause" ]
4
2019-10-17T02:29:48.000Z
2022-02-20T17:03:42.000Z
sr_apx/vc/lift/vc_lift.cpp
TheoryInPractice/structural-rounding
0aa961b9c8ecd4fd12f65302f6e95145ccb00cb6
[ "BSD-3-Clause" ]
null
null
null
sr_apx/vc/lift/vc_lift.cpp
TheoryInPractice/structural-rounding
0aa961b9c8ecd4fd12f65302f6e95145ccb00cb6
[ "BSD-3-Clause" ]
1
2020-01-14T15:51:50.000Z
2020-01-14T15:51:50.000Z
#include "vc_lift.hpp" #include "vc_apx.hpp" #include "vc_exact.hpp" #include "bipartite.hpp" Set* naive_lift(Graph* graph, Set* octset, Set* partial) { Set* cover = new Set(); for (Set::Iterator iu = octset->begin(); iu != octset->end(); ++iu) { int u = *iu; cover->insert(u); } for (Set::Iterator iu = partial->begin(); iu != partial->end(); ++iu) { int u = *iu; cover->insert(u); } return cover; } Set* greedy_lift(Graph* graph, Set* octset, Set* partial) { Set* cover = new Set(); for (Set::Iterator iu = partial->begin(); iu != partial->end(); ++iu) { int u = *iu; cover->insert(u); } Set processed; for (auto iu = graph->begin(); iu != graph->end(); ++iu) { int u = *iu; if (!octset->contains(u)) { processed.insert(u); } } for (Set::Iterator iu = octset->begin(); iu != octset->end(); ++iu) { int u = *iu; for (Set::Iterator iv = graph->neighbors(u)->begin(); iv != graph->neighbors(u)->end(); ++iv) { int v = *iv; if (processed.contains(v) && !cover->contains(v)) { cover->insert(u); break; } } processed.insert(u); } return cover; } Set* apx_lift(Graph* graph, Set* octset, Set* partial) { Set* subgraph_vertices = new Set(); for (auto it = graph->begin(); it != graph->end(); ++it) { if (octset->contains(*it) || !partial->contains(*it)) { subgraph_vertices->insert(*it); } } Graph* h = graph->subgraph(subgraph_vertices); delete subgraph_vertices; Set* cover = std_apx(h); for (Set::Iterator it = partial->begin(); it != partial->end(); ++it) { cover->insert(*it); } delete h; return cover; } Set* oct_lift(Graph* graph, Set* octset, Set* partial) { Graph* h = graph->subgraph(octset); Set* cover = std_apx(h); for (Set::Iterator it = partial->begin(); it != partial->end(); ++it) { cover->insert(*it); } delete h; Set* subgraph_vertices = new Set(); for (auto it = graph->begin(); it != graph->end(); ++it) { if (!cover->contains(*it)) { subgraph_vertices->insert(*it); } } h = graph->subgraph(subgraph_vertices); Set* bipcover = bip_exact(h); for (Set::Iterator it = bipcover->begin(); it != bipcover->end(); ++it) { cover->insert(*it); } delete h; delete subgraph_vertices; delete bipcover; return cover; } Set* bip_lift(Graph* graph, Set* octset, Set* partial) { Graph* h = new Graph(); for (auto iu = graph->begin(); iu != graph->end(); ++iu) { int u = *iu; if (!octset->contains(u)) { continue; } Set* nbrs = graph->neighbors(u); for (Set::Iterator iv = nbrs->begin(); iv != nbrs->end(); ++iv) { int v = *iv; if (!octset->contains(v) && !partial->contains(v)) { h->add_edge(u, v); } } } Set* cover = bip_exact(h); delete h; Set* subgraph_vertices = new Set(); for (Set::Iterator it = octset->begin(); it != octset->end(); ++it) { if (!cover->contains(*it)) { subgraph_vertices->insert(*it); } } h = graph->subgraph(subgraph_vertices); delete subgraph_vertices; Set* octcover = std_apx(h); delete h; for (Set::Iterator it = partial->begin(); it != partial->end(); ++it) { cover->insert(*it); } for (Set::Iterator it = octcover->begin(); it != octcover->end(); ++it) { cover->insert(*it); } delete octcover; return cover; } Set* recursive_lift(Graph* graph, Set* octset, Set* partial) { Set* subgraph_vertices = new Set(); for (auto it = graph->begin(); it != graph->end(); ++it) { if (octset->contains(*it) || !partial->contains(*it)) { subgraph_vertices->insert(*it); } } Graph* h = graph->subgraph(subgraph_vertices); delete subgraph_vertices; Set* octset2 = vertex_delete(h); subgraph_vertices = new Set(); for (auto it = h->begin(); it != h->end(); ++it) { if (!octset2->contains(*it)) { subgraph_vertices->insert(*it); } } Graph* g = h->subgraph(subgraph_vertices); delete h; delete subgraph_vertices; Set* cover = bip_exact(g); for (Set::Iterator it = partial->begin(); it != partial->end(); ++it) { cover->insert(*it); } for (Set::Iterator it = octset2->begin(); it != octset2->end(); ++it) { cover->insert(*it); } delete octset2; delete g; return cover; } Set* recursive_oct_lift(Graph* graph, Set* octset, Set* partial) { Graph* h = graph->subgraph(octset); Set* octset2 = vertex_delete(h); Set* subgraph_vertices = new Set(); for (auto it = h->begin(); it != h->end(); ++it) { if (!octset2->contains(*it)) { subgraph_vertices->insert(*it); } } Graph* g = h->subgraph(subgraph_vertices); delete h; delete subgraph_vertices; Set* cover = bip_exact(g); delete g; for (Set::Iterator it = octset2->begin(); it != octset2->end(); ++it) { cover->insert(*it); } delete octset2; for (Set::Iterator it = partial->begin(); it != partial->end(); ++it) { cover->insert(*it); } subgraph_vertices = new Set(); for (auto it = graph->begin(); it != graph->end(); ++it) { if (!cover->contains(*it)) { subgraph_vertices->insert(*it); } } g = graph->subgraph(subgraph_vertices); delete subgraph_vertices; Set* bipcover = bip_exact(g); delete g; for (Set::Iterator it = bipcover->begin(); it != bipcover->end(); ++it) { cover->insert(*it); } delete bipcover; return cover; } Set* recursive_bip_lift(Graph* graph, Set* octset, Set* partial) { Graph* h = new Graph(); for (auto iu = graph->begin(); iu != graph->end(); ++iu) { int u = *iu; if (!octset->contains(u)) { continue; } Set* nbrs = graph->neighbors(u); for (Set::Iterator iv = nbrs->begin(); iv != nbrs->end(); ++iv) { int v = *iv; if (!octset->contains(v) && !partial->contains(v)) { h->add_edge(u, v); } } } Set* cover = bip_exact(h); delete h; Set* subgraph_vertices = new Set(); for (Set::Iterator it = octset->begin(); it != octset->end(); ++it) { if (!cover->contains(*it)) { subgraph_vertices->insert(*it); } } h = graph->subgraph(subgraph_vertices); delete subgraph_vertices; Set* octset2 = vertex_delete(h); subgraph_vertices = new Set(); for (auto it = h->begin(); it != h->end(); ++it) { if (!octset2->contains(*it)) { subgraph_vertices->insert(*it); } } Graph* g = h->subgraph(subgraph_vertices); delete subgraph_vertices; delete h; Set* octcover = bip_exact(g); delete g; for (Set::Iterator it = octcover->begin(); it != octcover->end(); ++it) { cover->insert(*it); } delete octcover; for (Set::Iterator it = octset2->begin(); it != octset2->end(); ++it) { cover->insert(*it); } delete octset2; for (Set::Iterator it = partial->begin(); it != partial->end(); ++it) { cover->insert(*it); } return cover; }
22.326531
97
0.605728
TheoryInPractice
42ef587ad8c653cd5c9abdcc52b28aa8fbd0583b
7,253
hpp
C++
libs/ml/include/ml/ops/loss_functions/mean_square_error_loss.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/ops/loss_functions/mean_square_error_loss.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/ops/loss_functions/mean_square_error_loss.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "math/metrics/mean_square_error.hpp" #include "ml/ops/ops.hpp" #include <cassert> #include <memory> #include <vector> namespace fetch { namespace ml { namespace ops { template <class T> class MeanSquareErrorLoss : public Ops<T> { public: using ArrayType = T; using DataType = typename ArrayType::Type; using SizeType = typename ArrayType::SizeType; using VecTensorType = typename Ops<T>::VecTensorType; explicit MeanSquareErrorLoss(ArrayType const &weightings = ArrayType()) : weightings_(weightings) {} ~MeanSquareErrorLoss() override = default; void Forward(VecTensorType const &inputs, ArrayType &output) override { assert(inputs.size() == 2); assert(inputs.at(0)->shape() == inputs.at(1)->shape()); if (weightings_.size() == static_cast<SizeType>(0)) { output(0, 0) = fetch::math::MeanSquareError((*inputs.at(0)), (*inputs.at(1))); } // rescale according to weights else { SizeType data_size = inputs.at(0)->shape(inputs.at(0)->shape().size() - 1); auto it1 = inputs.at(0)->cbegin(); auto it2 = inputs.at(1)->cbegin(); // weighting is scalar if (weightings_.shape().size() == static_cast<SizeType>(1)) { while (it1.is_valid()) { DataType d = (*it1) - (*it2); output(0, 0) += (d * d) * weightings_(0); ++it1; ++it2; } } // weighting tensor is same shape as input (one weight for every parameter) else if (weightings_.shape() == inputs.at(0)->shape()) { auto w_it = weightings_.cbegin(); while (it1.is_valid()) { DataType d = (*it1) - (*it2); output(0, 0) += (d * d) * (*w_it); ++it1; ++it2; ++w_it; } } // weighting is a batch_size vector (one weight per data point) else if (weightings_.shape() == std::vector<SizeType>{data_size}) { SizeType data_count = 0; SizeType data_stride; fetch::math::Divide(inputs.at(0)->size(), weightings_.size(), data_stride); auto w_it = weightings_.cbegin(); while (it1.is_valid()) { DataType d = (*it1) - (*it2); output(0, 0) += (d * d) * (*w_it); ++it1; ++it2; ++data_count; if (data_count == data_stride) { data_count = 0; ++w_it; } } } // divide by number of elements fetch::math::Divide(output(0, 0), static_cast<DataType>(inputs.at(0)->size()), output(0, 0)); } // division by 2 allows us to cancel out with a 2 in the derivative for optimisation fetch::math::Divide(output(0, 0), static_cast<DataType>(2), output(0, 0)); } /** * Gradients for Mean Square Error Loss would usually be of the form: * grad[0] = 2 * err * (in[0] - in[1]) / data_size * grad[1] = -2 * err * (in[0] - in[1]) / data_size * * However we make a few alterations: * 1. we ignore the gradient for the ground truth (i.e. grad[1]), * 2. we drop the 2 since we divide by 2 in forward pass, * 3. we must incorporate the weightings, * * so the modified gradient is computed as: * grad[0] = (err * (in[0] - in[1]) * weighting) / data_size * grad[1] = grad[0] -- SHOULD NOT BE USED * * @param inputs vector of input_tensor and ground_truth tensor (order is important) * @param error_signal error_signal passed back from next layer - since there should not be a next * layer the calling function is required to set this to a tensor of size 1 and value 1 * @return */ std::vector<ArrayType> Backward(VecTensorType const &inputs, ArrayType const & error_signal) override { FETCH_UNUSED(error_signal); assert(inputs.size() == 2); assert(inputs.at(0)->shape() == inputs.at(1)->shape()); ArrayType return_signal(inputs.front()->shape()); SizeType data_size = inputs.at(0)->shape(inputs.at(0)->shape().size() - 1); auto count = static_cast<DataType>(data_size); // backprop update rule varies depending on shape of weightings auto a_it = inputs.at(0)->cbegin(); auto b_it = inputs.at(1)->cbegin(); auto r_it = return_signal.begin(); // no weighting if (weightings_.size() == static_cast<SizeType>(0)) { while (r_it.is_valid()) { *r_it = ((*a_it) - (*b_it)) / count; ++a_it; ++b_it; ++r_it; } } else { // weighting is scalar if (weightings_.shape().size() == static_cast<SizeType>(1)) { auto weight_over_count = weightings_(0) / count; while (r_it.is_valid()) { *r_it = ((*a_it) - (*b_it)) * weight_over_count; ++a_it; ++b_it; ++r_it; } } // weighting tensor is same shape as input (one weight for every parameter) else if (weightings_.shape() == inputs.at(0)->shape()) { auto w_it = weightings_.cbegin(); while (r_it.is_valid()) { *r_it = (((*a_it) - (*b_it)) * (*w_it)) / (count); ++a_it; ++b_it; ++r_it; ++w_it; } } // weighting is a batch_size vector (one weight per data point) else if (weightings_.shape() == std::vector<SizeType>{data_size}) { auto w_it = weightings_.cbegin(); SizeType data_count = 0; SizeType data_stride; fetch::math::Divide(inputs.at(0)->size(), weightings_.size(), data_stride); while (r_it.is_valid()) { *r_it = (((*a_it) - (*b_it)) * (*w_it)) / (count); ++a_it; ++b_it; ++r_it; // update weight value once per data point ++data_count; if (data_count == data_stride) { data_count = 0; ++w_it; } } } else { throw std::runtime_error("input or weightings_shape invalid"); } } return {return_signal, return_signal}; } std::vector<typename T::SizeType> ComputeOutputShape(VecTensorType const &inputs) const override { FETCH_UNUSED(inputs); return {1, 1}; } static constexpr char const *DESCRIPTOR = "MeanSquareErrorLoss"; private: ArrayType weightings_; }; } // namespace ops } // namespace ml } // namespace fetch
29.971074
100
0.560182
jinmannwong
42f17c77b425dc71ee0a5cfa35ce4258403145c2
1,477
cc
C++
src/libc/wchar/ungetwc_test.cc
NuxiNL/CloudLibc
d361c06c3fab3a7814d05b4630abe6da0cc7d757
[ "BSD-2-Clause" ]
298
2015-03-04T13:36:51.000Z
2021-12-19T05:11:58.000Z
src/libc/wchar/ungetwc_test.cc
NuxiNL/CloudLibc
d361c06c3fab3a7814d05b4630abe6da0cc7d757
[ "BSD-2-Clause" ]
31
2015-07-27T14:51:55.000Z
2020-09-14T15:59:57.000Z
src/libc/wchar/ungetwc_test.cc
NuxiNL/CloudLibc
d361c06c3fab3a7814d05b4630abe6da0cc7d757
[ "BSD-2-Clause" ]
18
2016-03-27T13:49:22.000Z
2021-09-21T19:02:04.000Z
// Copyright (c) 2015 Nuxi, https://nuxi.nl/ // // SPDX-License-Identifier: BSD-2-Clause #include <errno.h> #include <locale.h> #include <stdio.h> #include <unistd.h> #include <wchar.h> #include "gtest/gtest.h" TEST(ungetwc, eilseq) { FILE *fp = tmpfile(); ASSERT_NE(NULL, fp); // Attempted to push a Unicode character into an ASCII stream. ASSERT_EQ(WEOF, ungetwc(L'☃', fp)); ASSERT_FALSE(ferror(fp)); ASSERT_EQ(EILSEQ, errno); ASSERT_EQ(0, fclose(fp)); } TEST(ungetwc, einval) { // Pushing WEOF should leave the stream unchanged. FILE *fp = tmpfile(); ASSERT_NE(NULL, fp); ASSERT_EQ(WEOF, ungetwc(WEOF, fp)); ASSERT_EQ(EINVAL, errno); ASSERT_EQ(0, fclose(fp)); } TEST(ungetwc, enospc) { FILE *fp = tmpfile(); ASSERT_NE(NULL, fp); // Push back characters until it fails. wint_t ret; for (;;) { ret = ungetwc(L'a', fp); if (ret == WEOF) break; ASSERT_EQ(L'a', ret); } // Final push should have failed with ENOSPC. ASSERT_EQ(WEOF, ret); ASSERT_FALSE(ferror(fp)); ASSERT_EQ(ENOSPC, errno); ASSERT_EQ(0, fclose(fp)); } TEST(ungetwc, success) { // Create a Unicode capable stream containing a Unicode snowman. FILE *fp = tmpfile_l(LC_C_UNICODE_LOCALE); ASSERT_NE(NULL, fp); ASSERT_EQ(L'☃', ungetwc(L'☃', fp)); // Character should be decomposed into UTF-8. char buf[4]; ASSERT_EQ(3, fread(buf, 1, sizeof(buf), fp)); buf[3] = '\0'; ASSERT_STREQ("☃", buf); ASSERT_EQ(0, fclose(fp)); }
21.405797
66
0.647935
NuxiNL
42f6531ebc2e944c59b698966f111aeaab0a16ae
505
hpp
C++
include/xul/data/collection.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/data/collection.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/data/collection.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include <xul/lang/object.hpp> #include <xul/data/iterator.hpp> #include <xul/data/element_traits.hpp> namespace xul { template <typename T, typename TraitsT = element_traits<T> > class collection : public object { public: typedef T element_type; typedef TraitsT traits_type; virtual int get_count() const = 0; virtual iterator<typename TraitsT::const_accessor_type>* iterate() const = 0; virtual iterator<typename TraitsT::accessor_type>* iterate_ref() = 0; }; }
20.2
81
0.728713
hindsights
42f7541754e038a3a0cd02174229e8f3410e355e
588
hpp
C++
books/tech/cpp/std-14/m_gregoire-professional_cpp-3_ed/ch_09-discovering_inheritance_techniques/02_the_weather_prediction_class/WeatherPrediction.hpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
books/techno/cpp/__intermediate/professional_cpp_3_ed_m_gregoire/code/chapter_9/02_the_weather_prediction_class/WeatherPrediction.hpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
books/techno/cpp/__intermediate/professional_cpp_3_ed_m_gregoire/code/chapter_9/02_the_weather_prediction_class/WeatherPrediction.hpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
#ifndef WEATHER_PREDICTION_HPP #define WEATHER_PREDICTION_CPP #include <string> class WeatherPrediction { public: virtual ~WeatherPrediction(); virtual auto setCurrentTempFahrenheit(int inTemp) -> void; virtual auto setPositionOfJupiter(int inDistanceFromMars) -> void; virtual int getTomorrowTempFahrenheit() const; virtual double getChanceOfRain() const; virtual void showResult() const; virtual std::string getTemperature() const; private: int mCurrentTempFahrenheit; int mDistanceFromMars; }; #endif
26.727273
74
0.707483
ordinary-developer
42f88ef5e0712acd05f8351ac7b5cb2b9499eb9b
13,732
cpp
C++
dev/Gems/EMotionFX/Code/EMotionFX/Source/LookAtController.cpp
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Gems/EMotionFX/Code/EMotionFX/Source/LookAtController.cpp
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
null
null
null
dev/Gems/EMotionFX/Code/EMotionFX/Source/LookAtController.cpp
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // include the required headers #include "LookAtController.h" #include "Node.h" #include "ActorInstance.h" #include "NodeLimitAttribute.h" #include "GlobalPose.h" #include "TransformData.h" //#include <MCore/Source/SwingAndTwist.h> namespace EMotionFX { // constructor LookAtController::LookAtController(ActorInstance* actorInstance, uint32 nodeIndex) : GlobalSpaceController(actorInstance) { MCORE_ASSERT(nodeIndex < actorInstance->GetNumNodes()); mNodeIndex = nodeIndex; mGoal.Set(0.0f, 0.0f, 0.0f); mInterpolationSpeed = 1.0f; // we need to keep a copy of the rotation MCore::Matrix globalTM = actorInstance->GetTransformData()->GetGlobalInclusiveMatrices()[ nodeIndex ]; mRotationQuat.FromMatrix(globalTM.Normalized()); mRotationQuat.Normalize(); mPostRotation.Identity(); mPreRotation.Identity(); // set the limits accoring to the model's current limits if it has them set, otherwise just use default values NodeLimitAttribute* limit = (NodeLimitAttribute*)actorInstance->GetActor()->GetSkeleton()->GetNode(nodeIndex)->GetAttributeByType(NodeLimitAttribute::TYPE_ID); // set the limits if (limit) { SetEulerConstraints(limit->GetRotationMin(), limit->GetRotationMax()); } else { mEllipseOrientation.Identity(); mEllipseRadii.Set(1.0f, 1.0f); mMinMaxTwist.Set(0.0f, 0.0f); } // disable the constraints mConstraintType = CONSTRAINT_NONE; // disable EMotion FX 2 compatibility mode mEMFX2CompatibleMode = false; // specify that this controller will modify all nodes that come after the start node inside the hierarchy RecursiveSetNodeMask(mNodeIndex, true); } // destructor LookAtController::~LookAtController() { } // creation LookAtController* LookAtController::Create(ActorInstance* actorInstance, uint32 nodeIndex) { return new LookAtController(actorInstance, nodeIndex); } // reset the controller void LookAtController::Reset() { // get the current global space transform MCore::Matrix globalTM = mActorInstance->GetTransformData()->GetGlobalInclusiveMatrix(mNodeIndex); globalTM.Normalize(); // remove scaling // convert it into a quaternion and normalize it mRotationQuat.FromMatrix(globalTM); mRotationQuat.Normalize(); } // the main update method void LookAtController::Update(GlobalPose* outPose, float timePassedInSeconds) { /*// get the global space matrices and scale values MCore::Matrix* globalMatrices = outPose->GetGlobalMatrices(); MCore::Vector3* globalScales = mActorInstance->GetGlobalPose()->GetScales(); // calculate the new forward vector MCore::Vector3 forward = (mGoal - globalMatrices[mNodeIndex].GetTranslation()).SafeNormalized(); MCore::Vector3 up; const uint32 parentIndex = mActorInstance->GetActor()->GetSkeleton()->GetNode(mNodeIndex)->GetParentIndex(); MCore::Matrix parentGlobalTM; parentGlobalTM.Identity(); // if we have a parent node if (parentIndex != MCORE_INVALIDINDEX32) { parentGlobalTM = globalMatrices[parentIndex].Normalized(); // get the up vector from the parent if it exsists up = (mPreRotation * parentGlobalTM).GetUp().SafeNormalized(); } else // a root node, use the up vector of the node itself { up = (mPreRotation * globalMatrices[mNodeIndex].Normalized()).GetUp().SafeNormalized(); } // caclculate the right and up vector we wish to use MCore::Vector3 right = up.Cross(forward).SafeNormalized(); up = forward.Cross(right).SafeNormalized(); // build the destination rotation matrix MCore::Matrix destRotation; destRotation.Identity(); destRotation.SetRight(right); destRotation.SetUp(up); destRotation.SetForward(forward); // at this point, destRotation contains the global space orientation that we would like our node do be using // if we want to apply constraints if (mConstraintType != CONSTRAINT_NONE) { // find the destination relative to the node's parent if the node has one if (parentIndex != MCORE_INVALIDINDEX32) { destRotation = destRotation * parentGlobalTM.Inversed(); } // now destRotation contains the exact orientation we wish to apply constraints to (relative to the identity matrix) // multiply by the inverse of the ellipse's orientation, and rotate our coordinate system into 'ellipse space' if (mEMFX2CompatibleMode) { destRotation = mEllipseOrientation.Inversed() * destRotation; // OLD EMotion FX 2 / EMotion FX v3.0 mul order } else { destRotation = destRotation * mEllipseOrientation.Inversed(); } // calculate the swing and twist MCore::SwingAndTwist sAndt(destRotation); // apply swing constraints if (mConstraintType == CONSTRAINT_ELLIPSE) // constraint using an ellipse { sAndt.ConstrainSwingWithEllipse(mEllipseRadii); } else if (mConstraintType == CONSTRAINT_RECTANGLE) // constraint using a rectangle { // the rectangle method will be a lot faster than the ellipse, but doesn't look anywhere near as good // this should probably only be used for distant models using a lower LOD // treat the ellipse's radii as bounds for a rectangle sAndt.ConstrainSwingWithRectangle(mEllipseRadii); } // apply twist constraints sAndt.ConstrainTwist(mMinMaxTwist); // convert the swing and twist back to a matrix destRotation = sAndt.ToMatrix(); // rotate back out of ellipse space if (mEMFX2CompatibleMode) { destRotation = mEllipseOrientation * destRotation; // OLD EMotion FX 2 / EMotion FX v3.0 mul order } else { destRotation = destRotation * mEllipseOrientation; } // if we converted our coord system into the space relative to the parent, then convert it back to global space if (parentIndex != MCORE_INVALIDINDEX32) { destRotation = destRotation * parentGlobalTM; } } // apply the post rotation matrix destRotation = mPostRotation * destRotation; // interpolate between the current rotation and the destination rotation float speed = mInterpolationSpeed * timePassedInSeconds * 6.0f; speed = MCore::Clamp<float>(speed, 0.0f, 1.0f); mRotationQuat = mRotationQuat.Slerp(MCore::Quaternion(destRotation), speed); mRotationQuat.Normalize(); // TODO: this normally shouldn't be needed as Slerp already normalizes, still it is needed to prevent some suddenly introduced scaling // create the rotation matrix from the rotation quat destRotation = mRotationQuat.ToMatrix(); // scale the matrix and put it back in the right position destRotation.Scale3x3(globalScales[mNodeIndex]); destRotation.SetTranslation(globalMatrices[mNodeIndex].GetTranslation()); // update the matrix with forward kinematics mActorInstance->RecursiveUpdateGlobalTM(mNodeIndex, &destRotation, globalMatrices);*/ } // Calculate the Ellipse radii and the twist value from the min and max euler angles void LookAtController::SetEulerConstraints(const MCore::Vector3& minVals, const MCore::Vector3& maxVals) { // twist is z mMinMaxTwist.SetX(minVals.z); mMinMaxTwist.SetY(maxVals.z); // Offset is the average const float xOffset = (minVals.x + maxVals.x) * 0.5f; const float yOffset = (minVals.y + maxVals.y) * 0.5f; // these lines are the same as above mEllipseRadii.SetX(maxVals.x - xOffset); mEllipseRadii.SetY(maxVals.y - yOffset); // build the apropriate matrices MCore::Matrix xOffsetMat, yOffsetMat, zRot; xOffsetMat.SetRotationMatrixX(xOffset); yOffsetMat.SetRotationMatrixY(yOffset); mEllipseOrientation = xOffsetMat * yOffsetMat; // TODO: check if this is required // basically just swaps the x and y axii if (mEMFX2CompatibleMode) { zRot.SetRotationMatrixZ(-MCore::Math::halfPi); mEllipseOrientation = zRot * mEllipseOrientation; } } // clone the controller GlobalSpaceController* LookAtController::Clone(ActorInstance* targetActorInstance) { // create the new constraint and copy its members LookAtController* newController = new LookAtController(targetActorInstance, mNodeIndex); // copy the settings newController->mPreRotation = mPreRotation; newController->mPostRotation = mPostRotation; newController->mEllipseOrientation = mEllipseOrientation; newController->mRotationQuat = mRotationQuat; newController->mGoal = mGoal; newController->mEllipseRadii = mEllipseRadii; newController->mMinMaxTwist = mMinMaxTwist; newController->mInterpolationSpeed = mInterpolationSpeed; newController->mConstraintType = mConstraintType; // copy the base class weight settings // this makes sure the controller is in the same activated/deactivated and blending state // as the source controller that we are cloning newController->CopyBaseClassWeightSettings(this); // return the new controller return newController; } // get the type ID uint32 LookAtController::GetType() const { return LookAtController::TYPE_ID; } // get the type string const char* LookAtController::GetTypeString() const { return "LookAtController"; } // get the goal const MCore::Vector3& LookAtController::GetGoal() const { return mGoal; } // set the goal position void LookAtController::SetGoal(const MCore::Vector3& goalGlobalSpacePos) { mGoal = goalGlobalSpacePos; } // set the interpolation speed void LookAtController::SetInterpolationSpeed(float factor) { mInterpolationSpeed = factor; } // get the interplation speed float LookAtController::GetInterpolationSpeed() const { return mInterpolationSpeed; } // set the pre-rotation matrix void LookAtController::SetPreRotation(const MCore::Matrix& mat) { mPreRotation = mat; } // get the pre-rotation matrix const MCore::Matrix& LookAtController::GetPreRotation() const { return mPreRotation; } // set the post rotation matrix void LookAtController::SetPostRotation(const MCore::Matrix& mat) { mPostRotation = mat; } // get the post rotation matrix const MCore::Matrix& LookAtController::GetPostRotation() const { return mPostRotation; } // set the ellipse orientation void LookAtController::SetEllipseOrientation(const MCore::Matrix& mat) { mEllipseOrientation = mat; } // get the ellipse orientation const MCore::Matrix& LookAtController::GetEllipseOrientation() const { return mEllipseOrientation; } // set the ellipse radii void LookAtController::SetEllipseRadii(const AZ::Vector2& radii) { mEllipseRadii = radii; } // set the ellipse radii using two floats void LookAtController::SetEllipseRadii(float rx, float ry) { mEllipseRadii.Set(rx, ry); } // set the twist rotation limits void LookAtController::SetTwist(float minValue, float maxValue) { mMinMaxTwist.Set(minValue, maxValue); } // set the twist rotation limits using a Vector2 void LookAtController::SetTwist(const AZ::Vector2& minMaxTwist) { mMinMaxTwist = minMaxTwist; } // set the constraint type void LookAtController::SetConstraintType(EConstraintType constraintType) { mConstraintType = constraintType; } // get the constraint type LookAtController::EConstraintType LookAtController::GetConstraintType() const { return mConstraintType; } // enable/disable EMotion FX 2 compatibility mode void LookAtController::SetEMFX2CompatbilityModeEnabled(bool enabled) { mEMFX2CompatibleMode = enabled; } // check EMotion FX 2 compatibility mode bool LookAtController::GetIsEMFX2CompatbilityModeEnabled() const { return mEMFX2CompatibleMode; } } // namespace EMotionFX
32.851675
169
0.651325
horvay
42f93e5e12f8e7523524e1bf42cac2b1bbcc6b15
1,211
cc
C++
unit-test/test_thread_group.cc
anqin/trident
1291596db0532b07865920b46165722a6c6244f4
[ "BSD-3-Clause" ]
6
2015-03-03T14:22:29.000Z
2021-07-20T13:20:28.000Z
unit-test/test_thread_group.cc
anqin/trident
1291596db0532b07865920b46165722a6c6244f4
[ "BSD-3-Clause" ]
null
null
null
unit-test/test_thread_group.cc
anqin/trident
1291596db0532b07865920b46165722a6c6244f4
[ "BSD-3-Clause" ]
5
2015-03-03T14:30:18.000Z
2018-04-12T06:01:39.000Z
// Copyright (c) 2014 The Trident 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 <gtest/gtest.h> #include <trident/thread_group.h> #include <trident/closure.h> class ThreadGroupTest: public ::testing::Test { protected: ThreadGroupTest() {} virtual ~ThreadGroupTest() {} virtual void SetUp() { // Called before every TEST_F(ThreadGroupTest, *) } virtual void TearDown() { // Called after every TEST_F(ThreadGroupTest, *) } }; static void test_1_function(bool* called) { *called = true; } TEST_F(ThreadGroupTest, test_1) { trident::ThreadGroup* thread_group = new trident::ThreadGroup(4); bool dispatch_called = false; thread_group->dispatch(trident::NewClosure(&test_1_function, &dispatch_called)); bool post_called = false; thread_group->post(trident::NewClosure(&test_1_function, &post_called)); delete thread_group; ASSERT_TRUE(dispatch_called); ASSERT_TRUE(post_called); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } /* vim: set ts=4 sw=4 sts=4 tw=100 */
23.288462
84
0.690339
anqin
42fd121c07c5f2a1be8b451f2b77a4580177334c
1,158
cc
C++
components/arc/test/fake_policy_instance.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
components/arc/test/fake_policy_instance.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/arc/test/fake_policy_instance.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/arc/test/fake_policy_instance.h" #include "base/run_loop.h" namespace arc { FakePolicyInstance::FakePolicyInstance( mojo::InterfaceRequest<mojom::PolicyInstance> request, ArcBridgeService* bridge_service) : binding_(this, std::move(request)), bridge_service_(bridge_service) { bridge_service_->policy()->AddObserver(this); } FakePolicyInstance::~FakePolicyInstance() { bridge_service_->policy()->RemoveObserver(this); } void FakePolicyInstance::OnPolicyUpdated() {} void FakePolicyInstance::Init(mojom::PolicyHostPtr host_ptr) { host_ptr_ = std::move(host_ptr); } void FakePolicyInstance::OnInstanceReady() { ready_ = true; } void FakePolicyInstance::WaitForOnPolicyInstanceReady() { while (!ready_) { base::RunLoop().RunUntilIdle(); } } void FakePolicyInstance::CallGetPolicies( const mojom::PolicyHost::GetPoliciesCallback& callback) { host_ptr_->GetPolicies(callback); base::RunLoop().RunUntilIdle(); } } // namespace arc
26.318182
75
0.752159
Wzzzx
42fd14d29eb945747cf63df671ab8fe8a34d816d
51,984
cpp
C++
src/TSSequencerWidgetBase.cpp
j4s0n-c/trowaSoft-VCV
9cd0d05607c88e95200472725df1d032b42130cd
[ "MIT" ]
91
2017-11-28T07:23:09.000Z
2022-03-28T08:31:51.000Z
src/TSSequencerWidgetBase.cpp
j4s0n-c/trowaSoft-VCV
9cd0d05607c88e95200472725df1d032b42130cd
[ "MIT" ]
59
2017-11-28T06:12:18.000Z
2022-03-18T09:00:59.000Z
src/TSSequencerWidgetBase.cpp
j4s0n-c/trowaSoft-VCV
9cd0d05607c88e95200472725df1d032b42130cd
[ "MIT" ]
15
2017-11-28T13:42:35.000Z
2021-12-26T08:03:37.000Z
#include <string.h> #include <stdio.h> //#include "widgets.hpp" #include "trowaSoft.hpp" using namespace rack; //#include "dsp/digital.hpp" #include "trowaSoftComponents.hpp" #include "trowaSoftUtilities.hpp" #include "TSSequencerModuleBase.hpp" #include "TSSequencerWidgetBase.hpp" #include "TSOSCConfigWidget.hpp" //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSequencerWidgetBase() - Base constructor. // Instantiate a trowaSoft Sequencer widget. v0.60 must have module as param. // @seqModule : (IN) Pointer to the sequencer module. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TSSequencerWidgetBase::TSSequencerWidgetBase(TSSequencerModuleBase* seqModule) : TSSModuleWidgetBase(seqModule, /*randomizeParameters*/ false) { box.size = Vec(26 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT); return; } //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // Add common controls to the UI widget for trowaSoft sequencers. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSequencerWidgetBase::addBaseControls(bool addGridLines) { TSSequencerModuleBase *thisModule = NULL; if (this->module != NULL) { thisModule = dynamic_cast<TSSequencerModuleBase*>(this->module); } bool isPreview = thisModule == NULL; //////////////////////////////////// // DISPLAY //////////////////////////////////// { display = new TSSeqDisplay(); display->box.pos = Vec(13, 24); display->box.size = Vec(363, 48); display->module = thisModule; addChild(display); } //////////////////////////////////// // OSC configuration screen. // Should be a popup but J just wants it on the screen. //////////////////////////////////// if (!isPreview) { TSOSCConfigWidget* oscConfig = new TSOSCConfigWidget(thisModule, TSSequencerModuleBase::ParamIds::OSC_SAVE_CONF_PARAM, TSSequencerModuleBase::ParamIds::OSC_AUTO_RECONNECT_PARAM, thisModule->oscCurrentClient, thisModule->currentOSCSettings.oscTxIpAddress.c_str(), thisModule->currentOSCSettings.oscTxPort, thisModule->currentOSCSettings.oscRxPort); oscConfig->setVisible(false); oscConfig->box.pos = display->box.pos; oscConfig->box.size = display->box.size; this->oscConfigurationScreen = oscConfig; addChild(oscConfig); } //////////////////////////////////// // Pattern Sequencer Configuration / Auto-Play Patterns //////////////////////////////////// if (!isPreview && thisModule->allowPatternSequencing) { pattSeqConfigurationScreen = new TSSeqPatternSeqConfigWidget(thisModule); pattSeqConfigurationScreen->setVisible(false); pattSeqConfigurationScreen->box.pos = display->box.pos; pattSeqConfigurationScreen->box.size = display->box.size; addChild(pattSeqConfigurationScreen); } //////////////////////////////////// // Labels //////////////////////////////////// { FramebufferWidget* labelContainer = new FramebufferWidget(); labelContainer->box.pos = Vec(0, 0); labelContainer->box.size = Vec(box.size.x, 380); addChild(labelContainer); labelArea = new TSSeqLabelArea(); labelArea->box.pos = Vec(0, 0); labelArea->box.size = Vec(box.size.x, 380); labelArea->module = thisModule; labelArea->drawGridLines = addGridLines; labelContainer->addChild(labelArea); //addChild(labelArea); } // Screws: addChild(createWidget<ScrewBlack>(Vec(0, 0))); addChild(createWidget<ScrewBlack>(Vec(box.size.x - 15, 0))); addChild(createWidget<ScrewBlack>(Vec(0, box.size.y - 15))); addChild(createWidget<ScrewBlack>(Vec(box.size.x - 15, box.size.y - 15))); // Input Controls ================================================== // Run (Toggle) NVGcolor lightColor = nvgRGBAf(0.7, 0.7, 0.7, 0.8); //TSColors::COLOR_WHITE Vec btnSize = Vec(50,22); addParam(createParam<TS_PadBtn>(Vec(15, 320), thisModule, TSSequencerModuleBase::ParamIds::RUN_PARAM));//, 0.0, 1.0, 0.0)); TS_LightString* item = dynamic_cast<TS_LightString*>(TS_createColorValueLight<TS_LightString>(/*pos */ Vec(15, 320), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::RUNNING_LIGHT, /* size */ btnSize, /* color */ lightColor)); item->lightString = "RUN"; addChild(item); // Reset (Momentary) addParam(createParam<TS_PadBtn>(Vec(15, 292), thisModule, TSSequencerModuleBase::ParamIds::RESET_PARAM));//, 0.0, 1.0, 0.0)); item = dynamic_cast<TS_LightString*>(TS_createColorValueLight<TS_LightString>(/*pos */ Vec(15, 292), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::RESET_LIGHT, /* size */ btnSize, /* color */ lightColor)); item->lightString = "RESET"; addChild(item); // Paste button: addParam(createParam<TS_PadBtn>(Vec(15, 115), thisModule, TSSequencerModuleBase::ParamIds::PASTE_PARAM));//, 0.0, 1.0, 0.0)); item = dynamic_cast<TS_LightString*>(TS_createColorValueLight<TS_LightString>(/*pos */ Vec(15, 115), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::PASTE_LIGHT, /* size */ btnSize, /* color */ lightColor)); item->lightString = "PASTE"; // if (!isPreview) // thisModule->pasteLight = item; pasteLight = item; addChild(item); // Top Knobs : Keep references for later int knobRow = 79; int knobStart = 27; int knobSpacing = 61; TS_RoundBlackKnob* outKnobPtr = NULL; // Pattern Playback Select (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart, knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_PATTERN_PLAY_PARAM));//, /*min*/ 0.0, /*max*/ TROWA_SEQ_NUM_PATTERNS - 1, /*default value*/ 0.0)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Clock BPM (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 1), knobRow), thisModule, TSSequencerModuleBase::ParamIds::BPM_PARAM));//, TROWA_SEQ_BPM_KNOB_MIN, TROWA_SEQ_BPM_KNOB_MAX, (TROWA_SEQ_BPM_KNOB_MAX + TROWA_SEQ_BPM_KNOB_MIN) / 2)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; addParam(outKnobPtr); // Steps (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 2), knobRow), thisModule, TSSequencerModuleBase::ParamIds::STEPS_PARAM));//, 1.0, this->maxSteps, this->maxSteps)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Output Mode (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 3), knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_OUTPUT_VALUE_MODE_PARAM));//, 0, TROWA_SEQ_NUM_MODES - 1, TSSequencerModuleBase::ValueMode::VALUE_TRIGGER)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->minAngle = -0.6*M_PI; outKnobPtr->maxAngle = 0.6*M_PI; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Pattern Edit Select (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 4), knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_PATTERN_EDIT_PARAM));//, /*min*/ 0.0, /*max*/ TROWA_SEQ_NUM_PATTERNS - 1, /*default value*/ 0)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Selected Gate/Voice/Channel (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 5), knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_CHANNEL_PARAM));//, /*min*/ 0.0, /*max*/ TROWA_SEQ_NUM_CHNLS - 1, /*default value*/ 0)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); //======================================================= // Small buttons next to knobs //======================================================= Vec ledSize = Vec(15,15); int dx = 28; float xLightOffset = 1.5f; float yLightOffset = 1.5f; TS_LEDButton* btn; knobStart += 2; int y = knobRow; int x = knobStart; Vec ledBtnSize = Vec(ledSize.x - 2, ledSize.y - 2); //-------------------------------------------------------------------------- // PATTERN SEQ: Pattern Sequencing Configuration (+Config/Enabled Lights): //-------------------------------------------------------------------------- x = knobStart + dx; // 30 if (!isPreview && thisModule->allowPatternSequencing) { btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(x, y), module, TSSequencerModuleBase::ParamIds::PATTERN_SEQ_SHOW_CONFIG_PARAM)); btn->setSize(ledBtnSize); addParam(btn); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset, y + yLightOffset), module, TSSequencerModuleBase::LightIds::PATTERN_SEQ_CONFIGURE_LIGHT, ledSize, TSColors::COLOR_WHITE)); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset + 2, y + yLightOffset + 2), module, TSSequencerModuleBase::LightIds::PATTERN_SEQ_ENABLED_LIGHT, Vec(ledSize.x - 4, ledSize.y - 4), TS_PATTERN_SEQ_STATUS_COLOR)); } //------------------------------------------------------- // OSC: Configuration Button (+Config/Enabled Lights): //------------------------------------------------------- x = knobStart + (knobSpacing * 3) + dx; // 30 if (isPreview || thisModule->allowOSC) { btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(x, y), module, TSSequencerModuleBase::ParamIds::OSC_SHOW_CONF_PARAM));//, 0, 1, 0)); btn->setSize(ledBtnSize); addParam(btn); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset, y + yLightOffset), module, TSSequencerModuleBase::LightIds::OSC_CONFIGURE_LIGHT, ledSize, TSColors::COLOR_WHITE)); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset + 2, y + yLightOffset + 2), module, TSSequencerModuleBase::LightIds::OSC_ENABLED_LIGHT, Vec(ledSize.x - 4, ledSize.y - 4), TSOSC_STATUS_COLOR)); } ColorValueLight* lightPtr = NULL; //------------------------------------------------------- // COPY: Pattern Copy button: //------------------------------------------------------- btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(knobStart + (knobSpacing * 4) + dx, knobRow), module, TSSequencerModuleBase::ParamIds::COPY_PATTERN_PARAM));//, 0, 1, 0)); btn->setSize(ledSize); addParam(btn); lightPtr = dynamic_cast<ColorValueLight*>(TS_createColorValueLight<ColorValueLight>(Vec(knobStart + (knobSpacing * 4) + dx + xLightOffset, knobRow + yLightOffset), module, TSSequencerModuleBase::LightIds::COPY_PATTERN_LIGHT, ledSize, TSColors::COLOR_WHITE)); copyPatternLight = lightPtr; addChild(lightPtr); //------------------------------------------------------- // COPY: Channel Copy button: //------------------------------------------------------- btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(knobStart + (knobSpacing * 5) + dx, knobRow), module, TSSequencerModuleBase::ParamIds::COPY_CHANNEL_PARAM));//, 0, 1, 0)); btn->setSize(ledSize); addParam(btn); lightPtr = dynamic_cast<ColorValueLight*>(TS_createColorValueLight<ColorValueLight>(Vec(knobStart + (knobSpacing * 5) + dx + xLightOffset, knobRow + yLightOffset), module, TSSequencerModuleBase::LightIds::COPY_CHANNEL_LIGHT, ledSize, TSColors::COLOR_WHITE)); copyChannelLight = lightPtr; addChild(lightPtr); //------------------------------------------------------- // CHANGE BPM CALC NOTE (1/4, 1/8, 1/8T, 1/16) //------------------------------------------------------- btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(knobStart + (knobSpacing * 1) + dx, knobRow), module, TSSequencerModuleBase::ParamIds::SELECTED_BPM_MULT_IX_PARAM));//, 0, 1, 0)); btn->setSize(ledSize); addParam(btn); addChild(TS_createColorValueLight<ColorValueLight>(Vec(knobStart + (knobSpacing * 1) + dx + xLightOffset, knobRow + yLightOffset), module, TSSequencerModuleBase::LightIds::SELECTED_BPM_MULT_IX_LIGHT, ledSize, TSColors::COLOR_WHITE)); // Input Jacks: int xStart = 10; int ySpacing = 28; int portStart = 143; // Selected Pattern Playback: addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 0)), thisModule, TSSequencerModuleBase::InputIds::SELECTED_PATTERN_PLAY_INPUT)); // Clock addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 1)), thisModule, TSSequencerModuleBase::InputIds::BPM_INPUT)); // Steps addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 2)), thisModule, TSSequencerModuleBase::InputIds::STEPS_INPUT)); // External Clock addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 3)), thisModule, TSSequencerModuleBase::InputIds::EXT_CLOCK_INPUT)); // Reset addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 4)), thisModule, TSSequencerModuleBase::InputIds::RESET_INPUT)); // Outputs ================================================== // Loop through each channel/voice/gate y = 115; x = 314; int v = 0; float jackDiameter = 20.5; // 28.351 float add = 0; Vec outputLightSize = Vec(jackDiameter + add, jackDiameter + add); const NVGcolor* channelColors = NULL; if (!isPreview) { channelColors = thisModule->voiceColors; } else { channelColors = TSColors::CHANNEL_COLORS; // Point to our default array } for (int r = 0; r < 8; r++) { for (int c = 0; c < 2; c++) { // Triggers / Gates / Output: addOutput(TS_createOutput<TS_Port>(Vec(x, y), thisModule, TSSequencerModuleBase::OutputIds::CHANNELS_OUTPUT+v, /*color*/ channelColors[v])); // Match the color to the trigger/gate/output: addChild(TS_createColorValueLight<TS_LightRing>(/*position*/ Vec(x + 5, y + 5), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::CHANNEL_LIGHTS+v, /*size*/ outputLightSize, /*lightColor*/ channelColors[v % 16], /*backColor*/ channelColors[v % 16])); if (!isPreview) thisModule->lights[TSSequencerModuleBase::LightIds::CHANNEL_LIGHTS + v].value = 0; x += 36; v++; } // end for y += 28; // Next row x = 314; } // end loop through NxM grid return; } // end addBaseControls() //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // step(void) //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSequencerWidgetBase::step() { if (this->module == NULL) return; TSSequencerModuleBase* thisModule = dynamic_cast<TSSequencerModuleBase*>(module); //------------------------------------ // Step Matrix Color //------------------------------------ if (padLightPtrs && colorRGBNotEqual(lastStepMatrixColor, thisModule->currentStepMatrixColor)) { for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { padLightPtrs[r][c]->setColor(thisModule->currentStepMatrixColor); } } } lastStepMatrixColor = thisModule->currentStepMatrixColor; //------------------------------------ // Copy & Paste //------------------------------------ // Change colors of our lights here if (colorRGBNotEqual(thisModule->currentCopyChannelColor, copyChannelLight->color)) { copyChannelLight->setColor(thisModule->currentCopyChannelColor); } if (colorRGBNotEqual(thisModule->currentPasteColor, pasteLight->color)) { pasteLight->setColor(thisModule->currentPasteColor); } //------------------------------------ // Pattern Sequencing //------------------------------------ if (thisModule->allowPatternSequencing) { if (pattSeqConfigurationScreen != NULL) { thisModule->lastShowPatternSequencingConfig = thisModule->showPatternSequencingConfig; if (thisModule->patternSeqConfigTrigger.process(thisModule->params[TSSequencerModuleBase::ParamIds::PATTERN_SEQ_SHOW_CONFIG_PARAM].getValue())) { thisModule->showPatternSequencingConfig = !thisModule->showPatternSequencingConfig; // Set the Configuration Visible if (thisModule->showPatternSequencingConfig) { // SHOW Pattern Config this->display->showDisplay = false; pattSeqConfigurationScreen->setVisible(true); pattSeqConfigurationScreen->ckEnabled->checked = thisModule->patternSequencingOn; // Hide OSC Config thisModule->oscShowConfigurationScreen = false; this->oscConfigurationScreen->setVisible(false); thisModule->lights[TSSequencerModuleBase::LightIds::OSC_CONFIGURE_LIGHT].value = 0.0f; } else { // Hide Pattern Config this->display->showDisplay = !thisModule->oscShowConfigurationScreen; pattSeqConfigurationScreen->setVisible(false); } } // end if show config button pressed. } } // end if we are doing pattern sequencing //------------------------------------ // OSC //------------------------------------ if (thisModule->oscConfigTrigger.process(thisModule->params[TSSequencerModuleBase::ParamIds::OSC_SHOW_CONF_PARAM].getValue())) { thisModule->oscShowConfigurationScreen = !thisModule->oscShowConfigurationScreen; thisModule->lights[TSSequencerModuleBase::LightIds::OSC_CONFIGURE_LIGHT].value = (thisModule->oscShowConfigurationScreen) ? 1.0 : 0.0; this->oscConfigurationScreen->setVisible(thisModule->oscShowConfigurationScreen); this->display->showDisplay = !thisModule->oscShowConfigurationScreen; if (thisModule->oscShowConfigurationScreen) { thisModule->showPatternSequencingConfig = false; // Stop showing pattern configuration if showing if (pattSeqConfigurationScreen != NULL) pattSeqConfigurationScreen->setVisible(false); if (!thisModule->oscInitialized) { // Make sure the ports are available int p = TSOSCConnector::PortInUse(thisModule->currentOSCSettings.oscTxPort); if (p > 0 && p != thisModule->oscId) thisModule->currentOSCSettings.oscTxPort = TSOSCConnector::GetAvailablePortTrans(thisModule->oscId, thisModule->currentOSCSettings.oscTxPort); p = TSOSCConnector::PortInUse(thisModule->currentOSCSettings.oscRxPort); if (p > 0 && p != thisModule->oscId) thisModule->currentOSCSettings.oscRxPort = TSOSCConnector::GetAvailablePortRecv(thisModule->oscId, thisModule->currentOSCSettings.oscRxPort); } this->oscConfigurationScreen->setValues(thisModule->currentOSCSettings.oscTxIpAddress, thisModule->currentOSCSettings.oscTxPort, thisModule->currentOSCSettings.oscRxPort); this->oscConfigurationScreen->ckAutoReconnect->checked = thisModule->oscReconnectAtLoad; this->oscConfigurationScreen->setSelectedClient(thisModule->oscCurrentClient); // OSC Client this->oscConfigurationScreen->btnActionEnable = !thisModule->oscInitialized; this->oscConfigurationScreen->errorMsg = ""; if (thisModule->oscError) { this->oscConfigurationScreen->errorMsg = "Error connecting to " + thisModule->currentOSCSettings.oscTxIpAddress; } this->oscConfigurationScreen->setVisible(true); } else { this->oscConfigurationScreen->setVisible(false); } } if (thisModule->oscShowConfigurationScreen) { // Check for enable/disable if (thisModule->oscConnectTrigger.process(thisModule->params[TSSequencerModuleBase::ParamIds::OSC_SAVE_CONF_PARAM].getValue())) { if (oscConfigurationScreen->btnActionEnable) { // Enable OSC ------------------------------------------------------------------------ // User checked to connect if (!this->oscConfigurationScreen->isValidIpAddress()) { #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("IP Address is not valid."); #endif this->oscConfigurationScreen->errorMsg = "Invalid IP Address."; this->oscConfigurationScreen->tbIpAddress->requestFocus(); } else if (!this->oscConfigurationScreen->isValidTxPort()) { #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Tx Port is not valid."); #endif this->oscConfigurationScreen->errorMsg = "Invalid Output Port (0-" + std::to_string(0xFFFF) + ")."; this->oscConfigurationScreen->tbTxPort->requestFocus(); } else if (!this->oscConfigurationScreen->isValidRxPort()) { #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Rx Port is not valid."); #endif this->oscConfigurationScreen->errorMsg = "Invalid Input Port (0-" + std::to_string(0xFFFF) + ")."; this->oscConfigurationScreen->tbRxPort->requestFocus(); } else { // Try to connect #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Save OSC Configuration clicked, save information for module."); #endif this->oscConfigurationScreen->errorMsg = ""; thisModule->oscNewSettings.oscTxIpAddress = this->oscConfigurationScreen->tbIpAddress->text.c_str(); thisModule->oscNewSettings.oscTxPort = this->oscConfigurationScreen->getTxPort(); thisModule->oscNewSettings.oscRxPort = this->oscConfigurationScreen->getRxPort(); thisModule->oscCurrentClient = this->oscConfigurationScreen->getSelectedClient(); thisModule->oscCurrentAction = TSSequencerModuleBase::OSCAction::Enable; thisModule->oscReconnectAtLoad = this->oscConfigurationScreen->ckAutoReconnect->checked; #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Set osc current action to %d.", thisModule->oscCurrentAction); #endif } } // end if enable osc else { // Disable OSC ------------------------------------------------------------------ #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Disable OSC clicked."); #endif this->oscConfigurationScreen->errorMsg = ""; thisModule->oscCurrentAction = TSSequencerModuleBase::OSCAction::Disable; } // end else disable OSC } // end if OSC Save btn pressed else { if (thisModule->oscError) { if (this->oscConfigurationScreen->errorMsg.empty()) this->oscConfigurationScreen->errorMsg = "Error connecting to " + thisModule->currentOSCSettings.oscTxIpAddress + "."; } } // Current status of OSC if (thisModule->useOSC && thisModule->oscInitialized) { // Now we have a checkbox up top where statusMsg used to be, so let's not use it for now. //this->oscConfigurationScreen->statusMsg = OSCClientAbbr[thisModule->oscCurrentClient] + " " + thisModule->currentOSCSettings.oscTxIpAddress; //this->oscConfigurationScreen->statusMsg2 = ":" + std::to_string(thisModule->currentOSCSettings.oscTxPort) // + " :" + std::to_string(thisModule->currentOSCSettings.oscRxPort); this->oscConfigurationScreen->statusMsg2 = OSCClientAbbr[thisModule->oscCurrentClient] + " " + thisModule->currentOSCSettings.oscTxIpAddress; this->oscConfigurationScreen->btnActionEnable = false; } else { this->oscConfigurationScreen->successMsg = ""; this->oscConfigurationScreen->statusMsg = "";// "OSC Not Connected"; this->oscConfigurationScreen->statusMsg2 = "OSC Not Connected"; //""; this->oscConfigurationScreen->btnActionEnable = true; } } // end if show OSC config screen ModuleWidget::step(); return; } // end step() struct seqRandomSubMenuItem : MenuItem { TSSequencerModuleBase* sequencerModule; bool useStucturedRandom; enum ShiftType { // Current Edit Pattern & Channel CurrentChannelOnly, // Current Edit Pattern, All Channels ThisPattern, // All patterns, all channels AllPatterns, // Song mode / Pattern sequence. SongMode }; ShiftType Target = ShiftType::CurrentChannelOnly; seqRandomSubMenuItem(std::string text, ShiftType target, bool useStructured, TSSequencerModuleBase* seqModule) { this->box.size.x = 200; this->text = text; this->Target = target; this->useStucturedRandom = useStructured; this->sequencerModule = seqModule; } ~seqRandomSubMenuItem() { sequencerModule = NULL; } void onAction(const event::Action &e) override { switch (this->Target) { case ShiftType::CurrentChannelOnly: sequencerModule->randomize(sequencerModule->currentPatternEditingIx, sequencerModule->currentChannelEditingIx, useStucturedRandom); break; case ShiftType::ThisPattern: sequencerModule->randomize(sequencerModule->currentPatternEditingIx, TROWA_SEQ_COPY_CHANNELIX_ALL, useStucturedRandom); break; case ShiftType::SongMode: // PATTERN SEQUENCE sequencerModule->randomizePatternSequence(useStucturedRandom); break; default: // All steps sequencerModule->randomize(TROWA_INDEX_UNDEFINED, TROWA_SEQ_COPY_CHANNELIX_ALL, useStucturedRandom); break; } } }; struct seqRandomSubMenu : Menu { TSSequencerModuleBase* sequencerModule; bool useStucturedRandom; seqRandomSubMenu(bool useStructured, TSSequencerModuleBase* seqModule) { this->box.size = Vec(200, 60); this->useStucturedRandom = useStructured; this->sequencerModule = seqModule; return; } ~seqRandomSubMenu() { sequencerModule = NULL; } void createChildren() { addChild(new seqRandomSubMenuItem("Current Edit Channel", seqRandomSubMenuItem::ShiftType::CurrentChannelOnly, this->useStucturedRandom, this->sequencerModule)); addChild(new seqRandomSubMenuItem("Current Edit Pattern", seqRandomSubMenuItem::ShiftType::ThisPattern, this->useStucturedRandom, this->sequencerModule)); addChild(new seqRandomSubMenuItem("ALL Patterns", seqRandomSubMenuItem::ShiftType::AllPatterns, this->useStucturedRandom, this->sequencerModule)); if (sequencerModule->allowPatternSequencing) addChild(new seqRandomSubMenuItem("Song Mode", seqRandomSubMenuItem::ShiftType::SongMode, this->useStucturedRandom, this->sequencerModule)); return; } }; // First tier menu item. Create Submenu struct seqRandomMenuItem : MenuItem { TSSequencerModuleBase* sequencerModule; bool useStucturedRandom; seqRandomMenuItem(std::string text, bool useStructured, TSSequencerModuleBase* seqModule) { this->box.size.x = 200; this->text = text; this->useStucturedRandom = useStructured; this->sequencerModule = seqModule; return; } ~seqRandomMenuItem() { sequencerModule = NULL; return; } Menu *createChildMenu() override { seqRandomSubMenu* menu = new seqRandomSubMenu(useStucturedRandom, sequencerModule); menu->sequencerModule = this->sequencerModule; menu->createChildren(); menu->box.size = Vec(200, 60); return menu; } }; // Initialize menu items. struct seqInitializeMenuItem : MenuItem { TSSequencerModuleBase* sequencerModule; enum InitType { // Current Edit Pattern & Channel CurrentChannelOnly, // Current Edit Pattern, All Channels ThisPattern, // All patterns, all channels AllPatterns, // Song mode / Pattern sequence. SongMode }; InitType Target = InitType::CurrentChannelOnly; seqInitializeMenuItem(std::string text, InitType target, TSSequencerModuleBase* seqModule) { this->box.size.x = 200; this->text = text; this->Target = target; this->sequencerModule = seqModule; } ~seqInitializeMenuItem() { sequencerModule = NULL; } void onAction(const event::Action &e) override { switch (this->Target) { case InitType::ThisPattern: sequencerModule->reset(sequencerModule->currentPatternEditingIx, TROWA_INDEX_UNDEFINED); break; case InitType::CurrentChannelOnly: sequencerModule->reset(sequencerModule->currentPatternEditingIx, sequencerModule->currentChannelEditingIx); break; case InitType::SongMode: // PATTERN SEQUENCE sequencerModule->resetPatternSequence(); break; default: // All steps sequencerModule->reset(TROWA_INDEX_UNDEFINED, TROWA_INDEX_UNDEFINED); break; } return; } }; //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // createContextMenu() // Create context menu with more random options for sequencers. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSequencerWidgetBase::appendContextMenu(ui::Menu *menu) { MenuLabel *spacerLabel = new MenuLabel(); menu->addChild(spacerLabel); TSSequencerModuleBase* sequencerModule = dynamic_cast<TSSequencerModuleBase*>(module); MenuLabel* modeLabel = NULL; //-------- Initialize ----// modeLabel = new MenuLabel(); modeLabel->text = "Initialize Options"; menu->addChild(modeLabel); menu->addChild(new seqInitializeMenuItem("Current Edit Channel", seqInitializeMenuItem::InitType::CurrentChannelOnly, sequencerModule)); menu->addChild(new seqInitializeMenuItem("Current Edit Pattern", seqInitializeMenuItem::InitType::ThisPattern, sequencerModule)); menu->addChild(new seqInitializeMenuItem("ALL Patterns", seqInitializeMenuItem::InitType::AllPatterns, sequencerModule)); if (sequencerModule->allowPatternSequencing) { menu->addChild(new seqInitializeMenuItem("Song Mode", seqInitializeMenuItem::InitType::SongMode, sequencerModule)); } //-------- Spacer -------- // modeLabel = new MenuLabel(); modeLabel->text = ""; menu->addChild(modeLabel); //-------- Random ------- // modeLabel = new MenuLabel(); modeLabel->text = "Random Options"; menu->addChild(modeLabel); //menu->pushChild(modeLabel); menu->addChild(new seqRandomMenuItem("> All Steps Random", false, sequencerModule)); menu->addChild(new seqRandomMenuItem("> Structured Random", true, sequencerModule)); return; } //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqLabelArea // Draw labels on our sequencer. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // draw() // @args.vg : (IN) NVGcontext to draw on // Draw labels on a trowaSoft sequencer. // (Common across trigSeq, voltSeq, multiSeq). //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqLabelArea::draw(const DrawArgs &args) { // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 1); NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); nvgFillColor(args.vg, textColor); nvgFontSize(args.vg, fontSize); /// MAKE LABELS HERE int x = 45; int y = 163; int dy = 28; // Selected Pattern Playback: nvgText(args.vg, x, y, "PAT", NULL); // Clock y += dy; nvgText(args.vg, x, y, "BPM ", NULL); // Steps y += dy; nvgText(args.vg, x, y, "LNG", NULL); // Ext Clock y += dy; nvgText(args.vg, x, y, "CLK", NULL); // Reset y += dy; nvgText(args.vg, x, y, "RST", NULL); // Outputs nvgFontSize(args.vg, fontSize * 0.95); x = 320; y = 350; nvgText(args.vg, x, y, "OUTPUTS", NULL); // TINY btn labels nvgFontSize(args.vg, fontSize * 0.6); // OSC Labels y = 103; if (module == NULL || module->allowOSC) { x = 242; //240 nvgText(args.vg, x, y, "OSC", NULL); } // Copy button labels: x = 304; // 302 nvgText(args.vg, x, y, "CPY", NULL); x = 364; // 364 nvgText(args.vg, x, y, "CPY", NULL); // BPM divisor/note label: x = 120; //118 nvgText(args.vg, x, y, "DIV", NULL); // Pattern sequence label if (allowPatternSequencing) { x = 60; nvgText(args.vg, x, y, "SEQ", NULL); } if (drawGridLines) { NVGcolor gridColor = nvgRGB(0x44, 0x44, 0x44); nvgBeginPath(args.vg); x = 80; y = 228; nvgMoveTo(args.vg, /*start x*/ x, /*start y*/ y);// Starts new sub-path with specified point as first point x += 225; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to the left nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, gridColor); nvgStroke(args.vg); // Vertical nvgBeginPath(args.vg); x = 192; y = 116; nvgMoveTo(args.vg, /*start x*/ x, /*start y*/ y);// Starts new sub-path with specified point as first point y += 225; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to the left nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, gridColor); nvgStroke(args.vg); } return; } // end draw() //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqPatternSeqConfigWidget // Pattern sequencing configuration. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqPatternSeqConfigWidget(); //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TSSeqPatternSeqConfigWidget::TSSeqPatternSeqConfigWidget(TSSequencerModuleBase* module) { this->box.size = Vec(400, 50); seqModule = module; font = APP->window->loadFont(asset::plugin(pluginInstance, TROWA_DIGITAL_FONT)); labelFont = APP->window->loadFont(asset::plugin(pluginInstance, TROWA_LABEL_FONT)); fontSize = 12; memset(messageStr, '\0', TROWA_DISP_MSG_SIZE); ckEnabled = new TS_ScreenCheckBox(Vec(50, 14), seqModule, TSSequencerModuleBase::ParamIds::PATTERN_SEQ_ON_PARAM, "Enable"); ckEnabled->momentary = false; ckEnabled->box.pos = Vec(250, 20); ckEnabled->checkBoxWidth = 10; ckEnabled->checkBoxHeight = 10; ckEnabled->fontSize = 9; ckEnabled->borderWidth = 0; ckEnabled->padding = 1; ckEnabled->color = TS_PATTERN_SEQ_STATUS_COLOR; addChild(ckEnabled); TS_KnobColored* knobPtr = dynamic_cast<TS_KnobColored*>(createParam<TS_KnobColored>(Vec(200, 15), seqModule, TSSequencerModuleBase::ParamIds::PATTERN_SEQ_LENGTH_PARAM)); knobPtr->init(TS_KnobColored::SizeType::Small, TS_KnobColored::KnobColor::MedGray); knobPtr->getParamQuantity()->randomizeEnabled = false; //knobPtr->allowRandomize = false; knobPtr->snap = true; addChild(knobPtr); //parentWidget->addParam(knobPtr); return; } //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // draw() // @args.vg : (IN) NVGcontext to draw on //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqPatternSeqConfigWidget::draw(const DrawArgs &args) { if (!visible || seqModule == NULL) return; OpaqueWidget::draw(args); // Show the current pattern value int currentPatternIndex = seqModule->currentPatternDataBeingEditedIx; //0-63 int paramId = seqModule->currentPatternDataBeingEditedParamId; int currentPatternVal = (paramId > -1) ? seqModule->params[paramId].getValue() + 1 : -1; // 1-64 int currentPatternLength = seqModule->numPatternsInSequence; NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); int y1 = 42; int y2 = 27; int dx = 0; float x = 0; int spacing = 61; ///---------------/// /// * Edit Line * /// ///---------------/// float xl_0 = 36.0f; //41.0f; float xl_1 = xl_0 + spacing * 1.5f + 10.0f; const float yline = 5.0f; NVGcolor groupColor = nvgRGB(0xDD, 0xDD, 0xDD); nvgBeginPath(args.vg); nvgMoveTo(args.vg, xl_0, yline); nvgLineTo(args.vg, xl_1, yline); nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); nvgBeginPath(args.vg); nvgFillColor(args.vg, backgroundColor); x = (xl_0 + xl_1) / 2.0f - 11; nvgRect(args.vg, x, yline - 3, 22, 6); nvgFill(args.vg); nvgFillColor(args.vg, groupColor); nvgTextAlign(args.vg, NVG_ALIGN_CENTER); nvgFontSize(args.vg, fontSize - 5); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, (xl_0 + xl_1) / 2.0f, 8, "EDIT", NULL); ///-------------/// /// * DISPLAY * /// ///-------------/// nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.5); // Current Edit Pattern Index (Sequence #/Step #) nvgFillColor(args.vg, textColor); x = 56;// 26; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "SEQ", NULL); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); if (currentPatternIndex > -1) { sprintf(messageStr, "%02d", (currentPatternIndex + 1)); nvgText(args.vg, x + dx, y2, messageStr, NULL); } else { nvgText(args.vg, x + dx, y2, "--", NULL); } // Current PATTERN Value (control being dragged) nvgFillColor(args.vg, textColor); // Maybe highlight this and the pad being edited? x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); if (currentPatternVal > -1) { sprintf(messageStr, "%02d", currentPatternVal); nvgText(args.vg, x + dx, y2, messageStr, NULL); } else { nvgText(args.vg, x + dx, y2, "--", NULL); } // Pattern Length nvgFillColor(args.vg, textColor); // Maybe highlight this and the pad being edited? x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PLEN", NULL); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); sprintf(messageStr, "%02d", currentPatternLength); nvgText(args.vg, x + dx, y2, messageStr, NULL); return; } // Pattern Sequence Config Widget draw() //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqDisplay // A top digital display for trowaSoft sequencers. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // Draw the normal default overview. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqDisplay::drawNormalView(const DrawArgs &args) { bool isPreview = module == NULL; // May get a NULL module for preview int currPlayPattern = 1; int currEditPattern = 1; int currentChannel = 1; int currentNSteps = 16; float currentBPM = 120; TSSequencerModuleBase::ControlSource currPlayPatternCtrlSrc = TSSequencerModuleBase::ControlSource::UserParameterSrc; NVGcolor currColor = TSColors::COLOR_TS_RED; if (!isPreview) { currColor = module->voiceColors[module->currentChannelEditingIx]; currPlayPattern = module->currentPatternPlayingIx + 1; currEditPattern = module->currentPatternEditingIx + 1; currentChannel = module->currentChannelEditingIx + 1; currentNSteps = module->currentNumberSteps; currentBPM = module->currentBPM; currPlayPatternCtrlSrc = module->patternPlayingControlSource; } // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.5); NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); int y1 = 42; int y2 = 27; int dx = 0; int x = 0; int spacing = 61; nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Current Playing Pattern nvgFillColor(args.vg, textColor); x = 5 + 21; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); sprintf(messageStr, "%02d", currPlayPattern); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Little indicator for what is controlling the current playing pattern // // Highest Priority Source (0) - External message (OSC or in future direct MIDI integration) // ExternalMsgSrc = 0, // // Control Voltage Input - Priority (1) // CVInputSrc = 1, // // For like Auto-Pattern-Sequencing - Priority (2) // AutoSrc = 2, // // User Parameter (UI) Control - Priority (3 = Last) // UserParameterSrc = 3 const char *indicator[] = { "EXT", "CV", "SEQ", "USR" }; int x_ind = x + spacing / 2.0f - 12; float smFontSize = fontSize - 5.5; nvgFontSize(args.vg, smFontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); int y_ind = 17; //const float bWidth = 16; //const float bHeight = 8; nvgFillColor(args.vg, textColor); nvgTextAlign(args.vg, NVG_ALIGN_LEFT); //nvgText(args.vg, x_ind, y_ind, indicator[currPlayPatternCtrlSrc], NULL); // Make more room (if you put it at the highest BPM, it will cut it off), so we'll display it vertically const char* lbl = indicator[currPlayPatternCtrlSrc]; int len = static_cast<int>(strlen(lbl)); for (int i = 0; i < len; i++) { const char* end = (i < len-1) ? &(lbl[i + 1]) : NULL; nvgText(args.vg, x_ind, y_ind + i * smFontSize, &(lbl[i]), end); } // for (int s = 0; s < 4; s++) // { // if (s == currPlayPatternCtrlSrc) // { // nvgBeginPath(args.vg); // nvgRect(args.vg, x_ind - bWidth/2.0f, y_ind - bHeight / 2.0f, bWidth, bHeight); // nvgFillColor(args.vg, textColor); // nvgFill(args.vg); // nvgFillColor(args.vg, backgroundColor); // } // else // { // nvgFillColor(args.vg, textColor); // } // nvgText(args.vg, x_ind, y_ind, indicator[s], NULL); // y_ind += 9; // } // end for // Current Playing Speed nvgTextAlign(args.vg, NVG_ALIGN_CENTER); nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); if (isPreview) sprintf(messageStr, "BPM/%s", BPMOptions[1]->label); else sprintf(messageStr, "BPM/%s", BPMOptions[module->selectedBPMNoteIx]->label); nvgText(args.vg, x, y1, messageStr, NULL); if (!isPreview && module->lastStepWasExternalClock) { sprintf(messageStr, "%s", "CLK"); } else { sprintf(messageStr, "%03.0f", currentBPM); } nvgFontFaceId(args.vg, font->handle); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Playing # Steps nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "LENG", NULL); sprintf(messageStr, "%02d", currentNSteps); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Mode: nvgFillColor(args.vg, nvgRGB(0xda, 0xda, 0xda)); x += spacing + 5; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "MODE", NULL); nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, font->handle); // Mode is now associated to the Channel, so match the channel color: nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color if (!isPreview && module->modeString != NULL) { nvgText(args.vg, x + dx, y2, module->modeString, NULL); } else { nvgText(args.vg, x + dx, y2, "TRIG", NULL); } nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Current Edit Pattern nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); sprintf(messageStr, "%02d", currEditPattern); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Gate/Trigger nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "CHNL", NULL); sprintf(messageStr, "%02d", currentChannel); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // [[[[[[[[[[[[[[[[ EDIT Box Group ]]]]]]]]]]]]]]]]]]]]]]]]]]]]] nvgTextAlign(args.vg, NVG_ALIGN_LEFT); NVGcolor groupColor = nvgRGB(0xDD, 0xDD, 0xDD); nvgFillColor(args.vg, groupColor); int labelX = 297; x = labelX; // 289 nvgFontSize(args.vg, fontSize - 5); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, 8, "EDIT", NULL); // Edit Label Line --------------------------------------------------------------- nvgBeginPath(args.vg); // Start top to the left of the text "Edit" int y = 5; nvgMoveTo(args.vg, /*start x*/ x - 3, /*start y*/ y);// Starts new sub-path with specified point as first point.s x = 256;// x - 35;//xOffset + 3 * spacing - 3 + 60; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to Left (Line Start) x = labelX + 22; y = 5; nvgMoveTo(args.vg, /*x*/ x, /*y*/ y); // Right of "Edit" x = box.size.x - 6; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // RHS of box nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); // [[[[[[[[[[[[[[[[ PLAYBACK Box Group ]]]]]]]]]]]]]]]]]]]]]]]]]]]]] groupColor = nvgRGB(0xEE, 0xEE, 0xEE); nvgFillColor(args.vg, groupColor); labelX = 64; x = labelX; nvgFontSize(args.vg, fontSize - 5); // Small font nvgText(args.vg, x, 8, "PLAYBACK", NULL); // Play Back Label Line --------------------------------------------------------------- nvgBeginPath(args.vg); // Start top to the left of the text "Play" y = 5; nvgMoveTo(args.vg, /*start x*/ x - 3, /*start y*/ y);// Starts new sub-path with specified point as first point.s x = 6; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to the left x = labelX + 52; y = 5; nvgMoveTo(args.vg, /*x*/ x, /*y*/ y); // To the Right of "Playback" x = 165; //x + 62 ; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go Right nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); return; } // end drawNormalView() //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // Draw the edit step view. // @currEditStep : Step number (1 - N). //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqDisplay::drawEditStepView(const DrawArgs &args, int currEditStep) { bool isPreview = module == NULL; // May get a NULL module for preview int currEditPattern = 1; int currentChannel = 1; float currEditStepVal = 0.0f; int currEditStepParamId = -1; NVGcolor currColor = TSColors::COLOR_TS_RED; if (!isPreview) { currColor = module->voiceColors[module->currentChannelEditingIx]; currEditPattern = module->currentPatternEditingIx + 1; currentChannel = module->currentChannelEditingIx + 1; currEditStepParamId = module->currentStepBeingEditedParamId; currEditStepVal = module->params[currEditStepParamId].getValue(); } // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.5); NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); int y1 = 42; int y2 = 27; int dx = 0; float x = 0; int spacing = 61; nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Current Edit Pattern nvgFillColor(args.vg, textColor); x = 26; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); sprintf(messageStr, "%02d", currEditPattern); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Channel nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "CHNL", NULL); sprintf(messageStr, "%02d", currentChannel); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Step nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "STEP", NULL); sprintf(messageStr, "%02d", currEditStep); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Step Value nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); if (sequencerValueModePtr != NULL) { nvgText(args.vg, x, y1, sequencerValueModePtr->displayName, NULL); } else { nvgText(args.vg, x, y1, "VAL", NULL); } nvgFontSize(args.vg, fontSize * 1.3); // Large font nvgFontFaceId(args.vg, font->handle); if (sequencerValueModePtr != NULL) { sequencerValueModePtr->GetDisplayString(currEditStepVal, messageStr); } else { sprintf(messageStr, "%4.1f", currEditStepVal); } nvgText(args.vg, x + dx, y2, messageStr, NULL); ///---------------/// /// * Edit Line * /// ///---------------/// float xl_0 = 5.0f; float mult = 3.7f; if (module != NULL) { if (module->selectedOutputValueMode == TSSequencerModuleBase::ValueMode::VALUE_VOLT) mult = 4.0f; // Longer values } float xl_1 = xl_0 + spacing * mult; const float yline = 5.0f; NVGcolor groupColor = nvgRGB(0xDD, 0xDD, 0xDD); nvgBeginPath(args.vg); nvgMoveTo(args.vg, xl_0, yline); nvgLineTo(args.vg, xl_1, yline); nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); nvgBeginPath(args.vg); nvgFillColor(args.vg, backgroundColor); x = (xl_0 + xl_1) / 2.0f - 11; nvgRect(args.vg, x, yline - 3, 22, 6); nvgFill(args.vg); nvgFillColor(args.vg, groupColor); nvgTextAlign(args.vg, NVG_ALIGN_CENTER); nvgFontSize(args.vg, fontSize - 5); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, (xl_0 + xl_1) / 2.0f, 8, "EDIT", NULL); // if (lastStepEditShownParamId != currEditStepParamId || lastStepEditShownValue != currEditStepVal) // { // DEBUG("Param Value Change. Step #%d. Id = %d, Value = %4.1f", currEditStep, currEditStepParamId, currEditStepVal); // } lastStepEditShownParamId = currEditStepParamId; lastStepEditShownValue = currEditStepVal; return; } // end drawEditStepView()
38.336283
289
0.636734
j4s0n-c
6e02834dd17eb1d9d1c81772ff522533a147c9f8
2,368
cpp
C++
201-300/269-Alien_Dictionary-h.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
201-300/269-Alien_Dictionary-h.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
201-300/269-Alien_Dictionary-h.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// There is a new alien language which uses the latin alphabet. However, the // order among letters are unknown to you. You receive a list of non-empty words // from the dictionary, where words are sorted lexicographically by the rules of // this new language. Derive the order of letters in this language. // Example 1: // Input: // [ // "wrt", // "wrf", // "er", // "ett", // "rftt" // ] // Output: "wertf" // Example 2: // Input: // [ // "z", // "x" // ] // Output: "zx" // Example 3: // Input: // [ // "z", // "x", // "z" // ] // Output: "" // Explanation: The order is invalid, so return "". // Note: // You may assume all letters are in lowercase. // You may assume that if a is a prefix of b, then a must appear before b in the // given dictionary. If the order is invalid, return an empty string. There may // be multiple valid order of letters, return any one of them is fine. class Solution { public: string alienOrder(vector<string> &words) { // after['a'] is the set of chars ordered later than 'a' unordered_map<char, unordered_set<char>> after; // precnt['a'] is the (min) prefix length of 'a' in result // 'xyza', precnt['a'] == 3 unordered_map<char, int> precnt; for (auto &&w : words) for (auto &&c : w) precnt.emplace(c, 0); for (int i = 0; i < words.size() - 1; ++i) { int j = 0, sz = words[i].size(); // safe while (j < sz && words[i][j] == words[i + 1][j]) ++j; if (j == sz) continue; if (after.count(words[i + 1][j]) && after[words[i + 1][j]].count(words[i][j])) return ""; // invalid if (after[words[i][j]].insert(words[i + 1][j]).second) ++precnt[words[i + 1][j]]; } queue<char> q; string ret; for (auto &l : precnt) if (l.second == 0) q.push(l.first); while (!q.empty()) { char c = q.front(); q.pop(); ret += c; if (after.count(c)) for (auto &cc : after[c]) if (--precnt[cc] == 0) q.push(cc); } if (ret.size() != precnt.size()) return ""; return ret; } };
24.163265
80
0.489865
ysmiles
6e07301ca31abe344945c29129c033fc427e00f3
16,175
cpp
C++
src/pke/unittest/UnitTestBatching.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/unittest/UnitTestBatching.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/unittest/UnitTestBatching.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
/* * @file * @author TPOC: palisade@njit.edu * * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE 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 "include/gtest/gtest.h" #include <iostream> #include <vector> #include "../lib/cryptocontext.h" #include "encoding/byteplaintextencoding.h" #include "encoding/intplaintextencoding.h" #include "encoding/packedintplaintextencoding.h" #include "utils/debug.h" using namespace std; using namespace lbcrypto; class UnitTestBatching : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() {} public: }; /*Simple Encrypt-Decrypt check for DCRTPoly. The assumption is this test case is that everything with respect to lattice and math * layers and cryptoparameters work. This test case is only testing if the resulting plaintext from an encrypt/decrypt returns the same * plaintext * The cyclotomic order is set 2048 *tower size is set to 3*/ TEST(UTLTVBATCHING, Poly_Encrypt_Decrypt) { float stdDev = 4; usint m = 8; BigInteger modulus("2199023288321"); BigInteger rootOfUnity; modulus = NextPrime(modulus, m); rootOfUnity = RootOfUnity(m, modulus); std::vector<usint> vectorOfInts1 = { 1,2,3,4 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); shared_ptr<Poly::Params> ep( new Poly::Params(m, modulus, rootOfUnity) ); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(ep, 17, 8, stdDev); cc->Enable(ENCRYPTION); //Regular LWE-NTRU encryption algorithm //////////////////////////////////////////////////////////// //Perform the key generation operation. /////////////////////////////////////////////////////////// LPKeyPair<Poly> kp = cc->KeyGen(); //////////////////////////////////////////////////////////// //Encryption //////////////////////////////////////////////////////////// vector<shared_ptr<Ciphertext<Poly>>> ciphertext; ciphertext = cc->Encrypt(kp.publicKey, intArray1, false); //////////////////////////////////////////////////////////// //Decryption //////////////////////////////////////////////////////////// PackedIntPlaintextEncoding intArrayNew; DecryptResult result = cc->Decrypt(kp.secretKey, ciphertext, &intArrayNew, false); if (!result.isValid) { std::cout << "Decryption failed!" << std::endl; exit(1); } EXPECT_EQ(intArrayNew, vectorOfInts1); } TEST(UTLTVBATCHING, Poly_EVALADD) { float stdDev = 4; usint m = 8; BigInteger modulus("2199023288321"); BigInteger rootOfUnity; modulus = NextPrime(modulus, m); rootOfUnity = RootOfUnity(m, modulus); std::vector<usint> vectorOfInts1 = { 1,2,3,4 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsExpected = { 5,5,5,5 }; shared_ptr<Poly::Params> ep( new Poly::Params(m, modulus, rootOfUnity) ); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(ep, 17, 8, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); //Regular LWE-NTRU encryption algorithm //////////////////////////////////////////////////////////// //Perform the key generation operation. /////////////////////////////////////////////////////////// LPKeyPair<Poly> kp = cc->KeyGen(); //////////////////////////////////////////////////////////// //Encryption //////////////////////////////////////////////////////////// vector<shared_ptr<Ciphertext<Poly>>> ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); vector<shared_ptr<Ciphertext<Poly>>> ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); //////////////////////////////////////////////////////////// //EvalAdd Operation //////////////////////////////////////////////////////////// vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; ciphertextResult.insert(ciphertextResult.begin(), cc->EvalAdd(ciphertext1.at(0), ciphertext2.at(0)) ); //////////////////////////////////////////////////////////// //Decryption //////////////////////////////////////////////////////////// PackedIntPlaintextEncoding intArrayNew; DecryptResult result = cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); if (!result.isValid) { std::cout << "Decryption failed!" << std::endl; exit(1); } EXPECT_EQ(intArrayNew, vectorOfIntsExpected); } TEST(UTLTVBATCHING, Poly_EVALMULT) { usint ptMod = 17; usint m = 8; usint relin = 1; float stdDev = 4; BigInteger q("2199023288321"); q = NextPrime(q, m); BigInteger rootOfUnity(RootOfUnity(m, q)); shared_ptr<Poly::Params> parms( new Poly::Params(m, q, rootOfUnity) ); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextLTV(parms, ptMod, relin, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); cc->Enable(LEVELEDSHE); //Initialize the public key containers. LPKeyPair<Poly> kp; std::vector<usint> vectorOfInts1 = { 1,2,3,4 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsExpected = { 4,6,6,4 }; kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); vector<shared_ptr<Ciphertext<Poly>>> ciphertextResults; cc->EvalMultKeyGen(kp.secretKey); ciphertextResults.insert(ciphertextResults.begin(), cc->EvalMult(ciphertext1.at(0), ciphertext2.at(0))); PackedIntPlaintextEncoding results; cc->Decrypt(kp.secretKey, ciphertextResults, &results, false); EXPECT_EQ(results, vectorOfIntsExpected); } /*Simple Encrypt-Decrypt check for Poly. The assumption is this test case is that everything with respect to lattice and math * layers and cryptoparameters work. This test case is only testing if the resulting plaintext from an encrypt/decrypt returns the same * plaintext * The cyclotomic order is set to 22 *tower size is set to 3*/ TEST(UTLTVBATCHING, Poly_Encrypt_Decrypt_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("800053"); BigInteger modulusP(p); BigInteger rootOfUnity("59094"); BigInteger bigmodulus("1019642968797569"); BigInteger bigroot("116200103432701"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(params, p, 8, stdDev); cc->Enable(ENCRYPTION); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext; std::vector<usint> vectorOfInts = { 1,1,1,5,1,4,1,6,1,7 }; PackedIntPlaintextEncoding intArray(vectorOfInts); ciphertext = cc->Encrypt(kp.publicKey, intArray, false); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertext, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfInts); } TEST(UTLTVBATCHING, Poly_EVALADD_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("800053"); BigInteger modulusP(p); BigInteger rootOfUnity("59094"); BigInteger bigmodulus("1019642968797569"); BigInteger bigroot("116200103432701"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(params, p, 8, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; std::vector<usint> vectorOfInts1 = { 1,2,3,4,5,6,7,8,9,10 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 10,9,8,7,6,5,4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsAdd; std::transform(vectorOfInts1.begin(), vectorOfInts1.end(), vectorOfInts2.begin(), std::back_inserter(vectorOfIntsAdd), std::plus<usint>()); ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); auto ciphertextAdd = cc->EvalAdd(ciphertext1.at(0), ciphertext2.at(0)); ciphertextResult.insert(ciphertextResult.begin(), ciphertextAdd); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfIntsAdd); } TEST(UTBVBATCHING, Poly_EVALMULT_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("72385066601"); BigInteger modulusP(p); BigInteger rootOfUnity("69414828251"); BigInteger bigmodulus("77302754575416994210914689"); BigInteger bigroot("76686504597021638023705542"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(params, p, 1, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; std::vector<usint> vectorOfInts1 = { 1,2,3,4,5,6,7,8,9,10 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 10,9,8,7,6,5,4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsMult; std::transform(vectorOfInts1.begin(), vectorOfInts1.end(), vectorOfInts2.begin(), std::back_inserter(vectorOfIntsMult), std::multiplies<usint>()); ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); cc->EvalMultKeyGen(kp.secretKey); auto ciphertextMult = cc->EvalMult(ciphertext1.at(0), ciphertext2.at(0)); ciphertextResult.insert(ciphertextResult.begin(), ciphertextMult); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfIntsMult); } TEST(UTFVBATCHING, Poly_EVALMULT_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("72385066601"); BigInteger modulusP(p); BigInteger rootOfUnity("69414828251"); BigInteger bigmodulus("77302754575416994210914689"); BigInteger bigroot("76686504597021638023705542"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); BigInteger bigEvalMultModulus("37778931862957161710549"); BigInteger bigEvalMultRootOfUnity("7161758688665914206613"); BigInteger bigEvalMultModulusAlt("1461501637330902918203684832716283019655932547329"); BigInteger bigEvalMultRootOfUnityAlt("570268124029534407621996591794583635795426001824"); auto cycloPolyBig = GetCyclotomicPolynomial<BigVector, BigInteger>(m, bigEvalMultModulus); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPolyBig, bigEvalMultModulus); PackedIntPlaintextEncoding::SetParams(modulusP, m); usint batchSize = 8; shared_ptr<EncodingParams> encodingParams(new EncodingParams(modulusP, PackedIntPlaintextEncoding::GetAutomorphismGenerator(modulusP), batchSize)); BigInteger delta(modulusQ.DividedBy(modulusP)); //genCryptoContextFV(shared_ptr<typename Element::Params> params, // shared_ptr<typename EncodingParams> encodingParams, // usint relinWindow, float stDev, const std::string& delta, // MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", // int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, // const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0") shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextFV(params, encodingParams, 1, stdDev,delta.ToString(),OPTIMIZED, bigEvalMultModulus.ToString(), bigEvalMultRootOfUnity.ToString(),1,9,1.006, bigEvalMultModulusAlt.ToString(), bigEvalMultRootOfUnityAlt.ToString()); cc->Enable(ENCRYPTION); cc->Enable(SHE); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; std::vector<usint> vectorOfInts1 = { 1,2,3,4,5,6,7,8,9,10 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 10,9,8,7,6,5,4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsMult; std::transform(vectorOfInts1.begin(), vectorOfInts1.end(), vectorOfInts2.begin(), std::back_inserter(vectorOfIntsMult), std::multiplies<usint>()); ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); cc->EvalMultKeyGen(kp.secretKey); auto ciphertextMult = cc->EvalMult(ciphertext1.at(0), ciphertext2.at(0)); ciphertextResult.insert(ciphertextResult.begin(), ciphertextMult); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfIntsMult); }
35.163043
150
0.726306
marcelmon
6e107a9a24375a769e5d1f5923eb40da5f510006
9,611
cpp
C++
plugins/string-machine/StringMachinePlugin.cpp
jjYBdx4IL/string-machine
0bb2ac9092d31402c8ecfd5f681a3a4f2d575024
[ "BSL-1.0" ]
34
2019-07-08T15:02:10.000Z
2022-02-20T01:44:02.000Z
plugins/string-machine/StringMachinePlugin.cpp
jjYBdx4IL/string-machine
0bb2ac9092d31402c8ecfd5f681a3a4f2d575024
[ "BSL-1.0" ]
27
2019-07-08T21:46:19.000Z
2022-03-24T16:01:02.000Z
plugins/string-machine/StringMachinePlugin.cpp
jjYBdx4IL/string-machine
0bb2ac9092d31402c8ecfd5f681a3a4f2d575024
[ "BSL-1.0" ]
3
2019-08-03T22:35:08.000Z
2022-02-20T01:19:52.000Z
#include "StringMachinePlugin.hpp" #include "StringMachinePresets.hpp" #include "StringSynthDefs.h" #include "DenormalDisabler.h" StringMachinePlugin::StringMachinePlugin() : Plugin(Parameter_Count, NumPresets, State_Count) { double sampleRate = getSampleRate(); fSynth.init(sampleRate); for (unsigned p = 0; p < Parameter_Count; ++p) { Parameter param; InitParameter(p, param); setParameterValue(p, param.ranges.def); fParameterDefaults[p] = param.ranges.def; } } StringMachinePlugin::~StringMachinePlugin() { } const char *StringMachinePlugin::getLabel() const { return DISTRHO_PLUGIN_LABEL; } const char *StringMachinePlugin::getMaker() const { return DISTRHO_PLUGIN_MAKER; } const char *StringMachinePlugin::getLicense() const { return DISTRHO_PLUGIN_LICENSE; } const char *StringMachinePlugin::getDescription() const { return DISTRHO_PLUGIN_DESCRIPTION; } const char *StringMachinePlugin::getHomePage() const { return DISTRHO_PLUGIN_HOMEPAGE; } uint32_t StringMachinePlugin::getVersion() const { return d_version(DISTRHO_PLUGIN_VERSION); } int64_t StringMachinePlugin::getUniqueId() const { return d_cconst(DISTRHO_PLUGIN_UNIQUE_ID); } void StringMachinePlugin::initParameter(uint32_t index, Parameter &parameter) { InitParameter(index, parameter); } float StringMachinePlugin::getParameterValue(uint32_t index) const { const StringSynth &synth = fSynth; switch (index) { case pIdOscDetune: return synth.getDetune(); case pIdOscHpCutoffUpper: return synth.getOscSettings().highpassUpperCutoff; case pIdOscHpCutoffLower: return synth.getOscSettings().highpassLowerCutoff; case pIdOscPwmDepth: return synth.getOscSettings().pwmDepth; case pIdOscPwmFrequency: return synth.getOscSettings().pwmFrequency; case pIdOscEnhanceUpper: return synth.getOscSettings().enhanceUpper; case pIdOscEnhanceLower: return synth.getOscSettings().enhanceLower; case pIdFltLpCutoffUpper: return synth.getFltSettings().lowpassUpperCutoff; case pIdFltHpCutoffUpper: return synth.getFltSettings().highpassUpperCutoff; case pIdFltLpCutoffLower: return synth.getFltSettings().lowpassLowerCutoff; case pIdFltHpCutoffLower: return synth.getFltSettings().highpassLowerCutoff; case pIdFltHsCutoffEq: return synth.getFltSettings().highshelfEqCutoff; case pIdFltHsBoostEq: return synth.getFltSettings().highshelfEqBoost; case pIdMixGainUpper: return synth.getMixGainUpper(); case pIdMixGainLower: return synth.getMixGainLower(); case pIdEnvAttack: return synth.getEnvSettings().attack; case pIdEnvHold: return synth.getEnvSettings().hold; case pIdEnvDecay: return synth.getEnvSettings().decay; case pIdEnvSustain: return synth.getEnvSettings().sustain; case pIdEnvRelease: return synth.getEnvSettings().release; case pIdChoEnabled: return synth.getChorus().getEnabled(); case pIdChoDepth: return synth.getChorus().getLfo().get_globaldepth(); case pIdChoRate1: return synth.getChorus().getLfo().get_rate1(); case pIdChoDepth1: return synth.getChorus().getLfo().get_depth1(); case pIdChoRate2: return synth.getChorus().getLfo().get_rate2(); case pIdChoDepth2: return synth.getChorus().getLfo().get_depth2(); case pIdChoModel: return synth.getChorus().getAnalogMode(); case pIdMasterGain: return synth.getMasterGain(); case pIdPolyphony: return synth.getPolyphony(); case pIdOutDetuneUpper: return fSynth.getLastDetuneUpper(); case pIdOutDetuneLower: return fSynth.getLastDetuneLower(); case pIdOutChorusPhase1: return (2 * M_PI) * fSynth.getChorus().getPhase1(); case pIdOutChorusPhase2: return (2 * M_PI) * fSynth.getChorus().getPhase2(); case pIdOutMasterLevel1: case pIdOutMasterLevel2: { double level = fOutputLevelFollower[index - pIdOutMasterLevel1].last_output(); return 20 * std::log10(std::max(level, 1e-5)); } default: DISTRHO_SAFE_ASSERT(false); return 0.0; } } void StringMachinePlugin::setParameterValue(uint32_t index, float value) { StringSynth &synth = fSynth; switch (index) { case pIdOscDetune: synth.setDetune(value); break; case pIdOscHpCutoffUpper: synth.getOscSettings().highpassUpperCutoff = value; break; case pIdOscHpCutoffLower: synth.getOscSettings().highpassLowerCutoff = value; break; case pIdOscPwmDepth: synth.getOscSettings().pwmDepth = value; break; case pIdOscPwmFrequency: synth.getOscSettings().pwmFrequency = value; break; case pIdOscEnhanceUpper: synth.getOscSettings().enhanceUpper = value; break; case pIdOscEnhanceLower: synth.getOscSettings().enhanceLower = value; break; case pIdFltLpCutoffUpper: synth.getFltSettings().lowpassUpperCutoff = value; break; case pIdFltHpCutoffUpper: synth.getFltSettings().highpassUpperCutoff = value; break; case pIdFltLpCutoffLower: synth.getFltSettings().lowpassLowerCutoff = value; break; case pIdFltHpCutoffLower: synth.getFltSettings().highpassLowerCutoff = value; break; case pIdFltHsCutoffEq: synth.getFltSettings().highshelfEqCutoff = value; break; case pIdFltHsBoostEq: synth.getFltSettings().highshelfEqBoost = value; break; case pIdMixGainUpper: synth.setMixGainUpper(value); break; case pIdMixGainLower: synth.setMixGainLower(value); break; case pIdEnvAttack: synth.getEnvSettings().attack = value; break; case pIdEnvHold: synth.getEnvSettings().hold = value; break; case pIdEnvDecay: synth.getEnvSettings().decay = value; break; case pIdEnvSustain: synth.getEnvSettings().sustain = value; break; case pIdEnvRelease: synth.getEnvSettings().release = value; break; case pIdChoEnabled: synth.getChorus().setEnabled(value > 0.5f); break; case pIdChoDepth: synth.getChorus().getLfo().set_globaldepth(value); break; case pIdChoRate1: synth.getChorus().getLfo().set_rate1(value); break; case pIdChoDepth1: synth.getChorus().getLfo().set_depth1(value); break; case pIdChoRate2: synth.getChorus().getLfo().set_rate2(value); break; case pIdChoDepth2: synth.getChorus().getLfo().set_depth2(value); break; case pIdChoModel: synth.getChorus().setAnalogMode((int)value); break; case pIdMasterGain: synth.setMasterGain(value); break; case pIdPolyphony: synth.setPolyphony((int)std::lrint(value)); break; case pIdOutDetuneUpper: case pIdOutDetuneLower: case pIdOutChorusPhase1: case pIdOutChorusPhase2: case pIdOutMasterLevel1: case pIdOutMasterLevel2: break; default: DISTRHO_SAFE_ASSERT(false); break; } } void StringMachinePlugin::initProgramName(uint32_t index, String &programName) { DISTRHO_SAFE_ASSERT_RETURN(index < NumPresets, ); programName = Presets[index].name; } void StringMachinePlugin::loadProgram(uint32_t index) { DISTRHO_SAFE_ASSERT_RETURN(index < NumPresets, ); std::array<float, Parameter_Count> values = fParameterDefaults; for (const Preset::Parameter *pp = Presets[index].parameters; pp->id != -1; ++pp) values[pp->id] = pp->value; for (unsigned p = 0; p < Parameter_Count; ++p) setParameterValue(p, values[p]); } void StringMachinePlugin::activate() { double sampleRate = getSampleRate(); fSynth.init(sampleRate); for (unsigned c = 0; c < 2; ++c) fOutputLevelFollower[c].release(0.5 * sampleRate); } void StringMachinePlugin::deactivate() { } void StringMachinePlugin::run(const float **, float **outputs, uint32_t totalFrames, const MidiEvent *midiEvents, uint32_t midiEventCount) { WebCore::DenormalDisabler denormalsDisabled; StringSynth &synth = fSynth; constexpr unsigned bufferLimit = StringSynthDefs::BufferLimit; float *outL = outputs[0]; float *outR = outputs[1]; uint32_t frameIndex = 0; const MidiEvent *midiCurrent = midiEvents; while (totalFrames - frameIndex > 0) { uint32_t frames = totalFrames - frameIndex; frames = (frames < bufferLimit) ? frames : bufferLimit; while (midiCurrent != midiEvents + midiEventCount && (midiCurrent->frame < frameIndex + frames || frameIndex + frames == totalFrames)) { if (midiCurrent->size <= 4) synth.handleMessage(midiCurrent->data); ++midiCurrent; } float *outputsAtIndex[2] = { outL + frameIndex, outR + frameIndex }; synth.generate(outputsAtIndex, frames); frameIndex += frames; } for (unsigned c = 0; c < 2; ++c) { AmpFollower &follower = fOutputLevelFollower[c]; const float *output = outputs[c]; for (uint32_t i = 0; i < totalFrames; ++i) follower.process(output[i]); } } /// namespace DISTRHO { Plugin *createPlugin() { return new StringMachinePlugin; } } // namespace DISTRHO
27.617816
144
0.670482
jjYBdx4IL
6e12edfa8a7f3ff1449a60c8383aaea72796e357
1,589
cpp
C++
C++/sum-of-distances-in-tree.cpp
black-shadows/LeetCode-Solutions
b1692583f7b710943ffb19b392b8bf64845b5d7a
[ "Fair", "Unlicense" ]
1
2020-04-16T08:38:14.000Z
2020-04-16T08:38:14.000Z
sum-of-distances-in-tree.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
null
null
null
sum-of-distances-in-tree.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
1
2021-12-25T14:48:56.000Z
2021-12-25T14:48:56.000Z
// Time: O(n) // Space: O(n) class Solution { public: vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) { unordered_map<int, vector<int>> graph; for (const auto& edge : edges) { graph[edge[0]].emplace_back(edge[1]); graph[edge[1]].emplace_back(edge[0]); } vector<int> count(N, 1); vector<int> result(N, 0); dfs(graph, 0, -1, &count, &result); dfs2(graph, 0, -1, &count, &result); return result; } private: void dfs(const unordered_map<int, vector<int>>& graph, int node, int parent, vector<int> *count, vector<int> *result) { if (!graph.count(node)) { return; } for (const auto& nei : graph.at(node)) { if (nei != parent) { dfs(graph, nei, node, count, result); (*count)[node] += (*count)[nei]; (*result)[node] += (*result)[nei] + (*count)[nei]; } } } void dfs2(const unordered_map<int, vector<int>>& graph, int node, int parent, vector<int> *count, vector<int> *result) { if (!graph.count(node)) { return; } for (const auto& nei : graph.at(node)) { if (nei != parent) { (*result)[nei] = (*result)[node] - (*count)[nei] + count->size() - (*count)[nei]; dfs2(graph, nei, node, count, result); } } } };
30.557692
74
0.452486
black-shadows
6e163214b313f7debfbd7fb5f10c545127da76c3
312
hpp
C++
tests/typedefs.hpp
5cript/interval-tree
27ffeb8e6e8268cb94bd6d5c4f085cf5b595789f
[ "CC0-1.0" ]
36
2018-08-06T13:59:13.000Z
2022-03-25T19:58:58.000Z
tests/typedefs.hpp
5cript/interval-tree
27ffeb8e6e8268cb94bd6d5c4f085cf5b595789f
[ "CC0-1.0" ]
13
2017-04-03T12:17:27.000Z
2022-02-27T12:17:33.000Z
tests/typedefs.hpp
5cript/interval-tree
27ffeb8e6e8268cb94bd6d5c4f085cf5b595789f
[ "CC0-1.0" ]
5
2019-04-01T15:53:59.000Z
2021-09-15T16:38:32.000Z
#pragma once template <typename ContainedT> struct IntervalTypes { using value_type = ContainedT; using interval_type = lib_interval_tree::interval <ContainedT>; using tree_type = lib_interval_tree::interval_tree <interval_type>; using iterator_type = typename tree_type::iterator; };
28.363636
72
0.746795
5cript
6e1d2f46e2b460b613251bacb68a2e30a11cbe1e
3,526
cpp
C++
hphp/runtime/ext/hsl/ext_hsl_io.cpp
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
9,491
2015-01-01T00:30:28.000Z
2022-03-31T20:22:11.000Z
hphp/runtime/ext/hsl/ext_hsl_io.cpp
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
4,796
2015-01-01T00:26:31.000Z
2022-03-31T01:09:05.000Z
hphp/runtime/ext/hsl/ext_hsl_io.cpp
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
2,126
2015-01-01T11:13:29.000Z
2022-03-28T19:58:15.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/plain-file.h" #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/server/cli-server.h" #include "hphp/system/systemlib.h" namespace HPHP { namespace { bool is_any_cli_mode() { return is_cli_server_mode() || !RuntimeOption::ServerExecutionMode(); } Array HHVM_FUNCTION(HH_io_pipe) { int fds[2]; if (::pipe(fds) != 0) { raise_error("Failed to pipe(2)"); } return make_vec_array( req::make<PlainFile>(fds[0]), req::make<PlainFile>(fds[1]) ); } int64_t HHVM_FUNCTION(HH_io_response_write, const String& data) { if (is_any_cli_mode()) { auto stream = dyn_cast_or_null<File>(BuiltinFiles::getSTDOUT()); if (!stream) { return 0; } // Per `File`'s comments: // - write() for PHP stream behavior // - writeImpl() for C-like behavior return stream->writeImpl(data.c_str(), data.length()); } // Written length is not returned, assume it wrote all, like OutputFile g_context->write(data); return data.length(); } void HHVM_FUNCTION(HH_io_response_flush) { g_context->flush(); } RDS_LOCAL(ssize_t, request_read_offset); String HHVM_FUNCTION(HH_io_request_read, int64_t max) { if (is_any_cli_mode()) { auto stream = dyn_cast_or_null<File>(BuiltinFiles::getSTDIN()); if (!stream) { return StrNR(staticEmptyString()); } return stream->read(max); } const auto offset = *request_read_offset.get(); const auto raw_post = g_context->getRawPostData(); const auto remaining = raw_post.size() - offset; const auto to_read = max > remaining ? remaining : max; const auto result = raw_post.substr(offset, to_read); *request_read_offset.get() += to_read; return result; } struct IOExtension final : Extension { IOExtension() : Extension("hsl_io", "1.0") {} void moduleInit() override { HHVM_FALIAS( HH\\Lib\\_Private\\Native\\pipe, HH_io_pipe ); HHVM_FALIAS( HH\\Lib\\_Private\\_IO\\response_write, HH_io_response_write ); HHVM_FALIAS( HH\\Lib\\_Private\\_IO\\response_flush, HH_io_response_flush ); HHVM_FALIAS( HH\\Lib\\_Private\\_IO\\request_read, HH_io_request_read ); loadSystemlib(); } void requestInit() { *request_read_offset.get() = 0; } } s_io_extension; } // anonymous namespace } // namespace HPHP
31.765766
75
0.562961
donsbot
6e212aca7d62e722ea4d381b0d060a764c6b8a33
1,712
cpp
C++
src/RcppExports.cpp
cran/edina
90e721689f750eefc1f8294fa8763daefba60983
[ "OLDAP-2.4" ]
null
null
null
src/RcppExports.cpp
cran/edina
90e721689f750eefc1f8294fa8763daefba60983
[ "OLDAP-2.4" ]
null
null
null
src/RcppExports.cpp
cran/edina
90e721689f750eefc1f8294fa8763daefba60983
[ "OLDAP-2.4" ]
null
null
null
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include "../inst/include/edina.h" #include <RcppArmadillo.h> #include <Rcpp.h> using namespace Rcpp; // edina_Gibbs_Q Rcpp::List edina_Gibbs_Q(const arma::mat& Y, unsigned int K, unsigned int burnin, unsigned int chain_length); RcppExport SEXP _edina_edina_Gibbs_Q(SEXP YSEXP, SEXP KSEXP, SEXP burninSEXP, SEXP chain_lengthSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP); Rcpp::traits::input_parameter< unsigned int >::type K(KSEXP); Rcpp::traits::input_parameter< unsigned int >::type burnin(burninSEXP); Rcpp::traits::input_parameter< unsigned int >::type chain_length(chain_lengthSEXP); rcpp_result_gen = Rcpp::wrap(edina_Gibbs_Q(Y, K, burnin, chain_length)); return rcpp_result_gen; END_RCPP } // check_identifiability bool check_identifiability(const arma::mat& Q); RcppExport SEXP _edina_check_identifiability(SEXP QSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const arma::mat& >::type Q(QSEXP); rcpp_result_gen = Rcpp::wrap(check_identifiability(Q)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_edina_edina_Gibbs_Q", (DL_FUNC) &_edina_edina_Gibbs_Q, 4}, {"_edina_check_identifiability", (DL_FUNC) &_edina_check_identifiability, 1}, {NULL, NULL, 0} }; RcppExport void R_init_edina(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
37.217391
109
0.751168
cran
6e223d7642570e8cda894ef8230f867b0e0f5941
2,783
cc
C++
src/tck-simulate/graph.cc
schlepil/tchecker
3ab68fe150d16e3db77db8380c47e02026c7815f
[ "MIT" ]
null
null
null
src/tck-simulate/graph.cc
schlepil/tchecker
3ab68fe150d16e3db77db8380c47e02026c7815f
[ "MIT" ]
null
null
null
src/tck-simulate/graph.cc
schlepil/tchecker
3ab68fe150d16e3db77db8380c47e02026c7815f
[ "MIT" ]
null
null
null
/* * This file is a part of the TChecker project. * * See files AUTHORS and LICENSE for copyright details. * */ #include "graph.hh" namespace tchecker { namespace tck_simulate { /* node_t */ node_t::node_t(tchecker::zg::state_sptr_t const & s) : _state(s) {} node_t::node_t(tchecker::zg::const_state_sptr_t const & s) : _state(s) {} /* edge_t */ edge_t::edge_t(tchecker::zg::transition_t const & t) : _vedge(t.vedge_ptr()) {} /* graph_t */ graph_t::graph_t(std::shared_ptr<tchecker::zg::zg_t> const & zg, std::size_t block_size) : tchecker::graph::reachability::multigraph_t<tchecker::tck_simulate::node_t, tchecker::tck_simulate::edge_t>::multigraph_t( block_size), _zg(zg) { } graph_t::~graph_t() { tchecker::graph::reachability::multigraph_t<tchecker::tck_simulate::node_t, tchecker::tck_simulate::edge_t>::clear(); } void graph_t::attributes(tchecker::tck_simulate::node_t const & n, std::map<std::string, std::string> & m) const { _zg->attributes(n.state_ptr(), m); } void graph_t::attributes(tchecker::tck_simulate::edge_t const & e, std::map<std::string, std::string> & m) const { m["vedge"] = tchecker::to_string(e.vedge(), _zg->system().as_system_system()); } /* DOT output */ /*! \class node_lexical_less_t \brief Less-than order on nodes based on lexical ordering */ class node_lexical_less_t { public: /*! \brief Less-than order on nodes based on lexical ordering \param n1 : a node \param n2 : a node \return true if n1 is less-than n2 w.r.t. lexical ordering over the states in the nodes */ bool operator()(tchecker::tck_simulate::graph_t::node_sptr_t const & n1, tchecker::tck_simulate::graph_t::node_sptr_t const & n2) const { return tchecker::zg::lexical_cmp(n1->state(), n2->state()) < 0; } }; /*! \class edge_lexical_less_t \brief Less-than ordering on edges based on lexical ordering */ class edge_lexical_less_t { public: /*! \brief Less-than ordering on edges based on lexical ordering \param e1 : an edge \param e2 : an edge \return true if e1 is less-than e2 w.r.t. the tuple of edges in e1 and e2 */ bool operator()(tchecker::tck_simulate::graph_t::edge_sptr_t const & e1, tchecker::tck_simulate::graph_t::edge_sptr_t const & e2) const { return tchecker::lexical_cmp(e1->vedge(), e2->vedge()) < 0; } }; std::ostream & dot_output(std::ostream & os, tchecker::tck_simulate::graph_t const & g, std::string const & name) { return tchecker::graph::reachability::dot_output<tchecker::tck_simulate::graph_t, tchecker::tck_simulate::node_lexical_less_t, tchecker::tck_simulate::edge_lexical_less_t>(os, g, name); } } // namespace tck_simulate } // namespace tchecker
28.690722
128
0.679842
schlepil
6e2243f6b58f9a4c6317829b37bef02bec7f500b
6,411
cpp
C++
ViAn/GUI/viewpathdialog.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
1
2019-12-08T03:53:03.000Z
2019-12-08T03:53:03.000Z
ViAn/GUI/viewpathdialog.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
182
2018-02-08T11:03:26.000Z
2019-06-27T15:27:47.000Z
ViAn/GUI/viewpathdialog.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
null
null
null
#include "viewpathdialog.h" #include "Project/video.h" #include "viewpathitem.h" #include <QDebug> #include <QDesktopServices> #include <QDialogButtonBox> #include <QFile> #include <QFileDialog> #include <QFormLayout> #include <QHeaderView> #include <QLineEdit> #include <QPushButton> #include <QTreeWidget> #include <QUrl> ViewPathDialog::ViewPathDialog(std::vector<Video*> video_list, QWidget* parent) : QDialog(parent) { setWindowTitle("Vian - View paths"); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WA_DeleteOnClose); setMinimumSize(500,200); m_video_list = video_list; QVBoxLayout* v_layout = new QVBoxLayout(this); QHBoxLayout* h_layout = new QHBoxLayout(); path_list = new QTreeWidget(this); path_list->setSelectionMode(QAbstractItemView::ExtendedSelection); path_list->setColumnCount(NUM_COLUMNS); path_list->header()->resizeSection(0,40); path_list->headerItem()->setText(0, "Status"); path_list->headerItem()->setText(1, "Video name"); path_list->headerItem()->setText(2, "Path"); add_paths(path_list); QVBoxLayout* btn_layout = new QVBoxLayout(); btn_layout->setAlignment(Qt::AlignTop); QPushButton* open_folder_btn = new QPushButton(tr("Open folder")); QPushButton* update_path_btn = new QPushButton(tr("Update path")); QPushButton* update_folder_btn = new QPushButton(tr("Update folder")); connect(open_folder_btn, &QPushButton::clicked, this, &ViewPathDialog::open_folder_btn_clicked); connect(update_path_btn, &QPushButton::clicked, this, &ViewPathDialog::update_path_btn_clicked); connect(update_folder_btn, &QPushButton::clicked, this, &ViewPathDialog::update_folder_btn_clicked); btn_layout->addWidget(open_folder_btn); btn_layout->addWidget(update_path_btn); btn_layout->addWidget(update_folder_btn); h_layout->addWidget(path_list); h_layout->addLayout(btn_layout); // Add Buttons btn_box = new QDialogButtonBox; btn_box->addButton(QDialogButtonBox::Ok); btn_box->addButton(QDialogButtonBox::Cancel); connect(btn_box->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &ViewPathDialog::ok_btn_clicked); connect(btn_box->button(QDialogButtonBox::Cancel), &QPushButton::clicked, this, &ViewPathDialog::cancel_btn_clicked); v_layout->addLayout(h_layout); v_layout->addWidget(btn_box); setLayout(v_layout); } /** * @brief ViewPathDialog::add_paths * Add all videos in the video list to the treewidget * This will set the : * first column with a icon indicating if video can be read * second column with the video name * third column with the video path * @param tree */ void ViewPathDialog::add_paths(QTreeWidget* tree) { for (Video* video : m_video_list) { ViewPathItem* item = new ViewPathItem(video, tree); set_icon(item); } } /** * @brief ViewPathDialog::set_icon * Checks the item's path to see if there is a video file there * Then updates the item's icon to indicate success or failure. * @param item */ void ViewPathDialog::set_icon(ViewPathItem* item) { QFile load_file(item->get_path()); if (load_file.open(QIODevice::ReadOnly)) { // Attempt to open file item->setIcon(0, check_icon); item->set_valid(true); } else { item->setIcon(0, cross_icon); item->set_valid(false); } } /** * @brief ViewPathDialog::all_valid * Returns if all the videopaths are valid * That means the video file in the path can be read. * @return */ bool ViewPathDialog::all_valid() { for (auto i = 0; i < path_list->topLevelItemCount(); ++i) { ViewPathItem* vp_item = dynamic_cast<ViewPathItem*>(path_list->topLevelItem(i)); if (!vp_item->is_valid()) return false; } return true; } /** * @brief ViewPathDialog::open_folder_btn_clicked * Slot function for open_folder button * Open the folder where the selected items is. */ void ViewPathDialog::open_folder_btn_clicked() { if (path_list->selectedItems().length() != 1) return; auto v_item = dynamic_cast<ViewPathItem*>(path_list->currentItem()); QDesktopServices::openUrl(QUrl("file:///"+v_item->get_dir(), QUrl::TolerantMode)); } /** * @brief ViewPathDialog::update_path_btn_clicked * Slot function for update_path button * Open a dialog where the user can select a new path * where the video is. */ void ViewPathDialog::update_path_btn_clicked() { if (path_list->selectedItems().length() != 1) return; auto v_item = dynamic_cast<ViewPathItem*>(path_list->currentItem()); QDir standard; standard.mkpath(v_item->get_dir()); QString file_path = QFileDialog::getOpenFileName(this, tr("Choose project path"), v_item->get_dir()); // Update the path for the selected item. if(!file_path.isEmpty()) { v_item->set_path(file_path); set_icon(v_item); } } /** * @brief ViewPathDialog::update_folder_btn_clicked * Slot function for update_folder button * Open a dialog where the user can select a new folder * where the videos are. */ void ViewPathDialog::update_folder_btn_clicked() { // Can be done on multiple items if (path_list->selectedItems().length() < 1) return; auto v_item = dynamic_cast<ViewPathItem*>(path_list->currentItem()); QDir standard; standard.mkpath(v_item->get_dir()); QString new_dir = QFileDialog::getExistingDirectory(this, tr("Choose new directory"), v_item->get_dir()); // Update the directory for all selected items for (auto item : path_list->selectedItems()) { auto v_item = dynamic_cast<ViewPathItem*>(item); if(!new_dir.isEmpty()) { v_item->set_dir(new_dir); set_icon(v_item); } } } /** * @brief ViewPathDialog::ok_btn_clicked * Slot function for ok button */ void ViewPathDialog::ok_btn_clicked() { for (auto item : path_list->findItems("", Qt::MatchContains, 1)) { auto v_item = dynamic_cast<ViewPathItem*>(item); if (v_item->is_item_changed()) { v_item->update_video(); } } accept(); } /** * @brief ViewPathDialog::cancel_btn_clicked * Slot function for cancel button */ void ViewPathDialog::cancel_btn_clicked() { reject(); }
33.046392
121
0.684761
NFCSKL
6e235819495f5cf6377458a5b86b94b029566ffc
4,779
cpp
C++
src/bin/uptime.cpp
deep-1/haiku
b273e9733d25babe5e6702dc1e24f3dff1ffd6dc
[ "MIT" ]
4
2016-03-29T21:45:21.000Z
2016-12-20T00:50:38.000Z
src/bin/uptime.cpp
jessicah/haiku
c337460525c39e870d31221d205a299d9cd79c6a
[ "MIT" ]
null
null
null
src/bin/uptime.cpp
jessicah/haiku
c337460525c39e870d31221d205a299d9cd79c6a
[ "MIT" ]
1
2020-05-08T04:02:02.000Z
2020-05-08T04:02:02.000Z
/************ ** from http://www.beatjapan.org/mirror/www.be.com/beware/Utilities/uptime.html ** archive ftp://ftp.halcyon.com/pub/users/jrashmun/uptime.zip ** License : Freeware *************/ #include <stdio.h> #include <string.h> #include <time.h> #include <SupportDefs.h> #include <OS.h> void Usage( ); void Usage( ) { printf( "\nUsage: uptime [-u]\n" ); printf( "Prints the current date and time, as well\n" ); printf( "as the time elapsed since the system was started.\n" ); printf( "The optional argument omits the current date and time.\n\n" ); } int main( int argc, char* argv[] ) { char buf[255]; const char* day_strings[] = { "day", "days" }; const char* hour_strings[] = { "hour", "hours" }; const char* minute_strings[] = { "minute", "minutes" }; const char* day_string = 0; const char* hour_string = 0; const char* minute_string = 0; int print_uptime_only = 0; time_t current_time = 0; const time_t secs_per_day = 86400; const time_t secs_per_hour = 3600; const time_t secs_per_minute = 60; time_t uptime_days = 0; time_t uptime_hours = 0; time_t uptime_minutes = 0; time_t uptime_secs = 0; const bigtime_t usecs_per_sec = 1000000L; bigtime_t uptime_usecs = 0; bigtime_t usecs_since_sec = 0; if( argc > 2 ) { Usage( ); return 1; } if( argc == 2 ) { if( !strcmp( argv[1], "-u" ) ) print_uptime_only = 1; else { Usage( ); return 2; } } uptime_usecs = system_time( ); uptime_secs = uptime_usecs / usecs_per_sec; usecs_since_sec = uptime_usecs % usecs_per_sec; if( usecs_since_sec >= (usecs_per_sec / 2) ) uptime_secs++; uptime_days = uptime_secs / secs_per_day; uptime_hours = (uptime_secs % secs_per_day) / secs_per_hour; uptime_minutes = (uptime_secs % secs_per_hour) / secs_per_minute; current_time = time( 0 ); if( !print_uptime_only ) { strcpy( buf, ctime( &current_time ) ); buf[strlen( buf ) - 1] = '\0'; } day_string = (uptime_days == 1) ? day_strings[0] : day_strings[1]; hour_string = (uptime_hours == 1) ? hour_strings[0] : hour_strings[1]; minute_string = (uptime_minutes == 1) ? minute_strings[0] : minute_strings[1]; if( uptime_days && uptime_hours && uptime_minutes ) { if( !print_uptime_only ) printf( "%s, up %ld %s, %ld %s, %ld %s\n", buf, uptime_days, day_string, uptime_hours, hour_string, uptime_minutes, minute_string ); else printf( "up %ld %s, %ld %s, %ld %s\n", uptime_days, day_string, uptime_hours, hour_string, uptime_minutes, minute_string ); } else if( !uptime_days ) { if( uptime_hours && uptime_minutes ) { if( !print_uptime_only ) printf( "%s, up %ld %s, %ld %s\n", buf, uptime_hours, hour_string, uptime_minutes, minute_string ); else printf( "up %ld %s, %ld %s\n", uptime_hours, hour_string, uptime_minutes, minute_string ); } else if( uptime_hours ) { if( !print_uptime_only ) printf( "%s, up %ld %s\n", buf, uptime_hours, hour_string ); else printf( "up %ld %s\n", uptime_hours, hour_string ); } else { if( !print_uptime_only ) printf( "%s, up %ld %s\n", buf, uptime_minutes, minute_string ); else printf( "up %ld %s\n", uptime_minutes, minute_string ); } } else if( uptime_hours ) { if( !print_uptime_only ) printf( "%s, up %ld %s, %ld %s\n", buf, uptime_days, day_string, uptime_hours, hour_string ); else printf( "up %ld %s, %ld %s\n", uptime_days, day_string, uptime_hours, hour_string ); } else if( uptime_minutes ) { if( !print_uptime_only ) printf( "%s, up %ld %s, %ld %s\n", buf, uptime_days, day_string, uptime_minutes, minute_string ); else printf( "up %ld %s, %ld %s\n", uptime_days, day_string, uptime_minutes, minute_string ); } else { if( !print_uptime_only ) printf( "%s, up %ld %s\n", buf, uptime_days, day_string ); else printf( "up %ld %s\n", uptime_days, day_string ); } return 0; }
28.616766
81
0.529818
deep-1
6e26080ce8597ca5d0e7c254932c9c4e105ff076
35,217
cc
C++
acvIO.cc
kaityo256/acv
da5deb0f6e2298417c7c0241820096d806c7c2c4
[ "BSD-3-Clause" ]
null
null
null
acvIO.cc
kaityo256/acv
da5deb0f6e2298417c7c0241820096d806c7c2c4
[ "BSD-3-Clause" ]
null
null
null
acvIO.cc
kaityo256/acv
da5deb0f6e2298417c7c0241820096d806c7c2c4
[ "BSD-3-Clause" ]
null
null
null
#include <unistd.h> #include "acvIO.h" #define BUFFER_LENGTH 256 //------------------------------------------------------------ // Option Parser //------------------------------------------------------------ void Option::parseOptions(const int argc, char **argv, int &numfiles, System &sys, Type &typ) { std::string arg; std::string param = ""; if (argc > 2) param = std::string(argv[1]); File io; numfiles = 0; #ifndef DEMO if (argc == 1) { help(); exit(1); } #endif for (int i = 1; i < argc; i++) { arg = std::string(argv[i]); std::string::size_type opt = arg.find("-"); if (opt != 0) { numfiles++; continue; } if (arg.find("c") != std::string::npos) { param = std::string(argv[++i]); continue; } setOptions(arg.substr(opt + 1), sys, typ); } #ifndef DEMO sys.TYPE_MAX = io.MaxNumberofTypes(param); #endif typ.Init(sys.TYPE_MAX); io.loadParameters(sys, typ, param); } //------------------------------------------------------------ // Set Option values //------------------------------------------------------------ void Option::setOptions(std::string opt, System &sys, Type &typ) { std::string value; File io; if (opt.find("-generate") != std::string::npos) { io.saveParameter(sys, typ); std::cout << "Generate default parameter file : \"system_information.cfg\" \n"; std::cout << " 1) rename and edit parameter file.\n"; std::cout << " ex) $ mv system_information.cfg param.cfg\n"; std::cout << " 2) execute following command.\n"; std::cout << " ex) $ ./acv -c param.cfg data00001.dat data00002.dat ..." << std::endl; } else if (opt.find("-help") != std::string::npos) { help(); exit(1); } else if (opt.find("-version") != std::string::npos) { std::cout << "Version " << _VERSION_ << std::endl; } else if (opt.find("2D") != std::string::npos) { sys.ortho = 1; sys.quatanion[0] = 0.5; sys.quatanion[1] = 0.5; sys.quatanion[2] = 0.5; sys.quatanion[3] = 0.5; } else if (opt.find("multi") != std::string::npos) { sys.multi = 1; } else if (opt.find("stereo") != std::string::npos) { sys.stereo = 1; } else if (opt.find("d") != std::string::npos) { value = opt.substr(opt.find("d") + 1, opt.size()); sys.detail = atoi(value.c_str()); if (sys.detail < 6) sys.detail = 6; } else if (opt.find("h") != std::string::npos) { value = opt.substr(opt.find("h") + 1, opt.size()); sys.windowSize[1] = atoi(value.c_str()); } else if (opt.find("j") != std::string::npos) { sys.ortho = 1; } else if (opt.find("l") != std::string::npos) { value = opt.substr(opt.find("l") + 1, opt.size()); sys.distanceX = (GLfloat) atof(value.c_str()); } else if (opt.find("m") != std::string::npos) { value = opt.substr(opt.find("m") + 1, opt.size()); sys.numberParticle = atoi(value.c_str()); } else if (opt.find("p") != std::string::npos) { typ.visibleReverseAll(); } else if (opt.find("r") != std::string::npos) { value = opt.substr(opt.find("r") + 1, opt.size()); for (int i = 0; i < typ.types; i++) { typ.rad[i] = (GLfloat)atof(value.c_str()); typ.c_rad[i] = (GLfloat)atof(value.c_str()); } } else if (opt.find("w") != std::string::npos) { value = opt.substr(opt.find("w") + 1, opt.size()); sys.windowSize[0] = atoi(value.c_str()); } else if (opt.find("x") != std::string::npos) { value = opt.substr(opt.find("x") + 1, opt.size()); sys.windowPosition[0] = atoi(value.c_str()); } else if (opt.find("y") != std::string::npos) { value = opt.substr(opt.find("y") + 1, opt.size()); sys.windowPosition[1] = atoi(value.c_str()); } else if (opt.find("f") != std::string::npos) { value = opt.substr(opt.find("f") + 1, opt.size()); sys.fps = atoi(value.c_str()); } else if (opt.find("v") != std::string::npos) { value = opt.substr(opt.find("v") + 1, opt.size()); int direction = atoi(value.c_str()); sys.ConeDirection[direction] = 1; sys.ConeDisplay = true; } } //------------------------------------------------------------ // Display Help Information //------------------------------------------------------------ void Option::help(void) { std::cout << "Usage: acv [options] file... \n"; std::cout << "Options \n"; std::cout << " --generate \t Generate default parameter file (system_information.cfg). \n"; std::cout << " --version \t Display ACV version information. \n"; std::cout << " --help \t Display this information. \n"; std::cout << " -w<num> \t <num>:window width (default 640) \n"; std::cout << " -h<num> \t <num>:window height (default 480) \n"; std::cout << " -x<num> \t <num>:horizontal position (default 100) \n"; std::cout << " -y<num> \t <num>:vertical position (default 100) \n"; std::cout << " -d<num> \t <num>:polygon mesh (default 15) \n"; std::cout << " -l<num> \t <num>:eye position (default auto) \n"; std::cout << " -r<num> \t <num>:particle radius (default 0.7) \n"; std::cout << " -c <file>\t <file>:visualization information file \n"; std::cout << " -m<num> \t <num>:maximul number of particles (default 1000000) \n"; std::cout << " -f<num> \t <num>: FPS for movie (default 30) \n"; std::cout << " -p \t position preview mode. \n"; std::cout << " -j \t orthogonal projection mode. \n"; std::cout << " -2D \t XY-plane mode \n"; std::cout << " -multi \t multi drawing mode \n"; std::cout << std::endl; } //------------------------------------------------------------ File::File(void) { numfiles = 0; currentfile = 0; file_num_length = 0; } //------------------------------------------------------------ // Analyze File Name Format //------------------------------------------------------------ void File::setFilenameFormat(std::string filename) { file_ext = filename.substr(filename.rfind(".") + 1); std::string name = filename.substr(0, filename.rfind(".")); char fn[name.length()]; strcpy(fn, name.c_str()); file_num_length = 0; int num = name.length() - 1; while (isdigit(fn[num])) { file_num_length++; num--; } file_head = name.substr(0, num + 1); if (num < (int)name.length() - 1) { currentfile = atoi(name.substr(num + 1).c_str()); } else { currentfile = 0; } } //------------------------------------------------------------ // Get File Name //------------------------------------------------------------ std::string File::getCurrentFilename(void) { std::ostringstream filename; if (numfiles > 1) { filename << filenames[currentfile]; } else { filename << file_head << std::setfill('0') << std::setw(file_num_length) << currentfile << "." << file_ext; } return filename.str(); } std::string File::getCurrentFilename(const std::string ext) { std::ostringstream filename; filename << file_head << std::setfill('0') << std::setw(file_num_length) << currentfile << "." << ext; return filename.str(); } //------------------------------------------------------------ // Load Parameter File //------------------------------------------------------------ void File::loadParameters(System &sys, Type &typ, std::string path) { std::ifstream in; std::string line; in.open(path.c_str()); while (getline(in, line)) { std::string str, name, value; std::string::size_type comment = line.find("#"); if (comment == std::string::npos && line.length() != 0) { in.close(); return; } while (line.find("=") != std::string::npos) { str = line.substr(comment + 1); name = str.substr(0, str.find("=")); value = str.substr(str.find("=") + 1); if (value.find("=") != std::string::npos) { line = value.substr(value.find(",")); value = value.substr(0, value.find(",")); } else { line = value; } setParameter(sys, typ, name, value); } } in.close(); } //------------------------------------------------------------ // Max number of types //------------------------------------------------------------ int File::MaxNumberofTypes(std::string path) { int max_num_type = 40; std::ifstream in; std::string line; in.open(path.c_str()); while (getline(in, line)) { std::string str, name, value; std::string::size_type comment = line.find("#"); if (comment == std::string::npos && line.length() != 0) { in.close(); return max_num_type; } while (line.find("=") != std::string::npos) { str = line.substr(comment + 1); name = str.substr(0, str.find("=")); value = str.substr(str.find("=") + 1); if (value.find("=") != std::string::npos) { line = value.substr(value.find(",")); value = value.substr(0, value.find(",")); } else { line = value; } int type_num = 0; if (name.find("color") != std::string::npos) { type_num = atoi(name.substr(5).c_str()) + 1; } else if (name.find("radius") != std::string::npos) { type_num = atoi(name.substr(6).c_str()) + 1; } else if (name == "TYPE_MAX") { //type_num = atoi(value.c_str()); max_num_type = atoi(value.c_str()); return max_num_type; } if (type_num > max_num_type) { max_num_type = type_num; } } } in.close(); return max_num_type; } //------------------------------------------------------------ // Analyze Parameter File //------------------------------------------------------------ void File::setParameter(System &sys, Type &typ, std::string name, std::string value) { std::string vector[4]; if (name == "windowPosition") { splitVector(value, vector); for (int i = 0; i < 2; i++) sys.windowPosition[i] = atoi(vector[i].c_str()); } else if (name == "windowSize") { splitVector(value, vector); for (int i = 0; i < 2; i++) sys.windowSize[i] = atoi(vector[i].c_str()); } else if (name == "bgColor") { splitVector(value, vector); for (int i = 0; i < 4; i++) sys.bgColor[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "specular") { splitVector(value, vector); for (int i = 0; i < 4; i++) sys.specular[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "ambient") { splitVector(value, vector); for (int i = 0; i < 4; i++) sys.ambient[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "shininess") { sys.shininess[0] = (GLfloat)atof(value.c_str()); } else if (name == "lightPosition") { splitVector(value, vector); for (int i = 0; i < 4; i++) sys.lightPosition[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "numberParticle") { sys.numberParticle = atoi(value.c_str()); } else if (name == "systemSize") { splitVector(value, vector); for (int i = 0; i < 3; i++) sys.systemSize[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "systemCenter") { splitVector(value, vector); for (int i = 0; i < 3; i++) sys.systemCenter[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "boxColor") { splitVector(value, vector); for (int i = 0; i < 4; i++) sys.boxColor[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "boxStart") { splitVector(value, vector); for (int i = 0; i < 3; i++) sys.boxStart[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "boxEnd") { splitVector(value, vector); for (int i = 0; i < 3; i++) sys.boxEnd[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "boxWidth") { sys.boxWidth = (GLfloat)atof(value.c_str()); } else if (name == "boxVisible") { sys.boxVisible = atoi(value.c_str()); } else if (name == "boxDetail") { sys.boxDetail = atoi(value.c_str()); } else if (name == "distanceX") { sys.distanceX = (GLfloat)atof(value.c_str()); } else if (name == "distanceY") { sys.distanceY = (GLfloat)atof(value.c_str()); } else if (name == "distanceZ") { sys.distanceZ = (GLfloat)atof(value.c_str()); } else if (name == "quatanion") { splitVector(value, vector); for (int i = 0; i < 4; i++) sys.quatanion[i] = (GLfloat)atof(vector[i].c_str()); } else if (name == "axis") { splitVector(value, vector); for (int i = 0; i < 3; i++) sys.axis[i] = (GLfloat) atof(vector[i].c_str()); } else if (name == "angle") { sys.angle = atoi(value.c_str()); } else if (name == "detail") { sys.detail = atoi(value.c_str()); } else if (name == "scale") { sys.scale = (GLfloat)atof(value.c_str()); } else if (name == "shadow") { sys.shadow = atoi(value.c_str()); } else if (name == "fps") { sys.fps = atoi(value.c_str()); } else if (name.find("color") != std::string::npos) { int type_num; type_num = atoi(name.substr(5).c_str()); splitVector(value, vector); for (int i = 0; i < 4; i++) typ.color[type_num][i] = (GLfloat) atof(vector[i].c_str()); typ.clock[type_num] = 1; } else if (name.find("radius") != std::string::npos) { int type_num; type_num = atoi(name.substr(6).c_str()); typ.rad[type_num] = (GLfloat)atof(value.c_str()); typ.rlock[type_num] = 1; } else if (name.find("visible") != std::string::npos) { int type_num; type_num = atoi(name.substr(7).c_str()); typ.visible[type_num] = atoi(value.c_str()); } else if (name == "format") { splitDataColumn(sys, value); } else if (name == "box_sx") { sys.boxVisible = 1; sys.boxStart[0] = (GLfloat)atof(value.c_str()); } else if (name == "box_sy") { sys.boxStart[1] = (GLfloat) atof(value.c_str()); } else if (name == "box_sz") { sys.boxStart[2] = (GLfloat)atof(value.c_str()); } else if (name == "box_ex") { sys.boxEnd[0] = (GLfloat)atof(value.c_str()); } else if (name == "box_ey") { sys.boxEnd[1] = (GLfloat)atof(value.c_str()); } else if (name == "box_ez") { sys.boxEnd[2] = (GLfloat)atof(value.c_str()); } else if (name == "box_wt") { sys.boxWidth = (GLfloat)atof(value.c_str()); } else if (name.find("c") != std::string::npos) { if (isdigit(name.substr(name.find("c") + 1).c_str()[0])) { int type_num = atoi(name.substr(name.find("c") + 1).c_str()); if (typ.clock[type_num] == 1) return; splitVector(value, vector); for (int i = 0; i < 4; i++) typ.color[type_num][i] = (GLfloat)atof(vector[i].c_str()); } } else if (name.find("r") != std::string::npos) { if (isdigit(name.substr(name.find("r") + 1).c_str()[0])) { int type_num = atoi(name.substr(name.find("r") + 1).c_str()); if (typ.rlock[type_num] == 1) return; typ.rad[type_num] = (GLfloat)atof(value.c_str()); } } } //------------------------------------------------------------ // Save Parameter File //------------------------------------------------------------ void File::saveParameter(System sys, Type typ) { std::ofstream out; out.open("system_information.cfg"); out << "### Window Setting\n"; out << "#windowPosition=(" << sys.windowPosition[0] << "," << sys.windowPosition[1] << ")\n"; out << "#windowSize=(" << sys.windowSize[0] << "," << sys.windowSize[1] << ")\n"; out << "#bgColor=(" << sys.bgColor[0] << "," << sys.bgColor[1] << "," << sys.bgColor[2] << "," << sys.bgColor[3] << ")\n"; out << "\n"; out << "### Light Setting\n"; out << "#specular=(" << sys.specular[0] << "," << sys.specular[1] << "," << sys.specular[2] << "," << sys.specular[3] << ")\n"; out << "#ambient=(" << sys.ambient[0] << "," << sys.ambient[1] << "," << sys.ambient[2] << "," << sys.ambient[3] << ")\n"; out << "#shininess=" << sys.shininess[0] << "\n"; out << "#lightPosition=(" << sys.lightPosition[0] << "," << sys.lightPosition[1] << "," << sys.lightPosition[2] << "," << sys.lightPosition[3] << ")\n"; out << "\n"; out << "### System Setting\n"; out << "#numberParticle=" << 1000000 << "\n"; out << "#systemSize=(" << sys.systemSize[0] << "," << sys.systemSize[1] << "," << sys.systemSize[2] << ")\n"; out << "#systemCenter=(" << sys.systemCenter[0] << "," << sys.systemCenter[1] << "," << sys.systemCenter[2] << ")\n"; out << "#TYPE_MAX=" << sys.TYPE_MAX << "\n"; out << "\n"; out << "### Box Setting\n"; out << "#boxColor=(" << sys.boxColor[0] << "," << sys.boxColor[1] << "," << sys.boxColor[2] << "," << sys.boxColor[3] << ")\n"; out << "#boxStart=(" << sys.boxStart[0] << "," << sys.boxStart[1] << "," << sys.boxStart[2] << ")\n"; out << "#boxEnd=(" << sys.boxEnd[0] << "," << sys.boxEnd[1] << "," << sys.boxEnd[2] << ")\n"; out << "#boxWidth=" << sys.boxWidth << "\n"; out << "#boxVisible=" << sys.boxVisible << "\n"; out << "\n"; out << "### Orientation Setting\n"; out << "#distanceX=" << sys.distanceX << "\n"; out << "#distanceY=" << sys.distanceY << "\n"; out << "#distanceZ=" << sys.distanceZ << "\n"; out << "#quatanion=(" << sys.quatanion[0] << "," << sys.quatanion[1] << "," << sys.quatanion[2] << "," << sys.quatanion[3] << ")\n"; out << "\n"; out << "### Object Setting\n"; out << "#detail=" << sys.detail << "\n"; out << "#scale=" << sys.scale << "\n"; out << "\n"; out << "### Povray Setting\n"; out << "#shadow=" << sys.shadow << "\n"; out << "\n"; out << "### Movie Setting\n"; out << "#fps=" << sys.fps << "\n"; out << "\n"; out << "### Data File Format\n"; out << "#format="; std::string format = "", splitter = std::string(&sys.splitter); for (int i = 0; i < sys.columns; i++) { if (sys.column[0] == i)format += "id" + splitter; else if (sys.column[1] == i)format += "kind" + splitter; else if (sys.column[2] == i)format += "x" + splitter; else if (sys.column[3] == i)format += "y" + splitter; else if (sys.column[4] == i)format += "z" + splitter; else if (sys.column[5] == i)format += "r" + splitter; else if (sys.column[6] == i)format += "vx" + splitter; else if (sys.column[7] == i)format += "vy" + splitter; else if (sys.column[8] == i)format += "vz" + splitter; else if (sys.column[9] == i)format += "T" + splitter; else format += "dummy" + splitter; } format = format.substr(0, format.length() - 1); out << format << "\n\n"; out << "### Particle Color & Radius\n"; for (int i = 0; i < typ.types; i++) { //if(typ.clock[i]==1){ out << "#color" << i << "=(" << typ.color[i][0] << "," << typ.color[i][1] << "," << typ.color[i][2] << "," << typ.color[i][3] << ")\n"; //} //if(typ.rlock[i]==1){ out << "#radius" << i << "=" << typ.rad[i] << "\n"; //} out << "#visible" << i << "=" << typ.visible[i] << "\n"; out << "\n"; } out.close(); } //------------------------------------------------------------ // Convert String to 4-dimensional Vector //------------------------------------------------------------ void File::splitVector(std::string source, std::string vector[4]) { std::string tmp; tmp = source.substr(source.find("(") + 1, source.find(")") - source.find("(")); vector[0] = tmp.substr(0, tmp.find(",")); tmp = tmp.substr(tmp.find(",") + 1); vector[1] = tmp.substr(0, tmp.find(",")); tmp = tmp.substr(tmp.find(",") + 1); vector[2] = tmp.substr(0, tmp.find(",")); tmp = tmp.substr(tmp.find(",") + 1); vector[3] = tmp.substr(0, tmp.find(",")); } //------------------------------------------------------------ // Convert String to Data Column //------------------------------------------------------------ void File::splitDataColumn(System &sys, std::string source) { std::string tmp = source, cname; std::string splitter = " "; if (source.find(",") != std::string::npos) { splitter = ","; sys.splitter = 0x2C; //comma } int cols = 0; for (int i = 0; i < sys.columns; i++) { sys.column[i] = -1; } tmp = tmp.substr(tmp.find_first_not_of(" ")); tmp = tmp.substr(0, tmp.find_last_not_of(" ") + 1); while (true) { if (tmp.find(splitter) == std::string::npos) { cname = tmp.substr(0, tmp.find_last_not_of(splitter) + 1); setDataColumn(sys, cname, cols++); break; } else { cname = tmp.substr(0, tmp.find(splitter)); tmp = tmp.substr(tmp.find(splitter) + 1); tmp = tmp.substr(tmp.find_first_not_of(" ")); tmp = tmp.substr(tmp.find_first_not_of(splitter)); setDataColumn(sys, cname, cols++); } } sys.columns = cols; } //------------------------------------------------------------ // Set Data Column //------------------------------------------------------------ void File::setDataColumn(System &sys, const std::string name, const int col_num) { if (name == "id") sys.column[0] = col_num; else if (name == "kind") sys.column[1] = col_num; else if (name == "x") sys.column[2] = col_num; else if (name == "y") sys.column[3] = col_num; else if (name == "z") sys.column[4] = col_num; else if (name == "r") sys.column[5] = col_num; else if (name == "vx") sys.column[6] = col_num; else if (name == "vy") sys.column[7] = col_num; else if (name == "vz") sys.column[8] = col_num; else if (name == "T") sys.column[9] = col_num; } //------------------------------------------------------------ // Load Particle Information //------------------------------------------------------------ bool File::loadFile(System &sys, Type &typ, Particle *P, std::string filename) { int fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { std::cout << " cannot open " << filename << std::endl; close(fd); return false; } loadParameters(sys, typ, filename); float min_x = sizeof(float), min_y = sizeof(float), min_z = sizeof(float); float max_x = 0.0, max_y = 0.0, max_z = 0.0; float x = 0.0f, y = 0.0f, z = 0.0f; int num = 0; const int col_num = sys.columns; std::string str; std::string *element; element = new std::string[col_num]; struct stat statbuf; fstat(fd, &statbuf); char *buf, *buf_ini; buf = new char[statbuf.st_size + 1]; buf_ini = buf; int rd = read(fd, buf, statbuf.st_size); if (rd < 0) { std::cout << "Error: cannot read buffer : " << filename << std::endl; exit(1); } close(fd); if (buf[statbuf.st_size - 1] != '\n') buf[statbuf.st_size] = '\n'; char *sub, tmp[BUFFER_LENGTH], tmp2[BUFFER_LENGTH]; float max_norm = 0; while ((sub = strchr(buf, '\n')) != NULL || buf - buf_ini < statbuf.st_size) { *sub = '\0'; sub++; strncpy(tmp, buf, sub - buf); buf = sub; if (strchr(tmp, '#') != NULL) continue; int col = 0, len = 0; for (int i = 0; i < BUFFER_LENGTH; i++) { tmp2[len++] = tmp[i]; //if(tmp[i]==0x20){ if (tmp[i] == sys.splitter) { if (len > 1) { element[col++] = std::string(tmp2); } len = 0; } else if (tmp[i] == '\0') { element[col] = std::string(tmp2); break; } if (col == col_num) break; } if (sys.column[0] != -1) P[num].id = atoi(element[sys.column[0]].c_str()); else P[num].id = num; if (sys.column[1] != -1) P[num].type = atoi(element[sys.column[1]].c_str()) % sys.TYPE_MAX; else P[num].type = 0; if (sys.column[2] != -1) x = (float)atof(element[sys.column[2]].c_str()); else x = 0; if (sys.column[3] != -1) y = (float)atof(element[sys.column[3]].c_str()); else y = 0; if (sys.column[4] != -1) z = (float)atof(element[sys.column[4]].c_str()); else z = 0; if (x > max_x) max_x = x; else if (x < min_x) min_x = x; if (y > max_y) max_y = y; else if (y < min_y) min_y = y; if (z > max_z) max_z = z; else if (z < min_z) min_z = z; P[num].x[X] = x; P[num].x[Y] = y; P[num].x[Z] = z; if (sys.column[5] != -1) P[num].r = (GLfloat)atof(element[sys.column[5]].c_str()); //if(sys.column[6]!=-1 && sys.column[7]!=-1 && sys.column[8]!=- 1){ if (sys.ConeDisplay) { P[num].v[X] = (GLfloat)atof(element[sys.column[6]].c_str()); P[num].v[Y] = (GLfloat)atof(element[sys.column[7]].c_str()); P[num].v[Z] = (GLfloat)atof(element[sys.column[8]].c_str()); P[num].norm = sqrt(P[num].v[X] * P[num].v[X] + P[num].v[Y] * P[num].v[Y] + P[num].v[Z] * P[num].v[Z]); if (max_norm < P[num].norm) max_norm = P[num].norm; if (P[num].norm != 0.0) { P[num].v[X] /= P[num].norm; P[num].v[Y] /= P[num].norm; P[num].v[Z] /= P[num].norm; float dir = P[num].v[X] * sys.ConeDirection[0] + P[num].v[Y] * sys.ConeDirection[1] + P[num].v[Z] * sys.ConeDirection[2]; P[num].theta = acosf(dir) * 57.2957795130823f; } else { P[num].theta = 0; } } num++; } buf = buf_ini; delete []buf; if (num == 0) { std::cerr << filename << " does not have particle information." << std::endl; return false; } sys.numberParticle = num; if (sys.loaded == 0) { sys.systemSize[0] = (float)(max_x - min_x); sys.systemSize[1] = (float)(max_y - min_y); sys.systemSize[2] = (float)(max_z - min_z); sys.systemCenter[0] = (float)((max_x + min_x) * 0.5); sys.systemCenter[1] = (float)((max_y + min_y) * 0.5); sys.systemCenter[2] = (float)((max_z + min_z) * 0.5); sys.loaded = 1; } for (int i = 0; i < num; i++) { P[i].x[X] -= sys.systemCenter[0]; P[i].x[Y] -= sys.systemCenter[1]; P[i].x[Z] -= sys.systemCenter[2]; if (max_norm != 0) P[i].norm /= max_norm; } /* if(sys.columns>=6 && sys.column[1]==-1){ for(int i=0;i<10;i++){ typ.color[i][0]=(float)(i)/10.0f; typ.color[i][1]=0; typ.color[i][2]=((float)(10.0f - i)/10.0f); typ.color[i][3]=1.0; } for(int i=10;i<20;i++){ typ.color[i][0]=(float)(20.0f-i)/10.0f; typ.color[i][1]=(float)(i-10.0f)/10.0f; typ.color[i][2]=0.0f; typ.color[i][3]=1.0f; } for(int i=20;i<30;i++){ typ.color[i][0]=(float)(i-20.0f)/10.0f; typ.color[i][1]=(float)(i-20.0f)/10.0f; typ.color[i][2]=(float)(30.0f-i)/10.0f; typ.color[i][3]=1.0f; } for(int i=30;i<40;i++){ typ.color[i][0]=(float)(40.0f-i)/10.0f; typ.color[i][1]=1.0f; typ.color[i][2]=0.0f; typ.color[i][3]=1.0f; } } */ delete []element; return true; } //------------------------------------------------------------ // Generate FCC Configuration for DEMO //------------------------------------------------------------ void File::setFCC_DEMO(System &sys, Type &typ, Particle *P) { float radius = 1.0; float Lx = 40, Ly = 40, Lz = 40, dL = 2; int ngx = static_cast<int>(Lx / dL); int ngy = static_cast<int>(Ly / dL); int ngz = static_cast<int>(Lz / dL); int num = 0; for (int i = 0; i < ngx; i++) { for (int j = 0; j < ngy; j++) { for (int k = 0; k < ngz; k++) { ////// (0 , 0 , 0) P[num].id = num; P[num].type = 0; P[num].x[X] = i * dL + radius; P[num].x[Y] = j * dL + radius; P[num].x[Z] = k * dL + radius; P[num].r = radius; num++; ////// (1/2 , 1/2 , 0) P[num].id = num; P[num].type = 1; P[num].x[X] = (i + 0.5f) * dL + radius; P[num].x[Y] = (j + 0.5f) * dL + radius; P[num].x[Z] = k * dL + radius; P[num].r = radius; num++; ////// (1/2 , 0 , 1/2) P[num].id = num; P[num].type = 2; P[num].x[X] = (i + 0.5f) * dL + radius; P[num].x[Y] = j * dL + radius; P[num].x[Z] = (k + 0.5f) * dL + radius; P[num].r = radius; num++; ////// ( 0 , 1/2 , 1/2) P[num].id = num; P[num].type = 3; P[num].x[X] = i * dL + radius; P[num].x[Y] = (j + 0.5f) * dL + radius; P[num].x[Z] = (k + 0.5f) * dL + radius; P[num].r = radius; num++; } } } sys.numberParticle = num; sys.systemSize[0] = Lx; sys.systemSize[1] = Ly; sys.systemSize[2] = Lz; sys.systemCenter[0] = Lx * 0.5f; sys.systemCenter[1] = Ly * 0.5f; sys.systemCenter[2] = Lz * 0.5f; sys.boxStart[0] = 0; sys.boxStart[1] = 0; sys.boxStart[2] = 0; sys.boxEnd[0] = Lx; sys.boxEnd[1] = Ly; sys.boxEnd[2] = Lz; for (int i = 0; i < num; i++) { P[i].x[X] -= sys.systemCenter[0]; P[i].x[Y] -= sys.systemCenter[1]; P[i].x[Z] -= sys.systemCenter[2]; } sys.setInit(); saveDemoConfig(sys, P); } //------------------------------------------------------------ // Generate Random Configuration for DEMO //------------------------------------------------------------ void File::setRandom_DEMO(System &sys, Type &typ, Particle *P) { float radius = 1.0; float Lx = 80, Ly = 80, Lz = 100, dL = 2; int ngx = static_cast<int>(Lx / dL); int ngy = static_cast<int>(Ly / dL); int ngz = static_cast<int>(Lz / dL); int num = ngx * ngy * ngz * 4; srand((unsigned) time(NULL)); for (int i = 0; i < num; i++) { P[i].id = i; P[i].type = 0; P[i].x[X] = Lx * static_cast<float>(rand()) / static_cast<float>(RAND_MAX); P[i].x[Y] = Ly * static_cast<float>(rand()) / static_cast<float>(RAND_MAX); P[i].x[Z] = Lz * static_cast<float>(rand()) / static_cast<float>(RAND_MAX); P[i].r = radius; } sys.numberParticle = num; sys.systemSize[0] = Lx; sys.systemSize[1] = Ly; sys.systemSize[2] = Lz; sys.systemCenter[0] = Lx * 0.5f; sys.systemCenter[1] = Ly * 0.5f; sys.systemCenter[2] = Lz * 0.5f; sys.boxStart[0] = 0; sys.boxStart[1] = 0; sys.boxStart[2] = 0; sys.boxEnd[0] = Lx; sys.boxEnd[1] = Ly; sys.boxEnd[2] = Lz; for (int i = 0; i < num; i++) { P[i].x[X] -= sys.systemCenter[0]; P[i].x[Y] -= sys.systemCenter[1]; P[i].x[Z] -= sys.systemCenter[2]; } sys.setInit(); saveDemoConfig(sys, P); } //------------------------------------------------------------ // Save Configuration for DEMO //------------------------------------------------------------ void File::saveDemoConfig(System sys, Particle *P) { std::ofstream out; out.open("demo_config.dat"); for (int i = 0; i < sys.numberParticle; i++) { out << P[i].id << " " << P[i].type << " " << P[i].x[X] + sys.systemCenter[0] << " " << P[i].x[Y] + sys.systemCenter[1] << " " << P[i].x[Z] + sys.systemCenter[2] << std::endl; } out.close(); } //------------------------------------------------------------ // Save Bitmap //------------------------------------------------------------ int File::saveBitmap(const char *filename, const int width, const int height) { int alignmentParam; GLubyte *pixel_data; int glByteWidth; glGetIntegerv(GL_PACK_ALIGNMENT, &alignmentParam); if ((width * 3) % alignmentParam == 0) glByteWidth = width * 3; else glByteWidth = width * 3 + alignmentParam - (width * 3) % alignmentParam; pixel_data = new GLubyte[(glByteWidth) * (height) * (sizeof(GLubyte))]; glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixel_data); int checkByte = width & 3; /// Check number of bytes (multiples of 4 ) int writeWidth = width * 3 + checkByte; //std::ofstream out(filename, std::ios::binary); FILE *const out = std::fopen(filename, "w"); if (out == NULL) { delete []pixel_data; return -1; } AVI::bmp_writer bmp(out, width, height, writeWidth * height); char pixels[writeWidth * height]; unsigned char zero = 0; int count = 0; for (int y = 0 ; y < height ; y++) { for (int x = 0 ; x < width ; x++) { pixels[count++] = pixel_data[x * 3 + y * glByteWidth + 2]; pixels[count++] = pixel_data[x * 3 + y * glByteWidth + 1]; pixels[count++] = pixel_data[x * 3 + y * glByteWidth ]; } for (int j = 0; j < checkByte; j++) { pixels[count++] = zero; } } bmp.write(pixels); //out.close(); std::fclose(out); delete []pixel_data; return 0; } //------------------------------------------------------------ // Save Pov-Ray Format File //------------------------------------------------------------ void File::savePovRay(const char *fname, Type typ, System sys, Particle *P, GLfloat *rt) { std::ofstream out; out.open(fname); out << "camera{\n"; out << " location <" << -sys.distanceX << "," << sys.distanceY << "," << sys.distanceZ << ">\n"; out << " right <" << (float)sys.windowSize[0] / (float)sys.windowSize[1] << ",0,0>\n"; out << "angle 35 \n"; out << " up <0,1,0>\n"; out << " sky <0,0,1>\n"; out << " look_at <0.0," << sys.distanceY << "," << sys.distanceZ << ">\n"; out << "}\n"; out << "light_source {<" << -sys.lightPosition[0] << "," << sys.lightPosition[1] << "," << sys.lightPosition[2] << "> color rgb<1,1,1>}\n"; out << "background {color rgb<" << sys.bgColor[0] << "," << sys.bgColor[1] << "," << sys.bgColor[2] << ">}\n"; for (int i = 0; i < sys.numberParticle; i++) { if (typ.visible[P[i].type] == 1) { float d0 = rt[0] * P[i].x[X] + rt[4] * P[i].x[Y] + rt[8] * P[i].x[Z]; float d1 = rt[1] * P[i].x[X] + rt[5] * P[i].x[Y] + rt[9] * P[i].x[Z]; float d2 = rt[2] * P[i].x[X] + rt[6] * P[i].x[Y] + rt[10] * P[i].x[Z]; out << "sphere{<" << -d0 << "," << d1 << "," << d2 << ">," << sys.scale *typ.rad[P[i].type] << "\n"; out << " texture{\n"; out << " pigment{ color rgb <" << typ.color[P[i].type][0] << "," << typ.color[P[i].type][1] << "," << typ.color[P[i].type][2] << ">}\n"; out << " finish{\n"; out << " diffuse 1.0\n"; out << " ambient 0.4\n"; out << " }\n}\n "; if (sys.shadow == 0) out << "no_shadow\n"; out << "}\n"; } } out.close(); } //------------------------------------------------------------ // Save AVI Movie //------------------------------------------------------------ MakeAVI::MakeAVI(const std::string _filename) { out = NULL; filename = _filename; } void MakeAVI::initAVI(const int _width, const int _height, int fps = 30) { if (out == NULL) { #ifdef FFMPEG const char command_format[] = "ffmpeg -i - -y -sameq %s"; char command[sizeof(command_format) + 128]; sprintf(command, command_format, filename.c_str()); this->out = popen(command, "w"); #else //out.open(filename.c_str()); this->out = std::fopen(filename.c_str(), "w"); #endif } width = _width; height = _height; avi = new AVI::avi_writer(out, width, height, fps); } void MakeAVI::recAVI(void) { int alignmentParam; GLubyte *pixel_data; int glByteWidth; glGetIntegerv(GL_PACK_ALIGNMENT, &alignmentParam); if (width * 3 % alignmentParam == 0) glByteWidth = width * 3; else glByteWidth = width * 3 + alignmentParam - (width * 3) % alignmentParam; pixel_data = new GLubyte[(glByteWidth) * (height) * (sizeof(GLubyte))]; glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixel_data); char pixels[ width * height * 3]; int count = 0; for (int y = 0 ; y < height ; y++) { for (int x = 0 ; x < width ; x++) { pixels[count++] = pixel_data[x * 3 + 3 * y * width + 2]; pixels[count++] = pixel_data[x * 3 + 3 * y * width + 1]; pixels[count++] = pixel_data[x * 3 + 3 * y * width ]; } } avi->write((const char *)pixels); delete []pixel_data; } void MakeAVI::finishAVI(void) { #ifdef FFMPEG pclose(out); #else fclose(out); #endif }
32.943873
182
0.505353
kaityo256
6e289d4783777cc8b427352df6e1c3245a581215
3,022
hpp
C++
OptFrame/Util/TestMove.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/Util/TestMove.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/Util/TestMove.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef TESTMOVE_HPP_ #define TESTMOVE_HPP_ #include "../Move.hpp" #include <cstdlib> #include <iostream> namespace optframe { template<class R, class ADS = OPTFRAME_DEFAULT_ADS> class TestMove: public Move<R, ADS> { private: static const unsigned long long MAX_MOVE_IN_MEMORY_ERROR = 100000; static unsigned long long MAX_MOVE_IN_MEMORY_WARNING; static unsigned long long testmove_objects; static unsigned long long testmove_objects_nodecrement; unsigned long long testmove_number; public: TestMove() : Move<R, ADS>() { testmove_objects++; testmove_objects_nodecrement++; check(); testmove_number = testmove_objects_nodecrement; } virtual ~TestMove() { testmove_objects--; } void check() // check number of TestMove objects in memory { if (testmove_objects >= MAX_MOVE_IN_MEMORY_WARNING) { cout << "WARNING: " << TestMove<R, ADS>::testmove_objects << " TestMove objects in memory!" << endl; TestMove<R, ADS>::MAX_MOVE_IN_MEMORY_WARNING++; } if (testmove_objects >= MAX_MOVE_IN_MEMORY_ERROR) { cout << "ERROR: " << TestMove<R, ADS>::testmove_objects << " TestMove objects in memory!" << endl; cout << "MAX_MOVE_IN_MEMORY_ERROR = " << MAX_MOVE_IN_MEMORY_ERROR << endl; cout << "aborting..."; exit(1); } } void print() const { cout << "TestMove #" << testmove_number << " (" << testmove_objects << " in memory now): \n"; } TestMove<R, ADS>& operator=(const TestMove<R, ADS>& m) { if (&m == this) // auto ref check return *this; *this = Move<R, ADS>::operator=(m); // do not copy the 'testmove_number' return *this; } Move<R, ADS>& operator=(const Move<R, ADS>& m) { return operator=((const TestMove<R, ADS>&) m); } Move<R, ADS>& clone() const { Move<R, ADS>* m = new TestMove<R, ADS>(*this); return (*m); } }; template<class R, class ADS> unsigned long long TestMove<R, ADS>::MAX_MOVE_IN_MEMORY_WARNING = 0.7 * MAX_MOVE_IN_MEMORY_ERROR; template<class R, class ADS> unsigned long long TestMove<R, ADS>::testmove_objects = 0; template<class R, class ADS> unsigned long long TestMove<R, ADS>::testmove_objects_nodecrement = 0; } #endif /* TESTMOVE_HPP_ */
25.610169
103
0.708471
vncoelho
6e28af1cd0052ffafaaaea019130c799d8d50220
2,718
cpp
C++
test/matrix_array_test.cpp
muellan/containers
f07c4da2232faac115ff69b05f6d043308b01460
[ "MIT" ]
9
2017-07-03T20:57:53.000Z
2022-03-10T12:19:01.000Z
test/matrix_array_test.cpp
muellan/containers
f07c4da2232faac115ff69b05f6d043308b01460
[ "MIT" ]
null
null
null
test/matrix_array_test.cpp
muellan/containers
f07c4da2232faac115ff69b05f6d043308b01460
[ "MIT" ]
null
null
null
/***************************************************************************** * * AM utilities * * released under MIT license * * 2008-2017 André Müller * *****************************************************************************/ #include "matrix_array.h" #include <algorithm> #include <numeric> #include <stdexcept> #include <iostream> using namespace am; //------------------------------------------------------------------- void test_initialization() { matrix_array<int,4,3> m1 = { {11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43} }; matrix_array<int,1,3> m2 = {{1,2,3}}; if(!( (m1(0,0) == 11) && (m1(0,1) == 12) && (m1(0,2) == 13) && (m1(1,0) == 21) && (m1(1,1) == 22) && (m1(1,2) == 23) && (m1(2,0) == 31) && (m1(2,1) == 32) && (m1(2,2) == 33) && (m1(3,0) == 41) && (m1(3,1) == 42) && (m1(3,2) == 43) && (m2(0,0) == 1) && (m2(0,1) == 2) && (m2(0,2) == 3) )) { throw std::logic_error("am::matrix initialization"); } } //------------------------------------------------------------------- void test_iterators() { matrix_array<int,7,10> m; std::iota(begin(m), end(m), 11); long long int sum = 0; for(std::size_t j = 0; j < m.rows(); ++j) { for(auto i = m.begin_row(j), e = m.end_row(j); i != e; ++i) { sum += *i; } } sum *= 100; for(std::size_t j = 0; j < m.cols(); ++j) { for(auto i = m.begin_col(j), e = m.end_col(j); i != e; ++i) { sum += *i; } } sum *= 100; for(auto x : m.rectangle(0,0, m.rows()-1, m.cols()-1)) { sum += x; } sum *= 100; for(std::size_t r = 0; r < m.rows(); ++r) { for(std::size_t c = 0; c < m.cols(); ++c) { for(auto x : m.rectangle(0,0, r,c)) { sum += x; } } } for(int r = m.rows()-1; r >= 0; --r) { for(int c = m.cols()-1; c >= 0; --c) { for(auto x : m.rectangle(r,c, m.rows()-1, m.cols()-1)) { sum += x; } } } //diagonal iteration for square matrices { matrix_array<int,10,10> md; std::fill(begin(md), end(md), 0); std::fill(md.begin_diag(), md.end_diag(), 1); sum += std::accumulate(md.begin_diag(), md.end_diag(),0); } if(sum != 3217308650) { throw std::logic_error("am::matrix iteration"); } } //------------------------------------------------------------------- int main() { try { test_initialization(); test_iterators(); } catch(std::exception& e) { std::cerr << e.what(); return 1; } }
22.65
79
0.37454
muellan
6e2a758fd3a6f4f517647b12778d72c42caccd28
724
cc
C++
suif/lib/suif1/symaddr.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
5
2020-04-11T21:30:19.000Z
2021-12-04T16:16:09.000Z
suif/lib/suif1/symaddr.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
suif/lib/suif1/symaddr.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
/* Symbolic Address Implementation */ /* Copyright (c) 1994 Stanford University All rights reserved. This software is provided under the terms described in the "suif_copyright.h" include file. */ #include <suif_copyright.h> #define _MODULE_ "libsuif.a" #pragma implementation "symaddr.h" #define RCS_BASE_FILE symaddr_cc #include "suif1.h" RCS_BASE( "$Id$") void sym_addr::print (FILE *f) { putc('<', f); symbol()->print(f); fprintf(f, ",%d>", offset()); } sym_addr::sym_addr (in_stream *is, base_symtab *symtab) { sym = sym_node::read(is, symtab); off = is->read_int(); } void sym_addr::write (out_stream *os) { symbol()->write(os); os->write_int(offset()); }
15.083333
58
0.649171
paulhjkelly
6e32c57743069fda0ffce21b4fbd2939cde8edbd
5,376
cpp
C++
compiler/target_benchmark_internals/floyd_benchmark_main.cpp
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
95
2019-02-08T12:22:12.000Z
2019-07-29T06:32:29.000Z
compiler/target_benchmark_internals/floyd_benchmark_main.cpp
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
73
2019-02-25T18:44:36.000Z
2019-07-02T10:00:45.000Z
compiler/target_benchmark_internals/floyd_benchmark_main.cpp
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
9
2019-02-19T02:00:22.000Z
2019-07-01T19:10:33.000Z
// // main.cpp // megastruct // // Created by Marcus Zetterquist on 2019-01-28. // Copyright © 2019 Marcus Zetterquist. All rights reserved. // #include "gtest/gtest.h" #include "benchmark/benchmark.h" #include "hardware_caps.h" #include <iostream> #include <vector> //////////////////////////////// BENCHMARK -- GOOGLE EXAMPLES #if 0 int Factorial(int n) { if (n < 0 ) { return 0; } return !n ? 1 : n * Factorial(n - 1); } // IDEA: Only have load/store of entire cache lines. // Tests factorial of 0. TEST(FactorialTest, HandlesZeroInput) { EXPECT_EQ(Factorial(0), 1); } // Tests factorial of positive numbers. TEST(FactorialTest, HandlesPositiveInput) { EXPECT_EQ(Factorial(1), 1); EXPECT_EQ(Factorial(2), 2); EXPECT_EQ(Factorial(3), 6); EXPECT_EQ(Factorial(8), 40320); } namespace { double CalculatePi(int depth) { double pi = 0.0; for (int i = 0; i < depth; ++i) { double numerator = static_cast<double>(((i % 2) * 2) - 1); double denominator = static_cast<double>((2 * i) - 1); pi += numerator / denominator; } return (pi - 1.0) * 4; } std::set<int64_t> ConstructRandomSet(int64_t size) { std::set<int64_t> s; for (int i = 0; i < size; ++i) s.insert(s.end(), i); return s; } } // end namespace static void BM_Factorial(benchmark::State& state) { int fac_42 = 0; for (auto _ : state) fac_42 = Factorial(8); // Prevent compiler optimizations std::stringstream ss; ss << fac_42; state.SetLabel(ss.str()); } BENCHMARK(BM_Factorial); BENCHMARK(BM_Factorial)->UseRealTime(); static void BM_CalculatePiRange(benchmark::State& state) { double pi = 0.0; for (auto _ : state) pi = CalculatePi(static_cast<int>(state.range(0))); std::stringstream ss; ss << pi; state.SetLabel(ss.str()); } BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024); static void BM_CalculatePi(benchmark::State& state) { static const int depth = 1024; for (auto _ : state) { benchmark::DoNotOptimize(CalculatePi(static_cast<int>(depth))); } } BENCHMARK(BM_CalculatePi)->Threads(8); BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32); BENCHMARK(BM_CalculatePi)->ThreadPerCpu(); static void BM_SetInsert(benchmark::State& state) { std::set<int64_t> data; for (auto _ : state) { state.PauseTiming(); data = ConstructRandomSet(state.range(0)); state.ResumeTiming(); for (int j = 0; j < state.range(1); ++j) data.insert(rand()); } state.SetItemsProcessed(state.iterations() * state.range(1)); state.SetBytesProcessed(state.iterations() * state.range(1) * sizeof(int)); } // Test many inserts at once to reduce the total iterations needed. Otherwise, the slower, // non-timed part of each iteration will make the benchmark take forever. BENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}}); #endif #if 0 template <typename Container, typename ValueType = typename Container::value_type> static void BM_Sequential(benchmark::State& state) { ValueType v = 42; for (auto _ : state) { Container c; for (int64_t i = state.range(0); --i;) c.push_back(v); } const int64_t items_processed = state.iterations() * state.range(0); state.SetItemsProcessed(items_processed); state.SetBytesProcessed(items_processed * sizeof(v)); } BENCHMARK_TEMPLATE2(BM_Sequential, std::vector<int>, int) ->Range(1 << 0, 1 << 10); BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10); // Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond. #ifdef BENCHMARK_HAS_CXX11 BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>, int)->Arg(512); #endif static void BM_StringCompare(benchmark::State& state) { size_t len = static_cast<size_t>(state.range(0)); std::string s1(len, '-'); std::string s2(len, '-'); for (auto _ : state) benchmark::DoNotOptimize(s1.compare(s2)); } BENCHMARK(BM_StringCompare)->Range(1, 1 << 20); template <class... Args> void BM_with_args(benchmark::State& state, Args&&...) { for (auto _ : state) { } } BENCHMARK_CAPTURE(BM_with_args, int_test, 42, 43, 44); BENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string("abc"), std::pair<int, double>(42, 3.8)); void BM_non_template_args(benchmark::State& state, int, double) { while(state.KeepRunning()) {} } BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0); static void BM_DenseThreadRanges(benchmark::State& st) { switch (st.range(0)) { case 1: assert(st.threads == 1 || st.threads == 2 || st.threads == 3); break; case 2: assert(st.threads == 1 || st.threads == 3 || st.threads == 4); break; case 3: assert(st.threads == 5 || st.threads == 8 || st.threads == 11 || st.threads == 14); break; default: assert(false && "Invalid test case number"); } while (st.KeepRunning()) { } } BENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3); BENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2); BENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3); #endif int main(int argc, char** argv) { const auto caps = read_hardware_caps(); const auto caps_string = get_hardware_caps_string(caps); std::cout << caps_string; ::benchmark::Initialize(&argc, argv); if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; ::benchmark::RunSpecifiedBenchmarks(); }
25.722488
90
0.669085
Ebiroll
6e33019fa0d2effc92f96bd80fe19304a566073c
24,638
cpp
C++
MIRU_CORE/src/directx12/D3D12Image.cpp
AndrewRichards-Code/MIRU
7001830734c7ee0237243e3ab5cd9d2526d3db08
[ "MIT" ]
7
2020-09-07T12:36:42.000Z
2021-07-01T22:15:04.000Z
MIRU_CORE/src/directx12/D3D12Image.cpp
AndrewRichards-Code/MIRU
7001830734c7ee0237243e3ab5cd9d2526d3db08
[ "MIT" ]
null
null
null
MIRU_CORE/src/directx12/D3D12Image.cpp
AndrewRichards-Code/MIRU
7001830734c7ee0237243e3ab5cd9d2526d3db08
[ "MIT" ]
1
2021-06-11T04:28:57.000Z
2021-06-11T04:28:57.000Z
#include "miru_core_common.h" #if defined(MIRU_D3D12) #include "D3D12Image.h" #include "D3D12Allocator.h" using namespace miru; using namespace d3d12; Image::Image(Image::CreateInfo* pCreateInfo) :m_Device(reinterpret_cast<ID3D12Device*>(pCreateInfo->device)) { MIRU_CPU_PROFILE_FUNCTION(); m_CI = *pCreateInfo; m_ResourceDesc.Dimension = ToD3D12ImageType(m_CI.type); m_ResourceDesc.Alignment = 0; m_ResourceDesc.Width = m_CI.width; m_ResourceDesc.Height = m_CI.height; m_ResourceDesc.DepthOrArraySize = m_CI.type == Image::Type::TYPE_3D ? m_CI.depth : m_CI.arrayLayers; m_ResourceDesc.MipLevels = m_CI.mipLevels; m_ResourceDesc.Format = ToD3D12ImageFormat(m_CI.format); m_ResourceDesc.SampleDesc.Count = static_cast<UINT>(m_CI.sampleCount); m_ResourceDesc.SampleDesc.Quality = 0; m_ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; m_ResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; m_ResourceDesc.Flags |= (bool)(m_CI.usage & Image::UsageBit::COLOUR_ATTACHMENT_BIT) ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET : D3D12_RESOURCE_FLAGS(0); m_ResourceDesc.Flags |= (bool)(m_CI.usage & Image::UsageBit::DEPTH_STENCIL_ATTACHMENT_BIT) ? D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL : D3D12_RESOURCE_FLAGS(0); m_ResourceDesc.Flags |= (bool)(m_CI.usage & Image::UsageBit::STORAGE_BIT) ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAGS(0); D3D12_CLEAR_VALUE clear = {}; bool useClear = false; if (useClear = m_ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { clear.Format = m_ResourceDesc.Format; clear.Color[0] = 0.0f; clear.Color[1] = 0.0f; clear.Color[2] = 0.0f; clear.Color[3] = 0.0f; } if (useClear = m_ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { clear.Format = m_ResourceDesc.Format; clear.DepthStencil = { 0.0f, 0 }; } D3D12_HEAP_TYPE heapType = ref_cast<Allocator>(m_CI.pAllocator)->GetHeapProperties().Type; if (heapType == D3D12_HEAP_TYPE_DEFAULT) m_InitialResourceState = ToD3D12ImageLayout(m_CI.layout); if (heapType == D3D12_HEAP_TYPE_UPLOAD) m_InitialResourceState = D3D12_RESOURCE_STATE_GENERIC_READ; m_D3D12MAllocationDesc.Flags = D3D12MA::ALLOCATION_FLAG_NONE; m_D3D12MAllocationDesc.HeapType = heapType; m_D3D12MAllocationDesc.ExtraHeapFlags = D3D12_HEAP_FLAG_NONE; m_D3D12MAllocationDesc.CustomPool = nullptr; MIRU_ASSERT(m_CI.pAllocator->GetD3D12MAAllocator()->CreateResource(&m_D3D12MAllocationDesc, &m_ResourceDesc, m_InitialResourceState, useClear ? &clear : nullptr, &m_D3D12MAllocation, IID_PPV_ARGS(&m_Image)), "ERROR: D3D12: Failed to place Image."); D3D12SetName(m_Image, m_CI.debugName); m_Allocation.nativeAllocation = (crossplatform::NativeAllocation)m_D3D12MAllocation; m_Allocation.width = 0; m_Allocation.height = 0; m_Allocation.rowPitch = 0; m_Allocation.rowPadding = 0; if (m_CI.data) { m_CI.pAllocator->SubmitData(m_Allocation, m_CI.size, m_CI.data); } } Image::~Image() { MIRU_CPU_PROFILE_FUNCTION(); if (!m_SwapchainImage) { MIRU_D3D12_SAFE_RELEASE(m_D3D12MAllocation); MIRU_D3D12_SAFE_RELEASE(m_Image); } } void Image::GenerateMipmaps() { } D3D12_RESOURCE_DIMENSION Image::ToD3D12ImageType(Image::Type type) const { MIRU_CPU_PROFILE_FUNCTION(); switch (type) { case Image::Type::TYPE_1D: return D3D12_RESOURCE_DIMENSION_TEXTURE1D; case Image::Type::TYPE_2D: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; case Image::Type::TYPE_3D: return D3D12_RESOURCE_DIMENSION_TEXTURE3D; case Image::Type::TYPE_CUBE: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; case Image::Type::TYPE_1D_ARRAY: return D3D12_RESOURCE_DIMENSION_TEXTURE1D; case Image::Type::TYPE_2D_ARRAY: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; case Image::Type::TYPE_CUBE_ARRAY: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; default: return D3D12_RESOURCE_DIMENSION_UNKNOWN; } } DXGI_FORMAT Image::ToD3D12ImageFormat(Image::Format format) { MIRU_CPU_PROFILE_FUNCTION(); switch (format) { case Image::Format::UNKNOWN: case Image::Format::R4G4_UNORM_PACK8: case Image::Format::R4G4B4A4_UNORM_PACK16: case Image::Format::B4G4R4A4_UNORM_PACK16: return DXGI_FORMAT_UNKNOWN; case Image::Format::R5G6B5_UNORM_PACK16: case Image::Format::B5G6R5_UNORM_PACK16: return DXGI_FORMAT_B5G6R5_UNORM; case Image::Format::R5G5B5A1_UNORM_PACK16: case Image::Format::B5G5R5A1_UNORM_PACK16: case Image::Format::A1R5G5B5_UNORM_PACK16: return DXGI_FORMAT_B5G5R5A1_UNORM; //R8 case Image::Format::R8_UNORM: return DXGI_FORMAT_R8_UNORM; case Image::Format::R8_SNORM: return DXGI_FORMAT_R8_SNORM; case Image::Format::R8_USCALED: case Image::Format::R8_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8_UINT: return DXGI_FORMAT_R8_UINT; case Image::Format::R8_SINT: return DXGI_FORMAT_R8_SINT; case Image::Format::R8_SRGB: return DXGI_FORMAT_UNKNOWN; //RG8 case Image::Format::R8G8_UNORM: return DXGI_FORMAT_R8G8_UNORM; case Image::Format::R8G8_SNORM: return DXGI_FORMAT_R8G8_SNORM; case Image::Format::R8G8_USCALED: case Image::Format::R8G8_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8G8_UINT: return DXGI_FORMAT_R8G8_UINT; case Image::Format::R8G8_SINT: return DXGI_FORMAT_R8G8_SINT; case Image::Format::R8G8_SRGB: return DXGI_FORMAT_UNKNOWN; //RGB8 case Image::Format::R8G8B8_UNORM: case Image::Format::B8G8R8_UNORM: case Image::Format::R8G8B8_SNORM: case Image::Format::B8G8R8_SNORM: case Image::Format::R8G8B8_USCALED: case Image::Format::B8G8R8_USCALED: case Image::Format::R8G8B8_SSCALED: case Image::Format::B8G8R8_SSCALED: case Image::Format::R8G8B8_UINT: case Image::Format::B8G8R8_UINT: case Image::Format::R8G8B8_SINT: case Image::Format::B8G8R8_SINT: case Image::Format::R8G8B8_SRGB: case Image::Format::B8G8R8_SRGB: return DXGI_FORMAT_UNKNOWN; //RGBA8 case Image::Format::R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM; case Image::Format::B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM; case Image::Format::A8B8G8R8_UNORM_PACK32: return DXGI_FORMAT_R8G8B8A8_UNORM; case Image::Format::R8G8B8A8_SNORM: case Image::Format::B8G8R8A8_SNORM: case Image::Format::A8B8G8R8_SNORM_PACK32: return DXGI_FORMAT_R8G8B8A8_SNORM; case Image::Format::R8G8B8A8_USCALED: case Image::Format::B8G8R8A8_USCALED: case Image::Format::A8B8G8R8_USCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8G8B8A8_SSCALED: case Image::Format::B8G8R8A8_SSCALED: case Image::Format::A8B8G8R8_SSCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8G8B8A8_UINT: case Image::Format::B8G8R8A8_UINT: case Image::Format::A8B8G8R8_UINT_PACK32: return DXGI_FORMAT_R8G8B8A8_UINT; case Image::Format::R8G8B8A8_SINT: case Image::Format::B8G8R8A8_SINT: case Image::Format::A8B8G8R8_SINT_PACK32: return DXGI_FORMAT_R8G8B8A8_SINT; case Image::Format::R8G8B8A8_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; case Image::Format::B8G8R8A8_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; case Image::Format::A8B8G8R8_SRGB_PACK32: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; //RGB10_A2 case Image::Format::A2R10G10B10_UNORM_PACK32: case Image::Format::A2B10G10R10_UNORM_PACK32: return DXGI_FORMAT_R10G10B10A2_UNORM; case Image::Format::A2R10G10B10_SNORM_PACK32: case Image::Format::A2B10G10R10_SNORM_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::A2R10G10B10_USCALED_PACK32: case Image::Format::A2B10G10R10_USCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::A2R10G10B10_SSCALED_PACK32: case Image::Format::A2B10G10R10_SSCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::A2R10G10B10_UINT_PACK32: case Image::Format::A2B10G10R10_UINT_PACK32: return DXGI_FORMAT_R10G10B10A2_UINT; case Image::Format::A2R10G10B10_SINT_PACK32: case Image::Format::A2B10G10R10_SINT_PACK32: return DXGI_FORMAT_UNKNOWN; //R16 case Image::Format::R16_UNORM: return DXGI_FORMAT_R16_UNORM; case Image::Format::R16_SNORM: return DXGI_FORMAT_D16_UNORM; case Image::Format::R16_USCALED: case Image::Format::R16_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R16_UINT: return DXGI_FORMAT_R16_UINT; case Image::Format::R16_SINT: return DXGI_FORMAT_R16_SINT; case Image::Format::R16_SFLOAT: return DXGI_FORMAT_R16_FLOAT; //RG16 case Image::Format::R16G16_UNORM: return DXGI_FORMAT_R16G16_UNORM; case Image::Format::R16G16_SNORM: return DXGI_FORMAT_R16G16_SNORM; case Image::Format::R16G16_USCALED: case Image::Format::R16G16_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R16G16_UINT: return DXGI_FORMAT_R16G16_UINT; case Image::Format::R16G16_SINT: return DXGI_FORMAT_R16G16_SINT; case Image::Format::R16G16_SFLOAT: return DXGI_FORMAT_R16G16_FLOAT; //RGB16 case Image::Format::R16G16B16_UNORM: case Image::Format::R16G16B16_SNORM: case Image::Format::R16G16B16_USCALED: case Image::Format::R16G16B16_SSCALED: case Image::Format::R16G16B16_UINT: case Image::Format::R16G16B16_SINT: case Image::Format::R16G16B16_SFLOAT: return DXGI_FORMAT_UNKNOWN; //RGBA16 case Image::Format::R16G16B16A16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM; case Image::Format::R16G16B16A16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM; case Image::Format::R16G16B16A16_USCALED: case Image::Format::R16G16B16A16_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R16G16B16A16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT; case Image::Format::R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT; case Image::Format::R16G16B16A16_SFLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT; //R32 case Image::Format::R32_UINT: return DXGI_FORMAT_R32_UINT; case Image::Format::R32_SINT: return DXGI_FORMAT_R32_SINT; case Image::Format::R32_SFLOAT: return DXGI_FORMAT_R32_FLOAT; //RG32 case Image::Format::R32G32_UINT: return DXGI_FORMAT_R32G32_UINT; case Image::Format::R32G32_SINT: return DXGI_FORMAT_R32G32_SINT; case Image::Format::R32G32_SFLOAT: return DXGI_FORMAT_R32G32_FLOAT; //RGB32 case Image::Format::R32G32B32_UINT: return DXGI_FORMAT_R32G32B32_UINT; case Image::Format::R32G32B32_SINT: return DXGI_FORMAT_R32G32B32_SINT; case Image::Format::R32G32B32_SFLOAT: return DXGI_FORMAT_R32G32B32_FLOAT; //RGBA32 case Image::Format::R32G32B32A32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT; case Image::Format::R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT; case Image::Format::R32G32B32A32_SFLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT; //R64, RG64, RGB64, RGBA64 case Image::Format::R64_UINT: case Image::Format::R64_SINT: case Image::Format::R64_SFLOAT: case Image::Format::R64G64_UINT: case Image::Format::R64G64_SINT: case Image::Format::R64G64_SFLOAT: case Image::Format::R64G64B64_SINT: case Image::Format::R64G64B64_SFLOAT: case Image::Format::R64G64B64A64_UINT: case Image::Format::R64G64B64A64_SINT: case Image::Format::R64G64B64A64_SFLOAT: return DXGI_FORMAT_UNKNOWN; case Image::Format::B10G11R11_UFLOAT_PACK32: return DXGI_FORMAT_R11G11B10_FLOAT; case Image::Format::E5B9G9R9_UFLOAT_PACK32: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP; case Image::Format::D16_UNORM: return DXGI_FORMAT_D16_UNORM; case Image::Format::X8_D24_UNORM_PACK32: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; case Image::Format::D32_SFLOAT: return DXGI_FORMAT_D32_FLOAT; case Image::Format::S8_UINT: return DXGI_FORMAT_R8_UINT; case Image::Format::D16_UNORM_S8_UINT: return DXGI_FORMAT_UNKNOWN; case Image::Format::D24_UNORM_S8_UINT: return DXGI_FORMAT_D24_UNORM_S8_UINT; case Image::Format::D32_SFLOAT_S8_UINT: return DXGI_FORMAT_UNKNOWN; default: return DXGI_FORMAT_UNKNOWN; } } D3D12_RESOURCE_STATES Image::ToD3D12ImageLayout(Image::Layout layout) { MIRU_CPU_PROFILE_FUNCTION(); switch (layout) { case Image::Layout::UNKNOWN: return D3D12_RESOURCE_STATE_COMMON; case Image::Layout::GENERAL: return D3D12_RESOURCE_STATE_COMMON; case Image::Layout::COLOUR_ATTACHMENT_OPTIMAL: return D3D12_RESOURCE_STATE_RENDER_TARGET; case Image::Layout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_WRITE; case Image::Layout::DEPTH_STENCIL_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_READ; case Image::Layout::SHADER_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; case Image::Layout::TRANSFER_SRC_OPTIMAL: return D3D12_RESOURCE_STATE_COPY_SOURCE; case Image::Layout::TRANSFER_DST_OPTIMAL: return D3D12_RESOURCE_STATE_COPY_DEST; case Image::Layout::PREINITIALIZED: return D3D12_RESOURCE_STATE_COMMON; case Image::Layout::DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_READ; case Image::Layout::DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_READ; case Image::Layout::PRESENT_SRC: return D3D12_RESOURCE_STATE_PRESENT; case Image::Layout::SHARED_PRESENT: return D3D12_RESOURCE_STATE_PRESENT; case Image::Layout::D3D12_RESOLVE_SOURCE: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; case Image::Layout::D3D12_RESOLVE_DEST: return D3D12_RESOURCE_STATE_RESOLVE_DEST; case Image::Layout::D3D12_UNORDERED_ACCESS: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; case Image::Layout::D3D12_NON_PIXEL_SHADER_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; default: return D3D12_RESOURCE_STATE_COMMON; } } ImageView::ImageView(ImageView::CreateInfo* pCreateInfo) :m_Device(reinterpret_cast<ID3D12Device*>(pCreateInfo->device)) { MIRU_CPU_PROFILE_FUNCTION(); m_CI = *pCreateInfo; D3D12_RESOURCE_DESC resourceDesc = ref_cast<Image>(m_CI.pImage)->m_ResourceDesc; ID3D12Resource* image = ref_cast<Image>(m_CI.pImage)->m_Image; //RTV { m_RTVDesc.Format = resourceDesc.Format; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; m_RTVDesc.Texture1D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_2D: { if (resourceDesc.SampleDesc.Count > 1) { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS; break; } else { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; m_RTVDesc.Texture2D.MipSlice = m_CI.subresourceRange.baseMipLevel; m_RTVDesc.Texture2D.PlaneSlice = 0; break; } } case Image::Type::TYPE_3D: { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; m_RTVDesc.Texture3D.FirstWSlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture3D.WSize = m_CI.subresourceRange.arrayLayerCount; m_RTVDesc.Texture3D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_1D_ARRAY: { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; m_RTVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_RTVDesc.Texture1DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_CUBE: case Image::Type::TYPE_CUBE_ARRAY: case Image::Type::TYPE_2D_ARRAY: { if (resourceDesc.SampleDesc.Count > 1) { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; m_RTVDesc.Texture2DMSArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture2DMSArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; break; } else { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; m_RTVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_RTVDesc.Texture2DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; m_RTVDesc.Texture2DArray.PlaneSlice = 0; break; } } } } //DSV if(ref_cast<Image>(m_CI.pImage)->GetCreateInfo().format >= Image::Format::D16_UNORM) { m_DSVDesc.Format = resourceDesc.Format; m_DSVDesc.Flags = D3D12_DSV_FLAG_NONE; //D3D12_DSV_FLAG_READ_ONLY_DEPTH | D3D12_DSV_FLAG_READ_ONLY_STENCIL; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D; m_DSVDesc.Texture1D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_2D: { if (resourceDesc.SampleDesc.Count > 1) { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS; break; } else { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; m_DSVDesc.Texture2D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } } case Image::Type::TYPE_1D_ARRAY: { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1DARRAY; m_DSVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_DSVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_DSVDesc.Texture1DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_3D: case Image::Type::TYPE_CUBE: case Image::Type::TYPE_CUBE_ARRAY: case Image::Type::TYPE_2D_ARRAY: { if (resourceDesc.SampleDesc.Count > 1) { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; m_DSVDesc.Texture2DMSArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_DSVDesc.Texture2DMSArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; break; } else { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; m_DSVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_DSVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_DSVDesc.Texture2DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } } } } //SRV { m_SRVDesc.Format = resourceDesc.Format; m_SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; m_SRVDesc.Texture1D.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture1D.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture1D.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_2D: { if (resourceDesc.SampleDesc.Count > 1) { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS; break; } else { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; m_SRVDesc.Texture2D.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture2D.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture2D.PlaneSlice = 0; m_SRVDesc.Texture2D.ResourceMinLODClamp = 0.0f; break; } } case Image::Type::TYPE_3D: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; m_SRVDesc.Texture3D.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture3D.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture3D.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_CUBE: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; m_SRVDesc.TextureCube.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.TextureCube.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.TextureCube.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_1D_ARRAY: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; m_SRVDesc.Texture1DArray.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture1DArray.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_SRVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_SRVDesc.Texture1DArray.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_2D_ARRAY: { if (resourceDesc.SampleDesc.Count > 1) { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; m_SRVDesc.Texture2DMSArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_SRVDesc.Texture2DMSArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; break; } else { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; m_SRVDesc.Texture2DArray.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture2DArray.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_SRVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_SRVDesc.Texture2DArray.PlaneSlice = 0; m_SRVDesc.Texture2DArray.ResourceMinLODClamp = 0.0f; break; } } case Image::Type::TYPE_CUBE_ARRAY: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; m_SRVDesc.TextureCubeArray.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.TextureCubeArray.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.TextureCubeArray.First2DArrayFace = 0; m_SRVDesc.TextureCubeArray.NumCubes = resourceDesc.DepthOrArraySize / 6; m_SRVDesc.TextureCubeArray.ResourceMinLODClamp = 0.0f; break; } } } //UAV { m_UAVDesc.Format = resourceDesc.Format; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; m_UAVDesc.Texture1D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_2D: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; m_UAVDesc.Texture2D.MipSlice = m_CI.subresourceRange.baseMipLevel; m_UAVDesc.Texture2D.PlaneSlice = 0; break; } case Image::Type::TYPE_3D: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; m_UAVDesc.Texture3D.FirstWSlice = m_CI.subresourceRange.baseArrayLayer; m_UAVDesc.Texture3D.WSize = m_CI.subresourceRange.arrayLayerCount; m_UAVDesc.Texture3D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_1D_ARRAY: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; m_UAVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_UAVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_UAVDesc.Texture1DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_CUBE: case Image::Type::TYPE_CUBE_ARRAY: case Image::Type::TYPE_2D_ARRAY: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; m_UAVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_UAVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_UAVDesc.Texture2DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; m_UAVDesc.Texture2DArray.PlaneSlice = 0; break; } } } } ImageView::~ImageView() { MIRU_CPU_PROFILE_FUNCTION(); } Sampler::Sampler(Sampler::CreateInfo* pCreateInfo) :m_Device(reinterpret_cast<ID3D12Device*>(pCreateInfo->device)) { MIRU_CPU_PROFILE_FUNCTION(); m_CI = *pCreateInfo; m_SamplerDesc.Filter = ToD3D12Filter(m_CI.magFilter, m_CI.minFilter, m_CI.mipmapMode, m_CI.anisotropyEnable); m_SamplerDesc.AddressU = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(static_cast<uint32_t>(m_CI.addressModeU) + 1); m_SamplerDesc.AddressV = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(static_cast<uint32_t>(m_CI.addressModeV) + 1); m_SamplerDesc.AddressW = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(static_cast<uint32_t>(m_CI.addressModeW) + 1); m_SamplerDesc.MipLODBias = m_CI.mipLodBias; m_SamplerDesc.MaxAnisotropy = static_cast<UINT>(m_CI.maxAnisotropy); m_SamplerDesc.ComparisonFunc = static_cast<D3D12_COMPARISON_FUNC>(static_cast<uint32_t>(m_CI.compareOp) + 1); m_SamplerDesc.BorderColor[0] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_WHITE ? 0.0f : 1.0f; m_SamplerDesc.BorderColor[1] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_WHITE ? 0.0f : 1.0f; m_SamplerDesc.BorderColor[2] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_WHITE ? 0.0f : 1.0f; m_SamplerDesc.BorderColor[3] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_BLACK ? 0.0f : 1.0f; m_SamplerDesc.MinLOD = m_CI.minLod; m_SamplerDesc.MaxLOD = m_CI.maxLod; } Sampler::~Sampler() { MIRU_CPU_PROFILE_FUNCTION(); } D3D12_FILTER Sampler::ToD3D12Filter(Filter magFilter, Filter minFilter, MipmapMode mipmapMode, bool anisotropic) { MIRU_CPU_PROFILE_FUNCTION(); if (anisotropic) return D3D12_FILTER_ANISOTROPIC; uint32_t res = 0; if (mipmapMode == MipmapMode::LINEAR) res += 1; if (magFilter == Filter::LINEAR) res += 4; if (minFilter == Filter::LINEAR) res += 16; return static_cast<D3D12_FILTER>(res); } #endif
34.362622
249
0.79073
AndrewRichards-Code
6e37eb70713a8a61a8dd0019b40bf278c8943fdc
3,098
cpp
C++
codeforces/round698_div2/c.cpp
zaurus-yusya/atcoder
5fc345b3da50222fa1366d1ce52ae58799488cef
[ "MIT" ]
3
2020-05-27T16:27:12.000Z
2021-01-27T12:47:12.000Z
codeforces/round698_div2/c.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
codeforces/round698_div2/c.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> // #include <atcoder/all> // using namespace atcoder; typedef long long ll; typedef long double ld; #define rep(i,n) for(ll i=0;i<(n);i++) #define repr(i,n) for(ll i=(n-1);i>=0;i--) #define all(x) x.begin(),x.end() #define br cout << "\n"; using namespace std; const long long INF = 1e18; const long long MOD = 1e9+7; using Graph = vector<vector<ll>>; using pll = pair<ll, ll>; template<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;} template<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;} ll ceilll(ll a, ll b) {return (a + b-1) / b;} // if(a%b != 0) (a/b) + 1 ll get_digit(ll a) {ll digit = 0; while(a != 0){a /= 10; digit++;} return digit;} // a != 0 template<typename T> void vecdbg(vector<T>& v){ rep(i, v.size()){cout << v[i] << " ";} br;} template<typename T> void vecvecdbg(vector<vector<T>>& v){ rep(i, v.size()){rep(j, v[i].size()){cout << v[i][j] << " ";} br;}} // 0 false, 1 true // string number to int : -48 // a to A : -32 // ceil(a) 1.2->2.0 // c++17 g++ -std=c++17 a.cpp // global vector -> 0 initialization // DONT FORGET TO INTIALIZE // The type of GRID is CHAR. DONT USE STRING // If the result in local and judge is different, USE CODETEST!! int main() { std::cout << std::fixed << std::setprecision(15); ll t; cin >> t; rep(T, t){ ll n; cin >> n; vector<long long> d(2 * n); vector<ll> sum(2 * n + 1); map<ll, ll> mp; bool flag = true; for(long long i = 0; i < 2 * n; i ++){ cin >> d[i]; if(d[i] % 2 == 1) flag = false; mp[d[i]]++; } sort(all(d), greater<ll>()); rep(i, 2*n){ sum[i+1] = sum[i] + d[i]; } vecdbg(d); vecdbg(sum); cout << "---" << endl; for(ll i = 0; i < 2 * n; i++){ //cout << ( sum[i] - sum[0] - (i * d[i]) ) << " " << ( (2*n-i-1)*d[i] - (sum[2*n] - sum[i+1])) <<endl; cout << ( sum[i] - sum[0] - (i * d[i]) ) + ( (2*n-i-1)*d[i] - (sum[2*n] - sum[i+1])) <<endl; } cout << "---" << endl; vector<ll> sa; ll now = 0; ll res = 0; bool flag2 = false; for(auto i: mp){ if(flag2){ sa.push_back(i.first - now); now = i.first; res = i.first; }else{ flag2 = true; now = i.first; } /* now = i.first; cout << i.first << " " << i.second << endl; */ } vecdbg(sa); string ans = "YES"; ll tmp = 1, tmp2 = 1; ll cur = 2; rep(i, sa.size()){ if(sa[i] % cur != 0){ ans = "NO"; } tmp2 = tmp2 + sa[i] / cur; tmp += tmp2; cur += 2; } cout << tmp << " " << res << endl; if(tmp > (res/2)){ ans = "NO"; } cout << ans << endl; } }
29.504762
126
0.433505
zaurus-yusya
6e3825a9ba355e74773d092b7f48bc9c1269728b
41,987
cpp
C++
Software/2022-01-07d-OrangeHat-Webserver/src/ob.cpp
OrsoEric/OrangeHat
aac610605dd2dedd7c202b71d7002d1ffd33e853
[ "MIT" ]
3
2021-08-04T07:38:14.000Z
2022-01-05T09:46:59.000Z
Software/2022-01-07b Test OrangeBot Webserver/src/ob.cpp
OrsoEric/OrangeHat
aac610605dd2dedd7c202b71d7002d1ffd33e853
[ "MIT" ]
27
2021-06-26T09:55:26.000Z
2022-01-09T10:15:18.000Z
Software/2022-01-07d-OrangeHat-Webserver/src/ob.cpp
OrsoEric/OrangeHat
aac610605dd2dedd7c202b71d7002d1ffd33e853
[ "MIT" ]
null
null
null
/**************************************************************** ** OrangeBot Project ***************************************************************************** ** / ** / ** / ** ______ \ ** \ ** \ ***************************************************************************** ** ***************************************************************************** ** Author: Orso Eric ** Creation Date: ** Last Edit Date: ** Revision: 1 ** Version: 0.1 ALFA ****************************************************************************/ /**************************************************************************** ** HYSTORY VERSION ***************************************************************************** ** 2020-01-16 ** Upgrade to Uniparser V5 ** Added RX messages ** 2020-01-17 ** Added handlers ** Tested ping ** Tested signature ** Tested encoder absolute message ** Tested encoder relative message ** Tested encoder speed message ** Tested bad message ** 2020-01-26 ** Tested SET_PERF message. AT4809 Performance counters ** Fixed extra terminator problem of ParserWrap ** 2020-02-01 ** Added SET_PID_ERR_DUAL%S:%S:%S:%S from AT4809 ** Added ERR%u error message from AT4809 ****************************************************************************/ /**************************************************************************** ** DESCRIPTION ***************************************************************************** ** HOW TO ADD A MESSAGE: ** 1) "panopticon.h" add new status variables to the class header ** 2) "panopticon.cpp" add reference access methods to status variables ** 2b) "init" initialize new parameters to default values ** 3) "ob.cpp" add handler function to function prototypes and implementation ** 4) "ob.cpp" register message format and handler in "orangebot_node_cpp_init" ** 5) "ob.cpp" write the handler function to set the correct status vars inside panopticon ** 6) "ob.cpp" set BOILERPLATE_NAPI_STRING to 0 in order to enable the test bench ** 7) "example.cpp" add test cases, "show_robot_status" and check that the message is parsed correctly inside the status vars ** 8) "ob.cpp" set BOILERPLATE_NAPI_STRING to 1 in order to make the class work for the RPI ** 9) "orangebot_node_bindings.cpp" add the new fields to get_status_wrap ** 10) Transfer all the cpp and h files but example.cpp inside the raspberry pi scr directory ** 11) Compile the project there using "npm run build" ** The new status vars should now be parsed correctly and avaiable to "orangebot.js" NODE.JS RaspberryPi 3B+ ** From here you can add fields in index.html and bindings inside orangebot.js to process it correctly ***************************************************************************** ** MESSAGES FROM MAIN MOTOR BOARD ** F%s\0***STRING***\0 ** Get motor board signature. Argument is the number of bytes of the signature ** Handler is meant to raise a flag and intercept the required number of bytes without flipping them to the parser ** SET_ENC%u:%d\0 ** Main motor board answers with the encoder absolute reading for motor of index first argument ** SET_ENC_REL%s:%%s:%s:%s\0 ** Main Motor board answers with the relative encoder readings for all encoder channels ** SET_ENC_SPD%s:%%s:%s:%s\0 ** Main Motor board answers with the encoder speed readings for all encoder channels ***************************************************************************** ** MESSAGES TO MAIN MOTOR BOARD ** OFF\0 ** Disable Motors ** ON\0 ** Enable Motors ** PWM_DUAL%s:%s\0 ** Switch to PWM controls for the main wheels and set main wheel target PWM ** SPD_DUAL%s:%s\0 ** Switch to speed PID and set speed target ** POS_DUAL_REL%s:%s\0 ** Switch to position PID and set PID target. Meant for ultra precise positioning ** GET_ENC\0 ** Ask for absolute encoder readings ** Answer with four SET_ENC messages ** GET_REL_ENC\0 ** Ask for relative encoder readings ** Answer with one %s%s%s%s message ** GET_ENC_SPD\0 ** Ask for all encoder speed readings ** SET_PWM_SLOPE%s\0 ** Set the PWM slope of the PWM slew rate limiter controller ** GET_POS_PID%s\n ** ** SET_POS_PID%s:%s:%s\0 Set the gain of the position PID GET_POS_PID\0 Get the gain of the position PID Answer with a SET_POS_PID%s:%s:%s message GET_SPD_PID%s:%s:%s\0 Set the gain of the speed PID ****************************************************************************/ /**************************************************************************** ** KNOWN BUG ***************************************************************************** ** ****************************************************************************/ /**************************************************************************** ** INCLUDE ****************************************************************************/ //Standard C Libraries #include <cstdio> //#include <cstdlib> #include <stdint.h> //Standard C++ libraries #include <iostream> //#include <array> //#include <vector> //#include <queue> //#include <string> //#include <fstream> //#include <chrono> //#include <thread> //OS Libraries //#define _WIN32_WINNT 0x0500 //Enable GetConsoleWindow //#include <windows.h> //User Libraries //Include user log trace //#define ENABLE_DEBUG #include "debug.h" //Universal Parser V5 #include "uniparser.h" //Class header #include "ob.h" //Stores robot status variables #include "panopticon.h" /**************************************************************************** ** NAMESPACES ****************************************************************************/ using std::cout; namespace Orangebot { /**************************************************************************** ** GLOBAL VARIABILE ****************************************************************************/ //R parser used to decode messages from the motor board Uniparser g_orangebot_motor_board_rx_parser; //Memorize OrangeBot platform status vars Panopticon g_orangebot_platform; //signature characters left to parse int g_signature_remaining_length; //Size of the signature. = means invalid signature int g_signature_length; //Temp signature storage char g_signature[MAX_SIGNATURE_LENGTH]; /**************************************************************************** ** FUNCTION PROTOTYPES ****************************************************************************/ //Obtain the reference to the robot status vars structure extern Orangebot::Panopticon &get_robot_status( void ); //Hep convert from a small type to a regular int template <typename T> extern int to_int( T value ); //Expect the next (length) character received to be part of a signature extern bool set_signature_length( int length ); //Process current data as part of a signature extern bool parse_signature( uint8_t data ); //---------------------------------------------------------------- // HANDLERS //---------------------------------------------------------------- // Handlers automatically called when a message with arguments is received // Uniparser V5 is limited to regular function calls // Uniparser V5 needs a wrapper to call a class instance method //! Status Group //Ping Handler extern void ping_handler( void ); //Signature Handler extern void get_signature_handler( uint8_t str_length ); //Timestamp Handler extern void get_timestamp_handler( int32_t timestamp ); //AT4809 Error code extern void get_at4809_err_code( uint8_t err_code ); //AT4809 Performance Counters extern void set_perf_handler( int32_t at4809_cpu, uint8_t at4809_rxi, uint8_t at4809_txo ); //!Encoder Group //Single encoder absolute count update extern void get_one_enc_abs_handler( uint8_t index, int32_t enc ); //Quad encoder relative count update handler extern void get_four_enc_rel_handler( int16_t enc_rel_a, int16_t enc_rel_b, int16_t enc_rel_c, int16_t enc_rel_d ); //Quad encoder speed update handler extern void get_four_enc_spd_handler( int16_t enc_spd_a, int16_t enc_spd_b, int16_t enc_spd_c, int16_t enc_spd_d ); //Two encoder speed update handler extern void get_two_enc_spd_handler( int16_t enc_spd_a, int16_t enc_spd_b ); //! Control System Target Group //Handle the PWM message from the motor board extern void get_two_vnh7040_pwm_handler( int16_t pwm_a, int16_t pwm_b ); //! Control System Group //PWM slew rate limiter handler extern void get_pwm_ctrl_handler( int16_t slew_rate ); //Speed PID control parameters handler extern void get_spd_ctrl_handler( int16_t gain_proportional, int16_t gain_derivative, int16_t gain_integrative ); //Position PID control parameters handler extern void get_pos_ctrl_handler( int16_t gain_proportional, int16_t gain_derivative, int16_t gain_integrative ); //Error and slew rate of TWO PID controllers extern void get_pid_status_dual( int16_t err0, int16_t slew_rate0, int16_t err1, int16_t slew_rate1 ); /**************************************************************************** ** FUNCTION ****************************************************************************/ /***************************************************************************/ //! @brief reference //! get_robot_status | void /***************************************************************************/ //! @param x | //! @return void | //! @details /***************************************************************************/ Panopticon &get_robot_status( void ) { //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- return g_orangebot_platform; } //end function: get_robot_status | void /***************************************************************************/ //! @brief //! to_int<int16_t> | int16_t /***************************************************************************/ //! @param x | //! @return void | //! @details //! Help convert from a small type to a regular int /***************************************************************************/ template <> int to_int( int16_t value ) { //Trace Enter with arguments DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- int value_tmp = (int16_t)value; //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Fix illegal values if (value_tmp > 32767) { value_tmp -= 65536; } //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return value_tmp; } //end function: to_int<int16_t> | int16_t /***************************************************************************/ //! @brief Function //! orangebotNodeCppInit | void /***************************************************************************/ //! @param x | //! @return void | //! @details //! Initialize NODE.JS C++ library /***************************************************************************/ void orangebot_node_cpp_init( void ) { //Trace Enter with arguments DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- bool f_ret = false; //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //Construct platform structure g_orangebot_platform = Orangebot::Panopticon(); //Initialize parser class g_orangebot_motor_board_rx_parser = Orangebot::Uniparser(); //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //! Status Group //Register | Get Ping f_ret = g_orangebot_motor_board_rx_parser.add_cmd( "P", (void *)&ping_handler); //Register | Get Signature command f_ret = g_orangebot_motor_board_rx_parser.add_cmd( "F%u", (void *)&get_signature_handler); //Register | Get Timestamp f_ret = g_orangebot_motor_board_rx_parser.add_cmd( "TIME%d", (void *)&get_timestamp_handler); //Register | Set AT4809 Error code f_ret = g_orangebot_motor_board_rx_parser.add_cmd( "ERR%u", (void *)&get_at4809_err_code); //Register | Set AT4809 Performance f_ret = g_orangebot_motor_board_rx_parser.add_cmd( "SET_PERF%d:%u:%u", (void *)&set_perf_handler); //!Encoder Group //Get single absolute encoder reading f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "ENC_ABS%u:%d", (void *)&get_one_enc_abs_handler ); //Get quad relative encoder reading f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "ENC_REL%S:%S:%S:%S", (void *)&get_four_enc_rel_handler ); //Get quad encoder speed reading f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "ENC_SPD_DUAL%S:%S", (void *)&get_two_enc_spd_handler ); //Get quad encoder speed reading f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "ENC_SPD%S:%S:%S:%S", (void *)&get_four_enc_spd_handler ); //! Control System Target Group //Register | Dual PWM Command f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "PWM_DUAL%S:%S", (void *)&get_two_vnh7040_pwm_handler ); //! Control System Group //Register | Get PWM Slew Rate Limiter Parameters f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "PWM_PARAM%S", (void *)&get_pwm_ctrl_handler ); //Register | Get Speed PID Parameters f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "SPD_PARAM%S:%S:%S", (void *)&get_spd_ctrl_handler ); //Register | Get Position PID Parameters f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "POS_PARAM%S:%S:%S", (void *)&get_pos_ctrl_handler ); //Register | Get Pid status performance f_ret |= g_orangebot_motor_board_rx_parser.add_cmd( "SET_PID_ERR_DUAL%S:%S:%S:%S", (void *)&get_pid_status_dual ); //If: fail if (f_ret == true) { DPRINT("ERR: Failed to register command\n"); } //Initialize parser g_orangebot_motor_board_rx_parser.parse('\0'); //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN_ARG("success: %d\n", f_ret); return; } //end function: orangebotNodeCppInit | void /***************************************************************************/ //! @brief //! orangebotParse | std::string /***************************************************************************/ //! @param x | //! @return void | //! @details /***************************************************************************/ void orangebot_parse( std::string str ) { //Trace Enter with arguments DENTER_ARG( "%s\n", str.c_str() ); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //Counter unsigned int t; //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- cout << "CPP: Parsing: "; //For: all char in the string but the last (an extra \0) for (t = 0;t <= str.length()-BOILERPLATE_NAPI_STRING;t++) { //NODE:JS //If character is printable if ((str[t]>=' ') && (str[t]<='~')) { cout << str[t]; } else { int num = str[t]; cout << "(" << num << ")"; } //If: there are no signature characters to be processed if (g_signature_remaining_length <= 0) { DPRINT(">%x<\n", str[t]); //Extract char and feed it to the parser g_orangebot_motor_board_rx_parser.parse( str[t] ); } //If: there is at least a signature character to process else { //Process current data as part of a signature parse_signature( str[t] ); } } //End for: all cahr in the string cout << "\n"; //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: orangebotParse | std::string /***************************************************************************/ //! @brief function //! set_signature_length | int /***************************************************************************/ //! @param length | int //! @return void | //! @details //! Expect the next (length) character received to be part of a signature /***************************************************************************/ bool set_signature_length( int length ) { //Trace Enter DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- if (length >= MAX_SIGNATURE_LENGTH) { DRETURN_ARG("ERR: bad signature length: %d\n", length); return true; //OK } //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Expect the next n characters to be part of a signature g_signature_remaining_length = length; //Reset previous signature g_signature_length = 0; //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN_ARG("signature length: %d\n", length); return false; //OK } //end function: set_signature_length | int /***************************************************************************/ //! @brief function //! parse_signature | uint8_t /***************************************************************************/ //! @param data | uint8_t | signature character //! @return void | //! @details //! Process current data as part of a signature /***************************************************************************/ bool parse_signature( uint8_t data ) { //Trace Enter DENTER_ARG("data: %x\n", data); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //If: this data should not have been processed as signature if (g_signature_remaining_length <= 0) { //Invalidate signature g_signature_remaining_length = 0; g_signature_length = 0; DRETURN_ARG("ERR: no signature data left to be processed\n"); return true; //FAIL } //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Store current signature character g_signature[ g_signature_length ] = data; //Update current signature length g_signature_length++; //If: Exceed maximum size if (g_signature_length > MAX_SIGNATURE_LENGTH) { DRETURN_ARG("ERR: maximum signature size exceeded: %d\n", g_signature_length); cout << "CPP: maximum signature size exceeded:" << g_signature_length << "\n"; //Invalidate signature g_signature_remaining_length = 0; g_signature_length = 0; return true; //FAIL } //Data has been processed g_signature_remaining_length--; //If: last character is not a terminator if ((g_signature_remaining_length == 0) && (data != '\0')) { DRETURN_ARG("ERR: signature is not null terminated %x\n", data); //Invalidate signature g_signature_remaining_length = 0; g_signature_length = 0; cout << "CPP: Failed to decode signature. No NULL terminator\n"; return true; //FAIL } //If: string is complete and valid else if ((g_signature_remaining_length == 0) && (data == '\0')) { //Save the string inside the panopticon class g_orangebot_platform.signature() = std::string( g_signature ); cout << "CPP: Signature decoded: " << g_orangebot_platform.signature(); #ifdef ENABLE_DEBUG uint8_t *str_tmp = (uint8_t *)g_orangebot_platform.signature().c_str(); DPRINT("Signature decoded: %s\n", str_tmp ); #endif // ENABLE_DEBUG } //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return false; //OK } //end function: set_signature_length | int /**************************************************************************** ** PARSER HANDLERS ****************************************************************************/ /***************************************************************************/ //! @brief //! ping_handler | void /***************************************************************************/ //! @param x | //! @return void | //! @details //! Reset communication timeout /***************************************************************************/ void ping_handler( void ) { //Trace Enter DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: ping_handler | void /***************************************************************************/ //! @brief //! get_signature_handler | uint8_t /***************************************************************************/ //! @param x | //! @return void | //! @details //! Signature Handler /***************************************************************************/ void get_signature_handler( uint8_t str_length ) { //Trace Enter DENTER_ARG("Signature length: %d\n", str_length); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Setup the signature processor set_signature_length( str_length ); //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_signature_handler | uint8_t /***************************************************************************/ //! @brief //! get_timestamp_handler | int32_t /***************************************************************************/ //! @param timestamp | int32_t | platform side timestamp //! @return void | //! @details //! Timestamp Handler /***************************************************************************/ void get_timestamp_handler( int32_t timestamp ) { //Trace Enter DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //! @todo add timestamp on NODE.JS //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_timestamp_handler | int32_t /***************************************************************************/ //! @brief //! get_at4809_err_code | uint8_t /***************************************************************************/ //! @param err_code | uint8_t | AT4809 Error code (OrangeBot::Error_code) //! @return void | //! @details //! AT4809 Error code /***************************************************************************/ void get_at4809_err_code( uint8_t err_code ) { //Trace Enter DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Store error code from AT4809 g_orangebot_platform.at4809_err_code() = err_code; //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_at4809_err_code | uint8_t /**************************************************************************** ** Function ** Dummy | bool ****************************************************************************/ //! @param f bool //! @return bool | //! @brief dummy method to copy the code //! @details verbose description /***************************************************************************/ void set_perf_handler( int32_t at4809_cpu, uint8_t at4809_rxi, uint8_t at4809_txo ) { //Trace Enter with arguments DENTER_ARG("cpu: %d | rxi: %d | txo:%d\n", at4809_cpu, at4809_rxi, at4809_txo); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //! @details algorithm: g_orangebot_platform.cpu_scan_frequency() = at4809_cpu; g_orangebot_platform.uart_rxi_bandwidth() = at4809_rxi; g_orangebot_platform.uart_txo_bandwidth() = at4809_txo; //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- //Trace Return vith return value DRETURN_ARG("out: %d\n", 0); return; } //end function: Dummy | bool /***************************************************************************/ //! @brief //! get_one_enc_abs_handler | uint8_t, int32_t /***************************************************************************/ //! @param x | //! @return void | //! @details //! Single encoder absolute count update /***************************************************************************/ void get_one_enc_abs_handler( uint8_t index, int32_t enc ) { //Trace Enter DENTER_ARG( "index: %d | enc: %d\n", index, enc ); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //If: bad number of channels if (index >= NUM_ENC) { DRETURN_ARG("ERR: bad number of channel: %d\n", index); return; //FAIL } //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Save the encoder reading g_orangebot_platform.enc_pos( index ) = enc; #ifdef ENABLE_DEBUG enc = g_orangebot_platform.enc_pos( index ); DPRINT("enc_abs[%d]: %d\n", index, enc ); #endif //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_one_enc_abs_handler | uint8_t, int32_t /***************************************************************************/ //! @brief handler //! get_four_enc_rel_handler | int16_t, int16_t, int16_t, int16_t /***************************************************************************/ //! @param enc_rel_* | int16_t | encoder position reading change since last message //! @return void | //! @details //! Quad encoder relative count update handler /***************************************************************************/ void get_four_enc_rel_handler( int16_t enc_rel_a, int16_t enc_rel_b, int16_t enc_rel_c, int16_t enc_rel_d ) { //Trace Enter DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Save the encoder reading g_orangebot_platform.enc_pos( 0 ) += to_int<int16_t>(enc_rel_a); g_orangebot_platform.enc_pos( 1 ) += to_int<int16_t>(enc_rel_b); g_orangebot_platform.enc_pos( 2 ) += to_int<int16_t>(enc_rel_c); g_orangebot_platform.enc_pos( 3 ) += to_int<int16_t>(enc_rel_d); #ifdef ENABLE_DEBUG int t; int enc_tmp; for (t = 0;t < NUM_ENC;t++) { enc_tmp = g_orangebot_platform.enc_pos( t ); DPRINT( "enc[%d]: %d\n", t, enc_tmp ); } #endif // ENABLE_DEBUG //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //End handler: get_four_enc_rel_handler | int16_t, int16_t, int16_t, int16_t /***************************************************************************/ //! @brief handler //! get_four_enc_spd_handler | int16_t, int16_t, int16_t, int16_t /***************************************************************************/ //! @param enc_spd_* | int16_t | encoder speed reading //! @return void | //! @details //! Quad encoder speed update handler /***************************************************************************/ void get_four_enc_spd_handler( int16_t enc_spd_a, int16_t enc_spd_b, int16_t enc_spd_c, int16_t enc_spd_d ) { //Trace Enter DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Save the encoder reading g_orangebot_platform.enc_spd( 0 ) = to_int<int16_t>(enc_spd_a); g_orangebot_platform.enc_spd( 1 ) = to_int<int16_t>(enc_spd_b); g_orangebot_platform.enc_spd( 2 ) = to_int<int16_t>(enc_spd_c); g_orangebot_platform.enc_spd( 3 ) = to_int<int16_t>(enc_spd_d); #ifdef ENABLE_DEBUG int t; int enc_tmp; for (t = 0;t < NUM_ENC;t++) { enc_tmp = g_orangebot_platform.enc_spd( t ); DPRINT( "enc[%d]: %d\n", t, enc_tmp ); } #endif // ENABLE_DEBUG //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //End handler: get_four_enc_rel_handler | int16_t, int16_t, int16_t, int16_t /***************************************************************************/ //! @brief handler //! get_two_enc_spd_handler | int16_t, int16_t /***************************************************************************/ //! @param enc_spd_* | int16_t | encoder speed reading //! @return void | //! @details //! Quad encoder speed update handler /***************************************************************************/ void get_two_enc_spd_handler( int16_t enc_spd_a, int16_t enc_spd_b ) { //Trace Enter DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Save the encoder reading int tmp = enc_spd_a; tmp = to_int<int16_t>( tmp ); g_orangebot_platform.enc_spd( 0 ) = to_int<int16_t>( tmp ); tmp = enc_spd_b; tmp = to_int<int16_t>( tmp ); g_orangebot_platform.enc_spd( 1 ) = to_int<int16_t>( tmp ); #ifdef ENABLE_DEBUG int t; int enc_tmp; for (t = 0;t < NUM_ENC;t++) { enc_tmp = g_orangebot_platform.enc_spd( t ); DPRINT( "enc[%d]: %d\n", t, enc_tmp ); } #endif // ENABLE_DEBUG //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //End handler: get_two_enc_spd_handler | int16_t, int16_t /***************************************************************************/ //! @brief //! get_vnh7040_pwm_handler | int16_t | int16_t /***************************************************************************/ //! @param x | //! @return void | //! @details /***************************************************************************/ void get_two_vnh7040_pwm_handler( int16_t pwm_a, int16_t pwm_b ) { //Trace Enter DENTER_ARG("pwm: %d | %d\n", pwm_a, pwm_b); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- int tmp; //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- std::cout << "\nCPP: PWM: " << pwm_a << " | " << pwm_b << "\n"; //Save PWM targets tmp = pwm_a; tmp = to_int<int16_t>( tmp ); g_orangebot_platform.pwm( 0 ) = to_int<int16_t>(tmp); tmp = pwm_b; tmp = to_int<int16_t>( tmp ); g_orangebot_platform.pwm( 1 ) = to_int<int16_t>(tmp); /* g_orangebot_platform.pwm( 0 ) = pwm_a; g_orangebot_platform.pwm( 1 ) = pwm_b; */ //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_vnh7040_pwm_handler | int16_t | int16_t /***************************************************************************/ //! @brief //! get_pwm_ctrl_handler | int16_t /***************************************************************************/ //! @param slew_rate | int16_t | platform PWM slew rate settings //! @return void | //! @details //! PWM slew rate limiter handler /***************************************************************************/ void get_pwm_ctrl_handler( int16_t slew_rate ) { //Trace Enter DENTER_ARG("OrangeBot pwm slew rate: %d\n", slew_rate); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_pwm_ctrl_handler | int16_t /***************************************************************************/ //! @brief //! get_spd_ctrl_handler | int16_t, int16_t, int16_t /***************************************************************************/ //! @param gain_proportional | int16_t | platform PID parameter //! @param gain_derivative | int16_t | platform PID parameter //! @param gain_integrative | int16_t | platform PID parameter //! @return void | //! @details //! Speed PID control parameters handler /***************************************************************************/ void get_spd_ctrl_handler( int16_t gain_proportional, int16_t gain_derivative, int16_t gain_integrative ) { //Trace Enter DENTER_ARG("Gain | %d | %d | %d\n", gain_proportional, gain_derivative, gain_integrative); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_spd_ctrl_handler | int16_t, int16_t, int16_t /***************************************************************************/ //! @brief //! get_pos_ctrl_handler | int16_t, int16_t, int16_t /***************************************************************************/ //! @param gain_proportional | int16_t | platform PID parameter //! @param gain_derivative | int16_t | platform PID parameter //! @param gain_integrative | int16_t | platform PID parameter //! @return void | //! @details //! Position PID control parameters handler /***************************************************************************/ void get_pos_ctrl_handler( int16_t gain_proportional, int16_t gain_derivative, int16_t gain_integrative ) { //Trace Enter DENTER_ARG("Gain | %d | %d | %d\n", gain_proportional, gain_derivative, gain_integrative); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_spd_ctrl_handler | int16_t, int16_t, int16_t /***************************************************************************/ //! @brief //! get_pid_status_dual | int16_t, int16_t, int16_t, int16_t /***************************************************************************/ //! @param err* | int16_t | Error of the PID of index * //! @param slew_rate* | int16_t | Command slew rate of the PID of index * //! @return void | //! @details //! Error and slew rate of TWO PID controllers /***************************************************************************/ void get_pid_status_dual( int16_t err0, int16_t slew_rate0, int16_t err1, int16_t slew_rate1 ) { //Trace Enter DENTER_ARG("PID0 | Err: %d | Slew Rate: %d | PID1 | Err: %d | Slew Rate: %d\n", err0, slew_rate0, err1, slew_rate1); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //Store PID performance vars g_orangebot_platform.pid_err( 0 ) = err0; g_orangebot_platform.pid_slew_rate( 0 ) = slew_rate0; g_orangebot_platform.pid_err( 1 ) = err1; g_orangebot_platform.pid_slew_rate( 1 ) = slew_rate1; //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: get_pid_status_dual | int16_t, int16_t, int16_t, int16_t /***************************************************************************/ //! @brief //! function_template /***************************************************************************/ //! @param x | //! @return void | //! @details /***************************************************************************/ void function_template( void ) { //Trace Enter with arguments DENTER(); //---------------------------------------------------------------- // VARS //---------------------------------------------------------------- //---------------------------------------------------------------- // INIT //---------------------------------------------------------------- //---------------------------------------------------------------- // BODY //---------------------------------------------------------------- //---------------------------------------------------------------- // RETURN //---------------------------------------------------------------- DRETURN(); return; } //end function: /**************************************************************************** ** CLASSES ****************************************************************************/ } //End namespace: Orangebot
34.275102
125
0.399052
OrsoEric
6e3a00efcd6c178ce51b193d1565a185e01052da
1,461
cpp
C++
test/datastore/TestCacheMap.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
test/datastore/TestCacheMap.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
test/datastore/TestCacheMap.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
#include <pulsar/testing/CppTester.hpp> #include <pulsar/datastore/CacheMap.hpp> using namespace pulsar; using namespace std; TEST_SIMPLE(TestCacheMap){ CppTester tester("Testing CacheMap class"); CacheMap cm1; using Vector=vector<double>; Vector v1({1.0,2.0,3.0}),v2({2.0,3.0,4.0}); const std::string key="Vector1",not_key="Not A key"; unsigned int policy=CacheMap::NoPolicy; cm1.set(key,v1,policy); const set<string> keys({key}); tester.test_member_return("get_keys",true,keys,&CacheMap::get_keys,&cm1); shared_ptr<const int> pi; tester.test_member_return("get w/non-existent key",true,pi,&CacheMap::get<int>,&cm1,not_key,false); auto pj=cm1.get<Vector>(key,false); tester.test_equal("get_w/real key",v1,*pj); tester.test_member_return("size",true,1,&CacheMap::size,&cm1); cm1.set(key,v2,policy); pj=cm1.get<Vector>(key,false); tester.test_equal("set overwrote",v2,*pj); tester.test_member_call("erase w/non-existent key",true,&CacheMap::erase,&cm1,not_key); tester.test_member_return("erase did nothing",true,1,&CacheMap::size,&cm1); tester.test_member_call("erase w/real key",true,&CacheMap::erase,&cm1,key); tester.test_member_return("erased",true,0,&CacheMap::size,&cm1); tester.test_member_call("clear",true,&CacheMap::clear,&cm1); tester.test_member_return("cleared",true,0,&CacheMap::size,&cm1); tester.print_results(); return tester.nfailed(); }
39.486486
103
0.704997
pulsar-chem
6e3ae60f100a39af16412baea625c294224aa7e9
834
cpp
C++
Backtracking/Minimum Number of Jumps to Reach ( M , N ) From ( 1 , 1 )/SolutionByManisha.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
261
2019-09-30T19:47:29.000Z
2022-03-29T18:20:07.000Z
Backtracking/Minimum Number of Jumps to Reach ( M , N ) From ( 1 , 1 )/SolutionByManisha.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
647
2019-10-01T16:51:29.000Z
2021-12-16T20:39:44.000Z
Backtracking/Minimum Number of Jumps to Reach ( M , N ) From ( 1 , 1 )/SolutionByManisha.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
383
2019-09-30T19:32:07.000Z
2022-03-24T16:18:26.000Z
#include <iostream> using namespace std; int sol = INT_MAX; bool isSolve(int x, int y, int m, int n) { if (m > 0 && n > 0 && x <= m && y <= n) { return true; } return false; } void helper(int x, int y, int m, int n, int counter) { if (isSolve(x, y, m, n) == true) { if (x == m && y == n) { if (sol > counter) { sol = counter; } } helper(x + y, y, m, n, counter + 1); helper(x, x + y, m, n, counter + 1); } } int main() { int m, n; cout << "\nEnter M\t:\t"; cin >> m; cout << "\nEnter N\t:\t"; cin >> n; helper(1, 1, m, n, 0); if (sol == INT_MAX) { cout << "\nMinimum Number of Steps\t:\t-1\n"; } else { cout << "\nMinimum Number of Steps\t:\t" << sol << endl; } return 0; }
19.857143
64
0.43765
Mdanish777
6e3f4783bff8d26f9f70994215d52edba3f23321
922
cpp
C++
TC/721-DIV2-250.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
TC/721-DIV2-250.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
TC/721-DIV2-250.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned uint; class FlightDataRecorder { public: double getDistance(vector <int>, vector <int>); }; double FlightDataRecorder::getDistance(vector <int> heading, vector <int> distance) { double x = 0.0; double y = 0.0; const int N = (int) heading.size(); const double PI = acos(-1); for (int i = 0; i < N; i++) { x += cos(heading[i] / 180.0 * PI) * distance[i]; y += sin(heading[i] / 180.0 * PI) * distance[i]; } return hypot(x, y); } <%:testing-code%> //Powered by [KawigiEdit] 2.0!
22.487805
85
0.595445
aajjbb
6e41438a6878a205494243b850417d15701be8b7
3,178
cc
C++
reid_cloud/src/model/ImportSpecialPersonnelRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
reid_cloud/src/model/ImportSpecialPersonnelRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
reid_cloud/src/model/ImportSpecialPersonnelRequest.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/reid_cloud/model/ImportSpecialPersonnelRequest.h> using AlibabaCloud::Reid_cloud::Model::ImportSpecialPersonnelRequest; ImportSpecialPersonnelRequest::ImportSpecialPersonnelRequest() : RpcServiceRequest("reid_cloud", "2020-10-29", "ImportSpecialPersonnel") { setMethod(HttpRequest::Method::Post); } ImportSpecialPersonnelRequest::~ImportSpecialPersonnelRequest() {} long ImportSpecialPersonnelRequest::getUkId()const { return ukId_; } void ImportSpecialPersonnelRequest::setUkId(long ukId) { ukId_ = ukId; setBodyParameter("UkId", std::to_string(ukId)); } std::string ImportSpecialPersonnelRequest::getDescription()const { return description_; } void ImportSpecialPersonnelRequest::setDescription(const std::string& description) { description_ = description; setBodyParameter("Description", description); } std::string ImportSpecialPersonnelRequest::getExternalId()const { return externalId_; } void ImportSpecialPersonnelRequest::setExternalId(const std::string& externalId) { externalId_ = externalId; setBodyParameter("ExternalId", externalId); } long ImportSpecialPersonnelRequest::getSource()const { return source_; } void ImportSpecialPersonnelRequest::setSource(long source) { source_ = source; setBodyParameter("Source", std::to_string(source)); } std::string ImportSpecialPersonnelRequest::getPersonType()const { return personType_; } void ImportSpecialPersonnelRequest::setPersonType(const std::string& personType) { personType_ = personType; setBodyParameter("PersonType", personType); } std::string ImportSpecialPersonnelRequest::getUrls()const { return urls_; } void ImportSpecialPersonnelRequest::setUrls(const std::string& urls) { urls_ = urls; setBodyParameter("Urls", urls); } std::string ImportSpecialPersonnelRequest::getPersonName()const { return personName_; } void ImportSpecialPersonnelRequest::setPersonName(const std::string& personName) { personName_ = personName; setBodyParameter("PersonName", personName); } std::string ImportSpecialPersonnelRequest::getStoreIds()const { return storeIds_; } void ImportSpecialPersonnelRequest::setStoreIds(const std::string& storeIds) { storeIds_ = storeIds; setBodyParameter("StoreIds", storeIds); } std::string ImportSpecialPersonnelRequest::getStatus()const { return status_; } void ImportSpecialPersonnelRequest::setStatus(const std::string& status) { status_ = status; setBodyParameter("Status", status); }
24.635659
83
0.760227
aliyun
6e437318383671d2e835f4141ae32a3690d524d9
1,066
hpp
C++
inc/cxpr_swap.hpp
TinfoilPancakes/hilbert-generator
e53ce260e3e998d0c1e92e6e2165c0c0a347aa81
[ "MIT" ]
null
null
null
inc/cxpr_swap.hpp
TinfoilPancakes/hilbert-generator
e53ce260e3e998d0c1e92e6e2165c0c0a347aa81
[ "MIT" ]
null
null
null
inc/cxpr_swap.hpp
TinfoilPancakes/hilbert-generator
e53ce260e3e998d0c1e92e6e2165c0c0a347aa81
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* __ */ /* cxpr_swap.hpp <(o )___ */ /* ( ._> / - Weh. */ /* By: prp <tfm357@gmail.com> --`---'------------- */ /* 54 69 6E 66 6F 69 6C */ /* Created: 2020/09/11 16:09:39 by prp 2E 54 65 63 68 */ /* Updated: 2020/09/13 23:48:09 by prp 50 2E 52 2E 50 */ /* */ /* ************************************************************************** */ #ifndef CXPR_SWAP_HPP #define CXPR_SWAP_HPP template <typename T> constexpr void cxpr_swap( T&& a, T&& b ) { auto tmp = a; a = b; b = tmp; } #endif
48.454545
80
0.212946
TinfoilPancakes
6e452d29a3f39fb78781e818082866904b0f4aef
2,175
cpp
C++
icpc/2018-8-19/F.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
icpc/2018-8-19/F.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
icpc/2018-8-19/F.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long i64; #define NMAX 500 #define MOD 998244353 #define INV2 499122177 static int n, S[NMAX + 10][NMAX + 10]; static i64 G[NMAX + 10][NMAX + 10]; static bool m1[NMAX + 10], m2[NMAX + 10]; inline void add(i64 &a, i64 b) { a += b; if (a >= MOD) a -= MOD; } int main() { int T; scanf("%d", &T); while (T--) { scanf("%d", &n); i64 sum = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { scanf("%lld", &G[i][j]); add(sum, G[i][j] % MOD); } for (int k = 1; k <= n; k++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (G[i][j] > G[i][k] + G[k][j]) G[i][j] = G[i][k] + G[k][j]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) S[i][j] = j; sort(S[i] + 1, S[i] + n + 1, [i](int x, int y) { return G[i][x] < G[i][y]; }); } i64 ans = 0, d; for (int i = 1; i <= n; i++) for (int j = i + 1; j <= n; j++) { memset(m1, 0, sizeof(m1)); memset(m2, 0, sizeof(m2)); for (int k = 1; k <= n; k++) { if (G[i][k] < G[j][k]) m2[k] = true; else m1[k] = true; } int p = 1, q = 1; for (int k = 1; k <= n; k++) { while (p <= n && m1[S[i][p]]) p++; while (q <= n && m2[S[j][q]]) q++; if (p <= n && q <= n) { i64 id = G[i][S[i][p]], jd = G[j][S[j][q]]; if (id < jd) { d = id; p++; } else { d = jd; q++; } } else if (p <= n) d = G[i][S[i][p++]]; else d = G[j][S[j][q++]]; add(ans, d % MOD * (n - k) % MOD); } } i64 m = n * (n - 1) / 2; add(ans, sum * (m - 1) % MOD * INV2 % MOD); printf("%lld\n", ans); } return 0; }
27.884615
94
0.322299
Riteme
6e4bc35de6fb436d3f18646d12cf5f5e23d24710
6,760
cpp
C++
d3d10drv/texturecache.cpp
SuiMachine/khg-d3d10drv
58235d94440791f63abca857584bd2f06c963d60
[ "MIT" ]
null
null
null
d3d10drv/texturecache.cpp
SuiMachine/khg-d3d10drv
58235d94440791f63abca857584bd2f06c963d60
[ "MIT" ]
2
2019-06-11T16:46:56.000Z
2020-06-11T13:26:51.000Z
d3d10drv/texturecache.cpp
SuiMachine/khg-d3d10drv
58235d94440791f63abca857584bd2f06c963d60
[ "MIT" ]
1
2021-09-27T09:54:57.000Z
2021-09-27T09:54:57.000Z
/** Cache for game textures; also handles the external extra textures. */ #include "texturecache.h" #include "d3d10drv.h" //Definitions of extra external textures const TextureCache::ExternalTexture TextureCache::externalTextures[TextureCache::DUMMY_NUM_EXTERNAL_TEXTURES] = {{".detail",1},{".bump",0},{".height",0}}; TextureCache::TextureCache(ID3D10Device *device) { this->device = device; } /** Create a texture from a descriptor and data to fill it with. \param desc Direct3D texture description. \param data Data to fill the texture with. */ ID3D10Texture2D *TextureCache::createTexture(const D3D10_TEXTURE2D_DESC &desc,const D3D10_SUBRESOURCE_DATA &data) const { //Creates a texture, setting the TextureInfo's data member. HRESULT hr; ID3D10Texture2D *texture; hr=device->CreateTexture2D(&desc,&data, &texture); if(FAILED(hr)) { UD3D10RenderDevice::debugs("Error creating texture resource."); return nullptr; } return texture; } /** Update a single texture mip using a copy operation. \param id CacheID to insert texture with. \param mipNum Mip level to update. \param data Data to write to the mip. */ void TextureCache::updateMip(const FTextureInfo& Info,int mipNum,const D3D10_SUBRESOURCE_DATA &data) const { //If texture is currently bound, draw buffers before updating for(int i=0;i<TextureCache::DUMMY_NUM_TEXTURE_PASSES;i++) { if(texturePasses.boundTextureID[i]==Info.CacheID) { D3D::render(); break; } } //Update const auto& entry = textureCache.find(Info.CacheID)->second; //device->UpdateSubresource(entry.texture,mipNum,nullptr,(void*) data.pSysMem,data.SysMemPitch,data.SysMemSlicePitch); //UpdateSubResource leads to flickering on nvidia D3D10_MAPPED_TEXTURE2D Mapping; entry.texture->Map(mipNum,D3D10_MAP_WRITE_DISCARD,0,&Mapping); unsigned char* pDst = static_cast<unsigned char*>(Mapping.pData); const unsigned char* pSrc = static_cast<const unsigned char*>(data.pSysMem); for (int y = 0; y < Info.VClamp; y++) { memcpy(pDst, pSrc, Info.UClamp*sizeof(DWORD)>>mipNum); pSrc += data.SysMemPitch; pDst += Mapping.RowPitch; } entry.texture->Unmap(mipNum); } /** Load a texture from a .dds file \return true when succesful */ bool TextureCache::loadFileTexture(TCHAR* fileName, ID3D10Texture2D **tex, D3DX10_IMAGE_LOAD_INFO *loadInfo) const { HRESULT hr; hr = D3DX10CreateTextureFromFile(device, fileName, loadInfo, nullptr, (ID3D10Resource** )tex, nullptr); if(FAILED(hr)) return false; return true; } /** Create a resource view (texture usable by shader) from a filled-in texture and cache it. Caller can then release the texture. \param id CacheID to insert texture with. \param metadata Texture metadata. \param tex A filled Direct3D texture. \param extraIndex Index of the extra external texture slot to use (optional) */ void TextureCache::cacheTexture(unsigned __int64 id,const TextureMetaData &metadata, ID3D10Texture2D *tex, int extraIndex) { HRESULT hr; D3D10_TEXTURE2D_DESC desc; tex->GetDesc(&desc); //Create resource view ID3D10ShaderResourceView* r; D3D10_SHADER_RESOURCE_VIEW_DESC srDesc; srDesc.Format = desc.Format; srDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srDesc.Texture2D.MostDetailedMip = 0; srDesc.Texture2D.MipLevels = desc.MipLevels; hr = device->CreateShaderResourceView(tex,&srDesc,&r); if(FAILED(hr)) { UD3D10RenderDevice::debugs("Error creating texture shader resource view."); return; } //Cache texture if(extraIndex==-1) { CachedTexture c; c.metadata = metadata; tex->AddRef(); c.texture = tex; c.resourceView = r; for(int i=0;i<DUMMY_NUM_EXTERNAL_TEXTURES;i++) { c.externalTextures[i]=nullptr; } textureCache[id]=c; } else //add extra texture { CachedTexture *c = &textureCache[id]; c->externalTextures[extraIndex] = r; c->metadata.externalTextures[extraIndex]=true; } } /** Returns true if texture is in cache. \param id CacheID for texture. */ bool TextureCache::textureIsCached(DWORD64 id) const { return textureCache.find(id) != textureCache.end(); } /** Returns texture metadata. \param id CacheID for texture. */ const TextureCache::TextureMetaData &TextureCache::getTextureMetaData(DWORD64 id) const { return textureCache.find(id)->second.metadata; } /** Set the texture for a texture pass (diffuse, lightmap, etc). Texture is only set if it's not already the current one for that pass. Cached polygons (using the previous set of textures) are drawn before the switch is made. \param id CacheID for texture. NULL sets no texture for the pass (by disabling it using a shader constant). \param extraIndex Index of the extra external texture slot to use (optional), -1 for none. \return texture metadata so renderer can use parameters such as scale/pan; NULL is texture not found */ const TextureCache::TextureMetaData *TextureCache::setTexture(const Shader_Unreal* shader,TexturePass pass,DWORD64 id, int extraIndex) { static TextureMetaData *metadata[DUMMY_NUM_TEXTURE_PASSES]; //Cache this so it can even be returned when no texture was actually set (because same id as last time) if(id!=texturePasses.boundTextureID[pass]) //If different texture than previous one, draw geometry in buffer and switch to new texture { texturePasses.boundTextureID[pass]=id; D3D::render(); //Turn on and switch to new texture CachedTexture *tex; if(!textureIsCached(id)) //Texture not in cache, conversion probably went wrong. return nullptr; tex = &textureCache[id]; if(extraIndex==-1) shader->setTexture(pass,tex->resourceView); else shader->setTexture(pass,tex->externalTextures[extraIndex]); metadata[pass] = &tex->metadata; } return metadata[pass]; } /** Delete a texture (so it can be overwritten with an updated one). */ void TextureCache::deleteTexture(DWORD64 id) { std::unordered_map<DWORD64,CachedTexture>::iterator i = textureCache.find(id); if(i==textureCache.end()) return; SAFE_RELEASE(i->second.texture); SAFE_RELEASE(i->second.resourceView); for(int j=0;j<DUMMY_NUM_EXTERNAL_TEXTURES;j++) { SAFE_RELEASE(i->second.externalTextures[j]); } textureCache.erase(i); } /** Clear texture cache. */ void TextureCache::flush() { //Clear bindings so textures will be rebound after flush for(int i=0;i<DUMMY_NUM_TEXTURE_PASSES;i++) { texturePasses.boundTextureID[i]=0; } //Delete textures for(std::unordered_map<DWORD64,CachedTexture>::iterator i=textureCache.begin();i!=textureCache.end();i++) { while(i->second.resourceView) { SAFE_RELEASE(i->second.resourceView); } while(i->second.texture) { SAFE_RELEASE(i->second.texture); } for(int j=0;j<DUMMY_NUM_EXTERNAL_TEXTURES;j++) { SAFE_RELEASE(i->second.externalTextures[j]); } } textureCache.clear(); }
27.479675
165
0.744527
SuiMachine
6e4d53110d855e9f2bb81c97891cd90e71655e9e
15,076
cpp
C++
gem/Code/Source/Components/AlarmComponent.cpp
loherangrin/addons.o3de.date-time
e3e7719204490dc2b69598e88803aaa1b3bb4fa3
[ "Apache-2.0" ]
null
null
null
gem/Code/Source/Components/AlarmComponent.cpp
loherangrin/addons.o3de.date-time
e3e7719204490dc2b69598e88803aaa1b3bb4fa3
[ "Apache-2.0" ]
null
null
null
gem/Code/Source/Components/AlarmComponent.cpp
loherangrin/addons.o3de.date-time
e3e7719204490dc2b69598e88803aaa1b3bb4fa3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2022 Matteo Grasso * * 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 <AzCore/RTTI/BehaviorContext.h> #include <AzCore/Serialization/SerializeContext.h> #include <DateTime/Constants/DateTimeConstants.hpp> #include "../Types/Alarm.hpp" #include "AlarmComponent.hpp" using Loherangrin::Gems::DateTime::Date; using Loherangrin::Gems::DateTime::Time; using Loherangrin::Gems::DateTime::AlarmId; using Loherangrin::Gems::DateTime::AlarmComponent; namespace Loherangrin::Gems::DateTime { class AlarmComponentEventHandler : public AZ::SerializeContext::IEventHandler { void OnWriteEnd(void* io_classPtr) { auto* alarmComponent = reinterpret_cast<AlarmComponent*>(io_classPtr); alarmComponent->CancelAllAlarms(); alarmComponent->AddAlarmsFromConfig(alarmComponent->m_config.m_alarms); } }; class AlarmNotificationBusBehaviorHandler : public AlarmNotificationBus::Handler , public AZ::BehaviorEBusHandler { public: AZ_EBUS_BEHAVIOR_BINDER(AlarmNotificationBusBehaviorHandler, "{4E736648-7F9A-493A-811C-95AD6E855231}", AZ::SystemAllocator, OnAlarmBell ); void OnAlarmBell(const Date& i_date, const Time& i_time) override { Call(FN_OnAlarmBell, i_date, i_time); } }; } // Loherangrin::Gems::DateTime void AlarmComponent::Reflect(AZ::ReflectContext* io_context) { ConfigClass::Reflect(io_context); if(auto serializeContext = azrtti_cast<AZ::SerializeContext*>(io_context)) { serializeContext->Class<AlarmComponent, AZ::Component>() ->Version(0) ->EventHandler<AlarmComponentEventHandler>() ->Field("Configuration", &AlarmComponent::m_config) ; } if(auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(io_context)) { behaviorContext->EBus<AlarmRequestBus>("AlarmRequestBus") ->Attribute(AZ::Script::Attributes::Module, ScriptAttributes::MODULE) ->Attribute(AZ::Script::Attributes::Category, ScriptAttributes::CATEGORY) ->Event<AlarmId (AlarmRequestBus::Events::*)(const DateRecurrenceRuleBehaviorHandle&, const TimeRecurrenceRuleBehaviorHandle&, const AZ::EntityId&)>("SetAlarmToNotify", &AlarmRequestBus::Events::SetAlarmToNotify) ->Event("CancelAlarm", &AlarmRequestBus::Events::CancelAlarm) ->Event("CancelAllAlarms", &AlarmRequestBus::Events::CancelAllAlarms) ->Event("SilenceAlarm", &AlarmRequestBus::Events::SilenceAlarm) ->Event("SilenceAllAlarms", &AlarmRequestBus::Events::SilenceAllAlarms) ->Event("GetWhenNextAlarm", &AlarmRequestBus::Events::GetWhenNextAlarm) ->Event("GetNextAlarmDate", &AlarmRequestBus::Events::GetNextAlarmDate) ->Event("GetNextAlarmTime", &AlarmRequestBus::Events::GetNextAlarmTime) ; behaviorContext->EBus<AlarmNotificationBus>("AlarmNotificationBus") ->Attribute(AZ::Script::Attributes::Module, ScriptAttributes::MODULE) ->Attribute(AZ::Script::Attributes::Category, ScriptAttributes::CATEGORY) ->Handler<AlarmNotificationBusBehaviorHandler>() ; } } void AlarmComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& io_provided) { io_provided.push_back(Services::ALARM); } void AlarmComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& io_incompatible) { io_incompatible.push_back(Services::ALARM); } void AlarmComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& io_required) { io_required.push_back(Services::TIME); } void AlarmComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& io_dependent) { io_dependent.push_back(Services::DATE); } AlarmComponent::AlarmComponent() : m_isReversedTime { false } , m_alarmPrioritizer { m_isReversedTime } , m_allAlarms {} , m_orderedAlarms { m_alarmPrioritizer } , m_nowDate {} , m_config {} {} AlarmComponent::AlarmComponent(const ConfigClass& i_config) : m_isReversedTime { false } , m_alarmPrioritizer { m_isReversedTime } , m_allAlarms {} , m_orderedAlarms { m_alarmPrioritizer } , m_nowDate {} , m_config { i_config } { AddAlarmsFromConfig(m_config.m_alarms); } AlarmComponent::AlarmComponent(ConfigClass&& io_config) : m_isReversedTime { false } , m_alarmPrioritizer { m_isReversedTime } , m_allAlarms {} , m_orderedAlarms { m_alarmPrioritizer } , m_nowDate {} , m_config { AZStd::move(io_config) } { AddAlarmsFromConfig(m_config.m_alarms); } void AlarmComponent::Init() {} void AlarmComponent::Activate() { SynchronizeWithDateAndTimeComponents(); DateNotificationBus::Handler::BusConnect(); TimeNotificationBus::Handler::BusConnect(); AlarmRequestBus::Handler::BusConnect(); } void AlarmComponent::Deactivate() { AlarmRequestBus::Handler::BusDisconnect(); TimeNotificationBus::Handler::BusDisconnect(); DateNotificationBus::Handler::BusDisconnect(); } void AlarmComponent::OnDateDayChanged(const Date& i_nowDate) { m_nowDate = i_nowDate; } void AlarmComponent::OnDateReset(const Date& i_startDate) { m_nowDate = i_startDate; Time nowTime = GetCurrentTime(); ResetAlarms(nowTime); } void AlarmComponent::OnTimeSecondChanged(const Time& i_nowTime) { ProcessAlarms(i_nowTime); } void AlarmComponent::OnTimeSpeedChanged(float i_speed) { bool changed = CalculateTimeDirection(i_speed); if(!changed) { return; } Time nowTime; EBUS_EVENT_RESULT(nowTime, TimeRequestBus, GetCurrentTime); if(nowTime.IsValid()) { ResetAlarms(nowTime); } } void AlarmComponent::OnTimeReset(const Time& i_startTime) { ResetAlarms(i_startTime); } AlarmId AlarmComponent::SetAlarmToExecute(const DateRecurrenceRule& i_dateRule, const TimeRecurrenceRule& i_timeRule, const AlarmCallback& i_callback) { Time nowTime = GetCurrentTime(); AlarmHandle alarmHandle = Alarm::CreateInstance(i_dateRule, i_timeRule, i_callback); const AlarmId alarmId = AddAlarm(AZStd::move(alarmHandle), nowTime); return alarmId; } AlarmId AlarmComponent::SetAlarmToNotify(const DateRecurrenceRule& i_dateRule, const TimeRecurrenceRule& i_timeRule, const AZ::EntityId& i_requesterId) { Time nowTime = GetCurrentTime(); AlarmHandle alarmHandle = Alarm::CreateInstance(i_dateRule, i_timeRule, i_requesterId); const AlarmId alarmId = AddAlarm(AZStd::move(alarmHandle), nowTime); return alarmId; } AlarmId AlarmComponent::SetAlarmToNotify(const DateRecurrenceRuleBehaviorHandle& i_dateRuleHandle, const TimeRecurrenceRuleBehaviorHandle& i_timeRuleHandle, const AZ::EntityId& i_requester) { const DateRecurrenceRule* dateRule = i_dateRuleHandle.GetRule(); const TimeRecurrenceRule* timeRule = i_timeRuleHandle.GetRule(); if(!dateRule || !timeRule) { AZ_Assert(false, "Recurrence rule cannot be null"); return 0; } return SetAlarmToNotify(*dateRule, *timeRule, i_requester); } bool AlarmComponent::CancelAlarm(AlarmId i_alarmId) { auto result = m_allAlarms.find(Alarm::CreateEmpty(i_alarmId)); if(result == m_allAlarms.end()) { return false; } Alarm* alarm = result->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Cancel(); return true; } void AlarmComponent::CancelAllAlarms() { m_orderedAlarms = AlarmQueue { m_alarmPrioritizer }; m_allAlarms.clear(); } bool AlarmComponent::SilenceAlarm(AlarmId i_alarmId, bool i_silent) { auto result = m_allAlarms.find(Alarm::CreateEmpty(i_alarmId)); if(result == m_allAlarms.end()) { return false; } Alarm* alarm = result->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Silence(i_silent); return true; } void AlarmComponent::SilenceAllAlarms(bool i_silent) { for(auto& alarmHandle : m_allAlarms) { Alarm* alarm = alarmHandle.GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Silence(i_silent); } } AZStd::pair<Date, Time> AlarmComponent::GetWhenNextAlarm() const { if(m_orderedAlarms.empty()) { return AZStd::make_pair(Date {}, Time {}); } AlarmHandle* const alarmHandle = m_orderedAlarms.top(); Alarm* alarm = alarmHandle->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); return AZStd::make_pair(alarm->GetDate(), alarm->GetTime()); } Date AlarmComponent::GetNextAlarmDate() const { AZStd::pair<Date, Time> nextAlarm = GetWhenNextAlarm(); return nextAlarm.first; } Time AlarmComponent::GetNextAlarmTime() const { AZStd::pair<Date, Time> nextAlarm = GetWhenNextAlarm(); return nextAlarm.second; } bool AlarmComponent::DiscardPastAlarmRepeats(Alarm& io_alarm, const Time& i_nowTime) { const bool moved = io_alarm.GoToRepeatAt(m_nowDate, i_nowTime, m_isReversedTime); return moved; } AlarmId AlarmComponent::AddAlarm(AlarmHandle&& io_alarmHandle, const Time& i_nowTime) { auto result = m_allAlarms.find(io_alarmHandle); if(result != m_allAlarms.end()) { const AlarmId existingAlarmId = result->GetAlarmId(); return existingAlarmId; } AlarmHandle candidateAlarmHandle = AlarmHandle::ReWrapAlarm(AZStd::move(io_alarmHandle)); Alarm* candidateAlarm = candidateAlarmHandle.GetAlarm(); AZ_Assert(candidateAlarm != nullptr, "New alarm cannot be empty"); const bool hasRepeats = DiscardPastAlarmRepeats(*candidateAlarm, i_nowTime); if(!hasRepeats) { return 0; } AlarmId nTries = 0; const AlarmId maxTries = AZStd::numeric_limits<AlarmId>::max(); do { auto [ newAlarmHandle, inserted ] = m_allAlarms.insert(AZStd::move(candidateAlarmHandle)); if(!inserted) { candidateAlarmHandle = AlarmHandle::ReWrapAlarm(AZStd::move(candidateAlarmHandle)); ++nTries; continue; } auto newAlarmHandleAddress = &(*newAlarmHandle); m_orderedAlarms.emplace(newAlarmHandleAddress); const AlarmId newAlarmId = newAlarmHandle->GetAlarmId(); return newAlarmId; } while(nTries < maxTries); AZ_Assert(false, "Unable to find a free ID to insert the new alarm"); return 0; } void AlarmComponent::AddAlarmsFromConfig(const AZStd::vector<AlarmConfig>& i_alarmConfigs) { const Time emptyTime; for(const auto& alarmConfig : i_alarmConfigs) { AZStd::unique_ptr<DateRecurrenceRule> dateRule = alarmConfig.m_dateRule.CalculateRecurrenceRule(); AZStd::unique_ptr<TimeRecurrenceRule> timeRule = alarmConfig.m_timeRule.CalculateRecurrenceRule(); AlarmHandle alarmHandle; switch(alarmConfig.m_action) { case AlarmConfig::AlarmActionType::NOTIFY_REQUESTER: { alarmHandle = Alarm::CreateInstance(AZStd::move(dateRule), AZStd::move(timeRule), alarmConfig.m_actionRequesterId); } break; default: { AZ_Assert(false, "Unsupported action: %d", alarmConfig.m_action); return; } } if(alarmConfig.m_isSilent) { Alarm* alarm = alarmHandle.GetAlarm(); alarm->Silence(true); } AddAlarm(AZStd::move(alarmHandle), emptyTime); } } bool AlarmComponent::CalculateTimeDirection(float i_timeSpeed) { if(AZ::IsClose(i_timeSpeed, 0.0f, AZ::Constants::FloatEpsilon)) { return false; } bool oldReversedTime = m_isReversedTime; m_isReversedTime = (i_timeSpeed < 0.f); return (m_isReversedTime != oldReversedTime); } void AlarmComponent::ProcessAlarms(const Time& i_nowTime) { while(!m_orderedAlarms.empty()) { AlarmHandle* const alarmHandle = m_orderedAlarms.top(); Alarm* alarm = alarmHandle->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); if(!alarm->IsGoneOff(m_nowDate, i_nowTime, m_isReversedTime)) { if(!m_hasDate) { if(m_lastHours > i_nowTime.GetHours()) { for(auto& alarmHandle : m_allAlarms) { Alarm* alarm = alarmHandle.GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->ClearExtension(); } } m_lastHours = i_nowTime.GetHours(); } return; } bool hasRepeat; if(!alarm->IsCanceled()) { if(!alarm->IsSilent()) { if(const AZ::EntityId* requesterId = alarm->GetActionIfType<AZ::EntityId>()) { EBUS_EVENT_ID(*requesterId, AlarmNotificationBus, OnAlarmBell, alarm->GetDate(), alarm->GetTime()); } else if(const AlarmCallback* callback = alarm->GetActionIfType<AlarmCallback>()) { (*callback)(alarm->GetDate(), alarm->GetTime()); } else { AZ_Assert(false, "Unexpected action type: %d", alarm->GetActionType()); return; } } hasRepeat = alarm->NextRepeat(m_isReversedTime); } else { hasRepeat = false; } m_orderedAlarms.pop(); if(hasRepeat) { m_orderedAlarms.emplace(alarmHandle); } else { auto result = m_allAlarms.find(*alarmHandle); if(result != m_allAlarms.end()) { m_allAlarms.erase(result); } } } } void AlarmComponent::ResetAlarms(const Time& i_nowTime) { if(!m_orderedAlarms.empty()) { m_orderedAlarms = AlarmQueue { m_alarmPrioritizer }; } for(auto& alarmHandle : m_allAlarms) { Alarm* alarm = alarmHandle.GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Reset(); const bool hasRepeats = DiscardPastAlarmRepeats(*alarm, i_nowTime); if(!hasRepeats) { continue; } m_orderedAlarms.emplace(&alarmHandle); } } void AlarmComponent::SynchronizeWithDateAndTimeComponents() { Time nowTime; EBUS_EVENT_RESULT(nowTime, TimeRequestBus, GetCurrentTime); if(!nowTime.IsValid()) { AZ_Assert(false, "A running TimeComponent instance is required to process alarms, but none was found"); return; } float timeSpeed; EBUS_EVENT_RESULT(timeSpeed, TimeRequestBus, GetTimeSpeed); CalculateTimeDirection(timeSpeed); Date nowDate; EBUS_EVENT_RESULT(nowDate, DateRequestBus, GetCurrentDate); m_hasDate = nowDate.IsValid(); if(!m_hasDate) { AZ_Warning("AlarmLevelComponent", false, "Unable to find a DateComponent instance to synchronize with. Alarms will only be checked against time"); } m_nowDate = nowDate; ResetAlarms(nowTime); } Time AlarmComponent::GetCurrentTime() const { Time nowTime; EBUS_EVENT_RESULT(nowTime, TimeRequestBus, GetCurrentTime); AZ_Assert(nowTime.IsValid(), "A running TimeComponent instance is required to add a new alarm, but none was found"); return nowTime; } // --- bool AlarmComponent::AlarmComparator::operator()(const AlarmHandle& i_lhs, const AlarmHandle& i_rhs) const { return (i_lhs.CompareTo(i_rhs) == AlarmComparison::LESS_THAN); } AlarmComponent::AlarmPrioritizer::AlarmPrioritizer(bool i_reverse) : m_isReversedTime { i_reverse } {} bool AlarmComponent::AlarmPrioritizer::operator()(const AlarmHandle* i_lhs, const AlarmHandle* i_rhs) const { return (i_lhs->CompareTo(*i_rhs) == ((m_isReversedTime) ? AlarmComparison::LESS_THAN : AlarmComparison::GREATER_THAN)); }
26.542254
215
0.749005
loherangrin
6e4db13dd48163951056ee2a1dd16077f5c80020
9,380
cpp
C++
DlgSongProperties.cpp
addam/SkauTan
a46b60e91741da343a50a63948d3a19d961550d0
[ "Unlicense" ]
null
null
null
DlgSongProperties.cpp
addam/SkauTan
a46b60e91741da343a50a63948d3a19d961550d0
[ "Unlicense" ]
null
null
null
DlgSongProperties.cpp
addam/SkauTan
a46b60e91741da343a50a63948d3a19d961550d0
[ "Unlicense" ]
null
null
null
#include "DlgSongProperties.h" #include <assert.h> #include <QDebug> #include <QMessageBox> #include "ui_DlgSongProperties.h" #include "Database.h" #include "Settings.h" #include "Utils.h" DlgSongProperties::DlgSongProperties( Database & a_DB, SongPtr a_Song, QWidget * a_Parent ) : Super(a_Parent), m_UI(new Ui::DlgSongProperties), m_DB(a_DB), m_Song(a_Song), m_Duplicates(a_Song->duplicates()) { // Initialize the ChangeSets: m_TagManual = m_Song->tagManual(); m_Notes = m_Song->notes(); for (const auto & song: m_Duplicates) { m_TagID3Changes[song] = song->tagId3(); } // Initialize the UI: m_UI->setupUi(this); Settings::loadWindowPos("DlgSongProperties", *this); auto genres = Song::recognizedGenres(); genres.insert(0, ""); m_UI->cbManualGenre->addItems(genres); m_UI->cbManualGenre->setMaxVisibleItems(genres.count()); m_UI->lwDuplicates->addActions({ m_UI->actRemoveFromLibrary, m_UI->actDeleteFromDisk, }); // Connect the signals: connect(m_UI->btnCancel, &QPushButton::clicked, this, &DlgSongProperties::reject); connect(m_UI->btnOK, &QPushButton::clicked, this, &DlgSongProperties::applyAndClose); connect(m_UI->leManualAuthor, &QLineEdit::textEdited, this, &DlgSongProperties::authorTextEdited); connect(m_UI->leManualTitle, &QLineEdit::textEdited, this, &DlgSongProperties::titleTextEdited); connect(m_UI->cbManualGenre, &QComboBox::currentTextChanged, this, &DlgSongProperties::genreSelected); connect(m_UI->leManualMeasuresPerMinute, &QLineEdit::textEdited, this, &DlgSongProperties::measuresPerMinuteTextEdited); connect(m_UI->pteNotes, &QPlainTextEdit::textChanged, this, &DlgSongProperties::notesChanged); connect(m_UI->lwDuplicates, &QListWidget::currentRowChanged, this, &DlgSongProperties::switchDuplicate); connect(m_UI->actRemoveFromLibrary, &QAction::triggered, this, &DlgSongProperties::removeFromLibrary); connect(m_UI->actDeleteFromDisk, &QAction::triggered, this, &DlgSongProperties::deleteFromDisk); // Set the read-only edit boxes' palette to greyed-out: auto p = palette(); p.setColor(QPalette::Active, QPalette::Base, p.color(QPalette::Disabled, QPalette::Base)); p.setColor(QPalette::Inactive, QPalette::Base, p.color(QPalette::Disabled, QPalette::Base)); m_UI->leHash->setPalette(p); m_UI->leLength->setPalette(p); m_UI->leId3Author->setPalette(p); m_UI->leId3Title->setPalette(p); m_UI->leId3Genre->setPalette(p); m_UI->leId3MeasuresPerMinute->setPalette(p); m_UI->leFilenameAuthor->setPalette(p); m_UI->leFilenameTitle->setPalette(p); m_UI->leFilenameGenre->setPalette(p); m_UI->leFilenameMeasuresPerMinute->setPalette(p); // Fill in the data: m_IsInternalChange = true; m_UI->leHash->setText(Utils::toHex(a_Song->hash())); auto length = m_Song->length(); if (length.isValid()) { auto numSeconds = static_cast<int>(length.toDouble() + 0.5); m_UI->leLength->setText(tr("%1:%2 (%n seconds)", "SongLength", numSeconds) .arg(QString::number(numSeconds / 60)) .arg(QString::number(numSeconds % 60), 2, '0') ); } m_UI->leManualAuthor->setText(m_TagManual.m_Author.valueOrDefault()); m_UI->leManualTitle->setText(m_TagManual.m_Title.valueOrDefault()); m_UI->cbManualGenre->setCurrentText(m_TagManual.m_Genre.valueOrDefault()); if (m_TagManual.m_MeasuresPerMinute.isPresent()) { m_UI->leManualMeasuresPerMinute->setText(QLocale::system().toString(m_TagManual.m_MeasuresPerMinute.value())); } else { m_UI->leManualMeasuresPerMinute->clear(); } m_UI->pteNotes->setPlainText(m_Notes.valueOrDefault()); m_IsInternalChange = false; fillDuplicates(); selectSong(*m_Song); } DlgSongProperties::~DlgSongProperties() { Settings::saveWindowPos("DlgSongProperties", *this); } void DlgSongProperties::fillDuplicates() { int row = 0; for (const auto & song: m_Duplicates) { auto item = new QListWidgetItem(song->fileName()); item->setData(Qt::UserRole, reinterpret_cast<qulonglong>(song)); m_UI->lwDuplicates->addItem(item); row += 1; } } void DlgSongProperties::selectSong(const Song & a_Song) { // Select the song in tblDuplicates: m_IsInternalChange = true; m_Song = songPtrFromRef(a_Song); assert(m_Song != nullptr); auto numRows = m_UI->lwDuplicates->count(); for (int row = 0; row < numRows; ++row) { auto itemSong = reinterpret_cast<const Song *>(m_UI->lwDuplicates->item(row)->data(Qt::UserRole).toULongLong()); if (itemSong == &a_Song) { m_UI->lwDuplicates->setCurrentRow(row); break; } } const auto loc = QLocale::system(); m_UI->leId3Author->setText(a_Song.tagId3().m_Author.valueOrDefault()); m_UI->leId3Title->setText(a_Song.tagId3().m_Title.valueOrDefault()); m_UI->leId3Genre->setText(a_Song.tagId3().m_Genre.valueOrDefault()); if (a_Song.tagId3().m_MeasuresPerMinute.isPresent()) { m_UI->leId3MeasuresPerMinute->setText(loc.toString(a_Song.tagId3().m_MeasuresPerMinute.value())); } else { m_UI->leId3MeasuresPerMinute->clear(); } m_UI->leFilenameAuthor->setText(a_Song.tagFileName().m_Author.valueOrDefault()); m_UI->leFilenameTitle->setText(a_Song.tagFileName().m_Title.valueOrDefault()); m_UI->leFilenameGenre->setText(a_Song.tagFileName().m_Genre.valueOrDefault()); if (a_Song.tagFileName().m_MeasuresPerMinute.isPresent()) { m_UI->leFilenameMeasuresPerMinute->setText(loc.toString(a_Song.tagFileName().m_MeasuresPerMinute.value())); } else { m_UI->leFilenameMeasuresPerMinute->clear(); } m_IsInternalChange = false; } SongPtr DlgSongProperties::songPtrFromRef(const Song & a_Song) { for (const auto & song: m_Duplicates) { if (song == &a_Song) { return song->shared_from_this(); } } return nullptr; } void DlgSongProperties::applyAndClose() { m_Song->sharedData()->m_TagManual = m_TagManual; m_Song->sharedData()->m_Notes = m_Notes; m_DB.saveSongSharedData(m_Song->sharedData()); for (const auto & song: m_Duplicates) { const auto & cs = m_TagID3Changes[song]; // TODO: Apply the tag changes (#128) Q_UNUSED(cs); // m_DB.saveSong(song); } accept(); } void DlgSongProperties::authorTextEdited(const QString & a_NewText) { if (!m_IsInternalChange) { m_TagManual.m_Author = a_NewText; } } void DlgSongProperties::titleTextEdited(const QString & a_NewText) { if (!m_IsInternalChange) { m_TagManual.m_Title = a_NewText; } } void DlgSongProperties::genreSelected(const QString & a_NewGenre) { if (!m_IsInternalChange) { m_TagManual.m_Genre = a_NewGenre; } } void DlgSongProperties::measuresPerMinuteTextEdited(const QString & a_NewText) { if (m_IsInternalChange) { return; } if (a_NewText.isEmpty()) { m_UI->leManualMeasuresPerMinute->setStyleSheet(""); m_TagManual.m_MeasuresPerMinute.reset(); return; } bool isOK; auto mpm = QLocale::system().toDouble(a_NewText, &isOK); if (isOK) { m_UI->leManualMeasuresPerMinute->setStyleSheet(""); m_TagManual.m_MeasuresPerMinute = mpm; } else { m_UI->leManualMeasuresPerMinute->setStyleSheet("background-color:#fcc"); } } void DlgSongProperties::notesChanged() { m_Notes = m_UI->pteNotes->toPlainText(); } void DlgSongProperties::switchDuplicate(int a_Row) { if ((a_Row < 0) || (a_Row >= static_cast<int>(m_Duplicates.size()))) { qWarning() << "Invalid row: " << a_Row << " out of " << m_Duplicates.size(); return; } auto song = m_Duplicates[static_cast<size_t>(a_Row)]; selectSong(*song); } void DlgSongProperties::removeFromLibrary() { auto row = m_UI->lwDuplicates->currentRow(); if ((row < 0) || (row >= static_cast<int>(m_Duplicates.size()))) { qWarning() << "Invalid row: " << row; return; } auto song = m_Duplicates[static_cast<size_t>(row)]->shared_from_this(); assert(song != nullptr); // Ask for confirmation: if (QMessageBox::question( this, tr("SkauTan: Remove songs?"), tr( "Are you sure you want to remove the song %1 from the library? The song file will stay " "on the disk, but all properties set in the library will be lost.\n\n" "This operation cannot be undone!" ).arg(song->fileName()), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::No) { return; } // Remove from the DB: m_DB.removeSong(*song, false); m_Duplicates.erase(m_Duplicates.begin() + row); delete m_UI->lwDuplicates->takeItem(row); } void DlgSongProperties::deleteFromDisk() { auto row = m_UI->lwDuplicates->currentRow(); if ((row < 0) || (row >= static_cast<int>(m_Duplicates.size()))) { qWarning() << "Invalid row: " << row; return; } auto song = m_Duplicates[static_cast<size_t>(row)]->shared_from_this(); assert(song != nullptr); // Ask for confirmation: if (QMessageBox::question( this, tr("SkauTan: Remove songs?"), tr( "Are you sure you want to delete the file %1 from the disk? " "The file will be deleted and all its properties set in the library will be lost.\n\n" "This operation cannot be undone!" ).arg(song->fileName()), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::No) { return; } // Delete from the disk: m_DB.removeSong(*song, true); m_Duplicates.erase(m_Duplicates.begin() + row); delete m_UI->lwDuplicates->takeItem(row); }
25.48913
130
0.707143
addam
6e4ee48929e83cd9036ff866775394cbb8495e22
3,890
cpp
C++
src/View3d.cpp
peterlama/SMeshViewer
9982f4e79fd08190a730365a46afefa9f72298cf
[ "MIT" ]
1
2017-11-25T15:22:07.000Z
2017-11-25T15:22:07.000Z
src/View3d.cpp
peterlama/SMeshViewer
9982f4e79fd08190a730365a46afefa9f72298cf
[ "MIT" ]
null
null
null
src/View3d.cpp
peterlama/SMeshViewer
9982f4e79fd08190a730365a46afefa9f72298cf
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- //Copyright (c) 2014 Peter Lama // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. //----------------------------------------------------------------------------- #include <iostream> #include <vector> #include <algorithm> #include <QSize> #include <QElapsedTimer> #include <QFile> #include <QTextStream> #include <QtGlobal> #include <QDebug> #include <QMouseEvent> #include <glm/gtx/string_cast.hpp> #include <glm/gtc/matrix_transform.hpp> #include "View3d.h" #include "Mesh.h" #include "GroupNode.h" #include "GeometryNode.h" #include "VertexNode.h" #include "NormalNode.h" #include "IndexNode.h" #include "DrawMethodNode.h" #include "CameraNode.h" #include "LightDirectionalNode.h" View3d::View3d(const QGLFormat &format, QWidget *parent) : QGLWidget(format, parent), m_viewNav(7.0f, 0.0f, 0.0f) { //OpenGL context needs to be set up before initializing glew makeCurrent(); GLenum err = glewInit(); if (GLEW_OK != err) { std::cerr << "Error: " << glewGetErrorString(err) << std::endl; } m_sceneGraph.addDefaultCamera(); m_sceneGraph.addDefaultLights(); } View3d::~View3d() { } QSize View3d::sizeHint() const { return QSize(500, 500); } ViewNavigator* View3d::viewNav() { return &m_viewNav; } std::shared_ptr<sg::GroupNode> View3d::sceneGraphRoot() { return m_sceneGraph.root(); } void View3d::setSceneGraph(const sg::SceneGraph& sceneGraph) { m_sceneGraph = sceneGraph; m_renderer.reset(); } void View3d::initializeGL() { m_renderer.init(); m_sceneGraph.renderInit(&m_renderer); } void View3d::paintGL() { updateSceneGraph(); m_renderer.clearScreen(); m_sceneGraph.render(&m_renderer); } void View3d::resizeGL(int width, int height) { m_renderer.resizeViewport(width, height); } void View3d::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton || event->button() == Qt::RightButton) { m_viewNav.setStartPixel(event->pos().x(), event->pos().y()); } } void View3d::mouseMoveEvent(QMouseEvent* event) { if ((event->buttons() & Qt::LeftButton) && rect().contains(event->pos())) { m_viewNav.rotate(event->pos().x(), event->pos().y()); //updateSceneGraph(); updateGL(); } else if ((event->buttons() & Qt::RightButton) && rect().contains(event->pos())) { m_viewNav.pan(event->pos().x(), event->pos().y()); updateGL(); } else { event->ignore(); } } void View3d::wheelEvent(QWheelEvent *event) { if (event->orientation() == Qt::Vertical) { m_viewNav.zoom(event->delta() / -120); //updateSceneGraph(); updateGL(); } else { event->ignore(); } } void View3d::updateSceneGraph() { if (m_sceneGraph.camera() != 0) { m_sceneGraph.camera()->setOrigin(m_viewNav.origin()); m_sceneGraph.camera()->setPosition(m_viewNav.position()); m_sceneGraph.camera()->setRotation(m_viewNav.rotation()); } }
25.096774
82
0.685604
peterlama
6e54992eea4715de53e651cc99cc17caeae4c0f1
3,010
hpp
C++
SDK/PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
#pragma once // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.UserConstructionScript struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_UserConstructionScript_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeInOut__FinishedFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeInOut__FinishedFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeInOut__UpdateFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeInOut__UpdateFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeIn__FinishedFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeIn__FinishedFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeIn__UpdateFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeIn__UpdateFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeOut__FinishedFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeOut__FinishedFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeOut__UpdateFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeOut__UpdateFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.OnStartTravel struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_OnStartTravel_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.ReceiveEndPlay struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_ReceiveEndPlay_Params { TEnumAsByte<EEndPlayReason> EndPlayReason; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.ReceiveTick struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_ReceiveTick_Params { float* DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.ExecuteUbergraph_BP_TslBaseLobbySceneTravel_FadeInOut struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_ExecuteUbergraph_BP_TslBaseLobbySceneTravel_FadeInOut_Params { int* EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
37.625
152
0.772757
realrespecter
6e568aee0bafab1f4c516b59c764cf019d3c26fb
24,621
cpp
C++
src/min.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
1
2018-11-28T15:04:55.000Z
2018-11-28T15:04:55.000Z
src/min.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
null
null
null
src/min.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Aidan Thompson (SNL) improved CG and backtrack ls, added quadratic ls Sources: Numerical Recipes frprmn routine "Conjugate Gradient Method Without the Agonizing Pain" by JR Shewchuk, http://www-2.cs.cmu.edu/~jrs/jrspapers.html#cg ------------------------------------------------------------------------- */ #include <math.h> #include <stdlib.h> #include <string.h> #include "min.h" #include "atom.h" #include "atom_vec.h" #include "domain.h" #include "comm.h" #include "update.h" #include "modify.h" #include "fix_minimize.h" #include "compute.h" #include "neighbor.h" #include "force.h" #include "pair.h" #include "bond.h" #include "angle.h" #include "dihedral.h" #include "improper.h" #include "kspace.h" #include "output.h" #include "thermo.h" #include "timer.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ Min::Min(LAMMPS *lmp) : Pointers(lmp) { dmax = 0.1; searchflag = 0; linestyle = 1; elist_global = elist_atom = NULL; vlist_global = vlist_atom = NULL; nextra_global = 0; fextra = NULL; nextra_atom = 0; xextra_atom = fextra_atom = NULL; extra_peratom = extra_nlen = NULL; extra_max = NULL; requestor = NULL; external_force_clear = 0; } /* ---------------------------------------------------------------------- */ Min::~Min() { delete [] elist_global; delete [] elist_atom; delete [] vlist_global; delete [] vlist_atom; delete [] fextra; memory->sfree(xextra_atom); memory->sfree(fextra_atom); memory->destroy(extra_peratom); memory->destroy(extra_nlen); memory->destroy(extra_max); memory->sfree(requestor); } /* ---------------------------------------------------------------------- */ void Min::init() { // create fix needed for storing atom-based quantities // will delete it at end of run char **fixarg = new char*[3]; fixarg[0] = (char *) "MINIMIZE"; fixarg[1] = (char *) "all"; fixarg[2] = (char *) "MINIMIZE"; modify->add_fix(3,fixarg); delete [] fixarg; fix_minimize = (FixMinimize *) modify->fix[modify->nfix-1]; // clear out extra global and per-atom dof // will receive requests for new per-atom dof during pair init() // can then add vectors to fix_minimize in setup() nextra_global = 0; delete [] fextra; fextra = NULL; nextra_atom = 0; memory->sfree(xextra_atom); memory->sfree(fextra_atom); memory->destroy(extra_peratom); memory->destroy(extra_nlen); memory->destroy(extra_max); memory->sfree(requestor); xextra_atom = fextra_atom = NULL; extra_peratom = extra_nlen = NULL; extra_max = NULL; requestor = NULL; // virial_style: // 1 if computed explicitly by pair->compute via sum over pair interactions // 2 if computed implicitly by pair->virial_compute via sum over ghost atoms if (force->newton_pair) virial_style = 2; else virial_style = 1; // setup lists of computes for global and per-atom PE and pressure ev_setup(); // detect if fix omp is present for clearing force arrays int ifix = modify->find_fix("package_omp"); if (ifix >= 0) external_force_clear = 1; // set flags for arrays to clear in force_clear() torqueflag = extraflag = 0; if (atom->torque_flag) torqueflag = 1; if (atom->avec->forceclearflag) extraflag = 1; // allow pair and Kspace compute() to be turned off via modify flags if (force->pair && force->pair->compute_flag) pair_compute_flag = 1; else pair_compute_flag = 0; if (force->kspace && force->kspace->compute_flag) kspace_compute_flag = 1; else kspace_compute_flag = 0; // orthogonal vs triclinic simulation box triclinic = domain->triclinic; // reset reneighboring criteria if necessary neigh_every = neighbor->every; neigh_delay = neighbor->delay; neigh_dist_check = neighbor->dist_check; if (neigh_every != 1 || neigh_delay != 0 || neigh_dist_check != 1) { if (comm->me == 0) error->warning(FLERR, "Resetting reneighboring criteria during minimization"); } neighbor->every = 1; neighbor->delay = 0; neighbor->dist_check = 1; niter = neval = 0; } /* ---------------------------------------------------------------------- setup before run ------------------------------------------------------------------------- */ void Min::setup() { if (comm->me == 0 && screen) { fprintf(screen,"Setting up %s style minimization ...\n", update->minimize_style); fprintf(screen," Unit style : %s\n", update->unit_style); timer->print_timeout(screen); } update->setupflag = 1; // setup extra global dof due to fixes // cannot be done in init() b/c update init() is before modify init() nextra_global = modify->min_dof(); if (nextra_global) fextra = new double[nextra_global]; // compute for potential energy int id = modify->find_compute("thermo_pe"); if (id < 0) error->all(FLERR,"Minimization could not find thermo_pe compute"); pe_compute = modify->compute[id]; // style-specific setup does two tasks // setup extra global dof vectors // setup extra per-atom dof vectors due to requests from Pair classes // cannot be done in init() b/c update init() is before modify/pair init() setup_style(); // ndoftotal = total dof for entire minimization problem // dof for atoms, extra per-atom, extra global bigint ndofme = 3 * static_cast<bigint>(atom->nlocal); for (int m = 0; m < nextra_atom; m++) ndofme += extra_peratom[m]*atom->nlocal; MPI_Allreduce(&ndofme,&ndoftotal,1,MPI_LMP_BIGINT,MPI_SUM,world); ndoftotal += nextra_global; // setup domain, communication and neighboring // acquire ghosts // build neighbor lists atom->setup(); modify->setup_pre_exchange(); if (triclinic) domain->x2lamda(atom->nlocal); domain->pbc(); domain->reset_box(); comm->setup(); if (neighbor->style) neighbor->setup_bins(); comm->exchange(); if (atom->sortfreq > 0) atom->sort(); comm->borders(); if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost); domain->image_check(); domain->box_too_small_check(); modify->setup_pre_neighbor(); neighbor->build(); neighbor->ncalls = 0; // remove these restriction eventually if (searchflag == 0) { if (nextra_global) error->all(FLERR, "Cannot use a damped dynamics min style with fix box/relax"); if (nextra_atom) error->all(FLERR, "Cannot use a damped dynamics min style with per-atom DOF"); } if (strcmp(update->minimize_style,"hftn") == 0) { if (nextra_global) error->all(FLERR, "Cannot use hftn min style with fix box/relax"); if (nextra_atom) error->all(FLERR, "Cannot use hftn min style with per-atom DOF"); } // atoms may have migrated in comm->exchange() reset_vectors(); // compute all forces force->setup(); ev_set(update->ntimestep); force_clear(); modify->setup_pre_force(vflag); if (pair_compute_flag) force->pair->compute(eflag,vflag); else if (force->pair) force->pair->compute_dummy(eflag,vflag); if (atom->molecular) { if (force->bond) force->bond->compute(eflag,vflag); if (force->angle) force->angle->compute(eflag,vflag); if (force->dihedral) force->dihedral->compute(eflag,vflag); if (force->improper) force->improper->compute(eflag,vflag); } if (force->kspace) { force->kspace->setup(); if (kspace_compute_flag) force->kspace->compute(eflag,vflag); else force->kspace->compute_dummy(eflag,vflag); } modify->pre_reverse(eflag,vflag); if (force->newton) comm->reverse_comm(); // update per-atom minimization variables stored by pair styles if (nextra_atom) for (int m = 0; m < nextra_atom; m++) requestor[m]->min_xf_get(m); modify->setup(vflag); output->setup(); update->setupflag = 0; // stats for initial thermo output ecurrent = pe_compute->compute_scalar(); if (nextra_global) ecurrent += modify->min_energy(fextra); if (output->thermo->normflag) ecurrent /= atom->natoms; einitial = ecurrent; fnorm2_init = sqrt(fnorm_sqr()); fnorminf_init = fnorm_inf(); } /* ---------------------------------------------------------------------- setup without output or one-time post-init setup flag = 0 = just force calculation flag = 1 = reneighbor and force calculation ------------------------------------------------------------------------- */ void Min::setup_minimal(int flag) { update->setupflag = 1; // setup domain, communication and neighboring // acquire ghosts // build neighbor lists if (flag) { modify->setup_pre_exchange(); if (triclinic) domain->x2lamda(atom->nlocal); domain->pbc(); domain->reset_box(); comm->setup(); if (neighbor->style) neighbor->setup_bins(); comm->exchange(); comm->borders(); if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost); domain->image_check(); domain->box_too_small_check(); modify->setup_pre_neighbor(); neighbor->build(); neighbor->ncalls = 0; } // atoms may have migrated in comm->exchange() reset_vectors(); // compute all forces ev_set(update->ntimestep); force_clear(); modify->setup_pre_force(vflag); if (pair_compute_flag) force->pair->compute(eflag,vflag); else if (force->pair) force->pair->compute_dummy(eflag,vflag); if (atom->molecular) { if (force->bond) force->bond->compute(eflag,vflag); if (force->angle) force->angle->compute(eflag,vflag); if (force->dihedral) force->dihedral->compute(eflag,vflag); if (force->improper) force->improper->compute(eflag,vflag); } if (force->kspace) { force->kspace->setup(); if (kspace_compute_flag) force->kspace->compute(eflag,vflag); else force->kspace->compute_dummy(eflag,vflag); } modify->pre_reverse(eflag,vflag); if (force->newton) comm->reverse_comm(); // update per-atom minimization variables stored by pair styles if (nextra_atom) for (int m = 0; m < nextra_atom; m++) requestor[m]->min_xf_get(m); modify->setup(vflag); update->setupflag = 0; // stats for Finish to print ecurrent = pe_compute->compute_scalar(); if (nextra_global) ecurrent += modify->min_energy(fextra); if (output->thermo->normflag) ecurrent /= atom->natoms; einitial = ecurrent; fnorm2_init = sqrt(fnorm_sqr()); fnorminf_init = fnorm_inf(); } /* ---------------------------------------------------------------------- perform minimization, calling iterate() for N steps ------------------------------------------------------------------------- */ void Min::run(int n) { // minimizer iterations stop_condition = iterate(n); stopstr = stopstrings(stop_condition); // if early exit from iterate loop: // set update->nsteps to niter for Finish stats to print // set output->next values to this timestep // call energy_force() to insure vflag is set when forces computed // output->write does final output for thermo, dump, restart files // add ntimestep to all computes that store invocation times // since are hardwiring call to thermo/dumps and computes may not be ready if (stop_condition != MAXITER) { update->nsteps = niter; if (update->restrict_output == 0) { for (int idump = 0; idump < output->ndump; idump++) output->next_dump[idump] = update->ntimestep; output->next_dump_any = update->ntimestep; if (output->restart_flag) { output->next_restart = update->ntimestep; if (output->restart_every_single) output->next_restart_single = update->ntimestep; if (output->restart_every_double) output->next_restart_double = update->ntimestep; } } output->next_thermo = update->ntimestep; modify->addstep_compute_all(update->ntimestep); ecurrent = energy_force(0); output->write(update->ntimestep); } } /* ---------------------------------------------------------------------- */ void Min::cleanup() { modify->post_run(); // stats for Finish to print efinal = ecurrent; fnorm2_final = sqrt(fnorm_sqr()); fnorminf_final = fnorm_inf(); // reset reneighboring criteria neighbor->every = neigh_every; neighbor->delay = neigh_delay; neighbor->dist_check = neigh_dist_check; // delete fix at end of run, so its atom arrays won't persist modify->delete_fix("MINIMIZE"); domain->box_too_small_check(); } /* ---------------------------------------------------------------------- evaluate potential energy and forces may migrate atoms due to reneighboring return new energy, which should include nextra_global dof return negative gradient stored in atom->f return negative gradient for nextra_global dof in fextra ------------------------------------------------------------------------- */ double Min::energy_force(int resetflag) { // check for reneighboring // always communicate since minimizer moved atoms int nflag = neighbor->decide(); if (nflag == 0) { timer->stamp(); comm->forward_comm(); timer->stamp(Timer::COMM); } else { if (modify->n_min_pre_exchange) { timer->stamp(); modify->min_pre_exchange(); timer->stamp(Timer::MODIFY); } if (triclinic) domain->x2lamda(atom->nlocal); domain->pbc(); if (domain->box_change) { domain->reset_box(); comm->setup(); if (neighbor->style) neighbor->setup_bins(); } timer->stamp(); comm->exchange(); if (atom->sortfreq > 0 && update->ntimestep >= atom->nextsort) atom->sort(); comm->borders(); if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost); timer->stamp(Timer::COMM); neighbor->build(); timer->stamp(Timer::NEIGH); } ev_set(update->ntimestep); force_clear(); timer->stamp(); if (modify->n_min_pre_force) { modify->min_pre_force(vflag); timer->stamp(Timer::MODIFY); } if (pair_compute_flag) { force->pair->compute(eflag,vflag); timer->stamp(Timer::PAIR); } if (atom->molecular) { if (force->bond) force->bond->compute(eflag,vflag); if (force->angle) force->angle->compute(eflag,vflag); if (force->dihedral) force->dihedral->compute(eflag,vflag); if (force->improper) force->improper->compute(eflag,vflag); timer->stamp(Timer::BOND); } if (kspace_compute_flag) { force->kspace->compute(eflag,vflag); timer->stamp(Timer::KSPACE); } if (modify->n_pre_reverse) { modify->pre_reverse(eflag,vflag); timer->stamp(Timer::MODIFY); } if (force->newton) { comm->reverse_comm(); timer->stamp(Timer::COMM); } // update per-atom minimization variables stored by pair styles if (nextra_atom) for (int m = 0; m < nextra_atom; m++) requestor[m]->min_xf_get(m); // fixes that affect minimization if (modify->n_min_post_force) { timer->stamp(); modify->min_post_force(vflag); timer->stamp(Timer::MODIFY); } // compute potential energy of system // normalize if thermo PE does double energy = pe_compute->compute_scalar(); if (nextra_global) energy += modify->min_energy(fextra); if (output->thermo->normflag) energy /= atom->natoms; // if reneighbored, atoms migrated // if resetflag = 1, update x0 of atoms crossing PBC // reset vectors used by lo-level minimizer if (nflag) { if (resetflag) fix_minimize->reset_coords(); reset_vectors(); } return energy; } /* ---------------------------------------------------------------------- clear force on own & ghost atoms clear other arrays as needed ------------------------------------------------------------------------- */ void Min::force_clear() { if (external_force_clear) return; // clear global force array // if either newton flag is set, also include ghosts size_t nbytes = sizeof(double) * atom->nlocal; if (force->newton) nbytes += sizeof(double) * atom->nghost; if (nbytes) { memset(&atom->f[0][0],0,3*nbytes); if (torqueflag) memset(&atom->torque[0][0],0,3*nbytes); if (extraflag) atom->avec->force_clear(0,nbytes); } } /* ---------------------------------------------------------------------- pair style makes request to add a per-atom variables to minimization requestor stores callback to pair class to invoke during min to get current variable and forces on it and to update the variable return flag that pair can use if it registers multiple variables ------------------------------------------------------------------------- */ int Min::request(Pair *pair, int peratom, double maxvalue) { int n = nextra_atom + 1; xextra_atom = (double **) memory->srealloc(xextra_atom,n*sizeof(double *), "min:xextra_atom"); fextra_atom = (double **) memory->srealloc(fextra_atom,n*sizeof(double *), "min:fextra_atom"); memory->grow(extra_peratom,n,"min:extra_peratom"); memory->grow(extra_nlen,n,"min:extra_nlen"); memory->grow(extra_max,n,"min:extra_max"); requestor = (Pair **) memory->srealloc(requestor,n*sizeof(Pair *), "min:requestor"); requestor[nextra_atom] = pair; extra_peratom[nextra_atom] = peratom; extra_max[nextra_atom] = maxvalue; nextra_atom++; return nextra_atom-1; } /* ---------------------------------------------------------------------- */ void Min::modify_params(int narg, char **arg) { if (narg == 0) error->all(FLERR,"Illegal min_modify command"); int iarg = 0; while (iarg < narg) { if (strcmp(arg[iarg],"dmax") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal min_modify command"); dmax = force->numeric(FLERR,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"line") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal min_modify command"); if (strcmp(arg[iarg+1],"backtrack") == 0) linestyle = 0; else if (strcmp(arg[iarg+1],"quadratic") == 0) linestyle = 1; else if (strcmp(arg[iarg+1],"forcezero") == 0) linestyle = 2; else error->all(FLERR,"Illegal min_modify command"); iarg += 2; } else error->all(FLERR,"Illegal min_modify command"); } } /* ---------------------------------------------------------------------- setup lists of computes for global and per-atom PE and pressure ------------------------------------------------------------------------- */ void Min::ev_setup() { delete [] elist_global; delete [] elist_atom; delete [] vlist_global; delete [] vlist_atom; elist_global = elist_atom = NULL; vlist_global = vlist_atom = NULL; nelist_global = nelist_atom = 0; nvlist_global = nvlist_atom = 0; for (int i = 0; i < modify->ncompute; i++) { if (modify->compute[i]->peflag) nelist_global++; if (modify->compute[i]->peatomflag) nelist_atom++; if (modify->compute[i]->pressflag) nvlist_global++; if (modify->compute[i]->pressatomflag) nvlist_atom++; } if (nelist_global) elist_global = new Compute*[nelist_global]; if (nelist_atom) elist_atom = new Compute*[nelist_atom]; if (nvlist_global) vlist_global = new Compute*[nvlist_global]; if (nvlist_atom) vlist_atom = new Compute*[nvlist_atom]; nelist_global = nelist_atom = 0; nvlist_global = nvlist_atom = 0; for (int i = 0; i < modify->ncompute; i++) { if (modify->compute[i]->peflag) elist_global[nelist_global++] = modify->compute[i]; if (modify->compute[i]->peatomflag) elist_atom[nelist_atom++] = modify->compute[i]; if (modify->compute[i]->pressflag) vlist_global[nvlist_global++] = modify->compute[i]; if (modify->compute[i]->pressatomflag) vlist_atom[nvlist_atom++] = modify->compute[i]; } } /* ---------------------------------------------------------------------- set eflag,vflag for current iteration invoke matchstep() on all timestep-dependent computes to clear their arrays eflag/vflag based on computes that need info on this ntimestep always set eflag_global = 1, since need energy every iteration eflag = 0 = no energy computation eflag = 1 = global energy only eflag = 2 = per-atom energy only eflag = 3 = both global and per-atom energy vflag = 0 = no virial computation (pressure) vflag = 1 = global virial with pair portion via sum of pairwise interactions vflag = 2 = global virial with pair portion via F dot r including ghosts vflag = 4 = per-atom virial only vflag = 5 or 6 = both global and per-atom virial ------------------------------------------------------------------------- */ void Min::ev_set(bigint ntimestep) { int i,flag; int eflag_global = 1; for (i = 0; i < nelist_global; i++) elist_global[i]->matchstep(ntimestep); flag = 0; int eflag_atom = 0; for (i = 0; i < nelist_atom; i++) if (elist_atom[i]->matchstep(ntimestep)) flag = 1; if (flag) eflag_atom = 2; if (eflag_global) update->eflag_global = update->ntimestep; if (eflag_atom) update->eflag_atom = update->ntimestep; eflag = eflag_global + eflag_atom; flag = 0; int vflag_global = 0; for (i = 0; i < nvlist_global; i++) if (vlist_global[i]->matchstep(ntimestep)) flag = 1; if (flag) vflag_global = virial_style; flag = 0; int vflag_atom = 0; for (i = 0; i < nvlist_atom; i++) if (vlist_atom[i]->matchstep(ntimestep)) flag = 1; if (flag) vflag_atom = 4; if (vflag_global) update->vflag_global = update->ntimestep; if (vflag_atom) update->vflag_atom = update->ntimestep; vflag = vflag_global + vflag_atom; } /* ---------------------------------------------------------------------- compute and return ||force||_2^2 ------------------------------------------------------------------------- */ double Min::fnorm_sqr() { int i,n; double *fatom; double local_norm2_sqr = 0.0; for (i = 0; i < nvec; i++) local_norm2_sqr += fvec[i]*fvec[i]; if (nextra_atom) { for (int m = 0; m < nextra_atom; m++) { fatom = fextra_atom[m]; n = extra_nlen[m]; for (i = 0; i < n; i++) local_norm2_sqr += fatom[i]*fatom[i]; } } double norm2_sqr = 0.0; MPI_Allreduce(&local_norm2_sqr,&norm2_sqr,1,MPI_DOUBLE,MPI_SUM,world); if (nextra_global) for (i = 0; i < nextra_global; i++) norm2_sqr += fextra[i]*fextra[i]; return norm2_sqr; } /* ---------------------------------------------------------------------- compute and return ||force||_inf ------------------------------------------------------------------------- */ double Min::fnorm_inf() { int i,n; double *fatom; double local_norm_inf = 0.0; for (i = 0; i < nvec; i++) local_norm_inf = MAX(fabs(fvec[i]),local_norm_inf); if (nextra_atom) { for (int m = 0; m < nextra_atom; m++) { fatom = fextra_atom[m]; n = extra_nlen[m]; for (i = 0; i < n; i++) local_norm_inf = MAX(fabs(fatom[i]),local_norm_inf); } } double norm_inf = 0.0; MPI_Allreduce(&local_norm_inf,&norm_inf,1,MPI_DOUBLE,MPI_MAX,world); if (nextra_global) for (i = 0; i < nextra_global; i++) norm_inf = MAX(fabs(fextra[i]),norm_inf); return norm_inf; } /* ---------------------------------------------------------------------- possible stop conditions ------------------------------------------------------------------------- */ char *Min::stopstrings(int n) { const char *strings[] = {"max iterations", "max force evaluations", "energy tolerance", "force tolerance", "search direction is not downhill", "linesearch alpha is zero", "forces are zero", "quadratic factors are zero", "trust region too small", "HFTN minimizer error", "walltime limit reached"}; return (char *) strings[n]; }
30.209816
80
0.596401
luwei0917
6e5d0a1f79c6f9d2b44e14eea33ddc2f6dfa59cd
258
hpp
C++
src/OCGL_Buffer.hpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/OCGL_Buffer.hpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/OCGL_Buffer.hpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
#pragma once #include <NTL.hpp> #include <glad/glad.h> class OCGL_Buffer { public: OCGL_Buffer(size_t size); OCGL_Buffer(OCGL_Buffer const &deviceBuffer); OCGL_Buffer &operator=(OCGL_Buffer const &deviceBuffer); GLuint vbo; cl::Memory mem; };
17.2
60
0.728682
Jino42
6e6321da04804ffe3b088f4c0bec09eff53a567b
8,430
cpp
C++
src/sdk/hl2_csgo/game/missionchooser/vgui/RoomTemplateListPanel.cpp
newcommerdontblame/ionlib
47ca829009e1529f62b2134aa6c0df8673864cf3
[ "MIT" ]
51
2016-03-18T01:48:07.000Z
2022-03-21T20:02:02.000Z
src/game/missionchooser/vgui/RoomTemplateListPanel.cpp
senny970/AlienSwarm
c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84
[ "Unlicense" ]
null
null
null
src/game/missionchooser/vgui/RoomTemplateListPanel.cpp
senny970/AlienSwarm
c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84
[ "Unlicense" ]
26
2016-03-17T21:20:37.000Z
2022-03-24T10:21:30.000Z
#include <vgui/IVGui.h> #include <vgui/IInput.h> #include "vgui_controls/Controls.h" #include <vgui/IScheme.h> #include <vgui_controls/ImagePanel.h> #include <vgui_controls/Button.h> #include <KeyValues.h> #include "TileGenDialog.h" #include "RoomTemplateListPanel.h" #include "RoomTemplatePanel.h" #include "TileSource/RoomTemplate.h" #include "TileSource/LevelTheme.h" #include "vgui/missionchooser_tgaimagepanel.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui; CRoomTemplateListPanel::CRoomTemplateListPanel( Panel *parent, const char *name ) : BaseClass( parent, name ), m_RoomTemplateFolders( 0, 20 ) { KeyValues *pMessageKV; m_FilterText[0] = '\0'; m_pRefreshList = new Button( this, "RefreshListButton", "Refresh List", this, "RefreshList" ); pMessageKV = new KeyValues( "RefreshList" ); m_pRefreshList->SetCommand( pMessageKV ); m_pExpandAll = new Button( this, "ExpandAllButton", "Expand All", this, "ExpandAllFolders" ); pMessageKV = new KeyValues( "ExpandAllFolders" ); m_pExpandAll->SetCommand( pMessageKV ); m_pCollapseAll = new Button( this, "CollapseAllButton", "Collapse All", this, "CollapseAllFolders" ); pMessageKV = new KeyValues( "CollapseAllFolders" ); m_pCollapseAll->SetCommand( pMessageKV ); } CRoomTemplateListPanel::~CRoomTemplateListPanel( void ) { } void CRoomTemplateListPanel::PerformLayout() { // Set width to match parent panel SetWide( GetParent()->GetWide() ); int padding = 8; int cur_x = padding; int cur_y = padding; int nPanelWidth = GetWide(); int tallest_on_this_row = 0; // Place the refresh and expand/collapse buttons int nButtonWidth = nPanelWidth - 2 * padding; m_pRefreshList->SetBounds( padding, cur_y, nButtonWidth, 24 ); cur_y += 24 + padding; nButtonWidth = ( nPanelWidth - 3 * padding ) / 2; nButtonWidth = MAX( nButtonWidth, 40 ); m_pExpandAll->SetBounds( padding, cur_y, nButtonWidth, 24 ); m_pCollapseAll->SetBounds( 2 * padding + nButtonWidth, cur_y, nButtonWidth, 24 ); cur_y += 24 + padding; // Place buttons and images for each folder of room templates for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].SetButtonText(); m_RoomTemplateFolders[i].m_pFolderButton->SetBounds(padding, cur_y, GetWide() - padding * 2, 24); cur_y += 24; // Add every room template in this category for ( int j = 0; j < m_Thumbnails.Count(); ++ j ) { if ( Q_stricmp( m_Thumbnails[j]->m_pRoomTemplate->GetFolderName(), m_RoomTemplateFolders[i].m_FolderName ) != 0 ) continue; if ( m_RoomTemplateFolders[i].m_bExpanded && FilterTemplate( m_Thumbnails[j]->m_pRoomTemplate ) ) { m_Thumbnails[j]->SetVisible( true ); // make sure the template has sized itself m_Thumbnails[j]->InvalidateLayout( true ); int tw = m_Thumbnails[j]->GetWide(); int tt = m_Thumbnails[j]->GetTall(); // if the panel is too wide to fit, then move down a row if (cur_x + tw > nPanelWidth) { cur_x = padding; cur_y += tallest_on_this_row + padding; tallest_on_this_row = 0; } m_Thumbnails[j]->SetPos(cur_x, cur_y); if (tt > tallest_on_this_row) tallest_on_this_row = tt; cur_x += tw + padding; } else { m_Thumbnails[j]->SetVisible( false ); } } cur_y += tallest_on_this_row + padding; tallest_on_this_row = 0; cur_x = padding; } SetTall( cur_y ); } void CRoomTemplateListPanel::UpdatePanelsWithTemplate( const CRoomTemplate* pTemplate ) { int thumbs = m_Thumbnails.Count(); for (int i=0;i<thumbs;i++) { CRoomTemplatePanel* pPanel = m_Thumbnails[i]; if (!pPanel) continue; if (pPanel->m_pRoomTemplate == pTemplate) pPanel->UpdateImages(); } } void CRoomTemplateListPanel::UpdateRoomList() { // clear out the list for ( int i = 0; i < m_Thumbnails.Count(); ++ i ) { m_Thumbnails[i]->MarkForDeletion(); } m_Thumbnails.RemoveAll(); // Try to re-use folder buttons and preserve their state when possible. // Mark all folder buttons invisible to begin with. If they are needed, they will be // made visible again; otherwise, we can cull them. for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].m_pFolderButton->SetVisible( false ); } // Add every room template for the currently selected theme CLevelTheme *pCurrentTheme = CLevelTheme::s_pCurrentTheme; if ( pCurrentTheme == NULL ) return; for (int i = 0; i < pCurrentTheme->m_RoomTemplates.Count(); ++ i ) { CRoomTemplatePanel *pPanel = new CRoomTemplatePanel( this, "RoomTemplatePanel" ); pPanel->m_bRoomTemplateBrowserMode = true; pPanel->SetRoomTemplate( pCurrentTheme->m_RoomTemplates[i] ); m_Thumbnails.AddToTail( pPanel ); AddFolder( pCurrentTheme->m_RoomTemplates[i]->GetFolderName() ); } // Remove unused folder buttons for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { if ( !m_RoomTemplateFolders[i].m_pFolderButton->IsVisible() ) { m_RoomTemplateFolders[i].m_pFolderButton->MarkForDeletion(); m_RoomTemplateFolders.FastRemove( i ); // go back 1 since we just deleted an entry -- i; } } // Sort alphabetically m_RoomTemplateFolders.Sort( CompareFolders ); InvalidateLayout(); } void CRoomTemplateListPanel::OnRefreshList() { CLevelTheme *pCurrentTheme = CLevelTheme::s_pCurrentTheme; if ( pCurrentTheme == NULL ) return; CMissionChooserTGAImagePanel::ClearImageCache(); pCurrentTheme->LoadRoomTemplates(); UpdateRoomList(); } void CRoomTemplateListPanel::OnExpandAll() { for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].m_bExpanded = true; } InvalidateLayout(); } void CRoomTemplateListPanel::OnCollapseAll() { for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].m_bExpanded = false; } InvalidateLayout(); } void CRoomTemplateListPanel::OnToggleFolder( KeyValues *pKV ) { const char *pFolderName = pKV->GetString( "folder", NULL ); Assert( pFolderName != NULL); for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { if ( Q_stricmp( pFolderName, m_RoomTemplateFolders[i].m_FolderName ) == 0 ) { m_RoomTemplateFolders[i].m_bExpanded = !m_RoomTemplateFolders[i].m_bExpanded; InvalidateLayout(); return; } } } void CRoomTemplateListPanel::SetFilterText( const char *pText ) { Q_strncpy( m_FilterText, pText, m_nFilterTextLength ); } void CRoomTemplateListPanel::AddFolder( const char *pFolderName ) { int nNumFolders = m_RoomTemplateFolders.Count(); for ( int i = 0; i < nNumFolders; ++ i ) { if ( Q_stricmp( pFolderName, m_RoomTemplateFolders[i].m_FolderName ) == 0 ) { // Mark this folder as being used m_RoomTemplateFolders[i].m_pFolderButton->SetVisible( true ); return; } } // New folder, create a new entry m_RoomTemplateFolders.AddToTail(); Q_strncpy( m_RoomTemplateFolders[nNumFolders].m_FolderName, pFolderName, MAX_PATH ); m_RoomTemplateFolders[nNumFolders].m_bExpanded = true; m_RoomTemplateFolders[nNumFolders].m_pFolderButton = new Button( this, "FolderButton", "", this, "ToggleFolder" ); KeyValues *pMessageKV = new KeyValues( "ToggleFolder" ); KeyValues *pIndexKV = new KeyValues( "folder" ); pIndexKV->SetString( NULL, m_RoomTemplateFolders[nNumFolders].m_FolderName ); pMessageKV->AddSubKey( pIndexKV ); m_RoomTemplateFolders[nNumFolders].m_pFolderButton->SetCommand( pMessageKV ); } bool CRoomTemplateListPanel::FilterTemplate( const CRoomTemplate *pTemplate ) { bool bInvert = false; const char *pFilterText = m_FilterText; // If the user types in a "!" as the first character, invert the search results. if ( pFilterText[0] == '!' ) { bInvert = true; ++ pFilterText; } if ( pFilterText[0] == '\0' ) { return true; } else { if ( Q_stristr( pTemplate->GetDescription(), pFilterText ) != NULL ) { return !bInvert; } if ( Q_stristr( pTemplate->GetFullName(), pFilterText ) != NULL ) { return !bInvert; } int nNumTags = pTemplate->GetNumTags(); for ( int i = 0; i < nNumTags; ++ i ) { if ( Q_stristr( pTemplate->GetTag( i ), pFilterText ) != NULL ) { return !bInvert; } } } return bInvert; } void CRoomTemplateListPanel::RoomTemplateFolder_t::SetButtonText() { char buttonLabel[MAX_PATH + 5]; Q_snprintf( buttonLabel, MAX_PATH + 5, "%s %s", m_bExpanded ? "-" : "+", m_FolderName ); m_pFolderButton->SetText( buttonLabel ); }
28.19398
116
0.707355
newcommerdontblame
6e63b080e85c394eb82f84648a99299f50bb4233
14,241
cc
C++
3rdParty/s2geometry/552f562/src/s2/util/coding/varint.cc
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
[ "Apache-2.0" ]
1
2019-08-11T04:06:49.000Z
2019-08-11T04:06:49.000Z
3rdParty/s2geometry/552f562/src/s2/util/coding/varint.cc
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
[ "Apache-2.0" ]
null
null
null
3rdParty/s2geometry/552f562/src/s2/util/coding/varint.cc
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
[ "Apache-2.0" ]
1
2018-11-04T01:30:53.000Z
2018-11-04T01:30:53.000Z
// Copyright 2001 Google 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. // #include "s2/util/coding/varint.h" #include <string> #include "s2/third_party/absl/base/integral_types.h" #ifndef _MSC_VER const int Varint::kMax32; const int Varint::kMax64; const int Varint::kSlopBytes; #endif char* Varint::Encode32(char* sptr, uint32 v) { return Encode32Inline(sptr, v); } char* Varint::Encode64(char* sptr, uint64 v) { if (v < (1u << 28)) { return Varint::Encode32(sptr, v); } else { // Operate on characters as unsigneds unsigned char* ptr = reinterpret_cast<unsigned char*>(sptr); // Rather than computing four subresults and or'ing each with 0x80, // we can do two ors now. (Doing one now wouldn't work.) const uint32 x32 = v | (1 << 7) | (1 << 21); const uint32 y32 = v | (1 << 14) | (1 << 28); *(ptr++) = x32; *(ptr++) = y32 >> 7; *(ptr++) = x32 >> 14; *(ptr++) = y32 >> 21; if (v < (1ull << 35)) { *(ptr++) = v >> 28; return reinterpret_cast<char*>(ptr); } else { *(ptr++) = (v >> 28) | (1 << 7); return Varint::Encode32(reinterpret_cast<char*>(ptr), v >> 35); } } } const char* Varint::Parse32Fallback(const char* ptr, uint32* OUTPUT) { return Parse32FallbackInline(ptr, OUTPUT); } const char* Varint::Parse64Fallback(const char* p, uint64* OUTPUT) { const unsigned char* ptr = reinterpret_cast<const unsigned char*>(p); assert(*ptr >= 128); #if defined(__x86_64__) // This approach saves one redundant operation on the last byte (masking a // byte that doesn't need it). This is conditional on x86 because: // - PowerPC has specialized bit instructions that make masking and // shifting very efficient // - x86 seems to be one of the few architectures that has a single // instruction to add 3 values. // // e.g. // Input: 0xff, 0x40 // Mask & Or calculates: (0xff & 0x7f) | ((0x40 & 0x7f) << 7) = 0x207f // Sub1 & Add calculates: 0xff + ((0x40 - 1) << 7) = 0x207f // // The subtract one removes the bit set by the previous byte used to // indicate that more bytes are present. It also has the potential to // allow instructions like LEA to combine 2 adds into one instruction. // // E.g. on an x86 architecture, %rcx = %rax + (%rbx - 1) << 7 could be // emitted as: // shlq $7, %rbx // leaq -0x80(%rax, %rbx), %rcx // // Fast path: need to accumulate data in upto three result fragments // res1 bits 0..27 // res2 bits 28..55 // res3 bits 56..63 uint64 byte, res1, res2 = 0, res3 = 0; byte = *(ptr++); res1 = byte; byte = *(ptr++); res1 += (byte - 1) << 7; if (byte < 128) goto done1; byte = *(ptr++); res1 += (byte - 1) << 14; if (byte < 128) goto done1; byte = *(ptr++); res1 += (byte - 1) << 21; if (byte < 128) goto done1; byte = *(ptr++); res2 = byte; if (byte < 128) goto done2; byte = *(ptr++); res2 += (byte - 1) << 7; if (byte < 128) goto done2; byte = *(ptr++); res2 += (byte - 1) << 14; if (byte < 128) goto done2; byte = *(ptr++); res2 += (byte - 1) << 21; if (byte < 128) goto done2; byte = *(ptr++); res3 = byte; if (byte < 128) goto done3; byte = *(ptr++); res3 += (byte - 1) << 7; if (byte < 2) goto done3; return nullptr; // Value is too long to be a varint64 done1: assert(res2 == 0); assert(res3 == 0); *OUTPUT = res1; return reinterpret_cast<const char*>(ptr); done2: assert(res3 == 0); *OUTPUT = res1 + ((res2 - 1) << 28); return reinterpret_cast<const char*>(ptr); done3: *OUTPUT = res1 + ((res2 - 1) << 28) + ((res3 - 1) << 56); return reinterpret_cast<const char*>(ptr); #else uint32 byte, res1, res2=0, res3=0; byte = *(ptr++); res1 = byte & 127; byte = *(ptr++); res1 |= (byte & 127) << 7; if (byte < 128) goto done1; byte = *(ptr++); res1 |= (byte & 127) << 14; if (byte < 128) goto done1; byte = *(ptr++); res1 |= (byte & 127) << 21; if (byte < 128) goto done1; byte = *(ptr++); res2 = byte & 127; if (byte < 128) goto done2; byte = *(ptr++); res2 |= (byte & 127) << 7; if (byte < 128) goto done2; byte = *(ptr++); res2 |= (byte & 127) << 14; if (byte < 128) goto done2; byte = *(ptr++); res2 |= (byte & 127) << 21; if (byte < 128) goto done2; byte = *(ptr++); res3 = byte & 127; if (byte < 128) goto done3; byte = *(ptr++); res3 |= (byte & 127) << 7; if (byte < 2) goto done3; return nullptr; // Value is too long to be a varint64 done1: assert(res2 == 0); assert(res3 == 0); *OUTPUT = res1; return reinterpret_cast<const char*>(ptr); done2: assert(res3 == 0); *OUTPUT = res1 | (uint64(res2) << 28); return reinterpret_cast<const char*>(ptr); done3: *OUTPUT = res1 | (uint64(res2) << 28) | (uint64(res3) << 56); return reinterpret_cast<const char*>(ptr); #endif } const char* Varint::Parse32BackwardSlow(const char* ptr, const char* base, uint32* OUTPUT) { // Since this method is rarely called, for simplicity, we just skip backward // and then parse forward. const char* prev = Skip32BackwardSlow(ptr, base); if (prev == nullptr) return nullptr; // no value before 'ptr' Parse32(prev, OUTPUT); return prev; } const char* Varint::Parse64BackwardSlow(const char* ptr, const char* base, uint64* OUTPUT) { // Since this method is rarely called, for simplicity, we just skip backward // and then parse forward. const char* prev = Skip64BackwardSlow(ptr, base); if (prev == nullptr) return nullptr; // no value before 'ptr' Parse64(prev, OUTPUT); return prev; } const char* Varint::Parse64WithLimit(const char* p, const char* l, uint64* OUTPUT) { if (p + kMax64 <= l) { return Parse64(p, OUTPUT); } else { // See detailed comment in Varint::Parse64Fallback about this general // approach. const unsigned char* ptr = reinterpret_cast<const unsigned char*>(p); const unsigned char* limit = reinterpret_cast<const unsigned char*>(l); uint64 b, result; #if defined(__x86_64__) if (ptr >= limit) return nullptr; b = *(ptr++); result = b; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 7; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 14; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 21; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 28; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 35; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 42; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 49; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 56; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result += (b - 1) << 63; if (b < 2) goto done; return nullptr; // Value is too long to be a varint64 #else if (ptr >= limit) return nullptr; b = *(ptr++); result = b & 127; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 7; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 14; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 21; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 28; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 35; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 42; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 49; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 56; if (b < 128) goto done; if (ptr >= limit) return nullptr; b = *(ptr++); result |= (b & 127) << 63; if (b < 2) goto done; return nullptr; // Value is too long to be a varint64 #endif done: *OUTPUT = result; return reinterpret_cast<const char*>(ptr); } } const char* Varint::Skip32BackwardSlow(const char* p, const char* b) { const unsigned char* ptr = reinterpret_cast<const unsigned char*>(p); const unsigned char* base = reinterpret_cast<const unsigned char*>(b); assert(ptr >= base); // If the initial pointer is at the base or if the previous byte is not // the last byte of a varint, we return nullptr since there is nothing to // skip. if (ptr == base) return nullptr; if (*(--ptr) > 127) return nullptr; for (int i = 0; i < 5; i++) { if (ptr == base) return reinterpret_cast<const char*>(ptr); if (*(--ptr) < 128) return reinterpret_cast<const char*>(ptr + 1); } return nullptr; // value is too long to be a varint32 } const char* Varint::Skip64BackwardSlow(const char* p, const char* b) { const unsigned char* ptr = reinterpret_cast<const unsigned char*>(p); const unsigned char* base = reinterpret_cast<const unsigned char*>(b); assert(ptr >= base); // If the initial pointer is at the base or if the previous byte is not // the last byte of a varint, we return nullptr since there is nothing to // skip. if (ptr == base) return nullptr; if (*(--ptr) > 127) return nullptr; for (int i = 0; i < 10; i++) { if (ptr == base) return reinterpret_cast<const char*>(ptr); if (*(--ptr) < 128) return reinterpret_cast<const char*>(ptr + 1); } return nullptr; // value is too long to be a varint64 } void Varint::Append32Slow(string* s, uint32 value) { const size_t start = s->size(); s->resize(start + Varint::Length32(value)); Varint::Encode32(&((*s)[start]), value); } void Varint::Append64Slow(string* s, uint64 value) { const size_t start = s->size(); s->resize(start + Varint::Length64(value)); Varint::Encode64(&((*s)[start]), value); } void Varint::EncodeTwo32Values(string* s, uint32 a, uint32 b) { uint64 v = 0; int shift = 0; while ((a > 0) || (b > 0)) { uint8 one_byte = (a & 0xf) | ((b & 0xf) << 4); v |= ((static_cast<uint64>(one_byte)) << shift); shift += 8; a >>= 4; b >>= 4; } Append64(s, v); } namespace { // Skip the least signficant "offset" bits and extract the next "bits" bits. uint32 GetBits(uint32 byte, uint32 offset, uint32 bits) { return (byte >> offset) & ((1u << bits) - 1); } template <bool RespectLimit> const char* DecodeTwo32ValuesInternal(const char* ptr, const char* limit, uint32* a, uint32* b) { const uint8* uptr = reinterpret_cast<const uint8*>(ptr); const uint8* ulimit = reinterpret_cast<const uint8*>(limit); // Assert that an optimized path is used in DecodeTwo32Values before // DecodeTwo32ValuesSlow is invoked. This optimization does not exist for // DecodeTwo32ValuesWithLimit (the same way Parse64WithLimit does not have // this optimization). if (!RespectLimit) { assert(*uptr >= 128); } // Extract portions of bits for *a and *b from a byte that is formatted // as follows (least significant bits first): // shift bits for b // 4 bits for a // 3-shift bits for b // varint termination bit #define PARSE_BITS_DECODE_TWO(shift, a, a_shift, b, b_shift) \ if (RespectLimit && uptr >= ulimit) return nullptr; \ byte = *(uptr++); \ b |= GetBits(byte, 0, shift) << b_shift; \ a |= GetBits(byte, shift, 4) << a_shift; \ b |= GetBits(byte, shift + 4, 3 - shift) << (b_shift + shift); \ if (byte < 128) goto done; \ a_shift += 4; \ b_shift += 3; uint32 res1 = 0, res2 = 0, shift1 = 0, shift2 = 0, byte; // First four bytes contain four consecutive bits of res1 each. PARSE_BITS_DECODE_TWO(0, res1, shift1, res2, shift2); PARSE_BITS_DECODE_TWO(1, res1, shift1, res2, shift2); PARSE_BITS_DECODE_TWO(2, res1, shift1, res2, shift2); PARSE_BITS_DECODE_TWO(3, res1, shift1, res2, shift2); // Next four bytes contain four consecutive bits of res2 each. // Note the switched order of variables. PARSE_BITS_DECODE_TWO(0, res2, shift2, res1, shift1); PARSE_BITS_DECODE_TWO(1, res2, shift2, res1, shift1); PARSE_BITS_DECODE_TWO(2, res2, shift2, res1, shift1); PARSE_BITS_DECODE_TWO(3, res2, shift2, res1, shift1); // Back to the original order. PARSE_BITS_DECODE_TWO(0, res1, shift1, res2, shift2); #undef PARSE_BITS_DECODE_TWO byte = *(uptr++); // 10th byte has at most one bit set. if (byte > 1) { return nullptr; // Value is too long to be two encoded values. } res2 |= byte << 31; done: *a = res1; *b = res2; return reinterpret_cast<const char*>(uptr); } } // namespace const char* Varint::DecodeTwo32ValuesSlow(const char* p, uint32* a, uint32* b) { return DecodeTwo32ValuesInternal<false>(p, nullptr, a, b); } const char* Varint::DecodeTwo32ValuesWithLimit(const char* ptr, const char* limit, uint32* a, uint32* b) { if (ptr + kMax64 <= limit) { return DecodeTwo32Values(ptr, a, b); } return DecodeTwo32ValuesInternal<true>(ptr, limit, a, b); }
36.703608
80
0.592866
sita1999
6e64e46916600f8502d5e3c037f94ea03f22551c
5,043
cc
C++
chrome/browser/chrome_navigation_browsertest.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
chrome/browser/chrome_navigation_browsertest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/chrome_navigation_browsertest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" class ChromeNavigationBrowserTest : public InProcessBrowserTest { public: ChromeNavigationBrowserTest() {} ~ChromeNavigationBrowserTest() override {} void SetUpCommandLine(base::CommandLine* command_line) override { ASSERT_TRUE(embedded_test_server()->Start()); } void StartServerWithExpiredCert() { expired_https_server_.reset( new net::EmbeddedTestServer(net::EmbeddedTestServer::TYPE_HTTPS)); expired_https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED); expired_https_server_->AddDefaultHandlers( base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(expired_https_server_->Start()); } net::EmbeddedTestServer* expired_https_server() { return expired_https_server_.get(); } private: std::unique_ptr<net::EmbeddedTestServer> expired_https_server_; DISALLOW_COPY_AND_ASSIGN(ChromeNavigationBrowserTest); }; // Helper class to track and allow waiting for navigation start events. class DidStartNavigationObserver : public content::WebContentsObserver { public: explicit DidStartNavigationObserver(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), message_loop_runner_(new content::MessageLoopRunner) {} ~DidStartNavigationObserver() override {} // Runs a nested message loop and blocks until the full load has // completed. void Wait() { message_loop_runner_->Run(); } private: // WebContentsObserver void DidStartNavigation(content::NavigationHandle* handle) override { if (message_loop_runner_->loop_running()) message_loop_runner_->Quit(); } // The MessageLoopRunner used to spin the message loop. scoped_refptr<content::MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(DidStartNavigationObserver); }; // Test to verify that navigations are not deleting the transient // NavigationEntry when showing an interstitial page and the old renderer // process is trying to navigate. See https://crbug.com/600046. IN_PROC_BROWSER_TEST_F( ChromeNavigationBrowserTest, TransientEntryPreservedOnMultipleNavigationsDuringInterstitial) { StartServerWithExpiredCert(); GURL setup_url = embedded_test_server()->GetURL("/window_open_and_navigate.html"); GURL initial_url = embedded_test_server()->GetURL("/title1.html"); GURL error_url(expired_https_server()->GetURL("/ssl/blank_page.html")); ui_test_utils::NavigateToURL(browser(), setup_url); content::WebContents* main_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); // Call the JavaScript method in the test page, which opens a new window // and stores a handle to it. content::WindowedNotificationObserver tab_added_observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); EXPECT_TRUE(content::ExecuteScript(main_web_contents, "openWin();")); tab_added_observer.Wait(); content::WebContents* new_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); // Navigate the opened window to a page that will successfully commit and // create a NavigationEntry. { content::TestNavigationObserver observer(new_web_contents); EXPECT_TRUE(content::ExecuteScript( main_web_contents, "navigate('" + initial_url.spec() + "');")); observer.Wait(); EXPECT_EQ(initial_url, new_web_contents->GetLastCommittedURL()); } // Navigate the opened window to a page which will trigger an // interstitial. { content::TestNavigationObserver observer(new_web_contents); EXPECT_TRUE(content::ExecuteScript( main_web_contents, "navigate('" + error_url.spec() + "');")); observer.Wait(); EXPECT_EQ(initial_url, new_web_contents->GetLastCommittedURL()); EXPECT_EQ(error_url, new_web_contents->GetVisibleURL()); } // Navigate again the opened window to the same page. It should not cause // WebContents::GetVisibleURL to return the last committed one. { DidStartNavigationObserver nav_observer(new_web_contents); EXPECT_TRUE(content::ExecuteScript( main_web_contents, "navigate('" + error_url.spec() + "');")); nav_observer.Wait(); EXPECT_EQ(error_url, new_web_contents->GetVisibleURL()); EXPECT_TRUE(new_web_contents->GetController().GetTransientEntry()); EXPECT_FALSE(new_web_contents->IsLoading()); } }
39.093023
79
0.761452
Wzzzx
6e65502e96a12437e12aad53ae1f8063e28098ee
2,529
cpp
C++
011/011.cpp
joeymich/Project-Euler
a061f6ecc2afa9f95f3727380443dfc6e8d43db0
[ "MIT" ]
1
2022-03-26T07:05:21.000Z
2022-03-26T07:05:21.000Z
011/011.cpp
joeymich/Project-Euler
a061f6ecc2afa9f95f3727380443dfc6e8d43db0
[ "MIT" ]
null
null
null
011/011.cpp
joeymich/Project-Euler
a061f6ecc2afa9f95f3727380443dfc6e8d43db0
[ "MIT" ]
null
null
null
// Problem 11 -- Largest product in a grid /* 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 */ #include <iostream> #include <vector> using namespace std; int main() { vector<vector<int>> grid(20, vector<int>(20, 0)); for (unsigned int i = 0; i < 20; i++) for (unsigned int j = 0; j < 20; j++) cin >> grid.at(i).at(j); unsigned long long solution = 0; for (unsigned int i = 0; i < grid.size(); i++) { for (unsigned int j = 0; j < grid[i].size() - 3; j++) { unsigned long long temp1 = 1; // horizontal unsigned long long temp2 = 1; // vertical unsigned long long temp3 = 1; // up diagonal unsigned long long temp4 = 1; // down diagonal for (unsigned int k = 0; k < 4; k++) { temp1 *= grid[i][j + k]; temp2 *= grid[j + k][i]; if (i > 2) temp3 *= grid[i - k][j + k]; if (i < grid.size() - 3) temp4 *= grid[i + k][j + k]; } if (temp1 > solution) solution = temp1; if (temp2 > solution) solution = temp2; if (temp3 > solution) solution = temp3; if (temp4 > solution) solution = temp4; } } cout << solution << "\n"; return 0; }
40.142857
63
0.550415
joeymich
6e6747cd12f03d84ef2675e5a7b0bdb74173bc1b
1,145
hpp
C++
gearoenix/vulkan/texture/gx-vk-txt-cube.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/vulkan/texture/gx-vk-txt-cube.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/vulkan/texture/gx-vk-txt-cube.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_VULKAN_TEXTURE_CUBE_HPP #define GEAROENIX_VULKAN_TEXTURE_CUBE_HPP #include "../../core/gx-cr-build-configuration.hpp" #ifdef GX_USE_VULKAN #include "../../core/sync/gx-cr-sync-end-caller.hpp" #include "../../render/texture/gx-rnd-txt-texture-cube.hpp" #include "../../render/texture/gx-rnd-txt-texture-info.hpp" namespace gearoenix::vulkan::engine { class Engine; } namespace gearoenix::vulkan::image { class View; } namespace gearoenix::vulkan::texture { class TextureCube final : public render::texture::TextureCube { GX_GET_REFC_PRV(std::shared_ptr<image::View>, view) public: TextureCube( core::Id id, std::string name, engine::Engine* engine, std::vector<std::vector<std::vector<std::uint8_t>>> data, const render::texture::TextureInfo& info, std::size_t aspect, const core::sync::EndCaller<core::sync::EndCallerIgnore>& call) noexcept; ~TextureCube() noexcept final; void write_gx3d( const std::shared_ptr<system::stream::Stream>& s, const core::sync::EndCaller<core::sync::EndCallerIgnore>& c) noexcept final; }; } #endif #endif
30.945946
84
0.697817
Hossein-Noroozpour
6e67e9b6ff26bb8d951fb88800c8960d5a0cdfd5
1,019
cpp
C++
bp/src/OffscreenFramebuffer.cpp
larso0/bp
0aa13c6d78f6e6a1097d9231c1b9fc47ae74a9fe
[ "MIT" ]
8
2018-10-17T00:36:46.000Z
2020-11-18T05:34:28.000Z
bp/src/OffscreenFramebuffer.cpp
larso0/bp
0aa13c6d78f6e6a1097d9231c1b9fc47ae74a9fe
[ "MIT" ]
null
null
null
bp/src/OffscreenFramebuffer.cpp
larso0/bp
0aa13c6d78f6e6a1097d9231c1b9fc47ae74a9fe
[ "MIT" ]
1
2022-01-06T04:28:18.000Z
2022-01-06T04:28:18.000Z
#include <bp/OffscreenFramebuffer.h> #include <bp/RenderPass.h> namespace bp { void OffscreenFramebuffer::init(RenderPass& renderPass, uint32_t width, uint32_t height, const AttachmentSlot& colorAttachmentSlot, const AttachmentSlot& depthAttachmentSlot) { Device& device = renderPass.getDevice(); colorAttachment.init(device, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, width, height); depthAttachment.init(device, VK_FORMAT_D16_UNORM, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, width, height); depthAttachment.setClearValue({1.f, 0.f}); setAttachment(colorAttachmentSlot, colorAttachment); setAttachment(depthAttachmentSlot, depthAttachment); Framebuffer::init(renderPass, width, height); } void OffscreenFramebuffer::resize(uint32_t width, uint32_t height) { colorAttachment.resize(width, height); depthAttachment.resize(width, height); Framebuffer::resize(width, height); } }
30.878788
91
0.784102
larso0
6e6a63640b448ebb8e7891e60e2c4139077bfed4
8,080
hpp
C++
src/dag/dag.hpp
kostdima/taraxa
61e9a50a60049c3f989efaf6970cd99a74896767
[ "MIT" ]
null
null
null
src/dag/dag.hpp
kostdima/taraxa
61e9a50a60049c3f989efaf6970cd99a74896767
[ "MIT" ]
null
null
null
src/dag/dag.hpp
kostdima/taraxa
61e9a50a60049c3f989efaf6970cd99a74896767
[ "MIT" ]
null
null
null
#pragma once #include <atomic> #include <bitset> #include <boost/function.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/labeled_graph.hpp> #include <boost/graph/properties.hpp> #include <boost/property_map/property_map.hpp> #include <boost/thread.hpp> #include <chrono> #include <condition_variable> #include <iostream> #include <iterator> #include <list> #include <mutex> #include <queue> #include <string> #include "common/types.hpp" #include "consensus/pbft_chain.hpp" #include "dag_block.hpp" #include "storage/db_storage.hpp" #include "transaction_manager/transaction_manager.hpp" #include "util/util.hpp" namespace taraxa { /** * Thread safe. Labelled graph. */ class DagManager; class Dag { public: // properties using vertex_hash = std::string; using vertex_property_t = boost::property<boost::vertex_index_t, std::string, boost::property<boost::vertex_index1_t, uint64_t>>; using edge_property_t = boost::property<boost::edge_index_t, uint64_t>; // graph def using adj_list_t = boost::adjacency_list<boost::setS, boost::hash_setS, boost::directedS, vertex_property_t, edge_property_t>; using graph_t = boost::labeled_graph<adj_list_t, std::string, boost::hash_mapS>; using vertex_t = boost::graph_traits<graph_t>::vertex_descriptor; using edge_t = boost::graph_traits<graph_t>::edge_descriptor; using vertex_iter_t = boost::graph_traits<graph_t>::vertex_iterator; using edge_iter_t = boost::graph_traits<graph_t>::edge_iterator; using vertex_adj_iter_t = boost::graph_traits<graph_t>::adjacency_iterator; // property_map using vertex_index_map_const_t = boost::property_map<graph_t, boost::vertex_index_t>::const_type; using vertex_index_map_t = boost::property_map<graph_t, boost::vertex_index_t>::type; using vertex_period_map_const_t = boost::property_map<graph_t, boost::vertex_index1_t>::const_type; using vertex_period_map_t = boost::property_map<graph_t, boost::vertex_index1_t>::type; using edge_index_map_const_t = boost::property_map<graph_t, boost::edge_index_t>::const_type; using edge_index_map_t = boost::property_map<graph_t, boost::edge_index_t>::type; friend DagManager; explicit Dag(std::string const &genesis, addr_t node_addr); virtual ~Dag() = default; uint64_t getNumVertices() const; uint64_t getNumEdges() const; bool hasVertex(vertex_hash const &v) const; bool addVEEs(vertex_hash const &new_vertex, vertex_hash const &pivot, std::vector<vertex_hash> const &tips); void getLeaves(std::vector<vertex_hash> &tips) const; void drawGraph(vertex_hash filename) const; bool computeOrder(vertex_hash const &anchor, std::vector<vertex_hash> &ordered_period_vertices, std::map<uint64_t, std::vector<std::string>> const &non_finalized_blks); void clear(); protected: // Note: private functions does not lock // edge API edge_t addEdge(std::string const &v1, std::string const &v2); edge_t addEdge(vertex_t v1, vertex_t v2); // traverser API bool reachable(vertex_t const &from, vertex_t const &to) const; void collectLeafVertices(std::vector<vertex_t> &leaves) const; graph_t graph_; vertex_t genesis_; // root node protected: LOG_OBJECTS_DEFINE }; /** * PivotTree is a special DAG, every vertex only has one out-edge, * therefore, there is no convergent tree */ class PivotTree : public Dag { public: friend DagManager; explicit PivotTree(std::string const &genesis, addr_t node_addr) : Dag(genesis, node_addr){}; virtual ~PivotTree() = default; using vertex_t = Dag::vertex_t; using vertex_adj_iter_t = Dag::vertex_adj_iter_t; using vertex_index_map_const_t = Dag::vertex_index_map_const_t; void getGhostPath(vertex_hash const &vertex, std::vector<vertex_hash> &pivot_chain) const; }; class DagBuffer; class FullNode; class DagManager : public std::enable_shared_from_this<DagManager> { public: using uLock = boost::unique_lock<boost::shared_mutex>; using sharedLock = boost::shared_lock<boost::shared_mutex>; explicit DagManager(std::string const &genesis, addr_t node_addr, std::shared_ptr<TransactionManager> trx_mgr, std::shared_ptr<PbftChain> pbft_chain, std::shared_ptr<DbStorage> db); virtual ~DagManager() = default; std::shared_ptr<DagManager> getShared(); void stop(); std::string const &get_genesis() { return genesis_; } bool pivotAndTipsAvailable(DagBlock const &blk); void addDagBlock(DagBlock const &blk, bool finalized = false, bool save = true); // insert to buffer if fail // return {period, block order}, for pbft-pivot-blk proposing (does not // finalize) std::pair<uint64_t, std::shared_ptr<vec_blk_t>> getDagBlockOrder(blk_hash_t const &anchor); // receive pbft-povit-blk, update periods and finalized, return size of // ordered blocks uint setDagBlockOrder(blk_hash_t const &anchor, uint64_t period, vec_blk_t const &dag_order, const taraxa::DbStorage::BatchPtr &write_batch); bool getLatestPivotAndTips(std::string &pivot, std::vector<std::string> &tips) const; void collectTotalLeaves(std::vector<std::string> &leaves) const; void getGhostPath(std::string const &source, std::vector<std::string> &ghost) const; void getGhostPath(std::vector<std::string> &ghost) const; // get ghost path from last anchor // ----- Total graph void drawTotalGraph(std::string const &str) const; // ----- Pivot graph // can return self as pivot chain void drawPivotGraph(std::string const &str) const; void drawGraph(std::string const &dotfile) const; std::pair<uint64_t, uint64_t> getNumVerticesInDag() const; std::pair<uint64_t, uint64_t> getNumEdgesInDag() const; level_t getMaxLevel() const { return max_level_; } // DAG anchors uint64_t getLatestPeriod() const { sharedLock lock(mutex_); return period_; } std::pair<std::string, std::string> getAnchors() const { sharedLock lock(mutex_); return std::make_pair(old_anchor_, anchor_); } std::map<uint64_t, std::vector<std::string>> getNonFinalizedBlocks() const; DagFrontier getDagFrontier(); private: void recoverDag(); void addToDag(std::string const &hash, std::string const &pivot, std::vector<std::string> const &tips, uint64_t level, const taraxa::DbStorage::BatchPtr &write_batch, bool finalized = false); std::pair<std::string, std::vector<std::string>> getFrontier() const; // return pivot and tips std::atomic<level_t> max_level_ = 0; mutable boost::shared_mutex mutex_; std::shared_ptr<PivotTree> pivot_tree_; // only contains pivot edges std::shared_ptr<Dag> total_dag_; // contains both pivot and tips std::shared_ptr<TransactionManager> trx_mgr_; std::shared_ptr<PbftChain> pbft_chain_; std::shared_ptr<DbStorage> db_; std::string anchor_; // anchor of the last period std::string old_anchor_; // anchor of the second to last period uint64_t period_; // last period std::string genesis_; std::map<uint64_t, std::vector<std::string>> non_finalized_blks_; std::map<uint64_t, std::vector<std::string>> finalized_blks_; DagFrontier frontier_; LOG_OBJECTS_DEFINE }; // for graphviz template <class Property1> class vertex_label_writer { public: vertex_label_writer(Property1 name) : name(name) {} template <class Vertex> void operator()(std::ostream &out, const Vertex &v) const { out << "[label=\"" << name[v].substr(0, 8) << " " << "\"]"; } private: Property1 name; }; template <class Property> class edge_label_writer { public: explicit edge_label_writer(Property weight) : weight(weight) {} template <class Edge> void operator()(std::ostream &out, const Edge &e) const { if (weight[e] == 0) { out << "[style=\"dashed\" dir=\"back\"]"; } else { out << "[dir=\"back\"]"; } } private: Property weight; }; } // namespace taraxa
35.283843
120
0.727723
kostdima
6e6a707446cd007d30d0fcce7439127d819dfb5d
4,519
cpp
C++
src/common/common.cpp
nikolovjovan/exblas
7541d384242a84a8b8314648d939b846ca632321
[ "Apache-2.0" ]
null
null
null
src/common/common.cpp
nikolovjovan/exblas
7541d384242a84a8b8314648d939b846ca632321
[ "Apache-2.0" ]
null
null
null
src/common/common.cpp
nikolovjovan/exblas
7541d384242a84a8b8314648d939b846ca632321
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2016 Inria and University Pierre and Marie Curie * All rights reserved. */ #include <cstdlib> #include <cstdio> #include <random> #include <math.h> #include "common.hpp" double randDoubleUniform() { // Uniform distribution for now return double(rand() - RAND_MAX/4) * 12345.678901234; } double randDouble(int emin, int emax, int neg_ratio) { // Uniform mantissa double x = double(rand()) / double(RAND_MAX * .99) + 1.; // Uniform exponent int e = (rand() % (emax - emin)) + emin; // Sign if(neg_ratio > 1 && rand() % neg_ratio == 0) { x = -x; } return ldexp(x, e); } void init_fpuniform(const int n, double *a, int range, int emax) { for(int i = 0; i != n; ++i) a[i] = randDouble(emax-range, emax, 1); } void init_fpuniform_matrix(const bool iscolumnwise, const int m, const int n, double *a, const int lda, const int range, const int emax) { //Generate numbers on several bins starting from emax if (iscolumnwise) { for(int j = 0; j < n; ++j) for(int i = 0; i < m; ++i) a[j * lda + i] = randDouble(0, range, 1); } else { for(int i = 0; i < m; ++i) for(int j = 0; j < n; ++j) a[i * lda + j] = randDouble(0, range, 1); } } void init_fpuniform_tr_matrix(const char uplo, const char diag, const int n, double *a, const int range, const int emax) { if (uplo == 'U') { for(int i = n-1; i >= 0; i--) for(int j = i; j < n; ++j) if ((diag == 'U') && (j == i)) a[j * n + i] = 1.0; else a[j * n + i] = randDouble(emax-range, emax, 1); } else { for(int i = 0; i != n; ++i) for(int j = 0; j <= i; ++j) if ((diag == 'U') && (j == i)) a[j * n + i] = 1.0; else a[j * n + i] = randDouble(emax-range, emax, 1); } } void init_lognormal(const int n, double * a, double mean, double stddev) { std::random_device rd; std::default_random_engine gen(rd()); std::lognormal_distribution<> d(mean, stddev); for(int i = 0; i != n; ++i) a[i] = d(gen); } void init_lognormal_matrix(const bool iscolumnwise, const int m, const int n, double *a, const int lda, const double mean, const double stddev) { std::random_device rd; std::default_random_engine gen(rd()); std::lognormal_distribution<> d(mean, stddev); if (iscolumnwise) { for(int j = 0; j < n; ++j) for(int i = 0; i < m; ++i) a[j * lda + i] = 1.0;//d(gen); } else { for(int i = 0; i < m; ++i) for(int j = 0; j < n; ++j) a[i * lda + j] = 1.0;//d(gen); } } void init_lognormal_tr_matrix(const char uplo, const char diag, const int n, double * a, const double mean, const double stddev) { std::random_device rd; std::default_random_engine gen(rd()); std::lognormal_distribution<> d(mean, stddev); if (uplo == 'U') { for(int i = n-1; i >= 0; i--) for(int j = i; j < n; ++j) if ((diag == 'U') && (j == i)) a[i * n + j] = 1.0; else a[i * n + j] = d(gen); } else { for(int i = 0; i != n; ++i) for(int j = 0; j <= i; ++j) if ((diag == 'U') && (j == i)) a[i * n + j] = 1.0; else a[i * n + j] = d(gen); } } void init_ill_cond(const int n, double *a, double c) { int n2 = round(n / 2); for(int i = 0; i != n; ++i) a[i] = 0.0; // init the first half of exponents double *e, x; e = (double *) malloc(n * sizeof(double)); double b = log2(c); for(int i = 0; i != n2; ++i) { x = double(rand()) / double(RAND_MAX); e[i] = round(x * b / 2); } e[0] = round(b / 2) + 1.; e[n-1] = 0; // init the first half of the vector for(int i = 0; i != n2; ++i) { double x = double(rand()) / double(RAND_MAX); a[i] = (2. * x - 1.) * pow(2., e[i]); } // init the second half of the vector double step = (b / 2) / (n - n2); for(int i = n2; i != n; ++i) { double x = double(rand()) / double(RAND_MAX); e[i] = step * (i - n2); a[i] = (2. * x - 1.) * pow(2., e[i]); } free(e); } void init_naive(const int n, double *a) { for(int i = 0; i != n; ++i) a[i] = 1.1; }
29.730263
145
0.477097
nikolovjovan
6e6af1da2aa1e2121cebb42182a44dc806e4e110
2,426
hpp
C++
Nacro/SDK/FN_Landscape_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_Landscape_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_Landscape_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Landscape.LandscapeProxy.EditorApplySpline struct ALandscapeProxy_EditorApplySpline_Params { class USplineComponent* InSplineComponent; // (Parm, ZeroConstructor, InstancedReference, IsPlainOldData) float StartWidth; // (Parm, ZeroConstructor, IsPlainOldData) float EndWidth; // (Parm, ZeroConstructor, IsPlainOldData) float StartSideFalloff; // (Parm, ZeroConstructor, IsPlainOldData) float EndSideFalloff; // (Parm, ZeroConstructor, IsPlainOldData) float StartRoll; // (Parm, ZeroConstructor, IsPlainOldData) float EndRoll; // (Parm, ZeroConstructor, IsPlainOldData) int NumSubdivisions; // (Parm, ZeroConstructor, IsPlainOldData) bool bRaiseHeights; // (Parm, ZeroConstructor, IsPlainOldData) bool bLowerHeights; // (Parm, ZeroConstructor, IsPlainOldData) class ULandscapeLayerInfoObject* PaintLayer; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Landscape.LandscapeProxy.ChangeLODDistanceFactor struct ALandscapeProxy_ChangeLODDistanceFactor_Params { float InLODDistanceFactor; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
55.136364
172
0.40643
Milxnor
6e6bb91077029d71cde67930680eda2bdbdc66fe
4,131
cpp
C++
Kamek/src/meteor.cpp
H1dd3nM1nd/NewerSMBW
b747e89375245a1da650b186181d2b94a12387a0
[ "MIT" ]
1
2021-06-21T04:11:04.000Z
2021-06-21T04:11:04.000Z
Kamek/src/meteor.cpp
CLF78/NSMASR-Code
b747e89375245a1da650b186181d2b94a12387a0
[ "MIT" ]
null
null
null
Kamek/src/meteor.cpp
CLF78/NSMASR-Code
b747e89375245a1da650b186181d2b94a12387a0
[ "MIT" ]
null
null
null
#include <common.h> #include <game.h> #include <g3dhax.h> #include <sfx.h> #include "boss.h" const char* MEarcNameList [] = { "kazan_rock", NULL }; class dMeteor : public dEn_c { int onCreate(); int onDelete(); int onExecute(); int onDraw(); static dMeteor *build(); mHeapAllocator_c allocator; m3d::mdl_c bodyModel; nw4r::g3d::ResFile resFile; mEf::es2 effect; int spinSpeed; char spinDir; char isElectric; Physics MakeItRound; void updateModelMatrices(); void playerCollision(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther); public: void kill(); }; dMeteor *dMeteor::build() { void *buffer = AllocFromGameHeap1(sizeof(dMeteor)); return new(buffer) dMeteor; } void dMeteor::playerCollision(ActivePhysics *apThis, ActivePhysics *apOther) { DamagePlayer(this, apThis, apOther); } bool dMeteor::collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther) { this->playerCollision(apThis, apOther); return true; } void MeteorPhysicsCallback(dMeteor *self, dEn_c *other) { if (other->name == 657) { OSReport("CANNON COLLISION"); SpawnEffect("Wm_en_explosion", 0, &other->pos, &(S16Vec){0,0,0}, &(Vec){1.0, 1.0, 1.0}); SpawnEffect("Wm_en_explosion_smk", 0, &other->pos, &(S16Vec){0,0,0}, &(Vec){1.0, 1.0, 1.0}); PlaySound(other, SE_OBJ_TARU_BREAK); other->Delete(1); switch ((self->settings >> 24) & 3) { case 1: dStageActor_c::create(EN_HATENA_BALLOON, 0x100, &self->pos, 0, self->currentLayerID); break; case 2: VEC3 coinPos = {self->pos.x - 16.0f, self->pos.y, self->pos.z}; dStageActor_c::create(EN_COIN, 9, &coinPos, 0, self->currentLayerID); break; } self->kill(); } } int dMeteor::onCreate() { // Setup Model allocator.link(-1, GameHeaps[0], 0, 0x20); this->resFile.data = getResource("kazan_rock", "g3d/kazan_rock.brres"); nw4r::g3d::ResMdl mdl = this->resFile.GetResMdl("kazan_rock"); bodyModel.setup(mdl, &allocator, 0x224, 1, 0); SetupTextures_Enemy(&bodyModel, 0); allocator.unlink(); // Retrieve Scale and set it up float sca = (float)((this->settings >> 8) & 0xFF); sca = (sca/5.0) + 0.2; this->scale = (Vec){sca,sca,sca}; // Other settings this->spinDir = this->settings & 0x1; this->spinSpeed = ((this->settings >> 16) & 0xFF) * 20; this->isElectric = (this->settings >> 4) & 0x1; // Setup Physics if (isElectric) { ActivePhysics::Info elec; elec.xDistToCenter = 0.0; elec.yDistToCenter = 0.0; elec.xDistToEdge = 13.0 * sca; elec.yDistToEdge = 13.0 * sca; elec.category1 = 3; elec.category2 = 0; elec.bitfield1 = 0x4F; elec.bitfield2 = 0x200; elec.unkShort1C = 0; elec.callback = &dEn_c::collisionCallback; this->aPhysics.initWithStruct(this, &elec); this->aPhysics.addToList(); } MakeItRound.baseSetup(this, &MeteorPhysicsCallback, &MeteorPhysicsCallback, &MeteorPhysicsCallback, 1, 0); MakeItRound.x = 0.0; MakeItRound.y = 0.0; MakeItRound.diameter = 13.0 * sca; MakeItRound.isRound = 1; MakeItRound.update(); MakeItRound.addToList(); this->pos.z = (settings & 0x1000000) ? -2000.0f : 3458.0f; return true; } int dMeteor::onDelete() { return true; } int dMeteor::onExecute() { if (spinDir == 0) rot.z -= spinSpeed; else rot.z += spinSpeed; MakeItRound.update(); updateModelMatrices(); if (isElectric) { effect.spawn("Wm_en_birikyu_biri", 0, &(Vec){pos.x, pos.y, pos.z+500.0}, &rot, &(Vec){scale.x*0.8, scale.y*0.8, scale.z*0.8}); PlaySound(this, SE_EMY_BIRIKYU_SPARK); } return true; } int dMeteor::onDraw() { bodyModel.scheduleForDrawing(); bodyModel._vf1C(); return true; } void dMeteor::updateModelMatrices() { // This won't work with wrap because I'm lazy. matrix.translation(pos.x, pos.y, pos.z); matrix.applyRotationYXZ(&rot.x, &rot.y, &rot.z); bodyModel.setDrawMatrix(matrix); bodyModel.setScale(&scale); bodyModel.calcWorld(false); } void dMeteor::kill() { PlaySound(this, SE_OBJ_ROCK_LAND); SpawnEffect("Wm_ob_cmnboxsmoke", 0, &pos, &rot, &scale); SpawnEffect("Wm_ob_cmnboxgrain", 0, &pos, &rot, &scale); this->Delete(1); }
22.95
128
0.68458
H1dd3nM1nd
6e6cd33458522cbe4976a2251116feb73eb93c9e
8,752
cpp
C++
src/framework/factory.cpp
ancrist/apitest
cde1d337e7f0b60aa5bb943fb54219cccfa0ad06
[ "Unlicense" ]
1
2017-03-14T12:29:06.000Z
2017-03-14T12:29:06.000Z
src/framework/factory.cpp
ancrist/apitest
cde1d337e7f0b60aa5bb943fb54219cccfa0ad06
[ "Unlicense" ]
null
null
null
src/framework/factory.cpp
ancrist/apitest
cde1d337e7f0b60aa5bb943fb54219cccfa0ad06
[ "Unlicense" ]
null
null
null
#include "pch.h" #include "factory.h" #include "problems/dynamicstreaming.h" #include "problems/null.h" #include "problems/texturedquads.h" #include "problems/untexturedobjects.h" #include "solutions/dynamicstreaming/gl/buffersubdata.h" #include "solutions/dynamicstreaming/gl/mappersistent.h" #include "solutions/dynamicstreaming/gl/mapunsynchronized.h" #include "solutions/nullsoln.h" #include "solutions/untexturedobjects/gl/bindless.h" #include "solutions/untexturedobjects/gl/bindlessindirect.h" #include "solutions/untexturedobjects/gl/bufferrange.h" #include "solutions/untexturedobjects/gl/bufferstorage.h" #include "solutions/untexturedobjects/gl/dynamicbuffer.h" #include "solutions/untexturedobjects/gl/mapunsynchronized.h" #include "solutions/untexturedobjects/gl/mappersistent.h" #include "solutions/untexturedobjects/gl/drawloop.h" #include "solutions/untexturedobjects/gl/multidraw.h" #include "solutions/untexturedobjects/gl/multidrawbuffer.h" #include "solutions/untexturedobjects/gl/texcoord.h" #include "solutions/untexturedobjects/gl/uniform.h" #include "solutions/texturedquads/gl/bindless.h" #include "solutions/texturedquads/gl/bindlessmultidraw.h" #include "solutions/texturedquads/gl/naive.h" #include "solutions/texturedquads/gl/naiveuniform.h" #include "solutions/texturedquads/gl/notex.h" #include "solutions/texturedquads/gl/notexuniform.h" #include "solutions/texturedquads/gl/sparsebindlesstexturearray.h" #include "solutions/texturedquads/gl/sparsebindlesstexturearraymultidraw.h" #include "solutions/texturedquads/gl/texturearray.h" #include "solutions/texturedquads/gl/texturearrayuniform.h" #include "solutions/texturedquads/gl/texturearraymultidraw.h" // All D3D11 includes should go here. #if WITH_D3D11 # include "solutions/dynamicstreaming/d3d11/mapnooverwrite.h" # include "solutions/dynamicstreaming/d3d11/updatesubresource.h" # include "solutions/texturedquads/d3d11/naive.h" # include "solutions/untexturedobjects/d3d11/naive.h" #endif // -------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------- ProblemFactory::ProblemFactory(bool _skipInit) { Problem* newProb = nullptr; // Null newProb = new NullProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new NullSolution()); } else { newProb->Shutdown(); SafeDelete(newProb); console::error("Unable to create the Null Problem--exiting."); } // DynamicStreaming newProb = new DynamicStreamingProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingGLBufferSubData()); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingGLMapUnsynchronized()); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingGLMapPersistent()); #if WITH_D3D11 mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingD3D11MapNoOverwrite()); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingD3D11UpdateSubresource()); #endif } else { newProb->Shutdown(); SafeDelete(newProb); } // UntexturedObjects newProb = new UntexturedObjectsProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLUniform()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLDrawLoop()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDraw(true)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDraw(false)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDrawBuffer(true)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDrawBuffer(false)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBindless()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBindlessIndirect()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBufferRange()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBufferStorage(true)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBufferStorage(false)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLDynamicBuffer()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMapUnsynchronized()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMapPersistent()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLTexCoord()); #if WITH_D3D11 mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsD3D11Naive()); #endif } else { newProb->Shutdown(); SafeDelete(newProb); } // Textured Quads newProb = new TexturedQuadsProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLBindless()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLBindlessMultiDraw()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNaive()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNaiveUniform()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNoTex()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNoTexUniform()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLSparseBindlessTextureArray()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLSparseBindlessTextureArrayMultiDraw(true)); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLSparseBindlessTextureArrayMultiDraw(false)); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArray()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArrayUniform()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArrayMultiDraw(true)); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArrayMultiDraw(false)); #if WITH_D3D11 mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsD3D11Naive()); #endif } else { newProb->Shutdown(); SafeDelete(newProb); } } // -------------------------------------------------------------------------------------------------------------------- ProblemFactory::~ProblemFactory() { for (auto probIt = mSolutions.begin(); probIt != mSolutions.end(); ++probIt) { for (auto solIt = probIt->second.begin(); solIt != probIt->second.end(); ++solIt) { SafeDelete(*solIt); } } for (auto probIt = mProblems.begin(); probIt != mProblems.end(); ++probIt) { SafeDelete(*probIt); } } // -------------------------------------------------------------------------------------------------------------------- std::vector<Problem*> ProblemFactory::GetProblems() { return mProblems; } // -------------------------------------------------------------------------------------------------------------------- std::vector<Solution*> ProblemFactory::GetSolutions(Problem* _problem, GfxBaseApi* _activeApi) { assert(_problem); std::vector<Solution*> tmpProblems = mSolutions[_problem->GetName()]; if (_activeApi) { EGfxApi apiType = _activeApi->GetApiType(); std::vector<Solution*> retProblems; for (auto it = tmpProblems.cbegin(); it != tmpProblems.cend(); ++it) { if ((*it)->SupportsApi(apiType)) { retProblems.push_back((*it)); } } return retProblems; } return tmpProblems; }
46.802139
121
0.650594
ancrist
6e6d5ad686077d589e3ff777bf78c9fd6fcc5252
1,950
cpp
C++
src/harbour-hafenschau.cpp
black-sheep-dev/harbour-hafenschau
8384e769a0d6d5b85787e92565c475be9d2f37fa
[ "MIT" ]
8
2021-01-09T21:37:36.000Z
2022-01-05T09:27:13.000Z
src/harbour-hafenschau.cpp
black-sheep-dev/harbour-hafenschau
8384e769a0d6d5b85787e92565c475be9d2f37fa
[ "MIT" ]
null
null
null
src/harbour-hafenschau.cpp
black-sheep-dev/harbour-hafenschau
8384e769a0d6d5b85787e92565c475be9d2f37fa
[ "MIT" ]
1
2021-03-13T11:21:03.000Z
2021-03-13T11:21:03.000Z
#include <QtQuick> #include <sailfishapp.h> #include "api/apiinterface.h" #include "comments/commentsmodel.h" #include "comments/commentssortfiltermodel.h" #include "enums/enums.h" #include "news/newslistmodel.h" #include "news/newssortfiltermodel.h" #include "region/regionsmodel.h" #include "tools/datawriter.h" int main(int argc, char *argv[]) { // Disable crash guard and prefer egl for webgl. setenv("MOZ_DISABLE_CRASH_GUARD", "1", 1); setenv("MOZ_WEBGL_PREFER_EGL", "1", 1); // Set up QML engine. QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> v(SailfishApp::createView()); app->setApplicationName(QStringLiteral("Hafenschau")); app->setApplicationVersion(APP_VERSION); app->setOrganizationName(QStringLiteral("org.nubecula")); app->setOrganizationDomain(QStringLiteral("nubecula.org")); #ifndef QT_DEBUG auto uri = "org.nubecula.harbour.hafenschau"; #else #define uri "org.nubecula.harbour.hafenschau" #endif // register enums qmlRegisterUncreatableType<DeveloperOption>(uri, 1, 0, "DeveloperOption", ""); qmlRegisterUncreatableType<NewsType>(uri, 1, 0, "NewsType", ""); qmlRegisterUncreatableType<Ressort>(uri, 1, 0, "Ressort", ""); qmlRegisterUncreatableType<VideoQuality>(uri, 1, 0, "VideoQuality", ""); // register types qmlRegisterType<ApiInterface>(uri, 1, 0, "ApiInterface"); qmlRegisterType<CommentsModel>(uri, 1, 0, "CommentsModel"); qmlRegisterType<CommentsSortFilterModel>(uri, 1, 0, "CommentsSortFilterModel"); qmlRegisterType<DataWriter>(uri, 1, 0, "DataWriter"); qmlRegisterType<NewsListModel>(uri, 1, 0, "NewsListModel"); qmlRegisterType<NewsSortFilterModel>(uri, 1, 0, "NewsSortFilterModel"); qmlRegisterType<RegionsModel>(uri, 1, 0, "RegionsModel"); v->setSource(SailfishApp::pathTo("qml/harbour-hafenschau.qml")); v->show(); return app->exec(); }
34.821429
84
0.72
black-sheep-dev
6e6ed92c19e6d3d1cf2849e90e3fc564a379a8ae
4,760
cpp
C++
service/kernel/data_management/data_management_utils_cpu.cpp
rayrapetyan/daal
41cc748dc50097b1064e40395a4da7ce6f836244
[ "Apache-2.0" ]
null
null
null
service/kernel/data_management/data_management_utils_cpu.cpp
rayrapetyan/daal
41cc748dc50097b1064e40395a4da7ce6f836244
[ "Apache-2.0" ]
null
null
null
service/kernel/data_management/data_management_utils_cpu.cpp
rayrapetyan/daal
41cc748dc50097b1064e40395a4da7ce6f836244
[ "Apache-2.0" ]
null
null
null
/** file data_management_utils_cpu.cpp */ /******************************************************************************* * Copyright 2014-2018 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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 "data_utils.h" #include "service_data_utils.h" namespace daal { namespace data_feature_utils { namespace internal { template<typename T1, typename T2, CpuType cpu> void vectorConvertFuncCpu(size_t n, void *src, void *dst) { for(size_t i = 0; i < n; i++) { ((T2 *)dst)[i] = static_cast<T2>(((T1 *)src)[i]); } } template<typename T1, typename T2, CpuType cpu> void vectorStrideConvertFuncCpu(size_t n, void *src, size_t srcByteStride, void *dst, size_t dstByteStride) { for(size_t i = 0; i < n ; i++) { *(T2 *)(((char *)dst) + i * dstByteStride) = static_cast<T2>(*(T1 *)(((char *)src) + i * srcByteStride)); } } #undef DAAL_FUNCS_UP_ENTRY #define DAAL_FUNCS_UP_ENTRY(F,T,A) \ template void F<T, float , DAAL_CPU> A; \ template void F<T, double, DAAL_CPU> A; \ template void F<T, int , DAAL_CPU> A; #undef DAAL_FUNCS_DOWN_ENTRY #define DAAL_FUNCS_DOWN_ENTRY(F,T,A) \ template void F<float , T, DAAL_CPU> A; \ template void F<double, T, DAAL_CPU> A; \ template void F<int , T, DAAL_CPU> A; #undef DAAL_CONVERT_UP_FUNCS #define DAAL_CONVERT_UP_FUNCS(F,A) \ DAAL_FUNCS_UP_ENTRY(F,float,A) \ DAAL_FUNCS_UP_ENTRY(F,double,A) \ DAAL_FUNCS_UP_ENTRY(F,int,A) \ DAAL_FUNCS_UP_ENTRY(F,unsigned int,A) \ DAAL_FUNCS_UP_ENTRY(F,DAAL_INT64,A) \ DAAL_FUNCS_UP_ENTRY(F,DAAL_UINT64,A) \ DAAL_FUNCS_UP_ENTRY(F,char,A) \ DAAL_FUNCS_UP_ENTRY(F,unsigned char,A) \ DAAL_FUNCS_UP_ENTRY(F,short,A) \ DAAL_FUNCS_UP_ENTRY(F,unsigned short,A) #undef DAAL_CONVERT_DOWN_FUNCS #define DAAL_CONVERT_DOWN_FUNCS(F,A) \ DAAL_FUNCS_DOWN_ENTRY(F,unsigned int,A) \ DAAL_FUNCS_DOWN_ENTRY(F,DAAL_INT64,A) \ DAAL_FUNCS_DOWN_ENTRY(F,DAAL_UINT64,A) \ DAAL_FUNCS_DOWN_ENTRY(F,char,A) \ DAAL_FUNCS_DOWN_ENTRY(F,unsigned char,A) \ DAAL_FUNCS_DOWN_ENTRY(F,short,A) \ DAAL_FUNCS_DOWN_ENTRY(F,unsigned short,A) DAAL_CONVERT_UP_FUNCS(vectorConvertFuncCpu,(size_t n, void *src, void *dst)) DAAL_CONVERT_DOWN_FUNCS(vectorConvertFuncCpu,(size_t n, void *src, void *dst)) DAAL_CONVERT_UP_FUNCS(vectorStrideConvertFuncCpu,(size_t n, void *src, size_t srcByteStride, void *dst, size_t dstByteStride)) DAAL_CONVERT_DOWN_FUNCS(vectorStrideConvertFuncCpu,(size_t n, void *src, size_t srcByteStride, void *dst, size_t dstByteStride)) } } }
41.754386
128
0.664916
rayrapetyan
6e734e55003b77e7c2ab27f5661c6915e13f3bf6
4,628
cpp
C++
cpp/Inject0r/Inject0r/Helpers.cpp
ScriptIdiot/pantry
4cdda7bb8747f7b2eb00d85e929b9d797b1bcf85
[ "MIT" ]
4
2021-09-13T08:08:05.000Z
2022-03-27T20:08:34.000Z
cpp/Inject0r/Inject0r/Helpers.cpp
ScriptIdiot/pantry
4cdda7bb8747f7b2eb00d85e929b9d797b1bcf85
[ "MIT" ]
null
null
null
cpp/Inject0r/Inject0r/Helpers.cpp
ScriptIdiot/pantry
4cdda7bb8747f7b2eb00d85e929b9d797b1bcf85
[ "MIT" ]
2
2021-06-27T23:03:27.000Z
2021-08-01T08:47:52.000Z
#include "pch.h" FARPROC ResolveFunction(char* function, char* dll, BOOL Load) { HMODULE hModule; if (Load) { hModule = ::LoadLibraryA(dll); } else { hModule = ::GetModuleHandleA(dll); } if (hModule == NULL) { printf("[!] Failed to get handle on %s!\n", dll); return NULL; } FARPROC pFunction = ::GetProcAddress(hModule, function); if (hModule == NULL) { printf("[!] Failed to get address of %s!\n", function); return NULL; } else { return pFunction; } } int GetProcessByName(wchar_t* name) { DWORD dwFlags = TH32CS_SNAPPROCESS; DWORD th32ProcessID = 0; HANDLE hSnapshot = ::CreateToolhelp32Snapshot(dwFlags, th32ProcessID); if (hSnapshot == INVALID_HANDLE_VALUE) { printf("[!] Error: %u\n", ::GetLastError()); return -1; } PROCESSENTRY32 pe; pe.dwSize = sizeof(pe); if (::Process32First(hSnapshot, &pe)) { do { if (!_wcsicmp(pe.szExeFile, name)) { return pe.th32ProcessID; } } while (::Process32Next(hSnapshot, &pe)); } ::CloseHandle(hSnapshot); printf("[!] Failed to find %ws!\n", name); return -1; } BOOL SetPrivilege(wchar_t* lpszPrivilege, BOOL bEnablePrivilege) { HANDLE hToken; TOKEN_PRIVILEGES tp; LUID luid; ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken); if (!::LookupPrivilegeValueW(NULL, lpszPrivilege, &luid)) { printf("LookupPrivilegeValueW() failed, error %u\r\n", GetLastError()); return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if (bEnablePrivilege) { tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; } else { tp.Privileges[0].Attributes = SE_PRIVILEGE_REMOVED; } if (!::AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) { printf("AdjustTokenPrivileges() failed, error %u \r\n", GetLastError()); return FALSE; } return TRUE; } PROCESS_INFORMATION CreateProcessUnderExplorer() { int pid; size_t size; PROCESS_INFORMATION pi; STARTUPINFOEX si; wchar_t explorer[] = L"explorer.exe"; wchar_t notepad[] = L"notepad.exe"; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); pid = GetProcessByName(explorer); if (pid == 0) { return pi; } if (pid == -1) { return pi; } HANDLE hProcess = ::OpenProcess(MAXIMUM_ALLOWED, 0, pid); if (!hProcess) { return pi; } si.StartupInfo.cb = sizeof(STARTUPINFOEX); si.StartupInfo.dwFlags = EXTENDED_STARTUPINFO_PRESENT; ::InitializeProcThreadAttributeList(NULL, 1, 0, &size); si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)::HeapAlloc(::GetProcessHeap(), 0, size); ::InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &size); if (si.lpAttributeList == 0) { return pi; } ::UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hProcess, sizeof(hProcess), NULL, NULL); if (CreateProcess(0, notepad, 0, 0, FALSE, EXTENDED_STARTUPINFO_PRESENT, 0, 0, &si.StartupInfo, &pi)) { return pi; } else { return pi; } } DWORD ReadBytes(char* path, LPVOID* shellcode) { HANDLE hFile; DWORD size, readAmount = 0; hFile = CreateFileA(path, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { size = GetFileSize(hFile, 0); *shellcode = malloc(size + 16); ReadFile(hFile, *shellcode, size, &readAmount, 0); CloseHandle(hFile); } return readAmount; } DWORD GetCurrentIntegrity() { DWORD dwIntegrityLevel = 0; DWORD dwError = ERROR_SUCCESS; HANDLE hToken = NULL; DWORD cbTokenIL = 0; PTOKEN_MANDATORY_LABEL pTokenIL = NULL; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { dwError = GetLastError(); goto Cleanup; } if (!GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &cbTokenIL)) { if (ERROR_INSUFFICIENT_BUFFER != GetLastError()) { dwError = GetLastError(); goto Cleanup; } } pTokenIL = (TOKEN_MANDATORY_LABEL*)LocalAlloc(LPTR, cbTokenIL); if (pTokenIL == NULL) { dwError = GetLastError(); goto Cleanup; } if (!GetTokenInformation(hToken, TokenIntegrityLevel, pTokenIL, cbTokenIL, &cbTokenIL)) { dwError = GetLastError(); goto Cleanup; } dwIntegrityLevel = *GetSidSubAuthority(pTokenIL->Label.Sid, 0); Cleanup: if (hToken) { CloseHandle(hToken); hToken = NULL; } if (pTokenIL) { LocalFree(pTokenIL); pTokenIL = NULL; cbTokenIL = 0; } if (ERROR_SUCCESS != dwError) { throw dwError; } return dwIntegrityLevel; }
22.79803
132
0.66465
ScriptIdiot
6e7582ecc2442c469932f589a93c5c973835a973
352
cpp
C++
src/Encryptions/DES.cpp
mugwort-rc/pyOpenPGP
a1d35a93a69ed5bbec768f3c6347742630d71a15
[ "MIT" ]
null
null
null
src/Encryptions/DES.cpp
mugwort-rc/pyOpenPGP
a1d35a93a69ed5bbec768f3c6347742630d71a15
[ "MIT" ]
null
null
null
src/Encryptions/DES.cpp
mugwort-rc/pyOpenPGP
a1d35a93a69ed5bbec768f3c6347742630d71a15
[ "MIT" ]
null
null
null
#include <boost/python.hpp> #include "OpenPGP/Encryptions/DES.h" void DES_init() { boost::python::class_<DES, boost::python::bases<SymAlg>>("DES") .def(boost::python::init<const std::string &>()) .def("decrypt", &DES::decrypt) .def("blocksize", &DES::blocksize) .def("encrypt", &DES::encrypt) .def("setkey", &DES::setkey) ; }
23.466667
63
0.627841
mugwort-rc
6e75f6b18a9a6005dc80df6d97ad188b924729d5
8,840
hpp
C++
applications/GeoMechanicsApplication/custom_elements/transient_Pw_element.hpp
clazaro/Kratos
b947b82c90dfcbf13d60511427f85990d36b90be
[ "BSD-4-Clause" ]
null
null
null
applications/GeoMechanicsApplication/custom_elements/transient_Pw_element.hpp
clazaro/Kratos
b947b82c90dfcbf13d60511427f85990d36b90be
[ "BSD-4-Clause" ]
null
null
null
applications/GeoMechanicsApplication/custom_elements/transient_Pw_element.hpp
clazaro/Kratos
b947b82c90dfcbf13d60511427f85990d36b90be
[ "BSD-4-Clause" ]
null
null
null
// KRATOS___ // // ) ) // // ___ ___ // // ____ //___) ) // ) ) // // / / // // / / // ((____/ / ((____ ((___/ / MECHANICS // // License: geo_mechanics_application/license.txt // // Main authors: Vahid Galavi // #if !defined(KRATOS_GEO_PW_ELEMENT_H_INCLUDED ) #define KRATOS_GEO_PW_ELEMENT_H_INCLUDED // Project includes #include "includes/serializer.h" // Application includes #include "custom_utilities/stress_strain_utilities.hpp" #include "custom_elements/U_Pw_small_strain_element.hpp" #include "custom_utilities/element_utilities.hpp" #include "geo_mechanics_application_variables.h" namespace Kratos { template< unsigned int TDim, unsigned int TNumNodes > class KRATOS_API(GEO_MECHANICS_APPLICATION) TransientPwElement : public UPwSmallStrainElement<TDim, TNumNodes> { public: KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION( TransientPwElement ); typedef UPwSmallStrainElement<TDim, TNumNodes> BaseType; typedef std::size_t IndexType; typedef Properties PropertiesType; typedef Node <3> NodeType; typedef Geometry<NodeType> GeometryType; typedef Geometry<NodeType>::PointsArrayType NodesArrayType; typedef Vector VectorType; typedef Matrix MatrixType; typedef Element::DofsVectorType DofsVectorType; typedef Element::EquationIdVectorType EquationIdVectorType; /// The definition of the sizetype typedef std::size_t SizeType; using BaseType::mRetentionLawVector; using BaseType::mConstitutiveLawVector; using BaseType::mIsInitialised; using BaseType::CalculateRetentionResponse; typedef typename BaseType::ElementVariables ElementVariables; ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /// Default Constructor TransientPwElement(IndexType NewId = 0) : BaseType( NewId ) {} /// Constructor using an array of nodes TransientPwElement(IndexType NewId, const NodesArrayType& ThisNodes) : BaseType(NewId, ThisNodes) {} /// Constructor using Geometry TransientPwElement(IndexType NewId, GeometryType::Pointer pGeometry) : BaseType(NewId, pGeometry) {} /// Constructor using Properties TransientPwElement(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties) : BaseType( NewId, pGeometry, pProperties ) {} /// Destructor ~TransientPwElement() override {} ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Element::Pointer Create( IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties ) const override; Element::Pointer Create( IndexType NewId, GeometryType::Pointer pGeom, PropertiesType::Pointer pProperties ) const override; ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- int Check(const ProcessInfo& rCurrentProcessInfo) const override; void Initialize(const ProcessInfo& rCurrentProcessInfo) override; void InitializeSolutionStep(const ProcessInfo& rCurrentProcessInfo) override; void InitializeNonLinearIteration(const ProcessInfo& rCurrentProcessInfo) override; void FinalizeNonLinearIteration(const ProcessInfo& rCurrentProcessInfo) override; void FinalizeSolutionStep(const ProcessInfo& rCurrentProcessInfo) override; void GetDofList(DofsVectorType& rElementalDofList, const ProcessInfo& rCurrentProcessInfo) const override; void EquationIdVector( EquationIdVectorType& rResult, const ProcessInfo& rCurrentProcessInfo ) const override; void CalculateMassMatrix( MatrixType& rMassMatrix, const ProcessInfo& rCurrentProcessInfo ) override; void CalculateDampingMatrix( MatrixType& rDampingMatrix, const ProcessInfo& rCurrentProcessInfo ) override; void GetValuesVector(Vector& rValues, int Step = 0) const override; void GetFirstDerivativesVector(Vector& rValues, int Step = 0) const override; void GetSecondDerivativesVector(Vector& rValues, int Step = 0) const override; ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void CalculateOnIntegrationPoints(const Variable<double>& rVariable, std::vector<double>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints(const Variable<array_1d<double,3>>& rVariable, std::vector<array_1d<double,3>>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints(const Variable<Matrix>& rVariable, std::vector<Matrix>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; // Turn back information as a string. std::string Info() const override { std::stringstream buffer; buffer << "transient Pw flow Element #" << this->Id() << "\nRetention law: " << mRetentionLawVector[0]->Info(); return buffer.str(); } // Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "transient Pw flow Element #" << this->Id() << "\nRetention law: " << mRetentionLawVector[0]->Info(); } ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- protected: /// Member Variables ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void CalculateAll( MatrixType &rLeftHandSideMatrix, VectorType &rRightHandSideVector, const ProcessInfo& CurrentProcessInfo, const bool CalculateStiffnessMatrixFlag, const bool CalculateResidualVectorFlag ) override; void InitializeElementVariables( ElementVariables &rVariables, const ProcessInfo &CurrentProcessInfo ) override; void CalculateAndAddLHS(MatrixType &rLeftHandSideMatrix, ElementVariables &rVariables) override; void CalculateAndAddRHS(VectorType &rRightHandSideVector, ElementVariables &rVariables, unsigned int GPoint) override; void CalculateKinematics( ElementVariables &rVariables, const unsigned int &PointNumber ) override; void CalculateAndAddCompressibilityMatrix(MatrixType &rLeftHandSideMatrix, ElementVariables& rVariables) override; void CalculateAndAddPermeabilityFlow(VectorType &rRightHandSideVector, ElementVariables& rVariables) override; void CalculateAndAddFluidBodyFlow(VectorType &rRightHandSideVector, ElementVariables &rVariables) override; void CalculateAndAddPermeabilityMatrix(MatrixType &rLeftHandSideMatrix, ElementVariables &rVariables) override; void CalculateAndAddCompressibilityFlow(VectorType &rRightHandSideVector, ElementVariables &rVariables) override; unsigned int GetNumberOfDOF() const override; ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- private: /// Member Variables ///---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /// Serialization friend class Serializer; void save(Serializer& rSerializer) const override { KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, Element ) } void load(Serializer& rSerializer) override { KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, Element ) } // Assignment operator. TransientPwElement & operator=(TransientPwElement const& rOther); // Copy constructor. TransientPwElement(TransientPwElement const& rOther); }; // Class TransientPwElement } // namespace Kratos #endif // KRATOS_GEO_PW_ELEMENT_H_INCLUDED defined
41.895735
181
0.581787
clazaro
6e7601e6390fc6c5baf5e98225104f48ee026593
15,462
cpp
C++
Framewave/domain/fwImage/src/Sqrt.cpp
dbremner/framewave
94babe445689538e6c3b44b1575cca27893b9bb4
[ "Apache-2.0" ]
null
null
null
Framewave/domain/fwImage/src/Sqrt.cpp
dbremner/framewave
94babe445689538e6c3b44b1575cca27893b9bb4
[ "Apache-2.0" ]
1
2019-01-14T04:00:23.000Z
2019-01-14T04:00:23.000Z
Framewave/domain/fwImage/src/Sqrt.cpp
dbremner/framewave
94babe445689538e6c3b44b1575cca27893b9bb4
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2006-2009 Advanced Micro Devices, Inc. All Rights Reserved. This software is subject to the Apache v2.0 License. */ #include "Arithmetic/Def/SqrXDef.h" #include "fwImage.h" using namespace OPT_LEVEL; FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_8u_C1IRSfs )( A8U *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C1::Sqrt_8u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_8u<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C1::Sqrt_8u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_8u<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::C1::Sqrt_8u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_8u<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_8u_C3IRSfs )( A8U *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C3::Sqrt_8u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_8u<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C3::Sqrt_8u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_8u<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::C3::Sqrt_8u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_8u<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_8u_AC4IRSfs)( A8U *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::AC4::Sqrt_8u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_8u<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::AC4::Sqrt_8u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_8u<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::AC4::Sqrt_8u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_8u<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_8u_C1RSfs )( cA8U *s, int sStep, A8U *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C1::Sqrt_8u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_8u<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C1::Sqrt_8u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_8u<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::C1::Sqrt_8u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_8u<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_8u_C3RSfs )( cA8U *s, int sStep, A8U *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C3::Sqrt_8u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_8u<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C3::Sqrt_8u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_8u<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::C3::Sqrt_8u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_8u<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_8u_AC4RSfs )( cA8U *s, int sStep, A8U *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::AC4::Sqrt_8u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_8u<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::AC4::Sqrt_8u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_8u<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::AC4::Sqrt_8u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_8u<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16s_C1IRSfs )( A16S *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C1::Sqrt_16s<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16s<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C1::Sqrt_16s<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16s<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::C1::Sqrt_16s<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16s<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16s_C3IRSfs )( A16S *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C3::Sqrt_16s<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16s<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C3::Sqrt_16s<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16s<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::C3::Sqrt_16s<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16s<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16s_AC4IRSfs)( A16S *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::AC4::Sqrt_16s<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16s<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::AC4::Sqrt_16s<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16s<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::AC4::Sqrt_16s<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16s<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16s_C1RSfs )( cA16S *s, int sStep, A16S *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C1::Sqrt_16s<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16s<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C1::Sqrt_16s<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16s<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::C1::Sqrt_16s<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16s<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16s_C3RSfs )( cA16S *s, int sStep, A16S *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C3::Sqrt_16s<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16s<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C3::Sqrt_16s<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16s<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::C3::Sqrt_16s<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16s<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16s_AC4RSfs )( cA16S *s, int sStep, A16S *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::AC4::Sqrt_16s<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16s<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::AC4::Sqrt_16s<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16s<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::AC4::Sqrt_16s<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16s<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16u_C1IRSfs )( A16U *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C1::Sqrt_16u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16u<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C1::Sqrt_16u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16u<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::C1::Sqrt_16u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16u<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16u_C3IRSfs )( A16U *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C3::Sqrt_16u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16u<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C3::Sqrt_16u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16u<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::C3::Sqrt_16u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16u<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16u_AC4IRSfs)( A16U *sd, int sdStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::AC4::Sqrt_16u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16u<0> >(data, sd, sdStep, sd, sdStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::AC4::Sqrt_16u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16u<-1> >(data, sd, sdStep, sd, sdStep, roi); } else { DEF_SQRX::SQRT::AC4::Sqrt_16u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16u<1> >(data, sd, sdStep, sd, sdStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16u_C1RSfs )( cA16U *s, int sStep, A16U *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C1::Sqrt_16u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16u<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C1::Sqrt_16u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16u<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::C1::Sqrt_16u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_16u<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16u_C3RSfs )( cA16U *s, int sStep, A16U *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::C3::Sqrt_16u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16u<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::C3::Sqrt_16u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16u<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::C3::Sqrt_16u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_16u<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_16u_AC4RSfs )( cA16U *s, int sStep, A16U *d, int dStep, ASZ roi, int scale) { if(scale == 0) { DEF_SQRX::SQRT::AC4::Sqrt_16u<0> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16u<0> > (data, s, sStep, d, dStep, roi); } else if(scale < 0) { DEF_SQRX::SQRT::AC4::Sqrt_16u<-1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16u<-1> >(data, s, sStep, d, dStep, roi); } else { DEF_SQRX::SQRT::AC4::Sqrt_16u<1> data(scale); return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_16u<1> > (data, s, sStep, d, dStep, roi); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_32f_C1IR )( A32F *sd, int sdStep, ASZ roi) { DEF_SQRX::SQRT::C1::Sqrt_32f data; return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_32f>(data, sd, sdStep, sd, sdStep, roi); } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_32f_C3IR )( A32F *sd, int sdStep, ASZ roi) { DEF_SQRX::SQRT::C3::Sqrt_32f data; return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_32f>(data, sd, sdStep, sd, sdStep, roi); } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_32f_AC4IR)( A32F *sd, int sdStep, ASZ roi) { DEF_SQRX::SQRT::AC4::Sqrt_32f data; return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_32f>(data, sd, sdStep, sd, sdStep, roi); } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_32f_C4IR )( A32F *sd, int sdStep, ASZ roi) { DEF_SQRX::SQRT::C4::Sqrt_32f data; return OPT_LEVEL::fe< DEF_SQRX::SQRT::C4::Sqrt_32f>(data, sd, sdStep, sd, sdStep, roi); } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_32f_C1R )( cA32F *s, int sStep, A32F *d, int dStep, ASZ roi) { DEF_SQRX::SQRT::C1::Sqrt_32f data; return OPT_LEVEL::fe< DEF_SQRX::SQRT::C1::Sqrt_32f> (data, s, sStep, d, dStep, roi); } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_32f_C3R )( cA32F *s, int sStep, A32F *d, int dStep, ASZ roi) { DEF_SQRX::SQRT::C3::Sqrt_32f data; return OPT_LEVEL::fe< DEF_SQRX::SQRT::C3::Sqrt_32f> (data, s, sStep, d, dStep, roi); } FwStatus PREFIX_OPT(OPT_PREFIX, fwiSqrt_32f_AC4R )( cA32F *s, int sStep, A32F *d, int dStep, ASZ roi) { DEF_SQRX::SQRT::AC4::Sqrt_32f data; return OPT_LEVEL::fe< DEF_SQRX::SQRT::AC4::Sqrt_32f> (data, s, sStep, d, dStep, roi); } // Please do NOT remove the above line for CPP files that need to be multipass compiled // OREFR OSSE2 OF10H
38.849246
116
0.534213
dbremner
6e7a84cd88396685d4473b5cae04ca691f04212d
1,459
cc
C++
hdoj/tire.cc
baobei813214232/common-alglib
303e4edc5f7c1b5e9a2a6ebc4742d7bae61c5d31
[ "MIT" ]
4
2017-05-02T09:47:48.000Z
2019-05-01T06:26:26.000Z
hdoj/tire.cc
xiaolongnk/Alglib
303e4edc5f7c1b5e9a2a6ebc4742d7bae61c5d31
[ "MIT" ]
null
null
null
hdoj/tire.cc
xiaolongnk/Alglib
303e4edc5f7c1b5e9a2a6ebc4742d7bae61c5d31
[ "MIT" ]
1
2021-01-31T07:21:53.000Z
2021-01-31T07:21:53.000Z
#include <stdio.h> #include <iostream> #include <string.h> using namespace std; struct node { char data; struct node *next[26]; node(){ for(int i=0; i<26; i++){ next[i] = NULL; } } }; void insert(node *root,char *s){ int len = strlen(s); int idx; for(int i=0; i<len; i++){ idx = s[i] - 'a'; if(root->next[idx]){ root = root->next[idx]; }else { root->next[idx] = new node; root = root->next[idx]; root->data = s[i]; } } } void show(node *root,int idx){ if(root){ int cnt = 0; int array[26]; for(int i = 0; i<26; i++){ if(root->next[i]){ array[cnt++] = i; } } for(int i=0; i<cnt/2; i++){ show(root->next[array[i]],idx+5); } for(int i=0; i<idx; i++){ printf(" "); } if(idx==0) printf("root\n"); else printf("%c\n",root->data); for(int i=cnt/2; i<cnt; i++){ show(root->next[array[i]],idx+5); } } } void bfs(node *root){ if(root){ printf("%c",root->data); for(int i=0; i<26;i++){ bfs(root->next[i]); } } } int main(){ node *root = new node; char s[100]; while(scanf("%s",s)!=EOF){ if(s[0]=='-') break; else insert(root,s); } show(root,0); return 0; }
18.948052
45
0.415353
baobei813214232
6e81bf8f276bc39d920598cd7db6f308ad38f9a6
5,799
hpp
C++
src/graphlab/graph/mr_disk_graph_construction_impl.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
1
2018-08-01T06:32:58.000Z
2018-08-01T06:32:58.000Z
src/graphlab/graph/mr_disk_graph_construction_impl.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/graphlab/graph/mr_disk_graph_construction_impl.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef GRAPHLAB_MR_DISK_GRAPH_CONSTRUCTION_IMPL_HPP #define GRAPHLAB_MR_DISK_GRAPH_CONSTRUCTION_IMPL_HPP #include <map> #include <unistd.h> #include <omp.h> #include <graphlab/graph/disk_graph.hpp> #include <graphlab/serialization/serialization_includes.hpp> namespace graphlab { namespace mr_disk_graph_construction_impl { typedef disk_graph<int,int>::vertex_id_type vertex_id_type; vertex_id_type vertex_key_to_id(std::string s) { vertex_id_type vid; decompress_int<vertex_id_type>(s.c_str() + 1, vid); return vid; } std::pair<vertex_id_type, vertex_id_type> edge_key_to_id(std::string s) { ASSERT_EQ(s[0], 'e'); const char *c = s.c_str() + 1; std::pair<vertex_id_type, vertex_id_type> edge; decompress_int_from_ref<vertex_id_type>(c, edge.first); ++c; decompress_int_from_ref<vertex_id_type>(c, edge.second); return edge; } struct atom_properties{ size_t num_local_vertices; size_t num_local_edges; size_t max_color; std::string filename; std::string base_atom_filename; std::map<uint16_t, uint32_t> adjacent_atoms; void save(oarchive& oarc) const { oarc << num_local_vertices << num_local_edges << max_color << filename << base_atom_filename << adjacent_atoms; } void load(iarchive& iarc) { iarc >> num_local_vertices >> num_local_edges >> max_color >> filename >> base_atom_filename >> adjacent_atoms; } }; template <typename VertexData, typename EdgeData> atom_properties merge_parallel_disk_atom(std::vector<std::string> disk_atom_files, std::string base_atom_filename, size_t idx, disk_graph_atom_type::atom_type atomtype) { std::vector<write_only_disk_atom*> atoms; atoms.resize(disk_atom_files.size()); // open the atoms for (size_t i = 0;i < disk_atom_files.size(); ++i) { atoms[i] = new write_only_disk_atom(disk_atom_files[i], idx, false); } std::string output_disk_atom = base_atom_filename; // create the output store graph_atom* atomout = NULL; if (atomtype == disk_graph_atom_type::MEMORY_ATOM) { output_disk_atom += ".fast"; unlink(output_disk_atom.c_str()); atomout = new memory_atom(output_disk_atom, idx); } else if (atomtype == disk_graph_atom_type::WRITE_ONLY_ATOM) { output_disk_atom += ".dump"; unlink(output_disk_atom.c_str()); atomout = new write_only_disk_atom(output_disk_atom, idx, true); } else if (atomtype == disk_graph_atom_type::DISK_ATOM) { unlink(output_disk_atom.c_str()); atomout = new disk_atom(output_disk_atom, idx); } atomout->clear(); volatile uint32_t max_color = 0; // iterate through each database, joining the keys as we see it for (size_t i = 0;i < atoms.size(); ++i) { atoms[i]->play_back(atomout); } atomout->synchronize(); atom_properties ret; ret.adjacent_atoms = atomout->enumerate_adjacent_atoms(); ret.num_local_vertices = atomout->num_vertices(); ret.num_local_edges = atomout->num_edges(); ret.max_color = max_color; ret.filename = output_disk_atom; ret.base_atom_filename = base_atom_filename; std::cout << "Combined atom " << idx << " " << ret.num_local_vertices << " " << ret.num_local_edges << "\n"; for (size_t i = 0;i < disk_atom_files.size(); ++i) { delete atoms[i]; } delete atomout; return ret; } atom_index_file atom_index_from_properties(const std::map<size_t, atom_properties> &atomprops) { atom_index_file idx; std::map<size_t, atom_properties>::const_iterator iter = atomprops.begin(); // compute the graph parameters idx.nverts = 0, idx.nedges = 0, idx.ncolors = 0; idx.natoms = atomprops.size(); idx.atoms.resize(atomprops.size()); while (iter != atomprops.end()) { idx.nverts += iter->second.num_local_vertices; idx.nedges += iter->second.num_local_edges; idx.ncolors = std::max<size_t>(idx.ncolors, iter->second.max_color); // i is the current atom index size_t i = iter->first; idx.atoms[i].protocol = "file"; idx.atoms[i].file = iter->second.base_atom_filename; idx.atoms[i].nverts = iter->second.num_local_vertices; idx.atoms[i].nedges = iter->second.num_local_edges; std::map<uint16_t, uint32_t>::const_iterator iteradj = iter->second.adjacent_atoms.begin(); while (iteradj != iter->second.adjacent_atoms.end()) { idx.atoms[i].adjatoms.push_back(iteradj->first); idx.atoms[i].optional_weight_to_adjatoms.push_back(iteradj->second); ++iteradj; } ++iter; } return idx; } } // namespace } // namespace graphlab #endif
35.576687
114
0.644249
iivek
6e81dcec9630a1c2e954cf272b68ab3816fb45b7
32,135
cpp
C++
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_resource_view.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_resource_view.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_resource_view.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
 #include "rhi_resource_view.d3d12.h" #include "rhi.d3d12.h" #include <array> #include <algorithm> namespace ngl { namespace rhi { // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- ConstantBufferViewDep::ConstantBufferViewDep() { } ConstantBufferViewDep::~ConstantBufferViewDep() { Finalize(); } bool ConstantBufferViewDep::Initialize(BufferDep* p_buffer, const Desc& desc) { if (!p_buffer || !p_buffer->GetParentDevice()) { assert(false); return false; } if (!check_bits(ResourceBindFlag::ConstantBuffer, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } auto&& p_device = p_buffer->GetParentDevice(); auto&& descriptor_allocator = p_device->GetPersistentDescriptorAllocator(); view_ = descriptor_allocator->Allocate(); if (!view_.IsValid()) { std::cout << "[ERROR] ConstantBufferViewDep::Initialize" << std::endl; assert(false); return false; } D3D12_CONSTANT_BUFFER_VIEW_DESC view_desc = {}; view_desc.BufferLocation = p_buffer->GetD3D12Resource()->GetGPUVirtualAddress(); view_desc.SizeInBytes = p_buffer->GetBufferSize();// アライメント考慮サイズを指定している. auto handle = view_.cpu_handle; p_device->GetD3D12Device()->CreateConstantBufferView(&view_desc, handle); return true; } void ConstantBufferViewDep::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- VertexBufferViewDep::VertexBufferViewDep() { } VertexBufferViewDep::~VertexBufferViewDep() { Finalize(); } bool VertexBufferViewDep::Initialize(BufferDep* p_buffer, const Desc& desc) { if (!p_buffer || !p_buffer->GetParentDevice()) { assert(false); return false; } const auto& buffer_desc = p_buffer->GetDesc(); if (!check_bits(ResourceBindFlag::VertexBuffer, buffer_desc.bind_flag)) { assert(false); return false; } auto&& p_device = p_buffer->GetParentDevice(); view_ = {}; view_.SizeInBytes = buffer_desc.element_count * buffer_desc.element_byte_size; view_.StrideInBytes = buffer_desc.element_byte_size; view_.BufferLocation = p_buffer->GetD3D12Resource()->GetGPUVirtualAddress(); return true; } void VertexBufferViewDep::Finalize() { view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- IndexBufferViewDep::IndexBufferViewDep() { } IndexBufferViewDep::~IndexBufferViewDep() { Finalize(); } bool IndexBufferViewDep::Initialize(BufferDep* p_buffer, const Desc& desc) { if (!p_buffer || !p_buffer->GetParentDevice()) { assert(false); return false; } const auto& buffer_desc = p_buffer->GetDesc(); if (!check_bits(ResourceBindFlag::IndexBuffer, buffer_desc.bind_flag)) { assert(false); return false; } auto&& p_device = p_buffer->GetParentDevice(); view_ = {}; view_.SizeInBytes = buffer_desc.element_count * buffer_desc.element_byte_size; view_.BufferLocation = p_buffer->GetD3D12Resource()->GetGPUVirtualAddress(); view_.Format = (buffer_desc.element_byte_size == 4) ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; return true; } void IndexBufferViewDep::Finalize() { view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- SamplerDep::SamplerDep() { } SamplerDep::~SamplerDep() { Finalize(); } bool SamplerDep::Initialize(DeviceDep* p_device, const Desc& desc) { if (!p_device) return false; auto&& descriptor_allocator = p_device->GetPersistentSamplerDescriptorAllocator();// Samplerは専用のAllocatorを利用. view_ = descriptor_allocator->Allocate(); if (!view_.IsValid()) return false; // Persistent上に作成. D3D12_SAMPLER_DESC d3ddesc = {}; d3ddesc.AddressU = ConvertTextureAddressMode(desc.AddressU); d3ddesc.AddressV = ConvertTextureAddressMode(desc.AddressV); d3ddesc.AddressW = ConvertTextureAddressMode(desc.AddressW); d3ddesc.BorderColor[0] = desc.BorderColor[0]; d3ddesc.BorderColor[1] = desc.BorderColor[1]; d3ddesc.BorderColor[2] = desc.BorderColor[2]; d3ddesc.BorderColor[3] = desc.BorderColor[3]; d3ddesc.ComparisonFunc = ConvertComparisonFunc(desc.ComparisonFunc); d3ddesc.Filter = ConvertTextureFilter(desc.Filter); d3ddesc.MaxAnisotropy = desc.MaxAnisotropy; d3ddesc.MaxLOD = desc.MaxLOD; d3ddesc.MinLOD = desc.MinLOD; d3ddesc.MipLODBias = desc.MipLODBias; p_device->GetD3D12Device()->CreateSampler(&(d3ddesc), view_.cpu_handle); return true; } void SamplerDep::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- namespace { /** texture dimension -> view dimension. */ ResourceDimension getTextureDimension(TextureType type, bool is_texture_array) { switch (type) { //case TextureType::Buffer: // assert(is_texture_array == false); // return ResourceDimension::Buffer; case TextureType::Texture1D: return (is_texture_array) ? ResourceDimension::Texture1DArray : ResourceDimension::Texture1D; case TextureType::Texture2D: return (is_texture_array) ? ResourceDimension::Texture2DArray : ResourceDimension::Texture2D; case TextureType::Texture2DMultisample: return (is_texture_array) ? ResourceDimension::Texture2DMSArray : ResourceDimension::Texture2DMS; case TextureType::Texture3D: assert(is_texture_array == false); return ResourceDimension::Texture3D; case TextureType::TextureCube: return (is_texture_array) ? ResourceDimension::TextureCubeArray : ResourceDimension::TextureCube; default: assert(false); return ResourceDimension::Unknown; } } /** view dimension to D3D12 view dimension. */ template<typename ViewType> ViewType getTextureViewDimension(ResourceDimension dimension); // for srv. template<> D3D12_SRV_DIMENSION getTextureViewDimension<D3D12_SRV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_SRV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_SRV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_SRV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_SRV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture2DMS: return D3D12_SRV_DIMENSION_TEXTURE2DMS; case ResourceDimension::Texture2DMSArray: return D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; case ResourceDimension::Texture3D: return D3D12_SRV_DIMENSION_TEXTURE3D; case ResourceDimension::TextureCube: return D3D12_SRV_DIMENSION_TEXTURECUBE; case ResourceDimension::TextureCubeArray: return D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; case ResourceDimension::AccelerationStructure: return D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; default: assert(false); return D3D12_SRV_DIMENSION_UNKNOWN; } } // for uav. template<> D3D12_UAV_DIMENSION getTextureViewDimension<D3D12_UAV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_UAV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_UAV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_UAV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture3D: return D3D12_UAV_DIMENSION_TEXTURE3D; default: assert(false); return D3D12_UAV_DIMENSION_UNKNOWN; } } // for dsv. template<> D3D12_DSV_DIMENSION getTextureViewDimension<D3D12_DSV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_DSV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_DSV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_DSV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_DSV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture2DMS: return D3D12_DSV_DIMENSION_TEXTURE2DMS; case ResourceDimension::Texture2DMSArray: return D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; // TODO: Falcor previously mapped cube to 2D array. Not sure if needed anymore. //case ReflectionResourceType::Dimensions::TextureCube: return D3D12_DSV_DIMENSION_TEXTURE2DARRAY; default: assert(false); return D3D12_DSV_DIMENSION_UNKNOWN; } } // for rtv. template<> D3D12_RTV_DIMENSION getTextureViewDimension<D3D12_RTV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_RTV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_RTV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_RTV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_RTV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture2DMS: return D3D12_RTV_DIMENSION_TEXTURE2DMS; case ResourceDimension::Texture2DMSArray: return D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; case ResourceDimension::Texture3D: return D3D12_RTV_DIMENSION_TEXTURE3D; default: assert(false); return D3D12_RTV_DIMENSION_UNKNOWN; } } // ------------------------------------------------------------------------------------------------------------------------------------------------- // Texture Dsv, Rtv, Uavの設定共通化. template<typename DescType> DescType createDsvRtvUavDescCommon(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { assert(p_texture); // Buffers should not get here uint32_t arrayMultiplier = (p_texture->GetType() == TextureType::TextureCube) ? 6 : 1; if (array_size + first_array_slice > p_texture->GetArraySize()) { array_size = p_texture->GetArraySize() - first_array_slice; } DescType desc = {}; desc.Format = ConvertResourceFormat(p_texture->GetFormat()); desc.ViewDimension = getTextureViewDimension<decltype(desc.ViewDimension)>(getTextureDimension(p_texture->GetType(), p_texture->GetArraySize() > 1)); switch (p_texture->GetType()) { case TextureType::Texture1D: if (p_texture->GetArraySize() > 1) { desc.Texture1DArray.ArraySize = array_size; desc.Texture1DArray.FirstArraySlice = first_array_slice; desc.Texture1DArray.MipSlice = mip_slice; } else { desc.Texture1D.MipSlice = mip_slice; } break; case TextureType::Texture2D: case TextureType::TextureCube: if (p_texture->GetArraySize() * arrayMultiplier > 1) { desc.Texture2DArray.ArraySize = array_size * arrayMultiplier; desc.Texture2DArray.FirstArraySlice = first_array_slice * arrayMultiplier; desc.Texture2DArray.MipSlice = mip_slice; } else { desc.Texture2D.MipSlice = mip_slice; } break; case TextureType::Texture2DMultisample: if constexpr (std::is_same_v<DescType, D3D12_DEPTH_STENCIL_VIEW_DESC> || std::is_same_v<DescType, D3D12_RENDER_TARGET_VIEW_DESC>) { if (p_texture->GetArraySize() > 1) { desc.Texture2DMSArray.ArraySize = array_size; desc.Texture2DMSArray.FirstArraySlice = first_array_slice; } } else { throw std::exception("Texture2DMultisample does not support UAV views"); } break; case TextureType::Texture3D: if constexpr (std::is_same_v<DescType, D3D12_UNORDERED_ACCESS_VIEW_DESC> || std::is_same_v<DescType, D3D12_RENDER_TARGET_VIEW_DESC>) { assert(p_texture->GetArraySize() == 1); desc.Texture3D.MipSlice = mip_slice; desc.Texture3D.FirstWSlice = 0; desc.Texture3D.WSize = p_texture->GetDepth(mip_slice); } else { throw std::exception("Texture3D does not support DSV views"); } break; default: assert(false); } return desc; } // Texture Dsv用. D3D12_DEPTH_STENCIL_VIEW_DESC createDsvDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { return createDsvRtvUavDescCommon<D3D12_DEPTH_STENCIL_VIEW_DESC>(p_texture, mip_slice, first_array_slice, array_size); } // Texture Rtv用. D3D12_RENDER_TARGET_VIEW_DESC createRtvDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { return createDsvRtvUavDescCommon<D3D12_RENDER_TARGET_VIEW_DESC>(p_texture, mip_slice, first_array_slice, array_size); } // Texture Uav用. D3D12_UNORDERED_ACCESS_VIEW_DESC createUavDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { return createDsvRtvUavDescCommon<D3D12_UNORDERED_ACCESS_VIEW_DESC>(p_texture, mip_slice, first_array_slice, array_size); } // Texture Srv用. D3D12_SHADER_RESOURCE_VIEW_DESC createTextureSrvDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t mip_count, uint32_t first_array_slice, uint32_t array_size) { assert(p_texture); D3D12_SHADER_RESOURCE_VIEW_DESC desc = {}; //If not depth, returns input format desc.Format = ConvertResourceFormat(depthToColorFormat(p_texture->GetFormat())); bool isTextureArray = p_texture->GetArraySize() > 1; desc.ViewDimension = getTextureViewDimension<D3D12_SRV_DIMENSION>(getTextureDimension(p_texture->GetType(), isTextureArray)); switch (p_texture->GetType()) { case TextureType::Texture1D: if (isTextureArray) { desc.Texture1DArray.MipLevels = mip_count; desc.Texture1DArray.MostDetailedMip = mip_slice; desc.Texture1DArray.ArraySize = array_size; desc.Texture1DArray.FirstArraySlice = first_array_slice; } else { desc.Texture1D.MipLevels = mip_count; desc.Texture1D.MostDetailedMip = mip_slice; } break; case TextureType::Texture2D: if (isTextureArray) { desc.Texture2DArray.MipLevels = mip_count; desc.Texture2DArray.MostDetailedMip = mip_slice; desc.Texture2DArray.ArraySize = array_size; desc.Texture2DArray.FirstArraySlice = first_array_slice; } else { desc.Texture2D.MipLevels = mip_count; desc.Texture2D.MostDetailedMip = mip_slice; } break; case TextureType::Texture2DMultisample: if (array_size > 1) { desc.Texture2DMSArray.ArraySize = array_size; desc.Texture2DMSArray.FirstArraySlice = first_array_slice; } break; case TextureType::Texture3D: assert(array_size == 1); desc.Texture3D.MipLevels = mip_count; desc.Texture3D.MostDetailedMip = mip_slice; break; case TextureType::TextureCube: if (array_size > 1) { desc.TextureCubeArray.First2DArrayFace = 0; desc.TextureCubeArray.NumCubes = array_size; desc.TextureCubeArray.MipLevels = mip_count; desc.TextureCubeArray.MostDetailedMip = mip_slice; } else { desc.TextureCube.MipLevels = mip_count; desc.TextureCube.MostDetailedMip = mip_slice; } break; default: assert(false); } desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; return desc; } struct BufferViewMode { enum Type : u32 { // Typed Buffer View. Typed, // Structured な buffer view. Structured, // 4 Byte per element な raw buffer view. ByteAddress }; }; D3D12_SHADER_RESOURCE_VIEW_DESC createBufferSrvDesc(const BufferDep* pBuffer // 初期化モード. , BufferViewMode::Type mode // 初期化モードTyped の場合の要素フォーマットタイプ. , ResourceFormat typed_format // 初期化モードStructured の場合の要素サイズ. , u32 structured_element_size , u32 element_offset, u32 element_count) { assert(pBuffer); D3D12_SHADER_RESOURCE_VIEW_DESC desc = {}; u32 bufferElementCount = 0; if (BufferViewMode::Typed == mode) { // Typed. bufferElementCount = pBuffer->getElementCount(); desc.Format = ConvertResourceFormat(typed_format); } else if (BufferViewMode::Structured == mode) { // Structured. bufferElementCount = pBuffer->getElementCount(); desc.Format = DXGI_FORMAT_UNKNOWN; desc.Buffer.StructureByteStride = structured_element_size; } else { // ByteAddress. bufferElementCount = pBuffer->getElementCount(); desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; } assert((element_offset + element_count) <= bufferElementCount); // Check range desc.Buffer.FirstElement = element_offset; desc.Buffer.NumElements = element_count; desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; return desc; } D3D12_UNORDERED_ACCESS_VIEW_DESC createBufferUavDesc(const BufferDep* p_buffer // 初期化モード. , BufferViewMode::Type mode // 初期化モードTyped の場合の要素フォーマットタイプ. , ResourceFormat typed_format // 初期化モードStructured の場合の要素サイズ. , u32 structured_element_size , u32 element_offset, u32 element_count) { assert(p_buffer); D3D12_UNORDERED_ACCESS_VIEW_DESC desc = {}; u32 bufferElementCount = 0; if (BufferViewMode::Typed == mode) { // Typed. bufferElementCount = p_buffer->getElementCount(); desc.Format = ConvertResourceFormat(typed_format); } else if (BufferViewMode::Structured == mode) { // Structured. bufferElementCount = p_buffer->getElementCount(); desc.Format = DXGI_FORMAT_UNKNOWN; desc.Buffer.StructureByteStride = structured_element_size; } else { // ByteAddress. bufferElementCount = p_buffer->getElementCount(); desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; } assert((element_offset + element_count) <= bufferElementCount); // Check range desc.Buffer.FirstElement = element_offset; desc.Buffer.NumElements = element_count; desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; return desc; } } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- DepthStencilViewDep::DepthStencilViewDep() { } DepthStencilViewDep::~DepthStencilViewDep() { Finalize(); } bool DepthStencilViewDep::Initialize(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 first_array_slice, u32 array_size) { assert(p_device); assert(p_texture); if (!check_bits(ResourceBindFlag::DepthStencil, p_texture->GetBindFlag())) { assert(false); return false; } // 専有Heap確保. D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; heap_desc.NumDescriptors = 1; heap_desc.NodeMask = 0; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; if (FAILED(p_device->GetD3D12Device()->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&p_heap_)))) { std::cout << "[ERROR] Create DescriptorHeap" << std::endl; return false; } // 専有HeapにDescriptor作成. D3D12_DEPTH_STENCIL_VIEW_DESC desc = createDsvDesc(p_texture, mip_slice, first_array_slice, array_size); p_device->GetD3D12Device()->CreateDepthStencilView(p_texture->GetD3D12Resource(), &desc, p_heap_->GetCPUDescriptorHandleForHeapStart()); return true; } void DepthStencilViewDep::Finalize() { p_heap_.Release(); } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- RenderTargetViewDep::RenderTargetViewDep() { } RenderTargetViewDep::~RenderTargetViewDep() { Finalize(); } bool RenderTargetViewDep::Initialize(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 first_array_slice, u32 array_size) { assert(p_device); assert(p_texture); if (!check_bits(ResourceBindFlag::RenderTarget, p_texture->GetBindFlag())) { assert(false); return false; } // 専有Heap確保. D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; heap_desc.NumDescriptors = 1; heap_desc.NodeMask = 0; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; if (FAILED(p_device->GetD3D12Device()->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&p_heap_)))) { std::cout << "[ERROR] Create DescriptorHeap" << std::endl; return false; } // 専有HeapにDescriptor作成. { D3D12_RENDER_TARGET_VIEW_DESC desc = createRtvDesc(p_texture, mip_slice, first_array_slice, array_size); p_device->GetD3D12Device()->CreateRenderTargetView(p_texture->GetD3D12Resource(), &desc, p_heap_->GetCPUDescriptorHandleForHeapStart()); } return true; } // SwapChainからRTV作成. bool RenderTargetViewDep::Initialize(DeviceDep* p_device, SwapChainDep* p_swapchain, unsigned int buffer_index) { if (!p_device || !p_swapchain) return false; // 専有Heap確保. D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; heap_desc.NumDescriptors = 1; heap_desc.NodeMask = 0; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; if (FAILED(p_device->GetD3D12Device()->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&p_heap_)))) { std::cout << "[ERROR] Create DescriptorHeap" << std::endl; return false; } auto* buffer = p_swapchain->GetD3D12Resource(buffer_index); if (!buffer) { std::cout << "[ERROR] Invalid Buffer Index" << std::endl; return false; } auto handle_head = p_heap_->GetCPUDescriptorHandleForHeapStart(); p_device->GetD3D12Device()->CreateRenderTargetView(buffer, nullptr, handle_head); return true; } void RenderTargetViewDep::Finalize() { p_heap_.Release(); } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- UnorderedAccessView::UnorderedAccessView() { } UnorderedAccessView::~UnorderedAccessView() { Finalize(); } template<typename ResourceType> bool _Initialize(DeviceDep* p_device, const ResourceType* p_buffer, const D3D12_UNORDERED_ACCESS_VIEW_DESC& desc, PersistentDescriptorInfo& out_desc_info) { // Descriptor確保. auto&& descriptor_allocator = p_device->GetPersistentDescriptorAllocator(); out_desc_info = descriptor_allocator->Allocate(); if (!out_desc_info.IsValid()) { std::cout << "[ERROR] ShaderResourceViewDep::InitializeAsStructured" << std::endl; assert(false); return false; } constexpr ID3D12Resource* p_counter_resource = nullptr; p_device->GetD3D12Device()->CreateUnorderedAccessView(p_buffer->GetD3D12Resource(), p_counter_resource, &desc, out_desc_info.cpu_handle); return true; } // TextureのView. bool UnorderedAccessView::Initialize(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 first_array_slice, u32 array_size) { assert(p_device && p_texture); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_texture->GetBindFlag())) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createUavDesc(p_texture, mip_slice, first_array_slice, array_size); return _Initialize(p_device, p_texture, desc, view_); } // BufferのStructuredBufferView. bool UnorderedAccessView::InitializeAsStructured(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_size, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createBufferUavDesc(p_buffer, BufferViewMode::Structured, {}, element_size, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのTypedBufferView. bool UnorderedAccessView::InitializeAsTyped(DeviceDep* p_device, const BufferDep* p_buffer, ResourceFormat format, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createBufferUavDesc(p_buffer, BufferViewMode::Typed, format, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのByteAddressBufferView. bool UnorderedAccessView::InitializeAsRaw(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createBufferUavDesc(p_buffer, BufferViewMode::ByteAddress, {}, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } void UnorderedAccessView::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- ShaderResourceViewDep::ShaderResourceViewDep() { } ShaderResourceViewDep::~ShaderResourceViewDep() { Finalize(); } template<typename ResourceType> bool _Initialize(DeviceDep* p_device, const ResourceType* p_buffer, const D3D12_SHADER_RESOURCE_VIEW_DESC& desc, PersistentDescriptorInfo& out_desc_info) { // Descriptor確保. auto&& descriptor_allocator = p_device->GetPersistentDescriptorAllocator(); out_desc_info = descriptor_allocator->Allocate(); if (!out_desc_info.IsValid()) { std::cout << "[ERROR] ShaderResourceViewDep::InitializeAsStructured" << std::endl; assert(false); return false; } p_device->GetD3D12Device()->CreateShaderResourceView(p_buffer->GetD3D12Resource(), &desc, out_desc_info.cpu_handle); return true; } // TextureのView. bool ShaderResourceViewDep::InitializeAsTexture(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 mip_count, u32 first_array_slice, u32 array_size) { assert(p_device && p_texture); if (!p_device || !p_texture) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_texture->GetBindFlag())) { assert(false); return false; } // clamp mip, array range. if (mip_slice >= p_texture->GetMipCount()) { mip_slice = p_texture->GetMipCount() - 1; mip_count = 1; } else if ((mip_count == 0) || (mip_count > p_texture->GetMipCount() - mip_slice)) { mip_count = p_texture->GetMipCount() - mip_slice; } if (first_array_slice >= p_texture->GetArraySize()) { first_array_slice = p_texture->GetArraySize() - 1; array_size = 1; } else if ((array_size == 0) || (array_size > p_texture->GetArraySize() - first_array_slice)) { array_size = p_texture->GetArraySize() - first_array_slice; } // Desc生成. auto desc = createTextureSrvDesc(p_texture, mip_slice, mip_count, first_array_slice, array_size); return _Initialize(p_device, p_texture, desc, view_); } // BufferのStructuredBufferView. bool ShaderResourceViewDep::InitializeAsStructured(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_size, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!p_device || !p_buffer) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_SHADER_RESOURCE_VIEW_DESC desc = createBufferSrvDesc(p_buffer, BufferViewMode::Structured, {}, element_size, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのTypedBufferView. bool ShaderResourceViewDep::InitializeAsTyped(DeviceDep* p_device, const BufferDep* p_buffer, ResourceFormat format, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!p_device || !p_buffer) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_SHADER_RESOURCE_VIEW_DESC desc = createBufferSrvDesc(p_buffer, BufferViewMode::Typed, format, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのByteAddressBufferView. bool ShaderResourceViewDep::InitializeAsRaw(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!p_device || !p_buffer) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_SHADER_RESOURCE_VIEW_DESC desc = createBufferSrvDesc(p_buffer, BufferViewMode::ByteAddress, {}, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } void ShaderResourceViewDep::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- } }
35.390969
173
0.647394
nagakagachi
6e8df8ed79087855af3e93aa0c25fdda8d0629db
11,956
hpp
C++
include/frechetrange/detail/bb/spatial_index.hpp
TWTDIG/frechetrange
b5b30708a7d2ec181ed6a870923542e286f894ab
[ "MIT" ]
5
2018-03-24T02:40:36.000Z
2020-08-31T02:50:49.000Z
include/frechetrange/detail/bb/spatial_index.hpp
TWTDIG/frechetrange
b5b30708a7d2ec181ed6a870923542e286f894ab
[ "MIT" ]
9
2017-11-22T11:09:52.000Z
2018-03-03T09:55:01.000Z
include/frechetrange/detail/bb/spatial_index.hpp
TWTDIG/frechetrange
b5b30708a7d2ec181ed6a870923542e286f894ab
[ "MIT" ]
3
2017-11-21T07:29:32.000Z
2019-12-22T15:50:47.000Z
#ifndef BB_SPATIAL_INDEX_HPP #define BB_SPATIAL_INDEX_HPP #include <algorithm> // for std::max and std::min #include <array> #include <cmath> // for std::sqrt and std::abs #include <memory> // for std::unique_ptr #include <utility> // for std::pair #include <vector> #include "frechet_distance.hpp" namespace frechetrange { namespace detail { namespace bb { // TODO: multidimensional // A point in the n-dimensional space template <size_t dimensions> using nd_point = std::array<distance_t, dimensions>; // ----------- quadtree ----------- template <size_t dimensions> distance_t nd_point_dist(const nd_point<dimensions> &a, const nd_point<dimensions> &b); template <> distance_t nd_point_dist(const nd_point<8> &a, const nd_point<8> &b) { distance_t result = 0; for (size_t i = 0; i < 4; i += 2) { result = std::max( result, std::sqrt(sqr(a[i] - b[i]) + sqr(a[i + 1] - b[i + 1]))); } for (size_t i = 4; i < 8; ++i) { result = std::max(result, std::abs(a[i] - b[i])); } return result; } constexpr long long constexpr_power(long long base, long long exponent) { return (exponent == 0) ? 1 : base * constexpr_power(base, exponent - 1); } // Returns true iff the i-th lowest bit (starting at 0) in number is 1. constexpr bool bit_is_set(long long number, size_t i) { return (number & (static_cast<size_t>(1) << i)) != 0; } template <size_t dimensions, typename element, size_t max_elments_per_node> struct quadtree_node { typedef nd_point<dimensions> point; std::array<std::unique_ptr<quadtree_node>, constexpr_power(2, dimensions)> _children; point _min_coords, _max_coords; std::vector<std::pair<point, element>> _elements; bool _has_children; quadtree_node(const point &min_coords, const point &max_coords) : _children(), _min_coords(min_coords), _max_coords(max_coords), _elements(), _has_children(false) {} std::vector<element> get(const point &center, distance_t radius) const { std::vector<element> result; get_recursive(center, radius, result); return result; } void get_recursive(const point &center, distance_t radius, std::vector<element> &result) const { bool covered = true; for (size_t i = 0; i < dimensions; ++i) { if (_min_coords[i] > center[i] + radius || _max_coords[i] < center[i] - radius) { return; // circle does not intersect current area } if (_min_coords[i] < center[i] - radius || _max_coords[i] > center[i] + radius) { covered = false; } } if (_has_children && !covered) { for (auto &child : _children) { child->get_recursive(center, radius, result); } } else { for (const std::pair<point, element> &e : _elements) { if (nd_point_dist(center, e.first) <= radius) { result.push_back(e.second); } } } } size_t get_child_id(const point &position) const { size_t result = 0; for (int i = dimensions - 1; i >= 0; --i) { bool high = position[i] >= (_min_coords[i] + _max_coords[i]) / 2; result = 2 * result + high; } return result; } void add(const element &e, const point &position) { _elements.push_back(std::make_pair(position, e)); if (_has_children) { _children[get_child_id(position)]->add(e, position); } else { if (_elements.size() > max_elments_per_node) split(); } } void split() { bool splittable = false; for (size_t i = 1; i < _elements.size(); ++i) { if (_elements[i].first != _elements[i - 1].first) { splittable = true; break; } } if (!splittable) return; for (size_t i = 0; i < _children.size(); ++i) { point mini = _min_coords, maxi = _max_coords; for (size_t j = 0; j < dimensions; ++j) { distance_t center = (_min_coords[j] + _max_coords[j]) / 2; if (bit_is_set(i, j)) { mini[j] = center; } else { maxi[j] = center; } } _children[i] = std::unique_ptr<quadtree_node>(new quadtree_node(mini, maxi)); } _has_children = true; for (auto &e : _elements) { _children[get_child_id(e.first)]->add(e.second, e.first); } } }; template <size_t dimensions, typename element, size_t max_elments_per_node = constexpr_power(2, dimensions)> using quadtree = quadtree_node<dimensions, element, max_elments_per_node>; // ----------- spatial_index ----------- template <size_t dimensions, typename trajectory, typename get_coordinate, typename squared_distance = euclidean_distance_sqr<dimensions, get_coordinate>> class spatial_index { public: spatial_index(const squared_distance &dist2 = squared_distance()) : _q({{MIN_X, MIN_Y, MIN_X, MIN_Y, MIN_X, MIN_Y, MIN_X, MIN_Y}}, {{MAX_X, MAX_Y, MAX_X, MAX_Y, MAX_X, MAX_Y, MAX_X, MAX_Y}}), _curves(), _dist2(dist2), _frechet_dist(dist2) {} size_t size() const { return _curves.size(); } void insert(const trajectory &t) { _q.add(_curves.size(), get_position(t)); _curves.emplace_back(t, _dist2); } // Returns the ids of all trajectories that may have frechet distance d or // less. // The result may however contain some whose frechet distance to c is too // large. std::vector<const trajectory *> range_query(const trajectory &t, distance_t d) const { std::vector<const trajectory *> result_set; auto push_back_result = [&result_set](const trajectory &t) { result_set.push_back(&t); }; range_query(t, d, push_back_result); return result_set; } template <typename output_func> void range_query(const trajectory &t, distance_t d, output_func &output) const { // TODO: don't copy t curve<trajectory> c(t, _dist2); std::vector<size_t> potential_curves = _q.get(get_position(t), d); for (size_t i : potential_curves) { const curve<trajectory> &c2 = _curves[i]; if (get_frechet_distance_upper_bound(t, c2.get_trajectory()) <= sqr(d)) { output(c2.get_trajectory()); } else if (negfilter(c, c2, d)) { continue; } else if (_frechet_dist.is_bounded_by(c, c2, d)) { output(c2.get_trajectory()); } } } private: static constexpr distance_t MIN_X = -1e18l, MIN_Y = -1e18l, MAX_X = 1e18l, MAX_Y = 1e18l; quadtree<8, size_t> _q; // first x, first y, last x, last y, min x, min y, max x, max y std::vector<curve<trajectory>> _curves; squared_distance _dist2; frechet_distance<dimensions, get_coordinate, squared_distance> _frechet_dist; template <typename point_t> distance_t dist(point_t &p, point_t &q) const { return std::sqrt(_dist2(p, q)); } nd_point<8> get_position(const trajectory &t) const { size_t last = t.size() - 1; nd_point<8> p = {{get_coordinate::template get<0>(t[0]), get_coordinate::template get<1>(t[0]), get_coordinate::template get<0>(t[last]), get_coordinate::template get<1>(t[last]), MAX_X, MAX_Y, MIN_X, MIN_Y}}; for (size_t i = 0; i <= last; ++i) { p[4] = std::min(p[4], get_coordinate::template get<0>(t[i])); p[5] = std::min(p[5], get_coordinate::template get<1>(t[i])); p[6] = std::max(p[6], get_coordinate::template get<0>(t[i])); p[7] = std::max(p[7], get_coordinate::template get<1>(t[i])); } return p; } // ----------- filters ----------- /* * Calculates an upper bound for the squared Frechet distance of a and b by * guessing a matching between a and b * O(a.size() + b.size()) */ distance_t get_frechet_distance_upper_bound(const trajectory &a, const trajectory &b) const { distance_t sqrd_dist = _dist2(a[a.size() - 1], b[b.size() - 1]); size_t pos_a = 0, pos_b = 0; while (pos_a + pos_b < a.size() + b.size() - 2) { sqrd_dist = std::max(sqrd_dist, _dist2(a[pos_a], b[pos_b])); if (pos_a == a.size() - 1) ++pos_b; else if (pos_b == b.size() - 1) ++pos_a; else { distance_t dist_a = _dist2(a[pos_a + 1], b[pos_b]); distance_t dist_b = _dist2(a[pos_a], b[pos_b + 1]); distance_t dist_both = _dist2(a[pos_a + 1], b[pos_b + 1]); if (dist_a < dist_b && dist_a < dist_both) { ++pos_a; } else if (dist_b < dist_both) { ++pos_b; } else { ++pos_a; ++pos_b; } } } return sqrd_dist; } /* * Returns (a discrete approximation of) the first point c[j] on c, with j * >= * i, that is within distance d of point p. */ template <typename point_t> size_t nextclosepoint(const curve<trajectory> &c, size_t i, const point_t &p, distance_t d) const { const trajectory &t = c.get_trajectory(); size_t delta = 1; size_t k = i; while (true) { if (k == t.size() - 1) { if (_dist2(t[k], p) <= sqr(d)) { return k; } else { return c.size(); } } else { delta = std::min(delta, t.size() - 1 - k); if (dist(p, t[k]) - c.curve_length(k, k + delta) > d) { k += delta; delta *= 2; } else if (delta > 1) { delta /= 2; } else { return k; } } } } /* * Tries to show that the Frechet distance of a and b is more than d. * Returns * true if a proof is found. */ bool negfilter(const curve<trajectory> &c1, const curve<trajectory> &c2, distance_t d) const { for (size_t delta = std::max(c1.size(), c2.size()) - 1; delta >= 1; delta /= 2) { size_t i = 0; for (size_t j = 0; j < c2.size(); j += delta) { i = nextclosepoint(c1, i, c2.get_trajectory()[j], d); if (i >= c1.size()) { return true; } } size_t j = 0; for (size_t i = 0; i < c1.size(); i += delta) { j = nextclosepoint(c2, j, c1.get_trajectory()[i], d); if (j >= c2.size()) { return true; } } } return false; } }; } // namespace bb } // namespace detail } // namespace frechetrange #endif
34.655072
93
0.505353
TWTDIG
6e8ed7dc5bcc95a9ffc0a61de4edc4429711ae1e
4,144
inl
C++
include/as/as-mat.inl
pr0g/as
5698ded06abca884385b9deebe8a2e702e8a66a8
[ "MIT" ]
6
2019-06-16T22:20:55.000Z
2021-11-13T17:16:16.000Z
include/as/as-mat.inl
pr0g/as
5698ded06abca884385b9deebe8a2e702e8a66a8
[ "MIT" ]
null
null
null
include/as/as-mat.inl
pr0g/as
5698ded06abca884385b9deebe8a2e702e8a66a8
[ "MIT" ]
1
2020-04-11T14:24:13.000Z
2020-04-11T14:24:13.000Z
namespace as { template<typename T, index d> AS_API mat<T, d> mat_identity() { mat<T, d> identity{}; for (index i = 0; i < mat<T, d>::size(); i += d + 1) { identity[i] = T(1.0); } return identity; } template<typename T, index d> AS_API constexpr index mat<T, d>::dim() { return d; } template<typename T, index d> AS_API constexpr index mat<T, d>::size() { return d * d; } template<typename T, index d> AS_API constexpr index mat<T, d>::rows() { return mat<T, d>::dim(); } template<typename T, index d> AS_API constexpr index mat<T, d>::cols() { return mat<T, d>::dim(); } template<typename T, index d> AS_API mat<T, d> mat<T, d>::identity() { return mat_identity<T, d>(); } template<typename T, index d> AS_API constexpr T& mat<T, d>::operator[](const index i) & { return elem_rc[i]; } template<typename T, index d> AS_API constexpr const T& mat<T, d>::operator[](const index i) const& { return elem_rc[i]; } template<typename T, index d> AS_API constexpr const T mat<T, d>::operator[](const index i) && { return elem_rc[i]; } template<typename T, index d> AS_API const mat<T, d> operator*(const mat<T, d>& lhs, const mat<T, d>& rhs) { mat<T, d> result; #ifdef AS_COL_MAJOR for (index col = 0; col < d; ++col) { for (index row = 0; row < d; ++row) { auto value = T(0.0); for (index step = 0; step < d; ++step) { value += lhs[row + d * step] * rhs[col * d + step]; } result[col * d + row] = value; } } #elif defined AS_ROW_MAJOR for (index row = 0; row < d; ++row) { for (index col = 0; col < d; ++col) { auto value = T(0.0); for (index step = 0; step < d; ++step) { value += lhs[row * d + step] * rhs[col + d * step]; } result[row * d + col] = value; } } #endif // AS_ROW_MAJOR ? AS_COL_MAJOR return result; } template<typename T, index d> #ifdef AS_ROW_MAJOR AS_API const vec<T, d> operator*(const vec<T, d>& v, const mat<T, d>& m) #elif defined AS_COL_MAJOR AS_API const vec<T, d> operator*(const mat<T, d>& m, const vec<T, d>& v) #endif // AS_ROW_MAJOR ? AS_COL_MAJOR { vec<T, d> result; for (index i = 0; i < d; ++i) { auto value = T(0.0); for (index step = 0; step < d; ++step) { value += v[step] * m[i + step * d]; } result[i] = value; } return result; } template<typename T, index d> AS_API constexpr const mat<T, d> operator*(const mat<T, d>& m, const T scalar) { mat<T, d> result{m}; result *= scalar; return result; } template<typename T, index d> AS_API constexpr mat<T, d>& operator*=(mat<T, d>& m, const T scalar) { for (index row = 0; row < d; ++row) { for (index col = 0; col < d; ++col) { m[row * d + col] *= scalar; } } return m; } template<typename T, index d> AS_API constexpr bool operator==(const mat<T, d>& lhs, const mat<T, d>& rhs) { return !(lhs != rhs); } template<typename T, index d> AS_API constexpr bool operator!=(const mat<T, d>& lhs, const mat<T, d>& rhs) { for (index row = 0; row < d; ++row) { for (index col = 0; col < d; ++col) { const index lookup = row * d + col; if (lhs[lookup] != rhs[lookup]) { return true; } } } return false; } template<typename T, index d> AS_API constexpr subscript_iterator<mat<T, d>> begin(mat<T, d>& m) { return subscript_iterator<mat<T, d>>(m, 0); } template<typename T, index d> AS_API constexpr subscript_iterator<mat<T, d>> end(mat<T, d>& m) { return subscript_iterator<mat<T, d>>(m, mat<T, d>::size()); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> begin(const mat<T, d>& m) { return subscript_const_iterator<mat<T, d>>(m, 0); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> end(const mat<T, d>& m) { return subscript_const_iterator<mat<T, d>>(m, mat<T, d>::size()); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> cbegin(const mat<T, d>& m) { return begin(m); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> cend(const mat<T, d>& m) { return end(m); } } // namespace as
22.521739
79
0.610521
pr0g
6e8fa2fb56d06ebf06acaaa2e29e4db377dfd422
1,196
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR/List`1_Reverse/cpp/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR/List`1_Reverse/cpp/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR/List`1_Reverse/cpp/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet1> using namespace System; using namespace System::Collections::Generic; void main() { List<String^>^ dinosaurs = gcnew List<String^>(); dinosaurs->Add("Pachycephalosaurus"); dinosaurs->Add("Parasauralophus"); dinosaurs->Add("Mamenchisaurus"); dinosaurs->Add("Amargasaurus"); dinosaurs->Add("Coelophysis"); dinosaurs->Add("Oviraptor"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs) { Console::WriteLine(dinosaur); } dinosaurs->Reverse(); Console::WriteLine(); for each(String^ dinosaur in dinosaurs) { Console::WriteLine(dinosaur); } dinosaurs->Reverse(1, 4); Console::WriteLine(); for each(String^ dinosaur in dinosaurs) { Console::WriteLine(dinosaur); } } /* This code example produces the following output: Pachycephalosaurus Parasauralophus Mamenchisaurus Amargasaurus Coelophysis Oviraptor Oviraptor Coelophysis Amargasaurus Mamenchisaurus Parasauralophus Pachycephalosaurus Oviraptor Parasauralophus Mamenchisaurus Amargasaurus Coelophysis Pachycephalosaurus */ // </Snippet1>
18.4
54
0.664716
hamarb123
6e9167bc0867048bff0f11a078a6b739187a31a6
8,478
cpp
C++
Module/Components/TextureVideoPlayerComponent.cpp
afrostalin/CEVPlayer
5e91493a11b4c294d3582b80dae4ea2d95856a7d
[ "BSL-1.0" ]
14
2018-03-16T10:08:12.000Z
2021-04-13T21:11:53.000Z
Module/Components/TextureVideoPlayerComponent.cpp
afrostalin/CryVideoPlayer
5e91493a11b4c294d3582b80dae4ea2d95856a7d
[ "BSL-1.0" ]
4
2018-03-06T01:52:36.000Z
2021-04-26T07:25:07.000Z
Module/Components/TextureVideoPlayerComponent.cpp
afrostalin/CEVPlayer
5e91493a11b4c294d3582b80dae4ea2d95856a7d
[ "BSL-1.0" ]
8
2018-06-14T13:09:13.000Z
2021-04-13T21:11:57.000Z
// Copyright (C) 2017-2020 Ilya Chernetsov. All rights reserved. Contacts: <chernecoff@gmail.com> // License: https://github.com/afrostalin/CEVPlayer/blob/master/LICENSE #include "StdAfx.h" #include "PluginEnv.h" #include "TextureVideoPlayerComponent.h" #include "Video/TextureVideoQueue.h" #include <CrySchematyc/Utils/EnumFlags.h> #include <CrySchematyc/Env/Elements/EnvComponent.h> #include <CrySchematyc/Env/Elements/EnvFunction.h> #include <CrySchematyc/Env/Elements/EnvSignal.h> #include <CrySchematyc/ResourceTypes.h> #include <CrySchematyc/MathTypes.h> #include <CrySchematyc/IObject.h> namespace CEVPlayer { static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnStartPlaySignal>& desc) { desc.SetGUID("672B590C-E387-4357-BDD0-A3C3884277C5"_cry_guid); desc.SetLabel("OnStartPlay"); desc.SetDescription("Executed when video start playing to texture"); } static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnPausedSignal>& desc) { desc.SetGUID("92C48065-FC02-4CD3-A609-AF6384498627"_cry_guid); desc.SetLabel("OnPaused"); desc.SetDescription("Executed when video paused"); } static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnResumedSignal>& desc) { desc.SetGUID("176C5938-389B-470F-886D-CD13A82D9744"_cry_guid); desc.SetLabel("OnResumed"); desc.SetDescription("Executed when video resumed"); } static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnStoppedSignal>& desc) { desc.SetGUID("7F0EFF91-47B4-45F1-982E-F15613C9D4FB"_cry_guid); desc.SetLabel("OnStopped"); desc.SetDescription("Executed when video stopped"); } void CTextureVideoPlayerComponent::Register(Schematyc::CEnvRegistrationScope& componentScope) { { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Play, "1240FF98-3145-48BD-B282-4AEC7D647C1D"_cry_guid, "Play"); pFunction->SetDescription("Start play video to texture"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); pFunction->BindInput(1, 'val1', "VideoFilename", "Video file name without folder and extension (e.g. logo)"); pFunction->BindInput(2, 'val2', "OutputTextureName", "Output texture name for using in materials. Can't be null"); pFunction->BindInput(3, 'val3', "IsPreloaded", "File will be preloaded in memory before playing"); pFunction->BindInput(4, 'val4', "IsLooped", "Video can be looped here"); pFunction->BindInput(5, 'val5', "CanPlayInEditor", "Video can be play in editor"); componentScope.Register(pFunction); } { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Pause, "33121C57-8DDE-4845-9357-F4E34F6E77C9"_cry_guid, "Pause"); pFunction->SetDescription("Pause current playing video"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); componentScope.Register(pFunction); } { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Resume, "B6D31737-C79E-4A36-874D-A685A7C6E9FC"_cry_guid, "Resume"); pFunction->SetDescription("Resume paused video"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); componentScope.Register(pFunction); } { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Stop, "1EA6B0BD-4ED5-4C66-9AE0-1CC92DAD6AF7"_cry_guid, "Stop"); pFunction->SetDescription("Stop playing video"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); componentScope.Register(pFunction); } componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnStartPlaySignal)); componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnPausedSignal)); componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnResumedSignal)); componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnStoppedSignal)); } void CTextureVideoPlayerComponent::ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent>& desc) { desc.SetGUID("1AE1AB31-50A4-4D83-BAF0-FFB48CABF0B2"_cry_guid); desc.SetEditorCategory("Video"); desc.SetLabel("TextureVideoPlayer"); desc.SetDescription("Play video to texture"); desc.SetIcon("icons:General/Camera.ico"); desc.SetComponentFlags({ IEntityComponent::EFlags::Attach, IEntityComponent::EFlags::ClientOnly }); desc.AddMember(&CTextureVideoPlayerComponent::m_IsAutoPlay, 'auto', "autoplay", "IsAutoPlay", "If set it to true - video start play when game started", false); desc.AddMember(&CTextureVideoPlayerComponent::m_VideoFileName, 'vide', "videofile", "VideoFileName", "Video file name witout folder and extension", ""); desc.AddMember(&CTextureVideoPlayerComponent::m_OutputFileName, 'text', "outtexture", "OutputTextureName", "Output texture name for using in materials. Can't be null. Need start for $ simbol. (e.g. $videoplayer_1)", ""); desc.AddMember(&CTextureVideoPlayerComponent::m_IsPreloaded, 'prel', "preloaded", "IsPreloaded", "If set it to true - before playing video his will be loaded in memory", true); desc.AddMember(&CTextureVideoPlayerComponent::m_IsLooped, 'loop', "looped", "IsLooped", "If set it to true - video will be looped", false); desc.AddMember(&CTextureVideoPlayerComponent::m_IsCanPlayInEditor, 'edit', "canplayineditor", "IsCanPlayInEditor", "If set it to true - video can be played in editor mode", false); } void CTextureVideoPlayerComponent::Initialize() { } void CTextureVideoPlayerComponent::OnShutDown() { Stop(); } Cry::Entity::EventFlags CTextureVideoPlayerComponent::GetEventMask() const { return EEntityEvent::GameplayStarted; } void CTextureVideoPlayerComponent::ProcessEvent(const SEntityEvent& event) { switch (event.event) { case EEntityEvent::GameplayStarted: { if (m_IsAutoPlay) { Play(m_VideoFileName, m_OutputFileName, m_IsPreloaded, m_IsLooped, m_IsCanPlayInEditor); } break; } default: break; } } void CTextureVideoPlayerComponent::Play(Schematyc::CSharedString videoFile, Schematyc::CSharedString outputTexture, bool preload, bool looped, bool canPlayInEditor) { if (videoFile.empty()) { LogError("<CTextureVideoPlayerComponent> Can't play video, because video file name empty, check you component settings and try again!"); return; } if (outputTexture.empty()) { LogError("<CTextureVideoPlayerComponent> Can't play video, because output texture name empty, check you component settings and try again!"); return; } if (gEnv->IsEditor() && !canPlayInEditor) { LogError("<CTextureVideoPlayerComponent> Can't play video, because playing blocking in editor mode!"); return; } if (!m_IsAutoPlay) { m_VideoFileName = videoFile; m_OutputFileName = outputTexture; m_IsPreloaded = preload; m_IsLooped = looped; m_IsCanPlayInEditor = canPlayInEditor; } if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->PlayVideo(this, videoFile.c_str(), outputTexture.c_str(), preload, looped); } } void CTextureVideoPlayerComponent::Pause() { if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->PauseVideo(m_OutputFileName.c_str()); } } void CTextureVideoPlayerComponent::Resume() { if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->ResumeVideo(m_OutputFileName.c_str()); } } void CTextureVideoPlayerComponent::Stop() { if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->StopVideo(m_OutputFileName.c_str()); } } void CTextureVideoPlayerComponent::OnVideoPlayerEvent(const char* videoFileName, EVideoPlayerEvents event) { if (gEnv->pSystem != nullptr && gEnv->pSystem->IsQuitting()) { return; } Schematyc::IObject* const pSchematycObject = m_pEntity->GetSchematycObject(); if (pSchematycObject == nullptr) { return; } switch (event) { case EVideoPlayerEvents::OnPlay: pSchematycObject->ProcessSignal(SOnStartPlaySignal(), GetGUID()); break; case EVideoPlayerEvents::OnPause: pSchematycObject->ProcessSignal(SOnPausedSignal(), GetGUID()); break; case EVideoPlayerEvents::OnResume: pSchematycObject->ProcessSignal(SOnResumedSignal(), GetGUID()); break; case EVideoPlayerEvents::OnStop: pSchematycObject->ProcessSignal(SOnStoppedSignal(), GetGUID()); break; default: break; } } }
37.184211
222
0.760085
afrostalin
6e969556dfe5103fd7fa2c59af2895a8bf0b76ac
6,329
cpp
C++
src/index/ph_index.cpp
h-2/graphtyper
692eac909f00a888dcc14487fe57907ff88f6d17
[ "MIT" ]
null
null
null
src/index/ph_index.cpp
h-2/graphtyper
692eac909f00a888dcc14487fe57907ff88f6d17
[ "MIT" ]
null
null
null
src/index/ph_index.cpp
h-2/graphtyper
692eac909f00a888dcc14487fe57907ff88f6d17
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <boost/log/trivial.hpp> #include <parallel_hashmap/phmap.h> #include <graphtyper/graph/graph.hpp> #include <graphtyper/index/ph_index.hpp> #include <graphtyper/utilities/options.hpp> #include <graphtyper/utilities/type_conversions.hpp> namespace gyper { void PHIndex::put(uint64_t const key, KmerLabel && label) { hamming0[key].push_back(std::move(label)); } void PHIndex::put(uint64_t const key, std::vector<KmerLabel> && labels) { std::move(labels.begin(), labels.end(), std::back_inserter(hamming0[key])); } std::vector<KmerLabel> PHIndex::get(uint64_t const key) const { auto find_it = hamming0.find(key); if (find_it != hamming0.end()) return find_it->second; else return std::vector<KmerLabel>(); } std::vector<KmerLabel> PHIndex::get(std::vector<uint64_t> const & keys) const { std::vector<KmerLabel> labels; std::vector<PHtype::const_iterator> results; long num_results{0}; long const NUM_KEYS = keys.size(); for (long j = 0; j < NUM_KEYS; ++j) { auto find_it = hamming0.find(keys[j]); if (find_it != hamming0.end()) { num_results += find_it->second.size(); if (NUM_KEYS > 1 && num_results > Options::const_instance()->max_index_labels) { // Too many results, give up on this kmer results.clear(); break; } results.push_back(find_it); } } for (auto const res : results) std::copy(res->second.begin(), res->second.end(), std::back_inserter(labels)); return labels; } std::vector<std::vector<KmerLabel> > PHIndex::multi_get(std::vector<std::vector<uint64_t> > const & keys) const { std::vector<std::vector<KmerLabel> > labels(keys.size()); std::vector<std::vector<PHtype::const_iterator> > results(keys.size()); for (long i = 0; i < static_cast<long>(keys.size()); ++i) { long num_results{0}; long const NUM_KEYS{static_cast<long>(keys[i].size())}; for (long j = 0; j < NUM_KEYS; ++j) { auto find_it = hamming0.find(keys[i][j]); if (find_it != hamming0.end()) { num_results += find_it->second.size(); if (NUM_KEYS > 1 && num_results > Options::const_instance()->max_index_labels) { // Checking multiple keys and finding too many results, give up on this results[i].clear(); break; } results[i].push_back(find_it); } } } assert(labels.size() == keys.size()); assert(results.size() == keys.size()); // If there are not too many results, add them to labels and return them for (long i = 0; i < static_cast<long>(results.size()); ++i) { for (auto const res : results[i]) std::copy(res->second.begin(), res->second.end(), std::back_inserter(labels[i])); } return labels; } void PHIndex::print() const { for (auto it = hamming0.begin(); it != hamming0.end(); ++it) { std::cerr << to_dna_str(it->first) << " count=" << it->second.size() << '\n'; } } /* std::vector<std::vector<KmerLabel> > PHIndex::multi_get_hamming1(std::vector<std::vector<uint64_t> > const & keys) const { std::vector<std::vector<KmerLabel> > labels(keys.size()); for (long i = 0; i < static_cast<long>(keys.size()); ++i) { long const NUM_KEYS = keys[i].size(); for (long j = 0; j < NUM_KEYS; ++j) { auto find_it = hamming1.find(keys[i][j]); if (find_it != hamming1.end()) { auto hamming0_find_it = hamming0.find(find_it->second); assert(hamming0_find_it != hamming0.end()); std::copy(hamming0_find_it->second.begin(), hamming0_find_it->second.end(), std::back_inserter(labels[i])); } } } assert(keys.size() == labels.size()); return labels; } */ bool PHIndex::check() const { bool no_errors = true; // Check if reference is in the index std::vector<char> ref_seq = graph.get_all_ref(); if (ref_seq.size() < gyper::K) { BOOST_LOG_TRIVIAL(warning) << "[" << __HERE__ << "] The graph is too small for any K-mers to be extracted."; return true; } if (std::all_of(ref_seq.cbegin(), ref_seq.cend(), [](char c){ return c == 'N'; })) { BOOST_LOG_TRIVIAL(warning) << "[" << __HERE__ << "] The reference contains only Ns."; return true; } auto start_it = ref_seq.begin(); auto final_it = ref_seq.begin() + K; std::vector<std::vector<uint64_t> > keys; std::size_t constexpr MAX_KEYS = 100000; long constexpr STEP_SIZE = 5; keys.reserve(MAX_KEYS); std::size_t num_keys_full = 0; BOOST_LOG_TRIVIAL(debug) << "[" << __HERE__ << "] Checking index"; while (std::distance(final_it, ref_seq.end()) >= STEP_SIZE) { std::vector<char> k_mer(start_it, final_it); assert(k_mer.size() == K); // Ignore kmers with non ACGT bases if (std::all_of(k_mer.begin(), k_mer.end(), [](char c){ return c == 'A' || c == 'C' || c == 'G' || c == 'T'; })) { keys.push_back(std::vector<uint64_t>(1, to_uint64(std::move(k_mer)))); if (keys.size() == MAX_KEYS) { ++num_keys_full; std::vector<std::vector<KmerLabel> > labels = multi_get(keys); for (int i = 0; i < static_cast<int>(labels.size()); ++i) { if (labels[i].size() == 0) { assert(keys[i].size() == 1); BOOST_LOG_TRIVIAL(error) << "[" << __HERE__ << "] Could not find kmer at position " << std::string(start_it, final_it) << " " << (i + std::distance(ref_seq.begin(), start_it)); no_errors = false; } } keys.clear(); } } start_it += STEP_SIZE; final_it += STEP_SIZE; } std::vector<std::vector<KmerLabel> > labels = multi_get(keys); for (int i = 0; i < static_cast<int>(labels.size()); ++i) { if (labels[i].size() == 0) { assert(keys[i].size() == 1); BOOST_LOG_TRIVIAL(error) << "[" << __HERE__ << "] Could not find kmer at position " << to_dna_str(keys[i][0]) << " " << (std::distance(ref_seq.begin(), start_it)) << " with i=" << i; no_errors = false; } } BOOST_LOG_TRIVIAL(debug) << "[" << __HERE__ << "] DONE Checking index"; return no_errors; } } // namespace gyper
25.115079
115
0.588877
h-2
6e98d6768c8266328d120379214e497a368e85b9
4,383
cpp
C++
relationships/unify_years.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
relationships/unify_years.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
relationships/unify_years.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
#include <stdio.h> #include <ghutils.h> #include <vector> #include <map> FILE *fmyids = fopen("myids.txt", "wt"); FILE *fstats = fopen("stats.txt", "wt"); #define MAXLINE 1000000000 typedef unsigned char uchr; map <pair<int, int>, int > graf; struct osoba { string xlogin; uchr rozmiar; uchr padding; uchr org1, org2, usr1, usr2; uchr goodtime; uchr badtime; short reg; uchr ineryx, padding2; osoba() { rozmiar = org1 = org2 = usr1 = usr2 = goodtime = badtime = padding = 0; ineryx = padding2 = 0; reg = 32767; } }; map<string, int> grouptomyid; vector<osoba> osoby; int qosoby = 1; int alledges = 0; int nextid() { int v = qosoby++; osoby.resize(qosoby); return v; } bool nomore = false; int getmyid(const string& login) { string l = tolower(login); if(nomore && !grouptomyid.count(l)) return -1; int& gtm(grouptomyid[l]); if(gtm == 0 && !nomore) { gtm = nextid(); osoby[gtm].xlogin = login; fprintf(fmyids, "%d;%s\n", gtm, login.c_str()); } return gtm; } int main(int argc, char **argv) { // printf("ed = %d\n", (int) sizeof(edge)); return 0; osoby.resize(1); {csvparser in("../../agregaty/ktoto2.csv"); while(in.next() && in.fields == 3) { if(in.linenumber > MAXLINE) break; int id = getmyid(in[1]); grouptomyid[tolower(in[2])] = id; osoby[id].rozmiar++; } } fclose(fmyids); {csvparser in("../../id_eryx.csv", ','); in.next(); while(in.next() && in.fields == 3) { if(in.linenumber > MAXLINE) break; int id = getmyid(in[2]); int aid = tonum(in[0]); auto& o(osoby[id]); if(in[1] == "user") o.usr1++; else if(in[1] == "organization") o.org1++; else fprintf(fstats, "unknown type %s in crawl\n", in[1].c_str()); if(aid <= 2) o.reg = 2007*16+13; else if(aid <= 43569) o.reg = 2008*16+13; else if(aid <= 174849) o.reg = 2009*16+13; else if(aid <= 543015) o.reg = 2010*16+13; else if(aid <= 1296987) o.reg = 2011*16+13; else if(aid <= 3161234) o.reg = 2012*16+13; else if(aid <= 6295257) o.reg = 2013*16+13; else if(aid <=10361315) o.reg = 2014*16+13; else o.reg = 2015*16+13; o.ineryx++; } } {csvparser in("../../rawdata/ght/users.csv", ','); in.next(); while(in.next()) { if(in.linenumber > MAXLINE) break; if(in.fields != 12) fprintf(fstats, "bad fieldcount (%d) in users\n", in.fields); else { int id = getmyid(in[1]); auto& o(osoby[id]); if(in[5] == "1") in[4] = "ORG"; if(in[6] == "1") in[4] = "ORG"; if(in[4] == "USR") o.usr2++; else if(in[4] == "ORG") o.org2++; else fprintf(fstats, "unknown type %s in users\n", in[4].c_str()); string srok = in[3].substr(0, 4); string smon = in[3].substr(5, 2); int rok = atoi(srok.c_str()); int mon = atoi(smon.c_str()); int reg = rok * 16 + mon; if(reg < o.reg || ((o.reg&15) == 13)) o.reg = reg; if(rok >= 2000 && rok <= 2017) o.goodtime++; else if(rok >= 2017) o.badtime++; else fprintf(fstats, "unknown date %s in users\n", in[3].c_str()); } } } fprintf(fstats, "qosoby = %d\n", qosoby); fflush(fstats); {csvparser in(argv[1]); in.next(); while(in.next()) { if(in.fields < 3) continue; if(in.linenumber > MAXLINE) break; int id_source = getmyid(in[1]); int id_target = getmyid(in[2]); cout <<id_source <<";" <<id_target <<endl; if (graf.count(make_pair(id_source,id_target))==0) { graf[make_pair(id_source, id_target)]=tonum(in[0]); } else { if (graf[make_pair(id_source, id_target)] > tonum(in[0])) { graf[make_pair(id_source, id_target)] = tonum(in[0]); } } }} {csvparser in("../../agregaty/ktoto2.csv"); FILE *f = fopen("../../agregaty/my-ktoto.csv", "wt"); while(in.next() && in.fields == 3) { if(in.linenumber > MAXLINE) break; int id = getmyid(in[1]); if(id >= 0) fprintf(f, "%d;%s\n", id, in[2].c_str()); } fclose(f); } fclose(fstats); ofstream of1(argv[2]); for ( auto& edge: graf) { of1 <<edge.second <<";" <<edge.first.first <<";" <<edge.first.second << "\n"; } return 0; }
27.055556
86
0.534337
tehora