hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d0ada2a075844691aa31ef18a762cdbcb8eda10b | 386 | cpp | C++ | performerservice.cpp | BjarkiK/VerklegtNamskeidHR-2016 | ea05d8eae7f444371e93944165343a5a837ee273 | [
"MIT"
] | null | null | null | performerservice.cpp | BjarkiK/VerklegtNamskeidHR-2016 | ea05d8eae7f444371e93944165343a5a837ee273 | [
"MIT"
] | null | null | null | performerservice.cpp | BjarkiK/VerklegtNamskeidHR-2016 | ea05d8eae7f444371e93944165343a5a837ee273 | [
"MIT"
] | null | null | null | #include "performerservice.h"
Performerservice::Performerservice()
{
}
Performerservice::addPerformer(){
}
vector <Performer> Performerservice::getPerformers(/*Setja inn færibreytur hér*/){
vector <Performer> performers;
Performer p("Mamma Mia", 40);
Performer p2("Papa Dapa", 69);
performers.push_back(p);
performers.push_back(p2);
return performers;
}
| 16.782609 | 82 | 0.707254 | [
"vector"
] |
d0ae18880e578efb87407319aa338efcd5e87731 | 1,033 | cpp | C++ | src/predecl/DiagGaussianDistrDecl.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 22 | 2016-07-11T15:34:14.000Z | 2021-04-19T04:11:13.000Z | src/predecl/DiagGaussianDistrDecl.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 14 | 2016-07-11T14:28:42.000Z | 2017-01-27T02:59:24.000Z | src/predecl/DiagGaussianDistrDecl.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 7 | 2016-10-03T10:05:06.000Z | 2021-05-31T00:58:35.000Z | #include "DiagGaussianDistrDecl.h"
#include "../ir/DoubleLiteral.h"
#include "../ir/IntLiteral.h"
namespace swift {
namespace predecl {
DiagGaussianDistrDecl::DiagGaussianDistrDecl() :
PreDecl(std::string("DiagGaussian")) {
}
DiagGaussianDistrDecl::~DiagGaussianDistrDecl() {
}
std::shared_ptr<ir::Expr> DiagGaussianDistrDecl::getNew(
std::vector<std::shared_ptr<ir::Expr>>& args,
fabrica::TypeFactory* fact) const {
// Type Checking
if (args.size() != 2 || args[0] == nullptr || args[1] == nullptr)
return nullptr;
// Note: We only accept matrix as arguments
if (args[0]->getTyp() != fact->getTy(ir::IRConstString::MATRIX))
return nullptr;
// Note: We only accept matrix as arguments
if (args[1]->getTyp() != fact->getTy(ir::IRConstString::MATRIX))
return nullptr;
auto ret = std::make_shared<ir::Distribution>(this->getName(), this);
ret->setArgs(args);
ret->setTyp(fact->getTy(ir::IRConstString::MATRIX));
ret->processArgRandomness();
ret->setRandom(true);
return ret;
}
}
}
| 26.487179 | 71 | 0.685382 | [
"vector"
] |
d0bbbd561c074b526f9e6089c72697d1b3256f08 | 1,849 | cc | C++ | 3.triangle_simple/triangle.cc | joone/opengl-wayland | 76355d9fbe160c3991577fe206350d5f992a9395 | [
"BSD-2-Clause"
] | 5 | 2021-01-25T01:51:58.000Z | 2022-03-18T22:50:10.000Z | 3.triangle_simple/triangle.cc | joone/opengl-wayland | 76355d9fbe160c3991577fe206350d5f992a9395 | [
"BSD-2-Clause"
] | null | null | null | 3.triangle_simple/triangle.cc | joone/opengl-wayland | 76355d9fbe160c3991577fe206350d5f992a9395 | [
"BSD-2-Clause"
] | null | null | null | //
// Triangle example
// https://github.com/JoeyDeVries/LearnOpenGL/blob/master/src/1.getting_started/2.1.hello_triangle/hello_triangle.cpp
//
#include "../common/wayland_platform.h"
#include "../common/display.h"
#include "../common/window.h"
// #version 300 es
const char* vertexShaderSource =
"#version 300 es \n"
"layout(location = 0) in vec4 position; \n"
"void main() \n"
"{ \n"
" gl_Position = position; \n"
"}";
const char* fragmentShaderSource =
"#version 300 es \n"
"precision mediump float; \n"
"layout(location = 0) out vec4 out_color; \n"
"void main() \n"
"{ \n"
" out_color = vec4(1.0f, 0.0f, 0.0f, 1.0f); \n"
"} \n";
void redraw(WaylandWindow* window) {
float vertices[] = {
0.0f, 0.5f, 0.0f, // left
-0.5f, -0.5f, 0.0f, // right
0.5f, -0.5f, 0.0f // top
};
WaylandPlatform* platform = WaylandPlatform::getInstance();
glViewport(0, 0, window->geometry.width, window->geometry.height);
glClearColor(0.0, 0.0, 0.0, 0.5);
glClear(GL_COLOR_BUFFER_BIT);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
}
int main(int argc, char** argv) {
std::unique_ptr<WaylandPlatform> waylandPlatform = WaylandPlatform::create();
int width = 250;
int height = 250;
waylandPlatform->createWindow(width, height,vertexShaderSource,
fragmentShaderSource, redraw);
waylandPlatform->run();
waylandPlatform->terminate();
return 0;
}
| 29.822581 | 117 | 0.553272 | [
"geometry"
] |
d0c054669bc4c0b5e043fcf0b333bcce6ebae23d | 12,447 | cpp | C++ | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Logic/WeightedRandomSequencer.cpp | raghnarx/lumberyard | 1c52b941dcb7d94341fcf21275fe71ff67173ada | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Logic/WeightedRandomSequencer.cpp | 29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard | 1c52b941dcb7d94341fcf21275fe71ff67173ada | [
"AML"
] | null | null | null | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Logic/WeightedRandomSequencer.cpp | 29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard | 1c52b941dcb7d94341fcf21275fe71ff67173ada | [
"AML"
] | 4 | 2019-08-05T07:25:46.000Z | 2020-12-07T05:12:55.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 "WeightedRandomSequencer.h"
#include <AzCore/std/string/string.h>
#include <Include/ScriptCanvas/Libraries/Logic/WeightedRandomSequencer.generated.cpp>
#include <Include/ScriptCanvas/Libraries/Math/MathNodeUtilities.h>
namespace ScriptCanvas
{
namespace Nodes
{
namespace Logic
{
////////////////////////////
// WeightedRandomSequencer
////////////////////////////
void WeightedRandomSequencer::ReflectDataTypes(AZ::ReflectContext* reflectContext)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
if (serializeContext)
{
serializeContext->Class<WeightedPairing>()
->Version(1)
->Field("WeightSlotId", &WeightedPairing::m_weightSlotId)
->Field("ExecutionSlotId", &WeightedPairing::m_executionSlotId)
;
}
}
}
void WeightedRandomSequencer::OnInit()
{
for (const WeightedPairing& weightedPairing : m_weightedPairings)
{
EndpointNotificationBus::MultiHandler::BusConnect({ GetEntityId(), weightedPairing.m_weightSlotId });
EndpointNotificationBus::MultiHandler::BusConnect({ GetEntityId(), weightedPairing.m_executionSlotId });
}
// We always want at least one weighted transition state
if (m_weightedPairings.empty())
{
AddWeightedPair();
}
}
void WeightedRandomSequencer::OnInputSignal(const SlotId& slotId)
{
const SlotId inSlotId = WeightedRandomSequencerProperty::GetInSlotId(this);
if (slotId == inSlotId)
{
int runningTotal = 0;
AZStd::vector< WeightedStruct > weightedStructs;
weightedStructs.reserve(m_weightedPairings.size());
for (const WeightedPairing& weightedPairing : m_weightedPairings)
{
const Datum* datum = GetInput(weightedPairing.m_weightSlotId);
if (datum)
{
WeightedStruct weightedStruct;
weightedStruct.m_executionSlotId = weightedPairing.m_executionSlotId;
if (datum->GetType().IS_A(ScriptCanvas::Data::Type::Number()))
{
int weight = aznumeric_cast<int>((*datum->GetAs<Data::NumberType>()));
runningTotal += weight;
weightedStruct.m_totalWeight = runningTotal;
}
weightedStructs.emplace_back(weightedStruct);
}
}
// We have no weights. So just trigger the first execution output
// Weighted pairings is controlled to never be empty.
if (runningTotal == 0)
{
if (!m_weightedPairings.empty())
{
SignalOutput(m_weightedPairings.front().m_executionSlotId);
}
return;
}
int weightedResult = MathNodeUtilities::GetRandomIntegral<int>(1, runningTotal);
for (const WeightedStruct& weightedStruct : weightedStructs)
{
if (weightedResult <= weightedStruct.m_totalWeight)
{
SignalOutput(weightedStruct.m_executionSlotId);
break;
}
}
}
}
void WeightedRandomSequencer::OnEndpointConnected(const Endpoint& endpoint)
{
if (AllWeightsFilled())
{
AddWeightedPair();
}
}
void WeightedRandomSequencer::OnEndpointDisconnected(const Endpoint& endpoint)
{
// We always want one. So we don't need to do anything else.
if (m_weightedPairings.size() == 1)
{
return;
}
const SlotId& currentSlotId = EndpointNotificationBus::GetCurrentBusId()->GetSlotId();
// If there are still connections. We don't need to do anything.
if (IsConnected(currentSlotId))
{
return;
}
if (!HasExcessEndpoints())
{
return;
}
for (auto pairIter = m_weightedPairings.begin(); pairIter != m_weightedPairings.end(); ++pairIter)
{
if (pairIter->m_executionSlotId == currentSlotId)
{
if (!IsConnected(pairIter->m_weightSlotId))
{
RemoveWeightedPair(currentSlotId);
break;
}
}
else if (pairIter->m_weightSlotId == currentSlotId)
{
if (!IsConnected(pairIter->m_executionSlotId))
{
RemoveWeightedPair(currentSlotId);
break;
}
}
}
}
void WeightedRandomSequencer::RemoveWeightedPair(SlotId slotId)
{
for (auto pairIter = m_weightedPairings.begin(); pairIter != m_weightedPairings.end(); ++pairIter)
{
const WeightedPairing& weightedPairing = (*pairIter);
if (pairIter->m_executionSlotId == slotId
|| pairIter->m_weightSlotId == slotId)
{
EndpointNotificationBus::MultiHandler::BusDisconnect({ GetEntityId(), pairIter->m_executionSlotId});
EndpointNotificationBus::MultiHandler::BusDisconnect({ GetEntityId(), pairIter->m_weightSlotId});
RemoveSlot(pairIter->m_weightSlotId);
RemoveSlot(pairIter->m_executionSlotId);
m_weightedPairings.erase(pairIter);
break;
}
}
FixupStateNames();
}
bool WeightedRandomSequencer::AllWeightsFilled() const
{
bool isFilled = true;
for (const WeightedPairing& weightedPairing : m_weightedPairings)
{
if (!IsConnected(weightedPairing.m_weightSlotId))
{
isFilled = false;
break;
}
}
return isFilled;
}
bool WeightedRandomSequencer::HasExcessEndpoints() const
{
bool hasExcess = false;
bool hasEmpty = false;
for (const WeightedPairing& weightedPairing : m_weightedPairings)
{
if (!IsConnected(weightedPairing.m_weightSlotId) && !IsConnected(weightedPairing.m_executionSlotId))
{
if (hasEmpty)
{
hasExcess = true;
break;
}
else
{
hasEmpty = true;
}
}
}
return hasExcess;
}
void WeightedRandomSequencer::AddWeightedPair()
{
int counterWeight = static_cast<int>(m_weightedPairings.size()) + 1;
WeightedPairing weightedPairing;
DataSlotConfiguration dataSlotConfiguration;
dataSlotConfiguration.m_slotType = SlotType::DataIn;
dataSlotConfiguration.m_name = GenerateDataName(counterWeight);
dataSlotConfiguration.m_toolTip = "The weight associated with the execution state.";
dataSlotConfiguration.m_addUniqueSlotByNameAndType = false;
dataSlotConfiguration.m_dataType = Data::Type::Number();
dataSlotConfiguration.m_displayGroup = "WeightedExecutionGroup";
weightedPairing.m_weightSlotId = AddInputDatumSlot(dataSlotConfiguration);
SlotConfiguration slotConfiguration;
slotConfiguration.m_name = GenerateOutName(counterWeight);
slotConfiguration.m_addUniqueSlotByNameAndType = false;
slotConfiguration.m_slotType = SlotType::ExecutionOut;
slotConfiguration.m_displayGroup = "WeightedExecutionGroup";
weightedPairing.m_executionSlotId = AddSlot(slotConfiguration);
m_weightedPairings.push_back(weightedPairing);
EndpointNotificationBus::MultiHandler::BusConnect({GetEntityId(), weightedPairing.m_weightSlotId });
EndpointNotificationBus::MultiHandler::BusConnect({ GetEntityId(), weightedPairing.m_executionSlotId });
}
void WeightedRandomSequencer::FixupStateNames()
{
int counter = 1;
for (const WeightedPairing& weightedPairing : m_weightedPairings)
{
AZStd::string dataName = GenerateDataName(counter);
AZStd::string executionName = GenerateOutName(counter);
Slot* dataSlot = GetSlot(weightedPairing.m_weightSlotId);
if (dataSlot)
{
dataSlot->Rename(dataName);
}
Slot* executionSlot = GetSlot(weightedPairing.m_executionSlotId);
if (executionSlot)
{
executionSlot->Rename(executionName);
}
++counter;
}
}
AZStd::string WeightedRandomSequencer::GenerateDataName(int counter)
{
return AZStd::string::format("Weight %i", counter);
}
AZStd::string WeightedRandomSequencer::GenerateOutName(int counter)
{
return AZStd::string::format("Out %i", counter);
}
}
}
} | 41.352159 | 124 | 0.459629 | [
"vector"
] |
d0c38659ee5e514d806e37d58065405620d90bae | 1,185 | cpp | C++ | arrays/013_merge overlaping intervals.cpp | CodeMacrocosm/DSA-BOOK | a94bd9d6b7e4cbef46c7531c023b02dab94477aa | [
"MIT"
] | 9 | 2021-05-18T05:08:29.000Z | 2021-10-02T18:21:54.000Z | 013_merge overlaping intervals.cpp | srujana-55/DSA-BOOK | a874354e9f9f29c6a767031c4ccb7d1c1fa5e60d | [
"MIT"
] | null | null | null | 013_merge overlaping intervals.cpp | srujana-55/DSA-BOOK | a874354e9f9f29c6a767031c4ccb7d1c1fa5e60d | [
"MIT"
] | 3 | 2021-05-19T06:13:43.000Z | 2022-01-25T07:30:33.000Z | //author :shreyamalogi
//time complexity--o(NlogN)
//SPACE Complexity--o(N)
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector<pair<int,int>> a; //vector of pair
for(int i=0;i<n;i++){
int x,y; //2 inputs
cin>>x>>y;
a.push_back({x,y}); //array me push bk
}
//then sort it
sort(a.begin(),a.end());
stack<pair<int, int>> s; //taking a stack in pair wise
s.push({a[0].first,a[0].second}); //1st parameter ko gusadenge
for(int i=1;i<n;i++){ //1 to last tk run karenge
//taking 4 parameters
int start1= s.top().first;
int end1 = s.top().second;
int start2= a[i].first;
int end2 = a[i].second;
if(end1 < start2){
s.push({start2,end2}); //we acnt merge just push it to the stack
}
else{
s.pop(); //first we need to delete the top elements then update it
end1 = max(end1,end2); //update
s.push({start1,end1}); //push the updated into the stack
}
}
while(!s.empty()){ //while stack is not empty
cout<<s.top().first<<" "<<s.top().second<<endl;
s.pop();
}
return 0;
}
| 22.358491 | 85 | 0.544304 | [
"vector"
] |
d0c3a6bae37745dd13feb34aef93df7a3a878e60 | 3,274 | hpp | C++ | tridiagonal/off_tridiagonal_solver.hpp | kit71717/tridiagonal | 672fef309fbcc66d75f9678eeb20a47ea546ed55 | [
"MIT"
] | 4 | 2020-11-01T20:07:54.000Z | 2022-02-21T00:43:48.000Z | tridiagonal/off_tridiagonal_solver.hpp | kit71717/tridiagonal | 672fef309fbcc66d75f9678eeb20a47ea546ed55 | [
"MIT"
] | null | null | null | tridiagonal/off_tridiagonal_solver.hpp | kit71717/tridiagonal | 672fef309fbcc66d75f9678eeb20a47ea546ed55 | [
"MIT"
] | 2 | 2020-08-18T04:45:22.000Z | 2022-02-03T22:41:36.000Z | #ifndef TRIDIAGONAL_OFF_TRIDIAGONAL_HPP
#define TRIDIAGONAL_OFF_TRIDIAGONAL_HPP
#include <vector>
#include <type_traits>
#include "utils.hpp"
namespace tridiagonal {
/**
* Solve tri-diagonal block matrix system on the form
*
* | B_0 C_0 0 0 0 ... A_0 | | X_1 | | D_1 |
* | A_1 B_1 C_1 0 0 ... 0 | | X_2 | | D_2 |
* | 0 A_2 B_2 C_2 0 ... 0 | | | | |
* | | | . | | . |
* | . . . . . | | . | = | . |
* | . . . . . | | . | | . |
* | . . . . . | | | | |
* | A_n-2 B_n-2 C_n-2 | | X_n-2 | | D_n-2 |
* | C_n-1 0 A_n-1 B_n-1 | | X_n-1 | | D_n-1 |
*
* using a recursive algorithm
*
* @param lower_diagonal : list of matrices on the lower diagonal {A_0, ..., A_n-1}
* @param diagonal : list of matrices on the diagonal {B_1, ..., B_n-1}
* @param upper_diagonal : list of matrices on the upper diagonal {C_0, ..., C_n-1}
* @param rhs : list of matrices on the right and side {D_0, ..., D_n-1}
* @return list of solutions {X_0, ..., X_n-1}
*/
template <typename A, typename B, typename C, typename D,
typename std::enable_if<!is_dynamic<A>::value, int>::type = 0,
typename std::enable_if<!is_dynamic<B>::value, int>::type = 0,
typename std::enable_if<!is_dynamic<C>::value, int>::type = 0,
typename std::enable_if<!is_dynamic<D>::value, int>::type = 0,
typename std::enable_if<A::RowsAtCompileTime == A::ColsAtCompileTime, int>::type = 0,
typename std::enable_if<A::RowsAtCompileTime == B::RowsAtCompileTime, int>::type = 0,
typename std::enable_if<A::ColsAtCompileTime == B::ColsAtCompileTime, int>::type = 0,
typename std::enable_if<A::RowsAtCompileTime == C::RowsAtCompileTime, int>::type = 0,
typename std::enable_if<A::ColsAtCompileTime == C::ColsAtCompileTime, int>::type = 0,
typename std::enable_if<A::RowsAtCompileTime == D::RowsAtCompileTime, int>::type = 0
>
vector<D> solve_off_tridiagonal(std::vector<A> const & lower_diagonal,
std::vector<B> const & diagonal,
std::vector<C> const & upper_diagonal,
std::vector<D> const & rhs);
template <typename A, typename B, typename C, typename D,
typename std::enable_if<is_dynamic<A>::value or
is_dynamic<B>::value or
is_dynamic<C>::value or
is_dynamic<D>::value, int>::type = 0
>
vector<D> solve_off_tridiagonal(std::vector<A> const & lower_diagonal,
std::vector<B> const & diagonal,
std::vector<C> const & upper_diagonal,
std::vector<D> const & rhs);
}
#include "off_tridiagonal_solver.cpp"
#endif // TRIDIAGONAL_OFF_TRIDIAGONAL_HPP
| 50.369231 | 97 | 0.488699 | [
"vector"
] |
d0cd5cba405e1ac06d06645e3c9c773d6ff2c9bd | 5,989 | cpp | C++ | src/properties/optionproperty.cpp | hedbergj/OpenSpace | 0125fb7a3be4d6e6529781522f5d9e9a826241fb | [
"MIT"
] | null | null | null | src/properties/optionproperty.cpp | hedbergj/OpenSpace | 0125fb7a3be4d6e6529781522f5d9e9a826241fb | [
"MIT"
] | null | null | null | src/properties/optionproperty.cpp | hedbergj/OpenSpace | 0125fb7a3be4d6e6529781522f5d9e9a826241fb | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* 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 <openspace/properties/optionproperty.h>
#include <ghoul/logging/logmanager.h>
namespace {
constexpr const char* _loggerCat = "OptionProperty";
} // namespace
namespace openspace::properties {
const std::string OptionProperty::OptionsKey = "Options";
OptionProperty::OptionProperty(PropertyInfo info)
: IntProperty(std::move(info))
, _displayType(DisplayType::Radio)
{}
OptionProperty::OptionProperty(PropertyInfo info, DisplayType displayType)
: IntProperty(std::move(info))
, _displayType(displayType)
{}
std::string OptionProperty::className() const {
return "OptionProperty";
}
OptionProperty::DisplayType OptionProperty::displayType() const {
return _displayType;
}
const std::vector<OptionProperty::Option>& OptionProperty::options() const {
return _options;
}
void OptionProperty::addOption(int value, std::string desc) {
Option option = { std::move(value), std::move(desc) };
for (const Option& o : _options) {
if (o.value == option.value) {
LWARNING(fmt::format(
"The value of option {{ {} -> {} }} was already registered when trying "
"to add option {{ {} -> {} }}",
o.value, o.description, option.value, option.description
));
return;
}
}
_options.push_back(std::move(option));
}
void OptionProperty::addOptions(std::vector<std::pair<int, std::string>> options) {
for (std::pair<int, std::string>& p : options) {
addOption(std::move(p.first), std::move(p.second));
}
}
void OptionProperty::addOptions(std::vector<std::string> options) {
for (int i = 0; i < static_cast<int>(options.size()); ++i) {
addOption(i, std::move(options[i]));
}
}
void OptionProperty::clearOptions() {
_options.clear();
_value = 0;
}
void OptionProperty::setValue(int value) {
// Check if the passed value belongs to any option
for (size_t i = 0; i < _options.size(); ++i) {
const Option& o = _options[i];
if (o.value == value) {
// If it does, set it by calling the superclasses setValue method
// @TODO(abock): This should be setValue(value) instead or otherwise the
// stored indices and option values start to drift if the
// operator T of the OptionProperty is used
NumericalProperty::setValue(static_cast<int>(i));
return;
}
}
// Otherwise, log an error
LERROR(fmt::format("Could not find an option for value '{}'", value));
}
bool OptionProperty::hasOption() const {
return value() >= 0 && value() < static_cast<int>(_options.size());
}
const OptionProperty::Option& OptionProperty::option() const {
return _options[value()];
}
std::string OptionProperty::getDescriptionByValue(int value) {
auto it = std::find_if(
_options.begin(),
_options.end(),
[value](const Option& option) {
return option.value == value;
}
);
if (it != _options.end()) {
return it->description;
}
else {
return "";
}
}
std::string OptionProperty::generateAdditionalJsonDescription() const {
// @REFACTOR from selectionproperty.cpp, possible refactoring? ---abock
std::string result =
"{ \"" + OptionsKey + "\": [";
for (size_t i = 0; i < _options.size(); ++i) {
const Option& o = _options[i];
std::string v = std::to_string(o.value);
std::string vSan = sanitizeString(v);
std::string d = o.description;
std::string dSan = sanitizeString(d);
result += '{';
result += fmt::format(R"("{}": "{}")", vSan, dSan);
result += '}';
if (i != _options.size() - 1) {
result += ",";
}
}
result += "] }";
return result;
}
} // namespace openspace::properties
| 36.742331 | 90 | 0.53281 | [
"vector"
] |
d0d33d3a6742f4e62509375f7b0ba980b35e6584 | 14,100 | cc | C++ | chromeos/network/shill_property_util.cc | iplo/Chain | 8bc8943d66285d5258fffc41bed7c840516c4422 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | chromeos/network/shill_property_util.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-02-14T21:55:58.000Z | 2017-02-14T21:55:58.000Z | chromeos/network/shill_property_util.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/shill_property_util.h"
#include "base/i18n/icu_encoding_detection.h"
#include "base/i18n/icu_string_conversions.h"
#include "base/json/json_writer.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/values.h"
#include "chromeos/network/network_event_log.h"
#include "chromeos/network/network_ui_data.h"
#include "chromeos/network/onc/onc_utils.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
namespace shill_property_util {
namespace {
// Replace non UTF8 characters in |str| with a replacement character.
std::string ValidateUTF8(const std::string& str) {
std::string result;
for (int32 index = 0; index < static_cast<int32>(str.size()); ++index) {
uint32 code_point_out;
bool is_unicode_char = base::ReadUnicodeCharacter(
str.c_str(), str.size(), &index, &code_point_out);
const uint32 kFirstNonControlChar = 0x20;
if (is_unicode_char && (code_point_out >= kFirstNonControlChar)) {
base::WriteUnicodeCharacter(code_point_out, &result);
} else {
const uint32 kReplacementChar = 0xFFFD;
// Puts kReplacementChar if character is a control character [0,0x20)
// or is not readable UTF8.
base::WriteUnicodeCharacter(kReplacementChar, &result);
}
}
return result;
}
// If existent and non-empty, copies the string at |key| from |source| to
// |dest|. Returns true if the string was copied.
bool CopyStringFromDictionary(const base::DictionaryValue& source,
const std::string& key,
base::DictionaryValue* dest) {
std::string string_value;
if (!source.GetStringWithoutPathExpansion(key, &string_value) ||
string_value.empty())
return false;
dest->SetStringWithoutPathExpansion(key, string_value);
return true;
}
} // namespace
void SetSSID(const std::string ssid, base::DictionaryValue* properties) {
std::string hex_ssid = base::HexEncode(ssid.c_str(), ssid.size());
properties->SetStringWithoutPathExpansion(shill::kWifiHexSsid, hex_ssid);
}
std::string GetSSIDFromProperties(const base::DictionaryValue& properties,
bool* unknown_encoding) {
if (unknown_encoding)
*unknown_encoding = false;
std::string hex_ssid;
properties.GetStringWithoutPathExpansion(shill::kWifiHexSsid, &hex_ssid);
if (hex_ssid.empty()) {
NET_LOG_ERROR("GetSSIDFromProperties", "No HexSSID set.");
return std::string();
}
std::string ssid;
std::vector<uint8> raw_ssid_bytes;
if (base::HexStringToBytes(hex_ssid, &raw_ssid_bytes)) {
ssid = std::string(raw_ssid_bytes.begin(), raw_ssid_bytes.end());
NET_LOG_DEBUG(
"GetSSIDFromProperties",
base::StringPrintf("%s, SSID: %s", hex_ssid.c_str(), ssid.c_str()));
} else {
NET_LOG_ERROR("GetSSIDFromProperties",
base::StringPrintf("Error processing: %s", hex_ssid.c_str()));
return std::string();
}
if (IsStringUTF8(ssid))
return ssid;
// Detect encoding and convert to UTF-8.
std::string encoding;
if (!base::DetectEncoding(ssid, &encoding)) {
// TODO(stevenjb): This is currently experimental. If we find a case where
// base::DetectEncoding() fails, we need to figure out whether we can use
// country_code with ConvertToUtf8(). crbug.com/233267.
properties.GetStringWithoutPathExpansion(shill::kCountryProperty,
&encoding);
}
std::string utf8_ssid;
if (!encoding.empty() &&
base::ConvertToUtf8AndNormalize(ssid, encoding, &utf8_ssid)) {
if (utf8_ssid != ssid) {
NET_LOG_DEBUG(
"GetSSIDFromProperties",
base::StringPrintf(
"Encoding=%s: %s", encoding.c_str(), utf8_ssid.c_str()));
}
return utf8_ssid;
}
if (unknown_encoding)
*unknown_encoding = true;
NET_LOG_DEBUG(
"GetSSIDFromProperties",
base::StringPrintf("Unrecognized Encoding=%s", encoding.c_str()));
return ssid;
}
std::string GetNameFromProperties(const std::string& service_path,
const base::DictionaryValue& properties) {
std::string name;
properties.GetStringWithoutPathExpansion(shill::kNameProperty, &name);
std::string validated_name = ValidateUTF8(name);
if (validated_name != name) {
NET_LOG_DEBUG("GetNameFromProperties",
base::StringPrintf("Validated name %s: UTF8: %s",
service_path.c_str(),
validated_name.c_str()));
}
std::string type;
properties.GetStringWithoutPathExpansion(shill::kTypeProperty, &type);
if (!NetworkTypePattern::WiFi().MatchesType(type))
return validated_name;
bool unknown_ssid_encoding = false;
std::string ssid = GetSSIDFromProperties(properties, &unknown_ssid_encoding);
if (ssid.empty())
NET_LOG_ERROR("GetNameFromProperties", "No SSID set: " + service_path);
// Use |validated_name| if |ssid| is empty.
// And if the encoding of the SSID is unknown, use |ssid|, which contains raw
// bytes in that case, only if |validated_name| is empty.
if (ssid.empty() || (unknown_ssid_encoding && !validated_name.empty()))
return validated_name;
if (ssid != validated_name) {
NET_LOG_DEBUG("GetNameFromProperties",
base::StringPrintf("%s: SSID: %s, Name: %s",
service_path.c_str(),
ssid.c_str(),
validated_name.c_str()));
}
return ssid;
}
scoped_ptr<NetworkUIData> GetUIDataFromValue(const base::Value& ui_data_value) {
std::string ui_data_str;
if (!ui_data_value.GetAsString(&ui_data_str))
return scoped_ptr<NetworkUIData>();
if (ui_data_str.empty())
return make_scoped_ptr(new NetworkUIData());
scoped_ptr<base::DictionaryValue> ui_data_dict(
chromeos::onc::ReadDictionaryFromJson(ui_data_str));
if (!ui_data_dict)
return scoped_ptr<NetworkUIData>();
return make_scoped_ptr(new NetworkUIData(*ui_data_dict));
}
scoped_ptr<NetworkUIData> GetUIDataFromProperties(
const base::DictionaryValue& shill_dictionary) {
const base::Value* ui_data_value = NULL;
shill_dictionary.GetWithoutPathExpansion(shill::kUIDataProperty,
&ui_data_value);
if (!ui_data_value) {
VLOG(2) << "Dictionary has no UIData entry.";
return scoped_ptr<NetworkUIData>();
}
scoped_ptr<NetworkUIData> ui_data = GetUIDataFromValue(*ui_data_value);
if (!ui_data)
LOG(ERROR) << "UIData is not a valid JSON dictionary.";
return ui_data.Pass();
}
void SetUIData(const NetworkUIData& ui_data,
base::DictionaryValue* shill_dictionary) {
base::DictionaryValue ui_data_dict;
ui_data.FillDictionary(&ui_data_dict);
std::string ui_data_blob;
base::JSONWriter::Write(&ui_data_dict, &ui_data_blob);
shill_dictionary->SetStringWithoutPathExpansion(shill::kUIDataProperty,
ui_data_blob);
}
bool CopyIdentifyingProperties(const base::DictionaryValue& service_properties,
base::DictionaryValue* dest) {
bool success = true;
// GUID is optional.
CopyStringFromDictionary(service_properties, shill::kGuidProperty, dest);
std::string type;
service_properties.GetStringWithoutPathExpansion(shill::kTypeProperty, &type);
success &= !type.empty();
dest->SetStringWithoutPathExpansion(shill::kTypeProperty, type);
if (type == shill::kTypeWifi) {
success &= CopyStringFromDictionary(
service_properties, shill::kSecurityProperty, dest);
success &=
CopyStringFromDictionary(service_properties, shill::kWifiHexSsid, dest);
success &= CopyStringFromDictionary(
service_properties, shill::kModeProperty, dest);
} else if (type == shill::kTypeVPN) {
success &= CopyStringFromDictionary(
service_properties, shill::kNameProperty, dest);
// VPN Provider values are read from the "Provider" dictionary, but written
// with the keys "Provider.Type" and "Provider.Host".
const base::DictionaryValue* provider_properties = NULL;
if (!service_properties.GetDictionaryWithoutPathExpansion(
shill::kProviderProperty, &provider_properties)) {
NET_LOG_ERROR("CopyIdentifyingProperties", "Missing VPN provider dict");
return false;
}
std::string vpn_provider_type;
provider_properties->GetStringWithoutPathExpansion(shill::kTypeProperty,
&vpn_provider_type);
success &= !vpn_provider_type.empty();
dest->SetStringWithoutPathExpansion(shill::kProviderTypeProperty,
vpn_provider_type);
std::string vpn_provider_host;
provider_properties->GetStringWithoutPathExpansion(shill::kHostProperty,
&vpn_provider_host);
success &= !vpn_provider_host.empty();
dest->SetStringWithoutPathExpansion(shill::kProviderHostProperty,
vpn_provider_host);
} else if (type == shill::kTypeEthernet || type == shill::kTypeEthernetEap) {
// Ethernet and EthernetEAP don't have any additional identifying
// properties.
} else {
NOTREACHED() << "Unsupported network type " << type;
success = false;
}
if (!success)
NET_LOG_ERROR("CopyIdentifyingProperties", "Missing required properties");
return success;
}
bool DoIdentifyingPropertiesMatch(const base::DictionaryValue& properties_a,
const base::DictionaryValue& properties_b) {
base::DictionaryValue identifying_a;
if (!CopyIdentifyingProperties(properties_a, &identifying_a))
return false;
base::DictionaryValue identifying_b;
if (!CopyIdentifyingProperties(properties_b, &identifying_b))
return false;
return identifying_a.Equals(&identifying_b);
}
} // namespace shill_property_util
namespace {
const char kPatternDefault[] = "PatternDefault";
const char kPatternEthernet[] = "PatternEthernet";
const char kPatternWireless[] = "PatternWireless";
const char kPatternMobile[] = "PatternMobile";
const char kPatternNonVirtual[] = "PatternNonVirtual";
enum NetworkTypeBitFlag {
kNetworkTypeNone = 0,
kNetworkTypeEthernet = 1 << 0,
kNetworkTypeWifi = 1 << 1,
kNetworkTypeWimax = 1 << 2,
kNetworkTypeCellular = 1 << 3,
kNetworkTypeVPN = 1 << 4,
kNetworkTypeEthernetEap = 1 << 5,
kNetworkTypeBluetooth = 1 << 6
};
struct ShillToBitFlagEntry {
const char* shill_network_type;
NetworkTypeBitFlag bit_flag;
} shill_type_to_flag[] = {
{ shill::kTypeEthernet, kNetworkTypeEthernet },
{ shill::kTypeEthernetEap, kNetworkTypeEthernetEap },
{ shill::kTypeWifi, kNetworkTypeWifi },
{ shill::kTypeWimax, kNetworkTypeWimax },
{ shill::kTypeCellular, kNetworkTypeCellular },
{ shill::kTypeVPN, kNetworkTypeVPN },
{ shill::kTypeBluetooth, kNetworkTypeBluetooth }
};
NetworkTypeBitFlag ShillNetworkTypeToFlag(const std::string& shill_type) {
for (size_t i = 0; i < arraysize(shill_type_to_flag); ++i) {
if (shill_type_to_flag[i].shill_network_type == shill_type)
return shill_type_to_flag[i].bit_flag;
}
NET_LOG_ERROR("ShillNetworkTypeToFlag", "Unknown type: " + shill_type);
return kNetworkTypeNone;
}
} // namespace
// static
NetworkTypePattern NetworkTypePattern::Default() {
return NetworkTypePattern(~0);
}
// static
NetworkTypePattern NetworkTypePattern::Wireless() {
return NetworkTypePattern(kNetworkTypeWifi | kNetworkTypeWimax |
kNetworkTypeCellular);
}
// static
NetworkTypePattern NetworkTypePattern::Mobile() {
return NetworkTypePattern(kNetworkTypeCellular | kNetworkTypeWimax);
}
// static
NetworkTypePattern NetworkTypePattern::NonVirtual() {
return NetworkTypePattern(~kNetworkTypeVPN);
}
// static
NetworkTypePattern NetworkTypePattern::Ethernet() {
return NetworkTypePattern(kNetworkTypeEthernet);
}
// static
NetworkTypePattern NetworkTypePattern::WiFi() {
return NetworkTypePattern(kNetworkTypeWifi);
}
// static
NetworkTypePattern NetworkTypePattern::Cellular() {
return NetworkTypePattern(kNetworkTypeCellular);
}
// static
NetworkTypePattern NetworkTypePattern::VPN() {
return NetworkTypePattern(kNetworkTypeVPN);
}
// static
NetworkTypePattern NetworkTypePattern::Wimax() {
return NetworkTypePattern(kNetworkTypeWimax);
}
// static
NetworkTypePattern NetworkTypePattern::Primitive(
const std::string& shill_network_type) {
return NetworkTypePattern(ShillNetworkTypeToFlag(shill_network_type));
}
bool NetworkTypePattern::Equals(const NetworkTypePattern& other) const {
return pattern_ == other.pattern_;
}
bool NetworkTypePattern::MatchesType(
const std::string& shill_network_type) const {
return MatchesPattern(Primitive(shill_network_type));
}
bool NetworkTypePattern::MatchesPattern(
const NetworkTypePattern& other_pattern) const {
if (Equals(other_pattern))
return true;
return pattern_ & other_pattern.pattern_;
}
std::string NetworkTypePattern::ToDebugString() const {
if (Equals(Default()))
return kPatternDefault;
if (Equals(Ethernet()))
return kPatternEthernet;
if (Equals(Wireless()))
return kPatternWireless;
if (Equals(Mobile()))
return kPatternMobile;
if (Equals(NonVirtual()))
return kPatternNonVirtual;
std::string str;
for (size_t i = 0; i < arraysize(shill_type_to_flag); ++i) {
if (!(pattern_ & shill_type_to_flag[i].bit_flag))
continue;
if (!str.empty())
str += "|";
str += shill_type_to_flag[i].shill_network_type;
}
return str;
}
NetworkTypePattern::NetworkTypePattern(int pattern) : pattern_(pattern) {}
} // namespace chromeos
| 34.729064 | 80 | 0.698156 | [
"vector"
] |
d0da6842b463f0d5a3fd2ec6dd6aaa09c70285df | 6,151 | cpp | C++ | svc_kube_vision_opencvplus/extras/nanoflann/tests/test_main.cpp | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | 3 | 2018-06-22T07:55:51.000Z | 2021-06-21T19:18:16.000Z | svc_kube_vision_opencvplus/extras/nanoflann/tests/test_main.cpp | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | null | null | null | svc_kube_vision_opencvplus/extras/nanoflann/tests/test_main.cpp | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | 1 | 2020-11-04T04:56:50.000Z | 2020-11-04T04:56:50.000Z | /***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2011-2014 Jose Luis Blanco (joseluisblancoc@gmail.com).
* All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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 <gtest/gtest.h>
#include <nanoflann.hpp>
#include <cstdlib>
#include <iostream>
using namespace std;
using namespace nanoflann;
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
// This is an exampleof a custom data set class
template <typename T>
struct PointCloud
{
struct Point
{
T x,y,z;
};
std::vector<Point> pts;
// Must return the number of data points
inline size_t kdtree_get_point_count() const { return pts.size(); }
// Returns the distance between the vector "p1[0:size-1]" and the data point with index "idx_p2" stored in the class:
inline T kdtree_distance(const T *p1, const size_t idx_p2,size_t /* size*/) const
{
const T d0=p1[0]-pts[idx_p2].x;
const T d1=p1[1]-pts[idx_p2].y;
const T d2=p1[2]-pts[idx_p2].z;
return d0*d0+d1*d1+d2*d2;
}
// Returns the dim'th component of the idx'th point in the class:
// Since this is inlined and the "dim" argument is typically an immediate value, the
// "if/else's" are actually solved at compile time.
inline T kdtree_get_pt(const size_t idx, int dim) const
{
if (dim==0) return pts[idx].x;
else if (dim==1) return pts[idx].y;
else return pts[idx].z;
}
// Optional bounding-box computation: return false to default to a standard bbox computation loop.
// Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again.
// Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)
template <class BBOX>
bool kdtree_get_bbox(BBOX & /* bb*/ ) const { return false; }
};
template <typename T>
void generateRandomPointCloud(PointCloud<T> &point, const size_t N, const T max_range = 10)
{
point.pts.resize(N);
for (size_t i=0;i<N;i++)
{
point.pts[i].x = max_range * (rand() % 1000) / T(1000);
point.pts[i].y = max_range * (rand() % 1000) / T(1000);
point.pts[i].z = max_range * (rand() % 1000) / T(1000);
}
}
template <typename num_t>
void L2_vs_L2_simple_test(const size_t N, const size_t num_results)
{
PointCloud<num_t> cloud;
// Generate points:
generateRandomPointCloud(cloud, N);
num_t query_pt[3] = { 0.5, 0.5, 0.5};
// construct a kd-tree index:
typedef KDTreeSingleIndexAdaptor<
L2_Simple_Adaptor<num_t, PointCloud<num_t> > ,
PointCloud<num_t>,
3 /* dim */
> my_kd_tree_simple_t;
typedef KDTreeSingleIndexAdaptor<
L2_Adaptor<num_t, PointCloud<num_t> > ,
PointCloud<num_t>,
3 /* dim */
> my_kd_tree_t;
my_kd_tree_simple_t index1(3 /*dim*/, cloud, KDTreeSingleIndexAdaptorParams(10 /* max leaf */) );
index1.buildIndex();
my_kd_tree_t index2(3 /*dim*/, cloud, KDTreeSingleIndexAdaptorParams(10 /* max leaf */) );
index2.buildIndex();
// do a knn search
std::vector<size_t> ret_index(num_results);
std::vector<num_t> out_dist_sqr(num_results);
nanoflann::KNNResultSet<num_t> resultSet(num_results);
resultSet.init(&ret_index[0], &out_dist_sqr[0] );
index1.findNeighbors(resultSet, &query_pt[0], nanoflann::SearchParams(10));
std::vector<size_t> ret_index1 = ret_index;
std::vector<num_t> out_dist_sqr1 = out_dist_sqr;
resultSet.init(&ret_index[0], &out_dist_sqr[0] );
index2.findNeighbors(resultSet, &query_pt[0], nanoflann::SearchParams(10));
for (size_t i=0;i<num_results;i++)
{
EXPECT_EQ(ret_index1[i],ret_index[i]);
EXPECT_DOUBLE_EQ(out_dist_sqr1[i],out_dist_sqr[i]);
}
}
TEST(kdtree,L2_vs_L2_simple)
{
for (int nResults=1;nResults<10;nResults++)
{
L2_vs_L2_simple_test<float>(100, nResults);
L2_vs_L2_simple_test<double>(100, nResults);
}
}
TEST(kdtree,robust_empty_tree)
{
// Try to build a tree with 0 data points, to test
// robustness against this situation:
PointCloud<double> cloud;
double query_pt[3] = { 0.5, 0.5, 0.5};
// construct a kd-tree index:
typedef KDTreeSingleIndexAdaptor<
L2_Simple_Adaptor<double, PointCloud<double> > ,
PointCloud<double>,
3 /* dim */
> my_kd_tree_simple_t;
my_kd_tree_simple_t index1(3 /*dim*/, cloud, KDTreeSingleIndexAdaptorParams(10 /* max leaf */) );
index1.buildIndex();
// Now we will try to search in the tree, and WE EXPECT a result of
// no neighbors found if the error detection works fine:
const size_t num_results = 1;
std::vector<size_t> ret_index(num_results);
std::vector<double> out_dist_sqr(num_results);
nanoflann::KNNResultSet<double> resultSet(num_results);
resultSet.init(&ret_index[0], &out_dist_sqr[0] );
bool result = index1.findNeighbors(resultSet, &query_pt[0],
nanoflann::SearchParams(10));
EXPECT_EQ(result, false);
}
| 31.706186 | 123 | 0.703951 | [
"vector"
] |
d0e0a0d30d791daf1302b82940ef741234107214 | 3,614 | cpp | C++ | Dev/SourcesEngine/Gugu/Element/2D/ElementSprite.cpp | Legulysse/gugu-engine | 0014f85f27f378f4490918638fcc747367e82243 | [
"Zlib"
] | 15 | 2018-06-30T12:02:03.000Z | 2022-02-16T00:23:45.000Z | Dev/SourcesEngine/Gugu/Element/2D/ElementSprite.cpp | Legulysse/gugu-engine | 0014f85f27f378f4490918638fcc747367e82243 | [
"Zlib"
] | null | null | null | Dev/SourcesEngine/Gugu/Element/2D/ElementSprite.cpp | Legulysse/gugu-engine | 0014f85f27f378f4490918638fcc747367e82243 | [
"Zlib"
] | 1 | 2018-07-26T22:40:20.000Z | 2018-07-26T22:40:20.000Z | ////////////////////////////////////////////////////////////////
// Header
#include "Gugu/Common.h"
#include "Gugu/Element/2D/ElementSprite.h"
////////////////////////////////////////////////////////////////
// Includes
#include "Gugu/Resources/ManagerResources.h"
#include "Gugu/Resources/Texture.h"
#include "Gugu/Resources/ImageSet.h"
#include "Gugu/Window/Renderer.h"
#include "Gugu/External/PugiXmlWrap.h"
#include "Gugu/Math/MathUtility.h"
#include <SFML/Graphics/RenderTarget.hpp>
////////////////////////////////////////////////////////////////
// File Implementation
namespace gugu {
ElementSprite::ElementSprite()
: m_texture(nullptr)
{
}
ElementSprite::~ElementSprite()
{
}
void ElementSprite::SetTexture(const std::string& _strTexturePath)
{
SetTexture(GetResources()->GetTexture(_strTexturePath));
}
void ElementSprite::SetTexture(Texture* _pTexture)
{
if (_pTexture)
{
m_texture = _pTexture;
SetSubRect(sf::IntRect(Vector2i(), m_texture->GetSize()));
}
}
void ElementSprite::SetSubImage(const std::string& _strImageSetName, const std::string& _strSubImageName)
{
ImageSet* pImageSet = GetResources()->GetImageSet(_strImageSetName);
if (pImageSet)
SetSubImage(pImageSet->GetSubImage(_strSubImageName));
}
void ElementSprite::SetSubImage(SubImage* _pSubImage)
{
if (_pSubImage && _pSubImage->GetImageSet() && _pSubImage->GetImageSet()->GetTexture())
{
m_texture = _pSubImage->GetImageSet()->GetTexture();
SetSubRect(_pSubImage->GetRect());
}
}
Texture* ElementSprite::GetTexture() const
{
return m_texture;
}
void ElementSprite::RenderImpl(RenderPass& _kRenderPass, const sf::Transform& _kTransformSelf)
{
if (!m_texture || !m_texture->GetSFTexture())
return;
sf::FloatRect kGlobalTransformed = _kTransformSelf.transformRect(sf::FloatRect(Vector2f(), m_size));
if (_kRenderPass.rectViewport.intersects(kGlobalTransformed))
{
if (m_dirtyVertices)
{
m_dirtyVertices = false;
RecomputeVerticesPositionAndTextureCoords();
RecomputeVerticesColor();
}
// Draw
sf::RenderStates states;
states.transform = _kTransformSelf;
states.texture = m_texture->GetSFTexture();
_kRenderPass.target->draw(m_vertices, states);
// Stats
if (_kRenderPass.frameInfos)
{
_kRenderPass.frameInfos->statDrawCalls += 1;
_kRenderPass.frameInfos->statTriangles += m_vertices.getVertexCount() / 3;
}
_kRenderPass.statRenderedSprites += 1;
}
}
void ElementSprite::RecomputeVerticesPositionAndTextureCoords()
{
size_t count = GetRequiredVertexCount();
// Reset vertices
m_vertices.setPrimitiveType(sf::Triangles);
m_vertices.resize(count);
ElementSpriteBase::RecomputeVerticesPositionAndTextureCoords(&m_vertices[0]);
}
void ElementSprite::RecomputeVerticesColor()
{
ElementSpriteBase::RecomputeVerticesColor(&m_vertices[0], m_vertices.getVertexCount());
}
bool ElementSprite::LoadFromXml(const pugi::xml_node& _oNodeElement)
{
if (!ElementSpriteBase::LoadFromXml(_oNodeElement))
return false;
pugi::xml_node oNodeTexture = _oNodeElement.child("Texture");
if (!oNodeTexture.empty())
{
std::string strTexturePath = oNodeTexture.attribute("source").as_string("");
SetTexture(strTexturePath);
}
return true;
}
} // namespace gugu
| 27.172932 | 106 | 0.633924 | [
"transform"
] |
d0e698ddc6c18959304e709f7a88f8d8d5880dc0 | 34,923 | cpp | C++ | kgl_app/kgl_properties.cpp | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | 1 | 2021-04-09T16:24:06.000Z | 2021-04-09T16:24:06.000Z | kgl_app/kgl_properties.cpp | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | kgl_app/kgl_properties.cpp | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | //
// Created by kellerberrin on 11/11/18.
//
#include "kgl_properties.h"
#include "kel_utility.h"
#include <set>
namespace kgl = kellerberrin::genome;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Boilerplate code to extract structured analytic and file information from "runtime.xml"
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool kgl::RuntimeProperties::readProperties(const std::string& properties_file) {
std::string properties_path = Utility::filePath(properties_file, work_directory_);
return property_tree_.readProperties(properties_path);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Runtime xml retrieval
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A vector of active packages.
// Parse the list of VCF Alias for Chromosome/Contigs in the Genome Database.
kgl::ActivePackageVector kgl::RuntimeProperties::getActivePackages() const {
ActivePackageVector active_packages;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + std::string(EXECUTE_LIST_) + std::string(DOT_) + std::string(ACTIVE_);
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().info("RuntimeProperties::getActivePackages, No Active Packages Specified");
return active_packages;
}
for (const auto& sub_tree : property_tree_vector) {
if (sub_tree.first == PACKAGE_) {
std::string active_package = sub_tree.second.getValue();
active_packages.emplace_back(active_package);
}
}
return active_packages;
}
// A map of analysis
kgl::RuntimePackageMap kgl::RuntimeProperties::getPackageMap() const {
RuntimePackageMap package_map;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + PACKAGE_LIST_;
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().error("RuntimeProperties::getPackageMap, no Analysis Packages Specified (must be a least one)");
return package_map; // return empty map.
}
// For each package
for (auto const& sub_tree : property_tree_vector) {
// Only process Package records.
if (sub_tree.first != PACKAGE_) continue;
// Get the Package Ident.
key = std::string(PACKAGE_IDENT_);
std::string package_ident;
if (not sub_tree.second.getProperty(key, package_ident)) {
ExecEnv::log().error("RuntimeProperties::getPackageMap, No Package Identifier");
continue;
}
// Get a Vector of Analysis functions to perform. These must be defined in code.
// This means we can perform more than one analysis for each time-expensive data file read.
std::vector<SubPropertyTree> analysis_sub_trees;
std::string key = PACKAGE_ANALYSIS_LIST_;
if (not sub_tree.second.getPropertyTreeVector(key , analysis_sub_trees)) {
ExecEnv::log().warn("RuntimeProperties::getPackageMap, No Analysis specified for Package: {} (use 'NULL' analysis)", package_ident);
}
std::vector<std::string> analysis_vector;
for (auto const& analysis_sub_tree : analysis_sub_trees) {
if (analysis_sub_tree.first == ANALYSIS_) {
std::string analysis_ident = analysis_sub_tree.second.getValue();
if (analysis_ident.empty()) {
ExecEnv::log().critical("RuntimeProperties::getPackageMap, Package: {}, No Analysis identifier specified", package_ident);
} else {
analysis_vector.push_back(analysis_ident);
}
}
}
// Get a Vector of Package Resources to be provided to the package by the runtime executive.
// A package resource is simply a pair of a resource type as a string and a resource identifier as a string.
// This is done on initialization.
std::vector<SubPropertyTree> resource_vector;
if (not sub_tree.second.getPropertyTreeVector(PACKAGE_RESOURCE_LIST_, resource_vector)) {
ExecEnv::log().warn("RuntimeProperties::getPackageMap, No resources specified for Package: {}", package_ident);
}
std::vector<std::pair<RuntimeResourceType,std::string>> resources;
for (auto const& resource_sub_tree : resource_vector) {
std::string resource_type = resource_sub_tree.first;
std::string resource_identifier = resource_sub_tree.second.getValue();
if (resource_identifier.empty()) {
ExecEnv::log().critical("RuntimeProperties::getPackageMap, Package: {}, Resource: {} No resource identifier specified", package_ident, resource_type);
} else {
if (resource_type == ONTOLOGY_DATABASE_) {
resources.emplace_back(RuntimeResourceType::ONTOLOGY_DATABASE, resource_identifier);
} else if (resource_type == GENOME_DATABASE_) {
resources.emplace_back(RuntimeResourceType::GENOME_DATABASE, resource_identifier);
} else if (resource_type == GENE_ID_DATABASE_) {
resources.emplace_back(RuntimeResourceType::GENE_NOMENCLATURE, resource_identifier);
} else if (resource_type == GENEALOGY_ID_DATABASE_) {
resources.emplace_back(RuntimeResourceType::GENOME_GENEALOGY, resource_identifier);
} else if (resource_type == AUX_ID_DATABASE_) {
resources.emplace_back(RuntimeResourceType::GENOME_AUX_INFO, resource_identifier);
} else if (resource_type == CITATION_DATABASE_) {
resources.emplace_back(RuntimeResourceType::ALLELE_CITATION, resource_identifier);
} else if (resource_type == ENTREZ_DATABASE_) {
resources.emplace_back(RuntimeResourceType::ENTREZ_GENE, resource_identifier);
} else if (resource_type == PMID_BIO_DATABASE_) {
resources.emplace_back(RuntimeResourceType::BIO_PMID, resource_identifier);
} else if (resource_type == PUBMED_LIT_API_) {
resources.emplace_back(RuntimeResourceType::PUBMED_API, resource_identifier);
}
}
} // for resources
// Get a Vector of iteration items (VCF files) to load iteratively.
// Each of these larger data (VCF) files are iteratively loaded into memory and then presented to the analysis functions.
// The data memory is recovered and the next file is loaded and analysed.
std::vector<SubPropertyTree> iteration_vector;
if (not sub_tree.second.getPropertyTreeVector(PACKAGE_ITERATION_LIST_, iteration_vector)) {
ExecEnv::log().warn("RuntimeProperties::getPackageMap, No Iteration items (VCF Files) specified for Package: {}", package_ident);
}
std::vector<std::vector<std::string>> vector_iteration_files;
for (auto const& iteration_sub_tree : iteration_vector) {
std::vector<std::string> iteration_files;
if (iteration_sub_tree.first == PACKAGE_ITERATION_) {
if (not iteration_sub_tree.second.getNodeVector(DATA_FILE_IDENT_, iteration_files)) {
ExecEnv::log().critical("RuntimeProperties::getPackageMap, No Iteration items (VCF Files) specified for Package: {}", package_ident);
}
}
if (not iteration_files.empty()) {
vector_iteration_files.push_back(iteration_files);
}
}
std::pair<std::string, RuntimePackage> new_package(package_ident, RuntimePackage(package_ident, analysis_vector, resources, vector_iteration_files));
auto result = package_map.insert(new_package);
if (not result.second) {
ExecEnv::log().error("RuntimeProperties::getPackageMap, Could not add Package Ident: {} to map (duplicate)", package_ident);
}
}
return package_map;
}
// A map of analysis
kgl::RuntimeAnalysisMap kgl::RuntimeProperties::getAnalysisMap() const {
RuntimeAnalysisMap analysis_map;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + ANALYSIS_LIST_;
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().info("RuntimeProperties::getAnalysisMap, no Analysis specified (NULL analysis available)");
return analysis_map; // return empty map.
}
for (const auto& sub_tree : property_tree_vector) {
// Only process Analysis records.
if (sub_tree.first != ANALYSIS_) continue;
key = std::string(ANALYSIS_IDENT_);
std::string analysis_ident;
if (not sub_tree.second.getProperty( key, analysis_ident)) {
ExecEnv::log().error("RuntimeProperties::getAnalysisMap, No Analysis Identifier");
continue;
}
key = std::string(PARAMETER_RUNTIME_) + std::string(DOT_) + std::string(ACTIVE_);
std::vector<SubPropertyTree> parameter_tree_vector;
if (not sub_tree.second.getPropertyTreeVector(key, parameter_tree_vector)) {
ExecEnv::log().info("RuntimeProperties::getAnalysisMap, no Parameters Specified for Analysis: {}", analysis_ident);
return analysis_map; // return empty map.
}
RuntimeParameterMap parameter_map;
for (const auto& parameter_sub_tree : parameter_tree_vector) {
// Only process parameter records.
if (parameter_sub_tree.first == PARAMETER_BLOCK_) {
std::string parameter_ident = parameter_sub_tree.second.getValue();
if (parameter_ident.empty()) {
ExecEnv::log().error("RuntimeProperties::getAnalysisMap, No Parameter Identifier Found for Analysis: {}", analysis_ident);
continue;
} else {
parameter_map.push_back(parameter_ident);
}
} // if parameter block.
} // for parameter
std::pair<std::string, RuntimeAnalysis> new_analysis(analysis_ident, RuntimeAnalysis(analysis_ident, parameter_map));
auto result = analysis_map.insert(new_analysis);
if (not result.second) {
ExecEnv::log().error("RuntimeProperties::getAnalysisMap, Could not add Analysis Ident: {} to map (duplicate)", analysis_ident);
}
}
return analysis_map;
}
// A map of resources.
kgl::RuntimeResourceMap kgl::RuntimeProperties::getRuntimeResources() const {
RuntimeResourceMap resource_map;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + RESOURCE_LIST_;
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().warn("RuntimeProperties::getRuntimeResources; No runtime resources specified.");
return resource_map; // return empty map.
}
for (const auto& [tree_type, sub_tree] : property_tree_vector) {
// Only process Genome records.
if (tree_type == GENOME_DATABASE_) {
key = std::string(GENOME_IDENT_);
std::string genome_ident;
if (not sub_tree.getProperty( key, genome_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Genome Database Identifier.");
continue;
}
key = std::string(FASTA_FILE_);
std::string fasta_file_name;
if (not sub_tree.getFileProperty( key, workDirectory(), fasta_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Fasta file name information.");
continue;
}
key = std::string(GFF_FILE_);
std::string gff_file_name;
if (not sub_tree.getFileProperty( key, workDirectory(), gff_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, No Gff file name information.");
continue;
}
key = std::string(TRANSLATION_TABLE_);
std::string translation_table;
if (not sub_tree.getProperty( key, translation_table)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, No DNA/Amino translation table specified.");
continue;
}
key = std::string(GAF_ANNOTATION_FILE_);
std::string gaf_file_name;
if (not sub_tree.getOptionalFileProperty(key, workDirectory(), gaf_file_name)) {
gaf_file_name.clear();
}
RuntimeGenomeResource new_genome_db(genome_ident, fasta_file_name, gff_file_name, translation_table);
new_genome_db.setGafFileName(gaf_file_name);
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeGenomeResource>(new_genome_db);
auto const [iter, result] = resource_map.try_emplace(genome_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Genome Database ident: {} to map (duplicate)", genome_ident);
}
} else if (tree_type == ONTOLOGY_DATABASE_) {
key = std::string(ONTOLOGY_IDENT_);
std::string ontology_ident;
if (not sub_tree.getProperty(key, ontology_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Ontology Database Identifier.");
continue;
}
key = std::string(GAF_ANNOTATION_FILE_);
std::string annotation_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), annotation_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Ontology Annotation (GAF) file name information.");
continue;
}
key = std::string(GO_ONTOLOGY_FILE_);
std::string go_graph_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), go_graph_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, No Ontology GO file name information.");
continue;
}
RuntimeOntologyResource new_ontology_db(ontology_ident, annotation_file_name, go_graph_file_name);
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeOntologyResource>(new_ontology_db);
auto const [iter, result] = resource_map.try_emplace(ontology_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Genome Database ident: {} to map (duplicate)", ontology_ident);
}
} else if (tree_type == GENE_ID_DATABASE_) {
key = std::string(GENE_ID_IDENT_);
std::string nomenclature_ident;
if (not sub_tree.getProperty(key, nomenclature_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No gene Nomenclature Identifier.");
continue;
}
key = std::string(GENE_ID_FILE_);
std::string nomenclature_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), nomenclature_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Gene Nomenclature file name information, ident: {}", nomenclature_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeNomenclatureResource>(nomenclature_ident,
nomenclature_file_name);
auto const [iter, result] = resource_map.try_emplace(nomenclature_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Gene Nomenclature ident: {} to map (duplicate)", nomenclature_ident);
}
} else if (tree_type == GENEALOGY_ID_DATABASE_) {
key = std::string(GENEALOGY_ID_IDENT_);
std::string genealogy_ident;
if (not sub_tree.getProperty(key, genealogy_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Genome Genealogy Identifier.");
continue;
}
key = std::string(GENEALOGY_ID_FILE_);
std::string genealogy_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), genealogy_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Genome Genealogy file name information, ident: {}", genealogy_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeGenealogyResource>(genealogy_ident, genealogy_file_name);
auto const [iter, result] = resource_map.try_emplace(genealogy_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Genome Genealogy ident: {} to map (duplicate)", genealogy_ident);
}
} else if (tree_type == CITATION_DATABASE_) {
key = std::string(CITATION_IDENT_);
std::string citation_ident;
if (not sub_tree.getProperty(key, citation_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Allele Citation Identifier.");
continue;
}
key = std::string(CITATION_FILE_);
std::string citation_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), citation_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Allele Citation file name information, ident: {}", citation_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeCitationResource>(citation_ident, citation_file_name);
auto const [iter, result] = resource_map.try_emplace(citation_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Allele Citation ident: {} to map (duplicate)", citation_ident);
}
} else if (tree_type == ENTREZ_DATABASE_) {
key = std::string(ENTREZ_IDENT_);
std::string entrez_ident;
if (not sub_tree.getProperty(key, entrez_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Entrez Gene Identifier.");
continue;
}
key = std::string(ENTREZ_FILE_);
std::string entrez_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), entrez_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Entrez Gene file name information, ident: {}", entrez_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeEntrezResource>(entrez_ident, entrez_file_name);
auto const [iter, result] = resource_map.try_emplace(entrez_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Entrez Gene ident: {} to map (duplicate)", entrez_ident);
}
} else if (tree_type == PMID_BIO_DATABASE_) {
key = std::string(PMID_BIO_IDENT_);
std::string bio_ident;
if (not sub_tree.getProperty(key, bio_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No PMID Bio Gene Identifier.");
continue;
}
key = std::string(PMID_BIO_FILE_);
std::string bio_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), bio_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No PMID Bio file name information, ident: {}", bio_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeBioPMIDResource>(bio_ident, bio_file_name);
auto const [iter, result] = resource_map.try_emplace(bio_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add PMID Bio ident: {} to map (duplicate)", bio_ident);
}
} else if (tree_type == PUBMED_LIT_API_) {
key = std::string(PUBMED_LIT_IDENT_);
std::string pubmed_api_ident;
if (not sub_tree.getProperty(key, pubmed_api_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Pubmed API Identifier.");
continue;
}
key = std::string(PUBMED_PUBLICATION_CACHE_);
std::string publication_cache_file; // Note that the cache file(s) may not exist.
if (not sub_tree.getFileCreateProperty(key, workDirectory(), publication_cache_file)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; Cannot create Pubmed publication API Cache file, ident: {}", pubmed_api_ident);
continue;
}
key = std::string(PUBMED_CITATION_CACHE_);
std::string citation_cache_file; // Note that the cache file(s) may not exist.
if (not sub_tree.getFileCreateProperty(key, workDirectory(), citation_cache_file)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; Cannot create Pubmed citation API Cache file, ident: {}", pubmed_api_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimePubmedAPIResource>( pubmed_api_ident,
publication_cache_file,
citation_cache_file);
auto const [iter, result] = resource_map.try_emplace(pubmed_api_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Pubmed APi ident: {} to map (duplicate)", pubmed_api_ident);
}
} else if (tree_type == GENE_ID_DATABASE_) {
key = std::string(GENE_ID_IDENT_);
std::string nomenclature_ident;
if (not sub_tree.getProperty(key, nomenclature_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No gene Nomenclature Identifier.");
continue;
}
key = std::string(GENE_ID_FILE_);
std::string nomenclature_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), nomenclature_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Gene Nomenclature file name information, ident: {}", nomenclature_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeNomenclatureResource>(nomenclature_ident,
nomenclature_file_name);
auto const [iter, result] = resource_map.try_emplace(nomenclature_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Gene Nomenclature ident: {} to map (duplicate)", nomenclature_ident);
}
} else if (tree_type == AUX_ID_DATABASE_) {
key = std::string(AUX_ID_IDENT_);
std::string genome_aux_ident;
if (not sub_tree.getProperty(key, genome_aux_ident)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Genome Aux Identifier.");
continue;
}
key = std::string(AUX_ID_FILE_);
std::string genome_aux_file_name;
if (not sub_tree.getFileProperty(key, workDirectory(), genome_aux_file_name)) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources; No Genome Aux file name information, ident: {}", genome_aux_ident);
continue;
}
std::shared_ptr<const RuntimeResource> resource_ptr = std::make_shared<const RuntimeGenomeAuxResource>(genome_aux_ident, genome_aux_file_name);
auto const [iter, result] = resource_map.try_emplace(genome_aux_ident, resource_ptr);
if (not result) {
ExecEnv::log().error("RuntimeProperties::getRuntimeResources, Could not add Genome Aux ident: {} to map (duplicate)", genome_aux_ident);
}
} // Genome Aux
} // For all resources.
return resource_map;
}
// A map of VCF files.
kgl::RuntimeDataFileMap kgl::RuntimeProperties::getDataFiles() const {
RuntimeDataFileMap data_file_map;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + DATA_FILE_LIST_;
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().info("RuntimeProperties::getDataFiles, no Data files specified");
return data_file_map; // return empty map.
}
for (const auto& sub_tree : property_tree_vector) {
// Process VCF file record.
if (sub_tree.first == VCF_DATA_FILE_TYPE_) {
key = std::string(DATA_FILE_IDENT_);
std::string vcf_ident;
if (not sub_tree.second.getProperty( key, vcf_ident)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; No VCF Identifier");
continue;
}
key = std::string(DATA_FILE_NAME_);
std::string vcf_file_name;
if (not sub_tree.second.getFileProperty( key, workDirectory(), vcf_file_name)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; No VCF file name information");
continue;
}
key = std::string(DATA_PARSER_TYPE_);
std::string vcf_parser_type;
if (not sub_tree.second.getProperty( key, vcf_parser_type)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; No VCF file parser type information");
continue;
}
key = std::string(VCF_FILE_GENOME_);
std::string vcf_reference_genome;
if (not sub_tree.second.getProperty( key, vcf_reference_genome)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; No reference genome information for VCF file: {}", vcf_file_name);
continue;
}
key = std::string(VCF_INFO_EVIDENCE_);;
std::string evidence_ident;
if (not sub_tree.second.getProperty(key, evidence_ident)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; No VCF Info evidence specified for VCF file: {}", vcf_file_name);
}
std::shared_ptr<BaseFileInfo> file_info_ptr = std::make_shared<RuntimeVCFFileInfo>( vcf_ident,
vcf_file_name,
vcf_parser_type,
vcf_reference_genome,
evidence_ident);
auto result = data_file_map.try_emplace(vcf_ident, file_info_ptr);
if (not result.second) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; Could not add VCF file ident: {} to map (duplicate)", vcf_ident);
}
} else if (sub_tree.first == GENERAL_DATA_FILE_TYPE_) { // Process General file record.
key = std::string(DATA_FILE_IDENT_);
std::string ped_ident;
if (not sub_tree.second.getProperty(key, ped_ident)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; General Data File; No File Identifier");
continue;
}
key = std::string(DATA_FILE_NAME_);
std::string ped_file_name;
if (not sub_tree.second.getFileProperty(key, workDirectory(), ped_file_name)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; General Data File; No file name information");
continue;
}
key = std::string(DATA_PARSER_TYPE_);
std::string ped_parser_type;
if (not sub_tree.second.getProperty(key, ped_parser_type)) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; General Data File; No file parser type information");
continue;
}
std::shared_ptr<BaseFileInfo> file_info_ptr = std::make_shared<BaseFileInfo>( ped_ident,
ped_file_name,
ped_parser_type);
auto result = data_file_map.try_emplace(ped_ident, file_info_ptr);
if (not result.second) {
ExecEnv::log().error("RuntimeProperties::getDataFiles; Could not add PED file ident: {} to map (duplicate)", ped_ident);
}
}
} // for
return data_file_map;
}
// Parse the list of VCF Alias for Chromosome/Contigs in the Genome Database.
kgl::ContigAliasMap kgl::RuntimeProperties::getContigAlias() const {
ContigAliasMap contig_alias_map;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + std::string(ALIAS_LIST_);
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().info("RuntimeProperties::getContigAlias, No Contig Alias Specified");
return contig_alias_map;
}
for (const auto& sub_tree : property_tree_vector) {
std::string contig_ident;
if (not sub_tree.second.getProperty(ALIAS_IDENT_, contig_ident)) {
ExecEnv::log().error("RuntimeProperties::getContigAlias, No Chromosome/Contig Identifier specified for Alias.");
continue;
}
std::string chromosome_type;
if (not sub_tree.second.getProperty(ALIAS_TYPE_, chromosome_type)) {
ExecEnv::log().error("RuntimeProperties::getContigAlias, No Chromosome type ('autosome', 'allosomeX', 'allosomeY' or 'mitochrondria') specified");
continue;
}
// Alias is idempotent.
contig_alias_map.setAlias(contig_ident, contig_ident, chromosome_type);
// Get a vector of alias
std::vector<std::string> alias_vector;
if (not sub_tree.second.getNodeVector(ALIAS_ENTRY_, alias_vector)) {
ExecEnv::log().warn("RuntimeProperties::getContigAlias, No Alias Specified for Contig: {}", sub_tree.first);
}
for (auto const& alias : alias_vector) {
contig_alias_map.setAlias(alias, contig_ident, chromosome_type);
}
}
return contig_alias_map;
}
kgl::VariantEvidenceMap kgl::RuntimeProperties::getEvidenceMap() const {
VariantEvidenceMap variant_evidence_map;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + std::string(EVIDENCE_LIST_);
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().info("RuntimeProperties::getEvidenceMap, No Variant Evidence items specified.");
return variant_evidence_map;
}
for (const auto& sub_tree : property_tree_vector) {
std::string evidence_ident;
key = std::string(EVIDENCE_IDENT_);
if (not sub_tree.second.getProperty(key, evidence_ident)) {
ExecEnv::log().error("RuntimeProperties::getEvidenceMap, No Evidence Identifier specified for evidence list.");
continue;
}
key = EVIDENCE_INFO_LIST_;
std::vector<SubPropertyTree> info_tree_vector;
if (not sub_tree.second.getPropertyTreeVector(key, info_tree_vector)) {
ExecEnv::log().info("RuntimeProperties::getEvidenceMap, no info items specified for evidence ident: {}", evidence_ident);
}
std::set<std::string> evidence_list;
for (const auto& info_sub_tree : info_tree_vector) {
// Only process info records.
if (info_sub_tree.first != EVIDENCE_INFO_ITEM_) continue;
std::string info = info_sub_tree.second.getValue();
auto result = evidence_list.insert(info);
if (not result.second) {
ExecEnv::log().warn("RuntimeProperties::getEvidenceMap, Duplicate Info item: {} specified for evidence ident: {}", info, evidence_ident);
}
} // for info item
variant_evidence_map.setEvidence(evidence_ident, evidence_list);
}
return variant_evidence_map;
}
kgl::ActiveParameterList kgl::RuntimeProperties::getParameterMap() const {
ActiveParameterList defined_named_parameters;
ContigAliasMap contig_alias_map;
std::string key = std::string(RUNTIME_ROOT_) + std::string(DOT_) + std::string(PARAMETER_LIST_);
std::vector<SubPropertyTree> property_tree_vector;
if (not property_tree_.getPropertyTreeVector(key, property_tree_vector)) {
ExecEnv::log().warn("RuntimeProperties::getParameterMap; No Parameter Blocks specified");
} else {
for (auto const& subtree : property_tree_vector) {
auto const& [sub_tree_tag, sub_tree] = subtree;
// Ignore any comments.
if (sub_tree_tag == PARAMETER_BLOCK_) {
NamedParameterVector named_parameter_vector;
// Get the block name.
std::string block_name;
if (not sub_tree.getProperty(PARAMETER_NAME_, block_name)) {
ExecEnv::log().error("RuntimeProperties::getParameterMap; No block <parameterName> specified, block skipped");
continue;
}
// Store the block name.
named_parameter_vector.first = Utility::trimEndWhiteSpace(block_name);
std::vector<SubPropertyTree> property_block_vector;
if (not sub_tree.getPropertySubTreeVector(property_block_vector)) {
ExecEnv::log().warn("RuntimeProperties::getParameterMap; No Parameter Vectors specified");
}
ParameterVector parameter_vector;
for (auto const &block_tree : property_block_vector) {
auto& [block_tree_tag, block_sub_tree] = block_tree;
if (block_tree_tag == PARAMETER_VECTOR_) {
std::vector<SubPropertyTree> property_vector;
if (not block_sub_tree.getPropertySubTreeVector(property_vector)) {
continue;
}
// Create a parameter map for each parameter vector.
ParameterMap parameter_map;
// Unpack the parameter vector.
for (auto const& vector_item : property_vector) {
auto const& [item_tag, item_tree] = vector_item;
// Ignore help and info tags.
if (item_tag == PARAMETER_) {
std::string parameter_ident;
if (not item_tree.getProperty(PARAMETER_IDENT_, parameter_ident)) {
ExecEnv::log().error("RuntimeProperties::getParameterMap; No block <parameterIdent> specified, parameter skipped");
continue;
}
std::string parameter_value;
if (not item_tree.getProperty(PARAMETER_VALUE_, parameter_value)) {
ExecEnv::log().error("RuntimeProperties::getParameterMap; No block <parameterValue> specified, parameter skipped");
continue;
}
parameter_ident = Utility::trimEndWhiteSpace(parameter_ident);
parameter_value = Utility::trimEndWhiteSpace(parameter_value);
parameter_map.insert(parameter_ident, parameter_value);
} // if Parameter
} // for all vector tags.
parameter_vector.push_back(parameter_map);
} // if vector
} // for all block tags
named_parameter_vector.second = parameter_vector;
defined_named_parameters.addNamedParameterVector(named_parameter_vector);
} // if block.
} // for all blocks.
} // if any blocks.
return defined_named_parameters;
}
| 33.742029 | 158 | 0.669129 | [
"vector"
] |
d0e99a48da9ec030b089e9dce527b58a125956d2 | 2,680 | cpp | C++ | BZOJ/BZOJ3696.cpp | xehoth/OnlineJudgeCodes | 013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7 | [
"Apache-2.0"
] | 7 | 2017-09-21T13:20:05.000Z | 2020-03-02T03:03:04.000Z | BZOJ/BZOJ3696.cpp | xehoth/OnlineJudgeCodes | 013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7 | [
"Apache-2.0"
] | null | null | null | BZOJ/BZOJ3696.cpp | xehoth/OnlineJudgeCodes | 013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7 | [
"Apache-2.0"
] | 3 | 2019-01-05T07:02:57.000Z | 2019-06-13T08:23:13.000Z | #include <bits/stdc++.h>
namespace IO {
inline char read() {
static const int IN_LEN = 100000;
static char buf[IN_LEN], *s, *t;
s == t ? t = (s = buf) + fread(buf, 1, IN_LEN, stdin) : 0;
return s == t ? -1 : *s++;
}
template <typename T>
inline void read(T &x) {
static char c;
static bool iosig;
for (c = read(), iosig = false; !isdigit(c); c = read()) {
if (c == -1) return;
c == '-' ? iosig = true : 0;
}
for (x = 0; isdigit(c); c = read()) x = x * 10 + (c ^ '0');
iosig ? x = -x : 0;
}
inline int read(char *buf) {
register int s = 0;
register char c;
while (c = read(), isspace(c) && c != -1)
;
if (c == -1) {
*buf = 0;
return -1;
}
do
buf[s++] = c;
while (c = read(), !isspace(c) && c != -1);
buf[s] = 0;
return s;
}
inline void read(char &x) {
while (x = read(), isspace(x) && x != -1)
;
}
const int OUT_LEN = 100000;
char obuf[OUT_LEN], *oh = obuf;
inline void print(char c) {
oh == obuf + OUT_LEN ? (fwrite(obuf, 1, oh - obuf, stdout), oh = obuf) : 0;
*oh++ = c;
}
template <typename T>
inline void print(T x) {
static int buf[30], cnt;
if (x == 0) {
print('0');
} else {
x < 0 ? (print('-'), x = -x) : 0;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48;
while (cnt) print((char)buf[cnt--]);
}
}
inline void flush() { fwrite(obuf, 1, oh - obuf, stdout); }
struct InputOutputStream {
template <typename T>
inline InputOutputStream &operator<<(const T &x) {
print(x);
return *this;
}
template <typename T>
inline InputOutputStream &operator>>(T &x) {
read(x);
return *this;
}
~InputOutputStream() { flush(); }
} io;
} // namespace IO
const int MAXN = 100005;
std::vector<int> edge[MAXN + 1];
int n, cnt;
int a[MAXN][505];
int ans[512], dep[MAXN];
inline void addEdge(const int u, const int v) { edge[u].push_back(v); }
inline void dfs(int x) {
a[x][0] = 1;
for (register int i = 0, v; i < edge[x].size(); i++) {
dfs(v = edge[x][i]);
for (int j = 0; j <= dep[x]; j++)
for (int k = 0; k <= dep[v]; k++)
ans[j ^ (k + 1)] += a[x][j] * a[v][k];
dep[x] = std::max(dep[x], dep[v] + 1);
for (int j = 0; j <= dep[v]; j++) a[x][j + 1] += a[v][j];
}
}
using IO::io;
int main() {
io >> n;
for (int i = 2, x; i <= n; i++) {
io >> x;
addEdge(x, i);
}
dfs(1);
register int mx = 512;
for (; mx; mx--)
if (ans[mx]) break;
for (int i = 0; i <= mx; i++) io << ans[i] << '\n';
return 0;
}
| 21.967213 | 79 | 0.469403 | [
"vector"
] |
d0f23af9b3fe2d8dcb5f6eeb3ada849f33360b0f | 8,149 | cc | C++ | optickscore/Sparse.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 11 | 2020-07-05T02:39:32.000Z | 2022-03-20T18:52:44.000Z | optickscore/Sparse.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | null | null | null | optickscore/Sparse.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 4 | 2020-09-03T20:36:32.000Z | 2022-01-19T07:42:21.000Z | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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 <numeric>
#include <algorithm>
#include <functional>
#include <cstring>
#include <limits>
#include "BStr.hh"
#include "BHex.hh"
#include "PLOG.hh"
#include "NPY.hpp"
#include "Index.hpp"
#include "Sparse.hh"
template <typename T>
Sparse<T>::Sparse(const char* label, NPY<T>* source, bool hexkey)
:
m_label(strdup(label)),
m_reldir(NULL),
m_source(source),
m_hexkey(hexkey),
m_num_unique(0),
m_num_lookup(0),
m_index(NULL)
{
init();
}
template <typename T>
Index* Sparse<T>::getIndex()
{
return m_index ;
}
template <typename T>
void Sparse<T>::init()
{
m_index = new Index(m_label, m_reldir);
}
template <typename T>
void Sparse<T>::make_lookup()
{
count_unique();
update_lookup();
populate_index(m_index);
}
template <typename T>
void Sparse<T>::count_unique()
{
typedef std::vector<T> V ;
assert(m_source->hasData());
assert(m_source->getNumItems() > 0);
V data(m_source->data());
std::sort(data.begin(), data.end());
m_num_unique = std::inner_product(
data.begin(),data.end() - 1, // first1, last1
data.begin() + 1, // first2
int(1), // output type init
std::plus<int>(), // reduction operator
std::not_equal_to<T>() // pair-by-pair operator, returning 1 at edges
);
LOG(debug) << "Sparse<T>::count_unique"
<< " label " << m_label
<< " num_unique " << m_num_unique
;
reduce_by_key(data);
sort_by_key();
}
template <typename T>
void Sparse<T>::update_lookup()
{
unsigned int max_uniques = SPARSE_LOOKUP_N ;
T zero(0);
m_lookup.resize( max_uniques, zero);
m_num_lookup = std::min( m_num_unique, max_uniques );
for(unsigned int i=0 ; i < m_num_lookup ; i++)
{
P valuecount = m_valuecount[i] ;
T value = valuecount.first ;
m_lookup[i] = value ;
}
memcpy(m_sparse_lookup, m_lookup.data(), SPARSE_LOOKUP_N*sizeof(T));
}
template <typename T>
unsigned int Sparse<T>::count_value(const T value) const
{
typedef std::vector<T> V ;
V& data = m_source->data();
return std::count(data.begin(), data.end(), value );
}
template <typename T>
void Sparse<T>::reduce_by_key(std::vector<T>& data)
{
m_valuecount.resize(m_num_unique);
unsigned int n = data.size();
T* vals = data.data() ;
T prev = *(vals + 0);
int count(1) ;
unsigned int unique(0) ;
T value(0) ;
// presumably this is assuming the vals are sorted, so
// it looks for transitions between the runs of repeats
//
// from the second
for(unsigned int i=1 ; i < n ; i++)
{
value = *(vals+i) ;
#if DEBUG
if(count < 10)
LOG(info)
<< std::setw(3) << "c"
<< std::setw(8) << i
<< std::hex << std::setw(16) << value
<< std::dec << std::setw(16) << value
<< std::setw(8) << count
;
#endif
if(value == prev)
{
count += 1 ;
}
else
{
#if DEBUG
if(unique < 100)
LOG(info)
<< std::setw(3) << "u"
<< std::setw(8) << i
<< std::hex << std::setw(16) << value
<< std::dec << std::setw(16) << value
<< std::setw(8) << count
<< std::setw(8) << unique
;
#endif
m_valuecount[unique++] = P(prev, count) ;
prev = value ;
count = 1 ;
}
}
// no transition possible, so must special case the last
if(value == prev)
{
m_valuecount[unique++] = P(value, count) ;
}
LOG(debug) << "Sparse<T>::reduce_by_key"
<< " unique " << unique
<< " num_unique " << m_num_unique
;
if(n > 1)
{
assert(unique == m_num_unique);
}
}
template <class T>
struct second_descending : public std::binary_function<T,T,bool> {
bool operator()(const T& a, const T& b) const {
return a.second > b.second ;
}
};
template <typename T>
void Sparse<T>::sort_by_key()
{
std::sort( m_valuecount.begin(), m_valuecount.end(), second_descending<P>());
}
template <typename T>
std::string Sparse<T>::dump_(const char* msg, bool slowcheck) const
{
std::stringstream ss ;
ss << msg << " : num_unique " << m_num_unique << std::endl ;
for(unsigned int i=0 ; i < m_valuecount.size() ; i++)
{
P valuecount = m_valuecount[i] ;
T value = valuecount.first ;
int count = valuecount.second ;
ss << "[" << std::setw(2) << i << "] " ;
if(m_hexkey) ss << std::hex ;
ss << std::setw(16) << value ;
if(m_hexkey) ss << std::dec ;
ss << std::setw(10) << count ;
if(slowcheck)
{
ss << std::setw(10) << count_value(value) ;
}
ss << std::endl ;
}
return ss.str();
}
template <typename T>
void Sparse<T>::dump(const char* msg) const
{
bool slowcheck = false ;
LOG(info) << dump_(msg, slowcheck) ;
}
template <typename T>
void Sparse<T>::populate_index(Index* index)
{
for(unsigned int i=0 ; i < m_num_lookup ; i++)
{
P valuecount = m_valuecount[i] ;
T value = valuecount.first ;
int count = valuecount.second ;
std::string key = m_hexkey ? BHex<T>::as_hex(value) : BHex<T>::as_dec(value) ;
if(count > 0) index->add(key.c_str(), count );
#ifdef DEBUG
std::cout << "Sparse<T>::populate_index "
<< " i " << std::setw(4) << i
<< " value " << std::setw(10) << value
<< " count " << std::setw(10) << count
<< " key " << key
<< std::endl
;
#endif
}
}
template <typename T, typename S>
struct apply_lookup_functor : public std::unary_function<T, S>
{
S m_offset ;
S m_missing ;
S m_size ;
T* m_lookup ;
apply_lookup_functor(S offset, S missing, S size, T* lookup)
:
m_offset(offset),
m_missing(missing),
m_size(size),
m_lookup(lookup)
{
}
S operator()(T seq)
{
S idx(m_missing);
for(unsigned int i=0 ; i < m_size ; i++)
{
if(seq == m_lookup[i]) idx = i + m_offset ;
}
return idx ;
}
};
template <typename T>
template <typename S>
void Sparse<T>::apply_lookup(S* target, unsigned int stride, unsigned int offset)
{
S s_missing = std::numeric_limits<S>::max() ;
S s_offset = 1 ;
apply_lookup_functor<T,S> fn(s_offset, s_missing, SPARSE_LOOKUP_N, m_sparse_lookup );
T* src = m_source->getValues();
unsigned int size = m_source->getShape(0);
for(unsigned int i=0 ; i < size ; i++)
{
T value = *(src + i) ;
*(target + i*stride + offset) = fn(value) ;
}
}
template class Sparse<unsigned long long> ;
template void Sparse<unsigned long long>::apply_lookup<unsigned char>(unsigned char* target, unsigned int stride, unsigned int offset);
| 23.552023 | 135 | 0.53663 | [
"vector"
] |
d0f6a9ba9083a6c4d38c62bd03baf9d5081d3585 | 8,439 | cpp | C++ | util/monitor.cpp | Junkrat77/tablefs-kv-wrapper | 993d7171a51a306d86e3f4628f0b382e767fa0ba | [
"BSD-3-Clause"
] | null | null | null | util/monitor.cpp | Junkrat77/tablefs-kv-wrapper | 993d7171a51a306d86e3f4628f0b382e767fa0ba | [
"BSD-3-Clause"
] | null | null | null | util/monitor.cpp | Junkrat77/tablefs-kv-wrapper | 993d7171a51a306d86e3f4628f0b382e767fa0ba | [
"BSD-3-Clause"
] | null | null | null | #include "util/monitor.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
namespace tablefs {
static const char* diskmetric[11] = {
"read_requests", // Total number of reads completed successfully.
"read_merged", // Adjacent read requests merged in a single req.
"read_sectors", // Total number of sectors read successfully.
"msec_read", // Total number of ms spent by all reads.
"write_requests", // total number of writes completed successfully.
"write_merged", // Adjacent write requests merged in a single req.
"write_sectors", // total number of sectors written successfully.
"msec_write", // Total number of ms spent by all writes.
"ios_in_progress", // Number of actual I/O requests currently in flight
"msec_total", // Amount of time during which ios_in_progress >= 1.
"msec_weighted_total", // Measure of recent I/O completion time and backlog
};
class IOStat: public MetricStat {
std::string devname;
public:
IOStat(const std::string& device_name) {
devname = device_name;
}
virtual void GetMetric(TMetList &metlist, time_t now) {
FILE* f=fopen("/proc/diskstats", "r");
if (f == NULL) {
return;
}
char device[20];
TTSValue metric[11];
int ret = 0;
while (!feof(f)) {
if (fscanf(f, "%s %s %s", device, device, device) < 3) {
break;
}
if (devname.compare(device) == 0) {
if (fscanf(f, "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
&metric[0], &metric[1], &metric[2], &metric[3],
&metric[4], &metric[5], &metric[6], &metric[7],
&metric[8], &metric[9], &metric[10]) < 11) {
break;
}
for (int i = 0; i < 11; ++i) {
AddMetric(metlist, devname+"."+std::string(diskmetric[i]), now , metric[i]);
}
} else {
char c;
do {
c = getc(f);
} while (c != '\n' && c != EOF);
}
}
fclose(f);
}
};
const static int NUM_SLAB_METRIC = 3;
static const char* slabmetric[NUM_SLAB_METRIC] = {
"active_objs",
"num_objs",
"objsize",
};
const static int NUM_SLAB_OBJ = 2;
static const char* slabobjname[NUM_SLAB_OBJ] = {
"dentry",
"inode_cache"
};
class SlabStat: public MetricStat {
std::string fsname;
int len_fsname;
public:
SlabStat(const std::string& filesystem_name) {
fsname = filesystem_name;
len_fsname = fsname.size();
}
virtual void GetMetric(TMetList &metlist, time_t now) {
FILE* f=fopen("/proc/slabinfo", "r");
if (f == NULL) {
return;
}
char objname[256];
char junk[256];
int tmp;
TTSValue metric;
if (fread(junk, 204, 1, f) != 1) {
return;
}
while (!feof(f)) {
if (fscanf(f, "%s", objname) < 1) {
break;
}
if (strncmp(fsname.c_str(), objname, len_fsname) == 0) {
for (int i = 0; i < NUM_SLAB_METRIC; ++i) {
if (fscanf(f, "%lld", &metric) < 1) {
break;
}
AddMetric(metlist, std::string(objname)+"."+std::string(slabmetric[i]),
now , metric);
}
} else {
for (int j = 0; j < NUM_SLAB_OBJ; ++j)
if (strncmp(objname, slabobjname[j],
strlen(slabobjname[j])) == 0)
{
for (int i = 0; i < NUM_SLAB_METRIC; ++i) {
if (fscanf(f, "%lld", &metric) < 1) {
break;
}
AddMetric(metlist, std::string(slabobjname[j])+"."+std::string(slabmetric[i]),
now , metric);
}
break;
}
}
char c;
do {
c = getc(f);
} while (c != '\n' && c != EOF);
}
fclose(f);
}
};
class MemStat: public MetricStat {
std::string fsname;
public:
virtual void GetMetric(TMetList &metlist, time_t now) {
FILE* f=fopen("/proc/meminfo", "r");
if (f == NULL) {
return;
}
char metname[256];
char junk[256];
int tmp;
TTSValue metric;
for (int i = 0; i < 30; ++i) {
if (fscanf(f, "%s %lld %s", metname, &metric, junk) < 3) {
break;
}
AddMetric(metlist, std::string(metname, strlen(metname)), now , metric);
}
fclose(f);
}
};
class ProcStat: public MetricStat {
private:
int pid;
int page_size;
std::string name;
int FindPid(std::string cmdline) {
char shellcmd[1024];
sprintf(shellcmd, "ps -ef | grep /'%s/' | cut -c 9-15", cmdline.c_str());
FILE* outf = popen(shellcmd, "r");
int pid = -1;
if (outf != NULL) {
if (fscanf(outf, "%d", &pid) != 1) {
pid = -1;
}
pclose(outf);
}
printf("FindPid: %s, %d\n", cmdline.c_str(), pid);
return pid;
}
public:
ProcStat(std::string cmdline=std::string("")) {
if (cmdline.size() > 0) {
name = cmdline;
pid = FindPid(cmdline);
} else {
name = "self";
pid = getpid();
}
page_size = sysconf(_SC_PAGESIZE);
}
virtual void GetMetric(TMetList &metlist, time_t now) {
if (pid == -1) {
return;
}
char tmp[256];
sprintf(tmp, "/proc/%d/stat", pid);
FILE* f=fopen(tmp, "r");
if (f == NULL) {
return;
}
for (int i = 0; i < 13; ++i)
if (fscanf(f, "%s", tmp) < 1)
return;
double proctime;
if (fscanf(f, "%lf", &proctime) < 1)
return;
AddMetric(metlist, name+std::string(".utime"), now, TTSValue(proctime*100));
if (fscanf(f, "%lf", &proctime) < 1)
return;
AddMetric(metlist, name+std::string(".stime"), now, TTSValue(proctime*100));
for (int i = 0; i < 7; ++i)
if (fscanf(f, "%s", tmp) < 1)
return;
long long memory;
if (fscanf(f, "%lld", &memory) < 1)
return;
AddMetric(metlist, name+std::string(".vmsize"), now, memory);
if (fscanf(f, "%lld", &memory) < 1)
return;
AddMetric(metlist, name+std::string(".rss"), now, memory * page_size);
fclose(f);
}
};
class LatencyStat: public MetricStat {
std::string metname;
time_t lasttime;
public:
LatencyStat() {
lasttime = time(NULL);
metname = std::string("latency");
}
virtual void GetMetric(TMetList &metlist, time_t now) {
AddMetric(metlist, metname, now, TTSValue(now-lasttime));
}
};
Monitor::Monitor(const std::string &part, const std::string &fs) : logfile(NULL)
{
statlist.push_back(new IOStat(part));
statlist.push_back(new SlabStat(fs));
statlist.push_back(new MemStat());
statlist.push_back(new ProcStat());
statlist.push_back(new ProcStat(std::string("tablefs")));
statlist.push_back(new LatencyStat());
}
Monitor::Monitor(const std::string &part) : logfile(NULL)
{
statlist.push_back(new IOStat(part));
}
Monitor::Monitor() : logfile(NULL) {
}
void Monitor::AddMetricStat(MetricStat* mstat) {
if (mstat != NULL)
statlist.push_back(mstat);
}
Monitor::~Monitor() {
std::vector<MetricStat*>::iterator it;
for (it = statlist.begin(); it != statlist.end(); it++) {
delete (*it);
}
if (logfile != NULL) {
fclose(logfile);
}
}
void Monitor::SetLogFile(const std::string logfilename) {
logfile = fopen(logfilename.c_str(), "w");
}
void Monitor::DoMonitor() {
std::vector<MetricStat*>::iterator it;
time_t now = time(NULL);
int i = 0;
for (it = statlist.begin(); it != statlist.end(); it++) {
++i;
(*it)->GetMetric(metlist, now);
}
}
void Monitor::AddMetric(std::string name, TTSValue ts, TTSValue val) {
TMetList::iterator it = metlist.find(name);
if (it == metlist.end()) {
metlist[name] = TSeries();
it = metlist.find(name);
}
it->second.push_back(TSEntry(ts, val));
}
void Monitor::Report() {
for (TMetList::iterator it = metlist.begin(); it != metlist.end(); it++) {
printf("%s", it->first.c_str());
for (TSeries::iterator jt = it->second.begin();
jt != it->second.end(); jt++) {
printf(" %ld %lld", jt->first, jt->second);
}
printf("\n");
}
}
void Monitor::Report(FILE* logf) {
for (TMetList::iterator it = metlist.begin(); it != metlist.end(); it++) {
fprintf(logf, "%s", it->first.c_str());
for (TSeries::iterator jt = it->second.begin();
jt != it->second.end(); jt++) {
fprintf(logf, " %ld %lld", jt->first, jt->second);
}
fprintf(logf, "\n");
}
}
void Monitor::ReportToFile() {
Report(logfile);
}
}
| 26.046296 | 92 | 0.559426 | [
"vector"
] |
d0f6a9dc403404b7b153168f28ac224474cada94 | 15,214 | cc | C++ | mcg/src/external/BSR/src/math/geometry/point_3D.cc | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 392 | 2015-01-14T13:19:40.000Z | 2022-02-12T08:47:33.000Z | mcg/src/external/BSR/src/math/geometry/point_3D.cc | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 45 | 2015-02-03T12:16:10.000Z | 2022-03-07T00:25:09.000Z | mcg/src/external/BSR/src/math/geometry/point_3D.cc | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 168 | 2015-01-05T02:29:53.000Z | 2022-02-22T04:32:04.000Z | /*
* Point 3D.
*/
#include "io/serialization/serial_input_stream.hh"
#include "io/serialization/serial_output_stream.hh"
#include "io/streams/ostream.hh"
#include "lang/pointers/auto_ptr.hh"
#include "math/exact.hh"
#include "math/geometry/point_3D.hh"
#include "math/math.hh"
namespace math {
namespace geometry {
/*
* Imports.
*/
using io::serialization::serial_input_stream;
using io::serialization::serial_output_stream;
using io::streams::ostream;
using math::exact;
using lang::pointers::auto_ptr;
/***************************************************************************
* Constructors and destructor.
***************************************************************************/
/*
* Default constructor.
* Return the origin.
*/
point_3D::point_3D()
: _x(0), _y(0), _z(0)
{ }
/*
* Constructor.
* Return the point with the given coordinates.
*/
point_3D::point_3D(const double& x, const double& y, const double& z)
: _x(x), _y(y), _z(z)
{ }
/*
* Copy constructor.
*/
point_3D::point_3D(const point_3D& p)
: _x(p._x), _y(p._y), _z(p._z)
{ }
/*
* Destructor.
*/
point_3D::~point_3D() {
/* do nothing */
}
/***************************************************************************
* Named constructors.
***************************************************************************/
/*
* Polar form.
* Return the point at the given radius from the origin, theta radians from
* the positive x-axis, and psi radians above the xy-plane.
*/
point_3D point_3D::polar(
const double& r, const double& theta, const double& psi)
{
double r_xy = r*math::cos(psi);
return point_3D(
r_xy*math::cos(theta), r_xy*math::sin(theta), r*math::sin(psi)
);
}
/***************************************************************************
* Serialization.
***************************************************************************/
/*
* Serialize.
*/
void point_3D::serialize(serial_output_stream& s) const {
s << _x << _y << _z;
}
/*
* Deserialize.
*/
auto_ptr<point_3D> point_3D::deserialize(serial_input_stream& s) {
auto_ptr<point_3D> p(new point_3D());
s >> p->_x >> p->_y >> p->_z;
return p;
}
/***************************************************************************
* I/O.
***************************************************************************/
/*
* Formatted output to stream.
*/
ostream& operator<<(ostream& os, const point_3D& p) {
os << "(" << p._x << ", " << p._y << ", " << p._z << ")";
return os;
}
/***************************************************************************
* Assignment operator.
***************************************************************************/
point_3D& point_3D::operator=(const point_3D& p) {
_x = p._x;
_y = p._y;
_z = p._z;
return *this;
}
/***************************************************************************
* Binary operators.
***************************************************************************/
point_3D operator*(const double& s, const point_3D& p) {
return point_3D(s*p._x, s*p._y, s*p._z);
}
point_3D operator*(const point_3D& p, const double& s) {
return point_3D(p._x*s, p._y*s, p._z*s);
}
point_3D operator/(const point_3D& p, const double& s) {
return point_3D(p._x/s, p._y/s, p._z/s);
}
point_3D operator+(const point_3D& p0, const point_3D& p1) {
return point_3D(p0._x + p1._x, p0._y + p1._y, p0._z + p1._z);
}
point_3D operator-(const point_3D& p0, const point_3D& p1) {
return point_3D(p0._x - p1._x, p0._y - p1._y, p0._z - p1._z);
}
/***************************************************************************
* Unary operators.
***************************************************************************/
point_3D point_3D::operator+() const {
return *this;
}
point_3D point_3D::operator-() const {
return point_3D(-_x, -_y, -_z);
}
/***************************************************************************
* Binary equality tests.
***************************************************************************/
bool operator==(const point_3D& p0, const point_3D& p1) {
return ((p0._x == p1._x) && (p0._y == p1._y) && (p0._z == p1._z));
}
bool operator!=(const point_3D& p0, const point_3D& p1) {
return ((p0._x != p1._x) || (p0._y != p1._y) || (p0._z != p1._z));
}
/***************************************************************************
* Comparators.
***************************************************************************/
/*
* Binary comparators.
* These comparators enforce a lexicographic ordering on points.
*/
bool operator<(const point_3D& p0, const point_3D& p1) {
return (
(p0._x < p1._x) ||
((p0._x == p1._x) &&
((p0._y < p1._y) || ((p0._y == p1._y) && (p0._z < p1._z))))
);
}
bool operator>(const point_3D& p0, const point_3D& p1) {
return (
(p0._x > p1._x) ||
((p0._x == p1._x) &&
((p0._y > p1._y) || ((p0._y == p1._y) && (p0._z > p1._z))))
);
}
bool operator<=(const point_3D& p0, const point_3D& p1) {
return (
(p0._x < p1._x) ||
((p0._x == p1._x) &&
((p0._y < p1._y) || ((p0._y == p1._y) && (p0._z <= p1._z))))
);
}
bool operator>=(const point_3D& p0, const point_3D& p1) {
return (
(p0._x > p1._x) ||
((p0._x == p1._x) &&
((p0._y > p1._y) || ((p0._y == p1._y) && (p0._z >= p1._z))))
);
}
/*
* Comparison method (for lexicographic ordering on points).
*/
int point_3D::compare_to(const point_3D& p) const {
int cmp_x = (_x < p._x) ? -1 : ((_x > p._x) ? 1 : 0);
int cmp_y = (_y < p._y) ? -1 : ((_y > p._y) ? 1 : 0);
int cmp_z = (_z < p._z) ? -1 : ((_z > p._z) ? 1 : 0);
return ((cmp_x == 0) ? ((cmp_y == 0) ? cmp_z : cmp_y) : cmp_x);
}
/***************************************************************************
* Polar coordinates.
***************************************************************************/
/*
* Magnitude (distance from origin).
*/
double abs(const point_3D& p) {
return math::sqrt(p._x*p._x + p._y*p._y + p._z*p._z);
}
/*
* Argument (angle in radians from positive x-axis).
*/
double arg(const point_3D& p) {
return math::atan2(p._y, p._x);
}
/*
* Elevation (angle in radians from the xy-plane).
*/
double elev(const point_3D& p) {
double r_xy = math::sqrt(p._x*p._x + p._y*p._y);
return math::atan2(p._z, r_xy);
}
/***************************************************************************
* Dot product.
***************************************************************************/
/*
* Dot product.
*/
double dot(const point_3D& p0, const point_3D& p1) {
return (p0._x * p1._x + p0._y * p1._y + p0._z * p1._z);
}
/***************************************************************************
* Distance from point to line/segment.
***************************************************************************/
/*
* Distance from the point to the line passing through the specified points.
*/
double point_3D::distance_to_line(
const point_3D& p, const point_3D& q) const
{
/* compute vectors between points */
point_3D a = q - p;
point_3D b = *this - p;
/* compute distance */
double mag_a_sq = a._x*a._x + a._y*a._y + a._z*a._z;
double mag_b_sq = b._x*b._x + b._y*b._y + b._z*b._z;
double a_dot_b = dot(a, b);
return (mag_a_sq*mag_b_sq - a_dot_b*a_dot_b)/mag_a_sq;
}
/*
* Distance from the point to the line segment with the specified endpoints.
*/
double point_3D::distance_to_segment(
const point_3D& p, const point_3D& q) const
{
/* compute vectors between points */
point_3D a = q - p;
point_3D b = *this - p;
point_3D c = *this - q;
/* compute distance to segment */
if (dot(a, c) >= 0) {
/* q is closest point */
return abs(c);
} else if (dot(-a, b) >= 0) {
/* p is closest point */
return abs(b);
} else {
/* compute distance from point to line */
return this->distance_to_line(p, q);
}
}
/***************************************************************************
* Geometric predicates.
***************************************************************************/
/*
* Robust geometric orientation test (using exact arithmetic).
* Return -1 if the point is above plane pqr,
* 0 if the points are coplanar, and
* 1 if the point is below plane pqr.
*
* Note that "below" and "above" are defined so that p, q, and r appear
* in counterclockwise order when viewed from above plane pqr.
*/
int point_3D::orientation(
const point_3D& p, const point_3D& q, const point_3D& r) const
{
/* compute error bound beyond which exact arithmetic is needed */
static const double error_bound =
(7.0 + 56.0 * exact<>::epsilon()) * exact<>::epsilon();
/* perform approximate orientation test */
double ax = p.x() - _x; double ay = p.y() - _y; double az = p.z() - _z;
double bx = q.x() - _x; double by = q.y() - _y; double bz = q.z() - _z;
double cx = r.x() - _x; double cy = r.y() - _y; double cz = r.z() - _z;
double ax_by = ax * by; double bx_ay = bx * ay;
double ax_cy = ax * cy; double cx_ay = cx * ay;
double bx_cy = bx * cy; double cx_by = cx * by;
double det =
az * (bx_cy - cx_by) + bz * (cx_ay - ax_cy) + cz * (ax_by - bx_ay);
/* check if error cannot change result */
double permanent =
math::abs(az) * (math::abs(bx_cy) + math::abs(cx_by)) +
math::abs(bz) * (math::abs(cx_ay) + math::abs(ax_cy)) +
math::abs(cz) * (math::abs(ax_by) + math::abs(bx_ay));
double max_error = error_bound * permanent;
if ((-det) < max_error) {
return -1;
} else if (det > max_error) {
return 1;
} else {
/* perform exact orientation test */
exact<> ax_e = exact<>(p.x()) - _x;
exact<> ay_e = exact<>(p.y()) - _y;
exact<> az_e = exact<>(p.z()) - _z;
exact<> bx_e = exact<>(q.x()) - _x;
exact<> by_e = exact<>(q.y()) - _y;
exact<> bz_e = exact<>(q.z()) - _z;
exact<> cx_e = exact<>(r.x()) - _x;
exact<> cy_e = exact<>(r.y()) - _y;
exact<> cz_e = exact<>(r.z()) - _z;
exact<> ax_by_e = ax_e * by_e; exact<> bx_ay_e = bx_e * ay_e;
exact<> ax_cy_e = ax_e * cy_e; exact<> cx_ay_e = cx_e * ay_e;
exact<> bx_cy_e = bx_e * cy_e; exact<> cx_by_e = cx_e * by_e;
exact<> det_exact =
az_e * (bx_cy_e - cx_by_e) +
bz_e * (cx_ay_e - ax_cy_e) +
cz_e * (ax_by_e - bx_ay_e);
return det_exact.sign();
}
}
/*
* Robust geometric in-sphere test (using exact arithmetic).
* Return -1 if the point is outside the sphere,
* 0 if the point is on the sphere, and
* 1 if the point is inside the sphere.
*
* The four points defining the sphere must appear in order so that the
* fourth point is below the plane defined by the first three (positive
* orientation), or the sign of the result will be reversed.
*/
int point_3D::in_sphere(
const point_3D& p0,
const point_3D& p1,
const point_3D& p2,
const point_3D& p3) const
{
/* compute error bound beyond which exact arithmetic is needed */
static const double error_bound =
(16.0 + 224.0 * exact<>::epsilon()) * exact<>::epsilon();
/* perform approximate in-sphere test */
double ax = p0.x() - _x; double ay = p0.y() - _y; double az = p0.z() - _z;
double bx = p1.x() - _x; double by = p1.y() - _y; double bz = p1.z() - _z;
double cx = p2.x() - _x; double cy = p2.y() - _y; double cz = p2.z() - _z;
double dx = p3.x() - _x; double dy = p3.y() - _y; double dz = p3.z() - _z;
double ax_by = ax * by; double bx_ay = bx * ay;
double bx_cy = bx * cy; double cx_by = cx * by;
double cx_dy = cx * dy; double dx_cy = dx * cy;
double dx_ay = dx * ay; double ax_dy = ax * dy;
double ax_cy = ax * cy; double cx_ay = cx * ay;
double bx_dy = bx * dy; double dx_by = dx * by;
double ab_diff = ax_by - bx_ay;
double bc_diff = bx_cy - cx_by;
double cd_diff = cx_dy - dx_cy;
double da_diff = dx_ay - ax_dy;
double ac_diff = ax_cy - cx_ay;
double bd_diff = bx_dy - dx_by;
double abc = az * bc_diff - bz * ac_diff + cz * ab_diff;
double bcd = bz * cd_diff - cz * bd_diff + dz * bc_diff;
double cda = cz * da_diff + dz * ac_diff + az * cd_diff;
double dab = dz * ab_diff + az * bd_diff + bz * da_diff;
double a_sq = ax * ax + ay * ay + az * az;
double b_sq = bx * bx + by * by + bz * bz;
double c_sq = cx * cx + cy * cy + cz * cz;
double d_sq = dx * dx + dy * dy + dz * dz;
double det = (d_sq * abc - c_sq * dab) + (b_sq * cda - a_sq * bcd);
/* check if error cannot change result */
double permanent =
((math::abs(cx_dy) + math::abs(dx_cy)) * math::abs(bz) +
(math::abs(dx_by) + math::abs(bx_dy)) * math::abs(cz) +
(math::abs(bx_cy) + math::abs(cx_by)) * math::abs(dz)) * a_sq +
((math::abs(dx_ay) + math::abs(ax_dy)) * math::abs(cz) +
(math::abs(ax_cy) + math::abs(cx_ay)) * math::abs(dz) +
(math::abs(cx_dy) + math::abs(dx_cy)) * math::abs(az)) * b_sq +
((math::abs(ax_by) + math::abs(bx_ay)) * math::abs(dz) +
(math::abs(bx_dy) + math::abs(dx_by)) * math::abs(az) +
(math::abs(dx_ay) + math::abs(ax_dy)) * math::abs(bz)) * c_sq +
((math::abs(bx_cy) + math::abs(cx_by)) * math::abs(az) +
(math::abs(cx_ay) + math::abs(ax_cy)) * math::abs(bz) +
(math::abs(ax_by) + math::abs(bx_ay)) * math::abs(cz)) * d_sq;
double max_error = error_bound * permanent;
if ((-det) < max_error) {
return -1;
} else if (det > max_error) {
return 1;
} else {
/* perform exact in-sphere test */
exact<> ax_e = exact<>(p0.x()) - _x;
exact<> ay_e = exact<>(p0.y()) - _y;
exact<> az_e = exact<>(p0.z()) - _z;
exact<> bx_e = exact<>(p1.x()) - _x;
exact<> by_e = exact<>(p1.y()) - _y;
exact<> bz_e = exact<>(p1.z()) - _z;
exact<> cx_e = exact<>(p2.x()) - _x;
exact<> cy_e = exact<>(p2.y()) - _y;
exact<> cz_e = exact<>(p2.z()) - _z;
exact<> dx_e = exact<>(p3.x()) - _x;
exact<> dy_e = exact<>(p3.y()) - _y;
exact<> dz_e = exact<>(p3.z()) - _z;
exact<> ab_diff_e = ax_e * by_e - bx_e * ay_e;
exact<> bc_diff_e = bx_e * cy_e - cx_e * by_e;
exact<> cd_diff_e = cx_e * dy_e - dx_e * cy_e;
exact<> da_diff_e = dx_e * ay_e - ax_e * dy_e;
exact<> ac_diff_e = ax_e * cy_e - cx_e * ay_e;
exact<> bd_diff_e = bx_e * dy_e - dx_e * by_e;
exact<> abc_e = az_e * bc_diff_e - bz_e * ac_diff_e + cz_e * ab_diff_e;
exact<> bcd_e = bz_e * cd_diff_e - cz_e * bd_diff_e + dz_e * bc_diff_e;
exact<> cda_e = cz_e * da_diff_e + dz_e * ac_diff_e + az_e * cd_diff_e;
exact<> dab_e = dz_e * ab_diff_e + az_e * bd_diff_e + bz_e * da_diff_e;
exact<> a_sq_e = ax_e * ax_e + ay_e * ay_e + az_e * az_e;
exact<> b_sq_e = bx_e * bx_e + by_e * by_e + bz_e * bz_e;
exact<> c_sq_e = cx_e * cx_e + cy_e * cy_e + cz_e * cz_e;
exact<> d_sq_e = dx_e * dx_e + dy_e * dy_e + dz_e * dz_e;
exact<> det_exact =
(d_sq_e * abc_e - c_sq_e * dab_e) + (b_sq_e * cda_e - a_sq_e * bcd_e);
return det_exact.sign();
}
}
} /* namespace geometry */
} /* namespace math */
| 33.364035 | 79 | 0.502958 | [
"geometry",
"3d"
] |
d0f7aef3e4c189f42ad7a5aca334283ba684c04f | 12,645 | cc | C++ | src/Modules/Render/ViewScene.cc | Nahusa/SCIRun | c54e714d4c7e956d053597cf194e07616e28a498 | [
"MIT"
] | 1 | 2019-05-30T06:00:15.000Z | 2019-05-30T06:00:15.000Z | src/Modules/Render/ViewScene.cc | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | src/Modules/Render/ViewScene.cc | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <es-log/trace-log.h>
#include <Modules/Render/ViewScene.h>
#include <Core/Datatypes/Geometry.h>
#include <Core/Logging/Log.h>
#include <Core/Datatypes/Color.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <boost/thread.hpp>
// Needed to fix conflict between define in X11 header
// and eigen enum member.
#ifdef Success
# undef Success
#endif
using namespace SCIRun::Modules::Render;
using namespace SCIRun::Core::Algorithms;
using namespace Render;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Thread;
using namespace SCIRun::Core::Logging;
MODULE_INFO_DEF(ViewScene, Render, SCIRun)
Mutex ViewScene::mutex_("ViewScene");
ALGORITHM_PARAMETER_DEF(Render, GeomData);
ALGORITHM_PARAMETER_DEF(Render, GeometryFeedbackInfo);
ALGORITHM_PARAMETER_DEF(Render, ScreenshotData);
ALGORITHM_PARAMETER_DEF(Render, MeshComponentSelection);
ALGORITHM_PARAMETER_DEF(Render, ShowFieldStates);
ViewScene::ViewScene() : ModuleWithAsyncDynamicPorts(staticInfo_, true), asyncUpdates_(0)
{
RENDERER_LOG_FUNCTION_SCOPE;
INITIALIZE_PORT(GeneralGeom);
INITIALIZE_PORT(ScreenshotDataRed);
INITIALIZE_PORT(ScreenshotDataGreen);
INITIALIZE_PORT(ScreenshotDataBlue);
}
void ViewScene::setStateDefaults()
{
auto state = get_state();
state->setValue(BackgroundColor, ColorRGB(0.0, 0.0, 0.0).toString());
state->setValue(Ambient, 0.2);
state->setValue(Diffuse, 1.0);
state->setValue(Specular, 0.4);
state->setValue(Shine, 1.0);
state->setValue(Emission, 1.0);
state->setValue(FogOn, false);
state->setValue(ObjectsOnly, true);
state->setValue(UseBGColor, true);
state->setValue(FogStart, 0.0);
state->setValue(FogEnd, 0.71);
state->setValue(FogColor, ColorRGB(0.0, 0.0, 1.0).toString());
state->setValue(ShowScaleBar, false);
state->setValue(ScaleBarUnitValue, std::string("mm"));
state->setValue(ScaleBarLength, 1.0);
state->setValue(ScaleBarHeight, 1.0);
state->setValue(ScaleBarMultiplier, 1.0);
state->setValue(ScaleBarNumTicks, 11);
state->setValue(ScaleBarLineWidth, 1.0);
state->setValue(ScaleBarFontSize, 8);
state->setValue(Lighting, true);
state->setValue(ShowBBox, false);
state->setValue(UseClip, true);
state->setValue(BackCull, false);
state->setValue(DisplayList, false);
state->setValue(Stereo, false);
state->setValue(StereoFusion, 0.4);
state->setValue(PolygonOffset, 0.0);
state->setValue(TextOffset, 0.0);
state->setValue(FieldOfView, 20);
state->setValue(HeadLightOn, true);
state->setValue(Light1On, false);
state->setValue(Light2On, false);
state->setValue(Light3On, false);
state->setValue(HeadLightColor, ColorRGB(0.0, 0.0, 0.0).toString());
state->setValue(Light1Color, ColorRGB(0.0, 0.0, 0.0).toString());
state->setValue(Light2Color, ColorRGB(0.0, 0.0, 0.0).toString());
state->setValue(Light3Color, ColorRGB(0.0, 0.0, 0.0).toString());
state->setValue(ShowViewer, false);
get_state()->connectSpecificStateChanged(Parameters::GeometryFeedbackInfo, [this]() { processViewSceneObjectFeedback(); });
get_state()->connectSpecificStateChanged(Parameters::MeshComponentSelection, [this]() { processMeshComponentSelection(); });
}
void ViewScene::portRemovedSlotImpl(const PortId& pid)
{
//lock for state modification
{
Guard lock(mutex_.get());
auto loc = activeGeoms_.find(pid);
if (loc != activeGeoms_.end())
activeGeoms_.erase(loc);
updateTransientList();
}
get_state()->fireTransientStateChangeSignal();
}
void ViewScene::updateTransientList()
{
auto transient = get_state()->getTransientValue(Parameters::GeomData);
auto geoms = transient_value_cast<GeomListPtr>(transient);
if (!geoms)
{
geoms.reset(new GeomList());
}
geoms->clear();
for (const auto& geomPair : activeGeoms_)
{
auto geom = geomPair.second;
geom->addToList(geom, *geoms);
}
// Grab geometry inputs and pass them along in a transient value to the GUI
// thread where they will be transported to Spire.
// NOTE: I'm not implementing mutex locks for this now. But for production
// purposes, they NEED to be in there!
// Pass geometry object up through transient... really need to be concerned
// about the lifetimes of the buffers we have in GeometryObject. Need to
// switch to std::shared_ptr on an std::array when in production.
/// \todo Need to make this data transfer mechanism thread safe!
// I thought about dynamic casting geometry object to a weak_ptr, but I don't
// know where it will be destroyed. For now, it will have have stale pointer
// data lying around in it... yuck.
get_state()->setTransientValue(Parameters::GeomData, geoms, false);
}
void ViewScene::asyncExecute(const PortId& pid, DatatypeHandle data)
{
if (!data)
return;
//lock for state modification
{
LOG_DEBUG("ViewScene::asyncExecute {} before locking", get_id().id_);
Guard lock(mutex_.get());
get_state()->setTransientValue(Parameters::ScreenshotData, boost::any(), false);
LOG_DEBUG("ViewScene::asyncExecute {} after locking", get_id().id_);
auto geom = boost::dynamic_pointer_cast<GeometryObject>(data);
if (!geom)
{
error("Logical error: not a geometry object on ViewScene");
return;
}
{
auto iport = getInputPort(pid);
auto connectedModuleId = iport->connectedModuleId();
if (connectedModuleId->find("ShowField") != std::string::npos)
{
auto state = iport->stateFromConnectedModule();
syncMeshComponentFlags(*connectedModuleId, state);
}
}
activeGeoms_[pid] = geom;
updateTransientList();
}
get_state()->fireTransientStateChangeSignal();
asyncUpdates_.fetch_add(1);
}
void ViewScene::syncMeshComponentFlags(const std::string& connectedModuleId, ModuleStateHandle state)
{
if (connectedModuleId.find("ShowField:") != std::string::npos)
{
auto map = transient_value_cast<ShowFieldStatesMap>(get_state()->getTransientValue(Parameters::ShowFieldStates));
map[connectedModuleId] = state;
get_state()->setTransientValue(Parameters::ShowFieldStates, map, false);
}
}
void ViewScene::execute()
{
// hack for headless viewscene. Right now, it hangs/crashes/who knows.
#ifdef BUILD_HEADLESS
sendOutput(ScreenshotDataRed, boost::make_shared<DenseMatrix>(0, 0));
sendOutput(ScreenshotDataGreen, boost::make_shared<DenseMatrix>(0, 0));
sendOutput(ScreenshotDataBlue, boost::make_shared<DenseMatrix>(0, 0));
#else
if (needToExecute())
{
const int maxAsyncWaitTries = 100; //TODO: make configurable for longer-running networks
auto asyncWaitTries = 0;
if (inputPorts().size() > 1) // only send screenshot if input is present
{
while (asyncUpdates_ < inputPorts().size() - 1)
{
asyncWaitTries++;
if (asyncWaitTries == maxAsyncWaitTries)
return; // nothing coming down the ports
//wait until all asyncExecutes are done.
}
ModuleStateInterface::TransientValueOption screenshotDataOption;
auto state = get_state();
do
{
screenshotDataOption = state->getTransientValue(Parameters::ScreenshotData);
if (screenshotDataOption)
{
auto screenshotData = transient_value_cast<RGBMatrices>(screenshotDataOption);
if (screenshotData.red)
{
sendOutput(ScreenshotDataRed, screenshotData.red);
}
if (screenshotData.green)
{
sendOutput(ScreenshotDataGreen, screenshotData.green);
}
if (screenshotData.blue)
{
sendOutput(ScreenshotDataBlue, screenshotData.blue);
}
}
} while (!screenshotDataOption);
}
asyncUpdates_ = 0;
get_state()->setTransientValue(Parameters::ScreenshotData, boost::any(), false);
}
#endif
}
void ViewScene::processViewSceneObjectFeedback()
{
//TODO: match ID of touched geom object with port id, and send that info back too.
auto state = get_state();
auto newInfo = state->getTransientValue(Parameters::GeometryFeedbackInfo);
//TODO: lost equality test here due to change to boost::any. Would be nice to form a data class with equality to avoid repetitive signalling.
if (newInfo)
{
auto vsInfo = transient_value_cast<ViewSceneFeedback>(newInfo);
sendFeedbackUpstreamAlongIncomingConnections(vsInfo);
}
}
void ViewScene::processMeshComponentSelection()
{
auto state = get_state();
auto newInfo = state->getTransientValue(Parameters::MeshComponentSelection);
if (newInfo)
{
auto vsInfo = transient_value_cast<MeshComponentSelectionFeedback>(newInfo);
sendFeedbackUpstreamAlongIncomingConnections(vsInfo);
}
}
const AlgorithmParameterName ViewScene::BackgroundColor("BackgroundColor");
const AlgorithmParameterName ViewScene::Ambient("Ambient");
const AlgorithmParameterName ViewScene::Diffuse("Diffuse");
const AlgorithmParameterName ViewScene::Specular("Specular");
const AlgorithmParameterName ViewScene::Shine("Shine");
const AlgorithmParameterName ViewScene::Emission("Emission");
const AlgorithmParameterName ViewScene::FogOn("FogOn");
const AlgorithmParameterName ViewScene::ObjectsOnly("ObjectsOnly");
const AlgorithmParameterName ViewScene::UseBGColor("UseBGColor");
const AlgorithmParameterName ViewScene::FogStart("FogStart");
const AlgorithmParameterName ViewScene::FogEnd("FogEnd");
const AlgorithmParameterName ViewScene::FogColor("FogColor");
const AlgorithmParameterName ViewScene::ShowScaleBar("ShowScaleBar");
const AlgorithmParameterName ViewScene::ScaleBarUnitValue("ScaleBarUnitValue");
const AlgorithmParameterName ViewScene::ScaleBarLength("ScaleBarLength");
const AlgorithmParameterName ViewScene::ScaleBarHeight("ScaleBarHeight");
const AlgorithmParameterName ViewScene::ScaleBarMultiplier("ScaleBarMultiplier");
const AlgorithmParameterName ViewScene::ScaleBarNumTicks("ScaleBarNumTicks");
const AlgorithmParameterName ViewScene::ScaleBarLineWidth("ScaleBarLineWidth");
const AlgorithmParameterName ViewScene::ScaleBarFontSize("ScaleBarFontSize");
const AlgorithmParameterName ViewScene::Lighting("Lighting");
const AlgorithmParameterName ViewScene::ShowBBox("ShowBBox");
const AlgorithmParameterName ViewScene::UseClip("UseClip");
const AlgorithmParameterName ViewScene::Stereo("Stereo");
const AlgorithmParameterName ViewScene::BackCull("BackCull");
const AlgorithmParameterName ViewScene::DisplayList("DisplayList");
const AlgorithmParameterName ViewScene::StereoFusion("StereoFusion");
const AlgorithmParameterName ViewScene::PolygonOffset("PolygonOffset");
const AlgorithmParameterName ViewScene::TextOffset("TextOffset");
const AlgorithmParameterName ViewScene::FieldOfView("FieldOfView");
const AlgorithmParameterName ViewScene::HeadLightOn("HeadLightOn");
const AlgorithmParameterName ViewScene::Light1On("Light1On");
const AlgorithmParameterName ViewScene::Light2On("Light2On");
const AlgorithmParameterName ViewScene::Light3On("Light3On");
const AlgorithmParameterName ViewScene::HeadLightColor("HeadLightColor");
const AlgorithmParameterName ViewScene::Light1Color("Light1Color");
const AlgorithmParameterName ViewScene::Light2Color("Light2Color");
const AlgorithmParameterName ViewScene::Light3Color("Light3Color");
const AlgorithmParameterName ViewScene::ShowViewer("ShowViewer");
| 38.907692 | 143 | 0.748992 | [
"geometry",
"render",
"object"
] |
d0f9fbeef79c55ad7185c2bfa58a7c640b590870 | 3,180 | hpp | C++ | svntrunk/src/BlueMatter/analysis/include/DataReceiverQuadraticCons.hpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/BlueMatter/analysis/include/DataReceiverQuadraticCons.hpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/BlueMatter/analysis/include/DataReceiverQuadraticCons.hpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* 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.
*/
#ifndef DATARECEIVERQUADRATICCONS_HPP
#define DATARECEIVERQUADRATICCONS_HPP
#include <assert.h>
#include <fcntl.h>
#include <BlueMatter/DataReceiver.hpp>
#include <BlueMatter/ExternalDatagram.hpp>
#include <BlueMatter/ArrayGrowable.hpp>
#include <BlueMatter/DataReceiverSimpleLogger.hpp>
#include <BlueMatter/bootstrap.hpp>
#include <vector>
class DataReceiverQuadraticCons : public DataReceiverSimpleLogger
{
public:
vector<double> mKEs;
vector<double> mCQs;
double mTimeStep;
int mFirstOne;
DataReceiverQuadraticCons(int DelayStats = 0, int OutputPeriod = 1, int BootStrap = 0, int AllSnapshots = 0)
{
mUDFsKnown = 1; // simple hack to stop output of top line
mPressureColumn = 0;
for (int i=0; i<UDF_Binding::UDF_CODE_COUNT; i++)
mUDFColumn[i] = 0;
mLogCount = 0;
mCQSum = 0;
mCQSumSq = 0;
mDelayStats = DelayStats;
mOutputPeriod = OutputPeriod;
mHeaderBuffer[0] = '\0';
mValuesBuffer[0] = '\0';
mBootStrap = BootStrap;
mSaveAllSnapshots = AllSnapshots;
strcpy(mSnapshotNameStem, "Snapshot");
mFirstOne = 0;
}
virtual void sites(Frame *f)
{
DONEXT_1(sites, f);
}
virtual void logInfo(Frame *f)
{
doLogStats(f);
mTimeStep = f->mInformationRTP.mOuterTimeStepInPicoSeconds;
mCQs.push_back(f->mEnergyInfo.mEnergySums.mConservedQuantity);
mKEs.push_back(f->mEnergyInfo.mEnergySumAccumulator.mKineticEnergy);
#if 0
printf("%d %d %lf %lf %lf\n",
f->mOuterTimeStep,
f->mInformationRTP.mNumberOfOuterTimeSteps,
f->mInformationRTP.mOuterTimeStepInPicoSeconds,
f->mEnergyInfo.mEnergySumAccumulator.mKineticEnergy,
f->mEnergyInfo.mEnergySums.mConservedQuantity
);
#endif
DONEXT_1(logInfo, f);
}
virtual void final(int status=1)
{
DONEXT_0(final);
}
};
#endif
| 34.193548 | 118 | 0.734906 | [
"vector"
] |
cba19e94a57f423f7a10b079ac4093d6489a710c | 1,021 | hpp | C++ | JEBString/Unused/JEBString/String/Generic/WildcardMatcher.hpp | jebreimo/JEBLib | 9066403a9372951aa8ce4f129cd4877e2ae779ab | [
"BSD-3-Clause"
] | 1 | 2019-12-25T05:30:20.000Z | 2019-12-25T05:30:20.000Z | JEBString/Unused/JEBString/String/Generic/WildcardMatcher.hpp | jebreimo/JEBLib | 9066403a9372951aa8ce4f129cd4877e2ae779ab | [
"BSD-3-Clause"
] | null | null | null | JEBString/Unused/JEBString/String/Generic/WildcardMatcher.hpp | jebreimo/JEBLib | 9066403a9372951aa8ce4f129cd4877e2ae779ab | [
"BSD-3-Clause"
] | null | null | null | #ifndef JEB_WILDCARDMATCHER_HPP
#define JEB_WILDCARDMATCHER_HPP
#include <vector>
#include "WildcardWord.hpp"
namespace JEB { namespace String { namespace Generic {
class WildcardMatcher
{
public:
WildcardMatcher();
~WildcardMatcher();
template <typename StrFwdIt>
void parse(StrFwdIt begin, StrFwdIt end);
bool hasPrefix() const;
void setHasPrefix(bool hasPrefix);
bool hasSuffix() const;
void setHasSuffix(bool hasSuffix);
size_t numberOfWords() const;
template <typename StrBiIt>
std::pair<StrBiIt, StrBiIt> find(StrBiIt beg, StrBiIt end);
template <typename StrBiIt>
std::pair<StrBiIt, StrBiIt> findShortest(StrBiIt beg, StrBiIt end);
template <typename StrBiIt>
bool match(StrBiIt beg, StrBiIt end);
private:
WildcardWord& newWord();
bool m_HasPrefix;
bool m_HasSuffix;
std::vector<WildcardWord> m_Words;
};
template <typename FwidIt>
bool hasWildcards(FwidIt beg, FwidIt end);
}}}
#include "WildcardMatcher_Impl.hpp"
#endif
| 20.42 | 71 | 0.722821 | [
"vector"
] |
cba3c4533c6fd4884a969857065806d5c8ed3c84 | 12,262 | cpp | C++ | artemis-code/src/runtime/browser/webkitexecutor.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | artemis-code/src/runtime/browser/webkitexecutor.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | artemis-code/src/runtime/browser/webkitexecutor.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2012 Aarhus University
*
* 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 <iostream>
#include <unistd.h>
#include <QtWebKit>
#include <QApplication>
#include <QStack>
#include <QDebug>
#include <qwebexecutionlistener.h>
#include <instrumentation/executionlistener.h>
#include "runtime/input/forms/formfield.h"
#include "runtime/input/events/domelementdescriptor.h"
#include "strategies/inputgenerator/targets/jquerylistener.h"
#include "runtime/input/baseinput.h"
#include "strategies/inputgenerator/randominputgenerator.h"
#include "util/fileutil.h"
#include <sys/time.h>
#include "webkitexecutor.h"
extern bool modelGeneration;
extern int modelIteration;
extern QStringList originalModel;
extern QSet<QString> handlersSet;
extern QString subjectName;
extern QMap<QString, QStringList* > depMap;
extern bool isAbstract;
extern struct timeval start;
extern bool randomOrWeight;
extern int totalExe;
using namespace std;
namespace artemis
{
WebKitExecutor::WebKitExecutor(QObject* parent,
AppModelPtr appmodel,
QMap<QString, QString> presetFields,
JQueryListener* jqueryListener,
AjaxRequestListener* ajaxListener) :
QObject(parent)
{
mPresetFields = presetFields;
mJquery = jqueryListener;
mAjaxListener = ajaxListener;
mAjaxListener->setParent(this);
mPage = ArtemisWebPagePtr(new ArtemisWebPage());
mPage->setNetworkAccessManager(mAjaxListener);
QObject::connect(mPage.data(), SIGNAL(loadFinished(bool)),
this, SLOT(slLoadFinished(bool)));
mResultBuilder = ExecutionResultBuilderPtr(new ExecutionResultBuilder(mPage));
mCoverageListener = appmodel->getCoverageListener();
mJavascriptStatistics = appmodel->getJavascriptStatistics();
QWebExecutionListener::attachListeners();
webkitListener = QWebExecutionListener::getListener();
// TODO cleanup in ajax stuff, we are handling ajax through AjaxRequestListener, the ajaxRequest signal and addAjaxCallHandler
QObject::connect(webkitListener, SIGNAL(jqueryEventAdded(QString, QString, QString)),
mJquery, SLOT(slEventAdded(QString, QString, QString)));
QObject::connect(webkitListener, SIGNAL(loadedJavaScript(QString, QUrl, uint)),
mCoverageListener.data(), SLOT(slJavascriptScriptParsed(QString, QUrl, uint)));
QObject::connect(webkitListener, SIGNAL(statementExecuted(uint, QUrl, uint)),
mCoverageListener.data(), SLOT(slJavascriptStatementExecuted(uint, QUrl, uint)));
QObject::connect(webkitListener, SIGNAL(sigJavascriptBytecodeExecuted(uint, uint, QUrl, uint)),
mCoverageListener.data(), SLOT(slJavascriptBytecodeExecuted(uint, uint, QUrl, uint)));
QObject::connect(webkitListener, SIGNAL(sigJavascriptFunctionCalled(QString, size_t, uint, QUrl, uint)),
mCoverageListener.data(), SLOT(slJavascriptFunctionCalled(QString, size_t, uint, QUrl, uint)));
QObject::connect(webkitListener, SIGNAL(sigJavascriptPropertyRead(QString,intptr_t,intptr_t,QUrl,int)),
mJavascriptStatistics.data(), SLOT(slJavascriptPropertyRead(QString,intptr_t,intptr_t,QUrl,int)));
QObject::connect(webkitListener, SIGNAL(sigJavascriptPropertyWritten(QString,intptr_t,intptr_t,QUrl,int)),
mJavascriptStatistics.data(), SLOT(slJavascriptPropertyWritten(QString,intptr_t,intptr_t,QUrl,int)));
QObject::connect(webkitListener, SIGNAL(addedEventListener(QWebElement*, QString)),
mResultBuilder.data(), SLOT(slEventListenerAdded(QWebElement*, QString)));
QObject::connect(webkitListener, SIGNAL(removedEventListener(QWebElement*, QString)),
mResultBuilder.data(), SLOT(slEventListenerRemoved(QWebElement*, QString)));
QObject::connect(webkitListener, SIGNAL(addedTimer(int, int, bool)),
mResultBuilder.data(), SLOT(slTimerAdded(int, int, bool)));
QObject::connect(webkitListener, SIGNAL(removedTimer(int)),
mResultBuilder.data(), SLOT(slTimerRemoved(int)));
QObject::connect(webkitListener, SIGNAL(script_crash(QString, intptr_t, int)),
mResultBuilder.data(), SLOT(slScriptCrashed(QString, intptr_t, int)));
QObject::connect(webkitListener, SIGNAL(eval_call(QString)),
mResultBuilder.data(), SLOT(slStringEvaled(QString)));
QObject::connect(webkitListener, SIGNAL(addedAjaxCallbackHandler(int)),
mResultBuilder.data(), SLOT(slAjaxCallbackHandlerAdded(int)));
QObject::connect(webkitListener, SIGNAL(ajax_request(QUrl, QString)),
mResultBuilder.data(), SLOT(slAjaxRequestInitiated(QUrl, QString)));
QObject::connect(webkitListener, SIGNAL(sigJavascriptConstantEncountered(QString)),
mResultBuilder.data(), SLOT(slJavascriptConstantEncountered(QString)));
}
WebKitExecutor::~WebKitExecutor()
{
}
void WebKitExecutor::detach() {
webkitListener->disconnect(mResultBuilder.data());
}
void WebKitExecutor::executeSequence(ExecutableConfigurationConstPtr conf, InputGeneratorStrategy* mInputgenerator, QStringList testcase)
{
currentConf = conf;
currentGenerator = mInputgenerator;
currentTestcase = testcase;
mJquery->reset(); // TODO merge into result?
mResultBuilder->reset();
qDebug() << "--------------- FETCH PAGE --------------" << endl;
mCoverageListener->notifyStartingLoad();
mResultBuilder->notifyStartingLoad();
mJavascriptStatistics->notifyStartingLoad();
mPage->mainFrame()->load(conf->getUrl());
}
void WebKitExecutor::slLoadFinished(bool ok)
{
mResultBuilder->notifyPageLoaded();
if (!ok) {
emit sigAbortedExecution(QString("Error: The requested URL ") + currentConf->getUrl().toString() + QString(" could not be loaded"));
return;
}
foreach(QString f , mPresetFields.keys()) {
QWebElement elm = mPage->mainFrame()->findFirstElement(f);
if (elm.isNull()) {
continue;
}
elm.setAttribute("value", mPresetFields[f]);
}
qDebug() << "\n------------ EXECUTE SEQUENCE -----------" << endl;
if(modelGeneration == true) {
QMapIterator<QString, QStringList*> iter(depMap);
if(!iter.hasNext()) {
std::cout << "!!!!!!!!!!!!!!!!!!!!No dependent relations" << std::endl;
std::cout << "Reading dependency from file" << std::endl;
QString depFilePath = QString("../../raw-data/") + subjectName + QString("/info/dep.txt");
QString readRestul = readFile(depFilePath);
QStringList templist = readRestul.split("\n");
for(int i = 0; i < templist.size(); i += 4) {
if(templist[i].toStdString() == "")
break;
QString event1 = templist[i + 1] + "@" + templist[i];
QString event2 = templist[i + 3] + "@" + templist[i + 2];
if(depMap.contains(event2)) {
*(depMap[event2]) << event1;
} else {
depMap[event2] = new QStringList();
*(depMap[event2]) << event1;
}
}
QMapIterator<QString, QStringList*> iter(depMap);
if(!iter.hasNext())
std::cout << "still has no dependent relations" << std::endl;
} else{
std::cout << "Already Read successfully" << std::endl;
}
std::cout << "generating model..." << std::endl;
if(isAbstract) {
QSet<QSharedPointer<const FormField> > formfields = mResultBuilder->getResult()->getFormFields();
foreach(QSharedPointer<const FormField> formField, formfields) {
const DOMElementDescriptor* elmDesc = formField->getDomElement();
QWebElement element = elmDesc->getElement(this->mPage);
if (!element.isNull()) {
element.setAttribute("value", "gpf");
}
}
}
originalModel << QString::number(mResultBuilder->getResult()->getPageStateHash());
int i = 1;
QSharedPointer<const BaseInput> input;
if(randomOrWeight) {
std::cout << "Using random" << std::endl;
} else {
std::cout << "Using weighted" << std::endl;
}
std::cout << "modelIteration: " << modelIteration << std::endl;
while(i < modelIteration) {
input = ((RandomInputGenerator* )currentGenerator)->insertOne(currentConf, mResultBuilder->getResult(), &depMap, &numsOfEventExecution);
QString inputName = input->toString();
if(numsOfEventExecution.contains(inputName)) {
numsOfEventExecution[inputName] += 1;
} else {
numsOfEventExecution[inputName] = 1;
}
mResultBuilder->notifyStartingEvent();
mCoverageListener->notifyStartingEvent(input);
mJavascriptStatistics->notifyStartingEvent(input);
input->apply(this->mPage, this->webkitListener);
if(isAbstract) {
QSet<QSharedPointer<const FormField> > formfields = mResultBuilder->getResult()->getFormFields();
foreach(QSharedPointer<const FormField> formField, formfields) {
const DOMElementDescriptor* elmDesc = formField->getDomElement();
QWebElement element = elmDesc->getElement(this->mPage);
if (!element.isNull()) {
// element.setAttribute("value", input.second->stringRepresentation());
// std::cout << "value: " << element.attribute("value").toStdString() << std::endl;
element.setAttribute("value", "gpf");
}
}
}
originalModel << (input->toString() + QString(" ") + QString::number(mResultBuilder->getResult()->getPageStateHash()));
i++;
foreach (EventHandlerDescriptor* ee, mResultBuilder->getResult()->getEventHandlers()) {
handlersSet.insert(ee->name() + "@" + ee->domElement()->toString());
}
}
QMapIterator<QString, int> iter1(numsOfEventExecution);
while(iter1.hasNext()) {
iter1.next();
std::cout << iter1.key().toStdString() <<": " << iter1.value() << std::endl;
}
}
else {
totalExe += 1;
int length = currentTestcase.size();
QString temp;
temp = currentTestcase.join(" ");
int i = 0;
struct timeval startT;
double s;
gettimeofday(&startT, NULL);
QSharedPointer<const BaseInput> input;
while(length > i) {
input = ((RandomInputGenerator* )currentGenerator)->insertAEvent(currentConf, mResultBuilder->getResult(), currentTestcase[i]);
mResultBuilder->notifyStartingEvent();
mCoverageListener->notifyStartingEvent(input);
mJavascriptStatistics->notifyStartingEvent(input);
input->apply(this->mPage, this->webkitListener);
i++;
}
struct timeval endT;
gettimeofday(&endT, NULL);
s = endT.tv_sec - startT.tv_sec + (endT.tv_usec - startT.tv_usec) / 1000000.0f;
cout << "testcase running time: " << s << endl;
}
emit sigExecutedSequence(currentConf, mResultBuilder->getResult());
}
}
| 37.157576 | 148 | 0.625836 | [
"model"
] |
cbaaf857d76f91d59a378a9dc572dc8c00063033 | 628 | cpp | C++ | Source/SHOOTACUBE/Accessories/Accessories.cpp | marvkey/SHOOTACUBE | b98665dec593d2a5b33b66bcb1ebb5a4b896b23f | [
"Apache-2.0"
] | null | null | null | Source/SHOOTACUBE/Accessories/Accessories.cpp | marvkey/SHOOTACUBE | b98665dec593d2a5b33b66bcb1ebb5a4b896b23f | [
"Apache-2.0"
] | null | null | null | Source/SHOOTACUBE/Accessories/Accessories.cpp | marvkey/SHOOTACUBE | b98665dec593d2a5b33b66bcb1ebb5a4b896b23f | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Accessories.h"
#include "Components/BoxComponent.h"
#include "Components/SkeletalMeshComponent.h"
// Sets default values
AAccessories::AAccessories(){
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Collider =CreateDefaultSubobject<UBoxComponent>(TEXT("Box Collider"));
RootComponent=Collider;
SkeletalMesh=CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Skeletal Mesh"));
SkeletalMesh->SetupAttachment(RootComponent);
}
| 39.25 | 115 | 0.794586 | [
"mesh"
] |
cbad09822545dec26bc89b6d109ec003abce3322 | 7,107 | cc | C++ | chrome/browser/lacros/download_controller_client_lacros.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/lacros/download_controller_client_lacros.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/lacros/download_controller_client_lacros.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2021 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/lacros/download_controller_client_lacros.h"
#include "base/bind.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chromeos/crosapi/mojom/download_controller.mojom.h"
#include "chromeos/lacros/lacros_service.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/simple_download_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/download_item_utils.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
namespace {
crosapi::mojom::DownloadState ConvertMojoDownloadState(
download::DownloadItem::DownloadState value) {
switch (value) {
case download::DownloadItem::IN_PROGRESS:
return crosapi::mojom::DownloadState::kInProgress;
case download::DownloadItem::COMPLETE:
return crosapi::mojom::DownloadState::kComplete;
case download::DownloadItem::CANCELLED:
return crosapi::mojom::DownloadState::kCancelled;
case download::DownloadItem::INTERRUPTED:
return crosapi::mojom::DownloadState::kInterrupted;
case download::DownloadItem::MAX_DOWNLOAD_STATE:
NOTREACHED();
return crosapi::mojom::DownloadState::kUnknown;
}
}
crosapi::mojom::DownloadItemPtr ConvertToMojoDownloadItem(
download::DownloadItem* item) {
auto* profile = Profile::FromBrowserContext(
content::DownloadItemUtils::GetBrowserContext(item));
auto download = crosapi::mojom::DownloadItem::New();
download->guid = item->GetGuid();
download->state = ConvertMojoDownloadState(item->GetState());
download->full_path = item->GetFullPath();
download->target_file_path = item->GetTargetFilePath();
download->is_from_incognito_profile = profile->IsIncognitoProfile();
download->is_paused = item->IsPaused();
download->has_is_paused = true;
download->open_when_complete = item->GetOpenWhenComplete();
download->has_open_when_complete = true;
download->received_bytes = item->GetReceivedBytes();
download->has_received_bytes = true;
download->total_bytes = item->GetTotalBytes();
download->has_total_bytes = true;
download->start_time = item->GetStartTime();
download->is_dangerous = item->IsDangerous();
download->has_is_dangerous = true;
download->is_mixed_content = item->IsMixedContent();
download->has_is_mixed_content = true;
return download;
}
} // namespace
DownloadControllerClientLacros::DownloadControllerClientLacros() {
g_browser_process->profile_manager()->AddObserver(this);
auto profiles = g_browser_process->profile_manager()->GetLoadedProfiles();
for (auto* profile : profiles)
OnProfileAdded(profile);
auto* service = chromeos::LacrosService::Get();
if (!service->IsAvailable<crosapi::mojom::DownloadController>())
return;
int remote_version =
service->GetInterfaceVersion(crosapi::mojom::DownloadController::Uuid_);
if (remote_version < 0 ||
static_cast<uint32_t>(remote_version) <
crosapi::mojom::DownloadController::kBindClientMinVersion) {
return;
}
service->GetRemote<crosapi::mojom::DownloadController>()->BindClient(
client_receiver_.BindNewPipeAndPassRemoteWithVersion());
}
DownloadControllerClientLacros::~DownloadControllerClientLacros() {
if (g_browser_process && g_browser_process->profile_manager())
g_browser_process->profile_manager()->RemoveObserver(this);
}
void DownloadControllerClientLacros::GetAllDownloads(
crosapi::mojom::DownloadControllerClient::GetAllDownloadsCallback
callback) {
std::vector<crosapi::mojom::DownloadItemPtr> downloads;
// Aggregate all downloads.
for (auto* download : download_notifier_.GetAllDownloads())
downloads.push_back(ConvertToMojoDownloadItem(download));
// Sort chronologically by start time.
std::sort(downloads.begin(), downloads.end(),
[](const auto& a, const auto& b) {
return a->start_time.value_or(base::Time()) <
b->start_time.value_or(base::Time());
});
std::move(callback).Run(std::move(downloads));
}
void DownloadControllerClientLacros::Pause(const std::string& download_guid) {
auto* download = download_notifier_.GetDownloadByGuid(download_guid);
if (download)
download->Pause();
}
void DownloadControllerClientLacros::Resume(const std::string& download_guid,
bool user_resume) {
auto* download = download_notifier_.GetDownloadByGuid(download_guid);
if (download)
download->Resume(user_resume);
}
void DownloadControllerClientLacros::Cancel(const std::string& download_guid,
bool user_cancel) {
auto* download = download_notifier_.GetDownloadByGuid(download_guid);
if (download)
download->Cancel(user_cancel);
}
void DownloadControllerClientLacros::SetOpenWhenComplete(
const std::string& download_guid,
bool open_when_complete) {
auto* download = download_notifier_.GetDownloadByGuid(download_guid);
if (download)
download->SetOpenWhenComplete(open_when_complete);
}
void DownloadControllerClientLacros::OnProfileAdded(Profile* profile) {
download_notifier_.AddProfile(profile);
}
void DownloadControllerClientLacros::OnManagerInitialized(
content::DownloadManager* manager) {
download::SimpleDownloadManager::DownloadVector downloads;
manager->GetAllDownloads(&downloads);
for (auto* download : downloads)
OnDownloadCreated(manager, download);
}
void DownloadControllerClientLacros::OnManagerGoingDown(
content::DownloadManager* manager) {
download::SimpleDownloadManager::DownloadVector downloads;
manager->GetAllDownloads(&downloads);
for (auto* download : downloads)
OnDownloadDestroyed(manager, download);
}
void DownloadControllerClientLacros::OnDownloadCreated(
content::DownloadManager* manager,
download::DownloadItem* item) {
auto* service = chromeos::LacrosService::Get();
if (!service->IsAvailable<crosapi::mojom::DownloadController>())
return;
service->GetRemote<crosapi::mojom::DownloadController>()->OnDownloadCreated(
ConvertToMojoDownloadItem(item));
}
void DownloadControllerClientLacros::OnDownloadUpdated(
content::DownloadManager* manager,
download::DownloadItem* item) {
auto* service = chromeos::LacrosService::Get();
if (!service->IsAvailable<crosapi::mojom::DownloadController>())
return;
service->GetRemote<crosapi::mojom::DownloadController>()->OnDownloadUpdated(
ConvertToMojoDownloadItem(item));
}
void DownloadControllerClientLacros::OnDownloadDestroyed(
content::DownloadManager* manager,
download::DownloadItem* item) {
auto* service = chromeos::LacrosService::Get();
if (!service->IsAvailable<crosapi::mojom::DownloadController>())
return;
service->GetRemote<crosapi::mojom::DownloadController>()->OnDownloadDestroyed(
ConvertToMojoDownloadItem(item));
}
| 36.823834 | 80 | 0.748698 | [
"vector"
] |
cbb0ee16ba0188d77ba8b5a2f582c00a083eb222 | 7,092 | cc | C++ | src/trainer/server.cc | kaiping/RNNLM | 0bdc679deaf40216e8162f77d68b4e746b0b7516 | [
"Apache-2.0"
] | null | null | null | src/trainer/server.cc | kaiping/RNNLM | 0bdc679deaf40216e8162f77d68b4e746b0b7516 | [
"Apache-2.0"
] | null | null | null | src/trainer/server.cc | kaiping/RNNLM | 0bdc679deaf40216e8162f77d68b4e746b0b7516 | [
"Apache-2.0"
] | null | null | null | #include <list>
#include <tuple>
#include <queue>
#include "mshadow/tensor.h"
#include "trainer/server.h"
#include "utils/param.h"
#include "utils/singleton.h"
#include "utils/factory.h"
#include "utils/cluster.h"
#include "proto/common.pb.h"
using namespace mshadow;
namespace singa {
Server::Server(int thread_id,int group_id, int server_id):
thread_id_(thread_id),group_id_(group_id), server_id_(server_id){}
void Server::Setup(const UpdaterProto& proto,
shared_ptr<ServerShard> shard, const vector<int>& slice2group){
//VLOG(3) << "Parsing config file for host "<<hosts[id_] << " server id = " <<id_;
updater_=shared_ptr<Updater>(Singleton<Factory<Updater>>::Instance()
->Create("Updater"));
updater_->Init(proto);
shard_=shard;
slice2group_=slice2group;
}
void Server::Run(){
LOG(ERROR)<<"Server (group_id = "<<group_id_
<<", id = "<<server_id_<<") starts";
dealer_=std::make_shared<Dealer>(2*thread_id_);
dealer_->Connect(kInprocRouterEndpoint);
auto cluster=Cluster::Get();
Msg* ping=new Msg();
ping->set_src(group_id_, server_id_, kServer);
ping->set_dst(-1,-1,kStub);
ping->add_frame("PING", 4);
ping->set_type(kConnect);
dealer_->Send(&ping);
vector<Param*> master_params;
size_t syncEntry=0;
//start recv loop and process requests
while (true){
Msg* msg=dealer_->Receive();
if (msg==nullptr)
break;
Msg* response=nullptr, *sync=nullptr;
int type=msg->type();
if (type== kStop){
msg->set_src(group_id_, server_id_, kServer);
msg->set_dst(-1,-1, kStub);
dealer_->Send(&msg);
break;
}else if (type==kConnect){
// TODO remove receiving pong msg
string pong((char*)msg->frame_data(), msg->frame_size());
CHECK_STREQ("PONG", pong.c_str());
DeleteMsg(&msg);
}else if(type==kPut){
int pid = msg->trgt_second();
response = HandlePut(&msg);
if(slice2group_[pid]==group_id_)
master_params.push_back(shard_->at(pid));
}else{
int pid=msg->trgt_second();
if(shard_->find(pid)==shard_->end()){
// delay the processing by re-queue the msg.
response=msg;
//LOG(INFO)<<"Requeue msg"<<type;
}else if(type == kSyncReminder){
DeleteMsg(&msg);
if(syncEntry>=master_params.size())
continue;
auto param=master_params.at(syncEntry);
// control the frequency of synchronization
// currently sync is triggerred only when the slice is updated
// by local worker or other workers for at least nserver_groups times.
// TODO may optimize the trigger condition.
if(abs(param->local_version()-param->version())>=cluster->nserver_groups()){
// TODO replace the argument (0,0) to sync a chunk instead of a slice
sync=param->GenSyncMsg(0,0);
for(int i=0;i<cluster->nserver_groups();i++){
if(i!=group_id_) {
Msg* tmp=sync;
if(i<cluster->nserver_groups()-1)
tmp= new Msg(*sync);
// assume only one server per group, TODO generalize it
tmp->set_dst(i, 0, kServer);
tmp->set_src(group_id_, server_id_, kServer);
dealer_->Send(&tmp);
param->set_version(param->local_version());
//LOG(ERROR)<<"sync slice="<<param->id()<<" to procs "<<i;
}
}
syncEntry=(syncEntry+1)%master_params.size();
}
}else{
auto param=shard_->at(pid);
switch (type){
case kGet:
response=HandleGet(param, &msg);
break;
case kUpdate:
response = HandleUpdate(param, &msg);
break;
case kSyncRequest:
response = HandleSyncRequest(param, &msg);
break;
default:
LOG(ERROR)<<"Unknown message type "<<type;
break;
}
}
}
if (response!=nullptr)
dealer_->Send(&response);
}
LOG(ERROR)<<"Server (group_id = "<<group_id_
<<", id = "<<server_id_<<") stops";
}
Msg* Server::HandlePut(Msg **msg){
int version=(*msg)->trgt_third();
int pid=(*msg)->trgt_second();
Param* param=nullptr;
if(shard_->find(pid)!=shard_->end()){
LOG(ERROR)<<"Param ("<<pid<<") is put more than once";
param=shard_->at(pid);
}else{
auto factory=Singleton<Factory<Param>>::Instance();
param=factory ->Create("Param");
(*shard_)[pid]=param;
}
auto response=param->HandlePutMsg(msg);
// must set version after HandlePutMsg which allocates the memory
param->set_version(version);
param->set_local_version(version);
param->set_id(pid);
//LOG(ERROR)<<"put norm "<<param->data().asum_data()<<", "<<pid;
if(Cluster::Get()->nserver_groups()>1 &&
slice2group_[pid]!=group_id_){
last_data_[pid]=std::make_shared<Blob<float>>();
last_data_[pid]->ReshapeLike(param->data());
last_data_[pid]->CopyFrom(param->data());
}
LOG(INFO)<<"server ("<<group_id_<<", "<<server_id_
<<") put slice="<<pid<<" size="<<param->size();
return response;
}
Msg* Server::HandleGet(Param* param, Msg **msg){
if(param->version()<(*msg)->trgt_third())
return *msg;
else{
auto reply= param->HandleGetMsg(msg);
int paramid=reply->trgt_first(), slice=reply->trgt_second();
reply->set_trgt(paramid, slice, param->version());
return reply;
}
}
Msg* Server::HandleUpdate(Param* param, Msg **msg) {
auto* tmp=static_cast<Msg*>((*msg)->CopyAddr());
tmp->SwapAddr();
int paramid=(*msg)->trgt_first();
int sliceid=(*msg)->trgt_second();
int step=(*msg)->trgt_third();
bool copy=param->ParseUpdateMsg(msg);
updater_->Update(step, param);
param->set_local_version(param->local_version()+1);
auto response=param->GenUpdateResponseMsg(copy);
response->set_trgt(paramid, sliceid, param->local_version());
response->SetAddr(tmp);
delete tmp;
return response;
}
Msg* Server::HandleSyncRequest(Param* param, Msg **msg){
Msg* response=nullptr;
auto shape=Shape1(param->size());
CHECK_EQ((*msg)->frame_size(), param->size()*sizeof(float));
Tensor<cpu, 1> tmp(static_cast<float*>((*msg)->frame_data()), shape);
Tensor<cpu, 1> cur(param->mutable_cpu_data(), shape);
//LOG(ERROR)<<"Recv sync for "<<param->id();
if(slice2group_[param->id()]==group_id_){
cur+=tmp;
param->set_local_version(param->local_version()+1);
}else{
TensorContainer<cpu, 1> diff(shape);
Tensor<cpu, 1> prev(last_data_[param->id()]->mutable_cpu_data(), shape);
diff=cur-prev;
(*msg)->next_frame();
int bandwidth;
sscanf(static_cast<char*>((*msg)->frame_data()), "%d", &bandwidth);
if(bandwidth>0){
response=new Msg();
response->set_type(kSyncRequest);
response->set_trgt(-1, param->id(), param->version());
response->add_frame(diff.dptr, param->size()*sizeof(float));
(*msg)->SwapAddr();
response->SetAddr(*msg);
prev=diff+tmp;
Copy(cur, prev);
}else{
Copy(prev, tmp);
cur=tmp+diff;
}
}
DeleteMsg(msg);
return response;
}
} /* singa */
| 33.45283 | 84 | 0.617597 | [
"shape",
"vector"
] |
cbc3d51067f62019c44febc043444b6d7c5f8d5f | 5,340 | hpp | C++ | src/jk/cog/vm/executor.hpp | jdmclark/gorc | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | [
"Apache-2.0"
] | 97 | 2015-02-24T05:09:24.000Z | 2022-01-23T12:08:22.000Z | src/jk/cog/vm/executor.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 8 | 2015-03-27T23:03:23.000Z | 2020-12-21T02:34:33.000Z | src/jk/cog/vm/executor.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 10 | 2016-03-24T14:32:50.000Z | 2021-11-13T02:38:53.000Z | #pragma once
#include "call_stack_frame.hpp"
#include "content/asset_ref.hpp"
#include "content/id.hpp"
#include "executor_linkage.hpp"
#include "heap.hpp"
#include "instance.hpp"
#include "io/binary_input_stream.hpp"
#include "io/binary_output_stream.hpp"
#include "jk/cog/script/message_type.hpp"
#include "jk/cog/script/verb_table.hpp"
#include "pulse_record.hpp"
#include "sleep_record.hpp"
#include "timer_record.hpp"
#include "utility/range.hpp"
#include "utility/service_registry.hpp"
#include "virtual_machine.hpp"
#include <map>
#include <memory>
#include <tuple>
#include <vector>
namespace gorc {
namespace cog {
namespace detail {
struct executor_link_comp {
bool operator()(value left, value right) const;
};
struct executor_wait_comp {
bool operator()(std::tuple<message_type, value> const &,
std::tuple<message_type, value> const &) const;
};
struct executor_gi_comp {
bool operator()(asset_ref<script> left, asset_ref<script> right) const;
};
struct executor_timer_comp {
bool operator()(std::tuple<cog_id, value> const &,
std::tuple<cog_id, value> const &) const;
};
}
class executor {
private:
heap globals;
verb_table &verbs;
virtual_machine vm;
service_registry services;
std::vector<std::unique_ptr<instance>> instances;
std::vector<std::unique_ptr<sleep_record>> sleep_records;
std::multimap<std::tuple<message_type, value>,
std::unique_ptr<continuation>,
detail::executor_wait_comp>
wait_records;
std::map<cog_id, pulse_record> pulse_records;
std::multimap<std::tuple<cog_id, value>, timer_record, detail::executor_timer_comp>
timer_records;
std::multimap<value, executor_linkage, detail::executor_link_comp> linkages;
std::map<asset_ref<script>, cog_id, detail::executor_gi_comp> global_instance_map;
cog_id master_cog;
void add_linkage(cog_id id, instance const &inst);
public:
executor(service_registry const &svc);
executor(deserialization_constructor_tag, binary_input_stream &);
void binary_serialize_object(binary_output_stream &) const;
cog_id create_instance(asset_ref<cog::script>);
cog_id create_instance(asset_ref<cog::script>, std::vector<value> const &);
cog_id create_global_instance(asset_ref<cog::script>);
instance &get_instance(cog_id instance_id);
void add_sleep_record(std::unique_ptr<sleep_record> &&);
void add_wait_record(message_type msg, value sender, std::unique_ptr<continuation> &&);
void add_timer_record(cog_id, value id, time_delta, value param0, value param1);
void erase_timer_record(cog_id, value id);
void set_pulse(cog_id, maybe<time_delta>);
maybe<call_stack_frame> create_message_frame(cog_id instance,
message_type msg,
value sender,
value sender_id,
value source,
value param0,
value param1,
value param2,
value param3);
value send(cog_id instance,
message_type msg,
value sender,
value sender_id,
value source,
value param0 = value(),
value param1 = value(),
value param2 = value(),
value param3 = value(),
char const *send_reason = "direct");
void send_to_all(message_type msg,
value sender,
value sender_id,
value source,
value param0 = value(),
value param1 = value(),
value param2 = value(),
value param3 = value());
void send_to_linked(message_type msg,
value sender,
value source,
source_type st,
value param0 = value(),
value param1 = value(),
value param2 = value(),
value param3 = value());
void set_master_cog(cog_id);
cog_id get_master_cog() const;
void update(time_delta dt);
inline auto get_linkages() const
{
return make_range(linkages);
}
};
}
}
| 37.87234 | 99 | 0.501685 | [
"vector"
] |
cbc40ae5b3f85c9a6e33a018c3b59bdd9a6509ed | 35,575 | cxx | C++ | main/package/source/package/zippackage/ZipPackageStream.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/package/source/package/zippackage/ZipPackageStream.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/package/source/package/zippackage/ZipPackageStream.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER( update_precomp.py ): autogen include statement, do not remove
#include "precompiled_package.hxx"
#include <com/sun/star/packages/zip/ZipConstants.hpp>
#include <com/sun/star/embed/StorageFormats.hpp>
#include <com/sun/star/packages/zip/ZipIOException.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/xml/crypto/DigestID.hpp>
#include <com/sun/star/xml/crypto/CipherID.hpp>
#include <ZipPackageStream.hxx>
#include <ZipPackage.hxx>
#include <ZipFile.hxx>
#include <EncryptedDataHeader.hxx>
#include <vos/diagnose.hxx>
#include "wrapstreamforshare.hxx"
#include <comphelper/seekableinput.hxx>
#include <comphelper/storagehelper.hxx>
#include <rtl/instance.hxx>
#include <PackageConstants.hxx>
using namespace com::sun::star::packages::zip::ZipConstants;
using namespace com::sun::star::packages::zip;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star;
using namespace cppu;
using namespace rtl;
namespace { struct lcl_CachedImplId : public rtl::Static< Sequence < sal_Int8 >, lcl_CachedImplId > {}; }
const ::com::sun::star::uno::Sequence < sal_Int8 >& ZipPackageStream::static_getImplementationId()
{
return lcl_CachedImplId::get();
}
ZipPackageStream::ZipPackageStream ( ZipPackage & rNewPackage,
const uno::Reference< XMultiServiceFactory >& xFactory,
sal_Bool bAllowRemoveOnInsert )
: m_xFactory( xFactory )
, rZipPackage( rNewPackage )
, bToBeCompressed ( sal_True )
, bToBeEncrypted ( sal_False )
, bHaveOwnKey ( sal_False )
, bIsEncrypted ( sal_False )
, m_nImportedStartKeyAlgorithm( 0 )
, m_nImportedEncryptionAlgorithm( 0 )
, m_nImportedChecksumAlgorithm( 0 )
, m_nImportedDerivedKeySize( 0 )
, m_nStreamMode( PACKAGE_STREAM_NOTSET )
, m_nMagicalHackPos( 0 )
, m_nMagicalHackSize( 0 )
, m_bHasSeekable( sal_False )
, m_bCompressedIsSetFromOutside( sal_False )
, m_bFromManifest( sal_False )
, m_bUseWinEncoding( false )
{
OSL_ENSURE( m_xFactory.is(), "No factory is provided to ZipPackageStream!\n" );
this->mbAllowRemoveOnInsert = bAllowRemoveOnInsert;
SetFolder ( sal_False );
aEntry.nVersion = -1;
aEntry.nFlag = 0;
aEntry.nMethod = -1;
aEntry.nTime = -1;
aEntry.nCrc = -1;
aEntry.nCompressedSize = -1;
aEntry.nSize = -1;
aEntry.nOffset = -1;
aEntry.nPathLen = -1;
aEntry.nExtraLen = -1;
Sequence < sal_Int8 > &rCachedImplId = lcl_CachedImplId::get();
if ( !rCachedImplId.getLength() )
rCachedImplId = getImplementationId();
}
ZipPackageStream::~ZipPackageStream( void )
{
}
void ZipPackageStream::setZipEntryOnLoading( const ZipEntry &rInEntry )
{
aEntry.nVersion = rInEntry.nVersion;
aEntry.nFlag = rInEntry.nFlag;
aEntry.nMethod = rInEntry.nMethod;
aEntry.nTime = rInEntry.nTime;
aEntry.nCrc = rInEntry.nCrc;
aEntry.nCompressedSize = rInEntry.nCompressedSize;
aEntry.nSize = rInEntry.nSize;
aEntry.nOffset = rInEntry.nOffset;
aEntry.sPath = rInEntry.sPath;
aEntry.nPathLen = rInEntry.nPathLen;
aEntry.nExtraLen = rInEntry.nExtraLen;
if ( aEntry.nMethod == STORED )
bToBeCompressed = sal_False;
}
//--------------------------------------------------------------------------
void ZipPackageStream::CloseOwnStreamIfAny()
{
if ( xStream.is() )
{
xStream->closeInput();
xStream = uno::Reference< io::XInputStream >();
m_bHasSeekable = sal_False;
}
}
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > ZipPackageStream::GetOwnSeekStream()
{
if ( !m_bHasSeekable && xStream.is() )
{
// The package component requires that every stream either be FROM a package or it must support XSeekable!
// The only exception is a nonseekable stream that is provided only for storing, if such a stream
// is accessed before commit it MUST be wrapped.
// Wrap the stream in case it is not seekable
xStream = ::comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( xStream, m_xFactory );
uno::Reference< io::XSeekable > xSeek( xStream, UNO_QUERY );
if ( !xSeek.is() )
throw RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "The stream must support XSeekable!" ) ),
uno::Reference< XInterface >() );
m_bHasSeekable = sal_True;
}
return xStream;
}
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > ZipPackageStream::GetRawEncrStreamNoHeaderCopy()
{
if ( m_nStreamMode != PACKAGE_STREAM_RAW || !GetOwnSeekStream().is() )
throw io::IOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
if ( m_xBaseEncryptionData.is() )
throw ZipIOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Encrypted stream without encryption data!\n" ) ),
uno::Reference< XInterface >() );
uno::Reference< io::XSeekable > xSeek( GetOwnSeekStream(), UNO_QUERY );
if ( !xSeek.is() )
throw ZipIOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "The stream must be seekable!\n" ) ),
uno::Reference< XInterface >() );
// skip header
xSeek->seek( n_ConstHeaderSize + getInitialisationVector().getLength() +
getSalt().getLength() + getDigest().getLength() );
// create temporary stream
uno::Reference < io::XOutputStream > xTempOut(
m_xFactory->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.io.TempFile" ) ) ),
uno::UNO_QUERY );
uno::Reference < io::XInputStream > xTempIn( xTempOut, UNO_QUERY );
uno::Reference < io::XSeekable > xTempSeek( xTempOut, UNO_QUERY );
if ( !xTempOut.is() || !xTempIn.is() || !xTempSeek.is() )
throw io::IOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
// copy the raw stream to the temporary file starting from the current position
::comphelper::OStorageHelper::CopyInputToOutput( GetOwnSeekStream(), xTempOut );
xTempOut->closeOutput();
xTempSeek->seek( 0 );
return xTempIn;
}
//--------------------------------------------------------------------------
sal_Int32 ZipPackageStream::GetEncryptionAlgorithm() const
{
return m_nImportedEncryptionAlgorithm ? m_nImportedEncryptionAlgorithm : rZipPackage.GetEncAlgID();
}
//--------------------------------------------------------------------------
sal_Int32 ZipPackageStream::GetBlockSize() const
{
return GetEncryptionAlgorithm() == ::com::sun::star::xml::crypto::CipherID::AES_CBC_W3C_PADDING ? 16 : 8;
}
//--------------------------------------------------------------------------
::rtl::Reference< EncryptionData > ZipPackageStream::GetEncryptionData( bool bUseWinEncoding )
{
::rtl::Reference< EncryptionData > xResult;
if ( m_xBaseEncryptionData.is() )
xResult = new EncryptionData(
*m_xBaseEncryptionData,
GetEncryptionKey( bUseWinEncoding ),
GetEncryptionAlgorithm(),
m_nImportedChecksumAlgorithm ? m_nImportedChecksumAlgorithm : rZipPackage.GetChecksumAlgID(),
m_nImportedDerivedKeySize ? m_nImportedDerivedKeySize : rZipPackage.GetDefaultDerivedKeySize(),
GetStartKeyGenID() );
return xResult;
}
//--------------------------------------------------------------------------
void ZipPackageStream::SetBaseEncryptionData( const ::rtl::Reference< BaseEncryptionData >& xData )
{
m_xBaseEncryptionData = xData;
}
//--------------------------------------------------------------------------
uno::Sequence< sal_Int8 > ZipPackageStream::GetEncryptionKey( bool bUseWinEncoding )
{
uno::Sequence< sal_Int8 > aResult;
sal_Int32 nKeyGenID = GetStartKeyGenID();
bUseWinEncoding = ( bUseWinEncoding || m_bUseWinEncoding );
if ( bHaveOwnKey && m_aStorageEncryptionKeys.getLength() )
{
::rtl::OUString aNameToFind;
if ( nKeyGenID == xml::crypto::DigestID::SHA256 )
aNameToFind = PACKAGE_ENCRYPTIONDATA_SHA256UTF8;
else if ( nKeyGenID == xml::crypto::DigestID::SHA1 )
{
aNameToFind = bUseWinEncoding ? PACKAGE_ENCRYPTIONDATA_SHA1MS1252 : PACKAGE_ENCRYPTIONDATA_SHA1UTF8;
}
else
throw uno::RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "No expected key is provided!" ) ), uno::Reference< uno::XInterface >() );
for ( sal_Int32 nInd = 0; nInd < m_aStorageEncryptionKeys.getLength(); nInd++ )
if ( m_aStorageEncryptionKeys[nInd].Name.equals( aNameToFind ) )
m_aStorageEncryptionKeys[nInd].Value >>= aResult;
// empty keys are not allowed here
// so it is not important whether there is no key, or the key is empty, it is an error
if ( !aResult.getLength() )
throw uno::RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "No expected key is provided!" ) ), uno::Reference< uno::XInterface >() );
}
else
aResult = m_aEncryptionKey;
if ( !aResult.getLength() || !bHaveOwnKey )
aResult = rZipPackage.GetEncryptionKey();
return aResult;
}
//--------------------------------------------------------------------------
sal_Int32 ZipPackageStream::GetStartKeyGenID()
{
// generally should all the streams use the same Start Key
// but if raw copy without password takes place, we should preserve the imported algorithm
return m_nImportedStartKeyAlgorithm ? m_nImportedStartKeyAlgorithm : rZipPackage.GetStartKeyGenID();
}
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > ZipPackageStream::TryToGetRawFromDataStream( sal_Bool bAddHeaderForEncr )
{
if ( m_nStreamMode != PACKAGE_STREAM_DATA || !GetOwnSeekStream().is() || ( bAddHeaderForEncr && !bToBeEncrypted ) )
throw packages::NoEncryptionException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
Sequence< sal_Int8 > aKey;
if ( bToBeEncrypted )
{
aKey = GetEncryptionKey();
if ( !aKey.getLength() )
throw packages::NoEncryptionException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
}
try
{
// create temporary file
uno::Reference < io::XStream > xTempStream(
m_xFactory->createInstance ( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.io.TempFile" ) ) ),
uno::UNO_QUERY );
if ( !xTempStream.is() )
throw io::IOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
// create a package based on it
ZipPackage* pPackage = new ZipPackage( m_xFactory );
uno::Reference< XSingleServiceFactory > xPackageAsFactory( static_cast< XSingleServiceFactory* >( pPackage ) );
if ( !xPackageAsFactory.is() )
throw RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
Sequence< Any > aArgs( 1 );
aArgs[0] <<= xTempStream;
pPackage->initialize( aArgs );
// create a new package stream
uno::Reference< XDataSinkEncrSupport > xNewPackStream( xPackageAsFactory->createInstance(), UNO_QUERY );
if ( !xNewPackStream.is() )
throw RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
xNewPackStream->setDataStream( static_cast< io::XInputStream* >(
new WrapStreamForShare( GetOwnSeekStream(), rZipPackage.GetSharedMutexRef() ) ) );
uno::Reference< XPropertySet > xNewPSProps( xNewPackStream, UNO_QUERY );
if ( !xNewPSProps.is() )
throw RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
// copy all the properties of this stream to the new stream
xNewPSProps->setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) ), makeAny( sMediaType ) );
xNewPSProps->setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Compressed" ) ), makeAny( bToBeCompressed ) );
if ( bToBeEncrypted )
{
xNewPSProps->setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ENCRYPTION_KEY_PROPERTY ) ), makeAny( aKey ) );
xNewPSProps->setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Encrypted" ) ), makeAny( sal_True ) );
}
// insert a new stream in the package
uno::Reference< XUnoTunnel > xTunnel;
Any aRoot = pPackage->getByHierarchicalName( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) );
aRoot >>= xTunnel;
uno::Reference< container::XNameContainer > xRootNameContainer( xTunnel, UNO_QUERY );
if ( !xRootNameContainer.is() )
throw RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
uno::Reference< XUnoTunnel > xNPSTunnel( xNewPackStream, UNO_QUERY );
xRootNameContainer->insertByName( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "dummy" ) ), makeAny( xNPSTunnel ) );
// commit the temporary package
pPackage->commitChanges();
// get raw stream from the temporary package
uno::Reference< io::XInputStream > xInRaw;
if ( bAddHeaderForEncr )
xInRaw = xNewPackStream->getRawStream();
else
xInRaw = xNewPackStream->getPlainRawStream();
// create another temporary file
uno::Reference < io::XOutputStream > xTempOut(
m_xFactory->createInstance ( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.io.TempFile" ) ) ),
uno::UNO_QUERY );
uno::Reference < io::XInputStream > xTempIn( xTempOut, UNO_QUERY );
uno::Reference < io::XSeekable > xTempSeek( xTempOut, UNO_QUERY );
if ( !xTempOut.is() || !xTempIn.is() || !xTempSeek.is() )
throw io::IOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
// copy the raw stream to the temporary file
::comphelper::OStorageHelper::CopyInputToOutput( xInRaw, xTempOut );
xTempOut->closeOutput();
xTempSeek->seek( 0 );
// close raw stream, package stream and folder
xInRaw = uno::Reference< io::XInputStream >();
xNewPSProps = uno::Reference< XPropertySet >();
xNPSTunnel = uno::Reference< XUnoTunnel >();
xNewPackStream = uno::Reference< XDataSinkEncrSupport >();
xTunnel = uno::Reference< XUnoTunnel >();
xRootNameContainer = uno::Reference< container::XNameContainer >();
// return the stream representing the first temporary file
return xTempIn;
}
catch ( RuntimeException& )
{
throw;
}
catch ( Exception& )
{
}
throw io::IOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
}
//--------------------------------------------------------------------------
sal_Bool ZipPackageStream::ParsePackageRawStream()
{
OSL_ENSURE( GetOwnSeekStream().is(), "A stream must be provided!\n" );
if ( !GetOwnSeekStream().is() )
return sal_False;
sal_Bool bOk = sal_False;
::rtl::Reference< BaseEncryptionData > xTempEncrData;
sal_Int32 nMagHackSize = 0;
Sequence < sal_Int8 > aHeader ( 4 );
try
{
if ( GetOwnSeekStream()->readBytes ( aHeader, 4 ) == 4 )
{
const sal_Int8 *pHeader = aHeader.getConstArray();
sal_uInt32 nHeader = ( pHeader [0] & 0xFF ) |
( pHeader [1] & 0xFF ) << 8 |
( pHeader [2] & 0xFF ) << 16 |
( pHeader [3] & 0xFF ) << 24;
if ( nHeader == n_ConstHeader )
{
// this is one of our god-awful, but extremely devious hacks, everyone cheer
xTempEncrData = new BaseEncryptionData;
::rtl::OUString aMediaType;
sal_Int32 nEncAlgorithm = 0;
sal_Int32 nChecksumAlgorithm = 0;
sal_Int32 nDerivedKeySize = 0;
sal_Int32 nStartKeyGenID = 0;
if ( ZipFile::StaticFillData( xTempEncrData, nEncAlgorithm, nChecksumAlgorithm, nDerivedKeySize, nStartKeyGenID, nMagHackSize, aMediaType, GetOwnSeekStream() ) )
{
// We'll want to skip the data we've just read, so calculate how much we just read
// and remember it
m_nMagicalHackPos = n_ConstHeaderSize + xTempEncrData->m_aSalt.getLength()
+ xTempEncrData->m_aInitVector.getLength()
+ xTempEncrData->m_aDigest.getLength()
+ aMediaType.getLength() * sizeof( sal_Unicode );
m_nImportedEncryptionAlgorithm = nEncAlgorithm;
m_nImportedChecksumAlgorithm = nChecksumAlgorithm;
m_nImportedDerivedKeySize = nDerivedKeySize;
m_nImportedStartKeyAlgorithm = nStartKeyGenID;
m_nMagicalHackSize = nMagHackSize;
sMediaType = aMediaType;
bOk = sal_True;
}
}
}
}
catch( Exception& )
{
}
if ( !bOk )
{
// the provided stream is not a raw stream
return sal_False;
}
m_xBaseEncryptionData = xTempEncrData;
SetIsEncrypted ( sal_True );
// it's already compressed and encrypted
bToBeEncrypted = bToBeCompressed = sal_False;
return sal_True;
}
void ZipPackageStream::SetPackageMember( sal_Bool bNewValue )
{
if ( bNewValue )
{
m_nStreamMode = PACKAGE_STREAM_PACKAGEMEMBER;
m_nMagicalHackPos = 0;
m_nMagicalHackSize = 0;
}
else if ( m_nStreamMode == PACKAGE_STREAM_PACKAGEMEMBER )
m_nStreamMode = PACKAGE_STREAM_NOTSET; // must be reset
}
// XActiveDataSink
//--------------------------------------------------------------------------
void SAL_CALL ZipPackageStream::setInputStream( const uno::Reference< io::XInputStream >& aStream )
throw( RuntimeException )
{
// if seekable access is required the wrapping will be done on demand
xStream = aStream;
m_nImportedEncryptionAlgorithm = 0;
m_bHasSeekable = sal_False;
SetPackageMember ( sal_False );
aEntry.nTime = -1;
m_nStreamMode = PACKAGE_STREAM_DETECT;
}
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getRawData()
throw( RuntimeException )
{
try
{
if ( IsPackageMember() )
{
return rZipPackage.getZipFile().getRawData( aEntry, GetEncryptionData(), bIsEncrypted, rZipPackage.GetSharedMutexRef() );
}
else if ( GetOwnSeekStream().is() )
{
return new WrapStreamForShare( GetOwnSeekStream(), rZipPackage.GetSharedMutexRef() );
}
else
return uno::Reference < io::XInputStream > ();
}
catch ( ZipException & )//rException )
{
VOS_ENSURE( 0, "ZipException thrown" );//rException.Message );
return uno::Reference < io::XInputStream > ();
}
catch ( Exception & )
{
VOS_ENSURE( 0, "Exception is thrown during stream wrapping!\n" );
return uno::Reference < io::XInputStream > ();
}
}
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getInputStream()
throw( RuntimeException )
{
try
{
if ( IsPackageMember() )
{
return rZipPackage.getZipFile().getInputStream( aEntry, GetEncryptionData(), bIsEncrypted, rZipPackage.GetSharedMutexRef() );
}
else if ( GetOwnSeekStream().is() )
{
return new WrapStreamForShare( GetOwnSeekStream(), rZipPackage.GetSharedMutexRef() );
}
else
return uno::Reference < io::XInputStream > ();
}
catch ( ZipException & )//rException )
{
VOS_ENSURE( 0,"ZipException thrown" );//rException.Message );
return uno::Reference < io::XInputStream > ();
}
catch ( Exception & )
{
VOS_ENSURE( 0, "Exception is thrown during stream wrapping!\n" );
return uno::Reference < io::XInputStream > ();
}
}
// XDataSinkEncrSupport
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getDataStream()
throw ( packages::WrongPasswordException,
io::IOException,
RuntimeException )
{
// There is no stream attached to this object
if ( m_nStreamMode == PACKAGE_STREAM_NOTSET )
return uno::Reference< io::XInputStream >();
// this method can not be used together with old approach
if ( m_nStreamMode == PACKAGE_STREAM_DETECT )
throw packages::zip::ZipIOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
if ( IsPackageMember() )
{
uno::Reference< io::XInputStream > xResult;
try
{
xResult = rZipPackage.getZipFile().getDataStream( aEntry, GetEncryptionData(), bIsEncrypted, rZipPackage.GetSharedMutexRef() );
}
catch( packages::WrongPasswordException& )
{
// workaround for the encrypted documents generated with the old OOo1.x bug.
if ( rZipPackage.GetStartKeyGenID() == xml::crypto::DigestID::SHA1 && !m_bUseWinEncoding )
{
xResult = rZipPackage.getZipFile().getDataStream( aEntry, GetEncryptionData( true ), bIsEncrypted, rZipPackage.GetSharedMutexRef() );
m_bUseWinEncoding = true;
}
else
throw;
}
return xResult;
}
else if ( m_nStreamMode == PACKAGE_STREAM_RAW )
return ZipFile::StaticGetDataFromRawStream( m_xFactory, GetOwnSeekStream(), GetEncryptionData() );
else if ( GetOwnSeekStream().is() )
{
return new WrapStreamForShare( GetOwnSeekStream(), rZipPackage.GetSharedMutexRef() );
}
else
return uno::Reference< io::XInputStream >();
}
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getRawStream()
throw ( packages::NoEncryptionException,
io::IOException,
uno::RuntimeException )
{
// There is no stream attached to this object
if ( m_nStreamMode == PACKAGE_STREAM_NOTSET )
return uno::Reference< io::XInputStream >();
// this method can not be used together with old approach
if ( m_nStreamMode == PACKAGE_STREAM_DETECT )
throw packages::zip::ZipIOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
if ( IsPackageMember() )
{
if ( !bIsEncrypted || !GetEncryptionData().is() )
throw packages::NoEncryptionException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
return rZipPackage.getZipFile().getWrappedRawStream( aEntry, GetEncryptionData(), sMediaType, rZipPackage.GetSharedMutexRef() );
}
else if ( GetOwnSeekStream().is() )
{
if ( m_nStreamMode == PACKAGE_STREAM_RAW )
{
return new WrapStreamForShare( GetOwnSeekStream(), rZipPackage.GetSharedMutexRef() );
}
else if ( m_nStreamMode == PACKAGE_STREAM_DATA && bToBeEncrypted )
return TryToGetRawFromDataStream( sal_True );
}
throw packages::NoEncryptionException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
}
//--------------------------------------------------------------------------
void SAL_CALL ZipPackageStream::setDataStream( const uno::Reference< io::XInputStream >& aStream )
throw ( io::IOException,
RuntimeException )
{
setInputStream( aStream );
m_nStreamMode = PACKAGE_STREAM_DATA;
}
//--------------------------------------------------------------------------
void SAL_CALL ZipPackageStream::setRawStream( const uno::Reference< io::XInputStream >& aStream )
throw ( packages::EncryptionNotAllowedException,
packages::NoRawFormatException,
io::IOException,
RuntimeException )
{
// wrap the stream in case it is not seekable
uno::Reference< io::XInputStream > xNewStream = ::comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( aStream, m_xFactory );
uno::Reference< io::XSeekable > xSeek( xNewStream, UNO_QUERY );
if ( !xSeek.is() )
throw RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "The stream must support XSeekable!" ) ),
uno::Reference< XInterface >() );
xSeek->seek( 0 );
uno::Reference< io::XInputStream > xOldStream = xStream;
xStream = xNewStream;
if ( !ParsePackageRawStream() )
{
xStream = xOldStream;
throw packages::NoRawFormatException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
}
// the raw stream MUST have seekable access
m_bHasSeekable = sal_True;
SetPackageMember ( sal_False );
aEntry.nTime = -1;
m_nStreamMode = PACKAGE_STREAM_RAW;
}
//--------------------------------------------------------------------------
uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getPlainRawStream()
throw ( io::IOException,
uno::RuntimeException )
{
// There is no stream attached to this object
if ( m_nStreamMode == PACKAGE_STREAM_NOTSET )
return uno::Reference< io::XInputStream >();
// this method can not be used together with old approach
if ( m_nStreamMode == PACKAGE_STREAM_DETECT )
throw packages::zip::ZipIOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
if ( IsPackageMember() )
{
return rZipPackage.getZipFile().getRawData( aEntry, GetEncryptionData(), bIsEncrypted, rZipPackage.GetSharedMutexRef() );
}
else if ( GetOwnSeekStream().is() )
{
if ( m_nStreamMode == PACKAGE_STREAM_RAW )
{
// the header should not be returned here
return GetRawEncrStreamNoHeaderCopy();
}
else if ( m_nStreamMode == PACKAGE_STREAM_DATA )
return TryToGetRawFromDataStream( sal_False );
}
return uno::Reference< io::XInputStream >();
}
// XUnoTunnel
//--------------------------------------------------------------------------
sal_Int64 SAL_CALL ZipPackageStream::getSomething( const Sequence< sal_Int8 >& aIdentifier )
throw( RuntimeException )
{
sal_Int64 nMe = 0;
if ( aIdentifier.getLength() == 16 &&
0 == rtl_compareMemory( static_getImplementationId().getConstArray(), aIdentifier.getConstArray(), 16 ) )
nMe = reinterpret_cast < sal_Int64 > ( this );
return nMe;
}
// XPropertySet
//--------------------------------------------------------------------------
void SAL_CALL ZipPackageStream::setPropertyValue( const OUString& aPropertyName, const Any& aValue )
throw( beans::UnknownPropertyException, beans::PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException )
{
if ( aPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "MediaType" )) )
{
if ( rZipPackage.getFormat() != embed::StorageFormats::PACKAGE && rZipPackage.getFormat() != embed::StorageFormats::OFOPXML )
throw beans::PropertyVetoException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
if ( aValue >>= sMediaType )
{
if ( sMediaType.getLength() > 0 )
{
if ( sMediaType.indexOf ( OUString( RTL_CONSTASCII_USTRINGPARAM ( "text" ) ) ) != -1
|| sMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM ( "application/vnd.sun.star.oleobject" ) ) ) )
bToBeCompressed = sal_True;
else if ( !m_bCompressedIsSetFromOutside )
bToBeCompressed = sal_False;
}
}
else
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "MediaType must be a string!\n" ) ),
uno::Reference< XInterface >(),
2 );
}
else if ( aPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Size" ) ) )
{
if ( !( aValue >>= aEntry.nSize ) )
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Wrong type for Size property!\n" ) ),
uno::Reference< XInterface >(),
2 );
}
else if ( aPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Encrypted" ) ) )
{
if ( rZipPackage.getFormat() != embed::StorageFormats::PACKAGE )
throw beans::PropertyVetoException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
sal_Bool bEnc = sal_False;
if ( aValue >>= bEnc )
{
// In case of new raw stream, the stream must not be encrypted on storing
if ( bEnc && m_nStreamMode == PACKAGE_STREAM_RAW )
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Raw stream can not be encrypted on storing" ) ),
uno::Reference< XInterface >(),
2 );
bToBeEncrypted = bEnc;
if ( bToBeEncrypted && !m_xBaseEncryptionData.is() )
m_xBaseEncryptionData = new BaseEncryptionData;
}
else
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Wrong type for Encrypted property!\n" ) ),
uno::Reference< XInterface >(),
2 );
}
else if ( aPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ENCRYPTION_KEY_PROPERTY ) ) )
{
if ( rZipPackage.getFormat() != embed::StorageFormats::PACKAGE )
throw beans::PropertyVetoException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
uno::Sequence< sal_Int8 > aNewKey;
if ( !( aValue >>= aNewKey ) )
{
OUString sTempString;
if ( ( aValue >>= sTempString ) )
{
sal_Int32 nPathLength = sTempString.getLength();
Sequence < sal_Int8 > aSequence ( nPathLength );
sal_Int8 *pArray = aSequence.getArray();
const sal_Unicode *pChar = sTempString.getStr();
for ( sal_Int16 i = 0; i < nPathLength; i++ )
pArray[i] = static_cast < const sal_Int8 > ( pChar[i] );
aNewKey = aSequence;
}
else
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Wrong type for EncryptionKey property!\n" ) ),
uno::Reference< XInterface >(),
2 );
}
if ( aNewKey.getLength() )
{
if ( !m_xBaseEncryptionData.is() )
m_xBaseEncryptionData = new BaseEncryptionData;
m_aEncryptionKey = aNewKey;
// In case of new raw stream, the stream must not be encrypted on storing
bHaveOwnKey = sal_True;
if ( m_nStreamMode != PACKAGE_STREAM_RAW )
bToBeEncrypted = sal_True;
}
else
{
bHaveOwnKey = sal_False;
m_aEncryptionKey.realloc( 0 );
}
m_aStorageEncryptionKeys.realloc( 0 );
}
else if ( aPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( STORAGE_ENCRYPTION_KEYS_PROPERTY ) ) )
{
if ( rZipPackage.getFormat() != embed::StorageFormats::PACKAGE )
throw beans::PropertyVetoException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
uno::Sequence< beans::NamedValue > aKeys;
if ( !( aValue >>= aKeys ) )
{
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Wrong type for StorageEncryptionKeys property!\n" ) ),
uno::Reference< XInterface >(),
2 );
}
if ( aKeys.getLength() )
{
if ( !m_xBaseEncryptionData.is() )
m_xBaseEncryptionData = new BaseEncryptionData;
m_aStorageEncryptionKeys = aKeys;
// In case of new raw stream, the stream must not be encrypted on storing
bHaveOwnKey = sal_True;
if ( m_nStreamMode != PACKAGE_STREAM_RAW )
bToBeEncrypted = sal_True;
}
else
{
bHaveOwnKey = sal_False;
m_aStorageEncryptionKeys.realloc( 0 );
}
m_aEncryptionKey.realloc( 0 );
}
else if ( aPropertyName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Compressed" ) ) )
{
sal_Bool bCompr = sal_False;
if ( aValue >>= bCompr )
{
// In case of new raw stream, the stream must not be encrypted on storing
if ( bCompr && m_nStreamMode == PACKAGE_STREAM_RAW )
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Raw stream can not be encrypted on storing" ) ),
uno::Reference< XInterface >(),
2 );
bToBeCompressed = bCompr;
m_bCompressedIsSetFromOutside = sal_True;
}
else
throw IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Wrong type for Compressed property!\n" ) ),
uno::Reference< XInterface >(),
2 );
}
else
throw beans::UnknownPropertyException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
}
//--------------------------------------------------------------------------
Any SAL_CALL ZipPackageStream::getPropertyValue( const OUString& PropertyName )
throw( beans::UnknownPropertyException, WrappedTargetException, RuntimeException )
{
Any aAny;
if ( PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "MediaType" ) ) )
{
aAny <<= sMediaType;
return aAny;
}
else if ( PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Size" ) ) )
{
aAny <<= aEntry.nSize;
return aAny;
}
else if ( PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Encrypted" ) ) )
{
aAny <<= ( m_nStreamMode == PACKAGE_STREAM_RAW ) ? sal_True : bToBeEncrypted;
return aAny;
}
else if ( PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "WasEncrypted" ) ) )
{
aAny <<= bIsEncrypted;
return aAny;
}
else if ( PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Compressed" ) ) )
{
aAny <<= bToBeCompressed;
return aAny;
}
else if ( PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ENCRYPTION_KEY_PROPERTY ) ) )
{
aAny <<= m_aEncryptionKey;
return aAny;
}
else if ( PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( STORAGE_ENCRYPTION_KEYS_PROPERTY ) ) )
{
aAny <<= m_aStorageEncryptionKeys;
return aAny;
}
else
throw beans::UnknownPropertyException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
}
//--------------------------------------------------------------------------
void ZipPackageStream::setSize ( const sal_Int32 nNewSize )
{
if ( aEntry.nCompressedSize != nNewSize )
aEntry.nMethod = DEFLATED;
aEntry.nSize = nNewSize;
}
//--------------------------------------------------------------------------
OUString ZipPackageStream::getImplementationName()
throw ( RuntimeException )
{
return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "ZipPackageStream" ) );
}
//--------------------------------------------------------------------------
Sequence< OUString > ZipPackageStream::getSupportedServiceNames()
throw ( RuntimeException )
{
Sequence< OUString > aNames( 1 );
aNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.packages.PackageStream" ) );
return aNames;
}
//--------------------------------------------------------------------------
sal_Bool SAL_CALL ZipPackageStream::supportsService( OUString const & rServiceName )
throw ( RuntimeException )
{
return rServiceName == getSupportedServiceNames()[0];
}
| 37.805526 | 176 | 0.66676 | [
"object"
] |
cbc8fe668b5a79b3a108cde4d9d875c84540c908 | 12,189 | cc | C++ | test/src/unit-cppapi-fill_values.cc | aaronwolen/TileDB | a9aa26d0ce8be17f5cbff57a4fac169927501df2 | [
"MIT"
] | null | null | null | test/src/unit-cppapi-fill_values.cc | aaronwolen/TileDB | a9aa26d0ce8be17f5cbff57a4fac169927501df2 | [
"MIT"
] | null | null | null | test/src/unit-cppapi-fill_values.cc | aaronwolen/TileDB | a9aa26d0ce8be17f5cbff57a4fac169927501df2 | [
"MIT"
] | null | null | null | /**
* @file unit-cppapi-fill_values.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2020 TileDB Inc.
* @copyright Copyright (c) 2016 MIT and Intel Corporation
*
* 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.
*
* @section DESCRIPTION
*
* Tests the attribute fill values with the C++ API.
*/
#include "catch.hpp"
#include "tiledb/sm/cpp_api/tiledb"
#include "tiledb/sm/misc/constants.h"
#include <iostream>
using namespace tiledb;
void check_dump(const Attribute& attr, const std::string& gold_out) {
FILE* gold_fout = fopen("gold_fout.txt", "w");
fwrite(gold_out.c_str(), sizeof(char), gold_out.size(), gold_fout);
fclose(gold_fout);
FILE* fout = fopen("fout.txt", "w");
attr.dump(fout);
fclose(fout);
#ifdef _WIN32
CHECK(!system("FC gold_fout.txt fout.txt > nul"));
#else
CHECK(!system("diff gold_fout.txt fout.txt"));
#endif
// Clean up
Context ctx;
VFS vfs(ctx);
CHECK_NOTHROW(vfs.remove_file("gold_fout.txt"));
CHECK_NOTHROW(vfs.remove_file("fout.txt"));
}
void create_array_1d(
const std::string& array_name,
int32_t fill_int32 = tiledb::sm::constants::empty_int32,
std::string fill_char = std::string() + tiledb::sm::constants::empty_char,
std::array<double, 2> fill_double = {
{tiledb::sm::constants::empty_float64,
tiledb::sm::constants::empty_float64}}) {
Context ctx;
VFS vfs(ctx);
Domain domain(ctx);
auto d = Dimension::create<int32_t>(ctx, "d", {{1, 10}}, 10);
domain.add_dimension(d);
auto a1 = Attribute::create<int32_t>(ctx, "a1");
a1.set_fill_value(&fill_int32, sizeof(fill_int32));
auto a2 = Attribute::create<std::string>(ctx, "a2");
a2.set_fill_value(fill_char.c_str(), fill_char.size());
auto a3 = Attribute::create<double>(ctx, "a3");
a3.set_cell_val_num(2);
a3.set_fill_value(fill_double.data(), 2 * sizeof(double));
ArraySchema schema(ctx, TILEDB_DENSE);
schema.set_domain(domain);
schema.add_attributes(a1, a2, a3);
CHECK_NOTHROW(Array::create(array_name, schema));
}
void write_array_1d_partial(const std::string& array_name) {
Context ctx;
std::vector<int32_t> a1 = {3, 4};
std::vector<char> a2_val = {'3', '3', '4', '4', '4'};
std::vector<uint64_t> a2_off = {0, 2};
std::vector<double> a3 = {3.1, 3.2, 4.1, 4.2};
Array array(ctx, array_name, TILEDB_WRITE);
Query query(ctx, array, TILEDB_WRITE);
CHECK_NOTHROW(query.set_buffer("a1", a1));
CHECK_NOTHROW(query.set_buffer("a2", a2_off, a2_val));
CHECK_NOTHROW(query.set_buffer("a3", a3));
CHECK_NOTHROW(query.set_subarray<int32_t>({3, 4}));
CHECK_NOTHROW(query.set_layout(TILEDB_ROW_MAJOR));
REQUIRE(query.submit() == Query::Status::COMPLETE);
array.close();
}
void read_array_1d_partial(
const std::string& array_name,
int32_t fill_int32 = tiledb::sm::constants::empty_int32,
std::string fill_char = std::string() + tiledb::sm::constants::empty_char,
std::array<double, 2> fill_double = {
{tiledb::sm::constants::empty_float64,
tiledb::sm::constants::empty_float64}}) {
Context ctx;
std::vector<int32_t> a1(10);
std::vector<char> a2_val(100);
std::vector<uint64_t> a2_off(20);
std::vector<double> a3(20);
Array array(ctx, array_name, TILEDB_READ);
Query query(ctx, array, TILEDB_READ);
CHECK_NOTHROW(query.set_buffer("a1", a1));
CHECK_NOTHROW(query.set_buffer("a2", a2_off, a2_val));
CHECK_NOTHROW(query.set_buffer("a3", a3));
CHECK_NOTHROW(query.set_subarray<int32_t>({1, 10}));
REQUIRE(query.submit() == Query::Status::COMPLETE);
auto res = query.result_buffer_elements();
REQUIRE(res["a1"].second == 10);
REQUIRE(res["a2"].first == 10);
REQUIRE(res["a2"].second == 5 + 8 * fill_char.size());
REQUIRE(res["a3"].second == 20);
uint64_t off = 0;
for (size_t i = 0; i < 2; ++i) {
CHECK(a1[i] == fill_int32);
CHECK(a2_off[i] == off);
for (size_t c = 0; c < fill_char.size(); ++c) {
CHECK(a2_val[off] == fill_char[c]);
++off;
}
CHECK(!std::memcmp(&a3[2 * i], &fill_double[0], sizeof(double)));
CHECK(!std::memcmp(&a3[2 * i + 1], &fill_double[1], sizeof(double)));
}
CHECK(a1[2] == 3);
CHECK(a1[3] == 4);
CHECK(a2_off[2] == off);
CHECK(a2_val[off] == '3');
CHECK(a2_val[off + 1] == '3');
off += 2;
CHECK(a2_off[3] == off);
CHECK(a2_val[off] == '4');
CHECK(a2_val[off + 1] == '4');
CHECK(a2_val[off + 2] == '4');
off += 3;
CHECK(a3[4] == 3.1);
CHECK(a3[5] == 3.2);
CHECK(a3[6] == 4.1);
CHECK(a3[7] == 4.2);
for (size_t i = 4; i < 10; ++i) {
CHECK(a1[i] == fill_int32);
CHECK(a2_off[i] == off);
for (size_t c = 0; c < fill_char.size(); ++c) {
CHECK(a2_val[off] == fill_char[c]);
++off;
}
CHECK(!std::memcmp(&a3[2 * i], &fill_double[0], sizeof(double)));
CHECK(!std::memcmp(&a3[2 * i + 1], &fill_double[1], sizeof(double)));
}
array.close();
}
void read_array_1d_empty(
const std::string& array_name,
int32_t fill_int32 = tiledb::sm::constants::empty_int32,
std::string fill_char = std::string() + tiledb::sm::constants::empty_char,
std::array<double, 2> fill_double = {
{tiledb::sm::constants::empty_float64,
tiledb::sm::constants::empty_float64}}) {
Context ctx;
std::vector<int32_t> a1(10);
std::vector<char> a2_val(100);
std::vector<uint64_t> a2_off(20);
std::vector<double> a3(20);
Array array(ctx, array_name, TILEDB_READ);
Query query(ctx, array, TILEDB_READ);
CHECK_NOTHROW(query.set_buffer("a1", a1));
CHECK_NOTHROW(query.set_buffer("a2", a2_off, a2_val));
CHECK_NOTHROW(query.set_buffer("a3", a3));
CHECK_NOTHROW(query.set_subarray<int32_t>({1, 10}));
REQUIRE(query.submit() == Query::Status::COMPLETE);
auto res = query.result_buffer_elements();
REQUIRE(res["a1"].second == 10);
REQUIRE(res["a2"].first == 10);
REQUIRE(res["a2"].second == 10 * fill_char.size());
REQUIRE(res["a3"].second == 20);
uint64_t off = 0;
for (size_t i = 0; i < 10; ++i) {
CHECK(a1[i] == fill_int32);
CHECK(a2_off[i] == off);
for (size_t c = 0; c < fill_char.size(); ++c) {
CHECK(a2_val[off] == fill_char[c]);
++off;
}
CHECK(!std::memcmp(&a3[2 * i], &fill_double[0], sizeof(double)));
CHECK(!std::memcmp(&a3[2 * i + 1], &fill_double[1], sizeof(double)));
}
array.close();
}
TEST_CASE(
"C++ API: Test fill values, basic errors", "[cppapi][fill-values][basic]") {
int32_t value = 5;
uint64_t value_size = sizeof(int32_t);
Context ctx;
// Fixed-sized
auto a = tiledb::Attribute::create<int32_t>(ctx, "a");
// Null value
CHECK_THROWS(a.set_fill_value(nullptr, value_size));
// Zero size
CHECK_THROWS(a.set_fill_value(&value, 0));
// Wrong size
CHECK_THROWS(a.set_fill_value(&value, 100));
// Get default
const void* value_ptr;
CHECK_NOTHROW(a.get_fill_value(&value_ptr, &value_size));
CHECK(*(const int32_t*)value_ptr == -2147483648);
CHECK(value_size == sizeof(int32_t));
// Check dump
std::string dump = std::string("### Attribute ###\n") + "- Name: a\n" +
"- Type: INT32\n" + "- Cell val num: 1\n" +
"- Filters: 0\n" + "- Fill value: -2147483648\n";
check_dump(a, dump);
// Correct setter
CHECK_NOTHROW(a.set_fill_value(&value, value_size));
// Get the set value
CHECK_NOTHROW(a.get_fill_value(&value_ptr, &value_size));
CHECK(*(const int32_t*)value_ptr == 5);
CHECK(value_size == sizeof(int32_t));
// Check dump
dump = std::string("### Attribute ###\n") + "- Name: a\n" +
"- Type: INT32\n" + "- Cell val num: 1\n" + "- Filters: 0\n" +
"- Fill value: 5\n";
check_dump(a, dump);
// Setting the cell val num, also sets the fill value to a new default
CHECK_NOTHROW(a.set_cell_val_num(2));
CHECK_NOTHROW(a.get_fill_value(&value_ptr, &value_size));
CHECK(((const int32_t*)value_ptr)[0] == -2147483648);
CHECK(((const int32_t*)value_ptr)[1] == -2147483648);
CHECK(value_size == 2 * sizeof(int32_t));
// Check dump
dump = std::string("### Attribute ###\n") + "- Name: a\n" +
"- Type: INT32\n" + "- Cell val num: 2\n" + "- Filters: 0\n" +
"- Fill value: -2147483648, -2147483648\n";
check_dump(a, dump);
// Set a fill value that is comprised of two integers
int32_t value_2[2] = {1, 2};
CHECK_NOTHROW(a.set_fill_value(value_2, sizeof(value_2)));
// Get the new value back
CHECK_NOTHROW(a.get_fill_value(&value_ptr, &value_size));
CHECK(((const int32_t*)value_ptr)[0] == 1);
CHECK(((const int32_t*)value_ptr)[1] == 2);
CHECK(value_size == 2 * sizeof(int32_t));
// Check dump
dump = std::string("### Attribute ###\n") + "- Name: a\n" +
"- Type: INT32\n" + "- Cell val num: 2\n" + "- Filters: 0\n" +
"- Fill value: 1, 2\n";
check_dump(a, dump);
// Make the attribute var-sized
CHECK_NOTHROW(a.set_cell_val_num(TILEDB_VAR_NUM));
// Check dump
dump = std::string("### Attribute ###\n") + "- Name: a\n" +
"- Type: INT32\n" + "- Cell val num: var\n" + "- Filters: 0\n" +
"- Fill value: -2147483648\n";
check_dump(a, dump);
// Get the default var-sized fill value
CHECK_NOTHROW(a.get_fill_value(&value_ptr, &value_size));
CHECK(*(const int32_t*)value_ptr == -2147483648);
CHECK(value_size == sizeof(int32_t));
// Set a new fill value for the var-sized attribute
int32_t value_3[3] = {1, 2, 3};
CHECK_NOTHROW(a.set_fill_value(value_3, sizeof(value_3)));
// Get the new fill value
CHECK_NOTHROW(a.get_fill_value(&value_ptr, &value_size));
CHECK(((const int32_t*)value_ptr)[0] == 1);
CHECK(((const int32_t*)value_ptr)[1] == 2);
CHECK(((const int32_t*)value_ptr)[2] == 3);
CHECK(value_size == 3 * sizeof(int32_t));
// Check dump
dump = std::string("### Attribute ###\n") + "- Name: a\n" +
"- Type: INT32\n" + "- Cell val num: var\n" + "- Filters: 0\n" +
"- Fill value: 1, 2, 3\n";
check_dump(a, dump);
}
TEST_CASE(
"C++ API: Test fill values, partial array",
"[cppapi][fill-values][partial]") {
Context ctx;
VFS vfs(ctx);
std::string array_name = "fill_values_partial";
// First test with default fill values
if (vfs.is_dir(array_name))
CHECK_NOTHROW(vfs.remove_dir(array_name));
create_array_1d(array_name);
write_array_1d_partial(array_name);
read_array_1d_partial(array_name);
CHECK_NOTHROW(vfs.remove_dir(array_name));
std::string s("abc");
create_array_1d(array_name, 0, s, {1.0, 2.0});
write_array_1d_partial(array_name);
read_array_1d_partial(array_name, 0, s, {1.0, 2.0});
CHECK_NOTHROW(vfs.remove_dir(array_name));
}
TEST_CASE(
"C++ API: Test fill values, empty array", "[cppapi][fill-values][empty]") {
Context ctx;
VFS vfs(ctx);
std::string array_name = "fill_values_empty";
// First test with default fill values
if (vfs.is_dir(array_name))
CHECK_NOTHROW(vfs.remove_dir(array_name));
create_array_1d(array_name);
read_array_1d_empty(array_name);
CHECK_NOTHROW(vfs.remove_dir(array_name));
std::string s("abc");
create_array_1d(array_name, 0, s, {1.0, 2.0});
read_array_1d_empty(array_name, 0, s, {1.0, 2.0});
CHECK_NOTHROW(vfs.remove_dir(array_name));
} | 32.590909 | 80 | 0.649848 | [
"vector"
] |
cbd7944def8a876fd3589d050d8f4a865ab19d74 | 6,174 | cc | C++ | src/rocksdb2/utilities/column_aware_encoding_exp.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 5 | 2019-01-23T04:36:03.000Z | 2020-02-04T07:10:39.000Z | src/rocksdb2/utilities/column_aware_encoding_exp.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | null | null | null | src/rocksdb2/utilities/column_aware_encoding_exp.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 2 | 2019-05-14T07:26:59.000Z | 2020-06-15T07:25:01.000Z |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2011至今,Facebook,Inc.保留所有权利。
//此源代码在两个gplv2下都获得了许可(在
//复制根目录中的文件)和Apache2.0许可证
//(在根目录的license.apache文件中找到)。
//
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <cstdio>
#include <cstdlib>
#ifndef ROCKSDB_LITE
#ifdef GFLAGS
#include <gflags/gflags.h>
#include <inttypes.h>
#include <vector>
#include "rocksdb/env.h"
#include "rocksdb/options.h"
#include "table/block_based_table_builder.h"
#include "table/block_based_table_reader.h"
#include "table/format.h"
#include "tools/sst_dump_tool_imp.h"
#include "util/compression.h"
#include "util/stop_watch.h"
#include "utilities/col_buf_encoder.h"
#include "utilities/column_aware_encoding_util.h"
using GFLAGS::ParseCommandLineFlags;
DEFINE_string(encoded_file, "", "file to store encoded data blocks");
DEFINE_string(decoded_file, "",
"file to store decoded data blocks after encoding");
DEFINE_string(format, "col", "Output Format. Can be 'row' or 'col'");
//TODO(JHLI):选项“col”应删除并替换为“general”
//柱规格。
DEFINE_string(index_type, "col", "Index type. Can be 'primary' or 'secondary'");
DEFINE_string(dump_file, "",
"Dump data blocks separated by columns in human-readable format");
DEFINE_bool(decode, false, "Deocde blocks after they are encoded");
DEFINE_bool(stat, false,
"Print column distribution statistics. Cannot decode in this mode");
DEFINE_string(compression_type, "kNoCompression",
"The compression algorithm used to compress data blocks");
namespace rocksdb {
class ColumnAwareEncodingExp {
public:
static void Run(const std::string& sst_file) {
bool decode = FLAGS_decode;
if (FLAGS_decoded_file.size() > 0) {
decode = true;
}
if (FLAGS_stat) {
decode = false;
}
ColumnAwareEncodingReader reader(sst_file);
std::vector<ColDeclaration>* key_col_declarations;
std::vector<ColDeclaration>* value_col_declarations;
ColDeclaration* value_checksum_declaration;
if (FLAGS_index_type == "primary") {
ColumnAwareEncodingReader::GetColDeclarationsPrimary(
&key_col_declarations, &value_col_declarations,
&value_checksum_declaration);
} else {
ColumnAwareEncodingReader::GetColDeclarationsSecondary(
&key_col_declarations, &value_col_declarations,
&value_checksum_declaration);
}
KVPairColDeclarations kvp_cd(key_col_declarations, value_col_declarations,
value_checksum_declaration);
if (!FLAGS_dump_file.empty()) {
std::vector<KVPairBlock> kv_pair_blocks;
reader.GetKVPairsFromDataBlocks(&kv_pair_blocks);
reader.DumpDataColumns(FLAGS_dump_file, kvp_cd, kv_pair_blocks);
return;
}
std::unordered_map<std::string, CompressionType> compressions = {
{"kNoCompression", CompressionType::kNoCompression},
{"kZlibCompression", CompressionType::kZlibCompression},
{"kZSTD", CompressionType::kZSTD}};
//查找压缩
CompressionType compression_type = compressions[FLAGS_compression_type];
EnvOptions env_options;
if (CompressionTypeSupported(compression_type)) {
fprintf(stdout, "[%s]\n", FLAGS_compression_type.c_str());
unique_ptr<WritableFile> encoded_out_file;
std::unique_ptr<Env> env(NewMemEnv(Env::Default()));
if (!FLAGS_encoded_file.empty()) {
env->NewWritableFile(FLAGS_encoded_file, &encoded_out_file,
env_options);
}
std::vector<KVPairBlock> kv_pair_blocks;
reader.GetKVPairsFromDataBlocks(&kv_pair_blocks);
std::vector<std::string> encoded_blocks;
StopWatchNano sw(env.get(), true);
if (FLAGS_format == "col") {
reader.EncodeBlocks(kvp_cd, encoded_out_file.get(), compression_type,
kv_pair_blocks, &encoded_blocks, FLAGS_stat);
} else { //行格式
reader.EncodeBlocksToRowFormat(encoded_out_file.get(), compression_type,
kv_pair_blocks, &encoded_blocks);
}
if (encoded_out_file != nullptr) {
uint64_t size = 0;
env->GetFileSize(FLAGS_encoded_file, &size);
fprintf(stdout, "File size: %" PRIu64 "\n", size);
}
/*t64_t编码_time=sw.elapsednanossafe(false/*重置*/);
fprintf(stdout,“编码时间%”priu64“\n”,编码时间);
如果(译码){
唯一的_ptr<writablefile>decoded_out_file;
如果(!)标记_解码_file.empty())
env->newwritablefile(flags_decoded_file,&decoded_out_file,
Env期权);
}
SW()
if(flags_format==“col”)
reader.decodeblocks(kvp_cd,decoded_out_file.get(),&encoded_blocks);
}否则{
reader.decodeBlocksFromRowFormat(decoded_out_file.get(),
&encoded_块);
}
uint64解码时间=sw.elapsednanossafe(真/*重置*/);
fprintf(stdout, "Decode time: %" PRIu64 "\n", decode_time);
}
} else {
fprintf(stdout, "Unsupported compression type: %s.\n",
FLAGS_compression_type.c_str());
}
delete key_col_declarations;
delete value_col_declarations;
delete value_checksum_declaration;
}
};
} //命名空间rocksdb
int main(int argc, char** argv) {
int arg_idx = ParseCommandLineFlags(&argc, &argv, true);
if (arg_idx >= argc) {
fprintf(stdout, "SST filename required.\n");
exit(1);
}
std::string sst_file(argv[arg_idx]);
if (FLAGS_format != "row" && FLAGS_format != "col") {
fprintf(stderr, "Format must be 'row' or 'col'\n");
exit(1);
}
if (FLAGS_index_type != "primary" && FLAGS_index_type != "secondary") {
fprintf(stderr, "Format must be 'primary' or 'secondary'\n");
exit(1);
}
rocksdb::ColumnAwareEncodingExp::Run(sst_file);
return 0;
}
#else
int main() {
fprintf(stderr, "Please install gflags to run rocksdb tools\n");
return 1;
}
#endif //GFLAGS
#else
int main(int argc, char** argv) {
fprintf(stderr, "Not supported in lite mode.\n");
return 1;
}
#endif //摇滚乐
| 33.193548 | 80 | 0.674603 | [
"vector"
] |
cbd7e303df914834eb145c19d4f0816d4d542e80 | 911 | cpp | C++ | 27. LeetCode Problems/2034. Stock Price Fluctuation.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 225 | 2021-10-01T03:09:01.000Z | 2022-03-11T11:32:49.000Z | 27. LeetCode Problems/2034. Stock Price Fluctuation.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 252 | 2021-10-01T03:45:20.000Z | 2021-12-07T18:32:46.000Z | 27. LeetCode Problems/2034. Stock Price Fluctuation.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 911 | 2021-10-01T02:55:19.000Z | 2022-02-06T09:08:37.000Z | class StockPrice {
public:
map<int,int>mp;
multiset<int>ms;
StockPrice() {
}
void update(int timestamp, int price) {
if(mp.find(timestamp)!=mp.end())
{
auto it=ms.find(mp[timestamp]);
ms.erase(it);
}
mp[timestamp]=price;
ms.insert(price);
}
int current() {
auto it=mp.end();
it--;
return it->second;
}
int maximum() {
auto it=ms.end();
it--;
return *it;
}
int minimum() {
auto it=ms.begin();
// it--;
return *it;
}
};
/**
* Your StockPrice object will be instantiated and called as such:
* StockPrice* obj = new StockPrice();
* obj->update(timestamp,price);
* int param_2 = obj->current();
* int param_3 = obj->maximum();
* int param_4 = obj->minimum();
*/ | 20.704545 | 67 | 0.473106 | [
"object"
] |
cbe016a748ebf1eca1c8f542bb87c31d004f4466 | 12,162 | cpp | C++ | 01_Develop/libXMGraphics/Source/XMGMatrix.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMGraphics/Source/XMGMatrix.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMGraphics/Source/XMGMatrix.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /*
*
* File XMGMatrix.cpp
* Description Matrix implemation
* Version 0.20.0801, 2011-08-01
* Author Y.H Mun
*
* --------------------------------------------------------------------------
*
* Copyright (C) 2010-2011 XMSoft. All rights reserved.
*
* Contact Email: chris@xmsoft.co.kr
* xmsoft77@gmail.com
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
*/
#include "XMGLibrary.h"
XMGMatrix4F::XMGMatrix4F ( void )
{
Identity ( );
}
XMGMatrix4F::XMGMatrix4F ( const XMGMatrix4X& mat )
{
*this = mat;
}
XMGMatrix4F& XMGMatrix4F::Identity ( void )
{
m_m[ 0] = 1.f; m_m[ 1] = 0; m_m[ 2] = 0; m_m[ 3] = 0;
m_m[ 4] = 0; m_m[ 5] = 1.f; m_m[ 6] = 0; m_m[ 7] = 0;
m_m[ 8] = 0; m_m[ 9] = 0; m_m[10] = 1.f; m_m[11] = 0;
m_m[12] = 0; m_m[13] = 0; m_m[14] = 0; m_m[15] = 1.f;
return *this;
}
XMGMatrix4F& XMGMatrix4F::Translate ( GLfloat x, GLfloat y, GLfloat z )
{
XMGMatrix4F mat;
mat.m_m[12] = x;
mat.m_m[13] = y;
mat.m_m[14] = z;
return *this = mat * *this;
}
XMGMatrix4F& XMGMatrix4F::Scale ( GLfloat x, GLfloat y, GLfloat z )
{
XMGMatrix4F mat;
mat.m_m[ 0] = x;
mat.m_m[ 5] = y;
mat.m_m[10] = z;
return *this = mat * *this;
}
XMGMatrix4F& XMGMatrix4F::Rotate ( GLfloat angle, GLfloat x, GLfloat y, GLfloat z )
{
XMGMatrix4F mat;
GLfloat s = kdSinf ( XMG_DEG2RAD ( angle ) );
GLfloat c = kdCosf ( XMG_DEG2RAD ( angle ) );
GLfloat l = kdSqrtf ( x * x + y * y + z * z );
GLfloat ux = x / l;
GLfloat uy = y / l;
GLfloat uz = z / l;
GLfloat c1 = 1 - c;
mat.m_m[ 0] = ux * ux * c1 + c;
mat.m_m[ 1] = uy * ux * c1 + uz * s;
mat.m_m[ 2] = ux * uz * c1 - uy * s;
mat.m_m[ 4] = ux * uy * c1 - uz * s;
mat.m_m[ 5] = uy * uy * c1 + c;
mat.m_m[ 6] = uy * uz * c1 + ux * s;
mat.m_m[ 8] = ux * uz * c1 + uy * s;
mat.m_m[ 9] = uy * uz * c1 - ux * s;
mat.m_m[10] = uz * uz * c1 + c;
return *this = mat * *this;
}
XMGMatrix4F& XMGMatrix4F::Ortho ( GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat znear, GLfloat zfar )
{
m_m[ 0] = 2.f / ( right - left );
m_m[ 1] = 0;
m_m[ 2] = 0;
m_m[ 3] = 0;
m_m[ 4] = 0;
m_m[ 5] = 2.f / ( top - bottom );
m_m[ 6] = 0;
m_m[ 7] = 0;
m_m[ 8] = 0;
m_m[ 9] = 0;
m_m[10] = -2.f / ( zfar - znear );
m_m[11] = 0;
m_m[12] = -( right + left ) / ( right - left );
m_m[13] = -( top + bottom ) / ( top - bottom );
m_m[14] = -( zfar + znear ) / ( zfar - znear );
m_m[15] = 1.f;
return *this;
}
XMGMatrix4F& XMGMatrix4F::Frustum ( GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat znear, GLfloat zfar )
{
m_m[ 0] = 2.f * znear / ( right - left );
m_m[ 1] = 0;
m_m[ 2] = 0;
m_m[ 3] = 0;
m_m[ 4] = 0;
m_m[ 5] = 2.f * znear / ( top - bottom );
m_m[ 6] = 0;
m_m[ 7] = 0;
m_m[ 8] = ( right + left ) / ( right - left );
m_m[ 9] = ( top + bottom ) / ( top - bottom );
m_m[10] = ( -zfar - znear ) / ( zfar - znear );
m_m[11] = -1.f;
m_m[12] = 0;
m_m[13] = 0;
m_m[14] = ( -( 2.f * znear) * zfar ) / ( zfar - znear );
m_m[15] = 0;
return *this;
}
XMGMatrix4F& XMGMatrix4F::Perspective ( GLfloat fovy, GLfloat aspect, GLfloat znear, GLfloat zfar )
{
GLfloat h = 2.0f * znear * kdTanf ( XMG_DEG2RAD ( fovy ) * 0.5f );
GLfloat w = aspect * h;
GLfloat h2 = h * 0.5f;
GLfloat w2 = w * 0.5f;
Frustum ( -w2, w2, -h2, h2, znear, zfar );
return *this;
}
XMGVector3F XMGMatrix4F::Transform ( const XMGVector3F& vec ) const
{
XMGVector3F ret;
ret.m_x = vec.m_x * m_m[0] + vec.m_y * m_m[4] + vec.m_z * m_m[8];
ret.m_y = vec.m_x * m_m[1] + vec.m_y * m_m[5] + vec.m_z * m_m[9];
ret.m_z = vec.m_x * m_m[2] + vec.m_y * m_m[6] + vec.m_z * m_m[10];
return ret;
}
XMGMatrix4F& XMGMatrix4F::operator = ( const XMGMatrix4X& mat )
{
m_m[ 0] = XMG_X2F ( mat.m_m[ 0] ); m_m[ 1] = XMG_X2F ( mat.m_m[ 1] ); m_m[ 2] = XMG_X2F ( mat.m_m[ 2] ); m_m[ 3] = XMG_X2F ( mat.m_m[ 3] );
m_m[ 4] = XMG_X2F ( mat.m_m[ 4] ); m_m[ 5] = XMG_X2F ( mat.m_m[ 5] ); m_m[ 6] = XMG_X2F ( mat.m_m[ 6] ); m_m[ 7] = XMG_X2F ( mat.m_m[ 7] );
m_m[ 8] = XMG_X2F ( mat.m_m[ 8] ); m_m[ 9] = XMG_X2F ( mat.m_m[ 9] ); m_m[10] = XMG_X2F ( mat.m_m[10] ); m_m[11] = XMG_X2F ( mat.m_m[11] );
m_m[12] = XMG_X2F ( mat.m_m[12] ); m_m[13] = XMG_X2F ( mat.m_m[13] ); m_m[14] = XMG_X2F ( mat.m_m[14] ); m_m[15] = XMG_X2F ( mat.m_m[15] );
return *this;
}
XMGMatrix4F XMGMatrix4F::operator * ( const XMGMatrix4F& mat )
{
XMGMatrix4F ret;
ret.m_m[ 0] = m_m[ 0] * mat.m_m[ 0] + m_m[ 1] * mat.m_m[ 4] + m_m[ 2] * mat.m_m[ 8] + m_m[ 3] * mat.m_m[12];
ret.m_m[ 1] = m_m[ 0] * mat.m_m[ 1] + m_m[ 1] * mat.m_m[ 5] + m_m[ 2] * mat.m_m[ 9] + m_m[ 3] * mat.m_m[13];
ret.m_m[ 2] = m_m[ 0] * mat.m_m[ 2] + m_m[ 1] * mat.m_m[ 6] + m_m[ 2] * mat.m_m[10] + m_m[ 3] * mat.m_m[14];
ret.m_m[ 3] = m_m[ 0] * mat.m_m[ 3] + m_m[ 1] * mat.m_m[ 7] + m_m[ 2] * mat.m_m[11] + m_m[ 3] * mat.m_m[15];
ret.m_m[ 4] = m_m[ 4] * mat.m_m[ 0] + m_m[ 5] * mat.m_m[ 4] + m_m[ 6] * mat.m_m[ 8] + m_m[ 7] * mat.m_m[12];
ret.m_m[ 5] = m_m[ 4] * mat.m_m[ 1] + m_m[ 5] * mat.m_m[ 5] + m_m[ 6] * mat.m_m[ 9] + m_m[ 7] * mat.m_m[13];
ret.m_m[ 6] = m_m[ 4] * mat.m_m[ 2] + m_m[ 5] * mat.m_m[ 6] + m_m[ 6] * mat.m_m[10] + m_m[ 7] * mat.m_m[14];
ret.m_m[ 7] = m_m[ 4] * mat.m_m[ 3] + m_m[ 5] * mat.m_m[ 7] + m_m[ 6] * mat.m_m[11] + m_m[ 7] * mat.m_m[15];
ret.m_m[ 8] = m_m[ 8] * mat.m_m[ 0] + m_m[ 9] * mat.m_m[ 4] + m_m[10] * mat.m_m[ 8] + m_m[11] * mat.m_m[12];
ret.m_m[ 9] = m_m[ 8] * mat.m_m[ 1] + m_m[ 9] * mat.m_m[ 5] + m_m[10] * mat.m_m[ 9] + m_m[11] * mat.m_m[13];
ret.m_m[10] = m_m[ 8] * mat.m_m[ 2] + m_m[ 9] * mat.m_m[ 6] + m_m[10] * mat.m_m[10] + m_m[11] * mat.m_m[14];
ret.m_m[11] = m_m[ 8] * mat.m_m[ 3] + m_m[ 9] * mat.m_m[ 7] + m_m[10] * mat.m_m[11] + m_m[11] * mat.m_m[15];
ret.m_m[12] = m_m[12] * mat.m_m[ 0] + m_m[13] * mat.m_m[ 4] + m_m[14] * mat.m_m[ 8] + m_m[15] * mat.m_m[12];
ret.m_m[13] = m_m[12] * mat.m_m[ 1] + m_m[13] * mat.m_m[ 5] + m_m[14] * mat.m_m[ 9] + m_m[15] * mat.m_m[13];
ret.m_m[14] = m_m[12] * mat.m_m[ 2] + m_m[13] * mat.m_m[ 6] + m_m[14] * mat.m_m[10] + m_m[15] * mat.m_m[14];
ret.m_m[15] = m_m[12] * mat.m_m[ 3] + m_m[13] * mat.m_m[ 7] + m_m[14] * mat.m_m[11] + m_m[15] * mat.m_m[15];
return ret;
}
XMGMatrix4F& XMGMatrix4F::operator *= ( const XMGMatrix4F& mat )
{
return *this = *this * mat;
}
XMGMatrix4X::XMGMatrix4X ( void )
{
Identity ( );
}
XMGMatrix4X::XMGMatrix4X ( const XMGMatrix4F& mat )
{
*this = mat;
}
XMGMatrix4X& XMGMatrix4X::Identity ( void )
{
m_m[ 0] = 65536; m_m[ 1] = 0; m_m[ 2] = 0; m_m[ 3] = 0;
m_m[ 4] = 0; m_m[ 5] = 65536; m_m[ 6] = 0; m_m[ 7] = 0;
m_m[ 8] = 0; m_m[ 9] = 0; m_m[10] = 65536; m_m[11] = 0;
m_m[12] = 0; m_m[13] = 0; m_m[14] = 0; m_m[15] = 65536;
return *this;
}
XMGMatrix4X& XMGMatrix4X::Translate ( GLfixed x, GLfixed y, GLfixed z )
{
XMGMatrix4X mat;
mat.m_m[12] = x;
mat.m_m[13] = y;
mat.m_m[14] = z;
return *this = mat * *this;
}
XMGMatrix4X& XMGMatrix4X::Scale ( GLfixed x, GLfixed y, GLfixed z )
{
XMGMatrix4X mat;
mat.m_m[ 0] = x;
mat.m_m[ 5] = y;
mat.m_m[10] = z;
return *this = mat * *this;
}
XMGMatrix4X& XMGMatrix4X::Rotate ( GLfixed angle, GLfixed x, GLfixed y, GLfixed z )
{
XMGMatrix4X mat;
GLfloat s = kdSinf ( XMG_DEG2RAD ( XMG_X2F ( angle ) ) );
GLfloat c = kdCosf ( XMG_DEG2RAD ( XMG_X2F ( angle ) ) );
GLfloat fx = XMG_X2F ( x );
GLfloat fy = XMG_X2F ( y );
GLfloat fz = XMG_X2F ( z );
GLfloat fl = kdSqrtf ( fx * fx + fy * fy + fz * fz );
GLfloat ux = fx / fl;
GLfloat uy = fy / fl;
GLfloat uz = fz / fl;
GLfloat c1 = 1 - c;
mat.m_m[ 0] = XMG_F2X ( ux * ux * c1 + c );
mat.m_m[ 1] = XMG_F2X ( uy * ux * c1 + uz * s );
mat.m_m[ 2] = XMG_F2X ( ux * uz * c1 - uy * s );
mat.m_m[ 4] = XMG_F2X ( ux * uy * c1 - uz * s );
mat.m_m[ 5] = XMG_F2X ( uy * uy * c1 + c );
mat.m_m[ 6] = XMG_F2X ( uy * uz * c1 + ux * s );
mat.m_m[ 8] = XMG_F2X ( ux * uz * c1 + uy * s );
mat.m_m[ 9] = XMG_F2X ( uy * uz * c1 - ux * s );
mat.m_m[10] = XMG_F2X ( uz * uz * c1 + c );
return *this = mat * *this;
}
XMGMatrix4X& XMGMatrix4X::Ortho ( GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed znear, GLfixed zfar )
{
m_m[ 0] = XMG_F2X ( 2.f / XMG_X2F ( right - left ) );
m_m[ 1] = 0;
m_m[ 2] = 0;
m_m[ 3] = 0;
m_m[ 4] = 0;
m_m[ 5] = XMG_F2X ( 2.f / XMG_X2F ( top - bottom ) );
m_m[ 6] = 0;
m_m[ 7] = 0;
m_m[ 8] = 0;
m_m[ 9] = 0;
m_m[10] = XMG_F2X ( -2.f / XMG_X2F ( zfar - znear ) );
m_m[11] = 0;
m_m[12] = XMG_F2X ( -XMG_X2F ( right + left ) / XMG_X2F ( right - left ) );
m_m[13] = XMG_F2X ( -XMG_X2F ( top + bottom ) / XMG_X2F ( top - bottom ) );
m_m[14] = XMG_F2X ( -XMG_X2F ( zfar + znear ) / XMG_X2F ( zfar - znear ) );
m_m[15] = 65536;
return *this;
}
XMGMatrix4X& XMGMatrix4X::Frustum ( GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed znear, GLfixed zfar )
{
m_m[ 0] = XMG_F2X ( 2.f * XMG_X2F ( znear ) / XMG_X2F ( right - left ) );
m_m[ 1] = 0;
m_m[ 2] = 0;
m_m[ 3] = 0;
m_m[ 4] = 0;
m_m[ 5] = XMG_F2X ( 2.f * XMG_X2F ( znear ) / XMG_X2F ( top - bottom ) );
m_m[ 6] = 0;
m_m[ 7] = 0;
m_m[ 8] = XMG_F2X ( XMG_X2F ( right + left ) / XMG_X2F ( right - left ) );
m_m[ 9] = XMG_F2X ( XMG_X2F ( top + bottom ) / XMG_X2F ( top - bottom ) );
m_m[10] = XMG_F2X ( XMG_X2F ( -zfar - znear ) / XMG_X2F ( zfar - znear ) );
m_m[11] = -65536;
m_m[12] = 0;
m_m[13] = 0;
m_m[14] = XMG_F2X ( ( -( 2.f * XMG_X2F ( znear ) ) * XMG_X2F ( zfar ) ) / XMG_X2F ( zfar - znear ) );
m_m[15] = 0;
return *this;
}
XMGMatrix4X& XMGMatrix4X::Perspective ( GLfixed fovy, GLfixed aspect, GLfixed znear, GLfixed zfar )
{
GLfloat fh = 2.0f * XMG_X2F ( znear ) * kdTanf ( XMG_DEG2RAD ( XMG_X2F ( fovy ) ) * 0.5f );
GLfloat fw = XMG_X2F ( aspect ) * fh;
GLfixed xh2 = XMG_F2X ( fh * 0.5f );
GLfixed xw2 = XMG_F2X ( fw * 0.5f );
Frustum ( -xw2, xw2, -xh2, xh2, znear, zfar );
return *this;
}
XMGVector3X XMGMatrix4X::Transform ( const XMGVector3X& vec ) const
{
XMGVector3X ret;
ret.m_x = XMG_F2X ( XMG_X2F ( vec.m_x ) * XMG_X2F ( m_m[0] ) + XMG_X2F ( vec.m_y ) * XMG_X2F ( m_m[4] ) + XMG_X2F ( vec.m_z ) * XMG_X2F ( m_m[ 8] ) );
ret.m_y = XMG_F2X ( XMG_X2F ( vec.m_x ) * XMG_X2F ( m_m[1] ) + XMG_X2F ( vec.m_y ) * XMG_X2F ( m_m[5] ) + XMG_X2F ( vec.m_z ) * XMG_X2F ( m_m[ 9] ) );
ret.m_z = XMG_F2X ( XMG_X2F ( vec.m_x ) * XMG_X2F ( m_m[2] ) + XMG_X2F ( vec.m_y ) * XMG_X2F ( m_m[6] ) + XMG_X2F ( vec.m_z ) * XMG_X2F ( m_m[10] ) );
return ret;
}
XMGMatrix4X& XMGMatrix4X::operator = ( const XMGMatrix4F& mat )
{
m_m[ 0] = XMG_F2X ( mat.m_m[ 0] ); m_m[ 1] = XMG_F2X ( mat.m_m[ 1] ); m_m[ 2] = XMG_F2X ( mat.m_m[ 2] ); m_m[ 3] = XMG_F2X ( mat.m_m[ 3] );
m_m[ 4] = XMG_F2X ( mat.m_m[ 4] ); m_m[ 5] = XMG_F2X ( mat.m_m[ 5] ); m_m[ 6] = XMG_F2X ( mat.m_m[ 6] ); m_m[ 7] = XMG_F2X ( mat.m_m[ 7] );
m_m[ 8] = XMG_F2X ( mat.m_m[ 8] ); m_m[ 9] = XMG_F2X ( mat.m_m[ 9] ); m_m[10] = XMG_F2X ( mat.m_m[10] ); m_m[11] = XMG_F2X ( mat.m_m[11] );
m_m[12] = XMG_F2X ( mat.m_m[12] ); m_m[13] = XMG_F2X ( mat.m_m[13] ); m_m[14] = XMG_F2X ( mat.m_m[14] ); m_m[15] = XMG_F2X ( mat.m_m[15] );
return *this;
}
XMGMatrix4X XMGMatrix4X::operator * ( const XMGMatrix4X& mat )
{
return XMGMatrix4F ( *this ) * XMGMatrix4F ( mat );
}
XMGMatrix4X& XMGMatrix4X::operator *= ( const XMGMatrix4X& mat )
{
return *this = *this * mat;
} | 31.837696 | 154 | 0.551883 | [
"transform"
] |
cbe08b72496dbd8eea60250e015678087abe872c | 710 | hpp | C++ | NEFT/include/NEFT/nn.hpp | leopnt/NEFT | bae0dc858a53809dd4ee59a7b4fe78ac5b8e3cf2 | [
"MIT"
] | null | null | null | NEFT/include/NEFT/nn.hpp | leopnt/NEFT | bae0dc858a53809dd4ee59a7b4fe78ac5b8e3cf2 | [
"MIT"
] | null | null | null | NEFT/include/NEFT/nn.hpp | leopnt/NEFT | bae0dc858a53809dd4ee59a7b4fe78ac5b8e3cf2 | [
"MIT"
] | null | null | null | #ifndef NN_HPP
#define NN_HPP
#include <cmath>
#include "layer.hpp"
class NN
{
private:
int m_inputSize;
int m_outputSize;
std::vector<Layer> m_layers;
public:
NN(const int& inputSize, const int& outputSize);
~NN();
void addLayer(const int& inputSize);
void randomize(const float& min, const float& max);
std::vector<float> output(const std::vector<float>& input) const;
std::vector<float> getWeights() const;
void setWeights(const std::vector<float>& weights);
int size() const;
static void activate(std::vector<float>& arr);
friend std::ostream& operator<<(std::ostream& out, const NN& self);
};
#endif
| 19.189189 | 72 | 0.629577 | [
"vector"
] |
cbe37535e742b2a6b320b5c3f6b855b3b19abcbe | 3,597 | cc | C++ | src/reader/wgsl/parser_impl_param_list_test.cc | jhanssen/tint | 30c1f25a7a4e180419444c12046348edb0f8fdd0 | [
"Apache-2.0"
] | null | null | null | src/reader/wgsl/parser_impl_param_list_test.cc | jhanssen/tint | 30c1f25a7a4e180419444c12046348edb0f8fdd0 | [
"Apache-2.0"
] | null | null | null | src/reader/wgsl/parser_impl_param_list_test.cc | jhanssen/tint | 30c1f25a7a4e180419444c12046348edb0f8fdd0 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include "gtest/gtest.h"
#include "src/ast/variable.h"
#include "src/reader/wgsl/parser_impl.h"
#include "src/reader/wgsl/parser_impl_test_helper.h"
#include "src/type/f32_type.h"
#include "src/type/i32_type.h"
#include "src/type/vector_type.h"
namespace tint {
namespace reader {
namespace wgsl {
namespace {
TEST_F(ParserImplTest, ParamList_Single) {
auto p = parser("a : i32");
auto* i32 = p->builder().create<type::I32>();
auto e = p->expect_param_list();
ASSERT_FALSE(p->has_error()) << p->error();
ASSERT_FALSE(e.errored);
EXPECT_EQ(e.value.size(), 1u);
EXPECT_EQ(e.value[0]->symbol(), p->builder().Symbols().Get("a"));
EXPECT_EQ(e.value[0]->type(), i32);
EXPECT_TRUE(e.value[0]->is_const());
ASSERT_EQ(e.value[0]->source().range.begin.line, 1u);
ASSERT_EQ(e.value[0]->source().range.begin.column, 1u);
ASSERT_EQ(e.value[0]->source().range.end.line, 1u);
ASSERT_EQ(e.value[0]->source().range.end.column, 2u);
}
TEST_F(ParserImplTest, ParamList_Multiple) {
auto p = parser("a : i32, b: f32, c: vec2<f32>");
auto* i32 = p->builder().create<type::I32>();
auto* f32 = p->builder().create<type::F32>();
auto* vec2 = p->builder().create<type::Vector>(f32, 2);
auto e = p->expect_param_list();
ASSERT_FALSE(p->has_error()) << p->error();
ASSERT_FALSE(e.errored);
EXPECT_EQ(e.value.size(), 3u);
EXPECT_EQ(e.value[0]->symbol(), p->builder().Symbols().Get("a"));
EXPECT_EQ(e.value[0]->type(), i32);
EXPECT_TRUE(e.value[0]->is_const());
ASSERT_EQ(e.value[0]->source().range.begin.line, 1u);
ASSERT_EQ(e.value[0]->source().range.begin.column, 1u);
ASSERT_EQ(e.value[0]->source().range.end.line, 1u);
ASSERT_EQ(e.value[0]->source().range.end.column, 2u);
EXPECT_EQ(e.value[1]->symbol(), p->builder().Symbols().Get("b"));
EXPECT_EQ(e.value[1]->type(), f32);
EXPECT_TRUE(e.value[1]->is_const());
ASSERT_EQ(e.value[1]->source().range.begin.line, 1u);
ASSERT_EQ(e.value[1]->source().range.begin.column, 10u);
ASSERT_EQ(e.value[1]->source().range.end.line, 1u);
ASSERT_EQ(e.value[1]->source().range.end.column, 11u);
EXPECT_EQ(e.value[2]->symbol(), p->builder().Symbols().Get("c"));
EXPECT_EQ(e.value[2]->type(), vec2);
EXPECT_TRUE(e.value[2]->is_const());
ASSERT_EQ(e.value[2]->source().range.begin.line, 1u);
ASSERT_EQ(e.value[2]->source().range.begin.column, 18u);
ASSERT_EQ(e.value[2]->source().range.end.line, 1u);
ASSERT_EQ(e.value[2]->source().range.end.column, 19u);
}
TEST_F(ParserImplTest, ParamList_Empty) {
auto p = parser("");
auto e = p->expect_param_list();
ASSERT_FALSE(p->has_error());
ASSERT_FALSE(e.errored);
EXPECT_EQ(e.value.size(), 0u);
}
TEST_F(ParserImplTest, ParamList_HangingComma) {
auto p = parser("a : i32,");
auto e = p->expect_param_list();
ASSERT_TRUE(p->has_error());
ASSERT_TRUE(e.errored);
EXPECT_EQ(p->error(), "1:9: expected identifier for parameter");
}
} // namespace
} // namespace wgsl
} // namespace reader
} // namespace tint
| 32.7 | 75 | 0.677231 | [
"vector"
] |
cbe6b223c17f984e45ade9170f0dd31f2a298d98 | 22,539 | cpp | C++ | src/ethereum/eth_kvb_storage.cpp | MRHarrison/concord | 7d6417c09c8062111f93b3ff638c540d55e345b8 | [
"Apache-2.0"
] | null | null | null | src/ethereum/eth_kvb_storage.cpp | MRHarrison/concord | 7d6417c09c8062111f93b3ff638c540d55e345b8 | [
"Apache-2.0"
] | null | null | null | src/ethereum/eth_kvb_storage.cpp | MRHarrison/concord | 7d6417c09c8062111f93b3ff638c540d55e345b8 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Wrapper around KVB to provide EVM execution storage context. This class
// defines the mapping of EVM object to KVB address. It also records updates to
// be used in minting a block when a transaction finishes.
//
// Initializing a EthKvbStorage object without an IBlocksAppender causes it to
// operate in read-only mode. A ReadOnlyModeException will be thrown if any of
// the set/add/write functions are called on a EthKvbStorage object in read-only
// mode.
//
// To add a block, first call the set/add functions to prepare data for the
// block. When all data has been prepared, call `write_block`. After calling
// `write_block`, the staging area is cleared, and more objects can be prepared
// for a new block, if desired.
//
// After calling set/add/write, a copy of the data has been made, which is
// managed by this object. The original value passed to the set/add/write
// function can be safely destroyed or modified.
//
// KVBlockchain writes a block as a set of key-value pairs. We use the first
// byte of a key to signify the type of the value (see the `TYPE_*` constants in
// `kvb_storage.hpp`. Values are mostly Protocol Buffer encodings, defined in
// `concord_storage.proto`, with the exception being contract data (not code).
// All protobuf messages include a "version" field, so we can handle upgrades
// to storage at a later date.
//
// Storage layouts:
//
// * Block
// - Key: TYPE_BLOCK+[block hash (32 bytes)]
// - Value: com::vmware::concord::kvb::Block protobuf
// - Notes: Do not confuse this with the KVB block. This is Ethereum-level
// block information.
//
// * Transaction
// - Key: TYPE_TRANSACTION+[transaction hash (32 bytes)]
// - Value: com::vmware::concord::kvb::Transaction protobuf
//
// * Account or Contract Balance
// - Key: TYPE_BALANCE+[account/contract address (20 bytes)]
// - Value: com::vmware::concord::kvb::Balance protobuf
// - Notes: Yes, it seems a little overkill to wrap a number in a protobuf
// encoding, but this saves hassle with endian encoding.
//
// * Contract Code
// - Key: TYPE_CODE+[contract address (20 bytes)]
// - Value: com::vmware::concord::kvb::Code protobuf
//
// * Contract Data
// - Key: TYPE_STORAGE+[contract address (20 bytes)]+[location (32 bytes)]
// - Value: 32 bytes directly copied from an evmc_uint256be
// - Notes: aka "storage"
//
// * Account Nonce
// - Key: TYPE_NONCE+[account address (20 bytes)]
// - Value: com::vmware::concord::kvb::Nonce protobuf
// - Notes: As with balance, using protobuf solves encoding issues.
#include "eth_kvb_storage.hpp"
#include <cstring>
#include <vector>
#include "common/concord_exception.hpp"
#include "concord_storage.pb.h"
#include "evmjit.h"
#include "utils/concord_eth_hash.hpp"
using concord::common::BlockNotFoundException;
using concord::common::EthBlock;
using concord::common::EthTransaction;
using concord::common::EVMException;
using concord::common::ReadOnlyModeException;
using concord::common::TransactionNotFoundException;
using concord::common::zero_hash;
using concord::common::operator<<;
using concord::storage::blockchain::IBlocksAppender;
using concord::storage::blockchain::ILocalKeyValueStorageReadOnly;
using concordUtils::BlockId;
using concordUtils::SetOfKeyValuePairs;
using concordUtils::Sliver;
using concordUtils::Status;
namespace concord {
namespace ethereum {
////////////////////////////////////////
// GENERAL
/* Current storage versions. */
const int64_t balance_storage_version = 1;
const int64_t nonce_storage_version = 1;
const int64_t code_storage_version = 1;
// read-only mode
EthKvbStorage::EthKvbStorage(const ILocalKeyValueStorageReadOnly &roStorage)
: roStorage_(roStorage),
blockAppender_(nullptr),
logger(log4cplus::Logger::getInstance("com.vmware.concord.kvb")) {}
// read-write mode
EthKvbStorage::EthKvbStorage(const ILocalKeyValueStorageReadOnly &roStorage,
IBlocksAppender *blockAppender)
: roStorage_(roStorage),
blockAppender_(blockAppender),
logger(log4cplus::Logger::getInstance("com.vmware.concord.kvb")) {}
EthKvbStorage::~EthKvbStorage() {
// Any Slivers in updates will release their memory automatically.
// We don't own the blockAppender we're pointing to, so leave it alone.
}
bool EthKvbStorage::is_read_only() {
// if we don't have a blockAppender, we are read-only
auto res = blockAppender_ == nullptr;
return res;
}
/**
* Allow access to read-only storage object, to enabled downgrades to read-only
* EthKvbStorage when convenient.
*/
const ILocalKeyValueStorageReadOnly &EthKvbStorage::getReadOnlyStorage() {
return roStorage_;
}
////////////////////////////////////////
// ADDRESSING
/**
* Constructs a key: one byte of `type`, concatenated with `length` bytes of
* `bytes`.
*/
Sliver EthKvbStorage::kvb_key(uint8_t type, const uint8_t *bytes,
size_t length) const {
uint8_t *key = new uint8_t[1 + length];
key[0] = type;
std::copy(bytes, bytes + length, key + 1);
return Sliver(key, length + 1);
}
/**
* Convenience functions for constructing a key for each object type.
*/
Sliver EthKvbStorage::block_key(const EthBlock &blk) const {
return kvb_key(TYPE_BLOCK, blk.get_hash().bytes, sizeof(evmc_uint256be));
}
Sliver EthKvbStorage::block_key(const evmc_uint256be &hash) const {
return kvb_key(TYPE_BLOCK, hash.bytes, sizeof(hash));
}
Sliver EthKvbStorage::transaction_key(const EthTransaction &tx) const {
return kvb_key(TYPE_TRANSACTION, tx.hash().bytes, sizeof(evmc_uint256be));
}
Sliver EthKvbStorage::transaction_key(const evmc_uint256be &hash) const {
return kvb_key(TYPE_TRANSACTION, hash.bytes, sizeof(hash));
}
Sliver EthKvbStorage::balance_key(const evmc_address &addr) const {
return kvb_key(TYPE_BALANCE, addr.bytes, sizeof(addr));
}
Sliver EthKvbStorage::nonce_key(const evmc_address &addr) const {
return kvb_key(TYPE_NONCE, addr.bytes, sizeof(addr));
}
Sliver EthKvbStorage::code_key(const evmc_address &addr) const {
return kvb_key(TYPE_CODE, addr.bytes, sizeof(addr));
}
Sliver EthKvbStorage::storage_key(const evmc_address &addr,
const evmc_uint256be &location) const {
uint8_t combined[sizeof(addr) + sizeof(location)];
std::copy(addr.bytes, addr.bytes + sizeof(addr), combined);
std::copy(location.bytes, location.bytes + sizeof(location),
combined + sizeof(addr));
return kvb_key(TYPE_STORAGE, combined, sizeof(addr) + sizeof(location));
}
////////////////////////////////////////
// WRITING
/**
* Add a key-value pair to be stored in the block. Throws ReadOnlyModeException
* if this object is in read-only mode.
*/
void EthKvbStorage::put(const Sliver &key, const Sliver &value) {
if (!blockAppender_) {
throw ReadOnlyModeException();
}
updates[key] = value;
}
/**
* Add a block to the database, containing all of the key-value pairs that have
* been prepared. A ReadOnlyModeException will be thrown if this object is in
* read-only mode.
*/
Status EthKvbStorage::write_block(uint64_t timestamp, uint64_t gas_limit) {
if (!blockAppender_) {
throw ReadOnlyModeException();
}
// Prepare the block metadata
EthBlock blk;
blk.number = next_block_number();
if (blk.number == 0) {
blk.parent_hash = zero_hash;
} else {
EthBlock parent = get_block(blk.number - 1);
blk.parent_hash = parent.hash;
}
blk.timestamp = timestamp;
blk.gas_limit = gas_limit;
// We need hash of all transactions for calculating hash of a block
// but we also need block hash inside transaction structure (not required
// to calculate hash of that transaction). So first use transaction hash to
// get block hash and then populate that block hash & block number inside
// all transactions in that block
for (auto tx : pending_transactions) {
blk.transactions.push_back(tx.hash());
}
blk.hash = blk.get_hash();
blk.gas_used = 0;
for (auto tx : pending_transactions) {
tx.block_hash = blk.hash;
tx.block_number = blk.number;
Sliver txaddr = transaction_key(tx);
uint8_t *txser;
size_t txser_length = tx.serialize(&txser);
blk.gas_used += tx.gas_used;
put(txaddr, Sliver(txser, txser_length));
}
pending_transactions.clear();
// Create serialized versions of the objects and store them in a staging area.
add_block(blk);
// Actually write the block
BlockId outBlockId;
Status status = blockAppender_->addBlock(updates, outBlockId);
if (status.isOK()) {
LOG4CPLUS_INFO(logger, "Appended block number " << outBlockId);
} else {
LOG4CPLUS_ERROR(logger, "Failed to append block");
}
// Prepare to stage another block
reset();
return status;
}
/**
* Drop all pending updates.
*/
void EthKvbStorage::reset() {
// Slivers release their memory automatically.
updates.clear();
}
/**
* Preparation functions for each value type in a block. These creates
* serialized versions of the objects and store them in a staging area.
*/
void EthKvbStorage::add_block(EthBlock &blk) {
Sliver blkaddr = block_key(blk);
uint8_t *blkser;
size_t blkser_length = blk.serialize(&blkser);
put(blkaddr, Sliver(blkser, blkser_length));
}
void EthKvbStorage::add_transaction(EthTransaction &tx) {
// Like other add_* methods we don't serialized the transaction here. The
// reason is that block hash and block number is not known at this point
// hence we can not serialize the transaction properly. Instead we put the
// transaction in `pending_tansactions` vector for now and then in
// write_block properly fill block_number & block_hash inside each
// transaction
pending_transactions.push_back(tx);
}
void EthKvbStorage::set_balance(const evmc_address &addr,
evmc_uint256be balance) {
com::vmware::concord::kvb::Balance proto;
proto.set_version(balance_storage_version);
proto.set_balance(balance.bytes, sizeof(evmc_uint256be));
size_t sersize = proto.ByteSize();
uint8_t *ser = new uint8_t[sersize];
proto.SerializeToArray(ser, sersize);
put(balance_key(addr), Sliver(ser, sersize));
}
void EthKvbStorage::set_nonce(const evmc_address &addr, uint64_t nonce) {
com::vmware::concord::kvb::Nonce proto;
proto.set_version(nonce_storage_version);
proto.set_nonce(nonce);
size_t sersize = proto.ByteSize();
uint8_t *ser = new uint8_t[sersize];
proto.SerializeToArray(ser, sersize);
put(nonce_key(addr), Sliver(ser, sersize));
}
void EthKvbStorage::set_code(const evmc_address &addr, const uint8_t *code,
size_t code_size) {
com::vmware::concord::kvb::Code proto;
proto.set_version(code_storage_version);
proto.set_code(code, code_size);
evmc_uint256be hash = concord::utils::eth_hash::keccak_hash(code, code_size);
proto.set_hash(hash.bytes, sizeof(hash));
size_t sersize = proto.ByteSize();
uint8_t *ser = new uint8_t[sersize];
proto.SerializeToArray(ser, sersize);
put(code_key(addr), Sliver(ser, sersize));
}
void EthKvbStorage::set_storage(const evmc_address &addr,
const evmc_uint256be &location,
const evmc_uint256be &data) {
uint8_t *str = new uint8_t[sizeof(data)];
std::copy(data.bytes, data.bytes + sizeof(data), str);
put(storage_key(addr, location), Sliver(str, sizeof(data)));
}
////////////////////////////////////////
// READING
/**
* Get the number of the block that will be added when write_block is called.
*/
uint64_t EthKvbStorage::next_block_number() {
// Ethereum block number is 1+KVB block number. So, the most recent KVB block
// number is actually the next Ethereum block number.
return roStorage_.getLastBlock();
}
/**
* Get the number of the most recent block that was added.
*/
uint64_t EthKvbStorage::current_block_number() {
// Ethereum block number is 1+KVB block number. So, the most recent Ethereum
// block is one less than the most recent KVB block.
return roStorage_.getLastBlock() - 1;
}
/**
* Get a value from storage. The staging area is searched first, so that it can
* be used as a sort of current execution environment. If the key is not found
* in the staging area, its value in the most recent block in which it was
* written will be returned.
*/
Status EthKvbStorage::get(const Sliver &key, Sliver &value) {
uint64_t block_number = current_block_number();
BlockId out;
return get(block_number, key, value, out);
}
/**
* Get a value from storage. The staging area is searched first, so that it can
* be used as a sort of current execution environment. If the key is not found
* in the staging area, its value in the most recent block in which it was
* written will be returned.
* @param readVersion BlockId object signifying the read version with which a
* lookup needs to be done.
* @param key Sliver object of the key.
* @param value Sliver object where the value of the lookup result is stored.
* @param outBlock BlockId object where the read version of the result is stored
* @return
*/
Status EthKvbStorage::get(const BlockId readVersion, const Sliver &key,
Sliver &value, BlockId &outBlock) {
// TODO(BWF): this search will be very inefficient for a large set of changes
for (auto &u : updates) {
if (u.first == key) {
value = u.second;
return Status::OK();
}
}
// "1+" == KVBlockchain starts at block 1, but Ethereum starts at 0
return roStorage_.get(readVersion + 1, key, value, outBlock);
}
/**
* Fetch functions for each value type.
*/
EthBlock EthKvbStorage::get_block(uint64_t number) {
SetOfKeyValuePairs outBlockData;
// "1+" == KVBlockchain starts at block 1, but Ethereum starts at 0
Status status = roStorage_.getBlockData(1 + number, outBlockData);
LOG4CPLUS_DEBUG(logger, "Getting block number "
<< number << " status: " << status
<< " value.size: " << outBlockData.size());
if (status.isOK()) {
for (auto kvp : outBlockData) {
if (kvp.first.data()[0] == TYPE_BLOCK) {
return EthBlock::deserialize(kvp.second);
}
}
}
throw BlockNotFoundException();
}
EthBlock EthKvbStorage::get_block(const evmc_uint256be &hash) {
Sliver kvbkey = block_key(hash);
Sliver value;
Status status = get(kvbkey, value);
LOG4CPLUS_DEBUG(logger, "Getting block "
<< hash << " status: " << status << " key: "
<< kvbkey << " value.length: " << value.length());
if (status.isOK() && value.length() > 0) {
// TODO: we may store less for block, by using this part to get the number,
// then get_block(number) to rebuild the transaction list from KV pairs
return EthBlock::deserialize(value);
}
throw BlockNotFoundException();
}
EthTransaction EthKvbStorage::get_transaction(const evmc_uint256be &hash) {
Sliver kvbkey = transaction_key(hash);
Sliver value;
Status status = get(kvbkey, value);
LOG4CPLUS_DEBUG(logger, "Getting transaction "
<< hash << " status: " << status << " key: "
<< kvbkey << " value.length: " << value.length());
if (status.isOK() && value.length() > 0) {
// TODO: lookup block hash and number as well
return EthTransaction::deserialize(value);
}
throw TransactionNotFoundException();
}
evmc_uint256be EthKvbStorage::get_balance(const evmc_address &addr) {
uint64_t block_number = current_block_number();
return get_balance(addr, block_number);
}
evmc_uint256be EthKvbStorage::get_balance(const evmc_address &addr,
uint64_t &block_number) {
Sliver kvbkey = balance_key(addr);
Sliver value;
BlockId outBlock;
Status status = get(block_number, kvbkey, value, outBlock);
LOG4CPLUS_DEBUG(logger, "Getting balance "
<< addr
<< " lookup block starting at: " << block_number
<< " status: " << status << " key: " << kvbkey
<< " value.length: " << value.length()
<< " out block at: " << outBlock);
evmc_uint256be out;
if (status.isOK() && value.length() > 0) {
com::vmware::concord::kvb::Balance balance;
if (balance.ParseFromArray(value.data(), value.length())) {
if (balance.version() == balance_storage_version) {
std::copy(balance.balance().begin(), balance.balance().end(),
out.bytes);
return out;
} else {
throw EVMException("Unknown balance storage version");
}
} else {
LOG4CPLUS_ERROR(logger, "Unable to decode balance for addr " << addr);
throw EVMException("Corrupt balance storage");
}
}
// untouched accounts have a balance of 0
return evmc_uint256be{0};
}
uint64_t EthKvbStorage::get_nonce(const evmc_address &addr) {
uint64_t block_number = current_block_number();
return get_nonce(addr, block_number);
}
uint64_t EthKvbStorage::get_nonce(const evmc_address &addr,
uint64_t &block_number) {
Sliver kvbkey = nonce_key(addr);
Sliver value;
BlockId outBlock;
Status status = get(block_number, kvbkey, value, outBlock);
LOG4CPLUS_DEBUG(logger, "Getting nonce "
<< addr
<< " lookup block starting at: " << block_number
<< " status: " << status << " key: " << kvbkey
<< " value.length: " << value.length()
<< " out block at: " << outBlock);
if (status.isOK() && value.length() > 0) {
com::vmware::concord::kvb::Nonce nonce;
if (nonce.ParseFromArray(value.data(), value.length())) {
if (nonce.version() == nonce_storage_version) {
return nonce.nonce();
} else {
throw EVMException("Unknown nonce storage version");
}
}
}
// untouched accounts have a nonce of 0
return 0;
}
bool EthKvbStorage::account_exists(const evmc_address &addr) {
Sliver kvbkey = balance_key(addr);
Sliver value;
Status status = get(kvbkey, value);
LOG4CPLUS_DEBUG(logger, "Getting balance "
<< addr << " status: " << status << " key: "
<< kvbkey << " value.length: " << value.length());
if (status.isOK() && value.length() > 0) {
// if there was a balance recorded, the account exists
return true;
}
return false;
}
/**
* Code and hash will be copied to `out`, if found, and `true` will be
* returned. If no code is found, `false` is returned.
*/
bool EthKvbStorage::get_code(const evmc_address &addr,
std::vector<uint8_t> &out, evmc_uint256be &hash) {
uint64_t block_number = current_block_number();
return get_code(addr, out, hash, block_number);
}
/**
* Code and hash will be copied to `out`, if found, and `true` will be
* returned. If no code is found, `false` is returned.
* @param addr
* @param out
* @param hash
* @param block_number the starting block number for lookup,
* 'default block parameters'
* @return
*/
bool EthKvbStorage::get_code(const evmc_address &addr,
std::vector<uint8_t> &out, evmc_uint256be &hash,
uint64_t &block_number) {
Sliver kvbkey = code_key(addr);
Sliver value;
BlockId outBlock;
Status status = get(block_number, kvbkey, value, outBlock);
LOG4CPLUS_DEBUG(logger, "Getting code "
<< addr
<< " lookup block starting at: " << block_number
<< " status: " << status << " key: " << kvbkey
<< " value.length: " << value.length()
<< " out block at: " << outBlock);
if (status.isOK() && value.length() > 0) {
com::vmware::concord::kvb::Code code;
if (code.ParseFromArray(value.data(), value.length())) {
if (code.version() == code_storage_version) {
std::copy(code.code().begin(), code.code().end(),
std::back_inserter(out));
std::copy(code.hash().begin(), code.hash().end(), hash.bytes);
return true;
} else {
LOG4CPLUS_ERROR(logger,
"Unknown code storage version" << code.version());
throw EVMException("Unknown code storage version");
}
} else {
LOG4CPLUS_ERROR(logger,
"Unable to decode storage for contract at " << addr);
throw EVMException("Corrupt code storage");
}
}
return false;
}
evmc_uint256be EthKvbStorage::get_storage(const evmc_address &addr,
const evmc_uint256be &location) {
uint64_t block_number = current_block_number();
return get_storage(addr, location, block_number);
}
evmc_uint256be EthKvbStorage::get_storage(const evmc_address &addr,
const evmc_uint256be &location,
uint64_t &block_number) {
Sliver kvbkey = storage_key(addr, location);
Sliver value;
BlockId outBlock;
Status status = get(block_number, kvbkey, value, outBlock);
// (IG): when running ST tests, logs are full of this line. Changed to Debug
// level
LOG4CPLUS_DEBUG(logger, "Getting storage "
<< addr << " at " << location
<< " lookup block starting at: " << block_number
<< " status: " << status << " key: " << kvbkey
<< " value.length: " << value.length()
<< " out block at: " << outBlock);
evmc_uint256be out;
if (status.isOK() && value.length() > 0) {
if (value.length() == sizeof(evmc_uint256be)) {
std::copy(value.data(), value.data() + value.length(), out.bytes);
} else {
LOG4CPLUS_ERROR(logger, "Contract " << addr << " storage " << location
<< " only had " << value.length()
<< " bytes.");
throw EVMException("Corrupt contract storage");
}
} else {
std::memset(out.bytes, 0, sizeof(out));
}
return out;
}
} // namespace ethereum
} // namespace concord
| 34.944186 | 80 | 0.651759 | [
"object",
"vector"
] |
cbe9cddc23caaba31d42197450f5d6ce00153832 | 20,517 | hpp | C++ | simulator/include/simulator.hpp | DaoCasino/dc-blockchain | 37ac10f1165c25be4936464f3fb402653bd1c85c | [
"MIT"
] | 10 | 2019-05-06T16:15:54.000Z | 2019-06-12T05:12:18.000Z | simulator/include/simulator.hpp | DaoCasino/dc-blockchain | 37ac10f1165c25be4936464f3fb402653bd1c85c | [
"MIT"
] | 5 | 2019-10-07T13:25:39.000Z | 2020-06-18T00:06:18.000Z | simulator/include/simulator.hpp | DaoCasino/dc-blockchain | 37ac10f1165c25be4936464f3fb402653bd1c85c | [
"MIT"
] | 7 | 2019-10-04T23:02:14.000Z | 2022-02-26T14:00:05.000Z | #pragma once
#include "database.hpp"
#include "log.hpp"
#include <fc/bitutil.hpp>
#include <fc/crypto/sha256.hpp>
#include <boost/optional.hpp>
#include <algorithm>
#include <chrono>
#include <fstream>
#include <functional>
#include <iostream>
#include <numeric>
#include <queue>
#include <random>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
//---------- helpers ----------//
static std::ostream& operator<<(std::ostream& os, const block_id_type& block) {
os << block.str().substr(16, 4);
return os;
}
static std::ostream& operator<<(std::ostream& os, const fork_db_chain_type& chain) {
os << "[ " << chain.base_block;
for (const auto& block : chain.blocks) {
os << " -> " << block.first;
}
os << " ]";
return os;
}
static uint32_t get_block_height(const block_id_type& id) {
return fc::endian_reverse_u32(id._hash[0]);
}
static inline auto get_priv_key() {
return fc::crypto::private_key::generate();
}
//---------- types ----------//
enum class node_type_t { BP, FN };
using node_types_t = std::vector<node_type_t>;
class Clock {
public:
Clock() : now_{0} {}
explicit Clock(uint32_t now) : now_{now} {}
uint32_t now() const {
return now_;
}
void set(uint32_t now) {
now_ = now;
}
void update(uint32_t delta) {
now_ += delta;
}
private:
uint32_t now_;
};
class TestRunner;
class Node;
using NodePtr = std::shared_ptr<Node>;
struct Task {
uint32_t from;
uint32_t to;
uint32_t at;
std::function<void(NodePtr)> cb;
enum task_type {
// User tasks
STOP,
UPDATE_DELAY,
// Node tasks
SYNC,
CREATE_BLOCK,
// Network tasks
RELAY_BLOCK,
NETWORK_MSG,
// Default type
GENERAL,
};
task_type type = GENERAL;
///
std::string type_str() const {
switch (type) {
case STOP: return "STOP";
case UPDATE_DELAY: return "UPDATE_DELAY";
case SYNC: return "SYNC";
case CREATE_BLOCK: return "CREATE_BLOCK";
case RELAY_BLOCK: return "RELAY_BLOCK";
case NETWORK_MSG: return "NETWORK_MSG";
case GENERAL: return "GENERAL";
default: return "<unknown>";
}
}
bool operator<(const Task& task) const {
return at > task.at || (at == task.at && type > task.type);
}
};
using matrix_type = std::vector<std::vector<int>>;
/// Weighted adjacency matrix.
using graph_type = std::vector<std::vector<std::pair<int, int>>>;
class Network {
public:
Network() = delete;
explicit Network(uint32_t node_id, TestRunner* runner)
: node_id{node_id}, runner{runner}
{}
Network(Network&&) = default;
template <typename T>
void send(uint32_t to, const T&);
template <typename T>
void bcast(const T&);
TestRunner* get_runner() const {
return runner;
}
private:
uint32_t node_id;
TestRunner* runner;
};
class Node {
public:
const uint32_t id;
const node_type_t type;
Network net;
fork_db db;
const private_key_type private_key;
std::queue<fork_db_chain_type> pending_chains;
//
Node() = delete;
explicit Node(uint32_t id, node_type_t type, Network && net, fork_db&& db, private_key_type private_key)
: id{id}, type{type}, net{std::move(net)}, db{std::move(db)}, private_key{std::move(private_key)}
{}
virtual ~Node() = default;
TestRunner* get_runner() const {
return net.get_runner();
}
template <typename T>
void send(uint32_t to, const T& msg) {
net.send(to, msg);
}
bool apply_chain(const fork_db_chain_type& chain) {
std::stringstream ss;
ss << "[Node] #" << id << " ";
auto node_id = ss.str();
logger << node_id << "Received " << chain.blocks.size() << " blocks " << std::endl;
logger << node_id << chain << std::endl;
if (db.find(chain.blocks.back().first)) {
logger << node_id << "Already got chain head. Skipping chain " << std::endl;
return false;
}
if (get_block_height(chain.blocks.back().first) <= get_block_height(db.get_master_block_id())) {
logger << node_id << "Current master is not smaller than chain head. Skipping chain";
return false;
}
bool new_lib = false;
try {
new_lib = db.insert(chain);
} catch (const ForkDbInsertException&) {
logger << node_id << "Failed to apply chain" << std::endl;
pending_chains.push(chain);
return false;
}
for (const auto& block : chain.blocks) {
on_accepted_block_event(block);
}
if (new_lib) {
on_irreversible_block_event(db.last_irreversible_block_id());
}
return true;
}
inline Clock get_clock() const;
inline std::set<public_key_type> get_active_bp_keys() const;
virtual void on_receive(uint32_t from, void *) {
logger << "Received from " << from << std::endl;
}
virtual void on_new_peer_event(uint32_t from) {
logger << "On new peer event handled by " << id << " at " << get_clock().now() << std::endl;
}
virtual void on_accepted_block_event(pair<block_id_type, public_key_type> block) {
logger << "On accepted block event handled by " << id << " at " << get_clock().now() << std::endl;
}
virtual void on_irreversible_block_event(const block_id_type& block) {
logger << "On irreversible block event handled by " << id << " at " << get_clock().now() << std::endl;
}
virtual void restart() {}
bool should_sync() const {
return !pending_chains.empty();
}
};
class TestRunner {
public:
TestRunner() = default;
explicit TestRunner(int instances, size_t blocks_per_slot_ = 1)
: blocks_per_slot{blocks_per_slot_}
{
init_runner_data(instances);
}
explicit TestRunner(const matrix_type& matrix) {
// TODO check that it's square matrix
delay_matrix = matrix;
count_dist_matrix();
}
void load_graph(const graph_type& graph) {
for (int i = 0; i < graph.size(); i++) {
for (const auto& val : graph[i]) {
int j = val.first;
int delay = val.second;
delay_matrix[i][j] = delay_matrix[j][i] = delay;
}
}
assert(delay_matrix.size() == nodetypes.size());
count_dist_matrix();
}
void load_nodetypes(const node_types_t& tnodes) {
nodetypes = tnodes;
}
void load_graph_from_file(const char* filename) {
int instances;
int from, to, delay;
std::ifstream in(filename);
if (!in) {
std::cerr << "Failed to open file";
exit(1);
}
in >> instances;
init_runner_data(instances);
while (in >> from >> to >> delay) {
if (delay != -1) {
// assume graph is bidirectional
delay_matrix[from][to] = delay_matrix[to][from] = delay;
}
}
count_dist_matrix();
}
void load_matrix_from_file(const char* filename) {
std::ifstream in(filename);
int instances;
in >> instances;
init_runner_data(instances);
for (int i = 0; i < instances; i++) {
for (int j = 0; j < instances; j++) {
in >> delay_matrix[i][j];
}
}
count_dist_matrix();
}
void load_matrix(const matrix_type& matrix) {
delay_matrix = matrix;
count_dist_matrix();
}
fork_db_chain_type create_block(NodePtr node) {
auto& db = node->db;
std::stringstream ss;
ss << "[Node] #" << node->id << " ";
auto node_id = ss.str();
logger << node_id << "Generating block" << " at " << clock.now() << std::endl;
logger << node_id << "LIB height: " << get_block_height(db.last_irreversible_block_id()) << std::endl;
auto head = db.get_master_head();
auto head_block_height = fc::endian_reverse_u32(head->block_id._hash[0]);
logger << node_id << "Head block height: " << head_block_height << std::endl;
logger << node_id << "Building on top of " << head->block_id << std::endl;
auto new_block_id = generate_block(head_block_height + 1);
logger << node_id << "New block: " << new_block_id << std::endl;
return {head->block_id, {{new_block_id, node->private_key.get_public_key()}}};
}
vector<int> get_ordering() {
vector<int> permutation(get_bp_list());
std::random_device rd;
std::mt19937 gen(rd());
std::shuffle(permutation.begin(), permutation.end(), gen);
return permutation;
}
vector<int> get_bp_list() {
vector<int> bp_list;
for(int i = 0; i < nodetypes.size(); ++i) {
if(nodetypes[i] == node_type_t::BP) {
bp_list.push_back(i);
}
}
return bp_list;
}
void add_schedule_task(uint32_t at) {
Task task{RUNNER_ID, RUNNER_ID, at,
[&](NodePtr n) { schedule_producers(); }
};
add_task(std::move(task));
}
void add_stop_task(uint32_t at) {
Task task{RUNNER_ID, RUNNER_ID, DELAY_MS + at,
[&](NodePtr n) { should_stop = true; },
Task::STOP
};
add_task(std::move(task));
}
void add_update_delay_task(uint32_t at, size_t row, size_t col, int delay) {
Task task{RUNNER_ID, RUNNER_ID, DELAY_MS + at,
[this, row, col, delay](NodePtr n) { update_delay(row, col, delay); },
Task::UPDATE_DELAY
};
add_task(std::move(task));
}
void update_delay(uint32_t row, uint32_t col, int delay) {
delay_matrix[row][col] = delay_matrix[col][row] = delay;
count_dist_matrix();
}
void schedule_producer(uint32_t start_ms, uint32_t producer_id) {
for (int i = 0; i < blocks_per_slot; i++) {
Task task;
task.at = start_ms + i * BLOCK_GEN_MS;
task.to = producer_id;
task.cb = [this](NodePtr node) {
auto block = create_block(node);
relay_block(node, block);
bool new_lib = node->db.insert(block);
node->on_accepted_block_event(block.blocks[0]);
if (new_lib) {
node->on_irreversible_block_event(node->db.last_irreversible_block_id());
}
};
task.type = Task::CREATE_BLOCK;
add_task(std::move(task));
}
}
void schedule_producers() {
logger << "[TaskRunner] Scheduling PRODUCERS " << std::endl;
logger << "[TaskRunner] Ordering: " << "[ " ;
auto ordering = get_ordering();
for (const auto& x : ordering) {
logger << x << " ";
}
logger << "]" << std::endl;
auto now = clock.now();
int instances = ordering.size();
for (int i = 0; i < instances; i++) {
schedule_producer(now + i * get_slot_ms(), ordering[i]);
}
schedule_time = now + instances * get_slot_ms();
add_schedule_task(schedule_time);
}
void relay_block(NodePtr node, const fork_db_chain_type& chain) {
uint32_t from = node->id;
for (uint32_t to = 0; to < get_instances(); to++) {
if (from != to && dist_matrix[from][to] != -1) {
Task task{from, to, clock.now() + dist_matrix[from][to]};
task.cb = [chain](NodePtr node) {
node->apply_chain(chain);
};
task.type = Task::RELAY_BLOCK;
add_task(std::move(task));
}
}
}
void schedule_sync(NodePtr node) {
Task task{RUNNER_ID, node->id};
// syncing with the best peer aka largest master block height
NodePtr best_peer = node;
uint32_t best_peer_master_height = get_block_height(best_peer->db.get_master_block_id());
for (uint32_t peer = 0; peer < get_instances(); peer++) {
auto current_peer = nodes[peer];
auto current_peer_master_height = get_block_height(current_peer->db.get_master_block_id());
if (current_peer_master_height > best_peer_master_height) {
best_peer = current_peer;
best_peer_master_height = current_peer_master_height;
}
}
task.at = clock.now() + dist_matrix[node->id][best_peer->id];
task.cb = [=](NodePtr node) {
logger << "[Node #" << node->id << "] Executing sync " << std::endl;
const auto& peer_db = best_peer->db;
auto& node_db = node->db;
// sync done
logger << "[Node #" << node->id << "] best_peer=" << best_peer->id << std::endl;
// Copy fork_db and restart
node_db.set_root(deep_copy(peer_db.get_root()));
node->restart();
// insert chains that you failed to insert previously
auto& pending_chains = node->pending_chains;
while (!pending_chains.empty()) {
auto chain = pending_chains.front();
logger << "[Node #" << node->id << "] Applying chain " << chain << std::endl;
pending_chains.pop();
if (!node->apply_chain(chain)) {
break;
}
}
};
task.type = Task::SYNC;
add_task(std::move(task));
};
template <typename TNode>
void init_nodes(uint32_t count) {
nodes.clear();
for (auto i = 0; i < count; ++i) {
// See https://bit.ly/2Wp3Nsf
auto conf_number = 2 * blocks_per_slot * bft_threshold();
auto node = get_initialized_node<TNode>(i, conf_number);
nodes.push_back(node);
if (nodetypes[i] == node_type_t::BP) {
active_bp_keys.insert(node->private_key.get_public_key());
}
}
}
template <typename TNode>
void run() {
init_nodes<TNode>(get_instances());
run_initialized_nodes();
}
void run_initialized_nodes() {
init_connections();
assert(get_bp_list().size() != 0);
add_schedule_task(schedule_time);
run_loop();
}
void run_loop() {
logger << "[TaskRunner] Run loop " << std::endl;
should_stop = false;
while (!should_stop) {
auto task = timeline.top();
logger << "[TaskRunner] current_time=" << task.at << " schedule_time=" << schedule_time << std::endl;
timeline.pop();
clock.set(task.at);
if (task.to == RUNNER_ID) {
logger << "[TaskRunner] Executing task for TaskRunner" << std::endl;
task.cb(nullptr);
} else {
logger << "[TaskRunner] Gotta task " << task.type_str() << " for " << task.to << std::endl;
auto node = nodes[task.to];
if (node->should_sync() && task.type != Task::SYNC) {
logger << "[TaskRunner] Skipping task cause node is not synchronized" << std::endl;
} else {
logger << "[TaskRunner] Executing task ..." << std::endl;
task.cb(node);
}
if (node->should_sync()) {
logger << "[TaskRunner] Scheduling sync for node " << node->id << std::endl;
schedule_sync(node);
}
}
// this_thread::sleep_for(chrono::milliseconds(1000));
}
}
uint32_t get_instances() const {
return delay_matrix.size();
}
const matrix_type& get_delay_matrix() const {
return delay_matrix;
}
const matrix_type& get_dist_matrix() const {
return dist_matrix;
}
const vector<NodePtr> get_nodes() const {
return nodes;
}
NodePtr get_node(size_t index) const {
return nodes[index];
}
const fork_db& get_db(size_t index) {
return nodes[index]->db;
}
const Clock& get_clock() const {
return clock;
}
void add_task(Task && task) {
timeline.push(task);
}
size_t bft_threshold() const {
return 2 * get_instances() / 3 + 1;
}
uint32_t get_slot_ms() const {
return BLOCK_GEN_MS * blocks_per_slot;
}
std::set<public_key_type> get_active_bp_keys() const {
return active_bp_keys;
}
const block_id_type genesys_block;
const uint32_t RUNNER_ID = 10000000;
static const uint32_t DELAY_MS = 500;
static const uint32_t BLOCK_GEN_MS = 500;
size_t blocks_per_slot;
bool should_stop = false;
template<typename TNode>
void add_node(int conf_number = 0, node_type_t type = node_type_t::BP) {
conf_number = !conf_number ? 2 * blocks_per_slot * bft_threshold() : conf_number;
auto node = get_initialized_node<TNode>(nodes.size(), conf_number);
nodes.push_back(node);
if (type == node_type_t::BP) {
active_bp_keys.insert(node->private_key.get_public_key());
}
}
template<typename TNode>
NodePtr get_initialized_node(int id, int conf_number) {
auto priv_key = get_priv_key();
auto node = std::make_shared<TNode>(id, nodetypes[id], Network(id, this), fork_db(genesys_block, conf_number), priv_key);
return node;
}
private:
block_id_type generate_block(uint32_t block_height) {
auto block_id = digest_type::hash(fc::crypto::private_key::generate());
block_id._hash[0] = fc::endian_reverse_u32(block_height);
return block_id;
}
void init_connections() {
for (uint32_t from = 0; from < get_instances(); from++) {
for (uint32_t to = 0; to < get_instances(); to++) {
int delay = delay_matrix[from][to];
if (from != to && delay != -1) {
add_task(Task{from, to, static_cast<uint32_t>(0),
[from](NodePtr n){ n->on_new_peer_event(from); }});
}
}
}
}
void init_runner_data(int instances) {
nodetypes.resize(instances, node_type_t::BP);
delay_matrix.resize(instances);
for (int i = 0; i < instances; i++) {
delay_matrix[i] = vector<int>(instances, -1);
delay_matrix[i][i] = 0;
}
dist_matrix = delay_matrix;
}
void count_dist_matrix() {
int n = get_instances();
dist_matrix = delay_matrix;
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (dist_matrix[i][k] != -1 && dist_matrix[k][j] != -1) {
auto new_dist = dist_matrix[i][k] + dist_matrix[k][j];
auto& cur_dist = dist_matrix[i][j];
if (cur_dist == -1) {
cur_dist = new_dist;
} else {
cur_dist = std::min(cur_dist, new_dist);
}
}
}
}
}
}
node_types_t nodetypes;
std::vector<NodePtr> nodes;
matrix_type delay_matrix;
matrix_type dist_matrix;
std::priority_queue<Task> timeline;
std::set<public_key_type> active_bp_keys;
uint32_t schedule_time = DELAY_MS;
Clock clock;
};
template <typename T>
void Network::send(uint32_t to, const T& msg) {
auto matrix = runner->get_delay_matrix();
assert(matrix[node_id][to] != -1);
runner->add_task(Task {
node_id,
to,
get_runner()->get_clock().now() + matrix[node_id][to],
[node_id = node_id, msg = msg](NodePtr n) {
n->on_receive(node_id, (void*)&msg);
},
Task::NETWORK_MSG
});
}
template <typename T>
void Network::bcast(const T& msg) {
//TODO bcast to all nodes with calculate routes
}
inline Clock Node::get_clock() const {
return get_runner()->get_clock();
}
inline std::set<public_key_type> Node::get_active_bp_keys() const {
return get_runner()->get_active_bp_keys();
}
| 30.083578 | 129 | 0.553882 | [
"vector"
] |
cbeba1656df696374c1ee14bec6712823db50d39 | 10,501 | cc | C++ | engine/gui/controls/guiDirectoryTreeCtrl.cc | ClayHanson/B4v21-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | 1 | 2020-08-18T19:45:34.000Z | 2020-08-18T19:45:34.000Z | engine/gui/controls/guiDirectoryTreeCtrl.cc | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | engine/gui/controls/guiDirectoryTreeCtrl.cc | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#include "gui/controls/guiDirectoryTreeCtrl.h"
IMPLEMENT_CONOBJECT(GuiDirectoryTreeCtrl);
GuiDirectoryTreeCtrl::GuiDirectoryTreeCtrl(): GuiTreeViewCtrl()
{
// Parent configuration
mBounds.set( 0,0,200,100 );
mDestroyOnSleep = false;
mSupportMouseDragging = false;
mMultipleSelections = false;
mSelPath = StringTable->insert("");
}
bool GuiDirectoryTreeCtrl::onAdd()
{
if( !Parent::onAdd() )
return false;
// Specify our icons
buildIconTable( NULL );
return true;
}
bool GuiDirectoryTreeCtrl::onWake()
{
if( !Parent::onWake() )
return false;
// Kill off any existing items
destroyTree();
// Here we're going to grab our system volumes from the platform layer and create them as roots
//
// Note : that we're passing a 1 as the last parameter to Platform::dumpDirectories, which tells it
// how deep to dump in recursion. This is an optimization to keep from dumping the whole file system
// to the tree. The tree will dump more paths as necessary when the virtual parents are expanded,
// much as windows does.
ResourceManager->initExcludedDirectories();
StringTableEntry RootPath = ResourceManager->getModPaths();
//getUnit(argv[1], dAtoi(argv[2]), " \t\n");
S32 modCount = getUnitCount( RootPath, ";" );
for( S32 i = 0; i < modCount; i++ )
{
// Compose full mod path location, and dump the path to our vector
StringTableEntry currentMod = getUnit( RootPath, i, ";" );
char fullModPath [512];
dMemset( fullModPath, 0, 512 );
dSprintf( fullModPath, 512, "%s/%s/", Platform::getWorkingDirectory(), currentMod );
Vector<StringTableEntry> pathVec;
Platform::dumpDirectories( fullModPath, pathVec, 0, true);
if( ! pathVec.empty() )
{
// Iterate through the returned paths and add them to the tree
Vector<StringTableEntry>::iterator j = pathVec.begin();
for( ; j != pathVec.end(); j++ )
{
char fullModPathSub [512];
dMemset( fullModPathSub, 0, 512 );
dSprintf( fullModPathSub, 512, "%s/%s", currentMod, (*j) );
addPathToTree( fullModPathSub );
}
}
else
addPathToTree( fullModPath );
}
// Success!
return true;
}
bool GuiDirectoryTreeCtrl::onVirtualParentExpand(Item *item)
{
if( !item || !item->isExpanded() )
return true;
StringTableEntry pathToExpand = item->getValue();
if( !pathToExpand )
{
Con::errorf("GuiDirectoryTreeCtrl::onVirtualParentExpand - Unable to retrieve item value!");
return false;
}
Vector<StringTableEntry> pathVec;
Platform::dumpDirectories( pathToExpand, pathVec, 0, true );
if( ! pathVec.empty() )
{
// Iterate through the returned paths and add them to the tree
Vector<StringTableEntry>::iterator i = pathVec.begin();
for( ; i != pathVec.end(); i++ )
recurseInsert(item, (*i) );
item->setExpanded( true );
}
item->setVirtualParent( false );
// Update our tree view
buildVisibleTree();
return true;
}
bool GuiDirectoryTreeCtrl::buildIconTable(const char * icons)
{
// Icons should be designated by the bitmap/png file names (minus the file extensions)
// and separated by colons (:).
if (!icons)
icons = StringTable->insert("common/ui/folder:common/ui/folder:common/ui/folder_closed");
return Parent::buildIconTable( icons );
}
void GuiDirectoryTreeCtrl::addPathToTree( StringTableEntry path )
{
if( !path )
{
Con::errorf("GuiDirectoryTreeCtrl::addPathToTree - Invalid Path!");
return;
}
// Identify which root (volume) this path belongs to (if any)
S32 root = getFirstRootItem();
StringTableEntry ourPath = &path[ dStrcspn( path, "//" ) + 1];
StringTableEntry ourRoot = getUnit( path, 0, "//" );
// There are no current roots, we can safely create one
if( root == 0 )
{
recurseInsert( NULL, path );
}
else
{
while( root != 0 )
{
if( dStrcmp( getItemValue( root ), ourRoot ) == 0 )
{
recurseInsert( getItem( root ), ourPath );
break;
}
root = this->getNextSiblingItem( root );
}
// We found none so we'll create one
if ( root == 0 )
{
recurseInsert( NULL, path );
}
}
}
void GuiDirectoryTreeCtrl::onItemSelected( Item *item )
{
Con::executef( this, 2, "onSelectPath", avar("%s",item->getValue()) );
mSelPath = StringTable->insert( item->getValue() );
if( Platform::hasSubDirectory( item->getValue() ) )
item->setVirtualParent( true );
}
void GuiDirectoryTreeCtrl::recurseInsert( Item* parent, StringTableEntry path )
{
if( !path )
return;
char szPathCopy [ 1024 ];
dMemset( szPathCopy, 0, 1024 );
dStrcpy( szPathCopy, path );
// Jump over the first character if it's a root /
char *curPos = szPathCopy;
if( *curPos == '/' )
curPos++;
char *delim = dStrchr( curPos, '/' );
if ( delim )
{
// terminate our / and then move our pointer to the next character (rest of the path)
*delim = 0x00;
delim++;
}
S32 itemIndex = 0;
// only insert blindly if we have no root
if( !parent )
{
itemIndex = insertItem( 0, curPos, curPos );
getItem( itemIndex )->setNormalImage( Icon_FolderClosed );
getItem( itemIndex )->setExpandedImage( Icon_Folder );
}
else
{
Item *item = parent;
char *szValue = new char[ 1024 ];
dMemset( szValue, 0, 1024 );
dSprintf( szValue, 1024, "%s/%s", parent->getValue(), curPos );
Item *exists = item->findChildByValue( szValue );
if( !exists && dStrcmp( curPos, "" ) != 0 )
{
// Since we're adding a child this parent can't be a virtual parent, so clear that flag
item->setVirtualParent( false );
itemIndex = insertItem( item->getID(), curPos);
getItem( itemIndex )->setValue( szValue );
getItem( itemIndex )->setNormalImage( Icon_FolderClosed );
getItem( itemIndex )->setExpandedImage( Icon_Folder );
}
else
{
delete []szValue;
itemIndex = ( item != NULL ) ? ( ( exists != NULL ) ? exists->getID() : -1 ) : -1;
}
}
// since we're only dealing with volumes and directories, all end nodes will be virtual parents
// so if we are at the bottom of the rabbit hole, set the item to be a virtual parent
Item* item = getItem( itemIndex );
if( delim )
{
if( ( dStrcmp( delim, "" ) == 0 ) && item )
{
item->setExpanded( false );
if( parent && Platform::hasSubDirectory( item->getValue() ) )
item->setVirtualParent( true );
}
}
else
{
if( item )
{
item->setExpanded( false );
if( parent && Platform::hasSubDirectory( item->getValue() ) )
item->setVirtualParent( true );
}
}
// Down the rabbit hole we go
recurseInsert( getItem( itemIndex ), delim );
}
StringTableEntry GuiDirectoryTreeCtrl::getUnit(const char *string, U32 index, const char *set)
{
U32 sz;
while(index--)
{
if(!*string)
return "";
sz = dStrcspn(string, set);
if (string[sz] == 0)
return "";
string += (sz + 1);
}
sz = dStrcspn(string, set);
if (sz == 0)
return "";
char *ret = Con::getReturnBuffer(sz+1);
dStrncpy(ret, string, sz);
ret[sz] = '\0';
return ret;
}
StringTableEntry GuiDirectoryTreeCtrl::getUnits(const char *string, S32 startIndex, S32 endIndex, const char *set)
{
S32 sz;
S32 index = startIndex;
while(index--)
{
if(!*string)
return "";
sz = dStrcspn(string, set);
if (string[sz] == 0)
return "";
string += (sz + 1);
}
const char *startString = string;
while(startIndex <= endIndex--)
{
sz = dStrcspn(string, set);
string += sz;
if (*string == 0)
break;
string++;
}
if(!*string)
string++;
U32 totalSize = (U32(string - startString));
char *ret = Con::getReturnBuffer(totalSize);
dStrncpy(ret, startString, totalSize - 1);
ret[totalSize-1] = '\0';
return ret;
}
U32 GuiDirectoryTreeCtrl::getUnitCount(const char *string, const char *set)
{
U32 count = 0;
U8 last = 0;
while(*string)
{
last = *string++;
for(U32 i =0; set[i]; i++)
{
if(last == set[i])
{
count++;
last = 0;
break;
}
}
}
if(last)
count++;
return count;
}
ConsoleMethod( GuiDirectoryTreeCtrl, getSelectedPath, const char*, 2,2, "getSelectedPath() - returns the currently selected path in the tree")
{
return object->getSelectedPath();
}
StringTableEntry GuiDirectoryTreeCtrl::getSelectedPath()
{
return mSelPath;
}
ConsoleMethod( GuiDirectoryTreeCtrl, setSelectedPath, bool, 3, 3, "setSelectedPath(path) - expands the tree to the specified path")
{
return object->setSelectedPath( argv[2] );
}
bool GuiDirectoryTreeCtrl::setSelectedPath( StringTableEntry path )
{
if( !path )
return false;
// Since we only list one deep on paths, we need to add the path to the tree just incase it isn't already indexed in the tree
// or else we wouldn't be able to select a path we hadn't previously browsed to. :)
if( Platform::isDirectory( path ) )
addPathToTree( path );
// see if we have a child that matches what we want
for(U32 i = 0; i < mItems.size(); i++)
{
if( dStricmp( mItems[i]->getValue(), path ) == 0 )
{
Item* item = mItems[i];
AssertFatal(item,"GuiDirectoryTreeCtrl::setSelectedPath - Item Index Bad, Fatal Mistake!!!");
item->setExpanded( true );
clearSelection();
setItemSelected( item->getID(), true );
// make sure all of it's parents are expanded
S32 parent = getParentItem( item->getID() );
while( parent != 0 )
{
setItemExpanded( parent, true );
parent = getParentItem( parent );
}
// Rebuild our tree just incase we've oops'd
buildVisibleTree();
scrollVisible( item );
}
}
return false;
} | 27.489529 | 142 | 0.594896 | [
"object",
"vector"
] |
cbee8e7630960cf6135c24741e85d65fe372437e | 6,788 | cpp | C++ | UTEngine/Renderer/MeshRender.cpp | dpjudas/UTEngine | df9c7104c7d22c5b45eddc1515ddeab66b9c945e | [
"Apache-2.0",
"CC0-1.0"
] | 50 | 2020-12-02T17:41:17.000Z | 2022-03-18T05:08:21.000Z | UTEngine/Renderer/MeshRender.cpp | dpjudas/UTEngine | df9c7104c7d22c5b45eddc1515ddeab66b9c945e | [
"Apache-2.0",
"CC0-1.0"
] | 11 | 2021-07-14T13:41:12.000Z | 2021-09-30T10:32:58.000Z | UTEngine/Renderer/MeshRender.cpp | dpjudas/UTEngine | df9c7104c7d22c5b45eddc1515ddeab66b9c945e | [
"Apache-2.0",
"CC0-1.0"
] | 4 | 2021-07-20T20:22:36.000Z | 2022-01-06T15:30:26.000Z |
#include "Precomp.h"
#include "MeshRender.h"
#include "UObject/UMesh.h"
#include "UObject/UTexture.h"
#include "UObject/UActor.h"
#include "UObject/ULevel.h"
#include "RenderDevice/RenderDevice.h"
#include "Engine.h"
#include "UTRenderer.h"
#include "Window/Window.h"
void MeshRender::DrawMesh(FSceneNode* frame, UActor* actor)
{
UMesh* mesh = actor->Mesh();
const vec3& location = actor->Location();
const Rotator& rotation = actor->Rotation();
const vec3& color = actor->light;
if (!mesh)
return;
mat4 objectToWorld = mat4::translate(actor->Location() + actor->PrePivot()) * actor->Rotation().ToMatrix() * mat4::scale(actor->DrawScale());
mat4 meshToObject = mesh->RotOrigin.ToMatrix() * mat4::scale(mesh->Scale) * mat4::translate(-mesh->Origin);
mat4 meshToWorld = objectToWorld * meshToObject;
if (dynamic_cast<USkeletalMesh*>(mesh))
DrawSkeletalMesh(frame, actor, static_cast<USkeletalMesh*>(mesh), meshToWorld, color);
else if (dynamic_cast<ULodMesh*>(mesh))
DrawLodMesh(frame, actor, static_cast<ULodMesh*>(mesh), meshToWorld, color);
else
DrawMesh(frame, actor, mesh, meshToWorld, color);
}
void MeshRender::DrawMesh(FSceneNode* frame, UActor* actor, UMesh* mesh, const mat4& ObjectToWorld, const vec3& color)
{
}
void MeshRender::DrawLodMesh(FSceneNode* frame, UActor* actor, ULodMesh* mesh, const mat4& ObjectToWorld, const vec3& color)
{
MeshAnimSeq* seq = mesh->GetSequence(actor->AnimSequence());
float animFrame = actor->AnimFrame() * seq->NumFrames;
int vertexOffsets[3];
float t0, t1;
if (animFrame >= 0.0f)
{
int frame0 = (int)animFrame;
int frame1 = frame0 + 1;
t0 = animFrame - (float)frame0;
t1 = 0.0f;
frame0 = frame0 % seq->NumFrames;
frame1 = frame1 % seq->NumFrames;
vertexOffsets[0] = (seq->StartFrame + frame0) * mesh->FrameVerts;
vertexOffsets[1] = (seq->StartFrame + frame1) * mesh->FrameVerts;
vertexOffsets[2] = 0;
// Save old animation location to be able to tween from it:
actor->LastAnimFrame.V0 = vertexOffsets[0];
actor->LastAnimFrame.V1 = vertexOffsets[1];
actor->LastAnimFrame.T = t0;
}
else // Tween from old animation
{
vertexOffsets[2] = seq->StartFrame * mesh->FrameVerts;
if (actor->LastAnimFrame.T < 0.0f)
{
actor->LastAnimFrame.V0 = vertexOffsets[2];
actor->LastAnimFrame.V1 = vertexOffsets[2];
actor->LastAnimFrame.T = 0.0f;
}
vertexOffsets[0] = actor->LastAnimFrame.V0;
vertexOffsets[1] = actor->LastAnimFrame.V1;
t0 = actor->LastAnimFrame.T;
t1 = clamp(animFrame + 1.0f, 0.0f, 1.0f);
}
SetupTextures(actor, mesh);
DrawLodMeshFace(frame, actor, mesh, mesh->Faces, ObjectToWorld, color, mesh->SpecialVerts, vertexOffsets, t0, t1);
DrawLodMeshFace(frame, actor, mesh, mesh->SpecialFaces, ObjectToWorld, color, 0, vertexOffsets, t0, t1);
}
void MeshRender::SetupTextures(UActor* actor, ULodMesh* mesh)
{
if (textures.size() < mesh->Textures.size())
textures.resize(mesh->Textures.size());
envmap = nullptr;
for (int i = 0; i < (int)mesh->Textures.size(); i++)
{
UTexture* tex = actor->GetMultiskin(i);
if (i == 0)
{
if (!tex) tex = actor->Skin();
if (!tex) tex = mesh->Textures[i];
}
else
{
if (!tex) tex = mesh->Textures[i];
if (!tex) tex = actor->Skin();
}
if (tex)
tex = tex->GetAnimTexture();
if (tex)
envmap = tex;
textures[i] = tex;
}
if (actor->Texture())
{
envmap = actor->Texture();
}
else if (actor->Region().Zone && actor->Region().Zone->EnvironmentMap())
{
envmap = actor->Region().Zone->EnvironmentMap();
}
else if (actor->Level()->EnvironmentMap())
{
envmap = actor->Level()->EnvironmentMap();
}
}
void MeshRender::DrawLodMeshFace(FSceneNode* frame, UActor* actor, ULodMesh* mesh, const std::vector<MeshFace>& faces, const mat4& ObjectToWorld, const vec3& lightcolor, int baseVertexOffset, const int* vertexOffsets, float t0, float t1)
{
auto device = engine->window->GetRenderDevice();
uint32_t polyFlags = 0;
switch (actor->Style())
{
case 2: polyFlags |= PF_Masked; break; // STY_Masked
case 3: polyFlags |= PF_Translucent; break; // STY_Translucent
case 4: polyFlags |= PF_Modulated; break; // STY_Modulated
}
if (actor->bNoSmooth()) polyFlags |= PF_NoSmooth;
if (actor->bSelected()) polyFlags |= PF_Selected;
if (actor->bMeshEnviroMap()) polyFlags |= PF_Environment;
if (actor->bMeshCurvy()) polyFlags |= PF_Flat;
if (actor->bNoSmooth()) polyFlags |= PF_NoSmooth;
if (actor->bUnlit() || actor->Region().ZoneNumber == 0) polyFlags |= PF_Unlit;
vec3 color;
if (polyFlags & PF_Unlit)
{
color = vec3(clamp(actor->ScaleGlow() * 0.5f + actor->AmbientGlow() * (1.0f / 256.0f), 0.0f, 1.0f));
}
else
{
color = lightcolor;
}
GouraudVertex vertices[3];
for (const MeshFace& face : faces)
{
if (face.MaterialIndex >= mesh->Materials.size())
continue;
const MeshMaterial& material = mesh->Materials[face.MaterialIndex];
uint32_t renderflags = material.PolyFlags | polyFlags;
UTexture* tex = (renderflags & PF_Environment) ? envmap : textures[material.TextureIndex];
if (tex && tex->bMasked())
renderflags |= PF_Masked;
FTextureInfo texinfo;
texinfo.Texture = tex;
texinfo.CacheID = (uint64_t)(ptrdiff_t)texinfo.Texture;
float uscale = (texinfo.Texture ? texinfo.Texture->Mipmaps.front().Width : 256) * (1.0f / 255.0f);
float vscale = (texinfo.Texture ? texinfo.Texture->Mipmaps.front().Height : 256) * (1.0f / 255.0f);
for (int i = 0; i < 3; i++)
{
const MeshWedge& wedge = mesh->Wedges[face.Indices[i]];
const vec3& v0 = mesh->Verts[(size_t)wedge.Vertex + baseVertexOffset + vertexOffsets[0]];
const vec3& v1 = mesh->Verts[(size_t)wedge.Vertex + baseVertexOffset + vertexOffsets[1]];
vec3 vertex = mix(v0, v1, t0);
if (t1 != 0.0f)
{
const vec3& v2 = mesh->Verts[(size_t)wedge.Vertex + baseVertexOffset + vertexOffsets[2]];
vertex = mix(vertex, v2, t1);
}
vertices[i].Point = (ObjectToWorld * vec4(vertex, 1.0f)).xyz();
vertices[i].UV = { wedge.U * uscale, wedge.V * vscale };
vertices[i].Light = color;
}
if (renderflags & PF_Environment)
{
// To do: this needs to be the smoothed normal
vec3 n = normalize(cross(vertices[1].Point - vertices[0].Point, vertices[2].Point - vertices[0].Point));
mat3 rotmat = mat3(frame->Modelview);
for (int i = 0; i < 3; i++)
{
vec3 v = normalize(vertices[i].Point);
vec3 p = rotmat * reflect(v, n);
vertices[i].UV = { (p.x + 1.0f) * 128.0f * uscale, (p.y + 1.0f) * 128.0f * vscale };
}
}
device->DrawGouraudPolygon(frame, texinfo.Texture ? &texinfo : nullptr, vertices, 3, renderflags);
}
}
void MeshRender::DrawSkeletalMesh(FSceneNode* frame, UActor* actor, USkeletalMesh* mesh, const mat4& ObjectToWorld, const vec3& color)
{
DrawLodMesh(frame, actor, mesh, ObjectToWorld, color);
}
| 30.854545 | 237 | 0.678698 | [
"mesh",
"vector"
] |
cbf4a7bdf84a32066f1511c8267fd617c20417ca | 10,888 | cpp | C++ | rviz_plugin_covariance/src/covariance_visual.cpp | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | 7 | 2018-10-24T14:52:20.000Z | 2021-01-12T14:59:00.000Z | rviz_plugin_covariance/src/covariance_visual.cpp | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | null | null | null | rviz_plugin_covariance/src/covariance_visual.cpp | hect1995/Robotics_intro | 1b687585c20db5f1114d8ca6811a70313d325dd6 | [
"BSD-3-Clause"
] | 17 | 2019-09-29T10:22:41.000Z | 2021-04-08T12:38:37.000Z |
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <ros/console.h>
#include <rviz/ogre_helpers/axes.h>
#include <rviz/ogre_helpers/shape.h>
#include <Eigen/Dense>
#include "covariance_visual.h"
template<typename Derived>
inline bool isfinite(const Eigen::MatrixBase<Derived>& x)
{
return ( (x - x).array() == (x - x).array()).all();
}
template<typename Derived>
inline bool isnan(const Eigen::MatrixBase<Derived>& x)
{
return !((x.array() == x.array())).all();
}
std::pair<Eigen::Matrix3d, Eigen::Vector3d> computeEigenValuesAndVectors(const geometry_msgs::PoseWithCovariance& msg, unsigned offset)
{
Eigen::Matrix3d covariance = Eigen::Matrix3d::Zero();
Eigen::Vector3d eigenValues = Eigen::Vector3d::Identity();
Eigen::Matrix3d eigenVectors = Eigen::Matrix3d::Zero();
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
covariance (i, j) = msg.covariance[(i + offset) * 6 + j + offset];
}
}
// Compute eigen values and eigen vectors.
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(covariance);
if (eigensolver.info() == Eigen::Success)
{
eigenValues = eigensolver.eigenvalues();
eigenVectors = eigensolver.eigenvectors();
}
else
{
ROS_WARN_THROTTLE(1, "Failed to compute eigen vectors/values. Is the covariance matrix correct?");
}
return std::make_pair(eigenVectors, eigenValues);
}
Ogre::Quaternion computeRotation(const geometry_msgs::PoseWithCovariance& msg, std::pair<Eigen::Matrix3d, Eigen::Vector3d>& pair)
{
Ogre::Matrix3 rotation;
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
rotation[i][j] = pair.first(i, j);
}
}
return Ogre::Quaternion(rotation);
}
namespace rviz_plugin_covariance
{
CovarianceVisual::CovarianceVisual(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node)
: frame_node_(parent_node->createChildSceneNode())
, scene_manager_(scene_manager)
, scale_(1.0)
{
axes_.reset(new rviz::Axes(scene_manager_, frame_node_));
position_node_ = axes_->getSceneNode()->createChildSceneNode();
orientation_node_ = axes_->getSceneNode()->createChildSceneNode();
position_shape_.reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_, position_node_));
orientation_shape_.reset(new rviz::Shape(rviz::Shape::Cone, scene_manager_, orientation_node_));
axes_->getSceneNode()->setVisible(show_axis_);
position_node_->setVisible(show_position_);
orientation_node_->setVisible(use_6dof_ && show_orientation_);
}
CovarianceVisual::~CovarianceVisual()
{
scene_manager_->destroySceneNode(orientation_node_);
scene_manager_->destroySceneNode(position_node_);
scene_manager_->destroySceneNode(frame_node_);
}
void CovarianceVisual::setMessage(const geometry_msgs::PoseWithCovariance& msg)
{
// Construct pose position and orientation.
const geometry_msgs::Point& p = msg.pose.position;
Ogre::Vector3 position(p.x, p.y, p.z);
Ogre::Quaternion orientation(msg.pose.orientation.w, msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z);
// Set position and orientation for axes scene node.
if (!position.isNaN())
{
axes_->setPosition(position);
}
else
{
ROS_WARN_STREAM_THROTTLE(1, "Position contains NaN: " << position);
}
if (!orientation.isNaN())
{
axes_->setOrientation(orientation);
}
else
{
ROS_WARN_STREAM_THROTTLE(1, "Orientation contains NaN: " << orientation);
}
if (use_6dof_)
{
// Check for NaN in covariance
for (size_t i = 0; i < 3; ++i)
{
if (isnan(msg.covariance[i]))
{
ROS_WARN_THROTTLE(1, "Covariance contains NaN");
return;
}
}
// Compute eigen values and vectors for both shapes.
std::pair<Eigen::Matrix3d, Eigen::Vector3d> positionEigenVectorsAndValues(computeEigenValuesAndVectors(msg, 0));
std::pair<Eigen::Matrix3d, Eigen::Vector3d> orientationEigenVectorsAndValues(computeEigenValuesAndVectors(msg, 3));
Ogre::Quaternion positionQuaternion(computeRotation(msg, positionEigenVectorsAndValues));
Ogre::Quaternion orientationQuaternion(computeRotation(msg, orientationEigenVectorsAndValues));
position_node_->setOrientation(positionQuaternion);
orientation_node_->setOrientation(orientationQuaternion);
// Compute scaling.
Ogre::Vector3 positionScaling(
std::sqrt(positionEigenVectorsAndValues.second[0]),
std::sqrt(positionEigenVectorsAndValues.second[1]),
std::sqrt(positionEigenVectorsAndValues.second[2]));
positionScaling *= scale_;
Ogre::Vector3 orientationScaling(
std::sqrt(orientationEigenVectorsAndValues.second[0]),
std::sqrt(orientationEigenVectorsAndValues.second[1]),
std::sqrt(orientationEigenVectorsAndValues.second[2]));
orientationScaling *= scale_;
// Set the scaling.
if (!positionScaling.isNaN())
{
position_node_->setScale(positionScaling);
}
else
{
ROS_WARN_STREAM_THROTTLE(1, "PositionScaling contains NaN: " << positionScaling);
}
if (!orientationScaling.isNaN())
{
orientation_node_->setScale(orientationScaling);
}
else
{
ROS_WARN_STREAM_THROTTLE(1, "OrientationScaling contains NaN: " << orientationScaling);
}
// Debugging.
ROS_DEBUG_STREAM_THROTTLE(1,
"Position:\n"
<< position << "\n"
<< "Positional part 3x3 eigen values:\n"
<< positionEigenVectorsAndValues.second << "\n"
<< "Positional part 3x3 eigen vectors:\n"
<< positionEigenVectorsAndValues.first << "\n"
<< "Sphere orientation:\n"
<< positionQuaternion << "\n"
<< positionQuaternion.getYaw() << "\n"
<< "Sphere scaling:\n"
<< positionScaling << "\n"
<< "Rotational part 3x3 eigen values:\n"
<< orientationEigenVectorsAndValues.second << "\n"
<< "Rotational part 3x3 eigen vectors:\n"
<< orientationEigenVectorsAndValues.first << "\n"
<< "Cone orientation:\n"
<< orientationQuaternion << "\n"
<< orientationQuaternion.getRoll() << " "
<< orientationQuaternion.getPitch() << " "
<< orientationQuaternion.getYaw() << "\n"
<< "Cone scaling:\n"
<< orientationScaling);
}
else // 3DOF
{
// Take (x, y, th) part from the covariance matrix:
// x y z R P Y
// x * * x
// y * * x
// z
// R
// P
// Y x x *
//
// Actually, we only take the elements marked with '*', although we could
// also take a 3x3 matrix with the '*' and 'x' elements.
Eigen::Matrix2d cov_xy; cov_xy << msg.covariance[0], msg.covariance[1],
msg.covariance[6], msg.covariance[7];
const double cov_yaw = msg.covariance[35];
// Check for NaN in covariance
if (isnan(cov_xy) || isnan(cov_yaw))
{
ROS_WARN_STREAM_THROTTLE(1, "Covariance contains NaN: " <<
"C_xy = " << cov_xy << ", C_yaw = " << cov_yaw);
return;
}
// Compute eigen values and vectors for xy
Eigen::Vector2d eigen_values = Eigen::Vector2d::Identity();
Eigen::Matrix2d eigen_vectors = Eigen::Matrix2d::Zero();
Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eigensolver(cov_xy);
if (eigensolver.info() == Eigen::Success)
{
eigen_values = eigensolver.eigenvalues();
eigen_vectors = eigensolver.eigenvectors();
}
else
{
ROS_WARN_THROTTLE(1, "Failed to compute eigen values/vectors. Is the covariance matrix correct?");
}
// Compute ellipsoid angle, and axes
const double yaw = atan2(eigen_vectors(1, 0), eigen_vectors(0, 0));
const double axis_major = sqrt(eigen_values[0]);
const double axis_minor = sqrt(eigen_values[1]);
const double axis_yaw = sqrt(cov_yaw);
// Compute the ellipsoid orientation
Ogre::Quaternion positionQuaternion;
Ogre::Matrix3 R;
R.FromEulerAnglesXYZ(Ogre::Radian(0.0), Ogre::Radian(0.0), Ogre::Radian(yaw));
positionQuaternion.FromRotationMatrix(R);
// Set the orientation
position_node_->setOrientation(positionQuaternion);
// Compute the ellipsoid scale
Ogre::Vector3 positionScaling(
std::isnormal(axis_major) ? axis_major : 0.001,
std::isnormal(axis_minor) ? axis_minor : 0.001,
std::isnormal(axis_yaw ) ? axis_yaw : 0.001);
positionScaling *= scale_;
// Set the scaling
if (!positionScaling.isNaN())
{
position_node_->setScale(positionScaling);
}
else
{
ROS_WARN_STREAM_THROTTLE(1, "PositionScaling contains NaN: " << positionScaling);
}
// Debugging
ROS_DEBUG_STREAM_THROTTLE(1,
"Position:\n"
<< position << "\n"
<< "C_xy:\n"
<< cov_xy << "\n"
<< "C_yaw:\n"
<< cov_yaw << "\n"
<< "axis (major, minor, yaw): (" << axis_major << ", " << axis_minor << ", " << axis_yaw << ")\n"
<< "yaw: " << yaw << "\n"
<< "Positional part 2x2 eigen values:\n"
<< eigen_values << "\n"
<< "Positional part 2x2 eigen vectors:\n"
<< eigen_vectors << "\n"
<< "Sphere orientation:\n"
<< positionQuaternion << "\n"
<< positionQuaternion.getRoll() << " "
<< positionQuaternion.getPitch() << " "
<< positionQuaternion.getYaw() << "\n"
<< "Sphere scaling:\n"
<< positionScaling);
}
}
void CovarianceVisual::setMessage(const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg)
{
setMessage(msg->pose);
}
void CovarianceVisual::setMessage(const nav_msgs::OdometryConstPtr& msg)
{
setMessage(msg->pose);
}
void CovarianceVisual::setFramePosition(const Ogre::Vector3& position)
{
frame_node_->setPosition(position);
}
void CovarianceVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
frame_node_->setOrientation(orientation);
}
void CovarianceVisual::setColor(float r, float g, float b, float a)
{
position_shape_->setColor(r, g, b, a);
orientation_shape_->setColor(r, g, b, a);
}
void CovarianceVisual::setScale(float scale)
{
scale_ = scale;
}
void CovarianceVisual::setShowAxis(bool show_axis)
{
show_axis_ = show_axis;
axes_->getSceneNode()->setVisible(show_axis);
position_node_->setVisible(show_position_);
orientation_node_->setVisible(use_6dof_ && show_orientation_);
}
void CovarianceVisual::setShowPosition(bool show_position)
{
show_position_ = show_position;
position_node_->setVisible(show_position_);
}
void CovarianceVisual::setShowOrientation(bool show_orientation)
{
show_orientation_ = show_orientation;
orientation_node_->setVisible(use_6dof_ && show_orientation_);
}
void CovarianceVisual::setUse6DOF(bool use_6dof)
{
use_6dof_ = use_6dof;
orientation_node_->setVisible(use_6dof && show_orientation_);
}
} // end namespace rviz_plugin_covariance
| 29.99449 | 136 | 0.67083 | [
"shape"
] |
0202af2ededa10bfab133dc699c56901876777fc | 9,088 | cc | C++ | components/translate/core/language_detection/ngram_hash.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/translate/core/language_detection/ngram_hash.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/translate/core/language_detection/ngram_hash.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 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/translate/core/language_detection/ngram_hash.h"
#include <string>
#include "components/translate/core/language_detection/ngram_hash_ops_utils.h"
#include "third_party/flatbuffers/src/include/flatbuffers/flexbuffers.h"
#include "third_party/flatbuffers/src/include/flatbuffers/util.h"
#include "third_party/smhasher/src/MurmurHash2.h"
#include "third_party/tflite/src/tensorflow/lite/kernels/kernel_util.h"
#include "third_party/tflite/src/tensorflow/lite/string_util.h"
namespace {
using ::flexbuffers::GetRoot;
using ::flexbuffers::Map;
using ::flexbuffers::TypedVector;
using ::tflite::GetString;
using ::tflite::StringRef;
using ::translate::LowercaseUnicodeStr;
using ::translate::Tokenize;
using ::translate::TokenizedOutput;
constexpr int kInputMessage = 0;
constexpr int kOutputLabel = 0;
constexpr int kDefaultMaxSplits = 128;
// This op takes in a string, finds the character ngrams for it and then
// maps each of these ngrams to an index using the specified vocabulary sizes.
// Input(s):
// - input: Input string.
// - seeds: Seed for the random number generator.
// - ngram_lengths: Lengths of each of the ngrams. For example [1, 2, 3] would
// be interpreted as generating unigrams, bigrams, and trigrams.
// - vocab_sizes: Size of the vocabulary for each of the ngram features
// respectively. The op would generate vocab ids to be less than or equal to
// the vocab size. The index 0 implies an invalid ngram.
// - max_splits: Maximum number of tokens in the output. If this is unset, the
// limit is `kDefaultMaxSplits`.
// - lower_case_input: If this is set to true, the input string would be
// lower-cased before any processing.
// Output(s):
// - output: A tensor of size [number of ngrams, number of tokens + 2],
// where 2 tokens are reserved for the padding. If `max_splits` is set, this
// length is <= max_splits, otherwise it is <= `kDefaultMaxSplits`.
// Helper class used for pre-processing the input.
class NGramHashParams {
public:
NGramHashParams(const uint64_t seed,
const std::vector<int>& ngram_lengths,
const std::vector<int>& vocab_sizes,
int max_splits,
bool lower_case_input)
: seed_(seed),
ngram_lengths_(ngram_lengths),
vocab_sizes_(vocab_sizes),
max_splits_(max_splits),
lower_case_input_(lower_case_input) {}
TfLiteStatus PreprocessInput(const TfLiteTensor* input_t,
TfLiteContext* context) {
if (input_t->bytes == 0) {
context->ReportError(context, "Empty input not supported.");
return kTfLiteError;
}
// Do sanity checks on the input.
if (ngram_lengths_.empty()) {
context->ReportError(context, "`ngram_lengths` must be non-empty.");
return kTfLiteError;
}
if (vocab_sizes_.empty()) {
context->ReportError(context, "`vocab_sizes` must be non-empty.");
return kTfLiteError;
}
if (ngram_lengths_.size() != vocab_sizes_.size()) {
context->ReportError(
context,
"Sizes of `ngram_lengths` and `vocab_sizes` must be the same.");
return kTfLiteError;
}
if (max_splits_ <= 0) {
context->ReportError(context, "`max_splits` must be > 0.");
return kTfLiteError;
}
// Obtain and tokenize the input.
StringRef input_ref = GetString(input_t, /*string_index=*/0);
if (lower_case_input_) {
std::string lower_cased_str;
LowercaseUnicodeStr(input_ref.str, input_ref.len, &lower_cased_str);
tokenized_output_ =
Tokenize(lower_cased_str.c_str(), input_ref.len, max_splits_,
/*exclude_nonalphaspace_tokens=*/true);
} else {
tokenized_output_ = Tokenize(input_ref.str, input_ref.len, max_splits_,
/*exclude_nonalphaspace_tokens=*/true);
}
return kTfLiteOk;
}
uint64_t GetSeed() const { return seed_; }
int GetNumTokens() const { return tokenized_output_.tokens.size(); }
int GetNumNGrams() const { return ngram_lengths_.size(); }
const std::vector<int>& GetNGramLengths() const { return ngram_lengths_; }
const std::vector<int>& GetVocabSizes() const { return vocab_sizes_; }
const TokenizedOutput& GetTokenizedOutput() const {
return tokenized_output_;
}
TokenizedOutput tokenized_output_;
private:
const uint64_t seed_;
std::vector<int> ngram_lengths_;
std::vector<int> vocab_sizes_;
const int max_splits_;
const bool lower_case_input_;
};
// Convert the TypedVector into a regular std::vector.
std::vector<int> GetIntVector(TypedVector typed_vec) {
std::vector<int> vec(typed_vec.size());
for (size_t j = 0; j < typed_vec.size(); j++) {
vec[j] = typed_vec[j].AsInt32();
}
return vec;
}
void GetNGramHashIndices(NGramHashParams* params, int32_t* data) {
const int max_unicode_length = params->GetNumTokens();
const auto ngram_lengths = params->GetNGramLengths();
const auto vocab_sizes = params->GetVocabSizes();
const auto& tokenized_output = params->GetTokenizedOutput();
const auto seed = params->GetSeed();
// Compute for each ngram.
for (size_t ngram = 0; ngram < ngram_lengths.size(); ngram++) {
const int vocab_size = vocab_sizes[ngram];
const int ngram_length = ngram_lengths[ngram];
// Compute for each token within the input.
for (size_t start = 0; start < tokenized_output.tokens.size(); start++) {
// Compute the number of bytes for the ngram starting at the given
// token.
int num_bytes = 0;
for (size_t i = start;
i < tokenized_output.tokens.size() && i < (start + ngram_length);
i++) {
num_bytes += tokenized_output.tokens[i].second;
}
// Compute the hash for the ngram starting at the token.
//
// TODO(https://crbug.com/902789): Murmur2 has only 2 remaining uses in
// Chrome. Migrate to a different hash that's more widely used in future
// versions of the mode and also supports 32/64 bit platforms
// seamlessly. Anything over num_bytes = 7 can overflow on 32-bit. By
// limiting to 7, this may truncate the last byte of the input and result
// in a slightly different hash but impact should be minimal.
const auto str_hash = MurmurHash64A(
tokenized_output.str.c_str() + tokenized_output.tokens[start].first,
std::min(num_bytes, 7), seed);
// Map the hash to an index in the vocab.
data[ngram * max_unicode_length + start] = (str_hash % vocab_size) + 1;
}
}
}
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
const uint8_t* buffer_t = reinterpret_cast<const uint8_t*>(buffer);
const Map& m = GetRoot(buffer_t, length).AsMap();
const uint64_t seed = m["seed"].AsInt64();
const std::vector<int> ngram_lengths =
GetIntVector(m["ngram_lengths"].AsTypedVector());
const std::vector<int> vocab_sizes =
GetIntVector(m["vocab_sizes"].AsTypedVector());
const int max_splits =
m["max_splits"].IsNull() ? kDefaultMaxSplits : m["max_splits"].AsInt32();
const bool lowercase_input =
m["lowercase_input"].IsNull() ? true : m["lowercase_input"].AsBool();
return new NGramHashParams(seed, ngram_lengths, vocab_sizes, max_splits,
lowercase_input);
}
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<NGramHashParams*>(buffer);
}
TfLiteStatus Resize(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output = tflite::GetOutput(context, node, kOutputLabel);
TF_LITE_ENSURE(context, output != nullptr);
tflite::SetTensorToDynamic(output);
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
NGramHashParams* params = reinterpret_cast<NGramHashParams*>(node->user_data);
TF_LITE_ENSURE_OK(
context, params->PreprocessInput(
tflite::GetInput(context, node, kInputMessage), context));
TfLiteTensor* output = tflite::GetOutput(context, node, kOutputLabel);
TF_LITE_ENSURE(context, output != nullptr);
if (tflite::IsDynamicTensor(output)) {
TfLiteIntArray* output_size = TfLiteIntArrayCreate(3);
output_size->data[0] = 1;
output_size->data[1] = params->GetNumNGrams();
output_size->data[2] = params->GetNumTokens();
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, output, output_size));
} else {
context->ReportError(context, "Output must by dynamic.");
return kTfLiteError;
}
if (output->type == kTfLiteInt32) {
GetNGramHashIndices(params, output->data.i32);
} else {
context->ReportError(context, "Output type must be Int32.");
return kTfLiteError;
}
return kTfLiteOk;
}
} // namespace
namespace translate {
TfLiteRegistration* Register_NGRAM_HASH() {
static TfLiteRegistration r = {Init, Free, Resize, Eval};
return &r;
}
} // namespace translate
| 39.859649 | 80 | 0.692232 | [
"vector"
] |
020b171ba7e5c8c944412742a3953d077a1766a6 | 18,335 | cpp | C++ | pxr/usd/usd/testenv/testUsdCreateAttributeCpp.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 3,680 | 2016-07-26T18:28:11.000Z | 2022-03-31T09:55:05.000Z | pxr/usd/usd/testenv/testUsdCreateAttributeCpp.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 1,759 | 2016-07-26T19:19:59.000Z | 2022-03-31T21:24:00.000Z | pxr/usd/usd/testenv/testUsdCreateAttributeCpp.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 904 | 2016-07-26T18:33:40.000Z | 2022-03-31T09:55:16.000Z | //
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/usd/usd/attribute.h"
#include "pxr/usd/usd/references.h"
#include "pxr/usd/usd/stage.h"
#include "pxr/usd/usd/prim.h"
#include "pxr/usd/sdf/attributeSpec.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/debug.h"
#include "pxr/base/arch/fileSystem.h"
#ifdef PXR_PYTHON_SUPPORT_ENABLED
#include "pxr/base/tf/pySafePython.h"
#endif // PXR_PYTHON_SUPPORT_ENABLED
#include <iostream>
PXR_NAMESPACE_USING_DIRECTIVE
void
TestPrim()
{
SdfPath primPath("/CppFoo");
TfToken prop("Something");
std::string propPath(primPath.GetString() + ".Something");
std::string value = "Foobar";
std::string result = "not Foobar";
VtValue tmp;
ArchUnlinkFile("foo.usdc");
UsdStageRefPtr stage = UsdStage::CreateNew("foo.usdc");
SdfLayerHandle layer = stage->GetRootLayer();
{
// Listing fields for a property on a non-existent prim path should not
// post errors (bug 90170).
TfErrorMark mark;
TF_VERIFY(layer->ListFields(SdfPath("I_Do_Not_Exist.attribute")).empty());
TF_VERIFY(mark.IsClean());
}
TF_VERIFY(stage->OverridePrim(primPath),
"Failed to create prim at %s",
primPath.GetText());
UsdPrim prim(stage->GetPrimAtPath(primPath));
TF_VERIFY(prim,
"Failed to get Prim from %s",
primPath.GetText());
TF_VERIFY(prim.CreateAttribute(prop, SdfValueTypeNames->String),
"Failed to create property at %s",
propPath.c_str());
TF_VERIFY(prim.GetAttribute(prop).Set(VtValue(value), UsdTimeCode(0.0)),
"Failed to set property at %s",
propPath.c_str());
TF_VERIFY(prim.GetAttribute(prop).Get(&tmp, UsdTimeCode(0.0)),
"Failed to get property at %s",
propPath.c_str());
TF_VERIFY(tmp.IsHolding<std::string>(),
"Invalid type for value of property %s",
propPath.c_str());
result = tmp.UncheckedGet<std::string>();
TF_VERIFY(result == value,
"Values do not match for %s, %s != %s",
propPath.c_str(),
result.c_str(),
value.c_str());
}
void
TestIsDefined()
{
// This tests the functionality of UsdAttribute::IsDefined.
//
// It has the ability to specify a target layer, so here we will create an
// attribute in a weak layer, reference it into a stronger layer and then
// assert that it wasn't defined in the strong layer.
//
// Next, we set a value in the stronger layer, which implicitly must define
// the attribute, and then assert that the attribute exists in both layers.
SdfLayerRefPtr weakLayer = SdfLayer::CreateNew("IsDefined_weak.usd");
SdfLayerRefPtr strongLayer = SdfLayer::CreateNew("IsDefined_strong.usd");
//
// Weak Layer: Create prim and attribute.
//
UsdStageRefPtr stage = UsdStage::Open(weakLayer->GetIdentifier());
UsdPrim p = stage->OverridePrim(SdfPath("/Parent"));
TfToken attr1("attr1");
TF_VERIFY(!p.GetAttribute(attr1).IsDefined());
TF_VERIFY(p.CreateAttribute(attr1, SdfValueTypeNames->String));
//
// Strong Layer: Create prim and a reference to weak layer.
//
stage = UsdStage::Open(strongLayer->GetIdentifier());
p = stage->OverridePrim(SdfPath("/Parent"));
p.GetReferences().AddReference(
SdfReference(weakLayer->GetIdentifier(), SdfPath("/Parent")));
//
// Now that we've referenced in the weak layer, make sure our definition
// assumptions hold.
//
TF_VERIFY(p.GetAttribute(attr1).IsDefined());
TF_VERIFY(p.GetAttribute(attr1).IsAuthoredAt(weakLayer));
TF_VERIFY(!p.GetAttribute(attr1).IsAuthoredAt(strongLayer));
//
// Now set a value and verify that the attr is defined everywhere.
//
TF_VERIFY(p.GetAttribute(attr1).Set("foo"));
TF_VERIFY(p.GetAttribute(attr1).IsDefined());
TF_VERIFY(p.GetAttribute(attr1).IsAuthoredAt(weakLayer));
TF_VERIFY(p.GetAttribute(attr1).IsAuthoredAt(strongLayer));
}
class ExpectedError {
public:
ExpectedError() {
std::cerr << "--- BEGIN EXPECTED ERROR ---\n";
}
~ExpectedError() {
std::cerr << "--- END EXPECTED ERROR ---\n";
TF_VERIFY(!_mark.IsClean());
}
private:
TfErrorMark _mark;
};
void
VerifyTimeSampleRange(UsdAttribute const & attr, size_t expectedNumSamples,
double expectedMin = 0, double expectedMax = 0)
{
std::vector<double> samples;
if (!TF_VERIFY(attr.GetTimeSamples(&samples)))
return;
TF_VERIFY(expectedNumSamples == samples.size());
double upper=0., lower=0.;
bool hasTimeSamples=false;
attr.GetBracketingTimeSamples((expectedMin + expectedMax) / 2.0,
&lower, &upper, &hasTimeSamples);
size_t numSamples = attr.GetNumTimeSamples();
// Break-out verifies for better reporting.
if (expectedNumSamples == 0) {
TF_VERIFY(samples.empty());
TF_VERIFY(!hasTimeSamples);
TF_VERIFY(numSamples==0);
} else {
TF_VERIFY(!samples.empty());
TF_VERIFY(hasTimeSamples);
TF_VERIFY(numSamples == expectedNumSamples);
TF_VERIFY(expectedMin == samples.front());
TF_VERIFY(expectedMax == samples.back());
TF_VERIFY(expectedMin == lower);
TF_VERIFY(expectedMax == upper);
}
}
void
TestValueMutation(std::string const & layerTag)
{
UsdStageRefPtr stage = UsdStage::CreateInMemory(layerTag);
UsdPrim prim = stage->OverridePrim(SdfPath("/APrim"));
TfToken attrNameToken("attr1");
UsdAttribute attr = prim.CreateAttribute(attrNameToken, SdfValueTypeNames->String);
std::string value;
// Empty initial state
TF_VERIFY(!attr.Get(&value));
// Ensure that attempting to set a value with incorrect type issues an
// error.
{ ExpectedError err; TF_AXIOM(!attr.Set(1.234)); }
// Make sure clear doesn't do anything crazy before authoring values
TF_VERIFY(attr.ClearAtTime(1.0));
TF_VERIFY(attr.ClearDefault());
TF_VERIFY(attr.Clear());
// Has
TF_VERIFY(!attr.HasValue());
TF_VERIFY(!attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
// We should safely handle non-existant attributes as well
UsdAttribute bogusAttr = prim.GetAttribute(TfToken("Non_Existing_Attribute"));
TF_VERIFY(bogusAttr.Clear());
TF_VERIFY(bogusAttr.ClearAtTime(1.0));
TF_VERIFY(bogusAttr.ClearDefault());
//
// Test exclusively with UsdTimeCode::Default()
//
// Set
TF_VERIFY(attr.Set("foo bar"));
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
// Get
TF_VERIFY(attr.Get(&value));
TF_VERIFY(value == "foo bar");
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Clear a time, it should leave the default intact
TF_VERIFY(attr.ClearAtTime(1.0));
TF_VERIFY(attr.Get(&value));
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Now clear the default
TF_VERIFY(attr.ClearDefault());
TF_VERIFY(!attr.Get(&value));
// Has
TF_VERIFY(!attr.HasValue());
TF_VERIFY(!attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
//
// With a single time sample
//
// Set
TF_VERIFY(attr.Set("time=1", 1.0));
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 1, 1.0, 1.0);
// Get
TF_VERIFY(attr.Get(&value, 1.0));
TF_VERIFY(value == "time=1");
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Clear the default, it should leave the time intact
TF_VERIFY(attr.ClearDefault());
TF_VERIFY(attr.Get(&value, 1.0));
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 1, 1, 1);
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Now clear the time value
TF_VERIFY(attr.ClearAtTime(1.0));
TF_VERIFY(!attr.Get(&value, 1.0));
// Has
TF_VERIFY(!attr.HasValue());
TF_VERIFY(!attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
//
// With multiple time samples
//
// Set
TF_VERIFY(attr.Set("time=1", 1.0));
TF_VERIFY(attr.Set("time=2", 2.0));
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 2, 1, 2);
// Get
TF_VERIFY(attr.Get(&value, 1.0));
TF_VERIFY(value == "time=1");
TF_VERIFY(attr.Get(&value, 2.0));
TF_VERIFY(value == "time=2");
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Clear the default, it should leave the time intact
TF_VERIFY(attr.ClearDefault());
TF_VERIFY(attr.Get(&value, 1.0));
TF_VERIFY(value == "time=1");
TF_VERIFY(attr.Get(&value, 2.0));
TF_VERIFY(value == "time=2");
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Now clear the time=1 value
TF_VERIFY(attr.ClearAtTime(1.0));
TF_VERIFY(attr.Get(&value, 1.0));
TF_VERIFY(value == "time=2");
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 1, 2, 2);
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Now clear the time=2 value
TF_VERIFY(attr.ClearAtTime(2.0));
TF_VERIFY(!attr.Get(&value, 2.0));
// Has
TF_VERIFY(!attr.HasValue());
TF_VERIFY(!attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
//
// With multiple time samples and a default value
//
// Set
TF_VERIFY(attr.Set("time=default"));
TF_VERIFY(attr.Set("time=1", 1.0));
TF_VERIFY(attr.Set("time=2", 2.0));
// Get
TF_VERIFY(attr.Get(&value));
TF_VERIFY(value == "time=default");
TF_VERIFY(attr.Get(&value, 1.0));
TF_VERIFY(value == "time=1");
TF_VERIFY(attr.Get(&value, 2.0));
TF_VERIFY(value == "time=2");
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 2, 1, 2);
// Clear t=1, it should leave t=2 and t=default
TF_VERIFY(attr.ClearAtTime(1.0));
TF_VERIFY(attr.Get(&value, 1.0));
// Because of held-value interpolation, and because we cleared the value at 1.0,
// we expect value at 1.0 to be "time=2"
TF_VERIFY(value == "time=2");
TF_VERIFY(attr.Get(&value));
TF_VERIFY(value == "time=default");
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 1, 2, 2);
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Now clear the time=2 value, should leave t=default
TF_VERIFY(attr.ClearAtTime(2.0));
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
// Get
TF_VERIFY(attr.Get(&value, 1.0));
TF_VERIFY(value == "time=default");
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
// Now clear the default value
TF_VERIFY(attr.ClearDefault());
TF_VERIFY(!attr.Get(&value, 2.0));
// Has
TF_VERIFY(!attr.HasValue());
TF_VERIFY(!attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
// Get with wrong type.
{ double d; TF_VERIFY(!attr.Get<double>(&d)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 1.0)); }
{ double d; TF_VERIFY(!attr.Get<double>(&d, 2.0)); }
//
// Multiple time samples and single call to Clear
//
// Set
TF_VERIFY(attr.Set("time=default"));
TF_VERIFY(attr.Set("time=1", 1.0));
TF_VERIFY(attr.Set("time=2", 2.0));
// Get
TF_VERIFY(attr.Get(&value));
TF_VERIFY(value == "time=default");
TF_VERIFY(attr.Get(&value, 1.0));
TF_VERIFY(value == "time=1");
TF_VERIFY(attr.Get(&value, 2.0));
TF_VERIFY(value == "time=2");
// Has
TF_VERIFY(attr.HasValue());
TF_VERIFY(attr.HasAuthoredValue());
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 2, 1, 2);
// Clear() should remove all values
TF_VERIFY(attr.Clear());
TF_VERIFY(!attr.Get(&value, 1.0));
TF_VERIFY(!attr.Get(&value, 2.0));
TF_VERIFY(!attr.Get(&value));
// Has
TF_VERIFY(!attr.HasValue());
TF_VERIFY(!attr.HasAuthoredValue());
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->Default));
TF_VERIFY(!attr.HasMetadata(SdfFieldKeys->TimeSamples));
VerifyTimeSampleRange(attr, 0);
}
void
TestQueryTimeSample()
{
SdfLayerRefPtr l = SdfLayer::CreateAnonymous("f.usdc");
SdfPrimSpecHandle p = SdfPrimSpec::New(l, "Foo", SdfSpecifierDef, "Scope");
SdfAttributeSpecHandle a = SdfAttributeSpec::New(p, "attr",
SdfValueTypeNames->String);
SdfTimeSampleMap tsm;
tsm[1.0] = "Foo";
a->SetInfo(TfToken("timeSamples"),VtValue(tsm));
SdfPath path("/Foo.attr");
l->QueryTimeSample(path, 1.0);
}
void
TestVariability()
{
// XXX When bug/100734 is addressed, we should also test here
// that authoring to a uniform attribute creates no timeSamples
UsdStageRefPtr s = UsdStage::CreateInMemory();
UsdPrim foo = s->OverridePrim(SdfPath("/foo"));
UsdAttribute varAttr = foo.CreateAttribute(TfToken("varyingAttr"),
SdfValueTypeNames->TokenArray);
TF_VERIFY(varAttr.GetVariability() == SdfVariabilityVarying);
UsdAttribute uniformAttr = foo.CreateAttribute(TfToken("uniformAttr"),
SdfValueTypeNames->Token,
/* custom = */ true,
SdfVariabilityUniform);
TF_VERIFY(uniformAttr.GetVariability() == SdfVariabilityUniform);
}
int main()
{
TestPrim();
TestIsDefined();
TestValueMutation("foo.usda");
TestValueMutation("foo.usdc");
TestQueryTimeSample();
TestVariability();
#ifdef PXR_PYTHON_SUPPORT_ENABLED
TF_AXIOM(!Py_IsInitialized());
#endif // PXR_PYTHON_SUPPORT_ENABLED
}
| 34.20709 | 87 | 0.646741 | [
"vector"
] |
0210fc1f74e947f62c66986381912f812c9ae07b | 6,276 | cpp | C++ | tst/ga/uRigid.cpp | transpixel/TPQZcam | b44a97d44b49e9aa76c36efb6e4102091ff36c67 | [
"MIT"
] | 1 | 2017-06-01T00:21:16.000Z | 2017-06-01T00:21:16.000Z | tst/ga/uRigid.cpp | transpixel/TPQZcam | b44a97d44b49e9aa76c36efb6e4102091ff36c67 | [
"MIT"
] | 3 | 2017-06-01T00:26:16.000Z | 2020-05-09T21:06:27.000Z | testga/uRigid.cpp | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | null | null | null | //
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// 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.
//
/*! \file
\brief This file contains unit test for ga::Rigid
*/
#include "libga/Rigid.h"
#include "libio/stream.h"
#include "libga/ga.h"
#include <iostream>
#include <sstream>
#include <string>
namespace
{
//! Check for common functions
std::string
ga_Rigid_test0
()
{
std::ostringstream oss;
ga::Rigid const aNull;
if (aNull.isValid())
{
oss << "Failure of null value test" << std::endl;
oss << "infoString: " << aNull.infoString("aNull") << std::endl;
}
return oss.str();
}
//! Check basic transformation operations
std::string
ga_Rigid_test1
()
{
std::ostringstream oss;
// check identity transform
{
using namespace ga;
Rigid const ident(Rigid::identity());
if (! ident.isValid())
{
oss << "Failure of identity validity test" << std::endl;
oss << ident.infoString("ident") << std::endl;
}
Vector const expVec(13., -14., 3.);
Vector const gotVec(ident(expVec));
if (! gotVec.nearlyEquals(expVec))
{
oss << "Failure of identity transform test" << std::endl;
}
}
// check basic transformation properies
{
using namespace ga;
//! [ExampleCode]
Vector const station(-7., 5., 11.);
BiVector const pAngle(.625*math::pi * unit(BiVector(17., -19., 23.)));
Rigid const xForward(station, Pose(pAngle));
Rigid const xInverse(xForward.inverse());
//! [ExampleCode]
Spinor const spinR(exp(.5 * pAngle));
Vector const vecFrom(-17., 27., 5.);
Vector const vecInto(rotated(spinR, (vecFrom - station)));
// Vector const vecInto(spinR * (vecFrom - station) * spinR.reverse());
Vector const gotInto(xForward(vecFrom));
Vector const gotFrom(xInverse(vecInto));
if (! ga::nearlyEquals(gotInto, vecInto))
{
oss << "Failure of xform forward test" << std::endl;
oss << vecInto.infoString("exp") << std::endl;
oss << gotInto.infoString("got") << std::endl;
}
if (! ga::nearlyEquals(gotFrom, vecFrom))
{
oss << "Failure of xform inverse test" << std::endl;
oss << vecFrom.infoString("exp") << std::endl;
oss << gotFrom.infoString("got") << std::endl;
}
}
// check compositions
{
using namespace ga;
Vector const tA(7., -5., 11.);
Vector const tB(-11., 3., 2.);
BiVector const pAngleA(-.625*math::pi * unit(BiVector( 7., -3., -5.)));
BiVector const pAngleB( .125*math::pi * unit(BiVector(11., -2., 3.)));
Rigid const xBwrtA(tA, Pose(pAngleA));
Rigid const xCwrtB(tB, Pose(pAngleB));
Rigid const xCwrtA(xCwrtB * xBwrtA);
Vector const vecInA(-27., 29., -17);
Vector const expVecInC(xCwrtB(xBwrtA(vecInA)));
Vector const gotVecInC(xCwrtA(vecInA));
if (! ga::nearlyEquals(gotVecInC, expVecInC))
{
oss << "Failure of composition test" << std::endl;
oss << expVecInC.infoString("expVecInC") << std::endl;
oss << gotVecInC.infoString("gotVecInC") << std::endl;
}
}
return oss.str();
}
//! Check composite transformations more generally
std::string
ga_Rigid_test2
()
{
std::ostringstream oss;
constexpr double qt{ math::qtrTurn };
// define a round trip with easy physical interpretations
ga::Vector const locAwA( 0., 0., 0.);
ga::Vector const locBwA( 3., 0., 0.);
ga::Vector const locCwB( 0., 5., 0.);
ga::Vector const locDwC( 0., 0., 7.);
ga::Vector const locEwD( 4., 0., 5.);
ga::BiVector const bivAwA( 0., 0., 0.);
ga::BiVector const bivBwA( 0., -qt, 0.);
ga::BiVector const bivCwB( 0., 0., -qt);
ga::BiVector const bivDwC( 0., qt, 0.);
ga::BiVector const bivEwD(-qt, 0., 0.);
// form into orientations
ga::Rigid const oriAwA( locAwA, ga::Pose(bivAwA) );
ga::Rigid const oriBwA( locBwA, ga::Pose(bivBwA) );
ga::Rigid const oriCwB( locCwB, ga::Pose(bivCwB) );
ga::Rigid const oriDwC( locDwC, ga::Pose(bivDwC) );
ga::Rigid const oriEwD( locEwD, ga::Pose(bivEwD) );
// check some simple composition operations
ga::Rigid const oriCwA{ oriCwB * oriBwA };
ga::Rigid const oriDwA{ oriDwC * oriCwB * oriBwA };
ga::Rigid const oriEwA{ oriEwD * oriDwC * oriCwB * oriBwA };
if (! oriEwA.nearlyEquals(ga::Rigid::identity()))
{
oss << "Failure of orientation composition full trip test" << '\n';
oss << dat::infoString(oriAwA, "oriAwA") << std::endl;
oss << dat::infoString(oriBwA, "oriBwA") << std::endl;
oss << dat::infoString(oriCwA, "oriCwA") << std::endl;
oss << dat::infoString(oriDwA, "oriDwA") << std::endl;
oss << dat::infoString(oriEwA, "oriEwA") << std::endl;
}
// check a few composition and inversion combinations
ga::Rigid const oriDwE{ oriEwD.inverse() };
ga::Rigid const oriAwB{ oriBwA.inverse() };
ga::Rigid const oriDwB1{ oriDwE * oriEwA *oriAwB };
ga::Rigid const oriDwB2{ oriDwC * oriCwB };
if (! oriDwB2.nearlyEquals(oriDwB1))
{
oss << "Failure of partial inversion test" << std::endl;
}
return oss.str();
}
}
//! Unit test for ga::Rigid
int
main
( int const /*argc*/
, char const * const * const /*argv*/
)
{
std::ostringstream oss;
// run tests
oss << ga_Rigid_test0();
oss << ga_Rigid_test1();
oss << ga_Rigid_test2();
// check/report results
std::string const errMessages(oss.str());
if (! errMessages.empty())
{
io::err() << errMessages << std::endl;
return 1;
}
return 0;
}
| 27.647577 | 73 | 0.666507 | [
"vector",
"transform"
] |
0211d6c34321c04e07f0d716aebfc63b23ff9251 | 1,386 | cpp | C++ | VoxelEngine/Classes/RenderNode.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | VoxelEngine/Classes/RenderNode.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | VoxelEngine/Classes/RenderNode.cpp | bsy6766/VoxelEngine | d822d8bcc3bf5609bdce2fdc2ef5154994bc23f1 | [
"FTL",
"BSL-1.0",
"Zlib"
] | null | null | null | // pch
#include "PreCompiled.h"
#include "RenderNode.h"
Voxel::UI::RenderNode::RenderNode(const std::string & name)
: TransformNode(name)
, program(nullptr)
, vao(0)
, texture(nullptr)
, color(1.0f)
{}
Voxel::UI::RenderNode::~RenderNode()
{
std::cout << "~RenderNode() " + name + "\n";
if (vao)
{
// Delte array
std::cout << "vao = " << vao << "\n";
glDeleteVertexArrays(1, &vao);
vao = 0;
}
#if V_DEBUG && V_DEBUG_DRAW_UI_BOUNDING_BOX
if (bbVao)
{
// Delte array
glDeleteVertexArrays(1, &bbVao);
}
#endif
}
void Voxel::UI::RenderNode::setColor(const glm::vec3 & color)
{
this->color = glm::clamp(color, 0.0f, 1.0f);
}
glm::vec3 Voxel::UI::RenderNode::getColor() const
{
return color;
}
void Voxel::UI::RenderNode::render()
{
if (children.empty())
{
if (visibility)
{
renderSelf();
}
}
else
{
if (visibility)
{
auto children_it = children.begin();
auto beginZOrder = ((children_it)->first).getGlobalZOrder();
if (beginZOrder < 0)
{
// has negative ordered children
for (; ((children_it)->first).getGlobalZOrder() < 0; children_it++)
{
((children_it)->second)->render();
}
}
// else, doesn't have negative ordered children
// Render self
renderSelf();
// Render positive
for (; children_it != children.end(); children_it++)
{
((children_it)->second)->render();
}
}
}
} | 17.325 | 71 | 0.611833 | [
"render"
] |
02143463623e938b5726d63a6104cca4cfd3bb49 | 2,332 | cpp | C++ | src/code-examples/chapter-11/contained-type/main.cpp | nhatvu148/helpers | 1a6875017cf39790dfe40ecec9dcee4410b1d89e | [
"MIT"
] | null | null | null | src/code-examples/chapter-11/contained-type/main.cpp | nhatvu148/helpers | 1a6875017cf39790dfe40ecec9dcee4410b1d89e | [
"MIT"
] | null | null | null | src/code-examples/chapter-11/contained-type/main.cpp | nhatvu148/helpers | 1a6875017cf39790dfe40ecec9dcee4410b1d89e | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <string>
#include <type_traits>
#include "type_utils.h"
// Function that sums all items in an iterable collection
template < typename C
, typename R = contained_type<C>
>
R sum_iterable(const C &collection)
{
std::cout << "This is sum_iterable\n";
return std::accumulate(
begin(collection),
end(collection),
R());
}
// Function that sums all items in a collection
// that has a nested value_type definition
template < typename C
, typename R = typename C::value_type
>
R sum_collection(const C &collection)
{
std::cout << "This is sum_collection\n";
return std::accumulate(
begin(collection),
end(collection),
R());
}
// Function that sums all items in a collection
// which first tries to use C::value_type and then
// contained_type<C>
template <typename C>
auto sum(const C &collection)
{
if constexpr (has_value_type<C>()) {
return sum_collection(collection);
} else if constexpr (is_iterable<C>()) {
return sum_iterable(collection);
} else {
static_assert(false_<C>(), "sum can be called only on collections");
}
}
// Meta-function that checks whether two types
// are identical
template <typename T1, typename T2>
struct is_same: std::false_type {};
template <typename T>
struct is_same<T, T>: std::true_type {};
int main(int argc, char *argv[])
{
// Uncomment this to make the compiler write the
// exact result of the contained_type meta-function
// error<contained_type<std::vector<std::string>>>();
// Asserting that std::vector<std::string> contains
// values of type std::string
static_assert(
is_same<
contained_type<std::vector<std::string>>,
std::string
>(), "Expected the contained_type to return std::string");
// Calling the function sum on a vector of ints.
// The result will be an int
std::vector<int> xs { 1, 2, 3, 4 };
std::cout << sum_iterable(xs) << std::endl;
std::cout << sum_collection(xs) << std::endl;
std::cout << sum(xs) << std::endl;
// Uncomment this to trigger the static_assert in the
// sum function
// sum(1);
return 0;
}
| 25.075269 | 76 | 0.635077 | [
"vector"
] |
021676d4bdc0fe0b40a61233c5b729c31eb70cea | 97,894 | cpp | C++ | Code/src/sedvisualizerplot.cpp | scigeliu/ViaLacteaVisualAnalytics | 2ac79301ceaaab0415ec7105b8267552262c7650 | [
"Apache-2.0"
] | 1 | 2021-12-15T15:15:50.000Z | 2021-12-15T15:15:50.000Z | Code/src/sedvisualizerplot.cpp | scigeliu/ViaLacteaVisualAnalytics | 2ac79301ceaaab0415ec7105b8267552262c7650 | [
"Apache-2.0"
] | null | null | null | Code/src/sedvisualizerplot.cpp | scigeliu/ViaLacteaVisualAnalytics | 2ac79301ceaaab0415ec7105b8267552262c7650 | [
"Apache-2.0"
] | null | null | null | #include "sedvisualizerplot.h"
#include "ui_sedvisualizerplot.h"
#include <QInputDialog>
#include "sedplotpointcustom.h"
#include "loadingwidget.h"
#include "visivoimporterdesktop.h"
#include "vlkbquery.h"
#include <QFileDialog>
#include "sedfitgrid_thin.h"
#include "ui_sedfitgrid_thin.h"
#include "ui_sedfitgrid_thick.h"
#include <QSignalMapper>
#include <QCheckBox>
#include <QtConcurrent>
SEDVisualizerPlot::SEDVisualizerPlot(QList<SED *> s, vtkwindow_new *v, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SEDVisualizerPlot)
{
////qDebug()<<"SEDVisualizerPlot created";
ui->setupUi(this);
ui->theorGroupBox->hide();
ui->greyBodyGroupBox->hide();
// QString m_sSettingsFile = QApplication::applicationDirPath()+"/setting.ini";
QString m_sSettingsFile = QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp").append("/setting.ini");
QSettings settings(m_sSettingsFile, QSettings::NativeFormat);
idlPath = settings.value("idlpath", "").toString();
ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes | QCP::iSelectLegend | QCP::iSelectPlottables| QCP::iMultiSelect | QCP::iSelectItems);
sed_list=s;
vtkwin=v;
ui->resultsTableWidget->hide();
ui->resultsTableWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
QAction* addFitAction = new QAction("Add this fit", ui->resultsTableWidget);
ui->resultsTableWidget->addAction(addFitAction);
connect(addFitAction, SIGNAL(triggered()), this, SLOT(addNewTheoreticalFit()));
ui->customPlot->yAxis->setScaleType(QCPAxis::stLogarithmic);
ui->customPlot->yAxis->setScaleLogBase(10);
ui->customPlot->xAxis->setScaleType(QCPAxis::stLogarithmic);
ui->customPlot->xAxis->setScaleLogBase(10);
ui->customPlot->plotLayout()->insertRow(0);
ui->customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(ui->customPlot, "SED"));
ui->customPlot->xAxis->setLabel("Wavelength ["+QString::fromUtf8("\u00b5")+"m]");
ui->customPlot->yAxis->setLabel("Flux [Jy]");
minWavelen=std::numeric_limits<int>::max();;
maxWavelen= std::numeric_limits<int>::min();
minFlux=std::numeric_limits<int>::max();
maxFlux= std::numeric_limits<int>::min();
QString name;
// drawNode(s.at(0)->getRootNode());
for (sedCount=0;sedCount<s.count();sedCount++)
{
//qDebug()<<"SEDVisualizerPlot drawing sed "<<QString::number(sedCount);
sed=s.at(sedCount);
drawNode(sed->getRootNode());
}
double x_deltaRange=(maxWavelen-minWavelen)*0.02;
double y_deltaRange=(maxFlux-minFlux)*0.02;
// ui->customPlot->xAxis->setRange(minWavelen-x_deltaRange, maxWavelen+x_deltaRange);
// ui->customPlot->yAxis->setRange(minFlux-y_deltaRange, maxFlux+y_deltaRange);
ui->customPlot->yAxis->setRange(minFlux-y_deltaRange, maxFlux+y_deltaRange);
ui->customPlot->xAxis->setRange(minWavelen-x_deltaRange, maxWavelen+x_deltaRange);
//qDebug()<<"Wavelen: "<<maxWavelen-minWavelen<<" "<<x_deltaRange;
//qDebug()<<"Flux: "<<maxFlux-minFlux<<" "<<y_deltaRange;
// connect slot that ties some axis selections together (especially opposite axes):
connect(ui->customPlot, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
// connect slots that takes care that when an axis is selected, only that direction can be dragged and zoomed:
connect(ui->customPlot, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(mousePress()));
connect(ui->customPlot, SIGNAL(mouseWheel(QWheelEvent*)), this, SLOT(mouseWheel()));
connect(ui->customPlot, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseRelease()));
// make bottom and left axes transfer their ranges to top and right axes:
connect(ui->customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->xAxis2, SLOT(setRange(QCPRange)));
connect(ui->customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->yAxis2, SLOT(setRange(QCPRange)));
// connect some interaction slots:
connect(ui->customPlot, SIGNAL(titleDoubleClick(QMouseEvent*,QCPPlotTitle*)), this, SLOT(titleDoubleClick(QMouseEvent*,QCPPlotTitle*)));
connect(ui->customPlot, SIGNAL(axisDoubleClick(QCPAxis*,QCPAxis::SelectablePart,QMouseEvent*)), this, SLOT(axisLabelDoubleClick(QCPAxis*,QCPAxis::SelectablePart)));
// connect(ui->customPlot, SIGNAL(legendDoubleClick(QCPLegend*,QCPAbstractLegendItem*,QMouseEvent*)), this, SLOT(legendDoubleClick(QCPLegend*,QCPAbstractLegendItem*)));
// connect slot that shows a message in the status bar when a graph is clicked:
connect(ui->customPlot, SIGNAL(plottableClick(QCPAbstractPlottable*,QMouseEvent*)), this, SLOT(graphClicked(QCPAbstractPlottable*)));
// setup policy and connect slot for context menu popup:
ui->customPlot->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->customPlot, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuRequest(QPoint)));
modelFitBands.insert("wise1",3.37);
modelFitBands.insert("i1",3.6);
modelFitBands.insert("i2",4.5);
modelFitBands.insert("wise2",4.62);
modelFitBands.insert("i3",5.8);
modelFitBands.insert("i4",8);
modelFitBands.insert("wise3",12.08);
modelFitBands.insert("wise4",22.194);
modelFitBands.insert("m1",24);
modelFitBands.insert("pacs1",70);
modelFitBands.insert("pacs2",100);
modelFitBands.insert("pacs3",160);
modelFitBands.insert("spir1",250);
modelFitBands.insert("spir2",350);
modelFitBands.insert("spir3",500);
modelFitBands.insert("laboc",870);
modelFitBands.insert("bol11",1100);
columnNames.append("id");
columnNames.append("clump_mass");
columnNames.append("compact_mass_fraction");
columnNames.append("clump_upper_age");
columnNames.append("dust_temp");
columnNames.append("bolometric_luminosity");
columnNames.append("n_star_tot");
columnNames.append("m_star_tot");
columnNames.append("n_star_zams");
columnNames.append("m_star_zams");
columnNames.append("l_star_tot");
columnNames.append("l_star_zams");
columnNames.append("zams_luminosity_1");
columnNames.append("zams_mass_1");
columnNames.append("zams_temperature_1");
columnNames.append("zams_luminosity_2");
columnNames.append("zams_mass_2");
columnNames.append("zams_temperature_2");
columnNames.append("zams_luminosity_3");
columnNames.append("zams_mass_3");
columnNames.append("zams_temperature_3");
columnNames.append("m1");
columnNames.append("pacs1");
columnNames.append("pacs2");
columnNames.append("pacs3");
columnNames.append("spir1");
columnNames.append("spir2");
columnNames.append("spir3");
columnNames.append("laboc");
columnNames.append("bol11");
columnNames.append("CHI2");
columnNames.append("DIST");
resultsOutputColumn.insert("id",-1);
resultsOutputColumn.insert("clump_mass",-1);
resultsOutputColumn.insert("compact_mass_fraction",-1);
resultsOutputColumn.insert("clump_upper_age",-1);
resultsOutputColumn.insert("dust_temp",-1);
resultsOutputColumn.insert("bolometric_luminosity",-1);
resultsOutputColumn.insert("n_star_tot",-1);
resultsOutputColumn.insert("m_star_tot",-1);
resultsOutputColumn.insert("n_star_zams",-1);
resultsOutputColumn.insert("m_star_zams",-1);
resultsOutputColumn.insert("l_star_tot",-1);
resultsOutputColumn.insert("l_star_zams",-1);
resultsOutputColumn.insert("zams_luminosity_1",-1);
resultsOutputColumn.insert("zams_mass_1",-1);
resultsOutputColumn.insert("zams_temperature_1",-1);
resultsOutputColumn.insert("zams_luminosity_2",-1);
resultsOutputColumn.insert("zams_mass_2",-1);
resultsOutputColumn.insert("zams_temperature_2",-1);
resultsOutputColumn.insert("zams_luminosity_3",-1);
resultsOutputColumn.insert("zams_mass_3",-1);
resultsOutputColumn.insert("zams_temperature_3",-1);
resultsOutputColumn.insert("m1",-1);
resultsOutputColumn.insert("pacs1",-1);
resultsOutputColumn.insert("pacs2",-1);
resultsOutputColumn.insert("pacs3",-1);
resultsOutputColumn.insert("spir1",-1);
resultsOutputColumn.insert("spir2",-1);
resultsOutputColumn.insert("spir3",-1);
resultsOutputColumn.insert("laboc",-1);
resultsOutputColumn.insert("bol11",-1);
resultsOutputColumn.insert("CHI2",-1);
resultsOutputColumn.insert("DIST",-1);
QString libPath= QFileInfo(idlPath).absolutePath().append("/../lib/")+":"+qApp->applicationDirPath().append("/script_idl/")+":"+qApp->applicationDirPath().append("/script_idl/astrolib") ;
setenv("IDL_PATH",libPath.toStdString().c_str(),0);
ui->generatedSedBox->setHidden(true);
nSED=0;
multiSelectMOD=false;
temporaryMOD=false;
doubleClicked=false;
temporaryRow=0;
this->setFocus();
this->activateWindow();
//Save QList<SED *> s to a file to be loaded later on
QFile sedFile(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SEDList.dat"));
if(!sedFile.exists()){
sedFile.open(QIODevice::WriteOnly);
QDataStream out(&sedFile);
out << sed_list; // serialize the object
}
sedFile.flush();
sedFile.close();
for(int i=0;i<ui->customPlot->graphCount();i++)
{
originalGraphs.push_back(ui->customPlot->graph(i));
}
ui->histogramPlot->hide();
connect(ui->resultsTableWidget->horizontalHeader(), SIGNAL( sectionClicked( int ) ), this, SLOT( sectionClicked( int ) ) );
}
QDataStream &operator<<(QDataStream &out, QList<SED *> &sedlist)
{
out<<sedlist.count();
foreach(SED* sed, sedlist){
out<<sed;
}
return out;
}
void SEDVisualizerPlot::setTitle(QString t)
{
this->setWindowTitle(t);
}
void SEDVisualizerPlot::setDistances(double dist)
{
ui->distTheoLineEdit->setText(QString::number(dist));
}
void SEDVisualizerPlot::sectionClicked ( int index )
{
if(index>=1&&index<=4){
ui->histogramPlot->clearPlottables();
//qDebug() << "Clicked Index "<<index;
QVector<double> values=sedFitValues.value(index+1);
double min,max,bin_width;
QString title;
if(index==1){//clump_mass
//min=10;
//max=200000;
min=1;
max=5.3;
bin_width=0.1;
title="clump_mass (log scale)";
}
if(index==2){//compact_mass_fraction
min=0;
max=0.5;
bin_width=0.025;
title="compact_mass_fraction";
}
if(index==3){//clump_upper_age
min=4;
max=5.7;
bin_width=0.25;
title="clump_upper_age (log scale)";
}
if(index==4){//dust_temp
min=5;
max=50;
bin_width=1;
title="dust_temp";
}
ui->histogramPlot->show();
int bin_count=(max-min)/bin_width;
QVector<double> x1(bin_count), y1(bin_count);
for (int i=0; i<values.size(); ++i)
{
int bin;
if(index==1){
bin = (int)((log10(values.at(i)) - min) / bin_width);
}else if(index==3){
bin = (int)((log10(values.at(i)*100000) - min) / bin_width);
}else{
bin = (int)((values.at(i) - min) / bin_width);
}
if(bin>=0 && bin<bin_count){
y1[bin]++;
}
}
x1[0]=min;
for (int i=1; i<bin_count; ++i)
{
x1[i]=x1[i-1]+bin_width;
}
//qDebug()<<x1.size();
QCPBars *bars1 = new QCPBars(ui->histogramPlot->xAxis, ui->histogramPlot->yAxis);
bars1->setWidth(bin_width);
bars1->setData(x1, y1);
ui->histogramPlot->xAxis->setRange(min, max);
ui->histogramPlot->yAxis->setRange(0,values.size());
//if(index==1||index==3){
//ui->histogramPlot->xAxis->setScaleType(QCPAxis::stLogarithmic);
//ui->histogramPlot->xAxis->setScaleLogBase(10);
//}else{
// ui->histogramPlot->xAxis->setScaleType(QCPAxis::stLinear);
//}
//ui->histogramPlot->plotLayout()->insertRow(0);
//ui->histogramPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, title, QFont("sans", 12, QFont::Bold)));
ui->histogramPlot->xAxis->setLabel(title);
ui->histogramPlot->yAxis->setAutoTickStep(false);
ui->histogramPlot->yAxis->setTickStep(1);
ui->histogramPlot->addPlottable(bars1);
ui->histogramPlot->replot();
}else{
QMessageBox msgBox;
msgBox.setText("No histogram available for this values.");
msgBox.exec();
}
}
QDataStream &operator>>(QDataStream &in, QList<SED *> &sedlist)
{
//qDebug()<< "reading SED list";
int count;
in >> count;
//qDebug()<< "SED list size : "<<QString::number(count);
for(int i=0; i<count; i++){
SED * sed=new SED();
in >> sed;
sedlist.push_back(sed);
}
//qDebug()<< "SED list size : "<<QString::number(sedlist.count());
return in;
}
void SEDVisualizerPlot::drawNode( SEDNode *node)
{
//qDebug()<<"drawNode "<<node->getDesignation()<< " esiste "<<visualnode_hash.contains(node->getDesignation());
if(!visualnode_hash.contains(node->getDesignation()))
{
////qDebug()<<"drawNode inside if";
SEDPlotPointCustom *cp = new SEDPlotPointCustom(ui->customPlot,3.5,vtkwin);
if(vtkwin!=0){
if (vtkwin->getDesignation2fileMap().values(node->getDesignation()).length() >0)
{
double r= vtkwin->getEllipseActorList().value( vtkwin->getDesignation2fileMap().value(node->getDesignation()) )->GetProperty()->GetColor()[0];
double g= vtkwin->getEllipseActorList().value( vtkwin->getDesignation2fileMap().value(node->getDesignation()) )->GetProperty()->GetColor()[1];
double b= vtkwin->getEllipseActorList().value( vtkwin->getDesignation2fileMap().value(node->getDesignation()) )->GetProperty()->GetColor()[2];
cp->setColor(QColor(r*255,g*255,b*255));
}
}
cp->setAntialiased(true);
cp->setPos(node->getWavelength(), node->getFlux());
cp->setDesignation(node->getDesignation());
cp->setX(node->getX());
cp->setY(node->getY());
cp->setLat(node->getLat());
cp->setLon(node->getLon());
cp->setErrorFlux(node->getErrFlux());
cp->setEllipse(node->getSemiMinorAxisLength(),node->getSemiMajorAxisLength(),node->getAngle(),node->getArcpix());
cp->setNode(node);
ui->customPlot->addItem(cp);
//connect(ui->customPlot,SIGNAL(mousePress(QMouseEvent*)),cp,SLOT(onMousePress(QMouseEvent*)));
visualnode_hash.insert(node->getDesignation(),cp);
if (node->getWavelength()>maxWavelen)
maxWavelen=node->getWavelength();
if ( node->getWavelength() < minWavelen)
minWavelen=node->getWavelength();
if (node->getFlux()>maxFlux)
maxFlux=node->getFlux();
if ( node->getFlux() < minFlux)
{
minFlux=node->getFlux();
}
all_sed_node.insert(node->getWavelength(),node);
}
// //qDebug()<<"drawNode outside if";
QVector<double> x(2), y(2), y_err(2);
x[0]=node->getWavelength();
y[0]=node->getFlux();
y_err[0]=node->getErrFlux();
// //qDebug()<<"drawNode child count "<<QString::number(node->getChild().count());
for (int i=0;i<node->getChild().count();i++)
{
drawNode(node->getChild().values()[i]);
x[1]=node->getChild().values()[i]->getWavelength();
y[1]=node->getChild().values()[i]->getFlux();
y_err[1]=node->getChild().values()[i]->getErrFlux();
ui->customPlot->addGraph();
ui->customPlot->graph()->setDataValueError(x, y, y_err);
ui->customPlot->graph()->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDot, 1));
ui->customPlot->graph()->setPen(QPen(Qt::black));
ui->customPlot->graph()->setSelectedPen(QPen(Qt::red));
ui->customPlot->graph()->setAntialiased(true);
ui->customPlot->graph()->setErrorType(QCPGraph::etBoth);
}
}
void SEDVisualizerPlot::titleDoubleClick(QMouseEvent* event, QCPPlotTitle* title)
{
Q_UNUSED(event)
// Set the plot title by double clicking on it
bool ok;
QString newTitle = QInputDialog::getText(this, "SED Title", "New SED title:", QLineEdit::Normal, title->text(), &ok);
if (ok)
{
title->setText(newTitle);
ui->customPlot->replot();
}
}
void SEDVisualizerPlot::axisLabelDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part)
{
// Set an axis label by double clicking on it
if (part == QCPAxis::spAxisLabel) // only react when the actual axis label is clicked, not tick label or axis backbone
{
bool ok;
QString newLabel = QInputDialog::getText(this, "QCustomPlot example", "New axis label:", QLineEdit::Normal, axis->label(), &ok);
if (ok)
{
axis->setLabel(newLabel);
ui->customPlot->replot();
}
}
}
void SEDVisualizerPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item)
{
// Rename a graph by double clicking on its legend item
Q_UNUSED(legend)
if (item) // only react if item was clicked (user could have clicked on border padding of legend where there is no item, then item is 0)
{
QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item);
bool ok;
QString newName = QInputDialog::getText(this, "QCustomPlot example", "New graph name:", QLineEdit::Normal, plItem->plottable()->name(), &ok);
if (ok)
{
plItem->plottable()->setName(newName);
ui->customPlot->replot();
}
}
}
void SEDVisualizerPlot::selectionChanged()
{
if(multiSelectMOD){ // on "multi select mode" prevent a graph to be clicked. Only nodes can be selected.
// //qDebug()<<"selected graph count "<<ui->customPlot->selectedGraphs().count();
for(int i = 0; i < ui->customPlot->graphCount(); ++i)
ui->customPlot->graph(i)->setSelected(false);
}
}
void SEDVisualizerPlot::mouseRelease()
{
}
void SEDVisualizerPlot::mousePress()
{
if(multiSelectMOD){
QList<QCPAbstractItem *> list_items=ui->customPlot->selectedItems();
////qDebug()<<"Selected Items : "<<list_items.size();
}
else{
// //qDebug()<<"pre - # selzionato: " <<ui->customPlot->selectedGraphs().count();
for(int i = 0; i < ui->customPlot->graphCount(); ++i)
ui->customPlot->graph(i)->setSelected(true);
ui->customPlot->replot();
// //qDebug()<<"post - # selzionato: " <<ui->customPlot->selectedGraphs().count();
// //qDebug()<<"# grap: "<<ui->customPlot->graphCount();
}
// if an axis is selected, only allow the direction of that axis to be dragged
// if no axis is selected, both directions may be dragged
if (ui->customPlot->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->customPlot->axisRect()->setRangeDrag(ui->customPlot->xAxis->orientation());
else if (ui->customPlot->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->customPlot->axisRect()->setRangeDrag(ui->customPlot->yAxis->orientation());
else
ui->customPlot->axisRect()->setRangeDrag(Qt::Horizontal|Qt::Vertical);
}
void SEDVisualizerPlot::mouseWheel()
{
// if an axis is selected, only allow the direction of that axis to be zoomed
// if no axis is selected, both directions may be zoomed
if (ui->customPlot->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->customPlot->axisRect()->setRangeZoom(ui->customPlot->xAxis->orientation());
else if (ui->customPlot->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->customPlot->axisRect()->setRangeZoom(ui->customPlot->yAxis->orientation());
else
ui->customPlot->axisRect()->setRangeZoom(Qt::Horizontal|Qt::Vertical);
}
void SEDVisualizerPlot::removeSelectedGraph()
{
if (ui->customPlot->selectedGraphs().size() > 0)
{
ui->customPlot->removeGraph(ui->customPlot->selectedGraphs().first());
ui->customPlot->replot();
}
}
void SEDVisualizerPlot::removeAllGraphs()
{
ui->customPlot->clearGraphs();
ui->customPlot->replot();
}
void SEDVisualizerPlot::contextMenuRequest(QPoint pos)
{
QMenu *menu = new QMenu(this);
menu->setAttribute(Qt::WA_DeleteOnClose);
if (ui->customPlot->legend->selectTest(pos, false) >= 0) // context menu on legend requested
{
menu->addAction("Move to top left", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignLeft));
menu->addAction("Move to top center", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignHCenter));
menu->addAction("Move to top right", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignRight));
menu->addAction("Move to bottom right", this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom|Qt::AlignRight));
menu->addAction("Move to bottom left", this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom|Qt::AlignLeft));
}
else // general context menu on graphs requested
{
if (ui->customPlot->selectedGraphs().size() > 0)
menu->addAction("Remove selected connection", this, SLOT(removeSelectedGraph()));
}
menu->popup(ui->customPlot->mapToGlobal(pos));
}
void SEDVisualizerPlot::graphClicked(QCPAbstractPlottable *plottable)
{
//ui->statusbar->showMessage(QString("Clicked on graph '%1'.").arg(plottable->name()), 1000);
}
SEDVisualizerPlot::~SEDVisualizerPlot()
{
delete ui;
}
void SEDVisualizerPlot::on_actionEdit_triggered()
{
}
void SEDVisualizerPlot::on_actionFit_triggered()
{
}
bool SEDVisualizerPlot::prepareInputForSedFit( SEDNode *node)
{
bool validFit=true;
//qDebug()<<"Selected Items no multi : ";
sedFitInput.insert(node->getWavelength(),node->getFlux());
sedFitInputF= QString::number( node->getFlux() )+sedFitInputF;
sedFitInputErrF= QString::number( node->getErrFlux() )+sedFitInputErrF;
sedFitInputW= QString::number( node->getWavelength() )+sedFitInputW;
sedFitInputFflag ="1"+sedFitInputFflag;
for (int i=0; i<node->getChild().count(); i++)
{
sedFitInputF= ","+sedFitInputF;
sedFitInputErrF= ","+sedFitInputErrF;
sedFitInputW= ","+sedFitInputW;
sedFitInputFflag= ","+sedFitInputFflag;
prepareInputForSedFit(node->getChild().values()[i]);
}
return validFit;
}
bool SEDVisualizerPlot::prepareSelectedInputForSedFit()
{
bool validFit=false;
QMap <double, SEDNode *> selected_sed_map;
QList<QCPAbstractItem *> list_items=ui->customPlot->selectedItems();
for(int i=0;i<list_items.size();i++){
QString className=QString::fromUtf8(list_items.at(i)->metaObject()->className());
QString refName="SEDPlotPointCustom";
////qDebug()<<"Class name :"<<className<<" "<<QString::compare(className,refName);
if(QString::compare(className,refName)==0){
////qDebug()<<"Insert item";
SEDPlotPointCustom * cp=qobject_cast<SEDPlotPointCustom *>(list_items.at(i));
selected_sed_map.insert(cp->getNode()->getWavelength(),cp->getNode());
}
}
//qDebug()<<"Selected Items : "<<selected_sed_map.size();
if(selected_sed_map.size()>=2){
QMap<double, SEDNode *>::iterator iter;
iter=selected_sed_map.begin();
SEDNode *node=iter.value();
sedFitInput.insert(node->getWavelength(),node->getFlux());
sedFitInputF= QString::number( node->getFlux() )+sedFitInputF;
sedFitInputErrF= QString::number( node->getErrFlux() )+sedFitInputErrF;
sedFitInputW= QString::number( node->getWavelength() )+sedFitInputW;
sedFitInputFflag ="1"+sedFitInputFflag;
++iter;
for (; iter!=selected_sed_map.end(); ++iter)
{
node=iter.value();
sedFitInput.insert(node->getWavelength(),node->getFlux());
sedFitInputF= QString::number( node->getFlux() )+","+sedFitInputF;
sedFitInputErrF= QString::number( node->getErrFlux() )+","+sedFitInputErrF;
sedFitInputW= QString::number( node->getWavelength() )+","+sedFitInputW;
sedFitInputFflag ="1,"+sedFitInputFflag;
}
validFit=true;
}
else
{
QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr("Could not execute SED fit with less than 2 points selected.\n\rPlease select more points and try again."));
validFit=false;
}
return validFit;
}
void SEDVisualizerPlot::on_actionLocal_triggered()
{
}
void SEDVisualizerPlot::readSedFitResultsHeader(QString header)
{
////qDebug()<<header;
QList<QString> line_list_string=header.split(',');
QString field;
for(int i=0; i<line_list_string.size();i++){
field=line_list_string.at(i).simplified();
////qDebug()<<field;
if(resultsOutputColumn.contains(field)){
resultsOutputColumn.insert(field,i);
////qDebug()<<field<<"->"<<resultsOutputColumn.value(field);
}
}
}
void SEDVisualizerPlot::readSedFitOutput(QString filename)
{
int id;
double chi2=99999999999;
double tmp;
QString chi_str,id_str,dist_str,clamp_mass_str,clamp_upper_age_str, compact_mass_fraction_str, dust_temp_str;
QMap <double, int> results;
QMap <double, QList<QByteArray> > resultsLines;
QVector<double> clamp_mass;
QVector<double> clamp_upper_age;
QVector<double> compact_mass_fraction;
QVector<double> dust_temp;
//qDebug()<<"filename: "<<filename;
QFile file(filename);
// QFile file(qApp->applicationDirPath()+"/sedfit_output.dat");
if (!file.open(QIODevice::ReadOnly)) {
//qDebug() << file.errorString();
return ;
}
//read, and skip the first line (header)
//file.readLine();
QString header=file.readLine();
outputSedResults.append(header);
readSedFitResultsHeader(header);
// QStringList wordList;
int i=0;
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setRowCount(0);
ui->resultsTableWidget->setColumnCount(columnNames.size());
ui->resultsTableWidget->setHorizontalHeaderLabels(columnNames);
while (!file.atEnd()) {
QByteArray line = file.readLine();
//wordList.append(line.split(',').first());
outputSedResults.append(line);
QList<QByteArray> line_list_string=line.split(',');
////qDebug()<<i<<" line size = "<<line_list_string.length();
QList<QByteArray> tmp_string=line_list_string;
id_str=line_list_string.first().simplified();
dist_str=line_list_string.last().simplified();
line_list_string.removeLast();
chi_str=line_list_string.last().simplified();
resultsLines.insert(chi_str.toDouble(),tmp_string);
clamp_mass_str=line_list_string.at(2).simplified();
clamp_upper_age_str=line_list_string.at(4).simplified();
compact_mass_fraction_str=line_list_string.at(3).simplified();
dust_temp_str=line_list_string.at(5).simplified();
// //qDebug()<<"id_ "<<id_str<<" dist_ "<<dist_str<<" chi2 "<<chi_str;
// //qDebug()<<"clamp_mass_str "<<clamp_mass_str;
clamp_mass.append(clamp_mass_str.toDouble());
clamp_upper_age.append(clamp_upper_age_str.toDouble());
dust_temp.append(dust_temp_str.toDouble());
compact_mass_fraction.append(compact_mass_fraction_str.toDouble());
results.insert(chi_str.toDouble(), id_str.toInt());
if (chi_str.toDouble()<chi2)
{
id=id_str.toInt();
chi2=chi_str.toDouble();
dist=dist_str.toDouble();
}
}
sedFitValues.insert(2,clamp_mass);
sedFitValues.insert(4,clamp_upper_age);
sedFitValues.insert(3,compact_mass_fraction);
sedFitValues.insert(5,dust_temp);
int threshold = 5;
int nFitsResults=results.size()*threshold/100;
if(nFitsResults<1&&results.size()>=1){
nFitsResults=1;
}
if(nFitsResults<=10){
nFitsResults=results.size();
}
QMap<double, int>::iterator iter;
QMap <double, QList<QByteArray> >::iterator iterLines;
iter=results.begin();
iterLines=resultsLines.begin();
for(int i=0;i<nFitsResults;i++,iter++,iterLines++){
//for(int i=0;i<results.size();i++,iter++,iterLines++){
int new_id=iter.value();
if(i==0){ // Plot only the best one
QString query="SELECT * FROM vlkb_compactsources.sed_models where id="+ QString::number(new_id);
// //qDebug()<<"query: " << query;
// //qDebug()<<"color pre : blue " << Qt::blue;
new VLKBQuery(query,vtkwin, "model", this, Qt::blue);
}
/*
else{
if(i<10){
QString query="SELECT * FROM vlkb_compactsources.sed_models where id="+ QString::number(new_id);
new VLKBQuery(query,vtkwin, "model", this, Qt::cyan);
}
}*/
QList<QByteArray> line_list_string=iterLines.value();
ui->resultsTableWidget->insertRow(i);
for(int j=0;j<columnNames.length();j++){
if(resultsOutputColumn.value(columnNames.at(j))!=-1){
ui->resultsTableWidget->setItem(i, j, new QTableWidgetItem(QString(line_list_string.at(resultsOutputColumn.value(columnNames.at(j))).simplified())));
}
}
}
ui->resultsTableWidget->resizeColumnsToContents();
ui->resultsTableWidget->resizeRowsToContents();
loading->close();
}
void SEDVisualizerPlot::loadSedFitOutput(QString filename){
int id;
double chi2=99999999999;
double tmp;
QString chi_str,id_str,dist_str;
QMap <double, int> results;
QMap <double, QList<QByteArray> > resultsLines;
// //qDebug()<<"filename: "<<filename;
QFile file(filename);
// QFile file(qApp->applicationDirPath()+"/sedfit_output.dat");
if (!file.open(QIODevice::ReadOnly)) {
// //qDebug() << file.errorString();
return ;
}
//read, and skip the first line (header)
//file.readLine();
QString header=file.readLine();
outputSedResults.append(header);
readSedFitResultsHeader(header);
// QStringList wordList;
int i=0;
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setRowCount(0);
ui->resultsTableWidget->setColumnCount(columnNames.size());
ui->resultsTableWidget->setHorizontalHeaderLabels(columnNames);
while (!file.atEnd()) {
QByteArray line = file.readLine();
//wordList.append(line.split(',').first());
outputSedResults.append(line);
QList<QByteArray> line_list_string=line.split(',');
////qDebug()<<i<<" line size = "<<line_list_string.length();
/*
ui->resultsTableWidget->insertRow(i);
for(int j=0;j<columnNames.length();j++){
if(resultsOutputColumn.value(columnNames.at(j))!=-1){
ui->resultsTableWidget->setItem(i, j, new QTableWidgetItem(QString(line_list_string.at(resultsOutputColumn.value(columnNames.at(j))).simplified())));
}
}
i++;
*/
QList<QByteArray> tmp_string=line_list_string;
id_str=line_list_string.first().simplified();
dist_str=line_list_string.last().simplified();
line_list_string.removeLast();
chi_str=line_list_string.last().simplified();
// //qDebug()<<"id_ "<<id_str<<" dist_ "<<dist_str<<" chi2 "<<chi_str;
results.insert(chi_str.toDouble(), id_str.toInt());
resultsLines.insert(chi_str.toDouble(),tmp_string);
if (chi_str.toDouble()<chi2)
{
id=id_str.toInt();
chi2=chi_str.toDouble();
dist=dist_str.toDouble();
}
}
//qDebug()<<"id: "<<id<<" chi2: "<<chi2<<"dist: "<<dist;
//qDebug()<<"results chi2 :"<<results.firstKey();
int threshold = 5;
int nFitsResults=results.size()*threshold/100;
if(nFitsResults<1&&results.size()>=1){
nFitsResults=1;
}
if(nFitsResults<=10){
nFitsResults=results.size();
}
//qDebug()<<"All Fits :"<<QString::number(results.size());
//qDebug()<<"results chi2 :"<<results.firstKey()<<" nFitsResults: "<<QString::number(nFitsResults);
//qDebug()<<"resultsLines chi2 :"<<resultsLines.firstKey();
// //qDebug() << wordList;
QMap<double, int>::iterator iter;
QMap <double, QList<QByteArray> >::iterator iterLines;
iter=results.begin();
iterLines=resultsLines.begin();
for(int i=0;i<nFitsResults;i++,iter++,iterLines++){
//for(int i=0;i<results.size();i++,iter++,iterLines++){
QList<QByteArray> line_list_string=iterLines.value();
ui->resultsTableWidget->insertRow(i);
for(int j=0;j<columnNames.length();j++){
if(resultsOutputColumn.value(columnNames.at(j))!=-1){
ui->resultsTableWidget->setItem(i, j, new QTableWidgetItem(QString(line_list_string.at(resultsOutputColumn.value(columnNames.at(j))).simplified())));
}
}
}
ui->resultsTableWidget->resizeColumnsToContents();
}
void SEDVisualizerPlot::loadSedFitThin(QString filename){
qDebug()<<"leggo thin: "<<filename;
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setColumnCount(6);
ui->resultsTableWidget->setRowCount(0);
ui->resultsTableWidget->setHorizontalHeaderLabels(QStringList() << "fmass" << "dmass" << "ftemp" << "dtemp" << "fbeta" << "lum");
ui->resultsTableWidget->insertRow(0);
QFile filepar(filename);
if (!filepar.open(QIODevice::ReadOnly)) {
//qDebug() << filepar.errorString();
//qDebug() << "ERRORE Parametri";
return ;
}
QString line=filepar.readLine();
outputSedResults.append(line);
filepar.close();
QList<QString> line_list_string=line.split(',');
for(int i=0; i<line_list_string.size();i++){
ui->resultsTableWidget->setItem(0,i,new QTableWidgetItem(line_list_string.at(i).trimmed()));
}
ui->resultsTableWidget->resizeColumnsToContents();
}
void SEDVisualizerPlot::loadSedFitThick(QString filename){
qDebug()<<"leggo thick "<<filename;
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setColumnCount(9);
ui->resultsTableWidget->setRowCount(0);
ui->resultsTableWidget->setHorizontalHeaderLabels(QStringList() << "mass" << "dmass" << "ftemp" << "dtemp" << "fbeta" << "fl0" << "dlam0" << "sizesec" << "lum");
ui->resultsTableWidget->insertRow(0);
QFile filepar(filename);
if (!filepar.open(QIODevice::ReadOnly)) {
//qDebug() << filepar.errorString();
return ;
}
QString line=filepar.readLine();
outputSedResults.append(line);
filepar.close();
QList<QString> line_list_string=line.split(',');
for(int i=0; i<line_list_string.size();i++){
ui->resultsTableWidget->setItem(0,i,new QTableWidgetItem(line_list_string.at(i).trimmed()));
}
ui->resultsTableWidget->resizeColumnsToContents();
}
void SEDVisualizerPlot::setModelFitValue(QVector<QStringList> headerAndValueList, Qt::GlobalColor color)
{
//qDebug()<<"color set model fit : " << color;
QFile modelFile(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_sedfit_model.dat"));
if(!modelFile.exists()){
modelFile.open(QIODevice::WriteOnly);
QDataStream out(&modelFile);
out << headerAndValueList; // serialize the object
}
/*
QVectorIterator<QStringList> i(headerAndValueList);
int count=0;
while (i.hasNext()){
//qDebug()<<"List: "<<QString::number(count);
QStringList list= i.next();
foreach (const QString &str, list) {
//qDebug()<<str;
}
count++;
}
//modelFile.write()
}*/
QVector<double> x, y;
double scale;
QCPGraph *graph=ui->customPlot->addGraph();
QList<SEDPlotPointCustom *> points;
for( QMap<QString, double>::iterator it = modelFitBands.begin(); it != modelFitBands.end(); ++it)
{
// scale= 1/sqrt(dist);
scale = 1000/pow(dist,2);
//scale=1;
x.append(it.value());
int index=headerAndValueList.at(0).indexOf(it.key());
y.append(headerAndValueList.at(1).at(index).toDouble()*scale);
//y.append(headerAndValueList.at(1).at(index).toDouble());
SEDPlotPointCustom *cp = new SEDPlotPointCustom(ui->customPlot,3,vtkwin);
cp->setAntialiased(true);
//cp->setPos(it.value(), headerAndValueList.at(1).at(index).toDouble()*scale);
cp->setPos(it.value(), headerAndValueList.at(1).at(index).toDouble()*scale);
cp->setDesignation("");
cp->setX(0);
cp->setY(0);
cp->setLat(0);
cp->setLon(0);
points.push_back(cp);
//cp->setParent(graph);
ui->customPlot->addItem(cp);
}
//qDebug()<<"x:\n"<<x;
//qDebug()<<"y:\n"<<y;
//ui->customPlot->addGraph();
//qDebug()<<"temporaryMOD : "<<temporaryMOD;
if(color==Qt::blue || doubleClicked){
addNewSEDCheckBox("Theoretical Fit");
//qDebug()<<"Adding points of SED "<<QString::number(nSED-1);
sedGraphPoints.insert(nSED-1,points);
sedGraphs.push_back(graph);
doubleClicked=false;
}
if(temporaryMOD){
//qDebug()<<"Temporary MOD";
temporaryGraph=graph;
temporaryGraphPoints=points;
}
ui->customPlot->graph()->setData(x, y);
// ui->customPlot->graph()->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 6));
ui->customPlot->graph()->setPen(QPen(color));
ui->customPlot->graph()->setScatterStyle( QCPScatterStyle::ssNone);
ui->customPlot->replot();
this->setFocus();
this->activateWindow();
}
void SEDVisualizerPlot::on_actionScreenshot_triggered()
{
QPixmap qPixMap = QPixmap::grabWidget(this); // *this* is window pointer, the snippet is in the mainwindow.cpp file
QImage qImage = qPixMap.toImage();
QString fileName = QFileDialog::getSaveFileName(this,"Save screenshot", "", ".png");
//qDebug()<<"pre "<<fileName;
if(!fileName.endsWith(".png",Qt::CaseInsensitive) )
fileName.append(".png");
bool b = qImage.save(fileName);
}
void SEDVisualizerPlot::on_actionCollapse_triggered()
{
QPen pen;
pen.setStyle(Qt::DashLine);
pen.setColor(Qt::lightGray);
for(int i=0;i<originalGraphs.size();i++)
{
//originalGraphs.push_back(ui->customPlot->graph(i));
originalGraphs.at(i)->setPen(pen);
}
SED *coll_sed= new SED();
QVector<double> x, y;
SEDNode *old_tmp_node;
SEDNode *tmp_node;
int cnt=0;
double j;
foreach( j, all_sed_node.uniqueKeys() )
{
//qDebug() <<"j: "<< j;
QList<SEDNode*> node_list_tmp=all_sed_node.values(j);
double flux_sum=0;
double err_flux_sum=0;
if(cnt!=0)
{
old_tmp_node=tmp_node;
}
tmp_node=new SEDNode();
for (int z=0;z<node_list_tmp.count(); z++ )
{
//qDebug() <<"\t"<< node_list_tmp.at(z)->getDesignation();
flux_sum+=node_list_tmp.at(z)->getFlux();
err_flux_sum+=node_list_tmp.at(z)->getErrFlux();
}
tmp_node->setDesignation("");
tmp_node->setFlux(flux_sum);
tmp_node->setErrFlux(err_flux_sum);
tmp_node->setWavelength(j);
if(cnt!=0)
{
old_tmp_node->setParent(tmp_node);
tmp_node->setChild(old_tmp_node);
}
x.append(j);
y.append(flux_sum);
SEDPlotPointCustom *cp = new SEDPlotPointCustom(ui->customPlot,3,vtkwin);
cp->setAntialiased(true);
cp->setPos(j, flux_sum);
cp->setDesignation("");
cp->setX(0);
cp->setY(0);
cp->setLat(0);
cp->setLon(0);
cp->setErrorFlux(err_flux_sum);
cp->setNode(tmp_node);
collapsedGraphPoints.push_back(cp);
ui->customPlot->addItem(cp);
cnt++;
}
//qDebug()<<"x:\n"<<x;
//qDebug()<<"y:\n"<<y;
coll_sed->setRootNode(tmp_node);
collapsedGraph=ui->customPlot->addGraph();
ui->customPlot->graph()->setData(x, y);
ui->customPlot->graph()->setPen(QPen(Qt::red)); // line color red for second graph
ui->customPlot->graph()->setScatterStyle( QCPScatterStyle::ssNone);
ui->customPlot->replot();
//qDebug()<<sed_list.count();
sed_list.insert(0,coll_sed);
//qDebug()<<sed_list.count();
}
void SEDVisualizerPlot::on_TheoreticalLocaleFit_triggered()
{
sedFitInputFflag = "]";
sedFitInputF= "]";
sedFitInputW= "]";
sedFitInputErrF= "]";
sedFitInput.clear();
bool validFit=false;
// if(multiSelectMOD){
validFit=prepareSelectedInputForSedFit();
/*}else{
validFit=prepareInputForSedFit(sed_list.at(0)->getRootNode());
}
*/
if(validFit)
{
sedFitInputF ="["+sedFitInputF ;
sedFitInputW ="["+sedFitInputW;
sedFitInputFflag = "["+sedFitInputFflag;
sedFitInputErrF ="["+sedFitInputErrF ;
loading = new LoadingWidget();
loading->init();
loading->setText("Executing vialactea_tap_sedfit");
loading ->show();
loading->activateWindow();
loading->setFocus();
ui->outputTextBrowser->setText("");
process= new QProcess();
process->setProcessChannelMode(QProcess::MergedChannels);
//qDebug()<<idlPath+" -e \"sedpar=vialactea_tap_sedfit_v7("+sedFitInputW+","+sedFitInputF+","+sedFitInputErrF+","+sedFitInputFflag+","+ui->distTheoLineEdit->text()+","+ui->prefilterLineEdit->text()+",sed_weights=["+ui->mid_irLineEdit->text()+","+ui->far_irLineEdit->text()+","+ui->submmLineEdit->text()+"],use_wave="+sedFitInputW+",outdir='"+QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED))+"_',delta_chi2="+ui->delta_chi2_lineEdit->text()+")\" ";
connect(process,SIGNAL(readyReadStandardError()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(readyReadStandardOutput()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(finished(int)),this,SLOT(finishedTheoreticalLocaleFit()));
process->start (idlPath+" -e \"sedpar=vialactea_tap_sedfit_v7("+sedFitInputW+","+sedFitInputF+","+sedFitInputErrF+","+sedFitInputFflag+","+ui->distTheoLineEdit->text()+","+ui->prefilterLineEdit->text()+",sed_weights=["+ui->mid_irLineEdit->text()+","+ui->far_irLineEdit->text()+","+ui->submmLineEdit->text()+"],use_wave="+sedFitInputW+",outdir='"+QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED))+"_',delta_chi2="+ui->delta_chi2_lineEdit->text()+")\" ");
}
}
void SEDVisualizerPlot::finishedTheoreticalLocaleFit()
{
/*
QString output(process.readAll());
//qDebug()<<output;
outputSedLog=output;
ui->outputTextBrowser->setText(output);
*/
readSedFitOutput(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_sedfit_output.dat"));
//addNewSEDCheckBox("Theoretical Fit");
this->setFocus();
this->activateWindow();
}
void SEDVisualizerPlot::finishedTheoreticalRemoteFit()
{
QDir dir (QApplication::applicationDirPath());
dir.rename("sedfit_output.dat",QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_sedfit_output.dat"));
readSedFitOutput(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_sedfit_output.dat"));
this->setFocus();
this->activateWindow();
}
void SEDVisualizerPlot::onReadyReadStdOutput()
{
// process.setReadChannel(QProcess::readAllStandardError());
QTextStream stream(process);
while (!stream.atEnd()) {
QString line = stream.readLine();
// extract progress info from line and etc.
ui->outputTextBrowser->append(line);
}
}
//Add a new sed checkbox to the group of SED
void SEDVisualizerPlot::addNewSEDCheckBox(QString label, int nSED){
//qDebug()<<"Adding new SED Check Box "+QString::number(nSED);
QSignalMapper* mapper = new QSignalMapper(this);
ui->generatedSedBox->setVisible(true);
QCheckBox *newSed = new QCheckBox(label+" "+QString::number(nSED+1));
newSed->setChecked(true);
connect(newSed, SIGNAL(stateChanged(int)),mapper, SLOT(map()));
mapper->setMapping(newSed, nSED);
connect(mapper, SIGNAL(mapped(int)), this, SLOT(on_SEDCheckboxClicked(int)));
ui->generatedSedBox->layout()->addWidget(newSed);
//nSED++;
}
//Add a new sed checkbox to the group of SED
void SEDVisualizerPlot::addNewSEDCheckBox(QString label){
//qDebug()<<"Adding new SED Check Box "+QString::number(nSED);
QSignalMapper* mapper = new QSignalMapper(this);
ui->generatedSedBox->setVisible(true);
QCheckBox *newSed = new QCheckBox(QString::number(nSED+1)+":"+label);
newSed->setChecked(true);
connect(newSed, SIGNAL(stateChanged(int)),mapper, SLOT(map()));
mapper->setMapping(newSed, nSED);
connect(mapper, SIGNAL(mapped(int)), this, SLOT(on_SEDCheckboxClicked(int)));
ui->generatedSedBox->layout()->addWidget(newSed);
nSED++;
plottedSedLabels.append(label);
}
void SEDVisualizerPlot::on_SEDCheckboxClicked(int sedN)
{
qDebug()<<"processing checkbox "<<sedN;
qDebug()<<"sedGraphs.size() "<<QString::number(sedGraphs.size());
QCPGraph * graph=sedGraphs.at(sedN);
if(graph->visible()){
//qDebug()<<"Remove Graph "<<sedGraphPoints.contains(sedN);
graph->setVisible(false);
//temporaryGraph->setVisible(false);
//qDebug()<<"graph visibility "<<graph->visible();
if(sedGraphPoints.contains(sedN)){
QList<SEDPlotPointCustom *> points=sedGraphPoints.value(sedN);
for (int i = 0; i < points.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = points.at(i);
cp->setVisible(false);
//qDebug()<<"points visibility "<<cp->visible();
}
}
// ui->customPlot->removePlottable(graph);
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setRowCount(0);
}else{
////qDebug()<<"Add Graph";
//ui->customPlot->addGraph();
//ui->customPlot->graph();
graph->setVisible(true);
//qDebug()<<"graph visibility "<<graph->visible();
if(sedGraphPoints.contains(sedN)){ // This is a theoretical SED fit
QList<SEDPlotPointCustom *> points=sedGraphPoints.value(sedN);
for (int i = 0; i < points.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = points.at(i);
cp->setVisible(true);
}
loadSedFitOutput(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(sedN)+"_sedfit_output.dat"));
}else{ // This is a Thin or Thick SED fit
QString label=plottedSedLabels.at(sedN);
if(label.contains("Thick")){
loadSedFitThick(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(sedN)+"_thickfile.csv.par"));
}else{
loadSedFitThin(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(sedN)+"_thinfile.csv.par"));
}
}
}
ui->customPlot->replot();
}
void SEDVisualizerPlot::on_ThinLocalFit_triggered()
{
sedFitInputF= "]";
sedFitInputErrF= "]";
sedFitInputW= "]";
sedFitInput.clear();
/* if(multiSelectMOD){
prepareSelectedInputForSedFit();
}else{
prepareInputForSedFit(sed_list.at(0)->getRootNode());
}
*/
bool validFit=false;
validFit=prepareSelectedInputForSedFit();
if(validFit)
{
sedFitInputF ="["+sedFitInputF ;
sedFitInputErrF ="["+sedFitInputErrF ;
sedFitInputW ="["+sedFitInputW;
QString f=sedFitInputW.mid(1,sedFitInputW.length()-2);
QStringList wave = f.split(",");
QSignalMapper* mapper = new QSignalMapper(this);
sd_thin = new SedFitGrid_thin(this);
sd_thin->ui->distLineEdit->setText(ui->distTheoLineEdit->text());
sedFitInputUlimitString="[";
for(int i=0;i<wave.length();i++)
{
//qDebug()<<wave.at(i);
sedFitInputUlimit.insert(i,"0");
sedFitInputUlimitString+="0";
if(i<wave.size()-1)
sedFitInputUlimitString+=",";
int row= sd_thin->ui->tableWidget->model()->rowCount();
sd_thin->ui->tableWidget->insertRow(row);
QCheckBox *cb1= new QCheckBox();
cb1->setChecked(false);
sd_thin->ui->tableWidget->setCellWidget(row,1,cb1);
connect(cb1, SIGNAL(stateChanged(int)),mapper, SLOT(map()));
mapper->setMapping(cb1, row);
QTableWidgetItem *item_1 = new QTableWidgetItem();
item_1->setText(wave.at(i));
sd_thin->ui->tableWidget->setItem(row,0,item_1);
}
sedFitInputUlimitString+="]";
connect(mapper, SIGNAL(mapped(int)), this, SLOT(checkboxClicked(int)));
//qDebug()<<sedFitInputUlimitString;
sd_thin->show();
connect( sd_thin->ui->pushButton ,SIGNAL(clicked()),this,SLOT(doThinLocalFit()));
}
}
void SEDVisualizerPlot::checkboxClicked(int cb)
{
sedFitInputUlimit[cb].compare("0")==0? sedFitInputUlimit[cb]="1" : sedFitInputUlimit[cb]="0";
sedFitInputUlimitString="[";
for(int i=0;i<sedFitInputUlimit.size();i++)
{
sedFitInputUlimitString+=sedFitInputUlimit[i];
if(i<sedFitInputUlimit.size()-1)
sedFitInputUlimitString+=",";
}
sedFitInputUlimitString+="]";
}
void SEDVisualizerPlot::doThinLocalFit()
{
sd_thin->close();
ui->outputTextBrowser->setText("");
process = new QProcess(this);
process->setProcessChannelMode(QProcess::MergedChannels);
connect(process, SIGNAL(readyReadStandardError()), this, SLOT(onReadyReadStdOutput()));
connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadyReadStdOutput()));
connect(process, SIGNAL(finished(int)), this, SLOT(finishedThinLocalFit()));
QString mrange = "[" + sd_thin->ui->minMassLineEdit->text() + ", "
+ sd_thin->ui->maxMassLineEdit->text() + ", "
+ sd_thin->ui->stepMassLineEdit->text() + "]";
QString trange = "[" + sd_thin->ui->tempMinLineEdit->text() + ", "
+ sd_thin->ui->tempMaxLineEdit->text() + ", "
+ sd_thin->ui->tempStepLineEdit->text() + "]";
QString brange = "[" + sd_thin->ui->betaMinLineEdit->text() + ", "
+ sd_thin->ui->betaMaxLineEdit->text() + ", "
+ sd_thin->ui->betaStepLineEdit->text() + "]";
QString srefRange = "[" + sd_thin->ui->srefOpacityLineEdit->text() + ", "
+ sd_thin->ui->srefWavelengthLineEdit->text() + "]";
QString outputFile = QDir::homePath()
.append(QDir::separator())
.append("VisIVODesktopTemp/tmp_download/SED" + QString::number(nSED)
+ "_thinfile.csv");
QStringList args;
args << "sedfit_main.py"
<< "thin" << sedFitInputW << sedFitInputF << mrange << trange << brange
<< sd_thin->ui->distLineEdit->text() << srefRange << sedFitInputErrF
<< sedFitInputUlimitString << outputFile;
process->start("python3", args);
}
void SEDVisualizerPlot::doThinRemoteFit()
{
sd_thin->close();
ui->outputTextBrowser->setText("");
process= new QProcess();
connect(process,SIGNAL(readyReadStandardError()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(readyReadStandardOutput()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(finished(int)),this,SLOT(finishedThinRemoteFit()));
process->setProcessChannelMode(QProcess::MergedChannels);
QString mrange="["+ sd_thin->ui->minMassLineEdit->text()+", "+sd_thin->ui->maxMassLineEdit->text()+", "+ sd_thin->ui->stepMassLineEdit->text() +"]";
QString trange="["+ sd_thin->ui->tempMinLineEdit->text()+", "+sd_thin->ui->tempMaxLineEdit->text()+", "+ sd_thin->ui->tempStepLineEdit->text() +"]";
QString brange="["+ sd_thin->ui->betaMinLineEdit->text()+", "+sd_thin->ui->betaMaxLineEdit->text()+", "+ sd_thin->ui->betaStepLineEdit->text() +"]";
QString srefRange="["+ sd_thin->ui->srefOpacityLineEdit->text()+", "+ sd_thin->ui->srefWavelengthLineEdit->text() +"]";
////qDebug()<<"java -jar \"sedfitgrid_engine_thin_vialactea,"<<sedFitInputW<<", "<<sedFitInputF<<","<<mrange<<","<<trange<<" ,"<<brange<<" ,"<<sd_thin->ui->distLineEdit->text()<<","<<srefRange<<",lambdatn,flussotn,mtn,ttn,btn,ltn,dmtn,dttn,errorbars="<<sedFitInputErrF<<",ulimit="<<sedFitInputUlimitString<<",printfile= '"<<QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thinfile.csv")<<"'";
//process->start (idlPath+" -e \"sedfitgrid_engine_thin_vialactea,"+sedFitInputW+","+sedFitInputF+","+mrange+","+trange+" ,"+brange+" ,"+sd_thin->ui->distLineEdit->text()+","+srefRange+",lambdatn,flussotn,mtn,ttn,btn,ltn,dmtn,dttn,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= '"+QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thinfile.csv")+"'");
qDebug()<<" java -jar "<<QApplication::applicationDirPath().append("/vsh-ws-client.jar")<<" \"sedfitgrid_engine_thin_vialactea,"+sedFitInputW+","+sedFitInputF+","+mrange+","+trange+","+brange+","+sd_thin->ui->distLineEdit->text()+","+srefRange+",lambdatn,flussotn,mtn,ttn,btn,ltn,dmtn,dttn,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= 'sedfit_output.dat'";
process->setWorkingDirectory(QApplication::applicationDirPath());
//qDebug()<<"DIR: "<<process->workingDirectory();
//qDebug() << "App path : " << qApp->applicationDirPath();
//qDebug()<<"QDir::currentPath() :"<<QDir::currentPath() ;
process->start ("java -jar "+QApplication::applicationDirPath().append("/vsh-ws-client.jar")+" \"sedfitgrid_engine_thin_vialactea,"+sedFitInputW+","+sedFitInputF+","+mrange+","+trange+","+brange+","+sd_thin->ui->distLineEdit->text()+","+srefRange+",lambdatn,flussotn,mtn,ttn,btn,ltn,dmtn,dttn,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= 'sedfit_output.dat'\" ");
qDebug()<<"sedfitgrid_engine_thin_vialactea,"+sedFitInputW+","+sedFitInputF+","+mrange+","+trange+","+brange+","+sd_thin->ui->distLineEdit->text()+","+srefRange+",lambdatn,flussotn,mtn,ttn,btn,ltn,dmtn,dttn,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= 'sedfit_output.dat'\"";
ui->outputTextBrowser->append("java -jar "+QApplication::applicationDirPath().append("/vsh-ws-client.jar")+" \"sedfitgrid_engine_thin_vialactea,"+sedFitInputW+","+sedFitInputF+","+mrange+","+trange+","+brange+","+sd_thin->ui->distLineEdit->text()+","+srefRange+",lambdatn,flussotn,mtn,ttn,btn,ltn,dmtn,dttn,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= 'sedfit_output.dat'\" ");
ui->outputTextBrowser->append("\nDIR: "+process->workingDirectory());
ui->outputTextBrowser->append("\nApp path : " +qApp->applicationDirPath());
ui->outputTextBrowser->append("\nQDir::currentPath() :"+QDir::currentPath());
// process.waitForFinished(); // sets current thread to sleep and waits for process end
}
void SEDVisualizerPlot::doThickRemoteFit()
{
sd_thick->close();
ui->outputTextBrowser->setText("");
process= new QProcess();
connect(process,SIGNAL(readyReadStandardError()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(readyReadStandardOutput()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(finished(int)),this,SLOT(finishedThickRemoteFit()));
process->setProcessChannelMode(QProcess::MergedChannels);
QString trange="["+ sd_thick->ui->tempMinLineEdit->text()+", "+sd_thick->ui->tempMaxLineEdit->text()+", "+ sd_thick->ui->tempStepLineEdit->text() +"]";
QString brange="["+ sd_thick->ui->betaMinLineEdit->text()+", "+sd_thick->ui->betaMaxLineEdit->text()+", "+ sd_thick->ui->betaStepLineEdit->text() +"]";
QString l0range="["+ sd_thick->ui->minLambda_0LineEdit->text()+", "+sd_thick->ui->maxLambda_0LineEdit->text()+", "+ sd_thick->ui->stepLambda_0LineEdit->text() +"]";
QString sfactrange="["+ sd_thick->ui->scaleMinLineEdit->text()+", "+sd_thick->ui->scaleMaxLineEdit->text()+", "+ sd_thick->ui->scaleStepLineEdit->text() +"]";
QString srefRange="["+ sd_thick->ui->srefOpacityLineEdit->text()+", "+ sd_thick->ui->srefWavelengthLineEdit->text() +"]";
// process->start (idlPath+" -e \"sedfitgrid_engine_thick_vialactea,"+sedFitInputW+","+sedFitInputF+","+sd_thick->ui->sizeLineEdit->text()+","+trange+" ,"+brange+" ,"+l0range+", "+sfactrange+","+sd_thick->ui->distLineEdit->text()+","+srefRange+",lambdagb,flussogb,mtk,ttk,btk,l0,sizesec,ltk,dmtk,dtk,dl0,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= '"+QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thickfile.csv")+"'");
process->setWorkingDirectory(QApplication::applicationDirPath());
process->start ("java -jar "+QApplication::applicationDirPath().append("/vsh-ws-client.jar")+" \"sedfitgrid_engine_thick_vialactea,"+sedFitInputW+","+sedFitInputF+","+sd_thick->ui->sizeLineEdit->text()+","+trange+" ,"+brange+" ,"+l0range+", "+sfactrange+","+sd_thick->ui->distLineEdit->text()+","+srefRange+",lambdagb,flussogb,mtk,ttk,btk,l0,sizesec,ltk,dmtk,dtk,dl0,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= 'sedfit_output.dat'\" ");
qDebug()<<"sedfitgrid_engine_thick_vialactea,"+sedFitInputW+","+sedFitInputF+","+sd_thick->ui->sizeLineEdit->text()+","+trange+" ,"+brange+" ,"+l0range+", "+sfactrange+","+sd_thick->ui->distLineEdit->text()+","+srefRange+",lambdagb,flussogb,mtk,ttk,btk,l0,sizesec,ltk,dmtk,dtk,dl0,errorbars="+sedFitInputErrF+",ulimit="+sedFitInputUlimitString+",printfile= 'sedfit_output.dat'\" ";
}
void SEDVisualizerPlot::finishedThinLocalFit()
{
bool res = readThinFit(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thinfile.csv"));
if(res)
addNewSEDCheckBox("Thin Fit");
else
QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr("No results."));
}
bool SEDVisualizerPlot::readThinFit(QString resultPath){
QFile file(resultPath);
if (!file.open(QIODevice::ReadOnly)) {
//qDebug() << file.errorString();
//qDebug() << "ERRORE Disegno FIT";
return false ;
}
QVector<double> x, y;
while (!file.atEnd()) {
QByteArray line = file.readLine();
x.append( line.split(',').first().simplified().toDouble() );
y.append( line.split(',').last().simplified().toDouble() );
}
ui->customPlot->addGraph();
ui->customPlot->graph()->setData(x, y);
ui->customPlot->graph()->setScatterStyle( QCPScatterStyle::ssNone);
sedGraphs.push_back(ui->customPlot->graph());
ui->customPlot->replot();
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setColumnCount(6);
ui->resultsTableWidget->setRowCount(0);
ui->resultsTableWidget->setHorizontalHeaderLabels(QStringList() << "fmass" << "dmass" << "ftemp" << "dtemp" << "fbeta" << "lum");
ui->resultsTableWidget->insertRow(0);
QFile filepar(resultPath+".par");
if (!filepar.open(QIODevice::ReadOnly)) {
//qDebug() << file.errorString();
//qDebug() << "ERRORE Parametri";
return false ;
}
QString line=filepar.readLine();
filepar.close();
QList<QString> line_list_string=line.split(',');
for(int i=0; i<line_list_string.size();i++){
ui->resultsTableWidget->setItem(0,i,new QTableWidgetItem(line_list_string.at(i).trimmed()));
}
ui->resultsTableWidget->resizeColumnsToContents();
return true;
}
bool SEDVisualizerPlot::readThickFit(QString resultPath){
QFile file(resultPath);
if (!file.open(QIODevice::ReadOnly)) {
//qDebug() << file.errorString();
//qDebug() << "ERRORE Disegno FIT";
return false;
}
QVector<double> x, y;
while (!file.atEnd()) {
QByteArray line = file.readLine();
x.append( line.split(',').first().simplified().toDouble() );
y.append( line.split(',').last().simplified().toDouble() );
}
ui->customPlot->addGraph();
ui->customPlot->graph()->setData(x, y);
ui->customPlot->graph()->setScatterStyle( QCPScatterStyle::ssNone);
sedGraphs.push_back(ui->customPlot->graph());
ui->customPlot->replot();
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setColumnCount(9);
ui->resultsTableWidget->setRowCount(0);
ui->resultsTableWidget->setHorizontalHeaderLabels(QStringList() << "mass" << "dmass" << "ftemp" << "dtemp" << "fbeta" << "fl0" << "dlam0" << "sizesec" << "lum");
ui->resultsTableWidget->insertRow(0);
QFile filepar(resultPath+".par");
if (!filepar.open(QIODevice::ReadOnly)) {
//qDebug() << filepar.errorString();
return false ;
}
QString line=filepar.readLine();
filepar.close();
QList<QString> line_list_string=line.split(',');
for(int i=0; i<line_list_string.size();i++){
ui->resultsTableWidget->setItem(0,i,new QTableWidgetItem(line_list_string.at(i).trimmed()));
}
ui->resultsTableWidget->resizeColumnsToContents();
return true;
}
void SEDVisualizerPlot::doThickLocalFit()
{
sd_thick->close();
ui->outputTextBrowser->setText("");
process = new QProcess(this);
process->setProcessChannelMode(QProcess::MergedChannels);
connect(process, SIGNAL(readyReadStandardError()), this, SLOT(onReadyReadStdOutput()));
connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadyReadStdOutput()));
connect(process, SIGNAL(finished(int)), this, SLOT(finishedThickLocalFit()));
QString trange = "[" + sd_thick->ui->tempMinLineEdit->text() + ", "
+ sd_thick->ui->tempMaxLineEdit->text() + ", "
+ sd_thick->ui->tempStepLineEdit->text() + "]";
QString brange = "[" + sd_thick->ui->betaMinLineEdit->text() + ", "
+ sd_thick->ui->betaMaxLineEdit->text() + ", "
+ sd_thick->ui->betaStepLineEdit->text() + "]";
QString l0range = "[" + sd_thick->ui->minLambda_0LineEdit->text() + ", "
+ sd_thick->ui->maxLambda_0LineEdit->text() + ", "
+ sd_thick->ui->stepLambda_0LineEdit->text() + "]";
QString sfactrange = "[" + sd_thick->ui->scaleMinLineEdit->text() + ", "
+ sd_thick->ui->scaleMaxLineEdit->text() + ", "
+ sd_thick->ui->scaleStepLineEdit->text() + "]";
QString srefRange = "[" + sd_thick->ui->srefOpacityLineEdit->text() + ", "
+ sd_thick->ui->srefWavelengthLineEdit->text() + "]";
QString outputFile = QDir::homePath()
.append(QDir::separator())
.append("VisIVODesktopTemp/tmp_download/SED" + QString::number(nSED)
+ "_thickfile.csv");
QStringList args;
args << "sedfit_main.py"
<< "thick" << sedFitInputW << sedFitInputF << sd_thick->ui->sizeLineEdit->text() << trange
<< brange << l0range << sfactrange << sd_thick->ui->distLineEdit->text() << srefRange
<< sedFitInputErrF << sedFitInputUlimitString << outputFile;
process->start("python3", args);
}
void SEDVisualizerPlot::finishedThinRemoteFit()
{
QDir dir (QApplication::applicationDirPath());
dir.rename("sedfit_output.dat",QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thinfile.csv"));
dir.rename("sedfit_output.dat.par",QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thinfile.csv.par"));
// readSedFitOutput(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_sedfit_output.dat"));
bool res= readThickFit(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thinfile.csv"));
if (res)
addNewSEDCheckBox("Thin Fit");
else
QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr("No results."));
}
void SEDVisualizerPlot::finishedThickRemoteFit()
{
QDir dir (QApplication::applicationDirPath());
dir.rename("sedfit_output.dat",QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thickfile.csv"));
dir.rename("sedfit_output.dat.par",QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thickfile.csv.par"));
bool res = readThickFit(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thickfile.csv"));
if (res)
addNewSEDCheckBox("Thick Fit");
else
QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr("No results."));
}
void SEDVisualizerPlot::finishedThickLocalFit()
{
bool res = readThickFit(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/SED"+QString::number(nSED)+"_thickfile.csv"));
if (res)
addNewSEDCheckBox("Thick Fit");
else
QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr("No results."));
}
void SEDVisualizerPlot::on_ThickLocalFit_triggered()
{
sedFitInputF= "]";
sedFitInputErrF= "]";
sedFitInputW= "]";
sedFitInput.clear();
/* if(multiSelectMOD){
prepareSelectedInputForSedFit();
}else{
prepareInputForSedFit(sed_list.at(0)->getRootNode());
}
*/
bool validFit=false;
validFit=prepareSelectedInputForSedFit();
if(validFit)
{
sedFitInputF ="["+sedFitInputF ;
sedFitInputErrF ="["+sedFitInputErrF ;
sedFitInputW ="["+sedFitInputW;
//qDebug() << "f: " <<sedFitInputF;
//qDebug() << "e_f: " <<sedFitInputErrF;
//qDebug() << "w: " <<sedFitInputW;
QString f=sedFitInputW.mid(1,sedFitInputW.length()-2);
QStringList wave = f.split(",");
QSignalMapper* mapper = new QSignalMapper(this);
sd_thick = new SedFitgrid_thick(this);
sd_thick->ui->distLineEdit->setText(ui->distTheoLineEdit->text());
sedFitInputUlimitString="[";
for(int i=0;i<wave.length();i++)
{
//qDebug()<<wave.at(i);
sedFitInputUlimit.insert(i,"0");
sedFitInputUlimitString+="0";
if(i<wave.size()-1)
sedFitInputUlimitString+=",";
int row= sd_thick->ui->tableWidget->model()->rowCount();
sd_thick->ui->tableWidget->insertRow(row);
QCheckBox *cb1= new QCheckBox();
cb1->setChecked(false);
sd_thick->ui->tableWidget->setCellWidget(row,1,cb1);
connect(cb1, SIGNAL(stateChanged(int)),mapper, SLOT(map()));
mapper->setMapping(cb1, row);
QTableWidgetItem *item_1 = new QTableWidgetItem();
item_1->setText(wave.at(i));
sd_thick->ui->tableWidget->setItem(row,0,item_1);
}
sedFitInputUlimitString+="]";
connect(mapper, SIGNAL(mapped(int)), this, SLOT(checkboxClicked(int)));
sd_thick->show();
connect( sd_thick->ui->pushButton ,SIGNAL(clicked()),this,SLOT(doThickLocalFit()));
}
}
void SEDVisualizerPlot::executeRemoteCall(QString sedFitInputW, QString sedFitInputF,QString sedFitInputErrF, QString sedFitInputFflag, QMap<double,double> sedFitInput){
//qDebug()<<"Sono it thread executeRemoteCall"<<QThread::currentThread();
QString filename="sed_fit/execute.bin";
QFile file( filename );
if ( file.open(QIODevice::ReadWrite | QIODevice::Truncate) )
{
QTextStream stream( &file );
stream.reset();
stream <<"#!/bin/bash"<<endl;
stream <<"unzip scripts.zip"<<endl;
//stream <<"/usr/local/bin/idl -e \"sedpar=vialactea_tap_sedfit("+sedFitInputW+","+sedFitInputF+","+sedFitInputFflag+",1000.,0.2,sed_weights=[1.,1.,1.],use_wave="+QString::number(sedFitInput.keys()[0])+")\"" << endl;
stream <<"/usr/local/bin/idl -e \"sedpar=vialactea_tap_sedfit_v3("+sedFitInputW+","+sedFitInputF+","+sedFitInputErrF+","+sedFitInputFflag+",2000.,0.8,sed_weights=[1.,1.,1.],use_wave="+sedFitInputW+")\" &> log.dat"<< endl;
stream <<"zip output.zip *dat"<<endl;
}
//qDebug()<<"/usr/local/bin/idl -e \"sedpar=vialactea_tap_sedfit_v3("+sedFitInputW+","+sedFitInputF+","+sedFitInputErrF+","+sedFitInputFflag+",2000.,0.8,sed_weights=[1.,1.,1.],use_wave="+sedFitInputW+")\" &> log.dat"<< endl;
QProcess process_zip;
process_zip.start ("zip -j sed_fit/inputs.zip sed_fit/scripts.zip sed_fit/execute.bin ");
process_zip.waitForFinished(); // sets current thread to sleep and waits for process end
//curl -k -F m=submit -F pass=hp39A11 -F wfdesc=@workflow.xml -F inputzip=@inputs.zip -F portmapping=@portmapping.txt -F certs=@certs.zip http://via-lactea-sg00.iaps.inaf.it:8080/wspgrade/RemoteServlet
QProcess process;
process.start ("curl -k -F m=submit -F pass=hp39A11 -F wfdesc=@sed_fit/workflow.xml -F inputzip=@sed_fit/inputs.zip -F portmapping=@sed_fit/portmapping.txt -F certs=@sed_fit/certs.zip http://via-lactea-sg00.iaps.inaf.it:8080/wspgrade/RemoteServlet");
//qDebug()<<"curl -k -F m=submit -F pass=hp39A11 -F wfdesc=@sed_fit/workflow.xml -F inputzip=@sed_fit/inputs.zip -F portmapping=@sed_fit/portmapping.txt -F certs=@sed_fit/certs.zip http://via-lactea-sg00.iaps.inaf.it:8080/wspgrade/RemoteServlet";
process.waitForFinished(); // sets current thread to sleep and waits for process end
QString output(process.readAll());
//qDebug()<<output.simplified();
/*
QString output_status="";
QProcess process_status;
//output_status.compare("finished")!=0 ||
while (output_status.compare("finished")!=0)
{
process_status.start ("curl -k -F m=info -F pass=hp39A11 -F ID="+output.simplified()+" http://via-lactea-sg00.iaps.inaf.it:8080/wspgrade/RemoteServlet");
process_status.waitForFinished(); // sets current thread to sleep and waits for process end
output_status= process_status.readAll().simplified();
//qDebug()<<output_status;
if(output_status.compare("error")==0){
return;
}
}
*/
//extern bool checkIDRemoteCall(QString id);
QString id = output.simplified();
QFuture<bool> future = QtConcurrent::run(checkIDRemoteCall, id);
// future.waitForFinished();
bool finished=future.result();
if(finished){
QProcess process_download;
process_download.start ("curl -k -F m=download -F ID="+output.simplified()+" -F pass=hp39A11 -o sed_fit/output.zip http://via-lactea-sg00.iaps.inaf.it:8080/wspgrade/RemoteServlet");
process_download.waitForFinished(); // sets current thread to sleep and waits for process end
QString output_download(process_download.readAll());
//qDebug()<<output_download.simplified();
QProcess process_unzip;
//process_unzip.start ("unzip ""sed_fit/output.zip");
process_unzip.start ("unzip sed_fit/output.zip -d "+QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/"));
process_unzip.waitForFinished(); // sets current thread to sleep and waits for process end
QString output_unzip(process_unzip.readAll());
//qDebug()<<output_unzip.simplified();
QStringList pieces = output_unzip.split( " " );
//qDebug()<<pieces[pieces.length()-3];
QString path=pieces[pieces.length()-3];
path.replace(path.indexOf("guse.jsdl"),path.size(), QLatin1String("output.zip"));
//qDebug() << path;
//qDebug()<<"---- "<<"unzip "+path+" -d "+QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/");
QProcess process_unzip_2;
process_unzip_2.start ("unzip "+path+" -d "+QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/"));
process_unzip_2.waitForFinished(); // sets current thread to sleep and waits for process end
QString output_unzip_2(process_unzip_2.readAll());
//qDebug()<<output_unzip_2.simplified();
// readSedFitOutput(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/sedfit_output.dat"));
// QFile file_log( QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/log.dat"));
// if (!file_log.open(QFile::ReadOnly | QFile::Text)) return;
// QTextStream in(&file_log);
// outputSedLog=in.readAll();
// ui->outputTextBrowser->setText(outputSedLog);
// //qDebug()<<"****LOG***"<<outputSedLog;
}
}
bool SEDVisualizerPlot::checkIDRemoteCall(QString id){
//qDebug()<<"Sono it thread "<<QThread::currentThread();
QString output_status="";
QProcess process_status;
while (output_status.compare("finished")!=0)
{
process_status.start ("curl -k -F m=info -F pass=hp39A11 -F ID="+id+" http://via-lactea-sg00.iaps.inaf.it:8080/wspgrade/RemoteServlet");
process_status.waitForFinished(); // sets current thread to sleep and waits for process end
output_status= process_status.readAll().simplified();
////qDebug()<<output_status;
if(output_status.compare("error")==0){
return false;
}
}
return true;
}
void SEDVisualizerPlot::on_TheoreticalRemoteFit_triggered()
{
bool validFit=false;
sedFitInputFflag = "]";
sedFitInputF= "]";
sedFitInputW= "]";
sedFitInputErrF= "]";
sedFitInput.clear();
// if(multiSelectMOD){
validFit=prepareSelectedInputForSedFit();
// }
/* else{
validFit=prepareInputForSedFit(sed_list.at(0)->getRootNode());
}
*/
if(validFit)
{
sedFitInputF ="["+sedFitInputF ;
sedFitInputW ="["+sedFitInputW;
sedFitInputFflag = "["+sedFitInputFflag;
sedFitInputErrF ="["+sedFitInputErrF ;
loading = new LoadingWidget();
loading->init();
loading->setText("Executing vialactea_tap_sedfit");
loading ->show();
loading->activateWindow();
loading->setFocus();
ui->outputTextBrowser->setText("");
process= new QProcess();
process->setProcessChannelMode(QProcess::MergedChannels);
//qDebug()<<"sedFitInputErrF: "<<sedFitInputErrF;
//qDebug()<<" java -jar "<<QApplication::applicationDirPath().append("/vsh-ws-client.jar")<<" \"sedpar=vialactea_tap_sedfit_v7("+sedFitInputW+","+sedFitInputF+","+sedFitInputErrF+","+sedFitInputFflag+","+ui->distTheoLineEdit->text()+","+ui->prefilterLineEdit->text()+",sed_weights=["+ui->mid_irLineEdit->text()+","+ui->far_irLineEdit->text()+","+ui->submmLineEdit->text()+"],use_wave="+sedFitInputW+",outdir='./',delta_chi2="+ui->delta_chi2_lineEdit->text()+")\" ";
connect(process,SIGNAL(readyReadStandardError()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(readyReadStandardOutput()),this,SLOT(onReadyReadStdOutput()));
connect(process,SIGNAL(finished(int)),this,SLOT(finishedTheoreticalRemoteFit()));
process->setWorkingDirectory(QApplication::applicationDirPath());
process->start ("java -jar "+QApplication::applicationDirPath().append("/vsh-ws-client.jar")+" \"sedpar=vialactea_tap_sedfit_v7("+sedFitInputW+","+sedFitInputF+","+sedFitInputErrF+","+sedFitInputFflag+","+ui->distTheoLineEdit->text()+","+ui->prefilterLineEdit->text()+",sed_weights=["+ui->mid_irLineEdit->text()+","+ui->far_irLineEdit->text()+","+ui->submmLineEdit->text()+"],use_wave="+sedFitInputW+",outdir='./',delta_chi2="+ui->delta_chi2_lineEdit->text()+")\" ");
qDebug()<<"vialactea_tap_sedfit_v7("+sedFitInputW+","+sedFitInputF+","+sedFitInputErrF+","+sedFitInputFflag+","+ui->distTheoLineEdit->text()+","+ui->prefilterLineEdit->text()+",sed_weights=["+ui->mid_irLineEdit->text()+","+ui->far_irLineEdit->text()+","+ui->submmLineEdit->text()+"],use_wave="+sedFitInputW+",outdir='./',delta_chi2="+ui->delta_chi2_lineEdit->text()+")\" ";
}
}
void SEDVisualizerPlot::handleFinished(){
//qDebug()<<"handleFinished";
readSedFitOutput(QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/sedfit_output.dat"));
QFile file_log( QDir::homePath().append(QDir::separator()).append("VisIVODesktopTemp/tmp_download/log.dat"));
if (!file_log.open(QFile::ReadOnly | QFile::Text)) return;
QTextStream in(&file_log);
outputSedLog=in.readAll();
ui->outputTextBrowser->setText(outputSedLog);
//qDebug()<<"****LOG***"<<outputSedLog;
loading->close();
addNewSEDCheckBox("Theoretical Fit");
}
void SEDVisualizerPlot::on_logRadioButton_toggled(bool checked)
{
if(checked==true){
//Show log file
ui->outputTextBrowser->setText(outputSedLog);
ui->resultsTableWidget->hide();
ui->outputTextBrowser->show();
if(temporaryRow!=0){
ui->customPlot->removeGraph(temporaryGraph);
for (int i = 0; i < temporaryGraphPoints.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = temporaryGraphPoints.at(i);
ui->customPlot->removeItem(cp);
}
temporaryGraphPoints.clear();
temporaryRow=0;
}
}else{
//Show results
ui->outputTextBrowser->setText(outputSedResults);
ui->resultsTableWidget->show();
ui->outputTextBrowser->hide();
//ui->resultsTableWidget->setColumnCount(2);
//ui->resultsTableWidget->setRowCount(2);
//ui->resultsTableWidget->setItem(0, 1, new QTableWidgetItem("Hello"));
}
}
void SEDVisualizerPlot::on_clearAllButton_clicked()
{
//qDebug()<<"Graphs size "<<sedGraphs.size();
int size=sedGraphs.size();
for (int i = 0; i < size; ++i)
{
QCPGraph *qcp;
qcp = sedGraphs.at(i);
ui->customPlot->removeGraph(qcp);
//sedGraphs.removeAt(i);
}
//TODO: To check if items are removed from memory!
sedGraphs.clear();
//qDebug()<<"Graphs size "<<sedGraphs.size();
//
//qDebug()<<"Graph Points size "<<sedGraphPoints.size();
QMap <int, QList<SEDPlotPointCustom *> >::iterator iter;
for (iter = sedGraphPoints.begin(); iter != sedGraphPoints.end(); ++iter){
//qDebug()<<"Processing Graph: "<<iter.key();
QList<SEDPlotPointCustom *> points=sedGraphPoints.value(iter.key());
//qDebug()<<"Points size: "<<points.size();
for (int i = 0; i < points.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = points.at(i);
ui->customPlot->removeItem(cp);
}
}
sedGraphPoints.clear();
if(temporaryRow!=0){//there is a temporary graph still drawn
ui->customPlot->removeGraph(temporaryGraph);
for (int i = 0; i < temporaryGraphPoints.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = temporaryGraphPoints.at(i);
ui->customPlot->removeItem(cp);
}
temporaryGraphPoints.clear();
}
ui->customPlot->replot();
nSED=0;
temporaryMOD=false;
doubleClicked=false;
temporaryRow=0;
QLayoutItem *item;
//the key point here is that the layout items are stored inside the layout in a stack
while((item = ui->generatedSedBox->layout()->takeAt(1)) != 0) {
if (item->widget()) {
//if(item->widget()->metaObject()->className()=="QCheckBox"){
ui->generatedSedBox->layout()->removeWidget(item->widget());
delete item->widget();
//}
}
delete item;
}
//removeAllGraphs();
ui->resultsTableWidget->clearContents();
ui->resultsTableWidget->setRowCount(0);
ui->outputTextBrowser->setText("");
outputSedLog="";
QDir tmp_download(QDir::homePath()+"/VisIVODesktopTemp/tmp_download");
QStringList filters;
filters << "SED*";
tmp_download.setNameFilters(filters);
QStringList dirList=tmp_download.entryList();
//qDebug()<<"Dir size "<<dirList.size();
for(int i=0; i<dirList.size(); i++){
//qDebug()<<dirList.at(i);
QFile sedFile(QDir::homePath()+"/VisIVODesktopTemp/tmp_download/"+dirList.at(i));
sedFile.remove();
}
//tmp_download.removeRecursively();
plottedSedLabels.clear();
}
void SEDVisualizerPlot::on_normalRadioButton_toggled(bool selectNormal)
{
if(selectNormal==true){
multiSelectMOD=false;
ui->customPlot->setMultiSelectModifier(Qt::ControlModifier);
QList<QCPAbstractItem *> list_items=ui->customPlot->selectedItems();
for(int i=0;i<list_items.size();i++){
list_items.at(i)->setSelected(false);
}
ui->customPlot->replot();
}else{
multiSelectMOD=true;
ui->customPlot->setMultiSelectModifier(Qt::NoModifier);
}
//qDebug()<<"multiSelectMOD: "<<multiSelectMOD;
}
void SEDVisualizerPlot::on_actionSave_triggered()
{
QProcess process_zip;
QDir tmp_download(QDir::homePath()+"/VisIVODesktopTemp/tmp_download");
QStringList filters;
filters << "SED*";
tmp_download.setNameFilters(filters);
QStringList dirList=tmp_download.entryList();
//qDebug()<<"Dir size "<<dirList.size();
QString sedZipPath=QDir::homePath()+"/VisIVODesktopTemp/tmp_download/SED.zip";
for(int i=0; i<dirList.size(); i++){
QString sedPath=QDir::homePath()+"/VisIVODesktopTemp/tmp_download/"+dirList.at(i);
process_zip.start ("zip -j "+sedZipPath+" "+sedPath);
//qDebug()<<"zip -j "+sedZipPath+" "+sedPath;
process_zip.waitForFinished(); // sets current thread to sleep and waits for process end
QString output_zip(process_zip.readAll());
//qDebug()<<output_zip.simplified();
//FolderCompressor *fc=new FolderCompressor();
//fc->compressFolder(QDir::homePath()+"/VisIVODesktopTemp/tmp_download/"+dirList.at(i), sedZipPath);
}
QString fileName = QFileDialog::getSaveFileName(this,tr("Save SED fits"), QDir::homePath(), tr("*.zip"));
if(!fileName.endsWith(".zip",Qt::CaseInsensitive) )
fileName.append(".zip");
//qDebug()<<"Path: "<<fileName;
QFile::copy(sedZipPath, fileName);
}
void SEDVisualizerPlot::on_actionLoad_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("Load SED fits"), QDir::homePath(), tr("Archive (*.zip)"));
QString sedZipPath=QDir::homePath()+"/VisIVODesktopTemp/tmp_download/SED.zip";
QFile::copy(fileName, sedZipPath);
QProcess process_unzip;
process_unzip.start ("unzip "+sedZipPath+" -d "+QDir::homePath()+"/VisIVODesktopTemp/tmp_download");
//qDebug()<<"unzip "+sedZipPath+" -d "+QDir::homePath()+"/VisIVODesktopTemp/tmp_download";
process_unzip.waitForFinished(); // sets current thread to sleep and waits for process end
QString output_unzip(process_unzip.readAll());
//qDebug()<<output_unzip.simplified();
QDir tmp_download(QDir::homePath()+"/VisIVODesktopTemp/tmp_download");
QStringList filters;
filters << "SED*";
tmp_download.setNameFilters(filters);
QStringList dirList=tmp_download.entryList();
//qDebug()<<"Dir size "<<dirList.size();
for(int i=0; i<dirList.size(); i++){
QString sedPath=QDir::homePath()+"/VisIVODesktopTemp/tmp_download/"+dirList.at(i);
QString sedNumber = dirList.at(i).mid(3,1); // substring after "SED";
//qDebug()<<"SED Number "<<sedNumber;
bool ok;
int value = sedNumber.toInt(&ok);
if (ok) { // is an integer
if(sedPath.endsWith("sedfit_model.dat")){
//qDebug()<<"sedGraphs.size() before : "<<sedGraphs.size();
//qDebug()<<"sedGraphPoints.size() before : "<<sedGraphPoints.size();
//qDebug()<<"Drawing "+sedPath;
addNewSEDCheckBox("Theoretical Fit");
QFile file(sedPath);
file.open(QIODevice::ReadOnly);
QDataStream in(&file); // read the data serialized from the file
QVector<QStringList> headerAndValueList;
in >> headerAndValueList; // extract data
setModelFitValue(headerAndValueList, Qt::blue);
}
if(sedPath.endsWith("sedfit_output.dat")){
loadSedFitOutput(sedPath);
}
if(sedPath.endsWith("thinfile.csv")){
//qDebug()<<"sedGraphs.size() before : "<<sedGraphs.size();
//qDebug()<<"Drawing "+sedPath;
readThinFit(sedPath);
addNewSEDCheckBox("Thin Fit");
//qDebug()<<"sedGraphs.size() after : "<<sedGraphs.size();
}
if(sedPath.endsWith("thickfile.csv")){
//qDebug()<<"sedGraphs.size() before : "<<sedGraphs.size();
//qDebug()<<"Drawing "+sedPath;
readThinFit(sedPath);
addNewSEDCheckBox("Thick Fit");
//qDebug()<<"sedGraphs.size() after : "<<sedGraphs.size();
}
}
}
}
void SEDVisualizerPlot::loadSavedSED(QStringList dirList){
for(int i=0; i<dirList.size(); i++){
QString sedPath=QDir::homePath()+"/VisIVODesktopTemp/tmp_download/"+dirList.at(i);
QString sedNumber = dirList.at(i).mid(3,1); // substring after "SED";
//qDebug()<<"SED Number "<<sedNumber;
bool ok;
int value = sedNumber.toInt(&ok);
if (ok) { // is an integer
if(sedPath.endsWith("sedfit_model.dat")){
//qDebug()<<"sedGraphs.size() before : "<<sedGraphs.size();
//qDebug()<<"sedGraphPoints.size() before : "<<sedGraphPoints.size();
//qDebug()<<"Drawing "+sedPath;
QString sedOutput=QDir::homePath()+"/VisIVODesktopTemp/tmp_download/SED"+QString::number(value)+"_sedfit_output.dat";
loadSedFitOutput(sedOutput);
//addNewSEDCheckBox("Theoretical Fit");
QFile file(sedPath);
file.open(QIODevice::ReadOnly);
QDataStream in(&file); // read the data serialized from the file
QVector<QStringList> headerAndValueList;
in >> headerAndValueList; // extract data
setModelFitValue(headerAndValueList, Qt::blue);
}
/*if(sedPath.endsWith("sedfit_output.dat")){
loadSedFitOutput(sedPath);
}*/
if(sedPath.endsWith("thinfile.csv")){
//qDebug()<<"sedGraphs.size() before : "<<sedGraphs.size();
//qDebug()<<"Drawing "+sedPath;
readThinFit(sedPath);
addNewSEDCheckBox("Thin Fit");
//qDebug()<<"sedGraphs.size() after : "<<sedGraphs.size();
}
if(sedPath.endsWith("thickfile.csv")){
//qDebug()<<"sedGraphs.size() before : "<<sedGraphs.size();
//qDebug()<<"Drawing "+sedPath;
readThinFit(sedPath);
addNewSEDCheckBox("Thick Fit");
//qDebug()<<"sedGraphs.size() after : "<<sedGraphs.size();
}
}
}
}
void SEDVisualizerPlot::on_collapseCheckBox_toggled(bool checked)
{
if(checked){
this->on_actionCollapse_triggered();
}else{
//qDebug()<<"Return previous state";
QPen pen;
pen.setStyle(Qt::SolidLine);
pen.setColor(Qt::black);
for(int i=0;i<originalGraphs.size();i++)
{
originalGraphs.at(i)->setPen(pen);
}
//originalGraphs.clear();
ui->customPlot->removeGraph(collapsedGraph);
for (int i = 0; i < collapsedGraphPoints.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = collapsedGraphPoints.at(i);
ui->customPlot->removeItem(cp);
}
collapsedGraphPoints.clear();
ui->customPlot->replot();
}
}
void SEDVisualizerPlot::on_multiSelectCheckBox_toggled(bool checked)
{
if(checked==true){
multiSelectMOD=true;
ui->customPlot->setMultiSelectModifier(Qt::NoModifier);
}else{
multiSelectMOD=false;
ui->customPlot->setMultiSelectModifier(Qt::ControlModifier);
QList<QCPAbstractItem *> list_items=ui->customPlot->selectedItems();
for(int i=0;i<list_items.size();i++){
list_items.at(i)->setSelected(false);
}
ui->customPlot->replot();
}
//qDebug()<<"multiSelectMOD: "<<multiSelectMOD;
}
void SEDVisualizerPlot::addNewTheoreticalFit(){
QModelIndex index= ui->resultsTableWidget->selectionModel()->selectedIndexes().first();
//qDebug()<<"Clicked Menu ";
doubleClicked=true;
temporaryMOD=false;
//qDebug()<<"Double Cliked Row "+QString::number(index.row());
int id=ui->resultsTableWidget->item(index.row(),0)->text().toInt();
//qDebug()<<"Selected id "+QString::number(id);
if(index.row()==0){
// Do nothing on the first row which is already drawn by default
}
else{
QString query="SELECT * FROM vlkb_compactsources.sed_models where id="+ QString::number(id);
//qDebug()<<"query: " << query;
new VLKBQuery(query,vtkwin, "model", this, Qt::cyan);
if(temporaryRow!=0){
ui->customPlot->removeGraph(temporaryGraph);
for (int i = 0; i < temporaryGraphPoints.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = temporaryGraphPoints.at(i);
ui->customPlot->removeItem(cp);
}
temporaryGraphPoints.clear();
temporaryRow=0;
}
}
this->setFocus();
this->activateWindow();
}
void SEDVisualizerPlot::on_resultsTableWidget_clicked(const QModelIndex &index)
{
if(!doubleClicked){
temporaryMOD=true;
//qDebug()<<"Cliked Row "+QString::number(index.row());
int id=ui->resultsTableWidget->item(index.row(),0)->text().toInt();
//qDebug()<<"Selected id "+QString::number(id);
if(index.row()==0){
// Do nothing on the first row which is already drawn by default
// if a temporary graph was shown delete it
//qDebug()<<temporaryGraphPoints.size();
if(temporaryGraphPoints.size()!=0){
ui->customPlot->removeGraph(temporaryGraph);
for (int i = 0; i < temporaryGraphPoints.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = temporaryGraphPoints.at(i);
ui->customPlot->removeItem(cp);
}
temporaryGraphPoints.clear();
temporaryRow=0;
ui->customPlot->replot();
}
}
else if(index.row()!=temporaryRow){
if(temporaryRow!=0){
ui->customPlot->removeGraph(temporaryGraph);
for (int i = 0; i < temporaryGraphPoints.size(); ++i)
{
SEDPlotPointCustom *cp;
cp = temporaryGraphPoints.at(i);
ui->customPlot->removeItem(cp);
}
temporaryGraphPoints.clear();
}
QString query="SELECT * FROM vlkb_compactsources.sed_models where id="+ QString::number(id);
//qDebug()<<"query: " << query;
new VLKBQuery(query,vtkwin, "model", this, Qt::lightGray);
temporaryRow=index.row();
}
doubleClicked=false;
}
this->setFocus();
this->activateWindow();
}
void SEDVisualizerPlot::on_theoreticalPushButton_clicked()
{
ui->theorGroupBox->show();
ui->greyBodyGroupBox->hide();
}
void SEDVisualizerPlot::on_theorConfirmPushButton_clicked()
{
/*
if(false)
QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr("Could not execute SED fit with less than 2 points selected.\n\rPlease select more points and try again."));
*/
on_TheoreticalRemoteFit_triggered();
}
void SEDVisualizerPlot::on_greyBodyPushButton_clicked()
{
ui->theorGroupBox->hide();
ui->greyBodyGroupBox->show();
}
void SEDVisualizerPlot::on_ThinRemore_triggered()
{
sedFitInputF= "]";
sedFitInputErrF= "]";
sedFitInputW= "]";
sedFitInput.clear();
/* if(multiSelectMOD){
prepareSelectedInputForSedFit();
}else{
prepareInputForSedFit(sed_list.at(0)->getRootNode());
}
*/
bool validFit=false;
validFit=prepareSelectedInputForSedFit();
if(validFit)
{
sedFitInputF ="["+sedFitInputF ;
sedFitInputErrF ="["+sedFitInputErrF ;
sedFitInputW ="["+sedFitInputW;
QString f=sedFitInputW.mid(1,sedFitInputW.length()-2);
QStringList wave = f.split(",");
QSignalMapper* mapper = new QSignalMapper(this);
sd_thin = new SedFitGrid_thin(this);
sd_thin->ui->distLineEdit->setText(ui->distTheoLineEdit->text());
sedFitInputUlimitString="[";
for(int i=0;i<wave.length();i++)
{
//qDebug()<<wave.at(i);
sedFitInputUlimit.insert(i,"0");
sedFitInputUlimitString+="0";
if(i<wave.size()-1)
sedFitInputUlimitString+=",";
int row= sd_thin->ui->tableWidget->model()->rowCount();
sd_thin->ui->tableWidget->insertRow(row);
QCheckBox *cb1= new QCheckBox();
cb1->setChecked(false);
sd_thin->ui->tableWidget->setCellWidget(row,1,cb1);
connect(cb1, SIGNAL(stateChanged(int)),mapper, SLOT(map()));
mapper->setMapping(cb1, row);
QTableWidgetItem *item_1 = new QTableWidgetItem();
item_1->setText(wave.at(i));
sd_thin->ui->tableWidget->setItem(row,0,item_1);
}
sedFitInputUlimitString+="]";
connect(mapper, SIGNAL(mapped(int)), this, SLOT(checkboxClicked(int)));
//qDebug()<<sedFitInputUlimitString;
sd_thin->show();
connect( sd_thin->ui->pushButton ,SIGNAL(clicked()),this,SLOT(doThinRemoteFit()));
}
}
void SEDVisualizerPlot::on_ThickRemote_triggered()
{
sedFitInputF= "]";
sedFitInputErrF= "]";
sedFitInputW= "]";
sedFitInput.clear();
/*
if(multiSelectMOD){
prepareSelectedInputForSedFit();
}else{
prepareInputForSedFit(sed_list.at(0)->getRootNode());
}
*/
bool validFit=true;
validFit=prepareSelectedInputForSedFit();
if(validFit)
{
sedFitInputF ="["+sedFitInputF ;
sedFitInputErrF ="["+sedFitInputErrF ;
sedFitInputW ="["+sedFitInputW;
//qDebug() << "f: " <<sedFitInputF;
//qDebug() << "e_f: " <<sedFitInputErrF;
//qDebug() << "w: " <<sedFitInputW;
QString f=sedFitInputW.mid(1,sedFitInputW.length()-2);
QStringList wave = f.split(",");
QSignalMapper* mapper = new QSignalMapper(this);
sd_thick = new SedFitgrid_thick(this);
sd_thick->ui->distLineEdit->setText(ui->distTheoLineEdit->text());
sedFitInputUlimitString="[";
for(int i=0;i<wave.length();i++)
{
//qDebug()<<wave.at(i);
sedFitInputUlimit.insert(i,"0");
sedFitInputUlimitString+="0";
if(i<wave.size()-1)
sedFitInputUlimitString+=",";
int row= sd_thick->ui->tableWidget->model()->rowCount();
sd_thick->ui->tableWidget->insertRow(row);
QCheckBox *cb1= new QCheckBox();
cb1->setChecked(false);
sd_thick->ui->tableWidget->setCellWidget(row,1,cb1);
connect(cb1, SIGNAL(stateChanged(int)),mapper, SLOT(map()));
mapper->setMapping(cb1, row);
QTableWidgetItem *item_1 = new QTableWidgetItem();
item_1->setText(wave.at(i));
sd_thick->ui->tableWidget->setItem(row,0,item_1);
}
sedFitInputUlimitString+="]";
connect(mapper, SIGNAL(mapped(int)), this, SLOT(checkboxClicked(int)));
sd_thick->show();
connect( sd_thick->ui->pushButton ,SIGNAL(clicked()),this,SLOT(doThickRemoteFit()));
}
}
void SEDVisualizerPlot::on_Thick_clicked()
{
on_ThickRemote_triggered();
}
void SEDVisualizerPlot::on_thinButton_clicked()
{
on_ThinRemore_triggered();
}
| 37.81151 | 521 | 0.633399 | [
"object",
"model"
] |
0219990cb64e7dd8fc090f27c60fc280c2ae15f5 | 13,462 | hpp | C++ | include/util.hpp | UberDever/CREN | edde1fb8f262bcef930f20084b2f315f46f0d35c | [
"MIT"
] | null | null | null | include/util.hpp | UberDever/CREN | edde1fb8f262bcef930f20084b2f315f46f0d35c | [
"MIT"
] | null | null | null | include/util.hpp | UberDever/CREN | edde1fb8f262bcef930f20084b2f315f46f0d35c | [
"MIT"
] | null | null | null | //
// Created by uberdever on 18.02.2020.
//
#ifndef CREN_UTIL_H
#define CREN_UTIL_H
#include "global.hpp"
//cfg - all configuration parameters, useful for application.
namespace math {template <typename T> struct v2;}
//util - all utility constructions, does not required to be in particular context, or used by system itself
//includes: enums, struct/class prototypes, general use functions
namespace util
{
//constexpr vars
constexpr int HASH_KEY_LEN = 50;
constexpr int SDL_ParseCount = 8;
//game enums
enum e_exitCodes : uint8_t
{
OK = 0x00,
GUT_SDL_ERR = 0x01,
GUT_TTF_ERR = 0x02,
GUT_IMG_ERR = 0x03,
RES_TTF_ERR = 0x04,
RES_IMG_ERR = 0x05,
GAME_MAP_ERR = 0x06,
UI_PARSE_ERR = 0x07,
ITM_PARSE_ERR = 0x08,
ITM_ATTR_ERR = 0x09,
UNUSED2_ERR = 0x10,
};
enum e_gameStates : size_t
{
EXIT = 0x00,
UI = 0x01,
GAMEPLAY = 0x02,
TEMP = 0x03
};
/************************************************************/
//scene prototype
struct SCENE
{
SCENE() { init = nullptr; event = update = nullptr; render = nullptr; clean = nullptr;};
e_exitCodes init_scene(e_exitCodes (*_init)(), e_gameStates (*_event)(), e_gameStates (*_update)(), void (*_render)(float), void (*_clean)())
{
init = _init;
event = _event;
update = _update;
render = _render;
clean = _clean;
return init();
};
~SCENE() { clean(); }
e_exitCodes (*init)();
e_gameStates (*event)();
e_gameStates (*update)();
void (*render)(float);
void (*clean)();
};
//custom event struct
struct GAMEEVENT
{
union {int mx; uint32_t key{};}; // mx is key in onKeyUp and onKeyDown events
int my;
int32_t mxRel; int32_t myRel;
union {uint32_t mbutton; uint32_t scancode;};
uint8_t type;
uint8_t winEv;
GAMEEVENT(): mx(0), my(0), mbutton(0), type(8), mxRel{0}, myRel{0}, winEv{0} {}
};
//first 128 keyboard keys, for elegant implementation of repeating
static bool kbState[128];
//union for direct access of colors values
struct COLOR
{
union {
uint32_t color;
struct {uint8_t a; uint8_t b; uint8_t g; uint8_t r;};
};
};
template <typename T>
struct lNode
{
lNode* pr;
lNode* nx;
T data;
lNode<T>(): pr{nullptr}, nx{nullptr} {}
~lNode<T>() = default;
};
template <typename T>
struct list
{
lNode<T>* head;
lNode<T>* tail;
list<T>() : head{nullptr}, tail{nullptr} {}
~list<T>() {}
bool is_empty() {return !head;}
T* back() {
if (is_empty()) return nullptr;
return &tail->data;
}
void append(T& _data)
{
if (!head)
{
head = tail = new lNode<T>();
tail->data = _data;
return;
}
tail->nx = new lNode<T>();
tail->nx->data = _data;
tail->nx->pr = tail;
tail = tail->nx;
}
void append(T&& _data)
{
if (!head)
{
head = tail = new lNode<T>();
tail->data = _data;
return;
}
tail->nx = new lNode<T>();
tail->nx->data = _data;
tail->nx->pr = tail;
tail = tail->nx;
}
void clean()
{
if (is_empty()) return;
auto* p = head;
while (head)
{
p = p->nx;
delete head;
head = p;
}
}
void clean_heap()
{
if (is_empty()) return;
auto* p = head;
while (head)
{
p = p->nx;
delete head->data;
head->data = nullptr;
delete head;
head = p;
}
}
uint32_t size()
{
auto p = head;
uint32_t size = 0;
while (p) {p = p->nx; size++;}
return size;
}
void print()
{
for (lNode<T>* it = head; it != nullptr; it = it->nx)
{
std::cout << it->data << " ";
}
}
};
template <typename T>
struct vector
{
T* data {nullptr};
size_t capacity {1};
int load {0};
vector() { data = new T[capacity]{}; };
explicit vector(size_t _capacity) : capacity{_capacity} {data = new T[capacity]{};}
~vector() {delete[] data;}
bool is_empty()
{
return load <= 0;
}
bool is_full()
{
return load >= capacity;
}
void reserve(size_t _capacity)
{
std::cout << "Vector is resized (reserved)" << std::endl;
delete[] data;
capacity = _capacity;
data = new T[capacity];
}
void resize(size_t _capacity)
{
std::cout << "Vector is resized" << std::endl;
capacity = _capacity;
T* tmpData = new T[capacity]{};
memcpy(tmpData, data, load * sizeof(T));
delete [] data;
data = tmpData;
}
void push(T& el)
{
if (is_full())
{
std::cout << "Vector is resized (pushed)" << std::endl;
resize(capacity * 2);
}
//std::cerr << "data is: " << (void*)data << std::endl;
data[load] = el;
load++;
}
/*void push(T&& el)
{
if (is_full())
{
capacity *= 2;
T* tmpData = new T[capacity]{};
memcpy(tmpData, data, load * sizeof(T));
delete [] data;
data = tmpData;
}
std::cout << "pushed" << std::endl;
data[load] = el;
load++;
}*/
T* pop()
{
if (is_empty()) return nullptr;
return &data[--load];
}
T* tail()
{
if (is_empty()) return nullptr;
return &data[load - 1];
}
T* operator[](int index)
{
if (index >= load || index < 0) {return nullptr;}
return &data[index];
}
void shrink()
{
if (load <= 0) return;
T* tmpData = new T[load]();
memcpy(tmpData, data, load * sizeof(T));
delete [] data;
data = tmpData;
capacity = load;
}
};
template <typename T>
struct hNode
{
T data;
char key[HASH_KEY_LEN];
bool isEmpty;
bool isLast;
hNode() : data{}, isEmpty{true}, isLast{false}, key{""} {}
~hNode() = default;
hNode<T>& operator=(const T& rhs)
{
data = rhs;
return *this;
}
};
uint32_t hash(const char* data, size_t len);
template <typename T>
struct hashT
{
const size_t size;
hNode<T>* table;
explicit hashT(const uint32_t _size) : size{_size}, table{nullptr} { table = new hNode<T>[size]; }
~hashT() {delete[] table;}
hNode<T>& operator[](const char* _key) //do NOT use this for retrieving the element
{
char key[HASH_KEY_LEN] {};
strncat(key, _key, HASH_KEY_LEN - 1);
uint32_t h = hash(key, strlen(key)) % size;
uint32_t ind = 0; uint32_t probe = h;
while (!table[probe].isEmpty) {
table[probe].isLast = false;
ind++;
probe = (h + (ind * ind)) % size;
if (probe == h)
{
std::cout << "hashTable is full" << std::endl;
break;
}
}
strncat(table[probe].key, key, HASH_KEY_LEN - 1);
table[probe].isEmpty = false;
table[probe].isLast = true;
return table[probe];
}
T* search(const char* _key)
{
char key[HASH_KEY_LEN] {};
strncat(key, _key, HASH_KEY_LEN - 1);
uint32_t h = hash(key, strlen(key)) % size;
if (table[h].isEmpty) return nullptr;
uint32_t ind = 0;
uint32_t probe = h;
while (strcmp(table[probe].key, key))
{
if (table[probe].isLast)
return nullptr;
ind++;
probe = (h + (ind * ind)) % size;
}
//std::cout << table[probe].key << " -> " << h << std::endl;
return &table[probe].data;
}
void clean()
{
for (int i = 0; i < size; i++)
{
delete table[i]->data;
table[i]->isEmpty = true;
}
}
};
void parse_event(SDL_Event* rawEvent, GAMEEVENT* gameEvent);
//generic use functions
bool inField(int mx, int my, int px, int py, int sx, int sy);
math::v2<int> parseV2(const char* str);
template <typename T>
void traverseTrie(lNode<T>* pEl, void (*pFunc)(T))
{
pFunc(pEl->data);
if (!pEl->data->childNodes.is_empty())
{
traverseTrie(pEl->data->childNodes.head, pFunc);
}
if (pEl->nx)
traverseTrie(pEl->nx, pFunc);
}
inline int randRange(int min, int max)
{
if (min == max) return max;
if (!(min || max)) return 0;
return rand() % (max - min) + min;
}
}
//res - all technical outer world resource handling
namespace res
{
struct FNT
{
TTF_Font* font;
size_t size;
uint32_t id;
FNT(): font{nullptr}, size{0}, id{0} {}
~FNT() {TTF_CloseFont(font);}
};
TTF_Font* res_getFont(const char* name, uint32_t size);
SDL_Surface* res_loadPNG(const char* path);
TTF_Font* res_loadTTF(const char* path, uint32_t size);
util::e_exitCodes res_init();
void res_clean();
}
//math - all math, used in project (it can be not much, but it still required)
namespace math
{
constexpr float PI = 3.14159265;
//Vec2 struct and related functions
template <typename T>
struct v2
{
T x; T y;
constexpr explicit v2(T _x, T _y) : x(_x), y(_y) {};
v2() {x = y = 0;}
inline T norm1() {return fabs(x) + fabs(y);}
inline T norm2() {return sqrt(x * x + y * y);}
inline v2<T> rotate(T ang) {return v2<T>{(this->x * cos(ang) - this->y * sin(ang)), (this->x * sin(ang) + this->y * cos(ang))};}
inline v2<T> operator-() {return v2<T>{-this->x,-this->y};}
inline v2<T>& operator=(T rhs) {this->x = rhs; this->y = rhs; return *this;}
inline v2<T>& operator=(const v2<T> rhs) {this->x = rhs.x; this->y = rhs.y; return *this;}
inline v2<T>& operator+=(const v2<T>&rhs) {this->x += rhs.x; this->y += rhs.y; return *this;}
inline v2<T>& operator+=(const T rhs) {this->x += rhs; this->y += rhs; return *this;}
inline v2<T>& operator-=(const v2<T>& rhs) {this->x -= rhs.x; this->y -= rhs.y; return *this;}
inline v2<T>& operator-=(const T rhs) {this->x -= rhs; this->y -= rhs; return *this;}
inline v2<T>& operator*=(const v2<T>& rhs) {this->x *= rhs.x; this->y *= rhs.y; return *this;} //vector-row multiplication
inline v2<T>& operator*=(const T rhs) {this->x *= rhs; this->y *= rhs; return *this;}
template <typename TC>
inline explicit operator v2<TC>() const {return v2<TC>{static_cast<TC>(this->x), static_cast<TC>(this->y)};}
};
template <typename T>
inline v2<T> operator+ (const v2<T>& lhs, const v2<T>& rhs)
{
return v2<T>{lhs.x + rhs.x, lhs.y + rhs.y};
}
template <typename T>
inline v2<T> operator- (const v2<T>& lhs, const v2<T>& rhs)
{
return v2<T>{lhs.x - rhs.x, lhs.y - rhs.y};
}
template <typename T> //vector-row multiplication
inline v2<T> operator^ (const v2<T>&lhs, const v2<T>&rhs)
{
return v2<T>{lhs.x * rhs.x, lhs.y * rhs.y};
}
template <typename T> //vector-scalar multiplication
inline v2<T> operator* (const v2<T>&lhs, const T rhs)
{
return v2<T>{lhs.x * rhs, lhs.y * rhs};
}
template <typename T> //vector-scalar division
inline v2<T> operator/ (const v2<T>&lhs, const T rhs)
{
return v2<T>{lhs.x / rhs, lhs.y / rhs};
}
template <typename T> //scalar multiplication
inline T operator* (const v2<T>&lhs, const v2<T>& rhs)
{
return lhs.x * rhs.x + lhs.y * rhs.y;
}
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const v2<T>& vec)
{
os << "X: " << +vec.x << " Y: " << +vec.y << " ";
return os;
}
inline int log2(uint32_t num)
{
int counter = 0;
while (num >>= 1) counter++;
return counter;
}
}
#endif //CREN_UTIL_H
| 26.816733 | 149 | 0.471401 | [
"render",
"vector"
] |
022cbd6538b51f4d28a85100f22461449a84fca1 | 20,312 | cc | C++ | src/kernel/x64/irqs-x64.cc | Myrannas/runtime | d81f9ec641bb84e6713ae2ad8de29e1e54c65f4d | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-03-06T20:08:50.000Z | 2018-03-06T20:08:50.000Z | src/kernel/x64/irqs-x64.cc | Myrannas/runtime | d81f9ec641bb84e6713ae2ad8de29e1e54c65f4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/kernel/x64/irqs-x64.cc | Myrannas/runtime | d81f9ec641bb84e6713ae2ad8de29e1e54c65f4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright 2014 Runtime.JS project authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <kernel/kernel.h>
#include <kernel/irqs.h>
#include <kernel/x64/io-x64.h>
#include <kernel/x64/irqs-x64.h>
extern "C" {
#define GATE(NAME) uint64_t NAME()
GATE(int_gate_exception_DE);
GATE(int_gate_exception_DB);
GATE(int_gate_exception_NMI);
GATE(int_gate_exception_BP);
GATE(int_gate_exception_OF);
GATE(int_gate_exception_BR);
GATE(int_gate_exception_UD);
GATE(int_gate_exception_NM);
GATE(int_gate_exception_DF);
GATE(int_gate_exception_TS);
GATE(int_gate_exception_NP);
GATE(int_gate_exception_SS);
GATE(int_gate_exception_GP);
GATE(int_gate_exception_PF);
GATE(int_gate_exception_MF);
GATE(int_gate_exception_AC);
GATE(int_gate_exception_MC);
GATE(int_gate_exception_XF);
GATE(int_gate_exception_SX);
GATE(int_gate_exception_other);
GATE(int_gate_irq_timer);
GATE(int_gate_irq_keyboard);
GATE(int_gate_irq_other);
GATE(int_gate_irq_spurious);
GATE(gate_context_switch);
GATE(_irq_gate_20);
GATE(_irq_gate_21);
GATE(_irq_gate_22);
GATE(_irq_gate_23);
GATE(_irq_gate_24);
GATE(_irq_gate_25);
GATE(_irq_gate_26);
GATE(_irq_gate_27);
GATE(_irq_gate_28);
GATE(_irq_gate_29);
GATE(_irq_gate_2a);
GATE(_irq_gate_2b);
GATE(_irq_gate_2c);
GATE(_irq_gate_2d);
GATE(_irq_gate_2e);
GATE(_irq_gate_2f);
GATE(_irq_gate_30);
GATE(_irq_gate_31);
GATE(_irq_gate_32);
GATE(_irq_gate_33);
GATE(_irq_gate_34);
GATE(_irq_gate_35);
GATE(_irq_gate_36);
GATE(_irq_gate_37);
GATE(_irq_gate_38);
GATE(_irq_gate_39);
GATE(_irq_gate_3a);
GATE(_irq_gate_3b);
GATE(_irq_gate_3c);
GATE(_irq_gate_3d);
GATE(_irq_gate_3e);
GATE(_irq_gate_3f);
GATE(_irq_gate_40);
GATE(_irq_gate_41);
GATE(_irq_gate_42);
GATE(_irq_gate_43);
GATE(_irq_gate_44);
GATE(_irq_gate_45);
GATE(_irq_gate_46);
GATE(_irq_gate_47);
GATE(_irq_gate_48);
GATE(_irq_gate_49);
GATE(_irq_gate_4a);
GATE(_irq_gate_4b);
GATE(_irq_gate_4c);
GATE(_irq_gate_4d);
GATE(_irq_gate_4e);
GATE(_irq_gate_4f);
GATE(_irq_gate_50);
GATE(_irq_gate_51);
GATE(_irq_gate_52);
GATE(_irq_gate_53);
GATE(_irq_gate_54);
GATE(_irq_gate_55);
GATE(_irq_gate_56);
GATE(_irq_gate_57);
GATE(_irq_gate_58);
GATE(_irq_gate_59);
GATE(_irq_gate_5a);
GATE(_irq_gate_5b);
GATE(_irq_gate_5c);
GATE(_irq_gate_5d);
GATE(_irq_gate_5e);
GATE(_irq_gate_5f);
GATE(_irq_gate_60);
GATE(_irq_gate_61);
GATE(_irq_gate_62);
GATE(_irq_gate_63);
GATE(_irq_gate_64);
GATE(_irq_gate_65);
GATE(_irq_gate_66);
GATE(_irq_gate_67);
GATE(_irq_gate_68);
GATE(_irq_gate_69);
GATE(_irq_gate_6a);
GATE(_irq_gate_6b);
GATE(_irq_gate_6c);
GATE(_irq_gate_6d);
GATE(_irq_gate_6e);
GATE(_irq_gate_6f);
GATE(_irq_gate_70);
GATE(_irq_gate_71);
GATE(_irq_gate_72);
GATE(_irq_gate_73);
GATE(_irq_gate_74);
GATE(_irq_gate_75);
GATE(_irq_gate_76);
GATE(_irq_gate_77);
GATE(_irq_gate_78);
GATE(_irq_gate_79);
GATE(_irq_gate_7a);
GATE(_irq_gate_7b);
GATE(_irq_gate_7c);
GATE(_irq_gate_7d);
GATE(_irq_gate_7e);
GATE(_irq_gate_7f);
GATE(_irq_gate_80);
GATE(_irq_gate_81);
GATE(_irq_gate_82);
GATE(_irq_gate_83);
GATE(_irq_gate_84);
GATE(_irq_gate_85);
GATE(_irq_gate_86);
GATE(_irq_gate_87);
GATE(_irq_gate_88);
GATE(_irq_gate_89);
GATE(_irq_gate_8a);
GATE(_irq_gate_8b);
GATE(_irq_gate_8c);
GATE(_irq_gate_8d);
GATE(_irq_gate_8e);
GATE(_irq_gate_8f);
GATE(_irq_gate_90);
GATE(_irq_gate_91);
GATE(_irq_gate_92);
GATE(_irq_gate_93);
GATE(_irq_gate_94);
GATE(_irq_gate_95);
GATE(_irq_gate_96);
GATE(_irq_gate_97);
GATE(_irq_gate_98);
GATE(_irq_gate_99);
GATE(_irq_gate_9a);
GATE(_irq_gate_9b);
GATE(_irq_gate_9c);
GATE(_irq_gate_9d);
GATE(_irq_gate_9e);
GATE(_irq_gate_9f);
GATE(_irq_gate_a0);
GATE(_irq_gate_a1);
GATE(_irq_gate_a2);
GATE(_irq_gate_a3);
GATE(_irq_gate_a4);
GATE(_irq_gate_a5);
GATE(_irq_gate_a6);
GATE(_irq_gate_a7);
GATE(_irq_gate_a8);
GATE(_irq_gate_a9);
GATE(_irq_gate_aa);
GATE(_irq_gate_ab);
GATE(_irq_gate_ac);
GATE(_irq_gate_ad);
GATE(_irq_gate_ae);
GATE(_irq_gate_af);
GATE(_irq_gate_b0);
GATE(_irq_gate_b1);
GATE(_irq_gate_b2);
GATE(_irq_gate_b3);
GATE(_irq_gate_b4);
GATE(_irq_gate_b5);
GATE(_irq_gate_b6);
GATE(_irq_gate_b7);
GATE(_irq_gate_b8);
GATE(_irq_gate_b9);
GATE(_irq_gate_ba);
GATE(_irq_gate_bb);
GATE(_irq_gate_bc);
GATE(_irq_gate_bd);
GATE(_irq_gate_be);
GATE(_irq_gate_bf);
GATE(_irq_gate_c0);
GATE(_irq_gate_c1);
GATE(_irq_gate_c2);
GATE(_irq_gate_c3);
GATE(_irq_gate_c4);
GATE(_irq_gate_c5);
GATE(_irq_gate_c6);
GATE(_irq_gate_c7);
GATE(_irq_gate_c8);
GATE(_irq_gate_c9);
GATE(_irq_gate_ca);
GATE(_irq_gate_cb);
GATE(_irq_gate_cc);
GATE(_irq_gate_cd);
GATE(_irq_gate_ce);
GATE(_irq_gate_cf);
GATE(_irq_gate_d0);
GATE(_irq_gate_d1);
GATE(_irq_gate_d2);
GATE(_irq_gate_d3);
GATE(_irq_gate_d4);
GATE(_irq_gate_d5);
GATE(_irq_gate_d6);
GATE(_irq_gate_d7);
GATE(_irq_gate_d8);
GATE(_irq_gate_d9);
GATE(_irq_gate_da);
GATE(_irq_gate_db);
GATE(_irq_gate_dc);
GATE(_irq_gate_dd);
GATE(_irq_gate_de);
GATE(_irq_gate_df);
GATE(_irq_gate_e0);
GATE(_irq_gate_e1);
GATE(_irq_gate_e2);
GATE(_irq_gate_e3);
GATE(_irq_gate_e4);
GATE(_irq_gate_e5);
GATE(_irq_gate_e6);
GATE(_irq_gate_e7);
GATE(_irq_gate_e8);
GATE(_irq_gate_e9);
GATE(_irq_gate_ea);
GATE(_irq_gate_eb);
GATE(_irq_gate_ec);
GATE(_irq_gate_ed);
GATE(_irq_gate_ee);
GATE(_irq_gate_ef);
GATE(_irq_gate_f0);
GATE(_irq_gate_f1);
GATE(_irq_gate_f2);
GATE(_irq_gate_f3);
GATE(_irq_gate_f4);
GATE(_irq_gate_f5);
GATE(_irq_gate_f6);
GATE(_irq_gate_f7);
GATE(_irq_gate_f8);
GATE(_irq_gate_f9);
GATE(_irq_gate_fa);
GATE(_irq_gate_fb);
GATE(_irq_gate_fc);
GATE(_irq_gate_fd);
GATE(_irq_gate_fe);
#undef GATE
} // extern "C"
namespace rt {
void IrqsArch::DisableNMI() {
IoPortsX64::OutB(0x70, IoPortsX64::InB(0x70) | 0x80);
}
void IrqsArch::EnableNMI() {
IoPortsX64::OutB(0x70, IoPortsX64::InB(0x70) & 0x7F);
}
void IrqsArch::InstallGate(uint8_t vector, uint64_t (*func)(), uint8_t type) {
uint8_t* idt_table = (uint8_t*)kIDTTableBase;
uint8_t b[16];
b[0] = (uint64_t)func & 0x00000000000000FF;
b[1] = ((uint64_t)func & 0x000000000000FF00) >> 8;
b[2] = kCodeSelector;
b[3] = 0;
b[4] = 0;
b[5] = type;
b[6] = ((uint64_t)func & 0x0000000000FF0000) >> 16;
b[7] = ((uint64_t)func & 0x00000000FF000000) >> 24;
b[8] = ((uint64_t)func & 0x000000FF00000000) >> 32;
b[9] = ((uint64_t)func & 0x0000FF0000000000) >> 40;
b[10] = ((uint64_t)func & 0x00FF000000000000) >> 48;
b[11] = ((uint64_t)func & 0xFF00000000000000) >> 56;
b[12] = 0;
b[13] = 0;
b[14] = 0;
b[15] = 0;
for (uint32_t i = 0; i < 16; ++i) {
*(idt_table + vector * 16 + i) = b[i];
}
}
void IrqsArch::SetUp() {
DisableNMI();
// Remap IRQs
IoPortsX64::OutB(0x20, 0x11); // 00010001b, begin PIC 1 initialization
IoPortsX64::OutB(0xA0, 0x11); // 00010001b, begin PIC 2 initialization
IoPortsX64::OutB(0x21, 0x20); // IRQ 0-7, interrupts 20h-27h
IoPortsX64::OutB(0xA1, 0x28); // IRQ 8-15, interrupts 28h-2Fh
IoPortsX64::OutB(0x21, 0x04);
IoPortsX64::OutB(0xA1, 0x02);
IoPortsX64::OutB(0x21, 0x01);
IoPortsX64::OutB(0xA1, 0x01);
// Mask all PIC interrupts
IoPortsX64::OutB(0x21, 0xFF);
IoPortsX64::OutB(0xA1, 0xFF);
// Gate type
uint8_t type = 0x8e;
// Exceptions (0-31)
InstallGate(0x00, &int_gate_exception_DE, type);
InstallGate(0x01, &int_gate_exception_DB, type);
InstallGate(0x02, &int_gate_exception_NMI,type);
InstallGate(0x03, &int_gate_exception_BP, type);
InstallGate(0x04, &int_gate_exception_OF, type);
InstallGate(0x05, &int_gate_exception_BR, type);
InstallGate(0x06, &int_gate_exception_UD, type);
InstallGate(0x07, &int_gate_exception_NM, type);
InstallGate(0x08, &int_gate_exception_DF, type);
InstallGate(0x09, &int_gate_exception_other, type);
InstallGate(0x0A, &int_gate_exception_TS, type);
InstallGate(0x0B, &int_gate_exception_NP, type);
InstallGate(0x0C, &int_gate_exception_SS, type);
InstallGate(0x0D, &int_gate_exception_GP, type);
InstallGate(0x0E, &int_gate_exception_PF, type);
InstallGate(0x0F, &int_gate_exception_other, type);
InstallGate(0x10, &int_gate_exception_MF, type);
InstallGate(0x11, &int_gate_exception_AC, type);
InstallGate(0x12, &int_gate_exception_MC, type);
InstallGate(0x13, &int_gate_exception_XF, type);
InstallGate(0x14, &int_gate_exception_other, type);
InstallGate(0x15, &int_gate_exception_other, type);
InstallGate(0x16, &int_gate_exception_other, type);
InstallGate(0x17, &int_gate_exception_other, type);
InstallGate(0x18, &int_gate_exception_other, type);
InstallGate(0x19, &int_gate_exception_other, type);
InstallGate(0x1A, &int_gate_exception_other, type);
InstallGate(0x1B, &int_gate_exception_other, type);
InstallGate(0x1C, &int_gate_exception_other, type);
InstallGate(0x1D, &int_gate_exception_other, type);
InstallGate(0x1E, &int_gate_exception_SX, type);
InstallGate(0x1F, &int_gate_exception_other, type);
// Special
InstallGate(0x20, &int_gate_irq_timer, type);
// Other
InstallGate(0x21, &_irq_gate_21, type);
InstallGate(0x22, &_irq_gate_22, type);
InstallGate(0x23, &_irq_gate_23, type);
InstallGate(0x24, &_irq_gate_24, type);
InstallGate(0x25, &_irq_gate_25, type);
InstallGate(0x26, &_irq_gate_26, type);
InstallGate(0x27, &_irq_gate_27, type);
InstallGate(0x28, &_irq_gate_28, type);
InstallGate(0x29, &_irq_gate_29, type);
InstallGate(0x2a, &_irq_gate_2a, type);
InstallGate(0x2b, &_irq_gate_2b, type);
InstallGate(0x2c, &_irq_gate_2c, type);
InstallGate(0x2d, &_irq_gate_2d, type);
InstallGate(0x2e, &_irq_gate_2e, type);
InstallGate(0x2f, &_irq_gate_2f, type);
InstallGate(0x30, &_irq_gate_30, type);
InstallGate(0x31, &_irq_gate_31, type);
InstallGate(0x32, &_irq_gate_32, type);
InstallGate(0x33, &_irq_gate_33, type);
InstallGate(0x34, &_irq_gate_34, type);
InstallGate(0x35, &_irq_gate_35, type);
InstallGate(0x36, &_irq_gate_36, type);
InstallGate(0x37, &_irq_gate_37, type);
InstallGate(0x38, &_irq_gate_38, type);
InstallGate(0x39, &_irq_gate_39, type);
InstallGate(0x3a, &_irq_gate_3a, type);
InstallGate(0x3b, &_irq_gate_3b, type);
InstallGate(0x3c, &_irq_gate_3c, type);
InstallGate(0x3d, &_irq_gate_3d, type);
InstallGate(0x3e, &_irq_gate_3e, type);
InstallGate(0x3f, &_irq_gate_3f, type);
InstallGate(0x40, &_irq_gate_40, type);
InstallGate(0x41, &_irq_gate_41, type);
InstallGate(0x42, &_irq_gate_42, type);
InstallGate(0x43, &_irq_gate_43, type);
InstallGate(0x44, &_irq_gate_44, type);
InstallGate(0x45, &_irq_gate_45, type);
InstallGate(0x46, &_irq_gate_46, type);
InstallGate(0x47, &_irq_gate_47, type);
InstallGate(0x48, &_irq_gate_48, type);
InstallGate(0x49, &_irq_gate_49, type);
InstallGate(0x4a, &_irq_gate_4a, type);
InstallGate(0x4b, &_irq_gate_4b, type);
InstallGate(0x4c, &_irq_gate_4c, type);
InstallGate(0x4d, &_irq_gate_4d, type);
InstallGate(0x4e, &_irq_gate_4e, type);
InstallGate(0x4f, &_irq_gate_4f, type);
InstallGate(0x50, &_irq_gate_50, type);
InstallGate(0x51, &_irq_gate_51, type);
InstallGate(0x52, &_irq_gate_52, type);
InstallGate(0x53, &_irq_gate_53, type);
InstallGate(0x54, &_irq_gate_54, type);
InstallGate(0x55, &_irq_gate_55, type);
InstallGate(0x56, &_irq_gate_56, type);
InstallGate(0x57, &_irq_gate_57, type);
InstallGate(0x58, &_irq_gate_58, type);
InstallGate(0x59, &_irq_gate_59, type);
InstallGate(0x5a, &_irq_gate_5a, type);
InstallGate(0x5b, &_irq_gate_5b, type);
InstallGate(0x5c, &_irq_gate_5c, type);
InstallGate(0x5d, &_irq_gate_5d, type);
InstallGate(0x5e, &_irq_gate_5e, type);
InstallGate(0x5f, &_irq_gate_5f, type);
InstallGate(0x60, &_irq_gate_60, type);
InstallGate(0x61, &_irq_gate_61, type);
InstallGate(0x62, &_irq_gate_62, type);
InstallGate(0x63, &_irq_gate_63, type);
InstallGate(0x64, &_irq_gate_64, type);
InstallGate(0x65, &_irq_gate_65, type);
InstallGate(0x66, &_irq_gate_66, type);
InstallGate(0x67, &_irq_gate_67, type);
InstallGate(0x68, &_irq_gate_68, type);
InstallGate(0x69, &_irq_gate_69, type);
InstallGate(0x6a, &_irq_gate_6a, type);
InstallGate(0x6b, &_irq_gate_6b, type);
InstallGate(0x6c, &_irq_gate_6c, type);
InstallGate(0x6d, &_irq_gate_6d, type);
InstallGate(0x6e, &_irq_gate_6e, type);
InstallGate(0x6f, &_irq_gate_6f, type);
InstallGate(0x70, &_irq_gate_70, type);
InstallGate(0x71, &_irq_gate_71, type);
InstallGate(0x72, &_irq_gate_72, type);
InstallGate(0x73, &_irq_gate_73, type);
InstallGate(0x74, &_irq_gate_74, type);
InstallGate(0x75, &_irq_gate_75, type);
InstallGate(0x76, &_irq_gate_76, type);
InstallGate(0x77, &_irq_gate_77, type);
InstallGate(0x78, &_irq_gate_78, type);
InstallGate(0x79, &_irq_gate_79, type);
InstallGate(0x7a, &_irq_gate_7a, type);
InstallGate(0x7b, &_irq_gate_7b, type);
InstallGate(0x7c, &_irq_gate_7c, type);
InstallGate(0x7d, &_irq_gate_7d, type);
InstallGate(0x7e, &_irq_gate_7e, type);
InstallGate(0x7f, &_irq_gate_7f, type);
InstallGate(0x80, &_irq_gate_80, type);
InstallGate(0x81, &_irq_gate_81, type);
InstallGate(0x82, &_irq_gate_82, type);
InstallGate(0x83, &_irq_gate_83, type);
InstallGate(0x84, &_irq_gate_84, type);
InstallGate(0x85, &_irq_gate_85, type);
InstallGate(0x86, &_irq_gate_86, type);
InstallGate(0x87, &_irq_gate_87, type);
InstallGate(0x88, &_irq_gate_88, type);
InstallGate(0x89, &_irq_gate_89, type);
InstallGate(0x8a, &_irq_gate_8a, type);
InstallGate(0x8b, &_irq_gate_8b, type);
InstallGate(0x8c, &_irq_gate_8c, type);
InstallGate(0x8d, &_irq_gate_8d, type);
InstallGate(0x8e, &_irq_gate_8e, type);
InstallGate(0x8f, &_irq_gate_8f, type);
InstallGate(0x90, &_irq_gate_90, type);
InstallGate(0x91, &_irq_gate_91, type);
InstallGate(0x92, &_irq_gate_92, type);
InstallGate(0x93, &_irq_gate_93, type);
InstallGate(0x94, &_irq_gate_94, type);
InstallGate(0x95, &_irq_gate_95, type);
InstallGate(0x96, &_irq_gate_96, type);
InstallGate(0x97, &_irq_gate_97, type);
InstallGate(0x98, &_irq_gate_98, type);
InstallGate(0x99, &_irq_gate_99, type);
InstallGate(0x9a, &_irq_gate_9a, type);
InstallGate(0x9b, &_irq_gate_9b, type);
InstallGate(0x9c, &_irq_gate_9c, type);
InstallGate(0x9d, &_irq_gate_9d, type);
InstallGate(0x9e, &_irq_gate_9e, type);
InstallGate(0x9f, &_irq_gate_9f, type);
InstallGate(0xa0, &_irq_gate_a0, type);
InstallGate(0xa1, &_irq_gate_a1, type);
InstallGate(0xa2, &_irq_gate_a2, type);
InstallGate(0xa3, &_irq_gate_a3, type);
InstallGate(0xa4, &_irq_gate_a4, type);
InstallGate(0xa5, &_irq_gate_a5, type);
InstallGate(0xa6, &_irq_gate_a6, type);
InstallGate(0xa7, &_irq_gate_a7, type);
InstallGate(0xa8, &_irq_gate_a8, type);
InstallGate(0xa9, &_irq_gate_a9, type);
InstallGate(0xaa, &_irq_gate_aa, type);
InstallGate(0xab, &_irq_gate_ab, type);
InstallGate(0xac, &_irq_gate_ac, type);
InstallGate(0xad, &_irq_gate_ad, type);
InstallGate(0xae, &_irq_gate_ae, type);
InstallGate(0xaf, &_irq_gate_af, type);
InstallGate(0xb0, &_irq_gate_b0, type);
InstallGate(0xb1, &_irq_gate_b1, type);
InstallGate(0xb2, &_irq_gate_b2, type);
InstallGate(0xb3, &_irq_gate_b3, type);
InstallGate(0xb4, &_irq_gate_b4, type);
InstallGate(0xb5, &_irq_gate_b5, type);
InstallGate(0xb6, &_irq_gate_b6, type);
InstallGate(0xb7, &_irq_gate_b7, type);
InstallGate(0xb8, &_irq_gate_b8, type);
InstallGate(0xb9, &_irq_gate_b9, type);
InstallGate(0xba, &_irq_gate_ba, type);
InstallGate(0xbb, &_irq_gate_bb, type);
InstallGate(0xbc, &_irq_gate_bc, type);
InstallGate(0xbd, &_irq_gate_bd, type);
InstallGate(0xbe, &_irq_gate_be, type);
InstallGate(0xbf, &_irq_gate_bf, type);
InstallGate(0xc0, &_irq_gate_c0, type);
InstallGate(0xc1, &_irq_gate_c1, type);
InstallGate(0xc2, &_irq_gate_c2, type);
InstallGate(0xc3, &_irq_gate_c3, type);
InstallGate(0xc4, &_irq_gate_c4, type);
InstallGate(0xc5, &_irq_gate_c5, type);
InstallGate(0xc6, &_irq_gate_c6, type);
InstallGate(0xc7, &_irq_gate_c7, type);
InstallGate(0xc8, &_irq_gate_c8, type);
InstallGate(0xc9, &_irq_gate_c9, type);
InstallGate(0xca, &_irq_gate_ca, type);
InstallGate(0xcb, &_irq_gate_cb, type);
InstallGate(0xcc, &_irq_gate_cc, type);
InstallGate(0xcd, &_irq_gate_cd, type);
InstallGate(0xce, &_irq_gate_ce, type);
InstallGate(0xcf, &_irq_gate_cf, type);
InstallGate(0xd0, &_irq_gate_d0, type);
InstallGate(0xd1, &_irq_gate_d1, type);
InstallGate(0xd2, &_irq_gate_d2, type);
InstallGate(0xd3, &_irq_gate_d3, type);
InstallGate(0xd4, &_irq_gate_d4, type);
InstallGate(0xd5, &_irq_gate_d5, type);
InstallGate(0xd6, &_irq_gate_d6, type);
InstallGate(0xd7, &_irq_gate_d7, type);
InstallGate(0xd8, &_irq_gate_d8, type);
InstallGate(0xd9, &_irq_gate_d9, type);
InstallGate(0xda, &_irq_gate_da, type);
InstallGate(0xdb, &_irq_gate_db, type);
InstallGate(0xdc, &_irq_gate_dc, type);
InstallGate(0xdd, &_irq_gate_dd, type);
InstallGate(0xde, &_irq_gate_de, type);
InstallGate(0xdf, &_irq_gate_df, type);
InstallGate(0xe0, &_irq_gate_e0, type);
InstallGate(0xe1, &_irq_gate_e1, type);
InstallGate(0xe2, &_irq_gate_e2, type);
InstallGate(0xe3, &_irq_gate_e3, type);
InstallGate(0xe4, &_irq_gate_e4, type);
InstallGate(0xe5, &_irq_gate_e5, type);
InstallGate(0xe6, &_irq_gate_e6, type);
InstallGate(0xe7, &_irq_gate_e7, type);
InstallGate(0xe8, &_irq_gate_e8, type);
InstallGate(0xe9, &_irq_gate_e9, type);
InstallGate(0xea, &_irq_gate_ea, type);
InstallGate(0xeb, &_irq_gate_eb, type);
InstallGate(0xec, &_irq_gate_ec, type);
InstallGate(0xed, &_irq_gate_ed, type);
InstallGate(0xee, &_irq_gate_ee, type);
InstallGate(0xef, &_irq_gate_ef, type);
InstallGate(0xf0, &_irq_gate_f0, type);
InstallGate(0xf1, &_irq_gate_f1, type);
InstallGate(0xf2, &_irq_gate_f2, type);
InstallGate(0xf3, &_irq_gate_f3, type);
InstallGate(0xf4, &_irq_gate_f4, type);
InstallGate(0xf5, &_irq_gate_f5, type);
InstallGate(0xf6, &_irq_gate_f6, type);
InstallGate(0xf7, &_irq_gate_f7, type);
InstallGate(0xf8, &_irq_gate_f8, type);
InstallGate(0xf9, &_irq_gate_f9, type);
InstallGate(0xfa, &_irq_gate_fa, type);
InstallGate(0xfb, &_irq_gate_fb, type);
InstallGate(0xfc, &_irq_gate_fc, type);
InstallGate(0xfd, &_irq_gate_fd, type);
InstallGate(0xfe, &_irq_gate_fe, type);
// Spurious
InstallGate(0xff, &int_gate_irq_spurious, type);
}
} // namespace rt
| 33.90985 | 78 | 0.693728 | [
"vector"
] |
0230a3581b0287a6667932e608350182a6aaed24 | 1,256 | cpp | C++ | PrehistoricEngine/src/engine/platform/opengl/rendering/shaders/gui/GLGUIShader.cpp | Andrispowq/PrehistoricEngine---C- | 04159c9119b2f5e0148de21a85aa0dab2d6ba60e | [
"Apache-2.0"
] | 1 | 2020-12-04T13:36:03.000Z | 2020-12-04T13:36:03.000Z | PrehistoricEngine/src/engine/platform/opengl/rendering/shaders/gui/GLGUIShader.cpp | Andrispowq/PrehistoricEngine---C- | 04159c9119b2f5e0148de21a85aa0dab2d6ba60e | [
"Apache-2.0"
] | null | null | null | PrehistoricEngine/src/engine/platform/opengl/rendering/shaders/gui/GLGUIShader.cpp | Andrispowq/PrehistoricEngine---C- | 04159c9119b2f5e0148de21a85aa0dab2d6ba60e | [
"Apache-2.0"
] | null | null | null | #include "Includes.hpp"
#include "GLGUIShader.h"
#include "prehistoric/core/modules/gui/GUIElement.h"
#include "prehistoric/core/modules/gui/slider/GUISlider.h"
namespace Prehistoric
{
GLGUIShader::GLGUIShader()
: GLShader()
{
AddShader(ResourceLoader::LoadShaderGL("opengl/gui/gui_VS.glsl"), VERTEX_SHADER);
AddShader(ResourceLoader::LoadShaderGL("opengl/gui/gui_FS.glsl"), FRAGMENT_SHADER);
CompileShader();
AddUniform("m_transform");
AddUniform("colour");
AddUniform("image");
}
void GLGUIShader::UpdateCustomUniforms(Texture* texture, Vector3f colour) const
{
SetUniform("m_transform", Matrix4f::Identity());
SetUniform("colour", colour);
texture->Bind();
SetUniformi("image", 0);
}
void GLGUIShader::UpdateObjectUniforms(GameObject* object, uint32_t instance_index) const
{
GUIElement* gui = reinterpret_cast<GUIElement*>(object);
if (gui->getType() == GUIType::Slider)
{
GUISlider* gui_slider = reinterpret_cast<GUISlider*>(gui);
SetUniform("m_transform", gui_slider->getSliderTransform());
SetUniform("colour", gui_slider->getSliderColour());
}
else
{
SetUniform("m_transform", object->getWorldTransform().getTransformationMatrix());
SetUniform("colour", gui->getColour());
}
}
}; | 26.166667 | 90 | 0.730892 | [
"object"
] |
0231d97fecf42ab40ff489d4ef054733e5dbb20b | 9,656 | cpp | C++ | ScissorPoly/adjust_orientation_LBFGS.cpp | msraig/CE-PolyCube | e46aff6e0594b711735118bfa902a91bc3d392ca | [
"MIT"
] | 19 | 2020-08-13T05:15:09.000Z | 2022-03-31T14:51:29.000Z | ScissorPoly/adjust_orientation_LBFGS.cpp | xh-liu-tech/CE-PolyCube | 86d4ed0023215307116b6b3245e2dbd82907cbb8 | [
"MIT"
] | 2 | 2020-09-08T07:03:04.000Z | 2021-08-04T05:43:27.000Z | ScissorPoly/adjust_orientation_LBFGS.cpp | xh-liu-tech/CE-PolyCube | 86d4ed0023215307116b6b3245e2dbd82907cbb8 | [
"MIT"
] | 10 | 2020-08-06T02:37:46.000Z | 2021-07-01T09:12:06.000Z | #include "adjust_orientation_LBFGS.h"
#include <Eigen/Dense>
#include <Eigen/Sparse>
using Eigen::Matrix3d;
using Eigen::Vector3d;
void evalfunc_ad_LBFGS(int N, double* x, double *prev_x, double* f, double* g, void* user_pointer)
{
double alpha = x[0]; double beta = x[1]; double gamma = x[2];
double cos_alpha = std::cos(alpha); double sin_alpha = std::sin(alpha);
double cos_beta = std::cos(beta); double sin_beta = std::sin(beta);
double cos_gamma = std::cos(gamma); double sin_gamma = std::sin(gamma);
double r00 = cos_alpha*cos_gamma - cos_beta*sin_alpha*sin_gamma;
double r01 = sin_alpha*cos_gamma + cos_beta*cos_alpha*sin_gamma;
double r02 = sin_beta*sin_gamma;
double r10 = -cos_alpha*sin_gamma - cos_beta*sin_alpha*cos_gamma;
double r11 = -sin_alpha*sin_gamma + cos_beta*cos_alpha*cos_gamma;
double r12 = sin_beta*cos_gamma;
double r20 = sin_beta*sin_alpha;
double r21 = -sin_beta*cos_alpha;
double r22 = cos_beta;
user_pointer_ad* up = (user_pointer_ad*)(user_pointer);
int nbf = (int)up->bfn.size(); *f = 0.0;
g[0] = 0; g[1] = 0; g[2] = 0;
for (int i = 0; i < nbf; ++i)
{
OpenVolumeMesh::Geometry::Vec3d& n = up->bfn[i];
//OpenVolumeMesh::Geometry::Vec3d n(4.0, 5.0, 6.0);
double nx = r00 * n[0] + r01 * n[1] + r02 * n[2];
double ny = r10 * n[0] + r11 * n[1] + r12 * n[2];
double nz = r20 * n[0] + r21 * n[1] + r22 * n[2];
*f += (nx*ny)*(nx*ny) + (ny*nz)*(ny*nz) + (nz*nx)*(nz*nx);
double d_nx_alpha = (-sin_alpha*cos_gamma - cos_beta*cos_alpha*sin_gamma) * n[0] + (cos_alpha*cos_gamma - cos_beta*sin_alpha*sin_gamma) * n[1] + 0 * n[2];
double d_ny_alpha = (sin_alpha*sin_gamma - cos_beta*cos_alpha*cos_gamma) * n[0] + (-cos_alpha*sin_gamma - cos_beta*sin_alpha*cos_gamma) * n[1] + 0 * n[2];
double d_nz_alpha = sin_beta*cos_alpha * n[0] + sin_beta*sin_alpha * n[1] + 0 * n[2];
double d_nx_beta = (sin_beta*sin_alpha*sin_gamma) * n[0] + (-sin_beta*cos_alpha*sin_gamma) * n[1] + cos_beta*sin_gamma * n[2];
double d_ny_beta = (sin_beta*sin_alpha*cos_gamma) * n[0] + (-sin_beta*cos_alpha*cos_gamma) * n[1] + cos_beta*cos_gamma * n[2];
double d_nz_beta = cos_beta*sin_alpha *n[0] - cos_beta*cos_alpha * n[1] - sin_beta * n[2];
double d_nx_gamma = (-cos_alpha*sin_gamma - cos_beta*sin_alpha*cos_gamma) * n[0] + (-sin_alpha*sin_gamma + cos_beta*cos_alpha*cos_gamma) * n[1] + sin_beta*cos_gamma * n[2];
double d_ny_gamma = (-cos_alpha*cos_gamma + cos_beta*sin_alpha*sin_gamma) * n[0] + (-sin_alpha*cos_gamma - cos_beta*cos_alpha*sin_gamma) * n[1] + (-sin_beta*sin_gamma) * n[2];
double d_nz_gamma = 0.0;
g[0] += 2 * (nx*ny)*(d_nx_alpha*ny + nx*d_ny_alpha) + 2 * (ny*nz)*(d_ny_alpha*nz + ny*d_nz_alpha) + 2 * (nz*nx)*(d_nz_alpha*nx + nz*d_nx_alpha);
g[1] += 2 * (nx*ny)*(d_nx_beta*ny + nx*d_ny_beta) + 2 * (ny*nz)*(d_ny_beta*nz + ny*d_nz_beta) + 2 * (nz*nx)*(d_nz_beta*nx + nz*d_nx_beta);
g[2] += 2 * (nx*ny)*(d_nx_gamma*ny + nx*d_ny_gamma) + 2 * (ny*nz)*(d_ny_gamma*nz + ny*d_nz_gamma) + 2 * (nz*nx)*(d_nz_gamma*nx + nz*d_nx_gamma);
std::cout << "g: " << g[0] << " " << g[1] << " " << g[2] << std::endl;
}
}
void evalfunc_ad_LBFGS_xyz(int N, double* x, double *prev_x, double* f, double* g, void* user_pointer)
{
//x y z axis rotation
double cos_phi = std::cos(x[0]), sin_phi = std::sin(x[0]);
double cos_theta = std::cos(x[1]), sin_theta = std::sin(x[1]);
double cos_xi = std::cos(x[2]), sin_xi = std::sin(x[2]);
Matrix3d Mtheta, Mphi, Msi, DMtheta, DMphi, DMsi;
Mtheta.setZero(); Mphi.setZero(); Msi.setZero();
Mphi(0,0) = 1; Mphi(1,1) = Mphi(2,2) = cos_phi, Mphi(1, 2) = sin_phi, Mphi(2, 1) = -sin_phi;
Mtheta(1, 1) = 1; Mtheta(0,0) = Mtheta(2,2) = cos_theta, Mtheta(2,0) = sin_theta, Mtheta(0, 2) = -sin_theta;
Msi(2, 2) = 1; Msi(0, 0) = Msi(1, 1) = cos_xi, Msi(0, 1) = sin_xi, Msi(1, 0) = -sin_xi;
DMtheta.setZero(); DMphi.setZero(); DMsi.setZero();
DMphi(1, 1) = DMphi(2, 2) = -sin_phi, DMphi(1, 2) = cos_phi, DMphi(2, 1) = -cos_phi;
DMtheta(0, 0) = DMtheta(2, 2) = -sin_theta, DMtheta(2, 0) = cos_theta, DMtheta(0, 2) = -cos_theta;
DMsi(0, 0) = DMsi(1, 1) = -sin_xi, DMsi(0, 1) = cos_xi, DMsi(1,0) = -cos_xi;
Matrix3d M = Msi * Mphi * Mtheta, dMsi = DMsi * Mphi * Mtheta, dMphi = Msi * DMphi * Mtheta, dMtheta = Msi * Mphi * DMtheta;
Vector3d DN, diffN_theta, diffN_phi, diffN_si;
double xy, yz, zx;
user_pointer_ad* up = (user_pointer_ad*)(user_pointer);
int nbf = (int)up->bfn.size(); *f = 0.0;
g[0] = 0; g[1] = 0; g[2] = 0;
for (int i = 0; i < nbf; ++i)
{
OpenVolumeMesh::Geometry::Vec3d& n = up->bfn[i];
Vector3d N(n[0], n[1], n[2]);
//Vector3d N(1, 2, 3);
DN = M * N;
diffN_theta = dMtheta * N;
diffN_phi = dMphi * N;
diffN_si = dMsi * N;
xy = DN[0] * DN[1];
yz = DN[1] * DN[2];
zx = DN[2] * DN[0];
*f += (xy * xy + yz * yz + zx * zx) / 2;
g[0] += xy * (diffN_phi[0] * DN[1] + DN[0] * diffN_phi[1]) +
yz * (diffN_phi[1] * DN[2] + DN[1] * diffN_phi[2]) +
zx * (diffN_phi[2] * DN[0] + DN[2] * diffN_phi[0]);
g[1] += xy * (diffN_theta[0] * DN[1] + DN[0] * diffN_theta[1]) +
yz * (diffN_theta[1] * DN[2] + DN[1] * diffN_theta[2]) +
zx * (diffN_theta[2] * DN[0] + DN[2] * diffN_theta[0]);
g[2] += xy * (diffN_si[0] * DN[1] + DN[0] * diffN_si[1]) +
yz * (diffN_si[1] * DN[2] + DN[1] * diffN_si[2]) +
zx * (diffN_si[2] * DN[0] + DN[2] * diffN_si[0]);
//std::cout << "f: " << *f << " g: " << g[0] << " " << g[1] << " " << g[2] << std::endl;
}
//double alpha = x[0]; double beta = x[1]; double gamma = x[2];
//double cos_alpha = std::cos(alpha); double sin_alpha = std::sin(alpha);
//double cos_beta = std::cos(beta); double sin_beta = std::sin(beta);
//double cos_gamma = std::cos(gamma); double sin_gamma = std::sin(gamma);
//double r00 = cos_alpha * cos_gamma - cos_beta * sin_alpha*sin_gamma;
//double r01 = sin_alpha * cos_gamma + cos_beta * cos_alpha*sin_gamma;
//double r02 = sin_beta * sin_gamma;
//double r10 = -cos_alpha * sin_gamma - cos_beta * sin_alpha*cos_gamma;
//double r11 = -sin_alpha * sin_gamma + cos_beta * cos_alpha*cos_gamma;
//double r12 = sin_beta * cos_gamma;
//double r20 = sin_beta * sin_alpha;
//double r21 = -sin_beta * cos_alpha;
//double r22 = cos_beta;
//user_pointer_ad* up = (user_pointer_ad*)(user_pointer);
//int nbf = up->bfn.size(); *f = 0.0;
//g[0] = 0; g[1] = 0; g[2] = 0;
//for (int i = 0; i < nbf; ++i)
//{
// OpenVolumeMesh::Geometry::Vec3d& n = up->bfn[i];
// double nx = r00 * n[0] + r01 * n[1] + r02 * n[2];
// double ny = r10 * n[0] + r11 * n[1] + r12 * n[2];
// double nz = r20 * n[0] + r21 * n[1] + r22 * n[2];
// //*f += (nx*ny)*(nx*ny) + (ny*nz)*(ny*nz) + (nz*nx)*(nz*nx);
// *f += nx * nx * nx * nx + ny * ny * ny * ny + nz * nz * nz * nz;
// double d_nx_alpha = (-sin_alpha * cos_gamma - cos_beta * cos_alpha*sin_gamma) * n[0] + (cos_alpha*cos_gamma - cos_beta * sin_alpha*sin_gamma) * n[1] + 0 * n[2];
// double d_ny_alpha = (sin_alpha*sin_gamma - cos_beta * cos_alpha*cos_gamma) * n[0] + (-cos_alpha * sin_gamma - cos_beta * sin_alpha*cos_gamma) * n[1] + 0 * n[2];
// double d_nz_alpha = sin_beta * cos_alpha * n[0] + sin_beta * sin_alpha * n[1] + 0 * n[2];
// double d_nx_beta = (sin_beta*sin_alpha*sin_gamma) * n[0] + (-sin_beta * cos_alpha*sin_gamma) * n[1] + cos_beta * sin_gamma * n[2];
// double d_ny_beta = (sin_beta*sin_alpha*cos_gamma) * n[0] + (-sin_beta * cos_alpha*cos_gamma) * n[1] + cos_beta * cos_gamma * n[2];
// double d_nz_beta = cos_beta * sin_alpha *n[0] - cos_beta * cos_alpha * n[1] - sin_beta * n[2];
// double d_nx_gamma = (-cos_alpha * sin_gamma - cos_beta * sin_alpha*cos_gamma) * n[0] + (-sin_alpha * sin_gamma + cos_beta * cos_alpha*cos_gamma) * n[1] + sin_beta * cos_gamma * n[2];
// double d_ny_gamma = (-cos_alpha * cos_gamma + cos_beta * sin_alpha*sin_gamma) * n[0] + (-sin_alpha * cos_gamma - cos_beta * cos_alpha*sin_gamma) * n[1] + (-sin_beta * sin_gamma) * n[2];
// double d_nz_gamma = 0.0;
// /*g[0] += 2 * (nx*ny)*(d_nx_alpha*ny + nx * d_ny_alpha) + 2 * (ny*nz)*(d_ny_alpha*nz + ny * d_nz_alpha) + 2 * (nz*nx)*(d_nz_alpha*nx + nz * d_nx_alpha);
// g[1] += 2 * (nx*ny)*(d_nx_beta*ny + nx * d_ny_beta) + 2 * (ny*nz)*(d_ny_beta*nz + ny * d_nz_beta) + 2 * (nz*nx)*(d_nz_beta*nx + nz * d_nx_beta);
// g[2] += 2 * (nx*ny)*(d_nx_gamma*ny + nx * d_ny_gamma) + 2 * (ny*nz)*(d_ny_gamma*nz + ny * d_nz_gamma) + 2 * (nz*nx)*(d_nz_gamma*nx + nz * d_nx_gamma);*/
// g[0] += 4 * nx * nx * nx * (d_nx_alpha) + 4 * ny * ny * ny * (d_ny_alpha) + 4 * nz * nz * nz * (d_nz_alpha);
// g[1] += 4 * nx * nx * nx * (d_nx_beta) + 4 * ny * ny * ny * (d_ny_beta) + 4 * nz * nz * nz * (d_nz_beta);
// g[2] += 4 * nx * nx * nx * (d_nx_gamma) + 4 * ny * ny * ny * (d_ny_gamma) + 4 * nz * nz * nz * (d_nz_gamma);
//}
}
void newiteration_ad_LBFGS(int iter, int call_iter, double *x, double* f, double *g, double* gnorm, void* user_pointer)
{
printf("%d %d; %4.3e, %4.3e\n", iter, call_iter, f[0], gnorm[0]);
}
bool ad_LBFGS(std::vector<OpenVolumeMesh::Geometry::Vec3d>& bfn, std::vector<double>& X)
{
user_pointer_ad up;
up.bfn = bfn;
//LBFGS
double parameter[20];
int info[20];
//initialize
INIT_HLBFGS(parameter, info);
parameter[2] = 0.9;
info[4] = 100; //number of iteration
info[6] = 0;
info[7] = 0; //if with hessian 1, without 0
info[10] = 0;
int N = 3; int M = 7;
//m is the number of history value
//n is the number of variables
printf("-------------------------------\n");
printf("start LBFGS\n");
//function change to nx^4 + ny^4 + nz^ 4?
//HLBFGS(N, M, &X[0], evalfunc_ad_LBFGS, 0, HLBFGS_UPDATE_Hessian, newiteration_ad_LBFGS, parameter, info, &up);
HLBFGS(N, M, &X[0], evalfunc_ad_LBFGS_xyz, 0, HLBFGS_UPDATE_Hessian, newiteration_ad_LBFGS, parameter, info, &up);
return true;
}
| 59.239264 | 189 | 0.61454 | [
"geometry",
"vector"
] |
023a37c2c948471f33c947d0fee8d3e40d915f5e | 501 | hpp | C++ | src/gcc/harden.hpp | triton/cc-wrapper | 4be147e091897efc080691567034127dfafd75b9 | [
"Apache-2.0"
] | 1 | 2018-09-27T05:08:35.000Z | 2018-09-27T05:08:35.000Z | src/gcc/harden.hpp | triton/cc-wrapper | 4be147e091897efc080691567034127dfafd75b9 | [
"Apache-2.0"
] | null | null | null | src/gcc/harden.hpp | triton/cc-wrapper | 4be147e091897efc080691567034127dfafd75b9 | [
"Apache-2.0"
] | 3 | 2017-12-24T22:07:05.000Z | 2020-11-26T01:20:16.000Z | #pragma once
#include <nonstd/span.hpp>
#include <nonstd/string_view.hpp>
#include <vector>
#include <gcc/args.hpp>
namespace cc_wrapper {
namespace gcc {
namespace harden {
struct Env {
bool position_independent;
bool optimize;
};
Env getEnv();
void appendFlags(std::vector<nonstd::string_view> &args, const Env &env,
const args::State &state);
bool isValidFlag(nonstd::string_view arg, const Env &env);
} // namespace harden
} // namespace gcc
} // namespace cc_wrapper
| 20.04 | 72 | 0.706587 | [
"vector"
] |
023f9778b27ea77e6f5679a254824f4692ff8ebf | 3,307 | cpp | C++ | NameDisambiguation/Name.cpp | rdiersing1/FuzzyNameMatching | 1511d35e7448c8fa34b77b6e3dcdf7f80c5a2a62 | [
"Apache-2.0"
] | null | null | null | NameDisambiguation/Name.cpp | rdiersing1/FuzzyNameMatching | 1511d35e7448c8fa34b77b6e3dcdf7f80c5a2a62 | [
"Apache-2.0"
] | 1 | 2017-01-12T21:38:31.000Z | 2017-01-12T21:38:31.000Z | NameDisambiguation/Name.cpp | rdiersing1/FuzzyNameMatching | 1511d35e7448c8fa34b77b6e3dcdf7f80c5a2a62 | [
"Apache-2.0"
] | null | null | null | #include "Name.h"
#include <sstream>
#include <algorithm>
#include <iostream>
#include <map>
using namespace std;
void removePeriods(string &s) { // Removes the periods from the string
string retString;
retString.reserve(s.size());
for (int i = 0; i < s.size(); ++i) {
if (s.at(i) != '.') {
retString.push_back(s.at(i));
}
}
s = retString;
}
void removeSpaces(string &s) { // Removes the spaces from the string
string retString;
retString.reserve(s.size());
for (int i = 0; i < s.size(); ++i) {
if (s.at(i) != ' ') {
retString.push_back(s.at(i));
}
}
s = retString;
}
string Name::toStr() const { // outputs a string of the name in the correct format
stringstream returnSS;
string s;
if (title.size() != 0) { // checks case where there is a title
returnSS << title << ". ";
}
for (unsigned i = 0; i < nameBlocks.size(); ++i) { // prints all of the blocks
returnSS << nameBlocks.at(i);
if (abbreviated.at(i)) { // prints a period if the name is abreviated
returnSS << '.';
}
returnSS << ' '; // prints a space after every name block (even the last one)
}
returnSS << "\t {Title: "; // prints title info
if (title.size() != 0) {
returnSS << title;
}
else {
returnSS << "None";
}
returnSS << ", Name blocks count: " << nameBlocks.size(); // Prints name block count
int numAbbreviatedComponents = 0;
for (int i = 0; i < abbreviated.size(); ++i) {
if (abbreviated.at(i)) {
++numAbbreviatedComponents;
}
}
returnSS << ", Abbreviated components count: " << numAbbreviatedComponents << '}'; // Prints abrivated component count
if (hasNickName) {
returnSS << " [";
for (unsigned i = 0; i < possibleNames.size(); ++i) {
if (possibleNames.at(i).size() != 0) {
returnSS << "Nickname: " << nameBlocks.at(i);
returnSS << ", Possible Names:";
for (set<string>::iterator it = possibleNames.at(i).begin(); it != possibleNames.at(i).end(); ++it) {
returnSS << *it << ' ';
}
}
}
returnSS << ']';
}
getline(returnSS, s);
return s;
}
Name::Name(string s, const set<string> &titles, const map<string, set<string> > &nickNames) { // constructs a name, sorts name blocks, notes abriviations, and
stringstream ss(s);
hasNickName = false;
while (!ss.eof()) { // parses the string
string temp;
ss >> temp;
removePeriods(temp); // Removes periods to put string in proper format
if (titles.count(temp) != 0) {
title = temp; // Checks if the name block is a title (based on list of "all" titles in titles.txt)
}
else if (temp.size() != 0) { // Ensures no name block is empty
removeSpaces(temp); // Ensures no name block contains spaces
nameBlocks.push_back(temp);
}
}
sort(nameBlocks.begin(), nameBlocks.end()); // Sorts the name blocks alphabetically
possibleNames.resize(nameBlocks.size());
for (unsigned i = 0; i < nameBlocks.size(); ++i) {
if (nickNames.count(nameBlocks.at(i)) != 0) { // Stores the possible nicknames for a name
hasNickName = true;
cerr << "Has a nickname" << endl;
possibleNames.at(i) = nickNames.find(nameBlocks.at(i))->second;
}
if (nameBlocks.at(i).size() == 1) { // Stores which names are abbreviated in vector of bools
abbreviated.push_back(true);
}
else {
abbreviated.push_back(false);
}
}
} | 27.330579 | 159 | 0.624433 | [
"vector"
] |
02508916339cc12e8954a3bf40b932240f8c3624 | 4,368 | hh | C++ | extern/typed-geometry/src/typed-geometry/functions/matrix/rotation.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/functions/matrix/rotation.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/functions/matrix/rotation.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <typed-geometry/feature/assert.hh>
#include <typed-geometry/types/angle.hh>
#include <typed-geometry/types/dir.hh>
#include <typed-geometry/types/mat.hh>
#include <typed-geometry/detail/operators/ops_mat.hh>
#include <typed-geometry/functions/vector/normalize.hh>
#include "translation.hh"
namespace tg
{
template <class T>
[[nodiscard]] constexpr mat<4, 4, T> rotation_around(dir<3, T> const& axis, angle_t<T> angle)
{
auto ca = cos(angle);
auto sa = sin(angle);
auto one_minus_ca = T(1) - ca;
auto ux = axis.x;
auto uy = axis.y;
auto uz = axis.z;
// see https://en.wikipedia.org/wiki/Rotation_matrix
auto m = mat<4, 4, T>::identity;
m[0][0] = ca + ux * ux * one_minus_ca;
m[1][1] = ca + uy * uy * one_minus_ca;
m[2][2] = ca + uz * uz * one_minus_ca;
m[0][1] = uy * ux * one_minus_ca + uz * sa;
m[0][2] = uz * ux * one_minus_ca - uy * sa;
m[1][0] = ux * uy * one_minus_ca - uz * sa;
m[1][2] = uz * uy * one_minus_ca + ux * sa;
m[2][0] = ux * uz * one_minus_ca + uy * sa;
m[2][1] = uy * uz * one_minus_ca - ux * sa;
return m;
}
template <class T>
[[nodiscard]] constexpr mat<4, 4, T> rotation_around(angle_t<T> angle, dir<3, T> const& axis)
{
return rotation_around(axis, angle);
}
template <class T>
[[nodiscard]] constexpr mat<4, 4, T> rotation_x(angle_t<T> a)
{
auto ca = cos(a);
auto sa = sin(a);
auto m = mat<4, 4, T>::identity;
m[1][1] = ca;
m[2][1] = -sa;
m[1][2] = sa;
m[2][2] = ca;
return m;
}
template <class T>
[[nodiscard]] constexpr mat<4, 4, T> rotation_y(angle_t<T> a)
{
auto ca = cos(a);
auto sa = sin(a);
auto m = mat<4, 4, T>::identity;
m[0][0] = ca;
m[2][0] = sa;
m[0][2] = -sa;
m[2][2] = ca;
return m;
}
template <class T>
[[nodiscard]] constexpr mat<4, 4, T> rotation_z(angle_t<T> a)
{
auto ca = cos(a);
auto sa = sin(a);
auto m = mat<4, 4, T>::identity;
m[0][0] = ca;
m[1][0] = -sa;
m[0][1] = sa;
m[1][1] = ca;
return m;
}
// TODO: more performant with no matrix mul
template <class T>
[[nodiscard]] constexpr vec<3, T> rotate_x(vec<3, T> const& v, angle_t<T> a)
{
return rotation_x(a) * v;
}
template <class T>
[[nodiscard]] constexpr dir<3, T> rotate_x(dir<3, T> const& v, angle_t<T> a)
{
return dir<3, T>(rotation_x(a) * v);
}
template <class T>
[[nodiscard]] constexpr pos<3, T> rotate_x(pos<3, T> const& v, angle_t<T> a)
{
return rotation_x(a) * v;
}
template <class T>
[[nodiscard]] constexpr vec<3, T> rotate_y(vec<3, T> const& v, angle_t<T> a)
{
return rotation_y(a) * v;
}
template <class T>
[[nodiscard]] constexpr dir<3, T> rotate_y(dir<3, T> const& v, angle_t<T> a)
{
return dir<3, T>(rotation_y(a) * v);
}
template <class T>
[[nodiscard]] constexpr pos<3, T> rotate_y(pos<3, T> const& v, angle_t<T> a)
{
return rotation_y(a) * v;
}
template <class T>
[[nodiscard]] constexpr vec<3, T> rotate_z(vec<3, T> const& v, angle_t<T> a)
{
return rotation_z(a) * v;
}
template <class T>
[[nodiscard]] constexpr dir<3, T> rotate_z(dir<3, T> const& v, angle_t<T> a)
{
return dir<3, T>(rotation_z(a) * v);
}
template <class T>
[[nodiscard]] constexpr pos<3, T> rotate_z(pos<3, T> const& v, angle_t<T> a)
{
return rotation_z(a) * v;
}
template <class ScalarT>
[[nodiscard]] constexpr mat<3, 3, ScalarT> rotation_around(pos<2, ScalarT> p, angle_t<ScalarT> a)
{
auto origin_to_p = p - pos<2, ScalarT>::zero;
auto ca = cos(a);
auto sa = sin(a);
auto r = mat<3, 3, ScalarT>::identity;
r[0][0] = ca;
r[1][0] = -sa;
r[0][1] = sa;
r[1][1] = ca;
return translation(origin_to_p) * r * translation(-origin_to_p);
}
template <class ScalarT>
[[nodiscard]] constexpr vec<2, ScalarT> rotate(vec<2, ScalarT> v, angle_t<ScalarT> a)
{
auto [sin, cos] = tg::sin_cos(a);
return {cos * v.x - sin * v.y, sin * v.x + cos * v.y};
}
template <class ScalarT>
[[nodiscard]] constexpr dir<2, ScalarT> rotate(dir<2, ScalarT> v, angle_t<ScalarT> a)
{
auto [sin, cos] = tg::sin_cos(a);
return {cos * v.x - sin * v.y, sin * v.x + cos * v.y};
}
template <class ScalarT>
[[nodiscard]] constexpr pos<2, ScalarT> rotate(pos<2, ScalarT> v, angle_t<ScalarT> a)
{
auto [sin, cos] = tg::sin_cos(a);
return {cos * v.x - sin * v.y, sin * v.x + cos * v.y};
}
} // namespace tg
| 25.103448 | 97 | 0.594093 | [
"geometry",
"vector"
] |
02508cbb5dee91ed2e0e86e81106ac9d7fe70cf9 | 4,228 | cpp | C++ | src/mongo/db/global_settings.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/global_settings.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/global_settings.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/global_settings.h"
#include "mongo/db/client.h"
#include "mongo/db/mongod_options_general_gen.h"
#include "mongo/db/service_context.h"
namespace mongo {
MongodGlobalParams mongodGlobalParams;
namespace {
repl::ReplSettings globalReplSettings;
const auto getClusterNetworkRestrictionManager =
ServiceContext::declareDecoration<std::unique_ptr<ClusterNetworkRestrictionManager>>();
Mutex mtxSetAllowListedCluster = MONGO_MAKE_LATCH("AllowListedClusterNetworkSetting::mutex");
} // namespace
void setGlobalReplSettings(const repl::ReplSettings& settings) {
globalReplSettings = settings;
}
const repl::ReplSettings& getGlobalReplSettings() {
return globalReplSettings;
}
void ClusterNetworkRestrictionManager::set(
ServiceContext* service, std::unique_ptr<ClusterNetworkRestrictionManager> manager) {
getClusterNetworkRestrictionManager(service) = std::move(manager);
}
void AllowListedClusterNetworkSetting::append(OperationContext*,
BSONObjBuilder& b,
const std::string& name) {
auto allowlistedClusterNetwork =
std::atomic_load(&mongodGlobalParams.allowlistedClusterNetwork); // NOLINT
if (allowlistedClusterNetwork) {
BSONArrayBuilder bb(b.subarrayStart(name));
for (const auto& acn : *allowlistedClusterNetwork) {
bb << acn;
}
bb.doneFast();
} else {
b << name << BSONNULL;
}
}
Status AllowListedClusterNetworkSetting::set(const mongo::BSONElement& e) {
std::shared_ptr<std::vector<std::string>> allowlistedClusterNetwork;
if (e.isNull()) {
// noop
} else if (e.type() == mongo::Array) {
allowlistedClusterNetwork = std::make_shared<std::vector<std::string>>();
for (const auto& sub : e.Array()) {
if (sub.type() != mongo::String) {
return {ErrorCodes::BadValue, "Expected array of strings"};
}
allowlistedClusterNetwork->push_back(sub.str());
}
} else {
return {ErrorCodes::BadValue, "Expected array or null"};
}
const auto service = Client::getCurrent()->getServiceContext();
const auto updater = getClusterNetworkRestrictionManager(service).get();
if (updater) {
stdx::lock_guard<Mutex> guard(mtxSetAllowListedCluster);
mongodGlobalParams.allowlistedClusterNetwork = allowlistedClusterNetwork;
updater->updateClusterNetworkRestrictions();
}
return Status::OK();
}
Status AllowListedClusterNetworkSetting::setFromString(const std::string& s) {
return {ErrorCodes::InternalError, "Cannot invoke this method"};
}
} // namespace mongo
| 38.09009 | 93 | 0.697729 | [
"vector"
] |
025cca3aa119444a7a7f753ebcd0c89f3d9b49a0 | 1,595 | cpp | C++ | src/linad99/fvar_dif.cpp | wStockhausen/admb | 876ec704ae974d0ed3bcc329f243dbc401ad0e6d | [
"BSD-3-Clause"
] | 79 | 2015-01-16T14:14:22.000Z | 2022-01-24T06:28:15.000Z | src/linad99/fvar_dif.cpp | wStockhausen/admb | 876ec704ae974d0ed3bcc329f243dbc401ad0e6d | [
"BSD-3-Clause"
] | 172 | 2015-01-21T01:53:57.000Z | 2022-03-29T19:57:31.000Z | src/linad99/fvar_dif.cpp | wStockhausen/admb | 876ec704ae974d0ed3bcc329f243dbc401ad0e6d | [
"BSD-3-Clause"
] | 22 | 2015-01-15T18:11:54.000Z | 2022-01-11T21:47:51.000Z | /*
Author: David Fournier
Copyright (c) 2008-2012 Regents of the University of California
*/
#include "fvar.hpp"
void DF_first_diference(void);
/**
Returns a dvector containing the differences of an x(i) and x(i + 1) for i = 1 to x.indexmax() - 1.
\param x input.
*/
dvar_vector first_difference(const dvar_vector& x)
{
if (x.size() <= 1)
{
cerr << "Error -- vector size too small"
" in first_difference(const dvar_vector&)" << endl;
ad_exit(1);
}
RETURN_ARRAYS_INCREMENT();
int mmin=x.indexmin();
int mmax=x.indexmax()-1;
dvar_vector tmp(mmin,mmax);
for (int i=mmin; i<=mmax; i++)
{
tmp.elem_value(i)=x.elem_value(i+1)-x.elem_value(i);
}
save_identifier_string("CE4");
x.save_dvar_vector_position();
tmp.save_dvar_vector_position();
save_identifier_string("CE1");
gradient_structure::GRAD_STACK1->
set_gradient_stack(DF_first_diference);
RETURN_ARRAYS_DECREMENT();
return(tmp);
}
/**
* Description not yet available.
* \param
*/
void DF_first_diference(void)
{
verify_identifier_string("CE1");
dvar_vector_position tmp_pos=restore_dvar_vector_position();
dvar_vector_position x_pos=restore_dvar_vector_position();
verify_identifier_string("CE4");
dvector dftmp=restore_dvar_vector_derivatives(tmp_pos);
dvector dfx(x_pos.indexmin(),x_pos.indexmax());
dfx.initialize();
for (int i=dfx.indexmax()-1; i>=dfx.indexmin(); i--)
{
// tmp.elem_value(i)=x.elem_value(i+1)-x.elem_value(i);
dfx.elem(i+1)+=dftmp.elem(i);
dfx.elem(i)-=dftmp.elem(i);
}
dfx.save_dvector_derivatives(x_pos);
}
| 25.31746 | 100 | 0.694671 | [
"vector"
] |
02624a708e3cea3e5ff7e12b2383bcc3c34a4f6d | 4,860 | cc | C++ | mindspore/lite/src/expression/ops/dense.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/lite/src/expression/ops/dense.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/expression/ops/dense.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2022 Huawei Technologies Co., Ltd
*
* 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 "src/expression/ops/dense.h"
#include <memory>
#include "include/api/cfg.h"
#include "src/expression/ops/biasadd.h"
#include "src/expression/ops/depend.h"
#include "src/expression/ops.h"
#include "nnacl/matmul_parameter.h"
#include "src/expression/import.h"
#include "inner/model_generated.h"
#include "src/cxx_api/expression/node_impl.h"
namespace mindspore {
namespace lite {
DenseM::DenseM(const DenseConfig &cfg) : Node() {
auto op_param = calloc(1, sizeof(MatMulParameter));
if (op_param == nullptr) {
MS_LOG(ERROR) << " cannot allocate MatMulParameter";
return;
}
set_name(UniqueName("Dense"));
SetOpParam(op_param);
expr()->SetSize(C2NUM);
set_primitive(schema::PrimitiveType_MatMulFusion);
auto param = reinterpret_cast<MatMulParameter *>(opParam_.get());
param->row_ = cfg.out_channels_;
param->col_ = cfg.in_channels_;
param->a_transpose_ = false;
param->b_transpose_ = true;
std::vector<int> dims = {param->row_, param->col_};
auto w = Node::CreateWeights(dims, kNumberTypeFloat32, KHWC, Param::Mode::NORMAL, "weights");
expr()->set_params(C1NUM, w);
if (cfg.has_bias_) {
wbias_ = CreateWeights({cfg.out_channels_}, kNumberTypeFloat32, KHWC, Param::Mode::ZEROS, "bias_weights");
bias_ = new (std::nothrow) BiasAddM(KHWC);
if (bias_ == nullptr) {
MS_LOG(ERROR) << "Cannot allocate bias";
return;
}
bias_->update_name(name());
AddLearn(wbias_->node());
PushOp(bias_);
}
SetLearn();
}
std::vector<EXPR *> DenseM::construct(const std::vector<EXPR *> &inputs) {
auto x = Node::construct(inputs);
if (bias_ != nullptr) {
x = (*bias_)({x.front(), wbias_});
}
return x;
}
std::vector<EXPR *> DenseM::Grad(EXPR *yt) {
auto src_param = reinterpret_cast<MatMulParameter *>(opParam_.get());
bool ta = src_param->a_transpose_;
bool tb = src_param->b_transpose_;
// dx grad op
auto dxGrad = new (std::nothrow) DenseM();
if (dxGrad == nullptr) {
MS_LOG(ERROR) << "Cannot allocate dxGrad ";
return {};
}
PushOp(dxGrad);
dxGrad->CloneOpParam<MatMulParameter>(opParam_);
dxGrad->set_primitive(schema::PrimitiveType_MatMulFusion);
auto dxGradParam = reinterpret_cast<MatMulParameter *>(dxGrad->OpParam());
dxGradParam->a_transpose_ = (ta && tb);
dxGradParam->b_transpose_ = (ta || !tb);
dxGrad->set_name(name() + kGradName + "/dxGrad");
EXPR *dx = nullptr;
if (ta) {
dx = (*dxGrad)({input(1), yt}).front();
} else {
dx = (*dxGrad)({yt, input(1)}).front();
}
// Control execution flow
auto depend = NN::Depend();
if (depend == nullptr) {
MS_LOG(ERROR) << "Cannot allocate depend ";
return {};
}
PushOp(depend);
auto de = (*depend)({dxGrad->expr()}).front();
// dw grad op
auto dwGrad = new (std::nothrow) DenseM();
if (dwGrad == nullptr) {
MS_LOG(ERROR) << "Cannot allocate dwGrad ";
return {};
}
PushOp(dwGrad);
dwGrad->CloneOpParam<MatMulParameter>(opParam_);
dwGrad->set_primitive(schema::PrimitiveType_MatMulFusion);
auto dwGradParam = reinterpret_cast<MatMulParameter *>(dwGrad->OpParam());
dwGradParam->a_transpose_ = (!ta || tb);
dwGradParam->b_transpose_ = ta && tb;
dwGrad->set_name(name() + kGradName + "/dwGrad");
EXPR *dw = nullptr;
if (tb) {
dw = (*dwGrad)({yt, input(0), de}).front();
} else {
dw = (*dwGrad)({input(0), yt, de}).front();
}
return {dx, dw};
}
int DenseM::UnPopulate(const std::unique_ptr<schema::CNodeT> &cnode) {
auto dense_param = reinterpret_cast<const MatMulParameter *>(OpParam());
auto prim = new (std::nothrow) schema::MatMulFusionT;
if (prim == nullptr) {
MS_LOG(ERROR) << "Cannot allocate primitive";
return RET_ERROR;
}
prim->transpose_a = dense_param->a_transpose_;
prim->transpose_b = dense_param->b_transpose_;
cnode->primitive->value.value = prim;
return RET_OK;
}
void DenseM::SetLearn() { AddLearn(input(C1NUM)->node()); }
static ImportReg reg(schema::PrimitiveType_MatMulFusion, ReturnNode<DenseM>);
namespace NN {
Node *Dense(const DenseConfig &cfg) {
auto l = new (std::nothrow) DenseM(cfg);
if (l == nullptr) {
MS_LOG(ERROR) << "Cannot allocate Dense object";
}
return l;
}
} // namespace NN
} // namespace lite
} // namespace mindspore
| 31.973684 | 110 | 0.676749 | [
"object",
"vector"
] |
02627b7b9691c5159a0c282518d6c9b9134d52c3 | 1,955 | cpp | C++ | ModelGenerator/src/pixel_conversion.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | ModelGenerator/src/pixel_conversion.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | ModelGenerator/src/pixel_conversion.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021 Adam Lafontaine
*/
#include "pixel_conversion.hpp"
#include <cassert>
#include <random>
constexpr auto BITS32_MAX = UINT32_MAX;
constexpr double BITS8_MAX = 255;
constexpr auto MODEL_VALUE_MIN = 0.0;
constexpr auto MODEL_VALUE_MAX = BITS32_MAX;
using shade_t = u8;
constexpr shade_t PIXEL_ACTIVE = 255;
constexpr shade_t PIXEL_INACTIVE = 254;
namespace model_generator
{
bool is_relevant(double model_val)
{
return model_val >= MODEL_VALUE_MIN && model_val <= MODEL_VALUE_MAX;
}
double data_pixel_to_model_value(data_pixel_t const& data_pix)
{
return static_cast<double>(data_pix.value);
}
model_pixel_t model_value_to_model_pixel(double model_val, bool is_active)
{
assert(is_relevant(model_val)); // only valid values can be converted to a pixel
shade_t min = 0;
shade_t max = 255;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(min, max);
// red channel doesn't matter
const shade_t r = dist(gen);
// green channel doesn't matter
const shade_t g = dist(gen);
// only the blue channel is used to store data
// 32 bit number converted to 8 bit, loss of precision
const auto ratio = model_val / MODEL_VALUE_MAX;
const shade_t b = static_cast<shade_t>(ratio * max);
// use alpha channel to flag if pixel is used in the model
const shade_t a = is_active ? PIXEL_ACTIVE : PIXEL_INACTIVE;
return img::to_pixel(r, g, b, a);
}
double model_pixel_to_model_value(model_pixel_t const& model_pix)
{
const auto rgba = model_pix;
// if alpha channel has been flagged as inactive,
// return value makes is_relevant() == false
if (rgba.alpha != PIXEL_ACTIVE)
return MODEL_VALUE_MIN - 1;
// only the blue channel is used to store a value
// the red and green channels are random values used to make the model image look more interesting
const auto ratio = rgba.blue / BITS8_MAX;
return ratio * MODEL_VALUE_MAX;
}
} | 23.841463 | 100 | 0.732481 | [
"model"
] |
026a6eaa3aadc7c41db1f3b4e70c917e4fa70f8e | 33,470 | cpp | C++ | lammps-master/src/USER-NETCDF/dump_netcdf_mpiio.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-NETCDF/dump_netcdf_mpiio.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-NETCDF/dump_netcdf_mpiio.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"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: Lars Pastewka (University of Freiburg)
------------------------------------------------------------------------- */
#if defined(LMP_HAS_PNETCDF)
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <pnetcdf.h>
#include "dump_netcdf_mpiio.h"
#include "atom.h"
#include "comm.h"
#include "compute.h"
#include "domain.h"
#include "error.h"
#include "fix.h"
#include "group.h"
#include "input.h"
#include "math_const.h"
#include "memory.h"
#include "modify.h"
#include "update.h"
#include "universe.h"
#include "variable.h"
#include "force.h"
#include "output.h"
#include "thermo.h"
using namespace LAMMPS_NS;
using namespace MathConst;
enum{THERMO_INT,THERMO_FLOAT,THERMO_BIGINT}; // same as in thermo.cpp
enum{DUMP_INT,DUMP_DOUBLE,DUMP_STRING,DUMP_BIGINT}; // same as in DumpCFG
const char NC_FRAME_STR[] = "frame";
const char NC_SPATIAL_STR[] = "spatial";
const char NC_VOIGT_STR[] = "Voigt";
const char NC_ATOM_STR[] = "atom";
const char NC_CELL_SPATIAL_STR[] = "cell_spatial";
const char NC_CELL_ANGULAR_STR[] = "cell_angular";
const char NC_LABEL_STR[] = "label";
const char NC_TIME_STR[] = "time";
const char NC_CELL_ORIGIN_STR[] = "cell_origin";
const char NC_CELL_LENGTHS_STR[] = "cell_lengths";
const char NC_CELL_ANGLES_STR[] = "cell_angles";
const char NC_UNITS_STR[] = "units";
const char NC_SCALE_FACTOR_STR[] = "scale_factor";
const int THIS_IS_A_FIX = -1;
const int THIS_IS_A_COMPUTE = -2;
const int THIS_IS_A_VARIABLE = -3;
const int THIS_IS_A_BIGINT = -4;
/* ---------------------------------------------------------------------- */
#define NCERR(x) ncerr(x, NULL, __LINE__)
#define NCERRX(x, descr) ncerr(x, descr, __LINE__)
#if !defined(NC_64BIT_DATA)
#define NC_64BIT_DATA NC_64BIT_OFFSET
#endif
/* ---------------------------------------------------------------------- */
DumpNetCDFMPIIO::DumpNetCDFMPIIO(LAMMPS *lmp, int narg, char **arg) :
DumpCustom(lmp, narg, arg)
{
// arrays for data rearrangement
sort_flag = 1;
sortcol = 0;
binary = 1;
flush_flag = 0;
if (multiproc)
error->all(FLERR,"Multi-processor writes are not supported.");
if (append_flag && multifile)
error->all(FLERR,"Cannot append when writing to multiple files.");
perat = new nc_perat_t[nfield];
for (int i = 0; i < nfield; i++) {
perat[i].dims = 0;
}
n_perat = 0;
for (int iarg = 5; iarg < narg; iarg++) {
int i = iarg-5;
int idim = 0;
int ndims = 1;
char mangled[1024];
strcpy(mangled, arg[iarg]);
// name mangling
// in the AMBER specification
if (!strcmp(mangled, "x") || !strcmp(mangled, "y") ||
!strcmp(mangled, "z")) {
idim = mangled[0] - 'x';
ndims = 3;
strcpy(mangled, "coordinates");
}
else if (!strcmp(mangled, "vx") || !strcmp(mangled, "vy") ||
!strcmp(mangled, "vz")) {
idim = mangled[1] - 'x';
ndims = 3;
strcpy(mangled, "velocities");
}
else if (!strcmp(mangled, "xs") || !strcmp(mangled, "ys") ||
!strcmp(mangled, "zs")) {
idim = mangled[0] - 'x';
ndims = 3;
strcpy(mangled, "scaled_coordinates");
}
else if (!strcmp(mangled, "xu") || !strcmp(mangled, "yu") ||
!strcmp(mangled, "zu")) {
idim = mangled[0] - 'x';
ndims = 3;
strcpy(mangled, "unwrapped_coordinates");
}
else if (!strcmp(mangled, "fx") || !strcmp(mangled, "fy") ||
!strcmp(mangled, "fz")) {
idim = mangled[1] - 'x';
ndims = 3;
strcpy(mangled, "forces");
}
else if (!strcmp(mangled, "mux") || !strcmp(mangled, "muy") ||
!strcmp(mangled, "muz")) {
idim = mangled[2] - 'x';
ndims = 3;
strcpy(mangled, "mu");
}
else if (!strncmp(mangled, "c_", 2)) {
char *ptr = strchr(mangled, '[');
if (ptr) {
if (mangled[strlen(mangled)-1] != ']')
error->all(FLERR,"Missing ']' in dump command");
*ptr = '\0';
idim = ptr[1] - '1';
ndims = THIS_IS_A_COMPUTE;
}
}
else if (!strncmp(mangled, "f_", 2)) {
char *ptr = strchr(mangled, '[');
if (ptr) {
if (mangled[strlen(mangled)-1] != ']')
error->all(FLERR,"Missing ']' in dump command");
*ptr = '\0';
idim = ptr[1] - '1';
ndims = THIS_IS_A_FIX;
}
}
// find mangled name
int inc = -1;
for (int j = 0; j < n_perat && inc < 0; j++) {
if (!strcmp(perat[j].name, mangled)) {
inc = j;
}
}
if (inc < 0) {
// this has not yet been defined
inc = n_perat;
perat[inc].dims = ndims;
if (ndims < 0) ndims = DUMP_NC_MPIIO_MAX_DIMS;
for (int j = 0; j < DUMP_NC_MPIIO_MAX_DIMS; j++) {
perat[inc].field[j] = -1;
}
strcpy(perat[inc].name, mangled);
n_perat++;
}
perat[inc].field[idim] = i;
}
n_buffer = 0;
int_buffer = NULL;
double_buffer = NULL;
double_precision = false;
thermo = false;
thermovar = NULL;
framei = 0;
}
/* ---------------------------------------------------------------------- */
DumpNetCDFMPIIO::~DumpNetCDFMPIIO()
{
closefile();
delete [] perat;
if (thermovar) delete [] thermovar;
if (int_buffer) memory->sfree(int_buffer);
if (double_buffer) memory->sfree(double_buffer);
}
/* ---------------------------------------------------------------------- */
void DumpNetCDFMPIIO::openfile()
{
char *filecurrent = filename;
if (multifile && !singlefile_opened) {
char *filestar = filecurrent;
filecurrent = new char[strlen(filestar) + 16];
char *ptr = strchr(filestar,'*');
*ptr = '\0';
if (padflag == 0)
sprintf(filecurrent,"%s" BIGINT_FORMAT "%s",
filestar,update->ntimestep,ptr+1);
else {
char bif[8],pad[16];
strcpy(bif,BIGINT_FORMAT);
sprintf(pad,"%%s%%0%d%s%%s",padflag,&bif[1]);
sprintf(filecurrent,pad,filestar,update->ntimestep,ptr+1);
}
*ptr = '*';
}
if (thermo && !singlefile_opened) {
if (thermovar) delete [] thermovar;
thermovar = new int[output->thermo->nfield];
}
// now the computes and fixes have been initialized, so we can query
// for the size of vector quantities
for (int i = 0; i < n_perat; i++) {
if (perat[i].dims == THIS_IS_A_COMPUTE) {
int j = -1;
for (int k = 0; k < DUMP_NC_MPIIO_MAX_DIMS; k++) {
if (perat[i].field[k] >= 0) {
j = field2index[perat[i].field[0]];
}
}
if (j < 0)
error->all(FLERR,"Internal error.");
if (!compute[j]->peratom_flag)
error->all(FLERR,"compute does not provide per atom data");
perat[i].dims = compute[j]->size_peratom_cols;
if (perat[i].dims > DUMP_NC_MPIIO_MAX_DIMS)
error->all(FLERR,"perat[i].dims > DUMP_NC_MPIIO_MAX_DIMS");
}
else if (perat[i].dims == THIS_IS_A_FIX) {
int j = -1;
for (int k = 0; k < DUMP_NC_MPIIO_MAX_DIMS; k++) {
if (perat[i].field[k] >= 0) {
j = field2index[perat[i].field[0]];
}
}
if (j < 0)
error->all(FLERR,"Internal error.");
if (!fix[j]->peratom_flag)
error->all(FLERR,"fix does not provide per atom data");
perat[i].dims = fix[j]->size_peratom_cols;
if (perat[i].dims > DUMP_NC_MPIIO_MAX_DIMS)
error->all(FLERR,"perat[i].dims > DUMP_NC_MPIIO_MAX_DIMS");
}
}
// get total number of atoms
ntotalgr = group->count(igroup);
for (int i = 0; i < DUMP_NC_MPIIO_MAX_DIMS; i++) {
vector_dim[i] = -1;
}
if (append_flag && !multifile && access(filecurrent, F_OK) != -1) {
// Fixme! Perform checks if dimensions and variables conform with
// data structure standard.
MPI_Offset index[NC_MAX_VAR_DIMS], count[NC_MAX_VAR_DIMS];
double d[1];
if (singlefile_opened) return;
singlefile_opened = 1;
NCERRX( ncmpi_open(MPI_COMM_WORLD, filecurrent, NC_WRITE, MPI_INFO_NULL,
&ncid), filecurrent );
// dimensions
NCERRX( ncmpi_inq_dimid(ncid, NC_FRAME_STR, &frame_dim), NC_FRAME_STR );
NCERRX( ncmpi_inq_dimid(ncid, NC_ATOM_STR, &atom_dim), NC_ATOM_STR );
NCERRX( ncmpi_inq_dimid(ncid, NC_CELL_SPATIAL_STR, &cell_spatial_dim),
NC_CELL_SPATIAL_STR );
NCERRX( ncmpi_inq_dimid(ncid, NC_CELL_ANGULAR_STR, &cell_angular_dim),
NC_CELL_ANGULAR_STR );
NCERRX( ncmpi_inq_dimid(ncid, NC_LABEL_STR, &label_dim), NC_LABEL_STR );
for (int i = 0; i < n_perat; i++) {
int dims = perat[i].dims;
if (vector_dim[dims] < 0) {
char dimstr[1024];
if (dims == 3) {
strcpy(dimstr, NC_SPATIAL_STR);
}
else if (dims == 6) {
strcpy(dimstr, NC_VOIGT_STR);
}
else {
sprintf(dimstr, "vec%i", dims);
}
if (dims != 1) {
NCERRX( ncmpi_inq_dimid(ncid, dimstr, &vector_dim[dims]),
dimstr );
}
}
}
// default variables
NCERRX( ncmpi_inq_varid(ncid, NC_SPATIAL_STR, &spatial_var),
NC_SPATIAL_STR );
NCERRX( ncmpi_inq_varid(ncid, NC_CELL_SPATIAL_STR, &cell_spatial_var),
NC_CELL_SPATIAL_STR);
NCERRX( ncmpi_inq_varid(ncid, NC_CELL_ANGULAR_STR, &cell_angular_var),
NC_CELL_ANGULAR_STR);
NCERRX( ncmpi_inq_varid(ncid, NC_TIME_STR, &time_var), NC_TIME_STR );
NCERRX( ncmpi_inq_varid(ncid, NC_CELL_ORIGIN_STR, &cell_origin_var),
NC_CELL_ORIGIN_STR );
NCERRX( ncmpi_inq_varid(ncid, NC_CELL_LENGTHS_STR, &cell_lengths_var),
NC_CELL_LENGTHS_STR);
NCERRX( ncmpi_inq_varid(ncid, NC_CELL_ANGLES_STR, &cell_angles_var),
NC_CELL_ANGLES_STR);
// variables specified in the input file
for (int i = 0; i < n_perat; i++) {
NCERRX( ncmpi_inq_varid(ncid, perat[i].name, &perat[i].var),
perat[i].name );
}
// perframe variables
if (thermo) {
Thermo *th = output->thermo;
for (int i = 0; i < th->nfield; i++) {
NCERRX( ncmpi_inq_varid(ncid, th->keyword[i], &thermovar[i]),
th->keyword[i] );
}
}
MPI_Offset nframes;
NCERR( ncmpi_inq_dimlen(ncid, frame_dim, &nframes) );
// framei == -1 means append to file, == -2 means override last frame
// Note that in the input file this translates to 'yes', '-1', etc.
if (framei <= 0) framei = nframes+framei+1;
if (framei < 1) framei = 1;
} else {
if (framei != 0 && !multifile)
error->all(FLERR,"at keyword requires use of 'append yes'");
int dims[NC_MAX_VAR_DIMS];
MPI_Offset index[NC_MAX_VAR_DIMS], count[NC_MAX_VAR_DIMS];
double d[1];
if (singlefile_opened) return;
singlefile_opened = 1;
NCERRX( ncmpi_create(MPI_COMM_WORLD, filecurrent, NC_64BIT_DATA,
MPI_INFO_NULL, &ncid), filecurrent );
// dimensions
NCERRX( ncmpi_def_dim(ncid, NC_FRAME_STR, NC_UNLIMITED, &frame_dim),
NC_FRAME_STR );
NCERRX( ncmpi_def_dim(ncid, NC_ATOM_STR, ntotalgr, &atom_dim),
NC_ATOM_STR );
NCERRX( ncmpi_def_dim(ncid, NC_CELL_SPATIAL_STR, 3, &cell_spatial_dim),
NC_CELL_SPATIAL_STR );
NCERRX( ncmpi_def_dim(ncid, NC_CELL_ANGULAR_STR, 3, &cell_angular_dim),
NC_CELL_ANGULAR_STR );
NCERRX( ncmpi_def_dim(ncid, NC_LABEL_STR, 10, &label_dim),
NC_LABEL_STR );
for (int i = 0; i < n_perat; i++) {
int dims = perat[i].dims;
if (vector_dim[dims] < 0) {
char dimstr[1024];
if (dims == 3) {
strcpy(dimstr, NC_SPATIAL_STR);
}
else if (dims == 6) {
strcpy(dimstr, NC_VOIGT_STR);
}
else {
sprintf(dimstr, "vec%i", dims);
}
if (dims != 1) {
NCERRX( ncmpi_def_dim(ncid, dimstr, dims, &vector_dim[dims]),
dimstr );
}
}
}
// default variables
dims[0] = vector_dim[3];
NCERRX( ncmpi_def_var(ncid, NC_SPATIAL_STR, NC_CHAR, 1, dims, &spatial_var),
NC_SPATIAL_STR );
NCERRX( ncmpi_def_var(ncid, NC_CELL_SPATIAL_STR, NC_CHAR, 1, dims,
&cell_spatial_var), NC_CELL_SPATIAL_STR );
dims[0] = vector_dim[3];
dims[1] = label_dim;
NCERRX( ncmpi_def_var(ncid, NC_CELL_ANGULAR_STR, NC_CHAR, 2, dims,
&cell_angular_var), NC_CELL_ANGULAR_STR );
dims[0] = frame_dim;
NCERRX( ncmpi_def_var(ncid, NC_TIME_STR, NC_DOUBLE, 1, dims, &time_var),
NC_TIME_STR);
dims[0] = frame_dim;
dims[1] = cell_spatial_dim;
NCERRX( ncmpi_def_var(ncid, NC_CELL_ORIGIN_STR, NC_DOUBLE, 2, dims,
&cell_origin_var), NC_CELL_ORIGIN_STR );
NCERRX( ncmpi_def_var(ncid, NC_CELL_LENGTHS_STR, NC_DOUBLE, 2, dims,
&cell_lengths_var), NC_CELL_LENGTHS_STR );
dims[0] = frame_dim;
dims[1] = cell_angular_dim;
NCERRX( ncmpi_def_var(ncid, NC_CELL_ANGLES_STR, NC_DOUBLE, 2, dims,
&cell_angles_var), NC_CELL_ANGLES_STR );
// variables specified in the input file
dims[0] = frame_dim;
dims[1] = atom_dim;
dims[2] = vector_dim[3];
for (int i = 0; i < n_perat; i++) {
nc_type xtype;
// Type mangling
if (vtype[perat[i].field[0]] == DUMP_INT) {
xtype = NC_INT;
} else if (vtype[perat[i].field[0]] == DUMP_BIGINT) {
xtype = NC_INT64;
} else {
if (double_precision)
xtype = NC_DOUBLE;
else
xtype = NC_FLOAT;
}
if (perat[i].dims == 1) {
NCERRX( ncmpi_def_var(ncid, perat[i].name, xtype, 2, dims,
&perat[i].var), perat[i].name );
}
else {
// this is a vector
dims[2] = vector_dim[perat[i].dims];
NCERRX( ncmpi_def_var(ncid, perat[i].name, xtype, 3, dims,
&perat[i].var), perat[i].name );
}
}
// perframe variables
if (thermo) {
Thermo *th = output->thermo;
for (int i = 0; i < th->nfield; i++) {
if (th->vtype[i] == THERMO_FLOAT) {
NCERRX( ncmpi_def_var(ncid, th->keyword[i], NC_DOUBLE, 1, dims,
&thermovar[i]), th->keyword[i] );
}
else if (th->vtype[i] == THERMO_INT) {
NCERRX( ncmpi_def_var(ncid, th->keyword[i], NC_INT, 1, dims,
&thermovar[i]), th->keyword[i] );
}
else if (th->vtype[i] == THERMO_BIGINT) {
#if defined(LAMMPS_SMALLBIG) || defined(LAMMPS_BIGBIG)
NCERRX( ncmpi_def_var(ncid, th->keyword[i], NC_INT64, 1, dims,
&thermovar[i]), th->keyword[i] );
#else
NCERRX( ncmpi_def_var(ncid, th->keyword[i], NC_LONG, 1, dims,
&thermovar[i]), th->keyword[i] );
#endif
}
}
}
// attributes
NCERR( ncmpi_put_att_text(ncid, NC_GLOBAL, "Conventions",
5, "AMBER") );
NCERR( ncmpi_put_att_text(ncid, NC_GLOBAL, "ConventionVersion",
3, "1.0") );
NCERR( ncmpi_put_att_text(ncid, NC_GLOBAL, "program",
6, "LAMMPS") );
NCERR( ncmpi_put_att_text(ncid, NC_GLOBAL, "programVersion",
strlen(universe->version), universe->version) );
// units
if (!strcmp(update->unit_style, "lj")) {
NCERR( ncmpi_put_att_text(ncid, time_var, NC_UNITS_STR,
2, "lj") );
NCERR( ncmpi_put_att_text(ncid, cell_origin_var, NC_UNITS_STR,
2, "lj") );
NCERR( ncmpi_put_att_text(ncid, cell_lengths_var, NC_UNITS_STR,
2, "lj") );
}
else if (!strcmp(update->unit_style, "real")) {
NCERR( ncmpi_put_att_text(ncid, time_var, NC_UNITS_STR,
11, "femtosecond") );
NCERR( ncmpi_put_att_text(ncid, cell_origin_var, NC_UNITS_STR,
8, "Angstrom") );
NCERR( ncmpi_put_att_text(ncid, cell_lengths_var, NC_UNITS_STR,
8, "Angstrom") );
}
else if (!strcmp(update->unit_style, "metal")) {
NCERR( ncmpi_put_att_text(ncid, time_var, NC_UNITS_STR,
10, "picosecond") );
NCERR( ncmpi_put_att_text(ncid, cell_origin_var, NC_UNITS_STR,
8, "Angstrom") );
NCERR( ncmpi_put_att_text(ncid, cell_lengths_var, NC_UNITS_STR,
8, "Angstrom") );
}
else if (!strcmp(update->unit_style, "si")) {
NCERR( ncmpi_put_att_text(ncid, time_var, NC_UNITS_STR,
6, "second") );
NCERR( ncmpi_put_att_text(ncid, cell_origin_var, NC_UNITS_STR,
5, "meter") );
NCERR( ncmpi_put_att_text(ncid, cell_lengths_var, NC_UNITS_STR,
5, "meter") );
}
else if (!strcmp(update->unit_style, "cgs")) {
NCERR( ncmpi_put_att_text(ncid, time_var, NC_UNITS_STR,
6, "second") );
NCERR( ncmpi_put_att_text(ncid, cell_origin_var, NC_UNITS_STR,
10, "centimeter") );
NCERR( ncmpi_put_att_text(ncid, cell_lengths_var, NC_UNITS_STR,
10, "centimeter") );
}
else if (!strcmp(update->unit_style, "electron")) {
NCERR( ncmpi_put_att_text(ncid, time_var, NC_UNITS_STR,
11, "femtosecond") );
NCERR( ncmpi_put_att_text(ncid, cell_origin_var, NC_UNITS_STR,
4, "Bohr") );
NCERR( ncmpi_put_att_text(ncid, cell_lengths_var, NC_UNITS_STR,
4, "Bohr") );
}
else {
char errstr[1024];
sprintf(errstr, "Unsupported unit style '%s'", update->unit_style);
error->all(FLERR,errstr);
}
NCERR( ncmpi_put_att_text(ncid, cell_angles_var, NC_UNITS_STR,
6, "degree") );
d[0] = update->dt;
NCERR( ncmpi_put_att_double(ncid, time_var, NC_SCALE_FACTOR_STR,
NC_DOUBLE, 1, d) );
d[0] = 1.0;
NCERR( ncmpi_put_att_double(ncid, cell_origin_var, NC_SCALE_FACTOR_STR,
NC_DOUBLE, 1, d) );
d[0] = 1.0;
NCERR( ncmpi_put_att_double(ncid, cell_lengths_var, NC_SCALE_FACTOR_STR,
NC_DOUBLE, 1, d) );
/*
* Finished with definition
*/
NCERR( ncmpi_enddef(ncid) );
/*
* Write label variables
*/
NCERR( ncmpi_begin_indep_data(ncid) );
if (filewriter) {
NCERR( ncmpi_put_var_text(ncid, spatial_var, "xyz") );
NCERR( ncmpi_put_var_text(ncid, cell_spatial_var, "abc") );
index[0] = 0;
index[1] = 0;
count[0] = 1;
count[1] = 5;
NCERR( ncmpi_put_vara_text(ncid, cell_angular_var, index, count,
"alpha") );
index[0] = 1;
count[1] = 4;
NCERR( ncmpi_put_vara_text(ncid, cell_angular_var, index, count,
"beta") );
index[0] = 2;
count[1] = 5;
NCERR( ncmpi_put_vara_text(ncid, cell_angular_var, index, count,
"gamma") );
}
NCERR( ncmpi_end_indep_data(ncid) );
append_flag = 1;
framei = 1;
}
}
/* ---------------------------------------------------------------------- */
void DumpNetCDFMPIIO::closefile()
{
if (singlefile_opened) {
NCERR( ncmpi_close(ncid) );
singlefile_opened = 0;
// write to next frame upon next open
if (multifile)
framei = 1;
else {
// append next time DumpNetCDFMPIIO::openfile is called
append_flag = 1;
framei++;
}
}
}
/* ---------------------------------------------------------------------- */
template <typename T>
int ncmpi_put_var1_bigint(int ncid, int varid, const MPI_Offset index[],
const T* tp)
{
return ncmpi_put_var1_int(ncid, varid, index, tp);
}
template <>
int ncmpi_put_var1_bigint<long>(int ncid, int varid, const MPI_Offset index[],
const long* tp)
{
return ncmpi_put_var1_long(ncid, varid, index, tp);
}
template <>
int ncmpi_put_var1_bigint<long long>(int ncid, int varid,
const MPI_Offset index[],
const long long* tp)
{
return ncmpi_put_var1_longlong(ncid, varid, index, tp);
}
template <typename T>
int ncmpi_put_vara_bigint_all(int ncid, int varid, const MPI_Offset start[],
const MPI_Offset count[], const T* tp)
{
return ncmpi_put_vara_int_all(ncid, varid, start, count, tp);
}
template <>
int ncmpi_put_vara_bigint_all<long>(int ncid, int varid,
const MPI_Offset start[],
const MPI_Offset count[], const long* tp)
{
return ncmpi_put_vara_long_all(ncid, varid, start, count, tp);
}
template <>
int ncmpi_put_vara_bigint_all<long long>(int ncid, int varid,
const MPI_Offset start[],
const MPI_Offset count[],
const long long* tp)
{
return ncmpi_put_vara_longlong_all(ncid, varid, start, count, tp);
}
template <typename T>
int ncmpi_put_vars_bigint_all(int ncid, int varid, const MPI_Offset start[],
const MPI_Offset count[],
const MPI_Offset stride[], const T* tp)
{
return ncmpi_put_vars_int_all(ncid, varid, start, count, stride, tp);
}
template <>
int ncmpi_put_vars_bigint_all<long>(int ncid, int varid,
const MPI_Offset start[],
const MPI_Offset count[],
const MPI_Offset stride[], const long* tp)
{
return ncmpi_put_vars_long_all(ncid, varid, start, count, stride, tp);
}
template <>
int ncmpi_put_vars_bigint_all<long long>(int ncid, int varid,
const MPI_Offset start[],
const MPI_Offset count[],
const MPI_Offset stride[],
const long long* tp)
{
return ncmpi_put_vars_longlong_all(ncid, varid, start, count, stride, tp);
}
void DumpNetCDFMPIIO::write()
{
// open file
openfile();
// need to write per-frame (global) properties here since they may come
// from computes. write_header below is only called from the writing
// processes, but modify->compute[j]->compute_* must be called from all
// processes.
MPI_Offset start[2];
start[0] = framei-1;
start[1] = 0;
NCERR( ncmpi_begin_indep_data(ncid) );
if (thermo) {
Thermo *th = output->thermo;
for (int i = 0; i < th->nfield; i++) {
th->call_vfunc(i);
if (filewriter) {
if (th->vtype[i] == THERMO_FLOAT) {
NCERRX( ncmpi_put_var1_double(ncid, thermovar[i], start,
&th->dvalue),
th->keyword[i] );
}
else if (th->vtype[i] == THERMO_INT) {
NCERRX( ncmpi_put_var1_int(ncid, thermovar[i], start, &th->ivalue),
th->keyword[i] );
}
else if (th->vtype[i] == THERMO_BIGINT) {
NCERRX( ncmpi_put_var1_bigint(ncid, thermovar[i], start, &th->bivalue),
th->keyword[i] );
}
}
}
}
// write timestep header
write_time_and_cell();
NCERR( ncmpi_end_indep_data(ncid) );
// nme = # of dump lines this proc contributes to dump
nme = count();
int *block_sizes = new int[comm->nprocs];
MPI_Allgather(&nme, 1, MPI_INT, block_sizes, 1, MPI_INT, MPI_COMM_WORLD);
blocki = 0;
for (int i = 0; i < comm->me; i++) blocki += block_sizes[i];
delete [] block_sizes;
// insure buf is sized for packing and communicating
// use nme to insure filewriter proc can receive info from others
// limit nme*size_one to int since used as arg in MPI calls
if (nme > maxbuf) {
if ((bigint) nme * size_one > MAXSMALLINT)
error->all(FLERR,"Too much per-proc info for dump");
maxbuf = nme;
memory->destroy(buf);
memory->create(buf,maxbuf*size_one,"dump:buf");
}
// pack my data into buf
pack(NULL);
// each process writes its data
write_data(nme, buf);
// close file. this ensures data is flushed and minimizes data corruption
closefile();
}
/* ---------------------------------------------------------------------- */
void DumpNetCDFMPIIO::write_time_and_cell()
{
MPI_Offset start[2];
start[0] = framei-1;
start[1] = 0;
MPI_Offset count[2];
double time, cell_origin[3], cell_lengths[3], cell_angles[3];
time = update->ntimestep;
if (domain->triclinic == 0) {
cell_origin[0] = domain->boxlo[0];
cell_origin[1] = domain->boxlo[1];
cell_origin[2] = domain->boxlo[2];
cell_lengths[0] = domain->xprd;
cell_lengths[1] = domain->yprd;
cell_lengths[2] = domain->zprd;
cell_angles[0] = 90;
cell_angles[1] = 90;
cell_angles[2] = 90;
}
else {
double cosalpha, cosbeta, cosgamma;
double *h = domain->h;
cell_origin[0] = domain->boxlo[0];
cell_origin[1] = domain->boxlo[1];
cell_origin[2] = domain->boxlo[2];
cell_lengths[0] = domain->xprd;
cell_lengths[1] = sqrt(h[1]*h[1]+h[5]*h[5]);
cell_lengths[2] = sqrt(h[2]*h[2]+h[3]*h[3]+h[4]*h[4]);
cosalpha = (h[5]*h[4]+h[1]*h[3])/
sqrt((h[1]*h[1]+h[5]*h[5])*(h[2]*h[2]+h[3]*h[3]+h[4]*h[4]));
cosbeta = h[4]/sqrt(h[2]*h[2]+h[3]*h[3]+h[4]*h[4]);
cosgamma = h[5]/sqrt(h[1]*h[1]+h[5]*h[5]);
cell_angles[0] = acos(cosalpha)*180.0/MY_PI;
cell_angles[1] = acos(cosbeta)*180.0/MY_PI;
cell_angles[2] = acos(cosgamma)*180.0/MY_PI;
}
// Recent AMBER conventions say that non-periodic boundaries should have
// 'cell_lengths' set to zero.
for (int dim = 0; dim < 3; dim++) {
if (!domain->periodicity[dim])
cell_lengths[dim] = 0.0;
}
count[0] = 1;
count[1] = 3;
if (filewriter) {
NCERR( ncmpi_put_var1_double(ncid, time_var, start, &time) );
NCERR( ncmpi_put_vara_double(ncid, cell_origin_var, start, count,
cell_origin) );
NCERR( ncmpi_put_vara_double(ncid, cell_lengths_var, start, count,
cell_lengths) );
NCERR( ncmpi_put_vara_double(ncid, cell_angles_var, start, count,
cell_angles) );
}
}
/* ----------------------------------------------------------------------
write data lines to file in a block-by-block style
write head of block (mass & element name) only if has atoms of the type
------------------------------------------------------------------------- */
void DumpNetCDFMPIIO::write_data(int n, double *mybuf)
{
MPI_Offset start[NC_MAX_VAR_DIMS], count[NC_MAX_VAR_DIMS];
MPI_Offset stride[NC_MAX_VAR_DIMS];
if (!int_buffer) {
n_buffer = std::max(1, n);
int_buffer = (bigint *)
memory->smalloc(n_buffer*sizeof(bigint),"dump::int_buffer");
double_buffer = (double *)
memory->smalloc(n_buffer*sizeof(double),"dump::double_buffer");
}
if (n > n_buffer) {
n_buffer = std::max(1, n);
int_buffer = (bigint *)
memory->srealloc(int_buffer, n_buffer*sizeof(bigint),"dump::int_buffer");
double_buffer = (double *)
memory->srealloc(double_buffer, n_buffer*sizeof(double),
"dump::double_buffer");
}
start[0] = framei-1;
start[1] = blocki;
start[2] = 0;
if (n == 0) {
/* If there is no data, we need to make sure the start values don't exceed
dimension bounds. Just set them to zero. */
start[1] = 0;
}
count[0] = 1;
count[1] = n;
count[2] = 1;
stride[0] = 1;
stride[1] = 1;
stride[2] = 3;
for (int i = 0; i < n_perat; i++) {
int iaux = perat[i].field[0];
if (iaux < 0 || iaux >= size_one) {
char errmsg[1024];
sprintf(errmsg, "Internal error: name = %s, iaux = %i, "
"size_one = %i", perat[i].name, iaux, size_one);
error->one(FLERR,errmsg);
}
if (vtype[iaux] == DUMP_INT || vtype[iaux] == DUMP_BIGINT) {
// integers
if (perat[i].dims > 1) {
for (int idim = 0; idim < perat[i].dims; idim++) {
iaux = perat[i].field[idim];
if (iaux >= 0) {
if (iaux >= size_one) {
char errmsg[1024];
sprintf(errmsg, "Internal error: name = %s, iaux = %i, "
"size_one = %i", perat[i].name, iaux, size_one);
error->one(FLERR,errmsg);
}
if (vtype[iaux] == DUMP_INT) {
for (int j = 0; j < n; j++, iaux+=size_one) {
int_buffer[j] = static_cast<int>(mybuf[iaux]);
}
}
else { // DUMP_BIGINT
for (int j = 0; j < n; j++, iaux+=size_one) {
int_buffer[j] = static_cast<bigint>(mybuf[iaux]);
}
}
start[2] = idim;
NCERRX( ncmpi_put_vars_bigint_all(ncid, perat[i].var, start, count,
stride, int_buffer),
perat[i].name );
}
}
}
else {
for (int j = 0; j < n; j++, iaux+=size_one) {
int_buffer[j] = mybuf[iaux];
}
NCERRX( ncmpi_put_vara_bigint_all(ncid, perat[i].var, start, count,
int_buffer), perat[i].name );
}
}
else {
// doubles
if (perat[i].dims > 1) {
for (int idim = 0; idim < perat[i].dims; idim++) {
iaux = perat[i].field[idim];
if (iaux >= 0) {
if (iaux >= size_one) {
char errmsg[1024];
sprintf(errmsg, "Internal error: name = %s, iaux = %i, "
"size_one = %i", perat[i].name, iaux, size_one);
error->one(FLERR,errmsg);
}
for (int j = 0; j < n; j++, iaux+=size_one) {
double_buffer[j] = mybuf[iaux];
}
start[2] = idim;
NCERRX( ncmpi_put_vars_double_all(ncid, perat[i].var, start, count,
stride, double_buffer), perat[i].name );
}
}
}
else {
for (int j = 0; j < n; j++, iaux+=size_one) {
double_buffer[j] = mybuf[iaux];
}
NCERRX( ncmpi_put_vara_double_all(ncid, perat[i].var, start, count,
double_buffer), perat[i].name );
}
}
}
}
/* ---------------------------------------------------------------------- */
int DumpNetCDFMPIIO::modify_param(int narg, char **arg)
{
int iarg = 0;
if (strcmp(arg[iarg],"double") == 0) {
iarg++;
if (iarg >= narg)
error->all(FLERR,"expected 'yes' or 'no' after 'double' keyword.");
if (strcmp(arg[iarg],"yes") == 0) {
double_precision = true;
}
else if (strcmp(arg[iarg],"no") == 0) {
double_precision = false;
}
else error->all(FLERR,"expected 'yes' or 'no' after 'double' keyword.");
iarg++;
return 2;
}
else if (strcmp(arg[iarg],"at") == 0) {
iarg++;
if (iarg >= narg)
error->all(FLERR,"expected additional arg after 'at' keyword.");
framei = force->inumeric(FLERR,arg[iarg]);
if (framei == 0) error->all(FLERR,"frame 0 not allowed for 'at' keyword.");
else if (framei < 0) framei--;
iarg++;
return 2;
}
else if (strcmp(arg[iarg],"thermo") == 0) {
iarg++;
if (iarg >= narg)
error->all(FLERR,"expected 'yes' or 'no' after 'thermo' keyword.");
if (strcmp(arg[iarg],"yes") == 0) {
thermo = true;
}
else if (strcmp(arg[iarg],"no") == 0) {
thermo = false;
}
else error->all(FLERR,"expected 'yes' or 'no' after 'thermo' keyword.");
iarg++;
return 2;
} else return 0;
}
/* ---------------------------------------------------------------------- */
void DumpNetCDFMPIIO::ncerr(int err, const char *descr, int line)
{
if (err != NC_NOERR) {
char errstr[1024];
if (descr) {
sprintf(errstr, "NetCDF failed with error '%s' (while accessing '%s') "
" in line %i of %s.", ncmpi_strerror(err), descr, line, __FILE__);
}
else {
sprintf(errstr, "NetCDF failed with error '%s' in line %i of %s.",
ncmpi_strerror(err), line, __FILE__);
}
error->one(FLERR,errstr);
}
}
#endif /* defined(LMP_HAS_PNETCDF) */
| 31.967526 | 86 | 0.544159 | [
"vector"
] |
026a70ba4ed22c9537c660f77e2e704f81f43ed8 | 720 | cpp | C++ | test/snippet/range/views/deep_no_param.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | 1 | 2021-03-01T11:12:56.000Z | 2021-03-01T11:12:56.000Z | test/snippet/range/views/deep_no_param.cpp | simonsasse/seqan3 | 0ff2e117952743f081735df9956be4c512f4ccba | [
"CC0-1.0",
"CC-BY-4.0"
] | 2 | 2017-05-17T07:16:19.000Z | 2020-02-13T16:10:10.000Z | test/snippet/range/views/deep_no_param.cpp | simonsasse/seqan3 | 0ff2e117952743f081735df9956be4c512f4ccba | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | #include <vector>
#include <seqan3/alphabet/nucleotide/dna5.hpp>
#include <seqan3/range/views/deep.hpp>
#include <seqan3/std/ranges>
namespace my
{
// You can create a permanent alias:
inline auto const deep_reverse = seqan3::views::deep{std::views::reverse};
}
int main()
{
using seqan3::operator""_dna5;
std::vector<seqan3::dna5_vector> foo{"AAATTT"_dna5, "CCCGGG"_dna5};
auto r = foo | std::views::reverse; // == [ [C,C,C,G,G,G], [A,A,A,T,T,T] ]
// These two are equivalent:
auto e = foo | my::deep_reverse; // == [ [T,T,T,A,A,A], [G,G,G,C,C,C] ]
auto d = foo | seqan3::views::deep{std::views::reverse}; // == [ [T,T,T,A,A,A], [G,G,G,C,C,C] ]
}
| 28.8 | 99 | 0.583333 | [
"vector"
] |
026fdce9f16f626153ccfd7e9cb7e7443f2d7fe8 | 7,124 | cpp | C++ | vrjugglua/LuaScript.cpp | wangfeilong321/vr-jugglua | 5dbefe4c32dd3ddf498dab555373b767c3464df4 | [
"BSL-1.0"
] | 7 | 2015-03-28T04:24:48.000Z | 2021-07-16T06:17:31.000Z | vrjugglua/LuaScript.cpp | vancegroup/vr-jugglua | 5dbefe4c32dd3ddf498dab555373b767c3464df4 | [
"BSL-1.0"
] | null | null | null | vrjugglua/LuaScript.cpp | vancegroup/vr-jugglua | 5dbefe4c32dd3ddf498dab555373b767c3464df4 | [
"BSL-1.0"
] | 3 | 2015-06-17T14:43:43.000Z | 2021-07-16T06:17:40.000Z | /** @file
@brief implementation
@date
2009-2011
@author
Ryan Pavlik
<rpavlik@iastate.edu> and <abiryan@ryand.net>
http://academic.cleardefinition.com/
Iowa State University Virtual Reality Applications Center
Human-Computer Interaction Graduate Program
*/
// Copyright Iowa State University 2009-2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Internal Includes
#include "LuaScript.h"
#include "ApplyBinding.h"
#include "LuaGCBlock.h"
#include "LuaPath.h"
#include "VRJLuaOutput.h"
// Library/third-party includes
#include <vrjugglua/LuaIncludeFull.h>
#include <luabind/luabind.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
// Standard includes
#include <functional>
#include <iostream>
#include <sstream>
#ifdef VERBOSE
#define VERBOSE_MSG(X) \
std::cout << "In " << __FUNCTION__ << " at " << __FILE__ << ":" \
<< __LINE__ << " with this=" << this << ": " << X << std::endl
#else
#define VERBOSE_MSG(X)
#endif
namespace vrjLua {
bool LuaScript::exitOnError = false;
boost::function<void(std::string const &)> LuaScript::_printFunc;
LuaScript::LuaScript(const bool create) {
VERBOSE_MSG("Constructor");
if (create) {
VERBOSE_MSG("Create=true");
_state = LuaStatePtr(luaL_newstate(), std::ptr_fun(lua_close));
if (!_state) {
throw CouldNotOpenState();
}
{
/// RAII-style disabling of garbage collector during init
LuaGCBlock gcBlocker(_state.get());
// Load default Lua libs
luaL_openlibs(_state.get());
// Load our bindings.
_applyBindings();
}
}
}
LuaScript::LuaScript(lua_State *state, bool bind)
: _state(borrowStatePtr(state)) {
VERBOSE_MSG("Constructor from lua_State * with bind = " << bind);
if (!_state) {
throw NoValidLuaState();
}
// If requested, bind.
if (bind) {
_applyBindings();
}
}
LuaScript::LuaScript(const LuaScript &other) : _state(other._state) {
VERBOSE_MSG("Copy constructor");
}
LuaScript::LuaScript(const LuaStatePtr &otherptr) : _state(otherptr) {
VERBOSE_MSG("Constructor from LuaStatePtr (smart pointer)");
if (!_state) {
throw NoValidLuaState();
}
}
LuaScript::~LuaScript() { VERBOSE_MSG("Destructor"); }
LuaScript &LuaScript::operator=(const LuaScript &other) {
if (!other._state) {
std::cerr << "Warning: setting a LuaScript equal to another "
"LuaScript with an empty state smart pointer!"
<< std::endl;
}
if (&other == this) {
/// self assignment
return *this;
}
_state = other._state;
return *this;
}
void LuaScript::initWithArgv0(const char *argv0) {
LuaPath::instance(argv0);
}
bool LuaScript::_handleLuaReturnCode(int returnVal,
std::string const &failureMsg,
std::string const &successMsg) {
if (returnVal != 0) {
std::string err;
try {
luabind::object o(luabind::from_stack(_state.get(), -1));
err = " Lua returned this error message: " +
luabind::object_cast<std::string>(o);
}
catch (...) {
// do nothing - couldn't get an error string
err = " Furthermore, we couldn't get error details from Lua.";
}
doPrint(failureMsg + err);
return false;
} else {
if (!successMsg.empty()) {
VRJLUA_MSG_START(dbgVRJLUA, MSG_STATUS)
<< successMsg << VRJLUA_MSG_END(dbgVRJLUA, MSG_STATUS);
}
return true;
}
}
bool LuaScript::runFile(const std::string &fn, bool silentSuccess) {
if (!_state) {
throw NoValidLuaState();
}
return _handleLuaReturnCode(
luaL_dofile(_state.get(), fn.c_str()),
std::string("vrjLua ERROR: Could not run Lua file ") + fn + ".",
silentSuccess ? ""
: std::string("Successfully ran Lua file ") + fn);
}
bool LuaScript::requireModule(const std::string &mod, bool silentSuccess) {
if (!_state) {
throw NoValidLuaState();
}
try {
luabind::call_function<void>(_state.get(), "require", mod);
}
catch (std::exception &e) {
doPrint(std::string("vrjLua ERROR: Could not load Lua module ") +
mod + " - error: " + e.what());
return false;
}
if (!silentSuccess) {
VRJLUA_MSG_START(dbgVRJLUA, MSG_STATUS)
<< "Successfully loaded Lua module " << mod
<< VRJLUA_MSG_END(dbgVRJLUA, MSG_STATUS);
}
return true;
}
bool LuaScript::runString(const std::string &str, bool silentSuccess) {
if (!_state) {
throw NoValidLuaState();
}
return _handleLuaReturnCode(
luaL_dostring(_state.get(), str.c_str()),
"vrjLua ERROR: Could not run provided Lua string.",
silentSuccess ? "" : "Lua string executed successfully.");
}
void LuaScript::_applyBindings() {
if (!_state) {
throw NoValidLuaState();
}
applyBinding(_state.get());
}
bool LuaScript::call(const std::string &func, bool silentSuccess) {
if (!_state) {
throw NoValidLuaState();
}
try {
return luabind::call_function<bool>(_state.get(), func.c_str());
}
catch (const std::exception &e) {
std::cerr << "Caught exception calling '" << func
<< "': " << e.what() << std::endl;
throw;
}
}
void LuaScript::setPrintFunction(
boost::function<void(std::string const &)> func) {
_printFunc = func;
}
LuaStatePtr const &LuaScript::getLuaState() const {
if (!_state) {
throw NoValidLuaState();
}
return _state;
}
lua_State *LuaScript::getLuaRawState() const {
if (!_state) {
throw NoValidLuaState();
}
return _state.get();
}
void LuaScript::doPrint(std::string const &str) {
if (_printFunc) {
_printFunc(str);
} else {
VRJLUA_MSG_START(dbgVRJLUA_APP, MSG_STATUS)
<< str << VRJLUA_MSG_END(dbgVRJLUA_APP, MSG_STATUS);
}
}
} // end of vrjLua namespace
| 29.683333 | 80 | 0.535093 | [
"object"
] |
027cf8ab4a19d2f8132c09e9f283ad2ca773b520 | 8,733 | cpp | C++ | src/System/Double.cpp | kmc7468/CppNet2 | 29b7279b6f4bf10a88e513b97acef02e2159cae9 | [
"MIT"
] | 8 | 2017-04-05T13:07:47.000Z | 2021-09-05T20:22:20.000Z | src/System/Double.cpp | kmc7468/CppNet2 | 29b7279b6f4bf10a88e513b97acef02e2159cae9 | [
"MIT"
] | 1 | 2019-02-25T16:01:13.000Z | 2019-02-25T16:01:13.000Z | src/System/Double.cpp | kmc7468/CppNet2 | 29b7279b6f4bf10a88e513b97acef02e2159cae9 | [
"MIT"
] | null | null | null | #include <CppNet2/System/Double.hpp>
#include <CppNet2/Details/Hash32.hpp>
#include <CppNet2/Details/Sign.hpp>
#include <CppNet2/System/ArgumentException.hpp>
#include <cmath>
namespace CppNet2::System
{
Double::Double(double decimal) noexcept
: m_Value(decimal)
{}
Double::Double(const Double& decimal) noexcept
: m_Value(decimal.m_Value)
{}
Double& Double::operator=(double decimal) noexcept
{
return m_Value = decimal, *this;
}
Double& Double::operator=(const Double& decimal) noexcept
{
return m_Value = decimal.m_Value, *this;
}
Boolean operator==(double lhs, const Double& rhs) noexcept
{
return lhs == rhs.m_Value;
}
Boolean operator==(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value == rhs;
}
Boolean operator==(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value == rhs.m_Value;
}
Boolean operator!=(double lhs, const Double& rhs) noexcept
{
return lhs != rhs.m_Value;
}
Boolean operator!=(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value != rhs;
}
Boolean operator!=(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value != rhs.m_Value;
}
Boolean operator>(double lhs, const Double& rhs) noexcept
{
return lhs > rhs.m_Value;
}
Boolean operator>(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value > rhs;
}
Boolean operator>(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value > rhs.m_Value;
}
Boolean operator>=(double lhs, const Double& rhs) noexcept
{
return lhs >= rhs.m_Value;
}
Boolean operator>=(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value >= rhs;
}
Boolean operator>=(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value >= rhs.m_Value;
}
Boolean operator<(double lhs, const Double& rhs) noexcept
{
return lhs < rhs.m_Value;
}
Boolean operator<(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value < rhs;
}
Boolean operator<(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value < rhs.m_Value;
}
Boolean operator<=(double lhs, const Double& rhs) noexcept
{
return lhs <= rhs.m_Value;
}
Boolean operator<=(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value <= rhs;
}
Boolean operator<=(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value <= rhs.m_Value;
}
Double operator+(double lhs, const Double& rhs) noexcept
{
return lhs + rhs.m_Value;
}
Double operator+(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value + rhs;
}
Double operator+(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value + rhs.m_Value;
}
Double operator-(double lhs, const Double& rhs) noexcept
{
return lhs - rhs.m_Value;
}
Double operator-(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value - rhs;
}
Double operator-(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value - rhs.m_Value;
}
Double operator*(double lhs, const Double& rhs) noexcept
{
return lhs * rhs.m_Value;
}
Double operator*(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value * rhs;
}
Double operator*(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value * rhs.m_Value;
}
Double operator/(double lhs, const Double& rhs) noexcept
{
return lhs / rhs.m_Value;
}
Double operator/(const Double& lhs, double rhs) noexcept
{
return lhs.m_Value / rhs;
}
Double operator/(const Double& lhs, const Double& rhs) noexcept
{
return lhs.m_Value / rhs.m_Value;
}
Double operator%(double lhs, const Double& rhs) noexcept
{
return std::fmod(lhs, rhs.m_Value);
}
Double operator%(const Double& lhs, double rhs) noexcept
{
return std::fmod(lhs.m_Value, rhs);
}
Double operator%(const Double& lhs, const Double& rhs) noexcept
{
return std::fmod(lhs.m_Value, rhs.m_Value);
}
Double& Double::operator+=(double decimal) noexcept
{
return m_Value += decimal, *this;
}
Double& Double::operator+=(const Double& decimal) noexcept
{
return m_Value += decimal.m_Value, *this;
}
Double& Double::operator-=(double decimal) noexcept
{
return m_Value -= decimal, *this;
}
Double& Double::operator-=(const Double& decimal) noexcept
{
return m_Value -= decimal.m_Value, *this;
}
Double& Double::operator*=(double decimal) noexcept
{
return m_Value *= decimal, *this;
}
Double& Double::operator*=(const Double& decimal) noexcept
{
return m_Value *= decimal.m_Value, *this;
}
Double& Double::operator/=(double decimal) noexcept
{
return m_Value /= decimal, *this;
}
Double& Double::operator/=(const Double& decimal) noexcept
{
return m_Value /= decimal.m_Value, *this;
}
Double& Double::operator%=(double decimal) noexcept
{
return m_Value = std::fmod(m_Value, decimal), *this;
}
Double& Double::operator%=(const Double& decimal) noexcept
{
return m_Value = std::fmod(m_Value, decimal.m_Value), *this;
}
Double operator+(const Double& decimal) noexcept
{
return decimal.m_Value;
}
Double operator-(const Double& decimal) noexcept
{
return -decimal.m_Value;
}
Double& Double::operator++() noexcept
{
return ++m_Value, *this;
}
Double Double::operator++(int) noexcept
{
const Double temp(*this);
return ++m_Value, temp;
}
Double& Double::operator--() noexcept
{
return --m_Value, *this;
}
Double Double::operator--(int) noexcept
{
const Double temp(*this);
return --m_Value, temp;
}
Double::operator double() const noexcept
{
return m_Value;
}
Int32 Double::GetHashCode() const
{
return Details::Hash32(m_Value);
}
String Double::ToString() const
{
return {}; // TODO
}
Int32 Double::CompareTo(const Double& other) const
{
return Details::Sign(m_Value - other.m_Value);
}
Int32 Double::CompareTo(const Object& other) const
{
if (const Double* other_double = dynamic_cast<const Double*>(&other);
other_double) return CompareTo(*other_double);
throw ArgumentException(u"Object must be of type CppNet2::System::Double.", u"other");
}
Boolean Double::Equals(const Double& other) const
{
return *this == other;
}
Boolean Double::Equals(const Object& other) const
{
if (const Double* other_double = dynamic_cast<const Double*>(&other);
other_double) return Equals(*other_double);
else return false;
}
Boolean operator==(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) == rhs;
}
Boolean operator==(const Double& lhs, const Int32& rhs) noexcept
{
return lhs == static_cast<Double>(rhs);
}
Boolean operator!=(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) != rhs;
}
Boolean operator!=(const Double& lhs, const Int32& rhs) noexcept
{
return lhs != static_cast<Double>(rhs);
}
Boolean operator>(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) > rhs;
}
Boolean operator>(const Double& lhs, const Int32& rhs) noexcept
{
return lhs > static_cast<Double>(rhs);
}
Boolean operator>=(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) >= rhs;
}
Boolean operator>=(const Double& lhs, const Int32& rhs) noexcept
{
return lhs >= static_cast<Double>(rhs);
}
Boolean operator<(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) < rhs;
}
Boolean operator<(const Double& lhs, const Int32& rhs) noexcept
{
return lhs < static_cast<Double>(rhs);
}
Boolean operator<=(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) <= rhs;
}
Boolean operator<=(const Double& lhs, const Int32& rhs) noexcept
{
return lhs <= static_cast<Double>(rhs);
}
Double operator+(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) + rhs;
}
Double operator+(const Double& lhs, const Int32& rhs) noexcept
{
return lhs + static_cast<Double>(rhs);
}
Double operator-(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) - rhs;
}
Double operator-(const Double& lhs, const Int32& rhs) noexcept
{
return lhs - static_cast<Double>(rhs);
}
Double operator*(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) * rhs;
}
Double operator*(const Double& lhs, const Int32& rhs) noexcept
{
return lhs * static_cast<Double>(rhs);
}
Double operator/(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) / rhs;
}
Double operator/(const Double& lhs, const Int32& rhs) noexcept
{
return lhs / static_cast<Double>(rhs);
}
Double operator%(const Int32& lhs, const Double& rhs) noexcept
{
return static_cast<Double>(lhs) % rhs;
}
Double operator%(const Double& lhs, const Int32& rhs) noexcept
{
return lhs % static_cast<Double>(rhs);
}
} | 25.239884 | 88 | 0.69976 | [
"object"
] |
0281047f091b4ad231623e5207cdf4614f704f92 | 6,917 | cc | C++ | src/test_unix/TestVector.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/test_unix/TestVector.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/test_unix/TestVector.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | 1 | 2022-01-07T15:58:38.000Z | 2022-01-07T15:58:38.000Z | /*
**
** $Filename: TestVector.cc $
** $Release: Dortmund 2002 $
** $Revision$
** $Date$
** $Developer: Steffen A. Mork $
**
** Blizzard III - Test routines for vector computing
**
** (C) Copyright 2002 Steffen A. Mork
** All Rights Reserved
**
**
**
*/
/*************************************************************************
** **
** Blizzard III includes **
** **
*************************************************************************/
#include "blz3/b3Config.h"
#include "blz3/base/b3Array.h"
#include "blz3/base/b3Matrix.h"
#include "blz3/base/b3Vector.h"
/*************************************************************************
** **
** implementation **
** **
*************************************************************************/
#define MAX_DIM 1000
#define RAN_MAX 1024
class b3VectorTestSuite
{
b3Array<const char *> m_TestComment;
b3Array<b3_f64> m_TestResult;
public:
virtual ~b3VectorTestSuite() {}
virtual b3_f64 b3Length() = 0;
virtual b3_f64 b3Test() = 0;
void b3PrintResult()
{
for (int i = 0; i < m_TestResult.b3GetCount(); i++)
{
b3PrintF(B3LOG_NORMAL, "%2d: %3.5f - %s\n", i, m_TestResult[i], m_TestComment[i]);
}
}
protected:
b3_f64 b3Random()
{
return B3_FRAN(RAN_MAX) + RAN_MAX * 0.5;
}
void b3Add(const char * text)
{
m_TestComment.b3Add(text);
m_TestResult.b3Add(b3Length());
}
};
/*************************************************************************
** **
** Testing vector struct **
** **
*************************************************************************/
class b3VectorArray;
class b3VectorStruct : public b3VectorTestSuite
{
friend class b3VectorArray;
protected:
b3_vector m_Array[MAX_DIM];
public:
b3VectorStruct()
{
for (int i = 0; i < MAX_DIM; i++)
{
b3Vector::b3Init(&m_Array[i], b3Random(), b3Random(), b3Random());
}
b3Add("constructor");
}
virtual ~b3VectorStruct()
{
}
inline b3_f64 b3Length() override
{
b3_f64 length = 0;
for (int i = 0; i < MAX_DIM; i++)
{
length += b3Vector::b3Length(&m_Array[i]);
}
return length;
}
inline b3_f64 b3Test() override
{
b3_vector aux;
int k, max;
b3Vector::b3Init(&m_Array[20]);
for (k = 0; k < 20; k += 3)
{
b3Vector::b3Mul(&m_Array[k + 1], &m_Array[k + 2], &aux);
b3Vector::b3Add(&m_Array[k], &m_Array[20]);
b3Vector::b3Sub(&aux, &m_Array[20]);
}
b3Add("+/-/*");
b3Vector::b3Scale(&m_Array[20], &m_Array[20], 1.0 / 1024.0);
b3Add("/= 1024");
b3Vector::b3Scale(&m_Array[20], 0.25);
b3Add("*= 0.25");
while (k < 40)
{
b3Vector::b3CrossProduct(&m_Array[k], &m_Array[k + 1], &m_Array[k + 2]);
k += 3;
}
b3Add("cross product");
max = k + k;
for (k = 0; k < max; k += 2)
{
b3Vector::b3Init(
&m_Array[k + max],
b3Vector::b3Distance(&m_Array[k], &m_Array[k + 1]),
b3Vector::b3SMul(&m_Array[k], &m_Array[k + 1]),
b3Vector::b3Length(&m_Array[k]));
}
b3Add("distance/sMul/length");
for (k = 0; k < MAX_DIM; k++)
{
b3Vector::b3SetMinimum(&m_Array[k], -RAN_MAX * 0.5);
b3Vector::b3SetMaximum(&m_Array[k], RAN_MAX * 0.5);
}
b3Add("minimum/maximum");
b3Vector::b3InitBound(&m_Array[MAX_DIM - 2], &m_Array[MAX_DIM - 1]);
for (k = 0; k < (MAX_DIM - 2); k++)
{
b3Vector::b3AdjustBound(&m_Array[k], &m_Array[MAX_DIM - 2], &m_Array[MAX_DIM - 1]);
}
b3Add("check bound");
for (k = 0; k < MAX_DIM; k += 4)
{
b3Vector::b3LinearCombine(
&m_Array[k + 1],
&m_Array[k + 2],
&m_Array[k + 3],
m_Array[k].x,
m_Array[k].y,
&m_Array[k]);
}
b3Add("linear combination");
for (k = 0; k < MAX_DIM; k++)
{
b3Vector::b3Normalize(&m_Array[k], k);
}
b3Add("normalize(k)");
return b3Length();
}
};
/*************************************************************************
** **
** Testing vector array **
** **
*************************************************************************/
class b3VectorArray : public b3VectorTestSuite
{
b3Vector32 m_Array[MAX_DIM];
public:
b3VectorArray(b3VectorStruct & vStruct)
{
for (int i = 0; i < MAX_DIM; i++)
{
m_Array[i] = b3Vector32(vStruct.m_Array[i]);
}
b3Add("constructor");
}
virtual ~b3VectorArray()
{
}
inline b3_f64 b3Length() override
{
b3_f64 length = 0;
for (int i = 0; i < MAX_DIM; i++)
{
length += m_Array[i].b3Length();
}
return length;
}
inline b3_f64 b3Test() override
{
int k, max;
m_Array[20].b3Zero();
for (k = 0; k < 20; k += 3)
{
m_Array[20] = m_Array[20] + m_Array[k] - m_Array[k + 1] * m_Array[k + 2];
}
b3Add("+/-/*");
m_Array[20] /= 1024.0;
b3Add("/= 1024");
m_Array[20] *= 0.25;
b3Add("*= 0.25");
while (k < 40)
{
m_Array[k + 2] = b3Vector32::b3CrossProduct(m_Array[k], m_Array[k + 1]);
k += 3;
}
b3Add("cross product");
max = k + k;
for (k = 0; k < max; k += 2)
{
m_Array[k + max].b3Init(
b3Vector32::b3Distance(m_Array[k], m_Array[k + 1]),
b3Vector32::b3SMul(m_Array[k], m_Array[k + 1]),
m_Array[k].b3Length());
}
b3Add("distance/sMul/length");
for (k = 0; k < MAX_DIM; k++)
{
m_Array[k].b3SetMinimum(-RAN_MAX * 0.5);
m_Array[k].b3SetMaximum(RAN_MAX * 0.5);
}
b3Add("minimum/maximum");
b3Vector32::b3InitBound(m_Array[MAX_DIM - 2], m_Array[MAX_DIM - 1]);
for (k = 0; k < (MAX_DIM - 2); k++)
{
m_Array[k].b3AdjustBound(m_Array[MAX_DIM - 2], m_Array[MAX_DIM - 1]);
}
m_Array[MAX_DIM - 2].b3Print("Lower:");
m_Array[MAX_DIM - 1].b3Print("Upper:");
b3Add("check bound");
for (k = 0; k < MAX_DIM; k += 4)
{
m_Array[k] = m_Array[k + 1] + m_Array[k + 2] * m_Array[k][X] + m_Array[k + 3] * m_Array[k][Y];
}
b3Add("linear combination");
for (k = 0; k < MAX_DIM; k++)
{
m_Array[k].b3Normalize(k);
}
b3Add("normalize(k)");
return b3Length();
}
};
int main()
{
b3VectorStruct vStruct;
b3VectorArray vArray(vStruct);
b3_f64 a, b;
a = vStruct.b3Test();
b = vArray.b3Test();
if (a != b)
{
b3PrintF(B3LOG_NORMAL, "Test failed (distance: %3.5f).\n", fabs(a - b));
vStruct.b3PrintResult();
vArray.b3PrintResult();
}
return EXIT_SUCCESS;
}
| 23.133779 | 97 | 0.470435 | [
"vector"
] |
028e11920d6abd2d327d8a0c128079422ec1a1bc | 21,636 | cpp | C++ | src/Trinity.TSL/Trinity.TSL.CodeGen/Trinity.TSL.CodeGen.cpp | erinloy/GraphEngine | 1a913c18043192c597d48e0b4e77b0a62cd6a10e | [
"MIT"
] | 370 | 2019-05-08T07:40:52.000Z | 2022-03-28T15:29:18.000Z | src/Trinity.TSL/Trinity.TSL.CodeGen/Trinity.TSL.CodeGen.cpp | erinloy/GraphEngine | 1a913c18043192c597d48e0b4e77b0a62cd6a10e | [
"MIT"
] | 55 | 2019-05-20T09:01:48.000Z | 2022-03-31T23:05:23.000Z | src/Trinity.TSL/Trinity.TSL.CodeGen/Trinity.TSL.CodeGen.cpp | erinloy/GraphEngine | 1a913c18043192c597d48e0b4e77b0a62cd6a10e | [
"MIT"
] | 83 | 2019-05-15T14:16:23.000Z | 2022-03-06T07:04:10.000Z | #include <unordered_set>
#include <corelib>
#include <utilities>
#include <io>
#include "common.h"
#include "parser.tab.h"
#define NF(x) #x, x
#define NAME(x) #x
template<typename Func, typename N>
static void write_file(const String& target_path, const String& name, Func gen, N* node, std::vector<std::string*>* files)
{
Console::WriteLine("Generating {0}.cs...", name);
std::string* content = gen(node);
Trinity::String content_path = Path::GetFullPath(Path::Combine(target_path, name + ".cs"));
String lower_content_path = content_path;
lower_content_path.ToLower();
while (files && files->end() != std::find_if(files->begin(), files->end(),
[&](const std::string* pfname) { return String(pfname->c_str()).ToLower() == lower_content_path; }))
{
content_path = lower_content_path = Path::Combine(
Path::GetDirectoryName(content_path),
Path::GetFileNameWithoutExtension(content_path) + "_.cs");
lower_content_path.ToLower();
}
Trinity::String content_dir = Path::GetDirectoryName(content_path);
if (!Directory::Exists(content_dir))
Directory::EnsureDirectory(content_dir);
FILE *fp;
_wfopen_s(&fp, Trinity::String(content_path).ToWcharArray(), _u("w"));
if (fp == NULL)
{
error("Cannot open file " + content_path);
exit(-1);
}
// suppress warnings
fprintf(fp, "#pragma warning disable 162,168,649,660,661,1522\n");
fprintf(fp, "%s\n", content->c_str());
fprintf(fp, "#pragma warning restore 162,168,649,660,661,1522\n");
fclose(fp);
delete content;
if (files)
{
files->push_back(new std::string(content_path.c_str()));
}
}
namespace Trinity
{
namespace Codegen
{
std::string target_namespace;
bool contains_substring_index;
int celltype_offset;
/**
* TSLDataTypeVector: data types referenced as cell fields
* TSLExternalParserDataTypeVector: TSLDataTypeVector + data types referenced as struct fields
* TSLSerializerDataTypeVector: TSLExternalParserDataTypeVector + all structs(no matter referenced or not).
*/
std::vector<NFieldType*> *TSLDataTypeVector = NULL;
std::vector<NFieldType*> *TSLExternalParserDataTypeVector = NULL;
std::vector<NFieldType*> *TSLSerializerDataTypeVector = NULL;
std::vector<std::unique_ptr<NFieldType>> *TSLSubstringIndexedListTypes = NULL;
NFieldType *force_add_string_field_type = NULL;
NFieldType *force_add_list_string_field_type = NULL;
std::vector<std::unique_ptr<NFieldType>> *force_add_struct_type_list = NULL;
std::vector<NCell*>* TSLIndexIdentifierCellVector = NULL;
std::vector<NStruct*>* TSLIndexIdentifierStructVector = NULL;
std::unordered_map<NStructBase*, std::vector<NField*>*>* TSLIndexIdentifierSubstructureMap = NULL;
std::unordered_map<NStructBase*, std::vector<NField*>*>* TSLIndexIdentifierTargetMap = NULL;
std::unordered_map<NField*, int>* TSLIndexFieldIdMap = NULL;
std::unordered_map<NIndex*, int>* TSLIndexIdMap = NULL;
std::vector<NIndex*>* TSLIndexTargetVector = NULL;
std::unordered_set<NStructBase*> message_structs;
#pragma region Helper functions
NFieldType* _get_raw_ptr(NFieldType* ptr)
{
return ptr;
}
NFieldType* _get_raw_ptr(const std::unique_ptr<NFieldType> &ptr)
{
return ptr.get();
}
void _sort_ft_vec(std::vector<NFieldType*>* vec)
{
std::sort(vec->begin(), vec->end(), (bool(*)(NFieldType*, NFieldType*))NFieldType_LessThan);
}
void _sort_ft_vec(std::vector<std::unique_ptr<NFieldType>>* vec)
{
std::sort(vec->begin(), vec->end(), (bool(*)(const std::unique_ptr<NFieldType>&, const std::unique_ptr<NFieldType>&))NFieldType_LessThan);
}
#pragma endregion
template<typename NFieldTypePtr>
void DeduplicateNFieldTypeVector(std::vector<NFieldTypePtr>* vec)
{
_sort_ft_vec(vec);
NFieldType* previous = NULL;
NFieldType* current = NULL;
for (auto i = vec->begin(); i != vec->end();)
{
/* forcibly remove "string?" */
if ((*i)->is_string() && (*i)->is_optional())
{
i = vec->erase(i);
continue;
}
/* forcibly remove aliases */
if ((*i)->is_alias())
{
i = vec->erase(i);
continue;
}
current = _get_raw_ptr(*i);
if (previous == NULL || NFieldType_Compare(current, previous))
{
previous = _get_raw_ptr(*i++);
}
else
{
i = vec->erase(i);
}
}
}
void CalculateMessageAccessors(NTSL* tsl)
{
std::unordered_set<NStructBase*> message_cells;
auto try_add = [&](std::string* name)
{
if (name == nullptr) return;
auto s = tsl->find_struct_or_cell(name);
if (s == nullptr) return;
if (s->is_struct()) message_structs.insert(s);
else message_cells.insert(s);
};
for (auto proto : *tsl->protocolList)
{
if (proto->is_http_protocol()) continue;
if (proto->has_request()) { try_add(proto->request_message_struct); }
if (proto->has_response()) { try_add(proto->response_message_struct); }
}
/* add cell structs for messages */
for (auto msg_cell : message_cells)
{
/* deep copy from msg_cell */
NStruct* s = new NStruct(msg_cell);
/* append _Message to the name of the cell */
*s->name += "_Message";
/* add optional long CellId field */
NField *field = new NField();
field->attributes = new std::vector<NKVPair*>();
field->parent = msg_cell;
field->modifiers = new std::vector<int>();
field->modifiers->push_back(T_OPTIONALMODIFIER);
field->name = new std::string("CellId");
field->fieldType = new NFieldType();
field->fieldType->field = field;
field->fieldType->fieldType = FT_ATOM;
field->fieldType->atom_token = T_LONGTYPE;
field->fieldType->layoutType = LT_FIXED;
s->fieldList->push_back(field);
/* add the cell struct to the struct list */
tsl->structList->push_back(s);
/* replicate it back to a cell, add to message accessor list.
* note, this NCell will only be used for generating a message accessor.
*/
NCell* c = new NCell(s);
*c->name = *msg_cell->name;
message_structs.insert(c);
}
}
void CalculateCellFieldDataTypes(NTSL* node)
{
TSLDataTypeVector->clear();
for (auto *cell : *node->cellList)
cell->fill_with_sub_field_types(TSLDataTypeVector);
/* Forcibly enable string type. */
force_add_string_field_type = new NFieldType();
force_add_string_field_type->fieldType = FT_ATOM;
force_add_string_field_type->atom_token = T_STRINGTYPE;
force_add_string_field_type->field = NULL;
force_add_string_field_type->layoutType = LT_DYNAMIC;
TSLDataTypeVector->push_back(force_add_string_field_type);
/* Forcibly enable List<string> type. */
force_add_list_string_field_type = new NFieldType();
force_add_list_string_field_type->fieldType = FT_LIST;
force_add_list_string_field_type->field = NULL;
force_add_list_string_field_type->layoutType = LT_DYNAMIC;
force_add_list_string_field_type->listElementType = force_add_string_field_type;
TSLDataTypeVector->push_back(force_add_list_string_field_type);
DeduplicateNFieldTypeVector(TSLDataTypeVector);
}
void CalculateExternalParserDataTypes(NTSL* node)
{
TSLExternalParserDataTypeVector->clear();
TSLExternalParserDataTypeVector->insert(TSLExternalParserDataTypeVector->begin(),
TSLDataTypeVector->begin(),
TSLDataTypeVector->end());
for (auto *struct_ : *node->structList)
struct_->fill_with_sub_field_types(TSLExternalParserDataTypeVector);
std::vector<NFieldType*> forcibly_add_non_nullable_types;
for (auto* field_type : *TSLExternalParserDataTypeVector)
{
if (field_type->is_nullable())
{
//forcibly enable the non-nullable version
forcibly_add_non_nullable_types.push_back(new NFieldType(field_type));
}
}
TSLExternalParserDataTypeVector->insert(TSLExternalParserDataTypeVector->end(),
forcibly_add_non_nullable_types.begin(),
forcibly_add_non_nullable_types.end());
DeduplicateNFieldTypeVector(TSLExternalParserDataTypeVector);
}
void CalculateSerializerDataTypes(NTSL* node)
{
TSLSerializerDataTypeVector->clear();
TSLSerializerDataTypeVector->insert(TSLSerializerDataTypeVector->begin(),
TSLExternalParserDataTypeVector->begin(),
TSLExternalParserDataTypeVector->end());
/* Forcibly enable struct types. */
force_add_struct_type_list = new std::vector<std::unique_ptr<NFieldType>>();
for (auto *struct_ : *node->structList)
{
NFieldType* force_add_struct_type = new NFieldType();
force_add_struct_type->fieldType = FT_STRUCT;
force_add_struct_type->field = NULL;
force_add_struct_type->referencedTypeName = struct_->name;
force_add_struct_type->layoutType = LT_DYNAMIC;
force_add_struct_type->referencedNStruct = struct_;
if (std::binary_search(
TSLSerializerDataTypeVector->begin(),
TSLSerializerDataTypeVector->end(),
force_add_struct_type,
(bool(*)(NFieldType*, NFieldType*))NFieldType_LessThan))
{
delete force_add_struct_type;
continue;
}
force_add_struct_type_list->push_back(std::unique_ptr<NFieldType>(force_add_struct_type));
TSLSerializerDataTypeVector->push_back(force_add_struct_type);
}
DeduplicateNFieldTypeVector(TSLSerializerDataTypeVector);
}
inline void IndexAddSubstructure(NStructBase* from, NField* to)
{
if (!TSLIndexIdentifierSubstructureMap->count(from))
(*TSLIndexIdentifierSubstructureMap)[from] = new std::vector<NField*>();
(*TSLIndexIdentifierSubstructureMap)[from]->push_back(to);
}
inline void IndexAddTarget(NStructBase* from, NField* to)
{
if (!TSLIndexIdentifierTargetMap->count(from))
(*TSLIndexIdentifierTargetMap)[from] = new std::vector<NField*>();
(*TSLIndexIdentifierTargetMap)[from]->push_back(to);
}
void CalculateIndexVariables(NTSL* tsl)
{
std::unordered_set<NCell*> cellSet;
std::unordered_set<NStruct*> structSet;
int field_id = 0;
for (auto* cell : *tsl->cellList)
{
if (cell->indexList->size())
cellSet.insert(cell);
for (auto *index : *cell->indexList)
{
auto path = index->resolve_target();
NStructBase* structBase = cell;
for (auto* field : *path)
{
if (field->fieldType->is_struct())
{
NStruct* referencedStruct = dynamic_cast<NStruct*>(field->fieldType->referencedNStruct);
if (!referencedStruct) { error(cell, "CalculateIndexVariables: referencing a cell"); continue; }
IndexAddSubstructure(structBase, field);
structBase = referencedStruct;
structSet.insert(referencedStruct);
}
else
{
IndexAddTarget(structBase, field);
TSLIndexTargetVector->push_back(index);
(*TSLIndexFieldIdMap)[field] = field_id++;
}
}
}
}
for (auto* index : *TSLIndexTargetVector)
{
(*TSLIndexIdMap)[index] = (*TSLIndexFieldIdMap)[index->target_field];
}
TSLIndexIdentifierCellVector->insert(
TSLIndexIdentifierCellVector->begin(), cellSet.begin(), cellSet.end());
TSLIndexIdentifierStructVector->insert(
TSLIndexIdentifierStructVector->begin(), structSet.begin(), structSet.end());
}
void CalculateSubstringIndexedDataTypes(NTSL* tsl)
{
contains_substring_index = false;
for (auto* index : *TSLIndexTargetVector)
{
if (index->type != IT_SUBSTRING)
{
continue;
}
contains_substring_index = true;
if (index->target_field->fieldType->is_string())
{
/* string is always included in code generation */
}
else
{
auto* p_ft = new NFieldType(*index->target_field->fieldType);
p_ft->field = NULL;//remove field reference so that p_ft doesn't appear optional.
TSLSubstringIndexedListTypes->push_back(std::unique_ptr<NFieldType>(p_ft));
}
}
DeduplicateNFieldTypeVector(TSLSubstringIndexedListTypes);
}
void CalculateRootNamespace(NTSL* tsl)
{
for (auto* setting : *tsl->settingsList)
{
for (auto* kvpair : *setting->settings)
{
if (*kvpair->key == "RootNamespace")
target_namespace = *kvpair->value;
}
}
}
#define NEW(x) x = new std::remove_pointer<decltype(x)>::type()
void initialize(NTSL* tsl)
{
NEW(TSLDataTypeVector);
NEW(TSLExternalParserDataTypeVector);
NEW(TSLSerializerDataTypeVector);
NEW(TSLSubstringIndexedListTypes);
NEW(TSLIndexIdentifierCellVector);
NEW(TSLIndexIdentifierStructVector);
NEW(TSLIndexIdentifierSubstructureMap);
NEW(TSLIndexIdentifierTargetMap);
NEW(TSLIndexFieldIdMap);
NEW(TSLIndexIdMap);
NEW(TSLIndexTargetVector);
CalculateMessageAccessors(tsl);
CalculateCellFieldDataTypes(tsl);
CalculateExternalParserDataTypes(tsl);
CalculateSerializerDataTypes(tsl);
CalculateIndexVariables(tsl);
CalculateSubstringIndexedDataTypes(tsl);
CalculateRootNamespace(tsl);
}
void uninitialize()
{
delete TSLDataTypeVector;
delete TSLExternalParserDataTypeVector;
delete TSLSerializerDataTypeVector;
delete TSLSubstringIndexedListTypes;
delete force_add_string_field_type;
delete force_add_list_string_field_type;
delete force_add_struct_type_list;
delete TSLIndexIdentifierCellVector;
delete TSLIndexIdentifierStructVector;
delete TSLIndexIdentifierSubstructureMap;
delete TSLIndexIdentifierTargetMap;
delete TSLIndexFieldIdMap;
delete TSLIndexIdMap;
delete TSLIndexTargetVector;
//TODO delete vectors in maps?
}
std::vector<std::string*>* codegen_entry(NTSL* tsl, const std::string& target_path, const std::string& target_namespace, const int cell_type_offset)
{
initialize(tsl);
auto *files = new std::vector<std::string*>();
Trinity::Codegen::celltype_offset = cell_type_offset;
if (Trinity::Codegen::target_namespace.empty())
Trinity::Codegen::target_namespace = target_namespace;
String lib_path = Path::Combine(target_path, "Lib");
String linq_path = Path::Combine(lib_path, "LINQ");
String cell_path = Path::Combine(target_path, "Cells");
String struct_path = Path::Combine(target_path, "Structs");
String substring_index_path = Path::Combine(lib_path, "SubstringIndex");
if (tsl->cellList->size() != 0)
{
write_file(lib_path, NF(GenericCell), tsl, files);
write_file(lib_path, NF(StorageSchema), tsl, files);
write_file(lib_path, NF(CellTypeEnum), tsl, files);
write_file(lib_path, NF(CellTypeExtension), tsl, files);
}
write_file(lib_path, NF(Enum), tsl, files);
write_file(lib_path, NF(ExternalParser), tsl, files);
write_file(lib_path, NF(Traits), tsl, files);
write_file(lib_path, NF(GenericFieldAccessor), tsl, files);
write_file(lib_path, NF(HTTP), tsl, files);
write_file(lib_path, NF(Protocols), tsl, files);
write_file(lib_path, NF(CommunicationSchema), tsl, files);
write_file(lib_path, NF(Serializer), tsl, files);
write_file(lib_path, NF(CellSelectors), tsl, files);
write_file(lib_path, NF(Throw), tsl, files);
write_file(lib_path, NF(Index), tsl, files);
write_file(lib_path, NF(ExtensionAttribute), tsl, files);
/* basic data structure accessors */
write_file(lib_path, NF(BufferAllocator), tsl, files);
write_file(lib_path, NF(byteListAccessor), tsl, files);
write_file(lib_path, NF(DateTimeAccessor), tsl, files);
write_file(lib_path, NF(doubleListAccessor), tsl, files);
write_file(lib_path, NF(EnumAccessor), tsl, files);
write_file(lib_path, NF(GuidAccessor), tsl, files);
write_file(lib_path, NF(intListAccessor), tsl, files);
write_file(lib_path, NF(longListAccessor), tsl, files);
write_file(lib_path, NF(StringAccessor), tsl, files);
write_file(lib_path, NF(U8StringAccessor), tsl, files);
/* containers */
write_file(lib_path, NF(Containers), tsl, files);
/* Index and LINQ */
if (contains_substring_index)
{
write_file(substring_index_path, NF(Indexer), tsl, files);
write_file(substring_index_path, NF(IndexItem), tsl, files);
write_file(substring_index_path, NF(Searcher), tsl, files);
}
write_file(linq_path, NF(ExpressionTreeRewriter), tsl, files);
write_file(linq_path, NF(IndexQueryTreeExecutor), tsl, files);
write_file(linq_path, NF(IndexQueryTreeNode), tsl, files);
write_file(linq_path, NF(PLINQWrapper), tsl, files);
/* Cell and Struct */
for (auto* cell : *tsl->cellList)
{
write_file(cell_path, *cell->name, Cell, cell, files);
}
for (auto* _struct : *tsl->structList)
{
write_file(struct_path, *_struct->name, Struct, _struct, files);
}
/* Message accessors */
std::vector<NStructBase*> message_accessors;
message_accessors.insert(message_accessors.end(), message_structs.begin(), message_structs.end());
write_file(lib_path, NF(MessageAccessors), &message_accessors, files);
uninitialize();
return files;
}
}
}
| 41.448276 | 156 | 0.549778 | [
"vector"
] |
029a0e7352ec593a88db567bbea62e2d2460cf27 | 8,434 | cpp | C++ | FreeBSD/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 4 | 2016-08-22T22:02:55.000Z | 2017-03-04T22:56:44.000Z | FreeBSD/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | FreeBSD/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp | TigerBSD/TigerBSD | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | null | null | null | //===-- RegisterContextPOSIX_arm.cpp --------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cstring>
#include <errno.h>
#include <stdint.h>
#include "lldb/Core/DataBufferHeap.h"
#include "lldb/Core/DataExtractor.h"
#include "lldb/Core/RegisterValue.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Host/Endian.h"
#include "llvm/Support/Compiler.h"
#include "RegisterContextPOSIX_arm.h"
#include "Plugins/Process/elf-core/ProcessElfCore.h"
using namespace lldb;
using namespace lldb_private;
// arm general purpose registers.
const uint32_t g_gpr_regnums_arm[] =
{
gpr_r0_arm,
gpr_r1_arm,
gpr_r2_arm,
gpr_r3_arm,
gpr_r4_arm,
gpr_r5_arm,
gpr_r6_arm,
gpr_r7_arm,
gpr_r8_arm,
gpr_r9_arm,
gpr_r10_arm,
gpr_r11_arm,
gpr_r12_arm,
gpr_sp_arm,
gpr_lr_arm,
gpr_pc_arm,
gpr_cpsr_arm,
LLDB_INVALID_REGNUM // register sets need to end with this flag
};
static_assert(((sizeof g_gpr_regnums_arm / sizeof g_gpr_regnums_arm[0]) - 1) == k_num_gpr_registers_arm, \
"g_gpr_regnums_arm has wrong number of register infos");
// arm floating point registers.
static const uint32_t g_fpu_regnums_arm[] =
{
fpu_s0_arm,
fpu_s1_arm,
fpu_s2_arm,
fpu_s3_arm,
fpu_s4_arm,
fpu_s5_arm,
fpu_s6_arm,
fpu_s7_arm,
fpu_s8_arm,
fpu_s9_arm,
fpu_s10_arm,
fpu_s11_arm,
fpu_s12_arm,
fpu_s13_arm,
fpu_s14_arm,
fpu_s15_arm,
fpu_s16_arm,
fpu_s17_arm,
fpu_s18_arm,
fpu_s19_arm,
fpu_s20_arm,
fpu_s21_arm,
fpu_s22_arm,
fpu_s23_arm,
fpu_s24_arm,
fpu_s25_arm,
fpu_s26_arm,
fpu_s27_arm,
fpu_s28_arm,
fpu_s29_arm,
fpu_s30_arm,
fpu_s31_arm,
fpu_fpscr_arm,
fpu_d0_arm,
fpu_d1_arm,
fpu_d2_arm,
fpu_d3_arm,
fpu_d4_arm,
fpu_d5_arm,
fpu_d6_arm,
fpu_d7_arm,
fpu_d8_arm,
fpu_d9_arm,
fpu_d10_arm,
fpu_d11_arm,
fpu_d12_arm,
fpu_d13_arm,
fpu_d14_arm,
fpu_d15_arm,
fpu_d16_arm,
fpu_d17_arm,
fpu_d18_arm,
fpu_d19_arm,
fpu_d20_arm,
fpu_d21_arm,
fpu_d22_arm,
fpu_d23_arm,
fpu_d24_arm,
fpu_d25_arm,
fpu_d26_arm,
fpu_d27_arm,
fpu_d28_arm,
fpu_d29_arm,
fpu_d30_arm,
fpu_d31_arm,
fpu_q0_arm,
fpu_q1_arm,
fpu_q2_arm,
fpu_q3_arm,
fpu_q4_arm,
fpu_q5_arm,
fpu_q6_arm,
fpu_q7_arm,
fpu_q8_arm,
fpu_q9_arm,
fpu_q10_arm,
fpu_q11_arm,
fpu_q12_arm,
fpu_q13_arm,
fpu_q14_arm,
fpu_q15_arm,
LLDB_INVALID_REGNUM // register sets need to end with this flag
};
static_assert(((sizeof g_fpu_regnums_arm / sizeof g_fpu_regnums_arm[0]) - 1) == k_num_fpr_registers_arm, \
"g_fpu_regnums_arm has wrong number of register infos");
// Number of register sets provided by this context.
enum
{
k_num_register_sets = 2
};
// Register sets for arm.
static const lldb_private::RegisterSet
g_reg_sets_arm[k_num_register_sets] =
{
{ "General Purpose Registers", "gpr", k_num_gpr_registers_arm, g_gpr_regnums_arm },
{ "Floating Point Registers", "fpu", k_num_fpr_registers_arm, g_fpu_regnums_arm }
};
bool RegisterContextPOSIX_arm::IsGPR(unsigned reg)
{
return reg <= m_reg_info.last_gpr; // GPR's come first.
}
bool RegisterContextPOSIX_arm::IsFPR(unsigned reg)
{
return (m_reg_info.first_fpr <= reg && reg <= m_reg_info.last_fpr);
}
RegisterContextPOSIX_arm::RegisterContextPOSIX_arm(lldb_private::Thread &thread,
uint32_t concrete_frame_idx,
lldb_private::RegisterInfoInterface *register_info)
: lldb_private::RegisterContext(thread, concrete_frame_idx)
{
m_register_info_ap.reset(register_info);
switch (register_info->m_target_arch.GetMachine())
{
case llvm::Triple::arm:
m_reg_info.num_registers = k_num_registers_arm;
m_reg_info.num_gpr_registers = k_num_gpr_registers_arm;
m_reg_info.num_fpr_registers = k_num_fpr_registers_arm;
m_reg_info.last_gpr = k_last_gpr_arm;
m_reg_info.first_fpr = k_first_fpr_arm;
m_reg_info.last_fpr = k_last_fpr_arm;
m_reg_info.first_fpr_v = fpu_s0_arm;
m_reg_info.last_fpr_v = fpu_s31_arm;
m_reg_info.gpr_flags = gpr_cpsr_arm;
break;
default:
assert(false && "Unhandled target architecture.");
break;
}
::memset(&m_fpr, 0, sizeof m_fpr);
// elf-core yet to support ReadFPR()
lldb::ProcessSP base = CalculateProcess();
if (base.get()->GetPluginName() == ProcessElfCore::GetPluginNameStatic())
return;
}
RegisterContextPOSIX_arm::~RegisterContextPOSIX_arm()
{
}
void
RegisterContextPOSIX_arm::Invalidate()
{
}
void
RegisterContextPOSIX_arm::InvalidateAllRegisters()
{
}
unsigned
RegisterContextPOSIX_arm::GetRegisterOffset(unsigned reg)
{
assert(reg < m_reg_info.num_registers && "Invalid register number.");
return GetRegisterInfo()[reg].byte_offset;
}
unsigned
RegisterContextPOSIX_arm::GetRegisterSize(unsigned reg)
{
assert(reg < m_reg_info.num_registers && "Invalid register number.");
return GetRegisterInfo()[reg].byte_size;
}
size_t
RegisterContextPOSIX_arm::GetRegisterCount()
{
size_t num_registers = m_reg_info.num_gpr_registers + m_reg_info.num_fpr_registers;
return num_registers;
}
size_t
RegisterContextPOSIX_arm::GetGPRSize()
{
return m_register_info_ap->GetGPRSize ();
}
const lldb_private::RegisterInfo *
RegisterContextPOSIX_arm::GetRegisterInfo()
{
// Commonly, this method is overridden and g_register_infos is copied and specialized.
// So, use GetRegisterInfo() rather than g_register_infos in this scope.
return m_register_info_ap->GetRegisterInfo ();
}
const lldb_private::RegisterInfo *
RegisterContextPOSIX_arm::GetRegisterInfoAtIndex(size_t reg)
{
if (reg < m_reg_info.num_registers)
return &GetRegisterInfo()[reg];
else
return NULL;
}
size_t
RegisterContextPOSIX_arm::GetRegisterSetCount()
{
size_t sets = 0;
for (size_t set = 0; set < k_num_register_sets; ++set)
{
if (IsRegisterSetAvailable(set))
++sets;
}
return sets;
}
const lldb_private::RegisterSet *
RegisterContextPOSIX_arm::GetRegisterSet(size_t set)
{
if (IsRegisterSetAvailable(set))
{
switch (m_register_info_ap->m_target_arch.GetMachine())
{
case llvm::Triple::arm:
return &g_reg_sets_arm[set];
default:
assert(false && "Unhandled target architecture.");
return NULL;
}
}
return NULL;
}
const char *
RegisterContextPOSIX_arm::GetRegisterName(unsigned reg)
{
assert(reg < m_reg_info.num_registers && "Invalid register offset.");
return GetRegisterInfo()[reg].name;
}
lldb::ByteOrder
RegisterContextPOSIX_arm::GetByteOrder()
{
// Get the target process whose privileged thread was used for the register read.
lldb::ByteOrder byte_order = lldb::eByteOrderInvalid;
lldb_private::Process *process = CalculateProcess().get();
if (process)
byte_order = process->GetByteOrder();
return byte_order;
}
bool
RegisterContextPOSIX_arm::IsRegisterSetAvailable(size_t set_index)
{
return set_index < k_num_register_sets;
}
// Used when parsing DWARF and EH frame information and any other
// object file sections that contain register numbers in them.
uint32_t
RegisterContextPOSIX_arm::ConvertRegisterKindToRegisterNumber(lldb::RegisterKind kind,
uint32_t num)
{
const uint32_t num_regs = GetRegisterCount();
assert (kind < lldb::kNumRegisterKinds);
for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx)
{
const lldb_private::RegisterInfo *reg_info = GetRegisterInfoAtIndex (reg_idx);
if (reg_info->kinds[kind] == num)
return reg_idx;
}
return LLDB_INVALID_REGNUM;
}
| 25.10119 | 106 | 0.671093 | [
"object"
] |
02a06d22979ebba54cbf8363ac890f2eece0c6ba | 713 | cpp | C++ | STL/SumHalfEqual.cpp | AbhiSaphire/Codechef.Practice | f671292dad2695e37458866442a6b951ba4e1a71 | [
"MIT"
] | 27 | 2020-05-19T06:46:45.000Z | 2022-02-06T20:29:58.000Z | STL/SumHalfEqual.cpp | AbhiSaphire/Codechef.Practice | f671292dad2695e37458866442a6b951ba4e1a71 | [
"MIT"
] | 1 | 2020-06-23T13:08:08.000Z | 2020-10-06T06:27:15.000Z | STL/SumHalfEqual.cpp | AbhiSaphire/Codechef.Practice | f671292dad2695e37458866442a6b951ba4e1a71 | [
"MIT"
] | 4 | 2020-05-19T06:47:52.000Z | 2021-07-09T02:49:09.000Z | #include <map>
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;
int main(){
int n;
cin>> n;
vector<int> A(n, 0);
long long S = 0;
for (int i=0; i<n; i++) cin>>A[i];
for (int i=0; i<n; i++) S += A[i];
map<int, int> M1, M2;
M1[A[0]] = 1;
for (int i=0; i<n; i++) M2[A[i]]++;
int Sdash = 0;
for (int i=0 ; i<=n; i++){
Sdash += A[i];
if(Sdash == S/2){
cout<<"YES\n";
return 0;
}
if (Sdash < S/2){
long long x = S/2 - Sdash;
if (M2[x] > 0){
cout<<"Yes\n";
return 0;
}
}
else{
long long y = Sdash - S/2;
if(M1[y] > 0){
cout<<"Yes\n";
return 0;
}
}
M1[A[i+1]]++;
M2[A[i+1]]--;
}
cout<<"No\n";
return 0;
}
| 14.26 | 36 | 0.472651 | [
"vector"
] |
02a522b57640a5abc4cf1bc6845faebc3e2a2b56 | 6,856 | hpp | C++ | ColliderBit/include/gambit/ColliderBit/analyses/Cutflow.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | 2 | 2020-09-08T20:05:27.000Z | 2021-04-26T07:57:56.000Z | ColliderBit/include/gambit/ColliderBit/analyses/Cutflow.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | 9 | 2020-10-19T09:56:17.000Z | 2021-05-28T06:12:03.000Z | ColliderBit/include/gambit/ColliderBit/analyses/Cutflow.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | 5 | 2020-09-08T02:23:34.000Z | 2021-03-23T08:48:04.000Z | #pragma once
// GAMBIT: Global and Modular BSM Inference Tool
// *********************************************
/// \file
///
/// The Cutflow and Cutflows classes
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
// #include <cmath>
// #include <cfloat>
// #include <limits>
// #include <algorithm>
namespace Gambit {
namespace ColliderBit {
using namespace std;
/// A tracker of numbers & fractions of events passing sequential cuts
struct Cutflow {
/// @brief Default constructor
///
/// Does nothing! Just to allow storage in STL containers and use as a member variable without using the init list
Cutflow() {}
/// Proper constructor
Cutflow(const string& cfname, const vector<string>& cutnames)
: name(cfname), ncuts(cutnames.size()), cuts(cutnames), counts(ncuts+1, 0)
{ }
/// @brief Fill the pre-cut counter
void fillinit() {
counts[0] += 1;
}
/// @brief Fill the @a {icut}'th post-cut counter, starting at icut=1 for first cut
///
/// @note Returns the cut result to allow 'side-effect' cut-flow filling in an if-statement
bool fill(size_t icut, bool cutresult=true) {
if (cutresult) counts[icut] += 1;
return cutresult;
}
/// @brief Fill all cut-state counters from an Ncut-element results vector
///
/// This function is to be used to fill all of an event's pre- and post-cut
/// state counters at once, including the incoming event counter. It must not be
/// mixed with calls to the @c fill(size_t, bool) and @c fillinit() methods,
/// or double-counting will occur.
///
/// @note Returns the overall cut result to allow 'side-effect' cut-flow filling in an if-statement
bool fill(const vector<bool>& cutresults) {
if (cutresults.size() != ncuts)
throw runtime_error("Number of filled cut results needs to match the Cutflow construction");
counts[0] += 1;
for (size_t i = 0; i < ncuts; ++i) {
if (cutresults[i]) counts[i+1] += 1; else break;
}
for (bool x : cutresults)
if (!x) return false;
return true;
}
/// @brief Fill the N trailing post-cut counters, when supplied with an N-element results vector
///
/// The @a cutresults vector represents the boolean results of the last N cuts. This function
/// allows mixing of cut-flow filling with higher-level analyze() function escapes such as
/// the vetoEvent directive. The initial state (state 0) is not incremented.
///
/// @note Returns the overall cut result to allow 'side-effect' cut-flow filling in an if-statement
bool filltail(const vector<bool>& cutresults) {
if (cutresults.size() > ncuts)
throw runtime_error("Number of filled cut results needs to match the Cutflow construction");
const size_t offset = counts.size() - cutresults.size();
for (size_t i = 0; i < cutresults.size(); ++i) {
if (cutresults[i]) counts[offset+i] += 1; else break;
}
for (bool x : cutresults)
if (!x) return false;
return true;
}
/// Create a string representation
string str() const {
stringstream ss;
ss << name << " cut-flow:";
size_t maxlen = 0;
for (const string& t : cuts) maxlen = max(t.length(), maxlen);
for (size_t i = 0; i <= ncuts; ++i) {
const int pcttot = (counts[0] == 0) ? -1 : round(100*counts[i]/double(counts[0]));
const int pctinc = (i == 0 || counts[i-1] == 0) ? -1 : round(100*counts[i]/double(counts[i-1]));
ss << "\n" << setw(maxlen+5) << left
<< (i == 0 ? "" : "Pass "+cuts[i-1]) << " " << right
<< setw(floor(log10(counts[0]))+1) << counts[i] << " "
<< setw(4) << (pcttot < 0 ? "- " : to_string(pcttot)+"%") << " "
<< setw(4) << (pctinc < 0 ? "- " : to_string(pctinc)+"%");
}
return ss.str();
}
/// Print string representation to a stream
void print(ostream& os) const {
os << str() << flush;
}
string name;
size_t ncuts;
vector<string> cuts;
vector<int> counts;
};
/// Print a Cutflow to a stream
inline ostream& operator << (ostream& os, const Cutflow& cf) {
return os << cf.str();
}
/// A container for several Cutflow objects, with some convenient batch access
struct Cutflows {
/// Do-nothing default constructor
Cutflows() { }
/// Populating constructor
Cutflows(const vector<Cutflow>& cutflows) : cfs(cutflows) { }
/// Append a provided Cutflow to the list
void addCutflow(const Cutflow& cf) {
cfs.push_back(cf);
}
/// Append a newly constructed Cutflow to the list
void addCutflow(const string& cfname, const vector<string>& cutnames) {
cfs.push_back(Cutflow(cfname, cutnames));
}
/// Access the @a i'th Cutflow
Cutflow& operator [] (size_t i) { return cfs[i]; }
/// Access the @a i'th Cutflow (const)
const Cutflow& operator [] (size_t i) const { return cfs[i]; }
/// Access the Cutflow whose name is @a name
Cutflow& operator [] (const string& name) {
for (Cutflow& cf : cfs)
if (cf.name == name) return cf;
throw runtime_error("Requested cut-flow name '" + name + "' does not exist");
}
/// Access the @a i'th Cutflow (const)
const Cutflow& operator [] (const string& name) const {
for (const Cutflow& cf : cfs)
if (cf.name == name) return cf;
throw runtime_error("Requested cut-flow name '" + name + "' does not exist");
}
/// Fill the pre-cuts state counter for all contained Cutflows
void fillinit() {
for (Cutflow& cf : cfs) cf.fillinit();
}
/// @brief Fill the @a {icut}'th post-cut counter for all contained Cutflows, starting at icut=1 for first cut
///
/// @note Returns the cut result to allow 'side-effect' cut-flow filling in an if-statement
bool fill(size_t icut, bool cutresult=true) {
for (Cutflow& cf : cfs) cf.fill(icut, cutresult);
return cutresult;
}
/// Create a string representation
string str() const {
stringstream ss;
for (const Cutflow& cf : cfs)
ss << cf << "\n\n";
return ss.str();
}
/// Print string representation to a stream
void print(ostream& os) const {
os << str() << flush;
}
vector<Cutflow> cfs;
};
/// Print a Cutflows to a stream
inline ostream& operator << (ostream& os, const Cutflows& cfs) {
return os << cfs.str();
}
}
}
| 34.109453 | 120 | 0.577013 | [
"vector"
] |
02ad39c92aff14e6c35d07288cddba6c73c87f13 | 1,249 | hpp | C++ | src/Chromogenics/src/ThermochromicSurface.hpp | bakonyidani/Windows-CalcEngine | afa4c4a9f88199c6206af8bc994a073931fc8b91 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/Chromogenics/src/ThermochromicSurface.hpp | bakonyidani/Windows-CalcEngine | afa4c4a9f88199c6206af8bc994a073931fc8b91 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/Chromogenics/src/ThermochromicSurface.hpp | bakonyidani/Windows-CalcEngine | afa4c4a9f88199c6206af8bc994a073931fc8b91 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #ifndef THERMOCHROMICSURFACE_H
#define THERMOCHROMICSURFACE_H
#include <memory>
#include <vector>
#include "WCETarcog.hpp"
namespace FenestrationCommon
{
class IInterpolation2D;
}
namespace Chromogenics
{
namespace ISO15099 {
class CThermochromicSurface : public Tarcog::ISO15099::ISurface {
public:
CThermochromicSurface( const std::vector< std::pair< double, double>> & t_Emissivity,
const std::vector< std::pair< double, double>> & t_Transmittance );
CThermochromicSurface( double t_Emissivity,
const std::vector< std::pair< double, double>> & t_Transmittance );
CThermochromicSurface( const std::vector< std::pair< double, double>> & t_Emissivity,
double t_Transmittance );
CThermochromicSurface( const CThermochromicSurface & t_Surface );
CThermochromicSurface & operator=( const CThermochromicSurface & t_Surface );
std::shared_ptr< Tarcog::ISO15099::ISurface > clone() const override;
void setTemperature( double t_Temperature ) override;
private:
std::shared_ptr< FenestrationCommon::IInterpolation2D > m_EmissivityInterpolator;
std::shared_ptr< FenestrationCommon::IInterpolation2D > m_TransmittanceInterpolator;
};
}
} // namespace Chromogenics
#endif
| 29.046512 | 88 | 0.745396 | [
"vector"
] |
02b910340fe5ac67890e64db623e00da7326066c | 31,315 | cpp | C++ | AviSynthPlus/plugins/VDubFilter/VDubFilter.cpp | wurui1994/AviSynth | d318f4b455c49a8864c30b3cce84925ebb16c002 | [
"MIT"
] | 1 | 2018-09-27T09:37:42.000Z | 2018-09-27T09:37:42.000Z | AviSynthPlus/plugins/VDubFilter/VDubFilter.cpp | wurui1994/AviSynth | d318f4b455c49a8864c30b3cce84925ebb16c002 | [
"MIT"
] | null | null | null | AviSynthPlus/plugins/VDubFilter/VDubFilter.cpp | wurui1994/AviSynth | d318f4b455c49a8864c30b3cce84925ebb16c002 | [
"MIT"
] | null | null | null | // Avisynth v2.5.
// http://www.avisynth.org
// 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 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit
// http://www.gnu.org/copyleft/gpl.html .
//
// Linking Avisynth statically or dynamically with other modules is making a
// combined work based on Avisynth. Thus, the terms and conditions of the GNU
// General Public License cover the whole combination.
//
// As a special exception, the copyright holders of Avisynth give you
// permission to link Avisynth with independent modules that communicate with
// Avisynth solely through the interfaces defined in avisynth.h, regardless of the license
// terms of these independent modules, and to copy and distribute the
// resulting combined work under terms of your choice, provided that
// every copy of the combined work is accompanied by a complete copy of
// the source code of Avisynth (the version of Avisynth used to produce the
// combined work), being distributed under the terms of the GNU General
// Public License plus this exception. An independent module is a module
// which is not derived from or based on Avisynth, such as 3rd-party filters,
// import and export plugins, or graphical user interfaces.
#include <avisynth.h>
#include <avs/win.h>
#include <avs/minmax.h>
#include <cstdio>
#include <new>
typedef unsigned int Pixel;
typedef unsigned char Pixel8;
typedef int PixCoord; // long in vbitmap.h
typedef int PixDim; // long in vbitmap.h
//typedef int PixOffset; // P.F. 160421 this really broke on 64 bit machines
typedef ptrdiff_t PixOffset; // much better
/********************************************************************
* VirtualDub plugin support
********************************************************************/
// VirtualDub - Video processing and capture application
// Copyright (C) 1998-2000 Avery Lee
//
// 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 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
int GetCPUFlags();
#define VDcall __cdecl
class CScriptValue;
class CScriptValueStringHelper; // char ** helper
struct CScriptObject;
//////////////////// from sylia/ScriptInterpreter.h ////////////////////
class IScriptInterpreter {
public:
virtual void VDcall Destroy() =0;
virtual void VDcall SetRootHandler(void*, void*) =0;
virtual void VDcall ExecuteLine(char *s) =0;
virtual void VDcall ScriptError(int e) =0;
virtual char* VDcall TranslateScriptError(void* cse) =0;
virtual char** VDcall AllocTempString(long l) =0;
virtual CScriptValue VDcall LookupObjectMember(CScriptObject *obj, void *, char *szIdent) = 0;
};
//////////////////// from sylia/ScriptValue.h ////////////////////
class FilterActivation;
typedef void (VDcall *ScriptVoidFunctionPtr)(IScriptInterpreter *, FilterActivation *, CScriptValue *, int);
struct ScriptFunctionDef {
ScriptVoidFunctionPtr func_ptr;
char *name;
char *arg_list;
};
struct CScriptObject {
void* Lookup;
ScriptFunctionDef* func_list;
void* obj_list;
};
class CScriptValue {
public:
enum { T_VOID, T_INT, T_PINT, T_STR, T_ARRAY, T_OBJECT, T_FNAME, T_FUNCTION, T_VARLV, T_LONG, T_DOUBLE} type;
CScriptObject *thisPtr;
// see vdub: vdvideofilt.h
/* fails in x64 + vdub + neatvideo
union {
int i;
char **s;
} u;
void *lpVoid; // in 64 bit, the union is already 8 bytes, this extra helper pointer/padder makes it too big
*/
union {
int i;
char **s;
__int64 l; // in avs n/a
double d; // new type from 160420
} u;
CScriptValue() { type = T_VOID; }
void operator=(int i) { type = T_INT; u.i = i; }
void operator=(char **s) { type = T_STR; u.s = s; }
void operator=(__int64 l) { type = T_LONG; u.l = l; } // not used, only integer exists in avs
void operator=(double d) { type = T_DOUBLE; u.d = d; }
void operator=(float f) { type = T_DOUBLE; u.d = (double)f; }
};
class CScriptValueStringHelper {
public:
void *lpVoid; // char ** helper, introduced for x64, the CScriptValue union is already 8 bytes
};
//////////////////// from VBitmap.h ////////////////////
class VBitmap {
public:
Pixel * data;
Pixel * palette;
int depth;
PixCoord w, h;
PixOffset pitch;
PixOffset modulo;
PixOffset size;
PixOffset offset;
PixOffset PitchAlign4() {
return ((w * depth + 31)/32)*4;
}
PixOffset PitchAlign8() {
return ((w * depth + 63)/64)*8;
}
PixOffset Modulo() {
return pitch - (w*depth+7)/8;
}
PixOffset Size() {
return pitch*h;
}
//////
virtual VBitmap& VDcall init(void *data, PixDim w, PixDim h, int depth) throw();
virtual VBitmap& VDcall init(void *data, BITMAPINFOHEADER *) throw();
virtual void VDcall MakeBitmapHeader(BITMAPINFOHEADER *bih) const throw();
virtual void VDcall AlignTo4() throw();
virtual void VDcall AlignTo8() throw();
virtual void VDcall BitBlt(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy) const;
virtual void VDcall BitBltDither(PixCoord x2, PixCoord y2, const VBitmap *src, PixDim x1, PixDim y1, PixDim dx, PixDim dy, bool to565) const;
virtual void VDcall BitBlt565(PixCoord x2, PixCoord y2, const VBitmap *src, PixDim x1, PixDim y1, PixDim dx, PixDim dy) const;
virtual bool VDcall BitBltXlat1(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const Pixel8 *tbl) const;
virtual bool VDcall BitBltXlat3(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const Pixel32 *tbl) const;
virtual bool VDcall StretchBltNearestFast(PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const VBitmap *src, double x2, double y2, double dx1, double dy1) const;
virtual bool VDcall StretchBltBilinearFast(PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const VBitmap *src, double x2, double y2, double dx1, double dy1) const;
virtual bool VDcall RectFill(PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, Pixel32 c) const;
virtual bool VDcall Histogram(PixCoord x, PixCoord y, PixCoord dx, PixCoord dy, long *pHisto, int iHistoType) const;
//// NEW AS OF VIRTUALDUB V1.2B
virtual bool VDcall BitBltFromYUY2(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy) const;
virtual bool VDcall BitBltFromI420(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy) const;
};
VBitmap& VBitmap::init(void *lpData, BITMAPINFOHEADER *bmih) throw() {
data = (Pixel *)lpData;
palette = (Pixel *)(bmih+1);
depth = bmih->biBitCount;
w = bmih->biWidth;
h = bmih->biHeight;
offset = 0;
AlignTo4();
return *this;
}
VBitmap& VBitmap::init(void *data, PixDim w, PixDim h, int depth) throw() {
this->data = (Pixel32 *)data;
this->palette = NULL;
this->depth = depth;
this->w = w;
this->h = h;
this->offset = 0;
AlignTo8();
return *this;
}
void VBitmap::MakeBitmapHeader(BITMAPINFOHEADER *bih) const throw() {
bih->biSize = sizeof(BITMAPINFOHEADER);
bih->biBitCount = (WORD)depth;
bih->biPlanes = 1;
bih->biCompression = BI_RGB;
if (pitch == ((w*bih->biBitCount + 31)/32) * 4)
bih->biWidth = w;
else
bih->biWidth = LONG(pitch*8 / depth);
bih->biHeight = h;
bih->biSizeImage = DWORD(pitch*h);
bih->biClrUsed = 0;
bih->biClrImportant = 0;
bih->biXPelsPerMeter = 0;
bih->biYPelsPerMeter = 0;
}
void VBitmap::AlignTo4() throw() {
pitch = PitchAlign4();
modulo = Modulo();
size = Size();
}
void VBitmap::AlignTo8() throw() {
pitch = PitchAlign8();
modulo = Modulo();
size = Size();
}
//////////////////// from Filter.h ////////////////////
// This is really dumb, but necessary to support VTbls in C++.
struct FilterVTbls {
void *pvtblVBitmap;
};
//////////////////
enum {
FILTERPARAM_SWAP_BUFFERS = 0x00000001L,
FILTERPARAM_NEEDS_LAST = 0x00000002L,
};
///////////////////
class VFBitmap;
struct FilterFunctions;
typedef int (VDcall *FilterInitProc )(FilterActivation *fa, const FilterFunctions *ff);
typedef void (VDcall *FilterDeinitProc )(FilterActivation *fa, const FilterFunctions *ff);
typedef int (VDcall *FilterRunProc )(const FilterActivation *fa, const FilterFunctions *ff);
typedef long (VDcall *FilterParamProc )(FilterActivation *fa, const FilterFunctions *ff);
typedef int (VDcall *FilterConfigProc )(FilterActivation *fa, const FilterFunctions *ff, HWND hWnd);
typedef void (VDcall *FilterStringProc )(const FilterActivation *fa, const FilterFunctions *ff, char *buf);
typedef int (VDcall *FilterStartProc )(FilterActivation *fa, const FilterFunctions *ff);
typedef int (VDcall *FilterEndProc )(FilterActivation *fa, const FilterFunctions *ff);
typedef bool (VDcall *FilterScriptStrProc)(FilterActivation *fa, const FilterFunctions *, char *, int);
typedef int (VDcall *FilterModuleInitProc)(struct FilterModule *fm, const FilterFunctions *ff, int& vdfd_ver, int& vdfd_compat);
typedef void (VDcall *FilterModuleDeinitProc)(struct FilterModule *fm, const FilterFunctions *ff);
//////////
class IFilterPreview {
public:
virtual void VDcall SetButtonCallback(void*, void*)=0;
virtual void VDcall SetSampleCallback(void*, void*)=0;
virtual bool VDcall isPreviewEnabled()=0;
virtual void VDcall Toggle(HWND)=0;
virtual void VDcall Display(HWND, bool)=0;
virtual void VDcall RedoFrame()=0;
virtual void VDcall RedoSystem()=0;
virtual void VDcall UndoSystem()=0;
virtual void VDcall InitButton(HWND)=0;
virtual void VDcall Close()=0;
virtual bool VDcall SampleCurrentFrame()=0;
virtual long VDcall SampleFrames()=0;
};
//////////
#define VIRTUALDUB_FILTERDEF_VERSION (6)
#define VIRTUALDUB_FILTERDEF_COMPATIBLE (4)
// v3: added lCurrentSourceFrame to FrameStateInfo
// v4 (1.2): lots of additions (VirtualDub 1.2)
// v5 (1.3d): lots of bugfixes - stretchblt bilinear, and non-zero startproc
// v6 (1.4): added error handling functions
class FilterDefinitionList;
typedef struct FilterModule {
struct FilterModule *next, *prev;
HINSTANCE hInstModule;
FilterModuleInitProc initProc;
FilterModuleDeinitProc deinitProc;
IScriptEnvironment* env;
const char* avisynth_function_name;
int preroll;
FilterDefinitionList* fdl;
} FilterModule;
typedef struct FilterDefinition {
struct FilterDefinition *next, *prev;
FilterModule *module;
char * name;
char * desc;
char * maker;
void * private_data;
int inst_data_size;
FilterInitProc initProc;
FilterDeinitProc deinitProc;
FilterRunProc runProc;
FilterParamProc paramProc;
FilterConfigProc configProc;
FilterStringProc stringProc;
FilterStartProc startProc;
FilterEndProc endProc;
CScriptObject *script_obj;
FilterScriptStrProc fssProc;
} FilterDefinition;
class FilterDefinitionList {
public:
FilterModule* fm;
FilterDefinition* fd;
FilterDefinitionList* fdl;
FilterDefinitionList(FilterModule* _fm, FilterDefinition* _fd) : fm(_fm), fd(_fd), fdl(fm->fdl) { };
};
//////////
// FilterStateInfo: contains dynamic info about file being processed
class FilterStateInfo {
public:
long lCurrentFrame; // current sequence frame (previously called output frame)
long lMicrosecsPerFrame; // microseconds per output frame
long lCurrentSourceFrame; // current source frame
long lMicrosecsPerSrcFrame; // microseconds per source frame
long lSourceFrameMS; // source frame timestamp
long lDestFrameMS; // output frame timestamp
};
// VFBitmap: VBitmap extended to hold filter-specific information
class VFBitmap : public VBitmap {
public:
enum {
NEEDS_HDC = 0x00000001L,
};
DWORD dwFlags;
HDC hdc;
};
// FilterActivation: This is what is actually passed to filters at runtime.
class FilterActivation {
public:
FilterDefinition *filter;
void *filter_data;
VFBitmap &dst, &src;
VFBitmap *__reserved0, *const last;
unsigned int x1, y1, x2, y2;
FilterStateInfo *pfsi;
IFilterPreview *ifp;
FilterActivation(VFBitmap& _dst, VFBitmap& _src, VFBitmap *_last) : dst(_dst), src(_src), last(_last) {}
};
struct FilterFunctions {
FilterDefinition *(VDcall *addFilter)(FilterModule *, FilterDefinition *, int fd_len);
void (VDcall *removeFilter)(FilterDefinition *);
bool (VDcall *isFPUEnabled)();
bool (VDcall *isMMXEnabled)();
void (VDcall *InitVTables)(struct FilterVTbls *);
// These functions permit you to throw MyError exceptions from a filter.
// YOU MUST ONLY CALL THESE IN runProc, initProc, and startProc.
void (VDcall *ExceptOutOfMemory)(); // ADDED: V6 (VirtualDub 1.4)
void (VDcall *Except)(const char *format, ...); // ADDED: V6 (VirtualDub 1.4)
long (VDcall *getCPUFlags)(); // ADDED: V6 (VirtualDub 1.4)
};
////////////////////////////////////////////////////////////
// Avisynth doesn't support the following functions.
void VBitmap::BitBlt(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy) const
{
throw AvisynthError("Unsupported VBitmap method: BitBlt");
}
void VBitmap::BitBltDither(PixCoord x2, PixCoord y2, const VBitmap *src, PixDim x1, PixDim y1, PixDim dx, PixDim dy, bool to565) const
{
throw AvisynthError("Unsupported VBitmap method: BitBltDither");
}
void VBitmap::BitBlt565(PixCoord x2, PixCoord y2, const VBitmap *src, PixDim x1, PixDim y1, PixDim dx, PixDim dy) const
{
throw AvisynthError("Unsupported VBitmap method: BitBlt565");
}
bool VBitmap::BitBltXlat1(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const Pixel8 *tbl) const
{
throw AvisynthError("Unsupported VBitmap method: BitBltXlat1");
}
bool VBitmap::BitBltXlat3(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const Pixel32 *tbl) const
{
throw AvisynthError("Unsupported VBitmap method: BitBltXlat3");
}
bool VBitmap::StretchBltNearestFast(PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const VBitmap *src, double x2, double y2, double dx1, double dy1) const
{
throw AvisynthError("Unsupported VBitmap method: StretchBltNearestFast");
}
bool VBitmap::StretchBltBilinearFast(PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, const VBitmap *src, double x2, double y2, double dx1, double dy1) const
{
throw AvisynthError("Unsupported VBitmap method: StretchBltBilinearFast");
}
bool VBitmap::RectFill(PixCoord x1, PixCoord y1, PixDim dx, PixDim dy, Pixel32 c) const
{
throw AvisynthError("Unsupported VBitmap method: RectFill");
}
bool VBitmap::Histogram(PixCoord x, PixCoord y, PixCoord dx, PixCoord dy, long *pHisto, int iHistoType) const
{
throw AvisynthError("Unsupported VBitmap method: Histogram");
}
bool VBitmap::BitBltFromYUY2(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy) const
{
throw AvisynthError("Unsupported VBitmap method: BitBltFromYUY2");
}
bool VBitmap::BitBltFromI420(PixCoord x2, PixCoord y2, const VBitmap *src, PixCoord x1, PixCoord y1, PixDim dx, PixDim dy) const
{
throw AvisynthError("Unsupported VBitmap method: BitBltFromI420");
}
class DummyFilterPreview : public IFilterPreview {
void Die() { throw AvisynthError("IFilterPreview not supported"); }
public:
virtual void VDcall SetButtonCallback(void*, void*) { Die(); }
virtual void VDcall SetSampleCallback(void*, void*) { Die(); }
virtual bool VDcall isPreviewEnabled() { return false; }
virtual void VDcall Toggle(HWND) {}
virtual void VDcall Display(HWND, bool) {}
virtual void VDcall RedoFrame() {}
virtual void VDcall RedoSystem() {}
virtual void VDcall UndoSystem() {}
virtual void VDcall InitButton(HWND) {}
virtual void VDcall Close() {}
virtual bool VDcall SampleCurrentFrame() { return false; }
virtual long VDcall SampleFrames() { return 0; }
};
//////////////////// from Filters.cpp ////////////////////
char exception_conversion_buffer[2048];
static void VDcall FilterThrowExcept(const char *format, ...) {
va_list val;
va_start(val, format);
_vsnprintf(exception_conversion_buffer, sizeof(exception_conversion_buffer)-1, format, val);
va_end(val);
exception_conversion_buffer[sizeof(exception_conversion_buffer)-1] = '\0';
throw AvisynthError(exception_conversion_buffer);
}
static void VDcall FilterThrowExceptMemory() {
throw AvisynthError("VDubFilter: Out of memory.");
}
// This is really disgusting...
#pragma warning( push )
#pragma warning (disable: 4238) // nonstandard extension used : class rvalue used as lvalue
static void VDcall InitVTables(struct FilterVTbls *pvtbls) {
pvtbls->pvtblVBitmap = *(void **)&VBitmap();
}
FilterDefinition *VDcall FilterAdd(FilterModule *fm, FilterDefinition *pfd, int fd_len);
void VDcall FilterRemove(FilterDefinition*) {}
static long VDcall VD_GetCPUFlags() {
return GetCPUFlags();
}
bool VDcall isFPUEnabled() { return !!(GetCPUFlags() & CPUF_FPU); }
bool VDcall isMMXEnabled() { return !!(GetCPUFlags() & CPUF_MMX); }
FilterFunctions g_filterFuncs={
FilterAdd, FilterRemove, isFPUEnabled, isMMXEnabled, InitVTables,
FilterThrowExceptMemory, FilterThrowExcept, VD_GetCPUFlags
};
////////////////////////////////////////////////////////////
class MyScriptInterpreter : public IScriptInterpreter {
IScriptEnvironment* const env;
public:
MyScriptInterpreter(IScriptEnvironment* _env) : env(_env) {}
void VDcall Destroy() {}
void VDcall SetRootHandler(void*, void*) {}
void VDcall ExecuteLine(char *s) {}
void VDcall ScriptError(int e) {
switch (e) {
case 21: env->ThrowError("VirtualdubFilterProxy: OUT_OF_MEMORY");
case 24: env->ThrowError("VirtualdubFilterProxy: FCALL_OUT_OF_RANGE");
case 26: env->ThrowError("VirtualdubFilterProxy: FCALL_UNKNOWN_STR");
default: env->ThrowError("VirtualdubFilterProxy: Unknown error code %d", e);
}
}
char* VDcall TranslateScriptError(void* cse) { return const_cast<char *>(""); }
char** VDcall AllocTempString(long l) { return (char**)0; }
CScriptValue VDcall LookupObjectMember(CScriptObject *obj, void *, char *szIdent) { return CScriptValue(); }
};
class VirtualdubFilterProxy : public GenericVideoFilter {
PVideoFrame src, dst, last;
VFBitmap vbSrc, vbDst, vbLast;
FilterDefinitionList* const fdl;
FilterDefinition* const fd;
FilterStateInfo fsi;
FilterActivation fa;
DummyFilterPreview fp;
int expected_frame_number;
void CallStartProc() {
if (fd->startProc) {
int result = fd->startProc(&fa, &g_filterFuncs);
if (result != 0) {
if (fd->endProc)
fd->endProc(&fa, &g_filterFuncs);
throw AvisynthError("VirtualdubFilterProxy: error calling startProc");
}
}
}
void CallEndProc() {
if (fd->endProc) {
int result = fd->endProc(&fa, &g_filterFuncs);
if (result != 0) {
throw AvisynthError("VirtualdubFilterProxy: error calling endProc");
}
}
}
public:
VirtualdubFilterProxy(PClip _child, FilterDefinitionList* _fdl, AVSValue args, IScriptEnvironment* env)
: GenericVideoFilter(_child), fdl(_fdl), fd(_fdl->fd), fa(vbDst, vbSrc, &vbLast)
{
if (!fd)
env->ThrowError("VirtualdubFilterProxy: No FilterDefinition structure!");
if (!vi.IsRGB32())
throw AvisynthError("VirtualdubFilterProxy: only RGB32 supported for VirtualDub filters");
fa.filter = fd;
fa.pfsi = &fsi;
fa.ifp = &fp;
fa.filter_data = 0;
fsi.lMicrosecsPerFrame = fsi.lMicrosecsPerSrcFrame = MulDiv(vi.fps_denominator, 1000000, vi.fps_numerator);
if (fd->inst_data_size) {
fa.filter_data = new char[fd->inst_data_size];
memset(fa.filter_data, 0, fd->inst_data_size);
if (fd->initProc) {
if (fd->initProc(&fa, &g_filterFuncs) != 0)
throw AvisynthError("VirtualdubFilterProxy: Error calling initProc");
}
if (args.ArraySize() > 1)
InvokeSyliaConfigFunction(fd, args, env);
}
src = env->NewVideoFrame(vi);
SetVFBitmap(src, &vbSrc);
SetVFBitmap(src, &vbLast);
SetVFBitmap(src, &vbDst);
long flags = fd->paramProc ? fd->paramProc(&fa, &g_filterFuncs) : FILTERPARAM_SWAP_BUFFERS;
bool two_buffers = !!(flags & FILTERPARAM_SWAP_BUFFERS);
bool needs_last = !!(flags & FILTERPARAM_NEEDS_LAST);
bool src_needs_hdc = (vbSrc.dwFlags & VFBitmap::NEEDS_HDC);
bool dst_needs_hdc = (vbDst.dwFlags & VFBitmap::NEEDS_HDC);
if (src_needs_hdc || dst_needs_hdc) {
// throw AvisynthError("VirtualdubFilterProxy: HDC not supported");
vbSrc.hdc = vbDst.hdc = vbLast.hdc = GetDC(NULL);
}
if (needs_last) {
last = env->NewVideoFrame(vi);
SetVFBitmap(last, &vbLast);
}
if (two_buffers) {
vi.width = int(vbDst.pitch >> 2);
vi.height = vbDst.h;
dst = env->NewVideoFrame(vi);
SetVFBitmap(dst, &vbDst);
}
CallStartProc();
expected_frame_number = 0;
}
void SetVFBitmap(const PVideoFrame& pvf, VFBitmap* pvb) {
pvb->data = (Pixel*)pvf->GetReadPtr();
pvb->palette = 0;
pvb->depth = 32;
pvb->w = pvf->GetRowSize() >> 2;
pvb->h = pvf->GetHeight();
pvb->pitch = pvf->GetPitch();
pvb->modulo = pvb->Modulo();
pvb->size = pvb->Size();
pvb->offset = 0;
pvb->dwFlags = 0;
pvb->hdc = 0;
}
PVideoFrame FilterFrame(int n, IScriptEnvironment* env, bool in_preroll) {
if (last) {
env->BitBlt(last->GetWritePtr(), last->GetPitch(), src->GetReadPtr(), src->GetPitch(),
last->GetRowSize(), last->GetHeight());
}
{
PVideoFrame _src = child->GetFrame(n, env);
env->BitBlt(src->GetWritePtr(), src->GetPitch(), _src->GetReadPtr(), _src->GetPitch(),
src->GetRowSize(), src->GetHeight());
}
fsi.lCurrentSourceFrame = fsi.lCurrentFrame = n;
fsi.lDestFrameMS = fsi.lSourceFrameMS = MulDiv(n, fsi.lMicrosecsPerFrame, 1000);
fd->runProc(&fa, &g_filterFuncs);
if (in_preroll) {
return 0;
} else {
PVideoFrame _dst = env->NewVideoFrame(vi);
env->BitBlt(_dst->GetWritePtr(), _dst->GetPitch(), (dst?dst:src)->GetReadPtr(),
_dst->GetPitch(), _dst->GetRowSize(), _dst->GetHeight());
return _dst;
}
}
PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env) {
if (n != expected_frame_number) {
CallEndProc();
CallStartProc();
for (int i = min(n, fd->module->preroll); i > 0; i--)
FilterFrame(n-i, env, true);
}
expected_frame_number = n+1;
return FilterFrame(n, env, false);
}
static int ConvertArgs(const AVSValue* args, CScriptValue* sylia_args, CScriptValueStringHelper* sylia_args_string_helper, int count) {
for (int i=0; i<count; ++i) {
if (args[i].IsInt()) {
sylia_args[i] = args[i].AsInt();
} else if (args[i].IsFloat()) { // new from 160420 double support
sylia_args[i] = args[i].AsFloat();
} else if (args[i].IsString()) {
// Oops, where can we put the pointer to pointer in x64? no place in CScriptValue struct
// helper class/struct needed.
sylia_args_string_helper[i].lpVoid = (void*)args[i].AsString();
sylia_args[i] = (char**)&sylia_args_string_helper[i].lpVoid;
/* original, works only for 32 bit
sylia_args[i].lpVoid = (void*)args[i].AsString();
sylia_args[i] = (char**)&sylia_args[i].lpVoid;
*/
} else if (args[i].IsArray()) {
return i+ConvertArgs(&args[i][0], sylia_args+i, sylia_args_string_helper+i, args[i].ArraySize());
} else {
return -1000;
}
}
return count;
}
void InvokeSyliaConfigFunction(FilterDefinition* fd, AVSValue args, IScriptEnvironment* env) {
if (fd->script_obj && fd->script_obj->func_list && args.ArraySize() > 1) {
for (ScriptFunctionDef* i = fd->script_obj->func_list; i->arg_list; i++) {
const char* p = i->arg_list; // p: original virtualdub param list e.g. 0ddddddddd
int j;
for (j=1; j<args.ArraySize(); j++) {
if (p[j] == 'i' && args[j].IsInt()) continue;
else if (p[j] == 'l' && args[j].IsInt()) continue; // param long is only Int in avs
else if (p[j] == 'd' && args[j].IsFloat()) continue; // 160420 type double support
else if (p[j] == 's' && args[j].IsString()) continue;
else if (p[j] == '.' && args[j].IsArray()) continue;
else break;
}
if (j == args.ArraySize() && p[j] == 0) {
// match
MyScriptInterpreter si(env);
CScriptValue sylia_args[30];
CScriptValueStringHelper sylia_args_string_helper[30]; // helper class. x64 char ** helper did not fit into CScriptValue class size
int sylia_arg_count = ConvertArgs(&args[1], sylia_args, sylia_args_string_helper, args.ArraySize()-1);
if (sylia_arg_count < 0)
env->ThrowError("VirtualdubFilterProxy: arguments (after first) must be integers, double and strings only"); // 160420 double
i->func_ptr(&si, &fa, sylia_args, sylia_arg_count);
return;
}
}
env->ThrowError("VirtualdubFilterProxy: no matching config function (this shouldn't happen)");
}
}
~VirtualdubFilterProxy() {
CallEndProc();
FreeFilterModule(fdl->fm);
if (vbSrc.hdc)
ReleaseDC(NULL, vbSrc.hdc);
}
void __cdecl FreeFilterModule(FilterModule* fm) {
for (FilterDefinitionList* fdl = fm->fdl; fdl; fdl = fdl->fdl) {
delete fdl->fd;
fdl->fd = 0;
}
fm->deinitProc(fm, &g_filterFuncs);
FreeLibrary(fm->hInstModule);
if (fm->prev)
fm->prev->next = fm->next;
if (fm->next)
fm->next->prev = fm->prev;
delete fm;
}
static AVSValue __cdecl Create(AVSValue args, void* user_data, IScriptEnvironment* env) {
FilterDefinitionList* fdl = (FilterDefinitionList*)user_data;
return new VirtualdubFilterProxy(args[0].AsClip(), fdl, args, env);
}
};
FilterDefinition *VDcall FilterAdd(FilterModule *fm, FilterDefinition *pfd, int fd_len) {
FilterDefinition *fd = new(std::nothrow) FilterDefinition;
FilterDefinitionList _fdl(fm, fd);
FilterDefinitionList *fdl = (FilterDefinitionList*)fm->env->SaveString((const char*)&_fdl, sizeof(_fdl));
fm->fdl = fdl;
if (fd) {
memcpy(fd, pfd, min(size_t(fd_len), sizeof(FilterDefinition)));
fd->module = fm;
fd->prev = NULL;
fd->next = NULL;
}
const int MAX_PARAMS = 64;
char converted_paramlist[MAX_PARAMS+1];
fm->env->AddFunction(fm->avisynth_function_name, "c", VirtualdubFilterProxy::Create, fdl);
if (fd->script_obj && fd->script_obj->func_list) {
for (ScriptFunctionDef* i = fd->script_obj->func_list; i->arg_list; i++) {
// avisynth does not know 'd'ouble or 'l'ong
// let's fake them to 'f'loat and 'i'nt for avisynth
char *p_src = i->arg_list + 1;
char *p_target = converted_paramlist;
char ch;
while((ch = *p_src++) && (p_target-converted_paramlist)<MAX_PARAMS) {
if (ch == 'd') ch = 'f';
else if (ch == 'l') ch = 'i';
*p_target++ = ch;
}
*p_target = '\0';
const char* params = fm->env->Sprintf("c%s%s", converted_paramlist, strchr(i->arg_list+1, '.') ? "*" : "");
// put * if . found
fm->env->AddFunction(fm->avisynth_function_name, params, VirtualdubFilterProxy::Create, fdl);
}
}
return fd;
}
AVSValue __cdecl LoadVirtualdubPlugin(AVSValue args, void*, IScriptEnvironment* env) {
const char* const szModule = args[0].AsString();
const char* const avisynth_function_name = args[1].AsString();
const int preroll = args[2].AsInt(0);
HMODULE hmodule = LoadLibrary(szModule);
if (!hmodule)
env->ThrowError("LoadVirtualdubPlugin: Error opening \"%s\", error=0x%x", szModule, GetLastError());
FilterModuleInitProc initProc = (FilterModuleInitProc )GetProcAddress(hmodule, "VirtualdubFilterModuleInit2");
FilterModuleDeinitProc deinitProc = (FilterModuleDeinitProc)GetProcAddress(hmodule, "VirtualdubFilterModuleDeinit");
if (!initProc || !deinitProc) {
FreeLibrary(hmodule);
env->ThrowError("LoadVirtualdubPlugin: Module \"%s\" does not contain VirtualDub filters.", szModule);
}
FilterModule* loaded_modules = 0;
try {
loaded_modules = (FilterModule*)env->GetVar("$LoadVirtualdubPlugin$").AsString();
}
catch (IScriptEnvironment::NotFound) {}
for (FilterModule* i = loaded_modules; i; i = i->next) {
if (i->hInstModule == hmodule) {
FreeLibrary(hmodule);
return AVSValue();
}
}
FilterModule* fm = new FilterModule;
fm->hInstModule = hmodule;
fm->initProc = initProc;
fm->deinitProc = deinitProc;
fm->env = env;
fm->avisynth_function_name = avisynth_function_name;
fm->preroll = preroll;
fm->next = loaded_modules;
fm->prev = 0;
fm->fdl = 0;
int ver_hi = VIRTUALDUB_FILTERDEF_VERSION;
int ver_lo = VIRTUALDUB_FILTERDEF_COMPATIBLE;
if (fm->initProc(fm, &g_filterFuncs, ver_hi, ver_lo)) {
// Neuter any AVS functions that may have been created
for (FilterDefinitionList* fdl = fm->fdl; fdl; fdl = fdl->fdl) {
delete fdl->fd;
fdl->fd = 0;
}
FreeLibrary(hmodule);
delete fm;
env->ThrowError("LoadVirtualdubPlugin: Error initializing module \"%s\"", szModule);
}
if (fm->next)
fm->next->prev = fm;
env->SetGlobalVar("$LoadVirtualdubPlugin$", (const char*)fm);
return AVSValue();
}
const AVS_Linkage * AVS_linkage = 0;
extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) {
AVS_linkage = vectors;
// clip, base filename, start, end, image format/extension, info
env->AddFunction("LoadVirtualdubPlugin", "ss[preroll]i", LoadVirtualdubPlugin, 0);
return "`LoadVirtualdubPlugin' Allows to load and use filters written for VirtualDub.";
}
| 34.1494 | 165 | 0.676641 | [
"3d"
] |
02bda58a473e0cfeefe1cddc1fd9d1e3ba42d984 | 9,882 | cpp | C++ | src/elona/mapeditor/design_mode.cpp | ElonaFoobar/ElonaFoobar | 35864685dcca96c4c9ad683c4f5b3537e86bc06f | [
"MIT"
] | 84 | 2018-03-03T02:44:32.000Z | 2019-07-14T16:16:24.000Z | src/elona/mapeditor/design_mode.cpp | ki-foobar/ElonaFoobar | d251cf5bd8c21789db3b56b1c9b1302ce69b2c2e | [
"MIT"
] | 685 | 2018-02-27T04:31:17.000Z | 2019-07-12T13:43:00.000Z | src/elona/mapeditor/design_mode.cpp | ki-foobar/ElonaFoobar | d251cf5bd8c21789db3b56b1c9b1302ce69b2c2e | [
"MIT"
] | 23 | 2019-07-26T08:52:38.000Z | 2021-11-09T09:21:58.000Z | #include "design_mode.hpp"
#include "../audio.hpp"
#include "../character.hpp"
#include "../config.hpp"
#include "../draw.hpp"
#include "../game.hpp"
#include "../i18n.hpp"
#include "../input.hpp"
#include "../map.hpp"
#include "../menu.hpp"
#include "../text.hpp"
#include "../ui.hpp"
#include "../variables.hpp"
#include "undo_history.hpp"
namespace elona
{
extern int cansee;
extern int kdx;
extern int kdy;
namespace mapeditor
{
namespace
{
void prepare_house_board_tiles()
{
std::vector<int> unavailable_tiles{
15, 16, 24, 25, 26, 27, 28, 29, 30, 92, 93, 94, 95, 141,
169, 170, 171, 180, 182, 192, 244, 245, 246, 247, 248, 249, 250, 251,
252, 253, 254, 255, 256, 257, 258, 292, 293, 294, 309, 310, 311, 312,
313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 327, 328,
329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342,
343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356,
372, 373, 374, 375, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409,
410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 422, 431, 432, 433,
434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447,
448, 449, 450, 451, 452, 453, 454, 455};
p = 0;
p(1) = 0;
gsel(2);
for (int cnt = 0; cnt < 2772; ++cnt)
{
bool available{};
if (cnt < 231)
{
available = true;
}
if (cnt >= 396 && cnt < 429)
{
available = true;
}
if (cnt >= 462 && cnt < 495)
{
available = true;
}
if (cnt >= 561 && cnt < 726)
{
available = true;
}
if (!available)
{
continue;
}
if (chip_data[cnt].kind == 2)
{
continue;
}
if (chip_data[cnt].kind == 1)
{
continue;
}
if (chip_data[cnt].kind2 == 5)
{
continue;
}
if (chip_data[cnt].kind == 3)
{
if (game()->home_scale <= 3)
{
continue;
}
else
{
--p(1);
}
}
++p(1);
if (range::find(unavailable_tiles, p(1)) != std::end(unavailable_tiles))
{
continue;
}
list(0, p) = cnt;
++p;
if (chip_data[cnt].anime_frame != 0)
{
cnt = cnt + chip_data[cnt].anime_frame - 1;
continue;
}
}
listmax = p;
gsel(0);
}
void select_house_board_tile()
{
snd("core.pop2");
auto box_size = inf_tiles / 2;
while (1)
{
gmode(0);
p = 0;
// TODO
for (int y = 0; y < 20; ++y)
{
for (int x = 0; x < 33; ++x)
{
if (p < listmax)
{
const auto& chip = chip_data[list(0, p)];
draw_map_tile(
list(0, p),
x * box_size,
y * box_size,
inf_tiles,
inf_tiles,
box_size,
box_size);
if (chip.effect & 4)
{
boxl(
x * box_size,
y * box_size,
box_size,
box_size,
{240, 230, 220});
}
}
++p;
}
}
gmode(2);
redraw();
await(g_config.general_wait());
const auto input = stick();
if (input == StickKey::mouse_left)
{
p = mousex / box_size + mousey / box_size * 33;
if (p >= listmax)
{
snd("core.fail1");
continue;
}
tile = list(0, p);
snd("core.ok1");
house_board_update_screen();
return;
}
if (input == StickKey::mouse_right)
{
house_board_update_screen();
return;
}
}
}
int target_position_homemapmode(UndoHistory& undo_history)
{
tlocx = tlocinitx;
tlocy = tlocinity;
while (1)
{
screenupdate = -1;
update_screen();
dx = (tlocx - scx) * inf_tiles + inf_screenx;
dy = (tlocy - scy) * inf_tiles + inf_screeny;
if (dy + inf_tiles <= windowh - inf_verh)
{
snail::Application::instance().get_renderer().set_blend_mode(
snail::BlendMode::blend);
snail::Application::instance().get_renderer().set_draw_color(
{127, 127, 255, 50});
snail::Application::instance().get_renderer().fill_rect(
dx,
dy * (dy > 0),
inf_tiles -
(dx + inf_tiles > windoww) * (dx + inf_tiles - windoww),
inf_tiles + (dy < 0) * inf_screeny -
(dy + inf_tiles > windowh - inf_verh) *
(dy + inf_tiles - windowh + inf_verh));
}
draw_map_tile(tile, windoww - 80, 20);
txttargetnpc(tlocx, tlocy);
redraw();
auto action = key_check();
if (action == "enter")
{
select_house_board_tile();
wait_key_released();
continue;
}
if (action == "switch_mode")
{
undo_history.undo();
continue;
}
if (action == "identify")
{
undo_history.redo();
continue;
}
const auto input = stick(StickKey::mouse_left | StickKey::mouse_right);
if (input == StickKey::mouse_left)
{
action = "enter";
}
if (input == StickKey::mouse_right)
{
if (chip_data.for_cell(tlocx, tlocy).kind == 2 ||
chip_data.for_cell(tlocx, tlocy).kind == 1)
{
snd("core.fail1");
wait_key_released();
continue;
}
tile = cell_data.at(tlocx, tlocy).chip_id_actual;
snd("core.cursor1");
wait_key_released();
}
tx = clamp(mousex - inf_screenx, 0, windoww) / inf_tiles;
ty = clamp(mousey - inf_screeny, 0, (windowh - inf_verh)) / inf_tiles;
int stat = key_direction(action);
if (stat == 1)
{
cdata.player().position.x += kdx;
cdata.player().position.y += kdy;
if (cdata.player().position.x < 0)
{
cdata.player().position.x = 0;
}
else if (cdata.player().position.x >= map_data.width)
{
cdata.player().position.x = map_data.width - 1;
}
if (cdata.player().position.y < 0)
{
cdata.player().position.y = 0;
}
else if (cdata.player().position.y >= map_data.height)
{
cdata.player().position.y = map_data.height - 1;
}
}
tlocx = clamp(tx + scx, 0, map_data.width - 1);
tlocy = clamp(ty + scy, 0, map_data.height - 1);
if (action == "enter")
{
tlocinitx = 0;
tlocinity = 0;
return cansee;
}
if (action == "cancel")
{
tlocinitx = 0;
tlocinity = 0;
update_screen();
return -1;
}
}
}
void fill_tile(int x, int y, int from, int to)
{
// out of range
if (x < 0 || map_data.width <= x || y < 0 || map_data.height <= y)
return;
if (cell_data.at(x, y).chip_id_actual != from)
return;
if ((chip_data[to].effect & 4) != 0 &&
cell_data.at(x, y).chara_index_plus_one != 0)
return;
// Draw one tile.
cell_data.at(x, y).chip_id_actual = tile;
cell_data.at(x, y).chip_id_memory = tile;
// Draw tiles around.
fill_tile(x - 1, y, from, to);
fill_tile(x + 1, y, from, to);
fill_tile(x, y - 1, from, to);
fill_tile(x, y + 1, from, to);
}
} // namespace
void start_home_map_mode()
{
UndoHistory undo_history;
const auto pc_position_prev = cdata.player().position;
homemapmode = 1;
prepare_house_board_tiles();
Message::instance().linebreak();
txt(i18n::s.get("core.building.home.design.help"));
tlocinitx = cdata.player().position.x;
tlocinity = cdata.player().position.y;
tile = 0;
while (1)
{
await(g_config.general_wait());
int stat = target_position_homemapmode(undo_history);
if (stat == -1)
{
break;
}
if (getkey(snail::Key::ctrl))
{
if (cell_data.at(tlocx, tlocy).chip_id_actual != tile)
{
fill_tile(
tlocx,
tlocy,
cell_data.at(tlocx, tlocy).chip_id_actual,
tile);
}
}
else if (chip_data[tile].effect & 4)
{
undo_history.push_and_execute_command(
make_command<CreateWallCommand>(
tlocx,
tlocy,
cell_data.at(tlocx, tlocy).chip_id_actual,
tile));
}
else
{
undo_history.push_and_execute_command(make_command<PutTileCommand>(
tlocx, tlocy, cell_data.at(tlocx, tlocy).chip_id_actual, tile));
}
tlocinitx = tlocx;
tlocinity = tlocy;
}
homemapmode = 0;
cdata.player().position = pc_position_prev;
}
} // namespace mapeditor
} // namespace elona
| 26.005263 | 80 | 0.452236 | [
"vector"
] |
02c16e089bfa228ae98f17c78fd6f853e1ee8693 | 5,712 | cpp | C++ | Ciao/src/core/App.cpp | dfnzhc/Ciao | 751501b69e9d2eb3e9cf53be07def8989e921b92 | [
"MIT"
] | 1 | 2021-07-15T14:19:27.000Z | 2021-07-15T14:19:27.000Z | Ciao/src/core/App.cpp | dfnzhc/OpenGL-Renderer | 751501b69e9d2eb3e9cf53be07def8989e921b92 | [
"MIT"
] | null | null | null | Ciao/src/core/App.cpp | dfnzhc/OpenGL-Renderer | 751501b69e9d2eb3e9cf53be07def8989e921b92 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "App.h"
#include "render/Camera.h"
#include "render/ImGuiRenderer.h"
#include "render/Mouse.h"
namespace Ciao
{
App::App() : width_(800), height_(600), title_("We eat fish right.")
{
Logger::Init();
glfwSetErrorCallback([](int error, const char* description)
{
CIAO_CORE_ERROR("Error: {}.", description);
});
if (!glfwInit())
{
CIAO_CORE_ERROR("Initialize GLFW Failed.");
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
const GLFWvidmode* info = glfwGetVideoMode(glfwGetPrimaryMonitor());
// width_ = info->width;
// height_ = info->height;
window_ = glfwCreateWindow(width_, height_, title_.c_str(), nullptr, nullptr);
if (!window_)
{
CIAO_CORE_ERROR("Create GLFW window FAILED.");
exit(EXIT_FAILURE);
}
CIAO_CORE_INFO("Create GLFW window SUCCESS!\t-{}x{}.", width_, height_);
glfwSetWindowPos(window_, (info->width - width_) * 0.5f, (info->height - height_) * 0.5f);
//glfwMaximizeWindow(window_);
glfwMakeContextCurrent(window_);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
CIAO_CORE_ERROR("Failed to initialize GLAD");
exit(EXIT_FAILURE);
}
glfwSwapInterval(0);
glDebugMessageCallback(message_callback, nullptr);
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE);
setCallback();
// 初始化鼠标
mouse_ = new Mouse();
mouse_->Init();
imgui_renderer_ = new ImGuiRenderer();
imgui_renderer_->init(window_);
}
App::~App()
{
delete mouse_;
delete imgui_renderer_;
glfwDestroyWindow(window_);
glfwTerminate();
}
void App::swapBuffers()
{
imgui_renderer_->render();
if (!imgui_renderer_->CaptureMouse())
mouse_->Update(window_);
glfwPollEvents();
glfwSwapBuffers(window_);
assert(glGetError() == GL_NO_ERROR);
const double newTimeStamp = glfwGetTime();
deltaSeconds_ = static_cast<float>(newTimeStamp - timeStamp_);
timeStamp_ = newTimeStamp;
}
bool App::beginRender()
{
if (glfwWindowShouldClose(window_))
return false;
glfwGetFramebufferSize(window_, &width_, &height_);
glViewport(0, 0, width_, height_);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
imgui_renderer_->BeginRender();
return true;
}
void App::setCallback()
{
glfwSetScrollCallback(
window_,
[](GLFWwindow* window, double xoffset, double yoffset)
{
if (yoffset > 0)
CameraPositioner_Oribit::zoom(-0.5f);
else if (yoffset < 0)
CameraPositioner_Oribit::zoom(0.5f);
}
);
glfwSetKeyCallback(
window_,
[](GLFWwindow* window, int key, int scancode, int action, int mods)
{
const bool pressed = action != GLFW_RELEASE;
if (key == GLFW_KEY_ESCAPE && pressed)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
);
glfwSetWindowSizeCallback(
window_,
[](GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
);
}
void message_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, GLchar const* message,
void const* user_param)
{
auto const src_str = [source]()
{
switch (source)
{
case GL_DEBUG_SOURCE_API: return "API";
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WINDOW SYSTEM";
case GL_DEBUG_SOURCE_SHADER_COMPILER: return "SHADER COMPILER";
case GL_DEBUG_SOURCE_THIRD_PARTY: return "THIRD PARTY";
case GL_DEBUG_SOURCE_APPLICATION: return "APPLICATION";
case GL_DEBUG_SOURCE_OTHER: return "OTHER";
}
return "";
}();
auto const type_str = [type]()
{
switch (type)
{
case GL_DEBUG_TYPE_ERROR: return "ERROR";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "DEPRECATED_BEHAVIOR";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "UNDEFINED_BEHAVIOR";
case GL_DEBUG_TYPE_PORTABILITY: return "PORTABILITY";
case GL_DEBUG_TYPE_PERFORMANCE: return "PERFORMANCE";
case GL_DEBUG_TYPE_MARKER: return "MARKER";
case GL_DEBUG_TYPE_OTHER: return "OTHER";
}
return "";
}();
auto const severity_str = [severity]()
{
switch (severity)
{
case GL_DEBUG_SEVERITY_NOTIFICATION: return "NOTIFICATION";
case GL_DEBUG_SEVERITY_LOW: return "LOW";
case GL_DEBUG_SEVERITY_MEDIUM: return "MEDIUM";
case GL_DEBUG_SEVERITY_HIGH: return "HIGH";
}
return "";
}();
CIAO_CORE_INFO("{}, {}, {}, {}: {}.", src_str, type_str, severity_str, id, message);
}
}
| 29.905759 | 120 | 0.57493 | [
"render"
] |
02c596d6b6e486127ecdb36e7448c493177fc482 | 3,206 | cpp | C++ | external/glm/test/ext/ext_quaternion_type.cpp | diabl0-NEMESIS/enigma-android | 6768df01003254245de660a0b9593f54a113e49d | [
"MIT"
] | 83 | 2019-09-18T16:14:43.000Z | 2022-03-22T05:56:43.000Z | external/glm/test/ext/ext_quaternion_type.cpp | diabl0-NEMESIS/enigma-android | 6768df01003254245de660a0b9593f54a113e49d | [
"MIT"
] | 180 | 2022-01-27T15:25:15.000Z | 2022-03-30T13:41:12.000Z | external/glm/test/ext/ext_quaternion_type.cpp | diabl0-NEMESIS/enigma-android | 6768df01003254245de660a0b9593f54a113e49d | [
"MIT"
] | 7 | 2018-12-07T01:51:12.000Z | 2021-12-01T15:56:37.000Z | #include <glm/gtc/constants.hpp>
#include <glm/ext/quaternion_relational.hpp>
#include <glm/ext/quaternion_float.hpp>
#include <glm/ext/quaternion_float_precision.hpp>
#include <glm/ext/quaternion_double.hpp>
#include <glm/ext/quaternion_double_precision.hpp>
#include <glm/ext/vector_float3.hpp>
#include <vector>
static int test_ctr()
{
int Error(0);
# if GLM_HAS_TRIVIAL_QUERIES
// Error += std::is_trivially_default_constructible<glm::quat>::value ? 0 : 1;
// Error += std::is_trivially_default_constructible<glm::dquat>::value ? 0 : 1;
// Error += std::is_trivially_copy_assignable<glm::quat>::value ? 0 : 1;
// Error += std::is_trivially_copy_assignable<glm::dquat>::value ? 0 : 1;
Error += std::is_trivially_copyable<glm::quat>::value ? 0 : 1;
Error += std::is_trivially_copyable<glm::dquat>::value ? 0 : 1;
Error += std::is_copy_constructible<glm::quat>::value ? 0 : 1;
Error += std::is_copy_constructible<glm::dquat>::value ? 0 : 1;
# endif
# if GLM_HAS_INITIALIZER_LISTS
{
glm::quat A{0, 1, 2, 3};
std::vector<glm::quat> B{
{0, 1, 2, 3},
{0, 1, 2, 3}};
}
# endif//GLM_HAS_INITIALIZER_LISTS
return Error;
}
static int test_two_axis_ctr()
{
int Error = 0;
glm::quat const q1(glm::vec3(1, 0, 0), glm::vec3(0, 1, 0));
glm::vec3 const v1 = q1 * glm::vec3(1, 0, 0);
Error += glm::all(glm::equal(v1, glm::vec3(0, 1, 0), 0.0001f)) ? 0 : 1;
glm::quat const q2 = q1 * q1;
glm::vec3 const v2 = q2 * glm::vec3(1, 0, 0);
Error += glm::all(glm::equal(v2, glm::vec3(-1, 0, 0), 0.0001f)) ? 0 : 1;
glm::quat const q3(glm::vec3(1, 0, 0), glm::vec3(-1, 0, 0));
glm::vec3 const v3 = q3 * glm::vec3(1, 0, 0);
Error += glm::all(glm::equal(v3, glm::vec3(-1, 0, 0), 0.0001f)) ? 0 : 1;
glm::quat const q4(glm::vec3(0, 1, 0), glm::vec3(0, -1, 0));
glm::vec3 const v4 = q4 * glm::vec3(0, 1, 0);
Error += glm::all(glm::equal(v4, glm::vec3(0, -1, 0), 0.0001f)) ? 0 : 1;
glm::quat const q5(glm::vec3(0, 0, 1), glm::vec3(0, 0, -1));
glm::vec3 const v5 = q5 * glm::vec3(0, 0, 1);
Error += glm::all(glm::equal(v5, glm::vec3(0, 0, -1), 0.0001f)) ? 0 : 1;
return Error;
}
static int test_size()
{
int Error = 0;
std::size_t const A = sizeof(glm::quat);
Error += 16 == A ? 0 : 1;
std::size_t const B = sizeof(glm::dquat);
Error += 32 == B ? 0 : 1;
Error += glm::quat().length() == 4 ? 0 : 1;
Error += glm::dquat().length() == 4 ? 0 : 1;
Error += glm::quat::length() == 4 ? 0 : 1;
Error += glm::dquat::length() == 4 ? 0 : 1;
return Error;
}
static int test_precision()
{
int Error = 0;
Error += sizeof(glm::lowp_quat) <= sizeof(glm::mediump_quat) ? 0 : 1;
Error += sizeof(glm::mediump_quat) <= sizeof(glm::highp_quat) ? 0 : 1;
return Error;
}
static int test_constexpr()
{
#if GLM_HAS_CONSTEXPR
static_assert(glm::quat::length() == 4, "GLM: Failed constexpr");
static_assert(glm::quat(1.0f, glm::vec3(0.0f)).w > 0.0f, "GLM: Failed constexpr");
#endif
return 0;
}
int main()
{
int Error = 0;
Error += test_ctr();
Error += test_two_axis_ctr();
Error += test_size();
Error += test_precision();
Error += test_constexpr();
return Error;
}
| 28.122807 | 84 | 0.602932 | [
"vector"
] |
02c9e185c90b6529fb429a070e888ea820573b80 | 5,206 | cpp | C++ | test/StringTest.cpp | shift-left-test/sentinel | 64f401ead35ad564badedfd0956414a6d148077e | [
"MIT-0",
"MIT"
] | null | null | null | test/StringTest.cpp | shift-left-test/sentinel | 64f401ead35ad564badedfd0956414a6d148077e | [
"MIT-0",
"MIT"
] | null | null | null | test/StringTest.cpp | shift-left-test/sentinel | 64f401ead35ad564badedfd0956414a6d148077e | [
"MIT-0",
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 LG Electronics Inc.
* SPDX-License-Identifier: MIT
*/
#include <gtest/gtest.h>
#include <string>
#include "sentinel/util/string.hpp"
namespace sentinel {
class StringTest : public ::testing::Test {
};
static constexpr const char* SPACE_HELLO_WORLD_SPACE = " HELLO WORLD ";
static constexpr const char* SPACE_HELLO_WORLD = " HELLO WORLD";
static constexpr const char* HELLO_HELLO = "HELLO HELLO";
static constexpr const char* HELLO_WORLD_SPACE = "HELLO WORLD ";
static constexpr const char* HELLO_WORLD = "HELLO WORLD";
static constexpr const char* hello_world = "hello world";
static constexpr const char* HELLO = "HELLO";
static constexpr const char* WORLD = "WORLD";
static constexpr const char* WORLD_WORLD = "WORLD WORLD";
static constexpr const char* SPACE = " ";
static constexpr const char* BLANK = "";
TEST_F(StringTest, testStartsWithReturnTrueWhenValidArgsGiven) {
EXPECT_TRUE(string::startsWith(HELLO_WORLD, HELLO_WORLD));
EXPECT_TRUE(string::startsWith(HELLO_WORLD, HELLO));
EXPECT_TRUE(string::startsWith(HELLO_WORLD, BLANK));
EXPECT_TRUE(string::startsWith(SPACE, SPACE));
EXPECT_TRUE(string::startsWith(BLANK, BLANK));
}
TEST_F(StringTest, testStartsWithReturnFalseWhenInvalidArgsGiven) {
EXPECT_FALSE(string::startsWith(HELLO_WORLD, WORLD));
EXPECT_FALSE(string::startsWith(HELLO_WORLD, SPACE));
EXPECT_FALSE(string::startsWith(HELLO, WORLD));
}
TEST_F(StringTest, testEndsWithReturnTrueWhenValidArgsGiven) {
EXPECT_TRUE(string::endsWith(HELLO_WORLD, HELLO_WORLD));
EXPECT_TRUE(string::endsWith(HELLO_WORLD, WORLD));
EXPECT_TRUE(string::endsWith(HELLO_WORLD, BLANK));
EXPECT_TRUE(string::endsWith(SPACE, SPACE));
EXPECT_TRUE(string::endsWith(BLANK, BLANK));
}
TEST_F(StringTest, testEndsWithReturnFalseWhenInvalidArgsGiven) {
EXPECT_FALSE(string::endsWith(HELLO_WORLD, HELLO));
EXPECT_FALSE(string::endsWith(HELLO_WORLD, SPACE));
EXPECT_FALSE(string::endsWith(HELLO, WORLD));
}
TEST_F(StringTest, testLtrimShouldTrimLeadingWhitespaces) {
EXPECT_STREQ(HELLO_WORLD, string::ltrim(SPACE_HELLO_WORLD).c_str());
EXPECT_STREQ(HELLO_WORLD, string::ltrim(HELLO_WORLD).c_str());
EXPECT_STREQ(BLANK, string::ltrim(SPACE).c_str());
EXPECT_STREQ(BLANK, string::ltrim(BLANK).c_str());
}
TEST_F(StringTest, testLtrimShouldNotTrimTrailingWhitespaces) {
EXPECT_STRNE(HELLO_WORLD, string::ltrim(HELLO_WORLD_SPACE).c_str());
}
TEST_F(StringTest, testRtrimShouldTrimTrailingWhitespaces) {
EXPECT_STREQ(HELLO_WORLD, string::rtrim(HELLO_WORLD_SPACE).c_str());
EXPECT_STREQ(HELLO_WORLD, string::rtrim(HELLO_WORLD).c_str());
EXPECT_STREQ(BLANK, string::rtrim(SPACE).c_str());
EXPECT_STREQ(BLANK, string::rtrim(BLANK).c_str());
}
TEST_F(StringTest, testRtrimShouldNotTrimLeadingWhitespaces) {
EXPECT_STRNE(HELLO_WORLD, string::rtrim(SPACE_HELLO_WORLD).c_str());
}
TEST_F(StringTest, testTrimShouldTrimLeadingAndTrailingWhitespaces) {
EXPECT_STREQ(HELLO_WORLD,
string::trim(SPACE_HELLO_WORLD_SPACE).c_str());
EXPECT_STREQ(HELLO_WORLD, string::trim(SPACE_HELLO_WORLD).c_str());
EXPECT_STREQ(HELLO_WORLD, string::trim(HELLO_WORLD_SPACE).c_str());
EXPECT_STREQ(BLANK, string::trim(SPACE).c_str());
EXPECT_STREQ(BLANK, string::trim(BLANK).c_str());
}
TEST_F(StringTest, testContainsReturnTrueWhenValidArgsGiven) {
EXPECT_TRUE(string::contains(SPACE_HELLO_WORLD_SPACE, HELLO_WORLD));
EXPECT_TRUE(string::contains(HELLO_WORLD, HELLO));
EXPECT_TRUE(string::contains(HELLO_WORLD, WORLD));
EXPECT_TRUE(string::contains(HELLO_WORLD, SPACE));
EXPECT_TRUE(string::contains(HELLO_WORLD, BLANK));
}
TEST_F(StringTest, testContainsReturnFalseWhenInvalidArgsGiven) {
EXPECT_FALSE(string::contains(HELLO_WORLD, SPACE_HELLO_WORLD_SPACE));
EXPECT_FALSE(string::contains(HELLO_WORLD, hello_world));
EXPECT_FALSE(string::contains(HELLO, WORLD));
EXPECT_FALSE(string::contains(SPACE, HELLO_WORLD));
EXPECT_FALSE(string::contains(BLANK, HELLO_WORLD));
}
TEST_F(StringTest, testSplitReturnSplittedTokens) {
std::vector<std::string> expected = { HELLO, WORLD };
EXPECT_EQ(expected, string::split(HELLO_WORLD));
}
TEST_F(StringTest, testSplitByStringDeliReturnSplittedTokens) {
std::vector<std::string> expected = { HELLO, "ORLD" };
EXPECT_EQ(expected, string::split(HELLO_WORLD, " W"));
}
TEST_F(StringTest, testJoinReturnJoinedCharactersWhenVectorStrGiven) {
std::vector<std::string> input = { HELLO, WORLD };
EXPECT_STREQ(HELLO_WORLD, string::join(SPACE, input).c_str());
}
TEST_F(StringTest, testJoinReturnJoinedCharactersWhenVariadicArgsGiven) {
EXPECT_STREQ("a", string::join("", "a").c_str());
EXPECT_STREQ("ab", string::join("", "a", "b").c_str());
EXPECT_STREQ("abc", string::join("", "a", "b", "c").c_str());
}
TEST_F(StringTest, testReplaceAll) {
EXPECT_STREQ(BLANK, string::replaceAll(BLANK, BLANK, "b").c_str());
EXPECT_STREQ(BLANK, string::replaceAll(WORLD, WORLD, BLANK).c_str());
EXPECT_STREQ(WORLD, string::replaceAll(WORLD, "A", "B").c_str());
EXPECT_STREQ(HELLO_HELLO, string::replaceAll(
HELLO_WORLD, WORLD, HELLO).c_str());
EXPECT_STREQ(HELLO_HELLO, string::replaceAll(
WORLD_WORLD, WORLD, HELLO).c_str());
}
} // namespace sentinel
| 38.562963 | 73 | 0.761813 | [
"vector"
] |
c49bdb202a92deba48fda0b8afab9ef7da14eeca | 4,154 | cc | C++ | backend/simulator/agent_gprt/src/ag_needs_handler.cc | aislab-hevs/seamless | d222e272fee4cc1a4166660074633715e01f7a19 | [
"BSD-3-Clause"
] | null | null | null | backend/simulator/agent_gprt/src/ag_needs_handler.cc | aislab-hevs/seamless | d222e272fee4cc1a4166660074633715e01f7a19 | [
"BSD-3-Clause"
] | 1 | 2021-05-11T22:01:55.000Z | 2021-05-11T22:01:55.000Z | backend/simulator/agent_gprt/src/ag_needs_handler.cc | aislab-hevs/seamless | d222e272fee4cc1a4166660074633715e01f7a19 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020, HES-SO Valais-Wallis (https://www.hevs.ch)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <fstream>
#include "../headers/ag_needs_handler.h"
#include "../headers/json.hpp"
using namespace omnetpp;
using namespace std;
using json = nlohmann::json;
NeedsHandler::~NeedsHandler() {
if (!ag_needs_vector.empty()) {
for (auto need : ag_needs_vector) {
delete need;
}
ag_needs_vector.clear();
}
}
void NeedsHandler::read_needs_from_json(string path, int demander) {
ifstream i(path.c_str());
if (!i.fail()) {
json needs;
i >> needs;
int need_id = 0;
string id = to_string(demander);
for (const auto& need : needs[id]) {
vector<string> ids = need["neededTasks"];
double need_R = stod(need["releaseTime"].get<string>());
double needed_t_R = stod(need["neededTaskRelease"].get<string>());
double needed_t_ddl = stod(need["neededTaskDeadline"].get<string>());
int needed_t_n_exec = stoi(need["neededTaskNExec"].get<string>());
double needed_timeout = stod(need["neededTimeout"].get<string>());
double needed_t_min = -1;
double needed_t_max = -1;
if(need.find("neededTaskTMin") != need.end()) needed_t_min = stod(need["neededTaskTMin"].get<string>());
if(need.find("neededTaskTMax") != need.end()) needed_t_max = stod(need["neededTaskTMax"].get<string>());
vector<int> needed_tasks_ids;
for(auto id : ids){
needed_tasks_ids.push_back(stoi(id));
}
Need *new_need = new Need(need_id, need_R, needed_tasks_ids,
needed_t_R, needed_t_ddl, needed_t_n_exec, needed_timeout,
needed_t_min, needed_t_max);
ag_needs_vector.push_back(new_need);
need_id++; // auto-increment need id
}
} else {
//note: we can stop the simulation or not!
// EV_ERROR << "Cannot find root node" << endl;
// throw std::runtime_error("Could not open file");
EV_WARN << "Needs not found! Continuing the simulation...\n";
}
}
vector<Need*> NeedsHandler::get_needs_vector() {
return ag_needs_vector;
}
//TODO upgrade with find_if
Need* NeedsHandler::get_need_by_id(int p_need_id) {
Need *p_need;
int i = 0;
bool found = false;
while ((!found) && (i < ag_needs_vector.size())) {
if (ag_needs_vector[i]->get_need_id() == p_need_id) {
p_need = ag_needs_vector[i];
found = true;
}
i++;
}
return p_need;
}
| 39.188679 | 116 | 0.65792 | [
"vector"
] |
c49c023dfbe70ea6e4318f69fe67ec8791c90b78 | 335 | hpp | C++ | include/ActuationSystem.hpp | CaptCrunch333/positioning_system | 62da7f2773dae9a66f3e89d6134453fba526bb11 | [
"BSD-3-Clause"
] | null | null | null | include/ActuationSystem.hpp | CaptCrunch333/positioning_system | 62da7f2773dae9a66f3e89d6134453fba526bb11 | [
"BSD-3-Clause"
] | null | null | null | include/ActuationSystem.hpp | CaptCrunch333/positioning_system | 62da7f2773dae9a66f3e89d6134453fba526bb11 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "MsgEmitter.hpp"
#include "MsgReceiver.hpp"
#include "ControlSystemMessage.hpp"
#include "Actuator.hpp"
#include <vector>
class ActuationSystem : public msg_emitter, public msg_receiver{
public:
virtual void receive_msg_data(DataMessage* t_msg) = 0;
ActuationSystem(std::vector<Actuator*>) {};
}; | 20.9375 | 64 | 0.743284 | [
"vector"
] |
c49c73af7c31e703e7e68e80cd70647e258ded30 | 2,043 | cpp | C++ | depends/sdk/src/external_tool.cpp | sergeyrachev/neuon | 71db22ac607cdd14ad51678b437d70ff08395a28 | [
"MIT"
] | 9 | 2018-06-06T03:00:59.000Z | 2022-01-22T19:44:32.000Z | src/external_tool.cpp | sergeyrachev/mementor | 91efdd9237f2ee0460a6ea9ca8fd587718e33139 | [
"MIT"
] | null | null | null | src/external_tool.cpp | sergeyrachev/mementor | 91efdd9237f2ee0460a6ea9ca8fd587718e33139 | [
"MIT"
] | null | null | null | #include "external_tool.h"
#include <algorithm>
#include <iterator>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <boost/asio.hpp>
using namespace posix;
external_tool_t::external_tool_t(const std::string &exec)
: exec(exec)
{
}
external_tool_t::exit_status_t external_tool_t::execute(const std::vector<std::string> &args, int pipe) {
exit_status_t ret{};
int status(0);
child_pid = fork();
if (child_pid_error == *child_pid) {
ret.code = -1;
} else if (child_pid_default == *child_pid) {
dup2(pipe, STDOUT_FILENO);
dup2(pipe, STDERR_FILENO);
close(pipe);
auto argv = arguments(exec, args);
// Never returns in case of success, exit child process in case of failure
// Be aware - we cast pointer to const value to const pointer to value;
// it would be nice to have non-const allocated memory to avoid explicit const_cast
execve(exec.c_str(), const_cast<char *const *>(argv.data()), nullptr);
exit(errno);
} else if (*child_pid) {
bool is_waiting(true);
do {
waitpid(*child_pid, &status, WUNTRACED | WCONTINUED);
if (WIFEXITED(status)) {
is_waiting = false;
ret.code = WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
is_waiting = false;
ret.has_terminated = true;
ret.code = WTERMSIG(status);
}
} while (is_waiting);
}
return ret;
}
void external_tool_t::interrupt() const {
if( child_pid ){
kill(*child_pid, SIGINT);
}
}
std::vector<const char *> external_tool_t::arguments(const std::string& exec, const std::vector <std::string> &args) {
std::vector<const char *> argv;
argv.push_back(exec.c_str());
std::transform(args.begin(), args.end(), std::back_inserter(argv), [](const std::string &s) {
return s.c_str();
});
argv.push_back(nullptr);
return argv;
}
| 27.608108 | 118 | 0.60744 | [
"vector",
"transform"
] |
c49ce4c16a5d95b06dace587024c3d6ec1fb267e | 1,620 | cpp | C++ | src/student/particles.cpp | PaperbagLife/MyScotty3D | 1f7849aa03e7dc1cbb641cd658dad26848786776 | [
"MIT"
] | 1 | 2022-02-03T17:24:04.000Z | 2022-02-03T17:24:04.000Z | src/student/particles.cpp | PaperbagLife/MyScotty3D | 1f7849aa03e7dc1cbb641cd658dad26848786776 | [
"MIT"
] | null | null | null | src/student/particles.cpp | PaperbagLife/MyScotty3D | 1f7849aa03e7dc1cbb641cd658dad26848786776 | [
"MIT"
] | null | null | null |
#include "../scene/particles.h"
#include "../rays/pathtracer.h"
bool Scene_Particles::Particle::update(const PT::Object& scene, float dt, float radius) {
// TODO(Animation): Task 4
// Compute the trajectory of this particle for the next dt seconds.
// (1) Build a ray representing the particle's path if it travelled at constant velocity.
// (2) Intersect the ray with the scene and account for collisions. Be careful when placing
// collision points using the particle radius. Move the particle to its next position.
// (3) Account for acceleration due to gravity.
// (4) Repeat until the entire time step has been consumed.
// (5) Decrease the particle's age and return whether it should die.
while (dt > 0.0f) {
Ray ray = Ray(pos, velocity);
PT::Trace trace = scene.hit(ray);
float costheta = dot(trace.normal, -velocity)/(velocity.norm()*trace.normal.norm());
float theta = acos(costheta);
float extendX = fabsf(tan(theta) * radius);
if (!trace.hit || trace.distance > velocity.norm()*dt + extendX ) {
pos += velocity * dt;
velocity += acceleration * dt;
age -= dt;
return age > 0.0f;
}
// hit
float hitTime = (trace.distance - extendX)/velocity.norm();
if(trace.distance - extendX > 0.0f) {
pos += velocity * hitTime;
}
velocity = 2.0f*(dot(trace.normal, -velocity)*trace.normal) + velocity;
velocity += acceleration * hitTime;
dt -= hitTime;
age -= hitTime;
}
return age > 0.0f;
}
| 36 | 95 | 0.609259 | [
"object"
] |
c4a14419d7733ac8eb1da5d853e3c4b64032de8d | 10,848 | cc | C++ | components/autofill/core/common/autofill_features.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/core/common/autofill_features.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/core/common/autofill_features.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 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/autofill/core/common/autofill_features.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/autofill/core/common/autofill_prefs.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/prefs/pref_service.h"
#include "ui/base/l10n/l10n_util.h"
namespace autofill {
namespace features {
// Controls whether the AddressNormalizer is supplied. If available, it may be
// used to normalize address and will incur fetching rules from the server.
const base::Feature kAutofillAddressNormalizer{
"AutofillAddressNormalizer", base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether autofill activates on non-HTTP(S) pages. Useful for
// automated with data URLS in cases where it's too difficult to use the
// embedded test server. Generally avoid using.
const base::Feature kAutofillAllowNonHttpActivation{
"AutofillAllowNonHttpActivation", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillAlwaysFillAddresses{
"AlwaysFillAddresses", base::FEATURE_ENABLED_BY_DEFAULT};
// Controls the use of GET (instead of POST) to fetch cacheable autofill query
// responses.
const base::Feature kAutofillCacheQueryResponses{
"AutofillCacheQueryResponses", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kAutofillCreateDataForTest{
"AutofillCreateDataForTest", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillCreditCardAssist{
"AutofillCreditCardAssist", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether we download server credit cards to the ephemeral
// account-based storage when sync the transport is enabled.
const base::Feature kAutofillEnableAccountWalletStorage{
"AutofillEnableAccountWalletStorage",
#if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
// Wallet transport is only currently available on Win/Mac/Linux.
// (Somehow, swapping this check makes iOS unhappy?)
base::FEATURE_DISABLED_BY_DEFAULT
#else
base::FEATURE_ENABLED_BY_DEFAULT
#endif
};
// Controls whether we use COMPANY as part of Autofill
const base::Feature kAutofillEnableCompanyName{
"AutofillEnableCompanyName", base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether we show "Hide suggestions" item in the suggestions menu.
const base::Feature kAutofillEnableHideSuggestionsUI{
"AutofillEnableHideSuggestionsUI", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether or not a minimum number of fields is required before
// heuristic field type prediction is run for a form.
const base::Feature kAutofillEnforceMinRequiredFieldsForHeuristics{
"AutofillEnforceMinRequiredFieldsForHeuristics",
base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether or not a minimum number of fields is required before
// crowd-sourced field type predictions are queried for a form.
const base::Feature kAutofillEnforceMinRequiredFieldsForQuery{
"AutofillEnforceMinRequiredFieldsForQuery",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether or not a minimum number of fields is required before
// field type votes are uploaded to the crowd-sourcing server.
const base::Feature kAutofillEnforceMinRequiredFieldsForUpload{
"AutofillEnforceMinRequiredFieldsForUpload",
base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, autofill suggestions are displayed in the keyboard accessory
// instead of the regular popup.
const base::Feature kAutofillKeyboardAccessory{
"AutofillKeyboardAccessory", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillPruneSuggestions{
"AutofillPruneSuggestions", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillMetadataUploads{"AutofillMetadataUploads",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillOffNoServerData{"AutofillOffNoServerData",
base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, autofill server will override field types with rater
// consensus data before returning to client.
const base::Feature kAutofillOverrideWithRaterConsensus{
"AutofillOverrideWithRaterConsensus", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillPreferServerNamePredictions{
"AutofillPreferServerNamePredictions", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillProfileClientValidation{
"AutofillProfileClientValidation", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether Autofill uses server-side validation to ensure that fields
// with invalid data are not suggested.
const base::Feature kAutofillProfileServerValidation{
"AutofillProfileServerValidation", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether autofill rejects using non-verified company names that are
// in the format of a birthyear.
const base::Feature kAutofillRejectCompanyBirthyear{
"AutofillRejectCompanyBirthyear", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether autofill rejects using non-verified company names that are
// social titles (e.g., "Mrs.") in some languages.
const base::Feature kAutofillRejectCompanySocialTitle{
"AutofillRejectCompanySocialTitle", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether or not a group of fields not enclosed in a form can be
// considered a form. If this is enabled, unowned fields will only constitute
// a form if there are signals to suggest that this might a checkout page.
const base::Feature kAutofillRestrictUnownedFieldsToFormlessCheckout{
"AutofillRestrictUnownedFieldsToFormlessCheckout",
base::FEATURE_DISABLED_BY_DEFAULT};
// On Canary and Dev channels only, this feature flag instructs chrome to send
// rich form/field metadata with queries. This will trigger the use of richer
// field-type predictions model on the server, for testing/evaluation of those
// models prior to a client-push.
const base::Feature kAutofillRichMetadataQueries{
"AutofillRichMetadataQueries", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether UPI/VPA values will be saved and filled into payment forms.
const base::Feature kAutofillSaveAndFillVPA{"AutofillSaveAndFillVPA",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillSaveOnProbablySubmitted{
"AutofillSaveOnProbablySubmitted", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables or Disables (mostly for hermetic testing) autofill server
// communication. The URL of the autofill server can further be controlled via
// the autofill-server-url param. The given URL should specify the complete
// autofill server API url up to the parent "directory" of the "query" and
// "upload" resources.
// i.e., https://other.autofill.server:port/tbproxy/af/
const base::Feature kAutofillServerCommunication{
"AutofillServerCommunication", base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether autofill suggestions are filtered by field values previously
// filled by website.
const base::Feature kAutofillShowAllSuggestionsOnPrefilledForms{
"AutofillShowAllSuggestionsOnPrefilledForms",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether we show warnings in the Dev console for misused autocomplete
// types.
const base::Feature kAutofillShowAutocompleteConsoleWarnings{
"AutofillShowAutocompleteConsoleWarnings",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls attaching the autofill type predictions to their respective
// element in the DOM.
const base::Feature kAutofillShowTypePredictions{
"AutofillShowTypePredictions", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether inferred label is considered for comparing in
// FormFieldData.SimilarFieldAs.
const base::Feature kAutofillSkipComparingInferredLabels{
"AutofillSkipComparingInferredLabels", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether Autofill should search prefixes of all words/tokens when
// filtering profiles, or only on prefixes of the whole string.
const base::Feature kAutofillTokenPrefixMatching{
"AutofillTokenPrefixMatching", base::FEATURE_DISABLED_BY_DEFAULT};
// Enables the touch to fill feature for Android.
const base::Feature kAutofillTouchToFill = {"TouchToFillAndroid",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAutofillUploadThrottling{"AutofillUploadThrottling",
base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether to use the API or use the legacy server.
const base::Feature kAutofillUseApi{"AutofillUseApi",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether suggestions' labels use the improved label disambiguation
// format.
const base::Feature kAutofillUseImprovedLabelDisambiguation{
"AutofillUseImprovedLabelDisambiguation",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether or not autofill utilizes the country code from the Chrome
// variation service. The country code is used for determining the address
// requirements for address profile creation and as source for a default country
// used in a new address profile.
const base::Feature kAutofillUseVariationCountryCode{
"AutofillUseVariationCountryCode", base::FEATURE_DISABLED_BY_DEFAULT};
#if defined(OS_ANDROID)
// Controls whether the Autofill manual fallback for Addresses and Payments is
// present on Android.
const base::Feature kAutofillManualFallbackAndroid{
"AutofillManualFallbackAndroid", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether to use modernized style for the Autofill dropdown.
const base::Feature kAutofillRefreshStyleAndroid{
"AutofillRefreshStyleAndroid", base::FEATURE_DISABLED_BY_DEFAULT};
#endif // OS_ANDROID
#if defined(OS_ANDROID) || defined(OS_IOS)
const base::Feature kAutofillUseMobileLabelDisambiguation{
"AutofillUseMobileLabelDisambiguation", base::FEATURE_DISABLED_BY_DEFAULT};
const char kAutofillUseMobileLabelDisambiguationParameterName[] = "variant";
const char kAutofillUseMobileLabelDisambiguationParameterShowAll[] = "show-all";
const char kAutofillUseMobileLabelDisambiguationParameterShowOne[] = "show-one";
#endif // defined(OS_ANDROID) || defined(OS_IOS)
bool IsAutofillCreditCardAssistEnabled() {
#if !defined(OS_ANDROID) && !defined(OS_IOS)
return false;
#else
return base::FeatureList::IsEnabled(kAutofillCreditCardAssist);
#endif
}
} // namespace features
} // namespace autofill
| 45.579832 | 80 | 0.791759 | [
"model"
] |
c4aa8162247ed840d6e0f278a70876c57108643f | 1,145 | cpp | C++ | DGEMM/DGEMM/dgemm.cpp | ntauth/computer-architecture-unimib | f6a87c360d24289029adb35eb0244e59bc1dfa56 | [
"MIT"
] | null | null | null | DGEMM/DGEMM/dgemm.cpp | ntauth/computer-architecture-unimib | f6a87c360d24289029adb35eb0244e59bc1dfa56 | [
"MIT"
] | null | null | null | DGEMM/DGEMM/dgemm.cpp | ntauth/computer-architecture-unimib | f6a87c360d24289029adb35eb0244e59bc1dfa56 | [
"MIT"
] | null | null | null | /**
* @author: Ayoub Chouak (a.chouak@protonmail.com)
* @file: dgemm.cpp
*
*/
#include "dgemm.hpp"
#include <immintrin.h>
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
void __fastcall dgemm(double** src0, double** src1, double** dst, size_t shape)
{
SecureZeroMemory(dst, shape * shape);
for (size_t i = 0; i < shape; i++)
{
for (size_t j = 0; j < shape; j++)
{
double* dst_flat = reinterpret_cast<double*>(dst);
double dst_ij = 0;
for (size_t k = 0; k < shape; k++) {
dst_ij += reinterpret_cast<double*>(src0)[i + k * shape] * reinterpret_cast<double*>(src1)[k + j * shape];
}
dst_flat[i + j * shape] = dst_ij;
}
}
}
void __fastcall dgemm_avx(double** src0, double** src1, double** dst, size_t shape)
{
SecureZeroMemory(dst, shape * shape);
for (size_t i = 0; i < shape; i++)
{
for (size_t j = 0; j < shape; j++)
{
double* dst_flat = reinterpret_cast<double*>(dst);
double dst_ij = 0;
for (size_t k = 0; k < shape; k++) {
dst_ij += reinterpret_cast<double*>(src0)[i + k * shape] * reinterpret_cast<double*>(src1)[k + j * shape];
}
dst_flat[i + j * shape] = dst_ij;
}
}
} | 22.019231 | 110 | 0.61048 | [
"shape"
] |
c4aeae6120a72546ccddf624b4be1da5ca8f8ad8 | 2,694 | cpp | C++ | candidate_snps/overlap.cpp | gersteinlab/privaseq4 | de83070dd0a32d5f62f3f0a9a5a3b3d378b74e46 | [
"MIT"
] | null | null | null | candidate_snps/overlap.cpp | gersteinlab/privaseq4 | de83070dd0a32d5f62f3f0a9a5a3b3d378b74e46 | [
"MIT"
] | null | null | null | candidate_snps/overlap.cpp | gersteinlab/privaseq4 | de83070dd0a32d5f62f3f0a9a5a3b3d378b74e46 | [
"MIT"
] | 1 | 2022-03-31T02:10:18.000Z | 2022-03-31T02:10:18.000Z | // May 12, 2018
// by Gamze Gursoy
// input: matrix generated from 1000g vcf file and called SNVs in a txt format
#include <sstream>
#include <string>
#include "cstdio"
#include "cstring"
#include "cmath"
#include <string>
#include "iostream"
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "zlib.h"
#include <vector>
using namespace std;
int main(int argc, char * argv[])
{
if(argc == 1){
cout << "Please input 1000g genotype matrix and called genotype files" << endl;
return 1;
}
// files to open
// 1000g genotype matrix in txt format, delimiter is space
char *oneg = argv[1];
char filename1[80];
sprintf(filename1,oneg);
ifstream infile1(filename1);
// Called SNV matrix generated from vcf file of called set, delimiter is space
char *called = argv[2];
char filename2[80];
sprintf(filename2,called);
ifstream infile2(filename2);
char *chr = argv[3];
char chrom[80];
sprintf(chrom,chr);
//int chrom = stoi(what);;
// define the variables
vector<double> E;
vector<int> individual;
int ssfreq1, ssfreq2;
int loc, loc2;
float info;
string GT;
int freq;
string ref, ref2, alt, alt2, gt;
string line1;
string line2;
string delimiter = " ";
vector<string> chromosome;
vector<int> range1;
vector<int> range2;
while (getline(infile2,line2))
{
if ( !line2.empty() )
{
string buf2;
stringstream ss2(line2);
size_t pos2=0;
vector<string> tokens;
while ( ss2 >> buf2) {
tokens.push_back(buf2);
}
chromosome.push_back(tokens[0]);
range1.push_back(stoi(tokens[1]));
range2.push_back(stoi(tokens[2]));
}
}
//cout<<tokens[2504]<<endl ifstream infile1(filename1);
while (getline(infile1,line1))
{
if ( !line1.empty() )
{
string buf;
stringstream ss(line1);
size_t pos2 = 0;
vector<string> tokens2;
while ( ss >> buf) {
//cout<<"here"<<endl;
tokens2.push_back(buf);
}
// cout<<"here"<<endl;
loc = stoi(tokens2[1]);
//cout<<loc2<<endl;
ref = tokens2[2];
alt = tokens2[3];
GT = tokens2[4];
freq = stoi(tokens2[5]);
for (int i=0; i< chromosome.size(); i++)
{
//cout<<chromosome[i]<<endl;
//cout<<chrom<<endl;
if (chromosome[i].compare(chrom) == 0){
// cout<<range2[i]<<" "<<range1[i]<<" "<<loc<<endl;
if (range2[i]>=loc && range1[i]<=loc){
cout<<loc<<" "<<ref<<" "<<alt<<" "<<GT<<" "<<freq<<endl;
}
}
}
}
}
}
| 22.45 | 87 | 0.56533 | [
"vector"
] |
c4b62d46f052be5184a4e43418abbf0e3d06e5af | 6,388 | cpp | C++ | src/Sources/Extensions/FileExtensions.cpp | BerkanYildiz/EasyNT | 60441e098cae9a28174d1eb9c119742ff15a8d2a | [
"MIT"
] | 5 | 2021-06-17T03:01:11.000Z | 2022-02-07T03:47:46.000Z | src/Sources/Extensions/FileExtensions.cpp | BerkanYildiz/EasyNT | 60441e098cae9a28174d1eb9c119742ff15a8d2a | [
"MIT"
] | null | null | null | src/Sources/Extensions/FileExtensions.cpp | BerkanYildiz/EasyNT | 60441e098cae9a28174d1eb9c119742ff15a8d2a | [
"MIT"
] | 1 | 2021-07-23T11:59:34.000Z | 2021-07-23T11:59:34.000Z | #include "../../Headers/EasyNT.h"
/// <summary>
/// Reads and return the content of a file stored on disk.
/// </summary>
/// <param name="InFilePath">The path of the file.</param>
/// <param name="OutFileBuffer">The file's content.</param>
/// <param name="OutFileSize">The size (in bytes) of the file's content.</param>
NTSTATUS CkGetFileBuffer(UNICODE_STRING InFilePath, OUT PVOID* OutFileBuffer, OUT SIZE_T* OutFileSize)
{
NTSTATUS Status;
//
// Verify the passed parameters.
//
if (InFilePath.Buffer == NULL)
return STATUS_INVALID_PARAMETER_1;
if (OutFileBuffer == NULL)
return STATUS_INVALID_PARAMETER_2;
if (OutFileSize == NULL)
return STATUS_INVALID_PARAMETER_3;
//
// Initialize the object attributes.
//
OBJECT_ATTRIBUTES ObjectAttributes;
InitializeObjectAttributes(&ObjectAttributes, &InFilePath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
//
// Open a handle to the file.
//
HANDLE FileHandle = NULL;
IO_STATUS_BLOCK IoStatusBlock = { };
if (!NT_SUCCESS(Status = ZwCreateFile(&FileHandle, FILE_GENERIC_READ, &ObjectAttributes, &IoStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0)))
return Status;
//
// Query basic information about the file.
//
FILE_STANDARD_INFORMATION FileInformation = { };
if (!NT_SUCCESS(Status = ZwQueryInformationFile(FileHandle, &IoStatusBlock, &FileInformation, sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation)))
{
ZwClose(FileHandle);
return Status;
}
//
// Try to allocate memory to store the file's content.
//
auto* FileBuffer = CkAllocatePool(NonPagedPoolNx, (SIZE_T) FileInformation.EndOfFile.QuadPart);
if (FileBuffer == nullptr)
{
ZwClose(FileHandle);
return STATUS_INSUFFICIENT_RESOURCES;
}
//
// Read the file's content.
//
LARGE_INTEGER ByteOffset;
ByteOffset.QuadPart = 0;
if (!NT_SUCCESS(Status = ZwReadFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, FileBuffer, (ULONG) FileInformation.EndOfFile.QuadPart, &ByteOffset, NULL)))
{
CkFreePool(FileBuffer);
ZwClose(FileHandle);
return Status;
}
//
// Return the result.
//
if (OutFileBuffer != nullptr)
*OutFileBuffer = FileBuffer;
else
CkFreePool(FileBuffer);
if (OutFileSize != nullptr)
*OutFileSize = (SIZE_T) FileInformation.EndOfFile.QuadPart;
ZwClose(FileHandle);
return STATUS_SUCCESS;
}
/// <summary>
/// Reads and return the content of a file stored on disk.
/// </summary>
/// <param name="InFilePath">The path of the file.</param>
/// <param name="OutFileBuffer">The file's content.</param>
/// <param name="OutFileSize">The size (in bytes) of the file's content.</param>
NTSTATUS CkGetFileBuffer(CONST WCHAR* InFilePath, OUT PVOID* OutFileBuffer, OUT SIZE_T* OutFileSize)
{
UNICODE_STRING FilePath;
RtlInitUnicodeString(&FilePath, InFilePath);
return CkGetFileBuffer(FilePath, OutFileBuffer, OutFileSize);
}
/// <summary>
/// Reads and return the content of a file stored on disk.
/// </summary>
/// <param name="InFilePath">The path of the file.</param>
/// <param name="OutFileBuffer">The file's content.</param>
/// <param name="OutFileSize">The size (in bytes) of the file's content.</param>
NTSTATUS CkGetFileBuffer(CONST CHAR* InFilePath, OUT PVOID* OutFileBuffer, OUT SIZE_T* OutFileSize)
{
if (InFilePath == nullptr)
return STATUS_INVALID_PARAMETER_1;
ANSI_STRING FilePathToConvert;
RtlInitAnsiString(&FilePathToConvert, InFilePath);
UNICODE_STRING FilePath;
NTSTATUS Status = RtlAnsiStringToUnicodeString(&FilePath, &FilePathToConvert, TRUE);
if (NT_ERROR(Status))
return Status;
Status = CkGetFileBuffer(FilePath, OutFileBuffer, OutFileSize);
RtlFreeUnicodeString(&FilePath);
return Status;
}
/// <summary>
/// Retrieves the size (in bytes) of a file stored on disk.
/// </summary>
/// <param name="InFilePath">The path of the file.</param>
/// <param name="OutFileSize">The size of the file in bytes.</param>
NTSTATUS CkGetFileSize(UNICODE_STRING InFilePath, OUT SIZE_T* OutFileSize)
{
NTSTATUS Status;
//
// Verify the passed parameters.
//
if (InFilePath.Buffer == NULL)
return STATUS_INVALID_PARAMETER_1;
if (OutFileSize == NULL)
return STATUS_INVALID_PARAMETER_2;
//
// Initialize the object attributes.
//
OBJECT_ATTRIBUTES ObjectAttributes;
InitializeObjectAttributes(&ObjectAttributes, &InFilePath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
//
// Open a handle to the file.
//
HANDLE FileHandle = NULL;
IO_STATUS_BLOCK IoStatusBlock = { };
if (!NT_SUCCESS(Status = ZwCreateFile(&FileHandle, FILE_GENERIC_READ, &ObjectAttributes, &IoStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0)))
return Status;
//
// Query basic information about the file.
//
FILE_STANDARD_INFORMATION FileInformation = { };
if (!NT_SUCCESS(Status = ZwQueryInformationFile(FileHandle, &IoStatusBlock, &FileInformation, sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation)))
{
ZwClose(FileHandle);
return Status;
}
//
// Return the result.
//
if (OutFileSize != nullptr)
*OutFileSize = (SIZE_T) FileInformation.EndOfFile.QuadPart;
ZwClose(FileHandle);
return STATUS_SUCCESS;
}
/// <summary>
/// Retrieves the size (in bytes) of a file stored on disk.
/// </summary>
/// <param name="InFilePath">The path of the file.</param>
/// <param name="OutFileSize">The size of the file in bytes.</param>
NTSTATUS CkGetFileSize(CONST WCHAR* InFilePath, OUT SIZE_T* OutFileSize)
{
UNICODE_STRING FilePath;
RtlInitUnicodeString(&FilePath, InFilePath);
return CkGetFileSize(FilePath, OutFileSize);
}
/// <summary>
/// Retrieves the size (in bytes) of a file stored on disk.
/// </summary>
/// <param name="InFilePath">The path of the file.</param>
/// <param name="OutFileSize">The size of the file in bytes.</param>
NTSTATUS CkGetFileSize(CONST CHAR* InFilePath, OUT SIZE_T* OutFileSize)
{
if (InFilePath == nullptr)
return STATUS_INVALID_PARAMETER_1;
ANSI_STRING FilePathToConvert;
RtlInitAnsiString(&FilePathToConvert, InFilePath);
UNICODE_STRING FilePath;
NTSTATUS Status = RtlAnsiStringToUnicodeString(&FilePath, &FilePathToConvert, TRUE);
if (NT_ERROR(Status))
return Status;
Status = CkGetFileSize(FilePath, OutFileSize);
RtlFreeUnicodeString(&FilePath);
return Status;
}
| 27.895197 | 222 | 0.738729 | [
"object"
] |
c4b7ba339ed224a767aa03794220389fb96cece2 | 15,020 | cpp | C++ | paciofs-client/src/posix_io_rpc_client.cpp | jonasspenger/paciofs | b40fff93130f619ba351679926aca82e235f3f00 | [
"BSD-3-Clause"
] | 2 | 2019-04-22T16:37:52.000Z | 2019-09-13T12:11:09.000Z | paciofs-client/src/posix_io_rpc_client.cpp | jonasspenger/paciofs | b40fff93130f619ba351679926aca82e235f3f00 | [
"BSD-3-Clause"
] | 2 | 2020-03-02T14:37:29.000Z | 2020-03-11T15:14:46.000Z | paciofs-client/src/posix_io_rpc_client.cpp | jonasspenger/paciofs | b40fff93130f619ba351679926aca82e235f3f00 | [
"BSD-3-Clause"
] | 3 | 2019-04-22T16:37:58.000Z | 2020-03-12T09:01:50.000Z | /*
* Copyright (c) 2019, Zuse Institute Berlin.
*
* Licensed under the New BSD License, see LICENSE file for details.
*
*/
#include "posix_io_rpc_client.h"
#include "logging.h"
#include "posix_io.grpc.pb.h"
#include "rpc_client.h"
#include <grpcpp/grpcpp.h>
#include <sys/stat.h>
#include <future>
#include <string>
#include <vector>
namespace paciofs {
namespace io {
namespace posix {
namespace grpc {
PosixIoRpcClient::PosixIoRpcClient(std::string const &target,
std::string const &volume_name,
bool async_writes,
std::string const &cert_chain,
std::string const &private_key,
std::string const &root_certs)
: RpcClient<PosixIoService>(target, cert_chain, private_key, root_certs),
async_writes_(async_writes),
async_write_completion_queue_(
std::make_unique<::grpc::CompletionQueue>()),
volume_name_(volume_name),
logger_(paciofs::logging::Logger()) {}
PosixIoRpcClient::~PosixIoRpcClient() {
async_write_completion_queue_->Shutdown();
}
bool PosixIoRpcClient::Ping() {
PingRequest request;
logger_.Trace([request](auto &out) {
out << "Ping(" << request.ShortDebugString() << ")";
});
PingResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->Ping(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "Ping(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
} else {
logger_.Warning([request, status](auto &out) {
out << "Ping(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
}
return status.ok();
}
messages::Errno PosixIoRpcClient::Stat(std::string const &path,
messages::Stat &stat) {
StatRequest request;
request.set_path(PreparePath(path));
logger_.Trace([request](auto &out) {
out << "Stat(" << request.ShortDebugString() << ")";
});
StatResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->Stat(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "Stat(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
messages::Errno error = response.error();
if (error != messages::ERRNO_ESUCCESS) {
return error;
}
stat.CopyFrom(response.stat());
return messages::ERRNO_ESUCCESS;
} else {
logger_.Warning([request, status](auto &out) {
out << "Stat(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::MkNod(std::string const &path,
google::protobuf::uint32 mode,
google::protobuf::int32 dev) {
MkNodRequest request;
request.set_path(PreparePath(path));
request.set_mode(mode);
request.set_dev(dev);
logger_.Trace([request](auto &out) {
out << "MkNod(" << request.ShortDebugString() << ")";
});
MkNodResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->MkNod(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "MkNod(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
return response.error();
} else {
logger_.Warning([request, status](auto &out) {
out << "MkNod(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::MkDir(std::string const &path,
google::protobuf::uint32 mode) {
MkDirRequest request;
request.set_path(PreparePath(path));
request.set_mode(mode);
logger_.Trace([request](auto &out) {
out << "MkDir(" << request.ShortDebugString() << ")";
});
MkDirResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->MkDir(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "MkDir(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
return response.error();
} else {
logger_.Warning([request, status](auto &out) {
out << "MkDir(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::ChMod(std::string const &path,
google::protobuf::uint32 mode) {
ChModRequest request;
request.set_path(PreparePath(path));
request.set_mode(mode);
logger_.Trace([request](auto &out) {
out << "ChMod(" << request.ShortDebugString() << ")";
});
ChModResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->ChMod(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "ChMod(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
return response.error();
} else {
logger_.Warning([request, status](auto &out) {
out << "ChMod(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::ChOwn(std::string const &path,
google::protobuf::uint32 uid,
google::protobuf::uint32 gid) {
ChOwnRequest request;
request.set_path(PreparePath(path));
request.set_uid(uid);
request.set_gid(gid);
logger_.Trace([request](auto &out) {
out << "ChOwn(" << request.ShortDebugString() << ")";
});
ChOwnResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->ChOwn(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "ChOwn(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
return response.error();
} else {
logger_.Warning([request, status](auto &out) {
out << "ChOwn(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::Open(std::string const &path,
google::protobuf::int32 flags,
google::protobuf::uint64 &fh) {
OpenRequest request;
request.set_path(PreparePath(path));
request.set_flags(flags);
logger_.Trace([request](auto &out) {
out << "Open(" << request.ShortDebugString() << ")";
});
OpenResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->Open(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "Open(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
messages::Errno error = response.error();
if (error != messages::ERRNO_ESUCCESS) {
return error;
}
fh = response.fh();
return messages::ERRNO_ESUCCESS;
} else {
logger_.Warning([request, status](auto &out) {
out << "Open(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::Read(std::string const &path, char *buf,
google::protobuf::uint32 size,
google::protobuf::int64 offset,
google::protobuf::uint64 fh,
google::protobuf::uint32 &n) {
ReadRequest request;
request.set_path(PreparePath(path));
request.set_size(size);
request.set_offset(offset);
request.set_fh(fh);
logger_.Trace([request](auto &out) {
out << "Read(" << request.ShortDebugString() << ")";
});
ReadResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->Read(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
ReadResponse printResponse(response);
printResponse.clear_buf();
out << "Read(" << request.ShortDebugString()
<< "): " << printResponse.ShortDebugString();
});
if (response.eof()) {
n = 0;
} else {
n = response.n();
memcpy(buf, response.buf().c_str(), n);
}
return messages::ERRNO_ESUCCESS;
} else {
logger_.Warning([request, status](auto &out) {
out << "Read(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::Write(std::string const &path,
const char *buf,
google::protobuf::uint32 size,
google::protobuf::int64 offset,
google::protobuf::uint64 fh,
google::protobuf::uint32 &n) {
WriteRequest request;
request.set_path(PreparePath(path));
request.set_size(size);
request.set_offset(offset);
request.set_fh(fh);
// printable request without the data buffer
WriteRequest printable_request(request);
request.mutable_buf()->assign(buf, size);
logger_.Trace([&printable_request](auto &out) {
out << "Write(" << printable_request.ShortDebugString() << ")";
});
WriteResponse response;
::grpc::ClientContext context;
SetMetadata(context);
std::unique_ptr<::grpc::ClientAsyncResponseReader<WriteResponse>> async_write(
Stub()->PrepareAsyncWrite(&context, request,
async_write_completion_queue_.get()));
async_write->StartCall();
::grpc::Status status;
async_write->Finish(&response, &status, (void *)1);
if (async_writes_) {
n = size;
return messages::ERRNO_ESUCCESS;
} else {
void *tag;
bool ok = false;
bool got_event = async_write_completion_queue_->Next(&tag, &ok);
if (got_event && ok) {
// TODO check tag vs. request_tag
if (status.ok()) {
logger_.Trace([&printable_request, tag, &response](auto &out) {
out << "Write(" << printable_request.ShortDebugString() << ") ("
<< tag << "): " << response.ShortDebugString();
});
n = response.n();
return messages::ERRNO_ESUCCESS;
} else {
logger_.Warning([&printable_request, tag, &status](auto &out) {
out << "Write(" << printable_request.ShortDebugString() << ") ("
<< tag << "): " << status.error_message() << " ("
<< status.error_code() << ")";
});
return messages::ERRNO_EIO;
}
} else {
logger_.Warning([&printable_request, got_event, ok](auto &out) {
out << "Write(" << printable_request.ShortDebugString() << "): got "
<< (got_event ? "" : "no") << " event / " << (ok ? "" : "not")
<< " ok";
});
return messages::ERRNO_EIO;
}
}
}
messages::Errno PosixIoRpcClient::ReadDir(std::string const &path,
std::vector<messages::Dir> &dirs) {
ReadDirRequest request;
request.set_path(PreparePath(path));
logger_.Trace([request](auto &out) {
out << "ReadDir(" << request.ShortDebugString() << ")";
});
ReadDirResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->ReadDir(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "ReadDir(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
messages::Errno error = response.error();
if (error != messages::ERRNO_ESUCCESS) {
return error;
}
for (int i = 0; i < response.dirs_size(); ++i) {
dirs.push_back(response.dirs(i));
}
return messages::ERRNO_ESUCCESS;
} else {
logger_.Warning([request, status](auto &out) {
out << "ReadDir(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
messages::Errno PosixIoRpcClient::Create(std::string const &path,
google::protobuf::uint32 mode,
google::protobuf::int32 flags,
google::protobuf::uint64 &fh) {
CreateRequest request;
request.set_path(PreparePath(path));
request.set_mode(mode);
request.set_flags(flags);
logger_.Trace([request](auto &out) {
out << "Create(" << request.ShortDebugString() << ")";
});
CreateResponse response;
::grpc::ClientContext context;
SetMetadata(context);
::grpc::Status status = Stub()->Create(&context, request, &response);
if (status.ok()) {
logger_.Trace([request, response](auto &out) {
out << "Create(" << request.ShortDebugString()
<< "): " << response.ShortDebugString();
});
messages::Errno error = response.error();
if (error != messages::ERRNO_ESUCCESS) {
return error;
}
fh = response.fh();
return messages::ERRNO_ESUCCESS;
} else {
logger_.Warning([request, status](auto &out) {
out << "Create(" << request.ShortDebugString()
<< "): " << status.error_message() << " (" << status.error_code()
<< ")";
});
return messages::ERRNO_EIO;
}
}
std::string const PosixIoRpcClient::PreparePath(std::string const &path) const {
std::string prepared_path = path;
prepared_path = MakeAbsolute(prepared_path);
prepared_path = PrefixVolumeName(prepared_path);
return prepared_path;
}
std::string const PosixIoRpcClient::MakeAbsolute(std::string const &path) {
return path;
}
std::string const PosixIoRpcClient::PrefixVolumeName(
std::string const &path) const {
return volume_name_ + ":" + path;
}
} // namespace grpc
} // namespace posix
} // namespace io
} // namespace paciofs
| 30.221328 | 80 | 0.576831 | [
"vector"
] |
c4b8bff2fa61e998d2df8a21de9328584a52218b | 32,545 | cc | C++ | psdaq/psdaq/hsd/Module.cc | AntoineDujardin/lcls2 | 8b9d2815497fbbabb4d37800fd86a7be1728b552 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/psdaq/hsd/Module.cc | AntoineDujardin/lcls2 | 8b9d2815497fbbabb4d37800fd86a7be1728b552 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/psdaq/hsd/Module.cc | AntoineDujardin/lcls2 | 8b9d2815497fbbabb4d37800fd86a7be1728b552 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "psdaq/hsd/Module.hh"
#include "psdaq/mmhw/AxiVersion.hh"
#include "psdaq/mmhw/RegProxy.hh"
#include "psdaq/hsd/TprCore.hh"
#include "psdaq/hsd/RxDesc.hh"
#include "psdaq/hsd/ClkSynth.hh"
#include "psdaq/hsd/Mmcm.hh"
#include "psdaq/hsd/DmaCore.hh"
#include "psdaq/hsd/PhyCore.hh"
#include "psdaq/hsd/Pgp2b.hh"
#include "psdaq/mmhw/Pgp2bAxi.hh"
#include "psdaq/hsd/Pgp3.hh"
#include "psdaq/mmhw/Pgp3Axil.hh"
#include "psdaq/mmhw/RingBuffer.hh"
#include "psdaq/mmhw/Xvc.hh"
#include "psdaq/hsd/I2cSwitch.hh"
#include "psdaq/hsd/LocalCpld.hh"
#include "psdaq/hsd/FmcSpi.hh"
#include "psdaq/hsd/QABase.hh"
#include "psdaq/hsd/Adt7411.hh"
#include "psdaq/hsd/Tps2481.hh"
#include "psdaq/hsd/AdcCore.hh"
#include "psdaq/hsd/AdcSync.hh"
#include "psdaq/hsd/FmcCore.hh"
#include "psdaq/hsd/FmcCoreVoid.hh"
#include "psdaq/hsd/FexCfg.hh"
#include "psdaq/hsd/HdrFifo.hh"
#include "psdaq/hsd/PhaseMsmt.hh"
#include "psdaq/hsd/FlashController.hh"
using Pds::Mmhw::AxiVersion;
using Pds::Mmhw::Pgp2bAxi;
using Pds::Mmhw::Pgp3Axil;
using Pds::Mmhw::RingBuffer;
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/mman.h>
#include <poll.h>
#include <string.h>
using std::string;
#define GUARD(f) { _sem_i2c.take(); f; _sem_i2c.give(); }
namespace Pds {
namespace HSD {
class Module::PrivateData {
public:
// Initialize busses
void init();
// Initialize clock tree and IO training
void fmc_init(TimingType);
int train_io(unsigned);
void enable_test_pattern(TestPattern);
void disable_test_pattern();
void enable_cal ();
void disable_cal();
void setAdcMux(bool interleave,
unsigned channels);
void setRxAlignTarget(unsigned);
void setRxResetLength(unsigned);
void dumpRxAlign () const;
void dumpPgp () const;
//
// Low level API
//
public:
AxiVersion version;
uint32_t rsvd_to_0x08000[(0x8000-sizeof(AxiVersion))/4];
FlashController flash;
uint32_t rsvd_to_0x10000[(0x8000-sizeof(FlashController))/4];
I2cSwitch i2c_sw_control; // 0x10000
ClkSynth clksynth; // 0x10400
LocalCpld local_cpld; // 0x10800
Adt7411 vtmon1; // 0x10C00
Adt7411 vtmon2; // 0x11000
Adt7411 vtmon3; // 0x11400
Tps2481 imona; // 0x11800
Tps2481 imonb; // 0x11C00
Adt7411 vtmona; // 0x12000
FmcSpi fmc_spi; // 0x12400
uint32_t eeprom[0x100]; // 0x12800
uint32_t rsvd_to_0x18000[(0x08000-13*0x400)/4];
uint32_t regProxy[(0x08000)/4];
// DMA
DmaCore dma_core; // 0x20000
uint32_t rsvd_to_0x30000[(0x10000-sizeof(DmaCore))/4];
// PHY
PhyCore phy_core; // 0x30000
uint32_t rsvd_to_0x31000[(0x1000-sizeof(PhyCore))/4];
// GTH
uint32_t gthAlign[10]; // 0x31000
uint32_t rsvd_to_0x31100 [54];
uint32_t gthAlignTarget;
uint32_t gthAlignLast;
uint32_t rsvd_to_0x32000[(0x1000-0x108)/4];
// XVC
Pds::Mmhw::Jtag xvc;
uint32_t rsvd_to_0x40000[(0xE000-sizeof(xvc))/4];
// Timing
Pds::HSD::TprCore tpr; // 0x40000
uint32_t rsvd_to_0x50000 [(0x10000-sizeof(Pds::HSD::TprCore))/4];
RingBuffer ring0; // 0x50000
uint32_t rsvd_to_0x60000 [(0x10000-sizeof(RingBuffer))/4];
RingBuffer ring1; // 0x60000
uint32_t rsvd_to_0x70000 [(0x10000-sizeof(RingBuffer))/4];
uint32_t rsvd_to_0x80000 [0x10000/4];
// App registers
QABase base; // 0x80000
uint32_t rsvd_to_0x80800 [(0x800-sizeof(QABase))/4];
Mmcm mmcm; // 0x80800
FmcCore fmca_core; // 0x81000
AdcCore adca_core; // 0x81400
// FmcCore fmcb_core; // 0x81800
FmcCoreVoid fmcb_core; // 0x81800
AdcCore adcb_core; // 0x81C00
AdcSync adc_sync; // 0x82000
HdrFifo hdr_fifo[4]; // 0x82800
PhaseMsmt trg_phase[2];
uint32_t rsvd_to_0x88000 [(0x5800-4*sizeof(HdrFifo)-2*sizeof(PhaseMsmt))/4];
FexCfg fex_chan[4]; // 0x88000
uint32_t rsvd_to_0x90000 [(0x8000-4*sizeof(FexCfg))/4];
// Pgp (optional)
// Pgp2bAxi pgp[4]; // 0x90000
// uint32_t pgp_fmc1;
// uint32_t pgp_fmc2;
uint32_t pgp_reg[0x4000>>2];
uint32_t auxStatus;
uint32_t auxControl;
};
};
};
using namespace Pds::HSD;
Module* Module::create(int fd)
{
void* ptr = mmap(0, sizeof(Pds::HSD::Module::PrivateData), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
perror("Failed to map");
return 0;
}
Pds::HSD::Module* m = new Pds::HSD::Module;
m->p = reinterpret_cast<Pds::HSD::Module::PrivateData*>(ptr);
m->_fd = fd;
Pds::Mmhw::RegProxy::initialize(m->p, m->p->regProxy);
return m;
}
Module* Module::create(int fd, TimingType timing)
{
Module* m = create(fd);
//
// Verify clock synthesizer is setup
//
if (timing != EXTERNAL) {
timespec tvb;
clock_gettime(CLOCK_REALTIME,&tvb);
unsigned vvb = m->tpr().TxRefClks;
usleep(10000);
timespec tve;
clock_gettime(CLOCK_REALTIME,&tve);
unsigned vve = m->tpr().TxRefClks;
double dt = double(tve.tv_sec-tvb.tv_sec)+1.e-9*(double(tve.tv_nsec)-double(tvb.tv_nsec));
double txclkr = 16.e-6*double(vve-vvb)/dt;
printf("TxRefClk: %f MHz\n", txclkr);
static const double TXCLKR_MIN[] = { 118., 185., -1.00, 185., 185., 185. };
static const double TXCLKR_MAX[] = { 120., 187., 1000., 187., 187., 187. };
if (txclkr < TXCLKR_MIN[timing] ||
txclkr > TXCLKR_MAX[timing]) {
m->fmc_clksynth_setup(timing);
usleep(100000);
if (timing==LCLS)
m->tpr().setLCLS();
else
m->tpr().setLCLSII();
m->tpr().resetRxPll();
usleep(1000000);
m->tpr().resetBB();
m->p->base.resetFbPLL();
usleep(1000000);
m->p->base.resetFb ();
m->p->base.resetDma();
usleep(1000000);
m->tpr().resetCounts();
usleep(100000);
m->fmc_init(timing);
m->train_io(0);
}
}
return m;
}
Module::~Module()
{
}
int Module::read(uint32_t* data, unsigned data_size)
{
RxDesc* desc = new RxDesc(data,data_size);
int nw = ::read(_fd, desc, sizeof(*desc));
delete desc;
nw *= sizeof(uint32_t);
if (nw>=32)
data[7] = nw - 8*sizeof(uint32_t);
return nw;
}
enum
{
FMC12X_INTERNAL_CLK = 0, /*!< FMC12x_init() configure the FMC12x for internal clock operations */
FMC12X_EXTERNAL_CLK = 1, /*!< FMC12x_init() configure the FMC12x for external clock operations */
FMC12X_EXTERNAL_REF = 2, /*!< FMC12x_init() configure the FMC12x for external reference operations */
FMC12X_VCXO_TYPE_2500MHZ = 0, /*!< FMC12x_init() Vco on the card is 2.5GHz */
FMC12X_VCXO_TYPE_2200MHZ = 1, /*!< FMC12x_init() Vco on the card is 2.2GHz */
FMC12X_VCXO_TYPE_2000MHZ = 2, /*!< FMC12x_init() Vco on the card is 2.0GHz */
};
enum
{
CLOCKTREE_CLKSRC_EXTERNAL = 0, /*!< FMC12x_clocktree_init() configure the clock tree for external clock operations */
CLOCKTREE_CLKSRC_INTERNAL = 1, /*!< FMC12x_clocktree_init() configure the clock tree for internal clock operations */
CLOCKTREE_CLKSRC_EXTREF = 2, /*!< FMC12x_clocktree_init() configure the clock tree for external reference operations */
CLOCKTREE_VCXO_TYPE_2500MHZ = 0, /*!< FMC12x_clocktree_init() Vco on the card is 2.5GHz */
CLOCKTREE_VCXO_TYPE_2200MHZ = 1, /*!< FMC12x_clocktree_init() Vco on the card is 2.2GHz */
CLOCKTREE_VCXO_TYPE_2000MHZ = 2, /*!< FMC12x_clocktree_init() Vco on the card is 2.0GHz */
CLOCKTREE_VCXO_TYPE_1600MHZ = 3, /*!< FMC12x_clocktree_init() Vco on the card is 1.6 GHZ */
CLOCKTREE_VCXO_TYPE_BUILDIN = 4, /*!< FMC12x_clocktree_init() Vco on the card is the AD9517 build in VCO */
CLOCKTREE_VCXO_TYPE_2400MHZ = 5 /*!< FMC12x_clocktree_init() Vco on the card is 2.4GHz */
};
enum
{ // clock sources
CLKSRC_EXTERNAL_CLK = 0, /*!< FMC12x_cpld_init() external clock. */
CLKSRC_INTERNAL_CLK_EXTERNAL_REF = 3, /*!< FMC12x_cpld_init() internal clock / external reference. */
CLKSRC_INTERNAL_CLK_INTERNAL_REF = 6, /*!< FMC12x_cpld_init() internal clock / internal reference. */
// sync sources
SYNCSRC_EXTERNAL_TRIGGER = 0, /*!< FMC12x_cpld_init() external trigger. */
SYNCSRC_HOST = 1, /*!< FMC12x_cpld_init() software trigger. */
SYNCSRC_CLOCK_TREE = 2, /*!< FMC12x_cpld_init() signal from the clock tree. */
SYNCSRC_NO_SYNC = 3, /*!< FMC12x_cpld_init() no synchronization. */
// FAN enable bits
FAN0_ENABLED = (0<<4), /*!< FMC12x_cpld_init() FAN 0 is enabled */
FAN1_ENABLED = (0<<5), /*!< FMC12x_cpld_init() FAN 1 is enabled */
FAN2_ENABLED = (0<<6), /*!< FMC12x_cpld_init() FAN 2 is enabled */
FAN3_ENABLED = (0<<7), /*!< FMC12x_cpld_init() FAN 3 is enabled */
FAN0_DISABLED = (1<<4), /*!< FMC12x_cpld_init() FAN 0 is disabled */
FAN1_DISABLED = (1<<5), /*!< FMC12x_cpld_init() FAN 1 is disabled */
FAN2_DISABLED = (1<<6), /*!< FMC12x_cpld_init() FAN 2 is disabled */
FAN3_DISABLED = (1<<7), /*!< FMC12x_cpld_init() FAN 3 is disabled */
// LVTTL bus direction (HDMI connector)
DIR0_INPUT = (0<<0), /*!< FMC12x_cpld_init() DIR 0 is input */
DIR1_INPUT = (0<<1), /*!< FMC12x_cpld_init() DIR 1 is input */
DIR2_INPUT = (0<<2), /*!< FMC12x_cpld_init() DIR 2 is input */
DIR3_INPUT = (0<<3), /*!< FMC12x_cpld_init() DIR 3 is input */
DIR0_OUTPUT = (1<<0), /*!< FMC12x_cpld_init() DIR 0 is output */
DIR1_OUTPUT = (1<<1), /*!< FMC12x_cpld_init() DIR 1 is output */
DIR2_OUTPUT = (1<<2), /*!< FMC12x_cpld_init() DIR 2 is output */
DIR3_OUTPUT = (1<<3), /*!< FMC12x_cpld_init() DIR 3 is output */
};
void Module::PrivateData::init()
{
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmc_spi.initSPI();
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
fmc_spi.initSPI();
}
void Module::PrivateData::fmc_init(TimingType timing)
{
// if(FMC12x_init(AddrSipFMC12xBridge, AddrSipFMC12xClkSpi, AddrSipFMC12xAdcSpi, AddrSipFMC12xCpldSpi, AddrSipFMC12xAdcPhy,
// modeClock, cardType, GA, typeVco, carrierKC705)!=FMC12X_ERR_OK) {
#if 1
const uint32_t clockmode = FMC12X_EXTERNAL_REF;
#else
const uint32_t clockmode = FMC12X_INTERNAL_CLK;
#endif
// uint32_t clksrc_cpld;
uint32_t clksrc_clktree;
uint32_t vcotype = 0; // default 2500 MHz
if(clockmode==FMC12X_INTERNAL_CLK) {
// clksrc_cpld = CLKSRC_INTERNAL_CLK_INTERNAL_REF;
clksrc_clktree = CLOCKTREE_CLKSRC_INTERNAL;
}
else if(clockmode==FMC12X_EXTERNAL_REF) {
// clksrc_cpld = CLKSRC_INTERNAL_CLK_EXTERNAL_REF;
clksrc_clktree = CLOCKTREE_CLKSRC_EXTREF;
}
else {
// clksrc_cpld = CLKSRC_EXTERNAL_CLK;
clksrc_clktree = CLOCKTREE_CLKSRC_EXTERNAL;
}
if (!fmca_core.present()) {
printf("FMC card A not present\n");
printf("FMC init failed!\n");
return;
}
{
printf("FMC card A initializing\n");
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
if (fmc_spi.cpld_init())
printf("cpld_init failed!\n");
if (fmc_spi.clocktree_init(clksrc_clktree, vcotype, timing))
printf("clocktree_init failed!\n");
}
if (fmcb_core.present()) {
printf("FMC card B initializing\n");
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
if (fmc_spi.cpld_init())
printf("cpld_init failed!\n");
if (fmc_spi.clocktree_init(clksrc_clktree, vcotype, timing))
printf("clocktree_init failed!\n");
}
}
int Module::PrivateData::train_io(unsigned ref_delay)
{
//
// IO Training
//
if (!fmca_core.present()) {
printf("FMC card A not present\n");
printf("IO training failed!\n");
return -1;
}
bool fmcb_present = fmcb_core.present();
int rval = -1;
while(1) {
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
if (fmc_spi.adc_enable_test(Flash11))
break;
if (fmcb_present) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
if (fmc_spi.adc_enable_test(Flash11))
break;
}
// adcb_core training is driven by adca_core
adca_core.init_training(0x08);
if (fmcb_present)
adcb_core.init_training(ref_delay);
adca_core.start_training();
adca_core.dump_training();
if (fmcb_present)
adcb_core.dump_training();
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
if (fmc_spi.adc_disable_test())
break;
if (fmc_spi.adc_enable_test(Flash11))
break;
if (fmcb_present) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
if (fmc_spi.adc_disable_test())
break;
if (fmc_spi.adc_enable_test(Flash11))
break;
}
adca_core.loop_checking();
if (fmcb_present)
adcb_core.loop_checking();
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
if (fmc_spi.adc_disable_test())
break;
if (fmcb_present) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
if (fmc_spi.adc_disable_test())
break;
}
rval = 0;
break;
}
return rval;
}
void Module::PrivateData::enable_test_pattern(TestPattern p)
{
if (p < 8) {
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmc_spi.adc_enable_test(p);
if (fmcb_core.present()) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
fmc_spi.adc_enable_test(p);
}
}
else
base.enableDmaTest(true);
}
void Module::PrivateData::disable_test_pattern()
{
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmc_spi.adc_disable_test();
if (fmcb_core.present()) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
fmc_spi.adc_disable_test();
}
base.enableDmaTest(false);
}
void Module::PrivateData::enable_cal()
{
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmc_spi.adc_enable_cal();
fmca_core.cal_enable();
if (fmcb_core.present()) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
fmc_spi.adc_enable_cal();
fmca_core.cal_enable();
}
}
void Module::PrivateData::disable_cal()
{
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmca_core.cal_disable();
fmc_spi.adc_disable_cal();
if (fmcb_core.present()) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
fmcb_core.cal_disable();
fmc_spi.adc_disable_cal();
}
}
void Module::PrivateData::setRxAlignTarget(unsigned t)
{
unsigned v = gthAlignTarget;
v &= ~0x3f;
v |= (t&0x3f);
gthAlignTarget = v;
}
void Module::PrivateData::setRxResetLength(unsigned len)
{
unsigned v = gthAlignTarget;
v &= ~0xf0000;
v |= (len&0xf)<<16;
gthAlignTarget = v;
}
void Module::PrivateData::dumpRxAlign () const
{
printf("\nTarget: %u\tRstLen: %u\tLast: %u\n",
gthAlignTarget&0x7f,
(gthAlignTarget>>16)&0xf,
gthAlignLast&0x7f);
for(unsigned i=0; i<128; i++) {
printf(" %04x",(gthAlign[i/2] >> (16*(i&1)))&0xffff);
if ((i%10)==9) printf("\n");
}
printf("\n");
}
#define LPRINT(title,field) { \
printf("\t%20.20s :",title); \
for(unsigned i=0; i<4; i++) \
printf(" %11x",pgp[i].field); \
printf("\n"); }
#define LPRBF(title,field,shift,mask) { \
printf("\t%20.20s :",title); \
for(unsigned i=0; i<4; i++) \
printf(" %11x",(pgp[i].field>>shift)&mask); \
printf("\n"); }
#define LPRVC(title,field) { \
printf("\t%20.20s :",title); \
for(unsigned i=0; i<4; i++) \
printf(" %2x %2x %2x %2x", \
pgp[i].field##0, \
pgp[i].field##1, \
pgp[i].field##2, \
pgp[i].field##3 ); \
printf("\n"); }
#define LPRFRQ(title,field) { \
printf("\t%20.20s :",title); \
for(unsigned i=0; i<4; i++) \
printf(" %11.4f",double(pgp[i].field)*1.e-6); \
printf("\n"); }
void Module::PrivateData::dumpPgp () const
{
string buildStamp = version.buildStamp();
if (buildStamp.find("pgp")==string::npos)
return;
if (buildStamp.find("pgp3")==string::npos) {
const Pgp2bAxi* pgp = reinterpret_cast<const Pgp2bAxi*>(pgp_reg);
LPRINT("loopback",_loopback);
LPRINT("txUserData",_txUserData);
LPRBF ("rxPhyReady",_status,0,1);
LPRBF ("txPhyReady",_status,1,1);
LPRBF ("localLinkReady",_status,2,1);
LPRBF ("remoteLinkReady",_status,3,1);
LPRBF ("transmitReady",_status,4,1);
LPRBF ("rxPolarity",_status,8,3);
LPRBF ("remotePause",_status,12,0xf);
LPRBF ("localPause",_status,16,0xf);
LPRBF ("remoteOvfl",_status,20,0xf);
LPRBF ("localOvfl",_status,24,0xf);
LPRINT("remoteData",_remoteUserData);
LPRINT("cellErrors",_cellErrCount);
LPRINT("linkDown",_linkDownCount);
LPRINT("linkErrors",_linkErrCount);
LPRVC ("remoteOvflVC",_remoteOvfVc);
LPRINT("framesRxErr",_rxFrameErrs);
LPRINT("framesRx",_rxFrames);
LPRVC ("localOvflVC",_localOvfVc);
LPRINT("framesTxErr",_txFrameErrs);
LPRINT("framesTx",_txFrames);
LPRFRQ("rxClkFreq",_rxClkFreq);
LPRFRQ("txClkFreq",_txClkFreq);
LPRINT("lastTxOp",_lastTxOpcode);
LPRINT("lastRxOp",_lastRxOpcode);
LPRINT("nTxOps",_txOpcodes);
LPRINT("nRxOps",_rxOpcodes);
}
else {
const Pgp3Axil* pgp = reinterpret_cast<const Pgp3Axil*>(pgp_reg);
LPRINT("loopback" ,loopback);
LPRINT("skpInterval" ,skpInterval);
LPRBF ("localLinkReady" ,rxStatus,1,1);
LPRBF ("remoteLinkReady",rxStatus,2,1);
LPRINT("framesRxErr" ,rxFrameErrCnt);
LPRINT("framesRx" ,rxFrameCnt);
LPRINT("framesTxErr" ,txFrameErrCnt);
LPRINT("framesTx" ,txFrameCnt);
LPRFRQ("rxClkFreq" ,rxClkFreq);
LPRFRQ("txClkFreq" ,txClkFreq);
LPRINT("lastTxOp" ,txOpCodeLast);
LPRINT("lastRxOp" ,rxOpCodeLast);
LPRINT("nTxOps" ,txOpCodeCnt);
LPRINT("nRxOps" ,rxOpCodeCnt);
LPRINT("txCntrl" ,cntrl);
LPRINT("txStatus" ,txStatus);
LPRINT("locStatus" ,locStatus);
}
{ printf(" prsnt1L %x\n", (auxStatus>>0)&1);
printf(" pwrgd1 %x\n", (auxStatus>>1)&1);
printf(" qsfpPrsN %x\n", (auxStatus>>2)&3);
printf(" qsfpIntN %x\n", (auxStatus>>4)&3);
printf(" oe_osc %x\n", (auxControl>>0)&1);
printf(" qsfpRstN %x\n", (auxControl>>3)&1);
}
}
#undef LPRINT
#undef LPRBF
#undef LPRVC
#undef LPRFRQ
void Module::dumpBase() const
{
p->base.dump();
}
void Module::dumpMap() const
{
printf("AxiVersion : %p\n", &p->version);
printf("FlashController: %p\n", &p->flash);
printf("I2cSwitch : %p\n", &p->i2c_sw_control);
printf("ClkSynth : %p\n", &p->clksynth);
printf("LocalCpld : %p\n", &p->local_cpld);
printf("FmcSpi : %p\n", &p->fmc_spi);
printf("DmaCore : %p\n", &p->dma_core);
printf("TprCore : %p\n", &p->tpr);
printf("QABase : %p\n", &p->base);
printf("HdrFifo : %p\n", &p->hdr_fifo[0]);
printf("FexCfg : %p\n", &p->fex_chan[0]);
}
void Module::PrivateData::setAdcMux(bool interleave,
unsigned channels)
{
if (interleave) {
base.setChannels(channels);
base.setMode( QABase::Q_ABCD );
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmc_spi.setAdcMux(interleave, channels&0x0f);
if (fmcb_core.present()) {
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
fmc_spi.setAdcMux(interleave, (channels>>4)&0x0f);
}
}
else {
if (fmcb_core.present()) {
base.setChannels(channels & 0xff);
base.setMode( QABase::Q_NONE );
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmc_spi.setAdcMux(interleave, (channels>>0)&0xf);
i2c_sw_control.select(I2cSwitch::SecondaryFmc);
fmc_spi.setAdcMux(interleave, (channels>>4)&0xf);
}
else {
base.setChannels(channels & 0xf);
base.setMode( QABase::Q_NONE );
i2c_sw_control.select(I2cSwitch::PrimaryFmc);
fmc_spi.setAdcMux(interleave, channels&0xf);
}
}
}
void Module::init() { GUARD( p->init() ); }
void Module::fmc_init(TimingType timing) { GUARD( p->fmc_init(timing) ); }
void Module::fmc_dump() {
if (p->fmca_core.present())
for(unsigned i=0; i<16; i++) {
p->fmca_core.selectClock(i);
usleep(100000);
printf("Clock [%i]: rate %f MHz\n", i, p->fmca_core.clockRate()*1.e-6);
}
if (p->fmcb_core.present())
for(unsigned i=0; i<9; i++) {
p->fmcb_core.selectClock(i);
usleep(100000);
printf("Clock [%i]: rate %f MHz\n", i, p->fmcb_core.clockRate()*1.e-6);
}
}
void Module::fmc_clksynth_setup(TimingType timing)
{
_sem_i2c.take();
p->i2c_sw_control.select(I2cSwitch::LocalBus); // ClkSynth is on local bus
p->clksynth.setup(timing);
p->clksynth.dump ();
_sem_i2c.give();
}
void Module::fmc_modify(int A, int B, int P, int R, int cp, int ab)
{
_sem_i2c.take();
p->i2c_sw_control.select(I2cSwitch::PrimaryFmc);
p->fmc_spi.clocktree_modify(A,B,P,R,cp,ab);
_sem_i2c.give();
}
uint64_t Module::device_dna() const
{
uint64_t v = p->version.DeviceDnaHigh;
v <<= 32;
v |= p->version.DeviceDnaLow;
return v;
}
// Update ID advertised on timing link
void Module::set_local_id(unsigned bus)
{
struct addrinfo hints;
struct addrinfo* result;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
char hname[64];
gethostname(hname,64);
int s = getaddrinfo(hname, NULL, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
sockaddr_in* saddr = (sockaddr_in*)result->ai_addr;
unsigned id = 0xfc000000 | (bus<<16) |
(ntohl(saddr->sin_addr.s_addr)&0xffff);
p->base.localId = id;
p->version.UserConstants[0] = id;
}
void Module::board_status()
{
printf("Axi Version [%p]: BuildStamp[%p]: %s\n",
&(p->version), &(p->version.BuildStamp[0]), p->version.buildStamp().c_str());
printf("Dna: %08x%08x Serial: %08x%08x\n",
p->version.DeviceDnaHigh,
p->version.DeviceDnaLow,
p->version.FdSerialHigh,
p->version.FdSerialLow );
_sem_i2c.take();
p->i2c_sw_control.select(I2cSwitch::LocalBus);
p->i2c_sw_control.dump();
printf("Local CPLD revision: 0x%x\n", p->local_cpld.revision());
printf("Local CPLD GAaddr : 0x%x\n", p->local_cpld.GAaddr ());
p->local_cpld.GAaddr(0);
{ unsigned v;
printf("EEPROM:");
for(unsigned i=0; i<32; i++) {
v = p->eeprom[i];
printf(" %02x", v&0xff);
}
printf("\n");
}
printf("vtmon1 mfg:dev %x:%x\n", p->vtmon1.manufacturerId(), p->vtmon1.deviceId());
printf("vtmon2 mfg:dev %x:%x\n", p->vtmon2.manufacturerId(), p->vtmon2.deviceId());
printf("vtmon3 mfg:dev %x:%x\n", p->vtmon3.manufacturerId(), p->vtmon3.deviceId());
p->vtmon1.dump();
p->vtmon2.dump();
p->vtmon3.dump();
p->imona.dump();
p->imonb.dump();
printf("FMC A [%p]: %s present power %s\n",
&p->fmca_core,
p->fmca_core.present() ? "":"not",
p->fmca_core.powerGood() ? "up":"down");
printf("FMC B [%p]: %s present power %s\n",
&p->fmcb_core,
p->fmcb_core.present() ? "":"not",
p->fmcb_core.powerGood() ? "up":"down");
if (p->fmca_core.present()) {
p->i2c_sw_control.select(I2cSwitch::PrimaryFmc);
p->i2c_sw_control.dump();
printf("vtmona mfg:dev %x:%x\n", p->vtmona.manufacturerId(), p->vtmona.deviceId());
}
if (p->fmcb_core.present()) {
p->i2c_sw_control.select(I2cSwitch::SecondaryFmc);
p->i2c_sw_control.dump();
printf("vtmonb mfg:dev %x:%x\n", p->vtmona.manufacturerId(), p->vtmona.deviceId());
}
_sem_i2c.give();
}
void Module::flash_write(const char* fname)
{
p->flash.write(fname);
}
FlashController& Module::flash() { return p->flash; }
int Module::train_io(unsigned v)
{
int r; GUARD( r = p->train_io(v) ); return r;
}
void Module::enable_test_pattern(TestPattern t)
{ GUARD( p->enable_test_pattern(t) ); }
void Module::disable_test_pattern()
{ GUARD( p->disable_test_pattern() ); }
void Module::clear_test_pattern_errors() {
for(unsigned i=0; i<4; i++) {
p->fex_chan[i]._test_pattern_errors = 0;
p->fex_chan[i]._test_pattern_errbits = 0;
}
}
void Module::enable_cal ()
{ GUARD( p->enable_cal() ); }
void Module::disable_cal()
{ GUARD( p->disable_cal()); }
void Module::setAdcMux(unsigned channels)
{
_sem_i2c.take();
if (p->fmcb_core.present()) {
p->base.setChannels(0xff);
p->base.setMode( QABase::Q_NONE );
p->i2c_sw_control.select(I2cSwitch::PrimaryFmc);
p->fmc_spi.setAdcMux((channels>>0)&0xf);
p->i2c_sw_control.select(I2cSwitch::SecondaryFmc);
p->fmc_spi.setAdcMux((channels>>4)&0xf);
}
else {
p->base.setChannels(0xf);
p->base.setMode( QABase::Q_NONE );
p->i2c_sw_control.select(I2cSwitch::PrimaryFmc);
p->fmc_spi.setAdcMux(channels&0xf);
}
_sem_i2c.give();
}
void Module::setAdcMux(bool interleave,
unsigned channels)
{ GUARD( p->setAdcMux(interleave, channels) ); }
const Pds::Mmhw::AxiVersion& Module::version() const { return p->version; }
Pds::HSD::TprCore& Module::tpr () { return p->tpr; }
void Module::setRxAlignTarget(unsigned v) { p->setRxAlignTarget(v); }
void Module::setRxResetLength(unsigned v) { p->setRxResetLength(v); }
void Module::dumpRxAlign () const { p->dumpRxAlign(); }
void Module::dumpPgp () const { p->dumpPgp(); }
void Module::sample_init(unsigned length,
unsigned delay,
unsigned prescale)
{
p->base.init();
p->base.samples = length;
p->base.prescale = (delay<<6) | (prescale&0x3f);
p->dma_core.init(32+48*length);
p->dma_core.dump();
// p->dma.setEmptyThr(emptyThr);
// p->base.dmaFullThr=fullThr;
// flush out all the old
{ printf("flushing\n");
unsigned nflush=0;
uint32_t* data = new uint32_t[1<<20];
RxDesc* desc = new RxDesc(data,1<<20);
pollfd pfd;
pfd.fd = _fd;
pfd.events = POLLIN;
while(poll(&pfd,1,0)>0) {
::read(_fd, desc, sizeof(*desc));
nflush++;
}
delete[] data;
delete desc;
printf("done flushing [%u]\n",nflush);
}
p->base.resetCounts();
}
void Module::trig_lcls (unsigned eventcode)
{
p->base.setupLCLS(eventcode);
}
void Module::trig_lclsii(unsigned fixedrate)
{
p->base.setupLCLSII(fixedrate);
}
void Module::trig_daq (unsigned partition)
{
p->base.setupDaq(partition);
}
void Module::trig_shift (unsigned shift)
{
p->base.setTrigShift(shift);
}
void Module::start()
{
p->base.start();
}
void Module::stop()
{
p->base.stop();
p->dma_core.dump();
}
unsigned Module::get_offset(unsigned channel)
{
_sem_i2c.take();
p->i2c_sw_control.select((channel&0x4)==0 ?
I2cSwitch::PrimaryFmc :
I2cSwitch::SecondaryFmc);
unsigned v = p->fmc_spi.get_offset(channel&0x3);
_sem_i2c.give();
return v;
}
unsigned Module::get_gain(unsigned channel)
{
_sem_i2c.take();
p->i2c_sw_control.select((channel&0x4)==0 ?
I2cSwitch::PrimaryFmc :
I2cSwitch::SecondaryFmc);
unsigned v = p->fmc_spi.get_gain(channel&0x3);
_sem_i2c.give();
return v;
}
void Module::set_offset(unsigned channel, unsigned value)
{
_sem_i2c.take();
p->i2c_sw_control.select((channel&0x4)==0 ?
I2cSwitch::PrimaryFmc :
I2cSwitch::SecondaryFmc);
p->fmc_spi.set_offset(channel&0x3,value);
_sem_i2c.give();
}
void Module::set_gain(unsigned channel, unsigned value)
{
_sem_i2c.take();
p->i2c_sw_control.select((channel&0x4)==0 ?
I2cSwitch::PrimaryFmc :
I2cSwitch::SecondaryFmc);
p->fmc_spi.set_gain(channel&0x3,value);
_sem_i2c.give();
}
void Module::clocktree_sync()
{
_sem_i2c.take();
p->i2c_sw_control.select(I2cSwitch::PrimaryFmc);
p->fmc_spi.clocktree_sync();
_sem_i2c.give();
}
void Module::sync()
{
_sem_i2c.take();
p->i2c_sw_control.select(I2cSwitch::PrimaryFmc);
p->fmc_spi.applySync();
_sem_i2c.give();
}
void* Module::reg() { return (void*)p; }
std::vector<Pgp*> Module::pgp() {
std::vector<Pgp*> v(0);
while(1) {
string buildStamp = p->version.buildStamp();
if (buildStamp.find("pgp")==string::npos)
break;
if (buildStamp.find("pgp3")==string::npos) {
Pgp2bAxi* pgp = reinterpret_cast<Pgp2bAxi*>(p->pgp_reg);
for(unsigned i=0; i<4; i++)
v.push_back(new Pgp2b(pgp[i]));
}
else {
Pgp3Axil* pgp = reinterpret_cast<Pgp3Axil*>(p->pgp_reg);
for(unsigned i=0; i<4; i++)
v.push_back(new Pgp3(pgp[i]));
}
break;
}
return v;
}
Pds::Mmhw::Jtag* Module::xvc() { return &p->xvc; }
FexCfg* Module::fex() { return &p->fex_chan[0]; }
HdrFifo* Module::hdrFifo() { return &p->hdr_fifo[0]; }
uint32_t* Module::trgPhase() { return reinterpret_cast<uint32_t*>(&p->trg_phase[0]); }
void Module::mon_start()
{
_sem_i2c.take();
p->i2c_sw_control.select(I2cSwitch::LocalBus);
p->vtmon1.start();
p->vtmon2.start();
p->vtmon3.start();
p->imona.start();
p->imonb.start();
_sem_i2c.give();
}
EnvMon Module::mon() const
{
_sem_i2c.take();
p->i2c_sw_control.select(I2cSwitch::LocalBus);
EnvMon v;
Adt7411_Mon m;
m = p->vtmon1.mon();
v.local12v = m.ain[3]*6.;
v.edge12v = m.ain[6]*6.;
v.aux12v = m.ain[7]*6.;
m = p->vtmon2.mon();
v.boardTemp = m.Tint;
v.local1_8v = m.ain[6];
m = p->vtmon3.mon();
v.fmc12v = m.ain[2]*6.;
v.local2_5v = m.ain[6]*2.;
v.local3_3v = m.ain[7]*2.;
v.fmcPower = p->imona.power_W();
v.totalPower = p->imonb.power_W();
_sem_i2c.give();
return v;
}
void Module::i2c_lock(I2cSwitch::Port v)
{
_sem_i2c.take();
p->i2c_sw_control.select(v);
}
void Module::i2c_unlock() { _sem_i2c.give(); }
| 30.330848 | 178 | 0.583346 | [
"vector"
] |
c4bc97c541e37c1de942fe71a09f7e5477988ff3 | 12,171 | cpp | C++ | export/release/macos/obj/src/ResetSave.cpp | BushsHaxs/DOKIDOKI-MAC | 22729124a0b7b637d56ff3b18acb555ec05934f1 | [
"Apache-2.0"
] | null | null | null | export/release/macos/obj/src/ResetSave.cpp | BushsHaxs/DOKIDOKI-MAC | 22729124a0b7b637d56ff3b18acb555ec05934f1 | [
"Apache-2.0"
] | null | null | null | export/release/macos/obj/src/ResetSave.cpp | BushsHaxs/DOKIDOKI-MAC | 22729124a0b7b637d56ff3b18acb555ec05934f1 | [
"Apache-2.0"
] | 1 | 2021-12-11T09:19:29.000Z | 2021-12-11T09:19:29.000Z | #include <hxcpp.h>
#ifndef INCLUDED_Highscore
#include <Highscore.h>
#endif
#ifndef INCLUDED_LangUtil
#include <LangUtil.h>
#endif
#ifndef INCLUDED_Option
#include <Option.h>
#endif
#ifndef INCLUDED_ResetSave
#include <ResetSave.h>
#endif
#ifndef INCLUDED_Sys
#include <Sys.h>
#endif
#ifndef INCLUDED_flixel_FlxG
#include <flixel/FlxG.h>
#endif
#ifndef INCLUDED_flixel_util_FlxSave
#include <flixel/util/FlxSave.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_ds_StringMap
#include <haxe/ds/StringMap.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_c190fe98d048b78e_811_new,"ResetSave","new",0x602b4b7e,"ResetSave.new","Options.hx",811,0x9d9a0240)
HX_LOCAL_STACK_FRAME(_hx_pos_c190fe98d048b78e_822_press,"ResetSave","press",0x698b5221,"ResetSave.press","Options.hx",822,0x9d9a0240)
HX_LOCAL_STACK_FRAME(_hx_pos_c190fe98d048b78e_909_updateDisplay,"ResetSave","updateDisplay",0xb0e85bd7,"ResetSave.updateDisplay","Options.hx",909,0x9d9a0240)
void ResetSave_obj::__construct(::String desc){
HX_STACKFRAME(&_hx_pos_c190fe98d048b78e_811_new)
HXLINE( 813) this->confirm = false;
HXLINE( 817) super::__construct();
HXLINE( 818) this->description = desc;
}
Dynamic ResetSave_obj::__CreateEmpty() { return new ResetSave_obj; }
void *ResetSave_obj::_hx_vtable = 0;
Dynamic ResetSave_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< ResetSave_obj > _hx_result = new ResetSave_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool ResetSave_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x27a70eb9) {
return inClassId==(int)0x00000001 || inClassId==(int)0x27a70eb9;
} else {
return inClassId==(int)0x54dd8e04;
}
}
bool ResetSave_obj::press(){
HX_STACKFRAME(&_hx_pos_c190fe98d048b78e_822_press)
HXLINE( 823) if (!(this->confirm)) {
HXLINE( 825) this->confirm = true;
HXLINE( 826) this->display = this->updateDisplay();
HXLINE( 827) return true;
}
HXLINE( 830) ::flixel::FlxG_obj::save->data->__SetField(HX_("language",58,80,11,7a),null(),::hx::paccDynamic);
HXLINE( 831) ::flixel::FlxG_obj::save->data->__SetField(HX_("weekUnlocked",37,64,c4,a5),null(),::hx::paccDynamic);
HXLINE( 832) ::flixel::FlxG_obj::save->data->__SetField(HX_("newInput",8a,07,68,e1),null(),::hx::paccDynamic);
HXLINE( 833) ::flixel::FlxG_obj::save->data->__SetField(HX_("downscroll",ef,45,d4,4f),null(),::hx::paccDynamic);
HXLINE( 834) ::flixel::FlxG_obj::save->data->__SetField(HX_("dfjk",c3,18,67,42),null(),::hx::paccDynamic);
HXLINE( 835) ::flixel::FlxG_obj::save->data->__SetField(HX_("accuracyDisplay",09,75,5e,26),null(),::hx::paccDynamic);
HXLINE( 836) ::flixel::FlxG_obj::save->data->__SetField(HX_("offset",93,97,3f,60),null(),::hx::paccDynamic);
HXLINE( 837) ::flixel::FlxG_obj::save->data->__SetField(HX_("songPosition",9e,dd,3b,8d),null(),::hx::paccDynamic);
HXLINE( 838) ::flixel::FlxG_obj::save->data->__SetField(HX_("fps",e9,c7,4d,00),null(),::hx::paccDynamic);
HXLINE( 839) ::flixel::FlxG_obj::save->data->__SetField(HX_("changedHit",bf,5d,c0,31),null(),::hx::paccDynamic);
HXLINE( 840) ::flixel::FlxG_obj::save->data->__SetField(HX_("fpsRain",dd,e5,17,c7),null(),::hx::paccDynamic);
HXLINE( 841) ::flixel::FlxG_obj::save->data->__SetField(HX_("fpsCap",a9,7b,7e,91),null(),::hx::paccDynamic);
HXLINE( 842) ::flixel::FlxG_obj::save->data->__SetField(HX_("scrollSpeed",3a,e0,46,cb),null(),::hx::paccDynamic);
HXLINE( 843) ::flixel::FlxG_obj::save->data->__SetField(HX_("npsDisplay",51,08,e2,23),null(),::hx::paccDynamic);
HXLINE( 844) ::flixel::FlxG_obj::save->data->__SetField(HX_("frames",a6,af,85,ac),null(),::hx::paccDynamic);
HXLINE( 845) ::flixel::FlxG_obj::save->data->__SetField(HX_("accuracyMod",09,b2,8a,86),null(),::hx::paccDynamic);
HXLINE( 846) ::flixel::FlxG_obj::save->data->__SetField(HX_("watermark",a4,af,1e,e0),null(),::hx::paccDynamic);
HXLINE( 847) ::flixel::FlxG_obj::save->data->__SetField(HX_("ghost",4f,8f,58,93),null(),::hx::paccDynamic);
HXLINE( 848) ::flixel::FlxG_obj::save->data->__SetField(HX_("distractions",31,13,7d,60),null(),::hx::paccDynamic);
HXLINE( 849) ::flixel::FlxG_obj::save->data->__SetField(HX_("flashing",32,85,e8,99),null(),::hx::paccDynamic);
HXLINE( 850) ::flixel::FlxG_obj::save->data->__SetField(HX_("resetButton",21,e5,f4,79),null(),::hx::paccDynamic);
HXLINE( 851) ::flixel::FlxG_obj::save->data->__SetField(HX_("botplay",7b,fb,a9,61),null(),::hx::paccDynamic);
HXLINE( 852) ::flixel::FlxG_obj::save->data->__SetField(HX_("gfCountdown",92,1a,b1,82),null(),::hx::paccDynamic);
HXLINE( 853) ::flixel::FlxG_obj::save->data->__SetField(HX_("zoom",13,a3,f8,50),null(),::hx::paccDynamic);
HXLINE( 854) ::flixel::FlxG_obj::save->data->__SetField(HX_("cacheCharacters",8c,1d,70,34),null(),::hx::paccDynamic);
HXLINE( 855) ::flixel::FlxG_obj::save->data->__SetField(HX_("cacheSongs",5c,9d,7f,c3),null(),::hx::paccDynamic);
HXLINE( 856) ::flixel::FlxG_obj::save->data->__SetField(HX_("cacheMusic",03,37,13,53),null(),::hx::paccDynamic);
HXLINE( 857) ::flixel::FlxG_obj::save->data->__SetField(HX_("cacheSounds",a6,d4,cf,50),null(),::hx::paccDynamic);
HXLINE( 858) ::flixel::FlxG_obj::save->data->__SetField(HX_("middleScroll",42,cd,58,62),null(),::hx::paccDynamic);
HXLINE( 859) ::flixel::FlxG_obj::save->data->__SetField(HX_("laneUnderlay",58,04,15,b5),null(),::hx::paccDynamic);
HXLINE( 860) ::flixel::FlxG_obj::save->data->__SetField(HX_("laneTransparency",24,32,52,af),null(),::hx::paccDynamic);
HXLINE( 861) ::flixel::FlxG_obj::save->data->__SetField(HX_("monibeaten",3c,53,44,8f),null(),::hx::paccDynamic);
HXLINE( 862) ::flixel::FlxG_obj::save->data->__SetField(HX_("sayobeaten",43,14,7b,f6),null(),::hx::paccDynamic);
HXLINE( 863) ::flixel::FlxG_obj::save->data->__SetField(HX_("natbeaten",00,2f,7a,be),null(),::hx::paccDynamic);
HXLINE( 864) ::flixel::FlxG_obj::save->data->__SetField(HX_("yuribeaten",32,30,34,69),null(),::hx::paccDynamic);
HXLINE( 865) ::flixel::FlxG_obj::save->data->__SetField(HX_("extrabeaten",ef,e9,0c,61),null(),::hx::paccDynamic);
HXLINE( 866) ::flixel::FlxG_obj::save->data->__SetField(HX_("extra2beaten",81,0c,3e,cc),null(),::hx::paccDynamic);
HXLINE( 867) ::flixel::FlxG_obj::save->data->__SetField(HX_("gfCountdown",92,1a,b1,82),null(),::hx::paccDynamic);
HXLINE( 868) ::flixel::FlxG_obj::save->data->__SetField(HX_("unlockepip",d6,39,27,23),null(),::hx::paccDynamic);
HXLINE( 869) ::flixel::FlxG_obj::save->data->__SetField(HX_("monipopup",ef,24,f0,3d),null(),::hx::paccDynamic);
HXLINE( 870) ::flixel::FlxG_obj::save->data->__SetField(HX_("sayopopup",c8,a1,66,3e),null(),::hx::paccDynamic);
HXLINE( 871) ::flixel::FlxG_obj::save->data->__SetField(HX_("natpopup",ab,ed,49,7d),null(),::hx::paccDynamic);
HXLINE( 872) ::flixel::FlxG_obj::save->data->__SetField(HX_("yuripopup",b9,98,c5,1e),null(),::hx::paccDynamic);
HXLINE( 873) ::flixel::FlxG_obj::save->data->__SetField(HX_("extra1popup",eb,9e,36,28),null(),::hx::paccDynamic);
HXLINE( 874) ::flixel::FlxG_obj::save->data->__SetField(HX_("extra2popup",4a,fb,91,8e),null(),::hx::paccDynamic);
HXLINE( 875) ::flixel::FlxG_obj::save->data->__SetField(HX_("funnyquestionpopup",bc,24,5f,b0),null(),::hx::paccDynamic);
HXLINE( 876) ::flixel::FlxG_obj::save->data->__SetField(HX_("upBind",b8,51,92,70),null(),::hx::paccDynamic);
HXLINE( 877) ::flixel::FlxG_obj::save->data->__SetField(HX_("downBind",3f,f3,fe,75),null(),::hx::paccDynamic);
HXLINE( 878) ::flixel::FlxG_obj::save->data->__SetField(HX_("leftBind",64,39,12,48),null(),::hx::paccDynamic);
HXLINE( 879) ::flixel::FlxG_obj::save->data->__SetField(HX_("rightBind",b9,4b,dd,ab),null(),::hx::paccDynamic);
HXLINE( 880) ::flixel::FlxG_obj::save->data->__SetField(HX_("gpupBind",a1,30,42,a5),null(),::hx::paccDynamic);
HXLINE( 881) ::flixel::FlxG_obj::save->data->__SetField(HX_("gpdownBind",68,1e,93,1d),null(),::hx::paccDynamic);
HXLINE( 882) ::flixel::FlxG_obj::save->data->__SetField(HX_("gpleftBind",8d,64,a6,ef),null(),::hx::paccDynamic);
HXLINE( 883) ::flixel::FlxG_obj::save->data->__SetField(HX_("gprightBind",70,e4,ee,a5),null(),::hx::paccDynamic);
HXLINE( 884) ::flixel::FlxG_obj::save->data->__SetField(HX_("songScores",96,1a,f0,a0),null(),::hx::paccDynamic);
HXLINE( 885) {
HXLINE( 885) ::Dynamic key = ::Highscore_obj::songScores->keys();
HXDLIN( 885) while(( (bool)(key->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 885) ::String key1 = ( (::String)(key->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 887) ::Highscore_obj::songScores->set(key1,0);
}
}
HXLINE( 890) ::flixel::FlxG_obj::save->flush(null(),null());
HXLINE( 893) ::Sys_obj::exit(0);
HXLINE( 902) this->confirm = false;
HXLINE( 903) this->display = this->updateDisplay();
HXLINE( 904) return true;
}
::String ResetSave_obj::updateDisplay(){
HX_STACKFRAME(&_hx_pos_c190fe98d048b78e_909_updateDisplay)
HXDLIN( 909) if (this->confirm) {
HXDLIN( 909) return ::LangUtil_obj::getString(HX_("optSaveResetConfirm",21,70,d4,25));
}
else {
HXDLIN( 909) return ::LangUtil_obj::getString(HX_("optSaveReset",9f,f6,55,1c));
}
HXDLIN( 909) return null();
}
::hx::ObjectPtr< ResetSave_obj > ResetSave_obj::__new(::String desc) {
::hx::ObjectPtr< ResetSave_obj > __this = new ResetSave_obj();
__this->__construct(desc);
return __this;
}
::hx::ObjectPtr< ResetSave_obj > ResetSave_obj::__alloc(::hx::Ctx *_hx_ctx,::String desc) {
ResetSave_obj *__this = (ResetSave_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(ResetSave_obj), true, "ResetSave"));
*(void **)__this = ResetSave_obj::_hx_vtable;
__this->__construct(desc);
return __this;
}
ResetSave_obj::ResetSave_obj()
{
}
::hx::Val ResetSave_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"press") ) { return ::hx::Val( press_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"confirm") ) { return ::hx::Val( confirm ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"updateDisplay") ) { return ::hx::Val( updateDisplay_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val ResetSave_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 7:
if (HX_FIELD_EQ(inName,"confirm") ) { confirm=inValue.Cast< bool >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void ResetSave_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("confirm",00,9d,39,10));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo ResetSave_obj_sMemberStorageInfo[] = {
{::hx::fsBool,(int)offsetof(ResetSave_obj,confirm),HX_("confirm",00,9d,39,10)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *ResetSave_obj_sStaticStorageInfo = 0;
#endif
static ::String ResetSave_obj_sMemberFields[] = {
HX_("confirm",00,9d,39,10),
HX_("press",83,53,88,c8),
HX_("updateDisplay",39,8f,b8,86),
::String(null()) };
::hx::Class ResetSave_obj::__mClass;
void ResetSave_obj::__register()
{
ResetSave_obj _hx_dummy;
ResetSave_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("ResetSave",8c,74,0c,34);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(ResetSave_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< ResetSave_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ResetSave_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ResetSave_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
| 50.7125 | 157 | 0.703393 | [
"3d"
] |
c4c9a6a80ef496bbb9d12a202e239ef22df83eb3 | 6,685 | hh | C++ | include/nba/framework/threadcontext.hh | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 61 | 2015-03-25T04:49:09.000Z | 2020-11-24T08:36:19.000Z | include/nba/framework/threadcontext.hh | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 32 | 2015-04-29T08:20:39.000Z | 2017-02-09T22:49:37.000Z | include/nba/framework/threadcontext.hh | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 11 | 2015-07-24T22:48:05.000Z | 2020-09-10T11:48:47.000Z | #ifndef __NBA_THREADCONTEXT_HH__
#define __NBA_THREADCONTEXT_HH__
#include <nba/core/intrinsic.hh>
#include <nba/core/queue.hh>
#include <nba/framework/config.hh>
#include <cstdint>
#include <cstdbool>
#include <string>
#include <set>
#include <vector>
#include <unordered_map>
#include <functional>
#include <pthread.h>
#include <unistd.h>
#include <ev.h>
#include <rte_config.h>
#include <rte_atomic.h>
#include <rte_ring.h>
#include <rte_ether.h>
namespace nba {
/* forward declarations */
class CondVar;
class CountedBarrier;
class Lock;
class Element;
class PacketBatch;
class DataBlock;
class SystemInspector;
class ElementGraph;
class ComputeDevice;
class ComputeContext;
class NodeLocalStorage;
class OffloadTask;
class comp_thread_context;
struct io_port_stat;
struct core_location {
unsigned node_id;
unsigned core_id; /** system-global core index (used thread pinning) */
unsigned local_thread_idx; /** node-local thread index (used to access data structures) */
unsigned global_thread_idx; /** global thread index (used to access data structures) */
} __cache_aligned;
struct port_info {
unsigned port_idx;
struct ether_addr addr;
} __cache_aligned;
struct new_packet
{
char buf[NBA_MAX_PACKET_SIZE];
size_t len;
int out_port;
};
/* Thread arguments for each types of thread */
struct io_thread_context {
struct ev_async *terminate_watcher;
CondVar *init_cond;
bool *init_done;
Lock *io_lock;
char _reserved0[64]; // to prevent false-sharing
struct core_location loc;
struct ev_loop *loop;
bool loop_broken;
unsigned num_hw_rx_queues;
unsigned num_tx_ports;
unsigned num_iobatch_size;
unsigned num_io_threads;
uint64_t last_tx_tick;
uint64_t global_tx_cnt;
uint64_t tx_pkt_thruput;
uint64_t LB_THRUPUT_WINDOW_SIZE;
int emul_packet_size;
int emul_ip_version;
int mode;
struct hwrxq rx_hwrings[NBA_MAX_PORTS * NBA_MAX_QUEUES_PER_PORT];
struct ev_timer *stat_timer;
struct io_port_stat *port_stats;
struct io_thread_context *node_master_ctx;
#ifdef NBA_CPU_MICROBENCH
int papi_evset_rx;
int papi_evset_tx;
int papi_evset_comp;
long long papi_ctr_rx[5];
long long papi_ctr_tx[5];
long long papi_ctr_comp[5];
#endif
char _reserved1[64];
struct rte_ring *rx_queue;
struct ev_async *rx_watcher;
struct port_info tx_ports[NBA_MAX_PORTS];
comp_thread_context *comp_ctx;
char _reserved2[64]; // to prevent false-sharing
struct rte_ring *drop_queue;
struct rte_ring *tx_queues[NBA_MAX_PORTS];
struct rte_mempool* rx_pools[NBA_MAX_PORTS];
struct rte_mempool* emul_rx_packet_pool = nullptr;
struct rte_mempool* new_packet_pool = nullptr;
struct rte_mempool* new_packet_request_pool = nullptr;
struct rte_ring* new_packet_request_ring = nullptr;
char _reserved3[64]; // to prevent false-sharing
pid_t thread_id;
CondVar *block;
bool is_block;
unsigned int random_seed;
char _reserved4[64]; /* prevent false-sharing */
rte_atomic16_t *node_master_flag;
struct ev_async *node_stat_watcher;
struct io_node_stat *node_stat;
} __cache_aligned;
class comp_thread_context {
public:
comp_thread_context();
virtual ~comp_thread_context();
void stop_rx();
void resume_rx();
void build_element_graph(const char* config); // builds element graph
void initialize_graph_global();
void initialize_graph_per_node();
void initialize_graph_per_thread();
void initialize_offloadables_per_node(ComputeDevice *device);
void io_tx_new(void* data, size_t len, int out_port);
public:
struct ev_async *terminate_watcher;
CountedBarrier *thread_init_barrier;
CondVar *ready_cond;
bool *ready_flag;
Lock *elemgraph_lock;
NodeLocalStorage *node_local_storage;
char _reserved1[64]; /* prevent false-sharing */
struct ev_loop *loop;
struct core_location loc;
unsigned num_tx_ports;
unsigned num_nodes;
unsigned num_coproc_ppdepth;
unsigned num_combatch_size;
unsigned num_batchpool_size;
unsigned num_taskpool_size;
unsigned task_completion_queue_size;
bool preserve_latency;
struct rte_mempool *batch_pool;
struct rte_mempool *dbstate_pool;
struct rte_mempool *task_pool;
struct rte_mempool *packet_pool;
ElementGraph *elem_graph;
SystemInspector *inspector;
FixedRing<ComputeContext *> *cctx_list;
PacketBatch *input_batch;
DataBlock *datablock_registry[NBA_MAX_DATABLOCKS];
bool stop_task_batching;
struct rte_ring *rx_queue;
struct ev_async *rx_watcher;
struct coproc_thread_context *coproc_ctx;
char _reserved2[64]; /* prevent false-sharing */
struct io_thread_context *io_ctx;
std::unordered_map<std::string, ComputeDevice *> *named_offload_devices;
std::vector<ComputeDevice*> *offload_devices;
struct rte_ring *offload_input_queues[NBA_MAX_COPROCESSORS]; /* ptr to per-device task input queue */
char _reserved3[64]; /* prevent false-sharing */
struct rte_ring *task_completion_queue; /* to receive completed offload tasks */
struct ev_async *task_completion_watcher;
struct ev_check *check_watcher;
} __cache_aligned;
struct coproc_thread_context {
struct ev_async *terminate_watcher;
CountedBarrier *thread_init_done_barrier;
CountedBarrier *offloadable_init_barrier;
CountedBarrier *offloadable_init_done_barrier;
CountedBarrier *loopstart_barrier;
struct ev_async *offloadable_init_watcher;
comp_thread_context *comp_ctx_to_init_offloadable;
char _reserved1[64]; // to prevent false-sharing
struct core_location loc;
struct ev_loop *loop;
bool loop_broken;
unsigned device_id;
unsigned num_comp_threads_per_node;
unsigned task_input_queue_size;
ComputeDevice *device;
struct ev_async *task_d2h_watcher;
FixedRing<OffloadTask *> *d2h_pending_queue;
FixedRing<OffloadTask *> *task_done_queue;
struct ev_async *task_done_watcher;
char _reserved2[64]; // to prevent false-sharing
struct rte_ring *task_input_queue;
struct ev_async *task_input_watcher;
char _reserved3[64]; // to prevent false-sharing
} __cache_aligned;
struct spawned_thread {
pthread_t tid;
struct ev_async *terminate_watcher;
union {
struct io_thread_context *io_ctx;
struct comp_thread_context *comp_ctx;
struct coproc_thread_context *coproc_ctx;
};
} __cache_aligned;
struct thread_collection {
struct spawned_thread *io_threads;
unsigned num_io_threads;
} __cache_aligned;
}
#endif
// vim: ts=8 sts=4 sw=4 et
| 27.285714 | 105 | 0.744353 | [
"vector"
] |
c4cd4e56f42a514fe3f9f02998965e720583e0c7 | 3,087 | cpp | C++ | dali/internal/canvas-renderer/ubuntu/picture-impl-ubuntu.cpp | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2016-11-18T10:26:46.000Z | 2021-11-01T12:29:05.000Z | dali/internal/canvas-renderer/ubuntu/picture-impl-ubuntu.cpp | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2020-07-15T11:30:49.000Z | 2020-12-11T19:13:46.000Z | dali/internal/canvas-renderer/ubuntu/picture-impl-ubuntu.cpp | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2019-05-17T07:14:40.000Z | 2021-05-24T07:25:26.000Z | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/internal/canvas-renderer/ubuntu/picture-impl-ubuntu.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/public-api/object/type-registry.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace // unnamed namespace
{
// Type Registration
Dali::BaseHandle Create()
{
return Dali::BaseHandle();
}
Dali::TypeRegistration type(typeid(Dali::CanvasRenderer::Picture), typeid(Dali::BaseHandle), Create);
} // unnamed namespace
PictureUbuntu* PictureUbuntu::New()
{
return new PictureUbuntu();
}
PictureUbuntu::PictureUbuntu()
#ifdef THORVG_SUPPORT
: mTvgPicture(nullptr)
#endif
{
Initialize();
}
PictureUbuntu::~PictureUbuntu()
{
}
void PictureUbuntu::Initialize()
{
#ifdef THORVG_SUPPORT
mTvgPicture = tvg::Picture::gen().release();
if(!mTvgPicture)
{
DALI_LOG_ERROR("Picture is null [%p]\n", this);
}
Drawable::Create();
Drawable::SetObject(static_cast<void*>(mTvgPicture));
Drawable::SetType(Drawable::Types::PICTURE);
#endif
}
bool PictureUbuntu::Load(const std::string& url)
{
#ifdef THORVG_SUPPORT
if(!Drawable::GetObject() || !mTvgPicture)
{
DALI_LOG_ERROR("Picture is null [%p]\n", this);
return false;
}
if(url.empty())
{
DALI_LOG_ERROR("Url is empty [%p]\n", this);
return false;
}
if(mTvgPicture->load(url.c_str()) != tvg::Result::Success)
{
DALI_LOG_ERROR("Load() fail. (%s)\n", url.c_str());
return false;
}
Drawable::SetChanged(true);
return true;
#else
return false;
#endif
}
bool PictureUbuntu::SetSize(Vector2 size)
{
#ifdef THORVG_SUPPORT
if(!Drawable::GetObject() || !mTvgPicture)
{
DALI_LOG_ERROR("Picture is null [%p]\n", this);
return false;
}
if(mTvgPicture->size(size.width, size.height) != tvg::Result::Success)
{
DALI_LOG_ERROR("SetSize() fail.\n");
return false;
}
Drawable::SetChanged(true);
return true;
#else
return false;
#endif
}
Vector2 PictureUbuntu::GetSize() const
{
#ifdef THORVG_SUPPORT
if(!Drawable::GetObject() || !mTvgPicture)
{
DALI_LOG_ERROR("Picture is null [%p]\n", this);
return Vector2::ZERO;
}
auto width = 0.0f;
auto height = 0.0f;
if(mTvgPicture->size(&width, &height) != tvg::Result::Success)
{
DALI_LOG_ERROR("GetSize() fail.\n");
return Vector2::ZERO;
}
return Vector2(width, height);
#else
return Vector2::ZERO;
#endif
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
| 20.309211 | 101 | 0.690638 | [
"object"
] |
c4cec1ee570e2d7197b629005a7d354e1f84186a | 4,899 | cpp | C++ | tests/test-mp2p_optimize_pt2pl.cpp | MOLAorg/mp2_icp | e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb | [
"BSD-3-Clause"
] | 3 | 2019-06-07T08:10:09.000Z | 2019-06-07T15:01:02.000Z | tests/test-mp2p_optimize_pt2pl.cpp | MOLAorg/mp2_icp | e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb | [
"BSD-3-Clause"
] | null | null | null | tests/test-mp2p_optimize_pt2pl.cpp | MOLAorg/mp2_icp | e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb | [
"BSD-3-Clause"
] | null | null | null | /* -------------------------------------------------------------------------
* A Modular Optimization framework for Localization and mApping (MOLA)
* Copyright (C) 2018-2021 Jose Luis Blanco, University of Almeria
* See LICENSE for license information.
* ------------------------------------------------------------------------- */
/**
* @file test-mp2p_optimize_pt2pl.cpp
* @brief Unit tests for point-to-plane optimization
* @author Jose Luis Blanco Claraco
* @date Dec 4, 2021
*/
#include <mp2p_icp/Solver_GaussNewton.h>
#include <mp2p_icp/Solver_Horn.h>
#include <mrpt/poses/Lie/SE.h>
static void test_opt_pt2pl(
const mrpt::poses::CPose3D& groundTruth, const mp2p_icp::Solver& solver)
{
using namespace mrpt::poses::Lie;
MRPT_START
// Prepare test case pairings:
// 3 point-to-plane correspondences, such that the sought optimal
// pose is the given one:
mp2p_icp::Pairings p;
{
auto& pp = p.paired_pt2pl.emplace_back();
pp.pl_global = {
mrpt::math::TPlane::FromPointAndNormal({0, 0, 0}, {0, 0, 1}),
{0, 0, 0}};
pp.pt_local = groundTruth.inverseComposePoint({0.5, 0, 0});
}
{
auto& pp = p.paired_pt2pl.emplace_back();
pp.pl_global = {
mrpt::math::TPlane::FromPointAndNormal({0, 0, 0}, {1, 0, 0}),
{0, 0, 0}};
pp.pt_local = groundTruth.inverseComposePoint({0, 0.8, 0});
}
{
auto& pp = p.paired_pt2pl.emplace_back();
pp.pl_global = {
mrpt::math::TPlane::FromPointAndNormal({0, 0, 0}, {0, 1, 0}),
{0, 0, 0}};
pp.pt_local = groundTruth.inverseComposePoint({0, 0, 0.3});
}
{
auto& pp = p.paired_pt2pt.emplace_back();
pp.global = {0, 0, 0};
const auto loc = groundTruth.inverseComposePoint({0, 0, 0});
pp.local = loc;
}
std::cout << "Input pairings: " << p.contents_summary() << std::endl;
// Init solver:
mp2p_icp::OptimalTF_Result result;
mp2p_icp::SolverContext sc;
sc.guessRelativePose = mrpt::poses::CPose3D::Identity();
bool solvedOk = solver.optimal_pose(p, result, sc);
std::cout << "Found optimalPose: " << result.optimalPose << std::endl;
std::cout << "Expected optimalPose: " << groundTruth << std::endl;
// check results:
ASSERT_(solvedOk);
ASSERT_NEAR_(
mrpt::poses::Lie::SE<3>::log(result.optimalPose - groundTruth).norm(),
0.0, 1e-3);
MRPT_END
}
static void test_mp2p_optimize_pt2pl()
{
using mrpt::poses::CPose3D;
using namespace mrpt; // _deg
// With different solvers:
mp2p_icp::Solver_GaussNewton solverGN;
{
mrpt::containers::yaml solverParams;
solverParams["maxIterations"] = 25;
// solverParams["innerLoopVerbose"] = true;
solverGN.initialize(solverParams);
}
// mp2p_icp::Solver_Horn solverHorn;
const std::vector<const mp2p_icp::Solver*> solvers = {
&solverGN,
//&solverHorn
};
for (const auto solverPtr : solvers)
{
const auto& solver = *solverPtr;
std::cout
<< "Using solver: " << solver.GetRuntimeClass()->className
<< "\n"
"=========================================================\n";
test_opt_pt2pl(CPose3D::FromTranslation(0, 0, 0), solver);
test_opt_pt2pl(CPose3D::FromTranslation(1.0, 0, 0), solver);
test_opt_pt2pl(CPose3D::FromTranslation(0, 1.0, 0), solver);
test_opt_pt2pl(CPose3D::FromTranslation(0, 0, 1.0), solver);
test_opt_pt2pl(CPose3D::FromTranslation(-2.0, 0, 0), solver);
test_opt_pt2pl(CPose3D::FromTranslation(0, -3.0, 0), solver);
test_opt_pt2pl(CPose3D::FromTranslation(0, 0, -4.0), solver);
test_opt_pt2pl(
CPose3D::FromYawPitchRoll(20.0_deg, 0.0_deg, 0.0_deg), solver);
test_opt_pt2pl(
CPose3D::FromYawPitchRoll(-20.0_deg, 0.0_deg, 0.0_deg), solver);
test_opt_pt2pl(
CPose3D::FromYawPitchRoll(0.0_deg, 10.0_deg, 0.0_deg), solver);
test_opt_pt2pl(
CPose3D::FromYawPitchRoll(0.0_deg, -10.0_deg, 0.0_deg), solver);
test_opt_pt2pl(
CPose3D::FromYawPitchRoll(0.0_deg, 0.0_deg, 15.0_deg), solver);
test_opt_pt2pl(
CPose3D::FromYawPitchRoll(0.0_deg, 0.0_deg, -15.0_deg), solver);
test_opt_pt2pl(CPose3D::FromTranslation(1.0, 2.0, 3.0), solver);
test_opt_pt2pl(
CPose3D::FromXYZYawPitchRoll(
1.0, 2.0, 3.0, -10.0_deg, 5.0_deg, 30.0_deg),
solver);
}
}
int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
{
try
{
test_mp2p_optimize_pt2pl();
}
catch (std::exception& e)
{
std::cerr << mrpt::exception_to_str(e) << "\n";
return 1;
}
}
| 31.811688 | 79 | 0.571137 | [
"vector"
] |
c4d1bba954cc19f436720b524250f156c1c7621e | 3,006 | cpp | C++ | mlir/lib/ExecutionEngine/AsyncRuntime.cpp | hanzhan1/llvm | efe40bb5c797b102088e3cd2579a0f57ccf93310 | [
"Apache-2.0"
] | null | null | null | mlir/lib/ExecutionEngine/AsyncRuntime.cpp | hanzhan1/llvm | efe40bb5c797b102088e3cd2579a0f57ccf93310 | [
"Apache-2.0"
] | null | null | null | mlir/lib/ExecutionEngine/AsyncRuntime.cpp | hanzhan1/llvm | efe40bb5c797b102088e3cd2579a0f57ccf93310 | [
"Apache-2.0"
] | null | null | null | //===- AsyncRuntime.cpp - Async runtime reference implementation ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements basic Async runtime API for supporting Async dialect
// to LLVM dialect lowering.
//
//===----------------------------------------------------------------------===//
#include "mlir/ExecutionEngine/AsyncRuntime.h"
#ifdef MLIR_ASYNCRUNTIME_DEFINE_FUNCTIONS
#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
//===----------------------------------------------------------------------===//
// Async runtime API.
//===----------------------------------------------------------------------===//
struct AsyncToken {
bool ready = false;
std::mutex mu;
std::condition_variable cv;
std::vector<std::function<void()>> awaiters;
};
// Create a new `async.token` in not-ready state.
extern "C" MLIR_ASYNCRUNTIME_EXPORT AsyncToken *mlirAsyncRuntimeCreateToken() {
AsyncToken *token = new AsyncToken;
return token;
}
// Switches `async.token` to ready state and runs all awaiters.
extern "C" MLIR_ASYNCRUNTIME_EXPORT void
mlirAsyncRuntimeEmplaceToken(AsyncToken *token) {
std::unique_lock<std::mutex> lock(token->mu);
token->ready = true;
token->cv.notify_all();
for (auto &awaiter : token->awaiters)
awaiter();
}
extern "C" MLIR_ASYNCRUNTIME_EXPORT void
mlirAsyncRuntimeAwaitToken(AsyncToken *token) {
std::unique_lock<std::mutex> lock(token->mu);
if (!token->ready)
token->cv.wait(lock, [token] { return token->ready; });
delete token;
}
extern "C" MLIR_ASYNCRUNTIME_EXPORT void
mlirAsyncRuntimeExecute(CoroHandle handle, CoroResume resume) {
#if LLVM_ENABLE_THREADS
std::thread thread([handle, resume]() { (*resume)(handle); });
thread.detach();
#else
(*resume)(handle);
#endif
}
extern "C" MLIR_ASYNCRUNTIME_EXPORT void
mlirAsyncRuntimeAwaitTokenAndExecute(AsyncToken *token, CoroHandle handle,
CoroResume resume) {
std::unique_lock<std::mutex> lock(token->mu);
auto execute = [token, handle, resume]() {
mlirAsyncRuntimeExecute(handle, resume);
delete token;
};
if (token->ready)
execute();
else
token->awaiters.push_back([execute]() { execute(); });
}
//===----------------------------------------------------------------------===//
// Small async runtime support library for testing.
//===----------------------------------------------------------------------===//
extern "C" MLIR_ASYNCRUNTIME_EXPORT void
mlirAsyncRuntimePrintCurrentThreadId() {
static thread_local std::thread::id thisId = std::this_thread::get_id();
std::cout << "Current thread id: " << thisId << "\n";
}
#endif // MLIR_ASYNCRUNTIME_DEFINE_FUNCTIONS
| 30.989691 | 80 | 0.601131 | [
"vector"
] |
c4d3de7b45b6ab2cbccfe928b60535d12c217325 | 3,641 | cpp | C++ | src/XCurses/Graphics/Border.cpp | LazyMechanic/XCurses | 3880f006245b6c6795833741e4cd45944e0229f8 | [
"Apache-2.0"
] | null | null | null | src/XCurses/Graphics/Border.cpp | LazyMechanic/XCurses | 3880f006245b6c6795833741e4cd45944e0229f8 | [
"Apache-2.0"
] | null | null | null | src/XCurses/Graphics/Border.cpp | LazyMechanic/XCurses | 3880f006245b6c6795833741e4cd45944e0229f8 | [
"Apache-2.0"
] | null | null | null | #include <XCurses/Graphics/Border.h>
#include <algorithm>
#include <XCurses/System/Context.h>
#include <XCurses/Graphics/Container.h>
namespace xcur {
const BorderTraits BorderTraits::Blank = {
Char(' '),
Char(' '),
Char(' '),
Char(' '),
Char(' '),
Char(' '),
Char(' '),
Char(' ') };
const BorderTraits BorderTraits::Simple = {
Char('|'),
Char('|'),
Char('-'),
Char('-'),
Char('+'),
Char('+'),
Char('+'),
Char('+') };
const BorderTraits BorderTraits::Default = {
Char(0x2502),
Char(0x2502),
Char(0x2500),
Char(0x2500),
Char(0x250c),
Char(0x2510),
Char(0x2514),
Char(0x2518) };
const BorderTraits BorderTraits::Wide = {
Char(0x2551),
Char(0x2551),
Char(0x2550),
Char(0x2550),
Char(0x2554),
Char(0x2557),
Char(0x255a),
Char(0x255d) };
Object::Ptr<Border> Border::create()
{
return Border::create(BorderTraits::Blank);
}
Object::Ptr<Border> Border::create(const Char& ch)
{
BorderTraits bt = {
ch,
ch,
ch,
ch,
ch,
ch,
ch,
ch
};
return Border::create(bt);
}
Object::Ptr<Border> Border::create(const BorderTraits& borderTraits)
{
return std::shared_ptr<Border>(new Border(borderTraits));
}
void Border::draw() const
{
auto context = getContext();
auto parent = getParent();
if (context != nullptr &&
parent != nullptr) {
// Draw verticals
Vector2i topSidePosition = Vector2i::Zero;
Vector2i bottomSidePosition = Vector2i(0, std::max<uint32_t>(static_cast<int32_t>(parent->getSize().y) - 1, 0));
for (uint32_t i = 1; i < parent->getSize().x; ++i) {
topSidePosition.x = i;
bottomSidePosition.x = i;
context->addToVirtualScreen(shared_from_this(), borderTraits.topSide, topSidePosition);
context->addToVirtualScreen(shared_from_this(), borderTraits.bottomSide, bottomSidePosition);
}
// Draw horizontals
Vector2i leftSidePosition = Vector2i::Zero;
Vector2i rightSidePosition = Vector2i(std::max<uint32_t>(static_cast<int32_t>(parent->getSize().x) - 1, 0), 0);
for (uint32_t i = 1; i < parent->getSize().y; ++i) {
leftSidePosition.y = i;
rightSidePosition.y = i;
context->addToVirtualScreen(shared_from_this(), borderTraits.leftSide, leftSidePosition);
context->addToVirtualScreen(shared_from_this(), borderTraits.rightSide, rightSidePosition);
}
// Draw corners
Vector2i topLeftCornerPosition = Vector2i::Zero;
Vector2i topRightCornerPosition = Vector2i(std::max<uint32_t>(static_cast<int32_t>(parent->getSize().x) - 1, 0), 0);
Vector2i bottomLeftCornerPosition = Vector2i(0, std::max<uint32_t>(static_cast<int32_t>(parent->getSize().y) - 1, 0));
Vector2i bottomRightCornerPosition = Vector2i(std::max<uint32_t>(static_cast<int32_t>(parent->getSize().x) - 1, 0), std::max<uint32_t>(static_cast<int32_t>(parent->getSize().y) - 1, 0));
context->addToVirtualScreen(shared_from_this(), borderTraits.topLeftCorner, topLeftCornerPosition);
context->addToVirtualScreen(shared_from_this(), borderTraits.topRightCorner, topRightCornerPosition);
context->addToVirtualScreen(shared_from_this(), borderTraits.bottomLeftCorner, bottomLeftCornerPosition);
context->addToVirtualScreen(shared_from_this(), borderTraits.bottomRightCorner, bottomRightCornerPosition);
}
}
Border::Border(const BorderTraits& borderTraits) :
borderTraits(borderTraits)
{
}
}
| 30.855932 | 194 | 0.637737 | [
"object"
] |
c4d74f4ab1d3b66f48c52544c3c620f4a6bc7be7 | 3,989 | cpp | C++ | AdventOfCode2019/src/advent_p7.cpp | ooterness/AdventOfCode | a07846caa758891570986e0ec97d1f06c5baceb0 | [
"BSD-3-Clause"
] | null | null | null | AdventOfCode2019/src/advent_p7.cpp | ooterness/AdventOfCode | a07846caa758891570986e0ec97d1f06c5baceb0 | [
"BSD-3-Clause"
] | null | null | null | AdventOfCode2019/src/advent_p7.cpp | ooterness/AdventOfCode | a07846caa758891570986e0ec97d1f06c5baceb0 | [
"BSD-3-Clause"
] | null | null | null | // Advent of Code 2019, Day 7
// Copyright 2020 by Alex Utter
// https://adventofcode.com/2019/day/7
#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include "intcode.h"
struct Amplifier
{
Amplifier(const Program& ref, int phase)
: m_prog(ref)
, m_phase(phase)
, m_first(1)
{
// Nothing else to initialize.
}
// Continue program until next output.
int iterate(int input)
{
// Configure the input pipe.
std::stringstream strm_in;
if (m_first) {
strm_in << m_phase << ",";
m_first = 0;
}
strm_in << input;
// Continue program until next output.
int64_t output = -1;
m_prog.run_next(&strm_in, output);
return (int)output;
}
Program m_prog;
int m_phase;
int m_first;
};
typedef std::vector<int> PhaseConfig;
struct AmplifierChain
{
// Create a chain of amplifiers and set initial conditions.
AmplifierChain(const Program& ref, const PhaseConfig& phase)
{
for (PhaseConfig::const_iterator it = phase.begin() ; it != phase.end() ; ++it)
m_chain.push_back(Amplifier(ref, *it));
}
// Run the entire chain once.
int iterate(int next)
{
for (unsigned a = 0 ; a < m_chain.size() ; ++a)
next = m_chain[a].iterate(next);
return next;
}
std::vector<Amplifier> m_chain;
};
int max_thrust_part1(const Program& ref)
{
// Set baseline phase configuration = 0,1,2,3,4
PhaseConfig cfg(5);
for (unsigned a = 0 ; a < 5 ; ++a) cfg[a] = a;
// Lexicographic search of all possible permutations.
int max_thrust = 0;
do {
// Create a new chain and run each one once.
AmplifierChain chain(ref, cfg);
int thrust = chain.iterate(0);
if (thrust > max_thrust)
max_thrust = thrust;
} while (next_permutation(cfg.begin(), cfg.end()));
return max_thrust;
}
int max_thrust_part2(const Program& ref)
{
// Set baseline phase configuration = 5,6,7,8,9
PhaseConfig cfg(5);
for (unsigned a = 0 ; a < 5 ; ++a) cfg[a] = a+5;
// Lexicographic search of all possible permutations.
int max_thrust = 0;
do {
// Create a new chain and iterate until finished.
AmplifierChain chain(ref, cfg);
int thrust = 0;
while (thrust >= 0) {
thrust = chain.iterate(thrust);
if (thrust > max_thrust)
max_thrust = thrust;
}
} while (next_permutation(cfg.begin(), cfg.end()));
return max_thrust;
}
int main()
{
// Define each of the programs.
Program test1("3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0");
Program test2("3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0");
Program test3("3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0");
Program test4("3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5");
Program test5("3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,"\
"54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10");
Program thruster("advent_p7.txt", 1); // Load from file
// Unit tests for the forward search function.
assert (max_thrust_part1(test1) == 43210);
assert (max_thrust_part1(test2) == 54321);
assert (max_thrust_part1(test3) == 65210);
// Find the part-1 solution.
std::cout << "Max forward thrust = " << max_thrust_part1(thruster) << std::endl;
// Unit tests for the feedback search function.
assert (max_thrust_part2(test4) == 139629729);
assert (max_thrust_part2(test5) == 18216);
// Find the part-1 solution.
std::cout << "Max feedback thrust = " << max_thrust_part2(thruster) << std::endl;
return 0;
}
| 29.116788 | 121 | 0.600902 | [
"vector"
] |
c4e35147b0660506fa0293099da53ccceacca48d | 1,462 | cc | C++ | cc/puzzle_21_0/main.cc | craig-chasseur/aoc2019 | e2bed89deef4cabc37ff438dd7d26efe0187500b | [
"MIT"
] | null | null | null | cc/puzzle_21_0/main.cc | craig-chasseur/aoc2019 | e2bed89deef4cabc37ff438dd7d26efe0187500b | [
"MIT"
] | null | null | null | cc/puzzle_21_0/main.cc | craig-chasseur/aoc2019 | e2bed89deef4cabc37ff438dd7d26efe0187500b | [
"MIT"
] | null | null | null | #include <cstdint>
#include <iostream>
#include <vector>
#include "cc/util/intcode.h"
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "USAGE: main FILENAME\n";
return 1;
}
aoc2019::IntcodeMachine machine(aoc2019::ReadIntcodeProgram(argv[1]));
// JumpScript solution reasoning:
// 1. It's only possible to jump if D is ground.
// 2. You *must* jump if A is a hole.
// 3. If B is a hole, you must either jump now or in +1 turn.
// 4. If C is a hole, you must either jump now, at +1 turn, or +2 turn.
// 5. It is impossible to know if it will be safe to jump in +1 turn or +2
// turn. If you need to jump in the next couple of turns (i.e. A, B, or C
// is a hole) it is safe to jump now (i.e. D is ground), then you should;
// you will land on ground and you will not miss an opportune landing
// that you might have been able to make by waiting, since you would be
// able to reach the same spot by just walking forward.
// 6. You should not jump if you are not compelled to by holes in the next
// 3 spots. Doing so might land you in a position where both A and D are
// holes.
//
// This works out to J = (!A || !B || !C) && D
// Applying De Morgan's laws: J = !(A && B && C) && D
// Expressed in jumpscript this is:
//
// OR A J
// AND B J
// AND C J
// NOT J J
// AND D J
// WALK
machine.RunWithAsciiConsoleIO();
return 0;
}
| 34 | 80 | 0.611491 | [
"vector"
] |
c4e710d85a55af20f4b6429d811a03adb210a313 | 7,025 | cpp | C++ | src/fgseaMultilevelSupplement.cpp | auberginekenobi/fgsea | 159929a7262938f4aa0be75ddce89ad0a32a9cc7 | [
"MIT"
] | null | null | null | src/fgseaMultilevelSupplement.cpp | auberginekenobi/fgsea | 159929a7262938f4aa0be75ddce89ad0a32a9cc7 | [
"MIT"
] | null | null | null | src/fgseaMultilevelSupplement.cpp | auberginekenobi/fgsea | 159929a7262938f4aa0be75ddce89ad0a32a9cc7 | [
"MIT"
] | null | null | null | #include "fgseaMultilevelSupplement.h"
#include "esCalculation.h"
double betaMeanLog(unsigned long a, unsigned long b) {
return boost::math::digamma(a) - boost::math::digamma(b + 1);
}
pair<double, bool> calcLogCorrection(const vector<unsigned int> &probCorrector, long probCorrIndx,
const pair<unsigned int, unsigned int> posUnifScoreCount, unsigned int sampleSize){
double result = 0.0;
result -= betaMeanLog(posUnifScoreCount.first, posUnifScoreCount.second);
unsigned long halfSize = (sampleSize + 1) / 2;
unsigned long remainder = sampleSize - probCorrIndx % (halfSize);
double condProb = betaMeanLog(probCorrector[probCorrIndx] + 1, remainder);
result += condProb;
if (exp(condProb) >= 0.5){
return make_pair(result, true);
}
else{
return make_pair(result, false);
}
}
void fillRandomSample(set<int> &randomSample, mt19937 &gen,
const unsigned long ranksSize, const unsigned int pathwaySize) {
randomSample.clear();
uniform_int_distribution<> uid_n(0, static_cast<int>(ranksSize - 1));
while (static_cast<int>(randomSample.size()) < pathwaySize) {
randomSample.insert(uid_n(gen));
}
}
EsRuler::EsRuler(const vector<double> &inpRanks, unsigned int inpSampleSize, unsigned int inpPathwaySize) :
ranks(inpRanks), sampleSize(inpSampleSize), pathwaySize(inpPathwaySize) {
posUnifScoreCount = make_pair(0, 0);
currentSamples.resize(inpSampleSize);
}
EsRuler::~EsRuler() = default;
void EsRuler::duplicateSamples() {
/*
* Removes samples with an enrichment score less than the median value and
* replaces them with samples with an enrichment score greater than the median
* value
*/
vector<pair<double, int> > stats(sampleSize);
vector<int> posEsIndxs;
int totalPosEsCount = 0;
for (int sampleId = 0; sampleId < sampleSize; sampleId++) {
double sampleEsPos = calcPositiveES(ranks, currentSamples[sampleId]);
double sampleEs = calcES(ranks, currentSamples[sampleId]);
if (sampleEs > 0) {
totalPosEsCount++;
posEsIndxs.push_back(sampleId);
}
stats[sampleId] = make_pair(sampleEsPos, sampleId);
}
sort(stats.begin(), stats.end());
for (int sampleId = 0; 2 * sampleId < sampleSize; sampleId++) {
enrichmentScores.push_back(stats[sampleId].first);
if (find(posEsIndxs.begin(), posEsIndxs.end(), stats[sampleId].second) != posEsIndxs.end()) {
totalPosEsCount--;
}
probCorrector.push_back(totalPosEsCount);
}
vector<vector<int> > new_sets;
for (int sampleId = 0; 2 * sampleId < sampleSize - 2; sampleId++) {
for (int rep = 0; rep < 2; rep++) {
new_sets.push_back(currentSamples[stats[sampleSize - 1 - sampleId].second]);
}
}
new_sets.push_back(currentSamples[stats[sampleSize >> 1].second]);
swap(currentSamples, new_sets);
}
void EsRuler::extend(double ES, int seed, double absEps) {
unsigned int posCount = 0;
unsigned int totalCount = 0;
mt19937 gen(seed);
for (int sampleId = 0; sampleId < sampleSize; sampleId++) {
set<int> randomSample;
fillRandomSample(randomSample, gen, ranks.size(), pathwaySize);
currentSamples[sampleId] = vector<int>(randomSample.begin(), randomSample.end());
double currentES = calcES(ranks, currentSamples[sampleId]);
while (currentES <= 0) {
fillRandomSample(randomSample, gen, ranks.size(), pathwaySize);
currentES = calcES(ranks, vector<int>(randomSample.begin(), randomSample.end()));
totalCount++;
}
posCount++;
totalCount++;
}
posUnifScoreCount = make_pair(posCount, totalCount);
duplicateSamples();
while (ES > enrichmentScores.back()){
for (int moves = 0; moves < sampleSize * pathwaySize;) {
for (int sample_id = 0; sample_id < sampleSize; sample_id++) {
moves += perturbate(ranks, currentSamples[sample_id], enrichmentScores.back(), gen);
}
}
duplicateSamples();
if (absEps != 0){
unsigned long k = enrichmentScores.size() / ((sampleSize + 1) / 2);
if (k > - log2(0.5 * absEps * exp(betaMeanLog(posUnifScoreCount.first, posUnifScoreCount.second)))) {
break;
}
}
}
}
pair<double, bool> EsRuler::getPvalue(double ES, double absEps, bool sign) {
unsigned long halfSize = (sampleSize + 1) / 2;
auto it = enrichmentScores.begin();
if (ES >= enrichmentScores.back()){
it = enrichmentScores.end() - 1;
}
else{
it = lower_bound(enrichmentScores.begin(), enrichmentScores.end(), ES);
}
unsigned long indx = 0;
(it - enrichmentScores.begin()) > 0 ? (indx = (it - enrichmentScores.begin())) : indx = 0;
unsigned long k = (indx) / halfSize;
unsigned long remainder = sampleSize - (indx % halfSize);
double adjLog = betaMeanLog(halfSize, sampleSize);
double adjLogPval = k * adjLog + betaMeanLog(remainder + 1, sampleSize);
if (sign) {
return make_pair(max(0.0, min(1.0, exp(adjLogPval))), true);
} else {
pair<double, bool> correction = calcLogCorrection(probCorrector, indx, posUnifScoreCount, sampleSize);
double resLog = adjLogPval + correction.first;
return make_pair(max(0.0, min(1.0, exp(resLog))), correction.second);
}
}
int perturbate(const vector<double> &ranks, vector<int> &sample,
double bound, mt19937 &rng) {
double pertPrmtr = 0.1;
int n = (int) ranks.size();
int k = (int) sample.size();
uniform_int_distribution<> uid_n(0, n - 1);
uniform_int_distribution<> uid_k(0, k - 1);
double NS = 0;
for (int pos : sample) {
NS += ranks[pos];
}
int iters = max(1, (int) (k * pertPrmtr));
int moves = 0;
for (int i = 0; i < iters; i++) {
int id = uid_k(rng);
int old = sample[id];
NS -= ranks[sample[id]];
sample[id] = uid_n(rng);
while (id > 0 && sample[id] < sample[id - 1]) {
swap(sample[id], sample[id - 1]);
id--;
}
while (id < k - 1 && sample[id] > sample[id + 1]) {
swap(sample[id], sample[id + 1]);
id++;
}
if ((id > 0 && sample[id] == sample[id - 1]) || (id < k - 1 && sample[id] == sample[id + 1]) ||
!compareStat(ranks, sample, NS + ranks[sample[id]], bound)) {
// revert changes...
sample[id] = old;
while (id > 0 && sample[id] < sample[id - 1]) {
swap(sample[id], sample[id - 1]);
id--;
}
while (id < k - 1 && sample[id] > sample[id + 1]) {
swap(sample[id], sample[id + 1]);
id++;
}
} else {
moves++;
}
NS += ranks[sample[id]];
}
return moves;
}
| 35.125 | 113 | 0.596299 | [
"vector"
] |
c4ecaae6321f0a1681faac8a6e985bc1e4d6a3f1 | 3,481 | cpp | C++ | cascade-opencv.cpp | James-QiuHaoran/opencv-cpp | 54e6712fb340de15372ca595c293d98ba0cee63a | [
"Apache-2.0"
] | 8 | 2018-02-15T04:00:08.000Z | 2020-03-24T15:42:46.000Z | cascade-opencv.cpp | James-QiuHaoran/opencv-cpp | 54e6712fb340de15372ca595c293d98ba0cee63a | [
"Apache-2.0"
] | 1 | 2020-03-03T16:50:52.000Z | 2020-03-03T16:50:52.000Z | cascade-opencv.cpp | James-QiuHaoran/opencv-cpp | 54e6712fb340de15372ca595c293d98ba0cee63a | [
"Apache-2.0"
] | 5 | 2019-05-27T06:34:21.000Z | 2022-03-28T05:10:23.000Z | #include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
#define STOP_SIGN_CASCADE_NAME "/home/jamesqiu/Desktop/640-Project/stopsign_classifier2.xml"
#define TRAFFIC_LIGHT_CASCADE_NAME "/home/jamesqiu/Desktop/640-Project/trafficlight_classifier2.xml"
#define VEHICLE_CASCADE_NAME "/home/jamesqiu/Desktop/640-Project/cars3.xml"
#define PEDESTRIAN_CASCADE_NAME "/home/jamesqiu/Desktop/640-Project/pedestrian_classifier4.xml"
#define TARGET_IMAGE "/home/jamesqiu/Desktop/640-Project/test.jpg"
#define CAR_IMAGE "/home/jamesqiu/Desktop/640-Project/car.png"
#define WINDOW_NAME "WINDOW - Detection Results"
void draw_locations(Mat & img, vector< Rect > & locations, const Scalar & color,string text);
int main(int argc, char** argv) {
cout << "OpenCV Version: " << CV_VERSION << endl;
CascadeClassifier cars, traffic_light, stop_sign, pedestrian;
vector<Rect> cars_found, traffic_light_found, stop_sign_found , pedestrian_found, cars_tracking;
vector<Mat> cars_tracking_img;
vector<int> car_timer;
string address = TARGET_IMAGE;
Mat targetImage;
if (argc > 1) {
address = (string)(argv[1]);
}
targetImage = imread(address);
cout << "Target Image: " << address << endl;
cars.load(VEHICLE_CASCADE_NAME);
traffic_light.load(TRAFFIC_LIGHT_CASCADE_NAME);
stop_sign.load(STOP_SIGN_CASCADE_NAME);
pedestrian.load(PEDESTRIAN_CASCADE_NAME);
// Start and end times
time_t start, end;
time(&start);
// cars cascade
cars.detectMultiScale(targetImage, cars_found, 1.1, 5, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
// traffic lights cascade
traffic_light.detectMultiScale(targetImage, traffic_light_found, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
//pedestrian cascade
pedestrian.detectMultiScale(targetImage, pedestrian_found, 1.1, 1, 0 | CASCADE_SCALE_IMAGE, Size(20,50));
//stop sign cascade
stop_sign.detectMultiScale(targetImage, stop_sign_found, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
// End Time
time(&end);
// Time elapsed
double seconds = difftime(end, start);
cout << "Time taken : " << seconds << " seconds" << endl;
// draw_locations(targetImage, cars_found, Scalar(0, 255, 0),"Car");
draw_locations(targetImage, traffic_light_found, Scalar(0, 255, 255),"Traffic Light");
draw_locations(targetImage, stop_sign_found, Scalar(0, 0, 255), "Stop Sign");
draw_locations(targetImage, pedestrian_found, Scalar(255, 0, 0),"Pedestrian");
imshow(WINDOW_NAME, targetImage);
waitKey(3000);
address = "/home/jamesqiu/Desktop/output-images/" + address;
imwrite(address, targetImage);
return 0;
}
void draw_locations(Mat & img, vector< Rect > &locations, const Scalar & color, string text) {
Mat img1, car, carMask ,carMaskInv,car1;
img.copyTo(img1);
if (!locations.empty()) {
// double distance;
for(size_t i = 0 ; i < locations.size(); ++i) {
rectangle(img, locations[i], color, -1);
}
addWeighted(img1, 0.8, img, 0.2, 0, img);
for(size_t i = 0 ; i < locations.size() ; ++i) {
rectangle(img, locations[i], color, 3);
putText(img, text, Point(locations[i].x+1, locations[i].y+8), FONT_HERSHEY_DUPLEX, 0.3, color, 1);
if (text == "Car") {
locations[i].y = locations[i].y - img.rows/2; // shift the bounding box
}
}
}
}
| 39.11236 | 116 | 0.682275 | [
"vector"
] |
c4ee599d11d9848da22d1e3f74725dd5014eddfa | 2,242 | hpp | C++ | doc/quickbook/oglplus/quickref/enums/program_parameter_class.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | doc/quickbook/oglplus/quickref/enums/program_parameter_class.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | doc/quickbook/oglplus/quickref/enums/program_parameter_class.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | // File doc/quickbook/oglplus/quickref/enums/program_parameter_class.hpp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/program_parameter.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 Matus Chochlik.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
//[oglplus_enums_program_parameter_class
#if !__OGLPLUS_NO_ENUM_VALUE_CLASSES
namespace enums {
template <typename Base, template <__ProgramParameter> class Transform>
class __EnumToClass<Base, __ProgramParameter, Transform> /*<
Specialization of __EnumToClass for the __ProgramParameter enumeration.
>*/
: public Base {
public:
EnumToClass();
EnumToClass(Base&& base);
Transform<ProgramParameter::DeleteStatus> DeleteStatus;
Transform<ProgramParameter::LinkStatus> LinkStatus;
Transform<ProgramParameter::ValidateStatus> ValidateStatus;
Transform<ProgramParameter::InfoLogLength> InfoLogLength;
Transform<ProgramParameter::AttachedShaders> AttachedShaders;
Transform<ProgramParameter::ActiveAtomicCounterBuffers>
ActiveAtomicCounterBuffers;
Transform<ProgramParameter::ActiveAttributes> ActiveAttributes;
Transform<ProgramParameter::ActiveAttributeMaxLength>
ActiveAttributeMaxLength;
Transform<ProgramParameter::ActiveUniforms> ActiveUniforms;
Transform<ProgramParameter::ActiveUniformMaxLength> ActiveUniformMaxLength;
Transform<ProgramParameter::ProgramBinaryLength> ProgramBinaryLength;
Transform<ProgramParameter::ComputeWorkGroupSize> ComputeWorkGroupSize;
Transform<ProgramParameter::TransformFeedbackBufferMode>
TransformFeedbackBufferMode;
Transform<ProgramParameter::TransformFeedbackVaryings>
TransformFeedbackVaryings;
Transform<ProgramParameter::TransformFeedbackVaryingMaxLength>
TransformFeedbackVaryingMaxLength;
Transform<ProgramParameter::GeometryVerticesOut> GeometryVerticesOut;
Transform<ProgramParameter::GeometryInputType> GeometryInputType;
Transform<ProgramParameter::GeometryOutputType> GeometryOutputType;
};
} // namespace enums
#endif
//]
| 42.301887 | 79 | 0.805531 | [
"transform"
] |
c4fc95dd9f8c12bd8ce8f5462d84c798b0099c0b | 17,811 | cpp | C++ | source/d3d12/runtime_d3d12.cpp | EliphasNUIT/reshade | d767bece469df57aef005c71de6a53d83886c080 | [
"BSD-3-Clause"
] | null | null | null | source/d3d12/runtime_d3d12.cpp | EliphasNUIT/reshade | d767bece469df57aef005c71de6a53d83886c080 | [
"BSD-3-Clause"
] | null | null | null | source/d3d12/runtime_d3d12.cpp | EliphasNUIT/reshade | d767bece469df57aef005c71de6a53d83886c080 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "dll_log.hpp"
#include "dll_resources.hpp"
#include "runtime_d3d12.hpp"
#include "runtime_objects.hpp"
#include "dxgi/format_utils.hpp"
#include <CoreWindow.h>
#include <d3dcompiler.h>
reshade::d3d12::runtime_impl::runtime_impl(device_impl *device, command_queue_impl *queue, IDXGISwapChain3 *swapchain) :
api_object_impl(swapchain),
_device(device->_orig),
_cmd_queue(queue->_orig),
_device_impl(device),
_cmd_queue_impl(queue),
_cmd_impl(static_cast<command_list_immediate_impl *>(queue->get_immediate_command_list()))
{
_renderer_id = D3D_FEATURE_LEVEL_12_0;
// There is no swap chain in d3d12on7
if (com_ptr<IDXGIFactory4> factory;
_orig != nullptr && SUCCEEDED(_orig->GetParent(IID_PPV_ARGS(&factory))))
{
const LUID luid = _device->GetAdapterLuid();
if (com_ptr<IDXGIAdapter> dxgi_adapter;
SUCCEEDED(factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(&dxgi_adapter))))
{
if (DXGI_ADAPTER_DESC desc; SUCCEEDED(dxgi_adapter->GetDesc(&desc)))
{
_vendor_id = desc.VendorId;
_device_id = desc.DeviceId;
LOG(INFO) << "Running on " << desc.Description;
}
}
}
if (_orig != nullptr && !on_init())
LOG(ERROR) << "Failed to initialize Direct3D 12 runtime environment on runtime " << this << '!';
}
reshade::d3d12::runtime_impl::~runtime_impl()
{
on_reset();
if (_d3d_compiler != nullptr)
FreeLibrary(_d3d_compiler);
}
bool reshade::d3d12::runtime_impl::on_init()
{
assert(_orig != nullptr);
DXGI_SWAP_CHAIN_DESC swap_desc;
// Get description from IDXGISwapChain interface, since later versions are slightly different
if (FAILED(_orig->GetDesc(&swap_desc)))
return false;
// Update window handle in swap chain description for UWP applications
if (HWND hwnd = nullptr; SUCCEEDED(_orig->GetHwnd(&hwnd)))
swap_desc.OutputWindow = hwnd;
else if (com_ptr<ICoreWindowInterop> window_interop; // Get window handle of the core window
SUCCEEDED(_orig->GetCoreWindow(IID_PPV_ARGS(&window_interop))) && SUCCEEDED(window_interop->get_WindowHandle(&hwnd)))
swap_desc.OutputWindow = hwnd;
return on_init(swap_desc);
}
bool reshade::d3d12::runtime_impl::on_init(const DXGI_SWAP_CHAIN_DESC &swap_desc)
{
if (swap_desc.SampleDesc.Count > 1)
return false; // Multisampled swap chains are not currently supported
_width = _window_width = swap_desc.BufferDesc.Width;
_height = _window_height = swap_desc.BufferDesc.Height;
_color_bit_depth = dxgi_format_color_depth(swap_desc.BufferDesc.Format);
_backbuffer_format = swap_desc.BufferDesc.Format;
if (swap_desc.OutputWindow != nullptr)
{
RECT window_rect = {};
GetClientRect(swap_desc.OutputWindow, &window_rect);
_window_width = window_rect.right;
_window_height = window_rect.bottom;
}
// Allocate descriptor heaps
{ D3D12_DESCRIPTOR_HEAP_DESC desc = { D3D12_DESCRIPTOR_HEAP_TYPE_RTV };
desc.NumDescriptors = swap_desc.BufferCount * 2;
if (FAILED(_device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&_backbuffer_rtvs))))
return false;
_backbuffer_rtvs->SetName(L"ReShade RTV heap");
}
// Get back buffer textures (skip on d3d12on7 devices, since there is no swap chain there)
_backbuffers.resize(swap_desc.BufferCount);
if (_orig != nullptr)
{
D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = _backbuffer_rtvs->GetCPUDescriptorHandleForHeapStart();
for (unsigned int i = 0; i < swap_desc.BufferCount; ++i)
{
if (FAILED(_orig->GetBuffer(i, IID_PPV_ARGS(&_backbuffers[i]))))
return false;
for (int srgb_write_enable = 0; srgb_write_enable < 2; ++srgb_write_enable, rtv_handle.ptr += _device_impl->_descriptor_handle_size[D3D12_DESCRIPTOR_HEAP_TYPE_RTV])
{
D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = {};
rtv_desc.Format = srgb_write_enable ?
make_dxgi_format_srgb(_backbuffer_format) :
make_dxgi_format_normal(_backbuffer_format);
rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
_device->CreateRenderTargetView(_backbuffers[i].get(), &rtv_desc, rtv_handle);
}
}
}
return runtime::on_init(swap_desc.OutputWindow);
}
void reshade::d3d12::runtime_impl::on_reset()
{
runtime::on_reset();
// Make sure none of the resources below are currently in use (provided the runtime was initialized previously)
_cmd_impl->flush_and_wait(_cmd_queue.get());
_backbuffers.clear();
_backbuffer_rtvs.reset();
}
void reshade::d3d12::runtime_impl::on_present()
{
if (!_is_initialized)
return;
// There is no swap chain in d3d12on7
if (_orig != nullptr)
_swap_index = _orig->GetCurrentBackBufferIndex();
update_and_render_effects();
runtime::on_present();
_cmd_impl->flush(_cmd_queue.get());
}
bool reshade::d3d12::runtime_impl::on_present(ID3D12Resource *source, HWND hwnd)
{
assert(source != nullptr);
// Reinitialize runtime when the source texture dimensions changes
const D3D12_RESOURCE_DESC source_desc = source->GetDesc();
if (source_desc.Width != _width || source_desc.Height != _height || source_desc.Format != _backbuffer_format)
{
on_reset();
DXGI_SWAP_CHAIN_DESC swap_desc = {};
swap_desc.BufferDesc.Width = static_cast<UINT>(source_desc.Width);
swap_desc.BufferDesc.Height = source_desc.Height;
swap_desc.BufferDesc.Format = source_desc.Format;
swap_desc.SampleDesc = source_desc.SampleDesc;
swap_desc.BufferCount = 3; // Cycle between three fake back buffers
swap_desc.OutputWindow = hwnd;
if (!on_init(swap_desc))
{
LOG(ERROR) << "Failed to initialize Direct3D 12 runtime environment on runtime " << this << '!';
return false;
}
}
_swap_index = (_swap_index + 1) % 3;
// Update source texture render target view
assert(_backbuffers.size() == 3);
if (_backbuffers[_swap_index] != source)
{
_backbuffers[_swap_index] = source;
D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = _backbuffer_rtvs->GetCPUDescriptorHandleForHeapStart();
rtv_handle.ptr += _device_impl->_descriptor_handle_size[D3D12_DESCRIPTOR_HEAP_TYPE_RTV] * 2 * _swap_index;
for (int srgb_write_enable = 0; srgb_write_enable < 2; ++srgb_write_enable, rtv_handle.ptr += _device_impl->_descriptor_handle_size[D3D12_DESCRIPTOR_HEAP_TYPE_RTV])
{
D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = {};
rtv_desc.Format = srgb_write_enable ?
make_dxgi_format_srgb(_backbuffer_format) :
make_dxgi_format_normal(_backbuffer_format);
rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
_device->CreateRenderTargetView(source, &rtv_desc, rtv_handle);
}
}
on_present();
return true;
}
bool reshade::d3d12::runtime_impl::on_layer_submit(UINT eye, ID3D12Resource *source, const float bounds[4], ID3D12Resource **target)
{
assert(eye < 2 && source != nullptr);
D3D12_RESOURCE_DESC source_desc = source->GetDesc();
if (source_desc.SampleDesc.Count > 1)
return false; // When the resource is multisampled, 'CopyTextureRegion' can only copy whole subresources
D3D12_BOX source_region = { 0, 0, 0, static_cast<UINT>(source_desc.Width), source_desc.Height, 1 };
if (bounds != nullptr)
{
source_region.left = static_cast<UINT>(source_desc.Width * std::min(bounds[0], bounds[2]));
source_region.top = static_cast<UINT>(source_desc.Height * std::min(bounds[1], bounds[3]));
source_region.right = static_cast<UINT>(source_desc.Width * std::max(bounds[0], bounds[2]));
source_region.bottom = static_cast<UINT>(source_desc.Height * std::max(bounds[1], bounds[3]));
}
const UINT region_width = source_region.right - source_region.left;
const UINT target_width = region_width * 2;
const UINT region_height = source_region.bottom - source_region.top;
if (target_width != _width || region_height != _height || source_desc.Format != _backbuffer_format)
{
on_reset();
DXGI_SWAP_CHAIN_DESC swap_desc = {};
swap_desc.BufferDesc.Width = target_width;
swap_desc.BufferDesc.Height = region_height;
swap_desc.BufferDesc.Format = source_desc.Format;
swap_desc.SampleDesc = source_desc.SampleDesc;
swap_desc.BufferCount = 1;
if (!on_init(swap_desc))
{
LOG(ERROR) << "Failed to initialize Direct3D 12 runtime environment on runtime " << this << '!';
return false;
}
assert(_backbuffers.size() == 1);
source_desc.Width = target_width;
source_desc.Height = region_height;
source_desc.DepthOrArraySize = 1;
source_desc.MipLevels = 1;
source_desc.Format = make_dxgi_format_typeless(source_desc.Format);
const D3D12_HEAP_PROPERTIES heap_props = { D3D12_HEAP_TYPE_DEFAULT };
if (HRESULT hr = _device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &source_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&_backbuffers[0])); FAILED(hr))
{
LOG(ERROR) << "Failed to create region texture!" << " HRESULT is " << hr << '.';
LOG(DEBUG) << "> Details: Width = " << source_desc.Width << ", Height = " << source_desc.Height << ", Format = " << source_desc.Format << ", Flags = " << std::hex << source_desc.Flags << std::dec;
return false;
}
D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = _backbuffer_rtvs->GetCPUDescriptorHandleForHeapStart();
for (int srgb_write_enable = 0; srgb_write_enable < 2; ++srgb_write_enable, rtv_handle.ptr += _device_impl->_descriptor_handle_size[D3D12_DESCRIPTOR_HEAP_TYPE_RTV])
{
D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = {};
rtv_desc.Format = srgb_write_enable ?
make_dxgi_format_srgb(_backbuffer_format) :
make_dxgi_format_normal(_backbuffer_format);
rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
_device->CreateRenderTargetView(_backbuffers[0].get(), &rtv_desc, rtv_handle);
}
}
ID3D12GraphicsCommandList *const cmd_list = _cmd_impl->begin_commands();
D3D12_RESOURCE_BARRIER transitions[2];
transitions[0] = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION };
transitions[0].Transition.pResource = source;
transitions[0].Transition.Subresource = 0;
transitions[0].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
transitions[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
transitions[1] = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION };
transitions[1].Transition.pResource = _backbuffers[0].get();
transitions[1].Transition.Subresource = 0;
transitions[1].Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
transitions[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
cmd_list->ResourceBarrier(2, transitions);
// Copy region of the source texture
const D3D12_TEXTURE_COPY_LOCATION src_location = { source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX };
const D3D12_TEXTURE_COPY_LOCATION dest_location = { _backbuffers[0].get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX };
cmd_list->CopyTextureRegion(&dest_location, eye * region_width, 0, 0, &src_location, &source_region);
std::swap(transitions[0].Transition.StateBefore, transitions[0].Transition.StateAfter);
std::swap(transitions[1].Transition.StateBefore, transitions[1].Transition.StateAfter);
cmd_list->ResourceBarrier(2, transitions);
*target = _backbuffers[0].get();
return true;
}
bool reshade::d3d12::runtime_impl::capture_screenshot(uint8_t *buffer) const
{
if (_color_bit_depth != 8 && _color_bit_depth != 10)
{
if (const char *format_string = format_to_string(_backbuffer_format); format_string != nullptr)
LOG(ERROR) << "Screenshots are not supported for back buffer format " << format_string << '!';
else
LOG(ERROR) << "Screenshots are not supported for back buffer format " << _backbuffer_format << '!';
return false;
}
const uint32_t data_pitch = _width * 4;
const uint32_t download_pitch = (data_pitch + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
D3D12_RESOURCE_DESC desc = { D3D12_RESOURCE_DIMENSION_BUFFER };
desc.Width = _height * download_pitch;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc = { 1, 0 };
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
D3D12_HEAP_PROPERTIES props = { D3D12_HEAP_TYPE_READBACK };
com_ptr<ID3D12Resource> intermediate;
if (HRESULT hr = _device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&intermediate)); FAILED(hr))
{
LOG(ERROR) << "Failed to create system memory buffer for screenshot capture!" << " HRESULT is " << hr << '.';
LOG(DEBUG) << "> Details: Width = " << desc.Width;
return false;
}
intermediate->SetName(L"ReShade screenshot texture");
ID3D12GraphicsCommandList *const cmd_list = _cmd_impl->begin_commands();
// Was transitioned to D3D12_RESOURCE_STATE_RENDER_TARGET in 'on_present' already
D3D12_RESOURCE_BARRIER transition = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION };
transition.Transition.pResource = _backbuffers[_swap_index].get();
transition.Transition.Subresource = 0;
transition.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
transition.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
cmd_list->ResourceBarrier(1, &transition);
{
D3D12_TEXTURE_COPY_LOCATION src_location = { _backbuffers[_swap_index].get() };
src_location.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
src_location.SubresourceIndex = 0;
D3D12_TEXTURE_COPY_LOCATION dst_location = { intermediate.get() };
dst_location.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
dst_location.PlacedFootprint.Footprint.Width = _width;
dst_location.PlacedFootprint.Footprint.Height = _height;
dst_location.PlacedFootprint.Footprint.Depth = 1;
dst_location.PlacedFootprint.Footprint.Format = make_dxgi_format_normal(_backbuffer_format);
dst_location.PlacedFootprint.Footprint.RowPitch = download_pitch;
cmd_list->CopyTextureRegion(&dst_location, 0, 0, 0, &src_location, nullptr);
}
std::swap(transition.Transition.StateBefore, transition.Transition.StateAfter);
cmd_list->ResourceBarrier(1, &transition);
// Execute and wait for completion
if (!_cmd_impl->flush_and_wait(_cmd_queue.get()))
return false;
// Copy data from system memory texture into output buffer
uint8_t *mapped_data;
if (FAILED(intermediate->Map(0, nullptr, reinterpret_cast<void **>(&mapped_data))))
return false;
for (uint32_t y = 0; y < _height; y++, buffer += data_pitch, mapped_data += download_pitch)
{
if (_color_bit_depth == 10)
{
for (uint32_t x = 0; x < data_pitch; x += 4)
{
const uint32_t rgba = *reinterpret_cast<const uint32_t *>(mapped_data + x);
// Divide by 4 to get 10-bit range (0-1023) into 8-bit range (0-255)
buffer[x + 0] = ( (rgba & 0x000003FF) / 4) & 0xFF;
buffer[x + 1] = (((rgba & 0x000FFC00) >> 10) / 4) & 0xFF;
buffer[x + 2] = (((rgba & 0x3FF00000) >> 20) / 4) & 0xFF;
buffer[x + 3] = (((rgba & 0xC0000000) >> 30) * 85) & 0xFF;
}
}
else
{
std::memcpy(buffer, mapped_data, data_pitch);
if (_backbuffer_format == DXGI_FORMAT_B8G8R8A8_UNORM ||
_backbuffer_format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB)
{
// Format is BGRA, but output should be RGBA, so flip channels
for (uint32_t x = 0; x < data_pitch; x += 4)
std::swap(buffer[x + 0], buffer[x + 2]);
}
}
}
intermediate->Unmap(0, nullptr);
return true;
}
bool reshade::d3d12::runtime_impl::compile_effect(effect &effect, api::shader_stage type, const std::string &entry_point, api::shader_module &out)
{
if (_d3d_compiler == nullptr)
_d3d_compiler = LoadLibraryW(L"d3dcompiler_47.dll");
if (_d3d_compiler == nullptr)
{
LOG(ERROR) << "Unable to load HLSL compiler (\"d3dcompiler_47.dll\")!";
return false;
}
const auto D3DCompile = reinterpret_cast<pD3DCompile>(GetProcAddress(_d3d_compiler, "D3DCompile"));
const auto D3DDisassemble = reinterpret_cast<pD3DDisassemble>(GetProcAddress(_d3d_compiler, "D3DDisassemble"));
HRESULT hr = E_FAIL;
const std::string hlsl = effect.preamble + effect.module.hlsl;
std::string profile;
switch (type)
{
case api::shader_stage::vertex:
profile = "vs_5_0";
break;
case api::shader_stage::pixel:
profile = "ps_5_0";
break;
case api::shader_stage::compute:
profile = "cs_5_0";
break;
}
UINT compile_flags = D3DCOMPILE_ENABLE_STRICTNESS;
compile_flags |= (_performance_mode ? D3DCOMPILE_OPTIMIZATION_LEVEL3 : D3DCOMPILE_OPTIMIZATION_LEVEL1);
#ifndef NDEBUG
compile_flags |= D3DCOMPILE_DEBUG;
#endif
std::string attributes;
attributes += "entrypoint=" + entry_point + ';';
attributes += "profile=" + profile + ';';
attributes += "flags=" + std::to_string(compile_flags) + ';';
const size_t hash = std::hash<std::string_view>()(attributes) ^ std::hash<std::string_view>()(hlsl);
std::vector<char> cso;
if (!load_effect_cache(effect.source_file, entry_point, hash, cso, effect.assembly[entry_point]))
{
com_ptr<ID3DBlob> d3d_compiled, d3d_errors;
hr = D3DCompile(
hlsl.data(), hlsl.size(),
nullptr, nullptr, nullptr,
entry_point.c_str(),
profile.c_str(),
compile_flags, 0,
&d3d_compiled, &d3d_errors);
if (d3d_errors != nullptr) // Append warnings to the output error string as well
effect.errors.append(static_cast<const char *>(d3d_errors->GetBufferPointer()), d3d_errors->GetBufferSize() - 1); // Subtracting one to not append the null-terminator as well
// No need to setup resources if any of the shaders failed to compile
if (FAILED(hr))
return false;
cso.resize(d3d_compiled->GetBufferSize());
std::memcpy(cso.data(), d3d_compiled->GetBufferPointer(), cso.size());
if (com_ptr<ID3DBlob> d3d_disassembled; SUCCEEDED(D3DDisassemble(cso.data(), cso.size(), 0, nullptr, &d3d_disassembled)))
effect.assembly[entry_point].assign(static_cast<const char *>(d3d_disassembled->GetBufferPointer()), d3d_disassembled->GetBufferSize() - 1);
save_effect_cache(effect.source_file, entry_point, hash, cso, effect.assembly[entry_point]);
}
return _device_impl->create_shader_module(type, api::shader_format::dxbc, cso.data(), cso.size(), nullptr, &out);
}
| 37.339623 | 199 | 0.747852 | [
"render",
"vector"
] |
c4fe44ec144f905f96e68e8495bc86d090eb806b | 1,089 | cpp | C++ | src/page/page_scanner.cpp | abhijat/matchboxdb | 77c055690054deb96dffc29499ad99928370ae99 | [
"BSD-2-Clause"
] | 9 | 2021-11-09T13:55:41.000Z | 2022-03-04T05:22:15.000Z | src/page/page_scanner.cpp | abhijat/matchboxdb | 77c055690054deb96dffc29499ad99928370ae99 | [
"BSD-2-Clause"
] | null | null | null | src/page/page_scanner.cpp | abhijat/matchboxdb | 77c055690054deb96dffc29499ad99928370ae99 | [
"BSD-2-Clause"
] | null | null | null | #include "page_scanner.h"
#include "../storage/streamutils.h"
#include "metadata_page.h"
page_scan_utils::PageScanner::PageScanner(std::istream &table_stream, page_visitors::PageVisitor &page_visitor)
: _table_stream(table_stream), _page_visitor(page_visitor) {}
std::unordered_map<page::PageType, std::vector<page::PageId>> page_scan_utils::PageScanner::scan_pages() {
std::unordered_map<page::PageType, std::vector<page::PageId>> page_directory{
{page::PageType::Metadata, {}},
{page::PageType::Data, {}},
};
_table_stream.seekg(0, std::ios::beg);
auto metadata_page = page::MetadataPage{stream_utils::read_page_from_stream(_table_stream)};
for (auto i = 0; i < metadata_page.n_marked_pages(); ++i) {
auto page_buffer = stream_utils::read_page_from_stream(_table_stream);
_page_visitor.visit(page_buffer);
auto page_type = page::page_type_from_buffer(page_buffer);
auto page_id = page::page_id_from_buffer(page_buffer);
page_directory[page_type].push_back(page_id);
}
return page_directory;
}
| 38.892857 | 111 | 0.716253 | [
"vector"
] |
f2015ffd3f5ef35f24adae43feecd8062d2a2820 | 1,154 | cpp | C++ | src/process.cpp | aromans/Nanodegree-System-Monitor | 9b6ff863408cf6cccd61698c3cb91fdc9cb047e8 | [
"MIT"
] | null | null | null | src/process.cpp | aromans/Nanodegree-System-Monitor | 9b6ff863408cf6cccd61698c3cb91fdc9cb047e8 | [
"MIT"
] | null | null | null | src/process.cpp | aromans/Nanodegree-System-Monitor | 9b6ff863408cf6cccd61698c3cb91fdc9cb047e8 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include "process.h"
#include "format.h"
#include "linux_parser.h"
using std::string;
using std::to_string;
using std::vector;
// Returns this process's ID
int Process::Pid() { return m_Pid; }
// Returns this process's CPU utilization
float Process::CpuUtilization() {
float total = m_SystemCpu.GetTotal() - m_SystemCpu.GetPrevTotal();
m_CpuPercentage = (LinuxParser::ActiveJiffies(m_Pid)) / total;
return m_CpuPercentage;
}
// Return the command that generated this process
string Process::Command() { return LinuxParser::Command(m_Pid); }
// Return this process's memory utilization
string Process::Ram() { return LinuxParser::Ram(m_Pid); }
// Return the user (name) that generated this process
string Process::User() { return LinuxParser::User(m_Pid); }
// Return the age of this process (in seconds)
long int Process::UpTime() { return LinuxParser::UpTime(m_Pid); }
// Overload the "less than" comparison operator for Process objects
bool Process::operator<(Process const& a) const {
return a.m_CpuPercentage < m_CpuPercentage;
} | 28.85 | 70 | 0.733102 | [
"vector"
] |
f206478143d3e5cda23ceedc2fd7675ea452a8bb | 11,154 | cc | C++ | src/ledger/bin/tests/integration/sync/sync_tests.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/ledger/bin/tests/integration/sync/sync_tests.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/ledger/bin/tests/integration/sync/sync_tests.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/fidl/cpp/binding.h>
#include <lib/fidl/cpp/optional.h>
#include "src/ledger/bin/fidl/include/types.h"
#include "src/ledger/bin/testing/data_generator.h"
#include "src/ledger/bin/testing/ledger_matcher.h"
#include "src/ledger/bin/tests/integration/integration_test.h"
#include "src/ledger/bin/tests/integration/sync/test_sync_state_watcher.h"
#include "src/ledger/bin/tests/integration/test_page_watcher.h"
#include "src/ledger/lib/callback/capture.h"
#include "src/ledger/lib/convert/convert.h"
#include "src/ledger/lib/vmo/strings.h"
#include "src/ledger/lib/vmo/vector.h"
namespace ledger {
namespace {
using testing::SizeIs;
class SyncIntegrationTest : public IntegrationTest {
protected:
std::unique_ptr<TestSyncStateWatcher> WatchPageSyncState(PagePtr* page) {
auto watcher = std::make_unique<TestSyncStateWatcher>();
(*page)->SetSyncStateWatcher(watcher->NewBinding());
return watcher;
}
bool WaitUntilSyncIsIdle(TestSyncStateWatcher* watcher) {
return RunLoopUntil([watcher] { return watcher->Equals(SyncState::IDLE, SyncState::IDLE); });
}
};
using SyncIntegrationCloudTest = SyncIntegrationTest;
// Verifies that a new page entry is correctly synchronized between two Ledger app instances.
//
// In this test the app instances connect to the cloud one after the other: the first instance
// uploads data to the cloud and shuts down, and only after that the second instance is created and
// connected.
//
// This cannot work with P2P only: the two Ledger instances are not running simulateously.
TEST_P(SyncIntegrationCloudTest, SerialConnection) {
PageId page_id;
// Create the first instance and write the page entry.
auto instance1 = NewLedgerAppInstance();
auto page1 = instance1->GetTestPage();
auto page1_state_watcher = WatchPageSyncState(&page1);
page1->Put(convert::ToArray("Hello"), convert::ToArray("World"));
// Retrieve the page ID so that we can later connect to the same page from
// another app instance.
auto loop_waiter = NewWaiter();
page1->GetId(Capture(loop_waiter->GetCallback(), &page_id));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
// Wait until the sync state becomes idle.
EXPECT_TRUE(WaitUntilSyncIsIdle(page1_state_watcher.get()));
// Create the second instance, connect to the same page and download the
// data.
auto instance2 = NewLedgerAppInstance();
auto page2 = instance2->GetPage(fidl::MakeOptional(page_id));
auto page2_state_watcher = WatchPageSyncState(&page2);
EXPECT_TRUE(WaitUntilSyncIsIdle(page2_state_watcher.get()));
PageSnapshotPtr snapshot;
page2->GetSnapshot(snapshot.NewRequest(), {}, nullptr);
loop_waiter = NewWaiter();
fuchsia::ledger::PageSnapshot_GetInline_Result result;
snapshot->GetInline(convert::ToArray("Hello"), Capture(loop_waiter->GetCallback(), &result));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
EXPECT_THAT(result, MatchesString("World"));
// Verify that the sync state of the second page connection eventually becomes
// idle.
EXPECT_TRUE(WaitUntilSyncIsIdle(page2_state_watcher.get()));
}
// Verifies that a new page entry is correctly synchronized between two Ledger
// app instances.
//
// In this test the app instances connect to the cloud concurrently: the second
// instance is already connected when the first instance writes the entry.
TEST_P(SyncIntegrationTest, ConcurrentConnection) {
auto instance1 = NewLedgerAppInstance();
auto instance2 = NewLedgerAppInstance();
auto page1 = instance1->GetTestPage();
auto page1_state_watcher = WatchPageSyncState(&page1);
PageId page_id;
auto loop_waiter = NewWaiter();
page1->GetId(Capture(loop_waiter->GetCallback(), &page_id));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
auto page2 = instance2->GetPage(fidl::MakeOptional(page_id));
// Set a watcher on page2 so we are notified when page1's changes are downloaded.
auto snpashot_waiter = NewWaiter();
PageSnapshotPtr snapshot;
PageWatcherPtr watcher_ptr;
TestPageWatcher watcher(watcher_ptr.NewRequest(), snpashot_waiter->GetCallback());
page2->GetSnapshot(snapshot.NewRequest(), {}, std::move(watcher_ptr));
auto sync_waiter = NewWaiter();
page2->Sync(sync_waiter->GetCallback());
ASSERT_TRUE(sync_waiter->RunUntilCalled());
page1->Put(convert::ToArray("Hello"), convert::ToArray("World"));
// Wait until page1 finishes uploading the changes.
EXPECT_TRUE(WaitUntilSyncIsIdle(page1_state_watcher.get()));
// Wait until page 2 sees some changes.
ASSERT_TRUE(snpashot_waiter->RunUntilCalled());
page2->GetSnapshot(snapshot.NewRequest(), {}, nullptr);
loop_waiter = NewWaiter();
fuchsia::ledger::PageSnapshot_GetInline_Result result;
snapshot->GetInline(convert::ToArray("Hello"), Capture(loop_waiter->GetCallback(), &result));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
EXPECT_THAT(result, MatchesString("World"));
// Verify that the sync states of page2 eventually become idle.
auto page2_state_watcher = WatchPageSyncState(&page2);
EXPECT_TRUE(WaitUntilSyncIsIdle(page2_state_watcher.get()));
}
// Verifies that we download eager values in full, even if parts of these values
// were already present on disk.
//
// In this test, we connect to the page concurrently. The first connection
// uploads a big object as a LAZY value, then the second one fetches a part of
// it. After that, the first connection re-uploads the same value, but with an
// EAGER priority. When the second connection receives the changes, we verify
// that the object is fully present on disk and can be retrieved by calling Get.
TEST_P(SyncIntegrationTest, DISABLED_LazyToEagerTransition) {
auto instance1 = NewLedgerAppInstance();
auto instance2 = NewLedgerAppInstance();
auto page1 = instance1->GetTestPage();
auto page1_state_watcher = WatchPageSyncState(&page1);
PageId page_id;
auto loop_waiter = NewWaiter();
page1->GetId(Capture(loop_waiter->GetCallback(), &page_id));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
auto page2 = instance2->GetPage(fidl::MakeOptional(page_id));
PageSnapshotPtr snapshot;
PageWatcherPtr watcher_ptr;
TestPageWatcher page2_watcher(watcher_ptr.NewRequest(), []() {});
page2->GetSnapshot(snapshot.NewRequest(), {}, std::move(watcher_ptr));
DataGenerator generator = DataGenerator(GetRandom());
std::vector<uint8_t> key = convert::ToArray("Hello");
std::vector<uint8_t> big_value = generator.MakeValue(2 * 65536 + 1);
SizedVmo vmo;
ASSERT_TRUE(VmoFromVector(big_value, &vmo));
fuchsia::ledger::Page_CreateReferenceFromBuffer_Result create_result;
loop_waiter = NewWaiter();
page1->CreateReferenceFromBuffer(std::move(vmo).ToTransport(),
Capture(loop_waiter->GetCallback(), &create_result));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
ASSERT_TRUE(create_result.is_response());
page1->PutReference(key, create_result.response().reference, Priority::LAZY);
EXPECT_TRUE(RunLoopUntil([&page2_watcher]() { return page2_watcher.GetChangesSeen() == 1; }));
snapshot = std::move(*page2_watcher.GetLastSnapshot());
// Lazy value is not downloaded eagerly.
loop_waiter = NewWaiter();
fuchsia::ledger::PageSnapshot_Get_Result get_result;
snapshot->Get(convert::ToArray("Hello"), Capture(loop_waiter->GetCallback(), &get_result));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
EXPECT_THAT(get_result, MatchesError(fuchsia::ledger::Error::NEEDS_FETCH));
fuchsia::ledger::PageSnapshot_FetchPartial_Result fetch_result;
loop_waiter = NewWaiter();
// Fetch only a small part.
snapshot->FetchPartial(convert::ToArray("Hello"), 0, 10,
Capture(loop_waiter->GetCallback(), &fetch_result));
// TODO(LE-812): this assertion is flaky. Re-enable this test once fixed.
ASSERT_TRUE(loop_waiter->RunUntilCalled());
EXPECT_THAT(fetch_result, MatchesString(SizeIs(10)));
// Change priority to eager, re-upload.
page1->PutReference(key, create_result.response().reference, Priority::EAGER);
EXPECT_TRUE(RunLoopUntil([&page2_watcher]() { return page2_watcher.GetChangesSeen() == 2; }));
snapshot = std::move(*page2_watcher.GetLastSnapshot());
// Now Get succeeds, as the value is no longer lazy.
loop_waiter = NewWaiter();
snapshot->Get(convert::ToArray("Hello"), Capture(loop_waiter->GetCallback(), &get_result));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
EXPECT_THAT(get_result, MatchesString(convert::ToString(big_value)));
}
// Verifies that a PageWatcher correctly delivers notifications about the change in case of a lazy
// value not already present on disk.
// TODO(https://bugs.fuchsia.dev/p/fuchsia/issues/detail?id=12287): re-enable for P2P only once P2P
// handles large objects.
TEST_P(SyncIntegrationCloudTest, PageChangeLazyEntry) {
auto instance1 = NewLedgerAppInstance();
auto instance2 = NewLedgerAppInstance();
auto page1 = instance1->GetTestPage();
auto page1_state_watcher = WatchPageSyncState(&page1);
PageId page_id;
auto loop_waiter = NewWaiter();
page1->GetId(Capture(loop_waiter->GetCallback(), &page_id));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
auto page2 = instance2->GetPage(fidl::MakeOptional(page_id));
std::vector<uint8_t> key = convert::ToArray("Hello");
std::vector<uint8_t> big_value(2 * 65536 + 1);
SizedVmo vmo;
ASSERT_TRUE(VmoFromVector(big_value, &vmo));
fuchsia::ledger::Page_CreateReferenceFromBuffer_Result result;
loop_waiter = NewWaiter();
page1->CreateReferenceFromBuffer(std::move(vmo).ToTransport(),
Capture(loop_waiter->GetCallback(), &result));
ASSERT_TRUE(loop_waiter->RunUntilCalled());
ASSERT_TRUE(result.is_response());
loop_waiter = NewWaiter();
PageSnapshotPtr snapshot;
PageWatcherPtr watcher_ptr;
TestPageWatcher watcher(watcher_ptr.NewRequest(), loop_waiter->GetCallback());
page2->GetSnapshot(snapshot.NewRequest(), {}, std::move(watcher_ptr));
auto sync_waiter = NewWaiter();
page2->Sync(sync_waiter->GetCallback());
ASSERT_TRUE(sync_waiter->RunUntilCalled());
page1->PutReference(std::move(key), std::move(result.response().reference), Priority::LAZY);
ASSERT_TRUE(loop_waiter->RunUntilCalled());
EXPECT_EQ(watcher.GetChangesSeen(), 1u);
EXPECT_EQ(watcher.GetLastResultState(), ResultState::COMPLETED);
auto change = &(watcher.GetLastPageChange());
EXPECT_EQ(change->changed_entries.size(), 1u);
EXPECT_EQ(change->changed_entries[0].value, nullptr);
}
INSTANTIATE_TEST_SUITE_P(
SyncIntegrationTest, SyncIntegrationTest,
::testing::ValuesIn(GetLedgerAppInstanceFactoryBuilders(EnableSynchronization::SYNC_ONLY)),
PrintLedgerAppInstanceFactoryBuilder());
INSTANTIATE_TEST_SUITE_P(SyncIntegrationCloudTest, SyncIntegrationCloudTest,
::testing::ValuesIn(GetLedgerAppInstanceFactoryBuilders(
EnableSynchronization::CLOUD_SYNC_ONLY)),
PrintLedgerAppInstanceFactoryBuilder());
} // namespace
} // namespace ledger
| 42.572519 | 99 | 0.750224 | [
"object",
"vector"
] |
f2077d54930fea74918443a11ef9e5cebbd0be88 | 49,553 | cp | C++ | gpcp/SymReader.cp | imt-ag/gpcp | 1c3de23993e0979d672f1c8fe7f193d0de22991a | [
"BSD-3-Clause"
] | 32 | 2017-08-15T11:49:34.000Z | 2021-12-24T13:10:29.000Z | gpcp/SymReader.cp | imt-ag/gpcp | 1c3de23993e0979d672f1c8fe7f193d0de22991a | [
"BSD-3-Clause"
] | 14 | 2017-10-14T16:44:02.000Z | 2022-03-09T08:17:56.000Z | gpcp/SymReader.cp | imt-ag/gpcp | 1c3de23993e0979d672f1c8fe7f193d0de22991a | [
"BSD-3-Clause"
] | 7 | 2017-11-10T14:55:30.000Z | 2022-02-07T01:23:22.000Z | MODULE SymReader;
(* ========================================================================= *)
(* *)
(* Symbol file reading module for the .NET to Gardens Point Component *)
(* Pascal Symbols tool. *)
(* Copyright (c) Siu-Yuen Chan 2001. *)
(* *)
(* This module reads Gardens Point Component Pascal (GPCP) symbol files *)
(* and stores all meta information read into METASTORE (defined by *)
(* MetaStore module). *)
(* ========================================================================= *)
IMPORT
Error,
GPFiles,
GF := GPBinFiles,
MS := MetaStore,
MP := MetaParser,
ST := AscString,
RTS;
(* ========================================================================= *
// Collected syntax ---
//
// SymFile = Header [String (falSy | truSy | <other attribute>)]
// {Import | Constant | Variable | Type | Procedure}
// TypeList Key.
// -- optional String is external name.
// -- falSy ==> Java class
// -- truSy ==> Java interface
// -- others ...
// Header = magic modSy Name.
// VersionName= numSy longint numSy longint numSy longint.
// -- mj# mn# bld rv# 8xbyte extract
// Import = impSy Name [String] Key.
// -- optional string is explicit external name of class
// Constant = conSy Name Literal.
// Variable = varSy Name TypeOrd.
// Type = typSy Name TypeOrd.
// Procedure = prcSy Name [String] FormalType.
// -- optional string is explicit external name of procedure
// Method = mthSy Name byte byte TypeOrd [String] FormalType.
// -- optional string is explicit external name of method
// FormalType = [retSy TypeOrd] frmSy {parSy byte TypeOrd} endFm.
// -- optional phrase is return type for proper procedures
// TypeOrd = ordinal.
// TypeHeader = tDefS Ord [fromS Ord Name].
// -- optional phrase occurs if:
// -- type not from this module, i.e. indirect export
// TypeList = start { Array | Record | Pointer | ProcType } close.
// Array = TypeHeader arrSy TypeOrd (Byte | Number | <empty>) endAr.
// -- nullable phrase is array length for fixed length arrays
// Pointer = TypeHeader ptrSy TypeOrd.
// Event = TypeHeader evtSy FormalType.
// ProcType = TypeHeader pTpSy FormalType.
// Record = TypeHeader recSy recAtt [truSy | falSy]
// [basSy TypeOrd] [iFcSy {basSy TypeOrd}]
// {Name TypeOrd} {Method} endRc.
// -- truSy ==> is an extension of external interface
// -- falSy ==> is an extension of external class
// -- basSy option defines base type, if not ANY / j.l.Object
// NamedType = TypeHeader
// Name = namSy byte UTFstring.
// Literal = Number | String | Set | Char | Real | falSy | truSy.
// Byte = bytSy byte.
// String = strSy UTFstring.
// Number = numSy longint.
// Real = fltSy ieee-double.
// Set = setSy integer.
// Key = keySy integer..
// Char = chrSy unicode character.
//
// Notes on the syntax:
// All record types must have a Name field, even though this is often
// redundant. The issue is that every record type (including those that
// are anonymous in CP) corresponds to a IR class, and the definer
// and the user of the class _must_ agree on the IR name of the class.
// The same reasoning applies to procedure types, which must have equal
// interface names in all modules.
// ======================================================================== *)
CONST
modSy = ORD('H'); namSy = ORD('$'); bytSy = ORD('\');
numSy = ORD('#'); chrSy = ORD('c'); strSy = ORD('s');
fltSy = ORD('r'); falSy = ORD('0'); truSy = ORD('1');
impSy = ORD('I'); setSy = ORD('S'); keySy = ORD('K');
conSy = ORD('C'); typSy = ORD('T'); tDefS = ORD('t');
prcSy = ORD('P'); retSy = ORD('R'); mthSy = ORD('M');
varSy = ORD('V'); parSy = ORD('p'); start = ORD('&');
close = ORD('!'); recSy = ORD('{'); endRc = ORD('}');
frmSy = ORD('('); fromS = ORD('@'); endFm = ORD(')');
arrSy = ORD('['); endAr = ORD(']'); pTpSy = ORD('%');
ptrSy = ORD('^'); basSy = ORD('+'); eTpSy = ORD('e');
iFcSy = ORD('~'); evtSy = ORD('v');
CONST
tOffset* = 16; (* backward compatibility with JavaVersion *)
iOffset = 1;
CONST
magic = 0DEADD0D0H;
syMag = 0D0D0DEADH;
dumped* = -1;
CONST (* record attributes *)
noAtt* = ORD(MS.noAtt); (* no attribute *)
abstr* = ORD(MS.Rabstr); (* Is ABSTRACT *)
limit* = ORD(MS.Rlimit); (* Is LIMIT *)
extns* = ORD(MS.Rextns); (* Is EXTENSIBLE *)
iFace* = ORD(MS.RiFace); (* Is INTERFACE *)
nnarg* = ORD(MS.Rnnarg); (* Has NO NoArg Constructor ( cannot use NEW() ) *)
valTp* = ORD(MS.RvalTp); (* ValueType *)
TYPE
(*
CharOpen* = POINTER TO ARRAY OF CHAR;
*)
CharOpen* = ST.CharOpen;
TypeSeq = POINTER TO
RECORD
tide: INTEGER;
high: INTEGER;
a: POINTER TO ARRAY OF MS.Type;
END;
ScopeSeq = POINTER TO
RECORD
tide: INTEGER;
high: INTEGER;
a: POINTER TO ARRAY OF MS.Namespace;
END;
Reader* = POINTER TO
RECORD
file: GF.FILE;
fasb: MS.Assembly;
fns : MS.Namespace;
sSym : INTEGER; (* the symbol read in *)
cAtt : CHAR; (* character attribute *)
iAtt : INTEGER; (* integer attribute *)
lAtt : LONGINT; (* long attribute *)
rAtt : REAL; (* real attribute *)
sAtt : ARRAY 128 OF CHAR; (* string attribute *)
sArray: ScopeSeq;
tArray: TypeSeq;
tNxt : INTEGER;
END;
(* for building temporary formal list *)
FmlList = POINTER TO
RECORD
fml: MS.Formal;
nxt: FmlList;
END;
PROCEDURE InitTypeSeq(seq: TypeSeq; capacity : INTEGER);
BEGIN
NEW(seq.a, capacity);
seq.high := capacity-1;
seq.tide := 0;
END InitTypeSeq;
PROCEDURE AppendType(VAR seq : TypeSeq; elem : MS.Type);
VAR
temp : POINTER TO ARRAY OF MS.Type;
i : INTEGER;
BEGIN
IF seq.a = NIL THEN
InitTypeSeq(seq, 2);
ELSIF seq.tide > seq.high THEN (* must expand *)
temp := seq.a;
seq.high := seq.high * 2 + 1;
NEW(seq.a, (seq.high+1));
FOR i := 0 TO seq.tide-1 DO seq.a[i] := temp[i] END;
END; (* IF *)
seq.a[seq.tide] := elem; INC(seq.tide);
END AppendType;
PROCEDURE InitScopeSeq(seq: ScopeSeq; capacity : INTEGER);
BEGIN
NEW(seq.a, capacity);
seq.high := capacity-1;
seq.tide := 0;
END InitScopeSeq;
PROCEDURE AppendScope(VAR seq : ScopeSeq; elem : MS.Namespace);
VAR
temp : POINTER TO ARRAY OF MS.Namespace;
i : INTEGER;
BEGIN
IF seq.a = NIL THEN
InitScopeSeq(seq, 2);
ELSIF seq.tide > seq.high THEN (* must expand *)
temp := seq.a;
seq.high := seq.high * 2 + 1;
NEW(seq.a, (seq.high+1));
FOR i := 0 TO seq.tide-1 DO seq.a[i] := temp[i] END;
END; (* IF *)
seq.a[seq.tide] := elem; INC(seq.tide);
END AppendScope;
PROCEDURE (rd: Reader) Read(): INTEGER, NEW;
BEGIN
RETURN GF.readByte(rd.file);
END Read;
PROCEDURE (rd: Reader) ReadChar(): CHAR, NEW;
BEGIN
RETURN CHR(rd.Read() * 256 + rd.Read());
END ReadChar;
PROCEDURE (rd: Reader) ReadInt(): INTEGER, NEW;
BEGIN [UNCHECKED_ARITHMETIC]
(* overflow checking off here *)
RETURN ((rd.Read() * 256 + rd.Read()) * 256 + rd.Read()) * 256 + rd.Read();
END ReadInt;
PROCEDURE (rd: Reader) ReadLong(): LONGINT, NEW;
VAR
result : LONGINT;
index : INTEGER;
BEGIN [UNCHECKED_ARITHMETIC]
(* overflow checking off here *)
result := rd.Read();
FOR index := 1 TO 7 DO
result := result * 256 + rd.Read();
END; (* FOR *)
RETURN result;
END ReadLong;
PROCEDURE (rd: Reader) ReadReal(): REAL, NEW;
VAR
result : LONGINT;
BEGIN
result := rd.ReadLong();
RETURN RTS.longBitsToReal(result);
END ReadReal;
PROCEDURE (rd: Reader) ReadOrd(): INTEGER, NEW;
VAR
chr : INTEGER;
BEGIN
chr := rd.Read();
IF chr <= 07FH THEN RETURN chr;
ELSE
DEC(chr, 128);
RETURN chr + rd.Read() * 128;
END; (* IF *)
END ReadOrd;
PROCEDURE (rd: Reader) ReadUTF(OUT nam : ARRAY OF CHAR), NEW;
CONST
bad = "Bad UTF-8 string";
VAR
num : INTEGER;
bNm : INTEGER;
idx : INTEGER;
chr : INTEGER;
BEGIN
num := 0;
bNm := rd.Read() * 256 + rd.Read();
FOR idx := 0 TO bNm-1 DO
chr := rd.Read();
IF chr <= 07FH THEN (* [0xxxxxxx] *)
nam[num] := CHR(chr); INC(num);
ELSIF chr DIV 32 = 06H THEN (* [110xxxxx,10xxxxxx] *)
bNm := chr MOD 32 * 64;
chr := rd.Read();
IF chr DIV 64 = 02H THEN
nam[num] := CHR(bNm + chr MOD 64); INC(num);
ELSE
RTS.Throw(bad);
END; (* IF *)
ELSIF chr DIV 16 = 0EH THEN (* [1110xxxx,10xxxxxx,10xxxxxx] *)
bNm := chr MOD 16 * 64;
chr := rd.Read();
IF chr DIV 64 = 02H THEN
bNm := (bNm + chr MOD 64) * 64;
chr := rd.Read();
IF chr DIV 64 = 02H THEN
nam[num] := CHR(bNm + chr MOD 64); INC(num);
ELSE
RTS.Throw(bad);
END; (* IF *)
ELSE
RTS.Throw(bad);
END; (* IF *)
ELSE
RTS.Throw(bad);
END; (* IF *)
END; (* FOR *)
nam[num] := 0X;
END ReadUTF;
PROCEDURE (rd: Reader) GetSym(), NEW;
BEGIN
rd.sSym := rd.Read();
CASE rd.sSym OF
| namSy :
rd.iAtt := rd.Read(); rd.ReadUTF(rd.sAtt);
| strSy :
rd.ReadUTF(rd.sAtt);
| retSy, fromS, tDefS, basSy :
rd.iAtt := rd.ReadOrd();
| bytSy :
rd.iAtt := rd.Read();
| keySy, setSy :
rd.iAtt := rd.ReadInt();
| numSy :
rd.lAtt := rd.ReadLong();
| fltSy :
rd.rAtt := rd.ReadReal();
| chrSy :
rd.cAtt := rd.ReadChar();
ELSE (* nothing to do *)
END; (* CASE *)
END GetSym;
PROCEDURE (rd: Reader) Abandon(), NEW;
BEGIN
RTS.Throw(ST.StrCat(ST.ToChrOpen("Bad symbol file format - "),
ST.ToChrOpen(GF.getFullPathName(rd.file))));
END Abandon;
PROCEDURE (rd: Reader) ReadPast(sym : INTEGER), NEW;
BEGIN
IF rd.sSym # sym THEN rd.Abandon(); END;
rd.GetSym();
END ReadPast;
PROCEDURE NewReader*(file: GF.FILE) : Reader;
VAR
new: Reader;
BEGIN
NEW(new);
NEW(new.tArray);
NEW(new.sArray);
new.file := file;
InitTypeSeq(new.tArray, 8);
InitScopeSeq(new.sArray, 8);
new.tNxt := tOffset;
RETURN new;
END NewReader;
PROCEDURE (rd: Reader) TypeOf(ord : INTEGER): MS.Type, NEW;
VAR
newT : MS.TempType;
indx : INTEGER;
rslt : MS.Type;
BEGIN
IF ord < tOffset THEN (* builtin type *)
rslt := MS.baseTypeArray[ord];
IF rslt = NIL THEN
rslt := MS.MakeDummyPrimitive(ord);
END; (* IF *)
RETURN rslt;
ELSIF ord - tOffset < rd.tArray.tide THEN (* type already read *)
RETURN rd.tArray.a[ord - tOffset];
ELSE
indx := rd.tArray.tide + tOffset;
REPEAT
(* create types and append to tArray until ord is reached *)
(* details of these types are to be fixed later *)
newT := MS.NewTempType();
newT.SetTypeOrd(indx); INC(indx);
AppendType(rd.tArray, newT);
UNTIL indx > ord;
RETURN newT;
END; (* IF *)
END TypeOf;
PROCEDURE (rd: Reader) GetTypeFromOrd(): MS.Type, NEW;
VAR
ord : INTEGER;
BEGIN
ord := rd.ReadOrd();
rd.GetSym();
RETURN rd.TypeOf(ord);
END GetTypeFromOrd;
PROCEDURE (rd: Reader) GetHeader(modname: CharOpen), NEW;
VAR
marker: INTEGER;
idx1, idx2: INTEGER;
scopeNm: CharOpen;
str: CharOpen;
BEGIN
marker := rd.ReadInt();
IF marker = RTS.loInt(magic) THEN
(* normal case, nothing to do *)
ELSIF marker = RTS.loInt(syMag) THEN
(* should never reach here for foreign module *)
ELSE
(* Error *)
Error.WriteString("File <");
Error.WriteString(GF.getFullPathName(rd.file));
Error.WriteString("> wrong format"); Error.WriteLn;
RETURN;
END; (* IF *)
rd.GetSym();
rd.ReadPast(modSy);
IF rd.sSym = namSy THEN
IF modname^ # ST.ToChrOpen(rd.sAtt)^ THEN
Error.WriteString("Wrong name in symbol file. Expected <");
Error.WriteString(modname); Error.WriteString(">, found <");
Error.WriteString(rd.sAtt); Error.WriteString(">"); Error.WriteLn;
HALT(1);
END; (* IF *)
rd.GetSym();
ELSE
RTS.Throw("Bad symfile header");
END; (* IF *)
IF rd.sSym = strSy THEN (* optional name *)
(* non-GPCP module *)
scopeNm := ST.ToChrOpen(rd.sAtt);
idx1 := ST.StrChr(scopeNm, '['); idx2 := ST.StrChr(scopeNm, ']');
str := ST.SubStr(scopeNm,idx1+1, idx2-1);
rd.fasb := MS.GetAssemblyByName(ST.StrSubChr(str,'.','_'));
ASSERT(rd.fasb # NIL);
str := ST.SubStr(scopeNm, idx2+1, LEN(scopeNm)-1);
rd.fns := rd.fasb.GetNamespace(str);
ASSERT(rd.fns # NIL);
rd.GetSym();
IF (rd.sSym = falSy) OR (rd.sSym = truSy) THEN
rd.GetSym();
ELSE
RTS.Throw("Bad explicit name");
END; (* IF *)
ELSE
(* GPCP module *)
rd.fasb := MS.GetAssemblyByName(modname);
ASSERT(rd.fasb # NIL);
rd.fns := rd.fasb.GetNamespace(modname);
ASSERT(rd.fns # NIL);
END; (* IF *)
END GetHeader;
PROCEDURE (rd: Reader) GetVersionName(), NEW;
VAR
i: INTEGER;
version: MS.Version;
token: MS.PublicKeyToken;
BEGIN
(* get the assembly version *)
ASSERT(rd.sSym = numSy); NEW(version);
version[MS.Major] := RTS.loShort(RTS.hiInt(rd.lAtt));
version[MS.Minor] := RTS.loShort(RTS.loInt(rd.lAtt));
rd.GetSym();
version[MS.Build] := RTS.loShort(RTS.hiInt(rd.lAtt));
version[MS.Revis] := RTS.loShort(RTS.loInt(rd.lAtt));
rd.fasb.SetVersion(version);
(* get the assembly public key token *)
rd.sSym := rd.Read();
ASSERT(rd.sSym = numSy); NEW(token);
FOR i := 0 TO 7 DO
token[i] := RTS.loByte(RTS.loShort(rd.Read()));
END;
rd.fasb.SetPublicKeyToken(token);
(* get next symbol *)
rd.GetSym();
END GetVersionName;
PROCEDURE (rd: Reader)GetLiteral(): MS.Literal, NEW;
VAR
lit: MS.Literal;
BEGIN
CASE rd.sSym OF
| truSy :
lit := MS.MakeBoolLiteral(TRUE);
| falSy :
lit := MS.MakeBoolLiteral(FALSE);
| numSy :
lit := MS.MakeLIntLiteral(rd.lAtt);
| chrSy :
lit := MS.MakeCharLiteral(rd.cAtt);
| fltSy :
lit := MS.MakeRealLiteral(rd.rAtt);
| setSy :
lit := MS.MakeSetLiteral(BITS(rd.iAtt));
| strSy :
lit := MS.MakeStrLiteral(ST.ToChrOpen(rd.sAtt)); (* implicit rd.sAtt^ *)
ELSE
RETURN NIL;
END; (* CASE *)
rd.GetSym(); (* read past value *)
RETURN lit;
END GetLiteral;
PROCEDURE (rd: Reader) Import, NEW;
VAR
mname: CharOpen;
asbname: CharOpen;
asbfile: CharOpen;
nsname: CharOpen;
scopeNm: CharOpen;
idx1, idx2: INTEGER;
len: INTEGER;
asb: MS.Assembly;
ns: MS.Namespace;
BEGIN
rd.ReadPast(namSy);
mname := ST.ToChrOpen(rd.sAtt);
IF rd.sSym = strSy THEN
(* non-GPCP module *)
scopeNm := ST.ToChrOpen(rd.sAtt);
idx1 := ST.StrChr(scopeNm, '['); idx2 := ST.StrChr(scopeNm, ']');
asbfile := ST.SubStr(scopeNm,idx1+1, idx2-1);
nsname := ST.SubStr(scopeNm, idx2+1, LEN(scopeNm)-1);
rd.GetSym();
ELSE
(* possible GPCP module *)
len := LEN(mname);
IF mname[len-2] = '_' THEN mname := ST.SubStr(mname, 0, len-3); END;
asbfile := mname;
nsname := mname; (* or it can be assigned as MS.NULLSPACE *)
END; (* IF *)
(* need to get the assembly real name here *)
asbname := MP.GetAssemblyRealName(asbfile);
asb := MS.InsertAssembly(asbname, asbfile);
ns := asb.InsertNamespace(nsname);
AppendScope(rd.sArray, ns);
rd.ReadPast(keySy);
END Import;
PROCEDURE (rd: Reader) ParseType, NEW;
VAR
typ: MS.TempType;
ord: INTEGER;
BEGIN
typ := MS.NewTempType(); (* this is a temporay type, not the final type *)
typ.SetName(ST.ToChrOpen(rd.sAtt));
typ.SetFullName(ST.StrCat(ST.StrCatChr(rd.fns.GetName(),'.'),typ.GetName()));
typ.SetVisibility(rd.iAtt);
ord := rd.ReadOrd();
IF ord >= tOffset THEN
ASSERT(rd.tNxt = ord);
typ.SetTypeOrd(ord);
AppendType(rd.tArray, typ); INC(rd.tNxt);
typ.SetNamespace(rd.fns);
ELSE
(* primitive types *)
END; (* IF *)
rd.GetSym();
END ParseType;
PROCEDURE (rd: Reader) GetFormalTypes(): MS.FormalList, NEW;
(*
// FormalType = [retSy TypeOrd] frmSy {parSy byte TypeOrd} endFm.
// -- optional phrase is return type for proper procedures
*)
CONST
FNAME = "arg";
VAR
rslt: MS.FormalList;
ftype: MS.Type;
fmode: INTEGER;
count: INTEGER;
temp: FmlList;
head: FmlList;
last: FmlList;
fml: MS.Formal;
pos: INTEGER;
str: CharOpen;
nametype: MS.Type;
unresolved: INTEGER;
BEGIN
head := NIL; last := NIL; count := 0; ftype := NIL; NEW(str,3); unresolved := 0;
rd.ReadPast(frmSy);
WHILE rd.sSym = parSy DO
fmode := rd.Read();
ftype := rd.GetTypeFromOrd();
RTS.IntToStr(count, str);
WITH ftype: MS.NamedType DO
fml := MS.MakeFormal(ST.StrCat(ST.ToChrOpen(FNAME),str), ftype, fmode);
| ftype: MS.TempType DO
fml := MS.MakeFormal(ST.StrCat(ST.ToChrOpen(FNAME),str), MS.dmyTyp, fmode);
(* collect reference if TempType/NamedType *)
ftype.AddReferenceFormal(fml);
INC(unresolved);
ELSE
fml := MS.MakeFormal(ST.StrCat(ST.ToChrOpen(FNAME),str), ftype, fmode);
END; (* WITH *)
(* add the formal to a temporary formals linkedlist *)
NEW(temp); temp.nxt := NIL; temp.fml := fml;
IF last # NIL THEN last.nxt := temp; last := temp; ELSE last := temp; head := temp; END;
INC(count);
END; (* WHILE *)
rd.ReadPast(endFm);
(* now I know how many formals for the method *)
rslt := MS.CreateFormalList(count);
temp := head; pos := 0;
WHILE temp # NIL DO
rslt.AddFormal(temp.fml, pos);
temp := temp.nxt; INC(pos);
END; (* WHILE *)
rslt.ostd := unresolved;
RETURN rslt;
END GetFormalTypes;
PROCEDURE FixProcTypes(rec: MS.RecordType; newM: MS.Method; fl: MS.FormalList; rtype: MS.Type);
VAR
newF: MS.Method;
BEGIN
IF MS.WithoutMethodNameMangling() THEN
newF := newM;
WITH newF: MS.Function DO
WITH rtype: MS.TempType DO
(* not a concrete return type *)
WITH rtype: MS.NamedType DO
(* return type name is resolved *)
IF fl.ostd = 0 THEN
(* no unresolved formal types names *)
newM.FixSigCode(); (* fix the sigcode of newM *)
newM := rec.AddMethod(newM);
ELSE
(* need to AddMethod after formal type names resolved *)
END; (* IF *)
ELSE
(* return type name is unresolved *)
INC(newF.ostd);
(* need to AddMethod after return type name and formal type names resolved *)
END; (* IF *)
(* collect reference if TempType/NamedType *)
rtype.AddReferenceFunction(newF);
ELSE
(* concrete return type ==> type name is solved *)
IF fl.ostd = 0 THEN
(* no unresolved formal types names *)
newM.FixSigCode(); (* fix the sigcode of newM *)
newM := rec.AddMethod(newM);
ELSE
(* need to AddMethod after formal type names resolved *)
END; (* IF *)
END; (* WITH *)
ELSE
(* not a function *)
IF fl.ostd = 0 THEN
(* no unresolved formal types names *)
newM.FixSigCode(); (* fix the sigcode of newM *)
newM := rec.AddMethod(newM);
ELSE
(* need to AddMethod after formal type names resolved *)
END; (* IF *)
END; (* WITH *)
ELSE
newM.FixSigCode(); (* fix the sigcode of newM *)
newM := rec.AddMethod(newM);
WITH newM: MS.Function DO
WITH rtype: MS.TempType DO
(* collect reference if TempType/NamedType *)
rtype.AddReferenceFunction(newM);
ELSE
END; (* WITH *)
ELSE
END; (* IF *)
END; (* IF *)
END FixProcTypes;
PROCEDURE (rd: Reader) ParseMethod(rec: MS.RecordType), NEW;
VAR
newM: MS.Method;
newF: MS.Method;
mAtt: SET;
vMod: INTEGER;
rFrm: INTEGER;
fl: MS.FormalList;
rtype: MS.Type;
rectyp: MS.Type;
mname: CharOpen;
ovlname: CharOpen;
BEGIN
NEW(newM);
mname := ST.ToChrOpen(rd.sAtt);
vMod := rd.iAtt;
(* byte1 is the method attributes *)
mAtt := BITS(rd.Read());
(* byte2 is param form of receiver *)
rFrm := rd.Read();
(* next 1 or 2 bytes are rcv-type *)
rectyp := rd.TypeOf(rd.ReadOrd());
rd.GetSym();
ovlname := NIL;
IF ~MS.WithoutMethodNameMangling() THEN
IF rd.sSym = strSy THEN
(* optional invoking method name *)
ovlname := mname;
mname := ST.ToChrOpen(rd.sAtt);
rd.GetSym();
END; (* IF *)
END; (* IF *)
rtype := NIL;
IF rd.sSym = retSy THEN
rtype := rd.TypeOf(rd.iAtt);
rd.GetSym();
END; (* IF *)
fl := rd.GetFormalTypes();
newM := rec.MakeMethod(mname, MS.Mnonstatic, rtype, fl);
IF (rectyp # NIL) & (rectyp # rec) THEN newM.SetDeclaringType(rectyp); END;
IF MS.WithoutMethodNameMangling() THEN
ELSE
IF ovlname # NIL THEN
newM.SetOverload(ovlname); (* fix the sigcode of newM *)
ELSE
END;
END; (* IF *)
newM.SetVisibility(vMod);
newM.InclAttributes(mAtt);
FixProcTypes(rec, newM, fl, rtype);
END ParseMethod;
PROCEDURE (rd: Reader) ParseProcedure(rec: MS.RecordType), NEW;
VAR
newP: MS.Method;
newF: MS.Method;
vMod: INTEGER;
rFrm: INTEGER;
fl: MS.FormalList;
rtype: MS.Type;
rectyp: MS.Type;
pname: CharOpen;
ivkname: CharOpen;
ovlname: CharOpen;
isCtor: BOOLEAN;
idx: INTEGER;
BEGIN
NEW(newP);
pname := ST.ToChrOpen(rd.sAtt);
vMod := rd.iAtt;
rd.ReadPast(namSy);
ivkname := NIL; ovlname := NIL; isCtor := FALSE;
IF rd.sSym = strSy THEN
(* optional string of invoke name if overloaded method OR Constructor *)
ivkname := ST.ToChrOpen(rd.sAtt);
rd.GetSym();
IF rd.sSym = truSy THEN
(* optional truSy shows that procedure is a constructor *)
isCtor := TRUE;
IF LEN(pname) > LEN(MS.replCtor) THEN
(* overload constructor name is in the form of "init_..." *)
ovlname := pname;
idx := ST.StrChr(ovlname,'_');
IF idx # ST.NotExist THEN
pname := ST.SubStr(ovlname, 0, idx-1);
ELSE
ASSERT(FALSE);
END; (* IF *)
ELSE
(* constructor is not overloaded *)
END; (* IF *)
rd.GetSym();
ELSE
(* not a constructor *)
ovlname := pname;
pname := ivkname;
END; (* IF *)
END; (* IF *)
rtype := NIL;
IF rd.sSym = retSy THEN
rtype := rd.TypeOf(rd.iAtt);
rd.GetSym();
END; (* IF *)
fl := rd.GetFormalTypes();
newP := rec.MakeMethod(pname, MS.Mstatic, rtype, fl);
IF isCtor THEN
newP.SetConstructor();
newP.SetInvokeName(ivkname);
END; (* IF *)
IF MS.WithoutMethodNameMangling() THEN
ELSE
IF ovlname # NIL THEN
newP.SetOverload(ovlname); (* fix the sigcode of newM *)
END;
END; (* IF *)
newP.SetVisibility(vMod);
FixProcTypes(rec, newP, fl, rtype);
END ParseProcedure;
PROCEDURE (rd: Reader) ParseRecordField(rec: MS.RecordType), NEW;
VAR
fldname: CharOpen;
fvmod: INTEGER;
ftyp: MS.Type;
fld: MS.Field;
BEGIN
fldname := ST.ToChrOpen(rd.sAtt);
fvmod := rd.iAtt;
ftyp := rd.TypeOf(rd.ReadOrd());
WITH ftyp: MS.NamedType DO
fld := rec(MS.ValueType).MakeField(fldname, ftyp, FALSE);
| ftyp: MS.TempType DO
fld := rec(MS.ValueType).MakeField(fldname, MS.dmyTyp, FALSE);
(* collect reference if TempType/NamedType *)
ftyp.AddReferenceField(fld);
ELSE
fld := rec(MS.ValueType).MakeField(fldname, ftyp, FALSE);
END; (* WITH *)
fld.SetVisibility(fvmod);
WITH rec: MS.PrimType DO (* for IntPtr and UIntPtr, otherwise StrucType *)
ASSERT(rec.AddField(fld, FALSE));
ELSE (* IntfcType should not has data member *)
ASSERT(FALSE);
END; (* WITH *)
END ParseRecordField;
PROCEDURE (rd: Reader) ParseStaticVariable(rec: MS.RecordType), NEW;
(* Variable = varSy Name TypeOrd. *)
VAR
varname: CharOpen;
vvmod: INTEGER;
vtyp: MS.Type;
newV : MS.Field;
BEGIN
varname := ST.ToChrOpen(rd.sAtt);
vvmod := rd.iAtt;
vtyp := rd.TypeOf(rd.ReadOrd());
WITH vtyp: MS.NamedType DO
newV := rec(MS.ValueType).MakeField(varname, vtyp, FALSE);
| vtyp: MS.TempType DO
newV := rec(MS.ValueType).MakeField(varname, MS.dmyTyp, FALSE);
(* collect reference if TempType/NamedType *)
vtyp.AddReferenceField(newV);
ELSE
newV := rec(MS.ValueType).MakeField(varname, vtyp, FALSE);
END; (* WITH *)
newV.SetVisibility(vvmod);
WITH rec: MS.PrimType DO (* for IntPtr and UIntPtr, otherwise StrucType *)
ASSERT(rec.AddField(newV, TRUE));
ELSE (* IntfcType should not has data member *)
ASSERT(FALSE);
END; (* WITH *)
rd.GetSym();
END ParseStaticVariable;
PROCEDURE (rd: Reader) ParseConstant(rec: MS.RecordType), NEW;
(* Constant = conSy Name Literal. *)
(* Assert: f.sSym = namSy. *)
VAR
cname: CharOpen;
cvmod: INTEGER;
ctyp: MS.Type;
cvalue: MS.Literal;
newC : MS.Field;
tord: INTEGER;
BEGIN
cname := ST.ToChrOpen(rd.sAtt);
cvmod := rd.iAtt;
rd.ReadPast(namSy);
cvalue := rd.GetLiteral();
IF cvalue IS MS.BoolLiteral THEN
tord := MS.boolN;
ELSIF cvalue IS MS.LIntLiteral THEN
tord := MS.lIntN;
ELSIF cvalue IS MS.CharLiteral THEN
tord := MS.charN;
ELSIF cvalue IS MS.RealLiteral THEN
tord := MS.realN;
ELSIF cvalue IS MS.SetLiteral THEN
tord := MS.setN;
ELSIF cvalue IS MS.StrLiteral THEN
tord := MS.strN;
ELSE
tord := MS.unCertain;
END; (* IF *)
ctyp := MS.baseTypeArray[tord];
IF ctyp = NIL THEN
ctyp := MS.MakeDummyPrimitive(tord);
END; (* IF *)
newC := rec(MS.ValueType).MakeConstant(cname, ctyp, cvalue);
newC.SetVisibility(cvmod);
WITH rec: MS.ValueType DO
ASSERT(rec.AddField(newC, TRUE));
ELSE (* IntfcType should not has data member *)
ASSERT(FALSE);
END; (* WITH *)
END ParseConstant;
PROCEDURE (rd: Reader) ParsePointerType(old: MS.Type): MS.Type, NEW;
VAR
indx: INTEGER;
rslt: MS.PointerType;
junk: MS.Type;
ns: MS.Namespace;
tname: CharOpen;
ftname: CharOpen;
target: MS.Type;
BEGIN
(* read the target type ordinal *)
indx := rd.ReadOrd();
WITH old: MS.PointerType DO
rslt := old;
(*
* Check if there is space in the tArray for this
* element, otherwise expand using typeOf().
*)
IF indx - tOffset >= rd.tArray.tide THEN
junk := rd.TypeOf(indx);
END; (* IF *)
rd.tArray.a[indx-tOffset] := rslt.GetTarget();
| old: MS.TempType DO
ns := old.GetNamespace();
IF ns = NIL THEN
(* it is an anonymous pointer to array type *)
old.SetAnonymous();
target := rd.TypeOf(indx);
rslt := MS.MakeAnonymousPointerType(target);
ELSE
tname := old.GetName();
ftname := old.GetFullName();
target := rd.TypeOf(indx);
target.SetNamespace(ns); (* the the default namespace of the target *)
rslt := ns.InsertPointer(tname,ftname,target);
rslt.SetVisibility(old.GetVisibility());
END; (* IF *)
(* changed from TempType to PointerType, so fix all references to the type *)
MS.FixReferences(old, rslt);
IF target.GetName() = NIL THEN
target.SetAnonymous();
target.SetVisibility(MS.Vprivate);
(* collect reference if TempType/NamedType *)
target(MS.TempType).AddSrcPointerType(rslt); (* <== should that be for all TempType target?? *)
ELSE
END; (* IF *)
ELSE
ASSERT(FALSE); rslt := NIL;
END; (* WITH *)
rd.GetSym();
RETURN rslt;
END ParsePointerType;
PROCEDURE (rd: Reader) ParseArrayType(tpTemp: MS.Type): MS.Type, NEW;
VAR
rslt: MS.Type;
ns: MS.Namespace;
elemTp: MS.Type;
length: INTEGER;
tname: CharOpen;
ftname: CharOpen;
sptr: MS.PointerType;
sptrname: CharOpen;
typOrd: INTEGER;
BEGIN
typOrd := rd.ReadOrd();
elemTp := rd.TypeOf(typOrd);
ns := tpTemp.GetNamespace();
IF ns = NIL THEN
(* its name (currently "DummyType") can only be fixed after its element type is determined *)
tpTemp.SetAnonymous();
IF typOrd < tOffset THEN
(* element type is primitive, and was already create by TypeOf() calling MakeDummyPrimitive() *)
tname := elemTp.GetName();
tname := ST.StrCat(tname, MS.anonArr); (* append "_arr" *)
ns := elemTp.GetNamespace(); (* []SYSTEM - for dummy primitives *)
ftname := ST.StrCatChr(ns.GetName(), '.');
ftname := ST.StrCat(ftname, tname);
ELSE
ns := elemTp.GetNamespace();
IF ns # NIL THEN
(* the anonymous array element is already known *)
tname := elemTp.GetName();
tname := ST.StrCat(tname, MS.anonArr); (* append "_arr" *)
ftname := ST.StrCatChr(ns.GetName(), '.');
ftname := ST.StrCat(ftname, tname);
ELSE
(* cannot insert this type as its element type is still unknown, and so is its namespace ??? *)
tname := ST.NullString;
ftname := tname;
END; (* IF *)
END; (* IF *)
ELSE
IF ~tpTemp.IsAnonymous() THEN
tname := tpTemp.GetName();
ftname := tpTemp.GetFullName();
ELSE
(* if array is anonymous and has namespace,
then either its element type has been parsed (ARRAY OF ParsedElement),
or it has a src pointer type (Arr1AnonymousArray = POINTER TO ARRAY OF something) *)
tname := elemTp.GetName();
IF tname # NIL THEN
tname := ST.StrCat(tname, MS.anonArr); (* append "_arr" *)
ELSE
sptr := tpTemp(MS.TempType).GetNonAnonymousPTCrossRef();
sptrname := sptr.GetName();
tname := ST.SubStr(sptrname, 4, LEN(sptrname)-1); (* get rid of "Arr1" *)
tname := ST.StrCat(tname, MS.anonArr); (* append "_arr" *)
END; (* IF *)
ftname := ST.StrCatChr(ns.GetName(), '.');
ftname := ST.StrCat(ftname, tname);
END; (* IF *)
END; (* IF *)
rd.GetSym();
IF rd.sSym = bytSy THEN
length := rd.iAtt;
rd.GetSym();
ELSIF rd.sSym = numSy THEN
length := SHORT(rd.lAtt);
rd.GetSym();
ELSE
length := 0;
END; (* IF *)
IF ns # NIL THEN
rslt := ns.InsertArray(tname, ftname, 1, length, elemTp);
rslt.SetVisibility(tpTemp.GetVisibility());
(* changed from TempType to ArrayType, so fix all references to the type *)
MS.FixReferences(tpTemp, rslt);
IF tpTemp.IsAnonymous() THEN
rslt.SetAnonymous();
ELSE
rslt.NotAnonymous();
END; (* IF *)
ELSE
(* add this to defer anonymous array insertion list*)
tpTemp(MS.TempType).SetDimension(1);
tpTemp(MS.TempType).SetLength(length);
elemTp(MS.TempType).AddAnonymousArrayType(tpTemp(MS.TempType));
rslt := tpTemp;
END; (* IF *)
rd.ReadPast(endAr);
RETURN rslt;
END ParseArrayType;
PROCEDURE (rd: Reader) ParseRecordType(old: MS.Type; typIdx: INTEGER): MS.RecordType, NEW;
(* Assert: at entry the current symbol is recSy. *)
(* Record = TypeHeader recSy recAtt [truSy | falSy | <others>] *)
(* [basSy TypeOrd] [iFcSy {basSy TypeOrd}] *)
(* {Name TypeOrd} {Method} {Statics} endRc. *)
VAR
rslt: MS.RecordType;
recAtt: INTEGER;
oldS: INTEGER;
fldD: MS.Field;
mthD: MS.Method;
conD: MS.Constant;
isValueType: BOOLEAN; (* is ValueType *)
hasNarg: BOOLEAN; (* has noarg constructor ( can use NEW() ) *)
ns: MS.Namespace;
tname: CharOpen;
ftname: CharOpen;
attr: MS.Attribute;
tt: INTEGER;
sptr: MS.PointerType;
base: MS.Type;
itfc: MS.Type;
tord: INTEGER; (* temporary type storage *)
ttyp: MS.Type; (* temporary type storage *)
fldname: CharOpen;
fvmod: INTEGER;
BEGIN
WITH old: MS.RecordType DO
rslt := old;
recAtt := rd.Read(); (* record attribute *) (* <==== *)
rd.GetSym(); (* falSy *)
rd.GetSym(); (* optional basSy *)
IF rd.sSym = basSy THEN rd.GetSym() END;
| old: MS.TempType DO
ns := old.GetNamespace();
IF ~old.IsAnonymous() THEN
tname := old.GetName();
ftname := old.GetFullName();
ELSE
(* if record is anonymous, it has only one src pointer type *)
sptr := old(MS.TempType).GetFirstPTCrossRef();
tname := ST.StrCat(sptr.GetName(), MS.anonRec);
ftname := ST.StrCatChr(ns.GetName(), '.');
ftname := ST.StrCat(ftname, tname);
END; (* IF *)
recAtt := rd.Read(); (* <==== *)
(* check for ValueType *)
IF recAtt >= valTp THEN
isValueType := TRUE; recAtt := recAtt MOD valTp;
ELSE
isValueType := FALSE;
END; (* IF *)
(* check for no NOARG constructor *)
IF recAtt >= nnarg THEN
hasNarg := FALSE; recAtt := recAtt MOD nnarg;
ELSE
hasNarg := TRUE;
END; (* IF *)
(* Record default to Struct, change to Class if found to be ClassType later (when it has event?) *)
tt := MS.Struct;
IF recAtt = iFace THEN tt := MS.Interface; END;
rd.GetSym();
IF rd.sSym = falSy THEN
ELSIF rd.sSym = truSy THEN
END; (* IF *)
rslt := ns.InsertRecord(tname, ftname, tt);
rslt.SetVisibility(old.GetVisibility());
IF isValueType THEN rslt.InclAttributes(MS.RvalTp); END;
IF hasNarg THEN rslt.SetHasNoArgConstructor(); END;
CASE recAtt OF
abstr : rslt.InclAttributes(MS.Rabstr);
| limit : (* foreign has no LIMITED attribute *)
| extns : rslt.InclAttributes(MS.Rextns);
ELSE
(* noAtt *)
END; (* CASE *)
rd.GetSym();
IF rd.sSym = basSy THEN
base := rd.TypeOf(rd.iAtt);
WITH base: MS.NamedType DO
rslt.SetBaseType(base);
| base: MS.TempType DO
(* base is a temp type *)
(* collect reference if TempType/NamedType *)
base(MS.TempType).AddDeriveRecordType(rslt);
ELSE
(* base has already been parsed *)
rslt.SetBaseType(base);
END; (* WITH *)
rd.GetSym();
END; (* IF *)
IF rd.sSym = iFcSy THEN
rd.GetSym();
WHILE rd.sSym = basSy DO
itfc := rd.TypeOf(rd.iAtt);
WITH itfc: MS.NamedType DO
(* add to interface list of rslt *)
rslt.AddInterface(itfc);
| itfc: MS.TempType DO
(* itfc is a temp type *)
(* collect reference *)
itfc(MS.TempType).AddImplRecordType(rslt);
ELSE
(* itfc has already been parsed *)
(* add to interface list of rslt *)
rslt.AddInterface(itfc);
END; (* WITH *)
rd.GetSym();
END; (* WHILE *)
END; (* IF *)
(* changed from TempType to RecordType, so fix all references to the type *)
MS.FixReferences(old, rslt);
(* need to be here as its methods, fields, etc. may reference to this new type *)
rd.tArray.a[typIdx] := rslt;
ELSE
ASSERT(FALSE); rslt := NIL;
END; (* WITH *)
WHILE rd.sSym = namSy DO
(* check for record fields *)
rd.ParseRecordField(rslt);
rd.GetSym();
(* insert the field to the record's field list *)
END; (* WHILE *)
WHILE (rd.sSym = mthSy) OR (rd.sSym = prcSy) OR
(rd.sSym = varSy) OR (rd.sSym = conSy) DO
oldS := rd.sSym; rd.GetSym();
IF oldS = mthSy THEN
rd.ParseMethod(rslt);
ELSIF oldS = prcSy THEN
rd.ParseProcedure(rslt);
ELSIF oldS = varSy THEN
rd.ParseStaticVariable(rslt);
ELSIF oldS = conSy THEN
rd.ParseConstant(rslt);
ELSE
rd.Abandon();
END; (* IF *)
END; (* WHILE *)
rd.ReadPast(endRc);
RETURN rslt;
END ParseRecordType;
PROCEDURE (rd: Reader) ParseEnumType(tpTemp: MS.Type): MS.Type, NEW;
VAR
rslt: MS.EnumType;
const: MS.Constant;
ns: MS.Namespace;
tname: CharOpen;
ftname: CharOpen;
BEGIN
rslt := NIL;
ns := tpTemp.GetNamespace();
tname := tpTemp.GetName();
ftname := tpTemp.GetFullName();
rslt := ns.InsertRecord(tname, ftname, MS.Enum)(MS.EnumType);
rslt.SetVisibility(tpTemp.GetVisibility());
(* changed from TempType to EnumType, so fix all references to the type *)
MS.FixReferences(tpTemp, rslt);
rd.GetSym();
WHILE rd.sSym = conSy DO
rd.GetSym();
rd.ParseConstant(rslt);
END; (* WHILE *)
rd.ReadPast(endRc);
RETURN rslt;
END ParseEnumType;
PROCEDURE (rd: Reader) ParseDelegType(old: MS.Type; isMul: BOOLEAN): MS.Type, NEW;
VAR
rslt: MS.PointerType;
ns: MS.Namespace;
tname: CharOpen;
ftname: CharOpen;
ttname: CharOpen;
tftname: CharOpen;
target: MS.RecordType;
rtype: MS.Type;
fl: MS.FormalList;
newM: MS.Method;
newF: MS.Method;
BEGIN
(* create the pointer *)
WITH old: MS.PointerType DO
rslt := old;
| old: MS.TempType DO
ns := old.GetNamespace();
(* pointer name *)
tname := old.GetName();
ftname := old.GetFullName();
(* target name *)
ttname := ST.StrCat(tname, MS.anonRec);
tftname := ST.StrCatChr(ns.GetName(), '.');
tftname := ST.StrCat(tftname, ttname);
(* create the target record *)
target := ns.InsertRecord(ttname, tftname, MS.Delegate);
target.SetNamespace(ns); (* the the default namespace of the target *)
target.SetAnonymous();
IF isMul THEN target.SetMulticast() END;
(* target visibility *)
target.SetVisibility(MS.Vprivate);
(* Delegate is not value type *)
(* Delegate has no noarg constructor *)
(* Delegate is neither abstract, nor extensible *)
(* lost information on base type of Delegate *)
(* lost information on interface implemented by Delegate *)
rslt := ns.InsertPointer(tname,ftname,target);
rslt.SetVisibility(old.GetVisibility());
(* changed from TempType to PointerType, so fix all references to the type *)
MS.FixReferences(old, rslt);
(* the "Invoke" method of delegate *)
rd.GetSym();
rtype := NIL;
IF rd.sSym = retSy THEN
rtype := rd.TypeOf(rd.iAtt);
rd.GetSym();
END; (* IF *)
fl := rd.GetFormalTypes();
newM := target.MakeMethod(ST.ToChrOpen("Invoke"), MS.Mnonstatic, rtype, fl);
newM.SetVisibility(MS.Vpublic); (* "Invoke" method has Public visiblilty *)
(* "Invoke" method has final {} attribute (or should it has NEW attribute) *)
(* newM.InclAttributes(MS.Mnew); *)
FixProcTypes(target, newM, fl, rtype);
ELSE
ASSERT(FALSE); rslt := NIL;
END; (* WITH *)
RETURN rslt;
END ParseDelegType;
PROCEDURE (rd: Reader) ParseTypeList*(), NEW;
(* TypeList = start { Array | Record | Pointer *)
(* | ProcType } close. *)
(* TypeHeader = tDefS Ord [fromS Ord Name]. *)
VAR
typOrd: INTEGER;
typIdx: INTEGER;
tpTemp : MS.Type;
modOrd : INTEGER;
impMod : MS.Namespace;
tpDesc : MS.Type;
BEGIN
impMod := NIL;
WHILE rd.sSym = tDefS DO
(* Do type header *)
typOrd := rd.iAtt;
typIdx := typOrd - tOffset;
tpTemp := rd.tArray.a[typIdx];
rd.ReadPast(tDefS);
(* The fromS symbol appears if the type is imported *)
IF rd.sSym = fromS THEN
modOrd := rd.iAtt;
impMod := rd.sArray.a[modOrd-1];
rd.GetSym();
(* With the strict ordering of the imports,
* it may be unnecessary to create this object
* in case the other module has been fully read
* already?
* It is also possible that the type has
* been imported already, but just as an opaque.
*)
tpTemp.SetNamespace(impMod);
rd.ReadPast(namSy);
IF tpTemp.GetName() = NIL THEN
tpTemp.SetName(ST.ToChrOpen(rd.sAtt));
ELSE
END; (* IF *)
tpTemp.SetFullName(ST.StrCat(ST.StrCatChr(impMod.GetName(),'.'), tpTemp.GetName()));
END; (* IF *)
(* GetTypeinfo *)
CASE rd.sSym OF
| arrSy :
tpDesc := rd.ParseArrayType(tpTemp);
rd.tArray.a[typIdx] := tpDesc;
| recSy :
tpDesc := rd.ParseRecordType(tpTemp, typIdx);
rd.tArray.a[typIdx] := tpDesc;
| ptrSy :
tpDesc := rd.ParsePointerType(tpTemp);
rd.tArray.a[typIdx] := tpDesc;
| evtSy :
tpDesc := rd.ParseDelegType(tpTemp, TRUE);
rd.tArray.a[typIdx] := tpDesc;
| pTpSy :
tpDesc := rd.ParseDelegType(tpTemp, FALSE);
rd.tArray.a[typIdx] := tpDesc;
| eTpSy :
tpDesc := rd.ParseEnumType(tpTemp);
rd.tArray.a[typIdx] := tpDesc;
ELSE
(* NamedTypes come here *)
IF impMod = NIL THEN impMod := rd.fns; END;
(* the outcome could be a PointerType, ArrayType or RecordType if it already exist *)
tpDesc := impMod.InsertNamedType(tpTemp.GetName(), tpTemp.GetFullName());
rd.tArray.a[typIdx] := tpDesc;
(* changed from TempType to NamedType, so fix all references to the type *)
MS.FixReferences(tpTemp, tpDesc);
END; (* CASE *)
END; (* WHILE *)
rd.ReadPast(close);
END ParseTypeList;
PROCEDURE (rd: Reader) InsertMainClass(): MS.PointerType, NEW;
VAR
tname : ST.CharOpen;
tgtname: ST.CharOpen;
target : MS.RecordType;
rslt : MS.PointerType;
base : MS.Type;
ns : MS.Namespace;
asb : MS.Assembly;
BEGIN
ASSERT(ST.StrCmp(rd.fasb.GetName(), rd.fns.GetName()) = ST.Equal);
tname := rd.fns.GetName();
tgtname := ST.StrCat(tname, MS.anonRec);
target := rd.fns.InsertRecord(tgtname, tgtname, MS.Struct);
target.SetVisibility(MS.Vpublic);
target.SetHasNoArgConstructor();
base := MS.GetTypeByName(ST.ToChrOpen("mscorlib"),ST.ToChrOpen("System"),ST.ToChrOpen("Object"));
ASSERT(base # NIL); (* mscorlib_System.Object should always exist *)
target.SetBaseType(base);
rslt := rd.fns.InsertPointer(tname,tname,target);
rslt.SetVisibility(MS.Vpublic);
RETURN rslt;
END InsertMainClass;
PROCEDURE ParseSymbolFile*(symfile: GF.FILE; modname: CharOpen);
VAR
rd: Reader;
oldS: INTEGER;
class: MS.PointerType;
rec: MS.Type;
BEGIN
rec := NIL;
rd := NewReader(symfile);
rd.GetHeader(modname);
IF rd.sSym = numSy THEN rd.GetVersionName(); END; (* optional strong name info. *)
LOOP
oldS := rd.sSym;
rd.GetSym();
CASE oldS OF
| start : EXIT;
| impSy : rd.Import();
| typSy : rd.ParseType();
| conSy : (* a global variable belongs to an GPCP module, e.g. ["[GPFiles]GPFiles"] *)
IF rec = NIL THEN
class := rd.InsertMainClass();
rec := class.GetTarget();
END; (* IF *)
WITH rec: MS.RecordType DO
rd.ParseConstant(rec);
ELSE
ASSERT(FALSE);
END; (* WITH *)
| prcSy : (* a global variable belongs to an GPCP module, e.g. ["[GPFiles]GPFiles"] *)
IF rec = NIL THEN
class := rd.InsertMainClass();
rec := class.GetTarget();
END; (* IF *)
WITH rec: MS.RecordType DO
rd.ParseProcedure(rec);
ELSE
ASSERT(FALSE);
END; (* WITH *)
| varSy : (* a global variable belongs to an GPCP module, e.g. ["[GPFiles]GPFiles"] *)
IF rec = NIL THEN
class := rd.InsertMainClass();
rec := class.GetTarget();
END; (* IF *)
WITH rec: MS.RecordType DO
rd.ParseStaticVariable(rec);
ELSE
ASSERT(FALSE);
END; (* WITH *)
ELSE
RTS.Throw("Bad object");
END; (* CASE *)
END; (* LOOP *)
rd.ParseTypeList();
IF rd.sSym # keySy THEN RTS.Throw("Missing keySy"); END;
END ParseSymbolFile;
END SymReader.
| 32.881885 | 123 | 0.52126 | [
"object"
] |
f20b7da4f53ccfbd9cd67d6a57c59c49f465dcf7 | 6,599 | cc | C++ | lib/feature_vector.cc | tmcombi/tmcombi | 976d3f333c01104e5efcabd8834854ad7677ea73 | [
"MIT"
] | null | null | null | lib/feature_vector.cc | tmcombi/tmcombi | 976d3f333c01104e5efcabd8834854ad7677ea73 | [
"MIT"
] | null | null | null | lib/feature_vector.cc | tmcombi/tmcombi | 976d3f333c01104e5efcabd8834854ad7677ea73 | [
"MIT"
] | 3 | 2019-03-31T19:04:20.000Z | 2020-01-13T22:32:09.000Z | #ifndef TMC_UNIT_TESTS
#define BOOST_TEST_MODULE lib_test_feature_vector
#endif
#include <boost/test/included/unit_test.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "feature_vector.h"
#ifndef TMC_UNIT_TESTS
bool is_critical(const std::exception& ) { return true; }
#endif
BOOST_AUTO_TEST_SUITE( feature_vector )
BOOST_AUTO_TEST_CASE( basics )
{
FeatureVector fv({11, 22});
fv.inc_weight_negatives(2).inc_weight_positives(3);
BOOST_TEST_MESSAGE("Testing feature vector: " << fv);
BOOST_REQUIRE( fv.dim() == 2 ); // throws on error
BOOST_CHECK( fv.dim() > 0 ); // continues on error
BOOST_CHECK_EQUAL( fv.get_weight_negatives(), 2 ); // continues on error
BOOST_CHECK_EQUAL( fv.get_weight_positives(), 3 );
BOOST_CHECK_EQUAL( fv.inc_weight_positives(4).get_weight_positives(), 7 );
BOOST_REQUIRE_EQUAL( fv[0], 11 );
BOOST_CHECK_EQUAL( fv[1], 22 );
}
BOOST_AUTO_TEST_CASE( from_string_buffer )
{
FeatureVector
fv("11,22,33,44,55,66,77",{3,2},5,"foo","66");
BOOST_TEST_MESSAGE("Testing feature vector: " << fv);
BOOST_CHECK_EQUAL( fv.dim(), 2 );
BOOST_CHECK_EQUAL( fv[0], 44 );
BOOST_CHECK_EQUAL( fv[1], 33 );
BOOST_CHECK( fv.get_data() == std::vector<double>({44,33}) );
BOOST_CHECK_EQUAL( fv.get_weight_positives(), 1 );
BOOST_CHECK_EQUAL( fv.get_weight_negatives(), 0 );
FeatureVector
fv1("11,22,33,44,55,66,77",{3,2},5,"foo","66", 6);
BOOST_TEST_MESSAGE("Testing feature vector: " << fv1);
BOOST_CHECK_EQUAL( fv1.get_weight_positives(), 77 );
FeatureVector
fv2("11,22,33,44,55,foo,77",{3,2},5,"foo","66", 6);
BOOST_TEST_MESSAGE("Testing feature vector: " << fv2);
BOOST_CHECK_EQUAL( fv2.get_weight_negatives(), 77 );
}
BOOST_AUTO_TEST_CASE( exceptions ) {
BOOST_TEST_MESSAGE("Testing exception operator[] out of range");
FeatureVector fv("11,22,33,44,55,66,77",{3,2},5,"foo","66");
//BOOST_CHECK_EXCEPTION( fv[234], std::out_of_range, is_critical);
BOOST_TEST_MESSAGE("Testing exception target_feature_index out of range");
BOOST_CHECK_EXCEPTION(
FeatureVector("11,22,33,44,55,66,77",{3,2},555,"foo","bar"), std::out_of_range, is_critical);
BOOST_TEST_MESSAGE("Testing exception feature_index out of range");
BOOST_CHECK_EXCEPTION(
FeatureVector("11,22,33,44,55,bar,77",{333,2},5,"foo","bar"), std::out_of_range, is_critical);
BOOST_TEST_MESSAGE("Testing exception weight_index out of range");
BOOST_CHECK_EXCEPTION(
FeatureVector("11,22,33,44,55,66,77",{3,2},5,"foo","bar",1024), std::out_of_range, is_critical);
BOOST_TEST_MESSAGE("Testing exception for unknown class");
BOOST_CHECK_EXCEPTION(
FeatureVector("11,22,33,44,55,66,77",{3,2},5,"foo","bar"), std::invalid_argument, is_critical);
BOOST_TEST_MESSAGE("Testing exception for negative weight");
BOOST_CHECK_EXCEPTION(
FeatureVector("11,22,33,44,55,bar,-77",{3,2},5,"foo","bar",6), std::invalid_argument, is_critical);
BOOST_TEST_MESSAGE("Testing exception for non-numeric weight");
BOOST_CHECK_EXCEPTION(
FeatureVector("11,22,33,44,55,bar,ab",{3,2},5,"foo","bar",6), std::invalid_argument, is_critical);
BOOST_TEST_MESSAGE("Testing exception for non-numeric feature value");
BOOST_CHECK_EXCEPTION(
FeatureVector("11,22,ab,44,55,bar,77",{3,2},5,"foo","bar"), std::invalid_argument, is_critical);
}
BOOST_AUTO_TEST_CASE( equal ) {
FeatureVector fv1("11,22,33,44,55,66,77",{3,2},5,"foo","66");
FeatureVector fv2("0,11,22,33,44,foo,77",{4,3},5,"foo","66");
FeatureVector fv3("0,11,22,33,44,foo,77",{4,3,2},5,"foo","66");
FeatureVector fv4("0,11,22,33,44,foo,77",{4,2,3},5,"foo","66");
BOOST_TEST_MESSAGE("Testing feature vectors\n"
<< "fv1 = " << fv1 << '\n'
<< "fv2 = " << fv2 << '\n'
<< "fv3 = " << fv3 << '\n'
<< "fv4 = " << fv4);
BOOST_CHECK_EQUAL(fv1, fv2);
BOOST_CHECK_NE(fv1, fv3);
BOOST_CHECK_NE(fv3, fv4);
}
BOOST_AUTO_TEST_CASE( comparison ) {
FeatureVector fv1("11,22,33,44,55,66,77",{0,1},5,"foo","66");
FeatureVector fv2("12,22,33,44,55,66,77",{0,1},5,"foo","66");
FeatureVector fv3("11,23,33,44,55,66,77",{0,1},5,"foo","66");
FeatureVector fv4("12,23,33,44,55,66,77",{0,1},5,"foo","66");
BOOST_TEST_MESSAGE("Testing feature vectors\n"
<< "fv1 = " << fv1 << '\n'
<< "fv2 = " << fv2 << '\n'
<< "fv3 = " << fv3 << '\n'
<< "fv4 = " << fv4);
BOOST_CHECK_GE( fv1, fv1 );
BOOST_CHECK_GE( fv2, fv1 );
BOOST_CHECK_GE( fv3, fv1 );
BOOST_CHECK_GE( fv4, fv2 );
BOOST_CHECK_GE( fv4, fv3 );
BOOST_CHECK_GE( fv4, fv1 );
BOOST_CHECK_GT( fv2, fv1 );
BOOST_CHECK_GT( fv3, fv1 );
BOOST_CHECK_GT( fv4, fv2 );
BOOST_CHECK_GT( fv4, fv3 );
BOOST_CHECK_GT( fv4, fv1 );
BOOST_CHECK_LE( fv1, fv1 );
BOOST_CHECK_LE( fv1, fv2 );
BOOST_CHECK_LE( fv1, fv3 );
BOOST_CHECK_LE( fv2, fv4 );
BOOST_CHECK_LE( fv3, fv4 );
BOOST_CHECK_LE( fv1, fv4 );
BOOST_CHECK_LT( fv1, fv2 );
BOOST_CHECK_LT( fv1, fv3 );
BOOST_CHECK_LT( fv2, fv4 );
BOOST_CHECK_LT( fv3, fv4 );
BOOST_CHECK_LT( fv1, fv4 );
BOOST_CHECK(!(fv2 <= fv1));
BOOST_CHECK(!(fv2 < fv1));
BOOST_CHECK(!(fv1 >= fv2));
BOOST_CHECK(!(fv1 > fv2));
BOOST_CHECK(!(fv3 <= fv2));
BOOST_CHECK(!(fv2 <= fv3));
BOOST_CHECK(!(fv3 < fv2));
BOOST_CHECK(!(fv2 < fv3));
BOOST_CHECK(!(fv3 >= fv2));
BOOST_CHECK(!(fv2 >= fv3));
BOOST_CHECK(!(fv3 > fv2));
BOOST_CHECK(!(fv2 > fv3));
}
BOOST_AUTO_TEST_CASE( ptree ) {
FeatureVector fv("11,22,33,44,55,66,77",{4,3,2},5,"foo","66");
BOOST_TEST_MESSAGE("Feature vector: " << fv);
boost::property_tree::ptree pt;
fv.dump_to_ptree(pt);
BOOST_CHECK_EQUAL(pt.size(), 5);
std::stringstream ss;
boost::property_tree::json_parser::write_json(ss, pt);
BOOST_TEST_MESSAGE("Property tree as json:\n" << ss.str());
FeatureVector fv1(pt);
BOOST_TEST_MESSAGE("Read from ptree: " << fv1);
BOOST_CHECK_EQUAL(fv.dim(), fv1.dim());
BOOST_CHECK_EQUAL(fv.get_weight_negatives(), fv1.get_weight_negatives());
BOOST_CHECK_EQUAL(fv.get_weight_positives(), fv1.get_weight_positives());
BOOST_CHECK(fv.get_data() == fv1.get_data());
}
BOOST_AUTO_TEST_SUITE_END() | 37.925287 | 111 | 0.623125 | [
"vector"
] |
35f62df4335969e815eb09bb1f5679486fc3531a | 5,294 | cpp | C++ | c++/src/Reporter.cpp | SGrosse-Holz/flocking | ac3c02e13eda5da176723fe41dad926ac552f14d | [
"MIT"
] | null | null | null | c++/src/Reporter.cpp | SGrosse-Holz/flocking | ac3c02e13eda5da176723fe41dad926ac552f14d | [
"MIT"
] | null | null | null | c++/src/Reporter.cpp | SGrosse-Holz/flocking | ac3c02e13eda5da176723fe41dad926ac552f14d | [
"MIT"
] | null | null | null | /* This file is distributed under MIT license as part of the project flocksims.
* See LICENSE file for details.
* (c) Simon Grosse-Holz, 2019
*/
# include "Reporter.h"
# include "macros.h"
# include <fstream>
# include <iostream>
# include <sstream>
using namespace flocksims;
using namespace H5;
BaseReporter::BaseReporter(std::string filename) : filename(filename), do_report(true)
{
if (filename.empty())
{
do_report = false;
return;
}
try
{
outfile = H5File(filename, H5F_ACC_TRUNC);
outfile.close();
}
catch (FileIException)
{
std::cerr << "Could not open file " << filename << " for writing!" << std::endl;
do_report = false;
}
}
HDF5Reporter::savingConformation::savingConformation(const State& state, reportMode toReport)
: Conformation(state.conf)
{
t = state.t;
this->toReport = toReport;
// Never report thm, it's useless
delete[] thm;
thm = 0;
if (toReport & reportModes::noParticles)
{
delete[] x;
delete[] y;
delete[] thp;
x = 0;
y = 0;
thp = 0;
}
if (!(toReport & reportModes::noAnalysis))
{
P = state.calc_polarization();
dSdt_discrete = state.calc_dSdt_discrete();
}
if (!(toReport & reportModes::noTheory))
{
dSdt_expected = state.calc_dSdt_expected();
}
}
void HDF5Reporter::report(const State& state, reportMode toReport)
{
if (!do_report) return;
datalist.emplace_back(state, toReport);
}
// The workhorse of the reporter. Aggregates all the data in the data list into
// big arrays and then writes those to one HDF5 file. In doing so, creates a
// new group in the file, such that this function can be called whenever we
// want to dump stuff from memory.
void HDF5Reporter::dump()
{
if (!do_report) return;
// Pool all the datasets from the list in big arrays
// Note that the particle and analysis variables have their own times
// associated with them, because they might be different.
// Note: bookkeeping is easier if we aggregate the particle data, i.e.
// x, y, thm, thp in one 3d array. It will still be
// written as 3 named 1d arrays.
double **particle_data=0, *tps=0;
std::string pd_column_names[] = {"x", "y", "theta+"};
double *tas=0, *Ses=0, *Ps=0;
double *tts=0, *Sts=0;
// Get the relevant sizes
int Tp=0, Ta=0, Tt=0;
for (const auto& conf : datalist)
{
if (!(conf.toReport & reportModes::noParticles))
Tp++;
if (!(conf.toReport & reportModes::noAnalysis))
Ta++;
if (!(conf.toReport & reportModes::noTheory))
Tt++;
}
// Allocate memory
// Note: make sure that the allocated memory is contiguous, otherwise
// HDF5 will not work
int N = datalist.front().N;
particle_data = new double*[4];
for (int i = 0; i < 3; i++)
particle_data[i] = new double[Tp*N];
tps = new double[Tp];
tas = new double[Ta];
Ses = new double[Ta];
Ps = new double[Ta];
tts = new double[Tt];
Sts = new double[Tt];
int ip=0, ia=0, it=0;
for (const auto& conf : datalist)
{
if (!(conf.toReport & reportModes::noParticles))
{
for (int in = 0; in < N; in++)
{
particle_data[0][ip*N + in] = conf.x[in];
particle_data[1][ip*N + in] = conf.y[in];
particle_data[2][ip*N + in] = conf.thp[in];
}
tps[ip] = conf.t;
ip++;
}
if (!(conf.toReport & reportModes::noAnalysis))
{
Ses[ia] = conf.dSdt_discrete;
Ps[ia] = conf.P;
tas[ia] = conf.t;
ia++;
}
if (!(conf.toReport & reportModes::noTheory))
{
Sts[it] = conf.dSdt_expected;
tts[it] = conf.t;
it++;
}
}
// Now write these big arrays to an hdf5 file, creating a new group
// every time we dump() (which should be roughly once per simulation)
static int groupID = 0;
std::stringstream ss;
ss << "/" << groupID++;
std::string group_name = ss.str();
outfile.openFile(filename, H5F_ACC_RDWR);
Group *group = new Group(outfile.createGroup(group_name));
// Particle data
hsize_t dims[] = {(hsize_t)Tp, (hsize_t)N};
DataSpace dataspace(2, dims);
FloatType datatype(PredType::NATIVE_DOUBLE);
DataSet dataset;
for (int i = 0; i < 3; i++)
{
dataset = outfile.createDataSet(group_name+"/"+pd_column_names[i], datatype, dataspace);
dataset.write(particle_data[i], datatype);
}
// The corresponding times
dataspace = DataSpace(1, dims); // dims[0] = Tp already
dataset = outfile.createDataSet(group_name+"/t_particles", datatype, dataspace);
dataset.write(tps, datatype);
// Now the analysis data
dims[0] = (hsize_t)Ta;
dataspace = DataSpace(1, dims);
dataset = outfile.createDataSet(group_name+"/t_analysis", datatype, dataspace);
dataset.write(tas, datatype);
dataset = outfile.createDataSet(group_name+"/dSdt_discrete", datatype, dataspace);
dataset.write(Ses, datatype);
dataset = outfile.createDataSet(group_name+"/P+", datatype, dataspace);
dataset.write(Ps, datatype);
// And the theory stuff
dims[0] = (hsize_t)Tt;
dataspace = DataSpace(1, dims);
dataset = outfile.createDataSet(group_name+"/t_theory", datatype, dataspace);
dataset.write(tas, datatype);
dataset = outfile.createDataSet(group_name+"/dSdt_expected", datatype, dataspace);
dataset.write(Sts, datatype);
// Clean up
outfile.close();
delete group;
for (int i = 0; i < 3; i++)
delete[] particle_data[i];
delete[] particle_data;
delete[] tps;
delete[] tas;
delete[] Ses;
delete[] Ps;
delete[] tts;
delete[] Sts;
}
| 24.85446 | 93 | 0.670382 | [
"3d"
] |
35fd2fa3205d48d4106d8e325e57753f14a0c952 | 22,298 | cc | C++ | scripts/cbrem/ezcaRoot/src/ezcaRootDict.cc | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | scripts/cbrem/ezcaRoot/src/ezcaRootDict.cc | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | scripts/cbrem/ezcaRoot/src/ezcaRootDict.cc | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | //
// File generated by rootcint at Thu Mar 5 10:47:37 2015
// Do NOT change. Changes will be lost next time file is generated
//
#define R__DICTIONARY_FILENAME srcdIezcaRootDict
#include "RConfig.h" //rootcint 4834
#if !defined(R__ACCESS_IN_SYMBOL)
//Break the privacy of classes -- Disabled for the moment
#define private public
#define protected public
#endif
// Since CINT ignores the std namespace, we need to do so in this file.
namespace std {} using namespace std;
#include "ezcaRootDict.h"
#include "TClass.h"
#include "TBuffer.h"
#include "TMemberInspector.h"
#include "TInterpreter.h"
#include "TVirtualMutex.h"
#include "TError.h"
#ifndef G__ROOT
#define G__ROOT
#endif
#include "RtypesImp.h"
#include "TIsAProxy.h"
#include "TFileMergeInfo.h"
// Direct notice to TROOT of the dictionary's loading.
namespace {
static struct DictInit {
DictInit() {
ROOT::RegisterModule();
}
} __TheDictionaryInitializer;
}
// START OF SHADOWS
namespace ROOT {
namespace Shadow {
} // of namespace Shadow
} // of namespace ROOT
// END OF SHADOWS
/********************************************************
* src/ezcaRootDict.cc
* CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED
* FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX().
* CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE.
********************************************************/
#ifdef G__MEMTEST
#undef malloc
#undef free
#endif
#if defined(__GNUC__) && __GNUC__ >= 4 && ((__GNUC_MINOR__ == 2 && __GNUC_PATCHLEVEL__ >= 1) || (__GNUC_MINOR__ >= 3))
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
extern "C" void G__cpp_reset_tagtableezcaRootDict();
extern "C" void G__set_cpp_environmentezcaRootDict() {
G__add_compiledheader("TObject.h");
G__add_compiledheader("TMemberInspector.h");
G__add_compiledheader("src/ezcaRoot.h");
G__cpp_reset_tagtableezcaRootDict();
}
#include <new>
extern "C" int G__cpp_dllrevezcaRootDict() { return(30051515); }
/*********************************************************
* Member function Interface Method
*********************************************************/
/* Setting up global function */
static int G__ezcaRootDict__0_289(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGet((char*) G__int(libp->para[0]), (char) G__int(libp->para[1])
, (int) G__int(libp->para[2]), (void*) G__int(libp->para[3])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_290(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetChar((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (char*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_291(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetString((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (char*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_292(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetShort((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (short*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_293(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetFloat((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (float*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_294(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetDouble((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (double*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_295(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsPut((char*) G__int(libp->para[0]), (char) G__int(libp->para[1])
, (int) G__int(libp->para[2]), (void*) G__int(libp->para[3])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_296(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsPutChar((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (char*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_297(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsPutString((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (char*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_298(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsPutShort((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (short*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_299(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsPutFloat((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (float*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_300(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsPutDouble((char*) G__int(libp->para[0]), (int) G__int(libp->para[1])
, (double*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_301(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetControlLimits((char*) G__int(libp->para[0]), (double*) G__int(libp->para[1])
, (double*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_302(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetGraphicLimits((char*) G__int(libp->para[0]), (double*) G__int(libp->para[1])
, (double*) G__int(libp->para[2])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_303(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetNelem((char*) G__int(libp->para[0]), (int*) G__int(libp->para[1])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_304(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetPrecision((char*) G__int(libp->para[0]), (short*) G__int(libp->para[1])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_305(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetUnits((char*) G__int(libp->para[0]), (char*) G__int(libp->para[1])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_306(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsPutOldCa((char*) G__int(libp->para[0]), (char) G__int(libp->para[1])
, (int) G__int(libp->para[2]), (void*) G__int(libp->para[3])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_308(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letdouble(result7, 102, (double) epicsGetTimeout());
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_309(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsSetTimeout((float) G__double(libp->para[0])));
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_310(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsGetRetryCount());
return(1 || funcname || hash || result7 || libp) ;
}
static int G__ezcaRootDict__0_311(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash)
{
G__letint(result7, 105, (long) epicsSetRetryCount((int) G__int(libp->para[0])));
return(1 || funcname || hash || result7 || libp) ;
}
/*********************************************************
* Member function Stub
*********************************************************/
/*********************************************************
* Global function Stub
*********************************************************/
/*********************************************************
* Get size of pointer to member function
*********************************************************/
class G__Sizep2memfuncezcaRootDict {
public:
G__Sizep2memfuncezcaRootDict(): p(&G__Sizep2memfuncezcaRootDict::sizep2memfunc) {}
size_t sizep2memfunc() { return(sizeof(p)); }
private:
size_t (G__Sizep2memfuncezcaRootDict::*p)();
};
size_t G__get_sizep2memfuncezcaRootDict()
{
G__Sizep2memfuncezcaRootDict a;
G__setsizep2memfunc((int)a.sizep2memfunc());
return((size_t)a.sizep2memfunc());
}
/*********************************************************
* virtual base class offset calculation interface
*********************************************************/
/* Setting up class inheritance */
/*********************************************************
* Inheritance information setup/
*********************************************************/
extern "C" void G__cpp_setup_inheritanceezcaRootDict() {
/* Setting up class inheritance */
}
/*********************************************************
* typedef information setup/
*********************************************************/
extern "C" void G__cpp_setup_typetableezcaRootDict() {
/* Setting up typedef entry */
G__search_typename2("vector<ROOT::TSchemaHelper>",117,G__get_linked_tagnum(&G__ezcaRootDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR),0,-1);
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__ezcaRootDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__ezcaRootDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__ezcaRootDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__ezcaRootDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("vector<TVirtualArray*>",117,G__get_linked_tagnum(&G__ezcaRootDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR),0,-1);
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__ezcaRootDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__ezcaRootDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR));
G__setnewtype(-1,NULL,0);
G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__ezcaRootDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__ezcaRootDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR));
G__setnewtype(-1,NULL,0);
}
/*********************************************************
* Data Member information setup/
*********************************************************/
/* Setting up class,struct,union tag member variable */
extern "C" void G__cpp_setup_memvarezcaRootDict() {
}
/***********************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
***********************************************************/
/*********************************************************
* Member function information setup for each class
*********************************************************/
/*********************************************************
* Member function information setup
*********************************************************/
extern "C" void G__cpp_setup_memfuncezcaRootDict() {
}
/*********************************************************
* Global variable information setup for each class
*********************************************************/
static void G__cpp_setup_global0() {
/* Setting up global variables */
G__resetplocal();
}
static void G__cpp_setup_global1() {
G__memvar_setup((void*)G__PVOID,105,0,1,G__get_linked_tagnum(&G__ezcaRootDictLN_EEpicsTypes),-1,-1,1,"kEpicsBYTE=0",0,(char*)NULL);
G__memvar_setup((void*)G__PVOID,105,0,1,G__get_linked_tagnum(&G__ezcaRootDictLN_EEpicsTypes),-1,-1,1,"kEpicsSTRING=1",0,(char*)NULL);
G__memvar_setup((void*)G__PVOID,105,0,1,G__get_linked_tagnum(&G__ezcaRootDictLN_EEpicsTypes),-1,-1,1,"kEpicsSHORT=2",0,(char*)NULL);
G__memvar_setup((void*)G__PVOID,105,0,1,G__get_linked_tagnum(&G__ezcaRootDictLN_EEpicsTypes),-1,-1,1,"kEpicsLONG=3",0,(char*)NULL);
G__memvar_setup((void*)G__PVOID,105,0,1,G__get_linked_tagnum(&G__ezcaRootDictLN_EEpicsTypes),-1,-1,1,"kEpicsFLOAT=4",0,(char*)NULL);
G__memvar_setup((void*)G__PVOID,105,0,1,G__get_linked_tagnum(&G__ezcaRootDictLN_EEpicsTypes),-1,-1,1,"kEpicsDOUBLE=5",0,(char*)NULL);
G__resetglobalenv();
}
extern "C" void G__cpp_setup_globalezcaRootDict() {
G__cpp_setup_global0();
G__cpp_setup_global1();
}
/*********************************************************
* Global function information setup for each class
*********************************************************/
static void G__cpp_setup_func0() {
G__lastifuncposition();
}
static void G__cpp_setup_func1() {
}
static void G__cpp_setup_func2() {
G__memfunc_setup("epicsGet", 820, G__ezcaRootDict__0_289, 105, -1, -1, 0, 4, 1, 1, 0,
"C - - 0 - pvname c - - 0 - ezcatype "
"i - - 0 - nelem Y - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetChar", 1202, G__ezcaRootDict__0_290, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"C - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetString", 1451, G__ezcaRootDict__0_291, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"C - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetShort", 1348, G__ezcaRootDict__0_292, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"S - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetFloat", 1322, G__ezcaRootDict__0_293, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"F - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetDouble", 1423, G__ezcaRootDict__0_294, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"D - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsPut", 845, G__ezcaRootDict__0_295, 105, -1, -1, 0, 4, 1, 1, 0,
"C - - 0 - pvname c - - 0 - ezcatype "
"i - - 0 - nelem Y - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsPutChar", 1227, G__ezcaRootDict__0_296, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"C - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsPutString", 1476, G__ezcaRootDict__0_297, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"C - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsPutShort", 1373, G__ezcaRootDict__0_298, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"S - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsPutFloat", 1347, G__ezcaRootDict__0_299, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"F - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsPutDouble", 1448, G__ezcaRootDict__0_300, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname i - - 0 - nelem "
"D - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetControlLimits", 2183, G__ezcaRootDict__0_301, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname D - - 0 - low "
"D - - 0 - high", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetGraphicLimits", 2148, G__ezcaRootDict__0_302, 105, -1, -1, 0, 3, 1, 1, 0,
"C - - 0 - pvname D - - 0 - low "
"D - - 0 - high", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetNelem", 1317, G__ezcaRootDict__0_303, 105, -1, -1, 0, 2, 1, 1, 0,
"C - - 0 - pvname I - - 0 - nelem", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetPrecision", 1760, G__ezcaRootDict__0_304, 105, -1, -1, 0, 2, 1, 1, 0,
"C - - 0 - pvname S - - 0 - precision", (char*) NULL
, (void*) NULL, 0);
}
static void G__cpp_setup_func3() {
G__memfunc_setup("epicsGetUnits", 1351, G__ezcaRootDict__0_305, 105, -1, -1, 0, 2, 1, 1, 0,
"C - - 0 - pvname C - - 0 - units", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsPutOldCa", 1296, G__ezcaRootDict__0_306, 105, -1, -1, 0, 4, 1, 1, 0,
"C - - 0 - pvname c - - 0 - ezcatype "
"i - - 0 - nelem Y - - 0 - data_buff", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetTimeout", 1563, G__ezcaRootDict__0_308, 102, -1, -1, 0, 0, 1, 1, 0, "", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsSetTimeout", 1575, G__ezcaRootDict__0_309, 105, -1, -1, 0, 1, 1, 1, 0, "f - - 0 - sec", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsGetRetryCount", 1875, G__ezcaRootDict__0_310, 105, -1, -1, 0, 0, 1, 1, 0, "", (char*) NULL
, (void*) NULL, 0);
G__memfunc_setup("epicsSetRetryCount", 1887, G__ezcaRootDict__0_311, 105, -1, -1, 0, 1, 1, 1, 0, "i - - 0 - retry", (char*) NULL
, (void*) NULL, 0);
G__resetifuncposition();
}
extern "C" void G__cpp_setup_funcezcaRootDict() {
G__cpp_setup_func0();
G__cpp_setup_func1();
G__cpp_setup_func2();
G__cpp_setup_func3();
}
/*********************************************************
* Class,struct,union,enum tag information setup
*********************************************************/
/* Setup class/struct taginfo */
G__linked_taginfo G__ezcaRootDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR = { "vector<ROOT::TSchemaHelper,allocator<ROOT::TSchemaHelper> >" , 99 , -1 };
G__linked_taginfo G__ezcaRootDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR = { "reverse_iterator<vector<ROOT::TSchemaHelper,allocator<ROOT::TSchemaHelper> >::iterator>" , 99 , -1 };
G__linked_taginfo G__ezcaRootDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR = { "vector<TVirtualArray*,allocator<TVirtualArray*> >" , 99 , -1 };
G__linked_taginfo G__ezcaRootDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR = { "reverse_iterator<vector<TVirtualArray*,allocator<TVirtualArray*> >::iterator>" , 99 , -1 };
G__linked_taginfo G__ezcaRootDictLN_EEpicsTypes = { "EEpicsTypes" , 101 , -1 };
/* Reset class/struct taginfo */
extern "C" void G__cpp_reset_tagtableezcaRootDict() {
G__ezcaRootDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR.tagnum = -1 ;
G__ezcaRootDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR.tagnum = -1 ;
G__ezcaRootDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR.tagnum = -1 ;
G__ezcaRootDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR.tagnum = -1 ;
G__ezcaRootDictLN_EEpicsTypes.tagnum = -1 ;
}
extern "C" void G__cpp_setup_tagtableezcaRootDict() {
/* Setting up class,struct,union tag entry */
G__get_linked_tagnum_fwd(&G__ezcaRootDictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR);
G__get_linked_tagnum_fwd(&G__ezcaRootDictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR);
G__get_linked_tagnum_fwd(&G__ezcaRootDictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR);
G__get_linked_tagnum_fwd(&G__ezcaRootDictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR);
G__tagtable_setup(G__get_linked_tagnum_fwd(&G__ezcaRootDictLN_EEpicsTypes),sizeof(int),-1,0,(char*)NULL,NULL,NULL);
}
extern "C" void G__cpp_setupezcaRootDict(void) {
G__check_setup_version(30051515,"G__cpp_setupezcaRootDict()");
G__set_cpp_environmentezcaRootDict();
G__cpp_setup_tagtableezcaRootDict();
G__cpp_setup_inheritanceezcaRootDict();
G__cpp_setup_typetableezcaRootDict();
G__cpp_setup_memvarezcaRootDict();
G__cpp_setup_memfuncezcaRootDict();
G__cpp_setup_globalezcaRootDict();
G__cpp_setup_funcezcaRootDict();
if(0==G__getsizep2memfunc()) G__get_sizep2memfuncezcaRootDict();
return;
}
class G__cpp_setup_initezcaRootDict {
public:
G__cpp_setup_initezcaRootDict() { G__add_setup_func("ezcaRootDict",(G__incsetup)(&G__cpp_setupezcaRootDict)); G__call_setup_funcs(); }
~G__cpp_setup_initezcaRootDict() { G__remove_setup_func("ezcaRootDict"); }
};
G__cpp_setup_initezcaRootDict G__cpp_setup_initializerezcaRootDict;
| 44.596 | 319 | 0.653198 | [
"vector"
] |
c401cb8a2c67183ddf9f7b8f84a9a9877793970b | 46,332 | cpp | C++ | src/stream.cpp | UniversalLaserSystems/libuvc | d9727f8d4d4b8a5f708441d7802fe825fe984c1a | [
"BSD-3-Clause"
] | null | null | null | src/stream.cpp | UniversalLaserSystems/libuvc | d9727f8d4d4b8a5f708441d7802fe825fe984c1a | [
"BSD-3-Clause"
] | null | null | null | src/stream.cpp | UniversalLaserSystems/libuvc | d9727f8d4d4b8a5f708441d7802fe825fe984c1a | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (C) 2010-2012 Ken Tossell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the author nor other contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/**
* @defgroup streaming Streaming control functions
* @brief Tools for creating, managing and consuming video streams
*/
#include "libuvc/libuvc.h"
#include "libuvc/libuvc_internal.h"
#include "errno.h"
#include <algorithm>
#include <iterator>
#include <memory>
uvc_frame_desc_t *uvc_find_frame_desc_stream(uvc_stream_handle_t *strmh,
uint16_t format_id, uint16_t frame_id);
uvc_frame_desc_t *uvc_find_frame_desc(uvc_device_handle_t *devh,
uint16_t format_id, uint16_t frame_id);
void *_uvc_user_caller(void *arg);
void _uvc_populate_frame(uvc_stream_handle_t *strmh);
static uvc_streaming_interface_t *_uvc_get_stream_if(uvc_device_handle_t *devh, int interface_idx);
static uvc_stream_handle_t *_uvc_get_stream_by_interface(uvc_device_handle_t *devh, int interface_idx);
struct format_table_entry {
enum uvc_frame_format format;
uint8_t abstract_fmt;
uint8_t guid[16];
int children_count;
enum uvc_frame_format *children;
};
struct format_table_entry *_get_format_entry(enum uvc_frame_format format) {
#define ABS_FMT(_fmt, _num, ...) \
case _fmt: { \
static enum uvc_frame_format _fmt##_children[] = __VA_ARGS__; \
static struct format_table_entry _fmt##_entry = { \
_fmt, 0, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, _num, _fmt##_children }; \
return &_fmt##_entry; }
#define FMT(_fmt, ...) \
case _fmt: { \
static struct format_table_entry _fmt##_entry = { \
_fmt, 0, __VA_ARGS__, 0, NULL }; \
return &_fmt##_entry; }
switch(format) {
/* Define new formats here */
ABS_FMT(UVC_FRAME_FORMAT_ANY, 2,
{UVC_FRAME_FORMAT_UNCOMPRESSED, UVC_FRAME_FORMAT_COMPRESSED})
ABS_FMT(UVC_FRAME_FORMAT_UNCOMPRESSED, 6,
{UVC_FRAME_FORMAT_YUYV, UVC_FRAME_FORMAT_UYVY, UVC_FRAME_FORMAT_GRAY8,
UVC_FRAME_FORMAT_GRAY16, UVC_FRAME_FORMAT_NV12, UVC_FRAME_FORMAT_BGR})
FMT(UVC_FRAME_FORMAT_YUYV,
{'Y', 'U', 'Y', '2', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_UYVY,
{'U', 'Y', 'V', 'Y', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_GRAY8,
{'Y', '8', '0', '0', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_GRAY16,
{'Y', '1', '6', ' ', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_NV12,
{'N', 'V', '1', '2', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_BGR,
{0x7d, 0xeb, 0x36, 0xe4, 0x4f, 0x52, 0xce, 0x11, 0x9f, 0x53, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70})
FMT(UVC_FRAME_FORMAT_BY8,
{'B', 'Y', '8', ' ', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_BA81,
{'B', 'A', '8', '1', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_SGRBG8,
{'G', 'R', 'B', 'G', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_SGBRG8,
{'G', 'B', 'R', 'G', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_SRGGB8,
{'R', 'G', 'G', 'B', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
FMT(UVC_FRAME_FORMAT_SBGGR8,
{'B', 'G', 'G', 'R', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
ABS_FMT(UVC_FRAME_FORMAT_COMPRESSED, 2,
{UVC_FRAME_FORMAT_MJPEG, UVC_FRAME_FORMAT_H264})
FMT(UVC_FRAME_FORMAT_MJPEG,
{'M', 'J', 'P', 'G'})
FMT(UVC_FRAME_FORMAT_H264,
{'H', '2', '6', '4', 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71})
default:
return NULL;
}
#undef ABS_FMT
#undef FMT
}
static uint8_t _uvc_frame_format_matches_guid(enum uvc_frame_format fmt, uint8_t guid[16]) {
struct format_table_entry *format;
int child_idx;
format = _get_format_entry(fmt);
if (!format)
return 0;
if (!format->abstract_fmt && !memcmp(guid, format->guid, 16))
return 1;
for (child_idx = 0; child_idx < format->children_count; child_idx++) {
if (_uvc_frame_format_matches_guid(format->children[child_idx], guid))
return 1;
}
return 0;
}
static enum uvc_frame_format uvc_frame_format_for_guid(uint8_t guid[16]) {
struct format_table_entry *format;
int fmt;
for (fmt = 0; fmt < UVC_FRAME_FORMAT_COUNT; ++fmt) {
format = _get_format_entry(static_cast<enum uvc_frame_format>(fmt));
if (!format || format->abstract_fmt)
continue;
if (!memcmp(format->guid, guid, 16))
return format->format;
}
return UVC_FRAME_FORMAT_UNKNOWN;
}
/** @internal
* Run a streaming control query
* @param[in] devh UVC device
* @param[in,out] ctrl Control block
* @param[in] probe Whether this is a probe query or a commit query
* @param[in] req Query type
*/
uvc_error_t uvc_query_stream_ctrl(
uvc_device_handle_t *devh,
uvc_stream_ctrl_t *ctrl,
uint8_t probe,
enum uvc_req_code req) {
uint8_t buf[34];
size_t len;
int err;
memset(buf, 0, sizeof(buf));
if (devh->info->ctrl_if.bcdUVC >= 0x0110)
len = 34;
else
len = 26;
/* prepare for a SET transfer */
if (req == UVC_SET_CUR) {
SHORT_TO_SW(ctrl->bmHint, buf);
buf[2] = ctrl->bFormatIndex;
buf[3] = ctrl->bFrameIndex;
INT_TO_DW(ctrl->dwFrameInterval, buf + 4);
SHORT_TO_SW(ctrl->wKeyFrameRate, buf + 8);
SHORT_TO_SW(ctrl->wPFrameRate, buf + 10);
SHORT_TO_SW(ctrl->wCompQuality, buf + 12);
SHORT_TO_SW(ctrl->wCompWindowSize, buf + 14);
SHORT_TO_SW(ctrl->wDelay, buf + 16);
INT_TO_DW(ctrl->dwMaxVideoFrameSize, buf + 18);
INT_TO_DW(ctrl->dwMaxPayloadTransferSize, buf + 22);
if (len == 34) {
INT_TO_DW ( ctrl->dwClockFrequency, buf + 26 );
buf[30] = ctrl->bmFramingInfo;
buf[31] = ctrl->bPreferredVersion;
buf[32] = ctrl->bMinVersion;
buf[33] = ctrl->bMaxVersion;
/** @todo support UVC 1.1 */
}
}
/* do the transfer */
err = libusb_control_transfer(
devh->usb_devh,
req == UVC_SET_CUR ? 0x21 : 0xA1,
req,
probe ? (UVC_VS_PROBE_CONTROL << 8) : (UVC_VS_COMMIT_CONTROL << 8),
ctrl->bInterfaceNumber,
buf, static_cast<uint16_t>(len), 0
);
if (err <= 0) {
return static_cast<uvc_error_t>(err);
}
/* now decode following a GET transfer */
if (req != UVC_SET_CUR) {
ctrl->bmHint = SW_TO_SHORT(buf);
ctrl->bFormatIndex = buf[2];
ctrl->bFrameIndex = buf[3];
ctrl->dwFrameInterval = DW_TO_INT(buf + 4);
ctrl->wKeyFrameRate = SW_TO_SHORT(buf + 8);
ctrl->wPFrameRate = SW_TO_SHORT(buf + 10);
ctrl->wCompQuality = SW_TO_SHORT(buf + 12);
ctrl->wCompWindowSize = SW_TO_SHORT(buf + 14);
ctrl->wDelay = SW_TO_SHORT(buf + 16);
ctrl->dwMaxVideoFrameSize = DW_TO_INT(buf + 18);
ctrl->dwMaxPayloadTransferSize = DW_TO_INT(buf + 22);
if (len == 34) {
ctrl->dwClockFrequency = DW_TO_INT ( buf + 26 );
ctrl->bmFramingInfo = buf[30];
ctrl->bPreferredVersion = buf[31];
ctrl->bMinVersion = buf[32];
ctrl->bMaxVersion = buf[33];
/** @todo support UVC 1.1 */
}
else
ctrl->dwClockFrequency = devh->info->ctrl_if.dwClockFrequency;
/* fix up block for cameras that fail to set dwMax* */
if (ctrl->dwMaxVideoFrameSize == 0) {
uvc_frame_desc_t *frame = uvc_find_frame_desc(devh, ctrl->bFormatIndex, ctrl->bFrameIndex);
if (frame) {
ctrl->dwMaxVideoFrameSize = frame->dwMaxVideoFrameBufferSize;
}
}
}
return UVC_SUCCESS;
}
/** @internal
* Run a streaming control query
* @param[in] devh UVC device
* @param[in,out] ctrl Control block
* @param[in] probe Whether this is a probe query or a commit query
* @param[in] req Query type
*/
uvc_error_t uvc_query_still_ctrl(
uvc_device_handle_t *devh,
uvc_still_ctrl_t *still_ctrl,
uint8_t probe,
enum uvc_req_code req) {
uint8_t buf[11];
const size_t len = 11;
int err;
memset(buf, 0, sizeof(buf));
if (req == UVC_SET_CUR) {
/* prepare for a SET transfer */
buf[0] = still_ctrl->bFormatIndex;
buf[1] = still_ctrl->bFrameIndex;
buf[2] = still_ctrl->bCompressionIndex;
INT_TO_DW(still_ctrl->dwMaxVideoFrameSize, buf + 3);
INT_TO_DW(still_ctrl->dwMaxPayloadTransferSize, buf + 7);
}
/* do the transfer */
err = libusb_control_transfer(
devh->usb_devh,
req == UVC_SET_CUR ? 0x21 : 0xA1,
req,
probe ? (UVC_VS_STILL_PROBE_CONTROL << 8) : (UVC_VS_STILL_COMMIT_CONTROL << 8),
still_ctrl->bInterfaceNumber,
buf, len, 0
);
if (err <= 0) {
return static_cast<uvc_error_t>(err);
}
/* now decode following a GET transfer */
if (req != UVC_SET_CUR) {
still_ctrl->bFormatIndex = buf[0];
still_ctrl->bFrameIndex = buf[1];
still_ctrl->bCompressionIndex = buf[2];
still_ctrl->dwMaxVideoFrameSize = DW_TO_INT(buf + 3);
still_ctrl->dwMaxPayloadTransferSize = DW_TO_INT(buf + 7);
}
return UVC_SUCCESS;
}
/** Initiate a method 2 (in stream) still capture
* @ingroup streaming
*
* @param[in] devh Device handle
* @param[in] still_ctrl Still capture control block
*/
uvc_error_t uvc_trigger_still(
uvc_device_handle_t *devh,
uvc_still_ctrl_t *still_ctrl) {
uvc_stream_handle_t* stream;
uvc_streaming_interface_t* stream_if;
uint8_t buf;
int err;
/* Stream must be running for method 2 to work */
stream = _uvc_get_stream_by_interface(devh, still_ctrl->bInterfaceNumber);
if (!stream || !stream->running)
return UVC_ERROR_NOT_SUPPORTED;
/* Only method 2 is supported */
stream_if = _uvc_get_stream_if(devh, still_ctrl->bInterfaceNumber);
if(!stream_if || stream_if->bStillCaptureMethod != 2)
return UVC_ERROR_NOT_SUPPORTED;
/* prepare for a SET transfer */
buf = 1;
/* do the transfer */
err = libusb_control_transfer(
devh->usb_devh,
0x21, //type set
UVC_SET_CUR,
(UVC_VS_STILL_IMAGE_TRIGGER_CONTROL << 8),
still_ctrl->bInterfaceNumber,
&buf, 1, 0);
if (err <= 0) {
return static_cast<uvc_error_t>(err);
}
return UVC_SUCCESS;
}
/** @brief Reconfigure stream with a new stream format.
* @ingroup streaming
*
* This may be executed whether or not the stream is running.
*
* @param[in] strmh Stream handle
* @param[in] ctrl Control block, processed using {uvc_probe_stream_ctrl} or
* {uvc_get_stream_ctrl_format_size}
*/
uvc_error_t uvc_stream_ctrl(uvc_stream_handle_t *strmh, uvc_stream_ctrl_t *ctrl) {
uvc_error_t ret;
if (strmh->stream_if->bInterfaceNumber != ctrl->bInterfaceNumber)
return UVC_ERROR_INVALID_PARAM;
/* @todo Allow the stream to be modified without restarting the stream */
if (strmh->running)
return UVC_ERROR_BUSY;
ret = uvc_query_stream_ctrl(strmh->devh, ctrl, 0, UVC_SET_CUR);
if (ret != UVC_SUCCESS)
return ret;
strmh->cur_ctrl = *ctrl;
return UVC_SUCCESS;
}
/** @internal
* @brief Find the descriptor for a specific frame configuration
* @param stream_if Stream interface
* @param format_id Index of format class descriptor
* @param frame_id Index of frame descriptor
*/
static uvc_frame_desc_t *_uvc_find_frame_desc_stream_if(uvc_streaming_interface_t *stream_if,
uint16_t format_id, uint16_t frame_id) {
uvc_format_desc_t *format = NULL;
uvc_frame_desc_t *frame = NULL;
DL_FOREACH(stream_if->format_descs, format) {
if (format->bFormatIndex == format_id) {
DL_FOREACH(format->frame_descs, frame) {
if (frame->bFrameIndex == frame_id)
return frame;
}
}
}
return NULL;
}
uvc_frame_desc_t *uvc_find_frame_desc_stream(uvc_stream_handle_t *strmh,
uint16_t format_id, uint16_t frame_id) {
return _uvc_find_frame_desc_stream_if(strmh->stream_if, format_id, frame_id);
}
/** @internal
* @brief Find the descriptor for a specific frame configuration
* @param devh UVC device
* @param format_id Index of format class descriptor
* @param frame_id Index of frame descriptor
*/
uvc_frame_desc_t *uvc_find_frame_desc(uvc_device_handle_t *devh,
uint16_t format_id, uint16_t frame_id) {
uvc_streaming_interface_t *stream_if;
uvc_frame_desc_t *frame;
DL_FOREACH(devh->info->stream_ifs, stream_if) {
frame = _uvc_find_frame_desc_stream_if(stream_if, format_id, frame_id);
if (frame)
return frame;
}
return NULL;
}
/** Get a negotiated streaming control block for some common parameters.
* @ingroup streaming
*
* @param[in] devh Device handle
* @param[in,out] ctrl Control block
* @param[in] format_class Type of streaming format
* @param[in] width Desired frame width
* @param[in] height Desired frame height
* @param[in] fps Frame rate, frames per second
*/
uvc_error_t uvc_get_stream_ctrl_format_size(
uvc_device_handle_t *devh,
uvc_stream_ctrl_t *ctrl,
enum uvc_frame_format cf,
int width, int height,
int fps) {
uvc_streaming_interface_t *stream_if;
/* find a matching frame descriptor and interval */
DL_FOREACH(devh->info->stream_ifs, stream_if) {
uvc_format_desc_t *format;
DL_FOREACH(stream_if->format_descs, format) {
uvc_frame_desc_t *frame;
if (!_uvc_frame_format_matches_guid(cf, format->guidFormat))
continue;
DL_FOREACH(format->frame_descs, frame) {
if (frame->wWidth != width || frame->wHeight != height)
continue;
uint32_t *interval;
ctrl->bInterfaceNumber = stream_if->bInterfaceNumber;
UVC_DEBUG("claiming streaming interface %d", stream_if->bInterfaceNumber );
uvc_claim_if(devh, ctrl->bInterfaceNumber);
/* get the max values */
uvc_query_stream_ctrl( devh, ctrl, 1, UVC_GET_MAX);
if (frame->intervals) {
for (interval = frame->intervals; *interval; ++interval) {
// allow a fps rate of zero to mean "accept first rate available"
if (10000000 / *interval == (unsigned int) fps || fps == 0) {
ctrl->bmHint = (1 << 0); /* don't negotiate interval */
ctrl->bFormatIndex = format->bFormatIndex;
ctrl->bFrameIndex = frame->bFrameIndex;
ctrl->dwFrameInterval = *interval;
goto found;
}
}
} else {
uint32_t interval_100ns = 10000000 / fps;
uint32_t interval_offset = interval_100ns - frame->dwMinFrameInterval;
if (interval_100ns >= frame->dwMinFrameInterval
&& interval_100ns <= frame->dwMaxFrameInterval
&& !(interval_offset
&& (interval_offset % frame->dwFrameIntervalStep))) {
ctrl->bmHint = (1 << 0);
ctrl->bFormatIndex = format->bFormatIndex;
ctrl->bFrameIndex = frame->bFrameIndex;
ctrl->dwFrameInterval = interval_100ns;
goto found;
}
}
}
}
}
return UVC_ERROR_INVALID_MODE;
found:
return uvc_probe_stream_ctrl(devh, ctrl);
}
/** Get a negotiated still control block for some common parameters.
* @ingroup streaming
*
* @param[in] devh Device handle
* @param[in] ctrl Control block
* @param[in, out] still_ctrl Still capture control block
* @param[in] width Desired frame width
* @param[in] height Desired frame height
*/
uvc_error_t uvc_get_still_ctrl_format_size(
uvc_device_handle_t *devh,
uvc_stream_ctrl_t *ctrl,
uvc_still_ctrl_t *still_ctrl,
int width, int height) {
uvc_streaming_interface_t *stream_if;
uvc_still_frame_desc_t *still;
uvc_format_desc_t *format;
uvc_still_frame_res_t *sizePattern;
stream_if = _uvc_get_stream_if(devh, ctrl->bInterfaceNumber);
/* Only method 2 is supported */
if(!stream_if || stream_if->bStillCaptureMethod != 2)
return UVC_ERROR_NOT_SUPPORTED;
DL_FOREACH(stream_if->format_descs, format) {
if (ctrl->bFormatIndex != format->bFormatIndex)
continue;
/* get the max values */
uvc_query_still_ctrl(devh, still_ctrl, 1, UVC_GET_MAX);
//look for still format
DL_FOREACH(format->still_frame_desc, still) {
DL_FOREACH(still->imageSizePatterns, sizePattern) {
if (sizePattern->wWidth != width || sizePattern->wHeight != height)
continue;
still_ctrl->bInterfaceNumber = ctrl->bInterfaceNumber;
still_ctrl->bFormatIndex = format->bFormatIndex;
still_ctrl->bFrameIndex = sizePattern->bResolutionIndex;
still_ctrl->bCompressionIndex = 0; //TODO support compression index
goto found;
}
}
}
return UVC_ERROR_INVALID_MODE;
found:
return uvc_probe_still_ctrl(devh, still_ctrl);
}
/** @internal
* Negotiate streaming parameters with the device
*
* @param[in] devh UVC device
* @param[in,out] ctrl Control block
*/
uvc_error_t uvc_probe_stream_ctrl(
uvc_device_handle_t *devh,
uvc_stream_ctrl_t *ctrl) {
uvc_query_stream_ctrl(
devh, ctrl, 1, UVC_SET_CUR
);
uvc_query_stream_ctrl(
devh, ctrl, 1, UVC_GET_CUR
);
/** @todo make sure that worked */
return UVC_SUCCESS;
}
/** @internal
* Negotiate still parameters with the device
*
* @param[in] devh UVC device
* @param[in,out] still_ctrl Still capture control block
*/
uvc_error_t uvc_probe_still_ctrl(
uvc_device_handle_t *devh,
uvc_still_ctrl_t *still_ctrl) {
int res = uvc_query_still_ctrl(
devh, still_ctrl, 1, UVC_SET_CUR
);
if(res == UVC_SUCCESS) {
res = uvc_query_still_ctrl(
devh, still_ctrl, 1, UVC_GET_CUR
);
if(res == UVC_SUCCESS) {
res = uvc_query_still_ctrl(
devh, still_ctrl, 0, UVC_SET_CUR
);
}
}
return static_cast<uvc_error_t>(res);
}
/** @internal
* @brief Swap the working buffer with the presented buffer and notify consumers
*/
void _uvc_swap_buffers(uvc_stream_handle_t *strmh) {
{
std::lock_guard<std::mutex> lock(strmh->callback_mutex);
strmh->capture_time_finished = std::chrono::steady_clock::now();
// std::swap does not perform memcpy's; it just swaps the underlying
// pointers
/* swap the buffers */
std::swap(strmh->outbuf, strmh->holdbuf);
strmh->hold_last_scr = strmh->last_scr;
strmh->hold_pts = strmh->pts;
strmh->hold_seq = strmh->seq;
/* swap metadata buffer */
std::swap(strmh->meta_outbuf, strmh->meta_holdbuf);
}
strmh->callback_cond.notify_all();
// Clear the buffers used to accumulate the next frame. We want the size
// to be 0 but the capacity to remain the same, however the C++ standard
// doesn't guarantee the capacity won't change. Do a reserve() to
// ensure the buffer is the size we need. Hopefully it's just a noop on
// your compiler.
strmh->outbuf.clear();
strmh->outbuf.reserve(uvc_stream_config.size_of_transport_buffer);
strmh->meta_outbuf.clear();
strmh->meta_outbuf.reserve(uvc_stream_config.size_of_meta_transport_buffer);
strmh->seq++;
strmh->last_scr = 0;
strmh->pts = 0;
}
/** @internal
* @brief Process a payload transfer
*
* Processes stream, places frames into buffer, signals listeners
* (such as user callback thread and any polling thread) on new frame
*
* @param payload Contents of the payload transfer, either a packet (isochronous) or a full
* transfer (bulk mode)
* @param payload_len Length of the payload transfer
*/
void _uvc_process_payload(uvc_stream_handle_t *strmh, uint8_t *payload, size_t payload_len) {
size_t header_len;
uint8_t header_info;
size_t data_len;
/* magic numbers for identifying header packets from some iSight cameras */
static uint8_t isight_tag[] = {
0x11, 0x22, 0x33, 0x44,
0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xfa, 0xce
};
/* ignore empty payload transfers */
if (payload_len == 0)
return;
/* Certain iSight cameras have strange behavior: They send header
* information in a packet with no image data, and then the following
* packets have only image data, with no more headers until the next frame.
*
* The iSight header: len(1), flags(1 or 2), 0x11223344(4),
* 0xdeadbeefdeadface(8), ??(16)
*/
if (strmh->devh->is_isight &&
(payload_len < 14 || memcmp(isight_tag, payload + 2, sizeof(isight_tag))) &&
(payload_len < 15 || memcmp(isight_tag, payload + 3, sizeof(isight_tag)))) {
/* The payload transfer doesn't have any iSight magic, so it's all image data */
header_len = 0;
data_len = payload_len;
} else {
header_len = payload[0];
if (header_len > payload_len) {
UVC_DEBUG("bogus packet: actual_len=%zd, header_len=%zd\n", payload_len, header_len);
return;
}
if (strmh->devh->is_isight)
data_len = 0;
else
data_len = payload_len - header_len;
}
if (header_len < 2) {
header_info = 0;
} else {
/** @todo we should be checking the end-of-header bit */
size_t variable_offset = 2;
header_info = payload[1];
if (header_info & 0x40) {
UVC_DEBUG("bad packet: error bit set");
return;
}
if (strmh->fid != (header_info & 1) && !strmh->outbuf.empty()) {
/* The frame ID bit was flipped, but we have image data sitting
around from prior transfers. This means the camera didn't send
an EOF for the last transfer of the previous frame. */
_uvc_swap_buffers(strmh);
}
strmh->fid = header_info & 1;
if (header_info & (1 << 2)) {
strmh->pts = DW_TO_INT(payload + variable_offset);
variable_offset += 4;
}
if (header_info & (1 << 3)) {
/** @todo read the SOF token counter */
strmh->last_scr = DW_TO_INT(payload + variable_offset);
variable_offset += 6;
}
if (header_len > variable_offset)
{
// Metadata is attached to header
size_t sz = header_len - variable_offset;
uint8_t *src = payload + variable_offset;
std::copy(src, src+sz, std::back_inserter(strmh->meta_outbuf));
}
}
if (data_len > 0) {
uint8_t *src = payload + header_len;
std::copy(src, src+data_len, std::back_inserter(strmh->outbuf));
if (header_info & (1 << 1)) {
/* The EOF bit is set, so publish the complete frame */
_uvc_swap_buffers(strmh);
}
}
}
/** @internal
* @brief Stream transfer callback
*
* Processes stream, places frames into buffer, signals listeners
* (such as user callback thread and any polling thread) on new frame
*
* @param transfer Active transfer
*/
void LIBUSB_CALL _uvc_stream_callback(struct libusb_transfer *transfer) {
uvc_stream_handle_t *strmh = (uvc_stream_handle_t *)transfer->user_data;
int resubmit = 1;
switch (transfer->status) {
case LIBUSB_TRANSFER_COMPLETED:
if (transfer->num_iso_packets == 0) {
/* This is a bulk mode transfer, so it just has one payload transfer */
_uvc_process_payload(strmh, transfer->buffer, transfer->actual_length);
} else {
/* This is an isochronous mode transfer, so each packet has a payload transfer */
int packet_id;
for (packet_id = 0; packet_id < transfer->num_iso_packets; ++packet_id) {
uint8_t *pktbuf;
struct libusb_iso_packet_descriptor *pkt;
pkt = transfer->iso_packet_desc + packet_id;
if (pkt->status != 0) {
UVC_DEBUG("bad packet (isochronous transfer); status: %d", pkt->status);
continue;
}
pktbuf = libusb_get_iso_packet_buffer_simple(transfer, packet_id);
_uvc_process_payload(strmh, pktbuf, pkt->actual_length);
}
}
break;
case LIBUSB_TRANSFER_CANCELLED:
case LIBUSB_TRANSFER_ERROR:
case LIBUSB_TRANSFER_NO_DEVICE:
UVC_DEBUG("not retrying transfer, status = %d", transfer->status);
{
std::lock_guard<std::mutex> lock(strmh->callback_mutex);
auto it = std::find_if(
std::begin(strmh->transfers),
std::end(strmh->transfers),
[&](const std::unique_ptr<struct libusb_transfer, struct libusb_transfer_deleter>& t)
{
return t.get() == transfer;
});
if (it != std::end(strmh->transfers))
{
// Delete managed object
UVC_DEBUG("Freeing transfer (%p)", transfer);
it->reset();
}
else
{
UVC_DEBUG("transfer %p not found; not freeing!", transfer);
}
resubmit = 0;
}
strmh->callback_cond.notify_all();
break;
case LIBUSB_TRANSFER_TIMED_OUT:
case LIBUSB_TRANSFER_STALL:
case LIBUSB_TRANSFER_OVERFLOW:
UVC_DEBUG("retrying transfer, status = %d", transfer->status);
break;
}
if ( resubmit ) {
if ( strmh->running ) {
int libusbRet = libusb_submit_transfer(transfer);
if (libusbRet < 0)
{
{
std::lock_guard<std::mutex> lock(strmh->callback_mutex);
/* Mark transfer as deleted. */
auto it = std::find_if(
std::begin(strmh->transfers),
std::end(strmh->transfers),
[&](const std::unique_ptr<struct libusb_transfer, struct libusb_transfer_deleter>& t)
{
return t.get() == transfer;
});
if (it != std::end(strmh->transfers))
{
UVC_DEBUG("Freeing failed transfer (%p)", transfer);
it->reset();
}
else
{
UVC_DEBUG("failed transfer %p not found; not freeing!", transfer);
}
}
strmh->callback_cond.notify_all();
}
} else {
{
std::lock_guard<std::mutex> lock(strmh->callback_mutex);
/* Mark transfer as deleted. */
auto it = std::find_if(
std::begin(strmh->transfers),
std::end(strmh->transfers),
[&](const std::unique_ptr<struct libusb_transfer, struct libusb_transfer_deleter>& t)
{
return t.get() == transfer;
});
if (it != std::end(strmh->transfers))
{
UVC_DEBUG("Freeing orphan transfer (%p)", transfer);
it->reset();
}
else
{
UVC_DEBUG("failed transfer %p not found; not freeing!", transfer);
}
}
strmh->callback_cond.notify_all();
}
}
}
/** Begin streaming video from the camera into the callback function.
* @ingroup streaming
*
* @param devh UVC device
* @param ctrl Control block, processed using {uvc_probe_stream_ctrl} or
* {uvc_get_stream_ctrl_format_size}
* @param cb User callback function. See {uvc_frame_callback_t} for restrictions.
* @param flags Stream setup flags, currently undefined. Set this to zero. The lower bit
* is reserved for backward compatibility.
*/
uvc_error_t uvc_start_streaming(
uvc_device_handle_t *devh,
uvc_stream_ctrl_t *ctrl,
uvc_frame_callback_t *cb,
void *user_ptr,
uint8_t flags
) {
uvc_error_t ret;
uvc_stream_handle_t *strmh;
ret = uvc_stream_open_ctrl(devh, &strmh, ctrl);
if (ret != UVC_SUCCESS)
return ret;
ret = uvc_stream_start(strmh, cb, user_ptr, flags);
if (ret != UVC_SUCCESS) {
uvc_stream_close(strmh);
return ret;
}
return UVC_SUCCESS;
}
/** Begin streaming video from the camera into the callback function.
* @ingroup streaming
*
* @deprecated The stream type (bulk vs. isochronous) will be determined by the
* type of interface associated with the uvc_stream_ctrl_t parameter, regardless
* of whether the caller requests isochronous streaming. Please switch to
* uvc_start_streaming().
*
* @param devh UVC device
* @param ctrl Control block, processed using {uvc_probe_stream_ctrl} or
* {uvc_get_stream_ctrl_format_size}
* @param cb User callback function. See {uvc_frame_callback_t} for restrictions.
*/
uvc_error_t uvc_start_iso_streaming(
uvc_device_handle_t *devh,
uvc_stream_ctrl_t *ctrl,
uvc_frame_callback_t *cb,
void *user_ptr
) {
return uvc_start_streaming(devh, ctrl, cb, user_ptr, 0);
}
static uvc_stream_handle_t *_uvc_get_stream_by_interface(uvc_device_handle_t *devh, int interface_idx) {
uvc_stream_handle_t *strmh;
DL_FOREACH(devh->streams, strmh) {
if (strmh->stream_if->bInterfaceNumber == interface_idx)
return strmh;
}
return NULL;
}
static uvc_streaming_interface_t *_uvc_get_stream_if(uvc_device_handle_t *devh, int interface_idx) {
uvc_streaming_interface_t *stream_if;
DL_FOREACH(devh->info->stream_ifs, stream_if) {
if (stream_if->bInterfaceNumber == interface_idx)
return stream_if;
}
return NULL;
}
struct uvc_stream_config_t uvc_stream_config = {
20, // number_of_transport_buffers
8 * 1024 * 1024, // size_of_transport_buffer
4 * 1024 // size_of_meta_transport_buffer
};
void uvc_stream_set_default_number_of_transport_buffers(size_t s) {
uvc_stream_config.number_of_transport_buffers = s;
}
void uvc_stream_set_default_size_of_transport_buffer(size_t s) {
uvc_stream_config.size_of_transport_buffer = s;
}
void uvc_stream_set_default_size_of_meta_transport_buffer(size_t s) {
uvc_stream_config.size_of_meta_transport_buffer = s;
}
/** Open a new video stream.
* @ingroup streaming
*
* @param devh UVC device
* @param ctrl Control block, processed using {uvc_probe_stream_ctrl} or
* {uvc_get_stream_ctrl_format_size}
*/
uvc_error_t uvc_stream_open_ctrl(uvc_device_handle_t *devh, uvc_stream_handle_t **strmhp, uvc_stream_ctrl_t *ctrl) {
/* Chosen frame and format descriptors */
uvc_stream_handle_t *strmh = NULL;
uvc_streaming_interface_t *stream_if;
uvc_error_t ret;
UVC_ENTER();
if (_uvc_get_stream_by_interface(devh, ctrl->bInterfaceNumber) != NULL) {
ret = UVC_ERROR_BUSY; /* Stream is already opened */
goto fail;
}
stream_if = _uvc_get_stream_if(devh, ctrl->bInterfaceNumber);
if (!stream_if) {
ret = UVC_ERROR_INVALID_PARAM;
goto fail;
}
strmh = new uvc_stream_handle_t();
if (!strmh) {
ret = UVC_ERROR_NO_MEM;
goto fail;
}
strmh->devh = devh;
strmh->stream_if = stream_if;
strmh->frame.library_owns_data = 1;
ret = uvc_claim_if(strmh->devh, strmh->stream_if->bInterfaceNumber);
if (ret != UVC_SUCCESS)
goto fail;
ret = uvc_stream_ctrl(strmh, ctrl);
if (ret != UVC_SUCCESS)
goto fail;
// Set up the streaming status and data space
strmh->running = 0;
DL_APPEND(devh->streams, strmh);
*strmhp = strmh;
UVC_EXIT(0);
return UVC_SUCCESS;
fail:
if (strmh)
delete strmh;
UVC_EXIT(ret);
return ret;
}
/** Begin streaming video from the stream into the callback function.
* @ingroup streaming
*
* @param strmh UVC stream
* @param cb User callback function. See {uvc_frame_callback_t} for restrictions.
* @param flags Stream setup flags, currently undefined. Set this to zero. The lower bit
* is reserved for backward compatibility.
*/
uvc_error_t uvc_stream_start(
uvc_stream_handle_t *strmh,
uvc_frame_callback_t *cb,
void *user_ptr,
uint8_t flags
) {
/* USB interface we'll be using */
const struct libusb_interface *interface;
int interface_id;
char isochronous;
uvc_frame_desc_t *frame_desc;
uvc_format_desc_t *format_desc;
uvc_stream_ctrl_t *ctrl;
int ret;
/* Total amount of data per transfer */
size_t total_transfer_size = 0;
ctrl = &strmh->cur_ctrl;
UVC_ENTER();
if (strmh->running) {
UVC_EXIT(UVC_ERROR_BUSY);
return UVC_ERROR_BUSY;
}
strmh->running = 1;
strmh->seq = 1;
strmh->fid = 0;
strmh->pts = 0;
strmh->last_scr = 0;
frame_desc = uvc_find_frame_desc_stream(strmh, ctrl->bFormatIndex, ctrl->bFrameIndex);
if (!frame_desc) {
ret = UVC_ERROR_INVALID_PARAM;
goto fail;
}
format_desc = frame_desc->parent;
strmh->frame_format = uvc_frame_format_for_guid(format_desc->guidFormat);
if (strmh->frame_format == UVC_FRAME_FORMAT_UNKNOWN) {
ret = UVC_ERROR_NOT_SUPPORTED;
goto fail;
}
// Get the interface that provides the chosen format and frame configuration
interface_id = strmh->stream_if->bInterfaceNumber;
interface = &strmh->devh->info->config->interface[interface_id];
/* A VS interface uses isochronous transfers iff it has multiple altsettings.
* (UVC 1.5: 2.4.3. VideoStreaming Interface) */
isochronous = interface->num_altsetting > 1;
if (isochronous) {
/* For isochronous streaming, we choose an appropriate altsetting for the endpoint
* and set up several transfers */
const struct libusb_interface_descriptor *altsetting = 0;
const struct libusb_endpoint_descriptor *endpoint = 0;
/* The greatest number of bytes that the device might provide, per packet, in this
* configuration */
size_t config_bytes_per_packet;
/* Number of packets per transfer */
size_t packets_per_transfer = 0;
/* Size of packet transferable from the chosen endpoint */
size_t endpoint_bytes_per_packet = 0;
/* Index of the altsetting */
int alt_idx, ep_idx;
config_bytes_per_packet = strmh->cur_ctrl.dwMaxPayloadTransferSize;
/* Go through the altsettings and find one whose packets are at least
* as big as our format's maximum per-packet usage. Assume that the
* packet sizes are increasing. */
for (alt_idx = 0; alt_idx < interface->num_altsetting; alt_idx++) {
altsetting = interface->altsetting + alt_idx;
endpoint_bytes_per_packet = 0;
/* Find the endpoint with the number specified in the VS header */
for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
endpoint = altsetting->endpoint + ep_idx;
struct libusb_ss_endpoint_companion_descriptor *ep_comp = 0;
libusb_get_ss_endpoint_companion_descriptor(NULL, endpoint, &ep_comp);
if (ep_comp)
{
endpoint_bytes_per_packet = ep_comp->wBytesPerInterval;
libusb_free_ss_endpoint_companion_descriptor(ep_comp);
break;
}
else
{
if (endpoint->bEndpointAddress == format_desc->parent->bEndpointAddress) {
endpoint_bytes_per_packet = endpoint->wMaxPacketSize;
// wMaxPacketSize: [unused:2 (multiplier-1):3 size:11]
endpoint_bytes_per_packet = (endpoint_bytes_per_packet & 0x07ff) *
(((endpoint_bytes_per_packet >> 11) & 3) + 1);
break;
}
}
}
if (endpoint_bytes_per_packet >= config_bytes_per_packet) {
/* Transfers will be at most one frame long: Divide the maximum frame size
* by the size of the endpoint and round up */
packets_per_transfer = (ctrl->dwMaxVideoFrameSize +
endpoint_bytes_per_packet - 1) / endpoint_bytes_per_packet;
/* But keep a reasonable limit: Otherwise we start dropping data */
if (packets_per_transfer > 32)
packets_per_transfer = 32;
total_transfer_size = packets_per_transfer * endpoint_bytes_per_packet;
break;
}
}
/* If we searched through all the altsettings and found nothing usable */
if (alt_idx == interface->num_altsetting) {
ret = UVC_ERROR_INVALID_MODE;
goto fail;
}
/* Select the altsetting */
ret = libusb_set_interface_alt_setting(strmh->devh->usb_devh,
altsetting->bInterfaceNumber,
altsetting->bAlternateSetting);
if (ret != UVC_SUCCESS) {
UVC_DEBUG("libusb_set_interface_alt_setting failed");
goto fail;
}
/* Set up the transfers */
for (auto &transfer : strmh->transfers)
{
transfer = std::unique_ptr<struct libusb_transfer, struct libusb_transfer_deleter>(
libusb_alloc_transfer(packets_per_transfer));
uint8_t *buf = (uint8_t *)malloc(total_transfer_size);
libusb_fill_iso_transfer(
transfer.get(), strmh->devh->usb_devh, format_desc->parent->bEndpointAddress, buf,
total_transfer_size, packets_per_transfer, _uvc_stream_callback, (void*) strmh, 5000);
libusb_set_iso_packet_lengths(transfer.get(), endpoint_bytes_per_packet);
}
} else {
for (auto &transfer : strmh->transfers)
{
transfer = std::unique_ptr<struct libusb_transfer, struct libusb_transfer_deleter>(
libusb_alloc_transfer(0));
uint8_t *buf = (uint8_t *)malloc(strmh->cur_ctrl.dwMaxPayloadTransferSize);
libusb_fill_bulk_transfer(
transfer.get(), strmh->devh->usb_devh,
format_desc->parent->bEndpointAddress, buf,
strmh->cur_ctrl.dwMaxPayloadTransferSize, _uvc_stream_callback,
( void* ) strmh, 5000 );
}
}
strmh->user_cb = cb;
strmh->user_ptr = user_ptr;
/* If the user wants it, set up a thread that calls the user's function
* with the contents of each frame.
*/
if (cb) {
strmh->callback_thread = std::thread(_uvc_user_caller, (void*) strmh);
}
{
auto it = std::begin(strmh->transfers);
for ( ; it != std::end(strmh->transfers); ++it) {
ret = libusb_submit_transfer(it->get());
if (ret != UVC_SUCCESS) {
UVC_DEBUG("libusb_submit_transfer failed: %d",ret);
break;
}
}
if ( ret != UVC_SUCCESS && it != std::begin(strmh->transfers) ) {
for ( ; it != std::end(strmh->transfers); ++it) {
it->reset();
}
ret = UVC_SUCCESS;
}
}
UVC_EXIT(ret);
return static_cast<uvc_error_t>(ret);
fail:
strmh->running = 0;
UVC_EXIT(ret);
return static_cast<uvc_error_t>(ret);
}
/** Begin streaming video from the stream into the callback function.
* @ingroup streaming
*
* @deprecated The stream type (bulk vs. isochronous) will be determined by the
* type of interface associated with the uvc_stream_ctrl_t parameter, regardless
* of whether the caller requests isochronous streaming. Please switch to
* uvc_stream_start().
*
* @param strmh UVC stream
* @param cb User callback function. See {uvc_frame_callback_t} for restrictions.
*/
uvc_error_t uvc_stream_start_iso(
uvc_stream_handle_t *strmh,
uvc_frame_callback_t *cb,
void *user_ptr
) {
return uvc_stream_start(strmh, cb, user_ptr, 0);
}
/** @internal
* @brief User callback runner thread
* @note There should be at most one of these per currently streaming device
* @param arg Device handle
*/
void *_uvc_user_caller(void *arg) {
uvc_stream_handle_t *strmh = (uvc_stream_handle_t *) arg;
uint32_t last_seq = 0;
do {
{
std::unique_lock<std::mutex> lock(strmh->callback_mutex);
strmh->callback_cond.wait(lock, [&]{return !strmh->running || last_seq != strmh->hold_seq;});
if (!strmh->running) {
break;
}
last_seq = strmh->hold_seq;
_uvc_populate_frame(strmh);
}
strmh->user_cb(&strmh->frame, strmh->user_ptr);
} while(1);
return NULL; // return value ignored
}
/** @internal
* @brief Populate the fields of a frame to be handed to user code
* must be called with stream cb lock held!
*/
void _uvc_populate_frame(uvc_stream_handle_t *strmh) {
uvc_frame_t *frame = &strmh->frame;
uvc_frame_desc_t *frame_desc;
/** @todo this stuff that hits the main config cache should really happen
* in start() so that only one thread hits these data. all of this stuff
* is going to be reopen_on_change anyway
*/
frame_desc = uvc_find_frame_desc(strmh->devh, strmh->cur_ctrl.bFormatIndex,
strmh->cur_ctrl.bFrameIndex);
frame->frame_format = strmh->frame_format;
frame->width = frame_desc->wWidth;
frame->height = frame_desc->wHeight;
switch (frame->frame_format) {
case UVC_FRAME_FORMAT_BGR:
frame->step = frame->width * 3;
break;
case UVC_FRAME_FORMAT_YUYV:
frame->step = frame->width * 2;
break;
case UVC_FRAME_FORMAT_NV12:
frame->step = frame->width;
break;
case UVC_FRAME_FORMAT_MJPEG:
frame->step = 0;
break;
case UVC_FRAME_FORMAT_H264:
frame->step = 0;
break;
default:
frame->step = 0;
break;
}
frame->sequence = strmh->hold_seq;
frame->capture_time_finished = strmh->capture_time_finished;
/* copy the image data from the hold buffer to the frame (unnecessary extra buf?) */
auto sz = strmh->holdbuf.size();
if (frame->data_bytes < sz) {
frame->data = realloc(frame->data, sz);
}
frame->data_bytes = sz;
memcpy(frame->data, strmh->holdbuf.data(), sz);
if (!strmh->meta_holdbuf.empty())
{
auto sz = strmh->meta_holdbuf.size();
if (frame->metadata_bytes < sz)
{
frame->metadata = realloc(frame->metadata, sz);
}
frame->metadata_bytes = sz;
memcpy(frame->metadata, strmh->meta_holdbuf.data(), sz);
}
}
/** Poll for a frame
* @ingroup streaming
*
* @param devh UVC device
* @param[out] frame Location to store pointer to captured frame (NULL on error)
* @param timeout_us >0: Wait at most N microseconds; 0: Wait indefinitely; -1: return immediately
*/
uvc_error_t uvc_stream_get_frame(uvc_stream_handle_t *strmh,
uvc_frame_t **frame,
int32_t timeout_us) {
if (!strmh->running)
return UVC_ERROR_INVALID_PARAM;
if (strmh->user_cb)
return UVC_ERROR_CALLBACK_EXISTS;
std::unique_lock<std::mutex> lock(strmh->callback_mutex);
if (strmh->last_polled_seq < strmh->hold_seq) {
_uvc_populate_frame(strmh);
*frame = &strmh->frame;
strmh->last_polled_seq = strmh->hold_seq;
} else if (timeout_us != -1) {
if (timeout_us == 0) {
strmh->callback_cond.wait(lock);
} else {
auto frame_ready = strmh->callback_cond.wait_for(
lock, std::chrono::microseconds(timeout_us),
[&]{return strmh->last_polled_seq < strmh->hold_seq;});
if (!frame_ready)
{
*frame = NULL;
return UVC_ERROR_TIMEOUT;
}
}
if (strmh->last_polled_seq < strmh->hold_seq) {
_uvc_populate_frame(strmh);
*frame = &strmh->frame;
strmh->last_polled_seq = strmh->hold_seq;
} else {
*frame = NULL;
}
} else {
*frame = NULL;
}
return UVC_SUCCESS;
}
/** @brief Stop streaming video
* @ingroup streaming
*
* Closes all streams, ends threads and cancels pollers
*
* @param devh UVC device
*/
void uvc_stop_streaming(uvc_device_handle_t *devh) {
uvc_stream_handle_t *strmh, *strmh_tmp;
DL_FOREACH_SAFE(devh->streams, strmh, strmh_tmp) {
uvc_stream_close(strmh);
}
}
/** @brief Stop stream.
* @ingroup streaming
*
* Stops stream, ends threads and cancels pollers
*
* @param devh UVC device
*/
uvc_error_t uvc_stream_stop(uvc_stream_handle_t *strmh) {
if (!strmh->running)
return UVC_ERROR_INVALID_PARAM;
strmh->running = 0;
{
std::unique_lock<std::mutex> lock(strmh->callback_mutex);
// Wait for all transfers to complete/cancel
// The transfer callback resets a unique_ptr to indicate it has been
// cancelled.
const auto timeout = std::chrono::seconds(5);
const auto start_time = std::chrono::steady_clock::now();
UVC_DEBUG("WAITING FOR ALL TRANSFERS TO COMPLETE/CANCEL===================================================");
do {
int i = 0;
auto it = std::begin(strmh->transfers);
for ( ; it != std::end(strmh->transfers); ++it) {
auto &transfer = *it;
if (transfer)
{
UVC_DEBUG("transfer[%d] (%p)", i++, transfer.get());
break;
}
else
{
UVC_DEBUG("transfer[%d] ALREADY FREED", i++);
}
}
if (it == std::end(strmh->transfers))
{
UVC_DEBUG("ALL TRANSFERS FREED");
break;
}
if (std::chrono::steady_clock::now() > start_time + timeout)
{
UVC_DEBUG("TIMED OUT WAITING TO FREE TRANSFERS AFTER %d SECONDS", timeout.count());
break;
}
strmh->callback_cond.wait_for(lock, std::chrono::seconds(1));
} while(1);
}
// Kick the user thread awake
strmh->callback_cond.notify_all();
/** @todo stop the actual stream, camera side? */
if (strmh->user_cb) {
/* wait for the thread to stop (triggered by
* LIBUSB_TRANSFER_CANCELLED transfer) */
UVC_DEBUG("callback_thread joining");
strmh->callback_thread.join();
UVC_DEBUG("callback_thread joined");
}
return UVC_SUCCESS;
}
/** @brief Close stream.
* @ingroup streaming
*
* Closes stream, frees handle and all streaming resources.
*
* @param strmh UVC stream handle
*/
void uvc_stream_close(uvc_stream_handle_t *strmh) {
if (strmh->running)
uvc_stream_stop(strmh);
uvc_release_if(strmh->devh, strmh->stream_if->bInterfaceNumber);
if (strmh->frame.data)
free(strmh->frame.data);
DL_DELETE(strmh->devh->streams, strmh);
delete strmh;
}
| 30.582178 | 116 | 0.666667 | [
"object"
] |
c40626912489eed53ef5be1a111e62004331e9e9 | 3,787 | cpp | C++ | src/analyzers/analyzer.cpp | saq7/MeTA | 0392964c1cdc073ae5123f7d64affdc4105acc4f | [
"MIT"
] | null | null | null | src/analyzers/analyzer.cpp | saq7/MeTA | 0392964c1cdc073ae5123f7d64affdc4105acc4f | [
"MIT"
] | null | null | null | src/analyzers/analyzer.cpp | saq7/MeTA | 0392964c1cdc073ae5123f7d64affdc4105acc4f | [
"MIT"
] | 1 | 2021-09-06T06:08:38.000Z | 2021-09-06T06:08:38.000Z | /**
* @file analyzer.cpp
*/
#include "analyzers/analyzer_factory.h"
#include "analyzers/filter_factory.h"
#include "analyzers/multi_analyzer.h"
#include "analyzers/token_stream.h"
#include "analyzers/filters/alpha_filter.h"
#include "analyzers/filters/empty_sentence_filter.h"
#include "analyzers/filters/length_filter.h"
#include "analyzers/filters/list_filter.h"
#include "analyzers/filters/lowercase_filter.h"
#include "analyzers/filters/porter2_stemmer.h"
#include "analyzers/tokenizers/icu_tokenizer.h"
#include "corpus/document.h"
#include "cpptoml.h"
#include "io/mmap_file.h"
#include "util/shim.h"
#include "utf/utf.h"
namespace meta
{
namespace analyzers
{
std::string analyzer::get_content(const corpus::document& doc)
{
if (doc.contains_content())
return utf::to_utf8(doc.content(), doc.encoding());
io::mmap_file file{doc.path()};
return utf::to_utf8({file.begin(), file.size()}, doc.encoding());
}
io::parser analyzer::create_parser(const corpus::document& doc,
const std::string& extension,
const std::string& delims)
{
if (doc.contains_content())
return io::parser{doc.content(), delims,
io::parser::input_type::String};
else
return io::parser{doc.path() + extension, delims,
io::parser::input_type::File};
}
std::unique_ptr<token_stream>
analyzer::default_filter_chain(const cpptoml::table& config)
{
auto stopwords = config.get_as<std::string>("stop-words");
std::unique_ptr<token_stream> result;
result = make_unique<tokenizers::icu_tokenizer>();
result = make_unique<filters::lowercase_filter>(std::move(result));
result = make_unique<filters::alpha_filter>(std::move(result));
result = make_unique<filters::length_filter>(std::move(result), 2, 35);
result = make_unique<filters::list_filter>(std::move(result), *stopwords);
result = make_unique<filters::porter2_stemmer>(std::move(result));
result = make_unique<filters::empty_sentence_filter>(std::move(result));
return result;
}
std::unique_ptr<token_stream>
analyzer::load_filter(std::unique_ptr<token_stream> src,
const cpptoml::table& config)
{
auto type = config.get_as<std::string>("type");
if (!type)
throw analyzer_exception{"filter type missing in config file"};
return filter_factory::get().create(*type, std::move(src), config);
}
std::unique_ptr<token_stream>
analyzer::load_filters(const cpptoml::table& global,
const cpptoml::table& config)
{
auto check = config.get_as<std::string>("filter");
if (check)
{
if (*check == "default-chain")
return default_filter_chain(global);
else
throw analyzer_exception{"unknown filter option: " + *check};
}
auto filters = config.get_table_array("filter");
if (!filters)
throw analyzer_exception{"analyzer group missing filter configuration"};
std::unique_ptr<token_stream> result;
for (const auto filter : filters->get())
result = load_filter(std::move(result), *filter);
return result;
}
std::unique_ptr<analyzer> analyzer::load(const cpptoml::table& config)
{
using namespace analyzers;
std::vector<std::unique_ptr<analyzer>> toks;
auto analyzers = config.get_table_array("analyzers");
for (auto group : analyzers->get())
{
auto method = group->get_as<std::string>("method");
if (!method)
throw analyzer_exception{"failed to find analyzer method"};
toks.emplace_back(
analyzer_factory::get().create(*method, config, *group));
}
return make_unique<multi_analyzer>(std::move(toks));
}
}
}
| 32.646552 | 80 | 0.664642 | [
"vector"
] |
c40687ea667eabb22b5e99d65eadfd2ce6672262 | 4,445 | hpp | C++ | include/codegen/include/System/Xml/XmlQualifiedName.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Xml/XmlQualifiedName.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Xml/XmlQualifiedName.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:20 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Xml
namespace System::Xml {
}
// Completed forward declares
// Type namespace: System.Xml
namespace System::Xml {
// Autogenerated type: System.Xml.XmlQualifiedName
class XmlQualifiedName : public ::Il2CppObject {
public:
// Nested type: System::Xml::XmlQualifiedName::HashCodeOfStringDelegate
class HashCodeOfStringDelegate;
// Get static field: static private System.Xml.XmlQualifiedName/HashCodeOfStringDelegate hashCodeDelegate
static System::Xml::XmlQualifiedName::HashCodeOfStringDelegate* _get_hashCodeDelegate();
// Set static field: static private System.Xml.XmlQualifiedName/HashCodeOfStringDelegate hashCodeDelegate
static void _set_hashCodeDelegate(System::Xml::XmlQualifiedName::HashCodeOfStringDelegate* value);
// private System.String name
// Offset: 0x10
::Il2CppString* name;
// private System.String ns
// Offset: 0x18
::Il2CppString* ns;
// private System.Int32 hash
// Offset: 0x20
int hash;
// Get static field: static public readonly System.Xml.XmlQualifiedName Empty
static System::Xml::XmlQualifiedName* _get_Empty();
// Set static field: static public readonly System.Xml.XmlQualifiedName Empty
static void _set_Empty(System::Xml::XmlQualifiedName* value);
// public System.Void .ctor(System.String name)
// Offset: 0x1192058
static XmlQualifiedName* New_ctor(::Il2CppString* name);
// public System.Void .ctor(System.String name, System.String ns)
// Offset: 0x1191FA8
static XmlQualifiedName* New_ctor(::Il2CppString* name, ::Il2CppString* ns);
// public System.String get_Namespace()
// Offset: 0x11920C0
::Il2CppString* get_Namespace();
// public System.String get_Name()
// Offset: 0x11920C8
::Il2CppString* get_Name();
// static private System.Xml.XmlQualifiedName/HashCodeOfStringDelegate GetHashCodeDelegate()
// Offset: 0x11921BC
static System::Xml::XmlQualifiedName::HashCodeOfStringDelegate* GetHashCodeDelegate();
// static private System.Boolean IsRandomizedHashingDisabled()
// Offset: 0x11929DC
static bool IsRandomizedHashingDisabled();
// static private System.Int32 GetHashCodeOfString(System.String s, System.Int32 length, System.Int64 additionalEntropy)
// Offset: 0x11929F8
static int GetHashCodeOfString(::Il2CppString* s, int length, int64_t additionalEntropy);
// System.Void Init(System.String name, System.String ns)
// Offset: 0x1189784
void Init(::Il2CppString* name, ::Il2CppString* ns);
// static private System.Void .cctor()
// Offset: 0x1192A14
static void _cctor();
// public System.Void .ctor()
// Offset: 0x11893BC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static XmlQualifiedName* New_ctor();
// public override System.Int32 GetHashCode()
// Offset: 0x11920D0
// Implemented from: System.Object
// Base method: System.Int32 Object::GetHashCode()
int GetHashCode();
// public override System.String ToString()
// Offset: 0x119277C
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::Il2CppString* ToString();
// public override System.Boolean Equals(System.Object other)
// Offset: 0x11927F4
// Implemented from: System.Object
// Base method: System.Boolean Object::Equals(System.Object other)
bool Equals(::Il2CppObject* other);
}; // System.Xml.XmlQualifiedName
// static public System.Boolean op_Equality(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b)
// Offset: 0x1192970
bool operator ==(System::Xml::XmlQualifiedName* a, System::Xml::XmlQualifiedName& b);
// static public System.Boolean op_Inequality(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b)
// Offset: 0x11928F0
bool operator !=(System::Xml::XmlQualifiedName* a, System::Xml::XmlQualifiedName& b);
}
DEFINE_IL2CPP_ARG_TYPE(System::Xml::XmlQualifiedName*, "System.Xml", "XmlQualifiedName");
#pragma pack(pop)
| 45.357143 | 124 | 0.71901 | [
"object"
] |
c41a6acd759e92c49909ec305b52deacc6aa1cdb | 714 | hpp | C++ | src/Map.hpp | dimi309/islet-hell | 6e41c2d2c22564a3289f36a7152e2bb28bb76c7c | [
"BSD-3-Clause"
] | null | null | null | src/Map.hpp | dimi309/islet-hell | 6e41c2d2c22564a3289f36a7152e2bb28bb76c7c | [
"BSD-3-Clause"
] | null | null | null | src/Map.hpp | dimi309/islet-hell | 6e41c2d2c22564a3289f36a7152e2bb28bb76c7c | [
"BSD-3-Clause"
] | null | null | null | /*
* Map.hpp
*
* Created on: 12 Oct 2019
* Author: Dimitri Kourkoulis
* License: BSD 3-Clause License (see LICENSE file)
*/
#pragma once
#include <vector>
#include <string>
#if defined(ANDROID) || defined(__ANDROID__)
#include <android_native_app_glue.h>
#endif
class Map {
private:
std::vector<std::string> mapData;
char *region;
const uint32_t maxRegionRadius = 10;
int xsize = 0, ysize = 0;
public:
#if defined(ANDROID) || defined(__ANDROID__)
Map(std::string , ANativeActivity *activity);
#else
Map(std::string);
#endif
~Map();
int getXsize();
int getYsize();
const char* getRegion(int coordx, int coordy, uint32_t radius);
char getLocation(int coordx, int coordy);
};
| 19.833333 | 65 | 0.686275 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.