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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f514034e9d0344acd0c573e8b3bc1addaaba1d8
| 1,308
|
cpp
|
C++
|
graphs/cycle_detection_using_dsu.cpp
|
Ashish2030/C-_Language_Code
|
50b143124690249e5dbd4eaaddfb8a3dadf48f1f
|
[
"MIT"
] | 7
|
2021-05-05T00:14:39.000Z
|
2021-05-16T07:10:06.000Z
|
graphs/cycle_detection_using_dsu.cpp
|
Ashish2030/C-_Language_Code
|
50b143124690249e5dbd4eaaddfb8a3dadf48f1f
|
[
"MIT"
] | null | null | null |
graphs/cycle_detection_using_dsu.cpp
|
Ashish2030/C-_Language_Code
|
50b143124690249e5dbd4eaaddfb8a3dadf48f1f
|
[
"MIT"
] | 4
|
2021-05-17T07:54:57.000Z
|
2021-06-29T15:36:54.000Z
|
#include<iostream>
#include<map>
#include<list>
#include<cstring>
#include<unordered_map>
#include<queue>
#include<vector>
using namespace std;
class dsu{
vector<int>part;
public:
dsu(int n){
part.resize(n);
for(int i=0;i<n;i++){
part[i]=i;
}
}
int get_superparent(int x){
if(x==part[x]){
return x;
}
return part[x]=get_superparent(part[x]);
}
void unite(int x,int y){
int super_parent_x=get_superparent(x);
int super_parent_y=get_superparent(y);
if(super_parent_x!=super_parent_y){
part[super_parent_x]=super_parent_y;
}
}
bool detect_cycle(){
int n,m;
bool cycle_present=false;
cin>>n>>m;
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
if(get_superparent(x)!=get_superparent(y)){
unite(x,y);
}else{
cycle_present=true;
}
}
return cycle_present;
}
};
int main(){
dsu g(5);
if(g.detect_cycle()){
cout<<"Cycle is present"<<endl;
}else{
cout<<"Cycle not present"<<endl;
}
return 0;
}
| 16.35
| 56
| 0.474006
|
Ashish2030
|
1f56078dc315f07ce8c8a983d0fc31ce267fd54a
| 1,968
|
cpp
|
C++
|
Graphics2D/Source/DDraw1DrawList.cpp
|
TaylorClark/PrimeTime
|
3c62f6c53e0494146a95be1412273de3cf05bcd2
|
[
"MIT"
] | null | null | null |
Graphics2D/Source/DDraw1DrawList.cpp
|
TaylorClark/PrimeTime
|
3c62f6c53e0494146a95be1412273de3cf05bcd2
|
[
"MIT"
] | null | null | null |
Graphics2D/Source/DDraw1DrawList.cpp
|
TaylorClark/PrimeTime
|
3c62f6c53e0494146a95be1412273de3cf05bcd2
|
[
"MIT"
] | null | null | null |
#include "..\PrivateInclude\DDraw1DrawList.h"
/// Test if the rectangle intersects any of the dirty rectangles
bool DDraw1DrawList::IntersectsDirtyRects( const Box2i& destRect ) const
{
// Go through each dirty rectangle and test for intersection
for( std::list<Box2i>::const_iterator iterRect = m_DirtyRects.begin(); iterRect != m_DirtyRects.end(); ++iterRect )
{
if( destRect.Intersects( *iterRect ) )
return true;
}
// The destination rectangle does not intersect any of the dirty rectangles
return false;
}
DDraw1DrawList::DrawingList DDraw1DrawList::DrawImage( const TCImage* pImage, const Box2i& destRect, const Box2i& srcRect, int32 fx )
{
DrawingArray curDrawList = m_BackBufferList[m_CurBackBufferIndex];
DrawingList retList;
// Create the item for this draw
DrawnItem newItem;
newItem.destRect = destRect;
newItem.fx = fx;
newItem.pImage = pImage;
newItem.srcRect = srcRect;
// If this item has not been drawn yet then draw the entire thing
if( m_DrawIndex >= curDrawList.size() )
{
curDrawList.resize( m_DrawIndex + 1 );
curDrawList[ m_DrawIndex ] = newItem;
retList.push_back( newItem );
++m_DrawIndex;
return retList;
}
// Test if this will intersect any dirty rectangles
if( IntersectsDirtyRects( destRect ) )
{
}
// If this item is the same as last frame then there is no need to draw it
const DrawnItem& lastFrameDrawn = curDrawList[m_DrawIndex];
if( newItem == lastFrameDrawn )
{
++m_DrawIndex;
return retList;
}
// At this point in the method it is known that this draw needs to occur, but also that all
// subsequent draws above this image need to be drawn
return retList;
}
void DDraw1DrawList::DisplayScene()
{
// Step to the next back buffer, looping around if necessary
m_CurBackBufferIndex++;
m_CurBackBufferIndex %= m_BackBufferList.size();
// Clear the list of rectangles to which images were drawn
m_DirtyRects.clear();
// Reset the drawn image index
m_DrawIndex = 0;
}
| 26.958904
| 133
| 0.740346
|
TaylorClark
|
1f5c713e1791b673ed007f8bac5fb3134b7643f3
| 2,027
|
cpp
|
C++
|
binary.tree.cpp
|
lucasfrct/intro-C-PlusPlus
|
4f0ca777c655c00ce8c4e2e3e1ddab7dc6fd2b57
|
[
"MIT"
] | null | null | null |
binary.tree.cpp
|
lucasfrct/intro-C-PlusPlus
|
4f0ca777c655c00ce8c4e2e3e1ddab7dc6fd2b57
|
[
"MIT"
] | null | null | null |
binary.tree.cpp
|
lucasfrct/intro-C-PlusPlus
|
4f0ca777c655c00ce8c4e2e3e1ddab7dc6fd2b57
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
class Node
{
private:
Node *left, *right;
int key;
public:
Node(int key)
{
this->key = key;
this->left = NULL;
this->right = NULL;
}
int getKey()
{
return this->key;
}
Node* getLeft()
{
return this->left;
}
Node* getRight()
{
return this->right;
}
void setLeft(Node* node)
{
this->left = node;
}
void setRight(Node* node)
{
this->right = node;
}
};
class Tree
{
private:
Node* root;
public:
Tree()
{
this->root = NULL;
}
void insert(int key)
{
if(this->root == NULL) {
this->root = new Node(key);
} else {
this->insertAux(this->root, key);
}
}
void insertAux(Node* node, int key)
{
if(key < node->getKey()) {
if(node->getLeft() == NULL) {
Node* n = new Node(key);
node->setLeft(n);
} else {
this->insertAux(node->getLeft(), key);
}
} else if(key > node->getKey()) {
if(node->getRight() == NULL) {
Node* n = new Node(key);
node->setRight(n);
} else {
this->insertAux(node->getRight(), key);
}
}
}
Node* getRoot()
{
return this->root;
}
void ordered(Node* node)
{
if(node != NULL) {
this->ordered(node->getLeft());
cout << node->getKey() << " ";
this->ordered(node->getRight());
}
}
};
int main(int argc, char const *argv[])
{
Tree tree;
tree.insert(8);
tree.insert(10);
tree.insert(14);
tree.insert(13);
tree.insert(3);
tree.insert(1);
tree.insert(6);
tree.insert(4);
tree.insert(7);
tree.ordered(tree.getRoot());
cout << endl;
cout << endl;
system("pause");
return 0;
}
| 16.216
| 55
| 0.443019
|
lucasfrct
|
1f5cd7d826074a1caeb9fd00d225e1f0eaabad62
| 1,094
|
cpp
|
C++
|
Netcode/Graphics/DX12/DX12Texture.cpp
|
tyekx/netcode
|
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
|
[
"MIT"
] | null | null | null |
Netcode/Graphics/DX12/DX12Texture.cpp
|
tyekx/netcode
|
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
|
[
"MIT"
] | null | null | null |
Netcode/Graphics/DX12/DX12Texture.cpp
|
tyekx/netcode
|
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
|
[
"MIT"
] | null | null | null |
#include "DX12Texture.h"
#include <Netcode/Graphics/ResourceEnums.h>
namespace Netcode::Graphics::DX12 {
TextureImpl::TextureImpl(DirectX::ScratchImage && tData) : textureData{ std::move(tData) } { }
ResourceDimension TextureImpl::GetDimension() const {
switch(textureData.GetMetadata().dimension) {
case DirectX::TEX_DIMENSION_TEXTURE1D:
return ResourceDimension::TEXTURE1D;
case DirectX::TEX_DIMENSION_TEXTURE2D:
return ResourceDimension::TEXTURE2D;
case DirectX::TEX_DIMENSION_TEXTURE3D:
return ResourceDimension::TEXTURE3D;
default:
return ResourceDimension::UNKNOWN;
}
}
uint16_t TextureImpl::GetMipLevelCount() const {
return static_cast<uint16_t>(textureData.GetMetadata().mipLevels);
}
const Image * TextureImpl::GetImage(uint16_t mipIndex, uint16_t arrayIndex, uint32_t slice) {
return textureData.GetImage(mipIndex, arrayIndex, slice);
}
const Image * TextureImpl::GetImages() {
return textureData.GetImages();
}
uint16_t TextureImpl::GetImageCount() {
return static_cast<uint16_t>(textureData.GetMetadata().arraySize);
}
}
| 28.051282
| 95
| 0.761426
|
tyekx
|
48f824644beec0164416cd3e0b96bef31a14d756
| 158
|
cpp
|
C++
|
notebooks/funcs1.cpp
|
itachi4869/sta-663-2021
|
6f7a50f4a95207a26b01afa4439d992d767a1387
|
[
"MIT"
] | null | null | null |
notebooks/funcs1.cpp
|
itachi4869/sta-663-2021
|
6f7a50f4a95207a26b01afa4439d992d767a1387
|
[
"MIT"
] | null | null | null |
notebooks/funcs1.cpp
|
itachi4869/sta-663-2021
|
6f7a50f4a95207a26b01afa4439d992d767a1387
|
[
"MIT"
] | null | null | null |
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int a, int b) {
return a + b;
}
void init_f1(py::module &m) {
m.def("add", &add);
}
| 14.363636
| 30
| 0.601266
|
itachi4869
|
5b01e9f8a7ecf5aa9af4bd4b721f5a604bf0f518
| 1,343
|
cpp
|
C++
|
Vic2ToHoI4Tests/HoI4WorldTests/Regions/RegionsTests.cpp
|
CarbonY26/Vic2ToHoI4
|
af3684d6aaaafea81aaadfb64a21a2b696f618e1
|
[
"MIT"
] | 25
|
2018-12-10T03:41:49.000Z
|
2021-10-04T10:42:36.000Z
|
Vic2ToHoI4Tests/HoI4WorldTests/Regions/RegionsTests.cpp
|
CarbonY26/Vic2ToHoI4
|
af3684d6aaaafea81aaadfb64a21a2b696f618e1
|
[
"MIT"
] | 739
|
2018-12-13T02:01:20.000Z
|
2022-03-28T02:57:13.000Z
|
Vic2ToHoI4Tests/HoI4WorldTests/Regions/RegionsTests.cpp
|
IhateTrains/Vic2ToHoI4
|
5ad7f7c259f7495a10e043ade052d3b18a8951dc
|
[
"MIT"
] | 43
|
2018-12-10T03:41:58.000Z
|
2022-03-22T23:55:41.000Z
|
#include "HOI4World/Regions/Regions.h"
#include "HOI4World/Regions/RegionsFactory.h"
#include "gtest/gtest.h"
TEST(HoI4World_Regions_RegionsTests, ProvinceInUnmappedRegionsReturnsNullptr)
{
const auto regions = HoI4::Regions::Factory().getRegions();
EXPECT_EQ(std::nullopt, regions->getRegion(0));
}
TEST(HoI4World_Regions_RegionsTests, ProvinceInMappedRegionsReturnsRegion)
{
const auto regions = HoI4::Regions::Factory().getRegions();
EXPECT_EQ("test_region", regions->getRegion(42));
}
TEST(HoI4World_Regions_RegionsTests, NameInUnmappedRegionReturnsNullopt)
{
const auto regions = HoI4::Regions::Factory().getRegions();
EXPECT_EQ(std::nullopt, regions->getRegionName("missing_region"));
}
TEST(HoI4World_Regions_RegionsTests, NameInMappedRegionReturnsName)
{
const auto regions = HoI4::Regions::Factory().getRegions();
EXPECT_EQ("Test Region", regions->getRegionName("test_region"));
}
TEST(HoI4World_Regions_RegionsTests, AdjectiveInUnmappedRegionReturnsNullopt)
{
const auto regions = HoI4::Regions::Factory().getRegions();
EXPECT_EQ(std::nullopt, regions->getRegionName("missing_region"));
}
TEST(HoI4World_Regions_RegionsTests, AdjectiveInMappedRegionReturnsAdjective)
{
const auto regions = HoI4::Regions::Factory().getRegions();
EXPECT_EQ("Test Regional", regions->getRegionAdjective("test_region"));
}
| 25.826923
| 77
| 0.787789
|
CarbonY26
|
5b090d1d235ea99090453fb502d25c409a36e385
| 437
|
cpp
|
C++
|
src/ooni/tcp_connect.cpp
|
alessandro40/libight
|
de434be18791844076603b50167c436a768e830e
|
[
"BSD-2-Clause"
] | null | null | null |
src/ooni/tcp_connect.cpp
|
alessandro40/libight
|
de434be18791844076603b50167c436a768e830e
|
[
"BSD-2-Clause"
] | null | null | null |
src/ooni/tcp_connect.cpp
|
alessandro40/libight
|
de434be18791844076603b50167c436a768e830e
|
[
"BSD-2-Clause"
] | null | null | null |
#include <ight/ooni/tcp_connect.hpp>
using namespace ight::common::settings;
using namespace ight::ooni::tcp_connect;
void
TCPConnect::main(std::string input, Settings options,
std::function<void(ReportEntry)>&& cb)
{
options["host"] = input;
have_entry = cb;
client = connect(options, [this]() {
logger->debug("tcp_connect: Got response to TCP connect test");
have_entry(entry);
});
}
| 25.705882
| 71
| 0.652174
|
alessandro40
|
5b0b2b772b7a54dc8872b0c5c97e82516bea0976
| 6,858
|
cpp
|
C++
|
extras/usd/examples/usdDancingCubesExample/fileFormat.cpp
|
chen2qu/USD
|
2bbedce05f61f37e7461b0319609f9ceeb91725e
|
[
"AML"
] | 88
|
2018-07-13T01:22:00.000Z
|
2022-01-16T22:15:27.000Z
|
extras/usd/examples/usdDancingCubesExample/fileFormat.cpp
|
chen2qu/USD
|
2bbedce05f61f37e7461b0319609f9ceeb91725e
|
[
"AML"
] | 1
|
2022-01-14T21:25:56.000Z
|
2022-01-14T21:25:56.000Z
|
extras/usd/examples/usdDancingCubesExample/fileFormat.cpp
|
chen2qu/USD
|
2bbedce05f61f37e7461b0319609f9ceeb91725e
|
[
"AML"
] | 26
|
2018-06-06T03:39:22.000Z
|
2021-08-28T23:02:42.000Z
|
//
// Copyright 2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "data.h"
#include "fileFormat.h"
#include "pxr/usd/pcp/dynamicFileFormatContext.h"
#include "pxr/usd/usd/usdaFileFormat.h"
#include <fstream>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
TF_DEFINE_PUBLIC_TOKENS(
UsdDancingCubesExampleFileFormatTokens,
USD_DANCING_CUBES_EXAMPLE_FILE_FORMAT_TOKENS);
TF_REGISTRY_FUNCTION(TfType)
{
SDF_DEFINE_FILE_FORMAT(UsdDancingCubesExampleFileFormat, SdfFileFormat);
}
UsdDancingCubesExampleFileFormat::UsdDancingCubesExampleFileFormat()
: SdfFileFormat(
UsdDancingCubesExampleFileFormatTokens->Id,
UsdDancingCubesExampleFileFormatTokens->Version,
UsdDancingCubesExampleFileFormatTokens->Target,
UsdDancingCubesExampleFileFormatTokens->Extension)
{
}
UsdDancingCubesExampleFileFormat::~UsdDancingCubesExampleFileFormat()
{
}
bool
UsdDancingCubesExampleFileFormat::CanRead(const std::string& filePath) const
{
return true;
}
SdfAbstractDataRefPtr
UsdDancingCubesExampleFileFormat::InitData(
const FileFormatArguments &args) const
{
// Create our special procedural abstract data with its parameters extracted
// from the file format arguments.
return UsdDancingCubesExample_Data::New(
UsdDancingCubesExample_DataParams::FromArgs(args));
}
bool
UsdDancingCubesExampleFileFormat::Read(
SdfLayer *layer,
const std::string &resolvedPath,
bool metadataOnly) const
{
if (!TF_VERIFY(layer)) {
return false;
}
// Enforce that the layer is read only.
layer->SetPermissionToSave(false);
layer->SetPermissionToEdit(false);
// We don't do anything else when we read the file as the contents aren't
// used at all in this example. There layer's data has already been
// initialized from file format arguments.
return true;
}
bool
UsdDancingCubesExampleFileFormat::WriteToString(
const SdfLayer &layer,
std::string *str,
const std::string &comment) const
{
// Write the generated contents in usda text format.
return SdfFileFormat::FindById(
UsdUsdaFileFormatTokens->Id)->WriteToString(layer, str, comment);
}
bool
UsdDancingCubesExampleFileFormat::WriteToStream(
const SdfSpecHandle &spec,
std::ostream &out,
size_t indent) const
{
// Write the generated contents in usda text format.
return SdfFileFormat::FindById(
UsdUsdaFileFormatTokens->Id)->WriteToStream(spec, out, indent);
}
void
UsdDancingCubesExampleFileFormat::ComposeFieldsForFileFormatArguments(
const std::string &assetPath,
const PcpDynamicFileFormatContext &context,
FileFormatArguments *args,
VtValue *contextDependencyData) const
{
UsdDancingCubesExample_DataParams params;
// There is one relevant metadata field that should be dictionary valued.
// Compose this field's value and extract any param values from the
// resulting dictionary.
VtValue val;
if (context.ComposeValue(UsdDancingCubesExampleFileFormatTokens->Params, &val) &&
val.IsHolding<VtDictionary>()) {
params = UsdDancingCubesExample_DataParams::FromDict(
val.UncheckedGet<VtDictionary>());
}
// Convert the entire params object to file format arguments. We always
// convert all parameters even if they're default as the args are part of
// the identity of the layer.
*args = params.ToArgs();
}
bool
UsdDancingCubesExampleFileFormat::CanFieldChangeAffectFileFormatArguments(
const TfToken &field,
const VtValue &oldValue,
const VtValue &newValue,
const VtValue &contextDependencyData) const
{
// Theres only one relevant field and its values should hold a dictionary.
const VtDictionary &oldDict = oldValue.IsHolding<VtDictionary>() ?
oldValue.UncheckedGet<VtDictionary>() : VtGetEmptyDictionary();
const VtDictionary &newDict = newValue.IsHolding<VtDictionary>() ?
newValue.UncheckedGet<VtDictionary>() : VtGetEmptyDictionary();
// The dictionary values for our metadata key are not restricted as to what
// they may contain so it's possible they may have keys that are completely
// irrelevant to generating the this file format's parameters. Here we're
// demonstrating how we can do a more fine grained analysis based on this
// fact. In some cases this can provide a better experience for users if
// the extra processing in this function can prevent expensive prim
// recompositions for changes that don't require it. But keep in mind that
// there can easily be cases where making this function more expensive can
// outweigh the benefits of avoiding unnecessary recompositions.
// Compare relevant values in the old and new dictionaries.
// If both the old and new dictionaries are empty, there's no change.
if (oldDict.empty() && newDict.empty()) {
return false;
}
// Otherwise we iterate through each possible parameter value looking for
// any one that has a value change between the two dictionaries.
for (const TfToken &token : UsdDancingCubesExample_DataParamsTokens->allTokens) {
auto oldIt = oldDict.find(token);
auto newIt = newDict.find(token);
const bool oldValExists = oldIt == oldDict.end();
const bool newValExists = newIt == newDict.end();
// If param value exists in one or not the other, we have change.
if (oldValExists != newValExists) {
return true;
}
// Otherwise if it's both and the value differs, we also have a change.
if (newValExists && oldIt->second != newIt->second) {
return true;
}
}
// None of the relevant data params changed between the two dictionaries.
return false;
}
PXR_NAMESPACE_CLOSE_SCOPE
| 34.989796
| 86
| 0.729805
|
chen2qu
|
5b0bc75ab024c51e45cbebf36350bfb7371fa7f8
| 1,110
|
cpp
|
C++
|
5. Longest Palindromic Substring/main.cpp
|
majianfei/leetcode
|
d79ad7dd8c07e9f816b5727d1d98eb55c719cb6d
|
[
"MIT"
] | null | null | null |
5. Longest Palindromic Substring/main.cpp
|
majianfei/leetcode
|
d79ad7dd8c07e9f816b5727d1d98eb55c719cb6d
|
[
"MIT"
] | null | null | null |
5. Longest Palindromic Substring/main.cpp
|
majianfei/leetcode
|
d79ad7dd8c07e9f816b5727d1d98eb55c719cb6d
|
[
"MIT"
] | null | null | null |
#include <iostream>
//TODO,优化
/**
* Runtime: 200 ms, faster than 24.74% of C++ online submissions for Longest Palindromic Substring.
* Memory Usage: 186.7 MB, less than 8.03% of C++ online submissions for Longest Palindromic Substring.
*/
class Solution {
public:
string longestPalindrome(string s) {
int size = s.size();
if (size <= 1)return s;
int max_num = 1,start=0,end=0;
vector<vector<int>> dp(size,vector<int>(size,0));
for (int i = size - 1; i >= 0; i--){
dp[i][i] = 1;
for (int j = i+1; j <size; j++){
if (s[i] == s[j]){
if (j - i <= 1)dp[i][j] = 2;
else dp[i][j] = dp[i+1][j-1]==0?0:dp[i+1][j-1]+2;
}
else{
dp[i][j] = 0;
}
if (max_num < dp[i][j]){
start = i;
end = j;
max_num = dp[i][j];
}
}
}
return s.substr(start, end-start+1);
}
};
| 30.833333
| 104
| 0.405405
|
majianfei
|
5b1657def1ed0ccf941d0cba721f2570ed1536dc
| 7,816
|
cpp
|
C++
|
test/test_FMinus.cpp
|
skmuduli92/libprop
|
982753ee446a44aef2bfa92c944a3ce20c4a45ad
|
[
"BSD-3-Clause"
] | null | null | null |
test/test_FMinus.cpp
|
skmuduli92/libprop
|
982753ee446a44aef2bfa92c944a3ce20c4a45ad
|
[
"BSD-3-Clause"
] | null | null | null |
test/test_FMinus.cpp
|
skmuduli92/libprop
|
982753ee446a44aef2bfa92c944a3ce20c4a45ad
|
[
"BSD-3-Clause"
] | 2
|
2020-10-06T15:26:51.000Z
|
2020-10-11T12:55:00.000Z
|
#include <gtest/gtest.h>
#include "formula.h"
#include "parse_util.h"
#include "formula_util.h"
#include "trace.h"
#include "formula_util.h"
using namespace HyperPLTL;
using namespace std;
PHyperProp propertyOnceMinusOperator() {
PVarMap varmap = std::make_shared<VarMap>();
varmap->addIntVar("x");
varmap->addIntVar("y");
std::string formula = "(F- (AND (EQ x) (EQ y)))";
return parse_formula(formula, varmap);
}
TEST(PropertyLibTest, ValidTraceOnceMinusOperator_Simple) {
PVarMap varmap = std::make_shared<VarMap>();
unsigned xid = varmap->addIntVar("x");
PHyperProp property = parse_formula("(F- (EQ x))", varmap);
PTrace trace1(new Trace(0, 1));
PTrace trace2(new Trace(0, 1));
TraceList tracelist({trace1, trace2});
bool result = false;
unsigned traceLength = rand() % 20 + 20;
size_t cycle = 0;
for (cycle = 0; cycle < traceLength; cycle++) {
if(cycle == 10){
trace1->updateTermValue(xid, cycle, 10);
trace2->updateTermValue(xid, cycle, 10);
continue;
}
trace1->updateTermValue(xid, cycle, rand() % std::numeric_limits<unsigned>::max());
trace2->updateTermValue(xid, cycle, rand() % std::numeric_limits<unsigned>::max());
}
result = evaluateTraces(property, tracelist);
EXPECT_TRUE(result);
}
TEST(PropertyLibTest, InValidTraceOnceMinusOperator_Simple) {
PVarMap varmap = std::make_shared<VarMap>();
unsigned xid = varmap->addIntVar("x");
PHyperProp property = parse_formula("(F- (EQ x))", varmap);
PTrace trace1(new Trace(0, 1));
PTrace trace2(new Trace(0, 1));
TraceList tracelist({trace1, trace2});
bool result = false;
unsigned traceLength = rand() % 20 + 20;
size_t cycle = 0;
for (cycle = 0; cycle < traceLength; cycle++) {
unsigned xvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, !xvalue);
}
result = evaluateTraces(property, tracelist);
EXPECT_FALSE(result);
}
TEST(PropertyLibTest, ValidTraceOnceMinusOperator) {
PHyperProp property = propertyOnceMinusOperator();
PTrace trace1(new Trace(0, 2));
PTrace trace2(new Trace(0, 2));
TraceList tracelist({trace1, trace2});
unsigned xid = property->getVarId("x");
unsigned yid = property->getVarId("y");
bool result = false;
unsigned traceLength = rand() % 20 + 20;
size_t cycle = 0;
for (; cycle < traceLength; ++cycle) {
unsigned xvalue = rand() % 100;
// setting 'x' var value
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, !xvalue);
// setting 'y' var value
unsigned yvalue = rand() % 100;
trace1->updateTermValue(yid, cycle, yvalue);
trace2->updateTermValue(yid, cycle, !yvalue);
}
trace1->updateTermValue(xid, cycle, 10);
trace2->updateTermValue(xid, cycle, 10);
trace1->updateTermValue(yid, cycle, 11);
trace2->updateTermValue(yid, cycle, 11);
cycle = cycle + 1;
traceLength = rand() % 20 + 20 + cycle;
for (; cycle < traceLength; ++cycle) {
unsigned xvalue = rand() % 100;
// setting 'x' var value
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, !xvalue);
// setting 'y' var value
unsigned yvalue = rand() % 100;
trace1->updateTermValue(yid, cycle, yvalue);
trace2->updateTermValue(yid, cycle, !yvalue);
}
result = evaluateTraces(property, tracelist);
EXPECT_TRUE(result);
}
TEST(PropertyLibTest, InvalidTraceOnceMinusOperator) {
PHyperProp property = propertyOnceMinusOperator();
PTrace trace1(new Trace(0, 2));
PTrace trace2(new Trace(0, 2));
TraceList tracelist({trace1, trace2});
unsigned xid = property->getVarId("x");
unsigned yid = property->getVarId("y");
bool result = false;
unsigned traceLength = rand() % 20 + 20;
size_t cycle = 0;
for (; cycle < traceLength; ++cycle) {
unsigned xvalue = rand() % 100;
// setting 'x' var value
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, !xvalue);
// setting 'y' var value
unsigned yvalue = rand() % 100;
trace1->updateTermValue(yid, cycle, yvalue);
trace2->updateTermValue(yid, cycle, yvalue);
}
traceLength = rand() % 20 + 20 + cycle;
for (; cycle < traceLength; ++cycle) {
unsigned xvalue = rand() % 100;
// setting 'x' var value
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, xvalue);
// setting 'y' var value
unsigned yvalue = rand() % 100;
trace1->updateTermValue(yid, cycle, yvalue);
trace2->updateTermValue(yid, cycle, !yvalue);
}
result = evaluateTraces(property, tracelist);
EXPECT_FALSE(result);
}
TEST(PropertyLibTest, ValidTraceOperator_XMinus_FMinus) {
PVarMap varmap = std::make_shared<VarMap>();
unsigned xid = varmap->addIntVar("x");
unsigned yid = varmap->addIntVar("y");
std::string formula = "(F- (IMPLIES (EQ x) (X+ (EQ y))))";
auto property = parse_formula(formula, varmap);
PTrace trace1(new Trace(0, 2));
PTrace trace2(new Trace(0, 2));
TraceList tracelist({trace1, trace2});
unsigned xvalue = 0, yvalue = 0;
long cycle = 0;
for (; cycle < 10; ++cycle) {
xvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, xvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(yid, cycle, yvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace2->updateTermValue(yid, cycle, yvalue);
}
xvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, xvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(yid, cycle, yvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace2->updateTermValue(yid, cycle, yvalue);
++cycle;
xvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(xid, cycle, xvalue);
xvalue = rand() % std::numeric_limits<unsigned>::max();
trace2->updateTermValue(xid, cycle, xvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(yid, cycle, yvalue);
trace2->updateTermValue(yid, cycle, yvalue);
++cycle;
for (; cycle < 20; ++cycle) {
xvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(xid, cycle, xvalue);
xvalue = rand() % std::numeric_limits<unsigned>::max();
trace2->updateTermValue(xid, cycle, xvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(yid, cycle, yvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace2->updateTermValue(yid, cycle, yvalue);
}
bool result = false;
result = evaluateTraces(property, tracelist);
ASSERT_TRUE(result);
}
TEST(PropertyLibTest, InvalidTraceOperator_XMinus_FMinus) {
PVarMap varmap = std::make_shared<VarMap>();
unsigned xid = varmap->addIntVar("x");
unsigned yid = varmap->addIntVar("y");
std::string formula = "(F- (IMPLIES (EQ x) (X- (EQ y))))";
auto property = parse_formula(formula, varmap);
PTrace trace1(new Trace(0, 2));
PTrace trace2(new Trace(0, 2));
TraceList tracelist({trace1, trace2});
unsigned xvalue = 0, yvalue = 0;
long cycle = 0;
for (; cycle < 10; ++cycle) {
xvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(xid, cycle, xvalue);
trace2->updateTermValue(xid, cycle, xvalue);
yvalue = rand() % std::numeric_limits<unsigned>::max();
trace1->updateTermValue(yid, cycle, yvalue);
trace2->updateTermValue(yid, cycle, !yvalue);
}
bool result = false;
result = evaluateTraces(property, tracelist);
EXPECT_FALSE(result);
}
| 29.94636
| 87
| 0.670164
|
skmuduli92
|
5b16a4ac2415ecf7c2f5d50a7f5f5b7738fafef7
| 9,075
|
cpp
|
C++
|
listeners/GPII_RFIDListener/src/Diagnostic.cpp
|
colinbdclark/windows
|
3eb9e8c4bda54bc583af7309998ab202370bde23
|
[
"BSD-3-Clause"
] | null | null | null |
listeners/GPII_RFIDListener/src/Diagnostic.cpp
|
colinbdclark/windows
|
3eb9e8c4bda54bc583af7309998ab202370bde23
|
[
"BSD-3-Clause"
] | null | null | null |
listeners/GPII_RFIDListener/src/Diagnostic.cpp
|
colinbdclark/windows
|
3eb9e8c4bda54bc583af7309998ab202370bde23
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
//
// Diagnostic.cpp
//
// Copyright 2014 OpenDirective Ltd.
//
// Licensed under the New BSD license. You may not use this file except in
// compliance with this License.
//
// You may obtain a copy of the License at
// https://github.com/gpii/windows/blob/master/LICENSE.txt
//
// The research leading to these results has received funding from
// the European Union's Seventh Framework Programme (FP7/2007-2013)
// under grant agreement no. 289016.
//
// Access to the diagnostic window
//
// Project Files:
// Diagnostic.cpp
// Diagnostic.h
//
///////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <windowsx.h>
#include <Strsafe.h>
#include <Diagnostic.h>
//---------------------------------------------------------
// Global Constants
//---------------------------------------------------------
static const char MY_TITLE[] = "GpiiUserListener Diagnostic";
static const char MY_CLASS[] = "gpiiDiagnosticClass";
static const int MY_SIZE_X = 480;
static const int MY_SIZE_Y = 450;
static const int MY_FONT_HEIGHT = 16;
#define WM_MYLOG WM_USER + 100
#define ID_EDIT 1000
//---------------------------------------------------------
// Global Variables
//---------------------------------------------------------
static HWND g_hWnd = NULL;
static HFONT g_hFont;
//---------------------------------------------------------
// Local Functions:
//---------------------------------------------------------
static ATOM _MyRegisterClass(HINSTANCE hInstance);
static LRESULT CALLBACK _WndProc(HWND, UINT, WPARAM, LPARAM);
///////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// Register our window class so we can create it
//
///////////////////////////////////////////////////////////////////////////////
static ATOM _MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)_WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); // FIXME we have icon files so why not use them?
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = MY_CLASS;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
return RegisterClassEx(&wcex);
}
///////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Diagnostic_Init()
//
// PURPOSE: Initialise the diagnostic window
//
// COMMENTS:
//
// Init from InitInstance().
//
///////////////////////////////////////////////////////////////////////////////
BOOL Diagnostic_Init(HINSTANCE hInstance)
{
_MyRegisterClass(hInstance);
RECT rc;
GetWindowRect(GetDesktopWindow(), &rc);
HWND hWnd = CreateWindow(MY_CLASS, MY_TITLE, WS_OVERLAPPEDWINDOW | WS_SYSMENU,
rc.right / 10, rc.bottom / 15,
MY_SIZE_X, rc.bottom - 2 * (rc.bottom / 15), NULL, NULL, hInstance, NULL);
if (!hWnd)
return FALSE;
// Window style for the edit control.
DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL |
WS_BORDER | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL |
ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_READONLY;
// Create the edit control window.
HWND hwndEdit = CreateWindowEx(
0, TEXT("edit"),
NULL, // No Window title
dwStyle, // Window style
0, 0, 0, 0, // Set size in WM_SIZE of parent
hWnd, // Parent window
(HMENU) ID_EDIT, // Control identifier
hInstance, // Instance handle
NULL);
if (!hwndEdit)
return FALSE;
// Select a non proportional font
g_hFont = CreateFont(MY_FONT_HEIGHT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TEXT("Courier New"));
SetWindowFont(hwndEdit, g_hFont, FALSE);
g_hWnd = hWnd;
return TRUE;
}
void Diagnostic_CleanUp(void)
{
DestroyWindow(g_hWnd);
}
void Diagnostic_Show(BOOL bShow)
{
ShowWindow(g_hWnd, (bShow) ? SW_SHOW : SW_HIDE);
}
BOOL Diagnostic_IsShowing(void)
{
return IsWindowVisible(g_hWnd);
}
///////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
// WM_MYTRAY - a mouse command on the tray icon
// WM_DEVICECHANGE - a change to a device on this pc
//
///////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK _WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
//-----------------------------------------------------------
// Tray Icon Menu Commands to Show, Hide, Exit or Logout
//-----------------------------------------------------------
case WM_MYLOG:
{
LPCSTR pszStr = (LPCSTR)lParam;
// Append text - note will eventually fill up
const HWND hwndEdit = GetWindow(hWnd, GW_CHILD);
int len = Edit_GetTextLength(hwndEdit);
Edit_SetSel(hwndEdit, len, len);
Edit_ReplaceSel(hwndEdit, pszStr);
HANDLE hheap = GetProcessHeap();
HeapFree(hheap, 0, (LPVOID)pszStr);
}
break;
case WM_SETFOCUS:
{
const HWND hwndEdit = GetWindow(hWnd, GW_CHILD);
SetFocus(hwndEdit);
return 0;
}
case WM_SIZE:
// Make the edit control the size of the window's client area.
{
const HWND hwndEdit = GetWindow(hWnd, GW_CHILD);
MoveWindow(hwndEdit,
0, 0, // starting x- and y-coordinates
LOWORD(lParam), // width of client area
HIWORD(lParam), // height of client area
TRUE); // repaint window
return 0;
}
//-----------------------------------------------------------
// Close [X] Hides the Window
//-----------------------------------------------------------
case WM_CLOSE:
{
const HWND hwndEdit = GetWindow(hWnd, GW_CHILD);
Edit_SetText(hwndEdit, "");
}
break;
//-----------------------------------------------------------
// Cleanup resources
//-----------------------------------------------------------
case WM_DESTROY:
DeleteObject(g_hFont);
break;
//-----------------------------------------------------------
// Default Window Proc
//-----------------------------------------------------------
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
#define _countof(a) (sizeof(a)/sizeof(a[0]))
///////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: Diagnostic_LogString(LPCSTR pszPrefix, LPCSTR pszStr)
//
// PURPOSE: Cause a string to be logged in the daignostic window.
//
// NOTES: We PostMessage to be more thread safe. String is on Process Heap
//
///////////////////////////////////////////////////////////////////////////////
void Diagnostic_LogString(LPCSTR pszPrefix, LPCSTR pszString)
{
pszPrefix = (pszPrefix) ? pszPrefix : "";
pszString = (pszString) ? pszString : "";
const STRSAFE_LPCSTR pszFormat = TEXT("%s: %s\r\n");
HANDLE hheap = GetProcessHeap();
SIZE_T cbHeap = strlen(pszPrefix) + strlen(pszString) + strlen(pszFormat);
STRSAFE_LPSTR pszStrLog = (STRSAFE_LPSTR)HeapAlloc(hheap, 0, cbHeap);
if (pszStrLog)
{
(void)StringCchPrintf(pszStrLog, cbHeap, pszFormat, pszPrefix, pszString);
PostMessage(g_hWnd, WM_MYLOG, NULL, (LPARAM)pszStrLog);
}
}
//FIXME perhaps inline these functions. Perhasp use pointers not indexes
void Diagnostic_PrintHexBytes(LPTSTR pszDest, size_t cchDest, LPCBYTE pBytes, size_t cBytes)
{
*pszDest = '\0';
for (size_t i = 0; i < cBytes; i++)
{
(void)StringCchPrintf(&pszDest[i * 3], cchDest - (i * 3), TEXT("%02hhx "), pBytes[i]);
}
}
void Diagnostic_PrintCharBytes(LPTSTR pszDest, size_t cchDest, LPCBYTE pBytes, size_t cBytes)
{
*pszDest = '\0';
for (size_t i = 0; i < cBytes; i++)
{
(void)StringCchPrintf(&pszDest[i], cchDest - i, TEXT("%c"), pBytes[i]);
}
}
void Diagnostic_LogHexBlock(UINT uSector, UINT uBlock, LPCBYTE pbBlock, size_t cBytes)
{
static TCHAR pszPrefix[20];
static TCHAR pszString[500];
LPCTSTR pszFormatPrefix = TEXT("%02u-%02u");
(void)StringCchPrintf(pszPrefix, _countof(pszPrefix), pszFormatPrefix, uSector, uBlock);
Diagnostic_PrintHexBytes(pszString, _countof(pszString), pbBlock, cBytes);
Diagnostic_LogString(pszPrefix, pszString);
}
| 30.555556
| 98
| 0.53168
|
colinbdclark
|
5b1889c5959378c5db3f7e2f15ab2b20ed176b81
| 2,291
|
cpp
|
C++
|
YorozuyaGSLib/source/US__AbstractThreadDetail.cpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
YorozuyaGSLib/source/US__AbstractThreadDetail.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
YorozuyaGSLib/source/US__AbstractThreadDetail.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
#include <US__AbstractThreadDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace US
{
namespace Detail
{
Info::US__AbstractThreadctor_AbstractThread2_ptr US__AbstractThreadctor_AbstractThread2_next(nullptr);
Info::US__AbstractThreadctor_AbstractThread2_clbk US__AbstractThreadctor_AbstractThread2_user(nullptr);
Info::US__AbstractThreaddtor_AbstractThread7_ptr US__AbstractThreaddtor_AbstractThread7_next(nullptr);
Info::US__AbstractThreaddtor_AbstractThread7_clbk US__AbstractThreaddtor_AbstractThread7_user(nullptr);
void US__AbstractThreadctor_AbstractThread2_wrapper(struct US::AbstractThread* _this)
{
US__AbstractThreadctor_AbstractThread2_user(_this, US__AbstractThreadctor_AbstractThread2_next);
};
void US__AbstractThreaddtor_AbstractThread7_wrapper(struct US::AbstractThread* _this)
{
US__AbstractThreaddtor_AbstractThread7_user(_this, US__AbstractThreaddtor_AbstractThread7_next);
};
::std::array<hook_record, 2> AbstractThread_functions =
{
_hook_record {
(LPVOID)0x14041d660L,
(LPVOID *)&US__AbstractThreadctor_AbstractThread2_user,
(LPVOID *)&US__AbstractThreadctor_AbstractThread2_next,
(LPVOID)cast_pointer_function(US__AbstractThreadctor_AbstractThread2_wrapper),
(LPVOID)cast_pointer_function((void(US::AbstractThread::*)())&US::AbstractThread::ctor_AbstractThread)
},
_hook_record {
(LPVOID)0x14041d6e0L,
(LPVOID *)&US__AbstractThreaddtor_AbstractThread7_user,
(LPVOID *)&US__AbstractThreaddtor_AbstractThread7_next,
(LPVOID)cast_pointer_function(US__AbstractThreaddtor_AbstractThread7_wrapper),
(LPVOID)cast_pointer_function((void(US::AbstractThread::*)())&US::AbstractThread::dtor_AbstractThread)
},
};
}; // end namespace Detail
}; // end namespace US
END_ATF_NAMESPACE
| 46.755102
| 122
| 0.647316
|
lemkova
|
5b1f73ee50254763be96b6984639258706861a64
| 3,640
|
cpp
|
C++
|
Boggle/code_1.cpp
|
Jatin-Goyal5/Data-Structures-and-Algorithms
|
f6bd0f77e5640c2e0568f3fffc4694758e77af96
|
[
"MIT"
] | 27
|
2019-01-31T10:22:29.000Z
|
2021-08-29T08:25:12.000Z
|
Boggle/code_1.cpp
|
Jatin-Goyal5/Data-Structures-and-Algorithms
|
f6bd0f77e5640c2e0568f3fffc4694758e77af96
|
[
"MIT"
] | 6
|
2020-09-30T19:01:49.000Z
|
2020-12-17T15:10:54.000Z
|
Boggle/code_1.cpp
|
Jatin-Goyal5/Data-Structures-and-Algorithms
|
f6bd0f77e5640c2e0568f3fffc4694758e77af96
|
[
"MIT"
] | 27
|
2019-09-21T14:19:32.000Z
|
2021-09-15T03:06:41.000Z
|
//
// code_1.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
using namespace std;
#define char_int(c) ((int)c - (int)'A')
#define SIZE (26)
#define M 3
#define N 3
struct TrieNode {
TrieNode *Child[SIZE];
bool leaf;
};
TrieNode *getNode() {
TrieNode * newNode = new TrieNode;
newNode->leaf = false;
for (int i =0 ; i< SIZE ; i++) {
newNode->Child[i] = NULL;
}
return newNode;
}
void insert(TrieNode *root, char *Key) {
size_t n = strlen(Key);
TrieNode * pChild = root;
for (int i = 0; i < n; i++) {
int index = char_int(Key[i]);
if (pChild->Child[index] == NULL) {
pChild->Child[index] = getNode();
}
pChild = pChild->Child[index];
}
pChild->leaf = true;
}
bool isSafe(int i, int j, bool visited[M][N]) {
return (i >=0 && i < M && j >=0 && j < N && !visited[i][j]);
}
void searchWord(TrieNode *root, char boggle[M][N], int i, int j, bool visited[][N], string str) {
if (root->leaf == true) {
cout << str << endl ;
}
if (isSafe(i, j, visited)) {
visited[i][j] = true;
for (int K =0; K < SIZE; K++) {
if (root->Child[K] != NULL) {
char ch = (char)K + (char)'A' ;
if (isSafe(i+1,j+1,visited) && boggle[i+1][j+1] == ch) {
searchWord(root->Child[K],boggle,i+1,j+1,visited,str+ch);
}
if (isSafe(i, j+1,visited) && boggle[i][j+1] == ch) {
searchWord(root->Child[K],boggle,i, j+1,visited,str+ch);
}
if (isSafe(i-1,j+1,visited) && boggle[i-1][j+1] == ch) {
searchWord(root->Child[K],boggle,i-1, j+1,visited,str+ch);
}
if (isSafe(i+1,j, visited) && boggle[i+1][j] == ch) {
searchWord(root->Child[K],boggle,i+1, j,visited,str+ch);
}
if (isSafe(i+1,j-1,visited) && boggle[i+1][j-1] == ch) {
searchWord(root->Child[K],boggle,i+1, j-1,visited,str+ch);
}
if (isSafe(i, j-1,visited)&& boggle[i][j-1] == ch) {
searchWord(root->Child[K],boggle,i,j-1,visited,str+ch);
}
if (isSafe(i-1,j-1,visited) && boggle[i-1][j-1] == ch) {
searchWord(root->Child[K],boggle,i-1, j-1,visited,str+ch);
}
if (isSafe(i-1, j,visited) && boggle[i-1][j] == ch) {
searchWord(root->Child[K],boggle,i-1, j, visited,str+ch);
}
}
}
visited[i][j] = false;
}
}
void findWords(char boggle[M][N], TrieNode *root) {
bool visited[M][N];
memset(visited,false,sizeof(visited));
TrieNode *pChild = root ;
string str = "";
for (int i = 0 ; i < M; i++) {
for (int j = 0 ; j < N ; j++) {
if (pChild->Child[char_int(boggle[i][j])] ) {
str = str+boggle[i][j];
searchWord(pChild->Child[char_int(boggle[i][j])], boggle, i, j, visited, str);
str = "";
}
}
}
}
int main() {
char *dictionary[] = {"GEEKS", "FOR", "QUIZ", "GEE"};
TrieNode *root = getNode();
int n = sizeof(dictionary)/sizeof(dictionary[0]);
for (int i=0; i<n; i++) {
insert(root, dictionary[i]);
}
char boggle[M][N] = {
{'G','I','Z'},
{'U','E','K'},
{'Q','S','E'}
};
findWords(boggle, root);
return 0;
}
| 28.4375
| 97
| 0.467308
|
Jatin-Goyal5
|
5b1fc763f2b4d71d72ca122a57c98b9e2f695e8a
| 1,821
|
hpp
|
C++
|
src/hex_pathfinding.hpp
|
cbeck88/HexWarfare
|
94a70b1889afc2fbd990892ed66be874ac70d1b4
|
[
"Apache-2.0"
] | null | null | null |
src/hex_pathfinding.hpp
|
cbeck88/HexWarfare
|
94a70b1889afc2fbd990892ed66be874ac70d1b4
|
[
"Apache-2.0"
] | null | null | null |
src/hex_pathfinding.hpp
|
cbeck88/HexWarfare
|
94a70b1889afc2fbd990892ed66be874ac70d1b4
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2014 Kristina Simpson <sweet.kristas@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <tuple>
#include <boost/graph/astar_search.hpp>
#include <boost/graph/adjacency_list.hpp>
#include "geometry.hpp"
#include "game_state.hpp"
#include "hex_logical_fwd.hpp"
namespace hex
{
typedef float cost;
typedef point node_type;
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, cost>> hex_graph;
typedef boost::property_map<hex_graph, boost::edge_weight_t>::type WeightMap;
typedef hex_graph::vertex_descriptor vertex;
typedef hex_graph::edge_descriptor edge_descriptor;
typedef std::pair<point, point> edge;
struct graph_t
{
graph_t(size_t size) : graph(size) {}
hex_graph graph;
std::map<point, int> reverse_map;
std::vector<point> vertices;
};
typedef std::shared_ptr<graph_t> hex_graph_ptr;
typedef std::vector<point> result_path;
hex_graph_ptr create_cost_graph(const game::state& gs, const point& src, float max_cost);
hex_graph_ptr create_graph(const game::state& gs, int x=0, int y=0, int w=0, int h=0);
result_list find_available_moves(hex_graph_ptr graph, const point& src, float max_cost);
result_path find_path(hex_graph_ptr graph, const point& src, const point& dst);
}
| 34.358491
| 153
| 0.772103
|
cbeck88
|
5b21786e54a5cf1abf566e8988f8e7e8d35cf6a7
| 542
|
cpp
|
C++
|
Example/signals2_09/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/signals2_09/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/signals2_09/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
#include <boost/signals2.hpp>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace boost::signals2;
template <typename T>
struct return_all
{
typedef T result_type;
template <typename InputIterator>
T operator()(InputIterator first, InputIterator last) const
{
return T(first, last);
}
};
int main()
{
signal<int(), return_all<std::vector<int>>> s;
s.connect([]{ return 1; });
s.connect([]{ return 2; });
std::vector<int> v = s();
std::cout << *std::min_element(v.begin(), v.end()) << '\n';
}
| 20.074074
| 61
| 0.654982
|
KwangjoJeong
|
5b22f927d629a0595735e30fa52ce74c0d7fcbd7
| 2,201
|
cpp
|
C++
|
44_DigitsInSequence/DigitsInSequence.cpp
|
NoMoreWaiting/CodingInterviewChinese2
|
458b2fb52b91a6601fd9b70dd3b973d30c2f3f52
|
[
"BSD-3-Clause"
] | null | null | null |
44_DigitsInSequence/DigitsInSequence.cpp
|
NoMoreWaiting/CodingInterviewChinese2
|
458b2fb52b91a6601fd9b70dd3b973d30c2f3f52
|
[
"BSD-3-Clause"
] | null | null | null |
44_DigitsInSequence/DigitsInSequence.cpp
|
NoMoreWaiting/CodingInterviewChinese2
|
458b2fb52b91a6601fd9b70dd3b973d30c2f3f52
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题44:数字序列中某一位的数字
// 题目:数字以0123456789101112131415…的格式序列化到一个字符序列中。在这
// 个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一
// 个函数求任意位对应的数字。
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int countOfIntegers(int digits);
int digitAtIndex(int index, int digits);
int beginNumber(int digits);
int digitAtIndex(int index)
{
if(index < 0)
return -1;
int digits = 1;
while(true)
{
int numbers = countOfIntegers(digits);
if(index < numbers * digits)
return digitAtIndex(index, digits);
index -= digits * numbers;
digits++;
}
return -1;
}
int countOfIntegers(int digits)
{
if(digits == 1)
return 10;
int count = (int) std::pow(10, digits - 1);
return 9 * count;
}
int digitAtIndex(int index, int digits)
{
int number = beginNumber(digits) + index / digits;
int indexFromRight = digits - index % digits;
for(int i = 1; i < indexFromRight; ++i)
number /= 10;
return number % 10;
}
int beginNumber(int digits)
{
if(digits == 1)
return 0;
return (int) std::pow(10, digits - 1);
}
// ====================测试代码====================
void test(const char* testName, int inputIndex, int expectedOutput)
{
if(digitAtIndex(inputIndex) == expectedOutput)
cout << testName << " passed." << endl;
else
cout << testName << " FAILED." << endl;
}
int main()
{
test((char *)"test1", 0, 0);
test((char *)"test2", 1, 1);
test((char *)"test3", 9, 9);
test((char *)"test4", 10, 1);
test((char *)"test5", 189, 9); // 数字99的最后一位,9
test((char *)"test6", 190, 1); // 数字100的第一位,1
test((char *)"test7", 1000, 3); // 数字370的第一位,3
test((char *)"test8", 1001, 7); // 数字370的第二位,7
test((char *)"test9", 1002, 0); // 数字370的第三位,0
return 0;
}
| 22.690722
| 76
| 0.569741
|
NoMoreWaiting
|
5b240a57d34a46dc1bec99d97e7f964d1405ae3d
| 2,761
|
cpp
|
C++
|
src/Utils/String.cpp
|
vincentdelpech/biorbd
|
0d7968e75e182f067a4d4c24cc15fa9a331ca792
|
[
"MIT"
] | null | null | null |
src/Utils/String.cpp
|
vincentdelpech/biorbd
|
0d7968e75e182f067a4d4c24cc15fa9a331ca792
|
[
"MIT"
] | null | null | null |
src/Utils/String.cpp
|
vincentdelpech/biorbd
|
0d7968e75e182f067a4d4c24cc15fa9a331ca792
|
[
"MIT"
] | null | null | null |
#define BIORBD_API_EXPORTS
#include "Utils/String.h"
#include <map>
#include <algorithm>
#include <vector>
#include <boost/lexical_cast.hpp>
#include "Utils/Error.h"
biorbd::utils::String::String()
: std::string("")
{
}
biorbd::utils::String::String(const char *c)
: std::string(c)
{
}
biorbd::utils::String::String(const String &s)
: std::string(s)
{
}
biorbd::utils::String::String(const std::basic_string<char> &c)
: std::string(c)
{
}
biorbd::utils::String &biorbd::utils::String::operator=(const biorbd::utils::String &other)
{
if (this==&other) // check for self-assigment
return *this;
this->std::string::operator=(other);
return *this;
}
biorbd::utils::String biorbd::utils::String::operator+(const char *c){
String tp = *this;
tp.append(c);
return tp;
}
biorbd::utils::String biorbd::utils::String::operator+(double d){
return *this + boost::lexical_cast<std::string>(d);
}
biorbd::utils::String biorbd::utils::String::operator+(unsigned int d){
return *this + boost::lexical_cast<std::string>(d);
}
biorbd::utils::String biorbd::utils::String::operator+(int d){
return *this + boost::lexical_cast<std::string>(d);
}
biorbd::utils::String biorbd::utils::String::operator()(unsigned int i) const{
biorbd::utils::Error::check(i<this->length(), "Index for string out of range");
char out[2];
out[0] = (*this)[i];
out[1] = '\0';
return out;
}
biorbd::utils::String biorbd::utils::String::operator()(unsigned int i, unsigned int j) const{
biorbd::utils::Error::check((i<this->length() || j<this->length()), "Index for string out of range");
biorbd::utils::Error::check(j>i, "Second argument should be higher than first!");
char *out = static_cast<char*>(malloc(j-i+2*sizeof(char)));
for (unsigned int k=0; k<j-i+1; ++k)
out[k] = (*this)[i+k];
out[j-i+1] = '\0';
biorbd::utils::String Out(out);
free(out);
return Out;
}
biorbd::utils::String::~String()
{
}
biorbd::utils::String biorbd::utils::String::tolower(const biorbd::utils::String &str){
biorbd::utils::String new_str = str;
std::transform(new_str.begin(), new_str.end(), new_str.begin(), ::tolower);
return new_str;
}
biorbd::utils::String biorbd::utils::String::tolower() const{
return tolower(*this);
}
biorbd::utils::String biorbd::utils::String::toupper(const biorbd::utils::String &str){
biorbd::utils::String new_str = str;
std::transform(new_str.begin(), new_str.end(), new_str.begin(), ::toupper);
return new_str;
}
biorbd::utils::String biorbd::utils::String::toupper() const{
return toupper(*this);
}
std::ostream &operator<<(std::ostream &os, const biorbd::utils::String &a)
{
os << a.c_str();
return os;
}
| 25.330275
| 105
| 0.648678
|
vincentdelpech
|
5b24ce8aae34b943b10c84e33e9fb73e4a00f68e
| 16,480
|
hh
|
C++
|
dune/gdt/interpolations/boundary.hh
|
pymor/dune-gdt
|
fabc279a79e7362181701866ce26133ec40a05e0
|
[
"BSD-2-Clause"
] | 4
|
2018-10-12T21:46:08.000Z
|
2020-08-01T18:54:02.000Z
|
dune/gdt/interpolations/boundary.hh
|
dune-community/dune-gdt
|
fabc279a79e7362181701866ce26133ec40a05e0
|
[
"BSD-2-Clause"
] | 154
|
2016-02-16T13:50:54.000Z
|
2021-12-13T11:04:29.000Z
|
dune/gdt/interpolations/boundary.hh
|
dune-community/dune-gdt
|
fabc279a79e7362181701866ce26133ec40a05e0
|
[
"BSD-2-Clause"
] | 5
|
2016-03-02T10:11:20.000Z
|
2020-02-08T03:56:24.000Z
|
// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt 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:
// Felix Schindler (2019)
#ifndef DUNE_GDT_INTERPOLATIONS_BOUNDARY_HH
#define DUNE_GDT_INTERPOLATIONS_BOUNDARY_HH
#include <dune/geometry/referenceelements.hh>
#include <dune/grid/common/rangegenerators.hh>
#include <dune/xt/grid/boundaryinfo/interfaces.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/functions/generic/function.hh>
#include <dune/xt/functions/generic/grid-function.hh>
#include <dune/xt/functions/grid-function.hh>
#include <dune/gdt/exceptions.hh>
#include "default.hh"
namespace Dune {
namespace GDT {
// ### Variants for GridFunctionInterface
/**
* \brief Interpolates a localizable function restricted to certain boundary intersections within a given space [most
* general variant].
*
* Simply uses the interpolation() of the target spaces finite_element() and selects only those DoFs which lie on
* intersections of correct boundary type.
*
* \note The same restrictions apply as for the default interpolations.
*/
template <class GV, size_t r, size_t rC, class R, class V, class IGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGV::Grid::template Codim<0>::Entity>::value,
void>
boundary_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source,
DiscreteFunction<V, GV, r, rC, R>& target,
const GridView<IGV>& interpolation_grid_view,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridView<IGV>>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
using D = typename GridView<IGV>::ctype;
static constexpr int d = GridView<IGV>::dimension;
auto local_dof_vector = target.dofs().localize();
auto local_source = source.local_function();
DynamicVector<R> local_dofs(target.space().mapper().max_local_size());
const auto target_basis = target.space().basis().localize();
for (auto&& element : elements(interpolation_grid_view)) {
// first check if we should do something at all on this element
size_t matching_boundary_intersections = 0;
for (auto&& intersection : intersections(interpolation_grid_view, element))
if (boundary_info.type(intersection) == target_boundary_type)
++matching_boundary_intersections;
if (matching_boundary_intersections) {
target_basis->bind(element);
// some preparations
local_source->bind(element);
local_dof_vector.bind(element);
const auto& fe = target_basis->finite_element();
// interpolate
fe.interpolation().interpolate(
[&](const auto& xx) { return local_source->evaluate(xx); }, local_source->order(), local_dofs);
const auto& reference_element = ReferenceElements<D, d>::general(element.type());
// but keep only those DoFs associated with the intersection, therefore determine these DoFs
std::set<size_t> local_target_boundary_DoFs;
const auto local_key_indices = fe.coefficients().local_key_indices();
for (auto&& intersection : intersections(interpolation_grid_view, element)) {
if (boundary_info.type(intersection) == target_boundary_type) {
const auto intersection_index = intersection.indexInInside();
for (const auto& local_DoF : local_key_indices[1][intersection_index])
local_target_boundary_DoFs.insert(local_DoF);
for (int cc = 2; cc <= d; ++cc) {
for (int ii = 0; ii < reference_element.size(intersection_index, 1, cc); ++ii) {
const auto subentity_id = reference_element.subEntity(intersection_index, 1, ii, cc);
for (const auto& local_DoF : local_key_indices[cc][subentity_id])
local_target_boundary_DoFs.insert(local_DoF);
}
}
}
}
DUNE_THROW_IF(local_target_boundary_DoFs.size() == 0,
Exceptions::interpolation_error,
"The finite element is not suitable: although the element has an intersection on the boundary, no "
"DoFs are associated with it!");
// * and use only those
for (const auto& local_DoF_id : local_target_boundary_DoFs)
local_dof_vector[local_DoF_id] = local_dofs[local_DoF_id];
}
}
} // ... boundary_interpolation(...)
/**
* \brief Interpolates a localizable function restricted to certain boundary intersections within a given space [uses
* target.space().grid_view() as interpolation_grid_view].
**/
template <class GV, size_t r, size_t rC, class R, class V>
void boundary_interpolation(
const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source,
DiscreteFunction<V, GV, r, rC, R>& target,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GV>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
boundary_interpolation(source, target, target.space().grid_view(), boundary_info, target_boundary_type);
}
/**
* \brief Interpolates a localizable function restricted to certain boundary intersections within a given space [creates
* a suitable target function].
**/
template <class VectorType, class GV, size_t r, size_t rC, class R, class IGV>
std::enable_if_t<
XT::LA::is_vector<VectorType>::value
&& std::is_same<XT::Grid::extract_entity_t<GV>, typename IGV::Grid::template Codim<0>::Entity>::value,
DiscreteFunction<VectorType, GV, r, rC, R>>
boundary_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source,
const SpaceInterface<GV, r, rC, R>& target_space,
const GridView<IGV>& interpolation_grid_view,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridView<IGV>>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
auto target_function = make_discrete_function<VectorType>(target_space);
boundary_interpolation(source, target_function, interpolation_grid_view, boundary_info, target_boundary_type);
return target_function;
}
/**
* \brief Interpolates a localizable function restricted to certain boundary intersections within a given space [creates
* a suitable target function, uses target_space.grid_view() as interpolation_grid_view].
**/
template <class VectorType, class GV, size_t r, size_t rC, class R>
std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>>
boundary_interpolation(const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r, rC, R>& source,
const SpaceInterface<GV, r, rC, R>& target_space,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GV>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
auto target_function = make_discrete_function<VectorType>(target_space);
boundary_interpolation(source, target_function, boundary_info, target_boundary_type);
return target_function;
}
// ### Variants for FunctionInterface
/**
* \brief Interpolates a function restricted to certain boundary intersections within a given space [most general
* variant].
*
* Simply calls as_grid_function<>() and redirects to the appropriate boundary_interpolation() function.
*/
template <class GV, size_t r, size_t rC, class R, class V, class IGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGV::Grid::template Codim<0>::Entity>::value,
void>
boundary_interpolation(const XT::Functions::FunctionInterface<GridView<IGV>::dimension, r, rC, R>& source,
DiscreteFunction<V, GV, r, rC, R>& target,
const GridView<IGV>& interpolation_grid_view,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridView<IGV>>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
boundary_interpolation(XT::Functions::make_grid_function(source, interpolation_grid_view),
target,
interpolation_grid_view,
boundary_info,
target_boundary_type);
}
/**
* \brief Interpolates a function restricted to certain boundary intersections within a given space [uses
* target.space().grid_view() as interpolation_grid_view].
**/
template <class GV, size_t r, size_t rC, class R, class V>
void boundary_interpolation(const XT::Functions::FunctionInterface<GV::dimension, r, rC, R>& source,
DiscreteFunction<V, GV, r, rC, R>& target,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GV>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
boundary_interpolation(source, target, target.space().grid_view(), boundary_info, target_boundary_type);
}
/**
* \brief Interpolates a function restricted to certain boundary intersections within a given space [creates a suitable
* target function].
**/
template <class VectorType, class GV, size_t r, size_t rC, class R, class IGV>
std::enable_if_t<
XT::LA::is_vector<VectorType>::value
&& std::is_same<XT::Grid::extract_entity_t<GV>, typename IGV::Grid::template Codim<0>::Entity>::value,
DiscreteFunction<VectorType, GV, r, rC, R>>
boundary_interpolation(const XT::Functions::FunctionInterface<GridView<IGV>::dimension, r, rC, R>& source,
const SpaceInterface<GV, r, rC, R>& target_space,
const GridView<IGV>& interpolation_grid_view,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridView<IGV>>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
return boundary_interpolation<VectorType>(XT::Functions::make_grid_function(source, interpolation_grid_view),
target_space,
interpolation_grid_view,
boundary_info,
target_boundary_type);
}
/**
* \brief Interpolates a function restricted to certain boundary intersections within a given space [creates a suitable
* target function, uses target_space.grid_view() as interpolation_grid_view].
**/
template <class VectorType, class GV, size_t r, size_t rC, class R>
std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>>
boundary_interpolation(const XT::Functions::FunctionInterface<GV::dimension, r, rC, R>& source,
const SpaceInterface<GV, r, rC, R>& target_space,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GV>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
return boundary_interpolation<VectorType>(
source, target_space, target_space.grid_view(), boundary_info, target_boundary_type);
}
// ### Variants for GenericFunction
/**
* \brief Interpolates a function given as a lambda expression restricted to certain boundary intersections within a
* given space [most general variant].
*
* Simply creates a XT::Functions::GenericFunction and redirects to the appropriate boundary_interpolation() function.
*/
template <class GV, size_t r, size_t rC, class R, class V, class IGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<GV>, typename IGV::Grid::template Codim<0>::Entity>::value,
void>
boundary_interpolation(
const int source_order,
const std::function<typename XT::Functions::GenericFunction<GridView<IGV>::dimension, r, rC, R>::RangeReturnType(
const typename XT::Functions::GenericFunction<GridView<IGV>::dimension, r, rC, R>::DomainType&,
const XT::Common::Parameter&)> source_evaluate_lambda,
DiscreteFunction<V, GV, r, rC, R>& target,
const GridView<IGV>& interpolation_grid_view,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridView<IGV>>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
boundary_interpolation(
XT::Functions::GenericFunction<GridView<IGV>::dimension, r, rC, R>(source_order, source_evaluate_lambda),
target,
interpolation_grid_view,
boundary_info,
target_boundary_type);
}
/**
* \brief Interpolates a function given as a lambda expression restricted to certain boundary intersections within a
* given space [uses target.space().grid_view() as interpolation_grid_view].
**/
template <class GV, size_t r, size_t rC, class R, class V>
void boundary_interpolation(
const int source_order,
const std::function<typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::RangeReturnType(
const typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::DomainType&,
const XT::Common::Parameter&)> source_evaluate_lambda,
DiscreteFunction<V, GV, r, rC, R>& target,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GV>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
boundary_interpolation(XT::Functions::GenericFunction<GV::dimension, r, rC, R>(source_order, source_evaluate_lambda),
target,
boundary_info,
target_boundary_type);
}
/**
* \brief Interpolates a function given as a lambda expression within a given space [creates a suitable target
* function].
**/
template <class VectorType, class GV, size_t r, size_t rC, class R, class IGV>
std::enable_if_t<
XT::LA::is_vector<VectorType>::value
&& std::is_same<XT::Grid::extract_entity_t<GV>, typename IGV::Grid::template Codim<0>::Entity>::value,
DiscreteFunction<VectorType, GV, r, rC, R>>
boundary_interpolation(
const int source_order,
const std::function<typename XT::Functions::GenericFunction<GridView<IGV>::dimension, r, rC, R>::RangeReturnType(
const typename XT::Functions::GenericFunction<GridView<IGV>::dimension, r, rC, R>::DomainType&,
const XT::Common::Parameter&)> source_evaluate_lambda,
const SpaceInterface<GV, r, rC, R>& target_space,
const GridView<IGV>& interpolation_grid_view,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridView<IGV>>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
return boundary_interpolation<VectorType>(
XT::Functions::GenericFunction<GridView<IGV>::dimension, r, rC, R>(source_order, source_evaluate_lambda),
target_space,
interpolation_grid_view,
boundary_info,
target_boundary_type);
}
/**
* \brief Interpolates a function given as a lambda expression within a given space [creates a suitable target
* function, uses target_space.grid_view() as interpolation_grid_view].
**/
template <class VectorType, class GV, size_t r, size_t rC, class R>
std::enable_if_t<XT::LA::is_vector<VectorType>::value, DiscreteFunction<VectorType, GV, r, rC, R>>
boundary_interpolation(
const int source_order,
const std::function<typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::RangeReturnType(
const typename XT::Functions::GenericFunction<GV::dimension, r, rC, R>::DomainType&,
const XT::Common::Parameter&)> source_evaluate_lambda,
const SpaceInterface<GV, r, rC, R>& target_space,
const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GV>>& boundary_info,
const XT::Grid::BoundaryType& target_boundary_type)
{
return boundary_interpolation<VectorType>(
XT::Functions::GenericFunction<GV::dimension, r, rC, R>(source_order, source_evaluate_lambda),
target_space,
boundary_info,
target_boundary_type);
}
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_INTERPOLATIONS_BOUNDARY_HH
| 48.328446
| 120
| 0.694782
|
pymor
|
5b2686e34d63b86fc5a4ba61e692695f64e1e914
| 6,000
|
cpp
|
C++
|
test/marker.cpp
|
fizyr/dr_marker
|
039cdff23516749c5830acdce7f7be5ba71cae02
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
test/marker.cpp
|
fizyr/dr_marker
|
039cdff23516749c5830acdce7f7be5ba71cae02
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
test/marker.cpp
|
fizyr/dr_marker
|
039cdff23516749c5830acdce7f7be5ba71cae02
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 1
|
2018-06-06T10:07:13.000Z
|
2018-06-06T10:07:13.000Z
|
/**
* Copyright 2014-2018 Fizyr BV. https://fizyr.com
*
* 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 "marker.hpp"
#include <gtest/gtest.h>
#include <dr_eigen/ros.hpp>
#include <dr_eigen/eigen.hpp>
#include <dr_eigen/test/compare.hpp>
#include <cmath>
int main(int argc, char * * argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
namespace dr {
TEST(MarkerTest, makeSphereMarker) {
ros::Time::init();
ros::Time now = ros::Time::now();
Eigen::Vector3d position(0.5, 0.5, 0.5); // some position
std::string frame_id = "some_frame";
double radius = 0.5;
std::string ns = "some_namespace";
ros::Duration lifetime = ros::Duration(0.5); // 0.5s lifetime
std::array<float, 4> color({{0.3f, 0.4f, 0.5f, 0.6f}});
int id = 100;
visualization_msgs::Marker marker = createSphereMarker(
"some_frame",
position,
radius,
ns,
lifetime,
color,
id
);
// expect the supplied output to be the same
EXPECT_EQ(marker.header.frame_id, frame_id);
EXPECT_TRUE(marker.header.stamp.toSec() >= now.toSec());
EXPECT_TRUE(marker.header.stamp.toSec() <= ros::Time::now().toSec());
EXPECT_EQ(marker.id, id);
EXPECT_TRUE(testEqual(position, toEigen(marker.pose.position)));
EXPECT_FLOAT_EQ(marker.color.r, color[0]);
EXPECT_FLOAT_EQ(marker.color.g, color[1]);
EXPECT_FLOAT_EQ(marker.color.b, color[2]);
EXPECT_FLOAT_EQ(marker.color.a, color[3]);
EXPECT_DOUBLE_EQ(marker.scale.x, radius);
EXPECT_DOUBLE_EQ(marker.scale.y, radius);
EXPECT_DOUBLE_EQ(marker.scale.z, radius);
EXPECT_DOUBLE_EQ(marker.lifetime.toSec(), 0.5);
EXPECT_EQ(marker.type, visualization_msgs::Marker::SPHERE);
EXPECT_EQ(marker.action, visualization_msgs::Marker::ADD);
EXPECT_EQ(marker.ns, ns);
}
TEST(MarkerTest, makeCylinderMarker) {
ros::Time::init();
ros::Time now = ros::Time::now();
std::string frame_id = "some_frame";
Eigen::AngleAxisd rotation = rotateY(M_PI);
Eigen::Isometry3d pose = translate(0.5, 0.5, 0.5) * rotation;
double radius = 0.5;
double height = 1.0;
std::string ns = "some_namespace";
ros::Duration lifetime = ros::Duration(0.5); // 0.5s lifetime
std::array<float, 4> color({{0.3f, 0.4f, 0.5f, 0.6f}});
int id = 100;
visualization_msgs::Marker marker = createCylinderMarker(
"some_frame",
pose,
radius,
height,
ns,
lifetime,
color,
id
);
// expect the supplied output to be the same
EXPECT_EQ(marker.header.frame_id, frame_id);
EXPECT_TRUE(marker.header.stamp.toSec() >= now.toSec());
EXPECT_TRUE(marker.header.stamp.toSec() <= ros::Time::now().toSec());
EXPECT_EQ(marker.id, id);
EXPECT_TRUE(testEqual(pose.translation(), toEigen(marker.pose.position)));
EXPECT_FLOAT_EQ(marker.color.r, color[0]);
EXPECT_FLOAT_EQ(marker.color.g, color[1]);
EXPECT_FLOAT_EQ(marker.color.b, color[2]);
EXPECT_FLOAT_EQ(marker.color.a, color[3]);
EXPECT_DOUBLE_EQ(marker.scale.x, radius * 2);
EXPECT_DOUBLE_EQ(marker.scale.y, radius * 2);
EXPECT_DOUBLE_EQ(marker.scale.z, height);
EXPECT_DOUBLE_EQ(marker.lifetime.toSec(), 0.5);
EXPECT_EQ(marker.type, visualization_msgs::Marker::CYLINDER);
EXPECT_EQ(marker.action, visualization_msgs::Marker::ADD);
EXPECT_EQ(marker.ns, ns);
}
TEST(MarkerTest, makeBoxMarker) {
ros::Time::init();
ros::Time now = ros::Time::now();
std::string frame_id = "some_frame";
Eigen::AlignedBox3d box;
std::string ns = "some_namespace";
ros::Duration lifetime = ros::Duration(0.5); // 0.5s lifetime
std::array<float, 4> color({{0.3f, 0.4f, 0.5f, 0.6f}});
int id = 100;
visualization_msgs::Marker marker = createBoxMarker(
"some_frame",
box,
ns,
lifetime,
color,
id
);
// expect the supplied output to be the same
EXPECT_EQ(marker.header.frame_id, frame_id);
EXPECT_TRUE(marker.header.stamp.toSec() >= now.toSec());
EXPECT_TRUE(marker.header.stamp.toSec() <= ros::Time::now().toSec());
EXPECT_EQ(marker.id, id);
EXPECT_TRUE(testEqual(box.center(), toEigen(marker.pose.position)));
EXPECT_FLOAT_EQ(marker.color.r, color[0]);
EXPECT_FLOAT_EQ(marker.color.g, color[1]);
EXPECT_FLOAT_EQ(marker.color.b, color[2]);
EXPECT_FLOAT_EQ(marker.color.a, color[3]);
EXPECT_DOUBLE_EQ(marker.scale.x, box.sizes().x());
EXPECT_DOUBLE_EQ(marker.scale.y, box.sizes().y());
EXPECT_DOUBLE_EQ(marker.scale.z, box.sizes().z());
EXPECT_DOUBLE_EQ(marker.lifetime.toSec(), 0.5);
EXPECT_EQ(marker.type, visualization_msgs::Marker::CUBE);
EXPECT_EQ(marker.action, visualization_msgs::Marker::ADD);
EXPECT_EQ(marker.ns, ns);
}
}
| 32.258065
| 83
| 0.716833
|
fizyr
|
5b275307317bec0185acada3bc496e71c96d3347
| 32,316
|
cpp
|
C++
|
src/Services/PickerService/PickerService.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 39
|
2016-04-21T03:25:26.000Z
|
2022-01-19T14:16:38.000Z
|
src/Services/PickerService/PickerService.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 23
|
2016-06-28T13:03:17.000Z
|
2022-02-02T10:11:54.000Z
|
src/Services/PickerService/PickerService.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 14
|
2016-06-22T20:45:37.000Z
|
2021-07-05T12:25:19.000Z
|
#include "PickerService.h"
#include "Interface/InputServiceInterface.h"
#include "Interface/ApplicationInterface.h"
#include "Interface/EnumeratorServiceInterface.h"
#include "Kernel/Arrow.h"
#include "Kernel/Scene.h"
#include "Kernel/VectorAuxScope.h"
#include "Kernel/Logger.h"
#include "Kernel/VectorAuxScope.h"
#include "Kernel/IntrusivePtrView.h"
#include "Kernel/Assertion.h"
#include "Kernel/RenderContextHelper.h"
#include "Kernel/MixinDebug.h"
#include "Kernel/ProfilerHelper.h"
#include "Config/Algorithm.h"
//////////////////////////////////////////////////////////////////////////
SERVICE_FACTORY( PickerService, Mengine::PickerService );
//////////////////////////////////////////////////////////////////////////
namespace Mengine
{
namespace Detail
{
//////////////////////////////////////////////////////////////////////////
class PickerVisitor
{
public:
PickerVisitor( VectorPickerStates * _states, bool _exclusive )
: m_states( _states )
, m_exclusive( _exclusive )
{
}
~PickerVisitor()
{
}
protected:
void operator = ( const PickerVisitor & ) = delete;
public:
void visit( PickerInterface * _picker, const RenderContext & _context )
{
if( m_exclusive == true && _picker->isPickerExclusive() == false )
{
return;
}
PickerStateDesc desc;
desc.picker = _picker;
desc.context.target = nullptr;
desc.context.transformation = nullptr;
const RenderViewportInterfacePtr & pickerViewport = _picker->getPickerViewport();
if( pickerViewport != nullptr )
{
desc.context.viewport = pickerViewport.get();
}
else
{
desc.context.viewport = _context.viewport;
}
const RenderCameraInterfacePtr & pickerCamera = _picker->getPickerCamera();
if( pickerCamera != nullptr )
{
desc.context.camera = pickerCamera.get();
}
else
{
desc.context.camera = _context.camera;
}
const RenderTransformationInterfacePtr & pickerTransformation = _picker->getPickerTransformation();
if( pickerTransformation != nullptr )
{
desc.context.transformation = pickerTransformation.get();
}
else
{
desc.context.transformation = _context.transformation;
}
const RenderScissorInterfacePtr & pickerScissor = _picker->getPickerScissor();
if( pickerScissor != nullptr )
{
desc.context.scissor = pickerScissor.get();
}
else
{
desc.context.scissor = _context.scissor;
}
const RenderTargetInterfacePtr & pickerTarget = _picker->getPickerTarget();
if( pickerTarget != nullptr )
{
desc.context.target = pickerTarget.get();
}
else
{
desc.context.target = _context.target;
}
desc.context.zGroup = _context.zGroup;
desc.context.zIndex = _context.zIndex;
if( _picker->isPickerDummy() == false )
{
m_states->emplace_back( desc );
}
_picker->foreachPickerChildrenEnabled( [this, desc]( PickerInterface * _picker )
{
this->visit( _picker, desc.context );
} );
}
protected:
VectorPickerStates * m_states;
bool m_exclusive;
};
}
//////////////////////////////////////////////////////////////////////////
PickerService::PickerService()
: m_block( false )
, m_handleValue( true )
, m_invalidateTraps( false )
{
}
//////////////////////////////////////////////////////////////////////////
PickerService::~PickerService()
{
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::_initializeService()
{
return true;
}
//////////////////////////////////////////////////////////////////////////
void PickerService::_finalizeService()
{
m_arrow = nullptr;
m_scene = nullptr;
m_viewport = nullptr;
m_camera = nullptr;
m_transformation = nullptr;
m_scissor = nullptr;
m_target = nullptr;
MENGINE_ASSERTION_FATAL( m_states.empty() == true );
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setBlock( bool _value )
{
if( m_block == _value )
{
return;
}
m_block = _value;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setHandleValue( bool _value )
{
if( m_handleValue == _value )
{
return;
}
m_handleValue = _value;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setArrow( const ArrowPtr & _arrow )
{
if( m_arrow == _arrow )
{
return;
}
m_arrow = _arrow;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setScene( const ScenePtr & _scene )
{
if( m_scene == _scene )
{
return;
}
m_scene = _scene;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setRenderViewport( const RenderViewportInterfacePtr & _viewport )
{
if( m_viewport == _viewport )
{
return;
}
m_viewport = _viewport;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setRenderCamera( const RenderCameraInterfacePtr & _camera )
{
if( m_camera == _camera )
{
return;
}
m_camera = _camera;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setRenderTransformation( const RenderTransformationInterfacePtr & _transformation )
{
if( m_transformation == _transformation )
{
return;
}
m_transformation = _transformation;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setRenderScissor( const RenderScissorInterfacePtr & _scissor )
{
if( m_scissor == _scissor )
{
return;
}
m_scissor = _scissor;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
void PickerService::setRenderTarget( const RenderTargetInterfacePtr & _target )
{
if( m_target == _target )
{
return;
}
m_target = _target;
this->invalidateTraps();
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::pickTraps( const mt::vec2f & _point, ETouchCode _touchId, float _pressure, const InputSpecialData & _special, VectorPickers * const _pickers ) const
{
VectorPickerStates statesAux;
if( this->pickStates_( _point.x, _point.y, _touchId, _pressure, _special, &statesAux ) == false )
{
return false;
}
for( VectorPickerStates::reverse_iterator
it = statesAux.rbegin(),
it_end = statesAux.rend();
it != it_end;
++it )
{
PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerPicked() == false )
{
continue;
}
_pickers->emplace_back( picker );
}
return true;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::getTraps( const mt::vec2f & _point, VectorPickers * const _pickers ) const
{
VectorPickerStates statesAux;
if( this->getStates_( _point.x, _point.y, &statesAux ) == false )
{
return false;
}
for( const PickerStateDesc & desc : statesAux )
{
const PickerInterface * picker = desc.picker;
_pickers->emplace_back( picker );
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void PickerService::update()
{
MENGINE_PROFILER_CATEGORY();
if( m_invalidateTraps == true )
{
this->updateTraps_();
m_invalidateTraps = false;
}
}
//////////////////////////////////////////////////////////////////////////
void PickerService::updateTraps_()
{
ETouchCode touchId = TC_TOUCH0;
const mt::vec2f & position = INPUT_SERVICE()
->getCursorPosition( touchId );
float pressure = INPUT_SERVICE()
->getCursorPressure( touchId );
InputSpecialData special;
INPUT_SERVICE()
->getSpecial( &special );
VectorPickerStates statesAux;
this->pickStates_( position.x, position.y, touchId, pressure, special, &statesAux );
}
//////////////////////////////////////////////////////////////////////////
void PickerService::invalidateTraps()
{
m_invalidateTraps = true;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleKeyEvent( const InputKeyEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
if( this->pickStates_( _event.x, _event.y, TC_TOUCH0, 0.f, _event.special, &m_states ) == false )
{
return false;
}
MENGINE_PROFILER_CATEGORY();
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
InputKeyEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [key]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
if( inputHandler->handleKeyEvent( ne ) == false )
{
continue;
}
return m_handleValue;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleTextEvent( const InputTextEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
if( this->pickStates_( _event.x, _event.y, TC_TOUCH0, 0.f, _event.special, &m_states ) == false )
{
return false;
}
MENGINE_PROFILER_CATEGORY();
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
InputTextEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [text]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
if( inputHandler->handleTextEvent( ne ) == false )
{
continue;
}
return m_handleValue;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleMouseButtonEvent( const InputMouseButtonEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
if( this->pickStates_( _event.x, _event.y, _event.touchId, _event.pressure, _event.special, &m_states ) == false )
{
return false;
}
MENGINE_PROFILER_CATEGORY();
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
const PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
if( picker->isPickerPicked() == false )
{
continue;
}
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
InputMouseButtonEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
ne.isPressed = picker->isPickerPressed();
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse button]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
if( inputHandler->handleMouseButtonEvent( ne ) == false )
{
continue;
}
return m_handleValue;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleMouseButtonEventBegin( const InputMouseButtonEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
if( this->pickStates_( _event.x, _event.y, _event.touchId, _event.pressure, _event.special, &m_states ) == false )
{
return false;
}
MENGINE_PROFILER_CATEGORY();
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
const PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
if( picker->isPickerPicked() == false )
{
continue;
}
if( _event.isDown == true )
{
picker->setPickerPressed( true );
}
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
InputMouseButtonEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
ne.isPressed = picker->isPickerPressed();
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse button begin]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
if( inputHandler->handleMouseButtonEventBegin( ne ) == false )
{
continue;
}
return m_handleValue;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleMouseButtonEventEnd( const InputMouseButtonEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
if( this->pickStates_( _event.x, _event.y, _event.touchId, _event.pressure, _event.special, &m_states ) == false )
{
return false;
}
MENGINE_PROFILER_CATEGORY();
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
const PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
if( picker->isPickerPicked() == false )
{
continue;
}
if( _event.isDown == false )
{
if( picker->isPickerPressed() == false )
{
//continue;
}
else
{
picker->setPickerPressed( false );
}
}
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
InputMouseButtonEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
ne.isPressed = picker->isPickerPressed();
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse button end]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
if( inputHandler->handleMouseButtonEventEnd( ne ) == false )
{
continue;
}
return m_handleValue;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleMouseMove( const InputMouseMoveEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
if( this->pickStates_( _event.x, _event.y, _event.touchId, _event.pressure, _event.special, &m_states ) == false )
{
return false;
}
MENGINE_PROFILER_CATEGORY();
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
const PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
if( picker->isPickerPicked() == false )
{
continue;
}
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
mt::vec2f dp;
m_arrow->calcPointDeltha( &desc.context, mt::vec2f( _event.dx, _event.dy ), &dp );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
InputMouseMoveEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
ne.dx = dp.x;
ne.dy = dp.y;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse move]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
if( inputHandler->handleMouseMove( ne ) == false )
{
continue;
}
return m_handleValue;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleMouseWheel( const InputMouseWheelEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
if( this->pickStates_( _event.x, _event.y, TC_TOUCH0, 0.f, _event.special, &m_states ) == false )
{
return false;
}
MENGINE_PROFILER_CATEGORY();
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
const PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
if( picker->isPickerPicked() == false )
{
continue;
}
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
InputMouseWheelEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse wheel]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
if( inputHandler->handleMouseWheel( ne ) == false )
{
continue;
}
return m_handleValue;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::handleMouseEnter( const InputMouseEnterEvent & _event )
{
MENGINE_VECTOR_AUX( m_states );
this->pickStates_( _event.x, _event.y, _event.touchId, _event.pressure, _event.special, &m_states );
return false;
}
//////////////////////////////////////////////////////////////////////////
void PickerService::handleMouseLeave( const InputMouseLeaveEvent & _event )
{
if( m_arrow == nullptr )
{
return;
}
if( m_scene == nullptr )
{
return;
}
MENGINE_VECTOR_AUX( m_states );
this->fillStates_( &m_states );
for( VectorPickerStates::reverse_iterator
it = m_states.rbegin(),
it_end = m_states.rend();
it != it_end;
++it )
{
PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
if( picker->isPickerPicked() == false )
{
continue;
}
picker->setPickerPicked( false );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _event.x, _event.y ), &wp );
InputMouseLeaveEvent ne = _event;
ne.x = wp.x;
ne.y = wp.y;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse leave]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
inputHandler->handleMouseLeave( _event );
}
}
//////////////////////////////////////////////////////////////////////////
void PickerService::fillStates_( VectorPickerStates * const _states ) const
{
PickerInterface * picker = m_scene->getPicker();
Detail::PickerVisitor visitor( _states, false );
RenderContext context;
Helper::clearRenderContext( &context );
context.viewport = m_viewport.get();
context.camera = m_camera.get();
context.scissor = m_scissor.get();
visitor.visit( picker, context );
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::pickStates_( float _x, float _y, ETouchCode _touchId, float _pressure, const InputSpecialData & _special, VectorPickerStates * const _states ) const
{
MENGINE_ASSERTION_FATAL( _states->empty() );
MENGINE_PROFILER_CATEGORY();
if( m_arrow == nullptr )
{
return false;
}
if( m_scene == nullptr )
{
return false;
}
if( m_camera == nullptr )
{
return false;
}
this->fillStates_( _states );
const Resolution & contentResolution = APPLICATION_SERVICE()
->getContentResolution();
mt::vec2f adapt_screen_position;
m_arrow->adaptScreenPosition_( mt::vec2f( _x, _y ), &adapt_screen_position );
bool handle = false;
for( VectorPickerStates::reverse_iterator
it = _states->rbegin(),
it_end = _states->rend();
it != it_end;
++it )
{
const PickerStateDesc & desc = *it;
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
if( handle == false || m_handleValue == false )
{
bool picked = picker->pick( adapt_screen_position, &desc.context, contentResolution, m_arrow );
if( m_block == false && picked == true )
{
if( picker->isPickerPicked() == false )
{
picker->setPickerPicked( true );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _x, _y ), &wp );
InputMouseEnterEvent ne;
ne.special = _special;
ne.touchId = _touchId;
ne.x = wp.x;
ne.y = wp.y;
ne.pressure = _pressure;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse enter]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
handle = inputHandler->handleMouseEnter( ne );
picker->setPickerHandle( handle );
}
else
{
bool pickerHandle = picker->isPickerHandle();
handle = pickerHandle;
}
}
else
{
if( picker->isPickerPicked() == true )
{
picker->setPickerPicked( false );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _x, _y ), &wp );
InputMouseLeaveEvent ne;
ne.special = _special;
ne.touchId = _touchId;
ne.x = wp.x;
ne.y = wp.y;
ne.pressure = _pressure;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse leave]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
inputHandler->handleMouseLeave( ne );
}
}
}
else
{
if( picker->isPickerPicked() == true )
{
picker->setPickerPicked( false );
InputHandlerInterface * inputHandler = picker->getPickerInputHandler();
mt::vec2f wp;
m_arrow->calcPointClick( &desc.context, mt::vec2f( _x, _y ), &wp );
InputMouseLeaveEvent ne;
ne.special = _special;
ne.touchId = _touchId;
ne.x = wp.x;
ne.y = wp.y;
ne.pressure = _pressure;
LOGGER_INFO( "picker", "handle type '%s' name '%s' UID [%u] pos [%.4f;%.4f] [mouse leave]"
, MENGINE_MIXIN_DEBUG_TYPE( inputHandler )
, MENGINE_MIXIN_DEBUG_NAME( inputHandler )
, MENGINE_MIXIN_DEBUG_UID( inputHandler )
, ne.x
, ne.y
);
inputHandler->handleMouseLeave( ne );
}
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////
bool PickerService::getStates_( float _x, float _y, VectorPickerStates * const _states ) const
{
MENGINE_ASSERTION_FATAL( _states->empty() );
if( m_arrow == nullptr )
{
return false;
}
if( m_scene == nullptr )
{
return false;
}
if( m_camera == nullptr )
{
return false;
}
if( m_block == true )
{
return true;
}
VectorPickerStates statesAux;
this->fillStates_( &statesAux );
const Resolution & contentResolution = APPLICATION_SERVICE()
->getContentResolution();
mt::vec2f adapt_screen_position;
m_arrow->adaptScreenPosition_( mt::vec2f( _x, _y ), &adapt_screen_position );
for( const PickerStateDesc & desc : statesAux )
{
PickerInterface * picker = desc.picker;
if( picker->isPickerEnable() == false )
{
continue;
}
bool picked = picker->pick( adapt_screen_position, &desc.context, contentResolution, m_arrow );
if( picked == false )
{
continue;
}
_states->push_back( desc );
}
return true;
}
//////////////////////////////////////////////////////////////////////////
}
| 30.089385
| 172
| 0.453398
|
irov
|
5b2a210b884266a9629387e4c463dc844adb3705
| 1,182
|
cpp
|
C++
|
examples/twiscanner/main.cpp
|
2ni/aprico
|
0b421a1dcf523474d17df06ab5467ef5c369a6cd
|
[
"MIT"
] | 1
|
2021-03-02T19:54:04.000Z
|
2021-03-02T19:54:04.000Z
|
examples/twiscanner/main.cpp
|
2ni/aprico
|
0b421a1dcf523474d17df06ab5467ef5c369a6cd
|
[
"MIT"
] | null | null | null |
examples/twiscanner/main.cpp
|
2ni/aprico
|
0b421a1dcf523474d17df06ab5467ef5c369a6cd
|
[
"MIT"
] | null | null | null |
#include <util/delay.h>
#include <avr/io.h>
#include "uart.h"
#include "twi.h"
#include "mcu.h"
int main(void) {
mcu_init();
twi_init();
DL("start scanning");
for (uint8_t addr = 0; addr<128; addr+=1) {
// DF("0x%02x: %s\n", addr, twi_start(addr) ? "-" : "yes");
if (!twi_start(addr)) {
DF("0x%02x\n", addr);
}
twi_stop();
}
DL("done.");
uint8_t data[3] = {0};
// read raw data from an SHT20
// see https://github.com/DFRobot/DFRobot_SHT20/blob/master/DFRobot_SHT20.cpp
uint8_t status = twi_read_bytes(0x40, data, 0xe3, 2); // read temp hold
if (status == 0) {
uint32_t raw = ((uint32_t)data[0]<<8) | (uint32_t)data[1];
char out[6];
// DF("%u %u\n", data[0], data[1]);
// DF("temp raw: %lu\n", raw_temp);
raw *= 17572;
raw /= 65536;
raw -= 4685;
uart_u2c(out, raw, 2);
DF("temp: %sC\n", out);
twi_read_bytes(0x40, data, 0xe5, 2); // read humidity hold
raw = ((uint32_t)data[0]<<8) | (uint32_t)data[1];
raw *= 12500;
raw /= 65536;
raw -= 6;
uart_u2c(out, raw, 2);
DF("humidity: %s%%\n", out);
} else {
DF(NOK("sensor SHT20 not found:") " %u\n", status);
}
}
| 22.730769
| 79
| 0.551607
|
2ni
|
5b334ef7343ddfff5c1f6c39173f40733da94898
| 536
|
cpp
|
C++
|
Inheritance/hierarchical.cpp
|
git-elliot/competitive_programming_codes
|
b8b5646ae5074b453e7f1af982af174b9c4138e1
|
[
"MIT"
] | 1
|
2021-06-20T17:28:54.000Z
|
2021-06-20T17:28:54.000Z
|
Inheritance/hierarchical.cpp
|
git-elliot/competitive_programming_codes
|
b8b5646ae5074b453e7f1af982af174b9c4138e1
|
[
"MIT"
] | null | null | null |
Inheritance/hierarchical.cpp
|
git-elliot/competitive_programming_codes
|
b8b5646ae5074b453e7f1af982af174b9c4138e1
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
//Hierarchical inheritance is defined as the process of deriving more than one class from a base class.
class Shape{
public:
int a = 10;
int b = 20;
};
class Rectange : public Shape{
public:
int area(){
return a*b;
}
};
class Triangle : public Shape{
public:
float area(){
return 0.5*a*b;
}
};
int main(){
Rectange rect;
cout<<"Area of Rect: "<<rect.area()<<endl;
Triangle tri;
cout<<"Area of Triangle: "<<tri.area()<<endl;
}
| 18.482759
| 103
| 0.602612
|
git-elliot
|
5b35e72d4a64ecc037629c4f870702465262d8e3
| 156
|
cpp
|
C++
|
examples/core/static/application/main.cpp
|
smeualex/cmake-examples
|
d443a5d9359565f474f56f0251a511544b2168eb
|
[
"MIT"
] | 979
|
2019-03-10T15:31:09.000Z
|
2022-03-26T03:58:49.000Z
|
examples/core/static/application/main.cpp
|
smeualex/cmake-examples
|
d443a5d9359565f474f56f0251a511544b2168eb
|
[
"MIT"
] | 9
|
2019-03-11T13:05:08.000Z
|
2021-09-27T21:27:07.000Z
|
examples/core/static/application/main.cpp
|
smeualex/cmake-examples
|
d443a5d9359565f474f56f0251a511544b2168eb
|
[
"MIT"
] | 56
|
2019-03-11T07:05:54.000Z
|
2022-02-23T14:00:59.000Z
|
#include <iostream>
#include "calculator-static/calculator.h"
int main(int argc, char** argv)
{
std::cout << calc::square(4) << "\n";
return 0;
}
| 15.6
| 41
| 0.621795
|
smeualex
|
5b376114194c63acba15113fcd514aec00167d28
| 492
|
hpp
|
C++
|
FootCommander.hpp
|
Revertigo/wargame-b
|
8cd4591586b275923c38047c480a61529cc199dc
|
[
"MIT"
] | null | null | null |
FootCommander.hpp
|
Revertigo/wargame-b
|
8cd4591586b275923c38047c480a61529cc199dc
|
[
"MIT"
] | null | null | null |
FootCommander.hpp
|
Revertigo/wargame-b
|
8cd4591586b275923c38047c480a61529cc199dc
|
[
"MIT"
] | null | null | null |
//
// Created by osboxes on 5/19/20.
//
#ifndef WARGAME_A_FOOTCOMMANDER_HPP
#define WARGAME_A_FOOTCOMMANDER_HPP
#include "FootSoldier.hpp"
class FootCommander : public FootSoldier {
using FootSoldier::FootSoldier;
static const int DMG = 20;
static const int HP = 150;
protected:
void act(pair<int, int> src, vector<vector<Soldier *>> &board) override;
public:
FootCommander(int player): FootSoldier(player, HP, "FC", DMG){}
};
#endif //WARGAME_A_FOOTCOMMANDER_HPP
| 19.68
| 76
| 0.721545
|
Revertigo
|
5b38ab5fa55a82fcad14eb97c0489a7ae842c601
| 14,132
|
cpp
|
C++
|
test/input_cases/csp_financial_defaults.cpp
|
JordanMalan/ssc
|
cadb7a9f3183d63c600b5c33f53abced35b6b319
|
[
"BSD-3-Clause"
] | 61
|
2017-08-09T15:10:59.000Z
|
2022-02-15T21:45:31.000Z
|
test/input_cases/csp_financial_defaults.cpp
|
JordanMalan/ssc
|
cadb7a9f3183d63c600b5c33f53abced35b6b319
|
[
"BSD-3-Clause"
] | 462
|
2017-07-31T21:26:46.000Z
|
2022-03-30T22:53:50.000Z
|
test/input_cases/csp_financial_defaults.cpp
|
JordanMalan/ssc
|
cadb7a9f3183d63c600b5c33f53abced35b6b319
|
[
"BSD-3-Clause"
] | 73
|
2017-08-24T17:39:31.000Z
|
2022-03-28T08:37:47.000Z
|
#include "../input_cases/code_generator_utilities.h"
/**
* Default parameters for the PPA singleowner (utility) financial model
*/
ssc_data_t singleowner_defaults()
{
ssc_data_t data = ssc_data_create();
ssc_data_set_number(data, "analysis_period", 25);
ssc_number_t p_federal_tax_rate[1] = { 21 };
ssc_data_set_array(data, "federal_tax_rate", p_federal_tax_rate, 1);
ssc_number_t p_state_tax_rate[1] = { 7 };
ssc_data_set_array(data, "state_tax_rate", p_state_tax_rate, 1);
ssc_data_set_number(data, "property_tax_rate", 0);
ssc_data_set_number(data, "prop_tax_cost_assessed_percent", 100);
ssc_data_set_number(data, "prop_tax_assessed_decline", 0);
ssc_data_set_number(data, "real_discount_rate", 6.4000000953674316);
ssc_data_set_number(data, "inflation_rate", 2.5);
ssc_data_set_number(data, "insurance_rate", 0.5);
ssc_data_set_number(data, "system_capacity", 99899.9921875);
ssc_number_t p_om_fixed[1] = { 0 };
ssc_data_set_array(data, "om_fixed", p_om_fixed, 1);
ssc_data_set_number(data, "om_fixed_escal", 0);
ssc_number_t p_om_production[1] = { 4 };
ssc_data_set_array(data, "om_production", p_om_production, 1);
ssc_data_set_number(data, "om_production_escal", 0);
ssc_number_t p_om_capacity[1] = { 66 };
ssc_data_set_array(data, "om_capacity", p_om_capacity, 1);
ssc_data_set_number(data, "om_capacity_escal", 0);
ssc_number_t p_om_fuel_cost[1] = { 0 };
ssc_data_set_array(data, "om_fuel_cost", p_om_fuel_cost, 1);
ssc_data_set_number(data, "om_fuel_cost_escal", 0);
ssc_number_t p_om_batt_replacement_cost[1] = { 0 };
ssc_data_set_array(data, "om_batt_replacement_cost", p_om_batt_replacement_cost, 1);
ssc_data_set_number(data, "om_replacement_cost_escal", 0);
ssc_data_set_number(data, "itc_fed_amount", 0);
ssc_data_set_number(data, "itc_fed_amount_deprbas_fed", 1);
ssc_data_set_number(data, "itc_fed_amount_deprbas_sta", 1);
ssc_data_set_number(data, "itc_sta_amount", 0);
ssc_data_set_number(data, "itc_sta_amount_deprbas_fed", 0);
ssc_data_set_number(data, "itc_sta_amount_deprbas_sta", 0);
ssc_data_set_number(data, "itc_fed_percent", 30);
ssc_data_set_number(data, "itc_fed_percent_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "itc_fed_percent_deprbas_fed", 1);
ssc_data_set_number(data, "itc_fed_percent_deprbas_sta", 1);
ssc_data_set_number(data, "itc_sta_percent", 0);
ssc_data_set_number(data, "itc_sta_percent_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "itc_sta_percent_deprbas_fed", 0);
ssc_data_set_number(data, "itc_sta_percent_deprbas_sta", 0);
ssc_number_t p_ptc_fed_amount[1] = { 0 };
ssc_data_set_array(data, "ptc_fed_amount", p_ptc_fed_amount, 1);
ssc_data_set_number(data, "ptc_fed_term", 10);
ssc_data_set_number(data, "ptc_fed_escal", 0);
ssc_number_t p_ptc_sta_amount[1] = { 0 };
ssc_data_set_array(data, "ptc_sta_amount", p_ptc_sta_amount, 1);
ssc_data_set_number(data, "ptc_sta_term", 10);
ssc_data_set_number(data, "ptc_sta_escal", 0);
ssc_data_set_number(data, "ibi_fed_amount", 0);
ssc_data_set_number(data, "ibi_fed_amount_tax_fed", 1);
ssc_data_set_number(data, "ibi_fed_amount_tax_sta", 1);
ssc_data_set_number(data, "ibi_fed_amount_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_fed_amount_deprbas_sta", 0);
ssc_data_set_number(data, "ibi_sta_amount", 0);
ssc_data_set_number(data, "ibi_sta_amount_tax_fed", 1);
ssc_data_set_number(data, "ibi_sta_amount_tax_sta", 1);
ssc_data_set_number(data, "ibi_sta_amount_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_sta_amount_deprbas_sta", 0);
ssc_data_set_number(data, "ibi_uti_amount", 0);
ssc_data_set_number(data, "ibi_uti_amount_tax_fed", 1);
ssc_data_set_number(data, "ibi_uti_amount_tax_sta", 1);
ssc_data_set_number(data, "ibi_uti_amount_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_uti_amount_deprbas_sta", 0);
ssc_data_set_number(data, "ibi_oth_amount", 0);
ssc_data_set_number(data, "ibi_oth_amount_tax_fed", 1);
ssc_data_set_number(data, "ibi_oth_amount_tax_sta", 1);
ssc_data_set_number(data, "ibi_oth_amount_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_oth_amount_deprbas_sta", 0);
ssc_data_set_number(data, "ibi_fed_percent", 0);
ssc_data_set_number(data, "ibi_fed_percent_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "ibi_fed_percent_tax_fed", 1);
ssc_data_set_number(data, "ibi_fed_percent_tax_sta", 1);
ssc_data_set_number(data, "ibi_fed_percent_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_fed_percent_deprbas_sta", 0);
ssc_data_set_number(data, "ibi_sta_percent", 0);
ssc_data_set_number(data, "ibi_sta_percent_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "ibi_sta_percent_tax_fed", 1);
ssc_data_set_number(data, "ibi_sta_percent_tax_sta", 1);
ssc_data_set_number(data, "ibi_sta_percent_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_sta_percent_deprbas_sta", 0);
ssc_data_set_number(data, "ibi_uti_percent", 0);
ssc_data_set_number(data, "ibi_uti_percent_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "ibi_uti_percent_tax_fed", 1);
ssc_data_set_number(data, "ibi_uti_percent_tax_sta", 1);
ssc_data_set_number(data, "ibi_uti_percent_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_uti_percent_deprbas_sta", 0);
ssc_data_set_number(data, "ibi_oth_percent", 0);
ssc_data_set_number(data, "ibi_oth_percent_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "ibi_oth_percent_tax_fed", 1);
ssc_data_set_number(data, "ibi_oth_percent_tax_sta", 1);
ssc_data_set_number(data, "ibi_oth_percent_deprbas_fed", 0);
ssc_data_set_number(data, "ibi_oth_percent_deprbas_sta", 0);
ssc_data_set_number(data, "cbi_fed_amount", 0);
ssc_data_set_number(data, "cbi_fed_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "cbi_fed_tax_fed", 1);
ssc_data_set_number(data, "cbi_fed_tax_sta", 1);
ssc_data_set_number(data, "cbi_fed_deprbas_fed", 0);
ssc_data_set_number(data, "cbi_fed_deprbas_sta", 0);
ssc_data_set_number(data, "cbi_sta_amount", 0);
ssc_data_set_number(data, "cbi_sta_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "cbi_sta_tax_fed", 1);
ssc_data_set_number(data, "cbi_sta_tax_sta", 1);
ssc_data_set_number(data, "cbi_sta_deprbas_fed", 0);
ssc_data_set_number(data, "cbi_sta_deprbas_sta", 0);
ssc_data_set_number(data, "cbi_uti_amount", 0);
ssc_data_set_number(data, "cbi_uti_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "cbi_uti_tax_fed", 1);
ssc_data_set_number(data, "cbi_uti_tax_sta", 1);
ssc_data_set_number(data, "cbi_uti_deprbas_fed", 0);
ssc_data_set_number(data, "cbi_uti_deprbas_sta", 0);
ssc_data_set_number(data, "cbi_oth_amount", 0);
ssc_data_set_number(data, "cbi_oth_maxvalue", 9.9999996802856925e+37);
ssc_data_set_number(data, "cbi_oth_tax_fed", 1);
ssc_data_set_number(data, "cbi_oth_tax_sta", 1);
ssc_data_set_number(data, "cbi_oth_deprbas_fed", 0);
ssc_data_set_number(data, "cbi_oth_deprbas_sta", 0);
ssc_number_t p_pbi_fed_amount[1] = { 0 };
ssc_data_set_array(data, "pbi_fed_amount", p_pbi_fed_amount, 1);
ssc_data_set_number(data, "pbi_fed_term", 0);
ssc_data_set_number(data, "pbi_fed_escal", 0);
ssc_data_set_number(data, "pbi_fed_tax_fed", 1);
ssc_data_set_number(data, "pbi_fed_tax_sta", 1);
ssc_number_t p_pbi_sta_amount[1] = { 0 };
ssc_data_set_array(data, "pbi_sta_amount", p_pbi_sta_amount, 1);
ssc_data_set_number(data, "pbi_sta_term", 0);
ssc_data_set_number(data, "pbi_sta_escal", 0);
ssc_data_set_number(data, "pbi_sta_tax_fed", 1);
ssc_data_set_number(data, "pbi_sta_tax_sta", 1);
ssc_number_t p_pbi_uti_amount[1] = { 0 };
ssc_data_set_array(data, "pbi_uti_amount", p_pbi_uti_amount, 1);
ssc_data_set_number(data, "pbi_uti_term", 0);
ssc_data_set_number(data, "pbi_uti_escal", 0);
ssc_data_set_number(data, "pbi_uti_tax_fed", 1);
ssc_data_set_number(data, "pbi_uti_tax_sta", 1);
ssc_number_t p_pbi_oth_amount[1] = { 0 };
ssc_data_set_array(data, "pbi_oth_amount", p_pbi_oth_amount, 1);
ssc_data_set_number(data, "pbi_oth_term", 0);
ssc_data_set_number(data, "pbi_oth_escal", 0);
ssc_data_set_number(data, "pbi_oth_tax_fed", 1);
ssc_data_set_number(data, "pbi_oth_tax_sta", 1);
ssc_number_t p_degradation[1] = { 0 };
ssc_data_set_array(data, "degradation", p_degradation, 1);
ssc_data_set_number(data, "loan_moratorium", 0);
ssc_data_set_number(data, "system_use_recapitalization", 0);
ssc_data_set_number(data, "system_use_lifetime_output", 0);
ssc_data_set_number(data, "total_installed_cost", 562201472);
ssc_data_set_number(data, "reserves_interest", 1.75);
ssc_data_set_number(data, "equip1_reserve_cost", 0);
ssc_data_set_number(data, "equip1_reserve_freq", 12);
ssc_data_set_number(data, "equip2_reserve_cost", 0);
ssc_data_set_number(data, "equip2_reserve_freq", 15);
ssc_data_set_number(data, "equip3_reserve_cost", 0);
ssc_data_set_number(data, "equip3_reserve_freq", 3);
ssc_data_set_number(data, "equip_reserve_depr_sta", 0);
ssc_data_set_number(data, "equip_reserve_depr_fed", 0);
ssc_data_set_number(data, "salvage_percentage", 0);
ssc_data_set_number(data, "ppa_soln_mode", 0);
ssc_number_t p_ppa_price_input[1] = { 0.13 };
ssc_data_set_array(data, "ppa_price_input", p_ppa_price_input, 1);
ssc_data_set_number(data, "cp_capacity_payment_esc", 0);
ssc_data_set_number(data, "cp_capacity_payment_type", 0);
ssc_data_set_number(data, "cp_system_nameplate", 0);
ssc_data_set_number(data, "cp_battery_nameplate", 0);
ssc_data_set_array(data, "cp_capacity_credit_percent", p_ppa_price_input, 1);
ssc_data_set_array(data, "cp_capacity_payment_amount", p_ppa_price_input, 1);
ssc_data_set_number(data, "ppa_escalation", 1);
ssc_data_set_number(data, "construction_financing_cost", 28110074);
ssc_data_set_number(data, "term_tenor", 18);
ssc_data_set_number(data, "term_int_rate", 7);
ssc_data_set_number(data, "dscr", 1.2999999523162842);
ssc_data_set_number(data, "dscr_reserve_months", 6);
ssc_data_set_number(data, "debt_percent", 50);
ssc_data_set_number(data, "debt_option", 1);
ssc_data_set_number(data, "payment_option", 0);
ssc_data_set_number(data, "cost_debt_closing", 450000);
ssc_data_set_number(data, "cost_debt_fee", 2.75);
ssc_data_set_number(data, "months_working_reserve", 6);
ssc_data_set_number(data, "months_receivables_reserve", 0);
ssc_data_set_number(data, "cost_other_financing", 0);
ssc_data_set_number(data, "flip_target_percent", 11);
ssc_data_set_number(data, "flip_target_year", 20);
ssc_data_set_number(data, "depr_alloc_macrs_5_percent", 90);
ssc_data_set_number(data, "depr_alloc_macrs_15_percent", 1.5);
ssc_data_set_number(data, "depr_alloc_sl_5_percent", 0);
ssc_data_set_number(data, "depr_alloc_sl_15_percent", 2.5);
ssc_data_set_number(data, "depr_alloc_sl_20_percent", 3);
ssc_data_set_number(data, "depr_alloc_sl_39_percent", 0);
ssc_data_set_number(data, "depr_alloc_custom_percent", 0);
ssc_number_t p_depr_custom_schedule[1] = { 0 };
ssc_data_set_array(data, "depr_custom_schedule", p_depr_custom_schedule, 1);
ssc_data_set_number(data, "depr_bonus_sta", 0);
ssc_data_set_number(data, "depr_bonus_sta_macrs_5", 1);
ssc_data_set_number(data, "depr_bonus_sta_macrs_15", 1);
ssc_data_set_number(data, "depr_bonus_sta_sl_5", 0);
ssc_data_set_number(data, "depr_bonus_sta_sl_15", 0);
ssc_data_set_number(data, "depr_bonus_sta_sl_20", 0);
ssc_data_set_number(data, "depr_bonus_sta_sl_39", 0);
ssc_data_set_number(data, "depr_bonus_sta_custom", 0);
ssc_data_set_number(data, "depr_bonus_fed", 0);
ssc_data_set_number(data, "depr_bonus_fed_macrs_5", 1);
ssc_data_set_number(data, "depr_bonus_fed_macrs_15", 1);
ssc_data_set_number(data, "depr_bonus_fed_sl_5", 0);
ssc_data_set_number(data, "depr_bonus_fed_sl_15", 0);
ssc_data_set_number(data, "depr_bonus_fed_sl_20", 0);
ssc_data_set_number(data, "depr_bonus_fed_sl_39", 0);
ssc_data_set_number(data, "depr_bonus_fed_custom", 0);
ssc_data_set_number(data, "depr_itc_sta_macrs_5", 1);
ssc_data_set_number(data, "depr_itc_sta_macrs_15", 0);
ssc_data_set_number(data, "depr_itc_sta_sl_5", 0);
ssc_data_set_number(data, "depr_itc_sta_sl_15", 0);
ssc_data_set_number(data, "depr_itc_sta_sl_20", 0);
ssc_data_set_number(data, "depr_itc_sta_sl_39", 0);
ssc_data_set_number(data, "depr_itc_sta_custom", 0);
ssc_data_set_number(data, "depr_itc_fed_macrs_5", 1);
ssc_data_set_number(data, "depr_itc_fed_macrs_15", 0);
ssc_data_set_number(data, "depr_itc_fed_sl_5", 0);
ssc_data_set_number(data, "depr_itc_fed_sl_15", 0);
ssc_data_set_number(data, "depr_itc_fed_sl_20", 0);
ssc_data_set_number(data, "depr_itc_fed_sl_39", 0);
ssc_data_set_number(data, "depr_itc_fed_custom", 0);
ssc_data_set_number(data, "pbi_fed_for_ds", 0);
ssc_data_set_number(data, "pbi_sta_for_ds", 0);
ssc_data_set_number(data, "pbi_uti_for_ds", 0);
ssc_data_set_number(data, "pbi_oth_for_ds", 0);
ssc_data_set_number(data, "depr_stabas_method", 1);
ssc_data_set_number(data, "depr_fedbas_method", 1);
return data;
}
/**
* Default data for iph_to_lcoefcr
*/
void convert_and_adjust_fixed_charge(ssc_data_t& data)
{
ssc_data_set_number(data, "electricity_rate", 0.059999998658895493);
ssc_data_set_number(data, "fixed_operating_cost", 103758.203125);
}
/**
* Default data for lcoefcr
*/
void fixed_charge_rate_default(ssc_data_t& data)
{
ssc_data_set_number(data, "capital_cost", 7263074);
ssc_data_set_number(data, "variable_operating_cost", 0.0010000000474974513);
ssc_data_set_number(data, "fixed_charge_rate", 0.10807877779006958);
}
| 54.563707
| 88
| 0.755095
|
JordanMalan
|
5b46ab1a6aff59cd4e94dd3da52da4c678152257
| 1,801
|
hh
|
C++
|
src/server/world/world.hh
|
TheBenPerson/Game
|
824b2240e95529b735b4d8055a541c77102bb5dc
|
[
"MIT"
] | null | null | null |
src/server/world/world.hh
|
TheBenPerson/Game
|
824b2240e95529b735b4d8055a541c77102bb5dc
|
[
"MIT"
] | null | null | null |
src/server/world/world.hh
|
TheBenPerson/Game
|
824b2240e95529b735b4d8055a541c77102bb5dc
|
[
"MIT"
] | null | null | null |
/*
*
* Game Development Build
* https://github.com/TheBenPerson/Game
*
* Copyright (C) 2016-2018 Ben Stockett <thebenstockett@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef GAME_SERVER_WORLD
#define GAME_SERVER_WORLD
#include <stdint.h>
#include "client.hh"
#include "nodelist.hh"
#include "point.hh"
#include "tile.hh"
class World {
public:
static World *defaultWorld;
static NodeList worlds;
static World* get(char *name);
static World* newWorld(char *name);
static void sendWorld(Client *client);
Tile **tiles;
unsigned int width;
unsigned int height;
NodeList clients;
NodeList entities;
~World();
Tile* getTile(Point *pos);
void setTile(Point *pos, uint8_t id);
private:
char *name;
};
#endif
| 26.880597
| 81
| 0.738479
|
TheBenPerson
|
5b4808b262aef707ea7a7c1d8ebef6dda219df62
| 518
|
cpp
|
C++
|
CodeForces/fair_playoff.cpp
|
PieroNarciso/cprogramming
|
d3a53ce2afce6f853e0b7cc394190d5be6427902
|
[
"MIT"
] | 2
|
2021-05-22T17:47:01.000Z
|
2021-05-27T17:10:58.000Z
|
CodeForces/fair_playoff.cpp
|
PieroNarciso/cprogramming
|
d3a53ce2afce6f853e0b7cc394190d5be6427902
|
[
"MIT"
] | null | null | null |
CodeForces/fair_playoff.cpp
|
PieroNarciso/cprogramming
|
d3a53ce2afce6f853e0b7cc394190d5be6427902
|
[
"MIT"
] | null | null | null |
// https://codeforces.com/contest/1535/problem/A
#include <bits/stdc++.h>
using namespace std;
int s1, s2, s3, s4;
void solve() {
cin >> s1 >> s2 >> s3 >> s4;
int maxFirst = max(s1, s2);
int maxSec = max(s3, s4);
if ((maxFirst > s3 || maxFirst > s4) && (maxSec > s1 || maxSec > s2)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
int main(int argc, const char** argv) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| 17.862069
| 72
| 0.557915
|
PieroNarciso
|
5b49d4572a0c31abe9a58c95e07b28d9644d623f
| 1,017
|
hpp
|
C++
|
include/boost/simd/function/definition/divfix.hpp
|
yaeldarmon/boost.simd
|
561316cc54bdc6353ca78f3b6d7e9120acd11144
|
[
"BSL-1.0"
] | null | null | null |
include/boost/simd/function/definition/divfix.hpp
|
yaeldarmon/boost.simd
|
561316cc54bdc6353ca78f3b6d7e9120acd11144
|
[
"BSL-1.0"
] | null | null | null |
include/boost/simd/function/definition/divfix.hpp
|
yaeldarmon/boost.simd
|
561316cc54bdc6353ca78f3b6d7e9120acd11144
|
[
"BSL-1.0"
] | null | null | null |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
@copyright 2016 J.T.Lapreste
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_DEFINITION_DIVFIX_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_DEFINITION_DIVFIX_HPP_INCLUDED
#include <boost/simd/config.hpp>
#include <boost/dispatch/function/make_callable.hpp>
#include <boost/dispatch/hierarchy/functions.hpp>
#include <boost/simd/detail/dispatch.hpp>
namespace boost { namespace simd
{
namespace tag
{
BOOST_DISPATCH_MAKE_TAG(ext, divfix_, boost::dispatch::elementwise_<divfix_>);
}
namespace ext
{
BOOST_DISPATCH_FUNCTION_DECLARATION(tag, divfix_);
}
BOOST_DISPATCH_CALLABLE_DEFINITION(tag::divfix_,divfix);
} }
#endif
| 26.763158
| 100
| 0.621436
|
yaeldarmon
|
5b4ad5e9c00c8c56a79d05f88a8e6c79b366f86b
| 485
|
c++
|
C++
|
Hackerrank/Pairs [Medium].c++
|
ammar-sayed-taha/problem-solving
|
9677a738c0cc30078f6450f40fcc26ba2a379a8b
|
[
"MIT"
] | 1
|
2020-02-20T00:04:54.000Z
|
2020-02-20T00:04:54.000Z
|
Hackerrank/Pairs [Medium].c++
|
ammar-sayed-taha/Problem-Solving
|
c3ef98b8b0ebfbcc31d45990822b81a9dc549fe8
|
[
"MIT"
] | null | null | null |
Hackerrank/Pairs [Medium].c++
|
ammar-sayed-taha/Problem-Solving
|
c3ef98b8b0ebfbcc31d45990822b81a9dc549fe8
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the pairs function below.
int pairs(int k, vector<int> arr) {
sort(arr.begin(), arr.end()); // O(nlgn)
int counter=0;
for(auto i = 0; i < arr.size(); i++){ // O(n)
for(auto j=i+1; j<arr.size(); j++){ // O(n)
if(abs(arr[i] - arr[j]) == k)
counter++;
if(abs(arr[i] - arr[j]) > k) break;
}
}
return counter;
}
| 20.208333
| 51
| 0.503093
|
ammar-sayed-taha
|
5b5fa1086a789e5a089b07233585014982484c16
| 5,098
|
hpp
|
C++
|
viennacl/ocl/device_utils.hpp
|
yuchengs/viennacl-dev
|
99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa
|
[
"MIT"
] | 224
|
2015-02-15T21:50:13.000Z
|
2022-01-14T18:27:03.000Z
|
viennacl/ocl/device_utils.hpp
|
yuchengs/viennacl-dev
|
99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa
|
[
"MIT"
] | 189
|
2015-01-09T17:08:04.000Z
|
2021-06-04T06:23:22.000Z
|
viennacl/ocl/device_utils.hpp
|
yuchengs/viennacl-dev
|
99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa
|
[
"MIT"
] | 84
|
2015-01-15T14:06:13.000Z
|
2022-01-23T14:51:17.000Z
|
#ifndef VIENNACL_OCL_DEVICE_UTILS_HPP_
#define VIENNACL_OCL_DEVICE_UTILS_HPP_
/* =========================================================================
Copyright (c) 2010-2016, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/** @file viennacl/ocl/device_utils.hpp
@brief Various utility implementations for dispatching with respect to the different devices available on the market.
*/
#define VIENNACL_OCL_MAX_DEVICE_NUM 8
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#include <stddef.h>
#include <map>
#include <string>
#include "viennacl/forwards.h"
namespace viennacl
{
namespace ocl
{
enum vendor_id
{
beignet_id = 358,
intel_id = 32902,
nvidia_id = 4318,
amd_id = 4098,
unknown_id = 0
};
//Architecture Family
enum device_architecture_family
{
//NVidia
tesla = 0,
fermi,
kepler,
maxwell,
//AMD
evergreen,
northern_islands,
southern_islands,
volcanic_islands,
unknown
};
inline device_architecture_family get_architecture_family(cl_uint vendor_id, std::string const & name)
{
/*-NVidia-*/
if (vendor_id==nvidia_id)
{
//GeForce
vcl_size_t found=0;
if ((found= name.find("GeForce",0)) != std::string::npos)
{
if ((found = name.find_first_of("123456789", found)) != std::string::npos)
{
switch (name[found])
{
case '2' : return tesla;
case '3' : return tesla;
case '4' : return fermi;
case '5' : return fermi;
case '6' : return kepler;
case '7' : if (name[found+1] == '5')
return maxwell; // GeForce 750 (Ti) are Maxwell-based on desktop GPUs.
return kepler;
case '8' : if (name[found+3] == '0') // Geforce 8600 and friends
return tesla;
return kepler; // high-end mobile GPUs tend to be Kepler, low-end GPUs are Maxwell. What a mess. Better be conservative here and pick Kepler.
case '9' : if (name[found+3] == '0') // Geforce 9600 and friends
return tesla;
return maxwell; // GeForce 980, etc.
default: return unknown;
}
}
else
return unknown;
}
//Tesla
else if ((found = name.find("Tesla",0)) != std::string::npos)
{
if ((found = name.find_first_of("CMK", found)) != std::string::npos)
{
switch (name[found])
{
case 'C' : return fermi;
case 'M' : return fermi;
case 'K' : return kepler;
default : return unknown;
}
}
else
return unknown;
}
else
return unknown;
}
/*-AMD-*/
else if (vendor_id==amd_id)
{
#define VIENNACL_DEVICE_MAP(device,arch)if (name.find(device,0)!=std::string::npos) return arch;
//Evergreen
VIENNACL_DEVICE_MAP("Cedar",evergreen);
VIENNACL_DEVICE_MAP("Redwood",evergreen);
VIENNACL_DEVICE_MAP("Juniper",evergreen);
VIENNACL_DEVICE_MAP("Cypress",evergreen);
VIENNACL_DEVICE_MAP("Hemlock",evergreen);
//NorthernIslands
VIENNACL_DEVICE_MAP("Caicos",northern_islands);
VIENNACL_DEVICE_MAP("Turks",northern_islands);
VIENNACL_DEVICE_MAP("Barts",northern_islands);
VIENNACL_DEVICE_MAP("Cayman",northern_islands);
VIENNACL_DEVICE_MAP("Antilles",northern_islands);
//SouthernIslands
VIENNACL_DEVICE_MAP("Cape",southern_islands);
VIENNACL_DEVICE_MAP("Bonaire",southern_islands);
VIENNACL_DEVICE_MAP("Pitcairn",southern_islands);
VIENNACL_DEVICE_MAP("Curacao",southern_islands);
VIENNACL_DEVICE_MAP("Tahiti",southern_islands);
VIENNACL_DEVICE_MAP("Malta",southern_islands);
VIENNACL_DEVICE_MAP("Trinidad",southern_islands);
VIENNACL_DEVICE_MAP("Tobago",southern_islands);
VIENNACL_DEVICE_MAP("Oland",southern_islands);
//VolcanicIslands
VIENNACL_DEVICE_MAP("Hawaii",volcanic_islands);
VIENNACL_DEVICE_MAP("Vesuvius",volcanic_islands);
VIENNACL_DEVICE_MAP("Tonga",volcanic_islands);
VIENNACL_DEVICE_MAP("Antigua",volcanic_islands);
VIENNACL_DEVICE_MAP("Grenada",volcanic_islands);
VIENNACL_DEVICE_MAP("Fiji",volcanic_islands);
//APUs (map to closest hardware architecture)
VIENNACL_DEVICE_MAP("Scrapper",northern_islands);
VIENNACL_DEVICE_MAP("Devastator",northern_islands);
#undef VIENNACL_DEVICE_MAP
return unknown;
}
/*-Other-*/
else
return unknown;
}
}
} //namespace viennacl
#endif
| 26.414508
| 161
| 0.624166
|
yuchengs
|
5b6157f723c18eed98ad8e405446ae2b433f388a
| 868
|
cpp
|
C++
|
.LHP/.Lop10/.O.L.P/.T.Vinh/OL3/DAUXE/DAUXE/DAUXE.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop10/.O.L.P/.T.Vinh/OL3/DAUXE/DAUXE/DAUXE.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop10/.O.L.P/.T.Vinh/OL3/DAUXE/DAUXE/DAUXE.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#pragma warning(disable:4996)
#define maxN 101
#define maxL 121
#define empty '.'
#define block 'X'
typedef int maxn, maxl;
maxn n, L;
std::vector <maxl> a;
void Add(maxl &x) {
x = x - L + 1;
while (x > 0) {
a.push_back(std::min((maxl)L, x));
//std::cout << std::min(L, x) << '\n';
x -= (maxl)L;
}
x = 0;
}
void Prepare() {
std::cin >> n >> L;
char c;
maxl x = 0;
while (std::cin >> c) {
if (c == empty) x++;
if (c == block) Add(x);
}
Add(x);
}
void Process() {
std::sort(a.begin(), a.end());
maxl res = 0;
for (maxl i = 0; i < std::max((maxl)0, (maxl)a.size() - (maxl)n); i++)
res += a[i];
std::cout << res << '\n' << std::min((maxl)a.size(), (maxl)n);
}
int main() {
freopen("dauxe.inp", "r", stdin);
Prepare();
Process();
}
| 14
| 72
| 0.535714
|
sxweetlollipop2912
|
5b617b02df27c604edcbef53d1e78a5e445ff04b
| 1,546
|
cpp
|
C++
|
new folder/55.cpp
|
bprithiraj/DSA-CPsolvedproblemscode
|
4b3765e4afb26016fade1f1e526b36934583c668
|
[
"Apache-2.0"
] | null | null | null |
new folder/55.cpp
|
bprithiraj/DSA-CPsolvedproblemscode
|
4b3765e4afb26016fade1f1e526b36934583c668
|
[
"Apache-2.0"
] | null | null | null |
new folder/55.cpp
|
bprithiraj/DSA-CPsolvedproblemscode
|
4b3765e4afb26016fade1f1e526b36934583c668
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
using namespace std;
#define ll long long int
#define MP make_pair
#define PB push_back
long long int testcase()
{
long long int arr[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==1 && j==1)
continue;
cin>>arr[i][j];
}
}
map<ll,ll> m;
long double k=(arr[0][0]+arr[2][2])/2.0;
if(ceil(k)==floor(k))
m[k]++;
k=(arr[0][1]+arr[2][1])/2.0;
if(ceil(k)==floor(k))
m[k]++;
k=(arr[0][2]+arr[2][0])/2.0;
if(ceil(k)==floor(k))
m[k]++;
k=(arr[1][0]+arr[1][2])/2.0;
if(ceil(k)==floor(k))
m[k]++;
long long int a=0;
for(auto i:m)
{
a=max(a,i.second);
}
for(int i=0;i<3;i++)
{
if(arr[i][0]-arr[i][1]==arr[i][1]-arr[i][2])
a++;
}
for(int i=0;i<3;i++)
{
if(arr[0][i]-arr[1][i]==arr[1][i]-arr[2][i])
a++;
}
return a;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
long long int t;
cin>>t;
for(int i=1;i<=t;i++)
{
long long int ans=testcase();
cout<<"Case #"<<i<<": "<<ans;
cout<<"\n";
}
}
| 13.327586
| 52
| 0.487063
|
bprithiraj
|
5b6d3b36244ff88ef2574a5109f44e7677af00aa
| 1,355
|
cpp
|
C++
|
Broccoli/src/Broccoli/Renderer/Buffer.cpp
|
tross2552/broccoli
|
d7afc472e076fa801d0e7745e209553b73c34486
|
[
"Apache-2.0"
] | 1
|
2021-08-03T01:38:41.000Z
|
2021-08-03T01:38:41.000Z
|
Broccoli/src/Broccoli/Renderer/Buffer.cpp
|
tross2552/broccoli
|
d7afc472e076fa801d0e7745e209553b73c34486
|
[
"Apache-2.0"
] | null | null | null |
Broccoli/src/Broccoli/Renderer/Buffer.cpp
|
tross2552/broccoli
|
d7afc472e076fa801d0e7745e209553b73c34486
|
[
"Apache-2.0"
] | null | null | null |
#include "brclpch.h"
#include "Buffer.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLBuffer.h"
namespace brcl
{
std::unique_ptr<VertexBuffer> VertexBuffer::Create(uint32_t size)
{
switch (renderer::GetAPI())
{
case RendererAPI::API::None: BRCL_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_unique <OpenGLVertexBuffer>(size);
}
BRCL_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
std::unique_ptr<VertexBuffer> VertexBuffer::Create(float* vertices, uint32_t size)
{
switch (renderer::GetAPI())
{
case RendererAPI::API::None: BRCL_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_unique <OpenGLVertexBuffer>(vertices, size);
}
BRCL_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
std::unique_ptr<IndexBuffer> IndexBuffer::Create(uint32_t* indices, uint32_t size)
{
switch (renderer::GetAPI())
{
case RendererAPI::API::None: BRCL_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_unique<OpenGLIndexBuffer>(indices, size);
}
BRCL_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
}
| 29.456522
| 123
| 0.732841
|
tross2552
|
5b6fa607acf172b32aca9f7f553df46ba37ad09c
| 2,195
|
cpp
|
C++
|
SerialTesting/SerialHelper.cpp
|
jj9146/Arduino
|
bfee6d42067b342eb51cbe42bb3c2020f9c9c858
|
[
"MIT"
] | null | null | null |
SerialTesting/SerialHelper.cpp
|
jj9146/Arduino
|
bfee6d42067b342eb51cbe42bb3c2020f9c9c858
|
[
"MIT"
] | null | null | null |
SerialTesting/SerialHelper.cpp
|
jj9146/Arduino
|
bfee6d42067b342eb51cbe42bb3c2020f9c9c858
|
[
"MIT"
] | null | null | null |
/*
SerialHelper.cpp - Library for auto-magically determining
if a board is being powered by the USB port, and will halt
all attempts to connect to and send data over COM when
there is no computer/device to listen or respond.
*** For Arduino Nano boards ***
* NOTE: Requires a 10k resistor soldered between Pin 1 of the Micro USB jack and pin D12 on the
* arduino. Attach it to the shotsky diode directly below the USB jack (easiest to solder), and
* let it sit vertically along the left side of the Micro USB jack, with the top wire bent down and
* over to the 12 pin. You could put the entire resistor in shrink-wrap tubing, but there's really
* nothing to short on, so that might be a lost cause.
*/
#include "Arduino.h"
#include "SerialHelper.h"
SerialHelper::SerialHelper(int indicatorPin, int usbPowerPin, long COM_BPS)
{
pinMode(indicatorPin, OUTPUT);
pinMode(usbPowerPin, INPUT);
_serialIndicatorPin = indicatorPin;
_usbPowerPin = usbPowerPin;
_haveCOMConnection = false;
_COM_Speed = COM_BPS;
}
/*
* ConnectAndValidateUSBPower will look for power from the USB jack to be fed into D12
* If it finds power and can make the COM connection, then it'll set "_haveCOMConnection"
* to true, and return it as the response to the caller
*/
void SerialHelper::ConnectAndValidateUSBPower()
{
//Check pin 12 to see if we have a USB connection
int USBRead = digitalRead(_usbPowerPin);
if(USBRead == HIGH)
{
//Setup the connection
Serial.begin(_COM_Speed);
_haveCOMConnection = true;
//Setup the connection indicator pin
pinMode(_serialIndicatorPin, OUTPUT);
//Turn the indicator on
digitalWrite(_serialIndicatorPin, HIGH);
}
else
{
//We don't have a connection - bail
_haveCOMConnection = false;
}
//return _haveCOMConnection;
}
// Print text to COM port without a CrLf
void SerialHelper::PrintStr(String text)
{
if(_haveCOMConnection)
{
Serial.print(text);
}
}
// Print text to COM port with a CrLf
void SerialHelper::PrintStrLn(String text)
{
if(_haveCOMConnection)
{
Serial.println(text);
}
}
| 30.486111
| 100
| 0.69795
|
jj9146
|
ac93d08e920e7e3262ff43b035551fa9a6aaa854
| 5,889
|
cpp
|
C++
|
examples/chess/src/chess.cpp
|
KazDragon/munin
|
ca5ae77cf5f75f6604fddd1a39393fa6acb88769
|
[
"MIT"
] | 6
|
2017-07-15T10:16:20.000Z
|
2021-06-14T10:02:37.000Z
|
examples/chess/src/chess.cpp
|
KazDragon/munin
|
ca5ae77cf5f75f6604fddd1a39393fa6acb88769
|
[
"MIT"
] | 243
|
2017-05-01T19:27:07.000Z
|
2021-09-01T09:32:49.000Z
|
examples/chess/src/chess.cpp
|
KazDragon/munin
|
ca5ae77cf5f75f6604fddd1a39393fa6acb88769
|
[
"MIT"
] | 2
|
2019-07-16T00:29:43.000Z
|
2020-09-19T09:49:00.000Z
|
#include <munin/button.hpp>
#include <munin/compass_layout.hpp>
#include <munin/filled_box.hpp>
#include <munin/grid_layout.hpp>
#include <munin/image.hpp>
#include <munin/scroll_pane.hpp>
#include <munin/text_area.hpp>
#include <munin/view.hpp>
#include <munin/window.hpp>
#include <terminalpp/canvas.hpp>
#include <terminalpp/string.hpp>
#include <terminalpp/terminal.hpp>
#include <consolepp/console.hpp>
#include <boost/asio/io_context.hpp>
using namespace terminalpp::literals;
class terminal_reader
{
public:
explicit terminal_reader(munin::window &window)
: dispatcher_(window)
{
}
void operator()(terminalpp::tokens const &tokens)
{
for (auto const &token : tokens)
{
boost::apply_visitor(dispatcher_, token);
}
}
private:
struct event_dispatcher : public boost::static_visitor<>
{
explicit event_dispatcher(munin::window &window)
: window_(window)
{
}
template <class Event>
void operator()(Event const &event)
{
window_.event(event);
}
munin::window &window_;
};
event_dispatcher dispatcher_;
};
void schedule_read(
consolepp::console &console,
terminalpp::terminal &terminal,
terminal_reader &reader)
{
console.async_read(
[&](consolepp::bytes data)
{
terminal.read(reader) >> data;
schedule_read(console, terminal, reader);
});
}
auto make_board()
{
return munin::make_image({
{ "\\p-" " " "\\p+" " " "\\p-" " " "\\p+" " " "\\p-" "\\U265A " "\\p+" " " "\\p-" " " "\\p+" "\\U265C "_ets },
{ "\\p+" "\\U265F " "\\p-" "\\U265F " "\\p+" " " "\\p-" " " "\\p+" " " "\\p-" "\\U265F " "\\p+" "\\U265F " "\\p-" "\\U265F "_ets },
{ "\\p-" " " "\\p+" "\\U265B " "\\p-" " " "\\p+" " " "\\p-" "\\U265F " "\\p+" " " "\\p-" " " "\\p+" " "_ets },
{ "\\p+" " " "\\p-" " " "\\p+" " " "\\p-" "\\U265F " "\\p+" "\\U2659 " "\\p-" " " "\\p+" " " "\\p-" " "_ets },
{ "\\p-" " " "\\p+" " " "\\p-" " " "\\p+" "\\U2655 " "\\p-" " " "\\p+" "\\U2659 " "\\p-" " " "\\p+" " "_ets },
{ "\\p+" "\\U2659 " "\\p-" "\\U2659 " "\\p+" " " "\\p-" " " "\\p+" " " "\\p-" " " "\\p+" " " "\\p-" " "_ets },
{ "\\p-" " " "\\p+" " " "\\p-" " " "\\p+" " " "\\p-" " " "\\p+" " " "\\p-" "\\U2659 " "\\p+" "\\U2659 "_ets },
{ "\\p+" "\\U2656 " "\\p-" "\\U2658 " "\\p+" "\\U265C " "\\p-" "\\U2656 " "\\p+" " " "\\p-" " " "\\p+" "\\U2654 " "\\p- "_ets }
});
}
auto make_white_text()
{
auto text_area = munin::make_text_area();
text_area->insert_text(
"e4 d4 e5 Bd3 Q\\i>x\\xd3 f4 c3 Nf3 0-0 b3 c\\i>x\\xd4 Bb2 a3 "
"N\\i>x\\xd4 Rd1 B\\i>x\\xd4 Q\\i>x\\xd4 Kf2 Q\\i>x\\xb6 Ke2 Kd2 g3 "
"a4 b4"_ets);
return text_area;
}
auto make_black_text()
{
auto text_area = munin::make_text_area();
text_area->insert_text(
"c6 d5 Bf5 B\\i>x\\xd3 e6 c5 Nc6 Qb6 Nh6 c\\i>x\\xd4 Nf5 Rc8 "
"Nc\\i>x\\xd4 Bc5 N\\i>x\\xd5 B\\i>x\\xd4\\[3\\i>+\\x Rc1 R\\i>x\\xd1 "
"a\\i>x\\xb6 Rc1 Rg1 Kd7 Rc8 Rcc1"_ets
);
return text_area;
}
auto make_content(auto &button)
{
return munin::view(
munin::make_compass_layout(),
munin::view(
munin::make_grid_layout({2, 1}),
munin::view(
munin::make_compass_layout(),
make_board(),
munin::compass_layout::heading::centre,
munin::make_fill("\\[6\\U2502"_ete),
munin::compass_layout::heading::east),
munin::view(
munin::make_grid_layout({1, 2}),
munin::make_scroll_pane(make_white_text()),
munin::make_scroll_pane(make_black_text()))),
munin::compass_layout::heading::centre,
munin::view(
munin::make_compass_layout(),
munin::make_fill("\\[6\\U2500"_ete),
munin::compass_layout::heading::north,
munin::make_fill(' '),
munin::compass_layout::heading::centre,
button,
munin::compass_layout::heading::east),
munin::compass_layout::heading::south);
}
auto make_behaviour()
{
terminalpp::behaviour behaviour;
behaviour.supports_basic_mouse_tracking = true;
behaviour.supports_window_title_bel = true;
return behaviour;
}
int main()
{
auto button = munin::make_button(" OK ");
munin::window window{make_content(button)};
boost::asio::io_context io_context;
consolepp::console console{io_context};
terminalpp::canvas canvas{{console.size().width, console.size().height}};
terminalpp::terminal terminal{make_behaviour()};
auto const &console_write =
[&console](terminalpp::bytes data)
{
console.write(data);
};
auto const &repaint_window =
[&]()
{
window.repaint(canvas, terminal, console_write);
};
window.on_repaint_request.connect(repaint_window);
console.on_size_changed.connect(
[&]
{
auto const new_size = console.size();
canvas.resize({new_size.width, new_size.height});
repaint_window();
});
terminal.write(console_write)
<< terminalpp::enable_mouse()
<< terminalpp::use_alternate_screen_buffer()
<< terminalpp::set_window_title("Chess++");
auto work_guard = boost::asio::make_work_guard(io_context);
button->on_click.connect([&]{
io_context.stop();
work_guard.reset();
});
button->set_focus();
terminal_reader reader(window);
schedule_read(console, terminal, reader);
io_context.run();
terminal.write(console_write)
<< terminalpp::use_normal_screen_buffer()
<< terminalpp::disable_mouse();
}
| 30.994737
| 142
| 0.533707
|
KazDragon
|
ac96cdfc0f02aabe82becbdefc53c58933372f17
| 6,091
|
cc
|
C++
|
tests/unit/rdma/test_rdma_collection_handle.extended.cc
|
rbuch/vt
|
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
|
[
"BSD-3-Clause"
] | 26
|
2019-11-26T08:36:15.000Z
|
2022-02-15T17:13:21.000Z
|
tests/unit/rdma/test_rdma_collection_handle.extended.cc
|
rbuch/vt
|
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
|
[
"BSD-3-Clause"
] | 1,215
|
2019-09-09T14:31:33.000Z
|
2022-03-30T20:20:14.000Z
|
tests/unit/rdma/test_rdma_collection_handle.extended.cc
|
rbuch/vt
|
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
|
[
"BSD-3-Clause"
] | 12
|
2019-09-08T00:03:05.000Z
|
2022-02-23T21:28:35.000Z
|
/*
//@HEADER
// *****************************************************************************
//
// test_rdma_collection_handle.extended.cc
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#include <gtest/gtest.h>
#include "test_parallel_harness.h"
#include "test_helpers.h"
#include "vt/vrt/collection/manager.h"
namespace vt { namespace tests { namespace unit {
bool triggered_lb = false;
template <typename T>
struct TestCol : vt::Collection<TestCol<T>, vt::Index2D> {
TestCol() = default;
struct TestMsg : vt::CollectionMessage<TestCol> { };
void makeHandles(TestMsg*) {
auto proxy = this->getCollectionProxy();
auto idx = this->getIndex();
handle_ = proxy.template makeHandleRDMA<T>(idx, 8, true);
}
void setupData(TestMsg* msg) {
auto idx = this->getIndex();
handle_.modifyExclusive([&](T* t, std::size_t count) {
for (int i = 0; i < 8; i++) {
t[i] = idx.x() * 100 + idx.y();
}
});
}
void testData(TestMsg*) {
auto idx = this->getIndex();
auto next_x = idx.x() + 1 < 8 ? idx.x() + 1 : 0;
vt::Index2D next(next_x, idx.y());
auto ptr = std::make_unique<T[]>(8);
handle_.get(next, ptr.get(), 8, 0, vt::Lock::Shared);
for (int i = 0; i < 8; i++) {
EXPECT_EQ(ptr[i], next_x * 100 + idx.y());
}
}
void migrateObjs(TestMsg*) {
auto idx = this->getIndex();
if (idx.y() > 1) {
auto node = vt::theContext()->getNode();
auto num = vt::theContext()->getNumNodes();
auto next = node + 1 < num ? node + 1 : 0;
this->migrate(next);
}
}
void runLBHooksForRDMA(TestMsg*) {
if (not triggered_lb) {
triggered_lb = true;
//fmt::print("{}: run post migration hooks\n", theContext()->getNode());
vt::thePhase()->runHooksManual(vt::phase::PhaseHook::EndPostMigration);
}
}
void checkDataAfterMigrate(TestMsg*) {
auto idx = this->getIndex();
auto next_x = idx.x() + 1 < 8 ? idx.x() + 1 : 0;
vt::Index2D next(next_x, idx.y());
auto ptr = std::make_unique<T[]>(8);
handle_.get(next, ptr.get(), 8, 0, vt::Lock::Shared);
for (int i = 0; i < 8; i++) {
EXPECT_EQ(ptr[i], next_x * 100 + idx.y());
}
}
void destroyHandles(TestMsg*) {
auto proxy = this->getCollectionProxy();
proxy.destroyHandleRDMA(handle_);
}
template <typename SerializerT>
void serialize(SerializerT& s) {
vt::Collection<TestCol<T>, vt::Index2D>::serialize(s);
s | handle_;
}
private:
vt::HandleRDMA<T, vt::Index2D> handle_;
};
template <typename T>
struct TestRDMAHandleCollection : TestParallelHarness { };
TYPED_TEST_SUITE_P(TestRDMAHandleCollection);
TYPED_TEST_P(TestRDMAHandleCollection, test_rdma_handle_collection_1) {
SET_MAX_NUM_NODES_CONSTRAINT(CMAKE_DETECTED_MAX_NUM_NODES);
using T = TypeParam;
using ColType = TestCol<T>;
using MsgType = typename ColType::TestMsg;
triggered_lb = false;
CollectionProxy<TestCol<T>, Index2D> proxy;
runInEpochCollective([&]{
auto range = vt::Index2D(8,8);
proxy = theCollection()->constructCollective<ColType>(range);
});
runInEpochCollective([=]{
proxy.template broadcastCollective<MsgType, &ColType::makeHandles>();
});
runInEpochCollective([=]{
proxy.template broadcastCollective<MsgType, &ColType::setupData>();
});
runInEpochCollective([=]{
proxy.template broadcastCollective<MsgType, &ColType::testData>();
});
runInEpochCollective([=]{
proxy.template broadcastCollective<MsgType, &ColType::migrateObjs>();
});
runInEpochCollective([=]{
proxy.template broadcastCollective<MsgType, &ColType::runLBHooksForRDMA>();
});
runInEpochCollective([=]{
proxy.template broadcastCollective<MsgType, &ColType::checkDataAfterMigrate>();
});
runInEpochCollective([=]{
proxy.template broadcastCollective<MsgType, &ColType::destroyHandles>();
});
}
using RDMACollectionTestTypes = testing::Types<
int,
double
>;
REGISTER_TYPED_TEST_SUITE_P(
TestRDMAHandleCollection,
test_rdma_handle_collection_1
);
INSTANTIATE_TYPED_TEST_SUITE_P(
test_rdma_handle_collection, TestRDMAHandleCollection, RDMACollectionTestTypes,
DEFAULT_NAME_GEN
);
}}} /* end namespace vt::tests::unit */
| 31.076531
| 83
| 0.66902
|
rbuch
|
ac9dd0541a5ed85c2fb5017510845e234dbc75a0
| 991
|
cpp
|
C++
|
RTCSDK/service/biz_service_factory.cpp
|
tyouritsugun/janus-client-cplus
|
f478ddcf62d12f1b0efe213dd695ec022e793070
|
[
"MIT"
] | 1
|
2020-12-18T09:11:05.000Z
|
2020-12-18T09:11:05.000Z
|
RTCSDK/service/biz_service_factory.cpp
|
tyouritsugun/janus-client-cplus
|
f478ddcf62d12f1b0efe213dd695ec022e793070
|
[
"MIT"
] | null | null | null |
RTCSDK/service/biz_service_factory.cpp
|
tyouritsugun/janus-client-cplus
|
f478ddcf62d12f1b0efe213dd695ec022e793070
|
[
"MIT"
] | 1
|
2021-08-11T01:09:22.000Z
|
2021-08-11T01:09:22.000Z
|
/**
* This file is part of janus_client project.
* Author: Jackie Ou
* Created: 2020-10-01
**/
#include "biz_service_factory.h"
#include "notification_service.h"
namespace core {
BizServiceFactory::BizServiceFactory(const std::shared_ptr<IUnifiedFactory>& unifiedFactory)
: _unifiedFactory(unifiedFactory)
{
}
void BizServiceFactory::registerService(const std::string& key , const std::shared_ptr<IBizService> &service)
{
_serviceMap.insert(std::make_pair(key, service));
}
void BizServiceFactory::unregisterService(const std::string& key)
{
_serviceMap.erase(key);
}
std::shared_ptr<IBizService> BizServiceFactory::getService(const std::string& key)
{
auto it = _serviceMap.find(key);
return it == _serviceMap.end() ? nullptr : it->second;
}
void BizServiceFactory::cleanup()
{
for (auto item : _serviceMap) {
if(!item.second) {
continue;
}
item.second->cleanup();
}
}
void BizServiceFactory::init()
{
}
}
| 19.82
| 109
| 0.691221
|
tyouritsugun
|
acb3de12b891c8be8153746689eb3fa6c051b985
| 1,514
|
hpp
|
C++
|
cpp/map_key_iterator.hpp
|
frobware/cmd-key-happy
|
cd64bba07dc729f2701b0fc1e603d04d2dbc64e9
|
[
"MIT"
] | 35
|
2015-09-24T23:04:03.000Z
|
2022-03-09T16:31:16.000Z
|
cpp/map_key_iterator.hpp
|
frobware/cmd-key-happy
|
cd64bba07dc729f2701b0fc1e603d04d2dbc64e9
|
[
"MIT"
] | 4
|
2016-05-17T20:25:14.000Z
|
2019-06-05T16:14:34.000Z
|
cpp/map_key_iterator.hpp
|
frobware/cmd-key-happy
|
cd64bba07dc729f2701b0fc1e603d04d2dbc64e9
|
[
"MIT"
] | 8
|
2015-12-08T01:18:58.000Z
|
2020-07-24T21:53:34.000Z
|
#pragma once
// This class/idea/idiom taken from a reply on stackoverflow (but I
// cannot find the original author). XXX Add missing attribution for
// this code.
#include <map>
#include <iterator>
namespace frobware {
template<typename map_type>
class key_iterator : public map_type::iterator
{
public:
typedef typename map_type::iterator map_iterator;
typedef typename map_iterator::value_type::first_type key_type;
key_iterator(map_iterator& other) :map_type::iterator(other) {};
key_type& operator*() {
return map_type::iterator::operator*().first;
}
};
template<typename map_type>
key_iterator<map_type> key_begin(map_type& m)
{
return key_iterator<map_type>(m.begin());
}
template<typename map_type>
key_iterator<map_type> key_end(map_type& m)
{
return key_iterator<map_type>(m.end());
}
template<typename map_type>
class const_key_iterator : public map_type::const_iterator
{
public:
typedef typename map_type::const_iterator map_iterator;
typedef typename map_iterator::value_type::first_type key_type;
const_key_iterator(const map_iterator& other) :map_type::const_iterator(other) {};
const key_type& operator*() const {
return map_type::const_iterator::operator*().first;
}
};
template<typename map_type>
const_key_iterator<map_type> key_begin(const map_type& m)
{
return const_key_iterator<map_type>(m.begin());
}
template<typename map_type>
const_key_iterator<map_type> key_end(const map_type& m)
{
return const_key_iterator<map_type>(m.end());
}
}
| 23.65625
| 84
| 0.76288
|
frobware
|
acbff0d2bc6fd0d2b2a9c66d92ffb8ec3b355c0a
| 1,226
|
cpp
|
C++
|
OGDF/_examples/layout/orthogonal/main.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 13
|
2017-12-21T03:35:41.000Z
|
2022-01-31T13:45:25.000Z
|
OGDF/_examples/layout/orthogonal/main.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 7
|
2017-09-13T01:31:24.000Z
|
2021-12-14T00:31:50.000Z
|
OGDF/_examples/layout/orthogonal/main.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 15
|
2017-09-07T18:28:55.000Z
|
2022-01-18T14:17:43.000Z
|
#include <ogdf/planarity/PlanarizationLayout.h>
#include <ogdf/planarity/SubgraphPlanarizer.h>
#include <ogdf/planarity/VariableEmbeddingInserter.h>
#include <ogdf/planarity/FastPlanarSubgraph.h>
#include <ogdf/orthogonal/OrthoLayout.h>
#include <ogdf/planarity/EmbedderMinDepthMaxFaceLayers.h>
#include <ogdf/fileformats/GraphIO.h>
using namespace ogdf;
int main()
{
Graph G;
GraphAttributes GA(G,
GraphAttributes::nodeGraphics |
GraphAttributes::edgeGraphics |
GraphAttributes::nodeLabel |
GraphAttributes::edgeStyle |
GraphAttributes::nodeStyle |
GraphAttributes::nodeTemplate);
GraphIO::readGML(GA, G, "ERDiagram.gml");
PlanarizationLayout pl;
SubgraphPlanarizer *crossMin = new SubgraphPlanarizer;
FastPlanarSubgraph *ps = new FastPlanarSubgraph;
ps->runs(100);
VariableEmbeddingInserter *ves = new VariableEmbeddingInserter;
ves->removeReinsert(rrAll);
crossMin->setSubgraph(ps);
crossMin->setInserter(ves);
EmbedderMinDepthMaxFaceLayers *emb = new EmbedderMinDepthMaxFaceLayers;
pl.setEmbedder(emb);
OrthoLayout *ol = new OrthoLayout;
ol->separation(20.0);
ol->cOverhang(0.4);
pl.setPlanarLayouter(ol);
pl.call(GA);
GraphIO::writeGML(GA, "ERDiagram-layout.gml");
return 0;
}
| 24.52
| 72
| 0.777325
|
shahnidhi
|
acc1aeab0c888abdc127e061373d13a39f347805
| 10,148
|
cpp
|
C++
|
sdk/chustd/ImageFormat.cpp
|
hadrien-psydk/pngoptimizer
|
d92946e63a57a4562af0feaa9e4cfd8628373777
|
[
"Zlib"
] | 90
|
2016-08-23T00:13:04.000Z
|
2022-02-22T09:40:46.000Z
|
sdk/chustd/ImageFormat.cpp
|
hadrien-psydk/pngoptimizer
|
d92946e63a57a4562af0feaa9e4cfd8628373777
|
[
"Zlib"
] | 25
|
2016-09-01T07:09:03.000Z
|
2022-01-31T16:18:57.000Z
|
sdk/chustd/ImageFormat.cpp
|
hadrien-psydk/pngoptimizer
|
d92946e63a57a4562af0feaa9e4cfd8628373777
|
[
"Zlib"
] | 17
|
2017-05-03T17:49:25.000Z
|
2021-12-28T06:47:56.000Z
|
///////////////////////////////////////////////////////////////////////////////
// This file is part of the chustd library
// Copyright (C) ChuTeam
// For conditions of distribution and use, see copyright notice in chustd.h
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ImageFormat.h"
#include "File.h"
//////////////////////////////////////////////////////////////////////
using namespace chustd;
//////////////////////////////////////////////////////////////////////
Color Color::Black(0, 0, 0);
Color Color::White(255, 255, 255);
Color Color::Red(255, 0, 0);
Color Color::Green(0, 255, 0);
Color Color::Blue(0, 0, 255);
Color Color::Yellow(255, 255, 0);
Color Color::Cyan(0, 255, 255);
Color Color::Magenta(255, 0, 255);
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
PixelFormat AnimFrame::GetPixelFormat() const
{
if( m_pOwner )
{
return m_pOwner->GetPixelFormat();
}
return PF_Unknown;
}
bool AnimFrame::HasSimpleTransparency() const
{
if( m_pOwner )
{
return m_pOwner->HasSimpleTransparency();
}
return false;
}
uint16 AnimFrame::GetGreyTransIndex() const
{
if( m_pOwner )
{
return m_pOwner->GetGreyTransIndex();
}
return 0;
}
void AnimFrame::GetTransIndexes(uint16& red, uint16& green, uint16& blue) const
{
if( m_pOwner )
{
return m_pOwner->GetTransIndexes(red, green, blue);
}
red = green = blue = 0;
}
const Palette& AnimFrame::GetPalette() const
{
if( m_pOwner )
{
return m_pOwner->GetPalette();
}
return Palette::Null;
}
//////////////////////////////////////////////////////////////////////
const Palette Palette::Null;
//////////////////////////////////////////////////////////////////////
// Returns true if one of the color has a alpha not equal to 255
bool Palette::HasNonOpaqueColor() const
{
for(int i = 0; i < m_count; ++i)
{
if( m_colors[i].GetAlpha() != 255 )
{
return true;
}
}
return false;
}
bool Palette::AllAlphasAreOpaque() const
{
for(int i = 0; i < m_count; ++i)
{
if( m_colors[i].GetAlpha() != 0 )
return false;
}
return true;
}
void Palette::SetAlphaFullOpaque()
{
for(int i = 0; i < m_count; ++i)
{
m_colors[i].SetAlpha(255);
}
}
// Returns -1 if not found
int Palette::FindColor(Color col) const
{
for(int i = 0; i < m_count; ++i)
{
if( m_colors[i] == col )
{
return i;
}
}
return -1;
}
// Returns -1 if not found
int Palette::GetFirstFullyTransparentColor() const
{
for(int i = 0; i < m_count; ++i)
{
if( m_colors[i].a == 0 )
{
return i;
}
}
return -1;
}
//////////////////////////////////////////////////////////////////////
ImageFormat::ImageFormat()
{
m_width = 0;
m_height = 0;
m_lastError = 0;
}
ImageFormat::~ImageFormat()
{
}
////////////////////////////////////////////////////
bool ImageFormat::IsGray(PixelFormat pf)
{
switch(pf)
{
case PF_1bppGrayScale:
case PF_2bppGrayScale:
case PF_4bppGrayScale:
case PF_8bppGrayScale:
case PF_16bppGrayScale:
return true;
default:
break;
}
return false;
}
bool ImageFormat::IsIndexed(PixelFormat pf)
{
return pf == PF_1bppIndexed || pf == PF_2bppIndexed || pf == PF_4bppIndexed || pf == PF_8bppIndexed;
}
int32 ImageFormat::SizeofPixelInBits(PixelFormat ePixelFormat)
{
switch(ePixelFormat)
{
case PF_Unknown:
return 0;
case PF_1bppGrayScale:
return 1;
case PF_2bppGrayScale:
return 2;
case PF_4bppGrayScale:
return 4;
case PF_8bppGrayScale:
return 8;
case PF_16bppGrayScale:
return 16;
case PF_16bppGrayScaleAlpha:
return 16;
case PF_32bppGrayScaleAlpha:
return 32;
case PF_1bppIndexed:
return 1;
case PF_2bppIndexed:
return 2;
case PF_4bppIndexed:
return 4;
case PF_8bppIndexed:
return 8;
case PF_16bppArgb1555:
case PF_16bppArgb4444:
case PF_16bppRgb555:
case PF_16bppRgb565:
return 16;
case PF_24bppRgb:
case PF_24bppBgr:
return 24;
case PF_32bppRgba:
case PF_32bppBgra:
return 32;
case PF_48bppRgb:
return 48;
case PF_64bppRgba:
return 64;
}
ASSERT(0);
return 0;
}
int32 ImageFormat::ComputeByteWidth(PixelFormat epf, int32 width)
{
const int32 sizeofPixelInBits = ImageFormat::SizeofPixelInBits(epf);
// Size of a row in bits
const int32 bitWidth = width * sizeofPixelInBits;
// Round up for size of a row in bytes
const int32 addWidth = ((bitWidth & 7) != 0) ? 1 : 0;
const int32 byteWidth = bitWidth / 8 + addWidth;
return byteWidth;
}
//////////////////////////////////////////////////////////////////////////////
String ImageFormat::GetLastErrorString() const
{
switch(m_lastError)
{
case ioErr:
return "Error accessing to the file";
case badFileFormat:
return "Bad File Format";
case notEnoughMemory:
return "Not enough memory";
case uncompleteFile:
return "Uncomplete file";
}
return "Unknown error";
}
bool ImageFormat::Load(const String& filePath)
{
File file;
if( !file.Open(filePath) )
{
m_lastError = ioErr;
return false;
}
return LoadFromFile(file);
}
int32 ImageFormat::GetWidth() const
{
return m_width;
}
int32 ImageFormat::GetHeight() const
{
return m_height;
}
const Buffer& ImageFormat::GetPixels() const
{
return m_pixels;
}
void ImageFormat::FreeBuffer()
{
m_pixels.Clear();
}
void ImageFormat::FlipVertical()
{
PixelFormat epf = GetPixelFormat();
if( epf == PF_Unknown )
{
return;
}
const int32 bytesPerRow = ImageFormat::ComputeByteWidth(epf, m_width);
uint8* pComponents = m_pixels.GetWritePtr();
const int32 heightDiv2 = m_height / 2;
for(int iY = 0; iY < heightDiv2; ++iY)
{
uint8* pSrc = pComponents + (iY * bytesPerRow);
uint8* pDst = pComponents + ((m_height - 1 - iY) * bytesPerRow);
for(int iByte = 0; iByte < bytesPerRow; ++iByte)
{
uint8 swap = pDst[iByte];
pDst[iByte] = pSrc[iByte];
pSrc[iByte] = swap;
}
}
}
void ImageFormat::SetAlphaFullOpaque()
{
PixelFormat epf = GetPixelFormat();
if( epf == PF_Unknown )
{
return;
}
const int32 pixelCount = m_width * m_height;
if( epf == PF_32bppRgba || epf == PF_32bppBgra )
{
uint8* pDst = m_pixels.GetWritePtr();
const uint8 alpha = 255;
for(int i = 0; i < pixelCount; ++i)
{
pDst[3] = alpha;
pDst += 4;
}
}
}
int32 ImageFormat::GetLastError() const
{
return m_lastError;
}
bool ImageFormat::IsIndexed() const
{
return IsIndexed(GetPixelFormat());
}
bool ImageFormat::IsAnimated() const
{
return false;
}
bool ImageFormat::HasDefaultImage() const
{
return false;
}
int32 ImageFormat::GetFrameCount() const
{
return 0;
}
const AnimFrame* ImageFormat::GetAnimFrame(int /*index*/) const
{
return nullptr;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// If animated, gets the number of times the animation loops.
int32 ImageFormat::GetLoopCount() const
{
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Packs single-pixel bytes into multiple-pixels bytes.
//
// [in,out] pixels Pixels in: one pixel per byte, out: multiple pixels per byte
// [in] width Width in pixels
// [in] height Height in pixels
// [in] pixelFormat Target pixel format
//
// Returns true upon success
///////////////////////////////////////////////////////////////////////////////////////////////////
bool ImageFormat::PackPixels(Buffer& pixels, int width, int height, PixelFormat pixelFormat)
{
if( width < 0 || height < 0 )
{
return false; // Bad arg
}
int bitsPerPix = ImageFormat::SizeofPixelInBits(pixelFormat);
if( bitsPerPix > 8 )
{
return false; // Bad arg
}
if( bitsPerPix == 8 )
{
// Nothing to do
return true;
}
if( pixels.GetSize() < (width * height) )
{
ASSERT(0);
return false;
}
const int32 bytesPerRow = ImageFormat::ComputeByteWidth(pixelFormat, width);
uint8* pIn = pixels.GetWritePtr();
uint8* pOut = pIn;
// Note: there is padding at the end of each row
uint8 currentByte = 0; // Current byte value
int usedBitCount = 0; // Number of bits used inside the byte
for(int iRow = 0; iRow < height; iRow++)
{
currentByte = 0;
usedBitCount = 0;
for(int iCol = 0; iCol < width; iCol++)
{
uint8 nVal = pIn[iRow * width + iCol];
usedBitCount += bitsPerPix;
currentByte |= (nVal << (8 - usedBitCount));
if( usedBitCount == 8 )
{
pOut[0] = currentByte;
++pOut;
currentByte = 0;
usedBitCount = 0;
}
}
if( usedBitCount != 0 )
{
pOut[0] = currentByte;
++pOut;
}
}
int newSize = bytesPerRow * height;
pixels.SetSize(newSize);
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Unpacks multiple pixels per byte to get one pixel per byte.
//
// [in,out] pixels Pixels in: one pixel per bytes, out: multiple pixels per byte
// [in] width Width in pixels
// [in] height Height in pixels
// [in] pixelFormat Source pixel format
//
// Returns true upon success.
///////////////////////////////////////////////////////////////////////////////////////////////////
bool ImageFormat::UnpackPixels(Buffer& pixels, int width, int height, PixelFormat pixelFormat)
{
int bitsPerPix = ImageFormat::SizeofPixelInBits(pixelFormat);
if( bitsPerPix >= 8 )
{
// Nothing to do
return true;
}
Buffer newBuffer;
if( !newBuffer.SetSize(width * height) )
{
return false;
}
const uint8* pSrc = pixels.GetReadPtr();
uint8* pDst = newBuffer.GetWritePtr();
int32 mask = ~((~0UL) << bitsPerPix);
int32 shift = 8 - bitsPerPix;
int srcIndex = 0;
int dstIndex = 0;
for(int i = 0; i < height; ++i)
{
for(int j = 0; j < width; ++j)
{
uint8 currentByte = pSrc[srcIndex];
uint8 colorIndex = uint8( (currentByte >> shift) & mask);
shift -= bitsPerPix;
if( shift < 0 )
{
shift = 8 - bitsPerPix;
srcIndex++;
}
pDst[dstIndex] = colorIndex;
dstIndex++;
}
// Some padding bits may remain
if( shift != 8 - bitsPerPix )
{
shift = 8 - bitsPerPix;
srcIndex++;
}
}
pixels = newBuffer;
return true;
}
| 20.134921
| 101
| 0.582184
|
hadrien-psydk
|
acc251772bb370a154ff6840dedcb61bdce121e9
| 2,801
|
cpp
|
C++
|
tools/light-directions/main.cpp
|
bradparks/Restore__3d_model_from_pics_2d_multiple_images
|
58f935130693e6eba2db133ce8dec3fd6a3d3dd0
|
[
"MIT"
] | 21
|
2018-07-17T02:35:43.000Z
|
2022-02-25T00:45:09.000Z
|
tools/light-directions/main.cpp
|
bradparks/Restore__3d_model_from_pics_2d_multiple_images
|
58f935130693e6eba2db133ce8dec3fd6a3d3dd0
|
[
"MIT"
] | null | null | null |
tools/light-directions/main.cpp
|
bradparks/Restore__3d_model_from_pics_2d_multiple_images
|
58f935130693e6eba2db133ce8dec3fd6a3d3dd0
|
[
"MIT"
] | 11
|
2018-09-06T17:29:36.000Z
|
2022-01-29T12:20:59.000Z
|
// Copyright (c) 2015-2016, Kai Wolf
//
// 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 <string>
#include <memory>
#include <opencv2/highgui/highgui.hpp>
#include "common/dataset.hpp"
#include "common/utils.hpp"
#include "io/dataset_reader.hpp"
#include "io/assets_path.hpp"
#include "filtering/segmentation.hpp"
#include "rendering/bounding_box.hpp"
#include "rendering/voxel_carving.hpp"
#include "rendering/light_dir_estimation.hpp"
using namespace ret;
using namespace ret::io;
using namespace ret::calib;
using namespace ret::filtering;
using namespace ret::rendering;
std::shared_ptr<DataSet> loadDataSet(const std::string &path,
const std::size_t num_imgs) {
DataSetReader dsr(path);
auto ds = dsr.load(num_imgs);
for (std::size_t i = 0; i < num_imgs; ++i) {
ds->getCamera(i).setMask(Binarize(
ds->getCamera(i).getImage(), cv::Scalar(0, 0, 30)));
}
return ds;
}
int main() {
const std::size_t VOXEL_DIM = 128;
const std::size_t NUM_IMGS = 36;
auto ds = loadDataSet(std::string(ASSETS_PATH) + "/squirrel", NUM_IMGS);
BoundingBox bbox(ds->getCamera(0), ds->getCamera((NUM_IMGS / 4) - 1));
auto bb_bounds = bbox.getBounds();
auto vc = ret::make_unique<VoxelCarving>(bb_bounds, VOXEL_DIM);
for (const auto &cam : ds->getCameras()) {
vc->carve(cam);
}
auto mesh = vc->createVisualHull();
LightDirEstimation light;
for (auto idx = 0; idx < NUM_IMGS; ++idx) {
auto light_dir = light.execute(ds->getCamera(idx), mesh);
cv::Mat light_dirs = light.displayLightDirections(
ds->getCamera(idx), light_dir);
cv::imwrite("light_dir" + std::to_string(idx) + ".png", light_dirs);
}
return 0;
}
| 36.376623
| 80
| 0.697251
|
bradparks
|
acc3b189afe63eedffa6fa7e2d92c221cb77349a
| 48,337
|
cc
|
C++
|
supersonic/cursor/core/aggregate_groups.cc
|
IssamElbaytam/supersonic
|
062a48ddcb501844b25a8ae51bd777fcf7ac1721
|
[
"Apache-2.0"
] | 201
|
2015-03-18T21:55:00.000Z
|
2022-03-03T01:48:26.000Z
|
supersonic/cursor/core/aggregate_groups.cc
|
edisona/supersonic
|
062a48ddcb501844b25a8ae51bd777fcf7ac1721
|
[
"Apache-2.0"
] | 6
|
2015-03-19T16:47:19.000Z
|
2020-10-05T09:38:26.000Z
|
supersonic/cursor/core/aggregate_groups.cc
|
edisona/supersonic
|
062a48ddcb501844b25a8ae51bd777fcf7ac1721
|
[
"Apache-2.0"
] | 54
|
2015-03-19T16:31:57.000Z
|
2021-12-31T10:14:57.000Z
|
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stddef.h>
#include <algorithm>
#include "supersonic/utils/std_namespace.h"
#include <list>
#include "supersonic/utils/std_namespace.h"
#include <memory>
#include <set>
#include "supersonic/utils/std_namespace.h"
#include <vector>
using std::vector;
#include <glog/logging.h>
#include "supersonic/utils/logging-inl.h"
#include "supersonic/utils/macros.h"
#include "supersonic/utils/port.h"
#include "supersonic/utils/scoped_ptr.h"
#include "supersonic/utils/stringprintf.h"
#include "supersonic/utils/exception/failureor.h"
#include "supersonic/base/exception/exception.h"
#include "supersonic/base/exception/exception_macros.h"
#include "supersonic/base/exception/result.h"
#include "supersonic/base/infrastructure/bit_pointers.h"
#include "supersonic/base/infrastructure/block.h"
#include "supersonic/base/infrastructure/projector.h"
#include "supersonic/base/infrastructure/types.h"
#include "supersonic/base/memory/memory.h"
#include "supersonic/cursor/base/cursor.h"
#include "supersonic/cursor/base/operation.h"
#include "supersonic/cursor/proto/cursors.pb.h"
#include "supersonic/cursor/core/aggregate.h"
#include "supersonic/cursor/core/aggregator.h"
#include "supersonic/cursor/core/hybrid_group_utils.h"
#include "supersonic/cursor/core/sort.h"
#include "supersonic/cursor/infrastructure/basic_cursor.h"
#include "supersonic/cursor/infrastructure/basic_operation.h"
#include "supersonic/cursor/infrastructure/iterators.h"
#include "supersonic/cursor/infrastructure/ordering.h"
#include "supersonic/cursor/infrastructure/row_hash_set.h"
#include "supersonic/cursor/infrastructure/table.h"
#include "supersonic/proto/supersonic.pb.h"
#include "supersonic/utils/strings/join.h"
#include "supersonic/utils/container_literal.h"
#include "supersonic/utils/map_util.h"
#include "supersonic/utils/pointer_vector.h"
#include "supersonic/utils/stl_util.h"
namespace supersonic {
class TupleSchema;
namespace {
// Creates and updates a block of unique keys that are the result of grouping.
class GroupKeySet {
public:
typedef row_hash_set::FindResult FindResult; // Re-exporting.
// Creates a GroupKeySet. group_by_columns describes which columns constitute
// a key and should be grouped together, it can be empty, in which case all
// rows are considered equal and are grouped together. Set is pre-allocated
// to store initial_row_capacity unique keys, and it can grow as needed.
static FailureOrOwned<GroupKeySet> Create(
const BoundSingleSourceProjector* group_by,
BufferAllocator* allocator,
rowcount_t initial_row_capacity,
const int64 max_unique_keys_in_result) {
std::unique_ptr<GroupKeySet> group_key_set(
new GroupKeySet(group_by, allocator, max_unique_keys_in_result));
PROPAGATE_ON_FAILURE(group_key_set->Init(initial_row_capacity));
return Success(group_key_set.release());
}
const TupleSchema& key_schema() const {
return key_projector_->result_schema();
}
// View on a block that keeps unique keys. Can be called only when key is not
// empty.
const View& key_view() const {
return key_row_set_.indexed_view();
}
// How many rows can a view passed in the next call to Insert() have.
// TODO(user): Remove this limitation (the row hash set could use a loop
// to insert more items that it can process in a single shot).
rowcount_t max_view_row_count_to_insert() const {
// Does not accept views larger then cursor::kDefaultRowCount because this
// is the size of preallocated table that holds result of Insert().
return Cursor::kDefaultRowCount;
}
// Count of unique keys in the set.
rowcount_t size() const { return key_row_set_.size(); }
// Inserts all unique keys from the view to the key block. For each row
// from input view finds an index of its key in the key block and puts
// these indexes in the result table.
// Input view can not have more rows then max_view_row_count_to_insert().
const rowid_t Insert(const View& view, FindResult* result) {
CHECK_LE(view.row_count(), max_view_row_count_to_insert());
key_projector_->Project(view, &child_key_view_);
child_key_view_.set_row_count(view.row_count());
return key_row_set_.Insert(child_key_view_, result);
}
void Reset() { key_row_set_.Clear(); }
void Compact() { key_row_set_.Compact(); }
private:
GroupKeySet(const BoundSingleSourceProjector* group_by,
BufferAllocator* allocator,
const int64 max_unique_keys_in_result)
: key_projector_(group_by),
child_key_view_(key_projector_->result_schema()),
key_row_set_(key_projector_->result_schema(), allocator,
max_unique_keys_in_result) {}
FailureOrVoid Init(rowcount_t reserved_capacity) {
if (!key_row_set_.ReserveRowCapacity(reserved_capacity)) {
THROW(new Exception(
ERROR_MEMORY_EXCEEDED,
StrCat("Block allocation failed. Key block with capacity ",
reserved_capacity, " not allocated.")));
}
return Success();
}
std::unique_ptr<const BoundSingleSourceProjector> key_projector_;
// View over an input view from child but with only key columns.
View child_key_view_;
row_hash_set::RowHashSet key_row_set_;
DISALLOW_COPY_AND_ASSIGN(GroupKeySet);
};
// Cursor that is used for handling the standard GroupAggregate mode and
// BestEffortGroupAggregate mode. The difference between these two modes is that
// GroupAggregate needs to process the whole input during creation (returns out
// of memory error if aggregation result is too large) and
// BestEffortGroupAggregate does not process anything during creation and
// processes as large chunks as possible during iteration phase, but does not
// guarantee that the final result will be fully aggregated (i.e. there can be
// more than one output for a given key). To make BestEffortGroupAggregate
// deterministic (always producing the same output), pass GuaranteeMemory as its
// allocator.
class GroupAggregateCursor : public BasicCursor {
public:
// Creates the cursor. Returns immediately (w/o processing any input).
static FailureOrOwned<GroupAggregateCursor> Create(
const BoundSingleSourceProjector* group_by,
Aggregator* aggregator,
BufferAllocator* allocator, // Takes ownership
BufferAllocator* original_allocator, // Doesn't take ownership.
bool best_effort,
const int64 max_unique_keys_in_result,
Cursor* child) {
std::unique_ptr<BufferAllocator> allocator_owned(CHECK_NOTNULL(allocator));
std::unique_ptr<Cursor> child_owner(child);
std::unique_ptr<Aggregator> aggregator_owner(aggregator);
FailureOrOwned<GroupKeySet> key = GroupKeySet::Create(
group_by, allocator_owned.get(), aggregator_owner->capacity(),
max_unique_keys_in_result);
PROPAGATE_ON_FAILURE(key);
vector<const TupleSchema*> input_schemas(2);
input_schemas[0] = &key->key_schema();
input_schemas[1] = &aggregator->schema();
std::unique_ptr<MultiSourceProjector> result_projector(
(new CompoundMultiSourceProjector())
->add(0, ProjectAllAttributes())
->add(1, ProjectAllAttributes()));
FailureOrOwned<const BoundMultiSourceProjector> bound_result_projector(
result_projector->Bind(input_schemas));
PROPAGATE_ON_FAILURE(bound_result_projector);
TupleSchema result_schema = bound_result_projector->result_schema();
return Success(
new GroupAggregateCursor(result_schema,
allocator_owned.release(), // Takes ownership.
original_allocator,
key.release(),
aggregator_owner.release(),
bound_result_projector.release(),
best_effort,
max_unique_keys_in_result,
child_owner.release()));
}
virtual ResultView Next(rowcount_t max_row_count) {
while (true) {
if (result_.next(max_row_count)) {
return ResultView::Success(&result_.view());
}
if (input_exhausted_) return ResultView::EOS();
// No rows from this call, yet input not exhausted. Retry.
PROPAGATE_ON_FAILURE(ProcessInput());
if (child_.is_waiting_on_barrier()) return ResultView::WaitingOnBarrier();
}
}
// If false, the Cursor will not return more data above what was already
// returned from Next() calls (unless TruncateResultView is called). This
// method can be used to determine if best-effort group managed to do full
// grouping:
// - Call .Next(numeric_limits<rowcount_t>::max())
// - Now if CanReturnMoreData() == false, we know that all the results of
// best-effort group are in a single view, which means that the data was fully
// aggregated.
// - TruncateResultView can be used to rewind the cursor to the beginning.
bool CanReturnMoreData() const {
return !input_exhausted_ ||
(result_.rows_remaining() > result_.row_count());
}
// Truncates the current result ViewIterator. If we only called Next() once,
// this rewinds the Cursor to the beginning.
bool TruncateResultView() {
return result_.truncate(0);
}
virtual bool IsWaitingOnBarrierSupported() const {
return child_.is_waiting_on_barrier_supported();
}
virtual void Interrupt() { child_.Interrupt(); }
virtual void ApplyToChildren(CursorTransformer* transformer) {
child_.ApplyToCursor(transformer);
}
virtual CursorId GetCursorId() const {
return best_effort_
? BEST_EFFORT_GROUP_AGGREGATE
: GROUP_AGGREGATE;
}
private:
// Takes ownership of the allocator, key, aggregator, and child.
GroupAggregateCursor(const TupleSchema& result_schema,
BufferAllocator* allocator,
BufferAllocator* original_allocator,
GroupKeySet* key,
Aggregator* aggregator,
const BoundMultiSourceProjector* result_projector,
bool best_effort,
const int64 max_unique_keys_in_result,
Cursor* child)
: BasicCursor(result_schema),
allocator_(allocator),
original_allocator_(CHECK_NOTNULL(original_allocator)),
child_(child),
key_(key),
aggregator_(aggregator),
result_(result_schema),
result_projector_(result_projector),
inserted_keys_(Cursor::kDefaultRowCount),
best_effort_(best_effort),
input_exhausted_(false),
reset_aggregator_in_processinput_(false),
max_unique_keys_in_result_(max_unique_keys_in_result) {}
// Process as many rows from input as can fit into result block. If after the
// first call to ProcessInput() input_exhausted_ is true, the result is fully
// aggregated (there are no rows with equal group by columns).
// Initializes the result_ to iterate over the aggregation result.
FailureOrVoid ProcessInput();
// Owned allocator used to allocate the memory.
// NOTE: it is used by other member objects created by GroupAggregateCursor so
// it has to be destroyed last. Keep it as the first class member.
std::unique_ptr<const BufferAllocator> allocator_;
// Non-owned allocator used to check whether we can allocate more memory or
// not.
const BufferAllocator* original_allocator_;
// The input.
CursorIterator child_;
// Holds key columns of the result. Wrapper around RowHashSet.
std::unique_ptr<GroupKeySet> key_;
// Holds 'aggregated' columns of the result.
std::unique_ptr<Aggregator> aggregator_;
// Iterates over a result of last call to ProcessInput. If
// cursor_over_result_->Next() returns EOS and input_exhausted() is false,
// ProcessInput needs to be called again to prepare next part of a result and
// set cursor_over_result_ to iterate over it.
ViewIterator result_;
// Projector to combine key & aggregated columns into the result.
std::unique_ptr<const BoundMultiSourceProjector> result_projector_;
GroupKeySet::FindResult inserted_keys_;
// If true, OOM is not fatal; the data aggregated up-to OOM are emitted,
// and the aggregation starts anew.
bool best_effort_;
// Set when EOS reached in the input stream.
bool input_exhausted_;
// To track when ProcessInput() should reset key_ and aggregator_. It
// shouldn't be done after exiting with WAITING_ON_BARRIER - some data might
// lost. Reset is also not needed in first ProcessInput() call.
bool reset_aggregator_in_processinput_;
// Maximum number of unique key combination(as per input order) to aggregate
// the results upon. If limit is hit, all remaining rows are aggregated
// together in the last row at index = max_unique_keys_in_result_
const int64 max_unique_keys_in_result_;
DISALLOW_COPY_AND_ASSIGN(GroupAggregateCursor);
};
FailureOrVoid GroupAggregateCursor::ProcessInput() {
if (reset_aggregator_in_processinput_) {
reset_aggregator_in_processinput_ = false;
key_->Reset();
// Compacting GroupKeySet to release more memory. This is a workaround for
// having (allocator_->Available() == 0) constantly, which would allow to
// only process one block of input data per call to ProcessInput(). However,
// freeing the underlying datastructures and building them from scratch many
// times can be inefficient.
// TODO(user): Implement a less aggressive solution to this problem.
key_->Compact();
aggregator_->Reset();
}
rowcount_t row_count = key_->size();
// Process the input while not exhausted and memory quota not exceeded.
// (But, test the condition at the end of the loop, to guarantee that we
// process at least one chunk of the input data).
do {
// Fetch next block from the input.
if (!PREDICT_TRUE(child_.Next(Cursor::kDefaultRowCount, false))) {
PROPAGATE_ON_FAILURE(child_);
if (!child_.has_data()) {
if (child_.is_eos()) {
input_exhausted_ = true;
} else {
DCHECK(child_.is_waiting_on_barrier());
DCHECK(!reset_aggregator_in_processinput_);
return Success();
}
}
break;
}
// Add new rows to the key set.
child_.truncate(key_->Insert(child_.view(), &inserted_keys_));
if (child_.view().row_count() == 0) {
// Failed to add any new keys.
break;
}
row_count = key_->size();
if (aggregator_->capacity() < row_count) {
// Not enough space to hold the aggregate columns; need to reallocate.
// But, if already over quota, give up.
if (allocator_->Available() == 0) {
// Rewind the input and ignore trailing rows.
row_count = aggregator_->capacity();
for (rowid_t i = 0; i < child_.view().row_count(); ++i) {
if (inserted_keys_.row_ids()[i] >= row_count) {
child_.truncate(i);
break;
}
}
} else {
if (original_allocator_->Available() < allocator_->Available()) {
THROW(new Exception(ERROR_MEMORY_EXCEEDED,
"Underlying allocator ran out of memory."));
}
// Still have spare memory; reallocate.
rowcount_t requested_capacity = std::max(2 * aggregator_->capacity(),
row_count);
if (!aggregator_->Reallocate(requested_capacity)) {
// OOM when trying to make more room for aggregate columns. Rewind the
// last input block, so that it is re-fetched by the next
// ProcessInput, and break out of the loop, returning what we have up
// to now.
row_count = aggregator_->capacity();
child_.truncate(0);
break;
}
}
}
// Update the aggregate columns w/ new rows.
PROPAGATE_ON_FAILURE(
aggregator_->UpdateAggregations(child_.view(),
inserted_keys_.row_ids()));
} while (allocator_->Available() > 0);
if (!input_exhausted_) {
if (best_effort_) {
if (row_count == 0) {
THROW(new Exception(
ERROR_MEMORY_EXCEEDED,
StringPrintf(
"In best-effort mode, failed to process even a single row. "
"Memory free: %zd",
allocator_->Available())));
}
} else { // Non-best-effort.
THROW(new Exception(
ERROR_MEMORY_EXCEEDED,
StringPrintf(
"Failed to process the entire input. "
"Memory free: %zd",
allocator_->Available())));
}
}
const View* views[] = { &key_->key_view(), &aggregator_->data() };
result_projector_->Project(&views[0], &views[2], my_view());
my_view()->set_row_count(row_count);
result_.reset(*my_view());
reset_aggregator_in_processinput_ = true;
return Success();
}
class GroupAggregateOperation : public BasicOperation {
public:
// Takes ownership of SingleSourceProjector, AggregationSpecification and
// child_operation.
GroupAggregateOperation(const SingleSourceProjector* group_by,
const AggregationSpecification* aggregation,
GroupAggregateOptions* options,
bool best_effort,
Operation* child)
: BasicOperation(child),
group_by_(group_by),
aggregation_specification_(aggregation),
best_effort_(best_effort),
options_(options != NULL ? options : new GroupAggregateOptions()) {}
virtual ~GroupAggregateOperation() {}
virtual FailureOrOwned<Cursor> CreateCursor() const {
FailureOrOwned<Cursor> child_cursor = child()->CreateCursor();
PROPAGATE_ON_FAILURE(child_cursor);
BufferAllocator* original_allocator = buffer_allocator();
std::unique_ptr<BufferAllocator> allocator;
if (options_->enforce_quota()) {
allocator.reset(new GuaranteeMemory(options_->memory_quota(),
original_allocator));
} else {
allocator.reset(new MemoryLimit(
options_->memory_quota(), false, original_allocator));
}
FailureOrOwned<Aggregator> aggregator = Aggregator::Create(
*aggregation_specification_, child_cursor->schema(),
allocator.get(),
options_->estimated_result_row_count());
PROPAGATE_ON_FAILURE(aggregator);
FailureOrOwned<const BoundSingleSourceProjector> bound_group_by =
group_by_->Bind(child_cursor->schema());
PROPAGATE_ON_FAILURE(bound_group_by);
return BoundGroupAggregateWithLimit(
bound_group_by.release(), aggregator.release(),
allocator.release(),
original_allocator,
best_effort_,
options_->max_unique_keys_in_result(),
child_cursor.release());
}
private:
std::unique_ptr<const SingleSourceProjector> group_by_;
std::unique_ptr<const AggregationSpecification> aggregation_specification_;
const bool best_effort_;
std::unique_ptr<GroupAggregateOptions> options_;
DISALLOW_COPY_AND_ASSIGN(GroupAggregateOperation);
};
// Hybrid group implementation classes and functions.
// Hybrid group aggregate uses disk-based sorting to allow processing more data
// than would fit in memory.
//
// The key steps of the algorithm are:
// - DISTINCT aggregation elimination
// - preaggregation with best-effort GroupAggregate
// - sorting the preaggregated data
// - combining preaggregated rows on duplicate keys
// - final aggregation using AggregateClusters.
//
// The motivation for eliminating DISINCT aggregations is threefold:
// - partial results of DISTINCT aggregations can't be easily combined,
// - building a whole set of unique values of an attribute for a single key can
// take arbitrary amount of memory,
// - existing code for computing DISTINCT aggregations doesn't track the memory
// needed for tracking sets of unique values,
// Here DISTINCT aggregations are eliminated by removing duplicate values in
// DISTINCT aggregated columns, so these aggregations can then be computed with
// ordinary, non-DISTINCT aggregating functions. This is done by adding DISTINCT
// aggregated columns to the preaggregation key. To get unique values for each
// DISTINCT aggregated column, each column needs to be processed separately. It
// is achieved by transforming the input in such a way that each DISTINCT
// aggregated column gets its copy of rows, where all other distinct aggregated
// columns are set to NULL. This is the job of BoundHybridGroupTransform. The
// approach used here relies heavily on the way NULLs are handled in
// aggregation, most notably:
// - NULLs in grouping key is treated as a distinct value,
// - except for COUNT(*) aggregating functions ignore NULL input values.
//
// The next step is to preaggregate the (possibly transformed) input data using
// best-effort GroupAggregate on a key extended with any DISTINCT aggregated
// columns. This is done to reduce the amount of data that will need to be
// sorted before final aggregation. Also, when there are no DISTINCT
// aggregations best-effort preaggregation may manage to fully aggregate the
// input - in this case sorting and final aggregation is not needed (which
// improves performance).
//
// The preaggregated data is then sorted on the extended key and
// AggregateClusters is performed to combine rows with equal keys. In the last
// step final aggregation is performed with AggregateClusters on the original
// key.
// Analyzes grouping specification and sets up parameters for various stages of
// hybrid group implementation.
class HybridGroupSetup {
public:
// Takes ownership of input.
static FailureOrOwned<const HybridGroupSetup> Create(
const SingleSourceProjector& group_by_columns,
const AggregationSpecification& aggregation_specification,
const TupleSchema& input_schema) {
std::unique_ptr<HybridGroupSetup> setup(new HybridGroupSetup);
PROPAGATE_ON_FAILURE(setup->Init(group_by_columns,
aggregation_specification,
input_schema));
return Success(setup.release());
}
// For restoring non-nullability of COUNT columns in hybrid group by. We
// combine partial COUNT results using SUM and SUM's result is nullable.
// TODO(user): This would be unneccesary if we could specify that SUM's result
// should be not nullable.
FailureOrOwned<Cursor> MakeCountColumnsNotNullable(
Cursor* cursor,
BufferAllocator* allocator) const {
CHECK(initialized_);
vector<string> column_names(columns_to_make_not_nullable_.begin(),
columns_to_make_not_nullable_.end());
return column_names.empty()
? Success(cursor)
: MakeSelectedColumnsNotNullable(ProjectNamedAttributes(column_names),
allocator, cursor);
}
// Computes the result schema for HybridGroupFinalAggregationCursor.
FailureOr<TupleSchema> ComputeResultSchema(
const TupleSchema& group_by_columns_schema,
const TupleSchema& aggregator_schema) const {
CHECK(initialized_);
FailureOr<TupleSchema> result_schema_bad_nullability =
TupleSchema::TryMerge(group_by_columns_schema, aggregator_schema);
PROPAGATE_ON_FAILURE(result_schema_bad_nullability);
// Fixing nullability of COUNT columns. They may be wrong in
// final_aggregator->schema() because final_aggregation uses SUM to compute
// final results of COUNT(column) and SUMS's result is nullable.
TupleSchema result_schema;
for (int i = 0; i < result_schema_bad_nullability.get().attribute_count();
++i) {
const Attribute& attribute =
result_schema_bad_nullability.get().attribute(i);
result_schema.add_attribute(
Attribute(attribute.name(),
attribute.type(),
ContainsKey(columns_to_make_not_nullable_, attribute.name())
? NOT_NULLABLE
: attribute.nullability()));
}
return Success(result_schema);
}
// Returns a cursor with input transformed for hybrid group.
FailureOrOwned<Cursor> TransformInput(BufferAllocator* allocator,
Cursor* input) const {
CHECK(initialized_);
std::unique_ptr<Cursor> input_owned(input);
if (count_star_present_) {
// Add a column with non-null values for implementing COUNT(*).
FailureOrOwned<Cursor> input_with_count_star(
ExtendByConstantColumn(count_star_column_name_, allocator,
input_owned.release()));
PROPAGATE_ON_FAILURE(input_with_count_star);
input_owned.reset(input_with_count_star.release());
}
return BoundHybridGroupTransform(
group_by_columns_->Clone(),
column_group_projectors_,
allocator,
input_owned.release());
}
const AggregationSpecification& pregroup_aggregation() const {
CHECK(initialized_);
return pregroup_aggregation_;
}
const AggregationSpecification& pregroup_combine_aggregation() const {
CHECK(initialized_);
return pregroup_combine_aggregation_;
}
const AggregationSpecification& final_aggregation() const {
CHECK(initialized_);
return final_aggregation_;
}
const SingleSourceProjector& pregroup_group_by_columns() const {
CHECK(initialized_);
return pregroup_group_by_columns_;
}
bool has_distinct_aggregations() const {
CHECK(initialized_);
return has_distinct_aggregations_;
}
const SingleSourceProjector& group_by_columns_by_name() const {
CHECK(initialized_);
return *group_by_columns_by_name_;
}
private:
HybridGroupSetup()
: initialized_(false),
count_star_column_name_("$hybrid_group_count_star$") {}
FailureOrVoid Init(
const SingleSourceProjector& group_by_columns,
const AggregationSpecification& aggregation_specification,
const TupleSchema& input_schema) {
CHECK(!initialized_);
group_by_columns_.reset(group_by_columns.Clone());
has_distinct_aggregations_ = false;
count_star_present_ = false;
// Hybrid group-by may need to project group-by columns multiple times
// over transformed inputs, and it wouldn't work if the projector was
// renaming columns, selecting columns by position or taking all input
// columns. Because of this, in later stages of processing we use a
// projector based on result column names of the original projector.
FailureOrOwned<const SingleSourceProjector> group_by_columns_by_name(
ProjectUsingProjectorResultNames(group_by_columns, input_schema));
PROPAGATE_ON_FAILURE(group_by_columns_by_name);
group_by_columns_by_name_.reset(group_by_columns_by_name.release());
// pregroup_group_by_columns_ will contain all the original group-by columns
// plus all the distinct aggregated columns.
pregroup_group_by_columns_.add(group_by_columns_by_name_->Clone());
set<string> distinct_columns_set;
set<string> nondistinct_columns_set;
CompoundSingleSourceProjector nondistinct_columns;
for (int i = 0; i < aggregation_specification.size(); ++i) {
const AggregationSpecification::Element& elem =
aggregation_specification.aggregation(i);
const string pregroup_column_prefix =
elem.is_distinct()
? "$hybrid_group_pregroup_column_d$"
: "$hybrid_group_pregroup_column_nd$";
const string pregroup_column_name = StrCat(pregroup_column_prefix,
elem.input());
AggregationSpecification::Element final_elem(elem);
if (elem.is_distinct()) {
has_distinct_aggregations_ = true;
// <aggregate-function>(DISTINCT col).
if (elem.input() == "") {
THROW(new Exception(
ERROR_ATTRIBUTE_MISSING,
StringPrintf("Incorrect aggregation specification. Distinct "
"aggregation needs input column.")));
}
if (InsertIfNotPresent(&distinct_columns_set, elem.input())) {
column_group_projectors_.push_back(
ProjectNamedAttributeAs(elem.input(),
pregroup_column_name));
pregroup_group_by_columns_.add(
ProjectNamedAttributeAs(pregroup_column_name,
pregroup_column_name));
}
// No need to add anything to pregroup_aggregation_.
final_elem.set_input(pregroup_column_name);
} else {
AggregationSpecification::Element pregroup_elem(elem);
// <aggregate-function>(col) or COUNT(*).
if (elem.input() != "") {
if (InsertIfNotPresent(&nondistinct_columns_set, elem.input())) {
nondistinct_columns.add(
ProjectNamedAttributeAs(elem.input(),
pregroup_column_name));
}
pregroup_elem.set_input(pregroup_column_name);
} else {
count_star_present_ = true;
pregroup_elem.set_input(count_star_column_name_);
}
final_elem.set_input(pregroup_elem.output());
if (elem.aggregation_operator() == COUNT) {
columns_to_make_not_nullable_.insert(final_elem.output());
final_elem.set_aggregation_operator(SUM);
}
AggregationSpecification::Element pregroup_combine_elem(final_elem);
pregroup_combine_elem.set_output(pregroup_combine_elem.input());
pregroup_aggregation_.add(pregroup_elem);
pregroup_combine_aggregation_.add(pregroup_combine_elem);
}
final_aggregation_.add(final_elem);
}
if (count_star_present_) {
// Add a column with non-null values for implementing COUNT(*).
nondistinct_columns.add(
ProjectNamedAttributeAs(count_star_column_name_,
count_star_column_name_));
}
if (!nondistinct_columns_set.empty() || count_star_present_ ||
column_group_projectors_.empty()) {
column_group_projectors_.push_back(nondistinct_columns.Clone());
}
initialized_ = true;
return Success();
}
static FailureOrOwned<const SingleSourceProjector>
ProjectUsingProjectorResultNames(const SingleSourceProjector& projector,
const TupleSchema& schema) {
FailureOrOwned<const BoundSingleSourceProjector> bound_projector(
projector.Bind(schema));
PROPAGATE_ON_FAILURE(bound_projector);
const TupleSchema& result_schema = bound_projector->result_schema();
vector<string> result_names;
for (int i = 0; i < result_schema.attribute_count(); ++i) {
result_names.push_back(result_schema.attribute(i).name());
}
return Success(ProjectNamedAttributes(result_names));
}
private:
// Was the object initialized successfully with Init(...).
bool initialized_;
// Does the AggregationSpecification contain DISTINCT aggregations?
bool has_distinct_aggregations_;
// Does the AggregationSpecification contain COUNT(*)?
bool count_star_present_;
// The name of the column added for COUNT(*) implementation.
const string count_star_column_name_;
// The original group by columns projector.
std::unique_ptr<const SingleSourceProjector> group_by_columns_;
// A safe projector for use in later processing, based on the result
// names of the original group_by_columns_ projector.
std::unique_ptr<const SingleSourceProjector> group_by_columns_by_name_;
// A set of COUNT columns (names) that will need nullability fixing because
// the implementation uses SUM on later (post pregroup) stages.
set<string> columns_to_make_not_nullable_;
// A set of projectors that define column groups for the
// HybridGroupTransformCursor. There's a separate projector for each column
// that has DISTINCT aggregations on it, and a shared projector for all
// columns that have non-DISTINCT aggregations on them.
util::gtl::PointerVector<const SingleSourceProjector>
column_group_projectors_;
// Group-by columns for the pregroup aggregation (will additionally contain
// distinct aggregated columns).
CompoundSingleSourceProjector pregroup_group_by_columns_;
// The initial (pregroup) aggregation.
AggregationSpecification pregroup_aggregation_;
// Aggregation for combining results of pregroup for duplicated keys.
AggregationSpecification pregroup_combine_aggregation_;
// Final aggregation combining results of pregroup aggregation for
// non-DISTINCT aggregations and using ordinary, non-DISTINCT aggregations in
// place of original DISTINCT aggregations.
AggregationSpecification final_aggregation_;
DISALLOW_COPY_AND_ASSIGN(HybridGroupSetup);
};
// Combines preaggregated results on repeated (extended) keys and the final
// aggregation to compute the results for DISTINCT aggregations.
class HybridGroupFinalAggregationCursor : public BasicCursor {
public:
// Takes ownership of hybrid_group_setup, final_aggregator,
// final_group_by_columns and pregroup_cursor.
HybridGroupFinalAggregationCursor(
const TupleSchema& result_schema,
const HybridGroupSetup* hybrid_group_setup,
Aggregator* final_aggregator,
const BoundSingleSourceProjector* final_group_by_columns,
StringPiece temporary_directory_prefix,
BufferAllocator* allocator,
GroupAggregateCursor* pregroup_cursor)
: BasicCursor(result_schema),
is_waiting_on_barrier_supported_(
pregroup_cursor->IsWaitingOnBarrierSupported()),
hybrid_group_setup_(hybrid_group_setup),
final_aggregator_(final_aggregator),
final_group_by_columns_(final_group_by_columns),
temporary_directory_prefix_(temporary_directory_prefix.ToString()),
allocator_(allocator),
pregroup_cursor_(pregroup_cursor) {
}
virtual ResultView Next(rowcount_t max_row_count) {
if (result_cursor_ == NULL && sorter_ == NULL) {
ResultView first_result = pregroup_cursor_->Next(
numeric_limits<rowcount_t>::max());
if (first_result.is_eos() || !first_result.has_data()) {
return first_result;
}
if (!pregroup_cursor_->CanReturnMoreData() &&
!hybrid_group_setup_->has_distinct_aggregations()) {
pregroup_cursor_->TruncateResultView();
// There are no distinct aggregations, so if pregroup fully aggregated
// all the data (a single output block), its result can be returned as
// final result.
LOG(INFO) << "HybridGroupAggregate not using disk.";
PROPAGATE_ON_FAILURE(SetResultCursor(pregroup_cursor_.release()));
} else {
// Pregroup best-effort didn't fully aggregate the data. Sorting data to
// combine duplicate pregroup keys. The final aggregation will be
// performed using AggregateClusters, as the data will also be sorted on
// the original key.
if (first_result.has_data()) {
pregroup_cursor_->TruncateResultView();
}
LOG(INFO) << "HybridGroupAggregate using disk ("
<< (hybrid_group_setup_->has_distinct_aggregations()
? "distinct aggregations" : "best-effort failed")
<< ").";
FailureOrOwned<const BoundSingleSourceProjector> bound_group_by_columns(
hybrid_group_setup_->pregroup_group_by_columns().Bind(
pregroup_cursor_->schema()));
PROPAGATE_ON_FAILURE(bound_group_by_columns);
sorter_.reset(CreateUnbufferedSorter(
pregroup_cursor_->schema(),
new BoundSortOrder(bound_group_by_columns.release()),
temporary_directory_prefix_,
allocator_));
}
}
if (result_cursor_ == NULL && sorter_ != NULL) {
while (true) {
ResultView result = pregroup_cursor_->Next(
numeric_limits<rowcount_t>::max());
PROPAGATE_ON_FAILURE(result);
if (result.is_waiting_on_barrier()) {
return ResultView::WaitingOnBarrier();
}
if (result.is_eos()) {
break;
}
VLOG(1) << "Writing " << result.view().row_count()
<< " rows to UnbufferedSorter.";
FailureOr<rowcount_t> written = sorter_->Write(result.view());
PROPAGATE_ON_FAILURE(written);
CHECK_EQ(written.get(), result.view().row_count());
}
// Aggregate to combine duplicated pregroup keys.
FailureOrOwned<Cursor> sorted = sorter_->GetResultCursor();
PROPAGATE_ON_FAILURE(sorted);
sorter_.reset();
FailureOrOwned<Aggregator> aggregator = Aggregator::Create(
hybrid_group_setup_->pregroup_combine_aggregation(),
sorted.get()->schema(),
allocator_,
1024);
PROPAGATE_ON_FAILURE(aggregator);
FailureOrOwned<const BoundSingleSourceProjector> sorted_group_by_columns =
hybrid_group_setup_->pregroup_group_by_columns().Bind(
sorted.get()->schema());
PROPAGATE_ON_FAILURE(sorted_group_by_columns);
FailureOrOwned<Cursor> combine_cursor =
BoundAggregateClusters(
sorted_group_by_columns.release(),
aggregator.release(),
allocator_,
sorted.release());
PROPAGATE_ON_FAILURE(combine_cursor);
// Restoring COUNT column nullability, so we have exactly the same schema
// that final_aggregator was built for.
FailureOrOwned<Cursor> combine_cursor_count_nonnullable =
hybrid_group_setup_->MakeCountColumnsNotNullable(
combine_cursor.release(), allocator_);
PROPAGATE_ON_FAILURE(combine_cursor_count_nonnullable);
// Final aggregation on the original key using AggregateClusters.
FailureOrOwned<Cursor> aggregated = BoundAggregateClusters(
final_group_by_columns_.release(),
final_aggregator_.release(),
allocator_,
combine_cursor_count_nonnullable.release());
PROPAGATE_ON_FAILURE(aggregated);
PROPAGATE_ON_FAILURE(SetResultCursor(aggregated.release()));
}
CHECK(sorter_ == NULL);
CHECK(result_cursor_ != NULL);
ResultView result = result_cursor_->Next(max_row_count);
PROPAGATE_ON_FAILURE(result);
return result;
}
virtual bool IsWaitingOnBarrierSupported() const {
return is_waiting_on_barrier_supported_;
}
virtual void Interrupt() {
Cursor* pregroup_cursor = pregroup_cursor_.get();
if (pregroup_cursor != NULL) {
pregroup_cursor->Interrupt();
}
Cursor* result_cursor = result_cursor_.get();
if (result_cursor != NULL) {
result_cursor->Interrupt();
}
}
virtual CursorId GetCursorId() const {
return HYBRID_GROUP_FINAL_AGGREGATION;
}
// Runs the transformer recursively on the pregrouping aggregate cursor.
//
// This solution effectively omits the transformation of the pregrouping
// cursor, as it conflicts with the return type of Transform().
// The hybrid aggregate and pregroup aggregate cursor are treated as one
// by cursor transformers.
virtual void ApplyToChildren(CursorTransformer* transformer) {
pregroup_cursor_->ApplyToChildren(transformer);
}
private:
FailureOrVoid SetResultCursor(Cursor* result_cursor) {
FailureOrOwned<Cursor> result_cursor_fixed_nullability =
hybrid_group_setup_->MakeCountColumnsNotNullable(
result_cursor, allocator_);
PROPAGATE_ON_FAILURE(result_cursor_fixed_nullability);
result_cursor_.reset(result_cursor_fixed_nullability.release());
CHECK(TupleSchema::AreEqual(schema(), result_cursor_->schema(), true))
<< "schema(): "
<< schema().GetHumanReadableSpecification()
<< "\naggregated_owned->schema(): "
<< result_cursor_->schema().GetHumanReadableSpecification();
return Success();
}
bool is_waiting_on_barrier_supported_;
std::unique_ptr<const HybridGroupSetup> hybrid_group_setup_;
std::unique_ptr<Aggregator> final_aggregator_;
std::unique_ptr<const BoundSingleSourceProjector> final_group_by_columns_;
size_t memory_quota_;
string temporary_directory_prefix_;
BufferAllocator* allocator_;
std::unique_ptr<GroupAggregateCursor> pregroup_cursor_;
std::unique_ptr<Sorter> sorter_;
std::unique_ptr<Cursor> result_cursor_;
DISALLOW_COPY_AND_ASSIGN(HybridGroupFinalAggregationCursor);
};
} // namespace
Operation* GroupAggregate(
const SingleSourceProjector* group_by,
const AggregationSpecification* aggregation,
GroupAggregateOptions* options,
Operation* child) {
return new GroupAggregateOperation(group_by, aggregation, options, false,
child);
}
Operation* BestEffortGroupAggregate(
const SingleSourceProjector* group_by,
const AggregationSpecification* aggregation,
GroupAggregateOptions* options,
Operation* child) {
return new GroupAggregateOperation(group_by, aggregation, options, true,
child);
}
// TODO(user): Remove this variant in favor of BoundGroupAggregateWithLimit
FailureOrOwned<Cursor> BoundGroupAggregate(
const BoundSingleSourceProjector* group_by,
Aggregator* aggregator,
BufferAllocator* allocator,
BufferAllocator* original_allocator,
bool best_effort,
Cursor* child) {
return BoundGroupAggregateWithLimit(group_by,
aggregator,
allocator,
original_allocator,
best_effort,
kint64max,
child);
}
FailureOrOwned<Cursor> BoundGroupAggregateWithLimit(
const BoundSingleSourceProjector* group_by,
Aggregator* aggregator,
BufferAllocator* allocator,
BufferAllocator* original_allocator,
bool best_effort,
const int64 max_unique_keys_in_result,
Cursor* child) {
FailureOrOwned<GroupAggregateCursor> result =
GroupAggregateCursor::Create(
group_by, aggregator, allocator,
original_allocator == NULL ? allocator : original_allocator,
best_effort, max_unique_keys_in_result, child);
PROPAGATE_ON_FAILURE(result);
return Success(result.release());
}
FailureOrOwned<Cursor> BoundHybridGroupAggregate(
const SingleSourceProjector* group_by_columns,
const AggregationSpecification& aggregation_specification,
StringPiece temporary_directory_prefix,
BufferAllocator* allocator,
size_t memory_quota,
const HybridGroupDebugOptions* debug_options,
Cursor* child) {
std::unique_ptr<Cursor> child_owner(child);
std::unique_ptr<const SingleSourceProjector> group_by_columns_owner(
group_by_columns);
std::unique_ptr<const HybridGroupDebugOptions> debug_options_owned(
debug_options);
FailureOrOwned<const HybridGroupSetup> hybrid_group_setup(
HybridGroupSetup::Create(*group_by_columns_owner,
aggregation_specification,
child_owner->schema()));
PROPAGATE_ON_FAILURE(hybrid_group_setup);
FailureOrOwned<Cursor> transformed_input(
hybrid_group_setup->TransformInput(allocator, child_owner.release()));
PROPAGATE_ON_FAILURE(transformed_input);
if (debug_options_owned != NULL &&
debug_options_owned->return_transformed_input()) {
return transformed_input;
}
// Use best-effort group aggregate to pregroup the data.
FailureOrOwned<const BoundSingleSourceProjector> bound_pregroup_columns(
hybrid_group_setup->pregroup_group_by_columns().Bind(
transformed_input->schema()));
PROPAGATE_ON_FAILURE(bound_pregroup_columns);
// limit_allocator will be owned by 'pregroup_cursor'.
std::unique_ptr<BufferAllocator> limit_allocator(
new MemoryLimit(memory_quota, false, allocator));
FailureOrOwned<Aggregator> pregroup_aggregator = Aggregator::Create(
hybrid_group_setup->pregroup_aggregation(), transformed_input->schema(),
limit_allocator.get(),
1024);
PROPAGATE_ON_FAILURE(pregroup_aggregator);
FailureOrOwned<GroupAggregateCursor> pregroup_cursor =
GroupAggregateCursor::Create(
bound_pregroup_columns.release(),
pregroup_aggregator.release(),
limit_allocator.release(),
allocator,
true, // best effort.
kint64max,
transformed_input.release());
PROPAGATE_ON_FAILURE(pregroup_cursor);
// Building final_aggregator and final_group_by_columns to compute the
// result_schema for HybridGroupFinalAggregationCursor.
FailureOrOwned<Aggregator> final_aggregator = Aggregator::Create(
hybrid_group_setup->final_aggregation(),
pregroup_cursor->schema(),
allocator,
1024);
PROPAGATE_ON_FAILURE(final_aggregator);
FailureOrOwned<const BoundSingleSourceProjector> final_group_by_columns(
hybrid_group_setup->group_by_columns_by_name().Bind(
pregroup_cursor->schema()));
PROPAGATE_ON_FAILURE(final_group_by_columns);
// Calculate the schema of the final cursor.
FailureOr<TupleSchema> result_schema =
hybrid_group_setup->ComputeResultSchema(
final_group_by_columns->result_schema(),
final_aggregator->schema());
PROPAGATE_ON_FAILURE(result_schema);
return Success(new HybridGroupFinalAggregationCursor(
result_schema.get(),
hybrid_group_setup.release(),
final_aggregator.release(),
final_group_by_columns.release(),
temporary_directory_prefix,
allocator,
pregroup_cursor.release()));
}
class HybridGroupAggregateOperation : public BasicOperation {
public:
HybridGroupAggregateOperation(
const SingleSourceProjector* group_by_columns,
const AggregationSpecification* aggregation_specification,
size_t memory_quota,
StringPiece temporary_directory_prefix,
Operation* child)
: BasicOperation(child),
group_by_columns_(group_by_columns),
aggregation_specification_(aggregation_specification),
memory_quota_(memory_quota),
temporary_directory_prefix_(temporary_directory_prefix.ToString()) {}
virtual ~HybridGroupAggregateOperation() {}
virtual FailureOrOwned<Cursor> CreateCursor() const {
FailureOrOwned<Cursor> child_cursor = child()->CreateCursor();
PROPAGATE_ON_FAILURE(child_cursor);
return BoundHybridGroupAggregate(
group_by_columns_->Clone(),
*aggregation_specification_,
temporary_directory_prefix_,
buffer_allocator(),
memory_quota_,
NULL,
child_cursor.release());
}
private:
std::unique_ptr<const SingleSourceProjector> group_by_columns_;
std::unique_ptr<const AggregationSpecification> aggregation_specification_;
size_t memory_quota_;
string temporary_directory_prefix_;
DISALLOW_COPY_AND_ASSIGN(HybridGroupAggregateOperation);
};
Operation* HybridGroupAggregate(
const SingleSourceProjector* group_by_columns,
const AggregationSpecification* aggregation_specification,
size_t memory_quota,
StringPiece temporary_directory_prefix,
Operation* child) {
return new HybridGroupAggregateOperation(group_by_columns,
aggregation_specification,
memory_quota,
temporary_directory_prefix,
child);
}
} // namespace supersonic
| 41.669828
| 80
| 0.701781
|
IssamElbaytam
|
acc5d6b6567be09ad8389cda0ec835b7f7bc50ab
| 23,914
|
cpp
|
C++
|
src/states/main-state.cpp
|
xterminal86/nrogue
|
1d4e578b3d854b8e4d41f5ba1477de9b2c9e864f
|
[
"MIT"
] | 7
|
2019-03-05T05:32:13.000Z
|
2022-01-10T10:06:47.000Z
|
src/states/main-state.cpp
|
xterminal86/nrogue
|
1d4e578b3d854b8e4d41f5ba1477de9b2c9e864f
|
[
"MIT"
] | 2
|
2020-01-19T16:43:51.000Z
|
2021-12-16T14:54:56.000Z
|
src/states/main-state.cpp
|
xterminal86/nrogue
|
1d4e578b3d854b8e4d41f5ba1477de9b2c9e864f
|
[
"MIT"
] | null | null | null |
#include "main-state.h"
#include "application.h"
#include "map.h"
#include "printer.h"
#include "stairs-component.h"
#include "target-state.h"
#include "spells-processor.h"
void MainState::Init()
{
_playerRef = &Application::Instance().PlayerInstance;
}
void MainState::HandleInput()
{
//
// Otherwise we could still time-in some action
// even after we received fatal damage.
//
// E.g. we wait a turn, spider approaches and deals fatal damage,
// this results in Player.IsAlive = false, but if we check IsAlive()
// at the end of HandleInput(), we could still issue some other command
// if we are quick enough before condition is checked
// and current state changes to ENDGAME_STATE.
//
if (!_playerRef->IsAlive())
{
Application::Instance().ChangeState(GameStates::ENDGAME_STATE);
return;
}
_keyPressed = GetKeyDown();
switch (_keyPressed)
{
case ALT_K7:
case NUMPAD_7:
ProcessMovement({ -1, -1 });
break;
case ALT_K8:
case NUMPAD_8:
ProcessMovement({ 0, -1 });
break;
case ALT_K9:
case NUMPAD_9:
ProcessMovement({ 1, -1 });
break;
case ALT_K4:
case NUMPAD_4:
ProcessMovement({ -1, 0 });
break;
case ALT_K2:
case NUMPAD_2:
ProcessMovement({ 0, 1 });
break;
case ALT_K6:
case NUMPAD_6:
ProcessMovement({ 1, 0 });
break;
case ALT_K1:
case NUMPAD_1:
ProcessMovement({ -1, 1 });
break;
case ALT_K3:
case NUMPAD_3:
ProcessMovement({ 1, 1 });
break;
case ALT_K5:
case NUMPAD_5:
Printer::Instance().AddMessage(Strings::MsgWait);
_playerRef->FinishTurn();
break;
case 'a':
{
if (Map::Instance().CurrentLevel->Peaceful)
{
PrintNoAttackInTown();
}
else if (_playerRef->IsSwimming())
{
Printer::Instance().AddMessage(Strings::MsgNotInWater);
}
else
{
Application::Instance().ChangeState(GameStates::ATTACK_STATE);
}
}
break;
case '$':
{
auto str = Util::StringFormat("You have %i %s",
_playerRef->Money,
Strings::MoneyName.data());
Printer::Instance().AddMessage(str);
}
break;
case 'e':
Application::Instance().ChangeState(GameStates::INVENTORY_STATE);
break;
case 'm':
Application::Instance().ChangeState(GameStates::SHOW_MESSAGES_STATE);
break;
case 'l':
Application::Instance().ChangeState(GameStates::LOOK_INPUT_STATE);
break;
case 'i':
Application::Instance().ChangeState(GameStates::INTERACT_INPUT_STATE);
break;
case 'I':
DisplayScenarioInformation();
break;
case 'g':
TryToPickupItem();
break;
case '@':
Application::Instance().ChangeState(GameStates::INFO_STATE);
break;
case 'H':
case 'h':
case '?':
Application::Instance().ChangeState(GameStates::HELP_STATE);
break;
case 'Q':
Application::Instance().ChangeState(GameStates::EXITING_STATE);
break;
case 'f':
ProcessRangedWeapon();
break;
case '>':
{
auto res = CheckStairs('>');
if (res.first != nullptr)
{
ClimbStairs(res);
}
}
break;
case '<':
{
auto res = CheckStairs('<');
if (res.first != nullptr)
{
ClimbStairs(res);
}
}
break;
#ifdef DEBUG_BUILD
case '`':
Application::Instance().ChangeState(GameStates::DEV_CONSOLE);
break;
case 'T':
{
int exitX = Map::Instance().CurrentLevel->LevelExit.X;
int exitY = Map::Instance().CurrentLevel->LevelExit.Y;
if (_playerRef->MoveTo(exitX, exitY))
{
Map::Instance().CurrentLevel->AdjustCamera();
Update(true);
_playerRef->FinishTurn();
}
else
{
auto str = Util::StringFormat("[%i;%i] is occupied!", exitX, exitY);
Printer::Instance().AddMessage(str);
DebugLog("%s\n", str.data());
}
}
break;
case 's':
GetActorsAround();
break;
#endif
default:
break;
}
}
void MainState::Update(bool forceUpdate)
{
if (_keyPressed != -1 || forceUpdate)
{
Printer::Instance().Clear();
_playerRef->CheckVisibility();
Map::Instance().Draw();
_playerRef->Draw();
DisplayStartHint();
DisplayExitHint();
DisplayStatusIcons();
DrawHPMP();
if (Printer::Instance().ShowLastMessage)
{
DisplayGameLog();
}
else
{
Printer::Instance().ResetMessagesToDisplay();
}
Printer::Instance().PrintFB(Printer::TerminalWidth - 1,
0,
Map::Instance().CurrentLevel->LevelName,
Printer::kAlignRight,
Colors::WhiteColor);
#ifdef DEBUG_BUILD
PrintDebugInfo();
#endif
Printer::Instance().Render();
}
}
void MainState::ProcessMovement(const Position& dirOffsets)
{
// TODO: levitation
if (_playerRef->TryToAttack(dirOffsets.X, dirOffsets.Y))
{
_playerRef->FinishTurn();
}
else if (_playerRef->Move(dirOffsets.X, dirOffsets.Y))
{
// This line must be the first in order to
// allow potential messages to show in FinishTurn()
// (e.g. starvation damage message) after player moved.
Printer::Instance().ShowLastMessage = false;
Map::Instance().CurrentLevel->MapOffsetX -= dirOffsets.X;
Map::Instance().CurrentLevel->MapOffsetY -= dirOffsets.Y;
_playerRef->FinishTurn();
auto& px = _playerRef->PosX;
auto& py = _playerRef->PosY;
// Sometimes loot can drop on top of stairs
// which can make them hard to find on map.
if(Map::Instance().CurrentLevel->MapArray[px][py]->Image == '>')
{
Printer::Instance().AddMessage(Strings::MsgStairsDown);
}
else if(Map::Instance().CurrentLevel->MapArray[px][py]->Image == '<')
{
Printer::Instance().AddMessage(Strings::MsgStairsUp);
}
}
}
void MainState::DisplayGameLog()
{
int x = Printer::TerminalWidth - 1;
int y = Printer::TerminalHeight - 1;
int count = 0;
auto msgs = Printer::Instance().GetLastMessages();
for (auto& m : msgs)
{
Printer::Instance().PrintFB(x,
y - count,
m.Message,
Printer::kAlignRight,
m.FgColor,
m.BgColor);
count++;
}
}
void MainState::TryToPickupItem()
{
auto res = Map::Instance().GetGameObjectToPickup(_playerRef->PosX, _playerRef->PosY);
if (res.first != -1)
{
if (ProcessMoneyPickup(res))
{
CheckIfSomethingElseIsLyingHere({ _playerRef->PosX, _playerRef->PosY });
return;
}
if (_playerRef->Inventory.IsFull())
{
Application::Instance().ShowMessageBox(MessageBoxType::ANY_KEY,
Strings::MessageBoxEpicFailHeaderText,
{ Strings::MsgInventoryFull },
Colors::MessageBoxRedBorderColor);
return;
}
ProcessItemPickup(res);
CheckIfSomethingElseIsLyingHere({ _playerRef->PosX, _playerRef->PosY });
}
else
{
Printer::Instance().AddMessage(Strings::MsgNothingHere);
}
}
void MainState::CheckIfSomethingElseIsLyingHere(const Position& pos)
{
auto res = Map::Instance().GetGameObjectToPickup(pos.X, pos.Y);
if (res.first != -1)
{
Printer::Instance().AddMessage(Strings::MsgSomethingLying);
}
}
void MainState::DrawHPMP()
{
int curHp = _playerRef->Attrs.HP.Min().Get();
int maxHp = _playerRef->Attrs.HP.Max().Get();
int curMp = _playerRef->Attrs.MP.Min().Get();
int maxMp = _playerRef->Attrs.MP.Max().Get();
int th = Printer::TerminalHeight;
UpdateBar(1, th - 2, _playerRef->Attrs.HP);
auto str = Util::StringFormat("%i/%i", curHp, maxHp);
Printer::Instance().PrintFB(GlobalConstants::HPMPBarLength / 2,
th - 2,
str,
Printer::kAlignCenter,
Colors::WhiteColor,
"#880000");
UpdateBar(1, th - 1, _playerRef->Attrs.MP);
str = Util::StringFormat("%i/%i", curMp, maxMp);
Printer::Instance().PrintFB(GlobalConstants::HPMPBarLength / 2, th - 1, str, Printer::kAlignCenter, Colors::WhiteColor, "#000088");
}
void MainState::UpdateBar(int x, int y, RangedAttribute& attr)
{
float ratio = ((float)attr.Min().Get() / (float)attr.Max().Get());
int len = ratio * GlobalConstants::HPMPBarLength;
std::string bar = "[";
for (int i = 0; i < GlobalConstants::HPMPBarLength; i++)
{
bar += (i < len) ? "=" : " ";
}
bar += "]";
Printer::Instance().PrintFB(x, y, bar, Printer::kAlignLeft, Colors::WhiteColor);
}
std::pair<GameObject*, bool> MainState::CheckStairs(int stairsSymbol)
{
GameObject* stairsTile = Map::Instance().CurrentLevel->MapArray[_playerRef->PosX][_playerRef->PosY].get();
if (stairsSymbol == '>')
{
if (stairsTile->Image != stairsSymbol)
{
Printer::Instance().AddMessage(Strings::MsgNoStairsDown);
_stairsTileInfo.first = nullptr;
}
else
{
_stairsTileInfo.first = stairsTile;
_stairsTileInfo.second = true;
}
}
else if (stairsSymbol == '<')
{
if (stairsTile->Image != stairsSymbol)
{
Printer::Instance().AddMessage(Strings::MsgNoStairsUp);
_stairsTileInfo.first = nullptr;
}
else
{
_stairsTileInfo.first = stairsTile;
_stairsTileInfo.second = false;
}
}
return _stairsTileInfo;
}
void MainState::ClimbStairs(const std::pair<GameObject*, bool>& stairsTileInfo)
{
bool upOrDown = stairsTileInfo.second;
Component* c = stairsTileInfo.first->GetComponent<StairsComponent>();
StairsComponent* stairs = static_cast<StairsComponent*>(c);
Map::Instance().ChangeLevel(stairs->LeadsTo, upOrDown);
}
void MainState::PrintDebugInfo()
{
_debugInfo = Util::StringFormat("Act: %i Ofst: %i %i: Plr: [%i;%i] Hunger: %i",
_playerRef->Attrs.ActionMeter,
Map::Instance().CurrentLevel->MapOffsetX,
Map::Instance().CurrentLevel->MapOffsetY,
_playerRef->PosX,
_playerRef->PosY,
_playerRef->Attrs.Hunger);
Printer::Instance().PrintFB(1, 1, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor);
_debugInfo = Util::StringFormat("Key: %i Actors: %i Respawn: %i",
_keyPressed,
Map::Instance().CurrentLevel->ActorGameObjects.size(),
Map::Instance().CurrentLevel->RespawnCounter());
Printer::Instance().PrintFB(1, 2, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor);
_debugInfo = Util::StringFormat("Level Start: [%i;%i]", Map::Instance().CurrentLevel->LevelStart.X, Map::Instance().CurrentLevel->LevelStart.Y);
Printer::Instance().PrintFB(1, 3, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor);
_debugInfo = Util::StringFormat("Level Exit: [%i;%i]", Map::Instance().CurrentLevel->LevelExit.X, Map::Instance().CurrentLevel->LevelExit.Y);
Printer::Instance().PrintFB(1, 4, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor);
_debugInfo = Util::StringFormat("Colors Used: %i", Printer::Instance().ColorsUsed());
Printer::Instance().PrintFB(1, 5, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor);
_debugInfo = Util::StringFormat("Turns passed: %i", Application::Instance().TurnsPassed);
Printer::Instance().PrintFB(1, 6, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor);
Printer::Instance().PrintFB(1, 7, "Actors watched:", Printer::kAlignLeft, Colors::WhiteColor);
int yOffset = 0;
bool found = false;
for (auto& id : _actorsForDebugDisplay)
{
for (auto& a : Map::Instance().CurrentLevel->ActorGameObjects)
{
if (a->ObjectId() == id)
{
_debugInfo = Util::StringFormat("%s_%lu (%i)", a->ObjectName.data(), id, a->Attrs.ActionMeter);
Printer::Instance().PrintFB(1, 8 + yOffset, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor);
yOffset++;
found = true;
}
}
}
if (!found)
{
Printer::Instance().PrintFB(1, 8, "<Press 's' to scan 1x1 around player>", Printer::kAlignLeft, Colors::WhiteColor);
}
}
void MainState::ProcessRangedWeapon()
{
if (Map::Instance().CurrentLevel->Peaceful)
{
// NOTE: comment out all lines for debug if needed
PrintNoAttackInTown();
return;
}
if (_playerRef->IsSwimming())
{
Printer::Instance().AddMessage(Strings::MsgNotInWater);
return;
}
// TODO: wands in both hands?
ItemComponent* weapon = _playerRef->EquipmentByCategory[EquipmentCategory::WEAPON][0];
if (weapon != nullptr)
{
if (weapon->Data.ItemType_ == ItemType::WAND)
{
ProcessWand(weapon);
}
else if (weapon->Data.ItemType_ == ItemType::RANGED_WEAPON)
{
ProcessWeapon(weapon);
}
else
{
Printer::Instance().AddMessage(Strings::MsgNotRangedWeapon);
}
}
else
{
Printer::Instance().AddMessage(Strings::MsgEquipWeapon);
}
}
void MainState::ProcessWeapon(ItemComponent* weapon)
{
ItemComponent* arrows = _playerRef->EquipmentByCategory[EquipmentCategory::SHIELD][0];
if (arrows != nullptr)
{
bool isBow = (weapon->Data.RangedWeaponType_ == RangedWeaponType::SHORT_BOW
|| weapon->Data.RangedWeaponType_ == RangedWeaponType::LONGBOW
|| weapon->Data.RangedWeaponType_ == RangedWeaponType::WAR_BOW);
bool isXBow = (weapon->Data.RangedWeaponType_ == RangedWeaponType::LIGHT_XBOW
|| weapon->Data.RangedWeaponType_ == RangedWeaponType::XBOW
|| weapon->Data.RangedWeaponType_ == RangedWeaponType::HEAVY_XBOW);
if (arrows->Data.ItemType_ != ItemType::ARROWS)
{
Printer::Instance().AddMessage(Strings::MsgWhatToShoot);
}
else
{
if ( (isBow && arrows->Data.AmmoType == ArrowType::BOLTS)
|| (isXBow && arrows->Data.AmmoType == ArrowType::ARROWS) )
{
Printer::Instance().AddMessage(Strings::MsgWrongAmmo);
return;
}
if (arrows->Data.Amount == 0)
{
Printer::Instance().AddMessage(Strings::MsgNoAmmo);
}
else
{
auto s = Application::Instance().GetGameStateRefByName(GameStates::TARGET_STATE);
TargetState* ts = static_cast<TargetState*>(s);
ts->Setup(weapon);
Application::Instance().ChangeState(GameStates::TARGET_STATE);
}
}
}
else
{
Printer::Instance().AddMessage(Strings::MsgWhatToShoot);
}
}
void MainState::ProcessWand(ItemComponent* wand)
{
// NOTE: amount of charges should be subtracted
// separately in corresponding methods
// (i.e. EffectsProcessor or inside TargetState),
// because combat wands require targeting,
// which is checked against out of bounds,
// and only after it's OK and player hits "fire",
// the actual firing takes place.
if (wand->Data.Amount == 0)
{
Printer::Instance().AddMessage(Strings::MsgNoCharges);
}
else
{
switch (wand->Data.SpellHeld.SpellType_)
{
// TODO: finish wands effects and attack
// (e.g. wand of heal others etc.)
case SpellType::LIGHT:
SpellsProcessor::Instance().ProcessWand(wand);
break;
case SpellType::STRIKE:
case SpellType::FROST:
case SpellType::TELEPORT:
case SpellType::FIREBALL:
case SpellType::LASER:
case SpellType::LIGHTNING:
case SpellType::MAGIC_MISSILE:
case SpellType::NONE:
{
auto s = Application::Instance().GetGameStateRefByName(GameStates::TARGET_STATE);
TargetState* ts = static_cast<TargetState*>(s);
ts->Setup(wand);
Application::Instance().ChangeState(GameStates::TARGET_STATE);
}
break;
default:
break;
}
}
}
bool MainState::ProcessMoneyPickup(std::pair<int, GameObject*>& pair)
{
ItemComponent* ic = pair.second->GetComponent<ItemComponent>();
if (ic->Data.ItemType_ == ItemType::COINS)
{
auto message = Util::StringFormat(Strings::FmtPickedUpIS, ic->Data.Amount, ic->OwnerGameObject->ObjectName.data());
Printer::Instance().AddMessage(message);
_playerRef->Money += ic->Data.Amount;
auto it = Map::Instance().CurrentLevel->GameObjects.begin();
Map::Instance().CurrentLevel->GameObjects.erase(it + pair.first);
return true;
}
return false;
}
void MainState::ProcessItemPickup(std::pair<int, GameObject*>& pair)
{
ItemComponent* ic = pair.second->GetComponent<ItemComponent>();
auto go = Map::Instance().CurrentLevel->GameObjects[pair.first].release();
_playerRef->Inventory.Add(go);
std::string objName = ic->Data.IsIdentified ? go->ObjectName : ic->Data.UnidentifiedName;
std::string message;
if (ic->Data.IsStackable)
{
message = Util::StringFormat(Strings::FmtPickedUpIS, ic->Data.Amount, objName.data());
}
else
{
message = Util::StringFormat(Strings::FmtPickedUpS, objName.data());
}
Printer::Instance().AddMessage(message);
auto it = Map::Instance().CurrentLevel->GameObjects.begin();
Map::Instance().CurrentLevel->GameObjects.erase(it + pair.first);
}
void MainState::DisplayStartHint()
{
int th = Printer::TerminalHeight;
Printer::Instance().PrintFB(1,
th - 4,
'<',
Colors::WhiteColor,
Colors::DoorHighlightColor);
auto curLvl = Map::Instance().CurrentLevel;
int dx = curLvl->LevelStart.X - _playerRef->PosX;
int dy = curLvl->LevelStart.Y - _playerRef->PosY;
std::string dir;
if (dy > 0)
{
dir += "S";
}
else if (dy < 0)
{
dir += "N";
}
if (dx > 0)
{
dir += "E";
}
else if (dx < 0)
{
dir += "W";
}
Printer::Instance().PrintFB(2,
th - 4,
dir,
Printer::kAlignLeft,
Colors::WhiteColor);
}
void MainState::DisplayExitHint()
{
int th = Printer::TerminalHeight;
Printer::Instance().PrintFB(1,
th - 3,
'>',
Colors::WhiteColor,
Colors::DoorHighlightColor);
std::string dir;
auto curLvl = Map::Instance().CurrentLevel;
if (curLvl->ExitFound)
{
int dx = curLvl->LevelExit.X - _playerRef->PosX;
int dy = curLvl->LevelExit.Y - _playerRef->PosY;
if (dy > 0)
{
dir += "S";
}
else if (dy < 0)
{
dir += "N";
}
if (dx > 0)
{
dir += "E";
}
else if (dx < 0)
{
dir += "W";
}
}
Printer::Instance().PrintFB(2,
th - 3,
curLvl->ExitFound ? dir : "??",
Printer::kAlignLeft,
Colors::WhiteColor);
}
void MainState::DisplayStatusIcons()
{
int startPos = 4;
DisplayHungerStatus(startPos);
DisplayWeaponCondition(startPos);
DisplayArmorCondition(startPos);
DisplayAmmoCondition(startPos);
DisplayActiveEffects(startPos);
}
void MainState::DisplayHungerStatus(const int& startPos)
{
if (_playerRef->IsStarving)
{
Printer::Instance().PrintFB(startPos,
_th - 3,
'%',
Colors::WhiteColor,
Colors::RedColor);
}
else
{
int hungerMax = _playerRef->Attrs.HungerRate.Get();
int part = hungerMax - hungerMax * 0.25;
if (_playerRef->Attrs.Hunger >= part)
{
Printer::Instance().PrintFB(startPos, _th - 3, '%', Colors::WhiteColor, "#999900");
}
}
}
void MainState::DisplayWeaponCondition(const int& startPos)
{
ItemComponent* weapon = _playerRef->EquipmentByCategory[EquipmentCategory::WEAPON][0];
if (weapon != nullptr &&
(weapon->Data.ItemType_ == ItemType::WEAPON
|| weapon->Data.ItemType_ == ItemType::RANGED_WEAPON))
{
int maxDur = weapon->Data.Durability.Max().Get();
int warning = maxDur * 0.3f;
if (weapon->Data.Durability.Min().Get() <= warning)
{
Printer::Instance().PrintFB(startPos + 2, _th - 3, ')', Colors::YellowColor);
}
}
}
void MainState::DisplayArmorCondition(const int& startPos)
{
ItemComponent* armor = _playerRef->EquipmentByCategory[EquipmentCategory::TORSO][0];
if (armor != nullptr && armor->Data.ItemType_ == ItemType::ARMOR)
{
int maxDur = armor->Data.Durability.Max().Get();
int warning = maxDur * 0.3f;
if (armor->Data.Durability.Min().Get() <= warning)
{
Printer::Instance().PrintFB(startPos + 4, _th - 3, '[', Colors::YellowColor);
}
}
}
void MainState::DisplayAmmoCondition(const int& startPos)
{
ItemComponent* arrows = _playerRef->EquipmentByCategory[EquipmentCategory::SHIELD][0];
if (arrows != nullptr && arrows->Data.ItemType_ == ItemType::ARROWS)
{
int amount = arrows->Data.Amount;
if (amount <= 3)
{
Printer::Instance().PrintFB(startPos + 6, _th - 3, '^', Colors::YellowColor);
}
}
}
void MainState::DisplayActiveEffects(const int& startPos)
{
int offsetX = startPos;
std::map<std::string, int> effectDurationByName;
for (auto& kvp : _playerRef->Effects())
{
for (const ItemBonusStruct& item : kvp.second)
{
std::string shortName = GlobalConstants::BonusDisplayNameByType.at(item.Type);
int duration = item.Duration;
if (duration != -1)
{
effectDurationByName[shortName] += duration;
}
else
{
effectDurationByName[shortName] = duration;
}
}
}
for (auto& kvp : effectDurationByName)
{
bool isFading = (kvp.second <= GlobalConstants::TurnReadyValue
&& kvp.second != -1);
std::string color = isFading ?
Colors::ShadesOfGrey::Four :
Colors::WhiteColor;
Printer::Instance().PrintFB(offsetX,
_th - 4,
kvp.first,
Printer::kAlignLeft,
color);
offsetX += 4;
}
}
void MainState::PrintNoAttackInTown()
{
int index = RNG::Instance().RandomRange(0, 2);
Printer::Instance().AddMessage(Strings::MsgNotInTown[index]);
}
void MainState::GetActorsAround()
{
_actorsForDebugDisplay.clear();
int lx = _playerRef->PosX - 1;
int ly = _playerRef->PosY - 1;
int hx = _playerRef->PosX + 1;
int hy = _playerRef->PosY + 1;
if (lx >= 0 && ly >= 0
&& hx < Map::Instance().CurrentLevel->MapSize.X - 1
&& hy < Map::Instance().CurrentLevel->MapSize.Y - 1)
{
for (int x = lx; x <= hx; x++)
{
for (int y = ly; y <= hy; y++)
{
for (auto& a : Map::Instance().CurrentLevel->ActorGameObjects)
{
if (a->PosX == x && a->PosY == y)
{
_actorsForDebugDisplay.push_back(a->ObjectId());
}
}
}
}
}
}
void MainState::DisplayScenarioInformation()
{
std::vector<std::string> messages;
auto seedString = RNG::Instance().GetSeedString();
std::stringstream ss;
ss << "Seed string: \"" << seedString.first << "\"";
messages.push_back(ss.str());
ss.str("");
ss << "Seed value: " << seedString.second;
messages.push_back(ss.str());
Application::Instance().ShowMessageBox(MessageBoxType::ANY_KEY, "Scenario Information", messages);
}
| 26.308031
| 146
| 0.59116
|
xterminal86
|
acc80e24d55eaff214a28394fc1b5439f3009647
| 2,417
|
hpp
|
C++
|
src/game/level/tiled.hpp
|
lowkey42/MagnumOpus
|
87897b16192323b40064119402c74e014a48caf3
|
[
"MIT"
] | 5
|
2020-03-13T23:16:33.000Z
|
2022-03-20T19:16:46.000Z
|
src/game/level/tiled.hpp
|
lowkey42/MagnumOpus
|
87897b16192323b40064119402c74e014a48caf3
|
[
"MIT"
] | 24
|
2015-04-20T20:26:23.000Z
|
2015-11-20T22:39:38.000Z
|
src/game/level/tiled.hpp
|
lowkey42/medienprojekt
|
87897b16192323b40064119402c74e014a48caf3
|
[
"MIT"
] | 1
|
2022-03-08T03:11:21.000Z
|
2022-03-08T03:11:21.000Z
|
/**************************************************************************\
* load & save JSON files from Tiled editor *
* ___ *
* /\/\ __ _ __ _ _ __ _ _ _ __ ___ /___\_ __ _ _ ___ *
* / \ / _` |/ _` | '_ \| | | | '_ ` _ \ // // '_ \| | | / __| *
* / /\/\ \ (_| | (_| | | | | |_| | | | | | | / \_//| |_) | |_| \__ \ *
* \/ \/\__,_|\__, |_| |_|\__,_|_| |_| |_| \___/ | .__/ \__,_|___/ *
* |___/ |_| *
* *
* Copyright (c) 2014 Florian Oetke *
* *
* This file is part of MagnumOpus and distributed under the MIT License *
* See LICENSE file for details. *
\**************************************************************************/
#pragma once
#include <vector>
#include <string>
#include <unordered_map>
#include "../../core/utils/template_utils.hpp"
#include "../../core/utils/string_utils.hpp"
namespace mo {
namespace level {
struct TiledObject {
int height;
int width;
int x;
int y;
int rotation;
std::string name;
std::string type;
bool visible;
std::unordered_map<std::string, std::string> properties;
};
struct TiledLayer {
std::vector<int> data;
int height;
int width;
std::string name;
int opacity;
std::string type;
bool visible;
int x;
int y;
std::string draworder = "topdown";
std::vector<TiledObject> objects;
};
struct TiledLevel {
int height;
int width;
std::vector<TiledLayer> layers;
std::unordered_map<std::string, std::string> properties;
std::string orientation = "orthogonal";
std::string renderorder = "right-down";
int tileheight;
int tilewidth;
int version;
TiledLayer& add_layer(std::string name, std::string type) {
layers.emplace_back();
auto& l = layers.back();
l.height = height;
l.width = width;
l.x = 0;
l.y = 0;
l.visible = true;
l.name = std::move(name);
l.opacity = 1;
l.type = std::move(type);
return l;
}
};
extern TiledLevel parse_level(std::istream& s);
extern void write_level(std::ostream& s, const TiledLevel& level);
}
}
| 26.855556
| 76
| 0.456765
|
lowkey42
|
acc80f97c25dec5002e4fe818cfc940e628f317e
| 10,729
|
cpp
|
C++
|
src/storage-client.cpp
|
corehacker/ch-storage-client
|
d5621b0d5e6f16b9c517d4d048a209dde8169b61
|
[
"MIT"
] | null | null | null |
src/storage-client.cpp
|
corehacker/ch-storage-client
|
d5621b0d5e6f16b9c517d4d048a209dde8169b61
|
[
"MIT"
] | null | null | null |
src/storage-client.cpp
|
corehacker/ch-storage-client
|
d5621b0d5e6f16b9c517d4d048a209dde8169b61
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* BSD 2-Clause License
*
* Copyright (c) 2017, Sandeep Prakash
* 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.
*
* 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.
******************************************************************************/
/*******************************************************************************
* Copyright (c) 2017, Sandeep Prakash <123sandy@gmail.com>
*
* \file storage-client.cpp
*
* \author Sandeep Prakash
*
* \date Nov 02, 2017
*
* \brief
*
******************************************************************************/
#include <fstream>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <chrono>
#include <cstdio>
#include <dirent.h>
#include <ch-cpp-utils/utils.hpp>
#include <ch-cpp-utils/http/client/http.hpp>
#include <glog/logging.h>
#include "storage-client.hpp"
using std::ifstream;
using std::chrono::system_clock;
using ChCppUtils::mkPath;
using ChCppUtils::directoryListing;
using ChCppUtils::fileExpired;
using ChCppUtils::fileExists;
using ChCppUtils::getEpochNano;
using ChCppUtils::getDateTime;
using ChCppUtils::replace;
using ChCppUtils::Http::Client::HttpClientImpl;
namespace SC {
static int get_num_fds(void);
static int get_num_fds()
{
int fd_count;
char buf[64];
struct dirent *dp;
DIR *dir = NULL;
snprintf(buf, 64, "/proc/%i/fd/", getpid());
fd_count = 0;
dir = opendir(buf);
while ((dp = readdir(dir)) != NULL) {
fd_count++;
}
closedir(dir);
return fd_count;
}
UploadContext::UploadContext(StorageClient *client, HttpRequest *request) {
this->client = client;
this->request = request;
}
UploadContext::~UploadContext() {
}
StorageClient *UploadContext::getClient() {
return client;
}
HttpRequest *UploadContext::getRequest() {
return request;
}
StorageClient::StorageClient(Config *config) {
mConfig = config;
procStat = new ProcStat();
purge(true);
for(auto watch : mConfig->getWatchDirs()) {
FtsOptions options = {false};
options.bIgnoreRegularFiles = false;
options.bIgnoreHiddenFiles = true;
options.bIgnoreHiddenDirs = true;
options.bIgnoreRegularDirs = true;
options.filters = mConfig->getFilters();
Fts *fts = new Fts(watch.dir, &options);
mFts.emplace_back(fts);
FsWatch *fsWatch = new FsWatch(watch.dir);
LOG(INFO) << "Adding watch: " << watch.dir << ": " << (watch.upload ? "true" : "false");
mFsWatch.emplace_back(fsWatch);
mWatchDirMap.emplace(make_pair(watch.dir, watch.upload));
}
uploadPrefix = "http://" + mConfig->getHostname() + ":" +
std::to_string(mConfig->getPort()) + mConfig->getPrefix() + "/" +
mConfig->getName();
mTimer = new Timer();
struct timeval tv = {0};
tv.tv_sec = mConfig->getPurgeIntervalSec();
mTimerEvent = mTimer->create(&tv, StorageClient::_onTimerEvent, this);
}
StorageClient::~StorageClient() {
for(auto fts : mFts) {
delete fts;
}
for(auto watch : mFsWatch) {
delete watch;
}
mTimer->destroy(mTimerEvent);
delete mTimer;
}
void StorageClient::_onFile(OnFileData &data, void *this_) {
StorageClient *client = (StorageClient *) this_;
client->onFile(data);
}
bool StorageClient::shouldUpload(OnFileData &data) {
unordered_map<string, bool>::iterator it;
bool upload = false;
for ( it = mWatchDirMap.begin(); it != mWatchDirMap.end(); it++ ) {
string dir = it->first;
upload = it->second;
if(strncmp(data.path.c_str(), dir.c_str(), dir.size()) == 0) {
break;
}
}
return upload;
}
void StorageClient::onFile(OnFileData &data) {
LOG(INFO) << "onFile: " << data.name << ", " << data.path << ", " << data.ext;
if(!shouldUpload(data)) {
LOG(INFO) << "No upload needed based on config";
return;
}
LOG(INFO) << "Needs upload based on config";
if(data.ext == "ts") {
std::ifstream segmentFile(data.path);
if(!segmentFile.is_open()) {
LOG(WARNING) << "Segment file open failed. File may not exist. "
"Might be deleted on startup which got detected by "
"fs watch: " << data.path;
return;
}
LOG(INFO) << "Segment file exists. Will add it to the queue: " <<
data.path;
uploadQueue.emplace_back(data);
} else if(data.ext == "m3u8") {
if(uploadQueue.size() == 0) {
return;
}
std::vector<std::string> playlist;
std::ifstream playlistFile(data.path);
std::string line;
while(std::getline(playlistFile, line)) {
string filename = line.substr(line.find_last_of('/') + 1);
LOG(INFO) << " + " << filename;
playlist.push_back(filename);
}
OnFileData tsData = uploadQueue.at(0);
LOG(INFO) << "Queue head: " << tsData.name;
bool found = false;
string inf;
string targetDuration;
for(uint32_t i = 0; i < playlist.size(); i++) {
string filename = playlist[i];
if(filename.find("#EXT-X-TARGETDURATION") != string::npos) {
targetDuration = filename.substr(filename.find_first_of(":") + 1);
}
if(filename == tsData.name) {
found = true;
inf = playlist[i - 1];
break;
}
}
if(found) {
uploadQueue.erase(uploadQueue.begin());
string infValue = inf.substr(inf.find_last_of(":") + 1);
if(infValue.find_last_of(",") != string::npos) {
infValue.erase(infValue.find_last_of(","), 1);
}
LOG(INFO) << "File found: " << tsData.name << ":" << infValue;
upload(tsData, infValue, targetDuration);
}
} else {
}
}
void StorageClient::_onLoad(HttpRequestLoadEvent *event, void *this_) {
UploadContext *context = (UploadContext *) this_;
StorageClient *client = context->getClient();
client->onLoad(event);
HttpRequest *request = context->getRequest();
delete request;
delete context;
}
void StorageClient::onLoad(HttpRequestLoadEvent *event) {
LOG(INFO) << "Request Complete";
}
void StorageClient::_onFilePurge (OnFileData &data, void *this_) {
StorageClient *client = (StorageClient *) this_;
client->onFilePurge(data);
}
void StorageClient::onFilePurge (OnFileData &data) {
bool markForDelete = fileExpired(data.path, mConfig->getPurgeTtlSec());
if(markForDelete) {
if(0 != std::remove(data.path.data())) {
LOG(ERROR) << "File: " << data.path << ", marked for Delete! failed to delete";
perror("remove");
} else {
LOG(INFO) << "File: " << data.path << ", marked for Delete! Deleted successfully";
}
}
}
void StorageClient::_onFilePurgeForced (OnFileData &data, void *this_) {
StorageClient *client = (StorageClient *) this_;
client->onFilePurgeForced(data);
}
void StorageClient::onFilePurgeForced (OnFileData &data) {
if(0 != std::remove(data.path.data())) {
LOG(ERROR) << "File: " << data.path << ", marked for Delete! failed to delete";
perror("remove");
} else {
LOG(INFO) << "File: " << data.path << ", marked for Delete! Deleted successfully";
}
}
void StorageClient::purge(bool force) {
for(auto watchDir : mConfig->getWatchDirs()) {
FtsOptions options;
// LOG(INFO) << "Purging files in: " << watchDir;
memset(&options, 0x00, sizeof(FtsOptions));
options.bIgnoreRegularFiles = false;
options.bIgnoreHiddenFiles = true;
options.bIgnoreHiddenDirs = true;
options.bIgnoreRegularDirs = true;
Fts fts(watchDir.dir, &options);
if(!force) {
fts.walk(StorageClient::_onFilePurge, this);
} else {
fts.walk(StorageClient::_onFilePurgeForced, this);
}
}
}
void StorageClient::_onTimerEvent(TimerEvent *event, void *this_) {
StorageClient *server = (StorageClient *) this_;
server->onTimerEvent(event);
}
void StorageClient::onTimerEvent(TimerEvent *event) {
uint32_t rss = procStat->getRSS();
LOG(INFO) << "Number of open fd(s): " << get_num_fds();
LOG(INFO) << "RSS: " << rss / 1024 << " KB, Max RSS Configured: " <<
(mConfig->getMaxRss() / 1024) << " KB";
if(rss > mConfig->getMaxRss()) {
LOG(ERROR) << "*********FATAL**********";
LOG(ERROR) << "Too much memory in use. Exiting process.";
LOG(FATAL) << "*********FATAL**********";
exit(1);
}
purge(false);
mTimer->restart(event);
}
void StorageClient::upload(OnFileData &data, string &infValue, string &targetDuration) {
LOG(INFO) << "File to be uploaded: name: " << data.name << ", path: " << data.path;
string targetName = getDateTime() + "-" + std::to_string(getEpochNano()) +
"." + data.ext;
std::replace(targetName.begin(), targetName.end(), ' ', '-');
std::replace(targetName.begin(), targetName.end(), ':', '-');
LOG(INFO) << "Will rename to: " << targetName;
std::ifstream file(data.path, std::ios::binary | std::ios::ate);
if(!file.is_open()) {
LOG(WARNING) << "File open failed: " << data.path;
return;
}
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
LOG(INFO) << "File content read " << size << " bytes";
string url = uploadPrefix + "/" + targetName +
"?extinf=" + infValue +
"&targetduration=" + targetDuration;
LOG(INFO) << "Target URL: " << url;
HttpRequest *request = new HttpRequest();
UploadContext *context = new UploadContext(this, request);
request->onLoad(StorageClient::_onLoad).bind(context);
request->open(EVHTTP_REQ_POST, url).send(buffer.data(), buffer.size());
}
}
void StorageClient::start() {
for(auto watch : mFsWatch) {
watch->init();
watch->OnNewFileCbk(StorageClient::_onFile, this);
watch->start(mConfig->getFilters());
}
for(auto fts : mFts) {
fts->walk(StorageClient::_onFile, this);
}
}
} // End namespace SS.
| 28.919137
| 90
| 0.651412
|
corehacker
|
acc8a54f4767d35c69483b333b5d6c042883d19e
| 5,003
|
cpp
|
C++
|
test/CompilationTests/LambdaTests/MakePromise/RValue.cpp
|
rocky01/promise
|
638415a117207a4cae9181e04114e1d7575a9689
|
[
"MIT"
] | 2
|
2018-10-15T18:27:50.000Z
|
2019-04-16T18:34:59.000Z
|
test/CompilationTests/LambdaTests/MakePromise/RValue.cpp
|
rocky01/promise
|
638415a117207a4cae9181e04114e1d7575a9689
|
[
"MIT"
] | null | null | null |
test/CompilationTests/LambdaTests/MakePromise/RValue.cpp
|
rocky01/promise
|
638415a117207a4cae9181e04114e1d7575a9689
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "Promise.hpp"
using namespace prm;
/***
*
* 1. make_promise function.
*
* We have types:
* ExeT
* ExeVoid
*
* ResolveT
* ResolveVoid
* ResolveUndefined
*
* RejectT
* RejectVoid
* RejectUndefined
*
* There are the following combinations availiable:
* ExeT, ResolveT, RejectT
* ExeT, ResolveT, RejectVoid
* ExeT, ResolveT, RejectUndefined
*
* ExeT, ResolveVoid, RejectT
* ExeT, ResolveVoid, RejectVoid
* ExeT, ResolveVoid, RejectUndefined
*
* ExeT, ResolveUndefined, RejectT
* ExeT, ResolveUndefined, RejectVoid
* ExeT, ResolveUndefined, RejectUndefined <- Not supported
*
* ExeVoid, ResolveT, RejectT
* ExeVoid, ResolveT, RejectVoid
* ExeVoid, ResolveT, RejectUndefined
*
* ExeVoid, ResolveVoid, RejectT
* ExeVoid, ResolveVoid, RejectVoid
* ExeVoid, ResolveVoid, RejectUndefined
*
* ExeVoid, ResolveUndefined, RejectT
* ExeVoid, ResolveUndefined, RejectVoid
* ExeVoid, ResolveUndefined, RejectUndefined <- Not supported
*
***/
class MakePromiseLambdaRValue: public ::testing::TestWithParam<bool>
{ };
INSTANTIATE_TEST_CASE_P(
TestWithParameters, MakePromiseLambdaRValue, testing::Values(
false,
true
));
// ExeT, ResolveT, RejectT
TEST_P(MakePromiseLambdaRValue, ExeResolveReject)
{
make_promise([this](int e, Resolver<char> resolve, Rejector<double> reject) {
ASSERT_TRUE(10 == e);
return GetParam() ? resolve('w') : reject(5.3);
})
.startExecution(10);
}
// ExeT, ResolveT, RejectVoid
TEST_P(MakePromiseLambdaRValue, ExeResolveRejectVoid)
{
make_promise([this](int e, Resolver<char> resolve, Rejector<void> reject) {
ASSERT_TRUE(10 == e);
return GetParam() ? resolve('w') : reject();
})
.startExecution(10);
}
// ExeT, ResolveT, RejectUndefined
TEST(MakePromiseLambdaRValue, ExeResolve)
{
make_promise([](int e, Resolver<char> resolve) {
ASSERT_TRUE(10 == e);
return resolve('w');
})
.startExecution(10);
}
// ExeT, ResolveVoid, RejectT
TEST_P(MakePromiseLambdaRValue, ExeResolveVoidReject)
{
make_promise([this](int e, Resolver<void> resolve, Rejector<double> reject) {
ASSERT_TRUE(10 == e);
return GetParam() ? resolve() : reject(5.3);
})
.startExecution(10);
}
// ExeT, ResolveVoid, RejectVoid
TEST_P(MakePromiseLambdaRValue, ExeResolveVoidRejectVoid)
{
make_promise([this](int e, Resolver<void> resolve, Rejector<void> reject) {
ASSERT_TRUE(10 == e);
return GetParam() ? resolve() : reject();
})
.startExecution(10);
}
// ExeT, ResolveVoid, RejectUndefined
TEST(MakePromiseLambdaRValue, ExeResolveVoid)
{
make_promise([](int e, Resolver<void> resolve) {
ASSERT_TRUE(10 == e);
return resolve();
})
.startExecution(10);
}
// ExeT, ResolveUndefined, RejectT
TEST(MakePromiseLambdaRValue, ExeReject)
{
make_promise([](int e, Rejector<double> reject) {
ASSERT_TRUE(10 == e);
return reject(5.3);
})
.startExecution(10);
}
// ExeT, ResolveUndefined, RejectVoid
TEST(MakePromiseLambdaRValue, ExeRejectVoid)
{
make_promise([](int e, Rejector<void> reject) {
ASSERT_TRUE(10 == e);
return reject();
})
.startExecution(10);
}
// ExeVoid, ResolveT, RejectT
TEST_P(MakePromiseLambdaRValue, ResolveReject)
{
make_promise([this](Resolver<char> resolve, Rejector<double> reject) {
return GetParam() ? resolve('w') : reject(5.3);
})
.startExecution();
}
// ExeVoid, ResolveT, RejectVoid
TEST_P(MakePromiseLambdaRValue, ResolveRejectVoid)
{
make_promise([this](Resolver<char> resolve, Rejector<void> reject) {
return GetParam() ? resolve('w') : reject();
})
.startExecution();
}
// ExeVoid, ResolveT, RejectUndefined
TEST(MakePromiseLambdaRValue, Resolve)
{
make_promise([](Resolver<char> resolve) {
return resolve('w');
})
.startExecution();
}
// ExeVoid, ResolveVoid, RejectT
TEST_P(MakePromiseLambdaRValue, ResolvVoideReject)
{
make_promise([this](Resolver<void> resolve, Rejector<double> reject) {
return GetParam() ? resolve() : reject(5.3);
})
.startExecution();
}
// ExeVoid, ResolveVoid, RejectVoid
TEST_P(MakePromiseLambdaRValue, ResolvVoideRejectVoid)
{
make_promise([this](Resolver<void> resolve, Rejector<void> reject) {
return GetParam() ? resolve() : reject();
})
.startExecution();
}
// ExeVoid, ResolveVoid, RejectUndefined
TEST(MakePromiseLambdaRValue, ResolvVoide)
{
make_promise([](Resolver<void> resolve) {
return resolve();
})
.startExecution();
}
// ExeVoid, ResolveUndefined, RejectT
TEST(MakePromiseLambdaRValue, Reject)
{
make_promise([](Rejector<double> reject) {
return reject(5.3);
})
.startExecution();
}
// ExeVoid, ResolveUndefined, RejectVoid
TEST(MakePromiseLambdaRValue, RejectVoid)
{
make_promise([](Rejector<void> reject) {
return reject();
})
.startExecution();
}
| 23.82381
| 81
| 0.678193
|
rocky01
|
accadd5dba17414263f9529f7f8f55df3cdbe57a
| 1,445
|
cc
|
C++
|
src/envoy/http/grpc_metadata_scrubber/filter.cc
|
CorrelatedLabs/esp-v2
|
9fa93040d70f98087b3586a88a0764b9f5ec544c
|
[
"Apache-2.0"
] | 163
|
2019-12-18T18:40:50.000Z
|
2022-03-17T03:34:22.000Z
|
src/envoy/http/grpc_metadata_scrubber/filter.cc
|
CorrelatedLabs/esp-v2
|
9fa93040d70f98087b3586a88a0764b9f5ec544c
|
[
"Apache-2.0"
] | 669
|
2019-12-19T00:36:12.000Z
|
2022-03-30T20:27:52.000Z
|
src/envoy/http/grpc_metadata_scrubber/filter.cc
|
CorrelatedLabs/esp-v2
|
9fa93040d70f98087b3586a88a0764b9f5ec544c
|
[
"Apache-2.0"
] | 177
|
2019-12-19T00:35:51.000Z
|
2022-03-24T10:22:23.000Z
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/envoy/http/grpc_metadata_scrubber/filter.h"
#include <string>
#include "source/common/grpc/common.h"
#include "source/common/http/headers.h"
namespace espv2 {
namespace envoy {
namespace http_filters {
namespace grpc_metadata_scrubber {
Envoy::Http::FilterHeadersStatus Filter::encodeHeaders(
Envoy::Http::ResponseHeaderMap& headers, bool) {
ENVOY_LOG(debug, "Filter::encodeHeaders is called.");
config_->stats().all_.inc();
if (Envoy::Grpc::Common::hasGrpcContentType(headers) &&
headers.ContentLength() != nullptr) {
ENVOY_LOG(debug, "Content-length header is removed");
headers.removeContentLength();
config_->stats().removed_.inc();
}
return Envoy::Http::FilterHeadersStatus::Continue;
}
} // namespace grpc_metadata_scrubber
} // namespace http_filters
} // namespace envoy
} // namespace espv2
| 31.413043
| 75
| 0.737716
|
CorrelatedLabs
|
acd61f4db9e2ad2931692a24e7686ac496b734a9
| 969
|
hpp
|
C++
|
include/mcnla/isvd/integrator.hpp
|
emfomy/mcnla
|
9f9717f4d6449bbd467c186651856d6212035667
|
[
"MIT"
] | null | null | null |
include/mcnla/isvd/integrator.hpp
|
emfomy/mcnla
|
9f9717f4d6449bbd467c186651856d6212035667
|
[
"MIT"
] | null | null | null |
include/mcnla/isvd/integrator.hpp
|
emfomy/mcnla
|
9f9717f4d6449bbd467c186651856d6212035667
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file include/mcnla/isvd/integrator.hpp
/// @brief The iSVD integrator header.
///
/// @author Mu Yang <<emfomy@gmail.com>>
///
#ifndef MCNLA_ISVD_INTEGRATOR_HPP_
#define MCNLA_ISVD_INTEGRATOR_HPP_
// Kolmogorov-Nagumo-type
#include <mcnla/isvd/integrator/kolmogorov_nagumo_integrator.hpp>
#include <mcnla/isvd/integrator/row_block_kolmogorov_nagumo_integrator.hpp>
#include <mcnla/isvd/integrator/row_block_gramian_kolmogorov_nagumo_integrator.hpp>
// Wen-Yin line search
#include <mcnla/isvd/integrator/row_block_wen_yin_integrator.hpp>
#include <mcnla/isvd/integrator/row_block_gramian_wen_yin_integrator.hpp>
// Reduce-sum
#include <mcnla/isvd/integrator/row_block_reduction_integrator.hpp>
// Extrinsic mean
#include <mcnla/isvd/integrator/row_block_extrinsic_mean_integrator.hpp>
#endif // MCNLA_ISVD_INTEGRATOR_HPP_
| 35.888889
| 128
| 0.705882
|
emfomy
|
acdb388131cb6a63f8247b8982f33554a75e71df
| 449
|
hpp
|
C++
|
library/ATF/CCheckSumGuildConverter.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/CCheckSumGuildConverter.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/CCheckSumGuildConverter.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CCheckSumBaseConverter.hpp>
#include <CCheckSumGuildData.hpp>
START_ATF_NAMESPACE
struct CCheckSumGuildConverter : CCheckSumBaseConverter
{
public:
void Convert(long double dDalant, long double dGold, struct CCheckSumGuildData* pkCheckSum);
};
END_ATF_NAMESPACE
| 28.0625
| 108
| 0.768374
|
lemkova
|
acdf191c7bcfb35a6ab7f1fd2e1f2abea29d6b4d
| 2,147
|
cpp
|
C++
|
src/operators/opLess.cpp
|
athanor/athanor
|
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
|
[
"BSD-3-Clause"
] | 4
|
2018-08-31T09:44:52.000Z
|
2021-03-01T19:10:00.000Z
|
src/operators/opLess.cpp
|
athanor/athanor
|
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
|
[
"BSD-3-Clause"
] | 21
|
2019-12-29T08:33:34.000Z
|
2020-11-22T16:38:37.000Z
|
src/operators/opLess.cpp
|
athanor/athanor
|
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
|
[
"BSD-3-Clause"
] | null | null | null |
#include "operators/opLess.h"
#include "operators/simpleOperator.hpp"
using namespace std;
void OpLess::reevaluateImpl(IntView& leftView, IntView& rightView, bool, bool) {
Int diff = (rightView.value - 1) - leftView.value;
violation = abs(min<Int>(diff, 0));
}
void OpLess::updateVarViolationsImpl(const ViolationContext&,
ViolationContainer& vioContainer) {
if (violation == 0) {
return;
} else if (allOperandsAreDefined()) {
left->updateVarViolations(
IntViolationContext(violation,
IntViolationContext::Reason::TOO_LARGE),
vioContainer);
right->updateVarViolations(
IntViolationContext(violation,
IntViolationContext::Reason::TOO_SMALL),
vioContainer);
} else {
left->updateVarViolations(violation, vioContainer);
right->updateVarViolations(violation, vioContainer);
}
}
void OpLess::copy(OpLess&) const {}
ostream& OpLess::dumpState(ostream& os) const {
os << "OpLess: violation=" << violation << "\nleft: ";
left->dumpState(os);
os << "\nright: ";
right->dumpState(os);
return os;
}
string OpLess::getOpName() const { return "OpLess"; }
void OpLess::debugSanityCheckImpl() const {
left->debugSanityCheck();
right->debugSanityCheck();
auto leftOption = left->getViewIfDefined();
auto rightOption = right->getViewIfDefined();
if (!leftOption || !rightOption) {
sanityLargeViolationCheck(violation);
return;
}
auto& leftView = *leftOption;
auto& rightView = *rightOption;
Int diff = (rightView.value - 1) - leftView.value;
UInt checkViolation = abs(min<Int>(diff, 0));
sanityEqualsCheck(checkViolation, violation);
}
template <typename Op>
struct OpMaker;
template <>
struct OpMaker<OpLess> {
static ExprRef<BoolView> make(ExprRef<IntView> l, ExprRef<IntView> r);
};
ExprRef<BoolView> OpMaker<OpLess>::make(ExprRef<IntView> l,
ExprRef<IntView> r) {
return make_shared<OpLess>(move(l), move(r));
}
| 32.044776
| 80
| 0.63251
|
athanor
|
ace3f5b4bcba607dd8c0c08bbfa5d5dbc03dd891
| 2,711
|
hpp
|
C++
|
filelib/include/ini/INI_Tokenizer.hpp
|
radj307/307lib
|
16c5052481b2414ee68beeb7746c006461e8160f
|
[
"MIT"
] | 1
|
2021-12-09T20:01:21.000Z
|
2021-12-09T20:01:21.000Z
|
filelib/include/ini/INI_Tokenizer.hpp
|
radj307/307lib
|
16c5052481b2414ee68beeb7746c006461e8160f
|
[
"MIT"
] | null | null | null |
filelib/include/ini/INI_Tokenizer.hpp
|
radj307/307lib
|
16c5052481b2414ee68beeb7746c006461e8160f
|
[
"MIT"
] | null | null | null |
#pragma once
#include <TokenReduxDefaultDefs.hpp>
namespace file::ini::tokenizer {
using namespace token::DefaultDefs;
/**
* @struct INITokenizer
* @brief Tokenizes the contents of an INI config file.
*/
struct INITokenizer : token::base::TokenizerBase<LEXEME, LexemeDict, ::token::DefaultDefs::TokenType, Token> {
INITokenizer(std::stringstream&& buffer) : TokenizerBase(std::move(buffer), LEXEME::WHITESPACE, LEXEME::_EOF) {}
protected:
TokenT getNext() override
{
const auto ch{ getch() };
switch (get_lexeme(ch)) {
case LEXEME::POUND: [[fallthrough]];
case LEXEME::SEMICOLON:// Comment
return Token{ std::string(1ull, ch) += getline('\n', false), TokenType::COMMENT };
case LEXEME::EQUALS: // Setter Start
return Token{ ch, TokenType::SETTER };
case LEXEME::QUOTE_SINGLE: // String (single) start
return Token{ getline('\''), TokenType::STRING };
case LEXEME::QUOTE_DOUBLE: // String (double) start
return Token{ getline('\"'), TokenType::STRING };
case LEXEME::SQUAREBRACKET_OPEN:
return Token{ getline(']'), TokenType::HEADER };
case LEXEME::LETTER_LOWERCASE: [[fallthrough]]; // if text appears without an enclosing quote, parse it as a key
case LEXEME::LETTER_UPPERCASE:
{ // the case of unenclosed string variables is handled by the parser, not the tokenizer
const auto pos{ rollback() };
std::string str;
if (const auto lc{ str::tolower(ch) }; lc == 't' && getline_and_match(4u, "true", str))
return{ str, TokenType::BOOLEAN };
else if (lc == 'f' && getline_and_match(5u, "false", str))
return{ str, TokenType::BOOLEAN };
else
ss.seekg(pos - 1ll);
// getnotsimilar to newlines, equals, pound/semicolon '#'/';' (comments), and EOF
return Token{ str::strip_line(getnotsimilar(LEXEME::NEWLINE, LEXEME::EQUALS, LEXEME::POUND, LEXEME::SEMICOLON, LEXEME::_EOF), "#;"), TokenType::KEY };
}
case LEXEME::SUBTRACT: [[fallthrough]]; // number start
case LEXEME::DIGIT:
{
rollback();
const auto str{ getsimilar(LEXEME::SUBTRACT, LEXEME::DIGIT, LEXEME::PERIOD) };
return (str::pos_valid(str.find('.') || !str.empty() && (str.back() == 'f' || str.back() == 'F')) ? Token{ str, TokenType::NUMBER } : Token{ str, TokenType::NUMBER_INT });
}
case LEXEME::NEWLINE:
return Token{ ch, TokenType::NEWLINE };
case LEXEME::WHITESPACE:
throw make_exception("TokenizerINI::getNext()\tReceived unexpected whitespace character as input!");
case LEXEME::ESCAPE:
return Token{ std::string(1u, ch) += getch(true), TokenType::ESCAPED };
case LEXEME::_EOF:
return Token{ TokenType::END };
default:
return Token{ ch, TokenType::NULL_TYPE };
}
}
};
}
| 41.707692
| 175
| 0.665806
|
radj307
|
ace4859641d2c085e8fd73a2fa2df95442aa6b3c
| 1,496
|
cpp
|
C++
|
asps/modbus/pdu/message/message_service.cpp
|
activesys/asps
|
36cc90a192d13df8669f9743f80a0662fe888d16
|
[
"MIT"
] | null | null | null |
asps/modbus/pdu/message/message_service.cpp
|
activesys/asps
|
36cc90a192d13df8669f9743f80a0662fe888d16
|
[
"MIT"
] | null | null | null |
asps/modbus/pdu/message/message_service.cpp
|
activesys/asps
|
36cc90a192d13df8669f9743f80a0662fe888d16
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 The asps Authors. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// Modbus PDU Message Service.
#include <asps/modbus/pdu/message/message_service.hpp>
#include <asps/modbus/pdu/message/client_message.hpp>
namespace asps {
namespace modbus {
namespace pdu {
message_serialization_service::pointer_type
make_client_read_coils_request(uint16_t starting_address,
uint16_t quantity_of_coils)
{
return std::make_shared<client_read_coils_request>(starting_address,
quantity_of_coils);
}
message_unserialization_service::pointer_type
make_client_read_coils_response()
{
return std::make_shared<client_exception>(
std::make_shared<client_read_coils_response>());
}
message_serialization_service::pointer_type
make_client_read_discrete_inputs_request(uint16_t starting_address,
uint16_t quantity_of_inputs)
{
return std::make_shared<client_read_discrete_inputs_request>(starting_address,
quantity_of_inputs);
}
message_unserialization_service::pointer_type
make_client_read_discrete_inputs_response()
{
return std::make_shared<client_exception>(
std::make_shared<client_read_discrete_inputs_response>());
}
} // pdu
} // modbus
} // asps
| 31.829787
| 83
| 0.707888
|
activesys
|
ace55a95143f50865e1aed308f8888bebc014257
| 1,577
|
hpp
|
C++
|
include/helpFunctions.hpp
|
ekildishev/lab-01-parser
|
03b9bf4480ceb2285f2650249f4edeb30ae469ef
|
[
"MIT"
] | 2
|
2019-12-07T11:53:40.000Z
|
2020-09-28T17:47:20.000Z
|
include/helpFunctions.hpp
|
ekildishev/lab-01-parser
|
03b9bf4480ceb2285f2650249f4edeb30ae469ef
|
[
"MIT"
] | null | null | null |
include/helpFunctions.hpp
|
ekildishev/lab-01-parser
|
03b9bf4480ceb2285f2650249f4edeb30ae469ef
|
[
"MIT"
] | null | null | null |
// Copyright 2018 Your Name <your_email>
#pragma once
#include <iostream>
#include <sstream>
bool isSpace(char ch) {
return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}
int findEnd(const std::string &s, int start, char openSym, char closeSym) {
unsigned int i = 0;
unsigned int openC = 1;
unsigned int closeC = 0;
for (unsigned int j = start + 1; j < s.length(); ++j) {
char symbol = s[j];
if (symbol == openSym) {
openC++;
} else if (symbol == closeSym) {
closeC++;
}
if (openC == closeC) {
i = j;
break;
}
}
return i + 1;
}
unsigned int missSpaces(const std::string &s, unsigned int current) {
while (current < s.length() && isSpace(s[current])) {
++current;
}
return current;
}
std::string getString(const std::string &s, unsigned int start) {
unsigned int end = start + 1;
while (end < s.length() && s[end] != '\"') {
++end;
}
if (end >= s.length()) {
throw std::exception();
}
return s.substr(start + 1, end - start - 1);
}
bool isNum(char c) { return ((c > '0') && (c < '9')) || (c == '.'); }
std::pair<double, unsigned int> getNumAndLen(const std::string &s,
unsigned int start) {
double result;
unsigned int cur = start;
while (cur < s.length() && isNum(s[cur])) {
++cur;
}
if (cur == s.length()) {
throw std::exception();
}
std::stringstream ss;
std::string str = s.substr(start, cur - start);
ss << str;
ss >> result;
return std::pair<double, unsigned int>(result, cur - start);
}
| 23.191176
| 75
| 0.54851
|
ekildishev
|
ace7200352adb1e3e4c032c952d31007c6ad6491
| 4,610
|
hpp
|
C++
|
tests/widgets/ExampleColorWidget.hpp
|
noisecode3/DPF
|
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
|
[
"0BSD"
] | 372
|
2015-02-09T15:05:16.000Z
|
2022-03-30T15:35:17.000Z
|
tests/widgets/ExampleColorWidget.hpp
|
noisecode3/DPF
|
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
|
[
"0BSD"
] | 324
|
2015-10-05T14:30:41.000Z
|
2022-03-30T07:06:04.000Z
|
tests/widgets/ExampleColorWidget.hpp
|
noisecode3/DPF
|
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
|
[
"0BSD"
] | 89
|
2015-02-20T11:26:50.000Z
|
2022-02-11T00:07:27.000Z
|
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef EXAMPLE_COLOR_WIDGET_HPP_INCLUDED
#define EXAMPLE_COLOR_WIDGET_HPP_INCLUDED
// ------------------------------------------------------
// DGL Stuff
#include "../../dgl/Color.hpp"
#include "../../dgl/StandaloneWindow.hpp"
#include "../../dgl/SubWidget.hpp"
START_NAMESPACE_DGL
// ------------------------------------------------------
// our widget
template <class BaseWidget>
class ExampleColorWidget : public BaseWidget,
public IdleCallback
{
char cur;
bool reverse;
int r, g, b;
Rectangle<uint> bgFull, bgSmall;
public:
static constexpr const char* kExampleWidgetName = "Color";
// SubWidget
explicit ExampleColorWidget(Widget* const parent);
// TopLevelWidget
explicit ExampleColorWidget(Window& windowToMapTo);
// StandaloneWindow
explicit ExampleColorWidget(Application& app);
protected:
void idleCallback() noexcept override
{
switch (cur)
{
case 'r':
if (reverse)
{
if (--r == 0)
cur = 'g';
}
else
{
if (++r == 100)
cur = 'g';
}
break;
case 'g':
if (reverse)
{
if (--g == 0)
cur = 'b';
}
else
{
if (++g == 100)
cur = 'b';
}
break;
case 'b':
if (reverse)
{
if (--b == 0)
{
cur = 'r';
reverse = false;
}
}
else
{
if (++b == 100)
{
cur = 'r';
reverse = true;
}
}
break;
}
BaseWidget::repaint();
}
void onDisplay() override
{
const GraphicsContext& context(BaseWidget::getGraphicsContext());
// paint bg color (in full size)
Color(r, g, b).setFor(context);
bgFull.draw(context);
// paint inverted color (in 2/3 size)
Color(100-r, 100-g, 100-b).setFor(context);
bgSmall.draw(context);
}
void onResize(const Widget::ResizeEvent& ev) override
{
const uint width = ev.size.getWidth();
const uint height = ev.size.getHeight();
// full bg
bgFull = Rectangle<uint>(0, 0, width, height);
// small bg, centered 2/3 size
bgSmall = Rectangle<uint>(width/6, height/6, width*2/3, height*2/3);
}
};
// SubWidget
template<> inline
ExampleColorWidget<SubWidget>::ExampleColorWidget(Widget* const parent)
: SubWidget(parent),
cur('r'),
reverse(false),
r(0), g(0), b(0)
{
setSize(300, 300);
parent->getApp().addIdleCallback(this);
}
// TopLevelWidget
template<> inline
ExampleColorWidget<TopLevelWidget>::ExampleColorWidget(Window& windowToMapTo)
: TopLevelWidget(windowToMapTo),
cur('r'),
reverse(false),
r(0), g(0), b(0)
{
setSize(300, 300);
addIdleCallback(this);
}
// StandaloneWindow
template<> inline
ExampleColorWidget<StandaloneWindow>::ExampleColorWidget(Application& app)
: StandaloneWindow(app),
cur('r'),
reverse(false),
r(0), g(0), b(0)
{
setSize(300, 300);
addIdleCallback(this);
done();
}
typedef ExampleColorWidget<SubWidget> ExampleColorSubWidget;
typedef ExampleColorWidget<TopLevelWidget> ExampleColorTopLevelWidget;
typedef ExampleColorWidget<StandaloneWindow> ExampleColorStandaloneWindow;
// ------------------------------------------------------
END_NAMESPACE_DGL
#endif // EXAMPLE_COLOR_WIDGET_HPP_INCLUDED
| 25.611111
| 90
| 0.556182
|
noisecode3
|
acef454a33829800d8af20ea3d9e6a04a72644ae
| 94
|
cc
|
C++
|
cc/Neat/Bit/Sequence.cc
|
ma16/rpio
|
2e9e5f6794ebe8d60d62e0c65a14edd80f0194ec
|
[
"BSD-2-Clause"
] | 1
|
2020-06-07T14:50:44.000Z
|
2020-06-07T14:50:44.000Z
|
cc/Neat/Bit/Sequence.cc
|
ma16/rpio
|
2e9e5f6794ebe8d60d62e0c65a14edd80f0194ec
|
[
"BSD-2-Clause"
] | null | null | null |
cc/Neat/Bit/Sequence.cc
|
ma16/rpio
|
2e9e5f6794ebe8d60d62e0c65a14edd80f0194ec
|
[
"BSD-2-Clause"
] | null | null | null |
// BSD 2-Clause License, see github.com/ma16/rpio
#include "Sequence.h"
// empty on purpose
| 15.666667
| 49
| 0.712766
|
ma16
|
acf2ccbda43fc2317dd3b4cb2642161227aafc8f
| 1,955
|
hpp
|
C++
|
src/lib/lossy_cast.hpp
|
dey4ss/hyrise
|
c304b9ced36044e303eb8a4d68a05fc7edc04819
|
[
"MIT"
] | 1
|
2019-12-30T13:23:30.000Z
|
2019-12-30T13:23:30.000Z
|
src/lib/lossy_cast.hpp
|
dey4ss/hyrise
|
c304b9ced36044e303eb8a4d68a05fc7edc04819
|
[
"MIT"
] | 11
|
2019-12-02T20:47:52.000Z
|
2020-02-04T23:19:31.000Z
|
src/lib/lossy_cast.hpp
|
dey4ss/hyrise
|
c304b9ced36044e303eb8a4d68a05fc7edc04819
|
[
"MIT"
] | 1
|
2020-11-17T19:18:58.000Z
|
2020-11-17T19:18:58.000Z
|
#pragma once
#include <optional>
#include <string>
#include <type_traits>
#include <boost/lexical_cast.hpp>
#include <boost/variant.hpp>
#include "resolve_type.hpp"
namespace opossum {
/**
* Contrary to the functions in lossless_cast.hpp, converts from an AllTypeVariant to any target, even if accuracy/data
* is lost by the conversion.
*
* Use this function only in contexts where (query-)result accuracy is not affected (e.g., statistics/estimations)
*
* If @param source is NULL, return std::nullopt
* If @param source is a string, perform a boost::lexical_cast<>
* If @param source is arithmetic, perform a static_cast<>, clamping the returned value at
* `std::numeric_limits<Target>::min()/max()` to avoid undefined behaviour.
*/
template <typename Target>
std::optional<Target> lossy_variant_cast(const AllTypeVariant& source) {
if (variant_is_null(source)) return std::nullopt;
std::optional<Target> result;
resolve_data_type(data_type_from_all_type_variant(source), [&](const auto source_data_type_t) {
using SourceDataType = typename decltype(source_data_type_t)::type;
if constexpr (std::is_same_v<Target, SourceDataType>) {
result = boost::get<SourceDataType>(source);
} else {
if constexpr (std::is_same_v<pmr_string, SourceDataType> == std::is_same_v<pmr_string, Target>) {
const auto source_value = boost::get<SourceDataType>(source);
if (source_value > std::numeric_limits<Target>::max()) {
result = std::numeric_limits<Target>::max();
} else if (source_value < std::numeric_limits<Target>::lowest()) {
result = std::numeric_limits<Target>::lowest();
} else {
result = static_cast<Target>(boost::get<SourceDataType>(source));
}
} else {
result = boost::lexical_cast<Target>(boost::get<SourceDataType>(source));
}
}
});
return result;
}
} // namespace opossum
| 34.910714
| 119
| 0.685934
|
dey4ss
|
acf5d0d8f5329aaae342414fd903983e792ee2c4
| 254
|
cpp
|
C++
|
LeetCode/Problems/Algorithms/#476_NumberComplement_sol5_bit_manipulation_O(1)_time_O(1)_extra_space.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | 1
|
2022-01-26T14:50:07.000Z
|
2022-01-26T14:50:07.000Z
|
LeetCode/Problems/Algorithms/#476_NumberComplement_sol5_bit_manipulation_O(1)_time_O(1)_extra_space.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | null | null | null |
LeetCode/Problems/Algorithms/#476_NumberComplement_sol5_bit_manipulation_O(1)_time_O(1)_extra_space.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int findComplement(int num) {
int msb = 31 - __builtin_clz((unsigned int)num);
int fullMask = ((1U << (msb + 1)) - 1);
int numComplement = fullMask ^ num;
return numComplement;
}
};
| 28.222222
| 57
| 0.555118
|
Tudor67
|
acf81a09adee92346a866c739f451b3cc7006bf2
| 5,884
|
cc
|
C++
|
tree/TrieTree.cc
|
raining888/leetcode
|
e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b
|
[
"MIT"
] | null | null | null |
tree/TrieTree.cc
|
raining888/leetcode
|
e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b
|
[
"MIT"
] | null | null | null |
tree/TrieTree.cc
|
raining888/leetcode
|
e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <random>
#include <string>
#include <unordered_map>
#include <string.h>
using namespace std;
class TrieTree
{
public:
class Node
{
public:
int pass; // 标记该节点有多少个相同前缀的节点
int end; //标记该节点加入过多少次,或者说有多少个以该节点结尾的单词
unordered_map<int, Node*> nexts;
Node()
{
pass = 0;
end = 0;
}
};
class Trie
{
public:
Node* root;
Trie()
{
root = new Node();
}
void insert(string word)
{
if (word == "")
{
return;
}
const char* chs = word.c_str();
Node* node = root;
node->pass++;
int index = 0;
int len = strlen(chs);
for (int i = 0; i < len; i++)
{
// 从左往右遍历字符
index = (int)chs[i]; // 由字符,对应成走向哪条路
if (node->nexts.find(index) == node->nexts.end())
{
node->nexts.emplace(index, new Node());
}
node = node->nexts.at(index);
node->pass++;
}
node->end++;
}
void del(string word)
{
if (search(word) != 0)
{
const char* chs = word.c_str();
Node* node = root;
node->pass--;
int index = 0;
int len = strlen(chs);
for (int i = 0; i < len; i++)
{
index = (int) chs[i];
if (--node->nexts.at(index)->pass == 0)
{
node->nexts.erase(index);
return;
}
node = node->nexts.at(index);
}
node->end--;
}
}
// word这个单词之前加入过几次
int search(string word)
{
if (word == "")
{
return 0;
}
const char* chs = word.c_str();
Node* node = root;
int index = 0;
int len = strlen(chs);
for (int i = 0; i < len; i++)
{
index = (int) chs[i];
if (node->nexts.find(index) == node->nexts.end())
{
return 0;
}
node = node->nexts.at(index);
}
return node->end;
}
// 所有加入的字符串中,有几个是以pre这个字符串作为前缀的
int prefixNumber(string pre)
{
if (pre == "")
{
return 0;
}
const char* chs = pre.c_str();
Node* node = root;
int index = 0;
int len = strlen(chs);
for (int i = 0; i < len; i++)
{
index = (int) chs[i];
if (node->nexts.find(index) == node->nexts.end())
{
return 0;
}
node = node->nexts.at(index);
}
return node->pass;
}
};
class Right
{
public:
unordered_map<string, int> box;
void insert(string word)
{
if(box.find(word) == box.end())
{
box.emplace(word, 1);
}
else
{
box[word]++;
}
}
void del (string word)
{
if(box.find(word) != box.end())
{
if(box.at(word) == 1)
{
box.erase(word);
}
else
{
box[word]--;
}
}
}
int search(string word)
{
if(box.find(word) == box.end())
{
return 0;
}
else
{
return box.at(word);
}
}
int prefixNumber(string pre)
{
int count = 0;
for(auto cur : box)
{
if(cur.first.find(pre) == 0) // pre是开始字符
{
count += box.at(cur.first);
}
}
return count;
}
};
static int getRandom(int min, int max)
{
random_device seed; // 硬件生成随机数种子
ranlux48 engine(seed()); // 利用种子生成随机数引
uniform_int_distribution<> distrib(min, max); // 设置随机数范围,并为均匀分布
int res = distrib(engine); // 随机数
return res;
}
static string generateRandomString(int strLen)
{
int len = getRandom(1, strLen);
char* ans = new char[len];
for (int i = 0; i < len; i++)
{
int value = (int) getRandom(0, 5);
ans[i] = (char) (97 + value);
}
return string(ans);
}
static string* generateRandomStringArray(int arrLen, int strLen, int* len)
{
*len = getRandom(1, arrLen);
string* ans = new string[*len];
for (int i = 0; i < *len; i++)
{
ans[i] = generateRandomString(strLen);
}
return ans;
}
};
int main()
{
int arrLen = 100;
int strLen = 20;
int testTimes = 1000;
int len = 0;
for (int i = 0; i < testTimes; i++)
{
string* arr = TrieTree::generateRandomStringArray(arrLen, strLen, &len);
TrieTree::Trie trie;
TrieTree::Right right;
for (int j = 0; j < len; j++)
{
double decide = double (TrieTree::getRandom(0, 1023) / 1024.0);
if (decide < 0.25)
{
trie.insert(arr[j]);
right.insert(arr[j]);
}
else if (decide < 0.5)
{
trie.del(arr[j]);
right.del(arr[j]);
}
else if (decide < 0.75)
{
int ans1 = trie.search(arr[j]);
int ans2 = right.search(arr[j]);
if (ans1 != ans2)
{
cout << "Oops!" << endl;
}
}
else
{
int ans1 = trie.prefixNumber(arr[j]);
int ans2 = right.prefixNumber(arr[j]);
if (ans1 != ans2)
{
cout << "Oops!" << endl;
}
}
}
}
cout << "finish!" << endl;
return 0;
}
| 21.873606
| 78
| 0.406526
|
raining888
|
acf8e33715d26fbff11bf57300d429ec1ec3965c
| 2,786
|
cpp
|
C++
|
src/components/improviser.cpp
|
jan-van-bergen/Synth
|
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
|
[
"MIT"
] | 17
|
2021-03-22T14:17:16.000Z
|
2022-02-22T20:58:27.000Z
|
src/components/improviser.cpp
|
jan-van-bergen/Synth
|
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
|
[
"MIT"
] | null | null | null |
src/components/improviser.cpp
|
jan-van-bergen/Synth
|
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
|
[
"MIT"
] | 1
|
2021-11-17T18:00:55.000Z
|
2021-11-17T18:00:55.000Z
|
#include "improviser.h"
#include "synth/synth.h"
void ImproviserComponent::update(Synth const & synth) {
constexpr auto transfer = util::generate_lookup_table<float, 7 * 7>([](int index) -> float {
constexpr float matrix[7 * 7] = {
1.0f, 2.0f, 2.0f, 3.0f, 5.0f, 1.0f, 1.0f,
1.0f, 1.0f, 2.0f, 1.0f, 5.0f, 3.0f, 2.0f,
2.0f, 1.0f, 1.0f, 2.0f, 3.0f, 2.0f, 3.0f,
2.0f, 1.0f, 2.0f, 1.0f, 2.0f, 2.0f, 1.0f,
7.0f, 1.0f, 2.0f, 2.0f, 1.0f, 2.0f, 3.0f,
3.0f, 2.0f, 2.0f, 2.0f, 2.0f, 1.0f, 2.0f,
5.0f, 2.0f, 2.0f, 1.0f, 1.0f, 2.0f, 1.0f
};
auto row = index / 7;
auto offset = index % 7;
auto cumulative = 0.0f;
auto row_sum = 0.0f;
for (int i = 0; i < 7; i++) {
auto val = matrix[row * 7 + i];
if (i <= offset) cumulative += val;
row_sum += val;
}
return cumulative / row_sum;
});
constexpr int MAJOR_SCALE[7] = { 0, 2, 4, 5, 7, 9, 11 };
constexpr int MINOR_SCALE[7] = { 0, 2, 3, 5, 7, 8, 10 };
constexpr auto BASE_NOTE = util::note<util::NoteName::C, 3>();
constexpr auto VELOCITY = 0.5f;
auto const scale = mode == Mode::MAJOR ? MAJOR_SCALE : MINOR_SCALE;
auto steps_per_second = 4.0f / 60.0f * float(synth.settings.tempo);
auto samples = 16.0f * SAMPLE_RATE / steps_per_second;
for (int i = 0; i < BLOCK_SIZE; i++) {
if (current_time >= samples) {
for (auto note : chord) {
outputs[0].add_event(NoteEvent::make_release(synth.time + i, note));
}
chord.clear();
auto u = util::randf(seed);
auto next_chord = 0;
while (next_chord < 7 && transfer[current_chord * 7 + next_chord] < u) next_chord++;
current_chord = next_chord;
current_time = 0;
for (int n = 0; n < num_notes; n++) {
auto note = BASE_NOTE + tonality + scale[util::wrap(current_chord + 2*n, 7)];
chord.emplace_back(note);
outputs[0].add_event(NoteEvent::make_press(synth.time + i, note, VELOCITY));
}
}
current_time++;
}
}
void ImproviserComponent::render(Synth const & synth) {
auto fmt_tonality = [](int tonality, char * fmt, int len) {
static constexpr char const * names[12] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
strcpy_s(fmt, len, names[tonality]);
};
tonality .render(fmt_tonality); ImGui::SameLine();
num_notes.render();
auto mode_index = int(mode);
if (ImGui::BeginCombo("Mode", mode_names[mode_index])) {
for (int i = 0; i < util::array_count(mode_names); i++) {
if (ImGui::Selectable(mode_names[i], mode_index == i)) {
mode_index = i;
}
}
ImGui::EndCombo();
}
mode = Mode(mode_index);
}
void ImproviserComponent::serialize_custom(json::Writer & writer) const {
writer.write("mode", int(mode));
}
void ImproviserComponent::deserialize_custom(json::Object const & object) {
mode = Mode(object.find_int("mode"));
}
| 27.048544
| 112
| 0.609835
|
jan-van-bergen
|
acff9a03c40bfd96d0dc41ce22181ba72f6ae208
| 348
|
cpp
|
C++
|
2017-08-03/I.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 3
|
2018-04-02T06:00:51.000Z
|
2018-05-29T04:46:29.000Z
|
2017-08-03/I.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 2
|
2018-03-31T17:54:30.000Z
|
2018-05-02T11:31:06.000Z
|
2017-08-03/I.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 2
|
2018-10-07T00:08:06.000Z
|
2021-06-28T11:02:59.000Z
|
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
int T;
int N, cnt[2];
int main()
{
int t, i, x;
scanf("%d", &T);
for(t = 0;t < T;t += 1)
{
cnt[0] = cnt[1] = 0;
scanf("%d", &N);
for(i = 0;i < N;i += 1)
{
scanf("%d", &x);
cnt[x & 1] += 1;
}
printf("2 %d\n", cnt[0] >= cnt[1]?0:1);
}
exit(0);
}
| 12.888889
| 41
| 0.462644
|
tangjz
|
4a07244eeeb593544fc963b05a5583d3de6dbb77
| 1,758
|
cpp
|
C++
|
tests/Geometry/XSRay2Test.cpp
|
Sibras/ShiftLib
|
83e1ab9605aca6535af836ad1e68bf3c3049d976
|
[
"Apache-2.0"
] | null | null | null |
tests/Geometry/XSRay2Test.cpp
|
Sibras/ShiftLib
|
83e1ab9605aca6535af836ad1e68bf3c3049d976
|
[
"Apache-2.0"
] | null | null | null |
tests/Geometry/XSRay2Test.cpp
|
Sibras/ShiftLib
|
83e1ab9605aca6535af836ad1e68bf3c3049d976
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright Matthew Oliver
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef XSTESTMAIN
# include "XSCompilerOptions.h"
# define XS_OVERRIDE_SHIFT_NS TESTISA(Ray2Test)
# define XS_TESTING_RAY2
# include "Geometry/XSGTestGeometry.hpp"
using namespace XS_OVERRIDE_SHIFT_NS;
using namespace XS_OVERRIDE_SHIFT_NS::Shift;
template<typename T>
class TESTISA(Ray2)
: public ::testing::Test
{
public:
using Type = T;
using TypeInt = typename T::Type; // requested type
static constexpr SIMDWidth width = T::width; // requested width
static constexpr SIMDWidth widthImpl = T::widthImpl; // actual width in use
static constexpr bool packed = T::packed;
};
using Ray2TestTypes = ::testing::Types<Ray2<float, true, SIMDWidth::Scalar>, Ray2<float, false, SIMDWidth::Scalar>,
Ray2<float, true, SIMDWidth::B16>, Ray2<float, false, SIMDWidth::B16>, Ray2<float, true, SIMDWidth::B32>,
Ray2<float, false, SIMDWidth::B32> /*, Ray2<float, true, SIMDWidth::B64>, Ray2<float, false, SIMDWidth::B64>*/>;
TYPED_TEST_SUITE(TESTISA(Ray2), Ray2TestTypes);
TYPED_TEST_NS2(Ray2, TESTISA(Ray2), Ray2)
{
using TestType = typename TestFixture::Type;
// TODO:************
}
#endif
| 35.16
| 116
| 0.710466
|
Sibras
|
4a0e8d4bb60b0ec8f6211aaa2ff7184f24e140bd
| 561
|
cpp
|
C++
|
src/tema cu WHILE/Aplicatii 4/ex4.cpp
|
andrew-miroiu/Cpp-projects
|
d0917a7f78aef929c25dc9b019e910951c2050ac
|
[
"MIT"
] | 2
|
2021-11-27T18:29:32.000Z
|
2021-11-28T14:35:47.000Z
|
src/tema cu WHILE/Aplicatii 4/ex4.cpp
|
andrew-miroiu/Cpp-projects
|
d0917a7f78aef929c25dc9b019e910951c2050ac
|
[
"MIT"
] | null | null | null |
src/tema cu WHILE/Aplicatii 4/ex4.cpp
|
andrew-miroiu/Cpp-projects
|
d0917a7f78aef929c25dc9b019e910951c2050ac
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
/* 4. Se citeşte de la tastatură un număr natural x de cel mult 9 cifre. Se cere să se calculeze
produsul cifrelor impare. Exemplu: dacă x =6543 atunci produsul cifrelor impare este 3*5=15*/
int x,p=1;
cout<<"Scrie un nr. de macimum 9 cifre= ";
cin>>x;
while(x>0)
{
if(x%2!=0)
{
p=p*(x%10);
x=x/10;
}
else
{
x=x/10;
}
}
cout<<"Produsul cifrelor impare este "<<p;
return 0;
}
| 17
| 100
| 0.516934
|
andrew-miroiu
|
4a115e8ec19668860f858a4965ca76d1679f0649
| 615
|
hpp
|
C++
|
model/player.hpp
|
travnick/SlipperTanks
|
33334cf0994402e7ba0e8de54f75a86835e0bae0
|
[
"Apache-2.0"
] | 1
|
2015-01-11T11:03:18.000Z
|
2015-01-11T11:03:18.000Z
|
model/player.hpp
|
travnick/SlipperTanks
|
33334cf0994402e7ba0e8de54f75a86835e0bae0
|
[
"Apache-2.0"
] | null | null | null |
model/player.hpp
|
travnick/SlipperTanks
|
33334cf0994402e7ba0e8de54f75a86835e0bae0
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <string>
class QVector3D;
struct InputEvents;
class Node;
class Player
{
public:
Player();
~Player();
const std::string &getRequiredModelName() const;
void setAttachedNode(Node *attachedModel);
const Node &getAttachedNode() const;
Node &getAttachedNode();
void move(const QVector3D &moveDirection, float seconds);
void rotate(float angle, const QVector3D &axis);
void setSpeed(float speed);
private:
void handleInputEvents(const InputEvents & inputEvents, float secondsElapsed);
std::string _requiredModelName;
Node *_attachedNode;
};
| 18.636364
| 82
| 0.715447
|
travnick
|
4a1179ee7ae693a959bcea83b3a3d08e4fb0fc89
| 251
|
cpp
|
C++
|
lzham_assert.cpp
|
pg9182/tf2lzham
|
c11a1f50ebc85f9290ede436a1f8e2f34b646be0
|
[
"MIT"
] | null | null | null |
lzham_assert.cpp
|
pg9182/tf2lzham
|
c11a1f50ebc85f9290ede436a1f8e2f34b646be0
|
[
"MIT"
] | null | null | null |
lzham_assert.cpp
|
pg9182/tf2lzham
|
c11a1f50ebc85f9290ede436a1f8e2f34b646be0
|
[
"MIT"
] | null | null | null |
// File: lzham_assert.cpp
// See Copyright Notice and license at the end of lzham.h
#include "lzham_core.h"
void lzham_assert(const char* pExp, const char* pFile, unsigned line)
{
printf("%s(%u): Assertion failed: \"%s\"\n", pFile, line, pExp);
}
| 27.888889
| 69
| 0.693227
|
pg9182
|
4a11b18559df526fb7ed452752e4b5ef3820c186
| 8,879
|
cpp
|
C++
|
src/client/input/InputPicker.cpp
|
arthurmco/familyline
|
849eee40cff266af9a3f848395ed139b7ce66197
|
[
"MIT"
] | 6
|
2018-05-11T23:16:02.000Z
|
2019-06-13T01:35:07.000Z
|
src/client/input/InputPicker.cpp
|
arthurmco/familyline
|
849eee40cff266af9a3f848395ed139b7ce66197
|
[
"MIT"
] | 33
|
2018-05-11T14:12:22.000Z
|
2022-03-12T00:55:25.000Z
|
src/client/input/InputPicker.cpp
|
arthurmco/familyline
|
849eee40cff266af9a3f848395ed139b7ce66197
|
[
"MIT"
] | 1
|
2018-12-06T23:39:55.000Z
|
2018-12-06T23:39:55.000Z
|
#include <algorithm>
#include <client/input/InputPicker.hpp>
#include <common/logic/logic_service.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace familyline::input;
using namespace familyline::graphics;
using namespace familyline::logic;
InputPicker::InputPicker(
Terrain* terrain, Window* win, SceneManager* sm, Camera* cam, ObjectManager* om)
{
this->_terrain = terrain;
this->_win = win;
this->_sm = sm;
this->_cam = cam;
this->_om = om;
// ObjectEventEmitter::addListener(&oel);
}
/* Get cursor ray in screen space */
glm::vec4 InputPicker::GetCursorScreenRay()
{
int w = 0, h = 0, x = 0, y = 0;
_win->getSize(w, h);
Cursor::GetInstance()->GetPositions(x, y);
// Create ray data.
glm::vec4 ray = glm::vec4((2.0f * x) / w - 1.0f, 1.0f - (2.0f - y) / h, -1.0f, 1.0f);
return ray;
}
/* Get cursor ray in eye space */
glm::vec4 InputPicker::GetCursorEyeRay()
{
glm::vec4 cur_eye = glm::inverse(_cam->GetProjectionMatrix()) * this->GetCursorScreenRay();
return glm::vec4(cur_eye.x, cur_eye.y, -1.0f, 0.0f);
}
/* Get cursor ray in world space */
glm::vec3 InputPicker::GetCursorWorldRay()
{
/*
glm::vec4 cur_world = glm::inverse(_cam->GetViewMatrix()) * this->GetCursorEyeRay();
glm::vec3 cur_world3 = glm::vec3(cur_world.x, cur_world.y, cur_world.z);
return glm::normalize(cur_world3);
*/
int x = 0, y = 0, w = 0, h = 0;
_win->getSize(w, h);
Cursor::GetInstance()->GetPositions(x, y);
glm::vec3 cStart = glm::unProject(
glm::vec3(x, h - y, 0), _cam->GetViewMatrix(), _cam->GetProjectionMatrix(),
glm::vec4(0, 0, w, h));
glm::vec3 cEnd = glm::unProject(
glm::vec3(x, h - y, 1), _cam->GetViewMatrix(), _cam->GetProjectionMatrix(),
glm::vec4(0, 0, w, h));
glm::vec3 cur_world = glm::normalize(cEnd - cStart);
return cur_world;
}
/* Check if we intersect with the terrain between between start and end */
bool InputPicker::CheckIfTerrainIntersect(glm::vec3 ray, float start, float end)
{
glm::vec3 pStart = _cam->GetPosition() + (ray * start);
glm::vec3 pEnd = _cam->GetPosition() + (ray * end);
if (pStart.y >= 0 && pEnd.y < 0) {
return true;
}
return false;
}
void InputPicker::UpdateTerrainProjectedPosition()
{
glm::vec3 cur_world = this->GetCursorWorldRay();
/*printf("\ncamera_pos: %.4f %.4f %.4f, ray_pos: %.4f %.4f %.4f\n",
_cam->GetPosition().x, _cam->GetPosition().y, _cam->GetPosition().z,
cur_world.x, cur_world.y, cur_world.z);
*/
float prolong_near = 0.1f, prolong_far = 128.0f;
float prolong_now = prolong_near + ((prolong_far - prolong_near) / 2.0f);
glm::vec3 pHalf = glm::vec3(64, 0, 64);
auto [width, height] = _terrain->getSize();
// printf("near: %.3f %.3f %.3f, far: %.3f %.3f %.3f, prolongs: { ",
// pNear.x, pNear.y, pNear.z, pFar.x, pFar.y, pFar.z);
for (int i = 0; i < MAX_PICK_ITERATIONS; i++) {
/* Here, we'll check if the ray projection is above or below the terrain
If we're above, we'll adjust pNear to that point
If we're below, we'll adjust pFar to that point
To check that, we simply check if pFar is under and
pNear and pHalf are above
*/
if (this->CheckIfTerrainIntersect(cur_world, prolong_near, prolong_now))
prolong_far = prolong_now;
else
prolong_near = prolong_now;
prolong_now = prolong_near + ((prolong_far - prolong_near) / 2.0f);
pHalf = _cam->GetPosition() + (cur_world * prolong_now);
// printf("%.2f (%.2f %.2f %.2f), ", prolong_now, pHalf.x, pHalf.y, pHalf.z);
}
glm::vec3 collide = _terrain->graphicalToGame(pHalf);
/* Clamp collide to the terrain area */
if (collide.x >= width)
collide.x = width - 1;
if (collide.z >= height)
collide.z = height - 1;
if (collide.x < 0) collide.x = 0;
if (collide.z < 0) collide.z = 0;
auto pointHeight = _terrain->getHeightFromCoords(glm::vec2(collide.x, collide.z));
if (collide.x > 0 && collide.z > 0)
collide.y = pointHeight;
// printf(" }\nprol: %.2f, pos: %.3f %.3f %.3f, gamespace: %.3f %.3f %.3f\n\n",
// 1.0f, pHalf.x, pHalf.y, pHalf.z, collide.x, collide.y, collide.z);
_intersectedPosition = collide;
}
void InputPicker::UpdateIntersectedObject()
{
glm::vec3 direction = this->GetCursorWorldRay();
glm::vec3 origin = _cam->GetPosition();
const auto& olist = familyline::logic::LogicService::getObjectListener();
std::set<object_id_t> toAdd;
std::set<object_id_t> toRemove;
std::map<object_id_t, bool> aliveMap;
auto aliveObjects = olist->getAliveObjects();
for (auto obj : this->poi_list) {
// Stored object is still alive
if (aliveObjects.find(obj.ID) != aliveObjects.end()) {
aliveMap[obj.ID] = true;
}
// Stored object is not alive anymore
if (aliveObjects.find(obj.ID) == aliveObjects.end()) {
aliveMap[obj.ID] = false;
toRemove.insert(obj.ID);
}
}
for (auto objid : aliveObjects) {
// We have a new stored object
if (aliveMap.find(objid) == aliveMap.end()) {
toAdd.insert(objid);
}
}
for (auto objid : toRemove) {
poi_list.erase(std::remove_if(
poi_list.begin(), poi_list.end(),
[&](const PickerObjectInfo& poi) { return poi.ID == objid; }));
}
for (auto objid : toAdd) {
auto object = _om->get(objid).value();
if (!object->getLocationComponent()) {
continue;
}
auto mesh = object->getLocationComponent()->mesh;
poi_list.emplace_back(object->getPosition(), std::dynamic_pointer_cast<Mesh>(mesh), objid);
}
// Check the existing objects
for (const PickerObjectInfo& poi : poi_list) {
auto obj = _om->get(poi.ID);
if (!obj)
continue;
auto osize = (*obj)->getSize();
auto gsize = _terrain->gameToGraphical(
glm::vec3(osize.x, 0, osize.y));
if (!poi.mesh)
continue;
auto gpos = poi.mesh->getPosition();
glm::vec4 vmin = glm::vec4(-gsize.x/2, gpos.y, -gsize.z/2, 1);
glm::vec4 vmax = glm::vec4(gsize.x/2, glm::max(gsize.x, gsize.z),
gsize.z/2, 1);
vmin = poi.mesh->getWorldMatrix() * vmin;
vmax = poi.mesh->getWorldMatrix() * vmax;
glm::min(vmin.y, 0.0f);
glm::max(vmax.y, 0.0f);
// glm::vec3 planePosX, planePosY, planePosZ;
float tmin = -100000;
float tmax = 100000;
float dxmin, dxMax;
if (direction.x != 0) {
dxmin = (vmin.x - origin.x) / direction.x;
dxMax = (vmax.x - origin.x) / direction.x;
tmin = fmaxf(tmin, fminf(dxmin, dxMax));
tmax = fminf(tmax, fmaxf(dxmin, dxMax));
// printf("x: %.4f %.4f \t", dxmin, dxMax);
if (tmax < tmin) continue;
}
if (direction.y != 0) {
dxmin = (vmin.y - origin.y) / direction.y;
dxMax = (vmax.y - origin.y) / direction.y;
tmin = fmaxf(tmin, fminf(dxmin, dxMax));
tmax = fminf(tmax, fmaxf(dxmin, dxMax));
// printf("y: %.4f %.4f \t", dxmin, dxMax);
if (tmax < tmin) continue;
}
if (direction.z != 0) {
dxmin = (vmin.z - origin.z) / direction.z;
dxMax = (vmax.z - origin.z) / direction.z;
tmin = fmaxf(tmin, fminf(dxmin, dxMax));
tmax = fminf(tmax, fmaxf(dxmin, dxMax));
// printf("z: %.4f %.4f \t", dxmin, dxMax);
if (tmax < tmin) continue;
}
// printf("total: %.4f %.4f\n", tmin, tmax);
/* Ray misses */
if (tmin < 0) {
continue;
}
/* Collided with both 3 axis! */
if (tmax >= tmin) {
auto lobj = _om->get(poi.ID);
if (!lobj.has_value()) return;
_locatableObject = lobj.value();
if (!_locatableObject.expired()) return;
}
}
_locatableObject = std::weak_ptr<GameObject>();
}
/* Get position where the cursor collides with the
terrain, in render coordinates */
glm::vec3 InputPicker::GetTerrainProjectedPosition()
{
return _terrain->gameToGraphical(_intersectedPosition);
}
/* Get position where the cursor collides with the
terrain, in game coordinates */
glm::vec2 InputPicker::GetGameProjectedPosition()
{
glm::vec3 intGame = _intersectedPosition;
return glm::vec2(intGame.x, intGame.z);
}
/* Get the object that were intersected by the cursor ray */
std::weak_ptr<GameObject> InputPicker::GetIntersectedObject() { return this->_locatableObject; }
| 31.485816
| 99
| 0.580696
|
arthurmco
|
4a17238b90fd000f50b87eb59d7902c34bb96e19
| 965
|
cpp
|
C++
|
source/data_model/python/src/identity/object_id.cpp
|
OliverSchmitz/lue
|
da097e8c1de30724bfe7667cc04344b6535b40cd
|
[
"MIT"
] | 2
|
2021-02-26T22:45:56.000Z
|
2021-05-02T10:28:48.000Z
|
source/data_model/python/src/identity/object_id.cpp
|
OliverSchmitz/lue
|
da097e8c1de30724bfe7667cc04344b6535b40cd
|
[
"MIT"
] | 262
|
2016-08-11T10:12:02.000Z
|
2020-10-13T18:09:16.000Z
|
source/data_model/python/src/identity/object_id.cpp
|
computationalgeography/lue
|
71993169bae67a9863d7bd7646d207405dc6f767
|
[
"MIT"
] | 1
|
2020-03-11T09:49:41.000Z
|
2020-03-11T09:49:41.000Z
|
#include "../python_extension.hpp"
#include "lue/info/identity/object_id.hpp"
#include <pybind11/pybind11.h>
namespace py = pybind11;
using namespace pybind11::literals;
namespace lue {
namespace data_model {
void init_object_id(
py::module& module)
{
py::class_<ObjectID, same_shape::Value>(
module,
"ObjectID",
R"(
A class for storing the IDs of objects whose state does not change
through time
Use this class when object state is stored that does not change
through time. The order of the IDs stored must match the order of the
state stored. For example, when storing tree stem locations, the order
of space points stored in the space domain must match the order of
object IDs in the :class:`ObjectID` instance.
You never have to create an :class:`ObjectID` instance
yourself. :class:`Phenomenon` instances provide one.
)")
;
}
} // namespace data_model
} // namespace lue
| 24.125
| 74
| 0.700518
|
OliverSchmitz
|
4a1b0ba12f4518aaea6263a719ea6417392d33ea
| 1,902
|
cpp
|
C++
|
code/qttoolkit/importer/code/clip.cpp
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 67
|
2015-03-30T19:56:16.000Z
|
2022-03-11T13:52:17.000Z
|
code/qttoolkit/importer/code/clip.cpp
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 5
|
2015-04-15T17:17:33.000Z
|
2016-02-11T00:40:17.000Z
|
code/qttoolkit/importer/code/clip.cpp
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 34
|
2015-03-30T15:08:00.000Z
|
2021-09-23T05:55:10.000Z
|
#include "clip.h"
namespace Importer
{
//------------------------------------------------------------------------------
/**
*/
Clip::Clip()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
Clip::~Clip()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
Clip::SetName( const QString& name )
{
this->name = name;
}
//------------------------------------------------------------------------------
/**
*/
const QString&
Clip::GetName() const
{
return this->name;
}
//------------------------------------------------------------------------------
/**
*/
void
Clip::SetStart( uint start )
{
this->start = start;
}
//------------------------------------------------------------------------------
/**
*/
const uint
Clip::GetStart() const
{
return this->start;
}
//------------------------------------------------------------------------------
/**
*/
void
Clip::SetEnd( uint end )
{
this->end = end;
}
//------------------------------------------------------------------------------
/**
*/
const uint
Clip::GetEnd() const
{
return this->end;
}
//------------------------------------------------------------------------------
/**
*/
void
Clip::SetPreInfinity( Clip::InfinityType infinityType )
{
this->preInfinity = infinityType;
}
//------------------------------------------------------------------------------
/**
*/
const Clip::InfinityType
Clip::GetPreInfinity() const
{
return this->preInfinity;
}
//------------------------------------------------------------------------------
/**
*/
void
Clip::SetPostInfinity( Clip::InfinityType infinityType )
{
this->postInfinity = infinityType;
}
//------------------------------------------------------------------------------
/**
*/
const Clip::InfinityType
Clip::GetPostInfinity() const
{
return this->postInfinity;
}
}
| 17.135135
| 80
| 0.302839
|
gscept
|
4a1e2ead9d37ec79e2588268a92d9b2197f121fc
| 9,289
|
cpp
|
C++
|
Source/Plugin/MySql/Src/DatabaseStatementMySql.cpp
|
DragonJoker/DatabaseConnector
|
502b136588b46119c2a0f4ed6b6623c0cc6715c2
|
[
"MIT"
] | 2
|
2018-03-01T01:14:38.000Z
|
2019-10-27T13:29:18.000Z
|
Source/Plugin/MySql/Src/DatabaseStatementMySql.cpp
|
DragonJoker/DatabaseConnector
|
502b136588b46119c2a0f4ed6b6623c0cc6715c2
|
[
"MIT"
] | null | null | null |
Source/Plugin/MySql/Src/DatabaseStatementMySql.cpp
|
DragonJoker/DatabaseConnector
|
502b136588b46119c2a0f4ed6b6623c0cc6715c2
|
[
"MIT"
] | null | null | null |
/************************************************************************//**
* @file DatabaseStatementMySql.cpp
* @author Sylvain Doremus
* @version 1.0
* @date 3/20/2014 2:47:39 PM
*
*
* @brief CDatabaseStatementMySql class definition.
*
* @details Describes a statement for MYSQL database.
*
***************************************************************************/
#include "DatabaseMySqlPch.h"
#include "DatabaseStatementMySql.h"
#include "DatabaseConnectionMySql.h"
#include "DatabaseMySql.h"
#include "DatabaseParameterMySql.h"
#include "ExceptionDatabaseMySql.h"
#include <DatabaseStringUtils.h>
#include <DatabaseRow.h>
#include <mysql/mysql.h>
BEGIN_NAMESPACE_DATABASE_MYSQL
{
static const String ERROR_MYSQL_MISSING_INITIALIZATION = STR( "Method Initialise must be called before calling method CreateParameter" );
static const String ERROR_MYSQL_CANT_CREATE_STATEMENT = STR( "Couldn't create the statement" );
static const String ERROR_MYSQL_LOST_CONNECTION = STR( "The statement has lost his connection" );
static const String ERROR_FIELD_RETRIEVAL = STR( "Field retrieval error" );
static const String INFO_MYSQL_BIND_PARAMETER_NAME = STR( "BindParameter : " );
static const String INFO_MYSQL_BIND_PARAMETER_VALUE = STR( ", Value : " );
static const String DEBUG_MYSQL_PREPARING_STATEMENT = STR( "Preparing statement 0x%08X" );
static const TChar * INFO_MYSQL_STATEMENT_PREPARATION = STR( "Statement preparation" );
static const TChar * INFO_MYSQL_STATEMENT_PARAMS_BINDING = STR( "Statement parameters binding" );
static const TChar * INFO_MYSQL_STATEMENT_RESET = STR( "Statement reset" );
static const String MYSQL_SQL_DELIM = STR( "?" );
static const String MYSQL_SQL_PARAM = STR( "@" );
static const String MYSQL_SQL_SET = STR( "SET @" );
static const String MYSQL_SQL_NULL = STR( " = NULL;" );
static const String MYSQL_SQL_SELECT = STR( "SELECT " );
static const String MYSQL_SQL_AS = STR( " AS " );
static const String MYSQL_SQL_COMMA = STR( "," );
CDatabaseStatementMySql::CDatabaseStatementMySql( DatabaseConnectionMySqlSPtr connection, const String & query )
: CDatabaseStatement( connection, query )
, _statement( NULL )
, _connectionMySql( connection )
, _paramsCount( 0 )
{
}
CDatabaseStatementMySql::~CDatabaseStatementMySql()
{
Cleanup();
}
DatabaseParameterSPtr CDatabaseStatementMySql::DoCreateParameter( DatabaseValuedObjectInfosSPtr infos, EParameterType parameterType )
{
DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection();
if ( !connection )
{
DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION );
}
DatabaseParameterMySqlSPtr parameter = std::make_shared< CDatabaseParameterMySql >( connection, infos, uint16_t( _arrayInParams.size() + 1 ), parameterType, std::make_unique< SValueUpdater >( this ) );
DatabaseParameterSPtr ret = DoAddParameter( parameter );
if ( ret && parameterType == EParameterType_IN )
{
_arrayInParams.push_back( parameter );
}
return ret;
}
EErrorType CDatabaseStatementMySql::DoInitialise()
{
DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection();
if ( !connection )
{
DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION );
}
EErrorType eReturn = EErrorType_ERROR;
if ( !_query.empty() )
{
_paramsCount = uint32_t( std::count( _query.begin(), _query.end(), STR( '?' ) ) );
_arrayQueries = StringUtils::Split( _query, STR( "?" ), _paramsCount + 1 );
}
CLogger::LogDebug( ( Format( DEBUG_MYSQL_PREPARING_STATEMENT ) % this ).str() );
assert( _paramsCount == GetParametersCount() );
StringStream query;
unsigned short i = 0;
auto && itQueries = _arrayQueries.begin();
auto && itParams = DoGetParameters().begin();
auto && itParamsEnd = DoGetParameters().end();
_outInitialisers.clear();
_arrayOutParams.clear();
_outInitialisers.reserve( GetParametersCount() );
_arrayOutParams.reserve( GetParametersCount() );
_bindings.reserve( GetParametersCount() );
while ( itQueries != _arrayQueries.end() && itParams != itParamsEnd )
{
query << ( *itQueries );
DatabaseParameterMySqlSPtr parameter = std::static_pointer_cast< CDatabaseParameterMySql >( *itParams );
if ( parameter->GetParamType() == EParameterType_OUT )
{
query << MYSQL_SQL_PARAM + parameter->GetName();
DatabaseStatementSPtr stmt = connection->CreateStatement( MYSQL_SQL_SET + parameter->GetName() + MYSQL_SQL_NULL );
stmt->Initialise();
_outInitialisers.push_back( stmt );
_arrayOutParams.push_back( parameter );
}
else if ( parameter->GetParamType() == EParameterType_IN )
{
MYSQL_BIND bind = { 0 };
_bindings.push_back( bind );
query << MYSQL_SQL_DELIM;
}
else
{
query << MYSQL_SQL_PARAM + parameter->GetName();
DatabaseStatementSPtr stmt = connection->CreateStatement( MYSQL_SQL_SET + parameter->GetName() + STR( " = " ) + MYSQL_SQL_DELIM );
stmt->CreateParameter( parameter->GetName(), parameter->GetType(), parameter->GetLimits(), EParameterType_IN );
stmt->Initialise();
_inOutInitialisers.push_back( std::make_pair( stmt, parameter ) );
_arrayOutParams.push_back( parameter );
}
++i;
++itQueries;
++itParams;
}
while ( itQueries != _arrayQueries.end() )
{
query << ( *itQueries );
++itQueries;
}
_query = query.str();
if ( !_arrayOutParams.empty() )
{
String sep;
StringStream queryInOutParam;
queryInOutParam << MYSQL_SQL_SELECT;
for ( auto && parameter : _arrayOutParams )
{
queryInOutParam << sep << MYSQL_SQL_PARAM << parameter.lock()->GetName() << MYSQL_SQL_AS << parameter.lock()->GetName();
sep = MYSQL_SQL_COMMA;
}
_stmtOutParams = connection->CreateStatement( queryInOutParam.str() );
_stmtOutParams->Initialise();
}
_statement = mysql_stmt_init( connection->GetConnection() );
if ( _statement )
{
eReturn = EErrorType_NONE;
}
else
{
DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_CANT_CREATE_STATEMENT );
}
MySQLCheck( mysql_stmt_prepare( _statement, _query.c_str(), uint32_t( _query.size() ) ), INFO_MYSQL_STATEMENT_PREPARATION, EDatabaseExceptionCodes_StatementError, connection->GetConnection() );
MYSQL_RES * meta = mysql_stmt_param_metadata( _statement );
size_t index = 0;
for ( auto && it : _arrayInParams )
{
DatabaseParameterMySqlSPtr parameter = it.lock();
parameter->SetStatement( _statement );
parameter->SetBinding( &_bindings[index++] );
}
MySQLCheck( mysql_stmt_bind_param( _statement, _bindings.data() ), INFO_MYSQL_STATEMENT_PARAMS_BINDING, EDatabaseExceptionCodes_StatementError, connection->GetConnection() );
return eReturn;
}
bool CDatabaseStatementMySql::DoExecuteUpdate()
{
DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection();
if ( !connection )
{
DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION );
}
DoPreExecute();
bool bReturn = connection->ExecuteUpdate( _statement );
if ( bReturn )
{
DoPostExecute();
}
return bReturn;
}
DatabaseResultSPtr CDatabaseStatementMySql::DoExecuteSelect()
{
DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection();
if ( !connection )
{
DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION );
}
DoPreExecute();
DatabaseResultSPtr pReturn = connection->ExecuteSelect( _statement, _infos );
if ( pReturn )
{
DoPostExecute();
}
return pReturn;
}
void CDatabaseStatementMySql::DoCleanup()
{
_bindings.clear();
_arrayInParams.clear();
_arrayOutParams.clear();
_outInitialisers.clear();
_arrayQueries.clear();
_paramsCount = 0;
_stmtOutParams.reset();
if ( _statement )
{
mysql_stmt_close( _statement );
_statement = NULL;
}
}
void CDatabaseStatementMySql::DoPreExecute()
{
for ( auto && it : _inOutInitialisers )
{
DatabaseParameterSPtr parameter = it.second.lock();
if ( parameter->GetObjectValue().IsNull() )
{
it.first->SetParameterNull( 0 );
}
else
{
it.first->SetParameterValue( 0, static_cast< const CDatabaseValuedObject & >( *parameter ) );
}
it.first->ExecuteUpdate();
}
for ( auto && it : _outInitialisers )
{
it->ExecuteUpdate();
}
}
void CDatabaseStatementMySql::DoPostExecute()
{
if ( !_arrayOutParams.empty() )
{
DatabaseResultSPtr pReturn = _stmtOutParams->ExecuteSelect();
if ( pReturn && pReturn->GetRowCount() )
{
DatabaseRowSPtr row = pReturn->GetFirstRow();
for ( auto && wparameter : _arrayOutParams )
{
DatabaseParameterSPtr parameter = wparameter.lock();
if ( parameter->GetParamType() == EParameterType_INOUT || parameter->GetParamType() == EParameterType_OUT )
{
DatabaseFieldSPtr field;
try
{
field = row->GetField( parameter->GetName() );
}
COMMON_CATCH( ERROR_FIELD_RETRIEVAL )
if ( field )
{
parameter->SetValue( static_cast< const CDatabaseValuedObject & >( *field ) );
}
}
}
}
}
MySQLCheck( mysql_stmt_reset( _statement ), INFO_MYSQL_STATEMENT_RESET, EDatabaseExceptionCodes_StatementError, DoGetMySqlConnection()->GetConnection() );
}
}
END_NAMESPACE_DATABASE_MYSQL
| 28.937695
| 203
| 0.704597
|
DragonJoker
|
4a233bd65d10e1ffce66653b3d1f088b61feafc9
| 1,864
|
cpp
|
C++
|
Room.cpp
|
guyou/T-watch-2020
|
e68fb1c3171157bb943c1ebf8351f1d66411980a
|
[
"BSD-3-Clause"
] | 74
|
2020-09-29T17:27:03.000Z
|
2022-03-31T08:04:13.000Z
|
Room.cpp
|
guyou/T-watch-2020
|
e68fb1c3171157bb943c1ebf8351f1d66411980a
|
[
"BSD-3-Clause"
] | 36
|
2020-09-30T19:33:16.000Z
|
2021-04-18T03:31:32.000Z
|
Room.cpp
|
guyou/T-watch-2020
|
e68fb1c3171157bb943c1ebf8351f1d66411980a
|
[
"BSD-3-Clause"
] | 23
|
2020-10-09T07:41:09.000Z
|
2021-12-06T10:13:35.000Z
|
/*
# Maze Generator
### Date: 28 March 2018
### Author: Pisica Alin
*/
#include "config.h"
#include "DudleyWatch.h"
#include "Room.h"
using namespace std;
Room::Room(int i, int j, int rw) {
this->x = i;
this->y = j;
this->roomWidth = rw;
walls[0] = true;
walls[1] = true;
walls[2] = true;
walls[3] = true;
visited = false;
}
void Room::removeWalls(Room &r) {
if (this->x - r.x == -1) {
this->removeWall(1);
r.removeWall(3);
}
if (this->x - r.x == 1) {
this->removeWall(3);
r.removeWall(1);
}
if (this->y - r.y == -1) {
this->removeWall(2);
r.removeWall(0);
}
if (this->y - r.y == 1) {
this->removeWall(0);
r.removeWall(2);
}
}
void Room::show(void) {
int xCoord = this->x * roomWidth;
int yCoord = this->y * roomWidth;
if (this->walls[0]) {
tft->drawLine(xCoord, yCoord, // top
xCoord + this->roomWidth, yCoord, TFT_RED);
}
if (this->walls[1]) { // right
tft->drawLine(xCoord + this->roomWidth, yCoord,
xCoord + this->roomWidth, yCoord + this->roomWidth, TFT_RED);
}
if (this->walls[2]) { // bottom
tft->drawLine(xCoord, yCoord + this->roomWidth,
xCoord + this->roomWidth, yCoord + this->roomWidth, TFT_RED);
}
if (this->walls[3]) { // left
tft->drawLine(xCoord, yCoord,
xCoord, yCoord + this->roomWidth, TFT_RED);
}
}
void Room::printWalls() {
for (int i = 0; i < 4; i++) {
std::cout << walls[i] << " ";
}
std::cout << "\n";
}
void Room::removeWall(int w) {
this->walls[w] = false;
}
bool Room::hasWall(int w) {
return this->walls[w];
}
void Room::visit(bool setact) {
this->visited = setact;
}
int Room::getPositionInVector(int size) {
return this->x * size + this->y;
}
int Room::getX() {
return this->x;
}
int Room::getY() {
return this->y;
}
bool Room::isVisited() {
return this->visited;
}
| 18.828283
| 65
| 0.574571
|
guyou
|
4a2542f273d1a78e7a1b2055cf15342bb19ca5ec
| 6,574
|
cpp
|
C++
|
Unix/tests/micxx/test_array.cpp
|
Beguiled/omi
|
1c824681ee86f32314f430db972e5d3938f10fd4
|
[
"MIT"
] | 165
|
2016-08-18T22:06:39.000Z
|
2019-05-05T11:09:37.000Z
|
Unix/tests/micxx/test_array.cpp
|
snchennapragada/omi
|
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
|
[
"MIT"
] | 409
|
2016-08-18T20:52:56.000Z
|
2019-05-06T10:03:11.000Z
|
Unix/tests/micxx/test_array.cpp
|
snchennapragada/omi
|
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
|
[
"MIT"
] | 72
|
2016-08-23T02:30:08.000Z
|
2019-04-30T22:57:03.000Z
|
/*
**==============================================================================
**
** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
** for license information.
**
**==============================================================================
*/
#include <ut/ut.h>
#include <micxx/array.h>
#include <micxx/types.h>
#include <pal/atomic.h>
using namespace mi;
NitsSetup(TestArraySetup)
NitsEndSetup
NitsCleanup(TestArraySetup)
NitsEndCleanup
//union AlignmentStruct {
// void* p;
// Uint64 i;
//};
NitsTestWithSetup(TestArrayCtor, TestArraySetup)
{
const char s[] = "string1";
Array<char> v1(s, sizeof(s));
UT_ASSERT( strcmp(s, v1.GetData()) == 0);
UT_ASSERT( v1.GetSize() == sizeof(s));
// default ctor
Array<char> v2;
UT_ASSERT( v2.GetData() == 0);
UT_ASSERT( v2.GetSize() == 0);
// array ctor with 0 elements
Array<char> v3(s, 0);
UT_ASSERT( v3.GetData() == 0);
UT_ASSERT( v3.GetSize() == 0);
}
NitsEndTest
NitsTestWithSetup(TestAccessOperator, TestArraySetup)
{
unsigned int sample[] = {1,2,3};
Array<unsigned int> v(sample,3);
UT_ASSERT( v.GetSize() == 3);
UT_ASSERT( v[0] == 1 );
UT_ASSERT( v[1] == 2 );
UT_ASSERT( v[2] == 3 );
}
NitsEndTest
template< typename TYPE, size_t AligmentSize>
static void TestDataAlignmentT()
{
Array<TYPE> v;
v.PushBack( TYPE() );
UT_ASSERT(v.GetSize() == 1);
UT_ASSERT(((long)v.GetData()) % AligmentSize == 0);
}
struct AlignmentTestStruct {
char c[21];
void*p;
};
NitsTestWithSetup(TestDataAlignment, TestArraySetup)
{
TestDataAlignmentT<char,sizeof(char)>();
TestDataAlignmentT<long,sizeof(long)>();
TestDataAlignmentT<Uint64,sizeof(void*)>();
TestDataAlignmentT<void*,sizeof(void*)>();
TestDataAlignmentT<int,sizeof(int)>();
TestDataAlignmentT<short int,sizeof(short int)>();
TestDataAlignmentT<AlignmentTestStruct,sizeof(void*)>();
}
NitsEndTest
struct TestCreateDestroyClass{
bool m_created;
bool m_destroyed;
static volatile ptrdiff_t m_ctorCalls;
static volatile ptrdiff_t m_dtorCalls;
String s;
TestCreateDestroyClass()
{
s = MI_T("1");
m_created = true;
m_destroyed = false;
Atomic_Inc(&m_ctorCalls);
}
TestCreateDestroyClass(const TestCreateDestroyClass& x)
{
Atomic_Inc(&m_ctorCalls);
*this = x;
}
~TestCreateDestroyClass()
{
UT_ASSERT(isValid());
m_created = false;
m_destroyed = true;
Atomic_Inc(&m_dtorCalls);
}
bool isValid()const {return m_created && !m_destroyed && s == MI_T("1");}
};
volatile ptrdiff_t TestCreateDestroyClass::m_ctorCalls = 0;
volatile ptrdiff_t TestCreateDestroyClass::m_dtorCalls = 0;
static void TestAllItemsAreValid( const Array<TestCreateDestroyClass>& v )
{
for( Uint32 i = 0; i < v.GetSize(); i++ )
{
UT_ASSERT(v[i].isValid());
}
}
NitsTestWithSetup(TestCreatingDestroyingObjects, TestArraySetup)
{
Array<TestCreateDestroyClass> v, v2;
v.Resize(10);
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
v.PushBack( TestCreateDestroyClass() );
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
v2 = v;
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
v.PushBack( TestCreateDestroyClass() );
UT_ASSERT(v.GetSize() == 12);
UT_ASSERT(v2.GetSize() == 11);
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
v.Delete(0);
v2.Delete(10);
UT_ASSERT(v.GetSize() == 11);
UT_ASSERT(v2.GetSize() == 10);
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
v[1] = v2[4];
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
}
NitsEndTest
NitsTestWithSetup(TestClear, TestArraySetup)
{
Array<TestCreateDestroyClass> v, v2;
v.PushBack(TestCreateDestroyClass());
v2 = v;
v2.Resize(2);
UT_ASSERT(v.GetSize() == 1);
UT_ASSERT(v2.GetSize() == 2);
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
v2.Clear();
UT_ASSERT(v.GetSize() == 1);
UT_ASSERT(v2.GetSize() == 0);
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
}
NitsEndTest
NitsTestWithSetup(TestResize, TestArraySetup)
{
Array<TestCreateDestroyClass> v, v2;
v.Resize(3);
v2 = v;
v2.Resize(3);
UT_ASSERT(v.GetSize() == 3);
UT_ASSERT(v2.GetSize() == 3);
TestAllItemsAreValid(v);
TestAllItemsAreValid(v2);
}
NitsEndTest
NitsTestWithSetup(TestResizeWithRealloc, TestArraySetup)
{
Array<TestCreateDestroyClass> v, v2;
v.Resize(3);
UT_ASSERT(v.GetSize() == 3);
TestAllItemsAreValid(v);
// resize to big number to trigger re-alloc
v.Resize(3000);
UT_ASSERT(v.GetSize() == 3000);
TestAllItemsAreValid(v);
}
NitsEndTest
NitsTestWithSetup(TestAssignEmpty, TestArraySetup)
{
Array<TestCreateDestroyClass> v, v2;
v.Resize(3);
v = v2;
UT_ASSERT(v.GetSize() == 0);
UT_ASSERT(v2.GetSize() == 0);
}
NitsEndTest
NitsTestWithSetup(TestDeleteTheOnlyOne, TestArraySetup)
{
Array<TestCreateDestroyClass> v;
v.Resize(1);
v.Delete(0);
UT_ASSERT(v.GetSize() == 0);
}
NitsEndTest
NitsTestWithSetup(TestResizeToShrink, TestArraySetup)
{
Array<TestCreateDestroyClass> v;
v.Resize(100);
v.Resize(10);
UT_ASSERT(v.GetSize() == 10);
TestAllItemsAreValid(v);
}
NitsEndTest
NitsTestWithSetup(TestCtorDtorBalance, TestArraySetup)
{
ptrdiff_t ctor, dtor;
ctor = Atomic_Read(&TestCreateDestroyClass::m_ctorCalls);
dtor = Atomic_Read(&TestCreateDestroyClass::m_dtorCalls);
UT_ASSERT_EQUAL(ctor, dtor);
}
NitsEndTest
NitsTestWithSetup(TestGetWritableData, TestArraySetup)
{
Array< int > v;
v.Resize(3);
v.GetWritableData() [0] = 0;
v.GetWritableData() [1] = 1;
v.GetWritableData() [2] = 2;
UT_ASSERT(0 == v[0]);
UT_ASSERT(1 == v[1]);
UT_ASSERT(2 == v[2]);
}
NitsEndTest
NitsTestWithSetup(TestInlineCOW, TestArraySetup)
{
Array< int > v;
v.PushBack(0);
Array< int > v2 = v;
v2[0] = 1;
v.PushBack(1);
UT_ASSERT(0 == v[0]);
UT_ASSERT(1 == v[1]);
UT_ASSERT(1 == v2[0]);
UT_ASSERT(v.GetSize() == 2);
UT_ASSERT(v2.GetSize() == 1);
}
NitsEndTest
NitsTestWithSetup(TestInlineCOWFromEmptyVector, TestArraySetup)
{
Array< int > v;
int* p = v.GetWritableData();
UT_ASSERT(0 == p);
UT_ASSERT(v.GetSize() == 0);
}
NitsEndTest
// simple type
// alignment
// should be the last test - verifies balance of ctor/dtor
| 19.278592
| 80
| 0.635686
|
Beguiled
|
4a266040bbee1fab1478724187f55db0d23f53f4
| 4,382
|
cpp
|
C++
|
cpp/cpp_typecheck_enum_type.cpp
|
holao09/esbmc
|
659c006a45e9aaf8539b12484e2ec2b093cc6f02
|
[
"BSD-3-Clause"
] | null | null | null |
cpp/cpp_typecheck_enum_type.cpp
|
holao09/esbmc
|
659c006a45e9aaf8539b12484e2ec2b093cc6f02
|
[
"BSD-3-Clause"
] | null | null | null |
cpp/cpp_typecheck_enum_type.cpp
|
holao09/esbmc
|
659c006a45e9aaf8539b12484e2ec2b093cc6f02
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************************************************\
Module: C++ Language Type Checking
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include <i2string.h>
#include <arith_tools.h>
#include <ansi-c/c_qualifiers.h>
#include "cpp_typecheck.h"
#include "cpp_enum_type.h"
/*******************************************************************\
Function: cpp_typecheckt::typecheck_enum_body
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void cpp_typecheckt::typecheck_enum_body(symbolt &enum_symbol)
{
typet &type=enum_symbol.type;
exprt &body=static_cast<exprt &>(type.add("body"));
irept::subt &components=body.get_sub();
typet enum_type("symbol");
enum_type.identifier(enum_symbol.name);
mp_integer i=0;
Forall_irep(it, components)
{
const irep_idt &name=it->name();
if(it->find("value").is_not_nil())
{
exprt &value=static_cast<exprt &>(it->add("value"));
typecheck_expr(value);
make_constant_index(value);
if(to_integer(value, i))
throw "failed to produce integer for enum";
}
exprt final_value("constant", enum_type);
final_value.value(integer2string(i));
symbolt symbol;
symbol.name=id2string(enum_symbol.name)+"::"+id2string(name);
symbol.base_name=name;
symbol.value.swap(final_value);
symbol.location=static_cast<const locationt &>(it->find("#location"));
symbol.mode="C++"; // All types are c++ types
symbol.module=module;
symbol.type=enum_type;
symbol.is_type=false;
symbol.is_macro=true;
symbolt *new_symbol;
if(context.move(symbol, new_symbol))
throw "cpp_typecheckt::typecheck_enum_body: context.move() failed";
cpp_idt &scope_identifier=
cpp_scopes.put_into_scope(*new_symbol);
scope_identifier.id_class=cpp_idt::SYMBOL;
++i;
}
}
/*******************************************************************\
Function: cpp_typecheckt::typecheck_enum_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void cpp_typecheckt::typecheck_enum_type(typet &type)
{
// first save qualifiers
c_qualifierst qualifiers;
qualifiers.read(type);
// these behave like special struct types
// replace by type symbol
cpp_enum_typet &enum_type=to_cpp_enum_type(type);
bool has_body=enum_type.has_body();
std::string base_name=id2string(enum_type.get_name());
bool anonymous=base_name.empty();
bool tag_only_declaration=enum_type.get_tag_only_declaration();
if(anonymous)
base_name="#anon"+i2string(anon_counter++);
cpp_scopet &dest_scope=
tag_scope(base_name, has_body, tag_only_declaration);
const irep_idt symbol_name=
dest_scope.prefix+"tag."+base_name;
// check if we have it
symbolt* previous_symbol = context.find_symbol(symbol_name);
if(previous_symbol != nullptr)
{
// we do!
symbolt &symbol = *previous_symbol;
if(has_body)
{
err_location(type);
str << "error: enum symbol `" << base_name
<< "' declared previously" << std::endl;
str << "location of previous definition: "
<< symbol.location << std::endl;
throw 0;
}
}
else if(has_body)
{
std::string pretty_name=
cpp_scopes.current_scope().prefix+base_name;
symbolt symbol;
symbol.name=symbol_name;
symbol.base_name=base_name;
symbol.value.make_nil();
symbol.location=type.location();
symbol.mode="C++"; // All types are c++ types.
symbol.module=module;
symbol.type.swap(type);
symbol.is_type=true;
symbol.is_macro=false;
symbol.pretty_name=pretty_name;
// move early, must be visible before doing body
symbolt *new_symbol;
if(context.move(symbol, new_symbol))
throw "cpp_typecheckt::typecheck_enum_type: context.move() failed";
// put into scope
cpp_idt &scope_identifier=
cpp_scopes.put_into_scope(*new_symbol);
scope_identifier.id_class=cpp_idt::CLASS;
typecheck_enum_body(*new_symbol);
}
else
{
err_location(type);
str << "use of enum `" << base_name
<< "' without previous declaration";
throw 0;
}
// create type symbol
type=typet("symbol");
type.identifier(symbol_name);
qualifiers.write(type);
}
| 23.945355
| 74
| 0.620949
|
holao09
|
4a27d81860c96ee4d46eaac5afc22be73258a520
| 3,692
|
cpp
|
C++
|
src/gameobject/script.cpp
|
LePtitDev/gamengin
|
f0b2c966a96df5b56eb50fd0fb79eb14a68b859a
|
[
"BSD-3-Clause"
] | null | null | null |
src/gameobject/script.cpp
|
LePtitDev/gamengin
|
f0b2c966a96df5b56eb50fd0fb79eb14a68b859a
|
[
"BSD-3-Clause"
] | null | null | null |
src/gameobject/script.cpp
|
LePtitDev/gamengin
|
f0b2c966a96df5b56eb50fd0fb79eb14a68b859a
|
[
"BSD-3-Clause"
] | null | null | null |
#include "script.h"
#include "gameobject.h"
#include "../assets/assets.h"
ScriptComponent::ScriptComponent(GameObject *parent) :
Component(parent),
started(false)
{
script.loadLibScript();
}
const char * ScriptComponent::getScriptName() const {
return scriptName.c_str();
}
bool ScriptComponent::assign(const char * name) {
Asset * asset = Asset::Find(name);
if (asset == 0 || asset->getData<std::string>() == 0)
return false;
scriptName = name;
script.load(asset->getData<std::string>()->c_str());
LuaScript::Variable vr;
vr.type = LuaScript::VariableType::POINTER;
vr.v_pointer = (void *)&gameObject();
script.createVariable("this", vr);
script.execute();
return true;
}
void ScriptComponent::update() {
if (!started && script.getVariable("start").type == LuaScript::VariableType::FUNCTION)
script.callFunction("start", 0, 0);
started = true;
if (script.getVariable("update").type == LuaScript::VariableType::FUNCTION)
script.callFunction("update", 0, 0);
}
void ScriptComponent::keyPressEvent(QKeyEvent * event) {
if (script.getVariable("keyPress").type == LuaScript::VariableType::FUNCTION) {
LuaScript::Variable key;
key.type = LuaScript::INTEGER;
key.v_integer = event->key();
script.callFunction("keyPress", &key, 1);
}
}
void ScriptComponent::keyReleaseEvent(QKeyEvent * event) {
if (script.getVariable("keyRelease").type == LuaScript::VariableType::FUNCTION) {
LuaScript::Variable key;
key.type = LuaScript::INTEGER;
key.v_integer = event->key();
script.callFunction("keyRelease", &key, 1);
}
}
void ScriptComponent::mousePressEvent(QMouseEvent * event) {
if (script.getVariable("mousePress").type == LuaScript::VariableType::FUNCTION) {
LuaScript::Variable args[3];
args[0].type = LuaScript::INTEGER;
args[0].v_integer = (int)event->button();
args[1].type = LuaScript::INTEGER;
args[1].v_integer = (int)event->x();
args[2].type = LuaScript::INTEGER;
args[2].v_integer = (int)event->y();
script.callFunction("mousePress", args, 3);
}
}
void ScriptComponent::mouseReleaseEvent(QMouseEvent * event) {
if (script.getVariable("mouseRelease").type == LuaScript::VariableType::FUNCTION) {
LuaScript::Variable args[3];
args[0].type = LuaScript::INTEGER;
args[0].v_integer = (int)event->button();
args[1].type = LuaScript::INTEGER;
args[1].v_integer = (int)event->x();
args[2].type = LuaScript::INTEGER;
args[2].v_integer = (int)event->y();
script.callFunction("mouseRelease", args, 3);
}
}
void ScriptComponent::mouseMoveEvent(QMouseEvent * event) {
if (script.getVariable("mouseMove").type == LuaScript::VariableType::FUNCTION) {
LuaScript::Variable args[2];
args[0].type = LuaScript::INTEGER;
args[0].v_integer = (int)event->x();
args[1].type = LuaScript::INTEGER;
args[1].v_integer = (int)event->y();
script.callFunction("mouseMove", args, 2);
}
}
void ScriptComponent::wheelEvent(QWheelEvent * event) {
if (script.getVariable("wheel").type == LuaScript::VariableType::FUNCTION) {
LuaScript::Variable arg;
arg.type = LuaScript::INTEGER;
arg.v_integer = event->delta();
script.callFunction("wheel", &arg, 1);
}
}
void ScriptComponent::destroy() {
removeComponent();
delete this;
}
void ScriptComponent::clone(GameObject * c) {
ScriptComponent * s = c->addComponent<ScriptComponent>();
if (scriptName != "")
s->assign(scriptName.c_str());
}
| 32.964286
| 90
| 0.637866
|
LePtitDev
|
4a289bd2736decc8b8c7543b4098a3ffbf5db92e
| 1,389
|
hpp
|
C++
|
header/FemaleCharacter.hpp
|
digladieux/TP5_SMA
|
450153930410982c79dc79c5694885268fd4a04d
|
[
"Apache-2.0"
] | null | null | null |
header/FemaleCharacter.hpp
|
digladieux/TP5_SMA
|
450153930410982c79dc79c5694885268fd4a04d
|
[
"Apache-2.0"
] | null | null | null |
header/FemaleCharacter.hpp
|
digladieux/TP5_SMA
|
450153930410982c79dc79c5694885268fd4a04d
|
[
"Apache-2.0"
] | null | null | null |
/**
* \file FemaleCharacter.hpp
* \author Gladieux Cunha Dimitri & Gonzales Florian
* \brief Fichier d'en-tete du fichier source FemaleCharacter.cpp
* \date 2018-12-03
*/
#ifndef FEMALE_CHARACTER_HPP
#define FEMALE_CHARACTER_HPP
#include "Character.hpp"
#include "Date.hpp"
/**
* \class FemaleCharacter
* \brief Un personnage feminin herite des attributs et methodes d'un personnage. Le but d'un personnage feminin est de donner naissance a des enfants
*/
class FemaleCharacter : public Character
{
private:
unsigned int baby_per_pregnancy; /*! Nombre de bebe par couche */
Date pregnancy_time; /*! Nombre de mois avant la couche */
unsigned int menopause; /*! Age ou le personnage feminin ne pourra plus faire d'enfant */
public:
FemaleCharacter(const Date &, unsigned int team = 0);
FemaleCharacter(const Date &, unsigned int, unsigned int, unsigned int team = 0, unsigned int life = 200);
FemaleCharacter(const FemaleCharacter &);
~FemaleCharacter();
FemaleCharacter &operator=(const FemaleCharacter &) ;
unsigned int getBabyPerPregnancy() const noexcept;
Date getPregnancyTime() const noexcept;
void randomBabyPerPregnancy() noexcept;
void setTimePregnancy(const Date &date) noexcept;
unsigned int getMonthPregnancy(const Date &) const;
unsigned int getMenopause() const noexcept;
};
#endif
| 33.071429
| 151
| 0.726422
|
digladieux
|
4a2bb6a43126d867175c93d1ee451c82a38743a7
| 17,490
|
cpp
|
C++
|
src/pola/scene/mesh/MD2MeshLoader.cpp
|
lij0511/pandora
|
5988618f29d2f1ba418ef54a02e227903c1e7108
|
[
"Apache-2.0"
] | null | null | null |
src/pola/scene/mesh/MD2MeshLoader.cpp
|
lij0511/pandora
|
5988618f29d2f1ba418ef54a02e227903c1e7108
|
[
"Apache-2.0"
] | null | null | null |
src/pola/scene/mesh/MD2MeshLoader.cpp
|
lij0511/pandora
|
5988618f29d2f1ba418ef54a02e227903c1e7108
|
[
"Apache-2.0"
] | null | null | null |
/*
* MD2MeshLoader.cpp
*
* Created on: 2016年5月21日
* Author: lijing
*/
#include <stdint.h>
//#define USE_MD2_MESH
#include "pola/log/Log.h"
#include "pola/scene/mesh/MD2MeshLoader.h"
#include "pola/scene/mesh/Mesh.h"
#ifdef USE_MD2_MESH
#include "pola/scene/mesh/MD2AnimatedMesh.h"
#endif
#include <string.h>
namespace pola {
namespace scene {
const int32_t MD2_MAGIC_NUMBER = 844121161;
const int32_t MD2_VERSION = 8;
const int32_t MD2_MAX_VERTS = 2048;
const int32_t Q2_VERTEX_NORMAL_TABLE_SIZE = 162;
static const float Q2_VERTEX_NORMAL_TABLE[Q2_VERTEX_NORMAL_TABLE_SIZE][3] = {
{-0.525731f, 0.000000f, 0.850651f},
{-0.442863f, 0.238856f, 0.864188f},
{-0.295242f, 0.000000f, 0.955423f},
{-0.309017f, 0.500000f, 0.809017f},
{-0.162460f, 0.262866f, 0.951056f},
{0.000000f, 0.000000f, 1.000000f},
{0.000000f, 0.850651f, 0.525731f},
{-0.147621f, 0.716567f, 0.681718f},
{0.147621f, 0.716567f, 0.681718f},
{0.000000f, 0.525731f, 0.850651f},
{0.309017f, 0.500000f, 0.809017f},
{0.525731f, 0.000000f, 0.850651f},
{0.295242f, 0.000000f, 0.955423f},
{0.442863f, 0.238856f, 0.864188f},
{0.162460f, 0.262866f, 0.951056f},
{-0.681718f, 0.147621f, 0.716567f},
{-0.809017f, 0.309017f, 0.500000f},
{-0.587785f, 0.425325f, 0.688191f},
{-0.850651f, 0.525731f, 0.000000f},
{-0.864188f, 0.442863f, 0.238856f},
{-0.716567f, 0.681718f, 0.147621f},
{-0.688191f, 0.587785f, 0.425325f},
{-0.500000f, 0.809017f, 0.309017f},
{-0.238856f, 0.864188f, 0.442863f},
{-0.425325f, 0.688191f, 0.587785f},
{-0.716567f, 0.681718f, -0.147621f},
{-0.500000f, 0.809017f, -0.309017f},
{-0.525731f, 0.850651f, 0.000000f},
{0.000000f, 0.850651f, -0.525731f},
{-0.238856f, 0.864188f, -0.442863f},
{0.000000f, 0.955423f, -0.295242f},
{-0.262866f, 0.951056f, -0.162460f},
{0.000000f, 1.000000f, 0.000000f},
{0.000000f, 0.955423f, 0.295242f},
{-0.262866f, 0.951056f, 0.162460f},
{0.238856f, 0.864188f, 0.442863f},
{0.262866f, 0.951056f, 0.162460f},
{0.500000f, 0.809017f, 0.309017f},
{0.238856f, 0.864188f, -0.442863f},
{0.262866f, 0.951056f, -0.162460f},
{0.500000f, 0.809017f, -0.309017f},
{0.850651f, 0.525731f, 0.000000f},
{0.716567f, 0.681718f, 0.147621f},
{0.716567f, 0.681718f, -0.147621f},
{0.525731f, 0.850651f, 0.000000f},
{0.425325f, 0.688191f, 0.587785f},
{0.864188f, 0.442863f, 0.238856f},
{0.688191f, 0.587785f, 0.425325f},
{0.809017f, 0.309017f, 0.500000f},
{0.681718f, 0.147621f, 0.716567f},
{0.587785f, 0.425325f, 0.688191f},
{0.955423f, 0.295242f, 0.000000f},
{1.000000f, 0.000000f, 0.000000f},
{0.951056f, 0.162460f, 0.262866f},
{0.850651f, -0.525731f, 0.000000f},
{0.955423f, -0.295242f, 0.000000f},
{0.864188f, -0.442863f, 0.238856f},
{0.951056f, -0.162460f, 0.262866f},
{0.809017f, -0.309017f, 0.500000f},
{0.681718f, -0.147621f, 0.716567f},
{0.850651f, 0.000000f, 0.525731f},
{0.864188f, 0.442863f, -0.238856f},
{0.809017f, 0.309017f, -0.500000f},
{0.951056f, 0.162460f, -0.262866f},
{0.525731f, 0.000000f, -0.850651f},
{0.681718f, 0.147621f, -0.716567f},
{0.681718f, -0.147621f, -0.716567f},
{0.850651f, 0.000000f, -0.525731f},
{0.809017f, -0.309017f, -0.500000f},
{0.864188f, -0.442863f, -0.238856f},
{0.951056f, -0.162460f, -0.262866f},
{0.147621f, 0.716567f, -0.681718f},
{0.309017f, 0.500000f, -0.809017f},
{0.425325f, 0.688191f, -0.587785f},
{0.442863f, 0.238856f, -0.864188f},
{0.587785f, 0.425325f, -0.688191f},
{0.688191f, 0.587785f, -0.425325f},
{-0.147621f, 0.716567f, -0.681718f},
{-0.309017f, 0.500000f, -0.809017f},
{0.000000f, 0.525731f, -0.850651f},
{-0.525731f, 0.000000f, -0.850651f},
{-0.442863f, 0.238856f, -0.864188f},
{-0.295242f, 0.000000f, -0.955423f},
{-0.162460f, 0.262866f, -0.951056f},
{0.000000f, 0.000000f, -1.000000f},
{0.295242f, 0.000000f, -0.955423f},
{0.162460f, 0.262866f, -0.951056f},
{-0.442863f, -0.238856f, -0.864188f},
{-0.309017f, -0.500000f, -0.809017f},
{-0.162460f, -0.262866f, -0.951056f},
{0.000000f, -0.850651f, -0.525731f},
{-0.147621f, -0.716567f, -0.681718f},
{0.147621f, -0.716567f, -0.681718f},
{0.000000f, -0.525731f, -0.850651f},
{0.309017f, -0.500000f, -0.809017f},
{0.442863f, -0.238856f, -0.864188f},
{0.162460f, -0.262866f, -0.951056f},
{0.238856f, -0.864188f, -0.442863f},
{0.500000f, -0.809017f, -0.309017f},
{0.425325f, -0.688191f, -0.587785f},
{0.716567f, -0.681718f, -0.147621f},
{0.688191f, -0.587785f, -0.425325f},
{0.587785f, -0.425325f, -0.688191f},
{0.000000f, -0.955423f, -0.295242f},
{0.000000f, -1.000000f, 0.000000f},
{0.262866f, -0.951056f, -0.162460f},
{0.000000f, -0.850651f, 0.525731f},
{0.000000f, -0.955423f, 0.295242f},
{0.238856f, -0.864188f, 0.442863f},
{0.262866f, -0.951056f, 0.162460f},
{0.500000f, -0.809017f, 0.309017f},
{0.716567f, -0.681718f, 0.147621f},
{0.525731f, -0.850651f, 0.000000f},
{-0.238856f, -0.864188f, -0.442863f},
{-0.500000f, -0.809017f, -0.309017f},
{-0.262866f, -0.951056f, -0.162460f},
{-0.850651f, -0.525731f, 0.000000f},
{-0.716567f, -0.681718f, -0.147621f},
{-0.716567f, -0.681718f, 0.147621f},
{-0.525731f, -0.850651f, 0.000000f},
{-0.500000f, -0.809017f, 0.309017f},
{-0.238856f, -0.864188f, 0.442863f},
{-0.262866f, -0.951056f, 0.162460f},
{-0.864188f, -0.442863f, 0.238856f},
{-0.809017f, -0.309017f, 0.500000f},
{-0.688191f, -0.587785f, 0.425325f},
{-0.681718f, -0.147621f, 0.716567f},
{-0.442863f, -0.238856f, 0.864188f},
{-0.587785f, -0.425325f, 0.688191f},
{-0.309017f, -0.500000f, 0.809017f},
{-0.147621f, -0.716567f, 0.681718f},
{-0.425325f, -0.688191f, 0.587785f},
{-0.162460f, -0.262866f, 0.951056f},
{0.442863f, -0.238856f, 0.864188f},
{0.162460f, -0.262866f, 0.951056f},
{0.309017f, -0.500000f, 0.809017f},
{0.147621f, -0.716567f, 0.681718f},
{0.000000f, -0.525731f, 0.850651f},
{0.425325f, -0.688191f, 0.587785f},
{0.587785f, -0.425325f, 0.688191f},
{0.688191f, -0.587785f, 0.425325f},
{-0.955423f, 0.295242f, 0.000000f},
{-0.951056f, 0.162460f, 0.262866f},
{-1.000000f, 0.000000f, 0.000000f},
{-0.850651f, 0.000000f, 0.525731f},
{-0.955423f, -0.295242f, 0.000000f},
{-0.951056f, -0.162460f, 0.262866f},
{-0.864188f, 0.442863f, -0.238856f},
{-0.951056f, 0.162460f, -0.262866f},
{-0.809017f, 0.309017f, -0.500000f},
{-0.864188f, -0.442863f, -0.238856f},
{-0.951056f, -0.162460f, -0.262866f},
{-0.809017f, -0.309017f, -0.500000f},
{-0.681718f, 0.147621f, -0.716567f},
{-0.681718f, -0.147621f, -0.716567f},
{-0.850651f, 0.000000f, -0.525731f},
{-0.688191f, 0.587785f, -0.425325f},
{-0.587785f, 0.425325f, -0.688191f},
{-0.425325f, 0.688191f, -0.587785f},
{-0.425325f, -0.688191f, -0.587785f},
{-0.587785f, -0.425325f, -0.688191f},
{-0.688191f, -0.587785f, -0.425325f},
};
struct MD2AnimationType {
int32_t begin;
int32_t end;
int32_t fps;
std::string name;
};
const int32_t MD2_ANIMATION_TYPE_LIST_SIZE = 21;
static const MD2AnimationType MD2AnimationTypeList[MD2_ANIMATION_TYPE_LIST_SIZE] = {
{ 0, 39, 9, "STAND"}, // STAND
{ 40, 45, 10, "RUN"}, // RUN
{ 46, 53, 10, "ATTACK"}, // ATTACK
{ 54, 57, 7, "PAIN_A"}, // PAIN_A
{ 58, 61, 7, "PAIN_B"}, // PAIN_B
{ 62, 65, 7, "PAIN_C"}, // PAIN_C
{ 66, 71, 7, "JUMP"}, // JUMP
{ 72, 83, 7, "FLIP"}, // FLIP
{ 84, 94, 7, "SALUTE"}, // SALUTE
{ 95, 111, 10, "FALLBACK"}, // FALLBACK
{112, 122, 7, "WAVE"}, // WAVE
{123, 134, 6, "POINT"}, // POINT
{135, 153, 10, "CROUCH_STAND"}, // CROUCH_STAND
{154, 159, 7, "CROUCH_WALK"}, // CROUCH_WALK
{160, 168, 10, "CROUCH_ATTACK"}, // CROUCH_ATTACK
{169, 172, 7, "CROUCH_PAIN"}, // CROUCH_PAIN
{173, 177, 5, "CROUCH_DEATH"}, // CROUCH_DEATH
{178, 183, 7, "DEATH_FALLBACK"}, // DEATH_FALLBACK
{184, 189, 7, "DEATH_FALLFORWARD"}, // DEATH_FALLFORWARD
{190, 197, 7, "DEATH_FALLBACKSLOW"}, // DEATH_FALLBACKSLOW
{198, 198, 5, "BOOM"}, // BOOM
};
#include "pola/utils/spack.h"
struct MD2Header {
int32_t magic; // four character code "IDP2"
int32_t version; // must be 8
int32_t skinWidth; // width of the texture
int32_t skinHeight; // height of the texture
int32_t frameSize; // size in bytes of an animation frame
int32_t numSkins; // number of textures
int32_t numVertices; // total number of vertices
int32_t numTexcoords; // number of vertices with texture coords
int32_t numTriangles; // number of triangles
int32_t numGlCommands; // number of opengl commands (triangle strip or triangle fan)
int32_t numFrames; // animation keyframe count
int32_t offsetSkins; // offset in bytes to 64 character skin names
int32_t offsetTexcoords; // offset in bytes to texture coordinate list
int32_t offsetTriangles; // offset in bytes to triangle list
int32_t offsetFrames; // offset in bytes to frame list
int32_t offsetGlCommands;// offset in bytes to opengl commands
int32_t offsetEnd; // offset in bytes to end of file
} PACK_STRUCT;
struct MD2Vertex {
uint8_t vertex[3]; // [0] = X, [1] = Z, [2] = Y
uint8_t lightNormalIndex; // index in the normal table
} PACK_STRUCT;
struct MD2Frame {
float scale[3]; // first scale the vertex position
float translate[3]; // then translate the position
char name[16]; // the name of the animation that this key belongs to
MD2Vertex vertices[1]; // vertex 1 of SMD2Header.numVertices
} PACK_STRUCT;
struct MD2Triangle {
uint16_t vertexIndices[3];
uint16_t textureIndices[3];
} PACK_STRUCT;
struct MD2TextureCoordinate {
int16_t s;
int16_t t;
} PACK_STRUCT;
#include "pola/utils/sunpack.h"
MD2MeshLoader::MD2MeshLoader() {
}
MD2MeshLoader::~MD2MeshLoader() {
}
bool MD2MeshLoader::available(io::InputStream* is) {
MD2Header header;
is->read(&header, sizeof(MD2Header));
bool accept = true;
if (header.magic != MD2_MAGIC_NUMBER || header.version != MD2_VERSION) {
LOGE("MD2 Loader: Wrong file header\n");
accept = false;
}
return accept;
}
pola::utils::sp<MeshLoader::MeshInfo> MD2MeshLoader::doLoadMesh(io::InputStream* is) {
#if !defined(USE_MD2_MESH)
MD2Header header;
is->read(&header, sizeof(MD2Header));
if (header.magic != MD2_MAGIC_NUMBER || header.version != MD2_VERSION) {
LOGE("MD2 Loader: Wrong file header\n");
return nullptr;
}
// read Triangles
is->seek(header.offsetTriangles);
MD2Triangle *triangles = new MD2Triangle[header.numTriangles];
if (!is->read(triangles, header.numTriangles *sizeof(MD2Triangle)))
{
delete[] triangles;
LOGE("MD2 Loader: Error reading triangles.");
return nullptr;
}
// read Vertices
uint8_t buffer[MD2_MAX_VERTS*4+128];
MD2Frame* frame = (MD2Frame*)buffer;
is->seek(header.offsetFrames);
Mesh* mesh = new Mesh;
graphic::Geometry3D* geometry = (graphic::Geometry3D*) mesh->geometry();
geometry->alloc(header.numTriangles * 3, FLAG_GEOMETRY_DEFAULT | FLAG_GEOMETRY_NORMAL | FLAG_GEOMETRY_UV);
const int16_t count = header.numTriangles * 3;
for (int16_t i = 0; i < count; i += 3) {
geometry->addIndex((uint16_t) i);
geometry->addIndex((uint16_t) i + 1);
geometry->addIndex((uint16_t) i + 2);
}
Animations* animations = new Animations;
mesh->setAnimations(animations);
is->seek(header.offsetFrames);
graphic::Box3 boundingBox;
int32_t frameIndex = 0;
for (int32_t animationIndex = 0; animationIndex < MD2_ANIMATION_TYPE_LIST_SIZE; animationIndex ++) {
if (frameIndex >= header.numFrames) {
break;
}
MD2AnimationType animationType = MD2AnimationTypeList[animationIndex];
FrameAnimation* animation = new FrameAnimation(animationType.name);
animations->addAnimation(animation);
float frameTime = 1.f / animationType.fps;
for (frameIndex = animationType.begin; frameIndex <= animationType.end; frameIndex ++) {
if (frameIndex >= header.numFrames) {
break;
}
is->read(frame, header.frameSize);
LOGD("FrameName=%s", frame->name);
// add vertices
FrameAnimation::KeyFrameData& frameData = animation->addKeyFrame(frameTime);
frameData.positions.resize(header.numTriangles * 3);
frameData.normals.resize(header.numTriangles * 3);
graphic::vec3* positions = frameData.positions.data();
graphic::vec3* normals = frameData.normals.data();
for (int32_t j = 0; j < header.numTriangles; ++j) {
for (int32_t ti = 0; ti < 3; ++ti) {
uint32_t num = triangles[j].vertexIndices[ti];
float x = frame->vertices[num].vertex[0];
x = x * frame->scale[0] + frame->translate[0];
float y = frame->vertices[num].vertex[1];
y = y * frame->scale[1] + frame->translate[1];
float z = frame->vertices[num].vertex[2];
z = z * frame->scale[2] + frame->translate[2];
positions[0] = {x, z, y};
boundingBox.expandByPoint(positions[0]);
positions ++;
float nx = Q2_VERTEX_NORMAL_TABLE[frame->vertices[num].lightNormalIndex][0];
float ny = Q2_VERTEX_NORMAL_TABLE[frame->vertices[num].lightNormalIndex][1];
float nz = Q2_VERTEX_NORMAL_TABLE[frame->vertices[num].lightNormalIndex][2];
normals[0] = {nx, nz, ny};
normals ++;
}
}
if (frameIndex == 0) {
memcpy(geometry->positions(), frameData.positions.data(), sizeof(graphic::vec3) * header.numTriangles * 3);
memcpy(geometry->normals(), frameData.normals.data(), sizeof(graphic::vec3) * header.numTriangles * 3);
}
}
}
geometry->setBoundingBox(boundingBox);
is->seek(header.offsetTexcoords);
MD2TextureCoordinate* textureCoords = new MD2TextureCoordinate[header.numTexcoords];
is->read(textureCoords, sizeof(MD2TextureCoordinate)*header.numTexcoords);
if (header.numFrames > 0) {
float dmaxs = 1.0f / (header.skinWidth);
float dmaxt = 1.0f / (header.skinHeight);
graphic::vec2* uvs = geometry->uvs();;
for (int32_t t = 0; t < header.numTriangles; ++t) {
for (int32_t n = 0; n < 3; ++n) {
int32_t index = t * 3 + n;
uvs[index] = {(textureCoords[triangles[t].textureIndices[n]].s + 0.5f) * dmaxs, (textureCoords[triangles[t].textureIndices[n]].t + 0.5f) * dmaxt};
}
}
}
delete[] triangles;
delete[] textureCoords;
pola::utils::sp<MeshLoader::MeshInfo> result = new MeshInfo;
result->mesh = mesh;
return result;
#else
MD2Header header;
is->read(&header, sizeof(MD2Header));
if (header.magic != MD2_MAGIC_NUMBER || header.version != MD2_VERSION) {
LOGE("MD2 Loader: Wrong file header\n");
return nullptr;
}
// read Triangles
is->seek(header.offsetTriangles);
MD2Triangle *triangles = new MD2Triangle[header.numTriangles];
if (!is->read(triangles, header.numTriangles *sizeof(MD2Triangle)))
{
delete[] triangles;
LOGE("MD2 Loader: Error reading triangles.");
return nullptr;
}
// read Vertices
uint8_t buffer[MD2_MAX_VERTS*4+128];
MD2Frame* frame = (MD2Frame*)buffer;
is->seek(header.offsetFrames);
MD2AnimatedMesh* mesh = new MD2AnimatedMesh;
graphic::Geometry3D* geometry = (graphic::Geometry3D*) mesh->geometry();
geometry->alloc(header.numTriangles * 3, FLAG_GEOMETRY_DEFAULT | FLAG_GEOMETRY_NORMAL | FLAG_GEOMETRY_UV);
const int16_t count = header.numTriangles * 3;
for (int16_t i = 0; i < count; i += 3) {
geometry->addIndex((uint16_t) i);
geometry->addIndex((uint16_t) i + 1);
geometry->addIndex((uint16_t) i + 2);
}
mesh->frameTransforms.resize(header.numFrames);
mesh->frameList.resize(header.numFrames);
mesh->setFrameCount(header.numFrames);
is->seek(header.offsetFrames);
for (int32_t i = 0; i < header.numFrames; ++i) {
is->read(frame, header.frameSize);
LOGD("FrameName=%s", frame->name);
// save keyframe scale and translation
FrameTransform* frameTransforms = mesh->frameTransforms.data();
frameTransforms[i].scale[0] = frame->scale[0];
frameTransforms[i].scale[2] = frame->scale[1];
frameTransforms[i].scale[1] = frame->scale[2];
frameTransforms[i].translate[0] = frame->translate[0];
frameTransforms[i].translate[2] = frame->translate[1];
frameTransforms[i].translate[1] = frame->translate[2];
graphic::Box3 boundingBox;
mesh->frameList[i].resize(header.numTriangles * 3);
FrameItem* frameItems = mesh->frameList[i].data();
// add vertices
for (int32_t j = 0; j < header.numTriangles; ++j) {
for (int32_t ti = 0; ti < 3; ++ti) {
FrameItem v;
uint32_t num = triangles[j].vertexIndices[ti];
v.pos[0] = frame->vertices[num].vertex[0];
v.pos[2] = frame->vertices[num].vertex[1];
v.pos[1] = frame->vertices[num].vertex[2];
v.normal_index = frame->vertices[num].lightNormalIndex;
*(frameItems++) = v;
boundingBox.expandByPoint({v.pos[0] * frameTransforms[i].scale[0] + frameTransforms[i].translate[0],
v.pos[1] * frameTransforms[i].scale[0] + frameTransforms[i].translate[0],
v.pos[2] * frameTransforms[i].scale[0] + frameTransforms[i].translate[0]});
}
}
geometry->setBoundingBox(boundingBox);
}
is->seek(header.offsetTexcoords);
MD2TextureCoordinate* textureCoords = new MD2TextureCoordinate[header.numTexcoords];
is->read(textureCoords, sizeof(MD2TextureCoordinate)*header.numTexcoords);
if (header.numFrames > 0) {
float dmaxs = 1.0f / (header.skinWidth);
float dmaxt = 1.0f / (header.skinHeight);
graphic::vec2* uvs = geometry->uvs();;
for (int32_t t = 0; t < header.numTriangles; ++t) {
for (int32_t n = 0; n < 3; ++n) {
int32_t index = t * 3 + n;
uvs[index] = {(textureCoords[triangles[t].textureIndices[n]].s + 0.5f) * dmaxs, (textureCoords[triangles[t].textureIndices[n]].t + 0.5f) * dmaxt};
}
}
}
delete[] triangles;
delete[] textureCoords;
pola::utils::sp<MeshLoader::MeshInfo> result = new MeshInfo;
result->mesh = mesh;
return result;
#endif
}
} /* namespace scene */
} /* namespace pola */
| 34.702381
| 150
| 0.671755
|
lij0511
|
4a2f142e7fedc3ecb35677a84f21e77c4584a8bf
| 6,418
|
cpp
|
C++
|
main.cpp
|
SebMenozzi/NN
|
d9a5bd1a13cc4112711ad0483a6b9b94de80de46
|
[
"MIT"
] | null | null | null |
main.cpp
|
SebMenozzi/NN
|
d9a5bd1a13cc4112711ad0483a6b9b94de80de46
|
[
"MIT"
] | null | null | null |
main.cpp
|
SebMenozzi/NN
|
d9a5bd1a13cc4112711ad0483a6b9b94de80de46
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <math.h>
#include "matrix.h"
#include "NN.h"
// nombre de neurones en hidden layer
#define nb_neurons_hidden_layer 3
// nombre d'itération
#define epoch 2000
// capacité d'apprentissage
#define learning_rate 0.7
// GLOBAL
// donnée entrante d'input pour XOR
const int training_data[4][2] = {
{ 1, 0 }, // 1 XOR 1 = 1
{ 1, 1 }, // 0
{ 0, 1 }, // 1
{ 0, 0 } // 0
};
// résultat attendu
const int answer_data[4] = { 1, 0, 1, 0 };
// objectif
int target;
Matrix input_to_hidden_weights(nb_neurons_hidden_layer, 2);
Matrix input_to_hidden_bias(nb_neurons_hidden_layer, 1);
Matrix input_layer(2, 1);
Matrix hidden_to_output_weights(1, nb_neurons_hidden_layer);
Matrix hidden_to_output_bias(1, 1);
Matrix hidden_layer(nb_neurons_hidden_layer, 1);
Matrix output_layer(1, 1);
float error_rate; // for debug
// UTILS
// donne un float entre -1 et 1
double random_between_neg_1_pos_1() {
int randNumber = rand() % 2; // 0 or 1
double result = rand() / (RAND_MAX + 1.0); // between 0 and 1
return (randNumber == 1) ? result : -1 * result;
}
// met des poids aléatoires de input vers hidden layer
void generate_random_input_to_hidden_weights() {
for (size_t row = 0; row < nb_neurons_hidden_layer; row++) {
for (size_t column = 0; column < 2; column++)
{
input_to_hidden_weights.setValue(row, column, random_between_neg_1_pos_1());
}
}
}
// met des poids aléatoires de hidden vers output layer
void generate_random_hidden_to_output_weights() {
for (size_t row = 0; row < nb_neurons_hidden_layer; row++)
{
hidden_to_output_weights.setValue(0, row, random_between_neg_1_pos_1());
}
}
// activation function
float sigmoid(float x)
{
return 1.0 / (1.0 + exp(-x));
}
// derivative of activation function
float sigmoid_prime(float x)
{
return x * (1.0 - x);
}
// applique la fonction sigmoide pour chaque case d'une matrice
Matrix applySigmoid(Matrix a) {
for (size_t column = 0; column < a.getHeight(); column++) {
for (size_t row = 0; row < a.getWidth(); row++) {
a.setValue(column, row, sigmoid(a.getValue(column, row)));
}
}
return a;
}
// FORWARD PROPAGATION
void forward_propagate() {
hidden_layer = applySigmoid(input_to_hidden_weights * input_layer + input_to_hidden_bias);
output_layer = applySigmoid(hidden_to_output_weights * hidden_layer + hidden_to_output_bias);
}
// BACKWARD PROPAGATION
void back_propagate() {
float error = output_layer.getValue(0, 0) - target;
error_rate = pow(error, 2);
for (int row = 0; row < nb_neurons_hidden_layer; row++) {
for (int column = 0; column < 2; column++) {
float deltaw1 = error *
sigmoid_prime(output_layer.getValue(0, 0)) *
hidden_to_output_weights.getValue(0, row) *
sigmoid_prime(hidden_layer.getValue(row, 0)) *
input_layer.getValue(column, 0);
// new input weights
float new_input_to_hidden_weights = input_to_hidden_weights.getValue(row, column) - deltaw1 * learning_rate;
input_to_hidden_weights.setValue(row, column, new_input_to_hidden_weights);
}
float deltaw2 = error *
sigmoid_prime(output_layer.getValue(0, 0)) *
hidden_layer.getValue(row, 0);
// new hidden weights
float new_hidden_to_output_weights = hidden_to_output_weights.getValue(0, row) - deltaw2 * learning_rate;
hidden_to_output_weights.setValue(0, row, new_hidden_to_output_weights);
float deltab1 = error *
sigmoid_prime(output_layer.getValue(0, 0)) *
hidden_to_output_weights.getValue(0, row) *
sigmoid_prime(hidden_layer.getValue(row, 0));
// new input bias
float new_input_to_hidden_bias = input_to_hidden_bias.getValue(row, 0) - deltab1 * learning_rate;
input_to_hidden_bias.setValue(row, 0, new_input_to_hidden_bias);
float deltab2 = error *
sigmoid_prime(output_layer.getValue(0, 0));
// new hidden bias
float new_hidden_to_output_bias = hidden_to_output_bias.getValue(0, 0) - deltab2 * learning_rate;
hidden_to_output_bias.setValue(0, 0, new_hidden_to_output_bias);
}
}
void display_result() {
std::cout << "(" << input_layer.getValue(0, 0) << ", " << input_layer.getValue(1, 0) << ") : expected: " << target << " (error:" << output_layer.getValue(0, 0) << ")" << std::endl;
}
int main() {
/* generate_random_input_to_hidden_weights();
generate_random_hidden_to_output_weights();
// pour chaque itération (2000)
for (int i = 0; i < epoch; i++) {
// pour chaque données à apprendre ( (0, 0) , (1, 0) , (0, 1) , (1, 1) pour XOR)
for (int inputs = 0; inputs < 4; inputs++) {
// on initialize le premier neurone de input layer
input_layer.setValue(0, 0, training_data[inputs][0]);
// on initialize le second neurone de input layer
input_layer.setValue(1, 0, training_data[inputs][1]);
// on initialize la valeur target correspond au résulat attendu par rapport aux neurones de input layer (0 ou 1 pour XOR)
target = answer_data[inputs];
forward_propagate();
back_propagate();
display_result();
}
}*/
(void) training_data;
(void) answer_data;
// TEST
input_layer.setValue(0, 0, 0.01); // Entree 1
input_layer.setValue(1, 0, 0.99); // Entree 2
// Calcule
forward_propagate();
// Affichage
std::cout << "Sortie : " << output_layer.getValue(0, 0) << std::endl;
// Calcule
forward_propagate();
// Affichage
std::cout << "Sortie : " << output_layer.getValue(0, 0) << std::endl;
// Voici comment j'aimerais l'utiliser après apprentissage
std::vector<size_t> nbNeurones;
nbNeurones.push_back(2); // Inputs
nbNeurones.push_back(3); // First hidden layer
nbNeurones.push_back(1); // Output
NN nn(nbNeurones);
std::vector<float> inputs;
inputs.push_back(0.01); // Input 0
inputs.push_back(0.99); // Input 1
nn.setInputs(inputs);
std::vector<float> outputs = nn.getOutputs();
std::cout << "output : " << outputs[0] << std::endl;
return 0;
}
| 33.778947
| 184
| 0.636179
|
SebMenozzi
|
4a303890d6bfe4bcb7ea0879e59e2fff4af81c00
| 673
|
cpp
|
C++
|
Array6/Array6/Source.cpp
|
DipeshKazi/C-Repository
|
b58f26a1bdb2a159b3a1d025fea2f0d4b2d70823
|
[
"MIT"
] | null | null | null |
Array6/Array6/Source.cpp
|
DipeshKazi/C-Repository
|
b58f26a1bdb2a159b3a1d025fea2f0d4b2d70823
|
[
"MIT"
] | null | null | null |
Array6/Array6/Source.cpp
|
DipeshKazi/C-Repository
|
b58f26a1bdb2a159b3a1d025fea2f0d4b2d70823
|
[
"MIT"
] | null | null | null |
#include <iostream>
int addition[] = { 23, 6, 47, 35, 2, 14 };
int n, result = 0;
int high = 0;
int odd = 0;
int even = 0;
int main() {
//Avarage
int average = 0.0;
for (n = 0; n < 6; ++n)
{
result = addition[n] + result;
average = result / 6;
}
std::cout << "Average of Number "<< average << std::endl;
//Highest Number
for (n = 0; n < 6; ++n)
{
if (addition[n] >high)
high = addition[n];
}
std::cout << " Highest Number " << high << std::endl;
//Odd Number
for (n = 0; n < 6; ++n)
{
if (even != addition[n] % 2)
odd = addition[n];
std::cout << " odd Number " << odd << std::endl;
}
system("pause");
return 0;
}
| 12.942308
| 58
| 0.511144
|
DipeshKazi
|
4a333d1023d1ad880c887a985d7a962128604a34
| 2,102
|
hpp
|
C++
|
DFNs/Executors/StereoReconstruction/StereoReconstructionExecutor.hpp
|
H2020-InFuse/cdff
|
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
|
[
"BSD-2-Clause"
] | 7
|
2019-02-26T15:09:50.000Z
|
2021-09-30T07:39:01.000Z
|
DFNs/Executors/StereoReconstruction/StereoReconstructionExecutor.hpp
|
H2020-InFuse/cdff
|
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
|
[
"BSD-2-Clause"
] | null | null | null |
DFNs/Executors/StereoReconstruction/StereoReconstructionExecutor.hpp
|
H2020-InFuse/cdff
|
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
|
[
"BSD-2-Clause"
] | 1
|
2020-12-06T12:09:05.000Z
|
2020-12-06T12:09:05.000Z
|
/**
* @addtogroup DFNs
* @{
*/
#ifndef STEREORECONSTRUCTION_EXECUTOR_HPP
#define STEREORECONSTRUCTION_EXECUTOR_HPP
#include "DFNCommonInterface.hpp"
#include <StereoReconstruction/StereoReconstructionInterface.hpp>
#include <Types/CPP/PointCloud.hpp>
#include <Types/CPP/Frame.hpp>
namespace CDFF
{
namespace DFN
{
namespace Executors
{
/**
* All the methods in this class execute the DFN for the computation of a point cloud for a pair of stereo images.
* A DFN instance has to be passed in the constructor of these class. Each method takes the following parameters:
* @param leftInputFrame: left camera image;
* @param rightInputFrame: right camera image;
* @param outputCloud: output point cloud.
*
* The main difference between the four methods are input and output types:
* Methods (i) and (ii) have the constant pointer as input, Methods (iii) and (iv) have a constant reference as input;
* Methods (i) and (iii) are non-creation methods, they give constant pointers as output, the output is just the output reference in the DFN;
* When using creation methods, the output has to be initialized to NULL.
* Methods (ii) and (iv) are creation methods, they copy the output of the DFN in the referenced output variable. Method (ii) takes a pointer, method (iv) takes a reference.
*/
void Execute(StereoReconstructionInterface* dfn, FrameWrapper::FrameConstPtr leftInputFrame, FrameWrapper::FrameConstPtr rightInputFrame,
PointCloudWrapper::PointCloudConstPtr& outputCloud);
void Execute(StereoReconstructionInterface* dfn, FrameWrapper::FrameConstPtr inputFrame, FrameWrapper::FrameConstPtr rightInputFrame,
PointCloudWrapper::PointCloudPtr outputCloud);
void Execute(StereoReconstructionInterface* dfn, const FrameWrapper::Frame& leftInputFrame, const FrameWrapper::Frame& rightInputFrame,
PointCloudWrapper::PointCloudConstPtr& outputCloud);
void Execute(StereoReconstructionInterface* dfn, const FrameWrapper::Frame& leftInputFrame, const FrameWrapper::Frame& rightInputFrame,
PointCloudWrapper::PointCloud& outputCloud);
}
}
}
#endif // STEREORECONSTRUCTION_EXECUTOR_HPP
/** @} */
| 42.04
| 172
| 0.797336
|
H2020-InFuse
|
4a3420319bbb2383e61ff1c277b92243071423dc
| 9,890
|
cpp
|
C++
|
src/ukf.cpp
|
grygoryant/CarND-Unscented-Kalman-Filter-Project
|
c0519637544de1d31ff02712be632e622d66ef34
|
[
"MIT"
] | null | null | null |
src/ukf.cpp
|
grygoryant/CarND-Unscented-Kalman-Filter-Project
|
c0519637544de1d31ff02712be632e622d66ef34
|
[
"MIT"
] | null | null | null |
src/ukf.cpp
|
grygoryant/CarND-Unscented-Kalman-Filter-Project
|
c0519637544de1d31ff02712be632e622d66ef34
|
[
"MIT"
] | null | null | null |
#include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
/**
* Initializes Unscented Kalman filter
* This is scaffolding, do not modify
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
n_x_ = 5;
n_aug_ = n_x_ + 2;
lambda_ = 3 - n_aug_;
n_z_radar_ = 3;
n_z_laser_ = 2;
// initial state vector
x_ = eig_vec(n_x_);
// initial covariance matrix
P_ = eig_mat::Identity(n_x_, n_x_);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 2;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 0.3;
//DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer.
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
//DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer.
Xsig_pred_ = eig_mat(n_x_, 2 * n_aug_ + 1);
weights_ = eig_vec(2 * n_aug_ + 1);
weights_(0) = lambda_/(lambda_ + n_aug_);
for(int i = 1; i < 2 * n_aug_ + 1; ++i)
{
weights_(i) = 1/(2 * (lambda_ + n_aug_));
}
R_laser_ = eig_mat(n_z_laser_, n_z_laser_);
R_laser_ << std_laspx_*std_laspx_, 0,
0, std_laspy_*std_laspy_;
R_radar_ = eig_mat(n_z_radar_, n_z_radar_);
R_radar_ << std_radr_*std_radr_, 0, 0,
0, std_radphi_*std_radphi_, 0,
0, 0,std_radrd_*std_radrd_;
}
UKF::~UKF() {}
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
if (!is_initialized_)
{
// first measurement
if (meas_package.sensor_type_ == MeasurementPackage::RADAR)
{
double rho = meas_package.raw_measurements_[0];
double phi = meas_package.raw_measurements_[1];
double rho_dot = meas_package.raw_measurements_[2];
double vx = rho_dot * cos(phi);
double vy = rho_dot * sin(phi);
x_ << rho * cos(phi),
rho * sin(phi), sqrt(vx * vx + vy * vy), 0, 0;
}
else if (meas_package.sensor_type_ == MeasurementPackage::LASER)
{
x_ << meas_package.raw_measurements_[0],
meas_package.raw_measurements_[1], 0, 0, 0;
}
time_us_ = meas_package.timestamp_;
// done initializing, no need to predict or update
is_initialized_ = true;
return;
}
double dt = (meas_package.timestamp_ - time_us_) / 1000000.0; //dt - expressed in seconds
time_us_ = meas_package.timestamp_;
Prediction(dt);
if (use_radar_ && meas_package.sensor_type_ == MeasurementPackage::RADAR)
{
UpdateRadar(meas_package);
}
else if(use_laser_ && meas_package.sensor_type_ == MeasurementPackage::LASER)
{
UpdateLidar(meas_package);
}
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
auto Xsig_aug = eig_mat(n_aug_, 2 * n_aug_ + 1);
GenAugmentedSigmaPoints(Xsig_aug);
PredictSigmaPoints(Xsig_aug, delta_t);
PredictStateMean();
PredictStateCovariance();
}
/**
* Updates the state and the state covariance matrix using a laser measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateLidar(MeasurementPackage meas_package) {
auto z_pred = eig_vec(n_z_laser_);
auto S = eig_mat(n_z_laser_ , n_z_laser_);
auto Zsig = eig_mat(n_z_laser_, 2 * n_aug_ + 1);
GenLaserMeasSigPoints(Zsig);
PredictLaserMeasurement(Zsig, z_pred, S);
auto Tc = eig_mat(n_x_, n_z_laser_);
eig_vec z_diff = eig_vec::Zero(n_z_laser_);
UpdateCommon(meas_package, z_pred, S, Zsig, Tc, z_diff);
NIS_laser_ = z_diff.transpose() * S.inverse() * z_diff;
std::cout << "NIS_L = " << NIS_laser_ << std::endl;
}
void UKF::UpdateCommon(const MeasurementPackage& meas_package,
const eig_mat& z_pred, const eig_mat& S, const eig_mat& Zsig,
eig_mat& Tc, eig_vec& z_diff) {
Tc.fill(0.0);
for(int i = 0; i < 2 * n_aug_ + 1; i++)
{
z_diff = Zsig.col(i) - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;
// state difference
eig_vec x_diff = Xsig_pred_.col(i) - x_;
//angle normalization
while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI;
while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI;
Tc = Tc + weights_(i) * x_diff * z_diff.transpose();
}
//Kalman gain K;
eig_mat K = Tc * S.inverse();
//residual
z_diff = meas_package.raw_measurements_ - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;
//update state mean and covariance matrix
x_ = x_ + K * z_diff;
P_ = P_ - K*S*K.transpose();
}
/**
* Updates the state and the state covariance matrix using a radar measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateRadar(MeasurementPackage meas_package) {
auto z_pred = eig_vec(n_z_radar_);
auto S = eig_mat(n_z_radar_ , n_z_radar_);
auto Zsig = eig_mat(n_z_radar_, 2 * n_aug_ + 1);
GenRadarMeasSigPoints(Zsig);
PredictRadarMeasurement(Zsig, z_pred, S);
auto Tc = eig_mat(n_x_, n_z_radar_);
eig_vec z_diff = eig_vec::Zero(n_z_radar_);
UpdateCommon(meas_package, z_pred, S, Zsig, Tc, z_diff);
NIS_radar_ = z_diff.transpose() * S.inverse() * z_diff;
std::cout << "NIS_R = " << NIS_radar_ << std::endl;
}
void UKF::GenAugmentedSigmaPoints(eig_mat& aug_sigma_points) {
auto x_aug = eig_vec(n_aug_);
x_aug.setZero();
auto P_aug = eig_mat(n_aug_, n_aug_);
x_aug.head(n_x_) = x_;
P_aug.fill(0);
P_aug.topLeftCorner(n_x_, n_x_) = P_;
P_aug(5,5) = std_a_ * std_a_;
P_aug(6,6) = std_yawdd_ * std_yawdd_;
//create square root matrix
eig_mat A = P_aug.llt().matrixL();
//create augmented sigma points
aug_sigma_points.col(0) = x_aug;
for (int i = 0; i < n_aug_; i++)
{
aug_sigma_points.col(i + 1) = x_aug + sqrt(lambda_ + n_aug_) * A.col(i);
aug_sigma_points.col(i + 1 + n_aug_) = x_aug - sqrt(lambda_ + n_aug_) * A.col(i);
}
}
void UKF::PredictSigmaPoints(const eig_mat& aug_sigma_points, double delta_t) {
for(int i = 0; i < 2 * n_aug_ + 1; ++i)
{
double p_x = aug_sigma_points(0,i);
double p_y = aug_sigma_points(1,i);
double v = aug_sigma_points(2,i);
double yaw = aug_sigma_points(3,i);
double yawd = aug_sigma_points(4,i);
double nu_a = aug_sigma_points(5,i);
double nu_yawdd = aug_sigma_points(6,i);
double px_p, py_p;
if (fabs(yawd) > 0.001) {
px_p = p_x + v/yawd * ( sin (yaw + yawd*delta_t) - sin(yaw));
py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw+yawd*delta_t) );
}
else {
px_p = p_x + v*delta_t*cos(yaw);
py_p = p_y + v*delta_t*sin(yaw);
}
double v_p = v;
double yaw_p = yaw + yawd*delta_t;
double yawd_p = yawd;
px_p = px_p + 0.5*nu_a*delta_t*delta_t * cos(yaw);
py_p = py_p + 0.5*nu_a*delta_t*delta_t * sin(yaw);
v_p = v_p + nu_a*delta_t;
yaw_p = yaw_p + 0.5*nu_yawdd*delta_t*delta_t;
yawd_p = yawd_p + nu_yawdd*delta_t;
Xsig_pred_(0,i) = px_p;
Xsig_pred_(1,i) = py_p;
Xsig_pred_(2,i) = v_p;
Xsig_pred_(3,i) = yaw_p;
Xsig_pred_(4,i) = yawd_p;
}
}
void UKF::PredictStateMean() {
x_.setZero();
for (int i = 0; i < 2 * n_aug_ + 1; i++) {
x_ = x_ + weights_(i) * Xsig_pred_.col(i);
}
}
void UKF::PredictStateCovariance() {
P_.setZero();
for (int i = 0; i < 2 * n_aug_ + 1; i++) {
eig_vec x_diff = Xsig_pred_.col(i) - x_;
while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI;
while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI;
P_ = P_ + weights_(i) * x_diff * x_diff.transpose() ;
}
}
void UKF::GenRadarMeasSigPoints(eig_mat& z_sig) {
for(int i = 0; i < 2 * n_aug_ + 1; ++i)
{
double px = Xsig_pred_(0, i);
double py = Xsig_pred_(1, i);
double v = Xsig_pred_(2, i);
double psy = Xsig_pred_(3, i);
double psy_dot = Xsig_pred_(4, i);
double rho = sqrt(px * px + py * py) + 0.000001; // edding small value to avoid division by zero
double phi = atan2(py, px);
double rho_dot = (px*cos(psy)*v + py*sin(psy)*v)/rho;
z_sig(0, i) = rho;
z_sig(1, i) = phi;
z_sig(2, i) = rho_dot;
}
}
void UKF::GenLaserMeasSigPoints(eig_mat& z_sig) {
for(int i = 0; i < 2 * n_aug_ + 1; ++i)
{
double px = Xsig_pred_(0, i);
double py = Xsig_pred_(1, i);
z_sig(0, i) = px;
z_sig(1, i) = py;
}
}
void UKF::PredictRadarMeasurement(const eig_mat& z_sig, eig_vec& z_pred, eig_mat& S) {
CalcInnovCovMat(z_sig, z_pred, S);
S = S + R_radar_;
}
void UKF::PredictLaserMeasurement(const eig_mat& z_sig, eig_vec& z_pred, eig_mat& S) {
CalcInnovCovMat(z_sig, z_pred, S);
S = S + R_laser_;
}
void UKF::CalcInnovCovMat(const eig_mat& z_sig, eig_vec& z_pred, eig_mat& S) {
//calculate mean predicted measurement
z_pred.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++)
{
z_pred = z_pred + weights_(i) * z_sig.col(i);
}
//calculate innovation covariance matrix S
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++)
{
//residual
eig_vec z_diff = z_sig.col(i) - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;
S = S + weights_(i) * z_diff * z_diff.transpose();
}
}
| 28.257143
| 100
| 0.649646
|
grygoryant
|
6653f1069ceef9716aa05f73235434f7710e31da
| 19,579
|
hpp
|
C++
|
libraries/chain/include/evt/chain/contracts/evt_contract_utils.hpp
|
everitoken/evt
|
3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea
|
[
"Apache-2.0"
] | 1,411
|
2018-04-23T03:57:30.000Z
|
2022-02-13T10:34:22.000Z
|
libraries/chain/include/evt/chain/contracts/evt_contract_utils.hpp
|
baby636/evt
|
3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea
|
[
"Apache-2.0"
] | 27
|
2018-06-11T10:34:42.000Z
|
2019-07-27T08:50:02.000Z
|
libraries/chain/include/evt/chain/contracts/evt_contract_utils.hpp
|
baby636/evt
|
3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea
|
[
"Apache-2.0"
] | 364
|
2018-06-09T12:11:53.000Z
|
2020-12-15T03:26:48.000Z
|
/**
* @file
* @copyright defined in evt/LICENSE.txt
*/
#pragma once
namespace evt { namespace chain { namespace contracts {
/**
* Implements addmeta, paycharge, paybonus, prodvote, updsched, addscript and updscript actions
*/
namespace internal {
bool
check_involved_node(const group_def& group, const group::node& node, const public_key_type& key) {
auto result = false;
group.visit_node(node, [&](const auto& n) {
if(n.is_leaf()) {
if(group.get_leaf_key(n) == key) {
result = true;
// find one, return false to stop iterate group
return false;
}
return true;
}
if(check_involved_node(group, n, key)) {
result = true;
// find one, return false to stop iterate group
return false;
}
return true;
});
return result;
}
auto check_involved_permission = [](auto& tokendb_cache, const auto& permission, const auto& creator) {
for(auto& a : permission.authorizers) {
auto& ref = a.ref;
switch(ref.type()) {
case authorizer_ref::account_t: {
if(creator.is_account_ref() && ref.get_account() == creator.get_account()) {
return true;
}
break;
}
case authorizer_ref::group_t: {
const auto& name = ref.get_group();
if(creator.is_account_ref()) {
auto gp = make_empty_cache_ptr<group_def>();
READ_DB_TOKEN(token_type::group, std::nullopt, name, gp, unknown_group_exception, "Cannot find group: {}", name);
if(check_involved_node(*gp, gp->root(), creator.get_account())) {
return true;
}
}
else {
if(name == creator.get_group()) {
return true;
}
}
}
} // switch
}
return false;
};
auto check_involved_domain = [](auto& tokendb_cache, const auto& domain, auto pname, const auto& creator) {
switch(pname) {
case N(issue): {
return check_involved_permission(tokendb_cache, domain.issue, creator);
}
case N(transfer): {
return check_involved_permission(tokendb_cache, domain.transfer, creator);
}
case N(manage): {
return check_involved_permission(tokendb_cache, domain.manage, creator);
}
} // switch
return false;
};
auto check_involved_fungible = [](auto& tokendb_cache, const auto& fungible, auto pname, const auto& creator) {
switch(pname) {
case N(manage): {
return check_involved_permission(tokendb_cache, fungible.manage, creator);
}
} // switch
return false;
};
auto check_involved_group = [](const auto& group, const auto& key) {
if(group.key().is_public_key() && group.key().get_public_key() == key) {
return true;
}
return false;
};
auto check_involved_owner = [](const auto& token, const auto& key) {
for(auto& addr : token.owner) {
if(addr.is_public_key() && addr.get_public_key() == key) {
return true;
}
}
return false;
};
auto check_involved_creator = [](const auto& target, const auto& key) {
return target.creator == key;
};
template<typename T>
bool
check_duplicate_meta(const T& v, const meta_key& key) {
if(std::find_if(v.metas.cbegin(), v.metas.cend(), [&](const auto& meta) { return meta.key == key; }) != v.metas.cend()) {
return true;
}
return false;
}
template<>
bool
check_duplicate_meta<group_def>(const group_def& v, const meta_key& key) {
if(std::find_if(v.metas_.cbegin(), v.metas_.cend(), [&](const auto& meta) { return meta.key == key; }) != v.metas_.cend()) {
return true;
}
return false;
}
auto check_meta_key_reserved = [](const auto& key) {
EVT_ASSERT(!key.reserved(), meta_key_exception, "Meta-key is reserved and cannot be used");
};
} // namespace internal
EVT_ACTION_IMPL_BEGIN(addmeta) {
using namespace internal;
const auto& act = context.act;
auto& amact = context.act.data_as<add_clr_t<ACT>>();
try {
DECLARE_TOKEN_DB()
if(act.domain == N128(.group)) { // group
check_meta_key_reserved(amact.key);
auto gp = make_empty_cache_ptr<group_def>();
READ_DB_TOKEN(token_type::group, std::nullopt, act.key, gp, unknown_group_exception, "Cannot find group: {}", act.key);
EVT_ASSERT2(!check_duplicate_meta(*gp, amact.key), meta_key_exception,"Metadata with key: {} already exists.", amact.key);
if(amact.creator.is_group_ref()) {
EVT_ASSERT(amact.creator.get_group() == gp->name_, meta_involve_exception, "Only group itself can add its own metadata");
}
else {
// check involved, only group manager(aka. group key) can add meta
EVT_ASSERT(check_involved_group(*gp, amact.creator.get_account()), meta_involve_exception,
"Creator is not involved in group: ${name}.", ("name",act.key));
}
gp->metas_.emplace_back(meta(amact.key, amact.value, amact.creator));
UPD_DB_TOKEN(token_type::group, *gp);
}
else if(act.domain == N128(.fungible)) { // fungible
if(amact.key.reserved()) {
EVT_ASSERT(check_reserved_meta(amact, fungible_metas), meta_key_exception, "Meta-key is reserved and cannot be used");
}
auto fungible = make_empty_cache_ptr<fungible_def>();
READ_DB_TOKEN(token_type::fungible, std::nullopt, (symbol_id_type)std::stoul((std::string)act.key), fungible,
unknown_fungible_exception, "Cannot find fungible with symbol id: {}", act.key);
EVT_ASSERT(!check_duplicate_meta(*fungible, amact.key), meta_key_exception,
"Metadata with key ${key} already exists.", ("key",amact.key));
if(amact.creator.is_account_ref()) {
// check involved, only creator or person in `manage` permission can add meta
auto involved = check_involved_creator(*fungible, amact.creator.get_account())
|| check_involved_fungible(tokendb_cache, *fungible, N(manage), amact.creator);
EVT_ASSERT(involved, meta_involve_exception, "Creator is not involved in fungible: ${name}.", ("name",act.key));
}
else {
// check involved, only group in `manage` permission can add meta
EVT_ASSERT(check_involved_fungible(tokendb_cache, *fungible, N(manage), amact.creator), meta_involve_exception,
"Creator is not involved in fungible: ${name}.", ("name",act.key));
}
fungible->metas.emplace_back(meta(amact.key, amact.value, amact.creator));
UPD_DB_TOKEN(token_type::fungible, *fungible);
}
else if(act.key == N128(.meta)) { // domain
if(amact.key.reserved()) {
EVT_ASSERT(check_reserved_meta(amact, domain_metas), meta_key_exception, "Meta-key is reserved and cannot be used");
}
auto domain = make_empty_cache_ptr<domain_def>();
READ_DB_TOKEN(token_type::domain, std::nullopt, act.domain, domain, unknown_domain_exception,
"Cannot find domain: {}", act.domain);
EVT_ASSERT(!check_duplicate_meta(*domain, amact.key), meta_key_exception,
"Metadata with key ${key} already exists.", ("key",amact.key));
// check involved, only person involved in `manage` permission can add meta
EVT_ASSERT(check_involved_domain(tokendb_cache, *domain, N(manage), amact.creator), meta_involve_exception,
"Creator is not involved in domain: ${name}.", ("name",act.key));
domain->metas.emplace_back(meta(amact.key, amact.value, amact.creator));
UPD_DB_TOKEN(token_type::domain, *domain);
}
else { // token
check_meta_key_reserved(amact.key);
auto token = make_empty_cache_ptr<token_def>();
READ_DB_TOKEN(token_type::token, act.domain, act.key, token, unknown_token_exception, "Cannot find token: {} in {}", act.key, act.domain);
EVT_ASSERT(!check_token_destroy(*token), token_destroyed_exception, "Metadata cannot be added on destroyed token.");
EVT_ASSERT(!check_token_locked(*token), token_locked_exception, "Metadata cannot be added on locked token.");
EVT_ASSERT(!check_duplicate_meta(*token, amact.key), meta_key_exception, "Metadata with key ${key} already exists.", ("key",amact.key));
auto domain = make_empty_cache_ptr<domain_def>();
READ_DB_TOKEN(token_type::domain, std::nullopt, act.domain, domain, unknown_domain_exception, "Cannot find domain: {}", amact.key);
if(amact.creator.is_account_ref()) {
// check involved, only person involved in `issue` and `transfer` permissions or `owners` can add meta
auto involved = check_involved_owner(*token, amact.creator.get_account())
|| check_involved_domain(tokendb_cache, *domain, N(issue), amact.creator)
|| check_involved_domain(tokendb_cache, *domain, N(transfer), amact.creator);
EVT_ASSERT(involved, meta_involve_exception, "Creator is not involved in token ${domain}-${name}.", ("domain",act.domain)("name",act.key));
}
else {
// check involved, only group involved in `issue` and `transfer` permissions can add meta
auto involved = check_involved_domain(tokendb_cache, *domain, N(issue), amact.creator)
|| check_involved_domain(tokendb_cache, *domain, N(transfer), amact.creator);
EVT_ASSERT(involved, meta_involve_exception, "Creator is not involved in token ${domain}-${name}.", ("domain",act.domain)("name",act.key));
}
token->metas.emplace_back(meta(amact.key, amact.value, amact.creator));
UPD_DB_TOKEN(token_type::token, *token);
}
}
EVT_CAPTURE_AND_RETHROW(tx_apply_exception);
}
EVT_ACTION_IMPL_END()
EVT_ACTION_IMPL_BEGIN(paycharge) {
using namespace internal;
auto& pcact = context.act.data_as<add_clr_t<ACT>>();
try {
DECLARE_TOKEN_DB()
property_stakes evt, pevt;
READ_DB_ASSET_NO_THROW_NO_NEW(pcact.payer, pevt_sym(), pevt);
auto paid = std::min((int64_t)pcact.charge, pevt.amount);
if(paid > 0) {
pevt.amount -= paid;
PUT_DB_ASSET(pcact.payer, pevt);
}
if(paid < pcact.charge) {
READ_DB_ASSET_NO_THROW_NO_NEW(pcact.payer, evt_sym(), evt);
auto remain = pcact.charge - paid;
if(evt.amount < (int64_t)remain) {
EVT_THROW2(charge_exceeded_exception,"There are only {} and {} left, but charge is {}",
asset(evt.amount, evt_sym()), asset(pevt.amount, pevt_sym()), asset(pcact.charge, evt_sym()));
}
evt.amount -= remain;
PUT_DB_ASSET(pcact.payer, evt);
}
auto pbs = context.control.pending_block_state();
auto& prod = pbs->get_scheduled_producer(pbs->header.timestamp).block_signing_key;
property_stakes bp;
READ_DB_ASSET_NO_THROW(address(prod), evt_sym(), bp);
// give charge to producer
bp.amount += pcact.charge;
PUT_DB_ASSET(prod, bp);
}
EVT_CAPTURE_AND_RETHROW(tx_apply_exception);
}
EVT_ACTION_IMPL_END()
EVT_ACTION_IMPL_BEGIN(paybonus) {
// empty body
// will not execute here
assert(false);
return;
}
EVT_ACTION_IMPL_END()
namespace internal {
auto update_chain_config = [](auto& conf, auto key, auto v) {
switch(key.value) {
case N128(network-charge-factor): {
conf.base_network_charge_factor = v;
break;
}
case N128(storage-charge-factor): {
conf.base_storage_charge_factor = v;
break;
}
case N128(cpu-charge-factor): {
conf.base_cpu_charge_factor = v;
break;
}
case N128(global-charge-factor): {
conf.global_charge_factor = v;
break;
}
default: {
EVT_THROW2(prodvote_key_exception, "Configuration key: {} is not valid", key);
}
} // switch
};
} // namespace internal
EVT_ACTION_IMPL_BEGIN(prodvote) {
using namespace internal;
auto& pvact = context.act.data_as<add_clr_t<ACT>>();
try {
EVT_ASSERT(context.has_authorized(N128(.prodvote), pvact.key), action_authorize_exception,
"Invalid authorization fields in action(domain and key).");
EVT_ASSERT(pvact.value > 0 && pvact.value < 1'000'000, prodvote_value_exception, "Invalid prodvote value: ${v}", ("v",pvact.value));
auto conf = context.control.get_global_properties().configuration;
auto& sche = context.control.active_producers();
auto& exec_ctx = context.control.get_execution_context();
DECLARE_TOKEN_DB()
auto updact = false;
auto act = name();
// test if it's action-upgrade vote and wheather action is valid
{
auto key = pvact.key.to_string();
if(boost::starts_with(key, "action-")) {
try {
act = name(key.substr(7));
}
catch(name_type_exception&) {
EVT_THROW2(prodvote_key_exception, "Invalid action name provided: {}", key.substr(7));
}
auto cver = exec_ctx.get_current_version(act);
auto mver = exec_ctx.get_max_version(act);
EVT_ASSERT2(pvact.value >= cver && pvact.value <= exec_ctx.get_max_version(act), prodvote_value_exception,
"Provided version: {} for action: {} is not valid, should be in range ({},{}]", pvact.value, act, cver, mver);
updact = true;
}
}
auto pkey = sche.get_producer_key(pvact.producer);
EVT_ASSERT(pkey.has_value(), prodvote_producer_exception, "${p} is not a valid producer", ("p",pvact.producer));
auto map = make_empty_cache_ptr<flat_map<public_key_type, int64_t>>();
READ_DB_TOKEN_NO_THROW(token_type::prodvote, std::nullopt, pvact.key, map);
if(map == nullptr) {
auto newmap = flat_map<public_key_type, int64_t>();
newmap.emplace(*pkey, pvact.value);
map = tokendb_cache.put_token<std::add_rvalue_reference_t<decltype(newmap)>, true>(
token_type::prodvote, action_op::put, std::nullopt, pvact.key, std::move(newmap));
}
else {
auto it = map->emplace(*pkey, pvact.value);
if(it.second == false) {
// existed
EVT_ASSERT2(it.first->second != pvact.value, prodvote_value_exception, "Value voted for {} is the same as previous voted", pvact.key);
it.first->second = pvact.value;
}
tokendb_cache.put_token(token_type::prodvote, action_op::put, std::nullopt, pvact.key, *map);
}
auto is_prod = [&](auto& pk) {
for(auto& p : sche.producers) {
if(p.block_signing_key == pk) {
return true;
}
}
return false;
};
auto values = std::vector<int64_t>();
for(auto& it : *map) {
if(is_prod(it.first)) {
values.emplace_back(it.second);
}
}
auto limit = (int64_t)values.size();
if(values.size() != sche.producers.size()) {
limit = ::ceil(2.0 * sche.producers.size() / 3.0);
if((int64_t)values.size() <= limit) {
// if the number of votes is equal or less than 2/3 producers
// don't update
return;
}
}
if(!updact) {
// general global config updates, find the median and update
int64_t nv = 0;
// find median
if(values.size() % 2 == 0) {
auto it1 = values.begin() + values.size() / 2 - 1;
auto it2 = values.begin() + values.size() / 2;
std::nth_element(values.begin(), it1 , values.end());
std::nth_element(values.begin(), it2 , values.end());
nv = ::floor((*it1 + *it2) / 2);
}
else {
auto it = values.begin() + values.size() / 2;
std::nth_element(values.begin(), it , values.end());
nv = *it;
}
update_chain_config(conf, pvact.key, nv);
context.control.set_chain_config(conf);
}
else {
// update action version
// find the all the votes which vote-version is large than current version
// and update version with the version which has more than 2/3 votes of producers
auto cver = exec_ctx.get_current_version(act);
auto map = flat_map<int, int>(); // maps version to votes
for(auto& v : values) {
if(v > cver) {
map[v] += 1;
}
}
for(auto& it : map) {
if(it.second >= limit) {
exec_ctx.set_version(act, it.first);
break;
}
}
}
}
EVT_CAPTURE_AND_RETHROW(tx_apply_exception);
}
EVT_ACTION_IMPL_END()
EVT_ACTION_IMPL_BEGIN(updsched) {
auto usact = context.act.data_as<ACT>();
try {
EVT_ASSERT(context.has_authorized(N128(.prodsched), N128(.update)), action_authorize_exception,
"Invalid authorization fields in action(domain and key).");
context.control.set_proposed_producers(std::move(usact.producers));
}
EVT_CAPTURE_AND_RETHROW(tx_apply_exception);
}
EVT_ACTION_IMPL_END()
EVT_ACTION_IMPL_BEGIN(newscript) {
using namespace internal;
auto asact = context.act.data_as<ACT>();
try {
EVT_ASSERT(context.has_authorized(N128(.script), asact.name), action_authorize_exception,
"Invalid authorization fields in action(domain and key).");
DECLARE_TOKEN_DB()
EVT_ASSERT2(!tokendb.exists_token(token_type::script, std::nullopt, asact.name), script_duplicate_exception,
"Script: {} already exists.", asact.name);
auto script = script_def();
script.name = asact.name;
script.content = asact.content;
script.creator = asact.creator;
ADD_DB_TOKEN(token_type::script, script);
}
EVT_CAPTURE_AND_RETHROW(tx_apply_exception);
}
EVT_ACTION_IMPL_END()
EVT_ACTION_IMPL_BEGIN(updscript) {
using namespace internal;
auto usact = context.act.data_as<ACT>();
try {
EVT_ASSERT(context.has_authorized(N128(.script), usact.name), action_authorize_exception,
"Invalid authorization fields in action(domain and key).");
DECLARE_TOKEN_DB()
auto script = make_empty_cache_ptr<script_def>();
READ_DB_TOKEN(token_type::script, std::nullopt, usact.name, script, unknown_script_exception,"Cannot find script: {}", usact.name);
script->content = usact.content;
UPD_DB_TOKEN(token_type::script, *script);
}
EVT_CAPTURE_AND_RETHROW(tx_apply_exception);
}
EVT_ACTION_IMPL_END()
}}} // namespace evt::chain::contracts
| 38.847222
| 155
| 0.597579
|
everitoken
|
6664d56200c6f7ed14b7b4598c2b608bcad854dd
| 2,566
|
cpp
|
C++
|
graph-source-code/194-C/4785501.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/194-C/4785501.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/194-C/4785501.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: MS C++
#include <stdio.h>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int T = 0;
typedef vector < vector < int > > table;
int x[4] = { 0 , 0 , -1 , 1 };
int y[4] = { -1 , 1 , 0 , 0 };
table time ( 52 , vector < int > ( 52 , 0 ) );;
table up ( 52 , vector < int > ( 52 , 0 ) );;
bool dfs ( pair < int , int > v , pair < int , int > p , const table &graph , bool root )
{
T++;
int count_child = 0;
up [ v.first ][ v.second ] = time [ v.first ][ v.second ] = T;
bool res = false;
for ( int j = 0; j < 4; ++j )
{
if ( graph [ v.first + x[j] ][ v.second + y[j] ] == 1 )
{
pair < int , int > u = make_pair ( v.first + x[j] , v.second + y[j] );
if (u == p)
continue;
if ( time[u.first][u.second] != 0 )
up[ v.first ][ v.second ] = min ( up [ v.first ][ v.second ] , time [ u.first ][ u.second ] );
else
{
bool f = dfs ( u , v , graph , false );
if (f)
res = true;
count_child++;
up [ v.first ][ v.second ] = min ( up[ v.first ][ v.second ] , up [ u.first ][ u.second ] );
if (!root && up[u.first][u.second] >= time [v.first][v.second] )
return true;
}
}
}
if ( root && count_child > 1 )
return true;
return res;
}
int main()
{
int n;
int m;
cin >> n;
cin >> m;
table v ( n+2 , vector < int > ( m+2 , 0 ) );
for ( int i = 1; i <= n; ++i )
{
for ( int j = 1; j <= m; ++j )
{
char ch;
cin >> ch;
if ( ch == '#' )
v[i][j] = 1;
else v[i][j] = 0;
}
}
int ans = -1;
for ( int i = 1; i <= n; ++i )
for ( int j = 1; j <= m; ++j )
{
if (v[i][j] == 0)
continue;
if (ans == -1 && time[i][j] == 0 ) {
if (dfs ( make_pair( i , j ) , make_pair ( -1 , -1 ) , v , true )) {
ans = 1;
}
else {
ans = 2;
}
}
}
if (T <= 2) {
ans = -1;
}
cout << ans << "\n";
return 0;
}
| 27.891304
| 116
| 0.336321
|
AmrARaouf
|
666eeb467cce11b8f562f7f89184a0bc279cd124
| 2,675
|
hpp
|
C++
|
include/svgpp/adapter/line.hpp
|
RichardCory/svgpp
|
801e0142c61c88cf2898da157fb96dc04af1b8b0
|
[
"BSL-1.0"
] | 428
|
2015-01-05T17:13:54.000Z
|
2022-03-31T08:25:47.000Z
|
include/svgpp/adapter/line.hpp
|
andrew2015/svgpp
|
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
|
[
"BSL-1.0"
] | 61
|
2015-01-08T14:32:27.000Z
|
2021-12-06T16:55:11.000Z
|
include/svgpp/adapter/line.hpp
|
andrew2015/svgpp
|
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
|
[
"BSL-1.0"
] | 90
|
2015-05-19T04:56:46.000Z
|
2022-03-26T16:42:50.000Z
|
// Copyright Oleg Maximenko 2014.
// 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)
//
// See http://github.com/svgpp/svgpp for library home page.
#pragma once
#include <svgpp/definitions.hpp>
#include <svgpp/detail/adapt_context.hpp>
#include <boost/optional.hpp>
#include <boost/noncopyable.hpp>
#include <boost/mpl/set.hpp>
namespace svgpp
{
typedef boost::mpl::set4<tag::attribute::x1, tag::attribute::y1, tag::attribute::x2, tag::attribute::y2>
line_shape_attributes;
template<class Length>
class collect_line_attributes_adapter: boost::noncopyable
{
public:
template<class Context>
bool on_exit_attributes(Context & context) const
{
typedef detail::unwrap_context<Context, tag::length_policy> length_policy_context;
typedef typename length_policy_context::policy length_policy_t;
typename length_policy_t::length_factory_type & converter
= length_policy_t::length_factory(length_policy_context::get(context));
typename length_policy_t::length_factory_type::coordinate_type
x1 = 0, y1 = 0, x2 = 0, y2 = 0;
if (x1_)
x1 = converter.length_to_user_coordinate(*x1_, tag::length_dimension::width());
if (x2_)
x2 = converter.length_to_user_coordinate(*x2_, tag::length_dimension::width());
if (y1_)
y1 = converter.length_to_user_coordinate(*y1_, tag::length_dimension::height());
if (y2_)
y2 = converter.length_to_user_coordinate(*y2_, tag::length_dimension::height());
typedef detail::unwrap_context<Context, tag::basic_shapes_events_policy> basic_shapes_events;
basic_shapes_events::policy::set_line(basic_shapes_events::get(context), x1, y1, x2, y2);
return true;
}
void set(tag::attribute::x1, Length const & val) { x1_ = val; }
void set(tag::attribute::y1, Length const & val) { y1_ = val; }
void set(tag::attribute::x2, Length const & val) { x2_ = val; }
void set(tag::attribute::y2, Length const & val) { y2_ = val; }
private:
boost::optional<Length> x1_, y1_, x2_, y2_;
};
struct line_to_path_adapter
{
template<class Context, class Coordinate>
static void set_line(Context & context, Coordinate x1, Coordinate y1, Coordinate x2, Coordinate y2)
{
typedef detail::unwrap_context<Context, tag::path_events_policy> path_events;
typename path_events::type & path_context = path_events::get(context);
path_events::policy::path_move_to(path_context, x1, y1, tag::coordinate::absolute());
path_events::policy::path_line_to(path_context, x2, y2, tag::coordinate::absolute());
path_events::policy::path_exit(path_context);
}
};
}
| 36.148649
| 104
| 0.730841
|
RichardCory
|
667204f549368ec413d937251deae01f07e52a66
| 329
|
cpp
|
C++
|
pico_json/example.cpp
|
minamaged113/training
|
29984f4d22967625b87281bb2247246b1b0033a7
|
[
"MIT"
] | 46
|
2019-07-02T05:10:47.000Z
|
2022-03-19T16:29:19.000Z
|
pico_json/example.cpp
|
minamaged113/training
|
29984f4d22967625b87281bb2247246b1b0033a7
|
[
"MIT"
] | 62
|
2019-09-24T17:57:07.000Z
|
2022-03-28T15:35:45.000Z
|
pico_json/example.cpp
|
minamaged113/training
|
29984f4d22967625b87281bb2247246b1b0033a7
|
[
"MIT"
] | 33
|
2019-09-19T19:29:37.000Z
|
2022-03-17T05:28:06.000Z
|
#include "picojson/picojson.h"
int main(void) {
const char* json = "{\"a\":1}";
picojson::value v;
std::string err;
const char* json_end = picojson::parse(v, json, json + strlen(json), &err);
if (! err.empty()) {
std::cerr << err << std::endl;
}
std::cout << "Json parsed ok!" << std::endl;
return 0;
}
| 19.352941
| 77
| 0.571429
|
minamaged113
|
667c0041468b36c82a086ff95801b3f7aa5ce408
| 8,207
|
cpp
|
C++
|
src/libsnw_util/slot_allocator.cpp
|
Sojourn/snw
|
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
|
[
"MIT"
] | null | null | null |
src/libsnw_util/slot_allocator.cpp
|
Sojourn/snw
|
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
|
[
"MIT"
] | null | null | null |
src/libsnw_util/slot_allocator.cpp
|
Sojourn/snw
|
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <cassert>
#include <iostream>
#include "align.h"
#include "slot_allocator.h"
snw::slot_allocator::slot_allocator(size_t capacity)
: capacity_(capacity)
, size_(0)
, height_(0)
{
size_t branch_count = 0;
size_t leaf_count = 0;
// compute the tree layout
{
size_t width = align_up(capacity_, node_capacity) / node_capacity;
levels_[height_].width = width;
leaf_count += width;
++height_;
while (width > 1) {
width = align_up(width, node_capacity) / node_capacity;
levels_[height_].width = width;
branch_count += width;
++height_;
}
// put levels in desending order
std::reverse(levels_, levels_ + height_);
}
// setup the tree
{
size_t depth = 0;
if (branch_count > 0) {
branch_nodes_.resize(branch_count);
size_t branch_offset = 0;
for (; depth < (height_ - 1); ++depth) {
levels_[depth].first = &branch_nodes_[branch_offset];
branch_offset += levels_[depth].width;
}
}
leaf_nodes_.resize(leaf_count);
levels_[depth].first = leaf_nodes_.data();
}
check_integrity();
}
bool snw::slot_allocator::allocate(uint64_t* slot) {
if (size() == capacity()) {
return false;
}
cursor c;
for (size_t depth = 0; depth < height_; ++depth) {
node& node = levels_[depth].first[c.tell()];
int chunk_offset = 0;
int bit_offset = 0;
if (is_leaf_level(depth)) {
leaf_node& leaf = static_cast<leaf_node&>(node);
for (; chunk_offset < node_chunk_count; ++chunk_offset) {
uint64_t& live_chunk = leaf.live[chunk_offset];
uint64_t dead_chunk = ~live_chunk;
if (dead_chunk) {
bit_offset = count_trailing_zeros(dead_chunk);
break;
}
}
}
else {
branch_node& branch = static_cast<branch_node&>(node);
for (; chunk_offset < node_chunk_count; ++chunk_offset) {
uint64_t& dead_chunk = branch.any_dead[chunk_offset];
if (dead_chunk) {
bit_offset = count_trailing_zeros(dead_chunk);
break;
}
}
}
std::cout << "depth:" << depth << std::endl;
std::cout << "index:" << c.tell() << std::endl;
std::cout << "chunk_offset:" << chunk_offset << std::endl;
std::cout << "bit_offset:" << bit_offset << std::endl;
assert(chunk_offset < node_chunk_count);
c.desend(chunk_offset, bit_offset);
}
*slot = c.tell();
std::cout << "slot:" << *slot << std::endl;
assert(*slot < capacity_);
std::cout << std::endl;
bool any_live = false;
bool any_dead = false;
for (size_t i = 0; i < height_; ++i) {
int chunk_offset = c.chunk_offset();
int bit_offset = c.bit_offset();
c.ascend();
size_t depth = height_ - i - 1;
size_t node_index = c.tell();
node& node = levels_[depth].first[node_index];
if (is_leaf_level(depth)) {
leaf_node& leaf = static_cast<leaf_node&>(node);
assert(!test_bit(leaf.live[chunk_offset], bit_offset));
set_bit(leaf.live[chunk_offset], bit_offset);
any_live = true;
any_dead = !all(leaf.live);
}
else {
branch_node& branch = static_cast<branch_node&>(node);
if (any_live) {
set_bit(branch.any_live[chunk_offset], bit_offset);
any_live = true;
}
if (!any_dead) {
clear_bit(branch.any_dead[chunk_offset], bit_offset);
any_dead = none(branch.any_dead);
}
}
}
#if 1
check_integrity();
#endif
return true;
}
void snw::slot_allocator::deallocate(uint64_t slot) {
cursor c(slot);
bool any_live = false;
bool any_dead = false;
// TODO: detect if we can stop iteration early
for (size_t i = 0; i < height_; ++i) {
int chunk_offset = c.chunk_offset();
int bit_offset = c.bit_offset();
c.ascend();
size_t depth = height_ - i - 1;
size_t node_index = c.tell();
node& node = levels_[depth].first[node_index];
if (i == 0) {
leaf_node& leaf = static_cast<leaf_node&>(node);
assert(test_bit(leaf.live[chunk_offset], bit_offset));
clear_bit(leaf.live[chunk_offset], bit_offset);
any_live = any(leaf.live);
any_dead = true;
}
else {
branch_node& branch = static_cast<branch_node&>(node);
if (!any_live) {
clear_bit(branch.any_live[chunk_offset], bit_offset);
any_live = any(branch.any_live);
}
if (any_dead) {
set_bit(branch.any_dead[chunk_offset], bit_offset);
any_dead = true;
}
}
}
}
bool snw::slot_allocator::is_leaf_level(size_t depth) const {
return (depth == (height_ - 1));
}
bool snw::slot_allocator::any(const uint64_t (&chunks)[node_chunk_count]) {
for (uint64_t chunk: chunks) {
if (chunk != 0) {
return true;
}
}
return false;
}
bool snw::slot_allocator::all(const uint64_t (&chunks)[node_chunk_count]) {
for (uint64_t chunk: chunks) {
if (chunk != std::numeric_limits<uint64_t>::max()) {
return false;
}
}
return true;
}
bool snw::slot_allocator::none(const uint64_t (&chunks)[node_chunk_count]) {
return !any(chunks);
}
void snw::slot_allocator::check_integrity() const {
for (size_t depth = 0; depth < (height_ - 1); ++depth) {
for (size_t node_offset = 0; node_offset < levels_[depth].width; ++node_offset) {
const branch_node& branch = static_cast<const branch_node&>(levels_[depth].first[node_offset]);
for (int chunk_offset = 0; chunk_offset < node_chunk_count; ++chunk_offset) {
// check integrity of any_live
for_each_set_bit(branch.any_live[chunk_offset], [&](int bit_offset) {
cursor cursor(node_offset);
cursor.desend(chunk_offset, bit_offset);
const node& child_node = levels_[depth + 1].first[cursor.tell()];
if (is_leaf_level(depth + 1)) {
const leaf_node& child_leaf = static_cast<const leaf_node&>(child_node);
assert(any(child_leaf.live));
}
else {
const branch_node& child_branch = static_cast<const branch_node&>(child_node);
assert(any(child_branch.any_live));
}
});
// check integrity of any_dead
for_each_set_bit(branch.any_dead[chunk_offset], [&](int bit_offset) {
cursor cursor(node_offset);
cursor.desend(chunk_offset, bit_offset);
const node& child_node = levels_[depth + 1].first[cursor.tell()];
if (is_leaf_level(depth + 1)) {
const leaf_node& child_leaf = static_cast<const leaf_node&>(child_node);
assert(!all(child_leaf.live));
}
else {
const branch_node& child_branch = static_cast<const branch_node&>(child_node);
assert(any(child_branch.any_dead));
}
});
}
}
}
}
snw::slot_allocator::branch_node::branch_node() {
for (uint64_t& chunk: any_live) {
chunk = std::numeric_limits<uint64_t>::min();
}
for (uint64_t& chunk: any_dead) {
chunk = std::numeric_limits<uint64_t>::max();
}
}
snw::slot_allocator::leaf_node::leaf_node() {
for (uint64_t& chunk: live) {
chunk = std::numeric_limits<uint64_t>::min();
}
}
| 30.737828
| 107
| 0.540271
|
Sojourn
|
667c6c9b39a404741e3f5d8efeb2d55bdead5198
| 2,103
|
cpp
|
C++
|
15.cpp
|
TwoFX/aoc2021
|
0c6f4f1642c2efdc55d7cec5ef214803859b07cd
|
[
"Apache-2.0"
] | 1
|
2021-12-17T11:07:15.000Z
|
2021-12-17T11:07:15.000Z
|
15.cpp
|
TwoFX/aoc2021
|
0c6f4f1642c2efdc55d7cec5ef214803859b07cd
|
[
"Apache-2.0"
] | null | null | null |
15.cpp
|
TwoFX/aoc2021
|
0c6f4f1642c2efdc55d7cec5ef214803859b07cd
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define all(a) begin(a), end(a)
#define has(a, b) (a.find(b) != a.end())
#define fora(i, n) for(int i = 0; i < n; i++)
#define forb(i, n) for(int i = 1; i <= n; i++)
#define forc(a, b) for(const auto &a : b)
#define ford(i, n) for(int i = n; i >= 0; i--)
#define maxval(t) numeric_limits<t>::max()
#define minval(t) numeric_limits<t>::min()
#define imin(a, b) a = min(a, b)
#define imax(a, b) a = max(a, b)
#define sz(x) (int)(x).size()
#define pvec(v) copy(all(v), ostream_iterator<decltype(v)::value_type>(cout, " "))
#define dbgs(x) #x << " = " << x
#define dbgs2(x, y) dbgs(x) << ", " << dbgs(y)
#define dbgs3(x, y, z) dbgs2(x, y) << ", " << dbgs(z)
#define dbgs4(w, x, y, z) dbgs3(w, x, y) << ", " << dbgs(z)
using ll = long long;
using ld = long double;
int n;
constexpr ll inf = 100000000000;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
vector<vector<ll>> F;
string s;
while (cin >> s) {
F.eb();
forc(c, s) {
ll r = c - '0';
F.back().pb(r);
}
}
int m = sz(F);
n = 5 * sz(F);
vector<vector<ll>> f(n, vector<ll>(n));
fora(i, n) fora(j, n) {
int ir = i % m;
int jr = j % m;
int d = i / m + j / m;
int q = F[ir][jr] + d;
while (q > 9) q -= 9;
f[i][j] = q;
}
vector<vector<ll>> best(n, vector<ll>(n, inf));
priority_queue<pair<ll, pair<int, int>>, vector<pair<ll, pair<int, int>>>, greater<pair<ll, pair<int, int>>>> pq;
best[0][0] = 0;
pq.emplace(mp(0, mp(0, 0)));
while (!pq.empty()) {
auto t = pq.top();
pq.pop();
int i = t.second.first;
int j = t.second.second;
ll d = t.first;
if (d < best[i][j]) continue;
for (int di = -1; di <= 1; ++di) {
for (int dj = -1; dj <= 1; ++dj) {
if ((di == 0) == (dj == 0)) continue;
int ii = i + di;
int jj = j + dj;
if (ii < 0 || ii >= n || jj < 0 || jj >= n) continue;
ll pd = d + f[ii][jj];
if (pd < best[ii][jj]) {
best[ii][jj] = pd;
pq.emplace(mp(pd, mp(ii, jj)));
}
}
}
}
cout << best[n - 1][n - 1] << endl;
}
| 23.629213
| 114
| 0.527342
|
TwoFX
|
667ef198f1d97292a1674d2f8d27b80e0ae99630
| 2,100
|
cpp
|
C++
|
project/examples/baselib/src/baselib.cpp
|
qigao/cmake-template
|
cd1b7f8995bba7e672f3ca35463ecc129ea7bcbc
|
[
"MIT"
] | null | null | null |
project/examples/baselib/src/baselib.cpp
|
qigao/cmake-template
|
cd1b7f8995bba7e672f3ca35463ecc129ea7bcbc
|
[
"MIT"
] | 23
|
2022-03-08T11:24:35.000Z
|
2022-03-23T04:14:31.000Z
|
project/examples/baselib/src/baselib.cpp
|
qigao/project-cpp-template
|
cd1b7f8995bba7e672f3ca35463ecc129ea7bcbc
|
[
"MIT"
] | null | null | null |
#include "version.h"
#include <baselib.h>
#include <fstream>
#include <iostream>
#include <zmq.hpp>
#include <zmq_addon.hpp>
namespace baselib {
void printInfo()
{
zmq::context_t ctx;
zmq::socket_t sock1(ctx, zmq::socket_type::push);
zmq::socket_t sock2(ctx, zmq::socket_type::pull);
sock1.bind("tcp://127.0.0.1:*");
const std::string last_endpoint = sock1.get(zmq::sockopt::last_endpoint);
std::cout << "Connecting to " << last_endpoint << std::endl;
sock2.connect(last_endpoint);
std::array<zmq::const_buffer, 2> send_msgs = { zmq::str_buffer("foo"),
zmq::str_buffer("bar!") };
if (!zmq::send_multipart(sock1, send_msgs)) return;
std::vector<zmq::message_t> recv_msgs;
const auto ret = zmq::recv_multipart(sock2, std::back_inserter(recv_msgs));
if (!ret) return;
std::cout << "Got " << *ret << " messages" << std::endl;
std::string dataPath = "data";
std::cout << "Version: " << PROJECT_VERSION << "\n"
<< "Author: " << GIT_AUTHOR_NAME << "\n"
<< "Branch: " << GIT_BRANCH << "\n"
<< "Date: " << GIT_COMMIT_DATE_ISO8601 << "\n\n"
<< std::endl;
// Library name
std::cout << "Library template::baselib" << std::endl;
std::cout << "========================================" << std::endl;
// Library type (static or dynamic)
#ifdef BASELIB_STATIC_DEFINE
std::cout << "Library type: STATIC" << std::endl;
#else
std::cout << "Library type: SHARED" << std::endl;
#endif
// Data directory
std::cout << "Data path: " << dataPath << std::endl;
std::cout << std::endl;
// Read file
std::cout << "Data directory access" << std::endl;
std::cout << "========================================" << std::endl;
std::string fileName = dataPath + "/DATA_FOLDER.txt";
std::cout << "Reading from '" << fileName << "': " << std::endl;
std::cout << std::endl;
std::ifstream f(fileName);
if (f.is_open()) {
std::string line;
while (getline(f, line)) { std::cout << line << '\n'; }
f.close();
} else {
std::cout << "Unable to open file." << std::endl;
}
}
}// namespace baselib
| 31.343284
| 77
| 0.579524
|
qigao
|
667f4c8c0389e26678257aa84c2aef335fecde5b
| 1,643
|
cpp
|
C++
|
src/behaviors/charge.cpp
|
Datorsmurf/liang
|
0fc2f142429894f349399189eb16737ae71c2460
|
[
"MIT"
] | 1
|
2021-12-27T09:43:26.000Z
|
2021-12-27T09:43:26.000Z
|
src/behaviors/charge.cpp
|
Datorsmurf/liang
|
0fc2f142429894f349399189eb16737ae71c2460
|
[
"MIT"
] | null | null | null |
src/behaviors/charge.cpp
|
Datorsmurf/liang
|
0fc2f142429894f349399189eb16737ae71c2460
|
[
"MIT"
] | null | null | null |
#include "charge.h"
#include "Controller.h"
#include "Logger.h"
#include "definitions.h"
Charge::Charge(Controller *controller_, LOGGER *logger_, BATTERY *battery_, MowerModel* mowerModel_) {
controller = controller_;
logger = logger_;
battery = battery_;
mowerModel = mowerModel_;
}
void Charge::start() {
controller->StopMovement();
controller->StopCutter();
lastCharge = millis();
wiggleStart = 0;
}
int Charge::loop() {
if (mowerModel->CurrentOpModeId == OP_MODE_MOW && battery->isFullyCharged()) {
return BEHAVIOR_LAUNCH;
}
if(battery->isBeingCharged()) {
lastCharge = millis();
wiggleStart = 0;
}
//Give up wiggling after 2 minutes
if (hasTimeout(lastCharge, 120000)) {
//logger->log("Giving up wiggling.");
wiggleStart = 0;
} else if(hasTimeout(lastCharge, 2000) && wiggleStart == 0) {
logger->log("Dock connection lost. Trying wiggling to reconnect.");
wiggleStart = millis();
}
//Async wiggling allow for the wiggling to stop immediately when connection is restored.
if (wiggleStart > 0){
int i = ((wiggleStart - millis()) / 100) % 200;
if ( i == 0 || i == 16) {
controller->RunAsync(0, 190, SHORT_ACCELERATION_TIME);
} else if (i == 1|| i == 15) {
controller->RunAsync(190, 0, SHORT_ACCELERATION_TIME);
} else {
controller->StopMovement();
}
return id();
}
controller->StopMovement();
return id();
}
int Charge::id() {
return BEHAVIOR_CHARGE;
}
String Charge::desc() {
return "Charging";
}
| 25.671875
| 102
| 0.606817
|
Datorsmurf
|
668b22422cdc87542273663c4cb0b4a7c53dc990
| 1,006
|
cpp
|
C++
|
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/LAB MID/main(1).cpp
|
diptu/Teaching
|
20655bb2c688ae29566b0a914df4a3e5936a2f61
|
[
"MIT"
] | null | null | null |
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/LAB MID/main(1).cpp
|
diptu/Teaching
|
20655bb2c688ae29566b0a914df4a3e5936a2f61
|
[
"MIT"
] | null | null | null |
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/LAB MID/main(1).cpp
|
diptu/Teaching
|
20655bb2c688ae29566b0a914df4a3e5936a2f61
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "stack.cpp"
#include "queue.cpp"
using namespace std;
QueueLL Reverse (int k) {
QueueLL<char> qq ;
for(int i = k ; i > 0 ; i-- ) {
qq.insertAtEnd(q.getValue(i))
}
for (int i = k ; q.hasNext () ; i++ ) {
qq.enqueue(q.getValue(i)) ;
}
return qq ;
}
int getMax () {
int m = 0 ;
StackLL ss ;
StackLL sss ;
while (s.hasNext ()) {
ss.push(s.Top()) ;
sss.push (s.Top ()) ;
s.pop () ;
}
while (sss.hasNext ()) {
s.push (sss.pop()) ;
}
while (ss.hasNext()) {
if (m<ss.top) {
m= ss.pop() ;
sss.pop();
}
}
return m ;
}
int main()
{ //2-QUEUE
QueueLL <char> q ;
q.enqueue('a') ;
q.enqueue('b') ;
q.enqueue('c') ;
q.enqueue('d') ;
cout << q.Reverse (2 ) ;
//1-Stack
StackLL <int > s ;
s.push(1); s.push(2);
s.push(4); s.push(3);
s.push(5);
cout << s.getMax () ;
return 0;
}
| 16.766667
| 43
| 0.445328
|
diptu
|
668b330b93d84dd01a682426fbe99ced2598a426
| 1,210
|
cpp
|
C++
|
vanilla/34-find_first_and_last_position_of_element_in_sorted_array.cpp
|
Junlin-Yin/myLeetCode
|
8a33605d3d0de9faa82b5092a8e9f56b342c463f
|
[
"MIT"
] | null | null | null |
vanilla/34-find_first_and_last_position_of_element_in_sorted_array.cpp
|
Junlin-Yin/myLeetCode
|
8a33605d3d0de9faa82b5092a8e9f56b342c463f
|
[
"MIT"
] | null | null | null |
vanilla/34-find_first_and_last_position_of_element_in_sorted_array.cpp
|
Junlin-Yin/myLeetCode
|
8a33605d3d0de9faa82b5092a8e9f56b342c463f
|
[
"MIT"
] | null | null | null |
class Solution {
public:
//找到非降序数组中首个大于(等于)目标数的下标,以下两种均可
//注意r的初始赋值、迭代式和循环条件中的取等情况
int binarySearch(vector<int>& nums, int target, bool allow_eq){
int l = 0, r = nums.size() - 1, mid;
while(l <= r){
mid = (l + r) >> 1;
if((eq && nums[mid] < target) || (!eq && nums[mid] <= target)) l = mid + 1;
else r = mid - 1;
}
return l;
}
int binarySearch(vector<int>& nums, int target, bool allow_eq){
int l = 0, r = nums.size(), mid;
while(l < r){
mid = (l + r) >> 1;
if((eq && nums[mid] < target) || (!eq && nums[mid] <= target)) l = mid + 1;
else r = mid;
}
return l;
}
vector<int> searchRange(vector<int>& nums, int target) {
int first = binarySearch(nums, target, true);
if(first >= nums.size() || nums[first] != target) first = -1;
int second = first == -1 ? -1 : binarySearch(nums, target, false)-1;
vector<int> ans = {first, second};
return ans;
}
};
| 37.8125
| 89
| 0.428926
|
Junlin-Yin
|
668f0e3d40e90a9d5d1b759b8223cc378ad9c16d
| 2,685
|
hpp
|
C++
|
third_party/gfootball_engine/src/framework/scheduler.hpp
|
Jonas1711/football
|
6a20dcb832da71d4e97e094e4afa060533aa7dcc
|
[
"Apache-2.0"
] | 2
|
2021-03-16T06:46:38.000Z
|
2021-09-14T02:01:16.000Z
|
third_party/gfootball_engine/src/framework/scheduler.hpp
|
Jonas1711/football
|
6a20dcb832da71d4e97e094e4afa060533aa7dcc
|
[
"Apache-2.0"
] | null | null | null |
third_party/gfootball_engine/src/framework/scheduler.hpp
|
Jonas1711/football
|
6a20dcb832da71d4e97e094e4afa060533aa7dcc
|
[
"Apache-2.0"
] | 4
|
2020-07-30T17:02:42.000Z
|
2022-01-03T19:32:53.000Z
|
// Copyright 2019 Google LLC & Bastiaan Konings
// 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.
// written by bastiaan konings schuiling 2008 - 2014
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#ifndef _HPP_SCHEDULER
#define _HPP_SCHEDULER
#include "../defines.hpp"
#include "../systems/isystemtask.hpp"
#include "../types/iusertask.hpp"
#include "tasksequence.hpp"
namespace blunted {
struct TaskSequenceProgram {
boost::shared_ptr<TaskSequence> taskSequence;
int programCounter = 0;
int previousProgramCounter = 0;
unsigned long sequenceStartTime = 0;
unsigned long lastSequenceTime = 0;
unsigned long startTime = 0;
int timesRan = 0;
// set to true if sequence is finished
bool readyToQuit = false;
};
// sort of 'light version' of the above, meant as informative to return to nosey enquirers
struct TaskSequenceInfo {
TaskSequenceInfo() {
sequenceStartTime_ms = 0;
lastSequenceTime_ms = 0;
startTime_ms = 0;
sequenceTime_ms = 0;
timesRan = 0;
}
unsigned long sequenceStartTime_ms = 0;
unsigned long lastSequenceTime_ms = 0;
unsigned long startTime_ms = 0;
int sequenceTime_ms = 0;
int timesRan = 0;
};
struct TaskSequenceQueueEntry {
TaskSequenceQueueEntry() {
timeUntilDueEntry_ms = 0;
}
boost::shared_ptr<TaskSequenceProgram> program;
long timeUntilDueEntry_ms = 0;
};
class Scheduler {
public:
Scheduler();
virtual ~Scheduler();
int GetSequenceCount();
void RegisterTaskSequence(boost::shared_ptr<TaskSequence> sequence);
void ResetTaskSequenceTime(const std::string &name);
TaskSequenceInfo GetTaskSequenceInfo(const std::string &name);
/// send due system tasks a SystemTaskMessage_StartFrame message
/// invoke due user tasks with an Execute() call
bool Run();
protected:
unsigned long previousTime_ms = 0;
std::vector < boost::shared_ptr<TaskSequenceProgram> > sequences;
};
}
#endif
| 30.168539
| 132
| 0.707263
|
Jonas1711
|
66968babd49c7d9ec889fb929f4d1d532124cfce
| 1,151
|
cpp
|
C++
|
Dynamic Programming/goldmine.cpp
|
Ajax-07/Java-Questions-and-Solutions
|
816c0b7900340ddc438cb8091fbe64f7b56232cc
|
[
"MIT"
] | null | null | null |
Dynamic Programming/goldmine.cpp
|
Ajax-07/Java-Questions-and-Solutions
|
816c0b7900340ddc438cb8091fbe64f7b56232cc
|
[
"MIT"
] | null | null | null |
Dynamic Programming/goldmine.cpp
|
Ajax-07/Java-Questions-and-Solutions
|
816c0b7900340ddc438cb8091fbe64f7b56232cc
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int maxGold(int n, int m, vector<vector<int>> arr){
int ans = 0;
if(n==1){
for(int j=0; j<m; j++)
ans += arr[0][j];
return ans;
}
int dp[n][m];
for(int i=n-1; i>=0; i--)
dp[i][m-1] = arr[i][m-1];
ans=INT_MIN;
for(int j=m-2; j>=0; j--){
for(int i=0; i<n; i++){
if(i==0)
dp[i][j] = arr[i][j]+max(dp[i][j+1],dp[i+1][j+1]) ;
else if(i==n-1)
dp[i][j] = arr[i][j]+max(dp[i-1][j+1], dp[i][j+1]);
else
dp[i][j] = arr[i][j]+max(dp[i][j+1],max(dp[i-1][j+1], dp[i+1][j+1]));
}
}
for(int i=0; i<n; i++)
ans = max(ans,dp[i][0]);
return ans;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n,m; cin >> n >> m;
vector<vector<int>> arr(n);
for(int i=0; i<n; i++)
arr[i].resize(m);
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
cin >> arr[i][j];
cout << maxGold(n, m, arr);
return 0;
}
| 20.553571
| 81
| 0.414422
|
Ajax-07
|
6699f1c26ec120757725350b3486fceea61819c9
| 489
|
cpp
|
C++
|
chapter2/LinkList/practice/Search_K.cpp
|
verfallen/wang-dao
|
ac25e16010f675fa3cee9fe07de394d111ff61f5
|
[
"MIT"
] | null | null | null |
chapter2/LinkList/practice/Search_K.cpp
|
verfallen/wang-dao
|
ac25e16010f675fa3cee9fe07de394d111ff61f5
|
[
"MIT"
] | null | null | null |
chapter2/LinkList/practice/Search_K.cpp
|
verfallen/wang-dao
|
ac25e16010f675fa3cee9fe07de394d111ff61f5
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
/**
* 2.3节 21题
* 思路:定义p,q 两个指针 相差k,当p指向尾结点时,q指向倒数第k个结点
*/
typedef struct LNode
{
int data;
LNode *Link;
} LNode, *LinkList;
int Search_X(LinkList L, int k)
{
LNode *p = L->Link, *q;
int count = 0;
while (p != NULL)
{
if (count < k)
count++;
else
q = q->Link;
p = p->Link;
}
if (count < k)
return 0;
printf("%d", q->data);
return 1;
}
| 13.971429
| 40
| 0.564417
|
verfallen
|
66a1909d52bf9cd1f3642a73ab453ebaa4e5ef9f
| 3,384
|
cpp
|
C++
|
src/cube/src/syntax/cubepl/CubePL0Driver.cpp
|
OpenCMISS-Dependencies/cube
|
bb425e6f75ee5dbdf665fa94b241b48deee11505
|
[
"Cube"
] | null | null | null |
src/cube/src/syntax/cubepl/CubePL0Driver.cpp
|
OpenCMISS-Dependencies/cube
|
bb425e6f75ee5dbdf665fa94b241b48deee11505
|
[
"Cube"
] | null | null | null |
src/cube/src/syntax/cubepl/CubePL0Driver.cpp
|
OpenCMISS-Dependencies/cube
|
bb425e6f75ee5dbdf665fa94b241b48deee11505
|
[
"Cube"
] | 2
|
2016-09-19T00:16:05.000Z
|
2021-03-29T22:06:45.000Z
|
/****************************************************************************
** CUBE http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 1998-2016 **
** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre **
** **
** Copyright (c) 2009-2015 **
** German Research School for Simulation Sciences GmbH, **
** Laboratory for Parallel Programming **
** **
** This software may be modified and distributed under the terms of **
** a BSD-style license. See the COPYING file in the package base **
** directory for details. **
****************************************************************************/
#ifndef __CUBEPL0_DRIVER_CPP
#define __CUBEPL0_DRIVER_CPP 0
#include <vector>
#include <iostream>
#include <sstream>
#include <float.h>
#include <cmath>
#include "CubeTypes.h"
#include "CubeSysres.h"
#include "CubeLocation.h"
#include "CubeLocationGroup.h"
#include "CubeSystemTreeNode.h"
#include "CubePL0Driver.h"
#include "CubePL0Parser.h"
#include "CubePL0Scanner.h"
#include "CubePL0ParseContext.h"
#include "CubePL0MemoryManager.h"
using namespace std;
using namespace cube;
using namespace cubeplparser;
// cube::CubePL0MemoryManager cubepl_memory_manager;
CubePL0Driver::CubePL0Driver( Cube* _cube ) : CubePLDriver( _cube )
{
};
CubePL0Driver::~CubePL0Driver()
{
};
GeneralEvaluation*
CubePL0Driver::compile( istream* strin, ostream* errs )
{
// stringstream strin(cubepl_program);
CubePL0ParseContext* parseContext = new CubePL0ParseContext( cube );
cubeplparser::CubePL0Scanner* lexer = new cubeplparser::CubePL0Scanner( strin, errs, parseContext );
cubeplparser::CubePL0Parser* parser = new cubeplparser::CubePL0Parser( *parseContext, *lexer );
parser->parse();
GeneralEvaluation* formula = parseContext->result;
delete lexer;
delete parser;
delete parseContext;
return formula;
};
bool
CubePL0Driver::test( std::string& cubepl_program, std::string& error_message )
{
stringstream strin( cubepl_program );
stringstream ssout;
CubePL0ParseContext* parseContext = new CubePL0ParseContext( NULL, true );
cubeplparser::CubePL0Scanner* lexer = new cubeplparser::CubePL0Scanner( &strin, &ssout, parseContext );
cubeplparser::CubePL0Parser* parser = new cubeplparser::CubePL0Parser( *parseContext, *lexer );
parser->parse();
string error_output;
ssout >> error_output;
bool _ok = parseContext->syntax_ok;
if ( error_output.length() != 0 )
{
_ok = false;
parseContext->error_message = "CubePL0Scanner cannot recognize token: " + error_output;
}
if ( !_ok )
{
error_message = parseContext->error_message;
}
delete parseContext->result;
delete lexer;
delete parser;
delete parseContext;
return _ok;
}
std::string
CubePL0Driver::printStatus()
{
return "OK";
};
#endif
| 28.677966
| 114
| 0.568262
|
OpenCMISS-Dependencies
|
66a4b30447dfe20b2fab17a11a44a32c5e02122c
| 2,381
|
cpp
|
C++
|
src/kitchen.cpp
|
skvark/JuveFood
|
fed694f93ca2998a3cf77f0d83e246bb272ffcbf
|
[
"MIT"
] | 1
|
2015-02-05T20:00:04.000Z
|
2015-02-05T20:00:04.000Z
|
src/kitchen.cpp
|
skvark/JuveFood
|
fed694f93ca2998a3cf77f0d83e246bb272ffcbf
|
[
"MIT"
] | null | null | null |
src/kitchen.cpp
|
skvark/JuveFood
|
fed694f93ca2998a3cf77f0d83e246bb272ffcbf
|
[
"MIT"
] | 1
|
2019-07-03T12:13:37.000Z
|
2019-07-03T12:13:37.000Z
|
#include "kitchen.h"
#include <QDebug>
Kitchen::Kitchen(unsigned int kitchenId,
unsigned int kitchenInfoId,
unsigned int openInfoId,
unsigned int menuTypeId,
QString name,
QString shortName):
kitchenId_(kitchenId),
kitchenInfoId_(kitchenInfoId),
openInfoId_(openInfoId),
menuTypeId_(menuTypeId),
name_(name),
shortName_(shortName)
{}
QString Kitchen::getKitchenName()
{
return name_;
}
QString Kitchen::getShortName()
{
return shortName_;
}
QString Kitchen::getOpeningHours()
{
if(openingHours_.length() > 2) {
return openingHours_;
} else {
return QString("No data available.");
}
}
void Kitchen::setOpeningHours(QString hours)
{
openingHours_ = hours;
}
QList<QPair<QString, QString> > Kitchen::getByWeekdayQuery(QString lang, QDate date)
{
// format:
// GetMenuByWeekday?KitchenId=6&MenuTypeId=60&Week=50&Weekday=3&lang='fi'&format=json
QList<QPair<QString, QString> > query;
QString language = "Finnish";
if(QString::compare(lang, language) == 0) {
language = "'fi'";
} else {
language = "'en'";
}
// Add query components to a list
query.append(qMakePair(QString("KitchenId"), QString::number(kitchenId_, 10)));
query.append(qMakePair(QString("MenuTypeId"), QString::number(menuTypeId_, 10)));
query.append(qMakePair(QString("Week"), QString::number(date.weekNumber(), 10)));
query.append(qMakePair(QString("Weekday"), QString::number(date.dayOfWeek(), 10)));
// Debug for specific day and week
// query.append(qMakePair(QString("Week"), QString("7")));
// query.append(qMakePair(QString("Weekday"), QString("7")));
query.append(qMakePair(QString("lang"), language));
query.append(qMakePair(QString("format"), QString("json")));
return query;
}
QList<QPair<QString, QString> > Kitchen::getKitchenInfoQuery()
{
// format:
// GetKitchenInfo?KitchenInfoId=2360&format=json
QList<QPair<QString, QString> > query;
query.append(qMakePair(QString("KitchenInfoId"), QString::number(openInfoId_, 10)));
query.append(qMakePair(QString("format"), QString("json")));
query.append(qMakePair(QString("lang"), QString("'fi'")));
return query;
}
| 29.7625
| 89
| 0.636287
|
skvark
|
66abaeb0cd6e5f14cecc43cc598ea64f44436c40
| 2,501
|
cpp
|
C++
|
Game/Source/EntityManager.cpp
|
Hydeon-git/Project2_RPG
|
bed3f6ba412b4f533d6b8c9e401182259fcb43e5
|
[
"MIT"
] | 4
|
2021-02-23T20:18:27.000Z
|
2021-04-17T22:43:01.000Z
|
Game/Source/EntityManager.cpp
|
Hydeon-git/Project2_RPG
|
bed3f6ba412b4f533d6b8c9e401182259fcb43e5
|
[
"MIT"
] | 1
|
2021-02-25T11:10:11.000Z
|
2021-02-25T11:10:11.000Z
|
Game/Source/EntityManager.cpp
|
Hydeon-git/Project2_RPG
|
bed3f6ba412b4f533d6b8c9e401182259fcb43e5
|
[
"MIT"
] | null | null | null |
#include "EntityManager.h"
#include "Player.h"
#include "Enemy.h"
#include "FlyingEnemy.h"
#include "NPC1.h"
#include "NPC2.h"
#include "NPC3.h"
#include "NPC4.h"
#include "NPC5.h"
#include "Enemy1.h"
#include "Enemy2.h"
#include "Enemy3.h"
#include "ModuleParticles.h"
#include "App.h"
#include "Scene.h"
#include "Defs.h"
#include "Log.h"
EntityManager::EntityManager() : Module()
{
name.Create("entitymanager");
}
// Destructor
EntityManager::~EntityManager()
{}
// Called before render is available
bool EntityManager::Awake(pugi::xml_node& config)
{
LOG("Loading Entity Manager");
bool ret = true;
return ret;
}
// Called before quitting
bool EntityManager::CleanUp()
{
if (!active) return true;
return true;
}
Entity* EntityManager::CreateEntity(EntityType type)
{
Entity* ret = nullptr;
switch (type)
{
// L13: Create the corresponding type entity
case EntityType::NPC5: ret = new NPC5(); break;
case EntityType::PLAYER: ret = new Player(); break;
case EntityType::ENEMY: ret = new Enemy(); break;
case EntityType::FLYING_ENEMY: ret = new FlyingEnemy(); break;
case EntityType::PARTICLE: ret = new ModuleParticles(); break;
case EntityType::NPC1: ret = new NPC1(); break;
case EntityType::NPC2: ret = new NPC2(); break;
case EntityType::NPC3: ret = new NPC3(); break;
case EntityType::NPC4: ret = new NPC4(); break;
case EntityType::Enemy1: ret = new Enemy1(); break;
case EntityType::Enemy2: ret = new Enemy2(); break;
case EntityType::Enemy3: ret = new Enemy3(); break;
//case EntityType::ITEM: ret = new Item(); break;
default: break;
}
// Created entities are added to the list
if (ret != nullptr) entities.Add(ret);
return ret;
}
void EntityManager::DestroyEntity(Entity* entity)
{
ListItem <Entity*>* item = entities.start;
while (item != nullptr)
{
if (item->data == entity)
{
entities.Del(item);
break;
}
item = item->next;
}
}
bool EntityManager::PreUpdate()
{
bool ret = true;
ListItem<Entity*>* item = entities.start;
while ((item != nullptr))
{
ret = item->data->PreUpdate();
item = item->next;
}
return ret;
}
bool EntityManager::Update(float dt)
{
if (!app->scene->paused)
{
for (unsigned int i = 0; i < entities.Count(); i++)
{
entities.At(i)->data->Update(dt);
}
}
return true;
}
bool EntityManager::PostUpdate()
{
ListItem<Entity*>* item = entities.start;
while ((item != nullptr))
{
item->data->PostUpdate();
item = item->next;
}
return true;
}
| 18.804511
| 65
| 0.664534
|
Hydeon-git
|
66ad1a5b992e32cff0acc9c3e7c85a7e33d4ea7e
| 3,189
|
cpp
|
C++
|
src/interrupts.cpp
|
kshitej/HobOs
|
21cbe04a882389d402f936eaf0e1dd4c15a140be
|
[
"0BSD"
] | 9
|
2016-07-07T18:12:27.000Z
|
2022-03-11T06:41:38.000Z
|
src/interrupts.cpp
|
solson/spideros
|
a9c34f3aec10283d5623e821d70c2d9fb5fce843
|
[
"0BSD"
] | null | null | null |
src/interrupts.cpp
|
solson/spideros
|
a9c34f3aec10283d5623e821d70c2d9fb5fce843
|
[
"0BSD"
] | null | null | null |
#include "assert.h"
#include "interrupts.h"
#include "display.h"
#include "idt.h"
#include "ports.h"
// TODO: Deal with the magic numbers in this file.
namespace interrupts {
template<int n>
[[gnu::naked]] void interrupt() {
asm volatile("cli");
asm volatile("push %0" : : "i"(n));
asm volatile("jmp interruptCommon");
}
// Set the IDT gates for interrupts from 0 up to N - 1
template<unsigned N>
[[gnu::always_inline]] void setIdtGates() {
setIdtGates<N - 1>();
idt::setGate(N - 1, interrupt<N - 1>, 0x8, 0, 0, idt::INTR32);
}
template<> void setIdtGates<0>() {}
void init() {
remapPic();
setIdtGates<48>();
}
// Master PIC command and data port numbers.
const u16 PIC1_COMMAND_PORT = 0x20;
const u16 PIC1_DATA_PORT = 0x21;
// Slave PIC command and data port numbers.
const u16 PIC2_COMMAND_PORT = 0xA0;
const u16 PIC2_DATA_PORT = 0xA1;
// End-of-interupt command to send to the PICs when we are finished handling an
// interrupt to resume regularly scheduled programming.
const u8 PIC_EOI = 0x20;
// Normally, IRQs 0 to 7 are mapped to entries 8 to 15. This is a problem in
// protected mode, because IDT entry 8 is a Double Fault. Without remapping,
// every time irq0 fires, you get a Double Fault Exception, which is not
// actually what's happening. We send commands to the Programmable Interrupt
// Controller (PICs, also called the 8259s) in order to remap irq0 to 15 to IDT
// entries 32 to 47.
void remapPic() {
// Tell the PICs to wait for our 3 initialization bytes (we want to
// reinitialize).
ports::outb(PIC1_COMMAND_PORT, 0x11);
ports::outb(PIC2_COMMAND_PORT, 0x11);
// Set master PIC offset to 0x20 (= IRQ0 = 32).
ports::outb(PIC1_DATA_PORT, 0x20);
// Set slave PIC offset to 0x28 (= IRQ8 = 40).
ports::outb(PIC2_DATA_PORT, 0x28);
// Set the wiring to 'attached to corresponding interrupt pin'.
ports::outb(PIC1_DATA_PORT, 0x04);
ports::outb(PIC2_DATA_PORT, 0x02);
// We want to use 8086/8088 mode (bit 0).
ports::outb(PIC1_DATA_PORT, 0x01);
ports::outb(PIC2_DATA_PORT, 0x01);
// Restore masking (if a bit is not set_PORT, the interrupts is on).
ports::outb(PIC1_DATA_PORT, 0x00);
ports::outb(PIC2_DATA_PORT, 0x00);
}
IrqHandlerFn irqHandlerFns[16]; // Implicitly zero-initialized.
void setIrqHandler(u32 irqNum, IrqHandlerFn handlerFn) {
assert(irqNum < 16);
irqHandlerFns[irqNum] = handlerFn;
}
extern "C" void interruptHandler(Registers* regs) {
if (regs->interruptNum >= 32 && regs->interruptNum < 48) {
const u32 irqNum = regs->interruptNum - 32;
if (irqHandlerFns[irqNum]) {
irqHandlerFns[irqNum](regs);
} else {
display::println("Got unhandled irq ", irqNum);
}
// We need to send an EOI (end-of-interrupt command) to the interrupt
// controller when we are done. Only send EOI to slave controller if it's
// involved (irqs 8 and up).
if(regs->interruptNum >= 8) {
ports::outb(PIC2_COMMAND_PORT, PIC_EOI);
}
ports::outb(PIC1_COMMAND_PORT, PIC_EOI);
} else {
display::println("Got isr interrupt: ", regs->interruptNum);
// Disable interrupts and halt.
asm volatile("cli; hlt");
}
}
} // namespace interrupts
| 29.803738
| 79
| 0.691753
|
kshitej
|
66ad2f5ba38ad343a121298d8006a45e31af7c9a
| 685
|
cpp
|
C++
|
source/Gui/Animation/AnimationHandler.cpp
|
tillpp/GraphIDE
|
f88f1ca02a8f9f09fe965b69651ea45fbb1b5d1e
|
[
"MIT"
] | 2
|
2021-10-10T00:28:03.000Z
|
2021-11-11T20:33:40.000Z
|
source/Gui/Animation/AnimationHandler.cpp
|
tillpp/GraphIDE
|
f88f1ca02a8f9f09fe965b69651ea45fbb1b5d1e
|
[
"MIT"
] | null | null | null |
source/Gui/Animation/AnimationHandler.cpp
|
tillpp/GraphIDE
|
f88f1ca02a8f9f09fe965b69651ea45fbb1b5d1e
|
[
"MIT"
] | null | null | null |
#include "AnimationHandler.h"
AnimationHandler::AnimationHandler(GuiComponent& g)
:gui(g)
{
}
AnimationHandler::~AnimationHandler()
{
}
Animation* AnimationHandler::createAnimation(std::string name){
if(animations.find(name)!=animations.end()){
return nullptr;
}
Animation* rv = new Animation(&gui,name);
animations[name] = rv;
return rv;
}
void AnimationHandler::use(std::string name){
if(animations.find(name)==animations.end())
return;
currentAnimation = animations[name];
}
void AnimationHandler::update(){
if(currentAnimation)
currentAnimation->update();
}
void AnimationHandler::updateAttribute(){
if(currentAnimation)
currentAnimation->updateAttribute();
}
| 20.757576
| 63
| 0.748905
|
tillpp
|
66b6221709d6fcd49595b7cdf6de8571f5e71e64
| 5,543
|
cpp
|
C++
|
src/terrTriDomain.cpp
|
mnentwig/glTest5
|
004804482fb5bb72c8f32f50464b7feb8cfa12c3
|
[
"MIT"
] | null | null | null |
src/terrTriDomain.cpp
|
mnentwig/glTest5
|
004804482fb5bb72c8f32f50464b7feb8cfa12c3
|
[
"MIT"
] | null | null | null |
src/terrTriDomain.cpp
|
mnentwig/glTest5
|
004804482fb5bb72c8f32f50464b7feb8cfa12c3
|
[
"MIT"
] | null | null | null |
#include "terrTriDomain.h"
#include "terrTri.h"
#include <vector>
#include <algorithm> // std::find
#include <glm/vec2.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/intersect.hpp>
#include "geomUtils2d.hpp"
#include <iostream>
terrTriDomain::terrTriDomain(){
this->state_closed = false;
}
void terrTriDomain::reserveVertexSpace(unsigned int n){
assert(this->state_closed == false);
if (n > this->vertices.size ())
this->vertices.resize (n);
this->trisUsingVertex.resize (n);
}
void terrTriDomain::setVertex(terrTriVertIx index, const glm::vec3& pt){
assert(index < this->vertices.size ());
assert(this->state_closed == false);
// assert(std::find (this->vertices.begin (), this->vertices.end (), pt) == this->vertices.end ());
this->vertices[index] = pt;
assert(this->trisUsingVertex[index] == NULL);
this->trisUsingVertex[index] = new std::vector<terrTri*> ();
}
const glm::vec3& terrTriDomain::getVertex(terrTriVertIx index) const{
return this->vertices[index];
}
#if 0
void terrTriDomain::debug(){
int n01 = 0;
int n12 = 0;
int n20 = 0;
int count = 0;
for (auto it = this->allTerrTris.begin (); it != this->allTerrTris.end (); ++it) {
if ((*it)->getNeighbor01 ()) ++n01;
if ((*it)->getNeighbor12 ()) ++n12;
if ((*it)->getNeighbor20 ()) ++n20;
++count;
}
std::cout << n01 << " " << n12 << " " << n20 << " out of " << count << std::endl;
}
#endif
void terrTriDomain::registerTri(terrTriVertIx p0, terrTriVertIx p1, terrTriVertIx p2){
assert(this->state_closed == false);
terrTri *t = new terrTri (p0, p1, p2);
this->allTerrTris.push_back (t);
std::vector<terrTri*> *n0 = this->trisUsingVertex[p0];
std::vector<terrTri*> *n1 = this->trisUsingVertex[p1];
std::vector<terrTri*> *n2 = this->trisUsingVertex[p2];
for (auto it = n0->begin (); it != n0->end (); ++it) {
if (std::find (n1->begin (), n1->end (), *it) != n1->end ()) {
t->n01 = *it;
(*it)->registerNeighbor (t, p0, p1);
break;
}
}
for (auto it = n1->begin (); it != n1->end (); ++it) {
if (std::find (n2->begin (), n2->end (), *it) != n2->end ()) {
t->n12 = *it;
(*it)->registerNeighbor (t, p1, p2);
break;
}
}
for (auto it = n2->begin (); it != n2->end (); ++it) {
if (std::find (n0->begin (), n0->end (), *it) != n0->end ()) {
t->n20 = *it;
(*it)->registerNeighbor (t, p2, p0);
break;
}
}
// === once neighbor search is complete, add tri to lookup-by-vertex table ===
n0->push_back (t);
n1->push_back (t);
n2->push_back (t);
}
void terrTriDomain::close(){
assert(this->state_closed == false);
// === calculate vertex normals by averaging all tris that use it ===
this->vertexNormals.resize (this->allTerrTris.size ());// note: elements are zeroed via default constructor
for (auto it = this->allTerrTris.begin (); it != this->allTerrTris.end (); ++it) {
terrTri *t = *it;
glm::vec3 normal = t->getNormal (this);
this->vertexNormals[t->getIxV0 ()] += normal;
this->vertexNormals[t->getIxV1 ()] += normal;
this->vertexNormals[t->getIxV2 ()] += normal;
}
// === normalize length of all vertex normals ===
for (auto it = this->vertexNormals.begin (); it != this->vertexNormals.end (); ++it) {
//assert(glm::length (*it) > 1e-3);// vertex without tris using it?
if (glm::length (*it) > 1e-3){ // TODO: why unused vertices?
*it = glm::normalize (*it);
}
}
this->state_closed = true;
}
const glm::vec3& terrTriDomain::getVertexNormal(terrTriVertIx ix) const{
assert(this->state_closed == true);
return this->vertexNormals[ix];
}
terrTriDomain::~terrTriDomain(){
for (auto it = this->allTerrTris.begin (); it != this->allTerrTris.end (); ++it)
delete (*it);
}
terrTri* terrTriDomain::locateTriByVerticalProjection(const glm::vec3& pos){
auto it = this->allTerrTris.begin ();
while (it != this->allTerrTris.end ()) {
terrTri *t = *(it++);
if (geomUtils2d::pointInTriangleNoY (pos, t->getV0 (this), t->getV1 (this), t->getV2 (this))) {
return t;
}
}
return NULL;
}
void terrTriDomain::motion(terrTri** knownLastTri, glm::vec3& position, glm::vec3& dirFwd, glm::vec3& dirUp, float dist){
// === initialize ===
if (*knownLastTri == NULL) {
auto it = this->allTerrTris.begin ();
while (it != this->allTerrTris.end ()) {
terrTri *t = *(it++);
glm::vec2 isBary;
float d;
glm::vec3 v0 = t->getV0 (this);
glm::vec3 v1 = t->getV1 (this);
glm::vec3 v2 = t->getV2 (this);
if (glm::intersectRayTriangle (position, dirUp, v0, v1, v2, isBary, d)) {
*knownLastTri = t;
position = v0 + isBary[0] * (v1 - v0) + isBary[1] * (v2 - v0);
position += dirUp;
// printf("%f %f\n", (double)isBary.x, (double)isBary.y);
break;
}
}
}
}
std::vector<terrTri*>* terrTriDomain::getTrisUsingVertex(terrTriVertIx pt){
return this->trisUsingVertex[pt];
}
#if 0
void terrTriDomain::collectNeighbors(std::vector<terrTri*>* collection, terrTriVertIx pt) const{
// note: below alg is O{N^2} but N is known to be small (typical number of neighbors)
for (auto itSrc = this->trisUsingVertex[pt]->begin (); itSrc != this->trisUsingVertex[pt]->end (); ++itSrc) {
// don't add if already in list
for (auto itDest = collection->begin (); itDest != collection->end (); ++itDest) {
if (*itSrc == *itDest) {
goto neighborIsAlreadyInList;
}
}
collection->push_back(*itSrc);
neighborIsAlreadyInList:;
}
}
#endif
| 31.674286
| 121
| 0.611041
|
mnentwig
|
66b97549d02ce38d4f084c32d7a3ed8d59be8601
| 6,363
|
cpp
|
C++
|
packages/monte_carlo/collision/native/test/tstAceLaw11NuclearScatteringEnergyDistribution.cpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
packages/monte_carlo/collision/native/test/tstAceLaw11NuclearScatteringEnergyDistribution.cpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
packages/monte_carlo/collision/native/test/tstAceLaw11NuclearScatteringEnergyDistribution.cpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
//---------------------------------------------------------------------------//
//!
//! \file tstAceLaw5NuclearScatteringEnergyDistribution.cpp
//! \author Eli Moll
//! \brief Ace law 11 neutron scattering energy distribution unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_Array.hpp>
// FRENSIE Includes
#include "MonteCarlo_UnitTestHarnessExtensions.hpp"
#include "MonteCarlo_AceLaw11NuclearScatteringEnergyDistribution.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_WattDistribution.hpp"
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw11NuclearScatteringEnergyDistribution,
sample_lower_bounds )
{
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
a_distribution;
a_distribution.resize(2);
a_distribution[0].first = 1.0;
a_distribution[0].second = 1.0;
a_distribution[1].first = 2.0;
a_distribution[1].second = 2.0;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
b_distribution;
b_distribution.resize(2);
b_distribution[0].first = 1.0;
b_distribution[0].second = 3.0;
b_distribution[1].first = 2.0;
b_distribution[1].second = 4.0;
// Create the fake stream
std::vector<double> fake_stream( 4 );
fake_stream[0] = 0.75;
fake_stream[1] = 0.75;
fake_stream[2] = 0.5;
fake_stream[3] = 0.1;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
double restriction_energy = 0.05;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution distribution(
a_distribution,
b_distribution,
restriction_energy );
TEST_COMPARE(distribution.sampleEnergy(0.5) ,==,
Utility::WattDistribution::sample( 0.5,
a_distribution[0].second,
b_distribution[0].second,
restriction_energy ));
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw11NuclearScatteringEnergyDistribution,
sample_upper_bounds )
{
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
a_distribution;
a_distribution.resize(2);
a_distribution[0].first = 1.0;
a_distribution[0].second = 1.0;
a_distribution[1].first = 2.0;
a_distribution[1].second = 2.0;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
b_distribution;
b_distribution.resize(2);
b_distribution[0].first = 1.0;
b_distribution[0].second = 3.0;
b_distribution[1].first = 2.0;
b_distribution[1].second = 4.0;
// Create the fake stream
std::vector<double> fake_stream( 4 );
fake_stream[0] = 0.75;
fake_stream[1] = 0.75;
fake_stream[2] = 0.5;
fake_stream[3] = 0.1;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
double restriction_energy = 0.05;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution distribution(
a_distribution,
b_distribution,
restriction_energy );
TEST_COMPARE(distribution.sampleEnergy(3.0) ,==,
Utility::WattDistribution::sample( 3.0,
a_distribution[1].second,
b_distribution[1].second,
restriction_energy ));
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw11NuclearScatteringEnergyDistribution,
sampleEnergy )
{
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
a_distribution;
a_distribution.resize(2);
a_distribution[0].first = 1.0;
a_distribution[0].second = 1.0;
a_distribution[1].first = 2.0;
a_distribution[1].second = 2.0;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
b_distribution;
b_distribution.resize(2);
b_distribution[0].first = 1.0;
b_distribution[0].second = 3.0;
b_distribution[1].first = 2.0;
b_distribution[1].second = 4.0;
// Create the fake stream
std::vector<double> fake_stream( 4 );
fake_stream[0] = 0.75;
fake_stream[1] = 0.75;
fake_stream[2] = 0.5;
fake_stream[3] = 0.1;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
double restriction_energy = 0.05;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution distribution(
a_distribution,
b_distribution,
restriction_energy );
TEST_COMPARE(distribution.sampleEnergy(1.5) ,==,
Utility::WattDistribution::sample( 1.5,
1.5,
3.5,
restriction_energy ));
}
//---------------------------------------------------------------------------//
// Custom main function
//---------------------------------------------------------------------------//
int main( int argc, char** argv )
{
Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();
// Initialize the random number generator
Utility::RandomNumberGenerator::createStreams();
Teuchos::GlobalMPISession mpiSession( &argc, &argv );
return Teuchos::UnitTestRepository::runUnitTestsFromMain( argc, argv );
}
//---------------------------------------------------------------------------//
// tstAceLaw11NuclearScatteringDistribution.cpp
//---------------------------------------------------------------------------//
| 33.666667
| 116
| 0.534811
|
lkersting
|
66bb25af7ec30d134182e4e14368aa4fccf40ea0
| 4,249
|
cpp
|
C++
|
VectorTest/Vec3SSE.cpp
|
albinopapa/VectorTest
|
bf520ca561a70ef90c3820a797ce60f669693219
|
[
"MIT"
] | null | null | null |
VectorTest/Vec3SSE.cpp
|
albinopapa/VectorTest
|
bf520ca561a70ef90c3820a797ce60f669693219
|
[
"MIT"
] | null | null | null |
VectorTest/Vec3SSE.cpp
|
albinopapa/VectorTest
|
bf520ca561a70ef90c3820a797ce60f669693219
|
[
"MIT"
] | null | null | null |
#include "Vec3SSE.h"
using namespace SSE_Utils::Float4_Utils;
Vec3SSE::Vec3SSE()
:
v(ZeroPS)
{}
Vec3SSE::Vec3SSE(float S)
:
v(_mm_set1_ps(S)) // Set all elements to S (S, S, S, S)
{
// Zero out the last element as it won't be used (v, v, v, 0.0f)
//FLOAT4 t = _mm_shuffle_ps(v, _mm_setzero_ps(), _MM_SHUFFLE(0, 0, 2, 1));
FLOAT4 t = Shuffle<Axy | Bxy>(ZeroPS, v);
v = Shuffle<Axy | Bxz>(v, t);
}
Vec3SSE::Vec3SSE(float X, float Y, float Z)
:
v(_mm_set_ps(0.0f, Z, Y, X)) // SSE registers are setup backward
{}
Vec3SSE::Vec3SSE(const FLOAT4 &V)
:
v(V)
{}
Vec3SSE::Vec3SSE(const Vector3 &V)
:
v(_mm_set_ps(0.0f, V.z, V.y, V.x))
{}
Vec3SSE::Vec3SSE(const Vec3SSE &V)
:
v(V.v)
{}
Vec3SSE Vec3SSE::operator&(const Vec3SSE &V)const
{
return{ v & V.v };
}
Vec3SSE Vec3SSE::operator|(const Vec3SSE &V)const
{
return v | V.v;
}
Vec3SSE Vec3SSE::AndNot(const Vec3SSE &V)
{
return{ SSE_Utils::Float4_Utils::AndNot(v, V.v) };
}
Vec3SSE Vec3SSE::operator-()const
{
return{ -v };
}
Vec3SSE Vec3SSE::operator+(const Vec3SSE &V)const
{
return v + V.v;
}
Vec3SSE Vec3SSE::operator-(const Vec3SSE &V)const
{
return v - V.v;
}
Vec3SSE Vec3SSE::operator*(const float S)const
{
return v * S;
}
Vec3SSE Vec3SSE::operator*(const Vec3SSE &V)const
{
return v * V.v;
}
Vec3SSE Vec3SSE::operator/(const float S)const
{
return v / S;
}
Vec3SSE Vec3SSE::operator/(const Vec3SSE &V)const
{
return v / V.v;
}
Vec3SSE & Vec3SSE::operator+=(const Vec3SSE &V)
{
v += V.v;
return (*this);
}
Vec3SSE & Vec3SSE::operator-=(const Vec3SSE &V)
{
v -= V.v;
return (*this);
}
Vec3SSE & Vec3SSE::operator*=(const Vec3SSE &V)
{
v *= V.v;
return (*this);
}
Vec3SSE & Vec3SSE::operator/=(const Vec3SSE &V)
{
v /= V.v;
v = v & LoadFloat4(xyzMask);
return (*this);
}
Vec3SSE Vec3SSE::MultiplyAdd(const Vec3SSE &V0, const Vec3SSE &V1)
{
return V1.v + (v * V0.v);
}
Vec3SSE Vec3SSE::Dot(const Vec3SSE &V)const
{
/*
The dot product of a vector3 is X0*X1 + Y0*Y1 + Z0*Z1
In SSE we can vertically multiply:
X0 Y0 Z0
* X1 Y1 Z1
------------------
Xr Yr Zr
In order to add the results together we have to shuffle the elements
YrXrZr
then add them together
Xr Yr Zr
+ Yr Xr Zr
------------------
XYr YXr ZZr
This means X and Y have the same values but Z has been doubled, so we
have to shuffle in the Zr from the previous operation and add it's value
to the XYrYXr sum and copy XYr to the Zr position so that all 3 (X, Y and Z)
all have the same result
XYr YXr Zr
+ Zr Zr XYr
------------------
XYZr YXZr ZXYr
*/
FLOAT4 t0 = v * V.v;
FLOAT4 t1 = Shuffle<Ayx | Bzw>(t0, t0);
t0 += t1;
t0 = Shuffle<Axy | Bzw>(t0, t1);
t1 = Shuffle<Azz | Bxw>(t0, t0);
t0 += t1;
return t0;
}
Vec3SSE Vec3SSE::Cross(const Vec3SSE &V)const
{
FLOAT4 u0 = Shuffle<Ayz | Bxw>(v);
FLOAT4 u1 = Shuffle<Azx | Byw>(v);
FLOAT4 v0 = Shuffle<Ayz | Bxw>(V.v);
FLOAT4 v1 = Shuffle<Azx | Byw>(V.v);
FLOAT4 result = (u0 * v1) - (u1 * v0);
return result;
}
Vec3SSE Vec3SSE::Length()const
{
return{ SqrRoot(Dot(*this).v) };
}
Vec3SSE Vec3SSE::LengthSquare()const
{
return Dot(*this);
}
Vec3SSE Vec3SSE::InverseLength()const
{
FLOAT4 t0 = RecipSqrRoot(LengthSquare().v);
// Zero W component
FLOAT4 t1 = Shuffle<Axy | Bxx>(t0, ZeroPS);
t0 = Shuffle<Axy | Bxz>(t0, t1);
return t0;
}
Vec3SSE Vec3SSE::Normalize()
{
return ((*this) * InverseLength());
}
Vec3SSE Vec3SSE::SplatX()const
{
return Shuffle<XXXX>(v);
}
Vec3SSE Vec3SSE::SplatY()const
{
return Shuffle<YYYY>(v);
}
Vec3SSE Vec3SSE::SplatZ()const
{
return Shuffle<ZZZZ>(v);
}
Vector3 Vec3SSE::StoreFloat()const
{
Vector3 temp;
temp.x = X();
temp.y = Y();
temp.z = Z();
return temp;
}
Vector3 Vec3SSE::StoreInt()const
{
Vector3 temp;
temp.b = _mm_cvt_ss2si(v);
temp.g = _mm_cvt_ss2si(Shuffle<Ayx>(v));
temp.r = _mm_cvt_ss2si(Shuffle<Azx>(v));
return temp;
}
Vector3 Vec3SSE::StoreIntCast()
{
Vector3 temp;
Vector4 t;
_mm_store_si128((PDQWORD)&t, _mm_castps_si128(v));
temp.ix = t.iX;
temp.iy = t.iY;
temp.iz = t.iZ;
return temp;
}
float Vec3SSE::X()const
{
return _mm_cvtss_f32(v);
}
float Vec3SSE::Y()const
{
Vec3SSE t = SplatY();
return _mm_cvtss_f32(t.v);
}
float Vec3SSE::Z()const
{
Vec3SSE t = SplatZ();
return _mm_cvtss_f32(t.v);
}
| 18.393939
| 77
| 0.646976
|
albinopapa
|
66bc9546b85d0c4f77b87c79cf4bce72b7965ec1
| 234
|
c++
|
C++
|
10.1.character.c++
|
Sambitcr-7/DSA-C-
|
f3c80f54fa6160a99f39a934f330cdf40711de50
|
[
"Apache-2.0"
] | null | null | null |
10.1.character.c++
|
Sambitcr-7/DSA-C-
|
f3c80f54fa6160a99f39a934f330cdf40711de50
|
[
"Apache-2.0"
] | null | null | null |
10.1.character.c++
|
Sambitcr-7/DSA-C-
|
f3c80f54fa6160a99f39a934f330cdf40711de50
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
char arr[100] = "apple";
int i=0;
while(arr[i]!='\0')
{
cout<<arr[i]<<endl;
i++;
}
return 0;
}
| 9.75
| 29
| 0.380342
|
Sambitcr-7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.