blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
e1e6ae86a9a4117f5eb716a524eb02f3abbb13c3
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case10/Case/case4/1500/p_rgh
81f0303d38b665f7679abb778caefa5adaa0fd9e
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
4,912
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "1500"; object p_rgh; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField nonuniform List<scalar> 459 ( 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101325 101325 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101325 101325 101326 101326 101325 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101325 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101325 101325 101325 101325 101325 101325 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101325 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101326 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101326 101326 101326 101326 101325 101325 101325 101326 101326 101326 101326 101326 101326 101326 101326 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101326 101326 101326 101326 101326 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101326 101326 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 101325 ) ; boundaryField { floor { type zeroGradient; } ceiling { type zeroGradient; } sWall { type zeroGradient; } nWall { type zeroGradient; } sideWalls { type empty; } glass1 { type zeroGradient; } glass2 { type zeroGradient; } sun { type zeroGradient; } heatsource1 { type zeroGradient; } heatsource2 { type zeroGradient; } Table_master { type zeroGradient; } Table_slave { type zeroGradient; } inlet { type zeroGradient; } outlet { type fixedValue; value uniform 101325; } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
1f205e464562e674d6eb6e7bff70965552f14db5
d88da10c9e9765137ab2268fba9ff9ba8e77fdeb
/MatrixSolver/Assert.hpp
277abdc6804078067513b6c8c216e8b51c875a2d
[]
no_license
noaford/3DAsymptoticBiofilm
411218f885de8d72d822928153cfeb36c9c5dfe3
30f0b072ec8049a097418b7d120391c6062808c6
refs/heads/master
2020-09-25T04:43:37.219167
2019-12-04T17:18:12
2019-12-04T17:18:12
225,918,363
0
0
null
null
null
null
UTF-8
C++
false
false
2,266
hpp
#ifndef _ASSERT_HPP_10262004_ #define _ASSERT_HPP_10262004_ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief Expanded assert function. /// \ingroup debug ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef NASSERT //------------------------------------------------------------------------------------------------------------------------------// #include <string> #include <iostream> #include <cstdlib> ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Modified Assert Function. /// /// Stops execution and displays an error message if the assertion fails. It is disabled if NASSERT if defined. /// /// \param Assertion [in] Halts program if assertion is false, otherwise does nothing. /// \param ErrorMsg [in] Error message to display if assertion is false. /// \param File [in] Filename to display if assertion is false. Can be obtained from the preprocessor macro __FILE__. /// \param Function [in] Function name to display if assertion is false. Can be obtained from the preprocessor macro __FUNCTION__. /// \param Line [in] Line number to display if assertion is false. Can be obtained from the preprocessor macro __LINE__. /// \ingroup debug ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline void Assert( const bool Assertion, const char* ErrorMsg, const char* File, const char* Function, const int Line ) { if ( !Assertion ) { std::cerr << "\n**** Assertion Failed **** " << ErrorMsg << " - File: " << File << " Function: " << Function << " Line: "; std::cerr << Line << ".\n" << std::endl; abort(); } } #else //------------------------------------------------------------------------------------------------------------------------------// #define Assert( a, b, c, d, e ) //------------------------------------------------------------------------------------------------------------------------------// #endif #endif
[ "nford57@yahoo.com" ]
nford57@yahoo.com
569569f91125ed3e3d00af39e32bda1604d3288b
7e96161a9c6a035e519e298527658838ae35b96d
/core/unit_test/tstLinkedCellList.hpp
55bae93688bcf4d2bf00fc28eebd6c6523b2a544
[ "BSD-3-Clause" ]
permissive
cwsmith/Cabana
3f829b7427636adf0baf3c4f22118d627947a665
062ab61c163bedf69dc06b1ba76f5de37cb15650
refs/heads/master
2020-04-07T17:12:40.540383
2018-11-16T18:41:58
2018-11-16T18:41:58
158,560,677
0
0
BSD-3-Clause
2018-11-21T14:30:31
2018-11-21T14:30:31
null
UTF-8
C++
false
false
7,729
hpp
/**************************************************************************** * Copyright (c) 2018 by the Cabana authors * * All rights reserved. * * * * This file is part of the Cabana library. Cabana is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <Cabana_AoSoA.hpp> #include <Cabana_LinkedCellList.hpp> #include <gtest/gtest.h> namespace Test { //---------------------------------------------------------------------------// void testLinkedList() { // Make an AoSoA with positions and ijk cell ids. enum MyFields { Position = 0, CellId = 1 }; using DataTypes = Cabana::MemberTypes<double[3],int[3]>; using AoSoA_t = Cabana::AoSoA<DataTypes,TEST_MEMSPACE>; using size_type = typename AoSoA_t::memory_space::kokkos_memory_space::size_type; int num_p = 1000; AoSoA_t aosoa( num_p ); // Set the problem so each particle lives in the center of a cell on a // regular grid of cell size 1 and total size 10x10x10. We are making them // in the reverse order we expect the sort to happen. The sort binary // operator should order by i first and k last. int nx = 10; double dx = 1.0; double x_min = 0.0; double x_max = x_min + nx * dx; auto pos = aosoa.slice<Position>(); auto cell_id = aosoa.slice<CellId>(); std::size_t particle_id = 0; for ( int k = 0; k < nx; ++k ) { for ( int j = 0; j < nx; ++j ) { for ( int i = 0; i < nx; ++i, ++particle_id ) { cell_id( particle_id, 0 ) = i; cell_id( particle_id, 1 ) = j; cell_id( particle_id, 2 ) = k; pos( particle_id, 0 ) = x_min + (i + 0.5) * dx; pos( particle_id, 1 ) = x_min + (j + 0.5) * dx; pos( particle_id, 2 ) = x_min + (k + 0.5) * dx; } } } // Create a grid. double grid_delta[3] = {dx,dx,dx}; double grid_min[3] = {x_min,x_min,x_min}; double grid_max[3] = {x_max,x_max,x_max}; // Bin and permute the particles in the grid. First do this by only // operating on a subset of the particles. { std::size_t begin = 250; std::size_t end = 750; Cabana::LinkedCellList<typename AoSoA_t::memory_space> cell_list( aosoa.slice<Position>(), begin, end, grid_delta, grid_min, grid_max ); Cabana::permute( cell_list, aosoa ); // Checking the binning. EXPECT_EQ( cell_list.totalBins(), nx*nx*nx ); EXPECT_EQ( cell_list.numBin(0), nx ); EXPECT_EQ( cell_list.numBin(1), nx ); EXPECT_EQ( cell_list.numBin(2), nx ); // The order should be reversed with the i index moving the slowest // for those that are actually in the binning range. Do this pass // first. We do this by looping through in the sorted order and check // those that had original indices in the sorting range. particle_id = 0; for ( int i = 0; i < nx; ++i ) { for ( int j = 0; j < nx; ++j ) { for ( int k = 0; k < nx; ++k ) { std::size_t original_id = i + j * nx + k * nx * nx; if ( begin <= original_id && original_id < end ) { // Get what should be the local id of the particle in // the newly sorted decomposition. We are looping // through this in k-fastest order (the indexing of // the grid cells) and therefore should get the // particles in their sorted order. int sort_id = begin + particle_id; // Back calculate what we think the ijk indices of // the particle are based on k-fastest ordering. int grid_id = i * nx * nx + j * nx + k; int grid_i = grid_id / (nx*nx); int grid_j = (grid_id / nx) % nx; int grid_k = grid_id % nx; // Check the indices of the particle EXPECT_EQ( cell_id( sort_id, 0 ), grid_i ); EXPECT_EQ( cell_id( sort_id, 1 ), grid_j ); EXPECT_EQ( cell_id( sort_id, 2 ), grid_k ); // Check that we binned the particle and got the right // offset. EXPECT_EQ( cell_list.binSize(i,j,k), 1 ); EXPECT_EQ( cell_list.binOffset(i,j,k), size_type(particle_id) ); // Increment the particle id. ++particle_id; } } } } // For those that are outside the binned range things should be // unchanged and the bins should be unchanged. particle_id = 0; for ( int k = 0; k < nx; ++k ) { for ( int j = 0; j < nx; ++j ) { for ( int i = 0; i < nx; ++i, ++particle_id ) { if ( begin > particle_id || particle_id >= end ) { EXPECT_EQ( cell_id( particle_id, 0 ), i ); EXPECT_EQ( cell_id( particle_id, 1 ), j ); EXPECT_EQ( cell_id( particle_id, 2 ), k ); EXPECT_EQ( cell_list.binSize(i,j,k), 0 ); } } } } } // Now bin and permute all of the particles. { Cabana::LinkedCellList<typename AoSoA_t::memory_space> cell_list( aosoa.slice<Position>(), grid_delta, grid_min, grid_max ); Cabana::permute( cell_list, aosoa ); // Checking the binning. The order should be reversed with the i index // moving the slowest. EXPECT_EQ( cell_list.totalBins(), nx*nx*nx ); EXPECT_EQ( cell_list.numBin(0), nx ); EXPECT_EQ( cell_list.numBin(1), nx ); EXPECT_EQ( cell_list.numBin(2), nx ); particle_id = 0; for ( int i = 0; i < nx; ++i ) { for ( int j = 0; j < nx; ++j ) { for ( int k = 0; k < nx; ++k, ++particle_id ) { EXPECT_EQ( cell_id( particle_id, 0 ), i ); EXPECT_EQ( cell_id( particle_id, 1 ), j ); EXPECT_EQ( cell_id( particle_id, 2 ), k ); EXPECT_EQ( cell_list.cardinalBinIndex(i,j,k), particle_id ); EXPECT_EQ( cell_list.binSize(i,j,k), 1 ); EXPECT_EQ( cell_list.binOffset(i,j,k), size_type(particle_id) ); } } } } } //---------------------------------------------------------------------------// // RUN TESTS //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, linked_list_test ) { testLinkedList(); } //---------------------------------------------------------------------------// } // end namespace Test
[ "slatterysr@ornl.gov" ]
slatterysr@ornl.gov
75709be751c3c82a06f655f66fd22382179ea290
412a08f5d43fcd9dc5e06d2f587efa578ea40e8a
/BOJ/BFS-DFS/boj1707_이분_그래프.cpp
351336f541a863af7ed1f4b26780b5ab8f3878aa
[]
no_license
onww1/Problem-Solving
19b920f5f4caec50a3aded971e1f1e630e8b6c46
86cc8854ef0457f8f7741cbae401af5038f8ae05
refs/heads/master
2022-06-07T15:47:45.685775
2022-05-25T12:59:59
2022-05-25T12:59:59
130,528,244
6
0
null
null
null
null
UTF-8
C++
false
false
1,201
cpp
#include <cstdio> #include <queue> #include <vector> char vertex[20001] = {0, }; std::vector<int> edge[200001]; char converting(char c){ if(c == 'a') return 'b'; return 'a'; } void reset(int V){ for(int i=0; i<=V; i++){ vertex[i] = 0; edge[i].clear(); } } int main(void){ int T, V, E, u, v, isBipartite; char section = 'a'; scanf("%d", &T); while(T--){ isBipartite = 1; scanf("%d %d", &V, &E); reset(V); for(int i=0; i<E; i++){ scanf("%d %d", &u, &v); edge[u].push_back(v); edge[v].push_back(u); } if(V == 1){ printf("YES\n"); continue; } std::queue<int> q; for(int i=1; i<=V; i++){ if(vertex[i]) continue; q.push(i); vertex[i] = section; while(!q.empty()){ u = q.front(); q.pop(); section = converting(vertex[u]); auto endIdx = edge[u].end(); for(auto it = edge[u].begin(); it != endIdx; it++){ int v = *it; if(!vertex[v]) { vertex[v] = section; q.push(v); } else if(vertex[v] == vertex[u]){ isBipartite = 0; break; } } if(!isBipartite) break; } if(!isBipartite) break; } if(isBipartite) printf("YES\n"); else printf("NO\n"); } return 0; }
[ "sewon.dev@gmail.com" ]
sewon.dev@gmail.com
6009897cfc1e602113e5a0c615ca97c4ca4860d4
4a9d9625bcd033928343de5c93dc0df22d5fd55d
/silnik_genetyczny/GAzakres.h
32f5ba6b57c7d42f569d1907c016f328d35c53fc
[]
no_license
stachu5242/Optymalizacja
a8109e3c7bd5ddd2657d7984198af1887f29ee32
d1b7504906b298c9076ccc7759bbfe5154824000
refs/heads/master
2021-01-21T11:30:08.467913
2017-03-08T13:24:15
2017-03-08T13:24:15
83,567,548
0
0
null
null
null
null
ISO-8859-2
C++
false
false
517
h
/***************************************************************/ /* Autorzy: Radosław Szwarc */ /* Krzysztof Ginter */ /***************************************************************/ /// Klasa zawiera dwie liczby które są krańcami przedziału (zmienne publiczne). #ifndef ZAKRES_H #define ZAKRES_H class zakres_class { public: /// Początek przedziału. double a; /// Koniec przedziału. double b; }; #endif // ZAKRES_H
[ "andrzejstachowiak5242@gmail.com" ]
andrzejstachowiak5242@gmail.com
5a4101be17aee5acdf888fc7886cd7d3a12e0bbd
5639a0260d84882dc4c75844b6a6f38870fd0a12
/09/AutoPtrSample2/AutoPtrSample2.cpp
ef5c29b64e75c09b9804dd054e6f73c6ded503a0
[]
no_license
battlerhythm/cpp
ee01f657fa12150a309e5d9516c6ff91773455cf
4d0bbaccfbf03f41d8e967383a98b987c5a8ec83
refs/heads/master
2020-04-19T00:35:59.605204
2019-04-21T19:59:45
2019-04-21T19:59:45
167,851,128
0
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
#include <memory> #include <iostream> using namespace std; class CMyData { public: CMyData() { cout << " CMyData()" << endl; } ~CMyData() { cout << "~CMyData()" << endl; } void TestFunc() { cout << "CMyData::TestFunc()" << endl; } }; int main(int argc, char* argv[]) { auto_ptr<CMyData> ptrTest(new CMyData); auto_ptr<CMyData> ptrNew; cout << "0x" << ptrTest.get() << endl; ptrNew = ptrTest; // Copying 'auto_ptr' pointer to another does not create two equal objects since one has lost its ownership of the pointer. cout << "0x" << ptrTest.get() << endl; ptrTest->TestFunc(); // This line makes error return 0; }
[ "3820361@mobis.co.kr" ]
3820361@mobis.co.kr
10a71e69b03c82e5afa36050a2eb13457e9d51e9
72a176005d398b9d92d4fe087386d0ea3384806c
/random.h
ec65206517041a54f5e819b121af937f1a3e56c9
[ "MIT" ]
permissive
jayvalentine/evosim
72833c8d71317584830463ce5514f62b791f1e45
05c01f38314fb8fb556cfc1736530fff5ec0eb1c
refs/heads/master
2020-12-04T13:17:03.947952
2020-11-22T13:34:00
2020-11-22T13:34:00
231,778,261
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
#ifndef RANDOM_H #define RANDOM_H #include <stdlib.h> #include <vector> namespace Random { void Init(unsigned int seed); double Double(double min, double max); unsigned int UInt(unsigned int min, unsigned int max); int Int(int min, int max); // Template function defined in header. template<class T> T Choice(std::vector<T> options); } template <class T> T Random::Choice(std::vector<T> options) { unsigned int max = options.size() - 1; return options[UInt(0, max)]; } #endif // RANDOM_H
[ "jayv136@gmail.com" ]
jayv136@gmail.com
6e9656c71f28c086debd5a9015226adee0e0c7df
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/4a/036a535a532444/main.cpp
301fa95ab96b117c892b98dd290fcaeddccc33d7
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
#include <future> #include <chrono> #include <thread> #include <iostream> int main() { auto s = [](int n) { std::this_thread::sleep_for(std::chrono::seconds(n)); std::cout << "slept for " << n << " sec., thread id #" << std::this_thread::get_id() << std::endl; return n; }; std::packaged_task<int(int)> task1(s); std::packaged_task<int(int)> task2(s); auto r1 = task1.get_future(); std::thread t1(std::move(task1), 1); t1.detach(); std::cout << "1-st thread detached" << std::endl; auto r2 = task2.get_future(); std::thread t2(std::move(task2), 2); t2.detach(); std::cout << "2-nd thread detached" << std::endl; std::cout << "main thread id #" << std::this_thread::get_id() << std::endl; // here we are waiting for the result std::cout << r1.get() << std::endl; std::cout << r2.get() << std::endl; return 0; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
363e4f034aa52037c7d143770bcfda4de84d3b54
f42d648e4d284402ad465efa682c0e36197c4ec1
/winrt/impl/Windows.Storage.Provider.1.h
93d456a3e8b25768dc4b04a73abf4a2373554881
[]
no_license
kennykerr/modules
61bb39ae34cefcfec457d815b74db766cb6ea686
0faf4cd2fa757739c4a45e296bd24b8e652db490
refs/heads/master
2022-12-24T13:38:01.577626
2020-10-06T17:02:07
2020-10-06T17:02:07
301,795,870
2
0
null
null
null
null
UTF-8
C++
false
false
9,622
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.3.4.5 #ifndef WINRT_Windows_Storage_Provider_1_H #define WINRT_Windows_Storage_Provider_1_H #include "winrt/impl/Windows.Storage.Provider.0.h" WINRT_EXPORT namespace winrt::Windows::Storage::Provider { struct __declspec(empty_bases) ICachedFileUpdaterStatics : Windows::Foundation::IInspectable, impl::consume_t<ICachedFileUpdaterStatics> { ICachedFileUpdaterStatics(std::nullptr_t = nullptr) noexcept {} ICachedFileUpdaterStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ICachedFileUpdaterUI : Windows::Foundation::IInspectable, impl::consume_t<ICachedFileUpdaterUI> { ICachedFileUpdaterUI(std::nullptr_t = nullptr) noexcept {} ICachedFileUpdaterUI(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ICachedFileUpdaterUI2 : Windows::Foundation::IInspectable, impl::consume_t<ICachedFileUpdaterUI2>, impl::require<Windows::Storage::Provider::ICachedFileUpdaterUI2, Windows::Storage::Provider::ICachedFileUpdaterUI> { ICachedFileUpdaterUI2(std::nullptr_t = nullptr) noexcept {} ICachedFileUpdaterUI2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IFileUpdateRequest : Windows::Foundation::IInspectable, impl::consume_t<IFileUpdateRequest> { IFileUpdateRequest(std::nullptr_t = nullptr) noexcept {} IFileUpdateRequest(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IFileUpdateRequest2 : Windows::Foundation::IInspectable, impl::consume_t<IFileUpdateRequest2>, impl::require<Windows::Storage::Provider::IFileUpdateRequest2, Windows::Storage::Provider::IFileUpdateRequest> { IFileUpdateRequest2(std::nullptr_t = nullptr) noexcept {} IFileUpdateRequest2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IFileUpdateRequestDeferral : Windows::Foundation::IInspectable, impl::consume_t<IFileUpdateRequestDeferral> { IFileUpdateRequestDeferral(std::nullptr_t = nullptr) noexcept {} IFileUpdateRequestDeferral(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IFileUpdateRequestedEventArgs : Windows::Foundation::IInspectable, impl::consume_t<IFileUpdateRequestedEventArgs> { IFileUpdateRequestedEventArgs(std::nullptr_t = nullptr) noexcept {} IFileUpdateRequestedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderFileTypeInfo : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderFileTypeInfo> { IStorageProviderFileTypeInfo(std::nullptr_t = nullptr) noexcept {} IStorageProviderFileTypeInfo(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderFileTypeInfoFactory : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderFileTypeInfoFactory> { IStorageProviderFileTypeInfoFactory(std::nullptr_t = nullptr) noexcept {} IStorageProviderFileTypeInfoFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderGetContentInfoForPathResult : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderGetContentInfoForPathResult> { IStorageProviderGetContentInfoForPathResult(std::nullptr_t = nullptr) noexcept {} IStorageProviderGetContentInfoForPathResult(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderGetPathForContentUriResult : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderGetPathForContentUriResult> { IStorageProviderGetPathForContentUriResult(std::nullptr_t = nullptr) noexcept {} IStorageProviderGetPathForContentUriResult(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderItemPropertiesStatics : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderItemPropertiesStatics> { IStorageProviderItemPropertiesStatics(std::nullptr_t = nullptr) noexcept {} IStorageProviderItemPropertiesStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderItemProperty : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderItemProperty> { IStorageProviderItemProperty(std::nullptr_t = nullptr) noexcept {} IStorageProviderItemProperty(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderItemPropertyDefinition : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderItemPropertyDefinition> { IStorageProviderItemPropertyDefinition(std::nullptr_t = nullptr) noexcept {} IStorageProviderItemPropertyDefinition(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderItemPropertySource : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderItemPropertySource> { IStorageProviderItemPropertySource(std::nullptr_t = nullptr) noexcept {} IStorageProviderItemPropertySource(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderPropertyCapabilities : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderPropertyCapabilities> { IStorageProviderPropertyCapabilities(std::nullptr_t = nullptr) noexcept {} IStorageProviderPropertyCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderSyncRootInfo : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderSyncRootInfo> { IStorageProviderSyncRootInfo(std::nullptr_t = nullptr) noexcept {} IStorageProviderSyncRootInfo(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderSyncRootInfo2 : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderSyncRootInfo2> { IStorageProviderSyncRootInfo2(std::nullptr_t = nullptr) noexcept {} IStorageProviderSyncRootInfo2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderSyncRootInfo3 : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderSyncRootInfo3> { IStorageProviderSyncRootInfo3(std::nullptr_t = nullptr) noexcept {} IStorageProviderSyncRootInfo3(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderSyncRootManagerStatics : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderSyncRootManagerStatics> { IStorageProviderSyncRootManagerStatics(std::nullptr_t = nullptr) noexcept {} IStorageProviderSyncRootManagerStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderSyncRootManagerStatics2 : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderSyncRootManagerStatics2> { IStorageProviderSyncRootManagerStatics2(std::nullptr_t = nullptr) noexcept {} IStorageProviderSyncRootManagerStatics2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IStorageProviderUriSource : Windows::Foundation::IInspectable, impl::consume_t<IStorageProviderUriSource> { IStorageProviderUriSource(std::nullptr_t = nullptr) noexcept {} IStorageProviderUriSource(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; } #endif
[ "kenny.kerr@microsoft.com" ]
kenny.kerr@microsoft.com
a8367142527f14336fb5c84d999d49257e514421
051464fb239e33649f9a4691171863a45102671a
/WACClient/Core/WACClient.cpp
5f0d46af04828b55377dd46aa5c25a44d1a4a90d
[]
no_license
bosstonx/WaveAntiCheat
73ed15917a1c8f680f330a71df25da9d19e89a13
4f625dc737b9f85dd0e6021337959baaf5543e74
refs/heads/master
2020-03-19T04:47:41.252809
2017-09-22T16:22:50
2017-09-22T16:22:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include <Windows.h> BOOL APIENTRY DllMain(HMODULE Module, DWORD Reason, LPVOID Reserved) { switch (Reason) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
[ "andrewdepke@gmail.com" ]
andrewdepke@gmail.com
960f0962e3872830492695b7702d37d44b77538b
4dbda871cdfb6ae24ca7c45325de5013bed8a239
/bithorded/lib/assetsessions.hpp
8d0401797ae34e86dafa1d65aad145f4459723ff
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
testmana2/bithorde
28c712148b3252b9ee3242110191c6144d906344
14b6e8edabe8f6460c5158a9c5144abfd801c4ec
refs/heads/master
2021-05-16T17:26:13.678524
2017-01-24T00:25:20
2017-01-24T00:25:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,118
hpp
/* Copyright 2016 Ulrik Mikaelsson <ulrik.mikaelsson@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. */ #ifndef ASSETSESSIONS_HPP #define ASSETSESSIONS_HPP #include "../server/asset.hpp" #include "weakmap.hpp" namespace bithorded { class AssetSessions { bithorded::WeakMap<BinId, UpstreamRequestBinding> _tigerCache; public: UpstreamRequestBinding::Ptr findAsset(const bithorde::BindRead& req); protected: virtual IAsset::Ptr openAsset(const bithorde::BindRead& req) = 0; void add(const BinId& tigerId, const UpstreamRequestBinding::Ptr& asset); }; } #endif // ASSETSESSIONS_HPP
[ "ulrik.mikaelsson@gmail.com" ]
ulrik.mikaelsson@gmail.com
129e46d9095cd276a245b4fde043dd796986895e
dc4dd066e24bf8a64fa28a625b63748c46243250
/src/tools/DAT_functions.cpp
303ed9cf979560001bbff03eacc6a3f7a2498db6
[]
no_license
Okara/Minecraft
7b5173be89628bacd56273708b4146af0313d8dd
614f75df7236663d4c9dab3d6e2ccc7da4cb19f0
refs/heads/master
2021-01-13T01:59:00.577997
2012-06-26T13:48:05
2012-06-26T13:48:05
4,795,538
1
0
null
null
null
null
UTF-8
C++
false
false
3,732
cpp
#include "DAT_header.hpp" C_DAT::C_DAT (void) { m_buffer = NULL; } C_DAT::~C_DAT (void) { if (m_buffer!=NULL) delete (m_buffer); } bool C_DAT::Create (std::vector<std::string> files, std::string destination) { sFileEntry entry; std::ifstream file; std::ofstream datfile; char buffer[1]; memset (&m_header, 0, sizeof(m_header)); memcpy (m_header.uniqueID, "JGDAT", 5); memcpy (m_header.version, "0.1", 3); m_header.nb_files = files.size(); for (unsigned int i = 0; i<files.size(); i++) { file.open (files[i].c_str(), std::ifstream::in | std::ifstream::binary); if (file.is_open()) { memset (&entry, 0, sizeof(sFileEntry) ); memcpy (entry.name, files[i].c_str(), strlen ( files[i].c_str() ) ); file.seekg (0, std::ios::end); entry.size = file.tellg(); entry.offset = 0; file.close(); m_entries.push_back(entry); } else { std::cout<<"File "<<files[i]<<" raise an error."<<std::endl; return (false); } } long actual_offset = 0; actual_offset += sizeof(sDATHeader); actual_offset += m_header.nb_files * sizeof(sFileEntry); for (unsigned int i=0;i<m_entries.size();i++) { m_entries[i].offset = actual_offset; actual_offset += m_entries[i].size; } datfile.open (destination.c_str(), std::ofstream::out | std::ofstream::binary); datfile.write ((char*)&m_header, sizeof(sDATHeader) ); for (unsigned int i=0;i<m_entries.size();i++) { datfile.write ((char*)&m_entries[i], sizeof(sFileEntry) ); } for (unsigned int i = 0; i<m_entries.size(); i++) { file.open (m_entries[i].name, std::ifstream::in | std::ifstream::binary); if (file.is_open()) { file.seekg (0, std::ios::beg); while (file.read (buffer, 1)) { datfile.write (buffer, 1); } file.close(); } file.clear(); } datfile.close(); return (true); } void C_DAT::Read (std::string source) { std::ifstream datfile; sFileEntry entry; memset (&m_header, 0, sizeof(m_header)); datfile.open (source.c_str(), std::ifstream::in | std::ifstream::binary); if (datfile.is_open()) { datfile.seekg (0, std::ios::beg); datfile.read ((char*)&m_header, sizeof(sDATHeader)); for (unsigned int i=0;i<m_header.nb_files;i++) { datfile.read ((char*)&entry, sizeof(sFileEntry)); m_entries.push_back(entry); } m_datfile = source; } datfile.close(); } char* C_DAT::GetFile (std::string filename) { std::ifstream datfile; if (m_buffer != NULL) { delete (m_buffer); m_buffer = NULL; } for (unsigned int i=0; i<m_header.nb_files;i++) { if (m_entries[i].name == filename) { m_buffer = new char[(m_entries[i].size)]; if (m_buffer==NULL) return (NULL); datfile.open (m_datfile.c_str(), std::ifstream::in | std::ifstream::binary); if (datfile.is_open()) { datfile.seekg (m_entries[i].offset, std::ios::beg); datfile.read (m_buffer, m_entries[i].size); datfile.close(); return (m_buffer); } } } return (NULL); } long int C_DAT::GetFileSize (std::string filename) { for (unsigned int i=0; i<m_header.nb_files;i++) { if (m_entries[i].name == filename) { return (m_entries[i].size); } } return (0); }
[ "deblieck.guillaume@laposte.net" ]
deblieck.guillaume@laposte.net
06e61beea5c8bcdceee64861e87e54b764a459a3
c97d9b8a76f06361cbf7266a6952355dcdfb9e68
/Source/CarCpp/VehiclePawn.cpp
a4740426d65a960bd3f1911b3369680cecb0838d
[]
no_license
6amguy/RealisticVehTemplateCPP
1c0ee04e29781fcc5e1013ec8a5284c3de92a66f
5b1b4e912710b62b59d59d8db4b95963ee91d532
refs/heads/master
2023-04-01T10:46:32.146676
2021-04-10T10:26:45
2021-04-10T10:26:45
356,546,477
0
0
null
null
null
null
UTF-8
C++
false
false
4,922
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "VehiclePawn.h" #include "Components/SkeletalMeshComponent.h" #include "GameFramework/SpringArmComponent.h" #include "Camera/CameraComponent.h" #include "Components/InputComponent.h" #include "WheeledVehicleMovementComponent4W.h" static const FName NAME_SteerInput("Steer"); static const FName NAME_ThrottleInput("Throttle"); AVehiclePawn::AVehiclePawn() { UWheeledVehicleMovementComponent4W* Vehicle4W = CastChecked<UWheeledVehicleMovementComponent4W>(GetVehicleMovement()); // Adjust the tire loading Vehicle4W->MinNormalizedTireLoad = 0.0f; Vehicle4W->MinNormalizedTireLoadFiltered = 0.2f; Vehicle4W->MaxNormalizedTireLoad = 2.0f; Vehicle4W->MaxNormalizedTireLoadFiltered = 2.0f; //Torque setup Vehicle4W->MaxEngineRPM = 5700.0f; Vehicle4W->EngineSetup.TorqueCurve.GetRichCurve()->Reset(); Vehicle4W->EngineSetup.TorqueCurve.GetRichCurve()->AddKey(0.0f, 400.0f); Vehicle4W->EngineSetup.TorqueCurve.GetRichCurve()->AddKey(1890.0f, 500.0f); Vehicle4W->EngineSetup.TorqueCurve.GetRichCurve()->AddKey(57330.0f, 400.0f); //SteeringCurve Vehicle4W->SteeringCurve.GetRichCurve()->Reset(); Vehicle4W->SteeringCurve.GetRichCurve()->AddKey(0.0f, 1.0f); Vehicle4W->SteeringCurve.GetRichCurve()->AddKey(40.0f, 0.7f); Vehicle4W->SteeringCurve.GetRichCurve()->AddKey(120.0f, 0.6f); //Drifting Vehicle4W->DifferentialSetup.DifferentialType = EVehicleDifferential4W::LimitedSlip_4W; Vehicle4W->DifferentialSetup.FrontLeftRightSplit = 0.65; //Automatic gearbox Vehicle4W->TransmissionSetup.bUseGearAutoBox = true; Vehicle4W->TransmissionSetup.GearAutoBoxLatency = 0.15f; Vehicle4W->TransmissionSetup.GearSwitchTime = 1.0f; //SpringArm SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm")); SpringArm->SetupAttachment(RootComponent); SpringArm->TargetArmLength = 250.0f; SpringArm->bUsePawnControlRotation = true; //Camera Component Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("ChaseCamera")); Camera->SetupAttachment(SpringArm, USpringArmComponent::SocketName); Camera->FieldOfView = 90.f; } void AVehiclePawn::Tick(float DeltaTime) { Super::Tick(DeltaTime); UpdateAirControl(DeltaTime); } void AVehiclePawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); //AxisBinding PlayerInputComponent->BindAxis(NAME_ThrottleInput, this, &AVehiclePawn::ApplyThrottle); PlayerInputComponent->BindAxis(NAME_SteerInput, this, &AVehiclePawn::ApplySteering); PlayerInputComponent->BindAxis("LookUp", this, &AVehiclePawn::LookUp); PlayerInputComponent->BindAxis("Turn", this, &AVehiclePawn::Turn); //ActionBinding PlayerInputComponent->BindAction("Handbrake", IE_Pressed, this, &AVehiclePawn::OnHandBrakePressed); PlayerInputComponent->BindAction("Handbrake", IE_Pressed, this, &AVehiclePawn::OnHandBrakeReleased); } void AVehiclePawn::ApplyThrottle(float Val) { GetVehicleMovement()->SetThrottleInput(Val); } void AVehiclePawn::ApplySteering(float Val) { GetVehicleMovement()->SetSteeringInput(Val); } void AVehiclePawn::LookUp(float Val) { if (Val != 0.f) AddControllerPitchInput(Val); } void AVehiclePawn::Turn(float Val) { if (Val != 0.f) { AddControllerYawInput(Val); } } void AVehiclePawn::OnHandBrakePressed() { GetVehicleMovement()->SetHandbrakeInput(true); } void AVehiclePawn::OnHandBrakeReleased() { GetVehicleMovement()->SetHandbrakeInput(false); } void AVehiclePawn::UpdateAirControl(float Deltatime) { if (UWheeledVehicleMovementComponent4W* Vehicle4W = CastChecked<UWheeledVehicleMovementComponent4W>(GetVehicleMovement())) { FCollisionQueryParams QueryParams; QueryParams.AddIgnoredActor(this); const FVector TraceStart = GetActorLocation() + FVector(0.f, 0.f, 50.f); const FVector TraceEnd = GetActorLocation() - FVector(0.f, 0.f, 200.f); FHitResult Hit; //FlipityFlippuCheck const bool bInAir = !GetWorld()->LineTraceSingleByChannel(Hit, TraceStart, TraceEnd, ECC_Visibility, QueryParams); const bool bNotGrounded = FVector::DotProduct(GetActorUpVector(), FVector::UpVector) < 0.1f; //Only Allow in air-movement if (bInAir || bNotGrounded) { const float ForwardInput = InputComponent->GetAxisValue(NAME_ThrottleInput); const float RightInput = InputComponent->GetAxisValue(NAME_SteerInput); //Grounded Roll const float AirMovementForcePitch = 3.f; const float AirMovementForceRoll = !bInAir && bNotGrounded ? 20.f : 3.f; if (UPrimitiveComponent* VehicleMesh = Vehicle4W->UpdatedPrimitive) { const FVector MovementVector = FVector(RightInput * -AirMovementForceRoll, ForwardInput * AirMovementForcePitch, 0.f) * Deltatime * 200.f; const FVector NewAngularMovement = GetActorRotation().RotateVector(MovementVector); VehicleMesh->SetPhysicsAngularVelocity(NewAngularMovement, true); } } } }
[ "69509447+6amguy@users.noreply.github.com" ]
69509447+6amguy@users.noreply.github.com
24ab0003f390ea3b180070d1fe0a8ff5c300d96e
fda54804ce2cae92f8906e365c694ed2f89ec02c
/Macromedia_File_Format_SWF_SDK_11_2_00/Source/HFObject.cpp
24bb70226bd4de8358eb31c42aa7bb76077ed315
[ "MIT" ]
permissive
barrowxu/adobe
b575e1cd0de2207e48fc15180ca3792fff7c77f1
72d59b75faf39ff50dfba0f0b8a82cfe39e8a69f
refs/heads/master
2021-01-24T17:01:21.282684
2017-12-26T17:10:39
2017-12-26T17:10:39
123,221,204
2
0
null
2018-02-28T03:04:30
2018-02-28T03:04:30
null
WINDOWS-1252
C++
false
false
2,879
cpp
// Copyright © 1999 Middlesoft, Inc. All rights reserved. // First Created By Bate Yu. // First Created On 10/15/1999. // Last Modified On 11/09/1999. /**************************************************************************************** File Summary: HFObject.cpp ****************************************************************************************/ #pragma warning( disable : 4786 ) #include "HFObject.h" #include "HFMovie.h" #include "FCT.h" ////////////////////////////////////////////////////////////////////////////////////// // -------- HFObject -------------------------------------------------------------- HFObject::HFObject() { objectID = -1; depth = 1; defineWritten = false; embedded = false; } HFObject::~HFObject() { } // A utility function for the objects to use. It writes the PlaceObject2 tag // to put objects on the stage. void HFObject::AddPlaceObject2( std::list<FObj*> *objList, HFMovie* movie ) { FMatrix* matrix = 0; if ( HasMatrix() ) { matrix = CreateMatrix(); } FCTPlaceObject2 *placeObject = new FCTPlaceObject2( false, // has clip depth false, // has ratio true, // has char id false, // has move GetDepth(), DefineTagId(), matrix, NULL, // color xform 0, // ratio NULL, // name 0); // clip depth objList->push_back( placeObject ); // Record this add for the depth processing later. AddRemoveEvent ar; ar.place = placeObject; ar.remove = 0; ar.originalDepth = GetDepth(); // ar.newDepth = -1; // Now things get strange - since the HFObjects have less scope than the movie, for example: // HFMovie movie; // { // HFRectangle rect(.....); // movie.Frame( 0 )->AddObject( &rect ); // } // movie.Write(.....) // // is valid code. So nothing that needs to persist can be stored in the // objects. So the arLists are stored in the movie, and accessed by the define tag id. std::list<AddRemoveEvent> *arList = movie->GetARList( DefineTagId() ); arList->push_back( ar ); } void HFObject::RemoveFromFrame( std::list<FObj*> *objList, HFMovie* movie ) { FCTRemoveObject *removeObject = new FCTRemoveObject( DefineTagId(), GetDepth()); objList->push_back( removeObject ); // Record this add for the depth processing later. // There should be an add in our arList, for which this remove matches. std::list<AddRemoveEvent> *arList = movie->GetARList( DefineTagId() ); FLASHASSERT( arList->size() > 0 ); // If you get this assert, it means this objects is being // removed but was never added. AddRemoveEvent& ar = arList->back(); FLASHASSERT( ar.place ); // If you get these asserts, it probably means the object is being FLASHASSERT( ar.remove == NULL ); // doubly removed. Or there is an error with the id's. ar.remove = removeObject; }
[ "jdm7dv@gmail.com" ]
jdm7dv@gmail.com
464f8786b481544c6f1cdd9574050f0a1baa7cad
ffc42486797c0315559618da0380f441e1986843
/SDK/slamware_sdk_linux-x86_64-gcc4.8/linux-x86_64-release/include/rpos/features/sweep_motion_planner/feature.h
f7e29da99410401d57c8a9bc3009c27cc4c7a305
[]
no_license
henkeldi/slamwareAPP
a37f22d091157a0e0cde3b067b3bf4d14d7d7479
0d9a5fa60de581580a3db4dfe3b92a73ba6d3fef
refs/heads/master
2020-04-05T12:17:03.437303
2017-07-26T13:01:14
2017-07-26T13:01:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,220
h
/** * feature.h * The Sweep Motion Planner feature * * Created By Tony Huang @ 2015-4-3 * Copyright (c) 2015 Shanghai Slamtec Co., Ltd. */ #pragma once #include <rpos/rpos_config.h> #include <rpos/features/motion_planner/feature.h> #include <rpos/features/sweep_motion_planner/sweep_move_action.h> namespace rpos { namespace features { namespace detail { class SweepMotionPlannerImpl; } class RPOS_CORE_API SweepMotionPlanner : public rpos::features::MotionPlanner { public: typedef detail::SweepMotionPlannerImpl impl_t; RPOS_OBJECT_CTORS_WITH_BASE(SweepMotionPlanner, rpos::features::MotionPlanner); SweepMotionPlanner(boost::shared_ptr<impl_t> impl); ~SweepMotionPlanner(); public: rpos::actions::SweepMoveAction startSweep(); rpos::actions::SweepMoveAction sweepSpot(const rpos::core::Location& location); rpos::actions::MoveAction goHome(); }; } } namespace rpos { namespace core { namespace detail { template <> struct RPOS_CORE_API feature_caster < features::SweepMotionPlanner > { static features::SweepMotionPlanner cast(Feature& v); }; } } }
[ "kint.zhao@slamtec.com" ]
kint.zhao@slamtec.com
d5fcd8768ffd5b8f9d8a16bd180e89a341e7e786
3488d64088f475de18a83f21d225ccd2f1d42756
/module04/ex00/Victim.cpp
ad3deebb8d8768e094d80247510ad9ff852a9279
[ "MIT" ]
permissive
M-Philippe/cpp_piscine
4092b9222e3c4228a60728404223b1fd0bb39708
9584ebcb030c54ca522dbcf795bdcb13a0325f77
refs/heads/main
2023-06-06T22:44:59.193948
2021-07-03T18:42:35
2021-07-03T18:42:35
300,955,988
0
0
null
null
null
null
UTF-8
C++
false
false
772
cpp
#include "Victim.hpp" Victim::Victim() {} Victim::Victim(const std::string& name){ _name = name; std::cout << "A random victim called " << _name << " just appeared!" << std::endl; } Victim::Victim(const Victim &org){ *this = org; } void Victim::getPolymorphed() const { std::cout << _name << " was just polymorphed in a cute little sheep!" << std::endl; } Victim& Victim::operator=(const Victim& org){ _name = org._name; return (*this); } const std::string& Victim::getName() const{ return (_name); } Victim::~Victim(){ std::cout << "The victim " << _name << " died for no apparent reasons!" << std::endl; } std::ostream& operator<<(std::ostream& os, const Victim& fx){ os << "I'm " << fx.getName() << " and I like otters!" << std::endl; return (os); }
[ "m.philippe59@gmail.com" ]
m.philippe59@gmail.com
aa378cc77efb4f1282f01b1eb4731b5b5b306c34
0754325e40716e1a50e4bbf7d33ba18231f70a4c
/src/main/http/verb.cpp
4d7fc8c83354580ac94164567079fd016e74e3f9
[]
no_license
sdt1030433217/poseidon
8907b1a9b4ac61cbee44f1e0dc9c87fe1d4147dc
165f8111ee1eb25e03b056a8ae7a4fbf471257fb
refs/heads/master
2021-01-16T00:10:37.953115
2014-10-23T03:44:23
2014-10-23T03:44:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
666
cpp
#include "../../precompiled.hpp" #include "verb.hpp" using namespace Poseidon; namespace { const char VERB_TABLE[][16] = { "INVALID_VERB", "GET", "POST", "HEAD", "PUT", "DELETE", "TRACE", "CONNECT", "OPTIONS", }; } namespace Poseidon { HttpVerb httpVerbFromString(const char *str){ for(unsigned i = 0; i < COUNT_OF(VERB_TABLE); ++i){ if(std::strcmp(str, VERB_TABLE[i]) == 0){ return static_cast<HttpVerb>(i); } } return HTTP_INVALID_VERB; } const char *stringFromHttpVerb(HttpVerb verb){ unsigned i = static_cast<unsigned>(verb); if(i >= COUNT_OF(VERB_TABLE)){ i = static_cast<unsigned>(HTTP_INVALID_VERB); } return VERB_TABLE[i]; } }
[ "lh_mouse@126.com" ]
lh_mouse@126.com
e49ecace4d1f0f1ec7217c097c89fe9db13dd770
0f11bb938b31c083eb6354e4bd7305ea9239720b
/CFS64MAT/CFS64MAT/crc32.cpp
973af4ffd89fc95bc1837fdb7b18b89943269060
[ "MIT" ]
permissive
solocle/CFS64
73c5a7dee5cf42ea16ccebf288c71ed180099f18
ee78637caf9bc39fb0955373a8588bc2bb0a6121
refs/heads/master
2020-12-25T21:44:42.473419
2016-05-05T13:11:57
2016-05-05T13:11:57
57,405,113
1
0
null
null
null
null
UTF-8
C++
false
false
5,339
cpp
/*- * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or * code or tables extracted from it, as desired without restriction. * * First, the polynomial itself and its table of feedback terms. The * polynomial is * X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 * * Note that we take it "backwards" and put the highest-order term in * the lowest-order bit. The X^32 term is "implied"; the LSB is the * X^31 term, etc. The X^0 term (usually shown as "+1") results in * the MSB being 1 * * Note that the usual hardware shift register implementation, which * is what we're using (we're merely optimizing it by doing eight-bit * chunks at a time) shifts bits into the lowest-order term. In our * implementation, that means shifting towards the right. Why do we * do it this way? Because the calculated CRC must be transmitted in * order from highest-order term to lowest-order term. UARTs transmit * characters in order from LSB to MSB. By storing the CRC this way * we hand it to the UART in the order low-byte to high-byte; the UART * sends each low-bit to hight-bit; and the result is transmission bit * by bit from highest- to lowest-order term without requiring any bit * shuffling on our part. Reception works similarly * * The feedback terms table consists of 256, 32-bit entries. Notes * * The table can be generated at runtime if desired; code to do so * is shown later. It might not be obvious, but the feedback * terms simply represent the results of eight shift/xor opera * tions for all combinations of data and CRC register values * * The values must be right-shifted by eight bits by the "updcrc * logic; the shift must be unsigned (bring in zeroes). On some * hardware you could probably optimize the shift in assembler by * using byte-swap instructions * polynomial $edb88320 * * * CRC32 code derived from work by Gary S. Brown. */ #include "stdafx.h" static uint32_t crc32_tab[] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; uint32_t crc32(uint32_t crc, const void *buf, size_t size) { const uint8_t *p; p = (uint8_t*)buf; crc = crc ^ ~0U; while (size--) crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); return crc ^ ~0U; }
[ "chaios.project@gmail.com" ]
chaios.project@gmail.com
4ae9937d93715af3cb98d14f8ccc05cbbd294787
d9388bd07a1e7335902b0e5863a07b9ccdb8497f
/jacobi/jacobi3.cpp
4bbdbad94afbeb36c0ca1988da60f420d343d96b
[]
no_license
jhg023/brocard
060d763fe27087cae8400797920853236965f95d
a16ea0125f44e3b6bff8b9aa6851e8ea3a9dc02a
refs/heads/master
2022-10-03T14:18:53.484912
2022-09-28T15:43:40
2022-09-28T15:43:40
221,742,644
11
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
static inline int jacobi_modified3( int64_t a, int64_t b, int64_t bit ) { if ( __builtin_expect( a == b, 0 ) ) { return 0; } b >>= 1; unsigned int c = __builtin_ctzll( a ); bit &= c; a >>= c; a >>= 1; do { #pragma unroll( 1 ) for ( unsigned int i = 0; i < 1; ++i ) { int64_t t = a - b; /* If b > a, invoke reciprocity */ bit ^= ( a & ( a >= b ? 0 : b ) ); /* b <-- min (a, b) */ b = a < b ? a : b; /* a <-- |a - b| */ a = ( ( t < 0 ) ? -t : t ); c = __builtin_ctzll( a ) + 1; bit ^= c & ( b ^ ( b >> 1 ) ); a >>= c; } } while( b > 0 ); return bit & 1; }
[ "a.epstein@elsevier.com" ]
a.epstein@elsevier.com
03193b17abdfa011e9cdcd1c106c0b03c5685c3b
6c121e0c3fec192b58572567f06f6bdca8c5132a
/EclipseStudio/Sources/UI/m_LoginGNA.h
7dec4622c8ce57808912028d1f585a6ac1f95cdf
[]
no_license
gamedevforks/src
35555c4a32ce15692cd6cd1343aef16dd3307576
6e7470992ea47990c60ebceeb665a4d8c037c6d2
refs/heads/master
2020-05-21T16:09:56.595652
2014-09-20T22:54:59
2014-09-20T22:54:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
961
h
#pragma once #include "UIMenu.h" class CLoginGNAMenu : public UIMenu { public: enum { RET_Unknown = 0, RET_Exit, RET_Logged, }; CLoginGNAMenu(const char* movieName); virtual ~CLoginGNAMenu(); virtual bool Initialize(); virtual int Update(); const wchar_t* m_ShowMessageIfAny; private: static unsigned int WINAPI LoginGNAProcessThread(void* in_data); HANDLE loginThread; enum { ANS_Unactive, ANS_Processing, ANS_Timeout, ANS_Error, ANS_Logged, ANS_BadPassword, ANS_Frozen, }; volatile DWORD loginAnswerCode; void CheckAnswerCode(); r3dTexture* m_pBackgroundTex; bool loginStarted_; float menuInitTime; // time when menu was initialized void ShowErrorMessage(const wchar_t* msg); void eventLoginBoxAlertOkClick(r3dScaleformMovie* pMovie, const Scaleform::GFx::Value* args, unsigned argCount); void eventFadeOut(r3dScaleformMovie* pMovie, const Scaleform::GFx::Value* args, unsigned argCount); };
[ "muvucasbars@outlook.com" ]
muvucasbars@outlook.com
2e85775b335ec10c5d513671386d0f290091584f
51bf3e7f1633e5691d5d1aef492461c5f15f0ac1
/c10/util/ScopeExit.h
7626bb53f130ed29445c30fccdd7bfff0f0967d7
[]
no_license
quickwritereader/Pytorch_Vec256
6fd1267a4806dfb0afa8ef71f67e5bb63009194f
6f9f4761f57b3fe3145be226ebf9ec55c1b62d37
refs/heads/master
2023-08-23T20:36:12.438768
2021-10-11T02:01:34
2021-10-11T02:01:34
258,939,407
0
0
null
null
null
null
UTF-8
C++
false
false
1,398
h
#pragma once #include <type_traits> #include <utility> namespace c10 { /** * Mostly copied from https://llvm.org/doxygen/ScopeExit_8h_source.html */ template <typename Callable> class scope_exit { Callable ExitFunction; bool Engaged = true; // False once moved-from or release()d. public: template <typename Fp> // constructor accepting a forwarding reference can hide the // move constructor // @lint-ignore CLANGTIDY explicit scope_exit(Fp&& F) : ExitFunction(std::forward<Fp>(F)) {} scope_exit(scope_exit&& Rhs) noexcept : ExitFunction(std::move(Rhs.ExitFunction)), Engaged(Rhs.Engaged) { Rhs.release(); } scope_exit(const scope_exit&) = delete; scope_exit& operator=(scope_exit&&) = delete; scope_exit& operator=(const scope_exit&) = delete; void release() { Engaged = false; } ~scope_exit() { if (Engaged) { ExitFunction(); } } }; // Keeps the callable object that is passed in, and execute it at the // destruction of the returned object (usually at the scope exit where the // returned object is kept). // // Interface is specified by p0052r2. template <typename Callable> scope_exit<typename std::decay<Callable>::type> make_scope_exit(Callable&& F) { return scope_exit<typename std::decay<Callable>::type>( std::forward<Callable>(F)); } } // namespace c10
[ "quickwritereader@gmail.com" ]
quickwritereader@gmail.com
c7959e97a3b18dc65d780a9398896617ce5c1d6a
4fee08e558e77d16ab915f629df74a0574709e8b
/cpsc585/Havok/Physics/Dynamics/Destruction/Utilities/hkpDestructionBreakOffUtil.inl
f910f3689400f2cfb495de1352070ed45388c291
[]
no_license
NinjaMeTimbers/CPSC-585-Game-Project
c6fe97818ffa69b26e6e4dce622079068f5831cc
27a0ce3ef6daabb79e7bdfbe7dcd5635bafce390
refs/heads/master
2021-01-21T00:55:51.915184
2012-04-16T20:06:05
2012-04-16T20:06:05
3,392,986
1
0
null
null
null
null
UTF-8
C++
false
false
3,504
inl
/* * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2011 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. */ #include <Physics/Dynamics/Destruction/Utilities/hkpDestructionSpuUtil.h> // // Flags a rigid body as unbreakable HK_FORCE_INLINE void hkpDestructionBreakOffUtil::_markUnbreakableBody(hkpRigidBody* body) { // Un-mark it as breakable body->m_limitContactImpulseUtilAndFlag = 0; // Remove the contact listener from the body body->removeContactListener(m_entityContactsListener); } // // Returns true if the body is breakable HK_FORCE_INLINE hkBool hkpDestructionBreakOffUtil::canBreak(const hkpRigidBody* body) const { return body && m_entityContactsListener->canBreak(body); } // // Given a hkpCdBody, it returns the owning entity and shape key inline void HK_CALL hkpDestructionBreakOffUtil::ContactListener::getRootEntityAndKey(const hkpCdBody* bodyIn, hkpEntity*& entityOut, hkpShapeKey& keyOut) { const hkpCdBody* rootCollidable = bodyIn; const hkpCdBody* topChild = rootCollidable; while ( rootCollidable->m_parent ) { topChild = rootCollidable; rootCollidable = rootCollidable->m_parent; } keyOut = topChild->getShapeKey(); entityOut = hkpGetRigidBody(reinterpret_cast<const hkpCollidable*>(rootCollidable)); } // // Calculate a maxImpulse value given that current entity is colliding with another at key. // Returns true if the entity is breakable, false otherwise. inline hkBool HK_CALL hkpDestructionBreakOffUtil::ContactListener::getMaxImpulseForKey(hkpShapeKey key, hkpEntity* entity, hkUFloat8& shapeKeyImpulseOut) { // Get rigid body and its breakable body if any const hkpRigidBody* rigidBodySpu = reinterpret_cast<const hkpRigidBody*>(entity); hkpBreakableBody* breakableBodyPpu = const_cast<hkpBreakableBody*>(rigidBodySpu->m_breakableBody); // Try to call the breakable body controller to get the strength if ( breakableBodyPpu ) { // Need to download the breakable body on the SPU HK_DECLARE_SPU_LOCAL_DESTRUCTION_PTR(hkpBreakableBody, breakableBodySpu, sizeof(hkpBreakableBody)); HK_DOWNLOAD_DESTRUCTION_PTR_TO_SPU(breakableBodySpu, breakableBodyPpu, sizeof(hkpBreakableBody)); // Call the body controller to get the strength if ( hkpBreakableBody::Controller::getBodyStrengthAt(breakableBodySpu, rigidBodySpu, key, shapeKeyImpulseOut) ) { return true; } } return false; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20110913) * * Confidential Information of Havok. (C) Copyright 1999-2011 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ "cdebavel@ucalgary.ca" ]
cdebavel@ucalgary.ca
9548206793274e3f873d285198e9dc3b98d1823a
feac469cac55c9779da867e3375c1bbf74ea069a
/triangulo.cpp
5601c1baba4cc325e69aa4808c6e68a36fd67aae
[]
no_license
rrivas-utec/poo1_2020_1_lab209_clases_objetos
53d5426681d7c86776ecdc46c2459a502889460a
8bb7d1691bc54617afbf607502ab9014e52e1734
refs/heads/master
2022-09-27T19:42:34.897337
2020-06-05T15:00:08
2020-06-05T15:00:08
269,122,806
0
0
null
null
null
null
UTF-8
C++
false
false
1,126
cpp
// // Created by utec on 6/3/20. // #include <cmath> #include "triangulo.h" triangulo_t::triangulo_t() { lado_1 = 0; lado_2 = 0; lado_3 = 0; } triangulo_t::triangulo_t(double l1, double l2, double l3) { lado_1 = l1; lado_2 = l2; lado_3 = l3; } double triangulo_t::calcular_area() { auto s = calcular_semi_perimetro(); return sqrt(s*(s-lado_1)*(s-lado_2)*(s-lado_3)); } double triangulo_t::calcular_perimetro() { return lado_1+lado_2+lado_3; } double triangulo_t::calcular_semi_perimetro() { return (lado_1+lado_2+lado_3)/2; } void triangulo_t::set_lado_1(double value) { lado_1 = value; } double triangulo_t::get_lado_1() { return lado_1; } void triangulo_t::set_lado_2(double value) { lado_2 = value; } void triangulo_t::set_lado_3(double value) { lado_3 = value; } double triangulo_t::get_lado_2() { return lado_2; } double triangulo_t::get_lado_3() { return lado_3; } void triangulo_t::set_lados(double a, double b, double c) { lado_1 = a; lado_2 = b; lado_3 = c; } double Circulo::get_area() { } double Rectangulo::get_area() { }
[ "rrivas@utec.edu.pe" ]
rrivas@utec.edu.pe
280b866f45b4416d0187fbda2146aed47821f00f
0c2f777ad73f994dab85eccf8bd39526f65c739b
/Lista/listaSimple/ListaS.cpp
662612a90efdc1c5b5fb87310bfa378181d07645
[]
no_license
HungerWolf-LS/Udemy-Java-Course
6007e0f9c6f31acd8b22adcb335a5ef43b5d45f8
b3138f8f19f98e9c11bc221b49a17aceef8b8d94
refs/heads/master
2021-01-23T06:43:58.884128
2017-07-15T14:47:04
2017-07-15T14:47:04
86,391,379
0
0
null
null
null
null
UTF-8
C++
false
false
1,279
cpp
#include "ListaS.h" #include "NodoS.h" #include <iostream> ListaS::ListaS(){ first = NULL; act = NULL; } void ListaS::Insertar(int e){ NodoS *nuevo = new NodoS(e,NULL); if (listaVacia()){ first = nuevo; } else{ act->sig = nuevo; } act = nuevo; } void ListaS::Mostrar(){ NodoS *temp = first; while(temp){ cout<<temp->val<<"-->"; temp = temp->sig; } cout<<"Null"<<endl; } bool ListaS::listaVacia(){ return first == NULL; } void ListaS::Eliminar(int dat){ NodoS *first1; NodoS *second1; NodoS *firstfirst; NodoS *first1C; NodoS *second1C; NodoS *firstfirstC; int c=0,d=0; first1 = first; second1 = first; firstfirst = first ->sig; first1C = first; second1C = first; firstfirstC = first ->sig; while(c==0 && d==0){ if(first1->val==dat){ first = firstfirst; first ->sig = firstfirst ->sig; second1 = NULL; d=1; }else{ c=1; } } if(c==1){ second1 = first1C; first1 = second1C->sig; firstfirst = first1->sig; while(first1){ if(first1->val==dat){ if(firstfirst==NULL){ second1->sig = NULL; first1 = NULL; act = second1; c=1; }else{ second1->sig = first1->sig; first1 = NULL; c=1; } }else { firstfirst = firstfirst ->sig; first1 = first1->sig; second1= second1->sig; } } } }
[ "leonardo.solano.hw@gmail.com" ]
leonardo.solano.hw@gmail.com
72e58154611c34f44bc9f2e5263bfba915ab2efd
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5652388522229760_0/C++/krismaz/A.cpp
9205a7a2832c9aa85b261f6bfed8afa69c04087a
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,616
cpp
#include <bits/stdc++.h> #define FOR(i,b,e) for(int i=(b); i <= (e); ++i) #define FORD(i,b,e) for(int i=(b); i >= (e); --i) #define SIZE(c) (int) (c).size() #define FORE(i,c) FOR(i,0,SIZE(c)-1) #define FORDE(i,c) FORD(i,SIZE(c)-1,0) #define PB push_back #define MP make_pair #define ST first #define ND second using namespace std; typedef long long int LLI; typedef pair < int , int > PII; typedef pair < LLI , LLI > PLL; typedef vector < int > VI; typedef vector < bool > VB; typedef vector < PII > VP; typedef vector < LLI > VL; typedef vector < PLL > VPL; typedef vector < VI > VVI; typedef vector < VL > VVL; typedef vector < VB > VVB; typedef vector < VP > VVP; const int MOD = 1000000007; const int INF = 1000000001; const LLI LLINF = 1000000000000000001LL; /*************************************************************************/ int solve(int n) { VB dig(10,0); for (int i = n; ; i += n) { int j = i; while (j) { dig[j%10] = 1; j /= 10; } bool all = true; FOR(j,0,9) all = all && dig[j]; if (all) { return i; } } } /*************************************************************************/ int main() { ios_base::sync_with_stdio(0); int t; cin >> t; FOR(i,1,t) { int n; cin >> n; cout << "Case #" << i << ": "; if (!n) cout << "INSOMNIA"; else cout << solve(n); cout << '\n'; } return 0; } /*************************************************************************/
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
cc4392e9b1254c84458fa77e37b51ddf51dd4e4d
2d625f6da7b4145c4dce6634c9a2b72a27330ee0
/week-04/day-03/zoo/mammals.cpp
81a87a851d1b2280a082438e604e68047f76c666
[]
no_license
green-fox-academy/annatakacs
b721d447631c99e6408eb433978422b7a9cc5c4e
70f00a3aacd584af4193a226dbf5ecc267affb62
refs/heads/master
2020-04-16T18:52:13.600935
2019-06-06T11:07:59
2019-06-06T11:07:59
165,838,012
0
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
// // Created by Takacs Anna on 2019-04-24. // #include "mammals.h" Mammals::Mammals(std::string name) : Animals(name) { _name = name; }; std::string Mammals::getName() { return _name; } std::string Mammals::breed() { return " pushing miniature versions out."; }
[ "annatakacs96@gmail.com" ]
annatakacs96@gmail.com
9f1925bcdf8be797f333b5c8c056d71bd678ec19
898527d4796b1dcbe53a1c520ed60cf1a65b5370
/src/Lights/Light.h
8e91fe8051db0cdf7f47490d34226e2819a92644
[]
no_license
ecattell/CattellRT
22e9674ad3e02afefe5d9a8ad600673f8cca588f
786639feaa3eac45bba68ef805d119618f8b42e6
refs/heads/master
2021-01-18T05:00:18.559392
2016-07-09T18:57:38
2016-07-09T18:57:38
19,599,709
0
0
null
null
null
null
UTF-8
C++
false
false
537
h
#ifndef __LIGHT_H__ #define __LIGHT_H__ #include "../MathUtil/RTMath.h" #include "../MathUtil/Vec3f.h" typedef Vec3f Pnt3f; #include "../ImageUtil/Color3f.h" /* * Base class for lights. Inherited by other light classes (e.g. AmbientLight, AreaLight, DirectionalLight, and PointLight) */ class Light { protected: Light(void); public: virtual ~Light(void); Color3f color; const virtual Vec3f getDir(const Pnt3f&);// = 0; const virtual float getDist(const Pnt3f&);// = 0; }; #endif // __LIGHT_H__
[ "elliott@elliottcattell.com" ]
elliott@elliottcattell.com
8d9099ddce3b055872d972b2b26300a1eca0f08c
319c4e17b51b68e2eac9d365a70d53553318c097
/cpp04/ex01/srcs/Brain.cpp
722b8d023f0aefaf8e03e4956b8688fe77c2f89b
[]
no_license
PracticeofEno/CPP
079ea33273d461da1bbba9514bd49bc9f8e59600
192c6febcf79d497702cd95fbe52fb0a3dcd97ba
refs/heads/main
2023-08-22T04:38:38.914669
2021-10-10T03:43:43
2021-10-10T03:43:43
395,391,236
0
0
null
null
null
null
UTF-8
C++
false
false
721
cpp
#include "Brain.hpp" Brain::Brain() { _ideasIndex = 0; std::cout << "Brain create" << std::endl; } Brain::~Brain() { std::cout << "Brain deleted" << std::endl; } void Brain::addIdea(std::string idea) { if (_ideasIndex < 100) { _ideas[_ideasIndex] = idea; _ideasIndex++; } } Brain& Brain::operator=(Brain& tmp) { for (int i = 0; i < tmp.getIndex(); i++) { addIdea(tmp.getIdea(i)); } return *this; } int Brain::getIndex(void) { return _ideasIndex; } std::string Brain::getIdea(int index) { if (_ideasIndex < 100 && _ideasIndex >= 0) { return _ideas[index]; } return ""; } Brain::Brain(Brain& tmp) { _ideasIndex = 0; for (int i = 0; i < tmp.getIndex(); i++) { addIdea(tmp.getIdea(i)); } }
[ "k1990121@gmail.com" ]
k1990121@gmail.com
54733d320821ae941403bbfc5bed7cfa99d29751
3711371c059f75a0847f3ec533a5e05736f330c6
/Open_GL/Gizmos.h
24ec31528cd9b534a9fd5c0b05080258ba47c4e3
[]
no_license
bstelly/OpenGL
d69eb117eb4a8ff26588a6fb329360588e391f9e
649fc36c13afe61596445a637f9d936ab6c362cf
refs/heads/master
2020-03-26T14:40:48.789215
2018-10-19T22:55:55
2018-10-19T22:55:55
144,999,045
0
0
null
2018-08-31T22:11:05
2018-08-16T14:26:23
C
UTF-8
C++
false
false
6,402
h
#pragma once #include <glm> class Gizmos { public: static void create(unsigned int a_maxLines = 0xffff, unsigned int a_maxTris = 0xffff, unsigned int a_max2DLines = 0xff, unsigned int a_max2DTris = 0xff); static void destroy(); // removes all Gizmos static void clear(); // draws current Gizmo buffers, either using a combined (projection * view) matrix, or separate matrices static void draw(const glm::mat4& a_projectionView); static void draw(const glm::mat4& a_projection, const glm::mat4& a_view); // the projection matrix here should ideally be orthographic with a near of -1 and far of 1 static void draw2D(const glm::mat4& a_projection); // Adds a single debug line static void addLine(const glm::vec3& a_rv0, const glm::vec3& a_rv1, const glm::vec4& a_colour); // Adds a single debug line static void addLine(const glm::vec3& a_rv0, const glm::vec3& a_rv1, const glm::vec4& a_colour0, const glm::vec4& a_colour1); // Adds a triangle. static void addTri(const glm::vec3& a_rv0, const glm::vec3& a_rv1, const glm::vec3& a_rv2, const glm::vec4& a_colour); // Adds 3 unit-length lines (red,green,blue) representing the 3 axis of a transform, // at the transform's translation. Optional scale available. static void addTransform(const glm::mat4& a_transform, float a_fScale = 1.0f); // Adds a wireframe Axis-Aligned Bounding-Box with optional transform for rotation/translation. static void addAABB(const glm::vec3& a_center, const glm::vec3& a_extents, const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr); // Adds an Axis-Aligned Bounding-Box with optional transform for rotation. static void addAABBFilled(const glm::vec3& a_center, const glm::vec3& a_extents, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr); // Adds a cylinder aligned to the Y-axis with optional transform for rotation. static void addCylinderFilled(const glm::vec3& a_center, float a_radius, float a_fHalfLength, unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr); // Adds a double-sided hollow ring in the XZ axis with optional transform for rotation. // If a_rvFilLColour.w == 0 then only an outer and inner line is drawn. static void addRing(const glm::vec3& a_center, float a_innerRadius, float a_outerRadius, unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr); // Adds a double-sided disk in the XZ axis with optional transform for rotation. // If a_rvFilLColour.w == 0 then only an outer line is drawn. static void addDisk(const glm::vec3& a_center, float a_radius, unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr); // Adds an arc, around the Y-axis // If a_rvFilLColour.w == 0 then only an outer line is drawn. static void addArc(const glm::vec3& a_center, float a_rotation, float a_radius, float a_halfAngle, unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr); // Adds an arc, around the Y-axis, starting at the inner radius and extending to the outer radius // If a_rvFilLColour.w == 0 then only an outer line is drawn. static void addArcRing(const glm::vec3& a_center, float a_rotation, float a_innerRadius, float a_outerRadius, float a_arcHalfAngle, unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr); // Adds a Sphere at a given position, with a given number of rows, and columns, radius and a max and min long and latitude static void addSphere(const glm::vec3& a_center, float a_radius, int a_rows, int a_columns, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr, float a_longMin = 0.f, float a_longMax = 360, float a_latMin = -90, float a_latMax = 90 ); // Adds a capsule with a set height and radius static void addCapsule(const glm::vec3& a_center, float a_height, float a_radius, int a_rows, int a_cols, const glm::vec4& a_fillColour, const glm::mat4* a_rotation = nullptr); // Adds a single Hermite spline curve static void addHermiteSpline(const glm::vec3& a_start, const glm::vec3& a_end, const glm::vec3& a_tangentStart, const glm::vec3& a_tangentEnd, unsigned int a_segments, const glm::vec4& a_colour); // 2-dimensional gizmos static void add2DLine(const glm::vec2& a_start, const glm::vec2& a_end, const glm::vec4& a_colour); static void add2DLine(const glm::vec2& a_start, const glm::vec2& a_end, const glm::vec4& a_colour0, const glm::vec4& a_colour1); static void add2DTri(const glm::vec2& a_0, const glm::vec2& a_1, const glm::vec2& a_2, const glm::vec4& a_colour); static void add2DAABB(const glm::vec2& a_center, const glm::vec2& a_extents, const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr); static void add2DAABBFilled(const glm::vec2& a_center, const glm::vec2& a_extents, const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr); static void add2DCircle(const glm::vec2& a_center, float a_radius, unsigned int a_segments, const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr); private: Gizmos(unsigned int a_maxLines, unsigned int a_maxTris, unsigned int a_max2DLines, unsigned int a_max2DTris); ~Gizmos(); struct GizmoVertex { float x, y, z, w; float r, g, b, a; }; struct GizmoLine { GizmoVertex v0; GizmoVertex v1; }; struct GizmoTri { GizmoVertex v0; GizmoVertex v1; GizmoVertex v2; }; unsigned int m_shader; // line data unsigned int m_maxLines; unsigned int m_lineCount; GizmoLine* m_lines; unsigned int m_lineVAO; unsigned int m_lineVBO; // triangle data unsigned int m_maxTris; unsigned int m_triCount; GizmoTri* m_tris; unsigned int m_triVAO; unsigned int m_triVBO; unsigned int m_transparentTriCount; GizmoTri* m_transparentTris; unsigned int m_transparentTriVAO; unsigned int m_transparentTriVBO; // 2D line data unsigned int m_max2DLines; unsigned int m_2DlineCount; GizmoLine* m_2Dlines; unsigned int m_2DlineVAO; unsigned int m_2DlineVBO; // 2D triangle data unsigned int m_max2DTris; unsigned int m_2DtriCount; GizmoTri* m_2Dtris; unsigned int m_2DtriVAO; unsigned int m_2DtriVBO; static Gizmos* sm_singleton; };
[ "bstelly1999@gmail.com" ]
bstelly1999@gmail.com
4d369849d2286126f1986a72f0cee58407dcd0f4
dc58925b917a6e791344e19a5c596962fdeb6be0
/LCD/HD44780.cpp
94be1a3a677f4032b288a5e6c48b573f13084333
[]
no_license
kwakkel1000/fireplace
fab52bae47da14e9360b3300f3cdb51bcfe3bdf1
0bf9225dca59a56d1f0c106be0c70c94408ba7db
refs/heads/master
2016-09-05T10:40:35.820643
2013-01-21T23:42:29
2013-01-21T23:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,693
cpp
// HD44780 LCD 4-bit IO mode Driver // (C) 2009 - 2012 Radu Motisan , radu.motisan@gmail.com , www.pocketmagic.net // All rights reserved. // // To be used with AVR Studio 5 (avr-g++.exe) // // HD44780.cpp: Definitions for LCD command instructions // The constants define the various LCD controller instructions which can be passed to the // function lcd_command(), see HD44780 data sheet for a complete description. #include <avr/io.h> #include "HD44780.h" #include "aux_globals.h" // PURPOSE: flush channel E void HD44780::lcd_toggle_e(void) { lcd_e_high(); fcpu_delay_us(10); lcd_e_low(); } // PURPOSE: send a character or an instruction to the LCD void HD44780::lcd_write(uint8_t data,uint8_t rs) { // we cannot check LCD status (no read available) , so we will assume a default delay to wait for lcd to be ready fcpu_delay_us(1600); //check write type if (rs) lcd_rs_high(); //write data else lcd_rs_low(); //write instruciton // configure data pins as output LCD_DDR(LCD_4BIT_D4_PORT) |= _BV(LCD_4BIT_D4_PIN); LCD_DDR(LCD_4BIT_D5_PORT) |= _BV(LCD_4BIT_D5_PIN); LCD_DDR(LCD_4BIT_D6_PORT) |= _BV(LCD_4BIT_D6_PIN); LCD_DDR(LCD_4BIT_D7_PORT) |= _BV(LCD_4BIT_D7_PIN); // output high nibble first LCD_4BIT_D7_PORT &= ~_BV(LCD_4BIT_D7_PIN); LCD_4BIT_D6_PORT &= ~_BV(LCD_4BIT_D6_PIN); LCD_4BIT_D5_PORT &= ~_BV(LCD_4BIT_D5_PIN); LCD_4BIT_D4_PORT &= ~_BV(LCD_4BIT_D4_PIN); if(data & 0x80) LCD_4BIT_D7_PORT |= _BV(LCD_4BIT_D7_PIN); if(data & 0x40) LCD_4BIT_D6_PORT |= _BV(LCD_4BIT_D6_PIN); if(data & 0x20) LCD_4BIT_D5_PORT |= _BV(LCD_4BIT_D5_PIN); if(data & 0x10) LCD_4BIT_D4_PORT |= _BV(LCD_4BIT_D4_PIN); lcd_toggle_e(); // output low nibble LCD_4BIT_D7_PORT &= ~_BV(LCD_4BIT_D7_PIN); LCD_4BIT_D6_PORT &= ~_BV(LCD_4BIT_D6_PIN); LCD_4BIT_D5_PORT &= ~_BV(LCD_4BIT_D5_PIN); LCD_4BIT_D4_PORT &= ~_BV(LCD_4BIT_D4_PIN); if(data & 0x08) LCD_4BIT_D7_PORT |= _BV(LCD_4BIT_D7_PIN); if(data & 0x04) LCD_4BIT_D6_PORT |= _BV(LCD_4BIT_D6_PIN); if(data & 0x02) LCD_4BIT_D5_PORT |= _BV(LCD_4BIT_D5_PIN); if(data & 0x01) LCD_4BIT_D4_PORT |= _BV(LCD_4BIT_D4_PIN); lcd_toggle_e(); // all data pins high (inactive) LCD_4BIT_D4_PORT |= _BV(LCD_4BIT_D4_PIN); LCD_4BIT_D5_PORT |= _BV(LCD_4BIT_D5_PIN); LCD_4BIT_D6_PORT |= _BV(LCD_4BIT_D6_PIN); LCD_4BIT_D7_PORT |= _BV(LCD_4BIT_D7_PIN); } // PURPOSE: send an instruction to the LCD void HD44780::lcd_instr(uint8_t instr) { lcd_write(instr,0); } // PURPOSE: Initialize LCD to 4 bit I/O mode void HD44780::lcd_init() { // configure all port bits as output (LCD data and control lines on different ports LCD_DDR(LCD_RS_PORT) |= _BV(LCD_RS_PIN); LCD_DDR(LCD_E_PORT) |= _BV(LCD_E_PIN); LCD_DDR(LCD_4BIT_D4_PORT) |= _BV(LCD_4BIT_D4_PIN); LCD_DDR(LCD_4BIT_D5_PORT) |= _BV(LCD_4BIT_D5_PIN); LCD_DDR(LCD_4BIT_D6_PORT) |= _BV(LCD_4BIT_D6_PIN); LCD_DDR(LCD_4BIT_D7_PORT) |= _BV(LCD_4BIT_D7_PIN); // wait 25ms or more after power-on fcpu_delay_us(25000); // initial write to lcd is 8bit LCD_4BIT_D5_PORT |= _BV(LCD_4BIT_D5_PIN); // _BV(LCD_FUNCTION)>>4; LCD_4BIT_D4_PORT |= _BV(LCD_4BIT_D4_PIN); // _BV(LCD_FUNCTION_8BIT)>>4; lcd_toggle_e(); fcpu_delay_us(2000); //2000 // delay, busy flag can't be checked here // repeat last command lcd_toggle_e(); fcpu_delay_us(64); //64 // delay, busy flag can't be checked here // now configure for 4bit mode LCD_4BIT_D4_PORT &= ~_BV(LCD_4BIT_D4_PIN); // LCD_FUNCTION_4BIT_1LINE>>4 lcd_toggle_e(); fcpu_delay_us(2000); // some displays need this additional delay // set 4 bit IO lcd_instr(LCD_FUNCTION_4BIT_2LINES); // 4-bit interface, dual line, 5x7 dots lcd_toggle_e(); fcpu_delay_us(2000); // some displays need this additional delay lcd_instr(LCD_ENTRY_INC_);//cursor move right, no shift display lcd_toggle_e(); fcpu_delay_us(2500); // some displays need this additional delay lcd_instr(LCD_DISP_ON_CURSOR_BLINK);// display on, cursor on, blink char lcd_toggle_e(); fcpu_delay_us(2500); // some displays need this additional delay lcd_home();//set cursor to home and clear the cursor } // PURPOSE: send a character to the LCD void HD44780::lcd_char(uint8_t data) { if (data=='\n') { if (g_nCurrentLine >= LCD_LINES - 1) lcd_setline(0); else lcd_setline(g_nCurrentLine+1); } else lcd_write(data,1); } // PURPOSE: send a null terminated string to the LCD eg. char x[10]="hello!"; void HD44780::lcd_string(char *text) { char c; while ( (c = *text++) ) lcd_char(c); } void HD44780::lcd_string_format(char *szFormat, ...) { char szBuffer[256]; //in this buffer we form the message int NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]); int LASTCHAR = NUMCHARS - 1; va_list pArgs; va_start(pArgs, szFormat); vsnprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs); va_end(pArgs); lcd_string(szBuffer); } // PURPOSE: Set cursor to specified position // Input: x horizontal position (0: left most position) // y vertical position (0: first line) void HD44780::lcd_gotoxy(uint8_t x, uint8_t y) { #if LCD_LINES==1 lcd_instr((1<<LCD_DDRAM)+LCD_START_LINE1+x); #elif LCD_LINES==2 switch (y) { case 0:lcd_instr((1<<LCD_DDRAM)+LCD_START_LINE1+x);break; case 1:lcd_instr((1<<LCD_DDRAM)+LCD_START_LINE2+x);break; default: break; } #elif LCD_LINES==4 switch (y) { case 0:lcd_instr((1<<LCD_DDRAM)+LCD_START_LINE1+x);break; case 1:lcd_instr((1<<LCD_DDRAM)+LCD_START_LINE2+x);break; case 2:lcd_instr((1<<LCD_DDRAM)+LCD_START_LINE3+x);break; case 3:lcd_instr((1<<LCD_DDRAM)+LCD_START_LINE4+x);break; default: break; } #endif } // PURPOSE: Move cursor on specified line void HD44780::lcd_setline(uint8_t line) { uint8_t addressCounter = 0; switch(line) { case 0: addressCounter = LCD_START_LINE1; break; case 1: addressCounter = LCD_START_LINE2; break; case 2: addressCounter = LCD_START_LINE3; break; case 3: addressCounter = LCD_START_LINE4; break; default:addressCounter = LCD_START_LINE1; break; } g_nCurrentLine = line; lcd_instr((1<<LCD_DDRAM)+addressCounter); } // PURPOSE: Clear display and set cursor to home position void HD44780::lcd_clrscr(void) { g_nCurrentLine = 0; lcd_instr(1<<LCD_CLR); fcpu_delay_us(500); } // PURPOSE: Set cursor to home position void HD44780::lcd_home(void) { g_nCurrentLine = 0; lcd_instr(1<<LCD_HOME); }
[ "info@gijsweb.net" ]
info@gijsweb.net
d5f8347e88395a24a61fe53864c2ad3a907eeb1d
c351a56ac66c3e46841f6e2935dcf5f1c90032f8
/stack_2.cpp
577eeee02c7f3a103c332bdd919647a823f52a99
[]
no_license
yut-kt/jumbled-cpp
a59040e2f4260c8f83eef1375997b7778df7f7e0
b960562db1aa88e5b2a453cf27349944cc685a77
refs/heads/master
2020-03-10T18:51:47.118497
2018-04-14T16:43:05
2018-04-14T16:43:05
129,535,709
0
0
null
null
null
null
UTF-8
C++
false
false
1,737
cpp
#include <iostream> #include <string> #include <vector> using namespace std; class DataList { int idata; DataList *next; public: DataList(int a = 0,DataList *np = 0) { idata = a; next = np; } int getData() { return idata; } void print() { cout << idata <<" "; } void setNext(DataList *p){ next = p; } DataList *getNext(){ return next; } }; class Stack{ DataList *top; // スタックトップ int length; // スタック内のデータ数(スタックの長さ) public: Stack() { //コンストラクタ top=0; length=0; } void push(int d); // スタックにデータをpushする int back(); // スタックトップのデータを返す void pop(); // スタックトップのデータを取り出す(取り除く) bool empty(){ return length == 0; } // スタックが空かの判定 int size(){ return length; } // スタックの長さを返す }; void Stack::push(int d) { length++; if (top == NULL) { top = new DataList; *top = DataList(d); } else { DataList *head = new DataList; *head = DataList(d, top); top = head; } } int Stack::back() { return top->getData(); } void Stack::pop() { length--; DataList *temp = top; top = temp->getNext(); delete temp; } int main(){ Stack st1; // 空のスタックを作る int x; cout << "num : "; cin >> x; while (x > 0) { st1.push(x % 2); x /= 2; } cout << "2進数 : "; while (!st1.empty()) { cout << st1.back(); st1.pop(); } cout << endl; return 0; }
[ "yut.kt59@gmail.com" ]
yut.kt59@gmail.com
427a7760bb0c0f3adb7d1adbd18e280383ea9e0b
834fa96221815393d6e60cb08b4d7c51ce945ec0
/myrectangle.cpp
f667b1fb2fdc04d8faa2c55e000481366804a9b7
[]
no_license
richardmg/subpixelissue
7b152272533a8dfdefd9f712d459466e3c2bd76a
511e6ac3971bee7f28bf09709dd03ec75f4a6e05
refs/heads/master
2023-01-22T20:09:06.653682
2020-11-23T12:15:50
2020-11-23T12:44:02
315,314,100
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
cpp
#include "myrectangle.h" #include <QtGui/qpainter.h> #include <QtQuick/qsgimagenode.h> #include <QtQuick/qquickwindow.h> #include <QtQml/qqml.h> QT_BEGIN_NAMESPACE MyRectangle::MyRectangle(QQuickItem *parent) : QQuickItem(parent) { setFlag(QQuickItem::ItemHasContents); } QSGNode *MyRectangle::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *) { QSGImageNode *node = static_cast<QSGImageNode *>(oldNode); if (!node) node = window()->createImageNode(); QImage image(QSize(100, 100), QImage::Format_ARGB32_Premultiplied); image.fill(Qt::white); QPainter painter(&image); painter.setPen(QColor(255, 0, 0, 255)); painter.drawRect(QRect(QPoint(0, 0), QSize(50, 10))); auto texture = window()->createTextureFromImage(image); // QRectF bounds = boundingRect(); QRect bounds(QPoint(0, 0), image.size()); node->setSourceRect(bounds); node->setRect(bounds); node->setTexture(texture); return node; } QT_END_NAMESPACE
[ "richard.gustavsen@qt.io" ]
richard.gustavsen@qt.io
50fee68a8f83061a94f61d73cfef118e9381cced
55a3a2af7127a51c66a99e44bf33b539554d6273
/45.cpp
6254b6a91091093fe035689902e5890d8b58a768
[]
no_license
levylv/nowcoder
d367bcbc7105f8738e2d7aab40f07e033d59b021
23be13af2cbe86ea86a6b5c5918e2b7ff0656765
refs/heads/master
2020-04-05T14:03:47.257087
2017-06-28T09:42:20
2017-06-28T09:42:20
94,753,969
0
0
null
null
null
null
UTF-8
C++
false
false
820
cpp
class Solution { public: bool IsContinuous( vector<int> numbers ) { if (numbers.empty()) return false; int len = numbers.size(); sort(numbers.begin(), numbers.end(), compare); int number_zero = 0; for (int i = 0; i < len && numbers[i] == 0; i++) { number_zero++; } int number_gap = 0; int small = number_zero; int big = small + 1; while (big < len) { if (numbers[big] == numbers[small]) return false; number_gap += numbers[big] - numbers[small] - 1; small++; big++; } return (number_gap > number_zero)? false: true; } static bool compare(const int a, const int b) { return (a < b); } };
[ "levy_lv@hotmail.com" ]
levy_lv@hotmail.com
50fb054acbb637b57e194f2f044e4d0ab1caf580
03b5b626962b6c62fc3215154b44bbc663a44cf6
/src/instruction/VGETMANTSD.h
534b7ceddf834e7f0c56b3fa60109a58885df588
[]
no_license
haochenprophet/iwant
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
1c9bd95280216ee8cd7892a10a7355f03d77d340
refs/heads/master
2023-06-09T11:10:27.232304
2023-05-31T02:41:18
2023-05-31T02:41:18
67,756,957
17
5
null
2018-08-11T16:37:37
2016-09-09T02:08:46
C++
UTF-8
C++
false
false
250
h
#ifndef VGETMANTSD_H #define VGETMANTSD_H #include "../object.h" namespace n_VGETMANTSD { class CVGETMANTSD :public Object { public: CVGETMANTSD(); ~CVGETMANTSD(); int my_init(void *p=nullptr); }; } using namespace n_VGETMANTSD; #endif
[ "hao__chen@sina.com" ]
hao__chen@sina.com
7e3cabc3ffc2d5986c719a14fb11361eb2c28283
688a65767f7cab7bb30cf6ab60716849fe703970
/perfsquare.cpp
04efdbea5089ed5352df9aa34b931ed94e737313
[]
no_license
ankyyy/naive
5974ca0f160b48172dcd23da2b3af5770bd47047
68fa4fc306c5e95569ddb14aa35c3642f143fe26
refs/heads/master
2020-04-01T07:59:33.826682
2015-01-23T18:34:40
2015-01-23T18:34:40
21,989,055
0
0
null
null
null
null
UTF-8
C++
false
false
265
cpp
#include <iostream> using namespace std; int main() { int count,t=1,temp=0; cin>>count; for (int i = 0; i < count; ++i) { temp=temp+t; cout<<temp<<" "; t=t+2; } } /*perfect squares are succesive sum of odd nos 1,1+3,1+3+5,1+3+5+7 1, 4, 9, 16 */
[ "ankitm3114@gmail.com" ]
ankitm3114@gmail.com
0e0631f50e1cc0f275df69aeb05e013ade79e712
c093a46434c96b9071f4bbfa8a7c4bf1befa237f
/include/Siv3D/HalfFloat.hpp
0da677d84c6e744c2d9009347b094027a362891e
[]
no_license
mak1a/GoneElect
82415b35e6b39885972a2f9a280cdcfb4a1036af
a8a90cf03302e2335dfa03c10d2e4bcfcbc5aae0
refs/heads/master
2020-05-29T09:35:16.744493
2019-05-29T18:12:42
2019-05-29T18:12:42
189,069,078
1
0
null
null
null
null
UTF-8
C++
false
false
3,417
hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Fwd.hpp" # include "SIMDMath.hpp" # include "Format.hpp" namespace s3d { /// <summary> /// 半精度浮動小数点数 /// </summary> struct HalfFloat { private: uint16 m_bits; public: HalfFloat() = default; HalfFloat(float value) noexcept : m_bits(detail::FloatToHalf(value)) {} [[nodiscard]] operator float() const noexcept { return detail::HalfToFloat(m_bits); } template <class Type, std::enable_if_t<std::is_arithmetic<Type>::value>* = nullptr> HalfFloat(Type value) : HalfFloat(static_cast<float>(value)) {} HalfFloat& operator= (float value) noexcept { return (*this = HalfFloat(value)); } template <class Type> HalfFloat& operator= (Type value) { return (*this = HalfFloat(value)); } [[nodiscard]] bool operator ==(const HalfFloat other) const noexcept { if ((m_bits << 1u) == 0 && (other.m_bits << 1u) == 0) { return true; } return m_bits == other.m_bits && !isNaN(); } [[nodiscard]] bool operator !=(const HalfFloat other) const noexcept { return !(operator ==(other)); } [[nodiscard]] uint16 getBits() const noexcept { return m_bits; } void setBits(const uint16 bits) noexcept { m_bits = bits; } [[nodiscard]] bool isNaN() const noexcept { return (m_bits & 0x7FFFU) == 0x7FFFU; } [[nodiscard]] bool isInfinity() const noexcept { return (m_bits & 0x7FFFU) == 0x7C00U; } [[nodiscard]] int32 getSign() const noexcept { return (m_bits & 0x8000U) ? -1 : 1; } }; } ////////////////////////////////////////////////// // // Format // ////////////////////////////////////////////////// namespace s3d { inline void Formatter(FormatData& formatData, const HalfFloat& value) { return Formatter(formatData, static_cast<float>(value)); } template <class CharType> inline std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& ouput, const HalfFloat& value) { return ouput << static_cast<float>(value); } template <class CharType> inline std::basic_istream<CharType>& operator >>(std::basic_istream<CharType>& input, HalfFloat& value) { float t; if (input >> t) { value = t; } return input; } } ////////////////////////////////////////////////// // // Hash // ////////////////////////////////////////////////// namespace std { template <> struct hash<s3d::HalfFloat> { [[nodiscard]] size_t operator()(const s3d::HalfFloat& value) const noexcept { return hash<s3d::uint16>()(value.getBits()); } }; } ////////////////////////////////////////////////// // // fmt // ////////////////////////////////////////////////// namespace fmt { template <> struct formatter<s3d::HalfFloat, s3d::char32> { s3d::String tag; template <class ParseContext> auto parse(ParseContext& ctx) { return s3d::detail::GetFmtTag(tag, ctx); } template <class Context> auto format(const s3d::HalfFloat value, Context& ctx) { const s3d::String fmt = s3d::detail::MakeFmtArg( U"{:", tag, U"}" ); return format_to(ctx.begin(), wstring_view(fmt.data(), fmt.size()), static_cast<float>(value)); } }; }
[ "g1821120@gmail.com" ]
g1821120@gmail.com
e4204110029988c079f0eed484f02bd0d5c30b6f
2ccb2893e895cae01e508f5a669c39a3a4aeaf71
/Transform/rotatetransform.cpp
9506596d47833840f4454f13bfdb2deaa2ba4ea0
[ "Apache-2.0" ]
permissive
xubenhao/VisualAlgorithm
513942013716fc2caddae8e1cd32318fc50a8bdc
5fc45d9a4fc58569953fe3d880517adcd2fb0881
refs/heads/main
2023-02-28T19:31:51.437208
2021-02-08T02:29:50
2021-02-08T02:29:50
333,267,125
2
0
null
null
null
null
UTF-8
C++
false
false
1,848
cpp
// Author : XuBenHao // Version : 1.0.0 // Mail : xbh370970843@163.com // Copyright : XuBenHao 2020 - 2030 #include "rotatetransform.h" namespace NTransform { RotateTransform::RotateTransform(QObject* parent) : Transform(parent) { m_nAngle = 0.0; } RotateTransform::RotateTransform( NStruct::Point poCenter_, double nAngle_, QObject* parent) : Transform(parent) { m_poCenter = poCenter_; m_nAngle = nAngle_; } NMatrix::Matrix RotateTransform::GetMatrix() { NMatrix::Matrix _mxA; _mxA.Offset(m_poCenter.GetX(), m_poCenter.GetY()); _mxA.Rotate(m_nAngle); _mxA.Offset( -1.0 * m_poCenter.GetX(), -1.0 * m_poCenter.GetY()); return _mxA; } Transform* RotateTransform::DeepCopy() { RotateTransform* _pTrans = new RotateTransform(); _pTrans->m_poCenter = m_poCenter; _pTrans->m_nAngle = m_nAngle; return _pTrans; } void RotateTransform::PrintDebugInfo() { QString _str; _str.sprintf( "this is RotateTransform,Cente.x=%.2f,Center.y=%.2f,Angle=%.2f\n", m_poCenter.GetX(), m_poCenter.GetY(), m_nAngle); QByteArray ba(_str.toUtf8()); qWarning("%s",ba.data()); } void RotateTransform::PrintDebugInfo(QFile& hFile_) { QString _str; _str.sprintf( "this is RotateTransform\nCente.x=%.2f,Center.y=%.2f,Angle=%.2f\n", m_poCenter.GetX(), m_poCenter.GetY(), m_nAngle); QByteArray ba(_str.toUtf8()); hFile_.write(ba); hFile_.flush(); } }
[ "xbh370970843@163.com" ]
xbh370970843@163.com
c9a6cee87b41904d603445388b2cca7f80bb0924
bba8bb04425c9b166323cb5a831c94643cf62b97
/Source/VoxelGraph/Private/Examples/VoxelExample_HollowPlanet.cpp
6e9d5de8515eeafaf83224b48540d33ff4556795
[ "MIT" ]
permissive
jacobcoughenour/VoxelPlugin
2cf2e2195209285fbd8a589d8f994f7caaa651c2
fc2ddcc0d3bd4424a9be73c3ada70c4c5c158184
refs/heads/master
2022-11-11T04:16:35.908916
2020-07-04T11:12:38
2020-07-04T11:12:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,258
cpp
// Copyright 2020 Phyronnaz #include "VoxelExample_HollowPlanet.h" PRAGMA_GENERATED_VOXEL_GRAPH_START using FVoxelGraphSeed = int32; #if VOXEL_GRAPH_GENERATED_VERSION == 1 class FVoxelExample_HollowPlanetInstance : public TVoxelGraphGeneratorInstanceHelper<FVoxelExample_HollowPlanetInstance, UVoxelExample_HollowPlanet> { public: struct FParams { const bool Use_IQ_Noise; const float Noise_Bias; const float Intersection_Smoothness; const float Noise_Frequency; const float Noise_Scale; const float Radius; }; class FLocalComputeStruct_LocalValue { public: struct FOutputs { FOutputs() {} void Init(const FVoxelGraphOutputsInit& Init) { } template<typename T, uint32 Index> T Get() const; template<typename T, uint32 Index> void Set(T Value); v_flt Value; }; struct FBufferConstant { FBufferConstant() {} v_flt Variable_11; // Radius = 250.0 output 0 bool Variable_22; // Use IQ Noise = true output 0 v_flt Variable_16; // Noise Bias = 0.2 output 0 v_flt Variable_17; // Intersection Smoothness = 10.0 output 0 v_flt Variable_19; // Noise Frequency = 4.0 output 0 v_flt Variable_10; // Noise Scale = 20.0 output 0 v_flt Variable_12; // * -1 output 0 }; struct FBufferX { FBufferX() {} v_flt Variable_6; // X output 0 v_flt Variable_0; // X output 0 }; struct FBufferXY { FBufferXY() {} v_flt Variable_7; // Y output 0 v_flt Variable_1; // Y output 0 }; FLocalComputeStruct_LocalValue(const FParams& InParams) : Params(InParams) { } void Init(const FVoxelWorldGeneratorInit& InitStruct) { //////////////////////////////////////////////////// //////////////////// Init nodes //////////////////// //////////////////////////////////////////////////// { //////////////////////////////////////////////////// /////////////// Constant nodes init //////////////// //////////////////////////////////////////////////// { ///////////////////////////////////////////////////////////////////////////////// //////// First compute all seeds in case they are used by constant nodes //////// ///////////////////////////////////////////////////////////////////////////////// // Init of Seed FVoxelGraphSeed Variable_20; // Seed output 0 { static FName StaticName = "Seed"; Variable_20 = InitStruct.Seeds.Contains(StaticName) ? InitStruct.Seeds[StaticName] : 1443; } //////////////////////////////////////////////////// ///////////// Then init constant nodes ///////////// //////////////////////////////////////////////////// } //////////////////////////////////////////////////// //////////////////// Other inits /////////////////// //////////////////////////////////////////////////// Function0_XYZWithoutCache_Init(InitStruct); } //////////////////////////////////////////////////// //////////////// Compute constants ///////////////// //////////////////////////////////////////////////// { // Radius = 250.0 BufferConstant.Variable_11 = Params.Radius; // Use IQ Noise = true BufferConstant.Variable_22 = Params.Use_IQ_Noise; // Noise Bias = 0.2 BufferConstant.Variable_16 = Params.Noise_Bias; // Intersection Smoothness = 10.0 BufferConstant.Variable_17 = Params.Intersection_Smoothness; // Noise Frequency = 4.0 BufferConstant.Variable_19 = Params.Noise_Frequency; // Noise Scale = 20.0 BufferConstant.Variable_10 = Params.Noise_Scale; // * -1 BufferConstant.Variable_12 = BufferConstant.Variable_10 * -1; } } void ComputeX(const FVoxelContext& Context, FBufferX& BufferX) const { Function0_X_Compute(Context, BufferX); } void ComputeXYWithCache(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { Function0_XYWithCache_Compute(Context, BufferX, BufferXY); } void ComputeXYWithoutCache(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { Function0_XYWithoutCache_Compute(Context, BufferX, BufferXY); } void ComputeXYZWithCache(const FVoxelContext& Context, const FBufferX& BufferX, const FBufferXY& BufferXY, FOutputs& Outputs) const { Function0_XYZWithCache_Compute(Context, BufferX, BufferXY, Outputs); } void ComputeXYZWithoutCache(const FVoxelContext& Context, FOutputs& Outputs) const { Function0_XYZWithoutCache_Compute(Context, Outputs); } inline FBufferX GetBufferX() const { return {}; } inline FBufferXY GetBufferXY() const { return {}; } inline FOutputs GetOutputs() const { return {}; } private: FBufferConstant BufferConstant; const FParams& Params; FVoxelFastNoise _3D_IQ_Noise_0_Noise; TStaticArray<uint8, 32> _3D_IQ_Noise_0_LODToOctaves; FVoxelFastNoise _3D_Perlin_Noise_Fractal_0_Noise; TStaticArray<uint8, 32> _3D_Perlin_Noise_Fractal_0_LODToOctaves; /////////////////////////////////////////////////////////////////////// //////////////////////////// Init functions /////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_XYZWithoutCache_Init(const FVoxelWorldGeneratorInit& InitStruct) { // Init of Seed FVoxelGraphSeed Variable_20; // Seed output 0 { static FName StaticName = "Seed"; Variable_20 = InitStruct.Seeds.Contains(StaticName) ? InitStruct.Seeds[StaticName] : 1443; } // Init of 3D IQ Noise _3D_IQ_Noise_0_Noise.SetSeed(Variable_20); _3D_IQ_Noise_0_Noise.SetInterp(FVoxelFastNoise::Quintic); _3D_IQ_Noise_0_Noise.SetFractalOctavesAndGain(15, 0.5); _3D_IQ_Noise_0_Noise.SetFractalLacunarity(2.0); _3D_IQ_Noise_0_Noise.SetFractalType(FVoxelFastNoise::FBM); _3D_IQ_Noise_0_Noise.SetMatrix(ToMatrix(FRotator(40.000000, 45.000000, 50.000000))); _3D_IQ_Noise_0_LODToOctaves[0] = 15; _3D_IQ_Noise_0_LODToOctaves[1] = 15; _3D_IQ_Noise_0_LODToOctaves[2] = 15; _3D_IQ_Noise_0_LODToOctaves[3] = 15; _3D_IQ_Noise_0_LODToOctaves[4] = 15; _3D_IQ_Noise_0_LODToOctaves[5] = 15; _3D_IQ_Noise_0_LODToOctaves[6] = 15; _3D_IQ_Noise_0_LODToOctaves[7] = 15; _3D_IQ_Noise_0_LODToOctaves[8] = 15; _3D_IQ_Noise_0_LODToOctaves[9] = 15; _3D_IQ_Noise_0_LODToOctaves[10] = 15; _3D_IQ_Noise_0_LODToOctaves[11] = 15; _3D_IQ_Noise_0_LODToOctaves[12] = 15; _3D_IQ_Noise_0_LODToOctaves[13] = 15; _3D_IQ_Noise_0_LODToOctaves[14] = 15; _3D_IQ_Noise_0_LODToOctaves[15] = 15; _3D_IQ_Noise_0_LODToOctaves[16] = 15; _3D_IQ_Noise_0_LODToOctaves[17] = 15; _3D_IQ_Noise_0_LODToOctaves[18] = 15; _3D_IQ_Noise_0_LODToOctaves[19] = 15; _3D_IQ_Noise_0_LODToOctaves[20] = 15; _3D_IQ_Noise_0_LODToOctaves[21] = 15; _3D_IQ_Noise_0_LODToOctaves[22] = 15; _3D_IQ_Noise_0_LODToOctaves[23] = 15; _3D_IQ_Noise_0_LODToOctaves[24] = 15; _3D_IQ_Noise_0_LODToOctaves[25] = 15; _3D_IQ_Noise_0_LODToOctaves[26] = 15; _3D_IQ_Noise_0_LODToOctaves[27] = 15; _3D_IQ_Noise_0_LODToOctaves[28] = 15; _3D_IQ_Noise_0_LODToOctaves[29] = 15; _3D_IQ_Noise_0_LODToOctaves[30] = 15; _3D_IQ_Noise_0_LODToOctaves[31] = 15; // Init of 3D Perlin Noise Fractal _3D_Perlin_Noise_Fractal_0_Noise.SetSeed(Variable_20); _3D_Perlin_Noise_Fractal_0_Noise.SetInterp(FVoxelFastNoise::Quintic); _3D_Perlin_Noise_Fractal_0_Noise.SetFractalOctavesAndGain(3, 0.5); _3D_Perlin_Noise_Fractal_0_Noise.SetFractalLacunarity(2.0); _3D_Perlin_Noise_Fractal_0_Noise.SetFractalType(FVoxelFastNoise::FBM); _3D_Perlin_Noise_Fractal_0_LODToOctaves[0] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[1] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[2] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[3] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[4] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[5] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[6] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[7] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[8] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[9] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[10] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[11] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[12] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[13] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[14] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[15] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[16] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[17] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[18] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[19] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[20] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[21] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[22] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[23] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[24] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[25] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[26] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[27] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[28] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[29] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[30] = 3; _3D_Perlin_Noise_Fractal_0_LODToOctaves[31] = 3; } /////////////////////////////////////////////////////////////////////// ////////////////////////// Compute functions ////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_X_Compute(const FVoxelContext& Context, FBufferX& BufferX) const { // X BufferX.Variable_6 = Context.GetLocalX(); // X BufferX.Variable_0 = Context.GetLocalX(); } void Function0_XYWithCache_Compute(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { // Y BufferXY.Variable_7 = Context.GetLocalY(); // Y BufferXY.Variable_1 = Context.GetLocalY(); } void Function0_XYWithoutCache_Compute(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { // X BufferX.Variable_6 = Context.GetLocalX(); // X BufferX.Variable_0 = Context.GetLocalX(); // Y BufferXY.Variable_7 = Context.GetLocalY(); // Y BufferXY.Variable_1 = Context.GetLocalY(); } void Function0_XYZWithCache_Compute(const FVoxelContext& Context, const FBufferX& BufferX, const FBufferXY& BufferXY, FOutputs& Outputs) const { // Z v_flt Variable_2; // Z output 0 Variable_2 = Context.GetLocalZ(); // Z v_flt Variable_8; // Z output 0 Variable_8 = Context.GetLocalZ(); // Normalize.Vector Length v_flt Variable_24; // Normalize.Vector Length output 0 Variable_24 = FVoxelNodeFunctions::VectorLength(BufferX.Variable_0, BufferXY.Variable_1, Variable_2); // Vector Length v_flt Variable_5; // Vector Length output 0 Variable_5 = FVoxelNodeFunctions::VectorLength(BufferX.Variable_6, BufferXY.Variable_7, Variable_8); // Normalize./ v_flt Variable_25; // Normalize./ output 0 Variable_25 = BufferX.Variable_0 / Variable_24; // Normalize./ v_flt Variable_26; // Normalize./ output 0 Variable_26 = BufferXY.Variable_1 / Variable_24; // Normalize./ v_flt Variable_27; // Normalize./ output 0 Variable_27 = Variable_2 / Variable_24; // 3D IQ Noise v_flt Variable_18; // 3D IQ Noise output 0 v_flt _3D_IQ_Noise_0_Temp_1; // 3D IQ Noise output 1 v_flt _3D_IQ_Noise_0_Temp_2; // 3D IQ Noise output 2 v_flt _3D_IQ_Noise_0_Temp_3; // 3D IQ Noise output 3 Variable_18 = _3D_IQ_Noise_0_Noise.IQNoiseDeriv_3D(Variable_25, Variable_26, Variable_27, BufferConstant.Variable_19, _3D_IQ_Noise_0_LODToOctaves[FMath::Clamp(Context.LOD, 0, 31)],_3D_IQ_Noise_0_Temp_1,_3D_IQ_Noise_0_Temp_2,_3D_IQ_Noise_0_Temp_3); // 3D Perlin Noise Fractal v_flt Variable_3; // 3D Perlin Noise Fractal output 0 Variable_3 = _3D_Perlin_Noise_Fractal_0_Noise.GetPerlinFractal_3D(Variable_25, Variable_26, Variable_27, BufferConstant.Variable_19, _3D_Perlin_Noise_Fractal_0_LODToOctaves[FMath::Clamp(Context.LOD, 0, 31)]); // Switch (float) v_flt Variable_21; // Switch (float) output 0 Variable_21 = FVoxelNodeFunctions::Switch(Variable_18, Variable_3, BufferConstant.Variable_22); // + v_flt Variable_14; // + output 0 Variable_14 = Variable_21 + BufferConstant.Variable_16; // 2D Noise SDF.* v_flt Variable_29; // 2D Noise SDF.* output 0 Variable_29 = Variable_14 * BufferConstant.Variable_10; // 2D Noise SDF.* v_flt Variable_31; // 2D Noise SDF.* output 0 Variable_31 = Variable_14 * BufferConstant.Variable_12; // 2D Noise SDF.+ v_flt Variable_9; // 2D Noise SDF.+ output 0 Variable_9 = Variable_31 + BufferConstant.Variable_11; // 2D Noise SDF.+ v_flt Variable_4; // 2D Noise SDF.+ output 0 Variable_4 = Variable_29 + BufferConstant.Variable_11; // 2D Noise SDF.- v_flt Variable_28; // 2D Noise SDF.- output 0 Variable_28 = Variable_5 - Variable_4; // 2D Noise SDF.- v_flt Variable_30; // 2D Noise SDF.- output 0 Variable_30 = Variable_5 - Variable_9; // * -1 v_flt Variable_13; // * -1 output 0 Variable_13 = Variable_30 * -1; // Smooth Intersection v_flt Variable_15; // Smooth Intersection output 0 Variable_15 = FVoxelSDFNodeFunctions::SmoothIntersection(Variable_28, Variable_13, BufferConstant.Variable_17); // Set High Quality Value.* v_flt Variable_23; // Set High Quality Value.* output 0 Variable_23 = Variable_15 * v_flt(0.2f); Outputs.Value = Variable_23; } void Function0_XYZWithoutCache_Compute(const FVoxelContext& Context, FOutputs& Outputs) const { // X v_flt Variable_6; // X output 0 Variable_6 = Context.GetLocalX(); // Z v_flt Variable_2; // Z output 0 Variable_2 = Context.GetLocalZ(); // X v_flt Variable_0; // X output 0 Variable_0 = Context.GetLocalX(); // Y v_flt Variable_7; // Y output 0 Variable_7 = Context.GetLocalY(); // Z v_flt Variable_8; // Z output 0 Variable_8 = Context.GetLocalZ(); // Y v_flt Variable_1; // Y output 0 Variable_1 = Context.GetLocalY(); // Normalize.Vector Length v_flt Variable_24; // Normalize.Vector Length output 0 Variable_24 = FVoxelNodeFunctions::VectorLength(Variable_0, Variable_1, Variable_2); // Vector Length v_flt Variable_5; // Vector Length output 0 Variable_5 = FVoxelNodeFunctions::VectorLength(Variable_6, Variable_7, Variable_8); // Normalize./ v_flt Variable_25; // Normalize./ output 0 Variable_25 = Variable_0 / Variable_24; // Normalize./ v_flt Variable_26; // Normalize./ output 0 Variable_26 = Variable_1 / Variable_24; // Normalize./ v_flt Variable_27; // Normalize./ output 0 Variable_27 = Variable_2 / Variable_24; // 3D IQ Noise v_flt Variable_18; // 3D IQ Noise output 0 v_flt _3D_IQ_Noise_0_Temp_1; // 3D IQ Noise output 1 v_flt _3D_IQ_Noise_0_Temp_2; // 3D IQ Noise output 2 v_flt _3D_IQ_Noise_0_Temp_3; // 3D IQ Noise output 3 Variable_18 = _3D_IQ_Noise_0_Noise.IQNoiseDeriv_3D(Variable_25, Variable_26, Variable_27, BufferConstant.Variable_19, _3D_IQ_Noise_0_LODToOctaves[FMath::Clamp(Context.LOD, 0, 31)],_3D_IQ_Noise_0_Temp_1,_3D_IQ_Noise_0_Temp_2,_3D_IQ_Noise_0_Temp_3); // 3D Perlin Noise Fractal v_flt Variable_3; // 3D Perlin Noise Fractal output 0 Variable_3 = _3D_Perlin_Noise_Fractal_0_Noise.GetPerlinFractal_3D(Variable_25, Variable_26, Variable_27, BufferConstant.Variable_19, _3D_Perlin_Noise_Fractal_0_LODToOctaves[FMath::Clamp(Context.LOD, 0, 31)]); // Switch (float) v_flt Variable_21; // Switch (float) output 0 Variable_21 = FVoxelNodeFunctions::Switch(Variable_18, Variable_3, BufferConstant.Variable_22); // + v_flt Variable_14; // + output 0 Variable_14 = Variable_21 + BufferConstant.Variable_16; // 2D Noise SDF.* v_flt Variable_29; // 2D Noise SDF.* output 0 Variable_29 = Variable_14 * BufferConstant.Variable_10; // 2D Noise SDF.* v_flt Variable_31; // 2D Noise SDF.* output 0 Variable_31 = Variable_14 * BufferConstant.Variable_12; // 2D Noise SDF.+ v_flt Variable_9; // 2D Noise SDF.+ output 0 Variable_9 = Variable_31 + BufferConstant.Variable_11; // 2D Noise SDF.+ v_flt Variable_4; // 2D Noise SDF.+ output 0 Variable_4 = Variable_29 + BufferConstant.Variable_11; // 2D Noise SDF.- v_flt Variable_28; // 2D Noise SDF.- output 0 Variable_28 = Variable_5 - Variable_4; // 2D Noise SDF.- v_flt Variable_30; // 2D Noise SDF.- output 0 Variable_30 = Variable_5 - Variable_9; // * -1 v_flt Variable_13; // * -1 output 0 Variable_13 = Variable_30 * -1; // Smooth Intersection v_flt Variable_15; // Smooth Intersection output 0 Variable_15 = FVoxelSDFNodeFunctions::SmoothIntersection(Variable_28, Variable_13, BufferConstant.Variable_17); // Set High Quality Value.* v_flt Variable_23; // Set High Quality Value.* output 0 Variable_23 = Variable_15 * v_flt(0.2f); Outputs.Value = Variable_23; } }; class FLocalComputeStruct_LocalMaterial { public: struct FOutputs { FOutputs() {} void Init(const FVoxelGraphOutputsInit& Init) { MaterialBuilder.SetMaterialConfig(Init.MaterialConfig); } template<typename T, uint32 Index> T Get() const; template<typename T, uint32 Index> void Set(T Value); FVoxelMaterialBuilder MaterialBuilder; }; struct FBufferConstant { FBufferConstant() {} }; struct FBufferX { FBufferX() {} }; struct FBufferXY { FBufferXY() {} }; FLocalComputeStruct_LocalMaterial(const FParams& InParams) : Params(InParams) { } void Init(const FVoxelWorldGeneratorInit& InitStruct) { //////////////////////////////////////////////////// //////////////////// Init nodes //////////////////// //////////////////////////////////////////////////// { //////////////////////////////////////////////////// /////////////// Constant nodes init //////////////// //////////////////////////////////////////////////// { ///////////////////////////////////////////////////////////////////////////////// //////// First compute all seeds in case they are used by constant nodes //////// ///////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////// ///////////// Then init constant nodes ///////////// //////////////////////////////////////////////////// } //////////////////////////////////////////////////// //////////////////// Other inits /////////////////// //////////////////////////////////////////////////// Function0_XYZWithoutCache_Init(InitStruct); } //////////////////////////////////////////////////// //////////////// Compute constants ///////////////// //////////////////////////////////////////////////// { } } void ComputeX(const FVoxelContext& Context, FBufferX& BufferX) const { Function0_X_Compute(Context, BufferX); } void ComputeXYWithCache(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { Function0_XYWithCache_Compute(Context, BufferX, BufferXY); } void ComputeXYWithoutCache(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { Function0_XYWithoutCache_Compute(Context, BufferX, BufferXY); } void ComputeXYZWithCache(const FVoxelContext& Context, const FBufferX& BufferX, const FBufferXY& BufferXY, FOutputs& Outputs) const { Function0_XYZWithCache_Compute(Context, BufferX, BufferXY, Outputs); } void ComputeXYZWithoutCache(const FVoxelContext& Context, FOutputs& Outputs) const { Function0_XYZWithoutCache_Compute(Context, Outputs); } inline FBufferX GetBufferX() const { return {}; } inline FBufferXY GetBufferXY() const { return {}; } inline FOutputs GetOutputs() const { return {}; } private: FBufferConstant BufferConstant; const FParams& Params; /////////////////////////////////////////////////////////////////////// //////////////////////////// Init functions /////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_XYZWithoutCache_Init(const FVoxelWorldGeneratorInit& InitStruct) { } /////////////////////////////////////////////////////////////////////// ////////////////////////// Compute functions ////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_X_Compute(const FVoxelContext& Context, FBufferX& BufferX) const { } void Function0_XYWithCache_Compute(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { } void Function0_XYWithoutCache_Compute(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { } void Function0_XYZWithCache_Compute(const FVoxelContext& Context, const FBufferX& BufferX, const FBufferXY& BufferXY, FOutputs& Outputs) const { } void Function0_XYZWithoutCache_Compute(const FVoxelContext& Context, FOutputs& Outputs) const { } }; class FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ { public: struct FOutputs { FOutputs() {} void Init(const FVoxelGraphOutputsInit& Init) { } template<typename T, uint32 Index> T Get() const; template<typename T, uint32 Index> void Set(T Value); v_flt UpVectorX; v_flt UpVectorY; v_flt UpVectorZ; }; struct FBufferConstant { FBufferConstant() {} }; struct FBufferX { FBufferX() {} }; struct FBufferXY { FBufferXY() {} }; FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ(const FParams& InParams) : Params(InParams) { } void Init(const FVoxelWorldGeneratorInit& InitStruct) { //////////////////////////////////////////////////// //////////////////// Init nodes //////////////////// //////////////////////////////////////////////////// { //////////////////////////////////////////////////// /////////////// Constant nodes init //////////////// //////////////////////////////////////////////////// { ///////////////////////////////////////////////////////////////////////////////// //////// First compute all seeds in case they are used by constant nodes //////// ///////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////// ///////////// Then init constant nodes ///////////// //////////////////////////////////////////////////// } //////////////////////////////////////////////////// //////////////////// Other inits /////////////////// //////////////////////////////////////////////////// Function0_XYZWithoutCache_Init(InitStruct); } //////////////////////////////////////////////////// //////////////// Compute constants ///////////////// //////////////////////////////////////////////////// { } } void ComputeX(const FVoxelContext& Context, FBufferX& BufferX) const { Function0_X_Compute(Context, BufferX); } void ComputeXYWithCache(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { Function0_XYWithCache_Compute(Context, BufferX, BufferXY); } void ComputeXYWithoutCache(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { Function0_XYWithoutCache_Compute(Context, BufferX, BufferXY); } void ComputeXYZWithCache(const FVoxelContext& Context, const FBufferX& BufferX, const FBufferXY& BufferXY, FOutputs& Outputs) const { Function0_XYZWithCache_Compute(Context, BufferX, BufferXY, Outputs); } void ComputeXYZWithoutCache(const FVoxelContext& Context, FOutputs& Outputs) const { Function0_XYZWithoutCache_Compute(Context, Outputs); } inline FBufferX GetBufferX() const { return {}; } inline FBufferXY GetBufferXY() const { return {}; } inline FOutputs GetOutputs() const { return {}; } private: FBufferConstant BufferConstant; const FParams& Params; /////////////////////////////////////////////////////////////////////// //////////////////////////// Init functions /////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_XYZWithoutCache_Init(const FVoxelWorldGeneratorInit& InitStruct) { } /////////////////////////////////////////////////////////////////////// ////////////////////////// Compute functions ////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_X_Compute(const FVoxelContext& Context, FBufferX& BufferX) const { } void Function0_XYWithCache_Compute(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { } void Function0_XYWithoutCache_Compute(const FVoxelContext& Context, FBufferX& BufferX, FBufferXY& BufferXY) const { } void Function0_XYZWithCache_Compute(const FVoxelContext& Context, const FBufferX& BufferX, const FBufferXY& BufferXY, FOutputs& Outputs) const { } void Function0_XYZWithoutCache_Compute(const FVoxelContext& Context, FOutputs& Outputs) const { } }; class FLocalComputeStruct_LocalValueRangeAnalysis { public: struct FOutputs { FOutputs() {} void Init(const FVoxelGraphOutputsInit& Init) { } template<typename T, uint32 Index> TVoxelRange<T> Get() const; template<typename T, uint32 Index> void Set(TVoxelRange<T> Value); TVoxelRange<v_flt> Value; }; struct FBufferConstant { FBufferConstant() {} TVoxelRange<v_flt> Variable_8; // Radius = 250.0 output 0 TVoxelRange<v_flt> Variable_20; // Normalize.Range Union output 0 TVoxelRange<v_flt> Variable_13; // Noise Bias = 0.2 output 0 TVoxelRange<v_flt> Variable_14; // Intersection Smoothness = 10.0 output 0 TVoxelRange<v_flt> Variable_16; // Noise Frequency = 4.0 output 0 FVoxelBoolRange Variable_18; // Use IQ Noise = true output 0 TVoxelRange<v_flt> Variable_7; // Noise Scale = 20.0 output 0 TVoxelRange<v_flt> Variable_9; // * -1 output 0 }; struct FBufferX { FBufferX() {} TVoxelRange<v_flt> Variable_3; // X output 0 TVoxelRange<v_flt> Variable_6; // 2D Noise SDF.+ output 0 TVoxelRange<v_flt> Variable_1; // 2D Noise SDF.+ output 0 }; struct FBufferXY { FBufferXY() {} TVoxelRange<v_flt> Variable_4; // Y output 0 }; FLocalComputeStruct_LocalValueRangeAnalysis(const FParams& InParams) : Params(InParams) { } void Init(const FVoxelWorldGeneratorInit& InitStruct) { //////////////////////////////////////////////////// //////////////////// Init nodes //////////////////// //////////////////////////////////////////////////// { //////////////////////////////////////////////////// /////////////// Constant nodes init //////////////// //////////////////////////////////////////////////// { ///////////////////////////////////////////////////////////////////////////////// //////// First compute all seeds in case they are used by constant nodes //////// ///////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////// ///////////// Then init constant nodes ///////////// //////////////////////////////////////////////////// } //////////////////////////////////////////////////// //////////////////// Other inits /////////////////// //////////////////////////////////////////////////// Function0_XYZWithoutCache_Init(InitStruct); } //////////////////////////////////////////////////// //////////////// Compute constants ///////////////// //////////////////////////////////////////////////// { // Radius = 250.0 BufferConstant.Variable_8 = Params.Radius; // Normalize.Range Union BufferConstant.Variable_20 = FVoxelNodeFunctions::Union(TVoxelRange<v_flt>(-1.0f), TVoxelRange<v_flt>(1.0f)); // Noise Bias = 0.2 BufferConstant.Variable_13 = Params.Noise_Bias; // Intersection Smoothness = 10.0 BufferConstant.Variable_14 = Params.Intersection_Smoothness; // Noise Frequency = 4.0 BufferConstant.Variable_16 = Params.Noise_Frequency; // Use IQ Noise = true BufferConstant.Variable_18 = Params.Use_IQ_Noise; // Noise Scale = 20.0 BufferConstant.Variable_7 = Params.Noise_Scale; // * -1 BufferConstant.Variable_9 = BufferConstant.Variable_7 * -1; } } void ComputeXYZWithoutCache(const FVoxelContextRange& Context, FOutputs& Outputs) const { Function0_XYZWithoutCache_Compute(Context, Outputs); } inline FBufferX GetBufferX() const { return {}; } inline FBufferXY GetBufferXY() const { return {}; } inline FOutputs GetOutputs() const { return {}; } private: FBufferConstant BufferConstant; const FParams& Params; FVoxelFastNoise _3D_Perlin_Noise_Fractal_1_Noise; TStaticArray<uint8, 32> _3D_Perlin_Noise_Fractal_1_LODToOctaves; FVoxelFastNoise _3D_IQ_Noise_1_Noise; TStaticArray<uint8, 32> _3D_IQ_Noise_1_LODToOctaves; /////////////////////////////////////////////////////////////////////// //////////////////////////// Init functions /////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_XYZWithoutCache_Init(const FVoxelWorldGeneratorInit& InitStruct) { // Init of 3D Perlin Noise Fractal _3D_Perlin_Noise_Fractal_1_Noise.SetSeed(FVoxelGraphSeed(1337)); _3D_Perlin_Noise_Fractal_1_Noise.SetInterp(FVoxelFastNoise::Quintic); _3D_Perlin_Noise_Fractal_1_Noise.SetFractalOctavesAndGain(3, 0.5); _3D_Perlin_Noise_Fractal_1_Noise.SetFractalLacunarity(2.0); _3D_Perlin_Noise_Fractal_1_Noise.SetFractalType(FVoxelFastNoise::FBM); _3D_Perlin_Noise_Fractal_1_LODToOctaves[0] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[1] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[2] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[3] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[4] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[5] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[6] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[7] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[8] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[9] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[10] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[11] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[12] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[13] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[14] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[15] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[16] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[17] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[18] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[19] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[20] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[21] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[22] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[23] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[24] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[25] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[26] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[27] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[28] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[29] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[30] = 3; _3D_Perlin_Noise_Fractal_1_LODToOctaves[31] = 3; // Init of 3D IQ Noise _3D_IQ_Noise_1_Noise.SetSeed(FVoxelGraphSeed(1337)); _3D_IQ_Noise_1_Noise.SetInterp(FVoxelFastNoise::Quintic); _3D_IQ_Noise_1_Noise.SetFractalOctavesAndGain(15, 0.5); _3D_IQ_Noise_1_Noise.SetFractalLacunarity(2.0); _3D_IQ_Noise_1_Noise.SetFractalType(FVoxelFastNoise::FBM); _3D_IQ_Noise_1_Noise.SetMatrix(ToMatrix(FRotator(40.000000, 45.000000, 50.000000))); _3D_IQ_Noise_1_LODToOctaves[0] = 15; _3D_IQ_Noise_1_LODToOctaves[1] = 15; _3D_IQ_Noise_1_LODToOctaves[2] = 15; _3D_IQ_Noise_1_LODToOctaves[3] = 15; _3D_IQ_Noise_1_LODToOctaves[4] = 15; _3D_IQ_Noise_1_LODToOctaves[5] = 15; _3D_IQ_Noise_1_LODToOctaves[6] = 15; _3D_IQ_Noise_1_LODToOctaves[7] = 15; _3D_IQ_Noise_1_LODToOctaves[8] = 15; _3D_IQ_Noise_1_LODToOctaves[9] = 15; _3D_IQ_Noise_1_LODToOctaves[10] = 15; _3D_IQ_Noise_1_LODToOctaves[11] = 15; _3D_IQ_Noise_1_LODToOctaves[12] = 15; _3D_IQ_Noise_1_LODToOctaves[13] = 15; _3D_IQ_Noise_1_LODToOctaves[14] = 15; _3D_IQ_Noise_1_LODToOctaves[15] = 15; _3D_IQ_Noise_1_LODToOctaves[16] = 15; _3D_IQ_Noise_1_LODToOctaves[17] = 15; _3D_IQ_Noise_1_LODToOctaves[18] = 15; _3D_IQ_Noise_1_LODToOctaves[19] = 15; _3D_IQ_Noise_1_LODToOctaves[20] = 15; _3D_IQ_Noise_1_LODToOctaves[21] = 15; _3D_IQ_Noise_1_LODToOctaves[22] = 15; _3D_IQ_Noise_1_LODToOctaves[23] = 15; _3D_IQ_Noise_1_LODToOctaves[24] = 15; _3D_IQ_Noise_1_LODToOctaves[25] = 15; _3D_IQ_Noise_1_LODToOctaves[26] = 15; _3D_IQ_Noise_1_LODToOctaves[27] = 15; _3D_IQ_Noise_1_LODToOctaves[28] = 15; _3D_IQ_Noise_1_LODToOctaves[29] = 15; _3D_IQ_Noise_1_LODToOctaves[30] = 15; _3D_IQ_Noise_1_LODToOctaves[31] = 15; } /////////////////////////////////////////////////////////////////////// ////////////////////////// Compute functions ////////////////////////// /////////////////////////////////////////////////////////////////////// void Function0_XYZWithoutCache_Compute(const FVoxelContextRange& Context, FOutputs& Outputs) const { // 3D Perlin Noise Fractal TVoxelRange<v_flt> Variable_0; // 3D Perlin Noise Fractal output 0 Variable_0 = { -0.419158f, 0.458317f }; // 3D IQ Noise TVoxelRange<v_flt> Variable_15; // 3D IQ Noise output 0 TVoxelRange<v_flt> _3D_IQ_Noise_1_Temp_1; // 3D IQ Noise output 1 TVoxelRange<v_flt> _3D_IQ_Noise_1_Temp_2; // 3D IQ Noise output 2 TVoxelRange<v_flt> _3D_IQ_Noise_1_Temp_3; // 3D IQ Noise output 3 Variable_15 = { -0.732619f, 0.767129f }; _3D_IQ_Noise_1_Temp_1 = { -1.577728f, 1.771872f }; _3D_IQ_Noise_1_Temp_2 = { -1.779903f, 1.388687f }; _3D_IQ_Noise_1_Temp_3 = { -1.667376f, 1.695596f }; // Y TVoxelRange<v_flt> Variable_4; // Y output 0 Variable_4 = Context.GetLocalY(); // X TVoxelRange<v_flt> Variable_3; // X output 0 Variable_3 = Context.GetLocalX(); // Z TVoxelRange<v_flt> Variable_5; // Z output 0 Variable_5 = Context.GetLocalZ(); // Vector Length TVoxelRange<v_flt> Variable_2; // Vector Length output 0 Variable_2 = FVoxelNodeFunctions::VectorLength(Variable_3, Variable_4, Variable_5); // Switch (float) TVoxelRange<v_flt> Variable_17; // Switch (float) output 0 Variable_17 = FVoxelNodeFunctions::Switch(Variable_15, Variable_0, BufferConstant.Variable_18); // + TVoxelRange<v_flt> Variable_11; // + output 0 Variable_11 = Variable_17 + BufferConstant.Variable_13; // 2D Noise SDF.* TVoxelRange<v_flt> Variable_22; // 2D Noise SDF.* output 0 Variable_22 = Variable_11 * BufferConstant.Variable_7; // 2D Noise SDF.* TVoxelRange<v_flt> Variable_24; // 2D Noise SDF.* output 0 Variable_24 = Variable_11 * BufferConstant.Variable_9; // 2D Noise SDF.+ TVoxelRange<v_flt> Variable_6; // 2D Noise SDF.+ output 0 Variable_6 = Variable_24 + BufferConstant.Variable_8; // 2D Noise SDF.+ TVoxelRange<v_flt> Variable_1; // 2D Noise SDF.+ output 0 Variable_1 = Variable_22 + BufferConstant.Variable_8; // 2D Noise SDF.- TVoxelRange<v_flt> Variable_23; // 2D Noise SDF.- output 0 Variable_23 = Variable_2 - Variable_6; // 2D Noise SDF.- TVoxelRange<v_flt> Variable_21; // 2D Noise SDF.- output 0 Variable_21 = Variable_2 - Variable_1; // * -1 TVoxelRange<v_flt> Variable_10; // * -1 output 0 Variable_10 = Variable_23 * -1; // Smooth Intersection TVoxelRange<v_flt> Variable_12; // Smooth Intersection output 0 Variable_12 = FVoxelSDFNodeFunctions::SmoothIntersection(Variable_21, Variable_10, BufferConstant.Variable_14); // Set High Quality Value.* TVoxelRange<v_flt> Variable_19; // Set High Quality Value.* output 0 Variable_19 = Variable_12 * TVoxelRange<v_flt>(0.2f); Outputs.Value = Variable_19; } }; FVoxelExample_HollowPlanetInstance(const UVoxelExample_HollowPlanet& Object) : TVoxelGraphGeneratorInstanceHelper( { { "Value", 1 }, }, { }, { }, { { { "Value", NoTransformAccessor<v_flt>::Get<1, TOutputFunctionPtr<v_flt>>() }, }, { }, { }, { { "Value", NoTransformRangeAccessor<v_flt>::Get<1, TRangeOutputFunctionPtr<v_flt>>() }, } }, { { { "Value", WithTransformAccessor<v_flt>::Get<1, TOutputFunctionPtr_Transform<v_flt>>() }, }, { }, { }, { { "Value", WithTransformRangeAccessor<v_flt>::Get<1, TRangeOutputFunctionPtr_Transform<v_flt>>() }, } }, Object.bEnableRangeAnalysis) , Params(FParams { Object.Use_IQ_Noise, Object.Noise_Bias, Object.Intersection_Smoothness, Object.Noise_Frequency, Object.Noise_Scale, Object.Radius }) , LocalValue(Params) , LocalMaterial(Params) , LocalUpVectorXUpVectorYUpVectorZ(Params) , LocalValueRangeAnalysis(Params) { } virtual void InitGraph(const FVoxelWorldGeneratorInit& InitStruct) override final { LocalValue.Init(InitStruct); LocalMaterial.Init(InitStruct); LocalUpVectorXUpVectorYUpVectorZ.Init(InitStruct); LocalValueRangeAnalysis.Init(InitStruct); } template<uint32... Permutation> auto& GetTarget() const; template<uint32... Permutation> auto& GetRangeTarget() const; inline void ReportRangeAnalysisFailure() const {} private: FParams Params; FLocalComputeStruct_LocalValue LocalValue; FLocalComputeStruct_LocalMaterial LocalMaterial; FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ LocalUpVectorXUpVectorYUpVectorZ; FLocalComputeStruct_LocalValueRangeAnalysis LocalValueRangeAnalysis; }; template<> inline v_flt FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalValue::FOutputs::Get<v_flt, 1>() const { return Value; } template<> inline void FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalValue::FOutputs::Set<v_flt, 1>(v_flt InValue) { Value = InValue; } template<> inline FVoxelMaterial FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalMaterial::FOutputs::Get<FVoxelMaterial, 2>() const { return MaterialBuilder.Build(); } template<> inline void FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalMaterial::FOutputs::Set<FVoxelMaterial, 2>(FVoxelMaterial Material) { } template<> inline v_flt FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ::FOutputs::Get<v_flt, 3>() const { return UpVectorX; } template<> inline void FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ::FOutputs::Set<v_flt, 3>(v_flt InValue) { UpVectorX = InValue; } template<> inline v_flt FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ::FOutputs::Get<v_flt, 4>() const { return UpVectorY; } template<> inline void FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ::FOutputs::Set<v_flt, 4>(v_flt InValue) { UpVectorY = InValue; } template<> inline v_flt FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ::FOutputs::Get<v_flt, 5>() const { return UpVectorZ; } template<> inline void FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalUpVectorXUpVectorYUpVectorZ::FOutputs::Set<v_flt, 5>(v_flt InValue) { UpVectorZ = InValue; } template<> inline TVoxelRange<v_flt> FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalValueRangeAnalysis::FOutputs::Get<v_flt, 1>() const { return Value; } template<> inline void FVoxelExample_HollowPlanetInstance::FLocalComputeStruct_LocalValueRangeAnalysis::FOutputs::Set<v_flt, 1>(TVoxelRange<v_flt> InValue) { Value = InValue; } template<> inline auto& FVoxelExample_HollowPlanetInstance::GetTarget<1>() const { return LocalValue; } template<> inline auto& FVoxelExample_HollowPlanetInstance::GetTarget<2>() const { return LocalMaterial; } template<> inline auto& FVoxelExample_HollowPlanetInstance::GetRangeTarget<0, 1>() const { return LocalValueRangeAnalysis; } template<> inline auto& FVoxelExample_HollowPlanetInstance::GetTarget<3, 4, 5>() const { return LocalUpVectorXUpVectorYUpVectorZ; } #endif //////////////////////////////////////////////////////////// ////////////////////////// UCLASS ////////////////////////// //////////////////////////////////////////////////////////// UVoxelExample_HollowPlanet::UVoxelExample_HollowPlanet() { bEnableRangeAnalysis = true; } TMap<FName, int32> UVoxelExample_HollowPlanet::GetDefaultSeeds() const { return { { "Seed", 1443 }, }; } TVoxelSharedRef<FVoxelTransformableWorldGeneratorInstance> UVoxelExample_HollowPlanet::GetTransformableInstance() { #if VOXEL_GRAPH_GENERATED_VERSION == 1 return MakeVoxelShared<FVoxelExample_HollowPlanetInstance>(*this); #else #if VOXEL_GRAPH_GENERATED_VERSION > 1 EMIT_CUSTOM_WARNING("Outdated generated voxel graph: VoxelExample_HollowPlanet. You need to regenerate it."); FVoxelMessages::Warning("Outdated generated voxel graph: VoxelExample_HollowPlanet. You need to regenerate it."); #else EMIT_CUSTOM_WARNING("Generated voxel graph is more recent than the Voxel Plugin version: VoxelExample_HollowPlanet. You need to update the plugin."); FVoxelMessages::Warning("Generated voxel graph is more recent than the Voxel Plugin version: VoxelExample_HollowPlanet. You need to update the plugin."); #endif return MakeVoxelShared<FVoxelTransformableEmptyWorldGeneratorInstance>(); #endif } PRAGMA_GENERATED_VOXEL_GRAPH_END
[ "phyronnaz@gmail.com" ]
phyronnaz@gmail.com
fa1f3ae25f9a154a9b1d524610f48018b77415c6
21c85709179988d89ee2f45676061d49737eabc4
/include/grasp_detect/util/plot.h
73fcad827249af6197a53badf7a7fac76932d5fe
[]
no_license
GitWaHa/grasp_data_generator
775a8fa80745092b12501d8620f3213f1770fc3d
1eebc55b937ef7bf3e86e0d0cc0bd900bef78aef
refs/heads/master
2023-08-30T06:38:26.807487
2021-11-08T11:34:43
2021-11-08T11:34:43
425,146,582
0
0
null
null
null
null
UTF-8
C++
false
false
15,485
h
#pragma once #include <pcl/visualization/pcl_visualizer.h> #include "grasp_detect/candidate/hand.h" #include "grasp_detect/candidate/hand_set.h" #include "grasp_detect/candidate/local_frame.h" // #include "grasp_detect/descriptor/image_geometry.h" #include "grasp_detect/util/cloud.h" namespace grasp_detect { namespace util { typedef pcl::PointCloud<pcl::PointXYZRGBA> PointCloudRGBA; typedef pcl::PointCloud<pcl::PointNormal> PointCloudPointNormal; typedef boost::shared_ptr<pcl::visualization::PCLVisualizer> PCLVisualizer; /** * * \brief Visualization utilities * * Provides visualization methods that use the PCL Visualizer. Allows to * visualize samples, surface normals, grasps, and point clouds. * */ class Plot { public: using HandGeometry = grasp_detect::util::HandGeometryParams; /** * \brief Constructor. * \param num_axes the number of orientation axes * \param num_orientations the number of hand orientations */ Plot(int num_axes, int num_orientations) : num_axes_(num_axes), num_orientations_(num_orientations) {} Plot(ParamsManager &params) : num_axes_(params.getHandSearchParams().hand_axes_.size()), num_orientations_(params.getHandSearchParams().num_orientations_) { } // void plotHandGeometry(const candidate::Hand &hand, // const PointCloudRGBA::Ptr &cloud, // const candidate::HandGeometry &hand_geom, // const descriptor::ImageGeometry &image_geom); /** * \brief Plot a list of hand sets and their associated volumes. * \param hand_set_list the list of grasp sets * \param cloud the point cloud to be plotted * \param str the title of the plot window * \param outer_diameter the outer diameter of the robot hand * \param finger_width the width of the robot fingers * \param hand_depth the depth of the robot hand * \param hand_height the height of the robot hand */ void plotVolumes3D( const std::vector<std::unique_ptr<candidate::HandSet>> &hand_set_list, const PointCloudRGBA::Ptr &cloud, std::string str, double outer_diameter, double finger_width, double hand_depth, double hand_height, double volume_width, double volume_depth, double volume_height); /** * \brief Plot a list of hands and their associated volumes. * \param hand_set_list the list of grasp sets * \param cloud the point cloud to be plotted * \param str the title of the plot window * \param outer_diameter the outer diameter of the robot hand * \param finger_width the width of the robot fingers * \param hand_depth the depth of the robot hand * \param hand_height the height of the robot hand */ void plotVolumes3D( const std::vector<std::unique_ptr<candidate::Hand>> &hand_set_list, const PointCloudRGBA::Ptr &cloud, std::string str, double outer_diameter, double finger_width, double hand_depth, double hand_height, double volume_width, double volume_depth, double volume_height); void plotFingers3D( const std::vector<std::unique_ptr<candidate::HandSet>> &hand_set_list, const PointCloudRGBA::Ptr &cloud, std::string str, const HandGeometry &geometry, bool draw_all = false, bool draw_frame = false); /** * \brief Plot a list of grasp sets with 3D cubes. * \param hand_set_list the list of grasp sets * \param cloud the point cloud to be plotted * \param str the title of the plot window * \param outer_diameter the outer diameter of the robot hand * \param finger_width the width of the robot fingers * \param hand_depth the depth of the robot hand * \param hand_height the height of the robot hand */ void plotFingers3D(const std::vector<candidate::HandSet> &hand_set_list, const PointCloudRGBA::Ptr &cloud, std::string str, double outer_diameter, double finger_width, double hand_depth, double hand_height, bool draw_all = false, int num_axes = 1, int num_orientations = 8); void plotFingers3D( const std::vector<std::unique_ptr<candidate::Hand>> &hand_list, const PointCloudRGBA::Ptr &cloud, const std::string &str, const HandGeometry &geometry, bool use_same_color = true); void plotAntipodalHands( const std::vector<std::unique_ptr<candidate::Hand>> &hand_list, const PointCloudRGBA::Ptr &cloud, const std::string &str, const HandGeometry &geometry, bool draw_all = false); void plotAntipodalHands( const std::vector<std::unique_ptr<candidate::Hand>> &hand_list, const PointCloudRGBA::Ptr &cloud, const std::string &str, const HandGeometry &geometry, double score, bool draw_all = false); void plotAntipodalHands( const std::vector<std::unique_ptr<candidate::HandSet>> &hand_set_list, const PointCloudRGBA::Ptr &cloud, const std::string &str, const HandGeometry &geometry, bool draw_all = false); void plotAntipodalHands( const std::vector<std::unique_ptr<candidate::HandSet>> &hand_set_list, const PointCloudRGBA::Ptr &cloud, const std::string &str, const HandGeometry &geometry, double min_score, bool draw_all = false); void plotValidHands( const std::vector<std::unique_ptr<candidate::Hand>> &hand_list, const PointCloudRGBA::Ptr &cloud, const PointCloudRGBA::Ptr &mesh, const std::string &str, const HandGeometry &geometry); /** * \brief Plot a list of grasps with 3D cubes. * \param hand_list the list of grasps * \param cloud the point cloud to be plotted * \param str the title of the plot window * \param outer_diameter the outer diameter of the robot hand * \param finger_width the width of the robot fingers * \param hand_depth the depth of the robot hand * \param hand_height the height of the robot hand */ void plotFingers3D(const std::vector<candidate::Hand> &hand_list, const PointCloudRGBA::Ptr &cloud, std::string str, double outer_diameter, double finger_width, double hand_depth, double hand_height, bool draw_all = false); /** * \brief Plot a list of samples. * \param index_list the list of samples (indices into the point cloud) * \param cloud the point cloud to be plotted */ void plotSamples(const std::vector<int> &index_list, const PointCloudRGBA::Ptr &cloud); /** * \brief Plot a list of samples. * \param samples the list of samples (indices into the point cloud) * \param cloud the point cloud to be plotted */ void plotSamples(const Eigen::Matrix3Xd &samples, const PointCloudRGBA::Ptr &cloud); /** * \brief Plot a point cloud that contains samples. * \param samples_cloud the point cloud that contains the samples * \param cloud the point cloud to be plotted */ void plotSamples(const PointCloudRGBA::Ptr &samples_cloud, const PointCloudRGBA::Ptr &cloud); void plotNormals(const util::Cloud &cloud_cam, bool draw_camera_cone = false); void plotNormals(const PointCloudRGBA::Ptr &cloud, const PointCloudRGBA::Ptr &cloud_samples, const Eigen::Matrix3Xd &normals); /** * \brief Plot a list of normals. * \param cloud the point cloud to be plotted * \param normals the normals to be plotted */ void plotNormals(const PointCloudRGBA::Ptr &cloud, const Eigen::Matrix3Xd &normals); /** * \brief Plot a list of points and their normals. * \param pts the list of points to be plotted * \param normals the normals to be plotted */ void plotNormals(const Eigen::Matrix3Xd &pts, const Eigen::Matrix3Xd &normals); void plotNormals(const PointCloudRGBA::Ptr &cloud, const Eigen::Matrix3Xd &pts, const Eigen::Matrix3Xd &normals); /** * \brief Plot a list of local reference frames. * \param frame_list the list of frames to be plotted * \param cloud the point cloud to be plotted */ void plotLocalAxes(const std::vector<candidate::LocalFrame> &frames, const PointCloudRGBA::Ptr &cloud); void plotLocalAxes(const std::vector<std::vector<double>> &center, const std::vector<std::vector<double>> &x, const std::vector<std::vector<double>> &y, const std::vector<std::vector<double>> &z, const PointCloudRGBA::Ptr &cloud); /** * \brief Plot the camera source for each point in the point cloud. * \param pts_cam_source_in the camera source for each point in the point * cloud * \param cloud the point cloud to be plotted */ void plotCameraSource(const Eigen::VectorXi &pts_cam_source_in, const PointCloudRGBA::Ptr &cloud); /** * \brief Plot a point cloud. * \param cloud_rgb the point cloud to be plotted * \param str the title of the plot window */ void plotCloud(const PointCloudRGBA::Ptr &cloud_rgb, const std::string &title); private: void addDimensions(const Eigen::Vector3d &center, const Eigen::Matrix3d &rot, const Eigen::Vector3d &dimensions, const Eigen::Matrix3d &colors, const std::vector<std::string> &labels, PCLVisualizer &viewer); void addDoubleArrow(const Eigen::Vector3d &start, const Eigen::Vector3d &end, const std::string &label, const Eigen::Vector3d &rgb, PCLVisualizer &viewer, bool is_label_at_start = false); void plotHand3D(PCLVisualizer &viewer, const candidate::Hand &hand, const HandGeometry &geometry, int idx, const Eigen::Vector3d &rgb); /** * \brief Plot a grasp. * \param viewer viewer the PCL visualizer in which the grasp is plotted * \param hand the grasp * \param outer_diameter the outer diameter of the robot hand * \param finger_width the width of the robot fingers * \param hand_depth the depth of the robot hand * \param hand_height the height of the robot hand * \param idx the ID of the grasp in the viewer */ void plotHand3D(PCLVisualizer &viewer, const candidate::Hand &hand, double outer_diameter, double finger_width, double hand_depth, double hand_height, int idx, const Eigen::Vector3d &rgb); /** * \brief Plot a cube. * \param viewer viewer the PCL visualizer in which the grasp is plotted * \param position the center of the cube * \param rotation the orientation of the cube * \param width the width of the cube * \param height the height of the cube * \param depth the depth of the cube * \param name the name of the cube in the viewer */ void plotCube(PCLVisualizer &viewer, const Eigen::Vector3d &position, const Eigen::Quaterniond &rotation, double width, double height, double depth, const std::string &name, const Eigen::Vector3d &rgb); void plotFrame(PCLVisualizer &viewer, const Eigen::Vector3d &translation, const Eigen::Matrix3d &rotation, const std::string &id, double axis_length = 0.02); /** * \brief Create a point cloud that stores the visual representations of the * grasps. * \param hand_list the list of grasps to be be stored in the point cloud * \param outer_diameter the outer diameter of the visual grasp representation */ PointCloudRGBA::Ptr createFingersCloud( const std::vector<std::unique_ptr<candidate::Hand>> &hand_list, double outer_diameter); /** * \brief Convert an Eigen vector to a PCL point. * \param v the Eigen vector to be converted */ pcl::PointXYZRGBA eigenVector3dToPointXYZRGBA(const Eigen::Vector3d &v); /** * \brief Add a point cloud with normals to a PCL visualizer. * \param viewer the PCL visualizer that the cloud is added to * \param cloud the cloud to be added * \param line_width the line width for drawing normals * \param color_cloud the color that is used to draw the cloud * \param color_normals the color that is used to draw the normals * \param cloud_name an identifier string for the cloud * \param normals_name an identifier string for the normals */ void addCloudNormalsToViewer(PCLVisualizer &viewer, const PointCloudPointNormal::Ptr &cloud, double line_width, double *color_cloud, double *color_normals, const std::string &cloud_name, const std::string &normals_name); /** * \brief Run/show a PCL visualizer until an escape key is hit. * \param viewer the PCL visualizer to be shown */ void runViewer(PCLVisualizer &viewer); /** * \brief Create a PCL visualizer. * \param title the title of the visualization window */ PCLVisualizer createViewer(std::string title); void keyboardEventOccurred(const pcl::visualization::KeyboardEvent &event, void *viewer_void); int num_orientations_; int num_axes_; }; } // namespace util } // namespace grasp_detect
[ "wa.haoo@foxmail.com" ]
wa.haoo@foxmail.com
aa91750ffaf06fdbf2ceddfcdbd5109c5aa5d406
0350b44559e87949323b79a7f7c19afd6b1c3385
/src/Includes/Training.h
4b0134a39905a7b05827b5f81c28a2020a604071
[]
no_license
ProjPossibility/pp-usc-ss12-sign-language-reader
ed3f1020e18a1dba7f5bd71b0860fa6631ae810f
53678c2fb94b499c54fb322193f4908247fb1c6c
refs/heads/master
2020-05-18T08:53:29.193173
2015-04-29T01:47:44
2015-04-29T01:47:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
624
h
/* * Training.h * * Created on: 05-Mar-2010 * Author: parth */ #ifndef TRAINING_H_ #define TRAINING_H_ #include "Prerequs.h" #include "KNN.h" #include "FolderReader.h" class Training{ CvMat* Matrix; int Counter; CvMat* Labels; ML* StoredML; public: /** * Read the training dataset */ Training(InputReader *reader, FeatureDetector *fd, ML *ml); /** * Flatten the Image into the Matrix */ void FlattenImage(IplImage* Image, int Label); /** * Test the image using the learned model */ int test(IplImage*); }; #endif /* TRAINING_H_ */
[ "parthpatel.100@f7345894-23d3-11df-bcc3-9d5e0fc24faa" ]
parthpatel.100@f7345894-23d3-11df-bcc3-9d5e0fc24faa
1516b00fc6515367b04ff26528a0939f65795f89
df7f961cdb6f74382f2f2eedc0564b922970424b
/v0.1-source-proof-of-concept/3_testing.hpp
e4d62f0ac10db1405dfd5e5da87eb8d388d641b3
[]
no_license
tobias-loew/cpp-compile-time-register-machine
540276acd5a0c4bbf92dccc969b6aae412c99dd3
d891790b87d100fd541fbb5b6ab9ba1af9e0c2c3
refs/heads/main
2023-04-23T17:30:53.501957
2021-05-03T02:52:32
2021-05-03T02:52:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,010
hpp
/************************************************************************************************************************ ** ** Copyright 2021 Daniel Nikpayuk, Inuit Nunangat, The Inuit Nation ** ** This file is part of cpp_compile_time_register_machine. ** ** cpp_compile_time_register_machine is free software: you can redistribute it and/or modify it under the terms ** of the GNU General Public License as published by the Free Software Foundation, either version 3 ** of the License, or (at your option) any later version. ** ** cpp_compile_time_register_machine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ** See the GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License along with cpp_compile_time_register_machine. ** If not, see <http://www.gnu.org/licenses/>. ** ************************************************************************************************************************/ // testing: /***********************************************************************************************************************/ /***********************************************************************************************************************/ /***********************************************************************************************************************/ namespace testing { using namespace samples; /***********************************************************************************************************************/ /***********************************************************************************************************************/ /***********************************************************************************************************************/ // experimental alternatives: /***********************************************************************************************************************/ struct RI_v1 { enum : index_type { stop = 0 , pause , start , u_branch , b_branch , l_goto , r_goto , assign , save , restore , u_apply , b_apply , // dispatch optimizations require these to be consecutive: assign_0 , assign_1 , assign_2 , assign_3 , assign_4 , assign_5 , assign_6 , assign_7 , assign_8 , assign_9 , assign_10 , assign_11 , assign_12 , assign_13 , assign_14 , assign_15 , // dispatch optimizations require these to be consecutive: save_0 , save_1 , save_2 , save_3 , save_4 , save_5 , save_6 , save_7 , save_8 , save_9 , save_10 , save_11 , save_12 , save_13 , save_14 , save_15 , // dispatch optimizations require these to be consecutive: replace_0 , replace_1 , replace_2 , replace_3 , replace_4 , replace_5 , replace_6 , replace_7 , replace_8 , replace_9 , replace_10 , replace_11 , replace_12 , replace_13 , replace_14 , replace_15 , // dispatch optimizations require these to be consecutive: restore_0 , restore_1 , restore_2 , restore_3 , restore_4 , restore_5 , restore_6 , restore_7 , restore_8 , restore_9 , restore_10 , restore_11 , restore_12 , restore_13 , restore_14 , restore_15 , r_size }; enum : index_type { fold = r_size + 1 , fold_2_0 = r_size + 1 , fold_2_1 , fold_2_2 , fold_2_3 , fold_2_4 , fold_2_5 , fold_2_6 , fold_2_7 , fold_2_8 , fold_2_9 }; }; /***********************************************************************************************************************/ // next (alternate version): template < auto stop_next, auto pause_next, auto branch_next, auto l_goto_next, auto r_goto_next, auto label_next, auto instr_next > constexpr index_type next_v1(depth_type d, contr_type c, index_type l, index_type m, index_type n = 0, bool is_branch = false) { bool d_break = !bool(d); bool c_break = !d_break && (l == contr_length(c)); bool l_break = !d_break && !c_break && (m == label_length(c(l))); bool is_l_goto = !d_break && !c_break && !l_break && (c(l)(m)(1) == RI::l_goto); bool is_r_goto = !d_break && !c_break && !l_break && (c(l)(m)(1) == RI::r_goto); return (d_break ? pause_next : c_break ? stop_next : l_break ? (is_branch ? branch_next : is_l_goto ? l_goto_next : is_r_goto ? r_goto_next : label_next) : (is_branch ? branch_next : is_l_goto ? l_goto_next : is_r_goto ? r_goto_next : instr_next)) (c, l, m, n); } /***********************************************************************************************************************/ /***********************************************************************************************************************/ /***********************************************************************************************************************/ // printing: /***********************************************************************************************************************/ // register instruction: void print_RI(index_type n) { printf("%s, ", (n == RI::l_assign ) ? "l_assign" : (n == RI::r_assign ) ? "r_assign" : (n == RI::u_branch ) ? "u_branch" : (n == RI::b_branch ) ? "b_branch" : (n == RI::l_goto ) ? "l_goto" : (n == RI::r_goto ) ? "r_goto" : (n == RI::save ) ? "save" : (n == RI::restore ) ? "restore" : (n == RI::u_apply ) ? "u_apply" : "b_apply"); } void print_next(depth_type d, contr_type c, index_type l, index_type m, index_type n = 0, bool is_branch = false) { print_RI(next_i(d, c, l, m, n, is_branch)(1)); printf("%u, %u\n", next_l(d, c, l, m, n, is_branch), next_m(d, c, l, m, n, is_branch)); } /***********************************************************************************************************************/ /***********************************************************************************************************************/ /***********************************************************************************************************************/ // next: void test_next() { print_next(1, fact_contr<>, 1, 1, 0, true); // assign 3 1 print_next(1, fact_contr<>, 1, 1); // save 1 2 print_next(1, fact_contr<>, 1, 2); // save 1 3 print_next(1, fact_contr<>, 1, 3); // apply 1 4 print_next(1, fact_contr<>, 1, 4); // assign 1 5 print_next(1, fact_contr<>, 1, 5); // l_goto 1 6 print_next(1, fact_contr<>, 1, 6); // branch 1 1 printf("\n"); print_next(1, fact_contr<>, 2, 1); // restore 2 2 print_next(1, fact_contr<>, 2, 2); // apply 2 3 print_next(1, fact_contr<>, 2, 3); // r_goto 2 4 print_next(1, fact_contr<>, 2, 4, 1); // branch 1 1 print_next(1, fact_contr<>, 2, 4, 2); // restore 2 1 print_next(1, fact_contr<>, 2, 4, 3); // assign 3 1 printf("\n"); print_next(1, fact_contr<>, 3, 1); // r_goto 3 2 print_next(1, fact_contr<>, 3, 2, 1); // branch 1 1 print_next(1, fact_contr<>, 3, 2, 2); // restore 2 1 print_next(1, fact_contr<>, 3, 2, 3); // assign 3 1 } /***********************************************************************************************************************/ /***********************************************************************************************************************/ /***********************************************************************************************************************/ // debugging (tracing?): /***********************************************************************************************************************/ // restore, apply require 2 nesting depths. <-- the compilation error "between" suggests just one decrement. // n = 5 // depth: // branch 1 - c 1 1 4 1 5 ... // save 2 - c 1 2 4 1 5 ... 4 // save 3 - c 1 3 4 1 5 ... 5 4 // b_apply 4,5 - c 1 4 4 1 4 ... 5 4 // assign 6 - c 1 5 2 1 4 ... 5 4 // l_goto 7 - c 1 6 2 1 4 ... 5 4 // branch 8 - c 1 1 2 1 4 ... 5 4 // save 9 - c 1 2 2 1 4 ... 2 5 4 // save 10 - c 1 3 2 1 4 ... 4 2 5 4 // b_apply 11,12 - c 1 4 2 1 3 ... 4 2 5 4 // assign 13 - c 1 5 2 1 3 ... 4 2 5 4 // l_goto 14 - c 1 6 2 1 3 ... 4 2 5 4 /***********************************************************************************************************************/ // n = 1 // depth: // branch 1 - c 1 1 4 1 1 ... // r_assign 2 - c 3 1 4 1 1 ... // r_goto 3 - c 3 2 4 1 1 ... /***********************************************************************************************************************/ /***********************************************************************************************************************/ /***********************************************************************************************************************/ }
[ "djharris@ualberta.ca" ]
djharris@ualberta.ca
bc78754646eaa6a5af4343552763278c79ab024f
16f2dfe568c296a9356dbcdd5e8b6043967d025e
/ext/v8/upstream/2.1.10/src/heap-profiler.h
d6f26505cd96cfbcdcbcca0ce5d0f7648646bc0e
[ "MIT", "BSD-3-Clause" ]
permissive
skarayan/therubyracer
ddcdf5e3138cc292605ea77f2330b57b961dbb05
cd512d31359efa458d550aecd54686062d4b511c
refs/heads/master
2021-01-17T23:21:45.963707
2010-07-08T15:10:19
2010-07-08T15:10:19
795,376
3
0
null
null
null
null
UTF-8
C++
false
false
9,679
h
// Copyright 2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef V8_HEAP_PROFILER_H_ #define V8_HEAP_PROFILER_H_ #include "zone.h" namespace v8 { namespace internal { #ifdef ENABLE_LOGGING_AND_PROFILING // The HeapProfiler writes data to the log files, which can be postprocessed // to generate .hp files for use by the GHC/Valgrind tool hp2ps. class HeapProfiler { public: // Write a single heap sample to the log file. static void WriteSample(); private: // Update the array info with stats from obj. static void CollectStats(HeapObject* obj, HistogramInfo* info); }; // JSObjectsCluster describes a group of JS objects that are // considered equivalent in terms of a particular profile. class JSObjectsCluster BASE_EMBEDDED { public: // These special cases are used in retainer profile. enum SpecialCase { ROOTS = 1, GLOBAL_PROPERTY = 2, CODE = 3, SELF = 100 // This case is used in ClustersCoarser only. }; JSObjectsCluster() : constructor_(NULL), instance_(NULL) {} explicit JSObjectsCluster(String* constructor) : constructor_(constructor), instance_(NULL) {} explicit JSObjectsCluster(SpecialCase special) : constructor_(FromSpecialCase(special)), instance_(NULL) {} JSObjectsCluster(String* constructor, Object* instance) : constructor_(constructor), instance_(instance) {} static int CompareConstructors(const JSObjectsCluster& a, const JSObjectsCluster& b) { // Strings are unique, so it is sufficient to compare their pointers. return a.constructor_ == b.constructor_ ? 0 : (a.constructor_ < b.constructor_ ? -1 : 1); } static int Compare(const JSObjectsCluster& a, const JSObjectsCluster& b) { // Strings are unique, so it is sufficient to compare their pointers. const int cons_cmp = CompareConstructors(a, b); return cons_cmp == 0 ? (a.instance_ == b.instance_ ? 0 : (a.instance_ < b.instance_ ? -1 : 1)) : cons_cmp; } static int Compare(const JSObjectsCluster* a, const JSObjectsCluster* b) { return Compare(*a, *b); } bool is_null() const { return constructor_ == NULL; } bool can_be_coarsed() const { return instance_ != NULL; } String* constructor() const { return constructor_; } void Print(StringStream* accumulator) const; // Allows null clusters to be printed. void DebugPrint(StringStream* accumulator) const; private: static String* FromSpecialCase(SpecialCase special) { // We use symbols that are illegal JS identifiers to identify special cases. // Their actual value is irrelevant for us. switch (special) { case ROOTS: return Heap::result_symbol(); case GLOBAL_PROPERTY: return Heap::code_symbol(); case CODE: return Heap::arguments_shadow_symbol(); case SELF: return Heap::catch_var_symbol(); default: UNREACHABLE(); return NULL; } } String* constructor_; Object* instance_; }; struct JSObjectsClusterTreeConfig { typedef JSObjectsCluster Key; typedef NumberAndSizeInfo Value; static const Key kNoKey; static const Value kNoValue; static int Compare(const Key& a, const Key& b) { return Key::Compare(a, b); } }; typedef ZoneSplayTree<JSObjectsClusterTreeConfig> JSObjectsClusterTree; // ConstructorHeapProfile is responsible for gathering and logging // "constructor profile" of JS objects allocated on heap. // It is run during garbage collection cycle, thus it doesn't need // to use handles. class ConstructorHeapProfile BASE_EMBEDDED { public: ConstructorHeapProfile(); virtual ~ConstructorHeapProfile() {} void CollectStats(HeapObject* obj); void PrintStats(); // Used by ZoneSplayTree::ForEach. Made virtual to allow overriding in tests. virtual void Call(const JSObjectsCluster& cluster, const NumberAndSizeInfo& number_and_size); private: ZoneScope zscope_; JSObjectsClusterTree js_objects_info_tree_; }; // JSObjectsRetainerTree is used to represent retainer graphs using // adjacency list form: // // Cluster -> (Cluster -> NumberAndSizeInfo) // // Subordinate splay trees are stored by pointer. They are zone-allocated, // so it isn't needed to manage their lifetime. // struct JSObjectsRetainerTreeConfig { typedef JSObjectsCluster Key; typedef JSObjectsClusterTree* Value; static const Key kNoKey; static const Value kNoValue; static int Compare(const Key& a, const Key& b) { return Key::Compare(a, b); } }; typedef ZoneSplayTree<JSObjectsRetainerTreeConfig> JSObjectsRetainerTree; class ClustersCoarser BASE_EMBEDDED { public: ClustersCoarser(); // Processes a given retainer graph. void Process(JSObjectsRetainerTree* tree); // Returns an equivalent cluster (can be the cluster itself). // If the given cluster doesn't have an equivalent, returns null cluster. JSObjectsCluster GetCoarseEquivalent(const JSObjectsCluster& cluster); // Returns whether a cluster can be substitued with an equivalent and thus, // skipped in some cases. bool HasAnEquivalent(const JSObjectsCluster& cluster); // Used by JSObjectsRetainerTree::ForEach. void Call(const JSObjectsCluster& cluster, JSObjectsClusterTree* tree); void Call(const JSObjectsCluster& cluster, const NumberAndSizeInfo& number_and_size); private: // Stores a list of back references for a cluster. struct ClusterBackRefs { explicit ClusterBackRefs(const JSObjectsCluster& cluster_); ClusterBackRefs(const ClusterBackRefs& src); ClusterBackRefs& operator=(const ClusterBackRefs& src); static int Compare(const ClusterBackRefs& a, const ClusterBackRefs& b); void SortRefs() { refs.Sort(JSObjectsCluster::Compare); } static void SortRefsIterator(ClusterBackRefs* ref) { ref->SortRefs(); } JSObjectsCluster cluster; ZoneList<JSObjectsCluster> refs; }; typedef ZoneList<ClusterBackRefs> SimilarityList; // A tree for storing a list of equivalents for a cluster. struct ClusterEqualityConfig { typedef JSObjectsCluster Key; typedef JSObjectsCluster Value; static const Key kNoKey; static const Value kNoValue; static int Compare(const Key& a, const Key& b) { return Key::Compare(a, b); } }; typedef ZoneSplayTree<ClusterEqualityConfig> EqualityTree; static int ClusterBackRefsCmp(const ClusterBackRefs* a, const ClusterBackRefs* b) { return ClusterBackRefs::Compare(*a, *b); } int DoProcess(JSObjectsRetainerTree* tree); int FillEqualityTree(); static const int kInitialBackrefsListCapacity = 2; static const int kInitialSimilarityListCapacity = 2000; // Number of passes for finding equivalents. Limits the length of paths // that can be considered equivalent. static const int kMaxPassesCount = 10; ZoneScope zscope_; SimilarityList sim_list_; EqualityTree eq_tree_; ClusterBackRefs* current_pair_; JSObjectsRetainerTree* current_set_; const JSObjectsCluster* self_; }; // RetainerHeapProfile is responsible for gathering and logging // "retainer profile" of JS objects allocated on heap. // It is run during garbage collection cycle, thus it doesn't need // to use handles. class RetainerHeapProfile BASE_EMBEDDED { public: class Printer { public: virtual ~Printer() {} virtual void PrintRetainers(const JSObjectsCluster& cluster, const StringStream& retainers) = 0; }; RetainerHeapProfile(); void CollectStats(HeapObject* obj); void PrintStats(); void DebugPrintStats(Printer* printer); void StoreReference(const JSObjectsCluster& cluster, HeapObject* ref); private: ZoneScope zscope_; JSObjectsRetainerTree retainers_tree_; ClustersCoarser coarser_; }; class ProducerHeapProfile : public AllStatic { public: static void Setup(); static void RecordJSObjectAllocation(Object* obj) { if (FLAG_log_producers) DoRecordJSObjectAllocation(obj); } private: static void DoRecordJSObjectAllocation(Object* obj); static bool can_log_; }; #endif // ENABLE_LOGGING_AND_PROFILING } } // namespace v8::internal #endif // V8_HEAP_PROFILER_H_
[ "cowboyd@thefrontside.net" ]
cowboyd@thefrontside.net
4f8fa59abdf542089f784ed1f1249b3575710856
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/jingle/notifier/listener/xml_element_util.cc
280485eb71c872c816f727d9e455fd973daa2f69
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,896
cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "jingle/notifier/listener/xml_element_util.h" #include <sstream> #include <string> #include "base/strings/string_number_conversions.h" #include "third_party/webrtc/libjingle/xmllite/qname.h" #include "third_party/webrtc/libjingle/xmllite/xmlconstants.h" #include "third_party/webrtc/libjingle/xmllite/xmlelement.h" #include "third_party/webrtc/libjingle/xmllite/xmlprinter.h" namespace notifier { std::string XmlElementToString(const buzz::XmlElement& xml_element) { std::ostringstream xml_stream; buzz::XmlPrinter::PrintXml(&xml_stream, &xml_element); return xml_stream.str(); } buzz::XmlElement* MakeBoolXmlElement(const char* name, bool value) { const buzz::QName elementQName(buzz::STR_EMPTY, name); const buzz::QName boolAttrQName(buzz::STR_EMPTY, "bool"); buzz::XmlElement* bool_xml_element = new buzz::XmlElement(elementQName, true); bool_xml_element->AddAttr(boolAttrQName, value ? "true" : "false"); return bool_xml_element; } buzz::XmlElement* MakeIntXmlElement(const char* name, int value) { const buzz::QName elementQName(buzz::STR_EMPTY, name); const buzz::QName intAttrQName(buzz::STR_EMPTY, "int"); buzz::XmlElement* int_xml_element = new buzz::XmlElement(elementQName, true); int_xml_element->AddAttr(intAttrQName, base::IntToString(value)); return int_xml_element; } buzz::XmlElement* MakeStringXmlElement(const char* name, const char* value) { const buzz::QName elementQName(buzz::STR_EMPTY, name); const buzz::QName dataAttrQName(buzz::STR_EMPTY, "data"); buzz::XmlElement* data_xml_element = new buzz::XmlElement(elementQName, true); data_xml_element->AddAttr(dataAttrQName, value); return data_xml_element; } } // namespace notifier
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
d9cc7fd484218e5fcd78000a3ebfc5408130f1bc
00285893995139293cae205c5a3bf4a9b26c2042
/nhd2-exp/src/gui/service_setup.h
9b09cbc371abe1dac567bc28ecac9a47f0d37671
[]
no_license
lilo74/neutrinohd2-1
9e8c5148d1c7d39ba00bbc928cc67699cc4451e0
a2dd1c14e725251accda5ef97eb5cf24dc73bea6
refs/heads/master
2020-06-17T12:07:54.034300
2017-03-26T16:34:35
2017-03-26T16:34:35
195,919,111
1
0
null
2019-07-09T02:38:25
2019-07-09T02:38:24
null
UTF-8
C++
false
false
1,257
h
/* Neutrino-GUI - DBoxII-Project $id: service_setup.h 2015.12.22 17:04:28 mohousch $ Copyright (C) 2001 Steffen Hehn 'McClean' and some other guys Homepage: http://dbox.cyberphoria.org/ License: GPL This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __service__ #define __service__ #include <gui/widget/menue.h> #include <string> class CServiceSetup : public CMenuTarget { private: void showMenu(void); void showMenuSmart(void); void showMenuClassic(void); public: CServiceSetup(); ~CServiceSetup(); int exec(CMenuTarget* parent, const std::string& actionKey); }; #endif //__service__
[ "mohousch@gmail.com" ]
mohousch@gmail.com
2ebc9cb6b1b4b68a8a8564a088a8489df653f05f
5b9c956561ddc888a742ee1f17291b74d9cfb864
/felicia/drivers/camera/depth_camera_frame.cc
4114a16537dbe886ede97119a681956be566feb5
[]
no_license
lineCode/felicia
14249f540e453f3e6bdd530dcbb1169c370c9125
ab856fe0d5c85c13d250ecbe148775eda720c987
refs/heads/master
2020-08-31T13:39:20.671100
2019-10-22T23:23:47
2019-10-28T16:17:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,967
cc
#include "felicia/drivers/camera/depth_camera_frame.h" namespace felicia { namespace drivers { DepthCameraFrame::DepthCameraFrame() = default; DepthCameraFrame::DepthCameraFrame(const CameraFrame& other, float min, float max) : CameraFrame(other), min_(min), max_(max) {} DepthCameraFrame::DepthCameraFrame(CameraFrame&& other, float min, float max) : CameraFrame(std::move(other)), min_(min), max_(max) {} DepthCameraFrame::DepthCameraFrame(const DepthCameraFrame& other) : CameraFrame(other), min_(other.min_), max_(other.max_) {} DepthCameraFrame::DepthCameraFrame(DepthCameraFrame&& other) noexcept : CameraFrame(std::move(other)), min_(other.min_), max_(other.max_) {} DepthCameraFrame& DepthCameraFrame::operator=(const DepthCameraFrame& other) = default; DepthCameraFrame& DepthCameraFrame::operator=(DepthCameraFrame&& other) = default; DepthCameraFrame::~DepthCameraFrame() = default; DepthCameraFrameMessage DepthCameraFrame::ToDepthCameraFrameMessage(bool copy) { DepthCameraFrameMessage message; if (copy) { message.set_data(data_.data()); } else { message.set_data(std::move(data_).data()); } *message.mutable_camera_format() = camera_format_.ToCameraFormatMessage(); message.set_timestamp(timestamp_.InMicroseconds()); message.set_min(min_); message.set_max(max_); return message; } Status DepthCameraFrame::FromDepthCameraFrameMessage( const DepthCameraFrameMessage& message) { CameraFormat camera_format; Status s = camera_format.FromCameraFormatMessage(message.camera_format()); if (!s.ok()) return s; CameraFrame camera_frame( Data{message.data()}, camera_format, base::TimeDelta::FromMicroseconds(message.timestamp())); *this = DepthCameraFrame{std::move(camera_frame), message.min(), message.max()}; return Status::OK(); } Status DepthCameraFrame::FromDepthCameraFrameMessage( DepthCameraFrameMessage&& message) { CameraFormat camera_format; Status s = camera_format.FromCameraFormatMessage(message.camera_format()); if (!s.ok()) return s; std::unique_ptr<std::string> data(message.release_data()); CameraFrame camera_frame( Data{std::move(*data)}, camera_format, base::TimeDelta::FromMicroseconds(message.timestamp())); float min = message.min(); float max = message.max(); *this = DepthCameraFrame{std::move(camera_frame), min, max}; return Status::OK(); } #if defined(HAS_OPENCV) // static Status DepthCameraFrame::FromCvMat(cv::Mat mat, const CameraFormat& camera_format, base::TimeDelta timestamp, float min, float max) { CameraFrame camera_frame; Status s = camera_frame.FromCvMat(mat, camera_format, timestamp); if (!s.ok()) return s; *this = {std::move(camera_frame), min, max}; return Status::OK(); } #endif } // namespace drivers } // namespace felicia
[ "chokobole33@gmail.com" ]
chokobole33@gmail.com
2cd21e8fc54ccd796516a38556babbfcaf00067f
fe7113121c8e628fdbb166a3daf7958a187f0eb9
/testing/fuzzers/pdf_fuzzer_init_public.cc
a799c756a8cb06c4b8af15bafb33bb5f4cbde363
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
tszirr/pdfium
f80704b6293e3d07fcc73f8368dc1710c6b19617
6ab909c1a31743b218455ce90d698463069bae79
refs/heads/master
2022-12-31T02:41:35.858154
2020-10-21T10:57:12
2020-10-21T10:57:12
272,494,987
0
0
NOASSERTION
2020-06-15T16:53:13
2020-06-15T16:53:12
null
UTF-8
C++
false
false
3,383
cc
// Copyright 2019 The PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/fuzzers/pdf_fuzzer_init_public.h" #include <string.h> #include "testing/fuzzers/pdfium_fuzzer_util.h" #ifdef PDF_ENABLE_V8 #include "testing/free_deleter.h" #include "testing/v8_initializer.h" #ifdef PDF_ENABLE_XFA #include "testing/fuzzers/xfa_process_state.h" #endif // PDF_ENABLE_XFA #endif // PDF_ENABLE_V8 #ifdef _WIN32 #include <windows.h> #elif defined(__APPLE__) #include <mach-o/dyld.h> #else // Linux #include <linux/limits.h> #include <unistd.h> #endif // _WIN32 namespace { // pdf_fuzzer_init.cc and pdf_fuzzer_init_public.cc are mutually exclusive // and should not be built together. PDFFuzzerInitPublic* g_instance = new PDFFuzzerInitPublic(); #ifdef PDF_ENABLE_V8 std::string ProgramPath() { std::string result; #ifdef _WIN32 char path[MAX_PATH]; DWORD len = GetModuleFileNameA(nullptr, path, MAX_PATH); if (len != 0) result = std::string(path, len); #elif defined(__APPLE__) char path[PATH_MAX]; unsigned int len = PATH_MAX; if (!_NSGetExecutablePath(path, &len)) { std::unique_ptr<char, pdfium::FreeDeleter> resolved_path( realpath(path, nullptr)); if (resolved_path.get()) result = std::string(resolved_path.get()); } #else // Linux char path[PATH_MAX]; ssize_t len = readlink("/proc/self/exe", path, PATH_MAX); if (len > 0) result = std::string(path, len); #endif return result; } #endif // PDF_ENABLE_V8 } // namespace PDFFuzzerInitPublic::PDFFuzzerInitPublic() { #ifdef PDF_ENABLE_V8 #ifdef V8_USE_EXTERNAL_STARTUP_DATA platform_ = InitializeV8ForPDFiumWithStartupData( ProgramPath(), std::string(), std::string(), &snapshot_blob_); #else // V8_USE_EXTERNAL_STARTUP_DATA platform_ = InitializeV8ForPDFium(ProgramPath(), std::string()); #endif // V8_USE_EXTERNAL_STARTUP_DATA #ifdef PDF_ENABLE_XFA allocator_.reset(v8::ArrayBuffer::Allocator::NewDefaultAllocator()); v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = allocator_.get(); isolate_.reset(v8::Isolate::New(create_params)); #if defined(COMPONENT_BUILD) // NOTE: FXGC_* calls are not exported, so we get a separate copy of FXGC // instantiated in the _src targets of a component build. Initialize it, too. FXGC_Initialize(platform_.get(), isolate_.get()); #endif // COMPONENT_BUILD #endif // PDF_ENABLE_XFA #endif // PDF_ENABLE_V8 memset(&config_, '\0', sizeof(config_)); config_.version = 3; config_.m_pUserFontPaths = nullptr; config_.m_pPlatform = nullptr; config_.m_pIsolate = nullptr; config_.m_v8EmbedderSlot = 0; #ifdef PDF_ENABLE_V8 config_.m_pPlatform = platform_.get(); config_.m_pIsolate = isolate_.get(); #endif // PDF_ENABLE_V8 FPDF_InitLibraryWithConfig(&config_); memset(&unsupport_info_, '\0', sizeof(unsupport_info_)); unsupport_info_.version = 1; unsupport_info_.FSDK_UnSupport_Handler = [](UNSUPPORT_INFO*, int) {}; FSDK_SetUnSpObjProcessHandler(&unsupport_info_); #ifdef PDF_ENABLE_XFA xfa_process_state_ = std::make_unique<XFAProcessState>(platform_.get(), isolate_.get()); FPDF_SetFuzzerPerProcessState(xfa_process_state_.get()); #endif } PDFFuzzerInitPublic::~PDFFuzzerInitPublic() { FPDF_SetFuzzerPerProcessState(nullptr); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
5796800da65aa966ee66892152e0ce9021c36f21
f1b43dddc88b6f04aa44119a902bbc2b6610a68b
/Year3/FYP/BallisticsFYP/BallisticsFYP/Systems/CameraSystem.cpp
f16f21738335d79a5ef5764bc0bed17a1ff244ad
[]
no_license
GRMaverick/University
fbf453348e50f111c68f68230768ccda5e1725fc
7f213df8f5a1c81b5b20f30587d347dac3ac1a41
refs/heads/master
2023-03-28T13:50:56.705583
2021-03-31T20:47:11
2021-03-31T20:47:11
353,469,640
0
0
null
null
null
null
UTF-8
C++
false
false
5,396
cpp
#include "pch.h" #include <iostream> #include <DirectXMath.h> #include "IEntity.h" #include "IMediator.h" #include "CameraSystem.h" #include "SetActiveCamera.h" #include "RequestActiveCamera.h" #include "ActiveCameraMessage.h" #include "UpdateFollowMessage.h" #include "GetFollowTargetMessage.h" #include "EntityManager.h" #include "ComponentManager.h" #include "DelegateFactory.h" #include "TransformComponent.h" #include "FPSCameraComponent.h" #include "FollowCameraComponent.h" #include "StaticCameraComponent.h" CameraSystem::CameraSystem(void) { m_Mediator = nullptr; } CameraSystem::~CameraSystem(void) { } void CameraSystem::RegisterMediator(std::shared_ptr<IMediator> mediator) { m_Mediator = mediator; m_Mediator->RegisterReceiveCallback(DELEGATE(&CameraSystem::Receive, this)); } void CameraSystem::Receive(IMessage* pMessage) { if (RequestActiveCamera* pRequestMessage = dynamic_cast<RequestActiveCamera*>(pMessage)) { ActiveCameraMessage* pActiveCameraMessage = new ActiveCameraMessage(m_ActiveCamera); m_Mediator->Send(pActiveCameraMessage); delete pActiveCameraMessage; } if (SetActiveCamera* pSetActiveMessage = dynamic_cast<SetActiveCamera*>(pMessage)) { for (std::string entity : EntitiesManager->GetEntities()) { for (IComponent* component : ComponentsManager->GetAllComponentsForEntity(entity)) { if (ICameraComponent* cam = dynamic_cast<ICameraComponent*>(component)) { std::string target = pSetActiveMessage->GetNewActiveCamera(); if (entity != target) { cam->SetActive(false); } else { cam->SetActive(true); m_ActiveCamera = target; } } } } } if (UpdateFollowMessage* pFollowMessage = dynamic_cast<UpdateFollowMessage*>(pMessage)) { for (std::string entity : EntitiesManager->GetEntities()) { for (IComponent* pComponent : ComponentsManager->GetAllComponentsForEntity(entity)) { if (FollowCameraComponent* pFollowCamera = dynamic_cast<FollowCameraComponent*>(pComponent)) { m_FollowCameraTarget = pFollowMessage->GetTargetName(); pFollowCamera->UpdateViewMatrix(pFollowMessage->GetTarget() + pFollowMessage->GetOffset(), pFollowMessage->GetTarget(), Vector3(0.0f, 1.0f, 0.0f)); } } } } if (GetFollowTargetMessage* pFollowMessage = dynamic_cast<GetFollowTargetMessage*>(pMessage)) { SendFollowTargetMessage* pSendTargetMessage = new SendFollowTargetMessage(m_FollowCameraTarget); m_Mediator->Send(pSendTargetMessage); delete pSendTargetMessage; } } void CameraSystem::Update(DX::StepTimer const& timer) { std::vector<ICameraComponent*> cameraComponents; for (std::string entity : EntitiesManager->GetEntities()) { TransformComponent* pTransform = nullptr; FPSCameraComponent* pFPSCamera = nullptr; FollowCameraComponent* pFollowCamera = nullptr; for (IComponent* component : ComponentsManager->GetAllComponentsForEntity(entity)) { if (ICameraComponent* pTemp = dynamic_cast<ICameraComponent*>(component)) { cameraComponents.push_back(pTemp); } if (FPSCameraComponent* pTemp = dynamic_cast<FPSCameraComponent*>(component)) { pFPSCamera = pTemp; } if (TransformComponent* pTemp = dynamic_cast<TransformComponent*>(component)) { pTransform = pTemp; } } if (pFPSCamera && pTransform) { UpdateFPSCamera(pFPSCamera, pTransform); pTransform->Update(); } } for (ICameraComponent* camera : cameraComponents) { camera->Update(); } } void CameraSystem::UpdateFPSCamera(FPSCameraComponent* pCamera, TransformComponent* pTransform) { XMMATRIX camRotationMatrix = XMMatrixRotationRollPitchYaw(pCamera->GetPitch(), pCamera->GetYaw(), 0.0f); XMVECTOR camTarget = XMVector3TransformCoord(XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), camRotationMatrix); camTarget = XMVector3Normalize(camTarget); XMFLOAT3 forward = XMFLOAT3(pTransform->GetForward().x, pTransform->GetForward().y, pTransform->GetForward().z); XMStoreFloat3(&forward, camTarget); pTransform->SetForward(forward.x, forward.y, forward.z); float xx = asin(-forward.y) * (180 / 3.14159); float yy = (float)((atan2(forward.z, forward.x) / XM_PI) * 180.0f); float zz = 0.0f; if (yy < 0.0f) yy += 360.0f; pTransform->SetRotation(xx, -yy - 270.0f, zz); XMMATRIX rotationYTemp; rotationYTemp = XMMatrixRotationY(pCamera->GetYaw()); XMVECTOR camRight = XMVector3TransformCoord(XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f), rotationYTemp); XMVECTOR camUp = XMVector3TransformCoord(XMVectorSet(pTransform->GetUp().x, pTransform->GetUp().y, pTransform->GetUp().z, 0.0f), rotationYTemp); XMVECTOR camForward = XMVector3TransformCoord(XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), rotationYTemp); XMFLOAT3 cameraUp = XMFLOAT3(); XMStoreFloat3(&cameraUp, camUp); pTransform->SetUp(cameraUp.x, cameraUp.y, cameraUp.z); XMFLOAT3 camPosition = XMFLOAT3(pTransform->GetPosition().x, pTransform->GetPosition().y, pTransform->GetPosition().z); XMVECTOR camPosVector = XMLoadFloat3(&camPosition); camPosVector += pCamera->GetStrafe()*camRight; camPosVector += pCamera->GetAdvance()*camForward; XMStoreFloat3(&camPosition, camPosVector); pTransform->SetPosition(camPosition.x, camPosition.y, camPosition.z); camTarget = camPosVector + camTarget; XMStoreFloat3(&forward, camTarget); pCamera->UpdateViewMatrix(pTransform->GetPosition(), Vector3(forward.x, forward.y, forward.z), pTransform->GetUp()); }
[ "grmaverick@outlook.com" ]
grmaverick@outlook.com
0b1f9fd04c2231934752c932dc4f4b8ddcbb46b2
1901bdbaf57584e7c5ec21643db340f9d98d6807
/compute/tensor/src/cpu/x86/int32/clip.cpp
391bddf31a0f5d8fbf2ebaa5858a544a025a42b7
[ "MIT" ]
permissive
huawei-noah/bolt
2a4febe5f5cce64e3589c2782c489d59975eb6a3
cf4ca8f8646a8e30ddf91c29a18743d75ac1c172
refs/heads/master
2023-08-28T13:36:34.815244
2023-06-12T01:24:41
2023-06-12T01:24:41
225,365,905
889
168
MIT
2023-06-12T01:24:42
2019-12-02T12:06:12
C++
UTF-8
C++
false
false
1,933
cpp
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, 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 "cpu/x86/int32/tensor_computing_int32.h" EE clip_int32(I32 *input, I32 *output, I32 len, I32 minValue, I32 maxValue) { if (nullptr == input || nullptr == output) { CHECK_STATUS(NULL_POINTER); } __m256i min_v = _mm256_set1_epi32(minValue); __m256i max_v = _mm256_set1_epi32(maxValue); I32 i = 0; for (i = 0; i < len - 7; i += 8) { __m256i in = _mm256_loadu_si256((const __m256i *)(input + i)); __m256i tmp_v = _mm256_min_epi32(max_v, _mm256_max_epi32(min_v, in)); _mm256_storeu_si256((__m256i *)(output + i), tmp_v); } for (; i < len; i++) { I32 value = input[i]; value = (value > minValue) ? value : minValue; value = (value < maxValue) ? value : maxValue; output[i] = value; } return SUCCESS; }
[ "jianfeifeng@outlook.com" ]
jianfeifeng@outlook.com
d068627111c756a476bee3d69b60db6423f7602f
9835bee44f1edd6982303ba09b7aeff102f8ec6d
/include/bss-util/LinkedArray.h
3d8865b1f0dc8c6b39208890ed5c814e2f26d72a
[ "MIT", "Apache-2.0" ]
permissive
arves100/bss-util
4f16f1668ab22b5383f494525da9aa657263cf3f
25f5532580ec91d5a689691f4055aada8c730fb1
refs/heads/master
2020-06-19T19:04:59.598206
2019-07-14T15:04:31
2019-07-14T15:04:31
196,836,388
0
0
NOASSERTION
2019-07-14T12:54:23
2019-07-14T12:54:22
null
WINDOWS-1252
C++
false
false
8,372
h
// Copyright ©2018 Black Sphere Studios // For conditions of distribution and use, see copyright notice in "bss_util.h" #ifndef __LINKED_ARRAY_H__BSS__ #define __LINKED_ARRAY_H__BSS__ #include "bss_util.h" #include "Array.h" namespace bss { namespace internal { template<class T, typename CType> struct BSS_COMPILER_DLLEXPORT LINKEDNODE { T val; CType next; CType prev; }; } // Linked list implemented as an array. template<class T, typename CType = size_t, ARRAY_TYPE ArrayType = ARRAY_SIMPLE, typename Alloc = StandardAllocator<internal::LINKEDNODE<T, CType>>> class BSS_COMPILER_DLLEXPORT LinkedArray { public: typedef internal::LINKEDNODE<T, CType> TLNODE; typedef CType CT_; typedef T value_type; inline LinkedArray() : _ref(1), _length(0), _start(-1), _end(-1), _freelist(-1) { _setupChunk(0); } inline LinkedArray(const LinkedArray& copy) : _ref(copy._ref), _length(copy._length), _start(copy._start), _end(copy._end), _freelist(copy._freelist) {} inline LinkedArray(LinkedArray&& mov) : _ref(std::move(mov._ref)), _length(mov._length), _start(mov._start), _end(mov._end), _freelist(mov._freelist) { mov._ref = 1; mov._length = 0; mov._start = mov._end = -1 = mov._freelist = -1; } template<bool U = std::is_void_v<typename Alloc::policy_type>, std::enable_if_t<!U, int> = 0> inline LinkedArray(CT_ size, typename Alloc::policy_type* policy) : _ref(size, policy), _length(0), _start(-1), _end(-1), _freelist(-1) { _setupChunk(0); } inline explicit LinkedArray(CT_ size) : _ref(size), _length(0), _start(-1), _end(-1), _freelist(-1) { _setupChunk(0); } inline ~LinkedArray() {} BSS_FORCEINLINE CT_ Add(const T& item) { return InsertAfter(item, _end); } BSS_FORCEINLINE CT_ Add(T&& item) { return InsertAfter(std::move(item), _end); } BSS_FORCEINLINE CT_ InsertBefore(const T& item, CT_ index) { return _insertBefore<const T&>(item, index); } BSS_FORCEINLINE CT_ InsertBefore(T&& item, CT_ index) { return _insertBefore<T&&>(std::move(item), index); } BSS_FORCEINLINE CT_ InsertAfter(const T& item, CT_ index) { return _insertAfter<const T&>(item, index); } BSS_FORCEINLINE CT_ InsertAfter(T&& item, CT_ index) { return _insertAfter<T&&>(std::move(item), index); } T Remove(CT_ index) { assert(index < _ref.Capacity()); TLNODE& pcur = _ref[index]; if(pcur.next == (CT_)-1) _end = pcur.prev; //you're the end, reassign else _ref[pcur.next].prev = pcur.prev; if(pcur.prev == (CT_)-1) _start = pcur.next; //you're the root, reassign else _ref[pcur.prev].next = pcur.next; _addFreeList(index); --_length; return pcur.val; } inline CT_ Length() const { return _length; } inline CT_ Capacity() const { return _ref.Capacity(); } inline void SetCapacity(CT_ size) { if(size < _ref.Capacity()) return; CT_ hold = _ref.Capacity(); _ref.SetCapacity(size); _setupChunk(hold); } inline void Clear() { _freelist = _start = _end = -1; _length = 0; _setupChunk(0); } BSS_FORCEINLINE void Next(CT_& ref) const { ref = _ref[ref].next; } BSS_FORCEINLINE void Prev(CT_& ref) const { ref = _ref[ref].prev; } BSS_FORCEINLINE CT_ Front() const { return _start; } BSS_FORCEINLINE CT_ Back() const { return _end; } //inline LinkedArray& operator +=(const LinkedArray& right); //inline LinkedArray operator +(const LinkedArray& right) const { LinkedArray retval(*this); retval+=right; return retval; } inline LinkedArray& operator =(const LinkedArray& right) { _ref = right._ref; _length = right._length; _start = right._start; _end = right._end; _freelist = right._freelist; return *this; } inline LinkedArray& operator =(LinkedArray&& mov) { _ref = std::move(mov._ref); _length = mov._length; _start = mov._start; _end = mov._end; _freelist = mov._freelist; return *this; } BSS_FORCEINLINE T& GetItem(CT_ index) { return _ref[index].val; } BSS_FORCEINLINE const T& GetItem(CT_ index) const { return _ref[index].val; } BSS_FORCEINLINE T* GetItemPtr(CT_ index) { return &_ref[index].val; } BSS_FORCEINLINE T& operator [](CT_ index) { return GetItem(index); } BSS_FORCEINLINE const T& operator [](CT_ index) const { return GetItem(index); } // Iterator for LinkedArray template<bool ISCONST, typename U = typename std::conditional<ISCONST, typename std::add_const<T>::type, T>::type, typename D = typename std::conditional<ISCONST, typename std::add_const<LinkedArray>::type, LinkedArray>::type> class BSS_COMPILER_DLLEXPORT cLAIter { public: using iterator_category = std::bidirectional_iterator_tag; using value_type = typename D::value_type; using difference_type = ptrdiff_t; using pointer = U*; using reference = U&; inline explicit cLAIter(D& src) : _src(src), cur((CT_)-1) {} inline cLAIter(D& src, CT_ start) : _src(src), cur(start) {} inline cLAIter(const cLAIter& copy, CT_ start) : _src(copy._src), cur(start) {} BSS_FORCEINLINE U& operator*() const { return _src[cur]; } BSS_FORCEINLINE U* operator->() const { return &_src[cur]; } BSS_FORCEINLINE cLAIter& operator++() { _src.Next(cur); return *this; } //prefix BSS_FORCEINLINE cLAIter operator++(int) { cLAIter r = *this; ++*this; return r; } //postfix BSS_FORCEINLINE cLAIter& operator--() { _src.Prev(cur); return *this; } //prefix BSS_FORCEINLINE cLAIter operator--(int) { cLAIter r = *this; --*this; return r; } //postfix BSS_FORCEINLINE bool operator==(const cLAIter& _Right) const { return (cur == _Right.cur); } BSS_FORCEINLINE bool operator!=(const cLAIter& _Right) const { return (cur != _Right.cur); } BSS_FORCEINLINE bool operator!() const { return cur == (CT_)-1; } BSS_FORCEINLINE bool IsValid() { return cur != (CT_)-1; } BSS_FORCEINLINE void Remove() { _src.Remove(cur); } // Only use this in the form (i++).Remove(), so you don't blow up the iterator. CT_ cur; protected: D& _src; }; inline cLAIter<true> begin() const { return cLAIter<true>(*this, _start); } // Use these to get an iterator you can use in standard containers inline cLAIter<true> end() const { return cLAIter<true>(*this); } inline cLAIter<false> begin() { return cLAIter<false>(*this, _start); } // Use these to get an iterator you can use in standard containers inline cLAIter<false> end() { return cLAIter<false>(*this); } protected: template<typename U> CT_ _insertAfter(U && item, CT_ index) { CT_ cur = _insertPrep(); TLNODE& pcur = _ref[cur]; pcur.val = std::forward<U>(item); pcur.next = (CT_)-1; pcur.prev = (index == (CT_)-1) ? _end : index; if(pcur.prev == (CT_)-1) _start = cur; else { pcur.next = _ref[pcur.prev].next; _ref[pcur.prev].next = cur; } if(pcur.next == (CT_)-1) _end = cur; else _ref[pcur.next].prev = cur; ++_length; return cur; } template<typename U> CT_ _insertBefore(U && item, CT_ index) { CT_ cur = _insertPrep(); TLNODE& pcur = _ref[cur]; pcur.val = std::forward<U>(item); pcur.next = index; pcur.prev = (index == (CT_)-1) ? _end : (CT_)-1; //This allows one to insert after the end with this function if(pcur.next == (CT_)-1) _end = cur; else { pcur.prev = _ref[pcur.next].prev; _ref[pcur.next].prev = cur; } if(pcur.prev == (CT_)-1) _start = cur; else { _ref[pcur.prev].next = cur; } ++_length; return cur; } inline void _addFreeList(CT_ index) { _ref[index].next = _freelist; _freelist = index; } inline void _setupChunk(CT_ start) { CT_ i = _ref.Capacity(); while(i > start) //this trick lets us run backwards without worrying about the unsigned problem. _addFreeList(--i); } inline CT_ _insertPrep() { if(_freelist == (CT_)-1) SetCapacity(fbnext(_ref.Capacity())); CT_ cur = _freelist; _freelist = _ref[_freelist].next; //increment freelist return cur; } CT_ _length; CT_ _start; CT_ _end; CT_ _freelist; private: Array<internal::LINKEDNODE<T, CType>, CType, ArrayType, Alloc> _ref; }; } #endif
[ "erikm@blackspherestudios.com" ]
erikm@blackspherestudios.com
1244fa0f6cf3f1ffe9daeed92c29a1ccda89fef7
2038992ee0781618685d06a137893138b3ed24f5
/include/ipv4.h
434ec41968e5ff8a75ac0f417c672ae5ee70cb27
[]
no_license
eatonphil/unet
0fc19c820a466fce3d974237b1d5b2a3521933b7
bf0a8f56810ea0a60f830c7f87c1678e0a162f60
refs/heads/master
2020-05-01T05:32:30.706587
2019-06-03T01:02:29
2019-06-03T01:02:29
177,304,773
0
0
null
null
null
null
UTF-8
C++
false
false
442
h
#ifndef IPV4_H #define IPV4_H #include "common.h" #include "layers.h" #include "tcp.h" namespace IPv4 { const int OPCODE_IPV4_REQUEST = 1; const int OPCODE_IPV4_RESPONSE = 2; const int HRD_ETHERNET = 1; const int HRD_IEEE802 = 6; class Handler { private: uint8_t address[4]; TCP::Handler &handler; public: std::tuple<std::vector<uint8_t>, ssize_t, error> HandlePacket(Layers::HardwarePacket pkt); } } // namespace IPv4 #endif
[ "philneaton95@gmail.com" ]
philneaton95@gmail.com
9a225bf0ddbe0f85999e3950f554f605d653ab94
52146e6a28701dbe41f70035832e23a787598684
/thirdparty/Kinetis-SDK/middleware/multicore/erpc/erpcgen/src/types/SymbolScope.h
75db4e5c365f5359804aea4686ee40b69ecbd409
[ "BSD-3-Clause", "BSD-3-Clause-Clear" ]
permissive
hiteshrai/redurchin
0a47a589957f95385e1657960b5475f7b78494bd
4cfd6f93d4c9ee0b0166b6ea25b7f266695cb32d
refs/heads/master
2021-06-09T15:43:56.299547
2019-10-23T02:21:45
2019-10-23T02:21:45
146,197,681
0
0
null
null
null
null
UTF-8
C++
false
false
9,645
h
/* * The Clear BSD License * Copyright (c) 2014, Freescale Semiconductor, Inc. * Copyright 2016 NXP * All rights reserved. * * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided * that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o 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. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EMBEDDED_RPC__SYMBOLSCOPE_H_ #define _EMBEDDED_RPC__SYMBOLSCOPE_H_ #include "Symbol.h" #include <map> #include <string> #include <vector> //////////////////////////////////////////////////////////////////////////////// // Classes //////////////////////////////////////////////////////////////////////////////// namespace erpcgen { /*! * @brief A scoped namespace containing symbols. */ class SymbolScope { public: typedef std::map<std::string, Symbol *> symbol_map_t; /*!< Map symbol name to symbol type. */ typedef std::vector<Symbol *> symbol_vector_t; /*!< Vector of symbol types. */ class typed_iterator { public: typedef symbol_vector_t::iterator vit; typedef vit::value_type value_type; operator value_type &() { return *m_vec; } value_type &operator*() { return *m_vec; } value_type &operator->() { return *m_vec; } /*! * @brief */ typed_iterator &operator++(); bool operator==(const typed_iterator &other) { return (m_vec == other.m_vec); } bool operator!=(const typed_iterator &other) { return !(*this == other); } private: symbol_vector_t::iterator m_vec; symbol_vector_t::iterator m_endvec; Symbol::symbol_type_t m_predicateType; /*! * @brief * * @param[in] bv * @param[in] ev * @param[in] predicateType */ typed_iterator(const vit &bv, const vit &ev, Symbol::symbol_type_t predicateType); friend class SymbolScope; }; /*! * @brief Constructor. */ SymbolScope() : m_symbolMap() , m_symbolVector() , m_parent(nullptr) { } /*! * @brief Destructor. */ virtual ~SymbolScope() {} /*! * @brief This function returns true when name is found in symbol map. * * This function returns true when name is found in symbol map. Symbol is found using given name. * * @param[in] name Name, which is used to find symbol. * @param[in] recursive If true, then recursive finding is allowed. * * @retval true (symbol is found) * @retval false (symbol isn't found) * * @see void SymbolScope::addSymbol() * @see Symbol * SymbolScope::getSymbol() * @see void SymbolScope::replaceSymbol() */ bool hasSymbol(const std::string &name, bool recursive = true); /*! * @brief This function will return symbol. * * This function returns symbol found in symbol scope map m_symbolMap. Symbol is found using given name. * * @param[in] name Name, which is used to find symbol. * @param[in] recursive If true, then recursive finding is allowed. * * @return Requested symbol from symbol vector. * @retval nullptr (when symbol wasn't found) * * @see void SymbolScope::addSymbol() * @see bool SymbolScope::hasSymbol() * @see void SymbolScope::replaceSymbol() */ Symbol *getSymbol(const std::string &name, bool recursive = true); /*! * @brief This function will add symbol to the symbol scope. * * The function will add symbol given by pointer sym to the symbol scope vector m_symbolVector. * If symbol with same name is already added, will be throw semantic error. * * @param[in] sym Symbol pointer, which is added to symbol scope vector. * @param[in] pos Position where symbol should be added. Default -1 mean at the end of vector. * * @see Symbol * SymbolScope::getSymbol() * @see bool SymbolScope::hasSymbol() * @see void SymbolScope::replaceSymbol() */ void addSymbol(Symbol *sym, int32_t pos = -1); /*! * @brief This function will replace old symbol with new symbol in the symbol scope. * * The function will remove old symbol and call addSymbol with new symbol. * * @param[in] oldSym Symbol pointer, which will be replaced. * @param[in] newSym Symbol pointer, which will be replacer. * * @see Symbol * SymbolScope::addSymbol() * @see Symbol * SymbolScope::getSymbol() * @see bool SymbolScope::hasSymbol() */ void replaceSymbol(Symbol *oldSym, Symbol *newSym); /*! * @brief This function will return symbol position. * * The function will return symbol position of given symbol by pointer sym from the * symbol scope vector m_symbolVector. * * @param[in] sym Pointer of symbol, which position is searched. * * @return -1 if position is not found, else position number. * * @see Symbol * SymbolScope::addSymbol() */ int32_t getSymbolPos(Symbol *sym); /*! * @brief Return boolean representation about existence of parent. * * @retval true When parent is set. * @retval false When parent isn't set. */ bool hasParent() const { return m_parent != nullptr; } /*! * @brief Return pointer to parent. * * @return Pointer to parent. */ SymbolScope *getParent() { return m_parent; } /*! * @brief This function set parent for this object. * * @param[in] parent Pointer to given parent. */ void setParent(SymbolScope *parent) { m_parent = parent; } /*! * @brief Return begin of symbol vector. * * @return Return begin of symbol vector. */ symbol_vector_t::iterator begin() { return m_symbolVector.begin(); } /*! * @brief Return end of symbol vector. * * @return Return end of symbol vector. */ symbol_vector_t::iterator end() { return m_symbolVector.end(); } /*! * @brief * * @param[in] predicateType */ typed_iterator tbegin(Symbol::symbol_type_t predicateType); /*! * @brief * * @param[in] predicateType */ typed_iterator tend(Symbol::symbol_type_t predicateType); /*! * @brief This function returns symbol vector with symbols. * * This function returns symbol vector with symbols, which are requested. Symbols are found using given * symbol_type_t. * * @param[in] predicateType Symbol type, which is requested. * * @return Symbol vector with requested symbols. */ symbol_vector_t getSymbolsOfType(Symbol::symbol_type_t predicateType); /*! * @brief This function returns symbol vector. * * @return Symbol vector with all symbols. */ symbol_vector_t getSymbolVector() { return m_symbolVector; } /*! * @brief This function show debug description about the all symbols. * * @see std::string Interface::getDescription() const * @see std::string Function::getDescription() const * @see std::string AliasType::getDescription() const * @see std::string EnumMember::getDescription() const * @see std::string EnumType::getDescription() const * @see std::string StructMember::getDescription() const * @see std::string StructType::getDescription() const * @see std::string VoidType::getDescription() const * @see std::string ArrayType::getDescription() const * @see std::string ListType::getDescription() const */ void dump(); /*! * @brief Erase data from m_symbolMap and m_symbolVector */ void clear(); protected: symbol_map_t m_symbolMap; /*!< Map Symbols to names. */ symbol_vector_t m_symbolVector; /*!< Vector of Symbols */ SymbolScope *m_parent; /*!< Scope of Symbol */ }; } // namespace erpcgen #endif // _EMBEDDED_RPC__SYMBOLSCOPE_H_
[ "hiteshrai1013@gmail.com" ]
hiteshrai1013@gmail.com
a26c421916165148b98e409d8a6fabd88d714122
a1a57977131ea917a3f3094dae4a3d18846103c0
/unittests/libtests/friction/test_friction.cc
686c4d4fcbd804a4e4c02fb821953ee6f9a90e8d
[ "MIT" ]
permissive
rwalkerlewis/pylith
cef02d5543e99a3e778a1c530967e6b5f1d5dcba
8d0170324d3fcdc5e6c4281759c680faa5dd8d38
refs/heads/master
2023-08-24T18:27:30.877550
2020-08-05T16:37:28
2020-08-05T16:37:28
154,047,591
0
0
MIT
2018-10-21T20:05:59
2018-10-21T20:05:59
null
UTF-8
C++
false
false
2,244
cc
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include "petsc.h" #include <Python.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/BriefTestProgressListener.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/TextOutputter.h> #include <stdlib.h> // USES abort() #define MALLOC_DUMP int main(int argc, char* argv[]) { // main CppUnit::TestResultCollector result; try { // Initialize PETSc PetscErrorCode err = PetscInitialize(&argc, &argv, NULL, NULL);CHKERRQ(err); #if defined(MALLOC_DUMP) err = PetscOptionsSetValue(NULL, "-malloc_dump", "");CHKERRQ(err); #endif // Initialize Python (to eliminate need to initialize when // parsing units in spatial databases). Py_Initialize(); // Create event manager and test controller CppUnit::TestResult controller; // Add listener to collect test results controller.addListener(&result); // Add listener to show progress as tests run CppUnit::BriefTestProgressListener progress; controller.addListener(&progress); // Add top suite to test runner CppUnit::TestRunner runner; runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); runner.run(controller); // Print tests CppUnit::TextOutputter outputter(&result, std::cerr); outputter.write(); // Finalize Python Py_Finalize(); // Finalize PETSc err = PetscFinalize(); CHKERRQ(err); } catch (...) { abort(); } // catch #if !defined(MALLOC_DUMP) std::cout << "WARNING -malloc dump is OFF\n" << std::endl; #endif return (result.wasSuccessful() ? 0 : 1); } // main // End of file
[ "baagaard@usgs.gov" ]
baagaard@usgs.gov
d7da3a858aee6214d41f7acc0fb11fbfcd0b0c98
25cec3f4f349c4412d708effd916e9706c01c180
/Heur/EntropyCalculator.h
58579dbd6709646ed304885219b535ddbe52b905
[]
no_license
Confocus/DTHeur
72f8d58b72adff64d95a73e9b0904a681974ba00
e59e7966f7c0b7b65e1a939c48866d031dfe5ec1
refs/heads/master
2020-07-07T23:04:28.541158
2019-08-21T04:14:58
2019-08-21T04:14:58
203,500,063
2
1
null
null
null
null
GB18030
C++
false
false
2,647
h
#pragma once #include "stdafx.h" #include <stdint.h> #include <algorithm> #include <cmath> #define MAX_SIZE 0x500 class CEntropyCalculator { public: CEntropyCalculator(void); ~CEntropyCalculator(void); public: void Clean(); BOOL Check(PUCHAR, BOOL, LONGLONG); void Check2(PUCHAR, BOOL, LONGLONG, double*);//计算熵值但是不包括头部 BOOL CheckExtraEntropy(PUCHAR, BOOL, LONGLONG, LONGLONG, double*); /** * 设置这条特征的属性,是黑特征还是白特征 * * @param image_base : 待计算熵的内存数据地址 * @param bmem : 是内存数据还是文件映射,默认是FALSE(文件映射) * @param llSize : 传入的数据的大小 * @param nSecIndex : 要计算熵的节区的索引值 * @param pfent : 保存计算的熵值的变量的指针 * @return */ BOOL CheckSection(PUCHAR image_base, BOOL bmem, LONGLONG llSize, int nSecIndex, double* pfent); /** * 设置这条特征的属性,是黑特征还是白特征 * * @param image_base : 待计算熵的内存数据地址 * @param bmem : 是内存数据还是文件映射,默认是FALSE(文件映射) * @param llSize : 传入的数据的大小 * @param pfent : 保存计算的熵值的变量的指针 * @return */ BOOL CheckFileEntropy(PUCHAR image_base, BOOL bmem, LONGLONG llSize, double* pfent); /** * 设置这条特征的属性,是黑特征还是白特征 * * @param image_base : 待计算熵的内存数据地址 * @param bmem : 是内存数据还是文件映射,默认是FALSE(文件映射) * @param llSize : 传入的数据的大小 * @param pfent : 保存计算的熵值的变量的指针 * @return */ BOOL CheckRsrcEntropy(PUCHAR image_base, BOOL bmem, LONGLONG llSize, double* pfent); /** * 设置这条特征的属性,是黑特征还是白特征 * * @param image_base : 待计算熵的内存数据地址 * @param bmem : 是内存数据还是文件映射,默认是FALSE(文件映射) * @param llSize : 传入的数据的大小 * @return */ BOOL CheckBlockEntropy(PUCHAR image_base, BOOL bmem, LONGLONG llSize); BOOL Is_Packed(PUCHAR); double GetHighEntropySectionRatio(); double GetHighEntropyBlockRatio(); private: double CalcEntropy(const uint32_t byte_count[256], size_t total_length); double CalcEntropy(const char* data, size_t length); BOOL GetEntropyConfigPath(); BOOL ParseEntropyFile(); BOOL GetEntropyIniValue(char* szItemName, double* pEntropy); private: int m_nHighEntropyBlockCnt; double m_dHighBlockEntropy; double m_dHighEntropyBlockRatio; double m_dHighSectionEntropy; double m_dHighEntropySectionRatio; char m_szEntropyFilePath[MAX_SIZE]; };
[ "wangteng@qianxin.com" ]
wangteng@qianxin.com
76671118659899db975679143cf691ea9df5d169
0982a13a1b525931042b7ad1a3271f12673204c6
/Artefact Engine/madlibs/Include/PhysX/cooking/PxCooking.h
5a3d1c651aefb0137f3b3272780e9440aa808079
[]
no_license
Syzygy2048/InLimbo
a0a87e5a8296f2bec336165d58ef6a49f78cc830
cb7669d678b4e5a13176fe70288c0146e775b050
refs/heads/master
2021-01-19T10:34:58.934382
2014-04-28T17:33:48
2014-04-28T17:33:48
16,291,635
2
0
null
null
null
null
UTF-8
C++
false
false
12,275
h
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_COOKING_H #define PX_COOKING_H /** \addtogroup cooking @{ */ #include "PhysX/common/PxPhysXCommonConfig.h" #include "PhysX/common/PxTolerancesScale.h" #include "PhysX/cooking/Pxc.h" #include "PhysX/cooking/PxConvexMeshDesc.h" #include "PhysX/cooking/PxTriangleMeshDesc.h" #ifndef PX_DOXYGEN namespace physx { #endif class PxOutputStream; class PxBinaryConverter; struct PxPlatform { enum Enum { ePC, eXENON, ePLAYSTATION3, eARM, eWIIU }; }; /** \brief Enum for the set of mesh pre-processing parameters. */ struct PxMeshPreprocessingFlag { enum Enum { eWELD_VERTICES = 1 << 0, eREMOVE_UNREFERENCED_VERTICES = 1 << 1, eREMOVE_DUPLICATED_TRIANGLES = 1 << 2 }; }; typedef PxFlags<PxMeshPreprocessingFlag::Enum,PxU32> PxMeshPreprocessingFlags; /** \brief Structure describing parameters affecting mesh cooking. @see PxSetCookingParams() PxGetCookingParams() */ struct PxCookingParams { /** \brief Target platform Should be set to the platform which you intend to load the cooked mesh data on. This allows the SDK to optimize the mesh data in an appropriate way for the platform and make sure that endianness issues are accounted for correctly. <b>Default value:</b> Same as the platform on which the SDK is running. */ PxPlatform::Enum targetPlatform; /** \brief Skin width for convexes. Specifies the amount to inflate the convex mesh when the PxConvexFlag::eINFLATE_CONVEX is used. The value is used for moving planes outward, and beveling sharp edges. This helps the hull generator code produce more stable convexes for collision detection. Please note that the resulting hull will increase its size, so contact generation may produce noticeable separation between shapes. The separation distance can be reduced by decreasing the contactOffset and restOffset. See the user's manual on 'Shapes - Tuning Shape Collision Behavior' for details. Change the value if the produced hulls are too thin or improper for your usage. Increasing the value too much will result in incorrect hull size and a large separation between shapes. <b>Default value:</b> 0.025f*PxToleranceScale.length <b>Range:</b> (0.0f, PX_MAX_F32) */ float skinWidth; /** \brief When true, the face remap table is not created. This saves a significant amount of memory, but the SDK will not be able to provide information about which mesh triangle is hit in collisions, sweeps or raycasts hits. <b>Default value:</b> false */ bool suppressTriangleMeshRemapTable; /** \brief When true, the triangle adjacency information is created. You can get the adjacency triangles for a given triangle from getTriangle. <b>Default value:</b> false */ bool buildTriangleAdjacencies; /** \brief Tolerance scale is used to check if cooked triangles are not too huge. This check will help with simulation stability. @see PxTolerancesScale */ PxTolerancesScale scale; /** \brief Mesh pre-processing parameters. Used to control options like whether the mesh cooking performs vertex welding before cooking. <b>Default value:</b> 0 */ PxMeshPreprocessingFlags meshPreprocessParams; /** \brief Mesh weld tolerance. If mesh welding is enabled, this controls the distance at which vertices are welded. If mesh welding is not enabled, this value defines the acceptance distance for mesh validation. Provided no two vertices are within this distance, the mesh is considered to be clean. If not, a warning will be emitted. Having a clean, welded mesh is required to achieve the best possible performance. The default vertex welding uses a snap-to-grid approach. This approach effectively truncates each vertex to integer values using meshWeldTolerance. Once these snapped vertices are produced, all vertices that snap to a given vertex on the grid are remapped to reference a single vertex. Following this, all triangles' indices are remapped to reference this subset of clean vertices. It should be noted that the vertices that we do not alter the position of the vertices; the snap-to-grid is only performed to identify nearby vertices. The mesh validation approach also uses the same snap-to-grid approach to identify nearby vertices. If more than one vertex snaps to a given grid coordinate, we ensure that the distance between the vertices is at least meshWeldTolerance. If this is not the case, a warning is emitted. <b>Default value:</b> 0.0 */ PxReal meshWeldTolerance; PxCookingParams(const PxTolerancesScale& sc): skinWidth(0.025f*sc.length), suppressTriangleMeshRemapTable(false), buildTriangleAdjacencies(false), scale(sc), meshPreprocessParams(0), meshWeldTolerance(0.f) { #if defined(PX_X86) || defined(PX_X64) targetPlatform = PxPlatform::ePC; #elif defined(PX_X360) targetPlatform = PxPlatform::eXENON; #elif defined(PX_PS3) targetPlatform = PxPlatform::ePLAYSTATION3; #elif defined(PX_ARM) targetPlatform = PxPlatform::eARM; #elif defined(PX_WIIU) targetPlatform = PxPlatform::eWIIU; #else #error Unknown platform #endif } }; class PxCooking { public: /** \brief Closes this instance of the interface. This function should be called to cleanly shut down the Cooking library before application exit. \note This function is required to be called to release foundation usage. */ virtual void release() = 0; /** \brief Sets cooking parameters \param[in] params Cooking parameters @see getParams() */ virtual void setParams(const PxCookingParams& params) = 0; /** \brief Gets cooking parameters \return Current cooking parameters. @see PxCookingParams setParams() */ virtual const PxCookingParams& getParams() = 0; /** \brief Checks endianness is the same between cooking & target platforms \return True if there is and endian mismatch. */ virtual bool platformMismatch() = 0; /** \brief Cooks a triangle mesh. The results are written to the stream. To create a triangle mesh object it is necessary to first 'cook' the mesh data into a form which allows the SDK to perform efficient collision detection. cookTriangleMesh() allows a mesh description to be cooked into a binary stream suitable for loading and performing collision detection at runtime. Example \include PxCookTriangleMesh_Example.cpp \param[in] desc The triangle mesh descriptor to read the mesh from. \param[in] stream User stream to output the cooked data. \return true on success @see cookConvexMesh() setParams() PxPhysics.createTriangleMesh() */ virtual bool cookTriangleMesh(const PxTriangleMeshDesc& desc, PxOutputStream& stream) = 0; /** \brief Cooks a convex mesh. The results are written to the stream. To create a triangle mesh object it is necessary to first 'cook' the mesh data into a form which allows the SDK to perform efficient collision detection. cookConvexMesh() allows a mesh description to be cooked into a binary stream suitable for loading and performing collision detection at runtime. Example \include PxCookConvexMesh_Example.cpp \note This method is not reentrant if the convex mesh descriptor has the flag #PxConvexFlag::eCOMPUTE_CONVEX set. \note The number of vertices and the number of convex polygons in a cooked convex mesh is limited to 256. \note If those limits are exceeded in either the user-provided data or the final cooked mesh, an error is reported. \note If this happens, using the #PxConvexFlag::eINFLATE_CONVEX is usually enough to obtain a valid convex. \param[in] desc The convex mesh descriptor to read the mesh from. \param[in] stream User stream to output the cooked data. \return true on success @see cookTriangleMesh() setParams() */ virtual bool cookConvexMesh(const PxConvexMeshDesc& desc, PxOutputStream& stream) = 0; /** \brief Computed hull polygons from given vertices and triangles. Polygons are needed for PxConvexMeshDesc rather then triangles. \param[in] mesh Simple triangle mesh containing vertices and triangles used to compute polygons. \param[in] inCallback Memory allocator for out array allocations. \param[out] nbIndices Number of indices used by polygons. \param[out] indices Indices array used by polygons. \param[out] nbPolygons Number of created polygons. \param[out] hullPolygons Polygons array. \return true on success @see cookConvexMesh() PxConvexFlags PxConvexMeshDesc PxSimpleTriangleMesh */ virtual bool computeHullPolygons(const PxSimpleTriangleMesh& mesh, PxAllocatorCallback& inCallback, PxU32& nbIndices, PxU32*& indices, PxU32& nbPolygons, PxHullPolygon*& hullPolygons) = 0; /** \brief Cooks a heightfield. The results are written to the stream. To create a heightfield object there is an option to precompute some of calculations done while loading the heightfield data. cookHeightField() allows a heightfield description to be cooked into a binary stream suitable for loading and performing collision detection at runtime. Example \include PxCookConvexMesh_Example.cpp \param[in] desc The heightfield descriptor to read the HF from. \param[in] stream User stream to output the cooked data. \return true on success @see PxPhysics.createHeightField() */ virtual bool cookHeightField(const PxHeightFieldDesc& desc, PxOutputStream& stream) = 0; protected: virtual ~PxCooking(){} }; #ifndef PX_DOXYGEN } // namespace physx #endif /** \brief Create an instance of the cooking interface. Note that the foundation object is handled as an application-wide singleton in statically linked executables and a DLL-wide singleton in dynamically linked executables. Therefore, if you are using the runtime SDK in the same executable as cooking, you should pass the Physics's copy of foundation (acquired with PxPhysics::getFoundation()) to the cooker. This will also ensure correct handling of memory for objects passed from the cooker to the SDK. To use cooking in standalone mode, create an instance of the Foundation object with PxCreateCookingFoundation. You should pass the same foundation object to all instances of the cooking interface. \param[in] version the SDK version number \param[in] foundation the foundation object associated with this instance of the cooking interface. \param[in] params the parameters for this instance of the cooking interface \return true on success. */ PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxCooking* PX_CALL_CONV PxCreateCooking(physx::PxU32 version, physx::PxFoundation& foundation, const physx::PxCookingParams& params); /** @} */ #endif
[ "pollak.peter89@gmail.com" ]
pollak.peter89@gmail.com
e387b2c6fddf7f3974284409553fb01df9be4503
59bfc0d2a33eb31f49c9875ebbcedae503b81c84
/src/models/links/links.cpp
84d1af8cc40b3c4f5e187170bb96f12b0dd5f6a6
[]
no_license
lnxslck/buho
1e6475793904e5d6f9e5cb6f26657ed3b6150327
075e468e175490fe39066bab0191dc264d2bafc8
refs/heads/master
2020-04-09T02:45:37.479345
2018-12-01T20:08:55
2018-12-01T20:08:55
150,332,509
0
0
null
2018-09-25T21:40:43
2018-09-25T21:40:43
null
UTF-8
C++
false
false
5,774
cpp
#include "links.h" #include <QUuid> #include "db/db.h" #include "linker.h" #ifdef STATIC_MAUIKIT #include "tagging.h" #else #include <MauiKit/tagging.h> #endif Links::Links(QObject *parent) : BaseList(parent) { this->db = DB::getInstance(); this->tag = Tagging::getInstance(); this->sortList(); connect(this, &Links::sortByChanged, this, &Links::sortList); connect(this, &Links::orderChanged, this, &Links::sortList); } void Links::sortList() { emit this->preListChanged(); this->links = this->db->getDBData(QString("select * from links ORDER BY %1 %2").arg( OWL::KEYMAP[this->sort], this->order == ORDER::ASC ? "asc" : "desc")); emit this->postListChanged(); } QVariantMap Links::get(const int &index) const { if(index >= this->links.size() || index < 0) return QVariantMap(); QVariantMap res; const auto note = this->links.at(index); for(auto key : note.keys()) res.insert(OWL::KEYMAP[key], note[key]); return res; } OWL::DB_LIST Links::items() const { return this->links; } bool Links::insert(const QVariantMap &link) { emit this->preItemAppended(); auto url = link[OWL::KEYMAP[OWL::KEY::LINK]].toString(); auto color = link[OWL::KEYMAP[OWL::KEY::COLOR]].toString(); auto pin = link[OWL::KEYMAP[OWL::KEY::PIN]].toInt(); auto fav = link[OWL::KEYMAP[OWL::KEY::FAV]].toInt(); auto tags = link[OWL::KEYMAP[OWL::KEY::TAG]].toStringList(); auto preview = link[OWL::KEYMAP[OWL::KEY::PREVIEW]].toString(); auto title = link[OWL::KEYMAP[OWL::KEY::TITLE]].toString(); auto image_path = OWL::saveImage(Linker::getUrl(preview), OWL::LinksPath+QUuid::createUuid().toString()); QVariantMap link_map = { {OWL::KEYMAP[OWL::KEY::LINK], url}, {OWL::KEYMAP[OWL::KEY::TITLE], title}, {OWL::KEYMAP[OWL::KEY::PIN], pin}, {OWL::KEYMAP[OWL::KEY::FAV], fav}, {OWL::KEYMAP[OWL::KEY::PREVIEW], image_path}, {OWL::KEYMAP[OWL::KEY::COLOR], color}, {OWL::KEYMAP[OWL::KEY::ADD_DATE], QDateTime::currentDateTime().toString()}, {OWL::KEYMAP[OWL::KEY::UPDATED], QDateTime::currentDateTime().toString()} }; if(this->db->insert(OWL::TABLEMAP[OWL::TABLE::LINKS], link_map)) { for(auto tg : tags) this->tag->tagAbstract(tg, OWL::TABLEMAP[OWL::TABLE::LINKS], url, color); this->links << OWL::DB ({ {OWL::KEY::LINK, url}, {OWL::KEY::TITLE, title}, {OWL::KEY::COLOR, color}, {OWL::KEY::PREVIEW, image_path}, {OWL::KEY::PIN, QString::number(pin)}, {OWL::KEY::FAV, QString::number(fav)}, {OWL::KEY::UPDATED, QDateTime::currentDateTime().toString()}, {OWL::KEY::ADD_DATE, QDateTime::currentDateTime().toString()} }); emit postItemAppended(); return true; } else qDebug()<< "LINK COULD NOT BE INSTED"; return false; } bool Links::update(const int &index, const QVariant &value, const int &role) { if(index < 0 || index >= links.size()) return false; const auto oldValue = this->links[index][static_cast<OWL::KEY>(role)]; if(oldValue == value.toString()) return false; qDebug()<< "VALUE TO UPDATE"<< OWL::KEYMAP[static_cast<OWL::KEY>(role)] << oldValue; this->links[index].insert(static_cast<OWL::KEY>(role), value.toString()); this->update(this->links[index]); return true; } bool Links::update(const QVariantMap &data, const int &index) { if(index < 0 || index >= this->links.size()) return false; auto newData = this->links[index]; QVector<int> roles; for(auto key : data.keys()) if(newData[OWL::MAPKEY[key]] != data[key].toString()) { newData.insert(OWL::MAPKEY[key], data[key].toString()); roles << OWL::MAPKEY[key]; } this->links[index] = newData; if(this->update(newData)) { qDebug() << "update link" << newData; emit this->updateModel(index, roles); return true; } return false; } bool Links::update(const OWL::DB &link) { auto url = link[OWL::KEY::LINK]; auto color = link[OWL::KEY::COLOR]; auto pin = link[OWL::KEY::PIN].toInt(); auto fav = link[OWL::KEY::FAV].toInt(); auto tags = link[OWL::KEY::TAG].split(",", QString::SkipEmptyParts); auto updated = link[OWL::KEY::UPDATED]; QVariantMap link_map = { {OWL::KEYMAP[OWL::KEY::COLOR], color}, {OWL::KEYMAP[OWL::KEY::PIN], pin}, {OWL::KEYMAP[OWL::KEY::FAV], fav}, {OWL::KEYMAP[OWL::KEY::UPDATED], updated} }; for(auto tg : tags) this->tag->tagAbstract(tg, OWL::TABLEMAP[OWL::TABLE::LINKS], url, color); return this->db->update(OWL::TABLEMAP[OWL::TABLE::LINKS], link_map, {{OWL::KEYMAP[OWL::KEY::LINK], url}} ); } bool Links::remove(const int &index) { emit this->preItemRemoved(index); auto linkUrl = this->links.at(index)[OWL::KEY::LINK]; QVariantMap link = {{OWL::KEYMAP[OWL::KEY::LINK], linkUrl}}; if(this->db->remove(OWL::TABLEMAP[OWL::TABLE::LINKS], link)) { this->links.removeAt(index); emit this->postItemRemoved(); return true; } return false; } QVariantList Links::getTags(const int &index) { if(index < 0 || index >= this->links.size()) return QVariantList(); auto link = this->links.at(index)[OWL::KEY::LINK]; return this->tag->getAbstractTags(OWL::TABLEMAP[OWL::TABLE::LINKS], link); }
[ "milo.h@aol.com" ]
milo.h@aol.com
18c7257b2f14a5eec62805a86090f993ab471481
51dd54d61a04a7ba6c0d8c9bb35e2267cf68ac30
/Fish/Classes/CannonEffect.cpp
9647f0eebc48b4e7213a992ebb1d935bbe682220
[ "MIT" ]
permissive
xuerendeqing/ProjectWork
5a811b90e64389cb04aca6d2005351fddb8ff3ae
3f9bc7903f77570990531cff152ad5b65ac43b73
refs/heads/master
2020-12-30T13:28:43.924604
2017-05-14T09:54:17
2017-05-14T09:54:17
91,215,661
0
1
null
null
null
null
GB18030
C++
false
false
1,419
cpp
#include "CannonEffect.h" CannonEffect::CannonEffect() :e_delay(0.08f) { } CannonEffect::~CannonEffect() { AnimationCache::getInstance()->removeAnimation("RunCannonEffect"); } bool CannonEffect::init() { if (!Sprite::init()) { return false; } this->setAnchorPoint(Vec2::ANCHOR_MIDDLE); e_ActiveFrames =7;//特效的帧数 e_String = "WeaponSwitch00";//特效文件 auto m_Animation = createAnimation(e_String, e_ActiveFrames, e_delay); m_Animation->retain(); AnimationCache::getInstance()->addAnimation(m_Animation, "RunCannonEffect"); this->runAction(Sequence::create(Animate::create(AnimationCache::getInstance()->getAnimation("RunCannonEffect")), CallFunc::create(CC_CALLBACK_0(CannonEffect::EffectDestroy, this)), NULL)); return true; } void CannonEffect::EffectDestroy() { this->stopAllActions(); this->removeFromParentAndCleanup(true); } Animation* CannonEffect::createAnimation(std::string prefixName, unsigned short framesNum, float delay) { Vector<SpriteFrame*> animFrames; for (int i = 1; i <= framesNum; i++) { char buffer[20] = { 0 }; sprintf(buffer, "%d.png", i); string str = prefixName + buffer; auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(str); if (i == 1) { this->initWithSpriteFrame(frame); } if (frame) { animFrames.pushBack(frame); } } animFrames.popBack(); return Animation::createWithSpriteFrames(animFrames, delay); }
[ "569378175@qq.com" ]
569378175@qq.com
29426de301168873a667a7c4158fbd8e4372184a
9aa01c48c8c194e6a7dd560e7b38275c0445f46a
/src/keyprocessor.h
1ea42ca05426e8f12e2daf7ae491c9508643a4e0
[ "MIT" ]
permissive
penta7c9/vnip
d3d7dde67cae036399c61731f7575294861b7311
1170d1286966c5d254abdf1f4c7d781218b1e27f
refs/heads/master
2023-04-27T09:34:11.235798
2016-05-27T07:48:52
2016-05-27T07:48:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
399
h
#ifndef KEYPROCESSOR_H #define KEYPROCESSOR_H #include <QString> #include <QList> #include "keydata.h" class KeyProcessor { public: KeyProcessor(); QString process(QString str); private: QString lastString; QList<QChar> numList; QChar getNewPressedKey(QString str, int &index); QList<int> findAllInStr(QString str, QChar charToFind); int findSpecialChar(QChar sChar); }; #endif
[ "dmtmd2010@yahoo.com.vn" ]
dmtmd2010@yahoo.com.vn
1feadadc22e773e143ebef17a899810fccffc620
ea547b51871a2b1f760a0e474963a079d4316202
/Classes/GameEnemyA.cpp
061cf2087fe07aa2f41f1f176b354979c6173a5b
[ "MIT" ]
permissive
huaidan123456/GameTest
0c05e250924ec1594f63f5dc67acdd659c7c6b22
ad9f1f61f901e3f0c0812e4dca0989515f2f15b5
refs/heads/master
2020-03-22T17:30:24.495271
2019-12-02T08:33:49
2019-12-02T08:33:49
140,399,173
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
// // GameEnemyA.cpp // GameTest-mobile // // Created by Allen on 2018/7/11. // #include "GameEnemyA.h" #include "FightTestManager.h" void GameEnemyA::doAttackEnemyAs(int multiple) { FightTestManager::getInstance()->attackRoleAs(getRoleAttackRect(), multiple); }
[ "wei125423412@163.com" ]
wei125423412@163.com
d24773210d353e3b292d9571c417a2e98b5cbc69
b69f0664d69dab5dc80b7e2e80b43b5eddcc0dab
/openpeer/core/cpp/core_Account.cpp
fb0dcfd2d966674d869a2edefb0651fee791ef8c
[]
no_license
kruegerconsulting/op-core-cpp
35c902fd56d2849e3cc7133b4cce85538807ff98
b68f655a0eb79cf14a25c400855bd52ea040eed4
refs/heads/master
2021-01-14T13:06:21.749561
2014-08-10T16:38:12
2014-08-10T16:38:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
73,128
cpp
/* Copyright (c) 2013, SMB Phone Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <openpeer/core/internal/core_Account.h> #include <openpeer/core/internal/core_Stack.h> #include <openpeer/core/internal/core_Identity.h> #include <openpeer/core/internal/core_Contact.h> #include <openpeer/core/internal/core_ConversationThread.h> #include <openpeer/stack/IBootstrappedNetwork.h> #include <openpeer/stack/IPeerFiles.h> #include <openpeer/stack/IServiceIdentity.h> #include <openpeer/stack/IPeerFilePrivate.h> #include <openpeer/stack/IPublication.h> #include <openpeer/stack/message/IMessageHelper.h> #include <openpeer/services/ISettings.h> #include <zsLib/XML.h> namespace openpeer { namespace core { ZS_DECLARE_SUBSYSTEM(openpeer_core) } } namespace openpeer { namespace core { namespace internal { ZS_DECLARE_TYPEDEF_PTR(IConversationThreadForAccount, UseConversationThread) typedef IStackForInternal UseStack; using services::IHelper; typedef zsLib::XML::Exceptions::CheckFailed CheckFailed; //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IAccountForCall #pragma mark //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IAccountForContact #pragma mark //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IAccountForConversationThread #pragma mark //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account #pragma mark //----------------------------------------------------------------------- Account::Account( IMessageQueuePtr queue, IAccountDelegatePtr delegate, IConversationThreadDelegatePtr conversationThreadDelegate, ICallDelegatePtr callDelegate ) : MessageQueueAssociator(queue), SharedRecursiveLock(SharedRecursiveLock::create()), mDelegate(IAccountDelegateProxy::createWeak(UseStack::queueApplication(), delegate)), mConversationThreadDelegate(IConversationThreadDelegateProxy::createWeak(UseStack::queueApplication(), conversationThreadDelegate)), mCallDelegate(ICallDelegateProxy::createWeak(UseStack::queueApplication(), callDelegate)), mCurrentState(AccountState_Pending), mLastErrorCode(0), mLockboxForceCreateNewAccount(false) { ZS_LOG_BASIC(log("created")) } //----------------------------------------------------------------------- Account::~Account() { if(isNoop()) return; mThisWeak.reset(); ZS_LOG_BASIC(log("destroyed")) cancel(); } //----------------------------------------------------------------------- void Account::init() { AutoRecursiveLock lock(*this); mDelegateFilter = DelegateFilter::create(mThisWeak.lock(), mConversationThreadDelegate, mCallDelegate); // replace conversation thread delegate / call delegate with intercepted delegate mConversationThreadDelegate = IConversationThreadDelegateProxy::create(mDelegateFilter); mCallDelegate = ICallDelegateProxy::create(mDelegateFilter); mBackgroundingSubscription = IBackgrounding::subscribe(mThisWeak.lock(), services::ISettings::getUInt(OPENPEER_CORE_SETTING_ACCOUNT_BACKGROUNDING_PHASE)); step(); } //----------------------------------------------------------------------- AccountPtr Account::convert(IAccountPtr account) { return dynamic_pointer_cast<Account>(account); } //----------------------------------------------------------------------- AccountPtr Account::convert(ForCallPtr account) { return dynamic_pointer_cast<Account>(account); } //----------------------------------------------------------------------- AccountPtr Account::convert(ForContactPtr account) { return dynamic_pointer_cast<Account>(account); } //----------------------------------------------------------------------- AccountPtr Account::convert(ForConversationThreadPtr account) { return dynamic_pointer_cast<Account>(account); } //----------------------------------------------------------------------- AccountPtr Account::convert(ForIdentityPtr account) { return dynamic_pointer_cast<Account>(account); } //----------------------------------------------------------------------- AccountPtr Account::convert(ForIdentityLookupPtr account) { return dynamic_pointer_cast<Account>(account); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IAccount #pragma mark //----------------------------------------------------------------------- ElementPtr Account::toDebug(IAccountPtr account) { if (!account) return ElementPtr(); return Account::convert(account)->toDebug(); } //----------------------------------------------------------------------- AccountPtr Account::login( IAccountDelegatePtr delegate, IConversationThreadDelegatePtr conversationThreadDelegate, ICallDelegatePtr callDelegate, const char *namespaceGrantOuterFrameURLUponReload, const char *grantID, const char *lockboxServiceDomain, bool forceCreateNewLockboxAccount ) { ZS_THROW_INVALID_ARGUMENT_IF(!namespaceGrantOuterFrameURLUponReload) ZS_THROW_INVALID_ARGUMENT_IF(!grantID) ZS_THROW_INVALID_ARGUMENT_IF(!lockboxServiceDomain) AccountPtr pThis(new Account(UseStack::queueCore(), delegate, conversationThreadDelegate, callDelegate)); pThis->mThisWeak = pThis; AutoRecursiveLock lock(*pThis); String lockboxDomain(lockboxServiceDomain); IBootstrappedNetworkPtr lockboxNetwork = IBootstrappedNetwork::prepare(lockboxDomain); if (!lockboxNetwork) { ZS_LOG_ERROR(Detail, pThis->log("failed to prepare bootstrapped network for domain") + ZS_PARAM("domain", lockboxDomain)) return AccountPtr(); } pThis->mGrantSession = IServiceNamespaceGrantSession::create(pThis, namespaceGrantOuterFrameURLUponReload, grantID); ZS_THROW_BAD_STATE_IF(!pThis->mGrantSession) pThis->mLockboxService = IServiceLockbox::createServiceLockboxFrom(lockboxNetwork); ZS_THROW_BAD_STATE_IF(!pThis->mLockboxService) pThis->mLockboxForceCreateNewAccount = forceCreateNewLockboxAccount; pThis->init(); return pThis; } //----------------------------------------------------------------------- AccountPtr Account::relogin( IAccountDelegatePtr delegate, IConversationThreadDelegatePtr conversationThreadDelegate, ICallDelegatePtr callDelegate, const char *namespaceGrantOuterFrameURLUponReload, ElementPtr reloginInformation ) { ZS_THROW_INVALID_ARGUMENT_IF(!namespaceGrantOuterFrameURLUponReload) ZS_THROW_INVALID_ARGUMENT_IF(!reloginInformation) AccountPtr pThis(new Account(UseStack::queueCore(), delegate, conversationThreadDelegate, callDelegate)); pThis->mThisWeak = pThis; AutoRecursiveLock lock(*pThis); String lockboxDomain; String accountID; String grantID; SecureByteBlockPtr lockboxKey; try { lockboxDomain = reloginInformation->findFirstChildElementChecked("lockboxDomain")->getTextDecoded(); accountID = reloginInformation->findFirstChildElementChecked("accountID")->getTextDecoded(); grantID = reloginInformation->findFirstChildElementChecked("grantID")->getTextDecoded(); lockboxKey = IHelper::convertFromBase64(reloginInformation->findFirstChildElementChecked("lockboxKey")->getTextDecoded()); } catch (CheckFailed &) { return AccountPtr(); } IBootstrappedNetworkPtr lockboxNetwork = IBootstrappedNetwork::prepare(lockboxDomain); if (!lockboxNetwork) { ZS_LOG_ERROR(Detail, pThis->log("failed to prepare bootstrapped network for domain") + ZS_PARAM("domain", lockboxDomain)) return AccountPtr(); } if (IHelper::isEmpty(lockboxKey)) { ZS_LOG_ERROR(Detail, pThis->log("lockbox key specified in relogin information is not valid")) return AccountPtr(); } pThis->mGrantSession = IServiceNamespaceGrantSession::create(pThis, namespaceGrantOuterFrameURLUponReload, grantID); ZS_THROW_BAD_STATE_IF(!pThis->mGrantSession) pThis->mLockboxService = IServiceLockbox::createServiceLockboxFrom(lockboxNetwork); ZS_THROW_BAD_STATE_IF(!pThis->mLockboxService) pThis->mLockboxForceCreateNewAccount = false; pThis->mLockboxSession.set(IServiceLockboxSession::relogin(pThis, pThis->mLockboxService, pThis->mGrantSession, accountID, *lockboxKey)); pThis->init(); if (!pThis->mLockboxSession.get()) { ZS_LOG_ERROR(Detail, pThis->log("failed to create lockbox session from relogin information")) return AccountPtr(); } return pThis; } //----------------------------------------------------------------------- IAccount::AccountStates Account::getState( WORD *outErrorCode, String *outErrorReason ) const { AutoRecursiveLock lock(*this); if (outErrorCode) *outErrorCode = mLastErrorCode; if (outErrorReason) *outErrorReason = mLastErrorReason; ZS_LOG_DEBUG(debug("getting account state")) return mCurrentState; } //----------------------------------------------------------------------- ElementPtr Account::getReloginInformation() const { AutoRecursiveLock lock(*this); ZS_THROW_BAD_STATE_IF(!mLockboxService) String lockboxDomain = mLockboxService->getBootstrappedNetwork()->getDomain(); if (lockboxDomain.isEmpty()) { ZS_LOG_WARNING(Detail, log("missing lockbox domain information")) return ElementPtr(); } if (!mLockboxSession.get()) { ZS_LOG_WARNING(Detail, log("missing lockbox session information")) return ElementPtr(); } String accountID = mLockboxSession.get()->getAccountID(); if (accountID.isEmpty()) { ZS_LOG_WARNING(Detail, log("missing account ID information")) return ElementPtr(); } ZS_THROW_BAD_STATE_IF(!mGrantSession) String grantID = mGrantSession->getGrantID(); if (grantID.isEmpty()) { ZS_LOG_WARNING(Detail, log("missing grant ID information")) return ElementPtr(); } SecureByteBlockPtr lockboxKey = mLockboxSession.get()->getLockboxKey(); if (!lockboxKey) { ZS_LOG_WARNING(Detail, log("missing lockbox key information")) return ElementPtr(); } ElementPtr reloginEl = Element::create("relogin"); reloginEl->adoptAsLastChild(IMessageHelper::createElementWithTextAndJSONEncode("lockboxDomain", lockboxDomain)); reloginEl->adoptAsLastChild(IMessageHelper::createElementWithTextAndJSONEncode("accountID", accountID)); reloginEl->adoptAsLastChild(IMessageHelper::createElementWithTextAndJSONEncode("grantID", grantID)); reloginEl->adoptAsLastChild(IMessageHelper::createElementWithTextAndJSONEncode("lockboxKey", services::IHelper::convertToBase64(*lockboxKey))); return reloginEl; } //----------------------------------------------------------------------- String Account::getStableID() const { if (!mLockboxSession.get()) return String(); return mLockboxSession.get()->getStableID(); } //----------------------------------------------------------------------- String Account::getLocationID() const { if (!mStackAccount.get()) return String(); ILocationPtr self(ILocation::getForLocal(mStackAccount.get())); if (!self) { ZS_LOG_WARNING(Detail, debug("location ID is not available yet")) return String(); } ZS_LOG_DEBUG(log("getting location") + ILocation::toDebug(self)) return self->getLocationID(); } //----------------------------------------------------------------------- void Account::shutdown() { AutoRecursiveLock lock(*this); ZS_LOG_DEBUG(debug("shutdown called")) cancel(); } //----------------------------------------------------------------------- ElementPtr Account::savePeerFilePrivate() const { // look ma - no lock if (!mLockboxSession.get()) return ElementPtr(); IPeerFilesPtr peerFiles = mLockboxSession.get()->getPeerFiles(); if (!peerFiles) { ZS_LOG_WARNING(Detail, debug("peer files are not available")) return ElementPtr(); } return peerFiles->saveToPrivatePeerElement(); } //----------------------------------------------------------------------- SecureByteBlockPtr Account::getPeerFilePrivateSecret() const { // look ma - no lock if (!mLockboxSession.get()) return SecureByteBlockPtr(); IPeerFilesPtr peerFiles = mLockboxSession.get()->getPeerFiles(); if (!peerFiles) { ZS_LOG_WARNING(Detail, debug("peer files are not available")) return SecureByteBlockPtr(); } IPeerFilePrivatePtr peerFilePrivate = peerFiles->getPeerFilePrivate(); return peerFilePrivate->getPassword(); } //----------------------------------------------------------------------- IdentityListPtr Account::getAssociatedIdentities() const { AutoRecursiveLock lock(*this); IdentityListPtr result(new IdentityList); if ((isShuttingDown()) || (isShutdown())) { ZS_LOG_WARNING(Detail, debug("cannot get identities during shutdown")) return result; } ServiceIdentitySessionListPtr identities = mLockboxSession.get()->getAssociatedIdentities(); ZS_THROW_BAD_STATE_IF(!identities) for (ServiceIdentitySessionList::iterator iter = identities->begin(); iter != identities->end(); ++iter) { IServiceIdentitySessionPtr session = (*iter); IdentityMap::const_iterator found = mIdentities.find(session->getID()); if (found != mIdentities.end()) { UseIdentityPtr identity = (*found).second; ZS_LOG_DEBUG(log("found existing identity") + UseIdentity::toDebug(identity)) result->push_back(Identity::convert(identity)); continue; } UseIdentityPtr identity = IIdentityForAccount::createFromExistingSession(session); ZS_LOG_DEBUG(log("new identity found") + UseIdentity::toDebug(identity)) mIdentities[identity->getSession()->getID()] = identity; result->push_back(Identity::convert(identity)); } ZS_LOG_DEBUG(log("get associated identities complete") + ZS_PARAM("total", result->size())) return result; } //----------------------------------------------------------------------- void Account::removeIdentities(const IdentityList &identitiesToRemove) { AutoRecursiveLock lock(*this); if ((isShuttingDown()) || (isShutdown())) { ZS_LOG_WARNING(Detail, debug("cannot associate identities during shutdown")) return; } if (!mLockboxSession.get()) { ZS_LOG_WARNING(Detail, log("lockbox session has not yet been created")) return; } ServiceIdentitySessionList add; ServiceIdentitySessionList remove; for (IdentityList::const_iterator iter = identitiesToRemove.begin(); iter != identitiesToRemove.end(); ++iter) { UseIdentityPtr identity = Identity::convert(*iter); mIdentities[identity->getSession()->getID()] = identity; remove.push_back(identity->getSession()); } mLockboxSession.get()->associateIdentities(add, remove); } //----------------------------------------------------------------------- String Account::getInnerBrowserWindowFrameURL() const { ZS_THROW_BAD_STATE_IF(!mGrantSession) return mGrantSession->getInnerBrowserWindowFrameURL(); } //----------------------------------------------------------------------- void Account::notifyBrowserWindowVisible() { ZS_THROW_BAD_STATE_IF(!mGrantSession) mGrantSession->notifyBrowserWindowVisible(); } //----------------------------------------------------------------------- void Account::notifyBrowserWindowClosed() { ZS_THROW_BAD_STATE_IF(!mGrantSession) mGrantSession->notifyBrowserWindowClosed(); } //----------------------------------------------------------------------- ElementPtr Account::getNextMessageForInnerBrowerWindowFrame() { AutoRecursiveLock lock(*this); ZS_THROW_BAD_STATE_IF(!mGrantSession) DocumentPtr doc = mGrantSession->getNextMessageForInnerBrowerWindowFrame(); if (!doc) { ZS_LOG_WARNING(Detail, log("lockbox has no message pending for inner browser window frame")) return ElementPtr(); } ElementPtr root = doc->getFirstChildElement(); ZS_THROW_BAD_STATE_IF(!root) root->orphan(); return root; } //----------------------------------------------------------------------- void Account::handleMessageFromInnerBrowserWindowFrame(ElementPtr unparsedMessage) { ZS_THROW_INVALID_ARGUMENT_IF(!unparsedMessage) ZS_THROW_BAD_STATE_IF(!mGrantSession) DocumentPtr doc = Document::create(); doc->adoptAsLastChild(unparsedMessage); mGrantSession->handleMessageFromInnerBrowserWindowFrame(doc); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IAccountForCall #pragma mark //----------------------------------------------------------------------- CallTransportPtr Account::getCallTransport() const { // look ma - no lock return CallTransport::convert(mCallTransport.get()); } //----------------------------------------------------------------------- ICallDelegatePtr Account::getCallDelegate() const { // look ma - no lock return mCallDelegate; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IAccountForContact #pragma mark //----------------------------------------------------------------------- ContactPtr Account::findContact(const char *peerURI) const { ZS_THROW_INVALID_ARGUMENT_IF(!peerURI) AutoRecursiveLock lock(*this); ContactMap::const_iterator found = mContacts.find(peerURI); if (found == mContacts.end()) { ZS_LOG_DEBUG(log("contact was not found for peer URI") + ZS_PARAM("uri", peerURI)) return ContactPtr(); } const UseContactPtr &contact = (*found).second; return Contact::convert(contact); } //----------------------------------------------------------------------- void Account::notifyAboutContact(ContactPtr inContact) { UseContactPtr contact = inContact; ZS_THROW_INVALID_ARGUMENT_IF(!contact) AutoRecursiveLock lock(*this); String peerURI = contact->getPeerURI(); mContacts[peerURI] = contact; } //----------------------------------------------------------------------- void Account::hintAboutContactLocation( ContactPtr inContact, const char *locationID ) { UseContactPtr contact = inContact; ZS_THROW_INVALID_ARGUMENT_IF(!contact) ZS_THROW_INVALID_ARGUMENT_IF(!locationID) AutoRecursiveLock lock(*this); ContactSubscriptionMap::iterator found = mContactSubscriptions.find(contact->getPeerURI()); if (found != mContactSubscriptions.end()) { ContactSubscriptionPtr contactSubscription = (*found).second; if ((contactSubscription->isShuttingDown()) || (contactSubscription->isShutdown())) { // the contact subscription is dying, need to create a new one to replace the existing mContactSubscriptions.erase(found); found = mContactSubscriptions.end(); } } if (found == mContactSubscriptions.end()) { // In this scenario we need to subscribe to this peer since we // do not have a connection established to this peer as of yet. ContactSubscriptionPtr contactSubscription = ContactSubscription::create(mThisWeak.lock(), contact); mContactSubscriptions[contact->getPeerURI()] = contactSubscription; } // We need to hint about the contact location to the stack just in case // the stack does not know about this location. if (mStackAccount.get()) { ILocationPtr location = ILocation::getForPeer(contact->getPeer(), locationID); ZS_THROW_BAD_STATE_IF(!location) location->hintNowAvailable(); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IAccountForConversationThread #pragma mark //----------------------------------------------------------------------- ContactPtr Account::getSelfContact() const { AutoRecursiveLock lock(*this); return Contact::convert(mSelfContact); } //----------------------------------------------------------------------- ILocationPtr Account::getSelfLocation() const { // look ma - no lock if (!mStackAccount.get()) return ILocationPtr(); return ILocation::getForLocal(mStackAccount.get()); } //----------------------------------------------------------------------- stack::IAccountPtr Account::getStackAccount() const { // look ma - no lock return mStackAccount.get(); } //----------------------------------------------------------------------- IPublicationRepositoryPtr Account::getRepository() const { // look ma - no lock if (!mStackAccount.get()) return IPublicationRepositoryPtr(); return IPublicationRepository::getFromAccount(mStackAccount.get()); } //----------------------------------------------------------------------- IPeerFilesPtr Account::getPeerFiles() const { // look ma - no lock if (!mLockboxSession.get()) { ZS_LOG_WARNING(Detail, log("lockbox is not created yet thus peer files are not available yet")) return IPeerFilesPtr(); } return mLockboxSession.get()->getPeerFiles(); } //----------------------------------------------------------------------- IConversationThreadDelegatePtr Account::getConversationThreadDelegate() const { // look ma - no lock return mConversationThreadDelegate; } //----------------------------------------------------------------------- void Account::notifyConversationThreadCreated( ConversationThreadPtr inThread, bool notifyDelegate ) { UseConversationThreadPtr thread = inThread; ZS_THROW_INVALID_ARGUMENT_IF(!thread) AutoRecursiveLock lock(*this); if ((isShuttingDown()) || (isShutdown())) { ZS_LOG_WARNING(Detail, debug("cannot remember new thread or notify about it during shutdown")) return; } mConversationThreads[thread->getThreadID()] = thread; if (!notifyDelegate) { ZS_LOG_DEBUG(log("no need to notifify delegate")) return; } try { mConversationThreadDelegate->onConversationThreadNew(ConversationThread::convert(thread)); } catch (IConversationThreadDelegateProxy::Exceptions::DelegateGone &) { ZS_LOG_WARNING(Detail, log("could not notify of new conversation thread - conversation thread delegate is gone")) } } //----------------------------------------------------------------------- ConversationThreadPtr Account::getConversationThreadByID(const char *threadID) const { ZS_THROW_INVALID_ARGUMENT_IF(!threadID) AutoRecursiveLock lock(*this); ConversationThreadMap::const_iterator found = mConversationThreads.find(threadID); if (found == mConversationThreads.end()) return ConversationThreadPtr(); const UseConversationThreadPtr &thread = (*found).second; return ConversationThread::convert(thread); } //----------------------------------------------------------------------- void Account::getConversationThreads(ConversationThreadList &outConversationThreads) const { AutoRecursiveLock lock(*this); for (ConversationThreadMap::const_iterator iter = mConversationThreads.begin(); iter != mConversationThreads.end(); ++iter) { const UseConversationThreadPtr &thread = (*iter).second; outConversationThreads.push_back(ConversationThread::convert(thread)); } } //----------------------------------------------------------------------- void Account::notifyConversationThreadStateChanged() { AutoRecursiveLock lock(*this); ZS_LOG_DEBUG(log("notified conversation thread state changed")) IWakeDelegateProxy::create(mThisWeak.lock())->onWake(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IAccountForIdentity #pragma mark //----------------------------------------------------------------------- stack::IServiceNamespaceGrantSessionPtr Account::getNamespaceGrantSession() const { return mGrantSession; } //----------------------------------------------------------------------- stack::IServiceLockboxSessionPtr Account::getLockboxSession() const { return mLockboxSession.get(); } //----------------------------------------------------------------------- void Account::associateIdentity(IdentityPtr inIdentity) { UseIdentityPtr identity = inIdentity; ZS_THROW_INVALID_ARGUMENT_IF(!identity) ZS_LOG_DEBUG(log("associating identity to account/lockbox")) AutoRecursiveLock lock(*this); mIdentities[identity->getSession()->getID()] = identity; if (!mLockboxSession.get()) { ZS_LOG_DEBUG(log("creating lockbox session")) mLockboxSession.set(IServiceLockboxSession::login(mThisWeak.lock(), mLockboxService, mGrantSession, identity->getSession(), mLockboxForceCreateNewAccount)); } else { ZS_LOG_DEBUG(log("associating to existing lockbox session")) ServiceIdentitySessionList add; ServiceIdentitySessionList remove; add.push_back(identity->getSession()); mLockboxSession.get()->associateIdentities(add, remove); } IWakeDelegateProxy::create(mThisWeak.lock())->onWake(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IAccountForIdentityLookup #pragma mark //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => ICallTransportDelegate #pragma mark //----------------------------------------------------------------------- void Account::onCallTransportStateChanged( ICallTransportPtr inTransport, CallTransportStates state ) { ZS_LOG_DEBUG(log("notified call transport state changed")) AutoRecursiveLock lock(*this); step(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => stack::IAccountDelegate #pragma mark //----------------------------------------------------------------------- void Account::onAccountStateChanged( stack::IAccountPtr account, stack::IAccount::AccountStates state ) { AutoRecursiveLock lock(*this); step(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IPeerSubscriptionDelegate #pragma mark //----------------------------------------------------------------------- void Account::onPeerSubscriptionShutdown(IPeerSubscriptionPtr subscription) { AutoRecursiveLock lock(*this); if (subscription != mPeerSubscription) { ZS_LOG_WARNING(Detail, log("notified about obsolete subscription")) return; } mPeerSubscription.reset(); step(); } //----------------------------------------------------------------------- void Account::onPeerSubscriptionFindStateChanged( IPeerSubscriptionPtr subscription, IPeerPtr peer, PeerFindStates state ) { // IGNORED } //----------------------------------------------------------------------- void Account::onPeerSubscriptionLocationConnectionStateChanged( IPeerSubscriptionPtr subscription, ILocationPtr location, LocationConnectionStates state ) { AutoRecursiveLock lock(*this); if (subscription != mPeerSubscription) { ZS_LOG_WARNING(Detail, log("notified about obsolete subscription (thus ignoring)") + ZS_PARAM("subscription ID", subscription->getID())) return; } IPeerPtr peer = location->getPeer(); if (!peer) { if (location->getLocationType() == ILocation::LocationType_Finder) { ZS_LOG_TRACE(log("notified about location finder location (thus ignoring)") + ILocation::toDebug(location)) return; } ZS_LOG_WARNING(Detail, log("notified about location which is not a peer") + ILocation::toDebug(location)) return; } String peerURI = peer->getPeerURI(); ZS_LOG_TRACE(log("notified peer location state changed") + ZS_PARAM("state", ILocation::toString(state)) + ILocation::toDebug(location)) // see if there is a local contact with this peer URI ContactMap::iterator foundContact = mContacts.find(peerURI); if (foundContact == mContacts.end()) { // did not find a contact with this peer URI - thus we need to create one IPeerFilePublicPtr peerFilePublic = peer->getPeerFilePublic(); if (!peerFilePublic) { ZS_LOG_ERROR(Detail, log("no public peer file for location provided") + ILocation::toDebug(location)) return; } // create and remember this contact for the future UseContactPtr contact = IContactForAccount::createFromPeer(mThisWeak.lock(), peer); // attempt find once more as contact might now be registered foundContact = mContacts.find(peerURI); ZS_THROW_BAD_STATE_IF(foundContact == mContacts.end()) } UseContactPtr contact = (*foundContact).second; ContactSubscriptionMap::iterator foundContactSubscription = mContactSubscriptions.find(peerURI); ContactSubscriptionPtr contactSubscription; if (foundContactSubscription == mContactSubscriptions.end()) { switch (state) { case ILocation::LocationConnectionState_Pending: case ILocation::LocationConnectionState_Disconnecting: case ILocation::LocationConnectionState_Disconnected: { ZS_LOG_DEBUG(log("no need to create contact subscription when the connection is not ready") + ILocation::toDebug(location)) return; } case ILocation::LocationConnectionState_Connected: break; } ZS_LOG_DEBUG(log("creating a new contact subscription") + ILocation::toDebug(location)) contactSubscription = ContactSubscription::create(mThisWeak.lock(), contact, location); mContactSubscriptions[peerURI] = contactSubscription; } else { contactSubscription = (*foundContactSubscription).second; } ZS_LOG_DEBUG(log("notifying contact subscription about state") + ILocation::toDebug(location)) contactSubscription->notifyAboutLocationState(location, state); } //----------------------------------------------------------------------- void Account::onPeerSubscriptionMessageIncoming( IPeerSubscriptionPtr subscription, IMessageIncomingPtr message ) { // IGNORED } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IServiceLockboxSessionDelegate #pragma mark //----------------------------------------------------------------------- void Account::onServiceLockboxSessionStateChanged( IServiceLockboxSessionPtr session, LockboxSessionStates state ) { AutoRecursiveLock lock(*this); step(); } //----------------------------------------------------------------------- void Account::onServiceLockboxSessionAssociatedIdentitiesChanged(IServiceLockboxSessionPtr session) { AutoRecursiveLock lock(*this); if (session != mLockboxSession.get()) { ZS_LOG_WARNING(Detail, log("notified about unknown lockbox session")) return; } if ((isShuttingDown()) || (isShutdown())) { ZS_LOG_WARNING(Detail, log("notified of association change during shutdown")) return; } ZS_THROW_BAD_STATE_IF(!mDelegate) try { mDelegate->onAccountAssociatedIdentitiesChanged(mThisWeak.lock()); } catch(IAccountDelegateProxy::Exceptions::DelegateGone &) { ZS_LOG_WARNING(Detail, log("delegate gone")) } step(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IServiceNamespaceGrantSessionDelegate #pragma mark //----------------------------------------------------------------------- void Account::onServiceNamespaceGrantSessionStateChanged( IServiceNamespaceGrantSessionPtr session, GrantSessionStates state ) { AutoRecursiveLock lock(*this); step(); } //----------------------------------------------------------------------- void Account::onServiceNamespaceGrantSessionPendingMessageForInnerBrowserWindowFrame(IServiceNamespaceGrantSessionPtr session) { AutoRecursiveLock lock(*this); ZS_THROW_UNEXPECTED_ERROR_IF(session != mGrantSession) if ((isShuttingDown()) || (isShutdown())) { ZS_LOG_WARNING(Detail, log("notified pending messages during shutdown")) return; } ZS_THROW_BAD_STATE_IF(!mDelegate) try { mDelegate->onAccountPendingMessageForInnerBrowserWindowFrame(mThisWeak.lock()); } catch(IAccountDelegateProxy::Exceptions::DelegateGone &) { ZS_LOG_WARNING(Detail, log("delegate gone")) } step(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IBackgroundingDelegate #pragma mark //----------------------------------------------------------------------- void Account::onBackgroundingGoingToBackground( IBackgroundingSubscriptionPtr subscription, IBackgroundingNotifierPtr notifier ) { ZS_LOG_DEBUG(log("going to background")) } //----------------------------------------------------------------------- void Account::onBackgroundingGoingToBackgroundNow(IBackgroundingSubscriptionPtr subscription) { ZS_LOG_DEBUG(log("going to background now")) } //----------------------------------------------------------------------- void Account::onBackgroundingReturningFromBackground(IBackgroundingSubscriptionPtr subscription) { ZS_LOG_DEBUG(log("returning from background")) } //----------------------------------------------------------------------- void Account::onBackgroundingApplicationWillQuit(IBackgroundingSubscriptionPtr subscription) { ZS_LOG_DEBUG(log("application will quit")) AutoRecursiveLock lock(*this); setError(IHTTP::HTTPStatusCode_ClientClosedRequest, "application is quitting"); cancel(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => IWakeDelegate #pragma mark //----------------------------------------------------------------------- void Account::onWake() { AutoRecursiveLock lock(*this); ZS_LOG_DEBUG(log("on wake")) step(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => friend Account::ContactSubscription #pragma mark //----------------------------------------------------------------------- void Account::notifyContactSubscriptionShutdown(const String &peerURI) { AutoRecursiveLock lock(*this); ContactSubscriptionMap::iterator found = mContactSubscriptions.find(peerURI); if (found == mContactSubscriptions.end()) return; mContactSubscriptions.erase(found); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => friend Account::LocationSubscription #pragma mark //----------------------------------------------------------------------- UseConversationThreadPtr Account::notifyPublicationUpdated( ILocationPtr peerLocation, IPublicationMetaDataPtr metaData, const SplitMap &split ) { if (isShutdown()) { ZS_LOG_WARNING(Debug, log("received updated publication document after account was shutdown thus ignoring")) return ConversationThreadPtr(); } String baseThreadID = services::IHelper::get(split, OPENPEER_CONVERSATION_THREAD_BASE_THREAD_ID_INDEX); String hostThreadID = services::IHelper::get(split, OPENPEER_CONVERSATION_THREAD_HOST_THREAD_ID_INDEX); if ((baseThreadID.size() < 1) || (hostThreadID.size() < 1)) { ZS_LOG_WARNING(Debug, log("converation thread publication did not have a thread ID") + IPublicationMetaData::toDebug(metaData)) return ConversationThreadPtr(); } ConversationThreadMap::iterator found = mConversationThreads.find(baseThreadID); if (found != mConversationThreads.end()) { ZS_LOG_DEBUG(log("notify publication updated for existing thread") + ZS_PARAM("thread ID", baseThreadID) + IPublicationMetaData::toDebug(metaData)) UseConversationThreadPtr thread = (*found).second; thread->notifyPublicationUpdated(peerLocation, metaData, split); return thread; } ZS_LOG_DEBUG(log("notify publication for new thread") + ZS_PARAM("thread ID", baseThreadID) + IPublicationMetaData::toDebug(metaData)) UseConversationThreadPtr thread = IConversationThreadForAccount::create(mThisWeak.lock(), peerLocation, metaData, split); if (!thread) { ZS_LOG_WARNING(Debug, log("notify publication for new thread aborted")) return UseConversationThreadPtr(); } return thread; } //----------------------------------------------------------------------- void Account::notifyPublicationGone( ILocationPtr peerLocation, IPublicationMetaDataPtr metaData, const SplitMap &split ) { String baseThreadID = services::IHelper::get(split, OPENPEER_CONVERSATION_THREAD_BASE_THREAD_ID_INDEX); String hostThreadID = services::IHelper::get(split, OPENPEER_CONVERSATION_THREAD_HOST_THREAD_ID_INDEX); if ((baseThreadID.size() < 1) || (hostThreadID.size() < 1)) { ZS_LOG_WARNING(Debug, log("converation thread publication did not have a thread ID") + IPublicationMetaData::toDebug(metaData)) return; } ConversationThreadMap::iterator found = mConversationThreads.find(baseThreadID); if (found == mConversationThreads.end()) { ZS_LOG_WARNING(Debug, log("notify publication gone for thread that did not exist") + ZS_PARAM("thread ID", baseThreadID) + IPublicationMetaData::toDebug(metaData)) return; } ZS_LOG_DEBUG(log("notify publication gone for existing thread") + ZS_PARAM("thread ID", baseThreadID) + IPublicationMetaData::toDebug(metaData)) UseConversationThreadPtr thread = (*found).second; thread->notifyPublicationGone(peerLocation, metaData, split); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark Account => internal #pragma mark //----------------------------------------------------------------------- Log::Params Account::log(const char *message) const { ElementPtr objectEl = Element::create("core::Account"); IHelper::debugAppend(objectEl, "id", mID); return Log::Params(message, objectEl); } //----------------------------------------------------------------------- Log::Params Account::debug(const char *message) const { return Log::Params(message, toDebug()); } //----------------------------------------------------------------------- ElementPtr Account::toDebug() const { AutoRecursiveLock lock(*this); ElementPtr resultEl = Element::create("core::Account"); IHelper::debugAppend(resultEl, "id", mID); IHelper::debugAppend(resultEl, "state", toString(mCurrentState)); IHelper::debugAppend(resultEl, "error code", mLastErrorCode); IHelper::debugAppend(resultEl, "error reason", mLastErrorReason); IHelper::debugAppend(resultEl, "delegate", (bool)mDelegate); IHelper::debugAppend(resultEl, "conversation thread delegate", (bool)mConversationThreadDelegate); IHelper::debugAppend(resultEl, "call delegate", (bool)mCallDelegate); IHelper::debugAppend(resultEl, "backgrounding subscription", mBackgroundingSubscription ? mBackgroundingSubscription->getID() : 0); IHelper::debugAppend(resultEl, stack::IAccount::toDebug(mStackAccount.get())); IHelper::debugAppend(resultEl, stack::IServiceNamespaceGrantSession::toDebug(mGrantSession)); IHelper::debugAppend(resultEl, stack::IServiceLockboxSession::toDebug(mLockboxSession.get())); IHelper::debugAppend(resultEl, "force new lockbox account", mLockboxForceCreateNewAccount ? String("true") : String()); IHelper::debugAppend(resultEl, "identities", mIdentities.size()); IHelper::debugAppend(resultEl, stack::IPeerSubscription::toDebug(mPeerSubscription)); IHelper::debugAppend(resultEl, UseContact::toDebug(mSelfContact)); IHelper::debugAppend(resultEl, "contacts", mContacts.size()); IHelper::debugAppend(resultEl, "contact subscription", mContactSubscriptions.size()); IHelper::debugAppend(resultEl, "conversations", mConversationThreads.size()); IHelper::debugAppend(resultEl, "call transport", (bool)mCallTransport.get()); IHelper::debugAppend(resultEl, "subscribers permission document", (bool)mSubscribersPermissionDocument); return resultEl; } //----------------------------------------------------------------------- void Account::cancel() { AutoRecursiveLock lock(*this); // just in case ZS_LOG_DEBUG(debug("cancel called")) if (isShutdown()) return; if (!mGracefulShutdownReference) mGracefulShutdownReference = mThisWeak.lock(); setState(AccountState_ShuttingDown); if (mCallTransport.get()) { ZS_LOG_DEBUG(log("shutting down call transport")) mCallTransport.get()->shutdown(); } if (mStackAccount.get()) { ZS_LOG_DEBUG(log("shutting down stack account")) mStackAccount.get()->shutdown(); // do not reset } if (mPeerSubscription) { mPeerSubscription->cancel(); mPeerSubscription.reset(); } for (ConversationThreadMap::iterator iter_doNotUse = mConversationThreads.begin(); iter_doNotUse != mConversationThreads.end(); ) { ConversationThreadMap::iterator current = iter_doNotUse; ++iter_doNotUse; UseConversationThreadPtr thread = (*current).second; thread->shutdown(); } if (mGracefulShutdownReference) { for (ConversationThreadMap::iterator iter_doNotUse = mConversationThreads.begin(); iter_doNotUse != mConversationThreads.end(); ) { ConversationThreadMap::iterator current = iter_doNotUse; ++iter_doNotUse; const BaseThreadID &threadI = (*current).first; UseConversationThreadPtr thread = (*current).second; if (!thread->isShutdown()) { ZS_LOG_DEBUG(log("waiting for conversation thread to shutdown") + ZS_PARAM("base thread id", threadI)) return; } } if (mStackAccount.get()) { if (stack::IAccount::AccountState_Shutdown != mStackAccount.get()->getState()) { ZS_LOG_DEBUG(log("waiting for stack account to shutdown")) return; } } if (mCallTransport.get()) { if (ICallTransport::CallTransportState_Shutdown != mCallTransport.get()->getState()) { ZS_LOG_DEBUG(log("waiting for call transport to shutdown")) return; } } } setState(AccountState_Shutdown); if (mBackgroundingSubscription) { mBackgroundingSubscription->cancel(); mBackgroundingSubscription.reset(); } if (mGrantSession) { mGrantSession->cancel(); // do not reset } if (mLockboxSession.get()) { mLockboxSession.get()->cancel(); // do not reset } mGracefulShutdownReference.reset(); mDelegate.reset(); mConversationThreads.clear(); ZS_LOG_DEBUG(log("shutdown complete")) } //----------------------------------------------------------------------- void Account::step() { if ((isShutdown()) || (isShuttingDown())) { ZS_LOG_DEBUG(log("step forwarding to cancel")) cancel(); return; } ZS_LOG_DEBUG(debug("step")) if (!stepLoginIdentityAssociated()) return; if (!stepLockboxShutdownCheck()) return; if (!stepStackAccountCreation()) return; if (!stepGrantSession()) return; if (!stepLockboxSession()) return; if (!stepStackAccount()) return; if (!stepSelfContact()) return; if (!stepCallTransportSetup()) return; if (!stepSubscribersPermissionDocument()) return; if (!stepPeerSubscription()) return; if (!stepCallTransportFinalize()) return; setState(AccountState_Ready); ZS_LOG_TRACE(debug("step complete")) } //----------------------------------------------------------------------- bool Account::stepLoginIdentityAssociated() { if (mLockboxSession.get()) { ZS_LOG_DEBUG(log("lockbox is already created thus login identity associate is not needed")) return true; } ZS_LOG_DEBUG(log("waiting for account to be associated to an identity")) setState(AccountState_WaitingForAssociationToIdentity); return false; } //----------------------------------------------------------------------- bool Account::stepLockboxShutdownCheck() { WORD errorCode = 0; String reason; IServiceLockboxSession::SessionStates state = mLockboxSession.get()->getState(&errorCode, &reason); if (IServiceLockboxSession::SessionState_Shutdown == state) { ZS_LOG_ERROR(Detail, log("lockbox session shutdown")) setError(errorCode, reason); cancel(); return false; } ZS_LOG_TRACE(log("lockbox is not shutdown thus allowing to continue")) return true; } //----------------------------------------------------------------------- bool Account::stepGrantSession() { WORD errorCode = 0; String reason; IServiceNamespaceGrantSession::SessionStates state = mGrantSession->getState(&errorCode, &reason); switch (state) { case IServiceNamespaceGrantSession::SessionState_Pending: { ZS_LOG_TRACE(log("namespace grant session is pending")) setState(AccountState_Pending); return false; } case IServiceNamespaceGrantSession::SessionState_WaitingForBrowserWindowToBeLoaded: { ZS_LOG_TRACE(log("namespace grant is waiting for the browser window to be loaded")) setState(AccountState_WaitingForBrowserWindowToBeLoaded); return false; } case IServiceNamespaceGrantSession::SessionState_WaitingForBrowserWindowToBeMadeVisible: { ZS_LOG_TRACE(log("namespace grant is waiting for browser window to be made visible")) setState(AccountState_WaitingForBrowserWindowToBeMadeVisible); return false; } case IServiceNamespaceGrantSession::SessionState_WaitingForBrowserWindowToClose: { ZS_LOG_TRACE(log("namespace grant is waiting for browser window to close")) setState(AccountState_WaitingForBrowserWindowToClose); return false; } case IServiceNamespaceGrantSession::SessionState_Ready: { ZS_LOG_TRACE(log("namespace grant is ready")) return true; } case IServiceNamespaceGrantSession::SessionState_Shutdown: { ZS_LOG_ERROR(Detail, log("namespace grant is session shutdown")) setError(errorCode, reason); cancel(); return false; } } ZS_LOG_DEBUG(log("waiting for lockbox session to be ready")) return false; } //----------------------------------------------------------------------- bool Account::stepStackAccountCreation() { ZS_THROW_BAD_STATE_IF(!mLockboxSession.get()) if (mStackAccount.get()) { ZS_LOG_TRACE(log("stack account already created")) return true; } ZS_LOG_DEBUG(log("creating stack account")) mStackAccount.set(stack::IAccount::create(mThisWeak.lock(), mLockboxSession.get())); return true; } //----------------------------------------------------------------------- bool Account::stepLockboxSession() { ZS_THROW_BAD_STATE_IF(!mLockboxSession.get()) WORD errorCode = 0; String reason; IServiceLockboxSession::SessionStates state = mLockboxSession.get()->getState(&errorCode, &reason); switch (state) { case IServiceLockboxSession::SessionState_Pending: { ZS_LOG_DEBUG(log("lockbox is pending")) setState(AccountState_Pending); return false; } case IServiceLockboxSession::SessionState_PendingPeerFilesGeneration: { ZS_LOG_DEBUG(log("lockbox is pending and generating peer files")) setState(AccountState_PendingPeerFilesGeneration); return false; } case IServiceLockboxSession::SessionState_Ready: { ZS_LOG_DEBUG(log("lockbox session is ready")) return true; } case IServiceLockboxSession::SessionState_Shutdown: { ZS_LOG_ERROR(Detail, log("lockbox session shutdown")) setError(errorCode, reason); cancel(); return false; } } ZS_LOG_DEBUG(log("waiting for lockbox session to be ready")) return false; } //----------------------------------------------------------------------- bool Account::stepStackAccount() { ZS_THROW_BAD_STATE_IF(!mLockboxSession.get()) ZS_THROW_BAD_STATE_IF(!mStackAccount.get()) WORD errorCode = 0; String reason; stack::IAccount::AccountStates state = mStackAccount.get()->getState(&errorCode, &reason); if (stack::IAccount::AccountState_Ready == state) { ZS_LOG_DEBUG(log("step peer contact completed")) return true; } if ((stack::IAccount::AccountState_ShuttingDown == state) || (stack::IAccount::AccountState_Shutdown == state)) { ZS_LOG_ERROR(Detail, log("peer contact session shutdown")) setError(errorCode, reason); cancel(); return false; } ZS_LOG_DEBUG(log("waiting for stack account session to be ready")) return false; } //----------------------------------------------------------------------- bool Account::stepSelfContact() { if (mSelfContact) { ZS_LOG_DEBUG(log("contact self ready")) return true; } ILocationPtr selfLocation = ILocation::getForLocal(mStackAccount.get()); if (!selfLocation) { ZS_LOG_ERROR(Detail, log("could not obtain self location")) setError(IHTTP::HTTPStatusCode_InternalServerError, "Could not obtain location for self"); cancel(); return false; } mSelfContact = IContactForAccount::createFromPeer(mThisWeak.lock(), selfLocation->getPeer()); ZS_THROW_BAD_STATE_IF(!mSelfContact) return true; } //----------------------------------------------------------------------- bool Account::stepCallTransportSetup() { if (mCallTransport.get()) { ICallTransportForAccount::CallTransportStates state = mCallTransport.get()->getState(); if ((ICallTransport::CallTransportState_ShuttingDown == state) || (ICallTransport::CallTransportState_Shutdown == state)){ ZS_LOG_ERROR(Detail, log("premature shutdown of transport object (something is wrong)")) setError(IHTTP::HTTPStatusCode_InternalServerError, "Call transport shutdown unexpectedly"); cancel(); return false; } ZS_LOG_DEBUG(log("call transport ready")) return true; } IICESocket::TURNServerInfoList turnServers; IICESocket::STUNServerInfoList stunServers; mStackAccount.get()->getNATServers(turnServers, stunServers); mCallTransport.set(ICallTransportForAccount::create(mThisWeak.lock(), turnServers, stunServers)); if (!mCallTransport.get()) { ZS_LOG_ERROR(Detail, log("failed to create call transport object thus shutting down")) setError(IHTTP::HTTPStatusCode_InternalServerError, "Call transport failed to create"); cancel(); return false; } ZS_LOG_DEBUG(log("call transport is setup")) return true; } //----------------------------------------------------------------------- bool Account::stepSubscribersPermissionDocument() { if (mSubscribersPermissionDocument) { ZS_LOG_DEBUG(log("permission document ready")) return true; } IPublicationRepositoryPtr repository = getRepository(); if (!repository) { ZS_LOG_ERROR(Detail, log("repository on stack account is not valid thus account must shutdown")) setError(IHTTP::HTTPStatusCode_InternalServerError, "Repository object is missing"); cancel(); return false; } IPublication::RelationshipList relationships; relationships.push_back(mSelfContact->getPeerURI()); ILocationPtr selfLocation = ILocation::getForLocal(mStackAccount.get()); stack::IPublicationMetaData::PublishToRelationshipsMap empty; mSubscribersPermissionDocument = stack::IPublication::create(selfLocation, "/threads/1.0/subscribers/permissions", "text/x-json-openpeer-permissions", relationships, empty, selfLocation); if (!mSubscribersPermissionDocument) { ZS_LOG_ERROR(Detail, log("unable to create subscription permission document thus shutting down")) setError(IHTTP::HTTPStatusCode_InternalServerError, "Failed to create subscribers document"); cancel(); return false; } IPublicationPublisherPtr publisher = repository->publish(IPublicationPublisherDelegateProxy::createNoop(getAssociatedMessageQueue()), mSubscribersPermissionDocument); if (!publisher->isComplete()) { ZS_LOG_ERROR(Detail, log("unable to publish local subscription permission document which should have happened instantly")) setError(IHTTP::HTTPStatusCode_InternalServerError, "Failed to publish document to self"); cancel(); return false; } ZS_LOG_DEBUG(log("subscribers permission document created")) return true; } //----------------------------------------------------------------------- bool Account::stepPeerSubscription() { if (mPeerSubscription) { ZS_LOG_DEBUG(log("peer subscription ready")) return true; } mPeerSubscription = IPeerSubscription::subscribeAll(mStackAccount.get(), mThisWeak.lock()); if (!mPeerSubscription) { ZS_LOG_ERROR(Detail, log("unable to create a subscription to all connections")) setError(IHTTP::HTTPStatusCode_InternalServerError, "Failed to create peer subscription"); cancel(); return false; } ZS_LOG_DEBUG(log("peer subscription created")) return true; } //----------------------------------------------------------------------- bool Account::stepCallTransportFinalize() { if (ICallTransport::CallTransportState_Ready == mCallTransport.get()->getState()) { ZS_LOG_DEBUG(log("call transport is finalized")) return true; } ZS_LOG_DEBUG(log("waiting on call transport to be ready")) return false; } //----------------------------------------------------------------------- void Account::setState(IAccount::AccountStates state) { if (mCurrentState == state) return; ZS_LOG_BASIC(debug("state changed") + ZS_PARAM("new state", toString(state))) mCurrentState = state; AccountPtr pThis = mThisWeak.lock(); if (pThis) { try { mDelegate->onAccountStateChanged(mThisWeak.lock(), state); } catch (IAccountDelegateProxy::Exceptions::DelegateGone &) { ZS_LOG_WARNING(Detail, log("delegate gone")) } } } //----------------------------------------------------------------------- void Account::setError( WORD errorCode, const char *inReason ) { if (0 == errorCode) { ZS_LOG_DEBUG(log("no error specified")) return; } String reason(inReason ? String(inReason) : String()); if (reason.isEmpty()) { reason = IHTTP::toString(IHTTP::toStatusCode(errorCode)); } if (0 != mLastErrorCode) { ZS_LOG_WARNING(Detail, debug("error was already set (thus ignoring)") + ZS_PARAM("new error", errorCode) + ZS_PARAM("new reason", reason)) return; } mLastErrorCode = errorCode; mLastErrorReason = reason; ZS_LOG_ERROR(Detail, debug("account error")) } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark IAccount #pragma mark //------------------------------------------------------------------------- const char *IAccount::toString(AccountStates state) { switch (state) { case AccountState_Pending: return "Pending"; case AccountState_PendingPeerFilesGeneration: return "Pending Peer File Generation"; case AccountState_WaitingForAssociationToIdentity: return "Waiting for Association to Identity"; case AccountState_WaitingForBrowserWindowToBeLoaded: return "Waiting for Browser Window to be Loaded"; case AccountState_WaitingForBrowserWindowToBeMadeVisible: return "Waiting for Browser Window to be made Visible"; case AccountState_WaitingForBrowserWindowToClose: return "Waiting for Browser Window to Close"; case AccountState_Ready: return "Ready"; case AccountState_ShuttingDown: return "Shutting down"; case AccountState_Shutdown: return "Shutdown"; } return "UNDEFINED"; } //------------------------------------------------------------------------- ElementPtr IAccount::toDebug(IAccountPtr account) { return internal::Account::toDebug(account); } //------------------------------------------------------------------------- IAccountPtr IAccount::login( IAccountDelegatePtr delegate, IConversationThreadDelegatePtr conversationThreadDelegate, ICallDelegatePtr callDelegate, const char *namespaceGrantOuterFrameURLUponReload, const char *grantID, const char *lockboxServiceDomain, bool forceCreateNewLockboxAccount ) { return internal::IAccountFactory::singleton().login(delegate, conversationThreadDelegate, callDelegate, namespaceGrantOuterFrameURLUponReload, grantID, lockboxServiceDomain, forceCreateNewLockboxAccount); } //------------------------------------------------------------------------- IAccountPtr IAccount::relogin( IAccountDelegatePtr delegate, IConversationThreadDelegatePtr conversationThreadDelegate, ICallDelegatePtr callDelegate, const char *namespaceGrantOuterFrameURLUponReload, ElementPtr reloginInformation ) { return internal::IAccountFactory::singleton().relogin(delegate, conversationThreadDelegate, callDelegate, namespaceGrantOuterFrameURLUponReload, reloginInformation); } } }
[ "robin@hookflash.com" ]
robin@hookflash.com
16c1049a95a428b28463cf4d40078ef61fc6e469
b257bd5ea374c8fb296dbc14590db56cb7e741d8
/Extras/DevExpress VCL/Library/RS17/cxTLStyleSheetPreview.hpp
93eecc33b32a314a2e8ee1e925ec6f65a943ba12
[]
no_license
kitesoft/Roomer-PMS-1
3d362069e3093f2a49570fc1677fe5682de3eabd
c2f4ac76b4974e4a174a08bebdb02536a00791fd
refs/heads/master
2021-09-14T07:13:32.387737
2018-05-04T12:56:58
2018-05-04T12:56:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,862
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2012 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'cxTLStyleSheetPreview.pas' rev: 24.00 (Win32) #ifndef CxtlstylesheetpreviewHPP #define CxtlstylesheetpreviewHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <Winapi.Windows.hpp> // Pascal unit #include <Winapi.Messages.hpp> // Pascal unit #include <System.Classes.hpp> // Pascal unit #include <Vcl.Controls.hpp> // Pascal unit #include <System.SysUtils.hpp> // Pascal unit #include <cxStyles.hpp> // Pascal unit #include <cxTL.hpp> // Pascal unit #include <cxCustomData.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Cxtlstylesheetpreview { //-- type declarations ------------------------------------------------------- //-- var, const, procedure --------------------------------------------------- extern PACKAGE System::ResourceString _cxTextDescription; #define Cxtlstylesheetpreview_cxTextDescription System::LoadResourceString(&Cxtlstylesheetpreview::_cxTextDescription) extern PACKAGE System::ResourceString _cxPreviewDescription; #define Cxtlstylesheetpreview_cxPreviewDescription System::LoadResourceString(&Cxtlstylesheetpreview::_cxPreviewDescription) } /* namespace Cxtlstylesheetpreview */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_CXTLSTYLESHEETPREVIEW) using namespace Cxtlstylesheetpreview; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // CxtlstylesheetpreviewHPP
[ "bas@roomerpms.com" ]
bas@roomerpms.com
6168466c4c576cc825dc223e34b4517232899f2b
2f6f5729a36d484025d8e521d90349978a49f06f
/职工管理系统/Employee.h
903c9fb1fefd1b3a47e0ae1dc2d35b4d6042bf14
[]
no_license
Brendon3Tang/Employee-info-System
451081e30b1ba09fc18ca1539d1824fc9e3ac9c6
32b6bb0d4cba40fafb00beb3afe0338d9decc908
refs/heads/master
2023-08-25T04:04:55.984372
2021-10-25T03:57:35
2021-10-25T03:57:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
199
h
#pragma once #include <iostream> using namespace std; #include "Worker.h" class Employee:public Worker { public: Employee(int id, string name, int deptID); void showInfo(); string getDept(); };
[ "kyle3tang@gmail.com" ]
kyle3tang@gmail.com
5a192a7f140bcf1ae2cc9666d4e723121e273239
41ee3310acf30a8376f629c0cbd545c3ff18ed2e
/test/Challenges/ProjectEuler/LargestPrimeFactorTest.cpp
2f26f53f97082eee0922043f9b2e3c596701b620
[]
no_license
nponcian/LibroDeConocimiento
6f5c7ed3d487bdfcb9efdd70ecf3c66a92458613
59933de82547afa2437042e2c0a459d52c1a2425
refs/heads/master
2020-05-30T16:41:51.469600
2020-05-30T07:09:02
2020-05-30T07:09:02
189,851,906
0
1
null
null
null
null
UTF-8
C++
false
false
1,842
cpp
#include <iostream> #include <gtest/gtest.h> #include <Challenges/ProjectEuler/LargestPrimeFactor.hpp> using namespace src::challenges::euler; struct LargestPrimeFactorTest : public ::testing::Test { LargestPrimeFactorTest(){} virtual ~LargestPrimeFactorTest(){} virtual void SetUp(){} virtual void TearDown(){} LargestPrimeFactor impl_; }; TEST_F(LargestPrimeFactorTest, PrimeNumber) { long primeNumber = 19; std::stringstream iss; iss << primeNumber; auto result = impl_.run(iss); EXPECT_EQ(result.get<long>(), primeNumber); } TEST_F(LargestPrimeFactorTest, CompositeNumber) { long compositeNumber = 16; // 2 * 2 * 4 std::stringstream iss; iss << compositeNumber; auto result = impl_.run(iss); EXPECT_EQ(result.get<long>(), 2); } TEST_F(LargestPrimeFactorTest, MultiplyPrimeWithPrimeNumbers) { long largestPrimeNumber = 29; long answer = largestPrimeNumber * 5 * 7 * 13; std::stringstream iss; iss << answer; auto result = impl_.run(iss); EXPECT_EQ(result.get<long>(), largestPrimeNumber); } TEST_F(LargestPrimeFactorTest, MultiplyPrimeWithCompositeNumbers) { long largestPrimeNumber = 1999; long answer = largestPrimeNumber * 4 * 10 * 22; std::stringstream iss; iss << answer; auto result = impl_.run(iss); EXPECT_EQ(result.get<long>(), largestPrimeNumber); } TEST_F(LargestPrimeFactorTest, MultiplyPrimeWithMixOfPrimeAndCompositeNumbers) { long largestPrimeNumber = 1033; long primeNumber = 521; long largestCompositeNumber = 1034; long compositeNumber = 522; long answer = largestPrimeNumber * primeNumber * largestCompositeNumber * compositeNumber; std::stringstream iss; iss << answer; auto result = impl_.run(iss); EXPECT_EQ(result.get<long>(), largestPrimeNumber); }
[ "nielgp93@gmail.com" ]
nielgp93@gmail.com
d6ea6b288236e068a2ee2b2f0e71af8a14d73a95
68cf8fe6fdba5b0b2bbc17f0d920a20931871051
/src/module.h
5b720b035e814bf344f32fc60540c1e09289fa32
[]
no_license
boblancer/Godot-Networking
6e4fddb7eff39e78c0260f1ae9866e22a314e6b9
51cde68078741fb3493b1caf1190dc5bb9324013
refs/heads/master
2020-05-21T05:00:52.607680
2019-05-10T03:19:49
2019-05-10T03:19:49
185,910,573
1
2
null
null
null
null
UTF-8
C++
false
false
505
h
#ifndef GDEXAMPLE_H #define GDEXAMPLE_H #include <Godot.hpp> #include <Sprite.hpp> namespace godot { class GDExample : public Sprite { GODOT_CLASS(GDExample, Sprite) private: float time_passed; float time_emit; float amplitude; float speed; public: static void _register_methods(); GDExample(); ~GDExample(); void _init(); // our initializer called by Godot void _process(float delta); void set_speed(float p_speed); float get_speed(); }; } #endif
[ "janekarnkit2013@hotmail.com" ]
janekarnkit2013@hotmail.com
0494a674156b6c58febb8f8536180013d6aa125c
18a3f93e4b94f4f24ff17280c2820497e019b3db
/BOSS/facilities/Util.h
81e24c25504298b29123d825e0c5a487d8c6f9bc
[]
no_license
jjzhang166/BOSS_ExternalLibs
0e381d8420cea17e549d5cae5b04a216fc8a01d7
9b3b30f7874ed00a582aa9526c23ca89678bf796
refs/heads/master
2023-03-15T22:24:21.249109
2020-11-22T15:11:45
2020-11-22T15:11:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,479
h
// $ Header:$ #ifndef FACILITIES_UTIL_H #define FACILITIES_UTIL_H #include <string> #include <vector> #include <map> /** @file Util.h @author J. Bogart This file declares the class Util for basic static utilities and an associated exception class. */ namespace facilities { /// This class provides a home for utility functions with no need for /// any context (hence static) /// Exception class used by expandEnvVar class Untranslatable { public: Untranslatable(const std::string& toTrans) : m_badVar(toTrans) {} std::string m_badVar; }; /// Exception class used when converting from string to numeric type class WrongType { public: WrongType(const std::string& toConvert, const std::string& typeName) : m_toConvert(toConvert), m_typeName(typeName) {} std::string getMsg() { std::string msg = "facilities::WrongType. Cannot convert '" + m_toConvert + "' to type " + m_typeName; return msg; } private: std::string m_toConvert; std::string m_typeName; }; class Util { public: /** Given input string @a toExpand expand references to environment variables, by default of the form $(varname) and put the expanded version back into the original string. Alternate delimiters for the @a varname may optionally be specified @param toExpand string for which expansion is to be done @param openDel opening delimiter (defaults to "$(") @param closeDel closing delimiter (defaults to ")") @return -1 if attempt at expansion failed at least once, else number of successful expansions. TODO: Perhaps add optional arguments to specify alternate delimiters. */ static int expandEnvVar(std::string* toExpand, const std::string& openDel = std::string("$("), const std::string& closeDel = std::string(")")); /** Given an input integer @a val to convert and an output string @a outStr converts val into a std::string. This method duplicates the stdlib.h method itoa, except that it returns std::string rather than char*. @param val @param outStr will be modified by this method @return const char* based on the contents of outStr.c_str() */ static const char* itoa(int val, std::string &outStr); /// converts an std::string to an integer static int atoi(const std::string& InStr); /// converts a std::string to a double. If string contents are not /// of proper form, throws facilities::WrongType static double stringToDouble(const std::string& InStr); /// converts a std::string to an int. If string contents are not /// of proper form, throws facilities::WrongType static int stringToInt(const std::string& InStr); /** This routine breaks down a string into tokens, based on the characters appearing in the string @a delimiters. @param input string to be tokenized @param delimiters string containing one or more delimiter characters @param tokens vector of strings to hold resulting tokens @param clear if true (default) @a tokens will be cleared at the start of processing */ static void stringTokenize(std::string input, const std::string &delimiters, std::vector<std::string> &tokens, bool clear = true); /** This routine breaks down a string into key/value token pairs and stores them in the user-supplied map. , based on the characters appearing in the string @a delimiters and the value of @a pairDelimiter. In a typical example, @a input could be "key1=val1,key2=val2,key3=val3". In this case invoke with delimiters=std::string(",") and pairDelimiter=std::string("=") (or omit pairDelimiter since it has the default value) @param input string to be tokenized @param delimiters string containing one or more delimiter characters @param tokenMap map of strings to hold resulting tokens @param pairDelimiter string separating key and value; defaults to "=" @param clear if true (default) @a tokens will be cleared at the start of processing */ static void keyValueTokenize(std::string input, const std::string &delimiters, std::map<std::string,std::string> &tokenMap, const std::string& pairDelimiter = std::string("="), bool clear = true); /** return the "non-directory" part of a (supposed) file identifier, @a path. Environment variable translation should be done before calling @a basename. @sa { Util::expandEnvVar } @param path string assumed to be a file identifier. */ static std::string basename(const std::string &path); /** Trim trailing white space characters from the supplied string. White space characters for this purpose are blank, carriage return, line feed and form feed. Return # of characters trimmed. */ static unsigned trimTrailing(std::string* toTrim); }; } #endif
[ "r.e.deboer@students.uu.nl" ]
r.e.deboer@students.uu.nl
486a1d914d9b9229c896c9885a6b6741153eaee3
a7ee03b5a67b2a449352de4bb82573d556f56768
/CPP/PVT/lab2.cpp
5cc5e64d25ec9396f9d24e53a613789a8995b932
[]
no_license
TomatoFish/IV222
c0a54a6114008ba7f20985d7f4e5e4faa814a69d
19afe56ce96e857d3d83ad73eca08109eaeaf43c
refs/heads/master
2020-04-06T03:47:02.529630
2014-11-27T14:23:19
2014-11-27T14:23:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,916
cpp
#include <sys/types.h> #include <pthread.h> #include <sys/stat.h> #include <dirent.h> #include "errors.h" #include <signal.h> #include <chrono> #include <iostream> #define CREW_SIZE 8 using namespace std; typedef struct work_tag { struct work_tag *next; char *path; } work_t, *work_p; typedef struct worker_tag { int index; pthread_t thread; struct crew_tag *crew; } worker_t, *worker_p; typedef struct crew_tag { int crew_size; worker_t crew[CREW_SIZE]; long work_count; work_t *first, *last; pthread_mutex_t mutex; pthread_cond_t done; pthread_cond_t go; } crew_t, *crew_p; size_t path_max; size_t name_max; sigset_t mask; pthread_t sig; pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; int QUIT = 0; void copy_to(char *a, char *b) { while(*b != '.') { *a = *b; *b++; *a++; } } void *read_signals(void *arg) { crew_t *cr = (crew_t*)arg; int signo; for(;;){ sigwait(&mask,&signo); switch(signo) { case SIGINT: for(int i = 0;i < CREW_SIZE;i++){ pthread_cancel(cr->crew[i].thread); } exit(0); break; case SIGQUIT: if(QUIT == 0) QUIT = 1; break; default: printf("Неизвестный сигнал"); exit(1); } } } void unlock(void *arg) { pthread_mutex_t *t; t = (pthread_mutex_t *)arg; pthread_mutex_unlock(t); } void close_file(void *arg) { FILE *f; f = (FILE *)arg; fclose(f); } void *worker_routine (void *arg) { worker_p mine = (worker_t *) arg; crew_p crew = mine->crew; work_p work, new_work; struct stat filestat; struct dirent *entry; int rc; FILE *log; pthread_cleanup_push(close_file,&log); log = fopen("log.txt","a+"); entry = (struct dirent*)malloc ( sizeof (struct dirent) + name_max); pthread_cleanup_push(unlock, &crew->mutex); pthread_mutex_lock (&crew->mutex); while (crew->work_count == 0) { pthread_cond_wait (&crew->go, &crew->mutex); } pthread_mutex_unlock (&crew->mutex); pthread_cleanup_pop(0); for (;;) { pthread_cleanup_push(unlock, &crew->mutex); pthread_mutex_lock (&crew->mutex); while (crew->first == NULL) { pthread_cond_wait (&crew->go, &crew->mutex); } work = crew->first; crew->first = work->next; if (crew->first == NULL) crew->last = NULL; pthread_mutex_unlock (&crew->mutex); pthread_cleanup_pop(0); lstat (work->path, &filestat); if (S_ISDIR (filestat.st_mode)) { DIR *directory; struct dirent *result; directory = opendir (work->path); if (directory == NULL) { printf("..."); continue; } for (;;) { rc = readdir_r (directory, entry, &result); if (rc != 0) { fprintf(stderr, "..."); break; } if (result == NULL) break; if (strcmp (entry->d_name, ".") == 0) continue; if (strcmp (entry->d_name, "..") == 0) continue; new_work = (work_p) malloc (sizeof (work_t)); new_work->path = (char*) malloc (path_max); strcpy (new_work->path, work->path); strcat (new_work->path, "/"); strcat (new_work->path, entry->d_name); new_work->next = NULL; pthread_cleanup_push(unlock, &crew->mutex); pthread_mutex_lock (&crew->mutex); if (crew->first == NULL) { crew->first = new_work; crew->last = new_work; } else { crew->last->next = new_work; crew->last = new_work; } crew->work_count++; pthread_cond_signal (&crew->go); pthread_mutex_unlock (&crew->mutex); pthread_cleanup_pop(0); } closedir(directory); } else if (S_ISREG (filestat.st_mode)) { if (strstr(work->path,".cpp")){ char ch[200]="\0", buff[200]="\0", buf[200]="\0"; FILE *fp; copy_to(buff,work->path); sprintf(ch, "g++ %s -o %s && %s",work->path,buff,buff); pthread_cleanup_push(close_file, &fp); fp = popen(ch,"r"); pthread_cleanup_push(unlock, &mu); pthread_mutex_lock(&mu); while((fgets(buf, 80, fp)) != NULL) { fprintf(log, "Результат \"%s\" работы потока %d\n",buf,mine->index); } pthread_mutex_unlock(&mu); pthread_cleanup_pop(0); pclose(fp); pthread_cleanup_pop(0); } else if(strstr(work->path,".sh")) { char ch[80],buf[80]; sprintf(ch, "chmod +x %s && %s",work->path,work->path); FILE *f; pthread_cleanup_push(close_file,&f); f = popen(ch,"r"); pthread_cleanup_push(unlock,&mu); pthread_mutex_lock(&mu); while((fgets(buf, 80, f)) != NULL) { fprintf(log, "Результат '%s' работы потока %d\n",buf,mine->index); } pthread_mutex_unlock(&mu); pthread_cleanup_pop(0); pclose(f); pthread_cleanup_pop(0); } } free(work->path); free(work); pthread_cleanup_push(unlock,&crew->mutex); pthread_mutex_lock (&crew->mutex); crew->work_count--; if (crew->work_count <= 0) { pthread_cond_broadcast (&crew->done); pthread_mutex_unlock (&crew->mutex); break; } pthread_mutex_unlock (&crew->mutex); pthread_cleanup_pop(0); } fclose(log); pthread_cleanup_pop(0); free (entry); return NULL; } int crew_create (crew_t *crew, int crew_size) { int rc; int crew_index; if (crew_size > CREW_SIZE) return -1; crew->crew_size = crew_size; crew->work_count = 0; crew->first = NULL; crew->last = NULL; pthread_mutex_init (&crew->mutex, NULL); pthread_cond_init (&crew->done, NULL); pthread_cond_init (&crew->go, NULL); for (crew_index = 0; crew_index < CREW_SIZE; crew_index++) { crew->crew[crew_index].index = crew_index; crew->crew[crew_index].crew = crew; rc = pthread_create (&crew->crew[crew_index].thread, NULL, worker_routine, (void*)&crew->crew[crew_index]); if(rc != 0) printf("pthread_create error"); } rc = pthread_create(&sig,NULL,read_signals,crew); if(rc != 0) printf("pthread_create error"); return 0; } int crew_start(crew_p crew, char *filepath) { work_p request; pthread_mutex_lock (&crew->mutex); while (crew->work_count > 0) pthread_cond_wait (&crew->done, &crew->mutex); if(QUIT == 1){ return 0; } path_max = pathconf (filepath, _PC_PATH_MAX); if (path_max == -1) { /* ... */ } name_max = pathconf(filepath, _PC_NAME_MAX); if (name_max == -1) { /* ... */ } path_max++; name_max++; request = (work_p) malloc(sizeof(work_t)); request->path = (char *) malloc(path_max); strcpy (request->path, filepath); request->next = NULL; if (crew->first == NULL) { crew->first = request; crew->last = request; } else { crew->last->next = request; crew->last = request; } crew->work_count++; pthread_cond_signal (&crew->go); while (crew->work_count > 0) pthread_cond_wait (&crew->done, &crew->mutex); pthread_mutex_unlock (&crew->mutex); return 0; } int main (int argc, char *argv[]) { int rc; sigset_t oldmask; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); sigaddset(&mask, SIGTERM); rc = pthread_sigmask(SIG_BLOCK, &mask, &oldmask); if(rc != 0) printf("pthread_sigmask error"); crew_t my_crew; argv[1]="/home/madbomber/"; crew_create(&my_crew, CREW_SIZE); auto start = chrono::high_resolution_clock::now(); crew_start(&my_crew, argv[1]); auto end = chrono::high_resolution_clock::now(); cout << "Time taken: " << (end-start).count() * ((double)chrono::high_resolution_clock::period::num / chrono::high_resolution_clock::period::den) << endl; return 0; }
[ "madjarvan@gmail.com" ]
madjarvan@gmail.com
dfde4433ca3c49beb595b952881acf8d2c859f9a
fae2bf3d80f95450276685700d13c9f203fd2475
/Complex/Test Project/VP/VPTestCode/VMTestCode/lib.cpp
d858952f292dff32c6446c50b3215e12a2d8bab4
[]
no_license
TatianaLiakh/Verifying-Pack
0a188ff18540a00ff32785e5e62c9842bed01116
ac2b3342505a8565704a28a5067107922794bee1
refs/heads/master
2021-01-24T08:30:13.666017
2018-05-14T14:48:58
2018-05-14T14:48:58
93,384,208
1
0
null
null
null
null
UTF-8
C++
false
false
2,457
cpp
#include "lib.h" MgErr _states_array_resize(ArrayOfStatesHdl states_hdl) { MgErr error; if (mgNoErr == (error = DSSetHSzClr(states_hdl, Offset(ArrayOfStates, state) + sizeof(ProcessState) * (PROCESS_Nn + 1)))) { for (size_t i = 0; i <= PROCESS_Nn; i++) { (*states_hdl)->state[i].cur_state = (int8)STATE_OF_STOP; (*states_hdl)->state[i].TimeInState = 0; } (*states_hdl)->dimSize = PROCESS_Nn + 1; } return error; } MgErr _ports_array_resize(PortsHdl new_handler, size_t size, INT8S * & array, int32_t & counter) { MgErr error = NumericArrayResize(uB, 1, (UHandle*)(&new_handler), size); if (error == mgNoErr) { (*new_handler)->dimSize = size; counter = (*new_handler)->dimSize; } //(*new_handler)->ports[size] = 255; return error; } MgErr _msg_array_resize(ArrayOfMessagesHdl _msgs) { int32_t new_size = ARRLENRSMSG; MgErr err; if (mgNoErr == (err = DSSetHSzClr(_msgs, Offset(ArrayOfMessages, message) + new_size * sizeof(MessageCluster)))) { for (size_t i = 0; i < new_size; i++) { MessageCluster * msg = &(*_msgs)->message[i]; msg->msg = -1; msg->type = 0; msg->param = 0; } (*_msgs)->dimSize = new_size; } return err; } void parse_output_msg_array(MsgQueue & output_queue, ArrayOfMessagesHdl outputMsgArray) { for (int32_t i = 0; i < (*outputMsgArray)->dimSize; i++) { if (true != isEmptyMsgQueue(&output_queue)) { QueueMsg msg; GetHeadMsgQueue(&output_queue, &msg); (*outputMsgArray)->message[i].msg = msg.code; (*outputMsgArray)->message[i].param = msg.param.pr_long; (*outputMsgArray)->message[i].type = msg.type; } else { (*outputMsgArray)->message[i].msg = -1; (*outputMsgArray)->message[i].param = 0; (*outputMsgArray)->message[i].type = 0; } } } void parse_input_msg_array(ArrayOfMessagesHdl input_LV_queue, MsgQueue & result_queue) { //inputMsgArray MessageCluster * iter = (*input_LV_queue)->message; for (int i = 0; i < (*input_LV_queue)->dimSize; i++) { if (-1 == iter[i].msg) return; switch (iter[i].type) { case EMPTY_MSG: PutTailMsgQueue(&result_queue, iter[i].msg); break; case BYTE_TYPE: PutTailMsgQueueB(&result_queue, iter[i].msg, static_cast<char> (iter[i].param)); break; case INT_TYPE: PutTailMsgQueueI(&result_queue, iter[i].msg, iter[i].param); break; case FLOAT_TYPE: PutTailMsgQueueF(&result_queue, iter[i].msg, *(float32 *)(&(iter[i].param))); break; default: break; } } }
[ "antsys_nsu@mail.ru" ]
antsys_nsu@mail.ru
da38604248e0061cb2aa9a041a56f1d976fa780a
6cfdfea1780b3b57bea95277d09c369399a49d34
/include/BackTracking.h
f5ffefb95ad02d30db09b458e2401d390601894d
[]
no_license
Boscuit/UAV_BackTrack
51125e67d8aaa6d667737f89d19236ecd135408d
2cdd711c70f98a6baa71adb41bb367665f8ecf38
refs/heads/master
2022-12-03T20:47:18.514056
2020-08-27T16:30:00
2020-08-27T16:30:00
272,179,425
0
0
null
null
null
null
UTF-8
C++
false
false
1,285
h
#ifndef BACKTRACKING_H #define BACKTRACKING_H #include<opencv2/core/core.hpp> #include<opencv2/features2d/features2d.hpp> #include<unistd.h> #include<iostream> #include "Initializer.h" #include "Frame.h" #include "ORBVocabulary.h" #include "ORBextractor.h" namespace UAV_BackTrack { class BackTracking { public: BackTracking(ORBVocabulary* pVoc,const string &strSettingPath); //Return estimated pose of Im2 base on Im1 in camera frame cv::Mat BackTrack(const cv::Mat &Im1, const cv::Mat &Im2, const double &tframe1, const double &tframe2, int index1, int index2); std::vector<int> mvIniMatches; std::vector<cv::Point2f> mvbPrevMatched; std::vector<cv::Point3f> mvIniP3D; private: void ShowMatches(const cv::Mat &Im1, const cv::Mat &Im2, const Frame &Frame1, const Frame &Frame2, vector<int> vMatches21, int nBoWmatches, const string &methodName); //ORB ORBextractor* mpORBextractor; //BoW ORBVocabulary* mpORBVocabulary; // Initalization (only for monocular) Initializer* mpInitializer; //Calibration matrix cv::Mat mK; cv::Mat mDistCoef; float mbf; float mThDepth; //Color order (true RGB, false BGR, ignored if grayscale) bool mbRGB; }; } #endif // BACKTRACKING_H
[ "115010184@link.cuhk.edu.cn" ]
115010184@link.cuhk.edu.cn
47b71aa6083eb4c99895bd3a559c2d9bed892964
fa7f1f695900a8148f3db48d6ea3cb17768b610b
/include/FunctionInfo.h
2546b890bdd3777a545e2c96bbd0cde12831231e
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
mipek/detourdecon
6cc703668b1cd29cc3a13c39c5dc19f2256b3c9a
4c945ffe31fdaa2376a5bfbfc261d16f44d31c92
refs/heads/master
2020-12-31T02:01:35.810735
2015-02-28T16:46:42
2015-02-28T16:46:42
24,411,381
4
0
null
null
null
null
UTF-8
C++
false
false
2,878
h
/** * Copyright (c) 2014, Michael Pekar * 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 * 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. */ #ifndef _include_functioninfo_h_ #define _include_functioninfo_h_ #include "DetourDecon.h" /** * @brief Enumerates supported calling conventions. */ typedef enum CallConvention { CallConv_cdecl = 0, CallConv_stdcall, //CallConv_fastcall, CallConv_thiscall /**< not supported yet. */ } callConv_e; /** * @brief Lists available parameter types. */ typedef enum ParameterType { ParamType_POD, /**< Plain old data. */ ParamType_ByRef, /**< Pass by reference. */ ParamType_Float, /**< Floating point. */ } paramType_e; typedef struct Parameter { paramType_e type; int size; } param_t; typedef struct FuncProto { callConv_e callconv; int paramCount; param_t *params; param_t ret; } prototype_t; template<int P_COUNT> class TPrototype { param_t paraminf_[P_COUNT]; prototype_t proto_; int idx_; public: TPrototype(callConv_e x): idx_(0) { proto_.callconv = x; proto_.paramCount = P_COUNT; proto_.params = paraminf_; proto_.ret.size = 0; } void AddParam(int sz, paramType_e type) { paraminf_[idx_].size = sz; paraminf_[idx_++].type = type; } void SetReturn(int sz, paramType_e type) { proto_.ret.size = sz; proto_.ret.type = type; } void SetReturnNone() { proto_.ret.size = 0; } prototype_t *Prototype() { return proto_; } }; #endif //_include_functioninfo_h_
[ "donrevan@dscorp.de" ]
donrevan@dscorp.de
52bec585228fab768322987f9557a78e1cb8c034
999efeab3cfb421235596031dbd2a78cdb1e1050
/camera.hpp
f7e93f839c586cb5149bade8724e944e3b6a61c5
[]
no_license
BulatAbdullin/3D
cf00263b01093ee182556d3d919fe65f738bd0a3
5288af9d1e7bb2aa8f3c71532a419b40c7a8568a
refs/heads/main
2023-03-05T01:53:47.856559
2021-02-18T10:30:33
2021-02-18T10:30:33
313,311,891
0
0
null
null
null
null
UTF-8
C++
false
false
2,523
hpp
#ifndef CAMERA_HPP #define CAMERA_HPP #define GLFW_INCLUDE_ES3 #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> class Camera { private: GLfloat width; GLfloat height; glm::vec3 position; GLfloat near; GLfloat far; GLfloat fov; /* field of view */ GLfloat speed; GLfloat mouse_sensitivity; glm::vec3 direction; glm::vec3 up; glm::vec3 right; GLfloat yaw; GLfloat pitch; const static GLfloat pitch_max; const static GLfloat pitch_min; const static GLfloat fov_max; const static GLfloat fov_min; public: Camera(GLfloat width, GLfloat height, glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), GLfloat near = 0.1f, GLfloat far = 100.0f, GLfloat fov = 45.0f, GLfloat speed = 9.0f, GLfloat mouse_sensitivity = 0.1f, glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = -90.0f, GLfloat pitch = 0.0f) : width(width) , height(height) , position(position) , near(near) , far(far) , fov(fov) , speed(speed) , mouse_sensitivity(mouse_sensitivity) , up(up) , yaw(yaw) , pitch(pitch) { this->update(); } void update(); inline glm::vec3 get_position() const { return position; } inline glm::mat4 get_view_matrix() const { return glm::lookAt(position, position + direction /* target */, up); } inline glm::mat4 get_projection_matrix() const { return glm::perspective(fov, width / height, near, far); } inline void move_forward(GLfloat deltatime) { position += direction * speed * deltatime; } inline void move_backward(GLfloat deltatime) { position -= direction * speed * deltatime; } inline void move_right(GLfloat deltatime) { position += right * speed * deltatime; } inline void move_left(GLfloat deltatime) { position -= right * speed * deltatime; } inline void move_up(GLfloat deltatime) { position += up * speed * deltatime; } inline void move_down(GLfloat deltatime) { position -= up * speed * deltatime; } void process_mouse_movement(GLfloat xoffset, GLfloat yoffset); }; #endif /* CAMERA_HPP */
[ "bulat.abdullin@stud.cs.msu.ru" ]
bulat.abdullin@stud.cs.msu.ru
87c6785adc985c83993d0ba2e7de32ce25e3eb68
777d5f51e7931059cf2d10e758b17f6daf01bc4d
/include/WrappedRange.h
64944b5a09c44b6f61f6fddab1cffa1b642027e2
[ "MIT" ]
permissive
chubbymaggie/sasi
d9a728706000553714fc6958053e41a22625531e
a406bd69728f5502bc618fc01782a48db6c3d3ea
refs/heads/master
2020-06-30T06:45:49.319816
2019-06-21T18:47:27
2019-06-21T18:47:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,604
h
// Authors: Jorge. A Navas, Peter Schachte, Harald Sondergaard, and // Peter J. Stuckey. // The University of Melbourne 2012. #ifndef __WRAPPED_RANGE__H__ #define __WRAPPED_RANGE__H__ //////////////////////////////////////////////////////////////////////// /// \file WrappedRange.h /// Wrapped Interval Abstract Domain. /// /// This file contains the definition of the WrappedRange class, /// which improves the Range class by allowing an interval to /// be wrapped around without directly going to "top". /// /// Moreover, very importantly this analysis is sign-agnostic. That /// is, it does not make any assumption about sign of variables in /// opposite to Range and BaseRange classes. However, the abstract /// domain does not form a lattice so special care is needed since /// joins and meets are neither monotone nor associate. /// /// For details, we refer to "Signedness-Agnostic Program Analysis: /// Precise Integer Bounds for Low-Level Code" by J. A. Navas, /// P. Schachte, H. Sondergaard, P. J. Stuckey published in APLAS'12. /// /// We need a special symbol for bottom since the range [-1,0] is a /// valid wrapped interval that, in fact, it denotes top. //////////////////////////////////////////////////////////////////////// #include "AbstractValue.h" #include "BaseRange.h" #include "Support/Utils.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/BasicBlock.h" #include "llvm/Instructions.h" #include "llvm/Constants.h" #include "llvm/Attributes.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/Statistic.h" #include <tr1/memory> /// Wrapped intervals do not make any distinction whether variables /// are signed or not since the analysis is signed-agnostic. /// Therefore, by default we assume that all operations are unsigned /// except those that really depend on the sign (e.g. division, /// comparisons, etc). In any case, the analysis uses this flag. #define __SIGNED false // false means unsigned by default. #define DEBUG_TYPE "RangeAnalysis" namespace unimelb { class WrappedRange; typedef std::tr1::shared_ptr<WrappedRange> WrappedRangePtr; class WrappedRange: public BaseRange { public: virtual BaseId getValueID() const { return WrappedRangeId; } /// Constructor of the class. WrappedRange(Value *V): BaseRange(V, __SIGNED, false), __isBottom(false), CounterWideningCannotDoubling(0){} /// Constructor of the class for an integer constant. WrappedRange(const ConstantInt *C, unsigned Width): BaseRange(C,Width, __SIGNED, false), __isBottom(false), CounterWideningCannotDoubling(0){ } /// Constructor of the class for a TBool object WrappedRange(Value *V, TBool * B): BaseRange(V, __SIGNED, false), __isBottom(false), CounterWideningCannotDoubling(0){ if (B->isTrue()){ setLB((uint64_t) 1); setUB((uint64_t) 1); } else if (B->isFalse()){ setLB((uint64_t) 0); setUB((uint64_t) 0); } else{ setLB((uint64_t) 0); setUB((uint64_t) 1); } } /// Constructor of the class for APInt's /// For temporary computations. WrappedRange(APInt lb, APInt ub, unsigned Width): BaseRange(lb,ub,Width,__SIGNED,false), __isBottom(false), CounterWideningCannotDoubling(0){ } /// Copy constructor of the class. WrappedRange(const WrappedRange& other ): BaseRange(other){ __isBottom = other.__isBottom; CounterWideningCannotDoubling = other.CounterWideningCannotDoubling; } /// Destructor of the class. ~WrappedRange(){} /// Cardinality of a wrapped interval. static inline APInt WCard(const APInt &x, const APInt &y){ if (x == y+1){ // ie., if [MININT,MAXINT} APInt card = APInt::getMaxValue(x.getBitWidth()); // FIXME: getMaxValue(width) is actually 2^w - 1. // It should be card here 2^w return card; } else{ // Implicitly we use mod 2^w where w is the width of x and y. // since APInt will wraparound if overflow. APInt card = (y - x) + 1; return card; } } /// To try to have a single representation of top (e.g., [1,0], /// [2,1], [-1,-2], [MININT,MAXINIT], etc). This is not needed for /// correctness but it is vital for presentation and a fair /// comparison with other analyses. inline void normalizeTop(){ if (isBot()) return; if (LB == UB+1){ // implicitly using mod 2^w DEBUG(dbgs() << "Normalizing [" << LB << "," << UB << "]" << " to top interval (" << getWidth() << " bits).\n"); makeTop(); } } /// Used to compare precision with other analyses inline void normalize(){ if (IsTop()) return; if (isBot()) return; normalizeTop(); } // For comparison with other analyses. inline uint64_t Cardinality() const { if (isBot()) return 0; APInt x = getLB(); APInt y = getUB(); if (IsTop() || (x == y+1)) { APInt card = APInt::getMaxValue(width); return card.getZExtValue() + 1; } APInt card = (y - x + 1); return card.getZExtValue(); } /// Return true if | \gamma(this) | == 1 virtual bool isGammaSingleton() const { if (isBot() || IsTop()) return false; APInt lb = getLB(); APInt ub = getUB(); APInt card = WrappedRange::WCard(lb,ub); return (card == 1); } inline bool IsRangeTooBig(const APInt &lb, const APInt &ub){ APInt card = WrappedRange::WCard(lb,ub); // If card does not fit into uint64_t then APInt raises an // exception. uint64_t n = card.getZExtValue(); // If width of lb and ub are different then APInt raises an // exception. unsigned width = lb.getBitWidth(); // If 2^w does not fit into uint64_t then APInt raises an exception. uint64_t Max = (APInt::getMaxValue(width)).getZExtValue() + 1; return (n >= Max); } inline void convertWidenBoundsToWrappedRange(const APInt &lb, const APInt &ub){ if (IsRangeTooBig(lb,ub)) makeTop(); else{ setLB(lb); setUB(ub); } } /// clone method WrappedRange* clone(){ return new WrappedRange(*this); } /// Methods for support type inquiry through isa, cast, and /// dyn_cast. static inline bool classof(const WrappedRange *) { return true; } static inline bool classof(const BaseRange *V) { return (V->getValueID() == WrappedRangeId); } static inline bool classof(const AbstractValue *V) { return (V->getValueID() == WrappedRangeId); } virtual bool isBot() const; virtual bool IsTop() const ; virtual void makeBot(); virtual void makeTop(); virtual void print(raw_ostream &Out) const; inline void WrappedRangeAssign(WrappedRange * other) { BaseRange::RangeAssign(other); __isBottom = other->__isBottom; } /// Key auxiliary methods to split the wrapped range at the south /// and north poles. The use of these guys are key for most of the /// arithmetic, casting and bitwise operations as well as comparison /// operators. static std::vector<WrappedRangePtr> ssplit(const APInt&, const APInt&, unsigned); static std::vector<WrappedRangePtr> nsplit(const APInt&, const APInt&, unsigned); bool WrappedMember(const APInt&) const; virtual bool hasNoZero() const { APInt zero(1, 0); return !this->isBot() && !this->WrappedMember(zero); } bool WrappedlessOrEqual(AbstractValue *); virtual bool lessOrEqual(AbstractValue *); virtual void WrappedJoin(AbstractValue *); virtual void join(AbstractValue *); /// Apply the join but considering the fact that the domain is not /// associative. Thus, it may be more precise than apply simply /// join repeatedly. It can be used for operations like /// multiplication and phi nodes with multiple incoming values. virtual void GeneralizedJoin(std::vector<AbstractValue *>); virtual void meet(AbstractValue *, AbstractValue *); virtual bool isEqual(AbstractValue*); virtual void widening(AbstractValue *, const std::vector<int64_t> &); /// Return true is this is syntactically identical to V. virtual bool isIdentical(AbstractValue *V); /// To determine if the evaluation of a guard is true/false/maybe. virtual bool comparisonSle(AbstractValue *); virtual bool comparisonSlt(AbstractValue *); virtual bool comparisonUle(AbstractValue *); virtual bool comparisonUlt(AbstractValue *); bool isMoreOrEqualPrecise(AbstractValue *); /// To filter the interval of a variable involved in a guard. virtual void filterSigma(unsigned, AbstractValue*, AbstractValue*); void filterSigma_TwoVars(unsigned, WrappedRange*, WrappedRange*); void filterSigma_VarAndConst(unsigned, WrappedRange*, WrappedRange*); // Here abstract domain-dependent transfer functions void WrappedPlus(WrappedRange *, const WrappedRange *, const WrappedRange *); void WrappedMinus(WrappedRange *, const WrappedRange *, const WrappedRange *); void WrappedMultiplication(WrappedRange *, const WrappedRange *, const WrappedRange *); void WrappedDivision(WrappedRange *, const WrappedRange *, const WrappedRange *, bool); void WrappedRem(WrappedRange *, const WrappedRange *,const WrappedRange *, bool); // addition, substraction, and the rest above virtual AbstractValue* visitArithBinaryOp(AbstractValue *, AbstractValue *, unsigned, const char *); // truncation, signed/unsigned extension virtual AbstractValue* visitCast(Instruction &, AbstractValue *, TBool *, bool); // and, or, xor void WrappedLogicalBitwise(WrappedRange *, WrappedRange *, WrappedRange *, unsigned); // logical/arithmetic right shift, left shift void WrappedBitwiseShifts(WrappedRange *, WrappedRange *, WrappedRange *, unsigned); // all bitwise operations: many of them are quite tricky because // they are not monotone virtual AbstractValue* visitBitwiseBinaryOp(AbstractValue *, AbstractValue *, const Type *, const Type *, unsigned, const char *); private: bool __isBottom; //!< If true the interval is bottom. // During widening it is possible that we cannot doubling the // interval but we could choose a program constant that may // produce a tighter interval. However, we can only do this a // finite number of times. unsigned int CounterWideningCannotDoubling; inline void resetBottomFlag(){ __isBottom=false; } /// Convenient wrapper. void Binary_WrappedJoin(WrappedRange *R1, WrappedRange *R2); }; WrappedRange WrappedMeet(WrappedRange *, WrappedRange *); inline raw_ostream& operator<<(raw_ostream& o, WrappedRange r) { r.printRange(o); return o; } inline bool IsMSBOne(const APInt &x){ // This tests the high bit of the APInt to determine if it is set. return (x.isNegative()); } inline bool IsMSBZero(const APInt &x){ return (!x.isNegative()); } /// Return true if x is lexicographically smaller than y. inline bool Lex_LessThan(const APInt &x, const APInt &y){ bool a = !x.isNegative(); //IsMSBZero(x); bool b = !y.isNegative(); //IsMSBZero(y); if (!a && b) return false; else if ( a && !b) return true; else if (!a && !b) return x.slt(y); else return x.ult(y); } /// Return true if x is lexicographically smaller or equal than y. inline bool Lex_LessOrEqual(const APInt &x, const APInt &y){ bool a = !x.isNegative(); //IsMSBZero(x); bool b = !y.isNegative(); //IsMSBZero(y); if (!a && b) return false; else if ( a && !b) return true; else if (!a && !b) return x.sle(y); else return x.ule(y); } /// Lexicographical maximum inline APInt Lex_max(const APInt &x, const APInt &y){ return (Lex_LessOrEqual(x,y)? y : x); } /// Lexicographical minimum inline APInt Lex_min(const APInt &x, const APInt &y){ return (Lex_LessOrEqual(x,y)? x : y); } /// Return a wrapped interval that covers singleton x and y. inline WrappedRange mkSmallerInterval(const APInt &x, const APInt &y, unsigned width){ WrappedRange R1(x, x, width); WrappedRange R2(y, y, width); R1.join(&R2); return R1; } } // end namespace #endif
[ "n.redini@gmail.com" ]
n.redini@gmail.com
1fd5e3829076c3e1828e817eede4e442b449e608
d4620eb43e7d3145b9a7a9968cd7774fc7eb432e
/src/Callback/CallbackAddPointsInCurvesGraphs.cpp
5b9b6fbe8f6d1009296139e4a62efb9511093086
[]
no_license
TommyTeaVee/engauge6
ae7487f28c8da40c4c9ab8f83c9dc898097686d9
68876a80e2e2675ea66cd88b318ab5440d79387b
refs/heads/master
2021-11-12T08:05:23.786581
2015-01-27T10:37:14
2015-01-27T10:37:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
#include "CallbackAddPointsInCurvesGraphs.h" #include "Document.h" extern const QString AXIS_CURVE_NAME; CallbackAddPointsInCurvesGraphs::CallbackAddPointsInCurvesGraphs(Document &document) : m_document (document) { } CallbackSearchReturn CallbackAddPointsInCurvesGraphs::callback (const QString &curveName, const Point &point) { const QString identifier = point.identifier (); if (curveName == AXIS_CURVE_NAME) { m_document.addPointAxis (point.posScreen (), point.posGraph (), identifier); } else { m_document.addPointGraph (curveName, point.posScreen (), identifier); } return CALLBACK_SEARCH_RETURN_CONTINUE; }
[ "markummitchell@gmail.com" ]
markummitchell@gmail.com
77c236690e26f100d072b73d178685dc0067f0ee
ea4baa032d017598a1c85e3241a4399a09c0c805
/src/Edge.h
0ed8a06529e53ae05bf5f8803f57bad2906e8c24
[ "Apache-2.0" ]
permissive
PaceyIV/sskeleton
7370d05e88262a71c2ccc1af158527e2c3542985
ec5833c9f3b7eddf1d0249367345c1d762d411e4
refs/heads/master
2021-12-06T06:10:13.711923
2012-11-13T01:41:10
2012-11-13T01:41:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
h
#ifndef EDGE_H #define EDGE_H #include <boost/math/special_functions/fpclassify.hpp> #include <cmath> #include <iostream> #include <stdexcept> #include "Corner.h" #include "GC.h" #include "LinearForm3D.h" #include "LinkedHashContainer.h" #include "Point3D.h" #include "Vector3D.h" class Corner; class Machine; class Edge { public: Corner *start; Corner *end; /* orthogonal vector pointing uphill */ Vector3D uphill; LinearForm3D linearForm; /* corners that currently reference this edge in prevL or nextL */ IndirectLinkedHashSet<Corner *> currentCorners; Machine *machine; Edge(Corner *start, Corner *end, double angle); Edge(Corner *start, Corner *end); Edge(Point3D start, Point3D end, double angle); void calculateUphill(void); void calculateLinearForm(void); Vector3D direction(void); bool isCollisionNearHoriz(Edge *other); bool sameDirectedLine(Edge *nextL); double getAngle(void); Vector3D getPlaneNormal(void); void setAngle(double angle); bool operator==(const Edge &other) const; bool operator!=(const Edge &other) const; friend std::ostream & operator<<(std::ostream &strm, const Edge &e); static Tuple3D collide(Corner *a, double height); private: /* 0 is straight up, positive/-ve is inwards/outwards, absolute value * must be less than pi/2 */ double angle; }; size_t hash_value(const Edge &s); #endif
[ "tom@cornall.co" ]
tom@cornall.co
2fb96b6766aeff61ed57f4b3b09c3fe14f41df46
1831c3b7b80e2b0474c75b85a005e60df627b69c
/CodeChef/DSA Learning Series/Contest 1/CARVANS.cpp
c303c14463ac382a396f28f32a05126185d51fc0
[]
no_license
technodumb/Mission-Impossible
852a674bfe04c420938f3dc85f47fe914a7e5a55
1acfeb29b88c8c4633ba7ddc176780e058b28af3
refs/heads/main
2023-06-24T21:09:38.077833
2021-07-30T18:47:53
2021-07-30T18:47:53
369,279,946
1
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
#include<iostream> using namespace std; int main(){ ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); int t; cin>>t; while(t--){ long long int n, min, speed, nomax = 1; cin>>n; cin>>speed; min = speed; for(int i=0;i<n-1;i++){ cin>>speed; if(speed<=min){ min = speed; nomax++; } } cout<<nomax<<"\n"; } return 0; }
[ "alnaskabeer@gmail.com" ]
alnaskabeer@gmail.com
96363db02acfe62c3b375a577d0829a192c3e923
6d7f2381b8f1c5c0e0d96156ae36cac12be3017b
/atcoder/abc145/A/main.cpp
02a3930c695f2617d241d73140a8c10ff7098c50
[ "Unlicense" ]
permissive
Johniel/contests
708ccf944d6aeb0ef0404eec47e8ff7819ea00f0
15d465b08cac56e394509bcf8f24764e3dc6ca7d
refs/heads/master
2023-09-04T07:32:49.822786
2023-09-02T13:44:28
2023-09-02T13:44:50
48,701,889
0
0
null
2019-10-25T09:21:20
2015-12-28T16:38:38
C++
UTF-8
C++
false
false
1,131
cpp
// atcoder/abc145/A/main.cpp // author: @___Johniel // github: https://github.com/johniel/ #include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); int n; while (cin >> n) { cout << n * n << endl; } return 0; }
[ "johniel.s.m@gmail.com" ]
johniel.s.m@gmail.com
88656882aff67e60d4c4a055f7219d12e0f393c1
637f2006e0bbc8fe363f9780447dc3a7fb72d0b0
/Sandbox/src/Game/Commands/AttackCommand.h
a76bb82307dfabe674b038cf6e9a73b9dd9ad157
[ "Apache-2.0" ]
permissive
Benner727/SquareRPG
7bf2deb9fb97ccaac6b3e5391f3990e48f45c513
9333ff8417cf1bb74e215ab671554b9708551b64
refs/heads/master
2020-12-21T07:52:52.326340
2020-06-01T05:03:39
2020-06-01T05:03:39
236,363,059
0
0
Apache-2.0
2020-05-24T18:16:14
2020-01-26T19:19:36
C++
UTF-8
C++
false
false
583
h
#pragma once #include "ICommand.h" #include "Game/Actions/CombatAction.h" class AttackCommand : public ICommand { private: std::shared_ptr<Player> mPlayer; std::shared_ptr<Map> mMap; std::shared_ptr<MessageLog> mMessageLog; public: AttackCommand(std::shared_ptr<Player> player, std::shared_ptr<Map> map, std::shared_ptr<MessageLog> messageLog) { mPlayer = player; mMap = map; mMessageLog = messageLog; } ~AttackCommand() = default; bool CanExecute() { return true; } void Execute() { mPlayer->SetAction(new CombatAction(mPlayer, mMap, mMessageLog)); } };
[ "Benners727@gmail.com" ]
Benners727@gmail.com
dc20c9fee514019fef10e5ca434a4c4046dbefba
12aa23f58b840195f033f04cda660e403a903db6
/Joe_Task1/kinematics.h
5e10cd928688014ce7071743ab6854e9ce1b5b0f
[]
no_license
ashwindersk/Robotics_Systems
907177fa742b87845be7da4afefd032f0d399fb0
b92d8eef50b3994fc472c49cdb0aba8a1e9f469f
refs/heads/master
2022-06-26T05:20:04.192483
2019-12-18T14:48:58
2019-12-18T14:48:58
234,439,872
0
0
null
null
null
null
UTF-8
C++
false
false
2,514
h
#ifndef _Kinematics #define _Kinematics_h //You may want to use some/all of these variables const float WHEEL_DIAMETER = 70; const float WHEEL_RADIUS = 35; const float WHEEL_SEPERATION = 145; const float GEAR_RATIO = 120; const float COUNTS_PER_SHAFT_REVOLUTION = 12; const float COUNTS_PER_WHEEL_REVOLUTION = 1440; const float COUNTS_PER_MM = (COUNTS_PER_WHEEL_REVOLUTION / WHEEL_DIAMETER*M_PI); class Kinematics { public: Kinematics(); // Constructor, required. float update(long e_l, long e_r); // Write your method functions: // ... float TicksToDistance(long ticks); float GetAngleToHome(); float GetCurrentHeading(); bool IsHome(); void setDebug(bool state); private: // float TicksToDistance(long ticks); unsigned long old_encoder_count; long kin_last_count_el; long kin_last_count_er; float heading; float x_pos; float y_pos; float theta; float homex; float homey; bool debug; void printComponents(); //Private variables and methods go here }; // Required constructor. Initialise variables. Kinematics::Kinematics() { old_encoder_count = 0; theta = 0; x_pos = 0; y_pos = 0; homex = 0; homey = 0; } float Kinematics::update(long e_l, long e_r){ float lDist = (TicksToDistance(e_l - kin_last_count_el)); float rDist = (TicksToDistance(e_r - kin_last_count_er)); theta = theta + ((lDist - rDist)/WHEEL_SEPERATION) * (104.5/90.0); float average = (lDist + rDist) /2.0; x_pos = x_pos + average*cos(M_PI*(theta/180)); y_pos = y_pos + average*sin(M_PI*(theta/180)); if(debug) printComponents(); kin_last_count_el = e_l; kin_last_count_er = e_r; return theta; } void Kinematics::printComponents(){ Serial.print("x_pos:"); Serial.print(x_pos); Serial.print(",y_pos:"); Serial.print(y_pos); Serial.print(",theta:"); Serial.print(theta); Serial.print('\n'); } float Kinematics::TicksToDistance(long ticks){ if (ticks == 0) return 0; return (float)ticks/COUNTS_PER_MM * 1000; } /* float Kinematics::GetHomeHeading(){ float HomeAngle = GetAngleToHome(); return 0; } */ float Kinematics::GetAngleToHome(){ float dy = homey - y_pos; float dx = homex - x_pos; return (atan2(dy,dx) * (180.0 / M_PI)); } bool Kinematics::IsHome(){ float dy = x_pos - homex; float dx = y_pos - homey; if(abs(dx) < 100 && abs(dy) < 100) return true; else return false; } void Kinematics::setDebug(bool state){ debug = state; } #endif
[ "Joseph.Mills22@gmail.com" ]
Joseph.Mills22@gmail.com
8bb2c751f2143dbaa1b9f65c0171a27b2c971e39
c497cbaab5c9c20012c04afad174c3c3cb3160e0
/Astar.cpp
63094e5b4565a51863a596695b97fdea6ef6b389
[]
no_license
ChristianLloydSalon/Autonomous-Carrier-Robot
292ac8050a0e9346ce49a2f9ea68a51bb9135b90
503e052b4b1431b9636ace1bdec98eb0a978a536
refs/heads/master
2023-04-01T22:21:33.817957
2021-04-19T14:58:54
2021-04-19T14:58:54
359,487,227
1
0
null
null
null
null
UTF-8
C++
false
false
2,649
cpp
#include "Astar.h" Astar::Astar(int row, int col) { this->row = row; this->col = col; nodes = new Node*[col]; for (int i = 0; i < row; i++) { nodes[i] = new Node[row]; } ResetMap(); } bool Astar::FindPath(Vector vStart, Vector vEnd) { path.Clear(); start = &nodes[vStart.Y][vStart.X]; end = &nodes[vEnd.Y][vEnd.X]; start->hCost = getDistance(start, end); openList.Add(start); while (openList.Count > 0) { Node* node = openList[0]; for (int i = 1; i < openList.Count; i++) { if (openList[i]->fCost() < node->fCost() || openList[i]->fCost() == node->fCost()) { if (openList[i]->hCost < node->hCost) node = openList[i]; } } openList.Remove(node); closedList.Add(node); if (node == end) { openList.Clear(); closedList.Clear(); RetracePath(start, end); return true; } List neighbours = getNeigbours(node); for (int i = 0; i < neighbours.Count; i++) { if (!neighbours[i]->isWalkable || closedList.Contains(neighbours[i])) { continue; } double newCostToNeighbour = node->gCost + getDistance(node, neighbours[i]); if (newCostToNeighbour < neighbours[i]->gCost || !openList.Contains(neighbours[i])) { neighbours[i]->gCost = newCostToNeighbour; neighbours[i]->hCost = getDistance(neighbours[i], end); neighbours[i]->parent = node; if (!openList.Contains(neighbours[i])) { openList.Add(neighbours[i]); } } } neighbours.Clear(); } ResetMap(); return false; } void Astar::RetracePath(Node* s, Node* e) { Node* current = e; while (current != s) { path.Add(current); current = current->parent; } path.Add(s); path.Reverse(); } void Astar::ResetMap(void) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { nodes[i][j].isWalkable = true; nodes[i][j].coordinates.X = j; nodes[i][j].coordinates.Y = i; nodes[i][j].gCost = 0.0f; nodes[i][j].hCost = 0.0f; } } openList.Clear(); closedList.Clear(); path.Clear(); } List Astar::getNeigbours(Node *currentNode) { List neighbours; if (currentNode->coordinates.X - 1 >= 0) { neighbours.Add(&nodes[currentNode->coordinates.Y][currentNode->coordinates.X - 1]); } if (currentNode->coordinates.X + 1 < col) { neighbours.Add(&nodes[currentNode->coordinates.Y][currentNode->coordinates.X + 1]); } if (currentNode->coordinates.Y - 1 >= 0) { neighbours.Add(&nodes[currentNode->coordinates.Y - 1][currentNode->coordinates.X]); } if (currentNode->coordinates.Y + 1 < row) { neighbours.Add(&nodes[currentNode->coordinates.Y + 1][currentNode->coordinates.X]); } return neighbours; }
[ "christianlloydsalon396@gmail.com" ]
christianlloydsalon396@gmail.com
cdb33f197ca515ad277f71aedea008cf2d087d95
4be6611431e4ff6d53ad00df164646c7bce1c6b2
/codeforces/Educational Codeforces Round 110/C. Unstable String/main.cpp
2844eba20c61633562a523ed5f356df24361d047
[]
no_license
cheerconi/online-judge
98d0a8353cf80ade292cf8edfba3d02474a80b67
46cc0f35f2f66aac520557c511484393cf16888b
refs/heads/master
2022-09-22T13:24:38.477277
2022-09-18T12:26:53
2022-09-18T12:26:53
97,737,698
3
0
null
null
null
null
UTF-8
C++
false
false
2,080
cpp
#include <algorithm> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <ctime> #include <deque> #include <iostream> #include <list> #include <map> #include <memory.h> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; typedef long double LD; typedef long long LL; typedef pair<LL, LL> pll; typedef pair<int, int> pii; typedef vector<int> vi; #ifdef LOCAL #define DEBUG(x) { cerr << "# " << #x << ": " << x << endl;} #else #define DEBUG(x) #endif mt19937_64 mt(time(0)); /*---------------------------------------------------------------------------------------------------             ∧_∧       ∧_∧  (´<_` )  Welcome to My Coding Space!      ( ´_ゝ`) /  ⌒i     /   \    | |     /   / ̄ ̄ ̄ ̄/  |   __(__ニつ/  _/ .| .|____      \/____/ (u ⊃ ---------------------------------------------------------------------------------------------------*/ const int MAXN = 2e5 + 10; LL dp[2][MAXN]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.precision(10); cout << fixed; #ifdef LOCAL freopen("../test.txt", "r", stdin); // freopen("../output.txt", "w", stdout); #endif int T; cin >> T; while (T--) { string s; cin >> s; int n = s.size(); memset(dp, 0, sizeof(dp)); LL ret = 0; for (int i = 0; i < n; i++) { if (s[i] != '1') { dp[0][i] = dp[1][i-1]+1; } if (s[i] != '0') { dp[1][i] = dp[0][i-1] + 1; } ret += max(dp[0][i], dp[1][i]); } cout << ret << '\n'; } /*---------------------------------------Coding Space End------------------------------------------*/ #ifdef LOCAL cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s." << endl; #endif return 0; } /* author: txingml */ /* picture is from hamayanhamayan(CF handle) */
[ "carltianxing@didiglobal.com" ]
carltianxing@didiglobal.com
12e96a8b08d490fc4cad27ac5da12476c5491530
1af49694004c6fbc31deada5618dae37255ce978
/mojo/core/platform_handle_in_transit.h
ecf571bc7a1c017ec4595c23f902bd6628c9f581
[ "BSD-3-Clause" ]
permissive
sadrulhc/chromium
59682b173a00269ed036eee5ebfa317ba3a770cc
a4b950c23db47a0fdd63549cccf9ac8acd8e2c41
refs/heads/master
2023-02-02T07:59:20.295144
2020-12-01T21:32:32
2020-12-01T21:32:32
317,678,056
3
0
BSD-3-Clause
2020-12-01T21:56:26
2020-12-01T21:56:25
null
UTF-8
C++
false
false
4,160
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MOJO_CORE_PLATFORM_HANDLE_IN_TRANSIT_H_ #define MOJO_CORE_PLATFORM_HANDLE_IN_TRANSIT_H_ #include "base/macros.h" #include "base/process/process.h" #include "build/build_config.h" #include "mojo/public/cpp/platform/platform_handle.h" #if defined(OS_WIN) #include <windows.h> #endif namespace mojo { namespace core { // Owns a PlatformHandle which may actually belong to another process. On // Windows and (sometimes) Mac, handles in a message object may take on values // which only have meaning in the context of a remote process. // // This class provides a safe way of scoping the lifetime of such handles so // that they don't leak when transmission can't be completed. class PlatformHandleInTransit { public: PlatformHandleInTransit(); explicit PlatformHandleInTransit(PlatformHandle handle); PlatformHandleInTransit(PlatformHandleInTransit&&); ~PlatformHandleInTransit(); PlatformHandleInTransit& operator=(PlatformHandleInTransit&&); // Accessor for the owned handle. Must be owned by the calling process. const PlatformHandle& handle() const { DCHECK(!owning_process_.IsValid()); return handle_; } // Returns the process which owns this handle. If this is invalid, the handle // is owned by the current process. const base::Process& owning_process() const { return owning_process_; } // Takes ownership of the held handle as-is. The handle must belong to the // current process. PlatformHandle TakeHandle(); // Discards the handle owned by this object. The implication is that its // value has been successfully communicated to the owning process and the // calling process is no longer responsible for managing the handle's // lifetime. void CompleteTransit(); // Transfers ownership of this (local) handle to |target_process|. bool TransferToProcess(base::Process target_process); #if defined(OS_WIN) HANDLE remote_handle() const { return remote_handle_; } // Indicates whether |handle| is a known pseudo handle value. In a fuzzing // environment we merely simulate IPC, so we end up accepting "remote" handle // values from our own process. This means that unlike in production // scenarios, we may end up successfully calling DuplicateHandle on a fuzzed // pseudo handle value (in production if a remote process sent us a pseudo // handle value, DuplicateHandle would always fail). // // For some reason, a small number of special pseudo handle values always // duplicate to the same real handle value when DUPLICATE_CLOSE_SOURCE is // specified, presumably because the returned handle is closed before it's // even returned. For example, duplicating -10 with DUPLICATE_CLOSE_SOURCE // always yields the handle value 0x50. This ends up interacting poorly with // the rest of Mojo's handle deserialization code and eventually crashes // in ScopedHandleVerifier. // // We avoid the issue by explicitly discarding any known pseudo handle values, // since they are always invalid when received from a remote process anyway // and thus always signal a misbehaving client. static bool IsPseudoHandle(HANDLE handle); // Returns a new local handle, with ownership of |handle| being transferred // from |owning_process| to the caller. static PlatformHandle TakeIncomingRemoteHandle( HANDLE handle, base::ProcessHandle owning_process); #endif private: #if defined(OS_WIN) // We don't use a ScopedHandle (or, by extension, PlatformHandle) here because // the handle verifier expects all handle values to be owned by this process. // On Windows we use |handle_| for locally owned handles and |remote_handle_| // otherwise. On all other platforms we use |handle_| regardless of ownership. HANDLE remote_handle_ = INVALID_HANDLE_VALUE; #endif PlatformHandle handle_; base::Process owning_process_; DISALLOW_COPY_AND_ASSIGN(PlatformHandleInTransit); }; } // namespace core } // namespace mojo #endif // MOJO_CORE_PLATFORM_HANDLE_IN_TRANSIT_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
9d1e7c424264161b64c2c3016acf3966ee1dfa00
310ad9c9e34d258fe6192f6c954a0cff60e577ef
/チーム制作シューティング/チーム制作シューティング/Source.cpp
8855884ee4ddd16f13b3cc3a4870f3b2f15fa6ef
[]
no_license
HumanAcademy/2018-07-Murata
5d472c7e5ab8f8be1d73a95048e50a551cd68627
3dfeec20e1e5b16b870a65d902c93d60f59db4cd
refs/heads/master
2020-04-01T06:30:32.994182
2018-09-10T13:58:49
2018-09-10T14:01:02
152,951,064
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
21,567
cpp
#include <string> #include "XLibrary11.hpp" using namespace XLibrary; enum Mode { Title, Game, Gameover, Gameclear, }; //ランダムな座標を取得する Float3 GetRandomPosition() { float range = rand() / (float)RAND_MAX * Window::GetSize().x + 500.0f; float radian = rand() / (float)RAND_MAX* XM_PI * 2.0f; return Float3( cosf(radian) * range, sinf(radian) * range, 0.0f ); } bool IsHit( Float3 position1, Float3 position2, float range ) { if ( position1.x - range < position2.x && position1.x + range > position2.x && position1.y - range < position2.y && position1.y + range > position2.y) { //あたった return true; } //あたってない return false; } int MAIN() { Window::SetSize(1000, 600); Mode mode = Title; //最初はタイトル画面にする Camera camera; camera.color = Float4(0.0f, 0.0f, 0.0f, 1.0f); Sprite Chest[3]; //宝の画像 bool bossmuki = false;//false下 ture 上 Chest[0].Load(L"宝1.png"); Chest[1].Load(L"宝2.png"); Chest[2].Load(L"宝3.png"); for (int i = 0; i < 3; i++) { Chest[i].scale = 0.08f; } Sprite back[9]; for (int i = 0; i < 9; i++) { back[i].Load(L"背景.png"); } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { back[i + j * 3].position = Float2(-1000.0f + (i * 1000.0f), -600.0f + (j * 600.0f)); } } Sprite HP[3]; HP[0].Load(L"HP1.png"); HP[1].Load(L"HP2.png"); HP[2].Load(L"HP3.png"); for (int i = 0; i < 3; i++) { HP[i].scale = 0.5f; HP[i].SetPivot(Float2(-0.883333f, 0.0f)); } //true = まだ宝をとっていない false = もう宝をとっている bool ChestFlag[3] = {}; Sprite TITLE(L"タイトル画面.png"); TITLE.scale = Float2(0.90f, 0.90f); TITLE.position.y = -25.0f; Sprite gameover(L"gameover.png"); Sprite gameclear(L"gameclear.png"); //宝箱の矢印の画像 Sprite map[3]; map[0].Load(L"矢印0.png"); map[1].Load(L"矢印1.png"); map[2].Load(L"矢印2.png"); for (int i = 0; i < 3; i++) { map[i].scale = 0.1f; } int count = 0; float playerSpeed = 3.5f; //自機の速さ bool PlayerSpeed = false; Sprite player(L"player.png"); //自機の画像 player.scale = 0.1f; player.SetPivot(Float2(0.0f, 0.25f)); Sprite hidan(L"被弾.png"); hidan.scale = 0.1f; const int enemyNum = 150; // 敵の数 const float enemySpeed = 1.0f; //敵の速さ int enemylife[enemyNum] = { 3 }; //敵のライフ bool ENEMY[enemyNum] = { false };//敵の生死 false = 生 true = 死 Sprite enemy(L"enemy.png"); //敵の画像 enemy.scale = 0.1f; //ランダムなスピード float randspeed = 1.0f; //永遠に増える数 int j = 0; Float3 enemyPosition[enemyNum]; //敵の座標 //宝箱のスコア const float Score = 50.0f; const int bulletNum = 10; //弾の数 const float bulletSpeed = 10.0f; //弾の速さ int bulletIndex = 0; //次に発射する弾の番号 //弾の角度 Float3 BulletRadian[bulletNum]; Sprite bullet(L"弾2.png"); //弾の画像 bullet.scale = 0.03f; Float3 bulletPosition[bulletNum]; // 弾の座標 //次に発射するまでのカウント int bulletInterval = 0; int Rand = 0; int Randtime = 0; int playerangle = 0;//プレイヤーの向き 0 = 上 1 = 右 2 = 下 3 = 左 bool playerAngle = false; //プレイヤーの向き2 false 左  true 右 int playerlife = 0;//プレイヤーのHp int lifetime = 0;//プレイヤーの無敵時間 bool Life = false;//無敵かどうかfalse = 通常時 true = 無敵 float bossRadian = 0.0f; bool Flag = false; Sprite lifeSprite[3]; for (int i = 0; i < 3; i++) { lifeSprite[i].Load(L"player.png"); lifeSprite[i].angles.z = 90.0f; lifeSprite[i].scale = 0.08f; } int score = 0; //スコア int enemyscore = 0; //スコア Sprite boss(L"ボス.png"); boss.scale = 0.5f; Sprite bossposition(L"被弾.png"); bossposition.scale = 3.0f; int bosstime = 0; bool BOSS = false;//true = ボスがいる false = ボスがいない const int bossbulletNum = 200; //弾の数 const float bossbulletSpeed = 1.7f; //弾の速さ int bossbulletIndex = 0; //次に発射する弾の番号 //弾の角度 float bossBulletRadian[bossbulletNum]; Sprite bossbullet(L"弾1.png"); //弾の画像 bossbullet.scale = 0.05f; Float3 bossbulletPosition[bossbulletNum]; // 弾の座標 //次に発射するまでのカウント int bossbulletInterval = 0; int bosslife = 0; int maxlife = 0; while (Refresh()) { camera.Update(); Rand = rand(); j++; if (j == 15) { randspeed = (float)(Rand % 4 + 5) / 4; j = 0; Randtime = Rand; } switch (mode) { case Title: //ゲーム開始 camera.position = 0.0; TITLE.Draw(); playerangle = 1; playerAngle = true; bossmuki = false; player.position = 0.0; enemyscore = 0; score = 0; playerlife = 3; lifetime = 0; Life = false; bosstime = 0; PlayerSpeed = false; boss.position = Float3(0.0f, 1500.0f, 0.0f); //敵の座標の初期化 for (int i = 0; i < enemyNum; i++) { enemyPosition[i] = GetRandomPosition(); enemylife[i] = 2; ENEMY[i] = false; } //宝フラグの初期化 for (int i = 0; i < 3; i++) { ChestFlag[i] = false; } //弾の座標を初期化 for (int i = 0; i < bulletNum; i++) { //はるか彼方に飛ばす bulletPosition[i].x = 99999.0f; BulletRadian[i] = 0.0; } //弾の座標を初期化 for (int i = 0; i < bossbulletNum; i++) { //はるか彼方に飛ばす bossbulletPosition[i].x = 99999.0f; bossBulletRadian[i] = 0.0; } for (int i = 0; i < 3; i++) { map[i].position = Float2(0.0f, 0.0f); } if (Input::GetKeyDown(VK_SPACE)) { mode = Game; bosslife = 100; maxlife = bosslife; BOSS = false; } if (Input::GetKey('0') && Input::GetKey('1')) { mode = Game; bosslife = 300; maxlife = bosslife; BOSS = true; } break; case Game: if (!PlayerSpeed) { playerSpeed = 3.5f; } else { playerSpeed = 2.85f; } for (int i = 0; i < 9; i++) { back[i].Draw(); } for (int i = 0; i < 3; i++) { lifeSprite[i].position = Float2(camera.position.x + 450.0f - (i * 70), camera.position.y + 250.0f); if ((i + 1) * 40 == enemyscore && !ChestFlag[i]) { Chest[i].position = Float2(Rand * rand() % 3000 - 1499, Rand * rand() % 1800 - 899); ChestFlag[i] = true; } } for (int i = 0; i < 3; i++) { HP[i].position = Float2(camera.position.x - 300.0f, camera.position.y + 250.0f); } if (!Life) { hidan.position.x = player.position.x; hidan.position.y = player.position.y; } else if (lifetime < 60) { hidan.Draw(); } //宝箱との当たり判定 for (int i = 0; i < 3; i++) { if (enemyscore >= Score * (i + 1)) { if (ChestFlag[i] == true) { if (Chest[i].position.x >= player.position.x && Chest[i].position.y - player.position.y >= Chest[i].position.x - player.position.x) { //北北東に宝がある時 map[i].position = Float2(player.position.x + 50.0f, player.position.y + 42.0f); map[i].angles.z = -22.5; } else if (Chest[i].position.x >= player.position.x && Chest[i].position.y - player.position.y <= Chest[i].position.x - player.position.x&& player.position.y < Chest[i].position.y) { //東北東に宝がある時 map[i].position = Float2(player.position.x + 75.0f, player.position.y + 22.0f); map[i].angles.z = -67.5; } else if (Chest[i].position.x >= player.position.x && Chest[i].position.y - player.position.y >= -Chest[i].position.x - -player.position.x && player.position.y >= Chest[i].position.y) { //東南東に宝があるとき map[i].position = Float2(player.position.x + 75.0f, player.position.y + -22.0f); map[i].angles.z = -112.5; } else if (Chest[i].position.x >= player.position.x && Chest[i].position.y - player.position.y <= -Chest[i].position.x - -player.position.x&& player.position.y >= Chest[i].position.y) { //南南東に宝があるとき map[i].position = Float2(player.position.x + 50.0f, player.position.y + -42.0f); map[i].angles.z = -157.5; } else if (Chest[i].position.x <= player.position.x && Chest[i].position.y - player.position.y <= Chest[i].position.x - player.position.x && player.position.y >= Chest[i].position.y) { //南南西に宝があるとき map[i].position = Float2(player.position.x + -50.0f, player.position.y + -42.0f); map[i].angles.z = -202.5; } else if (Chest[i].position.x <= player.position.x && player.position.y >= Chest[i].position.y >= Chest[i].position.x - player.position.x && player.position.y >= Chest[i].position.y) { //西南西に宝があるとき map[i].position = Float2(player.position.x + -75.0f, player.position.y + -2.0f); map[i].angles.z = -247.5; } else if (Chest[i].position.x <= player.position.x && Chest[i].position.y - player.position.y <= -Chest[i].position.x - -player.position.x&& player.position.y <= Chest[i].position.y) { //西北西に宝があるとき map[i].position = Float2(player.position.x + -75.0f, player.position.y + 22.0f); map[i].angles.z = -292.5; } else if (Chest[i].position.x <= player.position.x && Chest[i].position.y - player.position.y >= -Chest[i].position.x - -player.position.x&& player.position.y <= Chest[i].position.y) { //北北西に宝があるとき map[i].position = Float2(player.position.x + -50.0f, player.position.y + 42.0f); map[i].angles.z = -337.5; } map[i].Draw(); } float hitRange = Chest[i].GetSize().x / 1.5f * Chest[i].scale.x; if (IsHit(Chest[i].position, player.position, hitRange ) && ChestFlag[i]) { score++; ChestFlag[i] = false; } if (!ChestFlag[i]) { Chest[i].position = Float2(camera.position.x + 450.0f - (i * 70), camera.position.y + 180.0f); } } } for (int i = 0; i < 3; i++) { if ((i + 1) * Score <= enemyscore) { Chest[i].Draw(); } } if (score >= 3) { BOSS = true; } if (BOSS) { //ボスのHPの表示 for (int i = 0; i < 3; i++) { HP[i].Draw(); } boss.Draw(); if (HP[1].scale.x != bosslife * 0.5 && bosslife >= 0 && maxlife == 100 || HP[1].scale.x != bosslife * 0.5f / 3 && bosslife >= 0 && maxlife == 300) { HP[1].scale.x = (float)bosslife / maxlife * 0.5; } bossposition.position = Float3(boss.position.x, boss.position.y, 0.0f); bossposition.angles.z -= rand() % 50; if (bossmuki == false) { boss.position.y -= 1.5f; } else { boss.position.y += 1.5f; } if (boss.position.y == 300) { bossmuki = false; } if (boss.position.y == -300) { bossmuki = true; } //雑魚敵を飛ばす for (int i = 55; i < enemyNum - 55; i++) { if (i <= 55 || i >= 145) { ENEMY[i] = true; enemyPosition[i] = Float3(10000000.0f, 0.0f, 0.0f); } } bossbulletInterval++; if (bossbulletInterval > 4 || bossbulletInterval > 2 && maxlife == 300) { bossbulletInterval = 0; //弾をプレイヤーの座標と角度に合わせる bossbulletPosition[bossbulletIndex] = boss.position; if (bossbulletIndex % 2 == 0) { bossRadian = bossposition.angles.z / 180.0f * XM_PI; } else { bossRadian = (bossposition.angles.z + 180.0f) / 180.0f * XM_PI; } bossBulletRadian[bossbulletIndex] = bossRadian; bossbulletIndex++; if (bossbulletIndex >= bossbulletNum) { bossbulletIndex = 0; } } for (int i = 0; i < bossbulletNum; i++) { //弾の移動 bossbulletPosition[i] += Float3( cosf(bossBulletRadian[i]), sinf(bossBulletRadian[i]), 0.0 ) * bossbulletSpeed * 2; bossbullet.position = bossbulletPosition[i]; //弾の描画 bossbullet.Draw(); } if (bosslife <= 0) { bossposition.Draw(); bosstime++; for (int i = 0; i < bossbulletNum; i++) { //弾の移動 bossbulletPosition[i] = Float3(100000.0f, 0.0f, 0.0f ); } for (int i = 0; i < enemyNum; i++) { ENEMY[i] = true; enemyPosition[i] = Float3(10000000.0f, 0.0f, 0.0f); } if (bosstime >= 90) { mode = Gameclear; } } } //自機の移動の処理 if (lifetime > 50 || lifetime == 0) { if (Input::GetKey('D') || Input::GetKey(VK_RIGHT)) { if (player.position.x < 1495) { player.position.x += playerSpeed; } if (!Input::GetKey('A') && !Input::GetKey(VK_LEFT)) { if (!Input::GetKey(VK_SPACE)) { playerangle = 1; playerAngle = true; } } if (Input::GetKey('W') || Input::GetKey(VK_UP) || Input::GetKey('S') || Input::GetKey(VK_DOWN)) { PlayerSpeed = true; } else { PlayerSpeed = false; } } if (Input::GetKey('A') || Input::GetKey(VK_LEFT)) { if (player.position.x > -1495) { player.position.x -= playerSpeed; } if (!Input::GetKey('D') && !Input::GetKey(VK_RIGHT)) { if (!Input::GetKey(VK_SPACE)) { playerangle = 3; playerAngle = false; } } if (Input::GetKey('W') || Input::GetKey(VK_UP) || Input::GetKey('S') || Input::GetKey(VK_DOWN)) { PlayerSpeed = true; } else { PlayerSpeed = false; } } if (Input::GetKey('W') || Input::GetKey(VK_UP)) { if (player.position.y < 895) { player.position.y += playerSpeed; } if (!Input::GetKey('D') && !Input::GetKey(VK_RIGHT) && !Input::GetKey('A') && !Input::GetKey(VK_LEFT) && !Input::GetKey('S') && !Input::GetKey(VK_DOWN)) { PlayerSpeed = false; if (!Input::GetKey(VK_SPACE)) { playerangle = 2; } } } if (Input::GetKey('S') || Input::GetKey(VK_DOWN)) { if (player.position.y > -895) { player.position.y -= playerSpeed; } if (!Input::GetKey('D') && !Input::GetKey(VK_RIGHT) && !Input::GetKey('A') && !Input::GetKey(VK_LEFT) && !Input::GetKey('W') && !Input::GetKey(VK_UP)) { PlayerSpeed = false; if (!Input::GetKey(VK_SPACE)) { playerangle = 0; } } } } if (playerAngle) { player.angles.x = 180; } else { player.angles.x = 0; } if (playerangle == 1) { player.angles.z = 90; } if (playerangle == 0) { if (playerAngle) { player.angles.z = 0; } else { player.angles.z = 180; } } if (playerangle == 3) { player.angles.z = 90; } if (playerangle == 2) { if (playerAngle) { player.angles.z = 180; } else { player.angles.z = 0; } } //自機の描画 if (!Life || lifetime >= 60 && lifetime <= 70 || lifetime >= 80 && lifetime <= 90 || lifetime >= 100 && lifetime <= 110) { player.Draw(); } for (int i = 0; i < 3; i++) { if (playerlife - i - 1 >= 0) { lifeSprite[playerlife - i - 1].Draw(); } } //カメラを自機に追従させる if (player.position.x < 1000 && player.position.x > -1000) { camera.position.x = player.position.x; } if (player.position.y < 600 && player.position.y > -600) { camera.position.y = player.position.y; } bulletInterval++; if (bulletInterval > 10) { bulletInterval = 0; //弾をプレイヤーの座標と角度に合わせる bulletPosition[bulletIndex] = player.position; if (playerangle == 0) { BulletRadian[bulletIndex] = Float3(0.0f, -1.0f, 0.0f); } if (playerangle == 1) { BulletRadian[bulletIndex] = Float3(1.0f, 0.0f, 0.0f); } if (playerangle == 2) { BulletRadian[bulletIndex] = Float3(0.0f, 1.0f, 0.0f); } if (playerangle == 3) { BulletRadian[bulletIndex] = Float3(-1.0f, 0.0f, 0.0f); } bulletIndex++; if (bulletIndex >= bulletNum) bulletIndex = 0; } for (int i = 0; i < enemyNum; i++) { float enemyRadian = atan2f( player.position.y - enemyPosition[i].y, player.position.x - enemyPosition[i].x ); //もし画面外にいれば湧きなおす if (enemyPosition[i].x >= 1505 && ENEMY[i] == false || enemyPosition[i].x <= -1505 && ENEMY[i] == false || enemyPosition[i].y >= 905 && ENEMY[i] == false || enemyPosition[i].y <= -905 && ENEMY[i] == false) { //画面外に湧かせる while (count != 1) { Flag = false; enemyPosition[i] = Float3(Rand % 4000 - 2000.0f, rand() % 2700 - 1350.0f, 0.0f); for (int g = 0; g < count + 1; g++)//1 { if (enemyPosition[i].x <= camera.position.x + (Window::GetSize().x / 2) + 600.0f&& enemyPosition[i].x >= camera.position.x - (Window::GetSize().x / 2) - 600.0f && enemyPosition[i].y <= camera.position.y + (Window::GetSize().y / 2) + 450.0f && enemyPosition[i].y >= camera.position.y - (Window::GetSize().y / 2) - 450.0f) { Flag = true; break; } g = 0; } if (!Flag) { count++; } } count = 0; } //敵を動かす処理 if (i <= 0) { enemyPosition[i] += Float3( cosf(enemyRadian), sinf(enemyRadian), 0.0 ) * enemySpeed; } else if (i <= 135) { if (enemyPosition[i].x <= player.position.x + (Window::GetSize().x / 4) && enemyPosition[i].x >= player.position.x - (Window::GetSize().x / 4) && enemyPosition[i].y <= player.position.y + (Window::GetSize().y / 4) && enemyPosition[i].y >= player.position.y - (Window::GetSize().y / 4)) { enemyPosition[i] += Float3( cosf(enemyRadian), sinf(enemyRadian), 0.0 ) * 1.5f; } else { enemyPosition[i] += Float3( cosf(Randtime / i), sinf(Randtime / i), 0.0 ) * enemySpeed * 2.0f; } } else if (i <= 140) { enemyPosition[i] += Float3( cosf(enemyRadian), sinf(enemyRadian), 0.0 ) * randspeed * ((i % 4 + 1) / 4.0f); } else { enemyPosition[i] += Float3( cosf(enemyRadian), sinf(enemyRadian), 0.0 ) * 1.5f; } enemy.position = enemyPosition[i]; float hitRange = 20.0f; //弾と当たり判定 for (int j = 0; j < bulletNum; j++) { if (IsHit(boss.position, bulletPosition[j], 125.0f ) && BOSS) { bulletPosition[j] = Float2(10000.0f, 0.0f); bosslife--; } if (IsHit(enemyPosition[i], bulletPosition[j], hitRange )) { if (enemylife[i] > 0) { enemylife[i]--; //画面外に湧かせる while (count != 1) { Flag = false; enemyPosition[i] = Float3(Rand % 3000 - 1500.0f, rand() % 1800 - 900.0f, 0.0f); for (int g = 0; g < count + 1; g++)//1 { if (enemyPosition[i].x <= camera.position.x + 500.0f + 600.0f&& enemyPosition[i].x >= camera.position.x - 500.0f - 600.0f && enemyPosition[i].y <= camera.position.y + 300.0f + 450.0f && enemyPosition[i].y >= camera.position.y - 300.0f - 450.0f) { Flag = true; break; } g = 0; } if (!Flag) { count++; } } } else { ENEMY[i] = true; enemyPosition[i] = Float3(10000000.0f, 0.0f, 0.0f); } bulletPosition[j] = Float2(10000.0f, 0.0f); count = 0; enemyscore++; } } //自機との当たり判定 if (IsHit( enemyPosition[i], player.position, hitRange ) && !Life) { playerlife--; Life = true; } //敵を描画 enemy.Draw(); } if (IsHit(boss.position, player.position, 125.0f ) && BOSS && !Life) { playerlife--; Life = true; } for (int i = 0; i < bossbulletNum; i++) { float hitRange = player.GetSize().x / 3.5f * player.scale.x; enemy.scale.x; if (IsHit(player.position, bossbulletPosition[i], hitRange ) && !Life) { playerlife--; Life = true; } } //無敵時間の処理 if (Life) { lifetime++; if (lifetime >= 120) { lifetime = 0; Life = false; } } if (playerlife <= 0 && lifetime >= 60) { camera.position = 0.0; mode = Gameover; } for (int i = 0; i < bulletNum; i++) { //弾の移動 bulletPosition[i] += Float3(BulletRadian[i].x, BulletRadian[i].y, 0.0f) * bulletSpeed; bullet.position = bulletPosition[i]; //弾の描画 bullet.Draw(); } break; case Gameover: camera.position = 0.0; gameover.Draw(); if (Input::GetKeyDown(VK_SPACE)) { mode = Title; } break; case Gameclear: camera.position = 0.0; gameclear.Draw(); if (Input::GetKeyDown(VK_SPACE)) { mode = Title; } break; } } return 0; }
[ "xxvraqwa@gmail.com" ]
xxvraqwa@gmail.com
4c206674bc4a48d521fd2a1333390f7987eb4855
caf0494d1837a190244729ac322f0104779e0750
/microcontroller/lpc4088/xbee/src/main.cpp
f46c9b45768f258b322bf7e08bbd7af50fce9896
[ "MIT" ]
permissive
DavidKendall/iot
d0e42d41e8dc4a31c78a2a2fc43bb687289f86ec
444210da7796b8230422de778d288452a52f9794
refs/heads/master
2021-01-10T18:04:31.843303
2017-02-28T19:24:26
2017-02-28T19:24:26
52,284,478
0
1
null
null
null
null
UTF-8
C++
false
false
9,529
cpp
/* * Simple program to turn the LPC4088QSB into * a node that can be monitored and controlled * remotely * * DK - 12-03-2016 */ #include <mbed.h> #include <MMA7455.h> #include <LM75B.h> #include <display.h> #include <ucos_ii.h> #include <string.h> #include "xb.h" /* ********************************************************************************************************* * NODE IDENTIFIER and DESCRIPTION ********************************************************************************************************* */ char const * const NODE_ID = "SN01"; char const * const NODE_DESCRIPTION = "Corbyn House"; /* ********************************************************************************************************* * APPLICATION TASK PRIORITIES ********************************************************************************************************* */ enum { APP_TASK_COMMAND_PRIO = 4, APP_TASK_LEDS_PRIO, APP_TASK_UART_WRITE_PRIO, APP_TASK_MONITOR_PRIO, APP_TASK_UART_READ_PRIO }; /* ********************************************************************************************************* * APPLICATION TASK STACKS ********************************************************************************************************* */ #define APP_TASK_COMMAND_STK_SIZE 128 #define APP_TASK_LEDS_STK_SIZE 256 #define APP_TASK_UART_WRITE_STK_SIZE 384 #define APP_TASK_MONITOR_STK_SIZE 512 #define APP_TASK_UART_READ_STK_SIZE 128 static OS_STK appTaskCommandStk[APP_TASK_COMMAND_STK_SIZE]; static OS_STK appTaskLedsStk[APP_TASK_LEDS_STK_SIZE]; static OS_STK appTaskUARTWriteStk[APP_TASK_UART_WRITE_STK_SIZE]; static OS_STK appTaskMonitorStk[APP_TASK_MONITOR_STK_SIZE]; static OS_STK appTaskUARTReadStk[APP_TASK_UART_READ_STK_SIZE]; /* ********************************************************************************************************* * GLOBAL VARIABLES ********************************************************************************************************* */ typedef struct { int32_t ax; int32_t ay; int32_t az; int32_t pt; int32_t js; float tm; } nodeData_t; static nodeData_t nodeData; static OS_EVENT *dataSem; static xbeeBuffer_t packetBuf; static OS_EVENT *packetSem; static bool led1Flashing = true; static bool led2Flashing = true; static bool led3Flashing = true; static bool led4Flashing = true; static char testMessage[61]; static Display *d = Display::theDisplay(); static Xb xbee(P4_22, P4_23); /* ********************************************************************************************************* * APPLICATION FUNCTION PROTOTYPES ********************************************************************************************************* */ static void appTaskCommand(void *pdata); static void appTaskLeds(void *pdata); static void appTaskUARTWrite(void *pdata); static void appTaskMonitor(void *pdata); static void appTaskUARTRead(void *pdata); /* ********************************************************************************************************* * LOCAL FUNCTION PROTOTYPES ********************************************************************************************************* */ void payloadData(char *payload, nodeData_t nodeData); void payloadPublish(char *payload, char const *description); /* ********************************************************************************************************* * GLOBAL FUNCTION DEFINITIONS ********************************************************************************************************* */ int main() { /* Initialise the display */ d->fillScreen(WHITE); d->setTextColor(BLACK, WHITE); /* ...and the network */ xbee.xbeeNodeDiscovery(); /* Initialise the OS */ OSInit(); /* Create the tasks */ OSTaskCreate(appTaskCommand, (void *)0, (OS_STK *)&appTaskCommandStk[APP_TASK_COMMAND_STK_SIZE - 1], APP_TASK_COMMAND_PRIO); OSTaskCreate(appTaskLeds, (void *)0, (OS_STK *)&appTaskLedsStk[APP_TASK_LEDS_STK_SIZE - 1], APP_TASK_LEDS_PRIO); OSTaskCreate(appTaskUARTWrite, (void *)0, (OS_STK *)&appTaskUARTWriteStk[APP_TASK_UART_WRITE_STK_SIZE - 1], APP_TASK_UART_WRITE_PRIO); OSTaskCreate(appTaskMonitor, (void *)0, (OS_STK *)&appTaskMonitorStk[APP_TASK_MONITOR_STK_SIZE - 1], APP_TASK_MONITOR_PRIO); OSTaskCreate(appTaskUARTRead, (void *)0, (OS_STK *)&appTaskUARTReadStk[APP_TASK_UART_READ_STK_SIZE - 1], APP_TASK_UART_READ_PRIO); dataSem = OSSemCreate(0); packetSem = OSSemCreate(0); /* Start the OS */ OSStart(); /* Should never arrive here */ return 0; } /* ********************************************************************************************************* * APPLICATION TASK DEFINITIONS ********************************************************************************************************* */ static void appTaskCommand(void *pdata) { uint8_t osStatus; char command[72]; uint32_t commandLen; uint32_t i; uint32_t j; /* Start the OS ticker -- must be done in the highest priority task */ SysTick_Config(SystemCoreClock / OS_TICKS_PER_SEC); while ( true ) { OSSemPend(packetSem, 0, &osStatus); commandLen = xbee.xbeeNetstring(packetBuf, command); switch (command[0]) { case '1': { led1Flashing = !led1Flashing; break; } case '2': { led2Flashing = !led2Flashing; break; } case '3': { led3Flashing = !led3Flashing; break; } case '4': { led4Flashing = !led4Flashing; break; } case '5': { break; } case '6': { memset(testMessage, ' ', 60); testMessage[60] = '\0'; for (i = 1, j = 0; j < commandLen - 1; i += 1, j += 1) { testMessage[j] = command[i]; } d->setCursor(2,22); d->printf("%s", testMessage); break; } case 'R': { d->fillScreen(RED); break; } case 'G': { d->fillScreen(GREEN); break; } case 'B': { d->fillScreen(BLUE); break; } case 'W': { d->fillScreen(WHITE); break; } default: { break; } } } } static void appTaskLeds(void *pdata) { DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); DigitalOut led4(LED4); /* Task main loop */ while (true) { if (led1Flashing) { led1 = !led1; } if (led2Flashing) { led2 = !led2; } if (led3Flashing) { led3 = !led3; } if (led4Flashing) { led4 = !led4; } OSTimeDlyHMSM(0,0,0,500); } } static void appTaskUARTWrite(void *pdata) { uint8_t osStatus; static xbeeBuffer_t packet; char payload[256]; uint32_t packetLen; payloadPublish(payload, NODE_DESCRIPTION); packetLen = xbee.xbeeMkPacketFromString(packet, payload); xbee.xbeeTxPacket(packet, packetLen); while ( true ) { OSSemPend(dataSem, 0, &osStatus); payloadData(payload, nodeData); packetLen = xbee.xbeeMkPacketFromString(packet, payload); xbee.xbeeTxPacket(packet, packetLen); } } static void appTaskMonitor(void *pdata) { MMA7455 acc(P0_27, P0_28); AnalogIn pot(p15); LM75B lm75B(P0_27, P0_28, LM75B::ADDRESS_1); d->setCursor(2,2); if (!acc.setMode(MMA7455::ModeMeasurement)) { d->printf("Unable to set mode for MMA7455!\n"); } else { if (!acc.calibrate()) { d->printf("Failed to calibrate MMA7455!\n"); } else { d->printf("MMA7455 initialised\n"); } } lm75B.open(); while ( true ) { acc.read(nodeData.ax, nodeData.ay, nodeData.az); nodeData.pt = (int32_t)((1.0F - pot.read()) * 100); nodeData.js = 0; nodeData.tm = lm75B.temp(); (void)OSSemPost(dataSem); OSTimeDly(200); } } static void appTaskUARTRead(void *pdata) { /* MUST be the lowest priority task */ while ( true ) { xbee.xbeeReceivePacket(packetBuf); (void)OSSemPost(packetSem); } } void payloadData(char *payload, nodeData_t nodeData) { sprintf(payload, "type:DATA,id:%s,ax:%d,ay:%d,az:%d,pt:%d,js:%d,tm:%.1f", NODE_ID, nodeData.ax, nodeData.ay, nodeData.az, nodeData.pt, nodeData.js,nodeData.tm ); } void payloadPublish(char *payload, char const *description) { sprintf(payload, "type:PUBLISH,id:%s,ds:%s", NODE_ID, description ); }
[ "david.kendall@northumbria.ac.uk" ]
david.kendall@northumbria.ac.uk
625023ca1b1207f64b199bae06efa157c57cf1cc
85bfb9f0b2303c57b4f7806af7ecb8af8399c72e
/KnapsackTester.h
44088561ee8cb39b85dcc37c769ba4c8e82e4a0f
[]
no_license
omc8db/CS2500_Knapsack_Project
87f6083ab1632205b3933c329f91883ade58ff93
c81c09ac59cab1265452f310fd4a5448db166dd0
refs/heads/master
2021-01-23T13:18:26.842348
2015-04-16T10:51:09
2015-04-16T10:51:09
33,678,231
0
0
null
null
null
null
UTF-8
C++
false
false
1,761
h
#ifndef KNAPSACK_TESTER_H #define KNAPSACK_TESTER_H #include <iostream> #include <fstream> #include <vector> //Used for performance benchmarking // And seeding RNG #include <time.h> //used for Random Number Generator #include <stdlib.h> #include "knapsack.h" using namespace std; const int MAX_CAPACITY = 8192; // Test up to 2^16 const int MIN_CAPACITY = 4; struct combinedTestResult { knapsackResult greedyResult; knapsackResult dynamicResult; int greedyTime; int dynamicTime; }; class KnapsackTester { public: KnapsackTester(const char* output_filename); ~KnapsackTester(); // Runs the tests and outputs the results to a file // Iterates through capacities, doubling each time. // Runs with inputs of size 1 to MAX_INPUT_SIZE // Steps in TEST_INPUT_SIZE_STEP // results output in CSV to specified output file // Individual results displayed on screen void runAutomatedTests(); //Runs the given input through a greedy and dynamic approach to solving the //knapsack problem. // // Inputs: List of items to knapsack // Capacity // Outputs: Time for dynamic approach // Time for greedy approach // knapsackResult for dynamic approach // knapsackResult for greedy approach combinedTestResult test(const vector<knapsackItem>& input, int capacity); private: vector<knapsackItem> generateRandom(int size, int max_val); vector<knapsackItem> generateDirect(int size); vector<knapsackItem> generateInverse(int size); ofstream m_output_file; }; //Outputs the combined test result in human readable format ostream& operator << (ostream& out, const combinedTestResult& in); //Outputs a list of knapsack items ostream& operator << (ostream& out, const vector<knapsackItem>& input); #endif
[ "omc8db@mst.edu" ]
omc8db@mst.edu
ab209f5502c22935f2922d6abbc783d16d75ae6e
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/hunk_4893.cpp
7d2f05b3c12cec04f8fe4a77effdcbe8baa784fa
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
461
cpp
strbuf_release(&sb); - determine_author_info(); + /* This checks and barfs if author is badly specified */ + determine_author_info(author_ident); /* This checks if committer ident is explicitly given */ - git_committer_info(0); + strbuf_addstr(&committer_ident, git_committer_info(0)); if (use_editor && include_status) { - char *author_ident; - const char *committer_ident; - + char *ai_tmp, *ci_tmp; if (in_merge) fprintf(fp, "#\n"
[ "993273596@qq.com" ]
993273596@qq.com
b5d085286c7c54e35891dc7f80d49100a03194f6
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/shell/ext/taskui/nusrmgr/mainpage.h
f0baa8df2caf55b8c0a6a3b2af6d15bc656708a3
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,719
h
// MainPage.h : Declaration of the CMainPage #ifndef __MAINPAGE_H_ #define __MAINPAGE_H_ #include "Nusrmgr.h" #include "HTMLImpl.h" #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CMainPage class ATL_NO_VTABLE DECLSPEC_UUID("C9332CBE-E2D6-4722-B81D-283E2A400E84") CMainPage : public CComObjectRoot, public CHTMLPageImpl<CMainPage,IMainPageUI> { public: DECLARE_NOT_AGGREGATABLE(CMainPage) //DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CMainPage) COM_INTERFACE_ENTRY(ITaskPage) COM_INTERFACE_ENTRY(IMainPageUI) COM_INTERFACE_ENTRY2(IDispatch, IMainPageUI) END_COM_MAP() // IMainPageUI public: STDMETHOD(createUserTable)(/*[in]*/ IDispatch* pdispParent); public: static LPWSTR c_aHTML[2]; }; EXTERN_C const CLSID CLSID_MainPage; LPWSTR FormatString(LPCWSTR pszFormat, ...); BOOL IsAccountType(ILogonUser* pUser, UINT iType); UINT GetAccountType(ILogonUser* pUser); BOOL IsSameAccount(ILogonUser* pUser, LPCWSTR pszLoginName); BSTR GetUserDisplayName(ILogonUser* pUser); LPWSTR CreateUserDisplayHTML(LPCWSTR pszName, LPCWSTR pszSubtitle, LPCWSTR pszPicture); LPWSTR CreateUserDisplayHTML(ILogonUser* pUser); LPWSTR CreateDisabledGuestHTML(); HRESULT CreateUserTableHTML(ILogonEnumUsers* pUserList, UINT cColumns, BSTR* pstrHTML); __inline BOOL IsOwnerAccount(ILogonUser* pUser) { return IsAccountType(pUser, 0); } __inline BOOL IsAdminAccount(ILogonUser* pUser) { return IsSameAccount(pUser, g_szAdminName); } __inline BOOL IsGuestAccount(ILogonUser* pUser) { return IsSameAccount(pUser, g_szGuestName); } #endif //__MAINPAGE_H_
[ "112426112@qq.com" ]
112426112@qq.com
a41275ae54ae557ec1144c606ac3ce6bfd9a8622
1c7d2d5069b70b723fb6b663c1569a17980a54aa
/main.cpp
95a06308c998f0ff85724c6c82cafa81c323887c
[]
no_license
spippolatore/ShaderTest
2f4a2d104b04bd90d9842856fcfa89f03942c3c2
692047861cc9404c327672b91344dba8291790f5
refs/heads/master
2021-01-18T07:21:14.100925
2013-07-03T17:46:29
2013-07-03T17:46:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,781
cpp
#define GL_GLEXT_PROTOTYPES 1 #include <SFML/System.hpp> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <GL/gl.h> #include <GL/glu.h> #include "GL/glext.h" #include <iostream> #include <cmath> #include <pulse/simple.h> #include <pulse/error.h> #include "record.h" #include "dsp.h" using namespace std; using namespace sf; float dt; float tim = 0; Window* app; float frameTime; int frameCount; int window_width = 512; int window_height = 512; #define texSize 2048 #define texRows 4 Texture tex; float beat; Shader* loadShader(string vertex, string fragment) { cerr << "* Loading shader: " << vertex << " " << fragment << endl; Shader* t = new Shader(); if (!t->loadFromFile(vertex, fragment)) exit(1); return t; } unsigned char fftTex[texRows][texSize*4]; FFT fft; void streamRecordCallback(short* buffer, int samples) { float buf[samples]; for(int i = 0; i < samples; i++) buf[i] = (float(buffer[2*i]) + float(buffer[2*i+1]))/float(1<<16); fft.forward(buf, samples); for(int i = 0; i < texSize; i++) { float v = fft.spectrum[i]; /* v -= fft.spectrum[i/2]*0.1; v -= fft.spectrum[i/3]*0.05; v -= fft.spectrum[i/4]*0.02;*/ v *= 3; if(v < 0) v = 0; if(v > 1) v = 1; fftTex[0][i*4] = (unsigned char)(v*255); fftTex[0][i*4] = (unsigned char)(v*2*255); } } int main(int argc, char** argv) { // Create the main window app = new Window(sf::VideoMode(window_width, window_height, 32), "SFML OpenGL"); //app->setVerticalSyncEnabled(true); // Create a clock for measuring time elapsed sf::Clock clock; // Set color and depth clear value glClearDepth(1.0f); glClearColor(0.f, 0.f, 0.f, 0.f); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Shader* shader = loadShader("vertex.glsl", "fragment.glsl"); Shader* fftShader = loadShader("vertex.glsl", "fragment-fft.glsl"); bool running = true; tex.create(texSize, texRows); tex.setSmooth(true); //sf::Thread thread(&startRecording, &streamRecordCallback); // thread.launch(); // start the thread (internally calls threadFunc(5)) // Start game loop while (app->isOpen()) { // Process events sf::Event event; while (app->pollEvent(event)) { // Close window : exit if (event.type == sf::Event::Closed) app->close(); // Escape key : exit if ((event.type == sf::Event::KeyPressed) && (event.key.code == Keyboard::Escape)) app->close(); if ((event.type == sf::Event::KeyPressed) && (event.key.code == Keyboard::Space)) running = !running; // Resize event : adjust viewport if (event.type == sf::Event::Resized) { window_width = event.size.width; window_height = event.size.height; glViewport(0, 0, window_width, window_height); } } app->setActive(); dt = clock.getElapsedTime().asSeconds(); clock.restart(); if(running) tim += dt; frameTime += dt; frameCount++; tex.update(&fftTex[0][0]); if(frameTime >= 1) { cout<<"FPS "<<frameCount/frameTime<<endl; frameTime = 0; frameCount = 0; } beat -= dt*2; if(beat < 0) beat = 0; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the depth and colour buffers if(true) { Shader::bind(shader); shader->setParameter("time", tim); shader->setParameter("beat", beat); glBegin(GL_QUADS); float aspectRatio = (float)app->getSize().x / (float)app->getSize().y; glTexCoord2f(-aspectRatio, -1); glVertex2f(-1, -1); glTexCoord2f(aspectRatio, -1); glVertex2f(1, -1); glTexCoord2f(aspectRatio, 1); glVertex2f(1, 1); glTexCoord2f(-aspectRatio, 1); glVertex2f(-1, 1); glEnd(); } /* Shader::bind(fftShader); fftShader->setParameter("fft", tex); glBegin(GL_QUADS); glTexCoord2f(-1, -1); glVertex2f(-1, -1); glTexCoord2f(1, -1); glVertex2f(1, -1); glTexCoord2f(1, 1); glVertex2f(1, 1); glTexCoord2f(-1, 1); glVertex2f(-1, 1); glEnd(); */ app->display(); } // thread.terminate(); //Terminate ALL the threads! return EXIT_SUCCESS; }
[ "dirbaio@dirbaio.net" ]
dirbaio@dirbaio.net
bd4b02a23aea5520ac9dd4609f152b0c02519348
e484ebc3705f140727aa70da4b1f7e7e412d0a7c
/hw8/Unit.h
c44cf001cc210a686aeaac1dce885f22361cef36
[]
no_license
aprox13/itmo_cpp
1a6d817e80fd8c891986c0fc3b6577357395ad32
f685fd7492b317a7e371d95a20bccc552600276f
refs/heads/master
2020-04-23T03:19:20.047090
2019-02-15T14:13:40
2019-02-15T14:13:40
170,874,609
0
0
null
null
null
null
UTF-8
C++
false
false
305
h
#pragma once #include <iostream> #include <string> #include <utility> class Unit { public: std::string name; int hp; int mood; explicit Unit(const std::string& name); void heal(int); void receiveDamage(int); void giveDamage(Unit&, int); virtual ~Unit() = default; };
[ "ifkbhit@gmail.com" ]
ifkbhit@gmail.com
c6b7f4137fc15fe7d5e2e488e06cd434b7a096d8
6c1221d962a6776f214ef18e1e509ff13c99702f
/input_for_FGR/filter_normals.inl
21926698591bef030dbc26455192cdbbf790c494
[]
no_license
juliasanchez/toolbox_pcl
fe5de04290e555f36687e73c4a02d38cf54b3955
617ff2404db1f9a5bc28a2d55a757e822dd5984d
refs/heads/master
2020-12-30T10:23:06.200771
2018-01-04T09:08:47
2018-01-04T09:08:47
78,561,247
0
0
null
null
null
null
UTF-8
C++
false
false
477
inl
void filter_normals(pcl::PointCloud<pcl_point>::Ptr normals, float radius, float perc, pcl::PointIndices::Ptr removed_indices) { pcl::RadiusOutlierRemoval<pcl_point> rorfilter(true); rorfilter.setInputCloud (normals); rorfilter.setRadiusSearch (radius); rorfilter.setMinNeighborsInRadius (floor(normals->points.size()*perc ) ); rorfilter.filter (*normals); pcl::IndicesConstPtr ind=rorfilter.getRemovedIndices(); removed_indices->indices = *ind; }
[ "julia.sanchez.moulle@gmail.com" ]
julia.sanchez.moulle@gmail.com
c2cd1ce089c69f5a44b87b1147113a9199457926
9b7964822100a804450fadfe3cd7ea72180eadcb
/src/blocksignature.cpp
1c977e90feebc59cc3d0f275997abeaf41456bb7
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thnass/adeptio
7415d6300e0aec964e2223c4c7b19ea51b173816
65aad9209588e62a3e58d6187a88253d3d5f04b1
refs/heads/master
2020-08-04T03:40:56.444722
2019-10-01T01:28:09
2019-10-01T01:28:09
211,990,234
0
0
MIT
2019-10-01T01:25:17
2019-10-01T01:25:16
null
UTF-8
C++
false
false
3,093
cpp
// Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2019 The Adeptio developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "blocksignature.h" #include "main.h" #include "zADEchain.h" bool SignBlockWithKey(CBlock& block, const CKey& key) { if (!key.Sign(block.GetHash(), block.vchBlockSig)) return error("%s: failed to sign block hash with key", __func__); return true; } bool GetKeyIDFromUTXO(const CTxOut& txout, CKeyID& keyID) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { keyID = CPubKey(vSolutions[0]).GetID(); } else if (whichType == TX_PUBKEYHASH) { keyID = CKeyID(uint160(vSolutions[0])); } return true; } bool SignBlock(CBlock& block, const CKeyStore& keystore) { CKeyID keyID; if (block.IsProofOfWork()) { bool fFoundID = false; for (const CTxOut& txout :block.vtx[0].vout) { if (!GetKeyIDFromUTXO(txout, keyID)) continue; fFoundID = true; break; } if (!fFoundID) return error("%s: failed to find key for PoW", __func__); } else { if (!GetKeyIDFromUTXO(block.vtx[1].vout[1], keyID)) return error("%s: failed to find key for PoS", __func__); } CKey key; if (!keystore.GetKey(keyID, key)) return error("%s: failed to get key from keystore", __func__); return SignBlockWithKey(block, key); } bool CheckBlockSignature(const CBlock& block) { if (block.IsProofOfWork()) return block.vchBlockSig.empty(); if (block.vchBlockSig.empty()) return error("%s: vchBlockSig is empty!", __func__); /** Each block is signed by the private key of the input that is staked. This can be either zADE or normal UTXO * zADE: Each zADE has a keypair associated with it. The serial number is a hash of the public key. * UTXO: The public key that signs must match the public key associated with the first utxo of the coinstake tx. */ CPubKey pubkey; bool fzADEStake = block.vtx[1].IsZerocoinSpend(); if (fzADEStake) { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(block.vtx[1].vin[0]); pubkey = spend.getPubKey(); } else { txnouttype whichType; std::vector<valtype> vSolutions; const CTxOut& txout = block.vtx[1].vout[1]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY || whichType == TX_PUBKEYHASH) { valtype& vchPubKey = vSolutions[0]; pubkey = CPubKey(vchPubKey); } } if (!pubkey.IsValid()) return error("%s: invalid pubkey %s", __func__, pubkey.GetHex()); return pubkey.Verify(block.GetHash(), block.vchBlockSig); }
[ "38818888+adeptio-project@users.noreply.github.com" ]
38818888+adeptio-project@users.noreply.github.com
145ba5587e5bbd2333e25be98e6ca76f98aca7bb
ba55f3c1d7bb36fbf26291eae92f70d039455ac7
/rclcpp/test/test_find_weak_nodes.cpp
e0850761ef71f81b6525ed87b4c56a4bf24d98c4
[ "Apache-2.0" ]
permissive
geoffviola/rclcpp
f71c1593b70400e9e32e129871d1531a07e14e09
15ea4bb8f40d4b5b72672c6c6a839fdcd69980a8
refs/heads/master
2020-04-05T22:43:10.193034
2016-11-19T03:54:29
2016-11-19T03:54:29
67,166,907
0
0
null
2016-09-01T21:15:34
2016-09-01T21:15:34
null
UTF-8
C++
false
false
2,706
cpp
// Copyright 2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <memory> #include "rclcpp/strategies/allocator_memory_strategy.hpp" #include "rclcpp/memory_strategy.hpp" #include "rclcpp/node.hpp" #include "rclcpp/rclcpp.hpp" class TestFindWeakNodes : public ::testing::Test { protected: static void SetUpTestCase() { rclcpp::init(0, nullptr); } }; TEST_F(TestFindWeakNodes, allocator_strategy_with_weak_nodes) { // GIVEN // A vector of weak pointers to nodes auto memory_strategy = std::make_shared< rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy<>>(); auto existing_node = rclcpp::node::Node::make_shared("existing_node"); auto dead_node = rclcpp::node::Node::make_shared("dead_node"); rclcpp::memory_strategy::MemoryStrategy::WeakNodeVector weak_nodes; weak_nodes.push_back(existing_node); weak_nodes.push_back(dead_node); // AND // Delete dead_node, creating a dangling pointer in weak_nodes dead_node.reset(); ASSERT_FALSE(weak_nodes[0].expired()); ASSERT_TRUE(weak_nodes[1].expired()); // WHEN bool has_invalid_weak_nodes = memory_strategy->collect_entities(weak_nodes); // THEN // The result of finding dangling node pointers should be true ASSERT_TRUE(has_invalid_weak_nodes); } TEST_F(TestFindWeakNodes, allocator_strategy_no_weak_nodes) { // GIVEN // A vector of weak pointers to nodes, all valid auto memory_strategy = std::make_shared< rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy<>>(); auto existing_node1 = rclcpp::node::Node::make_shared("existing_node1"); auto existing_node2 = rclcpp::node::Node::make_shared("existing_node2"); rclcpp::memory_strategy::MemoryStrategy::WeakNodeVector weak_nodes; weak_nodes.push_back(existing_node1); weak_nodes.push_back(existing_node2); ASSERT_FALSE(weak_nodes[0].expired()); ASSERT_FALSE(weak_nodes[1].expired()); // WHEN bool has_invalid_weak_nodes = memory_strategy->collect_entities(weak_nodes); // THEN // The result of finding dangling node pointers should be false ASSERT_FALSE(has_invalid_weak_nodes); }
[ "dhood@users.noreply.github.com" ]
dhood@users.noreply.github.com
c2c7c75b361bcde452b60733161d8973c47a7d9e
55de3b3bc0e3a33a3f5ba090431e528482a80150
/vivado_projekty/tor_wizyjny - Copy/tor_wizyjny.sdk/hellocpp2/src/main.cc
0223d27aacca3eb70e8b0cdcbe42368855b91368
[]
no_license
ghsecuritylab/konkurs
ade8d66bbd054ca4cc2530df32f5909442842a5f
bcd698b7b533bc9b953488655dc4c1aee669afbc
refs/heads/master
2021-02-28T17:48:41.765932
2019-05-08T12:44:48
2019-05-08T12:44:48
245,717,183
0
0
null
2020-03-07T22:49:35
2020-03-07T22:49:35
null
UTF-8
C++
false
false
177
cc
#include <stdio.h> #include "platform.h" #include "xparameters.h" int main() { init_platform(); print("Hello Worldcpp\n\r"); cleanup_platform(); return 0; }
[ "michal.danilowicz@nokia.com" ]
michal.danilowicz@nokia.com
511ed5c730821a4c2fadeb28d19d76ae07e3af6c
0fba517f10d2179a8aa838b9da9b789d4e203598
/HackerRank/cyclicquadruples.cpp
f7b7eae5a2cb1e822afff15d2651afc21b61dd24
[]
no_license
hdi-superuser/Codes
e7923975b4656a09b211710d659cd2ea7859bcbb
2ca9d777d6ecce59c0ed26e8db83b475b73b192a
refs/heads/master
2021-01-21T00:36:34.855984
2016-06-15T20:27:28
2016-06-15T20:27:28
61,238,394
0
0
null
2016-06-15T20:22:04
2016-06-15T20:22:04
null
UTF-8
C++
false
false
1,062
cpp
#include <bits/stdc++.h> #define pb push_back #define sqr(x) (x)*(x) #define sz(a) int(a.size()) #define reset(a,b) memset(a,b,sizeof(a)) #define oo 1000000007 using namespace std; typedef pair<int,int> pii; typedef long long ll; ll l[4],r[4]; int T; ll calc(int mask){ ll minv=-oo, maxv=oo; ll res = 1; for(int i=0; i<4; ++i) if(mask>>i&1){ minv = max(minv, l[i]); maxv = min(maxv, r[i]); }else{ res = res * (r[i]-l[i]+1)%oo; } if(minv>maxv) return 0; if(mask) res = res * (maxv-minv+1)%oo; return res; } int cntbit(int v){ int r = 0; while(v){ r+=v&1; v/=2; } return r; } int main(){ freopen("input.txt","r",stdin); cin>>T; while(T--){ for(int i=0; i<4; ++i) cin>>l[i]>>r[i]; ll res = calc(0); for(int i=0; i<16; ++i) if(cntbit(i)==2) res -= calc(i); else if(cntbit(i)==3) res += 2*calc(i); else if(cntbit(i)==4) res -= 4*calc(i); cout<<res<<endl; } }
[ "yenthanh.t7@gmail.com" ]
yenthanh.t7@gmail.com
61067952abe6560eeb99d3d618aa9d8f55bb698e
1f9103df0f41200d680431fea4bba6f1d449e6ec
/Drive.ino
308cb51806082e08f8311df4ed627e33fa797d9c
[]
no_license
kreidler-f65/HS-Projekt
015ea27bbd8e1d62fa832ae56322ac506432797e
88bdc20f73d1b7c775eaad284f8de193477dc544
refs/heads/master
2021-01-01T16:06:27.422652
2015-02-24T22:55:51
2015-02-24T22:55:51
30,314,985
0
0
null
null
null
null
UTF-8
C++
false
false
2,768
ino
//******************************************************************************************************************************************************************************** //Fahren Werte von -255 bis 255 werden verarbeitet // 0 = Fahrzeug steht -> Bremsen // Wert > 0 = Fahrzeug fährt mit Wert vorwärts // Wert < 0 = Fahrzeug fährt mit Wert rückwerts //******************************************************************************************************************************************************************************** void Drive (int DriveForSpeed){ int sort =rotating_direction(); // // Serial.print("\t rotating_direction: "); // // Serial.print(sort); DriveForSpeed = min(DriveForSpeed,MAXSPEED); if((sort==-1) || (sortold != sort)){ // 0 = Fahrzeug steht -> Bremsen oder Richtungsänderung Break (); } else if((sort==1 && DIRECTION==1)||(sort==2 && DIRECTION==2)){ // Wert > 0 = Fahrzeug fährt mit Wert vorwärts digitalWrite(SD_B, HIGH); digitalWrite(IN_B, LOW); digitalWrite(IN_A, HIGH); analogWrite(SD_A, DriveForSpeed); Serial.print("\t FOR: "); Serial.print(DriveForSpeed); Brakeaktive=false; } else if ((sort==1 && DIRECTION==2)||(sort==2 && DIRECTION==1)){ // Wert < 0 = Fahrzeug fährt mit Wert rückwerts DriveForSpeed = map(DriveForSpeed,0,MAXSPEED,0,MAXSPEED/2); //Halbe Geschwindigkeit bei Rückwärts fahren digitalWrite(SD_A, HIGH); digitalWrite(IN_A, LOW); digitalWrite(IN_B, HIGH); analogWrite(SD_B, DriveForSpeed); Serial.print("\t Back: "); Serial.print(DriveForSpeed); Brakeaktive=false; } sortold = sort; return; } //******************************************************************************************************************************************************************************** //Bremsen //******************************************************************************************************************************************************************************** void Break (){ if(Brakeaktive==false){ digitalWrite(SD_A, LOW); //Austrudeln 400ms digitalWrite(IN_A, LOW); digitalWrite(IN_B, LOW); digitalWrite(SD_B, LOW); delay(500); int i; for(i=0;i<=255;i++){ digitalWrite(SD_A, HIGH); //Bremsen auf Maximal digitalWrite(IN_A, LOW); digitalWrite(IN_B, LOW); analogWrite(SD_B, i); delay(2); Speed--; Speed=max(Speed,1); } Brakeaktive=true; } digitalWrite(SD_A, HIGH); //Bremsen Maximal digitalWrite(IN_A, LOW); digitalWrite(IN_B, LOW); digitalWrite(SD_B, HIGH); }
[ "manuelrude@gmx.de" ]
manuelrude@gmx.de
1a8c6c1de2cb51075f769bcab603c6c71207f0bc
82bd10199e849772d64724547b8e41ea8f700451
/dataeditwindow.h
95d2e8c563f6562ec264255e17861ad49a5ae7b1
[]
no_license
FreeLike76/PostServiceSQL
1f04517b62cea8ff5eb5e841038e51c5e6b3b7a8
014b92701d83a833ab6576c8b5586903e5b3b630
refs/heads/master
2023-01-30T19:20:39.032470
2020-12-13T09:58:48
2020-12-13T09:58:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
388
h
#ifndef DATAEDITWINDOW_H #define DATAEDITWINDOW_H #include <QWidget> #include <QSqlTableModel> namespace Ui { class DataEditWindow; } class DataEditWindow : public QWidget { Q_OBJECT public: explicit DataEditWindow(QString id, QWidget *parent = nullptr); ~DataEditWindow(); QSqlTableModel* rowModel; private: Ui::DataEditWindow *ui; }; #endif // DATAEDITWINDOW_H
[ "dmytro.geleshko01@gmail.com" ]
dmytro.geleshko01@gmail.com
4fb3bc673b23d6b97ad05b3a7129a3b1359423c6
e4d6a2b9da474c1bff7efc73536987e033b96135
/chapter8Quiz/HelloWorld.h
89eca31c9e6ee822dac0bc806c2f10045ed385db
[]
no_license
luyangtang/cppQuiz
578f4661121d4ad71b96bc6558a0e7f135443f26
7f6845e2e611e026625d8b5568ee5f4dfb697d2d
refs/heads/master
2020-04-11T09:45:57.256771
2019-04-26T22:27:19
2019-04-26T22:27:19
161,690,947
0
0
null
null
null
null
UTF-8
C++
false
false
346
h
#ifndef HELLOWORLD_H #define HELLOWORLD_H class HelloWorld { private: char *m_data; public: HelloWorld() { m_data = new char[14]; const char *init = "Hello, World!"; for (int i = 0; i < 14; ++i) m_data[i] = init[i]; } ~HelloWorld() { delete[] m_data; } void print() const { std::cout << m_data; } }; #endif
[ "kojika.tang@gmail.com" ]
kojika.tang@gmail.com
13005972b843a214edffe68978d09efadfa48f33
ccdbce6daae04ccb8818f49e64490c4de1366811
/ChatBox3/ChatBox3Server/ChatBox3Server/Source.cpp
e3862c24efbd6f02b46b7554ccf476e400245410
[]
no_license
Rohith24/ChatBox
8569940bd1f671804a85f84e4a741978ee059c9e
1ba93cc3b277cef0b50d92a01cb4cfe5fb4d9441
refs/heads/master
2020-03-27T22:53:44.054313
2016-07-13T15:32:12
2016-07-13T15:32:12
62,443,306
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
cpp
#include <windows.h> #include <stdio.h> #include <conio.h> DWORD WINAPI ReadThread(LPVOID par){ int prev = -1; while (1) { FILE *f = fopen("F:\\GIT\\ChatBox\\ChatBox3\\source.bin", "rb+"); char str[256]; int cno,sno; memset(str, '\0', 256); fseek(f, 0, 0); fread(&sno, sizeof(int), 1, f); fread(&cno, sizeof(int), 1, f); if (prev == cno){ fclose(f); continue; } prev = cno; fseek(f, (sno+cno-1) * 256 + 8, 0); if (fread(str, 256, 1, f) == 0){ fclose(f); continue; } if (str[0] == '\0'){ fclose(f); continue; } printf("Client: %s\n", str); } } DWORD WINAPI WriteThread(LPVOID par) { int cno,sno; while (1) { FILE *f = fopen("F:\\GIT\\ChatBox\\ChatBox3\\source.bin", "rb+"); char s[256]; memset(s, '\0', 256); gets(s); fseek(f, 0, 0); fread(&sno, sizeof(int), 1, f); fread(&cno, sizeof(int), 1, f); sno++; fseek(f, 0, 0); fwrite(&sno, sizeof(int), 1, f); fflush(f); fseek(f, (sno+cno - 1) * 256 + 8, 0); fwrite(s, 256, 1, f); fflush(f); fclose(f); } } void main(){ FILE *f = fopen("F:\\GIT\\ChatBox\\ChatBox3\\source.bin", "rb+"); DWORD dwThreadId, dwThrdParam = 1; HANDLE hThreadArray[2]; hThreadArray[0]=CreateThread(0, 0, ReadThread, 0, 0, 0); hThreadArray[1]=CreateThread(0, 0, WriteThread, 0, 0, 0); WaitForMultipleObjects(2, hThreadArray, TRUE, INFINITE); for (int i = 0; i<2; i++) { CloseHandle(hThreadArray[i]); } fclose(f); }
[ "rohithreddy24@hotmail.com" ]
rohithreddy24@hotmail.com
67846c2ff2427e0c12f67c54fcf47a9f6976a31a
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium/net/base/backoff_entry.cc
e7b7b558b70fc0e839044675f5af2412d5f86fed
[ "BSD-3-Clause", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
4,393
cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/backoff_entry.h" #include <algorithm> #include <cmath> #include "base/logging.h" #include "base/rand_util.h" namespace net { BackoffEntry::BackoffEntry(const BackoffEntry::Policy* const policy) : failure_count_(0), policy_(policy) { DCHECK(policy_); // Can't use GetTimeNow() as it's virtual. exponential_backoff_release_time_ = base::TimeTicks::Now(); } BackoffEntry::~BackoffEntry() { // TODO(joi): Remove this once our clients (e.g. URLRequestThrottlerManager) // always destroy from the I/O thread. DetachFromThread(); } void BackoffEntry::InformOfRequest(bool succeeded) { if (!succeeded) { ++failure_count_; exponential_backoff_release_time_ = CalculateReleaseTime(); } else { // We slowly decay the number of times delayed instead of resetting it to 0 // in order to stay stable if we receive successes interleaved between lots // of failures. // // TODO(joi): Revisit this; it might be most correct to go to zero // but have a way to go back to "old error count +1" if there is // another error soon after. if (failure_count_ > 0) --failure_count_; // The reason why we are not just cutting the release time to GetTimeNow() // is on the one hand, it would unset a release time set by // SetCustomReleaseTime and on the other we would like to push every // request up to our "horizon" when dealing with multiple in-flight // requests. Ex: If we send three requests and we receive 2 failures and // 1 success. The success that follows those failures will not reset the // release time, further requests will then need to wait the delay caused // by the 2 failures. exponential_backoff_release_time_ = std::max( GetTimeNow(), exponential_backoff_release_time_); } } bool BackoffEntry::ShouldRejectRequest() const { return exponential_backoff_release_time_ > GetTimeNow(); } base::TimeTicks BackoffEntry::GetReleaseTime() const { return exponential_backoff_release_time_; } void BackoffEntry::SetCustomReleaseTime(const base::TimeTicks& release_time) { exponential_backoff_release_time_ = release_time; } bool BackoffEntry::CanDiscard() const { if (policy_->entry_lifetime_ms == -1) return false; base::TimeTicks now = GetTimeNow(); int64 unused_since_ms = (now - exponential_backoff_release_time_).InMilliseconds(); // Release time is further than now, we are managing it. if (unused_since_ms < 0) return false; if (failure_count_ > 0) { // Need to keep track of failures until maximum back-off period // has passed (since further failures can add to back-off). return unused_since_ms >= std::max(policy_->maximum_backoff_ms, policy_->entry_lifetime_ms); } // Otherwise, consider the entry is outdated if it hasn't been used for the // specified lifetime period. return unused_since_ms >= policy_->entry_lifetime_ms; } base::TimeTicks BackoffEntry::GetTimeNow() const { return base::TimeTicks::Now(); } base::TimeTicks BackoffEntry::CalculateReleaseTime() const { int effective_failure_count = std::max(0, failure_count_ - policy_->num_errors_to_ignore); if (effective_failure_count == 0) { // Never reduce previously set release horizon, e.g. due to Retry-After // header. return std::max(GetTimeNow(), exponential_backoff_release_time_); } // The delay is calculated with this formula: // delay = initial_backoff * multiply_factor^( // effective_failure_count - 1) * Uniform(1 - jitter_factor, 1] double delay = policy_->initial_backoff_ms; delay *= pow(policy_->multiply_factor, effective_failure_count - 1); delay -= base::RandDouble() * policy_->jitter_factor * delay; // Ensure that we do not exceed maximum delay. int64 delay_int = static_cast<int64>(delay + 0.5); delay_int = std::min(delay_int, static_cast<int64>(policy_->maximum_backoff_ms)); // Never reduce previously set release horizon, e.g. due to Retry-After // header. return std::max(GetTimeNow() + base::TimeDelta::FromMilliseconds(delay_int), exponential_backoff_release_time_); } } // namespace net
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
171343967ef102b03de030453eadf80585a2488c
084684d625db6c51c2c1d6a7f9c163d621dc9f11
/test/testngpp-1.1/3rdparty/boost/utility/addressof.hpp
8e0a586880ec53de60565f422ef6d4677aa4db2d
[ "MIT", "GPL-3.0-or-later", "LGPL-3.0-only" ]
permissive
mswdwk/code_test_records
a9938f356d140aa921402d4f049d408bc9c6d2a5
aec5c92d48b07c834b66d4f8b17a789e9bac7531
refs/heads/master
2023-08-23T09:39:01.706418
2023-08-17T06:10:01
2023-08-17T06:10:01
122,560,853
1
0
MIT
2023-02-25T00:13:07
2018-02-23T02:04:29
C++
UTF-8
C++
false
false
1,441
hpp
// Copyright (C) 2002 Brad King (brad.king@kitware.com) // Douglas Gregor (gregod@cs.rpi.edu) // // Copyright (C) 2002, 2008 Peter Dimov // // 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) // For more information, see http://www.boost.org #ifndef BOOST_UTILITY_ADDRESSOF_HPP # define BOOST_UTILITY_ADDRESSOF_HPP # include <boost/config.hpp> # include <boost/detail/workaround.hpp> namespace boost { namespace detail { template<class T> struct addressof_impl { static inline T * f( T & v, long ) { return reinterpret_cast<T*>( &const_cast<char&>(reinterpret_cast<const volatile char &>(v))); } static inline T * f( T * v, int ) { return v; } }; } // namespace detail template<class T> T * addressof( T & v ) { return boost::detail::addressof_impl<T>::f( v, 0 ); } // Borland doesn't like casting an array reference to a char reference // but these overloads work around the problem. # if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) template<typename T,std::size_t N> T (*addressof(T (&t)[N]))[N] { return reinterpret_cast<T(*)[N]>(&t); } template<typename T,std::size_t N> const T (*addressof(const T (&t)[N]))[N] { return reinterpret_cast<const T(*)[N]>(&t); } # endif } // namespace boost #endif // BOOST_UTILITY_ADDRESSOF_HPP
[ "mswdwk@outlook.com" ]
mswdwk@outlook.com
5ccb73ef5b15def65b7587761d1ee6916104e3d9
2c721e4b4f9b4e893578f6ea728a7bf70bd1be87
/20191017 杨辉三角的变形 字符串 动态规划.cpp
9f31038b362aefed7ffb895c3b4035e0ebdfdb6c
[]
no_license
Y-puyu/Everyday_Coding
74060ae37de7c64d48bdb16cc02fd06bbab20eb1
b6204c986116c0a158b6e087045c32818febe162
refs/heads/master
2020-07-19T01:50:00.412119
2020-04-20T15:13:12
2020-04-20T15:13:12
206,354,309
0
0
null
null
null
null
GB18030
C++
false
false
785
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n, m; while (cin >> n) { m = 2 * n - 1; vector<vector<int>> dp(n, vector<int>(m, 0)); dp[0][0] = 1; for (int i = 1; i < n; ++i) { // 第一列和最后一列都为1 dp[i][0] = dp[i][2 * i] = 1; for (int j = 1; j < 2 * i; ++j) { if (j == 1) // 如果是第二列,则只是两个元素之和 dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; else // 第i, j元素等于上一行第j - 2, j - 1, j三列元素之和 dp[i][j] = dp[i - 1][j - 2] + dp[i - 1][j - 1] + dp[i - 1][j]; } } int k; for (k = 0; k < m; ++k) { if (dp[n - 1][k] % 2 == 0 && dp[n - 1][k] != 0) { cout << k + 1 << endl; break; } } if (k == m) cout << -1 << endl; } return 0; }
[ "345462072@qq.com" ]
345462072@qq.com
9231a483bad60292a7d96e596c64f4d664454566
94d8b66f6512f2f17f77000729fd8ac999484ed3
/workspace/Samples/SiviaIbex/ibex-2.0/include/ibex/ibex_DefaultOptimizer.h
cb6ea10a6832c11c79ec39325e58e121061b0d0a
[]
no_license
utctao/reliable-slam
7885c098574afb5284675a6f022d368f7f303ba6
1f00c584d9dacfc17e31e0aa91b0d717998b0310
refs/heads/master
2021-01-20T19:49:49.038094
2013-07-22T21:50:55
2013-07-22T21:50:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,626
h
//============================================================================ // I B E X // File : ibex_DefaultOptimizer.h // Author : Gilles Chabert, Bertrand Neveu // Copyright : Ecole des Mines de Nantes (France) // License : See the LICENSE file // Created : Aug 27, 2012 // Last Update : Sep 28, 2012 //============================================================================ #ifndef __IBEX_DEFAULT_OPTIMIZER_H__ #define __IBEX_DEFAULT_OPTIMIZER_H__ #include "ibex_Optimizer.h" #include "ibex_CtcCompo.h" #include "ibex_XNewton.h" namespace ibex { /** * \ingroup strategy * \brief Default optimizer. */ class DefaultOptimizer : public Optimizer { public: /** * \brief Create a default optimizer. * * \param sys - The system to optimize * \param prec - Stopping criterion for box splitting (absolute precision) * \param goal_prec - Stopping criterion for the objective (relative precision) */ DefaultOptimizer(System& sys, double prec, double goal_prec); /** * \brief Delete *this. */ ~DefaultOptimizer(); private: Array<Ctc>* contractor_list (System& sys, System& ext_sys,double prec); std::vector<X_Newton::corner_point>* default_corners (); // -------- information stored for cleanup ---------- // Extended system // (the objective is added in the system as the last variable and the first constraint // is used for contraction and bisection) System* __ext_sys; CtcCompo* __ctc; Bsc* __bsc; }; } // end namespace ibex #endif // __IBEX_DEFAULT_OPTIMIZER_H__
[ "jeremy@ubuntu.(none)" ]
jeremy@ubuntu.(none)
d28c34a67fa9128a13e1da7359e8d1622b752b95
1bf8b46afad5402fe6fa74293b464e1ca5ee5fd7
/Demo/Shenmue3SDK/SDK/BP_NewST_Input_classes.h
c0c217acafc7673db4919c97c3e5d7d667e1c471
[]
no_license
LemonHaze420/ShenmueIIISDK
a4857eebefc7e66dba9f667efa43301c5efcdb62
47a433b5e94f171bbf5256e3ff4471dcec2c7d7e
refs/heads/master
2021-06-30T17:33:06.034662
2021-01-19T20:33:33
2021-01-19T20:33:33
214,824,713
4
0
null
null
null
null
UTF-8
C++
false
false
2,047
h
#pragma once // Name: S3Demo, Version: 0.90.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_NewST_Input.BP_NewST_Input_C // 0x0016 (0x0358 - 0x0342) class ABP_NewST_Input_C : public ABP_MiniGameInputBase_C { public: unsigned char UnknownData00[0x6]; // 0x0342(0x0006) MISSED OFFSET struct FPointerToUberGraphFrame UberGraphFrame; // 0x0348(0x0008) (Transient, DuplicateTransient) float Turn; // 0x0350(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float moveSpeed; // 0x0354(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_NewST_Input.BP_NewST_Input_C"); return ptr; } void UserConstructionScript(); void InpActEvt_MG_Top_K2Node_InputActionEvent_6(const struct FKey& Key); void InpActEvt_MG_Bottom_K2Node_InputActionEvent_5(const struct FKey& Key); void InpActEvt_MG_ButtonRight_K2Node_InputActionEvent_4(const struct FKey& Key); void InpAxisEvt_MG_LeftStickHorizontal_K2Node_InputAxisEvent_15(float AxisValue); void InpAxisEvt_MG_LeftStickVertical_K2Node_InputAxisEvent_17(float AxisValue); void InpAxisEvt_MG_RightStickHorizontal_K2Node_InputAxisEvent_21(float AxisValue); void InpAxisEvt_MG_RightStickVertical_K2Node_InputAxisEvent_24(float AxisValue); void ReceiveTick(float* DeltaSeconds); void ExecuteUbergraph_BP_NewST_Input(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "35783139+LemonHaze420@users.noreply.github.com" ]
35783139+LemonHaze420@users.noreply.github.com