hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ce550df7d8325229e116695e1236a8bc15e35833
10,928
cpp
C++
src/bytecode/BytecodeGenerator.cpp
tadeuzagallo/reach-lang
52cd57074afd27df38d68dbfcfe7e9e43a6ab464
[ "MIT" ]
null
null
null
src/bytecode/BytecodeGenerator.cpp
tadeuzagallo/reach-lang
52cd57074afd27df38d68dbfcfe7e9e43a6ab464
[ "MIT" ]
null
null
null
src/bytecode/BytecodeGenerator.cpp
tadeuzagallo/reach-lang
52cd57074afd27df38d68dbfcfe7e9e43a6ab464
[ "MIT" ]
null
null
null
#include "BytecodeGenerator.h" #include "Instructions.h" BytecodeGenerator::BytecodeGenerator(VM& vm, std::string name) : m_vm(vm) , m_block(vm, name) { emit<Enter>(); } BytecodeGenerator::~BytecodeGenerator() { m_block.destroy(m_vm); } BytecodeBlock* BytecodeGenerator::finalize(Register result) { emit<End>(result); m_block->adjustOffsets(); if (std::getenv("DUMP_BYTECODE")) m_block->dump(std::cout); return m_block.get(); } Register BytecodeGenerator::newLocal() { return Register::forLocal(++m_block->m_numLocals); } Label BytecodeGenerator::label() { return Label { }; } void BytecodeGenerator::branch(Register condition, const std::function<void()>& consequent, const std::function<void()>& alternate) { Label alt = label(); Label end = label(); jumpIfFalse(condition, alt); consequent(); jump(end); emit(alt); alternate(); emit(end); } void BytecodeGenerator::emitLocation(const SourceLocation& location) { m_block->addLocation(location); } void BytecodeGenerator::emitPrologue(const std::function<void()>& functor) { m_block->emitPrologue([&] { m_block->instructions().emitPrologue(functor); }); } void BytecodeGenerator::loadConstant(Register dst, Value value) { m_block->m_constants.push_back(value); emit<LoadConstant>(dst, m_block->m_constants.size() - 1); } void BytecodeGenerator::loadConstantIndex(Register dst, uint32_t index) { emit<LoadConstant>(dst, index); } uint32_t BytecodeGenerator::storeConstant(Register value) { uint32_t constantIndex = m_block->m_constants.size(); m_block->m_constants.push_back(Value::crash()); emit<StoreConstant>(constantIndex, value); return constantIndex; } void BytecodeGenerator::getLocal(Register dst, const Identifier& ident) { getLocal(dst, ident.name); } void BytecodeGenerator::getLocal(Register dst, const std::string& ident) { uint32_t index = uniqueIdentifier(ident); emit<GetLocal>(dst, index); } void BytecodeGenerator::getLocalOrConstant(Register dst, const std::string& ident, Value constant) { uint32_t identIndex = uniqueIdentifier(ident); uint32_t constantIndex = m_block->m_constants.size(); m_block->m_constants.push_back(constant); emit<GetLocalOrConstant>(dst, identIndex, constantIndex); } void BytecodeGenerator::setLocal(const Identifier& ident, Register src) { setLocal(ident.name, src); } void BytecodeGenerator::setLocal(const std::string& ident, Register src) { uint32_t index = uniqueIdentifier(ident); emit<SetLocal>(index, src); } void BytecodeGenerator::call(Register dst, Register callee, const std::vector<Register>& args) { unsigned argc = args.size(); emit<Call>(dst, callee, argc, argc ? args[0] : Register::forParameter(0)); } void BytecodeGenerator::newArray(Register dst, Register type, unsigned size) { emit<NewArray>(dst, type, size); } void BytecodeGenerator::setArrayIndex(Register src, unsigned offset, Register value) { emit<SetArrayIndex>(src, offset, value); } void BytecodeGenerator::getArrayIndex(Register dst, Register array, Register index) { emit<GetArrayIndex>(dst, array, index); } void BytecodeGenerator::getArrayLength(Register dst, Register array) { emit<GetArrayLength>(dst, array); } void BytecodeGenerator::newTuple(Register dst, Register type, unsigned size) { emit<NewTuple>(dst, type, size); } void BytecodeGenerator::setTupleIndex(Register src, unsigned offset, Register value) { emit<SetTupleIndex>(src, offset, value); } void BytecodeGenerator::getTupleIndex(Register dst, Register tuple, Register index) { emit<GetTupleIndex>(dst, tuple, index); } uint32_t BytecodeGenerator::newFunction(Register dst, BytecodeBlock* block) { uint32_t functionIndex = m_block->addFunctionBlock(block); emit<NewFunction>(dst, functionIndex); return functionIndex; } void BytecodeGenerator::newFunction(Register dst, uint32_t functionIndex) { emit<NewFunction>(dst, functionIndex); } void BytecodeGenerator::move(Register from, Register to) { if (from == to) return; emit<Move>(from, to); } void BytecodeGenerator::newObject(Register dst, Register type, uint32_t inlineSize) { emit<NewObject>(dst, type, inlineSize); } void BytecodeGenerator::setField(Register object, const std::string& field, Register value) { uint32_t fieldIndex = uniqueIdentifier(field); emit<SetField>(object, fieldIndex, value); } void BytecodeGenerator::getField(Register dst, Register object, const std::string& field) { uint32_t fieldIndex = uniqueIdentifier(field); emit<GetField>(dst, object, fieldIndex); } void BytecodeGenerator::tryGetField(Register dst, Register object, const std::string& field, Label& target) { m_block->recordJump<TryGetField>(target); uint32_t fieldIndex = uniqueIdentifier(field); emit<TryGetField>(dst, object, fieldIndex, 0); } void BytecodeGenerator::jump(Label& target) { m_block->recordJump<Jump>(target); emit<Jump>(0); } void BytecodeGenerator::jumpIfFalse(Register condition, Label& target) { m_block->recordJump<JumpIfFalse>(target); emit<JumpIfFalse>(condition, 0); } void BytecodeGenerator::isEqual(Register dst, Register lhs, Register rhs) { emit<IsEqual>(dst, lhs, rhs); } void BytecodeGenerator::runtimeError(const SourceLocation& location, const char* message) { emitLocation(location); uint32_t messageIndex = uniqueIdentifier(message); emit<RuntimeError>(messageIndex); } void BytecodeGenerator::isCell(Register dst, Register value, Cell::Kind kind) { emit<IsCell>(dst, value, kind); } // Type checking void BytecodeGenerator::pushScope() { emit<PushScope>(); } void BytecodeGenerator::popScope() { emit<PopScope>(); } void BytecodeGenerator::pushUnificationScope() { emit<PushUnificationScope>(); } void BytecodeGenerator::popUnificationScope() { emit<PopUnificationScope>(); } void BytecodeGenerator::unify(Register lhs, Register rhs) { emit<Unify>(lhs, rhs); } void BytecodeGenerator::match(Register lhs, Register rhs) { emit<Match>(lhs, rhs); } void BytecodeGenerator::resolveType(Register dst, Register type) { emit<ResolveType>(dst, type); } void BytecodeGenerator::checkType(Register dst, Register type, Type::Class expected) { emit<CheckType>(dst, type, expected); } void BytecodeGenerator::checkTypeOf(Register dst, Register type, Type::Class expected) { emit<CheckTypeOf>(dst, type, expected); } void BytecodeGenerator::typeError(const SourceLocation& location, const char* message) { emitLocation(location); uint32_t messageIndex = uniqueIdentifier(message); emit<TypeError>(messageIndex); } void BytecodeGenerator::inferImplicitParameters(Register function, const std::vector<Register>& parameters) { ASSERT(parameters.size(), "OOPS"); emit<InferImplicitParameters>(function, parameters.size(), parameters[0]); } void BytecodeGenerator::endTypeChecking(Register type) { emit<End>(type); m_block->m_codeStart = m_block->instructions().size(); emit<Enter>(); } // Types void BytecodeGenerator::newVarType(Register result, const std::string& name, bool inferred, bool rigid, Register bounds) { uint32_t nameIndex = uniqueIdentifier(name); emit<NewVarType>(result, nameIndex, inferred, rigid, bounds); } void BytecodeGenerator::newNameType(Register result, const std::string& name) { uint32_t nameIndex = uniqueIdentifier(name); emit<NewNameType>(result, nameIndex); } void BytecodeGenerator::newArrayType(Register result, Register itemType) { emit<NewArrayType>(result, itemType); } void BytecodeGenerator::newTupleType(Register result, uint32_t itemCount) { emit<NewTupleType>(result, itemCount); } void BytecodeGenerator::newRecordType(Register result, const std::vector<std::pair<std::string, Register>>& fields) { // TODO: this is bad and I should feel bad uint32_t fieldCount = fields.size(); Register firstKey = Register::forParameter(0); Register firstType = Register::forParameter(0); std::vector<Register> keys; for (const auto& field : fields) { keys.emplace_back(newLocal()); uint32_t keyIndex = uniqueIdentifier(field.first); loadConstant(keys.back(), keyIndex); } if (fieldCount) { firstKey = keys[0]; firstType = fields[0].second; } emit<NewRecordType>(result, fieldCount, firstKey, firstType); } void BytecodeGenerator::newFunctionType(Register result, const std::vector<Register>& params, Register returnType, uint32_t inferredParameters) { uint32_t paramCount = params.size(); Register firstParam = paramCount ? params[0] : Register::forParameter(0); emit<NewFunctionType>(result, paramCount, firstParam, returnType, inferredParameters); } void BytecodeGenerator::newUnionType(Register dst, Register lhs, Register rhs) { emit<NewUnionType>(dst, lhs, rhs); } void BytecodeGenerator::newBindingType(Register dst, const std::string& name, Register type) { uint32_t nameIndex = uniqueIdentifier(name); emit<NewBindingType>(dst, nameIndex, type); } void BytecodeGenerator::newCallHole(Register dst, Register callee, const std::vector<Register>& arguments) { unsigned argumentCount = arguments.size(); emit<NewCallHole>(dst, callee, argumentCount, argumentCount ? arguments[0] : Register::forParameter(0)); } void BytecodeGenerator::newSubscriptHole(Register dst, Register target, Register index) { emit<NewSubscriptHole>(dst, target, index); } void BytecodeGenerator::newMemberHole(Register dst, Register object, const std::string& field) { uint32_t fieldIndex = uniqueIdentifier(field); emit<NewMemberHole>(dst, object, fieldIndex); } void BytecodeGenerator::newValue(Register dst, Register type) { emit<NewValue>(dst, type); } void BytecodeGenerator::getTypeForValue(Register dst, Register value) { emit<GetTypeForValue>(dst, value); } // Primitives void BytecodeGenerator::emit(Instruction::ID instructionID) { emit(static_cast<uint32_t>(instructionID)); } void BytecodeGenerator::emit(Register reg) { emit(static_cast<uint32_t>(reg.offset())); } void BytecodeGenerator::emit(Label& label) { label.link(m_block->m_prologueSize, m_block->instructions().end()); } void BytecodeGenerator::emit(uint32_t word) { m_block->instructions().emit(word); } template<typename T> std::enable_if_t<std::is_enum<T>::value, void> BytecodeGenerator::emit(T t) { emit(static_cast<std::underlying_type_t<T>>(t)); } uint32_t BytecodeGenerator::uniqueIdentifier(const std::string& ident) { auto it = m_uniqueIdentifierMapping.find(ident); if (it != m_uniqueIdentifierMapping.end()) return it->second; m_block->m_identifiers.push_back(ident); uint32_t index = m_block->m_identifiers.size() - 1; m_uniqueIdentifierMapping[ident] = index; return index; }
26.460048
143
0.730783
tadeuzagallo
ce556b6a0cdeb5488ea5ae0246a6fbe2c63443d9
2,246
hh
C++
include/ftk/geometry/points2vtk.hh
robertu94/ftk
96c53ec21b795bb596908910b0b6d379f3dca157
[ "MIT" ]
null
null
null
include/ftk/geometry/points2vtk.hh
robertu94/ftk
96c53ec21b795bb596908910b0b6d379f3dca157
[ "MIT" ]
null
null
null
include/ftk/geometry/points2vtk.hh
robertu94/ftk
96c53ec21b795bb596908910b0b6d379f3dca157
[ "MIT" ]
null
null
null
#ifndef _FTK_POINTS2VTK_HH #define _FTK_POINTS2VTK_HH #include <ftk/ftk_config.hh> #if FTK_HAVE_VTK #include <vtkSmartPointer.h> #include <vtkDoubleArray.h> #include <vtkPoints.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkCellArray.h> #include <vtkXMLPolyDataWriter.h> namespace ftk { template <typename Array> vtkSmartPointer<vtkPolyData> points2vtk(const Array &array) { vtkSmartPointer<vtkPolyData> polyData = vtkPolyData::New(); vtkSmartPointer<vtkPoints> points = vtkPoints::New(); vtkSmartPointer<vtkCellArray> vertices = vtkCellArray::New(); vtkIdType pid[1]; for (auto i = 0; i < array.size(); i ++) { double p[3] = {array[i][0], array[i][1], array[i][2]}; pid[0] = points->InsertNextPoint(p); vertices->InsertNextCell(1, pid); } polyData->SetPoints(points); polyData->SetVerts(vertices); return polyData; } template <typename T> vtkSmartPointer<vtkPolyData> points2vtk(const std::vector<T>& array, int skip = 3) { vtkSmartPointer<vtkPolyData> polyData = vtkPolyData::New(); vtkSmartPointer<vtkPoints> points = vtkPoints::New(); vtkSmartPointer<vtkCellArray> vertices = vtkCellArray::New(); vtkIdType pid[1]; for (auto i = 0; i < array.size() / skip; i ++) { T p[3] = {array[i*skip], array[i*skip+1], skip == 2 ? T(0) : array[i*skip+2]}; pid[0] = points->InsertNextPoint(p); vertices->InsertNextCell(1, pid); } polyData->SetPoints(points); polyData->SetVerts(vertices); return polyData; } template <typename T> vtkSmartPointer<vtkPolyData> points2vtk(const std::vector<T>& array, const std::vector<T>& scalar, int skip = 3) { auto polyData = points2vtk(array, skip); vtkSmartPointer<vtkDoubleArray> weights = vtkSmartPointer<vtkDoubleArray>::New(); weights->SetNumberOfValues(scalar.size()); for (auto i = 0; i < scalar.size(); i ++) weights->SetValue(i, scalar[i]); polyData->GetPointData()->SetScalars(weights); return polyData; } inline void write_vtp(const std::string& filename, vtkSmartPointer<vtkPolyData> polydata) { vtkSmartPointer<vtkXMLPolyDataWriter> writer = vtkXMLPolyDataWriter::New(); writer->SetFileName(filename.c_str()); writer->SetInputData(polydata); writer->Write(); } } #endif #endif
25.816092
89
0.70837
robertu94
ce55bce75d586bfd05c8017768c1781e5e79ef4e
2,883
hpp
C++
Protocols/HemiPrep.hpp
triplewz/MP-SPDZ
a858e5b440902ec25dbb97c555eef35e12fbf69c
[ "BSD-2-Clause" ]
null
null
null
Protocols/HemiPrep.hpp
triplewz/MP-SPDZ
a858e5b440902ec25dbb97c555eef35e12fbf69c
[ "BSD-2-Clause" ]
null
null
null
Protocols/HemiPrep.hpp
triplewz/MP-SPDZ
a858e5b440902ec25dbb97c555eef35e12fbf69c
[ "BSD-2-Clause" ]
null
null
null
/* * HemiPrep.hpp * */ #ifndef PROTOCOLS_HEMIPREP_HPP_ #define PROTOCOLS_HEMIPREP_HPP_ #include "HemiPrep.h" #include "FHEOffline/PairwiseMachine.h" #include "Tools/Bundle.h" template<class T> PairwiseMachine* HemiPrep<T>::pairwise_machine = 0; template<class T> Lock HemiPrep<T>::lock; template<class T> void HemiPrep<T>::teardown() { if (pairwise_machine) delete pairwise_machine; } template<class T> void HemiPrep<T>::basic_setup(Player& P) { assert(pairwise_machine == 0); pairwise_machine = new PairwiseMachine(P); auto& machine = *pairwise_machine; auto& setup = machine.setup<FD>(); setup.params.set_matrix_dim_from_options(); setup.params.set_sec(OnlineOptions::singleton.security_parameter); setup.secure_init(P, machine, T::clear::length(), 0); T::clear::template init<typename FD::T>(); } template<class T> const FHE_PK& HemiPrep<T>::get_pk() { assert(pairwise_machine); return pairwise_machine->pk; } template<class T> const typename T::clear::FD& HemiPrep<T>::get_FTD() { assert(pairwise_machine); return pairwise_machine->setup<FD>().FieldD; } template<class T> HemiPrep<T>::~HemiPrep() { for (auto& x : multipliers) delete x; } template<class T> vector<Multiplier<typename T::clear::FD>*>& HemiPrep<T>::get_multipliers() { assert(this->proc != 0); auto& P = this->proc->P; lock.lock(); if (pairwise_machine == 0 or pairwise_machine->enc_alphas.empty()) { PlainPlayer P(this->proc->P.N, "Hemi" + T::type_string()); if (pairwise_machine == 0) basic_setup(P); pairwise_machine->setup<FD>().covert_key_generation(P, *pairwise_machine, 1); pairwise_machine->enc_alphas.resize(1, pairwise_machine->pk); } lock.unlock(); if (multipliers.empty()) for (int i = 1; i < P.num_players(); i++) multipliers.push_back( new Multiplier<FD>(i, *pairwise_machine, P, timers)); return multipliers; } template<class T> void HemiPrep<T>::buffer_triples() { assert(this->proc != 0); auto& P = this->proc->P; auto& multipliers = get_multipliers(); auto& FieldD = pairwise_machine->setup<FD>().FieldD; Plaintext_<FD> a(FieldD), b(FieldD), c(FieldD); a.randomize(G); b.randomize(G); c.mul(a, b); Bundle<octetStream> bundle(P); pairwise_machine->pk.encrypt(a).pack(bundle.mine); P.unchecked_broadcast(bundle); Ciphertext C(pairwise_machine->pk); for (auto m : multipliers) { C.unpack(bundle[P.get_player(-m->get_offset())]); m->multiply_and_add(c, C, b); } assert(b.num_slots() == a.num_slots()); assert(c.num_slots() == a.num_slots()); for (unsigned i = 0; i < a.num_slots(); i++) this->triples.push_back( {{ a.element(i), b.element(i), c.element(i) }}); } #endif
25.289474
74
0.642733
triplewz
ce5681ca952dd01f5ec6da2512b7ef9a5c1fb190
806
cpp
C++
src/targets/cpu/target.cpp
aaronenyeshi/AMDMIGraphX
87528938188f0247f3dfcc6ab9b83c22187109fd
[ "MIT" ]
null
null
null
src/targets/cpu/target.cpp
aaronenyeshi/AMDMIGraphX
87528938188f0247f3dfcc6ab9b83c22187109fd
[ "MIT" ]
null
null
null
src/targets/cpu/target.cpp
aaronenyeshi/AMDMIGraphX
87528938188f0247f3dfcc6ab9b83c22187109fd
[ "MIT" ]
null
null
null
#include <migraphx/cpu/target.hpp> #include <migraphx/cpu/lowering.hpp> #include <migraphx/pass.hpp> #include <migraphx/auto_contiguous.hpp> #include <migraphx/rewrite_rnn.hpp> #include <migraphx/dead_code_elimination.hpp> #include <migraphx/generate.hpp> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { namespace cpu { std::string target::name() const { return "cpu"; } std::vector<pass> target::get_passes(migraphx::context&) const { return {rewrite_rnn{}, dead_code_elimination{}, auto_contiguous{}, dead_code_elimination{}, lowering{}, dead_code_elimination{}}; } argument target::allocate(const shape& s) const { return fill_argument(s, 0); } } // namespace cpu } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx
26
79
0.703474
aaronenyeshi
ce56a49738ea79aaf5b6f285d5005c846e3f7724
1,285
cpp
C++
mix/arr_limit_test.cpp
bigov/daft-lib
7890fdba0aab800022ab9afb958946bd06779f33
[ "MIT" ]
1
2022-03-14T08:20:58.000Z
2022-03-14T08:20:58.000Z
mix/arr_limit_test.cpp
bigov/daft-lib
7890fdba0aab800022ab9afb958946bd06779f33
[ "MIT" ]
null
null
null
mix/arr_limit_test.cpp
bigov/daft-lib
7890fdba0aab800022ab9afb958946bd06779f33
[ "MIT" ]
1
2020-12-22T08:36:48.000Z
2020-12-22T08:36:48.000Z
#include <iostream> #include <memory> #include <limits> #include <valarray> using std::cout; using std::endl; size_t V_V = std::numeric_limits<int>::max(); // creating array size int step = 100000000; // step for search bool step_setup() { if(step > 1) { V_V += step; step = step / 10; return false; } else { return true; } } // Display only first error message void show_err(std::exception & e) { static std::string err{}; if(err != e.what()) { err = e.what(); cout << V_V << ": " << err << endl; } return; } int main() { cout << endl; bool found = false; while (!found) { try { std::unique_ptr<short[]> space{new short[V_V]}; //std::valarray<short> space(V_V); found = step_setup(); if (found) { cout << V_V << ": array created on " << &space[0] << endl; //cout << space.size() << ": valarray size " << endl; //V_V += 10000; //space.resize(V_V); //cout << space.size() << ": valarray resized " << endl; space[0] = 88; space[V_V] = 11; int m; std::cin >> m; cout << m << ", " << space[0] << ", " << space[V_V] << endl; } } catch(std::exception & e) { show_err(e); V_V -= step; } } return EXIT_SUCCESS; }
18.098592
69
0.521401
bigov
ce58350f1ba1ff47af8a4ddd26dbeb3f4d3a0b1a
8,047
cpp
C++
src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/ShareNode.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
4
2016-03-29T21:45:21.000Z
2016-12-20T00:50:38.000Z
src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/ShareNode.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
null
null
null
src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/ShareNode.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
3
2018-12-17T13:07:38.000Z
2021-09-08T13:07:31.000Z
// ShareNode.cpp #include "ShareAttrDir.h" #include "ShareNode.h" // constructor ShareDirEntry::ShareDirEntry(ShareDir* directory, const char* name, ShareNode* node) : Referencable(true), fDirectory(directory), fName(name), fNode(node), fRevision(-1) { } // destructor ShareDirEntry::~ShareDirEntry() { } // InitCheck status_t ShareDirEntry::InitCheck() const { if (fName.GetLength() == 0) return B_NO_MEMORY; return B_OK; } // GetDirectory ShareDir* ShareDirEntry::GetDirectory() const { return fDirectory; } // GetName const char* ShareDirEntry::GetName() const { return fName.GetString(); } // GetNode ShareNode* ShareDirEntry::GetNode() const { return fNode; } // SetRevision void ShareDirEntry::SetRevision(int64 revision) { fRevision = revision; } // GetRevision int64 ShareDirEntry::GetRevision() const { return fRevision; } // IsActualEntry bool ShareDirEntry::IsActualEntry() const { return (fName.GetLength() > 0 && fName != "." && fName != ".."); } // #pragma mark - // constructor ShareNode::ShareNode(Volume* volume, vnode_id id, const NodeInfo* nodeInfo) : Node(volume, id), fInfo(), fReferringEntries(), fAttrDir(NULL) { if (nodeInfo) { fInfo = *nodeInfo; } else { // init the stat data at least a bit, if no node info is given fInfo.st.st_dev = -1; fInfo.st.st_ino = -1; fInfo.st.st_mode = S_IFDIR | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; fInfo.st.st_nlink = 1; fInfo.st.st_size = 1; fInfo.st.st_blksize = 1024; fInfo.st.st_crtime = 0; fInfo.st.st_ctime = fInfo.st.st_mtime = fInfo.st.st_atime = fInfo.st.st_crtime; // negative revision, to make sure it is updated fInfo.revision = -1; } } // destructor ShareNode::~ShareNode() { delete fAttrDir; } // GetNodeInfo const NodeInfo& ShareNode::GetNodeInfo() const { return fInfo; } // GetRemoteID NodeID ShareNode::GetRemoteID() const { return fInfo.GetID(); } // Update void ShareNode::Update(const NodeInfo& nodeInfo) { if (fInfo.revision < nodeInfo.revision) fInfo = nodeInfo; } // AddReferringEntry void ShareNode::AddReferringEntry(ShareDirEntry* entry) { if (entry) fReferringEntries.Insert(entry); } // RemoveReferringEntry void ShareNode::RemoveReferringEntry(ShareDirEntry* entry) { if (entry) fReferringEntries.Remove(entry); } // GetFirstReferringEntry ShareDirEntry* ShareNode::GetFirstReferringEntry() const { return fReferringEntries.GetFirst(); } // GetNextReferringEntry ShareDirEntry* ShareNode::GetNextReferringEntry(ShareDirEntry* entry) const { return (entry ? fReferringEntries.GetNext(entry) : NULL); } // GetActualReferringEntry ShareDirEntry* ShareNode::GetActualReferringEntry() const { for (ShareDirEntry* entry = GetFirstReferringEntry(); entry; entry = GetNextReferringEntry(entry)) { if (entry->IsActualEntry()) return entry; } return NULL; } // SetAttrDir void ShareNode::SetAttrDir(ShareAttrDir* attrDir) { delete fAttrDir; fAttrDir = attrDir; } // GetAttrDir ShareAttrDir* ShareNode::GetAttrDir() const { return fAttrDir; } // #pragma mark - // constructor ShareDirIterator::ShareDirIterator() { } // destructor ShareDirIterator::~ShareDirIterator() { } // #pragma mark - // constructor LocalShareDirIterator::LocalShareDirIterator() : fDirectory(NULL), fCurrentEntry(NULL) { } // destructor LocalShareDirIterator::~LocalShareDirIterator() { SetDirectory(NULL); } // SetDirectory void LocalShareDirIterator::SetDirectory(ShareDir* directory) { // unset the old directory if (fDirectory) fDirectory->RemoveDirIterator(this); // set the new directory fDirectory = directory; if (fDirectory) { fDirectory->AddDirIterator(this); fCurrentEntry = fDirectory->GetFirstEntry(); } } // GetCurrentEntry ShareDirEntry* LocalShareDirIterator::GetCurrentEntry() const { return fCurrentEntry; } // NextEntry void LocalShareDirIterator::NextEntry() { if (!fDirectory || !fCurrentEntry) return; fCurrentEntry = fDirectory->GetNextEntry(fCurrentEntry); } // Rewind void LocalShareDirIterator::Rewind() { fCurrentEntry = (fDirectory ? fDirectory->GetFirstEntry() : NULL); } // IsDone bool LocalShareDirIterator::IsDone() const { return !fCurrentEntry; } // #pragma mark - // constructor RemoteShareDirIterator::RemoteShareDirIterator() : fCookie(-1), fCapacity(kRemoteShareDirIteratorCapacity), fCount(0), fIndex(0), fRevision(-1), fDone(false), fRewind(false) { } // destructor RemoteShareDirIterator::~RemoteShareDirIterator() { Clear(); } // GetCurrentEntry ShareDirEntry* RemoteShareDirIterator::GetCurrentEntry() const { return (!fRewind && fIndex < fCount ? fEntries[fIndex] : NULL); } // NextEntry void RemoteShareDirIterator::NextEntry() { if (fIndex < fCount) fIndex++; } // Rewind void RemoteShareDirIterator::Rewind() { fRewind = true; fDone = false; } // IsDone bool RemoteShareDirIterator::IsDone() const { return fDone; } // GetCapacity int32 RemoteShareDirIterator::GetCapacity() const { return fCapacity; } // SetCookie void RemoteShareDirIterator::SetCookie(int32 cookie) { fCookie = cookie; } // GetCookie int32 RemoteShareDirIterator::GetCookie() const { return fCookie; } // Clear void RemoteShareDirIterator::Clear() { for (int32 i = 0; i < fCount; i++) fEntries[i]->RemoveReference(); fCount = 0; fIndex = 0; fDone = false; fRewind = false; } // AddEntry bool RemoteShareDirIterator::AddEntry(ShareDirEntry* entry) { if (!entry || fCount >= fCapacity) return false; fEntries[fCount++] = entry; entry->AddReference(); return true; } // SetRevision void RemoteShareDirIterator::SetRevision(int64 revision) { fRevision = revision; } // GetRevision int64 RemoteShareDirIterator::GetRevision() const { return fRevision; } // SetDone void RemoteShareDirIterator::SetDone(bool done) { fDone = done; } // GetRewind bool RemoteShareDirIterator::GetRewind() const { return fRewind; } // #pragma mark - // constructor ShareDir::ShareDir(Volume* volume, vnode_id id, const NodeInfo* nodeInfo) : ShareNode(volume, id, nodeInfo), fEntries(), fIterators(), fEntryCreatedEventRevision(-1), fEntryRemovedEventRevision(-1), fIsComplete(false) { } // destructor ShareDir::~ShareDir() { } // UpdateEntryCreatedEventRevision void ShareDir::UpdateEntryCreatedEventRevision(int64 revision) { if (revision > fEntryCreatedEventRevision) fEntryCreatedEventRevision = revision; } // GetEntryCreatedEventRevision int64 ShareDir::GetEntryCreatedEventRevision() const { return fEntryCreatedEventRevision; } // UpdateEntryRemovedEventRevision void ShareDir::UpdateEntryRemovedEventRevision(int64 revision) { if (revision > fEntryRemovedEventRevision) fEntryRemovedEventRevision = revision; } // GetEntryRemovedEventRevision int64 ShareDir::GetEntryRemovedEventRevision() const { return fEntryRemovedEventRevision; } // SetComplete void ShareDir::SetComplete(bool complete) { fIsComplete = complete; } // IsComplete bool ShareDir::IsComplete() const { return fIsComplete; } // AddEntry void ShareDir::AddEntry(ShareDirEntry* entry) { if (entry) fEntries.Insert(entry); } // RemoveEntry void ShareDir::RemoveEntry(ShareDirEntry* entry) { if (entry) { // update the directory iterators pointing to the removed entry for (LocalShareDirIterator* iterator = fIterators.GetFirst(); iterator; iterator = fIterators.GetNext(iterator)) { if (iterator->GetCurrentEntry() == entry) iterator->NextEntry(); } fEntries.Remove(entry); } } // GetFirstEntry ShareDirEntry* ShareDir::GetFirstEntry() const { return fEntries.GetFirst(); } // GetNextEntry ShareDirEntry* ShareDir::GetNextEntry(ShareDirEntry* entry) const { if (!entry) return NULL; return fEntries.GetNext(entry); } // AddDirIterator void ShareDir::AddDirIterator(LocalShareDirIterator* iterator) { if (!iterator) return; fIterators.Insert(iterator); } // RemoveDirIterator void ShareDir::RemoveDirIterator(LocalShareDirIterator* iterator) { if (!iterator) return; fIterators.Remove(iterator); }
15.594961
75
0.732571
axeld
ce593946ac58360950f0ea0a6fd794c788f70a2f
1,840
cpp
C++
Tools/KLEE_Platform/stp/build/lib/AST/ASTKind.cpp
seclab-ucr/SCENT
f2fbfc5902b2dbd7dc72c8dc23ff28e24c31e50a
[ "MIT" ]
3
2019-10-24T00:49:51.000Z
2020-12-16T13:34:49.000Z
Tools/KLEE_Platform/stp/build/lib/AST/ASTKind.cpp
seclab-ucr/SCENT
f2fbfc5902b2dbd7dc72c8dc23ff28e24c31e50a
[ "MIT" ]
null
null
null
Tools/KLEE_Platform/stp/build/lib/AST/ASTKind.cpp
seclab-ucr/SCENT
f2fbfc5902b2dbd7dc72c8dc23ff28e24c31e50a
[ "MIT" ]
1
2020-11-14T03:08:53.000Z
2020-11-14T03:08:53.000Z
// Generated automatically by genkinds.h from ASTKind.kinds Fri Nov 9 10:04:23 2018. // Do not edit namespace stp { #if defined(__GNUC__) || defined(__clang__) __attribute__((visibility("default"))) #endif const char * _kind_names[] = { "UNDEFINED", "SYMBOL", "BVCONST", "BVNOT", "BVCONCAT", "BVOR", "BVAND", "BVXOR", "BVNAND", "BVNOR", "BVXNOR", "BVEXTRACT", "BVLEFTSHIFT", "BVRIGHTSHIFT", "BVSRSHIFT", "BVPLUS", "BVSUB", "BVUMINUS", "BVMULT", "BVDIV", "BVMOD", "SBVDIV", "SBVREM", "SBVMOD", "BVSX", "BVZX", "ITE", "BOOLEXTRACT", "BVLT", "BVLE", "BVGT", "BVGE", "BVSLT", "BVSLE", "BVSGT", "BVSGE", "EQ", "FALSE", "TRUE", "NOT", "AND", "OR", "NAND", "NOR", "XOR", "IFF", "IMPLIES", "PARAMBOOL", "READ", "WRITE", "ARRAY", "BITVECTOR", "BOOLEAN", }; #if defined(__GNUC__) || defined(__clang__) __attribute__((visibility("default"))) #endif unsigned char _kind_categories[] = { 0, //UNDEFINED 3, //SYMBOL 1, //BVCONST 1, //BVNOT 1, //BVCONCAT 1, //BVOR 1, //BVAND 1, //BVXOR 1, //BVNAND 1, //BVNOR 1, //BVXNOR 1, //BVEXTRACT 1, //BVLEFTSHIFT 1, //BVRIGHTSHIFT 1, //BVSRSHIFT 1, //BVPLUS 1, //BVSUB 1, //BVUMINUS 1, //BVMULT 1, //BVDIV 1, //BVMOD 1, //SBVDIV 1, //SBVREM 1, //SBVMOD 1, //BVSX 1, //BVZX 3, //ITE 2, //BOOLEXTRACT 2, //BVLT 2, //BVLE 2, //BVGT 2, //BVGE 2, //BVSLT 2, //BVSLE 2, //BVSGT 2, //BVSGE 2, //EQ 2, //FALSE 2, //TRUE 2, //NOT 2, //AND 2, //OR 2, //NAND 2, //NOR 2, //XOR 2, //IFF 2, //IMPLIES 2, //PARAMBOOL 1, //READ 1, //WRITE 0, //ARRAY 0, //BITVECTOR 0, //BOOLEAN }; } // end namespace
14.263566
85
0.504348
seclab-ucr
ce5b693f2096dfde1f4209ad67d48c3a85bd6977
3,151
hpp
C++
ql/processes/hullwhiteprocess.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
3,358
2015-12-18T02:56:17.000Z
2022-03-31T02:42:47.000Z
ql/processes/hullwhiteprocess.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
965
2015-12-21T10:35:28.000Z
2022-03-30T02:47:00.000Z
ql/processes/hullwhiteprocess.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
1,663
2015-12-17T17:45:38.000Z
2022-03-31T07:58:29.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 Banca Profilo S.p.A. This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file hullwhiteprocess.hpp \brief Hull-White stochastic processes */ #ifndef quantlib_hull_white_processes_hpp #define quantlib_hull_white_processes_hpp #include <ql/processes/forwardmeasureprocess.hpp> #include <ql/processes/ornsteinuhlenbeckprocess.hpp> #include <ql/termstructures/yieldtermstructure.hpp> namespace QuantLib { //! Hull-White stochastic process /*! \ingroup processes */ class HullWhiteProcess: public StochasticProcess1D { public: HullWhiteProcess(const Handle<YieldTermStructure>& h, Real a, Real sigma); //! \name StochasticProcess1D interface //@{ Real x0() const override; Real drift(Time t, Real x) const override; Real diffusion(Time t, Real x) const override; Real expectation(Time t0, Real x0, Time dt) const override; Real stdDeviation(Time t0, Real x0, Time dt) const override; Real variance(Time t0, Real x0, Time dt) const override; Real a() const; Real sigma() const; Real alpha(Time t) const; //@} protected: ext::shared_ptr<QuantLib::OrnsteinUhlenbeckProcess> process_; Handle<YieldTermStructure> h_; Real a_, sigma_; }; //! %Forward Hull-White stochastic process /*! \ingroup processes */ class HullWhiteForwardProcess: public ForwardMeasureProcess1D { public: HullWhiteForwardProcess(const Handle<YieldTermStructure>& h, Real a, Real sigma); //! \name StochasticProcess1D interface //@{ Real x0() const override; Real drift(Time t, Real x) const override; Real diffusion(Time t, Real x) const override; Real expectation(Time t0, Real x0, Time dt) const override; Real stdDeviation(Time t0, Real x0, Time dt) const override; Real variance(Time t0, Real x0, Time dt) const override; //@} Real a() const; Real sigma() const; Real alpha(Time t) const; Real M_T(Real s, Real t, Real T) const; Real B(Time t, Time T) const; protected: ext::shared_ptr<QuantLib::OrnsteinUhlenbeckProcess> process_; Handle<YieldTermStructure> h_; Real a_, sigma_; }; } #endif
34.25
79
0.6563
jiangjiali
ce5ce186170baabe1de5be202d12a8a868bf8b28
12,252
cc
C++
components/translate/core/browser/translate_browser_metrics_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/translate/core/browser/translate_browser_metrics_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/translate/core/browser/translate_browser_metrics_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 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/browser/translate_browser_metrics.h" #include <memory> #include "base/macros.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" using base::HistogramBase; using base::HistogramSamples; using base::StatisticsRecorder; namespace { class MetricsRecorder { public: explicit MetricsRecorder(const char* key) : key_(key) { StatisticsRecorder::Initialize(); HistogramBase* histogram = StatisticsRecorder::FindHistogram(key_); if (histogram) base_samples_ = histogram->SnapshotSamples(); } void CheckInitiationStatus( int expected_disabled_by_prefs, int expected_disabled_by_config, int expected_disabled_by_build, int expected_language_is_not_supported, int expected_mime_type_is_not_supported, int expected_url_is_not_supported, int expected_similar_languages, int expected_accept_languages, int expected_auto_by_config, int expected_auto_by_link, int expected_show_infobar, int expected_language_in_ulp, int expected_aborted_by_ranker, int expected_aborted_by_too_often_denied, int expected_aborted_by_matches_previous_language) { Snapshot(); EXPECT_EQ(expected_disabled_by_prefs, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_DISABLED_BY_PREFS)); EXPECT_EQ( expected_disabled_by_config, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_DISABLED_BY_CONFIG)); EXPECT_EQ( expected_disabled_by_build, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_DISABLED_BY_KEY)); EXPECT_EQ(expected_language_is_not_supported, GetCountWithoutSnapshot( translate::TranslateBrowserMetrics:: INITIATION_STATUS_LANGUAGE_IS_NOT_SUPPORTED)); EXPECT_EQ(expected_mime_type_is_not_supported, GetCountWithoutSnapshot( translate::TranslateBrowserMetrics:: INITIATION_STATUS_MIME_TYPE_IS_NOT_SUPPORTED)); EXPECT_EQ( expected_url_is_not_supported, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_URL_IS_NOT_SUPPORTED)); EXPECT_EQ(expected_similar_languages, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_SIMILAR_LANGUAGES)); EXPECT_EQ(expected_accept_languages, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_ACCEPT_LANGUAGES)); EXPECT_EQ(expected_auto_by_config, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_AUTO_BY_CONFIG)); EXPECT_EQ(expected_auto_by_link, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_AUTO_BY_LINK)); EXPECT_EQ(expected_show_infobar, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_SHOW_INFOBAR)); EXPECT_EQ(expected_language_in_ulp, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_LANGUAGE_IN_ULP)); EXPECT_EQ(expected_aborted_by_ranker, GetCountWithoutSnapshot(translate::TranslateBrowserMetrics:: INITIATION_STATUS_ABORTED_BY_RANKER)); EXPECT_EQ(expected_aborted_by_too_often_denied, GetCountWithoutSnapshot( translate::TranslateBrowserMetrics:: INITIATION_STATUS_ABORTED_BY_TOO_OFTEN_DENIED)); EXPECT_EQ(expected_aborted_by_matches_previous_language, GetCountWithoutSnapshot( translate::TranslateBrowserMetrics:: INITIATION_STATUS_ABORTED_BY_MATCHES_PREVIOUS_LANGUAGE)); } HistogramBase::Count GetTotalCount() { Snapshot(); if (!samples_.get()) return 0; HistogramBase::Count count = samples_->TotalCount(); if (!base_samples_.get()) return count; return count - base_samples_->TotalCount(); } HistogramBase::Count GetCount(HistogramBase::Sample value) { Snapshot(); return GetCountWithoutSnapshot(value); } private: void Snapshot() { HistogramBase* histogram = StatisticsRecorder::FindHistogram(key_); if (!histogram) return; samples_ = histogram->SnapshotSamples(); } HistogramBase::Count GetCountWithoutSnapshot(HistogramBase::Sample value) { if (!samples_.get()) return 0; HistogramBase::Count count = samples_->GetCount(value); if (!base_samples_.get()) return count; return count - base_samples_->GetCount(value); } std::string key_; std::unique_ptr<HistogramSamples> base_samples_; std::unique_ptr<HistogramSamples> samples_; DISALLOW_COPY_AND_ASSIGN(MetricsRecorder); }; } // namespace TEST(TranslateBrowserMetricsTest, ReportInitiationStatus) { MetricsRecorder recorder(translate::TranslateBrowserMetrics::GetMetricsName( translate::TranslateBrowserMetrics::UMA_INITIATION_STATUS)); recorder.CheckInitiationStatus(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_DISABLED_BY_PREFS); recorder.CheckInitiationStatus(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_DISABLED_BY_CONFIG); recorder.CheckInitiationStatus(1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_DISABLED_BY_KEY); recorder.CheckInitiationStatus(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics:: INITIATION_STATUS_LANGUAGE_IS_NOT_SUPPORTED); recorder.CheckInitiationStatus(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics:: INITIATION_STATUS_MIME_TYPE_IS_NOT_SUPPORTED); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics:: INITIATION_STATUS_URL_IS_NOT_SUPPORTED); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_SIMILAR_LANGUAGES); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_ACCEPT_LANGUAGES); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_AUTO_BY_CONFIG); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_AUTO_BY_LINK); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_SHOW_INFOBAR); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_LANGUAGE_IN_ULP); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics::INITIATION_STATUS_ABORTED_BY_RANKER); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics:: INITIATION_STATUS_ABORTED_BY_TOO_OFTEN_DENIED); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0); translate::TranslateBrowserMetrics::ReportInitiationStatus( translate::TranslateBrowserMetrics:: INITIATION_STATUS_ABORTED_BY_MATCHES_PREVIOUS_LANGUAGE); recorder.CheckInitiationStatus(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); } TEST(TranslateBrowserMetricsTest, ReportLanguageDetectionError) { MetricsRecorder recorder(translate::TranslateBrowserMetrics::GetMetricsName( translate::TranslateBrowserMetrics::UMA_LANGUAGE_DETECTION_ERROR)); EXPECT_EQ(0, recorder.GetTotalCount()); translate::TranslateBrowserMetrics::ReportLanguageDetectionError(); EXPECT_EQ(1, recorder.GetTotalCount()); } TEST(TranslateBrowserMetricsTest, ReportedLocalesOnDisabledByPrefs) { const int ENGLISH = 25966; MetricsRecorder recorder(translate::TranslateBrowserMetrics::GetMetricsName( translate::TranslateBrowserMetrics::UMA_LOCALES_ON_DISABLED_BY_PREFS)); EXPECT_EQ(0, recorder.GetTotalCount()); translate::TranslateBrowserMetrics::ReportLocalesOnDisabledByPrefs("en"); EXPECT_EQ(1, recorder.GetCount(ENGLISH)); } TEST(TranslateBrowserMetricsTest, ReportedUndisplayableLanguage) { const int ENGLISH = 25966; MetricsRecorder recorder(translate::TranslateBrowserMetrics::GetMetricsName( translate::TranslateBrowserMetrics::UMA_UNDISPLAYABLE_LANGUAGE)); EXPECT_EQ(0, recorder.GetTotalCount()); translate::TranslateBrowserMetrics::ReportUndisplayableLanguage("en"); EXPECT_EQ(1, recorder.GetCount(ENGLISH)); } TEST(TranslateBrowserMetricsTest, ReportedUnsupportedLanguageAtInitiation) { const int ENGLISH = 25966; MetricsRecorder recorder(translate::TranslateBrowserMetrics::GetMetricsName( translate::TranslateBrowserMetrics:: UMA_UNSUPPORTED_LANGUAGE_AT_INITIATION)); EXPECT_EQ(0, recorder.GetTotalCount()); translate::TranslateBrowserMetrics::ReportUnsupportedLanguageAtInitiation( "en"); EXPECT_EQ(1, recorder.GetCount(ENGLISH)); } TEST(TranslateBrowserMetricsTest, ReportedTranslateSourceLanguage) { const int ENGLISH = -74147910; const int FRENCH = 1704315002; MetricsRecorder recorder(translate::TranslateBrowserMetrics::GetMetricsName( translate::TranslateBrowserMetrics::UMA_TRANSLATE_SOURCE_LANGUAGE)); EXPECT_EQ(0, recorder.GetTotalCount()); translate::TranslateBrowserMetrics::ReportTranslateSourceLanguage("en"); translate::TranslateBrowserMetrics::ReportTranslateSourceLanguage("fr"); translate::TranslateBrowserMetrics::ReportTranslateSourceLanguage("en"); EXPECT_EQ(2, recorder.GetCount(ENGLISH)); EXPECT_EQ(1, recorder.GetCount(FRENCH)); } TEST(TranslateBrowserMetricsTest, ReportedTranslateTargetLanguage) { const int ENGLISH = -74147910; const int FRENCH = 1704315002; MetricsRecorder recorder(translate::TranslateBrowserMetrics::GetMetricsName( translate::TranslateBrowserMetrics::UMA_TRANSLATE_TARGET_LANGUAGE)); EXPECT_EQ(0, recorder.GetTotalCount()); translate::TranslateBrowserMetrics::ReportTranslateTargetLanguage("en"); translate::TranslateBrowserMetrics::ReportTranslateTargetLanguage("fr"); translate::TranslateBrowserMetrics::ReportTranslateTargetLanguage("en"); EXPECT_EQ(2, recorder.GetCount(ENGLISH)); EXPECT_EQ(1, recorder.GetCount(FRENCH)); }
44.715328
80
0.730656
metux
ce5dd73ace326ad6aa31868fe01948c593ff26b5
11,616
cpp
C++
llvm-2.9/lib/Transforms/Scalar/SimplifyCFGPass.cpp
DependableSystemsLab/Trident
90b38ab3ce8b7ad743986ddf66eaea7d20d921cb
[ "MIT" ]
5
2018-09-23T05:44:31.000Z
2021-09-08T18:52:37.000Z
llvm-2.9/lib/Transforms/Scalar/SimplifyCFGPass.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
4
2019-06-13T16:27:31.000Z
2021-06-07T07:24:31.000Z
llvm-2.9/lib/Transforms/Scalar/SimplifyCFGPass.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
4
2018-09-23T05:44:33.000Z
2021-04-20T00:29:11.000Z
//===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements dead code elimination and basic block merging, along // with a collection of other peephole control flow optimizations. For example: // // * Removes basic blocks with no predecessors. // * Merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor. // * Eliminates a basic block that only contains an unconditional branch. // * Changes invoke instructions to nounwind functions to be calls. // * Change things like "if (x) if (y)" into "if (x&y)". // * etc.. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "simplifycfg" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/IntrinsicInst.h" #include "llvm/Module.h" #include "llvm/Attributes.h" #include "llvm/Support/CFG.h" #include "llvm/Pass.h" #include "llvm/Target/TargetData.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" using namespace llvm; STATISTIC(NumSimpl, "Number of blocks simplified"); namespace { struct CFGSimplifyPass : public FunctionPass { static char ID; // Pass identification, replacement for typeid CFGSimplifyPass() : FunctionPass(ID) { initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry()); } virtual bool runOnFunction(Function &F); }; } char CFGSimplifyPass::ID = 0; INITIALIZE_PASS(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false, false) // Public interface to the CFGSimplification pass FunctionPass *llvm::createCFGSimplificationPass() { return new CFGSimplifyPass(); } /// ChangeToUnreachable - Insert an unreachable instruction before the specified /// instruction, making it and the rest of the code in the block dead. static void ChangeToUnreachable(Instruction *I, bool UseLLVMTrap) { BasicBlock *BB = I->getParent(); // Loop over all of the successors, removing BB's entry from any PHI // nodes. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) (*SI)->removePredecessor(BB); // Insert a call to llvm.trap right before this. This turns the undefined // behavior into a hard fail instead of falling through into random code. if (UseLLVMTrap) { Function *TrapFn = Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap); CallInst::Create(TrapFn, "", I); } new UnreachableInst(I->getContext(), I); // All instructions after this are dead. BasicBlock::iterator BBI = I, BBE = BB->end(); while (BBI != BBE) { if (!BBI->use_empty()) BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); BB->getInstList().erase(BBI++); } } /// ChangeToCall - Convert the specified invoke into a normal call. static void ChangeToCall(InvokeInst *II) { BasicBlock *BB = II->getParent(); SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3); CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args.begin(), Args.end(), "", II); NewCall->takeName(II); NewCall->setCallingConv(II->getCallingConv()); NewCall->setAttributes(II->getAttributes()); II->replaceAllUsesWith(NewCall); // Follow the call by a branch to the normal destination. BranchInst::Create(II->getNormalDest(), II); // Update PHI nodes in the unwind destination II->getUnwindDest()->removePredecessor(BB); BB->getInstList().erase(II); } static bool MarkAliveBlocks(BasicBlock *BB, SmallPtrSet<BasicBlock*, 128> &Reachable) { SmallVector<BasicBlock*, 128> Worklist; Worklist.push_back(BB); bool Changed = false; do { BB = Worklist.pop_back_val(); if (!Reachable.insert(BB)) continue; // Do a quick scan of the basic block, turning any obviously unreachable // instructions into LLVM unreachable insts. The instruction combining pass // canonicalizes unreachable insts into stores to null or undef. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){ if (CallInst *CI = dyn_cast<CallInst>(BBI)) { if (CI->doesNotReturn()) { // If we found a call to a no-return function, insert an unreachable // instruction after it. Make sure there isn't *already* one there // though. ++BBI; if (!isa<UnreachableInst>(BBI)) { // Don't insert a call to llvm.trap right before the unreachable. ChangeToUnreachable(BBI, false); Changed = true; } break; } } // Store to undef and store to null are undefined and used to signal that // they should be changed to unreachable by passes that can't modify the // CFG. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { // Don't touch volatile stores. if (SI->isVolatile()) continue; Value *Ptr = SI->getOperand(1); if (isa<UndefValue>(Ptr) || (isa<ConstantPointerNull>(Ptr) && SI->getPointerAddressSpace() == 0)) { ChangeToUnreachable(SI, true); Changed = true; break; } } } // Turn invokes that call 'nounwind' functions into ordinary calls. if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) if (II->doesNotThrow()) { ChangeToCall(II); Changed = true; } Changed |= ConstantFoldTerminator(BB); for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) Worklist.push_back(*SI); } while (!Worklist.empty()); return Changed; } /// RemoveUnreachableBlocksFromFn - Remove blocks that are not reachable, even /// if they are in a dead cycle. Return true if a change was made, false /// otherwise. static bool RemoveUnreachableBlocksFromFn(Function &F) { SmallPtrSet<BasicBlock*, 128> Reachable; bool Changed = MarkAliveBlocks(F.begin(), Reachable); // If there are unreachable blocks in the CFG... if (Reachable.size() == F.size()) return Changed; assert(Reachable.size() < F.size()); NumSimpl += F.size()-Reachable.size(); // Loop over all of the basic blocks that are not reachable, dropping all of // their internal references... for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) { if (Reachable.count(BB)) continue; for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) if (Reachable.count(*SI)) (*SI)->removePredecessor(BB); BB->dropAllReferences(); } for (Function::iterator I = ++F.begin(); I != F.end();) if (!Reachable.count(I)) I = F.getBasicBlockList().erase(I); else ++I; return true; } /// MergeEmptyReturnBlocks - If we have more than one empty (other than phi /// node) return blocks, merge them together to promote recursive block merging. static bool MergeEmptyReturnBlocks(Function &F) { bool Changed = false; BasicBlock *RetBlock = 0; // Scan all the blocks in the function, looking for empty return blocks. for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) { BasicBlock &BB = *BBI++; // Only look at return blocks. ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()); if (Ret == 0) continue; // Only look at the block if it is empty or the only other thing in it is a // single PHI node that is the operand to the return. if (Ret != &BB.front()) { // Check for something else in the block. BasicBlock::iterator I = Ret; --I; // Skip over debug info. while (isa<DbgInfoIntrinsic>(I) && I != BB.begin()) --I; if (!isa<DbgInfoIntrinsic>(I) && (!isa<PHINode>(I) || I != BB.begin() || Ret->getNumOperands() == 0 || Ret->getOperand(0) != I)) continue; } // If this is the first returning block, remember it and keep going. if (RetBlock == 0) { RetBlock = &BB; continue; } // Otherwise, we found a duplicate return block. Merge the two. Changed = true; // Case when there is no input to the return or when the returned values // agree is trivial. Note that they can't agree if there are phis in the // blocks. if (Ret->getNumOperands() == 0 || Ret->getOperand(0) == cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) { BB.replaceAllUsesWith(RetBlock); BB.eraseFromParent(); continue; } // If the canonical return block has no PHI node, create one now. PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin()); if (RetBlockPHI == 0) { Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0); RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(), "merge", &RetBlock->front()); for (pred_iterator PI = pred_begin(RetBlock), E = pred_end(RetBlock); PI != E; ++PI) RetBlockPHI->addIncoming(InVal, *PI); RetBlock->getTerminator()->setOperand(0, RetBlockPHI); } // Turn BB into a block that just unconditionally branches to the return // block. This handles the case when the two return blocks have a common // predecessor but that return different things. RetBlockPHI->addIncoming(Ret->getOperand(0), &BB); BB.getTerminator()->eraseFromParent(); BranchInst::Create(RetBlock, &BB); } return Changed; } /// IterativeSimplifyCFG - Call SimplifyCFG on all the blocks in the function, /// iterating until no more changes are made. static bool IterativeSimplifyCFG(Function &F, const TargetData *TD) { bool Changed = false; bool LocalChange = true; while (LocalChange) { LocalChange = false; // Loop over all of the basic blocks and remove them if they are unneeded... // for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) { if (SimplifyCFG(BBIt++, TD)) { LocalChange = true; ++NumSimpl; } } Changed |= LocalChange; } return Changed; } // It is possible that we may require multiple passes over the code to fully // simplify the CFG. // bool CFGSimplifyPass::runOnFunction(Function &F) { const TargetData *TD = getAnalysisIfAvailable<TargetData>(); bool EverChanged = RemoveUnreachableBlocksFromFn(F); EverChanged |= MergeEmptyReturnBlocks(F); EverChanged |= IterativeSimplifyCFG(F, TD); // If neither pass changed anything, we're done. if (!EverChanged) return false; // IterativeSimplifyCFG can (rarely) make some loops dead. If this happens, // RemoveUnreachableBlocksFromFn is needed to nuke them, which means we should // iterate between the two optimizations. We structure the code like this to // avoid reruning IterativeSimplifyCFG if the second pass of // RemoveUnreachableBlocksFromFn doesn't do anything. if (!RemoveUnreachableBlocksFromFn(F)) return true; do { EverChanged = IterativeSimplifyCFG(F, TD); EverChanged |= RemoveUnreachableBlocksFromFn(F); } while (EverChanged); return true; }
35.2
80
0.640926
DependableSystemsLab
ce5f73d71f890b815fb7712f61a244c617624336
7,450
cpp
C++
cam_QGuide.cpp
arran-dengate/phd2-automated-mount-fork
3f03fe385b53eb46a46766074ca727ea95e66910
[ "BSD-3-Clause" ]
null
null
null
cam_QGuide.cpp
arran-dengate/phd2-automated-mount-fork
3f03fe385b53eb46a46766074ca727ea95e66910
[ "BSD-3-Clause" ]
null
null
null
cam_QGuide.cpp
arran-dengate/phd2-automated-mount-fork
3f03fe385b53eb46a46766074ca727ea95e66910
[ "BSD-3-Clause" ]
null
null
null
/* * cam_QGuide.cpp * PHD Guiding * * Created by Craig Stark. * Copyright (c) 2007-2010 Craig Stark. * All rights reserved. * * This source code is distributed under the following "BSD" license * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of Craig Stark, Stark Labs 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 "phd.h" #if defined (QGUIDE) #include "camera.h" #include "time.h" #include "image_math.h" #include "<iostream>" #include <wx/stdpaths.h> #include <wx/textfile.h> //wxTextFile *qglogfile; int ushort_compare (const void * a, const void * b) { if ( *(unsigned short *)a > *(unsigned short *)b ) return 1; if ( *(unsigned short *)a < *(unsigned short *)b ) return -1; return 0; } #define QGDEBUG 0 #include "cam_QGuide.h" // QHY CMOS guide camera version // Tom's driver Camera_QGuiderClass::Camera_QGuiderClass() { Connected = false; Name = _T("Q-Guider"); FullSize = wxSize(1280,1024); m_hasGuideOutput = true; HasGainControl = true; } wxByte Camera_QGuiderClass::BitsPerPixel() { return 16; } bool Camera_QGuiderClass::Connect(const wxString& camId) { // returns true on error // CameraReset(); if (!openUSB(0)) { wxMessageBox(_T("No camera")); return true; } // ClearGuidePort(); // GuideCommand(0x0F,10); // buffer = new unsigned char[1311744]; SETBUFFERMODE(0); Connected = true; // qglogfile = new wxTextFile(Debug.GetLogDir() + PATHSEPSTR + _T("PHD_QGuide_log.txt")); //qglogfile->AddLine(wxNow() + ": QGuide connected"); //qglogfile->Write(); return false; } bool Camera_QGuiderClass::ST4PulseGuideScope(int direction, int duration) { int reg = 0; int dur = duration / 10; //qglogfile->AddLine(wxString::Format("Sending guide dur %d",dur)); //qglogfile->Write(); if (dur >= 255) dur = 254; // Max guide pulse is 2.54s -- 255 keeps it on always // Output pins are NC, Com, RA+(W), Dec+(N), Dec-(S), RA-(E) ?? http://www.starlight-xpress.co.uk/faq.htm switch (direction) { case WEST: reg = 0x80; break; // 0111 0000 case NORTH: reg = 0x40; break; // 1011 0000 case SOUTH: reg = 0x20; break; // 1101 0000 case EAST: reg = 0x10; break; // 1110 0000 default: return true; // bad direction passed in } GuideCommand(reg,dur); //if (duration > 50) wxMilliSleep(duration - 50); // wait until it's mostly done WorkerThread::MilliSleep(duration + 10); //qglogfile->AddLine("Done"); //qglogfile->Write(); return false; } void Camera_QGuiderClass::ClearGuidePort() { // SendGuideCommand(DevName,0,0); } void Camera_QGuiderClass::InitCapture() { // CameraReset(); ProgramCamera(0,0,1280,1024, (GuideCameraGain * 63 / 100) ); // SetNoiseReduction(0); } bool Camera_QGuiderClass::Disconnect() { closeUSB(); // delete [] buffer; Connected = false; //qglogfile->AddLine(wxNow() + ": Disconnecting"); //qglogfile->Write(); //qglogfile->Close(); return false; } static bool StopExposure() { Debug.AddLine("QGuide: stop exposure"); CancelExposure(); return true; } bool Camera_QGuiderClass::Capture(int duration, usImage& img, int options, const wxRect& subframe) { // Only does full frames still unsigned short *dptr; bool firstimg = true; //qglogfile->AddLine(wxString::Format("Capturing dur %d",duration)); //qglogfile->Write(); // ThreadedExposure(10, buffer); ProgramCamera(0,0,1280,1024, (GuideCameraGain * 63 / 100) ); /* ThreadedExposure(10, NULL); while (isExposing()) wxMilliSleep(10); */ if (img.Init(FullSize)) { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } // ThreadedExposure(duration, buffer); ThreadedExposure(duration, NULL); //qglogfile->AddLine("Exposure programmed"); //qglogfile->Write(); CameraWatchdog watchdog(duration, GetTimeoutMs() + 1000); // typically 6 second timeout if (duration > 100) { // Shift to > duration if (WorkerThread::MilliSleep(duration + 100) && (WorkerThread::TerminateRequested() || StopExposure())) { return true; } } while (isExposing()) { wxMilliSleep(200); if (WorkerThread::InterruptRequested() && (WorkerThread::TerminateRequested() || StopExposure())) { return true; } if (watchdog.Expired()) { DisconnectWithAlert(CAPT_FAIL_TIMEOUT); return true; } } //qglogfile->AddLine("Exposure done"); //qglogfile->Write(); /* dptr = img.ImageData; for (i=0; i<img.NPixels; i++,dptr++) { *dptr = 0; } */ dptr = img.ImageData; GETBUFFER(dptr, img.NPixels * 2); if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); return false; } void Camera_QGuiderClass::RemoveLines(usImage& img) { int i, j, val; unsigned short data[21]; unsigned short *ptr1, *ptr2; unsigned short med[1024]; int offset; double mean; int h = img.Size.GetHeight(); int w = img.Size.GetWidth(); size_t sz = sizeof(unsigned short); mean = 0.0; for (i=0; i<h; i++) { ptr1 = data; ptr2 = img.ImageData + i*w; for (j=0; j<21; j++, ptr1++, ptr2++) *ptr1 = *ptr2; qsort(data,21,sz,ushort_compare); med[i] = data[10]; mean = mean + (double) (med[i]); } mean = mean / (double) h; for (i=0; i<h; i++) { offset = (int) mean - (int) med[i]; ptr2 = img.ImageData + i*w; for (j=0; j<w; j++, ptr2++) { val = (int) *ptr2 + offset; if (val < 0) val = 0; else if (val > 65535) val = 65535; *ptr2 = (unsigned short) val; } } } #endif
30.284553
111
0.61651
arran-dengate
ce60530ea503d03827bb08677826311f42924efa
1,132
cpp
C++
src/core/nodes/node_base.cpp
Ratstail91/zelda-framework
54e94fe7d69271a514142406355199e8dbcccd38
[ "Zlib" ]
5
2021-04-26T19:55:40.000Z
2021-07-20T08:34:57.000Z
src/core/nodes/node_base.cpp
Ratstail91/zelda-framework
54e94fe7d69271a514142406355199e8dbcccd38
[ "Zlib" ]
null
null
null
src/core/nodes/node_base.cpp
Ratstail91/zelda-framework
54e94fe7d69271a514142406355199e8dbcccd38
[ "Zlib" ]
null
null
null
#include "node_base.hpp" #include <stdexcept> NodeBase* NodeBase::AddChild(NodeBase* const ptr) { for (NodeBase* it = parent; it != nullptr; it = it->parent) { if (it == ptr) { std::logic_error("Looping hierarchy found"); } } children.push_back(ptr); ptr->parent = this; return ptr; } NodeBase* NodeBase::GetChild(int index) { if (index >= 0) { auto it = children.begin(); std::advance(it, index); return *it; } else { //backwards from the end auto it = children.rbegin(); std::advance(it, -index - 1); return *it; } } void NodeBase::RemoveChild(int index) { if (index >= 0) { auto it = children.begin(); std::advance(it, index); (*it)->parent = nullptr; removeDescendantsOfNode(*it); delete *it; children.erase(it); } else { //backwards from the end auto it = children.rbegin(); std::advance(it, -index - 1); (*it)->parent = nullptr; removeDescendantsOfNode(*it.base()); delete *it; children.erase(it.base()); } } void removeDescendantsOfNode(NodeBase* const root) { for (auto childPtr : root->children) { removeDescendantsOfNode(childPtr); delete childPtr; } }
20.962963
62
0.650177
Ratstail91
ce607df48faad17d36ba64da20d5b5d3db62ee58
2,555
cc
C++
algorithms/tests/stack_using_link_list_tests.cc
TusharJadhav/algorithms
eea5120f7d54d82e07eb71677df442248cb50286
[ "MIT" ]
null
null
null
algorithms/tests/stack_using_link_list_tests.cc
TusharJadhav/algorithms
eea5120f7d54d82e07eb71677df442248cb50286
[ "MIT" ]
null
null
null
algorithms/tests/stack_using_link_list_tests.cc
TusharJadhav/algorithms
eea5120f7d54d82e07eb71677df442248cb50286
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "gmock/gmock.h" #include "stack_using_link_list.h" #include <string> using namespace testing; using namespace algorithms; TEST(StackUsingLinkListTests, TestInitiallEmpty) { StackUsingLinkList<int> my_stack; EXPECT_TRUE(my_stack.Empty()) << "Initially the stack is supposed to be empty"; } TEST(StackUsingLinkListTests, TestInitialSizeZero) { StackUsingLinkList<int> my_stack; EXPECT_EQ(my_stack.Size(), 0) << "Initially the stack size should be zero since there are no elements pushed onto it"; } TEST(StackUsingLinkListTests, TestPushPopAndTopOperations) { StackUsingLinkList<int> my_stack; my_stack.Push(10); my_stack.Push(20); my_stack.Push(30); ASSERT_EQ(my_stack.Top(), 30) << "Top element is not correct"; my_stack.Pop(); ASSERT_EQ(my_stack.Top(), 20) << "Top element is not correct"; my_stack.Push(40); ASSERT_EQ(my_stack.Top(), 40) << "Top element is not correct"; my_stack.Pop(); my_stack.Pop(); ASSERT_EQ(my_stack.Top(), 10) << "Top element is not correct"; } TEST(StackUsingLinkListTests, TestNonEmpty) { StackUsingLinkList<int> my_stack; my_stack.Push(10); my_stack.Push(20); my_stack.Push(30); EXPECT_FALSE(my_stack.Empty()) << "Stack is empty after pushing few elements"; } TEST(StackUsingLinkListTests, TestEmpty) { StackUsingLinkList<std::string> my_stack; my_stack.Push("Hi"); my_stack.Push("Hello"); my_stack.Pop(); my_stack.Pop(); EXPECT_TRUE(my_stack.Empty()) << "Stack is not empty after popping all elements"; } TEST(StackUsingLinkListTests, TestSizeAfterPushPopOperations) { StackUsingLinkList<int> my_stack; my_stack.Push(100); my_stack.Push(200); my_stack.Push(300); my_stack.Push(400); ASSERT_EQ(my_stack.Size(), 4) << "Stack size is incorrect"; my_stack.Pop(); ASSERT_EQ(my_stack.Size(), 3) << "Stack size is incorrect"; my_stack.Pop(); my_stack.Pop(); ASSERT_EQ(my_stack.Size(), 1) << "Stack size is incorrect"; my_stack.Pop(); ASSERT_EQ(my_stack.Size(), 0) << "Stack size is incorrect"; } TEST(StackUsingLinkListTests, TestPoppingFromEmptyStack) { StackUsingLinkList<int> my_stack; ASSERT_THROW(my_stack.Pop(), std::underflow_error) << "Popping from an stack did not throw an exception"; } TEST(StackUsingLinkListTests, TestAccessingFrontElementFromEmptyList) { StackUsingLinkList<double> my_stack; ASSERT_THROW(my_stack.Top(), std::underflow_error) << "Accessing top element from an empty stack did not throw an exception"; }
26.894737
128
0.720157
TusharJadhav
ce61635ccca3ad3348a1089ee05f6524c5ecd7d3
17,699
cpp
C++
AlexCrutch/src/main.cpp
TomMinuzzo/CSALEX2022
28513f5e60cee890913c0c5d63fd9e3fcdf4039c
[ "Apache-2.0" ]
null
null
null
AlexCrutch/src/main.cpp
TomMinuzzo/CSALEX2022
28513f5e60cee890913c0c5d63fd9e3fcdf4039c
[ "Apache-2.0" ]
null
null
null
AlexCrutch/src/main.cpp
TomMinuzzo/CSALEX2022
28513f5e60cee890913c0c5d63fd9e3fcdf4039c
[ "Apache-2.0" ]
null
null
null
/* * CANopen main program file for Linux SocketCAN. * * @file main * @author Janez Paternoster * @copyright 2015 Janez Paternoster * * This file is part of CANopenSocket, a Linux implementation of CANopen * stack with master functionality. Project home page is * <https://github.com/CANopenNode/CANopenSocket>. CANopenSocket is based * on CANopenNode: <https://github.com/CANopenNode/CANopenNode>. * * CANopenSocket is free and open source 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, see <http://www.gnu.org/licenses/>. */ #include "CANopen.h" #include "CO_OD_storage.h" #include "CO_Linux_tasks.h" #include "CO_time.h" #include "application.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sched.h> #include <signal.h> #include <errno.h> #include <sys/epoll.h> #include <net/if.h> #include <linux/reboot.h> #include <sys/reboot.h> #include "CO_command.h" #include <pthread.h> #include <sys/time.h> #include <iostream> /*For master-> code SDO direct messaging*/ // #define CO_COMMAND_SDO_BUFFER_SIZE 100000 // #define STRING_BUFFER_SIZE (CO_COMMAND_SDO_BUFFER_SIZE * 4 + 100) #define NSEC_PER_SEC (1000000000) /* The number of nanoseconds per second. */ #define NSEC_PER_MSEC (1000000) /* The number of nanoseconds per millisecond. */ #define TMR_TASK_INTERVAL_NS (1000000) /* Interval of taskTmr in nanoseconds */ #define TMR_TASK_OVERFLOW_US (5000) /* Overflow detect limit for taskTmr in microseconds */ #define INCREMENT_1MS(var) (var++) /* Increment 1ms variable in taskTmr */ #define NODEID (101) #define CANMESSAGELENGTH (100) /* Global variable increments each millisecond. */ volatile uint32_t CO_timer1ms = 0U; /* Mutex is locked, when CAN is not valid (configuration state). May be used * from other threads. RT threads may use CO->CANmodule[0]->CANnormal instead. */ pthread_mutex_t CO_CAN_VALID_mtx = PTHREAD_MUTEX_INITIALIZER; /* Other variables and objects */ static int rtPriority = 2; /* Real time priority, configurable by arguments. (-1=RT disabled) */ static int rtControlPriority = 80; static int mainline_epoll_fd; /* epoll file descriptor for mainline */ static CO_OD_storage_t odStor; /* Object Dictionary storage object for CO_OD_ROM */ static CO_OD_storage_t odStorAuto; /* Object Dictionary storage object for CO_OD_EEPROM */ static char *odStorFile_rom = "od4_storage"; /* Name of the file */ static char *odStorFile_eeprom = "od4_storage_auto"; /* Name of the file */ static CO_time_t CO_time; /* Object for current time */ int commCount = 0; bool readyToStart = false; uint32_t tmr1msPrev = 0; // RT Tast timer struct period_info { struct timespec next_period; long period_ns; }; // Forward declartion of timer functions static void inc_period(struct period_info *pinfo); static void periodic_task_init(struct period_info *pinfo); static void wait_rest_of_period(struct period_info *pinfo); // Forward declaration of helper functions void configureCANopen(int nodeId, int rtPriority, int CANdevice0Index, char *CANdevice); /* Realtime thread */ static void *rt_thread(void *arg); static pthread_t rt_thread_id; static int rt_thread_epoll_fd; /* Realtime control thread */ static void *rt_control_thread(void *arg); static pthread_t rt_control_thread_id; static int rt_control_thread_epoll_fd; /* Signal handler */ volatile sig_atomic_t CO_endProgram = 0; static void sigHandler(int sig) { CO_endProgram = 1; } /* Helper functions ***********************************************************/ void CO_errExit(char *msg) { perror(msg); exit(EXIT_FAILURE); } /* send CANopen generic emergency message */ void CO_error(const uint32_t info) { CO_errorReport(CO->em, CO_EM_GENERIC_SOFTWARE_ERROR, CO_EMC_SOFTWARE_INTERNAL, info); fprintf(stderr, "canopend generic error: 0x%X\n", info); } /******************************************************************************/ /** Mainline and RT thread **/ /******************************************************************************/ int main(int argc, char *argv[]) { CO_NMT_reset_cmd_t reset = CO_RESET_NOT; CO_ReturnError_t odStorStatus_rom, odStorStatus_eeprom; int opt; bool_t firstRun = true; bool_t nodeIdFromArgs = true; /* True, if program arguments are used for CANopen Node Id */ bool_t rebootEnable = false; /* Configurable by arguments */ bool_t commandEnable = false; /* Configurable by arguments */ int nodeId = NODEID; /*!< CAN Network NODEID */ int can_dev_number=6; char CANdeviceList[can_dev_number][10] = {"vcan0\0", "can0\0", "can1\0", "can2\0", "can3\0", "can4\0"}; /*!< linux CAN device interface for app to bind to: change to can1 for bbb, can0 for BBAI vcan0 for virtual can*/ char CANdevice[10]=""; int CANdevice0Index; //Rotate through list of interfaces and select first one existing and up for(unsigned i=0; i<can_dev_number; i++) { printf("%s: ", CANdeviceList[i]); //Check if interface exists CANdevice0Index = if_nametoindex(CANdeviceList[i]);/*map linux CAN interface to corresponding int index return zero if no interface exists.*/ if(CANdevice0Index!=0) { char operstate_filename[255], operstate_s[25]; snprintf(operstate_filename, 254, "/sys/class/net/%s/operstate", CANdeviceList[i]); //Check if it's up FILE* operstate_f = fopen(operstate_filename, "r"); fscanf(operstate_f, "%s", &operstate_s); printf("%s\n", operstate_s); //Check if not "down" as will be "unknown" if up if(strcmp(operstate_s, "down")!=0) { snprintf(CANdevice, 9, "%s", CANdeviceList[i]); printf("Using: %s (%d)\n", CANdeviceList[i], CANdevice0Index); break; } else { CANdevice0Index=0; } } else { printf("-\n"); } } configureCANopen(nodeId, rtPriority, CANdevice0Index, CANdevice); /* Catch signals SIGINT and SIGTERM */ if (signal(SIGINT, sigHandler) == SIG_ERR) CO_errExit("Program init - SIGINIT handler creation failed"); if (signal(SIGTERM, sigHandler) == SIG_ERR) CO_errExit("Program init - SIGTERM handler creation failed"); /* increase variable each startup. Variable is automatically stored in non-volatile memory. */ printf(", count=%u ...\n", ++OD_powerOnCounter); while (reset != CO_RESET_APP && reset != CO_RESET_QUIT && CO_endProgram == 0) { /* CANopen communication reset - initialize CANopen objects *******************/ CO_ReturnError_t err; printf("Canopend- communication reset ...\n"); /* Wait other threads (command interface). */ pthread_mutex_lock(&CO_CAN_VALID_mtx); /* Wait rt_thread. */ if (!firstRun) { CO_LOCK_OD(); CO->CANmodule[0]->CANnormal = false; CO_UNLOCK_OD(); } /* Enter CAN configuration. */ CO_CANsetConfigurationMode(CANdevice0Index); /* initialize CANopen */ if (!nodeIdFromArgs) { /* use value from Object dictionary, if not set by program arguments */ nodeId = OD_CANNodeID; } err = CO_init(CANdevice0Index, nodeId, 0); if (err != CO_ERROR_NO) { char s[120]; snprintf(s, 120, "Communication reset - CANopen initialization failed, err=%d", err); CO_errExit(s); } /* Configure callback functions for task control */ CO_EM_initCallback(CO->em, taskMain_cbSignal); CO_SDO_initCallback(CO->SDO[0], taskMain_cbSignal); CO_SDOclient_initCallback(CO->SDOclient, taskMain_cbSignal); /* Initialize time */ CO_time_init(&CO_time, CO->SDO[0], &OD_time.epochTimeBaseMs, &OD_time.epochTimeOffsetMs, 0x2130); /* First time only initialization. */ if (firstRun) { firstRun = false; /* Configure epoll for mainline */ mainline_epoll_fd = epoll_create(4); if (mainline_epoll_fd == -1) CO_errExit("Program init - epoll_create mainline failed"); /* Init mainline */ taskMain_init(mainline_epoll_fd, &OD_performance[ODA_performance_mainCycleMaxTime]); /* Configure epoll for rt_thread */ rt_thread_epoll_fd = epoll_create(2); if (rt_thread_epoll_fd == -1) CO_errExit("Program init - epoll_create rt_thread failed"); /* Init taskRT */ CANrx_taskTmr_init(rt_thread_epoll_fd, TMR_TASK_INTERVAL_NS, &OD_performance[ODA_performance_timerCycleMaxTime]); OD_performance[ODA_performance_timerCycleTime] = TMR_TASK_INTERVAL_NS / 1000; /* informative */ /* Initialize socket command interface */ if (commandEnable) { if (CO_command_init() != 0) { CO_errExit("Socket command interface initialization failed"); } printf("Canopend - Command interface on socket '%s' started ...\n", CO_command_socketPath); } /*OLD THREAD CREATION*/ /* Create rt_thread */ if (pthread_create(&rt_thread_id, NULL, rt_thread, NULL) != 0) CO_errExit("Program init - rt_thread creation failed"); /* Set priority for rt_thread */ if (rtPriority > 0) { struct sched_param param; param.sched_priority = rtPriority; if (pthread_setschedparam(rt_thread_id, SCHED_FIFO, &param) != 0) CO_errExit("Program init - rt_thread set scheduler failed"); } /* Create rt_control_thread */ if (pthread_create(&rt_control_thread_id, NULL, rt_control_thread, NULL) != 0) CO_errExit("Program init - rt_thread_control creation failed"); /* Set priority for rt_thread */ if (rtPriority > 0) { struct sched_param paramc; paramc.sched_priority = rtControlPriority; if (pthread_setschedparam(rt_thread_id, SCHED_FIFO, &paramc) != 0) CO_errExit("Program init - rt_thread set scheduler failed"); } } /* start CAN */ CO_CANsetNormalMode(CO->CANmodule[0]); pthread_mutex_unlock(&CO_CAN_VALID_mtx); /* Execute optional additional application code */ // app_programStart(); reset = CO_RESET_NOT; // Create Statemachine Object -> will be loaded by taskmanager in end program. /* Execute optional additional application code */ app_communicationReset(); // Initialise the last time variable //gettimeofday(&last_tv,NULL); //struct timeval first_tv = last_tv; printf("Canopend- running ...\n"); readyToStart = true; while (reset == CO_RESET_NOT && CO_endProgram == 0) { /* loop for normal program execution ******************************************/ int ready; int first = 0; struct epoll_event ev; ready = epoll_wait(mainline_epoll_fd, &ev, 1, -1); if (ready != 1) { if (errno != EINTR) { CO_error(0x11100000L + errno); } } else if (taskMain_process(ev.data.fd, &reset, CO_timer1ms)) { uint32_t timer1msDiff; timer1msDiff = CO_timer1ms - tmr1msPrev; tmr1msPrev = CO_timer1ms; app_programAsync(timer1msDiff); CO_OD_storage_autoSave(&odStorAuto, CO_timer1ms, 60000); /* Execute optional additional application code */ } else { /* No file descriptor was processed. */ CO_error(0x11200000L); /* CHANGE TO FILE!*/ } } } /* program exit ***************************************************************/ /* join threads */ if (commandEnable) { if (CO_command_clear() != 0) { CO_errExit("Socket command interface removal failed"); } } CO_endProgram = 1; if (pthread_join(rt_thread_id, NULL) != 0) { CO_errExit("Program end - pthread_join failed"); } /* Execute optional additional application code */ app_programEnd(); /* Store CO_OD_EEPROM */ CO_OD_storage_autoSave(&odStorAuto, 0, 0); CO_OD_storage_autoSaveClose(&odStorAuto); /* delete objects from memory */ CANrx_taskTmr_close(); taskMain_close(); CO_delete(CANdevice0Index); printf("Canopend on %s (nodeId=0x%02X) - finished.\n\n", CANdevice, nodeId); /* Flush all buffers (and reboot) */ if (rebootEnable && reset == CO_RESET_APP) { sync(); if (reboot(LINUX_REBOOT_CMD_RESTART) != 0) { CO_errExit("Program end - reboot failed"); } } exit(EXIT_SUCCESS); } /* Realtime thread for CAN receive and taskTmr ********************************/ static void *rt_thread(void *arg) { /* Endless loop */ while (CO_endProgram == 0) { int ready; struct epoll_event ev; ready = epoll_wait(rt_thread_epoll_fd, &ev, 1, -1); if (ready != 1) { if (errno != EINTR) { CO_error(0x12100000L + errno); } } else if (CANrx_taskTmr_process(ev.data.fd)) { /* code was processed in the above function. Additional code process below */ INCREMENT_1MS(CO_timer1ms); /* Monitor variables with trace objects */ CO_time_process(&CO_time); #if CO_NO_TRACE > 0 for (i = 0; i < OD_traceEnable && i < CO_NO_TRACE; i++) { CO_trace_process(CO->trace[i], *CO_time.epochTimeOffsetMs); } #endif /* Execute optional additional application code */ // app_program1ms(); /* Detect timer large overflow */ // if (OD_performance[ODA_performance_timerCycleMaxTime] > TMR_TASK_OVERFLOW_US && rtPriority > 0 && CO->CANmodule[0]->CANnormal) // { // CO_errorReport(CO->em, CO_EM_ISR_TIMER_OVERFLOW, CO_EMC_SOFTWARE_INTERNAL, 0x22400000L | OD_performance[ODA_performance_timerCycleMaxTime]); // printf("Timer large overflow \n"); // } } else { /* No file descriptor was processed. */ CO_error(0x12200000L); } } return NULL; } /*Control thread*/ static void *rt_control_thread(void *arg) { struct period_info pinfo; periodic_task_init(&pinfo); app_programStart(); while (!readyToStart) { wait_rest_of_period(&pinfo); } while (CO_endProgram == 0) { app_program1ms(); wait_rest_of_period(&pinfo); } return NULL; } // RT Tast timer // Make sure RT control loop runs slow enough for bit flip messages to be sent and changed in each drive. static void inc_period(struct period_info *pinfo) { pinfo->next_period.tv_nsec += pinfo->period_ns; while (pinfo->next_period.tv_nsec >= 1000000000) { /* timespec nsec overflow */ pinfo->next_period.tv_sec++; pinfo->next_period.tv_nsec -= 1000000000; } } static void periodic_task_init(struct period_info *pinfo) { /* for simplicity, hardcoding a 1ms period */ pinfo->period_ns = 1000000; clock_gettime(CLOCK_MONOTONIC, &(pinfo->next_period)); } static void wait_rest_of_period(struct period_info *pinfo) { inc_period(pinfo); /* for simplicity, ignoring possibilities of signal wakes */ clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &pinfo->next_period, NULL); } void configureCANopen(int nodeId, int rtPriority, int CANdevice0Index, char *CANdevice) { if (nodeId < 1 || nodeId > 127) { fprintf(stderr, "NODE ID outside range (%d)\n", nodeId); exit(EXIT_FAILURE); } // rt Thread priority sanity check if (rtPriority != -1 && (rtPriority < sched_get_priority_min(SCHED_FIFO) || rtPriority > sched_get_priority_max(SCHED_FIFO))) { fprintf(stderr, "Wrong RT priority (%d)\n", rtPriority); exit(EXIT_FAILURE); } if (CANdevice0Index == 0) { char s[120]; snprintf(s, 120, "Can't find CAN device \"%s\"", CANdevice); CO_errExit(s); } /* Verify, if OD structures have proper alignment of initial values */ if (CO_OD_RAM.FirstWord != CO_OD_RAM.LastWord) { fprintf(stderr, "Program init - Canopend- Error in CO_OD_RAM.\n"); exit(EXIT_FAILURE); } };
34.90927
224
0.607548
TomMinuzzo
ce62629d46ebb99c0596ba8e4201ba606fc24424
4,488
cpp
C++
src/arch/Lights/LightsDriver_Linux_PIUIO.cpp
Midiman/stepmania
a55d5d614c4caa8b035b9b7cdca94017baba026b
[ "MIT" ]
null
null
null
src/arch/Lights/LightsDriver_Linux_PIUIO.cpp
Midiman/stepmania
a55d5d614c4caa8b035b9b7cdca94017baba026b
[ "MIT" ]
null
null
null
src/arch/Lights/LightsDriver_Linux_PIUIO.cpp
Midiman/stepmania
a55d5d614c4caa8b035b9b7cdca94017baba026b
[ "MIT" ]
null
null
null
#include "global.h" #include <stdio.h> #if defined(HAVE_UNISTD_H) #include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> #if defined(HAVE_FCNTL_H) #include <fcntl.h> #endif #include <errno.h> #include "LightsDriver_Linux_PIUIO.h" #include "GameState.h" #include "Game.h" #include "RageLog.h" REGISTER_SOUND_DRIVER_CLASS2(PIUIO, Linux_PIUIO); LightsDriver_Linux_PIUIO::LightsDriver_Linux_PIUIO() { // Open port fd = open("/dev/piuio0", O_WRONLY); if( fd < 0 ) { LOG->Warn( "Error opening serial port for lights. Error: %d %s", errno, strerror(errno) ); return; } LOG->Info("Opened PIUIO device for lights"); } LightsDriver_Linux_PIUIO::~LightsDriver_Linux_PIUIO() { if( fd >= 0 ) close(fd); } void LightsDriver_Linux_PIUIO::Set( const LightsState *ls ) { unsigned char buf[8] = { 0, 0, 0, 0x08, 0x37, 0, 0, 0 }; static unsigned char oldbuf[8] = { 0, 0, 0, 0x08, 0x37, 0, 0, 0 }; if (ls->m_bCabinetLights[LIGHT_MARQUEE_UP_LEFT]) buf[2] |= 0x80; if (ls->m_bCabinetLights[LIGHT_MARQUEE_UP_RIGHT]) buf[3] |= 0x04; if (ls->m_bCabinetLights[LIGHT_MARQUEE_LR_LEFT]) buf[3] |= 0x02; if (ls->m_bCabinetLights[LIGHT_MARQUEE_LR_RIGHT]) buf[3] |= 0x01; if (ls->m_bCabinetLights[LIGHT_BASS_LEFT] || ls->m_bCabinetLights[LIGHT_BASS_RIGHT]) buf[1] |= 0x04; RString sInput = GAMESTATE->GetCurrentGame()->m_InputScheme.m_szName; if (sInput.EqualsNoCase("dance")) { if (ls->m_bGameButtonLights[GameController_1][DANCE_BUTTON_UP]) buf[2] |= 0x04; if (ls->m_bGameButtonLights[GameController_1][DANCE_BUTTON_DOWN]) buf[2] |= 0x08; if (ls->m_bGameButtonLights[GameController_1][DANCE_BUTTON_LEFT]) buf[2] |= 0x10; if (ls->m_bGameButtonLights[GameController_1][DANCE_BUTTON_RIGHT]) buf[2] |= 0x20; if (ls->m_bGameButtonLights[GameController_2][DANCE_BUTTON_UP]) buf[0] |= 0x04; if (ls->m_bGameButtonLights[GameController_2][DANCE_BUTTON_DOWN]) buf[0] |= 0x08; if (ls->m_bGameButtonLights[GameController_2][DANCE_BUTTON_LEFT]) buf[0] |= 0x10; if (ls->m_bGameButtonLights[GameController_2][DANCE_BUTTON_RIGHT]) buf[0] |= 0x20; } else if (sInput.EqualsNoCase("pump")) { if (ls->m_bGameButtonLights[GameController_1][PUMP_BUTTON_UPLEFT]) buf[0] |= 0x04; if (ls->m_bGameButtonLights[GameController_1][PUMP_BUTTON_UPRIGHT]) buf[0] |= 0x08; if (ls->m_bGameButtonLights[GameController_1][PUMP_BUTTON_CENTER]) buf[0] |= 0x10; if (ls->m_bGameButtonLights[GameController_1][PUMP_BUTTON_DOWNLEFT]) buf[0] |= 0x20; if (ls->m_bGameButtonLights[GameController_1][PUMP_BUTTON_DOWNRIGHT]) buf[0] |= 0x40; if (ls->m_bGameButtonLights[GameController_2][PUMP_BUTTON_UPLEFT]) buf[2] |= 0x04; if (ls->m_bGameButtonLights[GameController_2][PUMP_BUTTON_UPRIGHT]) buf[2] |= 0x08; if (ls->m_bGameButtonLights[GameController_2][PUMP_BUTTON_CENTER]) buf[2] |= 0x10; if (ls->m_bGameButtonLights[GameController_2][PUMP_BUTTON_DOWNLEFT]) buf[2] |= 0x20; if (ls->m_bGameButtonLights[GameController_2][PUMP_BUTTON_DOWNRIGHT]) buf[2] |= 0x40; } if (!memcmp(buf, oldbuf, 8)) return; memcpy(oldbuf, buf, 8); if (write(fd, buf, 8) != 8) { LOG->Warn( "Error setting lights state. Error: %d %s", errno, strerror(errno) ); return; } } /* * (c) 2012-2013 StepMania team * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
41.174312
101
0.738414
Midiman
ce63a4cd3130c312792790c4e15a7571110a5c27
16,647
cc
C++
ppapi/proxy/tracked_callback_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ppapi/proxy/tracked_callback_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ppapi/proxy/tracked_callback_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2012 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 <stdint.h> #include "base/bind.h" #include "base/location.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" #include "base/threading/simple_thread.h" #include "ppapi/c/pp_completion_callback.h" #include "ppapi/c/pp_errors.h" #include "ppapi/proxy/ppapi_proxy_test.h" #include "ppapi/proxy/ppb_message_loop_proxy.h" #include "ppapi/shared_impl/callback_tracker.h" #include "ppapi/shared_impl/proxy_lock.h" #include "ppapi/shared_impl/resource.h" #include "ppapi/shared_impl/resource_tracker.h" #include "ppapi/shared_impl/scoped_pp_resource.h" #include "ppapi/shared_impl/test_globals.h" #include "ppapi/shared_impl/tracked_callback.h" #include "testing/gtest/include/gtest/gtest.h" // Note, this file tests TrackedCallback which lives in ppapi/shared_impl. // Unfortunately, we need the test to live in ppapi/proxy so that it can use // the thread support there. namespace ppapi { namespace proxy { namespace { class CallbackThread : public base::SimpleThread { public: explicit CallbackThread(PP_Instance instance) : SimpleThread("CallbackThread"), instance_(instance) {} ~CallbackThread() override {} // base::SimpleThread overrides. void BeforeStart() override { ProxyAutoLock acquire; // Create the message loop here, after PpapiGlobals has been created. message_loop_ = new MessageLoopResource(instance_); } void BeforeJoin() override { ProxyAutoLock acquire; message_loop()->PostQuit(PP_TRUE); message_loop_ = nullptr; } void Run() override { ProxyAutoLock acquire; // Make a local copy of message_loop_ for this thread so we can interact // with it even after the main thread releases it. scoped_refptr<MessageLoopResource> message_loop(message_loop_); message_loop->AttachToCurrentThread(); // Note, run releases the lock to run events. base::RunLoop().Run(); message_loop->DetachFromThread(); } MessageLoopResource* message_loop() { return message_loop_.get(); } private: PP_Instance instance_; scoped_refptr<MessageLoopResource> message_loop_; }; class TrackedCallbackTest : public PluginProxyTest { public: TrackedCallbackTest() : thread_(pp_instance()) {} CallbackThread& thread() { return thread_; } private: // PluginProxyTest overrides. void SetUp() override { PluginProxyTest::SetUp(); thread_.Start(); } void TearDown() override { thread_.Join(); PluginProxyTest::TearDown(); base::RunLoop run_loop; run_loop.RunUntilIdle(); } CallbackThread thread_; }; // All valid results (PP_OK, PP_ERROR_...) are nonpositive. const int32_t kInitializedResultValue = 1; const int32_t kOverrideResultValue = 2; struct CallbackRunInfo { explicit CallbackRunInfo(base::ThreadChecker* thread_checker) : run_count_(0), result_(kInitializedResultValue), completion_task_run_count_(0), completion_task_result_(kInitializedResultValue), thread_checker_(thread_checker), callback_did_run_event_( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED) {} void CallbackDidRun(int32_t result) { CHECK(thread_checker_->CalledOnValidThread()); if (!run_count_) result_ = result; ++run_count_; callback_did_run_event_.Signal(); } void CompletionTaskDidRun(int32_t result) { CHECK(thread_checker_->CalledOnValidThread()); if (!completion_task_run_count_) completion_task_result_ = result; ++completion_task_run_count_; } void WaitUntilCompleted() { callback_did_run_event_.Wait(); } unsigned run_count() { return run_count_; } int32_t result() { return result_; } unsigned completion_task_run_count() { return completion_task_run_count_; } int32_t completion_task_result() { return completion_task_result_; } private: unsigned run_count_; int32_t result_; unsigned completion_task_run_count_; int32_t completion_task_result_; // Weak; owned by the creator of CallbackRunInfo. base::ThreadChecker* thread_checker_; base::WaitableEvent callback_did_run_event_; }; void TestCallback(void* user_data, int32_t result) { CallbackRunInfo* info = static_cast<CallbackRunInfo*>(user_data); info->CallbackDidRun(result); } // CallbackShutdownTest -------------------------------------------------------- class CallbackShutdownTest : public TrackedCallbackTest { public: CallbackShutdownTest() : info_did_run_(&thread_checker_), info_did_abort_(&thread_checker_), info_didnt_run_(&thread_checker_) {} // Cases: // (1) A callback which is run (so shouldn't be aborted on shutdown). // (2) A callback which is aborted (so shouldn't be aborted on shutdown). // (3) A callback which isn't run (so should be aborted on shutdown). CallbackRunInfo& info_did_run() { return info_did_run_; } // (1) CallbackRunInfo& info_did_abort() { return info_did_abort_; } // (2) CallbackRunInfo& info_didnt_run() { return info_didnt_run_; } // (3) private: base::ThreadChecker thread_checker_; CallbackRunInfo info_did_run_; CallbackRunInfo info_did_abort_; CallbackRunInfo info_didnt_run_; }; } // namespace // Tests that callbacks are properly aborted on module shutdown. TEST_F(CallbackShutdownTest, DISABLED_AbortOnShutdown) { ProxyAutoLock lock; scoped_refptr<Resource> resource( new Resource(OBJECT_IS_PROXY, pp_instance())); // Set up case (1) (see above). EXPECT_EQ(0U, info_did_run().run_count()); // TODO(dmichael): Test this on a background thread? scoped_refptr<TrackedCallback> callback_did_run = new TrackedCallback( resource.get(), PP_MakeCompletionCallback(&TestCallback, &info_did_run())); EXPECT_EQ(0U, info_did_run().run_count()); callback_did_run->Run(PP_OK); EXPECT_EQ(1U, info_did_run().run_count()); EXPECT_EQ(PP_OK, info_did_run().result()); // Set up case (2). EXPECT_EQ(0U, info_did_abort().run_count()); scoped_refptr<TrackedCallback> callback_did_abort = new TrackedCallback( resource.get(), PP_MakeCompletionCallback(&TestCallback, &info_did_abort())); EXPECT_EQ(0U, info_did_abort().run_count()); callback_did_abort->Abort(); EXPECT_EQ(1U, info_did_abort().run_count()); EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort().result()); // Set up case (3). EXPECT_EQ(0U, info_didnt_run().run_count()); scoped_refptr<TrackedCallback> callback_didnt_run = new TrackedCallback( resource.get(), PP_MakeCompletionCallback(&TestCallback, &info_didnt_run())); EXPECT_EQ(0U, info_didnt_run().run_count()); GetGlobals()->GetCallbackTrackerForInstance(pp_instance())->AbortAll(); // Check case (1). EXPECT_EQ(1U, info_did_run().run_count()); // Check case (2). EXPECT_EQ(1U, info_did_abort().run_count()); // Check case (3). EXPECT_EQ(1U, info_didnt_run().run_count()); EXPECT_EQ(PP_ERROR_ABORTED, info_didnt_run().result()); } // CallbackResourceTest -------------------------------------------------------- namespace { class CallbackResourceTest : public TrackedCallbackTest { public: CallbackResourceTest() {} }; class CallbackMockResource : public Resource { public: static scoped_refptr<CallbackMockResource> Create(PP_Instance instance) { ProxyAutoLock acquire; return scoped_refptr<CallbackMockResource>( new CallbackMockResource(instance)); } ~CallbackMockResource() {} // Take a reference to this resource, which will add it to the tracker. void TakeRef() { ProxyAutoLock acquire; ScopedPPResource temp_resource(ScopedPPResource::PassRef(), GetReference()); EXPECT_NE(0, temp_resource.get()); reference_holder_ = temp_resource; } // Release it, removing it from the tracker. void ReleaseRef() { ProxyAutoLock acquire; reference_holder_ = 0; } // Create the test callbacks on a background thread, so that we can verify // they are run on the same thread where they were created. void CreateCallbacksOnLoop(MessageLoopResource* loop_resource) { ProxyAutoLock acquire; // |thread_checker_| will bind to the background thread. thread_checker_.DetachFromThread(); loop_resource->task_runner()->PostTask( FROM_HERE, RunWhileLocked(base::Bind( &CallbackMockResource::CreateCallbacks, this))); } int32_t CompletionTask(CallbackRunInfo* info, int32_t result) { // The completion task must run on the thread where the callback was // created, and must hold the proxy lock. CHECK(thread_checker_.CalledOnValidThread()); ProxyLock::AssertAcquired(); // We should run before the callback. CHECK_EQ(0U, info->run_count()); info->CompletionTaskDidRun(result); return kOverrideResultValue; } void CheckInitialState() { callbacks_created_event_.Wait(); EXPECT_EQ(0U, info_did_run_.run_count()); EXPECT_EQ(0U, info_did_run_.completion_task_run_count()); EXPECT_EQ(0U, info_did_run_with_completion_task_.run_count()); EXPECT_EQ(0U, info_did_run_with_completion_task_.completion_task_run_count()); EXPECT_EQ(0U, info_did_abort_.run_count()); EXPECT_EQ(0U, info_did_abort_.completion_task_run_count()); EXPECT_EQ(0U, info_didnt_run_.run_count()); EXPECT_EQ(0U, info_didnt_run_.completion_task_run_count()); } void RunCallbacks() { callback_did_run_->Run(PP_OK); callback_did_run_with_completion_task_->Run(PP_OK); callback_did_abort_->Abort(); info_did_run_.WaitUntilCompleted(); info_did_run_with_completion_task_.WaitUntilCompleted(); info_did_abort_.WaitUntilCompleted(); } void CheckIntermediateState() { EXPECT_EQ(1U, info_did_run_.run_count()); EXPECT_EQ(PP_OK, info_did_run_.result()); EXPECT_EQ(0U, info_did_run_.completion_task_run_count()); EXPECT_EQ(1U, info_did_run_with_completion_task_.run_count()); // completion task should override the result. EXPECT_EQ(kOverrideResultValue, info_did_run_with_completion_task_.result()); EXPECT_EQ(1U, info_did_run_with_completion_task_.completion_task_run_count()); EXPECT_EQ(PP_OK, info_did_run_with_completion_task_.completion_task_result()); EXPECT_EQ(1U, info_did_abort_.run_count()); // completion task shouldn't override an abort. EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort_.result()); EXPECT_EQ(1U, info_did_abort_.completion_task_run_count()); EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort_.completion_task_result()); EXPECT_EQ(0U, info_didnt_run_.completion_task_run_count()); EXPECT_EQ(0U, info_didnt_run_.run_count()); } void CheckFinalState() { info_didnt_run_.WaitUntilCompleted(); EXPECT_EQ(1U, info_did_run_with_completion_task_.run_count()); EXPECT_EQ(kOverrideResultValue, info_did_run_with_completion_task_.result()); callback_did_run_with_completion_task_ = nullptr; EXPECT_EQ(1U, info_did_run_.run_count()); EXPECT_EQ(PP_OK, info_did_run_.result()); callback_did_run_ = nullptr; EXPECT_EQ(1U, info_did_abort_.run_count()); EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort_.result()); callback_did_abort_ = nullptr; EXPECT_EQ(1U, info_didnt_run_.run_count()); EXPECT_EQ(PP_ERROR_ABORTED, info_didnt_run_.result()); callback_didnt_run_ = nullptr; } private: explicit CallbackMockResource(PP_Instance instance) : Resource(OBJECT_IS_PROXY, instance), info_did_run_(&thread_checker_), info_did_run_with_completion_task_(&thread_checker_), info_did_abort_(&thread_checker_), info_didnt_run_(&thread_checker_), callbacks_created_event_( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED) {} void CreateCallbacks() { // Bind thread_checker_ to the thread where we create the callbacks. // Later, when the callback runs, it will check that it was invoked on this // same thread. CHECK(thread_checker_.CalledOnValidThread()); callback_did_run_ = new TrackedCallback( this, PP_MakeCompletionCallback(&TestCallback, &info_did_run_)); // In order to test that the completion task can override the callback // result, we need to test callbacks with and without a completion task. callback_did_run_with_completion_task_ = new TrackedCallback( this, PP_MakeCompletionCallback(&TestCallback, &info_did_run_with_completion_task_)); callback_did_run_with_completion_task_->set_completion_task( Bind(&CallbackMockResource::CompletionTask, this, &info_did_run_with_completion_task_)); callback_did_abort_ = new TrackedCallback( this, PP_MakeCompletionCallback(&TestCallback, &info_did_abort_)); callback_did_abort_->set_completion_task( Bind(&CallbackMockResource::CompletionTask, this, &info_did_abort_)); callback_didnt_run_ = new TrackedCallback( this, PP_MakeCompletionCallback(&TestCallback, &info_didnt_run_)); callback_didnt_run_->set_completion_task( Bind(&CallbackMockResource::CompletionTask, this, &info_didnt_run_)); callbacks_created_event_.Signal(); } // Used to verify that the callback runs on the same thread where it is // created. base::ThreadChecker thread_checker_; scoped_refptr<TrackedCallback> callback_did_run_; CallbackRunInfo info_did_run_; scoped_refptr<TrackedCallback> callback_did_run_with_completion_task_; CallbackRunInfo info_did_run_with_completion_task_; scoped_refptr<TrackedCallback> callback_did_abort_; CallbackRunInfo info_did_abort_; scoped_refptr<TrackedCallback> callback_didnt_run_; CallbackRunInfo info_didnt_run_; base::WaitableEvent callbacks_created_event_; ScopedPPResource reference_holder_; }; } // namespace // Test that callbacks get aborted on the last resource unref. TEST_F(CallbackResourceTest, DISABLED_AbortOnNoRef) { // Test several things: Unref-ing a resource (to zero refs) with callbacks // which (1) have been run, (2) have been aborted, (3) haven't been completed. // Check that the uncompleted one gets aborted, and that the others don't get // called again. scoped_refptr<CallbackMockResource> resource_1( CallbackMockResource::Create(pp_instance())); resource_1->CreateCallbacksOnLoop(thread().message_loop()); resource_1->CheckInitialState(); resource_1->RunCallbacks(); resource_1->TakeRef(); resource_1->CheckIntermediateState(); // Also do the same for a second resource, and make sure that unref-ing the // first resource doesn't much up the second resource. scoped_refptr<CallbackMockResource> resource_2( CallbackMockResource::Create(pp_instance())); resource_2->CreateCallbacksOnLoop(thread().message_loop()); resource_2->CheckInitialState(); resource_2->RunCallbacks(); resource_2->TakeRef(); resource_2->CheckIntermediateState(); // Double-check that resource #1 is still okay. resource_1->CheckIntermediateState(); // Kill resource #1, spin the message loop to run posted calls, and check that // things are in the expected states. resource_1->ReleaseRef(); resource_1->CheckFinalState(); resource_2->CheckIntermediateState(); // Kill resource #2. resource_2->ReleaseRef(); resource_1->CheckFinalState(); resource_2->CheckFinalState(); { ProxyAutoLock lock; resource_1 = nullptr; resource_2 = nullptr; } } // Test that "resurrecting" a resource (getting a new ID for a |Resource|) // doesn't resurrect callbacks. TEST_F(CallbackResourceTest, DISABLED_Resurrection) { scoped_refptr<CallbackMockResource> resource( CallbackMockResource::Create(pp_instance())); resource->CreateCallbacksOnLoop(thread().message_loop()); resource->CheckInitialState(); resource->RunCallbacks(); resource->TakeRef(); resource->CheckIntermediateState(); // Unref it and check that things are in the expected states. resource->ReleaseRef(); resource->CheckFinalState(); // "Resurrect" it and check that the callbacks are still dead. resource->TakeRef(); resource->CheckFinalState(); // Unref it again and do the same. resource->ReleaseRef(); resource->CheckFinalState(); { ProxyAutoLock lock; resource = nullptr; } } } // namespace proxy } // namespace ppapi
35.194503
80
0.732685
zipated
ce6412410768fa4b36aa19e8ed8956bc19d443a5
1,916
cc
C++
tensorpipe/common/allocator.cc
pruthvistony/tensorpipe
3424d81160325e50ae9e001d0121e4f769dc30ac
[ "BSD-3-Clause" ]
null
null
null
tensorpipe/common/allocator.cc
pruthvistony/tensorpipe
3424d81160325e50ae9e001d0121e4f769dc30ac
[ "BSD-3-Clause" ]
null
null
null
tensorpipe/common/allocator.cc
pruthvistony/tensorpipe
3424d81160325e50ae9e001d0121e4f769dc30ac
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <tensorpipe/common/allocator.h> #include <tensorpipe/common/defs.h> #include <tensorpipe/common/error_macros.h> namespace tensorpipe { Allocator::Allocator(uint8_t* data, size_t numChunks, size_t chunkSize) : numChunks_(numChunks), chunkSize_(chunkSize), data_(data), chunkAvailable_(numChunks, true) {} Allocator::~Allocator() { close(); } void Allocator::alloc(size_t size, TAllocCallback callback) { TP_DCHECK(size <= chunkSize_); pendingAllocations_.push_back(std::move(callback)); processAllocations(); } size_t Allocator::getChunkLength() const { return chunkSize_; } void Allocator::close() { if (closed_) { return; } closed_ = true; processAllocations(); } void Allocator::processAllocations() { while (!pendingAllocations_.empty()) { auto& callback = pendingAllocations_.front(); if (closed_) { callback(TP_CREATE_ERROR(AllocatorClosedError), nullptr); } else { TChunk ptr = getAvailableChunk(); if (!ptr) { break; } callback(Error::kSuccess, std::move(ptr)); } pendingAllocations_.pop_front(); } } Allocator::TChunk Allocator::getAvailableChunk() { for (size_t curChunk = 0; curChunk < numChunks_; ++curChunk) { if (chunkAvailable_[curChunk]) { chunkAvailable_[curChunk] = false; ++allocatedChunks_; return TChunk(data_ + curChunk * chunkSize_, [this](uint8_t* ptr) { releaseChunk(ptr); }); } } return nullptr; } void Allocator::releaseChunk(uint8_t* ptr) { size_t chunkId = (ptr - data_) / chunkSize_; chunkAvailable_[chunkId] = true; --allocatedChunks_; processAllocations(); } } // namespace tensorpipe
23.365854
73
0.681106
pruthvistony
ce65abb357104751b18cf101c82cf8d34825ecd2
12,112
cpp
C++
tests/VkDrawableTest.cpp
TheRakeshPurohit/skia
817dd601f85f986a99d102de8dc42ee8638a56f9
[ "BSD-3-Clause" ]
null
null
null
tests/VkDrawableTest.cpp
TheRakeshPurohit/skia
817dd601f85f986a99d102de8dc42ee8638a56f9
[ "BSD-3-Clause" ]
null
null
null
tests/VkDrawableTest.cpp
TheRakeshPurohit/skia
817dd601f85f986a99d102de8dc42ee8638a56f9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This is a GPU-backend specific test. It relies on static initializers to work #include "include/core/SkTypes.h" #if SK_SUPPORT_GPU && defined(SK_VULKAN) #include "include/gpu/vk/GrVkVulkan.h" #include "include/core/SkBitmap.h" #include "include/core/SkDrawable.h" #include "include/core/SkSurface.h" #include "include/gpu/GrBackendDrawableInfo.h" #include "include/gpu/GrDirectContext.h" #include "src/gpu/ganesh/GrDirectContextPriv.h" #include "src/gpu/ganesh/vk/GrVkGpu.h" #include "src/gpu/ganesh/vk/GrVkInterface.h" #include "src/gpu/ganesh/vk/GrVkMemory.h" #include "src/gpu/ganesh/vk/GrVkSecondaryCBDrawContext_impl.h" #include "src/gpu/ganesh/vk/GrVkUtil.h" #include "tests/Test.h" #include "tools/gpu/GrContextFactory.h" using sk_gpu_test::GrContextFactory; static const int DEV_W = 16, DEV_H = 16; class TestDrawable : public SkDrawable { public: TestDrawable(const GrVkInterface* interface, GrDirectContext* dContext, int32_t width, int32_t height) : INHERITED() , fInterface(interface) , fDContext(dContext) , fWidth(width) , fHeight(height) {} ~TestDrawable() override {} class DrawHandlerBasic : public GpuDrawHandler { public: DrawHandlerBasic(const GrVkInterface* interface, int32_t width, int32_t height) : INHERITED() , fInterface(interface) , fWidth(width) , fHeight(height) {} ~DrawHandlerBasic() override {} void draw(const GrBackendDrawableInfo& info) override { GrVkDrawableInfo vkInfo; SkAssertResult(info.getVkDrawableInfo(&vkInfo)); // Clear to Red VkClearColorValue vkColor; vkColor.float32[0] = 1.0f; // r vkColor.float32[1] = 0.0f; // g vkColor.float32[2] = 0.0f; // b vkColor.float32[3] = 1.0f; // a // Clear right half of render target VkClearRect clearRect; clearRect.rect.offset = { fWidth / 2, 0 }; clearRect.rect.extent = { (uint32_t)fWidth / 2, (uint32_t)fHeight }; clearRect.baseArrayLayer = 0; clearRect.layerCount = 1; VkClearAttachment attachment; attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; attachment.colorAttachment = vkInfo.fColorAttachmentIndex; attachment.clearValue.color = vkColor; GR_VK_CALL(fInterface, CmdClearAttachments(vkInfo.fSecondaryCommandBuffer, 1, &attachment, 1, &clearRect)); vkInfo.fDrawBounds->offset = { fWidth / 2, 0 }; vkInfo.fDrawBounds->extent = { (uint32_t)fWidth / 2, (uint32_t)fHeight }; } private: const GrVkInterface* fInterface; int32_t fWidth; int32_t fHeight; using INHERITED = GpuDrawHandler; }; typedef void (*DrawProc)(TestDrawable*, const SkMatrix&, const SkIRect&, const SkImageInfo&, const GrVkDrawableInfo&); typedef void (*SubmitProc)(TestDrawable*); // Exercises the exporting of a secondary command buffer from one context and then importing // it into a second context. We then draw to the secondary command buffer from the second // context. class DrawHandlerImport : public GpuDrawHandler { public: DrawHandlerImport(TestDrawable* td, DrawProc drawProc, SubmitProc submitProc, const SkMatrix& matrix, const SkIRect& clipBounds, const SkImageInfo& bufferInfo) : INHERITED() , fTestDrawable(td) , fDrawProc(drawProc) , fSubmitProc(submitProc) , fMatrix(matrix) , fClipBounds(clipBounds) , fBufferInfo(bufferInfo) {} ~DrawHandlerImport() override { fSubmitProc(fTestDrawable); } void draw(const GrBackendDrawableInfo& info) override { GrVkDrawableInfo vkInfo; SkAssertResult(info.getVkDrawableInfo(&vkInfo)); fDrawProc(fTestDrawable, fMatrix, fClipBounds, fBufferInfo, vkInfo); } private: TestDrawable* fTestDrawable; DrawProc fDrawProc; SubmitProc fSubmitProc; const SkMatrix fMatrix; const SkIRect fClipBounds; const SkImageInfo fBufferInfo; using INHERITED = GpuDrawHandler; }; // Helper function to test drawing to a secondary command buffer that we imported into the // context using a GrVkSecondaryCBDrawContext. static void ImportDraw(TestDrawable* td, const SkMatrix& matrix, const SkIRect& clipBounds, const SkImageInfo& bufferInfo, const GrVkDrawableInfo& info) { td->fDrawContext = GrVkSecondaryCBDrawContext::Make(td->fDContext, bufferInfo, info, nullptr); if (!td->fDrawContext) { return; } SkCanvas* canvas = td->fDrawContext->getCanvas(); canvas->clipRect(SkRect::Make(clipBounds)); canvas->setMatrix(matrix); SkIRect rect = SkIRect::MakeXYWH(td->fWidth/2, 0, td->fWidth/4, td->fHeight); SkPaint paint; paint.setColor(SK_ColorRED); canvas->drawIRect(rect, paint); // Draw to an offscreen target so that we end up with a mix of "real" secondary command // buffers and the imported secondary command buffer. sk_sp<SkSurface> surf = SkSurface::MakeRenderTarget(td->fDContext, SkBudgeted::kYes, bufferInfo); surf->getCanvas()->clear(SK_ColorRED); SkRect dstRect = SkRect::MakeXYWH(3*td->fWidth/4, 0, td->fWidth/4, td->fHeight); SkRect srcRect = SkRect::MakeIWH(td->fWidth/4, td->fHeight); canvas->drawImageRect(surf->makeImageSnapshot(), srcRect, dstRect, SkSamplingOptions(), &paint, SkCanvas::kStrict_SrcRectConstraint); td->fDrawContext->flush(); } // Helper function to test waiting for the imported secondary command buffer to be submitted on // its original context and then cleaning up the GrVkSecondaryCBDrawContext from this context. static void ImportSubmitted(TestDrawable* td) { // Typical use case here would be to create a fence that we submit to the gpu and then wait // on before releasing the GrVkSecondaryCBDrawContext resources. To simulate that for this // test (and since we are running single threaded anyways), we will just force a sync of // the gpu and cpu here. td->fDContext->submit(true); td->fDrawContext->releaseResources(); // We release the context here manually to test that we waited long enough before // releasing the GrVkSecondaryCBDrawContext. This simulates when a client is able to delete // the context it used to imported the secondary command buffer. If we had released the // context's resources earlier (before waiting on the gpu above), we would get vulkan // validation layer errors saying we freed some vulkan objects while they were still in use // on the GPU. td->fDContext->releaseResourcesAndAbandonContext(); } std::unique_ptr<GpuDrawHandler> onSnapGpuDrawHandler(GrBackendApi backendApi, const SkMatrix& matrix, const SkIRect& clipBounds, const SkImageInfo& bufferInfo) override { if (backendApi != GrBackendApi::kVulkan) { return nullptr; } std::unique_ptr<GpuDrawHandler> draw; if (fDContext) { draw = std::make_unique<DrawHandlerImport>(this, ImportDraw, ImportSubmitted, matrix, clipBounds, bufferInfo); } else { draw = std::make_unique<DrawHandlerBasic>(fInterface, fWidth, fHeight); } return draw; } SkRect onGetBounds() override { return SkRect::MakeLTRB(fWidth / 2, 0, fWidth, fHeight); } void onDraw(SkCanvas*) override { SkASSERT(false); } private: const GrVkInterface* fInterface; GrDirectContext* fDContext; sk_sp<GrVkSecondaryCBDrawContext> fDrawContext; int32_t fWidth; int32_t fHeight; using INHERITED = SkDrawable; }; void draw_drawable_test(skiatest::Reporter* reporter, GrDirectContext* dContext, GrDirectContext* childDContext) { GrVkGpu* gpu = static_cast<GrVkGpu*>(dContext->priv().getGpu()); const SkImageInfo ii = SkImageInfo::Make(DEV_W, DEV_H, kRGBA_8888_SkColorType, kPremul_SkAlphaType); sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(dContext, SkBudgeted::kNo, ii, 0, kTopLeft_GrSurfaceOrigin, nullptr)); SkCanvas* canvas = surface->getCanvas(); canvas->clear(SK_ColorBLUE); sk_sp<TestDrawable> drawable(new TestDrawable(gpu->vkInterface(), childDContext, DEV_W, DEV_H)); canvas->drawDrawable(drawable.get()); SkPaint paint; paint.setColor(SK_ColorGREEN); SkIRect rect = SkIRect::MakeLTRB(0, DEV_H/2, DEV_W, DEV_H); canvas->drawIRect(rect, paint); // read pixels SkBitmap bitmap; bitmap.allocPixels(ii); canvas->readPixels(bitmap, 0, 0); const uint32_t* canvasPixels = static_cast<const uint32_t*>(bitmap.getPixels()); bool failureFound = false; SkPMColor expectedPixel; for (int cy = 0; cy < DEV_H && !failureFound; ++cy) { for (int cx = 0; cx < DEV_W && !failureFound; ++cx) { SkPMColor canvasPixel = canvasPixels[cy * DEV_W + cx]; if (cy < DEV_H / 2) { if (cx < DEV_W / 2) { expectedPixel = 0xFFFF0000; // Blue } else { expectedPixel = 0xFF0000FF; // Red } } else { expectedPixel = 0xFF00FF00; // Green } if (expectedPixel != canvasPixel) { failureFound = true; ERRORF(reporter, "Wrong color at %d, %d. Got 0x%08x when we expected 0x%08x", cx, cy, canvasPixel, expectedPixel); } } } } DEF_GPUTEST_FOR_VULKAN_CONTEXT(VkDrawableTest, reporter, ctxInfo) { draw_drawable_test(reporter, ctxInfo.directContext(), nullptr); } DEF_GPUTEST(VkDrawableImportTest, reporter, options) { for (int typeInt = 0; typeInt < sk_gpu_test::GrContextFactory::kContextTypeCnt; ++typeInt) { sk_gpu_test::GrContextFactory::ContextType contextType = (sk_gpu_test::GrContextFactory::ContextType) typeInt; if (contextType != sk_gpu_test::GrContextFactory::kVulkan_ContextType) { continue; } sk_gpu_test::GrContextFactory factory(options); sk_gpu_test::ContextInfo ctxInfo = factory.getContextInfo(contextType); skiatest::ReporterContext ctx( reporter, SkString(sk_gpu_test::GrContextFactory::ContextTypeName(contextType))); if (ctxInfo.directContext()) { sk_gpu_test::ContextInfo child = factory.getSharedContextInfo(ctxInfo.directContext(), 0); if (!child.directContext()) { continue; } draw_drawable_test(reporter, ctxInfo.directContext(), child.directContext()); } } } #endif
40.373333
100
0.602708
TheRakeshPurohit
ce65e32aa41d9c434f22cfb554a8cdbade9f8030
80
cxx
C++
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.4.2-.cxx
nalinimsingh/ITK_4D
95a2eacaeaffe572889832ef0894239f89e3f303
[ "Apache-2.0" ]
3
2018-10-01T20:46:17.000Z
2019-12-17T19:39:50.000Z
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.4.2-.cxx
nalinimsingh/ITK_4D
95a2eacaeaffe572889832ef0894239f89e3f303
[ "Apache-2.0" ]
null
null
null
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.4.2-.cxx
nalinimsingh/ITK_4D
95a2eacaeaffe572889832ef0894239f89e3f303
[ "Apache-2.0" ]
4
2018-05-17T16:34:54.000Z
2020-09-24T02:12:40.000Z
#include <vnl/vnl_matrix_fixed.hxx> VNL_MATRIX_FIXED_INSTANTIATE(double,4,2);
26.666667
42
0.8125
nalinimsingh
ce66764feb31359d1c044557f0c3d3c5692510af
1,868
cpp
C++
logdevice/common/protocol/GET_TRIM_POINT_Message.cpp
mickvav/LogDevice
24a8b6abe4576418eceb72974083aa22d7844705
[ "BSD-3-Clause" ]
1
2021-05-19T23:01:58.000Z
2021-05-19T23:01:58.000Z
logdevice/common/protocol/GET_TRIM_POINT_Message.cpp
mickvav/LogDevice
24a8b6abe4576418eceb72974083aa22d7844705
[ "BSD-3-Clause" ]
null
null
null
logdevice/common/protocol/GET_TRIM_POINT_Message.cpp
mickvav/LogDevice
24a8b6abe4576418eceb72974083aa22d7844705
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "GET_TRIM_POINT_Message.h" #include "logdevice/common/GetTrimPointRequest.h" #include "logdevice/common/Sender.h" #include "logdevice/common/Worker.h" namespace facebook { namespace logdevice { GET_TRIM_POINT_Message::GET_TRIM_POINT_Message( const GET_TRIM_POINT_Header& header) : Message(MessageType::GET_TRIM_POINT, TrafficClass::READ_BACKLOG), header_(header) {} void GET_TRIM_POINT_Message::serialize(ProtocolWriter& writer) const { writer.write(header_); } MessageReadResult GET_TRIM_POINT_Message::deserialize(ProtocolReader& reader) { GET_TRIM_POINT_Header hdr; // Defaults for old protocols hdr.shard = -1; reader.read(&hdr); return reader.result([&] { return new GET_TRIM_POINT_Message(hdr); }); } Message::Disposition GET_TRIM_POINT_Message::onReceived(const Address& /*from*/) { // Receipt handler lives in server/GET_TRIM_POINT_onReceived.cpp; this should // never get called. std::abort(); } void GET_TRIM_POINT_Message::onSent(Status status, const Address& to) const { ld_debug(": message=GET_TRIM_POINT st=%s to=%s", error_name(status), Sender::describeConnection(to).c_str()); // Inform the GetTrimPointRequest of the outcome of sending the message auto& rqmap = Worker::onThisThread()->runningGetTrimPoint().map; auto it = rqmap.find(header_.log_id); if (it != rqmap.end()) { ShardID shard(to.id_.node_.index(), header_.shard); it->second->onMessageSent(shard, status); } } uint16_t GET_TRIM_POINT_Message::getMinProtocolVersion() const { return Compatibility::GET_TRIM_POINT_SUPPORT; } }} // namespace facebook::logdevice
31.661017
79
0.74197
mickvav
ce676e2ad4f774a74fe5fd1fb58f783fa7cb2b82
1,017
cpp
C++
UVA/Queue/10935_ThrowingCardsAway.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
UVA/Queue/10935_ThrowingCardsAway.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
UVA/Queue/10935_ThrowingCardsAway.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdlib> #include <cstring> #include <vector> #include <algorithm> #include <sstream> #include <set> #include <climits> #include <cstdio> #include <string> #include <map> #include <unordered_map> #include <deque> #ifndef ONLINE_JUDGE #define getchar_unlocked getchar #define putchar_unlocked putchar #endif using namespace std; inline void scanint(int &); inline void scanstring(char *); inline void scanline(char *); int main() { #ifndef ONLINE_JUDGE freopen("1.txt", "r", stdin); freopen("2.txt", "w", stdout); #endif int n; deque<int> d; while (scanf("%d", &n), n != 0) { d.clear(); for (int i = 1; i <= n; i++) d.push_back(i); printf("Discarded cards:"); while (d.size() >= 2) { if (d.size() == n) printf(" %d", d.front()); else if (d.size() > 1) printf(", %d", d.front()); d.pop_front(); d.push_back(d.front()); d.pop_front(); } printf("\n"); printf("Remaining card: %d\n", d.front()); } }
21.638298
45
0.59882
shiva92
ce6800262e50e1c2acf2db9566d2d74746c3164d
37,339
cpp
C++
src/basis.cpp
twesterhout/lattice-symmetries
b6793fa9eeae6b9cbaa3844beec14ffe5ccfad45
[ "BSD-3-Clause" ]
12
2021-01-13T16:50:05.000Z
2021-12-16T09:04:23.000Z
src/basis.cpp
twesterhout/lattice-symmetries
b6793fa9eeae6b9cbaa3844beec14ffe5ccfad45
[ "BSD-3-Clause" ]
3
2021-07-26T09:54:31.000Z
2021-08-20T12:27:03.000Z
src/basis.cpp
twesterhout/lattice-symmetries
b6793fa9eeae6b9cbaa3844beec14ffe5ccfad45
[ "BSD-3-Clause" ]
2
2021-08-16T16:53:57.000Z
2021-12-11T04:22:13.000Z
// Copyright (c) 2019-2020, Tom Westerhout // 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 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 "basis.hpp" #include "cache.hpp" #include "cpu/state_info.hpp" #include "halide/kernels.hpp" #include <algorithm> #include <cstdlib> #include <cstring> #include <functional> #if defined(__APPLE__) # include <libkern/OSByteOrder.h> # include <machine/endian.h> # define htobe16(x) OSSwapHostToBigInt16(x) # define htole16(x) OSSwapHostToLittleInt16(x) # define be16toh(x) OSSwapBigToHostInt16(x) # define le16toh(x) OSSwapLittleToHostInt16(x) # define htobe32(x) OSSwapHostToBigInt32(x) # define htole32(x) OSSwapHostToLittleInt32(x) # define be32toh(x) OSSwapBigToHostInt32(x) # define le32toh(x) OSSwapLittleToHostInt32(x) # define htobe64(x) OSSwapHostToBigInt64(x) # define htole64(x) OSSwapHostToLittleInt64(x) # define be64toh(x) OSSwapBigToHostInt64(x) # define le64toh(x) OSSwapLittleToHostInt64(x) #else # include <endian.h> #endif namespace lattice_symmetries { namespace { template <class T> auto extract(tcb::span<ls_symmetry const> symmetries) -> std::vector<T> { auto r = std::vector<T>{}; r.reserve(symmetries.size()); std::transform(std::begin(symmetries), std::end(symmetries), std::back_inserter(r), [](auto const& x) { return std::get<T>(x.payload); }); return r; } auto split_into_batches(tcb::span<small_symmetry_t const> symmetries) // -> std::tuple<std::vector<batched_small_symmetry_t>, std::vector<small_symmetry_t>> -> std::tuple<std::vector<batched_small_symmetry_t>, std::optional<batched_small_symmetry_t>, unsigned> { constexpr auto batch_size = batched_small_symmetry_t::batch_size; auto offset = 0UL; std::vector<batched_small_symmetry_t> batched; for (; offset + batch_size <= symmetries.size(); offset += batch_size) { batched.emplace_back(symmetries.subspan(offset, batch_size)); } std::vector<small_symmetry_t> other; other.reserve(batch_size); // Make sure other is never reallocated std::copy(std::next(std::begin(symmetries), static_cast<ptrdiff_t>(offset)), std::end(symmetries), std::back_inserter(other)); if (other.empty()) { return std::make_tuple(std::move(batched), std::nullopt, 0U); } auto const count = other.size(); for (auto const& s = other.back(); other.size() != batch_size;) { other.push_back(s); } return std::make_tuple(std::move(batched), std::optional{batched_small_symmetry_t{other}}, count); } } // namespace small_basis_t::small_basis_t(ls_group const& group) : cache{nullptr} { auto symmetries = extract<small_symmetry_t>( tcb::span{ls_group_get_symmetries(&group), ls_get_group_size(&group)}); std::tie(batched_symmetries, other_symmetries, number_other_symmetries) = split_into_batches(symmetries); } big_basis_t::big_basis_t(ls_group const& group) : symmetries{extract<big_symmetry_t>( tcb::span{ls_group_get_symmetries(&group), ls_get_group_size(&group)})} {} } // namespace lattice_symmetries using namespace lattice_symmetries; struct ls_spin_basis { basis_base_t header; std::variant<small_basis_t, big_basis_t> payload; template <class T> explicit ls_spin_basis(std::in_place_type_t<T> tag, ls_group const& group, unsigned const number_spins, std::optional<unsigned> const hamming_weight, int const spin_inversion) : header{{}, number_spins, hamming_weight, spin_inversion, ls_get_group_size(&group) > 1 || spin_inversion != 0} , payload{tag, group} {} ls_spin_basis(ls_spin_basis const&) = delete; ls_spin_basis(ls_spin_basis&&) = delete; auto operator=(ls_spin_basis const&) -> ls_spin_basis& = delete; auto operator=(ls_spin_basis&&) -> ls_spin_basis& = delete; ~ls_spin_basis() { LATTICE_SYMMETRIES_CHECK(load(header.refcount) == 0, "there remain references to object"); } }; struct ls_states { tcb::span<uint64_t const> payload; ls_spin_basis* parent; ls_states(tcb::span<uint64_t const> states, ls_spin_basis const* owner) : payload{states}, parent{ls_copy_spin_basis(owner)} {} ls_states(ls_states const&) = delete; ls_states(ls_states&&) = delete; auto operator=(ls_states const&) -> ls_states& = delete; auto operator=(ls_states&&) -> ls_states& = delete; ~ls_states() { ls_destroy_spin_basis(parent); } }; namespace lattice_symmetries { template <class T> auto alloc_aligned_array(size_t alignment, size_t count) noexcept -> std::unique_ptr<T, free_deleter_fn_t<false>> { auto* ptr = count > 0 ? ::aligned_alloc(alignment, count * sizeof(T)) : nullptr; return std::unique_ptr<T, free_deleter_fn_t<false>>{static_cast<T*>(ptr)}; } template <class T, class... Args> auto alloc_aligned(Args&&... args) noexcept -> std::unique_ptr<T, free_deleter_fn_t<true>> { static_assert(std::is_nothrow_constructible_v<T, Args&&...>); constexpr auto alignment = 64U; auto* ptr = ::aligned_alloc(alignment, sizeof(T)); new (ptr) T{std::forward<Args>(args)...}; return std::unique_ptr<T, free_deleter_fn_t<true>>{static_cast<T*>(ptr)}; } } // namespace lattice_symmetries ls_flat_group::ls_flat_group(std::array<unsigned, 3> _shape) noexcept : shape{_shape} , masks{lattice_symmetries::alloc_aligned_array<uint64_t>(alignment, shape[0] * shape[1] * shape[2])} , shifts{lattice_symmetries::alloc_aligned_array<uint64_t>(alignment, shape[0])} , eigenvalues_real{lattice_symmetries::alloc_aligned_array<double>(alignment, shape[1])} , eigenvalues_imag{lattice_symmetries::alloc_aligned_array<double>(alignment, shape[1])} , sectors{lattice_symmetries::alloc_aligned_array<unsigned>(alignment, shape[1])} , periodicities{lattice_symmetries::alloc_aligned_array<unsigned>(alignment, shape[1])} {} auto ls_flat_group::has_allocation_succeeded() const noexcept -> bool { if (shape[0] * shape[1] * shape[2] != 0 && masks == nullptr) { LATTICE_SYMMETRIES_LOG_DEBUG("Failed to allocate 'masks' array of shape [%u, %u, %u]\n", shape[0], shape[1], shape[2]); return false; } if (shape[0] != 0 && shifts == nullptr) { LATTICE_SYMMETRIES_LOG_DEBUG("Failed to allocate 'shifts' array of shape [%u]\n", shape[0]); return false; } if (shape[1] != 0 && (eigenvalues_real == nullptr || eigenvalues_imag == nullptr || sectors == nullptr || periodicities == nullptr)) { LATTICE_SYMMETRIES_LOG_DEBUG( "Failed to allocate 'eigenvalues_real', 'eigenvalues_imag', 'sectors' or " "'periodicities' array of shape [%u]\n", shape[1]); return false; } return true; } ls_flat_spin_basis::ls_flat_spin_basis(std::array<unsigned, 3> shape, private_tag_type /*tag*/) noexcept : refcount{} , number_spins{} , hamming_weight{} , spin_inversion{} , group{shape} , state_info_kernel{} , is_representative_kernel{} { LATTICE_SYMMETRIES_LOG_DEBUG("Constructed ls_flat_spin_basis with masks shape [%u, %u, %u]\n", shape[0], shape[1], shape[2]); } auto ls_flat_spin_basis::allocate(std::array<unsigned, 3> shape) noexcept -> unique_ptr_type { auto p = lattice_symmetries::alloc_aligned<ls_flat_spin_basis>(shape, private_tag_type{}); if (p == nullptr) { return {}; } if (!p->group.has_allocation_succeeded()) { return {}; } return p; } namespace lattice_symmetries { namespace { auto masks_shape(ls_spin_basis const& basis) noexcept -> std::array<unsigned, 3> { struct get_shape_fn_t { auto operator()(small_basis_t const& b) const noexcept { auto network_depth = 0U; if (!b.batched_symmetries.empty()) { network_depth = b.batched_symmetries.front().network.depth; } else if (b.other_symmetries.has_value()) { network_depth = b.other_symmetries->network.depth; } auto number_permutations = static_cast<unsigned>( b.batched_symmetries.size() * batched_small_symmetry_t::batch_size + b.number_other_symmetries); auto mask_width = 1U; return std::array<unsigned, 3>{{network_depth, number_permutations, mask_width}}; } auto operator()(big_basis_t const& b) const noexcept { auto network_depth = 0U; if (!b.symmetries.empty()) { network_depth = b.symmetries.front().network.depth; } auto number_permutations = static_cast<unsigned>(b.symmetries.size()); auto mask_width = 8U; return std::array<unsigned, 3>{{network_depth, number_permutations, mask_width}}; } }; return std::visit(get_shape_fn_t{}, basis.payload); } } // namespace struct init_flat_group_contents_fn_t { ls_flat_group* g; auto operator()(small_basis_t const& b) const noexcept -> void { // Initializing masks auto offset = ptrdiff_t{0}; for (auto depth = 0U; depth < g->shape[0]; ++depth) { for (auto const& s : b.batched_symmetries) { for (auto i = 0U; i < batched_small_symmetry_t::batch_size; ++i) { g->masks.get()[offset] = s.network.masks[depth][i]; ++offset; } } for (auto i = 0U; i < b.number_other_symmetries; ++i) { g->masks.get()[offset] = b.other_symmetries->network.masks[depth][i]; ++offset; } } // Initializing shifts if (g->shifts != nullptr) { auto const& s = !b.batched_symmetries.empty() ? b.batched_symmetries.front() : *b.other_symmetries; for (auto depth = 0U; depth < g->shape[0]; ++depth) { g->shifts.get()[depth] = s.network.deltas[depth]; } } // Initializing eigenvalues, sectors, and periodicities offset = ptrdiff_t{0}; for (auto const& s : b.batched_symmetries) { for (auto i = 0U; i < batched_small_symmetry_t::batch_size; ++i) { g->eigenvalues_real.get()[offset] = s.eigenvalues_real[i]; g->eigenvalues_imag.get()[offset] = s.eigenvalues_imag[i]; g->sectors.get()[offset] = s.sectors[i]; g->periodicities.get()[offset] = s.periodicities[i]; ++offset; } } for (auto i = 0U; i < b.number_other_symmetries; ++i) { auto const& s = *b.other_symmetries; g->eigenvalues_real.get()[offset] = s.eigenvalues_real[i]; g->eigenvalues_imag.get()[offset] = s.eigenvalues_imag[i]; g->sectors.get()[offset] = s.sectors[i]; g->periodicities.get()[offset] = s.periodicities[i]; ++offset; } } auto operator()(big_basis_t const& b) const noexcept -> void { // Initializing masks auto offset = ptrdiff_t{0}; for (auto depth = 0U; depth < g->shape[0]; ++depth) { for (auto const& s : b.symmetries) { for (auto i = 0; i < 8; ++i) { g->masks.get()[offset] = s.network.masks[depth].words[i]; ++offset; } } } // Initializing shifts if (g->shifts != nullptr) { auto const& s = b.symmetries.front(); for (auto depth = 0U; depth < g->shape[0]; ++depth) { g->shifts.get()[depth] = s.network.deltas[depth]; } } // Initializing eigenvalues, sectors, and periodicities offset = ptrdiff_t{0}; for (auto const& s : b.symmetries) { for (auto i = 0U; i < batched_small_symmetry_t::batch_size; ++i) { g->eigenvalues_real.get()[offset] = s.eigenvalue.real(); g->eigenvalues_imag.get()[offset] = s.eigenvalue.imag(); g->sectors.get()[offset] = s.sector; g->periodicities.get()[offset] = s.periodicity; ++offset; } } } }; namespace { auto init_flat_group_contents(ls_flat_group* group, ls_spin_basis const& basis) noexcept -> void { std::visit(init_flat_group_contents_fn_t{group}, basis.payload); } } // namespace } // namespace lattice_symmetries extern "C" LATTICE_SYMMETRIES_EXPORT void ls_destroy_flat_spin_basis(ls_flat_spin_basis* ptr) { ls_flat_spin_basis::unique_ptr_type::deleter_type{}(ptr); } extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_convert_to_flat_spin_basis(ls_flat_spin_basis** ptr, ls_spin_basis const* basis) { using namespace lattice_symmetries; constexpr auto alignment = 64U; auto const shape = masks_shape(*basis); auto flat_basis_ptr = ls_flat_spin_basis::allocate(shape); if (flat_basis_ptr == nullptr) { return LS_OUT_OF_MEMORY; } flat_basis_ptr->number_spins = ls_get_number_spins(basis); flat_basis_ptr->hamming_weight = ls_get_hamming_weight(basis); flat_basis_ptr->spin_inversion = ls_get_spin_inversion(basis); init_flat_group_contents(&flat_basis_ptr->group, *basis); flat_basis_ptr->state_info_kernel = make_state_info_kernel(*flat_basis_ptr); flat_basis_ptr->is_representative_kernel = make_is_representative_kernel(*flat_basis_ptr); *ptr = flat_basis_ptr.release(); return LS_SUCCESS; } extern "C" LATTICE_SYMMETRIES_EXPORT uint64_t ls_get_buffer_size_for_flat_spin_basis(ls_flat_spin_basis const* basis) { auto const& g = basis->group; return sizeof(unsigned) // number_spins + sizeof(int) // hamming_weight + sizeof(int) // spin_inversion + 3 * sizeof(unsigned) // shape + g.shape[0] * g.shape[1] * g.shape[2] * sizeof(uint64_t) // masks + g.shape[0] * sizeof(uint64_t) // shifts + g.shape[1] * sizeof(double) // eigenvalues_real + g.shape[1] * sizeof(double) // eigenvalues_imag + g.shape[1] * sizeof(unsigned) // sectors + g.shape[1] * sizeof(unsigned); // periodicities } namespace lattice_symmetries { namespace { inline auto write_primitive(char* buffer, uint64_t x) noexcept -> char* { x = htole64(x); std::memcpy(buffer, &x, sizeof(x)); return buffer + sizeof(x); } inline auto write_primitive(char* buffer, int64_t x) noexcept -> char* { return write_primitive(buffer, static_cast<uint64_t>(x)); } inline auto write_primitive(char* buffer, uint32_t x) noexcept -> char* { x = htole32(x); std::memcpy(buffer, &x, sizeof(x)); return buffer + sizeof(x); } inline auto write_primitive(char* buffer, int32_t x) noexcept -> char* { return write_primitive(buffer, static_cast<uint32_t>(x)); } inline auto write_primitive(char* buffer, float x) noexcept -> char* { static_assert(sizeof(float) == sizeof(uint32_t)); uint32_t y; std::memcpy(&y, &x, sizeof(x)); return write_primitive(buffer, y); } inline auto write_primitive(char* buffer, double x) noexcept -> char* { static_assert(sizeof(double) == sizeof(uint64_t)); uint64_t y; std::memcpy(&y, &x, sizeof(x)); return write_primitive(buffer, y); } template <class T> auto write_primitive_array(char* buffer, T const* x, uint64_t const size) noexcept -> char* { for (auto i = uint64_t{0}; i < size; ++i) { buffer = write_primitive(buffer, x[i]); } return buffer; } inline auto read_primitive(uint64_t& x, char const* buffer) noexcept -> char const* { std::memcpy(&x, buffer, sizeof(x)); x = le64toh(x); return buffer + sizeof(x); } inline auto read_primitive(int64_t& x, char const* buffer) noexcept -> char const* { uint64_t y; buffer = read_primitive(y, buffer); x = static_cast<int64_t>(y); return buffer; } inline auto read_primitive(uint32_t& x, char const* buffer) noexcept -> char const* { std::memcpy(&x, buffer, sizeof(x)); x = le32toh(x); return buffer + sizeof(x); } inline auto read_primitive(int32_t& x, char const* buffer) noexcept -> char const* { uint32_t y; buffer = read_primitive(y, buffer); x = static_cast<int32_t>(y); return buffer; } inline auto read_primitive(float& x, char const* buffer) noexcept -> char const* { static_assert(sizeof(float) == sizeof(uint32_t)); uint32_t y; buffer = read_primitive(y, buffer); std::memcpy(&x, &y, sizeof(x)); return buffer; } inline auto read_primitive(double& x, char const* buffer) noexcept -> char const* { static_assert(sizeof(double) == sizeof(uint64_t)); uint64_t y; buffer = read_primitive(y, buffer); std::memcpy(&x, &y, sizeof(x)); return buffer; } template <class T> auto read_primitive_array(T* x, uint64_t const size, char const* buffer) noexcept -> char const* { for (auto i = uint64_t{0}; i < size; ++i) { buffer = read_primitive(x[i], buffer); } return buffer; } } // namespace } // namespace lattice_symmetries extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_serialize_flat_spin_basis(ls_flat_spin_basis const* basis, char* buffer, uint64_t size) { using namespace lattice_symmetries; auto const required_buffer_size = ls_get_buffer_size_for_flat_spin_basis(basis); auto* const original_buffer = buffer; if (size < required_buffer_size) { return LS_SYSTEM_ERROR; } buffer = write_primitive(buffer, basis->number_spins); buffer = write_primitive(buffer, basis->hamming_weight); buffer = write_primitive(buffer, basis->spin_inversion); auto const& g = basis->group; buffer = write_primitive_array(buffer, g.shape.data(), std::size(g.shape)); buffer = write_primitive_array(buffer, g.masks.get(), g.shape[0] * g.shape[1] * g.shape[2]); buffer = write_primitive_array(buffer, g.shifts.get(), g.shape[0]); buffer = write_primitive_array(buffer, g.eigenvalues_real.get(), g.shape[1]); buffer = write_primitive_array(buffer, g.eigenvalues_imag.get(), g.shape[1]); buffer = write_primitive_array(buffer, g.sectors.get(), g.shape[1]); buffer = write_primitive_array(buffer, g.periodicities.get(), g.shape[1]); LATTICE_SYMMETRIES_CHECK(buffer - original_buffer == static_cast<ptrdiff_t>(required_buffer_size), "buffer overflow"); return LS_SUCCESS; } extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_deserialize_flat_spin_basis(ls_flat_spin_basis** ptr, char const* buffer, uint64_t size) { using namespace lattice_symmetries; constexpr auto alignment = 64U; if (size < sizeof(ls_flat_spin_basis::number_spins) + sizeof(ls_flat_spin_basis::hamming_weight) + sizeof(ls_flat_spin_basis::spin_inversion) + sizeof(ls_flat_group::shape)) { return LS_SYSTEM_ERROR; } auto const* const original_buffer = buffer; decltype(ls_flat_spin_basis::number_spins) number_spins; decltype(ls_flat_spin_basis::hamming_weight) hamming_weight; decltype(ls_flat_spin_basis::spin_inversion) spin_inversion; decltype(ls_flat_group::shape) shape; buffer = read_primitive(number_spins, buffer); buffer = read_primitive(hamming_weight, buffer); buffer = read_primitive(spin_inversion, buffer); buffer = read_primitive_array(shape.data(), shape.size(), buffer); auto basis = ls_flat_spin_basis::allocate(shape); if (basis == nullptr) { return LS_OUT_OF_MEMORY; } auto const required_buffer_size = ls_get_buffer_size_for_flat_spin_basis(basis.get()); if (size < required_buffer_size) { return LS_SYSTEM_ERROR; } basis->number_spins = number_spins; basis->hamming_weight = hamming_weight; basis->spin_inversion = spin_inversion; auto& g = basis->group; buffer = read_primitive_array(g.masks.get(), g.shape[0] * g.shape[1] * g.shape[2], buffer); buffer = read_primitive_array(g.shifts.get(), g.shape[0], buffer); buffer = read_primitive_array(g.eigenvalues_real.get(), g.shape[1], buffer); buffer = read_primitive_array(g.eigenvalues_imag.get(), g.shape[1], buffer); buffer = read_primitive_array(g.sectors.get(), g.shape[1], buffer); buffer = read_primitive_array(g.periodicities.get(), g.shape[1], buffer); LATTICE_SYMMETRIES_CHECK(buffer - original_buffer == static_cast<ptrdiff_t>(required_buffer_size), "buffer overflow"); basis->state_info_kernel = make_state_info_kernel(*basis); basis->is_representative_kernel = make_is_representative_kernel(*basis); *ptr = basis.release(); return LS_SUCCESS; } extern "C" LATTICE_SYMMETRIES_EXPORT unsigned ls_flat_spin_basis_number_spins(ls_flat_spin_basis const* basis) { return basis->number_spins; } extern "C" LATTICE_SYMMETRIES_EXPORT int ls_flat_spin_basis_hamming_weight(ls_flat_spin_basis const* basis) { return basis->hamming_weight; } extern "C" LATTICE_SYMMETRIES_EXPORT int ls_flat_spin_basis_spin_inversion(ls_flat_spin_basis const* basis) { return basis->spin_inversion; } extern "C" LATTICE_SYMMETRIES_EXPORT void ls_flat_spin_basis_state_info(ls_flat_spin_basis const* basis, uint64_t count, void const* spin, void* repr, LATTICE_SYMMETRIES_COMPLEX128* character, double* norm) { LATTICE_SYMMETRIES_CHECK(static_cast<bool>(basis->state_info_kernel), "state_info_kernel not yet initialized"); basis->state_info_kernel(count, spin, repr, character, norm); } extern "C" LATTICE_SYMMETRIES_EXPORT void ls_flat_spin_basis_is_representative(ls_flat_spin_basis const* basis, uint64_t count, void const* spin, uint8_t* is_repr, double* norm) { LATTICE_SYMMETRIES_CHECK(static_cast<bool>(basis->is_representative_kernel), "is_representative_kernel not yet initialized"); basis->is_representative_kernel(count, spin, is_repr, norm); } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_create_spin_basis(ls_spin_basis** ptr, ls_group const* group, unsigned const number_spins, int const hamming_weight, int const spin_inversion) { // NOLINTNEXTLINE: 512 is the max supported system size (i.e. number of bits in ls_bits512) if (number_spins == 0 || number_spins > 512) { return LS_INVALID_NUMBER_SPINS; } if (auto const n = ls_group_get_number_spins(group); n != -1 && number_spins != static_cast<unsigned>(n)) { return LS_INVALID_NUMBER_SPINS; } if (!(hamming_weight == -1 || (0 <= hamming_weight && hamming_weight <= static_cast<int>(number_spins)))) { return LS_INVALID_HAMMING_WEIGHT; } if (spin_inversion != -1 && spin_inversion != 0 && spin_inversion != 1) { return LS_INVALID_SPIN_INVERSION; } // It's not possible to enforce spin inversion if number of spins up is not exactly // number_spins / 2 if (spin_inversion != 0 && hamming_weight != -1 && 2 * hamming_weight != static_cast<int>(number_spins)) { return LS_INVALID_SPIN_INVERSION; } auto const using_trivial_group = ls_get_group_size(group) == 0 && spin_inversion != 0; ls_group* trivial_group = nullptr; if (using_trivial_group) { auto const status = ls_create_trivial_group(&trivial_group, number_spins); LATTICE_SYMMETRIES_CHECK(status == LS_SUCCESS, "failed to create trivial group"); } auto const& group_ref = using_trivial_group ? *static_cast<ls_group const*>(trivial_group) : *group; auto const need_big = number_spins > 64; // NOLINT: 64 is number of bits in uint64_t auto const _hamming_weight = hamming_weight == -1 ? std::nullopt : std::optional<unsigned>{hamming_weight}; auto p = need_big ? std::make_unique<ls_spin_basis>(std::in_place_type_t<big_basis_t>{}, group_ref, number_spins, _hamming_weight, spin_inversion) : std::make_unique<ls_spin_basis>(std::in_place_type_t<small_basis_t>{}, group_ref, number_spins, _hamming_weight, spin_inversion); if (using_trivial_group) { ls_destroy_group(trivial_group); } increment(p->header.refcount); *ptr = p.release(); return LS_SUCCESS; } extern "C" LATTICE_SYMMETRIES_EXPORT ls_spin_basis* ls_copy_spin_basis(ls_spin_basis const* basis) { LATTICE_SYMMETRIES_ASSERT(load(basis->header.refcount) > 0, "refcount cannot be increased from zero"); increment(basis->header.refcount); // NOLINTNEXTLINE: We really do want const_cast here since the only non-const operation on // NOLINTNEXTLINE: ls_spin_basis is ls_build which may be called from on any instance return const_cast<ls_spin_basis*>(basis); } extern "C" LATTICE_SYMMETRIES_EXPORT void ls_destroy_spin_basis(ls_spin_basis* basis) { if (decrement(basis->header.refcount) == 0) { LATTICE_SYMMETRIES_LOG_DEBUG("Destroying basis %p\n", static_cast<void*>(basis)); std::default_delete<ls_spin_basis>{}(basis); } } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT unsigned ls_get_number_spins(ls_spin_basis const* basis) { return basis->header.number_spins; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT unsigned ls_get_number_bits(ls_spin_basis const* basis) { if (std::holds_alternative<big_basis_t>(basis->payload)) { return 512U; // NOLINT: number of bits in ls_bits512 } return 64U; // NOLINT: number of bits in uint64_t } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT int ls_get_hamming_weight(ls_spin_basis const* basis) { auto const& m = basis->header.hamming_weight; return m.has_value() ? static_cast<int>(*m) : -1; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT int ls_get_spin_inversion(ls_spin_basis const* basis) { return basis->header.spin_inversion; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT bool ls_has_symmetries(ls_spin_basis const* basis) { return basis->header.has_symmetries; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_get_number_states(ls_spin_basis const* basis, uint64_t* out) { auto const* p = std::get_if<small_basis_t>(&basis->payload); if (LATTICE_SYMMETRIES_UNLIKELY(p == nullptr)) { return LS_WRONG_BASIS_TYPE; } if (LATTICE_SYMMETRIES_UNLIKELY(p->cache == nullptr)) { return LS_CACHE_NOT_BUILT; } *out = p->cache->number_states(); return LS_SUCCESS; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_get_index(ls_spin_basis const* basis, uint64_t const bits, uint64_t* index) { auto const* p = std::get_if<small_basis_t>(&basis->payload); if (LATTICE_SYMMETRIES_UNLIKELY(p == nullptr)) { return LS_WRONG_BASIS_TYPE; } if (LATTICE_SYMMETRIES_UNLIKELY(p->cache == nullptr)) { return LS_CACHE_NOT_BUILT; } return p->cache->index(bits, index); } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_build(ls_spin_basis* basis) { auto* p = std::get_if<small_basis_t>(&basis->payload); if (p == nullptr) { return LS_WRONG_BASIS_TYPE; } if (p->cache == nullptr) { p->cache = std::make_unique<basis_cache_t>(basis->header, *p); } return LS_SUCCESS; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_build_unsafe(ls_spin_basis* basis, uint64_t const size, uint64_t const representatives[]) { auto* p = std::get_if<small_basis_t>(&basis->payload); if (p == nullptr) { return LS_WRONG_BASIS_TYPE; } if (p->cache == nullptr) { std::vector<uint64_t> rs{representatives, representatives + size}; p->cache = std::make_unique<basis_cache_t>(basis->header, *p, std::move(rs)); } return LS_SUCCESS; } namespace lattice_symmetries { namespace { struct get_state_info_visitor_t { basis_base_t const& header; ls_bits512 const* const bits; ls_bits512* const representative; std::complex<double>& character; double& norm; auto operator()(small_basis_t const& payload) const noexcept { get_state_info_64(header, payload, bits->words[0], representative->words[0], character, norm); } auto operator()(big_basis_t const& payload) const noexcept { get_state_info_512(header, payload, *bits, *representative, character, norm); } }; } // namespace } // namespace lattice_symmetries // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT void ls_get_state_info(ls_spin_basis const* basis, ls_bits512 const* bits, ls_bits512* representative, void* character, double* norm) { auto& ch = *reinterpret_cast<std::complex<double>*>(character); // NOLINT std::visit(get_state_info_visitor_t{basis->header, bits, representative, ch, *norm}, basis->payload); } extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_is_representative(ls_spin_basis const* basis, uint64_t const count, uint64_t const bits[], uint8_t out[]) { auto const* payload = std::get_if<small_basis_t>(&basis->payload); if (LATTICE_SYMMETRIES_UNLIKELY(payload == nullptr)) { return LS_WRONG_BASIS_TYPE; } for (auto i = uint64_t{0}; i < count; ++i) { out[i] = static_cast<uint8_t>(is_representative_64(basis->header, *payload, bits[i])); } return LS_SUCCESS; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_get_states(ls_states** ptr, ls_spin_basis const* basis) { auto const* small_basis = std::get_if<small_basis_t>(&basis->payload); if (LATTICE_SYMMETRIES_UNLIKELY(small_basis == nullptr)) { return LS_WRONG_BASIS_TYPE; } if (LATTICE_SYMMETRIES_UNLIKELY(small_basis->cache == nullptr)) { return LS_CACHE_NOT_BUILT; } auto const states = small_basis->cache->states(); auto p = std::make_unique<ls_states>(states, basis); *ptr = p.release(); return LS_SUCCESS; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT void ls_destroy_states(ls_states* states) { std::default_delete<ls_states>{}(states); } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT uint64_t const* ls_states_get_data(ls_states const* states) { return states->payload.data(); } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT uint64_t ls_states_get_size(ls_states const* states) { return states->payload.size(); } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_save_cache(ls_spin_basis const* basis, char const* filename) { auto const* small_basis = std::get_if<small_basis_t>(&basis->payload); if (small_basis == nullptr) { return LS_WRONG_BASIS_TYPE; } if (small_basis->cache == nullptr) { return LS_CACHE_NOT_BUILT; } auto const states = small_basis->cache->states(); auto const r = save_states(states, filename); if (!r) { if (r.error().category() == get_error_category()) { return static_cast<ls_error_code>(r.error().value()); } return LS_SYSTEM_ERROR; } return LS_SUCCESS; } // cppcheck-suppress unusedFunction extern "C" LATTICE_SYMMETRIES_EXPORT ls_error_code ls_load_cache(ls_spin_basis* basis, char const* filename) { auto* p = std::get_if<small_basis_t>(&basis->payload); if (p == nullptr) { return LS_WRONG_BASIS_TYPE; } // Cache already built if (p->cache != nullptr) { return LS_SUCCESS; } auto&& r = load_states(filename); if (!r) { if (r.error().category() == get_error_category()) { return static_cast<ls_error_code>(r.error().value()); } return LS_SYSTEM_ERROR; } p->cache = std::make_unique<basis_cache_t>(basis->header, *p, r.value()); return LS_SUCCESS; } namespace lattice_symmetries { auto is_real(ls_spin_basis const& basis) noexcept -> bool { struct visitor_fn_t { auto operator()(small_basis_t const& x) const noexcept -> bool { auto const batched = std::all_of(std::begin(x.batched_symmetries), std::end(x.batched_symmetries), [](auto const& s) { return is_real(s); }); auto const other = x.other_symmetries.has_value() ? is_real(*x.other_symmetries) : true; return batched && other; } auto operator()(big_basis_t const& x) const noexcept -> bool { return std::all_of(std::begin(x.symmetries), std::end(x.symmetries), [](auto const& s) { return is_real(s); }); } }; return std::visit(visitor_fn_t{}, basis.payload); } } // namespace lattice_symmetries
41.766219
100
0.626691
twesterhout
ce6accfbd1cb498f4cff888c284255dd88c5dc79
861
cpp
C++
p817_Linked_List_Components/p817.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p817_Linked_List_Components/p817.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p817_Linked_List_Components/p817.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include <stack> #include <queue> #include <map> #include <set> #include <string> #include <cassert> #include <stdlib.h> #include <fstream> #include <algorithm> #include <cmath> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: int numComponents(ListNode* head, vector<int>& G) { set<int> S(G.begin(), G.end()); bool flag = false; int ans = 0; while(head) { auto p = S.find(head->val); if(p!=S.end()) { if(!flag) { flag = true; ans++; } }else if(flag) flag = false; head = head->next; } return ans; } }; int main() { return 0; }
19.568182
55
0.509872
Song1996
ce6c2d5e483cd214d7d6bed149c755daca290b12
2,121
cpp
C++
src/util/string/string_util.cpp
luist18/feup-cal-proj
b7fbb8aaed63c705cd85125b3d3f88ae77b1416c
[ "MIT" ]
null
null
null
src/util/string/string_util.cpp
luist18/feup-cal-proj
b7fbb8aaed63c705cd85125b3d3f88ae77b1416c
[ "MIT" ]
null
null
null
src/util/string/string_util.cpp
luist18/feup-cal-proj
b7fbb8aaed63c705cd85125b3d3f88ae77b1416c
[ "MIT" ]
2
2020-05-05T11:19:34.000Z
2020-06-07T14:41:46.000Z
#include <chrono> #include <iomanip> #include <sstream> #include <random> #include <algorithm> #include "string_util.h" std::vector<std::string> string_util::split(std::string &string, char delimiter) { std::vector<std::string> res; size_t last = 0, next; while ((next = string.find(delimiter, last)) != std::string::npos) { res.push_back(string.substr(last, next - last)); last = next + 1; } res.push_back(string.substr(last)); return res; } std::string string_util::random_password(int length) { std::random_device rd; std::mt19937 mt(rd()); const char characters[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; std::stringstream password_stream; std::uniform_real_distribution<double> dist(0.0, (double) sizeof(characters) - .01); for (int i = 0; i < length; i++) { password_stream << characters[(int) dist(mt)]; } return password_stream.str(); } bool string_util::is_number(const std::string &string) { return !string.empty() && std::find_if(string.begin(), string.end(), [](char c) { return !std::isdigit(c); }) == string.end(); } std::string string_util::trim(const std::string &string) { auto it_b = string.begin(); for (; *it_b == ' '; it_b++); auto it_e = string.end() - 1; for (; *it_e == ' '; it_e--); int size = it_e + 1 - it_b; return string.substr(it_b - string.begin(), size < 0 ? 0 : size); } bool string_util::replace(std::string &str, const std::string &from, const std::string &to) { size_t start_pos = str.find(from); if (start_pos == std::string::npos) return false; str.replace(start_pos, from.length(), to); return true; } std::string string_util::toJSONObject(std::vector<std::pair<std::string, std::string>> values) { std::stringstream stream; stream << "{"; for (int i = 0; i < values.size(); ++i) { stream << values[i].first << ": " << values[i].second; if (i != values.size() - 1) stream << ", "; } stream << "}"; return stream.str(); }
27.907895
114
0.605375
luist18
ce6c476c21468f71f5f22ef7fdd37473b6f3b587
974
cpp
C++
of/OF47.cpp
4llenchan/dsa
314991a32a24578dbf48e82ddded95804c95aa10
[ "MIT" ]
null
null
null
of/OF47.cpp
4llenchan/dsa
314991a32a24578dbf48e82ddded95804c95aa10
[ "MIT" ]
null
null
null
of/OF47.cpp
4llenchan/dsa
314991a32a24578dbf48e82ddded95804c95aa10
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <algorithm> #include <unordered_map> #include <vector> #include "Common.h" using namespace std; class Solution { public: int maxValue(vector<vector<int>> &grid) { /* 利用原矩阵进行dp值的保存 */ int m = grid.size(), n = grid[0].size(); /* 初始化第一行 */ for (int j = 1; j < n; j++) { grid[0][j] += grid[0][j - 1]; } /* 初始化第一列 */ for (int i = 1; i < m; i++) { grid[i][0] += grid[i - 1][0]; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { grid[i][j] += max(grid[i][j - 1], grid[i - 1][j]); } } return grid[m - 1][n - 1]; } }; class OF47Tests : public ::testing::Test { protected: Solution solution; }; TEST_F(OF47Tests, normal) { vector<vector<int>> grid{ {1, 3, 1}, {1, 5, 1}, {4, 2, 1}}; EXPECT_EQ(solution.maxValue(grid), 12); }
22.136364
66
0.448665
4llenchan
ce6f10f5870da729f447dd824a9b70b4d440b162
9,199
cpp
C++
src/cc/triggers.cpp
wallnutkraken/komodo
536580bdeca6d3a9b719c5f8adc4ac1a9a1dcb57
[ "Unlicense" ]
1
2018-05-21T18:45:19.000Z
2018-05-21T18:45:19.000Z
src/cc/triggers.cpp
EqualiserCoinProject/komodo
1eb6f5db72ff0e9d0c3a6dd0a19172b889fd5bf2
[ "Unlicense" ]
null
null
null
src/cc/triggers.cpp
EqualiserCoinProject/komodo
1eb6f5db72ff0e9d0c3a6dd0a19172b889fd5bf2
[ "Unlicense" ]
null
null
null
/****************************************************************************** * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * * holder information and the developer policies on copyright and licensing. * * * * Unless otherwise agreed in a custom licensing agreement, no part of the * * SuperNET software, including this file may be copied, modified, propagated * * or distributed except according to the terms contained in the LICENSE file * * * * Removal or modification of this copyright notice is prohibited. * * * ******************************************************************************/ #include "CCTriggers.h" /* Triggers CC is a building block CC that allows creation of event -> action processing, where events are defined during trigger creation and actions to be mostly done via payments, but by making payments to other CC contracts, it can be used to invoke other CC contracts */ // start of consensus code int64_t IsTriggersvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v) { char destaddr[64]; if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 ) { if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 ) return(tx.vout[v].nValue); } return(0); } bool TriggersExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx,int32_t minage,uint64_t txfee) { static uint256 zerohash; CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; int64_t inputs=0,outputs=0,assetoshis; numvins = tx.vin.size(); numvouts = tx.vout.size(); for (i=0; i<numvins; i++) { //fprintf(stderr,"vini.%d\n",i); if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 ) { //fprintf(stderr,"vini.%d check mempool\n",i); if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 ) return eval->Invalid("cant find vinTx"); else { //fprintf(stderr,"vini.%d check hash and vout\n",i); if ( hashBlock == zerohash ) return eval->Invalid("cant Triggers from mempool"); if ( (assetoshis= IsTriggersvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 ) inputs += assetoshis; } } } for (i=0; i<numvouts; i++) { //fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts); if ( (assetoshis= IsTriggersvout(cp,tx,i)) != 0 ) outputs += assetoshis; } if ( inputs != outputs+txfee ) { fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs); return eval->Invalid("mismatched inputs != outputs + txfee"); } else return(true); } bool TriggersValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn) { int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks; bool retval; uint256 txid; uint8_t hash[32]; char str[65],destaddr[64]; return(false); std::vector<std::pair<CAddressIndexKey, CAmount> > txids; numvins = tx.vin.size(); numvouts = tx.vout.size(); preventCCvins = preventCCvouts = -1; if ( numvouts < 1 ) return eval->Invalid("no vouts"); else { for (i=0; i<numvins; i++) { if ( IsCCInput(tx.vin[0].scriptSig) == 0 ) { return eval->Invalid("illegal normal vini"); } } //fprintf(stderr,"check amounts\n"); if ( TriggersExactAmounts(cp,eval,tx,1,10000) == false ) { fprintf(stderr,"Triggersget invalid amount\n"); return false; } else { txid = tx.GetHash(); memcpy(hash,&txid,sizeof(hash)); retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) fprintf(stderr,"Triggersget validated\n"); else fprintf(stderr,"Triggersget invalid\n"); return(retval); } } } // end of consensus code // helper functions for rpc calls in rpcwallet.cpp int64_t AddTriggersInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,int64_t total,int32_t maxinputs) { // add threshold check char coinaddr[64]; int64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector<uint8_t> origpubkey; CTransaction vintx; int32_t vout,n = 0; std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs; GetCCaddress(cp,coinaddr,pk); SetCCunspents(unspentOutputs,coinaddr); for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; vout = (int32_t)it->first.index; // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { if ( (nValue= IsTriggersvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); nValue = it->second.satoshis; totalinputs += nValue; n++; if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) ) break; } } } return(totalinputs); } std::string TriggersGet(uint64_t txfee,int64_t nValue) { CMutableTransaction tmpmtx,mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey mypk,Triggerspk; int64_t inputs,CCchange=0; struct CCcontract_info *cp,C; std::string rawhex; uint32_t j; int32_t i,len; uint8_t buf[32768]; bits256 hash; cp = CCinit(&C,EVAL_TRIGGERS); if ( txfee == 0 ) txfee = 10000; Triggerspk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); if ( (inputs= AddTriggersInputs(cp,mtx,Triggerspk,nValue+txfee,60)) > 0 ) { if ( inputs > nValue ) CCchange = (inputs - nValue - txfee); if ( CCchange != 0 ) mtx.vout.push_back(MakeCC1vout(EVAL_TRIGGERS,CCchange,Triggerspk)); mtx.vout.push_back(CTxOut(nValue,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); fprintf(stderr,"start at %u\n",(uint32_t)time(NULL)); j = rand() & 0xfffffff; for (i=0; i<1000000; i++,j++) { tmpmtx = mtx; rawhex = FinalizeCCTx(-1LL,cp,tmpmtx,mypk,txfee,CScript() << OP_RETURN << E_MARSHAL(ss << (uint8_t)EVAL_TRIGGERS << (uint8_t)'G' << j)); if ( (len= (int32_t)rawhex.size()) > 0 && len < 65536 ) { len >>= 1; decode_hex(buf,len,(char *)rawhex.c_str()); hash = bits256_doublesha256(0,buf,len); if ( (hash.bytes[0] & 0xff) == 0 && (hash.bytes[31] & 0xff) == 0 ) { fprintf(stderr,"found valid txid after %d iterations %u\n",i,(uint32_t)time(NULL)); return(rawhex); } //fprintf(stderr,"%02x%02x ",hash.bytes[0],hash.bytes[31]); } } fprintf(stderr,"couldnt generate valid txid %u\n",(uint32_t)time(NULL)); return(""); } else fprintf(stderr,"cant find Triggers inputs\n"); return(""); } std::string TriggersFund(uint64_t txfee,int64_t funds) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey mypk,Triggerspk; CScript opret; struct CCcontract_info *cp,C; cp = CCinit(&C,EVAL_TRIGGERS); if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); Triggerspk = GetUnspendable(cp,0); if ( AddNormalinputs(mtx,mypk,funds+txfee,64) > 0 ) { mtx.vout.push_back(MakeCC1vout(EVAL_TRIGGERS,funds,Triggerspk)); return(FinalizeCCTx(0,cp,mtx,mypk,txfee,opret)); } return(""); } UniValue TriggersInfo() { UniValue result(UniValue::VOBJ); char numstr[64]; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey Triggerspk; struct CCcontract_info *cp,C; int64_t funding; result.push_back(Pair("result","success")); result.push_back(Pair("name","Triggers")); cp = CCinit(&C,EVAL_TRIGGERS); Triggerspk = GetUnspendable(cp,0); funding = AddTriggersInputs(cp,mtx,Triggerspk,0,0); sprintf(numstr,"%.8f",(double)funding/COIN); result.push_back(Pair("funding",numstr)); return(result); }
42.391705
270
0.581694
wallnutkraken
ce728886cb316176a60084c624c41c4c343873a3
10,282
cc
C++
apps/app_host/binaries_installer.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-03-10T13:08:49.000Z
2018-03-10T13:08:49.000Z
apps/app_host/binaries_installer.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
apps/app_host/binaries_installer.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:19:31.000Z
2020-11-04T07:19:31.000Z
// Copyright (c) 2012 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 "apps/app_host/binaries_installer.h" #include "base/logging.h" #include "base/threading/platform_thread.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_com_initializer.h" #include "base/win/scoped_comptr.h" #include "google_update/google_update_idl.h" namespace app_host { // Helpers -------------------------------------------------------------------- namespace { const wchar_t kAppHostAppId[] = L"{FDA71E6F-AC4C-4a00-8B70-9958A68906BF}"; const wchar_t kBinariesAppId[] = L"{4DC8B4CA-1BDA-483e-B5FA-D3C12E15B62D}"; const int kInstallationPollingIntervalMs = 50; HRESULT CreateInstalledApp(IAppBundle* app_bundle, const wchar_t* app_guid, IApp** app) { base::win::ScopedComPtr<IDispatch> idispatch; HRESULT hr = app_bundle->createInstalledApp(base::win::ScopedBstr(app_guid), idispatch.Receive()); if (FAILED(hr)) { LOG(ERROR) << "Failed to configure App Bundle: " << hr; return hr; } base::win::ScopedComPtr<IApp> temp_app; hr = temp_app.QueryFrom(idispatch); if (FAILED(hr)) { LOG(ERROR) << "Unexpected error querying IApp from " << "IAppBundle->createInstalledApp return value: " << hr; } else { *app = temp_app.Detach(); } return hr; } HRESULT GetAppHostApValue(IGoogleUpdate3* update3, IAppBundle* app_bundle, BSTR* ap_value) { base::win::ScopedComPtr<IApp> app; HRESULT hr = CreateInstalledApp(app_bundle, kAppHostAppId, app.Receive()); if (FAILED(hr)) return hr; hr = app->get_ap(ap_value); if (FAILED(hr)) LOG(ERROR) << "Failed to get the App Launcher AP value."; return hr; } HRESULT GetCurrentState(IApp* app, ICurrentState** current_state, CurrentState* state_value) { base::win::ScopedComPtr<IDispatch> idispatch; HRESULT hr = app->get_currentState(idispatch.Receive()); if (FAILED(hr)) { LOG(ERROR) << "Failed to get App Bundle state: " << hr; return hr; } base::win::ScopedComPtr<ICurrentState> temp_current_state; hr = temp_current_state.QueryFrom(idispatch); if (FAILED(hr)) { LOG(ERROR) << "Unexpected error querying ICurrentState from " << "IApp::get_currentState return value: " << hr; return hr; } LONG long_state_value; hr = temp_current_state->get_stateValue(&long_state_value); if (SUCCEEDED(hr)) { *state_value = static_cast<CurrentState>(long_state_value); *current_state = temp_current_state.Detach(); } else { LOG(ERROR) << "Failed to get App Bundle state value: " << hr; } return hr; } bool CheckIsBusy(IAppBundle* app_bundle, HRESULT* hr) { VARIANT_BOOL variant_is_busy = VARIANT_TRUE; *hr = app_bundle->isBusy(&variant_is_busy); if (FAILED(*hr)) LOG(ERROR) << "Failed to check app_bundle->isBusy: " << *hr; return (variant_is_busy == VARIANT_TRUE); } void OnUpdateAvailable(IAppBundle* app_bundle, HRESULT* hr) { // If the app bundle is busy we will just wait some more. if (CheckIsBusy(app_bundle, hr) || FAILED(*hr)) return; *hr = app_bundle->download(); if (FAILED(*hr)) LOG(ERROR) << "Failed to initiate bundle download: " << *hr; } void OnReadyToInstall(IAppBundle* app_bundle, HRESULT* hr) { // If the app bundle is busy we will just wait some more. if (CheckIsBusy(app_bundle, hr) || FAILED(*hr)) return; *hr = app_bundle->install(); if (FAILED(*hr)) LOG(ERROR) << "Failed to initiate bundle install: " << *hr; } HRESULT OnError(ICurrentState* current_state) { LONG error_code; HRESULT hr = current_state->get_errorCode(&error_code); if (FAILED(hr)) { LOG(ERROR) << "Failed to retrieve bundle error code: " << hr; return hr; } base::win::ScopedBstr completion_message; HRESULT completion_message_hr = current_state->get_completionMessage(completion_message.Receive()); if (FAILED(completion_message_hr)) { LOG(ERROR) << "Bundle installation failed with error " << error_code << ". Error message retrieval failed with error: " << completion_message_hr; } else { LOG(ERROR) << "Bundle installation failed with error " << error_code << ": " << completion_message; } return error_code; } HRESULT CreateGoogleUpdate3(IGoogleUpdate3** update3) { base::win::ScopedComPtr<IGoogleUpdate3> temp_update3; HRESULT hr = temp_update3.CreateInstance(CLSID_GoogleUpdate3UserClass); if (SUCCEEDED(hr)) { *update3 = temp_update3.Detach(); } else { // TODO(erikwright): Try in-proc to support running elevated? According // to update3_utils.cc (CreateGoogleUpdate3UserClass): // The primary reason for the LocalServer activation failing on Vista/Win7 // is that COM does not look at HKCU registration when the code is running // elevated. We fall back to an in-proc mode. The in-proc mode is limited to // one install at a time, so we use it only as a backup mechanism. LOG(ERROR) << "Failed to instantiate GoogleUpdate3: " << hr; } return hr; } HRESULT CreateAppBundle(IGoogleUpdate3* update3, IAppBundle** app_bundle) { base::win::ScopedComPtr<IDispatch> idispatch; HRESULT hr = update3->createAppBundle(idispatch.Receive()); if (FAILED(hr)) { LOG(ERROR) << "Failed to createAppBundle: " << hr; return hr; } base::win::ScopedComPtr<IAppBundle> temp_app_bundle; hr = temp_app_bundle.QueryFrom(idispatch); if (FAILED(hr)) { LOG(ERROR) << "Unexpected error querying IAppBundle from " << "IGoogleUpdate3->createAppBundle return value: " << hr; return hr; } hr = temp_app_bundle->initialize(); if (FAILED(hr)) LOG(ERROR) << "Failed to initialize App Bundle: " << hr; else *app_bundle = temp_app_bundle.Detach(); return hr; } HRESULT SelectBinariesApValue(IGoogleUpdate3* update3, IAppBundle* app_bundle, BSTR* ap_value) { HRESULT hr = GetAppHostApValue(update3, app_bundle, ap_value); if (SUCCEEDED(hr)) return hr; // TODO(erikwright): distinguish between AppHost not installed and an // error in GetAppHostApValue. // TODO(erikwright): Use stable by default when App Host support is in // stable. base::win::ScopedBstr temp_ap_value; if (temp_ap_value.Allocate(L"2.0-dev-multi-apphost") == NULL) { LOG(ERROR) << "Unexpected error in ScopedBstr::Allocate."; return E_FAIL; } *ap_value = temp_ap_value.Release(); return S_OK; } HRESULT CreateBinariesIApp(IAppBundle* app_bundle, BSTR ap, IApp** app) { base::win::ScopedComPtr<IDispatch> idispatch; HRESULT hr = app_bundle->createApp(base::win::ScopedBstr(kBinariesAppId), idispatch.Receive()); if (FAILED(hr)) { LOG(ERROR) << "Failed to configure App Bundle: " << hr; return hr; } base::win::ScopedComPtr<IApp> temp_app; hr = temp_app.QueryFrom(idispatch); if (FAILED(hr)) { LOG(ERROR) << "Unexpected error querying IApp from " << "IAppBundle->createApp return value: " << hr; return hr; } hr = temp_app->put_isEulaAccepted(VARIANT_TRUE); if (FAILED(hr)) { LOG(ERROR) << "Failed to set 'EULA Accepted': " << hr; return hr; } hr = temp_app->put_ap(ap); if (FAILED(hr)) LOG(ERROR) << "Failed to set AP value: " << hr; else *app = temp_app.Detach(); return hr; } bool CheckIfDone(IAppBundle* app_bundle, IApp* app, HRESULT* hr) { base::win::ScopedComPtr<ICurrentState> current_state; CurrentState state_value; *hr = GetCurrentState(app, current_state.Receive(), &state_value); if (FAILED(*hr)) return true; switch (state_value) { case STATE_WAITING_TO_CHECK_FOR_UPDATE: case STATE_CHECKING_FOR_UPDATE: case STATE_WAITING_TO_DOWNLOAD: case STATE_RETRYING_DOWNLOAD: case STATE_DOWNLOADING: case STATE_WAITING_TO_INSTALL: case STATE_INSTALLING: case STATE_DOWNLOAD_COMPLETE: case STATE_EXTRACTING: case STATE_APPLYING_DIFFERENTIAL_PATCH: // These states will all transition on their own. return false; case STATE_UPDATE_AVAILABLE: OnUpdateAvailable(app_bundle, hr); return FAILED(*hr); case STATE_READY_TO_INSTALL: OnReadyToInstall(app_bundle, hr); return FAILED(*hr); case STATE_NO_UPDATE: LOG(INFO) << "Google Update reports that the binaries are already " << "installed and up-to-date."; return true; case STATE_INSTALL_COMPLETE: return true; case STATE_ERROR: *hr = OnError(current_state); return FAILED(*hr); case STATE_INIT: case STATE_PAUSED: default: LOG(ERROR) << "Unexpected bundle state: " << state_value << "."; *hr = E_FAIL; return true; } } } // namespace // Globals -------------------------------------------------------------------- HRESULT InstallBinaries() { base::win::ScopedCOMInitializer initialize_com; if (!initialize_com.succeeded()) { LOG(ERROR) << "COM initialization failed"; return E_FAIL; } base::win::ScopedComPtr<IGoogleUpdate3> update3; HRESULT hr = CreateGoogleUpdate3(update3.Receive()); if (FAILED(hr)) return hr; base::win::ScopedComPtr<IAppBundle> app_bundle; hr = CreateAppBundle(update3, app_bundle.Receive()); if (FAILED(hr)) return hr; base::win::ScopedBstr ap_value; hr = SelectBinariesApValue(update3, app_bundle, ap_value.Receive()); if (FAILED(hr)) return hr; base::win::ScopedComPtr<IApp> app; hr = CreateBinariesIApp(app_bundle, ap_value, app.Receive()); if (FAILED(hr)) return hr; hr = app_bundle->checkForUpdate(); if (FAILED(hr)) { LOG(ERROR) << "Failed to initiate update check: " << hr; return hr; } // We rely upon Omaha to eventually time out and transition to a failure // state. while (!CheckIfDone(app_bundle, app, &hr)) { base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds( kInstallationPollingIntervalMs)); } return hr; } } // namespace app_host
31.347561
80
0.659794
GnorTech
ce74103755c2a0d811422a3be4d23f6fa2d688cd
2,530
cpp
C++
clang/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-startend.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-startend.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-startend.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %clang_cc1 -std=c++11 -S -triple x86_64-none-linux-gnu -emit-llvm -o - %s | FileCheck %s namespace std { typedef decltype(sizeof(int)) size_t; // libc++'s implementation with __size_ replaced by __end_ template <class _E> class initializer_list { const _E* __begin_; const _E* __end_; initializer_list(const _E* __b, const _E* __e) : __begin_(__b), __end_(__e) {} public: typedef _E value_type; typedef const _E& reference; typedef const _E& const_reference; typedef size_t size_type; typedef const _E* iterator; typedef const _E* const_iterator; initializer_list() : __begin_(nullptr), __end_(nullptr) {} size_t size() const {return __end_ - __begin_;} const _E* begin() const {return __begin_;} const _E* end() const {return __end_;} }; } // CHECK: @_ZGR15globalInitList1_ = internal constant [3 x i32] [i32 1, i32 2, i32 3] // CHECK: @globalInitList1 ={{.*}} global {{[^ ]+}} { i32* getelementptr inbounds ([3 x i32], [3 x i32]* @_ZGR15globalInitList1_, {{[^)]*}}), i32* std::initializer_list<int> globalInitList1 = {1, 2, 3}; void fn1(int i) { // CHECK-LABEL: define{{.*}} void @_Z3fn1i // temporary array // CHECK: [[array:%[^ ]+]] = alloca [3 x i32] // CHECK: getelementptr inbounds [3 x i32], [3 x i32]* [[array]], i{{32|64}} 0 // CHECK-NEXT: store i32 1, i32* // CHECK-NEXT: getelementptr // CHECK-NEXT: store // CHECK-NEXT: getelementptr // CHECK-NEXT: load // CHECK-NEXT: store // init the list // CHECK-NEXT: getelementptr // CHECK-NEXT: getelementptr inbounds [3 x i32], [3 x i32]* // CHECK-NEXT: store i32* // CHECK-NEXT: getelementptr // CHECK-NEXT: getelementptr inbounds [3 x i32], [3 x i32]* [[array]], i{{32|64}} 0, i{{32|64}} 3 // CHECK-NEXT: store i32* std::initializer_list<int> intlist{1, 2, i}; } struct destroyme1 { ~destroyme1(); }; struct destroyme2 { ~destroyme2(); }; void fn2() { // CHECK-LABEL: define{{.*}} void @_Z3fn2v void target(std::initializer_list<destroyme1>); // objects should be destroyed before dm2, after call returns target({ destroyme1(), destroyme1() }); // CHECK: call void @_ZN10destroyme1D1Ev destroyme2 dm2; // CHECK: call void @_ZN10destroyme2D1Ev } void fn3() { // CHECK-LABEL: define{{.*}} void @_Z3fn3v // objects should be destroyed after dm2 auto list = { destroyme1(), destroyme1() }; destroyme2 dm2; // CHECK: call void @_ZN10destroyme2D1Ev // CHECK: call void @_ZN10destroyme1D1Ev }
29.418605
146
0.64585
mkinsner
ce75b141582b342b736da07c788fee12161bcd26
1,874
cpp
C++
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/IsBalanced/IsBalanced.cpp
Vito-Swift/CourseMaterials
f2799f004f4353b5f35226158c8fd9f71818810e
[ "MIT" ]
null
null
null
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/IsBalanced/IsBalanced.cpp
Vito-Swift/CourseMaterials
f2799f004f4353b5f35226158c8fd9f71818810e
[ "MIT" ]
null
null
null
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/IsBalanced/IsBalanced.cpp
Vito-Swift/CourseMaterials
f2799f004f4353b5f35226158c8fd9f71818810e
[ "MIT" ]
2
2019-09-25T02:36:37.000Z
2020-06-05T08:47:01.000Z
/* * File: IsBalanced.cpp * -------------------- * This program checks to see whether the standard bracketing operators * (parentheses, square brackets, and curly braces) are correctly matched. */ #include <iostream> #include <string> #include "console.h" #include "simpio.h" #include "stack.h" using namespace std; /* Function prototypes */ bool isBalanced(string exp); bool operatorMatches(char open, char close); /* Main program */ int main() { while (true) { string str = getLine("Enter string: "); if (str == "") break; if (isBalanced(str)) { cout << "Brackets are properly nested" << endl; } else { cout << "Brackets are incorrect" << endl; } } return 0; } /* * Function: isBalanced * Usage: if (isBalanced(str)) . . . * --------------------------------- * Returns true if the bracketing operators (parentheses, square * brackets, and curly braces) are correctly paired in the input string. */ bool isBalanced(string str) { Stack<char> stack; for (int i = 0; i < str.length(); i++) { char ch = str[i]; switch (ch) { case '{': case '[': case '(': stack.push(ch); break; case '}': case ']': case ')': if (stack.isEmpty()) return false; if (!operatorMatches(stack.pop(), ch)) return false; break; } } return stack.isEmpty(); } /* * Function: operatorMatches * Usage: if (operatorMatches(open, close)) . . . * ---------------------------------------------- * Returns true if the characters open and close represent matching operators. * If op is not a bracketing operator, this function returns false. */ bool operatorMatches(char open, char close) { switch (open) { case '{': return close == '}'; case '[': return close == ']'; case '(': return close == ')'; default: return false; } }
25.324324
78
0.573106
Vito-Swift
ce787ad6e8aac4616c660be19d7f0b81c71ca343
5,703
hpp
C++
source/managers/StoryboardManager.hpp
skelleher/HappyGame
2c7610f420dab4ccf7e636c1c0d8fb6819989853
[ "BSD-3-Clause" ]
4
2015-06-23T19:23:31.000Z
2017-01-05T07:08:08.000Z
source/managers/StoryboardManager.hpp
skelleher/HappyGame
2c7610f420dab4ccf7e636c1c0d8fb6819989853
[ "BSD-3-Clause" ]
null
null
null
source/managers/StoryboardManager.hpp
skelleher/HappyGame
2c7610f420dab4ccf7e636c1c0d8fb6819989853
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "ResourceManager.hpp" #include "Handle.hpp" #include "Object.hpp" #include "Settings.hpp" #include "GameObject.hpp" #include "Layer.hpp" #include "Storyboard.hpp" #include <string> using std::string; class HAnimation; namespace Z { //============================================================================= // // StoryboardManager // //============================================================================= class StoryboardManager : public ResourceManager<Storyboard> { public: static StoryboardManager& Instance(); virtual RESULT Init ( IN const string& settingsFilename ); virtual RESULT Shutdown ( ); virtual RESULT Remove ( IN HStoryboard handle ); RESULT CreateStoryboard ( IN const string& name, IN HAnimation* pHAnimations = NULL, IN UINT8 numAnimations = 0, IN bool autoRepeat = false, IN bool autoReverse = false, IN bool releaseTargetOnFinish = true, IN bool deleteOnFinish = true, IN bool isRelative = false, INOUT HStoryboard* pHandle = NULL ); // TODO: Need convenience method for getting/binding/starting a Storyboard in one line of code. // StoryboardMan.RunWithTarget( "Name", hTarget, &hStoryboard ); RESULT BindTo ( IN HStoryboard hStoryboard, IN HGameObject hGameObject ); RESULT BindTo ( IN HStoryboard hStoryboard, IN HEffect hEffect ); RESULT BindTo ( IN HStoryboard hStoryboard, IN HLayer hLayer ); RESULT BindTo ( IN HStoryboard hStoryboard, IN HSprite hSprite ); RESULT BindTo ( IN HStoryboard hStoryboard, IN HParticleEmitter hEmitter ); RESULT BindTo ( IN HStoryboard hStoryboard, IN Object* pObject ); RESULT BindTo ( IN HStoryboard hStoryboard, IN IProperty* pProperty ); // HACK HACK: for binding to a single AnimationVariable. RESULT CallbackOnFinished ( IN HStoryboard handle, const ICallback& callback ); RESULT SetAutoRepeat ( IN HStoryboard handle, bool willAutoRepeat ); RESULT SetAutoReverse ( IN HStoryboard handle, bool willAutoReverse ); RESULT SetReleaseOnFinish ( IN HStoryboard handle, bool willReleaseTargetOnFinish ); RESULT SetDeleteOnFinish ( IN HStoryboard handle, bool willDeleteOnFinish ); RESULT SetRelativeToCurrentState ( IN HStoryboard handle, bool isRelativeToCurrentState ); RESULT Start ( IN HStoryboard handle ); RESULT Stop ( IN HStoryboard handle ); RESULT Pause ( IN HStoryboard handle ); RESULT Start ( IN Storyboard* pStoryboard ); RESULT Stop ( IN Storyboard* pStoryboard ); RESULT Pause ( IN Storyboard* pStoryboard ); bool IsStarted ( IN HStoryboard handle ); bool IsStopped ( IN HStoryboard handle ); bool IsPaused ( IN HStoryboard handle ); RESULT Update ( IN HStoryboard handle, UINT64 elapsedMS ); RESULT Update ( UINT64 elapsedMS ); // TODO: replace with struct StoryboardInfo? UINT64 GetDurationMS ( IN HStoryboard handle ); UINT64 GetDurationMS ( IN const string& name ); UINT8 GetNumAnimations ( IN HStoryboard handle ); UINT8 GetNumAnimations ( IN const string& nmae ); // Only public for Storyboard; make friend class? // TODO: move into ResourceManager<TYPE> since this is not uncommon. // E.G. ParticleEmitters need the same thing. RESULT ReleaseOnNextFrame ( IN HStoryboard handle ); RESULT ReleaseOnNextFrame ( IN Storyboard* pStoryboard ); // TODO: make all pointer methods PRIVATE and FRIEND the resource class. protected: StoryboardManager(); StoryboardManager( const StoryboardManager& rhs ); StoryboardManager& operator=( const StoryboardManager& rhs ); virtual ~StoryboardManager(); protected: RESULT CreateStoryboard( IN Settings* pSettings, IN const string& settingsPath, INOUT Storyboard** ppStoryboard ); protected: // Map of handles to currently-running Storyboards typedef list<Storyboard*> StoryboardList; typedef StoryboardList::iterator StoryboardListIterator; StoryboardList m_runningStoryboardsList; StoryboardList m_pendingReleaseStoryboardsList; }; #define StoryboardMan ((StoryboardManager&)StoryboardManager::Instance()) //#define Storyboards ((StoryboardManager&)StoryboardManager::Instance()) } // END namespace Z
45.624
164
0.525162
skelleher
706a161a93858fd8e9f79777d0a107dcc855a264
10,925
cpp
C++
src/Micro/Goals/FirstScoutGoal.cpp
syhw/BroodwarBotQ
71053d943d1bfb4cbf5a687bb015362decd9428c
[ "BSD-3-Clause" ]
10
2015-12-14T16:55:22.000Z
2022-02-04T20:51:38.000Z
src/Micro/Goals/FirstScoutGoal.cpp
SnippyHolloW/BroodwarBotQ
71053d943d1bfb4cbf5a687bb015362decd9428c
[ "BSD-3-Clause" ]
1
2019-10-22T04:52:28.000Z
2019-10-22T04:52:28.000Z
src/Micro/Goals/FirstScoutGoal.cpp
SnippyHolloW/BroodwarBotQ
71053d943d1bfb4cbf5a687bb015362decd9428c
[ "BSD-3-Clause" ]
2
2017-06-21T17:24:00.000Z
2017-10-21T14:15:17.000Z
#include <PrecompiledHeader.h> #include "Micro/Goals/FirstScoutGoal.h" #include "Macro/InformationManager.h" #include "Macro/BWSAL.h" #include <BWTA.h> #include "Subgoal.h" #include "Intelligence/Intelligence.h" #include "Regions/MapManager.h" #include "Micro/Micro.h" #include "Defines.h" using namespace BWAPI; using namespace std; inline BWTA::BaseLocation* getNearestBL(const TilePosition& tp, const set<BWTA::BaseLocation*>& s) { BWTA::BaseLocation* ret = *(s.begin()); double min = DBL_MAX; for (std::set<BWTA::BaseLocation*>::const_iterator it = s.begin(); it != s.end(); ++it) { double tmp = MapManager::Instance().distRegions((*it)->getRegion(), BWTA::getRegion(tp)); if (tmp > 0 && tmp < min) { min = tmp; ret = *it; } } return ret; } FirstScoutGoal::FirstScoutGoal(int priority) : Goal(priority) , _foundEnemy(false) , _nextToVisit(TilePositions::None) , _nextBase(NULL) , _gatheredIntel(false) , _stealingGas(true) , _mannerPylon(false) , _canHarassWorkers(true) , _arrivePosition(Positions::None) , _mineral(NULL) { BWTA::BaseLocation* home = BWTA::getStartLocation(Broodwar->self()); if (!home->getMinerals().empty()) _mineral = *(home->getMinerals().begin()); if (home->getRegion()->getChokepoints().empty()) // if we're on an island _status = GS_ACHIEVED; _neededUnits.insert(make_pair<UnitType, int>(Broodwar->self()->getRace().getWorker(), 1)); _notSeenStartLocations = BWTA::getStartLocations(); _notSeenStartLocations.erase(BWTA::getStartLocation(Broodwar->self())); _nextBase = getNearestBL(Broodwar->self()->getStartLocation(), _notSeenStartLocations); if (_nextBase != NULL) _nextToVisit = _nextBase->getTilePosition(); _unitsGroup.switchMode(MODE_SCOUT); // will use the scouting unit as leading units and update its path with threat aware pathfinding } void FirstScoutGoal::achieve() { if (_status != GS_IN_PROGRESS) // defensive return; /// If we have not unit, either we know where they are, or we need to send another scout if (!_unitsGroup.size()) { if (_notSeenStartLocations.size() > 1) { /// They killed our scout before _knowing_ where they are, we will request another scout _status = GS_WAIT_PRECONDITION; return; } else // either we found them or at least we know where they are { _status = GS_ACHIEVED; return; } } /// Set scoutUnit BWAPI::Unit* scoutUnit = NULL; if (_unitsGroup.size()) scoutUnit = (*_unitsGroup.units.begin())->unit; if (!scoutUnit->exists()) // defensive return; /// TODO change the moves for minerals clicks (mineral walking) if (!_foundEnemy) { /// We can see the next waypoint (_nextToVisit) if (Broodwar->isVisible(_nextToVisit.x(), _nextToVisit.y())) { /// If we see a ResourceDepot not belonging to us, it's them for each (Unit* u in Broodwar->getUnitsOnTile(_nextToVisit.x(), _nextToVisit.y())) { if (u->getPlayer() != Broodwar->self() && u->getType().isResourceDepot()) { _foundEnemy = true; break; } } /// Anyway we don't have to visit here again _notSeenStartLocations.erase(_nextBase); /// If we haven't found them, go to the next/nearest start location if (!_foundEnemy && _notSeenStartLocations.size()) // defensive { if (_notSeenStartLocations.size() == 1) // infer where the enemy is TheInformationManager->addEnemyBase(*_notSeenStartLocations.begin()); _nextBase = getNearestBL(_nextToVisit, _notSeenStartLocations); if (_nextBase != NULL) _nextToVisit = _nextBase->getTilePosition(); _unitsGroup.move(Position(_nextToVisit)); _arrivePosition = _unitsGroup.getCenter(); } } else { /* if (BWTA::getStartLocation(Broodwar->self())->getRegion() == BWTA::getRegion(TilePosition(_unitsGroup.center)) && _unitsGroup.getDistance(Micro::Instance().frontChoke->getCenter()) > 51) // can't base ourselved on the choke's center as the unit will stop while still in our region erratically { // still at home, trick to avoid going into sucking destructible backdoors/chokes _unitsGroup.move(Micro::Instance().frontChoke->getCenter()); } else _unitsGroup.move(Position(_nextToVisit)); if (_unitsGroup.groupMode != MODE_SCOUT) _unitsGroup.switchMode(MODE_SCOUT); _unitsGroup.update(); _arrivePosition = _unitsGroup.getCenter(); */ scoutUnit->move(Position(_nextToVisit)); _arrivePosition = scoutUnit->getPosition(); return; } } else /// Found enemy, harass then { if (Intelligence::Instance().enemyRush) // we are being rushed _stealingGas = false; if (scoutUnit->getDistance(Position(Broodwar->self()->getStartLocation())) < 20*TILE_SIZE) { _status = GS_ACHIEVED; return; } #ifdef __DO_NOT_HARASS_SCOUT__ goHome(scoutUnit); #else if (!_gatheredIntel) { _unitsAround = Broodwar->getUnitsInRadius(scoutUnit->getPosition(), 10*TILE_SIZE); Position c(Positions::None); for each (Unit* u in _unitsAround) { if (u->getType().isResourceDepot()) { c = u->getPosition(); break; } } BWTA::BaseLocation* b = NULL; if (!c.isValid() || c == Positions::None) b = BWTA::getNearestBaseLocation(scoutUnit->getPosition()); else b = BWTA::getNearestBaseLocation(c); if (b == NULL) { // hu? goHome(scoutUnit); return; } Vec dir(c.x() - _arrivePosition.x(), c.y() - _arrivePosition.y()); dir.normalize(); dir *= 5*TILE_SIZE; Position pos(dir.translate(c)); pos.makeValid(); if ((Broodwar->enemy()->getRace() == Races::Zerg && EUnitsFilter::Instance().getNumbersType(UnitTypes::Zerg_Spawning_Pool)) || (Broodwar->enemy()->getRace() == Races::Terran && EUnitsFilter::Instance().getNumbersType(UnitTypes::Terran_Barracks)) || (Broodwar->enemy()->getRace() == Races::Protoss && EUnitsFilter::Instance().getNumbersType(UnitTypes::Protoss_Gateway)) || scoutUnit->getDistance(pos) < 3*TILE_SIZE || scoutUnit->getHitPoints() < 20) // they cut through shield _gatheredIntel = true; Vec side(0,0); for each (Unit* u in b->getMinerals()) side += Vec(c.x() - u->getPosition().x(), c.y() - u->getPosition().y()); side.normalize(); side *= 5*TILE_SIZE; Position mid(side.translate(c)); mid.makeValid(); if (scoutUnit->getDistance(pos) > 11*TILE_SIZE) _unitsGroup.move(mid); else _unitsGroup.move(pos); if (_unitsGroup.groupMode != MODE_SCOUT) _unitsGroup.switchMode(MODE_SCOUT); _unitsGroup.update(); } if (_stealingGas) { /// Check if vespene extractor/assimilator/refinery and if not steal (if we have the money), build only one if 2 geysers... if (scoutUnit->isUnderAttack() || scoutUnit->getShields() < 2) { micro(scoutUnit); return; } TilePosition buildGas = TilePositions::None; for each (Unit* gas in _nextBase->getGeysers()) { if (!Broodwar->isVisible(gas->getTilePosition()) && scoutUnit->getDistance(Position(_nextToVisit)) > 4*TILE_SIZE) { scoutUnit->move(Position(_nextToVisit)); return; } for each (Unit* u in Broodwar->getUnitsOnTile(gas->getTilePosition().x(), gas->getTilePosition().y())) { if (u->getType().isRefinery()) _stealingGas = false; } if (_stealingGas) buildGas = gas->getTilePosition(); } if (buildGas != TilePositions::None) { scoutUnit->build(buildGas, Broodwar->self()->getRace().getRefinery()); return; } else _stealingGas = false; return; } /// Check if we can manner pylon // TODO manner pylon // !Intelligence::Instance().enemyRush /// Harass units then if (!_mannerPylon) { if (scoutUnit->getHitPoints() < 11) { _canHarassWorkers = false; goHome(scoutUnit); return; } if (!(Broodwar->getFrameCount() % (1 + Broodwar->getLatencyFrames()))) { micro(scoutUnit); return; } } if (!_canHarassWorkers) goHome(scoutUnit); #endif } } void FirstScoutGoal::micro(Unit* scoutUnit) { // because we're too hype to update units from filter (UnitsGroup) _unitsAround = Broodwar->getUnitsInRadius(scoutUnit->getPosition(), 192); set<Unit*> attackingMe; Unit* closestWorker = NULL; double closestDist = DBL_MAX; for each (Unit* u in _unitsAround) { if (u->getType().groundWeapon().maxRange() > 51 // > sqrt(2*TILE_SIZE^2) && < 2*TILE_SIZE || (u->getType() == UnitTypes::Zerg_Zergling && u->getDistance(scoutUnit) < 3*TILE_SIZE)) _canHarassWorkers = false; if (u->getTarget() == scoutUnit && u->getType().canAttack()) attackingMe.insert(u); if (u->getPlayer() == Broodwar->enemy() && u->getType().isWorker() && u->getDistance(scoutUnit) < closestDist) { closestDist = u->getDistance(scoutUnit); closestWorker = u; } } if (attackingMe.empty()) { if (closestWorker == NULL) scoutUnit->attack(Position(_nextToVisit)); else scoutUnit->attack(closestWorker); return; } else { scoutUnit->rightClick(_mineral); //direction.translate(scoutUnit->getPosition())); return; } } void FirstScoutGoal::goHome(Unit* scoutUnit) { if (_unitsGroup.groupMode != MODE_SCOUT) // defensive _unitsGroup.switchMode(MODE_SCOUT); Position middle(Broodwar->mapWidth()*TILE_SIZE/2, Broodwar->mapHeight()*TILE_SIZE/2); scoutUnit->rightClick(_mineral); _status = GS_ACHIEVED; } void FirstScoutGoal::onOffer(set<Unit*> objects) { GoalManager* gm = & GoalManager::Instance(); if ((_status == GS_WAIT_PRECONDITION || _status == GS_IN_PROGRESS) && _unitsGroup.emptyUnits()) { Position choke = (*BWTA::getStartLocation(Broodwar->self())->getRegion()->getChokepoints().begin())->getCenter(); double minDist = DBL_MAX; Unit* acceptedUnit = NULL; for each (Unit* u in objects) { if (gm->getCompletedUnits().find(u) != gm->getCompletedUnits().end() && _neededUnits.find(u->getType()) != _neededUnits.end() // take uniquely needed units && _neededUnits[u->getType()] > 0) { if (u->getDistance(choke) < minDist) { acceptedUnit = u; minDist = u->getDistance(choke); } } } if (acceptedUnit != NULL) { TheArbitrator->accept(this, acceptedUnit, _priority); _neededUnits[acceptedUnit->getType()] -= 1; pBayesianUnit tmp = gm->getCompletedUnit(acceptedUnit); if (tmp) // we only accept complete units but defensive _unitsGroup.dispatchCompleteUnit(tmp); } } else { TheArbitrator->decline(this, objects, 0); TheArbitrator->removeBid(this, objects); for each (Unit* u in objects) _biddedOn.erase(u); } } std::string FirstScoutGoal::getName() const { return "FScout"; }
30.774648
186
0.653913
syhw
706b218b3bd071612c6aa02b450247f6ee7fe915
12,961
cc
C++
aimsdata/src/aimsecat/io/ecatR.cc
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
4
2019-07-09T05:34:10.000Z
2020-10-16T00:03:15.000Z
aimsdata/src/aimsecat/io/ecatR.cc
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
72
2018-10-31T14:52:50.000Z
2022-03-04T11:22:51.000Z
aimsdata/src/aimsecat/io/ecatR.cc
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
null
null
null
/* This software and supporting documentation are distributed by * Institut Federatif de Recherche 49 * CEA/NeuroSpin, Batiment 145, * 91191 Gif-sur-Yvette cedex * France * * This software is governed by the CeCILL-B license under * French law and abiding by the rules of distribution of free software. * You can use, modify and/or redistribute the software under the * terms of the CeCILL-B license as circulated by CEA, CNRS * and INRIA at the following URL "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. */ // we don't want to issue a warning #ifndef AIMSDATA_CLASS_NO_DEPREC_WARNING #define AIMSDATA_CLASS_NO_DEPREC_WARNING #endif /* * Ecat6-6 data reader class */ #include <aims/io/ecatR.h> #include <cartobase/exception/assert.h> #include <ecat+/io/io.h> #include <cartobase/exception/format.h> #include <soma-io/datasource/filedatasource.h> #include <vector> #include <iostream> using namespace aims; using namespace carto; using namespace std; template< class T > string EcatReader< T >::removeExtension( const string& name ) { string res = name; string ext=""; if ( res.length() > 2 ) ext = res.substr( int(res.length() - 2), 2 ); if (ext == ".v") res = res.substr( 0, res.length() - 2 ); return res; } namespace aims { template<> void EcatReader< short >::frameRead( AimsData<short>&, const carto::AllocatorContext &, int, int ) { throw format_error( "frame by frame input capability is not supported for " "Ecat short reading", _name ); } template<> void EcatReader< float >::frameRead( AimsData<float>& thing, const carto::AllocatorContext & context, int frame, int border ) { UnifiedEcatInfo *uei; string fileName; // -------------------------Initialisation du header propri�taire and Fix it EcatHeader *hdr = new EcatHeader( _name ); try { hdr->read(); } catch( exception & e ) { delete hdr; throw( e ); } vector< int > sdt, sdt_s, sdt_d; if (!hdr->getProperty("start_time", sdt)) sdt_s.push_back( 0 ); else sdt_s.push_back( sdt[frame] ); hdr->setProperty("start_time", sdt_s); if (!hdr->getProperty("duration_time", sdt)) sdt_d.push_back( 0 ); else sdt_d.push_back( sdt[frame] ); hdr->setProperty("duration_time", sdt_d); vector< int > volDim; hdr->getProperty("volume_dimension",volDim); ASSERT( volDim[3] != 0 ); //It is not a dynamic series ?? ASSERT( (frame >= 0) && (frame < volDim[3]) ); // ----------------------------------------Ouverture du uei fileName = _name; // .i, .v, .p are different ECAT volumes if ( (uei = EcatOpen( (char*) hdr->name().c_str(), const_cast<char*>( "r" ) )) == ECATSHFJ_FAIL ) throw format_error( fileName ); carto::AllocatorContext cont2( context.accessMode(), rc_ptr<DataSource> ( new FileDataSource( hdr->name(), 0, DataSource::Read ) ), false, context.useFactor() ); AimsData<float> data( uei->size.x, uei->size.y, uei->size.z, 1, border, cont2 ); data.setSizeXYZT( uei->voxelsize.x, uei->voxelsize.y, uei->voxelsize.z, uei->voxelsize.t ); float *f_pt, *f_ima; // --------------------------------------------Lecture frame par frame AimsData<float>::iterator wit = data.begin() + data.oFirstPoint(); if ( ! EcatDataCalibrated(uei) ) { if( ( f_ima = EcatReadVolume_FLOAT( uei ,frame)) == ECATSHFJ_FAIL ) throw logic_error( "Internal error: read failed" ); f_pt = f_ima; for( int z = 0; z < EcatSizeZ(uei); z++ ) { for ( int y = 0; y < EcatSizeY(uei); y++ ) { for ( int x = 0; x < EcatSizeX(uei); x++ ) { *wit++ = (float)((double) *f_pt++ * (double) EcatCalib( uei )); } wit += data.oPointBetweenLine(); } wit += data.oLineBetweenSlice(); } wit += data.oSliceBetweenVolume(); free( f_ima ); } else { if( ( f_ima = EcatReadVolume_FLOAT( uei ,frame)) == ECATSHFJ_FAIL ) throw logic_error( "Internal error: read failed" ); f_pt = f_ima; for( int z = 0; z < EcatSizeZ(uei); z++ ) { for ( int y = 0; y < EcatSizeY(uei); y++ ) { for ( int x = 0; x < EcatSizeX(uei); x++ ) { *wit++ = *f_pt++; } wit += data.oPointBetweenLine(); } wit += data.oLineBetweenSlice(); } wit += data.oSliceBetweenVolume(); free( f_ima ); } data.setHeader( hdr ); // ------------------------------Fin. thing = data; } template<> void EcatReader< short >::read( AimsData<short>& thing, const carto::AllocatorContext & context, carto::Object options ) { int frame = -1, border = 0; options->getProperty( "frame", frame ); options->getProperty( "border", border ); if( frame >= 0 ) { frameRead( thing, context, frame, border ); return; } UnifiedEcatInfo *uei; string fileName; EcatHeader *hdr; // --------------------------------Initialisation du header proprietaire hdr = new EcatHeader( _name ); try { hdr->read(); } catch( exception & e ) { delete hdr; throw( e ); } // ----------------------------------------Ouverture du uei fileName = _name; // .i, .v, .p are different ECAT volumes if ( (uei = EcatOpen( (char*) hdr->name().c_str(), const_cast<char*>( "r" ) )) == ECATSHFJ_FAIL ) throw format_error( fileName ); carto::AllocatorContext cont2( context.accessMode(), rc_ptr<DataSource> ( new FileDataSource( hdr->name(), 0, carto::DataSource::Read ) ), false, context.useFactor() ); AimsData<short> data( uei->size.x, uei->size.y, uei->size.z, uei->size.t, border, cont2 ); data.setSizeXYZT( uei->voxelsize.x, uei->voxelsize.y, uei->voxelsize.z, uei->voxelsize.t ); data.setHeader( hdr ); short *s_pt, *s_ima; // (data is a temp allocated here so always has stride == 1) long stride = &data(1) - &data(0); // --------------------------------------------Lecture frame par frame for(int frame=0; frame < uei->size.t; frame++) { if( ( s_ima = EcatReadVolume_S16( uei, frame)) == ECATSHFJ_FAIL ) throw logic_error( "Internal error: read failed" ); s_pt = s_ima; for(int slice=0; slice<uei->size.z;slice++) for(int line=0;line <uei->size.y;line++) { memcpy((char*)&data(0,line,slice,frame),(char*)s_pt, uei->size.x*sizeof(short)); s_pt += uei->size.x; } free( s_ima ); } // ------------------------------Remise en coherence des scale factors if (string(EcatCalibUnit( uei )) != "Labels") { short *it; double maxi = data(0) * (double)EcatVolScale(uei,0) * (double)EcatCalib(uei); double mini = maxi; for(int frame=0; frame< EcatSizeT(uei); frame++) { double sf = (double)EcatVolScale(uei,frame ); // EcatCalib( uei ) inutile //car constant pour toutes les frames; for( int z = 0; z < EcatSizeZ(uei); z++ ) { for ( int y = 0; y < EcatSizeY(uei); y++ ) { it = &data( 0, y, z, frame ); for ( int x = 0; x < EcatSizeX(uei); x++ ) { double tmp =(double)*it * sf; if ( tmp > maxi ) maxi = tmp; if ( tmp < mini ) mini = tmp; it += stride; } } } } double ratio; if (maxi > -mini ) ratio = (double) 32767 / maxi; else ratio = (double) 32768 / (-mini); _scale = (float )((double) 1.0 / ratio); short *wit; for(int frame=0; frame< EcatSizeT(uei); frame++) { double sf = (double)EcatVolScale(uei,frame ) * (double)EcatCalib( uei ); for( int z = 0; z < EcatSizeZ(uei); z++ ) { for ( int y = 0; y < EcatSizeY(uei); y++ ) { wit = &data( 0, y, z, frame ); for ( int x = 0; x < EcatSizeX(uei); x++ ) { int tmp = (int) ((double)*wit * sf * ratio); if (tmp > 32767) *wit = 32767; else if (tmp < -32768 ) *wit = -32768; else *wit = (short) tmp; wit += stride; } } } } } // -------------------------------------------------fermeture de l'uei EcatClose( uei ); // ------------------------------Fin. thing = data; } template<> void EcatReader< float >::read( AimsData<float>& thing, const carto::AllocatorContext & context, carto::Object options ) { int frame = -1, border = 0; options->getProperty( "frame", frame ); options->getProperty( "border", border ); if( frame >= 0 ) { frameRead( thing, context, frame, border ); return; } UnifiedEcatInfo *uei; string fileName; EcatHeader *hdr; float *f_pt, *f_ima; // --------------------------------Initialisation du header propri�taire hdr = new EcatHeader( _name ); try { hdr->read(); } catch( exception & e ) { delete hdr; throw( e ); } // ----------------------------------------------------------Ouverture du uei fileName = _name; // .i, .v, .p are different ECAT volumes if ( (uei = EcatOpen( (char*) hdr->name().c_str(), const_cast<char*>( "r" ) )) == ECATSHFJ_FAIL ) throw format_error( fileName ); carto::AllocatorContext cont2( context.accessMode(), rc_ptr<DataSource> ( new FileDataSource( hdr->name(), 0, DataSource::Read ) ), false, context.useFactor() ); AimsData<float> data( uei->size.x, uei->size.y, uei->size.z, uei->size.t, border, cont2 ); data.setSizeXYZT( uei->voxelsize.x, uei->voxelsize.y, uei->voxelsize.z, uei->voxelsize.t ); data.setHeader( hdr ); // Caracteristiques des images // cout << "Image units are: " << EcatCalibUnit(uei) << endl; // --------------------------------------------Lecture frame par frame AimsData<float>::iterator wit = data.begin() + data.oFirstPoint(); if ( ! EcatDataCalibrated(uei) ) { for(int frame=0; frame < uei->size.t; frame++) { if( ( f_ima = EcatReadVolume_FLOAT( uei ,frame))==ECATSHFJ_FAIL ) throw logic_error( "Internal error: read failed" ); f_pt = f_ima; for( int z = 0; z < EcatSizeZ(uei); z++ ) { for ( int y = 0; y < EcatSizeY(uei); y++ ) { for ( int x = 0; x < EcatSizeX(uei); x++ ) { *wit++ = (float)((double) *f_pt++ * (double) EcatCalib( uei )); } wit += data.oPointBetweenLine(); } wit += data.oLineBetweenSlice(); } wit += data.oSliceBetweenVolume(); free( f_ima ); } } else { for(int frame=0; frame < uei->size.t; frame++) { if( ( f_ima = EcatReadVolume_FLOAT( uei ,frame))==ECATSHFJ_FAIL ) throw logic_error( "Internal error: read failed" ); f_pt = f_ima; for( int z = 0; z < EcatSizeZ(uei); z++ ) { for ( int y = 0; y < EcatSizeY(uei); y++ ) { for ( int x = 0; x < EcatSizeX(uei); x++ ) { *wit++ = *f_pt++; } wit += data.oPointBetweenLine(); } wit += data.oLineBetweenSlice(); } wit += data.oSliceBetweenVolume(); free( f_ima ); } } // --------------------------------------------------------fermeture de l'uei EcatClose( uei ); // ------------------------------Fin. thing = data; } template class EcatReader< int16_t >; template class EcatReader< float >; } // namespace aims
29.933025
90
0.548106
brainvisa
706b33f0539b9dcd2a887f154ef431417c2d5442
25,802
cpp
C++
src/model_infer.cpp
WinstonLy/Ascend310Projects
4535e1682fbd64e59644854574bab9e37cfdfdb4
[ "MIT" ]
10
2021-04-02T11:15:19.000Z
2022-02-13T06:31:57.000Z
src/model_infer.cpp
WinstonLy/Ascend310Projects
4535e1682fbd64e59644854574bab9e37cfdfdb4
[ "MIT" ]
1
2021-04-12T12:57:46.000Z
2021-04-15T00:50:50.000Z
src/model_infer.cpp
WinstonLy/Ascend310Projects
4535e1682fbd64e59644854574bab9e37cfdfdb4
[ "MIT" ]
3
2021-04-12T12:55:38.000Z
2022-03-03T03:04:15.000Z
/* * @Author: winston * @Date: 2021-01-07 20:58:09 * @Last Modified by: WinstonLy * @Last Modified time: 2021-04-16 14:38:31 * @Description: * @FilePath: /home/winston/AscendProjects/rtsp_dvpp_infer_dvpp_rtmp_test/atlas200dk_yolov4/Electricity-Inspection-Based-Ascend310/src/model_infer.cpp */ #include "model_infer.h" #include <iostream> #include <queue> #include <mutex> #include <chrono> #include <thread> #include <sys/time.h> typedef std::pair<vector<size_t>, vector<void*> > imgPair; extern std::mutex mtxQueueInfer; extern std::queue<std::pair<vector<size_t>, vector<void*>> > queueInfer; extern fstream resultInfer; namespace { const static std::vector<std::string> yolov3Label = { "person", "bicycle", "car", "motorbike", "aeroplane","bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag","tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "potted plant", "bed", "dining table", "toilet", "TV monitor", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase","scissors", "teddy bear", "hair drier", "toothbrush" }; //Inferential output dataset subscript 0 unit is detection box information data const uint32_t kBBoxDataBufId = 0; //The unit with subscript 1 is the number of boxes const uint32_t kBoxNumDataBufId = 1; //Each field subscript in the box message enum BBoxIndex { TOPLEFTX = 0, TOPLEFTY, BOTTOMRIGHTX, BOTTOMRIGHTY, SCORE, LABEL }; } namespace { const static std::vector<std::string> yolov4Label = { "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic_light", "fire_hydrant", "stop_sign", "parking_meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports_ball", "kite", "baseball_bat", "baseball_glove", "skateboard", "surfboard", "tennis_racket", "bottle", "wine_glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot_dog", "pizza", "donut", "cake", "chair", "couch", "potted_plant", "bed", "dining_table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell_phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy_bear", "hair_drier", "toothbrush "}; } ModelProcess::ModelProcess(aclrtStream _stream, int _width, int _height):stream(_stream), modelWidth(_width), modelHeight(_height), modelId(0), modelMemSize(0), modelWeightSize(0),loadFlag(false), modelMemBuffer(nullptr), modelWeightBuffer(nullptr), modelDesc(nullptr), modelInput(nullptr), modelOutput(nullptr), outputBuffer(nullptr), outputBufferSize(0) { } ModelProcess::~ModelProcess(){ } void ModelProcess::Destroy(){ Unload(); DestroyDesc(); DestroyInput(); DestroyOutput(); } Result ModelProcess::Init(const char* modelPath, void* inputDataBuffer, size_t inputBufferSize) { // 加载模型 // const char* modelPath = "./model/yolov3.om"; Result resCode = LoadModelFromFileWithMem(modelPath); if(resCode != SUCCESS){ ATLAS_LOG_ERROR("Load model file failed"); return FAILED; } // 创建模型描述信息 resCode = CreateDesc(); if(resCode != SUCCESS){ (void)aclmdlDestroyDesc(modelDesc); modelDesc = nullptr; ATLAS_LOG_ERROR("Create model desc failed"); return FAILED; } // 创建模型推理的输入输出 resCode = CreateInput(inputDataBuffer, modelWidth*modelHeight*3/2); if(resCode != SUCCESS){ ATLAS_LOG_ERROR("model infer create input failed"); DestroyInput(); CHECK_ACL(acldvppFree(inputDataBuffer)); return FAILED; } resCode = CreateOutputWithMem(); if(resCode != SUCCESS){ ATLAS_LOG_ERROR("model infer create output failed"); DestroyOutput(); CHECK_ACL(acldvppFree(inputDataBuffer)); } ATLAS_LOG_ERROR("model infer init success"); } Result ModelProcess::LoadModelFromFileWithMem(const char *modelPath){ if(loadFlag){ ATLAS_LOG_ERROR("ACL has already loaded a model"); return FAILED; } // 根据模型文件获取模型执行的时候需要的权值内存大小和工作内存大小 aclError ret = aclmdlQuerySize(modelPath,&modelMemSize, &modelWeightSize); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("ACL query mem and weight size failed, model file is %s", modelPath); return FAILED; } // 根据权值内存和工作内存大小,申请Device上的工作内存和权值内存 CHECK_ACL(aclrtMalloc(&modelMemBuffer, modelMemSize, ACL_MEM_MALLOC_HUGE_FIRST)); CHECK_ACL(aclrtMalloc(&modelWeightBuffer, modelWeightSize, ACL_MEM_MALLOC_HUGE_FIRST)); // 加载离线模型文件,用户自行管理模型运行内存 ret = aclmdlLoadFromFileWithMem(modelPath, &modelId, modelMemBuffer, modelMemSize, modelWeightBuffer, modelWeightSize); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("Load model from file failed, err code = %d", ret); ATLAS_LOG_ERROR("model file path is %s", modelPath); return FAILED; } loadFlag = true; ATLAS_LOG_INFO("load model %s success", modelPath); return SUCCESS; } void ModelProcess::Unload(){ if(!loadFlag){ WARN_LOG("no model had been loaded, uload failed"); return; } aclError ret = aclmdlUnload(modelId); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("ACL unload model failed, modelId is %u", modelId); } if(modelDesc != nullptr){ (void)aclmdlDestroyDesc(modelDesc); modelDesc = nullptr; } if(modelMemBuffer != nullptr){ aclrtFree(modelMemBuffer); modelMemBuffer = nullptr; modelMemSize = 0; } if(modelWeightBuffer != nullptr){ aclrtFree(modelWeightBuffer); modelWeightBuffer = nullptr; modelWeightSize = 0; } loadFlag = false; ATLAS_LOG_INFO("ACL unload model success, modelId is %u", modelId); } Result ModelProcess::CreateDesc(){ // 根据加载成功的模型的ID,获取模型的描述信息 modelDesc = aclmdlCreateDesc(); if(modelDesc == nullptr){ ATLAS_LOG_ERROR("create model description failed"); return FAILED; } aclError ret = aclmdlGetDesc(modelDesc, modelId); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("get model id failed"); return FAILED; } ATLAS_LOG_INFO("create model description success"); return SUCCESS; } void ModelProcess::DestroyDesc(){ if(modelDesc != nullptr){ (void)aclmdlDestroyDesc(modelDesc); modelDesc = nullptr; } } Result ModelProcess::CreateInput(void* inputDataBuffer, size_t inputBufferSize){ vector<DataInfo> inputData = {{inputDataBuffer, inputBufferSize}}; return CreateInput(inputData); } Result ModelProcess::CreateInput(void* inputDataBuffer, size_t inputBufferSize, void* imageInfoBuffer, size_t imageInfoSize){ vector<DataInfo> inputData = {{inputDataBuffer, inputBufferSize}, {imageInfoBuffer, imageInfoSize}}; return CreateInput(inputData); } Result ModelProcess::CreateInput(vector<DataInfo>& inputData){ if(inputData.size() == 0){ ATLAS_LOG_ERROR("Create model input failed for no input data"); return FAILED; } // 创建aclmdlDataset类型的数据,用于描述模型推理的输入数据,输入的内存地址、内存大小等信息 modelInput = aclmdlCreateDataset(); if(modelInput == nullptr){ ATLAS_LOG_ERROR("can't create dataset, create input failed"); return FAILED; } for(uint32_t i = 0; i < inputData.size(); i++){ aclError ret = AddDatasetBuffer(modelInput, inputData[i].data, inputData[i].size); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("Create input failed for add dataset buffer error %d", ret); return FAILED; } } ATLAS_LOG_INFO("create model input success"); return SUCCESS; } aclError ModelProcess::AddDatasetBuffer(aclmdlDataset *dataset, void* buffer, size_t bufferSize){ aclDataBuffer* modelDataBuf = aclCreateDataBuffer(buffer, bufferSize); if(modelDataBuf == nullptr){ ATLAS_LOG_ERROR("can't create data buffer, create input failed"); return ACL_ERROR_MODEL_INPUT_NOT_MATCH; } aclError ret = aclmdlAddDatasetBuffer(dataset, modelDataBuf); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("can't add dataset buffer, create input failed, err code = %d", ret); aclDestroyDataBuffer(modelDataBuf); return ret; } return ACL_ERROR_NONE; } void ModelProcess::DestroyInput(){ if(modelInput == nullptr){ return; } for(size_t i = 0; i < aclmdlGetDatasetNumBuffers(modelInput); ++i){ aclDataBuffer* dataBuffer = aclmdlGetDatasetBuffer(modelInput, i); aclDestroyDataBuffer(dataBuffer); } aclmdlDestroyDataset(modelInput); modelInput = nullptr; } // 模型输出需要另行获取 Result ModelProcess::CreateOutput() { if (modelDesc == nullptr) { ATLAS_LOG_ERROR("no model description, create ouput failed"); return FAILED; } // 创建描述模型推理的输出 modelOutput = aclmdlCreateDataset(); if(modelOutput == nullptr){ ATLAS_LOG_ERROR("can't create dataset, create model output failed"); return FAILED; } // 获取模型的输出个数 size_t outputSize = aclmdlGetNumOutputs(modelDesc); // 循环为每个输出申请内存,并将每个输出添加到aclmdlDataset类型的数据中 for(size_t i = 0; i < outputSize; ++i){ outputBufferSize = aclmdlGetOutputSizeByIndex(modelDesc, i); aclError ret = aclrtMalloc(&outputBuffer, outputBufferSize, ACL_MEM_MALLOC_NORMAL_ONLY); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("can't malloc buffer, size is %zu, create output failed", outputBufferSize); return FAILED; } aclDataBuffer* outputData = aclCreateDataBuffer(outputBuffer, outputBufferSize); ret = aclmdlAddDatasetBuffer(modelOutput, outputData); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("can't add dataset buffer, create output failed"); aclrtFree(outputBuffer); aclDestroyDataBuffer(outputData); return FAILED; } } ATLAS_LOG_INFO("create model output success"); return SUCCESS; } // 将模型输出存放到数组中 Result ModelProcess::CreateOutputWithMem(){ if (modelDesc == nullptr) { ATLAS_LOG_ERROR("no model description, create ouput failed"); return FAILED; } // 创建描述模型推理的输出 modelOutput = aclmdlCreateDataset(); if(modelOutput == nullptr){ ATLAS_LOG_ERROR("can't create dataset, create model output failed"); return FAILED; } // 获取模型的输出个数 size_t outputSize = aclmdlGetNumOutputs(modelDesc); // 循环为每个输出申请内存,并将每个输出添加到aclmdlDataset类型的数据中 for(size_t i = 0; i < outputSize; ++i){ size_t bufferSize = aclmdlGetOutputSizeByIndex(modelDesc, i); void* outputBuffer{nullptr}; aclError ret = aclrtMalloc(&outputBuffer, bufferSize, ACL_MEM_MALLOC_NORMAL_ONLY); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("can't malloc buffer, size is %zu, create output failed", bufferSize); return FAILED; } outputDataBufferSizes.push_back(bufferSize); outputDataBuffers.push_back(outputBuffer); std::cout << "create output size : " << bufferSize << std::endl; aclDataBuffer* outputData = aclCreateDataBuffer(outputBuffer, bufferSize); ret = aclmdlAddDatasetBuffer(modelOutput, outputData); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("can't add dataset buffer, create output failed"); aclrtFree(outputBuffer); aclDestroyDataBuffer(outputData); return FAILED; } } ATLAS_LOG_INFO("create model output success"); return SUCCESS; } void ModelProcess::DestroyOutput(){ if(modelOutput == nullptr){ return; } for(size_t i = 0; i < aclmdlGetDatasetNumBuffers(modelOutput); ++i){ aclDataBuffer* dataBuffer = aclmdlGetDatasetBuffer(modelOutput, i); void* data = aclGetDataBufferAddr(dataBuffer); (void)aclrtFree(data); (void)aclDestroyDataBuffer(dataBuffer); } (void)aclmdlDestroyDataset(modelOutput); modelOutput = nullptr; if(outputDataBuffers.size() != 0){ for(auto& j : outputDataBuffers){ aclrtFree(j); } } if(outputBuffer != nullptr){ aclrtFree(outputBuffer); } } Result ModelProcess::Execute(){ // clock_t beginTime = clock(); // 异步接口 // struct timeval a; gettimeofday(&a, NULL); aclError ret = aclmdlExecuteAsync(modelId, modelInput, modelOutput, stream); if (ret != ACL_ERROR_NONE) { ATLAS_LOG_ERROR("execute model failed, modelId is %u", modelId); return FAILED; } // 阻塞应用程序运行,直到指定stream中的所有任务完成 ret = aclrtSynchronizeStream(stream); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("synchronize stream failed, err code = %d", ret); return FAILED; } // // 同步接口 // aclError ret = aclmdlExecute(modelId, modelInput, modelOutput); // if (ret != ACL_ERROR_NONE) { // ATLAS_LOG_ERROR("execute model failed, modelId is %u", modelId); // return FAILED; // } struct timeval b; gettimeofday(&b, NULL); // clock_t endTime = clock(); resultInfer << "infer a frame time: " << ((double)(b.tv_sec - a.tv_sec)*1000000 + (b.tv_usec - a.tv_usec)) / 1000 << " ms" <<endl; if(outputDataBuffers.size() != 0){ mtxQueueInfer.lock(); if(queueInfer.size() > 50){ mtxQueueInfer.unlock(); } else{ std::vector<void *> dataBuffers(outputDataBuffers); std::vector<size_t> bufferSizes(outputDataBufferSizes); queueInfer.push(std::make_pair(bufferSizes, dataBuffers)); mtxQueueInfer.unlock(); } } ATLAS_LOG_INFO("model execute success"); return SUCCESS; } const std::vector<void*> &ModelProcess::GetOutputDataBuffers(){ return outputDataBuffers; } const std::vector<size_t> &ModelProcess::GetOutputBufferSizes() { return outputDataBufferSizes; } aclmdlDataset *ModelProcess::GetModelOutputData() { return modelOutput; } void ModelProcess::RegisterHandler(std::function<void(uint8_t*, int)> handler){ bufferHandler = handler; } void* ModelProcess::GetInferenceOutputItem(uint32_t& itemDataSize, aclmdlDataset* inferenceOutput , uint32_t idx) { aclDataBuffer* dataBuffer = aclmdlGetDatasetBuffer(inferenceOutput, idx); if (dataBuffer == nullptr) { ATLAS_LOG_ERROR("Get the %dth dataset buffer from model " "inference output failed", idx); } void* dataBufferDev = aclGetDataBufferAddr(dataBuffer); if (dataBufferDev == nullptr) { ATLAS_LOG_ERROR("Get the %dth dataset buffer address " "from model inference output failed", idx); } size_t bufferSize = aclGetDataBufferSize(dataBuffer); if (bufferSize == 0) { ATLAS_LOG_ERROR("The %dth dataset buffer size of " "model inference output is 0", idx); } void* data = nullptr; if (!(RunStatus::GetDeviceStatus())) { // data = Utils::CopyDataDeviceToLocal(dataBufferDev, bufferSize); // if (data == nullptr) { // ATLAS_LOG_ERROR("Copy inference output to host failed"); // return nullptr; // } ATLAS_LOG_ERROR("is not a device, need copy to device"); } else { data = dataBufferDev; } itemDataSize = bufferSize; return data; } // Yolov3修改之后的模型,加入3个yolo和一个yolodetecouput算子,不需要后处理 vector<DetectionResult> ModelProcess::PostProcessYolov3(int frameWidth, int frameHeight){ //Get box information data uint32_t dataSize = 0; // 检测信息按照x上、y上、x下、y下、得分、标签的顺序排列,多个目标也是如此。 float* detectData = (float*)GetInferenceOutputItem(dataSize, modelOutput, kBBoxDataBufId); if (detectData == nullptr) ATLAS_LOG_ERROR("detect data get failed"); //Gets the number of boxes uint32_t* boxNum = (uint32_t*)GetInferenceOutputItem(dataSize, modelOutput, kBoxNumDataBufId); if (boxNum == nullptr) ATLAS_LOG_ERROR("get infer output box num failed"); //Number of boxes The first data is valid uint32_t totalBox = boxNum[0]; // float widthScale = (float)(frameWidth) / modelWidth; float heightScale = (float)(frameHeight) / modelHeight; ATLAS_LOG_INFO("width Scale %f, heightScale %f", widthScale, heightScale); ATLAS_LOG_INFO("totalBox : %d", totalBox); vector<DetectionResult> detectResults; for (uint32_t i = 0; i < totalBox; i++) { DetectionResult oneResult; Point point_lt, point_rb; //get the confidence of the detected object. Anything less than 0.8 is considered invalid uint32_t score = (uint32_t)(detectData[totalBox * SCORE + i] * 100); if (score < 80) continue; ATLAS_LOG_INFO("infer score %d", score); //get the frame coordinates and converts them to the coordinates on the original frame oneResult.lt.x = detectData[totalBox * TOPLEFTX + i] * widthScale; oneResult.lt.y = detectData[totalBox * TOPLEFTY + i] * heightScale; oneResult.rb.x = detectData[totalBox * BOTTOMRIGHTX + i] * widthScale; oneResult.rb.y = detectData[totalBox * BOTTOMRIGHTY + i] * heightScale; //Construct a string that marks the object: object name + confidence uint32_t objIndex = (uint32_t)detectData[totalBox * LABEL + i]; oneResult.result_text = yolov3Label[objIndex] + std::to_string(score) + "\%"; ATLAS_LOG_INFO("%d %d %d %d %s\n", oneResult.lt.x, oneResult.lt.y, oneResult.rb.x, oneResult.rb.y, oneResult.result_text.c_str()); detectResults.emplace_back(oneResult); } //If it is the host side, the data is copied from the device and the memory used by the copy is freed if (!(RunStatus::GetDeviceStatus())) { delete[]((uint8_t*)detectData); delete[]((uint8_t*)boxNum); } // //Sends inference results and images to presenter Server for display // SendImage(detectResults, frameData, frameWidth, frameHeight); return detectResults; } aclError ModelProcess::WriteResult(const std::vector<ObjDetectInfo> &objInfos, int frameIndex) const { std::string timeString; GetCurTimeString(timeString); // Create result file under result directory // SetFileDefaultUmask(); std::string resultName = "./out/result/result_" + std::to_string(frameIndex); std::string fileNameSave = "./out/result/result_" + std::to_string(frameIndex); std::ofstream tfile(resultName, std::ios::app); // Check result file validity if (tfile.fail()) { ATLAS_LOG_ERROR("Failed to open result file: %s", resultName.c_str()); return ACL_ERROR_MEMORY_ADDRESS_UNALIGNED; } tfile.seekp(0, tfile.end); size_t dstFileSize = tfile.tellp(); tfile.close(); // if (dstFileSize > FILE_SIZE) { // if (access(resultBakName_.c_str(), 0) == APP_ERR_OK) { // APP_ERROR ret = remove(resultBakName_.c_str()); // if (ret != APP_ERR_OK) { // LogError << "remove " << resultBakName_ << " failed." << std::endl; // return ret; // } // } // APP_ERROR ret = rename(resultName.c_str(), resultBakName_.c_str()); // if (ret != APP_ERR_OK) { // LogError << "rename " << resultName << " failed." << std::endl; // return ret; // } // } tfile.open(resultName, std::ios::out); if (tfile.fail()) { ATLAS_LOG_ERROR("Failed to open result file: %s", resultName.c_str()); return ACL_ERROR_MEMORY_ADDRESS_UNALIGNED; } tfile << "[Date:" << timeString << " Frame:" << frameIndex << "] Object detected number is " << objInfos.size() << std::endl; // Write inference result into file std::cout <<"[Date:" << timeString <<" Frame:" << frameIndex << "] Object detected number is " << objInfos.size() << std::endl; for (uint32_t i = 0; i < objInfos.size(); i++) { tfile << "#Obj" << i << ", " << "box(" << objInfos[i].leftTopX << ", " << objInfos[i].leftTopY << ", " << objInfos[i].rightBotX << ", " << objInfos[i].rightBotY << ") " << " confidence: " << objInfos[i].confidence << " lable: " << objInfos[i].classId << std::endl; } // for (uint32_t i = 0; i < objInfos.size(); i++) { // std::cout << "#Obj" << i << ", " << "box(" << objInfos[i].leftTopX << ", " << objInfos[i].leftTopY << ", " // << objInfos[i].rightBotX << ", " << objInfos[i].rightBotY << ") " // << " confidence: " << objInfos[i].confidence << " lable: " << objInfos[i].classId << std::endl; // } tfile << std::endl; tfile.close(); return ACL_ERROR_NONE; } aclError ModelProcess::GetObjectInfoYolo(std::vector<RawData> &modelOutput, std::vector<ObjDetectInfo> &objInfos, int frameWidth, int frameHeight) { std::vector<std::shared_ptr<void>> hostPtr; for (size_t i = 0; i < modelOutput.size(); i++) { void *hostPtrBuffer = outputDataBuffers[i]; std::shared_ptr<void> hostPtrBufferManager(hostPtrBuffer, [](void *) {}); aclError ret = aclrtMemcpy(hostPtrBuffer, modelOutput[i].lenOfByte, modelOutput[i].data, modelOutput[i].lenOfByte, ACL_MEMCPY_DEVICE_TO_HOST); if (ret!= ACL_ERROR_NONE || hostPtrBuffer == nullptr) { ATLAS_LOG_ERROR("Failed to copy output buffer of model from device to host, ret =%d", ret); return ret; } hostPtr.push_back(hostPtrBufferManager); } YoloImageInfo yoloImageInfo = {}; yoloImageInfo.imgWidth = frameWidth; yoloImageInfo.imgHeight = frameHeight; yoloImageInfo.modelWidth = modelWidth; yoloImageInfo.modelHeight = modelHeight; Yolov4DetectionOutput(hostPtr, objInfos, yoloImageInfo); return ACL_ERROR_NONE; } vector<DetectionResult> ModelProcess::PostProcessYolov4(int frameWidth, int frameHeight){ std::vector<RawData> Output; // std::vector<void*> inferOutputBuffers = GetOutputDataBuffers(); // std::vector<size_t> inferOutputSizes = GetOutputBufferSizes(); int size = outputDataBuffers.size(); for(int i = 0; i < size; ++i){ RawData rawData = RawData(); // rawData.data.reset(outputDataBuffers[i], [](void*) {}); rawData.data = outputDataBuffers[i]; rawData.lenOfByte = outputDataBufferSizes[i]; Output.push_back(std::move(rawData)); } size_t outputLength = Output.size(); if(outputLength <= 0){ ATLAS_LOG_ERROR("Failed to get model infer output data"); // return ACL_ERROR_MEMORY_ADDRESS_UNALIGNED; } std::vector<ObjDetectInfo> objInfos; static int frameIndex = 0; aclError ret = GetObjectInfoYolo(Output, objInfos, frameWidth, frameHeight); if(ret != ACL_ERROR_NONE){ ATLAS_LOG_ERROR("Falied to get TensorFlow model output, ret = %d", ret); // return ret; } vector<DetectionResult> detectResults; for(int i = 0; i < objInfos.size(); i++){ DetectionResult oneResult; Point point_lt, point_rb; //get the confidence of the detected object. Anything less than 0.8 is considered invalid uint32_t score = (uint32_t)(objInfos[i].confidence * 100); if (score < 80) continue; ATLAS_LOG_INFO("infer score %d", score); //get the frame coordinates and converts them to the coordinates on the original frame oneResult.lt.x = objInfos[i].leftTopX; oneResult.lt.y = objInfos[i].leftTopY; oneResult.rb.x = objInfos[i].rightBotX; oneResult.rb.y = objInfos[i].rightBotY; //Construct a string that marks the object: object name + confidence uint32_t objIndex = (uint32_t)objInfos[i].classId; oneResult.result_text = yolov4Label[objIndex] + std::to_string(score) + "\%"; ATLAS_LOG_INFO("%d %d %d %d %s\n", oneResult.lt.x, oneResult.lt.y, oneResult.rb.x, oneResult.rb.y, oneResult.result_text.c_str()); detectResults.emplace_back(oneResult); } // // 手动提取3个feature,用python文件解析 // static int imageNum = 0; // int tensorNum = 1; // for(int i = 0; i < outputDataBuffers.size(); ++i){ // std::string fileNameSave = "./results/output" + std::to_string(imageNum) + "_" // + std::to_string(tensorNum ) + ".bin"; // FILE* output = fopen(fileNameSave.c_str(), "wb+"); // void* data = outputDataBuffers[i]; // int sizeData = outputDataBufferSizes[i]; // size_t num = fwrite(data, 1, sizeData, output); // std::cout << "write sizeData 0 : " << num << std::endl; // fclose(output); // if(tensorNum == 3){ // break; // } // ++tensorNum; // } // ++imageNum; return detectResults; // ret = WriteResult(objInfos, frameIndex); // if(ret != ACL_ERROR_NONE){ // ATLAS_LOG_ERROR("Failed to wrtie result, ret = %d", ret); // return ret; // } // ++frameIndex; // return ACL_ERROR_NONE; }
34.265604
150
0.642508
WinstonLy
706b84b8d5d50d8fa16324be5090ef7054a4d0e5
7,740
cpp
C++
src/core/MidiCCToCV.cpp
romsom/Rack
82ddeb946d576b5d5c6ee1be4d8abbe921484dfc
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/core/MidiCCToCV.cpp
romsom/Rack
82ddeb946d576b5d5c6ee1be4d8abbe921484dfc
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/core/MidiCCToCV.cpp
romsom/Rack
82ddeb946d576b5d5c6ee1be4d8abbe921484dfc
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
#include <list> #include <algorithm> #include "rtmidi/RtMidi.h" #include "core.hpp" #include "MidiIO.hpp" struct CCValue { int val = 0; // Controller value TransitionSmoother tSmooth; int num = 0; // Controller number bool numInited = false; // Num inited by config file bool numSelected = false; // Text field selected for midi learn bool changed = false; // Value has been changed by midi message (only if it is in sync!) int sync = 0; // Output value sync (implies diff) bool syncFirst = true; // First value after sync was reset void resetSync() { sync = 0; syncFirst = true; } }; struct MIDICCToCVInterface : MidiIO, Module { enum ParamIds { NUM_PARAMS }; enum InputIds { NUM_INPUTS }; enum OutputIds { NUM_OUTPUTS = 16 }; enum LightIds { NUM_LIGHTS = 16 }; CCValue cc[NUM_OUTPUTS]; MIDICCToCVInterface() : MidiIO(), Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) { for (int i = 0; i < NUM_OUTPUTS; i++) { cc[i].num = i; } } ~MIDICCToCVInterface() {} void step() override; void processMidi(std::vector<unsigned char> msg); void resetMidi() override; json_t *toJson() override { json_t *rootJ = json_object(); addBaseJson(rootJ); for (int i = 0; i < NUM_OUTPUTS; i++) { json_object_set_new(rootJ, ("ccNum" + std::to_string(i)).c_str(), json_integer(cc[i].num)); if (outputs[i].active) { json_object_set_new(rootJ, ("ccVal" + std::to_string(i)).c_str(), json_integer(cc[i].val)); } } return rootJ; } void fromJson(json_t *rootJ) override { baseFromJson(rootJ); for (int i = 0; i < NUM_OUTPUTS; i++) { json_t *ccNumJ = json_object_get(rootJ, ("ccNum" + std::to_string(i)).c_str()); if (ccNumJ) { cc[i].num = json_integer_value(ccNumJ); cc[i].numInited = true; } json_t *ccValJ = json_object_get(rootJ, ("ccVal" + std::to_string(i)).c_str()); if (ccValJ) { cc[i].val = json_integer_value(ccValJ); cc[i].tSmooth.set((cc[i].val / 127.0 * 10.0), (cc[i].val / 127.0 * 10.0)); cc[i].resetSync(); } } } void reset() override { resetMidi(); } }; void MIDICCToCVInterface::step() { if (isPortOpen()) { std::vector<unsigned char> message; // midiIn->getMessage returns empty vector if there are no messages in the queue getMessage(&message); while (message.size() > 0) { processMidi(message); getMessage(&message); } } for (int i = 0; i < NUM_OUTPUTS; i++) { lights[i].setBrightness(cc[i].sync / 127.0); if (cc[i].changed) { cc[i].tSmooth.set(outputs[i].value, (cc[i].val / 127.0 * 10.0), int(engineGetSampleRate() / 32)); cc[i].changed = false; } outputs[i].value = cc[i].tSmooth.next(); } } void MIDICCToCVInterface::resetMidi() { for (int i = 0; i < NUM_OUTPUTS; i++) { cc[i].val = 0; cc[i].resetSync(); cc[i].tSmooth.set(0,0); } }; void MIDICCToCVInterface::processMidi(std::vector<unsigned char> msg) { int channel = msg[0] & 0xf; int status = (msg[0] >> 4) & 0xf; int data1 = msg[1]; int data2 = msg[2]; //fprintf(stderr, "channel %d status %d data1 %d data2 %d\n", channel, status, data1,data2); // Filter channels if (this->channel >= 0 && this->channel != channel) return; if (status == 0xb) { for (int i = 0; i < NUM_OUTPUTS; i++) { if (cc[i].numSelected) { cc[i].resetSync(); cc[i].num = data1; } if (data1 == cc[i].num) { /* If the first value we received after sync was reset is +/- 1 of * the output value the values are in sync*/ if (cc[i].syncFirst) { cc[i].syncFirst = false; if (data2 < cc[i].val + 2 && data2 > cc[i].val - 2) { cc[i].sync = 0; }else { cc[i].sync = absi(data2 - cc[i].val); } return; } if (cc[i].sync == 0) { cc[i].val = data2; cc[i].changed = true; } else { cc[i].sync = absi(data2 - cc[i].val); } } } } } struct CCTextField : TextField { void onTextChange() override; void draw(NVGcontext *vg) override; void onMouseDown(EventMouseDown &e) override; void onMouseUp(EventMouseUp &e) override; void onMouseLeave(EventMouseLeave &e) override; int outNum; MIDICCToCVInterface *module; }; void CCTextField::draw(NVGcontext *vg) { /* This is necessary, since the save * file is loaded after constructing the widget*/ if (module->cc[outNum].numInited) { module->cc[outNum].numInited = false; text = std::to_string(module->cc[outNum].num); } /* If number is selected for midi learn*/ if (module->cc[outNum].numSelected) { text = std::to_string(module->cc[outNum].num); } TextField::draw(vg); } void CCTextField::onMouseUp(EventMouseUp &e) { if (e.button == 1) { module->cc[outNum].numSelected = false; e.consumed = true; } TextField::onMouseUp(e); } void CCTextField::onMouseDown(EventMouseDown &e) { if (e.button == 1) { module->cc[outNum].numSelected = true; e.consumed = true; } TextField::onMouseDown(e); } void CCTextField::onMouseLeave(EventMouseLeave &e) { module->cc[outNum].numSelected = false; e.consumed = true; } void CCTextField::onTextChange() { if (text.size() > 0) { try { int num = std::stoi(text); // Only allow valid cc numbers if (num < 0 || num > 127 || text.size() > 3) { text = ""; begin = end = 0; module->cc[outNum].num = -1; } else { module->cc[outNum].num = num; module->cc[outNum].resetSync(); } } catch (...) { text = ""; begin = end = 0; module->cc[outNum].num = -1; } }; } MIDICCToCVWidget::MIDICCToCVWidget() { MIDICCToCVInterface *module = new MIDICCToCVInterface(); setModule(module); box.size = Vec(16 * 15, 380); { Panel *panel = new LightPanel(); panel->box.size = box.size; addChild(panel); } float margin = 5; float labelHeight = 15; float yPos = margin; addChild(createScrew<ScrewSilver>(Vec(15, 0))); addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 0))); addChild(createScrew<ScrewSilver>(Vec(15, 365))); addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 365))); { Label *label = new Label(); label->box.pos = Vec(box.size.x - margin - 11 * 15, margin); label->text = "MIDI CC to CV"; addChild(label); yPos = labelHeight * 2; } { Label *label = new Label(); label->box.pos = Vec(margin, yPos); label->text = "MIDI Interface"; addChild(label); MidiChoice *midiChoice = new MidiChoice(); midiChoice->midiModule = dynamic_cast<MidiIO *>(module); midiChoice->box.pos = Vec((box.size.x - 10) / 2 + margin, yPos); midiChoice->box.size.x = (box.size.x / 2.0) - margin; addChild(midiChoice); yPos += midiChoice->box.size.y + margin; } { Label *label = new Label(); label->box.pos = Vec(margin, yPos); label->text = "Channel"; addChild(label); ChannelChoice *channelChoice = new ChannelChoice(); channelChoice->midiModule = dynamic_cast<MidiIO *>(module); channelChoice->box.pos = Vec((box.size.x - 10) / 2 + margin, yPos); channelChoice->box.size.x = (box.size.x / 2.0) - margin; addChild(channelChoice); yPos += channelChoice->box.size.y + margin * 3; } for (int i = 0; i < MIDICCToCVInterface::NUM_OUTPUTS; i++) { CCTextField *ccNumChoice = new CCTextField(); ccNumChoice->module = module; ccNumChoice->outNum = i; ccNumChoice->text = std::to_string(module->cc[i].num); ccNumChoice->box.pos = Vec(11 + (i % 4) * (63), yPos); ccNumChoice->box.size.x = 29; addChild(ccNumChoice); yPos += labelHeight + margin; addOutput(createOutput<PJ3410Port>(Vec((i % 4) * (63) + 10, yPos + 5), module, i)); addChild(createLight<SmallLight<RedLight>>(Vec((i % 4) * (63) + 32, yPos + 5), module, i)); if ((i + 1) % 4 == 0) { yPos += 47 + margin; } else { yPos -= labelHeight + margin; } } } void MIDICCToCVWidget::step() { ModuleWidget::step(); }
24.037267
100
0.630749
romsom
706bbd23157fb1b239e789593963a97aacd8a4cd
790
cpp
C++
call_by_ref.cpp
kangwonlee/cpp_study
22e2da7334ad273e6ba02a1928a323519bf9cabf
[ "BSD-3-Clause" ]
null
null
null
call_by_ref.cpp
kangwonlee/cpp_study
22e2da7334ad273e6ba02a1928a323519bf9cabf
[ "BSD-3-Clause" ]
8
2018-10-07T12:54:08.000Z
2019-05-22T03:07:00.000Z
call_by_ref.cpp
kangwonlee/cpp_study
22e2da7334ad273e6ba02a1928a323519bf9cabf
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <iomanip> using namespace std; void accumulate_array_ptr(double *, const double); void accumulate_array_ref(double &, const double); int main(const int argn, char *argv[]){ double update_this_with_pointer = 0.0; double update_this_with_reference = 0.0; for(int i=0; 10 > i; ++i){ accumulate_array_ptr(& update_this_with_pointer, (double) i); accumulate_array_ref(update_this_with_reference, (double) i); } cout << "Pointer result = " << update_this_with_pointer << '\n'; cout << "Reference result = " << update_this_with_reference << '\n'; return 0; } void accumulate_array_ptr(double * s, const double a){ *s += a; } void accumulate_array_ref(double & t, const double a){ t += a; }
24.6875
72
0.660759
kangwonlee
706ee3bec8672761b1da3de992eb5c96fb5c21d8
19,245
cpp
C++
src/sprite.cpp
Kozma04/TinyCADE
fc4d2f070630e7c853591a5aa0dd9c421b53ee42
[ "MIT" ]
1
2022-03-22T06:21:30.000Z
2022-03-22T06:21:30.000Z
src/sprite.cpp
Kozma04/TinyCADE
fc4d2f070630e7c853591a5aa0dd9c421b53ee42
[ "MIT" ]
null
null
null
src/sprite.cpp
Kozma04/TinyCADE
fc4d2f070630e7c853591a5aa0dd9c421b53ee42
[ "MIT" ]
null
null
null
#include "sprite.h" #define SHIFT_MASK() \ mask >>= 1; \ if(mask == 0) { \ mask = 0b10000000; \ p_spr++; \ foo++; \ } #define SHIFT_MASK_ALPHA() \ mask >>= 1; \ if(mask == 0) { \ mask = 0b10000000; \ p_spr++; \ p_spr_a++; \ foo++; \ } #define SPR_COORDS_CHECK() \ if(screenX + sprW < 0 || screenY + sprH < 0 || screenX >= 128 || screenY >= 64) \ return; \ if(screenX < 0) { \ sprX -= screenX; \ sprW += screenX; \ screenX = 0; \ } \ if(screenX + sprW >= 128) { \ sprW = 128 - screenX; \ } \ if(screenY < 0) { \ sprY -= screenY; \ sprH += screenY; \ screenY = 0; \ } \ if(screenY + sprH >= 64) { \ sprH = 64 - screenY; \ } \ extern "C" { uint8_t inv_shift_lut[8] = { 0b10000000, 0b01000000, 0b00100000, 0b00010000, 0b00001000, 0b00000100, 0b00000010, 0b00000001 }; } uint8_t get_pixel_4bpp(sprite_t* spr, uint8_t x, uint8_t y) { uint8_t p = *(spr->data + ((uint16_t(y) * spr->width + x) >> 1)); if(x & 1) return p & 0xf; return p >> 4; } uint8_t get_pixel_4bpp_progmem(sprite_t* spr, uint8_t x, uint8_t y) { uint8_t p = pgm_read_byte(spr->data + ((uint16_t(y) * spr->width + x) >> 1)); if(x & 1) return p & 0xf; return p >> 4; } void draw_sprite_1bpp_int(sprite_t* spr, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { uint8_t *p_fb = oled_framebuffer + (screenY * 128 + screenX) / 2; uint8_t *p_spr = spr->data + (sprY * (spr->width_d8 + ((((sprW + sprX) & 7) || (((sprW + sprX) ^ 0xff) & 7)) ? 1 : 0)) + sprX / 8); uint8_t mask = inv_shift_lut[sprX & 7]; uint8_t pal0 = sprPal & 0xf; uint8_t pal1 = sprPal >> 4; uint8_t out; uint8_t x; uint8_t foo; for(uint8_t y = 0; y < sprH; y++) { x = 0; foo = 0; if(screenX & 1) { // odd x++; if((*p_spr) & mask) out = pal1; else out = pal0; *p_fb = (*p_fb & 0xf0) | out; *p_fb++; SHIFT_MASK(); } for(; x <= sprW - 2; x += 2) { if((*p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; SHIFT_MASK(); if((*p_spr) & mask) out |= pal1; else out |= pal0; SHIFT_MASK(); *(p_fb++) = out; } if(x < sprW) { if((*p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; *p_fb = (*p_fb & 0x0f) | out; if((x & 1) == 0) p_fb++; SHIFT_MASK(); } p_fb += (128 - sprW) >> 1; p_spr += (spr->width_d8 - foo); if((sprW + sprX) & 7) p_spr++; else if(((sprW + sprX) ^ 0xff) & 7) p_spr++; mask = inv_shift_lut[sprX & 7]; } } void draw_sprite_1bpp_alpha_int(sprite_t *spr, sprite_t *alpha, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { uint16_t ptr_add = (sprY * (spr->width_d8 + ((((sprW + sprX) & 7) || (((sprW + sprX) ^ 0xff) & 7)) ? 1 : 0)) + sprX / 8); uint8_t *p_fb = oled_framebuffer + (screenY * 128 + screenX) / 2; uint8_t *p_spr = spr->data + ptr_add; uint8_t *p_spr_a = alpha->data + ptr_add; uint8_t mask = inv_shift_lut[sprX & 7]; uint8_t pal0 = sprPal & 0xf; uint8_t pal1 = sprPal >> 4; uint8_t out; uint8_t x; uint8_t na; uint8_t foo; for(uint8_t y = 0; y < sprH; y++) { x = 0; foo = 0; if(screenX & 1) { // odd x++; if(*p_spr_a & mask) { if((*p_spr) & mask) out = pal1; else out = pal0; *(p_fb++) = (*p_fb & 0xf0) | out; } else p_fb++; SHIFT_MASK_ALPHA(); } for(; x <= sprW - 2; x += 2) { out = 0; na = 0; if(*p_spr_a & mask) { na = 0b10; if((*p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; } SHIFT_MASK_ALPHA(); if(*p_spr_a & mask) { na |= 1; if((*p_spr) & mask) out |= pal1; else out |= pal0; } SHIFT_MASK_ALPHA(); if(na == 0b11) *(p_fb++) = out; else if(na == 0b10) *(p_fb++) = (*p_fb & 0xf) | out; else if(na == 0b1) *(p_fb++) = (*p_fb & 0xf0) | out; else p_fb++; } if(x < sprW) { if(*p_spr_a & mask) { if((*p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; *p_fb = (*p_fb & 0x0f) | out; } if((x & 1) == 0) p_fb++; SHIFT_MASK_ALPHA(); } p_fb += (128 - sprW) >> 1; p_spr += (spr->width_d8 - foo); p_spr_a += (spr->width_d8 - foo); if((sprW + sprX) & 7) p_spr++, p_spr_a++; else if(((sprW + sprX) ^ 0xff) & 7) p_spr++, p_spr_a++; mask = inv_shift_lut[sprX & 7]; } } void draw_sprite_1bpp_progmem_int(sprite_t *spr, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { uint8_t *p_fb = oled_framebuffer + (screenY * 128 + screenX) / 2; uint8_t *p_spr = spr->data + (sprY * (spr->width_d8 + ((((sprW + sprX) & 7) || (((sprW + sprX) ^ 0xff) & 7)) ? 1 : 0)) + sprX / 8); uint8_t mask = inv_shift_lut[sprX & 7]; uint8_t pal0 = sprPal & 0xf; uint8_t pal1 = sprPal >> 4; uint8_t out; uint8_t x; for(uint8_t y = 0; y < sprH; y++) { x = 0; uint8_t foo = 0; if(screenX & 1) { // odd x++; if(pgm_read_byte(p_spr) & mask) out = pal1; else out = pal0; *p_fb = (*p_fb & 0xf0) | out; p_fb++; SHIFT_MASK(); } for(; x <= sprW - 2; x += 2) { if(pgm_read_byte(p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; SHIFT_MASK(); if(pgm_read_byte(p_spr) & mask) out |= pal1; else out |= pal0; SHIFT_MASK(); *(p_fb++) = out; } if(x < sprW) { if(pgm_read_byte(p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; *p_fb = (*p_fb & 0x0f) | out; if((x & 1) == 0) p_fb++; SHIFT_MASK(); } p_fb += (128 - sprW) >> 1; p_spr += spr->width_d8 - foo; mask = inv_shift_lut[sprX & 7]; if((sprW + sprX) & 7) p_spr++; else if(((sprW + sprX) ^ 0xff) & 7) p_spr++; } } void draw_sprite_1bpp_alpha_progmem_int(sprite_t *spr, sprite_t *alpha, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { uint16_t ptr_add = (sprY * (spr->width_d8 + ((((sprW + sprX) & 7) || (((sprW + sprX) ^ 0xff) & 7)) ? 1 : 0)) + sprX / 8); uint8_t *p_fb = oled_framebuffer + (screenY * 128 + screenX) / 2; uint8_t *p_spr = spr->data + ptr_add; uint8_t *p_spr_a = alpha->data + ptr_add; uint8_t mask = inv_shift_lut[sprX & 7]; uint8_t pal0 = sprPal & 0xf; uint8_t pal1 = sprPal >> 4; uint8_t out; uint8_t x; uint8_t na; for(uint8_t y = 0; y < sprH; y++) { x = 0; uint8_t foo = 0; if(screenX & 1) { // odd x++; if(pgm_read_byte(p_spr_a) & mask) { if(pgm_read_byte(p_spr) & mask) out = pal1; else out = pal0; *(p_fb++) = (*p_fb & 0xf0) | out; } else p_fb++; SHIFT_MASK_ALPHA(); } for(; x <= sprW - 2; x += 2) { out = 0; na = 0; if(pgm_read_byte(p_spr_a) & mask) { na = 0b10; if(pgm_read_byte(p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; } SHIFT_MASK_ALPHA(); if(pgm_read_byte(p_spr_a) & mask) { na |= 1; if(pgm_read_byte(p_spr) & mask) out |= pal1; else out |= pal0; } SHIFT_MASK_ALPHA(); if(na == 0b11) *(p_fb++) = out; else if(na == 0b10) *(p_fb++) = (*p_fb & 0xf) | out; else if(na == 0b1) *(p_fb++) = (*p_fb & 0xf0) | out; else p_fb++; } if(x < sprW) { if(pgm_read_byte(p_spr_a) & mask) { if(pgm_read_byte(p_spr) & mask) out = pal1 << 4; else out = pal0 << 4; *p_fb = (*p_fb & 0x0f) | out; } if((x & 1) == 0) p_fb++; SHIFT_MASK_ALPHA(); } p_fb += (128 - sprW) >> 1; p_spr += spr->width_d8 - foo; p_spr_a += spr->width_d8 - foo; mask = inv_shift_lut[sprX & 7]; if((sprW + sprX) & 7) p_spr++, p_spr_a++; else if(((sprW + sprX) ^ 0xff) & 7) p_spr++, p_spr_a++; } } void draw_sprite_4bpp_int(sprite_t *spr, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH) { uint8_t *p_fb = oled_framebuffer + (screenY * 128 + screenX) / 2; uint8_t *p_spr = spr->data + (uint16_t(sprY) * spr->width + sprX) / 2; uint8_t x; uint8_t out; if((screenX & 1) == 0) { // even for(uint8_t y = 0; y < sprH; y++) { x = 0; if((sprX & 1) == 1) { // odd for(; x <= sprW - 2; x += 2) { out = (*(p_spr++) & 0xf) << 4; out |= (*p_spr & 0xf0) >> 4; *(p_fb++) = out; } if(x < sprW) { *(p_fb++) = (*p_fb & 0xf) | ((*(p_spr++) & 0xf) << 4); } } else { for(; x <= sprW - 2; x += 2) { *(p_fb++) = *(p_spr++); } if(x < sprW) { *(p_fb++) = (*p_fb & 0xf) | ((*(p_spr++) & 0xf0)); } } p_fb += (128 - sprW) >> 1; p_spr += (spr->width - sprW) >> 1; } } else { // odd for(uint8_t y = 0; y < sprH; y++) { x = 1; if((sprX & 1) == 1) { // odd *(p_fb++) = (*p_fb & 0xf0) | (*(p_spr++) & 0xf); for(; x <= sprW - 2; x += 2) { *(p_fb++) = *(p_spr++); } if(x < sprW) { *(p_fb++) = (*p_fb & 0xf) | ((*(p_spr) & 0xf0)); } else p_spr++; } else { *(p_fb++) = (*p_fb & 0xf0) | ((*(p_spr) & 0xf0) >> 4); for(; x <= sprW - 2; x += 2) { out = (*(p_spr++) & 0xf) << 4; out |= (*p_spr & 0xf0) >> 4; *(p_fb++) = out; } if(x < sprW) { *(p_fb++) = (*p_fb & 0xf) | ((*(p_spr++) & 0xf) << 4); } else p_spr++; } p_fb += (128 - sprW - 1) >> 1; p_spr += (spr->width - sprW) >> 1; } } } void draw_sprite_4bpp_alpha_int(sprite_t *spr, sprite_t *alpha, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH) { uint16_t alpha_ptr_add = (sprY * (spr->width_d8 + ((((sprW + sprX) & 7) || (((sprW + sprX) ^ 0xff) & 7)) ? 1 : 0)) + sprX / 8); uint8_t *p_fb = oled_framebuffer + (screenY * 128 + screenX) / 2; uint8_t *p_spr4 = spr->data + (uint16_t(sprY) * spr->width + sprX) / 2; uint8_t *p_spr = alpha->data + alpha_ptr_add; uint8_t mask = inv_shift_lut[sprX & 7]; uint8_t x; uint8_t out; uint8_t foo, na; if((screenX & 1) == 0) { // even for(uint8_t y = 0; y < sprH; y++) { foo = 0; x = 0; out = 0; if((sprX & 1) == 1) { // odd for(; x <= sprW - 2; x += 2) { out = 0, na = 0; if(*p_spr & mask) { na = 0b10; out = (*(p_spr4) & 0xf) << 4; } SHIFT_MASK(); p_spr4++; if(*p_spr & mask) { na |= 1; out |= (*p_spr4 & 0xf0) >> 4; } SHIFT_MASK(); if(na == 0b11) *(p_fb++) = out; else if(na == 0b10) *(p_fb++) = (*p_fb & 0xf) | out; else if(na == 0b1) *(p_fb++) = (*p_fb & 0xf0) | out; else p_fb++; } if(x < sprW) { if(*p_spr & mask) { *p_fb = (*p_fb & 0xf) | ((*(p_spr4) & 0xf) << 4); } SHIFT_MASK(); p_fb++; p_spr4++; } else p_spr4++; } else { for(; x <= sprW - 2; x += 2) { out = 0, na = 0; if(*p_spr & mask) { na = 0b10; out = (*(p_spr4) & 0xf0); } SHIFT_MASK(); if(*p_spr & mask) { na |= 1; out |= (*(p_spr4) & 0xf); } SHIFT_MASK(); if(na == 0b11) *(p_fb++) = out; else if(na == 0b10) *(p_fb++) = (*p_fb & 0xf) | out; else if(na == 0b1) *(p_fb++) = (*p_fb & 0xf0) | out; else p_fb++; p_spr4++; } if(x < sprW) { if(*p_spr & mask) { *p_fb = (*p_fb & 0xf) | ((*(p_spr4) & 0xf0)); } p_fb++; p_spr4++; SHIFT_MASK(); } } p_fb += (128 - sprW) >> 1; p_spr4 += (spr->width - sprW) >> 1; p_spr += spr->width_d8 - foo; mask = inv_shift_lut[sprX & 7]; if((sprW + sprX) & 7) p_spr++; else if(((sprW + sprX) ^ 0xff) & 7) p_spr++; } } // TODO COMPLETE else { // odd for(uint8_t y = 0; y < sprH; y++) { x = 1; foo = 0; out = 0; if((sprX & 1) == 1) { // odd if(*p_spr & mask) { *(p_fb) = (*p_fb & 0xf0) | (*(p_spr4) & 0xf); } p_fb++; p_spr4++; SHIFT_MASK(); for(; x <= sprW - 2; x += 2) { out = 0, na = 0; if(*p_spr & mask) { na = 0b10; out = *(p_spr4) & 0xf0; } SHIFT_MASK(); if(*p_spr & mask) { na |= 0b1; out |= *(p_spr4) & 0xf; } SHIFT_MASK(); if(na == 0b11) *(p_fb++) = out; else if(na == 0b10) *(p_fb++) = (*p_fb & 0xf) | out; else if(na == 0b1) *(p_fb++) = (*p_fb & 0xf0) | out; else p_fb++; p_spr4++; } if(x < sprW) { //*(p_fb++) = (*p_fb & 0xf) | ((*(p_spr4) & 0xf0)); if(*p_spr & mask) { *p_fb = (*p_fb & 0xf) | ((*(p_spr4) & 0xf0)); } SHIFT_MASK(); p_fb++; } else p_spr4++; } else { if(*p_spr & mask) { *p_fb = (*p_fb & 0xf0) | ((*(p_spr4) & 0xf0) >> 4); } p_fb++; SHIFT_MASK(); for(; x <= sprW - 2; x += 2) { out = 0, na = 0; if(*p_spr & mask) { na = 0b10; out = (*p_spr4 & 0xf) << 4; } p_spr4++; SHIFT_MASK(); if(*p_spr & mask) { na |= 1; out |= (*p_spr4 & 0xf0) >> 4; } SHIFT_MASK(); if(na == 0b11) *(p_fb++) = out; else if(na == 0b10) *(p_fb++) = (*p_fb & 0xf) | out; else if(na == 0b1) *(p_fb++) = (*p_fb & 0xf0) | out; else p_fb++; } if(x < sprW) { if(*p_spr & mask) { *p_fb = (*p_fb & 0xf) | ((*p_spr4 & 0xf) << 4); } SHIFT_MASK(); p_fb++; p_spr4++; } else p_spr4++; } p_fb += (128 - sprW - 1) >> 1; p_spr4 += (spr->width - sprW) >> 1; p_spr += spr->width_d8 - foo; mask = inv_shift_lut[sprX & 7]; if((sprW + sprX) & 7) p_spr++; else if(((sprW + sprX) ^ 0xff) & 7) p_spr++; } } } void draw_sprite_1bpp(sprite_t* spr, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { SPR_COORDS_CHECK(); draw_sprite_1bpp_int(spr, screenX, screenY, sprX, sprY, sprW, sprH, sprPal); } void draw_sprite_1bpp_alpha(sprite_t *spr, sprite_t *alpha, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { SPR_COORDS_CHECK(); draw_sprite_1bpp_alpha_int(spr, alpha, screenX, screenY, sprX, sprY, sprW, sprH, sprPal); } void draw_sprite_1bpp_progmem(sprite_t *spr, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { SPR_COORDS_CHECK(); draw_sprite_1bpp_progmem_int(spr, screenX, screenY, sprX, sprY, sprW, sprH, sprPal); } void draw_sprite_1bpp_alpha_progmem(sprite_t *spr, sprite_t *alpha, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH, uint8_t sprPal) { SPR_COORDS_CHECK(); draw_sprite_1bpp_alpha_progmem_int(spr, alpha, screenX, screenY, sprX, sprY, sprW, sprH, sprPal); } void draw_sprite_4bpp(sprite_t *spr, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH) { SPR_COORDS_CHECK(); draw_sprite_4bpp_int(spr, screenX, screenY, sprX, sprY, sprW, sprH); } void draw_sprite_4bpp_alpha(sprite_t *spr, sprite_t *alpha, int16_t screenX, int16_t screenY, uint8_t sprX, uint8_t sprY, uint8_t sprW, uint8_t sprH) { SPR_COORDS_CHECK(); draw_sprite_4bpp_alpha_int(spr, alpha, screenX, screenY, sprX, sprY, sprW, sprH); }
33.645105
179
0.406547
Kozma04
706ee5f7563b307d781e800085257e849b1c33cd
798
cpp
C++
tests/v2/url/url_literal_tests.cpp
BioDataAnalysis/url
281501b0fdf00b52eeb114f6856a9a83004d204e
[ "BSL-1.0" ]
47
2019-08-24T13:43:45.000Z
2022-02-21T11:45:19.000Z
tests/v2/url/url_literal_tests.cpp
BioDataAnalysis/url
281501b0fdf00b52eeb114f6856a9a83004d204e
[ "BSL-1.0" ]
35
2018-10-13T10:35:00.000Z
2021-06-11T12:23:55.000Z
tests/v2/url/url_literal_tests.cpp
BioDataAnalysis/url
281501b0fdf00b52eeb114f6856a9a83004d204e
[ "BSL-1.0" ]
25
2019-02-19T02:46:21.000Z
2021-10-21T14:53:00.000Z
// Copyright 2019-20 Glyn Matthews // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt of copy at // http://www.boost.org/LICENSE_1_0.txt) #include <algorithm> #include <memory> #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <skyr/v2/url.hpp> using namespace skyr::literals; TEST_CASE("url_tests", "[url]") { SECTION("construct url from literal") { CHECK_NOTHROW("http://www.example.com/"_url); } SECTION("construct url from wchar_t literal") { CHECK_NOTHROW(L"http://www.example.com/"_url); } SECTION("construct url from char16_t literal") { CHECK_NOTHROW(u"http://www.example.com/"_url); } SECTION("construct url from char32_t literal") { CHECK_NOTHROW(U"http://www.example.com/"_url); } }
25.741935
61
0.709273
BioDataAnalysis
706f56f53f8bce06c9f8b77c225bf1d16e312755
5,117
cpp
C++
Win32xx/samples/GDIPlus/src/GDIPlusView.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
2
2021-03-25T04:19:22.000Z
2021-05-03T03:23:30.000Z
Win32xx/samples/GDIPlus/src/GDIPlusView.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
null
null
null
Win32xx/samples/GDIPlus/src/GDIPlusView.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
1
2020-12-28T08:53:42.000Z
2020-12-28T08:53:42.000Z
////////////////////////////////////////////// // GDIPlusView.cpp // Definitions for the CGDIPlusView class #include "stdafx.h" #include "GDIPlusView.h" using namespace Gdiplus; CGDIPlusView::CGDIPlusView() { // Initialize GDI+. GdiplusStartupInput gdiplusStartupInput; GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL); } CGDIPlusView::~CGDIPlusView() { // Shutdown GDI+ GdiplusShutdown(m_gdiplusToken); } void CGDIPlusView::DrawCappedLine(CDC& dc) { Graphics graphics(dc); // Draw capped line, width 8 Pen penCapped(Color(255, 0, 0, 255), 8); penCapped.SetStartCap(LineCapArrowAnchor); penCapped.SetEndCap(LineCapRoundAnchor); graphics.DrawLine(&penCapped, 10, 175, 300, 175); } void CGDIPlusView::DrawGamaShapes(CDC& dc) { Graphics graphics(dc); // Draw Plygons with Gama Corrections // Put the points of a polygon in an array. GraphicsPath pathGama; int yOffset = 200; Point points[] = {Point(75, 0 +yOffset), Point(100, 50+yOffset), Point(150, 50 +yOffset), Point(112, 75+yOffset), Point(150, 150+yOffset), Point(75, 100+yOffset), Point(0, 150+yOffset), Point(37, 75+yOffset), Point(0, 50 +yOffset), Point(50, 50+yOffset)}; // Use the array of points to construct a path. pathGama.AddLines(points, 10); // Use the path to construct a path gradient brush. PathGradientBrush pthGrBrushGama(&pathGama); // Set the color at the center of the path to red. pthGrBrushGama.SetCenterColor(Color(255, 255, 0, 0)); // Set the colors of the points in the array. Color colorsGama[] = {Color(255, 0, 0, 0), Color(255, 0, 255, 0), Color(255, 0, 0, 255), Color(255, 255, 255, 255), Color(255, 0, 0, 0), Color(255, 0, 255, 0), Color(255, 0, 0, 255), Color(255, 255, 255, 255), Color(255, 0, 0, 0), Color(255, 0, 255, 0)}; int count = 10; pthGrBrushGama.SetSurroundColors(colorsGama, &count); // Fill the path with the path gradient brush. graphics.FillPath(&pthGrBrushGama, &pathGama); pthGrBrushGama.SetGammaCorrection(TRUE); graphics.TranslateTransform(200.0f, 0.0f); graphics.FillPath(&pthGrBrushGama, &pathGama); } void CGDIPlusView::DrawGradientElipse(CDC& dc) { Graphics graphics(dc); // Create a path that consists of a single ellipse. GraphicsPath path; path.AddEllipse(0, 80, 140, 70); // Use the path to construct a brush. PathGradientBrush pthGrBrush(&path); // Set the color at the center of the path to blue. pthGrBrush.SetCenterColor(Color(255, 0, 0, 255)); // Set the color along the entire boundary of the path to aqua. Color colors[] = {Color(255, 0, 255, 255)}; int count = 1; pthGrBrush.SetSurroundColors(colors, &count); graphics.FillEllipse(&pthGrBrush, 0, 80, 140, 70); } void CGDIPlusView::DrawSolidElipse(CDC& dc) { Graphics graphics(dc); SolidBrush solidBrush(Color(255, 255, 0, 0)); graphics.FillEllipse(&solidBrush, 160, 84, 100, 60); } void CGDIPlusView::DrawSolidLine(CDC& dc) { Graphics graphics(dc); // Draw solid line Pen penLine(Color(255, 0, 0, 255)); graphics.DrawLine(&penLine, 10, 70, 200, 70); } void CGDIPlusView::DrawText(CDC& dc) { Graphics graphics(dc); // Draw some text SolidBrush brush(Color(255, 0, 0, 255)); FontFamily fontFamily(L"Times New Roman"); Font font(&fontFamily, 24, FontStyleRegular, UnitPixel); PointF pointF(10.0f, 20.0f); graphics.DrawString(L"GDI+ Example", -1, &font, pointF, &brush); } void CGDIPlusView::OnDraw(CDC& dc) { DrawSolidLine(dc); DrawText(dc); DrawCappedLine(dc); DrawGradientElipse(dc); DrawSolidElipse(dc); DrawGamaShapes(dc); } void CGDIPlusView::OnInitialUpdate() { // OnInitialUpdate is called immediately after the window is created TRACE("View window created\n"); } void CGDIPlusView::PreCreate(CREATESTRUCT& cs) { // Here we set the defaults used by the create function for the view window // Preforming this is optional, but doing so allows us to // take more precise control over the window we create. // Set the extended style cs.dwExStyle = WS_EX_CLIENTEDGE; } void CGDIPlusView::RegisterClass(WNDCLASS& wc) { // Here we set the Window class parameters. // Preforming this is optional, but doing so allows us to // take more precise control over the type of window we create. // Set the Window Class name wc.lpszClassName = _T("View"); // Set the class style (not to be confused with the window styles set in PreCreate) wc.style = CS_DBLCLKS; // Generate left button double click messages } LRESULT CGDIPlusView::WndProc(UINT msg, WPARAM wparam, LPARAM lparam) { // switch (msg) // { // Add case statements for each messages to be handled here // } // pass unhandled messages on for default processing return WndProcDefault(msg, wparam, lparam); }
29.24
87
0.651554
mufunyo
70715793a716153bbd9fbc8117eac91d14390cde
68,819
cpp
C++
src/qt/src/gui/image/qpixmap.cpp
martende/phantomjs
5cecd7dde7b8fd04ad2c036d16f09a8d2a139854
[ "BSD-3-Clause" ]
1
2015-04-05T12:31:20.000Z
2015-04-05T12:31:20.000Z
src/qt/src/gui/image/qpixmap.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
src/qt/src/gui/image/qpixmap.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qglobal.h> #include "qpixmap.h" #include "qpixmapdata_p.h" #include "qimagepixmapcleanuphooks_p.h" #include "qbitmap.h" #include "qcolormap.h" #include "qimage.h" #include "qwidget.h" #include "qpainter.h" #include "qdatastream.h" #include "qbuffer.h" #include "qapplication.h" #include <private/qapplication_p.h> #include <private/qgraphicssystem_p.h> #include <private/qwidget_p.h> #include "qevent.h" #include "qfile.h" #include "qfileinfo.h" #include "qpixmapcache.h" #include "qdatetime.h" #include "qimagereader.h" #include "qimagewriter.h" #include "qpaintengine.h" #include "qthread.h" #ifdef Q_WS_MAC # include "private/qt_mac_p.h" # include "private/qpixmap_mac_p.h" #endif #ifdef Q_WS_QPA # include "qplatformintegration_qpa.h" #endif #if defined(Q_WS_X11) # include "qx11info_x11.h" # include <private/qt_x11_p.h> # include <private/qpixmap_x11_p.h> #endif #if defined(Q_OS_SYMBIAN) # include <private/qt_s60_p.h> #endif #include "qpixmap_raster_p.h" #include "private/qstylehelper_p.h" QT_BEGIN_NAMESPACE // ### Qt 5: remove Q_GUI_EXPORT qint64 qt_pixmap_id(const QPixmap &pixmap) { return pixmap.cacheKey(); } static bool qt_pixmap_thread_test() { if (!qApp) { qFatal("QPixmap: Must construct a QApplication before a QPaintDevice"); return false; } if (qApp->thread() != QThread::currentThread()) { bool fail = false; #if defined (Q_WS_X11) if (!QApplication::testAttribute(Qt::AA_X11InitThreads)) fail = true; #elif defined (Q_WS_QPA) if (!QApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps)) { printf("Lighthouse plugin does not support threaded pixmaps!\n"); fail = true; } #else if (QApplicationPrivate::graphics_system_name != QLatin1String("raster")) fail = true; #endif if (fail) { qWarning("QPixmap: It is not safe to use pixmaps outside the GUI thread"); return false; } } return true; } void QPixmap::init(int w, int h, Type type) { init(w, h, int(type)); } extern QApplication::Type qt_appType; void QPixmap::init(int w, int h, int type) { if (qt_appType == QApplication::Tty) { qWarning("QPixmap: Cannot create a QPixmap when no GUI is being used"); data = 0; return; } if ((w > 0 && h > 0) || type == QPixmapData::BitmapType) data = QPixmapData::create(w, h, (QPixmapData::PixelType) type); else data = 0; } /*! \enum QPixmap::ColorMode \compat This enum type defines the color modes that exist for converting QImage objects to QPixmap. It is provided here for compatibility with earlier versions of Qt. Use Qt::ImageConversionFlags instead. \value Auto Select \c Color or \c Mono on a case-by-case basis. \value Color Always create colored pixmaps. \value Mono Always create bitmaps. */ /*! Constructs a null pixmap. \sa isNull() */ QPixmap::QPixmap() : QPaintDevice() { (void) qt_pixmap_thread_test(); init(0, 0, QPixmapData::PixmapType); } /*! \fn QPixmap::QPixmap(int width, int height) Constructs a pixmap with the given \a width and \a height. If either \a width or \a height is zero, a null pixmap is constructed. \warning This will create a QPixmap with uninitialized data. Call fill() to fill the pixmap with an appropriate color before drawing onto it with QPainter. \sa isNull() */ QPixmap::QPixmap(int w, int h) : QPaintDevice() { if (!qt_pixmap_thread_test()) init(0, 0, QPixmapData::PixmapType); else init(w, h, QPixmapData::PixmapType); } /*! \overload Constructs a pixmap of the given \a size. \warning This will create a QPixmap with uninitialized data. Call fill() to fill the pixmap with an appropriate color before drawing onto it with QPainter. */ QPixmap::QPixmap(const QSize &size) : QPaintDevice() { if (!qt_pixmap_thread_test()) init(0, 0, QPixmapData::PixmapType); else init(size.width(), size.height(), QPixmapData::PixmapType); } /*! \internal */ QPixmap::QPixmap(const QSize &s, Type type) { if (!qt_pixmap_thread_test()) init(0, 0, type); else init(s.width(), s.height(), type); } /*! \internal */ QPixmap::QPixmap(const QSize &s, int type) { if (!qt_pixmap_thread_test()) init(0, 0, static_cast<QPixmapData::PixelType>(type)); else init(s.width(), s.height(), static_cast<QPixmapData::PixelType>(type)); } /*! \internal */ QPixmap::QPixmap(QPixmapData *d) : QPaintDevice(), data(d) { } /*! Constructs a pixmap from the file with the given \a fileName. If the file does not exist or is of an unknown format, the pixmap becomes a null pixmap. The loader attempts to read the pixmap using the specified \a format. If the \a format is not specified (which is the default), the loader probes the file for a header to guess the file format. The file name can either refer to an actual file on disk or to one of the application's embedded resources. See the \l{resources.html}{Resource System} overview for details on how to embed images and other resource files in the application's executable. If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the \a flags to control the conversion. The \a fileName, \a format and \a flags parameters are passed on to load(). This means that the data in \a fileName is not compiled into the binary. If \a fileName contains a relative path (e.g. the filename only) the relevant file must be found relative to the runtime working directory. \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing Image Files} */ QPixmap::QPixmap(const QString& fileName, const char *format, Qt::ImageConversionFlags flags) : QPaintDevice() { init(0, 0, QPixmapData::PixmapType); if (!qt_pixmap_thread_test()) return; load(fileName, format, flags); } /*! Constructs a pixmap that is a copy of the given \a pixmap. \sa copy() */ QPixmap::QPixmap(const QPixmap &pixmap) : QPaintDevice() { if (!qt_pixmap_thread_test()) { init(0, 0, QPixmapData::PixmapType); return; } if (pixmap.paintingActive()) { // make a deep copy operator=(pixmap.copy()); } else { data = pixmap.data; } } /*! Constructs a pixmap from the given \a xpm data, which must be a valid XPM image. Errors are silently ignored. Note that it's possible to squeeze the XPM variable a little bit by using an unusual declaration: \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 0 The extra \c const makes the entire definition read-only, which is slightly more efficient (for example, when the code is in a shared library) and ROMable when the application is to be stored in ROM. */ #ifndef QT_NO_IMAGEFORMAT_XPM QPixmap::QPixmap(const char * const xpm[]) : QPaintDevice() { init(0, 0, QPixmapData::PixmapType); if (!xpm) return; QImage image(xpm); if (!image.isNull()) { if (data && data->pixelType() == QPixmapData::BitmapType) *this = QBitmap::fromImage(image); else *this = fromImage(image); } } #endif /*! Destroys the pixmap. */ QPixmap::~QPixmap() { Q_ASSERT(!data || data->ref >= 1); // Catch if ref-counting changes again } /*! \internal */ int QPixmap::devType() const { return QInternal::Pixmap; } /*! \fn QPixmap QPixmap::copy(int x, int y, int width, int height) const \overload Returns a deep copy of the subset of the pixmap that is specified by the rectangle QRect( \a x, \a y, \a width, \a height). */ /*! \fn QPixmap QPixmap::copy(const QRect &rectangle) const Returns a deep copy of the subset of the pixmap that is specified by the given \a rectangle. For more information on deep copies, see the \l {Implicit Data Sharing} documentation. If the given \a rectangle is empty, the whole image is copied. \sa operator=(), QPixmap(), {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ QPixmap QPixmap::copy(const QRect &rect) const { if (isNull()) return QPixmap(); QRect r(0, 0, width(), height()); if (!rect.isEmpty()) r = r.intersected(rect); QPixmapData *d = data->createCompatiblePixmapData(); d->copy(data.data(), r); return QPixmap(d); } /*! \fn QPixmap::scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed) \since 4.6 This convenience function is equivalent to calling QPixmap::scroll(\a dx, \a dy, QRect(\a x, \a y, \a width, \a height), \a exposed). \sa QWidget::scroll(), QGraphicsItem::scroll() */ /*! \since 4.6 Scrolls the area \a rect of this pixmap by (\a dx, \a dy). The exposed region is left unchanged. You can optionally pass a pointer to an empty QRegion to get the region that is \a exposed by the scroll operation. \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 2 You cannot scroll while there is an active painter on the pixmap. \sa QWidget::scroll(), QGraphicsItem::scroll() */ void QPixmap::scroll(int dx, int dy, const QRect &rect, QRegion *exposed) { if (isNull() || (dx == 0 && dy == 0)) return; QRect dest = rect & this->rect(); QRect src = dest.translated(-dx, -dy) & dest; if (src.isEmpty()) { if (exposed) *exposed += dest; return; } detach(); if (!data->scroll(dx, dy, src)) { // Fallback QPixmap pix = *this; QPainter painter(&pix); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.drawPixmap(src.translated(dx, dy), *this, src); painter.end(); *this = pix; } if (exposed) { *exposed += dest; *exposed -= src.translated(dx, dy); } } /*! Assigns the given \a pixmap to this pixmap and returns a reference to this pixmap. \sa copy(), QPixmap() */ QPixmap &QPixmap::operator=(const QPixmap &pixmap) { if (paintingActive()) { qWarning("QPixmap::operator=: Cannot assign to pixmap during painting"); return *this; } if (pixmap.paintingActive()) { // make a deep copy *this = pixmap.copy(); } else { data = pixmap.data; } return *this; } /*! \fn void QPixmap::swap(QPixmap &other) \since 4.8 Swaps pixmap \a other with this pixmap. This operation is very fast and never fails. */ /*! Returns the pixmap as a QVariant. */ QPixmap::operator QVariant() const { return QVariant(QVariant::Pixmap, this); } /*! \fn bool QPixmap::operator!() const Returns true if this is a null pixmap; otherwise returns false. \sa isNull() */ /*! \fn QPixmap::operator QImage() const Returns the pixmap as a QImage. Use the toImage() function instead. */ /*! Converts the pixmap to a QImage. Returns a null image if the conversion fails. If the pixmap has 1-bit depth, the returned image will also be 1 bit deep. Images with more bits will be returned in a format closely represents the underlying system. Usually this will be QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without alpha. Note that for the moment, alpha masks on monochrome images are ignored. \sa fromImage(), {QImage#Image Formats}{Image Formats} */ QImage QPixmap::toImage() const { if (isNull()) return QImage(); return data->toImage(); } /*! \fn QMatrix QPixmap::trueMatrix(const QTransform &matrix, int width, int height) Returns the actual matrix used for transforming a pixmap with the given \a width, \a height and \a matrix. When transforming a pixmap using the transformed() function, the transformation matrix is internally adjusted to compensate for unwanted translation, i.e. transformed() returns the smallest pixmap containing all transformed points of the original pixmap. This function returns the modified matrix, which maps points correctly from the original pixmap into the new pixmap. \sa transformed(), {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ QTransform QPixmap::trueMatrix(const QTransform &m, int w, int h) { return QImage::trueMatrix(m, w, h); } /*! \overload This convenience function loads the matrix \a m into a QTransform and calls the overloaded function with the QTransform and the width \a w and the height \a h. */ QMatrix QPixmap::trueMatrix(const QMatrix &m, int w, int h) { return trueMatrix(QTransform(m), w, h).toAffine(); } /*! \fn bool QPixmap::isQBitmap() const Returns true if this is a QBitmap; otherwise returns false. */ bool QPixmap::isQBitmap() const { return data->type == QPixmapData::BitmapType; } /*! \fn bool QPixmap::isNull() const Returns true if this is a null pixmap; otherwise returns false. A null pixmap has zero width, zero height and no contents. You cannot draw in a null pixmap. */ bool QPixmap::isNull() const { return !data || data->isNull(); } /*! \fn int QPixmap::width() const Returns the width of the pixmap. \sa size(), {QPixmap#Pixmap Information}{Pixmap Information} */ int QPixmap::width() const { return data ? data->width() : 0; } /*! \fn int QPixmap::height() const Returns the height of the pixmap. \sa size(), {QPixmap#Pixmap Information}{Pixmap Information} */ int QPixmap::height() const { return data ? data->height() : 0; } /*! \fn QSize QPixmap::size() const Returns the size of the pixmap. \sa width(), height(), {QPixmap#Pixmap Information}{Pixmap Information} */ QSize QPixmap::size() const { return data ? QSize(data->width(), data->height()) : QSize(0, 0); } /*! \fn QRect QPixmap::rect() const Returns the pixmap's enclosing rectangle. \sa {QPixmap#Pixmap Information}{Pixmap Information} */ QRect QPixmap::rect() const { return data ? QRect(0, 0, data->width(), data->height()) : QRect(); } /*! \fn int QPixmap::depth() const Returns the depth of the pixmap. The pixmap depth is also called bits per pixel (bpp) or bit planes of a pixmap. A null pixmap has depth 0. \sa defaultDepth(), {QPixmap#Pixmap Information}{Pixmap Information} */ int QPixmap::depth() const { return data ? data->depth() : 0; } /*! \fn void QPixmap::resize(const QSize &size) \overload \compat Use QPixmap::copy() instead to get the pixmap with the new size. \oldcode pixmap.resize(size); \newcode pixmap = pixmap.copy(QRect(QPoint(0, 0), size)); \endcode */ #ifdef QT3_SUPPORT void QPixmap::resize_helper(const QSize &s) { int w = s.width(); int h = s.height(); if (w < 1 || h < 1) { *this = QPixmap(); return; } if (size() == s) return; // QPixmap.data member may be QRuntimePixmapData so use pixmapData() function to get // the actual underlaying runtime pixmap data. QPixmapData *pd = pixmapData(); // Create new pixmap QPixmap pm(QSize(w, h), pd ? pd->type : QPixmapData::PixmapType); bool uninit = false; #if defined(Q_WS_X11) QX11PixmapData *x11Data = pd && pd->classId() == QPixmapData::X11Class ? static_cast<QX11PixmapData*>(pd) : 0; if (x11Data) { pm.x11SetScreen(x11Data->xinfo.screen()); uninit = x11Data->flags & QX11PixmapData::Uninitialized; } #elif defined(Q_WS_MAC) QMacPixmapData *macData = pd && pd->classId() == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(pd) : 0; if (macData) uninit = macData->uninit; #endif if (!uninit && !isNull()) { // Copy old pixmap if (hasAlphaChannel()) pm.fill(Qt::transparent); QPainter p(&pm); p.drawPixmap(0, 0, *this, 0, 0, qMin(width(), w), qMin(height(), h)); } #if defined(Q_WS_X11) if (x11Data && x11Data->x11_mask) { QPixmapData *newPd = pm.pixmapData(); QX11PixmapData *pmData = (newPd && newPd->classId() == QPixmapData::X11Class) ? static_cast<QX11PixmapData*>(newPd) : 0; if (pmData) { pmData->x11_mask = (Qt::HANDLE)XCreatePixmap(X11->display, RootWindow(x11Data->xinfo.display(), x11Data->xinfo.screen()), w, h, 1); GC gc = XCreateGC(X11->display, pmData->x11_mask, 0, 0); XCopyArea(X11->display, x11Data->x11_mask, pmData->x11_mask, gc, 0, 0, qMin(width(), w), qMin(height(), h), 0, 0); XFreeGC(X11->display, gc); } } #endif *this = pm; } #endif /*! \fn void QPixmap::resize(int width, int height) \compat Use QPixmap::copy() instead to get the pixmap with the new size. \oldcode pixmap.resize(10, 20); \newcode pixmap = pixmap.copy(0, 0, 10, 20); \endcode */ /*! \fn bool QPixmap::selfMask() const \compat Returns whether the pixmap is its own mask or not. This function is no longer relevant since the concept of self masking doesn't exists anymore. */ /*! Sets a mask bitmap. This function merges the \a mask with the pixmap's alpha channel. A pixel value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0 means the pixel is transparent. The mask must have the same size as this pixmap. Setting a null mask resets the mask, leaving the previously transparent pixels black. The effect of this function is undefined when the pixmap is being painted on. \warning This is potentially an expensive operation. \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap Transformations}, QBitmap */ void QPixmap::setMask(const QBitmap &mask) { if (paintingActive()) { qWarning("QPixmap::setMask: Cannot set mask while pixmap is being painted on"); return; } if (!mask.isNull() && mask.size() != size()) { qWarning("QPixmap::setMask() mask size differs from pixmap size"); return; } if (isNull()) return; if (static_cast<const QPixmap &>(mask).data == data) // trying to selfmask return; detach(); data->setMask(mask); } #ifndef QT_NO_IMAGE_HEURISTIC_MASK /*! Creates and returns a heuristic mask for this pixmap. The function works by selecting a color from one of the corners and then chipping away pixels of that color, starting at all the edges. If \a clipTight is true (the default) the mask is just large enough to cover the pixels; otherwise, the mask is larger than the data pixels. The mask may not be perfect but it should be reasonable, so you can do things such as the following: \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 1 This function is slow because it involves converting to/from a QImage, and non-trivial computations. \sa QImage::createHeuristicMask(), createMaskFromColor() */ QBitmap QPixmap::createHeuristicMask(bool clipTight) const { QBitmap m = QBitmap::fromImage(toImage().createHeuristicMask(clipTight)); return m; } #endif /*! Creates and returns a mask for this pixmap based on the given \a maskColor. If the \a mode is Qt::MaskInColor, all pixels matching the maskColor will be transparent. If \a mode is Qt::MaskOutColor, all pixels matching the maskColor will be opaque. This function is slow because it involves converting to/from a QImage. \sa createHeuristicMask(), QImage::createMaskFromColor() */ QBitmap QPixmap::createMaskFromColor(const QColor &maskColor, Qt::MaskMode mode) const { QImage image = toImage().convertToFormat(QImage::Format_ARGB32); return QBitmap::fromImage(image.createMaskFromColor(maskColor.rgba(), mode)); } /*! \overload Creates and returns a mask for this pixmap based on the given \a maskColor. Same as calling createMaskFromColor(maskColor, Qt::MaskInColor) \sa createHeuristicMask(), QImage::createMaskFromColor() */ QBitmap QPixmap::createMaskFromColor(const QColor &maskColor) const { return createMaskFromColor(maskColor, Qt::MaskInColor); } /*! Loads a pixmap from the file with the given \a fileName. Returns true if the pixmap was successfully loaded; otherwise returns false. The loader attempts to read the pixmap using the specified \a format. If the \a format is not specified (which is the default), the loader probes the file for a header to guess the file format. The file name can either refer to an actual file on disk or to one of the application's embedded resources. See the \l{resources.html}{Resource System} overview for details on how to embed pixmaps and other resource files in the application's executable. If the data needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the \a flags to control the conversion. Note that QPixmaps are automatically added to the QPixmapCache when loaded from a file; the key used is internal and can not be acquired. \sa loadFromData(), {QPixmap#Reading and Writing Image Files}{Reading and Writing Image Files} */ bool QPixmap::load(const QString &fileName, const char *format, Qt::ImageConversionFlags flags) { if (fileName.isEmpty()) return false; QFileInfo info(fileName); QString key = QLatin1Literal("qt_pixmap") % info.absoluteFilePath() % HexString<uint>(info.lastModified().toTime_t()) % HexString<quint64>(info.size()) % HexString<uint>(data ? data->pixelType() : QPixmapData::PixmapType); // Note: If no extension is provided, we try to match the // file against known plugin extensions if (!info.completeSuffix().isEmpty() && !info.exists()) return false; if (QPixmapCache::find(key, *this)) return true; QScopedPointer<QPixmapData> tmp(QPixmapData::create(0, 0, data ? data->type : QPixmapData::PixmapType)); if (tmp->fromFile(fileName, format, flags)) { data = tmp.take(); QPixmapCache::insert(key, *this); return true; } return false; } /*! \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags) Loads a pixmap from the \a len first bytes of the given binary \a data. Returns true if the pixmap was loaded successfully; otherwise returns false. The loader attempts to read the pixmap using the specified \a format. If the \a format is not specified (which is the default), the loader probes the file for a header to guess the file format. If the data needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the \a flags to control the conversion. \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and Writing Image Files} */ bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags) { if (len == 0 || buf == 0) return false; if (!data) data = QPixmapData::create(0, 0, QPixmapData::PixmapType); return data->fromData(buf, len, format, flags); } /*! \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags) \overload Loads a pixmap from the binary \a data using the specified \a format and conversion \a flags. */ /*! Saves the pixmap to the file with the given \a fileName using the specified image file \a format and \a quality factor. Returns true if successful; otherwise returns false. The \a quality factor must be in the range [0,100] or -1. Specify 0 to obtain small compressed files, 100 for large uncompressed files, and -1 to use the default settings. If \a format is 0, an image format will be chosen from \a fileName's suffix. \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing Image Files} */ bool QPixmap::save(const QString &fileName, const char *format, int quality) const { if (isNull()) return false; // nothing to save QImageWriter writer(fileName, format); return doImageIO(&writer, quality); } /*! \overload This function writes a QPixmap to the given \a device using the specified image file \a format and \a quality factor. This can be used, for example, to save a pixmap directly into a QByteArray: \snippet doc/src/snippets/image/image.cpp 1 */ bool QPixmap::save(QIODevice* device, const char* format, int quality) const { if (isNull()) return false; // nothing to save QImageWriter writer(device, format); return doImageIO(&writer, quality); } /*! \internal */ bool QPixmap::doImageIO(QImageWriter *writer, int quality) const { if (quality > 100 || quality < -1) qWarning("QPixmap::save: quality out of range [-1,100]"); if (quality >= 0) writer->setQuality(qMin(quality,100)); return writer->write(toImage()); } // The implementation (and documentation) of // QPixmap::fill(const QWidget *, const QPoint &) // is in qwidget.cpp /*! \fn void QPixmap::fill(const QWidget *widget, int x, int y) \overload Fills the pixmap with the \a widget's background color or pixmap. The given point, (\a x, \a y), defines an offset in widget coordinates to which the pixmap's top-left pixel will be mapped to. */ /*! Fills the pixmap with the given \a color. The effect of this function is undefined when the pixmap is being painted on. \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ void QPixmap::fill(const QColor &color) { if (isNull()) return; // Some people are probably already calling fill while a painter is active, so to not break // their programs, only print a warning and return when the fill operation could cause a crash. if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) { qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on"); return; } if (data->ref == 1) { // detach() will also remove this pixmap from caches, so // it has to be called even when ref == 1. detach(); } else { // Don't bother to make a copy of the data object, since // it will be filled with new pixel data anyway. QPixmapData *d = data->createCompatiblePixmapData(); d->resize(data->width(), data->height()); data = d; } data->fill(color); } /*! \obsolete Returns a number that identifies the contents of this QPixmap object. Distinct QPixmap objects can only have the same serial number if they refer to the same contents (but they don't have to). Use cacheKey() instead. \warning The serial number doesn't necessarily change when the pixmap is altered. This means that it may be dangerous to use it as a cache key. For caching pixmaps, we recommend using the QPixmapCache class whenever possible. */ int QPixmap::serialNumber() const { if (isNull()) return 0; return data->serialNumber(); } /*! Returns a number that identifies this QPixmap. Distinct QPixmap objects can only have the same cache key if they refer to the same contents. The cacheKey() will change when the pixmap is altered. */ qint64 QPixmap::cacheKey() const { if (isNull()) return 0; Q_ASSERT(data); return data->cacheKey(); } static void sendResizeEvents(QWidget *target) { QResizeEvent e(target->size(), QSize()); QApplication::sendEvent(target, &e); const QObjectList children = target->children(); for (int i = 0; i < children.size(); ++i) { QWidget *child = static_cast<QWidget*>(children.at(i)); if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent)) sendResizeEvents(child); } } /*! \fn QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rectangle) Creates a pixmap and paints the given \a widget, restricted by the given \a rectangle, in it. If the \a widget has any children, then they are also painted in the appropriate positions. If no rectangle is specified (the default) the entire widget is painted. If \a widget is 0, the specified rectangle doesn't overlap the widget's rectangle, or an error occurs, the function will return a null QPixmap. If the rectangle is a superset of the given \a widget, the areas outside the \a widget are covered with the widget's background. This function actually asks \a widget to paint itself (and its children to paint themselves) by calling paintEvent() with painter redirection turned on. But QPixmap also provides the grabWindow() function which is a bit faster by grabbing pixels directly off the screen. In addition, if there are overlaying windows, grabWindow(), unlike grabWidget(), will see them. \warning Do not grab a widget from its QWidget::paintEvent(). However, it is safe to grab a widget from another widget's \l {QWidget::}{paintEvent()}. \sa grabWindow() */ QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rect) { if (!widget) return QPixmap(); if (widget->testAttribute(Qt::WA_PendingResizeEvent) || !widget->testAttribute(Qt::WA_WState_Created)) sendResizeEvents(widget); widget->d_func()->prepareToRender(QRegion(), QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask); QRect r(rect); if (r.width() < 0) r.setWidth(widget->width() - rect.x()); if (r.height() < 0) r.setHeight(widget->height() - rect.y()); if (!r.intersects(widget->rect())) return QPixmap(); QPixmap res(r.size()); if (!qt_widget_private(widget)->isOpaque) res.fill(Qt::transparent); widget->d_func()->render(&res, QPoint(), r, QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask, true); return res; } /*! \fn QPixmap QPixmap::grabWidget(QWidget *widget, int x, int y, int width, int height) \overload Creates a pixmap and paints the given \a widget, restricted by QRect(\a x, \a y, \a width, \a height), in it. \warning Do not grab a widget from its QWidget::paintEvent(). However, it is safe to grab a widget from another widget's \l {QWidget::}{paintEvent()}. */ /*! \since 4.5 \enum QPixmap::ShareMode This enum type defines the share modes that are available when creating a QPixmap object from a raw X11 Pixmap handle. \value ImplicitlyShared This mode will cause the QPixmap object to create a copy of the internal data before it is modified, thus keeping the original X11 pixmap intact. \value ExplicitlyShared In this mode, the pixmap data will \e not be copied before it is modified, which in effect will change the original X11 pixmap. \warning This enum is only used for X11 specific functions; using it is non-portable. \sa QPixmap::fromX11Pixmap() */ /*! \since 4.5 \fn QPixmap QPixmap::fromX11Pixmap(Qt::HANDLE pixmap, QPixmap::ShareMode mode) Creates a QPixmap from the native X11 Pixmap handle \a pixmap, using \a mode as the share mode. The default share mode is QPixmap::ImplicitlyShared, which means that a copy of the pixmap is made if someone tries to modify it by e.g. drawing onto it. QPixmap does \e not take ownership of the \a pixmap handle, and have to be deleted by the user. \warning This function is X11 specific; using it is non-portable. \sa QPixmap::ShareMode */ #if defined(Q_WS_X11) || defined(Q_WS_QWS) /*! Returns the pixmap's handle to the device context. Note that, since QPixmap make use of \l {Implicit Data Sharing}{implicit data sharing}, the detach() function must be called explicitly to ensure that only \e this pixmap's data is modified if the pixmap data is shared. \warning This function is X11 specific; using it is non-portable. \warning Since 4.8, pixmaps do not have an X11 handle unless created with \l {QPixmap::}{fromX11Pixmap()}, or if the native graphics system is explicitly enabled. \sa detach() \sa QApplication::setGraphicsSystem() */ Qt::HANDLE QPixmap::handle() const { #if defined(Q_WS_X11) const QPixmapData *pd = pixmapData(); if (pd && pd->classId() == QPixmapData::X11Class) return static_cast<const QX11PixmapData*>(pd)->handle(); #endif return 0; } #endif #ifdef QT3_SUPPORT static Qt::ImageConversionFlags colorModeToFlags(QPixmap::ColorMode mode) { Qt::ImageConversionFlags flags = Qt::AutoColor; switch (mode) { case QPixmap::Color: flags |= Qt::ColorOnly; break; case QPixmap::Mono: flags |= Qt::MonoOnly; break; default: break;// Nothing. } return flags; } /*! Use the constructor that takes a Qt::ImageConversionFlag instead. */ QPixmap::QPixmap(const QString& fileName, const char *format, ColorMode mode) : QPaintDevice() { init(0, 0, QPixmapData::PixmapType); if (!qt_pixmap_thread_test()) return; load(fileName, format, colorModeToFlags(mode)); } /*! Constructs a pixmap from the QImage \a image. Use the static fromImage() function instead. */ QPixmap::QPixmap(const QImage& image) : QPaintDevice() { init(0, 0, QPixmapData::PixmapType); if (!qt_pixmap_thread_test()) return; if (data && data->pixelType() == QPixmapData::BitmapType) *this = QBitmap::fromImage(image); else *this = fromImage(image); } /*! \overload Converts the given \a image to a pixmap that is assigned to this pixmap. Use the static fromImage() function instead. */ QPixmap &QPixmap::operator=(const QImage &image) { if (data && data->pixelType() == QPixmapData::BitmapType) *this = QBitmap::fromImage(image); else *this = fromImage(image); return *this; } /*! Use the load() function that takes a Qt::ImageConversionFlag instead. */ bool QPixmap::load(const QString &fileName, const char *format, ColorMode mode) { return load(fileName, format, colorModeToFlags(mode)); } /*! Use the loadFromData() function that takes a Qt::ImageConversionFlag instead. */ bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, ColorMode mode) { return loadFromData(buf, len, format, colorModeToFlags(mode)); } /*! Use the static fromImage() function instead. */ bool QPixmap::convertFromImage(const QImage &image, ColorMode mode) { if (data && data->pixelType() == QPixmapData::BitmapType) *this = QBitmap::fromImage(image, colorModeToFlags(mode)); else *this = fromImage(image, colorModeToFlags(mode)); return !isNull(); } #endif /***************************************************************************** QPixmap stream functions *****************************************************************************/ #if !defined(QT_NO_DATASTREAM) /*! \relates QPixmap Writes the given \a pixmap to the given \a stream as a PNG image. Note that writing the stream to a file will not produce a valid image file. \sa QPixmap::save(), {Serializing Qt Data Types} */ QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap) { return stream << pixmap.toImage(); } /*! \relates QPixmap Reads an image from the given \a stream into the given \a pixmap. \sa QPixmap::load(), {Serializing Qt Data Types} */ QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap) { QImage image; stream >> image; if (image.isNull()) { pixmap = QPixmap(); } else if (image.depth() == 1) { pixmap = QBitmap::fromImage(image); } else { pixmap = QPixmap::fromImage(image); } return stream; } #endif // QT_NO_DATASTREAM #ifdef QT3_SUPPORT Q_GUI_EXPORT void copyBlt(QPixmap *dst, int dx, int dy, const QPixmap *src, int sx, int sy, int sw, int sh) { Q_ASSERT_X(dst, "::copyBlt", "Destination pixmap must be non-null"); Q_ASSERT_X(src, "::copyBlt", "Source pixmap must be non-null"); if (src->hasAlphaChannel()) { if (dst->paintEngine()->hasFeature(QPaintEngine::PorterDuff)) { QPainter p(dst); p.setCompositionMode(QPainter::CompositionMode_Source); p.drawPixmap(dx, dy, *src, sx, sy, sw, sh); } else { QImage image = dst->toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied); QPainter p(&image); p.setCompositionMode(QPainter::CompositionMode_Source); p.drawPixmap(dx, dy, *src, sx, sy, sw, sh); p.end(); *dst = QPixmap::fromImage(image); } } else { QPainter p(dst); p.drawPixmap(dx, dy, *src, sx, sy, sw, sh); } } #endif /*! \internal */ bool QPixmap::isDetached() const { return data && data->ref == 1; } /*! \internal ### Qt5 - remove me. */ void QPixmap::deref() { Q_ASSERT_X(false, "QPixmap::deref()", "Do not call this function anymore!"); } /*! \fn QImage QPixmap::convertToImage() const Use the toImage() function instead. */ /*! Replaces this pixmap's data with the given \a image using the specified \a flags to control the conversion. The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a flags sets all the default options. Returns true if the result is that this pixmap is not null. Note: this function was part of Qt 3 support in Qt 4.6 and earlier. It has been promoted to official API status in 4.7 to support updating the pixmap's image without creating a new QPixmap as fromImage() would. \sa fromImage() \since 4.7 */ bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags) { if (image.isNull() || !data) *this = QPixmap::fromImage(image, flags); else data->fromImage(image, flags); return !isNull(); } /*! \fn QPixmap QPixmap::xForm(const QMatrix &matrix) const Use transformed() instead. */ /*! \fn QPixmap QPixmap::scaled(int width, int height, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformMode) const \overload Returns a copy of the pixmap scaled to a rectangle with the given \a width and \a height according to the given \a aspectRatioMode and \a transformMode. If either the \a width or the \a height is zero or negative, this function returns a null pixmap. */ /*! \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformMode) const Scales the pixmap to the given \a size, using the aspect ratio and transformation modes specified by \a aspectRatioMode and \a transformMode. \image qimage-scaling.png \list \i If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap is scaled to \a size. \i If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio. \i If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding, the pixmap is scaled to a rectangle as small as possible outside \a size, preserving the aspect ratio. \endlist If the given \a size is empty, this function returns a null pixmap. In some cases it can be more beneficial to draw the pixmap to a painter with a scale set rather than scaling the pixmap. This is the case when the painter is for instance based on OpenGL or when the scale factor changes rapidly. \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const { if (isNull()) { qWarning("QPixmap::scaled: Pixmap is a null pixmap"); return QPixmap(); } if (s.isEmpty()) return QPixmap(); QSize newSize = size(); newSize.scale(s, aspectMode); newSize.rwidth() = qMax(newSize.width(), 1); newSize.rheight() = qMax(newSize.height(), 1); if (newSize == size()) return *this; QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(), (qreal)newSize.height() / height()); QPixmap pix = transformed(wm, mode); return pix; } /*! \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode mode) const Returns a scaled copy of the image. The returned image is scaled to the given \a width using the specified transformation \a mode. The height of the pixmap is automatically calculated so that the aspect ratio of the pixmap is preserved. If \a width is 0 or negative, a null pixmap is returned. \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const { if (isNull()) { qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap"); return copy(); } if (w <= 0) return QPixmap(); qreal factor = (qreal) w / width(); QTransform wm = QTransform::fromScale(factor, factor); return transformed(wm, mode); } /*! \fn QPixmap QPixmap::scaledToHeight(int height, Qt::TransformationMode mode) const Returns a scaled copy of the image. The returned image is scaled to the given \a height using the specified transformation \a mode. The width of the pixmap is automatically calculated so that the aspect ratio of the pixmap is preserved. If \a height is 0 or negative, a null pixmap is returned. \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const { if (isNull()) { qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap"); return copy(); } if (h <= 0) return QPixmap(); qreal factor = (qreal) h / height(); QTransform wm = QTransform::fromScale(factor, factor); return transformed(wm, mode); } /*! Returns a copy of the pixmap that is transformed using the given transformation \a transform and transformation \a mode. The original pixmap is not changed. The transformation \a transform is internally adjusted to compensate for unwanted translation; i.e. the pixmap produced is the smallest pixmap that contains all the transformed points of the original pixmap. Use the trueMatrix() function to retrieve the actual matrix used for transforming the pixmap. This function is slow because it involves transformation to a QImage, non-trivial computations and a transformation back to a QPixmap. \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ QPixmap QPixmap::transformed(const QTransform &transform, Qt::TransformationMode mode) const { if (isNull() || transform.type() <= QTransform::TxTranslate) return *this; return data->transformed(transform, mode); } /*! \overload This convenience function loads the \a matrix into a QTransform and calls the overloaded function. */ QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const { return transformed(QTransform(matrix), mode); } /*! \class QPixmap \brief The QPixmap class is an off-screen image representation that can be used as a paint device. \ingroup painting \ingroup shared Qt provides four classes for handling image data: QImage, QPixmap, QBitmap and QPicture. QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen. QBitmap is only a convenience class that inherits QPixmap, ensuring a depth of 1. The isQBitmap() function returns true if a QPixmap object is really a bitmap, otherwise returns false. Finally, the QPicture class is a paint device that records and replays QPainter commands. A QPixmap can easily be displayed on the screen using QLabel or one of QAbstractButton's subclasses (such as QPushButton and QToolButton). QLabel has a pixmap property, whereas QAbstractButton has an icon property. In addition to the ordinary constructors, a QPixmap can be constructed using the static grabWidget() and grabWindow() functions which creates a QPixmap and paints the given widget, or window, into it. QPixmap objects can be passed around by value since the QPixmap class uses implicit data sharing. For more information, see the \l {Implicit Data Sharing} documentation. QPixmap objects can also be streamed. Note that the pixel data in a pixmap is internal and is managed by the underlying window system. Because QPixmap is a QPaintDevice subclass, QPainter can be used to draw directly onto pixmaps. Pixels can only be accessed through QPainter functions or by converting the QPixmap to a QImage. However, the fill() function is available for initializing the entire pixmap with a given color. There are functions to convert between QImage and QPixmap. Typically, the QImage class is used to load an image file, optionally manipulating the image data, before the QImage object is converted into a QPixmap to be shown on screen. Alternatively, if no manipulation is desired, the image file can be loaded directly into a QPixmap. On Windows, the QPixmap class also supports conversion between \c HBITMAP and QPixmap. On Symbian, the QPixmap class also supports conversion between CFbsBitmap and QPixmap. QPixmap provides a collection of functions that can be used to obtain a variety of information about the pixmap. In addition, there are several functions that enables transformation of the pixmap. \tableofcontents \section1 Reading and Writing Image Files QPixmap provides several ways of reading an image file: The file can be loaded when constructing the QPixmap object, or by using the load() or loadFromData() functions later on. When loading an image, the file name can either refer to an actual file on disk or to one of the application's embedded resources. See \l{The Qt Resource System} overview for details on how to embed images and other resource files in the application's executable. Simply call the save() function to save a QPixmap object. The complete list of supported file formats are available through the QImageReader::supportedImageFormats() and QImageWriter::supportedImageFormats() functions. New file formats can be added as plugins. By default, Qt supports the following formats: \table \header \o Format \o Description \o Qt's support \row \o BMP \o Windows Bitmap \o Read/write \row \o GIF \o Graphic Interchange Format (optional) \o Read \row \o JPG \o Joint Photographic Experts Group \o Read/write \row \o JPEG \o Joint Photographic Experts Group \o Read/write \row \o PNG \o Portable Network Graphics \o Read/write \row \o PBM \o Portable Bitmap \o Read \row \o PGM \o Portable Graymap \o Read \row \o PPM \o Portable Pixmap \o Read/write \row \o XBM \o X11 Bitmap \o Read/write \row \o XPM \o X11 Pixmap \o Read/write \endtable \section1 Pixmap Information QPixmap provides a collection of functions that can be used to obtain a variety of information about the pixmap: \table \header \o \o Available Functions \row \o Geometry \o The size(), width() and height() functions provide information about the pixmap's size. The rect() function returns the image's enclosing rectangle. \row \o Alpha component \o The hasAlphaChannel() returns true if the pixmap has a format that respects the alpha channel, otherwise returns false. The hasAlpha(), setMask() and mask() functions are legacy and should not be used. They are potentially very slow. The createHeuristicMask() function creates and returns a 1-bpp heuristic mask (i.e. a QBitmap) for this pixmap. It works by selecting a color from one of the corners and then chipping away pixels of that color, starting at all the edges. The createMaskFromColor() function creates and returns a mask (i.e. a QBitmap) for the pixmap based on a given color. \row \o Low-level information \o The depth() function returns the depth of the pixmap. The defaultDepth() function returns the default depth, i.e. the depth used by the application on the given screen. The cacheKey() function returns a number that uniquely identifies the contents of the QPixmap object. The x11Info() function returns information about the configuration of the X display used by the screen to which the pixmap currently belongs. The x11PictureHandle() function returns the X11 Picture handle of the pixmap for XRender support. Note that the two latter functions are only available on x11. \endtable \section1 Pixmap Conversion A QPixmap object can be converted into a QImage using the toImage() function. Likewise, a QImage can be converted into a QPixmap using the fromImage(). If this is too expensive an operation, you can use QBitmap::fromImage() instead. In addition, on Windows, the QPixmap class supports conversion to and from HBITMAP: the toWinHBITMAP() function creates a HBITMAP equivalent to the QPixmap, based on the given HBitmapFormat, and returns the HBITMAP handle. The fromWinHBITMAP() function returns a QPixmap that is equivalent to the given bitmap which has the specified format. The QPixmap class also supports conversion to and from HICON: the toWinHICON() function creates a HICON equivalent to the QPixmap, and returns the HICON handle. The fromWinHICON() function returns a QPixmap that is equivalent to the given icon. In addition, on Symbian, the QPixmap class supports conversion to and from CFbsBitmap: the toSymbianCFbsBitmap() function creates CFbsBitmap equivalent to the QPixmap, based on given mode and returns a CFbsBitmap object. The fromSymbianCFbsBitmap() function returns a QPixmap that is equivalent to the given bitmap and given mode. \section1 Pixmap Transformations QPixmap supports a number of functions for creating a new pixmap that is a transformed version of the original: The scaled(), scaledToWidth() and scaledToHeight() functions return scaled copies of the pixmap, while the copy() function creates a QPixmap that is a plain copy of the original one. The transformed() function returns a copy of the pixmap that is transformed with the given transformation matrix and transformation mode: Internally, the transformation matrix is adjusted to compensate for unwanted translation, i.e. transformed() returns the smallest pixmap containing all transformed points of the original pixmap. The static trueMatrix() function returns the actual matrix used for transforming the pixmap. \note When using the native X11 graphics system, the pixmap becomes invalid when the QApplication instance is destroyed. \sa QBitmap, QImage, QImageReader, QImageWriter */ /*! \typedef QPixmap::DataPtr \internal */ /*! \fn DataPtr &QPixmap::data_ptr() \internal */ /*! Returns true if this pixmap has an alpha channel, \e or has a mask, otherwise returns false. \sa hasAlphaChannel(), mask() */ bool QPixmap::hasAlpha() const { #if defined(Q_WS_X11) if (data && data->hasAlphaChannel()) return true; QPixmapData *pd = pixmapData(); if (pd && pd->classId() == QPixmapData::X11Class) { QX11PixmapData *x11Data = static_cast<QX11PixmapData*>(pd); #ifndef QT_NO_XRENDER if (x11Data->picture && x11Data->d == 32) return true; #endif if (x11Data->d == 1 || x11Data->x11_mask) return true; } return false; #else return data && data->hasAlphaChannel(); #endif } /*! Returns true if the pixmap has a format that respects the alpha channel, otherwise returns false. \sa hasAlpha() */ bool QPixmap::hasAlphaChannel() const { return data && data->hasAlphaChannel(); } /*! \internal */ int QPixmap::metric(PaintDeviceMetric metric) const { return data ? data->metric(metric) : 0; } /*! \fn void QPixmap::setAlphaChannel(const QPixmap &alphaChannel) \obsolete Sets the alpha channel of this pixmap to the given \a alphaChannel by converting the \a alphaChannel into 32 bit and using the intensity of the RGB pixel values. The effect of this function is undefined when the pixmap is being painted on. \warning This is potentially an expensive operation. Most usecases for this function are covered by QPainter and compositionModes which will normally execute faster. \sa alphaChannel(), {QPixmap#Pixmap Transformations}{Pixmap Transformations} */ void QPixmap::setAlphaChannel(const QPixmap &alphaChannel) { if (alphaChannel.isNull()) return; if (paintingActive()) { qWarning("QPixmap::setAlphaChannel: " "Cannot set alpha channel while pixmap is being painted on"); return; } if (width() != alphaChannel.width() && height() != alphaChannel.height()) { qWarning("QPixmap::setAlphaChannel: " "The pixmap and the alpha channel pixmap must have the same size"); return; } detach(); data->setAlphaChannel(alphaChannel); } /*! \obsolete Returns the alpha channel of the pixmap as a new grayscale QPixmap in which each pixel's red, green, and blue values are given the alpha value of the original pixmap. The color depth of the returned pixmap is the system depth on X11 and 8-bit on Windows and Mac OS X. You can use this function while debugging to get a visible image of the alpha channel. If the pixmap doesn't have an alpha channel, i.e., the alpha channel's value for all pixels equals 0xff), a null pixmap is returned. You can check this with the \c isNull() function. We show an example: \snippet doc/src/snippets/alphachannel.cpp 0 \image alphachannelimage.png The pixmap and channelImage QPixmaps \warning This is an expensive operation. The alpha channel of the pixmap is extracted dynamically from the pixeldata. Most usecases of this function are covered by QPainter and compositionModes which will normally execute faster. \sa setAlphaChannel(), {QPixmap#Pixmap Information}{Pixmap Information} */ QPixmap QPixmap::alphaChannel() const { return data ? data->alphaChannel() : QPixmap(); } /*! \internal */ QPaintEngine *QPixmap::paintEngine() const { return data ? data->paintEngine() : 0; } /*! \fn QBitmap QPixmap::mask() const Extracts a bitmap mask from the pixmap's alpha channel. \warning This is potentially an expensive operation. The mask of the pixmap is extracted dynamically from the pixeldata. \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information} */ QBitmap QPixmap::mask() const { return data ? data->mask() : QBitmap(); } /*! Returns the default pixmap depth used by the application. On Windows and Mac, the default depth is always 32. On X11 and embedded, the depth of the screen will be returned by this function. \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information} */ int QPixmap::defaultDepth() { #if defined(Q_WS_QWS) return QScreen::instance()->depth(); #elif defined(Q_WS_X11) return QX11Info::appDepth(); #elif defined(Q_WS_WINCE) return QColormap::instance().depth(); #elif defined(Q_WS_WIN) return 32; // XXX #elif defined(Q_WS_MAC) return 32; #elif defined(Q_OS_SYMBIAN) return S60->screenDepth; #elif defined(Q_WS_QPA) return 32; //LITE: use graphicssystem (we should do that in general) #endif } /*! Detaches the pixmap from shared pixmap data. A pixmap is automatically detached by Qt whenever its contents are about to change. This is done in almost all QPixmap member functions that modify the pixmap (fill(), fromImage(), load(), etc.), and in QPainter::begin() on a pixmap. There are two exceptions in which detach() must be called explicitly, that is when calling the handle() or the x11PictureHandle() function (only available on X11). Otherwise, any modifications done using system calls, will be performed on the shared data. The detach() function returns immediately if there is just a single reference or if the pixmap has not been initialized yet. */ void QPixmap::detach() { if (!data) return; // QPixmap.data member may be QRuntimePixmapData so use pixmapData() function to get // the actual underlaying runtime pixmap data. QPixmapData *pd = pixmapData(); QPixmapData::ClassId id = pd->classId(); if (id == QPixmapData::RasterClass) { QRasterPixmapData *rasterData = static_cast<QRasterPixmapData*>(pd); rasterData->image.detach(); } if (data->is_cached && data->ref == 1) QImagePixmapCleanupHooks::executePixmapDataModificationHooks(data.data()); #if defined(Q_WS_MAC) QMacPixmapData *macData = id == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(pd) : 0; if (macData) { if (macData->cg_mask) { CGImageRelease(macData->cg_mask); macData->cg_mask = 0; } } #endif if (data->ref != 1) { *this = copy(); } ++data->detach_no; #if defined(Q_WS_X11) if (pd->classId() == QPixmapData::X11Class) { QX11PixmapData *d = static_cast<QX11PixmapData*>(pd); d->flags &= ~QX11PixmapData::Uninitialized; // reset the cache data if (d->hd2) { XFreePixmap(X11->display, d->hd2); d->hd2 = 0; } } #elif defined(Q_WS_MAC) if (macData) { macData->macReleaseCGImageRef(); macData->uninit = false; } #endif } /*! \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags) Converts the given \a image to a pixmap using the specified \a flags to control the conversion. The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a flags sets all the default options. In case of monochrome and 8-bit images, the image is first converted to a 32-bit pixmap and then filled with the colors in the color table. If this is too expensive an operation, you can use QBitmap::fromImage() instead. \sa fromImageReader(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} */ QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags) { if (image.isNull()) return QPixmap(); QGraphicsSystem* gs = QApplicationPrivate::graphicsSystem(); QScopedPointer<QPixmapData> data(gs ? gs->createPixmapData(QPixmapData::PixmapType) : QGraphicsSystem::createDefaultPixmapData(QPixmapData::PixmapType)); data->fromImage(image, flags); return QPixmap(data.take()); } /*! \fn QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags) Create a QPixmap from an image read directly from an \a imageReader. The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a flags sets all the default options. On some systems, reading an image directly to QPixmap can use less memory than reading a QImage to convert it to QPixmap. \sa fromImage(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} */ QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags) { QGraphicsSystem *gs = QApplicationPrivate::graphicsSystem(); QScopedPointer<QPixmapData> data(gs ? gs->createPixmapData(QPixmapData::PixmapType) : QGraphicsSystem::createDefaultPixmapData(QPixmapData::PixmapType)); data->fromImageReader(imageReader, flags); return QPixmap(data.take()); } /*! \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int width, int height) Creates and returns a pixmap constructed by grabbing the contents of the given \a window restricted by QRect(\a x, \a y, \a width, \a height). The arguments (\a{x}, \a{y}) specify the offset in the window, whereas (\a{width}, \a{height}) specify the area to be copied. If \a width is negative, the function copies everything to the right border of the window. If \a height is negative, the function copies everything to the bottom of the window. The window system identifier (\c WId) can be retrieved using the QWidget::winId() function. The rationale for using a window identifier and not a QWidget, is to enable grabbing of windows that are not part of the application, window system frames, and so on. The grabWindow() function grabs pixels from the screen, not from the window, i.e. if there is another window partially or entirely over the one you grab, you get pixels from the overlying window, too. The mouse cursor is generally not grabbed. Note on X11 that if the given \a window doesn't have the same depth as the root window, and another window partially or entirely obscures the one you grab, you will \e not get pixels from the overlying window. The contents of the obscured areas in the pixmap will be undefined and uninitialized. On Windows Vista and above grabbing a layered window, which is created by setting the Qt::WA_TranslucentBackground attribute, will not work. Instead grabbing the desktop widget should work. \warning In general, grabbing an area outside the screen is not safe. This depends on the underlying window system. \sa grabWidget(), {Screenshot Example} */ /*! \internal */ QPixmapData* QPixmap::pixmapData() const { if (data) { QPixmapData* pm = data.data(); return pm->runtimeData() ? pm->runtimeData() : pm; } return 0; } /*! \enum QPixmap::HBitmapFormat \bold{Win32 only:} This enum defines how the conversion between \c HBITMAP and QPixmap is performed. \warning This enum is only available on Windows. \value NoAlpha The alpha channel is ignored and always treated as being set to fully opaque. This is preferred if the \c HBITMAP is used with standard GDI calls, such as \c BitBlt(). \value PremultipliedAlpha The \c HBITMAP is treated as having an alpha channel and premultiplied colors. This is preferred if the \c HBITMAP is accessed through the \c AlphaBlend() GDI function. \value Alpha The \c HBITMAP is treated as having a plain alpha channel. This is the preferred format if the \c HBITMAP is going to be used as an application icon or systray icon. \sa fromWinHBITMAP(), toWinHBITMAP() */ /*! \fn HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const \bold{Win32 only:} Creates a \c HBITMAP equivalent to the QPixmap, based on the given \a format. Returns the \c HBITMAP handle. It is the caller's responsibility to free the \c HBITMAP data after use. \warning This function is only available on Windows. \sa fromWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} */ /*! \fn QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format) \bold{Win32 only:} Returns a QPixmap that is equivalent to the given \a bitmap. The conversion is based on the specified \a format. \warning This function is only available on Windows. \sa toWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} */ /*! \fn HICON QPixmap::toWinHICON() const \since 4.6 \bold{Win32 only:} Creates a \c HICON equivalent to the QPixmap. Returns the \c HICON handle. It is the caller's responsibility to free the \c HICON data after use. \warning This function is only available on Windows. \sa fromWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} */ /*! \fn QPixmap QPixmap::fromWinHICON(HICON icon) \since 4.6 \bold{Win32 only:} Returns a QPixmap that is equivalent to the given \a icon. \warning This function is only available on Windows. \sa toWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} */ /*! \fn const QX11Info &QPixmap::x11Info() const \bold{X11 only:} Returns information about the configuration of the X display used by the screen to which the pixmap currently belongs. \warning This function is only available on X11. \sa {QPixmap#Pixmap Information}{Pixmap Information} */ /*! \fn Qt::HANDLE QPixmap::x11PictureHandle() const \bold{X11 only:} Returns the X11 Picture handle of the pixmap for XRender support. This function will return 0 if XRender support is not compiled into Qt, if the XRender extension is not supported on the X11 display, or if the handle could not be created. Use of this function is not portable. \warning This function is only available on X11. \sa {QPixmap#Pixmap Information}{Pixmap Information} */ /*! \fn int QPixmap::x11SetDefaultScreen(int screen) \internal */ /*! \fn void QPixmap::x11SetScreen(int screen) \internal */ /*! \fn QRgb* QPixmap::clut() const \internal */ /*! \fn int QPixmap::numCols() const \obsolete \internal \sa colorCount() */ /*! \fn int QPixmap::colorCount() const \since 4.6 \internal */ /*! \fn const uchar* QPixmap::qwsBits() const \internal \since 4.1 */ /*! \fn int QPixmap::qwsBytesPerLine() const \internal \since 4.1 */ QT_END_NAMESPACE
29.973432
115
0.673622
martende
70718aa26e53cbb87a19b4f9a0f4c38eac7d0800
1,458
cc
C++
physics/gravity_netcdf.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
physics/gravity_netcdf.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
physics/gravity_netcdf.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
/** * @file gravity_netcdf.cc */ #include <genecis/phsyics/gravity.h> using namespace genecis::physics ; /** * Initialize netCDF file for recording data */ void gravity::init_netcdf( const char* filename, const char* long_name ) { _nc_file = new NcFile( filename, NcFile::Replace ); _nc_rec = 0 ; if ( long_name ) { _nc_file->add_att("long_name", long_name ) ; } // dimensions NcDim* time_dim = _nc_file->add_dim( "travel_time" ) ; // coordinates _nc_time = _nc_file->add_var( "travel_time", ncDouble, time_dim ) ; _nc_pos1 = _nc_file->add_var( "Object1 location", ncDouble, time_dim, time_dim, time_dim ) ; _nc_pos2 = _nc_file->add_var( "Object2 location", ncDouble, time_dim, time_dim, time_dim ) ; // attributes _nc_time->add_att("units","days") ; _nc_pos1->add_att("units","rho,thata,phi") ; _nc_pos1->add_att("positive","out,up,clockwise") ; _nc_pos2->add_att("units","rho,thata,phi") ; _nc_pos2->add_att("positive","out,up,clockwise") ; } /** * Writes the time and position of both bodies to * the netCDF log */ void gravity::save_netcdf() { NcError( verbose_nonfatal ) ; _nc_time->put_rec( &_time, _nc_rec ) ; _nc_pos1->put_rec( "position1 data", _nc_rec ) ; // need to figure out how to do this _nc_pos2->put_rec( "position2 data", _nc_rec ) ; // need to figure out how to do this ++_nc_rec ; } /** * Closes the netCDF log file */ void gravity::close_netcdf() { delete _nc_file ; _nc_file = NULL ; }
25.137931
86
0.687243
Tibonium
707810bc6546d6f01200d1b8703ab397a33ada10
2,614
cpp
C++
libs/crypto/tests/unit/aes_tests.cpp
marcuswin/ledger
b79c5c4e7e92ff02ea4328fcc0885bf8ded2b8b2
[ "Apache-2.0" ]
1
2019-09-11T09:46:04.000Z
2019-09-11T09:46:04.000Z
libs/crypto/tests/unit/aes_tests.cpp
qati/ledger
e05a8f2d62ea1b79a704867d220cf307ef6b93b9
[ "Apache-2.0" ]
null
null
null
libs/crypto/tests/unit/aes_tests.cpp
qati/ledger
e05a8f2d62ea1b79a704867d220cf307ef6b93b9
[ "Apache-2.0" ]
1
2019-09-19T12:38:46.000Z
2019-09-19T12:38:46.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "aes.hpp" #include "core/byte_array/byte_array.hpp" #include "core/byte_array/const_byte_array.hpp" #include "core/byte_array/decoders.hpp" #include "crypto/block_cipher.hpp" #include "gtest/gtest.h" using fetch::byte_array::ConstByteArray; using fetch::byte_array::FromHex; using fetch::crypto::AesBlockCipher; using fetch::crypto::BlockCipher; namespace { TEST(AesTests, BasicAes256CbcTest) { // define the inputs to the object ConstByteArray plain_text = "The quick brown fox jumps over the lazy dog"; ConstByteArray key = FromHex("0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20"); ConstByteArray iv = FromHex("0102030405060708090A0B0C0D0E0F10"); // encrypt the plain text ConstByteArray cipher_text{}; ASSERT_TRUE(AesBlockCipher::Encrypt(BlockCipher::AES_256_CBC, key, iv, plain_text, cipher_text)); ConstByteArray recovered_text{}; ASSERT_TRUE( AesBlockCipher::Decrypt(BlockCipher::AES_256_CBC, key, iv, cipher_text, recovered_text)); ASSERT_EQ(plain_text, recovered_text); } TEST(AesTests, ExactMultipleOfBlockSize) { // define the inputs to the object ConstByteArray plain_text = "The quick brown fox jumps over the lazy dog....."; ConstByteArray key = FromHex("0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20"); ConstByteArray iv = FromHex("0102030405060708090A0B0C0D0E0F10"); // check the message size is as expected ASSERT_EQ(plain_text.size() % 16, 0); // encrypt the plain text ConstByteArray cipher_text{}; ASSERT_TRUE(AesBlockCipher::Encrypt(BlockCipher::AES_256_CBC, key, iv, plain_text, cipher_text)); ConstByteArray recovered_text{}; ASSERT_TRUE( AesBlockCipher::Decrypt(BlockCipher::AES_256_CBC, key, iv, cipher_text, recovered_text)); ASSERT_EQ(plain_text, recovered_text); } } // namespace
34.853333
99
0.713466
marcuswin
70793019df6e8d0cfa87e7130fff1734ed430179
1,727
hpp
C++
libs/renderer/include/sge/renderer/index/buffer.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/renderer/include/sge/renderer/index/buffer.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/renderer/include/sge/renderer/index/buffer.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_RENDERER_INDEX_BUFFER_HPP_INCLUDED #define SGE_RENDERER_INDEX_BUFFER_HPP_INCLUDED #include <sge/core/detail/class_symbol.hpp> #include <sge/renderer/resource_flags_field_fwd.hpp> #include <sge/renderer/size_type.hpp> #include <sge/renderer/detail/symbol.hpp> #include <sge/renderer/index/buffer_base.hpp> #include <fcppt/nonmovable.hpp> namespace sge::renderer::index { /** \brief A buffer for storing indices An index buffer can hold a fixed amount of indices in a given index format, of which there are currently two of: <ul> <li>16 bit indices</li> <li>32 bit indices</li> </ul> After an index buffer has been created, its size cannot be changed. To store data in it, it has to be locked first, which will return a view for accessing the data. Unlocking the buffer will make the update actually take place. \see sge::renderer::device::create_index_buffer \see sge::renderer::device::render_indexed \see sge::renderer::index::const_scoped_lock \see sge::renderer::index::scoped_lock */ class SGE_CORE_DETAIL_CLASS_SYMBOL buffer : public sge::renderer::index::buffer_base { FCPPT_NONMOVABLE(buffer); protected: SGE_RENDERER_DETAIL_SYMBOL buffer(); public: /** \brief Returns the resource flags the buffer has been created with */ [[nodiscard]] virtual sge::renderer::resource_flags_field resource_flags() const = 0; [[nodiscard]] SGE_RENDERER_DETAIL_SYMBOL sge::renderer::size_type linear_size() const; SGE_RENDERER_DETAIL_SYMBOL ~buffer() override; }; } #endif
27.854839
88
0.763752
cpreh
7079cc8af542ea107596cd7181181c0f974781f6
6,403
cxx
C++
samples/httptest/httptest.cxx
sverdlin/opalvoip-ptlib
f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be
[ "Beerware" ]
null
null
null
samples/httptest/httptest.cxx
sverdlin/opalvoip-ptlib
f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be
[ "Beerware" ]
null
null
null
samples/httptest/httptest.cxx
sverdlin/opalvoip-ptlib
f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be
[ "Beerware" ]
null
null
null
// // httptest.cxx // // Copyright 2011 Vox Lucida Pty. Ltd. // #include <ptlib.h> #include <ptlib/pprocess.h> #include <ptlib/sockets.h> #include <ptclib/pssl.h> #include <ptclib/http.h> #include <ptclib/threadpool.h> class HTTPConnection { public: HTTPConnection( PHTTPSpace & httpNameSpace #if P_SSL , PSSLContext * context #endif ) : m_httpNameSpace(httpNameSpace) #if P_SSL , m_context(context) #endif { } void Work() { PTRACE(3, "HTTPTest\tStarted work on " << m_socket.GetPeerAddress()); PHTTPServer httpServer(m_httpNameSpace); #if P_SSL if (m_context != NULL) { PSSLChannel * ssl = new PSSLChannel(m_context); if (!ssl->Open(m_socket)) return; if (!ssl->Accept()) return; if (!httpServer.Open(ssl)) return; } else #endif if (!httpServer.Open(m_socket)) return; unsigned count = 0; while (httpServer.ProcessCommand()) ++count; PTRACE(3, "HTTPTest\tEnded work on " << m_socket.GetPeerAddress() << ", " << count << " transactions."); } PHTTPSpace & m_httpNameSpace; #if P_SSL PSSLContext * m_context; #endif PTCPSocket m_socket; }; class HTTPTest : public PProcess { PCLASSINFO(HTTPTest, PProcess) PSyncPoint m_done; public: PDECLARE_HttpPoolNotifier(HTTPTest, OnPoolDone) { m_done.Signal(); } void ClientPool(PHTTP::Commands cmd, const PArgList & args) { PHTTPClientPool pool; #if P_SSL pool.SetSSLCredentials(args.GetOptionString("ca"), args.GetOptionString("certificate"), args.GetOptionString("private-key")); #endif pool.QueueRequest(PHTTPClientPool::Request(cmd, args[0], PCREATE_NOTIFIER(OnPoolDone))); m_done.Wait(); } void Client(PHTTP::Commands cmd, const PArgList & args) { PHTTPClient client; #if P_SSL client.SetSSLCredentials(args.GetOptionString("ca"), args.GetOptionString("certificate"), args.GetOptionString("private-key")); #endif bool ok; switch (cmd) { case PHTTP::GET : { PString str; ok = client.GetTextDocument(args[0], str); if (ok) cout << "Response body: \"" << str << '"' << endl; break; } case PHTTP::DELETE : ok = client.DeleteDocument(args[0]); break; case PHTTP::PUT : ok = client.PutDocument(args[0], PFilePath(args[1])); break; case PHTTP::POST : { PMIMEInfo outMIME; ok = client.PostData(args[0], outMIME, args[1]); break; } default : cerr << args.Usage("[ url [ file ] ]"); return; } if (ok) cout << client.GetNameFromCommand(cmd) << " sucessful."; else cout << "Error in " << client.GetNameFromCommand(cmd) << " code=" << client.GetLastResponseCode() << " info=\"" << client.GetLastResponseInfo() << '"'; cout << endl; } void Server(const PArgList & args) { PQueuedThreadPool<HTTPConnection> pool; pool.SetMaxWorkers(args.GetOptionString('T', "10").AsUnsigned()); #if P_SSL PSSLContext * sslContext = args.HasOption('s') ? new PSSLContext : NULL; if (sslContext != NULL) { if (!sslContext->SetCredentials(args.GetOptionString("ca", "."), args.GetOptionString("certificate", "certificate.pem"), args.GetOptionString("private-key", "privatekey.pem"), true)) { cerr << "Could not set credentials for SSL" << endl; return; } } PTCPSocket listener(args.GetOptionAs('p', (WORD)(sslContext != NULL ? 443 : 80))); #else PTCPSocket listener(args.GetOptionAs('p', 80)); #endif if (!listener.Listen(args.GetOptionString('Q', "100").AsUnsigned())) { cerr << "Could not listen on port " << listener.GetPort() << endl; return; } PHTTPSpace httpNameSpace; httpNameSpace.AddResource(new PHTTPString("index.html", "Hello", "text/plain")); cout << "Listening for " #if P_SSL << (sslContext != NULL ? "https" : "http") << #else "http" #endif " on port " << listener.GetPort() << endl; for (;;) { #if P_SSL HTTPConnection * connection = new HTTPConnection(httpNameSpace, sslContext); #else HTTPConnection * connection = new HTTPConnection(httpNameSpace); #endif if (connection->m_socket.Accept(listener)) pool.AddWork(connection); else { delete connection; cerr << "Error in accept: " << listener.GetErrorText() << endl; break; } } cout << "Exiting HTTP test" << endl; } void Main() { PArgList & args = GetArguments(); args.Parse("h-help. print this help message.\n" "O-operation: do a GET/POST/PUT/DELETE, if absent then acts as server\n" "P-pool. do above operation using client pool" "p-port: port number to listen on (default 80 or 443).\n" #if P_SSL "s-secure. SSL/TLS mode for server.\n" "-ca: SSL/TLS client certificate authority file/directory.\n" "-certificate: SSL/TLS server certificate.\n" "-private-key: SSL/TLS server private key.\n" #endif "T-theads: max number of threads in pool(default 10)\n" "Q-queue: max queue size for listening sockets(default 100).\n" PTRACE_ARGLIST ); PTRACE_INITIALISE(args); if (!args.IsParsed() || args.HasOption('h')) { cerr << args.Usage("[ options] [ url [ file ] ]"); return; } if (args.HasOption('O')) { PINDEX cmd = PHTTPClient().GetCommandFromName(args.GetOptionString('O')); if (cmd == P_MAX_INDEX) { cerr << args.Usage("[ options] [ url [ file ] ]"); return; } if (args.GetCount() < (cmd == PHTTP::PUT || cmd == PHTTP::POST ? 2 : 1)) { cerr << args.Usage("[ options] [ url [ file ] ]"); return; } if (args.HasOption('P')) ClientPool((PHTTP::Commands)cmd, args); else Client((PHTTP::Commands)cmd, args); } else Server(args); } }; PCREATE_PROCESS(HTTPTest) // End of hello.cxx
25.923077
110
0.56864
sverdlin
707cc39b567fbaeed5f36dbccfeb72f662379474
12,933
cpp
C++
src/MDIDocing/PropertiesWnd.cpp
Vladimir-Novick/MDIDocking
eef1a67a78a864cec90670d13f382b51f9b0a0b1
[ "MIT" ]
null
null
null
src/MDIDocing/PropertiesWnd.cpp
Vladimir-Novick/MDIDocking
eef1a67a78a864cec90670d13f382b51f9b0a0b1
[ "MIT" ]
null
null
null
src/MDIDocing/PropertiesWnd.cpp
Vladimir-Novick/MDIDocking
eef1a67a78a864cec90670d13f382b51f9b0a0b1
[ "MIT" ]
null
null
null
#include "pch.h" #include "framework.h" #include "PropertiesWnd.h" #include "Resource.h" #include "MainFrm.h" #include "MDIDocing.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ///////////////////////////////////////////////////////////////////////////// // CResourceViewBar CPropertiesWnd::CPropertiesWnd() noexcept { m_nComboHeight = 0; } CPropertiesWnd::~CPropertiesWnd() { } BEGIN_MESSAGE_MAP(CPropertiesWnd, CDockablePane) ON_WM_CREATE() ON_WM_SIZE() ON_COMMAND(ID_EXPAND_ALL, OnExpandAllProperties) ON_UPDATE_COMMAND_UI(ID_EXPAND_ALL, OnUpdateExpandAllProperties) ON_COMMAND(ID_SORTPROPERTIES, OnSortProperties) ON_UPDATE_COMMAND_UI(ID_SORTPROPERTIES, OnUpdateSortProperties) ON_COMMAND(ID_PROPERTIES1, OnProperties1) ON_UPDATE_COMMAND_UI(ID_PROPERTIES1, OnUpdateProperties1) ON_COMMAND(ID_PROPERTIES2, OnProperties2) ON_UPDATE_COMMAND_UI(ID_PROPERTIES2, OnUpdateProperties2) ON_WM_SETFOCUS() ON_WM_SETTINGCHANGE() ON_COMMAND(ID_SHOW_ALL_BUTTON, OnShowAllButton) ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_BUTTON, OnUpdateShowAllButton) ON_COMMAND(ID_CLEAR_BUTTON, OnClearButton) ON_UPDATE_COMMAND_UI(ID_CLEAR_BUTTON, OnUpdateClearButton) ON_COMMAND(ID_RUN_BUTTON, OnRunButton) ON_UPDATE_COMMAND_UI(ID_RUN_BUTTON, OnUpdateRunButton) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResourceViewBar message handlers void CPropertiesWnd::AdjustLayout() { if (GetSafeHwnd () == nullptr || (AfxGetMainWnd() != nullptr && AfxGetMainWnd()->IsIconic())) { return; } CRect rectClient; GetClientRect(rectClient); int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy; m_wndObjectCombo.SetWindowPos(nullptr, rectClient.left, rectClient.top, rectClient.Width(), m_nComboHeight*3, SWP_NOACTIVATE | SWP_NOZORDER); m_wndToolBar.SetWindowPos(nullptr, rectClient.left, rectClient.top + m_nComboHeight, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER); m_wndPropList.SetWindowPos(nullptr, rectClient.left, rectClient.top + m_nComboHeight + cyTlb, rectClient.Width(), rectClient.Height() -(m_nComboHeight+cyTlb)- m_nComboHeight*2 , SWP_NOACTIVATE | SWP_NOZORDER); m_CheckboxOR.SetWindowPos(nullptr, rectClient.left, rectClient.top + m_nComboHeight + cyTlb + rectClient.Height() - (m_nComboHeight + cyTlb) - m_nComboHeight*2, rectClient.Width(), m_nComboHeight , SWP_NOACTIVATE | SWP_NOZORDER); m_ButtonShowAll.SetWindowPos(nullptr, rectClient.left, rectClient.top + m_nComboHeight + cyTlb + rectClient.Height() - (m_nComboHeight + cyTlb) - m_nComboHeight, rectClient.Width() / 3, m_nComboHeight , SWP_NOACTIVATE | SWP_NOZORDER); m_ClearButton.SetWindowPos(nullptr, rectClient.left + rectClient.Width() / 3, rectClient.top + m_nComboHeight + cyTlb + rectClient.Height() - (m_nComboHeight + cyTlb) - m_nComboHeight, rectClient.Width()/3, m_nComboHeight , SWP_NOACTIVATE | SWP_NOZORDER); m_RunButton.SetWindowPos(nullptr, rectClient.left + (rectClient.Width()/3)*2, rectClient.top + m_nComboHeight + cyTlb + rectClient.Height() - (m_nComboHeight + cyTlb) - m_nComboHeight, rectClient.Width() / 3, m_nComboHeight , SWP_NOACTIVATE | SWP_NOZORDER); m_CheckboxOR.ShowWindow(TRUE); m_ButtonShowAll.ShowWindow(TRUE); m_ClearButton.ShowWindow(TRUE); m_RunButton.ShowWindow(TRUE); } int CPropertiesWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDockablePane::OnCreate(lpCreateStruct) == -1) return -1; CRect rectDummy; rectDummy.SetRectEmpty(); CRect rectDummy2; rectDummy2.SetRectEmpty(); // Create combo: const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | WS_BORDER | CBS_SORT | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; if (!m_wndObjectCombo.Create(dwViewStyle, rectDummy, this, 1)) { TRACE0("Failed to create Properties Combo \n"); return -1; // fail to create } m_wndObjectCombo.AddString(_T("Application")); m_wndObjectCombo.AddString(_T("Properties Window")); m_wndObjectCombo.SetCurSel(0); CRect rectCombo; m_wndObjectCombo.GetClientRect (&rectCombo); m_nComboHeight = rectCombo.Height(); if (!m_wndPropList.Create(WS_VISIBLE | WS_CHILD, rectDummy, this, 2)) { TRACE0("Failed to create Properties Grid \n"); return -1; // fail to create } InitPropList(); m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_PROPERTIES); m_wndToolBar.LoadToolBar(IDR_PROPERTIES, 0, 0, TRUE /* Is locked */); m_wndToolBar.CleanUpLockedImages(); m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_PROPERTIES_HC : IDR_PROPERTIES, 0, 0, TRUE /* Locked */); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT)); m_wndToolBar.SetOwner(this); // All commands will be routed via this control , not via the parent frame: m_wndToolBar.SetRouteCommandsViaFrame(FALSE); m_ButtonShowAll.Create(_T("Show All"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, rectDummy, this, ID_SHOW_ALL_BUTTON); m_ClearButton.Create(_T("Clear"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, rectDummy, this, ID_CLEAR_BUTTON); m_RunButton.Create(_T("Filter"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, rectDummy, this, ID_RUN_BUTTON); m_ButtonShowAll.SetIcon((HICON)LoadImage(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_PROPERTIES_SHOW_ALL), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR)); m_ClearButton.SetIcon((HICON)LoadImage(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_PROPERTIES_CLEAR), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR)); m_RunButton.SetIcon((HICON)LoadImage(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_PROPERTIES_RUN), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR)); m_CheckboxOR.Create(_T("OR Search Condition"), WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX | BST_CHECKED, rectDummy, this, ID_CHECK_BOX_OR); SetCheckBoxFont(); AdjustLayout(); return 0; } void CPropertiesWnd::OnSize(UINT nType, int cx, int cy) { CDockablePane::OnSize(nType, cx, cy); AdjustLayout(); } void CPropertiesWnd::OnExpandAllProperties() { m_wndPropList.ExpandAll(); } void CPropertiesWnd::OnUpdateExpandAllProperties(CCmdUI* /* pCmdUI */) { } void CPropertiesWnd::OnSortProperties() { m_wndPropList.SetAlphabeticMode(!m_wndPropList.IsAlphabeticMode()); } void CPropertiesWnd::OnUpdateSortProperties(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_wndPropList.IsAlphabeticMode()); } void CPropertiesWnd::OnProperties1() { // TODO: Add your command handler code here } void CPropertiesWnd::OnUpdateProperties1(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnProperties2() { // TODO: Add your command handler code here } void CPropertiesWnd::OnUpdateProperties2(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnShowAllButton() { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnUpdateShowAllButton(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnClearButton() { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnUpdateClearButton(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnRunButton() { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnUpdateRunButton(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here } void CPropertiesWnd::InitPropList() { SetPropListFont(); m_wndPropList.EnableHeaderCtrl(FALSE); m_wndPropList.EnableDescriptionArea(); m_wndPropList.SetVSDotNetLook(); m_wndPropList.MarkModifiedProperties(); CMFCPropertyGridProperty* pGroup1 = new CMFCPropertyGridProperty(_T("Appearance")); pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("3D Look"), (_variant_t) false, _T("Specifies the window's font will be non-bold and controls will have a 3D border"))); CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(_T("Border"), _T("Dialog Frame"), _T("One of: None, Thin, Resizable, or Dialog Frame")); pProp->AddOption(_T("None")); pProp->AddOption(_T("Thin")); pProp->AddOption(_T("Resizable")); pProp->AddOption(_T("Dialog Frame")); pProp->AllowEdit(FALSE); pGroup1->AddSubItem(pProp); pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("Caption"), (_variant_t) _T("About"), _T("Specifies the text that will be displayed in the window's title bar"))); m_wndPropList.AddProperty(pGroup1); CMFCPropertyGridProperty* pSize = new CMFCPropertyGridProperty(_T("Window Size"), 0, TRUE); pProp = new CMFCPropertyGridProperty(_T("Height"), (_variant_t) 250l, _T("Specifies the window's height")); pProp->EnableSpinControl(TRUE, 50, 300); pSize->AddSubItem(pProp); pProp = new CMFCPropertyGridProperty( _T("Width"), (_variant_t) 150l, _T("Specifies the window's width")); pProp->EnableSpinControl(TRUE, 50, 200); pSize->AddSubItem(pProp); m_wndPropList.AddProperty(pSize); CMFCPropertyGridProperty* pGroup2 = new CMFCPropertyGridProperty(_T("Font")); LOGFONT lf; CFont* font = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); font->GetLogFont(&lf); _tcscpy_s(lf.lfFaceName, _T("Arial")); pGroup2->AddSubItem(new CMFCPropertyGridFontProperty(_T("Font"), lf, CF_EFFECTS | CF_SCREENFONTS, _T("Specifies the default font for the window"))); pGroup2->AddSubItem(new CMFCPropertyGridProperty(_T("Use System Font"), (_variant_t) true, _T("Specifies that the window uses MS Shell Dlg font"))); m_wndPropList.AddProperty(pGroup2); CMFCPropertyGridProperty* pGroup3 = new CMFCPropertyGridProperty(_T("Misc")); pProp = new CMFCPropertyGridProperty(_T("(Name)"), _T("Application")); pProp->Enable(FALSE); pGroup3->AddSubItem(pProp); CMFCPropertyGridColorProperty* pColorProp = new CMFCPropertyGridColorProperty(_T("Window Color"), RGB(210, 192, 254), nullptr, _T("Specifies the default window color")); pColorProp->EnableOtherButton(_T("Other...")); pColorProp->EnableAutomaticButton(_T("Default"), ::GetSysColor(COLOR_3DFACE)); pGroup3->AddSubItem(pColorProp); static const TCHAR szFilter[] = _T("Icon Files(*.ico)|*.ico|All Files(*.*)|*.*||"); pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Icon"), TRUE, _T(""), _T("ico"), 0, szFilter, _T("Specifies the window icon"))); pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Folder"), _T("c:\\"))); m_wndPropList.AddProperty(pGroup3); CMFCPropertyGridProperty* pGroup4 = new CMFCPropertyGridProperty(_T("Hierarchy")); CMFCPropertyGridProperty* pGroup41 = new CMFCPropertyGridProperty(_T("First sub-level")); pGroup4->AddSubItem(pGroup41); CMFCPropertyGridProperty* pGroup411 = new CMFCPropertyGridProperty(_T("Second sub-level")); pGroup41->AddSubItem(pGroup411); pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 1"), (_variant_t) _T("Value 1"), _T("This is a description"))); pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 2"), (_variant_t) _T("Value 2"), _T("This is a description"))); pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 3"), (_variant_t) _T("Value 3"), _T("This is a description"))); pGroup4->Expand(FALSE); m_wndPropList.AddProperty(pGroup4); } void CPropertiesWnd::OnSetFocus(CWnd* pOldWnd) { CDockablePane::OnSetFocus(pOldWnd); m_wndPropList.SetFocus(); } void CPropertiesWnd::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { CDockablePane::OnSettingChange(uFlags, lpszSection); SetPropListFont(); } void CPropertiesWnd::SetPropListFont() { ::DeleteObject(m_fntPropList.Detach()); LOGFONT lf; afxGlobalData.fontRegular.GetLogFont(&lf); NONCLIENTMETRICS info; info.cbSize = sizeof(info); afxGlobalData.GetNonClientMetrics(info); lf.lfHeight = info.lfMenuFont.lfHeight; lf.lfWeight = info.lfMenuFont.lfWeight; lf.lfItalic = info.lfMenuFont.lfItalic; m_fntPropList.CreateFontIndirect(&lf); m_wndPropList.SetFont(&m_fntPropList); m_wndObjectCombo.SetFont(&m_fntPropList); } void CPropertiesWnd::SetCheckBoxFont() { ::DeleteObject(m_fntCheckBox.Detach()); LOGFONT lf; afxGlobalData.fontRegular.GetLogFont(&lf); NONCLIENTMETRICS info; info.cbSize = sizeof(info); afxGlobalData.GetNonClientMetrics(info); lf.lfHeight = info.lfMenuFont.lfHeight; lf.lfWeight = info.lfMenuFont.lfWeight; lf.lfItalic = info.lfMenuFont.lfItalic; m_fntCheckBox.CreateFontIndirect(&lf); m_CheckboxOR.SetFont(&m_fntCheckBox); }
31.85468
174
0.734632
Vladimir-Novick
707e59c0f74ea3662feec672701a34791ec2460c
14,278
hpp
C++
Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.hpp
azhirnov/DiligentCore
28ad08478938d8c910195eff169513cd4eef9e3e
[ "Apache-2.0" ]
null
null
null
Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.hpp
azhirnov/DiligentCore
28ad08478938d8c910195eff169513cd4eef9e3e
[ "Apache-2.0" ]
null
null
null
Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.hpp
azhirnov/DiligentCore
28ad08478938d8c910195eff169513cd4eef9e3e
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2021 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once /// \file /// Declaration of Diligent::RenderDeviceD3D12Impl class #include "RenderDeviceD3D12.h" #include "RenderDeviceD3DBase.hpp" #include "RenderDeviceNextGenBase.hpp" #include "DescriptorHeap.hpp" #include "CommandListManager.hpp" #include "CommandContext.hpp" #include "D3D12DynamicHeap.hpp" #include "Atomics.hpp" #include "CommandQueueD3D12.h" #include "GenerateMips.hpp" #include "QueryManagerD3D12.hpp" #include "DXCompiler.hpp" // The macros below are only defined in Win SDK 19041+ and are missing in 17763 #ifndef D3D12_RAYTRACING_MAX_RAY_GENERATION_SHADER_THREADS # define D3D12_RAYTRACING_MAX_RAY_GENERATION_SHADER_THREADS (1073741824) #endif #ifndef D3D12_RAYTRACING_MAX_SHADER_RECORD_STRIDE # define D3D12_RAYTRACING_MAX_SHADER_RECORD_STRIDE (4096) #endif #ifndef D3D12_RAYTRACING_MAX_INSTANCES_PER_TOP_LEVEL_ACCELERATION_STRUCTURE # define D3D12_RAYTRACING_MAX_INSTANCES_PER_TOP_LEVEL_ACCELERATION_STRUCTURE (16777216) #endif #ifndef D3D12_RAYTRACING_MAX_PRIMITIVES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE # define D3D12_RAYTRACING_MAX_PRIMITIVES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE (536870912) #endif #ifndef D3D12_RAYTRACING_MAX_GEOMETRIES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE # define D3D12_RAYTRACING_MAX_GEOMETRIES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE (16777216) #endif namespace Diligent { /// Render device implementation in Direct3D12 backend. class RenderDeviceD3D12Impl final : public RenderDeviceNextGenBase<RenderDeviceD3DBase<IRenderDeviceD3D12>, ICommandQueueD3D12> { public: using TRenderDeviceBase = RenderDeviceNextGenBase<RenderDeviceD3DBase<IRenderDeviceD3D12>, ICommandQueueD3D12>; RenderDeviceD3D12Impl(IReferenceCounters* pRefCounters, IMemoryAllocator& RawMemAllocator, IEngineFactory* pEngineFactory, const EngineD3D12CreateInfo& EngineCI, ID3D12Device* pD3D12Device, size_t CommandQueueCount, ICommandQueueD3D12** ppCmdQueues) noexcept(false); ~RenderDeviceD3D12Impl(); IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_RenderDeviceD3D12, TRenderDeviceBase) /// Implementation of IRenderDevice::CreateGraphicsPipelineState() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateGraphicsPipelineState(const GraphicsPipelineStateCreateInfo& PSOCreateInfo, IPipelineState** ppPipelineState) override final; /// Implementation of IRenderDevice::CreateComputePipelineState() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateComputePipelineState(const ComputePipelineStateCreateInfo& PSOCreateInfo, IPipelineState** ppPipelineState) override final; /// Implementation of IRenderDevice::CreateRayTracingPipelineState() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateRayTracingPipelineState(const RayTracingPipelineStateCreateInfo& PSOCreateInfo, IPipelineState** ppPipelineState) override final; /// Implementation of IRenderDevice::CreateBuffer() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer) override final; /// Implementation of IRenderDevice::CreateShader() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateShader(const ShaderCreateInfo& ShaderCreateInfo, IShader** ppShader) override final; /// Implementation of IRenderDevice::CreateTexture() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture) override final; void CreateTexture(const TextureDesc& TexDesc, ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, class TextureD3D12Impl** ppTexture); /// Implementation of IRenderDevice::CreateSampler() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateSampler(const SamplerDesc& SamplerDesc, ISampler** ppSampler) override final; /// Implementation of IRenderDevice::CreateFence() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateFence(const FenceDesc& Desc, IFence** ppFence) override final; /// Implementation of IRenderDevice::CreateQuery() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateQuery(const QueryDesc& Desc, IQuery** ppQuery) override final; /// Implementation of IRenderDevice::CreateRenderPass() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateRenderPass(const RenderPassDesc& Desc, IRenderPass** ppRenderPass) override final; /// Implementation of IRenderDevice::CreateFramebuffer() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateFramebuffer(const FramebufferDesc& Desc, IFramebuffer** ppFramebuffer) override final; /// Implementation of IRenderDevice::CreateBLAS() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateBLAS(const BottomLevelASDesc& Desc, IBottomLevelAS** ppBLAS) override final; /// Implementation of IRenderDevice::CreateTLAS() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateTLAS(const TopLevelASDesc& Desc, ITopLevelAS** ppTLAS) override final; /// Implementation of IRenderDevice::CreateSBT() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE CreateSBT(const ShaderBindingTableDesc& Desc, IShaderBindingTable** ppSBT) override final; /// Implementation of IRenderDeviceD3D12::GetD3D12Device(). virtual ID3D12Device* DILIGENT_CALL_TYPE GetD3D12Device() override final { return m_pd3d12Device; } /// Implementation of IRenderDeviceD3D12::CreateTextureFromD3DResource(). virtual void DILIGENT_CALL_TYPE CreateTextureFromD3DResource(ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, ITexture** ppTexture) override final; /// Implementation of IRenderDeviceD3D12::CreateBufferFromD3DResource(). virtual void DILIGENT_CALL_TYPE CreateBufferFromD3DResource(ID3D12Resource* pd3d12Buffer, const BufferDesc& BuffDesc, RESOURCE_STATE InitialState, IBuffer** ppBuffer) override final; /// Implementation of IRenderDeviceD3D12::CreateBLASFromD3DResource(). virtual void DILIGENT_CALL_TYPE CreateBLASFromD3DResource(ID3D12Resource* pd3d12BLAS, const BottomLevelASDesc& Desc, RESOURCE_STATE InitialState, IBottomLevelAS** ppBLAS) override final; /// Implementation of IRenderDeviceD3D12::CreateTLASFromD3DResource(). virtual void DILIGENT_CALL_TYPE CreateTLASFromD3DResource(ID3D12Resource* pd3d12TLAS, const TopLevelASDesc& Desc, RESOURCE_STATE InitialState, ITopLevelAS** ppTLAS) override final; DescriptorHeapAllocation AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1); DescriptorHeapAllocation AllocateGPUDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1); /// Implementation of IRenderDevice::IdleGPU() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE IdleGPU() override final; using PooledCommandContext = std::unique_ptr<CommandContext, STDDeleterRawMem<CommandContext>>; PooledCommandContext AllocateCommandContext(const Char* ID = ""); void CloseAndExecuteTransientCommandContext(Uint32 CommandQueueIndex, PooledCommandContext&& Ctx); Uint64 CloseAndExecuteCommandContexts(Uint32 QueueIndex, Uint32 NumContexts, PooledCommandContext pContexts[], bool DiscardStaleObjects, std::vector<std::pair<Uint64, RefCntAutoPtr<IFence>>>* pSignalFences); void SignalFences(Uint32 QueueIndex, std::vector<std::pair<Uint64, RefCntAutoPtr<IFence>>>& SignalFences); // Disposes an unused command context void DisposeCommandContext(PooledCommandContext&& Ctx); void FlushStaleResources(Uint32 CmdQueueIndex); /// Implementation of IRenderDevice::() in Direct3D12 backend. virtual void DILIGENT_CALL_TYPE ReleaseStaleResources(bool ForceRelease = false) override final; D3D12DynamicMemoryManager& GetDynamicMemoryManager() { return m_DynamicMemoryManager; } GPUDescriptorHeap& GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE Type) { VERIFY_EXPR(Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); return m_GPUDescriptorHeaps[Type]; } const GenerateMipsHelper& GetMipsGenerator() const { return m_MipsGenerator; } QueryManagerD3D12& GetQueryManager() { return m_QueryMgr; } IDXCompiler* GetDxCompiler() const { return m_pDxCompiler.get(); } ID3D12Device2* GetD3D12Device2(); ID3D12Device5* GetD3D12Device5(); struct Properties { const Uint32 ShaderGroupHandleSize = D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES; const Uint32 MaxShaderRecordStride = D3D12_RAYTRACING_MAX_SHADER_RECORD_STRIDE; const Uint32 ShaderGroupBaseAlignment = D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT; const Uint32 MaxDrawMeshTasksCount = 64000; // from specs: https://microsoft.github.io/DirectX-Specs/d3d/MeshShader.html#dispatchmesh-api const Uint32 MaxRayTracingRecursionDepth = D3D12_RAYTRACING_MAX_DECLARABLE_TRACE_RECURSION_DEPTH; const Uint32 MaxRayGenThreads = D3D12_RAYTRACING_MAX_RAY_GENERATION_SHADER_THREADS; const Uint32 MaxInstancesPerTLAS = D3D12_RAYTRACING_MAX_INSTANCES_PER_TOP_LEVEL_ACCELERATION_STRUCTURE; const Uint32 MaxPrimitivesPerBLAS = D3D12_RAYTRACING_MAX_PRIMITIVES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE; const Uint32 MaxGeometriesPerBLAS = D3D12_RAYTRACING_MAX_GEOMETRIES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE; ShaderVersion MaxShaderVersion; }; const Properties& GetProperties() const { return m_Properties; } private: template <typename PSOCreateInfoType> void CreatePipelineState(const PSOCreateInfoType& PSOCreateInfo, IPipelineState** ppPipelineState); virtual void TestTextureFormat(TEXTURE_FORMAT TexFormat) override final; void FreeCommandContext(PooledCommandContext&& Ctx); CComPtr<ID3D12Device> m_pd3d12Device; CComPtr<ID3D12Device2> m_pd3d12Device2; CComPtr<ID3D12Device5> m_pd3d12Device5; EngineD3D12CreateInfo m_EngineAttribs; CPUDescriptorHeap m_CPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES]; GPUDescriptorHeap m_GPUDescriptorHeaps[2]; // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV == 0 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER == 1 CommandListManager m_CmdListManager; std::mutex m_ContextPoolMutex; std::vector<PooledCommandContext, STDAllocatorRawMem<PooledCommandContext>> m_ContextPool; #ifdef DILIGENT_DEVELOPMENT Atomics::AtomicLong m_AllocatedCtxCounter = 0; #endif D3D12DynamicMemoryManager m_DynamicMemoryManager; // Note: mips generator must be released after the device has been idled GenerateMipsHelper m_MipsGenerator; QueryManagerD3D12 m_QueryMgr; Properties m_Properties; std::unique_ptr<IDXCompiler> m_pDxCompiler; }; } // namespace Diligent
53.276119
171
0.682098
azhirnov
707f028dc94c86acebdc96b427cc882e9a5ca825
24,563
hpp
C++
applications/PfemFluidDynamicsApplication/custom_strategies/builders_and_solvers/explicit_two_step_v_p_builder_and_solver.hpp
AndreaVoltan/MyKratos7.0
e977752722e8ef1b606f25618c4bf8fd04c434cc
[ "BSD-4-Clause" ]
2
2020-04-30T19:13:08.000Z
2021-04-14T19:40:47.000Z
applications/PfemFluidDynamicsApplication/custom_strategies/builders_and_solvers/explicit_two_step_v_p_builder_and_solver.hpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
1
2020-04-30T19:19:09.000Z
2020-05-02T14:22:36.000Z
applications/PfemFluidDynamicsApplication/custom_strategies/builders_and_solvers/explicit_two_step_v_p_builder_and_solver.hpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
1
2020-06-12T08:51:24.000Z
2020-06-12T08:51:24.000Z
// // Project Name: KratosSolidMechanicsApplication $ // Created by: $Author: JMCarbonell $ // Last modified by: $Co-Author: $ // Date: $Date: July 2013 $ // Revision: $Revision: 0.0 $ // // #if !defined(KRATOS_EXPLICIT_TWO_STEP_V_P_BUILDER_AND_SOLVER ) #define KRATOS_EXPLICIT_TWO_STEP_V_P_BUILDER_AND_SOLVER /* System includes */ #include <set> #ifdef _OPENMP #include <omp.h> #endif /* External includes */ #include "boost/smart_ptr.hpp" #include "utilities/timer.h" /* Project includes */ #include "includes/define.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" namespace Kratos { /**@name Kratos Globals */ /*@{ */ /*@} */ /**@name Type Definitions */ /*@{ */ /*@} */ /**@name Enum's */ /*@{ */ /*@} */ /**@name Functions */ /*@{ */ /*@} */ /**@name Kratos Classes */ /*@{ */ template<class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class ExplicitTwoStepVPBuilderAndSolver : public BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver > { public: /**@name Type Definitions */ /*@{ */ KRATOS_CLASS_POINTER_DEFINITION( ExplicitTwoStepVPBuilderAndSolver ); typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; /*@} */ /**@name Life Cycle */ /*@{ */ /** Constructor. */ ExplicitTwoStepVPBuilderAndSolver(typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver >(pNewLinearSystemSolver) { std::cout<<"ExplicitTwoStepVPBuilderAndSolver "<<std::endl; } /** Destructor. */ virtual ~ExplicitTwoStepVPBuilderAndSolver() { } /*@} */ /**@name Operators */ /*@{ */ //************************************************************************** //************************************************************************** void BuildLHS( typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A) override { KRATOS_TRY // std::cout<<"BuildLHS for the momentum equation "<<std::endl; //Set Nodal Mass to zero NodesArrayType& pNodes = r_model_part.Nodes(); ElementsArrayType& pElements = r_model_part.Elements(); ProcessInfo& rCurrentProcessInfo = r_model_part.GetProcessInfo(); #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif vector<unsigned int> node_partition; OpenMPUtils::CreatePartition(number_of_threads, pNodes.size(), node_partition); vector<unsigned int> element_partition; OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); #pragma omp parallel { #pragma omp for for(int k=0; k<number_of_threads; k++) { typename NodesArrayType::iterator i_begin=pNodes.ptr_begin()+node_partition[k]; typename NodesArrayType::iterator i_end=pNodes.ptr_begin()+node_partition[k+1]; for(ModelPart::NodeIterator i=i_begin; i!= i_end; ++i) { double& nodal_mass = i->FastGetSolutionStepValue(NODAL_MASS); nodal_mass = 0.0; } } } //Calculate and assemble Mass Matrix on nodes // unsigned int index = 0; bool CalculateLumpedMassMatrix = false; if( rCurrentProcessInfo.Has(COMPUTE_LUMPED_MASS_MATRIX) ){ CalculateLumpedMassMatrix = rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX]; } #pragma omp parallel { int k = OpenMPUtils::ThisThread(); typename ElementsArrayType::iterator ElemBegin = pElements.begin() + element_partition[k]; typename ElementsArrayType::iterator ElemEnd = pElements.begin() + element_partition[k + 1]; for (typename ElementsArrayType::iterator itElem = ElemBegin; itElem != ElemEnd; itElem++) //MSI: To be parallelized { Matrix MassMatrix; Element::GeometryType& geometry = itElem->GetGeometry(); (itElem)->CalculateMassMatrix(MassMatrix, rCurrentProcessInfo); // const unsigned int dimension = geometry.WorkingSpaceDimension(); // index = 0; for (unsigned int i = 0; i <geometry.size(); i++) { // index = i*dimension; double& mass = geometry(i)->FastGetSolutionStepValue(NODAL_MASS); geometry(i)->SetLock(); if(!CalculateLumpedMassMatrix){ for (unsigned int j = 0; j <MassMatrix.size2(); j++) { mass += MassMatrix(i,j); } } else{ mass += MassMatrix(i,i); } geometry(i)->UnSetLock(); } } } rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX] = CalculateLumpedMassMatrix; // std::cout<<"....BuildLHS done!!"<<std::endl; KRATOS_CATCH( "" ) } //************************************************************************** //************************************************************************** void BuildRHS( typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemVectorType& b) override { KRATOS_TRY ProcessInfo& rCurrentProcessInfo = r_model_part.GetProcessInfo(); ElementsArrayType& pElements = r_model_part.Elements(); #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif vector<unsigned int> element_partition; OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); #pragma omp parallel { int k = OpenMPUtils::ThisThread(); typename ElementsArrayType::iterator ElemBegin = pElements.begin() + element_partition[k]; typename ElementsArrayType::iterator ElemEnd = pElements.begin() + element_partition[k + 1]; for (typename ElementsArrayType::iterator itElem = ElemBegin; itElem != ElemEnd; itElem++) //MSI: To be parallelized { LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; //Dummy //basic operations for the element considered (itElem)-> CalculateRightHandSide(RHS_Contribution,rCurrentProcessInfo); //add explicit contribution of the Element Residual (RHS) to nodal Force Residual (nodal RHS) (itElem)-> AddExplicitContribution(RHS_Contribution, RESIDUAL_VECTOR, NODAL_ERROR, rCurrentProcessInfo); } } KRATOS_CATCH( "" ) } //************************************************************************** //************************************************************************** void Build( typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& b) override { KRATOS_TRY // std::cout<<"Build for the continuity equation "<<std::endl; //Set Nodal Mass to zero NodesArrayType& pNodes = r_model_part.Nodes(); ElementsArrayType& pElements = r_model_part.Elements(); ProcessInfo& rCurrentProcessInfo = r_model_part.GetProcessInfo(); #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif vector<unsigned int> node_partition; OpenMPUtils::CreatePartition(number_of_threads, pNodes.size(), node_partition); vector<unsigned int> element_partition; OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); #pragma omp parallel { #pragma omp for for(int k=0; k<number_of_threads; k++) { typename NodesArrayType::iterator i_begin=pNodes.ptr_begin()+node_partition[k]; typename NodesArrayType::iterator i_end=pNodes.ptr_begin()+node_partition[k+1]; for(ModelPart::NodeIterator i=i_begin; i!= i_end; ++i) { double& nodal_mass = i->FastGetSolutionStepValue(NODAL_MASS); //it is the bulk contribution nodal_mass = 0.0; } } } //Calculate and assemble Mass Matrix on nodes bool CalculateLumpedMassMatrix = false; if( rCurrentProcessInfo.Has(COMPUTE_LUMPED_MASS_MATRIX) ){ CalculateLumpedMassMatrix = rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX]; } #pragma omp parallel { int k = OpenMPUtils::ThisThread(); typename ElementsArrayType::iterator ElemBegin = pElements.begin() + element_partition[k]; typename ElementsArrayType::iterator ElemEnd = pElements.begin() + element_partition[k + 1]; for (typename ElementsArrayType::iterator itElem = ElemBegin; itElem != ElemEnd; itElem++) //MSI: To be parallelized { Matrix MassMatrix; Element::GeometryType& geometry = itElem->GetGeometry(); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); (itElem)->CalculateLocalSystem(MassMatrix, RHS_Contribution, rCurrentProcessInfo); const unsigned int dimension = geometry.WorkingSpaceDimension(); for (unsigned int i = 0; i <geometry.size(); i++) { unsigned int index = i*dimension; double& mass = geometry(i)->FastGetSolutionStepValue(NODAL_MASS); geometry(i)->SetLock(); if(!CalculateLumpedMassMatrix){ for (unsigned int j = 0; j <MassMatrix.size2(); j++) { mass += MassMatrix(index,j); } } else{ mass += MassMatrix(index,index); } geometry(i)->UnSetLock(); } itElem -> AddExplicitContribution(RHS_Contribution, RESIDUAL_VECTOR, FORCE_RESIDUAL, rCurrentProcessInfo); } } rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX] = CalculateLumpedMassMatrix; KRATOS_CATCH( "" ) } // // //************************************************************************** // // //************************************************************************** // void BuildLHS( // typename TSchemeType::Pointer pScheme, // ModelPart& r_model_part, // TSystemMatrixType& A) // { // KRATOS_TRY // // std::cout<<"BuildLHS for the momentum equation "<<std::endl; // //Set Nodal Mass to zero // NodesArrayType& pNodes = r_model_part.Nodes(); // ElementsArrayType& pElements = r_model_part.Elements(); // ProcessInfo& rCurrentProcessInfo = r_model_part.GetProcessInfo(); // #ifdef _OPENMP // int number_of_threads = omp_get_max_threads(); // #else // int number_of_threads = 1; // #endif // vector<unsigned int> node_partition; // OpenMPUtils::CreatePartition(number_of_threads, pNodes.size(), node_partition); // vector<unsigned int> element_partition; // OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); // #pragma omp parallel // { // #pragma omp for // for(int k=0; k<number_of_threads; k++) // { // typename NodesArrayType::iterator i_begin=pNodes.ptr_begin()+node_partition[k]; // typename NodesArrayType::iterator i_end=pNodes.ptr_begin()+node_partition[k+1]; // for(ModelPart::NodeIterator i=i_begin; i!= i_end; ++i) // { // double& nodal_mass = i->FastGetSolutionStepValue(NODAL_MASS); // nodal_mass = 0.0; // } // } // } // //Calculate and assemble Mass Matrix on nodes // unsigned int index = 0; // bool CalculateLumpedMassMatrix = false; // if( rCurrentProcessInfo.Has(COMPUTE_LUMPED_MASS_MATRIX) ){ // CalculateLumpedMassMatrix = rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX]; // } // #pragma omp parallel // { // int k = OpenMPUtils::ThisThread(); // typename ElementsArrayType::iterator ElemBegin = pElements.begin() + element_partition[k]; // typename ElementsArrayType::iterator ElemEnd = pElements.begin() + element_partition[k + 1]; // for (typename ElementsArrayType::iterator itElem = ElemBegin; itElem != ElemEnd; itElem++) //MSI: To be parallelized // { // Matrix MassMatrix; // Element::GeometryType& geometry = itElem->GetGeometry(); // (itElem)->CalculateMassMatrix(MassMatrix, rCurrentProcessInfo); // const unsigned int dimension = geometry.WorkingSpaceDimension(); // index = 0; // for (unsigned int i = 0; i <geometry.size(); i++) // { // index = i*dimension; // double& mass = geometry(i)->FastGetSolutionStepValue(NODAL_MASS); // geometry(i)->SetLock(); // if(!CalculateLumpedMassMatrix){ // for (unsigned int j = 0; j <MassMatrix.size2(); j++) // { // mass += MassMatrix(index,j); // } // } // else{ // mass += MassMatrix(index,index); // } // geometry(i)->UnSetLock(); // } // } // } // rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX] = CalculateLumpedMassMatrix; // // std::cout<<"....BuildLHS done!!"<<std::endl; // KRATOS_CATCH( "" ) // } // //************************************************************************** // //************************************************************************** // void BuildRHS( // typename TSchemeType::Pointer pScheme, // ModelPart& r_model_part, // TSystemVectorType& b) // { // KRATOS_TRY // // std::cout<<"BuildRHS for momentum equations "<<std::endl; // // // Compute condition contributions to RHS. // // CalculateAndAddConditionsRHS(pScheme, r_model_part); // // Compute element contributions to RHS. // CalculateAndAddElementsRHS(pScheme, r_model_part); // // std::cout<<"....BuildRHS done!!"<<std::endl; // KRATOS_CATCH( "" ) // } // //************************************************************************** // //************************************************************************** // void Build( // typename TSchemeType::Pointer pScheme, // ModelPart& r_model_part, // TSystemMatrixType& A, // TSystemVectorType& b) // { // KRATOS_TRY // // std::cout<<"Build for the continuity equation "<<std::endl; // //Set Nodal Mass to zero // NodesArrayType& pNodes = r_model_part.Nodes(); // ElementsArrayType& pElements = r_model_part.Elements(); // ProcessInfo& rCurrentProcessInfo = r_model_part.GetProcessInfo(); // #ifdef _OPENMP // int number_of_threads = omp_get_max_threads(); // #else // int number_of_threads = 1; // #endif // vector<unsigned int> node_partition; // OpenMPUtils::CreatePartition(number_of_threads, pNodes.size(), node_partition); // vector<unsigned int> element_partition; // OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); // #pragma omp parallel // { // #pragma omp for // for(int k=0; k<number_of_threads; k++) // { // typename NodesArrayType::iterator i_begin=pNodes.ptr_begin()+node_partition[k]; // typename NodesArrayType::iterator i_end=pNodes.ptr_begin()+node_partition[k+1]; // for(ModelPart::NodeIterator i=i_begin; i!= i_end; ++i) // { // double& nodal_mass = i->FastGetSolutionStepValue(NODAL_MASS); //it is the bulk contribution // nodal_mass = 0.0; // } // } // } // //Calculate and assemble Mass Matrix on nodes // bool CalculateLumpedMassMatrix = false; // if( rCurrentProcessInfo.Has(COMPUTE_LUMPED_MASS_MATRIX) ){ // CalculateLumpedMassMatrix = rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX]; // } // #pragma omp parallel // { // int k = OpenMPUtils::ThisThread(); // typename ElementsArrayType::iterator ElemBegin = pElements.begin() + element_partition[k]; // typename ElementsArrayType::iterator ElemEnd = pElements.begin() + element_partition[k + 1]; // for (typename ElementsArrayType::iterator itElem = ElemBegin; itElem != ElemEnd; itElem++) //MSI: To be parallelized // { // Matrix MassMatrix; // Element::GeometryType& geometry = itElem->GetGeometry(); // LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); // (itElem)->CalculateLocalSystem(MassMatrix, RHS_Contribution, rCurrentProcessInfo); // // const unsigned int dimension = geometry.WorkingSpaceDimension(); // for (unsigned int i = 0; i <geometry.size(); i++) // { // double& mass = geometry(i)->FastGetSolutionStepValue(NODAL_MASS); // geometry(i)->SetLock(); // if(!CalculateLumpedMassMatrix){ // for (unsigned int j = 0; j <MassMatrix.size2(); j++) // { // mass += MassMatrix(i,j); // } // } // else{ // mass += MassMatrix(i,i); // } // geometry(i)->UnSetLock(); // } // itElem -> AddExplicitContribution(RHS_Contribution, RESIDUAL_VECTOR, NODAL_ERROR, rCurrentProcessInfo); // } // } // rCurrentProcessInfo[COMPUTE_LUMPED_MASS_MATRIX] = CalculateLumpedMassMatrix; // KRATOS_CATCH( "" ) // } //*************************************************************************** //*************************************************************************** void CalculateAndAddConditionsRHS(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part ) { KRATOS_TRY ProcessInfo& rCurrentProcessInfo = r_model_part.GetProcessInfo(); ConditionsArrayType& pConditions = r_model_part.Conditions(); #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif vector<unsigned int> condition_partition; OpenMPUtils::CreatePartition(number_of_threads, pConditions.size(), condition_partition); #pragma omp parallel for for(int k=0; k<number_of_threads; k++) { typename ConditionsArrayType::ptr_iterator it_begin=pConditions.ptr_begin()+condition_partition[k]; typename ConditionsArrayType::ptr_iterator it_end=pConditions.ptr_begin()+condition_partition[k+1]; for (typename ConditionsArrayType::ptr_iterator it= it_begin; it!=it_end; ++it) { LocalSystemVectorType RHS_Condition_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; //Dummy pScheme->Condition_Calculate_RHS_Contribution(*it, RHS_Condition_Contribution, EquationId, rCurrentProcessInfo); } } KRATOS_CATCH("") } //*************************************************************************** //*************************************************************************** void CalculateAndAddElementsRHS(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part ) { KRATOS_TRY // std::cout<<" CalculateAndAddElementsRHS "<<std::endl; ProcessInfo& rCurrentProcessInfo = r_model_part.GetProcessInfo(); ElementsArrayType& pElements = r_model_part.Elements(); #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif vector<unsigned int> element_partition; OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); #pragma omp parallel for for(int k=0; k<number_of_threads; k++) { typename ElementsArrayType::ptr_iterator it_begin=pElements.ptr_begin()+element_partition[k]; typename ElementsArrayType::ptr_iterator it_end=pElements.ptr_begin()+element_partition[k+1]; for (typename ElementsArrayType::ptr_iterator it= it_begin; it!=it_end; ++it) { LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; //Dummy // pScheme->Calculate_RHS_Contribution(*it, RHS_Contribution, EquationId, rCurrentProcessInfo); this->Calculate_RHS_Contribution(*it, RHS_Contribution, EquationId, rCurrentProcessInfo); } } // std::cout<<"CalculateAndAddElementsRHS done"<<std::endl; KRATOS_CATCH("") } void Calculate_RHS_Contribution(Element::Pointer rCurrentElement, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY //basic operations for the element considered (rCurrentElement) -> CalculateRightHandSide(RHS_Contribution,rCurrentProcessInfo); // //add explicit contribution of the Element Residual (RHS) to nodal Force Residual (nodal RHS) (rCurrentElement) -> AddExplicitContribution(RHS_Contribution, RESIDUAL_VECTOR, FORCE_RESIDUAL, rCurrentProcessInfo); KRATOS_CATCH( "" ) } /** this function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { this->mDofSet.clear(); // = DofsArrayType(); if (this->mpReactionsVector != NULL) TSparseSpace::Clear((this->mpReactionsVector)); // this->mReactionsVector = TSystemVectorType(); this->mpLinearSystemSolver->Clear(); if (this->GetEchoLevel() > 1) { std::cout << "ExplicitTwoStepVPBuilderAndSolver Clear Function called" << std::endl; } } /** * This function is designed to be called once to perform all the checks needed * on the input provided. Checks can be "expensive" as the function is designed * to catch user's errors. * @param r_model_part * @return 0 all ok */ int Check(ModelPart& r_model_part) override { KRATOS_TRY return 0; KRATOS_CATCH( "" ) } /*@} */ /**@name Operations */ /*@{ */ /*@} */ /**@name Access */ /*@{ */ /*@} */ /**@name Inquiry */ /*@{ */ /*@} */ /**@name Friends */ /*@{ */ /*@} */ protected: /**@name Protected static Member Variables */ /*@{ */ /*@} */ /**@name Protected member Variables */ /*@{ */ /*@} */ /**@name Protected Operators*/ /*@{ */ //****************************************************************************************** //****************************************************************************************** /*@} */ /**@name Protected Operations*/ /*@{ */ /*@} */ /**@name Protected Access */ /*@{ */ /*@} */ /**@name Protected Inquiry */ /*@{ */ /*@} */ /**@name Protected LifeCycle */ /*@{ */ /*@} */ private: /**@name Static Member Variables */ /*@{ */ /*@} */ /**@name Member Variables */ /*@{ */ /*@} */ /**@name Private Operators*/ /*@{ */ /*@} */ /**@name Private Operations*/ /*@{ */ /*@} */ /**@name Private Access */ /*@{ */ /*@} */ /**@name Private Inquiry */ /*@{ */ /*@} */ /**@name Un accessible methods */ /*@{ */ /*@} */ }; /* Class ExplicitTwoStepVPBuilderAndSolver */ /*@} */ /**@name Type Definitions */ /*@{ */ /*@} */ } /* namespace Kratos.*/ #endif /* KRATOS_EXPLICIT_TWO_STEP_V_P_BUILDER_AND_SOLVER defined */
29.593976
125
0.596059
AndreaVoltan
708289167c6673634e3580ba3e765b0905b509bd
29,821
cc
C++
src/ge/graph/load/new_model_manager/model_manager.cc
zengchen1024/graphengine
0c33e9d12562953ca4bd6c03cb77da2c2da74acd
[ "Apache-2.0" ]
1
2020-07-18T17:49:20.000Z
2020-07-18T17:49:20.000Z
src/ge/graph/load/new_model_manager/model_manager.cc
zengchen1024/graphengine
0c33e9d12562953ca4bd6c03cb77da2c2da74acd
[ "Apache-2.0" ]
null
null
null
src/ge/graph/load/new_model_manager/model_manager.cc
zengchen1024/graphengine
0c33e9d12562953ca4bd6c03cb77da2c2da74acd
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019-2020 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 "graph/load/new_model_manager/model_manager.h" #include <string> #include "common/l2_cache_optimize.h" #include "common/profiling/profiling_manager.h" #include "common/properties_manager.h" #include "framework/common/debug/ge_log.h" #include "graph/load/new_model_manager/davinci_model.h" #include "graph/load/new_model_manager/davinci_model_parser.h" namespace ge { thread_local uint32_t device_count = 0; namespace { const int kCmdParSize = 2; const int kDumpCmdPairSize = 2; } // namespace std::shared_ptr<ModelManager> ModelManager::GetInstance() { static const std::shared_ptr<ModelManager> instance_ptr = shared_ptr<ModelManager>(new (std::nothrow) ModelManager(), ModelManager::FinalizeForPtr); return instance_ptr; } ModelManager::ModelManager() { max_model_id_ = 0; } Status ModelManager::KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType op_type, uint64_t session_id, uint32_t model_id) { STR_FWK_OP_KERNEL param_base = {}; void *devicebase = nullptr; void *aicpu_kernel_addr = nullptr; const uint32_t kKernelType = 0; param_base.fwkKernelType = kKernelType; param_base.fwkKernelBase.fwk_kernel.opType = op_type; param_base.fwkKernelBase.fwk_kernel.sessionID = session_id; if (op_type == aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY) { std::vector<uint64_t> v_aicpu_kernel; std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id); auto iter = model_aicpu_kernel_.find(model_key); if (iter != model_aicpu_kernel_.end()) { GELOGD("kernel destroy session_id %lu, model_id %u.", session_id, model_id); v_aicpu_kernel = model_aicpu_kernel_.at(model_key); // Insert size of aicpu kernel vector in the first element v_aicpu_kernel.insert(v_aicpu_kernel.begin(), v_aicpu_kernel.size()); auto kernel_size = sizeof(uint64_t) * (v_aicpu_kernel.size()); rtError_t rt_ret = rtMalloc(&aicpu_kernel_addr, kernel_size, RT_MEMORY_HBM); GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(RT_FAILED, "rtMalloc error, ret: 0x%X", rt_ret); return RT_FAILED;) rt_ret = rtMemcpy(aicpu_kernel_addr, kernel_size, v_aicpu_kernel.data(), kernel_size, RT_MEMCPY_HOST_TO_DEVICE); GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(rt_ret, "rtMemcpy to input_output_addr_ error: 0x%X", rt_ret); GE_CHK_RT(rtFree(aicpu_kernel_addr)); return FAILED;) uint64_t kernel_id_addr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(aicpu_kernel_addr)); param_base.fwkKernelBase.fwk_kernel.kernelID = kernel_id_addr; // Remove model key from map model_aicpu_kernel_.erase(iter); } } rtError_t rt_ret = rtMalloc(&(devicebase), sizeof(STR_FWK_OP_KERNEL), RT_MEMORY_HBM); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "malloc device memory failed."); GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr))); return FAILED; } rt_ret = rtMemcpy(devicebase, sizeof(STR_FWK_OP_KERNEL), &param_base, sizeof(STR_FWK_OP_KERNEL), RT_MEMCPY_HOST_TO_DEVICE); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "memory copy to device failed."); GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr))); GE_CHK_RT(rtFree(devicebase)); return FAILED; } rtStream_t stream = nullptr; rt_ret = rtStreamCreate(&stream, 0); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "create stream failed."); GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr))); GE_CHK_RT(rtFree(devicebase)); return FAILED; } rt_ret = rtKernelLaunchEx(devicebase, sizeof(STR_FWK_OP_KERNEL), 0, stream); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "rtKernelLaunchEx failed."); GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr))); GE_CHK_RT(rtFree(devicebase)); GE_CHK_RT(rtStreamDestroy(stream)); return FAILED; } rt_ret = rtStreamSynchronize(stream); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "rtStreamSynchronize failed."); GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr))); GE_CHK_RT(rtFree(devicebase)); GE_CHK_RT(rtStreamDestroy(stream)); return FAILED; } if (aicpu_kernel_addr != nullptr) { rt_ret = rtFree(aicpu_kernel_addr); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "free memory failed."); GE_CHK_RT(rtFree(devicebase)); GE_CHK_RT(rtStreamDestroy(stream)); return FAILED; } } rt_ret = rtFree(devicebase); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "free memory failed."); GE_CHK_RT(rtStreamDestroy(stream)); return FAILED; } rt_ret = rtStreamDestroy(stream); if (rt_ret != RT_ERROR_NONE) { GELOGE(rt_ret, "rtStreamDestroy failed."); return FAILED; } return SUCCESS; } void ModelManager::DestroyAicpuSession(uint64_t session_id) { std::lock_guard<std::mutex> lock(sess_ids_mutex_); auto it = sess_ids_.find(session_id); if (it == sess_ids_.end()) { GELOGI("The session: %lu not created.", session_id); return; } else { Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_DESTROY, session_id, 0); if (ret != SUCCESS) { GELOGW("The session: %lu destroy failed.", session_id); } else { (void)sess_ids_.erase(session_id); GELOGI("The session: %lu destroyed.", session_id); } } } ge::Status ModelManager::DestroyAicpuKernel(uint64_t session_id, uint32_t model_id) { GELOGD("destroy aicpu kernel in session_id %lu, model_id %u.", session_id, model_id); std::lock_guard<std::mutex> lock(sess_ids_mutex_); std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id); if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) { Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY, session_id, model_id); if (ret != SUCCESS) { GELOGE(FAILED, "Destroy aicpu kernel failed."); return FAILED; } } return SUCCESS; } ge::Status ModelManager::CreateAicpuKernel(uint64_t session_id, uint32_t model_id, uint64_t kernel_id) { std::vector<uint64_t> v_aicpu_kernel; std::lock_guard<std::mutex> lock(sess_ids_mutex_); std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id); if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) { v_aicpu_kernel = model_aicpu_kernel_.at(model_key); } v_aicpu_kernel.push_back(kernel_id); model_aicpu_kernel_[model_key] = v_aicpu_kernel; return SUCCESS; } ModelManager::~ModelManager() { std::lock_guard<std::mutex> lock(map_mutex_); model_map_.clear(); model_aicpu_kernel_.clear(); GE_IF_BOOL_EXEC(device_count > 0, GE_CHK_RT(rtDeviceReset(0))); } /// /// @ingroup domi_ome /// @brief set Device. If no device available, return failure /// @return Status run result /// @author /// Status ModelManager::SetDevice(int32_t deviceId) const { GE_CHK_RT_RET(rtSetDevice(deviceId)); return SUCCESS; } /// /// @ingroup domi_ome /// @brief load model online /// @return Status run result /// Status ModelManager::LoadModelOnline(uint32_t &model_id, shared_ptr<ge::Model> &model, std::shared_ptr<ModelListener> listener) { GE_CHK_BOOL_RET_STATUS(listener.get() != nullptr, PARAM_INVALID, "Param incorrect, listener is null"); GenModelId(&model_id); GE_CHK_STATUS_RET(SetDevice(static_cast<int32_t>(GetContext().DeviceId())), "Set device failed, model id:%u.", model_id); std::shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(0, listener); if (davinci_model == nullptr) { GELOGE(FAILED, "davinci_model is nullptr"); return FAILED; } davinci_model->SetId(model_id); davinci_model->SetDeviceId(GetContext().DeviceId()); Status ret = SUCCESS; do { GeModelPtr ge_model; GE_IF_BOOL_EXEC( ModelHelper::TransModelToGeModel(model, ge_model) != SUCCESS, GELOGW("trans model to ge_model failed."); break;); GE_TIMESTAMP_START(Assign); GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Assign(ge_model)), GELOGW("assign model to modeldef failed."); break;); GE_TIMESTAMP_END(Assign, "GraphLoader::ModelAssign"); GE_TIMESTAMP_START(Init); GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Init()), GELOGW("DavinciInit failed."); break;); GE_TIMESTAMP_END(Init, "GraphLoader::ModelInit"); InsertModel(model_id, davinci_model); GELOGI("Parse model %u success.", model_id); } while (0); GE_CHK_RT(rtDeviceReset(static_cast<int32_t>(GetContext().DeviceId()))); return ret; } void ModelManager::InsertModel(uint32_t id, std::shared_ptr<DavinciModel> &davinci_model) { GE_CHK_BOOL_EXEC(davinci_model != nullptr, return, "davinci_model ptr is null, id: %u", id); std::lock_guard<std::mutex> lock(map_mutex_); model_map_[id] = davinci_model; } Status ModelManager::DeleteModel(uint32_t id) { std::lock_guard<std::mutex> lock(map_mutex_); auto it = model_map_.find(id); if (it == model_map_.end()) { GELOGE(PARAM_INVALID, "model id %u does not exists.", id); return PARAM_INVALID; } (void)model_map_.erase(it); free_model_id_.push_back(id); return SUCCESS; } std::shared_ptr<DavinciModel> ModelManager::GetModel(uint32_t id) { std::lock_guard<std::mutex> lock(map_mutex_); auto it = model_map_.find(id); return (it == model_map_.end()) ? nullptr : it->second; } Status ModelManager::Unload(uint32_t model_id) { GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload model id: %u", model_id); if (device_count > 0) { device_count--; GELOGI("Unload model %u success.", model_id); } else { GELOGI("Unload model %u success.no need reset device,device_count: %u", model_id, device_count); } return SUCCESS; } Status ModelManager::UnloadModeldef(uint32_t model_id) { GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload modeldef id: %u", model_id); return SUCCESS; } Status ModelManager::DataInput(const InputData &input_data, OutputData &output_data) { GELOGI("calling the DataInput"); SysMode mode = DavinciModel::GetSysMode(); if ((mode == RESET) || (mode == STOP)) { GELOGE(domi::MODEL_NOT_READY, "System mode is reset or stop"); return domi::MODEL_NOT_READY; } shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper()); GE_CHECK_NOTNULL(data_wrap); Status status = data_wrap->Init(input_data, output_data); if (status != SUCCESS) { GELOGE(domi::PUSH_DATA_FAILED, "Init InputDataWrapper failed, input data index: %u.", input_data.index); return domi::PUSH_DATA_FAILED; } uint32_t model_id = input_data.model_id; output_data.model_id = model_id; std::shared_ptr<DavinciModel> model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid Model ID %u in InputData! ", model_id); GE_IF_BOOL_EXEC(model->GetDataInputTid() == 0, model->SetDataInputTid(mmGetTid())); DataInputer *inputer = model->GetDataInputer(); GE_CHECK_NOTNULL(inputer); if (inputer->Push(data_wrap) != SUCCESS) { GELOGE(domi::DATA_QUEUE_ISFULL, "Data queue is full, please call again later, model_id %u ", model_id); return domi::DATA_QUEUE_ISFULL; } GELOGD("Data input success, model id:%u", model_id); return SUCCESS; } /// /// @ingroup domi_ome /// @brief load Input and output TensorInfor for Model /// @return Status run result /// Status ModelManager::DataInputTensor(uint32_t model_id, const std::vector<TensorInfo> &inputs, std::vector<TensorInfo> &outputs) { SysMode mode = DavinciModel::GetSysMode(); if ((mode == RESET) || (mode == STOP)) { GELOGE(domi::MODEL_NOT_READY, "System mode is reset or stop"); return domi::MODEL_NOT_READY; } std::shared_ptr<DavinciModel> model = GetModel(model_id); GE_CHECK_NOTNULL(model); InputData input_data; input_data.model_id = model_id; input_data.timeout = 0; input_data.timestamp = 0; input_data.index = 0; std::size_t index = 0; for (const auto &item : model->GetOpList()) { auto op = item.second; GE_CHECK_NOTNULL(op); if (op->GetType() == DATA) { GE_CHECK_GE(inputs.size(), 1); GE_CHECK_GE(inputs.size() - 1, index); DataBuffer data; data.data = inputs[index].data.data; data.length = inputs[index].data.length; input_data.blobs.push_back(data); index++; } } CHECK_FALSE_EXEC(input_data.blobs.size() >= inputs.size(), GELOGW("cur_inputs size = %zu, inputs size = %zu.", input_data.blobs.size(), inputs.size());); OutputData output_data; output_data.model_id = model_id; output_data.index = 0; for (size_t i = 0; i < outputs.size(); i++) { DataBuffer data; data.data = outputs[i].data.data; data.length = outputs[i].data.length; output_data.blobs.push_back(data); } shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper()); GE_CHECK_NOTNULL(data_wrap); GE_CHK_STATUS_EXEC(data_wrap->Init(input_data, output_data), return domi::PUSH_DATA_FAILED, "Init InputDataWrapper failed,input data model_id is : %u.", model_id); GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid Model ID %u in InputData! ", model_id); DataInputer *inputer = model->GetDataInputer(); GE_CHECK_NOTNULL(inputer); GE_CHK_STATUS_EXEC(inputer->Push(data_wrap), return domi::DATA_QUEUE_ISFULL, "Data queue is full, please call again later, model_id %u ", model_id); GELOGD("Data input success, model id:%u", model_id); return SUCCESS; } /// /// @ingroup domi_ome /// @brief create model thread, start to execute model /// @param [in] model_id Model ID to be started /// @return Status model run result /// @author /// Status ModelManager::Start(uint32_t model_id) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid Model ID %u to start! ", model_id); Status status = davinci_model->ModelRunStart(); if (status == SUCCESS) { GELOGI("Start model %u success.", model_id); } return status; } /// /// @ingroup domi_ome /// @brief Model ID stop /// @only when unloaded /// @param [in] model_id Model ID to be stopped /// @return Status model stop result /// @author /// Status ModelManager::Stop(uint32_t model_id) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid Model ID %u to stop!", model_id); Status status = davinci_model->ModelRunStop(); if (status == SUCCESS) { GELOGI("Stop model %u success.", model_id); } return status; } /// /// @ingroup domi_ome /// @brief Command handle /// @iterator 1 only Ieference, Debug 2 modes /// @param [in] command command to handle /// @return Status command handle result /// @author /// Status ModelManager::HandleCommand(const Command &command) { static const std::map<std::string, std::function<uint32_t(const Command &)>> cmds = { {"profile", HandleProfileCommand}, {"dump", HandleDumpCommand}, {"profiling", HandleAclProfilingCommand}}; auto iter = cmds.find(command.cmd_type); if (iter == cmds.end()) { GELOGE(PARAM_INVALID, "Unsupported command: %s", command.cmd_type.c_str()); return PARAM_INVALID; } else { return iter->second(command); } } Status ModelManager::HandleAclProfilingCommand(const Command &command) { if (command.cmd_params.size() < kCmdParSize) { GELOGE(PARAM_INVALID, "When the cmd_type is 'profiling', the size of cmd_params must larger than 2."); return PARAM_INVALID; } std::string map_key = command.cmd_params[0]; std::string value = command.cmd_params[1]; if (map_key == PROFILE_CONFIG) { ProfilingManager::Instance().SetProfilingConfig(value); } return SUCCESS; } Status ModelManager::HandleProfileCommand(const Command &command) { if (command.cmd_params.size() < kCmdParSize) { GELOGE(PARAM_INVALID, "When the cmd_type is 'profile', the size of cmd_params must larger than 2."); return PARAM_INVALID; } std::string map_key = command.cmd_params[0]; std::string value = command.cmd_params[1]; GELOGI("Profiling mode, Command key:%s , value:%s ", map_key.c_str(), value.c_str()); auto iter = PROFILE_COMPONENT_MAP.find(map_key); if (iter != PROFILE_COMPONENT_MAP.end()) { std::string property_value = (value == "on") ? "1" : "0"; PropertiesManager::Instance().SetPropertyValue(iter->second, property_value); } if ((map_key == PROFILER_JOBCTX || map_key == PROFILER_TARGET_PATH || map_key == RTS_PROFILE_PATH)) { PropertiesManager::Instance().SetPropertyValue(map_key, value); } if ((map_key == PROFILE_STOP_KEY) && (value == PROFILE_STOP_VALUE)) { rtError_t rt_ret = rtProfilerStop(); if (rt_ret != RT_ERROR_NONE) { GELOGE(PARAM_INVALID, "Call rtProfilerStop ret:%d", rt_ret); return PARAM_INVALID; } } return SUCCESS; } Status ModelManager::HandleDumpCommand(const Command &command) { if (command.cmd_params.size() % kDumpCmdPairSize != 0) { GELOGE(PARAM_INVALID, "When the cmd_type is 'dump', the size of cmd_params must be a even number."); return PARAM_INVALID; } std::string dump_status("off"); std::string dump_model(DUMP_ALL_MODEL); std::string dump_path("/"); std::set<std::string> dump_layers; std::string dump_layer_count; auto iter_dump_status = std::find(command.cmd_params.begin(), command.cmd_params.end(), DUMP_STATUS); if (iter_dump_status != command.cmd_params.end()) { ++iter_dump_status; if (iter_dump_status == command.cmd_params.end()) { GELOGE(PARAM_INVALID, "Invalid access."); return PARAM_INVALID; } dump_status = *iter_dump_status; GELOGI("dump status = %s.", dump_status.c_str()); } auto iter_dump_model = std::find(command.cmd_params.begin(), command.cmd_params.end(), DUMP_MODEL); if (iter_dump_model != command.cmd_params.end()) { ++iter_dump_model; if (iter_dump_model == command.cmd_params.end()) { GELOGE(PARAM_INVALID, "Invalid access."); return PARAM_INVALID; } dump_model = *iter_dump_model; GELOGI("dump model = %s.", dump_model.c_str()); } if (dump_status == "off" || dump_status == "OFF") { PropertiesManager::Instance().DeleteDumpPropertyValue(dump_model); return SUCCESS; } for (size_t i = 0; i < command.cmd_params.size() / kDumpCmdPairSize; ++i) { if (command.cmd_params.at(i * kDumpCmdPairSize).find(DUMP_LAYER) != std::string::npos) { GELOGI("dump layer: %s.", command.cmd_params.at(i * kDumpCmdPairSize + 1).c_str()); dump_layers.insert(command.cmd_params.at(i * kDumpCmdPairSize + 1)); } } auto iter_dump_path = std::find(command.cmd_params.begin(), command.cmd_params.end(), DUMP_FILE_PATH); if (iter_dump_path != command.cmd_params.end()) { ++iter_dump_path; if (iter_dump_path == command.cmd_params.end()) { GELOGE(PARAM_INVALID, "Invalid access."); return PARAM_INVALID; } dump_path = *iter_dump_path; if (!dump_path.empty() && dump_path[dump_path.size() - 1] != '/') { dump_path += "/"; } GELOGI("dump path = %s.", dump_path.c_str()); } PropertiesManager::Instance().AddDumpPropertyValue(dump_model, dump_layers); PropertiesManager::Instance().SetDumpOutputPath(dump_path); return SUCCESS; } Status ModelManager::GetMaxUsedMemory(const uint32_t model_id, uint64_t &max_size) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetMaxUsedMemory Failed, Invalid Model ID %u !", model_id); max_size = davinci_model->TotalMemSize(); return SUCCESS; } Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc, vector<InputOutputDescInfo> &output_desc) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetInputOutputDescInfo Failed, Invalid Model ID %u !", model_id); return davinci_model->GetInputOutputDescInfo(input_desc, output_desc); } Status ModelManager::GetInputOutputDescInfoForZeroCopy(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc, vector<InputOutputDescInfo> &output_desc) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetInputOutputDescInfo Failed, Invalid Model ID %u !", model_id); return davinci_model->GetInputOutputDescInfoForZeroCopy(input_desc, output_desc); } Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc, vector<InputOutputDescInfo> &output_desc, std::vector<uint32_t> &inputFormats, std::vector<uint32_t> &outputFormats) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetInputOutputDescInfo Failed, Invalid Model ID %u !", model_id); return davinci_model->GetInputOutputDescInfo(input_desc, output_desc, inputFormats, outputFormats); } Status ModelManager::GetInputOutputDescInfoForZeroCopy(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc, vector<InputOutputDescInfo> &output_desc, std::vector<uint32_t> &inputFormats, std::vector<uint32_t> &outputFormats) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetInputOutputDescInfo Failed, Invalid Model ID %u !", model_id); return davinci_model->GetInputOutputDescInfoForZeroCopy(input_desc, output_desc, inputFormats, outputFormats); } Status ModelManager::LoadModelOffline(uint32_t &model_id, const ModelData &model, shared_ptr<ModelListener> listener, void *dev_ptr, size_t mem_size, void *weight_ptr, size_t weight_size) { GE_CHK_BOOL_RET_STATUS(model.key.empty() || access(model.key.c_str(), F_OK) == 0, PARAM_INVALID, "input key file path is not valid!"); GenModelId(&model_id); shared_ptr<DavinciModel> davinci_model = nullptr; ModelHelper model_helper; Status ret = model_helper.LoadModel(model); if (ret != SUCCESS) { GELOGE(ret, "load model failed."); return ret; } do { GeModelPtr ge_model = model_helper.GetGeModel(); try { davinci_model = std::make_shared<DavinciModel>(model.priority, listener); } catch (std::bad_alloc &) { GELOGE(FAILED, "Make shared failed"); return FAILED; } catch (...) { GELOGE(FAILED, "Make shared failed since other exception raise"); return FAILED; } ret = davinci_model->Assign(ge_model); if (ret != SUCCESS) { GELOGW("assign model failed."); break; } davinci_model->SetId(model_id); ret = davinci_model->Init(dev_ptr, mem_size, weight_ptr, weight_size); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "DavinciInit failed."); InsertModel(model_id, davinci_model); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(davinci_model == nullptr, ret = PARAM_INVALID; break, "Insert model failed"); GELOGI("Parse model %u success.", model_id); GE_IF_BOOL_EXEC(ret == SUCCESS, device_count++); return SUCCESS; } while (0); return ret; } /// /// @ingroup ge /// @brief ACL case, Load task list with queue. /// @param [out] model_id: model id for manager. /// @param [in] model_data: Model data load from offline model file. /// @param [in] input_que_ids: input queue ids from user, num equals Data Op. /// @param [in] output_que_ids: input queue ids from user, num equals NetOutput Op. /// @return: 0 for success / others for fail /// Status ModelManager::LoadModelWithQ(uint32_t &model_id, const ModelData &model_data, const std::vector<uint32_t> &input_queue_ids, const std::vector<uint32_t> &output_queue_ids) { GE_CHK_BOOL_RET_STATUS(model_data.key.empty() || access(model_data.key.c_str(), F_OK) == 0, PARAM_INVALID, "input key file path is not valid!"); ModelHelper model_helper; Status ret = model_helper.LoadModel(model_data); if (ret != SUCCESS) { GELOGE(ret, "load model failed."); return ret; } shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(model_data.priority, nullptr); if (davinci_model == nullptr) { GELOGE(FAILED, "create model failed."); return FAILED; } ret = davinci_model->Assign(model_helper.GetGeModel()); if (ret != SUCCESS) { GELOGE(ret, "assign model failed."); return ret; } GenModelId(&model_id); davinci_model->SetId(model_id); davinci_model->SetSessionId(model_id); ret = davinci_model->SetQueIds(input_queue_ids, output_queue_ids); if (ret != SUCCESS) { GELOGE(ret, "set model queue ids failed."); return ret; } ret = davinci_model->Init(); if (ret != SUCCESS) { GELOGE(ret, "init model failed."); return ret; } InsertModel(model_id, davinci_model); GELOGI("Parse model %u success.", model_id); return SUCCESS; } /// /// @ingroup domi_ome /// @brief ACL case, not start new thread, return result /// @param [in] model_id mode id /// @param [in] stream model stream /// @param [in] async_mode is asynchronize mode. /// @param [in] input_data input data /// @param [out] output_data output data /// Status ModelManager::ExecuteModel(uint32_t model_id, rtStream_t stream, bool async_mode, const InputData &input_data, OutputData &output_data) { std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id); GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid Model ID %u to start! ", model_id); Status status = davinci_model->NnExecute(stream, async_mode, input_data, output_data); if (status == SUCCESS) { GELOGI("Execute model %u success.", model_id); } return status; } Status ModelManager::CreateAicpuSession(uint64_t session_id) { std::lock_guard<std::mutex> lock(sess_ids_mutex_); auto it = sess_ids_.find(session_id); // never been created by any model if (it == sess_ids_.end()) { Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_CREATE, session_id, 0); if (ret == SUCCESS) { (void)sess_ids_.insert(session_id); GELOGI("The session: %lu create success.", session_id); } return ret; } return SUCCESS; } /// /// @ingroup ge /// @brief get model memory size and weight /// @param [in] const ModelData model: model type /// @param [out] size_t memSize: model memory usage /// size_t weightSize: model weight and memory size /// @return SUCCESS success / others failure /// Status ModelManager::GetModelMemAndWeightSize(const ModelData &model, size_t &mem_size, size_t &weight_size) { uint8_t *model_data = nullptr; uint32_t model_len = 0; Status ret = DavinciModelParser::ParseModelContent(model, model_data, model_len); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "parse model content failed!"); OmFileLoadHelper om_file_helper; ret = om_file_helper.Init(model_data, model_len); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "om file helperInit failed!"); ModelPartition task_partition; if (om_file_helper.GetModelPartition(ModelPartitionType::TASK_INFO, task_partition) != SUCCESS) { GELOGE(FAILED, "get task model partition failed."); return FAILED; } std::shared_ptr<domi::ModelTaskDef> model_task_def = MakeShared<domi::ModelTaskDef>(); if (model_task_def == nullptr) { return FAILED; } if (task_partition.size != 0) { if (!ReadProtoFromArray(task_partition.data, static_cast<int>(task_partition.size), model_task_def.get())) { GELOGE(FAILED, "ReadProtoFromArray failed."); return FAILED; } } ModelPartition partition_weight; ret = om_file_helper.GetModelPartition(ModelPartitionType::WEIGHTS_DATA, partition_weight); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Get weight partition failed. ret = %u", ret); mem_size = model_task_def->memory_size(); weight_size = partition_weight.size; return SUCCESS; } void ModelManager::GenModelId(uint32_t *id) { if (id == nullptr) { return; } std::lock_guard<std::mutex> lock(map_mutex_); if (free_model_id_.empty()) { *id = ++max_model_id_; } else { *id = free_model_id_.back(); free_model_id_.pop_back(); } } } // namespace ge
36.278589
120
0.698769
zengchen1024
7082b8386c7ec4affdb37df45a1e91cac019e7c8
4,422
cpp
C++
lib/mayaUsd/fileio/shaderReaderRegistry.cpp
ika-rporter/maya-usd
8f216a4fb955fc44c0abda55caa53ed295aaa625
[ "Apache-2.0" ]
3
2020-03-18T10:11:32.000Z
2020-05-27T08:52:26.000Z
lib/mayaUsd/fileio/shaderReaderRegistry.cpp
ika-rporter/maya-usd
8f216a4fb955fc44c0abda55caa53ed295aaa625
[ "Apache-2.0" ]
4
2020-05-04T19:21:26.000Z
2020-05-08T15:30:38.000Z
lib/mayaUsd/fileio/shaderReaderRegistry.cpp
ika-rporter/maya-usd
8f216a4fb955fc44c0abda55caa53ed295aaa625
[ "Apache-2.0" ]
2
2020-03-18T10:11:46.000Z
2021-02-20T06:45:47.000Z
// // Copyright 2020 Autodesk // // 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 "shaderReaderRegistry.h" #include <mayaUsd/base/debugCodes.h> #include <mayaUsd/fileio/functorPrimReader.h> #include <mayaUsd/fileio/registryHelper.h> #include <pxr/base/plug/registry.h> #include <pxr/base/tf/debug.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/registryManager.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/stl.h> #include <pxr/base/tf/token.h> #include <pxr/pxr.h> #include <string> #include <unordered_map> #include <utility> PXR_NAMESPACE_OPEN_SCOPE // clang-format off TF_DEFINE_PRIVATE_TOKENS( _tokens, (UsdMaya) (ShaderReader) ); // clang-format on namespace { struct _RegistryEntry { UsdMayaShaderReaderRegistry::ContextPredicateFn _pred; UsdMayaShaderReaderRegistry::ReaderFactoryFn _fn; int _index; }; typedef std::unordered_multimap<TfToken, _RegistryEntry, TfToken::HashFunctor> _Registry; static _Registry _reg; static int _indexCounter = 0; _Registry::const_iterator _Find(const TfToken& usdInfoId, const UsdMayaJobImportArgs& importArgs) { using ContextSupport = UsdMayaShaderReader::ContextSupport; _Registry::const_iterator ret = _reg.cend(); _Registry::const_iterator first, last; std::tie(first, last) = _reg.equal_range(usdInfoId); while (first != last) { ContextSupport support = first->second._pred(importArgs); if (support == ContextSupport::Supported) { ret = first; break; } else if (support == ContextSupport::Fallback && ret == _reg.end()) { ret = first; } ++first; } return ret; } } // namespace /* static */ void UsdMayaShaderReaderRegistry::Register( TfToken usdInfoId, UsdMayaShaderReaderRegistry::ContextPredicateFn pred, UsdMayaShaderReaderRegistry::ReaderFactoryFn fn) { int index = _indexCounter++; TF_DEBUG(PXRUSDMAYA_REGISTRY) .Msg( "Registering UsdMayaShaderReader for info:id %s with index %d.\n", usdInfoId.GetText(), index); _reg.insert(std::make_pair(usdInfoId, _RegistryEntry { pred, fn, index })); // The unloader uses the index to know which entry to erase when there are // more than one for the same usdInfoId. UsdMaya_RegistryHelper::AddUnloader([usdInfoId, index]() { _Registry::const_iterator it, itEnd; std::tie(it, itEnd) = _reg.equal_range(usdInfoId); for (; it != itEnd; ++it) { if (it->second._index == index) { _reg.erase(it); break; } } }); } /* static */ UsdMayaShaderReaderRegistry::ReaderFactoryFn UsdMayaShaderReaderRegistry::Find(const TfToken& usdInfoId, const UsdMayaJobImportArgs& importArgs) { using ContextSupport = UsdMayaShaderReader::ContextSupport; TfRegistryManager::GetInstance().SubscribeTo<UsdMayaShaderReaderRegistry>(); _Registry::const_iterator it = _Find(usdInfoId, importArgs); if (it != _reg.end()) { return it->second._fn; } // Try adding more writers via plugin load: static const TfTokenVector SCOPE = { _tokens->UsdMaya, _tokens->ShaderReader }; UsdMaya_RegistryHelper::FindAndLoadMayaPlug(SCOPE, usdInfoId); it = _Find(usdInfoId, importArgs); if (it != _reg.end()) { return it->second._fn; } if (_reg.count(usdInfoId) == 0) { // Nothing registered at all, remember that: Register( usdInfoId, [](const UsdMayaJobImportArgs&) { return ContextSupport::Fallback; }, nullptr); } return nullptr; } PXR_NAMESPACE_CLOSE_SCOPE
30.708333
99
0.649028
ika-rporter
70838abdc5c4ce612be8b0b977f31e96456ecee1
848
cpp
C++
src/lunasa/common/Helpers.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
src/lunasa/common/Helpers.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
src/lunasa/common/Helpers.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #include <cstring> #include "faodel-common/StringHelpers.hh" #include "lunasa/common/Helpers.hh" #include "lunasa/DataObject.hh" using namespace std; namespace lunasa { const uint16_t string_object_type_id = faodel::const_hash16("StringObject"); DataObject AllocateStringObject(const std::string &s) { DataObject ldo(s.size()); ldo.SetTypeID(string_object_type_id); memcpy(ldo.GetDataPtr(), s.c_str(), s.size()); return ldo; } std::string UnpackStringObject(DataObject &ldo) { if(ldo.GetTypeID()!=string_object_type_id) return ""; return std::string(ldo.GetDataPtr<char *>(), ldo.GetDataSize()); } } // namespace lunasa
26.5
76
0.746462
faodel
70866c13ebb688f6ab92e9650f6c7a0e97686894
828
hpp
C++
include/RED4ext/Types/generated/world/PerformanceAreaNode.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/world/PerformanceAreaNode.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/world/PerformanceAreaNode.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/DynArray.hpp> #include <RED4ext/Types/generated/world/QualitySetting.hpp> #include <RED4ext/Types/generated/world/TriggerAreaNode.hpp> namespace RED4ext { namespace world { struct PerformanceAreaNode : world::TriggerAreaNode { static constexpr const char* NAME = "worldPerformanceAreaNode"; static constexpr const char* ALIAS = NAME; DynArray<world::QualitySetting> qualitySettingsArray; // 70 CName disableCrowdUniqueName; // 80 float globalStreamingDistanceScale; // 88 uint8_t unk8C[0x90 - 0x8C]; // 8C }; RED4EXT_ASSERT_SIZE(PerformanceAreaNode, 0x90); } // namespace world } // namespace RED4ext
28.551724
67
0.762077
Cyberpunk-Extended-Development-Team
708697aab604ed9ffb7c92cef97e49f9243a2cf0
19,121
cpp
C++
old/tests/VolumetricForward.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
5
2018-08-16T00:55:33.000Z
2020-06-19T14:30:17.000Z
old/tests/VolumetricForward.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
old/tests/VolumetricForward.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
#include "scene/BaseScene.hpp" #include "common/CreateInfoBase.hpp" #include "core/Instance.hpp" #include "core/LogicalDevice.hpp" #include "resource/DescriptorPool.hpp" #include "resource/Buffer.hpp" #include "util/UtilitySphere.hpp" #include "math/Ray.hpp" #include "util/AABB.hpp" #include "lights/Light.hpp" #include "render/Swapchain.hpp" #include "command/CommandPool.hpp" #include "command/TransferPool.hpp" #include "geometries/vertex_t.hpp" #include "render/GraphicsPipeline.hpp" #include "render/Renderpass.hpp" #include "render/Framebuffer.hpp" #include "resource/ShaderModule.hpp" #include "resource/PipelineCache.hpp" #include "resource/PipelineLayout.hpp" #include "resource/DescriptorSetLayout.hpp" #include "resource/DescriptorSet.hpp" #include "scene/Window.hpp" #include "resources/Multisampling.hpp" #include "render/DepthStencil.hpp" #include "glm/gtc/matrix_transform.hpp" #include "resources/LightBuffers.hpp" #include "render/FrameData.hpp" #include "render/BackBuffer.hpp" #include "camera/Camera.hpp" #include "core/ShaderGroup.hpp" #include "core/ShaderPack.hpp" #include "core/ShaderResource.hpp" #include <memory> #include <set> #include <map> #include <random> #include <deque> #include <array> #include <experimental/filesystem> #include "util/easylogging++.h" INITIALIZE_EASYLOGGINGPP namespace volumetric_forward { constexpr uint32_t LightGridBlockSize = 32; constexpr uint32_t ClusterGridBlockSize = 64; struct alignas(4) light_counts_t { uint32_t NumPointLights{ 0 }; uint32_t NumSpotLights{ 0 }; uint32_t NumDirectionalLights{ 0 }; uint32_t GetMaxLights() const noexcept { return std::max(NumPointLights, std::max(NumSpotLights, NumDirectionalLights)); } } LightCounts; struct alignas(4) dispatch_params_t { glm::uvec3 NumThreadGroups{ 0, 0, 0 }; const uint32_t Padding0{ 0 }; glm::uvec3 NumThreads{ 0, 0, 0 }; const uint32_t Padding1{ 0 }; } DispatchParams; struct alignas(16) frustum_t { std::array<glm::vec4, 4> Planes; } Frustum; struct alignas(4) cluster_data_t { glm::uvec3 GridDim{ 0, 0, 0 }; float ViewNear{ 0.0f }; glm::uvec2 Size{ 0, 0 }; float NearK{ 0.0f }; float LogGridDimY{ 0.0f }; }; struct alignas(4) SortParams { uint32_t NumElements{ 0 }; uint32_t ChunkSize{ 0 }; }; struct alignas(4) BVHParams { uint32_t PointLightLevels{ 0 }; uint32_t SpotLightLevels{ 0 }; uint32_t ChildLevel{ 0 }; }; struct render_target_t { render_target_t() = default; ~render_target_t() = default; void CreateRT(const vpr::Device* dvc, const vpr::Swapchain* swap, const VkRenderPass& pass, const VkImageUsageFlagBits usage, const VkFormat fmt); std::unique_ptr<vpr::Image> Image{ nullptr }; std::unique_ptr<vpr::Framebuffer> Framebuffer{ nullptr }; } DepthOnlyRenderTarget; struct compute_pipeline_t { compute_pipeline_t() = default; ~compute_pipeline_t() = default; void BindSets(const VkCommandBuffer& cmd); VkPipeline Handle{ VK_NULL_HANDLE }; VkComputePipelineCreateInfo Info{ vpr::vk_compute_pipeline_create_info_base }; std::unique_ptr<vpr::PipelineLayout> PipelineLayout{ nullptr }; std::unique_ptr<vpr::DescriptorSetLayout> SetLayout{ nullptr }; std::unique_ptr<vpr::PipelineCache> Cache{ nullptr }; std::unordered_map<std::string, vpr::Buffer*> UsedBuffers; std::unordered_map<std::string, vpr::DescriptorSet*> Sets; }; struct graphics_pipeline_t { graphics_pipeline_t() = default; ~graphics_pipeline_t() = default; }; struct compute_pipelines_t { std::unordered_map<std::string, compute_pipeline_t> Handles; compute_pipeline_t& at(const std::string& key) { return Handles.at(key); } } ComputePipelines; std::unordered_map<std::string, std::unique_ptr<vpr::DescriptorSet>> DescriptorSets; std::unordered_map<std::string, std::unique_ptr<vpr::Buffer>> UniformBuffers; std::unordered_map<std::string, std::unique_ptr<vpr::Buffer>> StorageTexelBuffers; std::unordered_map<std::string, std::unique_ptr<vpr::Buffer>> StorageBuffers; constexpr static uint32_t SORTING_NUM_THREADS_PER_THREAD_GROUP = 256; constexpr static uint32_t SORT_NUM_VALUES_PER_THREAD = 8; constexpr static std::array<uint32_t, 6> NumLevelNodes{ 1, 32, 1024, 32768, 1048576, 33554432 }; constexpr static std::array<uint32_t, 6> NumBVHNodes{ 1, 33, 1057, 33825, 1082401, 34636833 }; uint32_t GetNumLevels(const uint32_t num_leaves) { static const double log32f = std::log(32.0); if (num_leaves > 0) { return static_cast<uint32_t>(std::ceil(std::log(static_cast<double>(num_leaves)) / log32f)); } else { return 0; } } uint32_t GetNumNodes(const uint32_t num_leaves) { const uint32_t num_levels = GetNumLevels(num_leaves); if (num_levels > 0 && num_levels < NumBVHNodes.size()) { return NumBVHNodes[num_levels - 1]; } else { return 0; } } void MergeSort(const VkCommandBuffer& cmd, vpr::Buffer* src_keys, vpr::Buffer* src_values, vpr::Buffer* dst_keys, vpr::Buffer* dst_values, const uint32_t num_values, const uint32_t chunk_size) { auto& merge_path_partitions = StorageTexelBuffers.at("MergePathPartitions"); auto& merge_partitions_pipeline = ComputePipelines.at("MergePathPartitions"); auto& merge_sort_pipeline = ComputePipelines.at("MergeSort"); constexpr uint32_t numThreadsPerGroup = SORTING_NUM_THREADS_PER_THREAD_GROUP; constexpr uint32_t numValuesPerThread = SORT_NUM_VALUES_PER_THREAD; constexpr uint32_t numValuesPerThreadGroup = numThreadsPerGroup * numValuesPerThread; uint32_t num_chunks = static_cast<uint32_t>(std::ceil(static_cast<double>(num_values) / static_cast<double>(chunk_size))); uint32_t pass = 0; uint32_t chunk_size_local = chunk_size; while (num_chunks > 1) { const SortParams params{ num_values, chunk_size_local }; const uint32_t num_sort_groups = num_chunks / 2; uint32_t num_thread_groups_per_sort_group = static_cast<uint32_t>( std::ceil(static_cast<double>(chunk_size * 2) / static_cast<double>(numValuesPerThreadGroup)) ); { merge_path_partitions->Fill(cmd, merge_path_partitions->Size(), 0, 0); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, merge_partitions_pipeline.Handle); merge_partitions_pipeline.BindSets(cmd); uint32_t num_merge_path_partitions_per_sort_group = num_thread_groups_per_sort_group + 1u; uint32_t total_merge_path_partitions = num_merge_path_partitions_per_sort_group * num_sort_groups; uint32_t num_thread_groups = static_cast<uint32_t>(std::ceil(static_cast<double>(total_merge_path_partitions) / static_cast<double>(numThreadsPerGroup))); vkCmdDispatch(cmd, num_thread_groups, 1, 1); const VkBufferMemoryBarrier barrier{ VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, merge_path_partitions->vkHandle(), 0, merge_path_partitions->Size() }; vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 1, &barrier, 0, nullptr); } { vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, merge_sort_pipeline.Handle); uint32_t numValuesPerSortGroup = std::min(chunk_size_local * 2, num_values); num_thread_groups_per_sort_group = static_cast<uint32_t>(std::ceil(static_cast<double>(numValuesPerSortGroup) / static_cast<double>(numValuesPerThreadGroup))); vkCmdDispatch(cmd, num_thread_groups_per_sort_group * num_sort_groups, 1, 1); } chunk_size_local *= 2; num_chunks = static_cast<uint32_t>(std::ceil(static_cast<double>(num_values) / static_cast<double>(chunk_size_local))); } // TODO: How to easily swap bindings so that src becomes dst and dst becomes src? } void UpdateLights(const VkCommandBuffer& cmd) { auto& update_pipeline = ComputePipelines.at("UpdateLights"); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, update_pipeline.Handle); update_pipeline.BindSets(cmd); uint32_t num_groups_x = std::max(LightCounts.NumPointLights, std::max(LightCounts.NumDirectionalLights, LightCounts.NumSpotLights)); num_groups_x = static_cast<uint32_t>(std::ceil(static_cast<double>(num_groups_x) / 1024.0)); vkCmdDispatch(cmd, num_groups_x, 1, 1); } void ReduceLights(const VkCommandBuffer& cmd) { // Descriptor sets from previous binding call are all we should still need. auto& reduce_pipeline = ComputePipelines.at("ReduceLights0"); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, reduce_pipeline.Handle); const uint32_t num_thread_groups = static_cast<uint32_t>(std::min(static_cast<int>(std::ceil(static_cast<double>(LightCounts.GetMaxLights()) / 512.0)), 512)); dispatch_params_t params0; params0.NumThreadGroups = glm::uvec3{ num_thread_groups, 1, 1 }; params0.NumThreads = glm::uvec3{ 512 * num_thread_groups, 1, 1 }; UniformBuffers.at("DispatchParams")->Update(cmd, sizeof(dispatch_params_t), 0, &params0); vkCmdDispatch(cmd, num_thread_groups, 1, 1); dispatch_params_t params1; params1.NumThreadGroups = glm::uvec3(1, 1, 1); params1.NumThreads = glm::uvec3(512, 1, 1); UniformBuffers.at("DispatchParams")->Update(cmd, sizeof(dispatch_params_t), 0, &params1); vkCmdDispatch(cmd, 1, 1, 1); } void ComputeMortonCodes(const VkCommandBuffer& cmd) { auto& morton_pipeline = ComputePipelines.at("ComputeMortonCodes"); // Only need to bind this single extra set morton_pipeline.BindSets(cmd); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, morton_pipeline.Handle); const uint32_t num_thread_groups = static_cast<uint32_t>(std::ceil(static_cast<double>(LightCounts.GetMaxLights()) / 1024.0)); vkCmdDispatch(cmd, num_thread_groups, 1, 1); } void SortByMortonCodes(const VkCommandBuffer& cmd) { auto& radix_pipeline = ComputePipelines.at("RadixSort"); } void BuildLightBVH(const VkCommandBuffer& cmd) { } void ExecutePrecomputeShaders(const VkCommandBuffer& cmd) { UpdateLights(cmd); ReduceLights(cmd); ComputeMortonCodes(cmd); SortByMortonCodes(cmd); BuildLightBVH(cmd); } void ComputeGridFrustums(const VkCommandBuffer& cmd, const uint32_t _screen_width, const uint32_t _screen_height) { const uint32_t screen_width = std::max(_screen_width, 1u); const uint32_t screen_height = std::max(_screen_height, 1u); const glm::uvec3 num_threads = glm::uvec3( static_cast<uint32_t>(std::ceil(static_cast<double>(screen_width) / 1024.0)), static_cast<uint32_t>(std::ceil(static_cast<double>(screen_height) / 1024.0)), 1u ); const glm::uvec3 num_thread_groups = glm::uvec3( static_cast<uint32_t>(std::ceil(static_cast<double>(num_threads.x) / static_cast<double>(LightGridBlockSize))), static_cast<uint32_t>(std::ceil(static_cast<double>(num_threads.y) / static_cast<double>(LightGridBlockSize))), 1u ); } void UpdateClusterGrid(const VkCommandBuffer& cmd, const vpsk::Camera& cam, const uint32_t screen_width, const uint32_t screen_height) { const uint32_t cluster_dim_x = static_cast<uint32_t>(std::ceil(static_cast<double>(screen_width) / static_cast<double>(ClusterGridBlockSize))); const uint32_t cluster_dim_y = static_cast<uint32_t>(std::ceil(static_cast<double>(screen_height) / static_cast<double>(ClusterGridBlockSize))); const float s_d = 2.0f * std::tan(cam.GetFOV() * 0.50f) / static_cast<float>(cluster_dim_y); const float log_dim_y = 1.0f / glm::log(1.0f + s_d); const float log_depth = glm::log(cam.GetNearPlane() / cam.GetFarPlane()); const uint32_t cluster_dim_z = static_cast<uint32_t>(glm::floor(log_depth * log_dim_y)); cluster_data_t cluster_data{ glm::uvec3{ cluster_dim_x, cluster_dim_y, cluster_dim_z }, cam.GetNearPlane(), glm::uvec2{ ClusterGridBlockSize, ClusterGridBlockSize }, 1.0f + s_d, log_dim_y }; const uint32_t num_clusters = cluster_dim_x * cluster_dim_y * cluster_dim_z; StorageTexelBuffers.at("ClusterFlags")->CreateBuffer(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, sizeof(uint8_t) * num_clusters); StorageTexelBuffers.at("ClusterFlags")->CreateView(VK_FORMAT_R8_UINT, StorageTexelBuffers.at("ClusterFlags")->Size(), 0); StorageTexelBuffers.at("UniqueClusters")->CreateBuffer(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, sizeof(uint32_t) * num_clusters); StorageTexelBuffers.at("UniqueClusters")->CreateView(VK_FORMAT_R32_UINT, StorageTexelBuffers.at("UniqueClusters")->Size(), 0); StorageTexelBuffers.at("PreviousUniqueClusters")->CreateBuffer(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, sizeof(uint32_t) * num_clusters); StorageTexelBuffers.at("PreviousUniqueClusters")->CreateView(VK_FORMAT_R32_UINT, StorageTexelBuffers.at("PreviousUniqueClusters")->Size(), 0); // TODO: Generate lights, update clusters now. Need some kind of byte address buffer? } void ClusteredPrePass(const VkCommandBuffer& cmd) { } void compute_pipeline_t::BindSets(const VkCommandBuffer & cmd) { std::vector<VkDescriptorSet> handles; for (auto& set : this->Sets) { handles.emplace_back(set.second->vkHandle()); } vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, PipelineLayout->vkHandle(), 0, static_cast<uint32_t>(handles.size()), handles.data(), 0, nullptr); } } static int screen_x() { return 1440; } static int screen_y() { return 720; } static vpsk::Camera camera; static double fov() { return camera.GetFOV(); } static double near_plane() { return camera.GetNearPlane(); } static double far_plane() { return camera.GetFarPlane(); } constexpr VkApplicationInfo app_info{ VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, "VolumetricForward", VK_MAKE_VERSION(0,1,0), "VulpesSceneKit", VK_MAKE_VERSION(0,1,0), VK_API_VERSION_1_1 }; int main(int argc, char* argv[]) { using namespace volumetric_forward; using namespace st; using namespace vpsk; using namespace vpr; ImGui::CreateContext(); auto window = std::make_unique<vpsk::Window>(1280, 720, "RendergraphSketch"); auto instance = std::make_unique<vpr::Instance>(false, &app_info, window->glfwWindow()); auto device = std::make_unique<vpr::Device>(instance.get(), instance->GetPhysicalDevice(), true); auto& callbacks = ShaderPack::RetrievalCallbacks(); callbacks.GetScreenSizeX = &screen_x; callbacks.GetScreenSizeY = &screen_y; callbacks.GetFOVY = &fov; callbacks.GetZNear = &near_plane; callbacks.GetZFar = &far_plane; ShaderPack pack("../third_party/shadertools/fragments/volumetric_forward/ShaderPack.lua"); std::vector<std::string> group_names; { auto names = pack.GetShaderGroupNames(); for (size_t i = 0; i < names.NumStrings; ++i) { group_names.emplace_back(names.Strings[i]); } } std::vector<std::string> resource_block_names; { auto retrieved_names = pack.GetResourceGroupNames(); for (size_t i = 0; i < retrieved_names.NumStrings; ++i) { resource_block_names.emplace_back(retrieved_names.Strings[i]); } } std::unordered_map<std::string, std::vector<const ShaderResource*>> resources; { for (const auto& block_name : resource_block_names) { size_t num_resources = 0; pack.GetResourceGroupPointers(block_name.c_str(), &num_resources, nullptr); std::vector<const ShaderResource*> vec(num_resources); pack.GetResourceGroupPointers(block_name.c_str(), &num_resources, vec.data()); resources.emplace(block_name, vec); } } std::unique_ptr<DescriptorPool> pool = std::make_unique<DescriptorPool>(device.get(), resources.size()); const auto& rsrc_counts = pack.GetTotalDescriptorTypeCounts(); pool->AddResourceType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, rsrc_counts.UniformBuffers); pool->AddResourceType(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, rsrc_counts.StorageTexelBuffers); pool->AddResourceType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, rsrc_counts.StorageBuffers); pool->AddResourceType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, rsrc_counts.CombinedImageSamplers); pool->Create(); for (const auto& block_name : resource_block_names) { for (const auto& resource : resources.at(block_name)) { const std::string rsrc_name = resource->GetName(); if (resource->GetType() == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) { UniformBuffers.emplace(rsrc_name, std::make_unique<Buffer>(device.get())); UniformBuffers.at(rsrc_name)->CreateBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VkDeviceSize(resource->GetAmountOfMemoryRequired())); } else if (resource->GetType() == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER) { StorageTexelBuffers.emplace(rsrc_name, std::make_unique<Buffer>(device.get())); StorageTexelBuffers.at(rsrc_name)->CreateBuffer(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VkDeviceSize(resource->GetAmountOfMemoryRequired())); StorageTexelBuffers.at(rsrc_name)->CreateView(resource->GetFormat(), resource->GetAmountOfMemoryRequired(), 0); } else if (resource->GetType() == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) { StorageBuffers.emplace(rsrc_name, std::make_unique<Buffer>(device.get())); StorageBuffers.at(rsrc_name)->CreateBuffer(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VkDeviceSize(resource->GetAmountOfMemoryRequired())); } } } return 0; }
44.571096
231
0.698028
fuchstraumer
708763dedd32925d0eb66905515208c01e525187
1,476
cc
C++
servlib/session/Subscriber.cc
delay-tolerant-networking/DTN2
1c12a9dea32c5cbae8c46db105012a2031f4161e
[ "Apache-2.0" ]
14
2016-06-27T19:28:23.000Z
2021-06-28T20:41:17.000Z
servlib/session/Subscriber.cc
delay-tolerant-networking/DTN2
1c12a9dea32c5cbae8c46db105012a2031f4161e
[ "Apache-2.0" ]
3
2020-09-18T13:48:53.000Z
2021-05-27T18:28:14.000Z
servlib/session/Subscriber.cc
lauramazzuca21/DTNME
c97b598b09a8c8e97c2e4136879d9f0e157c8df7
[ "Apache-2.0" ]
10
2020-09-26T05:08:40.000Z
2022-01-25T12:57:55.000Z
/* * Copyright 2007 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include <dtn-config.h> #endif #include "Subscriber.h" #include "reg/Registration.h" namespace dtn { //---------------------------------------------------------------------- Subscriber::~Subscriber() { } //---------------------------------------------------------------------- int Subscriber::format(char* buf, size_t len) const { if (is_null()) { return snprintf(buf, len, "(null_subscriber)"); } else if (is_local()) { return snprintf(buf, len, "regid:%d", reg_->regid()); } else { return snprintf(buf, len, "peer:%s", nexthop_.c_str()); } } //---------------------------------------------------------------------- bool Subscriber::operator==(const Subscriber& other) const { return (reg_ == other.reg_) && (nexthop_ == other.nexthop_); } } // namespace dtn
27.333333
78
0.563686
delay-tolerant-networking
70878d89ba52921210a7416987be2c93fdfd206a
1,520
hpp
C++
native-library/src/util_classes/etag.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
4
2021-03-03T11:27:57.000Z
2022-03-29T03:42:47.000Z
native-library/src/util_classes/etag.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
null
null
null
native-library/src/util_classes/etag.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
3
2020-11-04T13:13:24.000Z
2021-12-06T08:03:48.000Z
/* * Copyright 2020-2021 AVSystem <avsystem@avsystem.com> * * 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. */ #pragma once #include <vector> #include "../jni_wrapper.hpp" #include <anjay/download.h> namespace utils { struct Etag { anjay_etag_t *data; Etag(JNIEnv &env, const std::vector<jni::jbyte> &etag) { uint8_t size = static_cast<uint8_t>(etag.size()); if (size != etag.size()) { avs_throw(IllegalArgumentException(env, "etag too long")); } data = anjay_etag_new(size); if (!data) { // Out of memory is a pretty serious condition, // let this degenerate to java.lang.Error avs_throw(std::runtime_error("out of memory")); } memcpy(data->value, etag.data(), size); } ~Etag() { avs_free(data); } Etag(const Etag &) = delete; Etag &operator=(const Etag &) = delete; Etag(Etag &&) = delete; Etag &operator=(Etag &&) = delete; }; } // namespace utils
27.142857
75
0.640132
AVSystem
708cbcc4887a3b74d79504dd44d85f69dcb8cf4a
10,647
hpp
C++
include/ShaderProgram.hpp
pinam45/UTBM_IN55_ParametricObjectsConstruction
0bb92ccdf1e52b1715162d7934aaca736ffbc0e6
[ "MIT" ]
null
null
null
include/ShaderProgram.hpp
pinam45/UTBM_IN55_ParametricObjectsConstruction
0bb92ccdf1e52b1715162d7934aaca736ffbc0e6
[ "MIT" ]
null
null
null
include/ShaderProgram.hpp
pinam45/UTBM_IN55_ParametricObjectsConstruction
0bb92ccdf1e52b1715162d7934aaca736ffbc0e6
[ "MIT" ]
null
null
null
/***************************************************************************************** * * * MIT License * * * * Copyright (c) 2017 Julien Barbier & Jérôme Boulmier & Maxime Pinard * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in all * * copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * * SOFTWARE. * * * *****************************************************************************************/ #ifndef PARAMETRICOBJECTSCONSTRUCTION_SHADERPROGRAM_HPP #define PARAMETRICOBJECTSCONSTRUCTION_SHADERPROGRAM_HPP #include <GL/glew.h> #include "Shader.hpp" namespace poc { template <typename> struct dependent_false : public std::false_type { }; class ShaderProgram { public: ShaderProgram() noexcept; template <typename... Shaders> explicit ShaderProgram(Shaders&& ... shaders); ShaderProgram(const ShaderProgram&) = delete; ShaderProgram(ShaderProgram&&) noexcept; virtual ~ShaderProgram(); template <typename... Shaders> void setShaders(Shaders&& ... shaders); // Program need to be in use to set uniforms template <typename T> bool setUniform1(const char* name, T v0) const; template <typename T> bool setUniform2(const char* name, T v0, T v1) const; template <typename T> bool setUniform3(const char* name, T v0, T v1, T v2) const; template <typename T> bool setUniform4(const char* name, T v0, T v1, T v2, T v3) const; template <typename T> bool setUniform1v(const char* name, int count, const T* value) const; template <typename T> bool setUniform2v(const char* name, int count, const T* value) const; template <typename T> bool setUniform3v(const char* name, int count, const T* value) const; template <typename T> bool setUniform4v(const char* name, int count, const T* value) const; bool setUniformMatrix2v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix3v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix4v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix2x3v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix3x2v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix2x4v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix4x2v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix3x4v(const char* name, int count, bool transpose, const float* value) const; bool setUniformMatrix4x3v(const char* name, int count, bool transpose, const float* value) const; int getAttributeLocation(const char* name) const; void use() const; bool isValid() const; unsigned int getProgram() const; const std::string& getError() const; private: bool m_valid; unsigned int m_program; std::string m_error; }; } template<typename... Shaders> poc::ShaderProgram::ShaderProgram(Shaders&&... shaders) : m_valid(true) , m_program() , m_error() { setShaders(std::forward<Shaders>(shaders)...); } template <typename... Shaders> void poc::ShaderProgram::setShaders(Shaders&& ... shaders) { static_assert((std::is_same_v<std::decay_t<Shaders>, Shader> && ...)); if (m_program != 0) { glDeleteProgram(m_program); } m_program = glCreateProgram(); if (m_program == 0) { m_valid = false; m_error = "Shader program creation failed:\n"; char infoLog[512]; glGetShaderInfoLog(m_program, 512, nullptr, infoLog); m_error += infoLog; } (glAttachShader(m_program, shaders.getShader()), ...); glLinkProgram(m_program); int success; glGetProgramiv(m_program, GL_LINK_STATUS, &success); if (!success) { char infoLog[512]; glGetShaderInfoLog(m_program, 512, nullptr, infoLog); m_valid = false; m_error = "Shader program link failed:\n"; m_error += infoLog; } } template<typename T> bool poc::ShaderProgram::setUniform1(const char* name, T v0) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform1f(uniformLocation, v0); } else if constexpr(std::is_same<T, int>::value){ glUniform1i(uniformLocation, v0); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform1ui(uniformLocation, v0); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } template<typename T> bool poc::ShaderProgram::setUniform2(const char* name, T v0, T v1) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform2f(uniformLocation, v0, v1); } else if constexpr(std::is_same<T, int>::value){ glUniform2i(uniformLocation, v0, v1); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform2ui(uniformLocation, v0, v1); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } template<typename T> bool poc::ShaderProgram::setUniform3(const char* name, T v0, T v1, T v2) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform3f(uniformLocation, v0, v1, v2); } else if constexpr(std::is_same<T, int>::value){ glUniform3i(uniformLocation, v0, v1, v2); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform3ui(uniformLocation, v0, v1, v2); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } template<typename T> bool poc::ShaderProgram::setUniform4(const char* name, T v0, T v1, T v2, T v3) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform4f(uniformLocation, v0, v1, v2, v3); } else if constexpr(std::is_same<T, int>::value){ glUniform4i(uniformLocation, v0, v1, v2, v3); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform4ui(uniformLocation, v0, v1, v2, v3); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } template<typename T> bool poc::ShaderProgram::setUniform1v(const char* name, int count, const T* value) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform1fv(uniformLocation, count, value); } else if constexpr(std::is_same<T, int>::value){ glUniform1iv(uniformLocation, count, value); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform1uiv(uniformLocation, count, value); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } template<typename T> bool poc::ShaderProgram::setUniform2v(const char* name, int count, const T* value) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform2fv(uniformLocation, count, value); } else if constexpr(std::is_same<T, int>::value){ glUniform2iv(uniformLocation, count, value); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform2uiv(uniformLocation, count, value); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } template<typename T> bool poc::ShaderProgram::setUniform3v(const char* name, int count, const T* value) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform3fv(uniformLocation, count, value); } else if constexpr(std::is_same<T, int>::value){ glUniform3iv(uniformLocation, count, value); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform3uiv(uniformLocation, count, value); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } template<typename T> bool poc::ShaderProgram::setUniform4v(const char* name, int count, const T* value) const { int uniformLocation = glGetUniformLocation(m_program, name); if(uniformLocation == -1) return false; if constexpr(std::is_same<T, float>::value){ glUniform4fv(uniformLocation, count, value); } else if constexpr(std::is_same<T, int>::value){ glUniform4iv(uniformLocation, count, value); } else if constexpr(std::is_same<T, unsigned int>::value){ glUniform4uiv(uniformLocation, count, value); } else{ static_assert(dependent_false<T>::value, "Unsupported type"); } return true; } #endif //PARAMETRICOBJECTSCONSTRUCTION_SHADERPROGRAM_HPP
32.361702
99
0.652484
pinam45
708f308bbb612f0540fa9c4e9ce0cec004651647
5,430
cpp
C++
chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/html/forms/DateInputType.h" #include "core/HTMLNames.h" #include "core/InputTypeNames.h" #include "core/dom/Document.h" #include "core/html/HTMLInputElement.h" #include "core/html/forms/DateTimeFieldsState.h" #include "core/inspector/ConsoleMessage.h" #include "platform/DateComponents.h" #include "platform/JSONValues.h" #include "platform/text/PlatformLocale.h" #include "wtf/PassOwnPtr.h" namespace blink { using blink::WebLocalizedString; using namespace HTMLNames; static const int dateDefaultStep = 1; static const int dateDefaultStepBase = 0; static const int dateStepScaleFactor = 86400000; inline DateInputType::DateInputType(HTMLInputElement& element) : BaseDateInputType(element) { } PassRefPtrWillBeRawPtr<InputType> DateInputType::create(HTMLInputElement& element) { return adoptRefWillBeNoop(new DateInputType(element)); } void DateInputType::countUsage() { countUsageIfVisible(UseCounter::InputTypeDate); } const AtomicString& DateInputType::formControlType() const { return InputTypeNames::date; } StepRange DateInputType::createStepRange(AnyStepHandling anyStepHandling) const { DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (dateDefaultStep, dateDefaultStepBase, dateStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger)); return InputType::createStepRange(anyStepHandling, dateDefaultStepBase, Decimal::fromDouble(DateComponents::minimumDate()), Decimal::fromDouble(DateComponents::maximumDate()), stepDescription); } bool DateInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const { ASSERT(out); unsigned end; return out->parseDate(string, 0, end) && end == string.length(); } bool DateInputType::setMillisecondToDateComponents(double value, DateComponents* date) const { ASSERT(date); return date->setMillisecondsSinceEpochForDate(value); } void DateInputType::warnIfValueIsInvalid(const String& value) const { if (value != element().sanitizeValue(value)) { element().document().addConsoleMessage(ConsoleMessage::create(RenderingMessageSource, WarningMessageLevel, String::format("The specified value %s does not conform to the required format, \"yyyy-MM-dd\".", JSONValue::quoteString(value).utf8().data()))); } } #if ENABLE(INPUT_MULTIPLE_FIELDS_UI) String DateInputType::formatDateTimeFieldsState(const DateTimeFieldsState& dateTimeFieldsState) const { if (!dateTimeFieldsState.hasDayOfMonth() || !dateTimeFieldsState.hasMonth() || !dateTimeFieldsState.hasYear()) return emptyString(); return String::format("%04u-%02u-%02u", dateTimeFieldsState.year(), dateTimeFieldsState.month(), dateTimeFieldsState.dayOfMonth()); } void DateInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters& layoutParameters, const DateComponents& date) const { layoutParameters.dateTimeFormat = layoutParameters.locale.dateFormat(); layoutParameters.fallbackDateTimeFormat = "yyyy-MM-dd"; if (!parseToDateComponents(element().fastGetAttribute(minAttr), &layoutParameters.minimum)) layoutParameters.minimum = DateComponents(); if (!parseToDateComponents(element().fastGetAttribute(maxAttr), &layoutParameters.maximum)) layoutParameters.maximum = DateComponents(); layoutParameters.placeholderForDay = locale().queryString(WebLocalizedString::PlaceholderForDayOfMonthField); layoutParameters.placeholderForMonth = locale().queryString(WebLocalizedString::PlaceholderForMonthField); layoutParameters.placeholderForYear = locale().queryString(WebLocalizedString::PlaceholderForYearField); } bool DateInputType::isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const { return hasYear && hasMonth && hasDay; } #endif } // namespace blink
41.769231
197
0.779374
wedataintelligence
7091bab4412b92b9b5ed629c94438a0f23fe8443
32,054
cpp
C++
tests/SkSLTest.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
tests/SkSLTest.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
tests/SkSLTest.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkData.h" #include "include/core/SkImageInfo.h" #include "include/core/SkM44.h" #include "include/core/SkPaint.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkShader.h" #include "include/core/SkSpan.h" #include "include/core/SkString.h" #include "include/core/SkSurface.h" #include "include/core/SkTypes.h" #include "include/effects/SkRuntimeEffect.h" #include "include/gpu/GrDirectContext.h" #include "include/private/SkSLProgramElement.h" #include "include/private/SkSLProgramKind.h" #include "include/sksl/DSLCore.h" #include "src/core/SkRuntimeEffectPriv.h" #include "src/gpu/ganesh/GrCaps.h" #include "src/gpu/ganesh/GrDirectContextPriv.h" #include "src/gpu/ganesh/GrShaderCaps.h" #include "src/sksl/SkSLCompiler.h" #include "src/sksl/SkSLDehydrator.h" #include "src/sksl/SkSLRehydrator.h" #include "src/sksl/SkSLStringStream.h" #include "src/sksl/SkSLUtil.h" #include "src/sksl/ir/SkSLProgram.h" #include "tests/Test.h" #include "tests/TestHarness.h" #include "tools/Resources.h" #include "tools/gpu/GrContextFactory.h" #include <array> #include <memory> #include <string> #include <vector> static constexpr int kWidth = 2; static constexpr int kHeight = 2; namespace SkSLTestFlags { /** CPU tests must pass on the CPU backend. */ static constexpr int CPU = 1 << 0; /** CPU_ES3 tests must pass on the CPU backend when "enforce ES2 restrictions" is off. */ static constexpr int CPU_ES3 = 1 << 1; /** GPU tests must pass on all GPU backends. */ static constexpr int GPU = 1 << 2; /** GPU_ES3 tests must pass on ES3-compatible GPUs when "enforce ES2 restrictions" is off. */ static constexpr int GPU_ES3 = 1 << 3; /** SkQP tests will be run in Android/Fuchsia conformance tests with no driver workarounds. */ static constexpr int SkQP = 1 << 4; } static constexpr bool is_cpu(int flags) { return flags & (SkSLTestFlags::CPU | SkSLTestFlags::CPU_ES3); } static constexpr bool is_gpu(int flags) { return flags & (SkSLTestFlags::GPU | SkSLTestFlags::GPU_ES3); } static constexpr bool is_strict_es2(int flags) { return !(flags & (SkSLTestFlags::CPU_ES3 | SkSLTestFlags::GPU_ES3)); } static bool should_run_in_skqp(int flags) { if (CurrentTestHarnessIsSkQP()) { // Official SkQP builds should only run tests marked with the SkQP flag. return flags & (SkSLTestFlags::SkQP); } else { // Other test binaries (dm/fm) should run every test, regardless of the SkQP flag. return true; } } template <typename T> static void set_uniform(SkRuntimeShaderBuilder* builder, const char* name, const T& value) { SkRuntimeShaderBuilder::BuilderUniform uniform = builder->uniform(name); if (uniform.fVar) { uniform = value; } } template <typename T> static void set_uniform_array(SkRuntimeShaderBuilder* builder, const char* name, SkSpan<T> values) { SkRuntimeShaderBuilder::BuilderUniform uniform = builder->uniform(name); if (uniform.fVar) { uniform.set(values.data(), values.size()); } } static SkString load_source(skiatest::Reporter* r, const char* testFile, const char* permutationSuffix) { SkString resourcePath = SkStringPrintf("sksl/%s", testFile); sk_sp<SkData> shaderData = GetResourceAsData(resourcePath.c_str()); if (!shaderData) { ERRORF(r, "%s%s: Unable to load file", testFile, permutationSuffix); return SkString(""); } return SkString{reinterpret_cast<const char*>(shaderData->bytes()), shaderData->size()}; } static void test_one_permutation(skiatest::Reporter* r, SkSurface* surface, const char* testFile, const char* permutationSuffix, const SkRuntimeEffect::Options& options) { SkString shaderString = load_source(r, testFile, permutationSuffix); if (shaderString.isEmpty()) { return; } SkRuntimeEffect::Result result = SkRuntimeEffect::MakeForShader(shaderString, options); if (!result.effect) { ERRORF(r, "%s%s: %s", testFile, permutationSuffix, result.errorText.c_str()); return; } static constexpr float kArray[5] = {1, 2, 3, 4, 5}; SkRuntimeShaderBuilder builder(result.effect); set_uniform(&builder, "colorBlack", SkV4{0, 0, 0, 1}); set_uniform(&builder, "colorRed", SkV4{1, 0, 0, 1}); set_uniform(&builder, "colorGreen", SkV4{0, 1, 0, 1}); set_uniform(&builder, "colorBlue", SkV4{0, 0, 1, 1}); set_uniform(&builder, "colorWhite", SkV4{1, 1, 1, 1}); set_uniform(&builder, "testInputs", SkV4{-1.25, 0, 0.75, 2.25}); set_uniform(&builder, "unknownInput", 1.0f); set_uniform(&builder, "testMatrix2x2", std::array<float,4>{1, 2, 3, 4}); set_uniform(&builder, "testMatrix3x3", std::array<float,9>{1, 2, 3, 4, 5, 6, 7, 8, 9}); set_uniform(&builder, "testMatrix4x4", std::array<float,16>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); set_uniform_array(&builder, "testArray", SkMakeSpan(kArray)); sk_sp<SkShader> shader = builder.makeShader(); if (!shader) { ERRORF(r, "%s%s: Unable to build shader", testFile, permutationSuffix); return; } surface->getCanvas()->clear(SK_ColorBLACK); SkPaint paintShader; paintShader.setShader(shader); surface->getCanvas()->drawRect(SkRect::MakeWH(kWidth, kHeight), paintShader); SkBitmap bitmap; REPORTER_ASSERT(r, bitmap.tryAllocPixels(surface->imageInfo())); REPORTER_ASSERT(r, surface->readPixels(bitmap.info(), bitmap.getPixels(), bitmap.rowBytes(), /*srcX=*/0, /*srcY=*/0)); bool success = true; SkColor color[kHeight][kWidth]; for (int y = 0; y < kHeight; ++y) { for (int x = 0; x < kWidth; ++x) { color[y][x] = bitmap.getColor(x, y); if (color[y][x] != SkColorSetARGB(0xFF, 0x00, 0xFF, 0x00)) { success = false; } } } if (!success) { static_assert(kWidth == 2); static_assert(kHeight == 2); ERRORF(r, "Expected: solid green. Actual:\n" "RRGGBBAA RRGGBBAA\n" "%02X%02X%02X%02X %02X%02X%02X%02X\n" "%02X%02X%02X%02X %02X%02X%02X%02X", SkColorGetR(color[0][0]), SkColorGetG(color[0][0]), SkColorGetB(color[0][0]), SkColorGetA(color[0][0]), SkColorGetR(color[0][1]), SkColorGetG(color[0][1]), SkColorGetB(color[0][1]), SkColorGetA(color[0][1]), SkColorGetR(color[1][0]), SkColorGetG(color[1][0]), SkColorGetB(color[1][0]), SkColorGetA(color[1][0]), SkColorGetR(color[1][1]), SkColorGetG(color[1][1]), SkColorGetB(color[1][1]), SkColorGetA(color[1][1])); } } static void test_permutations(skiatest::Reporter* r, SkSurface* surface, const char* testFile, bool strictES2) { SkRuntimeEffect::Options options = strictES2 ? SkRuntimeEffect::Options{} : SkRuntimeEffectPriv::ES3Options(); options.forceNoInline = false; test_one_permutation(r, surface, testFile, "", options); options.forceNoInline = true; test_one_permutation(r, surface, testFile, " (NoInline)", options); } static void test_cpu(skiatest::Reporter* r, const char* testFile, int flags) { bool shouldRunCPU = (flags & SkSLTestFlags::CPU); bool shouldRunCPU_ES3 = (flags & SkSLTestFlags::CPU_ES3); SkASSERT(shouldRunCPU || shouldRunCPU_ES3); // Create a raster-backed surface. const SkImageInfo info = SkImageInfo::MakeN32Premul(kWidth, kHeight); sk_sp<SkSurface> surface(SkSurface::MakeRaster(info)); if (shouldRunCPU) { test_permutations(r, surface.get(), testFile, /*strictES2=*/true); } if (shouldRunCPU_ES3) { test_permutations(r, surface.get(), testFile, /*strictES2=*/false); } } static void test_gpu(skiatest::Reporter* r, GrDirectContext* ctx, const char* testFile, int flags) { // If this is an ES3-only test on a GPU which doesn't support SkSL ES3, return immediately. bool shouldRunGPU = (flags & SkSLTestFlags::GPU); bool shouldRunGPU_ES3 = (flags & SkSLTestFlags::GPU_ES3) && ctx->priv().caps()->shaderCaps()->supportsSkSLES3(); if (!shouldRunGPU && !shouldRunGPU_ES3) { return; } // Create a GPU-backed surface. const SkImageInfo info = SkImageInfo::MakeN32Premul(kWidth, kHeight); sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, info)); if (shouldRunGPU) { test_permutations(r, surface.get(), testFile, /*strictES2=*/true); } if (shouldRunGPU_ES3) { test_permutations(r, surface.get(), testFile, /*strictES2=*/false); } } static void test_clone(skiatest::Reporter* r, const char* testFile, int flags) { SkString shaderString = load_source(r, testFile, ""); if (shaderString.isEmpty()) { return; } std::unique_ptr<SkSL::ShaderCaps> caps = SkSL::ShaderCapsFactory::Standalone(); SkSL::Program::Settings settings; settings.fAllowVarDeclarationCloneForTesting = true; settings.fEnforceES2Restrictions = is_strict_es2(flags); SkSL::Compiler compiler(caps.get()); std::unique_ptr<SkSL::Program> program = compiler.convertProgram( SkSL::ProgramKind::kRuntimeShader, shaderString.c_str(), settings); if (!program) { ERRORF(r, "%s", compiler.errorText().c_str()); return; } // Starting DSL allows us to get access to the ThreadContext::Settings SkSL::dsl::Start(&compiler, SkSL::ProgramKind::kFragment, settings); for (const std::unique_ptr<SkSL::ProgramElement>& element : program->fOwnedElements) { std::string original = element->description(); std::string cloned = element->clone()->description(); REPORTER_ASSERT(r, original == cloned, "Mismatch after clone!\nOriginal: %s\nCloned: %s\n", original.c_str(), cloned.c_str()); } SkSL::dsl::End(); } static void test_rehydrate(skiatest::Reporter* r, const char* testFile, int flags) { SkString shaderString = load_source(r, testFile, ""); if (shaderString.isEmpty()) { return; } std::unique_ptr<SkSL::ShaderCaps> caps = SkSL::ShaderCapsFactory::Default(); SkSL::Compiler compiler(caps.get()); SkSL::Program::Settings settings; settings.fEnforceES2Restrictions = is_strict_es2(flags); // Inlining causes problems because it can create expressions like bool(1) that can't be // directly instantiated. After a dehydrate/recycle pass, that expression simply becomes "true" // due to optimization - which is fine, but would cause us to fail an equality comparison. We // disable inlining to avoid this issue. settings.fInlineThreshold = 0; std::unique_ptr<SkSL::Program> program = compiler.convertProgram( SkSL::ProgramKind::kRuntimeShader, shaderString.c_str(), settings); if (!program) { ERRORF(r, "%s", compiler.errorText().c_str()); return; } SkSL::Dehydrator dehydrator; dehydrator.write(*program); SkSL::StringStream stream; dehydrator.finish(stream); SkSL::Rehydrator rehydrator(compiler, (const uint8_t*) stream.str().data(), stream.str().length()); std::unique_ptr<SkSL::Program> rehydrated = rehydrator.program(); REPORTER_ASSERT(r, rehydrated->description() == program->description(), "Mismatch between original and dehydrated/rehydrated:\n-- Original:\n%s\n" "-- Rehydrated:\n%s", program->description().c_str(), rehydrated->description().c_str()); } #define SKSL_TEST(flags, name, path) \ DEF_CONDITIONAL_TEST(SkSL##name##_CPU, r, is_cpu(flags) && should_run_in_skqp(flags)) { \ test_cpu(r, path, flags); \ } \ DEF_CONDITIONAL_GPUTEST_FOR_RENDERING_CONTEXTS( \ SkSL##name##_GPU, r, ctxInfo, is_gpu(flags) && should_run_in_skqp(flags)) { \ test_gpu(r, ctxInfo.directContext(), path, flags); \ } \ DEF_TEST(SkSL##name##_Clone, r) { test_clone(r, path, flags); } \ DEF_TEST(SkSL##name##_Rehydrate, r) { test_rehydrate(r, path, flags); } /** * Test flags: * - CPU: this test should pass on the CPU backend * - CPU_ES3: this test should pass on the CPU backend when "enforce ES2 restrictions" is off * - GPU: this test should pass on the GPU backends * - GPU_ES3: this test should pass on an ES3-compatible GPU when "enforce ES2 restrictions" is off * - SkQP: Android CTS (go/wtf/cts) enforces that devices must pass this test */ // clang-format off using namespace SkSLTestFlags; SKSL_TEST(CPU + GPU + SkQP, ArraySizeFolding, "folding/ArraySizeFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, AssignmentOps, "folding/AssignmentOps.sksl") SKSL_TEST(CPU + GPU + SkQP, BoolFolding, "folding/BoolFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, CastFolding, "folding/CastFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, IntFoldingES2, "folding/IntFoldingES2.sksl") SKSL_TEST(GPU_ES3, IntFoldingES3, "folding/IntFoldingES3.sksl") SKSL_TEST(CPU + GPU + SkQP, FloatFolding, "folding/FloatFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, MatrixFoldingES2, "folding/MatrixFoldingES2.sksl") SKSL_TEST(GPU_ES3, MatrixFoldingES3, "folding/MatrixFoldingES3.sksl") SKSL_TEST(CPU + GPU + SkQP, Negation, "folding/Negation.sksl") // TODO(skia:13035): This test fails on Nvidia GPUs on OpenGL but passes Vulkan. Re-enable the test // on Vulkan when granular GPU backend selection is supported. SKSL_TEST(CPU + SkQP, PreserveSideEffects, "folding/PreserveSideEffects.sksl") SKSL_TEST(CPU + GPU + SkQP, SelfAssignment, "folding/SelfAssignment.sksl") SKSL_TEST(CPU + GPU + SkQP, ShortCircuitBoolFolding, "folding/ShortCircuitBoolFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, SwitchCaseFolding, "folding/SwitchCaseFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleFolding, "folding/SwizzleFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, TernaryFolding, "folding/TernaryFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, VectorScalarFolding, "folding/VectorScalarFolding.sksl") SKSL_TEST(CPU + GPU + SkQP, VectorVectorFolding, "folding/VectorVectorFolding.sksl") SKSL_TEST(GPU_ES3, DoWhileBodyMustBeInlinedIntoAScope, "inliner/DoWhileBodyMustBeInlinedIntoAScope.sksl") SKSL_TEST(GPU_ES3, DoWhileTestCannotBeInlined, "inliner/DoWhileTestCannotBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, ForBodyMustBeInlinedIntoAScope, "inliner/ForBodyMustBeInlinedIntoAScope.sksl") SKSL_TEST(GPU_ES3, ForInitializerExpressionsCanBeInlined, "inliner/ForInitializerExpressionsCanBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, ForWithoutReturnInsideCanBeInlined, "inliner/ForWithoutReturnInsideCanBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, ForWithReturnInsideCannotBeInlined, "inliner/ForWithReturnInsideCannotBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, IfBodyMustBeInlinedIntoAScope, "inliner/IfBodyMustBeInlinedIntoAScope.sksl") SKSL_TEST(CPU + GPU + SkQP, IfElseBodyMustBeInlinedIntoAScope, "inliner/IfElseBodyMustBeInlinedIntoAScope.sksl") SKSL_TEST(CPU + GPU + SkQP, IfElseChainWithReturnsCanBeInlined, "inliner/IfElseChainWithReturnsCanBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, IfTestCanBeInlined, "inliner/IfTestCanBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, IfWithReturnsCanBeInlined, "inliner/IfWithReturnsCanBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, InlineKeywordOverridesThreshold, "inliner/InlineKeywordOverridesThreshold.sksl") SKSL_TEST(CPU + GPU + SkQP, InlinerAvoidsVariableNameOverlap, "inliner/InlinerAvoidsVariableNameOverlap.sksl") SKSL_TEST(CPU + GPU + SkQP, InlinerElidesTempVarForReturnsInsideBlock, "inliner/InlinerElidesTempVarForReturnsInsideBlock.sksl") SKSL_TEST(CPU + GPU + SkQP, InlinerUsesTempVarForMultipleReturns, "inliner/InlinerUsesTempVarForMultipleReturns.sksl") SKSL_TEST(CPU + GPU + SkQP, InlinerUsesTempVarForReturnsInsideBlockWithVar, "inliner/InlinerUsesTempVarForReturnsInsideBlockWithVar.sksl") SKSL_TEST(CPU + GPU + SkQP, InlineThreshold, "inliner/InlineThreshold.sksl") SKSL_TEST(CPU + GPU + SkQP, InlineWithModifiedArgument, "inliner/InlineWithModifiedArgument.sksl") SKSL_TEST(CPU + GPU + SkQP, InlineWithNestedBigCalls, "inliner/InlineWithNestedBigCalls.sksl") SKSL_TEST(CPU + GPU + SkQP, InlineWithUnmodifiedArgument, "inliner/InlineWithUnmodifiedArgument.sksl") SKSL_TEST(CPU + GPU + SkQP, InlineWithUnnecessaryBlocks, "inliner/InlineWithUnnecessaryBlocks.sksl") SKSL_TEST(CPU + GPU + SkQP, NoInline, "inliner/NoInline.sksl") SKSL_TEST(CPU + GPU + SkQP, ShortCircuitEvaluationsCannotInlineRightHandSide, "inliner/ShortCircuitEvaluationsCannotInlineRightHandSide.sksl") SKSL_TEST(GPU_ES3, StaticSwitchInline, "inliner/StaticSwitch.sksl") SKSL_TEST(CPU + GPU + SkQP, StructsCanBeInlinedSafely, "inliner/StructsCanBeInlinedSafely.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleCanBeInlinedDirectly, "inliner/SwizzleCanBeInlinedDirectly.sksl") SKSL_TEST(CPU + GPU + SkQP, TernaryResultsCannotBeInlined, "inliner/TernaryResultsCannotBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, TernaryTestCanBeInlined, "inliner/TernaryTestCanBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, TrivialArgumentsInlineDirectly, "inliner/TrivialArgumentsInlineDirectly.sksl") SKSL_TEST(GPU_ES3, WhileBodyMustBeInlinedIntoAScope, "inliner/WhileBodyMustBeInlinedIntoAScope.sksl") SKSL_TEST(GPU_ES3, WhileTestCannotBeInlined, "inliner/WhileTestCannotBeInlined.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicAbsFloat, "intrinsics/AbsFloat.sksl") SKSL_TEST(GPU_ES3, IntrinsicAbsInt, "intrinsics/AbsInt.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicCeil, "intrinsics/Ceil.sksl") SKSL_TEST(GPU_ES3, IntrinsicDeterminant, "intrinsics/Determinant.sksl") SKSL_TEST(GPU_ES3, IntrinsicDFdx, "intrinsics/DFdx.sksl") SKSL_TEST(GPU_ES3, IntrinsicDFdy, "intrinsics/DFdy.sksl") SKSL_TEST(GPU_ES3, IntrinsicFloatBitsToInt, "intrinsics/FloatBitsToInt.sksl") SKSL_TEST(GPU_ES3, IntrinsicFloatBitsToUint, "intrinsics/FloatBitsToUint.sksl") SKSL_TEST(GPU_ES3, IntrinsicFwidth, "intrinsics/Fwidth.sksl") SKSL_TEST(GPU_ES3, IntrinsicIntBitsToFloat, "intrinsics/IntBitsToFloat.sksl") SKSL_TEST(GPU_ES3, IntrinsicIsInf, "intrinsics/IsInf.sksl") SKSL_TEST(GPU_ES3, IntrinsicClampInt, "intrinsics/ClampInt.sksl") SKSL_TEST(GPU_ES3, IntrinsicClampUInt, "intrinsics/ClampUInt.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicClampFloat, "intrinsics/ClampFloat.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicMatrixCompMultES2, "intrinsics/MatrixCompMultES2.sksl") SKSL_TEST(GPU_ES3, IntrinsicMatrixCompMultES3, "intrinsics/MatrixCompMultES3.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicMaxFloat, "intrinsics/MaxFloat.sksl") SKSL_TEST(GPU_ES3, IntrinsicMaxInt, "intrinsics/MaxInt.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicMinFloat, "intrinsics/MinFloat.sksl") SKSL_TEST(GPU_ES3, IntrinsicMinInt, "intrinsics/MinInt.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicMixFloat, "intrinsics/MixFloat.sksl") SKSL_TEST(GPU_ES3, IntrinsicModf, "intrinsics/Modf.sksl") SKSL_TEST(GPU_ES3, IntrinsicOuterProduct, "intrinsics/OuterProduct.sksl") // Fails on Mac OpenGL + Radeon 5300M (skia:12434) // SKSL_TEST(GPU_ES3, IntrinsicPackUnorm2x16, "intrinsics/PackUnorm2x16.sksl") SKSL_TEST(GPU_ES3, IntrinsicRound, "intrinsics/Round.sksl") SKSL_TEST(GPU_ES3, IntrinsicRoundEven, "intrinsics/RoundEven.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicSignFloat, "intrinsics/SignFloat.sksl") SKSL_TEST(GPU_ES3, IntrinsicSignInt, "intrinsics/SignInt.sksl") SKSL_TEST(CPU + GPU + SkQP, IntrinsicStep, "intrinsics/Step.sksl") SKSL_TEST(GPU_ES3, IntrinsicTrunc, "intrinsics/Trunc.sksl") SKSL_TEST(GPU_ES3, IntrinsicTranspose, "intrinsics/Transpose.sksl") SKSL_TEST(GPU_ES3, IntrinsicUintBitsToFloat, "intrinsics/UintBitsToFloat.sksl") SKSL_TEST(GPU_ES3, ArrayNarrowingConversions, "runtime/ArrayNarrowingConversions.rts") SKSL_TEST(CPU + GPU + SkQP, LoopFloat, "runtime/LoopFloat.rts") SKSL_TEST(CPU + GPU + SkQP, LoopInt, "runtime/LoopInt.rts") SKSL_TEST(CPU + GPU + SkQP, QualifierOrder, "runtime/QualifierOrder.rts") SKSL_TEST(CPU + GPU + SkQP, PrecisionQualifiers, "runtime/PrecisionQualifiers.rts") // These tests specifically rely the behavior of NaN values, but some older GPUs do not reliably // implement full IEEE support (skia:12977). They also rely on equality operators on array types // which are not available in GLSL ES 1.00. Therefore these tests are restricted to run on CPU and // with "strict ES2 mode" disabled. SKSL_TEST(CPU_ES3, RecursiveComparison_Arrays, "runtime/RecursiveComparison_Arrays.rts") SKSL_TEST(CPU_ES3, RecursiveComparison_Structs, "runtime/RecursiveComparison_Structs.rts") SKSL_TEST(CPU_ES3, RecursiveComparison_Types, "runtime/RecursiveComparison_Types.rts") SKSL_TEST(CPU_ES3, RecursiveComparison_Vectors, "runtime/RecursiveComparison_Vectors.rts") SKSL_TEST(GPU_ES3, ArrayCast, "shared/ArrayCast.sksl") SKSL_TEST(GPU_ES3, ArrayComparison, "shared/ArrayComparison.sksl") SKSL_TEST(GPU_ES3, ArrayConstructors, "shared/ArrayConstructors.sksl") SKSL_TEST(GPU_ES3, ArrayFollowedByScalar, "shared/ArrayFollowedByScalar.sksl") SKSL_TEST(CPU + GPU + SkQP, ArrayTypes, "shared/ArrayTypes.sksl") SKSL_TEST(CPU + GPU + SkQP, Assignment, "shared/Assignment.sksl") SKSL_TEST(CPU + GPU + SkQP, CastsRoundTowardZero, "shared/CastsRoundTowardZero.sksl") SKSL_TEST(CPU + GPU + SkQP, CommaMixedTypes, "shared/CommaMixedTypes.sksl") SKSL_TEST(CPU + GPU + SkQP, CommaSideEffects, "shared/CommaSideEffects.sksl") SKSL_TEST(CPU + GPU + SkQP, ConstantIf, "shared/ConstantIf.sksl") SKSL_TEST(GPU_ES3, ConstArray, "shared/ConstArray.sksl") SKSL_TEST(CPU + GPU + SkQP, ConstVariableComparison, "shared/ConstVariableComparison.sksl") SKSL_TEST(GPU_ES3, DeadLoopVariable, "shared/DeadLoopVariable.sksl") SKSL_TEST(CPU + GPU + SkQP, DeadIfStatement, "shared/DeadIfStatement.sksl") SKSL_TEST(CPU + GPU + SkQP, DeadReturn, "shared/DeadReturn.sksl") // TODO(skia:12012): some Radeons crash when compiling this code; disable them. // SKSL_TEST(GPU_ES3, SkSLDeadReturnES3, "shared/DeadReturnES3.sksl") SKSL_TEST(CPU + GPU + SkQP, DeadStripFunctions, "shared/DeadStripFunctions.sksl") SKSL_TEST(CPU + GPU + SkQP, DependentInitializers, "shared/DependentInitializers.sksl") SKSL_TEST(CPU + GPU + SkQP, DoubleNegation, "shared/DoubleNegation.sksl") SKSL_TEST(GPU_ES3, DoWhileControlFlow, "shared/DoWhileControlFlow.sksl") SKSL_TEST(CPU + GPU + SkQP, EmptyBlocksES2, "shared/EmptyBlocksES2.sksl") SKSL_TEST(GPU_ES3, EmptyBlocksES3, "shared/EmptyBlocksES3.sksl") SKSL_TEST(CPU + GPU + SkQP, ForLoopControlFlow, "shared/ForLoopControlFlow.sksl") SKSL_TEST(CPU + GPU + SkQP, FunctionAnonymousParameters, "shared/FunctionAnonymousParameters.sksl") SKSL_TEST(CPU + GPU + SkQP, FunctionArgTypeMatch, "shared/FunctionArgTypeMatch.sksl") SKSL_TEST(CPU + GPU + SkQP, FunctionReturnTypeMatch, "shared/FunctionReturnTypeMatch.sksl") SKSL_TEST(CPU + GPU + SkQP, Functions, "shared/Functions.sksl") SKSL_TEST(CPU + GPU + SkQP, FunctionPrototype, "shared/FunctionPrototype.sksl") SKSL_TEST(CPU + GPU + SkQP, GeometricIntrinsics, "shared/GeometricIntrinsics.sksl") SKSL_TEST(CPU + GPU + SkQP, HelloWorld, "shared/HelloWorld.sksl") SKSL_TEST(CPU + GPU + SkQP, Hex, "shared/Hex.sksl") SKSL_TEST(GPU_ES3, HexUnsigned, "shared/HexUnsigned.sksl") SKSL_TEST(CPU + GPU + SkQP, InoutParameters, "shared/InoutParameters.sksl") SKSL_TEST(CPU + GPU + SkQP, InoutParamsAreDistinct, "shared/InoutParamsAreDistinct.sksl") SKSL_TEST(CPU + GPU + SkQP, Matrices, "shared/Matrices.sksl") SKSL_TEST(GPU_ES3, MatricesNonsquare, "shared/MatricesNonsquare.sksl") // TODO(skia:12443) These tests actually don't work on MANY devices. The GLSL SkQP suite // does a terrible job of enforcing this rule. We still test them on CPU. SKSL_TEST(CPU, MatrixConstructorsES2, "shared/MatrixConstructorsES2.sksl") SKSL_TEST(CPU_ES3, MatrixConstructorsES3, "shared/MatrixConstructorsES3.sksl") SKSL_TEST(CPU + GPU + SkQP, MatrixEquality, "shared/MatrixEquality.sksl") SKSL_TEST(CPU + GPU + SkQP, MatrixScalarMath, "shared/MatrixScalarMath.sksl") SKSL_TEST(CPU + GPU + SkQP, MatrixToVectorCast, "shared/MatrixToVectorCast.sksl") SKSL_TEST(CPU + GPU + SkQP, MultipleAssignments, "shared/MultipleAssignments.sksl") SKSL_TEST(CPU + GPU + SkQP, NumberCasts, "shared/NumberCasts.sksl") SKSL_TEST(CPU + GPU + SkQP, OperatorsES2, "shared/OperatorsES2.sksl") SKSL_TEST(GPU_ES3, OperatorsES3, "shared/OperatorsES3.sksl") SKSL_TEST(CPU + GPU + SkQP, Ossfuzz36852, "shared/Ossfuzz36852.sksl") SKSL_TEST(CPU + GPU + SkQP, OutParams, "shared/OutParams.sksl") SKSL_TEST(CPU + GPU + SkQP, OutParamsAreDistinct, "shared/OutParamsAreDistinct.sksl") SKSL_TEST(CPU + GPU + SkQP, OutParamsAreDistinctFromGlobal, "shared/OutParamsAreDistinctFromGlobal.sksl") SKSL_TEST(CPU + GPU + SkQP, OutParamsTricky, "shared/OutParamsTricky.sksl") SKSL_TEST(CPU + GPU + SkQP, ResizeMatrix, "shared/ResizeMatrix.sksl") SKSL_TEST(GPU_ES3, ResizeMatrixNonsquare, "shared/ResizeMatrixNonsquare.sksl") SKSL_TEST(CPU + GPU + SkQP, ReturnsValueOnEveryPathES2, "shared/ReturnsValueOnEveryPathES2.sksl") SKSL_TEST(GPU_ES3, ReturnsValueOnEveryPathES3, "shared/ReturnsValueOnEveryPathES3.sksl") SKSL_TEST(CPU + GPU + SkQP, ScalarConversionConstructorsES2, "shared/ScalarConversionConstructorsES2.sksl") SKSL_TEST(GPU_ES3, ScalarConversionConstructorsES3, "shared/ScalarConversionConstructorsES3.sksl") SKSL_TEST(CPU + GPU + SkQP, ScopedSymbol, "shared/ScopedSymbol.sksl") SKSL_TEST(CPU + GPU + SkQP, StackingVectorCasts, "shared/StackingVectorCasts.sksl") SKSL_TEST(CPU + GPU + SkQP, StaticIf, "shared/StaticIf.sksl") SKSL_TEST(GPU_ES3, StaticSwitch, "shared/StaticSwitch.sksl") SKSL_TEST(CPU + GPU + SkQP, StructArrayFollowedByScalar, "shared/StructArrayFollowedByScalar.sksl") SKSL_TEST(CPU + GPU + SkQP, StructsInFunctions, "shared/StructsInFunctions.sksl") SKSL_TEST(CPU + GPU + SkQP, Switch, "shared/Switch.sksl") SKSL_TEST(CPU + GPU + SkQP, SwitchDefaultOnly, "shared/SwitchDefaultOnly.sksl") SKSL_TEST(CPU + GPU + SkQP, SwitchWithFallthrough, "shared/SwitchWithFallthrough.sksl") SKSL_TEST(CPU + GPU + SkQP, SwitchWithLoops, "shared/SwitchWithLoops.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleBoolConstants, "shared/SwizzleBoolConstants.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleByConstantIndex, "shared/SwizzleByConstantIndex.sksl") SKSL_TEST(GPU_ES3, SwizzleByIndex, "shared/SwizzleByIndex.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleConstants, "shared/SwizzleConstants.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleLTRB, "shared/SwizzleLTRB.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleOpt, "shared/SwizzleOpt.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleScalar, "shared/SwizzleScalar.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleScalarBool, "shared/SwizzleScalarBool.sksl") SKSL_TEST(CPU + GPU + SkQP, SwizzleScalarInt, "shared/SwizzleScalarInt.sksl") SKSL_TEST(CPU + GPU + SkQP, TernaryAsLValueEntirelyFoldable, "shared/TernaryAsLValueEntirelyFoldable.sksl") SKSL_TEST(CPU + GPU + SkQP, TernaryAsLValueFoldableTest, "shared/TernaryAsLValueFoldableTest.sksl") SKSL_TEST(CPU + GPU + SkQP, TernaryExpression, "shared/TernaryExpression.sksl") SKSL_TEST(CPU + GPU + SkQP, UnaryPositiveNegative, "shared/UnaryPositiveNegative.sksl") SKSL_TEST(CPU + GPU + SkQP, UniformArray, "shared/UniformArray.sksl") SKSL_TEST(CPU + GPU + SkQP, UnusedVariables, "shared/UnusedVariables.sksl") SKSL_TEST(CPU + GPU + SkQP, VectorConstructors, "shared/VectorConstructors.sksl") SKSL_TEST(CPU + GPU + SkQP, VectorToMatrixCast, "shared/VectorToMatrixCast.sksl") SKSL_TEST(CPU + GPU + SkQP, VectorScalarMath, "shared/VectorScalarMath.sksl") SKSL_TEST(GPU_ES3, WhileLoopControlFlow, "shared/WhileLoopControlFlow.sksl")
60.708333
142
0.643976
JimmySoftware
70929db9c14e6601c1bca30fd12e857640cff2cd
5,563
hpp
C++
include/El/lapack_like/funcs.hpp
justusc/Elemental
145ccb28411f3f0c65ca30ecea776df33297e4ff
[ "BSD-3-Clause" ]
null
null
null
include/El/lapack_like/funcs.hpp
justusc/Elemental
145ccb28411f3f0c65ca30ecea776df33297e4ff
[ "BSD-3-Clause" ]
null
null
null
include/El/lapack_like/funcs.hpp
justusc/Elemental
145ccb28411f3f0c65ca30ecea776df33297e4ff
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_FUNCS_HPP #define EL_FUNCS_HPP #include "El/lapack_like/factor.hpp" #include "El/lapack_like/spectral.hpp" namespace El { namespace SignScalingNS { enum SignScaling { SIGN_SCALE_NONE, SIGN_SCALE_DET, SIGN_SCALE_FROB }; } using namespace SignScalingNS; template<typename Real> struct SignCtrl { Int maxIts=100; Real tol=0; Real power=1; SignScaling scaling=SIGN_SCALE_FROB; bool progress=false; }; template<typename Real> struct SquareRootCtrl { Int maxIts=100; Real tol=0; Real power=1; bool progress=false; }; // Hermitian function // ================== template<typename F> void HermitianFunction ( UpperOrLower uplo, Matrix<F>& A, function<Base<F>(Base<F>)> func ); template<typename F> void HermitianFunction ( UpperOrLower uplo, AbstractDistMatrix<F>& A, function<Base<F>(Base<F>)> func ); template<typename Real> void HermitianFunction ( UpperOrLower uplo, Matrix<Complex<Real>>& A, function<Complex<Real>(Real)> func ); template<typename Real> void HermitianFunction ( UpperOrLower uplo, AbstractDistMatrix<Complex<Real>>& A, function<Complex<Real>(Real)> func ); // Inverse // ======= template<typename F> void Inverse( Matrix<F>& A ); template<typename F> void Inverse( AbstractDistMatrix<F>& A ); template<typename F> void LocalInverse( DistMatrix<F,STAR,STAR>& A ); namespace inverse { template<typename F> void AfterLUPartialPiv( Matrix<F>& A, const Matrix<Int>& p ); template<typename F> void AfterLUPartialPiv ( AbstractDistMatrix<F>& A, const AbstractDistMatrix<Int>& p ); } // namespace inverse template<typename F> void HPDInverse( UpperOrLower uplo, Matrix<F>& A ); template<typename F> void HPDInverse( UpperOrLower uplo, AbstractDistMatrix<F>& A ); template<typename F> void LocalHPDInverse( UpperOrLower uplo, DistMatrix<F,STAR,STAR>& A ); template<typename F> void HermitianInverse ( UpperOrLower uplo, Matrix<F>& A, const LDLPivotCtrl<Base<F>>& ctrl=LDLPivotCtrl<Base<F>>() ); template<typename F> void HermitianInverse ( UpperOrLower uplo, AbstractDistMatrix<F>& A, const LDLPivotCtrl<Base<F>>& ctrl=LDLPivotCtrl<Base<F>>() ); template<typename F> void LocalHermitianInverse ( UpperOrLower uplo, DistMatrix<F,STAR,STAR>& A, const LDLPivotCtrl<Base<F>>& ctrl=LDLPivotCtrl<Base<F>>() ); template<typename F> void SymmetricInverse ( UpperOrLower uplo, Matrix<F>& A, bool conjugate=false, const LDLPivotCtrl<Base<F>>& ctrl=LDLPivotCtrl<Base<F>>() ); template<typename F> void SymmetricInverse ( UpperOrLower uplo, AbstractDistMatrix<F>& A, bool conjugate=false, const LDLPivotCtrl<Base<F>>& ctrl=LDLPivotCtrl<Base<F>>() ); template<typename F> void LocalSymmetricInverse ( UpperOrLower uplo, DistMatrix<F,STAR,STAR>& A, bool conjugate=false, const LDLPivotCtrl<Base<F>>& ctrl=LDLPivotCtrl<Base<F>>() ); template<typename F> void TriangularInverse( UpperOrLower uplo, UnitOrNonUnit diag, Matrix<F>& A ); template<typename F> void TriangularInverse ( UpperOrLower uplo, UnitOrNonUnit diag, AbstractDistMatrix<F>& A ); template<typename F> void LocalTriangularInverse ( UpperOrLower uplo, UnitOrNonUnit diag, DistMatrix<F,STAR,STAR>& A ); // Pseudoinverse // ============= template<typename F> void Pseudoinverse( Matrix<F>& A, Base<F> tolerance=0 ); template<typename F> void Pseudoinverse( AbstractDistMatrix<F>& A, Base<F> tolerance=0 ); template<typename F> void HermitianPseudoinverse ( UpperOrLower uplo, Matrix<F>& A, Base<F> tolerance=0 ); template<typename F> void HermitianPseudoinverse ( UpperOrLower uplo, AbstractDistMatrix<F>& A, Base<F> tolerance=0 ); // Sign // ==== template<typename F> void Sign ( Matrix<F>& A, const SignCtrl<Base<F>> ctrl=SignCtrl<Base<F>>() ); template<typename F> void Sign ( AbstractDistMatrix<F>& A, const SignCtrl<Base<F>> ctrl=SignCtrl<Base<F>>() ); template<typename F> void Sign ( Matrix<F>& A, Matrix<F>& N, const SignCtrl<Base<F>> ctrl=SignCtrl<Base<F>>() ); template<typename F> void Sign ( AbstractDistMatrix<F>& A, AbstractDistMatrix<F>& N, const SignCtrl<Base<F>> ctrl=SignCtrl<Base<F>>() ); template<typename F> void HermitianSign ( UpperOrLower uplo, Matrix<F>& A, const HermitianEigCtrl<F>& ctrl=HermitianEigCtrl<F>() ); template<typename F> void HermitianSign ( UpperOrLower uplo, AbstractDistMatrix<F>& A, const HermitianEigCtrl<F>& ctrl=HermitianEigCtrl<F>() ); template<typename F> void HermitianSign ( UpperOrLower uplo, Matrix<F>& A, Matrix<F>& N, const HermitianEigCtrl<F>& ctrl=HermitianEigCtrl<F>() ); template<typename F> void HermitianSign ( UpperOrLower uplo, AbstractDistMatrix<F>& A, AbstractDistMatrix<F>& N, const HermitianEigCtrl<F>& ctrl=HermitianEigCtrl<F>() ); // SquareRoot // ========== template<typename F> void SquareRoot ( Matrix<F>& A, const SquareRootCtrl<Base<F>> ctrl=SquareRootCtrl<Base<F>>() ); template<typename F> void SquareRoot ( AbstractDistMatrix<F>& A, const SquareRootCtrl<Base<F>> ctrl=SquareRootCtrl<Base<F>>() ); template<typename F> void HPSDSquareRoot ( UpperOrLower uplo, Matrix<F>& A, const HermitianEigCtrl<F>& ctrl=HermitianEigCtrl<F>() ); template<typename F> void HPSDSquareRoot ( UpperOrLower uplo, AbstractDistMatrix<F>& A, const HermitianEigCtrl<F>& ctrl=HermitianEigCtrl<F>() ); } // namespace El #endif // ifndef EL_FUNCS_HPP
28.382653
79
0.735035
justusc
709577b78f903cff5d6576c3bfa842746ddcff02
231
cpp
C++
ion/src/shared/dummy/usb.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,442
2017-08-28T19:39:45.000Z
2022-03-30T00:56:14.000Z
ion/src/shared/dummy/usb.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,321
2017-08-28T23:03:10.000Z
2022-03-31T19:32:17.000Z
ion/src/shared/dummy/usb.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
421
2017-08-28T22:02:39.000Z
2022-03-28T20:52:21.000Z
#include <ion/usb.h> namespace Ion { namespace USB { bool isPlugged() { return false; } bool isEnumerated() { return false; } void clearEnumerationInterrupt() { } void DFU() { } void enable() { } void disable() { } } }
8.25
34
0.632035
VersiraSec
7096a1bbcd2c4e7199e6127d65867669820439cf
5,439
cpp
C++
Templates/Full/web/source/activex/IEWebGameWindow.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
2,113
2015-01-01T11:23:01.000Z
2022-03-28T04:51:46.000Z
Templates/Full/web/source/activex/IEWebGameWindow.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
948
2015-01-02T01:50:00.000Z
2022-02-27T05:56:40.000Z
Templates/Full/web/source/activex/IEWebGameWindow.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
944
2015-01-01T09:33:53.000Z
2022-03-15T22:23:03.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "StdAfx.h" #include <shlobj.h> #include "IEWebGameWindow.h" #include "../common/webCommon.h" // We hook the keyboard at application level so we TAB, Backspace, other accelerator combos // are captured and don't cause us grief static HHOOK hHook = NULL; // Hook procedure for WH_GETMESSAGE hook type. LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam) { // If this is a keystrokes message, translate it in controls' LPMSG lpMsg = (LPMSG) lParam; if( (nCode >= 0) && PM_REMOVE == wParam && (lpMsg->message >= WM_KEYFIRST && lpMsg->message <= WM_KEYLAST) ) { if (torque_directmessage) { // call directly into the Torque 3D message queue, bypassing the windows event queue // as we're hooking into the application level processing, this would cause a hang torque_directmessage(lpMsg->message, lpMsg->wParam, lpMsg->lParam); // The value returned from this hookproc is ignored, and it cannot // be used to tell Windows the message has been handled. To avoid // further processing, convert the message to WM_NULL before // returning. lpMsg->message = WM_NULL; lpMsg->lParam = 0L; lpMsg->wParam = 0; } } // Passes the hook information to the next hook procedure in // the current hook chain. return ::CallNextHookEx(hHook, nCode, wParam, lParam); } WebGameWindow::WebGameWindow(void) { mTimer = false; mInitialized = false; } WebGameWindow::~WebGameWindow(void) { //handling threads in event callbacks (onDestroy for instance) seems to cause loads of problems (deadlocks, etc) if (mInitialized) WebCommon::ShutdownTorque3D(); } // we use a timer to update the Torque 3D game loop (tick) and handle rendering VOID CALLBACK MyTimerProc( HWND hwnd, // handle to window for timer messages UINT message, // WM_TIMER message UINT idTimer, // timer identifier DWORD dwTime) // current system time { static bool reentrant = false; if (!reentrant) { reentrant = true; torque_enginetick(); reentrant = false; } } LRESULT WebGameWindow::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { bHandled = TRUE; // check that the domain we're loading the plugin from is allowed if (!checkDomain()) { return -1; } // load up the Torque 3D shared library and initialize it if (!WebCommon::InitTorque3D(this->m_hWnd)) { return -1; } mTimer = true; mInitialized = true; // fire up timer for ticking Torque 3D update SetTimer( 1, // timer identifier 1, // 1 millisecond (TIMERPROC) MyTimerProc); // timer callback hHook = ::SetWindowsHookEx( WH_GETMESSAGE, GetMessageProc, WebCommon::gPluginModule, GetCurrentThreadId()); return 0; } //------------------------------------------------------------------------------ /** */ LRESULT WebGameWindow::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { // let the default handler run bHandled = FALSE; // kill update timer if (mTimer) KillTimer( 1); mTimer = false; if (hHook) ::UnhookWindowsHookEx (hHook); hHook = NULL; return 0; } //------------------------------------------------------------------------------ /** */ LRESULT WebGameWindow::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { // let the default handler run bHandled = FALSE; // resize the Torque 3D child window depending on our browser's parent window if (mInitialized && torque_resizewindow) { int width = (int) LOWORD( lParam ); int height = (int) HIWORD( lParam ); torque_resizewindow(width,height); } return 0; } //------------------------------------------------------------------------------ /** */ LRESULT WebGameWindow::OnMouseActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { return MA_ACTIVATE; }
29.721311
115
0.616106
vbillet
7098d08f8428c82d2dcf2824d187fb1ce09fb70d
2,169
cpp
C++
tests/lex/identifier_test.cpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
14
2020-04-14T17:00:56.000Z
2021-08-30T08:29:26.000Z
tests/lex/identifier_test.cpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
27
2020-12-27T16:00:44.000Z
2021-08-01T13:12:14.000Z
tests/lex/identifier_test.cpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
1
2020-05-29T18:33:37.000Z
2020-05-29T18:33:37.000Z
#include "catch2/catch.hpp" #include "helpers.hpp" #include "lex/error.hpp" namespace lex { TEST_CASE("[lex] Lexing identifiers", "lex") { SECTION("Valid") { CHECK_TOKENS("hello", identiferToken("hello")); CHECK_TOKENS("héllo", identiferToken("héllo")); CHECK_TOKENS("_hello", identiferToken("_hello")); CHECK_TOKENS("_hello_world", identiferToken("_hello_world")); CHECK_TOKENS("_hello123", identiferToken("_hello123")); CHECK_TOKENS("_1", identiferToken("_1")); CHECK_TOKENS("_1", identiferToken("_1")); CHECK_TOKENS("你好世界", identiferToken("你好世界")); CHECK_TOKENS("_你好世界", identiferToken("_你好世界")); CHECK_TOKENS("_你1好2世3界", identiferToken("_你1好2世3界")); CHECK_TOKENS("_", basicToken(TokenKind::Discard)); } SECTION("Sequences") { CHECK_TOKENS("hello world", identiferToken("hello"), identiferToken("world")); CHECK_TOKENS( "hello,world", identiferToken("hello"), basicToken(TokenKind::SepComma), identiferToken("world")); CHECK_TOKENS( "hello;world", identiferToken("hello"), basicToken(TokenKind::OpSemi), identiferToken("world")); CHECK_TOKENS( "hello@world", identiferToken("hello"), errInvalidChar('@'), identiferToken("world")); CHECK_TOKENS("hello#world", identiferToken("hello"), errStaticIntInvalidChar()); } SECTION("Errors") { CHECK_TOKENS("1test", errLitNumberInvalidChar()); CHECK_TOKENS("h\a_hello", errIdentifierIllegalCharacter()); CHECK_TOKENS("@", errInvalidChar('@')); // Ids containing '__' are reserved for internal use. CHECK_TOKENS("__", errIdentifierIllegalSequence()); CHECK_TOKENS("___", errIdentifierIllegalSequence()); CHECK_TOKENS("__hello", errIdentifierIllegalSequence()); CHECK_TOKENS("hello__", errIdentifierIllegalSequence()); CHECK_TOKENS("hello__world", errIdentifierIllegalSequence()); } SECTION("Spans") { CHECK_SPANS(" helloworld ", input::Span{1, 10}); CHECK_SPANS(" helloworld__ ", input::Span{1, 12}); CHECK_SPANS(" __helloworld ", input::Span{1, 12}); CHECK_SPANS(" _1 ", input::Span{1, 2}); } } } // namespace lex
34.983871
94
0.674504
BastianBlokland
709e0d028293899ace396f1a15275a36d7c9faee
5,044
cpp
C++
Blue/Tools/zxcppvbn/adjacency_graphs.cpp
AmiditeX/Blue
6a7a5dfa5e719a97a628bf8c4f2be1e672ed7350
[ "MIT" ]
4
2018-05-30T16:45:46.000Z
2020-08-17T06:50:41.000Z
Blue/Tools/zxcppvbn/adjacency_graphs.cpp
AmiditeX/Blue
6a7a5dfa5e719a97a628bf8c4f2be1e672ed7350
[ "MIT" ]
5
2018-02-27T19:46:56.000Z
2018-05-30T16:44:58.000Z
Blue/Tools/zxcppvbn/adjacency_graphs.cpp
AmiditeX/Blue
6a7a5dfa5e719a97a628bf8c4f2be1e672ed7350
[ "MIT" ]
null
null
null
#include "zxcppvbn.hpp" const size_t zxcppvbn::adjacency_graphs_size = 1369; const uint8_t zxcppvbn::adjacency_graphs[] = {31,139,8,8,209,76,234,90,2,255,97,100,106,97,99,101,110,99,121,95,103,114,97,112,104,115,0,165,151,107,67,83,71,16,134,203,206,47,17,21,36,36,16,8,4,2,4,197,90,235,181,173,149,182,84,80,12,132,107,184,223,175,253,237,125,222,217,72,200,186,159,90,62,152,115,102,119,102,159,185,236,204,241,240,124,237,232,228,50,60,178,202,67,51,27,127,108,71,191,219,218,79,22,158,216,100,1,65,121,192,246,127,181,173,215,22,138,182,251,222,90,111,109,231,157,13,205,178,18,202,86,123,194,111,105,217,14,126,211,166,48,150,218,152,180,137,62,4,108,195,192,233,31,22,102,82,27,207,108,228,1,191,232,157,255,101,135,31,44,188,176,227,143,210,197,194,250,75,91,253,209,46,22,44,188,178,141,159,237,242,111,153,216,126,99,123,191,216,202,115,11,239,100,136,99,57,124,122,74,230,138,51,22,28,4,102,160,22,175,37,231,164,48,47,107,80,85,191,200,8,166,176,28,22,236,234,147,206,106,190,208,41,160,44,217,231,91,243,191,240,85,255,58,88,104,230,120,54,115,60,59,57,158,131,28,207,73,142,231,34,229,185,233,240,60,180,209,103,252,142,61,18,9,129,10,253,50,133,65,223,49,252,212,194,160,78,224,15,1,226,48,172,243,217,210,223,235,250,149,84,127,66,103,155,50,140,11,48,132,105,129,65,142,50,58,88,68,63,60,237,182,226,190,131,7,237,217,159,18,56,248,201,188,12,108,190,82,12,16,135,183,10,9,233,198,111,76,22,61,227,193,43,136,50,32,18,28,178,227,169,11,31,173,49,39,26,152,176,122,225,9,9,94,5,208,82,17,200,143,125,79,88,148,22,14,214,7,229,32,56,64,133,101,89,51,201,128,102,61,172,166,124,27,57,190,86,142,111,63,199,119,156,227,59,207,241,93,231,248,122,211,28,245,165,65,47,164,215,99,72,60,156,142,34,10,120,48,154,94,143,170,234,198,164,135,1,92,11,83,185,196,205,166,118,220,117,10,141,48,80,173,8,94,202,37,170,16,19,136,89,164,230,194,27,173,195,1,13,254,19,23,246,6,47,110,228,68,13,9,170,126,181,41,37,64,208,94,119,75,193,13,240,140,49,182,179,235,147,41,50,196,135,184,241,250,37,229,94,73,137,214,115,68,219,57,162,189,148,232,40,71,116,150,18,93,117,19,253,211,185,227,15,236,171,222,200,42,33,182,240,88,182,76,201,58,241,206,17,6,210,70,87,74,75,111,164,219,194,120,106,161,150,54,211,122,247,125,157,51,41,146,99,240,168,50,11,126,77,73,59,118,208,111,122,87,12,94,36,24,130,6,51,45,191,105,193,99,194,3,175,36,29,213,15,238,22,40,88,192,97,11,94,108,68,30,77,142,222,246,44,7,207,2,128,200,49,186,233,29,54,124,22,12,94,217,210,141,169,156,66,35,229,90,203,113,109,229,184,118,83,174,195,148,235,52,199,117,153,227,186,77,185,122,154,103,251,71,141,214,189,169,69,22,84,249,157,169,5,158,42,168,168,253,241,190,178,14,158,238,107,123,114,97,148,75,162,252,140,165,118,58,147,11,35,66,152,201,217,233,76,175,162,175,51,189,240,36,22,93,236,56,113,122,17,39,36,88,194,55,74,54,78,47,206,5,19,6,174,40,81,84,101,251,217,177,144,227,116,209,16,157,151,41,116,217,207,30,130,167,134,181,160,184,114,22,150,99,117,47,121,124,190,159,94,25,158,205,28,207,78,142,231,32,199,115,146,227,185,72,121,110,58,60,157,233,213,30,138,253,223,42,129,23,175,132,65,157,169,62,169,252,114,49,152,95,36,38,246,206,186,143,54,149,89,37,181,211,153,98,237,25,58,237,87,156,228,232,22,106,126,101,172,120,58,99,177,198,110,163,170,115,245,88,138,120,182,233,25,139,147,44,54,159,216,50,60,233,28,204,241,4,130,51,212,230,61,82,156,131,7,156,192,37,209,144,241,160,96,155,165,56,138,22,99,199,128,100,216,169,130,195,240,236,81,210,96,89,205,113,109,228,184,90,41,215,126,142,235,56,199,117,158,114,93,167,92,189,105,110,250,210,32,23,210,171,225,83,43,246,4,110,15,4,106,145,163,233,213,232,76,46,140,104,250,77,117,39,107,54,103,229,121,123,164,227,121,108,245,174,26,219,3,71,55,253,190,49,183,48,129,6,49,161,10,77,51,43,246,93,28,34,202,120,170,111,30,239,7,113,198,35,223,243,61,193,151,120,110,247,55,205,45,182,243,22,219,243,189,185,213,166,94,73,137,214,115,68,219,41,209,94,142,232,40,71,116,150,18,93,117,19,101,231,150,190,208,238,205,45,136,52,149,6,210,54,87,74,139,110,164,219,194,120,106,161,150,182,211,122,122,83,231,188,33,147,58,210,69,217,105,114,241,68,37,162,30,63,143,245,217,242,186,253,201,19,103,243,133,119,175,240,190,61,199,241,26,151,125,114,97,1,109,2,135,158,79,46,30,49,132,102,252,2,208,96,113,178,248,245,140,185,246,151,147,79,174,56,146,245,169,213,72,169,214,114,84,91,57,170,221,148,234,48,165,58,205,81,93,230,168,110,187,169,122,90,107,151,7,141,38,237,174,102,5,43,121,119,172,234,66,13,235,169,100,146,79,42,75,133,216,57,245,30,124,13,137,150,38,116,217,202,54,106,149,118,107,29,81,63,180,113,36,229,248,63,50,27,241,213,161,111,159,253,172,85,245,44,53,221,73,223,93,245,29,229,152,112,140,78,98,92,50,173,51,10,205,69,227,254,170,38,171,207,87,23,176,164,107,236,251,85,65,210,80,137,176,92,112,124,211,170,102,167,185,168,230,239,99,56,190,219,88,93,190,115,190,202,66,116,190,114,231,188,220,175,201,245,154,107,186,243,85,57,95,143,222,151,98,104,254,139,247,131,255,223,253,250,119,238,187,183,119,254,215,239,34,208,9,128,100,119,1,112,47,92,224,73,236,249,225,95,235,166,166,198,118,15,0,0};
840.666667
4,964
0.722839
AmiditeX
709ed893ddce1531250294ae89f372f432eb61d3
2,011
cpp
C++
Plugins/EZOnline/Source/EZOnline/Private/EZClientGameMode.cpp
feixuwu/TankFire
c172cab5d5599ff066dfe17bb89945893fdee572
[ "MIT" ]
41
2018-02-14T04:12:40.000Z
2022-03-14T09:24:37.000Z
Plugins/EZOnline/Source/EZOnline/Private/EZClientGameMode.cpp
feixuwu/TankFire
c172cab5d5599ff066dfe17bb89945893fdee572
[ "MIT" ]
3
2018-07-11T08:36:07.000Z
2020-10-03T02:19:35.000Z
Plugins/EZOnline/Source/EZOnline/Private/EZClientGameMode.cpp
feixuwu/TankFire
c172cab5d5599ff066dfe17bb89945893fdee572
[ "MIT" ]
35
2018-03-05T07:08:23.000Z
2022-03-28T11:17:17.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "EZClientGameMode.h" #include "WebSocketBlueprintLibrary.h" #include "EZOnline.h" #include "CoreGlobals.h" #include "Misc/ConfigCacheIni.h" #include "EZOnlineGameInstance.h" #include "GameMapsSettings.h" #include "Kismet/KismetStringLibrary.h" #include "Kismet/GameplayStatics.h" void AEZClientGameMode::BeginPlay() { Super::BeginPlay(); FString strServer;// = TEXT("ws://192.168.1.3:8000"); if (!GConfig->GetString(TEXT("/Script/EZOnlineEditor.ServerConfig"), TEXT("CenterServerForClient"), strServer, GEngineIni) || strServer.IsEmpty() ) { UE_LOG(EZOnline, Error, TEXT("CenterServer is not valid:%s"), *strServer); return; } UWebSocketBase* webSocket = UWebSocketBlueprintLibrary::Connect(strServer); UEZOnlineGameInstance* pEzGameInstance = Cast<UEZOnlineGameInstance>(GetGameInstance() ); if (pEzGameInstance == nullptr) { UE_LOG(EZOnline, Error, TEXT("Game Instance Must be set to EZOnlineGameInstance") ); return; } webSocket->OnClosed.AddDynamic(this, &AEZClientGameMode::OnSocketClosed); webSocket->OnConnectError.AddDynamic(this, &AEZClientGameMode::OnSocketConnectFail); webSocket->OnConnectComplete.AddDynamic(this, &AEZClientGameMode::OnSocketConnected); pEzGameInstance->SetCenterSocket(webSocket); } void AEZClientGameMode::OnSocketConnected() { K2OnSocketConnected(); } void AEZClientGameMode::OnSocketClosed() { K2OnSocketClosed(); } void AEZClientGameMode::OnSocketConnectFail(const FString& error) { K2OnSocketConnectFail(); } void AEZClientGameMode::GotoDefaultMap() { FString Error; FURL DefaultURL; DefaultURL.LoadURLConfig(TEXT("DefaultPlayer"), GGameIni); const UGameMapsSettings* GameMapsSettings = GetDefault<UGameMapsSettings>(); const FString& TextURL = GameMapsSettings->GetGameDefaultMap() + GameMapsSettings->LocalMapOptions; UGameplayStatics::OpenLevel(this, UKismetStringLibrary::Conv_StringToName(GameMapsSettings->GetGameDefaultMap() ), true); }
31.421875
148
0.785182
feixuwu
709f2fddada471c05939ae742c729c996ff40dd3
6,703
cpp
C++
toonz/sources/toonz/celldata.cpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
3,710
2016-03-26T00:40:48.000Z
2022-03-31T21:35:12.000Z
toonz/sources/toonz/celldata.cpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
4,246
2016-03-26T01:21:45.000Z
2022-03-31T23:10:47.000Z
toonz/sources/toonz/celldata.cpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
633
2016-03-26T00:42:25.000Z
2022-03-17T02:55:13.000Z
#include "celldata.h" #include <assert.h> #include "toonz/txsheet.h" #include "toonz/txshcolumn.h" #include "toonz/txshleveltypes.h" #include "toonz/txshzeraryfxcolumn.h" #include "toonz/txshzeraryfxlevel.h" #include "toonz/tcolumnfx.h" #include "toonz/fxdag.h" #include "toonz/txshlevelcolumn.h" //----------------------------------------------------------------------------- TCellData::TCellData() : m_rowCount(0), m_colCount(0) {} //----------------------------------------------------------------------------- TCellData::TCellData(const TCellData *src) : m_cells(src->m_cells) , m_rowCount(src->m_rowCount) , m_colCount(src->m_colCount) {} //----------------------------------------------------------------------------- TCellData::~TCellData() {} //----------------------------------------------------------------------------- const TXshCell TCellData::getCell(int row, int col) const { assert(0 <= row && row < m_rowCount); assert(0 <= col && col < m_colCount); return m_cells[row + col * m_rowCount]; } //----------------------------------------------------------------------------- // data <- xsh void TCellData::setCells(TXsheet *xsh, int r0, int c0, int r1, int c1) { assert(r0 <= r1 && c0 <= c1); m_rowCount = r1 - r0 + 1; m_colCount = c1 - c0 + 1; assert(m_rowCount > 0); assert(m_colCount > 0); m_cells.clear(); m_cells.resize(m_rowCount * m_colCount); int c; for (c = c0; c <= c1; c++) { int index = c - c0; TXshColumn *column = xsh->getColumn(c); if (!column || column->isEmpty()) continue; xsh->getCells(r0, c, m_rowCount, &m_cells[index * m_rowCount]); } setText("TCellData"); } //----------------------------------------------------------------------------- // data -> xsh bool TCellData::getCells(TXsheet *xsh, int r0, int c0, int &r1, int &c1, bool insert, bool doZeraryClone, bool skipEmptyCells) const { int c; r1 = r0 + m_rowCount - 1; c1 = c0 + m_colCount - 1; bool cellSet = false; for (c = c0; c < c0 + m_colCount; c++) { TXshColumn *column = xsh->getColumn(c); /*- index:選択範囲左から何番目のカラムか(一番左は0) -*/ int index = c - c0; std::vector<TXshCell> cells = m_cells; bool isColumnEmpty = true; if (column) { isColumnEmpty = column->isEmpty(); /*- 各セルに左上→右下で順に割り振られるIndex -*/ int cellIndex = index * m_rowCount; // increment the cellIndex and skip empty cells if (skipEmptyCells) { while (cellIndex < (index + 1) * m_rowCount && m_cells[cellIndex].isEmpty()) ++cellIndex; } // if the cellIndex reaches the end of the selection if ((int)m_cells.size() <= cellIndex) // Celle vuote. return cellSet; /*- カラムが変更不可なら次のカラムへ -*/ if (!canChange(column, index)) continue; } if (doZeraryClone && isColumnEmpty) cloneZeraryFx(index, cells); // inserisco le celle if (insert) xsh->insertCells(r0, c, m_rowCount); cellSet = xsh->setCells(r0, c, m_rowCount, &cells[index * m_rowCount]); } return cellSet; } //----------------------------------------------------------------------------- // Paste only cell numbers. // As a special behavior, enable to copy one column and paste into // multiple columns. bool TCellData::getNumbers(TXsheet *xsh, int r0, int c0, int &r1, int &c1) const { r1 = r0 + m_rowCount - 1; bool oneToMulti = m_colCount == 1 && c0 < c1; if (!oneToMulti) c1 = c0 + m_colCount - 1; bool cellSet = false; for (int c = c0; c <= c1; c++) { TXshColumn *column = xsh->getColumn(c); if (!column || column->isEmpty()) continue; TXshLevelColumn *levelColumn = column->getLevelColumn(); if (!levelColumn) continue; std::vector<TXshCell> cells = m_cells; int sourceColIndex = (oneToMulti) ? 0 : c - c0; int sourceCellIndex = sourceColIndex * m_rowCount; if (!canChange(column, sourceColIndex)) continue; bool isSet = levelColumn->setNumbers(r0, m_rowCount, &cells[sourceColIndex * m_rowCount]); cellSet = cellSet || isSet; } xsh->updateFrameCount(); return cellSet; } //----------------------------------------------------------------------------- /*-- c0 を起点に、TCellDataの選択範囲のカラム幅分、 全てのカラムがcanChangeかどうか調べる。 --*/ bool TCellData::canChange(TXsheet *xsh, int c0) const { int c; for (c = c0; c < c0 + m_colCount; c++) { int index = c - c0; TXshColumn *column = xsh->getColumn(c); if (!canChange(column, index)) return false; } return true; } //----------------------------------------------------------------------------- bool TCellData::canChange(TXshColumn *column, int index) const { /*- カラムが無い、又は空のときTrue(編集可) -*/ if (!column || column->isEmpty()) return true; /*- カラムがロックされていたらFalse(編集不可) -*/ if (column->isLocked()) return false; /*-- 全てのセルがcanSetCellかどうか調べる 今からペーストするセルが、 ペースト先のカラムと同種ならばtrueとなる。 --*/ TXshCellColumn *cellColumn = column->getCellColumn(); assert(cellColumn); int i; for (i = index * m_rowCount; i < (index * m_rowCount) + m_rowCount; i++) // for(i = 0; i < m_cells.size(); i++) if (!cellColumn->canSetCell(m_cells[i])) return false; return true; } //----------------------------------------------------------------------------- void TCellData::cloneZeraryFx(int index, std::vector<TXshCell> &cells) const { int firstNotEmptyIndex = index * m_rowCount; while (firstNotEmptyIndex < (index + 1) * m_rowCount && m_cells[firstNotEmptyIndex].isEmpty()) firstNotEmptyIndex++; if (firstNotEmptyIndex >= (index + 1) * m_rowCount) return; TXshZeraryFxLevel *fxLevel = m_cells[firstNotEmptyIndex].m_level->getZeraryFxLevel(); if (!fxLevel) return; TXshZeraryFxColumn *fxColumn = fxLevel->getColumn(); assert(fxColumn); TFx *zeraryFx = fxColumn->getZeraryColumnFx()->getZeraryFx(); if (zeraryFx) { std::wstring fxName = zeraryFx->getName(); TFx *newZeraryFx = zeraryFx->clone(false); fxColumn->getXsheet()->getFxDag()->assignUniqueId(newZeraryFx); newZeraryFx->setName(fxName); newZeraryFx->linkParams(zeraryFx); TXshZeraryFxLevel *newFxLevel = new TXshZeraryFxLevel(); TXshZeraryFxColumn *newFxColumn = new TXshZeraryFxColumn(0); newFxColumn->getZeraryColumnFx()->setZeraryFx(newZeraryFx); newFxLevel->setColumn(newFxColumn); // replace the zerary fx cells by the new fx int r; for (r = firstNotEmptyIndex; r < (index + 1) * m_rowCount; r++) cells[r] = TXshCell(newFxLevel, m_cells[r].getFrameId()); } }
33.348259
79
0.556616
rozhuk-im
709f36bc42bf51e90025683787cb7c19e928c65c
285
cpp
C++
fill/fill.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
1
2018-07-23T21:15:11.000Z
2018-07-23T21:15:11.000Z
fill/fill.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
null
null
null
fill/fill.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
3
2018-11-10T05:39:00.000Z
2019-12-08T12:14:19.000Z
#include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; std::fill(v.begin(), v.end(), 7); std::copy(v.begin(), v.end(), std::ostream_iterator<int>{ std::cout, " " }); return 0; }
20.357143
80
0.561404
danielkrupinski
70a2eaba47fee120665b177611f131b9784439c6
30,396
hpp
C++
vdf_parser.hpp
clayne/ValveFileVDF
808be2cd3fc3df6260752f9097aa2731b996f050
[ "MIT" ]
40
2016-11-13T16:26:53.000Z
2022-03-11T11:43:05.000Z
vdf_parser.hpp
clayne/ValveFileVDF
808be2cd3fc3df6260752f9097aa2731b996f050
[ "MIT" ]
10
2017-03-29T20:49:13.000Z
2020-07-15T16:02:36.000Z
vdf_parser.hpp
clayne/ValveFileVDF
808be2cd3fc3df6260752f9097aa2731b996f050
[ "MIT" ]
7
2018-01-04T07:15:07.000Z
2022-03-07T17:26:56.000Z
//MIT License // //Copyright(c) 2016 Matthias Moeller // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files(the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and / or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions : // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #ifndef __TYTI_STEAM_VDF_PARSER_H__ #define __TYTI_STEAM_VDF_PARSER_H__ #include <map> #include <vector> #include <unordered_map> #include <utility> #include <fstream> #include <memory> #include <unordered_set> #include <algorithm> #include <iterator> #include <functional> #include <system_error> #include <exception> //for wstring support #include <locale> #include <string> // internal #include <stack> //VS < 2015 has only partial C++11 support #if defined(_MSC_VER) && _MSC_VER < 1900 #ifndef CONSTEXPR #define CONSTEXPR #endif #ifndef NOEXCEPT #define NOEXCEPT #endif #else #ifndef CONSTEXPR #define CONSTEXPR constexpr #define TYTI_UNDEF_CONSTEXPR #endif #ifndef NOEXCEPT #define NOEXCEPT noexcept #define TYTI_UNDEF_NOEXCEPT #endif #endif namespace tyti { namespace vdf { namespace detail { /////////////////////////////////////////////////////////////////////////// // Helper functions selecting the right encoding (char/wchar_T) /////////////////////////////////////////////////////////////////////////// template <typename T> struct literal_macro_help { static CONSTEXPR const char *result(const char *c, const wchar_t *) NOEXCEPT { return c; } static CONSTEXPR const char result(const char c, const wchar_t) NOEXCEPT { return c; } }; template <> struct literal_macro_help<wchar_t> { static CONSTEXPR const wchar_t *result(const char *, const wchar_t *wc) NOEXCEPT { return wc; } static CONSTEXPR const wchar_t result(const char, const wchar_t wc) NOEXCEPT { return wc; } }; #define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text) inline std::string string_converter(const std::string &w) NOEXCEPT { return w; } // utility wrapper to adapt locale-bound facets for wstring/wbuffer convert // from cppreference template <class Facet> struct deletable_facet : Facet { template <class... Args> deletable_facet(Args &&... args) : Facet(std::forward<Args>(args)...) {} ~deletable_facet() {} }; inline std::string string_converter(const std::wstring &w) //todo: use us-locale { std::wstring_convert<deletable_facet<std::codecvt<wchar_t, char, std::mbstate_t>>> conv1; return conv1.to_bytes(w); } /////////////////////////////////////////////////////////////////////////// // Writer helper functions /////////////////////////////////////////////////////////////////////////// template <typename charT> class tabs { const size_t t; public: explicit CONSTEXPR tabs(size_t i) NOEXCEPT : t(i) {} std::basic_string<charT> print() const { return std::basic_string<charT>(t, TYTI_L(charT, '\t')); } inline CONSTEXPR tabs operator+(size_t i) const NOEXCEPT { return tabs(t + i); } }; template <typename oStreamT> oStreamT &operator<<(oStreamT &s, const tabs<typename oStreamT::char_type> t) { s << t.print(); return s; } } // end namespace detail /////////////////////////////////////////////////////////////////////////// // Interface /////////////////////////////////////////////////////////////////////////// /// custom objects and their corresponding write functions /// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens template <typename CharT> struct basic_object { typedef CharT char_type; std::basic_string<char_type> name; std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type>> attribs; std::unordered_map<std::basic_string<char_type>, std::shared_ptr<basic_object<char_type>>> childs; void add_attribute(std::basic_string<char_type> key, std::basic_string<char_type> value) { attribs.emplace(std::move(key), std::move(value)); } void add_child(std::unique_ptr<basic_object<char_type>> child) { std::shared_ptr<basic_object<char_type>> obj{child.release()}; childs.emplace(obj->name, obj); } void set_name(std::basic_string<char_type> n) { name = std::move(n); } }; template <typename CharT> struct basic_multikey_object { typedef CharT char_type; std::basic_string<char_type> name; std::unordered_multimap<std::basic_string<char_type>, std::basic_string<char_type>> attribs; std::unordered_multimap<std::basic_string<char_type>, std::shared_ptr<basic_multikey_object<char_type>>> childs; void add_attribute(std::basic_string<char_type> key, std::basic_string<char_type> value) { attribs.emplace(std::move(key), std::move(value)); } void add_child(std::unique_ptr<basic_multikey_object<char_type>> child) { std::shared_ptr<basic_multikey_object<char_type>> obj{child.release()}; childs.emplace(obj->name, obj); } void set_name(std::basic_string<char_type> n) { name = std::move(n); } }; typedef basic_object<char> object; typedef basic_object<wchar_t> wobject; typedef basic_multikey_object<char> multikey_object; typedef basic_multikey_object<wchar_t> wmultikey_object; struct Options { bool strip_escape_symbols; bool ignore_all_platform_conditionals; bool ignore_includes; Options() : strip_escape_symbols(true), ignore_all_platform_conditionals(false), ignore_includes(false) {} }; //forward decls //forward decl template <typename OutputT, typename iStreamT> OutputT read(iStreamT &inStream, const Options &opt = Options{}); /** \brief writes given object tree in vdf format to given stream. Output is prettyfied, using tabs */ template <typename oStreamT, typename T> void write(oStreamT &s, const T &r, const detail::tabs<typename oStreamT::char_type> tab = detail::tabs<typename oStreamT::char_type>(0)) { typedef typename oStreamT::char_type charT; using namespace detail; s << tab << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tab << TYTI_L(charT, "{\n"); for (const auto &i : r.attribs) s << tab + 1 << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n"); for (const auto &i : r.childs) if (i.second) write(s, *i.second, tab + 1); s << tab << TYTI_L(charT, "}\n"); } namespace detail { template <typename iStreamT> std::basic_string<typename iStreamT::char_type> read_file(iStreamT &inStream) { // cache the file typedef typename iStreamT::char_type charT; std::basic_string<charT> str; inStream.seekg(0, std::ios::end); str.resize(static_cast<size_t>(inStream.tellg())); if (str.empty()) return str; inStream.seekg(0, std::ios::beg); inStream.read(&str[0], str.size()); return str; } /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param exclude_files list of files which cant be included anymore. prevents circular includes can thow: - "std::runtime_error" if a parsing error occured - "std::bad_alloc" if not enough memory coup be allocated */ template <typename OutputT, typename IterT> std::vector<std::unique_ptr<OutputT>> read_internal(IterT first, const IterT last, std::unordered_set<std::basic_string<typename std::iterator_traits<IterT>::value_type>> &exclude_files, const Options &opt) { static_assert(std::is_default_constructible<OutputT>::value, "Output Type must be default constructible (provide constructor without arguments)"); static_assert(std::is_move_constructible<OutputT>::value, "Output Type must be move constructible"); typedef typename std::iterator_traits<IterT>::value_type charT; const std::basic_string<charT> comment_end_str = TYTI_L(charT, "*/"); const std::basic_string<charT> whitespaces = TYTI_L(charT, " \n\v\f\r\t"); #ifdef WIN32 std::function<bool(const std::basic_string<charT> &)> is_platform_str = [](const std::basic_string<charT> &in) { return in == TYTI_L(charT, "$WIN32") || in == TYTI_L(charT, "$WINDOWS"); }; #elif __APPLE__ // WIN32 stands for pc in general std::function<bool(const std::basic_string<charT> &)> is_platform_str = [](const std::basic_string<charT> &in) { return in == TYTI_L(charT, "$WIN32") || in == TYTI_L(charT, "$POSIX") || in == TYTI_L(charT, "$OSX"); }; #elif __linux__ // WIN32 stands for pc in general std::function<bool(const std::basic_string<charT> &)> is_platform_str = [](const std::basic_string<charT> &in) { return in == TYTI_L(charT, "$WIN32") || in == TYTI_L(charT, "$POSIX") || in == TYTI_L(charT, "$LINUX"); }; #else std::function<bool(const std::basic_string<charT> &)> is_platform_str = [](const std::basic_string<charT> &in) { return false; }; #endif if (opt.ignore_all_platform_conditionals) is_platform_str = [](const std::basic_string<charT> &) { return false; }; // function for skipping a comment block // iter: iterator poition to the position after a '/' auto skip_comments = [&comment_end_str](IterT iter, const IterT &last) -> IterT { ++iter; if (iter != last) { if (*iter == TYTI_L(charT, '/')) { // line comment, skip whole line iter = std::find(iter + 1, last, TYTI_L(charT, '\n')); } if (*iter == '*') { // block comment, skip until next occurance of "*\" iter = std::search(iter + 1, last, std::begin(comment_end_str), std::end(comment_end_str)); iter += 2; } } return iter; }; auto end_quote = [](IterT iter, const IterT &last) -> IterT { const auto begin = iter; auto last_esc = iter; do { ++iter; iter = std::find(iter, last, TYTI_L(charT, '\"')); if (iter == last) break; last_esc = std::prev(iter); while (last_esc != begin && *last_esc == '\\') --last_esc; } while (!(std::distance(last_esc, iter) % 2)); if (iter == last) throw std::runtime_error{"quote was opened but not closed."}; return iter; }; auto end_word = [&whitespaces](IterT iter, const IterT &last) -> IterT { const auto begin = iter; auto last_esc = iter; do { ++iter; iter = std::find_first_of(iter, last, std::begin(whitespaces), std::end(whitespaces)); if (iter == last) break; last_esc = std::prev(iter); while (last_esc != begin && *last_esc == '\\') --last_esc; } while (!(std::distance(last_esc, iter) % 2)); //if (iter == last) // throw std::runtime_error{ "word wasnt properly ended" }; return iter; }; auto skip_whitespaces = [&whitespaces](IterT iter, const IterT &last) -> IterT { iter = std::find_if_not(iter, last, [&whitespaces](charT c) { // return true if whitespace return std::any_of(std::begin(whitespaces), std::end(whitespaces), [c](charT pc) { return pc == c; }); }); return iter; }; std::function<void(std::basic_string<charT> &)> strip_escape_symbols = [](std::basic_string<charT> &s) { auto quote_searcher = [&s](size_t pos) { return s.find(TYTI_L(charT, "\\\""), pos); }; auto p = quote_searcher(0); while (p != s.npos) { s.replace(p, 2, TYTI_L(charT, "\"")); p = quote_searcher(p); } auto searcher = [&s](size_t pos) { return s.find(TYTI_L(charT, "\\\\"), pos); }; p = searcher(0); while (p != s.npos) { s.replace(p, 2, TYTI_L(charT, "\\")); p = searcher(p); } }; if (!opt.strip_escape_symbols) strip_escape_symbols = [](std::basic_string<charT> &) {}; auto conditional_fullfilled = [&skip_whitespaces, &is_platform_str](IterT &iter, const IterT &last) { iter = skip_whitespaces(iter, last); if (*iter == '[') { ++iter; const auto end = std::find(iter, last, ']'); const bool negate = *iter == '!'; if (negate) ++iter; auto conditional = std::basic_string<charT>(iter, end); const bool is_platform = is_platform_str(conditional); iter = end + 1; return static_cast<bool>(is_platform ^ negate); } return true; }; //read header // first, quoted name std::unique_ptr<OutputT> curObj = nullptr; std::vector<std::unique_ptr<OutputT>> roots; std::stack<std::unique_ptr<OutputT>> lvls; auto curIter = first; while (curIter != last && *curIter != '\0') { //find first starting attrib/child, or ending curIter = skip_whitespaces(curIter, last); if (curIter == last || *curIter == '\0') break; if (*curIter == TYTI_L(charT, '/')) { curIter = skip_comments(curIter, last); } else if (*curIter != TYTI_L(charT, '}')) { // get key const auto keyEnd = (*curIter == TYTI_L(charT, '\"')) ? end_quote(curIter, last) : end_word(curIter, last); if (*curIter == TYTI_L(charT, '\"')) ++curIter; std::basic_string<charT> key(curIter, keyEnd); strip_escape_symbols(key); curIter = keyEnd + ((*keyEnd == TYTI_L(charT, '\"')) ? 1 : 0); curIter = skip_whitespaces(curIter, last); auto conditional = conditional_fullfilled(curIter, last); if (!conditional) continue; while (*curIter == TYTI_L(charT, '/')) { curIter = skip_comments(curIter, last); if (curIter == last || *curIter == '}') throw std::runtime_error{"key declared, but no value"}; curIter = skip_whitespaces(curIter, last); if (curIter == last || *curIter == '}') throw std::runtime_error{"key declared, but no value"}; } // get value if (*curIter != '{') { const auto valueEnd = (*curIter == TYTI_L(charT, '\"')) ? end_quote(curIter, last) : end_word(curIter, last); if (*curIter == TYTI_L(charT, '\"')) ++curIter; auto value = std::basic_string<charT>(curIter, valueEnd); strip_escape_symbols(value); curIter = valueEnd + ((*valueEnd == TYTI_L(charT, '\"')) ? 1 : 0); auto conditional = conditional_fullfilled(curIter, last); if (!conditional) continue; // process value if (key != TYTI_L(charT, "#include") && key != TYTI_L(charT, "#base")) { curObj->add_attribute(std::move(key), std::move(value)); } else { if (!opt.ignore_includes && exclude_files.find(value) == exclude_files.end()) { exclude_files.insert(value); std::basic_ifstream<charT> i(detail::string_converter(value)); auto str = read_file(i); auto file_objs = read_internal<OutputT>(str.begin(), str.end(), exclude_files, opt); for (auto &n : file_objs) { if (curObj) curObj->add_child(std::move(n)); else roots.push_back(std::move(n)); } exclude_files.erase(value); } } } else if (*curIter == '{') { if (curObj) lvls.push(std::move(curObj)); curObj = std::make_unique<OutputT>(); curObj->set_name(std::move(key)); ++curIter; } } //end of new object else if (*curIter == TYTI_L(charT, '}')) { if (!lvls.empty()) { //get object before std::unique_ptr<OutputT> prev{std::move(lvls.top())}; lvls.pop(); // add finished obj to obj before and release it from processing prev->add_child(std::move(curObj)); curObj = std::move(prev); } else { roots.push_back(std::move(curObj)); curObj.reset(); } ++curIter; } } return roots; } } // namespace detail /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator can thow: - "std::runtime_error" if a parsing error occured - "std::bad_alloc" if not enough memory coup be allocated */ template <typename OutputT, typename IterT> OutputT read(IterT first, const IterT last, const Options &opt = Options{}) { auto exclude_files = std::unordered_set<std::basic_string<typename std::iterator_traits<IterT>::value_type>>{}; auto roots = detail::read_internal<OutputT>(first, last, exclude_files, opt); OutputT result; if (roots.size() > 1) { for (auto &i : roots) result.add_child(std::move(i)); } else if (roots.size() == 1) result = std::move(*roots[0]); return result; } /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ec output bool. 0 if ok, otherwise, holds an system error code Possible error codes: std::errc::protocol_error: file is mailformatted std::errc::not_enough_memory: not enough space std::errc::invalid_argument: iterators throws e.g. out of range */ template <typename OutputT, typename IterT> OutputT read(IterT first, IterT last, std::error_code &ec, const Options &opt = Options{}) NOEXCEPT { ec.clear(); OutputT r{}; try { r = read<OutputT>(first, last, opt); } catch (std::runtime_error &) { ec = std::make_error_code(std::errc::protocol_error); } catch (std::bad_alloc &) { ec = std::make_error_code(std::errc::not_enough_memory); } catch (...) { ec = std::make_error_code(std::errc::invalid_argument); } return r; } /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ok output bool. true, if parser successed, false, if parser failed */ template <typename OutputT, typename IterT> OutputT read(IterT first, const IterT last, bool *ok, const Options &opt = Options{}) NOEXCEPT { std::error_code ec; auto r = read<OutputT>(first, last, ec, opt); if (ok) *ok = !ec; return r; } template <typename IterT> inline auto read(IterT first, const IterT last, bool *ok, const Options &opt = Options{}) NOEXCEPT -> basic_object<typename std::iterator_traits<IterT>::value_type> { return read<basic_object<typename std::iterator_traits<IterT>::value_type>>(first, last, ok, opt); } template <typename IterT> inline auto read(IterT first, IterT last, std::error_code &ec, const Options &opt = Options{}) NOEXCEPT -> basic_object<typename std::iterator_traits<IterT>::value_type> { return read<basic_object<typename std::iterator_traits<IterT>::value_type>>(first, last, ec, opt); } template <typename IterT> inline auto read(IterT first, const IterT last, const Options &opt = Options{}) -> basic_object<typename std::iterator_traits<IterT>::value_type> { return read<basic_object<typename std::iterator_traits<IterT>::value_type>>(first, last, opt); } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated */ template <typename OutputT, typename iStreamT> OutputT read(iStreamT &inStream, std::error_code &ec, const Options &opt = Options{}) { // cache the file typedef typename iStreamT::char_type charT; std::basic_string<charT> str = detail::read_file(inStream); // parse it return read<OutputT>(str.begin(), str.end(), ec, opt); } template <typename iStreamT> inline basic_object<typename iStreamT::char_type> read(iStreamT &inStream, std::error_code &ec, const Options &opt = Options{}) { return read<basic_object<typename iStreamT::char_type>>(inStream, ec, opt); } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated ok == false, if a parsing error occured */ template <typename OutputT, typename iStreamT> OutputT read(iStreamT &inStream, bool *ok, const Options &opt = Options{}) { std::error_code ec; const auto r = read<OutputT>(inStream, ec, opt); if (ok) *ok = !ec; return r; } template <typename iStreamT> inline basic_object<typename iStreamT::char_type> read(iStreamT &inStream, bool *ok, const Options &opt = Options{}) { return read<basic_object<typename iStreamT::char_type>>(inStream, ok, opt); } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated throws "std::runtime_error" if a parsing error occured */ template <typename OutputT, typename iStreamT> OutputT read(iStreamT &inStream, const Options &opt) { // cache the file typedef typename iStreamT::char_type charT; std::basic_string<charT> str = detail::read_file(inStream); // parse it return read<OutputT>(str.begin(), str.end(), opt); } template <typename iStreamT> inline basic_object<typename iStreamT::char_type> read(iStreamT &inStream, const Options &opt = Options{}) { return read<basic_object<typename iStreamT::char_type>>(inStream, opt); } } // namespace vdf } // namespace tyti #ifndef TYTI_NO_L_UNDEF #undef TYTI_L #endif #ifdef TYTI_UNDEF_CONSTEXPR #undef CONSTEXPR #undef TYTI_NO_L_UNDEF #endif #ifdef TYTI_UNDEF_NOTHROW #undef NOTHROW #undef TYTI_UNDEF_NOTHROW #endif #endif //__TYTI_STEAM_VDF_PARSER_H__
42.511888
173
0.480228
clayne
70a38e2f5f52c64545cf98c624c73b4b89889789
4,723
cc
C++
content/browser/loader/certificate_resource_handler.cc
leiferikb/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-15T15:17:43.000Z
2021-11-15T15:17:43.000Z
content/browser/loader/certificate_resource_handler.cc
leiferikb/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/loader/certificate_resource_handler.cc
leiferikb/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-02-21T16:13:42.000Z
2019-02-21T16:13:42.000Z
// Copyright (c) 2012 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 "content/browser/loader/certificate_resource_handler.h" #include "base/string_util.h" #include "content/browser/loader/resource_request_info_impl.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/resource_response.h" #include "net/base/io_buffer.h" #include "net/base/mime_sniffer.h" #include "net/base/mime_util.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" namespace content { CertificateResourceHandler::CertificateResourceHandler( net::URLRequest* request, int render_process_host_id, int render_view_id) : request_(request), content_length_(0), read_buffer_(NULL), resource_buffer_(NULL), render_process_host_id_(render_process_host_id), render_view_id_(render_view_id), cert_type_(net::CERTIFICATE_MIME_TYPE_UNKNOWN) { } CertificateResourceHandler::~CertificateResourceHandler() { } bool CertificateResourceHandler::OnUploadProgress(int request_id, uint64 position, uint64 size) { return true; } bool CertificateResourceHandler::OnRequestRedirected(int request_id, const GURL& url, ResourceResponse* resp, bool* defer) { url_ = url; return true; } bool CertificateResourceHandler::OnResponseStarted(int request_id, ResourceResponse* resp, bool* defer) { cert_type_ = net::GetCertificateMimeTypeForMimeType(resp->head.mime_type); return cert_type_ != net::CERTIFICATE_MIME_TYPE_UNKNOWN; } bool CertificateResourceHandler::OnWillStart(int request_id, const GURL& url, bool* defer) { return true; } bool CertificateResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, int min_size) { static const int kReadBufSize = 32768; // TODO(gauravsh): Should we use 'min_size' here? DCHECK(buf && buf_size); if (!read_buffer_) { read_buffer_ = new net::IOBuffer(kReadBufSize); } *buf = read_buffer_.get(); *buf_size = kReadBufSize; return true; } bool CertificateResourceHandler::OnReadCompleted(int request_id, int bytes_read, bool* defer) { if (!bytes_read) return true; // We have more data to read. DCHECK(read_buffer_); content_length_ += bytes_read; // Release the ownership of the buffer, and store a reference // to it. A new one will be allocated in OnWillRead(). net::IOBuffer* buffer = NULL; read_buffer_.swap(&buffer); // TODO(gauravsh): Should this be handled by a separate thread? buffer_.push_back(std::make_pair(buffer, bytes_read)); return true; } bool CertificateResourceHandler::OnResponseCompleted( int request_id, const net::URLRequestStatus& urs, const std::string& sec_info) { if (urs.status() != net::URLRequestStatus::SUCCESS) return false; AssembleResource(); const void* content_bytes = NULL; if (resource_buffer_) content_bytes = resource_buffer_->data(); // Note that it's up to the browser to verify that the certificate // data is well-formed. GetContentClient()->browser()->AddCertificate( request_, cert_type_, content_bytes, content_length_, render_process_host_id_, render_view_id_); return true; } void CertificateResourceHandler::AssembleResource() { // 0-length IOBuffers are not allowed. if (content_length_ == 0) { resource_buffer_ = NULL; return; } // Create the new buffer. resource_buffer_ = new net::IOBuffer(content_length_); // Copy the data into it. size_t bytes_copied = 0; for (size_t i = 0; i < buffer_.size(); ++i) { net::IOBuffer* data = buffer_[i].first; size_t data_len = buffer_[i].second; DCHECK(data != NULL); DCHECK_LE(bytes_copied + data_len, content_length_); memcpy(resource_buffer_->data() + bytes_copied, data->data(), data_len); bytes_copied += data_len; } DCHECK_EQ(content_length_, bytes_copied); } } // namespace content
32.349315
76
0.635189
leiferikb
70a5e20183ae21e5347c1a9c8eb151fe0315a897
493
cpp
C++
src/use_protobuf/main.cpp
cwj5012/game_kit
587f55e6aa29fac3ef6b4649c7499f53e7b4829c
[ "MIT" ]
null
null
null
src/use_protobuf/main.cpp
cwj5012/game_kit
587f55e6aa29fac3ef6b4649c7499f53e7b4829c
[ "MIT" ]
null
null
null
src/use_protobuf/main.cpp
cwj5012/game_kit
587f55e6aa29fac3ef6b4649c7499f53e7b4829c
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <windows.h> #include "msg.pb.h" int main(int argc, char* argv[]) { Person john; john.set_id(1234); john.set_name("John Doe"); john.set_email("jdoe@example.com"); std::cout << john.DebugString() << std::endl; Person john_copy; john_copy.set_id(john.id()); john_copy.set_name(john.name()); john_copy.set_email(john.email()); std::cout << john_copy.DebugString() << std::endl; //john.SerializeToString(); Sleep(3000); return 0; }
18.961538
51
0.681542
cwj5012
70a7d56261053f4d3f2993e1599fd0dbf3a45150
451
cpp
C++
doc/examples/operatorarray__size_type.cpp
Hexlord/json
66869458b5227170e052d01aa65b47ee8350b666
[ "MIT" ]
23
2016-01-20T07:50:24.000Z
2021-09-08T05:08:19.000Z
json-master/doc/examples/operatorarray__size_type.cpp
bobismijnnaam/bobetex
9960eafd31c73b4070b236d5dfafd5734492aaf5
[ "MIT" ]
18
2016-06-01T11:56:54.000Z
2016-06-06T10:58:53.000Z
json-master/doc/examples/operatorarray__size_type.cpp
bobismijnnaam/bobetex
9960eafd31c73b4070b236d5dfafd5734492aaf5
[ "MIT" ]
19
2016-01-24T13:05:24.000Z
2021-06-25T01:36:47.000Z
#include <json.hpp> using namespace nlohmann; int main() { // create a JSON array json array = {1, 2, 3, 4, 5}; // output element at index 3 (fourth element) std::cout << array[3] << '\n'; // change last element to 6 array[array.size() - 1] = 6; // output changed array std::cout << array << '\n'; // write beyond array limit array[10] = 11; // output changed array std::cout << array << '\n'; }
18.04
49
0.552106
Hexlord
70a7f4f9db517de7493efed62f334f85b9b71355
16,517
cpp
C++
src/dagified_graph.cpp
lnceballosz/vg
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
[ "MIT" ]
null
null
null
src/dagified_graph.cpp
lnceballosz/vg
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
[ "MIT" ]
null
null
null
src/dagified_graph.cpp
lnceballosz/vg
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
[ "MIT" ]
null
null
null
// SPDX-FileCopyrightText: 2014 Erik Garrison // // SPDX-License-Identifier: MIT /** * \file dagified_graph.cpp: contains the implementation of DagifiedGraph */ #include "dagified_graph.hpp" //#define debug_dagify namespace vg { using namespace std; DagifiedGraph::DagifiedGraph(const HandleGraph* graph, size_t min_preserved_path_length) : graph(graph) { // find the numeric range of handles in the underlying graph (needed for later bookkeeping) uint64_t max_handle = std::numeric_limits<uint64_t>::min(); graph->for_each_handle([&](const handle_t& handle) { for (handle_t h : {handle, graph->flip(handle)}) { uint64_t integer_handle = handlegraph::as_integer(h); min_handle = min(integer_handle, min_handle); max_handle = max(integer_handle, max_handle); } }); handle_val_range = max_handle - min_handle + 1; // now we begin the dagify algorithm vector<vector<handle_t>> strong_components; { // get a low-FAS layout with a canonical orientation for each handle vector<handle_t> layout = handlealgs::eades_algorithm(graph); // invert the mapping for the layout layout_order.reserve(layout.size()); for (size_t i = 0; i < layout.size(); ++i) { layout_order[layout[i]] = i; } // identify the SCCs and build the reverse SCC mapping // TODO: annoying that we have to work with this return type for strongly_connected_components scc_of_handle.resize(layout.size()); size_t scc_idx = 0; for (const unordered_set<id_t>& scc : handlealgs::strongly_connected_components(graph)) { // init new component strong_components.emplace_back(); auto& component = strong_components.back(); component.reserve(scc.size()); // build the reverse mapping for this SCC for (const id_t& node_id : scc) { handle_t handle = graph->get_handle(node_id); auto iter = layout_order.find(handle); if (iter == layout_order.end()) { iter = layout_order.find(graph->flip(handle)); } scc_of_handle[iter->second] = scc_idx; } ++scc_idx; } // build the SCC components in layout order for (const handle_t& handle : layout) { strong_components[scc_of_handle[layout_order[handle]]].push_back(handle); } // let the layout fall out of scope } // identify how many times each SCC needs to be duplicated scc_copy_count.resize(strong_components.size()); for (size_t scc_idx = 0; scc_idx < strong_components.size(); ++scc_idx) { const vector<handle_t>& component = strong_components[scc_idx]; // record the ordering of the layout so we can build adjacency lists unordered_map<handle_t, size_t> ordering; for (size_t i = 0; i < component.size(); i++) { ordering[component[i]] = i; } // mark the edges as either forward or backward relative to the layout vector<vector<size_t>> forward_edges(component.size()); vector<pair<size_t, size_t>> backward_edges; for (size_t i = 0; i < component.size(); ++i) { graph->follow_edges(component[i], false, [&](const handle_t& next) { if (scc_of_handle[layout_order[next]] == scc_idx) { // this edge is internal to a strongly connected component size_t j = ordering[next]; if (i < j) { // non feedback arc forward_edges[i].push_back(j); } else { // feedback arc backward_edges.emplace_back(i, j); } } }); } // check for each node whether we've duplicated the component enough times // to preserve its cycles // dynamic progamming structures that represent distances within the current // copy of the SCC and the next copy vector<int64_t> distances(component.size(), numeric_limits<int64_t>::max()); // init the distances so that we are measuring from the end of the heads of // backward edges (which cross to the next copy of the SCC) for (const pair<size_t, size_t>& bwd_edge : backward_edges) { handle_t handle = component[bwd_edge.first]; distances[ordering[handle]] = -graph->get_length(handle); } // init the tracker that we use for the bail-out condition int64_t min_relaxed_dist = -1; // keep track of how many times we've implicitly copied uint64_t copy_num = 0; for (; min_relaxed_dist < int64_t(min_preserved_path_length); copy_num++) { // the distances in the next copy unit vector<int64_t> next_distances(component.size(), numeric_limits<int64_t>::max()); // find the shortest path to the nodes, staying within this copy of the SCC for (size_t i = 0; i < distances.size(); i++) { // skip infinity to avoid overflow if (distances[i] == numeric_limits<int64_t>::max()) { continue; } int64_t dist_thru = distances[i] + graph->get_length(component[i]); for (const size_t& j : forward_edges[i]) { distances[j] = min(distances[j], dist_thru); } } // now find the minimum distance to nodes in the next copy of the SCC min_relaxed_dist = numeric_limits<int64_t>::max(); for (const pair<size_t, size_t>& bwd_edge : backward_edges) { // skip infinity to avoid overflow if (distances[bwd_edge.first] == numeric_limits<int64_t>::max()) { continue; } int64_t dist_thru = distances[bwd_edge.first] + graph->get_length(component[bwd_edge.first]); if (dist_thru < next_distances[bwd_edge.second]) { next_distances[bwd_edge.second] = dist_thru; // keep track of the shortest distance to the next copy min_relaxed_dist = min(min_relaxed_dist, dist_thru); } } #ifdef debug_dagify cerr << "distances within component" << endl; for (size_t i = 0; i < distances.size(); i++) { cerr << "\t" << graph->get_id(component[i]) << (graph->get_is_reverse(component[i]) ? "-" : "+") << " " << distances[i] << endl; } cerr << "distances to next component" << endl; for (size_t i = 0; i < next_distances.size(); i++) { cerr << "\t" << graph->get_id(component[i]) << (graph->get_is_reverse(component[i]) ? "-" : "+") << " " << next_distances[i] << endl; } #endif // initialize the DP structures for the next iteration distances = move(next_distances); } // now we know that the copy count needs to be, so we can record the information we need // from this component // record the copy count scc_copy_count[scc_idx] = copy_num; // add the number of nodes to the total count node_count += component.size() * copy_num; // find the maximum projected node ID in this component id_t comp_max_id = numeric_limits<id_t>::min(); for (const handle_t& handle : component) { comp_max_id = max(comp_max_id, graph->get_id(handle)); } max_id = max<id_t>(max_id, comp_max_id + (copy_num - 1) * (graph->max_node_id() - graph->min_node_id() + 1)); } } bool DagifiedGraph::has_node(id_t node_id) const { id_t original_id = get_underlying_id(node_id); bool exists = graph->has_node(original_id); if (exists) { // was the node duplicated enough times to have created this node ID? exists = scc_copy_of_node_id(node_id) < scc_copy_count.at(scc_of_handle.at(layout_order_of_handle(graph->get_handle(original_id)))); } return exists; } handle_t DagifiedGraph::get_handle(const id_t& node_id, bool is_reverse) const { return nth_copy_of_handle(graph->get_handle(get_underlying_id(node_id), is_reverse), scc_copy_of_node_id(node_id)); } id_t DagifiedGraph::get_id(const handle_t& handle) const { return (graph->get_id(get_underlying_handle(handle)) + scc_copy_of_handle(handle) * (graph->max_node_id() - graph->min_node_id() + 1)); } bool DagifiedGraph::get_is_reverse(const handle_t& handle) const { return graph->get_is_reverse(get_underlying_handle(handle)); } handle_t DagifiedGraph::flip(const handle_t& handle) const { return nth_copy_of_handle(graph->flip(get_underlying_handle(handle)), scc_copy_of_handle(handle)); } size_t DagifiedGraph::get_length(const handle_t& handle) const { return graph->get_length(get_underlying_handle(handle)); } string DagifiedGraph::get_sequence(const handle_t& handle) const { return graph->get_sequence(get_underlying_handle(handle)); } bool DagifiedGraph::follow_edges_impl(const handle_t& handle, bool go_left, const function<bool(const handle_t&)>& iteratee) const { // this is the complicated part where we have to induce an edge structure that is a DAG handle_t underlying = get_underlying_handle(handle); uint64_t scc_copy = scc_copy_of_handle(handle); // does the handle match the canonical orientation of the layout we computed? bool matches_layout = layout_order.count(underlying); // are we traversing this node forward along the canonical orientation? bool canonical_fwd = matches_layout != go_left; size_t layout_index = layout_order_of_handle(underlying); uint64_t scc_id = scc_of_handle.at(layout_index); return graph->follow_edges(underlying, go_left, [&](const handle_t& next_underlying) { size_t next_layout_index = layout_order_of_handle(next_underlying); uint64_t next_scc_id = scc_of_handle.at(next_layout_index); bool keep_going = true; if (next_scc_id != scc_id) { // this is over an edge that's between two strongly connected component uint64_t next_scc_count = scc_copy_count.at(next_scc_id); if (canonical_fwd) { // we are traveling in the canonically forward direction if (scc_copy + 1 == scc_copy_count.at(scc_id)) { // only the last copy of a handle is allowd to extend to the next strongly // connected component, and it connects to all copies in the next one for (size_t i = 0; i < next_scc_count && keep_going; ++i) { keep_going = iteratee(nth_copy_of_handle(next_underlying, i)); } } } else { // we are going in the reverse direction of the canonical orientation, so we // can only connect to the last copy of the next handle keep_going = iteratee(nth_copy_of_handle(next_underlying, next_scc_count - 1)); } } else { // this edge is internal to a strongly connected component if (canonical_fwd) { // we are traversing in the direction of the canonical orientation if (next_layout_index > layout_index) { // we are not taking a reversing edge, so we stay in the same copy unit keep_going = iteratee(nth_copy_of_handle(next_underlying, scc_copy)); } else if (scc_copy + 1 < scc_copy_count.at(scc_id)) { // we are taking a reversing edge, and there are still copy units ahead keep_going = iteratee(nth_copy_of_handle(next_underlying, scc_copy + 1)); } } else { // we are traversing against the direction of the canonical orientation if (next_layout_index < layout_index) { // we are moving backwards over a forward edge, stay in the same copy unit keep_going = iteratee(nth_copy_of_handle(next_underlying, scc_copy)); } else if (scc_copy > 0) { // we are moving backwards over a reversing edge, and there are still copy units before this one keep_going = iteratee(nth_copy_of_handle(next_underlying, scc_copy - 1)); } } } return keep_going; }); } bool DagifiedGraph::for_each_handle_impl(const function<bool(const handle_t&)>& iteratee, bool parallel) const { return graph->for_each_handle([&](const handle_t& underlying) { // iterate over however many copies of the handle there are size_t copy_count = scc_copy_count.at(scc_of_handle.at(layout_order_of_handle(underlying))); bool keep_going = true; for (size_t i = 0; i < copy_count && keep_going; ++i) { keep_going = iteratee(nth_copy_of_handle(underlying, i)); } return keep_going; }, parallel); } size_t DagifiedGraph::get_node_count() const { return node_count; } id_t DagifiedGraph::min_node_id() const { // duplicated handles only increase in ID, so the original minimum doesn't change return graph->min_node_id(); } id_t DagifiedGraph::max_node_id() const { return max_id; } handle_t DagifiedGraph::get_underlying_handle(const handle_t& handle) const { return handlegraph::as_handle(((uint64_t(handlegraph::as_integer(handle)) - min_handle) % handle_val_range) + min_handle); } uint64_t DagifiedGraph::scc_copy_of_handle(const handle_t& handle) const { return (uint64_t(handlegraph::as_integer(handle)) - min_handle) / handle_val_range; } uint64_t DagifiedGraph::scc_copy_of_node_id(const id_t& node_id) const { return (node_id - graph->min_node_id()) / (graph->max_node_id() - graph->min_node_id() + 1); } size_t DagifiedGraph::layout_order_of_handle(const handle_t& handle) const { auto iter = layout_order.find(handle); if (iter == layout_order.end()) { iter = layout_order.find(graph->flip(handle)); } return iter->second; } id_t DagifiedGraph::get_underlying_id(const id_t& node_id) const { return ((node_id - graph->min_node_id()) % (graph->max_node_id() - graph->min_node_id() + 1)) + graph->min_node_id(); } handle_t DagifiedGraph::nth_copy_of_handle(const handle_t& handle, const uint64_t& n) const { return handlegraph::as_handle(uint64_t(handlegraph::as_integer(handle)) + n * handle_val_range); } }
46.266106
153
0.559181
lnceballosz
70a816ce81d79a28776a0dc52e8dcdf198559b1b
8,481
cpp
C++
src/org/apache/poi/ss/formula/functions/TextFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/functions/TextFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/functions/TextFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/functions/TextFunction.java #include <org/apache/poi/ss/formula/functions/TextFunction.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/String.hpp> #include <org/apache/poi/ss/formula/eval/ErrorEval.hpp> #include <org/apache/poi/ss/formula/eval/EvaluationException.hpp> #include <org/apache/poi/ss/formula/eval/OperandResolver.hpp> #include <org/apache/poi/ss/formula/eval/ValueEval.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_11.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_1.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_2.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_3.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_4.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_5.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_6.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_7.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_8.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_9.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_10.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_LeftRight.hpp> #include <org/apache/poi/ss/formula/functions/TextFunction_SearchFind.hpp> #include <org/apache/poi/ss/usermodel/DataFormatter.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace poi { namespace ss { namespace formula { namespace eval { typedef ::SubArray< ::poi::ss::formula::eval::ValueEval, ::java::lang::ObjectArray > ValueEvalArray; } // eval } // formula } // ss } // poi template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::ss::formula::functions::TextFunction::TextFunction(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::formula::functions::TextFunction::TextFunction() : TextFunction(*static_cast< ::default_init_tag* >(0)) { ctor(); } poi::ss::usermodel::DataFormatter*& poi::ss::formula::functions::TextFunction::formatter() { clinit(); return formatter_; } poi::ss::usermodel::DataFormatter* poi::ss::formula::functions::TextFunction::formatter_; java::lang::String* poi::ss::formula::functions::TextFunction::evaluateStringArg(::poi::ss::formula::eval::ValueEval* eval, int32_t srcRow, int32_t srcCol) /* throws(EvaluationException) */ { clinit(); auto ve = ::poi::ss::formula::eval::OperandResolver::getSingleValue(eval, srcRow, srcCol); return ::poi::ss::formula::eval::OperandResolver::coerceValueToString(ve); } int32_t poi::ss::formula::functions::TextFunction::evaluateIntArg(::poi::ss::formula::eval::ValueEval* arg, int32_t srcCellRow, int32_t srcCellCol) /* throws(EvaluationException) */ { clinit(); auto ve = ::poi::ss::formula::eval::OperandResolver::getSingleValue(arg, srcCellRow, srcCellCol); return ::poi::ss::formula::eval::OperandResolver::coerceValueToInt(ve); } double poi::ss::formula::functions::TextFunction::evaluateDoubleArg(::poi::ss::formula::eval::ValueEval* arg, int32_t srcCellRow, int32_t srcCellCol) /* throws(EvaluationException) */ { clinit(); auto ve = ::poi::ss::formula::eval::OperandResolver::getSingleValue(arg, srcCellRow, srcCellCol); return ::poi::ss::formula::eval::OperandResolver::coerceValueToDouble(ve); } poi::ss::formula::eval::ValueEval* poi::ss::formula::functions::TextFunction::evaluate(::poi::ss::formula::eval::ValueEvalArray* args, int32_t srcCellRow, int32_t srcCellCol) { try { return evaluateFunc(args, srcCellRow, srcCellCol); } catch (::poi::ss::formula::eval::EvaluationException* e) { return npc(e)->getErrorEval(); } } poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::CHAR() { clinit(); return CHAR_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::CHAR_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::LEN() { clinit(); return LEN_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::LEN_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::LOWER() { clinit(); return LOWER_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::LOWER_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::UPPER() { clinit(); return UPPER_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::UPPER_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::PROPER() { clinit(); return PROPER_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::PROPER_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::TRIM() { clinit(); return TRIM_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::TRIM_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::CLEAN() { clinit(); return CLEAN_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::CLEAN_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::MID() { clinit(); return MID_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::MID_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::LEFT() { clinit(); return LEFT_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::LEFT_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::RIGHT() { clinit(); return RIGHT_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::RIGHT_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::CONCATENATE() { clinit(); return CONCATENATE_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::CONCATENATE_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::EXACT() { clinit(); return EXACT_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::EXACT_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::TEXT() { clinit(); return TEXT_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::TEXT_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::FIND() { clinit(); return FIND_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::FIND_; poi::ss::formula::functions::Function*& poi::ss::formula::functions::TextFunction::SEARCH() { clinit(); return SEARCH_; } poi::ss::formula::functions::Function* poi::ss::formula::functions::TextFunction::SEARCH_; extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::formula::functions::TextFunction::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.functions.TextFunction", 48); return c; } void poi::ss::formula::functions::TextFunction::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; formatter_ = new ::poi::ss::usermodel::DataFormatter(); CHAR_ = new TextFunction_1(); LEN_ = new TextFunction_2(); LOWER_ = new TextFunction_3(); UPPER_ = new TextFunction_4(); PROPER_ = new TextFunction_5(); TRIM_ = new TextFunction_6(); CLEAN_ = new TextFunction_7(); MID_ = new TextFunction_8(); LEFT_ = new TextFunction_LeftRight(true); RIGHT_ = new TextFunction_LeftRight(false); CONCATENATE_ = new TextFunction_9(); EXACT_ = new TextFunction_10(); TEXT_ = new TextFunction_11(); FIND_ = new TextFunction_SearchFind(true); SEARCH_ = new TextFunction_SearchFind(false); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } java::lang::Class* poi::ss::formula::functions::TextFunction::getClass0() { return class_(); }
34.616327
189
0.703101
pebble2015
70a9f6e766d21ea8f1ae0d3b71e52a2ca24eec2c
9,525
cpp
C++
code/Plugins/Renderer/Direct3D9/Source/T3DD3D9Mappings.cpp
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
1
2021-11-16T15:11:52.000Z
2021-11-16T15:11:52.000Z
code/Plugins/Renderer/Direct3D9/Source/T3DD3D9Mappings.cpp
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
null
null
null
code/Plugins/Renderer/Direct3D9/Source/T3DD3D9Mappings.cpp
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
null
null
null
/******************************************************************************* * This file is part of Tiny3D (Tiny 3D Graphic Rendering Engine) * Copyright (C) 2015-2019 Answer Wong * For latest info, see https://github.com/answerear/Tiny3D * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "T3DD3D9Mappings.h" namespace Tiny3D { //-------------------------------------------------------------------------- D3DPRIMITIVETYPE D3D9Mappings::get(Renderer::PrimitiveType primitive) { D3DPRIMITIVETYPE d3dtype = D3DPT_TRIANGLESTRIP; switch (primitive) { case Renderer::E_PT_POINT_LIST: d3dtype = D3DPT_POINTLIST; break; case Renderer::E_PT_LINE_LIST: d3dtype = D3DPT_LINELIST; break; case Renderer::E_PT_TRIANGLE_LIST: d3dtype = D3DPT_TRIANGLELIST; break; case Renderer::E_PT_TRIANGLE_STRIP: d3dtype = D3DPT_TRIANGLESTRIP; break; case Renderer::E_PT_TRIANGLE_FAN: d3dtype = D3DPT_TRIANGLEFAN; } return d3dtype; } //-------------------------------------------------------------------------- DWORD D3D9Mappings::get(HardwareBuffer::Usage usage) { DWORD ret = 0; if (usage & HardwareBuffer::E_HBU_DYNAMIC) { ret |= D3DUSAGE_DYNAMIC; } if (usage & HardwareBuffer::E_HBU_WRITE_ONLY) { ret |= D3DUSAGE_WRITEONLY; } return ret; } //-------------------------------------------------------------------------- DWORD D3D9Mappings::get(HardwareBuffer::Usage usage, HardwareBuffer::LockOptions options) { DWORD ret = 0; if (options == HardwareBuffer::E_HBL_DISCARD) { if (usage & HardwareBuffer::E_HBU_DYNAMIC) ret |= D3DLOCK_DISCARD; } if (options == HardwareBuffer::E_HBL_READ_ONLY) { if (!(usage & HardwareBuffer::E_HBU_WRITE_ONLY)) ret |= D3DLOCK_READONLY; } if (options == HardwareBuffer::E_HBL_NO_OVERWRITE) { if (usage & HardwareBuffer::E_HBU_DYNAMIC) ret |= D3DLOCK_NOOVERWRITE; } return ret; } //-------------------------------------------------------------------------- D3DFORMAT D3D9Mappings::get(HardwareIndexBuffer::Type type) { if (type == HardwareIndexBuffer::E_IT_16BITS) { return D3DFMT_INDEX16; } return D3DFMT_INDEX32; } //-------------------------------------------------------------------------- D3DDECLTYPE D3D9Mappings::get(VertexAttribute::Type type) { D3DDECLTYPE d3dtype = D3DDECLTYPE_FLOAT3; switch (type) { case VertexAttribute::E_VAT_COLOR: d3dtype = D3DDECLTYPE_D3DCOLOR; break; case VertexAttribute::E_VAT_FLOAT1: d3dtype = D3DDECLTYPE_FLOAT1; break; case VertexAttribute::E_VAT_FLOAT2: d3dtype = D3DDECLTYPE_FLOAT2; break; case VertexAttribute::E_VAT_FLOAT3: d3dtype = D3DDECLTYPE_FLOAT3; break; case VertexAttribute::E_VAT_FLOAT4: d3dtype = D3DDECLTYPE_FLOAT4; break; case VertexAttribute::E_VAT_SHORT2: d3dtype = D3DDECLTYPE_SHORT2; break; case VertexAttribute::E_VAT_SHORT4: d3dtype = D3DDECLTYPE_SHORT4; break; case VertexAttribute::E_VAT_UBYTE4: d3dtype = D3DDECLTYPE_UBYTE4; break; } return d3dtype; } //-------------------------------------------------------------------------- D3DDECLUSAGE D3D9Mappings::get(VertexAttribute::Semantic semantic) { D3DDECLUSAGE usage = D3DDECLUSAGE_POSITION; switch (semantic) { case VertexAttribute::E_VAS_POSITION: usage = D3DDECLUSAGE_POSITION; break; case VertexAttribute::E_VAS_BLENDWEIGHT: usage = D3DDECLUSAGE_BLENDWEIGHT; break; case VertexAttribute::E_VAS_BLENDINDICES: usage = D3DDECLUSAGE_BLENDINDICES; break; case VertexAttribute::E_VAS_NORMAL: usage = D3DDECLUSAGE_NORMAL; break; case VertexAttribute::E_VAS_DIFFUSE: case VertexAttribute::E_VAS_SPECULAR: usage = D3DDECLUSAGE_COLOR; break; case VertexAttribute::E_VAS_TEXCOORD: usage = D3DDECLUSAGE_TEXCOORD; break; case VertexAttribute::E_VAS_TANGENT: usage = D3DDECLUSAGE_TANGENT; break; case VertexAttribute::E_VAS_BINORMAL: usage = D3DDECLUSAGE_BINORMAL; break; } return usage; } //-------------------------------------------------------------------------- D3DFORMAT D3D9Mappings::get(PixelFormat format) { D3DFORMAT d3dfmt = D3DFMT_A8B8G8R8; switch (format) { case E_PF_R5G6B5: d3dfmt = D3DFMT_R5G6B5; break; case E_PF_A1R5G5B5: d3dfmt = D3DFMT_A1R5G5B5; break; case E_PF_A4R4G4B4: d3dfmt = D3DFMT_A4R4G4B4; break; case E_PF_R8G8B8: d3dfmt = D3DFMT_R8G8B8; break; case E_PF_A8R8G8B8: d3dfmt = D3DFMT_A8R8G8B8; break; case E_PF_X8R8G8B8: d3dfmt = D3DFMT_X8R8G8B8; break; case E_PF_B8G8R8X8: d3dfmt = D3DFMT_X8B8G8R8; break; case E_PF_B8G8R8A8: d3dfmt = D3DFMT_A8B8G8R8; break; } return d3dfmt; } //-------------------------------------------------------------------------- PixelFormat D3D9Mappings::get(D3DFORMAT d3dfmt) { PixelFormat format = E_PF_A8R8G8B8; switch (d3dfmt) { case D3DFMT_R5G6B5: format = E_PF_R5G6B5; break; case D3DFMT_A1R5G5B5: format = E_PF_A1R5G5B5; break; case D3DFMT_A4R4G4B4: format = E_PF_A4R4G4B4; break; case D3DFMT_R8G8B8: format = E_PF_R8G8B8; break; case D3DFMT_A8R8G8B8: format = E_PF_A8R8G8B8; break; case D3DFMT_X8R8G8B8: format = E_PF_X8R8G8B8; break; case D3DFMT_A8B8G8R8: format = E_PF_B8G8R8A8; break; case D3DFMT_X8B8G8R8: format = E_PF_B8G8R8X8; break; } return format; } //-------------------------------------------------------------------------- D3DCOLORVALUE D3D9Mappings::get(const ColorARGB &color) { D3DCOLORVALUE d3dcolor; d3dcolor.a = color.alpha(); d3dcolor.r = color.red(); d3dcolor.g = color.green(); d3dcolor.b = color.blue(); return d3dcolor; } //-------------------------------------------------------------------------- D3DMATRIX D3D9Mappings::toD3DMatrix(const Matrix4 &mat) { // 转置矩阵 // D3D9 使用行向量 i.e. V*M // Tiny3D, OpenGL 等用列向量 i.e. M*V D3DXMATRIX d3dMat; d3dMat.m[0][0] = mat[0][0]; d3dMat.m[0][1] = mat[1][0]; d3dMat.m[0][2] = mat[2][0]; d3dMat.m[0][3] = mat[3][0]; d3dMat.m[1][0] = mat[0][1]; d3dMat.m[1][1] = mat[1][1]; d3dMat.m[1][2] = mat[2][1]; d3dMat.m[1][3] = mat[3][1]; d3dMat.m[2][0] = mat[0][2]; d3dMat.m[2][1] = mat[1][2]; d3dMat.m[2][2] = mat[2][2]; d3dMat.m[2][3] = mat[3][2]; d3dMat.m[3][0] = mat[0][3]; d3dMat.m[3][1] = mat[1][3]; d3dMat.m[3][2] = mat[2][3]; d3dMat.m[3][3] = mat[3][3]; return d3dMat; } //-------------------------------------------------------------------------- Matrix4 D3D9Mappings::toT3DMatrix(const D3DMATRIX &mat) { Matrix4 t3dMat; t3dMat[0][0] = mat.m[0][0]; t3dMat[1][0] = mat.m[0][1]; t3dMat[2][0] = mat.m[0][2]; t3dMat[3][0] = mat.m[0][3]; t3dMat[0][1] = mat.m[1][0]; t3dMat[1][1] = mat.m[1][1]; t3dMat[2][1] = mat.m[1][2]; t3dMat[3][1] = mat.m[1][3]; t3dMat[0][2] = mat.m[2][0]; t3dMat[1][2] = mat.m[2][1]; t3dMat[2][2] = mat.m[2][2]; t3dMat[3][2] = mat.m[2][3]; t3dMat[0][3] = mat.m[3][0]; t3dMat[1][3] = mat.m[3][1]; t3dMat[2][3] = mat.m[3][2]; t3dMat[3][3] = mat.m[3][3]; return t3dMat; } }
28.603604
81
0.489974
answerear
70ab4001756b4343b7b6c99ad2c1d4f61148a855
16,138
cpp
C++
test/Core/QubitMapping.test.cpp
QianJianhua1/QPanda-2
a13c7b733031b1d0007dceaf1dae6ad447bb969c
[ "Apache-2.0" ]
null
null
null
test/Core/QubitMapping.test.cpp
QianJianhua1/QPanda-2
a13c7b733031b1d0007dceaf1dae6ad447bb969c
[ "Apache-2.0" ]
null
null
null
test/Core/QubitMapping.test.cpp
QianJianhua1/QPanda-2
a13c7b733031b1d0007dceaf1dae6ad447bb969c
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include "QPanda.h" #include <iostream> #include <vector> #include <stdio.h> #include <memory> #include <chrono> #include <string> #include "Extensions/Extensions.h" #ifdef USE_EXTENSION #ifndef PI #define PI 3.1415926 #endif // !PI const size_t kShots = 2048; const size_t kEpsion = kShots * 0.07; #define CHECK_TIME 1 #define CHECK_SWAP 1 const std::string test_IR_1 = R"(QINIT 6 CREG 4 H q[0] X q[1] X q[5] CNOT q[0],q[1] CNOT q[4],q[5] CNOT q[0],q[2] RZ q[1],(1.16) RZ q[4],(0.785) RZ q[5],(2.78539816) RZ q[0],(1.9816) RY q[2],(1.112) CNOT q[3],q[5] CR q[2],q[4],(0.567) MEASURE q[1],c[0] MEASURE q[2],c[1] MEASURE q[3],c[2] MEASURE q[4],c[3] )"; const std::string test_IR_2 = R"(QINIT 4 CREG 1 H q[0] X q[1] X q[2] X q[3] CNOT q[3],q[1] MEASURE q[1],c[0] )"; USING_QPANDA using namespace std; template <class T = CPUQVM> class QVMInit { public: QVMInit() : m_qvm(nullptr){ m_qvm = new(std::nothrow) T; } ~QVMInit() { m_qvm->finalize(); delete m_qvm; } QVec allocate_qubits(size_t size) { return m_qvm->allocateQubits(size); } vector<ClassicalCondition> allocate_class_bits(size_t size) { return m_qvm->allocateCBits(size); } public: QuantumMachine *m_qvm; }; class CalcFidelity : public TraversalInterface<> { public: CalcFidelity() { int qnum = 0; JsonConfigParam config; const std::string config_data; config.load_config(/*config_data*/); config.getMetadataConfig(qnum, mCnotReliability); //mMeaReliability.resize(qnum); //for (int i = 0; i < qnum; i++) //{ // mMeaReliability[i] = 1.0; //} auto graph = mCnotReliability; for (int i = 0; i < qnum; i++) { for (int j = 0; j < qnum; j++) { if (i == j) graph[i][j] == 0.0; else if (graph[i][j] > 1e-6) graph[i][j] = 1.0 - graph[i][j]; else graph[i][j] = DBL_MAX; } } std::vector<std::vector<int>> path(qnum, std::vector<int>(qnum)); std::vector<std::vector<double>> dist(qnum, std::vector<double>(qnum)); for (int i = 0; i < qnum; i++) { for (int j = 0; j < qnum; j++) { dist[i][j] = graph[i][j]; path[i][j] = j; } } for (int k = 0; k < qnum; k++) { for (int i = 0; i < qnum; i++) { for (int j = 0; j < qnum; j++) { if ((dist[i][k] + dist[k][j] < dist[i][j]) && (dist[i][k] != DBL_MAX) && (dist[k][j] != DBL_MAX) && (i != j)) { dist[i][j] = dist[i][k] + dist[k][j]; path[i][j] = path[i][k]; } } } } mSwapDist.resize(qnum); for (int i = 0; i < qnum; i++) { mSwapDist[i].resize(qnum); for (int j = 0; j < qnum; j++) { int prev = i; double reliability = 1.0; int cur = path[i][j]; while (cur != j) { reliability *= std::pow(mCnotReliability[prev][cur], 3); prev = cur; cur = path[cur][j]; } reliability *= std::pow(mCnotReliability[prev][j], 3); mSwapDist[i][j] = reliability; } } } ~CalcFidelity() {}; template <typename _Ty> std::pair<double , int > calc_fidelity(_Ty& node) { m_fidelity = 1.0; m_swap_cnt = 0; execute(node.getImplementationPtr(), nullptr); return { m_fidelity, m_swap_cnt }; } virtual void execute(std::shared_ptr<AbstractQGateNode> cur_node, std::shared_ptr<QNode> parent_node) { auto type = cur_node->getQGate()->getGateType(); QVec qv; cur_node->getQuBitVector(qv); switch (type) { case GateType::CPHASE_GATE: case GateType::CZ_GATE: case GateType::CNOT_GATE: { auto idx_0 = qv[0]->get_phy_addr(); auto idx_1 = qv[1]->get_phy_addr(); m_fidelity *= mCnotReliability[idx_0][idx_1]; } break; case GateType::SWAP_GATE: { auto idx_0 = qv[0]->get_phy_addr(); auto idx_1 = qv[1]->get_phy_addr(); m_fidelity *= mSwapDist[idx_0][idx_1]; m_swap_cnt++; } break; default: break; } } virtual void execute(std::shared_ptr<AbstractQuantumMeasure> cur_node, std::shared_ptr<QNode> parent_node) {} virtual void execute(std::shared_ptr<AbstractQuantumReset> cur_node, std::shared_ptr<QNode> parent_node) {} virtual void execute(std::shared_ptr<AbstractControlFlowNode> cur_node, std::shared_ptr<QNode> parent_node) { Traversal::traversal(cur_node, *this); } virtual void execute(std::shared_ptr<AbstractQuantumCircuit> cur_node, std::shared_ptr<QNode> parent_node) { Traversal::traversal(cur_node, false, *this); } virtual void execute(std::shared_ptr<AbstractQuantumProgram> cur_node, std::shared_ptr<QNode> parent_node) { Traversal::traversal(cur_node, *this); } virtual void execute(std::shared_ptr<AbstractClassicalProg> cur_node,std::shared_ptr<QNode> parent_node){} double m_fidelity; std::vector<std::vector<double>> mCnotReliability; std::vector<std::vector<double>> mSwapDist; int m_swap_cnt; }; static bool test_opt_BMT_qubit_allocator_1() { auto qvm = new CPUQVM(); qvm->init(); std::vector<ClassicalCondition> c; //QVec q; auto q = qvm->qAllocMany(5); //auto c = qvm->cAllocMany(5); QProg prog; //prog = convert_originir_to_qprog("D:\\test.txt", qvm, q, c); prog << QFT(q); //prog = random_qprog(1, 8, 20, qvm, q); //write_to_originir_file(prog, qvm, "D:\\test.txt"); qvm->directlyRun(prog); auto r_1 = qvm->PMeasure_no_index( q); //cout << "srd prog:" << prog << endl; // test qubit allocator auto old_qv_1 = q; auto old_qv_2 = q; // 1. bmt auto bmt_mapped_prog = OBMT_mapping(prog, qvm, q); qvm->directlyRun(bmt_mapped_prog); auto r_2 = qvm->PMeasure_no_index(q); //cout << "bmt_mapped_prog:" << bmt_mapped_prog << endl; CalcFidelity cf; //std::cout << "bmt fidelity : "<< cf.calc_fidelity(bmt_mapped_prog).first << std::endl; //std::cout << "bmt swap : " << cf.calc_fidelity(bmt_mapped_prog).second << std::endl; if (cf.calc_fidelity(bmt_mapped_prog).first != 0.0203972 && cf.calc_fidelity(bmt_mapped_prog).second != 6) return false; #ifdef qcodar // 2. qcodar //auto qcodar_mapped_prog = qcodar_match_by_simple_type(prog, old_qv_1, qvm, 2, 4, 10); auto qcodar_mapped_prog = qcodar_match_by_config(prog, old_qv_1, qvm, "QPandaConfig.json", 5); cout << "qcodar_mapped_prog:" << qcodar_mapped_prog << endl; std::cout << "qcodar fidelity : " << cf.calc_fidelity(qcodar_mapped_prog).first << std::endl; std::cout << "qcodar swap : " << cf.calc_fidelity(qcodar_mapped_prog).second << std::endl; // 3. astar auto astar_mapped_prog = topology_match(prog, old_qv_2, qvm); cout << "astar_mapped_prog:" << astar_mapped_prog << endl; std::cout << "astar fidelity : " << cf.calc_fidelity(astar_mapped_prog).first << std::endl; std::cout << "astar swap : " << cf.calc_fidelity(astar_mapped_prog).second << std::endl; int size = std::min(r_1.size(), r_2.size()); for (int i = 0; i < size; i++) { if ((fabs(r_1[i] - r_2[i]) > 1e-6)) { std::cout << r_1[i] << " != " << r_2[i] << "i : " << i << std::endl; } } #endif // qcodar qvm->finalize(); delete qvm; return true; } static bool test_opt_BMT_qubit_allocator_3() { QVMInit<> tmp_qvm; auto machine = tmp_qvm.m_qvm; machine->setConfigure({ 128,128 }); //#define HHL_ORIGINIR_FILE "E:\\11\\random_100_qubit-1.txt" /*auto q = tmp_qvm.allocate_qubits(8); auto c = tmp_qvm.allocate_class_bits(8);*/ QVec q; vector<ClassicalCondition> c; QProg prog_100qubits = convert_originir_string_to_qprog(test_IR_1, machine, q, c); /*printf("^^^^^^^^^^^^^^^^^after decompose_multiple_control_qgate the hhl_cir_gate_cnt: %llu ^^^^^^^^^^^^^^^^^^^^\n", getQGateNum(prog_100qubits));*/ /*write_to_originir_file(hhl_prog, machine, HHL_ORIGINIR_FILE); getchar();*/ //cout << "src_prog:" << prog_100qubits << endl; // test qubit allocator /*QVec q; get_all_used_qubits(hhl_prog, q);*/ auto bmt_mapped_prog = OBMT_mapping(prog_100qubits, machine, q); //cout << "bmt_mapped_prog:" << bmt_mapped_prog << endl; CalcFidelity cf; //std::cout << "bmt fidelity : " << cf.calc_fidelity(bmt_mapped_prog).first << std::endl; //std::cout << "bmt swap : " << cf.calc_fidelity(bmt_mapped_prog).second << std::endl; if (cf.calc_fidelity(bmt_mapped_prog).first != 0.5832 && cf.calc_fidelity(bmt_mapped_prog).second != 0) return false; #ifdef qcodar // 2. qcodar std::cout << "start qcodar >>> " << endl; auto start = chrono::system_clock::now(); //auto qcodar_mapped_prog = qcodar_match_by_simple_type(prog, old_qv_1, qvm, 2, 4, 10); auto qcodar_mapped_prog = qcodar_match_by_config(prog_100qubits, q, machine, "QPandaConfig.json", 10); auto end = chrono::system_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(end - start); cout << "The QCodar takes " << double(duration.count()) * chrono::microseconds::period::num / chrono::microseconds::period::den << "seconds" << endl; //cout << "qcodar_mapped_prog:" << qcodar_mapped_prog << endl; std::cout << "qcodar fidelity : " << cf.calc_fidelity(qcodar_mapped_prog).first << std::endl; std::cout << "qcodar swap : " << cf.calc_fidelity(qcodar_mapped_prog).second << std::endl; #endif // qcodar return true; } static bool test_SABRE_qubit_mapping_1() { QVMInit<> tmp_qvm; auto machine = tmp_qvm.m_qvm; machine->setConfigure({ 128,128 }); auto q = tmp_qvm.allocate_qubits(5); QCircuit cir; cir << H(q[0]) << CNOT(q[0], q[1]) << H(q[1]) << H(q[1]) << CNOT(q[0], q[2]) << CNOT(q[1], q[2]) << CNOT(q[3], q[4]) << CNOT(q[2], q[3]) << CNOT(q[2], q[3]) << H(q[2]) << CNOT(q[2], q[3]) << CNOT(q[4], q[1]) << H(q[4]) << CNOT(q[4], q[0]) << CNOT(q[1], q[0]) << H(q[4]) << H(q[0]); //cout << "srd prog:" << cir << endl; // 1. SABRE auto sabre_mapped_prog = SABRE_mapping(cir, machine, q); //cout << "SABRE_mapped_prog:" << sabre_mapped_prog << endl; CalcFidelity cf; //std::cout << "bmt fidelity : " << cf.calc_fidelity(sabre_mapped_prog).first << std::endl; //std::cout << "bmt swap : " << cf.calc_fidelity(sabre_mapped_prog).second << std::endl; if (cf.calc_fidelity(sabre_mapped_prog).first != 0.098411 && cf.calc_fidelity(sabre_mapped_prog).second != 2) return false; return true; } static bool test_mapping_overall_1(const std::string& ir_str) { QVMInit<> tmp_qvm; auto machine = tmp_qvm.m_qvm; machine->setConfigure({ 128,128 }); QVec q; vector<ClassicalCondition> c; QProg test_prog = convert_originir_string_to_qprog(ir_str, machine, q, c); // Get correct result const std::map<string, size_t> correct_result = machine->runWithConfiguration(test_prog, c, kShots); // 1. SABRE auto start = chrono::system_clock::now(); auto _prog = deepCopy(test_prog); auto sabre_mapped_prog = SABRE_mapping(_prog, machine, q, 20, 10); auto end = chrono::system_clock::now(); // check Fidelity if (CHECK_TIME) { CalcFidelity cf; std::cout << "SABRE fidelity : " << cf.calc_fidelity(sabre_mapped_prog).first << std::endl; std::cout << "SABRE swap : " << cf.calc_fidelity(sabre_mapped_prog).second << std::endl; } // check circuit-deep if (CHECK_TIME) { cout << "SABRE_mapped_prog:" << sabre_mapped_prog << endl; auto layer_info = prog_layer(sabre_mapped_prog); cout << "SABRE_mapped_prog deeps = " << layer_info.size() << endl; auto duration = chrono::duration_cast<chrono::microseconds>(end - start); cout << "The SABRE takes " << double(duration.count()) * chrono::microseconds::period::num / chrono::microseconds::period::den << "seconds" << endl; std::cout << " <<<< ------------- SABRE END -------------------------- \n" << endl; } // check result { std::map<string, size_t> _result = machine->runWithConfiguration(sabre_mapped_prog, c, kShots); for (const auto& i : _result) { if (abs((long)i.second < kEpsion)) continue; const long _a = i.second - correct_result.at(i.first); if (std::abs(_a) > kEpsion){ return false; } } } // 2. opt-bmt //std::cout << "-------------------- start opt-bmt >>> " << endl; start = chrono::system_clock::now(); _prog = deepCopy(test_prog); auto bmt_mapped_prog = OBMT_mapping(_prog, machine, q, 200); end = chrono::system_clock::now(); // check Fidelity if (CHECK_TIME) { CalcFidelity cf; std::cout << "opt-bmt fidelity : " << cf.calc_fidelity(bmt_mapped_prog).first << std::endl; std::cout << "opt-bmt swap : " << cf.calc_fidelity(bmt_mapped_prog).second << std::endl; } // check circuit-deep if (CHECK_TIME) { //cout << "opt-bmt mapped_prog:" << bmt_mapped_prog << endl; auto layer_info = prog_layer(bmt_mapped_prog); //cout << "opt-bmt mapped_prog deeps = " << layer_info.size() << endl; auto duration = chrono::duration_cast<chrono::microseconds>(end - start); cout << "The opt-bmt takes " << double(duration.count()) * chrono::microseconds::period::num / chrono::microseconds::period::den << "seconds" << endl; std::cout << " <<<< ------------- opt-bmt END -------------------------- \n" << endl; } // check result { auto _result = machine->runWithConfiguration(bmt_mapped_prog, c, kShots); for (const auto& i : _result) { if (abs((long)i.second < kEpsion)) continue; if (abs((long)i.second - (long)correct_result.at(i.first)) > kEpsion) { return false; } } } #ifdef QCoadr // 3. QCodar std::cout << "-------------------- start QCodar >>> " << endl; start = chrono::system_clock::now(); //auto qcodar_mapped_prog = qcodar_match_by_config(test_prog, q, machine, CONFIG_PATH, 10); auto qcodar_mapped_prog = qcodar_match_by_simple_type(test_prog, q, machine, 2, 10, 10); end = chrono::system_clock::now(); duration = chrono::duration_cast<chrono::microseconds>(end - start); //cout << "qcodar_mapped_prog:" << qcodar_mapped_prog << endl; layer_info = prog_layer(qcodar_mapped_prog); cout << "qcodar_mapped_prog deeps = " << layer_info.size() << endl; std::cout << "QCodar fidelity : " << cf.calc_fidelity(qcodar_mapped_prog).first << std::endl; std::cout << "QCodar swap : " << cf.calc_fidelity(qcodar_mapped_prog).second << std::endl; cout << "The QCodar takes " << double(duration.count()) * chrono::microseconds::period::num / chrono::microseconds::period::den << "seconds" << endl; std::cout << " <<<< ------------- QCodar END -------------------------- \n" << endl; #endif // QCoadr // 4. A-star start = chrono::system_clock::now(); _prog = deepCopy(test_prog); auto astar_mapped_prog = topology_match(_prog, q, machine, CONFIG_PATH); end = chrono::system_clock::now(); // check Fidelity if (CHECK_TIME) { CalcFidelity cf; std::cout << "A-star fidelity : " << cf.calc_fidelity(astar_mapped_prog).first << std::endl; std::cout << "A-star swap : " << cf.calc_fidelity(astar_mapped_prog).second << std::endl; } // check circuit-deep if (CHECK_TIME) { //cout << "A-star mapped_prog:" << astar_mapped_prog << endl; auto layer_info = prog_layer(astar_mapped_prog); cout << "astar_mapped_prog deeps = " << layer_info.size() << endl; auto duration = chrono::duration_cast<chrono::microseconds>(end - start); cout << "The A-star takes " << double(duration.count()) * chrono::microseconds::period::num / chrono::microseconds::period::den << "seconds" << endl; std::cout << " <<<< ------------- A-star END -------------------------- \n" << endl; } // check result { auto _result = machine->runWithConfiguration(bmt_mapped_prog, c, kShots); for (const auto& i : _result) { if (abs((long)i.second < kEpsion)) continue; if (abs((long)i.second - (long)correct_result.at(i.first)) > kEpsion) { return false; } } } return true; } TEST(QubitMapping, test1) { bool test_val = false; try { for (size_t i = 0; i < 10; ++i) { test_val = test_mapping_overall_1(test_IR_1); test_val = test_val && test_mapping_overall_1(test_IR_2); /*test_val = test_val && test_opt_BMT_qubit_allocator_3(); test_val = test_val && test_SABRE_qubit_mapping_1(); test_val = test_val && test_opt_BMT_qubit_allocator_1();*/ if (!test_val){ break; } } } catch (const std::exception& e) { std::cout << "Got a exception: " << e.what() << endl; test_val = false; } catch (...) { std::cout << "Got an unknow exception: " << endl; test_val = false; } ASSERT_TRUE(test_val); } #endif
28.411972
118
0.641219
QianJianhua1
70ab524b8c2812cf12cc0bde557a89517e30a119
65,973
hpp
C++
third_party/xsimd/types/xsimd_base.hpp
PierreBlancfat/pythran2
37869bc73aae1054253c2b1643aee5c63f11b7e8
[ "BSD-3-Clause" ]
null
null
null
third_party/xsimd/types/xsimd_base.hpp
PierreBlancfat/pythran2
37869bc73aae1054253c2b1643aee5c63f11b7e8
[ "BSD-3-Clause" ]
null
null
null
third_party/xsimd/types/xsimd_base.hpp
PierreBlancfat/pythran2
37869bc73aae1054253c2b1643aee5c63f11b7e8
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_BASE_HPP #define XSIMD_BASE_HPP #include <cstddef> #include <complex> #include <iterator> #include <ostream> #include <type_traits> #ifdef XSIMD_ENABLE_XTL_COMPLEX #include "xtl/xcomplex.hpp" #endif #include "../memory/xsimd_alignment.hpp" #include "xsimd_utils.hpp" #include "xsimd_base_bool.hpp" namespace xsimd { template <class T, size_t N> class batch; namespace detail { template <class T, std::size_t N> struct batch_kernel; } template <class X> struct simd_batch_inner_types { using batch_reference = X&; using const_batch_reference = const X&; }; template <class T> using batch_type_t = typename T::batch_type; namespace detail { template <class X> struct get_real_batch_type { using batch_type = batch_type_t<X>; }; template <class T, std::size_t N> struct get_real_batch_type<batch<std::complex<T>, N>> { using batch_type = typename batch<std::complex<T>, N>::real_batch; }; #ifdef XSIMD_ENABLE_XTL_COMPLEX template <class T, bool i3ec, std::size_t N> struct get_real_batch_type<batch<xtl::xcomplex<T, T, i3ec>, N>> { using batch_type = typename batch<xtl::xcomplex<T, T, i3ec>, N>::real_batch; }; #endif } template <class T> using real_batch_type_t = typename detail::get_real_batch_type<typename T::batch_type>::batch_type; /************* * simd_base * *************/ /** * @class simd_base * @brief Base class for batches and batch proxies. * * The simd_base class is the base class for all classes * representing a batch or a batch proxy. It provides very few * methods, so concrete batches usually inherit from intermediate * classes. * * @tparam X The most derived type */ template <class X> class simd_base { public: using derived_class = X; using batch_reference = typename simd_batch_inner_types<X>::batch_reference; using const_batch_reference = typename simd_batch_inner_types<X>::const_batch_reference; batch_reference operator()(); const_batch_reference operator()() const; X& derived_cast(); const X& derived_cast() const; }; /************** * simd_batch * **************/ /** * @class simd_batch * @brief Base class for batch of integer or floating point values. * * The simd_batch class is the base class for all classes representing * a batch of integer or floating point values. Each type of batch (i.e. * a class inheriting from simd_batch) has its dedicated type of boolean * batch (i.e. a class inheriting from simd_batch_bool) for logical operations. * * @tparam X The derived type * @sa simd_batch_bool */ template <class X> class simd_batch : public simd_base<X> { public: using base_type = simd_base<X>; using batch_reference = typename base_type::batch_reference; using const_batch_reference = typename base_type::const_batch_reference; using batch_type = X; using value_type = typename simd_batch_traits<X>::value_type; static constexpr std::size_t size = simd_batch_traits<X>::size; using storage_type = typename simd_batch_traits<X>::storage_type; using iterator = value_type*; using const_iterator = const value_type*; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; X& operator+=(const X& rhs); X& operator+=(const value_type& rhs); X& operator-=(const X& rhs); X& operator-=(const value_type& rhs); X& operator*=(const X& rhs); X& operator*=(const value_type& rhs); X& operator/=(const X& rhs); X& operator/=(const value_type& rhs); X& operator&=(const X& rhs); X& operator|=(const X& rhs); X& operator^=(const X& rhs); X& operator++(); X& operator++(int); X& operator--(); X& operator--(int); X& load_aligned(const char* src); X& load_unaligned(const char* src); void store_aligned(char* dst) const; void store_unaligned(char* dst) const; batch_reference get(); const_batch_reference get() const; value_type& operator[](std::size_t index); const value_type& operator[](std::size_t index) const; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; reverse_iterator rbegin(); reverse_iterator rend(); const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; const_reverse_iterator crbegin() const; const_reverse_iterator crend() const; protected: simd_batch() = default; ~simd_batch() = default; simd_batch(const simd_batch&) = default; simd_batch& operator=(const simd_batch&) = default; simd_batch(simd_batch&&) = default; simd_batch& operator=(simd_batch&&) = default; simd_batch(storage_type value); using char_itype = typename std::conditional<std::is_signed<char>::value, int8_t, uint8_t>::type; union { storage_type m_value; value_type m_array[size]; }; }; template <class X> typename simd_batch_traits<X>::batch_bool_type operator!(const simd_base<X>& rhs); template <class X> batch_type_t<X> min(const simd_base<X>& lhs, const simd_base<X>& rhs); template <class X> batch_type_t<X> max(const simd_base<X>& lhs, const simd_base<X>& rhs); template <class X> batch_type_t<X> fmin(const simd_base<X>& lhs, const simd_base<X>& rhs); template <class X> batch_type_t<X> fmax(const simd_base<X>& lhs, const simd_base<X>& rhs); template <class X> real_batch_type_t<X> abs(const simd_base<X>& rhs); template <class X> batch_type_t<X> fabs(const simd_base<X>& rhs); template <class X> batch_type_t<X> sqrt(const simd_base<X>& rhs); template <class X> batch_type_t<X> fma(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z); template <class X> batch_type_t<X> fms(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z); template <class X> batch_type_t<X> fnma(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z); template <class X> batch_type_t<X> fnms(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z); template <class X> typename simd_batch_traits<X>::value_type hadd(const simd_base<X>& rhs); template <class X> batch_type_t<X> haddp(const simd_base<X>* row); template <class X> batch_type_t<X> select(const typename simd_batch_traits<X>::batch_bool_type& cond, const simd_base<X>& a, const simd_base<X>& b); template <class X> typename simd_batch_traits<X>::batch_bool_type isnan(const simd_base<X>& x); template <class X> std::ostream& operator<<(std::ostream& out, const simd_batch<X>& rhs); /*************************** * generic batch operators * ***************************/ template <class T, std::size_t N> batch<T, N> operator&&(const batch<T, N>& lhs, const batch<T, N>& rhs); template <class T, std::size_t N> batch<T, N> operator||(const batch<T, N>& lhs, const batch<T, N>& rhs); template <class T, std::size_t N> batch<T, N> operator<<(const batch<T, N>& lhs, const batch<T, N>& rhs); template <class T, std::size_t N> batch<T, N> operator>>(const batch<T, N>& lhs, const batch<T, N>& rhs); /************************** * bitwise cast functions * **************************/ // Provides a reinterpret_case from batch<T_in, N_in> to batch<T_out, N_out> template <class B_in, class B_out> struct bitwise_cast_impl; // Shorthand for defining an intrinsic-based bitwise_cast implementation #define XSIMD_BITWISE_CAST_INTRINSIC(T_IN, N_IN, T_OUT, N_OUT, INTRINSIC) \ template <> \ struct bitwise_cast_impl<batch<T_IN, N_IN>, batch<T_OUT, N_OUT>> \ { \ static inline batch<T_OUT, N_OUT> run(const batch<T_IN, N_IN>& x) \ { \ return INTRINSIC(x); \ } \ }; // Backwards-compatible interface to bitwise_cast_impl template <class B, std::size_t N = simd_batch_traits<B>::size> B bitwise_cast(const batch<float, N>& x); template <class B, std::size_t N = simd_batch_traits<B>::size> B bitwise_cast(const batch<double, N>& x); template <class B, std::size_t N = simd_batch_traits<B>::size> B bitwise_cast(const batch<int32_t, N>& x); template <class B, std::size_t N = simd_batch_traits<B>::size> B bitwise_cast(const batch<int64_t, N>& x); template <class T, std::size_t N> batch<T, N> bitwise_cast(const batch_bool<T, N>& src); /**************** * helper macro * ****************/ #define XSIMD_DECLARE_LOAD_STORE(TYPE, N, CVT_TYPE) \ batch<TYPE, N>& load_aligned(const CVT_TYPE*); \ batch<TYPE, N>& load_unaligned(const CVT_TYPE*); \ void store_aligned(CVT_TYPE* dst) const; \ void store_unaligned(CVT_TYPE* dst) const; #define XSIMD_DEFINE_LOAD_STORE(TYPE, N, CVT_TYPE, ALIGNMENT) \ inline batch<TYPE, N>& batch<TYPE, N>::load_aligned(const CVT_TYPE* src) \ { \ alignas(ALIGNMENT) TYPE tmp[N]; \ unroller<N>([&](std::size_t i) { \ tmp[i] = static_cast<TYPE>(src[i]); \ }); \ return load_aligned(tmp); \ } \ inline batch<TYPE, N>& batch<TYPE, N>::load_unaligned(const CVT_TYPE* src) \ { \ return load_aligned(src); \ } \ inline void batch<TYPE, N>::store_aligned(CVT_TYPE* dst) const \ { \ alignas(ALIGNMENT) TYPE tmp[N]; \ store_aligned(tmp); \ unroller<N>([&](std::size_t i) { \ dst[i] = static_cast<CVT_TYPE>(tmp[i]); \ }); \ } \ inline void batch<TYPE, N>::store_unaligned(CVT_TYPE* dst) const \ { \ return store_aligned(dst); \ } #ifdef XSIMD_32_BIT_ABI #define XSIMD_DECLARE_LOAD_STORE_LONG(TYPE, N) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, long) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, unsigned long) \ namespace detail { template <class T> struct get_int_type; template <> struct get_int_type<long> { using type = int32_t; }; template <> struct get_int_type<unsigned long> { using type = uint32_t; }; template <class T> using get_int_type_t = typename get_int_type<T>::type; } #define XSIMD_DEFINE_LOAD_STORE_LONG_IMPL(TYPE, N, CVT_TYPE, ALIGNMENT) \ inline batch<TYPE, N>& batch<TYPE, N>::load_aligned(const CVT_TYPE* src) \ { \ using int_type = detail::get_int_type_t<CVT_TYPE>; \ return this->load_aligned(reinterpret_cast<const int_type*>(src)); \ } \ inline batch<TYPE, N>& batch<TYPE, N>::load_unaligned(const CVT_TYPE* src) \ { \ using int_type = detail::get_int_type_t<CVT_TYPE>; \ return this->load_unaligned(reinterpret_cast<const int_type*>(src)); \ } \ inline void batch<TYPE, N>::store_aligned(CVT_TYPE* dst) const \ { \ using int_type = detail::get_int_type_t<CVT_TYPE>; \ this->store_aligned(reinterpret_cast<int_type*>(dst)); \ } \ inline void batch<TYPE, N>::store_unaligned(CVT_TYPE* dst) const \ { \ using int_type = detail::get_int_type_t<CVT_TYPE>; \ this->store_unaligned(reinterpret_cast<int_type*>(dst)); \ } \ #define XSIMD_DEFINE_LOAD_STORE_LONG(TYPE, N, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE_LONG_IMPL(TYPE, N, long, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE_LONG_IMPL(TYPE, N, unsigned long, ALIGNMENT) \ #else #define XSIMD_DECLARE_LOAD_STORE_LONG(TYPE, N) #define XSIMD_DEFINE_LOAD_STORE_LONG(TYPE, N, ALIGNMENT) #endif // XSIMD_32_BIT_ABI #define XSIMD_DECLARE_LOAD_STORE_INT8(TYPE, N) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, float) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, double) #define XSIMD_DEFINE_LOAD_STORE_INT8(TYPE, N, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int16_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint16_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int32_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint32_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int64_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint64_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, float, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, double, ALIGNMENT) #define XSIMD_DECLARE_LOAD_STORE_INT16(TYPE, N) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, float) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, double) #define XSIMD_DEFINE_LOAD_STORE_INT16(TYPE, N, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int8_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint8_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int32_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint32_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int64_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint64_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, float, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, double, ALIGNMENT) #define XSIMD_DECLARE_LOAD_STORE_INT32(TYPE, N) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, float) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, double) #define XSIMD_DEFINE_LOAD_STORE_INT32(TYPE, N, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int8_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint8_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int16_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint16_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int64_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint64_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, float, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, double, ALIGNMENT) #define XSIMD_DECLARE_LOAD_STORE_INT64(TYPE, N) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, float) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, double) #define XSIMD_DEFINE_LOAD_STORE_INT64(TYPE, N, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int8_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint8_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int16_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint16_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, int32_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, uint32_t, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, float, ALIGNMENT) \ XSIMD_DEFINE_LOAD_STORE(TYPE, N, double, ALIGNMENT) #define XSIMD_DECLARE_LOAD_STORE_ALL(TYPE, N) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint8_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint16_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint32_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, int64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, uint64_t) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, float) \ XSIMD_DECLARE_LOAD_STORE(TYPE, N, double) #define XSIMD_DEFINE_BITWISE_CAST(TYPE, N) \ inline batch<TYPE, N> bitwise_cast(const batch_bool<TYPE, N>& src) \ { \ TYPE z(0); \ return select(src, batch<TYPE, N>(~z), batch<TYPE, N>(z)); \ } #define XSIMD_DEFINE_BITWISE_CAST_FLOAT(TYPE, N) \ inline batch<TYPE, N> bitwise_cast(const batch_bool<TYPE, N>& src) \ { \ TYPE z0(0), z1(0); \ using int_type = as_unsigned_integer_t<TYPE>; \ *reinterpret_cast<int_type*>(&z1) = ~int_type(0); \ return select(src, batch<TYPE, N>(z1), batch<TYPE ,N>(z0)); \ } #define XSIMD_DEFINE_BITWISE_CAST_ALL(NMIN) \ XSIMD_DEFINE_BITWISE_CAST_FLOAT(double, NMIN) \ XSIMD_DEFINE_BITWISE_CAST_FLOAT(float, NMIN * 2) \ XSIMD_DEFINE_BITWISE_CAST(int64_t, NMIN) \ XSIMD_DEFINE_BITWISE_CAST(uint64_t, NMIN) \ XSIMD_DEFINE_BITWISE_CAST(int32_t, NMIN * 2) \ XSIMD_DEFINE_BITWISE_CAST(uint32_t, NMIN * 2) \ XSIMD_DEFINE_BITWISE_CAST(int16_t, NMIN * 4) \ XSIMD_DEFINE_BITWISE_CAST(uint16_t, NMIN * 4) \ XSIMD_DEFINE_BITWISE_CAST(int8_t, NMIN * 8) \ XSIMD_DEFINE_BITWISE_CAST(uint8_t, NMIN * 8) /**************************** * simd_base implementation * ****************************/ /** * @name Static downcast functions */ //@{ /** * Returns a reference to the batch type used for computation. */ template <class X> inline auto simd_base<X>::operator()() -> batch_reference { return derived_cast().get(); } /** * Returns a constant reference to the batch type used for computation. */ template <class X> inline auto simd_base<X>::operator()() const -> const_batch_reference { return derived_cast().get(); } /** * Returns a reference to the actual derived type of simd_base. */ template <class X> inline X& simd_base<X>::derived_cast() { return *static_cast<X*>(this); } /** * Returns a constant reference to the actual derived type of simd_base. */ template <class X> inline const X& simd_base<X>::derived_cast() const { return *static_cast<const X*>(this); } //@} /***************************** * simd_batch implementation * *****************************/ template <class X> inline simd_batch<X>::simd_batch(storage_type value) : m_value(value) { } /** * @name Arithmetic computed assignment */ //@{ /** * Adds the batch \c rhs to \c this. * @param rhs the batch to add. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator+=(const X& rhs) { (*this)() = (*this)() + rhs; return (*this)(); } /** * Adds the scalar \c rhs to each value contained in \c this. * @param rhs the scalar to add. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator+=(const value_type& rhs) { (*this)() = (*this)() + X(rhs); return (*this)(); } /** * Substracts the batch \c rhs to \c this. * @param rhs the batch to substract. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator-=(const X& rhs) { (*this)() = (*this)() - rhs; return (*this)(); } /** * Substracts the scalar \c rhs to each value contained in \c this. * @param rhs the scalar to substract. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator-=(const value_type& rhs) { (*this)() = (*this)() - X(rhs); return (*this)(); } /** * Multiplies \c this with the batch \c rhs. * @param rhs the batch involved in the multiplication. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator*=(const X& rhs) { (*this)() = (*this)() * rhs; return (*this)(); } /** * Multiplies each scalar contained in \c this with the scalar \c rhs. * @param rhs the scalar involved in the multiplication. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator*=(const value_type& rhs) { (*this)() = (*this)() * X(rhs); return (*this)(); } /** * Divides \c this by the batch \c rhs. * @param rhs the batch involved in the division. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator/=(const X& rhs) { (*this)() = (*this)() / rhs; return (*this)(); } /** * Divides each scalar contained in \c this by the scalar \c rhs. * @param rhs the scalar involved in the division. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator/=(const value_type& rhs) { (*this)() = (*this)() / X(rhs); return (*this)(); } //@} /** * @name Bitwise computed assignment */ /** * Assigns the bitwise and of \c rhs and \c this. * @param rhs the batch involved in the operation. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator&=(const X& rhs) { (*this)() = (*this)() & rhs; return (*this)(); } /** * Assigns the bitwise or of \c rhs and \c this. * @param rhs the batch involved in the operation. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator|=(const X& rhs) { (*this)() = (*this)() | rhs; return (*this)(); } /** * Assigns the bitwise xor of \c rhs and \c this. * @param rhs the batch involved in the operation. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator^=(const X& rhs) { (*this)() = (*this)() ^ rhs; return (*this)(); } //@} /** * @name Increment and decrement operators */ //@{ /** * Pre-increment operator. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator++() { (*this)() += value_type(1); return (*this)(); } /** * Post-increment operator. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator++(int) { X tmp = (*this)(); (*this)() += value_type(1); return tmp; } /** * Pre-decrement operator. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator--() { (*this)() -= value_type(1); return (*this)(); } /** * Post-decrement operator. * @return a reference to \c this. */ template <class X> inline X& simd_batch<X>::operator--(int) { X tmp = (*this)(); (*this)() -= value_type(1); return tmp; } //@} template <class X> inline X& simd_batch<X>::load_aligned(const char* src) { return (*this)().load_aligned(reinterpret_cast<const char_itype*>(src)); } template <class X> inline X& simd_batch<X>::load_unaligned(const char* src) { return (*this)().load_unaligned(reinterpret_cast<const char_itype*>(src)); } template <class X> void simd_batch<X>::store_aligned(char* dst) const { return (*this)().store_aligned(reinterpret_cast<char_itype*>(dst)); } template <class X> void simd_batch<X>::store_unaligned(char* dst) const { return (*this)().store_unaligned(reinterpret_cast<char_itype*>(dst)); } template <class X> inline auto simd_batch<X>::get() -> batch_reference { return this->derived_cast(); } template <class X> inline auto simd_batch<X>::get() const -> const_batch_reference { return this->derived_cast(); } template <class X> inline auto simd_batch<X>::operator[](std::size_t index) -> value_type& { return m_array[index & (size - 1)]; } template <class X> inline auto simd_batch<X>::operator[](std::size_t index) const -> const value_type& { return m_array[index & (size - 1)]; } template <class X> inline auto simd_batch<X>::begin() -> iterator { return m_array; } template <class X> inline auto simd_batch<X>::end() -> iterator { return m_array + size; } template <class X> inline auto simd_batch<X>::begin() const -> const_iterator { return cbegin(); } template <class X> inline auto simd_batch<X>::end() const -> const_iterator { return cend(); } template <class X> inline auto simd_batch<X>::cbegin() const -> const_iterator { return m_array; } template <class X> inline auto simd_batch<X>::cend() const -> const_iterator { return m_array + size; } template <class X> inline auto simd_batch<X>::rbegin() -> reverse_iterator { return reverse_iterator(end()); } template <class X> inline auto simd_batch<X>::rend() -> reverse_iterator { return reverse_iterator(begin()); } template <class X> inline auto simd_batch<X>::rbegin() const -> const_reverse_iterator { return crbegin(); } template <class X> inline auto simd_batch<X>::rend() const -> const_reverse_iterator { return crend(); } template <class X> inline auto simd_batch<X>::crbegin() const -> const_reverse_iterator { return const_reverse_iterator(end()); } template <class X> inline auto simd_batch<X>::crend() const -> const_reverse_iterator { return const_reverse_iterator(begin()); } #define XSIMD_UNARY_OP(OP, FUNC) \ template <class X> \ inline batch_type_t<X> operator OP(const simd_base<X>& rhs) \ { \ using value_type = typename simd_batch_traits<X>::value_type; \ using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; \ return kernel::FUNC(rhs()); \ } #define XSIMD_BINARY_OP(OP, FUNC) \ template <class X, class Y> \ inline batch_type_t<X> operator OP(const simd_base<X>& lhs, const simd_base<Y>& rhs) \ { \ using value_type = typename simd_batch_traits<X>::value_type; \ using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; \ return kernel::FUNC(lhs(), rhs()); \ } \ \ template <class X> \ inline batch_type_t<X> operator OP(const typename simd_batch_traits<X>::value_type& lhs, \ const simd_base<X>& rhs) \ { \ return batch_type_t<X>(lhs) OP rhs(); \ } \ \ template <class X> \ inline batch_type_t<X> operator OP(const simd_base<X>& lhs, \ const typename simd_batch_traits<X>::value_type& rhs) \ { \ return lhs() OP batch_type_t<X>(rhs); \ } #define XSIMD_BINARY_BOOL_OP(OP, FUNC) \ template <class X> \ inline typename simd_batch_traits<X>::batch_bool_type operator OP(const simd_base<X>& lhs, \ const simd_base<X>& rhs) \ { \ using value_type = typename simd_batch_traits<X>::value_type; \ using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; \ return kernel::FUNC(lhs(), rhs()); \ } \ \ template <class X> \ inline typename simd_batch_traits<X>::batch_bool_type operator OP( \ const typename simd_batch_traits<X>::value_type& lhs, const simd_base<X>& rhs) \ { \ return batch_type_t<X>(lhs) OP rhs(); \ } \ \ template <class X> \ inline typename simd_batch_traits<X>::batch_bool_type operator OP( \ const simd_base<X>& lhs, const typename simd_batch_traits<X>::value_type& rhs) \ { \ return lhs() OP batch_type_t<X>(rhs); \ } #define XSIMD_BINARY_BOOL_OP_DERIVED(OP, FUNC) \ template <class X> \ inline typename simd_batch_traits<X>::batch_bool_type operator OP(const simd_base<X>& lhs, \ const simd_base<X>& rhs) \ { \ return FUNC; \ } \ \ template <class X> \ inline typename simd_batch_traits<X>::batch_bool_type operator OP( \ const typename simd_batch_traits<X>::value_type& lhs, const simd_base<X>& rhs) \ { \ return FUNC; \ } \ \ template <class X> \ inline typename simd_batch_traits<X>::batch_bool_type operator OP( \ const simd_base<X>& lhs, const typename simd_batch_traits<X>::value_type& rhs) \ { \ return FUNC; \ } /** * @defgroup simd_batch_arithmetic Arithmetic operators */ /** * @ingroup simd_batch_arithmetic * * Computes the opposite of the batch \c rhs. * @tparam X the actual type of batch. * @param rhs batch involved in the operation. * @return the opposite of \c rhs. */ template <class X> inline batch_type_t<X> operator-(const simd_base<X>& rhs); XSIMD_UNARY_OP(-, neg) /** * @ingroup simd_batch_arithmetic * * No-op on \c rhs. * @tparam X the actual type of batch. * @param rhs batch involved in the operation. * @return \c rhs. */ template <class X> inline X operator+(const simd_batch<X>& rhs) { return rhs(); } /** * @ingroup simd_batch_arithmetic * * Computes the sum of the batches \c lhs and \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the addition. * @param rhs batch involved in the addition. * @return the result of the addition. */ template <class X, class Y> batch_type_t<X> operator+(const simd_base<X>& lhs, const simd_base<Y>& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the sum of the batch \c lhs and the scalar \c rhs. Equivalent to the * sum of two batches where all the values of the second one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the addition. * @param rhs scalar involved in the addition. * @return the result of the addition. */ template <class X> batch_type_t<X> operator+(const simd_base<X>& lhs, const typename simd_batch_traits<X>::value_type& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the sum of the scalar \c lhs and the batch \c rhs. Equivalent to the * sum of two batches where all the values of the first one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs scalar involved in the addition. * @param rhs batch involved in the addition. * @return the result of the addition. */ template <class X> batch_type_t<X> operator+(const typename simd_batch_traits<X>::value_type& lhs, const simd_base<X>& rhs); XSIMD_BINARY_OP(+, add) /** * @ingroup simd_batch_arithmetic * * Computes the difference of the batches \c lhs and \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the difference. * @param rhs batch involved in the difference. * @return the result of the difference. */ template <class X, class Y> batch_type_t<X> operator-(const simd_base<X>& lhs, const simd_base<Y>& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the difference of the batch \c lhs and the scalar \c rhs. Equivalent to the * difference of two batches where all the values of the second one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the difference. * @param rhs scalar involved in the difference. * @return the result of the difference. */ template <class X> batch_type_t<X> operator-(const simd_base<X>& lhs, const typename simd_batch_traits<X>::value_type& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the difference of the scalar \c lhs and the batch \c rhs. Equivalent to the * difference of two batches where all the values of the first one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs scalar involved in the difference. * @param rhs batch involved in the difference. * @return the result of the difference. */ template <class X> batch_type_t<X> operator-(const typename simd_batch_traits<X>::value_type& lhs, const simd_base<X>& rhs); XSIMD_BINARY_OP(-, sub) /** * @ingroup simd_batch_arithmetic * * Computes the product of the batches \c lhs and \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the product. * @param rhs batch involved in the product. * @return the result of the product. */ template <class X, class Y> batch_type_t<X> operator*(const simd_base<X>& lhs, const simd_base<Y>& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the product of the batch \c lhs and the scalar \c rhs. Equivalent to the * product of two batches where all the values of the second one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the product. * @param rhs scalar involved in the product. * @return the result of the product. */ template <class X> batch_type_t<X> operator*(const simd_base<X>& lhs, const typename simd_batch_traits<X>::value_type& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the product of the scalar \c lhs and the batch \c rhs. Equivalent to the * difference of two batches where all the values of the first one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs scalar involved in the product. * @param rhs batch involved in the product. * @return the result of the product. */ template <class X> batch_type_t<X> operator*(const typename simd_batch_traits<X>::value_type& lhs, const simd_base<X>& rhs); XSIMD_BINARY_OP(*, mul) /** * @ingroup simd_batch_arithmetic * * Computes the division of the batch \c lhs by the batch \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the division. * @param rhs batch involved in the division. * @return the result of the division. */ template <class X, class Y> batch_type_t<X> operator/(const simd_base<X>& lhs, const simd_base<Y>& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the division of the batch \c lhs by the scalar \c rhs. Equivalent to the * division of two batches where all the values of the second one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the division. * @param rhs scalar involved in the division. * @return the result of the division. */ template <class X> batch_type_t<X> operator/(const simd_base<X>& lhs, const typename simd_batch_traits<X>::value_type& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the division of the scalar \c lhs and the batch \c rhs. Equivalent to the * difference of two batches where all the values of the first one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs scalar involved in the division. * @param rhs batch involved in the division. * @return the result of the division. */ template <class X> batch_type_t<X> operator/(const typename simd_batch_traits<X>::value_type& lhs, const simd_base<X>& rhs); XSIMD_BINARY_OP(/, div) /** * @ingroup simd_batch_arithmetic * * Computes the integer modulo of the batch \c lhs by the batch \c rhs. * @param lhs batch involved in the modulo. * @param rhs batch involved in the modulo. * @return the result of the modulo. */ template <class X, class Y> batch_type_t<X> operator%(const simd_base<X>& lhs, const simd_base<Y>& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the integer modulo of the batch \c lhs by the scalar \c rhs. Equivalent to the * modulo of two batches where all the values of the second one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the modulo. * @param rhs scalar involved in the modulo. * @return the result of the modulo. */ template <class X> batch_type_t<X> operator%(const simd_base<X>& lhs, const typename simd_batch_traits<X>::value_type& rhs); /** * @ingroup simd_batch_arithmetic * * Computes the integer modulo of the scalar \c lhs and the batch \c rhs. Equivalent to the * difference of two batches where all the values of the first one are initialized to * \c rhs. * @tparam X the actual type of batch. * @param lhs scalar involved in the modulo. * @param rhs batch involved in the modulo. * @return the result of the modulo. */ template <class X> batch_type_t<X> operator%(const typename simd_batch_traits<X>::value_type& lhs, const simd_base<X>& rhs); XSIMD_BINARY_OP(%, mod) /** * @defgroup simd_batch_comparison Comparison operators */ /** * @ingroup simd_batch_comparison * * Element-wise equality comparison of batches \c lhs and \c rhs. * @param lhs batch involved in the comparison. * @param rhs batch involved in the comparison. * @return a boolean batch. */ template <class X> typename simd_batch_traits<X>::batch_bool_type operator==(const simd_base<X>& lhs, const simd_base<X>& rhs); XSIMD_BINARY_BOOL_OP(==, eq) /** * @ingroup simd_batch_comparison * * Element-wise inequality comparison of batches \c lhs and \c rhs. * @param lhs batch involved in the comparison. * @param rhs batch involved in the comparison. * @return a boolean batch. */ template <class X> typename simd_batch_traits<X>::batch_bool_type operator!=(const simd_base<X>& lhs, const simd_base<X>& rhs); XSIMD_BINARY_BOOL_OP(!=, neq) /** * @ingroup simd_batch_comparison * * Element-wise lesser than comparison of batches \c lhs and \c rhs. * @param lhs batch involved in the comparison. * @param rhs batch involved in the comparison. * @return a boolean batch. */ template <class X> typename simd_batch_traits<X>::batch_bool_type operator<(const simd_base<X>& lhs, const simd_base<X>& rhs); XSIMD_BINARY_BOOL_OP(<, lt) /** * @ingroup simd_batch_comparison * * Element-wise lesser or equal to comparison of batches \c lhs and \c rhs. * @param lhs batch involved in the comparison. * @param rhs batch involved in the comparison. * @return a boolean batch. */ template <class X> typename simd_batch_traits<X>::batch_bool_type operator<=(const simd_base<X>& lhs, const simd_base<X>& rhs); XSIMD_BINARY_BOOL_OP(<=, lte) /** * @ingroup simd_batch_comparison * * Element-wise greater than comparison of batches \c lhs and \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the comparison. * @param rhs batch involved in the comparison. * @return a boolean batch. */ template <class X> typename simd_batch_traits<X>::batch_bool_type operator>(const simd_base<X>& lhs, const simd_base<X>& rhs); XSIMD_BINARY_BOOL_OP_DERIVED(>, rhs() < lhs()) /** * @ingroup simd_batch_comparison * * Element-wise greater or equal comparison of batches \c lhs and \c rhs. * @tparam X the actual type of batch. * @param lhs batch involved in the comparison. * @param rhs batch involved in the comparison. * @return a boolean batch. */ template <class X> typename simd_batch_traits<X>::batch_bool_type operator>=(const simd_base<X>& lhs, const simd_base<X>& rhs); XSIMD_BINARY_BOOL_OP_DERIVED(>=, rhs() <= lhs()) /** * @defgroup simd_batch_bitwise Bitwise operators */ /** * @ingroup simd_batch_bitwise * * Computes the bitwise and of the batches \c lhs and \c rhs. * @param lhs batch involved in the operation. * @param rhs batch involved in the operation. * @return the result of the bitwise and. */ template <class X, class Y> inline batch_type_t<X> operator&(const simd_base<X>& lhs, const simd_base<Y>& rhs); XSIMD_BINARY_OP(&, bitwise_and) /** * @ingroup simd_batch_bitwise * * Computes the bitwise or of the batches \c lhs and \c rhs. * @param lhs batch involved in the operation. * @param rhs batch involved in the operation. * @return the result of the bitwise or. */ template <class X, class Y> inline batch_type_t<X> operator|(const simd_base<X>& lhs, const simd_base<Y>& rhs); XSIMD_BINARY_OP(|, bitwise_or) /** * @ingroup simd_batch_bitwise * * Computes the bitwise xor of the batches \c lhs and \c rhs. * @param lhs batch involved in the operation. * @param rhs batch involved in the operation. * @return the result of the bitwise xor. */ template <class X, class Y> inline batch_type_t<X> operator^(const simd_base<X>& lhs, const simd_base<Y>& rhs); XSIMD_BINARY_OP(^, bitwise_xor) /** * @ingroup simd_batch_bitwise * * Computes the bitwise not of the batches \c lhs and \c rhs. * @param rhs batch involved in the operation. * @return the result of the bitwise not. */ template <class X> batch_type_t<X> operator~(const simd_base<X>& rhs); XSIMD_UNARY_OP(~, bitwise_not) /** * @ingroup simd_batch_bitwise * * Computes the bitwise andnot of the batches \c lhs and \c rhs. * @param lhs batch involved in the operation. * @param rhs batch involved in the operation. * @return the result of the bitwise andnot. */ template <class X> inline batch_type_t<X> bitwise_andnot(const simd_batch<X>& lhs, const simd_batch<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; \ using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; \ return kernel::bitwise_andnot(lhs(), rhs()); } /** * Element-wise not of \c rhs. * @tparam X the actual type of batch. * @param rhs batch involved in the logical not operation. * @return boolean batch. */ template <class X> inline typename simd_batch_traits<X>::batch_bool_type operator!(const simd_base<X>& rhs) { using b_type = typename simd_batch_traits<X>::batch_type; return rhs() == b_type(0); } /** * Returns the smaller values of the batches \c lhs and \c rhs. * @param lhs a batch of integer or floating point values. * @param rhs a batch of integer or floating point values. * @return a batch of the smaller values. */ template <class X> inline batch_type_t<X> min(const simd_base<X>& lhs, const simd_base<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::min(lhs(), rhs()); } /** * Returns the larger values of the batches \c lhs and \c rhs. * @param lhs a batch of integer or floating point values. * @param rhs a batch of integer or floating point values. * @return a batch of the larger values. */ template <class X> inline batch_type_t<X> max(const simd_base<X>& lhs, const simd_base<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::max(lhs(), rhs()); } /** * Returns the smaller values of the batches \c lhs and \c rhs. * @param lhs a batch of floating point values. * @param rhs a batch of floating point values. * @return a batch of the smaller values. */ template <class X> inline batch_type_t<X> fmin(const simd_batch<X>& lhs, const simd_batch<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::fmin(lhs(), rhs()); } /** * Returns the larger values of the batches \c lhs and \c rhs. * @param lhs a batch of floating point values. * @param rhs a batch of floating point values. * @return a batch of the larger values. */ template <class X> inline batch_type_t<X> fmax(const simd_batch<X>& lhs, const simd_batch<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::fmax(lhs(), rhs()); } /** * Computes the absolute values of each scalar in the batch \c rhs. * @param rhs batch of integer or floating point values. * @return the asbolute values of \c rhs. */ template <class X> inline real_batch_type_t<X> abs(const simd_base<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::abs(rhs()); } /** * Computes the absolute values of each scalar in the batch \c rhs. * @param rhs batch floating point values. * @return the asbolute values of \c rhs. */ template <class X> inline batch_type_t<X> fabs(const simd_base<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::fabs(rhs()); } /** * Computes the square root of the batch \c rhs. * @param rhs batch of floating point values. * @return the square root of \c rhs. */ template <class X> inline batch_type_t<X> sqrt(const simd_base<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::sqrt(rhs()); } /** * Computes <tt>(x*y) + z</tt> in a single instruction when possible. * @param x a batch of integer or floating point values. * @param y a batch of integer or floating point values. * @param z a batch of integer or floating point values. * @return the result of the fused multiply-add operation. */ template <class X> inline batch_type_t<X> fma(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::fma(x(), y(), z()); } /** * Computes <tt>(x*y) - z</tt> in a single instruction when possible. * @param x a batch of integer or floating point values. * @param y a batch of integer or floating point values. * @param z a batch of integer or floating point values. * @return the result of the fused multiply-sub operation. */ template <class X> inline batch_type_t<X> fms(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::fms(x(), y(), z()); } /** * Computes <tt>-(x*y) + z</tt> in a single instruction when possible. * @param x a batch of integer or floating point values. * @param y a batch of integer or floating point values. * @param z a batch of integer or floating point values. * @return the result of the fused negated multiply-add operation. */ template <class X> inline batch_type_t<X> fnma(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::fnma(x(), y(), z()); } /** * Computes <tt>-(x*y) - z</tt> in a single instruction when possible. * @param x a batch of integer or floating point values. * @param y a batch of integer or floating point values. * @param z a batch of integer or floating point values. * @return the result of the fused negated multiply-sub operation. */ template <class X> inline batch_type_t<X> fnms(const simd_base<X>& x, const simd_base<X>& y, const simd_base<X>& z) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::fnms(x(), y(), z()); } /** * @defgroup simd_batch_reducers Reducers */ /** * @ingroup simd_batch_reducers * * Adds all the scalars of the batch \c rhs. * @param rhs batch involved in the reduction * @return the result of the reduction. */ template <class X> inline typename simd_batch_traits<X>::value_type hadd(const simd_base<X>& rhs) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::hadd(rhs()); } /** * @ingroup simd_batch_reducers * * Parallel horizontal addition: adds the scalars of each batch * in the array pointed by \c row and store them in a returned * batch. * @param row an array of \c N batches * @return the result of the reduction. */ template <class X> inline batch_type_t<X> haddp(const simd_batch<X>* row) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::haddp(row); } /** * @defgroup simd_batch_miscellaneous Miscellaneous */ /** * @ingroup simd_batch_miscellaneous * * Ternary operator for batches: selects values from the batches \c a or \c b * depending on the boolean values in \c cond. Equivalent to * \code{.cpp} * for(std::size_t i = 0; i < N; ++i) * res[i] = cond[i] ? a[i] : b[i]; * \endcode * @param cond batch condition. * @param a batch values for truthy condition. * @param b batch value for falsy condition. * @return the result of the selection. */ template <class X> inline batch_type_t<X> select(const typename simd_batch_traits<X>::batch_bool_type& cond, const simd_base<X>& a, const simd_base<X>& b) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::select(cond(), a(), b()); } /** * Determines if the scalars in the given batch \c x are NaN values. * @param x batch of floating point values. * @return a batch of booleans. */ template <class X> inline typename simd_batch_traits<X>::batch_bool_type isnan(const simd_base<X>& x) { using value_type = typename simd_batch_traits<X>::value_type; using kernel = detail::batch_kernel<value_type, simd_batch_traits<X>::size>; return kernel::isnan(x()); } /** * Insert the batch \c rhs into the stream \c out. * @tparam X the actual type of batch. * @param out the output stream. * @param rhs the batch to output. * @return the output stream. */ template <class X> inline std::ostream& operator<<(std::ostream& out, const simd_batch<X>& rhs) { out << '('; std::size_t s = simd_batch<X>::size; for (std::size_t i = 0; i < s - 1; ++i) { out << rhs()[i] << ", "; } out << rhs()[s - 1] << ')'; return out; } /****************************************** * generic batch operators implementation * ******************************************/ #define GENERIC_OPERATOR_IMPLEMENTATION(OP) \ using traits = simd_batch_traits<batch<T, N>>; \ constexpr std::size_t align = traits::align; \ alignas(align) T tmp_lhs[N]; \ alignas(align) T tmp_rhs[N]; \ alignas(align) T tmp_res[N]; \ lhs.store_aligned(tmp_lhs); \ rhs.store_aligned(tmp_rhs); \ for (std::size_t i = 0; i < traits::size; ++i) \ { \ tmp_res[i] = tmp_lhs[i] OP tmp_rhs[i]; \ } \ return batch<T, N>(tmp_res, aligned_mode()) template <class T, std::size_t N> inline batch<T, N> operator&&(const batch<T, N>& lhs, const batch<T, N>& rhs) { GENERIC_OPERATOR_IMPLEMENTATION(&&); } template <class T, std::size_t N> inline batch<T, N> operator||(const batch<T, N>& lhs, const batch<T, N>& rhs) { GENERIC_OPERATOR_IMPLEMENTATION(||); } template <class T, std::size_t N> inline batch<T, N> operator<<(const batch<T, N>& lhs, const batch<T, N>& rhs) { GENERIC_OPERATOR_IMPLEMENTATION(<<); } template <class T, std::size_t N> inline batch<T, N> operator>>(const batch<T, N>& lhs, const batch<T, N>& rhs) { GENERIC_OPERATOR_IMPLEMENTATION(>>); } /***************************************** * bitwise cast functions implementation * *****************************************/ template <class B, std::size_t N> inline B bitwise_cast(const batch<float, N>& x) { return bitwise_cast_impl<batch<float, N>, B>::run(x); } template <class B, std::size_t N> inline B bitwise_cast(const batch<double, N>& x) { return bitwise_cast_impl<batch<double, N>, B>::run(x); } template <class B, std::size_t N> inline B bitwise_cast(const batch<int32_t, N>& x) { return bitwise_cast_impl<batch<int32_t, N>, B>::run(x); } template <class B, std::size_t N> inline B bitwise_cast(const batch<int64_t, N>& x) { return bitwise_cast_impl<batch<int64_t, N>, B>::run(x); } template <class T, std::size_t N> inline batch<T, N> bitwise_cast(const batch_bool<T, N>& src) { return batch<T, N>(src.get_value()); } } #endif
38.289611
139
0.531566
PierreBlancfat
70acd4552510744f391fe70cfb97e67ea2ebc478
459
cpp
C++
src/function/scalar/trigonometrics_functions.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/function/scalar/trigonometrics_functions.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/function/scalar/trigonometrics_functions.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
#include "guinsoodb/function/scalar/trigonometric_functions.hpp" #include "guinsoodb/common/vector_operations/vector_operations.hpp" #include "guinsoodb/common/exception.hpp" namespace guinsoodb { void BuiltinFunctions::RegisterTrigonometricsFunctions() { Register<SinFun>(); Register<CosFun>(); Register<TanFun>(); Register<AsinFun>(); Register<AcosFun>(); Register<AtanFun>(); Register<CotFun>(); Register<Atan2Fun>(); } } // namespace guinsoodb
24.157895
67
0.769063
GuinsooLab
70ad47aad3ae1f96e94be9dfb3876b7687a13db6
16,278
cpp
C++
MultiSource/Benchmarks/7zip/CPP/7zip/Archive/Common/HandlerOut.cpp
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
1,975
2015-07-03T07:00:50.000Z
2022-03-31T20:04:04.000Z
third_party/lzma/files/CPP/7zip/Archive/Common/HandlerOut.cpp
rodriguez74745/omaha
a244aea380b48fc488a0555c3fa51a2e03677557
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
third_party/lzma/files/CPP/7zip/Archive/Common/HandlerOut.cpp
rodriguez74745/omaha
a244aea380b48fc488a0555c3fa51a2e03677557
[ "Apache-2.0" ]
685
2015-07-18T11:24:49.000Z
2022-03-30T20:50:12.000Z
// HandlerOut.cpp #include "StdAfx.h" #include "../../../Common/StringToInt.h" #include "../../../Windows/PropVariant.h" #ifndef _7ZIP_ST #include "../../../Windows/System.h" #endif #include "../../ICoder.h" #include "../Common/ParseProperties.h" #include "HandlerOut.h" using namespace NWindows; namespace NArchive { static const wchar_t *kCopyMethod = L"Copy"; static const wchar_t *kLZMAMethodName = L"LZMA"; static const wchar_t *kLZMA2MethodName = L"LZMA2"; static const wchar_t *kBZip2MethodName = L"BZip2"; static const wchar_t *kPpmdMethodName = L"PPMd"; static const wchar_t *kDeflateMethodName = L"Deflate"; static const wchar_t *kDeflate64MethodName = L"Deflate64"; static const wchar_t *kLzmaMatchFinderX1 = L"HC4"; static const wchar_t *kLzmaMatchFinderX5 = L"BT4"; static const UInt32 kLzmaAlgoX1 = 0; static const UInt32 kLzmaAlgoX5 = 1; static const UInt32 kLzmaDicSizeX1 = 1 << 16; static const UInt32 kLzmaDicSizeX3 = 1 << 20; static const UInt32 kLzmaDicSizeX5 = 1 << 24; static const UInt32 kLzmaDicSizeX7 = 1 << 25; static const UInt32 kLzmaDicSizeX9 = 1 << 26; static const UInt32 kLzmaFastBytesX1 = 32; static const UInt32 kLzmaFastBytesX7 = 64; static const UInt32 kPpmdMemSizeX1 = (1 << 22); static const UInt32 kPpmdMemSizeX5 = (1 << 24); static const UInt32 kPpmdMemSizeX7 = (1 << 26); static const UInt32 kPpmdMemSizeX9 = (192 << 20); static const UInt32 kPpmdOrderX1 = 4; static const UInt32 kPpmdOrderX5 = 6; static const UInt32 kPpmdOrderX7 = 16; static const UInt32 kPpmdOrderX9 = 32; static const UInt32 kDeflateAlgoX1 = 0; static const UInt32 kDeflateAlgoX5 = 1; static const UInt32 kDeflateFastBytesX1 = 32; static const UInt32 kDeflateFastBytesX7 = 64; static const UInt32 kDeflateFastBytesX9 = 128; static const UInt32 kDeflatePassesX1 = 1; static const UInt32 kDeflatePassesX7 = 3; static const UInt32 kDeflatePassesX9 = 10; static const UInt32 kBZip2NumPassesX1 = 1; static const UInt32 kBZip2NumPassesX7 = 2; static const UInt32 kBZip2NumPassesX9 = 7; static const UInt32 kBZip2DicSizeX1 = 100000; static const UInt32 kBZip2DicSizeX3 = 500000; static const UInt32 kBZip2DicSizeX5 = 900000; static const wchar_t *kDefaultMethodName = kLZMAMethodName; static const wchar_t *kLzmaMatchFinderForHeaders = L"BT2"; static const UInt32 kDictionaryForHeaders = 1 << 20; static const UInt32 kNumFastBytesForHeaders = 273; static const UInt32 kAlgorithmForHeaders = kLzmaAlgoX5; static bool AreEqual(const UString &methodName, const wchar_t *s) { return (methodName.CompareNoCase(s) == 0); } bool COneMethodInfo::IsLzma() const { return AreEqual(MethodName, kLZMAMethodName) || AreEqual(MethodName, kLZMA2MethodName); } static inline bool IsBZip2Method(const UString &methodName) { return AreEqual(methodName, kBZip2MethodName); } static inline bool IsPpmdMethod(const UString &methodName) { return AreEqual(methodName, kPpmdMethodName); } static inline bool IsDeflateMethod(const UString &methodName) { return AreEqual(methodName, kDeflateMethodName) || AreEqual(methodName, kDeflate64MethodName); } struct CNameToPropID { PROPID PropID; VARTYPE VarType; const wchar_t *Name; }; static CNameToPropID g_NameToPropID[] = { { NCoderPropID::kBlockSize, VT_UI4, L"C" }, { NCoderPropID::kDictionarySize, VT_UI4, L"D" }, { NCoderPropID::kUsedMemorySize, VT_UI4, L"MEM" }, { NCoderPropID::kOrder, VT_UI4, L"O" }, { NCoderPropID::kPosStateBits, VT_UI4, L"PB" }, { NCoderPropID::kLitContextBits, VT_UI4, L"LC" }, { NCoderPropID::kLitPosBits, VT_UI4, L"LP" }, { NCoderPropID::kEndMarker, VT_BOOL, L"eos" }, { NCoderPropID::kNumPasses, VT_UI4, L"Pass" }, { NCoderPropID::kNumFastBytes, VT_UI4, L"fb" }, { NCoderPropID::kMatchFinderCycles, VT_UI4, L"mc" }, { NCoderPropID::kAlgorithm, VT_UI4, L"a" }, { NCoderPropID::kMatchFinder, VT_BSTR, L"mf" }, { NCoderPropID::kNumThreads, VT_UI4, L"mt" }, { NCoderPropID::kDefaultProp, VT_UI4, L"" } }; static bool ConvertProperty(PROPVARIANT srcProp, VARTYPE varType, NCOM::CPropVariant &destProp) { if (varType == srcProp.vt) { destProp = srcProp; return true; } if (varType == VT_UI1) { if (srcProp.vt == VT_UI4) { UInt32 value = srcProp.ulVal; if (value > 0xFF) return false; destProp = (Byte)value; return true; } } else if (varType == VT_BOOL) { bool res; if (SetBoolProperty(res, srcProp) != S_OK) return false; destProp = res; return true; } return false; } static int FindPropIdExact(const UString &name) { for (int i = 0; i < sizeof(g_NameToPropID) / sizeof(g_NameToPropID[0]); i++) if (name.CompareNoCase(g_NameToPropID[i].Name) == 0) return i; return -1; } static int FindPropIdStart(const UString &name) { for (int i = 0; i < sizeof(g_NameToPropID) / sizeof(g_NameToPropID[0]); i++) { UString t = g_NameToPropID[i].Name; if (t.CompareNoCase(name.Left(t.Length())) == 0) return i; } return -1; } static void SetMethodProp(COneMethodInfo &m, PROPID propID, const NCOM::CPropVariant &value) { for (int j = 0; j < m.Props.Size(); j++) if (m.Props[j].Id == propID) return; CProp prop; prop.Id = propID; prop.Value = value; m.Props.Add(prop); } void COutHandler::SetCompressionMethod2(COneMethodInfo &oneMethodInfo #ifndef _7ZIP_ST , UInt32 numThreads #endif ) { UInt32 level = _level; if (oneMethodInfo.MethodName.IsEmpty()) oneMethodInfo.MethodName = kDefaultMethodName; if (oneMethodInfo.IsLzma()) { UInt32 dicSize = (level >= 9 ? kLzmaDicSizeX9 : (level >= 7 ? kLzmaDicSizeX7 : (level >= 5 ? kLzmaDicSizeX5 : (level >= 3 ? kLzmaDicSizeX3 : kLzmaDicSizeX1)))); UInt32 algo = (level >= 5 ? kLzmaAlgoX5 : kLzmaAlgoX1); UInt32 fastBytes = (level >= 7 ? kLzmaFastBytesX7 : kLzmaFastBytesX1); const wchar_t *matchFinder = (level >= 5 ? kLzmaMatchFinderX5 : kLzmaMatchFinderX1); SetMethodProp(oneMethodInfo, NCoderPropID::kDictionarySize, dicSize); SetMethodProp(oneMethodInfo, NCoderPropID::kAlgorithm, algo); SetMethodProp(oneMethodInfo, NCoderPropID::kNumFastBytes, fastBytes); SetMethodProp(oneMethodInfo, NCoderPropID::kMatchFinder, matchFinder); #ifndef _7ZIP_ST SetMethodProp(oneMethodInfo, NCoderPropID::kNumThreads, numThreads); #endif } else if (IsDeflateMethod(oneMethodInfo.MethodName)) { UInt32 fastBytes = (level >= 9 ? kDeflateFastBytesX9 : (level >= 7 ? kDeflateFastBytesX7 : kDeflateFastBytesX1)); UInt32 numPasses = (level >= 9 ? kDeflatePassesX9 : (level >= 7 ? kDeflatePassesX7 : kDeflatePassesX1)); UInt32 algo = (level >= 5 ? kDeflateAlgoX5 : kDeflateAlgoX1); SetMethodProp(oneMethodInfo, NCoderPropID::kAlgorithm, algo); SetMethodProp(oneMethodInfo, NCoderPropID::kNumFastBytes, fastBytes); SetMethodProp(oneMethodInfo, NCoderPropID::kNumPasses, numPasses); } else if (IsBZip2Method(oneMethodInfo.MethodName)) { UInt32 numPasses = (level >= 9 ? kBZip2NumPassesX9 : (level >= 7 ? kBZip2NumPassesX7 : kBZip2NumPassesX1)); UInt32 dicSize = (level >= 5 ? kBZip2DicSizeX5 : (level >= 3 ? kBZip2DicSizeX3 : kBZip2DicSizeX1)); SetMethodProp(oneMethodInfo, NCoderPropID::kNumPasses, numPasses); SetMethodProp(oneMethodInfo, NCoderPropID::kDictionarySize, dicSize); #ifndef _7ZIP_ST SetMethodProp(oneMethodInfo, NCoderPropID::kNumThreads, numThreads); #endif } else if (IsPpmdMethod(oneMethodInfo.MethodName)) { UInt32 useMemSize = (level >= 9 ? kPpmdMemSizeX9 : (level >= 7 ? kPpmdMemSizeX7 : (level >= 5 ? kPpmdMemSizeX5 : kPpmdMemSizeX1))); UInt32 order = (level >= 9 ? kPpmdOrderX9 : (level >= 7 ? kPpmdOrderX7 : (level >= 5 ? kPpmdOrderX5 : kPpmdOrderX1))); SetMethodProp(oneMethodInfo, NCoderPropID::kUsedMemorySize, useMemSize); SetMethodProp(oneMethodInfo, NCoderPropID::kOrder, order); } } static void SplitParams(const UString &srcString, UStringVector &subStrings) { subStrings.Clear(); UString name; int len = srcString.Length(); if (len == 0) return; for (int i = 0; i < len; i++) { wchar_t c = srcString[i]; if (c == L':') { subStrings.Add(name); name.Empty(); } else name += c; } subStrings.Add(name); } static void SplitParam(const UString &param, UString &name, UString &value) { int eqPos = param.Find(L'='); if (eqPos >= 0) { name = param.Left(eqPos); value = param.Mid(eqPos + 1); return; } for(int i = 0; i < param.Length(); i++) { wchar_t c = param[i]; if (c >= L'0' && c <= L'9') { name = param.Left(i); value = param.Mid(i); return; } } name = param; } HRESULT COutHandler::SetParam(COneMethodInfo &oneMethodInfo, const UString &name, const UString &value) { CProp prop; int index = FindPropIdExact(name); if (index < 0) return E_INVALIDARG; const CNameToPropID &nameToPropID = g_NameToPropID[index]; prop.Id = nameToPropID.PropID; if (prop.Id == NCoderPropID::kBlockSize || prop.Id == NCoderPropID::kDictionarySize || prop.Id == NCoderPropID::kUsedMemorySize) { UInt32 dicSize; RINOK(ParsePropDictionaryValue(value, dicSize)); prop.Value = dicSize; } else { NCOM::CPropVariant propValue; if (nameToPropID.VarType == VT_BSTR) propValue = value; else if (nameToPropID.VarType == VT_BOOL) { bool res; if (!StringToBool(value, res)) return E_INVALIDARG; propValue = res; } else { UInt32 number; if (ParseStringToUInt32(value, number) == value.Length()) propValue = number; else propValue = value; } if (!ConvertProperty(propValue, nameToPropID.VarType, prop.Value)) return E_INVALIDARG; } oneMethodInfo.Props.Add(prop); return S_OK; } HRESULT COutHandler::SetParams(COneMethodInfo &oneMethodInfo, const UString &srcString) { UStringVector params; SplitParams(srcString, params); if (params.Size() > 0) oneMethodInfo.MethodName = params[0]; for (int i = 1; i < params.Size(); i++) { const UString &param = params[i]; UString name, value; SplitParam(param, name, value); RINOK(SetParam(oneMethodInfo, name, value)); } return S_OK; } HRESULT COutHandler::SetSolidSettings(const UString &s) { UString s2 = s; s2.MakeUpper(); for (int i = 0; i < s2.Length();) { const wchar_t *start = ((const wchar_t *)s2) + i; const wchar_t *end; UInt64 v = ConvertStringToUInt64(start, &end); if (start == end) { if (s2[i++] != 'E') return E_INVALIDARG; _solidExtension = true; continue; } i += (int)(end - start); if (i == s2.Length()) return E_INVALIDARG; wchar_t c = s2[i++]; switch(c) { case 'F': if (v < 1) v = 1; _numSolidFiles = v; break; case 'B': _numSolidBytes = v; _numSolidBytesDefined = true; break; case 'K': _numSolidBytes = (v << 10); _numSolidBytesDefined = true; break; case 'M': _numSolidBytes = (v << 20); _numSolidBytesDefined = true; break; case 'G': _numSolidBytes = (v << 30); _numSolidBytesDefined = true; break; default: return E_INVALIDARG; } } return S_OK; } HRESULT COutHandler::SetSolidSettings(const PROPVARIANT &value) { bool isSolid; switch(value.vt) { case VT_EMPTY: isSolid = true; break; case VT_BOOL: isSolid = (value.boolVal != VARIANT_FALSE); break; case VT_BSTR: if (StringToBool(value.bstrVal, isSolid)) break; return SetSolidSettings(value.bstrVal); default: return E_INVALIDARG; } if (isSolid) InitSolid(); else _numSolidFiles = 1; return S_OK; } void COutHandler::Init() { _removeSfxBlock = false; _compressHeaders = true; _encryptHeadersSpecified = false; _encryptHeaders = false; WriteCTime = false; WriteATime = false; WriteMTime = true; #ifndef _7ZIP_ST _numThreads = NSystem::GetNumberOfProcessors(); #endif _level = 5; _autoFilter = true; _volumeMode = false; _crcSize = 4; InitSolid(); } void COutHandler::BeforeSetProperty() { Init(); #ifndef _7ZIP_ST numProcessors = NSystem::GetNumberOfProcessors(); #endif mainDicSize = 0xFFFFFFFF; mainDicMethodIndex = 0xFFFFFFFF; minNumber = 0; _crcSize = 4; } HRESULT COutHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value) { UString name = nameSpec; name.MakeUpper(); if (name.IsEmpty()) return E_INVALIDARG; if (name[0] == 'X') { name.Delete(0); _level = 9; return ParsePropValue(name, value, _level); } if (name[0] == L'S') { name.Delete(0); if (name.IsEmpty()) return SetSolidSettings(value); if (value.vt != VT_EMPTY) return E_INVALIDARG; return SetSolidSettings(name); } if (name == L"CRC") { _crcSize = 4; name.Delete(0, 3); return ParsePropValue(name, value, _crcSize); } UInt32 number; int index = ParseStringToUInt32(name, number); UString realName = name.Mid(index); if (index == 0) { if(name.Left(2).CompareNoCase(L"MT") == 0) { #ifndef _7ZIP_ST RINOK(ParseMtProp(name.Mid(2), value, numProcessors, _numThreads)); #endif return S_OK; } if (name.CompareNoCase(L"RSFX") == 0) return SetBoolProperty(_removeSfxBlock, value); if (name.CompareNoCase(L"F") == 0) return SetBoolProperty(_autoFilter, value); if (name.CompareNoCase(L"HC") == 0) return SetBoolProperty(_compressHeaders, value); if (name.CompareNoCase(L"HCF") == 0) { bool compressHeadersFull = true; RINOK(SetBoolProperty(compressHeadersFull, value)); if (!compressHeadersFull) return E_INVALIDARG; return S_OK; } if (name.CompareNoCase(L"HE") == 0) { RINOK(SetBoolProperty(_encryptHeaders, value)); _encryptHeadersSpecified = true; return S_OK; } if (name.CompareNoCase(L"TC") == 0) return SetBoolProperty(WriteCTime, value); if (name.CompareNoCase(L"TA") == 0) return SetBoolProperty(WriteATime, value); if (name.CompareNoCase(L"TM") == 0) return SetBoolProperty(WriteMTime, value); if (name.CompareNoCase(L"V") == 0) return SetBoolProperty(_volumeMode, value); number = 0; } if (number > 10000) return E_FAIL; if (number < minNumber) return E_INVALIDARG; number -= minNumber; for(int j = _methods.Size(); j <= (int)number; j++) { COneMethodInfo oneMethodInfo; _methods.Add(oneMethodInfo); } COneMethodInfo &oneMethodInfo = _methods[number]; if (realName.Length() == 0) { if (value.vt != VT_BSTR) return E_INVALIDARG; RINOK(SetParams(oneMethodInfo, value.bstrVal)); } else { int index = FindPropIdStart(realName); if (index < 0) return E_INVALIDARG; const CNameToPropID &nameToPropID = g_NameToPropID[index]; CProp prop; prop.Id = nameToPropID.PropID; if (prop.Id == NCoderPropID::kBlockSize || prop.Id == NCoderPropID::kDictionarySize || prop.Id == NCoderPropID::kUsedMemorySize) { UInt32 dicSize; RINOK(ParsePropDictionaryValue(realName.Mid(MyStringLen(nameToPropID.Name)), value, dicSize)); prop.Value = dicSize; if (number <= mainDicMethodIndex) mainDicSize = dicSize; } else { int index = FindPropIdExact(realName); if (index < 0) return E_INVALIDARG; const CNameToPropID &nameToPropID = g_NameToPropID[index]; prop.Id = nameToPropID.PropID; if (!ConvertProperty(value, nameToPropID.VarType, prop.Value)) return E_INVALIDARG; } oneMethodInfo.Props.Add(prop); } return S_OK; } }
26.086538
103
0.65137
gmlueck
70afe5fc53240327b2189f4f833331891eeac2a2
3,256
hpp
C++
assemble.hpp
noah-witt/riscv-engine
4caf55da2d8e5d473ac7e0634bef6a1d5ddc728b
[ "MIT" ]
null
null
null
assemble.hpp
noah-witt/riscv-engine
4caf55da2d8e5d473ac7e0634bef6a1d5ddc728b
[ "MIT" ]
null
null
null
assemble.hpp
noah-witt/riscv-engine
4caf55da2d8e5d473ac7e0634bef6a1d5ddc728b
[ "MIT" ]
null
null
null
/** * @file assemble.hpp * @author Noah Witt (nawitt18@ole.augie.edu) * @version 0.1 * @date 2021-09-01 * */ #pragma once #include <string> #include <cstring> #include <vector> #include <list> #include <unordered_map> #include "./registers.hpp" #include "./memory.h" #include "./memory.t.hpp" #include "symbol.hpp" class AssembleConstants { public: static char registerNameSeperator; static std::string registerNames[]; static uint registerCount; static std::vector<std::vector<std::string>> getNamesAsList(); static int getID(std::string name); static std::string getStr(int i); }; enum class SymbolOrRegisterType { UNSET, SYMBOL, REGISTER, LOCATION_OFFSET, IMMEDIATE_VALUE, }; struct SymbolOrRegister { SymbolOrRegisterType t; std::string val; Symbol * symbol = nullptr; Register * reg = nullptr; uint registerId = 0; // the zero register uint32_t immediate_value = 0; }; enum class Operations: uint16_t{ // three register operations ADD, SUB, MUL, MULH, MULHSU, MULHU, DIV, DIVU, REM, REMU, AND, OR, XOR, SLL, SLT, SLTU, SRL, SRA, ADDW, SUBW, SLLW, SRLW, SRAW, MULW, DIVW, DIVUW, REMW, REMUW, //two register, then immediate ops ADDI, SLTI, SLLI, SRLI, XORI, SRAI, ADDIW, SLLIW, SRLIW, SRAIW, // These are still two reg and immediate but the immediate is an offset from the Program counter in all cases at runtime. JALR, BEQ, BNE, BLT, BGE, BLTU, BGEU, // one register, then offset location LB, LH, LW, LWU, LD, LBU, LHU, SB, SH, SW, SD, JAL, // one register and immediate LUI, AUIPC, // two register operations // Special cases // I.E. instructions that are converted to others NOP, MV, NOT, NEG, NEGW, //Extra special // things I have just added. HALT, PRINT, INPUTI, INPUTB, INPUTS, INPUTF, DEBUG, //TODO add floating point operations. }; struct generatedInstruction { std::vector<unsigned long> values; }; class Instruction { protected: std::string value; SymbolTable* sym; ulong address; public: /** * @brief Construct a new Instruction object * * @param value the instruction string line */ Instruction(std::string value, SymbolTable* sym, ulong address); /** * @brief a register with the value * @note Free the register after your done with it. * @returns generatedInstruction with the value * an odd construct returning a register because it is just a place to put bytes. */ generatedInstruction getInstruction(); }; class Program { protected: std::string value; SymbolTable sym; void firstStep(); public: Program(std::string value); Program(std::ifstream& in); /** * load a program to memory. * @param mem the memory */ SymbolTable* toMemory(Memory* mem); };
18.5
125
0.579238
noah-witt
70b05f3c7e6f4157a74a577bf02f1ba12fcb810e
27,911
cpp
C++
src/libtsduck/dtv/descriptors/tsLinkageDescriptor.cpp
SS-FF/tsduck
fb7eb63a9091085a878d434cd8778b012aa09cb7
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/dtv/descriptors/tsLinkageDescriptor.cpp
SS-FF/tsduck
fb7eb63a9091085a878d434cd8778b012aa09cb7
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/dtv/descriptors/tsLinkageDescriptor.cpp
SS-FF/tsduck
fb7eb63a9091085a878d434cd8778b012aa09cb7
[ "BSD-2-Clause" ]
null
null
null
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2020, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // //---------------------------------------------------------------------------- #include "tsLinkageDescriptor.h" #include "tsDescriptor.h" #include "tsNames.h" #include "tsTablesDisplay.h" #include "tsPSIRepository.h" #include "tsDuckContext.h" #include "tsxmlElement.h" TSDUCK_SOURCE; #define MY_XML_NAME u"linkage_descriptor" #define MY_CLASS ts::LinkageDescriptor #define MY_DID ts::DID_LINKAGE #define MY_STD ts::STD_DVB TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Standard(MY_DID), MY_XML_NAME, MY_CLASS::DisplayDescriptor); //---------------------------------------------------------------------------- // Constructors for substructures //---------------------------------------------------------------------------- ts::LinkageDescriptor::MobileHandoverInfo::MobileHandoverInfo() : handover_type(0), origin_type(0), network_id(0), initial_service_id(0) { } void ts::LinkageDescriptor::MobileHandoverInfo::clear() { handover_type = 0; origin_type = 0; network_id = 0; initial_service_id = 0; } ts::LinkageDescriptor::EventLinkageInfo::EventLinkageInfo() : target_event_id(0), target_listed(false), event_simulcast(false) { } void ts::LinkageDescriptor::EventLinkageInfo::clear() { target_event_id = 0; target_listed = false; event_simulcast = false; } ts::LinkageDescriptor::ExtendedEventLinkageInfo::ExtendedEventLinkageInfo() : target_event_id(0), target_listed(false), event_simulcast(false), link_type(0), target_id_type(0), user_defined_id(0), target_transport_stream_id(0), target_original_network_id(), target_service_id() { } void ts::LinkageDescriptor::ExtendedEventLinkageInfo::clear() { target_event_id = 0; target_listed = false; event_simulcast = false; link_type = 0; target_id_type = 0; user_defined_id = 0; target_transport_stream_id = 0; target_original_network_id.reset(); target_service_id.reset(); } void ts::LinkageDescriptor::clear() { ts_id = 0; onetw_id = 0; service_id = 0; linkage_type = 0; mobile_handover_info.clear(); event_linkage_info.clear(); extended_event_linkage_info.clear(); private_data.clear(); } //---------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------- ts::LinkageDescriptor::LinkageDescriptor(uint16_t ts, uint16_t onetw, uint16_t service, uint8_t ltype) : AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0), ts_id(ts), onetw_id(onetw), service_id(service), linkage_type(ltype), mobile_handover_info(), event_linkage_info(), extended_event_linkage_info(), private_data() { _is_valid = true; } ts::LinkageDescriptor::LinkageDescriptor(DuckContext& duck, const Descriptor& desc) : LinkageDescriptor() { deserialize(duck, desc); } //---------------------------------------------------------------------------- // Serialization //---------------------------------------------------------------------------- void ts::LinkageDescriptor::serialize(DuckContext& duck, Descriptor& desc) const { ByteBlockPtr bbp(serializeStart()); // Fixed part. bbp->appendUInt16(ts_id); bbp->appendUInt16(onetw_id); bbp->appendUInt16(service_id); bbp->appendUInt8(linkage_type); // Known variable parts. if (linkage_type == LINKAGE_HAND_OVER) { bbp->appendUInt8(uint8_t(mobile_handover_info.handover_type << 4) | 0x0E | (mobile_handover_info.origin_type & 0x01)); if (mobile_handover_info.handover_type >= 1 && mobile_handover_info.handover_type <= 3) { bbp->appendUInt16(mobile_handover_info.network_id); } if (mobile_handover_info.origin_type == 0x00) { bbp->appendUInt16(mobile_handover_info.initial_service_id); } } else if (linkage_type == LINKAGE_EVENT) { bbp->appendUInt16(event_linkage_info.target_event_id); bbp->appendUInt8((event_linkage_info.target_listed ? 0x80 : 0x00) | (event_linkage_info.event_simulcast ? 0x40 : 0x00) | 0x3F); } else if (linkage_type >= LINKAGE_EXT_EVENT_MIN && linkage_type <= LINKAGE_EXT_EVENT_MAX) { const size_t length_index = bbp->size(); bbp->appendUInt8(0); // placeholder for loop_length for (ExtendedEventLinkageList::const_iterator it = extended_event_linkage_info.begin(); it != extended_event_linkage_info.end(); ++it) { bbp->appendUInt16(it->target_event_id); bbp->appendUInt8((it->target_listed ? 0x80 : 0x00) | (it->event_simulcast ? 0x40 : 0x00) | uint8_t((it->link_type & 0x03) << 4) | uint8_t((it->target_id_type & 0x03) << 2) | (it->target_original_network_id.set() ? 0x02 : 0x00) | (it->target_service_id.set() ? 0x01 : 0x00)); if (it->target_id_type == 3) { bbp->appendUInt16(it->user_defined_id); } if (it->target_id_type == 1) { bbp->appendUInt16(it->target_transport_stream_id); } if (it->target_original_network_id.set()) { bbp->appendUInt16(it->target_original_network_id.value()); } if (it->target_service_id.set()) { bbp->appendUInt16(it->target_service_id.value()); } } // Update loop_length. (*bbp)[length_index] = uint8_t(bbp->size() - length_index - 1); } // Finally, add private data. bbp->append(private_data); serializeEnd(desc, bbp); } //---------------------------------------------------------------------------- // Deserialization //---------------------------------------------------------------------------- void ts::LinkageDescriptor::deserialize(DuckContext& duck, const Descriptor& desc) { clear(); _is_valid = desc.isValid() && desc.tag() == _tag && desc.payloadSize() >= 7; if (_is_valid) { const uint8_t* data = desc.payload(); size_t size = desc.payloadSize(); // Fixed part. ts_id = GetUInt16(data); onetw_id = GetUInt16(data + 2); service_id = GetUInt16(data + 4); linkage_type = data[6]; data += 7; size -= 7; // Known variable parts. if (linkage_type == LINKAGE_HAND_OVER) { _is_valid = size >= 1; if (_is_valid) { mobile_handover_info.handover_type = data[0] >> 4; mobile_handover_info.origin_type = data[0] & 0x01; data += 1; size -= 1; } if (_is_valid && mobile_handover_info.handover_type >= 1 && mobile_handover_info.handover_type <= 3) { _is_valid = size >= 2; if (_is_valid) { mobile_handover_info.network_id = GetUInt16(data); data += 2; size -= 2; } } if (_is_valid && mobile_handover_info.origin_type == 0x00) { _is_valid = size >= 2; if (_is_valid) { mobile_handover_info.initial_service_id = GetUInt16(data); data += 2; size -= 2; } } } else if (linkage_type == LINKAGE_EVENT) { _is_valid = size >= 3; if (_is_valid) { event_linkage_info.target_event_id = GetUInt16(data); event_linkage_info.target_listed = (data[2] & 0x80) != 0; event_linkage_info.event_simulcast = (data[2] & 0x40) != 0; data += 3; size -= 3; } } else if (linkage_type >= LINKAGE_EXT_EVENT_MIN && linkage_type <= LINKAGE_EXT_EVENT_MAX) { _is_valid = size >= 1; if (_is_valid) { size_t loop_length = data[0]; data += 1; size -= 1; while (_is_valid && loop_length > 0) { _is_valid = loop_length >= 3; ExtendedEventLinkageInfo info; bool onetw_flag = false; bool serv_flag = false; if (_is_valid) { info.target_event_id = GetUInt16(data); info.target_listed = (data[2] & 0x80) != 0; info.event_simulcast = (data[2] & 0x40) != 0; info.link_type = (data[2] >> 4) & 0x03; info.target_id_type = (data[2] >> 2) & 0x03; onetw_flag = (data[2] & 0x02) != 0; serv_flag = (data[2] & 0x01) != 0; data += 3; size -= 3; loop_length -= 3; } if (_is_valid && info.target_id_type == 3) { _is_valid = size >= 2; if (_is_valid) { info.user_defined_id = GetUInt16(data); data += 2; size -= 2; loop_length -= 2; } } if (_is_valid && info.target_id_type == 1) { _is_valid = size >= 2; if (_is_valid) { info.target_transport_stream_id = GetUInt16(data); data += 2; size -= 2; loop_length -= 2; } } if (_is_valid && onetw_flag) { _is_valid = size >= 2; if (_is_valid) { info.target_original_network_id = GetUInt16(data); data += 2; size -= 2; loop_length -= 2; } } if (_is_valid && serv_flag) { _is_valid = size >= 2; if (_is_valid) { info.target_service_id = GetUInt16(data); data += 2; size -= 2; loop_length -= 2; } } if (_is_valid) { extended_event_linkage_info.push_back(info); } } } } // Remaining bytes are private data. if (_is_valid) { private_data.copy(data, size); } } } //---------------------------------------------------------------------------- // Static method to display a descriptor. //---------------------------------------------------------------------------- void ts::LinkageDescriptor::DisplayDescriptor(TablesDisplay& display, DID did, const uint8_t* data, size_t size, int indent, TID tid, PDS pds) { DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); if (size >= 7) { // Fixed part uint16_t tsid = GetUInt16(data); uint16_t onid = GetUInt16(data + 2); uint16_t servid = GetUInt16(data + 4); uint8_t ltype = data[6]; data += 7; size -= 7; strm << margin << UString::Format(u"Transport stream id: %d (0x%X)", {tsid, tsid}) << std::endl << margin << UString::Format(u"Original network Id: %d (0x%X)", {onid, onid}) << std::endl << margin << UString::Format(u"Service id: %d (0x%X)", {servid, servid}) << std::endl << margin << UString::Format(u"Linkage type: %s", {names::LinkageType(ltype, names::FIRST)}) << std::endl; // Variable part switch (ltype) { case 0x08: DisplayPrivateMobileHandover(display, data, size, indent, ltype); break; case 0x09: DisplayPrivateSSU(display, data, size, indent, ltype); break; case 0x0A: DisplayPrivateTableSSU(display, data, size, indent, ltype); break; case 0x0B: DisplayPrivateINT(display, data, size, indent, ltype); break; case 0x0C: DisplayPrivateDeferredINT(display, data, size, indent, ltype); break; default: break; } // Remaining private data display.displayPrivateData(u"Private data", data, size, indent); } else { display.displayExtraData(data, size, indent); } } //---------------------------------------------------------------------------- // Display linkage private data for mobile hand-over //---------------------------------------------------------------------------- void ts::LinkageDescriptor::DisplayPrivateMobileHandover(TablesDisplay& display, const uint8_t*& data, size_t& size, int indent, uint8_t ltype) { if (size < 1) { return; } DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); uint8_t hand_over = *data >> 4; uint8_t origin = *data & 0x01; data += 1; size -= 1; const UChar *name; switch (hand_over) { case 0x01: name = u"identical service in neighbour country"; break; case 0x02: name = u"local variation of same service"; break; case 0x03: name = u"associated service"; break; default: name = u"unknown"; break; } strm << margin << UString::Format(u"Hand-over type: 0x%X, %s, Origin: %s", {hand_over, name, origin ? u"SDT" : u"NIT"}) << std::endl; if ((hand_over == 0x01 || hand_over == 0x02 || hand_over == 0x03) && size >= 2) { uint16_t nwid = GetUInt16(data); data += 2; size -= 2; strm << margin << UString::Format(u"Network id: %d (0x%X)", {nwid, nwid}) << std::endl; } if (origin == 0x00 && size >= 2) { uint16_t org_servid = GetUInt16(data); data += 2; size -= 2; strm << margin << UString::Format(u"Original service id: %d (0x%X)", {org_servid, org_servid}) << std::endl; } } //---------------------------------------------------------------------------- // Display linkage private data for System Software Update (ETSI TS 102 006) //---------------------------------------------------------------------------- void ts::LinkageDescriptor::DisplayPrivateSSU(TablesDisplay& display, const uint8_t*& data, size_t& size, int indent, uint8_t ltype) { if (size < 1) { return; } DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); uint8_t dlength = data[0]; data += 1; size -= 1; if (dlength > size) { dlength = uint8_t(size); } while (dlength >= 4) { uint32_t oui = GetUInt24(data); uint8_t slength = data[3]; data += 4; size -= 4; dlength -= 4; const uint8_t* sdata = data; if (slength > dlength) { slength = dlength; } data += slength; size -= slength; dlength -= slength; strm << margin << "OUI: " << names::OUI(oui, names::FIRST) << std::endl; display.displayPrivateData(u"Selector data", sdata, slength, indent); } } //---------------------------------------------------------------------------- // Display linkage private data for TS with System Software Update // BAT or NIT (ETSI TS 102 006) //---------------------------------------------------------------------------- void ts::LinkageDescriptor::DisplayPrivateTableSSU(TablesDisplay& display, const uint8_t*& data, size_t& size, int indent, uint8_t ltype) { if (size >= 1) { DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); uint8_t ttype = data[0]; data += 1; size -= 1; strm << margin << "SSU table type: "; switch (ttype) { case 0x01: strm << "NIT"; break; case 0x02: strm << "BAT"; break; default: strm << UString::Hexa(ttype); break; } strm << std::endl; } } //---------------------------------------------------------------------------- // Display linkage private data for INT. //---------------------------------------------------------------------------- void ts::LinkageDescriptor::DisplayPrivateINT(TablesDisplay& display, const uint8_t*& data, size_t& size, int indent, uint8_t ltype) { if (size < 1) { return; } DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); uint8_t data_length = data[0]; data += 1; size -= 1; if (data_length > size) { data_length = uint8_t(size); } while (data_length >= 4) { uint32_t plf_id = GetUInt24(data); uint8_t loop_length = data[3]; data += 4; size -= 4; data_length -= 4; if (loop_length > data_length) { loop_length = data_length; } strm << margin << UString::Format(u"- Platform id: %s", {ts::names::PlatformId(plf_id, names::HEXA_FIRST)}) << std::endl; while (loop_length >= 4) { const UString lang(DeserializeLanguageCode(data)); uint8_t name_length = data[3]; data += 4; size -= 4; data_length -= 4; loop_length -= 4; if (name_length > loop_length) { name_length = loop_length; } const UString name(duck.decoded(data, name_length)); data += name_length; size -= name_length; data_length -= name_length; loop_length -= name_length; strm << margin << " Language: " << lang << ", name: \"" << name << "\"" << std::endl; } } } //---------------------------------------------------------------------------- // Display linkage private data for deferred INT. //---------------------------------------------------------------------------- void ts::LinkageDescriptor::DisplayPrivateDeferredINT(TablesDisplay& display, const uint8_t*& data, size_t& size, int indent, uint8_t ltype) { if (size >= 1) { DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); uint8_t ttype = data[0]; data += 1; size -= 1; strm << margin << "INT linkage table type: "; switch (ttype) { case 0x00: strm << "unspecified"; break; case 0x01: strm << "NIT"; break; case 0x02: strm << "BAT"; break; default: strm << UString::Hexa(ttype); break; } strm << std::endl; if (ttype == 0x02 && size >= 2) { const uint16_t bid = GetUInt16(data); data += 2; size -= 2; strm << margin << UString::Format(u"Bouquet id: 0x%X (%d)", {bid, bid}) << std::endl; } } } //---------------------------------------------------------------------------- // Enumerations for XML. //---------------------------------------------------------------------------- namespace { const ts::Enumeration OriginTypeNames({{u"NIT", 0}, {u"SDT", 1}}); } //---------------------------------------------------------------------------- // XML serialization //---------------------------------------------------------------------------- void ts::LinkageDescriptor::buildXML(DuckContext& duck, xml::Element* root) const { root->setIntAttribute(u"transport_stream_id", ts_id, true); root->setIntAttribute(u"original_network_id", onetw_id, true); root->setIntAttribute(u"service_id", service_id, true); root->setIntAttribute(u"linkage_type", linkage_type, true); if (linkage_type == LINKAGE_HAND_OVER) { xml::Element* e = root->addElement(u"mobile_handover_info"); e->setIntAttribute(u"handover_type", mobile_handover_info.handover_type, true); e->setIntEnumAttribute(OriginTypeNames, u"origin_type", mobile_handover_info.origin_type); if (mobile_handover_info.handover_type >= 1 && mobile_handover_info.handover_type <= 3) { e->setIntAttribute(u"network_id", mobile_handover_info.network_id, true); } if (mobile_handover_info.origin_type == 0x00) { e->setIntAttribute(u"initial_service_id", mobile_handover_info.initial_service_id, true); } } else if (linkage_type == LINKAGE_EVENT) { xml::Element* e = root->addElement(u"event_linkage_info"); e->setIntAttribute(u"target_event_id", event_linkage_info.target_event_id, true); e->setBoolAttribute(u"target_listed", event_linkage_info.target_listed); e->setBoolAttribute(u"event_simulcast", event_linkage_info.event_simulcast); } else if (linkage_type >= LINKAGE_EXT_EVENT_MIN && linkage_type <= LINKAGE_EXT_EVENT_MAX) { xml::Element* extInfo = root->addElement(u"extended_event_linkage_info"); for (ExtendedEventLinkageList::const_iterator it = extended_event_linkage_info.begin(); it != extended_event_linkage_info.end(); ++it) { xml::Element* e = extInfo->addElement(u"event"); e->setIntAttribute(u"target_event_id", it->target_event_id, true); e->setBoolAttribute(u"target_listed", it->target_listed); e->setBoolAttribute(u"event_simulcast", it->event_simulcast); e->setIntAttribute(u"link_type", it->link_type, true); e->setIntAttribute(u"target_id_type", it->target_id_type, true); if (it->target_id_type == 3) { e->setIntAttribute(u"user_defined_id", it->user_defined_id, true); } if (it->target_id_type == 1) { e->setIntAttribute(u"target_transport_stream_id", it->target_transport_stream_id, true); } if (it->target_original_network_id.set()) { e->setIntAttribute(u"target_original_network_id", it->target_original_network_id.value(), true); } if (it->target_service_id.set()) { e->setIntAttribute(u"target_service_id", it->target_service_id.value(), true); } } } if (!private_data.empty()) { root->addElement(u"private_data")->addHexaText(private_data); } } //---------------------------------------------------------------------------- // XML deserialization //---------------------------------------------------------------------------- void ts::LinkageDescriptor::fromXML(DuckContext& duck, const xml::Element* element) { clear(); _is_valid = checkXMLName(element) && element->getIntAttribute<uint16_t>(ts_id, u"transport_stream_id", true) && element->getIntAttribute<uint16_t>(onetw_id, u"original_network_id", true) && element->getIntAttribute<uint16_t>(service_id, u"service_id", true) && element->getIntAttribute<uint8_t>(linkage_type, u"linkage_type", true) && element->getHexaTextChild(private_data, u"private_data", false); xml::ElementVector mobileElements; xml::ElementVector eventElements; xml::ElementVector extEventElements; if (_is_valid) { const size_t mobileCount = linkage_type == LINKAGE_HAND_OVER ? 1 : 0; const size_t eventCount = linkage_type == LINKAGE_EVENT ? 1 : 0; const size_t extEventCount = linkage_type >= LINKAGE_EXT_EVENT_MIN && linkage_type <= LINKAGE_EXT_EVENT_MAX ? 1 : 0; _is_valid = element->getChildren(mobileElements, u"mobile_handover_info", mobileCount, mobileCount) && element->getChildren(eventElements, u"event_linkage_info", eventCount, eventCount) && element->getChildren(extEventElements, u"extended_event_linkage_info", extEventCount, extEventCount); } if (_is_valid && !mobileElements.empty()) { _is_valid = mobileElements[0]->getIntAttribute<uint8_t>(mobile_handover_info.handover_type, u"handover_type", true, 0, 0, 0x0F) && mobileElements[0]->getIntEnumAttribute(mobile_handover_info.origin_type, OriginTypeNames, u"origin_type", true) && mobileElements[0]->getIntAttribute<uint16_t>(mobile_handover_info.network_id, u"network_id", mobile_handover_info.handover_type >= 1 && mobile_handover_info.handover_type <= 3) && mobileElements[0]->getIntAttribute<uint16_t>(mobile_handover_info.initial_service_id, u"initial_service_id", mobile_handover_info.origin_type == 0x00); } if (_is_valid && !eventElements.empty()) { _is_valid = eventElements[0]->getIntAttribute<uint16_t>(event_linkage_info.target_event_id, u"target_event_id", true) && eventElements[0]->getBoolAttribute(event_linkage_info.target_listed, u"target_listed", true) && eventElements[0]->getBoolAttribute(event_linkage_info.event_simulcast, u"event_simulcast", true); } if (_is_valid && !extEventElements.empty()) { _is_valid = extEventElements[0]->getChildren(eventElements, u"event"); for (size_t i = 0; _is_valid && i < eventElements.size(); ++i) { ExtendedEventLinkageInfo info; _is_valid = eventElements[i]->getIntAttribute<uint16_t>(info.target_event_id, u"target_event_id", true) && eventElements[i]->getBoolAttribute(info.target_listed, u"target_listed", true) && eventElements[i]->getBoolAttribute(info.event_simulcast, u"event_simulcast", true) && eventElements[i]->getIntAttribute<uint8_t>(info.link_type, u"link_type", true, 0, 0, 3) && eventElements[i]->getIntAttribute<uint8_t>(info.target_id_type, u"target_id_type", true, 0, 0, 3) && eventElements[i]->getIntAttribute<uint16_t>(info.user_defined_id, u"user_defined_id", info.target_id_type == 3) && eventElements[i]->getIntAttribute<uint16_t>(info.target_transport_stream_id, u"target_transport_stream_id", info.target_id_type == 1) && eventElements[i]->getOptionalIntAttribute<uint16_t>(info.target_original_network_id, u"target_original_network_id") && eventElements[i]->getOptionalIntAttribute<uint16_t>(info.target_service_id, u"target_service_id"); if (_is_valid) { extended_event_linkage_info.push_back(info); } } } }
40.102011
152
0.550034
SS-FF
70b5a537b709715faa2ebcb578bbe130fea8dd75
24,019
cpp
C++
examples/window-app/common/src/WindowApp.cpp
mykrupp/connectedhomeip-1
c6ca8bde66f76fa95b0383e2faa6a67c74cef2c3
[ "Apache-2.0" ]
1
2022-01-07T23:56:28.000Z
2022-01-07T23:56:28.000Z
examples/window-app/common/src/WindowApp.cpp
mykrupp/connectedhomeip-1
c6ca8bde66f76fa95b0383e2faa6a67c74cef2c3
[ "Apache-2.0" ]
null
null
null
examples/window-app/common/src/WindowApp.cpp
mykrupp/connectedhomeip-1
c6ca8bde66f76fa95b0383e2faa6a67c74cef2c3
[ "Apache-2.0" ]
null
null
null
/* * * Copyright (c) 2021 Project CHIP 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 <AppConfig.h> #include <WindowApp.h> #include <app-common/zap-generated/attributes/Accessors.h> #include <app/clusters/identify-server/identify-server.h> #include <app/server/Server.h> #include <app/util/af.h> #include <credentials/DeviceAttestationCredsProvider.h> #include <credentials/examples/DeviceAttestationCredsExample.h> #include <lib/support/CodeUtils.h> #include <platform/CHIPDeviceLayer.h> using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; using namespace chip::app::Clusters::WindowCovering; inline void OnTriggerEffectCompleted(chip::System::Layer * systemLayer, void * appState) { WindowApp::Instance().PostEvent(WindowApp::EventId::WinkOff); } void OnTriggerEffect(Identify * identify) { EmberAfIdentifyEffectIdentifier sIdentifyEffect = identify->mCurrentEffectIdentifier; ChipLogProgress(Zcl, "IDENTFY OnTriggerEffect"); if (identify->mCurrentEffectIdentifier == EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE) { ChipLogProgress(Zcl, "IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE - Not supported, use effect varriant %d", identify->mEffectVariant); sIdentifyEffect = static_cast<EmberAfIdentifyEffectIdentifier>(identify->mEffectVariant); } switch (sIdentifyEffect) { case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: WindowApp::Instance().PostEvent(WindowApp::EventId::WinkOn); (void) chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds16(5), OnTriggerEffectCompleted, identify); break; case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: (void) chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerEffectCompleted, identify); break; default: ChipLogProgress(Zcl, "No identifier effect"); } } Identify gIdentify = { chip::EndpointId{ 1 }, [](Identify *) { ChipLogProgress(Zcl, "onIdentifyStart"); }, [](Identify *) { ChipLogProgress(Zcl, "onIdentifyStop"); }, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, OnTriggerEffect, }; void WindowApp::Timer::Timeout() { mIsActive = false; if (mCallback) { mCallback(*this); } } void WindowApp::Button::Press() { EventId event = Button::Id::Up == mId ? EventId::UpPressed : EventId::DownPressed; Instance().PostEvent(WindowApp::Event(event)); } void WindowApp::Button::Release() { Instance().PostEvent(Button::Id::Up == mId ? EventId::UpReleased : EventId::DownReleased); } WindowApp::Cover & WindowApp::GetCover() { return mCoverList[mCurrentCover]; } WindowApp::Cover * WindowApp::GetCover(chip::EndpointId endpoint) { for (uint16_t i = 0; i < WINDOW_COVER_COUNT; ++i) { if (mCoverList[i].mEndpoint == endpoint) { return &mCoverList[i]; } } return nullptr; } CHIP_ERROR WindowApp::Init() { // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); ConfigurationMgr().LogDeviceConfig(); // Timers mLongPressTimer = CreateTimer("Timer:LongPress", LONG_PRESS_TIMEOUT, OnLongPressTimeout, this); // Buttons mButtonUp = CreateButton(Button::Id::Up, "UP"); mButtonDown = CreateButton(Button::Id::Down, "DOWN"); // Coverings mCoverList[0].Init(WINDOW_COVER_ENDPOINT1); mCoverList[1].Init(WINDOW_COVER_ENDPOINT2); return CHIP_NO_ERROR; } CHIP_ERROR WindowApp::Run() { StateFlags oldState; #if CHIP_ENABLE_OPENTHREAD oldState.isThreadProvisioned = !ConnectivityMgr().IsThreadProvisioned(); #else oldState.isWiFiProvisioned = !ConnectivityMgr().IsWiFiStationProvisioned(); #endif while (true) { ProcessEvents(); // Collect connectivity and configuration state from the CHIP stack. Because // the CHIP event loop is being run in a separate task, the stack must be // locked while these values are queried. However we use a non-blocking // lock request (TryLockCHIPStack()) to avoid blocking other UI activities // when the CHIP task is busy (e.g. with a long crypto operation). if (PlatformMgr().TryLockChipStack()) { #if CHIP_ENABLE_OPENTHREAD mState.isThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); mState.isThreadEnabled = ConnectivityMgr().IsThreadEnabled(); #else mState.isWiFiProvisioned = ConnectivityMgr().IsWiFiStationProvisioned(); mState.isWiFiEnabled = ConnectivityMgr().IsWiFiStationEnabled(); #endif mState.haveBLEConnections = (ConnectivityMgr().NumBLEConnections() != 0); PlatformMgr().UnlockChipStack(); } #if CHIP_ENABLE_OPENTHREAD if (mState.isThreadProvisioned != oldState.isThreadProvisioned) #else if (mState.isWiFiProvisioned != oldState.isWiFiProvisioned) #endif { // Provisioned state changed DispatchEvent(EventId::ProvisionedStateChanged); } if (mState.haveBLEConnections != oldState.haveBLEConnections) { // Provisioned state changed DispatchEvent(EventId::BLEConnectionsChanged); } OnMainLoop(); oldState = mState; } return CHIP_NO_ERROR; } void WindowApp::Finish() { DestroyTimer(mLongPressTimer); DestroyButton(mButtonUp); DestroyButton(mButtonDown); for (uint16_t i = 0; i < WINDOW_COVER_COUNT; ++i) { mCoverList[i].Finish(); } } void WindowApp::DispatchEvent(const WindowApp::Event & event) { switch (event.mId) { case EventId::ResetWarning: mResetWarning = true; if (mLongPressTimer) { mLongPressTimer->Start(); } break; case EventId::ResetCanceled: mResetWarning = false; break; case EventId::Reset: chip::Server::GetInstance().ScheduleFactoryReset(); break; case EventId::UpPressed: mUpPressed = true; if (mLongPressTimer) { mLongPressTimer->Start(); } break; case EventId::UpReleased: mUpPressed = false; if (mLongPressTimer) { mLongPressTimer->Stop(); } if (mResetWarning) { PostEvent(EventId::ResetCanceled); } if (mUpSuppressed) { mUpSuppressed = false; } else if (mDownPressed) { mTiltMode = !mTiltMode; mUpSuppressed = mDownSuppressed = true; PostEvent(EventId::TiltModeChange); } else if (mTiltMode) { GetCover().TiltUp(); } else { GetCover().LiftUp(); } break; case EventId::DownPressed: mDownPressed = true; if (mLongPressTimer) { mLongPressTimer->Start(); } break; case EventId::DownReleased: mDownPressed = false; if (mLongPressTimer) { mLongPressTimer->Stop(); } if (mResetWarning) { PostEvent(EventId::ResetCanceled); } if (mDownSuppressed) { mDownSuppressed = false; } else if (mUpPressed) { mTiltMode = !mTiltMode; mUpSuppressed = mDownSuppressed = true; PostEvent(EventId::TiltModeChange); } else if (mTiltMode) { GetCover().TiltDown(); } else { GetCover().LiftDown(); } break; case EventId::AttributeChange: DispatchEventAttributeChange(event.mEndpoint, event.mAttributeId); break; default: break; } } void WindowApp::DispatchEventAttributeChange(chip::EndpointId endpoint, chip::AttributeId attribute) { Cover * cover = GetCover(endpoint); if (nullptr == cover) { emberAfWindowCoveringClusterPrint("Ep[%u] not supported AttributeId=%u\n", endpoint, (unsigned int) attribute); return; } switch (attribute) { /* For a device supporting Position Awareness : Changing the Target triggers motions on the real or simulated device */ case Attributes::TargetPositionLiftPercent100ths::Id: cover->LiftGoToTarget(); break; /* For a device supporting Position Awareness : Changing the Target triggers motions on the real or simulated device */ case Attributes::TargetPositionTiltPercent100ths::Id: cover->TiltGoToTarget(); break; /* RO OperationalStatus */ case Attributes::OperationalStatus::Id: chip::DeviceLayer::PlatformMgr().LockChipStack(); emberAfWindowCoveringClusterPrint("Global OpState: %02X\n", (unsigned int) OperationalStatusGet(endpoint).global); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); break; /* RW Mode */ case Attributes::Mode::Id: emberAfWindowCoveringClusterPrint("Mode set: ignored"); break; /* ### ATTRIBUTEs CHANGEs IGNORED ### */ /* RO Type: not supposed to dynamically change */ case Attributes::Type::Id: /* RO EndProductType: not supposed to dynamically change */ case Attributes::EndProductType::Id: /* RO ConfigStatus: set by WC server */ case Attributes::ConfigStatus::Id: /* RO SafetyStatus: set by WC server */ case Attributes::SafetyStatus::Id: /* ============= Positions for Position Aware ============= */ case Attributes::CurrentPositionLiftPercent100ths::Id: case Attributes::CurrentPositionTiltPercent100ths::Id: default: break; } } void WindowApp::DestroyTimer(Timer * timer) { if (timer) { delete timer; } } void WindowApp::DestroyButton(Button * btn) { if (btn) { delete btn; } } void WindowApp::HandleLongPress() { if (mUpPressed && mDownPressed) { // Long press both buttons: Cycle between window coverings mUpSuppressed = mDownSuppressed = true; mCurrentCover = mCurrentCover < WINDOW_COVER_COUNT - 1 ? mCurrentCover + 1 : 0; PostEvent(EventId::CoverChange); } else if (mUpPressed) { mUpSuppressed = true; if (mResetWarning) { // Double long press button up: Reset now, you were warned! PostEvent(EventId::Reset); } else { // Long press button up: Reset warning! PostEvent(EventId::ResetWarning); } } else if (mDownPressed) { // Long press button down: Cycle between covering types mDownSuppressed = true; EmberAfWcType cover_type = GetCover().CycleType(); mTiltMode = mTiltMode && (EMBER_ZCL_WC_TYPE_TILT_BLIND_LIFT_AND_TILT == cover_type); } } void WindowApp::OnLongPressTimeout(WindowApp::Timer & timer) { WindowApp * app = static_cast<WindowApp *>(timer.mContext); if (app) { app->HandleLongPress(); } } void WindowApp::Cover::Init(chip::EndpointId endpoint) { mEndpoint = endpoint; mLiftTimer = WindowApp::Instance().CreateTimer("Timer:Lift", COVER_LIFT_TILT_TIMEOUT, OnLiftTimeout, this); mTiltTimer = WindowApp::Instance().CreateTimer("Timer:Tilt", COVER_LIFT_TILT_TIMEOUT, OnTiltTimeout, this); Attributes::InstalledOpenLimitLift::Set(endpoint, LIFT_OPEN_LIMIT); Attributes::InstalledClosedLimitLift::Set(endpoint, LIFT_CLOSED_LIMIT); LiftPositionSet(endpoint, LiftToPercent100ths(endpoint, LIFT_CLOSED_LIMIT)); Attributes::InstalledOpenLimitTilt::Set(endpoint, TILT_OPEN_LIMIT); Attributes::InstalledClosedLimitTilt::Set(endpoint, TILT_CLOSED_LIMIT); TiltPositionSet(endpoint, TiltToPercent100ths(endpoint, TILT_CLOSED_LIMIT)); // Attribute: Id 0 Type TypeSet(endpoint, EMBER_ZCL_WC_TYPE_TILT_BLIND_LIFT_AND_TILT); // Attribute: Id 7 ConfigStatus ConfigStatus configStatus = { .operational = 1, .online = 1, .liftIsReversed = 0, .liftIsPA = HasFeaturePaLift(endpoint), .tiltIsPA = HasFeaturePaTilt(endpoint), .liftIsEncoderControlled = 1, .tiltIsEncoderControlled = 1 }; ConfigStatusSet(endpoint, configStatus); OperationalStatusSetWithGlobalUpdated(endpoint, mOperationalStatus); // Attribute: Id 13 EndProductType EndProductTypeSet(endpoint, EMBER_ZCL_WC_END_PRODUCT_TYPE_INTERIOR_BLIND); // Attribute: Id 24 Mode Mode mode = { .motorDirReversed = 0, .calibrationMode = 1, .maintenanceMode = 1, .ledDisplay = 1 }; ModeSet(endpoint, mode); // Attribute: Id 27 SafetyStatus (Optional) SafetyStatus safetyStatus = { 0x00 }; // 0 is no issues; SafetyStatusSet(endpoint, safetyStatus); } void WindowApp::Cover::Finish() { WindowApp::Instance().DestroyTimer(mLiftTimer); WindowApp::Instance().DestroyTimer(mTiltTimer); } void WindowApp::Cover::LiftDown() { EmberAfStatus status; chip::app::DataModel::Nullable<chip::Percent100ths> current; chip::Percent100ths percent100ths = 5000; // set at middle CoverWorkData * data = chip::Platform::New<CoverWorkData>(); VerifyOrReturn(data != nullptr, emberAfWindowCoveringClusterPrint("Cover::LiftDown - Out of Memory for WorkData")); chip::DeviceLayer::PlatformMgr().LockChipStack(); status = Attributes::CurrentPositionLiftPercent100ths::Get(mEndpoint, current); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); if ((status == EMBER_ZCL_STATUS_SUCCESS) && !current.IsNull()) percent100ths = current.Value(); if (percent100ths < 9000) { percent100ths += 1000; } else { percent100ths = 10000; } data->mEndpointId = mEndpoint; data->percent100ths = percent100ths; chip::DeviceLayer::PlatformMgr().ScheduleWork(ScheduleLiftPositionSet, reinterpret_cast<intptr_t>(data)); } void WindowApp::Cover::LiftUp() { EmberAfStatus status; chip::app::DataModel::Nullable<chip::Percent100ths> current; chip::Percent100ths percent100ths = 5000; // set at middle CoverWorkData * data = chip::Platform::New<CoverWorkData>(); VerifyOrReturn(data != nullptr, emberAfWindowCoveringClusterPrint("Cover::LiftUp - Out of Memory for WorkData")); chip::DeviceLayer::PlatformMgr().LockChipStack(); status = Attributes::CurrentPositionLiftPercent100ths::Get(mEndpoint, current); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); if ((status == EMBER_ZCL_STATUS_SUCCESS) && !current.IsNull()) percent100ths = current.Value(); if (percent100ths > 1000) { percent100ths -= 1000; } else { percent100ths = 0; } data->mEndpointId = mEndpoint; data->percent100ths = percent100ths; chip::DeviceLayer::PlatformMgr().ScheduleWork(ScheduleLiftPositionSet, reinterpret_cast<intptr_t>(data)); } void WindowApp::Cover::LiftUpdate(bool newTarget) { NPercent100ths current, target; CoverWorkData * data = chip::Platform::New<CoverWorkData>(); VerifyOrReturn(data != nullptr, emberAfWindowCoveringClusterPrint("Cover::LiftUpdate - Out of Memory for WorkData")); chip::DeviceLayer::PlatformMgr().LockChipStack(); Attributes::TargetPositionLiftPercent100ths::Get(mEndpoint, target); Attributes::CurrentPositionLiftPercent100ths::Get(mEndpoint, current); OperationalStatus opStatus = OperationalStatusGet(mEndpoint); OperationalState opState = ComputeOperationalState(target, current); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); /* If Triggered by a TARGET update */ if (newTarget) { mLiftTimer->Stop(); // Cancel previous motion if any mLiftOpState = opState; } if (mLiftOpState == opState) { /* Actuator still need to move, not reached/crossed Target yet */ switch (mLiftOpState) { case OperationalState::MovingDownOrClose: LiftDown(); break; case OperationalState::MovingUpOrOpen: LiftUp(); break; default: break; } } else /* CURRENT reached TARGET or crossed it */ { /* Actuator finalize the movement AND CURRENT Must be equal to TARGET at the end */ chip::DeviceLayer::PlatformMgr().LockChipStack(); Attributes::CurrentPositionLiftPercent100ths::Set(mEndpoint, target); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); mLiftOpState = OperationalState::Stall; } opStatus.lift = mLiftOpState; data->mEndpointId = mEndpoint; data->opStatus = opStatus; chip::DeviceLayer::PlatformMgr().ScheduleWork(ScheduleOperationalStatusSetWithGlobalUpdate, reinterpret_cast<intptr_t>(data)); if ((OperationalState::Stall != mLiftOpState) && mLiftTimer) { mLiftTimer->Start(); } } void WindowApp::Cover::TiltDown() { EmberAfStatus status; chip::app::DataModel::Nullable<chip::Percent100ths> current; chip::Percent100ths percent100ths = 5000; // set at middle CoverWorkData * data = chip::Platform::New<CoverWorkData>(); VerifyOrReturn(data != nullptr, emberAfWindowCoveringClusterPrint("Cover::TiltDown - Out of Memory for WorkData")); chip::DeviceLayer::PlatformMgr().LockChipStack(); status = Attributes::CurrentPositionTiltPercent100ths::Get(mEndpoint, current); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); if ((status == EMBER_ZCL_STATUS_SUCCESS) && !current.IsNull()) percent100ths = current.Value(); if (percent100ths < 9000) { percent100ths += 1000; } else { percent100ths = 10000; } data->mEndpointId = mEndpoint; data->percent100ths = percent100ths; chip::DeviceLayer::PlatformMgr().ScheduleWork(ScheduleTiltPositionSet, reinterpret_cast<intptr_t>(data)); } void WindowApp::Cover::TiltUp() { EmberAfStatus status; chip::app::DataModel::Nullable<chip::Percent100ths> current; chip::Percent100ths percent100ths = 5000; // set at middle CoverWorkData * data = chip::Platform::New<CoverWorkData>(); VerifyOrReturn(data != nullptr, emberAfWindowCoveringClusterPrint("Cover::TiltUp - Out of Memory for WorkData")); chip::DeviceLayer::PlatformMgr().LockChipStack(); status = Attributes::CurrentPositionTiltPercent100ths::Get(mEndpoint, current); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); if ((status == EMBER_ZCL_STATUS_SUCCESS) && !current.IsNull()) percent100ths = current.Value(); if (percent100ths > 1000) { percent100ths -= 1000; } else { percent100ths = 0; } data->mEndpointId = mEndpoint; data->percent100ths = percent100ths; chip::DeviceLayer::PlatformMgr().ScheduleWork(ScheduleTiltPositionSet, reinterpret_cast<intptr_t>(data)); } void WindowApp::Cover::TiltUpdate(bool newTarget) { NPercent100ths current, target; CoverWorkData * data = chip::Platform::New<CoverWorkData>(); VerifyOrReturn(data != nullptr, emberAfWindowCoveringClusterPrint("Cover::TiltUpdate - Out of Memory for WorkData")); chip::DeviceLayer::PlatformMgr().LockChipStack(); Attributes::TargetPositionTiltPercent100ths::Get(mEndpoint, target); Attributes::CurrentPositionTiltPercent100ths::Get(mEndpoint, current); OperationalStatus opStatus = OperationalStatusGet(mEndpoint); OperationalState opState = ComputeOperationalState(target, current); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); /* If Triggered by a TARGET update */ if (newTarget) { mTiltTimer->Stop(); // Cancel previous motion if any mTiltOpState = opState; } if (mTiltOpState == opState) { /* Actuator still need to move, not reached/crossed Target yet */ switch (mTiltOpState) { case OperationalState::MovingDownOrClose: TiltDown(); break; case OperationalState::MovingUpOrOpen: TiltUp(); break; default: break; } } else /* CURRENT reached TARGET or crossed it */ { /* Actuator finalize the movement AND CURRENT Must be equal to TARGET at the end */ chip::DeviceLayer::PlatformMgr().LockChipStack(); Attributes::CurrentPositionTiltPercent100ths::Set(mEndpoint, target); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); mTiltOpState = OperationalState::Stall; } opStatus.tilt = mTiltOpState; data->mEndpointId = mEndpoint; data->opStatus = opStatus; chip::DeviceLayer::PlatformMgr().ScheduleWork(ScheduleOperationalStatusSetWithGlobalUpdate, reinterpret_cast<intptr_t>(data)); if ((OperationalState::Stall != mTiltOpState) && mTiltTimer) { mTiltTimer->Start(); } } EmberAfWcType WindowApp::Cover::CycleType() { chip::DeviceLayer::PlatformMgr().LockChipStack(); EmberAfWcType type = TypeGet(mEndpoint); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); switch (type) { case EMBER_ZCL_WC_TYPE_ROLLERSHADE: type = EMBER_ZCL_WC_TYPE_DRAPERY; // tilt = false; break; case EMBER_ZCL_WC_TYPE_DRAPERY: type = EMBER_ZCL_WC_TYPE_TILT_BLIND_LIFT_AND_TILT; break; case EMBER_ZCL_WC_TYPE_TILT_BLIND_LIFT_AND_TILT: type = EMBER_ZCL_WC_TYPE_ROLLERSHADE; // tilt = false; break; default: type = EMBER_ZCL_WC_TYPE_TILT_BLIND_LIFT_AND_TILT; } chip::DeviceLayer::PlatformMgr().LockChipStack(); TypeSet(mEndpoint, type); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); return type; } void WindowApp::Cover::OnLiftTimeout(WindowApp::Timer & timer) { WindowApp::Cover * cover = static_cast<WindowApp::Cover *>(timer.mContext); if (cover) { cover->LiftContinueToTarget(); } } void WindowApp::Cover::OnTiltTimeout(WindowApp::Timer & timer) { WindowApp::Cover * cover = static_cast<WindowApp::Cover *>(timer.mContext); if (cover) { cover->TiltContinueToTarget(); } } void WindowApp::Cover::ScheduleTiltPositionSet(intptr_t arg) { WindowApp::Cover::CoverWorkData * data = reinterpret_cast<WindowApp::Cover::CoverWorkData *>(arg); TiltPositionSet(data->mEndpointId, data->percent100ths); chip::Platform::Delete(data); } void WindowApp::Cover::ScheduleLiftPositionSet(intptr_t arg) { WindowApp::Cover::CoverWorkData * data = reinterpret_cast<WindowApp::Cover::CoverWorkData *>(arg); LiftPositionSet(data->mEndpointId, data->percent100ths); chip::Platform::Delete(data); } void WindowApp::Cover::ScheduleOperationalStatusSetWithGlobalUpdate(intptr_t arg) { WindowApp::Cover::CoverWorkData * data = reinterpret_cast<WindowApp::Cover::CoverWorkData *>(arg); OperationalStatusSetWithGlobalUpdated(data->mEndpointId, data->opStatus); chip::Platform::Delete(data); }
31.153048
130
0.66131
mykrupp
70b7d05ab1bd18850b65c7953eaff0eb15c5a779
612
hpp
C++
bucket_7B/coinmp/patches/patch-CoinUtils_src_CoinSignal.hpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
17
2017-04-22T21:53:52.000Z
2021-01-21T16:57:55.000Z
bucket_7B/coinmp/patches/patch-CoinUtils_src_CoinSignal.hpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
186
2017-09-12T20:46:52.000Z
2021-11-27T18:15:14.000Z
bucket_7B/coinmp/patches/patch-CoinUtils_src_CoinSignal.hpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
74
2017-09-06T14:48:01.000Z
2021-08-28T02:48:27.000Z
--- CoinUtils/src/CoinSignal.hpp.orig 2015-03-13 20:16:34 UTC +++ CoinUtils/src/CoinSignal.hpp @@ -43,8 +43,15 @@ //----------------------------------------------------------------------------- +#if defined(__DragonFly__) && defined(__GNUC__) + typedef typeof(SIG_DFL) CoinSighandler_t; +# define CoinSighandler_t_defined +#endif + +//----------------------------------------------------------------------------- + #if defined(__FreeBSD__) && defined(__GNUC__) - typedef __decltype(SIG_DFL) CoinSighandler_t; + typedef typeof(SIG_DFL) CoinSighandler_t; # define CoinSighandler_t_defined #endif
30.6
80
0.542484
jrmarino
70bab7eb12e793e4faeba9e6a13bd6225a9c1ba6
4,420
hpp
C++
src/generator/gsql_parser/gsql_parser/core_parser.hpp
ostri/dbgen3
3430ef64f51d551a7ec4356daf52f80940ad7343
[ "Apache-2.0" ]
null
null
null
src/generator/gsql_parser/gsql_parser/core_parser.hpp
ostri/dbgen3
3430ef64f51d551a7ec4356daf52f80940ad7343
[ "Apache-2.0" ]
null
null
null
src/generator/gsql_parser/gsql_parser/core_parser.hpp
ostri/dbgen3
3430ef64f51d551a7ec4356daf52f80940ad7343
[ "Apache-2.0" ]
null
null
null
#ifndef CORE_PARSER_HPP #define CORE_PARSER_HPP #include <array> #include <filesystem> #include <memory> #include <xercesc/dom/DOM.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/validators/common/Grammar.hpp> #include "utility_classes/common.hpp" #include "db_integration/db2_reader.hpp" #include "gsql_parser/dom_error_handler.hpp" #include "gsql_parser/gsql_q_set.hpp" #include "gsql_parser/gsql_sql_set.hpp" #include "gsql_parser/xerces_strings.hpp" #include "runtime/statement.hpp" #include "utility_classes/log.hpp" #include "utility_classes/string_format.hpp" namespace dbgen3 { namespace x = xercesc; class core_parser // NOLINT clang-tidy(cppcoreguidelines-special-member-functions) { public: explicit core_parser(x::XMLGrammarPool* gp); ~core_parser(); core_parser(const core_parser&) = delete; core_parser& operator=(const core_parser&) = delete; core_parser& operator=(core_parser&&) = delete; /// @name getters ///@{ static std::string q_set_id(const x::DOMElement* an_el, cstr_t a_filename); ///@} int parse_set(const str_vec& gsql_files); gsql_q_set parse_file(cstr_t a_filename, const db2_reader& a_dbr, const RDBMS& a_db_type); protected: private: /// @name query set structure ///@{ static fld_dscr load_fld_dscr(cstr_t def_name, const db::BUF_TYPE& a_bt, SQLHANDLE h, uint ndx); static fld_vec fetch_param_dscr(const str_vec& names, const db::BUF_TYPE& a_bt, db::statement& a_stmt); static gsql_q_set load_q_set(const x::DOMElement* an_el, cstr_t a_filename, const db2_reader& a_dbr, const RDBMS& a_db_type); static gsql_q load_q(const x::DOMElement* an_el, uint a_ndx, str_vec a_ctx, const db2_reader& a_dbr, const RDBMS& a_db_type); static gsql_q load_q_children(const x::DOMElement* an_el, uint a_ndx, const str_vec& a_ctx, const db2_reader& a_dbr, const RDBMS& a_db_type, gsql_q& r); // static gsql_qbuf_dscr load_qp(const x::DOMElement* an_el, uint a_ndx); // static gsql_qbuf_dscr load_qr(const x::DOMElement* an_el, uint a_ndx); static gsql_qbuf_dscr load_buf(const db::BUF_TYPE& bt, const x::DOMElement* an_el ); static gsql_sql_set load_sql_set(const x::DOMElement* an_el, const str_vec& a_ctx, const RDBMS& a_db_type); static gsql_sql_set load_sql_set_sql(const x::DOMElement* el, str_vec a_ctx, const RDBMS& a_db_type, uint ndx, gsql_sql_set& r); static gsql_q load_q_sqlset_from_db(gsql_q& r, const db2_reader& a_dbr); ///@} static str_t attr_value(const x::DOMElement* an_el, cstr_t an_attr_name, cstr_t a_default); static bool attr_value_b(const x::DOMElement* an_el, cstr_t an_attr_name, bool a_default); bool init(); static std::string get_statement(const x::DOMElement* an_el, str_vec a_ctx); static std::string get_text_node(const x::DOMElement* an_el, str_vec a_ctx); static std::pair<str_t, str_t> get_text_node_with_prepare(const x::DOMElement* an_el, str_vec a_ctx); /* .........................................................*/ x::DOMLSParser* parser_; //!< DOM parser dom_error_handler eh_{}; //!< error handler }; }; // namespace dbgen3 #endif // CORE_PARSER_HPP
46.041667
105
0.565158
ostri
70bdebb3a00e551b8371ea101c72e0eac301c443
4,536
cc
C++
src/Obj.cc
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
src/Obj.cc
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
src/Obj.cc
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
// See the file "COPYING" in the main distribution directory for copyright. #include "zeek-config.h" #include "zeek/Obj.h" #include <stdlib.h> #include "zeek/Desc.h" #include "zeek/Func.h" #include "zeek/File.h" #include "zeek/plugin/Manager.h" namespace zeek { namespace detail { Location start_location("<start uninitialized>", 0, 0, 0, 0); Location end_location("<end uninitialized>", 0, 0, 0, 0); void Location::Describe(ODesc* d) const { if ( filename ) { d->Add(filename); if ( first_line == 0 ) return; d->AddSP(","); } if ( last_line != first_line ) { d->Add("lines "); d->Add(first_line); d->Add("-"); d->Add(last_line); } else { d->Add("line "); d->Add(first_line); } } bool Location::operator==(const Location& l) const { if ( filename == l.filename || (filename && l.filename && util::streq(filename, l.filename)) ) return first_line == l.first_line && last_line == l.last_line; else return false; } } // namespace detail int Obj::suppress_errors = 0; Obj::~Obj() { if ( notify_plugins ) PLUGIN_HOOK_VOID(HOOK_BRO_OBJ_DTOR, HookBroObjDtor(this)); delete location; } void Obj::Warn(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const { ODesc d; DoMsg(&d, msg, obj2, pinpoint_only, expr_location); reporter->Warning("%s", d.Description()); reporter->PopLocation(); } void Obj::Error(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const { if ( suppress_errors ) return; ODesc d; DoMsg(&d, msg, obj2, pinpoint_only, expr_location); reporter->Error("%s", d.Description()); reporter->PopLocation(); } void Obj::BadTag(const char* msg, const char* t1, const char* t2) const { char out[512]; if ( t2 ) snprintf(out, sizeof(out), "%s (%s/%s)", msg, t1, t2); else if ( t1 ) snprintf(out, sizeof(out), "%s (%s)", msg, t1); else snprintf(out, sizeof(out), "%s", msg); ODesc d; DoMsg(&d, out); reporter->FatalErrorWithCore("%s", d.Description()); reporter->PopLocation(); } void Obj::Internal(const char* msg) const { ODesc d; DoMsg(&d, msg); auto rcs = render_call_stack(); if ( rcs.empty() ) reporter->InternalError("%s", d.Description()); else reporter->InternalError("%s, call stack: %s", d.Description(), rcs.data()); reporter->PopLocation(); } void Obj::InternalWarning(const char* msg) const { ODesc d; DoMsg(&d, msg); reporter->InternalWarning("%s", d.Description()); reporter->PopLocation(); } void Obj::AddLocation(ODesc* d) const { if ( ! location ) { d->Add("<no location>"); return; } location->Describe(d); } bool Obj::SetLocationInfo(const detail::Location* start, const detail::Location* end) { if ( ! start || ! end ) return false; if ( end->filename && ! util::streq(start->filename, end->filename) ) return false; if ( location && (start == &detail::no_location || end == &detail::no_location) ) // We already have a better location, so don't use this one. return true; delete location; location = new detail::Location(start->filename, start->first_line, end->last_line, start->first_column, end->last_column); return true; } void Obj::UpdateLocationEndInfo(const detail::Location& end) { if ( ! location ) SetLocationInfo(&end, &end); location->last_line = end.last_line; location->last_column = end.last_column; } void Obj::DoMsg(ODesc* d, const char s1[], const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const { d->SetShort(); d->Add(s1); PinPoint(d, obj2, pinpoint_only); const detail::Location* loc2 = nullptr; if ( obj2 && obj2->GetLocationInfo() != &detail::no_location && *obj2->GetLocationInfo() != *GetLocationInfo() ) loc2 = obj2->GetLocationInfo(); else if ( expr_location ) loc2 = expr_location; reporter->PushLocation(GetLocationInfo(), loc2); } void Obj::PinPoint(ODesc* d, const Obj* obj2, bool pinpoint_only) const { d->Add(" ("); Describe(d); if ( obj2 && ! pinpoint_only ) { d->Add(" and "); obj2->Describe(d); } d->Add(")"); } void Obj::Print() const { static File fstderr(stderr); ODesc d(DESC_READABLE, &fstderr); Describe(&d); d.Add("\n"); } void bad_ref(int type) { reporter->InternalError("bad reference count [%d]", type); abort(); } void obj_delete_func(void* v) { Unref((Obj*) v); } } // namespace zeek void print(const zeek::Obj* obj) { obj->Print(); }
20.524887
114
0.64418
hugolin615
70bdf03408c8d575a6854d41081500e4ea1a494d
15,512
cc
C++
third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.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
third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.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 (c) 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 "third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver_impl.h" #include "base/bind.h" #include "base/check_op.h" #include "base/notreached.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_encoded_audio_stream_transformer.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_encoded_video_stream_transformer.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_rtp_sender_platform.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_rtp_source.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_stats.h" #include "third_party/blink/renderer/platform/peerconnection/webrtc_util.h" #include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h" #include "third_party/webrtc/api/scoped_refptr.h" namespace blink { RtpReceiverState::RtpReceiverState( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> signaling_task_runner, scoped_refptr<webrtc::RtpReceiverInterface> webrtc_receiver, std::unique_ptr<blink::WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref, std::vector<std::string> stream_id) : main_task_runner_(std::move(main_task_runner)), signaling_task_runner_(std::move(signaling_task_runner)), webrtc_receiver_(std::move(webrtc_receiver)), webrtc_dtls_transport_(webrtc_receiver_->dtls_transport()), webrtc_dtls_transport_information_(webrtc::DtlsTransportState::kNew), is_initialized_(false), track_ref_(std::move(track_ref)), stream_ids_(std::move(stream_id)) { DCHECK(main_task_runner_); DCHECK(signaling_task_runner_); DCHECK(webrtc_receiver_); DCHECK(track_ref_); if (webrtc_dtls_transport_) { webrtc_dtls_transport_information_ = webrtc_dtls_transport_->Information(); } } RtpReceiverState::RtpReceiverState(RtpReceiverState&& other) : main_task_runner_(other.main_task_runner_), signaling_task_runner_(other.signaling_task_runner_), webrtc_receiver_(std::move(other.webrtc_receiver_)), webrtc_dtls_transport_(std::move(other.webrtc_dtls_transport_)), webrtc_dtls_transport_information_( other.webrtc_dtls_transport_information_), is_initialized_(other.is_initialized_), track_ref_(std::move(other.track_ref_)), stream_ids_(std::move(other.stream_ids_)) { // Explicitly null |other|'s task runners for use in destructor. other.main_task_runner_ = nullptr; other.signaling_task_runner_ = nullptr; } RtpReceiverState::~RtpReceiverState() { // It's OK to not be on the main thread if this state has been moved, in which // case |main_task_runner_| is null. DCHECK(!main_task_runner_ || main_task_runner_->BelongsToCurrentThread()); } RtpReceiverState& RtpReceiverState::operator=(RtpReceiverState&& other) { DCHECK_EQ(main_task_runner_, other.main_task_runner_); DCHECK_EQ(signaling_task_runner_, other.signaling_task_runner_); // Explicitly null |other|'s task runners for use in destructor. other.main_task_runner_ = nullptr; other.signaling_task_runner_ = nullptr; webrtc_receiver_ = std::move(other.webrtc_receiver_); webrtc_dtls_transport_ = std::move(other.webrtc_dtls_transport_); webrtc_dtls_transport_information_ = other.webrtc_dtls_transport_information_; track_ref_ = std::move(other.track_ref_); stream_ids_ = std::move(other.stream_ids_); return *this; } bool RtpReceiverState::is_initialized() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return is_initialized_; } void RtpReceiverState::Initialize() { DCHECK(main_task_runner_->BelongsToCurrentThread()); if (is_initialized_) return; track_ref_->InitializeOnMainThread(); is_initialized_ = true; } scoped_refptr<base::SingleThreadTaskRunner> RtpReceiverState::main_task_runner() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return main_task_runner_; } scoped_refptr<base::SingleThreadTaskRunner> RtpReceiverState::signaling_task_runner() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return signaling_task_runner_; } scoped_refptr<webrtc::RtpReceiverInterface> RtpReceiverState::webrtc_receiver() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return webrtc_receiver_; } rtc::scoped_refptr<webrtc::DtlsTransportInterface> RtpReceiverState::webrtc_dtls_transport() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return webrtc_dtls_transport_; } webrtc::DtlsTransportInformation RtpReceiverState::webrtc_dtls_transport_information() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return webrtc_dtls_transport_information_; } const std::unique_ptr<blink::WebRtcMediaStreamTrackAdapterMap::AdapterRef>& RtpReceiverState::track_ref() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return track_ref_; } const std::vector<std::string>& RtpReceiverState::stream_ids() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return stream_ids_; } class RTCRtpReceiverImpl::RTCRtpReceiverInternal : public WTF::ThreadSafeRefCounted< RTCRtpReceiverImpl::RTCRtpReceiverInternal, RTCRtpReceiverImpl::RTCRtpReceiverInternalTraits> { public: RTCRtpReceiverInternal( scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection, RtpReceiverState state, bool force_encoded_audio_insertable_streams, bool force_encoded_video_insertable_streams) : native_peer_connection_(std::move(native_peer_connection)), main_task_runner_(state.main_task_runner()), signaling_task_runner_(state.signaling_task_runner()), webrtc_receiver_(state.webrtc_receiver()), state_(std::move(state)) { DCHECK(native_peer_connection_); DCHECK(state_.is_initialized()); if (force_encoded_audio_insertable_streams && webrtc_receiver_->media_type() == cricket::MEDIA_TYPE_AUDIO) { encoded_audio_transformer_ = std::make_unique<RTCEncodedAudioStreamTransformer>(main_task_runner_); webrtc_receiver_->SetDepacketizerToDecoderFrameTransformer( encoded_audio_transformer_->Delegate()); } if (force_encoded_video_insertable_streams && webrtc_receiver_->media_type() == cricket::MEDIA_TYPE_VIDEO) { encoded_video_transformer_ = std::make_unique<RTCEncodedVideoStreamTransformer>(main_task_runner_); webrtc_receiver_->SetDepacketizerToDecoderFrameTransformer( encoded_video_transformer_->Delegate()); } DCHECK(!encoded_audio_transformer_ || !encoded_video_transformer_); } const RtpReceiverState& state() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); return state_; } void set_state(RtpReceiverState state) { DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK(state.main_task_runner() == main_task_runner_); DCHECK(state.signaling_task_runner() == signaling_task_runner_); DCHECK(state.webrtc_receiver() == webrtc_receiver_); DCHECK(state.is_initialized()); state_ = std::move(state); } Vector<std::unique_ptr<RTCRtpSource>> GetSources() { // The webrtc_recever_ is a proxy, so this is a blocking call to the webrtc // signalling thread. auto webrtc_sources = webrtc_receiver_->GetSources(); Vector<std::unique_ptr<RTCRtpSource>> sources( static_cast<WTF::wtf_size_t>(webrtc_sources.size())); for (WTF::wtf_size_t i = 0; i < webrtc_sources.size(); ++i) { sources[i] = std::make_unique<RTCRtpSource>(webrtc_sources[i]); } return sources; } void GetStats(RTCStatsReportCallback callback, const Vector<webrtc::NonStandardGroupId>& exposed_group_ids) { signaling_task_runner_->PostTask( FROM_HERE, base::BindOnce(&RTCRtpReceiverInternal::GetStatsOnSignalingThread, this, std::move(callback), exposed_group_ids)); } std::unique_ptr<webrtc::RtpParameters> GetParameters() { return std::make_unique<webrtc::RtpParameters>( webrtc_receiver_->GetParameters()); } void SetJitterBufferMinimumDelay(absl::optional<double> delay_seconds) { webrtc_receiver_->SetJitterBufferMinimumDelay( blink::ToAbslOptional(delay_seconds)); } RTCEncodedAudioStreamTransformer* GetEncodedAudioStreamTransformer() const { return encoded_audio_transformer_.get(); } RTCEncodedVideoStreamTransformer* GetEncodedVideoStreamTransformer() const { return encoded_video_transformer_.get(); } private: friend class WTF::ThreadSafeRefCounted<RTCRtpReceiverInternal, RTCRtpReceiverInternalTraits>; friend struct RTCRtpReceiverImpl::RTCRtpReceiverInternalTraits; ~RTCRtpReceiverInternal() { DCHECK(main_task_runner_->BelongsToCurrentThread()); } void GetStatsOnSignalingThread( RTCStatsReportCallback callback, const Vector<webrtc::NonStandardGroupId>& exposed_group_ids) { native_peer_connection_->GetStats( webrtc_receiver_.get(), CreateRTCStatsCollectorCallback(main_task_runner_, std::move(callback), exposed_group_ids)); } const scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection_; // Task runners and webrtc receiver: Same information as stored in // |state_| but const and safe to touch on the signaling thread to // avoid race with set_state(). const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; const scoped_refptr<base::SingleThreadTaskRunner> signaling_task_runner_; const scoped_refptr<webrtc::RtpReceiverInterface> webrtc_receiver_; std::unique_ptr<RTCEncodedAudioStreamTransformer> encoded_audio_transformer_; std::unique_ptr<RTCEncodedVideoStreamTransformer> encoded_video_transformer_; RtpReceiverState state_; }; struct RTCRtpReceiverImpl::RTCRtpReceiverInternalTraits { static void Destruct(const RTCRtpReceiverInternal* receiver) { // RTCRtpReceiverInternal owns AdapterRefs which have to be destroyed on the // main thread, this ensures delete always happens there. if (!receiver->main_task_runner_->BelongsToCurrentThread()) { receiver->main_task_runner_->PostTask( FROM_HERE, base::BindOnce( &RTCRtpReceiverImpl::RTCRtpReceiverInternalTraits::Destruct, base::Unretained(receiver))); return; } delete receiver; } }; uintptr_t RTCRtpReceiverImpl::getId( const webrtc::RtpReceiverInterface* webrtc_rtp_receiver) { return reinterpret_cast<uintptr_t>(webrtc_rtp_receiver); } RTCRtpReceiverImpl::RTCRtpReceiverImpl( scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection, RtpReceiverState state, bool force_encoded_audio_insertable_streams, bool force_encoded_video_insertable_streams) : internal_(base::MakeRefCounted<RTCRtpReceiverInternal>( std::move(native_peer_connection), std::move(state), force_encoded_audio_insertable_streams, force_encoded_video_insertable_streams)) {} RTCRtpReceiverImpl::RTCRtpReceiverImpl(const RTCRtpReceiverImpl& other) : internal_(other.internal_) {} RTCRtpReceiverImpl::~RTCRtpReceiverImpl() {} RTCRtpReceiverImpl& RTCRtpReceiverImpl::operator=( const RTCRtpReceiverImpl& other) { internal_ = other.internal_; return *this; } const RtpReceiverState& RTCRtpReceiverImpl::state() const { return internal_->state(); } void RTCRtpReceiverImpl::set_state(RtpReceiverState state) { internal_->set_state(std::move(state)); } std::unique_ptr<RTCRtpReceiverPlatform> RTCRtpReceiverImpl::ShallowCopy() const { return std::make_unique<RTCRtpReceiverImpl>(*this); } uintptr_t RTCRtpReceiverImpl::Id() const { return getId(internal_->state().webrtc_receiver().get()); } rtc::scoped_refptr<webrtc::DtlsTransportInterface> RTCRtpReceiverImpl::DtlsTransport() { return internal_->state().webrtc_dtls_transport(); } webrtc::DtlsTransportInformation RTCRtpReceiverImpl::DtlsTransportInformation() { return internal_->state().webrtc_dtls_transport_information(); } MediaStreamComponent* RTCRtpReceiverImpl::Track() const { return internal_->state().track_ref()->track(); } Vector<String> RTCRtpReceiverImpl::StreamIds() const { const auto& stream_ids = internal_->state().stream_ids(); Vector<String> wtf_stream_ids( static_cast<WTF::wtf_size_t>(stream_ids.size())); for (WTF::wtf_size_t i = 0; i < stream_ids.size(); ++i) wtf_stream_ids[i] = String::FromUTF8(stream_ids[i]); return wtf_stream_ids; } Vector<std::unique_ptr<RTCRtpSource>> RTCRtpReceiverImpl::GetSources() { return internal_->GetSources(); } void RTCRtpReceiverImpl::GetStats( RTCStatsReportCallback callback, const Vector<webrtc::NonStandardGroupId>& exposed_group_ids) { internal_->GetStats(std::move(callback), exposed_group_ids); } std::unique_ptr<webrtc::RtpParameters> RTCRtpReceiverImpl::GetParameters() const { return internal_->GetParameters(); } void RTCRtpReceiverImpl::SetJitterBufferMinimumDelay( absl::optional<double> delay_seconds) { internal_->SetJitterBufferMinimumDelay(delay_seconds); } RTCEncodedAudioStreamTransformer* RTCRtpReceiverImpl::GetEncodedAudioStreamTransformer() const { return internal_->GetEncodedAudioStreamTransformer(); } RTCEncodedVideoStreamTransformer* RTCRtpReceiverImpl::GetEncodedVideoStreamTransformer() const { return internal_->GetEncodedVideoStreamTransformer(); } RTCRtpReceiverOnlyTransceiver::RTCRtpReceiverOnlyTransceiver( std::unique_ptr<RTCRtpReceiverPlatform> receiver) : receiver_(std::move(receiver)) { DCHECK(receiver_); } RTCRtpReceiverOnlyTransceiver::~RTCRtpReceiverOnlyTransceiver() {} RTCRtpTransceiverPlatformImplementationType RTCRtpReceiverOnlyTransceiver::ImplementationType() const { return RTCRtpTransceiverPlatformImplementationType::kPlanBReceiverOnly; } uintptr_t RTCRtpReceiverOnlyTransceiver::Id() const { NOTIMPLEMENTED(); return 0u; } String RTCRtpReceiverOnlyTransceiver::Mid() const { NOTIMPLEMENTED(); return String(); } std::unique_ptr<blink::RTCRtpSenderPlatform> RTCRtpReceiverOnlyTransceiver::Sender() const { NOTIMPLEMENTED(); return nullptr; } std::unique_ptr<RTCRtpReceiverPlatform> RTCRtpReceiverOnlyTransceiver::Receiver() const { return receiver_->ShallowCopy(); } bool RTCRtpReceiverOnlyTransceiver::Stopped() const { NOTIMPLEMENTED(); return false; } webrtc::RtpTransceiverDirection RTCRtpReceiverOnlyTransceiver::Direction() const { NOTIMPLEMENTED(); return webrtc::RtpTransceiverDirection::kSendOnly; } webrtc::RTCError RTCRtpReceiverOnlyTransceiver::SetDirection( webrtc::RtpTransceiverDirection direction) { NOTIMPLEMENTED(); return webrtc::RTCError::OK(); } absl::optional<webrtc::RtpTransceiverDirection> RTCRtpReceiverOnlyTransceiver::CurrentDirection() const { NOTIMPLEMENTED(); return webrtc::RtpTransceiverDirection::kSendOnly; } absl::optional<webrtc::RtpTransceiverDirection> RTCRtpReceiverOnlyTransceiver::FiredDirection() const { NOTIMPLEMENTED(); return webrtc::RtpTransceiverDirection::kSendOnly; } webrtc::RTCError RTCRtpReceiverOnlyTransceiver::SetCodecPreferences( Vector<webrtc::RtpCodecCapability>) { NOTIMPLEMENTED(); return {}; } } // namespace blink
35.907407
100
0.771725
zealoussnow
70bdfafed8ec1bf977d2c2dad470d11906bf44f9
2,910
cpp
C++
src/identify.cpp
clockley/watchdogd
7f03ad9a7317a11f246d29bce411d1e50265aa0e
[ "Apache-2.0" ]
17
2016-03-22T12:20:07.000Z
2022-01-24T17:49:39.000Z
src/identify.cpp
clockley/watchdogd
7f03ad9a7317a11f246d29bce411d1e50265aa0e
[ "Apache-2.0" ]
1
2021-10-04T17:35:13.000Z
2021-10-05T16:55:46.000Z
src/identify.cpp
clockley/watchdogd
7f03ad9a7317a11f246d29bce411d1e50265aa0e
[ "Apache-2.0" ]
1
2021-12-05T13:23:26.000Z
2021-12-05T13:23:26.000Z
/* * Copyright 2016-2020 Christian Lockley * * 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 "watchdogd.hpp" int Identify(long timeout, const char * identity, const char * deviceName, bool verbose) { struct sockaddr_un address = {0}; struct identinfo buf; int fd = -1; address.sun_family = AF_UNIX; strncpy(address.sun_path, "\0watchdogd.wdt.identity", sizeof(address.sun_path)-1); fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); if (fd < 0) { goto error; } if (connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) { close(fd); goto direct; } read(fd, &buf, sizeof(buf)); close(fd); if (verbose) { printf("watchdog was set to %li seconds\n", buf.timeout); } printf("%s\n", buf.name); return 0; direct: if (!identity) { size_t len0 = 0, len1 = 0; int addZero = isdigit(*(basename(deviceName)+(strlen(basename(deviceName))-1))); size_t l = strlen(basename(deviceName))+1; char * watchdogBasename = (char*)calloc(1, l+1); memcpy(watchdogBasename, basename(deviceName), l); if (!addZero) { watchdogBasename[strlen(watchdogBasename)] = '0'; } char * sysfsIdentity = (char*)calloc(1, strlen(watchdogBasename)+strlen("/sys/class/watchdog//identity")+1); char * sysfsTimeout = (char*)calloc(1, strlen(watchdogBasename)+strlen("/sys/class/watchdog//identity")+1); sprintf(sysfsIdentity, "/sys/class/watchdog/%s/identity", watchdogBasename); sprintf(sysfsTimeout, "/sys/class/watchdog/%s/timeout", watchdogBasename); FILE * timeoutFile = fopen(sysfsTimeout, "r"); FILE * identityFile = fopen(sysfsIdentity, "r"); if (!identityFile||!timeoutFile) goto error; char *timeoutString = nullptr; char *identityString = nullptr; getline(&timeoutString, &len0, timeoutFile); getline(&identityString, &len1, identityFile); timeoutString[strlen(timeoutString)-1] = '\0'; identityString[strlen(identityString)-1] = '\0'; if (verbose) { printf("watchdog was set to %s seconds\n", timeoutString); } printf("%s\n", identityString); return 0; } if (verbose) { printf("watchdog was set to %li seconds\n", timeout); } printf("%s\n", identity); return 0; error: if (access(deviceName, R_OK|W_OK) != 0) { printf("%s\n", "unable to open watchdog device, this operation requires permission from system Administrator"); return 0; } printf("%s\n", "Unable to open watchdog device"); return 0; }
27.980769
113
0.697595
clockley
70c1f6d21350d470cb8a297fae9ecc084afc3114
7,285
cpp
C++
Bonepick/test/engine/TestSystems.cpp
dodgelafnitz/Bonepick
1a12193e5d0cf5d4061d0d3cbd1529a206ed38f4
[ "MIT" ]
3
2018-10-09T02:08:57.000Z
2020-08-12T20:26:29.000Z
Bonepick/test/engine/TestSystems.cpp
dodgelafnitz/Bonepick
1a12193e5d0cf5d4061d0d3cbd1529a206ed38f4
[ "MIT" ]
1
2018-09-30T02:42:39.000Z
2018-09-30T02:42:39.000Z
Bonepick/test/engine/TestSystems.cpp
dodgelafnitz/Bonepick
1a12193e5d0cf5d4061d0d3cbd1529a206ed38f4
[ "MIT" ]
null
null
null
#include "test/engine/TestSystems.h" #include "engine/system/Entity.h" #include "engine/system/EntityManager.h" #include "engine/utility/Debug.h" namespace { //############################################################################ void TestEntityManagerSingleComponent(void) { EntityManager<float> entMan; int const ent0 = entMan.AddEntity(2.0f); int const ent1 = entMan.AddEntity(3.0f); int const nonEnt = (ent0 + 1 == ent1 ? ent1 : ent0) + 1; ASSERT(entMan.EntityCount() == 0); entMan.Advance(); ASSERT(entMan.EntityCount() == 2); ASSERT(entMan.GetComponent<float>(ent0) == 2.0f); ASSERT(entMan.GetComponent<float>(ent1) == 3.0f); ASSERT(entMan.ContainsComponent<float>(ent0)); ASSERT(entMan.ContainsComponent<float>(ent1)); EXPECT_ERROR(entMan.ContainsComponent<float>(nonEnt);); EXPECT_ERROR(entMan.GetComponent<float>(nonEnt);); entMan.SetComponent<float>(ent0, 4.0f); entMan.Advance(); ASSERT(entMan.GetComponent<float>(ent0) == 4.0f); entMan.SetComponent<float>(ent0, 2.0f); ASSERT(entMan.GetComponent<float>(ent0) == 4.0f); EXPECT_ERROR(entMan.SetComponent<float>(ent0, 3.0f);); entMan.UpdateComponent<float>(ent0) = 3.5f; entMan.UpdateComponent<float>(ent1) = 5.5f; entMan.Advance(); ASSERT(entMan.GetComponent<float>(ent0) == 3.5f); ASSERT(entMan.GetComponent<float>(ent1) == 5.5f); } //############################################################################ void TestEntityManagerMultipleComponents(void) { EntityManager<float, int, bool> entMan; int const ent0 = entMan.AddEntity(4.0f, 2); int const ent1 = entMan.AddEntity(false, 2.0f); int const ent2 = entMan.AddEntity(7, 3.0f, true); ASSERT(entMan.EntityCount() == 0); entMan.Advance(); ASSERT(entMan.EntityCount() == 3); ASSERT(entMan.GetComponent<float>(ent0) == 4.0f); ASSERT(entMan.ContainsComponent<float>(ent0)); ASSERT(entMan.ContainsComponent<float>(ent1)); ASSERT(entMan.ContainsComponent<float>(ent2)); ASSERT(entMan.ContainsComponent<int>(ent0)); ASSERT(!entMan.ContainsComponent<int>(ent1)); ASSERT(entMan.ContainsComponent<int>(ent2)); ASSERT(!entMan.ContainsComponent<bool>(ent0)); ASSERT(entMan.ContainsComponent<bool>(ent1)); ASSERT(entMan.ContainsComponent<bool>(ent2)); entMan.UpdateComponent<float>(ent1) = 3.5f; EXPECT_ERROR(entMan.UpdateComponent<bool>(ent0);); ASSERT(entMan.GetComponent<float>(ent0) == 4.0f); ASSERT(entMan.GetComponent<float>(ent1) == 2.0f); ASSERT(entMan.GetComponent<float>(ent2) == 3.0f); ASSERT(entMan.GetComponent<int>(ent0) == 2); ASSERT(entMan.GetComponent<int>(ent2) == 7); ASSERT(entMan.GetComponent<bool>(ent1) == false); ASSERT(entMan.GetComponent<bool>(ent2) == true); entMan.Advance(); ASSERT(entMan.GetComponent<float>(ent1) == 3.5f); entMan.AddComponent(ent1, 4); entMan.RemoveComponent<bool>(ent1); entMan.Advance(); ASSERT(entMan.GetComponent<int>(ent1) == 4); ASSERT(!entMan.ContainsComponent<bool>(ent1)); } //############################################################################ void TestEntityManagerDestruction(void) { EntityManager<float, int, bool> entMan; int const ent0 = entMan.AddEntity(4.0f, 2); int const ent1 = entMan.AddEntity(false, 2.0f); int const ent2 = entMan.AddEntity(7, 3.0f, true); EXPECT_ERROR(entMan.DestroyEntity(ent1);); entMan.Advance(); entMan.DestroyEntity(ent1); ASSERT(entMan.EntityCount() == 3); entMan.Advance(); ASSERT(entMan.EntityCount() == 2); ASSERT(entMan.DoesEntityExist(ent1) == false); } //############################################################################ void TestEntityManagerGroupGetters(void) { using EntMan = EntityManager<float, int, bool>; EntMan entMan; int const ent0 = entMan.AddEntity(4.0f, 2); int const ent1 = entMan.AddEntity(false, 2.0f); int const ent2 = entMan.AddEntity(7, 3.0f, true); entMan.Advance(); auto compArray = entMan.GetComponents<float, bool>(); SortedArray<int> const & entityIds = compArray.EntityIds(); Array<bool const *> const & compBools = compArray.Components<bool>(); Array<float const *> const & compFloats = compArray.Components<float>(); ASSERT(entityIds.Size() == 2); ASSERT(compBools.Size() == 2); ASSERT(compFloats.Size() == 2); int const ents[2] = { ent1, ent2 }; bool found[2] = { false, false }; for (int i = 0; i < entityIds.Size(); ++i) { ASSERT(entMan.GetEntityId(compBools[i]) == entityIds[i]); ASSERT(entMan.GetEntityId(compFloats[i]) == entityIds[i]); for (int j = 0; j < 2; ++j) { if (entityIds[i] == ents[j]) { ASSERT(!found[j]); found[j] = true; break; } } } ASSERT(found[0] && found[1]); } //############################################################################ void TestEntityManagerIdGetterHelper( EntityManager<float, int, bool> const & entMan) { Array<int> entityIds; for (int i = 0; i < entMan.EntityCount(); ++i) { ASSERT(!entityIds.Contains(entMan.GetEntityId(i))); entityIds.EmplaceBack(entMan.GetEntityId(i)); } ASSERT(entityIds.Size() == entMan.EntityCount()); } //############################################################################ void TestEntityManagerIdGetter(void) { EntityManager<float, int, bool> entMan; int const ent0 = entMan.AddEntity(4.0f, 2); int const ent1 = entMan.AddEntity(false, 2.0f); int const ent2 = entMan.AddEntity(7, 3.0f, true); entMan.Advance(); TestEntityManagerIdGetterHelper(entMan); entMan.DestroyEntity(ent1); entMan.Advance(); TestEntityManagerIdGetterHelper(entMan); int const ent3 = entMan.AddEntity(2.5f, false, 4); entMan.Advance(); TestEntityManagerIdGetterHelper(entMan); entMan.DestroyEntity(ent2); entMan.DestroyEntity(ent3); entMan.DestroyEntity(ent0); entMan.Advance(); TestEntityManagerIdGetterHelper(entMan); } //############################################################################ void TestEntityCreation(void) { EntityManager<float, int> entMan; int const entIndex = entMan.AddEntity(2.0f); Entity<float, int> ent(entMan, entIndex); auto easyEnt = MakeEntity(entMan, entIndex); ASSERT(easyEnt == ent); ASSERT(!(easyEnt != ent)); EXPECT_ERROR(ent.GetComponent<float>();); entMan.Advance(); ASSERT(ent.GetComponent<float>() == 2.0f); EXPECT_ERROR(ent.GetComponent<int>();); } //############################################################################ void TestEntityManagers(void) { TestEntityManagerSingleComponent(); TestEntityManagerMultipleComponents(); TestEntityManagerDestruction(); TestEntityManagerGroupGetters(); } //############################################################################ void TestEntities(void) { TestEntityCreation(); } } //############################################################################## void TestAllSystems(void) { TestEntityManagers(); TestEntities(); }
29.257028
80
0.588058
dodgelafnitz
70c3646edaee819442ad1234fd06f86882809484
23,952
hpp
C++
website/src/cgiroot.hpp
Wt-Works/saai.ir
18b9e75616300994c8d5034f766b6e91c6a48c16
[ "MIT", "Unlicense" ]
1
2021-08-28T01:24:22.000Z
2021-08-28T01:24:22.000Z
website/src/cgiroot.hpp
Wt-Works/saai.ir
18b9e75616300994c8d5034f766b6e91c6a48c16
[ "MIT", "Unlicense" ]
null
null
null
website/src/cgiroot.hpp
Wt-Works/saai.ir
18b9e75616300994c8d5034f766b6e91c6a48c16
[ "MIT", "Unlicense" ]
null
null
null
#ifndef CGIROOT_HPP #define CGIROOT_HPP #include <string> #include <Wt/WAnchor> #include <Wt/WApplication> #include <Wt/WButtonGroup> #include <Wt/WComboBox> #include <Wt/WContainerWidget> #include <Wt/WDialog> #include <Wt/WEnvironment> #include <Wt/WFileUpload> #include <Wt/WFormWidget> #include <Wt/WImage> #include <Wt/WInPlaceEdit> #include <Wt/WIntValidator> #include <Wt/WLineEdit> #include <Wt/WLengthValidator> #include <Wt/WMenuItem> #include <Wt/WMessageBox> #include <Wt/WPushButton> #include <Wt/WRegExpValidator> #include <Wt/WSignalMapper> #include <Wt/WString> #include <Wt/WText> #include <Wt/WTextArea> #include <Wt/WTextEdit> #include <Wt/WWidget> #include "clientinfo.hpp" #include "db.hpp" #include "serverinfo.hpp" namespace SAAIIR { class CgiRoot; } class SAAIIR::CgiRoot : public Wt::WApplication { public: CgiRoot(const Wt::WEnvironment& env); virtual ~CgiRoot(); private: ClientInfo *clientInfo; ServerInfo *serverInfo; std::string __loggedInUser; std::string __lastIP; std::string __lastCCode; std::string __lastCName; std::string __lastDate; std::string __lastTime; std::string __acLoggedInUser; std::string __acLoggedInCode; std::string __acLastIP; std::string __acLastCCode; std::string __acLastCName; std::string __acLastDate; std::string __acLastTime; int __capResult; std::string __capImage; void GenCap(); void InitEnv(const Wt::WEnvironment& env); bool IsReqRoot(const Wt::WEnvironment& env); std::string IsReqACP(const Wt::WEnvironment& env); DB db; DB dbPics; bool Validate(Wt::WFormWidget *widget); bool ValidatePic(const std::string& file); void ValidatePicClose(Wt::WDialog *sender); bool ValidatePicFlag; std::string ValidatePicPostAction; std::string ValidatePicPostArgs; /************* Home *************/ Wt::WWidget *Initialize_Home(); Wt::WContainerWidget *dvMainWrapper; Wt::WContainerWidget *dvRegister; Wt::WWidget *CMainMenu(); Wt::WWidget *CHowTo(); Wt::WWidget *CLinks(); Wt::WWidget *CContact(); Wt::WWidget *CAbout(); Wt::WMenu *mainMenu; Wt::WContainerWidget *dvMainVote; Wt::WLineEdit *followEdit; Wt::WLineEdit *followCapEdit; Wt::WLineEdit *academyUserEdit; Wt::WLineEdit *academyPwEdit; Wt::WLineEdit *academyCapEdit; Wt::WLineEdit *voteCapEdit; Wt::WLineEdit *regTyroCapEdit; Wt::WImage *followCaptcha; Wt::WImage *academyCaptcha; Wt::WImage *voteCaptcha; Wt::WImage *regTyroCaptcha; Wt::WIntValidator *followCapValidator; Wt::WIntValidator *academyCapValidator; Wt::WIntValidator *voteCapValidator; Wt::WIntValidator *regTyroCapValidator; Wt::WText *errFollowing; Wt::WText *errACLogin; Wt::WText *errVote; Wt::WButtonGroup *dvMainVoteRadioGroup; bool IsForgetFormShownAcademy; Wt::WContainerWidget *dvForgetFormWrapperAcademy; Wt::WText *errForgetAcademy; Wt::WLineEdit *forgetEmailEditAcademy; Wt::WLineEdit *forgetCapEditAcademy; Wt::WIntValidator *forgetCapValidatorAcademy; Wt::WRegExpValidator *forgetEmailValidatorAcademy; void ForgetOKAcademy(); void ReGenCap(); void AcademyForgetForm(); void FollowingOK(); void AcademiesOK(); void VoteOK(); void VoteChart(); Wt::WText *errContactForm; Wt::WComboBox *contactToCmb; Wt::WLineEdit *contactFromEdit; Wt::WLineEdit *contactEmailEdit; Wt::WLineEdit *contactUrlEdit; Wt::WLineEdit *contactSubjectEdit; Wt::WTextArea *contactBodyTArea; Wt::WPushButton *contactSendBtn; Wt::WPushButton *contactClearBtn; Wt::WLineEdit *contactCapEdit; Wt::WImage *contactCaptcha; Wt::WLengthValidator *contactFromValidator; Wt::WRegExpValidator *contactEmailValidator; Wt::WRegExpValidator *contactUrlValidator; Wt::WLengthValidator *contactSubjectValidator; Wt::WLengthValidator *contactBodyValidator; Wt::WIntValidator *contactCapValidator; void SetCContactForm(bool flag); void ContactToCmbChanged(Wt::WString to); void ContactClearOK_RP(); void SendMessageOK(); Wt::WDialog *dlg; Wt::WMessageBox *msgBox; Wt::WComboBox *regProvinceCmb; Wt::WComboBox *regCityCmb; Wt::WLineEdit *regTermTitleEdit; Wt::WComboBox *regTermBegdateCmbY; Wt::WComboBox *regTermBegdateCmbM; Wt::WComboBox *regTermBegdateCmbD; Wt::WComboBox *regTermEnddateCmbY; Wt::WComboBox *regTermEnddateCmbM; Wt::WComboBox *regTermEnddateCmbD; Wt::WComboBox *regTermDaypartCmb; Wt::WLineEdit *tyroFNameEdit; Wt::WLineEdit *tyroLNameEdit; Wt::WComboBox *tyroSexCmb ; Wt::WLineEdit *tyroFatherSNameEdit; Wt::WLineEdit *tyroNationalCodeEdit; Wt::WLineEdit *tyroBirthIdEdit; Wt::WComboBox *tyroBirthDateCmbY; Wt::WComboBox *tyroBirthDateCmbM; Wt::WComboBox *tyroBirthDateCmbD; Wt::WComboBox *tyroBirthlocCmb; Wt::WComboBox *tyroBirthEmissionLocCmb; Wt::WComboBox *tyroGraduateCertCmb; Wt::WLineEdit *tyroGraduateCourseEdit; Wt::WComboBox *tyroJobCmb; Wt::WTextArea *tyroAddrTArea; Wt::WLineEdit *tyroTelEdit; Wt::WLineEdit *tyroMobileEdit; Wt::WLineEdit *tyroEmailEdit; Wt::WLengthValidator *tyroFNameValidator; Wt::WLengthValidator *tyroLNameValidator; Wt::WLengthValidator *tyroSexValidator; Wt::WLengthValidator *tyroFatherSNameValidator; Wt::WRegExpValidator *tyroNationalCodeValidator; Wt::WRegExpValidator *tyroBirthIdValidator; Wt::WLengthValidator *tyroBirthDateYValidator; Wt::WLengthValidator *tyroBirthDateMValidator; Wt::WLengthValidator *tyroBirthDateDValidator; Wt::WLengthValidator *tyroBirthlocValidator; Wt::WLengthValidator *tyroBirthEmissionLocValidator; Wt::WLengthValidator *tyroGraduateCertValidator; Wt::WLengthValidator *tyroGraduateCourseValidator; Wt::WLengthValidator *tyroJobValidator; Wt::WLengthValidator *tyroAddrValidator; Wt::WRegExpValidator *tyroTelValidator; Wt::WRegExpValidator *tyroMobileValidator; Wt::WRegExpValidator *tyroEmailValidator; Wt::WText *errTyroForm; Wt::WFileUpload *tyroPicBirthCertFUP; Wt::WFileUpload *tyroPicNationalCardFUP; Wt::WFileUpload *tyroPicPersonnelFUP; Wt::WFileUpload *tyroPicServiceFUP; Wt::WPushButton *tyroPicBirthCertBtn; Wt::WPushButton *tyroPicNationalCardBtn; Wt::WPushButton *tyroPicPersonnelBtn; Wt::WPushButton *tyroPicServiceBtn; Wt::WPushButton *tyroRegFinishBtn; std::string regTermAcCode, regTermActCode, regTermStTitle, regTermBegdate, regTermEnddate, regTermDaypart, regTermBegtime, regTermEndtime, regTermLoc, regTermAcmName; std::string regTyroFName, regTyroLName, regTyroSex, regTyroFatherSName, regTyroNationalCode, regTyroBirthId, regTyroBirthDateY, regTyroBirthDateM, regTyroBirthDateD, regTyroBirthloc, regTyroBirthEmissionLoc, regTyroGraduateCert, regTyroGraduateCourse, regTyroJob, regTyroAddr, regTyroTel, regTyroMobile, regTyroEmail; void RegProvinceCmbChanged(Wt::WString pr); void ReturnHome(); void RegStep_2(); void RegStep_3(Wt::WPushButton *sender); void RegStep_4(); void RegStep_5(); void RegStep_5_1(); void RegStep_5_2(); void RegStep_5_3(); void RegStep_5_4(); void RegStep_6(); /************* End Home *************/ /************* Root Login *************/ Wt::WContainerWidget *dvForgetFormWrapper_Root; bool IsForgetFormShown_Root; Wt::WImage *loginCaptcha_Root; Wt::WIntValidator *loginCapValidator_Root; Wt::WIntValidator *forgetCapValidator_Root; Wt::WLengthValidator *loginUserValidator_Root; Wt::WLengthValidator *loginPwValidator_Root; Wt::WRegExpValidator *forgetEmailValidator_Root; Wt::WText *errLogin_Root; Wt::WText *errForget_Root; void Error_Root(const std::wstring& err, Wt::WText *txt); Wt::WLineEdit *loginUserEdit_Root; Wt::WLineEdit *loginPwEdit_Root; Wt::WLineEdit *loginCapEdit_Root; Wt::WLineEdit *forgetEmailEdit_Root; Wt::WLineEdit *forgetCapEdit_Root; Wt::WWidget *Initialize_Root(); void InitializeTables_Root(); Wt::WWidget *RootLoginForm(); Wt::WWidget *RootRegisterForm(); void RootForgetForm(); void ReGenCap_Root(); void LoginOK_Root(); void ForgetOK_Root(); /************* End Root Login *************/ /************* Root Panel *************/ Wt::WMenu *mainMenu_RP; void ExitRootPanel(Wt::WMenuItem *mItem); /*Wt::WWidget *CHome_RP(); Wt::WWidget *CBase_RP();*/ Wt::WWidget *CAcademies_RP(); Wt::WWidget *CPages_RP(); Wt::WWidget *CContact_RP(); Wt::WWidget *CPwEMail_RP(); Wt::WWidget *CExit_RP(); void Initialize_RP(); Wt::WComboBox *pagesPListCmb_RP; Wt::WTextEdit *pagesTEdit_RP; Wt::WPushButton *pagesSaveBtn_RP; Wt::WPushButton *pagesCloseBtn_RP; std::wstring GetPageContent(const std::string& pg); void SetPageContent(const std::string& pg, const std::string& content); void SetCPagesForm_RP(bool flag); void PagesPListCmbChanged_RP(Wt::WString pg); void PagesTEditChanged_RP(); void PagesSaveBtnOK_RP(); void PagesCloseBtnOK_RP(); Wt::WLineEdit *currentPwEdit_RP; Wt::WLineEdit *newPwEdit_RP; Wt::WLineEdit *confirmPwEdit_RP; Wt::WLineEdit *currentEmailEdit_RP; Wt::WLineEdit *currentPwEmailEdit_RP; Wt::WLengthValidator *currentPwValidator_RP; Wt::WLengthValidator *newPwValidator_RP; Wt::WLengthValidator *confirmPwValidator_RP; Wt::WRegExpValidator *currentEmailValidator_RP; Wt::WLengthValidator *currentPwEmailValidator_RP; Wt::WText *errPw_RP; Wt::WText *errEmail_RP; void PwOK_RP(); void EmailOK_RP(); Wt::WText *errAddContact_RP; Wt::WLengthValidator *contactNameValidator_RP; Wt::WRegExpValidator *contactAddrValidator_RP; Wt::WLineEdit *contactNameEdit_RP; Wt::WLineEdit *contactAddrEdit_RP; Wt::WPushButton *contactSaveBtn_RP; Wt::WContainerWidget *dvContactTableWrapper_RP; Wt::WInPlaceEdit *GetContactCell_RP(const std::string& cell, const std::string& id, const char *field, Wt::WSignalMapper<Wt::WInPlaceEdit *> *map); Wt::WPushButton *tableBtn_RP; void CContactDataTable_RP(); void SaveContactTableCell_RP(Wt::WInPlaceEdit *sender); void EraseContactTableCell_RP(Wt::WPushButton *sender); void EraseContactTableCellOK_RP(Wt::StandardButton result); void AddContactOK_RP(); Wt::WComboBox *academiesProvinceCmb_RP; Wt::WComboBox *academiesCityCmb_RP; void SetCAcademiesForm_RP(int flag); void AcademiesProvinceCmbChanged_RP(Wt::WString pr); void AcademiesCityCmbChanged_RP(Wt::WString pr); void AcademiesAddBtnOK_RP(); //void AcademiesReturnBtnOK_RP(); Wt::WContainerWidget *dvAcademiesWrapper_RP; Wt::WPushButton *academiesAddBtn_RP; //Wt::WPushButton *academiesReturnBtn_RP; void CAcademiesDataTable_RP(); void CourseAcademiesTableCell_RP(Wt::WPushButton *sender); void MoreInfoAcademiesTableCell_RP(Wt::WAnchor *sender); void MoreInfoAcademiesTableCell_RP(Wt::WPushButton *sender); //void CpAcademiesTableCell_RP(Wt::WAnchor *sender); void SuspendAcademiesTableCell_RP(Wt::WPushButton *sender); void SuspendAcademiesTableCellOK_RP(Wt::StandardButton result); void EditAcademiesTableCell_RP(Wt::WPushButton *sender); void EraseAcademiesTableCell_RP(Wt::WPushButton *sender); void EraseAcademiesTableCellOK_RP(Wt::StandardButton result); Wt::WLineEdit *academiesNameEdit_RP; Wt::WComboBox *academiesSexCmb_RP; Wt::WLineEdit *academiesSubstationEdit_RP; Wt::WComboBox *academiesJustificationCmb_RP; Wt::WTextArea *academiesAddrTArea_RP; Wt::WLineEdit *academiesTelEdit_RP; Wt::WLineEdit *academiesManagerEdit_RP; Wt::WLineEdit *academiesFounderEdit_RP; Wt::WLineEdit *academiesUserEdit_RP; Wt::WLineEdit *academiesPwEdit_RP; Wt::WPushButton *academiesSaveBtn_RP; /*Wt::WPushButton *eraseAcademiesBtn_RP; Wt::WPushButton *suspendAcademiesBtn_RP;*/ Wt::WLengthValidator *academiesNameValidator_RP; Wt::WLengthValidator *academiesSexValidator_RP; Wt::WIntValidator *academiesSubstationValidator_RP; Wt::WLengthValidator *academiesJustificationValidator_RP; Wt::WLengthValidator *academiesAddrValidator_RP; Wt::WRegExpValidator *academiesTelValidator_RP; Wt::WLengthValidator *academiesManagerValidator_RP; Wt::WLengthValidator *academiesFounderValidator_RP; Wt::WLengthValidator *academiesUserValidator_RP; Wt::WLengthValidator *academiesPwValidator_RP; Wt::WText *errAcademiesForm_RP; Wt::WWidget *GetAcademiesForm_RP(Wt::WString form); void AcademiesFormSaveBtnOK_RP(); void AcCourseAddBtnOK_RP(Wt::WPushButton *sender); void GetAcCourseDialog_RP(std::string acCode); void GetAcCourseDialog_RP(); void EditAcCourseTableCell_RP(Wt::WPushButton *sender); void EraseAcCourseTableCell_RP(Wt::WPushButton *sender); void EraseAcCourseTableCellOK_RP(Wt::StandardButton result); Wt::WComboBox *acCourseSkTitleCmb_RP; Wt::WLineEdit *acCourseBackgroundEdit_RP; Wt::WComboBox *acCourseJustdateCmbY_RP; Wt::WComboBox *acCourseJustdateCmbM_RP; Wt::WComboBox *acCourseJustdateCmbD_RP; Wt::WComboBox *acCourseActstatCmb_RP; Wt::WLineEdit *acCourseTyroaveragEdit_RP; Wt::WPushButton *courseSaveBtn_RP; Wt::WPushButton *eraseAcCourseBtn_RP; Wt::WPushButton *suspendAcCourseBtn_RP; Wt::WLengthValidator *acCourseSkTitleValidator_RP; Wt::WIntValidator *acCourseBackgroundValidator_RP; Wt::WLengthValidator *acCourseJustdateValidatorY_RP; Wt::WLengthValidator *acCourseJustdateValidatorM_RP; Wt::WLengthValidator *acCourseJustdateValidatorD_RP; Wt::WLengthValidator *acCourseActstatValidator_RP; Wt::WIntValidator *acCourseTyroaveragValidator_RP; Wt::WText *errAcCourseForm_RP; Wt::WWidget *GetAcCourseForm_RP(Wt::WString form); void AcCourseFormSaveBtnOK_RP(); /************* End Root Panel *************/ /************* Academy Panel *************/ void Initialize_ACP(); void ClearLoginForm_ACP(); Wt::WContainerWidget *academyPage; Wt::WWidget *FirstLogin_ACP(); Wt::WText *errConfirmFL_ACP; Wt::WLineEdit *newEmailEditFL_ACP; Wt::WLineEdit *confirmEmailEditFL_ACP; Wt::WLineEdit *newPwEditFL_ACP; Wt::WLineEdit *confirmPwEditFL_ACP; Wt::WLineEdit *currentPwEditFL_ACP; Wt::WPushButton *btnConfirmOK; Wt::WRegExpValidator *newEmailValidatorFL_ACP; Wt::WRegExpValidator *confirmEmailValidatorFL_ACP; Wt::WLengthValidator *newPwValidatorFL_ACP; Wt::WLengthValidator *confirmPwValidatorFL_ACP; Wt::WLengthValidator *currentPwValidatorFL_ACP; void ConfirmOKFL_ACP(); std::string AcSessionGen(const std::string& acCode, bool isRoot); bool AcSessionValidate(const std::string& session); void Go_ACPanel(const std::string& acCode); void GoAway_ACP(); void Initialize_ACPanel(); Wt::WMenu *mainMenu_ACP; void ExitACPanel(Wt::WMenuItem *mItem); Wt::WWidget *CMentors_ACP(); Wt::WWidget *CTyros_ACP(); Wt::WWidget *CTerms_ACP(); Wt::WWidget *CPwEMail_ACP(); Wt::WWidget *CExit_ACP(); Wt::WLineEdit *currentPwEdit_ACP; Wt::WLineEdit *newPwEdit_ACP; Wt::WLineEdit *confirmPwEdit_ACP; Wt::WLineEdit *currentEmailEdit_ACP; Wt::WLineEdit *currentPwEmailEdit_ACP; Wt::WLengthValidator *currentPwValidator_ACP; Wt::WLengthValidator *newPwValidator_ACP; Wt::WLengthValidator *confirmPwValidator_ACP; Wt::WRegExpValidator *currentEmailValidator_ACP; Wt::WLengthValidator *currentPwEmailValidator_ACP; Wt::WText *errPw_ACP; Wt::WText *errEmail_ACP; void PwOK_ACP(); void EmailOK_ACP(); void MentorsAddBtnOK_ACP(); Wt::WContainerWidget *dvMentorsWrapper_ACP; void CMentorsDataTable_ACP(); void MoreInfoMentorsTableCell_ACP(Wt::WAnchor *sender); void MoreInfoMentorsTableCell_ACP(Wt::WPushButton *sender); void CardMentorsTableCell_ACP(Wt::WPushButton *sender); void EditMentorsTableCell_ACP(Wt::WPushButton *sender); void EraseMentorsTableCell_ACP(Wt::WPushButton *sender); void EraseMentorsTableCellOK_ACP(Wt::StandardButton result); Wt::WLineEdit *mentorsFNameEdit_ACP; Wt::WLineEdit *mentorsLNameEdit_ACP; Wt::WComboBox *mentorsSexCmb_ACP; Wt::WLineEdit *mentorsNationalCodeEdit_ACP; Wt::WLineEdit *mentorsBirthIdEdit_ACP; Wt::WComboBox *mentorsBirthDateCmbY_ACP; Wt::WComboBox *mentorsBirthDateCmbM_ACP; Wt::WComboBox *mentorsBirthDateCmbD_ACP; Wt::WComboBox *mentorsBirthlocCmb_ACP; Wt::WComboBox *mentorsBirthEmissionLocCmb_ACP; Wt::WComboBox *mentorsGraduateCertCmb_ACP; Wt::WLineEdit *mentorsGraduateCourseEdit_ACP; Wt::WTextArea *mentorsAddrTArea_ACP; Wt::WLineEdit *mentorsTelEdit_ACP; Wt::WLineEdit *mentorsMobileEdit_ACP; Wt::WLineEdit *mentorsEmailEdit_ACP; Wt::WFileUpload *mentorsPicFUP_ACP; Wt::WPushButton *mentorsSaveBtn_ACP; Wt::WLengthValidator *mentorsFNameValidator_ACP; Wt::WLengthValidator *mentorsLNameValidator_ACP; Wt::WLengthValidator *mentorsSexValidator_ACP; Wt::WRegExpValidator *mentorsNationalCodeValidator_ACP; Wt::WRegExpValidator *mentorsBirthIdValidator_ACP; Wt::WLengthValidator *mentorsBirthDateYValidator_ACP; Wt::WLengthValidator *mentorsBirthDateMValidator_ACP; Wt::WLengthValidator *mentorsBirthDateDValidator_ACP; Wt::WLengthValidator *mentorsBirthlocValidator_ACP; Wt::WLengthValidator *mentorsBirthEmissionLocValidator_ACP; Wt::WLengthValidator *mentorsGraduateCertValidator_ACP; Wt::WLengthValidator *mentorsGraduateCourseValidator_ACP; Wt::WLengthValidator *mentorsAddrValidator_ACP; Wt::WRegExpValidator *mentorsTelValidator_ACP; Wt::WRegExpValidator *mentorsMobileValidator_ACP; Wt::WRegExpValidator *mentorsEmailValidator_ACP; Wt::WText *errMentorsForm_ACP; Wt::WWidget *GetMentorsForm_ACP(Wt::WString form); void MentorsFormFileUploaded_ACP(); void MentorsFormFileTooLarge_ACP(); void MentorsFormSaveBtnOK_ACP(); void MCardAddBtnOK_ACP(Wt::WPushButton *sender); void GetMCardDialog_ACP(std::string acmCode); void GetMCardDialog_ACP(); void EditMCardTableCell_ACP(Wt::WPushButton *sender); void EraseMCardTableCell_ACP(Wt::WPushButton *sender); void EraseMCardTableCellOK_ACP(Wt::StandardButton result); Wt::WComboBox *mCardStTitleCmb_ACP; Wt::WComboBox *mCardDateCmbY_ACP; Wt::WComboBox *mCardDateCmbM_ACP; Wt::WComboBox *mCardDateCmbD_ACP; Wt::WLineEdit *mCardPercentEdit_ACP; Wt::WPushButton *cardSaveBtn_ACP; Wt::WPushButton *eraseCardBtn_ACP; Wt::WPushButton *suspendCardBtn_ACP; Wt::WLengthValidator *mCardStTitleValidator_ACP; Wt::WLengthValidator *mCardDateValidatorY_ACP; Wt::WLengthValidator *mCardDateValidatorM_ACP; Wt::WLengthValidator *mCardDateValidatorD_ACP; Wt::WIntValidator *mCardPercentValidator_ACP; Wt::WText *errMCardForm_ACP; Wt::WWidget *GetMCardForm_ACP(Wt::WString form); void MCardFormSaveBtnOK_ACP(); void TermsAddBtnOK_ACP(); Wt::WContainerWidget *dvTermsWrapper_ACP; void CTermsDataTable_ACP(); void NoticeTermsTableCell_ACP(Wt::WPushButton *sender); void EditTermsTableCell_ACP(Wt::WPushButton *sender); void EraseTermsTableCell_ACP(Wt::WPushButton *sender); void EraseTermsTableCellOK_ACP(Wt::StandardButton result); Wt::WComboBox *termsStTitleCmb_ACP; Wt::WComboBox *termsBegdateCmbY_ACP; Wt::WComboBox *termsBegdateCmbM_ACP; Wt::WComboBox *termsBegdateCmbD_ACP; Wt::WComboBox *termsEnddateCmbY_ACP; Wt::WComboBox *termsEnddateCmbM_ACP; Wt::WComboBox *termsEnddateCmbD_ACP; Wt::WComboBox *termsDaypartCmb_ACP; Wt::WComboBox *termsBegtimeCmbH_ACP; Wt::WComboBox *termsBegtimeCmbM_ACP; Wt::WComboBox *termsEndtimeCmbH_ACP; Wt::WComboBox *termsEndtimeCmbM_ACP; Wt::WComboBox *termsLocCmb_ACP; Wt::WComboBox *termsMentorCmb_ACP; Wt::WPushButton *termsSaveBtn_ACP; Wt::WLengthValidator *termsStTitleValidator_ACP; Wt::WLengthValidator *termsBegdateValidatorY_ACP; Wt::WLengthValidator *termsBegdateValidatorM_ACP; Wt::WLengthValidator *termsBegdateValidatorD_ACP; Wt::WLengthValidator *termsEnddateValidatorY_ACP; Wt::WLengthValidator *termsEnddateValidatorM_ACP; Wt::WLengthValidator *termsEnddateValidatorD_ACP; Wt::WLengthValidator *termsDaypartValidator_ACP; Wt::WLengthValidator *termsBegtimeValidatorH_ACP; Wt::WLengthValidator *termsBegtimeValidatorM_ACP; Wt::WLengthValidator *termsEndtimeValidatorH_ACP; Wt::WLengthValidator *termsEndtimeValidatorM_ACP; Wt::WLengthValidator *termsLocValidator_ACP; Wt::WLengthValidator *termsMentorValidator_ACP; Wt::WText *errTermsForm_ACP; Wt::WWidget *GetTermsForm_ACP(Wt::WString form); void TermsFormSaveBtnOK_ACP(); Wt::WContainerWidget *dvTyrosWrapper_ACP; void CTyrosDataTable_ACP(); void MoreInfoTyrosTableCell_ACP(Wt::WPushButton *sender); void ShowTyroPic_ACP(Wt::WAnchor *sender); void EditPicsTyrosTableCell_ACP(Wt::WPushButton *sender); void EditPicsTyrosTableCellOK_ACP(Wt::WFileUpload *sender); void EditTyrosTableCell_ACP(Wt::WPushButton *sender); void EraseTyrosTableCell_ACP(Wt::WPushButton *sender); void EraseTyrosTableCellOK_ACP(Wt::StandardButton result); Wt::WLineEdit *tyrosFNameEdit_ACP; Wt::WLineEdit *tyrosLNameEdit_ACP; Wt::WComboBox *tyrosSexCmb_ACP; Wt::WLineEdit *tyrosFatherSNameEdit_ACP; Wt::WLineEdit *tyrosNationalCodeEdit_ACP; Wt::WLineEdit *tyrosBirthIdEdit_ACP; Wt::WComboBox *tyrosBirthDateCmbY_ACP; Wt::WComboBox *tyrosBirthDateCmbM_ACP; Wt::WComboBox *tyrosBirthDateCmbD_ACP; Wt::WComboBox *tyrosBirthlocCmb_ACP; Wt::WComboBox *tyrosBirthEmissionLocCmb_ACP; Wt::WComboBox *tyrosGraduateCertCmb_ACP; Wt::WLineEdit *tyrosGraduateCourseEdit_ACP; Wt::WComboBox *tyrosJobCmb_ACP; Wt::WTextArea *tyrosAddrTArea_ACP; Wt::WLineEdit *tyrosTelEdit_ACP; Wt::WLineEdit *tyrosMobileEdit_ACP; Wt::WLineEdit *tyrosEmailEdit_ACP; Wt::WPushButton *tyrosSaveBtn_ACP; Wt::WLengthValidator *tyrosFNameValidator_ACP; Wt::WLengthValidator *tyrosLNameValidator_ACP; Wt::WLengthValidator *tyrosSexValidator_ACP; Wt::WLengthValidator *tyrosFatherSNameValidator_ACP; Wt::WRegExpValidator *tyrosNationalCodeValidator_ACP; Wt::WRegExpValidator *tyrosBirthIdValidator_ACP; Wt::WLengthValidator *tyrosBirthDateYValidator_ACP; Wt::WLengthValidator *tyrosBirthDateMValidator_ACP; Wt::WLengthValidator *tyrosBirthDateDValidator_ACP; Wt::WLengthValidator *tyrosBirthlocValidator_ACP; Wt::WLengthValidator *tyrosBirthEmissionLocValidator_ACP; Wt::WLengthValidator *tyrosGraduateCertValidator_ACP; Wt::WLengthValidator *tyrosGraduateCourseValidator_ACP; Wt::WLengthValidator *tyrosJobValidator_ACP; Wt::WLengthValidator *tyrosAddrValidator_ACP; Wt::WRegExpValidator *tyrosTelValidator_ACP; Wt::WRegExpValidator *tyrosMobileValidator_ACP; Wt::WRegExpValidator *tyrosEmailValidator_ACP; Wt::WText *errTyrosForm_ACP; Wt::WWidget *GetTyrosForm_ACP(Wt::WString form); void TyrosFormSaveBtnOK_ACP(); Wt::WFileUpload *tyrosPicBirthCertFUP_ACP; Wt::WFileUpload *tyrosPicNationalCardFUP_ACP; Wt::WFileUpload *tyrosPicPersonnelFUP_ACP; Wt::WFileUpload *tyrosPicServiceFUP_ACP; /************* End Academy Panel *************/ }; #endif /* CGIROOT_HPP */
32.455285
106
0.73998
Wt-Works
70c89044cd53dfc552356fb206d75b7aa7475c9f
3,698
hh
C++
gazebo/physics/Contact.hh
traversaro/gazebo
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
[ "ECL-2.0", "Apache-2.0" ]
887
2020-04-18T08:43:06.000Z
2022-03-31T11:58:50.000Z
gazebo/physics/Contact.hh
traversaro/gazebo
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
[ "ECL-2.0", "Apache-2.0" ]
462
2020-04-21T21:59:19.000Z
2022-03-31T23:23:21.000Z
gazebo/physics/Contact.hh
traversaro/gazebo
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
[ "ECL-2.0", "Apache-2.0" ]
421
2020-04-21T09:13:03.000Z
2022-03-30T02:22:01.000Z
/* * Copyright (C) 2012 Open Source Robotics Foundation * * 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. * */ #ifndef GAZEBO_PHYSICS_CONTACT_HH_ #define GAZEBO_PHYSICS_CONTACT_HH_ #include <vector> #include <string> #include <ignition/math/Vector3.hh> #include "gazebo/common/Time.hh" #include "gazebo/msgs/msgs.hh" #include "gazebo/physics/JointWrench.hh" #include "gazebo/physics/PhysicsTypes.hh" #include "gazebo/util/system.hh" // For the sake of efficiency, use fixed size arrays for collision // MAX_COLLIDE_RETURNS limits contact detection, needs to be large // for proper contact dynamics. // MAX_CONTACT_JOINTS truncates <max_contacts> specified in SDF #define MAX_COLLIDE_RETURNS 250 #define MAX_CONTACT_JOINTS 250 namespace gazebo { namespace physics { class Collision; /// \addtogroup gazebo_physics /// \{ /// \class Contact Contact.hh physics/physics.hh /// \brief A contact between two collisions. Each contact can consist of /// a number of contact points class GZ_PHYSICS_VISIBLE Contact { /// \brief Constructor. public: Contact(); /// \brief Copy constructor /// \param[in] _contact Contact to copy. public: Contact(const Contact &_contact); /// \brief Destructor. public: virtual ~Contact(); /// \brief Operator =. /// \param[in] _contact Contact to copy. /// \return Reference to this contact public: Contact &operator =(const Contact &_contact); /// \brief Operator =. /// \param[in] _contact msgs::Contact to copy. /// \return Reference to this contact public: Contact &operator =(const msgs::Contact &_contact); /// \brief Populate a msgs::Contact with data from this. /// \param[out] _msg Contact message the will hold the data. public: void FillMsg(msgs::Contact &_msg) const; /// \brief Produce a debug string. /// \return A string that contains the values of the contact. public: std::string DebugString() const; /// \brief Reset to default values. public: void Reset(); /// \brief Pointer to the first collision object public: Collision *collision1; /// \brief Pointer to the second collision object public: Collision *collision2; /// \brief Array of forces for the contact. /// All forces and torques are in the world frame. /// All forces and torques are relative to the center of mass of the /// respective links that the collision elments are attached to. public: JointWrench wrench[MAX_CONTACT_JOINTS]; /// \brief Array of force positions. public: ignition::math::Vector3d positions[MAX_CONTACT_JOINTS]; /// \brief Array of force normals. public: ignition::math::Vector3d normals[MAX_CONTACT_JOINTS]; /// \brief Array of contact depths public: double depths[MAX_CONTACT_JOINTS]; /// \brief Length of all the arrays. public: int count; /// \brief Time at which the contact occurred. public: common::Time time; /// \brief World in which the contact occurred public: WorldPtr world; }; /// \} } } #endif
32.156522
76
0.678475
traversaro
70c8b431974d08f88549249329d4f2c06fe52902
7,464
cpp
C++
code/engine.vc2008/xrGame/CarInput.cpp
porames25/xray-oxygen
1f3f46a7a1ffc2be1de04a1ec665862127894ef7
[ "Apache-2.0" ]
null
null
null
code/engine.vc2008/xrGame/CarInput.cpp
porames25/xray-oxygen
1f3f46a7a1ffc2be1de04a1ec665862127894ef7
[ "Apache-2.0" ]
null
null
null
code/engine.vc2008/xrGame/CarInput.cpp
porames25/xray-oxygen
1f3f46a7a1ffc2be1de04a1ec665862127894ef7
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #pragma hdrstop #ifdef DEBUG #include "PHDebug.h" #endif #include "alife_space.h" #include "Hit.h" #include "PHDestroyable.h" #include "Car.h" #include "Actor.h" #include "script_entity_action.h" #include "../xrEngine/xr_level_controller.h" #include "../xrEngine/CameraBase.h" #include "../Include/xrRender/Kinematics.h" #include "Level.h" #include "CarWeapon.h" #include "script_game_object.h" void CCar::OnMouseMove(int dx, int dy) { if (Remote()) return; CCameraBase* C = active_camera; float scale = (C->f_fov/g_fov)*psMouseSens * psMouseSensScale/50.f; if (dx) { float d = float(dx)*scale; C->Move ((d<0)?kLEFT:kRIGHT, _abs(d)); } if (dy) { float d = ((psMouseInvert.test(1))?-1:1)*float(dy)*scale*3.f/4.f; C->Move ((d>0)?kUP:kDOWN, _abs(d)); } } bool CCar::bfAssignMovement(CScriptEntityAction *tpEntityAction) { if (tpEntityAction->m_tMovementAction.m_bCompleted) return(false); u32 l_tInput = tpEntityAction->m_tMovementAction.m_tInputKeys; vfProcessInputKey(kFWD , !!(l_tInput & CScriptMovementAction::eInputKeyForward )); vfProcessInputKey(kBACK , !!(l_tInput & CScriptMovementAction::eInputKeyBack )); vfProcessInputKey(kL_STRAFE , !!(l_tInput & CScriptMovementAction::eInputKeyLeft )); vfProcessInputKey(kR_STRAFE , !!(l_tInput & CScriptMovementAction::eInputKeyRight )); vfProcessInputKey(kACCEL , !!(l_tInput & CScriptMovementAction::eInputKeyShiftUp )); vfProcessInputKey(kCROUCH , !!(l_tInput & CScriptMovementAction::eInputKeyShiftDown )); vfProcessInputKey(kJUMP , !!(l_tInput & CScriptMovementAction::eInputKeyBreaks )); if (!!(l_tInput & CScriptMovementAction::eInputKeyEngineOn)) StartEngine(); if (!!(l_tInput & CScriptMovementAction::eInputKeyEngineOff)) StopEngine(); //if (_abs(tpEntityAction->m_tMovementAction.m_fSpeed) > EPS_L) //m_current_rpm = _abs(tpEntityAction->m_tMovementAction.m_fSpeed*m_current_gear_ratio); return (true); } bool CCar::bfAssignObject(CScriptEntityAction *tpEntityAction) { CScriptObjectAction &l_tObjectAction = tpEntityAction->m_tObjectAction; if (l_tObjectAction.m_bCompleted || !xr_strlen(l_tObjectAction.m_caBoneName)) return((l_tObjectAction.m_bCompleted = true) == false); s16 l_sBoneID = smart_cast<IKinematics*>(Visual())->LL_BoneID(l_tObjectAction.m_caBoneName); if (is_Door(l_sBoneID)) { switch(l_tObjectAction.m_tGoalType) { case MonsterSpace::eObjectActionActivate : { if (!DoorOpen(l_sBoneID)) return((l_tObjectAction.m_bCompleted = true) == false); break; } case MonsterSpace::eObjectActionDeactivate : { if (!DoorClose(l_sBoneID)) return((l_tObjectAction.m_bCompleted = true) == false); break; } case MonsterSpace::eObjectActionUse : { if (!DoorSwitch(l_sBoneID)) return((l_tObjectAction.m_bCompleted = true) == false); break; } default : return ((l_tObjectAction.m_bCompleted = true) == false); } return (false); } SCarLight* light=nullptr; if (m_lights.findLight(l_sBoneID,light)) { switch(l_tObjectAction.m_tGoalType) { case MonsterSpace::eObjectActionActivate : { light->TurnOn(); return ((l_tObjectAction.m_bCompleted = true) == false); } case MonsterSpace::eObjectActionDeactivate : { light->TurnOff(); return ((l_tObjectAction.m_bCompleted = true) == false); } case MonsterSpace::eObjectActionUse : { light->Switch(); return ((l_tObjectAction.m_bCompleted = true) == false); } default : return ((l_tObjectAction.m_bCompleted = true) == false); } } return (false); } void CCar::vfProcessInputKey (int iCommand, bool bPressed) { if (bPressed) OnKeyboardPress (iCommand); else OnKeyboardRelease (iCommand); } float const base_fov = g_fov; float const dest_fov = g_fov - (g_fov-30.f); void CCar::OnKeyboardPress(int cmd) { if (Remote()) return; switch (cmd) { case kCAM_1: OnCameraChange(ectFirst); break; case kCAM_2: OnCameraChange(ectChase); break; case kCAM_3: OnCameraChange(ectFree); break; case kACCEL: TransmissionUp(); break; case kCROUCH: TransmissionDown(); break; case kFWD: PressForward(); break; case kBACK: PressBack(); break; case kR_STRAFE: PressRight(); if (OwnerActor()) OwnerActor()->steer_Vehicle(1); break; case kL_STRAFE: PressLeft(); if (OwnerActor()) OwnerActor()->steer_Vehicle(-1); break; case kJUMP: PressBreaks(); break; case kTURN_ENGINE: SwitchEngine(); if (HasWeapon()) m_car_weapon->Action(CCarWeapon::eWpnActivate, b_engine_on); break; case kTORCH: m_lights.SwitchHeadLights(); break; case kUSE: if (HasWeapon()) (g_fov = base_fov); break; case kWPN_ZOOM: if (HasWeapon()) (g_fov = dest_fov); break; case kWPN_FIRE: if (HasWeapon()) m_car_weapon->Action(CCarWeapon::eWpnFire, 1); break; case kSWITCH_HORN: SwitchHorn(); break; }; } void CCar::OnKeyboardRelease(int cmd) { if (Remote()) return; switch (cmd) { case kACCEL: break; case kFWD: ReleaseForward(); break; case kBACK: ReleaseBack(); break; case kL_STRAFE: ReleaseLeft(); if (OwnerActor()) OwnerActor()->steer_Vehicle(0); break; case kR_STRAFE: ReleaseRight(); if (OwnerActor()) OwnerActor()->steer_Vehicle(0); break; case kWPN_FIRE: if (HasWeapon()) m_car_weapon->Action(CCarWeapon::eWpnFire, 0); break; case kJUMP: ReleaseBreaks(); break; case kWPN_ZOOM: if (HasWeapon()) (g_fov = base_fov); break; case kSWITCH_HORN: snd_horn.destroy(); break; }; } void CCar::OnKeyboardHold(int cmd) { if (Remote()) return; switch (cmd) { case kCAM_ZOOM_IN: case kCAM_ZOOM_OUT: case kUP: case kDOWN: case kLEFT: case kRIGHT: { active_camera->Move(cmd); break; } } } void CCar::Action(u16 id, u32 flags) { if(m_car_weapon)m_car_weapon->Action(id,flags); } void CCar::SetParam(int id, Fvector2 val) { if(m_car_weapon)m_car_weapon->SetParam(id,val); } void CCar::SetParam (int id, Fvector val) { if(m_car_weapon)m_car_weapon->SetParam(id,val); } bool CCar::WpnCanHit() { if(m_car_weapon) return m_car_weapon->AllowFire(); return false; } float CCar::FireDirDiff() { if(m_car_weapon) return m_car_weapon->FireDirDiff(); return 0.0f; } #include "script_game_object.h" #include "car_memory.h" #include "visual_memory_manager.h" bool CCar::isObjectVisible (CScriptGameObject* O_) { if(m_memory) { return m_memory->visual().visible_now(&O_->object()); }else { if(!O_) { Msg("Attempt to call CCar::isObjectVisible method wihth passed NULL parameter"); return false; } CObject* O = &O_->object(); Fvector dir_to_object; Fvector to_point; O->Center(to_point); Fvector from_point; Center (from_point); if(HasWeapon()) { from_point.y = XFORM().c.y + m_car_weapon->_height(); } dir_to_object.sub(to_point,from_point).normalize_safe(); float ray_length = from_point.distance_to(to_point); BOOL res = Level().ObjectSpace.RayTest(from_point, dir_to_object, ray_length, collide::rqtStatic, nullptr, nullptr); return (0==res); } } bool CCar::HasWeapon() { return (m_car_weapon != nullptr); } Fvector CCar::CurrentVel() { Fvector lin_vel; m_pPhysicsShell->get_LinearVel(lin_vel); return lin_vel; }
22.549849
118
0.682342
porames25
70c901b862e100eced4764fb17880d304db40c69
9,970
cpp
C++
ba/cpp/ba.cpp
daoran/ba
d38e58a1f9a1130e78626de34bfc3d722a968e5c
[ "Unlicense" ]
9
2020-04-26T02:40:48.000Z
2021-12-13T10:22:00.000Z
ba/cpp/ba.cpp
daoran/ba
d38e58a1f9a1130e78626de34bfc3d722a968e5c
[ "Unlicense" ]
null
null
null
ba/cpp/ba.cpp
daoran/ba
d38e58a1f9a1130e78626de34bfc3d722a968e5c
[ "Unlicense" ]
2
2020-11-27T07:12:36.000Z
2022-01-09T04:22:32.000Z
#include "ba.hpp" static mat2_t J_intrinsics(const mat3_t &K) { // J = [K[0, 0], 0.0, // 0.0, K[1, 1]]; mat2_t J = zeros(2, 2); J(0, 0) = K(0, 0); J(1, 1) = K(1, 1); return J; } static matx_t J_project(const vec3_t &p_C) { const real_t x = p_C(0); const real_t y = p_C(1); const real_t z = p_C(2); // J = [1 / z, 0, -x / z^2, // 0, 1 / z, -y / z^2]; matx_t J = zeros(2, 3); J(0, 0) = 1.0 / z; J(1, 1) = 1.0 / z; J(0, 2) = -x / (z * z); J(1, 2) = -y / (z * z); return J; } static mat3_t J_camera_rotation(const quat_t &q_WC, const vec3_t &r_WC, const vec3_t &p_W) { const mat3_t C_WC = q_WC.toRotationMatrix(); const mat3_t C_CW = C_WC.transpose(); return C_CW * skew(p_W - r_WC); } static mat3_t J_camera_translation(const quat_t &q_WC) { const mat3_t C_WC = q_WC.toRotationMatrix(); const mat3_t C_CW = C_WC.transpose(); return -C_CW; } static mat3_t J_target_point(const quat_t &q_WC) { const mat3_t C_WC = q_WC.toRotationMatrix(); const mat3_t C_CW = C_WC.transpose(); return C_CW; } int ba_residual_size(ba_data_t &data) { // Calculate residual size int r_size = 0; for (int k = 0; k < data.nb_frames; k++) { r_size += data.point_ids[k][0]; } r_size = r_size * 2; // ^ Scale 2 because each pixel error are size 2 return r_size; } vecx_t ba_residuals(ba_data_t &data) { // Initialize memory for residuals int r_size = ba_residual_size(data); vecx_t r{r_size}; // Loop over time int res_idx = 0; // Residual index for (int k = 0; k < data.nb_frames; k++) { // Form camera pose and its inverse const mat4_t T_WC = data.cam_poses[k].T(); const mat4_t T_CW = T_WC.inverse(); // Get point ids and measurements at time step k const int nb_ids = data.point_ids[k][0]; const int *point_ids = &data.point_ids[k][1]; for (int i = 0; i < nb_ids; i++) { // Get point in world frame and transform to camera frame const int id = point_ids[i]; const vec3_t p_W{data.points[id]}; const vec3_t p_C = tf_point(T_CW, p_W); // Project point in camera frame down to image plane const vec3_t x{p_C(0) / p_C(2), p_C(1) / p_C(2), 1.0}; const vec2_t z_hat = (data.cam_K * x).head(2); // Calculate reprojection error const vec2_t z = data.keypoints[k][i]; r.block(res_idx, 0, 2, 1) = z - z_hat; res_idx += 2; } } return r; } matx_t ba_jacobian(ba_data_t &data) { // Initialize memory for jacobian int J_rows = ba_residual_size(data); int J_cols = (data.nb_frames * 6) + (data.nb_points * 3); matx_t J = zeros(J_rows, J_cols); // Loop over camera poses int pose_idx = 0; int meas_idx = 0; for (int k = 0; k < data.nb_frames; k++) { // Form camera pose const mat4_t T_WC = data.cam_poses[k].T(); const quat_t q_WC = tf_quat(T_WC); const vec3_t r_WC = tf_trans(T_WC); const mat4_t T_CW = T_WC.inverse(); // Get point ids and measurements at time step k const int nb_ids = data.point_ids[k][0]; const int *point_ids = &data.point_ids[k][1]; // Loop over observations at time k for (int i = 0; i < nb_ids; i++) { // Get point in world frame and transform to camera frame const int id = point_ids[i]; const vec3_t p_W{data.points[id]}; const vec3_t p_C = tf_point(T_CW, p_W); // Camera pose jacobian const int rs = meas_idx * 2; int cs = pose_idx * 6; const mat2_t J_K = J_intrinsics(data.cam_K); const matx_t J_P = J_project(p_C); const matx_t J_h = J_K * J_P; const mat3_t J_C = J_camera_rotation(q_WC, r_WC, p_W); const mat3_t J_r = J_camera_translation(q_WC); const matx_t J_cam_rot = -1 * J_h * J_C; const matx_t J_cam_pos = -1 * J_h * J_r; J.block(rs, cs, 2, 3) = J_cam_rot; J.block(rs, cs + 3, 2, 3) = J_cam_pos; // Point jacobian cs = (data.nb_frames * 6) + point_ids[i] * 3; const matx_t J_point = -1 * J_h * J_target_point(q_WC); J.block(rs, cs, 2, 3) = J_point; meas_idx++; } pose_idx++; } return J; } void ba_update(ba_data_t &data, const vecx_t &e, const matx_t &E) { const real_t lambda = 1e-4; // LM damping term // Solve Gauss-Newton system [H dx = g]: Solve for dx matx_t H = E.transpose() * E; // Hessian approx: H = J^t J matx_t H_diag = (H.diagonal().asDiagonal()); H = H + lambda * H_diag; // R. Fletcher trust region mod const vecx_t g = -E.transpose() * e; const vecx_t dx = H.ldlt().solve(g); // Cholesky decomp // Update camera poses for (int k = 0; k < data.nb_frames; k++) { const int s = k * 6; // Update camera rotation const vec3_t dalpha{dx(s), dx(s + 1), dx(s + 2)}; const quat_t q = data.cam_poses[k].rot(); const quat_t dq = quat_delta(dalpha); data.cam_poses[k].set_rot(dq * q); // Update camera position const vec3_t r_WC = data.cam_poses[k].trans(); const vec3_t dr_WC{dx(s + 3), dx(s + 4), dx(s + 5)}; data.cam_poses[k].set_trans(r_WC + dr_WC); } // Update points for (int i = 0; i < data.nb_points; i++) { const int s = (data.nb_frames * 6) + (i * 3); const vec3_t dp_W{dx(s), dx(s + 1), dx(s + 2)}; data.points[i][0] += dp_W(0); data.points[i][1] += dp_W(1); data.points[i][2] += dp_W(2); } } real_t ba_cost(const vecx_t &e) { return 0.5 * e.transpose() * e; } void ba_solve(ba_data_t &data) { int max_iter = 10; real_t cost_prev = 0.0; for (int iter = 0; iter < max_iter; iter++) { // Update struct timespec t_start = tic(); const vecx_t e = ba_residuals(data); const matx_t E = ba_jacobian(data); ba_update(data, e, E); // Calculate reprojection error double sse = 0.0; int N = 0; for (int i = 0; i < e.size(); i += 2) { const real_t dx = e(i); const real_t dy = e(i + 1); const real_t reproj_error = sqrt(dx * dx + dy * dy); sse += reproj_error * reproj_error; N++; } const double rmse_reproj_error = sqrt(sse / N); // Print cost const real_t cost = ba_cost(e); printf(" - iter[%d] ", iter); printf("cost: %.2e ", cost); printf("time: %.3fs ", toc(&t_start)); printf("rmse_reproj_error: %.2fpx\n", rmse_reproj_error); // Termination criteria real_t cost_diff = fabs(cost - cost_prev); if (cost_diff < 1.0e-1) { printf("Done!\n"); break; } cost_prev = cost; } } void ba_save(const ba_data_t &data, std::string &save_dir) { // Create save directory const char last_char = save_dir[save_dir.length() - 1]; const std::string postfix = (last_char == '/') ? "" : "/"; save_dir += postfix; const std::string cmd = "mkdir -p " + save_dir; const int retval = system(cmd.c_str()); if (retval != 0) { printf("Error! Failed to save results to [%s]", save_dir.c_str()); } // Save camera matrix { const std::string csv_path = save_dir + "camera.csv"; FILE *camera_csv = fopen(csv_path.c_str(), "w"); fprintf(camera_csv, "#camera_K\n"); fprintf(camera_csv, "%f, 0.0000, %f\n", data.cam_K(0, 0), data.cam_K(0, 2)); fprintf(camera_csv, "0.0000, %f, %f\n", data.cam_K(1, 1), data.cam_K(1, 2)); fprintf(camera_csv, "0.0000, 0.0000, 1.0000\n"); fclose(camera_csv); } // Save camera poses { const std::string csv_path = save_dir + "camera_poses.csv"; FILE *poses_csv = fopen(csv_path.c_str(), "w"); fprintf(poses_csv, "#qw,qx,qy,qz,rx,ry,rz\n"); for (const auto &pose : data.cam_poses) { const auto &q = pose.rot(); const auto &r = pose.trans(); fprintf(poses_csv, "%f,%f,%f,%f,", q.w(), q.x(), q.y(), q.z()); fprintf(poses_csv, "%f,%f,%f", r(0), r(1), r(2)); fprintf(poses_csv, "\n"); } fclose(poses_csv); } // Save target pose { const std::string csv_path = save_dir + "target_pose.csv"; FILE *target_csv = fopen(csv_path.c_str(), "w"); fprintf(target_csv, "#qw,qx,qy,qz,rx,ry,rz\n"); { const auto &q = data.target_pose.rot(); const auto &r = data.target_pose.trans(); fprintf(target_csv, "%f,%f,%f,%f,", q.w(), q.x(), q.y(), q.z()); fprintf(target_csv, "%f,%f,%f", r(0), r(1), r(2)); fprintf(target_csv, "\n"); } fclose(target_csv); } // Save keypoints { const std::string csv_path = save_dir + "keypoints.csv"; FILE *keypoints_csv = fopen(csv_path.c_str(), "w"); fprintf(keypoints_csv, "#size,keypoints\n"); for (const auto &kps : data.keypoints) { int nb_kps = kps.size(); fprintf(keypoints_csv, "%d,", nb_kps * 2); for (int j = 0; j < nb_kps; j++) { fprintf(keypoints_csv, "%f,", kps[j](0)); fprintf(keypoints_csv, "%f", kps[j](1)); if (j + 1 < nb_kps) { fprintf(keypoints_csv, ","); } } fprintf(keypoints_csv, "\n"); } fclose(keypoints_csv); } // Save point ids { const std::string csv_path = save_dir + "point_ids.csv"; FILE *point_ids_csv = fopen(csv_path.c_str(), "w"); fprintf(point_ids_csv, "#size,point_ids\n"); for (int i = 0; i < data.nb_ids; i++) { int nb_ids = data.point_ids[i][0]; fprintf(point_ids_csv, "%d,", data.point_ids[i][0]); for (int j = 1; j < (nb_ids + 1); j++) { fprintf(point_ids_csv, "%d", data.point_ids[i][j]); if (j + 1 < (nb_ids + 1)) { fprintf(point_ids_csv, ","); } } fprintf(point_ids_csv, "\n"); } fclose(point_ids_csv); } // Save points { const std::string csv_path = save_dir + "points.csv"; FILE *points_csv = fopen(csv_path.c_str(), "w"); fprintf(points_csv, "#x,y,z\n"); for (int i = 0; i < data.nb_points; i++) { fprintf(points_csv, "%f,", data.points[i][0]); fprintf(points_csv, "%f,", data.points[i][1]); fprintf(points_csv, "%f\n", data.points[i][2]); } fclose(points_csv); } }
29.93994
80
0.582146
daoran
70cb2b5358d80a4f847edf37c38653a03a0d1a72
9,808
cpp
C++
Nacro/SDK/FN_ItemManagementEquipSlot_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_ItemManagementEquipSlot_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_ItemManagementEquipSlot_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.IsSelected // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool Selected (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UItemManagementEquipSlot_C::IsSelected(bool* Selected) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.IsSelected"); UItemManagementEquipSlot_C_IsSelected_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Selected != nullptr) *Selected = params.Selected; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusReceived // (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FFocusEvent* InFocusEvent (Parm) // struct FEventReply ReturnValue (Parm, OutParm, ReturnParm) struct FEventReply UItemManagementEquipSlot_C::OnFocusReceived(struct FGeometry* MyGeometry, struct FFocusEvent* InFocusEvent) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusReceived"); UItemManagementEquipSlot_C_OnFocusReceived_Params params; params.MyGeometry = MyGeometry; params.InFocusEvent = InFocusEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.SetSelected // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // bool Selected (Parm, ZeroConstructor, IsPlainOldData) void UItemManagementEquipSlot_C::SetSelected(bool Selected) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.SetSelected"); UItemManagementEquipSlot_C_SetSelected_Params params; params.Selected = Selected; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragDetected // (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FPointerEvent* PointerEvent (ConstParm, Parm, OutParm, ReferenceParm) // class UDragDropOperation* Operation (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UItemManagementEquipSlot_C::OnDragDetected(struct FGeometry* MyGeometry, struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragDetected"); UItemManagementEquipSlot_C_OnDragDetected_Params params; params.MyGeometry = MyGeometry; params.PointerEvent = PointerEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Operation != nullptr) *Operation = params.Operation; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnMouseButtonDown // (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FPointerEvent* MouseEvent (ConstParm, Parm, OutParm, ReferenceParm) // struct FEventReply ReturnValue (Parm, OutParm, ReturnParm) struct FEventReply UItemManagementEquipSlot_C::OnMouseButtonDown(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnMouseButtonDown"); UItemManagementEquipSlot_C_OnMouseButtonDown_Params params; params.MyGeometry = MyGeometry; params.MouseEvent = MouseEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDrop // (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FPointerEvent* PointerEvent (Parm) // class UDragDropOperation** Operation (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UItemManagementEquipSlot_C::OnDrop(struct FGeometry* MyGeometry, struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDrop"); UItemManagementEquipSlot_C_OnDrop_Params params; params.MyGeometry = MyGeometry; params.PointerEvent = PointerEvent; params.Operation = Operation; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.RefreshItem // (Public, BlueprintCallable, BlueprintEvent) void UItemManagementEquipSlot_C::RefreshItem() { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.RefreshItem"); UItemManagementEquipSlot_C_RefreshItem_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UItemManagementEquipSlot_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.Construct"); UItemManagementEquipSlot_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusLost // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FFocusEvent* InFocusEvent (Parm) void UItemManagementEquipSlot_C::OnFocusLost(struct FFocusEvent* InFocusEvent) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusLost"); UItemManagementEquipSlot_C_OnFocusLost_Params params; params.InFocusEvent = InFocusEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature // (BlueprintEvent) // Parameters: // bool bUsingGamepad (Parm, ZeroConstructor, IsPlainOldData) void UItemManagementEquipSlot_C::BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature(bool bUsingGamepad) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature"); UItemManagementEquipSlot_C_BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature_Params params; params.bUsingGamepad = bUsingGamepad; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragCancelled // (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintEvent) // Parameters: // struct FPointerEvent* PointerEvent (ConstParm, Parm, OutParm, ReferenceParm) // class UDragDropOperation** Operation (Parm, ZeroConstructor, IsPlainOldData) void UItemManagementEquipSlot_C::OnDragCancelled(struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragCancelled"); UItemManagementEquipSlot_C_OnDragCancelled_Params params; params.PointerEvent = PointerEvent; params.Operation = Operation; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.ExecuteUbergraph_ItemManagementEquipSlot // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UItemManagementEquipSlot_C::ExecuteUbergraph_ItemManagementEquipSlot(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.ExecuteUbergraph_ItemManagementEquipSlot"); UItemManagementEquipSlot_C_ExecuteUbergraph_ItemManagementEquipSlot_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
34.903915
206
0.749286
Milxnor
70cc4a2eb152ef9443f56851b930cd047462e958
4,159
cpp
C++
src/Cpl/Io/Stdio/_0test/atomic.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
src/Cpl/Io/Stdio/_0test/atomic.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
src/Cpl/Io/Stdio/_0test/atomic.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------- * This file is part of the Colony.Core Project. The Colony.Core Project is an * open source project with a BSD type of licensing agreement. See the license * agreement (license.txt) in the top/ directory or on the Internet at * http://integerfox.com/colony.core/license.txt * * Copyright (c) 2014-2020 John T. Taylor * * Redistributions of the source code must retain the above copyright notice. *----------------------------------------------------------------------------*/ #include "Catch/catch.hpp" #include "Cpl/Text/FString.h" #include "Cpl/System/Api.h" #include "Cpl/System/Thread.h" #include "Cpl/System/Trace.h" #include "Cpl/Io/AtomicOutput.h" #include "Cpl/Io/Stdio/StdOut.h" #include "Cpl/System/_testsupport/Shutdown_TS.h" #define SECT_ "_0test" /// using namespace Cpl::Io; //////////////////////////////////////////////////////////////////////////////// namespace { class MyRunnable : public Cpl::System::Runnable { public: /// const char* m_msg; /// Cpl::System::Thread& m_masterThread; /// int m_maxLoops; /// unsigned long m_delay; /// AtomicOutput<MyRunnable> m_out; public: /// MyRunnable( Cpl::System::Thread& masterThread, Output& fd, Cpl::System::Mutex& lock, int maxLoops, unsigned long delay, const char* msg ) :m_msg( msg ), m_masterThread( masterThread ), m_maxLoops( maxLoops ), m_delay( delay ), m_out( fd, lock ) { } public: /// bool many( Output& fd ) { Cpl::Text::FString<256> buffer; bool io = false; if ( fd.write( buffer, "1: %s", m_msg ) ) { if ( fd.write( buffer, "2: %s", m_msg ) ) { if ( fd.write( buffer, "3: %s", m_msg ) ) { io = true; } } } return io; } /// void appRun() { Cpl::Text::FString<256> buffer; // Wait till I'm told to start Cpl::System::Thread::wait(); int i; for ( i=0; i < m_maxLoops; i++ ) { m_out.write( buffer, "** %s", m_msg ); m_out.requestOutputs( *this, &MyRunnable::many ); Cpl::System::Api::sleep( m_delay ); } m_masterThread.signal(); } }; }; // end namespace //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "atomic", "[atomic]" ) { CPL_SYSTEM_TRACE_FUNC( SECT_ ); Cpl::System::Shutdown_TS::clearAndUseCounter(); Cpl::Io::Stdio::StdOut fd; Cpl::System::Mutex lock; MyRunnable appleRun( Cpl::System::Thread::getCurrent(), fd, lock, 10, 3, "Apple: very long string for more chance of interleaving 123456789 122456789 abcdef\n" ); MyRunnable orangeRun( Cpl::System::Thread::getCurrent(), fd, lock, 5, 7, "Orange: very long string for more chance of interleaving 123456789 122456789 abcdef\n" ); MyRunnable cherryRun( Cpl::System::Thread::getCurrent(), fd, lock, 13, 2, "Cherry: very long string for more chance of interleaving 123456789 122456789 abcdef\n" ); Cpl::System::Thread* appleThreadPtr = Cpl::System::Thread::create( appleRun, "APPLE" ); Cpl::System::Thread* orangeThreadPtr = Cpl::System::Thread::create( orangeRun, "ORANGE" ); Cpl::System::Thread* cherryThreadPtr = Cpl::System::Thread::create( cherryRun, "CHERRY" ); // Wait till all threads have spun up Cpl::System::Api::sleep( 100 ); // Start all threads running orangeThreadPtr->signal(); appleThreadPtr->signal(); cherryThreadPtr->signal(); // Wait for all threads to finish Cpl::System::Thread::wait(); Cpl::System::Thread::wait(); Cpl::System::Thread::wait(); // Destroy all threads Cpl::System::Thread::destroy( *orangeThreadPtr ); Cpl::System::Thread::destroy( *appleThreadPtr ); Cpl::System::Thread::destroy( *cherryThreadPtr ); REQUIRE( Cpl::System::Shutdown_TS::getAndClearCounter() == 0u ); }
30.137681
168
0.552056
johnttaylor
70ce809f995f55881361c4afa7ee2db8f9f8ffae
16,033
cpp
C++
src/SqlConnection.cpp
devinsmith/sql_pool
82a9dc3f8697c3105bcdc19e6af698843e7a4495
[ "MIT" ]
1
2022-03-28T06:55:26.000Z
2022-03-28T06:55:26.000Z
src/SqlConnection.cpp
devinsmith/sql_pool
82a9dc3f8697c3105bcdc19e6af698843e7a4495
[ "MIT" ]
null
null
null
src/SqlConnection.cpp
devinsmith/sql_pool
82a9dc3f8697c3105bcdc19e6af698843e7a4495
[ "MIT" ]
2
2021-03-04T06:11:08.000Z
2022-03-28T06:55:46.000Z
/* * Copyright (c) 2012-2021 Devin Smith <devin@devinsmith.net> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <algorithm> // std::replace #include <cstring> #include <stdexcept> // FreeTDS stuff #define MSDBLIB 1 #include <sqlfront.h> #include <sybdb.h> #include "SqlConnection.h" namespace drs { // Sadly, FreeTDS does not seem to check the return value of this message // handler. extern "C" int sql_db_msg_handler(DBPROCESS * dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line) { if (msgno == 5701 || msgno == 5703 || msgno == 5704) return 0; auto *conn = reinterpret_cast<SqlConnection *>(dbgetuserdata(dbproc)); if (conn != nullptr) { return conn->MsgHandler(dbproc, msgno, msgstate, severity, msgtext, srvname, procname, line); } // No connection associated?? return 0; } int SqlConnection::MsgHandler(DBPROCESS * dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line) { /* * If the severity is something other than 0 or the msg number is * 0 (user informational messages). */ if (severity >= 0 || msgno == 0) { /* * If the message was something other than informational, and * the severity was greater than 0, then print information to * stderr with a little pre-amble information. */ if (msgno > 0 && severity > 0) { _error.clear(); // Incorporate format? _error += "Msg "; _error += std::to_string(msgno); _error += ", Level "; _error += std::to_string(severity); _error += ", State "; _error += std::to_string(msgstate); _error += "\nServer '"; _error += srvname; _error += "'"; if (procname != nullptr && *procname != '\0') { _error += ", Procedure '"; _error += procname; _error += "'"; } if (line > 0) { _error += ", Line "; _error += std::to_string(line); } _error += "\n"; char *database = dbname(dbproc); if (database != nullptr && *database != '\0') { _error += "Database '"; _error += database; _error += "'\n"; } _error += msgtext; } else { if (_error.back() != '\n') { _error.append(1, '\n'); } _error += msgtext; if (msgno == 3621) { severity = 1; } else { severity = 0; } } } if (msgno == 904) { /* Database cannot be autostarted during server shutdown or startup */ _error += "Database does not exist, returning 0.\n"; return 0; } if (msgno == 911) { /* Database does not exist */ _error += "Database does not exist, returning 0.\n"; return 0; } if (msgno == 952) { /* Database is in transition. */ _error += "Database is in transition, returning 0.\n"; return 0; } return severity > 0; } extern "C" int sql_db_err_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr) { // For server messages, cancel the query and rely on the // message handler to capture the appropriate error message. return INT_CANCEL; } // FreeTDS DBLib requires some initialization. void sql_startup() { dbinit(); dbmsghandle(sql_db_msg_handler); dberrhandle(sql_db_err_handler); dbsetlogintime(5); } void sql_shutdown() { dbexit(); } SqlConnection::~SqlConnection() { Disconnect(); } void SqlConnection::Connect() { if (_dbHandle == nullptr || dbdead(_dbHandle)) { LOGINREC *login = dblogin(); DBSETLAPP(login, "Microsoft"); dbsetlversion(login, DBVERSION_72); DBSETLUSER(login, _user.c_str()); DBSETLPWD(login, _pass.c_str()); _dbHandle = tdsdbopen(login, fix_server(_server).c_str(), 1); dbloginfree(login); if (_dbHandle == nullptr || dbdead(_dbHandle)) throw std::runtime_error("Failed to connect to SQL Server"); // FreeTDS is so gross. Yep, instead of a void *, it's a BYTE * which // is an "unsigned char *" dbsetuserdata(_dbHandle, reinterpret_cast<BYTE *>(this)); dbuse(_dbHandle, _database.c_str()); run_initial_query(); } } void SqlConnection::run_initial_query() { // Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to // be set for the connection. ExecDML("SET ANSI_NULLS ON;" "SET ANSI_NULL_DFLT_ON ON;" "SET ANSI_PADDING ON;" "SET ANSI_WARNINGS ON;" "SET QUOTED_IDENTIFIER ON;" "SET CONCAT_NULL_YIELDS_NULL ON;"); } void SqlConnection::Disconnect() { if (_dbHandle != nullptr) { dbclose(_dbHandle); _dbHandle = nullptr; } } void SqlConnection::Dispose() { // We're done, so clear our error state. _error.clear(); // Did we already fetch all result sets? if (_fetched_results) return; // If the current result set has rows, drain them. if (!_fetched_rows) { while (NextRow()); } // While there are more results, drain those rows as well. while (NextResult()) { while (NextRow()); } _fetched_results = true; } void SqlConnection::ExecDML(const char *sql) { Connect(); // Dispose of any previous result set (if any). Dispose(); _fetched_rows = false; _fetched_results = false; if (dbcmd(_dbHandle, sql) == FAIL) throw std::runtime_error("Failed to submit command to freetds"); if (dbsqlexec(_dbHandle) == FAIL) throw std::runtime_error("Failed to execute DML"); Dispose(); } bool SqlConnection::NextResult() { // In order to advance to the next result set, we need to fetch // all rows. if (!_fetched_rows) { while (NextRow()); } int res = dbresults(_dbHandle); if (res == FAIL) throw std::runtime_error("Failed to fetch next result"); if (res == NO_MORE_RESULTS) { _fetched_results = true; return false; } return true; } bool SqlConnection::NextRow() { int row_code; do { row_code = dbnextrow(_dbHandle); if (row_code == NO_MORE_ROWS) { _fetched_rows = true; return false; } if (row_code == REG_ROW) return true; if (row_code == FAIL) { // ERROR ?? return false; } } while (row_code == BUF_FULL); return false; } void SqlConnection::ExecSql(const char *sql) { Connect(); // Dispose of any previous result set (if any). Dispose(); _fetched_rows = false; _fetched_results = false; if (dbcmd(_dbHandle, sql) == FAIL) throw std::runtime_error("Failed to submit command to freetds"); if (dbsqlexec(_dbHandle) == FAIL) { if (!_error.empty()) { throw std::runtime_error(_error); } else { throw std::runtime_error("Failed to execute SQL"); } } int res = dbresults(_dbHandle); if (res == FAIL) throw std::runtime_error("Failed to fetch results SQL"); if (res == NO_MORE_RESULTS) _fetched_results = true; } int SqlConnection::GetOrdinal(const char *colName) { int i; char errorStr[2048]; int total_cols = dbnumcols(_dbHandle); for (i = 0; i < total_cols; i++) { if (strcmp(dbcolname(_dbHandle, i + 1), colName) == 0) { break; } } if (i == total_cols) { snprintf(errorStr, sizeof(errorStr), "Requested column '%s' but does not exist.", colName); throw std::runtime_error(errorStr); } return i; } std::string SqlConnection::GetStringCol(int col) { if (col > dbnumcols(_dbHandle)) throw std::runtime_error("Requested string on nonexistent column"); int coltype = dbcoltype(_dbHandle, col + 1); DBINT srclen = dbdatlen(_dbHandle, col + 1); if (coltype == SYBDATETIME) { DBDATETIME data; DBDATEREC output; char date_string[64]; memcpy(&data, dbdata(_dbHandle, col + 1), srclen); dbdatecrack(_dbHandle, &output, &data); snprintf(date_string, sizeof(date_string), "%04d-%02d-%02d %02d:%02d:%02d.%03d", output.year, output.month, output.day, output.hour, output.minute, output.second, output.millisecond); return date_string; } else if (coltype != SYBCHAR && coltype != SYBTEXT) { char nonstr[4096]; int dest_size; dest_size = dbconvert(_dbHandle, coltype, dbdata(_dbHandle, col + 1), srclen, SYBCHAR, (BYTE *)nonstr, sizeof(nonstr)); if (dest_size == -1) { throw std::runtime_error("Could not convert source to string."); } nonstr[dest_size] = '\0'; return nonstr; } return std::string((const char *)dbdata(_dbHandle, col + 1), srclen); } std::string SqlConnection::GetStringColByName(const char *colName) { return GetStringCol(GetOrdinal(colName)); } int SqlConnection::GetInt32ColByName(const char *colName) { return GetInt32Col(GetOrdinal(colName)); } int SqlConnection::GetInt32Col(int col) { int ret; DBINT srclen; int coltype; if (col > dbnumcols(_dbHandle)) return 0; srclen = dbdatlen(_dbHandle, col + 1); coltype = dbcoltype(_dbHandle, col + 1); if (coltype == SYBINT4) { memcpy(&ret, dbdata(_dbHandle, col + 1), srclen); } else if (coltype == SYBNUMERIC) { dbconvert(nullptr, SYBNUMERIC, (BYTE *)dbdata(_dbHandle, col + 1), -1, SYBINT4, (BYTE *)&ret, 4); } else { dbconvert(nullptr, coltype, (BYTE *)dbdata(_dbHandle, col + 1), -1, SYBINT4, (BYTE *)&ret, 4); } return ret; } int SqlConnection::GetMoneyCol(int col, int *dol, int *cen) { int64_t t64; BYTE *src; if (col > dbnumcols(_dbHandle)) return 0; src = dbdata(_dbHandle, col + 1); t64 = (int64_t)src[4] | (int64_t)src[5] << 8 | (int64_t)src[6] << 16 | (int64_t)src[7] << 24 | (int64_t)src[0] << 32 | (int64_t)src[1] << 40 | (int64_t)src[2] << 48 | (int64_t)src[3] << 56; *dol = (int)(t64 / 10000); if (t64 < 0) t64 = -t64; *cen = (int)(t64 % 10000); return 1; } bool SqlConnection::IsNullCol(int col) { if (col > dbnumcols(_dbHandle)) return true; DBINT srclen = dbdatlen(_dbHandle, col + 1); return srclen <= 0; } void SqlConnection::ExecStoredProc(const char *proc, struct db_params *params, size_t parm_count) { execute_proc_common(proc, params, parm_count); int res = dbresults(_dbHandle); if (res == FAIL) throw std::runtime_error("Failed to get results"); if (res == NO_MORE_RESULTS) _fetched_results = true; } void SqlConnection::ExecNonQuery(const char *proc, struct db_params *params, size_t parm_count) { execute_proc_common(proc, params, parm_count); Dispose(); } void SqlConnection::ExecStoredProc(const char *proc, const std::vector<db_param>& params) { execute_proc_common2(proc, params); int res = dbresults(_dbHandle); if (res == FAIL) throw std::runtime_error("Failed to get results"); if (res == NO_MORE_RESULTS) _fetched_results = true; } void SqlConnection::ExecNonQuery(const char *proc, const std::vector<db_param>& params) { execute_proc_common2(proc, params); Dispose(); } std::string SqlConnection::fix_server(const std::string& str) { std::string clean_server = str; // A server contains a host and port, but users may be providing // a server string with properties that aren't supported by FreeTDS. // FreeTDS doesn't need the leading "tcp:" in some connection strings. // Remove it if it exists. std::string tcp_prefix("tcp:"); if (clean_server.compare(0, tcp_prefix.size(), tcp_prefix) == 0) clean_server = clean_server.substr(tcp_prefix.size()); // Some people use commas instead of colon to separate the port number. std::replace(clean_server.begin(), clean_server.end(), ',', ':'); return clean_server; } std::vector<std::string> SqlConnection::GetAllColumnNames() { int total_cols = dbnumcols(_dbHandle); std::vector<std::string> columns; columns.reserve(total_cols); for (int i = 0; i < total_cols; i++) { columns.emplace_back(dbcolname(_dbHandle, i + 1)); } return columns; } void SqlConnection::execute_proc_common(const char *proc, struct db_params *params, size_t parm_count) { Connect(); Dispose(); _fetched_rows = false; _fetched_results = false; if (dbrpcinit(_dbHandle, proc, 0) == FAIL) { std::string error = "Failed to init stored procedure: "; error += proc; throw std::runtime_error(error); } for (int i = 0; i < parm_count; i++) { int real_type = 0; switch (params[i].type) { case BIT_TYPE: real_type = SYBBITN; case INT32_TYPE: real_type = SYBINT4; break; case STRING_TYPE: real_type = SYBCHAR; break; default: throw std::runtime_error("Unknown stored procedure parameter type"); } if (dbrpcparam(_dbHandle, params[i].name, params[i].status, real_type, params[i].maxlen, params[i].datalen, (BYTE *)params[i].value) == FAIL) { std::string error = "Failed to set parameter "; if (params[i].name != nullptr) { error += params[i].name; error.append(1, ' '); } error += "on procedure "; error += proc; throw std::runtime_error(error); } } if (dbrpcsend(_dbHandle) == FAIL) throw std::runtime_error("Failed to send RPC"); // Wait for the server to return if (dbsqlok(_dbHandle) == FAIL) throw std::runtime_error(_error); // FreeTDS's implementation of dblib does not always process the result of // of the message handler. For instance there are situations where an error // has occurred but dbsqlok returned success. In these situations we need to // check the actual _error property and throw if it is not blank. if (!_error.empty()) throw std::runtime_error(_error); } void SqlConnection::execute_proc_common2(const char *proc, const std::vector<db_param>& params) { Connect(); Dispose(); _fetched_rows = false; _fetched_results = false; if (dbrpcinit(_dbHandle, proc, 0) == FAIL) { std::string error = "Failed to init stored procedure: "; error += proc; throw std::runtime_error(error); } for (const auto& param : params) { int real_type = 0; BYTE *value = (BYTE *)&param.ivalue; switch (param.type) { case ParamType::Bit: real_type = SYBBITN; break; case ParamType::Int: real_type = SYBINT4; break; case ParamType::String: real_type = SYBCHAR; value = (BYTE *)param.pvalue; break; default: // Not reached? throw std::runtime_error("Unknown stored procedure parameter type"); } if (dbrpcparam(_dbHandle, param.name, 0, real_type, -1, param.datalen, value) == FAIL) { std::string error = "Failed to set parameter "; if (param.name != nullptr) { error += param.name; error.append(1, ' '); } error += "on procedure "; error += proc; throw std::runtime_error(error); } } if (dbrpcsend(_dbHandle) == FAIL) throw std::runtime_error("Failed to send RPC"); // Wait for the server to return if (dbsqlok(_dbHandle) == FAIL) throw std::runtime_error(_error); // FreeTDS's implementation of dblib does not always process the result of // of the message handler. For instance there are situations where an error // has occurred but dbsqlok returned success. In these situations we need to // check the actual _error property and throw if it is not blank. if (!_error.empty()) throw std::runtime_error(_error); } }
25.051563
102
0.643485
devinsmith
70d268b60349d27d067b1977cad8a9015bda2b03
1,708
cpp
C++
LeetCode/c/113.cpp
Leoyuseu/Code
34edfbbfb7875b3ed06de393c192c1f13a5074f4
[ "BSD-Source-Code" ]
null
null
null
LeetCode/c/113.cpp
Leoyuseu/Code
34edfbbfb7875b3ed06de393c192c1f13a5074f4
[ "BSD-Source-Code" ]
null
null
null
LeetCode/c/113.cpp
Leoyuseu/Code
34edfbbfb7875b3ed06de393c192c1f13a5074f4
[ "BSD-Source-Code" ]
null
null
null
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int> > ans; if (root == NULL) return ans; vector<int> path; pathSumHelper(root, sum, ans, path); return ans; } void pathSumHelper(TreeNode *root, int sum, vector<vector<int> > &ans, vector<int> &path) { if (root == NULL) { return; } if (sum == root->val && root->left == NULL && root->right == NULL) { path.push_back(root->val); ans.push_back(path); path.pop_back(); return; } path.push_back(root->val); pathSumHelper(root->left, sum - root->val, ans, path); pathSumHelper(root->right, sum - root->val, ans, path); path.pop_back(); } }; int main() { int sum = 22; TreeNode *root = new TreeNode(5); root->left = new TreeNode(4); root->right = new TreeNode(8); root->left->left = new TreeNode(11); root->right->left = new TreeNode(13); root->right->right = new TreeNode(4); root->left->left->left = new TreeNode(7); root->left->left->right = new TreeNode(2); root->right->right->left = new TreeNode(5); root->right->right->right = new TreeNode(1); Solution s; auto ans = s.pathSum(root, sum); for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < ans[i].size(); j++) { printf("%d ", ans[i][j]); } printf("\n"); } return 0; }
23.722222
95
0.536885
Leoyuseu
70d4db043e146d7d0c76666aa877981a6b7e22a9
15,215
cc
C++
ns-3-dev/src/simple/model/simple-net-device.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
11
2015-11-24T11:07:28.000Z
2021-12-23T04:10:29.000Z
ns-3-dev/src/simple/model/simple-net-device.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
null
null
null
ns-3-dev/src/simple/model/simple-net-device.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
6
2016-03-01T06:32:21.000Z
2022-03-24T19:31:41.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "simple-net-device.h" #include "simple-channel.h" #include "ns3/node.h" #include "ns3/packet.h" #include "ns3/log.h" #include "ns3/pointer.h" #include "ns3/error-model.h" #include "ns3/trace-source-accessor.h" #include "ns3/ipv4-header.h" #include "ns3/arp-header.h" #include "ns3/tcp-l4-protocol.h" #include "ns3/udp-l4-protocol.h" #include "ns3/udp-header.h" #include "ns3/tcp-header.h" #include "ns3/message.h" #include "ns3/mal-proxy.h" #include "ns3/ethernet-header.h" #include "ns3/ethernet-trailer.h" #include "ns3/llc-snap-header.h" NS_LOG_COMPONENT_DEFINE ("SimpleNetDevice"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (SimpleNetDevice); TypeId SimpleNetDevice::GetTypeId (void) { static TypeId tid = TypeId ("ns3::SimpleNetDevice") .SetParent<NetDevice> () .AddConstructor<SimpleNetDevice> () .AddAttribute ("ReceiveErrorModel", "The receiver error model used to simulate packet loss", PointerValue (), MakePointerAccessor (&SimpleNetDevice::m_receiveErrorModel), MakePointerChecker<ErrorModel> ()) .AddTraceSource ("PhyRxDrop", "Trace source indicating a packet has been dropped by the device during reception", MakeTraceSourceAccessor (&SimpleNetDevice::m_phyRxDropTrace)) ; return tid; } SimpleNetDevice::SimpleNetDevice () : m_channel (0), m_node (0), m_mtu (1500), //m_mtu (0xffff), m_ifIndex (0) { } void SimpleNetDevice::AddHeaderTrailer (Ptr<Packet> p, Mac48Address source, Mac48Address dest, uint16_t protocolNumber) { EthernetHeader header (false); header.SetSource (source); header.SetDestination (dest); EthernetTrailer trailer; uint16_t lengthType = 0; lengthType = protocolNumber; LlcSnapHeader llc; llc.SetType (protocolNumber); p->AddHeader (llc); // // This corresponds to the length interpretation of the lengthType // field but with an LLC/SNAP header added to the payload as in // IEEE 802.2 // lengthType = p->GetSize (); // // All Ethernet frames must carry a minimum payload of 46 bytes. The // LLC SNAP header counts as part of this payload. We need to padd out // if we don't have enough bytes. These must be real bytes since they // will be written to pcap files and compared in regression trace files. // if (p->GetSize () < 46) { uint8_t buffer[46]; memset (buffer, 0, 46); Ptr<Packet> padd = Create<Packet> (buffer, 46 - p->GetSize ()); p->AddAtEnd (padd); } NS_ASSERT_MSG (p->GetSize () <= GetMtu (), "CsmaNetDevice::AddHeader(): 802.3 Length/Type field with LLC/SNAP: " "length interpretation must not exceed device frame size minus overhead " << p->GetSize() << ":" << GetMtu()); NS_LOG_LOGIC ("header.SetLengthType (" << lengthType << ")"); header.SetLengthType (lengthType); p->AddHeader (header); if (Node::ChecksumEnabled ()) { trailer.EnableFcs (true); } trailer.CalcFcs (p); p->AddTrailer (trailer); } Ipv4Header SimpleNetDevice::GetIPHeader(Ptr<Packet> packet_received) { Ptr<Packet> packet = packet_received->Copy (); EthernetTrailer trailer; packet->RemoveTrailer (trailer); EthernetHeader header (false); packet->RemoveHeader (header); Ipv4Header ipHeader; packet->PeekHeader(ipHeader); return ipHeader; } bool SimpleNetDevice::GhostIntercept(Ptr<Packet> packet_received, bool sending, bool *writeToTap, Mac48Address from) { ProfileFunction("GhostIntercept", true); NS_LOG_FUNCTION(this << " UID : " << packet_received->GetUid() << " NODE: " << m_node->GetId()); MaliciousTag mtag; int protocol; packet_received->PeekPacketTag(mtag); Ptr<Packet> packet = packet_received->Copy (); Ipv4Header ipHeader; packet->PeekHeader(ipHeader); //uint32_t size = packet->PeekHeader(ipHeader); NS_LOG_INFO("Packet " << packet_received->GetUid() << " IP header " << ipHeader); protocol = ipHeader.GetProtocol(); if (protocol != UdpL4Protocol::PROT_NUMBER && protocol != TcpL4Protocol::PROT_NUMBER) { NS_LOG_DEBUG( "GhostIntercept false 7: protocol" << protocol); packet->AddHeader(ipHeader); // Proxy only receives TCP and UDP packets ProfileFunction("GhostIntercept", false); return false; } // don't process UDP packets that you are receiving /* // REPLAY requires to look at packets being received if (protocol == UdpL4Protocol::PROT_NUMBER && !sending) { return false; } */ if (sending) { if (mtag.GetMalStatus() == MaliciousTag::FROMPROXY && mtag.GetSrcNode() == m_node->GetId()) { ProfileFunction("GhostIntercept", false); return false; // if sending, and from my proxy, no point to intercept, but possibly to write tap...? } } Ptr<Packet> pcopy = packet->Copy(); pcopy->RemoveHeader(ipHeader); if (ipHeader.GetPayloadSize () < pcopy->GetSize ()) { pcopy->RemoveAtEnd (pcopy->GetSize () - ipHeader.GetPayloadSize ()); } uint16_t destPort = 0; // check port: if the port is not a listening one, create a new one if (protocol == UdpL4Protocol::PROT_NUMBER) { UdpHeader udpHeader; pcopy->PeekHeader (udpHeader); destPort = udpHeader.GetDestinationPort() ; if (!m_node->IsLocalPort(false, destPort)) { ProfileFunction("GhostIntercept", false); return false; } //see if the malicious proxy cares about this message type /* XXX - Now this is done at TapDevice Ptr<Application> app = m_node->GetApplication(0); uint8_t *msg = new uint8_t[pcopy->GetSize()]; pcopy->CopyData(msg, pcopy->GetSize()); uint32_t offset = 8; //size of udp header Message *m = new Message(msg+offset); Application *ptr; ptr = GetPointer(app); Ptr<MalProxy> proxy = Ptr<MalProxy>((MalProxy*)ptr); if (!proxy->MalMsg(m)) { std::cout << "GhostIntercept false 3 type: " << m->type << std::endl; delete m; delete msg; ProfileFunction("GhostIntercept", false); return false; } delete m; delete msg; */ } if (protocol == TcpL4Protocol::PROT_NUMBER) { TcpHeader tcpHeader; pcopy->PeekHeader (tcpHeader); destPort = tcpHeader.GetDestinationPort() ; if (!m_node->IsLocalPort(true, destPort)) { ProfileFunction("GhostIntercept", false); return false; } } packet->RemovePacketTag(mtag); mtag.StartTimer(); mtag.SetIPDest(ipHeader.GetDestination().Get()); mtag.SetIPSource(ipHeader.GetSource().Get()); if (mtag.GetSrcNode() != m_node->GetId()) { // from outside - intercept NS_LOG_INFO(" Packet from outside. destination should be me " << ipHeader.GetDestination()); // actually, the destination should be already me } else { if (mtag.GetMalStatus() == MaliciousTag::FROMTAP) { NS_LOG_INFO(" Intercept packet from my TAP: to handle this packet should muck destination from original " << ipHeader.GetDestination() << " to myaddr " << ipHeader.GetSource()); // from my tap device. should intercept mtag.SetSpoof(true); } else { // from my proxy, do not intercept and it should be written on my tap if (m_node->IsLocalAddress(ipHeader.GetDestination())) { NS_LOG_INFO("from proxy and me for mine - spoof: " << mtag.IsSpoof() << " to my tap"); (*writeToTap) = true; packet->AddPacketTag(mtag); ProfileFunction("GhostIntercept", false); return false; } } } packet->AddPacketTag(mtag); // add sending information // make ipv4 receive the packet ProfileFunction("GhostIntercept", false); if (m_node->IsMalicious()) m_rxCallback (this, packet, 2048, from); //if (m_node->IsMalicious()) m_rxCallback (this, packet, 2048, header.GetSource ()); return true; } void SimpleNetDevice::Receive (Ptr<Packet> packet, uint16_t protocol, Mac48Address to, Mac48Address from) { ProfileFunction("SimpleReceive", true); NS_LOG_FUNCTION (m_node->GetId() << " pcaket: " << packet->GetUid() << protocol << to << from); NetDevice::PacketType packetType; if (m_receiveErrorModel && m_receiveErrorModel->IsCorrupt (packet) ) { m_phyRxDropTrace (packet); ProfileFunction("SimpleReceive", false); return; } Ptr<Packet> originalPacket = packet->Copy (); EthernetTrailer trailer; originalPacket->RemoveTrailer (trailer); if (Node::ChecksumEnabled ()) { trailer.EnableFcs (true); } trailer.CheckFcs (originalPacket); bool crcGood = trailer.CheckFcs (originalPacket); if (!crcGood) { NS_LOG_INFO ("CRC error on originalPacket " << originalPacket); m_phyRxDropTrace (originalPacket); ProfileFunction("SimpleReceive", false); return; } EthernetHeader header (false); originalPacket->RemoveHeader (header); uint16_t protocol_new; NS_LOG_INFO("Ethernet Header: " << header); // // If the length/type is less than 1500, it corresponds to a length // interpretation originalPacket. In this case, it is an 802.3 originalPacket and // will also have an 802.2 LLC header. If greater than 1500, we // find the protocol number (Ethernet type) directly. // if (header.GetLengthType () <= 1500) { if (originalPacket->GetSize() < header.GetLengthType()) return; NS_ASSERT (originalPacket->GetSize () >= header.GetLengthType ()); uint32_t padlen = originalPacket->GetSize () - header.GetLengthType (); if (padlen > 46) return; if (padlen > 0) { originalPacket->RemoveAtEnd (padlen); } LlcSnapHeader llc; originalPacket->RemoveHeader (llc); protocol_new = llc.GetType (); } else { protocol_new = header.GetLengthType (); } bool writeToTap = false; if (m_node->IsMalicious() && protocol == 2048) { //NS_LOG_INFO("try intercept while receiving at node " << m_node->GetId()); //if (GhostIntercept(originalPacket, false, &writeToTap, from)) return; } if (to == m_address) { packetType = NetDevice::PACKET_HOST; } else if (to.IsBroadcast ()) { packetType = NetDevice::PACKET_BROADCAST; } else if (to.IsGroup ()) { packetType = NetDevice::PACKET_MULTICAST; } else { packetType = NetDevice::PACKET_OTHERHOST; } /* if (protocol_new == 2048 && m_node->IsMalicious() && m_node->IsLocalAddress(GetIPHeader(packet).GetDestination())) { writeToTap = true; } */ if (!m_promiscCallback.IsNull ()) { m_promiscCallback (this, originalPacket, protocol, from, to, packetType); // this writes to tap } ProfileFunction("SimpleReceive", false); /*if (writeToTap) return;*/ if (packetType != PACKET_OTHERHOST) m_rxCallback (this, packet, protocol_new, from); // local up } void SimpleNetDevice::AddChannel (Ptr<SimpleChannel> channel, Mac48Address dest_addr) { uint64_t mac = 0; dest_addr.CopyTo((uint8_t*)&mac); m_channels[mac] = channel; channel->Add (this); } uint32_t SimpleNetDevice::GetNChannels (void) { return m_channels.size (); } /* Ptr<Channel> SimpleNetDevice::GetChannel (uint32_t i) { return m_channels[i]; } */ // hjlee deprecate later void SimpleNetDevice::SetChannel (Ptr<SimpleChannel> channel) { m_channel = channel; m_channel->Add (this); } void SimpleNetDevice::SetReceiveErrorModel (Ptr<ErrorModel> em) { m_receiveErrorModel = em; } void SimpleNetDevice::SetIfIndex (const uint32_t index) { m_ifIndex = index; } uint32_t SimpleNetDevice::GetIfIndex (void) const { return m_ifIndex; } Ptr<Channel> SimpleNetDevice::GetChannel (void) const { return m_channel; } void SimpleNetDevice::SetAddress (Address address) { m_address = Mac48Address::ConvertFrom (address); } Address SimpleNetDevice::GetAddress (void) const { // // Implicit conversion from Mac48Address to Address // return m_address; } bool SimpleNetDevice::SetMtu (const uint16_t mtu) { m_mtu = mtu; return true; } uint16_t SimpleNetDevice::GetMtu (void) const { return m_mtu; } bool SimpleNetDevice::IsLinkUp (void) const { return true; } void SimpleNetDevice::AddLinkChangeCallback (Callback<void> callback) {} bool SimpleNetDevice::IsBroadcast (void) const { return true; } Address SimpleNetDevice::GetBroadcast (void) const { return Mac48Address ("ff:ff:ff:ff:ff:ff"); } bool SimpleNetDevice::IsMulticast (void) const { return false; } Address SimpleNetDevice::GetMulticast (Ipv4Address multicastGroup) const { return Mac48Address::GetMulticast (multicastGroup); } Address SimpleNetDevice::GetMulticast (Ipv6Address addr) const { return Mac48Address::GetMulticast (addr); } bool SimpleNetDevice::IsPointToPoint (void) const { return false; } bool SimpleNetDevice::IsBridge (void) const { return false; } bool SimpleNetDevice::Send (Ptr<Packet> packet, const Address& dest, uint16_t protocolNumber) { NS_LOG_FUNCTION (" pcaket: " << packet->GetUid() << dest << protocolNumber); Mac48Address to = Mac48Address::ConvertFrom (dest); //m_channel->Send (packet, protocolNumber, to, m_address, this); SendFrom(packet, m_address, dest, protocolNumber); return true; } bool SimpleNetDevice::SendFrom (Ptr<Packet> packet, const Address& source, const Address& dest, uint16_t protocolNumber) { NS_LOG_FUNCTION (" pcaket: " << packet->GetUid() << source << dest << protocolNumber); ProfileFunction("SimpleSendFrom", true); Mac48Address to = Mac48Address::ConvertFrom (dest); Mac48Address from = Mac48Address::ConvertFrom (source); AddHeaderTrailer (packet, from, to, protocolNumber); //to avoid having to write a hash function for uint8_t[6], just sticking // the mac address into a uint64_t uint64_t mac = 0; to.CopyTo((uint8_t*)&mac); __gnu_cxx::hash_map<uint64_t, Ptr<SimpleChannel> >::iterator ch = m_channels.find(mac); ProfileFunction("SimpleSendFrom", false); if (ch != m_channels.end()) { (ch->second)->Send (packet, protocolNumber, to, from, this); } else { NS_LOG_INFO(" no matching address for " << to << ", broadcast "); for (ch = m_channels.begin(); ch != m_channels.end(); ch++) { (ch->second)->Send (packet, protocolNumber, to, from, this); } } return true; } Ptr<Node> SimpleNetDevice::GetNode (void) const { return m_node; } void SimpleNetDevice::SetNode (Ptr<Node> node) { m_node = node; } bool SimpleNetDevice::NeedsArp (void) const { return true; } void SimpleNetDevice::SetReceiveCallback (NetDevice::ReceiveCallback cb) { m_rxCallback = cb; } void SimpleNetDevice::DoDispose (void) { m_channel = 0; m_node = 0; m_receiveErrorModel = 0; NetDevice::DoDispose (); } void SimpleNetDevice::SetPromiscReceiveCallback (PromiscReceiveCallback cb) { m_promiscCallback = cb; } bool SimpleNetDevice::SupportsSendFrom (void) const { return true; } } // namespace ns3
26.506969
144
0.703648
maxvonhippel
70d8d78bb5c30a1020f9d6565371a6e3cea6bdae
6,270
hpp
C++
phonelibs/acado/include/acado/validated_integrator/ellipsoidal_integrator.hpp
Neptos/openpilot
01914a1a91ade18bd7aead99e7d1bf38cd22ad89
[ "MIT" ]
116
2018-03-07T09:00:10.000Z
2020-04-06T18:37:45.000Z
phonelibs/acado/include/acado/validated_integrator/ellipsoidal_integrator.hpp
Neptos/openpilot
01914a1a91ade18bd7aead99e7d1bf38cd22ad89
[ "MIT" ]
66
2020-04-09T20:27:57.000Z
2022-01-27T14:39:24.000Z
phonelibs/acado/include/acado/validated_integrator/ellipsoidal_integrator.hpp
Neptos/openpilot
01914a1a91ade18bd7aead99e7d1bf38cd22ad89
[ "MIT" ]
154
2020-04-08T21:41:22.000Z
2022-03-17T21:05:33.000Z
/* * This file is part of ACADO Toolkit. * * ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization. * Copyright (C) 2008-2014 by Boris Houska, Hans Joachim Ferreau, * Milan Vukov, Rien Quirynen, KU Leuven. * Developed within the Optimization in Engineering Center (OPTEC) * under supervision of Moritz Diehl. All rights reserved. * * ACADO Toolkit 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 3 of the License, or (at your option) any later version. * * ACADO Toolkit 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 ACADO Toolkit; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ /** * \file include/acado/validated_integrator/ellipsoidal_integrator.hpp * \author Boris Houska, Mario Villanueva, Benoit Chachuat */ #ifndef ACADO_TOOLKIT_ELLIPSOIDAL_INTEGRATOR_HPP #define ACADO_TOOLKIT_ELLIPSOIDAL_INTEGRATOR_HPP #include <iostream> #include <iomanip> #include <acado/clock/clock.hpp> #include <acado/utils/acado_utils.hpp> #include <acado/user_interaction/algorithmic_base.hpp> #include <acado/matrix_vector/matrix_vector.hpp> #include <acado/variables_grid/variables_grid.hpp> #include <acado/symbolic_expression/symbolic_expression.hpp> #include <acado/function/function.hpp> #include <acado/set_arithmetics/set_arithmetics.hpp> BEGIN_NAMESPACE_ACADO /** * \brief Validated integrator for ODEs based on Taylor models with ellipsoidal remainder term. * * \author Mario Villanueva, Boris Houska */ class EllipsoidalIntegrator : public AlgorithmicBase { public: /** Default constructor. */ EllipsoidalIntegrator( ); /** Constructor that takes the differential equation and the order (default 3) as an argument. * * \param rhs_ The differential equation. * \param N_ The order of the intergrator (default = 3). */ EllipsoidalIntegrator( const DifferentialEquation &rhs_, const int &N_ = 3 ); /** Copy constructor (deep copy). */ EllipsoidalIntegrator( const EllipsoidalIntegrator& arg ); /** Destructor. */ virtual ~EllipsoidalIntegrator( ); /** Assignment operator (deep copy). */ virtual EllipsoidalIntegrator& operator=( const EllipsoidalIntegrator& arg ); Tmatrix<Interval> integrate( double t0, double tf, int M, const Tmatrix<Interval> &x ); Tmatrix<Interval> integrate( double t0, double tf, int M, const Tmatrix<Interval> &x, const Tmatrix<Interval> &p ); Tmatrix<Interval> integrate( double t0, double tf, int M, const Tmatrix<Interval> &x, const Tmatrix<Interval> &p, const Tmatrix<Interval> &w ); template <typename T> returnValue integrate( double t0, double tf, Tmatrix<T> *x, Tmatrix<T> *p = 0, Tmatrix<T> *w = 0 ); template <typename T> double step( const double &t, const double &tf, Tmatrix<T> *x, Tmatrix<T> *p = 0, Tmatrix<T> *w = 0 ); returnValue init( const DifferentialEquation &rhs_, const int &N_ = 3 ); Tmatrix<Interval> boundQ() const; template <typename T> Tmatrix<Interval> getStateBound( const Tmatrix<T> &x ) const; // PRIVATE FUNCTIONS: // ---------------------------------------------------------- private: virtual returnValue setupOptions( ); void copy( const EllipsoidalIntegrator& arg ); template <typename T> void phase0( double t, Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w, Tmatrix<T> &coeff, Tmatrix<double> &C ); template <typename T> double phase1( double t, double tf, Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w, Tmatrix<T> &coeff, Tmatrix<double> &C ); template <typename T> void phase2( double t, double h, Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w, Tmatrix<T> &coeff, Tmatrix<double> &C ); template <typename T> Tmatrix<T> evaluate( Function &f, double t, Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w ) const; template <typename T> Tmatrix<T> evaluate( Function &f, Interval t, Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w ) const; template <typename T> Tmatrix<T> phi( const Tmatrix<T> &coeff, const double &h ) const; template <typename T> Tmatrix<double> hat( const Tmatrix<T> &x ) const; Tmatrix<Interval> evalC ( const Tmatrix<double> &C, double h ) const; Tmatrix<double> evalC2( const Tmatrix<double> &C, double h ) const; double scale( const Interval &E, const Interval &X ) const; double norm ( const Tmatrix<Interval> &E, Tmatrix<Interval> &X ) const; BooleanType isIncluded( const Tmatrix<Interval> &A, const Tmatrix<Interval> &B ) const; template <typename T> Tmatrix<Interval> bound( const Tmatrix<T> &x ) const; template <typename T> Tmatrix<Interval> getRemainder( const Tmatrix<T> &x ) const; template <typename T> Tmatrix<T> getPolynomial( const Tmatrix<T> &x ) const; template <typename T> void center( Tmatrix<T> &x ) const; void updateQ( Tmatrix<double> C, Tmatrix<Interval> R ); void setInfinity(); // PRIVATE MEMBERS: // ---------------------------------------------------------- private: int nx; // number of differential states. int N ; // the order of the integrator. Function g ; // Taylor expansion of the solution trajectory Function gr ; // Remainder term associated with g Function dg ; // Jacobian of the function g : g(t,x,...)/dx Function ddg; // Directional derivative of dg: (d^2 g(t,x,...)/d^2x)*r*r Tmatrix<double> Q; // Ellipsoidal remainder matrix RealClock totalTime ; RealClock Phase0Time; RealClock Phase1Time; }; CLOSE_NAMESPACE_ACADO #include <acado/validated_integrator/ellipsoidal_integrator.ipp> #endif // ACADO_TOOLKIT_ELLIPSOIDAL_INTEGRATOR_HPP // end of file.
31.35
116
0.675598
Neptos
70db14e2d202219c453ee61d65f932298e5a1f43
1,464
cpp
C++
CSES/Tree Algorithms/Company Queries I.cpp
s166harth/CC
b6c0fe58f03633fe2787a567a16909f1b2966e7b
[ "MIT" ]
406
2020-05-28T13:35:08.000Z
2022-03-31T17:23:26.000Z
CSES/Tree Algorithms/Company Queries I.cpp
shakeeb-droids/CC
2f49fcb52d748804aee9fc7f26abb3150bec69e5
[ "MIT" ]
3
2021-01-01T17:50:34.000Z
2021-10-02T10:02:27.000Z
CSES/Tree Algorithms/Company Queries I.cpp
shakeeb-droids/CC
2f49fcb52d748804aee9fc7f26abb3150bec69e5
[ "MIT" ]
108
2020-07-21T13:02:33.000Z
2022-03-28T22:46:49.000Z
/** 🍪 thew6rst 🍪 12.02.2021 10:45:31 **/ #ifdef W #include "k_II.h" #else #include <bits/stdc++.h> using namespace std; #endif #define pb emplace_back #define all(x) x.begin(), x.end() #define sz(x) static_cast<int32_t>(x.size()) template<class T> class Y { T f; public: template<class U> explicit Y(U&& f): f(forward<U>(f)) {} template<class... Args> decltype(auto) operator()(Args&&... args) { return f(ref(*this), forward<Args>(args)...); } }; template<class T> Y(T) -> Y<T>; const int64_t DESPACITO = 2e18; const int INF = 2e9, MOD = 1e9+7; const int N = 2e5 + 5; const int LG = 20; int main() { cin.tie(nullptr)->sync_with_stdio(false); int i, n, Q; cin >> n >> Q; vector<vector<int>> g(n); for(i = 1; i < n; i++) { int p; cin >> p; g[--p].pb(i); } array<vector<int>, LG> anc; for(auto& x: anc) x.assign(n, -1); Y([&](auto dfs, int v, int p) -> void { anc[0][v] = p; for(int k = 1; k < LG; k++) anc[k][v] = ~anc[k-1][v]? anc[k-1][anc[k-1][v]] : -1; for(auto& x: g[v]) dfs(x, v); })(0, -1); auto walk = [&anc](int v, int d) { for(int k = LG-1; ~v and ~k; k--) if(d>>k & 1) v = anc[k][v]; return ~v? v+1 : v; }; while(Q--) { int x, d; cin >> x >> d; cout << walk(--x, d) << '\n'; }
24.813559
72
0.456967
s166harth
70dbe8ee408e4f227614da2f7348e29f024c810c
78,997
cc
C++
src/net/reporting/reporting_header_parser_unittest.cc
Mr-Sheep/naiveproxy
9f6e9768295f6d1d41517a15a621d4756bd7d6be
[ "BSD-3-Clause" ]
null
null
null
src/net/reporting/reporting_header_parser_unittest.cc
Mr-Sheep/naiveproxy
9f6e9768295f6d1d41517a15a621d4756bd7d6be
[ "BSD-3-Clause" ]
null
null
null
src/net/reporting/reporting_header_parser_unittest.cc
Mr-Sheep/naiveproxy
9f6e9768295f6d1d41517a15a621d4756bd7d6be
[ "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// 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 "net/reporting/reporting_header_parser.h" #include <sstream> #include <string> #include <vector> #include "base/bind.h" #include "base/json/json_reader.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/test/scoped_feature_list.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "base/values.h" #include "net/base/features.h" #include "net/base/schemeful_site.h" #include "net/reporting/mock_persistent_reporting_store.h" #include "net/reporting/reporting_cache.h" #include "net/reporting/reporting_endpoint.h" #include "net/reporting/reporting_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" namespace net { namespace { using CommandType = MockPersistentReportingStore::Command::Type; // This test is parametrized on a boolean that represents whether to use a // MockPersistentReportingStore. class ReportingHeaderParserTest : public ReportingTestBase, public ::testing::WithParamInterface<bool> { protected: ReportingHeaderParserTest() { // This is a private API of the reporting service, so no need to test the // case kPartitionNelAndReportingByNetworkIsolationKey is disabled - the // feature is only applied at the entry points of the service. feature_list_.InitAndEnableFeature( features::kPartitionNelAndReportingByNetworkIsolationKey); ReportingPolicy policy; policy.max_endpoints_per_origin = 10; policy.max_endpoint_count = 20; UsePolicy(policy); if (GetParam()) store_ = std::make_unique<MockPersistentReportingStore>(); else store_ = nullptr; UseStore(store_.get()); } ~ReportingHeaderParserTest() override = default; void SetUp() override { // All ReportingCache methods assume that the store has been initialized. if (mock_store()) { mock_store()->LoadReportingClients( base::BindOnce(&ReportingCache::AddClientsLoadedFromStore, base::Unretained(cache()))); mock_store()->FinishLoading(true); } } MockPersistentReportingStore* mock_store() { return store_.get(); } ReportingEndpointGroup MakeEndpointGroup( const std::string& name, const std::vector<ReportingEndpoint::EndpointInfo>& endpoints, OriginSubdomains include_subdomains = OriginSubdomains::DEFAULT, base::TimeDelta ttl = base::TimeDelta::FromDays(1), url::Origin origin = url::Origin()) { ReportingEndpointGroupKey group_key(kNik_ /* unused */, url::Origin() /* unused */, name); ReportingEndpointGroup group; group.group_key = group_key; group.include_subdomains = include_subdomains; group.ttl = ttl; group.endpoints = std::move(endpoints); return group; } // Constructs a string which would represent a single group in a Report-To // header. If |group_name| is an empty string, the group name will be omitted // (and thus default to "default" when parsed). Setting |omit_defaults| omits // the priority, weight, and include_subdomains fields if they are default, // otherwise they are spelled out fully. std::string ConstructHeaderGroupString(const ReportingEndpointGroup& group, bool omit_defaults = true) { std::ostringstream s; s << "{ "; if (!group.group_key.group_name.empty()) { s << "\"group\": \"" << group.group_key.group_name << "\", "; } s << "\"max_age\": " << group.ttl.InSeconds() << ", "; if (group.include_subdomains != OriginSubdomains::DEFAULT) { s << "\"include_subdomains\": true, "; } else if (!omit_defaults) { s << "\"include_subdomains\": false, "; } s << "\"endpoints\": ["; for (const ReportingEndpoint::EndpointInfo& endpoint_info : group.endpoints) { s << "{ "; s << "\"url\": \"" << endpoint_info.url.spec() << "\""; if (!omit_defaults || endpoint_info.priority != ReportingEndpoint::EndpointInfo::kDefaultPriority) { s << ", \"priority\": " << endpoint_info.priority; } if (!omit_defaults || endpoint_info.weight != ReportingEndpoint::EndpointInfo::kDefaultWeight) { s << ", \"weight\": " << endpoint_info.weight; } s << " }, "; } if (!group.endpoints.empty()) s.seekp(-2, s.cur); // Overwrite trailing comma and space. s << "]"; s << " }"; return s.str(); } void ParseHeader(const NetworkIsolationKey& network_isolation_key, const GURL& url, const std::string& json) { std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated("[" + json + "]"); if (value) { ReportingHeaderParser::ParseHeader(context(), network_isolation_key, url, std::move(value)); } } base::test::ScopedFeatureList feature_list_; const GURL kUrl1_ = GURL("https://origin1.test/path"); const url::Origin kOrigin1_ = url::Origin::Create(kUrl1_); const GURL kUrl2_ = GURL("https://origin2.test/path"); const url::Origin kOrigin2_ = url::Origin::Create(kUrl2_); const NetworkIsolationKey kNik_ = NetworkIsolationKey(SchemefulSite(kOrigin1_), SchemefulSite(kOrigin1_)); const NetworkIsolationKey kOtherNik_ = NetworkIsolationKey(SchemefulSite(kOrigin2_), SchemefulSite(kOrigin2_)); const GURL kUrlEtld_ = GURL("https://co.uk/foo.html/"); const url::Origin kOriginEtld_ = url::Origin::Create(kUrlEtld_); const GURL kEndpoint1_ = GURL("https://endpoint1.test/"); const GURL kEndpoint2_ = GURL("https://endpoint2.test/"); const GURL kEndpoint3_ = GURL("https://endpoint3.test/"); const GURL kEndpointPathAbsolute_ = GURL("https://origin1.test/path-absolute-url"); const std::string kGroup1_ = "group1"; const std::string kGroup2_ = "group2"; // There are 2^3 = 8 of these to test the different combinations of matching // vs mismatching NIK, origin, and group. const ReportingEndpointGroupKey kGroupKey11_ = ReportingEndpointGroupKey(kNik_, kOrigin1_, kGroup1_); const ReportingEndpointGroupKey kGroupKey21_ = ReportingEndpointGroupKey(kNik_, kOrigin2_, kGroup1_); const ReportingEndpointGroupKey kGroupKey12_ = ReportingEndpointGroupKey(kNik_, kOrigin1_, kGroup2_); const ReportingEndpointGroupKey kGroupKey22_ = ReportingEndpointGroupKey(kNik_, kOrigin2_, kGroup2_); private: std::unique_ptr<MockPersistentReportingStore> store_; }; // TODO(juliatuttle): Ideally these tests should be expecting that JSON parsing // (and therefore header parsing) may happen asynchronously, but the entire // pipeline is also tested by NetworkErrorLoggingEndToEndTest. TEST_P(ReportingHeaderParserTest, Invalid) { static const struct { const char* header_value; const char* description; } kInvalidHeaderTestCases[] = { {"{\"max_age\":1, \"endpoints\": [{}]}", "missing url"}, {"{\"max_age\":1, \"endpoints\": [{\"url\":0}]}", "non-string url"}, {"{\"max_age\":1, \"endpoints\": [{\"url\":\"//scheme/relative\"}]}", "scheme-relative url"}, {"{\"max_age\":1, \"endpoints\": [{\"url\":\"relative/path\"}]}", "path relative url"}, {"{\"max_age\":1, \"endpoints\": [{\"url\":\"http://insecure/\"}]}", "insecure url"}, {"{\"endpoints\": [{\"url\":\"https://endpoint/\"}]}", "missing max_age"}, {"{\"max_age\":\"\", \"endpoints\": [{\"url\":\"https://endpoint/\"}]}", "non-integer max_age"}, {"{\"max_age\":-1, \"endpoints\": [{\"url\":\"https://endpoint/\"}]}", "negative max_age"}, {"{\"max_age\":1, \"group\":0, " "\"endpoints\": [{\"url\":\"https://endpoint/\"}]}", "non-string group"}, // Note that a non-boolean include_subdomains field is *not* invalid, per // the spec. // Priority should be a nonnegative integer. {"{\"max_age\":1, " "\"endpoints\": [{\"url\":\"https://endpoint/\",\"priority\":\"\"}]}", "non-integer priority"}, {"{\"max_age\":1, " "\"endpoints\": [{\"url\":\"https://endpoint/\",\"priority\":-1}]}", "negative priority"}, // Weight should be a non-negative integer. {"{\"max_age\":1, " "\"endpoints\": [{\"url\":\"https://endpoint/\",\"weight\":\"\"}]}", "non-integer weight"}, {"{\"max_age\":1, " "\"endpoints\": [{\"url\":\"https://endpoint/\",\"weight\":-1}]}", "negative weight"}, {"[{\"max_age\":1, \"endpoints\": [{\"url\":\"https://a/\"}]}," "{\"max_age\":1, \"endpoints\": [{\"url\":\"https://b/\"}]}]", "wrapped in list"}}; for (size_t i = 0; i < base::size(kInvalidHeaderTestCases); ++i) { auto& test_case = kInvalidHeaderTestCases[i]; ParseHeader(kNik_, kUrl1_, test_case.header_value); EXPECT_EQ(0u, cache()->GetEndpointCount()) << "Invalid Report-To header (" << test_case.description << ": \"" << test_case.header_value << "\") parsed as valid."; if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(0, mock_store()->StoredEndpointsCount()); EXPECT_EQ(0, mock_store()->StoredEndpointGroupsCount()); } } } TEST_P(ReportingHeaderParserTest, Basic) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(1u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_); ASSERT_TRUE(endpoint); EXPECT_EQ(kOrigin1_, endpoint.group_key.origin); EXPECT_EQ(kGroup1_, endpoint.group_key.group_name); EXPECT_EQ(kEndpoint1_, endpoint.info.url); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, PathAbsoluteURLEndpoint) { std::string header = "{\"group\": \"group1\", \"max_age\":1, \"endpoints\": " "[{\"url\":\"/path-absolute-url\"}]}"; ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(1u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpointPathAbsolute_); ASSERT_TRUE(endpoint); EXPECT_EQ(kOrigin1_, endpoint.group_key.origin); EXPECT_EQ(kGroup1_, endpoint.group_key.group_name); EXPECT_EQ(kEndpointPathAbsolute_, endpoint.info.url); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back( CommandType::ADD_REPORTING_ENDPOINT, ReportingEndpoint(kGroupKey11_, ReportingEndpoint::EndpointInfo{ kEndpointPathAbsolute_})); expected_commands.emplace_back( CommandType::ADD_REPORTING_ENDPOINT_GROUP, CachedReportingEndpointGroup( kGroupKey11_, OriginSubdomains::DEFAULT /* irrelevant */, base::Time() /* irrelevant */, base::Time() /* irrelevant */)); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, OmittedGroupName) { ReportingEndpointGroupKey kGroupKey(kNik_, kOrigin1_, "default"); std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(std::string(), endpoints)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(EndpointGroupExistsInCache(kGroupKey, OriginSubdomains::DEFAULT)); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(1u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey, kEndpoint1_); ASSERT_TRUE(endpoint); EXPECT_EQ(kOrigin1_, endpoint.group_key.origin); EXPECT_EQ("default", endpoint.group_key.group_name); EXPECT_EQ(kEndpoint1_, endpoint.info.url); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, IncludeSubdomainsTrue) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString( MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::INCLUDE)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::INCLUDE)); EXPECT_EQ(1u, cache()->GetEndpointCount()); EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, IncludeSubdomainsFalse) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString( MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::EXCLUDE), false /* omit_defaults */); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::EXCLUDE)); EXPECT_EQ(1u, cache()->GetEndpointCount()); EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, IncludeSubdomainsEtldRejected) { ReportingEndpointGroupKey kGroupKey(kNik_, kOriginEtld_, kGroup1_); std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString( MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::INCLUDE)); ParseHeader(kNik_, kUrlEtld_, header); EXPECT_EQ(0u, cache()->GetEndpointGroupCountForTesting()); EXPECT_FALSE( EndpointGroupExistsInCache(kGroupKey, OriginSubdomains::INCLUDE)); EXPECT_EQ(0u, cache()->GetEndpointCount()); EXPECT_FALSE(EndpointExistsInCache(kGroupKey, kEndpoint1_)); } TEST_P(ReportingHeaderParserTest, NonIncludeSubdomainsEtldAccepted) { ReportingEndpointGroupKey kGroupKey(kNik_, kOriginEtld_, kGroup1_); std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString( MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::EXCLUDE)); ParseHeader(kNik_, kUrlEtld_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(EndpointGroupExistsInCache(kGroupKey, OriginSubdomains::EXCLUDE)); EXPECT_EQ(1u, cache()->GetEndpointCount()); EXPECT_TRUE(EndpointExistsInCache(kGroupKey, kEndpoint1_)); } TEST_P(ReportingHeaderParserTest, IncludeSubdomainsNotBoolean) { std::string header = "{\"group\": \"" + kGroup1_ + "\", " "\"max_age\":86400, \"include_subdomains\": \"NotABoolean\", " "\"endpoints\": [{\"url\":\"" + kEndpoint1_.spec() + "\"}]}"; ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointCount()); EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, NonDefaultPriority) { const int kNonDefaultPriority = 10; std::vector<ReportingEndpoint::EndpointInfo> endpoints = { {kEndpoint1_, kNonDefaultPriority}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_); ASSERT_TRUE(endpoint); EXPECT_EQ(kNonDefaultPriority, endpoint.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, NonDefaultWeight) { const int kNonDefaultWeight = 10; std::vector<ReportingEndpoint::EndpointInfo> endpoints = { {kEndpoint1_, ReportingEndpoint::EndpointInfo::kDefaultPriority, kNonDefaultWeight}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_); ASSERT_TRUE(endpoint); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_EQ(kNonDefaultWeight, endpoint.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, MaxAge) { const int kMaxAgeSecs = 100; base::TimeDelta ttl = base::TimeDelta::FromSeconds(kMaxAgeSecs); base::Time expires = clock()->Now() + ttl; std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString( MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::DEFAULT, ttl)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT, expires)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, MultipleEndpointsSameGroup) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}, {kEndpoint2_}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(2u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_); ASSERT_TRUE(endpoint); EXPECT_EQ(kOrigin1_, endpoint.group_key.origin); EXPECT_EQ(kGroup1_, endpoint.group_key.group_name); EXPECT_EQ(kEndpoint1_, endpoint.info.url); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint.info.weight); ReportingEndpoint endpoint2 = FindEndpointInCache(kGroupKey11_, kEndpoint2_); ASSERT_TRUE(endpoint2); EXPECT_EQ(kOrigin1_, endpoint2.group_key.origin); EXPECT_EQ(kGroup1_, endpoint2.group_key.group_name); EXPECT_EQ(kEndpoint2_, endpoint2.info.url); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint2.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint2.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, MultipleEndpointsDifferentGroups) { std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints2)); ParseHeader(kNik_, kUrl1_, header); EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT)); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(2u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_); ASSERT_TRUE(endpoint); EXPECT_EQ(kOrigin1_, endpoint.group_key.origin); EXPECT_EQ(kGroup1_, endpoint.group_key.group_name); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint.info.weight); ReportingEndpoint endpoint2 = FindEndpointInCache(kGroupKey12_, kEndpoint1_); ASSERT_TRUE(endpoint2); EXPECT_EQ(kOrigin1_, endpoint2.group_key.origin); EXPECT_EQ(kGroup2_, endpoint2.group_key.group_name); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint2.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint2.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->StoredEndpointsCount()); EXPECT_EQ(2, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey12_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey12_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, MultipleHeadersFromDifferentOrigins) { // First origin sets a header with two endpoints in the same group. std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}, {kEndpoint2_}}; std::string header1 = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)); ParseHeader(kNik_, kUrl1_, header1); // Second origin has two endpoint groups. std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint1_}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints3 = {{kEndpoint2_}}; std::string header2 = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints3)); ParseHeader(kNik_, kUrl2_, header2); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_)); EXPECT_EQ(3u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey21_, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey22_, OriginSubdomains::DEFAULT)); EXPECT_EQ(4u, cache()->GetEndpointCount()); EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint2_)); EXPECT_TRUE(FindEndpointInCache(kGroupKey21_, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(kGroupKey22_, kEndpoint2_)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(4, mock_store()->StoredEndpointsCount()); EXPECT_EQ(3, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey21_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey22_, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey21_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey22_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } // Test that each combination of NIK, origin, and group name is considered // distinct. // See also: ReportingCacheTest.ClientsKeyedByEndpointGroupKey TEST_P(ReportingHeaderParserTest, EndpointGroupKey) { // Raise the endpoint limits for this test. ReportingPolicy policy; policy.max_endpoints_per_origin = 5; // This test should use 4. policy.max_endpoint_count = 20; // This test should use 16. UsePolicy(policy); std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}, {kEndpoint2_}}; std::string header1 = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints1)); const ReportingEndpointGroupKey kOtherGroupKey11 = ReportingEndpointGroupKey(kOtherNik_, kOrigin1_, kGroup1_); const ReportingEndpointGroupKey kOtherGroupKey21 = ReportingEndpointGroupKey(kOtherNik_, kOrigin2_, kGroup1_); const ReportingEndpointGroupKey kOtherGroupKey12 = ReportingEndpointGroupKey(kOtherNik_, kOrigin1_, kGroup2_); const ReportingEndpointGroupKey kOtherGroupKey22 = ReportingEndpointGroupKey(kOtherNik_, kOrigin2_, kGroup2_); const struct { NetworkIsolationKey network_isolation_key; GURL url; ReportingEndpointGroupKey group1_key; ReportingEndpointGroupKey group2_key; } kHeaderSources[] = { {kNik_, kUrl1_, kGroupKey11_, kGroupKey12_}, {kNik_, kUrl2_, kGroupKey21_, kGroupKey22_}, {kOtherNik_, kUrl1_, kOtherGroupKey11, kOtherGroupKey12}, {kOtherNik_, kUrl2_, kOtherGroupKey21, kOtherGroupKey22}, }; size_t endpoint_group_count = 0u; size_t endpoint_count = 0u; MockPersistentReportingStore::CommandList expected_commands; // Set 2 endpoints in each of 2 groups for each of 2x2 combinations of // (NIK, origin). for (const auto& source : kHeaderSources) { // Verify pre-parsing state EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint1_)); EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint2_)); EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint1_)); EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint2_)); EXPECT_FALSE(EndpointGroupExistsInCache(source.group1_key, OriginSubdomains::DEFAULT)); EXPECT_FALSE(EndpointGroupExistsInCache(source.group2_key, OriginSubdomains::DEFAULT)); ParseHeader(source.network_isolation_key, source.url, header1); endpoint_group_count += 2u; endpoint_count += 4u; EXPECT_EQ(endpoint_group_count, cache()->GetEndpointGroupCountForTesting()); EXPECT_EQ(endpoint_count, cache()->GetEndpointCount()); // Verify post-parsing state EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint2_)); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint2_)); EXPECT_TRUE(EndpointGroupExistsInCache(source.group1_key, OriginSubdomains::DEFAULT)); EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key, OriginSubdomains::DEFAULT)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(static_cast<int>(endpoint_count), mock_store()->StoredEndpointsCount()); EXPECT_EQ(static_cast<int>(endpoint_group_count), mock_store()->StoredEndpointGroupsCount()); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, source.group1_key, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, source.group1_key, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, source.group1_key); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, source.group2_key, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, source.group2_key, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, source.group2_key); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } // Check that expected data is present in the ReportingCache at the end. for (const auto& source : kHeaderSources) { EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint2_)); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint2_)); EXPECT_TRUE(EndpointGroupExistsInCache(source.group1_key, OriginSubdomains::DEFAULT)); EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key, OriginSubdomains::DEFAULT)); EXPECT_TRUE(cache()->ClientExistsForTesting( source.network_isolation_key, url::Origin::Create(source.url))); } // Test updating existing configurations // This removes endpoint 1, updates the priority of endpoint 2, and adds // endpoint 3. std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_, 2}, {kEndpoint3_}}; // Removes group 1, updates include_subdomains for group 2. std::string header2 = ConstructHeaderGroupString( MakeEndpointGroup(kGroup2_, endpoints2, OriginSubdomains::INCLUDE)); for (const auto& source : kHeaderSources) { // Verify pre-update state EXPECT_TRUE(EndpointGroupExistsInCache(source.group1_key, OriginSubdomains::DEFAULT)); EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key, OriginSubdomains::DEFAULT)); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint1_)); ReportingEndpoint endpoint = FindEndpointInCache(source.group2_key, kEndpoint2_); EXPECT_TRUE(endpoint); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint3_)); ParseHeader(source.network_isolation_key, source.url, header2); endpoint_group_count--; endpoint_count -= 2; EXPECT_EQ(endpoint_group_count, cache()->GetEndpointGroupCountForTesting()); EXPECT_EQ(endpoint_count, cache()->GetEndpointCount()); // Verify post-update state EXPECT_FALSE(EndpointGroupExistsInCache(source.group1_key, OriginSubdomains::DEFAULT)); EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key, OriginSubdomains::INCLUDE)); EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint1_)); endpoint = FindEndpointInCache(source.group2_key, kEndpoint2_); EXPECT_TRUE(endpoint); EXPECT_EQ(2, endpoint.info.priority); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint3_)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(static_cast<int>(endpoint_count), mock_store()->StoredEndpointsCount()); EXPECT_EQ(static_cast<int>(endpoint_group_count), mock_store()->StoredEndpointGroupsCount()); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, source.group1_key, kEndpoint1_); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, source.group1_key, kEndpoint2_); expected_commands.emplace_back( CommandType::DELETE_REPORTING_ENDPOINT_GROUP, source.group1_key); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, source.group2_key, kEndpoint1_); expected_commands.emplace_back( CommandType::UPDATE_REPORTING_ENDPOINT_DETAILS, source.group2_key, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, source.group2_key, kEndpoint3_); expected_commands.emplace_back( CommandType::UPDATE_REPORTING_ENDPOINT_GROUP_DETAILS, source.group2_key); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } // Check that expected data is present in the ReportingCache at the end. for (const auto& source : kHeaderSources) { EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint1_)); EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint2_)); EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint2_)); EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint3_)); EXPECT_FALSE(EndpointGroupExistsInCache(source.group1_key, OriginSubdomains::DEFAULT)); EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key, OriginSubdomains::INCLUDE)); EXPECT_TRUE(cache()->ClientExistsForTesting( source.network_isolation_key, url::Origin::Create(source.url))); } } TEST_P(ReportingHeaderParserTest, HeaderErroneouslyContainsMultipleGroupsOfSameName) { // Add a preexisting header to test that a header with multiple groups of the // same name is treated as if it specified a single group with the combined // set of specified endpoints. In particular, it must overwrite/update any // preexisting group all at once. See https://crbug.com/1116529. std::vector<ReportingEndpoint::EndpointInfo> preexisting = {{kEndpoint1_}}; std::string preexisting_header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, preexisting)); ParseHeader(kNik_, kUrl1_, preexisting_header); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(1u, cache()->GetEndpointCount()); ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_); ASSERT_TRUE(endpoint); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(1, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); // Reset commands so we can check that the next part, adding the header with // duplicate groups, does not cause clearing of preexisting endpoints twice. mock_store()->ClearCommands(); } std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_}}; std::string duplicate_groups_header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2)); ParseHeader(kNik_, kUrl1_, duplicate_groups_header); // Result is as if they set the two groups with the same name as one group. EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(2u, cache()->GetEndpointCount()); ReportingEndpoint endpoint1 = FindEndpointInCache(kGroupKey11_, kEndpoint1_); ASSERT_TRUE(endpoint); EXPECT_EQ(kOrigin1_, endpoint.group_key.origin); EXPECT_EQ(kGroup1_, endpoint.group_key.group_name); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint.info.weight); ReportingEndpoint endpoint2 = FindEndpointInCache(kGroupKey11_, kEndpoint2_); ASSERT_TRUE(endpoint2); EXPECT_EQ(kOrigin1_, endpoint2.group_key.origin); EXPECT_EQ(kGroup1_, endpoint2.group_key.group_name); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority, endpoint2.info.priority); EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight, endpoint2.info.weight); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->StoredEndpointsCount()); EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount()); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back( CommandType::UPDATE_REPORTING_ENDPOINT_DETAILS, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint2_); expected_commands.emplace_back( CommandType::UPDATE_REPORTING_ENDPOINT_GROUP_DETAILS, kGroupKey11_); MockPersistentReportingStore::CommandList actual_commands = mock_store()->GetAllCommands(); EXPECT_THAT(actual_commands, testing::IsSupersetOf(expected_commands)); for (const auto& command : actual_commands) { EXPECT_NE(CommandType::DELETE_REPORTING_ENDPOINT, command.type); EXPECT_NE(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, command.type); // The endpoint with URL kEndpoint1_ is only ever updated, not added anew. EXPECT_NE( MockPersistentReportingStore::Command( CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_), command); // The group is only ever updated, not added anew. EXPECT_NE(MockPersistentReportingStore::Command( CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_), command); } } } TEST_P(ReportingHeaderParserTest, HeaderErroneouslyContainsGroupsWithRedundantEndpoints) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}, {kEndpoint1_}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, kUrl1_, header); // We should dedupe the identical endpoint URLs. EXPECT_EQ(1u, cache()->GetEndpointCount()); ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); } TEST_P(ReportingHeaderParserTest, HeaderErroneouslyContainsMultipleGroupsOfSameNameAndEndpoints) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, kUrl1_, header); // We should dedupe the identical endpoint URLs, even when they're in // different group. EXPECT_EQ(1u, cache()->GetEndpointCount()); ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); } TEST_P(ReportingHeaderParserTest, HeaderErroneouslyContainsGroupsOfSameNameAndOverlappingEndpoints) { std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}, {kEndpoint2_}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint1_}, {kEndpoint3_}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2)); ParseHeader(kNik_, kUrl1_, header); // We should dedupe the identical endpoint URLs, even when they're in // different group. EXPECT_EQ(3u, cache()->GetEndpointCount()); ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_)); ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint2_)); ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint3_)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); } TEST_P(ReportingHeaderParserTest, OverwriteOldHeader) { // First, the origin sets a header with two endpoints in the same group. std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = { {kEndpoint1_, 10 /* priority */}, {kEndpoint2_}}; std::string header1 = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)); ParseHeader(kNik_, kUrl1_, header1); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_EQ(2u, cache()->GetEndpointCount()); EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_)); EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint2_)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(1, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Second header from the same origin should overwrite the previous one. std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = { // This endpoint should update the priority of the existing one. {kEndpoint1_, 20 /* priority */}}; // The second endpoint in this group will be deleted. // This group is new. std::vector<ReportingEndpoint::EndpointInfo> endpoints3 = {{kEndpoint2_}}; std::string header2 = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints3)); ParseHeader(kNik_, kUrl1_, header2); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT)); EXPECT_EQ(2u, cache()->GetEndpointCount()); EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_)); EXPECT_EQ(20, FindEndpointInCache(kGroupKey11_, kEndpoint1_).info.priority); EXPECT_FALSE(FindEndpointInCache(kGroupKey11_, kEndpoint2_)); EXPECT_TRUE(FindEndpointInCache(kGroupKey12_, kEndpoint2_)); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2 + 1, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(1 + 1, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ( 1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey12_, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey12_); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint2_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, OverwriteOldHeaderWithCompletelyNew) { ReportingEndpointGroupKey kGroupKey1(kNik_, kOrigin1_, "1"); ReportingEndpointGroupKey kGroupKey2(kNik_, kOrigin1_, "2"); ReportingEndpointGroupKey kGroupKey3(kNik_, kOrigin1_, "3"); ReportingEndpointGroupKey kGroupKey4(kNik_, kOrigin1_, "4"); ReportingEndpointGroupKey kGroupKey5(kNik_, kOrigin1_, "5"); std::vector<ReportingEndpoint::EndpointInfo> endpoints1_1 = {{MakeURL(10)}, {MakeURL(11)}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints2_1 = {{MakeURL(20)}, {MakeURL(21)}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints3_1 = {{MakeURL(30)}, {MakeURL(31)}}; std::string header1 = ConstructHeaderGroupString(MakeEndpointGroup("1", endpoints1_1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup("2", endpoints2_1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup("3", endpoints3_1)); ParseHeader(kNik_, kUrl1_, header1); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(3u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey1, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey2, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey3, OriginSubdomains::DEFAULT)); EXPECT_EQ(6u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(6, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(3, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey1, endpoints1_1[0].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey1, endpoints1_1[1].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey2, endpoints2_1[0].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey2, endpoints2_1[1].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey3, endpoints3_1[0].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey3, endpoints3_1[1].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey1); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey2); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey3); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Replace endpoints in each group with completely new endpoints. std::vector<ReportingEndpoint::EndpointInfo> endpoints1_2 = {{MakeURL(12)}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints2_2 = {{MakeURL(22)}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints3_2 = {{MakeURL(32)}}; std::string header2 = ConstructHeaderGroupString(MakeEndpointGroup("1", endpoints1_2)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup("2", endpoints2_2)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup("3", endpoints3_2)); ParseHeader(kNik_, kUrl1_, header2); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(3u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey1, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey2, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey3, OriginSubdomains::DEFAULT)); EXPECT_EQ(3u, cache()->GetEndpointCount()); EXPECT_TRUE(FindEndpointInCache(kGroupKey1, MakeURL(12))); EXPECT_FALSE(FindEndpointInCache(kGroupKey1, MakeURL(10))); EXPECT_FALSE(FindEndpointInCache(kGroupKey1, MakeURL(11))); EXPECT_TRUE(FindEndpointInCache(kGroupKey2, MakeURL(22))); EXPECT_FALSE(FindEndpointInCache(kGroupKey2, MakeURL(20))); EXPECT_FALSE(FindEndpointInCache(kGroupKey2, MakeURL(21))); EXPECT_TRUE(FindEndpointInCache(kGroupKey3, MakeURL(32))); EXPECT_FALSE(FindEndpointInCache(kGroupKey3, MakeURL(30))); EXPECT_FALSE(FindEndpointInCache(kGroupKey3, MakeURL(31))); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(6 + 3, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(3, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ( 6, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(0, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey1, endpoints1_2[0].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey2, endpoints2_2[0].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey3, endpoints3_2[0].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey1, endpoints1_1[0].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey1, endpoints1_1[1].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey2, endpoints2_1[0].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey2, endpoints2_1[1].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey3, endpoints3_1[0].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey3, endpoints3_1[1].url); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Replace all the groups with completely new groups. std::vector<ReportingEndpoint::EndpointInfo> endpoints4_3 = {{MakeURL(40)}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints5_3 = {{MakeURL(50)}}; std::string header3 = ConstructHeaderGroupString(MakeEndpointGroup("4", endpoints4_3)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup("5", endpoints5_3)); ParseHeader(kNik_, kUrl1_, header3); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey4, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey4, OriginSubdomains::DEFAULT)); EXPECT_FALSE( EndpointGroupExistsInCache(kGroupKey1, OriginSubdomains::DEFAULT)); EXPECT_FALSE( EndpointGroupExistsInCache(kGroupKey2, OriginSubdomains::DEFAULT)); EXPECT_FALSE( EndpointGroupExistsInCache(kGroupKey3, OriginSubdomains::DEFAULT)); EXPECT_EQ(2u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(6 + 3 + 2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(3 + 2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ(6 + 3, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(3, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey4, endpoints4_3[0].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey5, endpoints5_3[0].url); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey4); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey5); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey1, endpoints1_2[0].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey2, endpoints2_2[0].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey3, endpoints3_2[0].url); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey1); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey2); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey3); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, ZeroMaxAgeRemovesEndpointGroup) { // Without a pre-existing client, max_age: 0 should do nothing. ASSERT_EQ(0u, cache()->GetEndpointCount()); ParseHeader(kNik_, kUrl1_, "{\"endpoints\":[{\"url\":\"" + kEndpoint1_.spec() + "\"}],\"max_age\":0}"); EXPECT_EQ(0u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(0, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(0, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); } // Set a header with two endpoint groups. std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_}}; std::string header1 = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints2)); ParseHeader(kNik_, kUrl1_, header1); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT)); EXPECT_EQ(2u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey12_, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey12_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Set another header with max_age: 0 to delete one of the groups. std::string header2 = ConstructHeaderGroupString(MakeEndpointGroup( kGroup1_, endpoints1, OriginSubdomains::DEFAULT, base::TimeDelta::FromSeconds(0))) + ", " + ConstructHeaderGroupString(MakeEndpointGroup( kGroup2_, endpoints2)); // Other group stays. ParseHeader(kNik_, kUrl1_, header2); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); // Group was deleted. EXPECT_FALSE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); // Other group remains in the cache. EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ( 1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Set another header with max_age: 0 to delete the other group. (Should work // even if the endpoints field is an empty list.) std::string header3 = ConstructHeaderGroupString(MakeEndpointGroup( kGroup2_, std::vector<ReportingEndpoint::EndpointInfo>(), OriginSubdomains::DEFAULT, base::TimeDelta::FromSeconds(0))); ParseHeader(kNik_, kUrl1_, header3); // Deletion of the last remaining group also deletes the client for this // origin. EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(0u, cache()->GetEndpointGroupCountForTesting()); EXPECT_EQ(0u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ(1 + 1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(1 + 1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey12_, kEndpoint2_); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey12_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } // Invalid advertisements that parse as JSON should remove an endpoint group, // while those that don't are ignored. TEST_P(ReportingHeaderParserTest, InvalidAdvertisementRemovesEndpointGroup) { std::string invalid_non_json_header = "Goats should wear hats."; std::string invalid_json_header = "\"Goats should wear hats.\""; // Without a pre-existing client, neither invalid header does anything. ASSERT_EQ(0u, cache()->GetEndpointCount()); ParseHeader(kNik_, kUrl1_, invalid_non_json_header); EXPECT_EQ(0u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(0, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(0, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); } ASSERT_EQ(0u, cache()->GetEndpointCount()); ParseHeader(kNik_, kUrl1_, invalid_json_header); EXPECT_EQ(0u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(0, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(0, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); } // Set a header with two endpoint groups. std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}}; std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_}}; std::string header1 = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) + ", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints2)); ParseHeader(kNik_, kUrl1_, header1); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting()); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT)); EXPECT_EQ(2u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT, kGroupKey12_, kEndpoint2_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_); expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey12_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Set another header with max_age: 0 to delete one of the groups. std::string header2 = ConstructHeaderGroupString(MakeEndpointGroup( kGroup1_, endpoints1, OriginSubdomains::DEFAULT, base::TimeDelta::FromSeconds(0))) + ", " + ConstructHeaderGroupString(MakeEndpointGroup( kGroup2_, endpoints2)); // Other group stays. ParseHeader(kNik_, kUrl1_, header2); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting()); // Group was deleted. EXPECT_FALSE( EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT)); // Other group remains in the cache. EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ( 1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Invalid header values that are not JSON lists (without the outer brackets) // are ignored. ParseHeader(kNik_, kUrl1_, invalid_non_json_header); EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_TRUE( EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT)); EXPECT_EQ(1u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ( 1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey11_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } // Invalid headers that do parse as JSON should delete the corresponding // client. ParseHeader(kNik_, kUrl1_, invalid_json_header); // Deletion of the last remaining group also deletes the client for this // origin. EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin1_)); EXPECT_EQ(0u, cache()->GetEndpointGroupCountForTesting()); EXPECT_EQ(0u, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(2, mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT)); EXPECT_EQ(2, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ(1 + 1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(1 + 1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); MockPersistentReportingStore::CommandList expected_commands; expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT, kGroupKey12_, kEndpoint2_); expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, kGroupKey12_); EXPECT_THAT(mock_store()->GetAllCommands(), testing::IsSupersetOf(expected_commands)); } } TEST_P(ReportingHeaderParserTest, EvictEndpointsOverPerOriginLimit1) { // Set a header with too many endpoints, all in the same group. std::vector<ReportingEndpoint::EndpointInfo> endpoints; for (size_t i = 0; i < policy().max_endpoints_per_origin + 1; ++i) { endpoints.push_back({MakeURL(i)}); } std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, kUrl1_, header); // Endpoint count should be at most the limit. EXPECT_GE(policy().max_endpoints_per_origin, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(policy().max_endpoints_per_origin + 1, static_cast<unsigned long>(mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT))); EXPECT_EQ(1, mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP)); EXPECT_EQ( 1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); } } TEST_P(ReportingHeaderParserTest, EvictEndpointsOverPerOriginLimit2) { // Set a header with too many endpoints, in different groups. std::string header; for (size_t i = 0; i < policy().max_endpoints_per_origin + 1; ++i) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{MakeURL(i)}}; header = header + ConstructHeaderGroupString(MakeEndpointGroup( base::NumberToString(i), endpoints)); if (i != policy().max_endpoints_per_origin) header = header + ", "; } ParseHeader(kNik_, kUrl1_, header); // Endpoint count should be at most the limit. EXPECT_GE(policy().max_endpoints_per_origin, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(policy().max_endpoints_per_origin + 1, static_cast<unsigned long>(mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT))); EXPECT_EQ(policy().max_endpoints_per_origin + 1, static_cast<unsigned long>(mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP))); EXPECT_EQ( 1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); } } TEST_P(ReportingHeaderParserTest, EvictEndpointsOverGlobalLimit) { // Set headers from different origins up to the global limit. for (size_t i = 0; i < policy().max_endpoint_count; ++i) { std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{MakeURL(i)}}; std::string header = ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)); ParseHeader(kNik_, MakeURL(i), header); } EXPECT_EQ(policy().max_endpoint_count, cache()->GetEndpointCount()); // Parse one more header to trigger eviction. ParseHeader(kNik_, kUrl1_, "{\"endpoints\":[{\"url\":\"" + kEndpoint1_.spec() + "\"}],\"max_age\":1}"); // Endpoint count should be at most the limit. EXPECT_GE(policy().max_endpoint_count, cache()->GetEndpointCount()); if (mock_store()) { mock_store()->Flush(); EXPECT_EQ(policy().max_endpoint_count + 1, static_cast<unsigned long>(mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT))); EXPECT_EQ(policy().max_endpoint_count + 1, static_cast<unsigned long>(mock_store()->CountCommands( CommandType::ADD_REPORTING_ENDPOINT_GROUP))); EXPECT_EQ( 1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT)); EXPECT_EQ(1, mock_store()->CountCommands( CommandType::DELETE_REPORTING_ENDPOINT_GROUP)); } } INSTANTIATE_TEST_SUITE_P(ReportingHeaderParserStoreTest, ReportingHeaderParserTest, testing::Bool()); } // namespace } // namespace net
46.278266
80
0.693571
Mr-Sheep
70e036053ffc63c30da421d96d564d43b8de29da
3,693
cpp
C++
Applications/DataExplorer/DataView/FemConditionModel.cpp
MManicaM/ogs
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
[ "BSD-4-Clause" ]
null
null
null
Applications/DataExplorer/DataView/FemConditionModel.cpp
MManicaM/ogs
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
[ "BSD-4-Clause" ]
null
null
null
Applications/DataExplorer/DataView/FemConditionModel.cpp
MManicaM/ogs
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
[ "BSD-4-Clause" ]
null
null
null
/** * \file * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "FemConditionModel.h" #include "Applications/DataHolderLib/BoundaryCondition.h" #include "Applications/DataHolderLib/SourceTerm.h" #include "TreeItem.h" /** * Constructor. */ FemConditionModel::FemConditionModel(QObject* parent) : TreeModel(parent) { QList<QVariant> root_data; delete _rootItem; root_data << "Parameter" << "Value"; _rootItem = new TreeItem(root_data, nullptr); } void FemConditionModel::setFemCondition(DataHolderLib::FemCondition* cond) { beginResetModel(); this->clearView(); QList<QVariant> cond_data; cond_data << QString::fromStdString(cond->getConditionClassStr()) + ":" << QString::fromStdString(cond->getParamName()); TreeItem* cond_item = new TreeItem(cond_data, _rootItem); _rootItem->appendChild(cond_item); QList<QVariant> type_data; std::string type_str; if (cond->getConditionClassStr() == "Boundary Condition") type_str = DataHolderLib::BoundaryCondition::convertTypeToString( static_cast<DataHolderLib::BoundaryCondition*>(cond)->getType()); else if (cond->getConditionClassStr() == "Source Term") type_str = DataHolderLib::SourceTerm::convertTypeToString( static_cast<DataHolderLib::SourceTerm*>(cond)->getType()); type_data << "Type:" << QString::fromStdString(type_str); TreeItem* type_item = new TreeItem(type_data, cond_item); cond_item->appendChild(type_item); QString const obj_class_str = (cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH) ? "Mesh:" : "Geometry:"; QList<QVariant> obj_class_data; obj_class_data << "Set on " + obj_class_str << QString::fromStdString(cond->getBaseObjName()); TreeItem* obj_class_item = new TreeItem(obj_class_data, cond_item); cond_item->appendChild(obj_class_item); QString const obj_str = (cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH) ? "Mesh array:" : "Geo-Object:"; QString const name_str = (cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH) ? QString::fromStdString(cond->getParamName()) : QString::fromStdString(cond->getObjName()); QList<QVariant> obj_data; obj_data << obj_str << name_str; TreeItem* obj_item = new TreeItem(obj_data, cond_item); cond_item->appendChild(obj_item); endResetModel(); } void FemConditionModel::setProcessVariable(DataHolderLib::FemCondition* cond) { beginResetModel(); this->clearView(); DataHolderLib::ProcessVariable const& var(cond->getProcessVar()); QList<QVariant> pvar_data; pvar_data << "Process variable:" << QString::fromStdString(var.name); TreeItem* pvar_item = new TreeItem(pvar_data, _rootItem); _rootItem->appendChild(pvar_item); QList<QVariant> order_data; order_data << "Order:" << QString::number(var.order); TreeItem* order_item = new TreeItem(order_data, pvar_item); pvar_item->appendChild(order_item); QList<QVariant> comp_data; comp_data << "Number of components:" << QString::number(var.components); TreeItem* comp_item = new TreeItem(comp_data, pvar_item); pvar_item->appendChild(comp_item); endResetModel(); } void FemConditionModel::clearView() { beginResetModel(); _rootItem->removeChildren(0, _rootItem->childCount()); endResetModel(); }
33.572727
77
0.679664
MManicaM
70e1bebdcbd96978cdd7c021889ad9f3b7c189e4
1,723
hpp
C++
types/NullCoercibilityCheckMacro.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
types/NullCoercibilityCheckMacro.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
types/NullCoercibilityCheckMacro.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.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. **/ #ifndef QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_ #define QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_ #include "types/Type.hpp" #include "types/TypeID.hpp" /** \addtogroup Types * @{ */ /** * @brief A code-snippet for use in implementations of Type::isCoercibleFrom() * and Type::isSafelyCoercibleFrom() that does common checks for * nullability of types. **/ #define QUICKSTEP_NULL_COERCIBILITY_CHECK() \ do { \ if (original_type.isNullable() && !nullable_) { \ return false; \ } else if (original_type.getTypeID() == kNullType) { \ return true; \ } \ } while (false) /** @} */ #endif // QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_
36.659574
78
0.639582
Hacker0912
70e676213a71532c8ff231c8514ae5f76a826ac8
471
cpp
C++
tests/main.cpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
tests/main.cpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
tests/main.cpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
#define CATCH_CONFIG_RUNNER #include <catch2/catch.hpp> #include <Nazara/Audio/Audio.hpp> #include <Nazara/Core/Log.hpp> #include <Nazara/Core/AbstractLogger.hpp> #include <Nazara/Core/Modules.hpp> #include <Nazara/Network/Network.hpp> #include <Nazara/Physics2D/Physics2D.hpp> #include <Nazara/Utility/Utility.hpp> int main(int argc, char* argv[]) { Nz::Modules<Nz::Audio, Nz::Network, Nz::Physics2D, Nz::Utility> nazaza; return Catch::Session().run(argc, argv); }
26.166667
72
0.747346
NazaraEngine
70e6892f94a72a7c21bb275f99762fdedde036c3
589
cpp
C++
c-develop/pertemuan ke 6/ifBilTerbesar2.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
c-develop/pertemuan ke 6/ifBilTerbesar2.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
c-develop/pertemuan ke 6/ifBilTerbesar2.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
#include <iostream> //import input output using namespace std; //mengguanakan file fungsi std int main() //fungsi { double x, y; //deklarasi variable menggunakan tipe data double cout << "Masukkan x: "; //cetak ke layar monitor x cin >> x; //inputan kemudian di simpan di variable x cout << "Masukkan y: "; //cetak ke layar monitor Y cin >> y; ////cetak ke layar monitor Y if (x > y) { cout << "Bilangan terbesar adalah X" << "\n"; } else { cout << "Bilangan terbesar adalah Y" << "\n"; } return 0; }
32.722222
70
0.570458
GustiArsyad123