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
bd77be1ca2fd4290387eaaa6f82f3284d0d1e165
3,856
cc
C++
src/bin/copy-and-trim-int-vector.cc
Shuang777/kaldi-2016
5373fe4bd80857b53134db566cad48b8445cf3b9
[ "Apache-2.0" ]
null
null
null
src/bin/copy-and-trim-int-vector.cc
Shuang777/kaldi-2016
5373fe4bd80857b53134db566cad48b8445cf3b9
[ "Apache-2.0" ]
null
null
null
src/bin/copy-and-trim-int-vector.cc
Shuang777/kaldi-2016
5373fe4bd80857b53134db566cad48b8445cf3b9
[ "Apache-2.0" ]
null
null
null
// bin/copy-and-trim-int-vector.cc // Copyright 2016 Hang Su // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "matrix/kaldi-vector.h" #include "transform/transform-common.h" int main(int argc, char *argv[]) { try { using namespace kaldi; const char *usage = "Copy and trim vectors of integers, according to feature length \n" "(e.g. alignments)\n" "\n" "Usage: copy-and-trim-int-vector [options] <length-in-rspecifier> <length-out-rspecifier> <utt-map> <vector-in-rspecifier> <vector-out-wspecifier>\n" " e.g.: copy-and-trim-int-vector \"ark:feat-to-len feats1.scp\" \"ark:feat-to-len feats2.scp\" ark:utt_map \"ark:gunzip -c ali.*.gz |\" \"ark:|gzip -c > ali.trim.gz\" "; bool trim_front = false; ParseOptions po(usage); po.Register("trim-front", &trim_front, "Trim int vector from front"); po.Read(argc, argv); if (po.NumArgs() != 5) { po.PrintUsage(); exit(1); } std::string length_in_rspecifier = po.GetArg(1), length_out_rspecifier = po.GetArg(2), uttmap_rspecifier = po.GetArg(3), int32vector_rspecifier = po.GetArg(4), int32vector_wspecifier = po.GetArg(5); RandomAccessInt32Reader length_in_reader(length_in_rspecifier); RandomAccessInt32Reader length_out_reader(length_out_rspecifier); RandomAccessTokenReader uttmap_reader(uttmap_rspecifier); SequentialInt32VectorReader vector_reader(int32vector_rspecifier); Int32VectorWriter vector_writer(int32vector_wspecifier); int32 num_done = 0, num_err = 0; for (; !vector_reader.Done(); vector_reader.Next()) { std::string utt = vector_reader.Key(); if (!uttmap_reader.HasKey(utt)) { KALDI_WARN << "utterance " << utt << " not found in uttmap"; num_err++; continue; } if (!length_in_reader.HasKey(utt)) { KALDI_WARN << "utterance " << utt << " not found in length-in-rspecifier"; num_err++; continue; } std::string utt_out = uttmap_reader.Value(utt); std::vector<int32> vector_in = vector_reader.Value(); int32 length_in = length_in_reader.Value(utt); int32 length_out = length_out_reader.Value(utt_out); KALDI_ASSERT(length_in == vector_in.size()); if (length_out == length_in) { vector_writer.Write(utt_out, vector_in); } else if (length_out > length_in) { KALDI_ERR << "utterance " << utt << " length " << length_in << " smaller than utterance " << utt_out << " (out) length " << length_out; num_err++; continue; } else { int32 to_trim = length_in - length_out; if (trim_front) { vector_in.erase(vector_in.begin(), vector_in.begin() + to_trim); } else { vector_in.erase(vector_in.end() - to_trim, vector_in.end()); } vector_writer.Write(utt_out, vector_in); } num_done++; } KALDI_LOG << "Done " << num_done << " files, " << num_err << " with errors"; return (num_done != 0 ? 0 : 1); } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
34.428571
177
0.647822
Shuang777
bd7b938212717ab6beed501a09b3357878f69e54
22
cpp
C++
lib/StarAlign/starAlign.cpp
AndreiDiaconu97/tracket
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
[ "MIT" ]
null
null
null
lib/StarAlign/starAlign.cpp
AndreiDiaconu97/tracket
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
[ "MIT" ]
null
null
null
lib/StarAlign/starAlign.cpp
AndreiDiaconu97/tracket
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
[ "MIT" ]
null
null
null
#include "starAlign.h"
22
22
0.772727
AndreiDiaconu97
bd7bea2902cbfee312dbb6683c1099205b7704f3
3,194
cpp
C++
Engine/src/Components/collider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
1
2019-01-02T15:35:05.000Z
2019-01-02T15:35:05.000Z
Engine/src/Components/collider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
2
2018-11-11T21:29:05.000Z
2019-01-02T15:34:10.000Z
Engine/src/Components/collider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
null
null
null
#include "collider.h" namespace Ossium { REGISTER_COMPONENT(PhysicsBody); // Use OnLoadFinish() void PhysicsBody::OnLoadFinish() { ParentType::OnLoadFinish(); #ifndef OSSIUM_EDITOR // Update all attached collider shapes before building the body auto colliders = entity->GetComponents<Collider>(); for (auto collider : colliders) { collider->SetupShape(); } RebuildBody(); // TODO: update properties if body and fixture are already created. #endif // OSSIUM_EDITOR } void PhysicsBody::OnDestroy() { PhysicsBody::ParentType::OnDestroy(); if (body != nullptr) { Physics::PhysicsWorld* world = entity->GetService<Physics::PhysicsWorld>(); DEBUG_ASSERT(world != nullptr, "Physics world cannot be NULL"); // Body will cleanup any attached fixtures world->DestroyBody(body); body = nullptr; fixture = nullptr; } } void PhysicsBody::UpdatePhysics() { if (body != nullptr && bodyType != b2BodyType::b2_staticBody) { // Update location and rotation in-game. const b2Transform& b2t = body->GetTransform(); Transform* t = GetTransform(); t->SetLocalPosition(Vector2(MTP(b2t.p.x), MTP(b2t.p.y))); t->SetLocalRotation(Rotation(b2t.q)); } } void PhysicsBody::RebuildBody() { #ifndef OSSIUM_EDITOR Collider* collider = entity->GetComponent<Collider>(); if (collider == nullptr) { // Early out, no point. return; } Physics::PhysicsWorld* world = entity->GetService<Physics::PhysicsWorld>(); DEBUG_ASSERT(world != nullptr, "Physics world cannot be NULL"); if (body != nullptr) { world->DestroyBody(body); body = nullptr; fixture = nullptr; } // Define the body b2BodyDef bodyDef; bodyDef.position.Set(PTM(GetTransform()->GetWorldPosition().x), PTM(GetTransform()->GetWorldPosition().y)); bodyDef.angle = GetTransform()->GetWorldRotation().GetRadians(); bodyDef.type = bodyType; bodyDef.active = IsActiveAndEnabled(); bodyDef.awake = startAwake; bodyDef.allowSleep = allowSleep; bodyDef.angularDamping = angularDamping; bodyDef.angularVelocity = initialAngularVelocity; bodyDef.linearDamping = linearDamping; bodyDef.linearVelocity = initialLinearVelocity; bodyDef.bullet = bullet; bodyDef.fixedRotation = fixedRotation; bodyDef.gravityScale = gravityScale; // Create the body body = world->CreateBody(&bodyDef); // Define the fixture b2FixtureDef fixDef; fixDef.shape = &collider->GetShape(); fixDef.userData = (void*)collider; fixDef.density = density; fixDef.friction = friction; fixDef.isSensor = sensor; // Create the fixture fixture = body->CreateFixture(&fixDef); #endif // OSSIUM_EDITOR } REGISTER_ABSTRACT_COMPONENT(Collider); }
31.313725
115
0.599562
SpectralCascade
bd83c41cb6e725f59625eb34c8fce014d1f3f841
10,669
cpp
C++
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: ProgramGenerator.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "PLRenderer/Renderer/Renderer.h" #include "PLRenderer/Renderer/Program.h" #include "PLRenderer/Renderer/VertexShader.h" #include "PLRenderer/Renderer/FragmentShader.h" #include "PLRenderer/Renderer/ShaderLanguage.h" #include "PLRenderer/Renderer/ProgramGenerator.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; namespace PLRenderer { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ ProgramGenerator::ProgramGenerator(Renderer &cRenderer, const String &sShaderLanguage, const String &sVertexShader, const String &sVertexShaderProfile, const String &sFragmentShader, const String &sFragmentShaderProfile) : EventHandlerDirty(&ProgramGenerator::OnDirty, this), m_pRenderer(&cRenderer), m_sShaderLanguage(sShaderLanguage), m_sVertexShader(sVertexShader), m_sVertexShaderProfile(sVertexShaderProfile), m_sFragmentShader(sFragmentShader), m_sFragmentShaderProfile(sFragmentShaderProfile) { } /** * @brief * Destructor */ ProgramGenerator::~ProgramGenerator() { // Clear the cache of the program generator ClearCache(); } /** * @brief * Returns a program */ ProgramGenerator::GeneratedProgram *ProgramGenerator::GetProgram(const Flags &cFlags) { // Get the unique vertex shader and fragment shader ID's, we're taking the flags for this :D const uint32 nVertexShaderID = cFlags.GetVertexShaderFlags(); const uint32 nFragmentShaderID = cFlags.GetFragmentShaderFlags(); // Combine the two ID's into an unique 64 bit integer we can use to reference the linked program const uint64 nProgramID = nVertexShaderID + static_cast<uint64>(static_cast<uint64>(nFragmentShaderID)<<32); // Is there already a generated program with the requested flags? GeneratedProgram *pGeneratedProgram = m_mapPrograms.Get(nProgramID); if (!pGeneratedProgram) { // Is there already a vertex shader with the requested flags? VertexShader *pVertexShader = m_mapVertexShaders.Get(nVertexShaderID); if (!pVertexShader) { // Get the shader language to use ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage); if (pShaderLanguage) { // Create a new vertex shader instance pVertexShader = pShaderLanguage->CreateVertexShader(); if (pVertexShader) { String sSourceCode; // When using GLSL, the profile is the GLSL version to use - #version must occur before any other statement in the program! if (m_sShaderLanguage == "GLSL" && m_sVertexShaderProfile.GetLength()) sSourceCode += "#version " + m_sVertexShaderProfile + '\n'; // Add flag definitions to the shader source code const Array<const char *> &lstVertexShaderDefinitions = cFlags.GetVertexShaderDefinitions(); const uint32 nNumOfVertexShaderDefinitions = lstVertexShaderDefinitions.GetNumOfElements(); for (uint32 i=0; i<nNumOfVertexShaderDefinitions; i++) { // Get the flag definition const char *pszDefinition = lstVertexShaderDefinitions[i]; if (pszDefinition) { sSourceCode += "#define "; sSourceCode += pszDefinition; sSourceCode += '\n'; } } // Add the shader source code sSourceCode += m_sVertexShader; // Set the combined shader source code pVertexShader->SetSourceCode(sSourceCode, m_sVertexShaderProfile); // Add the created shader to the cache of the program generator m_lstVertexShaders.Add(pVertexShader); m_mapVertexShaders.Add(nVertexShaderID, pVertexShader); } } } // If we have no vertex shader, we don't need to continue constructing a program... if (pVertexShader) { // Is there already a fragment shader with the requested flags? FragmentShader *pFragmentShader = m_mapFragmentShaders.Get(nFragmentShaderID); if (!pFragmentShader) { // Get the shader language to use ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage); if (pShaderLanguage) { // Create a new fragment shader instance pFragmentShader = pShaderLanguage->CreateFragmentShader(); if (pFragmentShader) { String sSourceCode; // When using GLSL, the profile is the GLSL version to use - #version must occur before any other statement in the program! if (m_sShaderLanguage == "GLSL" && m_sFragmentShaderProfile.GetLength()) sSourceCode += "#version " + m_sFragmentShaderProfile + '\n'; // Add flag definitions to the shader source code const Array<const char *> &lstFragmentShaderDefinitions = cFlags.GetFragmentShaderDefinitions(); const uint32 nNumOfFragmentShaderDefinitions = lstFragmentShaderDefinitions.GetNumOfElements(); for (uint32 i=0; i<nNumOfFragmentShaderDefinitions; i++) { // Get the flag definition const char *pszDefinition = lstFragmentShaderDefinitions[i]; if (pszDefinition) { sSourceCode += "#define "; sSourceCode += pszDefinition; sSourceCode += '\n'; } } // Add the shader source code sSourceCode += m_sFragmentShader; // Set the combined shader source code pFragmentShader->SetSourceCode(sSourceCode, m_sFragmentShaderProfile); // Add the created shader to the cache of the program generator m_lstFragmentShaders.Add(pFragmentShader); m_mapFragmentShaders.Add(nFragmentShaderID, pFragmentShader); } } } // If we have no fragment shader, we don't need to continue constructing a program... if (pFragmentShader) { // Get the shader language to use ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage); if (pShaderLanguage) { // Create a program instance and assign the created vertex and fragment shaders to it Program *pProgram = pShaderLanguage->CreateProgram(pVertexShader, pFragmentShader); if (pProgram) { // Create a generated program contained pGeneratedProgram = new GeneratedProgram; pGeneratedProgram->pProgram = pProgram; pGeneratedProgram->nVertexShaderFlags = cFlags.GetVertexShaderFlags(); pGeneratedProgram->nFragmentShaderFlags = cFlags.GetFragmentShaderFlags(); pGeneratedProgram->pUserData = nullptr; // Add our nark which will inform us as soon as the program gets dirty pProgram->EventDirty.Connect(EventHandlerDirty); // Add the created program to the cache of the program generator m_lstPrograms.Add(pGeneratedProgram); m_mapPrograms.Add(nProgramID, pGeneratedProgram); } } } } } // Return the program return pGeneratedProgram; } /** * @brief * Clears the cache of the program generator */ void ProgramGenerator::ClearCache() { // Destroy all generated program instances for (uint32 i=0; i<m_lstPrograms.GetNumOfElements(); i++) { GeneratedProgram *pGeneratedProgram = m_lstPrograms[i]; delete pGeneratedProgram->pProgram; if (pGeneratedProgram->pUserData) delete pGeneratedProgram->pUserData; delete pGeneratedProgram; } m_lstPrograms.Clear(); m_mapPrograms.Clear(); // Destroy all generated fragment shader instances for (uint32 i=0; i<m_lstFragmentShaders.GetNumOfElements(); i++) delete m_lstFragmentShaders[i]; m_lstFragmentShaders.Clear(); m_mapFragmentShaders.Clear(); // Destroy all generated vertex shader instances for (uint32 i=0; i<m_lstVertexShaders.GetNumOfElements(); i++) delete m_lstVertexShaders[i]; m_lstVertexShaders.Clear(); m_mapVertexShaders.Clear(); } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Copy constructor */ ProgramGenerator::ProgramGenerator(const ProgramGenerator &cSource) : m_pRenderer(nullptr) { // No implementation because the copy constructor is never used } /** * @brief * Copy operator */ ProgramGenerator &ProgramGenerator::operator =(const ProgramGenerator &cSource) { // No implementation because the copy operator is never used return *this; } /** * @brief * Called when a program became dirty */ void ProgramGenerator::OnDirty(Program *pProgram) { // Search for the generated program and destroy the user data for (uint32 i=0; i<m_lstPrograms.GetNumOfElements(); i++) { GeneratedProgram *pGeneratedProgram = m_lstPrograms[i]; if (pGeneratedProgram->pProgram == pProgram) { // Is there user data we can destroy? if (pGeneratedProgram->pUserData) { delete pGeneratedProgram->pUserData; pGeneratedProgram->pUserData = nullptr; } // We're done, get us out of the loop i = m_lstPrograms.GetNumOfElements(); } } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLRenderer
37.566901
151
0.667823
ktotheoz
bd86280087c86bed9cc2a1f2459ef0297950c21d
1,350
hpp
C++
include/rua/callable.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
include/rua/callable.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
include/rua/callable.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
#ifndef _RUA_CALLABLE_HPP #define _RUA_CALLABLE_HPP #include "types/traits.hpp" #include <functional> #include <vector> namespace rua { template <typename Callable> inline std::function<callable_prototype_t<decay_t<Callable>>> wrap_callable(Callable &&c) { return std::forward<Callable>(c); } //////////////////////////////////////////////////////////////////////////// template <typename Ret, typename... Args> class _callchain_base : public std::vector<std::function<Ret(Args...)>> { public: _callchain_base() = default; }; template <typename Callback, typename = void> class callchain; template <typename Ret, typename... Args> class callchain< Ret(Args...), enable_if_t<!std::is_convertible<Ret, bool>::value>> : public _callchain_base<Ret, Args...> { public: callchain() = default; void operator()(Args &&... args) const { for (auto &cb : *this) { cb(std::forward<Args>(args)...); } } }; template <typename Ret, typename... Args> class callchain< Ret(Args...), enable_if_t<std::is_convertible<Ret, bool>::value>> : public _callchain_base<Ret, Args...> { public: callchain() = default; Ret operator()(Args &&... args) const { for (auto &cb : *this) { auto &&r = cb(std::forward<Args>(args)...); if (static_cast<bool>(r)) { return std::move(r); } } return Ret(); } }; } // namespace rua #endif
20.769231
76
0.634074
yulon
bd879321d9b78defa9f3b6b25da6f5c29af8a2fc
1,571
hpp
C++
TicTacToe/Score.hpp
djanko1337/TicTacToe
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
[ "MIT" ]
1
2018-02-14T18:00:52.000Z
2018-02-14T18:00:52.000Z
TicTacToe/Score.hpp
djanko1337/TicTacToe
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
[ "MIT" ]
null
null
null
TicTacToe/Score.hpp
djanko1337/TicTacToe
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
[ "MIT" ]
null
null
null
#pragma once namespace TicTacToe { class Score { public: constexpr Score() noexcept; constexpr auto count() const noexcept -> int; constexpr auto increment() noexcept -> void; constexpr auto reset() noexcept -> void; private: int mCount; }; constexpr auto operator==(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator!=(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator<(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator>(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator<=(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator>=(Score lhs, Score rhs) noexcept -> bool; constexpr Score::Score() noexcept : mCount(0) { } constexpr auto Score::count() const noexcept -> int { return mCount; } constexpr auto Score::increment() noexcept -> void { ++mCount; } constexpr auto Score::reset() noexcept -> void { mCount = 0; } constexpr auto operator==(Score lhs, Score rhs) noexcept -> bool { return lhs.count() == rhs.count(); } constexpr auto operator!=(Score lhs, Score rhs) noexcept -> bool { return !(lhs == rhs); } constexpr auto operator<(Score lhs, Score rhs) noexcept -> bool { return lhs.count() < rhs.count(); } constexpr auto operator>(Score lhs, Score rhs) noexcept -> bool { return lhs.count() > rhs.count(); } constexpr auto operator<=(Score lhs, Score rhs) noexcept -> bool { return !(lhs > rhs); } constexpr auto operator>=(Score lhs, Score rhs) noexcept -> bool { return !(lhs < rhs); } } // namespace TicTacToe
19.158537
65
0.674729
djanko1337
bd8c50deb2428e76a91e1731ad9a8523613d76dd
1,060
hpp
C++
libs/core/include/fcppt/enum/output.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/enum/output.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/enum/output.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // 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 FCPPT_ENUM_OUTPUT_HPP_INCLUDED #define FCPPT_ENUM_OUTPUT_HPP_INCLUDED #include <fcppt/enum/to_string.hpp> #include <fcppt/io/ostream.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace enum_ { /** \brief Outputs an enum value to a stream. \ingroup fcpptenum Uses #fcppt::enum_::to_string to output \a _value to \a _stream. This function is useful to implement <code>operator<<</code> for an enum type. \tparam Enum Must be an enum type \return \a _stream */ template< typename Enum > fcppt::io::ostream & output( fcppt::io::ostream &_stream, Enum const _value ) { static_assert( std::is_enum< Enum >::value, "Enum must be an enum type" ); return _stream << fcppt::enum_::to_string( _value ); } } } #endif
17.096774
78
0.711321
pmiddend
bd8cd24fba3ddb9a267618809b3a6ad818b1339b
945
hpp
C++
src/include/XEEditor/Editor.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
11
2017-01-17T15:02:25.000Z
2020-11-27T16:54:42.000Z
src/include/XEEditor/Editor.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
9
2016-10-23T20:15:38.000Z
2018-02-06T11:23:17.000Z
src/include/XEEditor/Editor.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
2
2019-08-29T10:23:51.000Z
2020-04-03T06:08:34.000Z
#ifndef EDITOR_HPP #define EDITOR_HPP #include <XEngine.hpp> #include <XEEditor/Event/Event.h> namespace EI { class EditorCommand; enum ObjType { Physic = 0, GameEntity = 1, }; enum Status { Unknown = 0, OK = 1, Error = 2, }; class Editor { public: Editor(); inline XE::XEngine* getEngine() { return m_engine; } void* InitState(const char* stateName, int width, int height); unsigned char* consoleCmd(const char* command, unsigned char* data, int len); bool moveToState(const char* stateName); void renderTargetSize(const char* rtName, Ogre::Real x, Ogre::Real y); // void test(sf::String str, std::function<void()> fkttest); int pushEvent(const sfEvent& event); private : // std::unordered_map<std::string, std::function<void(std::string)>> command_map; XE::XEngine* m_engine; //todo #################### XE::OgreConsole* m_console; EditorCommand* mEditorCommand; }; } #endif //EDITOR_HPP
20.106383
82
0.674074
devxkh
bd8f12d6d2ef16317d360b1060caa92b0319eacb
373
cpp
C++
src/learn/test_bitset.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
src/learn/test_bitset.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
src/learn/test_bitset.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
#include "stdafx.h" #include "test_bitset.h" void test_bitset() { std::bitset<32> bt32; bt32.set(); assert(bt32.all()); bt32.reset(); assert(bt32.none()); bt32.set(0); assert(bt32.any()); assert(bt32.size() == 32); bt32.flip(); assert(bt32.count() == 31); bt32 <<= 15; std::cout << bt32.to_string('X', 'O') << std::endl; }
18.65
55
0.544236
wohaaitinciu
bd93b99635fd75bddeaaea5d7980b57d005a85c0
21,349
cc
C++
src/tpl/vx_str.cc
eedsp/tlx
2555853646920168570bd630850dc22bc2cb327d
[ "Apache-2.0" ]
null
null
null
src/tpl/vx_str.cc
eedsp/tlx
2555853646920168570bd630850dc22bc2cb327d
[ "Apache-2.0" ]
null
null
null
src/tpl/vx_str.cc
eedsp/tlx
2555853646920168570bd630850dc22bc2cb327d
[ "Apache-2.0" ]
null
null
null
// // Created by Shiwon Cho on 2005.10.27. // #include <iostream> #include "vx_str.h" #define UPDATE_UCS_offset(p_offset_utf8, p_offset_utf8_s, pSTR, pSTR_len, p_offset_ucs) { \ int32_t __v_idx_utf8 = p_offset_utf8; \ while (__v_idx_utf8 < p_offset_utf8_s && __v_idx_utf8 < pSTR_len) \ { \ UChar32 __c = 0; \ U8_NEXT (pSTR, __v_idx_utf8, pSTR_len, __c); \ p_offset_ucs++; \ } \ } #define UPDATE_UCS_len(pSTR, pSTR_len, p_len_ucs) { \ int32_t __v_idx_utf8 = 0; \ while (__v_idx_utf8 < pSTR_len) \ { \ UChar32 __c = 0; \ U8_NEXT (pSTR, __v_idx_utf8, pSTR_len, __c); \ p_len_ucs++; \ } \ } static const char *_TPL_DEFAULT_TAG = "_PHRASE_"; vx_str::vx_str (apr_pool_t *p_pool, const hx_shm_rec_t *p_shm_t) { v_pool = nullptr; vSTR = nullptr; vSTR_len = 0; v_number_of_codes = 0; v_list_of_codes = nullptr; v_ctx_general = nullptr; v_error_code = v_error_offset = 0; v_name_count = nullptr; v_name_entry_size = nullptr; v_name_table = nullptr; v_name_entry_max_size = 0; v_match_context = nullptr; v_jit_stack = nullptr; v_match_data = nullptr; v_out_vector = nullptr; v_token_list = nullptr; v_status = APR_SUCCESS; v_status = apr_pool_create (&v_pool, p_pool); is_attached = false; vDB = p_shm_t; if (vDB && vDB->v_ptr) { is_attached = true; } } vx_str::~vx_str () { vSTR_len = 0; if (v_token_list) { vtx_delete (v_token_list); } if (v_status == APR_SUCCESS && v_pool) { apr_pool_destroy(v_pool); v_pool = NULL; } } void *vx_str::ctx_malloc (PCRE2_SIZE pSIZE, void *pFUNC) { #if defined(USE_TCMALLOC) void *block = (void *)tc_malloc ((size_t)pSIZE); #elif defined(USE_JEMALLOC) void *block = (void *) je_malloc((size_t) pSIZE); #else void *block = (void *)malloc ((size_t)pSIZE); #endif (void) pFUNC; return block; } void vx_str::ctx_free (void *pBLOCK, void *pFUNC) { (void) pFUNC; #if defined(USE_TCMALLOC) tc_free ((void *)pBLOCK); #elif defined(USE_JEMALLOC) je_free((void *) pBLOCK); #else free ((void *)pBLOCK); #endif } void vx_str::context_create () { if (!vDB || !is_attached) { return; } if (!vDB->v_ptr) { return; } v_number_of_codes = pcre2_serialize_get_number_of_codes ((const uint8_t *)vDB->v_ptr); if (v_number_of_codes > 0) { v_ctx_general = pcre2_general_context_create(ctx_malloc, ctx_free, NULL); v_list_of_codes = (pcre2_code **) apr_palloc(v_pool, sizeof(pcre2_code *) * v_number_of_codes); v_name_count = (int32_t *) apr_palloc(v_pool, sizeof(int32_t) * v_number_of_codes); v_name_table = (PCRE2_SPTR *) apr_palloc(v_pool, sizeof(PCRE2_SPTR) * v_number_of_codes); v_name_entry_size = (int32_t *) apr_palloc(v_pool, sizeof(int32_t) * v_number_of_codes); v_match_context = (pcre2_match_context **) apr_palloc(v_pool, sizeof(pcre2_match_context *) * v_number_of_codes); v_jit_stack = (pcre2_jit_stack **) apr_palloc(v_pool, sizeof(pcre2_jit_stack *) * v_number_of_codes); v_match_data = (pcre2_match_data **) apr_palloc(v_pool, sizeof(pcre2_match_data *) * v_number_of_codes); v_out_vector = (PCRE2_SIZE **) apr_palloc(v_pool, sizeof(PCRE2_SIZE *) * v_number_of_codes); pcre2_serialize_decode(v_list_of_codes, v_number_of_codes, (const uint8_t *)vDB->v_ptr, v_ctx_general); for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++) { pcre2_code *v_re = v_list_of_codes[v_idx_code]; pcre2_jit_compile(v_re, PCRE2_JIT_COMPLETE); (void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMECOUNT, &v_name_count[v_idx_code]); (void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMETABLE, &v_name_table[v_idx_code]); (void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMEENTRYSIZE, &v_name_entry_size[v_idx_code]); if (v_name_entry_max_size < v_name_entry_size[v_idx_code]) { v_name_entry_max_size = v_name_entry_size[v_idx_code]; } v_match_context[v_idx_code] = pcre2_match_context_create(NULL); pcre2_set_match_limit (v_match_context[v_idx_code], -1); pcre2_set_recursion_limit (v_match_context[v_idx_code], 1); v_jit_stack[v_idx_code] = pcre2_jit_stack_create(32 * 1024, 512 * 1024, NULL); pcre2_jit_stack_assign(v_match_context[v_idx_code], NULL, v_jit_stack[v_idx_code]); v_match_data[v_idx_code] = pcre2_match_data_create_from_pattern(v_re, NULL); v_out_vector[v_idx_code] = pcre2_get_ovector_pointer(v_match_data[v_idx_code]); } #if 0 re = pcre2_compile( (PCRE2_SPTR) pPATTERN, /* the pattern */ (PCRE2_SIZE) PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */ PCRE2_UCP | PCRE2_UTF | PCRE2_DUPNAMES | PCRE2_CASELESS | PCRE2_ALLOW_EMPTY_CLASS, /* Option bits */ &v_error_code, /* for error code */ &v_error_offset, /* for error offset */ v_ctx_compile); /* use default compile context */ if (re != NULL) { pcre2_jit_compile(re, PCRE2_JIT_COMPLETE); (void) pcre2_pattern_info(re, PCRE2_INFO_NAMECOUNT, &v_name_count); (void) pcre2_pattern_info(re, PCRE2_INFO_NAMETABLE, &v_name_table); (void) pcre2_pattern_info(re, PCRE2_INFO_NAMEENTRYSIZE, &v_name_entry_size); } else { PCRE2_UCHAR8 vBUF[512]; (void) pcre2_get_error_message(v_error_code, vBUF, 512); std::cout << _INFO (v_pool) << __func__ << ":" << vBUF << std::endl << std::flush; } #endif } } void vx_str::context_free () { for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++) { pcre2_code *v_re = v_list_of_codes[v_idx_code]; pcre2_code_free (v_re); pcre2_match_data_free(v_match_data[v_idx_code]); /* Release memory used for the match */ pcre2_match_context_free(v_match_context[v_idx_code]); pcre2_jit_stack_free(v_jit_stack[v_idx_code]); } if (v_ctx_general) { pcre2_general_context_free(v_ctx_general); } } #if 0 void vx_str::read (const char *pSTR, int32_t pSTR_len) { uSTR.remove(); uSTR_len = 0; apr_pool_clear(v_pool_token); vSTR = NULL; vSTR_len = 0; uSTR = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len)); uSTR_len = uSTR.length(); std::string szUTF8_tmp(""); uSTR.toLower().toUTF8String(szUTF8_tmp); vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str()); vSTR_len = (int32_t) szUTF8_tmp.length(); szUTF8_tmp.clear(); } void vx_str::Text_normalize (const char *pSTR, int32_t pSTR_len, bool toLower) { UErrorCode status = U_ZERO_ERROR; uSTR.remove(); uSTR_len = 0; apr_pool_clear(v_pool_token); vSTR = NULL; vSTR_len = 0; const Normalizer2 &nNFC = *Normalizer2::getNFCInstance(status); if (U_SUCCESS(status)) { UnicodeString uSTR_tmp = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len)); status = U_ZERO_ERROR; uSTR = nNFC.normalize((toLower) ? uSTR_tmp.toLower() : uSTR_tmp, status); if (U_SUCCESS(status)) { std::string szUTF8_tmp(""); uSTR.toUTF8String(szUTF8_tmp); uSTR_len = uSTR.length(); vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str()); vSTR_len = (int32_t) szUTF8_tmp.length(); szUTF8_tmp.clear(); } } } void vx_str::normalize (const char *pSTR, int32_t pSTR_len) { if (U_SUCCESS(v_error_code_normlzer)) { uSTR.remove(); uSTR_len = 0; apr_pool_clear(v_pool_token); vSTR = NULL; vSTR_len = 0; UnicodeString uSTR_raw = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len)); UErrorCode status = U_ZERO_ERROR; uSTR = v_NFC->normalize((opt_toLowerCase) ? uSTR_raw.toLower() : uSTR_raw, status); if (U_SUCCESS(status)) { std::string szUTF8_tmp(""); uSTR.toUTF8String(szUTF8_tmp); uSTR_len = uSTR.length(); vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str()); vSTR_len = (int32_t) szUTF8_tmp.length(); szUTF8_tmp.clear(); } } } #endif PCRE2_SPTR vx_str::proc_token_tag (int32_t p_idx_code, int32_t p_offset_utf8, int32_t p_len_utf8, const PCRE2_SIZE *p_vector) { PCRE2_SPTR v_name = nullptr; PCRE2_SPTR p_table = v_name_table[p_idx_code]; int32_t n = 0; int32_t v_offset_utf8_s = 0; // 2 * n int32_t v_offset_utf8_e = 0; // 2 * n + 1 int32_t v_len_utf8 = 0; for (int32_t vIDX = 0; !v_name && vIDX < v_name_count[p_idx_code]; vIDX+=2) { if (!v_name && vIDX < v_name_count[p_idx_code]) { n = (p_table[0] << 8) | p_table[1]; v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1 v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s); if (v_offset_utf8_s == p_offset_utf8 && (v_len_utf8 > 0 && v_len_utf8 == p_len_utf8)) { v_name = (PCRE2_SPTR) p_table + 2; break; } p_table += v_name_entry_size[p_idx_code]; } if (!v_name && (vIDX + 1) < v_name_count[p_idx_code]) { n = (p_table[0] << 8) | p_table[1]; v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1 v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s); if (v_offset_utf8_s == p_offset_utf8 && (v_len_utf8 > 0 && v_len_utf8 == p_len_utf8)) { v_name = (PCRE2_SPTR) p_table + 2; break; } p_table += v_name_entry_size[p_idx_code]; } } return v_name; } #if 0 PCRE2_SPTR vx_str::proc_token_tag_all (int32_t p_idx_token, int32_t p_idx_code, int32_t p_offset_utf8, int32_t p_len_utf8, int32_t p_offset_ucs_s, const PCRE2_SIZE *p_vector) { PCRE2_SPTR v_name = NULL; PCRE2_SPTR p_name = v_name_table[p_idx_code]; // int32_t v_offset_utf8 = p_offset_utf8; // int32_t v_offset_ucs = p_offset_ucs_s; int32_t vFLAG = 1; for (int32_t vIDX = 0; vFLAG && vIDX < v_name_count[p_idx_code]; vIDX++) { int32_t n = (p_name[0] << 8) | p_name[1]; int32_t v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n int32_t v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1 int32_t v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s); if (v_len_utf8 > 0) { if ( v_name == NULL && (v_offset_utf8_s == p_offset_utf8 && v_len_utf8 == p_len_utf8) ) { v_name = (PCRE2_SPTR) p_name + 2; vFLAG = 0; break; } int32_t v_offset_utf8 = p_offset_utf8; int32_t v_offset_ucs = p_offset_ucs_s; PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s; UPDATE_UCS_offset (v_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs); // update UCS offset int32_t v_len_ucs = 0; UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length // std::cout << apr_psprintf (v_pool, " (%d)", n); // std::cout << apr_psprintf (v_pool, "[%2d/%d]", vIDX + 1, v_name_count); std::cout << apr_psprintf(v_pool, "%6d %5d(%3d) %5d(%3d)", p_idx_token, (int32_t) v_offset_ucs, (int32_t) v_len_ucs, (int32_t) v_offset_utf8_s, (int32_t) v_len_utf8 ); std::cout << apr_psprintf(v_pool, " [%*s]", v_name_entry_max_size - 3, (char *) (p_name + 2)); std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) v_len_utf8, v_ptr); std::cout << std::endl; } p_name += v_name_entry_size[p_idx_code]; } return v_name; } #endif void vx_str::tokenize (const char *pSTR, size_t pSTR_len) { if (!v_ctx_general || !v_number_of_codes) { return; } int32_t v_idx_token = 0; int32_t v_offset_utf8 = 0; int32_t v_offset_ucs = 0; int32_t v_offset_ucs_prev = -1; int32_t v_idx_sgmt = 0; int32_t v_idx_elt = 0; int32_t vFLAG = 1; vSTR = pSTR; vSTR_len = pSTR_len; if (v_token_list) { vtx_clear(v_token_list); } else { v_token_list = vtx_create(v_pool); } int32_t vIDX_code = v_number_of_codes - 1; pcre2_code *v_re = v_list_of_codes[vIDX_code]; for (; vFLAG && v_offset_utf8 < (int32_t)vSTR_len;) { uint32_t v_options = 0; /* Normally no options */ int32_t rc = pcre2_jit_match( v_re, /* the compiled pattern */ (PCRE2_SPTR) vSTR, /* the subject string */ (size_t) vSTR_len, /* the length of the subject */ (size_t) v_offset_utf8, /* start at offset 0 in the subject */ v_options, /* default options */ v_match_data[vIDX_code], /* block for storing the result */ v_match_context[vIDX_code]); /* use default match context */ if (rc == PCRE2_ERROR_NOMATCH) { vFLAG = 0; break; } else if (rc > 0) { int32_t v_offset_utf8_s = (int32_t) v_out_vector[vIDX_code][0]; // 2 * vIDX int32_t v_offset_utf8_e = (int32_t) v_out_vector[vIDX_code][1]; // 2 * vIDX + 1 int32_t v_len_utf8 = v_offset_utf8_e - v_offset_utf8_s; if (v_offset_utf8_e > 0 && v_len_utf8 > 0) { PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s; int32_t v_offset_ucs_s = v_offset_ucs; int32_t v_len_ucs = 0; UPDATE_UCS_offset (v_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs_s); // update UCS offset v_offset_ucs = v_offset_ucs_s; v_offset_utf8 = v_offset_utf8_e; UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length v_offset_ucs += v_len_ucs; PCRE2_SPTR v_name = proc_token_tag(vIDX_code, v_offset_utf8_s, v_len_utf8, (const PCRE2_SIZE *) v_out_vector[vIDX_code]); if (v_offset_ucs_prev != -1 && v_offset_ucs_prev != v_offset_ucs_s) { v_idx_sgmt++; v_idx_elt = 0; } #if 0 std::cout << apr_psprintf(v_pool, "%6d [%6d] <%5d>%5d(%3d) %5d(%3d)", v_idx_sgmt, v_idx_token, v_offset_ucs_prev, (int32_t) v_offset_ucs_s, (int32_t) v_len_ucs, (int32_t) v_offset_utf8_s, (int32_t) v_len_utf8 ); std::cout << apr_psprintf(v_pool, " [%*s]", v_name_entry_max_size - 3, (v_name == NULL) ? (char *) _TPL_DEFAULT_TAG : (char *) v_name); std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) v_len_utf8, (char *) v_ptr); std::cout << std::endl; #endif vtx_push_back (v_token_list, v_idx_token, v_idx_sgmt, v_idx_elt, (const char *) v_ptr, v_len_utf8, v_offset_ucs_s, v_len_ucs, v_offset_utf8_s, v_len_utf8, (v_name == NULL) ? _TPL_DEFAULT_TAG : (const char *) v_name); v_offset_ucs_prev = v_offset_ucs; v_idx_token++; v_idx_elt++; } // if v_offset_utf8_e > 0 } // if else else { std::cout << ">>> " << __LINE__ << ":" << v_offset_utf8 << ":" << rc << std::endl; vFLAG = 0; break; } } // for } void vx_str::print () { if (v_token_list) { vtx_print(v_token_list); } } const char * vx_str::dumps_text () { const char *v_buffer = nullptr; if (vDB && is_attached && v_token_list) { v_buffer = vtx_text_print(v_token_list); } return v_buffer; } const char * vx_str::dumps_json () { const char *v_buffer = nullptr; if (vDB && is_attached && v_token_list) { v_buffer = vtx_json_print(v_token_list); } return v_buffer; } #if 0 void vx_str::tokenize_2 () { int32_t v_offset_utf8 = 0; int32_t v_offset_ucs = 0; int32_t vFLAG = 1; int32_t vIDX_ = v_number_of_codes - 1; int32_t *flag_code = new int32_t[vIDX_]; for (int32_t vIDX = 0; vIDX < vIDX_; vIDX++) { flag_code[vIDX] = 1; } while (vFLAG && v_offset_utf8 < vSTR_len) { // std::cout << _INFO (v_pool) << apr_psprintf(v_pool, "%4d/%d", v_offset_utf8, vSTR_len) << std::endl << std::flush; int32_t v_offset_last_utf8 = vSTR_len; int32_t l_idx = -1; int32_t l_offset_ucs_s = 0; int32_t l_offset_utf8_s = 0; int32_t l_len_ucs = 0; int32_t l_len_utf8 = 0; for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++) { if (flag_code[v_idx_code] == 0) { continue; } pcre2_code *v_re = v_list_of_codes[v_idx_code]; int32_t t_offset_utf8 = v_offset_utf8; uint32_t v_options = 0; /* Normally no options */ int32_t rc = pcre2_jit_match( v_re, /* the compiled pattern */ (PCRE2_SPTR) vSTR, /* the subject string */ (size_t) vSTR_len, /* the length of the subject */ (size_t) t_offset_utf8, /* start at offset 0 in the subject */ v_options, /* default options */ v_match_data[v_idx_code], /* block for storing the result */ v_match_context[v_idx_code]); /* use default match context */ if (rc == PCRE2_ERROR_NOMATCH) { flag_code[v_idx_code] = 0; continue; } else if (rc > 0) { int32_t v_offset_utf8_s = (int32_t) v_out_vector[v_idx_code][0]; // 2 * vIDX int32_t v_offset_utf8_e = (int32_t) v_out_vector[v_idx_code][1]; // 2 * vIDX + 1 int32_t v_len_utf8 = v_offset_utf8_e - v_offset_utf8_s; if (v_offset_utf8_e > 0 && v_len_utf8 > 0) { PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s; int32_t v_offset_ucs_s = v_offset_ucs; int32_t v_len_ucs = 0; UPDATE_UCS_offset (t_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs_s); // update UCS offset UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length if (t_offset_utf8 < v_offset_last_utf8) { l_idx = v_idx_code; v_offset_last_utf8 = v_offset_utf8_s; l_offset_utf8_s = v_offset_utf8_s; l_offset_ucs_s = v_offset_ucs_s; l_len_utf8 = v_len_utf8; l_len_ucs = v_len_ucs; //std::cout << _INFO (v_pool) << apr_psprintf(v_pool, "%4d/%d", v_offset_utf8_s, vSTR_len) << std::endl << std::flush; } } // if v_offset_utf8_e > 0 } // if else } // for v_offset_utf8 = l_offset_utf8_s + l_len_utf8; v_offset_ucs = l_offset_ucs_s + l_len_ucs; if (l_idx >= 0) { PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + l_offset_utf8_s; PCRE2_SPTR v_name = proc_token_tag(l_idx, l_offset_utf8_s, l_len_utf8, l_offset_ucs_s, (const PCRE2_SIZE *) v_out_vector[l_idx]); if (v_name == NULL) { std::cout << apr_psprintf(v_pool, "%5d(%3d) %5d(%3d)", (int32_t) l_offset_ucs_s, (int32_t) l_len_ucs, (int32_t) l_offset_utf8_s, (int32_t) l_len_utf8 ); std::cout << apr_psprintf(v_pool, " (%*s)", v_name_entry_max_size - 3, (v_name == NULL) ? (char *) "_PHRASE" : (char *) v_name); std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) l_len_utf8, (char *) v_ptr); std::cout << std::endl; } } else{ vFLAG = 0; break; } } // while delete flag_code; } #endif
33.357813
174
0.569582
eedsp
bd97711b92e2f01bc90806429d49e045296546de
961
hpp
C++
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
#if !defined CONFIGURATION_PARAMETER_TEMPLATE_BASE_TEST_HPP #define CONFIGURATION_PARAMETER_TEMPLATE_BASE_TEST_HPP #include "Test.hpp" #include "TestCases.hpp" #include "TestMacros.hpp" #include "ConfigurationParameterTemplateBase.hpp" namespace Configuration { TEST_CASES_BEGIN(ParameterTemplateBase_test) TEST_CASES_BEGIN(SetValue) TEST(Bool) TEST(String) TEST(Char) TEST(Double) TEST(Float) TEST(Int) TEST(Long) TEST(LongDouble) TEST(LongLong) TEST(Short) TEST(UnsignedChar) TEST(UnsignedInt) TEST(UnsignedLong) TEST(UnsignedLongLong) TEST(UnsignedShort) template <class T> static Test::Result test(const T& initial_value, const T& set_value); TEST_CASES_END(SetValue) TEST_CASES_END(ParameterTemplateBase_test) } #endif
23.439024
81
0.630593
leighgarbs
bd98395a457e90264d2f4dca55fd2dea7fdec95d
133
cc
C++
gcc/libjava/include/jrate/sched/Runnable.cc
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
1
2021-06-15T05:43:22.000Z
2021-06-15T05:43:22.000Z
src/native/src/jrate/sched/Runnable.cc
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
null
null
null
src/native/src/jrate/sched/Runnable.cc
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
null
null
null
#include <jrate/sched/Runnable.h> jrate::sched::Runnable jrate::sched::Runnable::NoAction; jrate::sched::Runnable::~Runnable() { }
22.166667
56
0.721805
giraffe
bd9aa5fcefffa258da01289c607f52f9f3d35378
211
cpp
C++
DeSpeect/Test/View_idTest.cpp
matteo-rizzo/DeSpeect
843b74f00016538fd4a6a0ec9641a72f000998a2
[ "MIT" ]
null
null
null
DeSpeect/Test/View_idTest.cpp
matteo-rizzo/DeSpeect
843b74f00016538fd4a6a0ec9641a72f000998a2
[ "MIT" ]
null
null
null
DeSpeect/Test/View_idTest.cpp
matteo-rizzo/DeSpeect
843b74f00016538fd4a6a0ec9641a72f000998a2
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "id.h" TEST(Graph, VerifyId){ ID a("a","a"); ID b("b","b"); EXPECT_FALSE(a==b); } TEST(Graph, VerifyIdEq){ ID a("a","a"); ID b=a; EXPECT_TRUE(a==b); }
14.066667
24
0.521327
matteo-rizzo
bd9d4dc9dfce443023372e920c45c77eed31b9ad
1,743
cc
C++
vize/src/vize/factory/async_volume_document_factory.cc
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
47
2020-03-30T14:36:46.000Z
2022-03-06T07:44:54.000Z
vize/src/vize/factory/async_volume_document_factory.cc
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
null
null
null
vize/src/vize/factory/async_volume_document_factory.cc
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
8
2020-04-01T01:22:45.000Z
2022-01-02T13:06:09.000Z
#include "vize/factory/async_volume_document_factory.hpp" #include "vize/factory/volume_factory.hpp" #include "vize/document/volume_document.hpp" namespace vize { AsyncVolumeDocumentFactory::AsyncVolumeDocumentFactory(VolumeDocument& document, std::unique_ptr<VolumeFactory> factory) : _document(document), _volumeFactory(std::move(factory)) { _volumeFactory.connectToVolumeBuiltSignal(std::bind(&AsyncVolumeDocumentFactory::_volumeBuilt, this, std::placeholders::_1, std::placeholders::_2)); } AsyncVolumeDocumentFactory::~AsyncVolumeDocumentFactory() = default; void AsyncVolumeDocumentFactory::run() { _volumeFactory.run(); } bool AsyncVolumeDocumentFactory::isRunning() const { return _volumeFactory.isRunning(); } void AsyncVolumeDocumentFactory::showProgressDialog(const std::string& progressDialogTitle) { _volumeFactory.showProgressDialog(progressDialogTitle); } void AsyncVolumeDocumentFactory::addVolumeImagesDirectory(const std::string& imagesDirectory) { _volumeFactory.addVolumeImagesDirectory(imagesDirectory); } void AsyncVolumeDocumentFactory::addVolumeImage(const std::string& imageFile) { _volumeFactory.addVolumeImage(imageFile); } void AsyncVolumeDocumentFactory::clearVolumeImages() { _volumeFactory.clearVolumeImages(); } void AsyncVolumeDocumentFactory::_volumeBuilt(const std::shared_ptr<Volume>& volume, const std::string& volumeName) { if (volume) { _document.setDocumentName(volumeName); _document.setVolume(volume); _documentBuilt(_document, *volume); } else { AYLA_DEBUG_MESSAGE("Unable to create volume."); } } boost::signals2::connection AsyncVolumeDocumentFactory::connectToDocumentBuiltSignal(DocumentBuiltSignalListener listener) { return _documentBuilt.connect(listener); } }
32.277778
149
0.815835
oprogramadorreal
bd9ec24d3dab1b3d9fab7650571cb40639a1c1ec
61,331
cpp
C++
src/NLO_PL.cpp
gvita/RHEHpt
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
[ "MIT" ]
null
null
null
src/NLO_PL.cpp
gvita/RHEHpt
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
[ "MIT" ]
null
null
null
src/NLO_PL.cpp
gvita/RHEHpt
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
[ "MIT" ]
null
null
null
#include "NLO_PL.h" #include "cuba.h" #include <gsl/gsl_sf_dilog.h> /*double B2pp_ANALITIC(long double x, long double xp) { return(1./3.*3.*5.*(2.+3.*xp)/(xp*(1.+xp))*std::log(x)); }*/ //Used to cross-check the complete form above long double B2pp_ANALITICS(long double x, long double xp){ long double ymax=0.5*std::log((1.+std::sqrt(1.-4.*x*(1.+xp)/std::pow(1.+x,2)))/(1.-std::sqrt(1.-4.*x*(1.+xp)/std::pow(1.+x,2)))); long double wmax=std::exp(ymax); long double R1=1./12.*x*xp*(1./std::sqrt(x)*(1./wmax*(2.+3.*x)*std::sqrt(1.+xp)) -2.*std::pow(wmax,2)*x*(1.+xp)-8.*std::pow(x,5)*xp*xp*std::pow(1.+xp,3)/(3.*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),3)) +4.*x/(wmax*std::sqrt(x*(1.+xp))-x)+wmax*std::sqrt(1.+xp)*(2.+3.*x-8.*x*x*(1.+2.*xp))/std::sqrt(x) +2.*x*x*x*xp*std::pow(1.+xp,2)*(1.+x*x*(1.+7.*xp)-x*(4.+7.*xp))/((x-1.)*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),2)) -(4.*x*(2.*(1.+xp)+2.*x*xp*(1.+xp)+x*x*(-3.+4.*xp+18.*xp*xp+11.*xp*xp*xp)+x*x*x*x*(2.+9.*xp+18.*xp*xp+11.*xp*xp*xp)-x*x*x*(1.+15.*xp+36.*xp*xp+22.*xp*xp*xp))) /(std::pow(x-1.,2)*(x+x*xp-wmax*std::sqrt(x*(1.+xp)))) -(-2.+3.*x+x*x+2.*xp-3.*x*xp)*std::log(wmax*std::sqrt(x*(1.+xp)))/x -((2.+2.*xp-2.*xp*xp*xp+std::pow(x,6)*(2.+xp)-3.*std::pow(x,5)*(4.+3.*xp)+std::pow(x,4)*(30.+26.*xp+4.*xp*xp-3.*xp*xp*xp) -x*(12.+23.*xp+4.*xp*xp+3.*xp*xp*xp)-std::pow(x,3)*(40.+48.*xp+9.*xp*xp*xp)+x*x*(30.+51.*xp+9.*xp*xp*xp))*std::log(1.+xp-wmax*std::sqrt(x*(1.+xp)))) /(std::pow(x-1.,3)*x*(x-xp-1.)*xp) -1./(x*xp*(x-xp-1.))*(4.*x*x*x*x+x*x*x*(10.+xp)-2.*x*x*(3.+5.*xp)+2.*(1.-xp+xp*xp*xp)-x*(2.+7.*xp+3.*xp*xp*xp))*std::log(-x+wmax*std::sqrt(x*(1.+xp))) -1./(std::pow(x-1.,3)*x*xp)*4.*(-1.+2.*x*(2.+xp)-x*x*(5.+6.*xp+3.*xp*xp)-6.*std::pow(x,5)*xp*(2.+6.*xp+5.*xp*xp) -x*x*x*xp*(1.+8.*xp+10.*xp*xp)+std::pow(x,6)*(-1.+3.*xp+12.*xp*xp+10.*xp*xp*xp) +std::pow(x,4)*(3.+14.*xp+33.*xp*xp+30.*xp*xp*xp))*std::log(wmax*std::sqrt(x*(1.+xp))-x*(1.+xp))); ymax=std::log(((1.+x)-std::sqrt(std::pow(1.-x,2)-4.*x*xp))/(2.*std::sqrt(x*(1.+xp)))); wmax=std::exp(ymax); long double R2=1./12.*x*xp*(1./std::sqrt(x)*(1./wmax*(2.+3.*x)*std::sqrt(1.+xp)) -2.*std::pow(wmax,2)*x*(1.+xp)-8.*std::pow(x,5)*xp*xp*std::pow(1.+xp,3)/(3.*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),3)) +4.*x/(wmax*std::sqrt(x*(1.+xp))-x)+wmax*std::sqrt(1.+xp)*(2.+3.*x-8.*x*x*(1.+2.*xp))/std::sqrt(x) +2.*x*x*x*xp*std::pow(1.+xp,2)*(1.+x*x*(1.+7.*xp)-x*(4.+7.*xp))/((x-1.)*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),2)) -(4.*x*(2.*(1.+xp)+2.*x*xp*(1.+xp)+x*x*(-3.+4.*xp+18.*xp*xp+11.*xp*xp*xp)+x*x*x*x*(2.+9.*xp+18.*xp*xp+11.*xp*xp*xp)-x*x*x*(1.+15.*xp+36.*xp*xp+22.*xp*xp*xp))) /(std::pow(x-1.,2)*(x+x*xp-wmax*std::sqrt(x*(1.+xp)))) -(-2.+3.*x+x*x+2.*xp-3.*x*xp)*std::log(wmax*std::sqrt(x*(1.+xp)))/x -((2.+2.*xp-2.*xp*xp*xp+std::pow(x,6)*(2.+xp)-3.*std::pow(x,5)*(4.+3.*xp)+std::pow(x,4)*(30.+26.*xp+4.*xp*xp-3.*xp*xp*xp) -x*(12.+23.*xp+4.*xp*xp+3.*xp*xp*xp)-std::pow(x,3)*(40.+48.*xp+9.*xp*xp*xp)+x*x*(30.+51.*xp+9.*xp*xp*xp))*std::log(1.+xp-wmax*std::sqrt(x*(1.+xp)))) /(std::pow(x-1.,3)*x*(x-xp-1.)*xp) -1./(x*xp*(x-xp-1.))*(4.*x*x*x*x+x*x*x*(10.+xp)-2.*x*x*(3.+5.*xp)+2.*(1.-xp+xp*xp*xp)-x*(2.+7.*xp+3.*xp*xp*xp))*std::log(-x+wmax*std::sqrt(x*(1.+xp))) -1./(std::pow(x-1.,3)*x*xp)*4.*(-1.+2.*x*(2.+xp)-x*x*(5.+6.*xp+3.*xp*xp)-6.*std::pow(x,5)*xp*(2.+6.*xp+5.*xp*xp) -x*x*x*xp*(1.+8.*xp+10.*xp*xp)+std::pow(x,6)*(-1.+3.*xp+12.*xp*xp+10.*xp*xp*xp) +std::pow(x,4)*(3.+14.*xp+33.*xp*xp+30.*xp*xp*xp))*std::log(wmax*std::sqrt(x*(1.+xp))-x*(1.+xp))); long double R3=-1./6.*(1.+x*x-x*(2.+xp))*(std::log(x)+std::log(1.+xp)+2.*std::log(2)-2.*std::log(1.+x+std::sqrt((1.-x)*(1.-x)-4.*x*xp))); return(2./xp*(R1-R2+R3)); } //Delta contribution //gg channel long double NLOPL::NLO_PL_delta(double xp){ const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); const long double MUR=pow(_muR/_mH,2.); const long double MUF=pow(_muF/_mH,2.); const long double b0=11./6.*_Nc-1./3.*_Nf; const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc)); const long double delta=3./2.*b0*(std::log(MUR*x/(-t))+std::log(MUR*x/(-u)))+(67./18.*_Nc-5./9.*_Nf); const long double U=1./2.*std::pow(std::log(u/t),2.)+M_PIl*M_PIl/3.-std::log(x)*std::log(x/(-t))-std::log(x)*std::log(x/(-u)) -std::log(x/(-t))*std::log(x/(-u))+std::pow(std::log(x),2.)+std::pow(std::log(x/(x-t)),2.)+std::pow(std::log(x/(x-u)),2.) +2.*gsl_sf_dilog(1.-x)+2.*gsl_sf_dilog(x/(x-t))+2.*gsl_sf_dilog(x/(x-u)); const long double ris=x*(Delta+delta+_Nc*U)*_Nc*(pow(x,4)+1.+pow(t,4)+pow(u,4))/(u*t) +(_Nc-_Nf)*_Nc/3.*(x*x+(x*x/t)+(x*x/u)+x); const long double Jac1=-(1.-x-rad)/(2.*rad); const long double Jac2=(1.-x+rad)/(2.*rad); const long double Si5z1=1./t*(std::pow(x,4)+1.+std::pow(t,4)+std::pow(u,4))/(u*t)*std::log(x*MUF/(-t)); const long double Si5z2=1./u*(std::pow(x,4)+1.+std::pow(u,4)+std::pow(t,4))/(u*t)*std::log(x*MUF/(-u)); return (ris/rad*2.+2.*x*_Nc*b0*(Jac2*Si5z2-Jac1*Si5z1)+_Nc*_Nf*B2pp_ANALITICS(x,xp)); } //gq channel long double NLOPL::NLO_PL_delta_gq(double xp){ const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); const long double MUR=pow(_muR/_mH,2.); const long double MUF=pow(_muF/_mH,2.); const long double b0=11./6.*_Nc-1./3.*_Nf; const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc)); const long double V11=0.5*std::pow(std::log(u/t),2.)+0.5*std::pow(std::log(1./(-u)),2.)-0.5*std::pow(std::log(1./(-t)),2.) -std::log(x)*std::log((-t)/x)+std::log(x)*std::log((-u)/x)-std::log((-t)/x)*std::log((-u)/x) +2.*dilog_r(x/(x-u))+std::pow(std::log(x/(x-u)),2.)+M_PIl*M_PIl; const long double V21=std::pow(std::log(x),2)+std::pow(std::log(x/(x-t)),2)-2.*std::log(1./x)*std::log((-t)/x)+2.*dilog_r(1.-x) +2.*dilog_r(x/(x-t))-7./2.-2.*M_PIl*M_PIl/3.; const long double V31=b0*(2.*std::log(MUR*x/(-u))+std::log(MUR*x/(-t)))+(67./9.*_Nc-10./9.*_Nf); const long double V12=0.5*std::pow(std::log(t/u),2.)+0.5*std::pow(std::log(1./(-t)),2.)-0.5*std::pow(std::log(1./(-u)),2.) -std::log(x)*std::log((-u)/x)+std::log(x)*std::log((-t)/x)-std::log((-u)/x)*std::log((-t)/x) +2.*dilog_r(x/(x-t))+std::pow(std::log(x/(x-t)),2.)+M_PIl*M_PIl; const long double V22=std::pow(std::log(x),2)+std::pow(std::log(x/(x-u)),2)-2.*std::log(1./x)*std::log((-u)/x)+2.*dilog_r(1.-x) +2.*dilog_r(x/(x-u))-7./2.-2.*M_PIl*M_PIl/3.; const long double V32=b0*(2.*std::log(MUR*x/(-t))+std::log(MUR*x/(-u)))+(67./9.*_Nc-10./9.*_Nf); long double ris=0.; ris+=x*((Delta+_Nc*V11+_Cf*V21+V31)*_Cf*(1.+t*t)/(-u)+(_Nc-_Cf)*_Cf*((1.+t*t+u*u-u*x)/(-u))); ris+=x*((Delta+_Nc*V12+_Cf*V22+V32)*_Cf*(1.+u*u)/(-t)+(_Nc-_Cf)*_Cf*((1.+u*u+t*t-t*x)/(-t))); const long double Jac1=-(1.-x-rad)/(2.*rad); const long double Jac2=(1.-x+rad)/(2.*rad); const long double Sideltaz1=x/t*b0*std::log(MUF*x/(-t))*(1.+t*t)/(-x*xp/(t)); const long double Sideltaz2=x/u*b0*std::log(MUF*x/(-u))*(1.+u*u)/(-x*xp/(u)); const long double Sideltazb1=x/(t)*3./2.*_Cf*std::log(MUF*x/(-t))*_Cf*(1.+u*u)/(-t); const long double Sideltazb2=x/(u)*3./2.*_Cf*std::log(MUF*x/(-u))*_Cf*(1.+t*t)/(-u); return(ris/rad+Jac2*(Sideltaz2+Sideltazb2)-Jac1*(Sideltaz1+Sideltazb1)); // OK } //qqbar channel long double NLOPL::NLO_PL_delta_qqbar(double xp){ const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); const long double MUR=pow(_muR/_mH,2.); const long double MUF=pow(_muF/_mH,2.); const long double b0=11./6.*_Nc-1./3.*_Nf; const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc)); const long double W1=std::log(-u/x)*std::log(-t/x)-std::log(1./x)*std::log(-u/x)-std::log(1./x)*std::log(-t/x) +2.*dilog_r(1.-x)+std::pow(std::log(x),2)-0.5*std::pow(std::log(u/t),2)-5./3.*M_PIl*M_PIl; const long double W2=3./2.*(std::log(1./(-t))+std::log(1./(-u)))+std::pow(std::log(u/t),2)-2.*std::log(-u/x)*std::log(-t/x) +std::pow(std::log(x/(x-u)),2)+std::pow(std::log(x/(x-t)),2)+2.*dilog_r(x/(x-u))+2.*dilog_r(x/(x-t))-7.+2.*M_PIl*M_PIl; const long double W3=b0/2.*(4.*std::log(MUR*x)+std::log(MUR*x/(-u))+std::log(MUR*x/(-t)))+(67./6.*_Nc-5./3.*_Nf); const long double ris=x*((Delta+_Nc*W1+_Cf*W2+W3)*2.*_Cf*_Cf*(t*t+u*u)+(_Nc-_Cf)*2.*_Cf*_Cf*((t*t+u*u+1.-x))); const long double Jac1=-(1.-x-rad)/(2.*rad); const long double Jac2=(1.-x+rad)/(2.*rad); const long double Sidelta1=2.*x/(t)*_Cf*3./2.*std::log(MUF*x/(-t))*2.*_Cf*_Cf*(x*x*xp*xp/(t*t)+t*t); const long double Sidelta2=2.*x/(u)*_Cf*3./2.*std::log(MUF*x/(-u))*2.*_Cf*_Cf*(x*x*xp*xp/(u*u)+u*u); return (2.*ris/rad+Jac2*Sidelta2-Jac1*Sidelta1); //OK No Logs //return 0; } //Singular Part //gg channel long double NLOPL::NLO_PL_sing_doublediff(double xp, double zz) { long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable za const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double muF=_muF; const long double muR=_muR; const long double b0=11./6.*Nc-1./3.*Nf; const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); const long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); const long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); //Define and add the different singular parts const long double Si12=2.*xx/(-t2)*(1.+std::pow(z,4)+std::pow(1.-z,4))/(z)*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t2,4)+std::pow(xx*xp*z/t2,4))/(z*z*xx*xp); const long double Si11=2.*xx/(-t1)*(1.+std::pow(z,4)+std::pow(1.-z,4))/(z)*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t1,4)+std::pow(xx*xp*z/t1,4))/(z*z*xx*xp); const long double Si12z1=16.*Nc*Nc*(1.+std::pow(xx,4)-2.*xx*(1.+xp)-2*xx*xx*xx*(1.+xp)+xx*xx*(3.+4.*xp+xp*xp))/(xp*(1.-xx+sqrt(1.-2.*xx+xx*xx-4.*xx*xp))); const long double Si11z1=16.*Nc*Nc*(1.+std::pow(xx,4)-2.*xx*(1.+xp)-2*xx*xx*xx*(1.+xp)+xx*xx*(3.+4.*xp+xp*xp))/(xp*(1.-xx-sqrt(1.-2.*xx+xx*xx-4.*xx*xp))); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); const long double Si21=2.*xx*(z/(-t1))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1,4)+std::pow(t1,4))+z*zb1*(std::pow(xx,4) +1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1); const long double Si22=2.*xx*(z/(-t2))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2,4)+std::pow(t2,4))+z*zb2*(std::pow(xx,4) +1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2); const long double Si21z1=(8.*Nc*Nc*(-std::pow(1.+(xx-1.)*xx,2)+2.*std::pow(1.-xx,2)*xx*xp-xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si22z1=(8.*Nc*Nc*(-std::pow(1.+(xx-1.)*xx,2)+2.*std::pow(1.-xx,2)*xx*xp-xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); const long double Si31=2.*xx*(z/(-t1))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1,4)+std::pow(t1,4))+z*zb1*(std::pow(xx,4) +1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1)*(std::log(Qt1*z/(-t1))); const long double Si32=2.*xx*(z/(-t2))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2,4)+std::pow(t2,4))+z*zb2*(std::pow(xx,4) +1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2)*(std::log(Qt2*z/(-t2))); const long double Si31z1=-(8.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp))) *std::log(2.*xx*xp/(1.-xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si32z1=-(8.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp))) *std::log(2.*xx*xp/(1.-xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=-1./(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); const long double Si41=2.*xx*(z/t1)*b0*Nc/2.*(std::pow(xx,4)+1.+z*zb1*(std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1); const long double Si42=2.*xx*(z/t2)*b0*Nc/2.*(std::pow(xx,4)+1.+z*zb2*(std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2); const long double Si41z1=(4.*Nc*b0*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si42z1=(4.*Nc*b0*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=1./(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); const long double Si51=2.*xx/t1*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(muF*xx*z/(-t1))*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t1,4)+std::pow(xx*xp*z/t1,4))/(z*z*xx*xp); const long double Si52=2.*xx/t2*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(muF*xx*z/(-t2))*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t2,4)+std::pow(xx*xp*z/t2,4))/(z*z*xx*xp); const long double Si51z1=(16.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))*std::log(muF*2.*xx/(1.-xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si52z1=(16.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))*std::log(muF*2.*xx/(1.-xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=1./(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); ris*=(1.-zmin); return ris; } //gq channel long double NLOPL::NLO_PL_sing_doublediff_gq(double xp, double zz) { long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable za const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); const long double rad1=std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp); const long double t=0.5*(xx-1.+rad1); const long double u=0.5*(xx-1.-rad1); const long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); const long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); //Define and add the different singular parts const long double Si11=xx/(t1)*_Nc*_Cf*((1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(MUF*xx*z/(-t1)))*(z*z+t1*t1)/(-xx*xp*z/(t1)); const long double Si12=xx/(t2)*_Nc*_Cf*((1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(MUF*xx*z/(-t2)))*(z*z+t2*t2)/(-xx*xp*z/(t2)); const long double Si11z1=xx/(t)*_Nc*_Cf*(2.*std::log(MUF*xx/(-t)))*(1.+t*t)/(-xx*xp/(t)); const long double Si12z1=xx/(u)*_Nc*_Cf*(2.*std::log(MUF*xx/(-u)))*(1.+u*u)/(-xx*xp/(u)); ris+=1./(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); // OK 4 Nc Cf Log(x)^2/xp const long double Si21=xx/(-t1)*_Nc*_Cf*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*(z*z+t1*t1)/(-xx*xp*z/(t1)); const long double Si22=xx/(-t2)*_Nc*_Cf*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*(z*z+t2*t2)/(-xx*xp*z/(t2)); const long double Si21z1=xx/(-t)*_Nc*_Cf*(2.)*(1.+t*t)/(-xx*xp/(t)); const long double Si22z1=xx/(-u)*_Nc*_Cf*(2.)*(1.+u*u)/(-xx*xp*z/(u)); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); //OK no logs const long double Si31=xx/(t1)*(_Cf*(1.+z*z)*std::log(MUF*xx*z/(-t1)))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t1*t1))/(-t1); const long double Si32=xx/(t2)*(_Cf*(1.+z*z)*std::log(MUF*xx*z/(-t2)))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t2*t2))/(-t2); const long double Si31z1=xx/(t)*(_Cf*(2.)*std::log(MUF*xx/(-t)))*_Cf*(1.+xx*xx*xp*xp/(t*t))/(-t); const long double Si32z1=xx/(u)*(_Cf*(2.)*std::log(MUF*xx/(-u)))*_Cf*(1.+xx*xx*xp*xp/(u*u))/(-u); ris+=1./(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); //OK no logs const long double Si41=xx/(-t1)*(_Cf*(1.+z*z))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t1*t1))/(-t1); const long double Si42=xx/(-t2)*(_Cf*(1.+z*z))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t2*t2))/(-t2); const long double Si41z1=xx/(-t)*(_Cf*(2.))*_Cf*(1.+xx*xx*xp*xp/(t*t))/(-t); const long double Si42z1=xx/(-u)*(_Cf*(2.))*_Cf*(1.+xx*xx*xp*xp/(u*u))/(-u); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); //OK no logs const long double Si51=xx*z/(-t1)*_Nc*_Cf*((-t1-t1*t1*t1+Q1*Q1*Q1*t1+Q1*t1*t1*t1)/(u1*t1) +(z*zb1*(-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*(u1/zb1)-Q1*std::pow(u1/zb1,3)))/(u1*t1)); const long double Si52=xx*z/(-t2)*_Nc*_Cf*((-t2-t2*t2*t2+Q2*Q2*Q2*t2+Q2*t2*t2*t2)/(u2*t2) +(z*zb2*(-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*(u2/zb2)-Q2*std::pow(u2/zb2,3)))/(u2*t2)); const long double Si51z1=xx/(-t)*_Nc*_Cf*((-t-t*t*t)/(u*t)+(-(t)-std::pow(t,3))/(u*t)); const long double Si52z1=xx*z/(-u)*_Nc*_Cf*((-u-u*u*u)/(u*t)+(-(u)-std::pow(u,3))/(u*t)); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); //OK +Nc*Cf*Log(x)^2/xp const long double Si61=xx*z/(t1)*std::log(Qt1*z/(-t1))*_Nc*_Cf*((-t1-t1*t1*t1+Q1*Q1*Q1*t1+Q1*t1*t1*t1)/(u1*t1) +(z*zb1*(-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*(u1/zb1)-Q1*std::pow(u1/zb1,3)))/(u1*t1)); const long double Si62=xx*z/(t2)*std::log(Qt2*z/(-t2))*_Nc*_Cf*((-t2-t2*t2*t2+Q2*Q2*Q2*t2+Q2*t2*t2*t2)/(u2*t2) +(z*zb2*(-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*(u2/zb2)-Q2*std::pow(u2/zb2,3)))/(u2*t2)); const long double Si61z1=xx/(t)*std::log(xx*xp/(-t))*_Nc*_Cf*((-t-t*t*t)/(u*t)+(-(t)-std::pow(t,3))/(u*t)); const long double Si62z1=xx/(u)*std::log(xx*xp/(-u))*_Nc*_Cf*((-u-u*u*u)/(u*t)+(-(u)-std::pow(u,3))/(u*t)); ris+=1./(1.-z)*(Jac2*Si62-Jac2z1*Si62z1-Jac1*Si61+Jac1z1*Si61z1); //OK -3Nc*Cf*Log(x)^2/xp const long double Si71=xx*z/(t1)*3./2.*_Cf*_Cf*(u1*u1+1.)/(-t1); const long double Si72=xx*z/(t2)*3./2.*_Cf*_Cf*(u2*u2+1.)/(-t2); const long double Si71z1=xx*z/(t)*3./2.*_Cf*_Cf*(u*u+1.)/(-t); const long double Si72z1=xx*z/(u)*3./2.*_Cf*_Cf*(t*t+1.)/(-u); ris+=1./(1.-z)*(Jac2*Si72-Jac2z1*Si72z1-Jac1*Si71+Jac1z1*Si71z1);//OK (Log semplice non Log squared) ris*=(1.-zmin); return ris; } //qqbar channel long double NLOPL::NLO_PL_sing_doublediff_qqbar(double xp, double zz) { long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable za const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); const long double rad1=std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp); const long double t=0.5*(xx-1.+rad1); const long double u=0.5*(xx-1.-rad1); const long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); const long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); //Define and add the different singular parts const long double Si11=xx/(-t1)*(-_Cf*(1.+z*z)*std::log(MUF*z*xx/(-t1)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t1*t1)*z*z+t1*t1)/z; const long double Si12=xx/(-t2)*(-_Cf*(1.+z*z)*std::log(MUF*z*xx/(-t2)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t2*t2)*z*z+t2*t2)/z; const long double Si11z1=xx/(-t)*(-_Cf*(2.)*std::log(MUF*xx/(-t)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t*t)+t*t); const long double Si12z1=xx/(-t2)*(-_Cf*(2.)*std::log(MUF*xx/(-u)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(u*u)+u*u); ris+=2./(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); //OK no Logs const long double Si21= xx/(-t1)*(_Cf*(1.+z*z))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t1*t1)*z*z+t1*t1)/z; const long double Si22=xx/(-t2)*(_Cf*(1.+z*z))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t2*t2)*z*z+t2*t2)/z; const long double Si21z1=xx/(-t)*(_Cf*(2.))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t*t)+t*t); const long double Si22z1=xx/(-u)*(_Cf*(2.))*2.*_Cf*_Cf*(xx*xx*xp*xp/(u*u)+u*u); ris+=2.*std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); //OK no Logs const long double Si31=xx*z/(-t1)*(2.*_Cf-_Nc)*_Cf*_Cf*((t1*t1+u1*u1+std::pow(t1/z,2)+std::pow(u1/zb1,2))); const long double Si32=xx*z/(-t2)*(2.*_Cf-_Nc)*_Cf*_Cf*((t2*t2+u2*u2+std::pow(t2/z,2)+std::pow(u2/zb1,2))); const long double Si31z1=xx/(-t)*(2.*_Cf-_Nc)*_Cf*_Cf*((t*t+u*u+std::pow(t,2)+std::pow(u,2))); const long double Si32z1=xx/(-u)*(2.*_Cf-_Nc)*_Cf*_Cf*((u*u+t*t+std::pow(u,2)+std::pow(t,2))); ris+=2.*std::log(1.-z)/(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); // OK no Logs const long double Si41=xx*z/(t1)*std::log(Qt1*z/(-t1))*(2.*_Cf-_Nc)*_Cf*_Cf*((t1*t1+u1*u1+std::pow(t1/z,2)+std::pow(u1/zb1,2))); const long double Si42=xx*z/(t2)*std::log(Qt2*z/(-t2))*(2.*_Cf-_Nc)*_Cf*_Cf*((t2*t2+u2*u2+std::pow(t2/z,2)+std::pow(u2/zb1,2))); const long double Si41z1=xx/t*std::log(xx*xp/(-t))*(2.*_Cf-_Nc)*_Cf*_Cf*((t*t+u*u+std::pow(t,2)+std::pow(u,2))); const long double Si42z1=xx/u*std::log(xx*xp/(-u))*(2.*_Cf-_Nc)*_Cf*_Cf*((u*u+t*t+std::pow(u,2)+std::pow(t,2))); ris+=2./(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); //OK no Logs const long double Si51=-xx*z/(-t1)*b0*_Cf*_Cf*((t1*t1+u1*u1)); const long double Si52=-xx*z/(-t2)*b0*_Cf*_Cf*((t2*t2+u2*u2)); const long double Si51z1=-xx/(-t)*b0*_Cf*_Cf*((t*t+u*u)); const long double Si52z1=-xx/(-u)*b0*_Cf*_Cf*((t*t+u*u)); ris+=2./(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); //OK no Logs ris*=(1.-zmin); //OK NO LOGS return ris; } //Not-Singular Part //gg channel long double NLOPL::NLO_PL_notsing_doublediff(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double muF=_muF; const long double muR=_muR; const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (paper Glover for definition of G2s) const long double Fi1_1=xx/(-t1)*(-2.*Nf*std::log(muF*xx/Q1)*0.5*(z*z+(1.-z)*(1.-z))+2.*Nf*z*(1.-z))*Cf*(z*z*xx*xx*xp*xp/(t1*t1)+z*z)/(-t1); const long double Fi1_2=xx/(-t2)*(-2.*Nf*std::log(muF*xx/Q2)*0.5*(z*z+(1.-z)*(1.-z))+2.*Nf*z*(1.-z))*Cf*(z*z*xx*xx*xp*xp/(t2*t2)+z*z)/(-t2); ris+=2.*(Jac2*Fi1_2-Jac1*Fi1_1); //Separate divergent part Q->0 (ref Grazzini) const long double tiny=1e-4; const long double Fi2_1 = (Q1 > tiny*(xx*xp) ) ? Nc*Nc*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4))*(Q1+Qt1)/(Q1*Qt1) +(2.*xx*xx*(std::pow(xx-t1,4)+std::pow(xx-u1,4)+std::pow(u1,4)+std::pow(t1,4)))/(u1*t1*(xx-u1)*(xx-t1)))*1./(xp) *std::log(xx*xp/Qt1) : -Nc*Nc*((std::pow(xx,4)+1.+std::pow(u1,4)+std::pow(t1,4))/(xx*xp*xp)); const long double Fi2_2 = ( Q2 > tiny*(xx*xp)) ? Nc*Nc*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4))*(Q2+Qt2)/(Q2*Qt2) +(2.*xx*xx*(std::pow(xx-t2,4)+std::pow(xx-u2,4)+std::pow(u2,4)+std::pow(t2,4)))/(u2*t2*(xx-u2)*(xx-t2)))*1./(xp) *std::log(xx*xp/Qt2) : -Nc*Nc*((std::pow(xx,4)+1.+std::pow(u2,4)+std::pow(t2,4))/(xx*xp*xp)); ris+=(Jac2*Fi2_2-Jac1*Fi2_1); //Define and add G2ns (paper Glover for definition of G2ns) //A1234 const long double A1234_1_1=-0.5*((pow(xx*xp/t1,4)+pow(xx*Q1/t1,4))*L1a1+pow(u1,4)*L1b1); const long double A1234_1_2=(pow(xx,2)*Q1*pow(u1,3))/(2.*t1*(u1-xx)*(t1-xx))*(L1a1+L1b1) +(xx*xp*Q1*pow(u1,3))/(2.*A1*(t1-xx))*(L2b1-L1b1) +(xx*xp*Q1*(pow(xx,4)+pow(u1-xx,4)))/(2.*A1*t1*(u1-xx))*(L2a1-L1a1); const long double A1234_1_3=pow(xx,2)*xp*Q1*(pow(u1,4)/(2.*pow(B1*t1,2))+pow(u1,2)/(2.*pow(B1,2))) +pow(xx,4)*pow(xp*Q1,2)*(-6./pow(B1,4)-4./pow(t1,4)+8./pow(B1*t1,2)); const long double A1234_1_4=L31*(xx*xp*pow(u1,3)*(u1+t1)/(B1*t1)+pow(xx,4)*pow(Q1*xp,2)*(3.*A1/pow(B1,5)-1./(A1*pow(B1,3))) -pow(xx,2)*xp*Q1*(1./(B1*t1)*(t1*t1+t1*u1+4.*pow(u1,2)-2.*xx*Q1) +A1/(2.*pow(B1,3))*(t1*t1+3.*t1*u1+3.*u1*u1-6*xx*Q1)+1./(2.*A1*B1)*(t1*t1+t1*u1+7.*u1*u1-2.*xx*Q1))); const long double A1234_2_1=-0.5*((pow(xx*xp/t2,4)+pow(xx*Q2/t2,4))*L1a2+pow(u2,4)*L1b2); const long double A1234_2_2=(pow(xx,2)*Q2*pow(u2,3))/(2.*t2*(u2-xx)*(t2-xx))*(L1a2+L1b2) +(xx*xp*Q2*pow(u2,3))/(2.*A2*(t2-xx))*(L2b2-L1b2) +(xx*xp*Q2*(pow(xx,4)+pow(u2-xx,4)))/(2.*A2*t2*(u2-xx))*(L2a2-L1a2); const long double A1234_2_3=pow(xx,2)*xp*Q2*(pow(u2,4)/(2.*pow(B2*t2,2))+pow(u2,2)/(2.*pow(B2,2))) +pow(xx,4)*pow(xp*Q2,2)*(-6./pow(B2,4)-4./pow(t2,4)+8./pow(B2*t2,2)); const long double A1234_2_4=L32*(xx*xp*pow(u2,3)*(u2+t2)/(B2*t2)+pow(xx,4)*pow(Q2*xp,2)*(3.*A2/pow(B2,5)-1./(A2*pow(B2,3))) -pow(xx,2)*xp*Q2*(1./(B2*t2)*(t2*t2+t2*u2+4.*pow(u2,2)-2.*xx*Q2) +A2/(2.*pow(B2,3))*(t2*t2+3.*t2*u2+3.*u2*u2-6*xx*Q2)+1./(2.*A2*B2)*(t2*t2+t2*u2+7.*u2*u2-2.*xx*Q2))); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A1234_2_1+A1234_2_2+A1234_2_3+A1234_2_4)-Jac1/(xp*Q1)*(A1234_1_1+A1234_1_2+A1234_1_3+A1234_1_4)); //A3412 const long double A3412_1_1=xx*xp*Q1*pow(A1,3)/(2.*t1*(u1-xx))*(L2a1+L1b1) +xx*xp*(u1+t1)/(16.*u1*t1*B1)*(pow(A1,4)+6.*pow(A1*B1,2)+pow(B1,4))*L31; const long double A3412_1_2=(-xx*xp/(2.*u1*t1)*(pow(1.-Q1,4)+pow(xx,4)+2.*Q1*A1*pow(1.-Q1,2)-2.*Q1*pow(xx,3)) -pow(xx,4)*pow(Q1*xp,2)/pow(u1,4)+(2.*pow(xx,2)*xp*Q1*(A1*A1-xx))/(u1*u1))*L1b1; const long double A3412_1_3=xx*xp*pow(Q1-u1,3)/(8.*u1*t1*(Q1-t1))*((Q1-t1)+Q1*u1)* (4./3.+2.*xx*xp/Qt1+4.*pow(xx*xp/Qt1,2)-44./3.*pow(xx*xp/Qt1,3)) +xx*xp*pow(Q1-t1,3)/(8.*u1*t1*(Q1-u1))*((Q1-u1)+Q1*t1)* (4./3.+2.*xx*xp/Qt1+4.*pow(xx*xp/Qt1,2)-44./3.*pow(xx*xp/Qt1,3)); const long double A3412_1_4=xx*xp*pow(Q1-u1,2)/(4.*u1*t1*(Q1-t1))* (-3.*(t1-xx)*((Q1-t1)+Q1*u1)-Q1*(xx*(t1-xx)+Q1*(u1-xx)))*(1.+2.*xx*xp/Qt1-6.*pow(xx*xp/Qt1,2)) +xx*xp*pow(Q1-t1,2)/(4.*u1*t1*(Q1-u1))* (-3.*(u1-xx)*((Q1-u1)+Q1*t1)+3.*Q1*(xx*(u1-xx)+Q1*(t1-xx))+4.*u1)*(1.+2.*xx*xp/Qt1-6.*pow(xx*xp/Qt1,2)); const long double A3412_1_5=xx*xp*(Q1-t1)/(2.*u1*t1*(Q1-u1))*(3.*pow(u1-xx,2)*((Q1-u1)+Q1*t1)+8.*u1*t1+2.*u1-2.*Q1*u1*pow(u1-Q1,2) -3.*xx*Q1*pow(t1-xx,2)-3.*Q1*(xx-Q1)*pow(t1,2)-Q1*u1*(4.*u1*t1-u1*xx-Q1*t1+2.*pow(t1,2)-4.*xx*xx)+3.*xx*pow(Q1,2)*(t1-xx) +xx*Q1*u1*(t1-Q1))*(1.-2.*xx*xp/Qt1)+xx*xp*(Q1-u1)/(2.*u1*t1*(Q1-t1))* (3.*pow(t1-xx,2)*((Q1-t1)+Q1*u1)+3.*(t1-xx)*Q1*(xx*(t1-xx)+Q1*(u1-xx))+Q1*u1*(xx*(t1-Q1)+Q1*(u1-xx)))*(1.-2.*xp*xx/Qt1); const long double A3412_1_6=-4.*pow(xx,4)*pow(Q1*xp,2)/pow(u1,4)+xp*Q1*pow(xx*B1,2)/(2.*u1*u1) +pow(xx,3)*xp/6.*((1.+Q1)/(u1*t1)+Q1/(u1*u1)+Q1/(t1*t1))+(2.*xp*pow(xx,3)*Q1)/(u1*u1)+pow(xx,3)*xp/u1 -xx*xp/(12.*t1*u1)*(30.*pow(xx,3)+54.*pow(Q1,2)*xx+8.*pow(Q1,3)) +xx*xp/(12*u1*t1)*(11.+17.*pow(xx,4)+Q1*(61.*u1*u1*t1+17.*pow(u1,3)+73.*u1*t1*t1+29.*pow(t1,3)) +xx*(24.*u1*u1*t1+6.*pow(u1,3)+36.*u1*t1*t1+18.*pow(t1,3))+Q1*Q1*(-21.*u1*u1-33.*t1*t1-52.*u1*t1) +xx*Q1*(-73.*u1*u1-109.*t1*t1-170.*u1*t1)+xx*xx*(-23.*u1*u1-35.*t1*t1-52.*u1*t1) +xx*xx*Q1*(134.*t1+110.*u1)+4.*pow(Q1,4)+52.*xx*pow(Q1,3)+20.*xx*xx*Q1*Q1-22.*pow(xx,3)*Q1); const long double A3412_2_1=xx*xp*Q2*pow(A2,3)/(2.*t2*(u2-xx))*(L2a2+L1b2) +xx*xp*(u2+t2)/(16.*u2*t2*B2)*(pow(A2,4)+6.*pow(A2*B2,2)+pow(B2,4))*L32; const long double A3412_2_2=(-xx*xp/(2.*u2*t2)*(pow(1.-Q2,4)+pow(xx,4)+2.*Q2*A2*pow(1.-Q2,2)-2.*Q2*pow(xx,3)) -pow(xx,4)*pow(Q2*xp,2)/pow(u2,4)+(2.*pow(xx,2)*xp*Q2*(A2*A2-xx))/(u2*u2))*L1b2; const long double A3412_2_3=xx*xp*pow(Q2-u2,3)/(8.*u2*t2*(Q2-t2))*((Q2-t2)+Q2*u2)* (4./3.+2.*xx*xp/Qt2+4.*pow(xx*xp/Qt2,2)-44./3.*pow(xx*xp/Qt2,3)) +xx*xp*pow(Q2-t2,3)/(8.*u2*t2*(Q2-u2))*((Q2-u2)+Q2*t2)* (4./3.+2.*xx*xp/Qt2+4.*pow(xx*xp/Qt2,2)-44./3.*pow(xx*xp/Qt2,3)); const long double A3412_2_4=xx*xp*pow(Q2-u2,2)/(4.*u2*t2*(Q2-t2))* (-3.*(t2-xx)*((Q2-t2)+Q2*u2)-Q2*(xx*(t2-xx)+Q2*(u2-xx)))*(1.+2.*xx*xp/Qt2-6.*pow(xx*xp/Qt2,2)) +xx*xp*pow(Q2-t2,2)/(4.*u2*t2*(Q2-u2))* (-3.*(u2-xx)*((Q2-u2)+Q2*t2)+3.*Q2*(xx*(u2-xx)+Q2*(t2-xx))+4.*u2)*(1.+2.*xx*xp/Qt2-6.*pow(xx*xp/Qt2,2)); const long double A3412_2_5=xx*xp*(Q2-t2)/(2.*u2*t2*(Q2-u2))*(3.*pow(u2-xx,2)*((Q2-u2)+Q2*t2)+8.*u2*t2+2.*u2-2.*Q2*u2*pow(u2-Q2,2) -3*xx*Q2*pow(t2-xx,2)-3.*Q2*(xx-Q2)*pow(t2,2)-Q2*u2*(4.*u2*t2-u2*xx-Q2*t2+2.*pow(t2,2)-4.*xx*xx)+3.*xx*pow(Q2,2)*(t2-xx) +xx*Q2*u2*(t2-Q2))*(1-2.*xx*xp/Qt2)+xx*xp*(Q2-u2)/(2.*u2*t2*(Q2-t2))* (3.*pow(t2-xx,2)*((Q2-t2)+Q2*u2)+3.*(t2-xx)*Q2*(xx*(t2-xx)+Q2*(u2-xx))+Q2*u2*(xx*(t2-Q2)+Q2*(u2-xx)))*(1-2.*xp*xx/Qt2); const long double A3412_2_6=-4.*pow(xx,4)*pow(Q2*xp,2)/pow(u2,4)+xp*Q2*pow(xx*B2,2)/(2.*u2*u2) +pow(xx,3)*xp/6.*((1.+Q2)/(u2*t2)+Q2/(u2*u2)+Q2/(t2*t2))+(2.*xp*pow(xx,3)*Q2)/(u2*u2)+pow(xx,3)*xp/u2 -xx*xp/(12.*t2*u2)*(30.*pow(xx,3)+54.*pow(Q2,2)*xx+8.*pow(Q2,3)) +xx*xp/(12*u2*t2)*(11.+17.*pow(xx,4)+Q2*(61.*u2*u2*t2+17.*pow(u2,3)+73.*u2*t2*t2+29.*pow(t2,3)) +xx*(24.*u2*u2*t2+6.*pow(u2,3)+36.*u2*t2*t2+18.*pow(t2,3))+Q2*Q2*(-21.*u2*u2-33.*t2*t2-52.*u2*t2) +xx*Q2*(-73.*u2*u2-109.*t2*t2-170.*u2*t2)+xx*xx*(-23.*u2*u2-35.*t2*t2-52.*u2*t2) +xx*xx*Q2*(134.*t2+110.*u2)+4.*pow(Q2,4)+52.*xx*pow(Q2,3)+20.*xx*xx*Q2*Q2-22.*pow(xx,3)*Q2); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A3412_2_1+A3412_2_2+A3412_2_3+A3412_2_4+A3412_2_5+A3412_2_6)-Jac1/(xp*Q1)*(A3412_1_1+A3412_1_2+A3412_1_3+A3412_1_4+A3412_1_5+A3412_1_6)); //A1324 const long double A1324_1_1=-0.5*((pow(xx*xp/t1,4)+pow(xx*Q1/t1,4))*L1a1+pow(u1,4)*L1b1) +pow(xx,3)*xp*Q1/(t1*t1)*L1a1+(pow(xx,2)*Q1*pow(u1,3)/(2.*t1*(u1-xx)*(t1-xx))+xx*xp*pow(u1,3)/(2.*t1)) *(L1a1+L1b1); const long double A1324_1_2=xx*xp*(1.-zb1)*pow(u1,3)/(2.*A1*(t1-xx))*(L2b1-L1b1) +(xx*xp*(1.-z)*(pow(xx,4)+pow(u1-xx,4)))/(2.*A1*t1*(u1-xx))*(L2a1-L1a1) +pow(xx,3)*xp*Q1/(A1*B1)*L31+xx*xx*xp*Q1/(2.*pow(t1,4))*(pow(xx*xp,2)-6.*xx*xx*xp*Q1+pow(xx*Q1,2)); const long double A1324_2_1=-0.5*((pow(xx*xp/t2,4)+pow(xx*Q2/t2,4))*L1a2+pow(u2,4)*L1b2) +pow(xx,3)*xp*Q2/(t2*t2)*L1a2+(pow(xx,2)*Q2*pow(u2,3)/(2.*t2*(u2-xx)*(t2-xx))+xx*xp*pow(u2,3)/(2.*t2)) *(L1a2+L1b2); const long double A1324_2_2=xx*xp*(1.-zb2)*pow(u2,3)/(2.*A2*(t2-xx))*(L2b2-L1b2) +(xx*xp*(1.-z)*(pow(xx,4)+pow(u2-xx,4)))/(2.*A2*t2*(u2-xx))*(L2a2-L1a2) +pow(xx,3)*xp*Q2/(A2*B2)*L32+xx*xx*xp*Q2/(2.*pow(t2,4))*(pow(xx*xp,2)-6.*xx*xx*xp*Q2+pow(xx*Q2,2)); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A1324_2_1+A1324_2_2)-Jac1/(xp*Q1)*(A1324_1_1+A1324_1_2)); //A3241 const long double A3241_1_1=xx*xp*pow(A1,3)*(1.-z)/(2.*t1*(u1-xx))*(L2a1-L1a1) +(-pow(xx,4)*pow(xp*Q1,2)/pow(t1,4)+pow(xx,3)*xp*pow(Q1,2)/(u1*t1) -xx*xx*xp*Q1*pow(A1,4)/(2.*u1*t1*(u1-xx)*(t1-xx))+xx*xx*xp*Q1*(u1+t1)*(2.*A1*A1-xx)/(u1*t1*t1))*L1a1; const long double A3241_1_2=xx*xp*Q1*pow(Q1-u1,2)/(2.*u1*t1*pow(Q1-t1,2))* (-u1*t1-pow(Q1-t1,2))*(-3.+10.*Q1/Qt1-6.*pow(Q1/Qt1,2)) +xx*xp*Q1*(Q1-u1)/(u1*t1*pow(Q1-t1,2))*(u1*t1*(Q1-u1)-pow(Q1-t1,3)-xx*pow(Q1-t1,2)-xx*(Q1-t1)*(Q1-u1)) *(-1.+2.*Q1/Qt1); const long double A3241_1_3=xx*xx*xp*Q1*(B1*B1/(2.*t1*t1)-2.*xx*Q1/(t1*t1)+(u1+t1)*(u1+t1)/(2.*u1*t1)) -4.*pow(xx,4)*pow(xp*Q1,2)/pow(t1,4)+xx*xp*Q1/(4.*u1*t1) *(pow(t1+u1,2)-(t1+u1)*(6.*Q1+4.*xx)+6.*Q1*Q1+8.*xx*Q1)+pow(xx,3)*xp*Q1*pow(t1+u1,2)/(4.*u1*u1*t1*t1); const long double A3241_2_1=xx*xp*pow(A2,3)*(1.-z)/(2.*t2*(u2-xx))*(L2a2-L1a2) +(-pow(xx,4)*pow(xp*Q2,2)/pow(t2,4)+pow(xx,3)*xp*pow(Q2,2)/(u2*t2) -xx*xx*xp*Q2*pow(A2,4)/(2.*u2*t2*(u2-xx)*(t2-xx))+xx*xx*xp*Q2*(u2+t2)*(2.*A2*A2-xx)/(u2*t2*t2))*L1a2; const long double A3241_2_2=xx*xp*Q2*pow(Q2-u2,2)/(2.*u2*t2*pow(Q2-t2,2))* (-u2*t2-pow(Q2-t2,2))*(-3.+10.*Q2/Qt2-6.*pow(Q2/Qt2,2)) +xx*xp*Q2*(Q2-u2)/(u2*t2*pow(Q2-t2,2))*(u2*t2*(Q2-u2)-pow(Q2-t2,3)-xx*pow(Q2-t2,2)-xx*(Q2-t2)*(Q2-u2)) *(-1.+2.*Q2/Qt2); const long double A3241_2_3=xx*xx*xp*Q2*(B2*B2/(2.*t2*t2)-2.*xx*Q2/(t2*t2)+(u2+t2)*(u2+t2)/(2.*u2*t2)) -4.*pow(xx,4)*pow(xp*Q2,2)/pow(t2,4)+xx*xp*Q2/(4.*u2*t2) *(pow(t2+u2,2)-(t2+u2)*(6.*Q2+4.*xx)+6.*Q2*Q2+8.*xx*Q2)+pow(xx,3)*xp*Q2*pow(t2+u2,2)/(4.*u2*u2*t2*t2); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A3241_2_1+A3241_2_2+A3241_2_3)-Jac1/(xp*Q1)*(A3241_1_1+A3241_1_2+A3241_1_3)); //Aepsilon const long double Aepsilon_1=4.*pow(xx,4)*pow(xp*Q1,2)*(1./pow(t1,4)+1./pow(u1,4)); const long double Aepsilon_2=4.*pow(xx,4)*pow(xp*Q2,2)*(1./pow(t2,4)+1./pow(u2,4)); ris+=Nc*Nc*(Jac2/(xp*Q2)*(Aepsilon_2)-Jac1/(xp*Q1)*(Aepsilon_1)); //A0 const long double A0_1= (pow(t1/z,4)+pow(u1/zb1,4))*xx*xp/(Qt1*Qt1)*(5.-7.*Q1/Qt1+20./3.*pow(Q1/Qt1,2)) +xx*xp*(17./3.+4.*std::log(xx*xp/Qt1)); const long double A0_2=(pow(t2/z,4)+pow(u2/zb2,4))*xx*xp/(Qt2*Qt2)*(5.-7.*Q2/Qt2+20./3.*pow(Q2/Qt2,2)) +xx*xp*(17./3.+4.*std::log(xx*xp/Qt2)); ris+=Nc*Nc*(Jac2/(xp)*(A0_2)-Jac1/(xp)*(A0_1)); //B1pm const long double B1pm_1=xx*xp*z*pow(1.-z,3)/t1+pow(xx*xp*z/t1,3)*(1.-z) +4.*pow(xx*xp*z/t1*(1.-z),2)-xx*xp*Q1*(1.+std::log(xx*xp/Qt1)); const long double B1pm_2=xx*xp*z*pow(1.-z,3)/t2+pow(xx*xp*z/t2,3)*(1.-z) +4.*pow(xx*xp*z/t2*(1.-z),2)-xx*xp*Q2*(1.+std::log(xx*xp/Qt2)); ris+=2.*Nf*Cf*(Jac2/(xp*Q2)*B1pm_2-Jac1/(xp*Q1)*B1pm_1); //B2pm //FIXME? C'è una differenza con risultato mathematica ma non capisco da dove dipenda. Contributo completamente negiglible comunque const long double B2pm_1=1./3.*pow(t1/z,4.)*xx*xp/Qt1*(-3./Qt1+3.*Q1/(Qt1*Qt1)-2.*Q1*Q1/(Qt1*Qt1*Qt1)) -1./3.*xx*xp; const long double B2pm_2=1./3.*pow(t2/z,4.)*xx*xp/Qt2*(-3./Qt2+3.*Q1/(Qt2*Qt2)-2.*Q2*Q2/(Qt2*Qt2*Qt2)) -1./3.*xx*xp; ris+=2.*Nf*Nc*(Jac2/xp*B2pm_2-Jac1/xp*B2pm_1); //B1pp const long double B1pp_1=xx*xp*pow(z,3)*(1.-z)/t1+pow(xx*xp*(1.-z)/t1,3)*z +4.*pow(xx*xp*z*(1.-z)/t1,2)-xx*xp*Q1/(Qt1*Qt1*u1*t1)*(pow(u1*t1+xx*xp*Q1,2)+2.*xx*xp*Q1*Qt1) +xx*xp*Q1/(u1*t1)*(1.+Q1*Q1)*std::log(1.+(xx*xp/Q1)); const long double B1pp_2=xx*xp*pow(z,3)*(1.-z)/t2+pow(xx*xp*(1.-z)/t2,3)*z +4.*pow(xx*xp*z*(1.-z)/t2,2)-xx*xp*Q2/(Qt2*Qt2*u2*t2)*(pow(u2*t2+xx*xp*Q2,2)+2.*xx*xp*Q2*Qt2) +xx*xp*Q2/(u2*t2)*(1.+Q2*Q2)*std::log(1.+(xx*xp/Q2)); ris+=2.*Nf*Cf*(Jac2/(xp*Q2)*B1pp_2-Jac1/(xp*Q1)*B1pp_1); //B2pp const long double B2pp_1_1=-xx*xp*Q1/(2.*u1*t1)*(1.+Q1*Q1)*std::log(Qt1/Q1); const long double B2pp_1_2=+xx*xp*std::pow(Q1-u1,3.)/(2.*u1*t1*(Q1-t1))*((Q1-t1)+Q1*u1) *(2./3.+Q1/Qt1-19./3.*std::pow(Q1/Qt1,3.)) -xx*xp*std::pow(Q1-u1,2.)/(2.*u1*t1*std::pow(Q1-t1,2.)) *(3.*std::pow(Q1-t1,3.)*Q1+(Q1-t1)*Q1*(2.*u1*t1+xx*xx) +std::pow(Q1-t1,2.)*(1+4.*xx*Q1-u1*(Q1+xx))-u1*u1*Q1*Q1+u1*t1*t1*xx)*(1.-2.*Q1*Q1/(Qt1*Qt1)) +xx*xp*(Q1-u1)/(2.*u1*t1*(Q1-t1))*(3.*Q1*(Q1+1.)*(Q1-t1)-t1+xx*Q1+Q1*u1*(xx-Q1)*(xx-Q1))*(1.-2.*Q1/Qt1); const long double B2pp_1_3=xx*xp/(12.*u1*t1)*(-2.+6.*xx*t1*(t1-xx)+2.*xx*xx*xx+8.*Q1*(1.-Q1)*(1.-Q1) -2.*u1*t1*Q1+7.*xx*xp*Q1-2.*Q1*Q1*xx-xx*xx*xx*Q1+3.*xx*Q1*Q1*Q1-4.*u1*t1*xx*Q1) +11./6.*xx*xp*Q1*Q1/(u1*t1)-xx*xp*xx*xx*Q1/(3.*t1*t1); const long double B2pp_2_1=-xx*xp*Q2/(2.*u2*t2)*(1.+Q2*Q2)*std::log(Qt2/Q2); const long double B2pp_2_2=+xx*xp*std::pow(Q2-u2,3.)/(2.*u2*t2*(Q2-t2))*((Q2-t2)+Q2*u2) *(2./3.+Q2/Qt2-19./3.*std::pow(Q2/Qt2,3.)) -xx*xp*std::pow(Q2-u2,2.)/(2.*u2*t2*std::pow(Q2-t2,2.)) *(3.*std::pow(Q2-t2,3.)*Q2+(Q2-t2)*Q2*(2.*u2*t2+xx*xx) +std::pow(Q2-t2,2.)*(1+4.*xx*Q2-u2*(Q2+xx))-u2*u2*Q2*Q2+u2*t2*t2*xx)*(1.-2.*Q2*Q2/(Qt2*Qt2)) +xx*xp*(Q2-u2)/(2.*u2*t2*(Q2-t2))*(3.*Q2*(Q2+1.)*(Q2-t2)-t2+xx*Q2+Q2*u2*(xx-Q2)*(xx-Q2))*(1.-2.*Q2/Qt2); const long double B2pp_2_3=xx*xp/(12.*u2*t2)*(-2.+6.*xx*t2*(t2-xx)+2.*xx*xx*xx+8.*Q2*(1.-Q2)*(1.-Q2) -2.*u2*t2*Q2+7.*xx*xp*Q2-2.*Q2*Q2*xx-xx*xx*xx*Q2+3.*xx*Q2*Q2*Q2-4.*u2*t2*xx*Q2) +11./6.*xx*xp*Q2*Q2/(u2*t2)-xx*xp*xx*xx*Q2/(3.*t2*t2); //res[0]+=2.*Nc*Nf*(Jac2/(xp*Q2)*(B2pp_2_1+B2pp_2_2+B2pp_2_3)-Jac1/(xp*Q1)*(B2pp_1_1+B2pp_1_2+B2pp_1_3)); ris+=2.*Nc*Nf*(Jac2/(xp*Q2)*(B2pp_2_1)-Jac1/(xp*Q1)*(B2pp_1_1)); // Il resto è integrato analiticamente in B2pp_ANALITICS /*if (res[0]!=res[0]) { std::cout << "nan Yes \t z= " << z << " x= " << xx << std::endl; }*/ ris*=(1.-zmin); return ris; } //gq channel long double NLOPL::NLO_PL_notsing_doublediff_gq(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11=xx/(-t1)*(-0.5*(z*z+(1.-z)*(1.-z))*std::log(MUF*xx/Q1)+z*(1.-z)) *2.*_Cf*_Cf*(xx*xx*xp*xp*z*z/(t1*t1)+t1*t1)/(z)+xx/(-t1)*_Cf*(1.-z)*_Cf*(xx*xx*xp*xp*z*z/(t1*t1)+z*z)/(-t1) +xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z) *_Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(z*xx*xp/t1,4)+std::pow(t1,4))/(z*z*xx*xp); const long double Fi12=xx/(-t2)*(-0.5*(z*z+(1.-z)*(1.-z))*std::log(MUF*xx/Q2)+z*(1.-z)) *2.*_Cf*_Cf*(xx*xx*xp*xp*z*z/(t2*t2)+t2*t2)/(z)+xx/(-t2)*_Cf*(1.-z)*_Cf*(xx*xx*xp*xp*z*z/(t2*t2)+z*z)/(-t2) +xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z) *_Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(z*xx*xp/t2,4)+std::pow(t2,4))/(z*z*xx*xp); ris+=(Jac2*Fi12-Jac1*Fi11); // OK 6 Nc Cf Log(x)^2/xp //Separate Divergent part (Q^2->0) see Grazzini const long double tiny=1e-4; const long double Fi21=(Q1>tiny*xx*xp) ? xx* _Nc*_Cf*(((-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*u1/zb1-Q1*std::pow(u1/zb1,3))*(Q1+Qt1))/(Q1*Qt1) -(2.*xx*xx*((xx-t1)*(xx-t1)+t1*t1))/(u1*(xx-u1)))/(xx*xp)*std::log(xx*xp/Qt1) : (t1*t1*t1+t1*z*z)/(z*z*z*xx*xp*xp) ; const long double Fi22=(Q2>tiny*xx*xp) ? xx* _Nc*_Cf*(((-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*u2/zb2-Q2*std::pow(u2/zb2,3))*(Q2+Qt2))/(Q2*Qt2) -(2.*xx*xx*((xx-t2)*(xx-t2)+t2*t2))/(u2*(xx-u2)))/(xx*xp)*std::log(xx*xp/Qt2) : (t2*t2*t2+t2*z*z)/(z*z*z*xx*xp*xp) ; ris+=(Jac2*Fi22-Jac1*Fi21); // OK -10 Nc Cf Log(x)^2/xp const long double C1pm1=-2.*xx*gsl_sf_log(xx*xp/Qt1); const long double C1pm2=-2.*xx*gsl_sf_log(xx*xp/Qt2); ris+=_Cf*_Cf*(Jac2*(C1pm2)-Jac1*(C1pm1)); const long double C1mp1=xx*xp*Q1-3.*xx*xp*t1*t1/2./u1+xx*xp/(2.*Qt1)*(pow(Q1-t1,3)+Q1*pow(Q1-u1,3))*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1); const long double C1mp2=xx*xp*Q2-3.*xx*xp*t2*t2/2./u2+xx*xp/(2.*Qt2)*(pow(Q2-t2,3)+Q1*pow(Q2-u2,3))*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2); ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1mp2)-1./xp/Q1*Jac1*(C1mp1)); const long double C1pp1=-3.*xx*xp/(2.*u1)-xx*xp*Q1*A1*A1/u1*L2b1+xx*xp/(u1*t1*t1)*L1a1*((A1-xx)*(A1-xx)*t1*t1-2.*Q1*xx*u1*t1*A1-Q1*xx*xx*(Q1-t1)*u1) +xx*xp/(u1*B1)*L31*((1.+Q1-xx)*((A1-xx)*(A1-xx)+Q1*A1*A1)-4.*Q1*A1*(A1-xx))+1./2.*xx*xp*(Q1-t1)*(Q1-t1)*(1./(Q1-u1)-Q1/u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1) +1./2.*xx*xp*(Q1-u1)*(Q1-u1)*(Q1/(Q1-t1)+1./u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1)+xx*xp*(Q1-t1)/(u1*(Q1-u1))*(2.*u1*(1.+t1) -Q1*(4.*xx*Q1-Q1*t1-xx*u1-2.*u1*t1))*(-1.+2.*Q1/Qt1)+xx*xp*(Q1-u1)/(u1*(Q1-t1))*(t1-2.*u1*t1+2.*Q1*u1*(Q1-t1))*(-1.+2.*Q1/Qt1) +xx*xp*Q1*xx*(t1+u1)/t1-2.*xx*xp*Q1*Q1*xx*xx/(t1*t1)+xx*xp*Q1*xx*xx/(2.*u1*u1)+xx*xp/(2.*u1)*(-2.*(Q1+xx)*u1+2.*xx+xx*xx+xx*Q1*(2.*(1.-Q1)+3.*xx-u1)+5.*Q1*(1.-Q1)); const long double C1pp2=-3.*xx*xp/(2.*u2)-xx*xp*Q2*A2*A2/u2*L2b2+xx*xp/(u2*t2*t2)*L1a2*((A2-xx)*(A2-xx)*t2*t2-2.*Q2*xx*u2*t2*A2-Q2*xx*xx*(Q2-t2)*u2) +xx*xp/(u2*B2)*L32*((1.+Q2-xx)*((A2-xx)*(A2-xx)+Q2*A2*A2)-4.*Q2*A2*(A2-xx))+1./2.*xx*xp*(Q2-t2)*(Q2-t2)*(1./(Q2-u2)-Q2/u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2) +1./2.*xx*xp*(Q2-u2)*(Q2-u2)*(Q2/(Q2-t2)+1./u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2)+xx*xp*(Q2-t2)/(u2*(Q2-u2))*(2.*u2*(1.+t2) -Q2*(4.*xx*Q2-Q2*t2-xx*u2-2.*u2*t2))*(-1.+2.*Q2/Qt2)+xx*xp*(Q2-u2)/(u2*(Q2-t2))*(t2-2.*u2*t2+2.*Q2*u2*(Q2-t2))*(-1.+2.*Q2/Qt2) +xx*xp*Q2*xx*(t2+u2)/t2-2.*xx*xp*Q2*Q2*xx*xx/(t2*t2)+xx*xp*Q2*xx*xx/(2.*u2*u2)+xx*xp/(2.*u2)*(-2.*(Q2+xx)*u2+2.*xx+xx*xx+xx*Q2*(2.*(1.-Q2)+3.*xx-u2)+5.*Q2*(1.-Q2)); ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1pp2)-1./xp/Q1*Jac1*(C1pp1)); const long double C1mm1=xx*xp*t1*t1/u1*L1a1-xx*xp*Q1*(xx-t1)*(xx-t1)/u1*L2b1+xx*xp*xx*Q1/B1/B1*(t1*(u1+t1)-2.*xx*Q1) +xx*xp/(u1*B1)*(t1*t1*B1*B1-xx*t1*t1*(u1+t1)+2.*Q1*Q1*xx*xx+Q1*xx*xx*(3.*t1-u1)+Q1*xx*xx*u1/(B1*B1)*(-t1*(u1+t1)+2.*xx*Q1+Q1*(t1-u1)))*L31; const long double C1mm2=xx*xp*t2*t2/u2*L1a2-xx*xp*Q2*(xx-t2)*(xx-t2)/u2*L2b2+xx*xp*xx*Q2/B2/B2*(t2*(u2+t2)-2.*xx*Q2) +xx*xp/(u2*B2)*(t2*t2*B2*B2-xx*t2*t2*(u2+t2)+2.*Q2*Q2*xx*xx+Q2*xx*xx*(3.*t2-u2)+Q2*xx*xx*u2/(B2*B2)*(-t2*(u2+t2)+2.*xx*Q2+Q2*(t2-u2)))*L32; ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1mm2)-1./xp/Q1*Jac1*(C1mm1)); const long double C2mp1=xx*xp*Q1/Qt1/Qt1*(pow(Q1-t1,3)+Q1*pow(Q1-u1,3))*(-2.+3.*Q1/Qt1)+2.*xx*xp*Q1+4.*xx*xp*Q1*gsl_sf_log(xx*xp/Qt1); const long double C2mp2=xx*xp*Q2/Qt2/Qt2*(pow(Q2-t2,3)+Q2*pow(Q2-u2,3))*(-2.+3.*Q2/Qt2)+2.*xx*xp*Q2+4.*xx*xp*Q2*gsl_sf_log(xx*xp/Qt2); ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2mp2)-1./xp/Q1*Jac1*(C2mp1)); const long double C2pp1=1./2.*xx*xp*A1*A1*(1.-z)*(L2a1-L1a1)+(xx*xp*(xx-t1)*A1*A1*(1.-zb1))/(2.*u1)*(L1b1-L2b1) +xx*xp*pow(1.-Q1,3)/(2.*u1)*(L1b1-L1a1)+xx*xp*Q1*A1*A1/(xx-u1)*(L1b1+L2a1) +xx*xp*Q1/(u1*u1)*L1b1*(2.*u1*(1.-Q1)*(1.-Q1)+4.*xx*(xx-t1)*A1-2.*xx*xx*(Q1-t1)-xx*xx*xx) -1./2.*xx*xp*pow(Q1-t1,2)*(1./(Q1-u1)-Q1/u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1) -1./2.*xx*xp*pow(Q1-u1,2)*(Q1/(Q1-t1)+1./u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1) +xx*xp*(Q1-t1)/(2.*u1*(Q1-u1))*((-3.*xx*xp+u1*u1-Q1*Q1)*(1.+Q1)-xx*u1+2.*Q1*Q1*(Q1-u1))*(-1.+2.*Q1/Qt1) +xx*xp*(Q1-u1)/(2.*u1*(Q1-t1))*(3.*xx*xp*(1.+Q1)-u1*Q1*(Q1-t1)+3.*Q1*xx*(Q1-u1)+t1*(u1+1.))*(-1.+2.*Q1/Qt1) +xx*xp*xx*Q1/(2.*u1*u1)*(2.*(1.-Q1)*(1.-Q1)-2.*xx*(1.-xx)-u1*(Q1-u1)-4.*xx*Q1)+xx*xp*(u1-t1)*(xx+Q1)/(2.*u1) -8.*pow(xx*xx*xp*Q1,2)/pow(u1,4)-2.*pow(xx*xx*xp*Q1,2)/pow(u1,4)*L1b1; const long double C2pp2=1./2.*xx*xp*A2*A2*(1.-z)*(L2a2-L1a2)+(xx*xp*(xx-t2)*A2*A2*(1.-zb2))/(2.*u2)*(L1b2-L2b2) +xx*xp*pow(1.-Q2,3)/(2.*u2)*(L1b2-L1a2)+xx*xp*Q2*A2*A2/(xx-u2)*(L1b2+L2a2) +xx*xp*Q2/(u2*u2)*L1b2*(2.*u2*(1.-Q2)*(1.-Q2)+4.*xx*(xx-t2)*A2-2.*xx*xx*(Q2-t2)-xx*xx*xx) -1./2.*xx*xp*pow(Q2-t2,2)*(1./(Q2-u2)-Q2/u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2) -1./2.*xx*xp*pow(Q2-u2,2)*(Q2/(Q2-t2)+1./u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2) +xx*xp*(Q2-t2)/(2.*u2*(Q2-u2))*((-3.*xx*xp+u2*u2-Q2*Q2)*(1.+Q2)-xx*u2+2.*Q2*Q2*(Q2-u2))*(-1.+2.*Q2/Qt2) +xx*xp*(Q2-u2)/(2.*u2*(Q2-t2))*(3.*xx*xp*(1.+Q2)-u2*Q2*(Q2-t2)+3.*Q2*xx*(Q2-u2)+t2*(u2+1.))*(-1.+2.*Q2/Qt2) +xx*xp*xx*Q2/(2.*u2*u2)*(2.*(1.-Q2)*(1.-Q2)-2.*xx*(1.-xx)-u2*(Q2-u2)-4.*xx*Q2)+xx*xp*(u2-t2)*(xx+Q2)/(2.*u2) -8.*pow(xx*xx*xp*Q2,2)/pow(u2,4)-2.*pow(xx*xx*xp*Q2,2)/pow(u2,4)*L1b2; ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2pp2)-1./xp/Q1*Jac1*(C2pp1)); const long double C2mm1=xx*xp*t1*t1*Q1/(2.*u1)*(L1a1+3.*L1b1)+1./2.*xx*xp*t1*t1*(1.-z)*(L2a1-L1a1)+xx*xp*Q1*pow(xx-t1,3)*zb1/(2.*u1*u1)*(L2b1-L1b1)+xx*xp*t1*t1*Q1/(xx-u1)*(L1b1+L2a1) +xx*xp*t1*t1/(2.*u1)*(L1b1-L1a1)+xx*xp*xx*Q1/(u1*u1)*(4.*t1*(t1-xx)+xx*xx)*L1b1-2.*pow(xx*xx*xp*Q1,2)/pow(u1,4)*L1b1+xx*xp*t1*t1*xx*Q1/(u1*u1)-8.*pow(xx*xx*xp*Q1,2)/(pow(u1,4)); const long double C2mm2=xx*xp*t2*t2*Q2/(2.*u2)*(L1a2+3.*L1b2)+1./2.*xx*xp*t2*t2*(1.-z)*(L2a2-L1a2)+xx*xp*Q2*pow(xx-t2,3)*zb2/(2.*u2*u2)*(L2b2-L1b2)+xx*xp*t2*t2*Q2/(xx-u2)*(L1b2+L2a2) +xx*xp*t2*t2/(2.*u2)*(L1b2-L1a2)+xx*xp*xx*Q2/(u2*u2)*(4.*t2*(t2-xx)+xx*xx)*L1b2-2.*pow(xx*xx*xp*Q2,2)/pow(u2,4)*L1b2+xx*xp*t2*t2*xx*Q2/(u2*u2)-8.*pow(xx*xx*xp*Q2,2)/(pow(u2,4)); ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2mm2)-1./xp/Q1*Jac1*(C2mm1)); const long double C2epsilon1=4.*pow(xx*xx*xp*Q1,2)/(pow(u1,4)); const long double C2epsilon2=4.*pow(xx*xx*xp*Q2,2)/(pow(u2,4)); ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2epsilon2)-1./xp/Q1*Jac1*(C2epsilon1));// All C2's OK -2 Nc Cf Log(x)^2/xp ris*=(1.-zmin); return ris; } // qqbar channel long double NLOPL::NLO_PL_notsing_doublediff_qqbar(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11= xx/(-t1)*_Cf*(1.-z)*2.*_Cf*_Cf*(t1*t1+z*z*xx*xx*xp*xp/(t1*t1))/z + xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(z*z+t1*t1)/(-xx*xp*z/(t1)); const long double Fi12= xx/(-t2)*_Cf*(1.-z)*2.*_Cf*_Cf*(t2*t2+z*z*xx*xx*xp*xp/(t2*t2))/z + xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(z*z+t2*t2)/(-xx*xp*z/(t2)); ris+=2.*(Jac2*Fi12-Jac1*Fi11); const long double Fi21=1./xp*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+(u1+t1-2.*Q1)*(u1+t1-2.*Q1))*std::log(xx*xp/Qt1); const long double Fi22=1./xp*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+(u2+t2-2.*Q2)*(u2+t2-2.*Q2))*std::log(xx*xp/Qt2); ris+=(Jac2*Fi22-Jac1*Fi21); // OK Log squared cancel themselves with similar in Fi1 const long double D1pm1=-xx*xp*Q1*(1.+std::log(xx*xp/Qt1))-(xx*xp*xx*xp*z*(1.-z))/(t1)-xx*xp*(1.-z)*(1.-z); const long double D1pm2=-xx*xp*Q2*(1.+std::log(xx*xp/Qt2))-(xx*xp*xx*xp*z*(1.-z))/(t2)-xx*xp*(1.-z)*(1.-z); ris+=2.*2.*_Cf*_Cf*_Cf*(Jac2/xp/Q2*D1pm2-Jac1/xp/Q1*D1pm1); // OK no Logs const long double D2pm1=-1./3.*xx*xp*Q1-xx*xp*t1*t1/(6.*z*z)*(11.-12.*Q1/Qt1+3.*Q1*Q1/Qt1/Qt1)+11.*xx*xp*t1*t1/6.; const long double D2pm2=-1./3.*xx*xp*Q2-xx*xp*t2*t2/(6.*z*z)*(11.-12.*Q2/Qt2+3.*Q2*Q2/Qt2/Qt2)+11.*xx*xp*t2*t2/6.; ris+=2.*2.*_Nc*_Cf*_Cf*(Jac2/xp/Q2*D2pm2-Jac1/xp/Q1*D2pm1); //OK no Logs const long double D1pp1=xx*xp*u1*u1*(1.-zb1)/A1*(L2b1-L1b1)+xx*xp*(xx-u1)*(xx-u1)*(1.-z)/A1*(L2a1-L1a1) +xx*xp*xx*Q1*(xx*xp+u1*t1)/(t1*t1)*L1a1-2.*xx*xp*xx*xx*Q1/(A1*B1)*L31+xx*xp*xx*Q1*(2.*xx*xp-u1*t1)/(t1*t1); const long double D1pp2=xx*xp*u2*u2*(1.-zb2)/A2*(L2b2-L1b2)+xx*xp*(xx-u2)*(xx-u2)*(1.-z)/A2*(L2a2-L1a2) +xx*xp*xx*Q2*(xx*xp+u2*t2)/(t2*t2)*L1a2-2.*xx*xp*xx*xx*Q2/(A2*B2)*L32+xx*xp*xx*Q2*(2.*xx*xp-u2*t2)/(t2*t2); ris+=2.*2.*_Cf*_Cf*_Cf*(Jac2/xp/Q2*D1pp2-Jac1/xp/Q1*D1pp1); //OK no Logs const long double D2pp1=xx*xp*u1*u1*(xx-t1)*(1.-zb1)/(2.*A1)*(L1b1-L2b1)+xx*xp*std::pow(xx-u1,3)*(1.-z)/(2.*A1)*(L1a1-L2a1) -0.5*xx*xp*u1*u1*(L1a1+L1b1)+6.*std::pow(xx*xp*xx*Q1,2)/std::pow(B1,4)-xx*xp*xx*Q1*u1*u1/B1/B1 +L31*(xx*xp*u1*u1*(u1+t1)/B1+std::pow(xx*xp*xx*Q1,2)*(1./(A1*B1*B1*B1)-3.*A1/std::pow(B1,5)) +xx*xp*xx*Q1*((t1-3.*u1)/(2.*B1)+A1*(B1*B1+2.*u1*u1)/(4.*B1*B1*B1)+(t1*t1-6.*t1*u1+7.*u1+u1)/(4.*A1*B1))); const long double D2pp2=xx*xp*u2*u2*(xx-t2)*(1.-zb2)/(2.*A2)*(L1b2-L2b2)+xx*xp*std::pow(xx-u2,3)*(1.-z)/(2.*A2)*(L1a2-L2a2) -0.5*xx*xp*u2*u2*(L1a2+L1b2)+6.*std::pow(xx*xp*xx*Q2,2)/std::pow(B2,4)-xx*xp*xx*Q2*u2*u2/B2/B2 +L32*(xx*xp*u2*u2*(u2+t2)/B2+std::pow(xx*xp*xx*Q2,2)*(1./(A2*B2*B2*B2)-3.*A2/std::pow(B2,5)) +xx*xp*xx*Q2*((t2-3.*u2)/(2.*B2)+A2*(B2*B2+2.*u2*u2)/(4.*B2*B2*B2)+(t2*t2-6.*t2*u2+7.*u2+u2)/(4.*A2*B2))); ris+=2.*2.*_Nc*_Cf*_Cf*(Jac2/xp/Q2*D2pp2-Jac1/xp/Q1*D2pp1); //OK no Logs const long double E11=8./3.*xx-4./3.*xx*xx; ris+=_Nf*_Cf*_Cf*E11*(Jac2-Jac1); //OK no Logs const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx; const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx; ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21); const long double E31=-2.*xx*xp*(std::pow(u1+t1-2.*Q1,2)-2.*xx*xp)*std::log(xx*xp/Qt1) -xx*xp*Q1*(2.*Qt1+Q1)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))-6.*xp*xx*Q1; const long double E32=-2.*xx*xp*(std::pow(u2+t2-2.*Q2,2)-2.*xx*xp)*std::log(xx*xp/Qt2) -xx*xp*Q2*(2.*Qt2+Q2)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))-6.*xp*xx*Q2; ris+=_Cf*_Cf/_Nc*(Jac2/(xp*Q2)*E32-Jac1/(xp*Q1)*E31); //OK no Logs ris*=(1.-zmin); return ris; } //qq channel long double NLOPL::NLO_PL_notsing_doublediff_qq(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11=xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(t1*t1+z*z)/(-xx*xp*z/(t1)); const long double Fi12=xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(t2*t2+z*z)/(-xx*xp*z/(t2)); ris+=2.*(Jac2*Fi12-Jac1*Fi11); const long double Fi21=xx*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+std::pow(u1+t1-2.*Q1,2))/(xx*xp)*std::log(xx*xp/Qt1); const long double Fi22=xx*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+std::pow(u2+t2-2.*Q2,2))/(xx*xp)*std::log(xx*xp/Qt2); ris+=(Jac2*Fi22-Jac1*Fi21); const long double E41=2.*xx*(1.+Q1*Q1)/Qt1*std::log(x*xp/Q1)+4.*xx*std::log(xx*xp/Qt1); const long double E42=2.*xx*(1.+Q2*Q2)/Qt2*std::log(x*xp/Q2)+4.*xx*std::log(xx*xp/Qt2); ris+=_Cf*_Cf/_Nc*(Jac2*E42-Jac1*E41); const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx; const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx; ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21); ris*=(1.-zmin); return ris; } //qqprime channel long double NLOPL::NLO_PL_notsing_doublediff_qqprime(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11=xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(t1*t1+z*z)/(-xx*xp*z/(t1)); const long double Fi12=xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(t2*t2+z*z)/(-xx*xp*z/(t2)); ris+=2.*(Jac2*Fi12-Jac1*Fi11); const long double Fi21=xx*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+std::pow(u1+t1-2.*Q1,2))/(xx*xp)*std::log(xx*xp/Qt1); const long double Fi22=xx*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+std::pow(u2+t2-2.*Q2,2))/(xx*xp)*std::log(xx*xp/Qt2); ris+=(Jac2*Fi22-Jac1*Fi21); const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx; const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx; ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21); ris*=(1.-zmin); return ris; } long double NLOPL::NLO_PL_notsing_doublediff_qqbarprime(double xp, double zz) { return(NLO_PL_notsing_doublediff_qqprime(xp,zz)); } long double NLOPL::LO_PL(double xp){ //we have to multiply later for sigma0 normalization const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); switch(_channel){ case(1):{ return (4.*_Nc*(std::pow(1.+(x-1.)*x,2)-2.*(x-1.)*(x-1.)*x*xp+x*x*xp*xp)/(xp*rad)*_as/(2.*M_PIl)); break; } case(2):{ return(_as/(2.*M_PIl)*_Cf*x/rad*((1.+u*u)/(-t)+(1.+t*t)/(-u))); break; } case(3):{ return(_as/(2.*M_PIl)*2.*_Cf*_Cf*x/rad*(u*u+t*t)); break; } case(4):{ return 0; break; } case(5):{ return 0; break; } case(6):{ return 0; break; } } }
58.466158
214
0.576788
gvita
bda5c0edf01f038f611d78c8ee2b7e90a0a7c0a1
9,628
cpp
C++
src/Game.cpp
M4T1A5/IndieSpeedRun2013
75b1adc4716c2e32f308289cce51a78a10681697
[ "Zlib" ]
null
null
null
src/Game.cpp
M4T1A5/IndieSpeedRun2013
75b1adc4716c2e32f308289cce51a78a10681697
[ "Zlib" ]
null
null
null
src/Game.cpp
M4T1A5/IndieSpeedRun2013
75b1adc4716c2e32f308289cce51a78a10681697
[ "Zlib" ]
null
null
null
#include <Game.h> #include <time.h> #include <stdlib.h> using namespace EGEMath; using namespace EGEMotor; Game::Game(Viewport& viewport, Input &input) : input(&input), viewport(&viewport), gameState(MENU), _clock(0), Difficulty(1) { font = new Font("square.ttf"); resourceText = new Text("", font); resourceText->setPosition(Vector(viewport.getWindowSize().x - 75, 0)); resourceText->setOriginPoint(9); resourceText->setLayer(295); resources = 6; health = 5; healthText = new Text("", font); healthText->setPosition(Vector(viewport.getWindowSize().x - 75, 30)); healthText->setOriginPoint(9); healthText->setLayer(295); activeButton[FOREST]=false; activeButton[SWAMP]=false; activeButton[HURRICANE]=false; activeButton[BUG]=false; activeButton[CAT]=false; activeButton[RIVER]=false; srand(time(NULL)); camera = new Camera(input, viewport, map.GetSize()); _townTexture.loadTexture("village.png"); _villageTexture.loadTexture("settlement.png"); _explorerTexture.loadTexture("arke_sheet.png"); _villages.push_back(new Village(&_townTexture,Vector(300,800))); // Menu menuTexture = new Texture("menu.png"); menu.setTexture(menuTexture); startTexture = new Texture("startbutton.png"); startButton = new GUIButton(startTexture, viewport.getWindowSize() / 2, Rectangle(Vector(), startTexture->getTextureSize()), &input); startButton->setOriginPoint(5); gameOverTexture = new Texture("game over.png"); gameOver.setTexture(gameOverTexture); gameOver.setPosition(startButton->getPosition()); gameOver.setOriginPoint(5); tutorialNumber = 0; for(int i = 0; i < 5; ++i) { char merkkijono[20]; sprintf(merkkijono, "tutorial-%d.png", i+1); tutorialTexture.push_back(new Texture(merkkijono)); tutorial.push_back(new GameObject(tutorialTexture[i])); tutorial[i]->setPosition(Vector(-1000,-1000)); tutorial[i]->setOriginPoint(5); } // Sidebar sidebarTexture = new Texture("sidebar2.png"); sidebar.setTexture(sidebarTexture); Vector sidebarPos = Vector(viewport.getWindowSize().x - sidebarTexture->getTextureSize().x, 0); sidebar.setPosition(sidebarPos); sidebar.setLayer(295); // Buttons buttonTexture = new Texture("buttons2.png"); for(int i = 0; i < 6; ++i) { Vector buttonPos = sidebarPos + Vector(0, i*120); Rectangle crop = Rectangle(Vector(i*75, 0), Vector(150,150)); auto button = new GUIButton(buttonTexture, buttonPos, crop, &input); button->setLayer(296); buttons.push_back(button); } buttons[0]->elementToSpawn = Forest; buttons[1]->elementToSpawn = Swamp; buttons[2]->hazardToSpawn = tornado; buttons[3]->hazardToSpawn = cat; buttons[4]->hazardToSpawn = bug; buttons[5]; particleEngine = new ParticleEngine(); } Game::~Game() { delete startTexture; delete startButton; delete menuTexture; delete sidebarTexture; delete buttonTexture; tutorialTexture.empty(); tutorial.empty(); buttons.empty(); } // Public void Game::Update(const double& dt) { char merkkijono[20]; Vector windowSize = viewport->getWindowSize(); Vector mousePos = input->getMousePosition(); switch (gameState) { case MENU: if (tutorialNumber == 0 && startButton->isPressed() ) { tutorial[tutorialNumber]->setPosition(startButton->getPosition()); tutorialNumber++; } if(tutorialNumber > 0 && tutorialNumber < tutorial.size()) { if(input->isButtonPressed(MouseLeft)) { tutorial[tutorialNumber]->setPosition(startButton->getPosition()); tutorialNumber++; } } if(tutorialNumber == tutorial.size()) { if(input->isButtonPressed(MouseLeft)) { for(int i = 0; i < tutorial.size(); ++i) tutorial[i]->setPosition(Vector(-1000,-1000)); gameState = WARMUP; } } break; case WARMUP: sprintf(merkkijono, "Resources: %d", resources); resourceText->setString(merkkijono); resourceText->updateOrigin(); sprintf(merkkijono, "Health: %d", health); healthText->setString(merkkijono); healthText->updateOrigin(); _clock += dt; if((windowSize.x - mousePos.x) < 5 || mousePos.x < 5) { camera->FollowMouse(dt); } else if((windowSize.y - mousePos.y) < 5 || mousePos.y < 5) { camera->FollowMouse(dt); } for(int i = 0; i < 2; ++i) { if(buttons[i]->isPressed()) spawnElement = buttons[i]->elementToSpawn; } if(spawnElement > 0 && input->isButtonPressed(Button::MouseLeft) && resources > 0) { map.AddElement(spawnElement, input->getMousePositionOnMap()); resources--; } if (_clock > 20) { _clock=0; gameState = PLAY; } break; case PLAY: sprintf(merkkijono, "Health: %d", health); healthText->setString(merkkijono); healthText->updateOrigin(); if((windowSize.x - mousePos.x) < 5 || mousePos.x < 5) { camera->FollowMouse(dt); } else if((windowSize.y - mousePos.y) < 5 || mousePos.y < 5) { camera->FollowMouse(dt); } for(int i = 2; i < 5; ++i) { if(buttons[i]->isPressed()) { spawnHazard = buttons[i]->hazardToSpawn; spawnElement = Background; } } if(spawnHazard >= 0 && input->isButtonPressed(Button::MouseLeft) ) { switch(spawnHazard) { case tornado: particleEngine->addTornado(input->getMousePositionOnMap(), Vector(1,1)); break; case cat: particleEngine->addCat(input->getMousePositionOnMap(), Vector(100,1)); break; case bug: particleEngine->addBug(input->getMousePositionOnMap(), Vector(100,1)); break; } } for (int i=0; i<_villages.size(); ++i) { _villages[i]->Update(dt); if (_villages[i]->Clock > _villages[i]->NextVillager) { _villages[i]->Clock -= _villages[i]->NextVillager; _villages[i]->NextVillager = (rand()%5)/Difficulty; _explorers.push_back(new Explorer(&_explorerTexture,16, _explorerTexture.getTextureSize().x/4.0f, _explorerTexture.getTextureSize().y/4.0f, 12,_villages[i]->getPosition())); } } for (int i=0; i<_explorers.size(); ++i) { _explorers[i]->Update(dt, map._mapElements[Volcano][0]->getPosition()); for (int j=0; j<map._mapElements.size();++j) { for (int k=0; k<map._mapElements[j].size();++k) { switch(j) { case Background: break; case River: if (map.GetPixel(_explorers[i]->getPosition()) != sf::Color::Transparent) { _explorers[i]->slowed=true; if (activeButton[RIVER]) { _explorers[i]->poison=true; } } break; case Forest: _explorers[i]->getPosition(); map._mapElements[j][k]->getPosition(); if ((_explorers[i]->getPosition()-map._mapElements[j][k]->getPosition()) .getLenght()< map._mapElementList[j]->Radius) { _explorers[i]->slowed=true; if (activeButton[FOREST]) { if(rand()%10000 > 9999-10000*dt); } } break; case Swamp: if ((_explorers[i]->getPosition()-map._mapElements[j][k]->getPosition()) .getLenght()< map._mapElementList[j]->Radius) { _explorers[i]->slowed=true; _explorers[i]->poison=true; if (activeButton[SWAMP]) { } } break; case Volcano: if(map._mapElements[j][k]-> getGlobalBounds().contains(_explorers[i]->getPosition())) { health--; _explorers.erase(_explorers.begin() + i); } break; } } } for (int j=0; j<particleEngine->m_TornadoParticles.size();++j) { if ((_explorers[i]->getPosition()-particleEngine->m_TornadoParticles[j]->m_position+Vector(0,-60)).getLenght() < particleEngine->m_TornadoParticles[j]->AreaOfEffect) { _explorers[i]->setPosition(particleEngine->m_TornadoParticles[j]->m_position+Vector(0,-10)); } } for (int j=0; j<particleEngine->m_BugParticles.size();++j) { if ((_explorers[i]->getPosition()-particleEngine->m_BugParticles[j]->m_position+Vector(0,80)).getLenght() < particleEngine->m_BugParticles[j]->AreaOfEffect) { _explorers[i]->poison = true; } } for (int j=0; j<particleEngine->m_CatParticles.size();++j) { if ((_explorers[i]->getPosition()-particleEngine->m_CatParticles[j]->m_position).getLenght() < particleEngine->m_CatParticles[j]->AreaOfEffect) { _explorers[i]->dead = true; } } if (_explorers[i]->dead) _explorers.erase(_explorers.begin() + i); } if(health == 0) gameState = GAMEOVER; break; case PAUSE: break; case GAMEOVER: if(input->isButtonPressed(MouseLeft)) exit(0); break; } for(size_t i = 0; i < buttons.size(); ++i) { if(buttons[i]->mouseOver()) buttons[i]->setColor(255,255,255,255); else buttons[i]->setColor(255,255,255,150); } map.Update(dt); particleEngine->Update(dt); } void Game::Draw(EGEMotor::Viewport& viewport) { switch (gameState) { case MENU: menu.Draw(viewport); startButton->draw(viewport); for(int i = 0; i < tutorial.size(); ++i) tutorial[i]->Draw(viewport); viewport.renderSprites(); break; case PAUSE: case WARMUP: case PLAY: map.Draw(viewport); for (int i=0;i<_villages.size();++i) _villages[i]->Draw(viewport); for (int i=0;i<_explorers.size();++i) _explorers[i]->Draw(viewport); for(size_t i = 0; i < buttons.size(); ++i) { buttons[i]->draw(viewport); } sidebar.Draw(viewport); viewport.draw(resourceText); viewport.draw(healthText); viewport.renderSprites(); break; case GAMEOVER: gameOver.Draw(viewport); viewport.renderSprites(); break; } particleEngine->Draw(&viewport); viewport.renderSprites(); } void Game::reset() { health = 5; resources = 6; gameState = MENU; _villages.empty(); _explorers.empty(); map.Reset(); }
24.498728
169
0.654342
M4T1A5
bdaf2f711fbe5aed14096c7ac4c7304eeab8ab0b
2,988
hpp
C++
include/makeshift/experimental/mpark/variant.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
3
2020-04-03T14:06:41.000Z
2021-11-09T23:55:52.000Z
include/makeshift/experimental/mpark/variant.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
2
2020-04-03T14:21:09.000Z
2022-02-08T14:37:01.000Z
include/makeshift/experimental/mpark/variant.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
null
null
null
#ifndef INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_ #define INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_ #include <utility> // for forward<>() #include <type_traits> // for remove_cv<>, remove_reference<> #include <gsl-lite/gsl-lite.hpp> // for gsl_Expects(), gsl_NODISCARD #include <mpark/variant.hpp> #include <makeshift/experimental/detail/variant.hpp> namespace makeshift { namespace gsl = ::gsl_lite; namespace mpark { // // Given an argument of type `mpark::variant<Ts...>`, this is `mpark::variant<::mpark::monostate, Ts...>`. // template <typename V> using with_monostate = typename detail::with_monostate_<::mpark::variant, ::mpark::monostate, V>::type; // // Given an argument of type `mpark::variant<::mpark::monostate, Ts...>`, this is `mpark::variant<Ts...>`. // template <typename V> using without_monostate = typename detail::without_monostate_<::mpark::variant, ::mpark::monostate, V>::type; // // Casts an argument of type `mpark::variant<Ts...>` to the given variant type. // template <typename DstV, typename SrcV> gsl_NODISCARD constexpr DstV variant_cast(SrcV&& variant) { #if !(defined(_MSC_VER) && defined(__INTELLISENSE__)) return ::mpark::visit( [](auto&& arg) -> DstV { return std::forward<decltype(arg)>(arg); }, std::forward<SrcV>(variant)); #endif // MAKESHIFT_INTELLISENSE } // // Converts an argument of type `mpark::variant<::mpark::monostate, Ts...>` to `std::optional<::mpark::variant<Ts...>>`. // //template <typename V> //gsl_NODISCARD constexpr decltype(auto) //variant_to_optional(V&& variantWithMonostate) //{ // using R = without_monostate<std::remove_cv_t<std::remove_reference_t<V>>>; // if (std::holds_alternative<::mpark::monostate>(variantWithMonostate)) // { // return std::optional<R>(std::nullopt); // } //#if !(defined(_MSC_VER) && defined(__INTELLISENSE__)) // return std::optional<R>(::mpark::visit( // detail::monostate_filtering_visitor<::mpark::monostate, R>{ }, // std::forward<V>(variantWithMonostate))); //#endif // MAKESHIFT_INTELLISENSE //} // // Converts an argument of type `std::optional<::mpark::variant<Ts...>>` to `mpark::variant<::mpark::monostate, Ts...>`. // //template <typename VO> //gsl_NODISCARD constexpr decltype(auto) //optional_to_variant(VO&& optionalVariant) //{ // using R = with_monostate<typename std::remove_cv_t<std::remove_reference_t<VO>>::value_type>; // if (!optionalVariant.has_value()) // { // return R{ ::mpark::monostate{ } }; // } // return variant_cast<R>(*std::forward<VO>(optionalVariant)); //} // // Concatenates the alternatives in the given variants. // template <typename... Vs> using variant_cat_t = typename detail::variant_cat_<::mpark::variant, Vs...>::type; } // namespace mpark } // namespace makeshift #endif // INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_
30.489796
131
0.670348
mbeutel
bdb2cae06023da708310a9bf1a528329ad9e9245
1,554
cpp
C++
interface/src/graphics/RenderEventHandler.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
272
2021-01-07T03:06:08.000Z
2022-03-25T03:54:07.000Z
interface/src/graphics/RenderEventHandler.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
1,021
2020-12-12T02:33:32.000Z
2022-03-31T23:36:37.000Z
interface/src/graphics/RenderEventHandler.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
77
2020-12-15T06:59:34.000Z
2022-03-23T22:18:04.000Z
// // RenderEventHandler.cpp // // Created by Bradley Austin Davis on 29/6/2018. // Copyright 2018 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "RenderEventHandler.h" #include "Application.h" #include <shared/GlobalAppProperties.h> #include <shared/QtHelpers.h> #include "CrashHandler.h" RenderEventHandler::RenderEventHandler(CheckCall checkCall, RenderCall renderCall) : _checkCall(checkCall), _renderCall(renderCall) { // Transfer to a new thread moveToNewNamedThread(this, "RenderThread", [this](QThread* renderThread) { hifi::qt::addBlockingForbiddenThread("Render", renderThread); _lastTimeRendered.start(); }, std::bind(&RenderEventHandler::initialize, this), QThread::HighestPriority); } void RenderEventHandler::initialize() { setObjectName("Render"); PROFILE_SET_THREAD_NAME("Render"); setCrashAnnotation("render_thread_id", std::to_string((size_t)QThread::currentThreadId())); } void RenderEventHandler::resumeThread() { _pendingRenderEvent = false; } void RenderEventHandler::render() { if (_checkCall()) { _lastTimeRendered.start(); _renderCall(); } } bool RenderEventHandler::event(QEvent* event) { switch ((int)event->type()) { case ApplicationEvent::Render: render(); _pendingRenderEvent.store(false); return true; default: break; } return Parent::event(event); }
26.338983
95
0.699485
Darlingnotin
bdb8301f9fe674aa624ee931f7f6bdc8dbd8aa25
1,832
cpp
C++
DigitalRoot.cpp
jb2020-super/kata
f6217d8b7c8854c89ff27d6bd70975b7aff85f89
[ "MIT" ]
null
null
null
DigitalRoot.cpp
jb2020-super/kata
f6217d8b7c8854c89ff27d6bd70975b7aff85f89
[ "MIT" ]
null
null
null
DigitalRoot.cpp
jb2020-super/kata
f6217d8b7c8854c89ff27d6bd70975b7aff85f89
[ "MIT" ]
null
null
null
/* Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer. 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2 */ /* best solution: A math guy here. Let me do my best to explain this code to anybody who does not yet understands it. The idea behind this trick is: sum of digits of a number 'n' is same as the number 'n' itself modulo 9. For example, 23 = 9*2+5 = 5 (modulo 9) = 2 + 3 (sum of digits modulo 9). If you don't believe it - try it with any number you come up with, I will leave a semiformal proof in the end. So, after any interchanging 'n' with a sum of digits of 'n' we have the same number modulo 9. And in the end we clearly have a one-digit number. I hope you got the gist of how we can figure the final number. //semiformal proof further //before further reading - be sure to understand why 9, 99, 999, 9999, etc are divisible by 9. Let us prove it for a number 7235. First, notice that 7000 = 7 (modulo 9). Why is that? Because 7000 - 7 = 7 * (1000 - 1) = 7 * 999 = 0 (modulo 9). Then, 200 = 2 (modulo 9). Again, 200 - 2 = 2 * (100-1) = 2 * 99 = 0(modulo 9) Hopefully, you see how this works. Now without my annoying comments: 7000 = 7(modulo 9) 200 = 2 (modulo 9) 30 = 3 (modulo 9) 5 = 5(modulo 9) all that is left to do is to add up these equations. */ int digital_root(int Z) { return --Z % 9 + 1; } int digital_root1(int n) { int sum = n; do { n = sum; sum = 0; while (n) { sum += n % 10; n /= 10; } } while (sum >= 10); return sum; }
38.166667
287
0.606441
jb2020-super
bdb98f8b83fe9562eb64a33632de182e2f962789
1,525
cc
C++
chrome/services/printing/pdf_to_emf_converter_factory.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
chrome/services/printing/pdf_to_emf_converter_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/services/printing/pdf_to_emf_converter_factory.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 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 "chrome/services/printing/pdf_to_emf_converter_factory.h" #include <utility> #include "chrome/services/printing/pdf_to_emf_converter.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "mojo/public/cpp/system/platform_handle.h" namespace printing { PdfToEmfConverterFactory::PdfToEmfConverterFactory() = default; PdfToEmfConverterFactory::~PdfToEmfConverterFactory() = default; void PdfToEmfConverterFactory::CreateConverter( base::ReadOnlySharedMemoryRegion pdf_region, const PdfRenderSettings& render_settings, mojo::PendingRemote<mojom::PdfToEmfConverterClient> client, CreateConverterCallback callback) { auto converter = std::make_unique<PdfToEmfConverter>( std::move(pdf_region), render_settings, std::move(client)); uint32_t page_count = converter->total_page_count(); mojo::PendingRemote<mojom::PdfToEmfConverter> converter_remote; mojo::MakeSelfOwnedReceiver( std::move(converter), converter_remote.InitWithNewPipeAndPassReceiver()); std::move(callback).Run(std::move(converter_remote), page_count); } // static void PdfToEmfConverterFactory::Create( mojo::PendingReceiver<mojom::PdfToEmfConverterFactory> receiver) { mojo::MakeSelfOwnedReceiver(std::make_unique<PdfToEmfConverterFactory>(), std::move(receiver)); } } // namespace printing
37.195122
79
0.775082
zealoussnow
bdba0a9c8a4aa4bb8f2faa7e5818dc3bc650d72b
1,256
cpp
C++
lib/code/widgets/single_child.cpp
leddoo/cpp-gui
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
[ "MIT" ]
null
null
null
lib/code/widgets/single_child.cpp
leddoo/cpp-gui
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
[ "MIT" ]
null
null
null
lib/code/widgets/single_child.cpp
leddoo/cpp-gui
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
[ "MIT" ]
null
null
null
#include <cpp-gui/core/gui.hpp> #include <cpp-gui/widgets/single_child.hpp> Single_Child_Def::~Single_Child_Def() { safe_delete(&this->child); } Widget* Single_Child_Def::on_get_widget(Gui* gui) { return gui->create_widget_and_match<Single_Child_Widget>(*this); } Single_Child_Widget::~Single_Child_Widget() { this->drop_maybe(this->child); this->child = nullptr; } void Single_Child_Widget::match(const Single_Child_Def& def) { this->child = this->reconcile(this->child, def.child); this->mark_for_layout(); } Bool Single_Child_Widget::on_try_match(Def* def) { return try_match_t<Single_Child_Def>(this, def); } void Single_Child_Widget::on_layout(Box_Constraints constraints) { // todo: sizing bias. if(this->child != nullptr) { this->child->layout(constraints); this->size = this->child->size; } else { this->size = { 0, 0 }; } } void Single_Child_Widget::on_paint(ID2D1RenderTarget* target) { if(this->child != nullptr) { this->child->paint(target); } } Bool Single_Child_Widget::visit_children_for_hit_testing(std::function<Bool(Widget* child)> visitor, V2f point) { UNUSED(point); return this->child != nullptr && visitor(this->child); }
22.836364
113
0.684713
leddoo
bdbb708a347c590ef630a45f6f1b3ef678bc7ce5
253
cpp
C++
src/process.cpp
Matthew-Zimmer/Harpoon
81420c815f8930d20c9e082973442d9fe7a7ddea
[ "BSL-1.0" ]
1
2019-12-22T20:02:31.000Z
2019-12-22T20:02:31.000Z
src/process.cpp
Matthew-Zimmer/harpoon
81420c815f8930d20c9e082973442d9fe7a7ddea
[ "BSL-1.0" ]
null
null
null
src/process.cpp
Matthew-Zimmer/harpoon
81420c815f8930d20c9e082973442d9fe7a7ddea
[ "BSL-1.0" ]
null
null
null
#include "process.hpp" namespace Slate::Harpoon { Base_Process::Base_Process(std::string const& name) : name{ name } {} Memory::Block& Buffer<void, void>::Queues() { static Memory::Block queues; return queues; }; }
19.461538
71
0.608696
Matthew-Zimmer
bdbf9abebcd92508f563e26a4b124f176142bb6b
21,051
hh
C++
src/exec/NodeImpl.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
1
2022-03-30T20:16:43.000Z
2022-03-30T20:16:43.000Z
src/exec/NodeImpl.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
src/exec/NodeImpl.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2006-2021, Universities Space Research Association (USRA). * 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 Universities Space Research Association 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 USRA ``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 USRA BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NODE_IMPL_HH #define NODE_IMPL_HH // *** For debug use only *** // Uncomment this if we don't trust the condition activation/deactivation logic // #define PARANOID_ABOUT_CONDITION_ACTIVATION 1 #include "Node.hh" #include "NodeVariables.hh" #include "Notifier.hh" #include <memory> // std::unique_ptr namespace PLEXIL { using ExpressionPtr = std::unique_ptr<Expression>; class Mutex; using MutexPtr = std::unique_ptr<Mutex>; class NodeVariableMap; using NodeVariableMapPtr = std::unique_ptr<NodeVariableMap>; class NodeTimepointValue; using NodeTimepointValuePtr = std::unique_ptr<NodeTimepointValue>; class NodeImpl; using NodeImplPtr = std::unique_ptr<NodeImpl>; /** * @class NodeImpl * @brief The innards shared between node implementation classes, * the XML parser, and external interfaces; also the * implementation class for empty nodes. */ class NodeImpl : public Node, public Notifier { public: // NOTE: this used to be 100000000, which somehow gets printed as // scientific notation in XML and doesn't parse correctly. static constexpr int32_t WORST_PRIORITY = 100000; static char const * const ALL_CONDITIONS[]; // N.B.: These need to match the order of ALL_CONDITIONS enum ConditionIndex { // Conditions on parent // N.B. Ancestor end/exit/invariant MUST come before // end/exit/invariant, respectively, because the former depend // on the latter and must be cleaned up first. ancestorExitIdx = 0, ancestorInvariantIdx, ancestorEndIdx, // User specified conditions skipIdx, startIdx, preIdx, exitIdx, invariantIdx, endIdx, postIdx, repeatIdx, // For all but Empty nodes actionCompleteIdx, // For all but Empty and Update nodes abortCompleteIdx, conditionIndexMax }; /** * @brief The constructor. * @param nodeId The name of this node. * @param parent The parent of this node (used for the ancestor conditions and variable lookup). */ NodeImpl(char const *nodeId, NodeImpl *parent = nullptr); /** * @brief Alternate constructor. Used only by Exec test module. */ NodeImpl(const std::string& type, const std::string& name, NodeState state, NodeImpl *parent = nullptr); virtual ~NodeImpl(); // // Listenable API // virtual bool isPropagationSource() const override { return true; } // Override Notifier method virtual bool isActive() const override { return true; } virtual void activate() override { } virtual void deactivate() override { } // // LinkedQueue API used by PlexilExec // virtual Node *next() const override { return static_cast<Node *>(m_next); } virtual Node **nextPtr() override { return static_cast<Node **>(&m_next); } // // NodeConnector API to expressions // virtual std::string const &getNodeId() const override { return m_nodeId; } /** * @brief Looks up a variable by name. * @param name Name of the variable. * @return The variable, or nullptr if not found. * @note Used only by XML parser. */ virtual Expression *findVariable(char const *name) override; // // ExpressionListener API // virtual void notifyChanged() override; // // Node API // // Make the node active. virtual void activateNode() override; //! Notify the node that something has changed. //! @param exec The PlexilExec instance. //! @note This is an optimization for cases where the change is //! the direct result of executive action. virtual void notifyChanged(PlexilExec *exec) override; /** * @brief Gets the destination state of this node, were it to transition, * based on the values of various conditions. * @return True if the new destination state is different from the last check, false otherwise. * @note Sets m_nextState, m_nextOutcome, m_nextFailureType as a side effect. */ virtual bool getDestState() override; /** * @brief Gets the previously calculated destination state of this node. * @return The destination state. */ virtual NodeState getNextState() const override { return (NodeState) m_nextState; } /** * @brief Commit a pending state transition based on the statuses of various conditions. * @param time The time of the transition. */ void transition(PlexilExec *exec, double time = 0.0) override; /** * @brief Get the priority of a node. * @return the priority of this node. */ virtual int32_t getPriority() const override { return m_priority; } /** * @brief Gets the current state of this node. * @return the current node state as a NodeState (enum) value. */ virtual NodeState getState() const override; /** * @brief Gets the outcome of this node. * @return the current outcome as an enum value. */ virtual NodeOutcome getOutcome() const override; /** * @brief Gets the failure type of this node. * @return the current failure type as an enum value. */ virtual FailureType getFailureType() const override; /** * @brief Accessor for an assignment node's assigned variable. * @note Default method, overridden by AssignmentNode. */ virtual Assignable *getAssignmentVariable() const override { return nullptr; } /** * @brief Gets the type of this node. * @return The type of this node. * @note Empty node method. */ virtual PlexilNodeType getType() const override { return NodeType_Empty; } /** * @brief Gets the parent of this node. */ virtual Node const *getParent() const override { return dynamic_cast<Node const *>(m_parent); } // // Resource conflict API // //! Does this node need to acquire resources before it can execute? //! @return true if resources must be acquired, false otherwise. virtual bool acquiresResources() const override; //! Reserve the resources needed by the node. //! On failure, add self to the resources' wait lists. //! @return true if successful, false if not. virtual bool tryResourceAcquisition() override; //! Remove the node from the pending queues of any resources //! it was trying to acquire. virtual void releaseResourceReservations() override; /** * @brief Notify that a resource on which we're pending is now available. */ virtual void notifyResourceAvailable() override; virtual QueueStatus getQueueStatus() const override { return m_queueStatus; } virtual void setQueueStatus(QueueStatus newval) override { m_queueStatus = newval; } virtual std::string toString(const unsigned int indent = 0) const override; virtual void print(std::ostream& stream, const unsigned int indent = 0) const override; // // Local to this class and derived classes // /** * @brief Set priority of a node. * @param prio The new priority. * @note Used by parser. */ void setPriority(int32_t prio) { m_priority = prio; } /** * @brief Accessor for the Node's parent. * @return This node's parent. */ NodeImpl *getParentNode() {return m_parent; } NodeImpl const *getParentNode() const {return m_parent; } //! Sets the state variable to the new state. //! @param exec The Exec to notify of the change. //! @param newValue The new node state. //! @param tym The time of transition. //! @note Virtual so it can be overridden by ListNode wrapper method. //! @note Only used by node implementation classes and unit tests. virtual void setState(PlexilExec *exec, NodeState newValue, double tym); // Used by unit tests void setNodeFailureType(FailureType f); /** * @brief Gets the time at which this node entered its current state. * @return Time value as a double. * @note Used by PlanDebugListener. */ double getCurrentStateStartTime() const; /** * @brief Gets the time at which this node entered the given state. * @param state The state. * @return Time value as a double. If not found, returns -DBL_MAX. * @note Used by PlanDebugListener. */ double getStateStartTime(NodeState state) const; /** * @brief Find the named variable in this node, ignoring its ancestors. * @param name Name of the variable. * @return The variable, or nullptr if not found. * @note Used only by XML parser. */ Expression *findLocalVariable(char const *name); virtual std::vector<NodeImplPtr> &getChildren(); virtual const std::vector<NodeImplPtr> &getChildren() const; virtual NodeImpl const *findChild(char const *childName) const; virtual NodeImpl *findChild(char const *childName); // // Utilities for plan parser and analyzer // // Pre-allocate local variable vector, variable map. void allocateVariables(size_t nVars); /** * @brief Add a named "variable" to the node, to be deleted with the node. * @param name The name * @param var The expression to associate with the name. * It will be deleted when the node is deleted. * @return true if successful, false if name is a duplicate */ bool addLocalVariable(char const *name, Expression *var); // Pre-allocate mutex vector. void allocateMutexes(size_t n); void allocateUsingMutexes(size_t n); // Add a mutex. void addMutex(Mutex *m); void addUsingMutex(Mutex *m); /** * @brief Looks up a mutex by name. Searches ancestors and globals. * @param name Name of the mutex. * @return The mutex, or nullptr if not found. */ Mutex *findMutex(char const *name) const; // May return nullptr. NodeVariableMap const *getVariableMap() const { return m_variablesByName.get(); } /** * @brief Add a condition expression to the node. * @param cname The name of the condition. * @param cond The expression. * @param isGarbage True if the expression should be deleted with the node. */ void addUserCondition(char const *cname, Expression *cond, bool isGarbage); /** * @brief Construct any internal conditions now that the node is complete. */ void finalizeConditions(); // Public only for plan analyzer static char const *getConditionName(size_t idx); /** * @brief Gets the state variable representing the state of this node. * @return the state variable. */ Expression *getStateVariable() { return &m_stateVariable; } Expression *getOutcomeVariable() { return &m_outcomeVariable; } Expression *getFailureTypeVariable() { return &m_failureTypeVariable; } // For use of plan parser. Expression *ensureTimepoint(NodeState st, bool isEnd); // May return nullptr. // Used by plan analyzer and plan parser module test only. const std::vector<ExpressionPtr> *getLocalVariables() const { return m_localVariables.get(); } // Condition accessors // These are public only to appease the module test // These conditions belong to the parent node. Expression *getAncestorEndCondition() { return getCondition(ancestorEndIdx); } Expression *getAncestorExitCondition() { return getCondition(ancestorExitIdx); } Expression *getAncestorInvariantCondition() { return getCondition(ancestorInvariantIdx); } // User conditions Expression *getSkipCondition() { return m_conditions[skipIdx]; } Expression *getStartCondition() { return m_conditions[startIdx]; } Expression *getEndCondition() { return m_conditions[endIdx]; } Expression *getExitCondition() { return m_conditions[exitIdx]; } Expression *getInvariantCondition() { return m_conditions[invariantIdx]; } Expression *getPreCondition() { return m_conditions[preIdx]; } Expression *getPostCondition() { return m_conditions[postIdx]; } Expression *getRepeatCondition() { return m_conditions[repeatIdx]; } // These are for specialized node types Expression *getActionCompleteCondition() { return m_conditions[actionCompleteIdx]; } Expression *getAbortCompleteCondition() { return m_conditions[abortCompleteIdx]; } // Abstracts out the issue of where the condition comes from. // Used internally, also by LuvListener. Non-const variant is protected. Expression const *getCondition(size_t idx) const; protected: friend class ListNode; Expression *getCondition(size_t idx); // Only used by Node, ListNode, LibraryCallNode. virtual NodeVariableMap const *getChildVariableMap() const; // *** Seems to be called only from NodeImpl constructor? void commonInit(); // Called from the transition handler void execute(PlexilExec *exec); void reset(); void deactivateExecutable(PlexilExec *exec); // Variables void activateLocalVariables(); void deactivateLocalVariables(); // Activate conditions // These are special because parent owns the condition expression void activateAncestorEndCondition(); void activateAncestorExitInvariantConditions(); // User conditions void activatePreSkipStartConditions(); void activateEndCondition(); void activateExitCondition(); void activateInvariantCondition(); void activatePostCondition(); void activateRepeatCondition(); // These are for specialized node types void activateActionCompleteCondition(); void activateAbortCompleteCondition(); // Deactivate a condition // These are special because parent owns the condition expression void deactivateAncestorEndCondition(); void deactivateAncestorExitInvariantConditions(); // User conditions void deactivatePreSkipStartConditions(); void deactivateEndCondition(); void deactivateExitCondition(); void deactivateInvariantCondition(); void deactivatePostCondition(); void deactivateRepeatCondition(); // These are for specialized node types void deactivateActionCompleteCondition(); void deactivateAbortCompleteCondition(); // Specific behaviors for derived classes virtual void specializedCreateConditionWrappers(); virtual void specializedActivate(); virtual void specializedHandleExecution(PlexilExec *exec); virtual void specializedDeactivateExecutable(PlexilExec *exec); // // State transition implementation methods // // Non-virtual member functions are common to all node types. // Virtual members are specialized by node type. // // getDestStateFrom... // Return true if the new destination state is different from the last check, false otherwise. // Set m_nextState, m_nextOutcome, m_nextFailureType as a side effect. bool getDestStateFromInactive(); bool getDestStateFromWaiting(); virtual bool getDestStateFromExecuting(); virtual bool getDestStateFromFinishing(); bool getDestStateFromFinished(); virtual bool getDestStateFromFailing(); bool getDestStateFromIterationEnded(); // // Transition out of the named current state. void transitionFromInactive(); void transitionFromWaiting(); virtual void transitionFromExecuting(PlexilExec *exec); virtual void transitionFromFinishing(PlexilExec *exec); void transitionFromFinished(); virtual void transitionFromFailing(PlexilExec *exec); void transitionFromIterationEnded(); void transitionToInactive(); void transitionToWaiting(); virtual void transitionToExecuting(); virtual void transitionToFinishing(); virtual void transitionToFinished(); virtual void transitionToFailing(PlexilExec *exec); virtual void transitionToIterationEnded(); // Phases of destructor // Not useful if called from base class destructor! virtual void cleanUpConditions(); void cleanUpVars(); virtual void cleanUpNodeBody(); // Printing utility virtual void printCommandHandle(std::ostream& stream, const unsigned int indent) const; // // Common state // Node *m_next; /*!< For LinkedQueue<Node> */ QueueStatus m_queueStatus; /*!< Which exec queue the node is in, if any. */ NodeState m_state; /*!< The current state of the node. */ NodeOutcome m_outcome; /*!< The current outcome. */ FailureType m_failureType; /*!< The current failure. */ bool m_pad; // to ensure 8 byte alignment NodeState m_nextState; /*!< The state returned by getDestState() the last time checkConditions() was called. */ NodeOutcome m_nextOutcome; /*!< The pending outcome. */ FailureType m_nextFailureType; /*!< The pending failure. */ NodeImpl *m_parent; /*!< The parent of this node.*/ Expression *m_conditions[conditionIndexMax]; /*!< The condition expressions. */ std::unique_ptr<std::vector<ExpressionPtr>> m_localVariables; /*!< Variables created in this node. */ std::unique_ptr<std::vector<MutexPtr>> m_localMutexes; /*!< Mutexes created in this node. */ std::unique_ptr<std::vector<Mutex *>> m_usingMutexes; /*!< Mutexes to be acquired by this node. */ StateVariable m_stateVariable; OutcomeVariable m_outcomeVariable; FailureVariable m_failureTypeVariable; NodeVariableMapPtr m_variablesByName; /*!< Locally declared variables or references to variables gotten through an interface. */ std::string m_nodeId; /*!< the NodeId from the xml.*/ int32_t m_priority; private: // Node transition history trace double m_currentStateStartTime; NodeTimepointValuePtr m_timepoints; protected: // Housekeeping details bool m_garbageConditions[conditionIndexMax]; /*!< Flags for conditions to delete. */ bool m_cleanedConditions, m_cleanedVars, m_cleanedBody; private: void createConditionWrappers(); // These should only be called from transition(). void setNodeOutcome(NodeOutcome o); void transitionFrom(PlexilExec *exec); void transitionTo(PlexilExec *exec, double tym); void logTransition(double time, NodeState newState); // // Internal versions // void printVariables(std::ostream& stream, const unsigned int indent = 0) const; void printMutexes(std::ostream& stream, const unsigned int indent = 0) const; }; } #endif // NODE_IMPL_HH
33.574163
132
0.663294
taless474
bdc49488d0957d4292661a5c6aba0fad298a3a78
8,344
cpp
C++
Project/Source/Components/UI/ComponentText.cpp
TBD-org/TBD-Engine
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
[ "MIT" ]
7
2021-04-26T21:32:12.000Z
2022-02-14T13:48:53.000Z
Project/Source/Components/UI/ComponentText.cpp
TBD-org/RealBugEngine
0131fde0abc2d86137500acd6f63ed8f0fc2835f
[ "MIT" ]
66
2021-04-24T10:08:07.000Z
2021-10-05T16:52:56.000Z
Project/Source/Components/UI/ComponentText.cpp
TBD-org/TBD-Engine
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
[ "MIT" ]
1
2021-07-13T21:26:13.000Z
2021-07-13T21:26:13.000Z
#include "ComponentText.h" #include "Application.h" #include "GameObject.h" #include "Modules/ModulePrograms.h" #include "Modules/ModuleCamera.h" #include "Modules/ModuleRender.h" #include "Modules/ModuleUserInterface.h" #include "Modules/ModuleResources.h" #include "Modules/ModuleEditor.h" #include "ComponentTransform2D.h" #include "Resources/ResourceTexture.h" #include "Resources/ResourceFont.h" #include "FileSystem/JsonValue.h" #include "Utils/ImGuiUtils.h" #include "GL/glew.h" #include "Math/TransformOps.h" #include "imgui_stdlib.h" #include "Utils/Leaks.h" #define JSON_TAG_TEXT_FONTID "FontID" #define JSON_TAG_TEXT_FONTSIZE "FontSize" #define JSON_TAG_TEXT_LINEHEIGHT "LineHeight" #define JSON_TAG_TEXT_LETTER_SPACING "LetterSpacing" #define JSON_TAG_TEXT_VALUE "Value" #define JSON_TAG_TEXT_ALIGNMENT "Alignment" #define JSON_TAG_COLOR "Color" ComponentText::~ComponentText() { App->resources->DecreaseReferenceCount(fontID); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); } void ComponentText::Init() { App->resources->IncreaseReferenceCount(fontID); glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); Invalidate(); } void ComponentText::OnEditorUpdate() { if (ImGui::Checkbox("Active", &active)) { if (GetOwner().IsActive()) { if (active) { Enable(); } else { Disable(); } } } ImGui::Separator(); ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; bool mustRecalculateVertices = false; if (ImGui::InputTextMultiline("Text input", &text, ImVec2(0.0f, ImGui::GetTextLineHeight() * 8), flags)) { SetText(text); } UID oldFontID = fontID; ImGui::ResourceSlot<ResourceFont>("Font", &fontID); if (oldFontID != fontID) { mustRecalculateVertices = true; } if (ImGui::DragFloat("Font Size", &fontSize, 2.0f, 0.0f, FLT_MAX)) { mustRecalculateVertices = true; } if (ImGui::DragFloat("Line height", &lineHeight, 2.0f, -FLT_MAX, FLT_MAX)) { mustRecalculateVertices = true; } if (ImGui::DragFloat("Letter spacing", &letterSpacing, 0.1f, -FLT_MAX, FLT_MAX)) { mustRecalculateVertices = true; } mustRecalculateVertices |= ImGui::RadioButton("Left", &textAlignment, 0); ImGui::SameLine(); mustRecalculateVertices |= ImGui::RadioButton("Center", &textAlignment, 1); ImGui::SameLine(); mustRecalculateVertices |= ImGui::RadioButton("Right", &textAlignment, 2); ImGui::ColorEdit4("Color##", color.ptr()); if (mustRecalculateVertices) { Invalidate(); } } void ComponentText::Save(JsonValue jComponent) const { jComponent[JSON_TAG_TEXT_FONTID] = fontID; jComponent[JSON_TAG_TEXT_FONTSIZE] = fontSize; jComponent[JSON_TAG_TEXT_LINEHEIGHT] = lineHeight; jComponent[JSON_TAG_TEXT_LETTER_SPACING] = letterSpacing; jComponent[JSON_TAG_TEXT_ALIGNMENT] = textAlignment; jComponent[JSON_TAG_TEXT_VALUE] = text.c_str(); JsonValue jColor = jComponent[JSON_TAG_COLOR]; jColor[0] = color.x; jColor[1] = color.y; jColor[2] = color.z; jColor[3] = color.w; } void ComponentText::Load(JsonValue jComponent) { fontID = jComponent[JSON_TAG_TEXT_FONTID]; fontSize = jComponent[JSON_TAG_TEXT_FONTSIZE]; lineHeight = jComponent[JSON_TAG_TEXT_LINEHEIGHT]; letterSpacing = jComponent[JSON_TAG_TEXT_LETTER_SPACING]; textAlignment = jComponent[JSON_TAG_TEXT_ALIGNMENT]; text = jComponent[JSON_TAG_TEXT_VALUE]; JsonValue jColor = jComponent[JSON_TAG_COLOR]; color.Set(jColor[0], jColor[1], jColor[2], jColor[3]); } void ComponentText::Draw(ComponentTransform2D* transform) { if (fontID == 0) { return; } ProgramTextUI* textUIProgram = App->programs->textUI; if (textUIProgram == nullptr) return; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glActiveTexture(GL_TEXTURE0); glBindVertexArray(vao); glUseProgram(textUIProgram->program); float4x4 model = transform->GetGlobalMatrix(); float4x4& proj = App->camera->GetProjectionMatrix(); float4x4& view = App->camera->GetViewMatrix(); if (App->userInterface->IsUsing2D()) { proj = float4x4::D3DOrthoProjLH(-1, 1, App->renderer->GetViewportSize().x, App->renderer->GetViewportSize().y); //near plane. far plane, screen width, screen height view = float4x4::identity; } ComponentCanvasRenderer* canvasRenderer = GetOwner().GetComponent<ComponentCanvasRenderer>(); if (canvasRenderer != nullptr) { float factor = canvasRenderer->GetCanvasScreenFactor(); view = view * float4x4::Scale(factor, factor, factor); } glUniformMatrix4fv(textUIProgram->viewLocation, 1, GL_TRUE, view.ptr()); glUniformMatrix4fv(textUIProgram->projLocation, 1, GL_TRUE, proj.ptr()); glUniformMatrix4fv(textUIProgram->modelLocation, 1, GL_TRUE, model.ptr()); glUniform4fv(textUIProgram->textColorLocation, 1, color.ptr()); RecalculateVertices(); for (size_t i = 0; i < text.size(); ++i) { if (text.at(i) != '\n') { Character character = App->userInterface->GetCharacter(fontID, text.at(i)); // render glyph texture over quad glBindTexture(GL_TEXTURE_2D, character.textureID); // update content of VBO memory glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(verticesText[i]), &verticesText[i].front()); glBindBuffer(GL_ARRAY_BUFFER, 0); // render quad glDrawArrays(GL_TRIANGLES, 0, 6); } } glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_BLEND); } void ComponentText::SetText(const std::string& newText) { text = newText; Invalidate(); } void ComponentText::SetFontSize(float newfontSize) { fontSize = newfontSize; Invalidate(); } void ComponentText::SetFontColor(const float4& newColor) { color = newColor; } float4 ComponentText::GetFontColor() const { return color; } void ComponentText::RecalculateVertices() { if (!dirty) { return; } if (fontID == 0) { return; } verticesText.resize(text.size()); ComponentTransform2D* transform = GetOwner().GetComponent<ComponentTransform2D>(); float x = -transform->GetSize().x * 0.5f; float y = 0; float dy = 0; // additional y shifting int j = 0; // index of row // FontSize / size of imported font. 48 is due to FontImporter default PixelSize float scale = (fontSize / 48); for (size_t i = 0; i < text.size(); ++i) { Character character = App->userInterface->GetCharacter(fontID, text.at(i)); float xpos = x + character.bearing.x * scale; float ypos = y - (character.size.y - character.bearing.y) * scale; float w = character.size.x * scale; float h = character.size.y * scale; switch (textAlignment) { case TextAlignment::LEFT: { // Default branch, could be deleted break; } case TextAlignment::CENTER: { xpos += (transform->GetSize().x - SubstringWidth(&text.c_str()[j], scale)) * 0.5f; break; } case TextAlignment::RIGHT: { xpos += transform->GetSize().x - SubstringWidth(&text.c_str()[j], scale); break; } } if (text.at(i) == '\n') { dy += lineHeight; // shifts to next line x = -transform->GetSize().x * 0.5f; // reset to initial position j = i + 1; // updated j variable in order to get the substringwidth of the following line in the next iteration } // clang-format off verticesText[i] = { xpos, ypos + h - dy, 0.0f, 0.0f, xpos, ypos - dy, 0.0f, 1.0f, xpos + w, ypos - dy, 1.0f, 1.0f, xpos, ypos + h - dy, 0.0f, 0.0f, xpos + w, ypos - dy, 1.0f, 1.0f, xpos + w, ypos + h - dy, 1.0f, 0.0f }; // clang-format on // now advance cursors for next glyph (note that advance is number of 1/64 pixels) if (text.at(i) != '\n') { x += ((character.advance >> 6) + letterSpacing) * scale; // bitshift by 6 to get value in pixels (2^6 = 64). Divides / 64 } } dirty = false; } void ComponentText::Invalidate() { dirty = true; } float ComponentText::SubstringWidth(const char* substring, float scale) { float subWidth = 0.f; for (int i = 0; substring[i] != '\0' && substring[i] != '\n'; ++i) { Character c = App->userInterface->GetCharacter(fontID, substring[i]); subWidth += ((c.advance >> 6) + letterSpacing) * scale; } subWidth -= letterSpacing * scale; return subWidth; }
28.094276
166
0.71081
TBD-org
bdca10dd283e3e72c5305613605227c50d78bb0f
1,062
cpp
C++
proj4/PongGame.cpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
proj4/PongGame.cpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
proj4/PongGame.cpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
// Our Pong Game #include <Game.hpp> #include <Vector2d.hpp> #include <Keyboard.hpp> #include <Color.hpp> #include "PongGame.h" #include "Ball.h" #include "Wall.h" using namespace vmi; // Create the game window PongGame::PongGame() : Game("Pong-ish", 640, 480), done(false) { // create the ball ball = new Ball(); // create the walls topWall = new Wall(Vector2d(0, 0), Vector2d(639, 1), Vector2d(0, 1)); bottomWall = new Wall(Vector2d(0, 478), Vector2d(639, 479), Vector2d(0, -1)); leftWall = new Wall(Vector2d(0, 1), Vector2d(1, 478), Vector2d(1, 0)); rightWall = new Wall(Vector2d(638, 1), Vector2d(639, 478), Vector2d(-1, 0)); // serve the ball ball->serve(Vector2d(100, 240), Vector2d(1, 0)); } PongGame::~PongGame() { delete ball; delete topWall; delete bottomWall; delete leftWall; delete rightWall; } // Per-frame update for game play void PongGame::update(double dt) { // intentionally blank } // Whether or not the game is over bool PongGame::isOver() const { return done; }
20.423077
79
0.645951
bakerjm24450
bdcc523c3973e8d9b3dd26d7cda0166aebdf59de
417
cpp
C++
sesion1/ejercicio_voltaje.cpp
dmateos-ugr/FP
6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e
[ "MIT" ]
1
2018-12-11T09:32:59.000Z
2018-12-11T09:32:59.000Z
sesion1/ejercicio_voltaje.cpp
dmateos-ugr/FP
6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e
[ "MIT" ]
null
null
null
sesion1/ejercicio_voltaje.cpp
dmateos-ugr/FP
6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e
[ "MIT" ]
2
2018-11-13T12:32:35.000Z
2018-11-27T14:43:30.000Z
#include <iostream> using namespace std; int main(){ double intensidad; double resistencia; double voltaje; cout << "Introduzca el valor de la intensidad: "; cin >> intensidad; cout << "Introduzca el valor de la resistencia: "; cin >> resistencia; voltaje = resistencia*intensidad; cout << "El valor del voltaje resultante es " << voltaje << endl; return 0; }
20.85
69
0.628297
dmateos-ugr
bdd2332404ec0f7842784cdfe9c22d1b54510d48
8,558
hpp
C++
MadgwickFilter/Quaternion/Quaternion.hpp
calm0815/robotrack
c3aedfa1d76173fe2729972d5a94ebb3bd84e3a1
[ "MIT" ]
3
2018-11-03T15:58:49.000Z
2019-04-11T22:46:32.000Z
MadgwickFilter/Quaternion/Quaternion.hpp
calm0815/robotrack
c3aedfa1d76173fe2729972d5a94ebb3bd84e3a1
[ "MIT" ]
null
null
null
MadgwickFilter/Quaternion/Quaternion.hpp
calm0815/robotrack
c3aedfa1d76173fe2729972d5a94ebb3bd84e3a1
[ "MIT" ]
null
null
null
#ifndef _QUATERNION_HPP_ #define _QUATERNION_HPP_ #include "Vector3/Vector3.hpp" /** * クォータニオンの足し,引き,掛け算などを簡単にできるようになります. * @author Gaku MATSUMOTO * @bref クォータニオンを使えるクラスです. */ class Quaternion{ public: /** @bref Quaternionインスタンスを生成します */ Quaternion(){ w = 1.0f; x = 0.0f; y = 0.0f; z = 0.0f; }; /** * @bref Vector3クラスからクォータニオンを作ります */ Quaternion(Vector3 vector){ Set(vector); } /** * @bref クォータニオンを回転軸と回転角度によって初期化します。 * @param vec 回転軸となる3次元ベクトル * @param angle 回転角 [rad] */ Quaternion(Vector3 vec, float angle){ Set(vec, angle); } /** @bref 要素を代入しながら,インスタンスを生成します. @param[in] _w 実部wの初期値 @param[in] _x 虚部iの初期値 @param[in] _y 虚部jの初期値 @param[in] _z 虚部kの初期値 */ Quaternion(float _w, float _x, float _y, float _z){ w = _w; x = _x; y = _y; z = _z; }; public: float w; float x; float y; float z; public: /** @bref クォータニオンの要素をコピーします. @note 通常の数のように代入できます */ Quaternion operator=(Quaternion r){ w = r.w; x = r.x; y = r.y; z = r.z; return *this; }; /** @bref クォータニオンを足して代入します. @note 通常の数のように代入できます */ Quaternion operator+=(Quaternion r){ w += r.w; x += r.x; y += r.y; z += r.z; return *this; }; /** @bref クォータニオンを引いて代入します. @note 通常の数のように代入できます */ Quaternion operator-=(Quaternion r){ w -= r.w; x -= r.x; y -= r.y; z -= r.z; return *this; }; /** * @bref クォータニオンの掛け算をします. * @note この際も順序は重要です. */ Quaternion operator*=(Quaternion r){ static Quaternion QQ; QQ.w = w*r.w - x*r.x - y*r.y - z*r.z; QQ.x = x*r.w + w*r.x - z*r.y + y*r.z; QQ.y = y*r.w + z*r.x + w*r.y - x*r.z; QQ.z = z*r.w - y*r.x + x*r.y + w*r.z; w = QQ.w; x = QQ.x; y = QQ.y; z = QQ.z; return *this; }; /** @bref クォータニオンの複素共役を返します. @note 本当はアスタリスクが良かったのですが,ポインタと紛らわしいのでマイナスにしました. */ Quaternion operator-(){ Quaternion Q; Q.w = w; Q.x = -x; Q.y = -y; Q.z = -z; return Q; }; /** @bref クォータニオンを正規化して,単位クォータニオンにします. @note 掛け算などを行うたびに実行することをお勧めします. @note ただ、クォータニオンの時間微分は正規化してはいけません */ void Normalize(){ float norm = sqrt(w*w + x*x + y*y + z*z); if (norm != 0.0f){ w /= norm; x /= norm; y /= norm; z /= norm; return; } else{ return; } }; /** * @bref クォータニオンを初期化します */ template <typename T> void Set(T _w, T _x, T _y, T _z); /** * @bref クォータニオンをVector3クラスで初期化します。 */ void Set(Vector3 vec); /** * @bref クォータニオンを回転軸と回転角度によって初期化します。 * param vec 回転軸となる3次元ベクトル * param angle 回転角 [rad] */ void Set(Vector3 vec, float angle){ vec.Normalize(); float halfAngle = 0.5f * angle ; w = cosf(halfAngle); x = vec.x * sinf(halfAngle); y = vec.y * sinf(halfAngle); z = vec.z * sinf(halfAngle); } /** * @bref クォータニオンの各要素に配列のようにアクセスします */ float q(int i){ float ans = 0.0; switch (i){ case 1: ans = w; break; case 2: ans = x; break; case 3: ans = y; break; case 4: ans = z; break; } return ans; } /** * @bref クォータニオンのノルムを計算します */ float Norm(){ return fabsf(w*w + x*x + y*y + z*z); } /** クォータニオンとクォータニオンを比較して等しければtrue 等しくなければfalse*/ bool operator==(Quaternion Q){ if (w == Q.w && x == Q.x && y == Q.y && z == Q.z){ return true; } return false; } /** クォータニオンとクォータニオンを比較して等しくなければtrue 等しければfalse*/ bool operator!=(Quaternion Q){ if (w == Q.w && x == Q.x && y == Q.y && z == Q.z){ return false; } return true; } /** * @bref 2つの3次元ベクトルを一致させるクォータニオンを計算 * @param from 始点となるベクトルのインスタンス * @param to 終点となるベクトルのインスタンス */ void FromToRotation(Vector3 from, Vector3 to); /** @bref オイラー角で姿勢を取得します. @param val ロール,ピッチ,ヨーの順に配列に格納します.3つ以上の要素の配列を入れてください. @note 値は[rad]です.[degree]に変換が必要な場合は別途計算して下さい. */ void GetEulerAngle(float *val){ float q0q0 = w * w, q1q1q2q2 = x * x - y * y, q3q3 = z * z; val[0] = (atan2f(2.0f * (w * x + y * z), q0q0 - q1q1q2q2 + q3q3)); val[1] = (-asinf(2.0f * (x * z - w * y))); val[2] = (atan2f(2.0f * (x * y + w * z), q0q0 + q1q1q2q2 - q3q3)); } /** @bref オイラー角で姿勢を取得します. @param val ロール,ピッチ,ヨーの順に配列に格納します.3つ以上の要素の配列を入れてください. @note 値は[rad]です.[degree]に変換が必要な場合は別途計算して下さい. */ void GetEulerAngle(Vector3 *v) { float q0q0 = w * w, q1q1q2q2 = x * x - y * y, q3q3 = z * z; v->x = (atan2f(2.0f * (w * x + y * z), q0q0 - q1q1q2q2 + q3q3)); v->y = (-asinf(2.0f * (x * z - w * y))); v->z = (atan2f(2.0f * (x * y + w * z), q0q0 + q1q1q2q2 - q3q3)); } /** * @bref クォータニオンをVector3クラスに変換します * @note クォータニオンのx,y,z成分を持ったベクトルを作ります */ Vector3 ToVector3(){ Vector3 vec3(x, y, z); return vec3; } /** * @bref 3次元ベクトルを回転します * @param v 回転させたい3次元ベクトルのポインタ * @note 余計なオブジェクトを作りません */ void Rotation(Vector3* v) { if (v == NULL) return; static float ww = 0.0f; static float xx = 0.0f; static float yy = 0.0f; static float zz = 0.0f; static float vx = 0.0f, vy = 0.0f, vz = 0.0f; static float _wx, _wy, _wz, _xy, _zx, _yz; ww = w * w; xx = x * x; yy = y * y; zz = z * z; _wx = w * x; _wy = w * y; _wz = w * z; _xy = x * y; _zx = z * x; _yz = y * z; vx = (ww + xx - yy - zz) * v->x + 2.0f*(_xy - _wz)*v->y + 2.0f*(_zx + _wy) * v->z; vy = 2.0f * (_xy + _wz) * v->x + (ww - xx + yy - zz) * v->y + 2.0f*(_yz - _wx)*v->z; vz = 2.0f * (_zx - _wy) * v->x + 2.0f * (_wx + _yz)*v->y + (ww - xx - yy + zz)*v->z; v->x = vx; v->y = vy; v->z = vz; } /** * @bref 3次元ベクトルを回転します.ただし逆回転です * @param v 回転させたい3次元ベクトルのポインタ * @note 余計なオブジェクトを作りません */ void InvRotation(Vector3* v) { if (v == NULL) return; static float ww = 0.0f; static float xx = 0.0f; static float yy = 0.0f; static float zz = 0.0f; static float vx = 0.0f, vy = 0.0f, vz = 0.0f; static float _wx, _wy, _wz, _xy, _xz, _yz; ww = w * w; xx = x * x; yy = y * y; zz = z * z; _wx = w * x; _wy = w * y; _wz = w * z; _xy = x * y; _xz = x * z; _yz = y * z; vx = (ww + xx - yy - zz) * v->x + 2.0f*(_xy + _wz)*v->y + 2.0f*(_xz - _wy) * v->z; vy = 2.0f * (_xy - _wz) * v->x + (ww - xx + yy - zz) * v->y + 2.0f*(_yz + _wx)*v->z; vz = 2.0f * (_xz + _wy) * v->x + 2.0f * (-_wx + _yz)*v->y + (ww - xx - yy + zz)*v->z; v->x = vx; v->y = vy; v->z = vz; } }; void Quaternion::FromToRotation(Vector3 from, Vector3 to){ float halfTheta = 0.5f * from.Angle(to);//回転角度 0からpi/2 Vector3 axis = from * to; axis.Normalize(); w = cos(halfTheta); x = axis.x * sin(halfTheta); y = axis.y * sin(halfTheta); z = axis.z * sin(halfTheta); } template<typename T>void Quaternion::Set(T _w, T _x, T _y, T _z){ w = _w; x = _x; y = _y; z = _z; return; } void Quaternion::Set(Vector3 vec){ w = 0.0; x = vec.x; y = vec.y; z = vec.z; return; } /** * @fn Quaternion operator*(Quaternion l, Quaternion r) * @bref クォータニオンの掛け算をします.この際,順序が重要です. */ Quaternion operator*(Quaternion l, Quaternion r){ static Quaternion Q; Q.w = l.w*r.w - l.x*r.x - l.y*r.y - l.z*r.z; Q.x = l.x*r.w + l.w*r.x - l.z*r.y + l.y*r.z; Q.y = l.y*r.w + l.z*r.x + l.w*r.y - l.x*r.z; Q.z = l.z*r.w - l.y*r.x + l.x*r.y + l.w*r.z; return Q; }; /** * @fn Quaternion operator*(double s, Quaternion q) * @bref クォータニオンをスカラー倍します. */ Quaternion operator*(float s, Quaternion q){ static Quaternion Q; Q.w = q.w * s; Q.x = q.x * s; Q.y = q.y * s; Q.z = q.z * s; return Q; }; /** * @fn Quaternion operator*(Quaternion q, double s) * @bref クォータニオンをスカラー倍します. */ Quaternion operator*(Quaternion q, float s){ static Quaternion Q; Q.w = q.w * s; Q.x = q.x * s; Q.y = q.y * s; Q.z = q.z * s; return Q; }; /** */ Vector3 operator*(Quaternion q, Vector3 v) { static Vector3 ans; static float ww = 0.0f; static float xx = 0.0f; static float yy = 0.0f; static float zz = 0.0f; //static float vx = 0.0f, vy = 0.0f, vz = 0.0f; static float _wx, _wy, _wz, _xy, _zx, _yz; ww = q.w * q.w; xx = q.x * q.x; yy = q.y * q.y; zz = q.z * q.z; _wx = q.w * q.x; _wy = q.w * q.y; _wz = q.w * q.z; _xy = q.x * q.y; _zx = q.z * q.x; _yz = q.y * q.z; ans.x = (ww + xx - yy - zz) * v.x + 2.0f*(_xy - _wz)*v.y + 2.0f*(_zx + _wy) * v.z; ans.y = 2.0f * (_xy + _wz) * v.x + (ww - xx + yy - zz) * v.y + 2.0f*(_yz - _wx)*v.z; ans.z = 2.0f * (_zx - _wy) * v.x + 2.0f * (_wx + _yz)*v.y + (ww - xx - yy + zz)*v.z; return ans; } /** @bref クォータニオンの足し算をします. */ Quaternion operator+(Quaternion l, Quaternion r){ static Quaternion Q; Q.w = l.w + r.w; Q.x = l.x + r.x; Q.y = l.y + r.y; Q.z = l.z + r.z; return Q; } /** @bref クォータニオンの引き算をします. */ Quaternion operator-(Quaternion l, Quaternion r){ static Quaternion Q; Q.w = l.w - r.w; Q.x = l.x - r.x; Q.y = l.y - r.y; Q.z = l.z - r.z; return Q; } #endif
19.102679
87
0.550946
calm0815
bdd3fc610582165f95b2ec03d5b299e7b69beedb
12,575
cc
C++
EventFilter/CSCTFRawToDigi/plugins/CSCTFUnpacker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
EventFilter/CSCTFRawToDigi/plugins/CSCTFUnpacker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
EventFilter/CSCTFRawToDigi/plugins/CSCTFUnpacker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "EventFilter/CSCTFRawToDigi/interface/CSCTFUnpacker.h" //Framework stuff #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" //Digi #include "DataFormats/CSCDigi/interface/CSCCorrelatedLCTDigi.h" #include "DataFormats/L1CSCTrackFinder/interface/L1Track.h" #include "DataFormats/L1CSCTrackFinder/interface/L1CSCSPStatusDigi.h" #include "DataFormats/L1CSCTrackFinder/interface/TrackStub.h" //Digi collections #include "DataFormats/CSCDigi/interface/CSCCorrelatedLCTDigiCollection.h" #include "DataFormats/L1CSCTrackFinder/interface/L1CSCTrackCollection.h" #include "DataFormats/L1CSCTrackFinder/interface/L1CSCStatusDigiCollection.h" #include "DataFormats/L1CSCTrackFinder/interface/CSCTriggerContainer.h" //Unique key #include "DataFormats/MuonDetId/interface/CSCDetId.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" //Don't know what #include <EventFilter/CSCTFRawToDigi/interface/CSCTFMonitorInterface.h> #include "FWCore/ServiceRegistry/interface/Service.h" #include "CondFormats/CSCObjects/interface/CSCTriggerMappingFromFile.h" //#include <DataFormats/MuonDetId/interface/CSCTriggerNumbering.h> //#include <iostream> #include <sstream> CSCTFUnpacker::CSCTFUnpacker(const edm::ParameterSet& pset):edm::stream::EDProducer<>(),mapping(0){ LogDebug("CSCTFUnpacker|ctor")<<"Started ..."; // Edges of the time window, which LCTs are put into (unlike tracks, which are always centred around 0): m_minBX = pset.getParameter<int>("MinBX"); //3 m_maxBX = pset.getParameter<int>("MaxBX"); //9 // Swap: if(swapME1strips && me1b && !zplus) strip = 65 - strip; // 1-64 -> 64-1 : swapME1strips = pset.getParameter<bool>("swapME1strips"); // Initialize slot<->sector assignment slot2sector = pset.getParameter< std::vector<int> >("slot2sector"); LogDebug("CSCTFUnpacker|ctor")<<"Verifying slot<->sector map from 'vint32 slot2sector'"; for(int slot=0; slot<22; slot++) if( slot2sector[slot]<0 || slot2sector[slot]>12 ) throw cms::Exception("Invalid configuration")<<"CSCTFUnpacker: sector index is set out of range (slot2sector["<<slot<<"]="<<slot2sector[slot]<<", should be [0-12])"; // Just for safety (in case of bad data): slot2sector.resize(32); // As we use standard CSC digi containers, we have to initialize mapping: std::string mappingFile = pset.getParameter<std::string>("mappingFile"); if( mappingFile.length() ){ LogDebug("CSCTFUnpacker|ctor") << "Define ``mapping'' only if you want to screw up real geometry"; mapping = new CSCTriggerMappingFromFile(mappingFile); } else { LogDebug("CSCTFUnpacker|ctor") << "Generating default hw<->geometry mapping"; class M: public CSCTriggerSimpleMapping{ void fill(void) override{} }; mapping = new M(); for(int endcap=1; endcap<=2; endcap++) for(int station=1; station<=4; station++) for(int sector=1; sector<=6; sector++) for(int csc=1; csc<=9; csc++){ if( station==1 ){ mapping->addRecord(endcap,station,sector,1,csc,endcap,station,sector,1,csc); mapping->addRecord(endcap,station,sector,2,csc,endcap,station,sector,2,csc); } else mapping->addRecord(endcap,station,sector,0,csc,endcap,station,sector,0,csc); } } producer = pset.getParameter<edm::InputTag>("producer"); produces<CSCCorrelatedLCTDigiCollection>(); produces<L1CSCTrackCollection>(); produces<L1CSCStatusDigiCollection>(); produces<CSCTriggerContainer<csctf::TrackStub> >("DT"); Raw_token = consumes<FEDRawDataCollection>(producer); } CSCTFUnpacker::~CSCTFUnpacker(){ if( mapping ) delete mapping; } void CSCTFUnpacker::produce(edm::Event& e, const edm::EventSetup& c){ // Get a handle to the FED data collection edm::Handle<FEDRawDataCollection> rawdata; e.getByToken(Raw_token,rawdata); // create the collection of CSC wire and strip digis as well as of DT stubs, which we receive from DTTF auto LCTProduct = std::make_unique<CSCCorrelatedLCTDigiCollection>(); auto trackProduct = std::make_unique<L1CSCTrackCollection>(); auto statusProduct = std::make_unique<L1CSCStatusDigiCollection>(); auto dtProduct = std::make_unique<CSCTriggerContainer<csctf::TrackStub>>(); for(int fedid=FEDNumbering::MINCSCTFFEDID; fedid<=FEDNumbering::MAXCSCTFFEDID; fedid++){ const FEDRawData& fedData = rawdata->FEDData(fedid); if( fedData.size()==0 ) continue; //LogDebug("CSCTFUnpacker|produce"); //if( monitor ) monitor->process((unsigned short*)fedData.data()); unsigned int unpacking_status = tfEvent.unpack((unsigned short*)fedData.data(),fedData.size()/2); if( unpacking_status==0 ){ // There may be several SPs in event std::vector<const CSCSPEvent*> SPs = tfEvent.SPs_fast(); // Cycle over all of them for(std::vector<const CSCSPEvent *>::const_iterator spItr=SPs.begin(); spItr!=SPs.end(); spItr++){ const CSCSPEvent *sp = *spItr; L1CSCSPStatusDigi status; /// status.sp_slot = sp->header().slot(); status.l1a_bxn = sp->header().BXN(); status.fmm_status = sp->header().status(); status.track_cnt = sp->counters().track_counter(); status.orbit_cnt = sp->counters().orbit_counter(); // Finds central LCT BX // assumes window is odd number of bins int central_lct_bx = (m_maxBX + m_minBX)/2; // Find central SP BX // assumes window is odd number of bins int central_sp_bx = int(sp->header().nTBINs()/2); for(unsigned int tbin=0; tbin<sp->header().nTBINs(); tbin++){ status.se |= sp->record(tbin).SEs(); status.sm |= sp->record(tbin).SMs(); status.bx |= sp->record(tbin).BXs(); status.af |= sp->record(tbin).AFs(); status.vp |= sp->record(tbin).VPs(); for(unsigned int FPGA=0; FPGA<5; FPGA++) for(unsigned int MPClink=0; MPClink<3; ++MPClink){ std::vector<CSCSP_MEblock> lct = sp->record(tbin).LCT(FPGA,MPClink); if( lct.size()==0 ) continue; status.link_status[lct[0].spInput()] |= (1<<lct[0].receiver_status_frame1())| (1<<lct[0].receiver_status_frame2())| ((lct[0].aligment_fifo()?1:0)<<4); status.mpc_link_id |= (lct[0].link()<<2)|lct[0].mpc(); int station = ( FPGA ? FPGA : 1 ); int endcap=0, sector=0; if( slot2sector[sp->header().slot()] ){ endcap = slot2sector[sp->header().slot()]/7 + 1; sector = slot2sector[sp->header().slot()]; if( sector>6 ) sector -= 6; } else { endcap = (sp->header().endcap()?1:2); sector = sp->header().sector(); } int subsector = ( FPGA>1 ? 0 : FPGA+1 ); int cscid = lct[0].csc() ; try{ CSCDetId id = mapping->detId(endcap,station,sector,subsector,cscid,0); // corrlcts now have no layer associated with them LCTProduct->insertDigi(id, CSCCorrelatedLCTDigi( 0,lct[0].vp(),lct[0].quality(),lct[0].wireGroup(), (swapME1strips && cscid<=3 && station==1 && endcap==2 && lct[0].strip()<65 ? 65 - lct[0].strip() : lct[0].strip() ), lct[0].pattern(),lct[0].l_r(), (lct[0].tbin()+(central_lct_bx-central_sp_bx)), lct[0].link(), lct[0].BXN(), 0, cscid ) ); } catch(cms::Exception &e) { edm::LogInfo("CSCTFUnpacker|produce") << e.what() << "Not adding digi to collection in event " <<sp->header().L1A()<<" (endcap="<<endcap<<",station="<<station<<",sector="<<sector<<",subsector="<<subsector<<",cscid="<<cscid<<",spSlot="<<sp->header().slot()<<")"; } } std::vector<CSCSP_MBblock> mbStubs = sp->record(tbin).mbStubs(); for(std::vector<CSCSP_MBblock>::const_iterator iter=mbStubs.begin(); iter!=mbStubs.end(); iter++){ int endcap, sector; if( slot2sector[sp->header().slot()] ){ endcap = slot2sector[sp->header().slot()]/7 + 1; sector = slot2sector[sp->header().slot()]; if( sector>6 ) sector -= 6; } else { endcap = (sp->header().endcap()?1:2); sector = sp->header().sector(); } const unsigned int csc2dt[6][2] = {{2,3},{4,5},{6,7},{8,9},{10,11},{12,1}}; DTChamberId id((endcap==1?2:-2),1, csc2dt[sector-1][iter->id()-1]); CSCCorrelatedLCTDigi base(0,iter->vq(),iter->quality(),iter->cal(),iter->flag(),iter->bc0(),iter->phi_bend(),tbin+(central_lct_bx-central_sp_bx),iter->id(),iter->bxn(),iter->timingError(),iter->BXN()); csctf::TrackStub dtStub(base,id,iter->phi(),0); dtProduct->push_back(dtStub); } std::vector<CSCSP_SPblock> tracks = sp->record(tbin).tracks(); unsigned int trkNumber=0; for(std::vector<CSCSP_SPblock>::const_iterator iter=tracks.begin(); iter!=tracks.end(); iter++,trkNumber++){ L1CSCTrack track; if( slot2sector[sp->header().slot()] ){ track.first.m_endcap = slot2sector[sp->header().slot()]/7 + 1; track.first.m_sector = slot2sector[sp->header().slot()]; if( track.first.m_sector>6 ) track.first.m_sector -= 6; } else { track.first.m_endcap = (sp->header().endcap()?1:2); track.first.m_sector = sp->header().sector(); } track.first.m_lphi = iter->phi(); track.first.m_ptAddress = iter->ptLUTaddress(); track.first.m_fr = iter->f_r(); track.first.m_ptAddress|=(iter->f_r() << 21); track.first.setStationIds(iter->ME1_id(),iter->ME2_id(),iter->ME3_id(),iter->ME4_id(),iter->MB_id()); track.first.setTbins(iter->ME1_tbin(), iter->ME2_tbin(), iter->ME3_tbin(), iter->ME4_tbin(), iter->MB_tbin() ); track.first.setBx(iter->tbin()-central_sp_bx); track.first.setBits(iter->syncErr(), iter->bx0(), iter->bc0()); track.first.setLocalPhi(iter->phi()); track.first.setEtaPacked(iter->eta()); track.first.setChargePacked(iter->charge()); track.first.m_output_link = iter->id(); if( track.first.m_output_link ){ track.first.m_rank = (iter->f_r()?sp->record(tbin).ptSpy()&0x7F:(sp->record(tbin).ptSpy()&0x7F00)>>8); track.first.setChargeValidPacked((iter->f_r()?(sp->record(tbin).ptSpy()&0x80)>>8:(sp->record(tbin).ptSpy()&0x8000)>>15)); } else { track.first.m_rank = 0; track.first.setChargeValidPacked(0); } track.first.setFineHaloPacked(iter->halo()); track.first.m_winner = iter->MS_id()&(1<<trkNumber); std::vector<CSCSP_MEblock> lcts = iter->LCTs(); for(std::vector<CSCSP_MEblock>::const_iterator lct=lcts.begin(); lct!=lcts.end(); lct++){ int station = ( lct->spInput()>6 ? (lct->spInput()-1)/3 : 1 ); int subsector = ( lct->spInput()>6 ? 0 : (lct->spInput()-1)/3 + 1 ); try{ CSCDetId id = mapping->detId(track.first.m_endcap,station,track.first.m_sector,subsector,lct->csc(),0); track.second.insertDigi(id, CSCCorrelatedLCTDigi( 0,lct->vp(),lct->quality(),lct->wireGroup(), (swapME1strips && lct->csc()<=3 && station==1 && track.first.m_endcap==2 && lct[0].strip()<65 ? 65 - lct[0].strip() : lct[0].strip() ), lct->pattern(),lct->l_r(), (lct->tbin()+(central_lct_bx-central_sp_bx)), lct->link(), lct->BXN(), 0, lct->csc() ) ); } catch(cms::Exception &e) { edm::LogInfo("CSCTFUnpacker|produce") << e.what() << "Not adding track digi to collection in event" <<sp->header().L1A()<<" (endcap="<<track.first.m_endcap<<",station="<<station<<",sector="<<track.first.m_sector<<",subsector="<<subsector<<",cscid="<<lct->csc()<<",spSlot="<<sp->header().slot()<<")"; } } std::vector<CSCSP_MBblock> mbStubs = iter->dtStub(); for(std::vector<CSCSP_MBblock>::const_iterator iter=mbStubs.begin(); iter!=mbStubs.end(); iter++){ CSCDetId id = mapping->detId(track.first.m_endcap,1,track.first.m_sector,iter->id(),1,0); track.second.insertDigi(id, CSCCorrelatedLCTDigi(iter->phi(),iter->vq(),iter->quality()+100,iter->cal(),iter->flag(),iter->bc0(),iter->phi_bend(),tbin+(central_lct_bx-central_sp_bx),iter->id(),iter->bxn(),iter->timingError(),iter->BXN()) ); } trackProduct->push_back( track ); } } statusProduct->second.push_back( status ); } } else { edm::LogError("CSCTFUnpacker|produce")<<" problem of unpacking TF event: 0x"<<std::hex<<unpacking_status<<std::dec<<" code"; } statusProduct->first = unpacking_status; } //end of fed cycle e.put(std::move(dtProduct),"DT"); e.put(std::move(LCTProduct)); // put processed lcts into the event. e.put(std::move(trackProduct)); e.put(std::move(statusProduct)); }
44.910714
217
0.65169
pasmuss
bdd4533dbcf1e985c9bdb2b026299460f56eaf0f
1,545
cpp
C++
week2/Searching and Sorting/Search in a Rotated Array.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
9
2021-08-01T16:17:04.000Z
2022-01-22T19:51:18.000Z
week2/Searching and Sorting/Search in a Rotated Array.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
null
null
null
week2/Searching and Sorting/Search in a Rotated Array.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
1
2021-08-30T12:26:11.000Z
2021-08-30T12:26:11.000Z
#include<bits/stdc++.h> using namespace std; int Search(vector<int> , int); int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<int> v(n); for(int i=0;i<n;i++) cin>>v[i]; int target; cin>>target; cout<<Search(v,target)<<endl; } } int binary_search(vector<int>arr,int l , int h , int k) { if (h < l) return -1; int mid=(l+h)/2; if (k == arr[mid]) return mid; else if (k > arr[mid]) return binary_search(arr, (mid + 1), h, k); else return binary_search(arr, l, (mid - 1), k); } int findpivot(vector<int>arr, int low, int high) { if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid] > arr[mid + 1]) return mid; else if (mid > low && arr[mid] < arr[mid - 1]) return (mid - 1); else if (arr[low] >= arr[mid]) return findpivot(arr, low, mid - 1); else return findpivot(arr, mid + 1, high); } int Search(vector<int>A, int target) { int n = A.size(); int pivot=findpivot(A,0,n-1); if(pivot==-1) { return binary_search(A,0,n-1,target); } if(A[pivot]==target) return pivot; else if(A[0]<=target) return binary_search(A,0,pivot-1,target); else return binary_search(A,pivot+1,n-1,target); }
22.071429
55
0.471845
rishabhrathore055
bdd623ceed6f588f267e4b4bdf3f66365b2ca406
738
cc
C++
common/filesystem.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
common/filesystem.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
common/filesystem.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
// Normally we would #include drake/common/filesystem.h prior to this header // ("include yourself first"), but we can't do that given the way the ghc // library implements separate compilation. So, we have to NOLINT it below. // Keep this sequence in sync with drake/common/filesystem.h. #if __has_include(<filesystem>) && !defined(__APPLE__) // No compilation required for std::filesystem. #else // Compile ghc::filesystem into object code. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated" #pragma GCC diagnostic ignored "-Wold-style-cast" #define GHC_FILESYSTEM_IMPLEMENTATION #include "ghc/filesystem.hpp" // NOLINT(build/include) #undef GHC_FILESYSTEM_IMPLEMENTATION #pragma GCC diagnostic pop #endif
33.545455
76
0.775068
RobotLocomotion
752a2a1c33f360e89df42e5b02fece2122c6b95c
26,965
cpp
C++
src/state_manager.cpp
cognicept-admin/rosrect_listener_Agent
d1fdc435e28d413379f6e7dd98fca4e72cf853f1
[ "BSD-3-Clause" ]
6
2020-05-07T14:26:23.000Z
2021-05-03T01:02:35.000Z
src/state_manager.cpp
cognicept-admin/error_resolution_diagnoser
6666b0597904a005ef90d0d82463544c88e6068c
[ "BSD-3-Clause" ]
1
2020-05-18T04:41:00.000Z
2020-06-04T07:03:17.000Z
src/state_manager.cpp
cognicept-admin/error_resolution_diagnoser
6666b0597904a005ef90d0d82463544c88e6068c
[ "BSD-3-Clause" ]
3
2020-09-23T03:54:39.000Z
2021-09-29T12:10:07.000Z
#include <error_resolution_diagnoser/state_manager.h> using namespace web::json; // JSON features using namespace web; // Common features like URIs. StateManager::StateManager() { // Boolean flag to decide whether to suppress a message or not this->suppress_flag = false; // Timeout parameter in minutes for alert timeout this->alert_timeout_limit = 5.0; } std::vector<std::string> StateManager::does_exist(std::string robot_code, std::string msg_text) { // Find if msg is already recorded for the given robot code std::vector<std::vector<std::string>>::const_iterator row; for (row = this->msg_data.begin(); row != this->msg_data.end(); row++) { if ((find(row->begin(), row->end(), msg_text) != row->end()) && (find(row->begin(), row->end(), robot_code) != row->end())) return *(row); } std::vector<std::string> emptyString; emptyString.push_back(""); return emptyString; } void StateManager::check_message(std::string agent_type, std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { if (agent_type == "ECS") { // std::cout << "Checking with ECS..." << std::endl; this->check_message_ecs(robot_code, data, telemetry); } else if ((agent_type == "ERT") || (agent_type == "DB")) { // std::cout << "Checking with ERT..." << std::endl; this->check_message_ert(robot_code, data, telemetry); } else { // std::cout << "Checking with ROS..." << std::endl; this->check_message_ros(robot_code, data, telemetry); } } void StateManager::check_message_ecs(std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { // Parse message to query-able format std::string msg_text = data->msg; // std::replace(msg_text.begin(), msg_text.end(), '/', ' '); // std::cout << "Querying: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // ECS has a hit, follow the message cycle // std::cout << "JSON parsed"; // msg_info = msg_info[0]; int error_level = (msg_info.at(utility::conversions::to_string_t("severity"))).as_integer(); // std::cout << "Level: " << error_level << std::endl; std::string error_msg = (msg_info.at(utility::conversions::to_string_t("error_text"))).as_string(); // std::cout << "Text: " << error_msg << std::endl; if ((error_level == 8) || (error_level == 16)) { // std::cout << "Error... " << data->msg << std::endl; // Check for suppression this->check_error(robot_code, error_msg); } else if (error_level == 4) { // std::cout << "Warning... " << data->msg << std::endl; // Check for suppression this->check_warning(robot_code, error_msg); } else { // std::cout << "Info... " << data->msg << std::endl; // Check for suppression this->check_info(robot_code, error_msg); } // Process result of event if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { // std::cout << "Not suppressed!" << std::endl; // If not suppressed, send it to event to update this->event_instance.update_log(data, msg_info, telemetry, "ECS"); // Push to stream this->api_instance.push_event_log(this->event_instance.get_log()); // Get compounding flag bool cflag = (msg_info.at(utility::conversions::to_string_t("compounding_flag"))).as_bool(); if (cflag == true) { // Nothing to do here unless it is a compounding error if ((error_level == 8) || (error_level == 16)) { // Push on ALL errors / One named Info msg // Clear only event log since this is compounding this->event_instance.clear_log(); } else { // Nothing to do } } else { // This is a compounding log, Clear everything this->clear(); } } } else { // ECS does not have a hit, normal operation resumes } } void StateManager::check_message_ert(std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { // Parse message to query-able format std::string msg_text = data->msg; // std::replace(msg_text.begin(), msg_text.end(), '/', ' '); // std::cout << "Querying: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // ECS has a hit, follow the message cycle // std::cout << "JSON parsed"; // msg_info = msg_info[0]; int error_level = (msg_info.at(utility::conversions::to_string_t("error_level"))).as_integer(); // std::cout << "Level: " << error_level << std::endl; std::string error_msg = (msg_info.at(utility::conversions::to_string_t("error_text"))).as_string(); // std::cout << "Text: " << error_msg << std::endl; if (error_level == 8) { // std::cout << "Error... " << data->msg << std::endl; // Check for suppression this->check_error(robot_code, error_msg); } else if (error_level == 4) { // std::cout << "Warning... " << data->msg << std::endl; // Check for suppression this->check_warning(robot_code, error_msg); } else { // std::cout << "Info... " << data->msg << std::endl; // Check for suppression this->check_info(robot_code, error_msg); } // Process result of event if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { // std::cout << "Not suppressed!" << std::endl; // If not suppressed, send it to event to update this->event_instance.update_log(data, msg_info, telemetry, "ERT"); // Push to stream this->api_instance.push_event_log(this->event_instance.get_log()); // Get compounding flag bool cflag = (msg_info.at(utility::conversions::to_string_t("compounding_flag"))).as_bool(); if (cflag == true) { // Nothing to do here unless it is a compounding error if (error_level == 8) { // Push on ALL errors / One named Info msg // Clear only event log since this is compounding this->event_instance.clear_log(); } else { // Nothing to do } } else { // This is a compounding log, Clear everything this->clear(); } } } else { // ECS does not have a hit, normal operation resumes } } void StateManager::check_message_ros(std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { if (data->level == 8) { // std::cout << "Error... " << data->msg << std::endl; // Check for suppression this->check_error(robot_code, data->msg); } else if (data->level == 4) { // std::cout << "Warning... " << data->msg << std::endl; // Check for suppression this->check_warning(robot_code, data->msg); } else { // std::cout << "Info... " << data->msg << std::endl; // Check for suppression this->check_info(robot_code, data->msg); } // Process result of event if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { // std::cout << "Not suppressed!" << std::endl; // If not suppressed, send it to event to update this->event_instance.update_log(data, json::value::null(), telemetry, "ROS"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); if ((data->level == 8) || (data->msg == "Goal reached")) { // Clear everything, end of event this->clear(); } else { // Clear only log this->event_instance.clear_log(); } } } void StateManager::check_error(std::string robot_code, std::string msg_text) { std::vector<std::string> found = this->does_exist(robot_code, msg_text); bool exist; if (found[0] == "") { exist = false; } else { exist = true; } if (exist) { // Found, suppress this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> msg_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data msg_details.push_back(robot_code); msg_details.push_back(msg_text); msg_details.push_back(time_str); this->msg_data.push_back(msg_details); // Do not suppress this->suppress_flag = false; } } void StateManager::check_warning(std::string robot_code, std::string msg_text) { std::vector<std::string> found = this->does_exist(robot_code, msg_text); bool exist; if (found[0] == "") { exist = false; } else { exist = true; } if (exist) { // Found, check timeout limit - not implemented yet this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> msg_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data msg_details.push_back(robot_code); msg_details.push_back(msg_text); msg_details.push_back(time_str); this->msg_data.push_back(msg_details); // Do not suppress this->suppress_flag = false; } } void StateManager::check_info(std::string robot_code, std::string msg_text) { std::vector<std::string> found = this->does_exist(robot_code, msg_text); bool exist; if (found[0] == "") { exist = false; // std::cout << "Msg found status: False" << std::endl; } else { exist = true; // std::cout << "Msg found status: True" << std::endl; } if (exist) { // Found, suppress this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> msg_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data msg_details.push_back(robot_code); msg_details.push_back(msg_text); msg_details.push_back(time_str); this->msg_data.push_back(msg_details); // Do not suppress this->suppress_flag = false; } } void StateManager::check_heartbeat(bool status, json::value telemetry) { // Pass data to backend to push appropriate status this->api_instance.push_status(status, telemetry); } void StateManager::check_diagnostic(std::string agent_type, std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // this->check_diagnostic_ros(robot_code, current_diag, telemetry); if (agent_type == "ECS") { // std::cout << "Checking with ECS..." << std::endl; this->check_diagnostic_ecs(robot_code, current_diag, telemetry); } else if ((agent_type == "ERT") || (agent_type == "DB")) { // std::cout << "Checking with ERT..." << std::endl; this->check_diagnostic_ert(robot_code, current_diag, telemetry); } else { // std::cout << "Checking with ROS..." << std::endl; this->check_diagnostic_ros(robot_code, current_diag, telemetry); } } void StateManager::check_diagnostic_ros(std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // Check diagnostic data and if not suppressed, push it to the event // Variables to store diagnostic info for state management std::string diag_str; int diag_level; std::string diag_ident; for (unsigned int idx = 0; idx < current_diag.size(); idx++) { // Store diagnostics name+hardware_id in a single string for quick search diag_str = current_diag[idx].name + "_" + current_diag[idx].hardware_id; // Diagnostics level. Main determination for state suppression diag_level = static_cast<int>(current_diag[idx].level); // std::cout << "Checking: " << diag_level << " " << diag_str << std::endl; // Check if diagnostic needs to be suppressed. All diagnostics with the same str // and no change in level are suppressed. We process only when there is change in levels. this->check_diag_data(robot_code, diag_str, std::to_string(diag_level)); if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { std::string diag_name = current_diag[idx].name; std::string diag_hwid = current_diag[idx].hardware_id; if (!diag_name.empty()) { diag_ident = diag_name; } else if (!diag_hwid.empty()) { diag_ident = diag_hwid; } // If not suppressed, send it to event to update // Construct ROS log equivalent of diag rosgraph_msgs::Log rosmsg; rosmsg.name = diag_str; if (!diag_ident.empty()) { rosmsg.msg = diag_ident + "-->" + current_diag[idx].message; } else { rosmsg.msg = current_diag[idx].message; } if (diag_level == 2) { rosmsg.level = rosmsg.ERROR; rosmsg.msg = "[ERROR] " + rosmsg.msg; } else if ((diag_level == 1) || (diag_level == 3)) { rosmsg.level = rosmsg.WARN; rosmsg.msg = "[WARN] " + rosmsg.msg; } else { rosmsg.level = rosmsg.INFO; rosmsg.msg = "[INFO] " + rosmsg.msg; } std::cout << "Diagnostic Message State Change: " << rosmsg.msg << std::endl; rosgraph_msgs::Log::ConstPtr data(new rosgraph_msgs::Log(rosmsg)); this->event_instance.update_log(data, json::value::null(), telemetry, "ROS"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); // if (data->level == 8) // { // // Clear everything, end of event // this->clear(); // } // else // { // // Clear only log // this->event_instance.clear_log(); // } } } } void StateManager::check_diagnostic_ert(std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // Check diagnostic data and if not suppressed, push it to the event // Variables to store diagnostic info for state management std::string diag_str; int diag_level; std::string diag_ident; for (unsigned int idx = 0; idx < current_diag.size(); idx++) { // Store diagnostics name+hardware_id in a single string for quick search diag_str = current_diag[idx].name + "_" + current_diag[idx].hardware_id; // Diagnostics level. Main determination for state suppression diag_level = static_cast<int>(current_diag[idx].level); // Check if diagnostic needs to be suppressed. All diagnostics with the same str // and no change in level are suppressed. We process only when there is change in levels. this->check_diag_data(robot_code, diag_str, std::to_string(diag_level)); if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { std::string diag_name = current_diag[idx].name; std::string diag_hwid = current_diag[idx].hardware_id; if (!diag_name.empty()) { diag_ident = diag_name; } else if (!diag_hwid.empty()) { diag_ident = diag_hwid; } // If not suppressed, send it to event to update // Parse message to query-able format std::string msg_text; if (!diag_ident.empty()) { msg_text = diag_ident + "-->" + current_diag[idx].message; } else { msg_text = current_diag[idx].message; } if (diag_level == 2) { msg_text = "[ERROR] " + msg_text; } else if ((diag_level == 1) || (diag_level == 3)) { msg_text = "[WARN] " + msg_text; } else { msg_text = "[INFO] " + msg_text; } std::cout << "Diagnostic Message State Change: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // Construct ROS log equivalent of diag rosgraph_msgs::Log rosmsg; rosmsg.name = diag_str; rosmsg.msg = msg_text; if (diag_level == 2) { rosmsg.level = rosmsg.ERROR; } else if ((diag_level == 1) || (diag_level == 3)) { rosmsg.level = rosmsg.WARN; } else { rosmsg.level = rosmsg.INFO; } rosgraph_msgs::Log::ConstPtr data(new rosgraph_msgs::Log(rosmsg)); this->event_instance.update_log(data, msg_info, telemetry, "ERT"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); } else { // ECS does not have a hit, normal operation resumes } // if (data->level == 8) // { // // Clear everything, end of event // this->clear(); // } // else // { // // Clear only log // this->event_instance.clear_log(); // } } } } void StateManager::check_diagnostic_ecs(std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // Check diagnostic data and if not suppressed, push it to the event // Variables to store diagnostic info for state management std::string diag_str; int diag_level; std::string diag_ident; for (unsigned int idx = 0; idx < current_diag.size(); idx++) { // Store diagnostics name+hardware_id in a single string for quick search diag_str = current_diag[idx].name + "_" + current_diag[idx].hardware_id; // Diagnostics level. Main determination for state suppression diag_level = static_cast<int>(current_diag[idx].level); // Check if diagnostic needs to be suppressed. All diagnostics with the same str // and no change in level are suppressed. We process only when there is change in levels. this->check_diag_data(robot_code, diag_str, std::to_string(diag_level)); if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { std::string diag_name = current_diag[idx].name; std::string diag_hwid = current_diag[idx].hardware_id; if (!diag_name.empty()) { diag_ident = diag_name; } else if (!diag_hwid.empty()) { diag_ident = diag_hwid; } // If not suppressed, send it to event to update // Parse message to query-able format std::string msg_text; if (!diag_ident.empty()) { msg_text = diag_ident + "-->" + current_diag[idx].message; } else { msg_text = current_diag[idx].message; } if (diag_level == 2) { msg_text = "[ERROR] " + msg_text; } else if ((diag_level == 1) || (diag_level == 3)) { msg_text = "[WARN] " + msg_text; } else { msg_text = "[INFO] " + msg_text; } std::cout << "Diagnostic Message State Change: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // Construct ROS log equivalent of diag rosgraph_msgs::Log rosmsg; rosmsg.name = diag_str; rosmsg.msg = msg_text; if (diag_level == 2) { rosmsg.level = rosmsg.ERROR; } else if ((diag_level == 1) || (diag_level == 3)) { rosmsg.level = rosmsg.WARN; } else { rosmsg.level = rosmsg.INFO; } rosgraph_msgs::Log::ConstPtr data(new rosgraph_msgs::Log(rosmsg)); this->event_instance.update_log(data, msg_info, telemetry, "ECS"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); } else { // ECS does not have a hit, normal operation resumes } // if (data->level == 8) // { // // Clear everything, end of event // this->clear(); // } // else // { // // Clear only log // this->event_instance.clear_log(); // } } } } void StateManager::check_diag_data(std::string robot_code, std::string diag_str, std::string level) { // Check if diagnostic already reported std::vector<std::string> found = this->does_diag_exist(robot_code, diag_str, level); bool exist; if (found[0] == "") { exist = false; } else { exist = true; } if (exist) { // Found, suppress this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> diag_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data diag_details.push_back(robot_code); diag_details.push_back(diag_str); diag_details.push_back(level); diag_details.push_back(time_str); this->diag_data.push_back(diag_details); // Do not suppress this->suppress_flag = false; } } std::vector<std::string> StateManager::does_diag_exist(std::string robot_code, std::string diag_str, std::string level) { // Find if diagnostic is already recorded for the given robot code at the given level std::vector<std::vector<std::string>>::const_iterator row; std::vector<std::vector<std::vector<std::string>>::const_iterator> erase_list; for (row = this->diag_data.begin(); row != this->diag_data.end(); row++) { auto found_name = find(row->begin(), row->end(), diag_str); if (found_name != row->end()) { // Found name, check for other parameters if ((find(row->begin(), row->end(), level) != row->end()) && (find(row->begin(), row->end(), robot_code) != row->end())) { // Found level as well, just return the row since it is already reported return *(row); } else { // Level not found but name is. This means state has changed. // Add row to erase list. // Will add a new row with this name downstream. erase_list.push_back(row); } } } // Erase elements for (auto element : erase_list) { this->diag_data.erase(element); } // Return empty string if no match std::vector<std::string> emptyString; emptyString.push_back(""); return emptyString; } void StateManager::clear() { // Clears the state manager data for a new session this->suppress_flag = false; this->msg_data.clear(); this->event_instance.clear(); }
31.318235
167
0.531096
cognicept-admin
752db47227df30cc728e232d1b1026633ca70523
1,234
cpp
C++
bitbots_splines_extension/src/handle/position_handle.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
bitbots_splines_extension/src/handle/position_handle.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
bitbots_splines_extension/src/handle/position_handle.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
#include "handle/position_handle.h" namespace bitbots_splines { PositionHandle::PositionHandle(std::shared_ptr<Curve> x, std::shared_ptr<Curve> y, std::shared_ptr<Curve> z) : x_(std::move(x)), y_(std::move(y)), z_(std::move(z)) { } geometry_msgs::Point PositionHandle::get_geometry_msg_position(double time) { geometry_msgs::Point msg; tf2::Vector3 tf_vec = get_position(time); msg.x = tf_vec.x(); msg.y = tf_vec.y(); msg.z = tf_vec.z(); return msg; } tf2::Vector3 PositionHandle::get_position(double time) { tf2::Vector3 pos; pos[0] = x_->position(time); pos[1] = y_->position(time); pos[2] = z_->position(time); return pos; } tf2::Vector3 PositionHandle::get_velocity(double time) { tf2::Vector3 vel; vel[0] = x_->velocity(time); vel[1] = y_->velocity(time); vel[2] = z_->velocity(time); return vel; } tf2::Vector3 PositionHandle::get_acceleration(double time) { tf2::Vector3 acc; acc[0] = x_->acceleration(time); acc[1] = y_->acceleration(time); acc[2] = z_->acceleration(time); return acc; } std::shared_ptr<Curve> PositionHandle::x() { return x_; } std::shared_ptr<Curve> PositionHandle::y() { return y_; } std::shared_ptr<Curve> PositionHandle::z() { return z_; } }
22.851852
109
0.676661
5reichar
752f29b5a05e379e520f0891f8209031df398cd3
1,130
cpp
C++
doubly_linked_list/doubly_linked_list.cpp
Khushmeet/dsa
580fcff399bf1950b7b1fd70838e091a63eac2a9
[ "MIT" ]
null
null
null
doubly_linked_list/doubly_linked_list.cpp
Khushmeet/dsa
580fcff399bf1950b7b1fd70838e091a63eac2a9
[ "MIT" ]
null
null
null
doubly_linked_list/doubly_linked_list.cpp
Khushmeet/dsa
580fcff399bf1950b7b1fd70838e091a63eac2a9
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; struct Node { int data; struct Node *next; struct Node *prev; }; struct Node *head = (struct Node *)malloc(sizeof(struct Node)); struct Node* get_new_node(int data) { Node *temp = new Node(); temp->data = data; temp->next = NULL; temp->prev = NULL; return temp; } void insert_at_0(int data) { Node *temp = get_new_node(data); if (head == NULL) { head = temp; return; } temp->next = head; head->prev = temp; head = temp; } void print() { Node *temp = head; cout << "List is "; while (temp != NULL) { cout << " " << temp->data; temp = temp->next; } cout << endl; } void print_reverse() { Node *temp = head; while(temp->next != NULL) { temp = temp->next; } cout << "List is "; while (temp != NULL) { cout << " " << temp->data; temp = temp->prev; } cout << endl; } int main() { head = NULL; insert_at_0(7); insert_at_0(0); insert_at_0(4); insert_at_0(1); print(); print_reverse(); }
15.479452
63
0.517699
Khushmeet
752fff563ecb7483027347c994bc5304477725d1
258
cpp
C++
hackerrank/practice/mathematics/fundamentals/handshake.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
hackerrank/practice/mathematics/fundamentals/handshake.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
hackerrank/practice/mathematics/fundamentals/handshake.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.hackerrank.com/challenges/handshake #include "common/stl/base.h" int main_handshake() { unsigned T; cin >> T; for (unsigned it = 0; it < T; ++it) { uint64_t n; cin >> n; cout << (n * (n - 1)) / 2 << endl; } return 0; }
17.2
50
0.550388
Loks-
75393ebccbc3603325e492b4e136b3e73182bc82
2,387
cpp
C++
dataserver/src/storage/processor_data_sample.cpp
jimdb-org/jimdb
927e4447879189597dbe7f91a7fe0e8865107ef4
[ "Apache-2.0" ]
59
2020-01-10T06:27:12.000Z
2021-12-16T06:37:36.000Z
dataserver/src/storage/processor_data_sample.cpp
jimdb-org/jimdb
927e4447879189597dbe7f91a7fe0e8865107ef4
[ "Apache-2.0" ]
null
null
null
dataserver/src/storage/processor_data_sample.cpp
jimdb-org/jimdb
927e4447879189597dbe7f91a7fe0e8865107ef4
[ "Apache-2.0" ]
3
2020-02-13T05:04:20.000Z
2020-06-29T01:07:48.000Z
// Copyright 2019 The JIMDB 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 "processor_data_sample.h" #include <chrono> namespace jim { namespace ds { namespace storage { DataSample::DataSample(const dspb::DataSample & data_sample, const dspb::KeyRange & range_default, Store & s, bool gather_trace ) : str_last_key_(""), over_(false), range_default_(range_default), key_schema_( s.GetKeySchema()), row_fetcher_(new RowFetcher( s, data_sample, range_default.start_key(), range_default.end_key())) { gather_trace_ = gather_trace; for (const auto & col : data_sample.columns()) { col_ids.push_back(col.id()); } } DataSample::~DataSample() { } const std::string DataSample::get_last_key() { return str_last_key_; } Status DataSample::next( RowResult & row) { Status s; if (over_) { return Status( Status::kNoMoreData, " last key: ", EncodeToHexString(get_last_key()) ); } std::chrono::system_clock::time_point time_begin; if (gather_trace_) { time_begin = std::chrono::system_clock::now(); } s = row_fetcher_->Next( row, over_); if (over_ && s.ok()) { s = Status( Status::kNoMoreData, " last key: ", EncodeToHexString(get_last_key()) ); } if (s.ok()) { str_last_key_ = row.GetKey(); } if (gather_trace_) { ++rows_count_; time_processed_ns_ += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - time_begin).count(); } return s; } const std::vector<uint64_t> DataSample::get_col_ids() { return col_ids; } void DataSample::get_stats(std::vector<ProcessorStat> &stats) { stats.emplace_back(rows_count_, time_processed_ns_); } } /* namespace storage */ } /* namespace ds */ } /* namespace jim */
26.230769
138
0.661919
jimdb-org
753a78fefd48383246b2b7bf9549887fa5cbb79d
32,746
cpp
C++
indra/newview/llcallingcard.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/llcallingcard.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/newview/llcallingcard.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llcallingcard.cpp * @brief Implementation of the LLPreviewCallingCard class * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #if LL_WINDOWS #pragma warning( disable : 4800 ) // performance warning in <functional> #endif #include "llcallingcard.h" #include <algorithm> #include "indra_constants.h" //#include "llcachename.h" #include "llstl.h" #include "lltimer.h" #include "lluuid.h" #include "message.h" #include "llagent.h" #include "llavatarnamecache.h" #include "llinventoryobserver.h" #include "llinventorymodel.h" #include "llnotifications.h" #include "llslurl.h" #include "llimview.h" #include "lltrans.h" #include "llviewercontrol.h" #include "llviewerobjectlist.h" #include "llvoavatar.h" #include "llavataractions.h" // Firestorm includes #include "fscommon.h" #include "fsfloaternearbychat.h" #include "fskeywords.h" #include "lggcontactsets.h" #include "llfloaterreg.h" #include "llnotificationmanager.h" ///---------------------------------------------------------------------------- /// Local function declarations, constants, enums, and typedefs ///---------------------------------------------------------------------------- class LLTrackingData { public: LLTrackingData(const LLUUID& avatar_id, const std::string& name); bool haveTrackingInfo(); void setTrackedCoarseLocation(const LLVector3d& global_pos); void agentFound(const LLUUID& prey, const LLVector3d& estimated_global_pos); public: LLUUID mAvatarID; std::string mName; LLVector3d mGlobalPositionEstimate; bool mHaveInfo; bool mHaveCoarseInfo; LLTimer mCoarseLocationTimer; LLTimer mUpdateTimer; LLTimer mAgentGone; }; const F32 COARSE_FREQUENCY = 2.2f; const F32 FIND_FREQUENCY = 29.7f; // This results in a database query, so cut these back const F32 OFFLINE_SECONDS = FIND_FREQUENCY + 8.0f; // static LLAvatarTracker LLAvatarTracker::sInstance; static void on_avatar_name_cache_notify(const LLUUID& agent_id, const LLAvatarName& av_name, bool online, LLSD payload); ///---------------------------------------------------------------------------- /// Class LLAvatarTracker ///---------------------------------------------------------------------------- LLAvatarTracker::LLAvatarTracker() : mTrackingData(NULL), mTrackedAgentValid(false), mModifyMask(0x0), mIsNotifyObservers(FALSE) { } LLAvatarTracker::~LLAvatarTracker() { deleteTrackingData(); std::for_each(mObservers.begin(), mObservers.end(), DeletePointer()); mObservers.clear(); std::for_each(mBuddyInfo.begin(), mBuddyInfo.end(), DeletePairedPointer()); mBuddyInfo.clear(); } void LLAvatarTracker::track(const LLUUID& avatar_id, const std::string& name) { deleteTrackingData(); mTrackedAgentValid = false; mTrackingData = new LLTrackingData(avatar_id, name); findAgent(); // We track here because findAgent() is called on a timer (for now). if(avatar_id.notNull()) { LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_TrackAgent); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->nextBlockFast(_PREHASH_TargetData); msg->addUUIDFast(_PREHASH_PreyID, avatar_id); gAgent.sendReliableMessage(); } } void LLAvatarTracker::untrack(const LLUUID& avatar_id) { if (mTrackingData && mTrackingData->mAvatarID == avatar_id) { deleteTrackingData(); mTrackedAgentValid = false; LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_TrackAgent); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->nextBlockFast(_PREHASH_TargetData); msg->addUUIDFast(_PREHASH_PreyID, LLUUID::null); gAgent.sendReliableMessage(); } } void LLAvatarTracker::setTrackedCoarseLocation(const LLVector3d& global_pos) { if(mTrackingData) { mTrackingData->setTrackedCoarseLocation(global_pos); } } bool LLAvatarTracker::haveTrackingInfo() { if(mTrackingData) { return mTrackingData->haveTrackingInfo(); } return false; } LLVector3d LLAvatarTracker::getGlobalPos() { if(!mTrackedAgentValid || !mTrackingData) return LLVector3d(); LLVector3d global_pos; LLViewerObject* object = gObjectList.findObject(mTrackingData->mAvatarID); if(object && !object->isDead()) { global_pos = object->getPositionGlobal(); // HACK - for making the tracker point above the avatar's head // rather than its groin LLVOAvatar* av = (LLVOAvatar*)object; global_pos.mdV[VZ] += 0.7f * (av->mBodySize.mV[VZ] + av->mAvatarOffset.mV[VZ]); mTrackingData->mGlobalPositionEstimate = global_pos; } else { global_pos = mTrackingData->mGlobalPositionEstimate; } return global_pos; } void LLAvatarTracker::getDegreesAndDist(F32& rot, F64& horiz_dist, F64& vert_dist) { if(!mTrackingData) return; LLVector3d global_pos; LLViewerObject* object = gObjectList.findObject(mTrackingData->mAvatarID); if(object && !object->isDead()) { global_pos = object->getPositionGlobal(); mTrackingData->mGlobalPositionEstimate = global_pos; } else { global_pos = mTrackingData->mGlobalPositionEstimate; } LLVector3d to_vec = global_pos - gAgent.getPositionGlobal(); horiz_dist = sqrt(to_vec.mdV[VX] * to_vec.mdV[VX] + to_vec.mdV[VY] * to_vec.mdV[VY]); vert_dist = to_vec.mdV[VZ]; rot = F32(RAD_TO_DEG * atan2(to_vec.mdV[VY], to_vec.mdV[VX])); } const std::string& LLAvatarTracker::getName() { if(mTrackingData) { return mTrackingData->mName; } else { return LLStringUtil::null; } } const LLUUID& LLAvatarTracker::getAvatarID() { if(mTrackingData) { return mTrackingData->mAvatarID; } else { return LLUUID::null; } } S32 LLAvatarTracker::addBuddyList(const LLAvatarTracker::buddy_map_t& buds) { using namespace std; U32 new_buddy_count = 0; LLUUID agent_id; for(buddy_map_t::const_iterator itr = buds.begin(); itr != buds.end(); ++itr) { agent_id = (*itr).first; buddy_map_t::const_iterator existing_buddy = mBuddyInfo.find(agent_id); if(existing_buddy == mBuddyInfo.end()) { ++new_buddy_count; mBuddyInfo[agent_id] = (*itr).second; // pre-request name for notifications? LLAvatarName av_name; LLAvatarNameCache::get(agent_id, &av_name); addChangedMask(LLFriendObserver::ADD, agent_id); LL_DEBUGS() << "Added buddy " << agent_id << ", " << (mBuddyInfo[agent_id]->isOnline() ? "Online" : "Offline") << ", TO: " << mBuddyInfo[agent_id]->getRightsGrantedTo() << ", FROM: " << mBuddyInfo[agent_id]->getRightsGrantedFrom() << LL_ENDL; } else { LLRelationship* e_r = (*existing_buddy).second; LLRelationship* n_r = (*itr).second; LL_WARNS() << "!! Add buddy for existing buddy: " << agent_id << " [" << (e_r->isOnline() ? "Online" : "Offline") << "->" << (n_r->isOnline() ? "Online" : "Offline") << ", " << e_r->getRightsGrantedTo() << "->" << n_r->getRightsGrantedTo() << ", " << e_r->getRightsGrantedTo() << "->" << n_r->getRightsGrantedTo() << "]" << LL_ENDL; } } // do not notify observers here - list can be large so let it be done on idle. return new_buddy_count; } void LLAvatarTracker::copyBuddyList(buddy_map_t& buddies) const { buddy_map_t::const_iterator it = mBuddyInfo.begin(); buddy_map_t::const_iterator end = mBuddyInfo.end(); for(; it != end; ++it) { buddies[(*it).first] = (*it).second; } } void LLAvatarTracker::terminateBuddy(const LLUUID& id) { LL_DEBUGS() << "LLAvatarTracker::terminateBuddy()" << LL_ENDL; LLRelationship* buddy = get_ptr_in_map(mBuddyInfo, id); if(!buddy) return; mBuddyInfo.erase(id); LLMessageSystem* msg = gMessageSystem; msg->newMessage("TerminateFriendship"); msg->nextBlock("AgentData"); msg->addUUID("AgentID", gAgent.getID()); msg->addUUID("SessionID", gAgent.getSessionID()); msg->nextBlock("ExBlock"); msg->addUUID("OtherID", id); gAgent.sendReliableMessage(); addChangedMask(LLFriendObserver::REMOVE, id); delete buddy; } // get all buddy info const LLRelationship* LLAvatarTracker::getBuddyInfo(const LLUUID& id) const { if(id.isNull()) return NULL; return get_ptr_in_map(mBuddyInfo, id); } bool LLAvatarTracker::isBuddy(const LLUUID& id) const { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); return (info != NULL); } // online status void LLAvatarTracker::setBuddyOnline(const LLUUID& id, bool is_online) { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { info->online(is_online); addChangedMask(LLFriendObserver::ONLINE, id); LL_DEBUGS() << "Set buddy " << id << (is_online ? " Online" : " Offline") << LL_ENDL; } else { //<FS:LO> Fix possible log spam with a large friendslist when SL messes up. //LL_WARNS() << "!! No buddy info found for " << id LL_DEBUGS() << "!! No buddy info found for " << id << ", setting to " << (is_online ? "Online" : "Offline") << LL_ENDL; //</FS:LO> } } bool LLAvatarTracker::isBuddyOnline(const LLUUID& id) const { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { return info->isOnline(); } return false; } // empowered status void LLAvatarTracker::setBuddyEmpowered(const LLUUID& id, bool is_empowered) { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { info->grantRights(LLRelationship::GRANT_MODIFY_OBJECTS, 0); mModifyMask |= LLFriendObserver::POWERS; } } bool LLAvatarTracker::isBuddyEmpowered(const LLUUID& id) const { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { return info->isRightGrantedTo(LLRelationship::GRANT_MODIFY_OBJECTS); } return false; } void LLAvatarTracker::empower(const LLUUID& id, bool grant) { // wrapper for ease of use in some situations. buddy_map_t list; /* list.insert(id); empowerList(list, grant); */ } void LLAvatarTracker::empowerList(const buddy_map_t& list, bool grant) { LL_WARNS() << "LLAvatarTracker::empowerList() not implemented." << LL_ENDL; /* LLMessageSystem* msg = gMessageSystem; const char* message_name; const char* block_name; const char* field_name; if(grant) { message_name = _PREHASH_GrantModification; block_name = _PREHASH_EmpoweredBlock; field_name = _PREHASH_EmpoweredID; } else { message_name = _PREHASH_RevokeModification; block_name = _PREHASH_RevokedBlock; field_name = _PREHASH_RevokedID; } std::string name; gAgent.buildFullnameAndTitle(name); bool start_new_message = true; buddy_list_t::const_iterator it = list.begin(); buddy_list_t::const_iterator end = list.end(); for(; it != end; ++it) { if(NULL == get_ptr_in_map(mBuddyInfo, (*it))) continue; setBuddyEmpowered((*it), grant); if(start_new_message) { start_new_message = false; msg->newMessageFast(message_name); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->addStringFast(_PREHASH_GranterName, name); } msg->nextBlockFast(block_name); msg->addUUIDFast(field_name, (*it)); if(msg->isSendFullFast(block_name)) { start_new_message = true; gAgent.sendReliableMessage(); } } if(!start_new_message) { gAgent.sendReliableMessage(); } */ } void LLAvatarTracker::deleteTrackingData() { //make sure mTrackingData never points to freed memory LLTrackingData* tmp = mTrackingData; mTrackingData = NULL; delete tmp; } void LLAvatarTracker::findAgent() { if (!mTrackingData) return; if (mTrackingData->mAvatarID.isNull()) return; LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_FindAgent); // Request msg->nextBlockFast(_PREHASH_AgentBlock); msg->addUUIDFast(_PREHASH_Hunter, gAgentID); msg->addUUIDFast(_PREHASH_Prey, mTrackingData->mAvatarID); msg->addU32Fast(_PREHASH_SpaceIP, 0); // will get filled in by simulator msg->nextBlockFast(_PREHASH_LocationBlock); const F64 NO_LOCATION = 0.0; msg->addF64Fast(_PREHASH_GlobalX, NO_LOCATION); msg->addF64Fast(_PREHASH_GlobalY, NO_LOCATION); gAgent.sendReliableMessage(); } void LLAvatarTracker::addObserver(LLFriendObserver* observer) { if(observer) { mObservers.push_back(observer); } } void LLAvatarTracker::removeObserver(LLFriendObserver* observer) { mObservers.erase( std::remove(mObservers.begin(), mObservers.end(), observer), mObservers.end()); } void LLAvatarTracker::idleNotifyObservers() { if (mModifyMask == LLFriendObserver::NONE && mChangedBuddyIDs.size() == 0) { return; } notifyObservers(); } void LLAvatarTracker::notifyObservers() { if (mIsNotifyObservers) { // Don't allow multiple calls. // new masks and ids will be processed later from idle. return; } mIsNotifyObservers = TRUE; observer_list_t observers(mObservers); observer_list_t::iterator it = observers.begin(); observer_list_t::iterator end = observers.end(); for(; it != end; ++it) { (*it)->changed(mModifyMask); } for (changed_buddy_t::iterator it = mChangedBuddyIDs.begin(); it != mChangedBuddyIDs.end(); it++) { notifyParticularFriendObservers(*it); } mModifyMask = LLFriendObserver::NONE; mChangedBuddyIDs.clear(); mIsNotifyObservers = FALSE; } void LLAvatarTracker::addParticularFriendObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.notNull() && observer) mParticularFriendObserverMap[buddy_id].insert(observer); } void LLAvatarTracker::removeParticularFriendObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.isNull() || !observer) return; observer_map_t::iterator obs_it = mParticularFriendObserverMap.find(buddy_id); if(obs_it == mParticularFriendObserverMap.end()) return; obs_it->second.erase(observer); // purge empty sets from the map // AO: Remove below check as last resort to resolve a crash from dangling pointer. // TODO: clean up all observers and don't leave dangling pointers here. if (obs_it->second.size() == 0) mParticularFriendObserverMap.erase(obs_it); } void LLAvatarTracker::notifyParticularFriendObservers(const LLUUID& buddy_id) { observer_map_t::iterator obs_it = mParticularFriendObserverMap.find(buddy_id); if(obs_it == mParticularFriendObserverMap.end()) return; // Notify observers interested in buddy_id. // <FS:ND> FIRE-6077; FIRE-6227; FIRE-6431; SUP-9654; make a copy of observer_set. Just in case some implementation of changed() calls add/remove...Observer // observer_set_t& obs = obs_it->second; observer_set_t obs = obs_it->second; // </FS:ND: for (observer_set_t::iterator ob_it = obs.begin(); ob_it != obs.end(); ob_it++) { (*ob_it)->changed(mModifyMask); // <FS:ND/> Paranoia check. Of course someone could add x observer than add the same amount of x. That won't be found by comparing size alone, but it is good enough for a quick test llassert( obs.size() == obs_it->second.size() ); } } void LLAvatarTracker::addFriendPermissionObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.notNull() && observer) { mFriendPermissionObserverMap[buddy_id].insert(observer); } } void LLAvatarTracker::removeFriendPermissionObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.isNull() || !observer) return; observer_map_t::iterator obs_it = mFriendPermissionObserverMap.find(buddy_id); if(obs_it == mFriendPermissionObserverMap.end()) return; obs_it->second.erase(observer); // purge empty sets from the map if (obs_it->second.size() == 0) mFriendPermissionObserverMap.erase(obs_it); } void LLAvatarTracker::notifyFriendPermissionObservers(const LLUUID& buddy_id) { observer_map_t::iterator obs_it = mFriendPermissionObserverMap.find(buddy_id); if(obs_it == mFriendPermissionObserverMap.end()) { return; } // Notify observers interested in buddy_id. // <FS:ND> FIRE-6077; FIRE-6227; FIRE-6431; SUP-9654; make a copy of observer_set. Just in case some implementation of changed() calls add/remove...Observer // observer_set_t& obs = obs_it->second; observer_set_t obs = obs_it->second; // </FS:ND> for (observer_set_t::iterator ob_it = obs.begin(); ob_it != obs.end(); ob_it++) { (*ob_it)->changed(LLFriendObserver::PERMS); // <FS:ND/> Paranoia check. Of course someone could add x observer than add the same amount of x. That won't be found by comparing size alone, but it is good enough for a quick test llassert( obs.size() == obs_it->second.size() ); } } // store flag for change // and id of object change applies to void LLAvatarTracker::addChangedMask(U32 mask, const LLUUID& referent) { mModifyMask |= mask; if (referent.notNull()) { mChangedBuddyIDs.insert(referent); } } void LLAvatarTracker::applyFunctor(LLRelationshipFunctor& f) { buddy_map_t::iterator it = mBuddyInfo.begin(); buddy_map_t::iterator end = mBuddyInfo.end(); for(; it != end; ++it) { f((*it).first, (*it).second); } } void LLAvatarTracker::registerCallbacks(LLMessageSystem* msg) { msg->setHandlerFuncFast(_PREHASH_FindAgent, processAgentFound); msg->setHandlerFuncFast(_PREHASH_OnlineNotification, processOnlineNotification); msg->setHandlerFuncFast(_PREHASH_OfflineNotification, processOfflineNotification); //msg->setHandlerFuncFast(_PREHASH_GrantedProxies, // processGrantedProxies); msg->setHandlerFunc("TerminateFriendship", processTerminateFriendship); msg->setHandlerFunc(_PREHASH_ChangeUserRights, processChangeUserRights); } // static void LLAvatarTracker::processAgentFound(LLMessageSystem* msg, void**) { LLUUID id; msg->getUUIDFast(_PREHASH_AgentBlock, _PREHASH_Hunter, id); msg->getUUIDFast(_PREHASH_AgentBlock, _PREHASH_Prey, id); // *FIX: should make sure prey id matches. LLVector3d estimated_global_pos; msg->getF64Fast(_PREHASH_LocationBlock, _PREHASH_GlobalX, estimated_global_pos.mdV[VX]); msg->getF64Fast(_PREHASH_LocationBlock, _PREHASH_GlobalY, estimated_global_pos.mdV[VY]); LLAvatarTracker::instance().agentFound(id, estimated_global_pos); } void LLAvatarTracker::agentFound(const LLUUID& prey, const LLVector3d& estimated_global_pos) { if(!mTrackingData) return; //if we get a valid reply from the server, that means the agent //is our friend and mappable, so enable interest list based updates LLAvatarTracker::instance().setTrackedAgentValid(true); mTrackingData->agentFound(prey, estimated_global_pos); } // static void LLAvatarTracker::processOnlineNotification(LLMessageSystem* msg, void**) { LL_DEBUGS() << "LLAvatarTracker::processOnlineNotification()" << LL_ENDL; instance().processNotify(msg, true); } // static void LLAvatarTracker::processOfflineNotification(LLMessageSystem* msg, void**) { LL_DEBUGS() << "LLAvatarTracker::processOfflineNotification()" << LL_ENDL; instance().processNotify(msg, false); } void LLAvatarTracker::processChange(LLMessageSystem* msg) { S32 count = msg->getNumberOfBlocksFast(_PREHASH_Rights); LLUUID agent_id, agent_related; S32 new_rights; msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id); for(int i = 0; i < count; ++i) { msg->getUUIDFast(_PREHASH_Rights, _PREHASH_AgentRelated, agent_related, i); msg->getS32Fast(_PREHASH_Rights,_PREHASH_RelatedRights, new_rights, i); if(agent_id == gAgent.getID()) { if(mBuddyInfo.find(agent_related) != mBuddyInfo.end()) { (mBuddyInfo[agent_related])->setRightsTo(new_rights); // I'm not totally sure why it adds the agents id to the changed list // nor why it doesn't add the friends's ID. // Add the friend's id to the changed list for contacts list -KC mChangedBuddyIDs.insert(agent_related); } } else { if(mBuddyInfo.find(agent_id) != mBuddyInfo.end()) { if((mBuddyInfo[agent_id]->getRightsGrantedFrom() ^ new_rights) & LLRelationship::GRANT_MODIFY_OBJECTS) { LLSD args; // <FS:Ansariel> Always show complete name in rights dialogs //args["NAME"] = LLSLURL("agent", agent_id, "displayname").getSLURLString(); args["NAME"] = LLSLURL("agent", agent_id, "completename").getSLURLString(); LLSD payload; payload["from_id"] = agent_id; if(LLRelationship::GRANT_MODIFY_OBJECTS & new_rights) { LLNotifications::instance().add("GrantedModifyRights",args, payload); } else { LLNotifications::instance().add("RevokedModifyRights",args, payload); } } // <FS:Ansariel> Online status right apparently only provided as part of login response in idle_startup (response["buddy-list"]), // so we can only keep current grant new_rights = new_rights | (mBuddyInfo[agent_id]->getRightsGrantedFrom() & LLRelationship::GRANT_ONLINE_STATUS); (mBuddyInfo[agent_id])->setRightsFrom(new_rights); } } } addChangedMask(LLFriendObserver::POWERS, agent_id); notifyObservers(); notifyFriendPermissionObservers(agent_related); } void LLAvatarTracker::processChangeUserRights(LLMessageSystem* msg, void**) { LL_DEBUGS() << "LLAvatarTracker::processChangeUserRights()" << LL_ENDL; instance().processChange(msg); } void LLAvatarTracker::processNotify(LLMessageSystem* msg, bool online) { S32 count = msg->getNumberOfBlocksFast(_PREHASH_AgentBlock); // <FS:PP> Attempt to speed up things a little // BOOL chat_notify = gSavedSettings.getBOOL("ChatOnlineNotification"); static LLCachedControl<bool> ChatOnlineNotification(gSavedSettings, "ChatOnlineNotification"); BOOL chat_notify = ChatOnlineNotification; // </FS:PP> LL_DEBUGS() << "Received " << count << " online notifications **** " << LL_ENDL; if(count > 0) { LLUUID agent_id; const LLRelationship* info = NULL; LLUUID tracking_id; if(mTrackingData) { tracking_id = mTrackingData->mAvatarID; } LLSD payload; for(S32 i = 0; i < count; ++i) { msg->getUUIDFast(_PREHASH_AgentBlock, _PREHASH_AgentID, agent_id, i); payload["FROM_ID"] = agent_id; info = getBuddyInfo(agent_id); if(info) { setBuddyOnline(agent_id,online); } else { LL_WARNS() << "Received online notification for unknown buddy: " << agent_id << " is " << (online ? "ONLINE" : "OFFLINE") << LL_ENDL; } if(tracking_id == agent_id) { // we were tracking someone who went offline deleteTrackingData(); } // *TODO: get actual inventory id gInventory.addChangedMask(LLInventoryObserver::CALLING_CARD, LLUUID::null); } //[FIX FIRE-3522 : SJ] Notify Online/Offline to Nearby Chat even if chat_notify isnt true // <FS:PP> Attempt to speed up things a little // if(chat_notify||LGGContactSets::getInstance()->notifyForFriend(agent_id)||gSavedSettings.getBOOL("OnlineOfflinetoNearbyChat")) static LLCachedControl<bool> OnlineOfflinetoNearbyChat(gSavedSettings, "OnlineOfflinetoNearbyChat"); if(chat_notify || LGGContactSets::getInstance()->notifyForFriend(agent_id) || OnlineOfflinetoNearbyChat) // </FS:PP> { // Look up the name of this agent for the notification LLAvatarNameCache::get(agent_id,boost::bind(&on_avatar_name_cache_notify,_1, _2, online, payload)); } mModifyMask |= LLFriendObserver::ONLINE; instance().notifyObservers(); gInventory.notifyObservers(); } } static void on_avatar_name_cache_notify(const LLUUID& agent_id, const LLAvatarName& av_name, bool online, LLSD payload) { // Popup a notify box with online status of this agent // Use display name only because this user is your friend LLSD args; // <FS:Ansariel> Make name clickable // args["NAME"] = av_name.getDisplayName(); std::string used_name = FSCommon::getAvatarNameByDisplaySettings(av_name); args["NAME"] = used_name; // </FS:Ansariel> args["STATUS"] = online ? LLTrans::getString("OnlineStatus") : LLTrans::getString("OfflineStatus"); args["AGENT-ID"] = agent_id; LLNotificationPtr notification; if (online) { make_ui_sound("UISndFriendOnline"); // <FS:PP> FIRE-2731: Online/offline sound alert for friends notification = LLNotifications::instance().add("FriendOnlineOffline", args, payload.with("respond_on_mousedown", TRUE), boost::bind(&LLAvatarActions::startIM, agent_id)); } else { make_ui_sound("UISndFriendOffline"); // <FS:PP> FIRE-2731: Online/offline sound alert for friends notification = LLNotifications::instance().add("FriendOnlineOffline", args, payload); } // If there's an open IM session with this agent, send a notification there too. LLUUID session_id = LLIMMgr::computeSessionID(IM_NOTHING_SPECIAL, agent_id); std::string notify_msg = notification->getMessage(); LLIMModel::instance().proccessOnlineOfflineNotification(session_id, notify_msg); // If desired, also send it to nearby chat, this allows friends' // online/offline times to be referenced in chat & logged. // [FIRE-3522 : SJ] Only show Online/Offline toast for groups which have enabled "Show notice for this set" and in the settingpage of CS is checked that the messages need to be in Toasts // or for groups which have enabled "Show notice for this set" and in the settingpage of CS is checked that the messages need to be in Nearby Chat static LLCachedControl<bool> OnlineOfflinetoNearbyChat(gSavedSettings, "OnlineOfflinetoNearbyChat"); static LLCachedControl<bool> FSContactSetsNotificationNearbyChat(gSavedSettings, "FSContactSetsNotificationNearbyChat"); if ((OnlineOfflinetoNearbyChat) || (FSContactSetsNotificationNearbyChat && LGGContactSets::getInstance()->notifyForFriend(agent_id))) { static LLCachedControl<bool> history_only(gSavedSettings, "OnlineOfflinetoNearbyChatHistory"); // LO - Adding a setting to show online/offline notices only in chat history. Helps prevent your screen from being filled with online notices on login. LLChat chat; chat.mText = (online ? LLTrans::getString("FriendOnlineNotification") : LLTrans::getString("FriendOfflineNotification")); chat.mSourceType = CHAT_SOURCE_SYSTEM; chat.mChatType = CHAT_TYPE_RADAR; chat.mFromID = agent_id; chat.mFromName = used_name; if (history_only) { FSFloaterNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<FSFloaterNearbyChat>("fs_nearby_chat", LLSD()); nearby_chat->addMessage(chat, true, LLSD()); } else { LLNotificationsUI::LLNotificationManager::instance().onChat(chat, args); } // <FS:PP> FIRE-10178: Keyword Alerts in group IM do not work unless the group is in the foreground (notification on receipt of IM) chat.mText = notify_msg; if (FSKeywords::getInstance()->chatContainsKeyword(chat, true)) { FSKeywords::notify(chat); } // </FS:PP> } } void LLAvatarTracker::formFriendship(const LLUUID& id) { if(id.notNull()) { LLRelationship* buddy_info = get_ptr_in_map(instance().mBuddyInfo, id); if(!buddy_info) { LLAvatarTracker& at = LLAvatarTracker::instance(); //The default for relationship establishment is to have both parties //visible online to each other. buddy_info = new LLRelationship(LLRelationship::GRANT_ONLINE_STATUS,LLRelationship::GRANT_ONLINE_STATUS, false); at.mBuddyInfo[id] = buddy_info; at.addChangedMask(LLFriendObserver::ADD, id); at.notifyObservers(); } } } void LLAvatarTracker::processTerminateFriendship(LLMessageSystem* msg, void**) { LLUUID id; msg->getUUID("ExBlock", "OtherID", id); if(id.notNull()) { LLAvatarTracker& at = LLAvatarTracker::instance(); LLRelationship* buddy = get_ptr_in_map(at.mBuddyInfo, id); if(!buddy) return; at.mBuddyInfo.erase(id); at.addChangedMask(LLFriendObserver::REMOVE, id); delete buddy; at.notifyObservers(); } } ///---------------------------------------------------------------------------- /// Tracking Data ///---------------------------------------------------------------------------- LLTrackingData::LLTrackingData(const LLUUID& avatar_id, const std::string& name) : mAvatarID(avatar_id), mHaveInfo(false), mHaveCoarseInfo(false) { mCoarseLocationTimer.setTimerExpirySec(COARSE_FREQUENCY); mUpdateTimer.setTimerExpirySec(FIND_FREQUENCY); mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); if(!name.empty()) { mName = name; } } void LLTrackingData::agentFound(const LLUUID& prey, const LLVector3d& estimated_global_pos) { if(prey != mAvatarID) { LL_WARNS() << "LLTrackingData::agentFound() - found " << prey << " but looking for " << mAvatarID << LL_ENDL; } mHaveInfo = true; mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); mGlobalPositionEstimate = estimated_global_pos; } bool LLTrackingData::haveTrackingInfo() { LLViewerObject* object = gObjectList.findObject(mAvatarID); if(object && !object->isDead()) { mCoarseLocationTimer.checkExpirationAndReset(COARSE_FREQUENCY); mUpdateTimer.setTimerExpirySec(FIND_FREQUENCY); mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); mHaveInfo = true; return true; } if(mHaveCoarseInfo && !mCoarseLocationTimer.checkExpirationAndReset(COARSE_FREQUENCY)) { // if we reach here, then we have a 'recent' coarse update mUpdateTimer.setTimerExpirySec(FIND_FREQUENCY); mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); return true; } if(mUpdateTimer.checkExpirationAndReset(FIND_FREQUENCY)) { LLAvatarTracker::instance().findAgent(); mHaveCoarseInfo = false; } if(mAgentGone.checkExpirationAndReset(OFFLINE_SECONDS)) { mHaveInfo = false; mHaveCoarseInfo = false; } return mHaveInfo; } void LLTrackingData::setTrackedCoarseLocation(const LLVector3d& global_pos) { mCoarseLocationTimer.setTimerExpirySec(COARSE_FREQUENCY); mGlobalPositionEstimate = global_pos; mHaveInfo = true; mHaveCoarseInfo = true; } ///---------------------------------------------------------------------------- // various buddy functors ///---------------------------------------------------------------------------- bool LLCollectProxyBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { if(buddy->isRightGrantedFrom(LLRelationship::GRANT_MODIFY_OBJECTS)) { mProxy.insert(buddy_id); } return true; } bool LLCollectMappableBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { LLAvatarName av_name; LLAvatarNameCache::get( buddy_id, &av_name); buddy_map_t::value_type value(buddy_id, av_name.getDisplayName()); if(buddy->isOnline() && buddy->isRightGrantedFrom(LLRelationship::GRANT_MAP_LOCATION)) { // <FS:Ansariel> Friend names on worldmap should respect display name settings //mMappable.insert(value); // <FS:PP> Attempt to speed up things a little // if (LLAvatarNameCache::useDisplayNames() && gSavedSettings.getBOOL("NameTagShowUsernames")) static LLCachedControl<bool> NameTagShowUsernames(gSavedSettings, "NameTagShowUsernames"); if (LLAvatarName::useDisplayNames() && NameTagShowUsernames) // </FS:PP> { buddy_map_t::value_type value(buddy_id, av_name.getCompleteName()); mMappable.insert(value); } else { buddy_map_t::value_type value(buddy_id, av_name.getDisplayName()); mMappable.insert(value); } // </FS:Ansariel> } return true; } bool LLCollectOnlineBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { LLAvatarName av_name; LLAvatarNameCache::get(buddy_id, &av_name); mFullName = av_name.getUserName(); buddy_map_t::value_type value(buddy_id, mFullName); if(buddy->isOnline()) { mOnline.insert(value); } return true; } bool LLCollectAllBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { LLAvatarName av_name; LLAvatarNameCache::get(buddy_id, &av_name); // <FS:Ansariel> FIRE-13756: Friends avatar picker only shows display name //mFullName = av_name.getDisplayName(); mFullName = FSCommon::getAvatarNameByDisplaySettings(av_name); // </FS:Ansariel> buddy_map_t::value_type value(buddy_id, mFullName); if(buddy->isOnline()) { mOnline.insert(value); } else { mOffline.insert(value); } return true; }
30.32037
248
0.719966
SaladDais
753acc92fb7bcfa2bc75b5a5260671e628e0ce24
8,866
cpp
C++
x86/vm/ops/store.cpp
zero-rp/ZVM
66319025a4dfff813e580f68a0183841de9a72cd
[ "MIT" ]
9
2019-03-08T07:56:12.000Z
2021-03-06T01:57:43.000Z
x86/vm/ops/store.cpp
zero-rp/ZVM
66319025a4dfff813e580f68a0183841de9a72cd
[ "MIT" ]
null
null
null
x86/vm/ops/store.cpp
zero-rp/ZVM
66319025a4dfff813e580f68a0183841de9a72cd
[ "MIT" ]
2
2019-03-16T12:47:05.000Z
2019-09-15T15:03:50.000Z
/** Copyright (c) 2007 - 2010 Jordan "Earlz/hckr83" Earls <http://www.Earlz.biz.tm> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This file is part of the x86Lib project. **/ #include <x86lib.h> namespace x86Lib { using namespace std; void x86CPU::op_mov_r8_imm8() { //0xB0+r SetReg8(opbyte - 0xB0, ReadCode8(1)); eip++; } void x86CPU::op_mov_rW_immW() { //0xB8+r SetReg(opbyte - 0xB8, ReadCodeW(1)); eip += OperandSize(); } void x86CPU::op_mov_sr_rm16() { //0x8E ModRM rm(this); //need ModRM for parsing, but otherwise it's a no-op } void x86CPU::op_mov_rm16_sr() { //0x8C ModRM rm(this); rm.WriteWord(0); } void x86CPU::op_mov_rW_rmW() { ModRM rm(this); SetReg(rm.GetExtra(), rm.ReadW()); } void x86CPU::op_mov_rmW_rW() { ModRM rm(this); rm.WriteW(Reg(rm.GetExtra())); } void x86CPU::op_mov_al_m8() { SetReg8(AL, ReadByteA(DS, ImmA())); } void x86CPU::op_mov_axW_mW() { SetReg(AX, ReadWA(DS, ImmA())); } void x86CPU::op_mov_rm8_r8() { ModRM rm(this); rm.WriteByte(Reg8(rm.GetExtra())); } void x86CPU::op_mov_r8_rm8() { ModRM rm(this); SetReg8(rm.GetExtra(), rm.ReadByte()); } void x86CPU::op_mov_m8_al() { WriteByte(DS, ImmA(), Reg8(AL)); } void x86CPU::op_mov_mW_axW() { WriteWA(DS, ImmA(), Reg(AX)); } void x86CPU::op_mov_rm8_imm8() { ModRM rm(this); //eventually fix this so that if r is used, then invalid opcode... rm.WriteByte(ReadByte(cCS, eip + rm.GetLength())); eip++; } void x86CPU::op_mov_rmW_immW() { ModRM rm(this); rm.WriteW(ReadW(cCS, eip + rm.GetLength())); eip += OperandSize(); } void x86CPU::op_lds() { throw new CpuInt_excp(GPF_IEXCP); } void x86CPU::op_les() { throw new CpuInt_excp(GPF_IEXCP); } void x86CPU::op_lea() { ModRM rm(this); SetReg(rm.GetExtra(), rm.ReadOffset()); } void x86CPU::op_push_imm8() { Push(ReadCode8(1)); eip++; } void x86CPU::op_push_rmW(ModRM &rm) { Push(rm.ReadW()); } void x86CPU::op_push_immW() { //0x68 Push(ImmW()); } void x86CPU::op_push_rW() { //0x50+reg Push(Reg(opbyte - 0x50)); } void x86CPU::op_push_es() { Push(0); } void x86CPU::op_push_cs() { Push(0); } void x86CPU::op_push_ds() { Push(0); } void x86CPU::op_push_ss() { Push(0); } void x86CPU::op_push_fs() { Push(0); } void x86CPU::op_push_gs() { Push(0); } void x86CPU::op_pop_rmW(ModRM &rm) { rm.WriteW(Pop()); } void x86CPU::op_pop_rW() { //0x58+reg SetReg(opbyte - 0x58, Pop()); } void x86CPU::op_pop_es() { Pop(); } void x86CPU::op_pop_ss() { Pop(); } void x86CPU::op_pop_ds() { Pop(); } void x86CPU::op_pop_fs() { Pop(); } void x86CPU::op_pop_gs() { Pop(); } void x86CPU::op_out_imm8_al() { uint8_t tmp = Reg8(AL); Ports->Write(ReadCode8(1), 1, &tmp); eip++; } void x86CPU::op_out_imm8_axW() { uint32_t tmp = Reg(AX); if (OperandSize16) { Ports->Write(ReadCode8(1), 2, (void*)&tmp); } else { Ports->Write(ReadCode8(1), 4, (void*)&tmp); } eip++; } void x86CPU::op_out_dx_al() { uint8_t tmp = Reg8(AL); Ports->Write(Reg16(DX), 1, (void*)&tmp); } void x86CPU::op_out_dx_axW() { uint32_t tmp = Reg(AX); if (OperandSize16) { Ports->Write(Reg16(DX), 2, (void*)&tmp); } else { Ports->Write(Reg16(DX), 4, (void*)&tmp); } } void x86CPU::op_in_al_imm8() { uint8_t tmp; Ports->Read(ReadCode8(1), 1, (void*)&tmp); SetReg8(AL, tmp); eip++; } void x86CPU::op_in_axW_imm8() { uint32_t tmp; if (OperandSize16) { Ports->Read(ReadCode8(1), 2, (void*)&tmp); } else { Ports->Read(ReadCode8(1), 4, (void*)&tmp); } SetReg(AX, tmp); eip++; } void x86CPU::op_in_al_dx() { uint8_t tmp; Ports->Read(Reg16(DX), 1, (void*)&tmp); SetReg8(AL, tmp); } void x86CPU::op_in_axW_dx() { uint32_t tmp; if (OperandSize16) { Ports->Read(Reg16(DX), 2, (void*)&tmp); } else { Ports->Read(Reg16(DX), 4, (void*)&tmp); } SetReg(AX, tmp); } void x86CPU::op_xchg_rm8_r8() { #ifndef X86_MULTITHREADING if (IsLocked() == 1) { eip--; return; } #endif Lock(); ModRM rm(this); uint8_t tmp = Reg8(rm.GetExtra()); SetReg8(rm.GetExtra(), rm.ReadByte()); rm.WriteByte(tmp); Unlock(); } void x86CPU::op_xchg_rmW_rW() { #ifndef X86_MULTITHREADING if (IsLocked() == 1) { eip--; return; } #endif Lock(); ModRM rm(this); uint32_t tmp = Reg(rm.GetExtra()); SetReg(rm.GetExtra(), rm.ReadW()); rm.WriteW(tmp); Unlock(); } void x86CPU::op_xchg_axW_rW() { //0x90+r uint32_t tmp = Reg(AX); SetReg(AX, Reg(opbyte - 0x90)); SetReg(opbyte - 0x90, tmp); } void x86CPU::op_xlatb() { SetReg8(AL, ReadByteA(DS, RegA(BX) + (Reg8(AL)))); } void x86CPU::op_movzx_rW_rm8() { ModRM rm(this); SetReg(rm.GetExtra(), rm.ReadByte()); } void x86CPU::op_movzx_r32_rmW() { ModRM rm(this); regs32[rm.GetExtra()] = rm.ReadWord(); } void x86CPU::op_pushaW() { uint32_t tmp; tmp = Reg(SP); Push(Reg(AX)); Push(Reg(CX)); Push(Reg(DX)); Push(Reg(BX)); Push(tmp); Push(Reg(BP)); Push(Reg(SI)); Push(Reg(DI)); } void x86CPU::op_popaW() { uint32_t ofs = 0; if (OperandSize16) { ofs = 2; } else { ofs = 4; } SetReg(DI, Pop()); SetReg(SI, Pop()); SetReg(BP, Pop()); SetReg(SP, Reg(SP) + ofs); SetReg(BX, Pop()); SetReg(DX, Pop()); SetReg(CX, Pop()); SetReg(AX, Pop()); } void x86CPU::op_enter() { uint16_t size = ReadCode16(1); eip += 2; uint8_t nestingLevel = ReadCode8(1) % 32; eip += 1; Push(Reg(EBP)); uint32_t frameTemp = Reg(ESP); for (int i = 1; i < nestingLevel; ++i) { if (OperandSize16) { SetReg(EBP, Reg(EBP) - 2); } else { SetReg(EBP, Reg(EBP) - 4); } Push(Reg(EBP)); } if (nestingLevel > 0) { Push(frameTemp); } SetReg(EBP, frameTemp); SetReg(ESP, Reg(EBP) - size); } void x86CPU::op_leave() { SetReg(ESP, Reg(EBP)); SetReg(EBP, Pop()); } void x86CPU::op_movsx_rW_rm8() { ModRM rm(this); SetReg(rm.GetExtra(), SignExtend8to32(rm.ReadByte())); } void x86CPU::op_pushf() { Push(freg.data); } void x86CPU::op_popf() { freg.data = Pop(); } };
22.733333
80
0.533724
zero-rp
753bebc066f0f4bc0f6d4b49bfbc299d14e4cafe
8,167
cpp
C++
src/engine/map2d/map2disoobjectslayer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/engine/map2d/map2disoobjectslayer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/engine/map2d/map2disoobjectslayer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file map2disoobjectslayer.cpp * @brief * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2001-12-25 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/engine/map2d/map2disoobjectslayer.h" #include "o3d/engine/map2d/map2dvisibility.h" #include "o3d/engine/scene/scene.h" #include "o3d/engine/object/camera.h" #include "o3d/engine/context.h" #include <algorithm> using namespace o3d; O3D_IMPLEMENT_DYNAMIC_CLASS1(Map2dIsoObjectsLayer, ENGINE_MAP_2D_OBJECT_LAYER, Map2dLayer) Map2dIsoObjectsLayer::Map2dIsoObjectsLayer( BaseObject *parent, const Box2i &area, UInt32 maxDepth, UInt32 maxObjectsPerCell) : Map2dLayer(parent), m_sort(True), m_box(area), m_visibility(nullptr) { m_visibility = new Map2dVisibility( area.pos(), nextPow2(max(area.width(), area.height())), max((UInt32)1, maxDepth), maxObjectsPerCell); } Map2dIsoObjectsLayer::~Map2dIsoObjectsLayer() { m_visibility->clear(); IT_Map2dObjectList it = m_objects.begin(); while (it != m_objects.end()) { deletePtr(*it); ++it; } deletePtr(m_visibility); } Bool Map2dIsoObjectsLayer::deleteChild(BaseObject *child) { if (child) { if (child->getParent() != this) O3D_ERROR(E_InvalidParameter("The parent child differ from this")); else { // object should be type of Map2dObject Map2dObject *object = dynamicCast<Map2dObject*>(child); if (object) { IT_Map2dObjectList it = m_objects.begin(); for (; it != m_objects.end(); ++it) { if ((*it) == object) break; } // remove the object of the son list if (it != m_objects.end()) { // remove it from the quadtree if (m_visibility != nullptr) m_visibility->removeObject(object); m_sort = True; m_objects.erase(it); object->setNode(nullptr); } deletePtr(object); } else { // otherwise simply delete it deletePtr(child); } return True; } } return False; } UInt32 Map2dIsoObjectsLayer::getNumElt() const { return m_objects.size(); } const Transform *Map2dIsoObjectsLayer::getTransform() const { return nullptr; } Transform *Map2dIsoObjectsLayer::getTransform() { return nullptr; } void Map2dIsoObjectsLayer::update() { if (!getActivity()) return; clearUpdated(); Bool dirty = False; if (getNode() && getNode()->hasUpdated()) { // the parent has change so the child need to be updated dirty = True; } if (dirty) { setUpdated(); } // check if a sort is necessary at the next draw m_sort |= m_visibility->hasUpdated(); m_visibility->clearUpdated(); /* // update each son (recursively if necessary) TODO optimize that for (IT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { Map2dObject *object = (*it); if (object->getActivity()) { // compute object absolute matrix object->update(); if (object->hasUpdated()) { // only for drawable and dynamic objects if (object->hasDrawable()) { m_visibility->updateObject(object); m_sort = True; } } } }*/ } void Map2dIsoObjectsLayer::draw(const DrawInfo &drawInfo) { if (!m_capacities.getBit(STATE_ACTIVITY) || !m_capacities.getBit(STATE_VISIBILITY)) return; setUpModelView(); if (getScene()->getDrawObject(Scene::DRAW_MAP_2D_LAYER)) { // TODO Symbolics a quad in red } Camera *camera = getScene()->getActiveCamera(); // process to a sort on the visible area if necessary if (m_sort || camera->isCameraChanged()) { Vector3 camPos = camera->getAbsoluteMatrix().getTranslation(); Box2i viewport( camPos.x() - (-camera->getLeft() + camera->getRight()) / 2, camPos.y() - (camera->getBottom() - camera->getTop()) / 2, -camera->getLeft() + camera->getRight(), camera->getBottom() - camera->getTop()); m_drawList.clear(); /*UInt32 rejected = */m_visibility->checkVisibleObject(viewport); T_Map2dObjectList &drawList = m_visibility->getDrawList(); m_drawList.reserve(drawList.size()); // inject for sort for (Map2dObject *object : drawList) { m_drawList.push_back(object); } std::sort(m_drawList.begin(), m_drawList.end(), &Map2dObject::compare); m_sort = False; //System::print(String::print("rejected object=%u", rejected), ""); //System::print(m_visibility->getTreeView(), ""); } for (Map2dObject *object : m_drawList) { object->draw(drawInfo); } } UInt32 Map2dIsoObjectsLayer::getNumSon() const { return m_objects.size(); } Bool Map2dIsoObjectsLayer::hasSon(SceneObject *object) const { CIT_Map2dObjectList cit = m_objects.begin(); for (; cit != m_objects.cend(); ++cit) { if ((*cit) == object) return True; } return False; } SceneObject* Map2dIsoObjectsLayer::findSon(const String &name) { if (getName() == name) return this; for (IT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { SceneObject *object = (*it); if (object->isNodeObject()) { SceneObject *result = ((BaseNode*)object)->findSon(name); if (result) return result; } else if (object->getName() == name) return object; } return nullptr; } const SceneObject* Map2dIsoObjectsLayer::findSon(const String &name) const { if (getName() == name) return this; for (CIT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { const SceneObject *object = (*it); if (object->isNodeObject()) { const SceneObject *result = ((BaseNode*)object)->findSon(name); if (result) return result; } else if (object->getName() == name) return object; } return nullptr; } Bool Map2dIsoObjectsLayer::findSon(SceneObject *object) const { if (this == object) return True; for (CIT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { const SceneObject *search = (*it); if (search->isNodeObject()) { Bool result = ((BaseNode*)search)->findSon(object); if (result) return True; } else if (search == object) return True; } return False; } const T_Map2dObjectList &Map2dIsoObjectsLayer::getObjects() { return m_objects; } const T_Map2dObjectList& Map2dIsoObjectsLayer::getVisiblesObjects() { return m_visibility->getDrawList(); } Bool Map2dIsoObjectsLayer::isObjectIntersect(const Box2i &box) const { return m_visibility->isObjectIntersect(box); } Bool Map2dIsoObjectsLayer::isObjectBaseIntersect(const Map2dObject *from) const { return m_visibility->isObjectBaseIntersect(from); } Map2dObject* Map2dIsoObjectsLayer::addObject( const String &name, const Vector2i &pos, const Rect2i &baseRect, Map2dTileSet *tileSet, UInt32 tileId) { Map2dObject *object = new Map2dObject(this); object->setName(name); object->setNode(this); object->setTile(tileSet, tileId); object->setBaseRect(baseRect); object->setPos(pos); m_objects.push_back(object); m_sort = True; m_visibility->addObject(object); return object; } // remove a specified son void Map2dIsoObjectsLayer::removeObject(Map2dObject *object) { IT_Map2dObjectList it = m_objects.begin(); for (; it != m_objects.end(); ++it) { if ((*it) == object) break; } if (it == m_objects.end()) { O3D_ERROR(E_InvalidParameter("Object not found")); } else { m_visibility->removeObject(object); // remove the object of the son list m_objects.erase(it); // no node object->setParent(getScene()); object->setNode(nullptr); object->setPersistant(False); m_sort = True; } } void Map2dIsoObjectsLayer::updateObject(Map2dObject *object) { } //void Map2dIsoObjectsLayer::moveObject(Map2dObject *object, const Vector2i &pos) //{ // if (object != nullptr) // { // object->setPos(pos); // m_visibility->updateObject(object); // } //} // Remove all sons (delete objects if no longer used) void Map2dIsoObjectsLayer::deleteAllObjects() { IT_Map2dObjectList it = m_objects.begin(); while (it != m_objects.end()) { deletePtr(*it); ++it; } m_objects.clear(); m_visibility->clear(); m_sort = True; }
20.623737
90
0.668177
dream-overflow
753f1e0eb88b1ed2be6875a7cfba33cf116bbc4d
14,916
cpp
C++
addons/ofxCvGui/src/ofxCvGui/Controller.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxCvGui/src/ofxCvGui/Controller.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxCvGui/src/ofxCvGui/Controller.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
#include "pch_ofxCvGui.h" //---------- OFXSINGLETON_DEFINE(ofxCvGui::Controller); namespace ofxCvGui { //---------- Controller::Controller() { this->maximised = false; this->chromeVisible = true; this->mouseOwner = nullptr; this->lastClickOwner = nullptr; this->lastMouseClick = pair<long long, ofMouseEventArgs>(std::numeric_limits<long long>::min(), ofMouseEventArgs()); this->cachedWidth = 0.0f; this->cachedHeight = 0.0f; } //---------- void Controller::init(shared_ptr<Panels::Groups::Base> rootGroup) { ofBackground(30); ofAddListener(ofEvents().update, this, &Controller::update); ofAddListener(ofEvents().draw, this, &Controller::draw); ofAddListener(ofEvents().mouseMoved, this, &Controller::mouseMoved); ofAddListener(ofEvents().mousePressed, this, &Controller::mousePressed); ofAddListener(ofEvents().mouseReleased, this, &Controller::mouseReleased); ofAddListener(ofEvents().mouseDragged, this, &Controller::mouseDragged); ofAddListener(ofEvents().mouseScrolled, this, &Controller::mouseScrolled); ofAddListener(ofEvents().keyPressed, this, &Controller::keyPressed); ofAddListener(ofEvents().keyReleased, this, &Controller::keyReleased); ofAddListener(ofEvents().fileDragEvent, this, &Controller::filesDragged); ofAddListener(ofEvents().windowResized, this, &Controller::windowResized); ofAddListener(ofEvents().exit, this, &Controller::exit, 0); ofxAssets::Register::X().addAddon("ofxCvGui"); rootGroup->setBounds(ofGetCurrentViewport()); this->rootGroup = rootGroup; this->currentPanel = PanelPtr(); this->currentPanelBounds = ofGetCurrentViewport(); //cache fonts ofxAssets::font("ofxCvGui::swisop3", 12); ofxAssets::font("ofxCvGui::swisop3", 14); ofxAssets::font("ofxCvGui::swisop3", 18); ofxAssets::font("ofxCvGui::swisop3", 24); } //---------- void Controller::add(PanelPtr panel) { if (!this->rootGroup) return; this->rootGroup->add(panel); } //---------- void Controller::remove(PanelPtr panel) { if (!this->rootGroup) return; this->rootGroup->remove(panel); } //---------- void Controller::clear() { if (!this->rootGroup) return; this->rootGroup->clear(); } //---------- void Controller::toggleFullscreen() { ofToggleFullscreen(); } //---------- void Controller::toggleMaximised() { if (!this->maximised) { //maximise current panel auto currentPanel = this->currentPanel.lock(); if (currentPanel) { this->setMaximised(currentPanel); currentPanel->setBounds(ofGetCurrentViewport()); } } else { //clear maximise this->clearMaximised(); } } //---------- void Controller::setMaximised(PanelPtr panel) { this->maximised = true; this->currentPanel = panel; this->currentPanelBounds = ofGetCurrentViewport(); panel->setBounds(ofRectangle(0, 0, ofGetScreenWidth(), ofGetScreenHeight())); } //---------- void Controller::clearMaximised() { this->maximised = false; rootGroup->setBounds(ofGetCurrentViewport()); this->updateCurrentPanel(); } //---------- void Controller::showChrome() { this->chromeVisible = true; } //---------- void Controller::hideChrome() { this->chromeVisible = false; } //---------- void Controller::setActiveDialog(PanelPtr panel) { if (panel) { auto bounds = ofGetCurrentViewport(); //first get a cached draw for the background this->activeDialogBackground.grabScreen(0, 0, ofGetWindowWidth(), ofGetWindowHeight()); //setup the active Dialog this->activeDialog = panel; //setup the size of the Dialog ofResizeEventArgs resizeArgs = { ofGetViewportWidth(), ofGetViewportHeight() }; this->windowResized(resizeArgs); } else { this->closeActiveDialog(); } } //---------- void Controller::closeActiveDialog() { if (this->activeDialog) { this->onDialogClose.notifyListeners(this->activeDialog); this->activeDialog.reset(); //setup the size of the root group ofResizeEventArgs resizeArgs = { ofGetViewportWidth(), ofGetViewportHeight() }; this->windowResized(resizeArgs); } } //---------- bool Controller::isDialogOpen() { return (this->activeDialog.get()); } //---------- void Controller::update(ofEventArgs& args) { if (!this->rootGroup) { return; } InspectController::X().update(); if (this->activeDialog) { this->activeDialog->update(); } else if (this->maximised) { this->currentPanel.lock()->update(); } else { rootGroup->update(); } } //---------- void Controller::draw(ofEventArgs& args) { if (!this->rootGroup) { return; } DrawArguments rootDrawArguments; rootDrawArguments.chromeEnabled = this->chromeVisible; rootDrawArguments.naturalBounds = ofGetCurrentViewport(); rootDrawArguments.globalTransform = glm::mat4(); rootDrawArguments.globalScale = 1.0f; rootDrawArguments.localBounds = ofRectangle(0, 0, rootDrawArguments.naturalBounds.getWidth(), rootDrawArguments.naturalBounds.getHeight()); rootDrawArguments.globalBounds = rootDrawArguments.naturalBounds; auto currentPanel = this->currentPanel.lock(); if (this->activeDialog) { this->activeDialogBackground.draw(rootDrawArguments.naturalBounds); ofPushStyle(); { //draw light box background ofEnableAlphaBlending(); ofSetColor(0, 200); ofDrawRectangle(rootDrawArguments.naturalBounds); //shadow for dialog ofFill(); ofSetColor(0, 100); ofPushMatrix(); { ofTranslate(5, 5); ofDrawRectangle(this->activeDialog->getBounds()); } ofPopMatrix(); //background for dialog ofSetColor(80); ofDrawRectangle(this->activeDialog->getBounds()); } ofPopStyle(); this->activeDialog->draw(rootDrawArguments); } else { if (this->maximised) { currentPanel->draw(rootDrawArguments); } else { //highlight panel if (currentPanel) { ofPushStyle(); ofEnableAlphaBlending(); ofSetColor(40, 40, 40, 100); ofDrawRectangle(this->currentPanelBounds); ofPopStyle(); } this->rootGroup->draw(rootDrawArguments); } } for (const auto & delayedDrawCommand : this->delayedDrawCommands) { delayedDrawCommand(); } this->delayedDrawCommands.clear(); } //---------- void Controller::exit(ofEventArgs & args) { this->rootGroup.reset(); ofRemoveListener(ofEvents().update, this, &Controller::update); ofRemoveListener(ofEvents().draw, this, &Controller::draw); ofRemoveListener(ofEvents().mouseMoved, this, &Controller::mouseMoved); ofRemoveListener(ofEvents().mousePressed, this, &Controller::mousePressed); ofRemoveListener(ofEvents().mouseReleased, this, &Controller::mouseReleased); ofRemoveListener(ofEvents().mouseDragged, this, &Controller::mouseDragged); ofRemoveListener(ofEvents().keyPressed, this, &Controller::keyPressed); ofRemoveListener(ofEvents().keyReleased, this, &Controller::keyReleased); ofRemoveListener(ofEvents().fileDragEvent, this, &Controller::filesDragged); ofRemoveListener(ofEvents().windowResized, this, &Controller::windowResized); } //---------- PanelGroupPtr Controller::getRootGroup() const { return this->rootGroup; } //---------- void Controller::setRootGroup(PanelGroupPtr rootGroup) { this->rootGroup = rootGroup; this->rootGroup->arrange(); } //---------- PanelPtr Controller::getPanelUnderCursor(const glm::vec2 & position) { if (this->maximised) { return currentPanel.lock(); } else { ofRectangle panelBounds = this->rootGroup->getBounds(); return this->findPanelUnderCursor(panelBounds, position); } } //---------- void Controller::drawDelayed(function<void()> && drawFunction) { this->delayedDrawCommands.emplace_back(drawFunction); } //---------- void Controller::mouseMoved(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); MouseArguments action(MouseArguments(args, MouseArguments::Moved, rootGroup->getBounds(), currentPanel, this->mouseOwner)); this->mouseAction(action); this->updateCurrentPanel(); } //---------- void Controller::mousePressed(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto thisMouseClick = pair<long long, ofMouseEventArgs>(ofGetElapsedTimeMillis(), args); bool isDoubleClick = (thisMouseClick.first - this->lastMouseClick.first) < OFXCVGUI_DOUBLECLICK_TIME_THRESHOLD_MS; auto distanceSinceLastClick = glm::distance( (glm::vec2) thisMouseClick.second, (glm::vec2) this->lastMouseClick.second ); isDoubleClick &= distanceSinceLastClick < OFXCVGUI_DOUBLECLICK_SPACE_THRESHOLD_PX; if (isDoubleClick) { this->mouseOwner = this->lastClickOwner; } auto currentPanel = this->currentPanel.lock(); auto action = MouseArguments(args, isDoubleClick ? MouseArguments::Action::DoubleClick : MouseArguments::Action::Pressed, rootGroup->getBounds(), currentPanel, this->mouseOwner); if (this->activeDialog && !this->activeDialog->getBounds().inside(action.local)) { this->closeActiveDialog(); } else { this->mouseAction(action); } this->mouseCached = action.global; this->mouseOwner = action.getOwner(); this->lastMouseClick = thisMouseClick; } //---------- void Controller::mouseReleased(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); MouseArguments action(args, MouseArguments::Released, rootGroup->getBounds(), currentPanel, this->mouseOwner); this->mouseAction(action); this->lastClickOwner = this->mouseOwner; this->mouseOwner = nullptr; } //---------- void Controller::mouseDragged(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); MouseArguments action(args, MouseArguments::Dragged, rootGroup->getBounds(), currentPanel, this->mouseOwner, mouseCached); this->mouseAction(action); this->mouseCached = action.global; } //---------- void Controller::mouseScrolled(ofMouseEventArgs& args) { if (!this->rootGroup) { return; } auto panelUnderCursor = this->getPanelUnderCursor(args); if (panelUnderCursor) { MouseArguments action(args, MouseArguments::Scrolled, rootGroup->getBounds(), panelUnderCursor, this->mouseOwner, mouseCached); this->mouseAction(action); } } //---------- void Controller::mouseAction(MouseArguments & action) { if (this->activeDialog) { this->activeDialog->mouseAction(action); } else { auto currentPanel = this->currentPanel.lock(); if (this->maximised) { currentPanel->mouseAction(action); } else { rootGroup->mouseAction(action); } } } //---------- void Controller::keyReleased(ofKeyEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); KeyboardArguments action(args, KeyboardArguments::Released, currentPanel); if (this->activeDialog) { this->activeDialog->keyboardAction(action); } else { if (this->maximised) { //if something is maximised, only it get the key press currentPanel->keyboardAction(action); } else { //otherwise everything visible gets the key press rootGroup->keyboardAction(action); } } } void Controller::keyPressed(ofKeyEventArgs & args) { if (!this->rootGroup) { return; } if (args.key == 0) { // This sometimes happens with mouse button 4 return; } if (!this->activeDialog) { if (args.key == 'f') this->toggleFullscreen(); if (args.key == 'm') this->toggleMaximised(); } auto currentPanel = this->currentPanel.lock(); KeyboardArguments action(args, KeyboardArguments::Pressed, currentPanel); if (this->activeDialog) { if (args.key == OF_KEY_ESC) { this->closeActiveDialog(); } else { this->activeDialog->keyboardAction(action); } } else { if (this->maximised) { //if something is maximised, only it get the key press currentPanel->keyboardAction(action); } else { //otherwise everything visible gets the key press rootGroup->keyboardAction(action); } } } //---------- void Controller::filesDragged(ofDragInfo & args) { if (!this->rootGroup) { return; } auto rootBounds = this->rootGroup->getBounds(); auto panel = this->findPanelUnderCursor(rootBounds); if (panel != PanelPtr()) { auto panelBounds = panel->getBounds(); auto panelTopLeft = panelBounds.getTopLeft(); auto newArgs = FilesDraggedArguments((glm::vec2) args.position - panelTopLeft, (glm::vec2) args.position, args.files); panel->onFilesDragged(newArgs); } } //---------- void Controller::windowResized(ofResizeEventArgs & args) { if (!this->rootGroup) { return; } const auto viewportBounds = ofRectangle(0, 0, args.width, args.height); if (this->activeDialog) { const auto padding = 80.0f; ofRectangle bounds = viewportBounds; bounds.x += padding; bounds.y += padding; bounds.width -= padding * 2.0f; bounds.height -= padding * 2.0f; //if bounds are too small, use all of it if (bounds.width < 200 || bounds.height < 200) { bounds = viewportBounds; } this->activeDialog->setBounds(bounds); } else { auto currentPanel = this->currentPanel.lock(); if (this->maximised) { currentPanel->setBounds(viewportBounds); } else { this->rootGroup->setBounds(viewportBounds); } } } //---------- bool Controller::checkInitialised() { if (this->rootGroup) return true; else { ofLogError("ofxCvGui") << "cannot perform this action as gui is not initialised"; return false; } } //---------- PanelPtr Controller::findPanelUnderCursor(ofRectangle & panelBounds, const glm::vec2 & position) { if (!this->rootGroup) { return PanelPtr(); } if (this->activeDialog) { return activeDialog; } else if (this->maximised) { return this->currentPanel.lock(); } else { return rootGroup->findScreen(position, panelBounds); } } //---------- void Controller::updateCurrentPanel() { if (!this->maximised) { auto currentPanelBounds = this->rootGroup->getBounds(); this->currentPanel = this->findPanelUnderCursor(currentPanelBounds); this->currentPanelBounds = currentPanelBounds; } } //---------- ofxCvGui::PanelPtr Controller::getActiveDialog() { return this->activeDialog; } //---------- void openDialog(PanelPtr panel) { Controller::X().setActiveDialog(panel); } //---------- void closeDialog(Panels::Base * panel) { if (Controller::X().getActiveDialog().get() == panel) { Controller::X().closeActiveDialog(); } } //---------- void closeDialog() { Controller::X().closeActiveDialog(); } //---------- bool isDialogOpen() { return Controller::X().isDialogOpen(); } }
26.635714
180
0.669482
syeminpark
7541639e7eebe2db9694f668a355f034bb9fab99
370
cpp
C++
acmicpc.net/9461.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
4
2016-04-15T07:54:39.000Z
2021-01-11T09:02:16.000Z
acmicpc.net/9461.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
acmicpc.net/9461.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> using namespace std; int t,n; long long int A[101] = { 1, 1, 1, 0 }; int main() { scanf("%d", &t); for (int i = 0; i < t; i++) { scanf("%d", &n); for (int j = 3; j < n; j++) { A[j] = A[j-3] + A[j-2]; } printf("%lld\n", A[n-1]); } return 0; }
17.619048
38
0.486486
kbu1564
754603bd2a3852c0186f083b10dab76446692a11
3,847
cpp
C++
bgcc/nb_data_buffer.cpp
duzhanyuan/testbdrpc
da572ea2dcb81985d65214819a834ccfbc89262d
[ "BSD-3-Clause" ]
8
2018-01-31T05:20:46.000Z
2021-06-11T17:45:34.000Z
bgcc/nb_data_buffer.cpp
duzhanyuan/testbdrpc
da572ea2dcb81985d65214819a834ccfbc89262d
[ "BSD-3-Clause" ]
null
null
null
bgcc/nb_data_buffer.cpp
duzhanyuan/testbdrpc
da572ea2dcb81985d65214819a834ccfbc89262d
[ "BSD-3-Clause" ]
31
2017-05-10T19:32:40.000Z
2021-06-16T13:22:22.000Z
/*********************************************************************** * Copyright (c) 2012, Baidu Inc. All rights reserved. * * Licensed under the BSD License * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * license.txt *********************************************************************/ #ifndef _WIN32 #include <netinet/in.h> #endif #include <string.h> #include "nb_data_buffer.h" #include "byte_order.h" #include "bgcc_error.h" namespace bgcc { NBDataBuffer::NBDataBuffer() :_size(0), _maxsize(0), _data(NULL) { } NBDataBuffer::~NBDataBuffer() { clear(); } int32_t NBDataBuffer::append_bool(bool b) { uint8_t tmp = b ? 1 : 0; return append(&tmp, sizeof(uint8_t)); } int32_t NBDataBuffer::append_int8(int8_t i8) { return append(&i8, sizeof(int8_t)); } int32_t NBDataBuffer::append_int16(int16_t i16) { uint16_t tmp = htons((uint16_t)i16); return append(&tmp, sizeof(uint16_t)); } int32_t NBDataBuffer::append_int32(int32_t i32) { uint32_t tmp = htonl((uint32_t)i32); return append(&tmp, sizeof(uint32_t)); } int32_t NBDataBuffer::append_int64(int64_t i64) { uint64_t tmp = HTONLL((uint64_t)i64); return append(&tmp, sizeof(uint64_t)); } int32_t NBDataBuffer::append_float(float f) { uint32_t tmp = htonl(*(uint32_t*)&f); return append(&tmp, sizeof(uint32_t)); } int32_t NBDataBuffer::append_string(const std::string& str) { int32_t ret; int32_t len = (int32_t)str.length(); ret = append_int32(len); if (0 != ret) { return ret; } return append(str.data(), len); } int32_t NBDataBuffer::append_binary(const void* buffer, int32_t buflen) { int32_t ret; ret = append_int32(buflen); if (0 != ret) { return ret; } return append(buffer, buflen); } int32_t NBDataBuffer::append(const void* buffer, int32_t buflen) { if (NULL == buffer) { return E_BGCC_NULL_POINTER; } if (buflen < 0) { return E_BGCC_INVALID_PARAM; } else if (0 == buflen) { return 0; } if (_size + buflen > _maxsize) { int32_t newsize = (buflen + _maxsize) * 2; void *ptr; ptr = realloc(_data, newsize); if (NULL == ptr) { newsize = _size + buflen; ptr = realloc(_data, newsize); if (NULL == ptr) { return E_BGCC_NOMEM; } } _data = ptr; _maxsize = newsize; } memcpy((char*)_data + _size, buffer, buflen); _size += buflen; return 0; } int32_t NBDataBuffer::get_data(void** ppdata, int32_t& size) { if (NULL == ppdata) { return E_BGCC_NULL_POINTER; } *ppdata = _data; size = _size; return 0; } int32_t NBDataBuffer::get_data_copy(void** ppdata, int32_t& size) { if (NULL == ppdata) { return E_BGCC_NULL_POINTER; } if (0 == _size) { *ppdata = NULL; } else { *ppdata = malloc(_size); if (NULL == *ppdata) { return E_BGCC_NOMEM; } else { memcpy(*ppdata, _data, _size); } } size = _size; return 0; } int32_t NBDataBuffer::clear(bool keepAllocatedMem) { _size = 0; if (NULL != _data && !keepAllocatedMem) { free(_data); _data = NULL; _maxsize = 0; } return 0; } }
24.819355
77
0.505329
duzhanyuan
75464bec70a43a9e4d4ef45a6b757513d15e8a95
446
cpp
C++
src/test/main_victim_test.cpp
davitkalantaryan/wlac-sources
0878d97df0900b16f72c63f187be44ae9bef8949
[ "MIT" ]
null
null
null
src/test/main_victim_test.cpp
davitkalantaryan/wlac-sources
0878d97df0900b16f72c63f187be44ae9bef8949
[ "MIT" ]
4
2021-10-05T05:28:22.000Z
2021-12-28T22:48:21.000Z
src/test/main_victim_test.cpp
davitkalantaryan/wlac-sources
0878d97df0900b16f72c63f187be44ae9bef8949
[ "MIT" ]
null
null
null
// // file: main_victim_test.cpp // created on: 2018 Dec 18 // #ifndef CINTERFACE #define CINTERFACE #endif // !CINTERFACE #include <WinSock2.h> #include <WS2tcpip.h> #include <Windows.h> #include <stdio.h> static volatile int s_nRun = 1; int main() { int nPid = GetCurrentProcessId(); printf("pid=%d, lodaLibraryAddress=%p\n", nPid,&LoadLibraryA); s_nRun = 1; while(s_nRun){ SleepEx(INFINITE, TRUE); } }
15.928571
64
0.64574
davitkalantaryan
754b36c3ba2e2753bd7467e45a79c0e7acad2213
723
cpp
C++
emerald/util/tests/test_vector_util.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
3
2020-08-16T17:56:25.000Z
2021-02-25T21:55:39.000Z
emerald/util/tests/test_vector_util.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
emerald/util/tests/test_vector_util.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
#include <emerald/util/format.h> #include <emerald/util/foundation.h> #include <emerald/util/random.h> #include <emerald/util/vector_util.h> #include <fmt/format.h> #include <gtest/gtest.h> #include <cstdio> #include <cstdlib> #include <vector> namespace emerald::util { TEST(Test_vector_util, Print_hash_key) { V3d g; set_zero(g); UniformRand rand; std::vector<float> v; for (int i = 0; i < 100; ++i) { v.push_back(static_cast<float>(rand())); } auto const* const vdata = v.data(); for (int i = 0; i < 100; ++i) { fmt::print("{}\n", vdata[i]); } auto const vkey = ComputeVectorHashKey(v); fmt::print("Vector hash key: {}\n", FormatHashKey(vkey)); } } // namespace emerald::util
24.1
78
0.648686
blackencino
754c73ea5c5b7b8b0f39c1ccc23a51d1287a1455
2,878
hh
C++
include/introvirt/windows/kernel/nt/types/PEB.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
include/introvirt/windows/kernel/nt/types/PEB.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
include/introvirt/windows/kernel/nt/types/PEB.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
4
2021-02-17T16:53:18.000Z
2021-04-13T16:51:10.000Z
/* * Copyright 2021 Assured Information Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <introvirt/core/memory/guest_ptr.hh> #include <introvirt/windows/kernel/nt/fwd.hh> #include <cstdint> #include <memory> namespace introvirt { namespace windows { namespace nt { /** * Parser for the Windows Process Environment Block (PEB) */ class PEB { public: /** * @returns The base address of the executable image */ virtual guest_ptr<void> ImageBaseAddress() const = 0; /** * @returns The PEB_LDR_DATA, containing information about loaded libraries and the exe itself */ virtual const PEB_LDR_DATA* Ldr() const = 0; virtual PEB_LDR_DATA* Ldr() = 0; /** * @return Information about the process environment */ virtual const RTL_USER_PROCESS_PARAMETERS* ProcessParameters() const = 0; virtual RTL_USER_PROCESS_PARAMETERS* ProcessParameters() = 0; /** * @returns The major version of the OS */ virtual uint32_t OSMajorVersion() const = 0; /** * @returns The minor version of the OS */ virtual uint32_t OSMinorVersion() const = 0; /** * @returns The build number of the OS */ virtual uint16_t OSBuildNumber() const = 0; /** * @returns The CSD version of the OS, containing service pack information */ virtual uint16_t OSCSDVersion() const = 0; /** * @returns The platform ID of the OS */ virtual uint32_t OSPlatformId() const = 0; /** * @returns The service pack number of the OS */ virtual uint16_t ServicePackNumber() const = 0; /** * @returns The minor service pack number of the OS */ virtual uint16_t MinorServicePackNumber() const = 0; /** * @returns The number of physical processors */ virtual uint32_t NumberOfProcessors() const = 0; /** * @returns The virtual address of the PEB in-guest */ virtual guest_ptr<void> ptr() const = 0; /** * @returns The value of the BeingDebugged field */ virtual bool BeingDebugged() const = 0; /** * @returns The value of the BeingDebugged field */ virtual void BeingDebugged(bool BeingDebugged) = 0; virtual ~PEB() = default; }; } /* namespace nt */ } /* namespace windows */ } /* namespace introvirt */
25.927928
98
0.658443
IntroVirt
75504f62dadac215cd69a00917affe0e57447838
376
cpp
C++
game/server/entities/triggers/CTriggerTeleport.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
83
2016-06-10T20:49:23.000Z
2022-02-13T18:05:11.000Z
game/server/entities/triggers/CTriggerTeleport.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
26
2016-06-16T22:27:24.000Z
2019-04-30T19:25:51.000Z
game/server/entities/triggers/CTriggerTeleport.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
58
2016-06-10T23:52:33.000Z
2021-12-30T02:30:50.000Z
#include "extdll.h" #include "util.h" #include "cbase.h" #include "CTriggerTeleport.h" LINK_ENTITY_TO_CLASS( trigger_teleport, CTriggerTeleport ); //TODO: Consider making this its own class - Solokiller LINK_ENTITY_TO_CLASS( info_teleport_destination, CPointEntity ); void CTriggerTeleport::Spawn( void ) { InitTrigger(); SetTouch( &CTriggerTeleport::TeleportTouch ); }
22.117647
64
0.776596
xalalau
755199317f3fade2b7ce3139ef6dba5776bbf8f3
14,130
cpp
C++
embeddedCNN/src/utils/check.cpp
yuehniu/embeddedCNN
1067867830300cc55b4573d633c9fa1226c64868
[ "MIT" ]
21
2018-07-10T07:47:51.000Z
2021-12-03T05:47:30.000Z
embeddedCNN/src/utils/check.cpp
honorpeter/embeddedCNN
1067867830300cc55b4573d633c9fa1226c64868
[ "MIT" ]
3
2018-09-05T03:09:40.000Z
2019-04-15T10:01:40.000Z
embeddedCNN/src/utils/check.cpp
honorpeter/embeddedCNN
1067867830300cc55b4573d633c9fa1226c64868
[ "MIT" ]
8
2018-06-10T02:04:09.000Z
2021-12-03T05:47:31.000Z
/* Desc: Result check function set. * Accurate data check (Dataflow). * Approximate data check (Compute result). Date: 06/05/2018 Author: Yue Niu */ #include <iostream> #include <fstream> #include <stdlib.h> #include "../../include/utils/check.h" extern const int SHAPE[]; extern const int CHNEL[]; bool dataflow_check(Dtype * Ref, Dtype * Res, int Cnt) { std::cout << "[INFO] " << __FUNCTION__ << ", " << __LINE__ << ": Check dataflow between DDR and FPGA" << std::endl; bool all_same = true; std::ofstream log("check_df.log"); for (int i = 0; i < Cnt; i++){ if (*(Res + i) != *(Ref + i)) { all_same = false; log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << i << "th data check fail" << std::endl; log << "[LOG] " << "Ref data: " << *(Ref + i) << ", Result data: " << *(Res + i) << std::endl; } else { log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << i << "th data check pass" << std::endl; log << "[LOG] " << "Ref data: " << *(Ref + i) << ", Result data: " << *(Res + i) << std::endl; } } log.close(); return all_same; } /* Check in_buf */ void conv_inbuf_check( Dtype *Ref, Dtype InBuf[ITILE][I_BUF_DEPTH], int Lyr, int RowsPre, int RowsRead, int RowsValid ) { static int til; if (1 == RowsPre) til = 0; else til += 1; std::ofstream log("check_InBuf.log", std::ios::app); int chnl_til_num = Lyr == 0 ? 3 : ITILE; int chnl_num = Lyr == 0 ? 3 : CHNEL[Lyr - 1]; int col_num = SHAPE[Lyr] + 2; Dtype *ref_ptr = Ref; log << "[INFO] " << __FUNCTION__ << ", " << __LINE__ << ": Check " << til << "th tile." << std::endl; for (int ch = 0; ch < chnl_til_num; ch++){ for (int row = 0; row < RowsPre+RowsValid; row++){ for (int col = 0; col < col_num; col++){ Dtype ref = 0.0; if ((0 == col) || (col_num-1 == col)) ref = 0.0; else { if (0 == row){ if (1 == RowsPre) ref = 0.0; else ref = *(ref_ptr - 2 * chnl_num * (col_num-2) + ch * (col_num-2) + col - 1); } else if (1 == row){ if (1 == RowsPre) ref = *(ref_ptr + ch * (col_num-2) + col - 1); else ref = *(ref_ptr - chnl_num * (col_num-2) + ch * (col_num-2) + col - 1); } else { ref = *(ref_ptr + (row - RowsPre) * chnl_num * (col_num-2) + ch * (col_num-2) + col - 1); } } Dtype inbuf = InBuf[ch][row * col_num + col]; if (ref == inbuf) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << ch << "th channel, " << row << "th row, " << col << "th col data check pass." << std::endl; else log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << ch << "th channel, " << row << "th row, " << col << "th col data check fail." << std::endl; log << "[LOG] " << "Ref data: " << ref << ", InBuf: " << inbuf << std::endl; } } } log.close(); return; } /* Check w_buf */ void conv_wbuf_check( Dtype *Param, Dtype WBuf[OTILE * ITILE][W_BUF_DEPTH], int IChnlTil, int OChnlTil, int Kern, int Sec ) { std::ofstream log("check_WBuf.log", std::ios::app); log << "[INFO] " << __FUNCTION__ << ", " << __LINE__ << ": Check " << Sec << "th sector." << std::endl; for(int och = 0; och < OChnlTil; och++){ for(int ich = 0; ich < ITILE; ich++) { for(int k = 0; k < Kern * Kern; k++){ if (ich < IChnlTil){ Dtype ref = *(Param + och * IChnlTil * Kern * Kern + ich * Kern * Kern + k); Dtype wbuf = WBuf[och * ITILE + ich][Sec * Kern * Kern + k]; if (ref == wbuf){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << Sec << "th sector, " << och << "th ochannel, " << ich << "th ichannel, " << k << "th weight check pass." << std::endl; } else{ log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << Sec << "th sector, " << och << "th ochannel, " << ich << "th ichannel, " << k << "th weight check fail." << std::endl; } log << "[LOG] " << "Ref weight: " << ref << ", WBuf: " << wbuf << std::endl; } } } } log.close(); return; } /* Check b_buf */ void conv_bias_check(Dtype *Param, Dtype BBuf[B_BUF_DEPTH], int OChnl) { std::ofstream log("check_BBuf.log", std::ios::app); for (int och = 0; och < OChnl; och++){ Dtype ref = *(Param + och); Dtype bbuf = BBuf[och]; if (ref == bbuf){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check pass." << std::endl; } else { log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check fail." << std::endl; } log << "[LOG] " << "Ref bias: " << ref << ", BBuf: " << bbuf << std::endl; } log.close(); return; } /* Check b_buf */ void onchip_check(Dtype *Ref, Dtype *Chip, int OChnl) { std::ofstream log("check_Onchip.log", std::ios::app); for (int och = 0; och < OChnl; och++){ Dtype ref = *(Ref + och); Dtype bbuf = *(Chip + och); if (ref == bbuf){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check pass." << std::endl; } else { log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check fail." << std::endl; } log << "[LOG] " << "Ref bias: " << ref << ", BBuf: " << bbuf << std::endl; } log.close(); return; } /* Check computing result */ void conv_check(Dtype *Out, int Lyr, bool Pooling) { std::ofstream log("check_conv_result.log", std::ios::app); std::ifstream feature; if (0 == Lyr) feature.open("./data/conv1_1fp16.bin", std::ios::binary); else if (1 == Lyr){ if (Pooling) feature.open("./data/pool1fp16.bin", std::ios::binary); else feature.open("./data/conv1_2fp16.bin", std::ios::binary); } else if (2 == Lyr) feature.open("./data/conv2_1fp16.bin", std::ios::binary); else if (3 == Lyr){ if (Pooling) feature.open("./data/pool2fp16.bin", std::ios::binary); else feature.open("./data/conv2_2.bin", std::ios::binary); } else if (4 == Lyr) feature.open("./data/conv3_1fp16.bin", std::ios::binary); else if (5 == Lyr) feature.open("./data/conv3_2fp16.bin", std::ios::binary); else if (6 == Lyr){ if (Pooling) feature.open("./data/pool3fp16.bin", std::ios::binary); else feature.open("./data/conv3_3.bin", std::ios::binary); } else if (7 == Lyr) feature.open("./data/conv4_1fp16.bin", std::ios::binary); else if (8 == Lyr) feature.open("./data/conv4_2fp16.bin", std::ios::binary); else if (9 == Lyr){ if (Pooling) feature.open("./data/pool4fp16.bin", std::ios::binary); else feature.open("./data/conv4_3.bin", std::ios::binary); } else if (10 == Lyr) feature.open("./data/conv5_1fp16.bin", std::ios::binary); else if (11 == Lyr) feature.open("./data/conv5_2fp16.bin", std::ios::binary); else if (12 == Lyr){ if (Pooling) feature.open("./data/pool5fp16.bin", std::ios::binary); else feature.open("./data/conv5_3fp16.bin", std::ios::binary); } int r_size = 0; if (Pooling) r_size = CHNEL[Lyr] * SHAPE[Lyr] * SHAPE[Lyr] >> 2; else r_size = CHNEL[Lyr] * SHAPE[Lyr] * SHAPE[Lyr]; Dtype *ref_feat = (Dtype *) malloc(r_size * sizeof(Dtype)); char *ref_char = reinterpret_cast<char *>(ref_feat); feature.read(ref_char, r_size * sizeof(Dtype)); int row_num = Pooling ? SHAPE[Lyr] / 2 : SHAPE[Lyr]; int col_num = Pooling ? SHAPE[Lyr] / 2 : SHAPE[Lyr]; for (int row = 0; row < row_num; row++) { for (int och = 0; och < CHNEL[Lyr]; och++) { for (int col = 0; col < col_num; col++) { int pos = row * CHNEL[Lyr] * row_num + och * col_num + col; Dtype ref = *(ref_feat + pos); Dtype out = *(Out + pos); if (ref < 10.0){ float abs_err = ref - out; if (-ABS_ERR <= abs_err && abs_err <= ABS_ERR) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check pass." << std::endl; else log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check fail." << std::endl; } else{ float rel_err = (ref - out) / ref; if (-REL_ERR <= rel_err && rel_err <= REL_ERR) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check pass." << std::endl; else log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check fail." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref data, " << ref << "; Compute data, " << out << std::endl; } } } free(ref_feat); feature.close(); return; } /* Check output from FC */ void fc_check(Dtype *Out, int Lyr) { std::ofstream log("check_fc_result.log", std::ios::app); std::ifstream fc_out; if(0 == Lyr) fc_out.open("./data/fc6_1fp16.bin", std::ios::binary); else if(1 == Lyr) fc_out.open("./data/fc6_2fp16.bin", std::ios::binary); else if(2 == Lyr) fc_out.open("./data/fc7_1fp16.bin", std::ios::binary); else if(3 == Lyr) fc_out.open("./data/fc7_2fp16.bin", std::ios::binary); else if(4 == Lyr) fc_out.open("./data/fc8fp16.bin", std::ios::binary); int out_len = CHNEL[13 + Lyr]; Dtype *ref_out = (Dtype *)malloc(out_len * sizeof(Dtype)); char *ref_out_char = reinterpret_cast<char *>(ref_out); fc_out.read(ref_out_char, out_len * sizeof(Dtype)); log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Check " << Lyr << "th layer." << std::endl; for (int m = 0; m < out_len; m++){ Dtype ref = ref_out[m]; Dtype out = Out[m]; float rel_err = (ref - out)/ ref; if (-REL_ERR <= rel_err && rel_err <= REL_ERR) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th data check pass." << std::endl; else log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th data check fail." << std::endl; log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref data, " << ref << "; Compute data, " << out << std::endl; } free(ref_out); fc_out.close(); return; } /* Check bias in FC layer */ void fc_bias_check(Dtype *Param, Dtype *BBuf, int Len) { std::ofstream log("check_fc_bias.log", std::ios::app); for (int n = 0; n < Len; n++){ Dtype ref = Param[n]; Dtype bias = BBuf[n]; if (ref == bias){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th bias check pass." << std::endl; } else{ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th bias check pass." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref, " << ref << "; On-chip, " << bias << std::endl; } return; } /* Check input in FC layer */ void fc_inbuf_check(Dtype *In, Dtype BufferA[BUFA_DEPTH], int Len) { std::ofstream log("check_fc_inbuf.log", std::ios::app); for (int n = 0; n < Len; n++){ Dtype ref = In[n]; Dtype data = BufferA[n]; if (ref == data){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th data check pass." << std::endl; } else{ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th data check pass." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref data, " << ref << "; On-chip data, " << data << std::endl; } return; } /* Check weight in FC layer */ void fc_weight_check(Dtype *Param, Dtype WBuf[128][1024], int ONum) { std::ofstream log("check_fc_weight.log", std::ios::app); for (int m = 0; m < ONum; m++){ for (int n = 0; n < 128; n++){ Dtype ref = *Param++; Dtype weight = WBuf[n][m]; if (ref == weight){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th inchnl, " << n << "th ochnl weight check pass." << std::endl; } else{ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th inchnl, " << n << "th ochnl weight check pass." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref, " << ref << "; On-chip, " << weight << std::endl; } } return; }
31.752809
105
0.456688
yuehniu
7552f7572a0397d169d54e2bfa7693a0e087a7f6
9,359
cpp
C++
Productivity-Companion/InputTodo.cpp
Despicable-Us/Productivity-Companion
2a18e9cc8c01c88012030ed599805298239da497
[ "CC0-1.0" ]
12
2021-11-22T11:49:26.000Z
2022-03-04T03:31:17.000Z
Productivity-Companion/InputTodo.cpp
Despicable-Us/Productivity-Companion
2a18e9cc8c01c88012030ed599805298239da497
[ "CC0-1.0" ]
null
null
null
Productivity-Companion/InputTodo.cpp
Despicable-Us/Productivity-Companion
2a18e9cc8c01c88012030ed599805298239da497
[ "CC0-1.0" ]
null
null
null
#include "InputTodo.h" #include "Database.h" //default constructor extern std::vector<udh::inputField> textList; extern std::vector<udh::inputField> completed; extern udh::inputField sampletext; udh::inputField::inputField() { this->font.loadFromFile("Fonts/Roboto-Medium.ttf"); this->textdata.setFont(font); this->textdata.setFillColor(sf::Color(0,0,0)); this->textdata.setString(""); this->textdata.setCharacterSize(16); // Icon loading and setting this->loadIconTexture(); //assigning day when task was created std::time_t current; std::time (&current); struct tm* timecreated; timecreated = std::localtime(&current); this->creationDay = timecreated->tm_year * 365 + timecreated->tm_mon * 30 + timecreated->tm_mday; } void udh::inputField::loadIconTexture() { if (!del_tex.loadFromFile("Texture/dust-bin1.png")) throw "Error in loading the 'dust_bin.png'"; if (!edit_tex.loadFromFile("Texture/pencil.png")) throw "Error in loading the 'pencil.png'"; del_icon = Icon(del_tex); edit_icon = Icon(edit_tex); } void udh::inputField::setdata(std::string str) { text = str; textdata.setString(text); } void udh::inputField::drawtext(sf::RenderWindow* window) { window->draw(textdata); } std::string udh::inputField::getdata() { return this->text; } sf::Text udh::inputField::gettext() { return textdata; } void udh::inputField::setposition(sf::Vector2f position) { textdata.setPosition(position); } sf::Font udh::inputField::getfont() { return font; } void udh::inputField::setdone() { this->completed = true; } bool udh::inputField::getstatus() { return this->completed; } int udh::inputField::getDay() { return this->creationDay; } void udh::inputField::setday(int a) { this->creationDay = a; } void udh::inputField::setCreationTime() { time_t current; time(&current); struct tm* timecreated = localtime(&current); char timebuffer[40]; strftime(timebuffer, 40, "%a %b %d %Y\n",timecreated); } std::string udh::inputField::SanitizedData() { size_t pos = 0; std::string data=this->getdata(); while ((pos = data.find('\'', pos)) != std::string::npos) { data.replace(pos, 1, "''"); pos += 2; } return data; } void udh::drawlist(std::vector<udh::inputField>& textlist, std::vector<udh::inputField>& completed, sf::RenderWindow* window) { float i = 0; if (!textlist.empty()) { for (std::vector<udh::inputField>::iterator itr = textlist.begin(); itr < textlist.end(); itr++) { sf::CircleShape cL(15.f), cR(15.f); sf::RectangleShape Rect; Rect.setSize({700.f, 30.f}); Rect.setPosition({ 20.f,i }); cL.setPosition(5.f, i); cR.setPosition(705.f, i); Rect.setFillColor(sf::Color(200, 200, 200)); cL.setFillColor(sf::Color(200, 200, 200)); cR.setFillColor(sf::Color(200, 200, 200)); itr->setposition(sf::Vector2f(50.f, i+5)); //setting up mark done button itr->done.setBtnPosition(sf::Vector2f(20.f, i + 9)); itr->done.setBtnSize(sf::Vector2f(12.f, 12.f)); itr->done.setbtnRect(sf::FloatRect(20.f, i + 5, 18.f, 18.f)); itr->done.setoutline(sf::Color(150, 150, 150), 2); itr->del_icon.Set_Icon_Pos({630.f, i+15}); window->draw(Rect); window->draw(cL); window->draw(cR); itr->done.drawTo(*window); itr->del_icon.Draw_To(*window); itr->edit_icon.Set_Icon_Pos({ 680.f, i + 15 }); itr->edit_icon.Draw_To(*window); itr->drawtext(window); itr->done.setbtncolor(sf::Color(235, 235, 235)); itr->textdata.setFillColor(sf::Color::Black); i += 40; } } if (!completed.empty()) { sf::CircleShape cL(15.f), cR(15.f); sf::RectangleShape Rect; Rect.setSize({ 105.f, 30.f }); Rect.setPosition({ 20.f, i }); cL.setPosition(5.f, i); cR.setPosition(110.f, i); Rect.setFillColor(sf::Color(COMPLETED_C)); cL.setFillColor(sf::Color(COMPLETED_C)); cR.setFillColor(sf::Color(COMPLETED_C)); sf::Font roboto_font; roboto_font.loadFromFile("Fonts/Roboto-Medium.ttf"); sf::Text completed_text("Completed", roboto_font, 16); completed_text.setPosition({ 30.f, i + 5.f }); completed_text.setFillColor(sf::Color::White); window->draw(Rect); window->draw(cL); window->draw(cR); window->draw(completed_text); i += 40; for (std::vector<udh::inputField>::iterator itr = completed.begin(); itr < completed.end(); itr++) { sf::CircleShape cL(15.f), cR(15.f); sf::RectangleShape Rect; Rect.setSize({ 700.f, 30.f }); Rect.setPosition({ 20.f,i }); cL.setPosition(5.f, i); cR.setPosition(705.f, i); Rect.setFillColor(sf::Color(200, 200, 200)); cL.setFillColor(sf::Color(200, 200, 200)); cR.setFillColor(sf::Color(200, 200, 200)); itr->setposition(sf::Vector2f(50.f, i + 5)); //setting up mark done button itr->done.setBtnPosition(sf::Vector2f(20.f, i + 9)); itr->done.setBtnSize(sf::Vector2f(12.f, 12.f)); itr->done.setbtnRect(sf::FloatRect(20.f, i + 5, 18.f, 18.f)); itr->done.setoutline(sf::Color(150, 150, 150), 2); itr->del_icon.Set_Icon_Pos({ 630.f, i + 15 }); window->draw(Rect); window->draw(cL); window->draw(cR); itr->done.drawTo(*window); itr->del_icon.Draw_To(*window); itr->drawtext(window); itr->done.setbtncolor(sf::Color(40, 40, 40)); itr->crossline.setPosition(sf::Vector2f(50, i + 14)); itr->crossline.setFillColor(sf::Color(40, 40, 40)); itr->crossline.setSize({ itr->gettext().getGlobalBounds().width + 1, 3 }); itr->textdata.setFillColor(sf::Color(100, 100, 100)); window->draw(itr->crossline); i += 40; } } } void udh::checkAction(sf::Event event,std::vector<udh::inputField>&list, sf::RenderWindow* window, std::vector<udh::inputField>::iterator& itredit, udh::inputField& sample, udh::Button& textarea, bool &selected) { for (std::vector<udh::inputField>::iterator itr = list.begin(); itr < list.end(); itr++) { if (itr->done.ispressed(event, *window)) { if (!itr->completed) { itr->completed = true; std::string sql = "UPDATE TASKS SET Status = " + std::to_string(itr->getstatus()) + " WHERE Task = '" + itr->SanitizedData() + "';"; completed.push_back(*itr); list.erase(itr); udh::UpdateStatus(sql); selected = false; } else if(itr->completed) { itr->completed = false; std::string sql = "UPDATE TASKS SET Status = " + std::to_string(itr->getstatus()) + " WHERE Task = '" + itr->SanitizedData() + "';"; textList.push_back(*itr); list.erase(itr); udh::UpdateStatus(sql); selected = false; } break; } else if (itr->del_icon.Run_Outside_Event(*window, event)) { udh::DeleteTask(itr); list.erase(itr); break; } else if (itr->edit_icon.Run_Outside_Event(*window, event) && !itr->completed) { itredit = itr; itr->edit.setbtncolor(sf::Color(150, 140, 220)); sample.setdata(itr->getdata()); textarea.setEditing(); textarea.setbtntext(""); textarea.setpressed(); break; } } } void udh::editTask(udh::inputField& sampletext, std::string& a, sf::Event event, std::vector<udh::inputField>::iterator& edititr, udh::Button& textarea) { unsigned char b; a = sampletext.getdata(); a.pop_back(); a.push_back('_'); sampletext.setdata(a); if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (b == 8) { if (!a.empty()) { a.pop_back(); if (!a.empty()) a.pop_back(); a.push_back('_'); sampletext.setdata(a); } } else if (b == 13) { if (a.length() > 1) { a.pop_back(); a.push_back('\n'); sampletext.setdata(a); udh::updateTask(edititr); edititr->setdata(a); edititr->edit.setbtncolor(sf::Color(235, 235, 235)); sampletext.setdata(""); a.erase(); textarea.unsetEditing(); textarea.releasePressed(); edititr->edit_icon.Set_Unheld(); } } else if (sampletext.gettext().getGlobalBounds().width <= 560) { a.pop_back(); a.push_back(b); a.push_back('_'); sampletext.setdata(a); } } } } void udh::addTask(udh::inputField& sampletext, std::string& a, sf::Event event, std::vector<udh::inputField>& textlist, udh::Button textarea, bool is_planner_list) { unsigned char b; if (sampletext.getdata().empty() && textarea.getstate()) { if (a.empty()) a.push_back('_'); sampletext.setdata(a); } if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (b == 8) { if (!a.empty()) { a.pop_back(); if (!a.empty()) a.pop_back(); a.push_back('_'); sampletext.setdata(a); } } else if (b == 13) { if (a.length() > 1) { a.pop_back(); a.push_back('\n'); sampletext.setdata(a); sampletext.setCreationTime(); textlist.push_back(sampletext); if (!is_planner_list) { udh::AddTask(sampletext); } sampletext.setdata(""); a = ""; } } else if (sampletext.gettext().getGlobalBounds().width <= 560 && !a.empty()) { a.pop_back(); a.push_back(b); a.push_back('_'); sampletext.setdata(a); } } } }
24.628947
163
0.635752
Despicable-Us
7559227d53fb15d1087d9057fe94c213920a541c
4,404
cpp
C++
ProjectEuler+/euler-0278.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0278.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0278.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
1
2021-05-28T11:14:34.000Z
2021-05-28T11:14:34.000Z
// //////////////////////////////////////////////////////// // # Title // Linear Combinations of Semiprimes // // # URL // https://projecteuler.net/problem=278 // http://euler.stephan-brumme.com/278/ // // # Problem // Given the values of integers `1 < a_1 < a_2 < ... < a_n`, consider the linear combination // `q_1 a_1 + q_2 a_2 + ... + q_n a_n = b`, using only integer values `q_k >= 0`. // // Note that for a given set of `a_k`, it may be that not all values of `b` are possible. // For instance, if `a_1 = 5` and `a_2 = 7`, there are no `q_1 >= 0` and `q_2 >= 0` such that `b` could be // 1, 2, 3, 4, 6, 8, 9, 11, 13, 16, 18 or 23. // In fact, 23 is the largest impossible value of `b` for `a_1 = 5` and `a_2 = 7`. // We therefore call `f(5, 7) = 23`. // Similarly, it can be shown that `f(6, 10, 15) = 29` and `f(14, 22, 77) = 195`. // // Find `sum{f(pq,pr,qr)}`, where `p`, `q` and `r` are prime numbers and `p < q < r < 5000`. // // # Solved by // Stephan Brumme // July 2017 // // # Algorithm // Assume I have two numbers `x` and `y` where `gcd(x,y)=1`. // The value `m = xy - x - y` can't be represented with some coefficients `m = px + qy` because: // `xy - x - y = px + qy` // `xy = px + qy + x + y` // `xy = (p+1)x + (q+1)y` // // `xy` is a multiple of `x` and `(p+1)x` is a multiple of `x`, hence `(q+1)y` should be a multiple of `x`, too. // `xy` is a multiple of `y` and `(q+1)y` is a multiple of `y`, hence `(p+1)x` should be a multiple of `y`, too. // But `gcd(x,y)=1` so `y` can't be a multiple of `x` and therefore `q+1` should be a multiple of `x`. // And for the same reason `x` can't be a multiple of `y` and therefore `p+1` should be a multiple of `y`. // Possible values for `q+1` would be `x`, `2x`, `3x`, ... (and for `p+1`: `y`, `2y`, `3y`, ...) // If I assume the lowest value `p+1=y` and `q+1=x` then the equation becomes // `xy = y * x + x * y` // `xy = 2xy` ==> contradition ! // // Therefore `m = xy - x - y` actually can't be represented with some coefficients `m = px + qy`. // // With three numbers `x`,`y`,`z` and `gcd(x,y,z)=1` the idea is very similar: // if there would be some coefficients `p`, `q` and `r` such that `m = pxy + qxz + ryz` represents `m = 2xyz - xy - xz - yz` then // `(2xyz - xy - xz - yz) mod x = -yz` // `pxy + qxz + ryz = 2xyz - xy - xz - yz` // `2xyz = pxy + qxz + ryz + xy + xz + yz` // `2xyz = (py+qz+y+z)x + (rz + z)y` // Hence `rz + z = (r+1)z` must be a multiple of `x`. `z` can't be such a multiple (because of `gcd(x,y,z) = 1`). // The same idea for `y` and `z` gives that `p+1` must be a multiple of `z` and `q+1` a multiple of `y`. // As before - if I choose the smallest possible `p+1=z`, `q+1=y` and `r+1=x`: // `2xyz = zxy + yxz + xyz + xy + xz + yz` // `2xyz = 3xyz + xy + xz + yz` ==> contradiction // // I didn't come up with the full solution, I just know how to use search engines :-; // I found the problem in the 24th International Mathemtical Olympiad held 1983 in Paris, France // somewhat cryptic solution: http://www.cs.cornell.edu/~asdas/imo/imo/isoln/isoln833.html // I stumbled across it while reading the German Wikipedia https://de.wikipedia.org/wiki/M%C3%BCnzproblem // unfortunately, the English page misses that special case https://en.wikipedia.org/wiki/Coin_problem // but it can be derived from their `n=2` explanations (pretty much what I have done above) #include <iostream> #include <vector> int main() { unsigned int limit = 5000; std::cin >> limit; // simple prime sieve from my toolbox std::vector<unsigned long long> primes = { 2 }; for (unsigned int i = 3; i <= limit; i += 2) { bool isPrime = true; // test against all prime numbers we have so far (in ascending order) for (auto x : primes) { // prime is too large to be a divisor if (x*x > i) break; // divisible => not prime if (i % x == 0) { isPrime = false; break; } } // yes, we have a prime if (isPrime) primes.push_back(i); } // all combinations of primes unsigned long long sum = 0; for (size_t i = 0; i < primes.size(); i++) for (size_t j = i + 1; j < primes.size(); j++) for (size_t k = j + 1; k < primes.size(); k++) { auto p = primes[i]; auto q = primes[j]; auto r = primes[k]; sum += 2*p*q*r - p*q - p*r - q*r; } std::cout << sum << std::endl; return 0; }
39.321429
129
0.576067
sarvekash
75594f0eca0759b6efde094fb69d845c8d7336ae
2,501
cpp
C++
DecodeString.cpp
GolferChen/LeetCode
b502a57ff1ebe8daf670e7b068dd98cec0b9bf38
[ "MIT" ]
null
null
null
DecodeString.cpp
GolferChen/LeetCode
b502a57ff1ebe8daf670e7b068dd98cec0b9bf38
[ "MIT" ]
null
null
null
DecodeString.cpp
GolferChen/LeetCode
b502a57ff1ebe8daf670e7b068dd98cec0b9bf38
[ "MIT" ]
null
null
null
// // Created by Golfer on 2020/7/28. // #include <string> #include <stack> using namespace std; #include <cstdio> #include <iostream> // Version 1, Stack //class Solution { //public: // string decodeString(string s) { // stack<string> stack_string; // stack<int> stack_num; // int number = 0; // string result= ""; // for (char &c : s) { //// if ('0' <= c <= '9') { // wrong !!! //// number = number * 10 + c - '0'; //// } // if ('0' <= c && c <= '9') { // number = number * 10 + c - '0'; // } // else if (c == '[') { // stack_num.push(number); // number = 0; // stack_string.push(result); // result = ""; // } // else if (c == ']') { // int num = stack_num.top(); // stack_num.pop(); // string last_string = stack_string.top(); // stack_string.pop(); // string result_tmp = result; // for (int i = 0; i < num - 1; i++) { // result += result_tmp; // } // result = last_string + result; //// result = last_string + result // } // else { // result += c; // } // } // return result; // } //}; // Version 2, recrusive class Solution { public: string decodeString(string s) { return dfs(s, 0).second; } pair<int, string> dfs(string s, int i) { int number = 0; string result = ""; while (i < s.size()) { char c = s[i]; if (c >= '0' && c <= '9') { number = number * 10 + c - '0'; } else if (c == '[') { pair<int, string> dfs_call = dfs(s, i + 1); i = dfs_call.first; string tmp = dfs_call.second; for (int j = 0; j < number; j++) result += tmp; number = 0; } else if (c == ']') { return make_pair(i, result); } else { result += c; } ++i; } return make_pair(-1, result); } }; int main() { string s = "3[a]2[bc]"; Solution solution = Solution(); string decode_s = solution.decodeString(s); cout << decode_s << endl; return 0; }
26.606383
59
0.387845
GolferChen
7559e00fbea33a8739a688ccab89f9bb06122363
2,753
cpp
C++
MySpaceShooter/src/Gameplay/SpaceShip.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
MySpaceShooter/src/Gameplay/SpaceShip.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
MySpaceShooter/src/Gameplay/SpaceShip.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
#include "SpaceShip.h" namespace Game { void SpaceShip::Update() { UpdateSpaceShipPosition(); UpdateSpaceShipRotation(); UpdateCameraPose(); UpdateSpaceshipGun(); } glm::vec3 SpaceShip::GetControllerIRotationnput() { // Calculate controller input with deadzone auto& cont = m_Controller; glm::vec3 rotation = glm::length(glm::vec3(cont->GetOrientation().z, -cont->GetOrientation().x, 0)) > DEADZONE ? glm::vec3(cont->GetOrientation().z, -cont->GetOrientation().x, 0) : glm::vec3(0, 0, 0); return rotation; } bool SpaceShip::GetControllerButtonInput() { std::cout << m_Controller->IsProximity() << "\n"; return m_Controller->IsProximity(); } void SpaceShip::UpdateSpaceShipRotation() { // Get rotation from spaceship glm::vec3 rot = m_Object->GetRotation(); // Corrent Angles if (m_Object->GetRotation().x > 180 || m_Object->GetRotation().x < -180) rot.x = -rot.x; if (m_Object->GetRotation().y > 180 || m_Object->GetRotation().y < -180) rot.y = -rot.y; if (m_Object->GetRotation().z > 180 || m_Object->GetRotation().z < -180) rot.z = -rot.z; m_Object->SetRotation(rot); // Correct controller input when upside down glm::vec3 input = GetControllerIRotationnput(); if (m_Object->GetRotation().x > 90 || m_Object->GetRotation().x < -90) input.y = -input.y; // Rotate spaceship m_Object->Rotate(input * Core::Time::GetDeltaTime()); } void SpaceShip::UpdateSpaceShipPosition() { // Move spaceship forward m_Object->Translate(m_Object->GetForward() * Core::Time::GetDeltaTime() * SPACESHIP_SPEED); // Move spaceship back if it goes out of bounds glm::vec3 pos = m_Object->GetPosition(); if (m_Object->GetPosition().x > PLAYFIELD_SIZE || m_Object->GetPosition().x < -PLAYFIELD_SIZE) pos.x = -pos.x; if (m_Object->GetPosition().y > PLAYFIELD_SIZE || m_Object->GetPosition().y < -PLAYFIELD_SIZE) pos.y = -pos.y; if (m_Object->GetPosition().z > PLAYFIELD_SIZE || m_Object->GetPosition().z < -PLAYFIELD_SIZE) pos.z = -pos.z; m_Object->SetPosition(pos); } void SpaceShip::UpdateCameraPose() { // Correct reverse rotation glm::vec3 rot = m_Object->GetRotation(); rot.y += 180; rot.x = -rot.x; rot.z = -rot.z; // Set camera rotation and position m_Camera->SetRotation(rot); m_Camera->SetPosition(m_Object->GetPosition() + m_Object->GetForward() * 800 + m_Object->GetUp() * 10); } void SpaceShip::UpdateSpaceshipGun() { // If button is held shoot at BULLET SHOOT SPEED rate if (GetControllerButtonInput() && m_ShootTime > BULLET_SHOOT_SPEED) { m_ShootTime = 0; m_BulletPool.SpawnBullet(m_Object->GetPosition(), m_Object->GetRotation()); } m_ShootTime += Core::Time::GetDeltaTime(); m_BulletPool.Update(); } }
28.091837
105
0.680349
TygoB-B5
755aaab5f9350ef704e1545ecd661418f70e1e57
389
hpp
C++
Hurrican/src/stdafx.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
21
2018-04-13T10:45:45.000Z
2022-03-29T14:53:43.000Z
Hurrican/src/stdafx.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
10
2021-06-30T14:29:36.000Z
2022-01-06T17:03:48.000Z
Hurrican/src/stdafx.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
3
2021-10-08T12:35:05.000Z
2022-03-03T06:03:49.000Z
#ifndef _STDAFX_HPP_ #define _STDAFX_HPP_ #include "Console.hpp" #include "DX8Font.hpp" #include "DX8Sound.hpp" #include "GUISystem.hpp" #include "Gameplay.hpp" #include "Globals.hpp" #include "HUD.hpp" #include "Logdatei.hpp" #include "Mathematics.hpp" #include "Partikelsystem.hpp" #include "Player.hpp" #include "Projectiles.hpp" #include "Tileengine.hpp" #include "Timer.hpp" #endif
19.45
29
0.758355
s1eve-mcdichae1
755db57e3190fddc30ff73cdb43146adb417b9e5
1,259
cpp
C++
LeetCode/C++/144_Binary_Tree_Preorder_Traversal.cpp
icgw/LeetCode
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
4
2018-09-12T09:32:17.000Z
2018-12-06T03:17:38.000Z
LeetCode/C++/144_Binary_Tree_Preorder_Traversal.cpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
LeetCode/C++/144_Binary_Tree_Preorder_Traversal.cpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
/* Given a binary tree, return the preorder traversal of its nodes' values. * * Example: * Input: [1, null, 2, 3] * 1 * \ * 2 * / * 3 * Output: [1, 2, 3] * * Follow up: Recursive solution is trivial, could you do it iteratively? */ #include <iostream> #include <vector> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: static vector<int> preorderTraversal(TreeNode* root){ vector<int> tra; if (!root) return tra; stack<TreeNode*> stk; stk.push(root); TreeNode *tmp; while (!stk.empty()){ tmp = stk.top(); stk.pop(); tra.push_back(tmp->val); if (tmp->right) stk.push(tmp->right); if (tmp->left) stk.push(tmp->left); } return tra; } }; int main(int argc, char *argv[]){ TreeNode* tree = new TreeNode(1); tree->left = new TreeNode(2); tree->right = new TreeNode(3); tree->left->left = new TreeNode(4); tree->left->right = new TreeNode(5); tree->right->left = new TreeNode(6); tree->right->right = new TreeNode(7); vector<int> ans = Solution::preorderTraversal(tree); for (auto& x : ans) cout << x << " "; cout << endl; return 0; }
21.706897
75
0.612391
icgw
755f00c26dd122d684c7a1211db67d8f9181ba13
9,419
cpp
C++
lepra/src/metafile.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
9
2019-09-03T18:33:31.000Z
2022-02-04T04:00:02.000Z
lepra/src/metafile.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
lepra/src/metafile.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
// Author: Jonas Byström // Copyright (c) Pixel Doctrine #include "pch.h" #include "../include/metafile.h" #include <algorithm> #include "../include/path.h" namespace lepra { MetaFile::MetaFile() : disk_file_(0), archive_file_(0), reader_(0), writer_(0), endian_(Endian::kTypeBigEndian) { } MetaFile::MetaFile(Reader* reader) : disk_file_(0), archive_file_(0), reader_(reader), writer_(0), endian_(Endian::kTypeBigEndian) { } MetaFile::MetaFile(Writer* writer) : disk_file_(0), archive_file_(0), reader_(0), writer_(writer), endian_(Endian::kTypeBigEndian) { } MetaFile::MetaFile(Reader* reader, Writer* writer) : disk_file_(0), archive_file_(0), reader_(reader), writer_(writer), endian_(Endian::kTypeBigEndian) { } MetaFile::~MetaFile() { Close(); } bool MetaFile::Open(const str& file_name, OpenMode mode, bool create_path, Endian::EndianType endian) { Close(); SetEndian(endian); bool ok = false; size_t _split_index = 0; str path; str file; bool do_continue = true; // Find a valid combination of archive and file... while (do_continue) { do_continue = SplitPath(file_name, path, file, _split_index); if (_split_index == 0) { ok = DiskFile::Exists(path); if (ok) { AllocDiskFile(); ok = disk_file_->Open(path, ToDiskFileMode(mode), create_path, endian); if (ok) { do_continue = false; } else { Close(); } } } else { str _archive_name; ok = FindValidArchiveName(path, _archive_name); if (ok) { AllocArchiveFile(_archive_name); ok = archive_file_->Open(file, ToArchiveMode(mode), endian); } if (ok) { do_continue = false; } else { Close(); } } _split_index++; } ok = (disk_file_ != 0 || archive_file_ != 0); return ok; } void MetaFile::Close() { if (disk_file_ != 0) { disk_file_->Close(); delete disk_file_; disk_file_ = 0; } else if (archive_file_ != 0) { archive_file_->Close(); delete archive_file_; archive_file_ = 0; } } void MetaFile::SetEndian(Endian::EndianType endian) { endian_ = endian; Parent::SetEndian(endian); if (disk_file_ != 0) { disk_file_->SetEndian(endian_); } else if (archive_file_ != 0) { archive_file_->SetEndian(endian_); } } Endian::EndianType MetaFile::GetEndian() { return endian_; } int64 MetaFile::GetSize() const { int64 _size = 0; if (disk_file_ != 0) { _size = disk_file_->GetSize(); } else if (archive_file_ != 0) { _size = archive_file_->GetSize(); } return _size; } int64 MetaFile::Tell() const { int64 pos = 0; if (disk_file_ != 0) { pos = disk_file_->Tell(); } else if (archive_file_ != 0) { pos = archive_file_->Tell(); } return pos; } int64 MetaFile::Seek(int64 offset, FileOrigin from) { int64 _offset = 0; if (disk_file_ != 0) { _offset = disk_file_->Seek(offset, from); } else if (archive_file_ != 0) { _offset = archive_file_->Seek(offset, from); } return _offset; } str MetaFile::GetFullName() const { if (disk_file_ != 0) { return disk_file_->GetFullName(); } else if (archive_file_ != 0) { return archive_file_->GetFullName(); } return ""; } str MetaFile::GetName() const { if (disk_file_ != 0) { return disk_file_->GetName(); } else if (archive_file_ != 0) { return archive_file_->GetName(); } return ""; } str MetaFile::GetPath() const { if (disk_file_ != 0) { return disk_file_->GetPath(); } else if (archive_file_ != 0) { return archive_file_->GetPath(); } return ""; } IOError MetaFile::ReadData(void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->ReadData(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->ReadData(buffer, size); } return error; } IOError MetaFile::WriteData(const void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->WriteData(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->WriteData(buffer, size); } return error; } int64 MetaFile::GetAvailable() const { int64 available = 0; if (disk_file_ != 0) { available = disk_file_->GetAvailable(); } else if (archive_file_ != 0) { available = archive_file_->GetAvailable(); } return available; } IOError MetaFile::ReadRaw(void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->ReadRaw(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->ReadRaw(buffer, size); } return error; } IOError MetaFile::Skip(size_t size) { return (Parent::Skip(size)); } IOError MetaFile::WriteRaw(const void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->WriteRaw(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->WriteRaw(buffer, size); } return error; } void MetaFile::Flush() { if (disk_file_ != 0) { disk_file_->Flush(); } else if (archive_file_ != 0) { archive_file_->Flush(); } } void MetaFile::AllocDiskFile() { if(reader_ != 0 && writer_ != 0) { disk_file_ = new DiskFile(reader_, writer_); } else if(reader_ != 0) { disk_file_ = new DiskFile(reader_); } else if(writer_ != 0) { disk_file_ = new DiskFile(writer_); } else { disk_file_ = new DiskFile(); } disk_file_->SetEndian(endian_); } void MetaFile::AllocArchiveFile(const str& archive_name) { if(reader_ != 0 && writer_ != 0) { archive_file_ = new ArchiveFile(archive_name, reader_, writer_); } else if(reader_ != 0) { archive_file_ = new ArchiveFile(archive_name, reader_); } else if(writer_ != 0) { archive_file_ = new ArchiveFile(archive_name, writer_); } else { archive_file_ = new ArchiveFile(archive_name); } if (IsZipFile(Path::GetExtension(archive_name))) { archive_file_->SetArchiveType(ArchiveFile::kZip); } else { archive_file_->SetArchiveType(ArchiveFile::kUncompressed); } archive_file_->SetEndian(endian_); } DiskFile::OpenMode MetaFile::ToDiskFileMode(OpenMode mode) { DiskFile::OpenMode _mode = DiskFile::kModeRead; switch (mode) { case kReadOnly: { _mode = DiskFile::kModeRead; break; } case kWriteOnly: { _mode = DiskFile::kModeWrite; break; } case kWriteAppend: { _mode = DiskFile::kModeWriteAppend; break; } } return _mode; } ArchiveFile::OpenMode MetaFile::ToArchiveMode(OpenMode mode) { ArchiveFile::OpenMode _mode = ArchiveFile::kReadOnly; switch (mode) { case kReadOnly: { _mode = ArchiveFile::kReadOnly; break; } case kWriteOnly: { _mode = ArchiveFile::kWriteOnly; break; } case kWriteAppend: { _mode = ArchiveFile::kWriteAppend; break; } } return _mode; } bool MetaFile::IsZipFile(const str& extension) { bool ok = false; if (zip_extensions_ != 0) { ok = (std::find(zip_extensions_->begin(), zip_extensions_->end(), extension) != zip_extensions_->end()); } return ok; } bool MetaFile::IsUncompressedArchive(const str& extension) { bool ok = false; if (archive_extensions_ != 0) { ok = (std::find(archive_extensions_->begin(), archive_extensions_->end(), extension) != archive_extensions_->end()); } return ok; } void MetaFile::AddZipExtension(const str& extension) { if (zip_extensions_ == 0) { zip_extensions_ = new std::list<str>(); } zip_extensions_->push_back(extension); zip_extensions_->sort(); zip_extensions_->unique(); } void MetaFile::AddUncompressedExtension(const str& extension) { if (archive_extensions_ == 0) { archive_extensions_ = new std::list<str>(); } archive_extensions_->push_back(extension); archive_extensions_->sort(); archive_extensions_->unique(); } void MetaFile::ClearExtensions() { if (zip_extensions_) { zip_extensions_->clear(); delete zip_extensions_; zip_extensions_ = 0; } if (archive_extensions_) { archive_extensions_->clear(); delete archive_extensions_; archive_extensions_ = 0; } } std::list<str>* MetaFile::zip_extensions_; std::list<str>* MetaFile::archive_extensions_; bool MetaFile::SplitPath(const str& filename, str& left, str& right, size_t split_index) { bool ok = true; size_t _split_index = filename.length(); size_t i; for (i = 0; i < split_index; i++) { int index1 = (int)filename.rfind((char)'/', _split_index-1); int index2 = (int)filename.rfind((char)'\\', _split_index-1); if (index1 > index2) { _split_index = index1; } else if (index2 > index1) { _split_index = index2; } else if (index1 == -1 && index2 == -1) { _split_index = 0; ok = false; break; } } left = filename.substr(0, _split_index); right = filename.substr(_split_index); if (!right.empty() && (right[0] == '/' || right[0] == '\\')) { right.erase(0, 1); } return ok; } bool MetaFile::FindValidArchiveName(const str& archive_prefix, str& full_archive_name) { std::list<str>::iterator iter; bool ok = false; if (zip_extensions_ != 0) { for (iter = zip_extensions_->begin(); iter != zip_extensions_->end(); ++iter) { str _file_name(archive_prefix + (*iter)); if (DiskFile::Exists(_file_name) == true) { full_archive_name = _file_name; ok = true; break; } } } if (ok == false && archive_extensions_ != 0) { for (iter = archive_extensions_->begin(); iter != archive_extensions_->end(); ++iter) { str _file_name(archive_prefix + (*iter)); if (DiskFile::Exists(_file_name) == true) { full_archive_name = _file_name; ok = true; break; } } } return ok; } }
20.655702
118
0.669498
highfestiva
755f0257792b6d75a9c44b69ae9cf39ae2f5185b
4,172
cpp
C++
src/lib/lgui/widgets/wrapwidget.cpp
jacmoe/lgui
92f7e655832487b9ac29ef6043a79745329c90f6
[ "BSD-3-Clause" ]
4
2020-12-31T00:01:32.000Z
2021-11-20T15:39:46.000Z
src/lib/lgui/widgets/wrapwidget.cpp
jacmoe/lgui
92f7e655832487b9ac29ef6043a79745329c90f6
[ "BSD-3-Clause" ]
null
null
null
src/lib/lgui/widgets/wrapwidget.cpp
jacmoe/lgui
92f7e655832487b9ac29ef6043a79745329c90f6
[ "BSD-3-Clause" ]
1
2021-11-10T16:55:09.000Z
2021-11-10T16:55:09.000Z
/* _ _ * | | (_) * | | __ _ _ _ _ * | | / _` || | | || | * | || (_| || |_| || | * |_| \__, | \__,_||_| * __/ | * |___/ * * Copyright (c) 2015-20 frank256 * * License (BSD): * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "wrapwidget.h" #include "lgui/platform/graphics.h" #include "lgui/drawevent.h" namespace lgui { WrapWidget::WrapWidget(Widget* widget) : mcontent(widget) { if (widget) set_content(widget); } void WrapWidget::draw(const DrawEvent& de) const { if (mcontent) { // FIXME: draw backgr. when mcontent == nullptr? draw_background(de); de.gfx().push_draw_area(children_area(), false); mcontent->draw(DrawEvent(de.gfx(), de.draw_disabled() || mcontent->is_disabled(), de.opacity() * mcontent->effective_opacity())); de.gfx().pop_draw_area(); } } Rect WrapWidget::children_area() const { if (mcontent) return lgui::Rect(mpadding.left_top_offs(), mpadding.sub(size())); else return size_rect(); } Widget* WrapWidget::get_child_at(PointF) { // FIXME: check contains? return mcontent; } void WrapWidget::set_content(lgui::Widget* widget) { mcontent = widget; if (widget) { widget->set_pos(0, 0); configure_new_child(*widget); if (!widget->has_strong_style() && &widget->style() != &style()) widget->set_style(&style()); request_layout(); } } void WrapWidget::style_changed() { if (mcontent && !mcontent->has_strong_style()) mcontent->set_style(&style()); } void WrapWidget::resized(const Size& old_size) { (void) old_size; if (mcontent) { mcontent->layout(Rect({0, 0}, mpadding.sub(size()))); } } void WrapWidget::set_padding(const Padding& padding) { mpadding = padding; set_size(Size(width(), height())); // will set size of content } MeasureResults WrapWidget::measure(SizeConstraint wc, SizeConstraint hc) { if (!mcontent) return force_size_constraints(Size(mpadding.horz(), mpadding.vert()), wc, hc); else { MeasureResults r = mcontent->measure(wc.sub(mpadding.horz()), hc.sub(mpadding.vert())); return force_size_constraints(mpadding.add(r), wc, hc); } } Size WrapWidget::min_size_hint() { Size s; if (mcontent) s = mcontent->min_size_hint(); return mpadding.add(s); } void WrapWidget::visit_down(const std::function<void(Widget&)>& f) { f(*this); if (mcontent) mcontent->visit_down(f); } void WrapWidget::child_about_to_die(Widget& child) { if (&child == mcontent) set_content(nullptr); } }
31.368421
95
0.659156
jacmoe
7561738404c4724e9c0ea390ee747020e653f54a
654
cpp
C++
codechef/febLongChallenge20/ony.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
codechef/febLongChallenge20/ony.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
codechef/febLongChallenge20/ony.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
// vovuh.pb(temp);vovuh.pb(temp1);vovuh.pb(temp2);vovuh.pb(temp3); for(int tat = 0; tat <= 3; tat++) { auto x = adj[tat]; int sz = x.size(); if (sz > 0) { sort(x.begin(),x.end(),greater<int>()); if (x[0] > 0) vovuh.pb(x[0]); } } sort(vovuh.begin(), vovuh.end(),greater<int>()); // ll cnt = 0; cout << temp4 << " is the new ans" << endl; for (auto ss : vovuh) { cout << ss << " "; } ll lauda = 1, vovuhKaSize = vovuh.size(); temp4 -= 100*(4-vovuhKaSize); for (int i = 0; i < vovuhKaSize; i++) { temp4 +=(100-25*(lauda-1))*vovuh[i]; lauda++; } // ans = max(ans, temp4); if (temp4 > ans) { ans = temp4; cout << endl; }
21.8
66
0.529052
xenowits
756286d348fbeee56dd518ef8d73d72403bdc748
476
cpp
C++
Project2/main.cpp
cpurev/CS311
c86bb0dc917ff98edf698adedb4c3f0f9745ce9f
[ "MIT" ]
null
null
null
Project2/main.cpp
cpurev/CS311
c86bb0dc917ff98edf698adedb4c3f0f9745ce9f
[ "MIT" ]
null
null
null
Project2/main.cpp
cpurev/CS311
c86bb0dc917ff98edf698adedb4c3f0f9745ce9f
[ "MIT" ]
1
2021-11-16T05:01:57.000Z
2021-11-16T05:01:57.000Z
#include "ssarray.h" #include <iostream> #include <utility> #include <string> class Count{ public: Count(){ ++_ctorCount; } ~Count(){ --_ctorCount; ++_DctorCount; } static size_t _ctorCount; static size_t _DctorCount; }; size_t Count::_ctorCount = size_t(0); size_t Count::_DctorCount = size_t(0); int main(){ SSArray<std::string> ss1; SSArray<int> ss2; std::cout << ((ss1 == ss2) ? "yes" : "no") << std::endl; return 1; }
15.354839
58
0.602941
cpurev
75662c717c2d191852fb1b9030c03cedb4756939
2,696
cpp
C++
09-lcd/02-lcd-reg/lcd-reg.cpp
initdb/embedded-systems
7a716a22a045510a9cccded6c15a40ac3ed72858
[ "MIT" ]
3
2019-03-19T19:59:05.000Z
2019-11-22T19:02:56.000Z
09-lcd/02-lcd-reg/lcd-reg.cpp
initdb/embedded-systems
7a716a22a045510a9cccded6c15a40ac3ed72858
[ "MIT" ]
null
null
null
09-lcd/02-lcd-reg/lcd-reg.cpp
initdb/embedded-systems
7a716a22a045510a9cccded6c15a40ac3ed72858
[ "MIT" ]
1
2019-03-26T17:16:09.000Z
2019-03-26T17:16:09.000Z
#include "Arduino.h" #include <LiquidCrystal.h> #define RS 12 // controls RS pin of LCD (digital pin 12) #define E 11 // controls Enable pin to LCD (digital pin 11) // Note: Not need to control RW pin: it's set to GND by hardware since we always write and never read void enablePulse() { digitalWrite(E, LOW); delayMicroseconds(3); digitalWrite(E, HIGH); delayMicroseconds(3); // enable pulse must be > 450 ns, see p49 of HD44780 manual digitalWrite(E, LOW); delayMicroseconds(200); // commands need > 37 us to settle } // write an instruction, indicated by RS == LOW void writeInstruction(char instr) { digitalWrite(RS, LOW); PORTC = instr; enablePulse(); // commit command, short pulse on E pin PORTC = (instr << 4); enablePulse(); } // write character, indicated by RS == HIGH, automatically moves cursor void writeData(char data) { digitalWrite(RS, HIGH); PORTC = data; enablePulse(); // commit command, short pulse on E pin PORTC = (data << 4); enablePulse(); } void setup() { // set pins to output pinMode(RS, OUTPUT); pinMode(E, OUTPUT); DDRC = 0xF0; // data pins PC7 to PC4 // Set RS and E to Low to begin commands digitalWrite(RS, LOW); digitalWrite(E, LOW); // manual HD44780, p46, Figure 24: initialization specification for 4-bit mode // wait for more than 15 ms delay(30); // initialization sequence (Figure 24): sequence (0 0 0 0 1 1), then wait for > 4.1 ms PORTC = (0x03 << 4); enablePulse(); delay(5); // initialization sequence (Figure 24): sequence (0 0 0 0 1 1), then wait for > 100 us PORTC = (0x03 << 4); // only highest byte enablePulse(); delayMicroseconds(200); // initialization sequence: sequence (0 0 0 0 1 1) PORTC = (0x03 << 4); // only highest byte enablePulse(); delayMicroseconds(50); //finally, set to 4-bit interface: (0 0 0 0 1 1) PORTC = (0x02 << 4); enablePulse(); // TODO: Function Set, 4-bit, 2 line mode, 5x8 dots // TODO: Return Home, set cursor to beginning delayMicroseconds(2500); // TODO: Entry Mode Set, increment cursor, no display shift // clear display: 0x01 writeInstruction(0x01); delayMicroseconds(300); } void loop() { // set cursor to beginning if first line: command 0x80 (DDRAM address 0x00, see p11 of manual) writeInstruction(0x80); char line1[] = {"Embedded Systems "}; // TODO: Write line 1 // set cursor to beginning of 2nd line line: command 0xC0 (DDRAM address 0x40, see p11 of manual) writeInstruction(0xC0); char line2[] = {"macht Spass"}; // TODO: Write line 2 }
26.431373
101
0.640208
initdb
75681b4297eca4f3ba317ff88d40fde6acf4530a
272
cpp
C++
src/world/light.cpp
fiddleplum/ve
1e45de0488d593069032714ebe67725f468054f8
[ "MIT" ]
null
null
null
src/world/light.cpp
fiddleplum/ve
1e45de0488d593069032714ebe67725f468054f8
[ "MIT" ]
16
2016-12-27T16:57:09.000Z
2017-04-30T23:34:58.000Z
src/world/light.cpp
fiddleplum/ve
1e45de0488d593069032714ebe67725f468054f8
[ "MIT" ]
null
null
null
#include "world/light.hpp" namespace ve { namespace world { Light::Light() { color = {1, 1, 1}; } Light::~Light() { } Vector3f Light::getColor() const { return color; } void Light::setColor(Vector3f color_) { color = color_; } } }
9.714286
39
0.558824
fiddleplum
756ba6c9e52a7081be16b9be4f2173e1c55f0da0
1,270
cpp
C++
Source/Archiver/FileSerializer.cpp
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
Source/Archiver/FileSerializer.cpp
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
Source/Archiver/FileSerializer.cpp
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
// Copyright 2020, Nathan Blane #include "FileSerializer.hpp" #include "Logging/CoreLogChannels.hpp" #include "Logging/LogFunctions.hpp" FileSerializer::FileSerializer(const Path& filePath) : pathToFile(filePath) { bool result = FileSystem::OpenFile(handle, pathToFile.GetString(), FileMode::Write); if (!result) { // TODO - GetLastError MUSA_ERR(SerializationLog, "Failed to open file {}", *pathToFile.GetFileName()); } } FileSerializer::~FileSerializer() { Flush(); auto result = FileSystem::CloseFile(handle); if (!result) { // TODO - GetLastError MUSA_ERR(SerializationLog, "Failed to close file {}", *pathToFile.GetFileName()); } } void FileSerializer::SerializeData(const void* data, size_t dataSize) { serializedData.Add(data, dataSize); } void FileSerializer::Flush() { // TODO - Using the low level file writing interface. Should consider not doing this sort of thing because of the limitations for loading large files auto result = FileSystem::WriteFile(handle, serializedData.Offset(bufferWriteIndex), (u32)serializedData.Size() - bufferWriteIndex); if (!result) { // TODO - GetLastError MUSA_ERR(SerializationLog, "Failed to write to file {}", *pathToFile.GetFileName()); } bufferWriteIndex = (u32)serializedData.Size(); }
27.608696
150
0.740157
frobro98
756e3e110e56ec813d1c8c29b1be78995bbef5f2
1,737
hh
C++
dune/xt/common/numeric.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
2
2020-02-08T04:08:52.000Z
2020-08-01T18:54:14.000Z
dune/xt/common/numeric.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
35
2019-08-19T12:06:35.000Z
2020-03-27T08:20:39.000Z
dune/xt/common/numeric.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
1
2020-02-08T04:09:34.000Z
2020-02-08T04:09:34.000Z
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // René Fritze (2020) // Tobias Leibner (2019 - 2020) #ifndef DUNE_XT_COMMON_NUMERIC_HH #define DUNE_XT_COMMON_NUMERIC_HH #include <numeric> #if defined(__cpp_lib_parallel_algorithm) && __cpp_lib_parallel_algorithm >= 201603 # define CPP17_PARALLELISM_TS_SUPPORTED 1 #else # define CPP17_PARALLELISM_TS_SUPPORTED 0 #endif namespace Dune::XT::Common { // Uses std::reduce if available, and falls back to std::accumulate on older compilers. // The std::reduce versions with an execution policy as first argument are not supported. template <class... Args> decltype(auto) reduce(Args&&... args) { #if CPP17_PARALLELISM_TS_SUPPORTED return std::reduce(std::forward<Args>(args)...); #else return std::accumulate(std::forward<Args>(args)...); #endif } // Uses std::transform_reduce if available, and falls back to std::inner_product on older compilers. // The std::transform_reduce versions with an execution policy as first argument are not supported. template <class... Args> decltype(auto) transform_reduce(Args&&... args) { #if CPP17_PARALLELISM_TS_SUPPORTED return std::transform_reduce(std::forward<Args>(args)...); #else return std::inner_product(std::forward<Args>(args)...); #endif } } // namespace Dune::XT::Common #endif // DUNE_XT_COMMON_NUMERIC_HH
32.773585
100
0.745538
dune-community
757109a8c12f857a049986a1b25b17804c53d25f
12,809
cpp
C++
src/c/HarmoniaInterface.cpp
Hiiragi/Harmonia
e47e811364e15a9bc7b2322c10d1e35fca041e2a
[ "MIT" ]
null
null
null
src/c/HarmoniaInterface.cpp
Hiiragi/Harmonia
e47e811364e15a9bc7b2322c10d1e35fca041e2a
[ "MIT" ]
null
null
null
src/c/HarmoniaInterface.cpp
Hiiragi/Harmonia
e47e811364e15a9bc7b2322c10d1e35fca041e2a
[ "MIT" ]
null
null
null
/** * Harmonia * * Copyright (c) 2018 Hiiragi * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ #include "HarmoniaInterface.h" #include "Harmonia.h" #include "ogg/ogg.h" #include <algorithm> #include <string> #include <sstream> // General #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_initialize(unsigned int bufferSize) { Harmonia::initialize(bufferSize); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_finalize() { Harmonia::finalize(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_register_sound(const char* id, unsigned char* binaryData, int size, unsigned int loopStartPoint, unsigned int loopLength) { Harmonia::register_sound(id, binaryData, size, loopStartPoint, loopLength); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_register_sounds(const char** idList, unsigned char** binaryDataList, int* sizeList, unsigned int* loopStartPointList, unsigned int* loopLengthList, unsigned int numRegister) { Harmonia::register_sounds(idList, binaryDataList, sizeList, loopStartPointList, loopLengthList, numRegister); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_unregister_sound(const char* id) { Harmonia::unregister_sound(id); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_pause_all() { Harmonia::pause(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_resume_all() { Harmonia::resume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_stop_all() { Harmonia::stop(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif float harmonia_get_master_volume() { SoundGroup* masterGroup = Harmonia::get_group(Harmonia::MASTER_GROUP_NAME.c_str()); return masterGroup->get_volume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_master_volume(float volume) { SoundGroup* masterGroup = Harmonia::get_group(Harmonia::MASTER_GROUP_NAME.c_str()); return masterGroup->set_volume(volume); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_mute_all() { Harmonia::mute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_unmute_all() { Harmonia::unmute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_start_capture_errors() { Harmonia::start_capture_errors(); } int _harmonia_capture_data_size; #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_errors() { std::list<HarmoniaErrorData*>* list = Harmonia::get_capture_errors(); if (list != NULL && list->size() > 0) { std::string jsonStr = "{\"errors\":["; std::for_each(list->begin(), list->end(), [&jsonStr](HarmoniaErrorData* data) { int type = static_cast<int>(data->get_error_type()); std::string typeStr; #if ANDROID || _ANDROID_ std::stringstream stream; stream << "" << type; typeStr = stream.str(); #else typeStr = std::to_string(type); #endif jsonStr += "{\"type\":" + typeStr + "},"; }); jsonStr = jsonStr.substr(0, jsonStr.size() - 1); jsonStr += "]}"; const char* str = jsonStr.c_str(); size_t length = strlen(str) + 1; char* returnChar = (char*)malloc(length); #if _WIN32 strcpy_s(returnChar, length, str); #else strcpy(returnChar, str); #endif _harmonia_capture_data_size = (int)length; return returnChar; } return NULL; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_errors_with_size(int* size) { char* result = harmonia_get_capture_errors(); if (result == NULL) { *size = 0; } else { *size = _harmonia_capture_data_size; } return result; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_stop_capture_errors() { Harmonia::stop_capture_errors(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_start_capture_events() { Harmonia::start_capture_events(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_events() { std::list<SoundEventData*>* list = Harmonia::get_captured_events(); if (list != NULL && list->size() > 0) { std::string jsonStr = "{\"events\":["; std::for_each(list->begin(), list->end(), [&jsonStr](SoundEventData* data) { jsonStr += "{\"rid\":\"" + std::string(data->get_rid()) + "\",\"sid\":\"" + std::string(data->get_sid()) + "\","; int type = static_cast<int>(data->get_type()); std::string typeStr; #if ANDROID || _ANDROID_ std::stringstream stream; stream << "" << type; typeStr = stream.str(); #else typeStr = std::to_string(type); #endif jsonStr += "\"type\":" + typeStr; jsonStr += "},"; delete data; }); jsonStr = jsonStr.substr(0, jsonStr.size() - 1); jsonStr += "]}"; delete list; const char* str = jsonStr.c_str(); size_t length = strlen(str) + 1; char* returnChar = (char*)malloc(length); #if _WIN32 strcpy_s(returnChar, length, str); #else strcpy(returnChar, str); #endif _harmonia_capture_data_size = (int)length; return returnChar; } return NULL; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_events_with_size(int* size) { char* result = harmonia_get_capture_events(); if (result == NULL) { *size = 0; } else { *size = _harmonia_capture_data_size; } return result; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_stop_capture_events() { Harmonia::stop_capture_events(); } // Sound #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_play(const char* registeredId, const char* soundId, const char* targetGroupId) { Harmonia::play(registeredId, soundId, targetGroupId); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_pause(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->pause(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_resume(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->resume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_stop(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->stop(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_mute(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->mute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_unmute(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->unmute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif float harmonia_get_sound_volume(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); return data->get_volume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_sound_volume(const char* playingDataId, float volume) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->set_volume(volume); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif unsigned int harmonia_get_sound_status(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); return data->get_status(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif unsigned int harmonia_get_sound_current_position(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); return (unsigned int)data->get_current_position(); } // Group #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_create_group(const char* groupId, const char* parentGroupId, int maxPolyphony) { Harmonia::create_group(groupId, parentGroupId, maxPolyphony); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_delete_group(const char* groupId) { Harmonia::delete_group(groupId); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_pause(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->pause(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_resume(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->resume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_stop(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->stop(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_mute(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->mute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_unmute(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->unmute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif float harmonia_get_group_volume(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); return group->get_volume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_group_volume(const char* groupId, float volume) { SoundGroup* group = Harmonia::get_group(groupId); group->set_volume(volume); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_ducker(const char* triggerGroupId, const char* targetGroupId, float ratio, float attackTimeByMS, float releaseTimeByMS) { SoundGroup* triggerGroup = Harmonia::get_group(triggerGroupId); SoundGroup* targetGroup = Harmonia::get_group(targetGroupId); targetGroup->set_ducker(triggerGroup, ratio, attackTimeByMS, releaseTimeByMS); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif unsigned int harmonia_get_group_status(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); return group->get_status(); } /* #if _WIN32 extern "C" _declspec(dllexport) void initialize() { Harmonia::initialize(); } extern "C" _declspec(dllexport) unsigned int registerSound(unsigned char* binaryPointer, unsigned long size) { return Harmonia::registerSound(binaryPointer, size); } extern "C" _declspec(dllexport) int play(unsigned int registeredId) { return Harmonia::play(registeredId); } extern "C" _declspec(dllexport) ogg_int64_t getCurrentTimeInPlayer(unsigned int playerId) { return Harmonia::getCurrentTimeInPlayer(playerId); } extern "C" _declspec(dllexport) void finalize() { Harmonia::finalize(); } #elif (__ANDROID__ || ANDROID) extern "C" { void initialize() { Harmonia::initialize(); } void initializeForAndroid(int sampleRate, int bufferSize) { Harmonia::initializeForAndroid(sampleRate, bufferSize); } unsigned int registerSound(unsigned char* binaryPointer, unsigned int size) { return Harmonia::registerSound(binaryPointer, size); } int play(unsigned int registeredId) { return Harmonia::play(registeredId); } ogg_int64_t getCurrentTimeInPlayer(unsigned int playerId) { return Harmonia::getCurrentTimeInPlayer(playerId); } void harmonia_pause() { Harmonia::pause(); } void harmonia_resume() { Harmonia::resume(); } void finalize() { Harmonia::finalize(); } } #elif __APPLE__ #include "TargetConditionals.h" #if TARGET_OS_IPHONE || TARGET_OS_MAC #include <string.h> #include <stdlib.h> extern "C" { void initialize() { Harmonia::initialize(); } unsigned int registerSound(unsigned char* binaryPointer, unsigned int size) { return Harmonia::registerSound(binaryPointer, size); } int play(unsigned int registeredId) { return Harmonia::play(registeredId); } ogg_int64_t getCurrentTimeInPlayer(unsigned int playerId) { return Harmonia::getCurrentTimeInPlayer(playerId); } void finalize() { Harmonia::finalize(); } const char* aaaaa() { const char *str = "{\"e\":[{\"t\":1,\"v\":2},{\"t\":3,\"v\":4}]}"; char* retStr = (char*)malloc(strlen(str) + 1); strcpy(retStr, str); return retStr; } } #endif #endif */
18.672012
187
0.708408
Hiiragi
75737379a402b92d7209b5a3668b3bd1f84577d8
53
hpp
C++
src/boost_numeric_odeint_util_unit_helper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_numeric_odeint_util_unit_helper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_numeric_odeint_util_unit_helper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/numeric/odeint/util/unit_helper.hpp>
26.5
52
0.811321
miathedev
7573bfef037cbe0664a1346c1ec5c5eecc9e9a9a
12,410
cpp
C++
Engine/Source/Runtime/ShaderCore/Private/VertexFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/ShaderCore/Private/VertexFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/ShaderCore/Private/VertexFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= VertexFactory.cpp: Vertex factory implementation =============================================================================*/ #include "VertexFactory.h" #include "Serialization/MemoryWriter.h" #include "UObject/DebugSerializationFlags.h" uint32 FVertexFactoryType::NextHashIndex = 0; bool FVertexFactoryType::bInitializedSerializationHistory = false; /** * @return The global shader factory list. */ TLinkedList<FVertexFactoryType*>*& FVertexFactoryType::GetTypeList() { static TLinkedList<FVertexFactoryType*>* TypeList = NULL; return TypeList; } /** * Finds a FVertexFactoryType by name. */ FVertexFactoryType* FVertexFactoryType::GetVFByName(const FString& VFName) { for(TLinkedList<FVertexFactoryType*>::TIterator It(GetTypeList()); It; It.Next()) { FString CurrentVFName = FString(It->GetName()); if (CurrentVFName == VFName) { return *It; } } return NULL; } void FVertexFactoryType::Initialize(const TMap<FString, TArray<const TCHAR*> >& ShaderFileToUniformBufferVariables) { if (!FPlatformProperties::RequiresCookedData()) { // Cache serialization history for each VF type // This history is used to detect when shader serialization changes without a corresponding .usf change for(TLinkedList<FVertexFactoryType*>::TIterator It(FVertexFactoryType::GetTypeList()); It; It.Next()) { FVertexFactoryType* Type = *It; GenerateReferencedUniformBuffers(Type->ShaderFilename, Type->Name, ShaderFileToUniformBufferVariables, Type->ReferencedUniformBufferStructsCache); for (int32 Frequency = 0; Frequency < SF_NumFrequencies; Frequency++) { // Construct a temporary shader parameter instance, which is initialized to safe values for serialization FVertexFactoryShaderParameters* Parameters = Type->CreateShaderParameters((EShaderFrequency)Frequency); if (Parameters) { // Serialize the temp shader to memory and record the number and sizes of serializations TArray<uint8> TempData; FMemoryWriter Ar(TempData, true); FShaderSaveArchive SaveArchive(Ar, Type->SerializationHistory[Frequency]); Parameters->Serialize(SaveArchive); delete Parameters; } } } } bInitializedSerializationHistory = true; } void FVertexFactoryType::Uninitialize() { for(TLinkedList<FVertexFactoryType*>::TIterator It(FVertexFactoryType::GetTypeList()); It; It.Next()) { FVertexFactoryType* Type = *It; for (int32 Frequency = 0; Frequency < SF_NumFrequencies; Frequency++) { Type->SerializationHistory[Frequency] = FSerializationHistory(); } } bInitializedSerializationHistory = false; } FVertexFactoryType::FVertexFactoryType( const TCHAR* InName, const TCHAR* InShaderFilename, bool bInUsedWithMaterials, bool bInSupportsStaticLighting, bool bInSupportsDynamicLighting, bool bInSupportsPrecisePrevWorldPos, bool bInSupportsPositionOnly, ConstructParametersType InConstructParameters, ShouldCacheType InShouldCache, ModifyCompilationEnvironmentType InModifyCompilationEnvironment, SupportsTessellationShadersType InSupportsTessellationShaders ): Name(InName), ShaderFilename(InShaderFilename), TypeName(InName), bUsedWithMaterials(bInUsedWithMaterials), bSupportsStaticLighting(bInSupportsStaticLighting), bSupportsDynamicLighting(bInSupportsDynamicLighting), bSupportsPrecisePrevWorldPos(bInSupportsPrecisePrevWorldPos), bSupportsPositionOnly(bInSupportsPositionOnly), ConstructParameters(InConstructParameters), ShouldCacheRef(InShouldCache), ModifyCompilationEnvironmentRef(InModifyCompilationEnvironment), SupportsTessellationShadersRef(InSupportsTessellationShaders), GlobalListLink(this) { // Make sure the format of the source file path is right. check(CheckVirtualShaderFilePath(InShaderFilename)); checkf(FPaths::GetExtension(InShaderFilename) == TEXT("ush"), TEXT("Incorrect virtual shader path extension for vertex factory shader header '%s': Only .ush files should be included."), InShaderFilename); for (int32 Platform = 0; Platform < SP_NumPlatforms; Platform++) { bCachedUniformBufferStructDeclarations[Platform] = false; } // This will trigger if an IMPLEMENT_VERTEX_FACTORY_TYPE was in a module not loaded before InitializeShaderTypes // Vertex factory types need to be implemented in modules that are loaded before that checkf(!bInitializedSerializationHistory, TEXT("VF type was loaded after engine init, use ELoadingPhase::PostConfigInit on your module to cause it to load earlier.")); // Add this vertex factory type to the global list. GlobalListLink.LinkHead(GetTypeList()); // Assign the vertex factory type the next unassigned hash index. HashIndex = NextHashIndex++; } FVertexFactoryType::~FVertexFactoryType() { GlobalListLink.Unlink(); } /** Calculates a Hash based on this vertex factory type's source code and includes */ const FSHAHash& FVertexFactoryType::GetSourceHash() const { return GetShaderFileHash(GetShaderFilename()); } FArchive& operator<<(FArchive& Ar,FVertexFactoryType*& TypeRef) { if(Ar.IsSaving()) { FName TypeName = TypeRef ? FName(TypeRef->GetName()) : NAME_None; Ar << TypeName; } else if(Ar.IsLoading()) { FName TypeName = NAME_None; Ar << TypeName; TypeRef = FindVertexFactoryType(TypeName); } return Ar; } FVertexFactoryType* FindVertexFactoryType(FName TypeName) { // Search the global vertex factory list for a type with a matching name. for(TLinkedList<FVertexFactoryType*>::TIterator VertexFactoryTypeIt(FVertexFactoryType::GetTypeList());VertexFactoryTypeIt;VertexFactoryTypeIt.Next()) { if(VertexFactoryTypeIt->GetFName() == TypeName) { return *VertexFactoryTypeIt; } } return NULL; } void FVertexFactory::Set(FRHICommandList& RHICmdList) const { check(IsInitialized()); for(int32 StreamIndex = 0;StreamIndex < Streams.Num();StreamIndex++) { const FVertexStream& Stream = Streams[StreamIndex]; if (!Stream.bSetByVertexFactoryInSetMesh) { if (!Stream.VertexBuffer) { RHICmdList.SetStreamSource(StreamIndex, nullptr, 0); } else { checkf(Stream.VertexBuffer->IsInitialized(), TEXT("Vertex buffer was not initialized! Stream %u, Stride %u, Name %s"), StreamIndex, Stream.Stride, *Stream.VertexBuffer->GetFriendlyName()); RHICmdList.SetStreamSource(StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset); } } } } void FVertexFactory::OffsetInstanceStreams(FRHICommandList& RHICmdList, uint32 FirstVertex) const { for(int32 StreamIndex = 0;StreamIndex < Streams.Num();StreamIndex++) { const FVertexStream& Stream = Streams[StreamIndex]; if (Stream.bUseInstanceIndex) { RHICmdList.SetStreamSource( StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset + Stream.Stride * FirstVertex); } } } void FVertexFactory::SetPositionStream(FRHICommandList& RHICmdList) const { check(IsInitialized()); // Set the predefined vertex streams. for(int32 StreamIndex = 0;StreamIndex < PositionStream.Num();StreamIndex++) { const FVertexStream& Stream = PositionStream[StreamIndex]; check(Stream.VertexBuffer->IsInitialized()); RHICmdList.SetStreamSource( StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset); } } void FVertexFactory::OffsetPositionInstanceStreams(FRHICommandList& RHICmdList, uint32 FirstVertex) const { for(int32 StreamIndex = 0;StreamIndex < PositionStream.Num();StreamIndex++) { const FVertexStream& Stream = PositionStream[StreamIndex]; if (Stream.bUseInstanceIndex) { RHICmdList.SetStreamSource( StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset + Stream.Stride * FirstVertex); } } } void FVertexFactory::ReleaseRHI() { Declaration.SafeRelease(); PositionDeclaration.SafeRelease(); Streams.Empty(); PositionStream.Empty(); } /** * Fill in array of strides from this factory's vertex streams without shadow/light maps * @param OutStreamStrides - output array of # MaxVertexElementCount stream strides to fill */ int32 FVertexFactory::GetStreamStrides(uint32 *OutStreamStrides, bool bPadWithZeroes) const { int32 StreamIndex; for(StreamIndex = 0;StreamIndex < Streams.Num();++StreamIndex) { OutStreamStrides[StreamIndex] = Streams[StreamIndex].Stride; } if (bPadWithZeroes) { // Pad stream strides with 0's to be safe (they can be used in hashes elsewhere) for (;StreamIndex < MaxVertexElementCount;++StreamIndex) { OutStreamStrides[StreamIndex] = 0; } } return StreamIndex; } /** * Fill in array of strides from this factory's position only vertex streams * @param OutStreamStrides - output array of # MaxVertexElementCount stream strides to fill */ void FVertexFactory::GetPositionStreamStride(uint32 *OutStreamStrides) const { int32 StreamIndex; for(StreamIndex = 0;StreamIndex < PositionStream.Num();++StreamIndex) { OutStreamStrides[StreamIndex] = PositionStream[StreamIndex].Stride; } // Pad stream strides with 0's to be safe (they can be used in hashes elsewhere) for (;StreamIndex < MaxVertexElementCount;++StreamIndex) { OutStreamStrides[StreamIndex] = 0; } } FVertexElement FVertexFactory::AccessStreamComponent(const FVertexStreamComponent& Component,uint8 AttributeIndex) { FVertexStream VertexStream; VertexStream.VertexBuffer = Component.VertexBuffer; VertexStream.Stride = Component.Stride; VertexStream.Offset = 0; VertexStream.bUseInstanceIndex = Component.bUseInstanceIndex; VertexStream.bSetByVertexFactoryInSetMesh = Component.bSetByVertexFactoryInSetMesh; return FVertexElement(Streams.AddUnique(VertexStream),Component.Offset,Component.Type,AttributeIndex,VertexStream.Stride,Component.bUseInstanceIndex); } FVertexElement FVertexFactory::AccessPositionStreamComponent(const FVertexStreamComponent& Component,uint8 AttributeIndex) { FVertexStream VertexStream; VertexStream.VertexBuffer = Component.VertexBuffer; VertexStream.Stride = Component.Stride; VertexStream.Offset = 0; VertexStream.bUseInstanceIndex = Component.bUseInstanceIndex; VertexStream.bSetByVertexFactoryInSetMesh = Component.bSetByVertexFactoryInSetMesh; return FVertexElement(PositionStream.AddUnique(VertexStream),Component.Offset,Component.Type,AttributeIndex,VertexStream.Stride,Component.bUseInstanceIndex); } void FVertexFactory::InitDeclaration(FVertexDeclarationElementList& Elements) { // Create the vertex declaration for rendering the factory normally. Declaration = RHICreateVertexDeclaration(Elements); } void FVertexFactory::InitPositionDeclaration(const FVertexDeclarationElementList& Elements) { PositionDeclaration = RHICreateVertexDeclaration(Elements); } FVertexFactoryParameterRef::FVertexFactoryParameterRef(FVertexFactoryType* InVertexFactoryType,const FShaderParameterMap& ParameterMap, EShaderFrequency InShaderFrequency) : Parameters(NULL) , VertexFactoryType(InVertexFactoryType) , ShaderFrequency(InShaderFrequency) { Parameters = VertexFactoryType->CreateShaderParameters(InShaderFrequency); VFHash = GetShaderFileHash(VertexFactoryType->GetShaderFilename()); if(Parameters) { Parameters->Bind(ParameterMap); } } bool operator<<(FArchive& Ar,FVertexFactoryParameterRef& Ref) { bool bShaderHasOutdatedParameters = false; Ar << Ref.VertexFactoryType; uint8 ShaderFrequencyByte = Ref.ShaderFrequency; Ar << ShaderFrequencyByte; if(Ar.IsLoading()) { Ref.ShaderFrequency = (EShaderFrequency)ShaderFrequencyByte; } Ar << Ref.VFHash; if (Ar.IsLoading()) { delete Ref.Parameters; if (Ref.VertexFactoryType) { Ref.Parameters = Ref.VertexFactoryType->CreateShaderParameters(Ref.ShaderFrequency); } else { bShaderHasOutdatedParameters = true; Ref.Parameters = NULL; } } // Need to be able to skip over parameters for no longer existing vertex factories. int32 SkipOffset = Ar.Tell(); { FArchive::FScopeSetDebugSerializationFlags S(Ar, DSF_IgnoreDiff); // Write placeholder. Ar << SkipOffset; } if(Ref.Parameters) { Ref.Parameters->Serialize(Ar); } else if(Ar.IsLoading()) { Ar.Seek( SkipOffset ); } if( Ar.IsSaving() ) { int32 EndOffset = Ar.Tell(); Ar.Seek( SkipOffset ); Ar << EndOffset; Ar.Seek( EndOffset ); } return bShaderHasOutdatedParameters; } /** Returns the hash of the vertex factory shader file that this shader was compiled with. */ const FSHAHash& FVertexFactoryParameterRef::GetHash() const { return VFHash; }
31.497462
192
0.770749
windystrife
75791efa4e695d9d48d0a8e9d3206221e16d6efc
1,157
cpp
C++
src/scheduler/FunctionCallClient.cpp
dgoltzsche/faabric
b1edd26d2b07102255491d7fbb661586d58970f5
[ "Apache-2.0" ]
null
null
null
src/scheduler/FunctionCallClient.cpp
dgoltzsche/faabric
b1edd26d2b07102255491d7fbb661586d58970f5
[ "Apache-2.0" ]
null
null
null
src/scheduler/FunctionCallClient.cpp
dgoltzsche/faabric
b1edd26d2b07102255491d7fbb661586d58970f5
[ "Apache-2.0" ]
null
null
null
#include <faabric/scheduler/FunctionCallClient.h> #include <grpcpp/create_channel.h> #include <grpcpp/security/credentials.h> #include <faabric/proto/macros.h> namespace faabric::scheduler { FunctionCallClient::FunctionCallClient(const std::string& hostIn) : host(hostIn) , channel(grpc::CreateChannel(host + ":" + std::to_string(FUNCTION_CALL_PORT), grpc::InsecureChannelCredentials())) , stub(faabric::FunctionRPCService::NewStub(channel)) {} void FunctionCallClient::shareFunctionCall(const faabric::Message& call) { ClientContext context; faabric::FunctionStatusResponse response; CHECK_RPC("function_share", stub->ShareFunction(&context, call, &response)); } void FunctionCallClient::sendFlush() { ClientContext context; faabric::Message call; faabric::FunctionStatusResponse response; CHECK_RPC("function_flush", stub->Flush(&context, call, &response)); } void FunctionCallClient::sendMPIMessage(const faabric::MPIMessage& msg) { ClientContext context; faabric::FunctionStatusResponse response; CHECK_RPC("mpi_message", stub->MPICall(&context, msg, &response)); } }
29.666667
80
0.737252
dgoltzsche
757ae3a25a167a19621dc9d620353e420d53ee7e
828
hpp
C++
tests/CellMLContextTest.hpp
metatoaster/cellml-api
d7baf9038e42859fa96117db6c9644f9f09ecf8b
[ "W3C" ]
1
2018-12-27T01:06:37.000Z
2018-12-27T01:06:37.000Z
tests/CellMLContextTest.hpp
metatoaster/cellml-api
d7baf9038e42859fa96117db6c9644f9f09ecf8b
[ "W3C" ]
1
2016-12-05T09:20:14.000Z
2016-12-05T18:08:05.000Z
tests/CellMLContextTest.hpp
metatoaster/cellml-api
d7baf9038e42859fa96117db6c9644f9f09ecf8b
[ "W3C" ]
14
2015-07-27T13:45:54.000Z
2022-02-02T05:19:53.000Z
#ifndef CELLMLCONTEXTTEST_H #define CELLMLCONTEXTTEST_H #include <cppunit/extensions/HelperMacros.h> #include "cda_config.h" #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include "IfaceCellML_Context.hxx" class CellMLContextTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(CellMLContextTest); CPPUNIT_TEST(testCellMLContext); CPPUNIT_TEST(testModelList); CPPUNIT_TEST(testModelNode); CPPUNIT_TEST_SUITE_END(); iface::cellml_context::CellMLContext* mContext; iface::cellml_api::DOMModelLoader* mModelLoader; iface::cellml_api::Model* mAchCascade; iface::cellml_api::Model* mBeelerReuter; public: void setUp(); void tearDown(); void loadAchCascade(); void loadBeelerReuter(); void testCellMLContext(); void testModelList(); void testModelNode(); }; #endif // CELLMLCONTEXTTEST_H
23.657143
53
0.780193
metatoaster
757af3258b0bd1de500a8bd36dfbb26c6060a56b
1,322
cpp
C++
src/pkg_exe/pkg_exe_service.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
src/pkg_exe/pkg_exe_service.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
src/pkg_exe/pkg_exe_service.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
#include <pkg/exe/pkg_exe_service.hpp> #include <pkg/exe/iscc.hpp> #include <pkg/exe/help.hpp> #include <pkg/exe/temp.hpp> #include <pkg/utils.hpp> #include <boost/algorithm/string/replace.hpp> #include <map> #include <iostream> using namespace std; using namespace pkg::exe; pkg_exe_service::pkg_exe_service(const PkgExeArgs &args) { if (args.needs_help()) { cout << help() << endl; return; } bf::path file_path(args.file()); string win_path = boost::replace_all_copy("Z:" + args.path(), "/", "\\"); map<string, string> overrides = { {"appName", args.name()}, {"appVersion", args.version()}, {"outputDir", win_path} }; bf::current_path(file_path.parent_path()); _overriden_file = override_file(file_path, Temp::uuid_str(), overrides); _win_overriden_file = boost::replace_all_copy("Z:" + _overriden_file.string(), "/", "\\"); _out = args.out(); bf::create_directories(Temp::path()); created = true; } pkg_exe_service::~pkg_exe_service() { bf::remove_all(Temp::path()); bf::remove(_overriden_file); } void pkg_exe_service::execute() { if (!created) return; cout << "Started exe packaging ..." << endl; iscc(_win_overriden_file, _out).execute(); cout << "done. out -> " << _out << endl; }
24.036364
94
0.630106
naughtybikergames
757ba4b1ba66acf6abd3e09aae9f73d82e55103d
637
cpp
C++
Sniper.cpp
snir1551/Ex8_C-
f226d73c18ef8011b90ee46048494a82c05f198a
[ "MIT" ]
1
2021-05-31T13:11:02.000Z
2021-05-31T13:11:02.000Z
Sniper.cpp
snir1551/Ex8_C-
f226d73c18ef8011b90ee46048494a82c05f198a
[ "MIT" ]
null
null
null
Sniper.cpp
snir1551/Ex8_C-
f226d73c18ef8011b90ee46048494a82c05f198a
[ "MIT" ]
null
null
null
#include "Sniper.hpp" #include "Board.hpp" namespace WarGame { Sniper::Sniper(int numPlayer): Soldier(numPlayer,100,50) { } Sniper::Sniper(int numPlayer, int health, int damage): Soldier(numPlayer,health,damage) { } int Sniper::maxHealth() const { return 100; } const char* Sniper::letter() const { return "SN"; } void Sniper::attack(Board& board) const { Soldier* target = board.mostCurrentHealth(this); if (target) { target->setHealth(target->getHealth() - this->getDamage()); board.removeDeadSoldiers(); } } }
19.30303
91
0.583987
snir1551
757bdb569ae20630278ce6e737d4c38ec50d5560
9,906
cc
C++
examples/fontscan.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
7
2021-07-28T19:03:08.000Z
2022-02-02T23:17:11.000Z
examples/fontscan.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
2
2021-06-15T22:34:44.000Z
2021-11-10T04:27:21.000Z
examples/fontscan.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdint> #include <cstdlib> #include <cstring> #include <climits> #include <cstdlib> #include <climits> #include <cctype> #include <map> #include <vector> #include <memory> #include <string> #include <algorithm> #include <atomic> #include <mutex> #include <ft2build.h> #include FT_FREETYPE_H #include FT_MODULE_H #include FT_GLYPH_H #include FT_OUTLINE_H #include "binpack.h" #include "image.h" #include "draw.h" #include "font.h" #include "glyph.h" #include "file.h" static font_manager_ft manager; static const char* font_dir = "fonts"; static bool print_font_list = false; static bool print_block_stats = false; static bool help_text = false; static float cover_min = 0.05; static int family_width = 80; void print_help(int argc, char **argv) { fprintf(stderr, "Usage: %s [options]\n" "\n" "Options:\n" " -d, --font-dir <name> font dir\n" " -l, --list list fonts\n" " -l, --stats show font stats (block)\n" " -h, --help command line help\n", argv[0]); } bool check_param(bool cond, const char *param) { if (cond) { printf("error: %s requires parameter\n", param); } return (help_text = cond); } bool match_opt(const char *arg, const char *opt, const char *longopt) { return strcmp(arg, opt) == 0 || strcmp(arg, longopt) == 0; } void parse_options(int argc, char **argv) { int i = 1; while (i < argc) { if (match_opt(argv[i], "-d", "--font-dir")) { if (check_param(++i == argc, "--font-dir")) break; font_dir = argv[i++]; } else if (match_opt(argv[i], "-c", "--cover-min")) { if (check_param(++i == argc, "--cover-min")) break; cover_min = atof(argv[i++]); } else if (match_opt(argv[i], "-w", "--family-width")) { if (check_param(++i == argc, "--family-width")) break; family_width = atoi(argv[i++]); } else if (match_opt(argv[i], "-b", "--block-stats")) { print_block_stats = true; i++; } else if (match_opt(argv[i], "-l", "--list")) { print_font_list = true; i++; } else if (match_opt(argv[i], "-h", "--help")) { help_text = true; i++; } else { fprintf(stderr, "error: unknown option: %s\n", argv[i]); help_text = true; break; } } if (help_text) { print_help(argc, argv); exit(1); } } static bool endsWith(std::string str, std::string ext) { size_t i = str.find(ext); return (i == str.size() - ext.size()); } void scanFontDir(std::string dir) { std::vector<std::string> dirs; std::vector<std::string> fontfiles; size_t i = 0; dirs.push_back(dir); while(i < dirs.size()) { std::string current_dir = dirs[i++]; for (auto &name : file::list(current_dir)) { if (file::dirExists(name)) { dirs.push_back(name); } else if (endsWith(name, ".ttf")) { fontfiles.push_back(name); } } } for (auto &name : fontfiles) { manager.scanFontPath(name); } } static std::vector<uint> allCodepoints(FT_Face ftface) { std::vector<uint> l; unsigned glyph, codepoint = FT_Get_First_Char(ftface, &glyph); do { l.push_back(codepoint); codepoint = FT_Get_Next_Char(ftface, codepoint, &glyph); } while (glyph); return l; } void do_print_font_list() { for (auto &font : manager.getFontList()) { printf("font[%d] -> %s\n", font->font_id, font->getFontData().toString().c_str()); } } static std::string ltrim(std::string s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); return s; } static std::string rtrim(std::string s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end()); return s; } struct block { uint start; uint end; std::string name; }; std::vector<block> read_blocks() { // # @missing: 0000..10FFFF; No_Block // 0000..007F; Basic Latin std::vector<block> blocks; FILE *f; char buf[128]; const char* p; if ((f = fopen("data/unicode/Blocks.txt", "r")) == nullptr) { fprintf(stderr, "fopen: %s\n", strerror(errno)); exit(1); } while((p = fgets(buf, sizeof(buf), f)) != nullptr) { auto l = ltrim(rtrim(std::string(p))); if (l.size() == 0) continue; if (l.find("#") != std::string::npos) continue; size_t d = l.find(".."); size_t s = l.find(";"); blocks.push_back({ (uint)strtoul(l.substr(0,d).c_str(),nullptr, 16), (uint)strtoul(l.substr(d+2,s-d-2).c_str(),nullptr, 16), l.substr(s+2) }); } fclose(f); return blocks; } uint find_block(std::vector<block> &blocks, uint32_t cp) { uint i = 0; for (auto &b: blocks) { if (cp >= b.start && cp <= b.end) return i; i++; } return blocks.size()-1; } template <typename K, typename V> void hist_add(std::map<K,V> &hist, K key, V val) { auto hci = hist.find(key); if (hci == hist.end()) { hist.insert(hist.end(),std::pair<K,V>(key,val)); } else { hci->second += val; } } template <typename K> struct id_map { uint id; std::map<K,uint> map; std::map<uint,K> rmap; id_map() : id(0), map() {} uint get_id(K key) { auto i = map.find(key); if (i == map.end()) { i = map.insert(map.end(), std::pair<K,uint>(key, id++)); rmap[i->second] = key; } return i->second; } K get_key(uint i) { return rmap[i]; } }; template <typename T, typename K, typename V> auto find_or_insert(T &map, K key, V def) { auto i = map.find(key); if (i == map.end()) { i = map.insert(map.end(), std::pair<K,V>(key, def)); } return i; } std::string truncate(std::string str, size_t sz) { if (str.length() < sz) return str; else return str.substr(0, sz) + "..."; } struct block_family_data { std::map<font_face*,uint> codes; }; struct block_data { std::map<uint,block_family_data> families; }; struct family_data { std::string family_name; std::string font_names; uint family_count; uint glyph_count; }; template <typename K, typename V, typename F> std::string to_string(std::map<K,V> &list, F fn, std::string sep = ", ") { std::string str; auto i = list.begin(); if (i == list.end()) goto out; str.append(fn(i)); if (++i == list.end()) goto out; for (; i != list.end(); i++) { str.append(sep); str.append(fn(i)); } out: return str; } std::string remove_prefix(std::string &str, std::string sep) { auto i = str.find(sep); return (i != std::string::npos) ? str.substr(i+1) : str; } void do_print_block_stats() { id_map<std::string> font_name_map; id_map<std::string> font_family_map; std::vector<block> blocks; std::map<uint,block_data> block_stats; blocks = read_blocks(); blocks.push_back({0,0xfffff,"Unknown"}); for (auto &font : manager.getFontList()) { FT_Face ftface = static_cast<font_face_ft*>(font.get())->ftface; uint font_name_id = font_name_map.get_id(font->path); uint font_family_id = font_family_map.get_id(font->fontData.familyName); FT_Select_Charmap(ftface, FT_ENCODING_UNICODE); auto cplist = allCodepoints(ftface); for (auto cp : cplist) { uint bc = find_block(blocks,cp); auto bsi = find_or_insert(block_stats, bc, block_data()); auto fsi = find_or_insert(bsi->second.families, font_family_id, block_family_data()); auto gsi = find_or_insert(fsi->second.codes, font.get(), 0); gsi->second++; } } for (size_t i = 0; i < blocks.size(); i++) { auto &b = blocks[i]; auto bsi = block_stats.find(i); if (bsi->second.families.size() == 0) continue; printf("%06x..%06x; %-80s\n", b.start, b.end, b.name.c_str()); std::vector<family_data> fam_data; for (auto &ent : bsi->second.families) { uint font_family_id = ent.first; block_family_data &block_family_data = ent.second; std::string family_name = font_family_map.get_key(font_family_id); std::string font_names = to_string(block_family_data.codes, [](auto i) { return remove_prefix(i->first->name, "-"); }); uint glyph_count = 0; for (auto ent : block_family_data.codes) glyph_count += ent.second; uint family_count = (uint)block_family_data.codes.size(); fam_data.push_back(family_data{family_name, font_names, family_count, glyph_count}); } std::sort(fam_data.begin(), fam_data.end(), [](auto a, auto b) { return a.glyph_count/a.family_count > b.glyph_count/b.family_count; }); for (auto &ent: fam_data) { uint glyph_avg = ent.glyph_count/ent.family_count; uint block_glyphs = (b.end - b.start); float cover = (float)glyph_avg/(float)block_glyphs; if (cover < cover_min) continue; printf("\t%5.2f %10u,%-10u %-20s %s\n", cover, ent.family_count, ent.glyph_count/ent.family_count, ent.family_name.c_str(), truncate(ent.font_names, family_width).c_str()); } } } int main(int argc, char **argv) { parse_options(argc, argv); scanFontDir(font_dir); if (print_font_list) do_print_font_list(); if (print_block_stats) do_print_block_stats(); }
27.289256
97
0.564304
michaeljclark
757d05b94d787a75b21658024e4689120f2500d8
713
hpp
C++
source/rectangle.hpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
source/rectangle.hpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
source/rectangle.hpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
#ifndef RECTANGLE_HPP #define RECTANGLE_HPP #include "vec2.hpp" #include "color.hpp" #include "window.hpp" class Rectangle { public: Rectangle(); Rectangle(Vec2 const& vec1, Vec2 const& vec2); Rectangle(Vec2 const& vec1, Vec2 const& vec2, Color const& col); // getter Vec2 getMax() const; Vec2 getMin() const; Color getColor() const; // setter void setMax(Vec2 const& vecmax); void setMin(Vec2 const& vecmin); void setColor(Color const& col); // methods float circumference() const; void draw(Window const& window); void draw(Window const& window, Color const& color); bool is_inside(Vec2 const& vec); private: Vec2 max_; Vec2 min_; Color colour_; }; #endif
19.805556
68
0.687237
SVincent
757de7f894579fe556a75aca8069431c8e9df4f6
855
hpp
C++
50_su2mesh/inc/SU2meshparser.hpp
nishiys/CFDbasics
638372956e31f8392f20b0d2027762cc4f9ef10b
[ "MIT" ]
1
2020-06-19T10:17:17.000Z
2020-06-19T10:17:17.000Z
50_su2mesh/inc/SU2meshparser.hpp
nishiys/CFDbasics
638372956e31f8392f20b0d2027762cc4f9ef10b
[ "MIT" ]
null
null
null
50_su2mesh/inc/SU2meshparser.hpp
nishiys/CFDbasics
638372956e31f8392f20b0d2027762cc4f9ef10b
[ "MIT" ]
1
2020-06-19T10:22:36.000Z
2020-06-19T10:22:36.000Z
#pragma once #include <string> #include <vector> #include "CellQuad4.hpp" #include "Face2d.hpp" #include "Node2d.hpp" namespace su2mesh { class SU2meshparser { public: SU2meshparser(std::string meshfilename); ~SU2meshparser(); void LoadData(); void WriteVtkFile(std::string vtkfilename); private: std::string meshfilename_; void ReadFile(); void CreateQuadArray(); std::vector<CellQuad4> cellarray_; // std::vector<Face2d> facearray_; std::vector<Node2d> nodearray_; unsigned int DIM_; unsigned int NElement_; unsigned int NPoint_; unsigned int NMarker_; const unsigned int LINE = 3; const unsigned int QUAD4 = 9; std::vector<std::vector<unsigned int>> element_table_; std::vector<std::vector<std::string>> marker_table_; void PrintDebug(); }; } // namespace su2mesh
19.431818
58
0.687719
nishiys
757fdcd03e7aa69d58068e1e383dcbaf0140708b
4,549
cpp
C++
init/init_xt897.cpp
chakaponden/android_device_motorola_xt897-lineage
d85dca38801ea4a4309411d1f17434124403169e
[ "FTL" ]
null
null
null
init/init_xt897.cpp
chakaponden/android_device_motorola_xt897-lineage
d85dca38801ea4a4309411d1f17434124403169e
[ "FTL" ]
null
null
null
init/init_xt897.cpp
chakaponden/android_device_motorola_xt897-lineage
d85dca38801ea4a4309411d1f17434124403169e
[ "FTL" ]
null
null
null
/* Copyright (c) 2013, The Linux Foundation. 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT 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 <stdlib.h> #include <stdio.h> #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_ #include <sys/_system_properties.h> #include <android-base/properties.h> #include <android-base/logging.h> #include "vendor_init.h" #include "property_service.h" #include "log.h" #include "util.h" void property_override(char const prop[], char const value[]) { prop_info *pi; pi = (prop_info*) __system_property_find(prop); if (pi) __system_property_update(pi, value, strlen(value)); else __system_property_add(prop, strlen(prop), value, strlen(value)); } void vendor_load_properties() { std::string carrier, device, modelno, platform; char hardware_variant[92]; FILE *fp; platform = android::base::GetProperty("ro.board.platform", ""); if (platform != ANDROID_TARGET) return; modelno = android::base::GetProperty("ro.boot.modelno", ""); carrier = android::base::GetProperty("ro.boot.carrier", ""); fp = popen("/system/xbin/sed -n '/Hardware/,/Revision/p' /proc/cpuinfo | /system/xbin/cut -d ':' -f2 | /system/xbin/head -1", "r"); fgets(hardware_variant, sizeof(hardware_variant), fp); pclose(fp); property_override("ro.product.device", "asanti_c"); property_override("ro.product.model", "PHOTON Q"); if (modelno == "XT897") { /* xt897 CSpire */ property_override("ro.build.description", "asanti_c_cspire-user 4.1.2 9.8.2Q-122_XT897_FFW-7 8 release-keys"); property_override("ro.build.fingerprint", "motorola/XT897_us_csp/asanti_c:4.1.2/9.8.2Q-122_XT897_FFW-7/8:user/release-keys"); android::init::property_set("ro.cdma.home.operator.alpha", "Cspire"); android::init::property_set("ro.cdma.home.operator.numeric", "311230"); } else if (carrier == "sprint") { /* xt897 Sprint */ property_override("ro.build.description", "XT897_us_spr-user 4.1.2 9.8.2Q-122_XT897_FFW-5 6 release-keys"); property_override("ro.build.fingerprint", "motorola/XT897_us_spr/asanti_c:4.1.2/9.8.2Q-122_XT897_FFW-5/6:user/release-keys"); android::init::property_set("ro.cdma.international.eri", "2,74,124,125,126,157,158,159,193,194,195,196,197,198,228,229,230,231,232,233,234,235"); android::init::property_set("ro.cdma.home.operator.alpha", "Sprint"); android::init::property_set("ro.cdma.home.operator.numeric", "310120"); android::init::property_set("ro.com.google.clientidbase.ms", "android-sprint-us"); android::init::property_set("ro.com.google.clientidbase.am", "android-sprint-us"); android::init::property_set("ro.com.google.clientidbase.yt", "android-sprint-us"); } device = android::base::GetProperty("ro.product.device", ""); LOG(INFO) << "Found carrier id: " << carrier.c_str() << " " << "hardware: " << hardware_variant << " " << "model no: " << modelno.c_str() << " " << "Setting build properties for " << device.c_str() << " device"; }
47.884211
153
0.697516
chakaponden
7582140c15c0c274c42fdd5cf142baf443e87a21
11,685
cpp
C++
openreil/libasmir/src/stmt.cpp
aeveris/openreil-sys
47a89248dfdfba88c4040cff77fc3efcde6f80e9
[ "MIT" ]
3
2017-06-27T22:33:16.000Z
2017-06-28T23:11:44.000Z
openreil/libasmir/src/stmt.cpp
aeveris/openreil-sys
47a89248dfdfba88c4040cff77fc3efcde6f80e9
[ "MIT" ]
null
null
null
openreil/libasmir/src/stmt.cpp
aeveris/openreil-sys
47a89248dfdfba88c4040cff77fc3efcde6f80e9
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <fstream> #include <stdlib.h> #include <string.h> #include <assert.h> using namespace std; #include "stmt.h" Stmt *Stmt::clone(Stmt *s) { return s->clone(); } void Stmt::destroy(Stmt *s) { Move *move = NULL; Jmp *jmp = NULL; CJmp *cjmp = NULL; ExpStmt *expstmt = NULL; Call *call = NULL; Return *ret = NULL; Func *fun = NULL; switch (s->stmt_type) { case MOVE: move = (Move *)s; Exp::destroy(move->lhs); Exp::destroy(move->rhs); break; case JMP: jmp = (Jmp *)s; Exp::destroy(jmp->target); break; case CJMP: cjmp = (CJmp *)s; Exp::destroy(cjmp->cond); Exp::destroy(cjmp->t_target); Exp::destroy(cjmp->f_target); break; case EXPSTMT: expstmt = (ExpStmt *)s; Exp::destroy(expstmt->exp); break; case CALL: call = (Call *)s; if (call->lval_opt != NULL) { Exp::destroy(call->lval_opt); } for (vector<Exp *>::iterator i = call->params.begin(); i != call->params.end(); i++) { Exp::destroy(*i); } break; case RETURN: ret = (Return *)s; if (ret->exp_opt != NULL) { Exp::destroy(ret->exp_opt); } break; case FUNCTION: fun = (Func *)s; for (vector<VarDecl *>::iterator i = fun->params.begin(); i != fun->params.end(); i++) { Stmt::destroy(*i); } for (vector<Stmt *>::iterator i = fun->body.begin(); i != fun->body.end(); i++) { Stmt::destroy(*i); } break; case COMMENT: case SPECIAL: case LABEL: case VARDECL: case ASSERT: break; } delete s; } VarDecl::VarDecl(string n, reg_t t, address_t asm_ad, address_t ir_ad) : Stmt(VARDECL, asm_ad, ir_ad), name(n), typ(t) { } VarDecl::VarDecl(const VarDecl &other) : Stmt(VARDECL, other.asm_address, other.ir_address), name(other.name), typ(other.typ) { } VarDecl::VarDecl(Temp *t) : Stmt(VARDECL, 0x0, 0x0), name(t->name), typ(t->typ) { } string VarDecl::tostring() { string ret = "var " + name + ":" + Exp::string_type(this->typ) + ";"; return ret; } VarDecl *VarDecl::clone() const { return new VarDecl(*this); } string Move::tostring() { return lhs->tostring() + " = " + rhs->tostring() + ";"; } Move::Move(const Move &other) : Stmt(MOVE, other.asm_address, other.ir_address) { this->lhs = other.lhs->clone(); this->rhs = other.rhs->clone(); } Move::Move(Exp *l, Exp *r, address_t asm_addr, address_t ir_addr) : Stmt(MOVE, asm_addr, ir_addr), lhs(l), rhs(r) { } Move *Move::clone() const { return new Move(*this); } Label::Label(const Label &other) : Stmt(LABEL, other.asm_address, other.ir_address) { this->label = string(other.label); } Label::Label(string l, address_t asm_addr, address_t ir_addr) : Stmt(LABEL, asm_addr, ir_addr) { label = l; } Label *Label::clone() const { return new Label(*this); } string Label::tostring() { return "label " + label + ":"; } Jmp::Jmp(Exp *e, address_t asm_addr, address_t ir_addr) : Stmt(JMP, asm_addr, ir_addr), target(e) { } Jmp::Jmp(const Jmp &other) : Stmt(JMP, other.asm_address, other.ir_address) { target = other.target->clone(); } Jmp *Jmp::clone() const { return new Jmp(*this); } string Jmp::tostring() { string ret = "jmp(" + target->tostring() + ");"; return ret; } CJmp::CJmp(Exp *c, Exp *t, Exp *f, address_t asm_addr, address_t ir_addr) : Stmt(CJMP, asm_addr, ir_addr), cond(c), t_target(t), f_target(f) { } CJmp::CJmp(const CJmp &other) : Stmt(CJMP, other.asm_address, other.ir_address) { cond = other.cond->clone(); f_target = other.f_target->clone(); t_target = other.t_target->clone(); } CJmp *CJmp::clone() const { return new CJmp(*this); } string CJmp::tostring() { string ret = "cjmp(" + cond->tostring() + "," + t_target->tostring() + "," + f_target->tostring() + ");"; return ret; } Special::Special(string s, address_t asm_addr, address_t ir_addr) : Stmt(SPECIAL, asm_addr, ir_addr), special(s) { } Special::Special(const Special &other) : Stmt(SPECIAL, other.asm_address, other.ir_address) { special = other.special; } Special *Special::clone() const { return new Special(*this); } string Special::tostring() { string ret = "special(\"" + special + "\");"; return ret; } Comment::Comment(string s, address_t asm_addr, address_t ir_addr) : Stmt(COMMENT, asm_addr, ir_addr) { comment = s; } Comment::Comment(const Comment &other) : Stmt(COMMENT, other.asm_address, other.ir_address) { comment = other.comment; } Comment *Comment::clone() const { return new Comment(*this); } string Comment::tostring() { string s = "// " + string(comment); return s; } ExpStmt::ExpStmt(Exp *e, address_t asm_addr, address_t ir_addr) : Stmt(EXPSTMT, asm_addr, ir_addr) { exp = e; } ExpStmt::ExpStmt(const ExpStmt &other) : Stmt(EXPSTMT, other.asm_address, other.ir_address) { exp = other.exp->clone(); } ExpStmt *ExpStmt::clone() const { return new ExpStmt(*this); } string ExpStmt::tostring() { string s = exp->tostring() + ";"; return s; } Call::Call(Exp *lval_opt, string fnname, vector<Exp *> params, address_t asm_ad, address_t ir_ad) : Stmt(CALL, asm_ad, ir_ad) { this->lval_opt = lval_opt; this->callee = new Name(fnname); this->params = params; } Call::Call(Exp *lval_opt, Exp *callee, vector<Exp *> params, address_t asm_ad, address_t ir_ad) : Stmt(CALL, asm_ad, ir_ad) { this->lval_opt = lval_opt; this->callee = callee; this->params = params; } Call::Call(const Call &other) : Stmt(CALL, other.asm_address, other.ir_address) { this->lval_opt = (other.lval_opt == NULL) ? NULL : other.lval_opt->clone(); assert(other.callee); this->callee = other.callee->clone(); this->params.clear(); for (vector<Exp *>::const_iterator i = other.params.begin(); i != other.params.end(); i++) { this->params.push_back((*i)->clone()); } } string Call::tostring() { ostringstream ostr; Name *name; if (this->lval_opt != NULL) { ostr << this->lval_opt->tostring() << " = "; } if (this->callee->exp_type == NAME) { name = (Name *) this->callee; ostr << name->name; } else { ostr << "call " << this->callee->tostring(); } ostr << "("; for (vector<Exp *>::iterator i = this->params.begin(); i != this->params.end(); i++) { ostr << (*i)->tostring(); if ((i + 1) != this->params.end()) { ostr << ", "; } } ostr << ");"; string str = ostr.str(); return str; } Call *Call::clone() const { return new Call(*this); } Return::Return(Exp *exp_opt, address_t asm_ad, address_t ir_ad) : Stmt(RETURN, asm_ad, ir_ad) { this->exp_opt = exp_opt; } Return::Return(const Return &other) : Stmt(RETURN, other.asm_address, other.ir_address) { this->exp_opt = (other.exp_opt == NULL) ? NULL : other.exp_opt->clone(); } string Return::tostring() { ostringstream ostr; ostr << "return"; if (this->exp_opt != NULL) { ostr << " " << this->exp_opt->tostring(); } ostr << ";"; return ostr.str(); } Return *Return::clone() const { return new Return(*this); } Func::Func(string fnname, bool has_rv, reg_t rt, vector<VarDecl *> params, bool external, vector<Stmt *> body, address_t asm_ad, address_t ir_ad) : Stmt(FUNCTION, asm_ad, ir_ad) { this->fnname = fnname; this->has_rv = has_rv; this->rt = rt; this->params = params; this->external = external; this->body = body; } Func::Func(const Func &other) : Stmt(FUNCTION, other.asm_address, other.ir_address) { this->fnname = other.fnname; this->has_rv = other.has_rv; this->rt = other.rt; this->params.clear(); for (vector<VarDecl *>::const_iterator i = other.params.begin(); i != other.params.end(); i++) { this->params.push_back((*i)->clone()); } this->external = other.external; this->body.clear(); for (vector<Stmt *>::const_iterator i = other.body.begin(); i != other.body.end(); i++) { this->body.push_back((*i)->clone()); } } string Func::tostring() { ostringstream ostr; if (external) { ostr << "extern "; } if (has_rv) { ostr << Exp::string_type(rt) << " "; } else { ostr << "void "; } ostr << this->fnname << "("; for (vector<VarDecl *>::iterator i = this->params.begin(); i != this->params.end(); i++) { ostr << (*i)->tostring(); if ((i + 1) != this->params.end()) { ostr << ", "; } } ostr << ")"; if (this->body.empty()) { ostr << ";"; } else { ostr << "\n"; ostr << "{\n"; for (vector<Stmt *>::iterator i = this->body.begin(); i != this->body.end(); i++) { ostr << "\t" << (*i)->tostring() << endl; } ostr << "}"; } return ostr.str(); } Func *Func::clone() const { return new Func(*this); } Assert::Assert(Exp *cond, address_t asm_ad, address_t ir_ad) : Stmt(ASSERT, asm_ad, ir_ad), cond(cond) { } Assert::Assert(const Assert &other) : Stmt(ASSERT, other.asm_address, other.ir_address) { cond = other.cond->clone(); } string Assert::tostring() { return "assert(" + cond->tostring() + ");"; } Internal::Internal(int type, int size, address_t asm_addr, address_t ir_addr) : Stmt(INTERNAL, asm_addr, ir_addr) { this->type = type; this->size = size; if (size > 0) { this->data = malloc(size); assert(this->data); memset(this->data, 0, size); } else { this->data = NULL; } } Internal::Internal(const Internal &other) : Stmt(INTERNAL, other.asm_address, other.ir_address) { this->type = other.type; this->size = other.size; if (other.data) { this->data = malloc(other.size); assert(this->data); memcpy(this->data, other.data, other.size); } else { this->data = NULL; } } Internal::~Internal() { if (this->data) { free(this->data); } } Internal *Internal::clone() const { return new Internal(*this); } string Internal::tostring() { string s = ""; return s; } //---------------------------------------------------------------------- // Convert int to std::string in decimal form //---------------------------------------------------------------------- string int_to_str(int i) { ostringstream stream; stream << i << flush; return (stream.str()); } //---------------------------------------------------------------------- // Convert int to std::string in hex form //---------------------------------------------------------------------- string int_to_hex(int i) { ostringstream stream; stream << hex << i << flush; return (stream.str()); } //---------------------------------------------------------------------- // Generate a unique label, this is done using a static counter // internal to the function. //---------------------------------------------------------------------- Label *mk_label() { static int label_counter = 0; return new Label("L_" + int_to_str(label_counter++)); }
19.638655
113
0.543004
aeveris
7582297e43ee942e00e602f4e8cb642d4a4bdcf6
407
cpp
C++
Wonderland/Wonderland/Old Files/Source/Engine/Common/Containers/List/TLinkedList.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
3
2018-04-09T13:01:07.000Z
2021-03-18T12:28:48.000Z
Wonderland/Wonderland/Old Files/Source/Engine/Common/Containers/List/TLinkedList.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
null
null
null
Wonderland/Wonderland/Old Files/Source/Engine/Common/Containers/List/TLinkedList.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
1
2021-03-18T12:28:50.000Z
2021-03-18T12:28:50.000Z
/////////////////////////////////////////////////////////////////////////////// // Filename: TLinkedList.cpp /////////////////////////////////////////////////////////////////////////////// #include "TLinkedList.h" /* TLinkedList::TLinkedList() { } TLinkedList::TLinkedList(const TLinkedList& other) { } TLinkedList::~TLinkedList() { } bool TLinkedList::Initialize() { bool result; return true; } */
15.074074
79
0.425061
RodrigoHolztrattner
7586ba4cb3cf416d70a14bae06b2dc545a587962
491
cpp
C++
src/Arduino/ADXL345/example_basics.cpp
smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries
30795f46112ab5b56a8244b198f0193afb8755ba
[ "MIT" ]
null
null
null
src/Arduino/ADXL345/example_basics.cpp
smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries
30795f46112ab5b56a8244b198f0193afb8755ba
[ "MIT" ]
null
null
null
src/Arduino/ADXL345/example_basics.cpp
smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries
30795f46112ab5b56a8244b198f0193afb8755ba
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <stdint.h> #include <Math.h> #include "ADXL345.h" ADXL345 accel; void setup() { Serial.begin(9600); Wire.begin(); accel.begin(); delay(1500); } void loop() { float x = (int16_t) accel.getXAccel()* 0.00390625; Serial.println(x); float y = (int16_t) accel.getYAccel()* 0.00390625; Serial.println(y); float z = (int16_t) accel.getZAccel()* 0.00390625; Serial.println(z); Serial.println(); delay(500); }
15.83871
54
0.608961
smurilogs
758f6d7f32b13e08da3d2976b778a0f019bbf483
294
cpp
C++
app/src/main/cpp/native-lib.cpp
brayskiy/android-example
330e6e4e8d0f3f5037694f82fef7182a5dc251dd
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/native-lib.cpp
brayskiy/android-example
330e6e4e8d0f3f5037694f82fef7182a5dc251dd
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/native-lib.cpp
brayskiy/android-example
330e6e4e8d0f3f5037694f82fef7182a5dc251dd
[ "Apache-2.0" ]
null
null
null
#include <jni.h> #include <string> /** * Created by brayskiy on 01/31/19. */ extern "C" JNIEXPORT jstring JNICALL Java_com_brayskiy_example_NativeBridge_stringFromJNI(JNIEnv *env, jobject /* this */) { std::string hello = "Boris Example"; return env->NewStringUTF(hello.c_str()); }
22.615385
87
0.707483
brayskiy
75903e1d779e41bb474b8e1e222ec93febd70090
1,980
cpp
C++
GetMedian.cpp
Kwongrf/JianZhi
04c1135788cbc2cca472bb8ed79170003392f8ad
[ "Apache-2.0" ]
null
null
null
GetMedian.cpp
Kwongrf/JianZhi
04c1135788cbc2cca472bb8ed79170003392f8ad
[ "Apache-2.0" ]
null
null
null
GetMedian.cpp
Kwongrf/JianZhi
04c1135788cbc2cca472bb8ed79170003392f8ad
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<queue> #include<stack> using namespace std; class Solution { public: priority_queue<int,vector<int>,greater<int> >Q; void Insert(int num) { Q.push(num); } double GetMedian() { stack<int>s; int size; if(Q.size()%2 == 0) { size = Q.size(); for(int i = 0;i < size/2-1;i++) { s.push(Q.top()); Q.pop(); } int a1 = Q.top(); s.push(Q.top()); Q.pop(); int a2 = Q.top(); while(!s.empty()) { Q.push(s.top()); s.pop(); } return ((double)a1 + (double)a2) / 2; } else { size = Q.size(); for(int i = 0;i < size/2;i++) { s.push(Q.top()); Q.pop(); } int a = Q.top(); while(!s.empty()) { Q.push(s.top()); s.pop(); } return (double)a; } return -1.0; } void show() { stack<int>s; while(!Q.empty()) { cout<<Q.top()<<" "; s.push(Q.top()); Q.pop(); } cout<<endl<<endl; while(!s.empty()) { Q.push(s.top()); s.pop(); } } }; int main() { Solution so; so.Insert(5); cout<<so.GetMedian()<<endl; so.show(); so.Insert(2); cout<<so.GetMedian()<<endl; so.show(); so.Insert(3); cout<<so.GetMedian()<<endl; so.show(); so.Insert(4); cout<<so.GetMedian()<<endl; so.show(); so.Insert(1); cout<<so.GetMedian()<<endl; so.show(); so.Insert(6); cout<<so.GetMedian()<<endl; so.show(); so.Insert(7); cout<<so.GetMedian()<<endl; so.show(); so.Insert(0); cout<<so.GetMedian()<<endl; so.show(); so.Insert(8); cout<<so.GetMedian()<<endl; so.show(); }
18.679245
51
0.40101
Kwongrf
7595c473c83949b920e976fe7882de7871505b6a
7,715
cpp
C++
test/cpp/exceptions.cpp
fujiehuang/ecto
fea744337aa1fad1397c9a3ba5baa143993cb5eb
[ "BSD-3-Clause" ]
77
2015-01-30T15:45:43.000Z
2022-03-03T02:29:37.000Z
test/cpp/exceptions.cpp
fujiehuang/ecto
fea744337aa1fad1397c9a3ba5baa143993cb5eb
[ "BSD-3-Clause" ]
37
2015-01-18T21:04:36.000Z
2021-07-09T08:24:54.000Z
test/cpp/exceptions.cpp
fujiehuang/ecto
fea744337aa1fad1397c9a3ba5baa143993cb5eb
[ "BSD-3-Clause" ]
29
2015-02-17T14:37:18.000Z
2021-11-16T07:46:26.000Z
// // Copyright (c) 2011, Willow Garage, 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 the Willow Garage, 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 <Python.h> #include <gtest/gtest.h> #include <boost/exception/diagnostic_information.hpp> #include <ecto/ecto.hpp> #include <ecto/except.hpp> #include <ecto/plasm.hpp> #include <ecto/scheduler.hpp> #define STRINGDIDLY(A) std::string(#A) using namespace ecto; struct InConstructorExcept { InConstructorExcept() { throw std::logic_error("no.... I do not want to live."); } }; struct ExceptionalModule1 { static void declare_params(tendrils& p) { p.declare<double> ("d"); p.declare<float> ("f").set_default_val(p.get<float> ("d")); } }; struct ExceptionUnknownException { static void declare_params(tendrils& p) { p.declare<double> ("d"); } static void declare_io(const tendrils& p, tendrils& in, tendrils& out) { in.declare<double> ("d"); throw "A string"; } }; struct NotExist { static void declare_params(tendrils& p) { p.declare<int> ("a"); } static void declare_io(const tendrils& p, tendrils& in, tendrils& out) { in.declare<double> ("d"); in.declare<ExceptionalModule1> ("c"); in.declare<std::string> ("e"); out.declare<std::string> ("a"); } int process(const tendrils& in, const tendrils& out) { in.get<double> ("a"); return 0; } }; struct WrongType { static void declare_io(const tendrils& p, tendrils& in, tendrils& out) { in.declare<double> ("d"); } int process(const tendrils& in, const tendrils& out) { in.get<int> ("d"); return 0; } }; struct ParameterCBExcept { static void declare_params(tendrils& p) { p.declare<double> ("x"); } void xcb(double x) { std::cout << "*** about to throw std::runtime_error ***" << std::endl; throw std::runtime_error("I'm a bad callback, and I like it that way."); } void configure(const tendrils& p,const tendrils& in, const tendrils& out) { std::cout << "configurated ***" << std::endl; spore<double> x = p["x"]; x.set_callback(boost::bind(&ParameterCBExcept::xcb,this,_1)); } }; struct ProcessException { int process(const tendrils& in, const tendrils& out) { throw std::logic_error("A standard exception"); return ecto::OK; } }; TEST(Exceptions, ExceptionalModules) { try { cell* p = new cell_<ExceptionalModule1>; p->declare_params(); } catch (except::EctoException& e) { std::cout << "Good, threw an exception:\n" << e.what() << std::endl; } } TEST(Exceptions, ExceptionUnknownException) { try { cell* c = new cell_<ExceptionUnknownException>; c->declare_params(); c->declare_io(); } catch (except::EctoException& e) { std::cout << "Good, threw an exception:\n" << e.what() << std::endl; } } #define MEH(x, y) x TEST(Exceptions, ProcessException) { std::string stre("Original Exception: std::logic_error\n" " What : A standard exception\n" " Module : ProcessException\n" " Function: process"); cell::ptr m(new cell_<ProcessException>); EXPECT_THROW( try { m->process(); } catch (except::EctoException& e) { std::cout << "Good, threw an exception:\n" << e.what() << std::endl; std::cout << diagnostic_information(e) << "\n"; /* if(stre != e.msg_) { throw std::runtime_error("Got :" + e.msg_ +"\nExpected :" +stre); } */ throw; } , ecto::except::EctoException); } TEST(Exceptions, NotExist) { std::string stre( "'a' does not exist in this tendrils object. Possible keys are: 'c':type(ExceptionalModule1) 'd':type(double) 'e':type(std::string)\n" " Hint : 'a' does exist in parameters (type == int) outputs (type == std::string)\n" " Module : NotExist\n" " Function: process"); cell::ptr m(new cell_<NotExist>); try { m->process(); } catch (except::NonExistant& e) { std::cout << "Good, threw an exception:\n" << e.what() << std::endl; //EXPECT_EQ(stre, e.msg_); } } TEST(Exceptions, WrongType) { std::string stre("double is not a int\n" " Hint : 'd' is of type double\n" " Module : WrongType\n" " Function: process"); cell::ptr m(new cell_<WrongType>); m->declare_params(); m->declare_io(); bool threw = false; try { m->process(); } catch (except::TypeMismatch& e) { std::cout << "Good, threw an exception:\n" << e.what() << std::endl; // EXPECT_EQ(stre, e.msg_); threw = true; } EXPECT_TRUE(threw); } TEST(Exceptions, WrongType_sched) { for (unsigned j=0; j<100; ++j) { cell::ptr m(new cell_<WrongType>); m->declare_params(); m->declare_io(); plasm::ptr p(new plasm); p->insert(m); scheduler sched(p); bool threw = false; try { sched.execute(8); FAIL(); } catch (except::TypeMismatch& e) { std::cout << "Good, threw an exception:\n" << e.what() << std::endl; threw = true; } EXPECT_TRUE(threw); } } TEST(Exceptions, ParameterCBExcept_sched) { cell::ptr m(new cell_<ParameterCBExcept>); m->declare_params(); m->declare_io(); m->parameters["x"] << 5.1; m->parameters["x"]->dirty(true); plasm::ptr p(new plasm); p->insert(m); scheduler sched(p); try { sched.execute(8); FAIL(); } catch (except::EctoException& e) { std::cout << "Good, threw an exception:\n" << ecto::except::diagnostic_string(e) << std::endl; } } TEST(Exceptions, ConstructorExcept) { cell::ptr m(new cell_<InConstructorExcept>); m->declare_params(); m->declare_io(); plasm::ptr p(new plasm); p->insert(m); scheduler sched(p); try { sched.execute(8); FAIL(); } catch (except::EctoException& e) { std::cout << "Good, threw an exception:\n" << ecto::except::diagnostic_string(e) << std::endl; const std::string* what = boost::get_error_info<ecto::except::what>(e); EXPECT_TRUE(what); EXPECT_EQ(*what, std::string("no.... I do not want to live.")); } }
24.967638
146
0.623331
fujiehuang
759700e8171ec4a0b2c3899cc3ccdea6d83aa383
462
cpp
C++
18-STL/03-Using_STL.cpp
PronomitaDey/Cpp_Tutorial
a64a10a27d018bf9edf5280505201a1fbfd359ed
[ "MIT" ]
null
null
null
18-STL/03-Using_STL.cpp
PronomitaDey/Cpp_Tutorial
a64a10a27d018bf9edf5280505201a1fbfd359ed
[ "MIT" ]
1
2021-10-01T13:35:44.000Z
2021-10-02T03:54:29.000Z
18-STL/03-Using_STL.cpp
PronomitaDey/Cpp_Tutorial
a64a10a27d018bf9edf5280505201a1fbfd359ed
[ "MIT" ]
3
2021-10-01T14:07:09.000Z
2021-10-01T18:24:31.000Z
#include <vector> #include <list> #include <iostream> using namespace std; int main() { // Creating a Vector vector<int> v = {10, 20, 40}; v.push_back(25); v.push_back(55); v.pop_back(); // To create an iterator vector<int>::iterator itr = v.begin(); for (itr = v.begin(); itr != v.end(); itr++) { cout << ++*itr << endl; } // for (int x : v) // { // cout << x << " "; // } return 0; }
16.5
48
0.484848
PronomitaDey
759e21d1f0182578dd7f01be8e13627a7295980b
100
cpp
C++
src/Plugins/U4_AdminCommands/Source/U4_AdminCommands/Private/U4_AdminCommand_Sunset.cpp
CyberAndrii/unturned4-mod-example
05595a0e5411b18ac6b8b06bbf8e2797f95defaa
[ "MIT" ]
6
2022-03-20T01:34:32.000Z
2022-03-28T19:32:53.000Z
src/Plugins/U4_AdminCommands/Source/U4_AdminCommands/Private/U4_AdminCommand_Sunset.cpp
CyberAndrii/unturned4-mod-example
05595a0e5411b18ac6b8b06bbf8e2797f95defaa
[ "MIT" ]
null
null
null
src/Plugins/U4_AdminCommands/Source/U4_AdminCommands/Private/U4_AdminCommand_Sunset.cpp
CyberAndrii/unturned4-mod-example
05595a0e5411b18ac6b8b06bbf8e2797f95defaa
[ "MIT" ]
null
null
null
// Copyright Smartly Dressed Games Ltd. All Rights Reserved. #include "U4_AdminCommand_Sunset.h"
16.666667
60
0.78
CyberAndrii
75a3e45d268250dc4c29690f7603562f056bea3d
6,455
cpp
C++
src/LLAPI/Math/Vector3.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/LLAPI/Math/Vector3.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/LLAPI/Math/Vector3.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
#include <cmath> #include "Vector3.h" #include "Vector4.h" #include "Matrix.h" namespace oakvr { namespace math { // -------------------------------------------------------------------------------- Vector3::Vector3(BaseType x, BaseType y, BaseType z) noexcept : x(x), y(y), z(z) { } Vector3::Vector3(const std::initializer_list<BaseType> &initList) noexcept { BaseType *p = &x; for (size_t i = 0; i < initList.size() && i < 3; ++i) *(p++) = *(initList.begin() + i); for (size_t i = initList.size(); i < 3; ++i) *(p++) = 0.0f; } // -------------------------------------------------------------------------------- Vector3::Vector3(const Vector4 &vec) noexcept { x = vec.x; y = vec.y; z = vec.z; } // -------------------------------------------------------------------------------- Vector3::Vector3(const BaseType* arr) noexcept { x = arr[0]; y = arr[1]; z = arr[2]; } //------------------------------------------------------ // other methods // -------------------------------------------------------------------------------- auto Vector3::GetLength() const noexcept -> BaseType { return std::pow(x * x + y * y + z * z, 0.5f); } // -------------------------------------------------------------------------------- auto Vector3::GetSquareLength() const noexcept -> BaseType { return x * x + y * y + z * z; } // -------------------------------------------------------------------------------- auto Vector3::GetNormalized() const noexcept -> Vector3 { const BaseType magnitudeSquare = x * x + y * y + z * z; if (magnitudeSquare < 1e-15f) return Vector3(0.0f, 0.0f, 0.0f); const BaseType invDenom = 1.0f / std::pow(magnitudeSquare, 0.5f); return Vector3(x * invDenom, y * invDenom, z * invDenom); } // -------------------------------------------------------------------------------- auto Vector3::Normalize() noexcept -> BaseType { const BaseType magnitudeSquare = x * x + y * y + z * z; if (magnitudeSquare < 1e-15f) return 0.0f; BaseType length = std::pow(magnitudeSquare, 0.5f); const BaseType invDenom = 1.0f / length; x *= invDenom; y *= invDenom; z *= invDenom; return length; } // -------------------------------------------------------------------------------- auto Vector3::Dot(const Vector3 &vec) const noexcept -> BaseType { return x * vec.x + y * vec.y + z * vec.z; } // -------------------------------------------------------------------------------- auto Vector3::Cross(const Vector3 &vec) const noexcept -> Vector3 { // compute as 3D cross product return Vector3(y * vec.z - z * vec.y, z * vec.x - x * vec.z, x * vec.y - y * vec.x); } // -------------------------------------------------------------------------------- auto Vector3::operator * (const Matrix &mat) const noexcept -> Vector3 { Vector3 result; result.x = x * mat._11 + y * mat._21 + z * mat._31 + mat._41; result.y = x * mat._12 + y * mat._22 + z * mat._32 + mat._42; result.z = x * mat._13 + y * mat._23 + z * mat._33 + mat._43; return result; } // -------------------------------------------------------------------------------- auto operator * (const Matrix &mat, const Vector3 &vec) noexcept -> Vector3 { Vector3 result; result.x = vec.x * mat._11 + vec.y * mat._12 + vec.z * mat._13 + mat._14; result.y = vec.x * mat._21 + vec.y * mat._22 + vec.z * mat._23 + mat._24; result.z = vec.x * mat._31 + vec.y * mat._32 + vec.z * mat._33 + mat._34; return result; } // -------------------------------------------------------------------------------- auto Vector3::operator * (BaseType scalar) const noexcept -> Vector3 { return Vector3(scalar * x, scalar * y, scalar * z); } // -------------------------------------------------------------------------------- auto operator * (Vector3::BaseType scalar, const Vector3 &vec) noexcept -> Vector3 { return Vector3(scalar * vec.x, scalar * vec.y, scalar * vec.z); } // -------------------------------------------------------------------------------- auto Vector3::operator / (BaseType scalar) const noexcept -> Vector3 { BaseType invDenom = 1 / scalar; return Vector3(x * invDenom, y * invDenom, z * invDenom); } // -------------------------------------------------------------------------------- auto Vector3::operator + () const noexcept -> Vector3 { return *this; } // -------------------------------------------------------------------------------- auto Vector3::operator - () const noexcept -> Vector3 { return Vector3(-x, -y, -z); } // -------------------------------------------------------------------------------- auto Vector3::operator + (const Vector3 &vec) const noexcept -> Vector3 { return Vector3(x + vec.x, y + vec.y, z + vec.z); } // -------------------------------------------------------------------------------- auto Vector3::operator - (const Vector3 &vec) const noexcept -> Vector3 { return Vector3(x - vec.x, y - vec.y, z - vec.z); } // -------------------------------------------------------------------------------- auto Vector3::operator += (const Vector3 &vec) noexcept -> Vector3& { x += vec.x; y += vec.y; z += vec.z; return *this; } // -------------------------------------------------------------------------------- auto Vector3::operator -= (const Vector3 &vec) noexcept -> Vector3& { x -= vec.x; y -= vec.y; z -= vec.z; return *this; } // -------------------------------------------------------------------------------- auto Vector3::operator *= (BaseType scalar) noexcept -> Vector3& { x *= scalar; y *= scalar; z *= scalar; return *this; } // -------------------------------------------------------------------------------- auto Vector3::operator /= (BaseType scalar) noexcept -> Vector3& { x /= scalar; y /= scalar; z /= scalar; return *this; } auto Vector3::operator==(const Vector3& vec) const noexcept -> bool { return (x == vec.x) && (y == vec.y) && (z == vec.z); } auto Vector3::operator!=(const Vector3& vec) const noexcept -> bool { return (x != vec.x) || (y != vec.y) || (z != vec.z); } // static member initialization Vector3 Vector3::One = { 1.0f, 1.0f, 1.0f }; Vector3 Vector3::Zero = { 0.0f, 0.0f, 0.0f }; } // namespace math } // namespace oakvr
30.163551
87
0.410225
bluespeck
75a3f78aae1ebf4bad6c984235a3a46d637404ee
1,946
cpp
C++
battleship/PlayState.cpp
YourRoyalLinus/Battleship
b7cbad63a44ce896d678ff66521d00d4835274c7
[ "MIT" ]
null
null
null
battleship/PlayState.cpp
YourRoyalLinus/Battleship
b7cbad63a44ce896d678ff66521d00d4835274c7
[ "MIT" ]
null
null
null
battleship/PlayState.cpp
YourRoyalLinus/Battleship
b7cbad63a44ce896d678ff66521d00d4835274c7
[ "MIT" ]
null
null
null
#include "PlayState.h" #include "Game.h" #include "Marker.h" PlayState::PlayState(Game& game) : GameState(game) { game.player->board->addObserver(&game); } void PlayState::render() { game.renderRadarPings(); //update uniforms if (game.activePlayer == game.player) { ResourceManager::getShader("radar2").use().setFloat("turn", 1.0f); } else { ResourceManager::getShader("radar2").use().setFloat("turn", 0.0f); } ResourceManager::getShader("grid").use().setFloat("iTime", game.mticks()); ResourceManager::getShader("water").use().setFloat("iTime", game.mticks()); //testing new radar effect. //TODO: these don't need to be done with uniforms right now. ResourceManager::getShader("radar2").use().setFloat("time", game.mticks()); //Render to off-screen buffer for postprocessing effects game.effects->beginRender(); game.opponent->board->draw(*game.radarBoardRenderer); game.player->board->draw(*game.waterRenderer); glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); game.grid->draw(*game.gridRenderer); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //if (game.activePlayer == game.player) { // turnPrompt.draw(*game.spriteRenderer); //} //Draw miss markers where opponent guessed wrong for(auto square : game.player->board->guessedSquares){ if (!square.occupied) { Marker miss(Marker::Type::MISS, glm::vec2(600 + square.col * Game::SQUARE_PIXEL_SIZE, square.row * Game::SQUARE_PIXEL_SIZE)); miss.draw(*game.spriteRenderer); } } //draw placed ships on player's board for (auto& ship : game.player->board->activeShips) { ship.draw(*game.shipRenderer); } for (auto& fireEmitter : game.fireEmitters) { fireEmitter.draw(); } for (auto& smokeEmitter : game.smokeEmitters) { smokeEmitter.draw(); } game.removeUnderwaterFire(); //after redering whole scene to off-screen buffer, apply postprocessing affects and blit to screen. game.effects->endRender(); game.effects->render(game.shakeTime); }
31.901639
128
0.720966
YourRoyalLinus
b5a4f06b8dc249bcc64b0fe586600ccf5c8393c0
2,609
cpp
C++
samples/std-remove-if/std-remove-if.cpp
Studiofreya/code-samples
4057c5204d7d37c29ded306861ef6eaded7527e5
[ "MIT" ]
17
2015-08-13T05:30:48.000Z
2022-03-16T16:03:28.000Z
samples/std-remove-if/std-remove-if.cpp
Studiofreya/code-samples
4057c5204d7d37c29ded306861ef6eaded7527e5
[ "MIT" ]
null
null
null
samples/std-remove-if/std-remove-if.cpp
Studiofreya/code-samples
4057c5204d7d37c29ded306861ef6eaded7527e5
[ "MIT" ]
18
2015-02-22T16:36:54.000Z
2022-02-07T00:04:39.000Z
#include <vector> #include <list> #include <string> #include <algorithm> #include <iterator> #include <iostream> template<typename T> void printVector(const T & v) { std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; } int main() { { // Vector with numbers, initialized with an initializer list std::vector<int> numbers{ 1,1,2,3,4,5,6 }; // Lambda for removing numbers less than 3 auto removeNumbers = [&](int number) -> bool { return number < 3; }; // Print contents of vector printVector(numbers); // Call std::remove_if and obtain iterator auto iterator = std::remove_if(numbers.begin(), numbers.end(), removeNumbers); // Print vector again printVector(numbers); // Remove from vector numbers.erase(iterator, numbers.end());; // Final print of vectors printVector(numbers); } { std::list<int> numbers{ 1,1,2,3,4,5,6 }; // Lambda for removing numbers less than 3 auto removeNumbers = [](int number) -> bool { return number < 3; }; printVector(numbers); numbers.remove_if(removeNumbers); printVector(numbers); } { std::vector<int> numbers{ 1,1,2,3,4,5,6 }; std::vector<int> removed(numbers.size()); // Lambda for removing numbers less than 3 auto removeNumbers = [&](int number) -> bool { return number < 3; }; printVector(numbers); std::remove_copy_if(numbers.begin(), numbers.end(), removed.begin(), removeNumbers); printVector(numbers); int baba = 0; } { struct Widget { std::string name; // Widget name bool deleted; // Should be deleted }; auto printWidgets = [&](const std::vector<Widget> & widgets) { for (const auto & w : widgets) { std::cout << std::boolalpha << "'" << w.name << "'=" << w.deleted << " "; } std::cout << "\n"; }; // Store them in a container std::vector<Widget> widgets; widgets.emplace_back(Widget{ "W1", true }); widgets.emplace_back(Widget{ "W2", true }); widgets.emplace_back(Widget{ "W3", false }); widgets.emplace_back(Widget{ "W4", true }); widgets.emplace_back(Widget{ "W5", false }); widgets.emplace_back(Widget{ "W6", true }); widgets.emplace_back(Widget{ "W7", true }); widgets.emplace_back(Widget{ "W8", false }); auto removeDeletedWidgets = [&](const Widget & widget) -> bool { return widget.deleted; }; printWidgets(widgets); auto iterator = std::remove_if(widgets.begin(), widgets.end(), removeDeletedWidgets); printWidgets(widgets); widgets.erase(iterator, widgets.end()); printWidgets(widgets); int baba = 0; } return 0; }
20.382813
87
0.643542
Studiofreya
b5a6756ac95c7f7af30a235d76eef0fe9278fc0c
3,129
cpp
C++
LargeCarCO.cpp
IRLSCU/QtController
597d6153f641073c367724fcccc9fe5e68cb2c18
[ "Apache-2.0" ]
null
null
null
LargeCarCO.cpp
IRLSCU/QtController
597d6153f641073c367724fcccc9fe5e68cb2c18
[ "Apache-2.0" ]
null
null
null
LargeCarCO.cpp
IRLSCU/QtController
597d6153f641073c367724fcccc9fe5e68cb2c18
[ "Apache-2.0" ]
null
null
null
#include "LargeCarCO.h" LargeCarCO::LargeCarCO() {} LargeCarCO::~LargeCarCO(){} LargeCarCO& LargeCarCO::setTurnRange(qint16 turnRange) {//0~15位,第0、1个字节 // if (turnRange > LARGECARCO_MAX_TURN_RANGE) { // turnRange = LARGECARCO_MAX_TURN_RANGE; // } // else if (turnRange < LARGECARCO_MIN_TURN_RANGE) { // turnRange = LARGECARCO_MIN_TURN_RANGE; // } this->turnRange = turnRange; return *this; } LargeCarCO& LargeCarCO::setSpeed(quint8 speed) {//16~23位,第2个字节.0表示最大加速度,127表示最小加速度 // if (speed < LARGECARCO_MAX_SPEED) { // speed = LARGECARCO_MAX_SPEED; // } // else if (speed > LARGECARCO_MIN_SPEED) { speed = LARGECARCO_MIN_SPEED; } this->speed = speed; return *this; } LargeCarCO& LargeCarCO::setBrake(quint8 brake) {//16~23位,第2个字节,128最小减速度,255最大减速度 // if (brake > LARGECARCO_MAX_BRAKE) { // brake = LARGECARCO_MAX_BRAKE; // } // else if (brake < LARGECARCO_MIN_BRAKE) { brake = LARGECARCO_MIN_BRAKE; } this->speed = brake; return *this; } /* 三种挡位0空挡,1表示前进挡,2表示后退挡 */ LargeCarCO& LargeCarCO::setGear(quint8 gear) {//24~31,第3个字节 if (gear == LARGECARCO_GEAR_ZERO || gear == LARGECARCO_GEAR_FORWARD || gear == LARGECARCO_GEAR_BACKWARD) { this->gear = gear; }else{ qDebug("geal=%d,setting error",gear); } return *this; } /* 灯光 0不亮 1右转向灯亮 2左转向灯亮 3应急灯亮 */ LargeCarCO& LargeCarCO::setSignal(quint8 signal) {//32-39,第4个字节 if (signal==LARGECARCO_LIGHT_ALL_OFF||signal==LARGECARCO_LIGHT_LEFT_ON||signal==LARGECARCO_LIGHT_RIGHT_ON) { this->signal = signal; }else{ qDebug("signal=%d,setting error",signal); } return *this; } /* (1)代表鸣笛;(0)代表静音 */ LargeCarCO& LargeCarCO::setHorn(quint8 horn) {//40-47,第5个字节 if (horn == LARGECARCO_HORN_OFF || horn == LARGECARCO_HORN_ON) { this->horn = horn; }else{ qDebug("horn=%d,setting error",horn); } return *this; } void LargeCarCO::emergencyBraking() { init(); setBrake(LARGECARCO_MAX_BRAKE); qDebug()<<QStringLiteral("紧急刹车"); } void LargeCarCO::init() { for (int i = 0; i < 8; i++) { this->charOrder[i] = 0; } setTurnRange(0); setSpeed(LARGECARCO_MIN_SPEED); setSignal(0); setHorn(0); setGear(0); } quint8* LargeCarCO::getCharOrder() { //转向 quint8 low = (turnRange & 0x00FF); quint8 high = (turnRange >>8) & 0x00FF; this->charOrder[0] = low; this->charOrder[1] = high; //速度 this->charOrder[2] = speed; //挡位 this->charOrder[3] =gear; //转向灯 this->charOrder[4] = signal; //鸣笛 this->charOrder[5] = horn; return charOrder; } void LargeCarCO::printInfo(){ qDebug("Large Car Control Order: speed:%d,turnRange:%d,gear:%d%s,lightSignal:%d%s,hore:%d%s", speed,turnRange, gear,gear==0?QStringLiteral("空挡"):gear==1?QStringLiteral("前进挡"):QStringLiteral("后退档"), signal,signal==0?QStringLiteral("所有灯光关闭"):signal==1?QStringLiteral("右转向灯亮"):QStringLiteral("左转向灯亮"), horn,horn==0?QStringLiteral("静音"):QStringLiteral("鸣笛") ); }
27.447368
113
0.628316
IRLSCU
b5a6eeec7f14c117b98107898c5773542a18e012
1,602
cpp
C++
src/autoCL.cpp
jeschwarz0/JobHelper
6e86270717e053e7798b06726b0a076d20894c62
[ "MIT" ]
null
null
null
src/autoCL.cpp
jeschwarz0/JobHelper
6e86270717e053e7798b06726b0a076d20894c62
[ "MIT" ]
null
null
null
src/autoCL.cpp
jeschwarz0/JobHelper
6e86270717e053e7798b06726b0a076d20894c62
[ "MIT" ]
null
null
null
/* * File: autoCL.cpp * Author: Jesse Schwarz * * Created on January 15, 2018, 7:22 PM */ #include <stdio.h> #include <iostream> #include <string> #include <stdlib.h> #include "autoCL.h" using namespace std; namespace autoCL { cltype manualGetType(cltype rec) { cout << "What type would you like:\n" << none << "='EXIT'\n" << (rec == 1 ? "(R)" : "") << Default << "=Default\n"; char c; cin >> c; cin.clear(); cin.ignore(); return (c == 'r' || c == 'R') ? rec : (cltype) atoi(&c); } //TODO: Fix this string getString(const char* IDENTIFIER, const string& REC) { const bool USEREC = REC != "NA" && REC != "NYI"; cout << "Please enter the " << IDENTIFIER << (USEREC ? ",[r]" : "") << (USEREC ? REC : "") << ": "; string rv; getline(cin, rv); return !rv.empty()&&(rv.at(0) == 'r' || rv.at(0) == 'R') && REC != "NA" ? REC : rv; } void strReplace(string& haystack, const string find, const string replace) { for (size_t offset = haystack.find(find); offset != string::npos; offset = haystack.find(find)) { haystack.erase(offset, find.size()); haystack.insert(offset, replace); } } std::string getCoverLetter(cltype t, const string POSITION, const string COMPANY) { string rawrval = "!!!Not Implemented!!!";//TODO: Implement from file system strReplace(rawrval, "<position>", POSITION); strReplace(rawrval, "<employer>", COMPANY); return rawrval; } }
31.411765
105
0.535581
jeschwarz0
b5a824768873235c4384d56b669ab26f2eafc9e5
2,494
cpp
C++
console/src/boost_1_78_0/libs/bind/test/apply_rv_test2.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
106
2015-08-07T04:23:50.000Z
2020-12-27T18:25:15.000Z
console/src/boost_1_78_0/libs/bind/test/apply_rv_test2.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
130
2016-06-22T22:11:25.000Z
2020-11-29T20:24:09.000Z
Libs/boost_1_76_0/libs/bind/test/apply_rv_test2.cpp
Antd23rus/S2DE
47cc7151c2934cd8f0399a9856c1e54894571553
[ "MIT" ]
41
2015-07-08T19:18:35.000Z
2021-01-14T16:39:56.000Z
// Copyright 2021 Peter Dimov // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt #include<boost/bind/apply.hpp> #include<boost/bind/bind.hpp> #include <boost/core/lightweight_test.hpp> #include <boost/config.hpp> #include <boost/config/pragma_message.hpp> #if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) BOOST_PRAGMA_MESSAGE("Skipping test because BOOST_NO_CXX11_RVALUE_REFERENCES is defined") int main() {} #elif defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) BOOST_PRAGMA_MESSAGE("Skipping test because BOOST_NO_CXX11_VARIADIC_TEMPLATES is defined") int main() {} #elif defined(BOOST_NO_CXX11_REF_QUALIFIERS) BOOST_PRAGMA_MESSAGE("Skipping test because BOOST_NO_CXX11_REF_QUALIFIERS is defined") int main() {} #else struct F { public: int operator()( int & x ) & { return x; } int operator()( int && x ) & { return -x; } int operator()( int & x ) && { return x + 10; } int operator()( int && x ) && { return -x - 10; } }; int& get_lvalue_arg() { static int a = 1; return a; } int get_prvalue_arg() { return 2; } F& get_lvalue_f() { static F f; return f; } F get_prvalue_f() { return F(); } int main() { using namespace boost::placeholders; BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(get_lvalue_f), boost::bind(get_lvalue_arg))(), 1 ); BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(get_lvalue_f), boost::bind(get_prvalue_arg))(), -2 ); BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(get_prvalue_f), boost::bind(get_lvalue_arg))(), 11 ); BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(get_prvalue_f), boost::bind(get_prvalue_arg))(), -12 ); BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(boost::apply<F&>(), _1), boost::bind(boost::apply<int&>(), _2))(get_lvalue_f, get_lvalue_arg), 1 ); BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(boost::apply<F&>(), _1), boost::bind(boost::apply<int>(), _2))(get_lvalue_f, get_prvalue_arg), -2 ); BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(boost::apply<F>(), _1), boost::bind(boost::apply<int&>(), _2))(get_prvalue_f, get_lvalue_arg), 11 ); BOOST_TEST_EQ( boost::bind(boost::apply<int>(), boost::bind(boost::apply<F>(), _1), boost::bind(boost::apply<int>(), _2))(get_prvalue_f, get_prvalue_arg), -12 ); return boost::report_errors(); } #endif
26.817204
165
0.670409
vany152
b5a9b5fe2ec358ffd88a72c58e05529f9c85ee6e
3,706
cpp
C++
PostView2/AreaCoverageTool.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
9
2020-03-22T08:27:03.000Z
2021-09-24T10:02:37.000Z
PostView2/AreaCoverageTool.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
1
2021-03-02T06:45:59.000Z
2021-03-02T06:45:59.000Z
PostView2/AreaCoverageTool.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
2
2020-06-27T13:59:49.000Z
2021-09-08T16:39:39.000Z
/*This file is part of the PostView source code and is licensed under the MIT license listed below. See Copyright-PostView.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "AreaCoverageTool.h" #include <QBoxLayout> #include <QPushButton> #include <QLineEdit> #include <QLabel> #include <vector> #include "Document.h" #include <PostLib/FEAreaCoverage.h> using namespace std; using namespace Post; class CAreaCoverageToolUI : public QWidget { public: QPushButton* p1; QPushButton* p2; QLineEdit* name; FEAreaCoverage m_tool; public: CAreaCoverageToolUI(CAreaCoverageTool* tool) : m_tool(nullptr) { name = new QLineEdit; name->setPlaceholderText("Enter name here"); p1 = new QPushButton("Assign to surface 1"); p2 = new QPushButton("Assign to surface 2"); QPushButton* apply = new QPushButton("Apply"); QHBoxLayout* h = new QHBoxLayout; h->addWidget(new QLabel("Name:")); h->addWidget(name); QVBoxLayout* pv = new QVBoxLayout; pv->addLayout(h); pv->addWidget(p1); pv->addWidget(p2); pv->addWidget(apply); pv->addStretch(); setLayout(pv); QObject::connect(p1, SIGNAL(clicked(bool)), tool, SLOT(OnAssign1())); QObject::connect(p2, SIGNAL(clicked(bool)), tool, SLOT(OnAssign2())); QObject::connect(apply, SIGNAL(clicked(bool)), tool, SLOT(OnApply())); } }; //============================================================================= CAreaCoverageTool::CAreaCoverageTool(CMainWindow* wnd) : CAbstractTool("Area Coverage", wnd) { ui = 0; } QWidget* CAreaCoverageTool::createUi() { return ui = new CAreaCoverageToolUI(this); } void CAreaCoverageTool::OnAssign1() { CDocument* doc = GetActiveDocument(); if (doc && doc->IsValid()) { vector<int> sel; doc->GetGLModel()->GetSelectionList(sel, SELECT_FACES); ui->m_tool.SetSelection1(sel); int n = (int)sel.size(); ui->p1->setText(QString("Assign to surface 1 (%1 faces)").arg(n)); } } void CAreaCoverageTool::OnAssign2() { CDocument* doc = GetActiveDocument(); if (doc && doc->IsValid()) { vector<int> sel; doc->GetGLModel()->GetSelectionList(sel, SELECT_FACES); ui->m_tool.SetSelection2(sel); int n = (int)sel.size(); ui->p2->setText(QString("Assign to surface 2 (%1 faces)").arg(n)); } } void CAreaCoverageTool::OnApply() { CDocument* doc = GetActiveDocument(); if (doc && doc->IsValid()) { /* FEAreaCoverage& tool = ui->m_tool; tool.SetDataFieldName(""); QString name = ui->name->text(); if (name.isEmpty() == false) { tool.SetDataFieldName(name.toStdString()); } tool.Apply(doc->GetFEModel()); updateUi(); */ } }
28.075758
92
0.712628
febiosoftware
b5ab6f6812fe48806537cf6080b72c65ca2dcf1c
2,304
cpp
C++
src/vec3.cpp
francisrstokes/WaveStrider
854095c6fec04dfcafabc8bcbf65745fa62f4880
[ "MIT" ]
1
2021-05-30T16:21:11.000Z
2021-05-30T16:21:11.000Z
src/vec3.cpp
francisrstokes/cpp-raymarcher
854095c6fec04dfcafabc8bcbf65745fa62f4880
[ "MIT" ]
null
null
null
src/vec3.cpp
francisrstokes/cpp-raymarcher
854095c6fec04dfcafabc8bcbf65745fa62f4880
[ "MIT" ]
null
null
null
#include "vec3.hpp" #include <math.h> namespace WaveStrider { vec3::vec3(double X, double Y, double Z) : x{ X }, y{ Y }, z{ Z } {}; vec3::vec3(double n) : x{ n }, y{ n }, z{ n } {}; vec3::vec3() : x{ 0 }, y{ 0 }, z{ 0 } {}; vec3::vec3(const vec3 &v) : x{ v.x }, y{ v.y }, z{ v.z } {}; double vec3::length() { return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)); }; vec3 vec3::clamp(double minVal, double maxVal) { return vec3( x < minVal ? minVal : x > maxVal ? maxVal : x, y < minVal ? minVal : y > maxVal ? maxVal : y, z < minVal ? minVal : z > maxVal ? maxVal : z); }; double vec3::dot(vec3 const &b) { return x * b.x + y * b.y + z * b.z; }; vec3 vec3::normalize() { double l = length(); if (l == 0) return vec3(x, y, z); return vec3( x / l, y / l, z / l); }; vec3 vec3::max(double n) { return vec3( x > n ? x : n, y > n ? y : n, z > n ? z : n); }; vec3 vec3::min(double n) { return vec3( x < n ? x : n, y < n ? y : n, z < n ? z : n); }; vec3 vec3::operator+(const vec3 &b) { return vec3(this->x + b.x, this->y + b.y, this->z + b.z); }; vec3 vec3::operator-(const vec3 &b) { return vec3(this->x - b.x, this->y - b.y, this->z - b.z); }; vec3 vec3::operator*(const vec3 &b) { return vec3(this->x * b.x, this->y * b.y, this->z * b.z); }; vec3 vec3::operator*(double n) { return vec3(this->x * n, this->y * n, this->z * n); }; vec3 vec3::operator*=(double n) { this->x *= n; this->y *= n; this->z *= n; return *this; }; vec3 vec3::operator/(const vec3 &b) { return vec3(this->x / b.x, this->y / b.y, this->z / b.z); }; vec3 vec3::operator/(double n) { return vec3(this->x / n, this->y / n, this->z / n); }; vec3 vec3::operator/=(double n) { this->x /= n; this->y /= n; this->z /= n; return *this; }; vec3 vec3::operator+=(vec3 const &b) { this->x += b.x; this->y += b.y; this->z += b.z; return *this; }; vec3 vec3::operator-=(vec3 const &b) { this->x -= b.x; this->y -= b.y; this->z -= b.z; return *this; }; std::ostream &operator<<(std::ostream &out, const vec3 &v) { out << "vec3(" << v.x << "," << v.y << "," << v.z << ")"; return out; } }// namespace WaveStrider
18.141732
69
0.486979
francisrstokes
b5abbb93815cdfa4e547b0261b130fec9c308955
1,747
hpp
C++
include/kiview_app.hpp
magicmoremagic/bengine-kiview
c96092c1f90d729069676b31d2b1c079fddb7053
[ "MIT" ]
null
null
null
include/kiview_app.hpp
magicmoremagic/bengine-kiview
c96092c1f90d729069676b31d2b1c079fddb7053
[ "MIT" ]
null
null
null
include/kiview_app.hpp
magicmoremagic/bengine-kiview
c96092c1f90d729069676b31d2b1c079fddb7053
[ "MIT" ]
null
null
null
#pragma once #ifndef KIVIEW_APP_HPP_ #define KIVIEW_APP_HPP_ #include "node.hpp" #include <be/core/lifecycle.hpp> #include <be/core/extents.hpp> #include <be/util/string_interner.hpp> #include <be/platform/lifecycle.hpp> #include <be/platform/glfw_window.hpp> #include <glm/vec2.hpp> #include <functional> #include <random> #include <set> /////////////////////////////////////////////////////////////////////////////// class KiViewApp final { public: KiViewApp(int argc, char** argv); int operator()(); private: void run_(); void load_(be::SV filename); void autoscale_(); void select_at_(glm::vec2 pos); void select_all_like_(const Node& mod); void process_command_(be::SV cmd); void set_segment_density_(be::SV params, void(*fp)(be::U32), be::SV label); void render_(); be::CoreInitLifecycle init_; be::CoreLifecycle core_; be::platform::PlatformLifecycle platform_; be::I8 status_ = 0; be::S filename_; be::util::StringInterner si_; Node root_; be::rect board_bounds_; be::U32 ground_net_ = 0; GLFWwindow* wnd_; glm::ivec2 viewport_ = glm::ivec2(640, 480); glm::vec2 center_; be::F32 scale_ = 1; bool enable_autoscale_ = true; bool enable_autocenter_ = true; glm::vec2 relative_cursor_; glm::vec2 cursor_; bool dragging_ = false; be::S info_; bool input_enabled_ = false; bool select_only_modules_ = false; bool select_only_nets_ = false; bool flipped_ = false; bool wireframe_ = false; bool see_thru_ = false; bool skip_copper_ = false; bool skip_silk_ = false; bool skip_zones_ = false; std::set<be::U32> skip_nets_; std::set<be::U32> highlight_nets_; std::set<const Node*> highlight_modules_; }; #endif
22.986842
79
0.660561
magicmoremagic
b5ae3051b8f8dbdf0bed97eedba7153afebcf8b4
6,726
cpp
C++
Source/Voxel/Private/VoxelTools/VoxelPaintMaterial.cpp
RobertBiehl/VoxelPlugin
49abc94261b3d93c9d8fe392a3731b6d09100941
[ "MIT" ]
null
null
null
Source/Voxel/Private/VoxelTools/VoxelPaintMaterial.cpp
RobertBiehl/VoxelPlugin
49abc94261b3d93c9d8fe392a3731b6d09100941
[ "MIT" ]
null
null
null
Source/Voxel/Private/VoxelTools/VoxelPaintMaterial.cpp
RobertBiehl/VoxelPlugin
49abc94261b3d93c9d8fe392a3731b6d09100941
[ "MIT" ]
null
null
null
// Copyright 2020 Phyronnaz #include "VoxelTools/VoxelPaintMaterial.h" #include "VoxelMathUtilities.h" FVoxelPaintMaterial FVoxelPaintMaterial::CreateRGB(FLinearColor Color, bool bPaintR, bool bPaintG, bool bPaintB, bool bPaintA) { FVoxelPaintMaterial Material; Material.Type = EVoxelPaintMaterialType::RGB; Material.Color.Color = Color; Material.Color.bPaintR = bPaintR; Material.Color.bPaintG = bPaintG; Material.Color.bPaintB = bPaintB; Material.Color.bPaintA = bPaintA; return Material; } FVoxelPaintMaterial FVoxelPaintMaterial::CreateFiveWayBlend(int32 Channel, float TargetValue, bool bPaintR, bool bPaintG, bool bPaintB, bool bPaintA) { ensure(0 <= Channel && Channel < 5); FVoxelPaintMaterial Material; Material.Type = EVoxelPaintMaterialType::FiveWayBlend; Material.FiveWayBlend.Channel = Channel; Material.FiveWayBlend.TargetValue = TargetValue; Material.FiveWayBlend.bPaintR = bPaintR; Material.FiveWayBlend.bPaintG = bPaintG; Material.FiveWayBlend.bPaintB = bPaintB; Material.FiveWayBlend.bPaintA = bPaintA; return Material; } FVoxelPaintMaterial FVoxelPaintMaterial::CreateSingleIndex(uint8 Index) { FVoxelPaintMaterial Material; Material.Type = EVoxelPaintMaterialType::SingleIndex; Material.Index = Index; return Material; } FVoxelPaintMaterial FVoxelPaintMaterial::CreateDoubleIndexSet(uint8 IndexA, uint8 IndexB, float Blend, bool bSetIndexA, bool bSetIndexB, bool bSetBlend) { FVoxelPaintMaterial Material; Material.Type = EVoxelPaintMaterialType::DoubleIndexSet; Material.DoubleIndexSet.IndexA = IndexA; Material.DoubleIndexSet.IndexB = IndexB; Material.DoubleIndexSet.Blend = Blend; Material.DoubleIndexSet.bSetIndexA = bSetIndexA; Material.DoubleIndexSet.bSetIndexB = bSetIndexB; Material.DoubleIndexSet.bSetBlend = bSetBlend; return Material; } FVoxelPaintMaterial FVoxelPaintMaterial::CreateDoubleIndexBlend(uint8 Index) { FVoxelPaintMaterial Material; Material.Type = EVoxelPaintMaterialType::DoubleIndexBlend; Material.Index = Index; return Material; } FVoxelPaintMaterial FVoxelPaintMaterial::CreateUV(uint8 Channel, FVector2D UV, bool bPaintU, bool bPaintV) { FVoxelPaintMaterial Material; Material.Type = EVoxelPaintMaterialType::UVs; Material.UV.Channel = Channel; Material.UV.UV = UV; Material.UV.bPaintU = bPaintU; Material.UV.bPaintV = bPaintV; return Material; } inline uint8 LerpUINT8_CustomRounding(uint8 A, uint8 B, float Amount) { const float LerpResult = FMath::Lerp<float>(A, B, Amount); // Do special rounding to not get stuck, eg Lerp(251, 255, 0.1) = 251 const int32 RoundedResult = Amount > 0 ? FMath::CeilToInt(LerpResult) : FMath::FloorToInt(LerpResult); return FVoxelUtilities::ClampToUINT8(RoundedResult); } void FVoxelPaintMaterial::ApplyToMaterial(FVoxelMaterial& Material, float Strength) const { switch (Type) { case EVoxelPaintMaterialType::RGB: { FColor IntColor = Color.Color.ToFColor(false); if (Strength < 0) { Strength = -Strength; IntColor = FColor(0, 0, 0, 0); } if (Color.bPaintR) { Material.SetR(LerpUINT8_CustomRounding(Material.GetR(), IntColor.R, Strength)); } if (Color.bPaintG) { Material.SetG(LerpUINT8_CustomRounding(Material.GetG(), IntColor.G, Strength)); } if (Color.bPaintB) { Material.SetB(LerpUINT8_CustomRounding(Material.GetB(), IntColor.B, Strength)); } if (Color.bPaintA) { Material.SetA(LerpUINT8_CustomRounding(Material.GetA(), IntColor.A, Strength)); } break; } case EVoxelPaintMaterialType::FiveWayBlend: { if (!ensure(0 <= FiveWayBlend.Channel && FiveWayBlend.Channel < 5)) { return; } const float TargetValue = Strength > 0 ? FiveWayBlend.TargetValue : 1.f - FiveWayBlend.TargetValue; Strength = FMath::Abs(Strength); const float R = FiveWayBlend.bPaintR ? Material.GetR_AsFloat() : 0.f; const float G = FiveWayBlend.bPaintG ? Material.GetG_AsFloat() : 0.f; const float B = FiveWayBlend.bPaintB ? Material.GetB_AsFloat() : 0.f; const float A = FiveWayBlend.bPaintA ? Material.GetA_AsFloat() : 0.f; TStaticArray<float, 5> Strengths = FVoxelUtilities::ConvertRGBAToFiveWayBlendStrengths(FVector4(R, G, B, A)); Strengths[FiveWayBlend.Channel] = FMath::Clamp(FMath::Lerp(Strengths[FiveWayBlend.Channel], TargetValue, Strength), 0.f, 1.f); const FVector4 NewColor = FVoxelUtilities::ConvertFiveWayBlendStrengthsToRGBA(Strengths); const auto CustomFloatToUINT8 = [](float NewValue, float OldValue) { // Round up if the new value is higher than the previous one, to avoid being stuck return FVoxelUtilities::ClampToUINT8(NewValue > OldValue ? FMath::CeilToInt(NewValue * 255.999f) : FMath::FloorToInt(NewValue * 255.999f)); }; if (FiveWayBlend.bPaintR) Material.SetR(CustomFloatToUINT8(NewColor.X, R)); if (FiveWayBlend.bPaintG) Material.SetG(CustomFloatToUINT8(NewColor.Y, G)); if (FiveWayBlend.bPaintB) Material.SetB(CustomFloatToUINT8(NewColor.Z, B)); if (FiveWayBlend.bPaintA) Material.SetA(CustomFloatToUINT8(NewColor.W, A)); break; } case EVoxelPaintMaterialType::SingleIndex: { Material.SetSingleIndex_Index(Index); break; } case EVoxelPaintMaterialType::DoubleIndexSet: { if (DoubleIndexSet.bSetIndexA) { Material.SetDoubleIndex_IndexA(DoubleIndexSet.IndexA); } if (DoubleIndexSet.bSetIndexB) { Material.SetDoubleIndex_IndexB(DoubleIndexSet.IndexB); } if (DoubleIndexSet.bSetBlend) { Material.SetDoubleIndex_Blend_AsFloat(DoubleIndexSet.Blend); } break; } case EVoxelPaintMaterialType::DoubleIndexBlend: { int32 SlotIndex; if (Index == Material.GetDoubleIndex_IndexA()) { SlotIndex = 0; } else if (Index == Material.GetDoubleIndex_IndexB()) { SlotIndex = 1; } else if (Material.GetDoubleIndex_Blend() == 255) { Material.SetDoubleIndex_IndexA(Index); SlotIndex = 0; } else if (Material.GetDoubleIndex_Blend() == 0) { Material.SetDoubleIndex_IndexB(Index); SlotIndex = 1; } else { // Fill as fast as we can SlotIndex = Material.GetDoubleIndex_Blend() < 128 ? 0 : 1; } Material.SetDoubleIndex_Blend(FVoxelUtilities::ClampToUINT8(Material.GetDoubleIndex_Blend() + 255 * Strength * (SlotIndex == 0 ? -1 : +1))); break; } case EVoxelPaintMaterialType::UVs: { FVector2D TargetUV = UV.UV; if (Strength < 0) { Strength = -Strength; TargetUV = FVector2D(1, 1) - TargetUV; } if (UV.bPaintU) { Material.SetU(UV.Channel, LerpUINT8_CustomRounding(Material.GetU(UV.Channel), FVoxelUtilities::FloatToUINT8(TargetUV.X), Strength)); } if (UV.bPaintV) { Material.SetV(UV.Channel, LerpUINT8_CustomRounding(Material.GetV(UV.Channel), FVoxelUtilities::FloatToUINT8(TargetUV.Y), Strength)); } break; } default: ensure(false); } }
30.572727
152
0.750223
RobertBiehl
b5af7516fe8f690e3e7b97c37ffedbd6badf574e
5,470
hpp
C++
framework/areg/base/private/BufferPosition.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
framework/areg/base/private/BufferPosition.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
framework/areg/base/private/BufferPosition.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
#pragma once /************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/base/private/BufferPosition.hpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform, buffer cursor position interface. * ************************************************************************/ /************************************************************************ * Includes ************************************************************************/ #include "areg/base/GEGlobal.h" #include "areg/base/IECursorPosition.hpp" /************************************************************************ * Dependencies ************************************************************************/ class IEByteBuffer; ////////////////////////////////////////////////////////////////////////// // BufferPosition class declaration ////////////////////////////////////////////////////////////////////////// /** * \brief This class is defining Buffer cursor position and contains * implementation of simple cursor move functionalities. * The object is used in buffer classes. **/ class AREG_API BufferPosition : public IECursorPosition { ////////////////////////////////////////////////////////////////////////// // Constructor / Destructor ////////////////////////////////////////////////////////////////////////// public: /** * \brief Sets the instance of byte buffer object * \param buffer Instance of Byte Buffer object **/ BufferPosition( IEByteBuffer & buffer ); /** * \brief Destructor **/ virtual ~BufferPosition( void ) = default; ////////////////////////////////////////////////////////////////////////// // Operations ////////////////////////////////////////////////////////////////////////// public: /** * \brief Invalidates current position, i.e. sets current position to IECursorPosition::INVALID_CURSOR_POSITION **/ inline void invalidate( void ); ////////////////////////////////////////////////////////////////////////// // Overrides ////////////////////////////////////////////////////////////////////////// public: /************************************************************************/ // IECursorPosition interface overrides /************************************************************************/ /** * \brief Returns the current position of pointer relative to begin in streaming data. * The valid position should not be equal to INVALID_CURSOR_POSITION. * Check current position validation before accessing data in streaming object. * \return Returns the current position of pointer relative to begin in streaming data. **/ virtual unsigned int getPosition( void ) const override; /** * \brief Sets the pointer position and returns current position in streaming data * The positive value of offset means move pointer forward. * The negative value of offset means move pointer back. * * \param offset The offset in bytes to move. Positive value means moving forward. Negative value means moving back. * \param startAt Specifies the starting position of pointer and should have one of values: * IECursorPosition::eCursorPosition::PositionBegin -- position from the beginning of data * IECursorPosition::eCursorPosition::PositionCurrent -- position from current pointer position * IECursorPosition::eCursorPosition::PositionEnd -- position from the end of file * * \return If succeeds, returns the current position of pointer in bytes or value IECursorPosition::INVALID_CURSOR_POSITION if fails. **/ virtual unsigned int setPosition( int offset, IECursorPosition::eCursorPosition startAt ) const override; ////////////////////////////////////////////////////////////////////////// // Member variables ////////////////////////////////////////////////////////////////////////// private: /** * \brief Reference to the Byte Buffer object **/ IEByteBuffer & mBuffer; /** * \brief Current position of Byte Buffer cursor. * Value IECursorPosition::INVALID_CURSOR_POSITION means invalid position. **/ mutable unsigned int mPosition; ////////////////////////////////////////////////////////////////////////// // Hidden / Disabled methods ////////////////////////////////////////////////////////////////////////// private: BufferPosition( void ) = delete; DECLARE_NOCOPY_NOMOVE( BufferPosition ); }; ////////////////////////////////////////////////////////////////////////// // BufferPosition class inline function implementation ////////////////////////////////////////////////////////////////////////// inline void BufferPosition::invalidate( void ) { mPosition = IECursorPosition::INVALID_CURSOR_POSITION; }
43.76
137
0.488665
Ali-Nasrolahi
b5b10da1dcf70fa8b265a750f775f5bc1cf2657f
28,137
cxx
C++
private/inet/mshtml/src/site/encode/encode.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/src/site/encode/encode.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/src/site/encode/encode.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+------------------------------------------------------------------------ // // Microsoft Forms // Copyright (C) Microsoft Corporation, 1992 - 1995. // // File: encode.cxx // // Contents: Support for HTML character set encoding // //------------------------------------------------------------------------- #include "headers.hxx" #ifndef X_ENCODE_HXX_ #define X_ENCODE_HXX_ #include "encode.hxx" #endif #ifndef X_INTL_HXX_ #define X_INTL_HXX_ #include "intl.hxx" #endif #ifdef WIN16 #define MB_PRECOMPOSED 0 #define MB_ERR_INVALID_CHARS 0 #endif #ifndef NO_MLANG extern IMultiLanguage *g_pMultiLanguage; extern IMultiLanguage2 *g_pMultiLanguage2; #endif DeclareTag(tagEncGeneral, "Enc", "Encode: General"); DeclareTag(tagEncAlwaysUseMlang, "Enc", "Encode: Always Use Mlang"); MtDefine(CEncodeReader, Utilities, "CEncodeReader") MtDefine(CEncodeReaderPbBuf, CEncodeReader, "CEncodeReader::_pbBuffer") MtDefine(CEncodeWriter, Utilities, "CEncodeWriter") MtDefine(CEncodeWriterPbBuf, CEncodeWriter, "CEncodeWriter::_pbBuffer") MtDefine(CEncodeWriterPchBuf, CEncodeWriter, "CEncodeWriter::_pchBuffer") MtDefine(CToUnicodeConverterPchBuf, Utilities, "CToUnicodeConverter") BOOL IsSameEncoding(CODEPAGE cp1, CODEPAGE cp2) { if (cp1 == cp2) return TRUE; // For now, all encodings are different except for windows-1252 and ISO-8859 if (cp1 == CP_1252 && cp2 == CP_ISO_8859_1 || cp1 == CP_ISO_8859_1 && cp2 == CP_1252) return TRUE; return FALSE; } CEncode::CEncode( size_t nBlockSize ) { _cp = CP_UNDEFINED; _nBlockSize = nBlockSize; _dwState = 0UL; } CEncode::~CEncode() { } CEncodeReader::CEncodeReader( CODEPAGE cp, size_t nBlockSize ) : CEncode( nBlockSize ) { _fCheckedForUnicode = FALSE; _fDiscardUtf7BOM = FALSE; _fDetectionFailed = FALSE; _cbScanStart = 0; _pfnWideCharFromMultiByte = NULL; _pchBuffer = NULL; _pbBuffer = NULL; // BUGBUG (cthrash) Create and move to Init method. SwitchCodePage( cp, NULL ); // sets _pfnWideCharFromMultiByte } CEncodeReader::~CEncodeReader() { if (_pchBuffer) { MemFree(_pchBuffer); _pchBuffer = NULL; } if (_pbBuffer) { MemFree(_pbBuffer); _pbBuffer = NULL; } } BOOL CEncodeReader::Exhausted() { // If we're left with a only few DBCS orphan characters at the end, // consider ourselves exhausted. The orphan characters will come // back to life in the next iteration of CEncodeReader::PrepareForRead(). // Note that if we're in autodetect mode, we can have _cbScanStart != 0. // What this means is that we've scanned that many bytes without being // able determine the encoding. We leave _pbBufferPtr as is because // that's where we need to start converting, but there's no point in // rescanning from there when we read more bytes. We start scanning from // _cbScanStart bytes in to _pbBufferPtr. return _pbBuffer && (_cbBuffer - ( _pbBufferPtr + _cbScanStart - _pbBuffer ) < ENCODE_DBCS_THRESHOLD); } struct ENCODINGREADFUNC { CODEPAGE cp; DECLARE_ENCODING_FUNCTION( (CEncodeReader::*pfnWCFromMB) ); }; BOOL CEncodeReader::ForceSwitchCodePage( CODEPAGE cp, BOOL *pfDifferentEncoding ) { BOOL fSwitched = FALSE; fSwitched = CEncodeReader::SwitchCodePage(cp, pfDifferentEncoding); // see if we wanted to switch but failed if (cp != _cp && !fSwitched) { // check to see if the codepage can be jit-in if (EnsureMultiLanguage() == S_OK && g_pMultiLanguage2 && g_pMultiLanguage2->IsCodePageInstallable(cp) == S_OK) { fSwitched = TRUE; if (pfDifferentEncoding) { *pfDifferentEncoding = !IsSameEncoding(cp, _cp); } _cp = cp; } } return fSwitched; } BOOL CEncodeReader::SwitchCodePage( CODEPAGE cp, BOOL *pfDifferentEncoding, BOOL fNeedRestart) { BOOL fSuccess = FALSE, fSwitched; #ifndef WIN16 static const struct ENCODINGREADFUNC aEncodingFuncs[] = { { CP_1252, &CEncodeReader::WideCharFromMultiByteGeneric }, #ifndef WINCE { CP_UTF_8, &CEncodeReader::WideCharFromUtf8 }, #endif // WINCE { CP_UCS_2, &CEncodeReader::WideCharFromUcs2 }, { CP_1250, &CEncodeReader::WideCharFromMultiByteGeneric }, { CP_1251, &CEncodeReader::WideCharFromMultiByteGeneric }, { CP_1253, &CEncodeReader::WideCharFromMultiByteGeneric }, { CP_1254, &CEncodeReader::WideCharFromMultiByteGeneric }, { CP_1257, &CEncodeReader::WideCharFromMultiByteGeneric }, }; const struct ENCODINGREADFUNC * p = aEncodingFuncs; const struct ENCODINGREADFUNC * pStop = aEncodingFuncs + ARRAY_SIZE( aEncodingFuncs ); // Nothing has changed, quickly bail. if (cp == _cp && _pfnWideCharFromMultiByte) goto Cleanup; Assert(cp != CP_ACP); #if DBG == 1 if (!IsTagEnabled(tagEncAlwaysUseMlang)) { #endif // See if we can handle this codepage natively. for (;p < pStop;p++) { if (cp == p->cp) break; } if (p < pStop) { // Check to see if we can go from the native codepage to Unicode. fSuccess = IsStraightToUnicodeCodePage(cp); if (!fSuccess) { UINT uCP = WindowsCodePageFromCodePage( cp ); CPINFO cpinfo; fSuccess = GetCPInfo( uCP, &cpinfo ); if (fSuccess) { _uMaxCharSize = cpinfo.MaxCharSize; } } } #if DBG == 1 } else { p = pStop; TraceTag((tagEncAlwaysUseMlang, "Forcing mlang use for codepage %d", cp)); } #endif #ifndef NO_MULTILANG // If we cannot handle this codepage natively, hand it over to mlang fSuccess = fSuccess || (EnsureMultiLanguage() == S_OK && g_pMultiLanguage->IsConvertible(cp, CP_UCS_2) == S_OK); #endif // !NO_MULTILANG if (fSuccess) { _pfnWideCharFromMultiByte = p == pStop ? &CEncodeReader::WideCharFromMultiByteMlang : p->pfnWCFromMB; } else #endif { // If we failed, do not switch code pages. TraceTag((tagEncGeneral, "Don't know how to read with codepage: %d", cp)); cp = _cp; } TraceTag((tagEncGeneral, "CEncodeReader switching to codepage: %d", cp)); Cleanup: if (!_pfnWideCharFromMultiByte) { // If we still haven't come up with an encoding use 1252 _pfnWideCharFromMultiByte = &CEncodeReader::WideCharFromMultiByteGeneric; cp = CP_1252; _uMaxCharSize = 1; } fSwitched = _cp != cp; if (pfDifferentEncoding) { *pfDifferentEncoding = !IsSameEncoding(cp, _cp); } _cp = cp; return fSwitched; } HRESULT CEncodeReader::PrepareToEncode() { HRESULT hr = S_OK; if (!_pbBuffer) { _cbBufferMax = BlockSize() + ENCODE_DBCS_THRESHOLD; _cbBuffer = _cbBufferMax; _pbBuffer = (unsigned char *)MemAlloc(Mt(CEncodeReaderPbBuf), _cbBufferMax ); if (!_pbBuffer) { hr = E_OUTOFMEMORY; goto Cleanup; } _pbBufferPtr = _pbBuffer + _cbBuffer; } // // _cbBuffer is the number of valid multibyte characters in our // multibyte buffer. It is non-zero when (a) you've split a multibyte // character at a read boundary, or (b) autodetection has not yet been // able to correctly identify the encoding. // _cbBuffer -= (INT)(_pbBufferPtr - _pbBuffer); memmove( _pbBuffer, _pbBufferPtr, _cbBuffer ); if (_cbBuffer > ENCODE_DBCS_THRESHOLD) { // Ensure that we have space to read an BlockSize() chunk. _cbBufferMax = _cbBuffer + BlockSize(); hr = THR( MemRealloc(Mt(CEncodeReaderPbBuf), (void **)&_pbBuffer , _cbBufferMax ) ); if (hr) goto Cleanup; } _pbBufferPtr = _pbBuffer + _cbBuffer; Cleanup: RRETURN(hr); } HRESULT CEncodeReader::WideCharFromMultiByte( BOOL fReadEof, int * pcch ) { HRESULT hr; #ifndef WIN16 // Do a quick check for Unicode files if (!_fCheckedForUnicode) { AssertSz(_pbBufferPtr == _pbBuffer, "We should be at the beginning of the buffer."); BOOL fCheckNoFurther = FALSE; for (;;) { if (_cbBuffer > 1) { WCHAR uSignature = *(WCHAR *)_pbBuffer; // BUGBUG (davidd) Support NON/NATIVE_UNICODE_CODEPAGE (sizeof(WCHAR) == 4/2) if (NATIVE_UNICODE_SIGNATURE == uSignature) { // (davidd) CP_UCS_2 does not currently distinguish between // 2/4 byte unicode so it is the right answer for native // unicode reading.. should be NATIVE_UNICODE_CODEPAGE SwitchCodePage( CP_UCS_2 ); _pbBufferPtr += sizeof(WCHAR); fCheckNoFurther = TRUE; break; } else if (NONNATIVE_UNICODE_SIGNATURE == uSignature) { SwitchCodePage( CP_UCS_2_BIGENDIAN ); _pbBufferPtr += sizeof(WCHAR); fCheckNoFurther = TRUE; break; } } if (_cbBuffer > 2) { if ( _pbBufferPtr[0] == 0xEF && _pbBufferPtr[1] == 0xBB && _pbBufferPtr[2] == 0xBF) { SwitchCodePage( CP_UTF_8 ); _pbBufferPtr += 3; fCheckNoFurther = TRUE; break; } } if (_cbBuffer > 3) { if ( _pbBufferPtr[0] == '+' && _pbBufferPtr[1] == '/' && _pbBufferPtr[2] == 'v' && ( _pbBufferPtr[3] == '8' || _pbBufferPtr[3] == '9' || _pbBufferPtr[3] == '+' || _pbBufferPtr[3] == '/')) { SwitchCodePage( CP_UTF_7 ); _fDiscardUtf7BOM = TRUE; } fCheckNoFurther = TRUE; } break; } _fCheckedForUnicode = fCheckNoFurther; } #endif //!WIN16 hr = THR( CALL_METHOD( this, _pfnWideCharFromMultiByte, ( fReadEof, pcch )) ); RRETURN(hr); } HRESULT CEncodeReader::WideCharFromMultiByteGeneric( BOOL fReadEof, int * pcch ) { size_t cb = _cbBuffer - (_pbBufferPtr - _pbBuffer); size_t cch = 0; HRESULT hr = S_OK; // If we have a multibyte character encoding, we are at risk of splitting // some characters at the read boundary. We must Make sure we have a // discrete number of characters first. Assert( _uMaxCharSize ); if (_uMaxCharSize > 1) { UINT uMax = _uMaxCharSize; cb++;// pre-increment do { cch = MultiByteToWideChar( _cp, MB_ERR_INVALID_CHARS | MB_PRECOMPOSED, (char *)_pbBufferPtr, --cb, NULL, 0 ); --uMax; } while (!cch && uMax && cb); } else { cch = cb; } if (cch == 0) { cch = MultiByteToWideChar( _cp, MB_PRECOMPOSED, (char*)_pbBufferPtr, cb, NULL, 0 ); } if (cch) { hr = THR(MakeRoomForChars(cch)); if (hr) goto Cleanup; cch = MultiByteToWideChar( _cp, MB_PRECOMPOSED, (char *)_pbBufferPtr, cb, _pchEnd, cch ); } *pcch = cch; _pbBufferPtr += cb; Cleanup: RRETURN(hr); } #ifndef NO_MLANG HRESULT CEncodeReader::WideCharFromMultiByteMlang( BOOL fReadEof, int * pcch ) { HRESULT hr; UINT cch = 0, cb = _cbBuffer - (_pbBufferPtr - _pbBuffer); DWORD dwState = _dwState; Assert(g_pMultiLanguage); hr = THR(g_pMultiLanguage->ConvertStringToUnicode( &dwState, _cp, (CHAR *)_pbBufferPtr, &cb, NULL, &cch )); if (FAILED(hr)) goto Cleanup; hr = THR(MakeRoomForChars(cch)); if (hr) goto Cleanup; hr = THR(g_pMultiLanguage->ConvertStringToUnicode( &_dwState, _cp, (CHAR *)_pbBufferPtr, &cb, (WCHAR *)_pchEnd, &cch )); if (FAILED(hr)) goto Cleanup; if (IsAutodetectCodePage(_cp)) { // Mlang stuffs the actual codepage into the hiword of the state CODEPAGE cpDetected = HIWORD(_dwState); // if cpDetected is zero, it implies that there was insufficient data // (typically all-ASCII data) to determine the charset. We will // continue to encode in autodetect mode in this case. If non-zero, // we'll switch the doc so that we can submit, etc., correctly. if (cpDetected) { // if we're getting codepage detecting result from // mlang, chances are that we have not processed // the stream at all because the system didn't have // the corresponding codepage installed. // we need to start over and get the codepage JIT-in. // BOOL fNeedRestart = _fDetectionFailed; if (_cp == CP_AUTO) { MIMECPINFO cpinfo; SlowMimeGetCodePageInfo(cpDetected, &cpinfo); if (!(cpinfo.dwFlags & MIMECONTF_VALID)) fNeedRestart = TRUE; } _fDetectionFailed = FALSE; SwitchCodePage(cpDetected, NULL, fNeedRestart); } else _fDetectionFailed = TRUE; } else if (_fDiscardUtf7BOM) { // Discard the BOM. Note we can't do this sooner because part of the // first character is mixed in with the BOM bytes. --cch; memmove( _pchEnd, _pchEnd + 1, cch * sizeof(wchar_t)); _fDiscardUtf7BOM = FALSE; } hr = S_OK; *pcch = cch; _pbBufferPtr += cb; Cleanup: RRETURN(hr); } #endif // !NO_MLANG HRESULT CEncodeReader::MakeRoomForChars( int cch ) { // call my superclass first! _pchEndLast = _pchEnd; _pbBufferPtrLast = _pbBufferPtr; RRETURN(S_OK); } //--------------------------------------------------------------------- CEncodeWriter::CEncodeWriter( CODEPAGE cp, size_t nBlockSize ) : CEncode( nBlockSize ) { _pfnMultiByteFromWideChar = NULL; _pchBuffer = NULL; _cchBuffer = _cchBufferMax = 0; _pbBuffer = NULL; _cbBuffer = _cbBufferMax = 0; _cDefaultChar = '?'; _fEntitizeUnknownChars = TRUE; // Choose something sane for _uiWinCodepage _uiWinCodepage = g_cpDefault; // BUGBUG (cthrash) Create and move to Init method. SwitchCodePage( cp ); // sets _pfnWideCharFromMultiByte } CEncodeWriter::~CEncodeWriter() { if (_pchBuffer) { MemFree(_pchBuffer); _pchBuffer = NULL; _cchBuffer = _cchBufferMax = 0; } if (_pbBuffer) { MemFree(_pbBuffer); _pbBuffer = NULL; _cbBuffer = _cbBufferMax = 0; } } BOOL CEncodeWriter::SwitchCodePage( CODEPAGE cp, BOOL *pfDifferentEncoding, BOOL fNeedRestart ) { BOOL fSuccess, fSwitched; // Nothing has changed, quickly bail. if (cp == _cp && _pfnMultiByteFromWideChar) goto Cleanup; Assert(cp != CP_ACP); switch (cp) { case CP_UCS_2: _pfnMultiByteFromWideChar = CEncodeWriter::UnicodeFromWideChar; fSuccess = TRUE; break; #ifndef WINCE case CP_UTF_8: _pfnMultiByteFromWideChar = CEncodeWriter::Utf8FromWideChar; fSuccess = TRUE; break; #endif // WINCE default: if (OK(EnsureMultiLanguage())) { _pfnMultiByteFromWideChar = g_pMultiLanguage2 #ifdef _MAC ? &CEncodeWriter::MultiByteFromWideCharMlang2 : &CEncodeWriter::MultiByteFromWideCharMlang; #else ? CEncodeWriter::MultiByteFromWideCharMlang2 : CEncodeWriter::MultiByteFromWideCharMlang; #endif fSuccess = S_OK == g_pMultiLanguage->IsConvertible(CP_UCS_2, cp); } else { CPINFO cpinfo; _pfnMultiByteFromWideChar = MultiByteFromWideCharGeneric; fSuccess = GetCPInfo( cp, &cpinfo ); } if (!fSuccess) { cp = g_cpDefault; // desperation } break; } TraceTag((tagEncGeneral, "CEncodeWriter switching to codepage: %d", cp)); Cleanup: fSwitched = _cp != cp; if (pfDifferentEncoding) { *pfDifferentEncoding = fSwitched; } _cp = cp; // Cache the windows codepage for the new cp _uiWinCodepage = WindowsCodePageFromCodePage( _cp ); if (fSwitched) { _dwState = 0; } return fSwitched; } HRESULT CEncodeWriter::PrepareToEncode() { HRESULT hr = S_OK; // // Allocate a unicode buffer the size of our block size, if we haven't already. // if (!_pchBuffer) { _cchBufferMax = BlockSize(); _cchBuffer = 0; _pchBuffer = (TCHAR*)MemAlloc(Mt(CEncodeWriterPchBuf), _cchBufferMax*sizeof(TCHAR) ); if (!_pchBuffer) { hr = E_OUTOFMEMORY; goto Cleanup; } } Cleanup: RRETURN(hr); } HRESULT CEncodeWriter::MultiByteFromWideChar( BOOL fReadEof, int * pcch ) { HRESULT hr; Assert( _pfnMultiByteFromWideChar != NULL ); hr = THR( CALL_METHOD( this, _pfnMultiByteFromWideChar, ( fReadEof, pcch ) )); RRETURN(hr); } HRESULT CEncodeWriter::MultiByteFromWideCharGeneric( BOOL fReadEof, int * pcch ) { HRESULT hr; BOOL fMapFailed = FALSE; UINT cch, cchTotal; cch = WideCharToMultiByte( _uiWinCodepage, 0, _pchBuffer, _cchBuffer, NULL, 0, NULL, &fMapFailed ); hr = THR(MakeRoomForChars(cch)); if( hr ) goto Cleanup; if( !fMapFailed || !_fEntitizeUnknownChars ) { cchTotal = WideCharToMultiByte( _uiWinCodepage, 0, _pchBuffer, _cchBuffer, (char*)_pbBuffer + _cbBuffer, _cbBufferMax - _cbBuffer, &_cDefaultChar, NULL ); _cbBuffer += cchTotal; } else { // N.B. (johnv) If we had to use a default character and are in entitize // mode, replace unknown characters with &#xxxxx; Need to go one // byte at a time. TCHAR * pch, *pchEnd; unsigned char* pb, *pbStart; UINT cchMin = cch; // we need at least this much room in the buffer cchTotal = 0; pchEnd = _pchBuffer + _cchBuffer; for( pch = _pchBuffer, pb = _pbBuffer + _cbBuffer; pch < pchEnd; ++pch ) { cch = WideCharToMultiByte( _uiWinCodepage, 0, pch, 1, (char*)pb, 1, NULL, &fMapFailed ); if( !fMapFailed ) { pb += cch; cchMin -= cch; Assert(cchMin >= 0); } else { // Fill in an entitity reference instead // Allocate eight more characters for the numeric entity hr = THR(MakeRoomForChars(8 + cchMin)); if( hr ) goto Cleanup; // _pbBuffer can change in MakeRoomForChars pb = pbStart = _pbBuffer + _cbBuffer; *pb++ = '&'; *pb++ = '#'; _ultoa( (unsigned long)*pch, (char*)pb, 10 ); pb += lstrlenA((const char*)pb); *pb++ = ';'; AssertSz(pb <= _pbBuffer + _cbBufferMax, "Entitizing overflow"); cch = pb - pbStart; } cchTotal += cch; _cbBuffer += cch; } } *pcch = cchTotal; Cleanup: RRETURN( hr ); } #ifndef NO_MLANG HRESULT CEncodeWriter::MultiByteFromWideCharMlang( BOOL fReadEof, int * pcch ) { HRESULT hr; UINT cb = 0, cch = _cchBuffer; DWORD dwState; _dwState |= _fEntitizeUnknownChars ? 0x00008000 : 0; dwState = _dwState; Assert(g_pMultiLanguage); hr = THR(g_pMultiLanguage->ConvertStringFromUnicode( &dwState, _cp, (WCHAR *)_pchBuffer, &cch, NULL, &cb)); if (FAILED(hr)) goto Cleanup; hr = THR(MakeRoomForChars(cb)); if( hr ) goto Cleanup; hr = THR(g_pMultiLanguage->ConvertStringFromUnicode( &_dwState, _cp, (WCHAR *)_pchBuffer, &cch, (CHAR *)_pbBuffer + _cbBuffer, &cb)); if (FAILED(hr)) goto Cleanup; // NB (cthrash) MLANG returns S_FALSE when everything converted fine, except // there were WC chars not native to the codepage _cp. These are entitized, // so there's no error. We don't want to propagate the S_FALSE up to the caller. hr = S_OK; *pcch = cb; _cbBuffer += cb; Cleanup: RRETURN( hr ); } HRESULT CEncodeWriter::MultiByteFromWideCharMlang2( BOOL fReadEof, int * pcch ) { HRESULT hr; UINT cb = 0, cch = _cchBuffer; DWORD dwArg = _fEntitizeUnknownChars ? (MLCONVCHARF_NAME_ENTITIZE | MLCONVCHARF_NCR_ENTITIZE) : 0; DWORD dwState = _dwState; Assert(g_pMultiLanguage2); hr = THR(g_pMultiLanguage2->ConvertStringFromUnicodeEx( &dwState, _cp, (WCHAR *)_pchBuffer, &cch, NULL, &cb, dwArg, NULL)); if (FAILED(hr)) goto Cleanup; hr = THR(MakeRoomForChars(cb)); if( hr ) goto Cleanup; hr = THR(g_pMultiLanguage2->ConvertStringFromUnicodeEx( &_dwState, _cp, (WCHAR *)_pchBuffer, &cch, (CHAR *)_pbBuffer + _cbBuffer, &cb, dwArg, NULL)); if (FAILED(hr)) goto Cleanup; // NB (cthrash) MLANG returns S_FALSE when everything converted fine, except // there were WC chars not native to the codepage _cp. These are entitized, // so there's no error. We don't want to propagate the S_FALSE up to the caller. hr = S_OK; *pcch = cb; _cbBuffer += cb; Cleanup: RRETURN( hr ); } #endif // !NO_MLANG HRESULT CEncodeWriter::MakeRoomForChars( int cch ) { HRESULT hr = S_OK; if (!_pbBuffer) { // round up to block size multiple >= cch+1 _cbBufferMax = (cch + _nBlockSize*2 - 1) & ~(_nBlockSize*2 - 1); _pbBuffer = (unsigned char*)MemAlloc(Mt(CEncodeWriterPbBuf), _cbBufferMax); if (!_pbBuffer) RRETURN( E_OUTOFMEMORY ); } else { int cchNeed = _cbBuffer + cch; // Reallocate the chunk if we need more memory for the extra characters. if (cchNeed >= _cbBufferMax) { // round up to WBUFF_SIZE*2 cchNeed = (cchNeed + _nBlockSize*2 - 1) & ~(_nBlockSize*2 - 1); hr = THR(MemRealloc(Mt(CEncodeWriterPbBuf), (void**)&_pbBuffer, cchNeed ) ); if (hr) goto Cleanup; _cbBufferMax = cchNeed; } } Cleanup: RRETURN( hr ); } //+---------------------------------------------------------------------------- // // Function: CToUnicodeConverter::Convert // // Synopsis: Convert a multibyte string to a Unicode string. // // Input: pbBuffer - multibyte string. // // cbBuffer - byte count of pbBuffer, or -1. // -1 implies that the string is nul-terminated. // // Returns: HRESULT - S_OK/E_OUTOFMEMORY // // *ppchBuffer - Unicode buffer. Allocated by this object. // Should be freed by caller. // // *pcch - Character count of string in *ppchBuffer // //----------------------------------------------------------------------------- HRESULT CToUnicodeConverter::Convert( const char *pbBuffer, // IN const int cbBuffer, // IN TCHAR ** ppchBuffer, // OUT int *pcch ) // OUT { HRESULT hr = S_OK; Assert(pbBuffer && cbBuffer >= -1); _fMakeRoomForNUL = (cbBuffer != -1); _pbBuffer = _pbBufferPtr = (unsigned char *)pbBuffer; _cbBuffer = _cbBufferMax = _fMakeRoomForNUL ? cbBuffer : lstrlenA(pbBuffer) + 1; hr = THR(WideCharFromMultiByte(TRUE, pcch)); if (FAILED(hr)) goto Cleanup; if (AutoDetectionFailed()) { SwitchCodePage( g_cpDefault ); hr = THR(WideCharFromMultiByte(TRUE, pcch)); if (FAILED(hr)) goto Cleanup; } *ppchBuffer = _pchBuffer; Cleanup: RRETURN(hr); } //+---------------------------------------------------------------------------- // // Function: CToUnicodeConverter::MakeRoomForChars // // Synopsis: Allocate a Unicode string buffer. // // Input: cch = Unicode character count // // Returns: HRESULT - S_OK/E_OUTOFMEMORY // //----------------------------------------------------------------------------- HRESULT CToUnicodeConverter::MakeRoomForChars( int cch ) { HRESULT hr = S_OK; Assert( !_pchBuffer || _cchBuffer >= cch ); if (!_pchBuffer) { if (_fMakeRoomForNUL) ++cch; _pchBuffer = (TCHAR *)MemAlloc(_mt, cch * sizeof(TCHAR)); if (!_pchBuffer) { hr = E_OUTOFMEMORY; goto Cleanup; } _cchBuffer = cch; _pchEnd = _pchBuffer; } IGNORE_HR(CEncodeReader::MakeRoomForChars(cch)); Cleanup: RRETURN(hr); } //+---------------------------------------------------------------------------- // // Function: CToUnicodeConverter dtor // // Synopsis: Caller should free both the multibyte and unicode string // buffers. To prevent the base class CEncodeReader from freeing // if for you, we NULL out the pointers. // //----------------------------------------------------------------------------- CToUnicodeConverter::~CToUnicodeConverter() { // Let the caller free this memory _pbBuffer = NULL; _pchBuffer = NULL; }
27.666667
105
0.528095
King0987654
b5b24ff891964693ff566f14edf602774f2c59e6
7,221
cpp
C++
test/duplicate-detection/t_dupd.cpp
izenecloud/idmlib
ec6afd44490170a70ef980afa6d21fba8c77ed9d
[ "Apache-2.0" ]
1
2017-11-14T06:37:25.000Z
2017-11-14T06:37:25.000Z
test/duplicate-detection/t_dupd.cpp
izenecloud/idmlib
ec6afd44490170a70ef980afa6d21fba8c77ed9d
[ "Apache-2.0" ]
null
null
null
test/duplicate-detection/t_dupd.cpp
izenecloud/idmlib
ec6afd44490170a70ef980afa6d21fba8c77ed9d
[ "Apache-2.0" ]
4
2015-09-06T05:59:29.000Z
2020-01-17T06:11:24.000Z
/// @file t_UString.cpp /// @brief A test unit for checking if all interfaces is /// available to use. /// @author Do Hyun Yun /// @date 2008-07-11 /// /// /// @brief Test all the interfaces in UString class. /// /// @details /// /// ==================================== [ Test Schemes ] ==================================== /// /// /// -# Tested basic part of UString according to the certain scenario with simple usage.\n /// \n /// -# Create three UString variables in different ways : Default Initializing, Initializing with another UString, and initialize with stl string class.\n\n /// -# Check attributes of some characters in UString using is_____Char() interface. With this interface, it is possible to recognize certain character is alphabet or number or something.\n\n /// -# Get attribute of certain characters in UString using charType() interface.\n\n /// -# Change some characters into upper alphabet or lower alphabet using toUpperChar() and toLowerChar(), and toLowerString() which changes all characters in UString into lower one.\n\n /// -# With given pattern string, Get the index of matched position by using find(). \n\n /// -# Create the sub-string using subString() with the index number which is the result of find().\n\n /// -# Assign string data in different ways using assign(), format() interfaces and "=" "+=" operators.\n\n /// -# Export UString data into stl string class according to the encoding type.\n\n /// -# Check size, buffer size, and its length. Clear string data and re-check its information including empty().\n\n /// \n /// -# Tested all the interfaces by using correct and incorrect test sets. //#include <util/log.h #include <idmlib/duplicate-detection/DupDetector.h> #include <idmlib/duplicate-detection/rand_proj_gen.h> #include <idmlib/duplicate-detection/rand_proj.h> #include <string> #include <time.h> #include <math.h> #include <boost/test/unit_test.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/operations.hpp> #include <sys/time.h> #include <fstream> #include <iostream> #include <vector> #include<stdio.h> BOOST_AUTO_TEST_SUITE( t_duplication_detection_suite ) using namespace std; using namespace sf1v5; using namespace boost::unit_test; #define CHECK(f)\ { \ if (!(f)){ BOOST_CHECK(false); std::cout<<"ERROR: "<<__FILE__<<": "<<__LINE__<<": "<<__FUNCTION__<<endl;} \ } #define ERROR_COUNT {if(error_count>0)cout<<endl<<error_count<<" errors ware found!";else{cout<<"\nNo error detected!\n"}} void rand_str(string& s) { s.clear(); size_t l = rand()%10; while (l == 0) l = rand()%10; for (size_t i=0; i<l; ++i) s += 'a' + i; } void rand_doc(std::vector<std::string>& strs, size_t max=100) { strs.clear(); size_t l = rand()%max; while (l == 0) l = rand()%max; for (size_t i=0; i<l; ++i) { string t; rand_str(t); strs.push_back(t); } } bool match(const std::string& path, const char* prefix) { uint32_t i = path.find_last_of('/'); i = path.substr(i+1).find(prefix); if (i != (uint32_t)-1) return true; return false; } void remove(const char* prefix) { boost::filesystem::path full_path( "./" ,boost::filesystem::native); if (boost::filesystem::exists(full_path)) { boost::filesystem::directory_iterator item_begin(full_path); boost::filesystem::directory_iterator item_end; for ( ;item_begin != item_end; item_begin ++ ) { if (match(item_begin ->path().native_file_string(), prefix)) boost::filesystem::remove(item_begin ->path().native_file_string()); //cout << item_begin ->path().native_file_string() << " \t[dir] " << endl; } } } BOOST_AUTO_TEST_CASE(RandProjGen_check ) { boost::filesystem::remove_all("./tt"); const size_t SIZE= 100000; vector<std::string> strs; vector<RandProj> projs; { RandProjGen pg("./tt", 384); struct timeval tvafter,tvpre; struct timezone tz; gettimeofday (&tvpre , &tz); for (uint32_t i=0; i<SIZE; ++i) { string str; rand_str(str); strs.push_back(str); projs.push_back(pg.get_random_projection(str)); } gettimeofday (&tvafter , &tz); cout<<"\nFP Generation: "<<((tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000)/1000.<<std::endl; pg.commit(); } { RandProjGen pg("./tt", 384); for (uint32_t i=0; i<SIZE; ++i) { if (!(pg.get_random_projection(strs[i]) == projs[i])) { std::cout<<pg.get_random_projection(strs[i])<<endl; cout<<projs[i]<<endl; CHECK(false); return; } } } } BOOST_AUTO_TEST_CASE(DupDetector_check ) { boost::filesystem::remove_all("./tt"); const size_t SIZE= 20;//1000000; const size_t TYPES_NUM= 4;//40000; vector<vector<string> > v; v.reserve(TYPES_NUM); for (size_t i = 0; i<TYPES_NUM; i++) { vector<string> vs; rand_doc(vs); v.push_back(vs); } cout<<"Data is ready!\n"; boost::filesystem::remove_all("./tt"); struct timeval tvafter,tvpre; struct timezone tz; { DupDetector dupd(1, "./tt"); gettimeofday (&tvpre , &tz); dupd.ready_for_insert(); for (size_t i=0; i<SIZE; i++) dupd.insertDocument(i, v[i%TYPES_NUM]); gettimeofday (&tvafter , &tz); cout<<"Adding docs is over! "<<((tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000)/60000.<<std::endl; // getchar(); gettimeofday (&tvpre , &tz); dupd.runDuplicateDetectionAnalysis(); gettimeofday (&tvafter , &tz); cout<<"Indexing docs is over! "<<((tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000)/60000.<<std::endl; //getchar(); } //test for incremental { DupDetector dupd(1, "./tt"); dupd.ready_for_insert(); for (size_t i=SIZE; i<SIZE+2*TYPES_NUM; i++) dupd.insertDocument(i, v[i%TYPES_NUM]); dupd.runDuplicateDetectionAnalysis(); } //test for updating { DupDetector dupd(1, "./tt"); dupd.ready_for_insert(); dupd.updateDocument(1, v[0%TYPES_NUM]); dupd.updateDocument(9, v[0%TYPES_NUM]); dupd.runDuplicateDetectionAnalysis(); dupd.ready_for_insert(); dupd.updateDocument(1, v[1%TYPES_NUM]); dupd.updateDocument(9, v[9%TYPES_NUM]); dupd.runDuplicateDetectionAnalysis(); dupd.ready_for_insert(); dupd.removeDocument(SIZE+1); dupd.removeDocument(SIZE+2); dupd.runDuplicateDetectionAnalysis(); dupd.ready_for_insert(); dupd.insertDocument(SIZE+1, v[(SIZE+1)%TYPES_NUM]); dupd.insertDocument(SIZE+2, v[(SIZE+2)%TYPES_NUM]); dupd.runDuplicateDetectionAnalysis(); } { DupDetector dupd(1, "./tt"); vector<unsigned int> ids; dupd.getDuplicatedDocIdList(1, ids); // for (uint32_t i=0; i<ids.size(); ++i) // cout<<ids[i]<<" "; // cout<<endl; for (size_t i=0; i<SIZE+TYPES_NUM; ++i) { //cout<<i<<" "<<i+TYPES_NUM<<std::endl; CHECK(dupd.isDuplicated(i, i+TYPES_NUM)); } } remove("tt"); remove("fp_"); } BOOST_AUTO_TEST_SUITE_END()
28.429134
195
0.632738
izenecloud
b5b71b190a4cef5b7f56354f9ea9add05abe2643
813
cpp
C++
acmicpcnet/1168.cpp
irresi/algostudy
489739d641d6e36bbedf86be6391d1db27456585
[ "MIT" ]
null
null
null
acmicpcnet/1168.cpp
irresi/algostudy
489739d641d6e36bbedf86be6391d1db27456585
[ "MIT" ]
null
null
null
acmicpcnet/1168.cpp
irresi/algostudy
489739d641d6e36bbedf86be6391d1db27456585
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; #define nm (ns+ne)/2 using ll = long long; using pii = pair<int, int>; typedef tree<int, null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; const int inf=1e9+3; #define all(x) (x).begin(),(x).end() #define sync() {ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);} //do not use int n,k; int t[400003]; ordered_set s; int main() { int tc,i,j,x,nx; //sync() cin>>n>>k; for(i=1;i<=n;i++)s.insert(i); x=n-1; cout<<'<'; for(;n>=1;n--){ nx=(x+k)%n; ordered_set::iterator t = s.find_by_order(nx); cout<<*t; if(n-1)cout<<", "; s.erase(t); x=(nx-1+n)%n; if(nx<x) x--; } cout<<'>'; return 0; }
23.228571
97
0.589176
irresi
b5b9ffe328fa54177619eeac4e282d054e4f7b20
362
hpp
C++
CookieEngine/include/Core/Window.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Core/Window.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Core/Window.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#ifndef __WINDOW_HPP__ #define __WINDOW_HPP__ #include <GLFW/glfw3.h> namespace Cookie { namespace Core { class Window { public: GLFWwindow* window = nullptr; int width = 0; int height = 0; private: void SetIcon(); public: /* CONSTRUCTORS/DESTRUCTORS */ Window(); ~Window(); }; } } #endif /*__WINDOW_HPP__*/
11.677419
34
0.61326
qbleuse
b5ba72ccdb8c6a52dbe567e85cbff678e63e1d4c
7,010
cpp
C++
OpenSim/Tools/Test/testVisualization.cpp
chrisdembia/opensim-debian
50c255ce850aab252f26ac73b67bd2b78dc65cfe
[ "Apache-2.0" ]
null
null
null
OpenSim/Tools/Test/testVisualization.cpp
chrisdembia/opensim-debian
50c255ce850aab252f26ac73b67bd2b78dc65cfe
[ "Apache-2.0" ]
null
null
null
OpenSim/Tools/Test/testVisualization.cpp
chrisdembia/opensim-debian
50c255ce850aab252f26ac73b67bd2b78dc65cfe
[ "Apache-2.0" ]
null
null
null
/* -------------------------------------------------------------------------- * * OpenSim: testVisualization.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2014 Stanford University and the Authors * * Author(s): Ayman Habib * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include <stdint.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Manager/Manager.h> #include <OpenSim/Common/LoadOpenSimLibrary.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; using namespace SimTK; void testVisModel(string fileName); // Implementation of DecorativeGeometryImplementation that prints the representation to // a StringStream for comparison class DecorativeGeometryImplementationText : public SimTK::DecorativeGeometryImplementation { void implementPointGeometry(const DecorativePoint& dp) override{ printout << "DecorativePoint:" << dp.getPoint() << printCommonProps(dp) << std::endl; }; void implementLineGeometry(const DecorativeLine& dl) override{ printout << "DecorativeLine:" << dl.getPoint1() << dl.getPoint2() << printCommonProps(dl) << std::endl; }; void implementBrickGeometry(const DecorativeBrick& db) override{ printout << "DecorativeBrick:" << db.getHalfLengths() << printCommonProps(db) << std::endl; }; void implementCylinderGeometry(const DecorativeCylinder& dc) override{ printout << "DecorativeCylinder:" << dc.getHalfHeight() << dc.getRadius() << printCommonProps(dc) << std::endl; }; void implementCircleGeometry(const DecorativeCircle& dc) override{ printout << "DecorativeCircle:" << dc.getRadius() << printCommonProps(dc) << std::endl; }; void implementSphereGeometry(const DecorativeSphere& dp) override{ printout << "DecorativeSphere:" << dp.getRadius() << printCommonProps(dp) << std::endl; }; void implementEllipsoidGeometry(const DecorativeEllipsoid& dp) override{ printout << "DecorativeEllipsoid:" << dp.getRadii() << printCommonProps(dp) << std::endl; }; void implementFrameGeometry(const DecorativeFrame& dp) override{ printout << "DecorativeFrame:" << dp.getAxisLength() << printCommonProps(dp) << std::endl; }; void implementTextGeometry(const DecorativeText& dp) override{ printout << "DecorativeText:" << dp.getText() << printCommonProps(dp) << std::endl; }; void implementMeshGeometry(const DecorativeMesh& dp) override{ printout << "DecorativeMesh:" << dp.getMesh().getNumFaces() << " " << dp.getMesh().getNumVertices() << printCommonProps(dp) << std::endl; }; void implementMeshFileGeometry(const DecorativeMeshFile& dp) override{ printout << "DecorativeMeshFile:" << dp.getMeshFile() << " " << printCommonProps(dp) << std::endl; }; void implementArrowGeometry(const DecorativeArrow& dp) override{ printout << "DecorativeArrow:" << dp.getStartPoint() << dp.getEndPoint() << dp.getTipLength() << printCommonProps(dp) << std::endl; }; void implementTorusGeometry(const DecorativeTorus& dp) override{ printout << "DecorativeTorus:" << dp.getTorusRadius() << dp.getTubeRadius() << printCommonProps(dp) << std::endl; }; void implementConeGeometry(const DecorativeCone& dp) override{ printout << "DecorativeTorus:" << dp.getBaseRadius() << dp.getDirection() << dp.getHeight() << printCommonProps(dp) << std::endl; }; public: std::string getAsString() { return printout.str(); } private: std::stringstream printout; std::string printCommonProps(const DecorativeGeometry& dg){ std::stringstream oneDGStream; oneDGStream << " bodyId:" << dg.getBodyId() << " color:" << dg.getColor() << " indexOnBody:" << dg.getIndexOnBody() << " Opacity:" << dg.getOpacity() << " Rep:" << dg.getRepresentation() << " Scale:" << dg.getScaleFactors() << " Transform:" << dg.getTransform(); return oneDGStream.str(); } }; int main() { try { LoadOpenSimLibrary("osimActuators"); testVisModel("BuiltinGeometry.osim"); } catch (const OpenSim::Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } void testVisModel(string fileName) { Model* model = new Model(fileName, true); SimTK::State& si = model->initSystem(); ModelDisplayHints mdh; SimTK::Array_<SimTK::DecorativeGeometry> geometryToDisplay; model->generateDecorations(true, mdh, si, geometryToDisplay); cout << geometryToDisplay.size() << endl; model->generateDecorations(false, mdh, si, geometryToDisplay); cout << geometryToDisplay.size() << endl; DecorativeGeometryImplementationText dgiText; for (unsigned i = 0; i < geometryToDisplay.size(); i++) geometryToDisplay[i].implementGeometry(dgiText); std::string baseName = fileName.substr(0, fileName.find_last_of('.')); std::ifstream t("vis_" + baseName + ".txt"); if (!t.good()) throw OpenSim::Exception("Could not open file."); std::stringstream buffer; buffer << t.rdbuf(); std::string fromFile = buffer.str(); std::string fromModel = dgiText.getAsString(); cout << "From Model " << endl << "=====" << endl; cout << fromModel << endl; cout << "From File " << endl << "=====" << endl; cout << fromFile << endl; int same = fromFile.compare(fromModel); delete model; ASSERT(same == 0, __FILE__, __LINE__, "Files do not match."); }
49.020979
145
0.609558
chrisdembia
b5c093af0b258796fb64c0c453a9611ed8458061
11,622
cpp
C++
Tools/PL3dsMaxSceneExport_2008/src/PLSceneLight.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Tools/PL3dsMaxSceneExport_2008/src/PLSceneLight.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Tools/PL3dsMaxSceneExport_2008/src/PLSceneLight.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: PLSceneLight.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLCore/Xml/Xml.h> #include <IGame/IGame.h> #include "PL3dsMaxSceneExport/PLLog.h" #include "PL3dsMaxSceneExport/PLScene.h" #include "PL3dsMaxSceneExport/PLSceneTexture.h" #include "PL3dsMaxSceneExport/PLSceneLight.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ PLSceneLight::PLSceneLight(PLSceneContainer &cContainer, IGameNode &cIGameNode, const String &sName) : PLSceneNode(&cContainer, &cIGameNode, sName, TypeLight, "") { } /** * @brief * Destructor */ PLSceneLight::~PLSceneLight() { } //[-------------------------------------------------------] //[ Private virtual PLSceneNode functions ] //[-------------------------------------------------------] void PLSceneLight::WriteToFile(XmlElement &cSceneElement, const String &sApplicationDrive, const String &sApplicationDir) { bool bError = true; // Error by default // Get the IGame light object of the given IGame node IGameObject *pIGameObject = GetIGameNode()->GetIGameObject(); if (pIGameObject) { // One thing... if the light is for example a 'VRay'-light 'GetLightType()' will crash! // So we have to do this quite complicated... Object *pMaxObject = pIGameObject->GetMaxObject(); if (pMaxObject && pMaxObject->SuperClassID() == LIGHT_CLASS_ID && (pMaxObject->CanConvertToType(Class_ID(OMNI_LIGHT_CLASS_ID, 0)) || pMaxObject->CanConvertToType(Class_ID(SPOT_LIGHT_CLASS_ID, 0)) || pMaxObject->CanConvertToType(Class_ID(DIR_LIGHT_CLASS_ID, 0)) || pMaxObject->CanConvertToType(Class_ID(FSPOT_LIGHT_CLASS_ID, 0)) || pMaxObject->CanConvertToType(Class_ID(TDIR_LIGHT_CLASS_ID, 0)))) { // Check the type of the IGame object IGameLight &cIGameLight = *static_cast<IGameLight*>(pIGameObject); if (pIGameObject->GetIGameType() == IGameObject::IGAME_LIGHT && cIGameLight.GetLightType() != IGameLight::IGAME_UNKNOWN) { // Initialize the data of the IGame object - because of the 'clever' default implementation // that returns 'false' if nothing was to do, we can't call this function and have to be // 'inconsistent'... // if (cIGameLight.InitializeData()) { // Is the light not hidden and is rendered but should still not be used? if (!GetIGameNode()->IsNodeHidden() && GetIGameNode()->GetMaxNode()->Renderable() && !cIGameLight.IsLightOn()) AddFlag("Invisible"); // Get a GenLight from the node GenLight &cMaxLight = *static_cast<GenLight*>(pMaxObject); // Cast shadows? if (cIGameLight.CastShadows()) { // Shadow active? (jap, another state we have to check :) if (cMaxLight.GetShadow()) { // We only accept shadow mapping if (cMaxLight.GetShadowMethod() == LIGHTSHADOW_MAPPED && !cMaxLight.GetShadowType()) AddFlag("CastShadow|ReceiveShadow"); else g_pLog->LogFLine(PLLog::Hint, "Light node '%s' shadow casting is deactivated because only shadow mapping is supported.", GetIGameNode()->GetName()); } } // Get the projector map... I found no way to do this using IGame... BitmapTex *pBitmapTex = nullptr; Texmap *pMap = cMaxLight.GetProjector() ? cMaxLight.GetProjMap() : nullptr; if (pMap && pMap->ClassID() == Class_ID(BMTEX_CLASS_ID, 0x00)) pBitmapTex = static_cast<BitmapTex*>(pMap); // Add scene node XmlElement *pNodeElement = new XmlElement("Node"); // Spot light String sClassName; bool bDirectionalLight = false; bool bSpotLight = (cIGameLight.GetLightType() == IGameLight::IGAME_TSPOT || cIGameLight.GetLightType() == IGameLight::IGAME_FSPOT); if (bSpotLight) { // Is this a projective spot light? if (pBitmapTex) { sClassName = "PLScene::SNProjectiveSpotLight"; // Light shape if (cIGameLight.GetSpotLightShape() != RECT_LIGHT) { // [HACK] Just a 'dummy'-flag because if no flags are set the default setting // is used which is 'NoCone'... AddFlag("Cone"); } } else { sClassName = "PLScene::SNSpotLight"; // Light shape if (cIGameLight.GetSpotLightShape() == RECT_LIGHT) AddFlag("NoCone"); } // Directional light } else if (cIGameLight.GetLightType() == IGameLight::IGAME_DIR || cIGameLight.GetLightType() == IGameLight::IGAME_TDIR) { sClassName = "PLScene::SNDirectionalLight"; bDirectionalLight = true; // Omni directional light } else { sClassName = pBitmapTex ? "PLScene::SNProjectivePointLight" : "PLScene::SNPointLight"; } // Class name if (GetClassName().GetLength()) sClassName = GetClassName(); // Overwrite the default PixelLight class name pNodeElement->SetAttribute("Class", sClassName); // Name pNodeElement->SetAttribute("Name", GetName()); // Write position, rotation, scale, bounding box and flags WriteToFilePosRotScaleBoxFlags(*pNodeElement); // Color IGameProperty *pIGameProperty = cIGameLight.GetLightColor(); if (pIGameProperty) { // Get the light multiplier data float fMultiplier = 1.0f; IGameProperty *pIGameMultiplierProperty = cIGameLight.GetLightMultiplier(); if (pIGameMultiplierProperty) pIGameMultiplierProperty->GetPropertyValue(fMultiplier); // Get light color Point3 vColor; if (pIGameProperty->GetPropertyValue(vColor)) { vColor *= fMultiplier; if (vColor.x != 1.0f || vColor.y != 1.0f || vColor.z != 1.0f) pNodeElement->SetAttribute("Color", String::Format("%f %f %f", vColor.x, vColor.y, vColor.z)); } } // Directional light? if (bDirectionalLight) { // No special parameters } else { // Range ('far attenuation - end') pIGameProperty = cIGameLight.GetLightAttenEnd(); if (pIGameProperty) { float fRange; if (pIGameProperty->GetPropertyValue(fRange)) PLTools::XmlElementSetAttributeWithDefault(*pNodeElement, "Range", fRange, 1.0f); } // Special spot light settings if (bSpotLight) { // OuterAngle pIGameProperty = cIGameLight.GetLightFallOff(); if (pIGameProperty) { float fFallOff; if (pIGameProperty->GetPropertyValue(fFallOff)) PLTools::XmlElementSetAttributeWithDefault(*pNodeElement, "OuterAngle", fFallOff, 45.0f); } // InnerAngle pIGameProperty = cIGameLight.GetLightHotSpot(); if (pIGameProperty) { float fHotSpot; if (pIGameProperty->GetPropertyValue(fHotSpot)) PLTools::XmlElementSetAttributeWithDefault(*pNodeElement, "InnerAngle", fHotSpot, 35.0f); } // ZNear ('near attenuation - start') pIGameProperty = cIGameLight.GetLightAttenStart(); if (pIGameProperty) { float fAttenStart; if (pIGameProperty->GetPropertyValue(fAttenStart) && fAttenStart != 0.1f) { PLTools::XmlElementSetAttributeWithDefault(*pNodeElement, "ZNear", fAttenStart, 0.1f); // 'Normally' the near plane should never ever be <=0! (crazy z-fighting!) if (fAttenStart <= 1.0000000e-006 && GetIGameNode()) g_pLog->LogFLine(PLLog::Warning, "Light (3ds Max node '%s') 'near attenuation' (= near plane) '%f' (really small number) but recommended is '>1.0000000e-006'!", GetIGameNode()->GetName(), fAttenStart); } } // Aspect (only used for rectangle light shape!) if (cIGameLight.GetSpotLightShape() == RECT_LIGHT) { pIGameProperty = cIGameLight.GetLightAspectRatio(); if (pIGameProperty) { float fAspectRatio; if (pIGameProperty->GetPropertyValue(fAspectRatio)) PLTools::XmlElementSetAttributeWithDefault(*pNodeElement, "Aspect", fAspectRatio, 1.0f); } } } } // Projected material if (pBitmapTex) { // Copy the texture PLSceneTexture *pTexture = GetScene().CopyTexture(pBitmapTex->GetMapName()); if (pTexture) { // Add as light variable pNodeElement->SetAttribute("ProjectedMaterial", pTexture->GetName()); } } // Write flexible variables WriteVariables(*pNodeElement); // Write modifiers WriteModifiers(*pNodeElement, sApplicationDrive, sApplicationDir); // Link node element cSceneElement.LinkEndChild(*pNodeElement); // No error occurred bError = false; // } } else { g_pLog->LogFLine(PLLog::Error, "%s: IGame object is no known light object!", GetIGameNode()->GetName()); } } else { g_pLog->LogFLine(PLLog::Error, "%s: IGame object is no known light object!", GetIGameNode()->GetName()); } // Release the IGame object GetIGameNode()->ReleaseIGameObject(); } else { g_pLog->LogFLine(PLLog::Error, "%s: IGame node has no IGame object!", GetIGameNode()->GetName()); } // Was there an error? If yes we replace this light node through an 'unknown' node. if (bError) { // Update the statistics GetContainer()->m_sStatistics.nNumOfLights--; GetContainer()->m_sStatistics.nNumOfUnknown++; GetScene().m_sSceneStatistics.nNumOfLights--; GetScene().m_sSceneStatistics.nNumOfUnknown++; // Add scene node XmlElement *pNodeElement = new XmlElement("Node"); pNodeElement->SetAttribute("Class", GetClassName().GetLength() ? GetClassName() : "PLScene::SNUnknown"); pNodeElement->SetAttribute("Name", GetName()); // Write position, rotation, scale, bounding box and flags WriteToFilePosRotScaleBoxFlags(*pNodeElement); // Write flexible variables WriteVariables(*pNodeElement); // Write modifiers WriteModifiers(*pNodeElement, sApplicationDrive, sApplicationDir); // Link node element cSceneElement.LinkEndChild(*pNodeElement); } }
39.263514
211
0.635519
ktotheoz
b5c0d5f1fcc0a79e64cadcbcd1db641dca7fd043
3,462
cpp
C++
Engine/Source/Runtime/Engine/Private/OnlineReplStructs.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Private/OnlineReplStructs.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Engine/Private/OnlineReplStructs.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= OnlineReplStructs.cpp: Unreal networking serialization helpers =============================================================================*/ #include "EnginePrivate.h" #include "OnlineSubsystemUtils.h" FArchive& operator<<( FArchive& Ar, FUniqueNetIdRepl& UniqueNetId) { int32 Size = UniqueNetId.IsValid() ? UniqueNetId->GetSize() : 0; Ar << Size; if (Size > 0) { if (Ar.IsSaving()) { check(UniqueNetId.IsValid()); FString Contents = UniqueNetId->ToString(); Ar << Contents; } else if (Ar.IsLoading()) { FString Contents; Ar << Contents; // that takes care about possible overflow // Don't need to distinguish OSS interfaces here with world because we just want the create function below IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(); if (IdentityInt.IsValid()) { TSharedPtr<const FUniqueNetId> UniqueNetIdPtr = IdentityInt->CreateUniquePlayerId(Contents); UniqueNetId.SetUniqueNetId(UniqueNetIdPtr); } } } return Ar; } bool FUniqueNetIdRepl::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess) { Ar << *this; bOutSuccess = true; return true; } bool FUniqueNetIdRepl::Serialize(FArchive& Ar) { Ar << *this; return true; } bool FUniqueNetIdRepl::ExportTextItem(FString& ValueStr, FUniqueNetIdRepl const& DefaultValue, UObject* Parent, int32 PortFlags, UObject* ExportRootScope) const { ValueStr += UniqueNetId.IsValid() ? UniqueNetId->ToString() : TEXT("INVALID"); return true; } void TestUniqueIdRepl(UWorld* InWorld) { bool bSuccess = true; IOnlineIdentityPtr IdentityPtr = Online::GetIdentityInterface(InWorld); if (IdentityPtr.IsValid()) { TSharedPtr<const FUniqueNetId> UserId = IdentityPtr->GetUniquePlayerId(0); FUniqueNetIdRepl EmptyIdIn; if (EmptyIdIn.IsValid()) { UE_LOG(LogNet, Warning, TEXT("EmptyId is valid."), *EmptyIdIn->ToString()); bSuccess = false; } FUniqueNetIdRepl ValidIdIn(UserId); if (!ValidIdIn.IsValid() || UserId != ValidIdIn.GetUniqueNetId()) { UE_LOG(LogNet, Warning, TEXT("UserId input %s != UserId output %s"), *UserId->ToString(), *ValidIdIn->ToString()); bSuccess = false; } if (bSuccess) { TArray<uint8> Buffer; for (int32 i=0; i<2; i++) { Buffer.Empty(); FMemoryWriter TestWriteUniqueId(Buffer); if (i == 0) { // Normal serialize TestWriteUniqueId << EmptyIdIn; TestWriteUniqueId << ValidIdIn; } else { // Net serialize bool bOutSuccess = false; EmptyIdIn.NetSerialize(TestWriteUniqueId, NULL, bOutSuccess); ValidIdIn.NetSerialize(TestWriteUniqueId, NULL, bOutSuccess); } FMemoryReader TestReadUniqueId(Buffer); FUniqueNetIdRepl EmptyIdOut; TestReadUniqueId << EmptyIdOut; if (EmptyIdOut.GetUniqueNetId().IsValid()) { UE_LOG(LogNet, Warning, TEXT("EmptyId %s should have been invalid"), *EmptyIdOut->ToString()); bSuccess = false; } FUniqueNetIdRepl ValidIdOut; TestReadUniqueId << ValidIdOut; if (*UserId != *ValidIdOut.GetUniqueNetId()) { UE_LOG(LogNet, Warning, TEXT("UserId input %s != UserId output %s"), *ValidIdIn->ToString(), *ValidIdOut->ToString()); bSuccess = false; } } } } if (!bSuccess) { UE_LOG(LogNet, Warning, TEXT("TestUniqueIdRepl test failure!")); } }
25.644444
160
0.660312
PopCap
b5c1a04fa20d4b7706e77c28818aa6547039663b
3,568
cpp
C++
src/CRoiObjectDetection.cpp
CountrySideEngineer/ObjectDetection
4438dd42e913ba03c1e995a82bb34089aafe28e7
[ "MIT" ]
null
null
null
src/CRoiObjectDetection.cpp
CountrySideEngineer/ObjectDetection
4438dd42e913ba03c1e995a82bb34089aafe28e7
[ "MIT" ]
null
null
null
src/CRoiObjectDetection.cpp
CountrySideEngineer/ObjectDetection
4438dd42e913ba03c1e995a82bb34089aafe28e7
[ "MIT" ]
null
null
null
/* * CRoiObjectDetection.cpp * * Created on: 2018/06/15 * Author: orca2 */ #include <iostream> #include <vector> #include <unistd.h> #include <time.h> #include <sys/time.h> #include "CRoiObjectDetection.h" #include "opencv/cv.hpp" #include "opencv2/core.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgcodecs.hpp" using namespace std; using namespace cv; #ifdef _DEBUG #define DETECT_DEBUG_IMAGE_ON (1) #define CALC_DETECT_TIME (1) #else #define DETECT_DEBUG_IMAGE_ON (0) #define CALC_DETECT_TIME (1) #endif /** * Constructor with default argument. * * @param[in] FilterSize Size of filter used in object detection. * @param[in] Thresh Threshold value used to change image into binary format. * @param[in] MaxValue Max value used to change image into binary format. */ CRoiObjectDetection::CRoiObjectDetection(int FilterSize, int Thresh, int MaxValue) : CDilateErodeObjectDetection(FilterSize, Thresh, MaxValue) {} CRoiObjectDetection::~CRoiObjectDetection() { #if DETECT_DEBUG_IMAGE_ON == 1 destroyWindow(String("Lower right side")); destroyWindow(String("Lower left side")); #endif } /** * Draw contours into argument TargetImage. * * @param[in,out] TargetImage Pointer to image input and detected image will * be drawn. * @return Returns pointer to image */ Mat* CRoiObjectDetection::Find(Mat* TargetImage) { Mat BinImage; Mat* BinImageRet = NULL; BinImageRet = this->Convert2Bin(TargetImage, (Mat*)&BinImage); if (BinImageRet != (&BinImage)) { cerr << "Image output err!" << endl; return NULL; } vector< vector<Point> > Contours; findContours(BinImage, Contours, CV_RETR_LIST, CHAIN_APPROX_SIMPLE); for (unsigned int index = 0; index < Contours.size(); index++) { drawContours((Mat&)(*TargetImage), Contours, index, Scalar(0, 0, 255), 5); } return TargetImage; } /** * Detect and mark traffic object. * The area of handling image is limited. * * @paran[in] SrcImage Source image to scan. * @param[out] DstImage Image detected object will be drawn. * @return Returns pointer to image the objected detected is drawn if the sequence * has finished successfully, otherwise returns NULL. */ Mat* CRoiObjectDetection::Find(const Mat* SrcImage, const Mat* DstImage) { #if CALC_DETECT_TIME == 1 timeval StartTime; gettimeofday(&StartTime, NULL); #endif //CALC_DETECT_TIME == 1 Mat* BinImageRet = NULL; SrcImage->copyTo(*DstImage); //Lower right side. int HeightHalf = SrcImage->rows / 2; int WidthHalf = SrcImage->cols / 2; Rect RoiLowRight(WidthHalf, HeightHalf, WidthHalf, HeightHalf); Mat DstImageRoiLowRight = (Mat)(*DstImage)(RoiLowRight); BinImageRet = this->Find((Mat*)(&DstImageRoiLowRight)); if (NULL == BinImageRet) { return NULL; } //Lower left side. Rect RoiLowLeft(0, HeightHalf, WidthHalf, HeightHalf); Mat DstImageRoiLowLeft = (Mat)(*DstImage)(RoiLowLeft); Mat RotateImage; cv::flip(DstImageRoiLowLeft, RotateImage, 1); BinImageRet = this->Find((Mat*)(&RotateImage)); if (NULL == BinImageRet) { return NULL; } cv::flip(RotateImage, DstImageRoiLowLeft, 1); #if CALC_DETECT_TIME == 1 timeval EndTime; gettimeofday(&EndTime, NULL); long PassedTime = ((EndTime.tv_sec * 1000) + (EndTime.tv_usec / 1000)) - ((StartTime.tv_sec * 1000) + (StartTime.tv_usec / 1000)); cout << "Passed time = " << PassedTime << " millisecond" << endl; #endif //CALC_DETECT_TIME == 1 #if DETECT_DEBUG_IMAGE_ON == 1 imshow(String("Lower right side"), DstImageRoiLowRight); imshow(String("Lower left side"), DstImageRoiLowLeft); #endif return (Mat*)DstImage; }
27.446154
82
0.720572
CountrySideEngineer
b5c3c6eb98df16a20889b79a7145a4eb120bac3c
1,739
cpp
C++
Greedy/number-of-orders-in-the-backlog.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Medium/number-of-orders-in-the-backlog.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Medium/number-of-orders-in-the-backlog.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: int getNumberOfBacklogOrders(vector<vector<int>>& orders) { int count=0; map<int,int,greater<int>> buy; map<int,int> sell; for(int i=0;i<orders.size();i++) { if(orders[i][2]) //sell { while(orders[i][1]>0&&buy.size()>0&&begin(buy)->first>=orders[i][0]) { if(orders[i][1]>=begin(buy)->second) { orders[i][1]-=begin(buy)->second; buy.erase(begin(buy)->first); } else { buy[begin(buy)->first]-=orders[i][1]; orders[i][1]=0; } } if(orders[i][1]>0) sell[orders[i][0]]+=orders[i][1]; } else //buy { while(orders[i][1]>0&&sell.size()>0&&begin(sell)->first<=orders[i][0]) { if(orders[i][1]>=begin(sell)->second) { orders[i][1]-=begin(sell)->second; sell.erase(begin(sell)->first); } else { sell[begin(sell)->first]-=orders[i][1]; orders[i][1]=0; } } if(orders[i][1]>0) buy[orders[i][0]]+=orders[i][1]; } } for(auto e: buy) count=(count+e.second)%1000000007; for(auto e: sell) count=(count+e.second)%1000000007; return count; } };
32.811321
86
0.346751
PrakharPipersania
b5c72289b5d91a386f34a44289a4689873d000f1
2,520
cpp
C++
test/src/test_storage.cpp
steinwurf/storage
80b445cdd56b6a228c6d6ab294dfad5af30a7694
[ "BSD-3-Clause" ]
2
2017-12-09T20:36:05.000Z
2021-02-09T12:37:52.000Z
test/src/test_storage.cpp
steinwurf/storage
80b445cdd56b6a228c6d6ab294dfad5af30a7694
[ "BSD-3-Clause" ]
2
2016-05-23T12:28:29.000Z
2018-01-03T13:08:03.000Z
test/src/test_storage.cpp
steinwurf/storage
80b445cdd56b6a228c6d6ab294dfad5af30a7694
[ "BSD-3-Clause" ]
1
2017-12-09T20:35:20.000Z
2017-12-09T20:35:20.000Z
// Copyright (c) Steinwurf ApS 2016. // All Rights Reserved // // Distributed under the "BSD License". See the accompanying LICENSE.rst file. #include <storage/storage.hpp> #include <storage/cast.hpp> #include <cstdint> #include <vector> #include <iterator> #include <gtest/gtest.h> template<class PodType> static void test_vector_helper(uint64_t vector_size) { std::vector<PodType> v(vector_size); storage::const_storage cs = storage::storage(v); EXPECT_EQ(cs.size(), vector_size * sizeof(PodType)); EXPECT_EQ(storage::cast<PodType>(cs), &v[0]); storage::mutable_storage ms = storage::storage(v); EXPECT_EQ(ms.size(), vector_size * sizeof(PodType)); EXPECT_EQ(storage::cast<PodType>(ms), &v[0]); // Check const const std::vector<PodType>& v_ref = v; storage::const_storage const_cs = storage::storage(v_ref); EXPECT_EQ(const_cs.size(), vector_size * sizeof(PodType)); EXPECT_EQ(storage::cast<PodType>(const_cs), &v_ref[0]); } TEST(test_storage, test_vector_helper) { uint64_t size = rand() % 100000; test_vector_helper<char>(size); test_vector_helper<short>(size); test_vector_helper<int>(size); test_vector_helper<uint8_t>(size); test_vector_helper<uint16_t>(size); test_vector_helper<uint32_t>(size); test_vector_helper<uint64_t>(size); } template<class PodType> static void test_buffer_helper(uint64_t buffer_size) { std::vector<PodType> buffer(buffer_size); PodType* data = buffer.data(); uint64_t size = buffer.size() * sizeof(PodType); storage::const_storage const_storage = storage::storage(data, size); EXPECT_EQ(const_storage.size(), size); EXPECT_EQ(storage::cast<PodType>(const_storage), &data[0]); storage::mutable_storage mutable_storage = storage::storage(data, size); EXPECT_EQ(mutable_storage.size(), size); EXPECT_EQ(storage::cast<PodType>(mutable_storage), &data[0]); // Check const const PodType* const_data = data; storage::const_storage const_storage2 = storage::storage(const_data, size); EXPECT_EQ(const_storage2.size(), size); EXPECT_EQ(storage::cast<PodType>(const_storage2), &const_data[0]); } TEST(test_storage, test_buffer_helper) { uint64_t size = rand() % 100000; test_buffer_helper<char>(size); test_buffer_helper<short>(size); test_buffer_helper<int>(size); test_buffer_helper<uint8_t>(size); test_buffer_helper<uint16_t>(size); test_buffer_helper<uint32_t>(size); test_buffer_helper<uint64_t>(size); }
30.361446
79
0.714683
steinwurf