hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fa516317ceb552f45ff177c73ba06212b5698ec4
| 8,309
|
cpp
|
C++
|
test/BondStereopermutator.cpp
|
Dom1L/molassembler
|
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
|
[
"BSD-3-Clause"
] | 17
|
2020-11-27T14:59:34.000Z
|
2022-03-28T10:31:25.000Z
|
test/BondStereopermutator.cpp
|
Dom1L/molassembler
|
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
|
[
"BSD-3-Clause"
] | null | null | null |
test/BondStereopermutator.cpp
|
Dom1L/molassembler
|
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
|
[
"BSD-3-Clause"
] | 6
|
2020-12-09T09:21:53.000Z
|
2021-08-22T15:42:21.000Z
|
/*!@file
* @copyright This code is licensed under the 3-clause BSD license.
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
* See LICENSE.txt for details.
*/
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include "boost/filesystem.hpp"
#include "boost/test/unit_test.hpp"
#include "Molassembler/Conformers.h"
#include "Molassembler/IO.h"
#include "Molassembler/Molecule.h"
#include "Molassembler/Graph.h"
#include "Molassembler/AtomStereopermutator.h"
#include "Molassembler/BondStereopermutator.h"
#include "Molassembler/StereopermutatorList.h"
#include <iostream>
using namespace Scine;
using BondIndex = Molassembler::BondIndex;
struct Expectation {
BondIndex edge;
unsigned numAssignments;
unsigned fittedAssignment;
Expectation(
BondIndex passEdge,
unsigned assignments,
unsigned assignment
) : edge(passEdge),
numAssignments(assignments),
fittedAssignment(assignment)
{
assert(assignments > 1);
}
Expectation(
BondIndex passEdge,
unsigned assignments
) : edge(passEdge),
numAssignments(assignments)
{
assert(assignments == 1);
// Define the value, but no comparisons with it should be performed
fittedAssignment = std::numeric_limits<unsigned>::max();
}
};
/* This is the current interpretation of yielded indices of permutations of
* BondStereopermutator for all combinations of the shapes triangle and
* bent.
*/
constexpr unsigned Z = 1;
constexpr unsigned E = 0;
constexpr unsigned stereogenic = 2;
constexpr unsigned nonStereogenic = 1;
const std::map<std::string, Expectation> recognitionExpectations {
{
"but-2E-ene",
{{0, 1}, stereogenic, E}
},
{
"but-2Z-ene",
{{0, 1}, stereogenic, Z}
},
{
"E-diazene",
{{0, 1}, stereogenic, E}
},
{
"ethanimine",
{{0, 2}, stereogenic, E}
},
{
"ethene",
{{0, 1}, nonStereogenic}
},
{
"methanimine",
{{0, 1}, nonStereogenic}
}
// formaldehyde is omitted, since there cannot be a BondStereopermutator on it
};
void checkExpectations(const boost::filesystem::path& filePath) {
using namespace Molassembler;
using namespace std::string_literals;
std::string moleculeName = filePath.stem().string();
// Read the file
auto mol = IO::read(filePath.string());
// Check if expectations are met
auto findIter = recognitionExpectations.find(filePath.stem().string());
if(findIter == std::end(recognitionExpectations)) {
// There should be no BondStereopermutator in this molecule
auto bondStereopermutatorRange = mol.stereopermutators().bondStereopermutators();
BOOST_CHECK(
std::distance(
bondStereopermutatorRange.first,
bondStereopermutatorRange.second
) == 0
);
/* No DG work is needed since it doesn't involve BondStereopermutator (there
* are none in the molecule)
*/
} else {
const Expectation& expectation = findIter->second;
auto bondStereopermutatorOption = mol.stereopermutators().option(expectation.edge);
BOOST_REQUIRE_MESSAGE(
bondStereopermutatorOption,
"There is no BondStereopermutator on the expected edge for " << moleculeName
);
BOOST_REQUIRE_MESSAGE(
bondStereopermutatorOption->numAssignments() == expectation.numAssignments,
"The expected number of permutations was not met for " << moleculeName
<< ": expected " << expectation.numAssignments << ", got "
<< bondStereopermutatorOption->numAssignments()
);
if(expectation.numAssignments == stereogenic) {
auto assignmentOptional = bondStereopermutatorOption->assigned();
BOOST_REQUIRE(assignmentOptional);
BOOST_REQUIRE_MESSAGE(
assignmentOptional.value() == expectation.fittedAssignment,
"The stereopermutator is not assigned the expected value for "
<< moleculeName << ": Expected " << expectation.fittedAssignment
<< ", got " << *assignmentOptional << " instead"
);
}
// Generate a conformation
auto positionsResult = generateRandomConformation(mol);
// If DG fails, we're screwed
if(!positionsResult) {
BOOST_FAIL(positionsResult.error().message());
}
// Reinterpret the molecule from the existing graph and the generated positions
Molecule reinterpreted {
mol.graph(),
AngstromPositions {positionsResult.value()}
};
bool pass = reinterpreted == mol;
if(!pass) {
std::cout << "Initial molecule: " << mol << "\nReinterpreted:"
<< reinterpreted;
}
BOOST_CHECK_MESSAGE(
pass,
"The reinterpreted molecule does not equal the initial molecule for "
<< moleculeName
);
}
}
BOOST_AUTO_TEST_CASE(BondStereopermutatorConsistency, *boost::unit_test::label("Molassembler")) {
for(
const boost::filesystem::path& currentFilePath :
boost::filesystem::recursive_directory_iterator("ez_stereocenters")
) {
BOOST_CHECK_NO_THROW(
checkExpectations(currentFilePath)
);
}
}
BOOST_AUTO_TEST_CASE(BondStatePropagation, *boost::unit_test::label("Molassembler")) {
using namespace Molassembler;
auto mol = IO::read("ez_stereocenters/but-2E-ene.mol");
// Alter a hydrogen at the bond stereopermutator
const StereopermutatorList& stereopermutators = mol.stereopermutators();
auto bondStereopermutatorRange = stereopermutators.bondStereopermutators();
BOOST_REQUIRE(std::distance(bondStereopermutatorRange.first, bondStereopermutatorRange.second) > 0);
const BondStereopermutator& mainStereopermutator = *bondStereopermutatorRange.first;
BOOST_REQUIRE(mainStereopermutator.assigned());
unsigned priorAssignment = mainStereopermutator.assigned().value();
// Pick a side
const AtomIndex side = mainStereopermutator.placement().first;
// Find a hydrogen substituent
boost::optional<AtomIndex> hydrogenSubstituent;
for(const AtomIndex substituent : mol.graph().adjacents(side)) {
if(mol.graph().elementType(substituent) == Utils::ElementType::H) {
hydrogenSubstituent = substituent;
break;
}
}
BOOST_REQUIRE(hydrogenSubstituent);
// Replace the hydrogen substituent with a fluorine
mol.setElementType(*hydrogenSubstituent, Utils::ElementType::F);
// All references are, in principle, invalidated. Just being extra careful.
auto postPermutatorRange = stereopermutators.bondStereopermutators();
// The new stereopermutator must still be assigned, and have a different assignment
BOOST_REQUIRE(std::distance(postPermutatorRange.first, postPermutatorRange.second) > 0);
const BondStereopermutator& postPermutator = *postPermutatorRange.first;
BOOST_REQUIRE(postPermutator.assigned());
// In this particular case, we know that the final assignment has to be different
BOOST_CHECK(postPermutator.assigned().value() != priorAssignment);
}
BOOST_AUTO_TEST_CASE(StereocentersInSmallCycles, *boost::unit_test::label("Molassembler")) {
// Flat map from cycle size to number of assignments
const std::vector<unsigned> expectedAssignmentsMap {
0, 0, 0, 1, 1, 1, 1, 2, 2
};
using namespace Molassembler;
/* In small cycles, double bond stereopermutators should exclude the E
* stereopermutation and have only a single assignment
*/
for(unsigned cycleSize = 3; cycleSize <= 8; ++cycleSize) {
Molecule mol {
Utils::ElementType::C,
Utils::ElementType::C,
BondType::Double
};
// Add cycle atoms
AtomIndex last = 0;
for(unsigned i = 0; i < cycleSize - 2; ++i) {
last = mol.addAtom(Utils::ElementType::C, last);
}
// Close the cycle
mol.addBond(last, 1);
// Set geometries
for(unsigned i = 0; i < cycleSize; ++i) {
mol.setShapeAtAtom(i, Shapes::Shape::Bent);
}
auto bondStereopermutatorOption = mol.stereopermutators().option(BondIndex {0, 1});
BOOST_REQUIRE_MESSAGE(
bondStereopermutatorOption,
"Expected a BondStereopermutator on {0, 1}, got None"
);
BOOST_CHECK_MESSAGE(
bondStereopermutatorOption->numAssignments() == expectedAssignmentsMap.at(cycleSize),
"Expected " << expectedAssignmentsMap.at(cycleSize)
<< " assignments for cycle of size " << cycleSize
<< ", got " << bondStereopermutatorOption->numAssignments()
<< "instead."
);
}
}
| 30.435897
| 102
| 0.703213
|
Dom1L
|
fa560f221384189593c6d4e70dafe8cb08e627ca
| 4,963
|
hpp
|
C++
|
ql/experimental/templatemodels/hullwhite/g2ppT.hpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | null | null | null |
ql/experimental/templatemodels/hullwhite/g2ppT.hpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 9
|
2021-05-17T06:40:39.000Z
|
2022-03-28T08:08:46.000Z
|
ql/experimental/templatemodels/hullwhite/g2ppT.hpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 1
|
2020-11-23T09:16:13.000Z
|
2020-11-23T09:16:13.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2018, Sebastian Schlenkrich
*/
#ifndef quantlib_templateg2pp_hpp
#define quantlib_templateg2pp_hpp
#include <ql/shared_ptr.hpp>
#include <ql/errors.hpp>
#include <ql/termstructures/yieldtermstructure.hpp>
#include <ql/experimental/templatemodels/stochasticprocessT.hpp>
#define _MIN_( a, b ) ( (a) < (b) ? (a) : (b) )
#define _MAX_( a, b ) ( (a) > (b) ? (a) : (b) )
namespace QuantLib {
// G2++ model
// r(t) = phi(t) + x(t) + y(t)
// dx(t) = -a x(t) dt + sigma dW_1(t)
// dy(t) = -b y(t) dt + eta dW_2(t)
// dB(t) = B(t) r(t) dt
// dW_1(t) dW_2(t) = rho dt
//
template <class DateType, class PassiveType, class ActiveType>
class G2ppT : public StochasticProcessT<DateType,PassiveType,ActiveType> {
private:
ActiveType sigma_, eta_, a_, b_, rho_;
Handle<YieldTermStructure> termStructure_; // the yield curve is
inline ActiveType V(DateType t) const {
ActiveType expat = exp(-a_*t);
ActiveType expbt = exp(-b_*t);
ActiveType cx = sigma_ / a_;
ActiveType cy = eta_ / b_;
ActiveType valuex = cx*cx*(t + (2.0*expat - 0.5*expat*expat - 1.5) / a_);
ActiveType valuey = cy*cy*(t + (2.0*expbt - 0.5*expbt*expbt - 1.5) / b_);
ActiveType value = 2.0*rho_*cx*cy* (t + (expat - 1.0) / a_
+ (expbt - 1.0) / b_
- (expat*expbt - 1.0) / (a_ + b_));
return valuex + valuey + value;
}
inline ActiveType A(DateType t, DateType T) const {
return termStructure_->discount(T) / termStructure_->discount(t) * exp(0.5*(V(T - t) - V(T) + V(t)));
}
inline ActiveType B(PassiveType x, DateType t) const {
return (1.0 - exp(-x*t)) / x;
}
public:
// constructor
G2ppT( const Handle<YieldTermStructure>& termStructure,
const ActiveType sigma,
const ActiveType eta,
const ActiveType a,
const ActiveType b,
const ActiveType rho )
: termStructure_(termStructure), sigma_(sigma), eta_(eta), a_(a), b_(b), rho_(rho) {
// check for valid parameter inputs
}
// stochastic process interface
// dimension of X = [ x, y, B ]
inline virtual size_t size() { return 3; }
// stochastic factors (x and y)
inline virtual size_t factors() { return 2; }
// initial values for simulation
inline virtual VecP initialValues() {
VecP X(3);
X[0] = 0.0; // x(t)
X[1] = 0.0; // y(t)
X[2] = 1.0; // B(t) bank account numeraire
return X;
}
// a[t,X(t)]
inline virtual VecA drift( const DateType t, const VecA& X) {
QL_FAIL("Drift is not implemented");
return VecA(0);
}
// b[t,X(t)]
inline virtual MatA diffusion( const DateType t, const VecA& X) {
QL_FAIL("Diffusion is not implemented");
return MatA(0);
}
// integrate X1 = X0 + drift()*dt + diffusion()*dW*sqrt(dt)
inline void evolve(const DateType t0, const VecA& X0, const DateType dt, const VecD& dW, VecA& X1) {
// ensure X1 has size of X0
ActiveType ExpX = X0[0] * exp(-a_*dt);
ActiveType ExpY = X0[1] * exp(-b_*dt);
ActiveType VarX = sigma_*sigma_ / 2.0 / a_*(1.0 - exp(-2.0*a_*dt));
ActiveType VarY = eta_ *eta_ / 2.0 / b_*(1.0 - exp(-2.0*b_*dt));
ActiveType CovXY = rho_*sigma_*eta_ / (a_ + b_)*(1.0 - exp(-(a_ + b_)*dt));
ActiveType corr = CovXY / sqrt(VarX) / sqrt(VarY);
ActiveType dZ = corr*dW[0] + sqrt(1 - corr*corr)*dW[1];
X1[0] = ExpX + sqrt(VarX)*dW[0];
X1[1] = ExpY + sqrt(VarY)*dZ;
// Brigo, Corollary 4.2.1
ActiveType expIntPhi = termStructure_->discount(t0) / termStructure_->discount(t0 + dt) * exp(0.5*(V(t0 + dt) - V(t0)));
ActiveType expIntX = exp(0.5*(X0[0] + X1[0])*dt); // numerical integration
ActiveType expIntY = exp(0.5*(X0[1] + X1[1])*dt); // numerical integration
X1[2] = X0[2] * expIntPhi * expIntX * expIntY; // using that r = phi + x + y
}
inline ActiveType zeroBond(const DateType t, const DateType T, const VecA& X) {
QL_REQUIRE(t <= T, "G2++ Model ZeroBond t <= T required");
if (t == T) return (ActiveType)1.0;
return A(t, T) * exp(-B(a_, (T - t))*X[0] - B(b_, (T - t))*X[1]); // assume X = [x, y, B]
}
inline ActiveType numeraire(const DateType t, const VecA& X) {
return X[2];
}
};
}
#undef _MIN_
#undef _MAX_
#endif /* ifndef quantlib_templateshiftedsabrmodel_hpp */
| 38.176923
| 132
| 0.531735
|
urgu00
|
fa66dcee1c507681a3ee361e1656ddfef366c021
| 3,242
|
cpp
|
C++
|
graph-source-code/445-C/7033658.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/445-C/7033658.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/445-C/7033658.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: GNU C++0x
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <string>
#include <cstdlib>
#include <set>
#include <map>
#include <fstream>
#define PI 3.14159265359
using namespace std;
typedef unsigned long long ull;
template <typename T>
void print2dvector(vector< vector<T> > v)
{
cout << "A 2d vector:" << endl;
int a = v.size();
int b = v[0].size();
if (a <= 15 && b <= 15)
{
for (int i=0; i<a; i++)
{
for (int j=0; j<b; j++)
{
cout << setw(4) << v[i][j];
}
cout << endl;
}
}
if (a > 15 && b > 15)
{
for (int i=0; i<9; i++)
{
for (int j = 0; j<9; j++)
{
cout << setw(4) << v[i][j];
}
cout << " " << ". . ." << setw(4) << v[i][b-3] << setw(4) << v[i][b-2] << setw(4) << v[i][b-1] << endl;
}
for (int i=0; i<15; i++)
{
cout << setw(4) << '.';
}
cout << endl;
for (int i=a-3; i<a; i++)
{
for (int j = 0; j<9; j++)
{
cout << setw(4) << v[i][j];
}
cout << " " << ". . ." << setw(4) << v[i][b-3] << setw(4) << v[i][b-2] << setw(4) << v[i][b-1] << endl;
}
}
if (a>15)
{
for (int i=0; i<9; i++)
{
for (int j=0; j<b; j++)
{
cout << setw(4) << v[i][j];
}
cout << endl;
}
for (int i=0; i<b; i++)
{
cout << setw(4) << '.';
}
cout << endl;
for (int i=a-3; i<a; i++)
{
for (int j = 0; j<b; j++)
{
cout << setw(4) << v[i][j];
}
cout << endl;
}
}
if (b>15)
{
for (int i=0; i<a; i++)
{
for (int j = 0; j<9; j++)
{
cout << setw(4) << v[i][j];
}
cout << " " << ". . ." << setw(4) << v[i][b-3] << setw(4) << v[i][b-2] << setw(4) << v[i][b-1] << endl;
}
}
}
template <typename T>
void printvector(vector<T> v)
{
cout << "A 1d vector:" << endl;
int a = v.size();
if (a <= 15)
{
for (int i=0; i<a; i++)
{
cout << setw(4) << v[i];
}
}
else
{
for (int i=0; i<9; i++)
{
cout << setw(4) << v[i];
}
cout << " " << ". . ." << setw(4) << v[a-3] << setw(4) << v[a-2] << setw(4) << v[a-1];
}
cout << endl;
}
int main()
{
int n, m;
scanf("%d %d", &n, &m);
vector<int> v(n, 0);
for(int i=0; i<n; i++)
{
scanf("%d", &v[i]);
}
double ans = 0;
int a, b, c;
for(int i=0; i<m; i++)
{
scanf("%d %d %d", &a, &b, &c);
ans = max(ans, 1.0*(v[a-1]+v[b-1])/c);
}
printf("%.12lf", ans);
return 0;
}
| 20.389937
| 122
| 0.317705
|
AmrARaouf
|
fa6b0f8ca1e8ca70fadd339abc1dab370544b02a
| 17,099
|
cpp
|
C++
|
WRK-V1.2/csharp/sccomp/bitset.cpp
|
intj-t/openvmsft
|
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
|
[
"Intel"
] | null | null | null |
WRK-V1.2/csharp/sccomp/bitset.cpp
|
intj-t/openvmsft
|
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
|
[
"Intel"
] | null | null | null |
WRK-V1.2/csharp/sccomp/bitset.cpp
|
intj-t/openvmsft
|
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
|
[
"Intel"
] | null | null | null |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
// ===========================================================================
// File: bitset.cpp
//
// BitSet implementation
// ===========================================================================
#include "stdafx.h"
/***************************************************************************************************
Initialize the bitset to all zeros. Make sure there is room for cbit bits. Uses the given
heap to allocate a BitSetImp (if needed).
***************************************************************************************************/
void BitSet::Init(int cbit, NRHEAP * heap)
{
// cbit should be non-negative and shouldn't overflow.
ASSERT(0 <= cbit && 0 <= (cbit + kcbitBlob - 1));
if (cbit <= kcbitSmall)
m_bits = 1;
else {
// Allocate at least kcbitBlob more bits than kcbitSmall.
// Then we'll always grow by at least kcbitBlob.
if (cbit < kcbitSmall + kcbitBlob)
cbit = kcbitSmall + kcbitBlob;
int cblob = (int)((uint)(cbit + kcbitBlob - 1) / kcbitBlob);
int cbTot = cblob * sizeof(Blob) + sizeof(BitSetImp);
BitSetImp * pbsi = (BitSetImp *)heap->AllocZero(cbTot);
pbsi->cblob = cblob;
m_bits = (Blob)pbsi;
ASSERT(!FSmall());
}
}
/***************************************************************************************************
Grow the bitset to accomodate at least cbit bits. This preserves any existing bits.
***************************************************************************************************/
void BitSet::Grow(int cbit, NRHEAP * heap)
{
if (!m_bits)
Init(cbit, heap);
else if (Cbit() >= cbit)
VSFAIL("Why is Grow being called?");
else if (FSmall()) {
Blob blob = m_bits >> 1;
Init(cbit, heap);
ASSERT(cbit <= Cbit());
// Preserve the previous bits.
Pbsi()->rgblob[0] = blob;
}
else {
BitSetImp * pbsi = Pbsi();
Init(cbit, heap);
ASSERT(cbit <= Cbit());
// Preserve the previous bits.
memcpy(Pbsi()->rgblob, pbsi->rgblob, pbsi->cblob * sizeof(Blob));
}
}
/***************************************************************************************************
Return true iff the given bit is set. If ibit >= Cbit(), returns false.
***************************************************************************************************/
bool BitSet::TestBit(int ibit)
{
ASSERT(0 <= ibit);
if (!m_bits)
return false;
if (FSmall())
return ibit < kcbitSmall && ((m_bits >> (ibit + 1)) & 1);
BitSetImp * pbsi = Pbsi();
int iblob = (uint)ibit / kcbitBlob;
return iblob < pbsi->cblob && ((pbsi->rgblob[iblob] >> ((uint)ibit % kcbitBlob)) & 1);
}
/***************************************************************************************************
Return true iff all the bits in the range [ibitMin, ibitLim) are set. If ibitLim > Cbit(),
returns false. If ibitMin == ibitLim, returns true (vacuous).
***************************************************************************************************/
bool BitSet::TestAllRange(int ibitMin, int ibitLim)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
if (ibitLim - ibitMin <= 1) {
if (ibitLim - ibitMin == 1)
return TestBit(ibitMin);
return true; // Vacuous
}
if (!m_bits)
return false;
if (FSmall()) {
if (ibitLim > kcbitSmall)
return false;
Blob blobMask = MaskSmall(ibitMin, ibitLim);
return (m_bits & blobMask) == blobMask;
}
MaskData md(ibitMin, ibitLim);
BitSetImp * pbsi = Pbsi();
if (md.iblobLast >= pbsi->cblob)
return false;
if ((pbsi->rgblob[md.iblobMin] & md.blobMaskMin) != md.blobMaskMin)
return false;
if (md.iblobMin >= md.iblobLast)
return true;
return (pbsi->rgblob[md.iblobLast] & md.blobMaskLast) == md.blobMaskLast &&
AreBitsOne(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1);
}
/***************************************************************************************************
Returns true iff any bits in the range [ibitMin, ibitLim) are set.
***************************************************************************************************/
bool BitSet::TestAnyRange(int ibitMin, int ibitLim)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
if (ibitLim - ibitMin <= 1) {
if (ibitLim - ibitMin == 1)
return TestBit(ibitMin);
return false;
}
if (!m_bits)
return false;
if (FSmall()) {
if (ibitMin >= kcbitSmall)
return false;
if (ibitLim > kcbitSmall)
ibitLim = kcbitSmall;
Blob blobMask = MaskSmall(ibitMin, ibitLim);
return (m_bits & blobMask) != 0;
}
MaskData md(ibitMin, ibitLim);
BitSetImp * pbsi = Pbsi();
if (md.iblobMin >= pbsi->cblob)
return false;
if ((pbsi->rgblob[md.iblobMin] & md.blobMaskMin) != 0)
return true;
if (md.iblobLast >= pbsi->cblob)
md.iblobLast = pbsi->cblob;
else if ((pbsi->rgblob[md.iblobLast] & md.blobMaskLast) != 0)
return true;
return !AreBitsZero(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1);
}
/***************************************************************************************************
Returns true iff any bits in the range [0, infinity) are set.
***************************************************************************************************/
bool BitSet::TestAnyBits()
{
if (!m_bits)
return false;
if (FSmall())
return m_bits != 1;
BitSetImp * pbsi = Pbsi();
return !AreBitsZero(pbsi->rgblob, pbsi->cblob);
}
/***************************************************************************************************
Returns true iff there are any bits that are set in both this bitset and bsetCheck.
***************************************************************************************************/
bool BitSet::TestAnyBits(BitSet & bsetCheck)
{
if (!m_bits || !bsetCheck.m_bits)
return false;
if (FSmall()) {
if (bsetCheck.FSmall())
return (m_bits & bsetCheck.m_bits) != 1;
ASSERT(bsetCheck.Pbsi()->cblob > 0);
return (bsetCheck.Pbsi()->rgblob[0] & (m_bits >> 1)) != 0;
}
BitSetImp * pbsi1 = Pbsi();
ASSERT(pbsi1->cblob > 0);
if (bsetCheck.FSmall())
return (pbsi1->rgblob[0] & (bsetCheck.m_bits >> 1)) != 0;
BitSetImp * pbsi2 = bsetCheck.Pbsi();
ASSERT(pbsi2->cblob > 0);
for (int iblob = min(pbsi1->cblob, pbsi2->cblob); --iblob >= 0; ) {
if (pbsi1->rgblob[iblob] & pbsi2->rgblob[iblob])
return true;
}
return false;
}
/***************************************************************************************************
Sets the bit at position ibit, ensuring that the bitset is large enough.
***************************************************************************************************/
void BitSet::SetBit(int ibit, NRHEAP * heap)
{
// ibit should be non-negative and shouldn't overflow.
ASSERT(0 <= ibit && 0 <= (ibit + kcbitBlob - 1));
if (ibit >= Cbit())
Grow(ibit + 1, heap);
if (FSmall())
m_bits |= MaskSmall(ibit);
else {
BitSetImp * pbsi = Pbsi();
pbsi->rgblob[(uint)ibit / kcbitBlob] |= ((Blob)1 << ((uint)ibit % kcbitBlob));
}
}
/***************************************************************************************************
Clear all the bits in the bitset, but don't discard any memory allocated.
***************************************************************************************************/
void BitSet::ClearAll()
{
if (FSmall())
m_bits = 1;
else if (m_bits) {
BitSetImp * pbsi = Pbsi();
SetBlobs(pbsi->rgblob, pbsi->cblob, 0);
}
}
/***************************************************************************************************
Clear the given bit. If the bit is out of the range of the bitset, it is already considered
cleared, so nothing is changed.
***************************************************************************************************/
void BitSet::ClearBit(int ibit)
{
ASSERT(0 <= ibit);
if (FSmall()) {
if (ibit < kcbitSmall)
m_bits &= ~MaskSmall(ibit);
}
else if (m_bits) {
BitSetImp * pbsi = Pbsi();
int iblob = (uint)ibit / kcbitBlob;
if (iblob < pbsi->cblob)
pbsi->rgblob[iblob] &= ~((Blob)1 << ((uint)ibit % kcbitBlob));
}
}
/***************************************************************************************************
Set the range of bits [ibitMin, ibitLim), growing the bitset if needed.
***************************************************************************************************/
void BitSet::SetBitRange(int ibitMin, int ibitLim, NRHEAP * heap)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
if (ibitLim - ibitMin <= 1) {
if (1 == ibitLim - ibitMin)
SetBit(ibitMin, heap);
return;
}
if (ibitLim > Cbit())
Grow(ibitLim, heap);
ASSERT(ibitLim <= Cbit());
if (FSmall()) {
m_bits |= MaskSmall(ibitMin, ibitLim);
return;
}
BitSetImp * pbsi = Pbsi();
MaskData md(ibitMin, ibitLim);
pbsi->rgblob[md.iblobMin] |= md.blobMaskMin;
if (md.iblobMin >= md.iblobLast)
return;
SetBlobs(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1, ~(Blob)0);
pbsi->rgblob[md.iblobLast] |= md.blobMaskLast;
}
/***************************************************************************************************
Clear the range of bits [ibitMin, ibitLim).
***************************************************************************************************/
void BitSet::ClearBitRange(int ibitMin, int ibitLim)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
int cbit = Cbit();
if (ibitLim > cbit)
ibitLim = cbit;
if (ibitMin >= ibitLim)
return;
ASSERT(0 <= ibitMin && ibitMin < ibitLim && ibitLim <= Cbit());
if (1 == ibitLim - ibitMin) {
ClearBit(ibitMin);
return;
}
if (FSmall()) {
m_bits &= ~MaskSmall(ibitMin, ibitLim);
return;
}
BitSetImp * pbsi = Pbsi();
MaskData md(ibitMin, ibitLim);
pbsi->rgblob[md.iblobMin] &= ~md.blobMaskMin;
if (md.iblobMin >= md.iblobLast)
return;
SetBlobs(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1, 0);
pbsi->rgblob[md.iblobLast] &= ~md.blobMaskLast;
}
/***************************************************************************************************
Set the bitset to a copy of bset.
***************************************************************************************************/
void BitSet::Set(BitSet & bset, NRHEAP * heap)
{
ASSERT(this != &bset);
if (!bset.m_bits) {
ClearAll();
return;
}
int cbit = bset.Cbit();
if (Cbit() < cbit)
Init(cbit, heap);
if (FSmall()) {
ASSERT(bset.FSmall());
m_bits = bset.m_bits;
return;
}
BitSetImp * pbsiDst = Pbsi();
if (bset.FSmall()) {
pbsiDst->rgblob[0] = bset.m_bits >> 1;
SetBlobs(pbsiDst->rgblob + 1, pbsiDst->cblob - 1, 0);
return;
}
BitSetImp * pbsiSrc = bset.Pbsi();
ASSERT(pbsiDst->cblob >= pbsiSrc->cblob);
memcpy(pbsiDst->rgblob, pbsiSrc->rgblob, SizeMul(pbsiSrc->cblob, sizeof(Blob)));
if (pbsiDst->cblob > pbsiSrc->cblob)
SetBlobs(pbsiDst->rgblob + pbsiSrc->cblob, pbsiDst->cblob - pbsiSrc->cblob, 0);
}
/***************************************************************************************************
Return true iff this bitset contains the same set as bset.
***************************************************************************************************/
bool BitSet::Equals(BitSet & bset)
{
if (m_bits == bset.m_bits)
return true;
if (!m_bits)
return !bset.TestAnyBits();
if (!bset.m_bits)
return !TestAnyBits();
BitSetImp * pbsi;
if (FSmall()) {
if (bset.FSmall())
return false;
pbsi = bset.Pbsi();
return (pbsi->rgblob[0] == (m_bits >> 1)) &&
AreBitsZero(pbsi->rgblob + 1, pbsi->cblob - 1);
}
if (bset.FSmall()) {
pbsi = Pbsi();
return (pbsi->rgblob[0] == (bset.m_bits >> 1)) &&
AreBitsZero(pbsi->rgblob + 1, pbsi->cblob - 1);
}
pbsi = Pbsi();
BitSetImp * pbsi2 = bset.Pbsi();
int cblob = min(pbsi->cblob, pbsi2->cblob);
if (memcmp(pbsi->rgblob, pbsi2->rgblob, SizeMul(cblob, sizeof(Blob))))
return false;
if (pbsi->cblob == pbsi2->cblob)
return true;
if (cblob < pbsi->cblob)
return AreBitsZero(pbsi->rgblob + cblob, pbsi->cblob - cblob);
ASSERT(cblob < pbsi2->cblob);
return AreBitsZero(pbsi2->rgblob + cblob, pbsi2->cblob - cblob);
}
/***************************************************************************************************
Ensures that any bits that are set in bset are also set in this bitset.
***************************************************************************************************/
void BitSet::Union(BitSet & bset, NRHEAP * heap)
{
int cbitSrc = bset.Cbit();
if (!cbitSrc)
return;
if (Cbit() < cbitSrc)
Grow(cbitSrc, heap);
ASSERT(Cbit() >= cbitSrc);
if (FSmall()) {
ASSERT(bset.FSmall());
m_bits |= bset.m_bits;
}
else if (bset.FSmall())
Pbsi()->rgblob[0] |= bset.m_bits >> 1;
else {
BitSetImp * pbsiDst = Pbsi();
BitSetImp * pbsiSrc = bset.Pbsi();
for (int iblob = pbsiSrc->cblob; --iblob >= 0; )
pbsiDst->rgblob[iblob] |= pbsiSrc->rgblob[iblob];
}
}
/***************************************************************************************************
Ensures that any bits that are clear in bset are also clear in this bitset. Returns true iff
this bitset changes as a result (ie, if this bitset "shrunk").
***************************************************************************************************/
bool BitSet::FIntersectChanged(BitSet & bset)
{
BitSetImp * pbsiDst;
if (m_bits <= 1)
return false;
if (bset.m_bits <= 1) {
if (FSmall())
m_bits = 1;
else {
pbsiDst = Pbsi();
if (AreBitsZero(pbsiDst->rgblob, pbsiDst->cblob))
return false;
ClearAll();
}
return true;
}
if (FSmall()) {
Blob blob = bset.FSmall() ? bset.m_bits : ((bset.Pbsi()->rgblob[0] << 1) | 1);
return AndBlobChanged(m_bits, blob);
}
bool fChanged;
int cblob;
pbsiDst = Pbsi();
if (bset.FSmall()) {
fChanged = AndBlobChanged(pbsiDst->rgblob[0], bset.m_bits >> 1);
cblob = 1;
}
else {
BitSetImp * pbsiSrc = bset.Pbsi();
cblob = min(pbsiDst->cblob, pbsiSrc->cblob);
fChanged = false;
for (int iblob = cblob; --iblob >= 0; )
fChanged |= AndBlobChanged(pbsiDst->rgblob[iblob], pbsiSrc->rgblob[iblob]);
}
if (pbsiDst->cblob == cblob || AreBitsZero(pbsiDst->rgblob + cblob, pbsiDst->cblob - cblob))
return fChanged;
SetBlobs(pbsiDst->rgblob + cblob, pbsiDst->cblob - cblob, 0);
return true;
}
/***************************************************************************************************
Ensures that any bits that are clear in bset are also clear in this bitset.
***************************************************************************************************/
void BitSet::Intersect(BitSet & bset)
{
if (m_bits <= 1)
return;
if (bset.m_bits <= 1) {
ClearAll();
return;
}
if (FSmall()) {
Blob blob = bset.FSmall() ? bset.m_bits : ((bset.Pbsi()->rgblob[0] << 1) | 1);
m_bits &= blob;
return;
}
BitSetImp * pbsiDst = Pbsi();
int cblob;
if (bset.FSmall()) {
pbsiDst->rgblob[0] &= bset.m_bits >> 1;
cblob = 1;
}
else {
BitSetImp * pbsiSrc = bset.Pbsi();
cblob = min(pbsiDst->cblob, pbsiSrc->cblob);
for (int iblob = cblob; --iblob >= 0; )
pbsiDst->rgblob[iblob] &= pbsiSrc->rgblob[iblob];
}
if (pbsiDst->cblob > cblob)
SetBlobs(pbsiDst->rgblob + cblob, pbsiDst->cblob - cblob, 0);
}
| 32.140977
| 100
| 0.450494
|
intj-t
|
fa6c012b93520ec881141c8547bc1337327463da
| 3,633
|
hpp
|
C++
|
include/UnityEngine/U2D/SpriteAtlasManager.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/U2D/SpriteAtlasManager.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/U2D/SpriteAtlasManager.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: UnityEngine::U2D
namespace UnityEngine::U2D {
// Forward declaring type: SpriteAtlas
class SpriteAtlas;
}
// Completed forward declares
// Type namespace: UnityEngine.U2D
namespace UnityEngine::U2D {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.U2D.SpriteAtlasManager
// [NativeHeaderAttribute] Offset: D90E44
// [StaticAccessorAttribute] Offset: D90E44
// [NativeHeaderAttribute] Offset: D90E44
class SpriteAtlasManager : public ::Il2CppObject {
public:
// Creating value type constructor for type: SpriteAtlasManager
SpriteAtlasManager() noexcept {}
// [CompilerGeneratedAttribute] Offset: 0xD93EC8
// [DebuggerBrowsableAttribute] Offset: 0xD93EC8
// Get static field: static private System.Action`2<System.String,System.Action`1<UnityEngine.U2D.SpriteAtlas>> atlasRequested
static System::Action_2<::Il2CppString*, System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>* _get_atlasRequested();
// Set static field: static private System.Action`2<System.String,System.Action`1<UnityEngine.U2D.SpriteAtlas>> atlasRequested
static void _set_atlasRequested(System::Action_2<::Il2CppString*, System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>* value);
// [CompilerGeneratedAttribute] Offset: 0xD93F04
// [DebuggerBrowsableAttribute] Offset: 0xD93F04
// Get static field: static private System.Action`1<UnityEngine.U2D.SpriteAtlas> atlasRegistered
static System::Action_1<UnityEngine::U2D::SpriteAtlas*>* _get_atlasRegistered();
// Set static field: static private System.Action`1<UnityEngine.U2D.SpriteAtlas> atlasRegistered
static void _set_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value);
// static private System.Boolean RequestAtlas(System.String tag)
// Offset: 0x2306B98
static bool RequestAtlas(::Il2CppString* tag);
// static public System.Void add_atlasRegistered(System.Action`1<UnityEngine.U2D.SpriteAtlas> value)
// Offset: 0x2306C94
static void add_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value);
// static public System.Void remove_atlasRegistered(System.Action`1<UnityEngine.U2D.SpriteAtlas> value)
// Offset: 0x2306D84
static void remove_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value);
// static private System.Void PostRegisteredAtlas(UnityEngine.U2D.SpriteAtlas spriteAtlas)
// Offset: 0x2306E74
static void PostRegisteredAtlas(UnityEngine::U2D::SpriteAtlas* spriteAtlas);
// static System.Void Register(UnityEngine.U2D.SpriteAtlas spriteAtlas)
// Offset: 0x2306F00
static void Register(UnityEngine::U2D::SpriteAtlas* spriteAtlas);
// static private System.Void .cctor()
// Offset: 0x2306F40
static void _cctor();
}; // UnityEngine.U2D.SpriteAtlasManager
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::U2D::SpriteAtlasManager*, "UnityEngine.U2D", "SpriteAtlasManager");
| 51.169014
| 131
| 0.730526
|
darknight1050
|
fa73bc930dbdce149f3b39567c17ef2558ba1e20
| 5,230
|
cc
|
C++
|
src/atlas/grid/detail/spacing/gaussian/N256.cc
|
mlange05/atlas
|
d8198435a9e39fbf67bfc467fe734203414af608
|
[
"Apache-2.0"
] | null | null | null |
src/atlas/grid/detail/spacing/gaussian/N256.cc
|
mlange05/atlas
|
d8198435a9e39fbf67bfc467fe734203414af608
|
[
"Apache-2.0"
] | null | null | null |
src/atlas/grid/detail/spacing/gaussian/N256.cc
|
mlange05/atlas
|
d8198435a9e39fbf67bfc467fe734203414af608
|
[
"Apache-2.0"
] | null | null | null |
// TL511
#include "atlas/grid/detail/spacing/gaussian/N.h"
namespace atlas {
namespace grid {
namespace spacing {
namespace gaussian {
DEFINE_GAUSSIAN_LATITUDES(
256, LIST( 89.731148618413, 89.382873896334, 89.032542423790, 88.681746243591, 88.330773788807, 87.979716034326,
87.628610609484, 87.277475867224, 86.926321817646, 86.575154382095, 86.223977286346, 85.872792991467,
85.521603188281, 85.170409076734, 84.819211531931, 84.468011207066, 84.116808599553, 83.765604094844,
83.414397996248, 83.063190545702, 82.711981938543, 82.360772334213, 82.009561864138, 81.658350637624,
81.307138746324, 80.955926267657, 80.604713267476, 80.253499802142, 79.902285920181, 79.551071663595,
79.199857068926, 78.848642168112, 78.497426989195, 78.146211556892, 77.794995893075, 77.443780017172,
77.092563946496, 76.741347696526, 76.390131281143, 76.038914712832, 75.687698002854, 75.336481161390,
74.985264197669, 74.634047120076, 74.282829936248, 73.931612653153, 73.580395277164, 73.229177814120,
72.877960269381, 72.526742647876, 72.175524954146, 71.824307192381, 71.473089366452, 71.121871479946,
70.770653536183, 70.419435538248, 70.068217489009, 69.716999391133, 69.365781247107, 69.014563059252,
68.663344829736, 68.312126560585, 67.960908253699, 67.609689910856, 67.258471533726, 66.907253123876,
66.556034682780, 66.204816211827, 65.853597712321, 65.502379185494, 65.151160632510, 64.799942054463,
64.448723452393, 64.097504827279, 63.746286180050, 63.395067511586, 63.043848822719, 62.692630114242,
62.341411386903, 61.990192641418, 61.638973878463, 61.287755098684, 60.936536302693, 60.585317491076,
60.234098664389, 59.882879823163, 59.531660967905, 59.180442099098, 58.829223217203, 58.478004322663,
58.126785415899, 57.775566497315, 57.424347567296, 57.073128626212, 56.721909674418, 56.370690712253,
56.019471740043, 55.668252758099, 55.317033766721, 54.965814766198, 54.614595756804, 54.263376738806,
53.912157712459, 53.560938678008, 53.209719635690, 52.858500585731, 52.507281528350, 52.156062463759,
51.804843392159, 51.453624313747, 51.102405228712, 50.751186137234, 50.399967039491, 50.048747935650,
49.697528825877, 49.346309710328, 48.995090589156, 48.643871462509, 48.292652330530, 47.941433193356,
47.590214051120, 47.238994903953, 46.887775751977, 46.536556595315, 46.185337434084, 45.834118268396,
45.482899098363, 45.131679924089, 44.780460745679, 44.429241563233, 44.078022376847, 43.726803186616,
43.375583992632, 43.024364794983, 42.673145593755, 42.321926389033, 41.970707180896, 41.619487969425,
41.268268754697, 40.917049536785, 40.565830315762, 40.214611091700, 39.863391864666, 39.512172634728,
39.160953401950, 38.809734166396, 38.458514928128, 38.107295687205, 37.756076443686, 37.404857197628,
37.053637949087, 36.702418698117, 36.351199444770, 35.999980189098, 35.648760931151, 35.297541670979,
34.946322408628, 34.595103144147, 34.243883877579, 33.892664608970, 33.541445338363, 33.190226065800,
32.839006791323, 32.487787514973, 32.136568236789, 31.785348956809, 31.434129675072, 31.082910391614,
30.731691106472, 30.380471819681, 30.029252531276, 29.678033241291, 29.326813949758, 28.975594656711,
28.624375362181, 28.273156066200, 27.921936768798, 27.570717470004, 27.219498169849, 26.868278868361,
26.517059565568, 26.165840261498, 25.814620956179, 25.463401649636, 25.112182341895, 24.760963032984,
24.409743722926, 24.058524411747, 23.707305099470, 23.356085786120, 23.004866471720, 22.653647156293,
22.302427839862, 21.951208522449, 21.599989204076, 21.248769884764, 20.897550564535, 20.546331243409,
20.195111921408, 19.843892598551, 19.492673274857, 19.141453950348, 18.790234625041, 18.439015298957,
18.087795972114, 17.736576644529, 17.385357316222, 17.034137987211, 16.682918657513, 16.331699327146,
15.980479996126, 15.629260664472, 15.278041332199, 14.926821999325, 14.575602665866, 14.224383331838,
13.873163997257, 13.521944662139, 13.170725326500, 12.819505990355, 12.468286653719, 12.117067316609,
11.765847979038, 11.414628641021, 11.063409302574, 10.712189963711, 10.360970624447, 10.009751284795,
9.658531944770, 9.307312604387, 8.956093263659, 8.604873922599, 8.253654581223, 7.902435239543,
7.551215897573, 7.199996555326, 6.848777212817, 6.497557870058, 6.146338527062, 5.795119183843,
5.443899840414, 5.092680496788, 4.741461152978, 4.390241808997, 4.039022464858, 3.687803120573,
3.336583776155, 2.985364431618, 2.634145086974, 2.282925742235, 1.931706397414, 1.580487052524,
1.229267707577, 0.878048362586, 0.526829017564, 0.175609672524 ) )
} // namespace gaussian
} // namespace spacing
} // namespace grid
} // namespace atlas
| 88.644068
| 116
| 0.7174
|
mlange05
|
fa767dffcfd85faec8c76169b414c96c96c625ea
| 28,938
|
cpp
|
C++
|
src/resolver/sleefResolver.cpp
|
sx-aurora-test/rv
|
5d546958b155d7349b20a8cbbeff1b4c65589fd7
|
[
"Apache-2.0"
] | null | null | null |
src/resolver/sleefResolver.cpp
|
sx-aurora-test/rv
|
5d546958b155d7349b20a8cbbeff1b4c65589fd7
|
[
"Apache-2.0"
] | null | null | null |
src/resolver/sleefResolver.cpp
|
sx-aurora-test/rv
|
5d546958b155d7349b20a8cbbeff1b4c65589fd7
|
[
"Apache-2.0"
] | null | null | null |
//===- sleefLibrary.cpp -----------------------------===//
//
// The Region Vectorizer
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <llvm/Support/SourceMgr.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Dominators.h>
#include <llvm/Analysis/PostDominators.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/ScalarEvolution.h>
#include <llvm/Analysis/MemoryDependenceAnalysis.h>
#include <llvm/Analysis/BranchProbabilityInfo.h>
#include <llvm/Passes/PassBuilder.h>
#include "llvm/Transforms/Utils/LCSSA.h"
#include "rv/PlatformInfo.h"
#include "utils/rvTools.h"
#include "utils/rvLinking.h"
#include "rvConfig.h"
#include "rv/rv.h"
#include "rv/utils.h"
#include "rv/region/FunctionRegion.h"
#include "rv/transform/singleReturnTrans.h"
#include "rv/transform/loopExitCanonicalizer.h"
#include "report.h"
#include <llvm/IR/Verifier.h>
#include <vector>
#include <sstream>
#if 1
#define IF_DEBUG_SLEEF IF_DEBUG
#else
#define IF_DEBUG_SLEEF if (true)
#endif
// used for on-demand mappings
//
using namespace llvm;
// vector-length agnostic
extern "C" {
#define EXTERNAL_GENBC_BUFFER(NAME) \
extern const unsigned char * NAME##_Buffer; \
extern const size_t NAME##_BufferLen;
#define EMPTY_GENBC_BUFFER(NAME) \
const unsigned char * NAME##_Buffer = nullptr; \
const size_t NAME##_BufferLen = 0;
#ifdef RV_ENABLE_SLEEF
EXTERNAL_GENBC_BUFFER(rempitab)
EXTERNAL_GENBC_BUFFER(vla_sp)
EXTERNAL_GENBC_BUFFER(vla_dp)
#else
EMPTY_GENBC_BUFFER(rempitab)
EMPTY_GENBC_BUFFER(vla_sp)
EMPTY_GENBC_BUFFER(vla_dp)
#endif
#ifdef RV_ENABLE_ADVSIMD
EXTERNAL_GENBC_BUFFER(advsimd_extras)
EXTERNAL_GENBC_BUFFER(advsimd_sp)
EXTERNAL_GENBC_BUFFER(advsimd_dp)
#else
EMPTY_GENBC_BUFFER(advsimd_extras)
EMPTY_GENBC_BUFFER(advsimd_sp)
EMPTY_GENBC_BUFFER(advsimd_dp)
#endif
#ifdef RV_ENABLE_X86
EXTERNAL_GENBC_BUFFER(avx512_extras)
EXTERNAL_GENBC_BUFFER(avx512_sp)
EXTERNAL_GENBC_BUFFER(avx512_dp)
EXTERNAL_GENBC_BUFFER(avx2_extras)
EXTERNAL_GENBC_BUFFER(avx2_sp)
EXTERNAL_GENBC_BUFFER(avx2_dp)
EXTERNAL_GENBC_BUFFER(avx_sp)
EXTERNAL_GENBC_BUFFER(avx_dp)
EXTERNAL_GENBC_BUFFER(sse_sp)
EXTERNAL_GENBC_BUFFER(sse_dp)
#else
EMPTY_GENBC_BUFFER(avx512_extras)
EMPTY_GENBC_BUFFER(avx512_sp)
EMPTY_GENBC_BUFFER(avx512_dp)
EMPTY_GENBC_BUFFER(avx2_extras)
EMPTY_GENBC_BUFFER(avx2_sp)
EMPTY_GENBC_BUFFER(avx2_dp)
EMPTY_GENBC_BUFFER(avx_sp)
EMPTY_GENBC_BUFFER(avx_dp)
EMPTY_GENBC_BUFFER(sse_sp)
EMPTY_GENBC_BUFFER(sse_dp)
#endif
} // extern "C"
#undef EMPTY_GENBC_BUFFER
#undef EXTERNAL_GENBC_BUFFER
namespace rv {
// internal structures for named mappings (without fancily shaped arguments)
struct PlainVecDesc {
std::string scalarFnName;
std::string vectorFnName;
int vectorWidth;
PlainVecDesc(std::string _scalarName, std::string _vectorName, int _width)
: scalarFnName(_scalarName), vectorFnName(_vectorName), vectorWidth(_width)
{}
PlainVecDesc()
: scalarFnName()
, vectorFnName()
, vectorWidth(0)
{}
};
using PlainVecDescVector = std::vector<PlainVecDesc>;
using AddToListFuncType = std::function<void(const PlainVecDescVector&, bool)>;
enum SleefISA {
SLEEF_VLA = 0,
SLEEF_SSE = 1,
SLEEF_AVX = 2,
SLEEF_AVX2 = 3,
SLEEF_AVX512 = 4,
SLEEF_ADVSIMD = 5,
SLEEF_Enum_Entries = 6
};
inline int sleefModuleIndex(SleefISA isa, bool doublePrecision) {
return int(isa) + (doublePrecision ? (int) SLEEF_Enum_Entries : 0);
}
static const size_t sleefModuleBufferLens[] = {
vla_sp_BufferLen,
sse_sp_BufferLen,
avx_sp_BufferLen,
avx2_sp_BufferLen,
avx512_sp_BufferLen,
advsimd_sp_BufferLen,
vla_dp_BufferLen,
sse_dp_BufferLen,
avx_dp_BufferLen,
avx2_dp_BufferLen,
avx512_dp_BufferLen,
advsimd_dp_BufferLen,
};
static const unsigned char** sleefModuleBuffers[] = {
&vla_sp_Buffer,
&sse_sp_Buffer,
&avx_sp_Buffer,
&avx2_sp_Buffer,
&avx512_sp_Buffer,
&advsimd_sp_Buffer,
&vla_dp_Buffer,
&sse_dp_Buffer,
&avx_dp_Buffer,
&avx2_dp_Buffer,
&avx512_dp_Buffer,
&advsimd_dp_Buffer,
};
static const size_t extraModuleBufferLens[] = {
0, // VLA
0, // SSE
0, // AVX
avx2_extras_BufferLen,
avx512_extras_BufferLen,
advsimd_extras_BufferLen,
};
static const unsigned char** extraModuleBuffers[] = {
nullptr, // VLA
nullptr, // SSE
nullptr, // AVX
&avx2_extras_Buffer,
&avx512_extras_Buffer,
&advsimd_extras_Buffer,
};
static Module *sleefModules[SLEEF_Enum_Entries * 2];
static Module *extraModules[SLEEF_Enum_Entries * 2];
static Module &requestSharedModule(LLVMContext &Ctx) {
static Module *SharedModule = nullptr;
if (!SharedModule)
SharedModule =
createModuleFromBuffer(reinterpret_cast<const char *>(&rempitab_Buffer),
rempitab_BufferLen, Ctx);
assert(SharedModule);
return *SharedModule;
}
const LinkerCallback SharedModuleLookup = [](GlobalValue& GV, Module& M) -> Value * {
IF_DEBUG_SLEEF {
errs() << "SharedModuleLookup: " << GV.getName() << "\n";
}
// Definition available
if (!GV.isDeclaration())
return &GV;
// Ignore intrinsic decls
auto *F = dyn_cast<Function>(&GV);
if (F && F->getIntrinsicID() != Intrinsic::not_intrinsic)
return nullptr;
// Lookup symbol in shared 'rempitab' module
auto &SharedMod = requestSharedModule(M.getContext());
auto *SharedGV = SharedMod.getNamedValue(GV.getName());
// N/a in the shared module -> back to the original source.
if (!SharedGV)
return nullptr;
IF_DEBUG_SLEEF {
errs() << "Pulling shared global: " << SharedGV->getName() << "\n";
}
// Don't recurse into lookup
GlobalVariable * ClonedGV = cast<GlobalVariable>(&cloneGlobalIntoModule(*SharedGV, M, nullptr));
// Uniquify the 'rempitab' constant globals.
ClonedGV->setLinkage(GlobalVariable::LinkOnceODRLinkage);
return ClonedGV;
};
static
void
InitSleefMappings(PlainVecDescVector & archMappings, int floatWidth, int doubleWidth) {
PlainVecDescVector VecFuncs = {
{"ilogbf", "xilogbf", floatWidth},
{"fmaf", "xfmaf", floatWidth},
{"fabsf", "xfabsf", floatWidth},
{"copysignf", "xcopysignf", floatWidth},
{"fmaxf", "xfmaxf", floatWidth},
{"fminf", "xfminf", floatWidth},
{"fdimf", "xfdimf", floatWidth},
{"truncf", "xtruncf", floatWidth},
{"floorf", "xfloorf", floatWidth},
{"ceilf", "xceilf", floatWidth},
{"roundf", "xroundf", floatWidth},
{"rintf", "xrintf", floatWidth},
{"nextafterf", "xnextafterf", floatWidth},
{"frfrexpf", "xfrfrexpf", floatWidth},
{"expfrexpf", "xexpfrexpf", floatWidth},
{"fmodf", "xfmodf", floatWidth},
{"modff", "xmodff", floatWidth},
{"ilogb", "xilogb", doubleWidth},
{"fma", "xfma", doubleWidth},
{"fabs", "xfabs", doubleWidth},
{"copysign", "xcopysign", doubleWidth},
{"fmax", "xfmax", doubleWidth},
{"fmin", "xfmin", doubleWidth},
{"fdim", "xfdim", doubleWidth},
{"trunc", "xtrunc", doubleWidth},
{"floor", "xfloor", doubleWidth},
{"ceil", "xceil", doubleWidth},
{"round", "xround", doubleWidth},
{"rint", "xrint", doubleWidth},
{"nextafter", "xnextafter", doubleWidth},
{"frfrexp", "xfrfrexp", doubleWidth},
{"expfrexp", "xexpfrexp", doubleWidth},
{"fmod", "xfmod", doubleWidth},
{"modf", "xmodf", floatWidth},
{"llvm.floor.f32", "xfloorf", floatWidth},
{"llvm.fabs.f32", "xfabsf", floatWidth},
{"llvm.copysign.f32", "xcopysignf", floatWidth},
{"llvm.minnum.f32", "xfminf", floatWidth},
{"llvm.maxnum.f32", "xfmaxf", floatWidth},
{"llvm.floor.f64", "xfloor", doubleWidth},
{"llvm.fabs.f64", "xfabs", doubleWidth},
{"llvm.copysign.f64", "xcopysign", doubleWidth},
{"llvm.minnum.f64", "xfmin", doubleWidth},
{"llvm.maxnum.f64", "xfmax", doubleWidth},
#if 0
// TODO VLA random number generator
// extras
{"drand48", "vrand_extra_vla", 2},
{"frand48", "vrand_extra_vla", 4}
#endif
#define ALSO_FINITE(IRNAME, SLEEFNAME, WIDTH) \
{#IRNAME, #SLEEFNAME, WIDTH}, \
{"__" #IRNAME "_finite", #SLEEFNAME, floatWidth}
#define ALSO_FINITE_ULP(IRNAME, ULP, SLEEFNAME, WIDTH) \
{#IRNAME, #SLEEFNAME, WIDTH}, \
{"__" #IRNAME "_" #ULP "_finite", #SLEEFNAME, floatWidth}
// EXPORT CONST vfloat __atan2f_finite (vfloat, vfloat) __attribute__((weak, alias(str_xatan2f_u1 )));
// EXPORT CONST vfloat __fmodf_finite (vfloat, vfloat) __attribute__((weak, alias(str_xfmodf )));
// EXPORT CONST vfloat __modff_finite (vfloat, vfloat *) __attribute__((weak, alias(str_xmodff )));
// EXPORT CONST vfloat __hypotf_u05_finite(vfloat, vfloat) __attribute__((weak, alias(str_xhypotf_u05)));
// TODO: Auto-generate this from some API header/description file.
ALSO_FINITE(acosf,xacosf, floatWidth),
ALSO_FINITE(acoshf,xacoshf, floatWidth),
ALSO_FINITE(acoshf,xacoshf,floatWidth),
ALSO_FINITE(asinf,xasinf, floatWidth),
ALSO_FINITE(asinhf, xasinhf, floatWidth),
ALSO_FINITE(atan2f,xatan2f, floatWidth),
ALSO_FINITE(atanf,xatanf, floatWidth),
ALSO_FINITE(atanhf,xatanhf,floatWidth),
ALSO_FINITE(cbrtf,xcbrtf, floatWidth),
ALSO_FINITE(cosf,xcosf, floatWidth),
ALSO_FINITE(coshf, xcoshf, floatWidth),
ALSO_FINITE(erfcf,xerfcf, floatWidth),
ALSO_FINITE(erff,xerff, floatWidth),
ALSO_FINITE(exp10f,xexp10f, floatWidth),
ALSO_FINITE(exp2f,xexp2f, floatWidth),
ALSO_FINITE(expf,xexpf,floatWidth),
ALSO_FINITE(expm1f,xexpm1f, floatWidth),
ALSO_FINITE(log10f,xlog10f,floatWidth),
ALSO_FINITE(log1pf,xlog1pf,floatWidth),
ALSO_FINITE(logf,xlogf, floatWidth),
ALSO_FINITE(powf,xpowf,floatWidth),
ALSO_FINITE(sinf,xsinf, floatWidth),
ALSO_FINITE(sinhf,xsinhf, floatWidth),
ALSO_FINITE(sqrtf,xsqrtf,floatWidth),
ALSO_FINITE(tanf,xtanf, floatWidth),
ALSO_FINITE(tanhf, xtanhf, floatWidth),
ALSO_FINITE_ULP(hypotf,u05,xhypotf,floatWidth),
ALSO_FINITE_ULP(lgammaf,u1,xlgammaf, floatWidth),
ALSO_FINITE_ULP(tgammaf,u1,xtgammaf, floatWidth),
#undef ALSO_FINITE
#undef ALSO_FINITE_ULP
{"sin", "xsin", doubleWidth},
{"cos", "xcos", doubleWidth},
{"tan", "xtan", doubleWidth},
{"asin", "xasin", doubleWidth},
{"acos", "xacos", doubleWidth},
{"atan", "xatan", doubleWidth},
{"atan2", "xatan2", doubleWidth},
{"log", "xlog", doubleWidth},
{"cbrt", "xcbrt", doubleWidth},
{"exp", "xexp", doubleWidth},
{"pow", "xpow", doubleWidth},
{"sinh", "xsinh", doubleWidth},
{"cosh", "xcosh", doubleWidth},
{"tanh", "xtanh", doubleWidth},
{"asinh", "xasinh", doubleWidth},
{"acosh", "xacosh", doubleWidth},
{"atanh", "xatanh", doubleWidth},
{"exp2", "xexp2", doubleWidth},
{"exp10", "xexp10", doubleWidth},
{"expm1", "xexpm1", doubleWidth},
{"log10", "xlog10", doubleWidth},
{"log1p", "xlog1p", doubleWidth},
{"sqrt", "xsqrt", doubleWidth},
{"hypot", "xhypot", doubleWidth},
{"lgamma", "xlgamma", doubleWidth},
{"tgamma", "xtgamma", doubleWidth},
{"erf", "xerf", doubleWidth},
{"erfc", "xerfc", doubleWidth},
{"llvm.sin.f32", "xsinf", floatWidth},
{"llvm.cos.f32", "xcosf", floatWidth},
{"llvm.log.f32", "xlogf", floatWidth},
{"llvm.exp.f32", "xexpf", floatWidth},
{"llvm.pow.f32", "xpowf", floatWidth},
{"llvm.sqrt.f32", "xsqrtf", floatWidth},
{"llvm.exp2.f32", "xexp2f", floatWidth},
{"llvm.log10.f32", "xlog10f", floatWidth},
{"llvm.sin.f64", "xsin", doubleWidth},
{"llvm.cos.f64", "xcos", doubleWidth},
{"llvm.log.f64", "xlog", doubleWidth},
{"llvm.exp.f64", "xexp", doubleWidth},
{"llvm.pow.f64", "xpow", doubleWidth},
{"llvm.sqrt.f64", "xsqrt", doubleWidth},
{"llvm.exp2.f64", "xexp2", doubleWidth},
{"llvm.log10.f64", "xlog10", doubleWidth}
};
archMappings.insert(archMappings.end(), VecFuncs.begin(), VecFuncs.end());
}
class SleefResolverService : public ResolverService {
PlatformInfo & platInfo;
struct ArchFunctionList {
SleefISA isaIndex;
std::string archSuffix;
PlainVecDescVector commonVectorMappings;
void addNamedMappings(const PlainVecDescVector & funcs, bool givePrecedence) {
auto itInsert = givePrecedence ? commonVectorMappings.begin() : commonVectorMappings.end();
commonVectorMappings.insert(itInsert, funcs.begin(), funcs.end());
}
ArchFunctionList(SleefISA _isaIndex, std::string _archSuffix)
: isaIndex(_isaIndex)
, archSuffix(_archSuffix)
{}
};
std::vector<ArchFunctionList*> archLists;
Config config;
public:
void
print(llvm::raw_ostream & out) const override {
out << "SLEEFResolver:\n"
<< "\tarch order: ";
bool later = false;
for (const auto * archList : archLists) {
if (later) { out << ","; }
later = true;
out << archList->archSuffix;
}
}
SleefResolverService(PlatformInfo & _platInfo, const Config & _config)
: platInfo(_platInfo)
, config(_config)
{
// ARM
#ifdef RV_ENABLE_ADVSIMD
if (config.useADVSIMD) {
auto * advSimdArch = new ArchFunctionList(SleefISA::SLEEF_ADVSIMD, "advsimd");
InitSleefMappings(advSimdArch->commonVectorMappings, 4, 2);
archLists.push_back(advSimdArch);
}
#endif
// x86
#ifdef RV_ENABLE_X86
if (config.useAVX512) {
auto * avx512Arch = new ArchFunctionList(SleefISA::SLEEF_AVX512, "avx512");
InitSleefMappings(avx512Arch->commonVectorMappings, 16, 8);
archLists.push_back(avx512Arch);
}
if (config.useAVX2 || config.useAVX512) {
auto * avx2Arch = new ArchFunctionList(SleefISA::SLEEF_AVX2, "avx2");
InitSleefMappings(avx2Arch->commonVectorMappings, 8, 4);
archLists.push_back(avx2Arch);
}
if (config.useAVX) {
auto * avxArch = new ArchFunctionList(SleefISA::SLEEF_AVX, "avx");
InitSleefMappings(avxArch->commonVectorMappings, 8, 4);
archLists.push_back(avxArch);
}
if (config.useSSE || config.useAVX || config.useAVX2 || config.useAVX512) {
auto * sseArch = new ArchFunctionList(SleefISA::SLEEF_SSE, "sse");
InitSleefMappings(sseArch->commonVectorMappings, 4, 2);
archLists.push_back(sseArch);
}
#endif
// generic
// fall back to automatic vectorization of scalar implementations (baseline)
auto * vlaArch = new ArchFunctionList(SleefISA::SLEEF_VLA, "vla");
InitSleefMappings(vlaArch->commonVectorMappings, -1, -1);
vlaArch->commonVectorMappings.emplace_back("ldexpf", "xldexpf", -1);
vlaArch->commonVectorMappings.emplace_back("ldexp", "xldexp", -1);
archLists.push_back(vlaArch);
}
~SleefResolverService() {
for (auto * archList : archLists) delete archList;
}
std::unique_ptr<FunctionResolver> resolve(llvm::StringRef funcName, llvm::FunctionType & scaFuncTy, const VectorShapeVec & argShapes, int vectorWidth, bool hasPredicate, llvm::Module & destModule) override;
};
// simply links-in the pre-vectorized SLEEF function
class SleefLookupResolver : public FunctionResolver {
VectorShape resShape;
Function & vecFunc;
std::string destFuncName;
public:
SleefLookupResolver(Module & _targetModule, VectorShape resShape, Function & _vecFunc, std::string _destFuncName)
: FunctionResolver(_targetModule)
, resShape(resShape)
, vecFunc(_vecFunc)
, destFuncName(_destFuncName)
{}
CallPredicateMode getCallSitePredicateMode() override {
// FIXME this is not entirely true for vector math
return CallPredicateMode::SafeWithoutPredicate;
}
// mask position (if any)
int getMaskPos() override {
return -1; // FIXME vector math is unpredicated
}
llvm::Function&
requestVectorized() override {
auto * existingFunc = targetModule.getFunction(destFuncName);
if (existingFunc) {
return *existingFunc;
}
// Picks 'Sleef_rempitab' from the shared module.
Function &clonedVecFunc = cloneFunctionIntoModule(
vecFunc, targetModule, destFuncName, SharedModuleLookup);
clonedVecFunc.setDoesNotRecurse(); // SLEEF math does not recurse
return clonedVecFunc;
}
// result shape of function @funcName in target module @module
VectorShape requestResultShape() override { return resShape; }
};
// on-the-fly vectorizing resolver
struct SleefVLAResolver : public FunctionResolver {
VectorizerInterface vectorizer;
std::unique_ptr<VectorizationInfo> vecInfo;
Function & scaFunc;
Function * clonedFunc;
Function * vecFunc;
VectorShapeVec argShapes;
VectorShape resShape;
int vectorWidth;
std::string vecFuncName;
SleefVLAResolver(PlatformInfo & platInfo, std::string baseName, Config config, Function & _scaFunc, const VectorShapeVec & _argShapes, int _vectorWidth)
: FunctionResolver(platInfo.getModule())
, vectorizer(platInfo, config)
, vecInfo(nullptr)
, scaFunc(_scaFunc)
, clonedFunc(nullptr)
, vecFunc(nullptr)
, argShapes(_argShapes)
, resShape(VectorShape::undef())
, vectorWidth(_vectorWidth)
, vecFuncName(platInfo.createMangledVectorName(baseName, argShapes, vectorWidth, -1))
{
IF_DEBUG_SLEEF { errs() << "VLA: " << vecFuncName << "\n"; }
}
CallPredicateMode getCallSitePredicateMode() override {
// FIXME this is not entirely true for vector math
return CallPredicateMode::SafeWithoutPredicate;
}
// mask position (if any)
int getMaskPos() override {
return -1; // FIXME vector math is unpredicated
}
// materialized the vectorized function in the module @insertInto and returns a reference to it
llvm::Function& requestVectorized() override {
if (vecFunc) return *vecFunc;
vecFunc = targetModule.getFunction(vecFuncName);
if (vecFunc) return *vecFunc;
// FIXME this is a hacky workaround for sqrt
if (scaFunc.getName().startswith("xsqrt")) {
auto funcTy = scaFunc.getFunctionType();
auto vecTy = FixedVectorType::get(funcTy->getReturnType(), vectorWidth);
vecFunc = Intrinsic::getDeclaration(&targetModule, Intrinsic::sqrt, {vecTy});
return *vecFunc;
}
requestResultShape();
// prepare scalar copy for transforming
clonedFunc = &cloneFunctionIntoModule(
scaFunc, targetModule, vecFuncName + ".tmp", SharedModuleLookup);
assert(clonedFunc);
// create SIMD declaration
const int maskPos = -1; // TODO add support for masking
vecFunc = createVectorDeclaration(*clonedFunc, resShape, argShapes, vectorWidth, maskPos);
vecFunc->setName(vecFuncName);
// override with no-recurse flag (so we won't get guards in the vector code)
vecFunc->copyAttributesFrom(&scaFunc);
vecFunc->setDoesNotRecurse();
// Use fastest possible CC.
vecFunc->setCallingConv(CallingConv::Fast);
vecFunc->setLinkage(GlobalValue::LinkOnceAnyLinkage);
VectorMapping mapping(clonedFunc, vecFunc, vectorWidth, maskPos, resShape, argShapes, CallPredicateMode::SafeWithoutPredicate);
vectorizer.getPlatformInfo().addMapping(mapping); // prevent recursive vectorization
// set-up vecInfo
FunctionRegion funcWrapper(*clonedFunc);
Region funcRegion(funcWrapper);
VectorizationInfo vecInfo(funcRegion, mapping);
// unify returns (if necessary)
SingleReturnTrans::run(funcRegion);
// compute anlaysis results
PassBuilder PB;
FunctionAnalysisManager FAM;
PB.registerFunctionAnalyses(FAM);
// compute DT, PDT, LI
FAM.getResult<DominatorTreeAnalysis>(*clonedFunc);
FAM.getResult<PostDominatorTreeAnalysis>(*clonedFunc);
FAM.getResult<LoopAnalysis>(*clonedFunc);
FAM.getResult<ScalarEvolutionAnalysis>(*clonedFunc);
FAM.getResult<MemoryDependenceAnalysis>(*clonedFunc);
FAM.getResult<BranchProbabilityAnalysis>(*clonedFunc);
// re-establish LCSSA
FunctionPassManager FPM;
FPM.addPass<LCSSAPass>(LCSSAPass());
FPM.run(*clonedFunc, FAM);
// normalize loop exits (TODO make divLoopTrans work without this)
{
LoopInfo &LI = FAM.getResult<LoopAnalysis>(*clonedFunc);
LoopExitCanonicalizer canonicalizer(LI);
canonicalizer.canonicalize(*clonedFunc);
FAM.invalidate<DominatorTreeAnalysis>(*clonedFunc);
FAM.invalidate<PostDominatorTreeAnalysis>(*clonedFunc);
// invalidate & recompute LI
FAM.invalidate<LoopAnalysis>(*clonedFunc);
FAM.getResult<LoopAnalysis>(*clonedFunc);
}
// run pipeline
vectorizer.analyze(vecInfo, FAM);
vectorizer.linearize(vecInfo, FAM);
vectorizer.vectorize(vecInfo, FAM, nullptr);
vectorizer.finalize();
// discard temporary mapping
vectorizer.getPlatformInfo().forgetAllMappingsFor(*clonedFunc);
// can dispose of temporary function now
clonedFunc->eraseFromParent();
return *vecFunc;
}
// result shape of function @funcName in target module @module
VectorShape requestResultShape() override {
if (resShape.isDefined()) return resShape;
// TODO run VA
for (const auto & argShape : argShapes) {
if (!argShape.isUniform()) {
resShape = VectorShape::varying();
return resShape;
}
}
resShape = VectorShape::uni();
return resShape;
}
// whether this resolver can provide a vectorized version ofthis function
bool isVectorizable(const VectorShapeVec & argShapes, int vectorWidth) {
return true;
}
};
// used for shape-based call mappings
using VecMappingShortVec = llvm::SmallVector<VectorMapping, 4>;
using VectorFuncMap = std::map<const llvm::Function *, VecMappingShortVec*>;
// parse ULP error bound from mangled SLEEF name
static unsigned
ReadULPBound(StringRef sleefName) {
auto itStart = sleefName.find_last_of("_u");
if (itStart == StringRef::npos) return 0; // unspecified -> perfect rounding
StringRef ulpPart = sleefName.substr(itStart + 1);
// single digit ULP value
unsigned ulpBound;
if (ulpPart.size() == 1) {
ulpBound = 10 * (ulpPart[0] - '0');
// lsc is tenth of ULP
} else {
bool parseError = ulpPart.consumeInteger<unsigned>(10, ulpBound);
(void) parseError; assert(!parseError);
}
return ulpBound;
}
static Function*
GetLeastPreciseImpl(Module & mod, const std::string & funcPrefix, const unsigned maxULPBound) {
Function * currBest = nullptr;
unsigned bestBound = 0;
IF_DEBUG_SLEEF { errs() << "SLEEF: impl: " << funcPrefix << "\n"; }
for (auto & func : mod) {
if (func.isDeclaration()) continue;
if (!func.getName().startswith(funcPrefix)) continue;
// not a complete funcname match (ie "xlog" would otw match "xlog1p")
if ((func.getName().size() > funcPrefix.size()) &&
(func.getName()[funcPrefix.size()] != '_'))
{
continue;
}
IF_DEBUG_SLEEF { errs() << "\t candidate: " << func.getName() << "\n"; }
unsigned funcBound = ReadULPBound(func.getName());
// dismiss too imprecise functions
if (funcBound > maxULPBound) {
IF_DEBUG_SLEEF { errs() << "discard, ulp was: " << funcBound << "\n"; }
continue;
// accept functions with higher ULP error within maxUPLBound
} else if (!currBest || (funcBound > bestBound)) {
IF_DEBUG_SLEEF { errs() << "\tOK! " << func.getName() << " with ulp bound: " << funcBound << "\n"; }
bestBound = funcBound;
currBest = &func;
}
}
return currBest;
}
std::unique_ptr<FunctionResolver>
SleefResolverService::resolve(llvm::StringRef funcName, llvm::FunctionType & scaFuncTy, const VectorShapeVec & argShapes, int vectorWidth, bool hasPredicate, llvm::Module & destModule) {
IF_DEBUG_SLEEF { errs() << "SLEEFResolverService: " << funcName << " for width " << vectorWidth << "\n"; }
(void) hasPredicate; // FIXME use predicated versions
// Otw, start looking for a SIMD-ized implementation
ArchFunctionList * archList = nullptr;
PlainVecDesc funcDesc;
for (auto * candList : archLists) {
// query custom mappings with precedence
std::string funcNameStr = funcName.str();
for (const auto & vd : candList->commonVectorMappings) {
if (vd.scalarFnName == funcNameStr &&
((vd.vectorWidth <= 0) || (vd.vectorWidth == vectorWidth)))
{
funcDesc = vd;
archList = candList;
break;
}
};
if (archList) break;
}
IF_DEBUG_SLEEF { errs() << "\tsleef: n/a\n"; }
if (!archList) return nullptr;
// Make sure the shared module is available
auto & Ctx = destModule.getContext();
// decode bitwidth (for module lookup)
bool doublePrecision = false;
for (const auto * argTy : scaFuncTy.params()) {
doublePrecision |= argTy->isDoubleTy();
}
// remove the trailing isa specifier (_avx2/_avx/_sse/..)
SleefISA isa = archList->isaIndex;
std::string sleefName = funcDesc.vectorFnName;
// TODO factor out
bool isExtraFunc = funcDesc.vectorFnName.find("_extra") != std::string::npos;
if (isExtraFunc) {
int modIdx = (int) isa;
auto *& mod = extraModules[modIdx];
if (!mod) mod = createModuleFromBuffer(reinterpret_cast<const char*>(extraModuleBuffers[modIdx]), extraModuleBufferLens[modIdx], Ctx);
Function *vecFunc = mod->getFunction(sleefName);
assert(vecFunc && "mapped extra function not found in module!");
return std::make_unique<SleefLookupResolver>(destModule, /* RNG result */ VectorShape::varying(), *vecFunc, funcDesc.vectorFnName);
}
// Skip for fast builtin functions // FIXME should be in its own target-dependent resolver
if (StringRef(sleefName).startswith("xsqrt")) {
// "every" target has a sqrt instruction of sorts
auto vecTy = FixedVectorType::get(scaFuncTy.getReturnType(), vectorWidth);
auto vecFunc = Intrinsic::getDeclaration(&destModule, Intrinsic::sqrt, {vecTy});
// FIXME abusing the SleefLookupResolver to retrieve an existing declaration...
return std::make_unique<SleefLookupResolver>(destModule, VectorShape::varying(), *vecFunc, vecFunc->getName().str());
}
// Look in SLEEF module
auto modIndex = sleefModuleIndex(isa, doublePrecision);
llvm::Module*& mod = sleefModules[modIndex]; // TODO const Module
if (!mod) {
mod = createModuleFromBuffer(reinterpret_cast<const char*>(sleefModuleBuffers[modIndex]), sleefModuleBufferLens[modIndex], Ctx);
IF_DEBUG {
bool brokenMod = verifyModule(*mod, &errs());
if (brokenMod) abort();
}
}
if (isa == SLEEF_VLA) {
// on-the-fly vectorization module
Function *vlaFunc = GetLeastPreciseImpl(*mod, sleefName, config.maxULPErrorBound);
if (!vlaFunc) {
IF_DEBUG_SLEEF { errs() << "sleef: " << sleefName << " n/a with maxULPError: " << config.maxULPErrorBound << "\n"; }
return nullptr;
}
return std::make_unique<SleefVLAResolver>(platInfo, vlaFunc->getName().str(), config, *vlaFunc, argShapes, vectorWidth);
} else {
// these are pure functions
VectorShape resShape = VectorShape::uni();
for (const auto argShape : argShapes) {
if (!argShape.isUniform()) {
resShape = VectorShape::varying();
break;
}
}
// we'll have to link in the function
Function *vecFunc = GetLeastPreciseImpl(*mod, sleefName, config.maxULPErrorBound);
if (!vecFunc) {
IF_DEBUG_SLEEF { errs() << "sleef: " << sleefName << " n/a with maxULPError: " << config.maxULPErrorBound << "\n"; }
return nullptr;
}
std::string vecFuncName = vecFunc->getName().str() + "_" + archList->archSuffix;
return std::make_unique<SleefLookupResolver>(destModule, resShape, *vecFunc, vecFuncName);
}
}
void
addSleefResolver(const Config & config, PlatformInfo & platInfo) {
#ifdef RV_ENABLE_SLEEF
auto sleefRes = std::make_unique<SleefResolverService>(platInfo, config);
platInfo.addResolverService(std::move(sleefRes), false); // give precedence to VectorABI
#else
Report() << " build w/o SLEEF (tried to add SleefResolver)!\n";
#endif
}
} // namespace rv
| 33.33871
| 208
| 0.670952
|
sx-aurora-test
|
fa77c3022865e3f92693358145303215345ca6a1
| 631
|
cpp
|
C++
|
Vic2ToHoI4Tests/HoI4WorldTests/OperativeNames/OperativeNamesTests.cpp
|
gawquon/Vic2ToHoI4
|
8371cfb1fd57cf81d854077963135d8037e754eb
|
[
"MIT"
] | 25
|
2018-12-10T03:41:49.000Z
|
2021-10-04T10:42:36.000Z
|
Vic2ToHoI4Tests/HoI4WorldTests/OperativeNames/OperativeNamesTests.cpp
|
gawquon/Vic2ToHoI4
|
8371cfb1fd57cf81d854077963135d8037e754eb
|
[
"MIT"
] | 739
|
2018-12-13T02:01:20.000Z
|
2022-03-28T02:57:13.000Z
|
Vic2ToHoI4Tests/HoI4WorldTests/OperativeNames/OperativeNamesTests.cpp
|
Osariusz/Vic2ToHoI4
|
9738b52c7602b1fe187c3820660c58a8d010d87e
|
[
"MIT"
] | 43
|
2018-12-10T03:41:58.000Z
|
2022-03-22T23:55:41.000Z
|
#include "HOI4World/OperativeNames/OperativeNames.h"
#include "HOI4World/OperativeNames/OperativeNamesFactory.h"
#include "gtest/gtest.h"
#include <sstream>
TEST(HoI4World_OperativeNames_OperativeNamesTests, OperativeNamesDefaultsToEmpty)
{
const auto operativeNames = HoI4::OperativeNames::Factory::getOperativeNames("bad_path");
ASSERT_TRUE(operativeNames->getOperativeNamesSets().empty());
}
TEST(HoI4World_OperativeNames_OperativeNamesTests, OperativeNamesCanBeAdded)
{
const auto operativeNames = HoI4::OperativeNames::Factory::getOperativeNames(".");
ASSERT_EQ(2, operativeNames->getOperativeNamesSets().size());
}
| 30.047619
| 90
| 0.81775
|
gawquon
|
fa78add51b4e41dcc8b8ff9fc82ca69b143115e3
| 154
|
cpp
|
C++
|
stat.cpp
|
sagar-sam/codechef-solutions
|
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
|
[
"MIT"
] | null | null | null |
stat.cpp
|
sagar-sam/codechef-solutions
|
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
|
[
"MIT"
] | null | null | null |
stat.cpp
|
sagar-sam/codechef-solutions
|
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int i=0;
int j=n-1;
}
}
| 9.058824
| 20
| 0.506494
|
sagar-sam
|
fa79764ed3fe4e562a1bf37035b400745cd61fd1
| 2,267
|
cpp
|
C++
|
BetaEngine/Comp/Lab1/Source/Level1.cpp
|
PowerUser64/dP-2
|
98e5edc2dca4ed629e2bbf222c5b764e166e7193
|
[
"MIT"
] | null | null | null |
BetaEngine/Comp/Lab1/Source/Level1.cpp
|
PowerUser64/dP-2
|
98e5edc2dca4ed629e2bbf222c5b764e166e7193
|
[
"MIT"
] | null | null | null |
BetaEngine/Comp/Lab1/Source/Level1.cpp
|
PowerUser64/dP-2
|
98e5edc2dca4ed629e2bbf222c5b764e166e7193
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Level1.h"
#include "MonkeyMovement.h"
using namespace Beta;
Level1::Level1() : Level("Leve1")
{
}
void Level1::Load()
{
// Create a sprite component and set its mesh and sprite source
textureMonkey = ResourceGetTexture("Monkey.png");
spriteSourceMonkey = std::make_shared<SpriteSource>(textureMonkey, "Monkey", 3, 5);
// animations
//"MonkeyWalk" (8 frames, starts from frame 0, frame duration of 0.15f seconds)
animationWalk = std::make_shared<Animation>("MonkeyWalk", spriteSourceMonkey, 8, 0, 0.01f);
//"MonkeyJump" (1 frame, starts from frame 9)
animationJump = std::make_shared<Animation>("MonkeyJump", spriteSourceMonkey, 1, 9, 0.0f);
//"MonkeyIdle" (1 frame, starts from frame 12)
animationIdle = std::make_shared<Animation>("MonkeyIdle", spriteSourceMonkey, 1, 12, 0.0f);
}
void Level1::Initialize()
{
std::cout << "Level1::Initialize" << std::endl;
// set bkgnd color
GraphicsEngine *graphix = EngineGetModule(GraphicsEngine);
graphix->SetBackgroundColor(Colors::Blue);
GetSpace()->GetObjectManager().AddObject(*CreateMonkey());
}
void Level1::Update(float dt)
{
UNREFERENCED_PARAMETER(dt);
Input *input = EngineGetModule(Input);
// If the user presses the '1' key, restart the current level
if (input->CheckTriggered('1'))
GetSpace()->RestartLevel();
}
void Level1::Shutdown()
{
std::cout << "Level1::Shutdown\n";
}
void Level1::Unload()
{
std::cout << "Level1::Unload\n";
}
Beta::GameObject *Level1::CreateMonkey(void)
{
GameObject *Monkey = new GameObject("Monkey");
Transform *transform = new Transform(0.0f, 0.0f);
transform->SetScale(Vector2D(2.0f, 2.0f));
Sprite *sprite = new Sprite();
sprite->SetColor(Colors::Green);
sprite->SetSpriteSource(spriteSourceMonkey);
Monkey->AddComponent(sprite);
Monkey->AddComponent(transform);
Animator *animator = new Animator();
Monkey->AddComponent(animator);
animator->AddAnimation(animationWalk);
animator->AddAnimation(animationJump);
animator->AddAnimation(animationIdle);
RigidBody *rigidBody = new RigidBody();
Monkey->AddComponent(rigidBody);
MonkeyMovement *movement = new MonkeyMovement();
Monkey->AddComponent(movement);
return Monkey;
}
| 27.987654
| 93
| 0.703573
|
PowerUser64
|
fa7c8e73799feb7707f1f90d68a0f5cfb6678d50
| 2,118
|
hh
|
C++
|
include/WCSimDetectorZone.hh
|
chipsneutrino/chips-sim
|
19d3f2d75c674c06d2f27b9a344b70ca53e672c5
|
[
"MIT"
] | null | null | null |
include/WCSimDetectorZone.hh
|
chipsneutrino/chips-sim
|
19d3f2d75c674c06d2f27b9a344b70ca53e672c5
|
[
"MIT"
] | null | null | null |
include/WCSimDetectorZone.hh
|
chipsneutrino/chips-sim
|
19d3f2d75c674c06d2f27b9a344b70ca53e672c5
|
[
"MIT"
] | null | null | null |
/*
* WCSimDetectorZone.hh
*
* Created on: 24 Nov 2014
* Author: ajperch
*/
#pragma once
#include "G4ThreeVector.hh"
#include "WCSimGeometryEnums.hh"
#include <map>
#include <vector>
class WCSimDetectorZone
{
public:
WCSimDetectorZone();
virtual ~WCSimDetectorZone();
void AddCellPMTName(std::string name);
std::string GetCellPMTName(unsigned int pmt) const;
std::vector<std::string> GetCellPMTName() const;
void AddCellPMTX(double x);
double GetCellPMTX(unsigned int pmt) const;
std::vector<double> GetCellPMTX() const;
void AddCellPMTY(double y);
double GetCellPMTY(unsigned int pmt) const;
std::vector<double> GetCellPMTY() const;
void AddCellPMTFaceType(WCSimGeometryEnums::PMTDirection_t face);
WCSimGeometryEnums::PMTDirection_t GetCellPMTFaceType(unsigned int pmt) const;
std::vector<WCSimGeometryEnums::PMTDirection_t> GetCellPMTFaceType() const;
void AddCellPMTFaceTheta(double theta);
double GetCellPMTFaceTheta(unsigned int pmt) const;
std::vector<double> GetCellPMTFaceTheta() const;
void AddCellPMTFacePhi(double phi);
double GetCellPMTFacePhi(unsigned int pmt) const;
std::vector<double> GetCellPMTPhi() const;
void SetPMTLimit(std::string name, int limit);
int GetPMTLimit(std::string name) const;
int GetMaxNumCells() const;
bool IsGood(WCSimGeometryEnums::DetectorRegion_t region) const;
double GetCoverage() const
{
return fCoverage;
}
void SetCoverage(double coverage)
{
this->fCoverage = coverage;
}
void Print() const;
double GetThetaEnd() const
{
return fThetaEnd;
}
void SetThetaEnd(double thetaEnd)
{
this->fThetaEnd = thetaEnd;
}
double GetThetaStart() const
{
return fThetaStart;
}
void SetThetaStart(double thetaStart)
{
this->fThetaStart = thetaStart;
}
private:
double fCoverage;
std::vector<std::string> fCellPMTName;
std::map<std::string, int> fPMTLimit;
std::vector<double> fCellPMTX;
std::vector<double> fCellPMTY;
std::vector<WCSimGeometryEnums::PMTDirection_t> fDirectionType;
std::vector<double> fCellDirTheta;
std::vector<double> fCellDirPhi;
double fThetaStart;
double fThetaEnd;
};
| 21.612245
| 79
| 0.756374
|
chipsneutrino
|
fa817f8b0dd229fd2d71bbcd788ff35c5df0a81d
| 1,435
|
cpp
|
C++
|
WonderMake/Collision/ColliderDebug.cpp
|
nicolasgustafsson/WonderMake
|
9661d5dab17cf98e06daf6ea77c5927db54d62f9
|
[
"MIT"
] | 3
|
2020-03-27T15:25:19.000Z
|
2022-01-18T14:12:25.000Z
|
WonderMake/Collision/ColliderDebug.cpp
|
nicolasgustafsson/WonderMake
|
9661d5dab17cf98e06daf6ea77c5927db54d62f9
|
[
"MIT"
] | null | null | null |
WonderMake/Collision/ColliderDebug.cpp
|
nicolasgustafsson/WonderMake
|
9661d5dab17cf98e06daf6ea77c5927db54d62f9
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "ColliderDebug.h"
#include "Colliders.h"
void DrawSphere(const Colliders::SSphere& aCollider, const SColor& aColor)
{
constexpr u32 points = 16;
SVector2f positions[points];
for (u32 i = 0; i < points; ++i)
{
positions[i].X = std::cosf((Constants::Pi * 2.f) / points * i);
positions[i].Y = std::sinf((Constants::Pi * 2.f) / points * i);
positions[i] *= aCollider.Radius;
positions[i] += aCollider.Position;
}
SDebugLine line;
line.Color = aColor;
for (u32 i = 0; i < points - 1; ++i)
{
line.Start = positions[i];
line.End = positions[i + 1];
WmDrawDebugLine(line);
}
line.Start = positions[points - 1];
line.End = positions[0];
//WmDrawDebugLine(line);
}
void DrawLine(const Colliders::SCollisionLine& aCollider, const SColor& aColor)
{
SDebugLine line;
line.Color = aColor;
line.Start = aCollider.Position;
line.End = aCollider.GetLineEnd();
//WmDrawDebugLine(line);
}
void DrawCollider(const Colliders::Shape& aCollider, const SColor& aColor)
{
std::visit([aColor](const auto& aCollider)
{
using T = std::decay_t<decltype(aCollider)>;
if constexpr (std::is_same_v<T, Colliders::SSphere>)
{
DrawSphere(aCollider, aColor);
}
else if constexpr (std::is_same_v<T, Colliders::SCollisionLine>)
{
DrawLine(aCollider, aColor);
}
else
{
static_assert(std::false_type::value, "Collider not implemented!");
}
}, aCollider);
}
| 21.41791
| 79
| 0.667596
|
nicolasgustafsson
|
fa836b9da81e50a6e7a7fa097ac97bd5cb0c6bd4
| 11,001
|
cpp
|
C++
|
[Lib]__Engine/Sources/Common/profile.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
[Lib]__Engine/Sources/Common/profile.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
[Lib]__Engine/Sources/Common/profile.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
// "Portions Copyright (C) Steve Rabin, 2000"
// Edit by Jung DH, 2002.
//
#include "pch.h"
#include "./profile.h"
#include "./DebugSet.h"
#include "./DxInputDevice.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CPROFILE g_profile_1;
CPROFILE g_profile_2;
BOOL g_bProfile = FALSE;
namespace
{
#define _HISTORY_RATE_ ( 5000.0f )
#define _GETCURTIME_ ( timeGetTime() )
#define _GETELAPSEDTIME_ ( (float)( m_endProfile - m_startProfile ) )
};
CPROFILE::CPROFILE ()
: m_startProfile(0)
, m_endProfile(0)
{
}
CPROFILE::~CPROFILE ()
{
}
void CPROFILE::Init (void)
{
unsigned int i;
for( i=0; i<NUM_PROFILE_SAMPLES; i++ )
{
m_samples[i].bValid = false;
m_history[i].bValid = false;
}
m_startProfile = _GETCURTIME_;
}
void CPROFILE::BlockStart ()
{
if ( m_startProfile==0 ) return;
unsigned int i; // Reset samples for next frame
for (i=0; i<NUM_PROFILE_SAMPLES; ++i)
{
m_samples[i].bValid = false;
}
DxInputDevice &IDev = DxInputDevice::GetInstance();
if (IDev.GetKeyState(DIK_LCONTROL)&DXKEY_PRESSED)
{
if (IDev.GetKeyState(DIK_F12)&DXKEY_UP)
{
for (i=0; i<NUM_PROFILE_SAMPLES; ++i)
{
m_history[i].bValid = false;
}
}
}
m_startProfile = _GETCURTIME_;
}
void CPROFILE::BlockEnd ()
{
if (m_startProfile==0)
{
return;
}
else
{
m_endProfile = _GETCURTIME_;
}
}
void CPROFILE::Begin(char* name)
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
while ( i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true )
{
if( strcmp( m_samples[i].szName, name ) == 0 ) //Found the sample
{
m_samples[i].iOpenProfiles++;
m_samples[i].iProfileInstances++;
m_samples[i].fStartTime = _GETCURTIME_;
GASSERT( m_samples[i].iOpenProfiles == 1 ); //max 1 open at once
return;
}
i++;
}
if( i >= NUM_PROFILE_SAMPLES )
{
GASSERT( !"Exceeded Max Available Profile Samples" );
return;
}
StringCchCopy( m_samples[i].szName, 256, name );
m_samples[i].bValid = true;
m_samples[i].iOpenProfiles = 1;
m_samples[i].iProfileInstances = 1;
m_samples[i].fAccumulator = 0;
m_samples[i].fStartTime = _GETCURTIME_;
m_samples[i].fChildrenSampleTime = 0;
}
void CPROFILE::End ( char* name )
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
unsigned int numParents = 0;
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
if (strcmp(m_samples[i].szName, name) == 0) //Found the sample
{
unsigned int inner = 0;
int parent = -1;
unsigned long fEndTime = _GETCURTIME_;
m_samples[i].iOpenProfiles--;
while (m_samples[inner].bValid == true) //Count all parents and find the immediate parent
{
if (m_samples[inner].iOpenProfiles > 0) //Found a parent (any open profiles are parents)
{
numParents++;
if (parent < 0) //Replace invalid parent (index)
{
parent = inner;
}
else if (m_samples[inner].fStartTime >= m_samples[parent].fStartTime) //Replace with more immediate parent
{
parent = inner;
}
}
inner++;
}
m_samples[i].iNumParents = numParents; //Remember the current number of parents of the sample
if (parent >= 0)
{
m_samples[parent].fChildrenSampleTime += fEndTime - m_samples[i].fStartTime; //Record this time in fChildrenSampleTime (add it in)
}
m_samples[i].fAccumulator += fEndTime - m_samples[i].fStartTime; //Save sample time in accumulator
return;
} // if
i++;
} // while
}
void CPROFILE::DumpOutputToView (int _OUTCHANNEL)
{
if ( m_startProfile==0 ) return;
unsigned int i=0;
float fDxTIME = _GETELAPSEDTIME_;
if (fDxTIME <= 0.0f)
return;
CDebugSet::ToView ( _OUTCHANNEL, 0, " Ave : Min : Max : # : Profile Name" );
CDebugSet::ToView ( _OUTCHANNEL, 1, "--------------------------------------------" );
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
unsigned int indent = 0;
float sampleTime = 0;
float percentTime = 0;
float aveTime = 0;
float minTime = 0;
float maxTime = 0;
char name[256] = "";
char indentedName[256] = "";
char ave[16] = "";
char min[16] = "";
char max[16] = "";
char num[16] = "";
if (m_samples[i].iOpenProfiles < 0)
{
char szDump[256] = "";
StringCchPrintf(szDump, 256, "%s, ProfileEnd() called without a ProfileBegin()", m_samples[i].szName);
GASSERT (!szDump);
}
else if (m_samples[i].iOpenProfiles > 0)
{
char szDump[256] = "";
StringCchPrintf(szDump, 256, "%s, ProfileBegin() called without a ProfileEnd()", m_samples[i].szName);
GASSERT (!szDump);
}
sampleTime = (float)( m_samples[i].fAccumulator - m_samples[i].fChildrenSampleTime );
if (sampleTime < 0)
{
sampleTime = 0;
}
percentTime = ( ( sampleTime / fDxTIME ) * 100.0f );
if (percentTime < 0)
{
percentTime = 0;
}
aveTime = minTime = maxTime = percentTime;
//Add new measurement into the history and get the ave, min, and max
StoreInHistory ( m_samples[i].szName, percentTime );
GetFromHistory ( m_samples[i].szName, &aveTime, &minTime, &maxTime );
//Format the data
StringCchPrintf( ave, 16, "%3.1f", aveTime );
StringCchPrintf( min, 16, "%3.1f", minTime );
StringCchPrintf( max, 16, "%3.1f", maxTime );
StringCchPrintf( num, 16, "%3d", m_samples[i].iProfileInstances );
StringCchCopy (indentedName, 256, m_samples[i].szName);
for (indent=0; indent<m_samples[i].iNumParents; ++indent)
{
StringCchPrintf(name, 256, " %s", indentedName);
StringCchCopy(indentedName, 256, name);
}
CDebugSet::ToView( _OUTCHANNEL, 2+i, "%5s : %5s : %5s : %3s : %s", ave, min, max, num, indentedName );
i++;
} // while
CDebugSet::ToView(_OUTCHANNEL, 2+i+0, "--------------------------------------------");
CDebugSet::ToView(_OUTCHANNEL, 2+i+1, "Reset Stats : Ctrl + F12");
}
void CPROFILE::DumpOutputToFile ()
{
if (m_startProfile==0)
{
return;
}
unsigned int i=0;
float fDxTIME = _GETELAPSEDTIME_;
if (fDxTIME <= 0.0f)
return;
CDebugSet::ToLogFile ( " Ave : Min : Max : # : Profile Name" );
CDebugSet::ToLogFile ( "--------------------------------------------" );
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
unsigned int indent = 0;
float sampleTime = 0;
float percentTime = 0;
float aveTime = 0;
float minTime = 0;
float maxTime = 0;
char name[256] = "";
char indentedName[256] = "";
char ave[16] = "";
char min[16] = "";
char max[16] = "";
char num[16] = "";
if (m_samples[i].iOpenProfiles < 0)
{
char szDump[256] = "";
StringCchPrintf(szDump,
256,
_T("%s, ProfileEnd() called without a ProfileBegin()"),
m_samples[i].szName);
GASSERT(!szDump);
}
else if (m_samples[i].iOpenProfiles > 0)
{
char szDump[256] = "";
StringCchPrintf (szDump,
256,
_T("%s, ProfileBegin() called without a ProfileEnd()"),
m_samples[i].szName);
GASSERT ( !szDump );
}
sampleTime = (float)( m_samples[i].fAccumulator - m_samples[i].fChildrenSampleTime );
if (sampleTime < 0)
{
sampleTime = 0;
}
percentTime = ( ( sampleTime / fDxTIME ) * 100.0f );
if (percentTime < 0)
{
percentTime = 0;
}
aveTime = minTime = maxTime = percentTime;
//Add new measurement into the history and get the ave, min, and max
StoreInHistory ( m_samples[i].szName, percentTime );
GetFromHistory ( m_samples[i].szName, &aveTime, &minTime, &maxTime );
//Format the data
StringCchPrintf( ave, 16, "%3.1f", aveTime );
StringCchPrintf( min, 16, "%3.1f", minTime );
StringCchPrintf( max, 16, "%3.1f", maxTime );
StringCchPrintf( num, 16, "%3d", m_samples[i].iProfileInstances );
StringCchCopy( indentedName, 256, m_samples[i].szName );
for( indent=0; indent<m_samples[i].iNumParents; indent++ )
{
StringCchPrintf ( name, 256, " %s", indentedName );
StringCchCopy( indentedName, 256, name );
}
CDebugSet::ToLogFile( "%5s : %5s : %5s : %3s : %s", ave, min, max, num, indentedName );
i++;
} // while
CDebugSet::ToLogFile ( "--------------------------------------------" );
}
void CPROFILE::DumpOutputToNon ()
{
if (m_startProfile==0)
{
return;
}
unsigned int i=0;
float fDxTIME = _GETELAPSEDTIME_;
if (fDxTIME <= 0.0f)
return;
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
unsigned int indent = 0;
float sampleTime = 0;
float percentTime = 0;
float aveTime = 0;
float minTime = 0;
float maxTime = 0;
if ( m_samples[i].iOpenProfiles < 0 )
{
char szDump[256] = "";
StringCchPrintf( szDump, 256, "%s, ProfileEnd() called without a ProfileBegin()", m_samples[i].szName );
GASSERT ( !szDump );
}
else if ( m_samples[i].iOpenProfiles > 0 )
{
char szDump[256] = "";
StringCchPrintf( szDump, 256, "%s, ProfileBegin() called without a ProfileEnd()", m_samples[i].szName );
GASSERT ( !szDump );
}
sampleTime = (float)( m_samples[i].fAccumulator - m_samples[i].fChildrenSampleTime );
if (sampleTime < 0)
{
sampleTime = 0;
}
percentTime = ( ( sampleTime / fDxTIME ) * 100.0f );
if (percentTime < 0)
{
percentTime = 0;
}
aveTime = minTime = maxTime = percentTime;
//Add new measurement into the history and get the ave, min, and max
StoreInHistory(m_samples[i].szName, percentTime);
GetFromHistory(m_samples[i].szName, &aveTime, &minTime, &maxTime);
i++;
} // while
}
void CPROFILE::StoreInHistory ( char* name, float percent )
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
float oldRatio = 0;
float newRatio = _GETELAPSEDTIME_ / _HISTORY_RATE_;
if ( newRatio > 1.0f )
{
newRatio = 1.0f;
}
oldRatio = 1.0f - newRatio;
while (i < NUM_PROFILE_SAMPLES && m_history[i].bValid == true)
{
if (strcmp(m_history[i].szName, name) == 0) //Found the sample
{
m_history[i].fAve = (m_history[i].fAve*oldRatio) + (percent*newRatio);
if ( percent < m_history[i].fMin )
{
m_history[i].fMin = percent;
}
else
{
m_history[i].fMin = (m_history[i].fMin*oldRatio) + (percent*newRatio);
}
if ( m_history[i].fMin < 0.0f )
{
m_history[i].fMin = 0.0f;
}
if ( percent > m_history[i].fMax )
{
m_history[i].fMax = percent;
}
else
{
m_history[i].fMax = (m_history[i].fMax*oldRatio) + (percent*newRatio);
}
return;
} // if
i++;
} // while
if (i < NUM_PROFILE_SAMPLES) //Add to history
{
StringCchCopy( m_history[i].szName, 256, name );
m_history[i].bValid = true;
m_history[i].fAve = m_history[i].fMin = m_history[i].fMax = percent;
}
else
{
GASSERT ( !"Exceeded Max Available Profile Samples!");
}
}
void CPROFILE::GetFromHistory ( char* name, float* ave, float* min, float* max )
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
while (i < NUM_PROFILE_SAMPLES && m_history[i].bValid == true)
{
if (strcmp(m_history[i].szName, name) == 0)
{ //Found the sample
*ave = m_history[i].fAve;
*min = m_history[i].fMin;
*max = m_history[i].fMax;
return;
}
i++;
}
*ave = *min = *max = 0.0f;
}
| 22.871102
| 134
| 0.624852
|
yexiuph
|
fa8513b9b1598a97d7e11ea82cb932f68a07efaa
| 544
|
cpp
|
C++
|
GameEngine/Sources/IndexBufferSegment.cpp
|
GPUWorks/OpenGL-Mini-CAD-2D
|
fedb903302f82a1d1ff0ca6776687a60a237008a
|
[
"MIT"
] | 1
|
2021-08-10T02:48:57.000Z
|
2021-08-10T02:48:57.000Z
|
GameEngine/Sources/IndexBufferSegment.cpp
|
GPUWorks/OpenGL-Mini-CAD-2D
|
fedb903302f82a1d1ff0ca6776687a60a237008a
|
[
"MIT"
] | null | null | null |
GameEngine/Sources/IndexBufferSegment.cpp
|
GPUWorks/OpenGL-Mini-CAD-2D
|
fedb903302f82a1d1ff0ca6776687a60a237008a
|
[
"MIT"
] | null | null | null |
#include "IndexBufferSegment.h"
//------------------------------ Constructors
storage::IndexBufferSegment::IndexBufferSegment()
{
}
storage::IndexBufferSegment::IndexBufferSegment(GLuint start, GLuint end)
{
this->start = start;
this->end = end;
}
//------------------------------ Secondary Functions (Provide Data)
void storage::IndexBufferSegment::update(GLuint start, GLuint end)
{
this->start = start;
this->end = end;
}
void storage::IndexBufferSegment::update(GLuint end)
{
this->end = end;
}
| 17.548387
| 74
| 0.606618
|
GPUWorks
|
fa87955f9a6f32cc158faeaa7263440951aa935b
| 2,821
|
cpp
|
C++
|
src/main.cpp
|
cbeck88/flashcards
|
dc3a517c1bb527645358db0229075b4a1692c3c6
|
[
"WTFPL"
] | null | null | null |
src/main.cpp
|
cbeck88/flashcards
|
dc3a517c1bb527645358db0229075b4a1692c3c6
|
[
"WTFPL"
] | null | null | null |
src/main.cpp
|
cbeck88/flashcards
|
dc3a517c1bb527645358db0229075b4a1692c3c6
|
[
"WTFPL"
] | null | null | null |
#include <algorithm>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "catalog.hpp"
namespace flash {
struct controller {
catalog cards;
std::mt19937 rng;
static void prompt_impl(const std::string & query, const std::string & answer) {
std::cout << '"' << query << "\":" << std::endl;
std::string result;
std::getline(std::cin, result);
std::cout << answer << std::endl << std::endl;
}
static void prompt_forward(const spair & card) {
prompt_impl(card.first, card.second);
}
static void prompt_backward(const spair & card) {
prompt_impl(card.second, card.first);
}
std::vector<int> get_cards_permutation() {
std::vector<int> result(cards.size());
for (unsigned int i = 0; i < result.size(); ++i) {
result[i] = i;
}
std::shuffle(result.begin(), result.end(), rng);
return result;
}
template <typename V>
void for_each_card(V && v) {
std::vector<int> perm{ this->get_cards_permutation() };
for (int idx : perm) {
v(cards[idx]);
}
}
// Main interface
void do_each_forward() {
this->for_each_card(controller::prompt_forward);
}
void do_each_backward() {
this->for_each_card(controller::prompt_backward);
}
// ctor
controller(catalog && cat)
: cards(std::move(cat))
, rng()
{
std::random_device rdev;
rng = std::mt19937(rdev());
}
};
} // end namespace flash
int main(int argc, char * argv[]) {
if (argc != 2) { std::cerr << "Expected: [catalog file]\n"; return 1; }
std::string fname{argv[1]};
std::ifstream ifs{fname};
if (!ifs) { std::cerr << "Could not read file: " << fname << std::endl; return 1; }
flash::catalog cat{ flash::parse_catalog(ifs) };
std::cout << "Read: " << cat.size() << " flash cards." << std::endl;
if (!cat.size()) { return 0; }
else {
std::cout << std::endl;
for (const auto & card : cat) {
std::cout << card.first << " -- " << card.second << std::endl;
}
std::cout << std::endl;
std::cout << std::endl;
}
// Load cards into the controller
flash::controller ctrl{std::move(cat)};
// Main loop
int option = 0;
do {
std::cout << "\nOptions:\n"
<< "[1] Read flash cards forwards\n"
<< "[2] Read flash cards backwards\n"
<< "[0] Exit\n"
<< std::endl;
option = 0;
if (std::cin >> option) {
std::string temp;
std::getline(std::cin, temp);
switch (option) {
case 1:
ctrl.do_each_forward();
break;
case 2:
ctrl.do_each_backward();
break;
default:
option = 0;
break;
}
}
} while(option);
std::cout << "Goodbye!" << std::endl;
}
| 20.442029
| 85
| 0.556186
|
cbeck88
|
fa88d7eba6f8e9eaf50ecb4b4df86f9b212bed51
| 6,340
|
cc
|
C++
|
tasks/process_metabuf_task.cc
|
smukil/cachemover
|
159ae10072f23b7d4168a804b672e1e810d4df19
|
[
"Apache-2.0"
] | 27
|
2021-11-27T06:11:54.000Z
|
2022-03-31T18:53:51.000Z
|
tasks/process_metabuf_task.cc
|
Netflix/cachemover
|
236998c442eed704cc9cf9df9be4f299e7f3b6e1
|
[
"Apache-2.0"
] | null | null | null |
tasks/process_metabuf_task.cc
|
Netflix/cachemover
|
236998c442eed704cc9cf9df9be4f299e7f3b6e1
|
[
"Apache-2.0"
] | null | null | null |
/**
*
* Copyright 2021 Netflix, 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 "common/logger.h"
#include "dumper/dumper.h"
#include "tasks/process_metabuf_task.h"
#include "tasks/s3_upload_task.h"
#include "tasks/task_scheduler.h"
#include "tasks/task_thread.h"
#include "utils/mem_mgr.h"
#include "utils/memcache_utils.h"
#include "utils/socket.h"
#include <fstream>
#include <sstream>
namespace memcachedumper {
ProcessMetabufTask::ProcessMetabufTask(const std::string& filename, bool is_s3_dump)
: filename_(filename),
is_s3_dump_(is_s3_dump) {
}
std::string ProcessMetabufTask::UrlDecode(std::string& str){
std::ostringstream oss;
char ch;
int i, ii, len = str.length();
for (i=0; i < len; i++){
if(str[i] != '%'){
if(str[i] == '+')
oss << ' ';
else
oss << str[i];
}else{
sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
oss << ch;
i = i + 2;
}
}
return oss.str();
}
void ProcessMetabufTask::ProcessMetaBuffer(MetaBufferSlice* mslice) {
time_t now = std::time(0);
char* newline_pos = nullptr;
do {
const char *key_pos = mslice->next_key_pos();
if (key_pos == nullptr) {
if (newline_pos != nullptr) {
mslice->CopyRemainingToStart(newline_pos);
}
break;
}
const char *exp_pos = mslice->next_exp_pos();
if (exp_pos == nullptr) {
if (newline_pos != nullptr) {
mslice->CopyRemainingToStart(newline_pos);
}
break;
}
const char *la_pos = mslice->next_la_pos();
if (la_pos == nullptr) {
if (newline_pos != nullptr) {
mslice->CopyRemainingToStart(newline_pos);
}
break;
}
char *unused;
int32_t expiry = strtol(exp_pos + 4, &unused, 10);
std::string encoded_key(
const_cast<char*>(key_pos) + 4, static_cast<int>(
exp_pos - key_pos - 4 - 1));
std::string decoded_key = UrlDecode(encoded_key);
if (expiry != -1 && MemcachedUtils::KeyExpiresSoon(now,
static_cast<uint32_t>(expiry))) {
owning_thread()->increment_keys_ignored();
continue;
}
// Filter the key out if required.
if (MemcachedUtils::FilterKey(decoded_key) == true) {
owning_thread()->increment_keys_filtered();
continue;
}
// Track the key and queue it for processing.
McData *new_key = new McData(decoded_key, expiry);
data_writer_->QueueForProcessing(new_key);
} while ((newline_pos = const_cast<char*>(mslice->next_newline())) != nullptr);
}
void ProcessMetabufTask::MarkCheckpoint() {
std::ofstream checkpoint_file;
std::string chkpt_file_path =
MemcachedUtils::GetKeyFilePath() + "CHECKPOINTS_" + owning_thread()->thread_name();
checkpoint_file.open(chkpt_file_path, std::ofstream::app);
// Omit the path while writing the file name.
// Also add a new line after every file name.
std::string file_sans_path = filename_.substr(filename_.rfind("/") + 1) + "\n";
checkpoint_file.write(file_sans_path.c_str(), file_sans_path.length());
checkpoint_file.close();
}
void ProcessMetabufTask::Execute() {
Socket *mc_sock = owning_thread()->task_scheduler()->GetMemcachedSocket();
assert(mc_sock != nullptr);
uint8_t* data_writer_buf = owning_thread()->mem_mgr()->GetBuffer();
assert(data_writer_buf != nullptr);
// Extract the key file's index from its name, so that we can use the same index
// for data files.
std::string keyfile_idx_str = filename_.substr(filename_.rfind("_") + 1);
data_writer_.reset(new KeyValueWriter(
MemcachedUtils::DataFilePrefix() + "_" + keyfile_idx_str,
owning_thread()->thread_name(),
data_writer_buf, owning_thread()->mem_mgr()->chunk_size(),
MemcachedUtils::MaxDataFileSize(), mc_sock));
// TODO: Check return status
Status init_status = data_writer_->Init();
if (!init_status.ok()) {
LOG_ERROR("FAILED TO INITIALIZE KeyValueWriter. (Status: {0})", init_status.ToString());
owning_thread()->task_scheduler()->ReleaseMemcachedSocket(mc_sock);
owning_thread()->mem_mgr()->ReturnBuffer(data_writer_buf);
return;
}
std::ifstream metafile;
metafile.open(filename_);
LOG("Processing file: {0}", filename_);
char *metabuf = reinterpret_cast<char*>(owning_thread()->mem_mgr()->GetBuffer());
uint64_t buf_size = owning_thread()->mem_mgr()->chunk_size();
int32_t bytes_read = metafile.readsome(metabuf, buf_size);
size_t mslice_size = bytes_read;
char *buf_begin_fill = metabuf;
while (bytes_read > 0) {
MetaBufferSlice mslice(metabuf, mslice_size);
ProcessMetaBuffer(&mslice);
// Find number of bytes free in the buffer. Usually should be the entire 'buf_size',
// but in some cases, we can have a little leftover unparsed bytes at the end of the
// buffer which 'ProcessMetaBuffer()' would have copied to the start of the buffer.
size_t free_bytes = mslice.free_bytes();
size_t size_remaining = mslice.size() - free_bytes;
// Start filling the buffer from after the unparsed bytes.
buf_begin_fill = mslice.buf_begin_fill();
bytes_read = metafile.readsome(buf_begin_fill, free_bytes);
mslice_size = size_remaining + bytes_read;
}
data_writer_->Finalize();
owning_thread()->account_keys_processed(data_writer_->num_processed_keys());
owning_thread()->account_keys_missing(data_writer_->num_missing_keys());
metafile.close();
owning_thread()->task_scheduler()->ReleaseMemcachedSocket(mc_sock);
owning_thread()->mem_mgr()->ReturnBuffer(reinterpret_cast<uint8_t*>(metabuf));
owning_thread()->mem_mgr()->ReturnBuffer(data_writer_buf);
MarkCheckpoint();
}
} // namespace memcachedumper
| 31.078431
| 92
| 0.672871
|
smukil
|
fa8a431ac27f66c322f134372c2d59cc6876d0b4
| 3,263
|
inl
|
C++
|
owCore/RefManager1DimAssync.inl
|
adan830/OpenWow
|
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
|
[
"Apache-2.0"
] | null | null | null |
owCore/RefManager1DimAssync.inl
|
adan830/OpenWow
|
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
|
[
"Apache-2.0"
] | null | null | null |
owCore/RefManager1DimAssync.inl
|
adan830/OpenWow
|
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
|
[
"Apache-2.0"
] | 1
|
2020-05-11T13:32:49.000Z
|
2020-05-11T13:32:49.000Z
|
#pragma once
#include "RefManager1DimAssync.h"
template <class T>
CRefManager1DimAssync<T>::CRefManager1DimAssync()
{
#ifndef DISABLE_ASSYNC
if (m_Event_Add == nullptr && m_Thread_Loader == nullptr)
{
m_Event_Add = CreateEvent(NULL, TRUE, TRUE, NULL);
m_Thread_Loader = CreateThread(NULL, 0, &ThreadProc, this, NULL, NULL);
SetThreadPriority(m_Thread_Loader, THREAD_PRIORITY_BELOW_NORMAL);
}
#endif
}
template <class T>
CRefManager1DimAssync<T>::~CRefManager1DimAssync()
{
for (auto it = objects.begin(); it != objects.end(); )
{
SharedTexturePtr item = it->second;
string name = GetNameByItem(item);
this->DeleteAction(name);
//delete item;
it = objects.erase(it);
//item = nullptr;
}
#ifndef DISABLE_ASSYNC
ResetEvent(m_Event_Add);
CloseHandle(m_Event_Add);
TerminateThread(m_Thread_Loader, 1);
CloseHandle(m_Thread_Loader);
#endif
}
template <class T>
inline shared_ptr<T> CRefManager1DimAssync<T>::Add(cstring name)
{
SharedTexturePtr item = GetItemByName(name);
if (item != nullptr)
{
return item;
}
item = CreateAction(name);
#ifndef DISABLE_ASSYNC
// Add to load list
m_ObjectsToLoad.add(name, item);
// Start thread if stopped
if (m_ObjectsToLoad.size() > 0)
{
SetEvent(m_Event_Add);
}
#else
LoadAction(name, item);
#endif
if (item != nullptr)
{
objects[name] = item;
}
return item;
}
template <class T>
bool CRefManager1DimAssync<T>::Exists(cstring name) const
{
return objects.find(name) != objects.end();
}
template <class T>
inline void CRefManager1DimAssync<T>::Delete(cstring name)
{
shared_ptr<T> item = GetItemByName(name);
if (item != nullptr)
{
auto it = objects.find(name);
this->DeleteAction(name);
//delete item;
objects.erase(name);
//item = nullptr;
}
}
template <class T>
inline void CRefManager1DimAssync<T>::Delete(shared_ptr<T> item)
{
for (auto it = objects.begin(); it != objects.end(); ++it)
{
if (it->second == item)
{
this->Delete(it->first);
return;
}
}
// If not found
//delete item;
//item = nullptr;
}
template <class T>
inline shared_ptr<T> CRefManager1DimAssync<T>::GetItemByName(cstring name) const
{
auto name_item = objects.find(name);
if (name_item != objects.end())
{
return name_item->second;
}
return nullptr;
}
template <class T>
inline std::string CRefManager1DimAssync<T>::GetNameByItem(shared_ptr<T> item) const
{
for (auto it = objects.begin(); it != objects.end(); ++it)
{
if (it->second == item)
{
return it->first;
}
}
return "";
}
// Log
template <class T>
inline void CRefManager1DimAssync<T>::PrintAllInfo()
{
uint32 refsCnt = 0;
for (auto it = objects.begin(); it != objects.end(); ++it)
{
refsCnt += it->second.use_count();
Log::Info("Item (%d) [%s]", it->second.use_count(), it->first.c_str());
}
Log::Info("Item's count [%d], items refs [%d]", objects.size(), refsCnt);
}
template<class T>
inline shared_ptr<T> CRefManager1DimAssync<T>::CreateAction(cstring name)
{
return NULL;
}
template<class T>
inline void CRefManager1DimAssync<T>::LoadAction(string name, shared_ptr<T>& item)
{
}
template<class T>
inline bool CRefManager1DimAssync<T>::DeleteAction(cstring name)
{
return false;
}
template<class T>
inline void CRefManager1DimAssync<T>::MakeContext()
{
}
| 18.861272
| 84
| 0.694146
|
adan830
|
fa8c15f2e16ba4777ea1417d021e2af3df6b2e70
| 5,157
|
cpp
|
C++
|
Source/src/components/ComponentObstacle.cpp
|
Akita-Interactive/Hachiko-Engine
|
0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b
|
[
"MIT"
] | 5
|
2022-02-10T23:31:11.000Z
|
2022-02-11T19:32:38.000Z
|
Source/src/components/ComponentObstacle.cpp
|
Akita-Interactive/Hachiko-Engine
|
0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b
|
[
"MIT"
] | null | null | null |
Source/src/components/ComponentObstacle.cpp
|
Akita-Interactive/Hachiko-Engine
|
0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b
|
[
"MIT"
] | null | null | null |
#include "core/hepch.h"
#include "ComponentObstacle.h"
#include "ComponentTransform.h"
#include "Application.h"
#include "modules/ModuleNavigation.h"
#include "resources/ResourceNavMesh.h"
#include "DetourTileCache/DetourTileCache.h"
Hachiko::ComponentObstacle::ComponentObstacle(GameObject* container) : Component(Type::OBSTACLE, container)
{}
Hachiko::ComponentObstacle::~ComponentObstacle()
{
RemoveObstacle();
}
void Hachiko::ComponentObstacle::Start()
{
AddObstacle();
}
void Hachiko::ComponentObstacle::Stop()
{
RemoveObstacle();
}
void Hachiko::ComponentObstacle::Update()
{
if (dirty)
{
++count_since_update;
if (count_since_update > update_freq)
{
RefreshObstacle();
dirty = false;
count_since_update = 0;
}
}
}
void Hachiko::ComponentObstacle::OnTransformUpdated()
{
Invalidate();
}
void Hachiko::ComponentObstacle::SetType(ObstacleType new_type)
{
obstacle_type = new_type;
Invalidate();
}
void Hachiko::ComponentObstacle::SetSize(const float3& new_size)
{
size = new_size;
Invalidate();
}
void Hachiko::ComponentObstacle::DrawGui()
{
ImGui::PushID(this);
if (ImGui::CollapsingHeader("Obstacle", ImGuiTreeNodeFlags_DefaultOpen))
{
if (!obstacle && ImGui::Button("Add to navmesh"))
{
AddObstacle();
}
if (obstacle && ImGui::Button("Remove from navmesh"))
{
RemoveObstacle();
}
if (obstacle_type == ObstacleType::DT_OBSTACLE_CYLINDER)
{
if (ImGui::DragFloat2("Radius, Height", size.ptr()))
{
SetSize(size);
}
}
else
{
if (ImGui::DragFloat3("Size", size.ptr()))
{
SetSize(size);
}
}
bool changed_type = false;
ImGui::Text("Type");
changed_type |= ImGui::RadioButton("Cylinder", (int*) &obstacle_type, static_cast<int>(ObstacleType::DT_OBSTACLE_CYLINDER));
ImGui::SameLine();
changed_type |= ImGui::RadioButton("Box", (int*)&obstacle_type, static_cast<int>(ObstacleType::DT_OBSTACLE_BOX));
ImGui::SameLine();
changed_type |= ImGui::RadioButton("Oriented Box", (int*)&obstacle_type, static_cast<int>(ObstacleType::DT_OBSTACLE_ORIENTED_BOX));
if (changed_type)
{
SetType(obstacle_type); // Changes the obstacle type
}
ImGui::Text("Exists: %d", obstacle != nullptr);
}
ImGui::PopID();
}
void Hachiko::ComponentObstacle::AddObstacle()
{
dtTileCache* tile_cache = App->navigation->GetTileCache();
if (!tile_cache)
{
HE_LOG("Failed to add obstacle on unexisting tile cache");
return;
}
// If obstacle is already set remove it before adding it again
// Remove already contains the check
RemoveObstacle();
obstacle = new dtObstacleRef;
ComponentTransform* transform = game_object->GetTransform();
switch (obstacle_type)
{
case ObstacleType::DT_OBSTACLE_CYLINDER:
// In this case we dont use size z, we only need height and radius
// Look for draw gizmo option that seems to be used on some examples
tile_cache->addObstacle(transform->GetGlobalPosition().ptr(), size.x, size.y, obstacle);
break;
case ObstacleType::DT_OBSTACLE_BOX:
{
// This case needs a scope for initializing
AABB aabb;
aabb.SetFromCenterAndSize(transform->GetGlobalPosition(), size);
tile_cache->addBoxObstacle(aabb.minPoint.ptr(), aabb.maxPoint.ptr(), obstacle);
break;
}
case ObstacleType::DT_OBSTACLE_ORIENTED_BOX:
// Method expects half the desired size of the box to be passed
// Expects y rotation in radians and says box cant be rotated in y
tile_cache->addBoxObstacle(transform->GetGlobalPosition().ptr(), (size / 2.f).ptr(), transform->GetGlobalRotation().ToEulerXYX().y, obstacle);
break;
}
if (!obstacle)
{
HE_LOG("Failed to add obstacle with existing navmesh and tile cache");
}
}
void Hachiko::ComponentObstacle::RemoveObstacle()
{
if (!obstacle)
{
// No need to remove an obstacle that is already not being used
return;
}
dtTileCache* tile_cache = App->navigation->GetTileCache();
if (!tile_cache)
{
HE_LOG("Failed to remove obstacle from unexisting tile cache");
return;
}
tile_cache->removeObstacle(*obstacle);
RELEASE(obstacle);
}
void Hachiko::ComponentObstacle::RefreshObstacle()
{
if (obstacle)
{
// Refesh the obstacle position if it exists
AddObstacle();
}
}
void Hachiko::ComponentObstacle::Save(YAML::Node& node) const
{
node[OBSTACLE_TYPE] = static_cast<unsigned int>(obstacle_type);
node[OBSTACLE_SIZE] = size;
}
void Hachiko::ComponentObstacle::Load(const YAML::Node& node)
{
SetType(static_cast<ObstacleType>(node[OBSTACLE_TYPE].as<unsigned int>()));
SetSize(node[OBSTACLE_SIZE].as<float3>());
}
| 27
| 150
| 0.631181
|
Akita-Interactive
|
fa8faa3a10d43824e6cca0cee3f02a341a6cd088
| 519
|
cpp
|
C++
|
leetcode2/countprime.cpp
|
WIZARD-CXY/pl
|
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
|
[
"Apache-2.0"
] | 1
|
2016-01-20T08:26:34.000Z
|
2016-01-20T08:26:34.000Z
|
leetcode2/countprime.cpp
|
WIZARD-CXY/pl
|
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
|
[
"Apache-2.0"
] | 1
|
2015-10-21T05:38:17.000Z
|
2015-11-02T07:42:55.000Z
|
leetcode2/countprime.cpp
|
WIZARD-CXY/pl
|
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
int countPrimes(int n) {
vector<bool> vis(n,0);
for(int i=2; i<sqrt(n); i++){
if(!vis[i]){
// j*i may overflow when n is large near INT_MAX
for(int j=i; j*i<n; j++){
vis[j*i]=1;
}
}
}
int cnt=0;
for(int i=2; i<n; i++){
if(!vis[i]){
cnt++;
}
}
return cnt;
}
};
| 20.76
| 64
| 0.314066
|
WIZARD-CXY
|
fa998feef8edbb4fa6a19de46241a75869655a88
| 10,531
|
cpp
|
C++
|
Sunny-Core/01_FRAMEWORK/app/Window.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | 20
|
2018-01-19T06:28:36.000Z
|
2021-08-06T14:06:13.000Z
|
Sunny-Core/01_FRAMEWORK/app/Window.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | null | null | null |
Sunny-Core/01_FRAMEWORK/app/Window.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | 3
|
2019-01-29T08:58:04.000Z
|
2021-01-02T06:33:20.000Z
|
//
// Created by adunstudio on 2018-01-08.
//
#include "Window.h"
#include "../directx/Context.h"
#include "../directx/Renderer.h"
#include "../graphics/fonts/FontManager.h"
#include "../audio/MusicManager.h"
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
namespace sunny
{
// 메시지를 처리하는 함수
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
// Input.cpp
extern void KeyCallback(InputManager* inputManager, int flags, int key, unsigned int message);
extern void MouseButtonCallback(InputManager* inputManager, int button, int x, int y);
// Server.cpp
extern void ServerPacketCallback(ServerManager* serverManager, SOCKET socket);
extern void ServerCloseCallback (ServerManager* serverManager, SOCKET socket);
HINSTANCE hInstance; // 윈도우 핸들 인스턴스 식별자
HDC hDc; // 윈도우 핸들 디바이스 컨텍스트
HWND hWnd; // 윈도우 핸들 (번호)
std::map<void*, Window*> Window::s_handles;
void Window::RegisterWindowClass(void* handle, Window* window)
{
s_handles[handle] = window;
}
Window* Window::GetWindowClass(void* handle)
{
if(handle == nullptr)
return s_handles.begin()->second;
return s_handles[handle];
}
Window::Window(const std::string title, const WindowProperties& properties)
: m_title(title), m_properties(properties), m_handle(nullptr), m_closed(false)
{
m_resolutionWidth = m_properties.width ;
m_resolutionHeight = m_properties.height;
if(!Init())
{
// TODO: Debug System
return;
}
using namespace graphics;
//FontManager::SetScale(maths::vec2(m_properties.width, m_properties.height));
FontManager::Add(new Font("nanum", "04_ASSET/FONT/NanumGothic.ttf", 32));
FontManager::Add(new Font("nanum", "04_ASSET/FONT/NanumGothic.ttf", 24));
FontManager::Add(new Font("nanum", "04_ASSET/FONT/NanumGothic.ttf", 16));
FontManager::Add(new Font("consola", "04_ASSET/FONT/consola.ttf", 32));
FontManager::Add(new Font("SourceSansPro", "04_ASSET/FONT/SourceSansPro-Light.ttf", 32));
FontManager::Add(new Font("dot", "04_ASSET/FONT/small_dot_digital-7.ttf", 32));
FontManager::Add(new Font("dot", "04_ASSET/FONT/small_dot_digital-7.ttf", 24));
FontManager::Add(new Font("dot", "04_ASSET/FONT/small_dot_digital-7.ttf", 16));
FontManager::Add(new Font("power", "04_ASSET/FONT/power_pixel-7.ttf", 32));
FontManager::Add(new Font("power", "04_ASSET/FONT/power_pixel-7.ttf", 24));
FontManager::Add(new Font("power", "04_ASSET/FONT/power_pixel-7.ttf", 16));
FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 32));
FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 28));
FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 24));
FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 16));
FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 16));
FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 24));
FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 28));
FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 32));
m_inputManager = new InputManager();
m_serverManager = new ServerManager();
audio::MusicManager::Init();
}
Window::~Window()
{
audio::MusicManager::Clean();
}
bool Window::Init()
{
hInstance = (HINSTANCE)&__ImageBase;
WNDCLASS winClass = {}; // 생성하려는 윈도우의 속성 값을 저장해 등록하는 구조체
winClass.hInstance = hInstance; //
winClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // 윈도우가 출력되는 형태
winClass.lpfnWndProc = (WNDPROC)WndProc; // 메시지 처리에 사용될 함수
winClass.lpszClassName = (LPCTSTR)"Sunny Win64 Window"; // 윈도우 클래스의 이름 (윈도우를 만들 때 이 이름을 이용한다.)
winClass.hCursor = LoadCursor(nullptr, IDC_ARROW); // 기본 커서
winClass.hIcon = LoadIcon(nullptr, IDI_WINLOGO); // 기본 아이콘
/*
winClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // 윈도우의 배경 색
winClass.cbClsExtra = 0; // 클래스를 위한 여분의 메모리 크기
winClass.cbWndExtra = 0; // 윈도우를 위한 여분의 메모리 크기
*/
// 윈도우 클래스를 커널에 등록한다.
if(!RegisterClass(&winClass))
{
// TODO: Debug System
return false;
}
RECT size = { 0, 0, m_properties.width, m_properties.height };
DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU | WS_BORDER;
// WS_OVERLAPPEDWINDOW : 타이틀 바에 최소화, 최대화, 닫기 버튼이 나타나고 오른쪽 버튼을 눌렀을 때 시스템 메뉴가 나타난다.
// WS_OVERLAPPED : 기본적인 윈도우로 아이콘이 없고 최소화, 최대화, 닫기 버튼도 없다, 또한 시스템 메뉴가 나타나지 않는다.
// ... 검색
AdjustWindowRect(&size, style, false);
// TODO: 한글 처리
hWnd = CreateWindowEx(
WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, // 태스크바에 나타낸다.
winClass.lpszClassName, // 윈도우 클래스의 이름
//(LPCWSTR)m_title.c_str(), // 만들어질 윈도우의 타이틀 바에 나타내는 문자열
_T("가나sunny"), // 만들어질 윈도우의 타이틀 바에 나타내는 문자열
WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // 윈도우 스타일 조합
GetSystemMetrics(SM_CXSCREEN) / 2 - m_properties.width / 2, // 윈도우 생성 위치 x
GetSystemMetrics(SM_CYSCREEN) / 2 - m_properties.height / 2 - 40, // 윈도우 생성 위치 y
// TODO: This requires some... attention
size.right + (-size.left), size.bottom + (-size.top), // 생성되는 윈도우의 폭과 높이
NULL,
NULL,
hInstance,
NULL
);
m_handle = hWnd;
if(!hWnd)
{
// TODO: Debug System
return false;
}
RegisterWindowClass(hWnd, this);
directx::Context::Create(m_properties, hWnd);
ShowWindow(hWnd, SW_SHOW);
SetFocus(hWnd);
directx::Renderer::Init();
directx::GeometryBuffer::Init();
SetTitle(m_title);
// imGui
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImFont* pFont = io.Fonts->AddFontFromFileTTF("04_ASSET/FONT/NanumGothic.ttf", 17, NULL, io.Fonts->GetGlyphRangesKorean());
ImGui_ImplDX11_Init(hWnd, directx::Context::GetDevice(), directx::Context::GetDeviceContext(DIMENSION::D2));
ImGui::StyleColorsDark();
return true;
}
void Window::Update()
{
MSG message;
while(PeekMessage(&message, nullptr, 0, 0, PM_REMOVE) > 0)
{
if (message.message == WM_QUIT)
{
m_closed = true;
return;
}
TranslateMessage(&message);
DispatchMessage(&message);
}
audio::MusicManager::Update();
m_inputManager->Update();
directx::Renderer::Present();
}
void Window::Clear() const
{
// 화면을 지워주는 작업
directx::Renderer::Clear(RENDERER_BUFFER_COLOR | RENDERER_BUFFER_DEPTH | RENDERER_BUFFER_SHADOW | RENDERER_BUFFER_DEFERRED);
}
bool Window::Closed() const
{
return m_closed;
}
void Window::SetTitle(const std::string title)
{
m_title = title;
wchar_t* text = CA2W(title.c_str());
SetWindowText(hWnd, text);
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, message, wParam, lParam))
return true;
LRESULT result = NULL;
Window* window = Window::GetWindowClass(hWnd);
if(window == nullptr)
return DefWindowProc(hWnd, message, wParam, lParam);
InputManager* inputManager = window->GetInputManager();
ServerManager* serverManager = window->GetServerManager();
switch(message)
{
case WM_SETFOCUS:
FocusCallback(window, true);
break;
case WM_KILLFOCUS:
FocusCallback(window, false);
break;
case WM_CLOSE:
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
KeyCallback(inputManager, lParam, wParam, message);
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
MouseButtonCallback(inputManager, message, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
break;
case WM_SIZE:
ResizeCallback(window, LOWORD(lParam), HIWORD(lParam));
break;
case WM_SOCKET:
if (WSAGETSELECTERROR(lParam))
{
ServerCloseCallback(serverManager, (SOCKET)wParam);
break;
}
switch (WSAGETSELECTEVENT(lParam))
{
case FD_READ:
ServerPacketCallback(serverManager, (SOCKET)wParam);
break;
case FD_CLOSE:
ServerCloseCallback(serverManager, (SOCKET)wParam);
break;
}
default:
result = DefWindowProc(hWnd, message, wParam, lParam);
}
return result;
}
void Window::SetVsnyc(bool enabled)
{
m_properties.vsync = enabled;
}
void Window::SetEventCallback(const WindowEventCallback& callback)
{
m_eventCallback = callback;
m_inputManager->SetEventCallback(m_eventCallback);
m_serverManager->SetEventCallback(m_eventCallback);
}
void ResizeCallback(Window* window, int width, int height)
{
window->m_properties.width = width;
window->m_properties.height = height;
if (window->m_eventCallback)
window->m_eventCallback(events::ResizeEvent((unsigned int)width, (unsigned int)height));
}
void FocusCallback(Window* window, bool focused)
{
// 포커싱 또는 포커싱을 잃었을때 작업하는 함수
}
}
| 34.191558
| 126
| 0.590827
|
adunStudio
|
b709c7b500a0492d0c671d56147ebbf9410e0376
| 2,042
|
cpp
|
C++
|
src/xercesc/util/Compilers/OS400SetDefs.cpp
|
rherardi/xerces-c-src_2_7_0
|
a23711292bba70519940d7e6aeb07100319b607c
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/xercesc/util/Compilers/OS400SetDefs.cpp
|
rherardi/xerces-c-src_2_7_0
|
a23711292bba70519940d7e6aeb07100319b607c
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/xercesc/util/Compilers/OS400SetDefs.cpp
|
rherardi/xerces-c-src_2_7_0
|
a23711292bba70519940d7e6aeb07100319b607c
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: OS400SetDefs.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <sys/types.h>
#include <ctype.h>
int
strcasecmp (const char *string1,const char * string2)
{
char *s1, *s2;
int result;
s1 = (char *)string1;
s2 = (char *)string2;
while ((result = tolower (*s1) - tolower (*s2)) == 0)
{
if (*s1++ == '\0')
return 0;
s2++;
}
return (result);
}
int
strncasecmp (const char *string1,const char *string2,size_t count)
{
register char *s1, *s2;
register int r;
register unsigned int rcount;
rcount = (unsigned int) count;
if (rcount > 0)
{
s1 = (char *)string1;
s2 = (char *)string2;
do
{
if ((r = tolower (*s1) - tolower (*s2)) != 0)
return r;
if (*s1++ == '\0')
break;
s2++;
}
while (--rcount != 0);
}
return (0);
}
/* des not appear as though the following is needed */
#ifndef __OS400__
int stricmp(const char* str1, const char* str2)
{
return strcasecmp(str1, str2);
}
int strnicmp(const char* str1, const char* str2, const unsigned int count)
{
if (count == 0)
return 0;
return strncasecmp( str1, str2, (size_t)count);
}
#endif
| 24.902439
| 79
| 0.561704
|
rherardi
|
b710336e07b0b9bf6a9d9ce277efd5d7fb416817
| 221
|
cpp
|
C++
|
src/actionscript/extern.cpp
|
feliwir/libapt
|
43b05b3de632896cb7d1351191a07c0f0cdf801a
|
[
"MIT"
] | 7
|
2016-12-19T21:13:41.000Z
|
2021-03-19T11:14:29.000Z
|
src/actionscript/extern.cpp
|
feliwir/libapt
|
43b05b3de632896cb7d1351191a07c0f0cdf801a
|
[
"MIT"
] | 1
|
2017-06-17T12:14:08.000Z
|
2017-06-17T14:47:20.000Z
|
src/actionscript/extern.cpp
|
feliwir/libapt
|
43b05b3de632896cb7d1351191a07c0f0cdf801a
|
[
"MIT"
] | 3
|
2017-11-07T12:22:10.000Z
|
2020-04-30T20:48:59.000Z
|
#include "extern.hpp"
using namespace libapt;
using namespace libapt::as;
Value Extern::GetProperty(const std::string & property)
{
return Value();
}
void Extern::SetProperty(const std::string & property, Value v)
{
}
| 17
| 63
| 0.733032
|
feliwir
|
b711e7c11ff601db91700d6e00c83529e7742b52
| 20,780
|
hpp
|
C++
|
src/ttauri/bigint.hpp
|
RustWorks/ttauri
|
4b093eb16465091d01d80159e23fd26e5d4e4c03
|
[
"BSL-1.0"
] | 279
|
2021-02-17T09:53:40.000Z
|
2022-03-22T04:08:40.000Z
|
src/ttauri/bigint.hpp
|
RustWorks/ttauri
|
4b093eb16465091d01d80159e23fd26e5d4e4c03
|
[
"BSL-1.0"
] | 269
|
2021-02-17T12:53:15.000Z
|
2022-03-29T22:10:49.000Z
|
src/ttauri/bigint.hpp
|
sthagen/ttauri
|
772f4e55c007e0bc199a07d86ef4e2d4d46af139
|
[
"BSL-1.0"
] | 25
|
2021-02-17T17:14:10.000Z
|
2022-03-16T04:13:00.000Z
|
// Copyright Take Vos 2019-2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "strings.hpp"
#include "math.hpp"
#include "int_carry.hpp"
#include "codec/base_n.hpp"
#include <format>
#include <type_traits>
#include <ostream>
#include <concepts>
namespace tt::inline v1 {
/** High performance big integer implementation.
* The bigint is a fixed width integer which will allow the compiler
* to make aggressive optimizations, unrolling most loops and easy inlining.
*/
template<std::unsigned_integral DigitType, std::size_t NumDigits, bool IsSigned>
struct bigint {
using digit_type = DigitType;
using signed_digit_type = std::make_signed_t<digit_type>;
static constexpr auto num_digits = NumDigits;
static constexpr auto is_signed = IsSigned;
static constexpr auto bits_per_digit = sizeof(digit_type) * CHAR_BIT;
static constexpr digit_type zero_digit = 0;
static constexpr digit_type min1_digit = static_cast<digit_type>(signed_digit_type{-1});
/** Digits, in little endian order.
*/
digit_type digits[num_digits];
/** Construct and clear an bigint.
*/
constexpr bigint() noexcept
{
for (std::size_t i = 0; i != num_digits; ++i) {
digits[i] = zero_digit;
}
}
constexpr bigint(bigint const &) noexcept = default;
constexpr bigint &operator=(bigint const &) noexcept = default;
constexpr bigint(bigint &&) noexcept = default;
constexpr bigint &operator=(bigint &&) noexcept = default;
/** Construct from a small bigint.
*/
template<std::size_t N, bool S>
constexpr bigint(bigint<digit_type, N, S> const &rhs) noexcept requires(N < num_digits)
{
std::size_t i = 0;
// Copy the data from a smaller bigint.
for (; i != N; ++i) {
digits[i] = rhs.digits[i];
}
// Sign extent the most-siginificant-digit.
ttlet sign = rhs.is_negative() ? min1_digit : zero_digit;
for (; i != num_digits; ++i) {
digits[i] = sign;
}
}
/** Assign from a small bigint.
*/
template<std::size_t N, bool S>
constexpr bigint &operator=(bigint<digit_type, N, S> const &rhs) noexcept requires(N < num_digits)
{
std::size_t i = 0;
// Copy the data from a smaller bigint.
for (; i != N; ++i) {
digits[i] = rhs.digits[i];
}
// Sign extent the most-siginificant-digit.
ttlet sign = rhs.is_negative() ? min1_digit : zero_digit;
for (; i != num_digits; ++i) {
digits[i] = sign;
}
return *this;
}
constexpr bigint(std::integral auto value) noexcept
{
static_assert(sizeof(value) <= sizeof(digit_type));
static_assert(num_digits > 0);
if constexpr (std::is_signed_v<decltype(value)>) {
// Sign extent the value to the size of the first digit.
digits[0] = static_cast<digit_type>(static_cast<signed_digit_type>(value));
} else {
digits[0] = static_cast<digit_type>(value);
}
// Sign extent to the rest of the digits.
ttlet sign = value < 0 ? min1_digit : zero_digit;
for (std::size_t i = 1; i != num_digits; ++i) {
digits[i] = sign;
}
}
constexpr bigint &operator=(std::integral auto value) noexcept
{
static_assert(sizeof(value) <= sizeof(digit_type));
static_assert(num_digits > 0);
if constexpr (std::is_signed_v<decltype(value)>) {
// Sign extent the value to the size of the first digit.
digits[0] = static_cast<digit_type>(static_cast<signed_digit_type>(value));
} else {
digits[0] = static_cast<digit_type>(value);
}
// Sign extent to the rest of the digits.
ttlet sign = value < 0 ? min1_digit : zero_digit;
for (std::size_t i = 1; i != num_digits; ++i) {
digits[i] = sign;
}
return *this;
}
constexpr explicit bigint(std::string_view str, int base = 10) noexcept : bigint()
{
std::size_t i = 0;
for (; i < str.size(); ++i) {
(*this) *= base;
(*this) += base16::int_from_char<int>(str[i]);
}
}
constexpr explicit operator unsigned long long() const noexcept
{
return static_cast<unsigned long long>(digits[0]);
}
constexpr explicit operator signed long long() const noexcept
{
return static_cast<signed long long>(digits[0]);
}
constexpr explicit operator unsigned long() const noexcept
{
return static_cast<unsigned long>(digits[0]);
}
constexpr explicit operator signed long() const noexcept
{
return static_cast<signed long>(digits[0]);
}
constexpr explicit operator unsigned int() const noexcept
{
return static_cast<unsigned int>(digits[0]);
}
constexpr explicit operator signed int() const noexcept
{
return static_cast<signed int>(digits[0]);
}
constexpr explicit operator unsigned short() const noexcept
{
return static_cast<unsigned short>(digits[0]);
}
constexpr explicit operator signed short() const noexcept
{
return static_cast<signed short>(digits[0]);
}
constexpr explicit operator unsigned char() const noexcept
{
return static_cast<unsigned char>(digits[0]);
}
constexpr explicit operator signed char() const noexcept
{
return static_cast<signed char>(digits[0]);
}
constexpr explicit operator bool() const noexcept
{
for (std::size_t i = 0; i != num_digits; ++i) {
if (digits[i] != 0) {
return true;
}
}
return false;
}
[[nodiscard]] constexpr bool is_negative() const noexcept
{
if constexpr (is_signed and num_digits > 0) {
return static_cast<signed_digit_type>(digits[num_digits - 1]) < 0;
} else {
return false;
}
}
template<std::size_t N, bool S>
constexpr explicit operator bigint<digit_type, N, S>() const noexcept
{
auto r = bigint<digit_type, N, S>{};
ttlet sign = is_negative() ? min1_digit : zero_digit;
for (auto i = 0; i != N; ++i) {
r.digits[i] = i < num_digits ? digits[i] : sign;
}
return r;
}
std::string string() const noexcept
{
constexpr auto oneOver10 = reciprocal(bigint<digit_type, num_digits * 2, is_signed>{10});
auto tmp = *this;
std::string r;
if (tmp == 0) {
r = "0";
} else {
while (tmp > 0) {
bigint remainder;
std::tie(tmp, remainder) = div(tmp, bigint{10}, oneOver10);
r += (static_cast<unsigned char>(remainder) + '0');
}
}
std::reverse(r.begin(), r.end());
return r;
}
std::string uuid_string() const noexcept
{
static_assert(
std::is_same_v<digit_type, uint64_t> && num_digits == 2,
"uuid_string should only be called on a uuid compatible type");
return std::format(
"{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
static_cast<uint32_t>(digits[1] >> 32),
static_cast<uint16_t>(digits[1] >> 16),
static_cast<uint16_t>(digits[1]),
static_cast<uint16_t>(digits[0] >> 48),
digits[0] & 0x0000ffff'ffffffffULL);
}
[[nodiscard]] constexpr bigint operator-() const noexcept
{
bigint r;
neg_carry_chain(r.digits, digits, num_digits);
return r;
}
constexpr bigint &operator<<=(std::size_t rhs) noexcept
{
sll_carry_chain(digits, digits, rhs, num_digits);
return *this;
}
constexpr bigint &operator>>=(std::size_t rhs) noexcept
{
if constexpr (is_signed) {
sra_carry_chain(digits, digits, rhs, num_digits);
} else {
srl_carry_chain(digits, digits, rhs, num_digits);
}
return *this;
}
constexpr bigint &operator*=(bigint const &rhs) noexcept
{
auto r = bigint{0};
mul_carry_chain(r.digits, digits, rhs.digits, num_digits);
*this = r;
return *this;
}
constexpr bigint &operator+=(bigint const &rhs) noexcept
{
add_carry_chain(digits, digits, rhs.digits, num_digits);
return *this;
}
constexpr bigint &operator-=(bigint const &rhs) noexcept
{
sub_carry_chain(digits, digits, rhs.digits, num_digits);
return *this;
}
constexpr bigint &operator&=(bigint const &rhs) noexcept
{
and_carry_chain(digits, digits, rhs.digits, num_digits);
return *this;
}
constexpr bigint &operator|=(bigint const &rhs) noexcept
{
or_carry_chain(digits, digits, rhs.digits, num_digits);
return *this;
}
constexpr bigint &operator^=(bigint const &rhs) noexcept
{
xor_carry_chain(digits, digits, rhs.digits, num_digits);
return *this;
}
static bigint from_big_endian(uint8_t const *data) noexcept
{
auto r = bigint{};
for (ssize_t i = static_cast<ssize_t>(num_digits) - 1; i >= 0; i--) {
digit_type d = 0;
for (std::size_t j = 0; j < sizeof(digit_type); j++) {
d <<= 8;
d |= *(data++);
}
r.digits[i] = d;
}
return r;
}
static bigint from_little_endian(uint8_t const *data) noexcept
{
auto r = bigint{};
for (int i = 0; i < num_digits; ++i) {
digit_type d = 0;
for (std::size_t j = 0; j < sizeof(digit_type); j++) {
d |= static_cast<digit_type>(*(data++)) << (j * 8);
}
r.digits[i] = d;
}
return r;
}
static bigint from_big_endian(void const *data) noexcept
{
return from_big_endian(static_cast<uint8_t const *>(data));
}
static bigint from_little_endian(void const *data) noexcept
{
return from_little_endian(static_cast<uint8_t const *>(data));
}
/*! Calculate the remainder of a CRC check.
* \param r Return value, the remainder.
* \param lhs The number to check.
* \param rhs Polynomial.
*/
[[nodiscard]] constexpr friend bigint crc(bigint const &lhs, bigint const &rhs) noexcept requires(not is_signed)
{
ttlet polynomialOrder = bsr_carry_chain(rhs.digits, rhs.num_digits);
tt_assert(polynomialOrder >= 0);
auto tmp = static_cast<bigint<digit_type, 2 * num_digits>>(lhs) << polynomialOrder;
auto rhs_ = static_cast<bigint<digit_type, 2 * num_digits>>(rhs);
auto tmp_highest_bit = bsr_carry_chain(tmp.digits, tmp.num_digits);
while (tmp_highest_bit >= polynomialOrder) {
ttlet divident = rhs_ << (tmp_highest_bit - polynomialOrder);
tmp ^= divident;
tmp_highest_bit = bsr_carry_chain(tmp.digits, tmp.num_digits);
}
return static_cast<bigint>(tmp);
}
/*! Calculate the reciprocal at a certain precision.
*
* N should be two times the size of the eventual numerator.
*
* \param divider The divider of 1.
* \return (1 << (K*sizeof(T)*8)) / divider
*/
[[nodiscard]] constexpr friend bigint reciprocal(bigint const &rhs)
{
auto r = bigint<digit_type, num_digits + 1, is_signed>(0);
r.digits[num_digits] = 1;
return static_cast<bigint>(r / rhs);
}
[[nodiscard]] constexpr friend bool operator==(bigint const &lhs, bigint const &rhs) noexcept
{
return eq_carry_chain(lhs.digits, rhs.digits, lhs.num_digits);
}
[[nodiscard]] constexpr friend std::strong_ordering operator<=>(bigint const &lhs, bigint const &rhs) noexcept
{
if constexpr (lhs.is_signed or rhs.is_signed) {
return cmp_signed_carry_chain(lhs.digits, rhs.digits, lhs.num_digits);
} else {
return cmp_unsigned_carry_chain(lhs.digits, rhs.digits, lhs.num_digits);
}
}
[[nodiscard]] constexpr friend bigint operator<<(bigint const &lhs, std::size_t rhs) noexcept
{
auto r = bigint{};
sll_carry_chain(r.digits, lhs.digits, rhs, lhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend bigint operator>>(bigint const &lhs, std::size_t rhs) noexcept
{
auto r = bigint{};
if constexpr (lhs.is_signed) {
sra_carry_chain(r.digits, lhs.digits, rhs, lhs.num_digits);
} else {
srl_carry_chain(r.digits, lhs.digits, rhs, lhs.num_digits);
}
return r;
}
[[nodiscard]] constexpr friend bigint operator*(bigint const &lhs, bigint const &rhs) noexcept
{
auto r = bigint{};
mul_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend bigint operator+(bigint const &lhs, bigint const &rhs) noexcept
{
auto r = bigint{};
add_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend bigint operator-(bigint const &lhs, bigint const &rhs) noexcept
{
auto r = bigint{};
sub_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend bigint operator~(bigint const &rhs) noexcept
{
auto r = bigint{};
invert_carry_chain(r.digits, rhs.digits, rhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend bigint operator|(bigint const &lhs, bigint const &rhs) noexcept
{
auto r = bigint{};
or_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend bigint operator&(bigint const &lhs, bigint const &rhs) noexcept
{
auto r = bigint{};
and_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend bigint operator^(bigint const &lhs, bigint const &rhs) noexcept
{
auto r = bigint{};
xor_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits);
return r;
}
[[nodiscard]] constexpr friend std::pair<bigint, bigint> div(bigint const &lhs, bigint const &rhs) noexcept
{
auto quotient = bigint{};
auto remainder = bigint{};
if constexpr (is_signed) {
signed_div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits);
} else {
div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits);
}
return std::pair{quotient, remainder};
}
[[nodiscard]] constexpr friend std::pair<bigint, bigint>
div(bigint const &lhs, bigint const &rhs, bigint<digit_type, 2 * num_digits, is_signed> const &rhs_reciprocal) noexcept
requires(not is_signed)
{
constexpr auto nr_bits = num_digits * bits_per_digit;
using bigint_x3_type = bigint<digit_type, 3 * num_digits, is_signed>;
auto quotient = bigint_x3_type{lhs} * bigint_x3_type{rhs_reciprocal};
quotient >>= (2 * nr_bits);
auto product = bigint_x3_type{quotient} * bigint_x3_type{rhs};
tt_axiom(product <= lhs);
auto remainder = lhs - product;
int retry = 0;
while (remainder >= rhs) {
if (retry++ > 3) {
return div(lhs, rhs);
}
remainder -= rhs;
quotient += 1;
}
return std::pair{static_cast<bigint>(quotient), static_cast<bigint>(remainder)};
}
[[nodiscard]] constexpr friend bigint operator/(bigint const &lhs, bigint const &rhs) noexcept
{
auto quotient = bigint{};
auto remainder = bigint{};
if constexpr (is_signed) {
signed_div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits);
} else {
div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits);
}
return quotient;
}
[[nodiscard]] constexpr friend bigint operator%(bigint const &lhs, bigint const &rhs) noexcept
{
auto quotient = bigint{};
auto remainder = bigint{};
if constexpr (is_signed) {
signed_div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits);
} else {
div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits);
}
return remainder;
}
friend std::ostream &operator<<(std::ostream &lhs, bigint const &rhs)
{
return lhs << rhs.string();
}
};
template<std::unsigned_integral T, std::size_t N>
struct is_numeric_unsigned_integral<bigint<T, N, false>> : std::true_type {
};
template<std::unsigned_integral T, std::size_t N>
struct is_numeric_signed_integral<bigint<T, N, true>> : std::true_type {
};
template<std::unsigned_integral T, std::size_t N, bool S>
struct is_numeric_integral<bigint<T, N, S>> : std::true_type {
};
using ubig128 = bigint<uint64_t, 2, false>;
using big128 = bigint<uint64_t, 2, true>;
using uuid = bigint<uint64_t, 2, false>;
} // namespace tt::inline v1
template<std::unsigned_integral DigitType, std::size_t NumDigits, bool IsSigned>
struct std::numeric_limits<tt::bigint<DigitType, NumDigits, IsSigned>> {
using value_type = tt::bigint<DigitType, NumDigits, IsSigned>;
static constexpr bool is_specialized = true;
static constexpr bool is_signed = IsSigned;
static constexpr bool is_integer = true;
static constexpr bool is_exact = true;
static constexpr bool has_infinity = false;
static constexpr bool has_quiet_NaN = false;
static constexpr bool has_signaling_NaN = false;
static constexpr float_denorm_style has_denorm = std::denorm_absent;
static constexpr bool has_denorm_loss = false;
static constexpr float_round_style round_style = std::round_toward_zero;
static constexpr bool is_iec559 = false;
static constexpr bool is_bounded = true;
static constexpr bool is_modulo = true;
static constexpr int digits = std::numeric_limits<DigitType>::digits * NumDigits;
static constexpr int digits10 = std::numeric_limits<DigitType>::digits10 * NumDigits;
static constexpr int max_digits10 = 0;
static constexpr int min_exponent = 0;
static constexpr int min_exponent10 = 0;
static constexpr int max_exponent = 0;
static constexpr int max_exponent10 = 0;
static constexpr bool traps = std::numeric_limits<DigitType>::traps;
static constexpr bool tinyness_before = false;
static constexpr value_type min() noexcept
{
auto r = value_type{};
constexpr auto smin = std::numeric_limits<value_type::signed_digit_type>::min();
constexpr auto umin = std::numeric_limits<value_type::digit_type>::min();
for (std::size_t i = 0; i != value_type::num_digits; ++i) {
r.digits[i] = umin;
}
if constexpr (value_type::is_signed and value_type::num_digits > 0) {
r.digits[value_type::num_digits - 1] = static_cast<value_type::digit_type>(smin);
}
return r;
}
static constexpr value_type lowest() noexcept
{
return min();
}
static constexpr value_type max() noexcept
{
auto r = value_type{};
constexpr auto smax = std::numeric_limits<value_type::signed_digit_type>::max();
constexpr auto umax = std::numeric_limits<value_type::digit_type>::max();
for (std::size_t i = 0; i != value_type::num_digits; ++i) {
r.digits[i] = umax;
}
if constexpr (value_type::is_signed and value_type::num_digits > 0) {
r.digits[value_type::num_digits - 1] = smax;
}
return r;
}
static constexpr value_type epsilon() noexcept
{
return value_type{0};
}
static constexpr value_type round_error() noexcept
{
return value_type{0};
}
static constexpr value_type infinity() noexcept
{
return value_type{0};
}
static constexpr value_type quiet_NaN() noexcept
{
return value_type{0};
}
static constexpr value_type signaling_NaN() noexcept
{
return value_type{0};
}
static constexpr value_type denorm_min() noexcept
{
return value_type{0};
}
};
| 31.871166
| 123
| 0.612079
|
RustWorks
|
b717465d9f435083c6e894c1a5652c02087b0bef
| 588
|
cpp
|
C++
|
tests/lexy/dsl/return.cpp
|
gkgoat1/lexy
|
9c600fa906e81efbb3e34b8951ebc56809f2a0df
|
[
"BSL-1.0"
] | null | null | null |
tests/lexy/dsl/return.cpp
|
gkgoat1/lexy
|
9c600fa906e81efbb3e34b8951ebc56809f2a0df
|
[
"BSL-1.0"
] | null | null | null |
tests/lexy/dsl/return.cpp
|
gkgoat1/lexy
|
9c600fa906e81efbb3e34b8951ebc56809f2a0df
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (C) 2020-2022 Jonathan Müller and lexy contributors
// SPDX-License-Identifier: BSL-1.0
#include <lexy/dsl/return.hpp>
#include "verify.hpp"
TEST_CASE("dsl::return_")
{
constexpr auto rule = dsl::return_ + LEXY_LIT("abc");
CHECK(lexy::is_rule<decltype(dsl::return_)>);
constexpr auto callback = token_callback;
auto empty = LEXY_VERIFY("");
CHECK(empty.status == test_result::success);
CHECK(empty.trace == test_trace());
auto abc = LEXY_VERIFY("abc");
CHECK(abc.status == test_result::success);
CHECK(abc.trace == test_trace());
}
| 24.5
| 64
| 0.67517
|
gkgoat1
|
b71ab820ce1d29a86af167f60c7b75ec80756a5c
| 7,825
|
cpp
|
C++
|
src/server/main.cpp
|
Kuga23/Projet-M2
|
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
|
[
"MIT"
] | null | null | null |
src/server/main.cpp
|
Kuga23/Projet-M2
|
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
|
[
"MIT"
] | null | null | null |
src/server/main.cpp
|
Kuga23/Projet-M2
|
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h> // Pour compter une minute d'enregistrement
#include <fstream> // Pour la gestion des fichiers
#include <sstream>
#include <map>
#include <memory>
#include <microhttpd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/select.h>
#include "state.h"
#include "engine.h"
#include "ai.h"
#include "server.h"
using namespace std;
using namespace state;
using namespace engine;
using namespace ai;
using namespace server;
class Request
{
public:
struct MHD_PostProcessor *pp = nullptr;
string data;
~Request()
{
if (pp)
MHD_destroy_post_processor(pp);
}
};
static int post_iterator(void *cls,
enum MHD_ValueKind kind,
const char *key,
const char *filename,
const char *content_type,
const char *transfer_encoding,
const char *data, uint64_t off, size_t size)
{
return MHD_NO;
}
static int handler(void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method,
const char *version,
const char *upload_data, size_t *upload_data_size, void **ptr)
{
Request *request = (Request *)*ptr;
if (!request)
{
request = new Request();
if (!request)
{
return MHD_NO;
}
*ptr = request;
if (strcmp(method, MHD_HTTP_METHOD_POST) == 0 || strcmp(method, MHD_HTTP_METHOD_PUT) == 0)
{
request->pp = MHD_create_post_processor(connection, 1024, &post_iterator, request);
if (!request->pp)
{
cerr << "Failed to setup post processor for " << url << endl;
return MHD_NO;
}
}
return MHD_YES;
}
if (strcmp(method, MHD_HTTP_METHOD_POST) == 0 || strcmp(method, MHD_HTTP_METHOD_PUT) == 0)
{
MHD_post_process(request->pp, upload_data, *upload_data_size);
if (*upload_data_size != 0)
{
request->data = upload_data;
*upload_data_size = 0;
return MHD_YES;
}
}
HttpStatus status;
string response;
try
{
ServicesManager *manager = (ServicesManager *)cls;
status = manager->queryService(response, request->data, url, method);
}
catch (ServiceException &e)
{
status = e.getStatus();
response += "\n";
}
catch (exception &e)
{
status = HttpStatus::SERVER_ERROR;
response = e.what();
response += "\n";
}
catch (...)
{
status = HttpStatus::SERVER_ERROR;
response = "Unknown exception\n";
}
struct MHD_Response *mhd_response;
mhd_response = MHD_create_response_from_buffer(response.size(), (void *)response.c_str(), MHD_RESPMEM_MUST_COPY);
if (strcmp(method, MHD_HTTP_METHOD_GET) == 0)
{
MHD_add_response_header(mhd_response, "Content-Type", "application/json; charset=utf-8");
}
int ret = MHD_queue_response(connection, status, mhd_response);
MHD_destroy_response(mhd_response);
return ret;
}
static void request_completed(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe)
{
Request *request = (Request *)*con_cls;
if (request)
{
delete request;
*con_cls = nullptr;
}
}
int main(int argc, char const *argv[])
{
if (argc > 1){
// Test pour un Hello
if (strcmp(argv[1], "Hello") == 0)
cout << "Bonjour " << endl;
else if (strcmp(argv[1], "record") == 0){
std::string commands_file = "res/record/replay.txt";
engine::Engine myEngine;
myEngine.setEnableRecord(true);
myEngine.getState().initPlayers();
myEngine.getState().initCharacters();
myEngine.getState().initMapCell();
ai::HeuristicAI AI_1(myEngine, 1);
ai::HeuristicAI AI_2(myEngine, 2);
cout << "<<< Record >>>" << endl;
cout << "HAi vs HAI" << commands_file << endl;
sleep(2);
cout << "<<< Début de l'enregistrement >>>" << endl;
// On joue une minute de jeu
clock_t time;
while (time=clock()/CLOCKS_PER_SEC <=60){
// joueur1
if(myEngine.getState().getEndGame())
break;
if (myEngine.getState().getRound() % 2 != 0)
{
AI_1.run(myEngine);
}
// joueur2
else
{
AI_2.run(myEngine);
}
}
cout << "<<< Fin de l'enregistrement >>>" << endl;
cout << "<<< ###############################################################" << endl;
cout << " ENREGISTREMENT DANS LE FICHIER REPLAY.TXT "<<endl;
cout << "<<< ###############################################################" << endl;
// Ouverture du fichier en ecriture en effacant son contenu à l'ouverture
std::ofstream written_file(commands_file, ios::out | ios::trunc);
if (written_file){
Json::Value record = myEngine.getRecord();
cout << record << endl;
// Ecriture dans le fichier du tableau de commandes de cette partie
written_file << record;
// Fermeture du fichier
written_file.close();
}
else{
cerr << "Impossible d'ouvrir le fichier pour l'ecriture" << endl;
}
}
else if (strcmp(argv[1], "listen") == 0){
try
{
VersionService versionService;
std::unique_ptr<AbstractService> ptr_versionService(new VersionService(versionService));
ServicesManager servicesManager;
servicesManager.registerService(move(ptr_versionService));
Game game;
PlayerService playerService(std::ref(game));
std::unique_ptr<AbstractService> ptr_playerService(new PlayerService(playerService));
servicesManager.registerService(move(ptr_playerService));
struct MHD_Daemon *d;
if (argc != 2)
{
printf("%s PORT\n", argv[0]);
return 1;
}
int port_id = 80;
d = MHD_start_daemon( // MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | MHD_USE_POLL,
MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
// MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG | MHD_USE_POLL,
// MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
port_id,
NULL, NULL,
&handler, (void *)&servicesManager,
MHD_OPTION_NOTIFY_COMPLETED, request_completed, NULL,
MHD_OPTION_END);
if (d == NULL)
return 1;
cout << "server is listening in port " << port_id << endl << "press any button to stop the server" << endl;
(void)getc(stdin);
MHD_stop_daemon(d);
}
catch (exception &e)
{
cerr << "Exception: " << e.what() << endl;
}
}
}
}
| 30.212355
| 128
| 0.511182
|
Kuga23
|
b71b00f47e7de6b078f53209e6a9019f96dc56e1
| 1,845
|
cpp
|
C++
|
第九周/Insertion or Heap Sort/Insertion or Heap Sort.cpp
|
Daipuwei/-MOOC-
|
e6589e4b62f86c50fb34f2b395230c8dd49cf3d1
|
[
"MIT"
] | 11
|
2019-11-12T09:22:03.000Z
|
2021-01-24T02:26:10.000Z
|
第九周/Insertion or Heap Sort/Insertion or Heap Sort.cpp
|
Daipuwei/-MOOC-
|
e6589e4b62f86c50fb34f2b395230c8dd49cf3d1
|
[
"MIT"
] | null | null | null |
第九周/Insertion or Heap Sort/Insertion or Heap Sort.cpp
|
Daipuwei/-MOOC-
|
e6589e4b62f86c50fb34f2b395230c8dd49cf3d1
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
bool Check(int a[],int b[],int N)
{
bool flag = true;
for ( int i = 0 ; i < N ; i++){
if ( a[i] != b[i]){
flag = false;
break;
}
}
return flag;
}
void Print(int a[],int N)
{
cout<<a[0];
for (int i = 1 ; i < N ; i++){
cout<<" "<<a[i];
}
}
bool Insert_Sort(int a[],int b[],int N)
{
bool isInsert = false;
for ( int i = 1 ; i < N ; i++){
int tmp = a[i];
int j;
for (j = i ; j > 0 && a[j-1] > tmp ; j--){
a[j] = a[j-1];
}
a[j] = tmp;
if (isInsert){
cout<<"Insertion Sort"<<endl;
Print(a,N);
break;
}else if(Check(a,b,N)){
isInsert = true;
}
}
return isInsert;
}
void PreDown(int a[],int p,int N)
{
int parent,child;
int x = a[p];
for ( parent = p ; (parent * 2 + 1) < N ; parent = child){
child = parent * 2 + 1;
if ( (child != N -1) && ( a[child] < a[child+1])){
child++;
}
if ( x >= a[child]){
break;
}else{
a[parent] = a[child];
}
}
a[parent] = x;
}
void swap(int* a ,int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
bool Heap_Sort(int a[],int b[],int N)
{
bool isHeap = false;
for ( int i = N/2-1 ; i >= 0 ; i--){
PreDown(a,i,N);
}
for ( int i = N-1 ; i > 0 ; i--){
swap(&a[0],&a[i]);
PreDown(a,0,i);
if (isHeap){
cout<<"Heap Sort"<<endl;
Print(a,N);
break;
}else if(Check(a,b,N)){
isHeap = true;
}
}
}
int main()
{
int len;
cin>>len;
int *A,*B,*C;
A = new int[len];
B = new int[len];
C = new int[len];
for ( int i = 0 ; i < len ; i++){
cin>>A[i];
C[i] = A[i];
}
for ( int i = 0 ; i < len ; i++){
cin>>B[i];
}
bool isHeap = Heap_Sort(A,B,len);
if ( isHeap){
return 0;
}else{
bool isInsert = Insert_Sort(C,B,len);
return 0;
}
return 0;
}
| 16.043478
| 60
| 0.452033
|
Daipuwei
|
b71c41bf6a917a0818128e07e9d8a7969c309bb0
| 2,489
|
cpp
|
C++
|
QtOrm/Registry.cpp
|
rensfo/QtOrm
|
46a16ee507cff4b1367b674420365137bf20aa9f
|
[
"MIT"
] | null | null | null |
QtOrm/Registry.cpp
|
rensfo/QtOrm
|
46a16ee507cff4b1367b674420365137bf20aa9f
|
[
"MIT"
] | 1
|
2016-11-04T14:26:58.000Z
|
2016-11-04T14:27:57.000Z
|
QtOrm/Registry.cpp
|
rensfo/QtOrm
|
46a16ee507cff4b1367b674420365137bf20aa9f
|
[
"MIT"
] | null | null | null |
#include "Registry.h"
#include <QMetaObject>
#include "Mappings/ConfigurationMap.h"
#include "Mappings/SubClassMap.h"
namespace QtOrm {
Registry::Registry(QObject *parent) : QObject(parent) {
}
bool Registry::contains(const QString &table, const IdType &id) {
if (data.contains(table)) {
return data.value(table).contains(id);
}
return false;
}
void Registry::insert(const QString &table, const IdType &id, ItemType object) {
if (data.contains(table)) {
if (!data.value(table).contains(id)) {
data[table].insert(id, object);
itemsIds.insert(object, id);
}
} else {
RegistryData ids;
ids.insert(id, object);
data.insert(table, ids);
itemsIds.insert(object, id);
}
}
void Registry::remove(const QString &table, const IdType &id) {
if (contains(table, id)) {
auto object = value(table, id);
itemsIds.remove(object);
data[table].remove(id);
}
}
void Registry::remove(ItemType object) {
for (RegistryData &ids : data) {
for (QSharedPointer<QObject> ®istryObject : ids) {
if (registryObject == object) {
IdType key = ids.key(object);
ids.remove(key);
itemsIds.remove(object);
return;
}
}
}
}
Registry::ItemType Registry::value(const QString &table, const IdType &id) {
if (contains(table, id)) {
return data[table][id];
}
return ItemType();
}
Registry::ItemType Registry::value(QObject *object) {
QString className = object->metaObject()->className();
QString tableName;
auto classBase = configuration->getMappedClass(className);
if(Mapping::SubClassMap::isClassTableInheritance(classBase)){
classBase = classBase->toSubclass()->getBaseClass();
}
tableName = classBase->getTable();
if (data.contains(tableName)) {
for (QSharedPointer<QObject> ®istryObject : data[tableName]) {
if (registryObject.data() == object) {
return registryObject;
}
}
}
return QSharedPointer<QObject>();
}
bool Registry::contains(Registry::ItemType object) {
return itemsIds.contains(object);
}
Registry::IdType Registry::getId(ItemType object) {
return itemsIds.value(object);
}
void Registry::clear() {
data.clear();
}
QSharedPointer<Config::ConfigurationMap> Registry::getConfiguration() const
{
return configuration;
}
void Registry::setConfiguration(QSharedPointer<Config::ConfigurationMap> value)
{
configuration = value;
}
}
uint qHash(const QVariant&var)
{
return qHash(var.toString());
}
| 22.223214
| 80
| 0.677782
|
rensfo
|
b71ec959e3b67a00b0ad45464015ab0bec1d1615
| 1,543
|
cc
|
C++
|
2021/PTA/Pratice 1/M.cc
|
slowbear/TrainingCode
|
688872b9dab784a410069b787457f8c0871648aa
|
[
"CC0-1.0"
] | null | null | null |
2021/PTA/Pratice 1/M.cc
|
slowbear/TrainingCode
|
688872b9dab784a410069b787457f8c0871648aa
|
[
"CC0-1.0"
] | null | null | null |
2021/PTA/Pratice 1/M.cc
|
slowbear/TrainingCode
|
688872b9dab784a410069b787457f8c0871648aa
|
[
"CC0-1.0"
] | null | null | null |
#include <bits/extc++.h>
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using Pii = pair<int, int>;
using Pll = pair<LL, LL>;
using VI = vector<int>;
using VP = vector<pair<int, int>>;
#define rep(i, a, b) for (auto i = (a); i < (b); ++i)
#define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i)
#define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i])
#define mem(x, v) memset(x, v, sizeof(x))
#define cpy(x, y) memcpy(x, y, sizeof(x))
#define SZ(V) static_cast<int>(V.size())
#define pb push_back
#define mp make_pair
constexpr int maxn = 1010;
int lc[maxn], rc[maxn], fa[maxn], val[maxn], total;
int insert(int rt, int key) {
if (!rt) {
lc[total] = rc[total] = fa[total] = 0;
val[total] = key;
return total++;
}
if (key > val[rt]) {
lc[rt] = insert(lc[rt], key);
fa[lc[rt]] = rt;
} else {
rc[rt] = insert(rc[rt], key);
fa[rc[rt]] = rt;
}
return rt;
}
int tag[maxn], cnt;
int main() {
int n, rt = 0;
total = 1;
scanf("%d", &n);
rep(i, 0, n) {
int x;
scanf("%d", &x);
rt = insert(rt, x);
}
bool flag = true, first_print = true;
queue<int> que;
que.push(rt);
cnt = 1;
while (!que.empty()) {
int u = que.front();
que.pop();
tag[u] = cnt++;
if (tag[fa[u]] != tag[u] / 2) flag = false;
if (!lc[u] && rc[u]) flag = false;
if (!first_print) putchar(' ');
printf("%d", val[u]);
first_print = false;
if (lc[u]) que.push(lc[u]);
if (rc[u]) que.push(rc[u]);
}
printf("\n");
puts(flag ? "YES" : "NO");
}
| 22.691176
| 59
| 0.528192
|
slowbear
|
b71edd52079289ee9815d3e9422ff530e4ebfe59
| 2,050
|
cpp
|
C++
|
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
|
hyperventilation/Fedoraware
|
4cd6bea1711a31a797adf855f6ee979138558d3c
|
[
"WTFPL"
] | 28
|
2022-02-02T04:36:09.000Z
|
2022-03-31T19:05:10.000Z
|
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
|
hyperventilation/Fedoraware
|
4cd6bea1711a31a797adf855f6ee979138558d3c
|
[
"WTFPL"
] | 103
|
2022-02-03T11:52:24.000Z
|
2022-03-31T18:33:55.000Z
|
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
|
hyperventilation/Fedoraware
|
4cd6bea1711a31a797adf855f6ee979138558d3c
|
[
"WTFPL"
] | 39
|
2022-02-02T23:34:15.000Z
|
2022-03-27T21:36:05.000Z
|
#include "Aimbot.h"
#include "../Vars.h"
#include "AimbotHitscan/AimbotHitscan.h"
#include "AimbotProjectile/AimbotProjectile.h"
#include "AimbotMelee/AimbotMelee.h"
bool CAimbot::ShouldRun(CBaseEntity* pLocal, CBaseCombatWeapon* pWeapon)
{
if (G::FreecamActive)
return false;
if (!Vars::Aimbot::Global::Active.Value)
return false;
if (I::EngineVGui->IsGameUIVisible() || I::Surface->IsCursorVisible())
return false;
if (!pLocal->IsAlive()
|| pLocal->IsTaunting()
|| pLocal->IsBonked()
|| pLocal->GetFeignDeathReady()
|| pLocal->IsCloaked()
|| pLocal->IsInBumperKart()
|| pLocal->IsAGhost())
return false;
switch (G::CurItemDefIndex)
{
case Soldier_m_RocketJumper:
case Demoman_s_StickyJumper: return false;
default: break;
}
switch (pWeapon->GetWeaponID())
{
case TF_WEAPON_PDA:
case TF_WEAPON_PDA_ENGINEER_BUILD:
case TF_WEAPON_PDA_ENGINEER_DESTROY:
case TF_WEAPON_PDA_SPY:
case TF_WEAPON_PDA_SPY_BUILD:
case TF_WEAPON_BUILDER:
case TF_WEAPON_INVIS:
case TF_WEAPON_BUFF_ITEM:
case TF_WEAPON_GRAPPLINGHOOK:
{
return false;
}
default: break;
}
return true;
}
void CAimbot::Run(CUserCmd* pCmd)
{
G::CurrentTargetIdx = 0;
G::CurAimFOV = 0.0f;
G::PredictedPos = Vec3();
G::HitscanRunning = false;
G::HitscanSilentActive = false;
G::ProjectileSilentActive = false;
G::AimPos = Vec3();
auto pLocal = I::EntityList->GetClientEntity(I::Engine->GetLocalPlayer());
if (pLocal)
{
auto pWeapon = pLocal->GetActiveWeapon();
if (!pWeapon)
{
return;
}
if (!ShouldRun(pLocal, pWeapon))
return;
SandvichAimbot::IsSandvich();
if (SandvichAimbot::bIsSandvich) {
G::CurWeaponType = EWeaponType::HITSCAN;
}
switch (G::CurWeaponType)
{
case EWeaponType::HITSCAN:
{
F::AimbotHitscan.Run(pLocal, pWeapon, pCmd);
break;
}
case EWeaponType::PROJECTILE:
{
F::AimbotProjectile.Run(pLocal, pWeapon, pCmd);
break;
}
case EWeaponType::MELEE:
{
F::AimbotMelee.Run(pLocal, pWeapon, pCmd);
break;
}
default: break;
}
}
}
| 18.807339
| 75
| 0.694634
|
hyperventilation
|
b71ef886c7bf06ebcb1cc3b42866438a517da7e4
| 4,382
|
cpp
|
C++
|
code archive/TIOJ/1840.cpp
|
brianbbsu/program
|
c4505f2b8c0b91010e157db914a63c49638516bc
|
[
"MIT"
] | 4
|
2018-04-08T08:07:58.000Z
|
2021-06-07T14:55:24.000Z
|
code archive/TIOJ/1840.cpp
|
brianbbsu/program
|
c4505f2b8c0b91010e157db914a63c49638516bc
|
[
"MIT"
] | null | null | null |
code archive/TIOJ/1840.cpp
|
brianbbsu/program
|
c4505f2b8c0b91010e157db914a63c49638516bc
|
[
"MIT"
] | 1
|
2018-10-29T12:37:25.000Z
|
2018-10-29T12:37:25.000Z
|
//{
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#endif // brian
//}
const ll MAXn=7e4+5,MAXlg=__lg(10*MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e15);
struct chtag{
ll t,p,x,type;
chtag(ll ti,ll pi,ll xi,ll tpi):t(ti),p(pi),x(xi),type(tpi){}
};
struct qrtag{
ll t,l,r,k;
qrtag(ll ti,ll li,ll ri,ll ki):t(ti),l(li),r(ri),k(ki){}
};
ll aryd[10*MAXn];
vector<chtag> ch[MAXlg],tmpch;
vector<qrtag> qr[MAXlg],tmpqr;
stack<chtag> st;
ll n,q;
ll it=-1;
ll ans[10*MAXn];
vector<ll> uni;
//bit
ll bit[MAXn*10];
void ins(ll x,ll k){
while(x<=n)bit[x]+=k,x+=x&-x;
}
ll precnt(ll x){
ll r=0;while(x>0)r+=bit[x],x-=x&-x;return r;
}
void DC(ll now,ll l,ll r)
{
assert(now<MAXlg);
debug(now,l,r);
if(l==r-1)
{
for(auto &k:qr[now])ans[k.t]=uni[r];
return;
}
tmpqr.clear();
tmpch.clear();
ch[now+1].clear();
qr[now+1].clear();
ll chit=0;
ll h=(l+r)/2;
assert(h>=0);
for(auto &k:qr[now])
{
while(chit<SZ(ch[now])&&ch[now][chit].t<k.t)
{
if(ch[now][chit].x<=h)
{
auto &chn=ch[now][chit];
st.push(chn);
ins(chn.p,chn.type);
}
chit++;
}
ll tmps=precnt(k.r)-precnt(k.l-1);
if(tmps>=k.k)
{
qr[now+1].pb(k);
}
else
{
k.k-=tmps;
tmpqr.pb(k);
}
}
while(SZ(st))
{
ins(st.top().p,st.top().type*-1);
st.pop();
}
for(auto &k:ch[now])
{
if(k.x<=h)ch[now+1].pb(k);
else tmpch.pb(k);
}
ch[now].swap(tmpch);
qr[now].swap(tmpqr);
DC(now+1,l,h);
ch[now+1].swap(ch[now]);
qr[now+1].swap(qr[now]);
DC(now+1,h,r);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
debug(MAXlg);
ll T;
cin>>T;
while(T--&&cin>>n>>q)
{
it=-1;
REP(i,MAXlg)ch[i].clear(),qr[i].clear();
uni.clear();
FILL(bit,0);
while(SZ(st))st.pop();
REP(i,n)cin>>aryd[i+1],uni.pb(aryd[i+1]),ch[0].pb(chtag(-1,i+1,aryd[i+1],1));
//input
REP(i,q)
{
ll t;
cin>>t;
if(t==1)
{
ll l,r,k;
cin>>l>>r>>k;
it++;
qr[0].pb(qrtag(it,l,r,k));
}
else if(t==2)
{
ll x,k;
cin>>x>>k;
ch[0].pb(chtag(it,x,k,1));
ch[0].pb(chtag(it,x,aryd[x],-1));
aryd[x]=k;
uni.pb(k);
}
else
{
ll x;
cin>>x>>x;
it++;
ans[it]=7122;
}
}
sort(ALL(uni));
uni.resize(unique(ALL(uni))-uni.begin());
assert(SZ(uni)<MAXn*10);
for(auto &k:ch[0])k.x=lower_bound(ALL(uni),k.x)-uni.begin();
DC(0,-1,SZ(uni)-1);
REP(i,it+1)cout<<ans[i]<<endl;
}
}
| 23.185185
| 129
| 0.482656
|
brianbbsu
|
b7253a6f511f2a7e69a54f27bcf6a2dc20c5d63d
| 11,489
|
hpp
|
C++
|
Controller/CPU-related/AMD/beginningWithFam10h/voltage.hpp
|
st-gb/CPUinfoAndControl
|
5e93d4a195b4692d147bb05cfef534e38d7f8b64
|
[
"MIT"
] | null | null | null |
Controller/CPU-related/AMD/beginningWithFam10h/voltage.hpp
|
st-gb/CPUinfoAndControl
|
5e93d4a195b4692d147bb05cfef534e38d7f8b64
|
[
"MIT"
] | null | null | null |
Controller/CPU-related/AMD/beginningWithFam10h/voltage.hpp
|
st-gb/CPUinfoAndControl
|
5e93d4a195b4692d147bb05cfef534e38d7f8b64
|
[
"MIT"
] | 1
|
2021-07-16T21:01:26.000Z
|
2021-07-16T21:01:26.000Z
|
/*
* from_K10.h
*
* Created on: Aug 28, 2013
* Author: Stefan
*/
#ifndef FROM_K10_VOLTAGE_H_
#define FROM_K10_VOLTAGE_H_
#include <hardware/CPU/fastest_data_type.h> //typedef fastestUnsignedDataType
#include <preprocessor_macros/bitmasks.h>
#include <stdint.h> // uint32_t
//ReadMSR(...)
#include <Controller/AssignPointersToExportedExeFunctions/inline_register_access_functions.hpp>
//CPU_TEMPERATURE_DEVICE_AND_FUNCTION_NUMBER, ...
#include "../configuration_space_addresses.h"
extern ReadPCIconfigSpace_func_type g_pfnReadPCIconfigSpace;
/** Use prefix "COFVID_STATUS_MSR" to be eindeutig (because there may
* also be a field with the same meaning in e.g. another register, but at
* another start address) */
/** "48:42 [...]: minimum voltage. Read-only. Specifies the VID code
* corresponding to the minimum voltage (highest VID code) that the processor
* drives. 00h indicates that no minimum VID code is specified.
* See section 2.4.1 [Processor Power Planes And Voltage Control]." */
#define COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID 42
#define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID \
COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID
#define COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID_IN_EDX \
(COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID - 32)
#define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID_IN_EDX \
COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID_IN_EDX
#define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VOLTAGE_VID 35
#define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VOLTAGE_VID_IN_EDX \
COFVID_STATUS_REGISTER_START_BIT_FOR_MAX_VOLTAGE_VID - 32
/** "MSRC001_0071 COFVID Status" : "41:35 MaxVid: maximum voltage."
* "VID code corresponding to the maximum voltage" */
#define COFVID_STATUS_REGISTER_START_BIT_FOR_MIN_VID \
COFVID_STATUS_MSR_START_BIT_FOR_MAX_VOLTAGE_VID
//"MSRC001_0070 COFVID Control Register"
#define COFVID_CONTROL_REGISTER_MSR_ADDRESS 0xC0010070
/** see "31116 Rev 3.00 - September 07, 2007 AMD Family 10h Processor BKDG"
* "MSRC001_0071 COFVID Status Register" */
#define COFVID_STATUS_REGISTER_MSR_ADDRESS 0xC0010071
extern float g_fMaxMultiplier;
namespace AMD
{
/** function for AMD CPUs beginning with K10 (including 15hex. */
namespace fromK10
{
/** Applies to AMD family 10h,11h */
inline float GetVoltageInVolt(const fastestUnsignedDataType voltageID)
{
/** BIOS and Kernel Developer’s Guide (BKDG)
For AMD Family 10h Processors 31116 Rev 3.62 - January 11, 2013
MSRC001_0071CO COFVID Status Register
* 2.4.1.6.3 Serial VID (SVI) Encodings: 1.550V - 0.0125V * SviVid[6:0];
/** BIOS and Kernel Developer’s Guide (BKDG)
For AMD Family 10h Processors 31116 Rev 3.62 - January 11, 2013
MSRC001_0071CO COFVID Status Register
* 15:9 CurCpuVid: current core VID. Read-only. In dual-node processors,
CurCpuVid on internal node 0 is the voltage driven to VDD.
CurCpuVid on internal node 1 is the voltage of the higest performance
* P-state (lowest numbered P-state) requested by all cores on internal
* node 1. CurCpuVid on internal node 1 is greater than or equal to
* CurCpuVid on internal node 0. */
/** For AMD Turion X2 Ultra (family 11h) :
* VID 28 = 1.2 = 1.55 - 28 * 0.0125 ;
VID 64 = 0.75 = 1.55 - 64 * 0.0125
=> 1.55 - voltageID * 0.0125 */
/** 41256 Rev 3.00 - July 07, 2008 AMD Family 11h Processor BKDG
* chapter "2.4.1.2 Serial VID Interface" :
* "The processor includes an interface, intended to control external
* voltage regulators, called the serial VID inter-face (SVI)."
*
* see "31116 Rev 3.00 - September 07, 2007 AMD Family 10h Processor BKDG"
* chapter "2.4.1.6.3 Serial VID (SVI) Encodings"
*
* see Intersil "ISL6265 FN6599.0 Data Sheet May 7, 2008",
* "TABLE 3. SERIAL VID CODES"
*
* For family 15h CPU:
inbetween VID "148" is shown when under load and on highest multiplier
* VID 11 corresponds to 1.428 V? in CPU-Z 1.55 - 11 * 0.0125 = 1,4125
* VID 14 corresponds to 1.296/ 1.284 V in CPU-Z
* VID 47 corresponds to 1.008 V shown in CPU-Z 1.55 - 47×0,0125=0,9625
*
* 1.296V-1.008V=0,288V 47-14=33
* 1.428V- 1.008V=0,42V */
return 1.55f - voltageID*0.0125f;
}
inline fastestUnsignedDataType GetMaximumVoltageID()
{
// return 64 ;
uint32_t dwEAXlowMostBits, dwEDXhighMostBits ;
ReadMSR(
COFVID_STATUS_REGISTER_MSR_ADDRESS,
& dwEAXlowMostBits,
& dwEDXhighMostBits,
1 ) ;
fastestUnsignedDataType highestVID = ( dwEDXhighMostBits >>
( COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID - 32 )
) & BITMASK_FOR_LOWMOST_7BIT;
DEBUGN("highest VID:" << highestVID)
return highestVID ;
}
inline fastestUnsignedDataType GetMinimumVoltageID()
{
// return 36 ;
uint32_t dwEAXlowMostBits, dwEDXhighMostBits ;
ReadMSR(
COFVID_STATUS_REGISTER_MSR_ADDRESS,
& dwEAXlowMostBits,
& dwEDXhighMostBits,
1
) ;
const fastestUnsignedDataType lowestVID = ( dwEDXhighMostBits >>
( COFVID_STATUS_REGISTER_START_BIT_FOR_MIN_VID - 32 )
) & BITMASK_FOR_LOWMOST_7BIT;
DEBUGN("lowest VID:" << lowestVID)
return lowestVID ;
}
/** Applies to AMD family 10h, 11h, 15h */
inline void GetMinAndMaxVoltageID(
fastestUnsignedDataType & voltageIDforLowestVoltage,
fastestUnsignedDataType & voltageIDforHighestVoltage)
{
static uint32_t lowmost32bit, highmost32bit;
ReadMSR(
COFVID_STATUS_REGISTER_MSR_ADDRESS,
& lowmost32bit,
& highmost32bit,
1 ) ;
/** -"42301 Rev 3.14 - January 23, 2013 BKDG for AMD Family 15h Models"
* 00h-0Fh Processors",
* -"31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG"
* -"41256 Rev 3.00 - July 07, 2008 AMD Family 11h Processor BKDG":
* "MSRC001_0071 COFVID Status:"
* "48:42 MinVid: minimum voltage." "41:35 MaxVid: maximum voltage." */
voltageIDforLowestVoltage = ( highmost32bit >>
( COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID_IN_EDX )
) & BITMASK_FOR_LOWMOST_7BIT;
/** -31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG :
* "MSRC001_0071 COFVID Status Register",
* "48:42 MinVid: minimum voltage" :
* "00h indicates that no minimum VID code is specified." */
if( voltageIDforLowestVoltage == 0 )
voltageIDforLowestVoltage = 0b1010100;
//Table 8: SVI and internal VID codes: 101_0100b 0.5000 V
DEBUGN("voltage ID for minimum voltage::" << voltageIDforLowestVoltage )
voltageIDforHighestVoltage = ( highmost32bit >>
/** -31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG :
* "MSRC001_0071 COFVID Status Register",
* "41:35 MaxVid: maximum voltages. Read-only. Specifies the VID code" :
* "00h indicates that no maximum VID code is specified." */
/** 41256 Rev 3.00 - July 07, 2008 AMD Family 11h Processor BKDG :
* MSRC001_0071 COFVID Status Register :
* "41:35 [...]: maximum voltage. Read-only. Specifies the VID code
* corresponding to the maximum voltage (lowest VID code) that the processor
* drives. 00h indicates that no maximum VID code is specified.
* See section 2.4.1 [Processor Power Planes And Voltage Control].*/
( COFVID_STATUS_REGISTER_START_BIT_FOR_MIN_VID - 32 )
) & BITMASK_FOR_LOWMOST_7BIT;
DEBUGN("lowest VID:" << voltageIDforHighestVoltage )
}
inline void GetCurrentVoltageIDfromCOFVIDstatusRegisterBits(
const DWORD dwMSRlowmost,
BYTE & byVoltageID)
{
/** 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG
* "15:9 CurCpuVid: current core VID. Read-only." */
byVoltageID = //(BYTE) (
// (g_dwLowmostBits & BITMASK_FOR_CPU_CORE_VOLTAGE_ID//=1111111000000000bin
// ) >> 9 ) ; //<=>bits 9-15 shifted }
( dwMSRlowmost >> 9 ) & BITMASK_FOR_LOWMOST_7BIT ;
}
/** works for family 15 model 0-F, but not for family 15 model F-1F?! */
inline fastestUnsignedDataType GetCurrentVoltageIDfromCOFVIDstatusRegisterBits(
const DWORD dwMSRlowmost)
{
/** 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG
* "15:9 CurCpuVid: current core VID. Read-only." */
return //(BYTE) (
// (g_dwLowmostBits & BITMASK_FOR_CPU_CORE_VOLTAGE_ID//=1111111000000000bin
// ) >> 9 ) ; //<=>bits 9-15 shifted }
( dwMSRlowmost >> 9 ) & BITMASK_FOR_LOWMOST_7BIT ;
}
/** Uses table "Table 5: SVI and internal VID codes" (7 bit) because same
* bit width as "15:9 CurCpuVid: current CPU core VID." (7 bit) ? */
inline fastestUnsignedDataType GetVoltageID(const float fVoltageInVolt )
{
/** E.g. for "1.1" V the float value is 1.0999999
* (because not all numbers are representable with a 8 byte value)
* so the voltage ID as float value gets "36.000004". */
/** 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG :
* "voltage = 1.550V - 0.0125V * SviVid[6:0];"
* voltage = 1,55V - 0.0125V * voltageID | - 1.55V
* voltage - 1.55 V = - 0.0125V * voltageID | : -0.0125V
* (voltage - 1.55 V) / -0.0125V = voltageID */
float fVoltageID = (fVoltageInVolt - 1.55f) / -0.0125f;
fastestUnsignedDataType voltageID =
/** without explicit cast: compiler warning
* Avoid g++ warning "warning: converting to `WORD' from `float'" */
(fastestUnsignedDataType)
fVoltageID;
/** Check to which integer voltage ID the float value is nearer.
* E.g. for: "36.0000008" - "36" = "0.0000008". -> use "36" */
if (fVoltageID - (float) voltageID >= 0.5)
++ voltageID;
return voltageID;
}
/** Applies to AMD family 10h, 11h */
inline float * GetAvailableVoltagesInVolt(
WORD wCoreID
, WORD * p_wNum )
{
/** Must be a signed data type, else in the comparison in the loop the
* signed data type is converted to the data type of this variable
* (unsigned) */
fastestSignedDataType voltageIDforHighestVoltage;
fastestUnsignedDataType voltageIDforLowestVoltage;
GetMinAndMaxVoltageID(voltageIDforLowestVoltage,
(fastestUnsignedDataType &) voltageIDforHighestVoltage);
const fastestUnsignedDataType numAvailableVoltages =
voltageIDforLowestVoltage - voltageIDforHighestVoltage + 1;
float * ar_f = new float[numAvailableVoltages];
if( ar_f)
{
fastestUnsignedDataType arrayIndex = 0;
/** see 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG
* , "Table 8: SVI and internal VID codes" :
* Higher voltage IDs mean lower voltages */
for( /** Use signed data type here, else the value wraps to the max
* value for the data type if 0 is decremented. */
fastestSignedDataType voltageID = voltageIDforLowestVoltage;
voltageID >= voltageIDforHighestVoltage; voltageID --)
{
ar_f[arrayIndex ++] = GetVoltageInVolt(voltageID);
}
* p_wNum = numAvailableVoltages;
}
else
* p_wNum = 0;
return ar_f;
}
/*inline void GetAvailableVoltagesInVolt(VIDforLowestVoltage, minVID)
{
}*/
}
}
#endif /* FROM_K10_H_ */
| 42.238971
| 95
| 0.675081
|
st-gb
|
b72fb196dd2c5415588ce2146628e6f56fc4cb26
| 12,364
|
cpp
|
C++
|
Chapter04/scratchpad.cpp
|
trantrongquy/Hands-On-System-Programming-with-CPP
|
c29f464c4df79f0d5a55a61f02a2558be74a329c
|
[
"MIT"
] | 88
|
2018-07-20T17:38:40.000Z
|
2022-03-16T15:00:20.000Z
|
Chapter04/scratchpad.cpp
|
trantrongquy/Hands-On-System-Programming-with-CPP
|
c29f464c4df79f0d5a55a61f02a2558be74a329c
|
[
"MIT"
] | 1
|
2020-01-01T08:12:24.000Z
|
2020-01-01T08:12:24.000Z
|
Chapter04/scratchpad.cpp
|
trantrongquy/Hands-On-System-Programming-with-CPP
|
c29f464c4df79f0d5a55a61f02a2558be74a329c
|
[
"MIT"
] | 46
|
2019-01-27T15:19:45.000Z
|
2022-03-04T13:21:23.000Z
|
//
// Copyright (C) 2018 Rian Quinn <rianquinn@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// -----------------------------------------------------------------------------
// Section: Stream Based IO
// -----------------------------------------------------------------------------
#if SNIPPET01
#include <iostream>
int main(void)
{
if (auto i = 42; i > 0) {
std::cout << "Hello World\n";
}
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET02
#include <iostream>
int main(void)
{
switch(auto i = 42) {
case 42:
std::cout << "Hello World\n";
break;
default:
break;
}
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET03
#include <iostream>
constexpr const auto val = true;
int main(void)
{
if (val) {
std::cout << "Hello World\n";
}
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET04
#include <iostream>
int main(void)
{
if constexpr (constexpr const auto i = 42; i > 0) {
std::cout << "Hello World\n";
}
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET05
#include <iostream>
int main(void)
{
static_assert(42 == 42, "the answer");
}
// > g++ scratchpad.cpp; ./a.out
//
#endif
#if SNIPPET06
#include <iostream>
int main(void)
{
static_assert(42 == 42);
}
// > g++ scratchpad.cpp; ./a.out
//
#endif
#if SNIPPET07
#include <iostream>
namespace X::Y::Z
{
auto msg = "Hello World\n";
}
int main(void)
{
std::cout << X::Y::Z::msg;
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET08
#include <iostream>
namespace X
{
namespace Y
{
namespace Z
{
auto msg = "Hello World\n";
}
}
}
int main(void)
{
std::cout << X::Y::Z::msg;
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET09
#include <iostream>
std::pair<const char *, int>
give_me_a_pair()
{
return {"The answer is: ", 42};
}
int main(void)
{
auto [msg, answer] = give_me_a_pair();
std::cout << msg << answer << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// The answer is: 42
#endif
#if SNIPPET10
#include <utility>
#include <iostream>
std::pair<const char *, int>
give_me_a_pair()
{
return {"The answer is: ", 42};
}
int main(void)
{
auto p = give_me_a_pair();
std::cout << std::get<0>(p) << std::get<1>(p) << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// The answer is: 42
#endif
#if SNIPPET11
#include <iostream>
struct mystruct
{
const char *msg;
int answer;
};
mystruct
give_me_a_struct()
{
return {"The answer is: ", 42};
}
int main(void)
{
auto [msg, answer] = give_me_a_struct();
std::cout << msg << answer << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// The answer is: 42
#endif
#if SNIPPET12
#include <iostream>
inline auto msg = "Hello World\n";
int main(void)
{
std::cout << msg;
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET13
#include <iostream>
#include <string_view>
int main(void)
{
std::string_view str("Hello World\n");
std::cout << str;
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET14
#include <iostream>
#include <string_view>
int main(void)
{
std::string_view str("Hello World");
std::cout << str.front() << '\n';
std::cout << str.back() << '\n';
std::cout << str.at(1) << '\n';
std::cout << str.data() << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// H
// d
// e
// Hello World
#endif
#if SNIPPET15
#include <iostream>
#include <string_view>
int main(void)
{
std::string_view str("Hello World");
std::cout << str.size() << '\n';
std::cout << str.max_size() << '\n';
std::cout << str.empty() << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// 11
// 4611686018427387899
// 0
#endif
#if SNIPPET16
#include <iostream>
#include <string_view>
int main(void)
{
std::string_view str("Hello World");
str.remove_prefix(1);
str.remove_suffix(1);
std::cout << str << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// ello Worl
#endif
#if SNIPPET17
#include <iostream>
#include <string_view>
int main(void)
{
std::string_view str("Hello World");
std::cout << str.substr(0, 5) << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// Hello
#endif
#if SNIPPET18
#include <iostream>
#include <string_view>
int main(void)
{
std::string_view str("Hello World");
if (str.compare("Hello World") == 0) {
std::cout << "Hello World\n";
}
std::cout << str.compare("Hello") << '\n';
std::cout << str.compare("World") << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
// 6
// -1
#endif
#if SNIPPET19
#include <iostream>
int main(void)
{
std::string_view str("Hello this is a test of Hello World");
std::cout << str.find("Hello") << '\n';
std::cout << str.rfind("Hello") << '\n';
std::cout << str.find_first_of("Hello") << '\n';
std::cout << str.find_last_of("Hello") << '\n';
std::cout << str.find_first_not_of("Hello") << '\n';
std::cout << str.find_last_not_of("Hello") << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// 0
// 24
// 0
// 33
// 5
// 34
#endif
#if SNIPPET20
#include <iostream>
#include <any>
struct mystruct {
int data;
};
int main(void)
{
auto myany = std::make_any<int>(42);
std::cout << std::any_cast<int>(myany) << '\n';
myany = 4.2;
std::cout << std::any_cast<double>(myany) << '\n';
myany = mystruct{42};
std::cout << std::any_cast<mystruct>(myany).data << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// 42
// 4.2
// 42
#endif
#if SNIPPET21
#include <iostream>
#include <variant>
int main(void)
{
std::variant<int, double> v = 42;
std::cout << std::get<int>(v) << '\n';
v = 4.2;
std::cout << std::get<double>(v) << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// 42
// 4.2
#endif
#if SNIPPET22
#include <iostream>
#include <optional>
class myclass
{
public:
int val;
myclass(int v) :
val{v}
{
std::cout << "constructed\n";
}
};
int main(void)
{
std::optional<myclass> o;
std::cout << "created, but not constructed\n";
if (o) {
std::cout << "Attempt #1: " << o->val << '\n';
}
o = myclass{42};
if (o) {
std::cout << "Attempt #2: " << o->val << '\n';
}
}
// > g++ scratchpad.cpp; ./a.out
// created, but not constructed
// constructed
// Attempt #2: 42
#endif
#if SNIPPET23
#include <iostream>
class myclass
{
public:
myclass()
{
std::cout << "Hello from constructor\n";
}
~myclass()
{
std::cout << "Hello from destructor\n";
}
};
int main(void)
{
myclass c;
}
// > g++ scratchpad.cpp; ./a.out
// Hello from constructor
// Hello from destructor
#endif
#if SNIPPET24
#include <iostream>
class myclass
{
int *ptr;
public:
myclass() :
ptr{new int(42)}
{ }
~myclass()
{
delete ptr;
}
int get()
{
return *ptr;
}
};
int main(void)
{
myclass c;
std::cout << "The answer is: " << c.get() << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// The answer is: 42
#endif
#if SNIPPET25
#include <iostream>
class myclass
{
FILE *m_file;
public:
myclass(const char *filename) :
m_file{fopen(filename, "rb")}
{
if (m_file == 0) {
throw std::runtime_error("unable to open file");
}
}
~myclass()
{
fclose(m_file);
std::clog << "Hello from destructor\n";
}
};
int main(void)
{
myclass c1("test.txt");
try {
myclass c2("does_not_exist.txt");
}
catch(const std::exception &e) {
std::cout << "exception: " << e.what() << '\n';
}
}
// > g++ scratchpad.cpp; touch test.txt; ./a.out
// exception: unable to open file
// Hello from destructor
#endif
#if SNIPPET26
#include <gsl/gsl>
void init(int *p)
{
*p = 0;
}
int main(void)
{
auto p = new int;
init(p);
delete p;
}
// > g++ scratchpad.cpp; ./a.out
//
#endif
#if SNIPPET27
#include <gsl/gsl>
void init(int *p)
{
*p = 0;
}
int main(void)
{
gsl::owner<int *> p = new int;
init(p);
delete p;
}
// > g++ scratchpad.cpp; ./a.out
//
#endif
#if SNIPPET28
#include <gsl/gsl>
gsl::not_null<int *>
test(gsl::not_null<int *> p)
{
return p;
}
int main(void)
{
auto p1 = std::make_unique<int>();
auto p2 = test(gsl::not_null(p1.get()));
}
// > g++ scratchpad.cpp; ./a.out
//
#endif
#if SNIPPET29
#define GSL_THROW_ON_CONTRACT_VIOLATION
#include <gsl/gsl>
#include <iostream>
int main(void)
{
int array[5] = {1, 2, 3, 4, 5};
auto span = gsl::span(array);
for (const auto &elem : span) {
std::clog << elem << '\n';
}
for (auto i = 0; i < 5; i++) {
std::clog << span[i] << '\n';
}
try {
std::clog << span[5] << '\n';
}
catch(const gsl::fail_fast &e) {
std::cout << "exception: " << e.what() << '\n';
}
}
// > g++ scratchpad.cpp; ./a.out
// 1
// 2
// 3
// 4
// 5
// 1
// 2
// 3
// 4
// 5
// exception: GSL: Precondition failure at ...
#endif
#if SNIPPET30
#include <gsl/gsl>
#include <iostream>
int main(void)
{
gsl::cstring_span<> str = gsl::ensure_z("Hello World\n");
std::cout << str.data();
for (const auto &elem : str) {
std::clog << elem;
}
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
// Hello World
#endif
#if SNIPPET31
#define GSL_THROW_ON_CONTRACT_VIOLATION
#include <gsl/gsl>
#include <iostream>
int main(void)
{
try {
Expects(false);
}
catch(const gsl::fail_fast &e) {
std::cout << "exception: " << e.what() << '\n';
}
}
// > g++ scratchpad.cpp; ./a.out
// exception: GSL: Precondition failure at ...
#endif
#if SNIPPET32
#define GSL_THROW_ON_CONTRACT_VIOLATION
#include <gsl/gsl>
#include <iostream>
int
test(int i)
{
Expects(i >= 0 && i < 41);
i++;
Ensures(i < 42);
return i;
}
int main(void)
{
test(0);
try {
test(42);
}
catch(const gsl::fail_fast &e) {
std::cout << "exception: " << e.what() << '\n';
}
}
// > g++ scratchpad.cpp; ./a.out
// exception: GSL: Precondition failure at ...
#endif
#if SNIPPET33
#include <gsl/gsl>
#include <iostream>
int
test(int i)
{
Expects(i < 42);
i = 42;
Ensures(i == 42);
return i;
}
int main(void)
{
std::cout << test(0) << '\n';
}
// > g++ scratchpad.cpp; ./a.out
// 42
#endif
#if SNIPPET34
#define concat1(a,b) a ## b
#define concat2(a,b) concat1(a,b)
#define ___ concat2(dont_care, __COUNTER__)
#include <gsl/gsl>
#include <iostream>
int main(void)
{
auto ___ = gsl::finally([]{
std::cout << "Hello World\n";
});
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
#endif
#if SNIPPET35
#include <gsl/gsl>
#include <iostream>
int main(void)
{
uint64_t val = 42;
auto val1 = gsl::narrow<uint32_t>(val);
auto val2 = gsl::narrow_cast<uint32_t>(val);
}
// > g++ scratchpad.cpp; ./a.out
//
#endif
#if SNIPPET36
#define GSL_THROW_ON_CONTRACT_VIOLATION
#include <gsl/gsl>
#include <iostream>
int main(void)
{
uint64_t val = 0xFFFFFFFFFFFFFFFF;
try {
gsl::narrow<uint32_t>(val);
}
catch(...) {
std::cout << "narrow failed\n";
}
}
// > g++ scratchpad.cpp; ./a.out
// narrow failed
#endif
| 14.376744
| 81
| 0.566564
|
trantrongquy
|
b7340c408c1c4898afc411a34aa908f0ed5ca779
| 2,378
|
cpp
|
C++
|
framework/sphere.cpp
|
henrik-leisdon/programmiersprachen-raytracer-1
|
bd3185095ba50b55f85394d361deb43a7a30c871
|
[
"MIT"
] | null | null | null |
framework/sphere.cpp
|
henrik-leisdon/programmiersprachen-raytracer-1
|
bd3185095ba50b55f85394d361deb43a7a30c871
|
[
"MIT"
] | 1
|
2019-08-03T11:36:46.000Z
|
2019-08-27T16:23:08.000Z
|
framework/sphere.cpp
|
henrik-leisdon/programmiersprachen-raytracer-1
|
bd3185095ba50b55f85394d361deb43a7a30c871
|
[
"MIT"
] | null | null | null |
#include "sphere.hpp"
#include <math.h>
#include <glm/gtx/intersect.hpp>
using namespace std;
using namespace glm;
Sphere::Sphere():
Shape(),
center_({0.0,0.0,0.0}),
radius_{0.0}
{};
Sphere::Sphere(string name, vec3 const& center, double radius, shared_ptr<Material> material):
Shape{name, material},
center_{center},
radius_{radius}
{};
Sphere::~Sphere() {}
vec3 Sphere::getCenter() const
{
return center_;
}
double Sphere::getRadius() const
{
return radius_;
}
double Sphere::area() const {
double area = 4*M_PI*pow(getRadius(),2);
return area;
}
double Sphere::volume() const {
double volume = (4.0/3.0)*M_PI*pow(getRadius(),3);
return volume;
}
Hit Sphere::intersect(Ray const &firstRay, float &t) {
bool intersect;
Hit result;
Ray ray={firstRay.origin, firstRay.direction};
if(isTransformed_){
ray = transformRay(inverse_world_transform_, ray);
} else {
ray = firstRay;
}
vec3 normDir = normalize(ray.direction);
intersect = intersectRaySphere(ray.origin, normalize(ray.direction), center_ ,radius_*radius_, t);
if(intersect) {
vec3 hitpoint = vec3{ray.origin+normDir*t};
vec3 normToShape = vec3{hitpoint-center_};
//cout << getName() << " normal in intersect: " << normToShape.x << " " << normToShape.y << " " << normToShape.z << "\n";
result.hit_ = true;
result.hitnormal_ = normToShape;
result.hitpoint_ = hitpoint;
result.dist_ = t;
result.direction_ = normDir;
if(isTransformed_) {
vec4 transformNormal = glm::normalize(transpose(inverse_world_transform_)*vec4{result.hitnormal_,0});
result.hitnormal_ = vec3({transformNormal.x, transformNormal.y, transformNormal.z});
vec4 transformHit = world_transform_ * vec4{result.hitpoint_, 1};
result.hitpoint_ = vec3{transformHit.x, transformHit.y, transformHit.z};
}
return result;
}
else {
Hit result = Hit();
return result;
}
}
ostream& Sphere::print(ostream &os) const {
Shape::print(os);
os
<< "Position : " << center_.x << ", " << center_.y << ", " << center_.z << "\n"
<< "Radius : " << radius_ << "\n";
return os;
}
ostream& operator << (ostream& os, const Sphere s) {
return s.print(os);
}
| 25.297872
| 130
| 0.611438
|
henrik-leisdon
|
b738175f4ebe5b9369135316a54a20bd5967766b
| 1,600
|
cc
|
C++
|
UVa/409_Excuses, Excuses!/409.cc
|
pdszhh/ACM
|
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
|
[
"MIT"
] | 1
|
2019-05-05T03:51:20.000Z
|
2019-05-05T03:51:20.000Z
|
UVa/409_Excuses, Excuses!/409.cc
|
pdszhh/ACM
|
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
|
[
"MIT"
] | null | null | null |
UVa/409_Excuses, Excuses!/409.cc
|
pdszhh/ACM
|
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <algorithm>
#include <locale>
using namespace std;
int main() {
std::locale loc;
int k, e;
int index = 1;
while (cin >> k >> e) {
cin.get();
string *keyword = new string[k];
string *excuse = new string[e];
string *excuseLower = new string[e];
int *times = new int[e];
int maxTimes = 0;
// input
for (int i = 0; i < k; i++) {
getline(cin, keyword[i]);
}
for (int i = 0; i < e; i++) {
getline(cin, excuse[i]);
excuseLower[i] = excuse[i];
transform(excuseLower[i].begin(), excuseLower[i].end(), excuseLower[i].begin(), ::tolower);
}
// calc
for (int i = 0; i < e; i++) {
times[i] = -1;
for (int j = 0; j < k; j++) {
int pos = -1;
while ((pos = excuseLower[i].find(keyword[j], pos + 1)) != excuseLower[i].npos) {
if (pos == 0 or pos + keyword[j].length() == excuseLower[i].length()
or (not isalpha(excuseLower[i][pos - 1], loc)
and not isalpha(excuseLower[i][pos + keyword[j].length()], loc)))
times[i]++;
}
maxTimes = max(times[i], maxTimes);
}
}
// output
cout << "Excuse Set #" << index++ << endl;
for (int i = 0; i < e; i++)
if (times[i] == maxTimes)
cout << excuse[i] << endl;
cout << endl;
}
return 0;
}
| 28.571429
| 103
| 0.434375
|
pdszhh
|
b7385a71a9bcf5c02ed00ee07eebbb6b98551212
| 12,793
|
cpp
|
C++
|
benchmark-tests/benchmark_tests_fftw3.cpp
|
opalcompany/Simple-FFT
|
5f397670ecac53c68ab1df90c36a319bd277b5d3
|
[
"MIT"
] | 115
|
2015-01-11T23:41:28.000Z
|
2022-03-08T01:09:49.000Z
|
benchmark-tests/benchmark_tests_fftw3.cpp
|
opalcompany/Simple-FFT
|
5f397670ecac53c68ab1df90c36a319bd277b5d3
|
[
"MIT"
] | 7
|
2018-07-26T21:42:40.000Z
|
2021-11-08T20:24:03.000Z
|
benchmark-tests/benchmark_tests_fftw3.cpp
|
opalcompany/Simple-FFT
|
5f397670ecac53c68ab1df90c36a319bd277b5d3
|
[
"MIT"
] | 25
|
2015-03-20T14:41:56.000Z
|
2021-12-29T09:51:54.000Z
|
#include "../include/simple_fft/fft_settings.h"
#ifndef __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR
#define __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR
#endif
#include "benchmark_tests_fftw3.h"
#include "../unit-tests/test_fft.hpp"
#include <vector>
#include <complex>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <fftw3.h>
namespace simple_fft {
namespace fft_test {
bool BenchmarkTestAgainstFFTW3()
{
bool res;
const char * err_str = NULL;
const int numFFTLoops1D = 10000;
const int numFFTLoops2D = 500;
const int numFFTLoops3D = 15;
using namespace pulse_params;
std::vector<real_type> t, x, y;
makeGridsForPulse3D(t, x, y);
// typedefing vectors
typedef std::vector<real_type> RealArray1D;
typedef std::vector<complex_type> ComplexArray1D;
typedef std::vector<std::vector<real_type> > RealArray2D;
typedef std::vector<std::vector<complex_type> > ComplexArray2D;
typedef std::vector<std::vector<std::vector<real_type> > > RealArray3D;
typedef std::vector<std::vector<std::vector<complex_type> > > ComplexArray3D;
// 1D fields and spectrum
RealArray1D E1_real(nt);
ComplexArray1D E1_complex(nt), G1(nt);
// 2D fields and spectrum
RealArray2D E2_real(nt);
ComplexArray2D E2_complex(nt), G2(nt);
int grid_size_t = static_cast<int>(nt);
#ifndef __clang__
#ifdef __USE_OPENMP
#pragma omp parallel for
#endif
#endif
for(int i = 0; i < grid_size_t; ++i) {
E2_real[i].resize(nx);
E2_complex[i].resize(nx);
G2[i].resize(nx);
}
// 3D fields and spectrum
RealArray3D E3_real(nt);
ComplexArray3D E3_complex(nt), G3(nt);
int grid_size_x = static_cast<int>(nx);
#ifndef __clang__
#ifdef __USE_OPENMP
#pragma omp parallel for
#endif
#endif
for(int i = 0; i < grid_size_t; ++i) {
E3_real[i].resize(nx);
E3_complex[i].resize(nx);
G3[i].resize(nx);
for(int j = 0; j < grid_size_x; ++j) {
E3_real[i][j].resize(ny);
E3_complex[i][j].resize(ny);
G3[i][j].resize(ny);
}
}
CMakeInitialPulses3D<RealArray1D,RealArray2D,RealArray3D,true>::makeInitialPulses(E1_real, E2_real, E3_real);
CMakeInitialPulses3D<ComplexArray1D,ComplexArray2D,ComplexArray3D,false>::makeInitialPulses(E1_complex, E2_complex, E3_complex);
// Measure the execution time of Simple FFT
// 1) 1D Simple FFT for real data
clock_t beginTime = clock();
for(int i = 0; i < numFFTLoops1D; ++i) {
res = FFT(E1_real, G1, nt, err_str);
if (!res) {
std::cout << "Simple FFT 1D real failed: " << err_str << std::endl;
return false;
}
}
std::cout << "Simple 1D FFT for real data: execution time for "
<< numFFTLoops1D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
// 2) 1D Simple FFT for complex data
beginTime = clock();
for(int i = 0; i < numFFTLoops1D; ++i) {
res = FFT(E1_complex, G1, nt, err_str);
if (!res) {
std::cout << "Simple FFT 1D complex failed: " << err_str << std::endl;
return false;
}
}
std::cout << "Simple 1D FFT for complex data: execution time for "
<< numFFTLoops1D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
// 3) 2D Simple FFT for real data
beginTime = clock();
for(int i = 0; i < numFFTLoops2D; ++i) {
res = FFT(E2_real, G2, nt, nx, err_str);
if (!res) {
std::cout << "Simple FFT 2D real failed: " << err_str << std::endl;
return false;
}
}
std::cout << "Simple 2D FFT for real data: execution time for "
<< numFFTLoops2D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
// 4) 2D Simple FFT for complex data
beginTime = clock();
for(int i = 0; i < numFFTLoops2D; ++i) {
res = FFT(E2_complex, G2, nt, nx, err_str);
if (!res) {
std::cout << "Simple FFT 2D complex failed: " << err_str << std::endl;
return false;
}
}
std::cout << "Simple 2D FFT for complex data: execution time for "
<< numFFTLoops2D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
// 5) 3D Simple FFT for real data
beginTime = clock();
for(int i = 0; i < numFFTLoops3D; ++i) {
res = FFT(E3_real, G3, nt, nx, ny, err_str);
if (!res) {
std::cout << "Simple FFT 3D real failed: " << err_str << std::endl;
return false;
}
}
std::cout << "Simple 3D FFT for real data: execution time for "
<< numFFTLoops3D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
// 6) 3D Simple FFT for complex data
beginTime = clock();
for(int i = 0; i < numFFTLoops3D; ++i) {
res = FFT(E3_complex, G3, nt, nx, ny, err_str);
if (!res) {
std::cout << "Simple FFT 3D complex failed: " << err_str << std::endl;
return false;
}
}
std::cout << "Simple 3D FFT for complex data: execution time for "
<< numFFTLoops3D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
// Measure the execution time for FFTW3
// 1) FFTW 1D for real data
fftw_plan fftwPlan = fftw_plan_dft_r2c_1d(nt, &E1_real[0],
reinterpret_cast<fftw_complex*>(&G1[0]),
FFTW_MEASURE);
beginTime = clock();
for(int i = 0; i < numFFTLoops1D; ++i) {
fftw_execute(fftwPlan);
}
std::cout << "FFTW3 1D FFT for real data: execution time for "
<< numFFTLoops1D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
fftw_destroy_plan(fftwPlan);
// 2) FFTW 1D for complex data
fftwPlan = fftw_plan_dft_1d(nt, reinterpret_cast<fftw_complex*>(&E1_complex[0]),
reinterpret_cast<fftw_complex*>(&G1[0]),
FFTW_FORWARD, FFTW_MEASURE);
beginTime = clock();
for(int i = 0; i < numFFTLoops1D; ++i) {
fftw_execute(fftwPlan);
}
std::cout << "FFTW3 1D FFT for complex data: execution time for "
<< numFFTLoops1D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
fftw_destroy_plan(fftwPlan);
// 3) FFTW 2D for real data
// NOTE: I can't pass my data to FFTW in its original form, it causes runtime errors,
// so I'm allocating another buffer array and copying my data twice -
// before and after the FFT. And yes, I'm including the time it takes
// into the measurement because I'm measuring the time to get the job done,
// not the time of some function being running.
beginTime = clock();
real_type* twoDimRealArray = (real_type*)(fftw_malloc(nt*nx*sizeof(real_type)));
fftw_complex* twoDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*sizeof(fftw_complex)));
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
*(twoDimRealArray + i * nx + j) = E2_real[i][j];
}
}
fftwPlan = fftw_plan_dft_r2c_2d(nt, nx, twoDimRealArray, twoDimComplexArray,
FFTW_MEASURE);
for(int i = 0; i < numFFTLoops2D; ++i) {
fftw_execute(fftwPlan);
}
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
G2[i][j] = complex_type((*(twoDimComplexArray + i*nx + j))[0],
(*(twoDimComplexArray + i*nx + j))[1]);
}
}
std::cout << "FFTW 2D FFT for real data: execution time for "
<< numFFTLoops2D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
fftw_destroy_plan(fftwPlan);
// 4) FFTW 2D for complex data
beginTime = clock();
twoDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*sizeof(fftw_complex)));
fftw_complex* twoDimComplexArraySpectrum = (fftw_complex*)(fftw_malloc(nt*nx*sizeof(fftw_complex)));
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
*(twoDimComplexArray + i * nx + j)[0] = std::real(E2_complex[i][j]);
*(twoDimComplexArray + i * nx + j)[1] = std::imag(E2_complex[i][j]);
}
}
fftwPlan = fftw_plan_dft_2d(nt, nx, twoDimComplexArray, twoDimComplexArraySpectrum,
FFTW_FORWARD, FFTW_MEASURE);
for(int i = 0; i < numFFTLoops2D; ++i) {
fftw_execute(fftwPlan);
}
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
G2[i][j] = complex_type((*(twoDimComplexArraySpectrum + i*nx + j))[0],
(*(twoDimComplexArraySpectrum + i*nx + j))[1]);
}
}
std::cout << "FFTW 2D FFT for complex data: execution time for "
<< numFFTLoops2D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
fftw_destroy_plan(fftwPlan);
// 5) FFTW 3D for real data
beginTime = clock();
real_type* threeDimRealArray = (real_type*)(fftw_malloc(nt*nx*ny*sizeof(real_type)));
fftw_complex* threeDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*ny*sizeof(fftw_complex)));
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
for(size_t k = 0; k < ny; ++k) {
*(threeDimRealArray + i * nx * ny + j * ny + k) = E3_real[i][j][k];
}
}
}
fftwPlan = fftw_plan_dft_r2c_3d(nt, nx, ny, threeDimRealArray, threeDimComplexArray,
FFTW_MEASURE);
for(int i = 0; i < numFFTLoops3D; ++i) {
fftw_execute(fftwPlan);
}
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
for(size_t k = 0; k < ny; ++k) {
E3_real[i][j][k] = *(threeDimRealArray + i * nx * ny + j * ny + k);
G3[i][j][k] = complex_type((*(threeDimComplexArray + i * nx * ny + j * ny + k))[0],
(*(threeDimComplexArray + i * nx * ny + j * ny + k))[1]);
}
}
}
std::cout << "FFTW 3D FFT for real data: execution time for "
<< numFFTLoops3D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
fftw_destroy_plan(fftwPlan);
// 6) FFTW 3D for complex data
beginTime = clock();
threeDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*ny*sizeof(fftw_complex)));
fftw_complex* threeDimComplexArraySpectrum = (fftw_complex*)(fftw_malloc(nt*nx*ny*sizeof(fftw_complex)));
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
for(size_t k = 0; k < ny; ++k) {
*(threeDimComplexArray + i * nx * ny + j * ny + k)[0] = std::real(E3_complex[i][j][k]);
*(threeDimComplexArray + i * nx * ny + j * ny + k)[1] = std::imag(E3_complex[i][j][k]);
}
}
}
fftwPlan = fftw_plan_dft_3d(nt, nx, ny, threeDimComplexArray, threeDimComplexArraySpectrum,
FFTW_FORWARD, FFTW_MEASURE);
for(int i = 0; i < numFFTLoops3D; ++i) {
fftw_execute(fftwPlan);
}
for(size_t i = 0; i < nt; ++i) {
for(size_t j = 0; j < nx; ++j) {
for(size_t k = 0; k < ny; ++k) {
G3[i][j][k] = complex_type((*(threeDimComplexArraySpectrum + i * nx * ny + j * ny + k))[0],
(*(threeDimComplexArraySpectrum + i * nx * ny + j * ny + k))[1]);
}
}
}
std::cout << "FFTW 3D FFT for complex data: execution time for "
<< numFFTLoops3D << " loops: " << std::setprecision(20)
<< real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl;
fftw_destroy_plan(fftwPlan);
return true;
}
} // namespace fft_test
} // namespace simple_fft
| 41.944262
| 133
| 0.551317
|
opalcompany
|
b73bcc568506cfed291532a642ee8941cfce80be
| 1,736
|
cpp
|
C++
|
docker/build/face_detection/face_detector/src/utils.cpp
|
mykiscool/DeepCamera
|
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
|
[
"MIT"
] | 914
|
2019-03-07T14:57:45.000Z
|
2022-03-31T14:54:15.000Z
|
docker/build/face_detection/face_detector/src/utils.cpp
|
mykiscool/DeepCamera
|
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
|
[
"MIT"
] | 45
|
2019-03-11T09:53:37.000Z
|
2022-03-30T21:59:37.000Z
|
docker/build/face_detection/face_detector/src/utils.cpp
|
mykiscool/DeepCamera
|
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
|
[
"MIT"
] | 148
|
2019-03-08T00:40:28.000Z
|
2022-03-30T09:22:18.000Z
|
#include <iostream>
#include "utils.h"
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
float getElapse(struct timeval *tv1,struct timeval *tv2)
{
float t = 0.0f;
if (tv1->tv_sec == tv2->tv_sec)
t = (tv2->tv_usec - tv1->tv_usec)/1000.0f;
else
t = ((tv2->tv_sec - tv1->tv_sec) * 1000 * 1000 + tv2->tv_usec - tv1->tv_usec)/1000.0f;
return t;
}
int trave_dir(std::string& path, std::vector<std::string>& file_list)
{
DIR *d; //声明一个句柄
struct dirent* dt; //readdir函数的返回值就存放在这个结构体中
struct stat sb;
if(!(d = opendir(path.c_str())))
{
std::cout << "Error opendir: " << path << std::endl;
return -1;
}
while((dt = readdir(d)) != NULL)
{
// std::cout << "file name: " << dt->d_name << std::endl;
std::string file_name = dt->d_name;
if(file_name[0] == '.') {
continue;
}
// if(strncmp(dt->d_name, ".", 1) == 0 || strncmp(dt->d_name, "..", 2) == 0) {
// continue;
// }
std::string file_path = path + "/" + dt->d_name;
// std::cout << "file path: " << file_path << std::endl;
if(stat(file_path.c_str(), &sb) < 0) {
std::cout << "Error stat file: " << file_path << std::endl;
return -1;
}
if (S_ISDIR(sb.st_mode)) {
// is a directory
// std::cout << "directory: " << file_path << std::endl;
trave_dir(file_path, file_list);
} else {
// is a regular file
// std::cout << "file: " << file_path << std::endl;
file_list.push_back(file_path);
}
}
// close directory
closedir(d);
return 0;
}
| 28
| 94
| 0.49712
|
mykiscool
|
b73ebe1ddd7c7c326523e29757b1db694d23a093
| 993
|
cpp
|
C++
|
backup/2/hackerrank/c++/find-merge-point-of-two-lists.cpp
|
yangyanzhan/code-camp
|
4272564e916fc230a4a488f92ae32c07d355dee0
|
[
"Apache-2.0"
] | 21
|
2019-11-16T19:08:35.000Z
|
2021-11-12T12:26:01.000Z
|
backup/2/hackerrank/c++/find-merge-point-of-two-lists.cpp
|
yangyanzhan/code-camp
|
4272564e916fc230a4a488f92ae32c07d355dee0
|
[
"Apache-2.0"
] | 1
|
2022-02-04T16:02:53.000Z
|
2022-02-04T16:02:53.000Z
|
backup/2/hackerrank/c++/find-merge-point-of-two-lists.cpp
|
yangyanzhan/code-camp
|
4272564e916fc230a4a488f92ae32c07d355dee0
|
[
"Apache-2.0"
] | 4
|
2020-05-15T19:39:41.000Z
|
2021-10-30T06:40:31.000Z
|
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/hackerrank/find-merge-point-of-two-lists.html .
int findMergeNode(SinglyLinkedListNode *head1, SinglyLinkedListNode *head2) {
auto curr1 = head1, curr2 = head2;
while (curr1 != curr2) {
if (curr1->next) {
curr1 = curr1->next;
} else {
curr1 = head2;
}
if (curr2->next) {
curr2 = curr2->next;
} else {
curr2 = head1;
}
}
return curr1;
}
| 45.136364
| 345
| 0.655589
|
yangyanzhan
|
b744b10f31a5dee404f71196448427003b79ebb8
| 4,573
|
cpp
|
C++
|
src/strategy/values/LootValues.cpp
|
htc16/mod-playerbots
|
2307e3f980035a244bfb4fedefda5bc55903d470
|
[
"MIT"
] | 12
|
2022-03-23T05:14:53.000Z
|
2022-03-30T12:12:58.000Z
|
src/strategy/values/LootValues.cpp
|
htc16/mod-playerbots
|
2307e3f980035a244bfb4fedefda5bc55903d470
|
[
"MIT"
] | 24
|
2022-03-23T13:56:37.000Z
|
2022-03-31T18:23:32.000Z
|
src/strategy/values/LootValues.cpp
|
htc16/mod-playerbots
|
2307e3f980035a244bfb4fedefda5bc55903d470
|
[
"MIT"
] | 3
|
2022-03-24T21:47:10.000Z
|
2022-03-31T06:21:46.000Z
|
/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
*/
#include "LootValues.h"
#include "SharedValueContext.h"
#include "Playerbots.h"
LootTemplateAccess const* DropMapValue::GetLootTemplate(ObjectGuid guid, LootType type)
{
LootTemplate const* lTemplate = nullptr;
if (guid.IsCreature())
{
CreatureTemplate const* info = sObjectMgr->GetCreatureTemplate(guid.GetEntry());
if (info)
{
if (type == LOOT_CORPSE)
lTemplate = LootTemplates_Creature.GetLootFor(info->lootid);
else if (type == LOOT_PICKPOCKETING && info->pickpocketLootId)
lTemplate = LootTemplates_Pickpocketing.GetLootFor(info->pickpocketLootId);
else if (type == LOOT_SKINNING && info->SkinLootId)
lTemplate = LootTemplates_Skinning.GetLootFor(info->SkinLootId);
}
}
else if (guid.IsGameObject())
{
GameObjectTemplate const* info = sObjectMgr->GetGameObjectTemplate(guid.GetEntry());
if (info && info->GetLootId() != 0)
{
if (type == LOOT_CORPSE)
lTemplate = LootTemplates_Gameobject.GetLootFor(info->GetLootId());
else if (type == LOOT_FISHINGHOLE)
lTemplate = LootTemplates_Fishing.GetLootFor(info->GetLootId());
}
}
else if (guid.IsItem())
{
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(guid.GetEntry());
if (proto)
{
if (type == LOOT_CORPSE)
lTemplate = LootTemplates_Item.GetLootFor(proto->ItemId);
else if (type == LOOT_DISENCHANTING && proto->DisenchantID)
lTemplate = LootTemplates_Disenchant.GetLootFor(proto->DisenchantID);
if (type == LOOT_MILLING)
lTemplate = LootTemplates_Milling.GetLootFor(proto->ItemId);
if (type == LOOT_PROSPECTING)
lTemplate = LootTemplates_Prospecting.GetLootFor(proto->ItemId);
}
}
LootTemplateAccess const* lTemplateA = reinterpret_cast<LootTemplateAccess const*>(lTemplate);
return lTemplateA;
}
DropMap* DropMapValue::Calculate()
{
DropMap* dropMap = new DropMap;
int32 sEntry = 0;
if (CreatureTemplateContainer const* creatures = sObjectMgr->GetCreatureTemplates())
{
for (CreatureTemplateContainer::const_iterator itr = creatures->begin(); itr != creatures->end(); ++itr)
{
sEntry = itr->first;
if (LootTemplateAccess const* lTemplateA = GetLootTemplate(ObjectGuid::Create<HighGuid::Unit>(sEntry, uint32(1)), LOOT_CORPSE))
for (auto const& lItem : lTemplateA->Entries)
dropMap->insert(std::make_pair(lItem->itemid, sEntry));
}
}
if (GameObjectTemplateContainer const* gameobjects = sObjectMgr->GetGameObjectTemplates())
{
for (auto const& itr : *gameobjects)
{
sEntry = itr.first;
if (LootTemplateAccess const* lTemplateA = GetLootTemplate(ObjectGuid::Create<HighGuid::GameObject>(sEntry, uint32(1)), LOOT_CORPSE))
for (auto const& lItem : lTemplateA->Entries)
dropMap->insert(std::make_pair(lItem->itemid, -sEntry));
}
}
return dropMap;
}
//What items does this entry have in its loot list?
std::vector<int32> ItemDropListValue::Calculate()
{
uint32 itemId = stoi(getQualifier());
DropMap* dropMap = GAI_VALUE(DropMap*, "drop map");
std::vector<int32> entries;
auto range = dropMap->equal_range(itemId);
for (auto itr = range.first; itr != range.second; ++itr)
entries.push_back(itr->second);
return entries;
}
//What items does this entry have in its loot list?
std::vector<uint32> EntryLootListValue::Calculate()
{
int32 entry = stoi(getQualifier());
std::vector<uint32> items;
LootTemplateAccess const* lTemplateA;
if (entry > 0)
lTemplateA = DropMapValue::GetLootTemplate(ObjectGuid::Create<HighGuid::Unit>(entry, uint32(1)), LOOT_CORPSE);
else
lTemplateA = DropMapValue::GetLootTemplate(ObjectGuid::Create<HighGuid::GameObject>(entry, uint32(1)), LOOT_CORPSE);
if (lTemplateA)
for (auto const& lItem : lTemplateA->Entries)
items.push_back(lItem->itemid);
return items;
}
itemUsageMap EntryLootUsageValue::Calculate()
{
itemUsageMap items;
for (auto itemId : GAI_VALUE2(std::vector<uint32>, "entry loot list", getQualifier()))
{
items[AI_VALUE2(ItemUsage, "item usage", itemId)].push_back(itemId);
}
return items;
};
bool HasUpgradeValue::Calculate()
{
itemUsageMap uMap = AI_VALUE2(itemUsageMap, "entry loot usage", getQualifier());
return uMap.find(ITEM_USAGE_EQUIP) != uMap.end() || uMap.find(ITEM_USAGE_REPLACE) != uMap.end();
}
| 30.898649
| 205
| 0.704352
|
htc16
|
b7461dc3c38f04a368b803fea9a21530d882799f
| 6,821
|
cpp
|
C++
|
src/libcipcm/cwrap.cpp
|
wrathematics/pbdPAPI
|
cb3fad3bccd54b7aeeef9e687b52d938613a356e
|
[
"Intel",
"BSD-3-Clause"
] | 8
|
2015-02-14T17:00:51.000Z
|
2016-02-01T20:13:43.000Z
|
src/libcipcm/cwrap.cpp
|
QuantScientist3/pbdPAPI
|
708bee501de20eb82829e03b92b24b6352044f49
|
[
"Intel",
"BSD-3-Clause"
] | null | null | null |
src/libcipcm/cwrap.cpp
|
QuantScientist3/pbdPAPI
|
708bee501de20eb82829e03b92b24b6352044f49
|
[
"Intel",
"BSD-3-Clause"
] | 3
|
2015-03-26T13:41:27.000Z
|
2015-04-01T11:36:34.000Z
|
#define HACK_TO_REMOVE_DUPLICATE_ERROR
#include <iostream>
#ifdef OK_WIN_BUILD
#pragma warning(disable : 4996) // for sprintf
#include <windows.h>
#include "PCM_Win/windriver.h"
#else
#include <unistd.h>
#include <signal.h>
#endif
#include <math.h>
#include <iomanip>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <assert.h>
#include "cpucounters.h"
#include "utils.h"
#include "cwrap.h"
using namespace std;
#define SIZE (10000000)
#define DELAY 1 // in seconds
struct CSysCounterState{
PCM *m;
SystemCounterState start;
SystemCounterState end;
int cpu_model;
}global_state;
struct event_list_s{
uint64(*event_function)(const SystemCounterState&,const SystemCounterState&);
int atom;
};
static const struct event_list_s event_list[]={
{getL2CacheMisses,1},
{getL2CacheHits,1},
{getInstructionsRetired,1},
{getCycles,1},
{getL3CacheHitsNoSnoop,0},
{getL3CacheHitsSnoop,0},
{getL3CacheHits,0},
{getL3CacheMisses,0},
};
static int global_cpu_model=0;
static long long global_nominal_frequency=0;
static int global_max_cpus=0;
long long ipcm_get_frequency(){
return global_nominal_frequency;
}
int ipcm_get_cpus(){
return global_max_cpus;
}
void ipcm_get_cpuid(int *family, int *model){
*family=global_state.m->getCPUFamily();
*model=global_state.m->getCPUModel();
}
void ipcm_cpu_strings(char *vendor, char *model, char *codename){
int i;
const char *tmp = global_state.m->getCPUBrandString().c_str();
for(i=0;tmp[i] && tmp[i]!=' ';i++);
memcpy(vendor,tmp,i);
tmp+=i+1;
strcpy(model,tmp);
tmp=global_state.m->getUArchCodename();
strcpy(codename,tmp);
}
int ipcm_event_avail(const int code){
if(code>=IPCM_START_EVENT && code<IPCM_NULL_EVENT){
if(global_cpu_model==PCM::ATOM)
return event_list[code].atom;
else
return 1;
}
return 0;
}
static void set_diff_vals(PCM *m, const SystemCounterState *sstate1, const SystemCounterState *sstate2, const int cpu_model, ipcm_event_val_t *values, const int num){
int i;
for(i=0;i<num;i++){
//if(values[i].code>=IPCM_START_EVENT && values[i].code<IPCM_NULL_EVENT){
if(ipcm_event_avail(values[i].code))
values[i].val=event_list[values[i].code].event_function(*sstate1,*sstate2);
else
values[i].val=-1;
}
}
static void print_diff(
PCM *m,
const SystemCounterState *sstate1,
const SystemCounterState *sstate2,
const int cpu_model){
if (cpu_model != PCM::ATOM)
{
cout << " TOTAL * " << getExecUsage(*sstate1, *sstate2) <<
" " << getIPC(*sstate1, *sstate2) <<
" " << getRelativeFrequency(*sstate1, *sstate2) <<
" " << getActiveRelativeFrequency(*sstate1, *sstate2) <<
" " << unit_format(getL3CacheMisses(*sstate1, *sstate2)) <<
" " << unit_format(getL2CacheMisses(*sstate1, *sstate2)) <<
" " << getL3CacheHitRatio(*sstate1, *sstate2) <<
" " << getL2CacheHitRatio(*sstate1, *sstate2) <<
" " << getCyclesLostDueL3CacheMisses(*sstate1, *sstate2) <<
" " << getCyclesLostDueL2CacheMisses(*sstate1, *sstate2);
if (!(m->memoryTrafficMetricsAvailable()))
cout << " N/A N/A";
else
cout << " " << getBytesReadFromMC(*sstate1, *sstate2) / double(1024ULL * 1024ULL * 1024ULL) <<
" " << getBytesWrittenToMC(*sstate1, *sstate2) / double(1024ULL * 1024ULL * 1024ULL);
cout << " N/A\n";
}
else
cout << " TOTAL * " << getExecUsage(*sstate1, *sstate2) <<
" " << getIPC(*sstate1, *sstate2) <<
" " << getRelativeFrequency(*sstate1, *sstate2) <<
" " << unit_format(getL2CacheMisses(*sstate1, *sstate2)) <<
" " << getL2CacheHitRatio(*sstate1, *sstate2) <<
" N/A\n";
}
int ipcm_init(){
//struct CSysCounterState *ret;
#ifdef PCM_FORCE_SILENT
streambuf *oldout, *olderr;
null_stream nullStream1, nullStream2;
oldout=std::cout.rdbuf();
olderr=std::cerr.rdbuf();
std::cout.rdbuf(&nullStream1);
std::cerr.rdbuf(&nullStream2);
#endif
#ifdef OK_WIN_BUILD
// Increase the priority a bit to improve context switching delays on Windows
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
char driverPath[1040]; // length for current directory + "\\msr.sys"
//TCHAR driverPath[1040]; // length for current directory + "\\msr.sys"
GetCurrentDirectory(1024, driverPath);
strncat(driverPath,"\\msr.sys",1040);
//strcat_s(driverPath, 1040, "\\msr.sys");
//wcscat_s(driverPath, 1040, L"\\msr.sys");
SetConsoleCtrlHandler((PHANDLER_ROUTINE)cleanup, TRUE);
#else
/*
signal(SIGPIPE, cleanup);
signal(SIGINT, cleanup);
signal(SIGKILL, cleanup);
signal(SIGTERM, cleanup);
*/
#endif
// interesting start
int tryagain=0;
PCM * m = PCM::getInstance();
//if(disable_JKT_workaround) m->disableJKTWorkaround();
PCM::ErrorCode status = m->program();
PCM::ErrorCode secondstatus;
switch (status)
{
case PCM::Success:
break;
case PCM::MSRAccessDenied:
cerr << "Access to Intel(r) Performance Counter Monitor has denied (no MSR or PCI CFG space access)." << endl;
return 0;
case PCM::PMUBusy:
cerr << "Access to Intel(r) Performance Counter Monitor has denied (Performance Monitoring Unit is occupied by other application). Try to stop the application that uses PMU." << endl;
cerr << "Alternatively you can try to reset PMU configuration at your own risk. Try to reset? (y/n)" << endl;
//char yn;
//std::cin >> yn;
//if ('y' == yn)
//{
m->resetPMU();
cout << "PMU configuration has been reset. Try to rerun the program again." << endl;
//}
//return 0;
m = PCM::getInstance();
secondstatus=m->program();
if(secondstatus!=PCM::Success)
return 0;
break;
default:
cerr << "Access to Intel(r) Performance Counter Monitor has denied (Unknown error)." << endl;
return 0;
}
//global_state=(struct CSysCounterState*)malloc(sizeof(*ret));
global_state.m=m;
global_cpu_model=m->getCPUModel();
global_nominal_frequency=m->getNominalFrequency();
global_max_cpus=m->getNumCores();
#ifdef PCM_FORCE_SILENT
std::cout.rdbuf(oldout);
std::cerr.rdbuf(olderr);
#endif
return 1;
}
void ipcm_get_events(){
std::vector<CoreCounterState> cstates1, cstates2;
std::vector<SocketCounterState> sktstate1, sktstate2;
//SystemCounterState sstate1, sstate2;
uint64 TimeAfterSleep = 0;
global_state.m->getAllCounterStates(global_state.start, sktstate1, cstates1);
//return ret;
}
void ipcm_end_events(ipcm_event_val_t *values, const int num){
std::vector<CoreCounterState> cstates1, cstates2;
std::vector<SocketCounterState> sktstate1, sktstate2;
//struct CSysCounterState *sa=(struct CSysCounterState*)state;
global_state.m->getAllCounterStates(global_state.end, sktstate2, cstates2);
//print_diff(sa->m,&sa->start,&sa->end,sa->cpu_model);
set_diff_vals(global_state.m,&global_state.start,&global_state.end,global_state.cpu_model,values,num);
//free(state);
}
| 28.069959
| 186
| 0.702536
|
wrathematics
|
b74866f1493fc08fac3da9777ba9f8d85878cc8b
| 1,787
|
cpp
|
C++
|
code-forces/Educational 89/D.cpp
|
ErickJoestar/competitive-programming
|
76afb766dbc18e16315559c863fbff19a955a569
|
[
"MIT"
] | 1
|
2020-04-23T00:35:38.000Z
|
2020-04-23T00:35:38.000Z
|
code-forces/Educational 89/D.cpp
|
ErickJoestar/competitive-programming
|
76afb766dbc18e16315559c863fbff19a955a569
|
[
"MIT"
] | null | null | null |
code-forces/Educational 89/D.cpp
|
ErickJoestar/competitive-programming
|
76afb766dbc18e16315559c863fbff19a955a569
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define ENDL '\n'
#define deb(u) cout << #u " : " << (u) << ENDL;
#define deba(alias, u) cout << alias << ": " << (u) << ENDL;
#define debp(u, v) cout << u << " : " << v << ENDL;
#define pb push_back
#define F first
#define S second
#define lli long long
#define pii pair<int, int>
#define pll pair<lli, lli>
#define ALL(a) (a).begin(), (a).end()
#define ALLR(a) (a).rbegin(), (a).rend()
#define FOR(i, a, n) for (int i = (a); i < (n); ++i)
#define FORN(i, a, n) for (int i = (a - 1); i >= n; --i)
#define IO \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
using namespace std;
#define INF 10000020LL
vector<int> d(INF, -1);
void criba()
{
for (lli i = 2; i < INF; i++)
{
if (d[i] == -1)
{
d[i] = i;
for (lli j = 2; (j * i) < INF; j++)
{
d[j * i] = d[j * i] == -1 ? i : d[j * i];
}
}
}
}
int main()
{
IO;
int n;
cin >> n;
vector<int> v(n);
FOR(i, 0, n)
cin >> v[i];
criba();
vector<pii> ans;
for (auto u : v)
{
map<int, int> m;
if (u == d[u])
{
ans.pb({-1, -1});
continue;
}
int copy = u;
while (copy != 1)
{
m[d[copy]]++;
copy /= d[copy];
}
if (m.size() == 1)
{
ans.pb({-1, -1});
continue;
}
else
{
int a = u / d[u], b = d[u];
// debp(a, b);
// deb(__gcd(u, a + b));
while (__gcd(u, (a + b)) != 1 && a > 1 && b > 1)
{
b *= d[a];
a = a / d[a];
}
if (a > 1 && b > 1)
ans.pb({a, b});
else
ans.pb({-1, -1});
}
}
for (auto e : ans)
{
cout << e.F << " ";
}
cout << ENDL;
for (auto e : ans)
{
cout << e.S << " ";
}
return 0;
}
| 18.42268
| 60
| 0.404589
|
ErickJoestar
|
b748e30bcef883d86729495dfe82623b2538f6df
| 3,006
|
cpp
|
C++
|
Strings/Knuth-Morris-Pratt.cpp
|
Rand0mUsername/Algorithms
|
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
|
[
"MIT"
] | 2
|
2020-01-10T14:12:03.000Z
|
2020-05-28T19:12:21.000Z
|
Strings/Knuth-Morris-Pratt.cpp
|
Rand0mUsername/algorithms
|
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
|
[
"MIT"
] | null | null | null |
Strings/Knuth-Morris-Pratt.cpp
|
Rand0mUsername/algorithms
|
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
|
[
"MIT"
] | 1
|
2022-01-11T03:14:48.000Z
|
2022-01-11T03:14:48.000Z
|
// RandomUsername (Nikola Jovanovic)
// Knuth-Morris-Pratt (KMP)
// String matching: O( N + M )
// N - word length, M - text length
#include <bits/stdc++.h>
#define DBG false
#define debug(x) if(DBG) printf("(ln %d) %s = %d\n", __LINE__, #x, x);
#define lld long long
#define ff(i,a,b) for(int i=a; i<=b; i++)
#define fb(i,a,b) for(int i=a; i>=b; i--)
#define par pair<int, int>
#define fi first
#define se second
#define mid (l+r)/2
#define INF 1000000000
#define MAXLEN 100005
using namespace std;
/*
Useful tutorial: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=stringSearching
Failure function f[i] := the length of the longest proper suffix=prefix for string w[ 0 ]..w[ i-1 ] (string of length i)
If we align t[j] and w[i] and fail to match a character, we should try to match w[f[i]] and t[j]
We move our word to the right skipping all the unnecessary comparations
f[f[i]] is the second "best" prefix=suffix (best prefix=suffix of the best prefix=suffix )
*/
// Text and text length, word and word length
// Searching for word in text
char t[MAXLEN];
int tl;
char w[MAXLEN];
int wl;
// Matches will be stored here
vector<int> matches;
// Failure function
int F[MAXLEN];
// KMP
void KMP()
{
// Computing the faliure function
int i, j;
// Base cases
F[0] = F[1] = 0;
// Computing F[i]
for(i = 2; i <= wl; i++)
{
// Expanding the solution for i-1 is our best guess for F[i]
j = F[i-1];
while(1)
{
// If w[j] and w[i-1] match, we expand, F[i] is found, break
if(w[j] == w[i-1]) { F[i] = j + 1; break; }
// If we failed to expand an empty string, we have to quit trying, F[i] is zero, break
if(j == 0) { F[i] = 0; break; }
// Otherwise we just try expanding the next best match
j = F[j];
}
}
// Doing the actual matching
// i - word iterator, j - text iterator
i = j = 0;
while(1)
{
// We reached the end of the text
if(j == tl) break;
// We are trying to match t[j] and w[i]
if(t[j] == w[i])
{
// If they match, move on
i++, j++;
// We reached the end of the word, we found a full match!
if(i == wl)
{
// The match starts at t[j-wl]
matches.push_back(j - wl);
// The next possible match
i = F[i];
}
}
// If they do not match, try the next possible match for t[j]
else if(i > 0) i = F[i];
// If i=0 failed to match there are no more possible matches for t[j], move on
else j++;
}
}
// Testing
// Test problem: http://www.spoj.com/problems/NHAY/
int main()
{
scanf("%s", t);
scanf("%s", w);
tl = strlen(t);
wl = strlen(w);
KMP();
printf("Matches:\n");
for(int i = 0; i < matches.size(); i++)
printf("%d ", matches[i]);
return 0;
}
| 27.833333
| 124
| 0.549235
|
Rand0mUsername
|
b75917a6a569ffb4ca4d4912db8ab9ae7ef4d253
| 1,341
|
hpp
|
C++
|
include/context.hpp
|
chGoodchild/powerloader
|
11b48413d0b3fb953430666153caf95e68158e4d
|
[
"BSD-3-Clause"
] | null | null | null |
include/context.hpp
|
chGoodchild/powerloader
|
11b48413d0b3fb953430666153caf95e68158e4d
|
[
"BSD-3-Clause"
] | null | null | null |
include/context.hpp
|
chGoodchild/powerloader
|
11b48413d0b3fb953430666153caf95e68158e4d
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <vector>
#include <string>
#include <chrono>
#include <map>
#ifdef WITH_ZCHUNK
extern "C"
{
#include <zck.h>
}
#endif
#include "mirror.hpp"
namespace powerloader
{
class Context
{
public:
bool offline = false;
int verbosity = 0;
bool adaptive_mirror_sorting = true;
bool disable_ssl = false;
long connect_timeout = 30L;
long low_speed_time = 30L;
long low_speed_limit = 1000L;
bool ftp_use_seepsv = true;
fs::path cache_dir;
std::size_t retry_backoff_factor = 2;
std::size_t max_resume_count = 3;
std::chrono::steady_clock::duration retry_default_timeout = std::chrono::seconds(2);
std::map<std::string, std::vector<std::shared_ptr<Mirror>>> mirror_map;
std::vector<std::string> additional_httpheaders;
static Context& instance();
inline void set_verbosity(int v)
{
verbosity = v;
if (v > 0)
{
#ifdef WITH_ZCHUNK
zck_set_log_level(ZCK_LOG_DEBUG);
#endif
spdlog::set_level(spdlog::level::debug);
}
else
{
spdlog::set_level(spdlog::level::warn);
}
}
private:
Context();
~Context() = default;
};
}
| 20.630769
| 92
| 0.56525
|
chGoodchild
|
b75f589c332ceafcdedd5da03c1a1f8acd656f28
| 3,974
|
cpp
|
C++
|
ad_map_access/impl/tests/generated/ad/map/landmark/TrafficLightTypeValidInputRangeTests.cpp
|
seowwj/map
|
2afacd50e1b732395c64b1884ccfaeeca0040ee7
|
[
"MIT"
] | null | null | null |
ad_map_access/impl/tests/generated/ad/map/landmark/TrafficLightTypeValidInputRangeTests.cpp
|
seowwj/map
|
2afacd50e1b732395c64b1884ccfaeeca0040ee7
|
[
"MIT"
] | null | null | null |
ad_map_access/impl/tests/generated/ad/map/landmark/TrafficLightTypeValidInputRangeTests.cpp
|
seowwj/map
|
2afacd50e1b732395c64b1884ccfaeeca0040ee7
|
[
"MIT"
] | 1
|
2020-10-27T11:09:30.000Z
|
2020-10-27T11:09:30.000Z
|
/*
* ----------------- BEGIN LICENSE BLOCK ---------------------------------
*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
* ----------------- END LICENSE BLOCK -----------------------------------
*/
/*
* Generated file
*/
#include <gtest/gtest.h>
#include <limits>
#include "ad/map/landmark/TrafficLightTypeValidInputRange.hpp"
TEST(TrafficLightTypeValidInputRangeTests, testValidInputRangeValid)
{
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::INVALID));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::UNKNOWN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::LEFT_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::RIGHT_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::STRAIGHT_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::LEFT_STRAIGHT_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::RIGHT_STRAIGHT_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_RED_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_RED_YELLOW_GREEN));
ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_YELLOW_GREEN));
}
TEST(TrafficLightTypeValidInputRangeTests, testValidInputRangeInvalid)
{
int32_t minValue = std::numeric_limits<int32_t>::max();
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::INVALID));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::UNKNOWN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW_GREEN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::LEFT_RED_YELLOW_GREEN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::RIGHT_RED_YELLOW_GREEN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::STRAIGHT_RED_YELLOW_GREEN));
minValue
= std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::LEFT_STRAIGHT_RED_YELLOW_GREEN));
minValue
= std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::RIGHT_STRAIGHT_RED_YELLOW_GREEN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_GREEN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_RED_GREEN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_GREEN));
minValue
= std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_YELLOW_GREEN));
minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_RED_YELLOW_GREEN));
minValue
= std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_YELLOW_GREEN));
ASSERT_FALSE(withinValidInputRange(static_cast<::ad::map::landmark::TrafficLightType>(minValue - 1)));
}
| 60.212121
| 120
| 0.762959
|
seowwj
|
b75fb5c1b8a68b30c3c076bc8e577ca19d64ab25
| 5,354
|
cpp
|
C++
|
src/game/shared/tf/tf_projectile_nail.cpp
|
Xen-alpha/UltraFortress
|
3c2e0cbb5c6d1efe362619cd3fb94bac9067f913
|
[
"Unlicense"
] | null | null | null |
src/game/shared/tf/tf_projectile_nail.cpp
|
Xen-alpha/UltraFortress
|
3c2e0cbb5c6d1efe362619cd3fb94bac9067f913
|
[
"Unlicense"
] | null | null | null |
src/game/shared/tf/tf_projectile_nail.cpp
|
Xen-alpha/UltraFortress
|
3c2e0cbb5c6d1efe362619cd3fb94bac9067f913
|
[
"Unlicense"
] | null | null | null |
//====== Copyright ?1996-2005, Valve Corporation, All rights reserved. =======
//
// TF Nail
//
//=============================================================================
#include "cbase.h"
#include "tf_projectile_nail.h"
#include "tf_gamerules.h"
#ifdef CLIENT_DLL
#include "c_basetempentity.h"
#include "c_te_legacytempents.h"
#include "c_te_effect_dispatch.h"
#include "input.h"
#include "c_tf_player.h"
#include "cliententitylist.h"
#endif
#define NAIL_MODEL "models/weapons/w_models/w_nail.mdl"
#define NAIL_DISPATCH_EFFECT "ClientProjectile_Syringe"
#define NAIL_GRAVITY 0.2f
LINK_ENTITY_TO_CLASS(tf_projectile_nail, CTFProjectile_Nail);
PRECACHE_REGISTER(tf_projectile_nail);
short g_sModelIndexNail;
void PrecacheNail(void *pUser)
{
g_sModelIndexNail = modelinfo->GetModelIndex(NAIL_MODEL);
}
PRECACHE_REGISTER_FN(PrecacheNail);
CTFProjectile_Nail::CTFProjectile_Nail()
{
}
CTFProjectile_Nail::~CTFProjectile_Nail()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFProjectile_Nail *CTFProjectile_Nail::Create(const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner, CBaseEntity *pScorer, bool bCritical)
{
return static_cast<CTFProjectile_Nail*>(CTFBaseProjectile::Create("tf_projectile_nail", vecOrigin, vecAngles, pOwner, CTFProjectile_Nail::GetInitialVelocity(), g_sModelIndexNail, NAIL_DISPATCH_EFFECT, pScorer, bCritical));
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CTFProjectile_Nail::GetProjectileModelName(void)
{
return NAIL_MODEL;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CTFProjectile_Nail::GetGravity(void)
{
return NAIL_GRAVITY;
}
//=============================================================================
//
// TF Syringe Projectile functions (Server specific).
//
#define SYRINGE_MODEL "models/weapons/w_models/w_syringe_proj.mdl"
#define SYRINGE_DISPATCH_EFFECT "ClientProjectile_Syringe"
#define SYRINGE_GRAVITY 0.3f
LINK_ENTITY_TO_CLASS( tf_projectile_syringe, CTFProjectile_Syringe );
PRECACHE_REGISTER( tf_projectile_syringe );
short g_sModelIndexSyringe;
void PrecacheSyringe(void *pUser)
{
g_sModelIndexSyringe = modelinfo->GetModelIndex( SYRINGE_MODEL );
}
PRECACHE_REGISTER_FN(PrecacheSyringe);
CTFProjectile_Syringe::CTFProjectile_Syringe()
{
}
CTFProjectile_Syringe::~CTFProjectile_Syringe()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFProjectile_Syringe *CTFProjectile_Syringe::Create( const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner, CBaseEntity *pScorer, bool bCritical )
{
return static_cast<CTFProjectile_Syringe*>( CTFBaseProjectile::Create( "tf_projectile_syringe", vecOrigin, vecAngles, pOwner, CTFProjectile_Syringe::GetInitialVelocity(), g_sModelIndexSyringe, SYRINGE_DISPATCH_EFFECT, pScorer, bCritical ) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CTFProjectile_Syringe::GetProjectileModelName( void )
{
return SYRINGE_MODEL;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CTFProjectile_Syringe::GetGravity( void )
{
return SYRINGE_GRAVITY;
}
#ifdef CLIENT_DLL
//-----------------------------------------------------------------------------
// Purpose:
// Output : const char
//-----------------------------------------------------------------------------
const char *GetSyringeTrailParticleName( int iTeamNumber, bool bCritical )
{
const char *pszFormat = bCritical ? "nailtrails_medic_%s_crit" : "nailtrails_medic_%s";
return ConstructTeamParticle( pszFormat, iTeamNumber, true );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ClientsideProjectileSyringeCallback( const CEffectData &data )
{
// Get the syringe and add it to the client entity list, so we can attach a particle system to it.
C_TFPlayer *pPlayer = dynamic_cast<C_TFPlayer*>( ClientEntityList().GetBaseEntityFromHandle( data.m_hEntity ) );
if ( pPlayer )
{
C_LocalTempEntity *pSyringe = ClientsideProjectileCallback( data, SYRINGE_GRAVITY );
if ( pSyringe )
{
switch (pPlayer->GetTeamNumber())
{
case TF_TEAM_RED:
pSyringe->m_nSkin = 0;
break;
case TF_TEAM_BLUE:
pSyringe->m_nSkin = 1;
break;
}
bool bCritical = ( ( data.m_nDamageType & DMG_CRITICAL ) != 0 );
pSyringe->AddParticleEffect(GetSyringeTrailParticleName(pPlayer->GetTeamNumber(), bCritical));
pSyringe->AddEffects( EF_NOSHADOW );
pSyringe->flags |= FTENT_USEFASTCOLLISIONS;
}
}
}
DECLARE_CLIENT_EFFECT( SYRINGE_DISPATCH_EFFECT, ClientsideProjectileSyringeCallback );
#endif
| 33.049383
| 242
| 0.570601
|
Xen-alpha
|
b7628b6db5bf6f1739d9cb6fbc5b3fce98b7e3dd
| 585
|
cpp
|
C++
|
C++/Strings/StringStream/Solution.cpp
|
iamnambiar/HackerRank-Solutions
|
6fdcab79b18e66a6d7278b979a8be087f8f6c696
|
[
"MIT"
] | 2
|
2020-04-06T10:32:08.000Z
|
2021-04-23T04:32:45.000Z
|
C++/Strings/StringStream/Solution.cpp
|
iamnambiar/HackerRank-Solutions
|
6fdcab79b18e66a6d7278b979a8be087f8f6c696
|
[
"MIT"
] | null | null | null |
C++/Strings/StringStream/Solution.cpp
|
iamnambiar/HackerRank-Solutions
|
6fdcab79b18e66a6d7278b979a8be087f8f6c696
|
[
"MIT"
] | null | null | null |
// https://www.hackerrank.com/challenges/c-tutorial-stringstream/problem
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
// Complete this function
stringstream ss(str);
vector<int> vect;
int num;
while(ss>>num) {
vect.push_back(num);
char ch;
ss>>ch;
}
return vect;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
| 18.870968
| 72
| 0.582906
|
iamnambiar
|
b762e751d7391c15134c15de56bc730b88fb99d7
| 737
|
cpp
|
C++
|
src/dsm_to_dtm.cpp
|
pierriko/clara
|
3b0f788f5d120ca4be8a1ae5ab65c7c4d811a49d
|
[
"BSD-3-Clause"
] | 1
|
2015-04-23T02:21:11.000Z
|
2015-04-23T02:21:11.000Z
|
src/dsm_to_dtm.cpp
|
pierriko/clara
|
3b0f788f5d120ca4be8a1ae5ab65c7c4d811a49d
|
[
"BSD-3-Clause"
] | null | null | null |
src/dsm_to_dtm.cpp
|
pierriko/clara
|
3b0f788f5d120ca4be8a1ae5ab65c7c4d811a49d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* region.cpp
*
* Common LAAS Raster library
*
* author: Pierrick Koch <pierrick.koch@laas.fr>
* created: 2013-06-12
* license: BSD
*/
#include <string> // for string
#include <stdexcept> // for runtime_error
#include <cstdlib> // exit status
#include <cmath>
#include "gdalwrap/gdal.hpp"
int main(int argc, char * argv[])
{
std::cout<<"Common LAAS Raster library"<<std::endl;
if (argc < 3) {
std::cerr<<"usage: "<<argv[0]<<" dsm.dtm dtm.tif"<<std::endl;
return EXIT_FAILURE;
}
gdalwrap::gdal dsm(argv[1]);
dsm.names = {"Z_MAX", "N_POINTS"};
dsm.bands.push_back(gdalwrap::raster(dsm.bands[0].size(), 1));
dsm.save(argv[2]);
return EXIT_SUCCESS;
}
| 22.333333
| 69
| 0.598372
|
pierriko
|
b766226e90bd1d9a173a974a1d869d1f0a82f44b
| 391
|
cpp
|
C++
|
AtCoder/abc207/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
AtCoder/abc207/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | 1
|
2021-10-19T08:47:23.000Z
|
2022-03-07T05:23:56.000Z
|
AtCoder/abc207/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
long long int a, b, c, d; cin >> a >> b >> c >> d;
long long int x = a, y = 0;
for (int i = 1; i <= a; i++) {
x += b, y += c;
if (x <= d * y) {
cout << i << endl;
return 0;
}
}
cout << -1 << endl;
return 0;
}
| 20.578947
| 54
| 0.432225
|
H-Tatsuhiro
|
b768d9ae87f1069a6b2fa493f74aa314abdf0a08
| 5,032
|
cpp
|
C++
|
scope_onboard_st4.cpp
|
iphantomsky/open-phd-guiding
|
41f6f277cd2a2efd25dc198eae3206cf95102608
|
[
"BSD-3-Clause"
] | null | null | null |
scope_onboard_st4.cpp
|
iphantomsky/open-phd-guiding
|
41f6f277cd2a2efd25dc198eae3206cf95102608
|
[
"BSD-3-Clause"
] | null | null | null |
scope_onboard_st4.cpp
|
iphantomsky/open-phd-guiding
|
41f6f277cd2a2efd25dc198eae3206cf95102608
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* scope_onboard_st4.cpp
* PHD Guiding
*
* Created by Bret McKee
* Copyright (c) 2012 Bret McKee
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of Bret McKee, Dad Dog Development,
* Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#include "scope_onboard_st4.h"
ScopeOnboardST4::ScopeOnboardST4(void)
{
m_pOnboardHost = NULL;
}
ScopeOnboardST4::~ScopeOnboardST4(void)
{
if (IsConnected())
{
Disconnect();
}
m_pOnboardHost = NULL;
}
bool ScopeOnboardST4::ConnectOnboardST4(OnboardST4 *pOnboardHost)
{
bool bError = false;
try
{
if (!pOnboardHost)
{
throw ERROR_INFO("Attempt to Connect OnboardST4 mount with pOnboardHost == NULL");
}
m_pOnboardHost = pOnboardHost;
if (IsConnected())
{
Disconnect();
}
if (!m_pOnboardHost->ST4HasGuideOutput())
{
throw ERROR_INFO("Attempt to Connect Onboard ST4 mount when host does not have guide output");
}
if (!m_pOnboardHost->ST4HostConnected())
{
throw ERROR_INFO("Attempt to Connect Onboard ST4 mount when host is not connected");
}
Scope::Connect();
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool ScopeOnboardST4::Disconnect(void)
{
bool bError = false;
try
{
if (!IsConnected())
{
throw ERROR_INFO("Attempt to Disconnect On Camera mount when not connected");
}
assert(m_pOnboardHost);
m_pOnboardHost = NULL;
bError = Scope::Disconnect();
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
Mount::MOVE_RESULT ScopeOnboardST4::Guide(GUIDE_DIRECTION direction, int duration)
{
MOVE_RESULT result = MOVE_OK;
try
{
if (!IsConnected())
{
throw ERROR_INFO("Attempt to Guide On Camera mount when not connected");
}
if (!m_pOnboardHost)
{
throw ERROR_INFO("Attempt to Guide OnboardST4 mount when m_pOnboardHost == NULL");
}
if (!m_pOnboardHost->ST4HostConnected())
{
throw ERROR_INFO("Attempt to Guide On Camera mount when camera is not connected");
}
if (m_pOnboardHost->ST4PulseGuideScope(direction,duration))
{
result = MOVE_ERROR;
}
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
result = MOVE_ERROR;
}
return result;
}
bool ScopeOnboardST4::HasNonGuiMove(void)
{
bool bReturn = false;
try
{
if (!IsConnected())
{
throw ERROR_INFO("Attempt to HasNonGuiMove On Camera mount when not connected");
}
if (!m_pOnboardHost->ST4HostConnected())
{
throw ERROR_INFO("Attempt to HasNonGuiMove On Camera mount when camera is not connected");
}
if (!m_pOnboardHost)
{
throw ERROR_INFO("Attempt HasNonGuiMove OnboardST4 mount when m_pOnboardHost == NULL");
}
bReturn = m_pOnboardHost->ST4HasNonGuiMove();
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
}
return bReturn;
}
| 27.497268
| 107
| 0.618641
|
iphantomsky
|
b768f8c2923c44ca69840774707ed8be76aeb06a
| 487
|
hpp
|
C++
|
Siv3D/src/Siv3D/Webcam/CWebcam.hpp
|
Fuyutsubaki/OpenSiv3D
|
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
|
[
"MIT"
] | null | null | null |
Siv3D/src/Siv3D/Webcam/CWebcam.hpp
|
Fuyutsubaki/OpenSiv3D
|
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
|
[
"MIT"
] | null | null | null |
Siv3D/src/Siv3D/Webcam/CWebcam.hpp
|
Fuyutsubaki/OpenSiv3D
|
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
|
[
"MIT"
] | null | null | null |
//-----------------------------------------------
//
// 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 "IWebcam.hpp"
# include <Siv3D/Webcam.hpp>
namespace s3d
{
class CWebcam : public ISiv3DWebcam
{
private:
public:
CWebcam();
~CWebcam() override;
bool init() override;
};
}
| 15.709677
| 50
| 0.529774
|
Fuyutsubaki
|
b76a4bfae5704831e9f9e2867814a38e3cd6abd1
| 5,486
|
cpp
|
C++
|
src/main.cpp
|
ilyayunkin/StocksMonitor
|
92ba47fa4e92e9dab498ea6751178ef823a83bbc
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
ilyayunkin/StocksMonitor
|
92ba47fa4e92e9dab498ea6751178ef823a83bbc
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
ilyayunkin/StocksMonitor
|
92ba47fa4e92e9dab498ea6751178ef823a83bbc
|
[
"MIT"
] | 1
|
2020-12-04T08:18:21.000Z
|
2020-12-04T08:18:21.000Z
|
#include "WidgetsUi/mainwindow.h"
#include <QApplication>
#include <QDir>
#include <QDebug>
#include <QMessageBox>
#include <vector>
#include "logger.h"
#include "ExceptionClasses.h"
#include "WidgetsUi/Dialogs.h"
#include "WidgetsUi/Notifier.h"
#include "WidgetsUi/Sounds/Signalizer.h"
#include "Application/PluginsLoader.h"
#include "Application/Market.h"
#include "Application/CurrencyConverter.h"
#include "Application/CurrencyCourseSource.h"
#include "Application/Browser.h"
#include "Application/StatisticsCsvSaver.h"
#include "Application/StatisticsConfigDatabase.h"
#include "Application/PortfolioDatabase.h"
#include "Application/Controllers/StatisticsController.h"
#include "Application/Controllers/ProcessStatisticsController.h"
#include "Application/PortfolioInterface.h"
#include "Application/StatisticsConfigDatabase.h"
#include "Rules/Portfolio.h"
#include "Rules/ProcessStatisticsInteractor.h"
#include "Rules/StatisticsInteractor.h"
#include "Rules/AddToPortfolioInteractor.h"
#include "Rules/UpdatePortfolioFromStocksInteractor.h"
#include "Rules/OpenUrlInteractor.h"
#include "Rules/ChainOfStocksProcessing/DummyNode.h"
typedef std::vector<std::unique_ptr<Market>> MarketsList;
MarketsList createMarkets(AbstractDialogs &dialogs)
{
MarketsList list;
auto plugins = PluginsLoader::loadPlugins();
list.reserve(plugins.size());
for(auto &p : plugins){
list.push_back(std::make_unique<Market>(&dialogs, *p));
}
return list;
}
StocksInterfacesList createStocksInterfacesList(MarketsList &markets)
{
StocksInterfacesList list;
list.reserve(markets.size());
for(auto &market : markets){
list.push_back(&*market);
}
return list;
}
CurrencyConverter createCurrencyConverter(const MarketsList &markets, const Dialogs &dialogs)
{
auto getCurrencySourceInterface = [&]{
auto cbrfInterfaceIterator = std::find_if(markets.begin(), markets.end(),
[](const auto &interface){return interface->getPluginName() == PluginName("CBRF-Currency");});
if(cbrfInterfaceIterator != markets.end())
return new CurrencyCourseSource(**cbrfInterfaceIterator);
return static_cast<CurrencyCourseSource *>(nullptr);
};
return CurrencyConverter (CurrencyCode("RUB"), dialogs, getCurrencySourceInterface());
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setOrganizationName("Ilya");
a.setApplicationName("StocksMonitor");
int ret = -1;
try
{
Logger::instance().log("The program is started");
Dialogs dialogs;
auto markets = createMarkets(dialogs);
auto stocksInterfacesList = createStocksInterfacesList(markets);
CurrencyConverter currencyConverter = createCurrencyConverter(markets, dialogs);
Portfolio portfolio(std::make_unique<PortfolioDatabase>());
PortfolioInterface portfolioInterface(
portfolio,
stocksInterfacesList,
currencyConverter);
StatisticsCsvSaver csvSaver;
StatisticsConfigList statisticsConfigList;
ProcessStatisticsInteractor processStatisticsInteractor(statisticsConfigList, currencyConverter);
StatisticsInteractor statisticsInteractor(std::make_unique<StatisticsConfigDatabase>(), statisticsConfigList, dialogs);
StatisticsController statisticsController(statisticsInteractor);
ProcessStatisticsController processStatisticsController(
portfolio, processStatisticsInteractor, csvSaver);
MainWindow w;
Browser browser;
AddToPortfolioInteractor addToPortfolioInteractor(portfolio, stocksInterfacesList, dialogs);
UpdatePortfolioFromStocksInteractor updatePortfolioFromStocksInteractor(portfolio, stocksInterfacesList, dialogs);
OpenUrlInteractor openUrlInteractor(stocksInterfacesList, browser);
StocksProcessing::DummyNode processingHeadDummy;
for(auto &m : markets){
StocksProcessing::connect(&*m, &processingHeadDummy);
}
StocksProcessing::connect(&portfolioInterface,
&processingHeadDummy,
&addToPortfolioInteractor,
&updatePortfolioFromStocksInteractor,
&openUrlInteractor,
w.getNotifier());
for(auto &m : markets){
w.addTab(*m, *m);
}
w.addTab(portfolioInterface);
w.addTab(processStatisticsController, statisticsController, stocksInterfacesList);
w.showMaximized();
dialogs.setMainWindow(&w);
ret = a.exec();
}catch(std::runtime_error &e)
{
Logger::instance().log(e.what());
QMessageBox::critical(nullptr, QObject::tr("Critical error"),
QObject::tr("Application will be closed: %1"
"\nCheck the log file.").arg(e.what()));
std::terminate();
}catch (...)
{
Logger::instance().log("Undefined exception");
QMessageBox::critical(nullptr, QObject::tr("Critical error"),
QObject::tr("Application will be closed: "
"Undefined exception"
"\nCheck the log file."));
std::terminate();
}
return ret;
}
| 37.319728
| 144
| 0.666788
|
ilyayunkin
|
b76b38b2e3b3456212205a2de6e37d6c993eff79
| 1,796
|
cpp
|
C++
|
Treap (Cartesian Tree)/Treap.cpp
|
yokeshrana/Fast_Algorithms_in_Data_Structures
|
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
|
[
"MIT"
] | null | null | null |
Treap (Cartesian Tree)/Treap.cpp
|
yokeshrana/Fast_Algorithms_in_Data_Structures
|
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
|
[
"MIT"
] | null | null | null |
Treap (Cartesian Tree)/Treap.cpp
|
yokeshrana/Fast_Algorithms_in_Data_Structures
|
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
|
[
"MIT"
] | 1
|
2021-06-23T04:48:59.000Z
|
2021-06-23T04:48:59.000Z
|
// github.com/andy489
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
struct item {
int key, prior;
item *l, *r;
int cnt = 0;
item(int key, int prior) : key(key), prior(prior), l(nullptr), r(nullptr) {};
};
typedef item *pitem;
int cnt(pitem t) {
return t ? t->cnt : 0;
}
void upd_cnt(pitem t) {
if (t)
t->cnt = 1 + cnt(t->l) + cnt(t->r);
}
void heapify(pitem t) {
if (!t) return;
pitem max = t;
if (t->l != nullptr && t->l->prior > max->prior)
max = t->l;
if (t->r != nullptr && t->r->prior > max->prior)
max = t->r;
if (max != t) {
swap(t->prior, max->prior);
heapify(max);
}
}
pitem build(int *a, int n) {
/// Construct a treap on values {a[0], a[1], ..., a[n-1]}
if (n == 0) return nullptr;
int mid = n >> 1;
pitem t = new item(a[mid], rand() % 300);
t->l = build(a, mid);
t->r = build(a + mid + 1, n - mid - 1);
heapify(t);
upd_cnt(t);
return t;
}
void dfs(pitem t) {
if (!t)
return;
dfs(t->l);
printf("%d %d, ", t->key, t->prior);
dfs(t->r);
}
#include <queue>
void bfs(pitem t) {
queue<pitem> Q;
Q.push(t);
int SZ;
while (!Q.empty()) {
SZ = Q.size();
while (SZ--) {
pitem curr = Q.front();
Q.pop();
printf("%d %d, ", curr->key, curr->prior);
if (curr->l)
Q.push(curr->l);
if (curr->r)
Q.push(curr->r);
}
printf("\n");
}
}
int main() {
srand(time(nullptr));
int a[] = {2, 4, 8, 3, 6, 22, 9, 1};
int n = sizeof a / sizeof(int);
pitem treap = build(a, n);
dfs(treap);
printf("\n\n");
bfs(treap);
return 0;
}
| 19.521739
| 81
| 0.465479
|
yokeshrana
|
b770222dc888eba5d4a8dadd20d596b2b4c0a7a8
| 8,995
|
cc
|
C++
|
tests/libtests/materials/data/obsolete/DruckerPrager3DElasticData.cc
|
Grant-Block/pylith
|
f6338261b17551eba879da998a5aaf2d91f5f658
|
[
"MIT"
] | 93
|
2015-01-08T16:41:22.000Z
|
2022-02-25T13:40:02.000Z
|
tests/libtests/materials/data/obsolete/DruckerPrager3DElasticData.cc
|
Grant-Block/pylith
|
f6338261b17551eba879da998a5aaf2d91f5f658
|
[
"MIT"
] | 277
|
2015-02-20T16:27:35.000Z
|
2022-03-30T21:13:09.000Z
|
tests/libtests/materials/data/obsolete/DruckerPrager3DElasticData.cc
|
Grant-Block/pylith
|
f6338261b17551eba879da998a5aaf2d91f5f658
|
[
"MIT"
] | 71
|
2015-03-24T12:11:08.000Z
|
2022-03-03T04:26:02.000Z
|
// -*- 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.
//
// ======================================================================
//
// DO NOT EDIT THIS FILE
// This file was generated from python application druckerprager3delastic.
#include "DruckerPrager3DElasticData.hh"
const int pylith::materials::DruckerPrager3DElasticData::_dimension = 3;
const int pylith::materials::DruckerPrager3DElasticData::_numLocs = 2;
const int pylith::materials::DruckerPrager3DElasticData::_numProperties = 6;
const int pylith::materials::DruckerPrager3DElasticData::_numStateVars = 1;
const int pylith::materials::DruckerPrager3DElasticData::_numDBProperties = 6;
const int pylith::materials::DruckerPrager3DElasticData::_numDBStateVars = 6;
const int pylith::materials::DruckerPrager3DElasticData::_numPropsQuadPt = 6;
const int pylith::materials::DruckerPrager3DElasticData::_numVarsQuadPt = 6;
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_lengthScale = 1.00000000e+03;
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_timeScale = 1.00000000e+00;
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_pressureScale = 2.25000000e+10;
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_densityScale = 2.25000000e+04;
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dtStableImplicit = 1.00000000e+10;
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dtStableExplicit = 1.92450090e-01;
const int pylith::materials::DruckerPrager3DElasticData::_numPropertyValues[] = {
1,
1,
1,
1,
1,
1,
};
const int pylith::materials::DruckerPrager3DElasticData::_numStateVarValues[] = {
6,
};
const char* pylith::materials::DruckerPrager3DElasticData::_dbPropertyValues[] = {
"density",
"vs",
"vp",
"friction-angle",
"cohesion",
"dilatation-angle",
};
const char* pylith::materials::DruckerPrager3DElasticData::_dbStateVarValues[] = {
"plastic-strain-xx",
"plastic-strain-yy",
"plastic-strain-zz",
"plastic-strain-xy",
"plastic-strain-yz",
"plastic-strain-xz",
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dbProperties[] = {
2.50000000e+03,
3.00000000e+03,
5.19615242e+03,
5.23598776e-01,
3.00000000e+05,
3.49065850e-01,
2.00000000e+03,
1.20000000e+03,
2.07846097e+03,
4.36332313e-01,
1.00000000e+05,
4.36332313e-01,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dbStateVars[] = {
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_properties[] = {
2.50000000e+03,
2.25000000e+10,
2.25000000e+10,
2.30940108e-01,
3.60000000e+05,
1.48583084e-01,
2.00000000e+03,
2.88000000e+09,
2.88000000e+09,
1.89338478e-01,
1.21811303e+05,
1.89338478e-01,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stateVars[] = {
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_propertiesNondim[] = {
1.11111111e-01,
1.00000000e+00,
1.00000000e+00,
2.30940108e-01,
1.60000000e-05,
1.48583084e-01,
8.88888889e-02,
1.28000000e-01,
1.28000000e-01,
1.89338478e-01,
5.41383567e-06,
1.89338478e-01,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stateVarsNondim[] = {
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_density[] = {
2.50000000e+03,
2.00000000e+03,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_strain[] = {
-1.10000000e-04,
-1.20000000e-04,
-1.30000000e-04,
1.40000000e-04,
1.50000000e-04,
1.60000000e-04,
4.10000000e-04,
4.20000000e-04,
4.30000000e-04,
4.40000000e-04,
4.50000000e-04,
4.60000000e-04,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stress[] = {
-4.85790000e+07,
-4.94780000e+07,
-5.03770000e+07,
-8.97600000e+06,
-8.97500000e+06,
-8.97400000e+06,
-2.82900000e+06,
-2.82800000e+06,
-2.82700000e+06,
-1.09800000e+06,
-1.09700000e+06,
-1.09600000e+06,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_elasticConsts[] = {
6.75000000e+10,
2.25000000e+10,
2.25000000e+10,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
2.25000000e+10,
6.75000000e+10,
2.25000000e+10,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
2.25000000e+10,
2.25000000e+10,
6.75000000e+10,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
4.50000000e+10,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
4.50000000e+10,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
4.50000000e+10,
8.64000000e+09,
2.88000000e+09,
2.88000000e+09,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
2.88000000e+09,
8.64000000e+09,
2.88000000e+09,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
2.88000000e+09,
2.88000000e+09,
8.64000000e+09,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
5.76000000e+09,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
5.76000000e+09,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
5.76000000e+09,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_initialStress[] = {
2.10000000e+04,
2.20000000e+04,
2.30000000e+04,
2.40000000e+04,
2.50000000e+04,
2.60000000e+04,
5.10000000e+04,
5.20000000e+04,
5.30000000e+04,
5.40000000e+04,
5.50000000e+04,
5.60000000e+04,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_initialStrain[] = {
3.10000000e-04,
3.20000000e-04,
3.30000000e-04,
3.40000000e-04,
3.50000000e-04,
3.60000000e-04,
6.10000000e-04,
6.20000000e-04,
6.30000000e-04,
6.40000000e-04,
6.50000000e-04,
6.60000000e-04,
};
const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stateVarsUpdated[] = {
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
0.00000000e+00,
};
pylith::materials::DruckerPrager3DElasticData::DruckerPrager3DElasticData(void)
{ // constructor
dimension = _dimension;
numLocs = _numLocs;
numProperties = _numProperties;
numStateVars = _numStateVars;
numDBProperties = _numDBProperties;
numDBStateVars = _numDBStateVars;
numPropsQuadPt = _numPropsQuadPt;
numVarsQuadPt = _numVarsQuadPt;
lengthScale = _lengthScale;
timeScale = _timeScale;
pressureScale = _pressureScale;
densityScale = _densityScale;
dtStableImplicit = _dtStableImplicit;
dtStableExplicit = _dtStableExplicit;
numPropertyValues = const_cast<int*>(_numPropertyValues);
numStateVarValues = const_cast<int*>(_numStateVarValues);
dbPropertyValues = const_cast<char**>(_dbPropertyValues);
dbStateVarValues = const_cast<char**>(_dbStateVarValues);
dbProperties = const_cast<PylithScalar*>(_dbProperties);
dbStateVars = const_cast<PylithScalar*>(_dbStateVars);
properties = const_cast<PylithScalar*>(_properties);
stateVars = const_cast<PylithScalar*>(_stateVars);
propertiesNondim = const_cast<PylithScalar*>(_propertiesNondim);
stateVarsNondim = const_cast<PylithScalar*>(_stateVarsNondim);
density = const_cast<PylithScalar*>(_density);
strain = const_cast<PylithScalar*>(_strain);
stress = const_cast<PylithScalar*>(_stress);
elasticConsts = const_cast<PylithScalar*>(_elasticConsts);
initialStress = const_cast<PylithScalar*>(_initialStress);
initialStrain = const_cast<PylithScalar*>(_initialStrain);
stateVarsUpdated = const_cast<PylithScalar*>(_stateVarsUpdated);
} // constructor
pylith::materials::DruckerPrager3DElasticData::~DruckerPrager3DElasticData(void)
{}
// End of file
| 24.442935
| 103
| 0.722179
|
Grant-Block
|
b77104c671b2196abd39c3d53f1fea5c1d4a0e7b
| 5,824
|
cpp
|
C++
|
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwpWiFiInterface.cpp
|
caixue901102/mbed-os
|
483833a8d4612845408fea5b1986d20ab8428580
|
[
"Apache-2.0"
] | null | null | null |
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwpWiFiInterface.cpp
|
caixue901102/mbed-os
|
483833a8d4612845408fea5b1986d20ab8428580
|
[
"Apache-2.0"
] | null | null | null |
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwpWiFiInterface.cpp
|
caixue901102/mbed-os
|
483833a8d4612845408fea5b1986d20ab8428580
|
[
"Apache-2.0"
] | 4
|
2018-12-10T12:03:54.000Z
|
2019-01-26T02:46:40.000Z
|
/* LWIP implementation of NetworkInterfaceAPI
* Copyright (c) 2015 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "WiFiInterface.h"
#include "uwpWiFiInterface.h"
#include "nsapi_types.h"
#include "uwp_emac.h"
#include "uwp_wifi_cmdevt.h"
#include "uwp_wifi_api.h"
/* Interface implementation */
//WiFiInterface::WiFiInterface(EMAC &emac, OnboardNetworkStack &stack) :
//{
//}
//RDAWiFiInterface *RDAWiFiInterface::get_target_default_instance()
//{
// static RDAWiFiInterface wifinet;
// return wifinet;
//}
nsapi_error_t UWPWiFiInterface::set_channel(uint8_t channel)
{
#if 0
int ret= 0;
init();
if (channel > 13)
return NSAPI_ERROR_PARAMETER;
if (channel == 0){
_channel = 0;
return NSAPI_ERROR_OK;
}
ret = rda5981_set_channel(channel);
if (ret == 0) {
_channel = channel;
return NSAPI_ERROR_OK;
} else
return NSAPI_ERROR_TIMEOUT;
#endif
printf("%s\r\n",__func__);
return NSAPI_ERROR_OK;
}
int8_t UWPWiFiInterface::get_rssi()
{
#if 0
return rda5981_get_rssi();
#endif
printf("%s\r\n",__func__);
return 0;
}
nsapi_error_t UWPWiFiInterface::init()
{
#if 1
if (!_interface) {
if (!_emac.power_up()) {
printf("power up failed!\n");
}
int ret = uwp_mgmt_open();
if(ret != 0)
printf("wifi open failed\r\n");
nsapi_error_t err = _stack.add_ethernet_interface(_emac, true, &_interface);
if (err != NSAPI_ERROR_OK) {
_interface = NULL;
return err;
}
_interface->attach(_connection_status_cb);
}
#endif
return NSAPI_ERROR_OK;
}
// TODO:need confirm
nsapi_error_t UWPWiFiInterface::set_credentials(const char *ssid, const char *pass,
nsapi_security_t security)
{
if(ssid == 0 || strlen(ssid) == 0)
return NSAPI_ERROR_PARAMETER;
if(security != NSAPI_SECURITY_NONE && (pass == 0 || strlen(pass) == 0))
return NSAPI_ERROR_PARAMETER;
if(strlen(ssid) > 32 || strlen(pass) > 63)
return NSAPI_ERROR_PARAMETER;
memcpy((void*)_ssid, (void*)ssid, strlen(ssid));
_ssid[strlen(ssid)] = '\0';
memcpy((void*)_pass, (void*)pass, strlen(pass));
_pass[strlen(pass)] = '\0';
_security = security;
return NSAPI_ERROR_OK;
}
nsapi_error_t UWPWiFiInterface::connect(const char *ssid, const char *pass,
nsapi_security_t security, uint8_t channel)
{
int ret;
bool find = false;
int retry_count = 4;
printf("%s\r\n",__func__);
if (ssid == NULL || ssid[0] == 0) {
return NSAPI_ERROR_PARAMETER;
}
init();
/*because cp will check whether there is a "ssid" in scan_result list, if not
the connect cmd will return an error. */
if (uwp_mgmt_scan_result_name(ssid) == false) {
uwp_mgmt_scan(0, 0, NULL);
if(uwp_mgmt_scan_result_name(ssid) == false) {
while(retry_count-- > 0) {
//maybe it's a hidden ssid, transfer ssid to probe it.
uwp_mgmt_scan(0, 0, ssid);
if(uwp_mgmt_scan_result_name(ssid) == true) {
find = true;
break;
}
}
} else
find = true;
} else
find = true;
if (!find) {
printf("no %s cached in scan result list!\r\n", ssid);
return NSAPI_ERROR_NO_SSID;
}
ret = uwp_mgmt_connect(ssid,pass,channel);
if (ret) {
printf("uwp_mgmt_connect failed:%d\n", ret);
return ret;
}
osDelay(300);
ret = _interface->bringup(_dhcp,
_ip_address[0] ? _ip_address : 0,
_netmask[0] ? _netmask : 0,
_gateway[0] ? _gateway : 0,
DEFAULT_STACK,
_blocking);
if (ret == NSAPI_ERROR_DHCP_FAILURE)
ret = NSAPI_ERROR_CONNECTION_TIMEOUT;
return ret;
}
nsapi_error_t UWPWiFiInterface::connect()
{
printf("%s\r\n",__func__);
return connect(_ssid, _pass, _security, _channel);
}
// TODO: return value
nsapi_error_t UWPWiFiInterface::disconnect()
{
#if 0
rda_msg msg;
if(sta_state < 2)
return NSAPI_ERROR_NO_CONNECTION;
init();
msg.type = WLAND_DISCONNECT;
rda_mail_put(wland_msgQ, (void*)&msg, osWaitForever);
if (_interface) {
return _interface->bringdown();
}
#endif
printf("%s\r\n",__func__);
int ret = uwp_mgmt_disconnect();
if(_interface)
return _interface->bringdown();
}
// TODO: only test scan
nsapi_size_or_error_t UWPWiFiInterface::scan(WiFiAccessPoint *res, nsapi_size_t count)
{
int ret;
init();
ret = uwp_mgmt_scan(0, 0, NULL);
struct event_scan_result *bss = (struct event_scan_result *)malloc(ret * sizeof(struct event_scan_result));
if(bss == NULL)
return NSAPI_ERROR_NO_MEMORY;
memset(bss, 0, ret * sizeof(struct event_scan_result));
uwp_mgmt_get_scan_result(bss, ret);
for(int i=0; i<ret; i++){
printf("%-32s %-10s %-2d %02x:%02x:%02x:%02x:%02x:%02x\r\n",
bss[i].ssid, security2str(bss[i].encrypt_mode), bss[i].rssi,
(bss[i].bssid)[0],(bss[i].bssid)[1],(bss[i].bssid)[2],
(bss[i].bssid)[3],(bss[i].bssid)[4],(bss[i].bssid)[5]);
}
free(bss);
return 0;
}
WiFiInterface *WiFiInterface::get_default_instance() {
static UWPWiFiInterface wifinet;
return &wifinet;
}
| 26.83871
| 111
| 0.6341
|
caixue901102
|
b7777dc3e401af320b7d119684b1266e5867a9d8
| 288
|
cc
|
C++
|
042. Multiply Strings/TEST.cc
|
corkiwang1122/LeetCode
|
39b1680b58173e6ec23a475605c3450ce8f78a81
|
[
"MIT"
] | 3,690
|
2015-01-03T03:40:23.000Z
|
2022-03-31T08:10:19.000Z
|
042. Multiply Strings/TEST.cc
|
Windfall94/LeetCode
|
1756256d7e619164076bbf358c8f7ca68cd8bd79
|
[
"MIT"
] | 21
|
2015-01-25T16:39:43.000Z
|
2021-02-26T05:28:22.000Z
|
042. Multiply Strings/TEST.cc
|
Windfall94/LeetCode
|
1756256d7e619164076bbf358c8f7ca68cd8bd79
|
[
"MIT"
] | 1,290
|
2015-01-09T01:28:20.000Z
|
2022-03-28T12:20:39.000Z
|
#define CATCH_CONFIG_MAIN
#include "../Catch/single_include/catch.hpp"
#include "solution.h"
TEST_CASE("Multiply Strings", "multiply")
{
Solution s;
REQUIRE(s.multiply("123456", "789") == "97406784");
REQUIRE(s.multiply("123456789", "987654321") == "121932631112635269");
}
| 24
| 74
| 0.690972
|
corkiwang1122
|
b778e069dbbad5b352c9ae66f6512e2c87046021
| 12,612
|
cpp
|
C++
|
src/extern/inventor/lib/database/src/so/engines/SoCompose.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 2
|
2020-05-21T07:06:07.000Z
|
2021-06-28T02:14:34.000Z
|
src/extern/inventor/lib/database/src/so/engines/SoCompose.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | null | null | null |
src/extern/inventor/lib/database/src/so/engines/SoCompose.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 6
|
2016-03-21T19:53:18.000Z
|
2021-06-08T18:06:03.000Z
|
/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Classes:
| SoComposeVec3f
|
| Author(s) : Ronen Barzel
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include <Inventor/engines/SoCompose.h>
#include "SoEngineUtil.h"
//////////////////
//
// Utility macro defines basic source for composition/decomposition
// engines
//
#define SO_COMPOSE__SOURCE(Name) \
SO_ENGINE_SOURCE(Name); \
Name::~Name() { }
////////////////////////////////////////////////////////////////////////
//
// Source for SoComposeVec2f
//
SO_COMPOSE__SOURCE(SoComposeVec2f);
SoComposeVec2f::SoComposeVec2f()
{
SO_ENGINE_CONSTRUCTOR(SoComposeVec2f);
SO_ENGINE_ADD_INPUT(x, (0.0));
SO_ENGINE_ADD_INPUT(y, (0.0));
SO_ENGINE_ADD_OUTPUT(vector, SoMFVec2f);
isBuiltIn = TRUE;
}
void
SoComposeVec2f::evaluate()
{
int nx = x.getNum();
int ny = y.getNum();
int nout = max(nx,ny);
SO_ENGINE_OUTPUT(vector, SoMFVec2f, setNum(nout));
for (int i=0; i<nout; i++) {
float vx = x[clamp(i,nx)];
float vy = y[clamp(i,ny)];
SO_ENGINE_OUTPUT(vector, SoMFVec2f, set1Value(i, vx, vy));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoComposeVec3f
//
SO_COMPOSE__SOURCE(SoComposeVec3f);
SoComposeVec3f::SoComposeVec3f()
{
SO_ENGINE_CONSTRUCTOR(SoComposeVec3f);
SO_ENGINE_ADD_INPUT(x, (0.0));
SO_ENGINE_ADD_INPUT(y, (0.0));
SO_ENGINE_ADD_INPUT(z, (0.0));
SO_ENGINE_ADD_OUTPUT(vector, SoMFVec3f);
isBuiltIn = TRUE;
}
void
SoComposeVec3f::evaluate()
{
int nx = x.getNum();
int ny = y.getNum();
int nz = z.getNum();
int nout=max(nx,ny,nz);
SO_ENGINE_OUTPUT(vector, SoMFVec3f, setNum(nout));
for (int i=0; i<nout; i++) {
float vx = x[clamp(i,nx)];
float vy = y[clamp(i,ny)];
float vz = z[clamp(i,nz)];
SO_ENGINE_OUTPUT(vector, SoMFVec3f, set1Value(i, vx, vy, vz));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoComposeVec4f
//
SO_COMPOSE__SOURCE(SoComposeVec4f);
SoComposeVec4f::SoComposeVec4f()
{
SO_ENGINE_CONSTRUCTOR(SoComposeVec4f);
SO_ENGINE_ADD_INPUT(x, (0.0));
SO_ENGINE_ADD_INPUT(y, (0.0));
SO_ENGINE_ADD_INPUT(z, (0.0));
SO_ENGINE_ADD_INPUT(w, (0.0));
SO_ENGINE_ADD_OUTPUT(vector, SoMFVec4f);
isBuiltIn = TRUE;
}
void
SoComposeVec4f::evaluate()
{
int nx = x.getNum();
int ny = y.getNum();
int nz = z.getNum();
int nw = w.getNum();
int nout=max(nx,ny,nz,nw);
SO_ENGINE_OUTPUT(vector, SoMFVec4f, setNum(nout));
for (int i=0; i<nout; i++) {
float vx = x[clamp(i,nx)];
float vy = y[clamp(i,ny)];
float vz = z[clamp(i,nz)];
float vw = w[clamp(i,nw)];
SO_ENGINE_OUTPUT(vector, SoMFVec4f, set1Value(i, vx, vy, vz, vw));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoDecomposeVec2f
//
SO_COMPOSE__SOURCE(SoDecomposeVec2f);
SoDecomposeVec2f::SoDecomposeVec2f()
{
SO_ENGINE_CONSTRUCTOR(SoDecomposeVec2f);
SO_ENGINE_ADD_INPUT(vector, (SbVec2f(0,0)));
SO_ENGINE_ADD_OUTPUT(x, SoMFFloat);
SO_ENGINE_ADD_OUTPUT(y, SoMFFloat);
isBuiltIn = TRUE;
}
void
SoDecomposeVec2f::evaluate()
{
int nout=vector.getNum();
SO_ENGINE_OUTPUT(x, SoMFFloat, setNum(nout));
SO_ENGINE_OUTPUT(y, SoMFFloat, setNum(nout));
for (int i=0; i<nout; i++) {
SO_ENGINE_OUTPUT(x, SoMFFloat, set1Value(i,vector[i][0]));
SO_ENGINE_OUTPUT(y, SoMFFloat, set1Value(i,vector[i][1]));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoDecomposeVec3f
//
SO_COMPOSE__SOURCE(SoDecomposeVec3f);
SoDecomposeVec3f::SoDecomposeVec3f()
{
SO_ENGINE_CONSTRUCTOR(SoDecomposeVec3f);
SO_ENGINE_ADD_INPUT(vector, (SbVec3f(0,0,0)));
SO_ENGINE_ADD_OUTPUT(x, SoMFFloat);
SO_ENGINE_ADD_OUTPUT(y, SoMFFloat);
SO_ENGINE_ADD_OUTPUT(z, SoMFFloat);
isBuiltIn = TRUE;
}
void
SoDecomposeVec3f::evaluate()
{
int nout=vector.getNum();
SO_ENGINE_OUTPUT(x, SoMFFloat, setNum(nout));
SO_ENGINE_OUTPUT(y, SoMFFloat, setNum(nout));
SO_ENGINE_OUTPUT(z, SoMFFloat, setNum(nout));
for (int i=0; i<nout; i++) {
SO_ENGINE_OUTPUT(x, SoMFFloat, set1Value(i,vector[i][0]));
SO_ENGINE_OUTPUT(y, SoMFFloat, set1Value(i,vector[i][1]));
SO_ENGINE_OUTPUT(z, SoMFFloat, set1Value(i,vector[i][2]));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoDecomposeVec4f
//
SO_COMPOSE__SOURCE(SoDecomposeVec4f);
SoDecomposeVec4f::SoDecomposeVec4f()
{
SO_ENGINE_CONSTRUCTOR(SoDecomposeVec4f);
SO_ENGINE_ADD_INPUT(vector, (SbVec4f(0,0,0,0)));
SO_ENGINE_ADD_OUTPUT(x, SoMFFloat);
SO_ENGINE_ADD_OUTPUT(y, SoMFFloat);
SO_ENGINE_ADD_OUTPUT(z, SoMFFloat);
SO_ENGINE_ADD_OUTPUT(w, SoMFFloat);
isBuiltIn = TRUE;
}
void
SoDecomposeVec4f::evaluate()
{
int nout=vector.getNum();
SO_ENGINE_OUTPUT(x, SoMFFloat, setNum(nout));
SO_ENGINE_OUTPUT(y, SoMFFloat, setNum(nout));
SO_ENGINE_OUTPUT(z, SoMFFloat, setNum(nout));
SO_ENGINE_OUTPUT(w, SoMFFloat, setNum(nout));
for (int i=0; i<nout; i++) {
SO_ENGINE_OUTPUT(x, SoMFFloat, set1Value(i,vector[i][0]));
SO_ENGINE_OUTPUT(y, SoMFFloat, set1Value(i,vector[i][1]));
SO_ENGINE_OUTPUT(z, SoMFFloat, set1Value(i,vector[i][2]));
SO_ENGINE_OUTPUT(w, SoMFFloat, set1Value(i,vector[i][3]));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoComposeRotation
//
SO_COMPOSE__SOURCE(SoComposeRotation);
SoComposeRotation::SoComposeRotation()
{
SO_ENGINE_CONSTRUCTOR(SoComposeRotation);
SO_ENGINE_ADD_INPUT(axis, (SbVec3f(0,0,1)));
SO_ENGINE_ADD_INPUT(angle, (0.0));
SO_ENGINE_ADD_OUTPUT(rotation, SoMFRotation);
isBuiltIn = TRUE;
}
void
SoComposeRotation::evaluate()
{
int naxis = axis.getNum();
int nangle = angle.getNum();
int nout=max(naxis,nangle);
SO_ENGINE_OUTPUT(rotation, SoMFRotation, setNum(nout));
for (int i=0; i<nout; i++) {
SbVec3f vaxis = axis[clamp(i,naxis)];
float vangle = angle[clamp(i,nangle)];
SO_ENGINE_OUTPUT(rotation, SoMFRotation, set1Value(i, vaxis, vangle));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoComposeRotationFromTo
//
SO_COMPOSE__SOURCE(SoComposeRotationFromTo);
SoComposeRotationFromTo::SoComposeRotationFromTo()
{
SO_ENGINE_CONSTRUCTOR(SoComposeRotationFromTo);
SO_ENGINE_ADD_INPUT(from, (SbVec3f(0,0,1)));
SO_ENGINE_ADD_INPUT(to, (SbVec3f(0,0,1)));
SO_ENGINE_ADD_OUTPUT(rotation, SoMFRotation);
isBuiltIn = TRUE;
}
void
SoComposeRotationFromTo::evaluate()
{
int nfrom = from.getNum();
int nto = to.getNum();
int nout=max(nfrom,nto);
SO_ENGINE_OUTPUT(rotation, SoMFRotation, setNum(nout));
for (int i=0; i<nout; i++) {
SbVec3f vfrom = from[clamp(i,nfrom)];
SbVec3f vto = to[clamp(i,nto)];
SO_ENGINE_OUTPUT(rotation, SoMFRotation, set1Value(i, SbRotation(vfrom, vto)));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoDecomposeRotation
//
SO_COMPOSE__SOURCE(SoDecomposeRotation);
SoDecomposeRotation::SoDecomposeRotation()
{
SO_ENGINE_CONSTRUCTOR(SoDecomposeRotation);
SO_ENGINE_ADD_INPUT(rotation, (SbRotation::identity()));
SO_ENGINE_ADD_OUTPUT(axis, SoMFVec3f);
SO_ENGINE_ADD_OUTPUT(angle, SoMFFloat);
isBuiltIn = TRUE;
}
void
SoDecomposeRotation::evaluate()
{
int nout=rotation.getNum();
SO_ENGINE_OUTPUT(axis, SoMFVec3f, setNum(nout));
SO_ENGINE_OUTPUT(angle, SoMFFloat, setNum(nout));
for (int i=0; i<nout; i++) {
SbVec3f vaxis;
float vangle;
rotation[i].getValue(vaxis, vangle);
SO_ENGINE_OUTPUT(axis, SoMFVec3f, set1Value(i,vaxis));
SO_ENGINE_OUTPUT(angle, SoMFFloat, set1Value(i,vangle));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoComposeMatrix
//
SO_COMPOSE__SOURCE(SoComposeMatrix);
SoComposeMatrix::SoComposeMatrix()
{
SO_ENGINE_CONSTRUCTOR(SoComposeMatrix);
SO_ENGINE_ADD_INPUT(translation, (SbVec3f(0,0,0)));
SO_ENGINE_ADD_INPUT(rotation, (SbRotation::identity()));
SO_ENGINE_ADD_INPUT(scaleFactor, (SbVec3f(1,1,1)));
SO_ENGINE_ADD_INPUT(scaleOrientation,(SbRotation::identity()));
SO_ENGINE_ADD_INPUT(center, (SbVec3f(0,0,0)));
SO_ENGINE_ADD_OUTPUT(matrix, SoMFMatrix);
isBuiltIn = TRUE;
}
void
SoComposeMatrix::evaluate()
{
int ntranslation = translation.getNum();
int nrotation = rotation.getNum();
int nscaleFactor = scaleFactor.getNum();
int nscaleOrientation = scaleOrientation.getNum();
int ncenter = center.getNum();
int nout=max(ntranslation,nrotation,nscaleFactor,nscaleOrientation,ncenter);
SO_ENGINE_OUTPUT(matrix, SoMFMatrix, setNum(nout));
for (int i=0; i<nout; i++) {
SbVec3f vtrans = translation[clamp(i,ntranslation)];
SbRotation vrot = rotation[clamp(i,nrotation)];
SbVec3f vscale = scaleFactor[clamp(i,nscaleFactor)];
SbRotation vscaleO = scaleOrientation[clamp(i,nscaleOrientation)];
SbVec3f vcenter = center[clamp(i,ncenter)];
SbMatrix m;
m.setTransform(vtrans, vrot, vscale, vscaleO, vcenter);
SO_ENGINE_OUTPUT(matrix, SoMFMatrix, set1Value(i, m));
}
}
////////////////////////////////////////////////////////////////////////
//
// Source for SoDecomposeMatrix
//
SO_COMPOSE__SOURCE(SoDecomposeMatrix);
SoDecomposeMatrix::SoDecomposeMatrix()
{
SO_ENGINE_CONSTRUCTOR(SoDecomposeMatrix);
SO_ENGINE_ADD_INPUT(matrix, (SbMatrix::identity()));
SO_ENGINE_ADD_INPUT(center, (SbVec3f(0,0,0)));
SO_ENGINE_ADD_OUTPUT(translation, SoMFVec3f);
SO_ENGINE_ADD_OUTPUT(rotation, SoMFRotation);
SO_ENGINE_ADD_OUTPUT(scaleFactor, SoMFVec3f);
SO_ENGINE_ADD_OUTPUT(scaleOrientation, SoMFRotation);
isBuiltIn = TRUE;
}
void
SoDecomposeMatrix::evaluate()
{
int nmatrix = matrix.getNum();
int ncenter = center.getNum();
int nout=max(nmatrix,ncenter);
SO_ENGINE_OUTPUT(translation, SoMFVec3f, setNum(nout));
SO_ENGINE_OUTPUT(rotation, SoMFRotation, setNum(nout));
SO_ENGINE_OUTPUT(scaleFactor, SoMFVec3f, setNum(nout));
SO_ENGINE_OUTPUT(scaleOrientation, SoMFRotation, setNum(nout));
for (int i=0; i<nout; i++) {
SbVec3f trans;
SbRotation rot;
SbVec3f scale;
SbRotation scaleO;
SbVec3f vcenter = center[clamp(i,ncenter)];
SbMatrix vmatrix = matrix[clamp(i,nmatrix)];
vmatrix.getTransform(trans, rot, scale, scaleO, vcenter);
SO_ENGINE_OUTPUT(translation, SoMFVec3f, set1Value(i, trans));
SO_ENGINE_OUTPUT(rotation, SoMFRotation, set1Value(i, rot));
SO_ENGINE_OUTPUT(scaleFactor, SoMFVec3f, set1Value(i, scale));
SO_ENGINE_OUTPUT(scaleOrientation, SoMFRotation, set1Value(i, scaleO));
}
}
| 29.127021
| 80
| 0.660006
|
OpenXIP
|
b77aca1fd6485a14df48ba50d7967575c7478b9d
| 1,226
|
cpp
|
C++
|
Thread/ThreadPool.cpp
|
ReliaSolve/acl
|
a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9
|
[
"MIT"
] | null | null | null |
Thread/ThreadPool.cpp
|
ReliaSolve/acl
|
a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9
|
[
"MIT"
] | null | null | null |
Thread/ThreadPool.cpp
|
ReliaSolve/acl
|
a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9
|
[
"MIT"
] | null | null | null |
/**
* \copyright Copyright 2021 Aqueti, Inc. All rights reserved.
* \license This project is released under the MIT Public License.
**/
/**
* \file ThreadPool.cpp
**/
#include "ThreadPool.h"
namespace acl
{
/**
* \brief initializes the thread pool
*
* \param [in] numThreads the number of threads
* \param [in] maxJobLength the maximum number of jobs that can be submitted
* \param [in] timeout the time a thread should process before moving on
**/
ThreadPool::ThreadPool(int numThreads, int maxJobLength, double timeout): MultiThread(numThreads), TSQueue<std::function<void()>>()
{
set_max_size(maxJobLength);
m_timeout = timeout;
}
/**
* \brief adds jobs to the pool
*
* \param [in] f the job to be added
* \return true if the job has been successfully enqueued
**/
bool ThreadPool::push_job(std::function<void()> f)
{
return enqueue(f);
}
/**
* \brief main function to loop through the queue and run jobs
**/
void ThreadPool::mainLoop()
{
std::function<void()> f;
if (dequeue(f, m_timeout) && f) {
f();
}
}
/**
* \brief sets the timeout value
*
* \param [in] timeout the timeout value to be set
**/
void ThreadPool::setTimeout(double timeout)
{
m_timeout = timeout;
}
}
| 20.433333
| 131
| 0.677814
|
ReliaSolve
|
b77b530d3b6239307317187caaf9c2a06a9f69df
| 4,915
|
hpp
|
C++
|
include/humanize/numbers.hpp
|
pajlada/humanize
|
13867379249c64cd44b9cd4c03f18c1a52d56587
|
[
"MIT"
] | 2
|
2017-12-17T02:12:33.000Z
|
2018-06-05T16:49:51.000Z
|
include/humanize/numbers.hpp
|
pajlada/humanize
|
13867379249c64cd44b9cd4c03f18c1a52d56587
|
[
"MIT"
] | null | null | null |
include/humanize/numbers.hpp
|
pajlada/humanize
|
13867379249c64cd44b9cd4c03f18c1a52d56587
|
[
"MIT"
] | null | null | null |
#pragma once
#include "humanize/format_string.hpp"
#include <array>
#include <cstring>
#include <limits>
#include <string>
#include <type_traits>
namespace humanize {
namespace {
struct NumberStruct {
int length;
char suffix;
};
// return const char * with arguments typename Number, and input char buffer
// with size of numeric_limits<Number, and with input format string from
// format_string<Number>
template <typename Number>
void
numberToChars(char *str, Number x)
{
std::sprintf(str, format_string<Number>::format(), x);
}
template <typename Number>
void
absValue(Number &x,
typename std::enable_if<std::is_signed<Number>::value>::type * = 0)
{
x = static_cast<Number>(std::abs(x));
}
template <typename Number>
void
absValue(Number &,
typename std::enable_if<std::is_unsigned<Number>::value>::type * = 0)
{
// do nothing
}
template <bool IsSigned>
struct SignedHelper {
};
template <>
struct SignedHelper<false> {
template <typename Number>
static char *
getStringWithoutSign(char *str, Number)
{
return str;
}
template <typename Number>
static void
test(char *str, Number, unsigned decimals, const char *numberStr,
int decimalIndex, const NumberStruct &ns)
{
if (decimals > 0) {
std::sprintf(str, "%.*s.%.*s%c", decimalIndex, numberStr, decimals,
numberStr + decimalIndex, ns.suffix);
} else {
std::sprintf(str, "%.*s%c", decimalIndex, numberStr, ns.suffix);
}
}
};
template <>
struct SignedHelper<true> {
template <typename Number>
static char *
getStringWithoutSign(char *str, Number number)
{
if (number < 0) {
return str + 1;
} else {
return str;
}
}
template <typename Number>
static void
test(char *str, Number number, unsigned decimals, const char *numberStr,
int decimalIndex, const NumberStruct &ns)
{
if (number < 0) {
if (decimals > 0) {
std::sprintf(str, "-%.*s.%.*s%c", decimalIndex, numberStr,
decimals, numberStr + decimalIndex, ns.suffix);
} else {
std::sprintf(str, "-%.*s%c", decimalIndex, numberStr,
ns.suffix);
}
} else {
SignedHelper<false>::test(str, number, decimals, numberStr,
decimalIndex, ns);
}
}
};
} // anonymous namespace
// Signed integer
template <typename Number, typename = typename std::enable_if<
std::is_integral<Number>::value>::type>
std::string
compactInteger(Number number, unsigned decimals = 0)
{
constexpr auto maxStringSize = std::numeric_limits<Number>::digits10 +
std::numeric_limits<Number>::is_signed + 2;
char str[maxStringSize];
numberToChars<Number>(str, number);
Number absNumber = number;
absValue(absNumber);
static std::array<NumberStruct, 4> numberLengths = {{
{13, 'T'}, //
{10, 'B'}, //
{7, 'M'}, //
{4, 'k'}, //
}};
char *numberStr =
SignedHelper<std::is_signed<Number>::value>::getStringWithoutSign(
str, number);
int absNumberLength = static_cast<int>(std::strlen(numberStr));
if (absNumber < 1000) {
return str;
}
// do complicated shit
for (const auto &numberStruct : numberLengths) {
if (absNumberLength >= numberStruct.length) {
// Found matching NumberStruct
int decimalIndex = absNumberLength - numberStruct.length + 1;
char finalStr[maxStringSize];
SignedHelper<std::is_signed<Number>::value>::test(
finalStr, number, decimals, numberStr, decimalIndex,
numberStruct);
return finalStr;
}
}
// This should never happen
return "?";
}
template <typename Number, typename = typename std::enable_if<
std::is_integral<Number>::value>::type>
std::string
ordinal(const Number number)
{
std::string numString = std::to_string(number);
if (number < 0) {
return numString;
}
std::string end;
switch (number % 100) {
case 11:
case 12:
case 13:
end = "th";
break;
default: {
switch (number % 10) {
case 1:
end = "st";
break;
case 2:
end = "nd";
break;
case 3:
end = "rd";
break;
default:
end = "th";
break;
}
} break;
}
return numString + end;
}
} // namespace humanize
| 24.698492
| 79
| 0.546083
|
pajlada
|
b77bc5e85478a41af59b4d57e231db4900b50d4f
| 21,205
|
cpp
|
C++
|
dbms/src/Functions/tests/gtest_bitand.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 85
|
2022-03-25T09:03:16.000Z
|
2022-03-25T09:45:03.000Z
|
dbms/src/Functions/tests/gtest_bitand.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 7
|
2022-03-25T08:59:10.000Z
|
2022-03-25T09:40:13.000Z
|
dbms/src/Functions/tests/gtest_bitand.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 11
|
2022-03-25T09:15:36.000Z
|
2022-03-25T09:45:07.000Z
|
// Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Columns/ColumnConst.h>
#include <Columns/ColumnString.h>
#include <Common/Exception.h>
#include <DataTypes/DataTypeNothing.h>
#include <Functions/FunctionFactory.h>
#include <Interpreters/Context.h>
#include <TestUtils/FunctionTestUtils.h>
#include <TestUtils/TiFlashTestBasic.h>
#include <string>
#include <unordered_map>
#include <vector>
namespace DB
{
namespace tests
{
class TestFunctionBitAnd : public DB::tests::FunctionTest
{
};
#define ASSERT_BITAND(t1, t2, result) \
ASSERT_COLUMN_EQ(result, executeFunction("bitAnd", {t1, t2}))
TEST_F(TestFunctionBitAnd, Simple)
try
{
ASSERT_BITAND(createColumn<Nullable<Int64>>({-1, 1}), createColumn<Nullable<Int64>>({0, 0}), createColumn<Nullable<Int64>>({0, 0}));
}
CATCH
/// Note: Only IntX and UIntX will be received by BitAnd, others will be casted by TiDB Planner.
TEST_F(TestFunctionBitAnd, TypePromotion)
try
{
// Type Promotion
ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int16>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<Nullable<Int32>>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int32>>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Nullable<UInt16>>({0}), createColumn<Nullable<UInt16>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt16>>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<UInt32>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0}));
// Type Promotion across signed/unsigned
ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int64>>({1}), createColumn<Nullable<UInt8>>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0}));
}
CATCH
TEST_F(TestFunctionBitAnd, Nullable)
try
{
// Non Nullable
ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Int16>({0}), createColumn<Int16>({0}));
ASSERT_BITAND(createColumn<Int16>({1}), createColumn<Int32>({0}), createColumn<Int32>({0}));
ASSERT_BITAND(createColumn<Int32>({1}), createColumn<Int64>({0}), createColumn<Int64>({0}));
ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Int64>({0}), createColumn<Int64>({0}));
ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<UInt16>({0}), createColumn<UInt16>({0}));
ASSERT_BITAND(createColumn<UInt16>({1}), createColumn<UInt32>({0}), createColumn<UInt32>({0}));
ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<UInt64>({0}), createColumn<UInt64>({0}));
ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<UInt64>({0}), createColumn<UInt64>({0}));
ASSERT_BITAND(createColumn<Int16>({1}), createColumn<UInt32>({0}), createColumn<Int32>({0}));
ASSERT_BITAND(createColumn<Int64>({1}), createColumn<UInt8>({0}), createColumn<Int64>({0}));
ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<Int16>({0}), createColumn<Int32>({0}));
ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Int64>({0}), createColumn<Int64>({0}));
// Across Nullable and non-Nullable
ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int16>>({0}));
ASSERT_BITAND(createColumn<Int16>({1}), createColumn<Nullable<Int32>>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Int32>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Nullable<UInt16>>({0}), createColumn<Nullable<UInt16>>({0}));
ASSERT_BITAND(createColumn<UInt16>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<UInt32>>({0}));
ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0}));
ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0}));
ASSERT_BITAND(createColumn<Int16>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Int64>({1}), createColumn<Nullable<UInt8>>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Int16>({0}), createColumn<Nullable<Int16>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<Int32>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int32>>({1}), createColumn<Int64>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Int64>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<UInt16>({0}), createColumn<Nullable<UInt16>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt16>>({1}), createColumn<UInt32>({0}), createColumn<Nullable<UInt32>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<UInt64>({0}), createColumn<Nullable<UInt64>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<UInt64>({0}), createColumn<Nullable<UInt64>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<UInt32>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Nullable<Int64>>({1}), createColumn<UInt8>({0}), createColumn<Nullable<Int64>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<Int16>({0}), createColumn<Nullable<Int32>>({0}));
ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Int64>({0}), createColumn<Nullable<Int64>>({0}));
}
CATCH
TEST_F(TestFunctionBitAnd, TypeCastWithConst)
try
{
/// need test these kinds of columns:
/// 1. ColumnVector
/// 2. ColumnVector<Nullable>
/// 3. ColumnConst
/// 4. ColumnConst<Nullable>, value != null
/// 5. ColumnConst<Nullable>, value = null
ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Int64>({0, 0, 0, 1}));
ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt}));
ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createConstColumn<UInt64>(4, 0), createColumn<Int64>({0, 0, 0, 0}));
ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createConstColumn<Nullable<UInt64>>(4, 0), createColumn<Nullable<Int64>>({0, 0, 0, 0}));
ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt)); // become const in wrapInNullable
ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Nullable<Int64>>({0, 1, std::nullopt, std::nullopt}));
ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 1, std::nullopt, std::nullopt}));
ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<UInt64>(4, 0), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt}));
ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<Nullable<UInt64>>(4, 0), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt}));
ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt));
ASSERT_BITAND(createConstColumn<Int8>(4, 0), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Int64>({0, 0, 0, 0}));
ASSERT_BITAND(createConstColumn<Int8>(4, 0), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt}));
ASSERT_BITAND(createConstColumn<Int8>(4, 0), createConstColumn<UInt64>(4, 0), createConstColumn<Int64>(4, 0));
ASSERT_BITAND(createConstColumn<Int8>(4, 0), createConstColumn<Nullable<UInt64>>(4, 0), createConstColumn<Nullable<Int64>>(4, 0));
ASSERT_BITAND(createConstColumn<Int8>(4, 0), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Nullable<Int64>>({0, 0, 0, 0}));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt}));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createConstColumn<UInt64>(4, 0), createConstColumn<Nullable<Int64>>(4, 0));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createConstColumn<Nullable<UInt64>>(4, 0), createConstColumn<Nullable<Int64>>(4, 0));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createColumn<UInt64>({0, 1, 0, 1}), createConstColumn<Nullable<Int64>>(4, std::nullopt));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<Nullable<Int64>>(4, std::nullopt));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createConstColumn<UInt64>(4, 0), createConstColumn<Nullable<Int64>>(4, std::nullopt));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createConstColumn<Nullable<UInt64>>(4, 0), createConstColumn<Nullable<Int64>>(4, std::nullopt));
ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt));
}
CATCH
TEST_F(TestFunctionBitAnd, Boundary)
try
{
ASSERT_BITAND(createColumn<Int8>({127, 127, -128, -128}), createColumn<UInt8>({0, 255, 0, 255}), createColumn<Int8>({0, 127, 0, -128}));
ASSERT_BITAND(createColumn<Int8>({127, 127, -128, -128}), createColumn<UInt16>({0, 65535, 0, 65535}), createColumn<Int16>({0, 127, 0, -128}));
ASSERT_BITAND(createColumn<Int16>({32767, 32767, -32768, -32768}), createColumn<UInt8>({0, 255, 0, 255}), createColumn<Int16>({0, 255, 0, 0}));
ASSERT_BITAND(createColumn<Int64>({0, 0, 1, 1, -1, -1, INT64_MAX, INT64_MAX, INT64_MIN, INT64_MIN}),
createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX, 0, UINT64_MAX, 0, UINT64_MAX, 0, UINT64_MAX}),
createColumn<Int64>({0, 0, 0, 1, 0, -1, 0, INT64_MAX, 0, INT64_MIN}));
}
CATCH
TEST_F(TestFunctionBitAnd, UINT64)
try
{
ASSERT_BITAND(createColumn<UInt64>({0, 0, UINT64_MAX, UINT64_MAX}),
createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX}),
createColumn<UInt64>({0, 0, 0, UINT64_MAX}));
ASSERT_BITAND(createColumn<Nullable<UInt64>>({0, 0, UINT64_MAX, UINT64_MAX, 0, std::nullopt}),
createColumn<Nullable<UInt64>>({0, UINT64_MAX, 0, UINT64_MAX, std::nullopt, 0}),
createColumn<Nullable<UInt64>>({0, 0, 0, UINT64_MAX, std::nullopt, std::nullopt}));
ASSERT_BITAND(createColumn<Nullable<UInt64>>({0, 0, UINT64_MAX, UINT64_MAX, std::nullopt}),
createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX, 0}),
createColumn<Nullable<UInt64>>({0, 0, 0, UINT64_MAX, std::nullopt}));
ASSERT_BITAND(createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX, 0}),
createColumn<Nullable<UInt64>>({0, 0, UINT64_MAX, UINT64_MAX, std::nullopt}),
createColumn<Nullable<UInt64>>({0, 0, 0, UINT64_MAX, std::nullopt}));
/*
std::mt19937 gen(std::random_device{}());
std::uniform_int_distribution<unsigned long long> dis(
std::numeric_limits<std::uint64_t>::min(),
std::numeric_limits<std::uint64_t>::max()
);
size_t count = 100;
std::vector<UINT64> v1(count), v2(count), res(count);
for (size_t i=0; i<count; ++i) {
v1[i] = dis(gen);
v2[i] = dis(gen);
res[i] = v1[i] & v2[i];
}
*/
// clang-format off
ASSERT_BITAND(createColumn<UInt64>({7091597907609164394ull,12147405979737555885ull,4944752083022751199ull,5266856817029714805ull,16249582031829054894ull,14585895400450077565ull,16559878625296112963ull,11686022872732312883ull,2252836050652542276ull,18270461639320085260ull,477362305064009683ull,5924031996839311984ull,13502342125078821090ull,1983692735111761557ull,7075393861938658224ull,8534577556983106270ull,6961865328371185981ull,8145880463914069438ull,5244290579560821188ull,10259565555661135100ull,4653092958722629712ull,8153941146514590265ull,16445187578470766485ull,126971754730186422ull,12494401415606381041ull,821635861271395080ull,10789756166060569460ull,17220753103104465161ull,4214870374383746276ull,11087492977524287663ull,13202884495831508537ull,15975448051191870337ull,14627676554537635677ull,4349811632778009896ull,17130992699769672908ull,11200975303296257603ull,7275004492439954170ull,16274625055262694174ull,9100812775640660847ull,10611801488751952495ull,13988464420037366691ull,12715906540348551121ull,11766429052248709786ull,3338715427749605ull,2190861738386064756ull,2380874473443914065ull,5805871478722753955ull,18380152411992198484ull,17753836161221930124ull,558899075728331952ull,6945707259485057305ull,15540448118791785514ull,14100396407684167764ull,7686576470926131642ull,6847113332786445596ull,8571497544299597952ull,5107506230492840013ull,13809089677202756103ull,11850464950116242772ull,8665410045503026098ull,12611995970725331088ull,14716086967124651162ull,8332337353906700486ull,1055042741385964424ull,15747416080677248841ull,14915670236539320530ull,7900308686393206650ull,4979886344023150111ull,5902402781825910141ull,3255426766738440460ull,15073047456619535065ull,14385299733787058194ull,9204231696702233102ull,10378053593247535553ull,17743937090908512033ull,284875276098321550ull,8191444072549517566ull,11831960808665605673ull,16522251628765377415ull,9489110493662951639ull,2985165104683868371ull,1923666239526938648ull,2608156467518575538ull,15010176170111705563ull,8595623925997760729ull,5537255266788969170ull,4026706972241118255ull,10146297908886518879ull,11571719523540239514ull,8947543025284496775ull,6474440949527995615ull,8042516419360849959ull,12772931646054458863ull,8362173284515136314ull,2965170807480292156ull,3697936742835324831ull,2548596695355670143ull,678615102317890017ull,18347860548317292650ull,5348024243900531994ull,
}),
createColumn<UInt64>({1963993824751904883ull,8092151856919135067ull,5131775057722478077ull,15715528133814023746ull,15505304522311288171ull,10286790629013975231ull,1501823745926746029ull,12973914748851182578ull,8210074373542591108ull,13460194198694121125ull,5224676877811702912ull,9335603723497191999ull,14816589124295502018ull,4954279722715295418ull,11100674508285551899ull,13464602075238859455ull,16853392590959687352ull,1817058812112508107ull,15556867487501561584ull,10284485237014856710ull,14437749781215352280ull,5771839681340207927ull,16055484011087334393ull,3176481359853048004ull,7814936607178752912ull,2494931346489092259ull,8767088596499268464ull,14226279241180503276ull,7473321867985919185ull,6734041306837931713ull,13235889048871924509ull,10991267203008554602ull,16751923766106295286ull,10095830120191421323ull,16222110847614790525ull,9842614984677906240ull,4933809552431881486ull,8405192294344557484ull,4959648925715618956ull,6697802956154799897ull,12131820337280328334ull,7842863996271662529ull,16569735361616664303ull,12858241103410228367ull,5513953872175351416ull,859413842831558633ull,13344669626051684726ull,13723621615205909176ull,15587646588258269977ull,14455229124733503750ull,1897402925930790108ull,15359004855099545708ull,12520174369297951929ull,10652815703651083579ull,8168743478119503616ull,13222025305950777542ull,1407449211367397936ull,719150994271271568ull,13201069077204373904ull,7881062513337573241ull,505835289877393142ull,16274255003040284083ull,5851222720449930723ull,10184171151253590546ull,10760806328248813948ull,11613887821236610307ull,396890304498933892ull,2817599718757852634ull,206272906874991324ull,11706414073185557053ull,1232629356308009454ull,11720363557979026158ull,7397814221360500092ull,17105630191392625269ull,17759165119137150028ull,11745869976822508796ull,13060766979359736635ull,6099807408799721275ull,9051766638104113010ull,9942483311080030083ull,5022375889081250419ull,16686942398742544149ull,17812504368324647606ull,14378217067310861473ull,13056638079919822910ull,6759774801955234976ull,12848167735234317960ull,532081090242244444ull,6210198885610140778ull,12902504877688878394ull,16860750806044045906ull,9057877269281939547ull,6387131386245764054ull,14021225438163328133ull,17155620859144768173ull,5353199724262717805ull,2748605048746777638ull,18127535939063270402ull,7104584635051455285ull,12463829834478575910ull,
}),
createColumn<UInt64>({162130378342041698ull,2306970147751363337ull,4906399183902082525ull,5192791187330961984ull,13907124735635686698ull,9962525953971236925ull,346918583778004225ull,11532613229130318130ull,1243004632125550596ull,13298056637815390724ull,36528456736988288ull,1726331243280944ull,9872189512905173186ull,36347689790344848ull,144256074823770384ull,3625644066346730142ull,6953842598776156216ull,1225956686928544906ull,4667154241155113152ull,10241542350102922244ull,4616489114865270864ull,5767017669974884913ull,14127801515980751761ull,281625320505476ull,3198685346327036304ull,146085883425597440ull,1272513185338262384ull,14153799398103144456ull,2465177654445579456ull,1825101351191904385ull,13198379756955640345ull,10988802093375644160ull,14446070136962059092ull,871868740806920456ull,16222109997211058252ull,9804857694914446912ull,4931441594151796746ull,6953862676154024716ull,4919078683284953100ull,1170971123190399497ull,9223374512903684738ull,2330455578176390593ull,11619991280813265546ull,426645963123845ull,866099620573742192ull,74309462839738689ull,1157574982499393826ull,13695456519373488144ull,15006629391026759688ull,36321322981392384ull,19151158298030104ull,15357838821927438376ull,9331608240669354000ull,181309540438966586ull,5838094792777667840ull,3923780495183728768ull,180145741880360960ull,694310827035464192ull,11831253089948602640ull,7512330184322847536ull,505536205530431632ull,13841813592565902482ull,5846279246746534082ull,865889046541369856ull,10376856859172309320ull,9235775630514724866ull,396889200523485184ull,367043386831602714ull,56440184765546588ull,2316408220766846988ull,1227838705627107528ull,9413113126569910274ull,7397814219170809868ull,9224005362282401857ull,17741122064043496448ull,216195325862358156ull,3531114965719253050ull,297959404870379049ull,7280724381522551554ull,9344973233195333763ull,81346546033008723ull,185258913461970960ull,2608156312547431090ull,13837468399527035009ull,3819134019844542488ull,5532681290774216832ull,3621347271012271112ull,306882631328345180ull,1970980911154186ull,3462149708829635842ull,5321356472062500946ull,7895938256515104771ull,1153625330601771462ull,4612917523078266880ull,2883431871756632620ull,162165595591180557ull,2451085405657799718ull,648765478774114304ull,7097813840969080864ull,590089416916222210ull,
}));
// clang-format on
}
CATCH
} // namespace tests
} // namespace DB
| 94.665179
| 2,386
| 0.777317
|
solotzg
|
b77d00b0b3cc78953d68a764bf11a7ebe8b6ef3f
| 1,336
|
cpp
|
C++
|
src/scene/SpriteScene.cpp
|
projectivemotion/sdlgame1
|
9e126b6ef096605008dfc5db8e9264b68582b38a
|
[
"MIT"
] | null | null | null |
src/scene/SpriteScene.cpp
|
projectivemotion/sdlgame1
|
9e126b6ef096605008dfc5db8e9264b68582b38a
|
[
"MIT"
] | null | null | null |
src/scene/SpriteScene.cpp
|
projectivemotion/sdlgame1
|
9e126b6ef096605008dfc5db8e9264b68582b38a
|
[
"MIT"
] | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: SpriteScene.cpp
* Author: eye
*
* Created on October 15, 2019, 4:33 PM
*/
#include "SpriteScene.h"
#include "DrawableTexture.h"
#include "entities/entity.h"
bool SpriteScene::init() {
auto am = app->getAssetManager();
auto canvas = am.createSurfaceEntity(300, 200);
auto dots = am.openid(ASSET_DOTSIMG);
entity<SDL_Surface> a(dots, 100, 100, 0, 0);
entity<SDL_Surface> b(dots, 100, 100, 1, 0);
entity<SDL_Surface> c(dots, 100, 100, 0, 1);
entity<SDL_Surface> d(dots, 100, 100, 1, 1);
entity<SDL_Surface> z(dots, 200, 200);
canvas.draw(z.move(200,100).resize(100,100));
canvas.draw(a.move(0,0));
canvas.draw(b.move(100,0));
canvas.draw(c.move(200,0));
canvas.draw(d.move(0,100));
// canvas.draw(d);
// auto clip = am.fromSurface(canvas, app).resize(100, 100);
auto stretched = am.fromSurface(canvas, app).resize(300, 300);
auto proportional = am.fromSurface(canvas, app).resize(300, 200).move(300,0);
group.add(stretched, app);
group.add(proportional, app);
return true;
}
SpriteScene::~SpriteScene() {
}
| 25.692308
| 81
| 0.637725
|
projectivemotion
|
b787d8c8027dd9c81a46ae29f82fbb07871ae73c
| 1,077
|
cpp
|
C++
|
tests/test_connect_ports.cpp
|
verificationcontractor/sc_enhance
|
d4aa800a0ec20e420c1479fb6ba81c366eaf884f
|
[
"MIT"
] | 3
|
2021-01-10T13:35:11.000Z
|
2022-02-08T06:42:55.000Z
|
tests/test_connect_ports.cpp
|
verificationcontractor/sc_enhance
|
d4aa800a0ec20e420c1479fb6ba81c366eaf884f
|
[
"MIT"
] | 1
|
2022-02-07T19:19:23.000Z
|
2022-02-12T10:40:23.000Z
|
tests/test_connect_ports.cpp
|
verificationcontractor/sc_enhance
|
d4aa800a0ec20e420c1479fb6ba81c366eaf884f
|
[
"MIT"
] | null | null | null |
#include <systemc>
#include "sc_enhance.hpp"
using namespace sc_core;
using namespace sc_dt;
SC_MODULE(producer) {
SC_PROCESS_UTILS(producer);
sc_out_decl(bool, out_port);
SC_THREAD_DECLARE(logic)
SC_THREAD_BEGIN
bool x = false;
out_port.write(0);
sc_repeat(5) {
out_port.write(x);
x = !x;
wait(5, SC_NS);
}
sc_stop();
SC_THREAD_END
SC_CONS(producer) {}
};
SC_MODULE(consumer) {
SC_PROCESS_UTILS(consumer);
sc_in_decl(bool, in_port);
SC_METHOD_DECLARE(logic)
sensitive << in_port.pos();
SC_METHOD_BEGIN
std::cout << "Found posedge." << std::endl;
SC_METHOD_END
SC_CONS(consumer) {}
};
SC_MODULE(tb) {
SC_PROCESS_UTILS(tb);
sc_signal_decl(bool, signal);
sc_instance(producer, prod);
sc_instance(consumer, cons);
CONNECT_PORTS_BEGIN
prod.out_port(signal);
cons.in_port(signal);
CONNECT_PORTS_END
SC_CONS(tb) {}
};
int sc_main(int argc, char** argv) {
tb tb_inst("tb_inst");
sc_start();
return 0;
}
| 17.370968
| 49
| 0.628598
|
verificationcontractor
|
b78bbdae64676266973a03e73617c37f4f107cd1
| 6,244
|
cpp
|
C++
|
openEAR-0.1.0/src/SMILExtract.cpp
|
trimlab/Voice-Emotion-Detection
|
c7272dd2f70e2d4b8eee304e68578494d7ef624c
|
[
"MIT"
] | null | null | null |
openEAR-0.1.0/src/SMILExtract.cpp
|
trimlab/Voice-Emotion-Detection
|
c7272dd2f70e2d4b8eee304e68578494d7ef624c
|
[
"MIT"
] | null | null | null |
openEAR-0.1.0/src/SMILExtract.cpp
|
trimlab/Voice-Emotion-Detection
|
c7272dd2f70e2d4b8eee304e68578494d7ef624c
|
[
"MIT"
] | null | null | null |
/*F******************************************************************************
*
* openSMILE - open Speech and Music Interpretation by Large-space Extraction
* the open-source Munich Audio Feature Extraction Toolkit
* Copyright (C) 2008-2009 Florian Eyben, Martin Woellmer, Bjoern Schuller
*
*
* Institute for Human-Machine Communication
* Technische Universitaet Muenchen (TUM)
* D-80333 Munich, Germany
*
*
* If you use openSMILE or any code from openSMILE in your research work,
* you are kindly asked to acknowledge the use of openSMILE in your publications.
* See the file CITING.txt for details.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
******************************************************************************E*/
/*
This is the main commandline application
*/
#include <smileCommon.hpp>
#include <configManager.hpp>
#include <commandlineParser.hpp>
#include <componentManager.hpp>
#define MODULE "SMILExtract"
/************** Ctrl+C signal handler **/
#include <signal.h>
cComponentManager *cmanGlob = NULL;
void INThandler(int);
int ctrlc = 0;
void INThandler(int sig)
{
signal(sig, SIG_IGN);
if (cmanGlob != NULL) cmanGlob->requestAbort();
signal(SIGINT, INThandler);
ctrlc = 1;
}
/*******************************************/
int main(int argc, char *argv[])
{
try {
// set up the smile logger
LOGGER.setLogLevel(1);
LOGGER.enableConsoleOutput();
// commandline parser:
cCommandlineParser cmdline(argc,argv);
cmdline.addStr( "configfile", 'C', "Path to openSMILE config file", "smile.conf" );
cmdline.addInt( "loglevel", 'l', "Verbosity level (0-9)", 2 );
#ifdef DEBUG
cmdline.addBoolean( "debug", 'd', "Show debug messages (on/off)", 0 );
#endif
cmdline.addInt( "nticks", 't', "Number of ticks to process (-1 = infinite) (only works for single thread processing, i.e. nThreads=1)", -1 );
//cmdline.addBoolean( "configHelp", 'H', "Show documentation of registered config types (on/off)", 0 );
cmdline.addBoolean( "components", 'L', "Show component list", 0 );
cmdline.addStr( "configHelp", 'H', "Show documentation of registered config types (on/off/argument) (if an argument is given, show only documentation for config types beginning with the name given in the argument)", NULL, 0 );
cmdline.addBoolean( "ccmdHelp", 'c', "Show custom commandline option help (those specified in config file)", 0 );
cmdline.addStr( "logfile", 0, "set log file", "smile.log" );
cmdline.addBoolean( "nologfile", 0, "don't write to a log file (e.g. on a read-only filesystem)", 0 );
cmdline.addBoolean( "noconsoleoutput", 0, "don't output any messages to the console (log file is not affected by this option)", 0 );
cmdline.addBoolean( "appendLogfile", 0, "append log messages to an existing logfile instead of overwriting the logfile at every start", 0 );
int help = 0;
if (cmdline.doParse() == -1) {
LOGGER.setLogLevel(0);
help = 1;
}
if (argc <= 1) {
printf("\nNo commandline options were given.\n Please run ' SMILExtract -h ' to see some usage information!\n\n");
return 10;
}
if (cmdline.getBoolean("nologfile")) {
LOGGER.setLogFile((const char *)NULL,0,!(cmdline.getBoolean("noconsoleoutput")));
} else {
LOGGER.setLogFile(cmdline.getStr("logfile"),cmdline.getBoolean("appendLogfile"),!(cmdline.getBoolean("noconsoleoutput")));
}
LOGGER.setLogLevel(cmdline.getInt("loglevel"));
SMILE_MSG(2,"openSMILE starting!");
#ifdef DEBUG // ??
if (!cmdline.getBoolean("debug"))
LOGGER.setLogLevel(LOG_DEBUG, 0);
#endif
SMILE_MSG(2,"config file is: %s",cmdline.getStr("configfile"));
// create configManager:
cConfigManager *configManager = new cConfigManager(&cmdline);
cComponentManager *cMan = new cComponentManager(configManager,componentlist);
const char *selStr=NULL;
if (cmdline.isSet("configHelp")) {
selStr = cmdline.getStr("configHelp");
configManager->printTypeHelp(0,selStr);
help = 1;
}
if (cmdline.getBoolean("components")) {
cMan->printComponentList();
help = 1;
}
if (help==1) {
delete configManager;
delete cMan;
return -1;
}
// TODO: read config here and print ccmdHelp...
// add the file config reader:
configManager->addReader( new cFileConfigReader( cmdline.getStr("configfile") ) );
configManager->readConfig();
/* re-parse the command-line to include options created in the config file */
cmdline.doParse(1,0); // warn if unknown options are detected on the commandline
if (cmdline.getBoolean("ccmdHelp")) {
cmdline.showUsage();
delete configManager;
delete cMan;
return -1;
}
/* create all instances specified in the config file */
cMan->createInstances(0); // 0 = do not read config (we already did that above..)
/*
MAIN TICK LOOP :
*/
cmanGlob = cMan;
signal(SIGINT, INThandler); // install Ctrl+C signal handler
/* run single or mutli-threaded, depending on componentManager config in config file */
long long nTicks = cMan->runMultiThreaded(cmdline.getInt("nticks"));
/* it is important that configManager is deleted BEFORE componentManger!
(since component Manger unregisters plugin Dlls, which might have allocated configTypes, etc.) */
delete configManager;
delete cMan;
} catch(cSMILException *c) {
// free exception ??
return EXIT_ERROR;
}
if (ctrlc) return EXIT_CTRLC;
return EXIT_SUCCESS;
}
| 34.882682
| 230
| 0.662076
|
trimlab
|
b7974f5615870f97c9dcc40c9b346dca3cb54ddf
| 2,584
|
cpp
|
C++
|
src/Verde/graphics/Graphics.cpp
|
Cannedfood/Verde2D
|
3a09e2ecc6b62281e5190183faef55c8f0447d27
|
[
"CC0-1.0"
] | null | null | null |
src/Verde/graphics/Graphics.cpp
|
Cannedfood/Verde2D
|
3a09e2ecc6b62281e5190183faef55c8f0447d27
|
[
"CC0-1.0"
] | null | null | null |
src/Verde/graphics/Graphics.cpp
|
Cannedfood/Verde2D
|
3a09e2ecc6b62281e5190183faef55c8f0447d27
|
[
"CC0-1.0"
] | null | null | null |
#include "Graphics.hpp"
#include "StaticGraphics.hpp"
#include "AtlasAnimation.hpp"
#include <unordered_map>
#include <cstring>
#include <fstream>
void Graphics::writeOrPrefab(YAML::Emitter &to) {
if(mPrefab.size() != 0)
to << mPrefab;
else
write(to);
}
std::unordered_map<std::string, std::shared_ptr<Graphics>>* pGraphicsCache = nullptr;
void Graphics::InitCache() {
pGraphicsCache = new std::unordered_map<std::string, std::shared_ptr<Graphics>>;
}
void Graphics::FreeCache() {
delete pGraphicsCache;
}
void Graphics::CleanCache() {
// TODO: remove unique shared_ptr from cache
}
std::shared_ptr<Graphics> Graphics::Load(const std::string &s) {
if(pGraphicsCache) {
auto& p = (*pGraphicsCache)[s];
if(!p) {
if(s.size() > 4 && strcmp(s.c_str() + s.size() - 4, ".yml") == 0) {
std::ifstream file(s, std::ios::binary);
if(!file)
printf("Failed loading description file %s\n", s.c_str());
else {
YAML::Node data;
try {
data = YAML::Load(file);
p = Graphics::Load(data);
p->mPrefab = s;
}
catch(std::exception& e) {
printf("Failed loading %s: %s\n", s.c_str(), e.what());
return nullptr;
}
}
}
else {
p = std::make_shared<StaticGraphics>();
YAML::Node node;
node = s;
try {
if(!((StaticGraphics*)p.get())->load(node)) // Failed loading texture
p.reset();
}
catch(std::exception& e) {
printf("Failed loading %s: %s\n", s.c_str(), e.what());
return nullptr;
}
}
}
return p;
}
else {
auto p = std::make_shared<StaticGraphics>();
YAML::Node tmp;
tmp = s;
if(((StaticGraphics*)p.get())->load(tmp))
return p;
else
return nullptr;
}
}
std::shared_ptr<Graphics> Graphics::Load(YAML::Node n) {
if(!n) return nullptr;
if(n.IsScalar())
return Load(n.as<std::string>());
std::shared_ptr<Graphics> p;
YAML::Node type_n = n["type"];
if(type_n) {
std::string type_s = type_n.as<std::string>();
if(type_s != "default") {
if(type_s == "atlas-animation") {
p = std::make_shared<AtlasAnimation>();
if(((AtlasAnimation*) p.get())->load(n))
return p;
else {
printf("Failed loading atlas-animation\n");
return nullptr;
}
}
printf("Graphics: Type %s not supported\n", type_s.c_str());
return nullptr;
}
}
p = Load(n["texture"].as<std::string>());
if(YAML::Node nn = n["wrapping"]) {
if(nn.IsSequence()) {
p->setWrapping({
nn[0].as<float>(),
nn[1].as<float>()
});
}
else {
p->setWrapping(glm::vec2(nn.as<float>()));
}
}
return p;
}
| 20.83871
| 85
| 0.596362
|
Cannedfood
|
b797b8da62ddc030639442dbbcda567330b71efa
| 1,718
|
cpp
|
C++
|
Stats_Simulator/Varistein_BattleSimulator/Main.cpp
|
KuronoaScarlet/Varistein-Battle-Prototype
|
4409087771a0d00be0e707838858c6782435cf85
|
[
"MIT"
] | null | null | null |
Stats_Simulator/Varistein_BattleSimulator/Main.cpp
|
KuronoaScarlet/Varistein-Battle-Prototype
|
4409087771a0d00be0e707838858c6782435cf85
|
[
"MIT"
] | null | null | null |
Stats_Simulator/Varistein_BattleSimulator/Main.cpp
|
KuronoaScarlet/Varistein-Battle-Prototype
|
4409087771a0d00be0e707838858c6782435cf85
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "Utils.h"
#include <sys/types.h>
using namespace std;
int main()
{
srand(time(NULL));
float repeat = 10, simNum = 1000, allyWins, enemWins;
int atk = 4, def = 5, hp = 100, cc = 10;
int eatk = 10, edef = 10, ehp = 100, ecc = 10;
Ability* punch = new Ability(0, 20, 0, "Punch", Tag::OFFENSIVE);
Ability* chargedPunch = new Ability(2, 40, 0, "Charged Punch", Tag::OFFENSIVE);
Ability* cleave = new Ability(0, 40, 0, "Cleave", Tag::OFFENSIVE);
bool cont = true;
for (unsigned int i = 0; i < repeat; i++)
{
allyWins = enemWins = 0;
for (unsigned int i = 0; i < simNum; i++)
{
// Starter variables
Character* player = new Character(hp, def, atk, cc, "Nicole");
Character* enemy = new Character(ehp, edef, eatk, ecc, "Monster");
allies.push_back(player);
enemies.push_back(enemy);
player->abilities.push_back(punch);
player->abilities.push_back(chargedPunch);
enemy->abilities.push_back(cleave);
do
{
// Player Action
if (allies.size() != 0)
{
PerformSimulatedAction(allies, enemies);
cont = Check();
}
// Enemy Action
if (enemies.size() != 0)
{
PerformSimulatedAction(enemies, allies);
cont = Check();
}
} while (cont);
if (allies.size() != 0)
{
allyWins++;
allies[0]->abilities.clear();
allies.clear();
}
if (enemies.size() != 0)
{
enemWins++;
enemies[0]->abilities.clear();
enemies.clear();
}
cont = true;
}
float aWr = (allyWins / simNum) * 100.0f;
float eWr = (enemWins / simNum) * 100.0f;
std::cout << "Allies Wr: " << aWr << "%" << endl << "Enemies Wr: " << eWr << "%" << endl << endl;
}
system("pause");
return 0;
}
| 22.025641
| 99
| 0.587893
|
KuronoaScarlet
|
b799c1ee976390431876cf1e3d57d4b2066ecc41
| 7,197
|
cpp
|
C++
|
src/hssh/global_topological/graph.cpp
|
h2ssh/Vulcan
|
cc46ec79fea43227d578bee39cb4129ad9bb1603
|
[
"MIT"
] | 6
|
2020-03-29T09:37:01.000Z
|
2022-01-20T08:56:31.000Z
|
src/hssh/global_topological/graph.cpp
|
h2ssh/Vulcan
|
cc46ec79fea43227d578bee39cb4129ad9bb1603
|
[
"MIT"
] | 1
|
2021-03-05T08:00:50.000Z
|
2021-03-05T08:00:50.000Z
|
src/hssh/global_topological/graph.cpp
|
h2ssh/Vulcan
|
cc46ec79fea43227d578bee39cb4129ad9bb1603
|
[
"MIT"
] | 11
|
2019-05-13T00:04:38.000Z
|
2022-01-20T08:56:38.000Z
|
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file graph.cpp
* \author Collin Johnson
*
* Definition of convert_map_to_graph.
*/
#include <hssh/global_topological/graph.h>
#include <hssh/global_topological/topological_map.h>
#include <boost/range/adaptor/map.hpp>
#include <cassert>
namespace vulcan
{
namespace hssh
{
TopologicalVertex convert_path_segment_to_vertex(const GlobalPathSegment& segment,
const Point<float>& plusPosition,
const Point<float>& minusPosition);
TopologicalVertex convert_frontier_path_segment_to_vertex(const GlobalPathSegment& segment,
const Point<float>& position);
void add_explored_segment(const GlobalPathSegment& segment,
const TopologicalMap& map,
TopologicalGraph& graph);
void add_frontier_segment(const GlobalPathSegment& segment,
const TopologicalMap& map,
TopologicalGraph& graph);
GlobalPlace transition_place(const GlobalTransition& transition,
const GlobalPathSegment& segment,
const TopologicalMap& map);
TopologicalGraph convert_map_to_graph(const TopologicalMap& map)
{
auto& segments = map.segments();
TopologicalGraph graph;
for(auto& s : boost::adaptors::values(segments))
{
if(s->isFrontier())
{
add_frontier_segment(*s, map, graph);
}
else
{
add_explored_segment(*s, map, graph);
}
}
return graph;
}
TopologicalVertex convert_location_to_vertex(const GlobalLocation& location, const TopologicalMap& map)
{
if(location.areaType == AreaType::path_segment)
{
assert(map.getPathSegment(location.areaId));
GlobalPathSegment segment = *map.getPathSegment(location.areaId);
if(!segment.isFrontier())
{
const GlobalPlace plus = transition_place(segment.plusTransition(), segment, map);
const GlobalPlace minus = transition_place(segment.minusTransition(), segment, map);
return TopologicalVertex(convert_path_segment_to_vertex(segment,
map.referenceFrame(plus.id()).toPoint(),
map.referenceFrame(minus.id()).toPoint()));
}
else
{
auto transition = segment.plusTransition().isFrontier() ? segment.plusTransition() : segment.minusTransition();
GlobalPlace place = transition_place(transition, segment, map);
return TopologicalVertex(convert_frontier_path_segment_to_vertex(segment,
map.referenceFrame(place.id()).toPoint()));
}
}
else // at a place
{
return convert_place_to_vertex(*map.getPlace(location.areaId), map);
}
}
TopologicalVertex convert_place_to_vertex(const GlobalPlace& place, const TopologicalMap& map)
{
Point<float> location = map.referenceFrame(place.id()).toPoint();
return TopologicalVertex(place.id(), location, NodeData(place.id()));
}
TopologicalVertex convert_path_segment_to_vertex(const GlobalPathSegment& segment,
const Point<float>& plusPosition,
const Point<float>& minusPosition)
{
Point<float> segmentLocation((plusPosition.x + minusPosition.x) / 2.0f,
(plusPosition.y + minusPosition.y) / 2.0f);
return TopologicalVertex(segment.id(),
segmentLocation,
NodeData(segment.id(), true),
segment.lambda().magnitude());
}
TopologicalVertex convert_frontier_path_segment_to_vertex(const GlobalPathSegment& segment,
const Point<float>& position)
{
// For frontier segments, put the location halfway down the explored section of the segment.
Point<float> segmentLocation((position.x + segment.lambda().x) / 2.0f,
(position.y + segment.lambda().y) / 2.0f);
return TopologicalVertex(segment.id(),
segmentLocation,
NodeData(segment.id(), true),
segment.lambda().magnitude());
}
void add_explored_segment(const GlobalPathSegment& segment,
const TopologicalMap& map,
TopologicalGraph& graph)
{
// Ids for the edges in the graph are monotonically increasing. Can just use the current number of edges
// as the benchmark for determining the next id
auto plus = segment.plusTransition();
auto minus = segment.minusTransition();
TopologicalVertex plusVertex = convert_place_to_vertex(transition_place(plus, segment, map), map);
TopologicalVertex minusVertex = convert_place_to_vertex(transition_place(minus, segment, map), map);
TopologicalVertex segmentVertex = convert_path_segment_to_vertex(segment,
plusVertex.getPosition(),
minusVertex.getPosition());
TopologicalEdge plusEdge (graph.numEdges() + 1, plusVertex, segmentVertex, 0.0);
TopologicalEdge minusEdge(graph.numEdges() + 2, minusVertex, segmentVertex, 0.0);
graph.addVertex(plusVertex);
graph.addVertex(minusVertex);
graph.addVertex(segmentVertex);
graph.addEdge(plusEdge);
graph.addEdge(minusEdge);
}
void add_frontier_segment(const GlobalPathSegment& segment,
const TopologicalMap& map,
TopologicalGraph& graph)
{
auto transition = segment.plusTransition().isFrontier() ? segment.plusTransition() : segment.minusTransition();
TopologicalVertex placeVertex = convert_place_to_vertex(transition_place(transition, segment, map), map);
TopologicalVertex segmentVertex = convert_frontier_path_segment_to_vertex(segment, placeVertex.getPosition());
TopologicalEdge edge(graph.numEdges() + 1, placeVertex, segmentVertex, 0.0);
graph.addVertex(placeVertex);
graph.addVertex(segmentVertex);
graph.addEdge(edge);
}
GlobalPlace transition_place(const GlobalTransition& transition,
const GlobalPathSegment& segment,
const TopologicalMap& map)
{
return *map.getPlace(transition.otherArea(segment.toArea()).id());
}
} // namespace hssh
} // namespace vulcan
| 38.486631
| 123
| 0.610393
|
h2ssh
|
b7a21ee24a54fed701d3ae10fc5fffe59fead599
| 634
|
cpp
|
C++
|
source/glbinding/source/gl/functions_h.cpp
|
dutow/glbinding
|
ac12883c4387650c29dbbf01278b7198083750d9
|
[
"MIT"
] | null | null | null |
source/glbinding/source/gl/functions_h.cpp
|
dutow/glbinding
|
ac12883c4387650c29dbbf01278b7198083750d9
|
[
"MIT"
] | null | null | null |
source/glbinding/source/gl/functions_h.cpp
|
dutow/glbinding
|
ac12883c4387650c29dbbf01278b7198083750d9
|
[
"MIT"
] | 1
|
2021-07-01T07:45:44.000Z
|
2021-07-01T07:45:44.000Z
|
#include "../Binding_pch.h"
#include <glbinding/gl/functions.h>
using namespace glbinding;
namespace gl
{
void glHint(GLenum target, GLenum mode)
{
return Binding::Hint(target, mode);
}
void glHintPGI(GLenum target, GLint mode)
{
return Binding::HintPGI(target, mode);
}
void glHistogram(GLenum target, GLsizei width, GLenum internalformat, GLboolean sink)
{
return Binding::Histogram(target, width, internalformat, sink);
}
void glHistogramEXT(GLenum target, GLsizei width, GLenum internalformat, GLboolean sink)
{
return Binding::HistogramEXT(target, width, internalformat, sink);
}
} // namespace gl
| 16.684211
| 88
| 0.736593
|
dutow
|
b7a6cbea9cff8d1602e5b7f70ebf37a7fb6e41a8
| 9,647
|
cpp
|
C++
|
igraph/src/prpack_base_graph.cpp
|
jmazon/haskell-igraph
|
c000ec7939e73d4f563a85751aaeb973bfda7d40
|
[
"MIT"
] | 8
|
2017-07-22T21:49:37.000Z
|
2021-02-24T20:57:15.000Z
|
igraph/src/prpack_base_graph.cpp
|
jmazon/haskell-igraph
|
c000ec7939e73d4f563a85751aaeb973bfda7d40
|
[
"MIT"
] | 4
|
2018-05-22T17:48:16.000Z
|
2021-03-16T20:23:23.000Z
|
igraph/src/prpack_base_graph.cpp
|
jmazon/haskell-igraph
|
c000ec7939e73d4f563a85751aaeb973bfda7d40
|
[
"MIT"
] | 3
|
2017-09-08T07:49:21.000Z
|
2021-04-26T13:00:56.000Z
|
#include "prpack_base_graph.h"
#include "prpack_utils.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <limits>
using namespace prpack;
using namespace std;
void prpack_base_graph::initialize() {
heads = NULL;
tails = NULL;
vals = NULL;
}
prpack_base_graph::prpack_base_graph() {
initialize();
num_vs = num_es = 0;
}
prpack_base_graph::prpack_base_graph(const prpack_csc* g) {
initialize();
num_vs = g->num_vs;
num_es = g->num_es;
// fill in heads and tails
num_self_es = 0;
int* hs = g->heads;
int* ts = g->tails;
tails = new int[num_vs];
memset(tails, 0, num_vs*sizeof(tails[0]));
for (int h = 0; h < num_vs; ++h) {
const int start_ti = hs[h];
const int end_ti = (h + 1 != num_vs) ? hs[h + 1] : num_es;
for (int ti = start_ti; ti < end_ti; ++ti) {
const int t = ts[ti];
++tails[t];
if (h == t)
++num_self_es;
}
}
for (int i = 0, sum = 0; i < num_vs; ++i) {
const int temp = sum;
sum += tails[i];
tails[i] = temp;
}
heads = new int[num_es];
int* osets = new int[num_vs];
memset(osets, 0, num_vs*sizeof(osets[0]));
for (int h = 0; h < num_vs; ++h) {
const int start_ti = hs[h];
const int end_ti = (h + 1 != num_vs) ? hs[h + 1] : num_es;
for (int ti = start_ti; ti < end_ti; ++ti) {
const int t = ts[ti];
heads[tails[t] + osets[t]++] = h;
}
}
// clean up
delete[] osets;
}
prpack_base_graph::prpack_base_graph(const prpack_int64_csc* g) {
initialize();
// TODO remove the assert and add better behavior
assert(num_vs <= std::numeric_limits<int>::max());
num_vs = (int)g->num_vs;
num_es = (int)g->num_es;
// fill in heads and tails
num_self_es = 0;
int64_t* hs = g->heads;
int64_t* ts = g->tails;
tails = new int[num_vs];
memset(tails, 0, num_vs*sizeof(tails[0]));
for (int h = 0; h < num_vs; ++h) {
const int start_ti = (int)hs[h];
const int end_ti = (h + 1 != num_vs) ? (int)hs[h + 1] : num_es;
for (int ti = start_ti; ti < end_ti; ++ti) {
const int t = (int)ts[ti];
++tails[t];
if (h == t)
++num_self_es;
}
}
for (int i = 0, sum = 0; i < num_vs; ++i) {
const int temp = sum;
sum += tails[i];
tails[i] = temp;
}
heads = new int[num_es];
int* osets = new int[num_vs];
memset(osets, 0, num_vs*sizeof(osets[0]));
for (int h = 0; h < num_vs; ++h) {
const int start_ti = (int)hs[h];
const int end_ti = (h + 1 != num_vs) ? (int)hs[h + 1] : num_es;
for (int ti = start_ti; ti < end_ti; ++ti) {
const int t = (int)ts[ti];
heads[tails[t] + osets[t]++] = h;
}
}
// clean up
delete[] osets;
}
prpack_base_graph::prpack_base_graph(const prpack_csr* g) {
initialize();
assert(false);
// TODO
}
prpack_base_graph::prpack_base_graph(const prpack_edge_list* g) {
initialize();
num_vs = g->num_vs;
num_es = g->num_es;
// fill in heads and tails
num_self_es = 0;
int* hs = g->heads;
int* ts = g->tails;
tails = new int[num_vs];
memset(tails, 0, num_vs*sizeof(tails[0]));
for (int i = 0; i < num_es; ++i) {
++tails[ts[i]];
if (hs[i] == ts[i])
++num_self_es;
}
for (int i = 0, sum = 0; i < num_vs; ++i) {
const int temp = sum;
sum += tails[i];
tails[i] = temp;
}
heads = new int[num_es];
int* osets = new int[num_vs];
memset(osets, 0, num_vs*sizeof(osets[0]));
for (int i = 0; i < num_es; ++i)
heads[tails[ts[i]] + osets[ts[i]]++] = hs[i];
// clean up
delete[] osets;
}
prpack_base_graph::prpack_base_graph(const char* filename, const char* format, const bool weighted) {
initialize();
FILE* f = fopen(filename, "r");
const string s(filename);
const string t(format);
const string ext = (t == "") ? s.substr(s.rfind('.') + 1) : t;
if (ext == "smat") {
read_smat(f, weighted);
} else {
prpack_utils::validate(!weighted,
"Error: graph format is not compatible with weighted option.");
if (ext == "edges" || ext == "eg2") {
read_edges(f);
} else if (ext == "graph-txt") {
read_ascii(f);
} else {
prpack_utils::validate(false, "Error: invalid graph format.");
}
}
fclose(f);
}
prpack_base_graph::~prpack_base_graph() {
delete[] heads;
delete[] tails;
delete[] vals;
}
void prpack_base_graph::read_smat(FILE* f, const bool weighted) {
// read in header
double ignore = 0.0;
assert(fscanf(f, "%d %lf %d", &num_vs, &ignore, &num_es) == 3);
// fill in heads and tails
num_self_es = 0;
int* hs = new int[num_es];
int* ts = new int[num_es];
heads = new int[num_es];
tails = new int[num_vs];
double* vs = NULL;
if (weighted) {
vs = new double[num_es];
vals = new double[num_es];
}
memset(tails, 0, num_vs*sizeof(tails[0]));
for (int i = 0; i < num_es; ++i) {
assert(fscanf(f, "%d %d %lf",
&hs[i], &ts[i], &((weighted) ? vs[i] : ignore)) == 3);
++tails[ts[i]];
if (hs[i] == ts[i])
++num_self_es;
}
for (int i = 0, sum = 0; i < num_vs; ++i) {
const int temp = sum;
sum += tails[i];
tails[i] = temp;
}
int* osets = new int[num_vs];
memset(osets, 0, num_vs*sizeof(osets[0]));
for (int i = 0; i < num_es; ++i) {
const int idx = tails[ts[i]] + osets[ts[i]]++;
heads[idx] = hs[i];
if (weighted)
vals[idx] = vs[i];
}
// clean up
delete[] hs;
delete[] ts;
delete[] vs;
delete[] osets;
}
void prpack_base_graph::read_edges(FILE* f) {
vector<vector<int> > al;
int h, t;
num_es = num_self_es = 0;
while (fscanf(f, "%d %d", &h, &t) == 2) {
const int m = (h < t) ? t : h;
if ((int) al.size() < m + 1)
al.resize(m + 1);
al[t].push_back(h);
++num_es;
if (h == t)
++num_self_es;
}
num_vs = al.size();
heads = new int[num_es];
tails = new int[num_vs];
for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) {
tails[tails_i] = heads_i;
for (int j = 0; j < (int) al[tails_i].size(); ++j)
heads[heads_i++] = al[tails_i][j];
}
}
void prpack_base_graph::read_ascii(FILE* f) {
assert(fscanf(f, "%d", &num_vs) == 1);
while (getc(f) != '\n');
vector<int>* al = new vector<int>[num_vs];
num_es = num_self_es = 0;
char s[32];
for (int h = 0; h < num_vs; ++h) {
bool line_ended = false;
while (!line_ended) {
for (int i = 0; ; ++i) {
s[i] = getc(f);
if ('9' < s[i] || s[i] < '0') {
line_ended = s[i] == '\n';
if (i != 0) {
s[i] = '\0';
const int t = atoi(s);
al[t].push_back(h);
++num_es;
if (h == t)
++num_self_es;
}
break;
}
}
}
}
heads = new int[num_es];
tails = new int[num_vs];
for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) {
tails[tails_i] = heads_i;
for (int j = 0; j < (int) al[tails_i].size(); ++j)
heads[heads_i++] = al[tails_i][j];
}
delete[] al;
}
prpack_base_graph::prpack_base_graph(int nverts, int nedges,
std::pair<int,int>* edges) {
initialize();
num_vs = nverts;
num_es = nedges;
// fill in heads and tails
num_self_es = 0;
int* hs = new int[num_es];
int* ts = new int[num_es];
tails = new int[num_vs];
memset(tails, 0, num_vs*sizeof(tails[0]));
for (int i = 0; i < num_es; ++i) {
assert(edges[i].first >= 0 && edges[i].first < num_vs);
assert(edges[i].second >= 0 && edges[i].second < num_vs);
hs[i] = edges[i].first;
ts[i] = edges[i].second;
++tails[ts[i]];
if (hs[i] == ts[i])
++num_self_es;
}
for (int i = 0, sum = 0; i < num_vs; ++i) {
int temp = sum;
sum += tails[i];
tails[i] = temp;
}
heads = new int[num_es];
int* osets = new int[num_vs];
memset(osets, 0, num_vs*sizeof(osets[0]));
for (int i = 0; i < num_es; ++i)
heads[tails[ts[i]] + osets[ts[i]]++] = hs[i];
// clean up
delete[] hs;
delete[] ts;
delete[] osets;
}
/** Normalize the edge weights to sum to one.
*/
void prpack_base_graph::normalize_weights() {
if (!vals) {
// skip normalizing weights if not using values
return;
}
std::vector<double> rowsums(num_vs,0.);
// the graph is in a compressed in-edge list.
for (int i=0; i<num_vs; ++i) {
int end_ei = (i + 1 != num_vs) ? tails[i + 1] : num_es;
for (int ei=tails[i]; ei < end_ei; ++ei) {
int head = heads[ei];
rowsums[head] += vals[ei];
}
}
for (int i=0; i<num_vs; ++i) {
rowsums[i] = 1./rowsums[i];
}
for (int i=0; i<num_vs; ++i) {
int end_ei = (i + 1 != num_vs) ? tails[i + 1] : num_es;
for (int ei=tails[i]; ei < end_ei; ++ei) {
vals[ei] *= rowsums[heads[ei]];
}
}
}
| 28.883234
| 101
| 0.497357
|
jmazon
|
b7a6dad9078d2a05fed828dfa606c14d9ec831c4
| 181
|
cpp
|
C++
|
src/asserter.cpp
|
IanHG/cutee
|
b3b3eba5d78b4871847a5251d311b588e7ba97c0
|
[
"MIT"
] | null | null | null |
src/asserter.cpp
|
IanHG/cutee
|
b3b3eba5d78b4871847a5251d311b588e7ba97c0
|
[
"MIT"
] | 12
|
2018-06-18T12:56:33.000Z
|
2020-09-08T10:29:29.000Z
|
src/asserter.cpp
|
IanHG/cutee
|
b3b3eba5d78b4871847a5251d311b588e7ba97c0
|
[
"MIT"
] | null | null | null |
#include "../include/cutee/typedef.hpp"
#include "../include/cutee/suite.hpp"
namespace cutee
{
Cutee_thread_local suite* asserter::_suite_ptr = nullptr;
} /* namespace cutee */
| 18.1
| 57
| 0.729282
|
IanHG
|
b7aa4dd7bf752da74e01f9965d6e97d55b0fcc23
| 1,672
|
cpp
|
C++
|
MMOCoreORB/src/server/zone/objects/tangible/variables/SkillModMap.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 18
|
2017-02-09T15:36:05.000Z
|
2021-12-21T04:22:15.000Z
|
MMOCoreORB/src/server/zone/objects/tangible/variables/SkillModMap.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 61
|
2016-12-30T21:51:10.000Z
|
2021-12-10T20:25:56.000Z
|
MMOCoreORB/src/server/zone/objects/tangible/variables/SkillModMap.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 71
|
2017-01-01T05:34:38.000Z
|
2022-03-29T01:04:00.000Z
|
/*
* SkillModMap.cpp
*
* Created on: Jan 31, 2012
* Author: xyborn
*/
#include "SkillModMap.h"
SkillModMap::SkillModMap() {
skillMods.setNoDuplicateInsertPlan();
skillMods.setNullValue(0);
addSerializableVariables();
}
SkillModMap::SkillModMap(const SkillModMap& smm) : Object() {
skillMods = smm.skillMods;
addSerializableVariables();
}
SkillModMap& SkillModMap::operator=(const SkillModMap& smm) {
if (this == &smm)
return *this;
skillMods = smm.skillMods;
return *this;
}
void SkillModMap::add(SkillModMap* smm) {
for (int i = 0; i < smm->size(); ++i) {
VectorMapEntry<String, int64> entry = smm->skillMods.elementAt(i);
skillMods.put(entry.getKey(), skillMods.get(entry.getKey()) + entry.getValue());
}
}
void SkillModMap::add(VectorMap<String, int64>* map) {
for (int i = 0; i < map->size(); ++i) {
VectorMapEntry<String, int64> entry = map->elementAt(i);
skillMods.put(entry.getKey(), skillMods.get(entry.getKey()) + entry.getValue());
}
}
void SkillModMap::subtract(SkillModMap* smm) {
for (int i = 0; i < smm->skillMods.size(); ++i) {
VectorMapEntry<String, int64> entry = smm->skillMods.elementAt(i);
int val = skillMods.get(entry.getKey()) - entry.getValue();
if (val <= 0) {
skillMods.drop(entry.getKey());
} else {
skillMods.put(entry.getKey(), val);
}
}
}
void SkillModMap::subtract(VectorMap<String, int64>* map) {
for (int i = 0; i < map->size(); ++i) {
VectorMapEntry<String, int64> entry = map->elementAt(i);
int val = skillMods.get(entry.getKey()) - entry.getValue();
if (val <= 0) {
skillMods.drop(entry.getKey());
} else {
skillMods.put(entry.getKey(), val);
}
}
}
| 22.293333
| 82
| 0.657895
|
V-Fib
|
b7ac72637aa6f8b8a7cc7147ea7462a528fffbc1
| 57
|
cpp
|
C++
|
src/sink.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
src/sink.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
src/sink.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
#include "sink.hpp"
namespace jhm
{
} // namespace jhm.
| 11.4
| 20
| 0.666667
|
JacknJo
|
b7ad65a26c97cb14a2497f45b667f3303bafb8fc
| 10,685
|
cpp
|
C++
|
test/acl_sampler_test.cpp
|
sherry-yuan/fpga-runtime-for-opencl
|
df4be1924268cdb7841da2a6b0618b7bb8a47628
|
[
"BSD-3-Clause"
] | 11
|
2021-11-19T20:52:09.000Z
|
2022-03-23T10:41:42.000Z
|
test/acl_sampler_test.cpp
|
sherry-yuan/fpga-runtime-for-opencl
|
df4be1924268cdb7841da2a6b0618b7bb8a47628
|
[
"BSD-3-Clause"
] | 49
|
2021-11-08T18:26:37.000Z
|
2022-03-31T14:25:29.000Z
|
test/acl_sampler_test.cpp
|
sherry-yuan/fpga-runtime-for-opencl
|
df4be1924268cdb7841da2a6b0618b7bb8a47628
|
[
"BSD-3-Clause"
] | 6
|
2021-11-02T17:45:37.000Z
|
2022-02-12T00:47:15.000Z
|
// Copyright (C) 2010-2021 Intel Corporation
// SPDX-License-Identifier: BSD-3-Clause
#if ACL_SUPPORT_IMAGES == 1
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100) // unreferenced formal parameter
#endif
#include <CppUTest/TestHarness.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <CL/opencl.h>
#include <acl.h>
#include <acl_types.h>
#include <acl_util.h>
#include "acl_test.h"
MT_TEST_GROUP(acl_sampler) {
enum { MAX_DEVICES = 100 };
void setup() {
if (threadNum() == 0) {
acl_test_setup_generic_system();
}
syncThreads();
m_callback_count = 0;
m_callback_errinfo = 0;
this->load();
}
void teardown() {
syncThreads();
if (threadNum() == 0) {
acl_test_teardown_generic_system();
}
acl_test_run_standard_teardown_checks();
}
void load(void) {
CHECK_EQUAL(CL_SUCCESS, clGetPlatformIDs(1, &m_platform, 0));
ACL_LOCKED(CHECK(acl_platform_is_valid(m_platform)));
CHECK_EQUAL(CL_SUCCESS,
clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_ALL, MAX_DEVICES,
&m_device[0], &m_num_devices));
CHECK(m_num_devices >= 3);
}
protected:
cl_platform_id m_platform;
cl_device_id m_device[MAX_DEVICES];
cl_uint m_num_devices;
public:
cl_ulong m_callback_count;
const char *m_callback_errinfo;
};
static void CL_CALLBACK notify_me(const char *errinfo, const void *private_info,
size_t cb, void *user_data) {
CppUTestGroupacl_sampler *inst = (CppUTestGroupacl_sampler *)user_data;
if (inst) {
inst->m_callback_count++;
inst->m_callback_errinfo = errinfo;
}
cb = cb; // avoid warning on windows
private_info = private_info; // avoid warning on windows
}
MT_TEST(acl_sampler, basic) {
cl_sampler sampler;
cl_int status;
cl_sampler_properties sampler_properties[7];
cl_uint ref_count;
cl_context test_context;
cl_addressing_mode test_addressing_mode;
cl_filter_mode test_filter_mode;
cl_bool test_normalized_coord;
cl_context context =
clCreateContext(0, m_num_devices, &m_device[0], notify_me, this, &status);
CHECK_EQUAL(CL_SUCCESS, status);
// Just grab devices that are present.
CHECK(m_device[0]);
CHECK(m_device[0]->present);
CHECK(m_device[1]);
CHECK(m_device[1]->present);
CHECK(m_device[2]);
CHECK(m_device[2]->present);
m_num_devices = 3;
// Bad contexts
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSampler(0, CL_TRUE, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST,
&status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_CONTEXT, status);
syncThreads();
acl_set_allow_invalid_type<cl_context>(1);
syncThreads();
status = CL_SUCCESS;
struct _cl_context fake_context = {0};
sampler = clCreateSampler(&fake_context, CL_TRUE, CL_ADDRESS_REPEAT,
CL_FILTER_NEAREST, &status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_CONTEXT, status);
syncThreads();
acl_set_allow_invalid_type<cl_context>(0);
syncThreads();
// Invalid value
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSampler(context, CL_TRUE, CL_ADDRESS_REPEAT + 6,
CL_FILTER_NEAREST, &status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_VALUE, status);
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSampler(context, CL_TRUE, CL_ADDRESS_REPEAT,
CL_FILTER_NEAREST + 2, &status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_VALUE, status);
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSampler(context, CL_TRUE + 2, CL_ADDRESS_REPEAT,
CL_FILTER_NEAREST, &status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_VALUE, status);
sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS + 5;
sampler_properties[1] = CL_TRUE;
sampler_properties[2] = 0;
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSamplerWithProperties(context, sampler_properties, &status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_VALUE, status);
sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS;
sampler_properties[1] = CL_TRUE + 3;
sampler_properties[2] = 0;
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSamplerWithProperties(context, sampler_properties, &status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_VALUE, status);
sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS;
sampler_properties[1] = CL_TRUE;
sampler_properties[2] = CL_SAMPLER_NORMALIZED_COORDS;
sampler_properties[3] = CL_TRUE;
sampler_properties[4] = 0;
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSamplerWithProperties(context, sampler_properties, &status);
CHECK_EQUAL(0, sampler);
CHECK_EQUAL(CL_INVALID_VALUE, status);
// Invalid sampler
CHECK_EQUAL(CL_INVALID_SAMPLER, clReleaseSampler(0));
CHECK_EQUAL(CL_INVALID_SAMPLER, clReleaseSampler((cl_sampler)&status));
CHECK_EQUAL(CL_INVALID_SAMPLER,
clGetSamplerInfo(0, CL_SAMPLER_REFERENCE_COUNT, 0, 0, 0));
CHECK_EQUAL(CL_INVALID_SAMPLER,
clGetSamplerInfo((cl_sampler)&status, CL_SAMPLER_REFERENCE_COUNT,
0, 0, 0));
// Good sampler
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSampler(context, CL_TRUE, CL_ADDRESS_REPEAT,
CL_FILTER_NEAREST, &status);
CHECK(sampler != 0);
CHECK_EQUAL(CL_SUCCESS, status);
status = clReleaseSampler(sampler);
CHECK_EQUAL(CL_SUCCESS, status);
sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS;
sampler_properties[1] = CL_TRUE;
sampler_properties[2] = 0;
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSamplerWithProperties(context, sampler_properties, &status);
CHECK(sampler != 0);
CHECK_EQUAL(CL_SUCCESS, status);
status = clReleaseSampler(sampler);
CHECK_EQUAL(CL_SUCCESS, status);
sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS;
sampler_properties[1] = CL_FALSE;
sampler_properties[2] = CL_SAMPLER_ADDRESSING_MODE;
sampler_properties[3] = CL_ADDRESS_REPEAT;
sampler_properties[4] = CL_SAMPLER_FILTER_MODE;
sampler_properties[5] = CL_FILTER_LINEAR;
sampler_properties[6] = 0;
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSamplerWithProperties(context, sampler_properties, &status);
CHECK(sampler != 0);
CHECK_EQUAL(CL_SUCCESS, status);
status = clReleaseSampler(sampler);
CHECK_EQUAL(CL_SUCCESS, status);
CHECK_EQUAL(6, this->m_callback_count);
sampler = clCreateSamplerWithProperties(context, sampler_properties, &status);
CHECK_EQUAL(CL_SUCCESS, status);
// let all threads get different samplers before continuing
syncThreads();
CHECK_EQUAL(CL_INVALID_SAMPLER, clRetainSampler(0));
CHECK_EQUAL(CL_INVALID_SAMPLER, clRetainSampler((cl_sampler)&status));
CHECK_EQUAL(CL_SUCCESS, clRetainSampler(sampler));
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &ref_count, NULL));
CHECK_EQUAL(2, ref_count);
CHECK_EQUAL(CL_SUCCESS, clRetainSampler(sampler));
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &ref_count, NULL));
CHECK_EQUAL(3, ref_count);
CHECK_EQUAL(CL_SUCCESS,
clGetSamplerInfo(sampler, CL_SAMPLER_CONTEXT, sizeof(cl_context),
&test_context, NULL));
CHECK_EQUAL(context, test_context);
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_ADDRESSING_MODE,
sizeof(cl_addressing_mode),
&test_addressing_mode, NULL));
CHECK_EQUAL(CL_ADDRESS_REPEAT, test_addressing_mode);
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_FILTER_MODE,
sizeof(cl_filter_mode),
&test_filter_mode, NULL));
CHECK_EQUAL(CL_FILTER_LINEAR, test_filter_mode);
CHECK_EQUAL(CL_SUCCESS,
clGetSamplerInfo(sampler, CL_SAMPLER_NORMALIZED_COORDS,
sizeof(cl_bool), &test_normalized_coord, NULL));
CHECK_EQUAL(CL_FALSE, test_normalized_coord);
CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler));
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &ref_count, NULL));
CHECK_EQUAL(2, ref_count);
CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler));
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &ref_count, NULL));
CHECK_EQUAL(1, ref_count);
CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler));
CHECK_EQUAL(CL_INVALID_SAMPLER,
clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &ref_count, NULL));
// don't let any thread create a new sampler before we check
// CL_INVALID_SAMPLER above using the old sampler pointer
syncThreads();
// Check that default values are used when nothing is provided
sampler_properties[0] = 0;
sampler = (cl_sampler)1;
status = CL_SUCCESS;
sampler = clCreateSamplerWithProperties(context, sampler_properties, &status);
CHECK_EQUAL(CL_SUCCESS, status);
// let all threads get different samplers before continuing
syncThreads();
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_ADDRESSING_MODE,
sizeof(cl_addressing_mode),
&test_addressing_mode, NULL));
CHECK_EQUAL(CL_ADDRESS_CLAMP, test_addressing_mode);
CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_FILTER_MODE,
sizeof(cl_filter_mode),
&test_filter_mode, NULL));
CHECK_EQUAL(CL_FILTER_NEAREST, test_filter_mode);
CHECK_EQUAL(CL_SUCCESS,
clGetSamplerInfo(sampler, CL_SAMPLER_NORMALIZED_COORDS,
sizeof(cl_bool), &test_normalized_coord, NULL));
CHECK_EQUAL(CL_TRUE, test_normalized_coord);
CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler));
CHECK_EQUAL(CL_INVALID_SAMPLER,
clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &ref_count, NULL));
CHECK_EQUAL(CL_SUCCESS, clReleaseContext(context));
}
#endif
| 34.691558
| 80
| 0.69153
|
sherry-yuan
|
b7b0d41ce7c0d9e3f31ebf247c1b6a5a57f9b276
| 6,982
|
cpp
|
C++
|
source/engine/adl_editor/adlSpawn_editor.cpp
|
AtakanFire/adlGame
|
d617988b166c1cdd50dd7acb26507231a502a537
|
[
"MIT"
] | 6
|
2018-08-28T19:52:03.000Z
|
2020-12-02T13:59:00.000Z
|
source/engine/adl_editor/adlSpawn_editor.cpp
|
AtakanFire/adlGame
|
d617988b166c1cdd50dd7acb26507231a502a537
|
[
"MIT"
] | 16
|
2019-03-01T09:37:33.000Z
|
2019-05-13T13:10:54.000Z
|
source/engine/adl_editor/adlSpawn_editor.cpp
|
AtakanFire/adlGame
|
d617988b166c1cdd50dd7acb26507231a502a537
|
[
"MIT"
] | 4
|
2018-10-29T18:04:18.000Z
|
2021-02-05T13:13:00.000Z
|
#include "adlSpawn_editor.h"
#include "engine/adl_debug/imgui/imgui.h"
#include "engine/adl_entities/adlEntity_factory.h"
#include "engine/adl_resource/adlResource_manager.h"
adlSpawn_editor::adlSpawn_editor()
{
}
adlSpawn_editor::~adlSpawn_editor()
{
}
void adlSpawn_editor::init()
{
spawn_transform_.scale = adlVec3(1.0f);
}
void adlSpawn_editor::update(adlScene_manager* scene_manager)
{
is_visible_ = true;
adlEntity_factory* factory = &adlEntity_factory::get();
adlResource_manager* adl_rm = &adlResource_manager::get();
const std::vector<std::string>& entities = adl_rm->get_all_entity_names();
ImGui::Begin("Spawn Editor");
for (unsigned int i = 0; i < entities.size(); i++)
{
ImGui::Indent();
if (ImGui::Button(entities[i].c_str()))
{
scene_manager->add_entity_to_scene(entities[i].c_str());
//factory->construct_entity(entities[i]);
}
ImGui::Unindent();
}
ImGui::End();
//ImGui::Begin("Spawn Editor");
//if (ImGui::CollapsingHeader("Entities"))
//{
// ImGui::Indent();
// for (size_t i = 0; i < actors.size(); i++)
// {
// if (ImGui::CollapsingHeader(actors[i].data()))
// {
// ImGui::Indent();
// adlVec3 actor_position = spawn_transform_.o;
// adlVec3 actor_rotation = spawn_transform_.rot;
// adlVec3 actor_scale = spawn_transform_.scale;
// if (ImGui::CollapsingHeader("Transform"))
// {
// ImGui::Indent();
// if (ImGui::CollapsingHeader("Position"))
// {
// ImGui::Text("Position(x,y,z)");
// std::string label = actors[i] + " Pos";
// float actorPos[3] = { actor_position.x, actor_position.y, actor_position.z };
// ImGui::InputFloat3(label.data(), &actorPos[0], 2);
// actor_position = adlVec3(actorPos[0], actorPos[1], actorPos[2]);
// }
// if (ImGui::CollapsingHeader("Rotation"))
// {
// ImGui::Text("Rotation(x,y,z)");
// std::string label = actors[i] + " Rot";
// float actorRot[3] = { adlMath::rad_to_deg(actor_rotation.x), adlMath::rad_to_deg(actor_rotation.y), adlMath::rad_to_deg(actor_rotation.z) };
// ImGui::InputFloat3(label.data(), &actorRot[0], 2);
// actor_rotation = adlVec3(adlMath::deg_to_rad(actorRot[0]), adlMath::deg_to_rad(actorRot[1]), adlMath::deg_to_rad(actorRot[2]));
// }
// if (ImGui::CollapsingHeader("Scale"))
// {
// ImGui::Text("Scale(x,y,z)");
// std::string label = actors[i] + " Scale";
// float actorScale[3] = { actor_scale.x, actor_scale.y, actor_scale.z };
// ImGui::InputFloat3(label.data(), &actorScale[0], 2);
// actor_scale = adlVec3(actorScale[0], actorScale[1], actorScale[2]);
// }
// spawn_transform_.o = actor_position;
// spawn_transform_.rot = actor_rotation;
// spawn_transform_.scale = actor_scale;
// ImGui::Unindent();
// }
// if (ImGui::CollapsingHeader("Actor Properties"))
// {
// ImGui::Indent();
// if (ImGui::CollapsingHeader("Model"))
// {
// ImGui::Indent();
// if (ImGui::CollapsingHeader("Mesh"))
// {
// ImGui::Indent();
// static char model_name[20] = {};
// ImGui::Text("Mesh(Name)");
// ImGui::InputText("(max 20 char)", model_name, sizeof(model_name));
// if (ImGui::Button("Refresh Mesh"))
// {
// spawn_model_ = adl_rm->get_model(model_name);
// }
// ImGui::Unindent();
// }
// if (ImGui::CollapsingHeader("Material"))
// {
// ImGui::Indent();
// static char material_name[20] = {};
// ImGui::Text("Material(Name)");
// ImGui::InputText("(max 20 char)", material_name, sizeof(material_name));
// if (ImGui::Button("Refresh Material"))
// {
// spawn_material_ = adl_rm->get_material(material_name);
// }
// ImGui::Unindent();
// }
// ImGui::Unindent();
// }
// ImGui::Unindent();
// }
// std::string button_label = "Spawn " + actors[i] + " actor";
// if (ImGui::Button(button_label.data()))
// {
// ImGui::Indent();
// //adlActor_shared_ptr spawned_actor = scene_manager->spawn_actor(actors[i].data(), spawn_transform_.o, spawn_transform_.rot, spawn_transform_.scale);
// if (spawn_model_ != nullptr)
// {
// //spawned_actor->set_model(spawn_model_);
// spawn_model_ = adl_rm->get_model("");
// }
// if (spawn_material_ != nullptr)
// {
// //spawned_actor->set_material(spawn_material_);
// spawn_material_ = adl_rm->get_material("");
// }
// //is_visible_ = false;
// ImGui::Unindent();
// }
// ImGui::Unindent();
// }
// }
// ImGui::Unindent();
//}
//if (ImGui::CollapsingHeader("Lights"))
//{
// ImGui::Indent();
// for (size_t i = 0; i < lights.size(); i++)
// {
// if (ImGui::CollapsingHeader(lights[i].data()))
// {
// ImGui::Indent();
// adlVec3 light_position = spawn_transform_.o;
// adlVec3 light_rotation = spawn_transform_.rot;
// adlVec3 light_scale = spawn_transform_.scale;
// if (ImGui::CollapsingHeader("Transform"))
// {
// ImGui::Indent();
// if (ImGui::CollapsingHeader("Position"))
// {
// ImGui::Text("Position(x,y,z)");
// std::string label = lights[i] + " Pos";
// float lightPos[3] = { light_position.x, light_position.y, light_position.z };
// ImGui::InputFloat3(label.data(), &lightPos[0], 2);
// light_position = adlVec3(lightPos[0], lightPos[1], lightPos[2]);
// }
// if (ImGui::CollapsingHeader("Rotation"))
// {
// ImGui::Text("Rotation(x,y,z)");
// std::string label = lights[i] + " Rot";
// float lightRot[3] = { adlMath::rad_to_deg(light_rotation.x), adlMath::rad_to_deg(light_rotation.y), adlMath::rad_to_deg(light_rotation.z) };
// ImGui::InputFloat3(label.data(), &lightRot[0], 2);
// light_rotation = adlVec3(adlMath::deg_to_rad(lightRot[0]), adlMath::deg_to_rad(lightRot[1]), adlMath::deg_to_rad(lightRot[2]));
// }
// if (ImGui::CollapsingHeader("Scale"))
// {
// ImGui::Text("Scale(x,y,z)");
// std::string label = lights[i] + " Scale";
// float lightScale[3] = { light_scale.x, light_scale.y, light_scale.z };
// ImGui::InputFloat3(label.data(), &lightScale[0], 2);
// light_scale = adlVec3(lightScale[0], lightScale[1], lightScale[2]);
// }
// spawn_transform_.o = light_position;
// spawn_transform_.rot = light_rotation;
// spawn_transform_.scale = light_scale;
// ImGui::Unindent();
// }
// std::string button_label = "Spawn " + lights[i] + " light";
// if (ImGui::Button(button_label.data()))
// {
// ImGui::Indent();
// //scene_manager->spawn_light(lights[i].data(), spawn_transform_.o, spawn_transform_.rot, spawn_transform_.scale);
// is_visible_ = false;
// ImGui::Unindent();
// }
// ImGui::Unindent();
// }
// }
// ImGui::Unindent();
//}
//ImGui::End();
}
bool adlSpawn_editor::get_visible()
{
return is_visible_;
}
| 26.24812
| 156
| 0.600687
|
AtakanFire
|
b7b1421c6992b2f7df2f48a563a55201391df9a3
| 2,330
|
hpp
|
C++
|
test/TestApp/Source/MaidChanGame.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
test/TestApp/Source/MaidChanGame.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
test/TestApp/Source/MaidChanGame.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_MAIDCHANGAME_FB2D5E96_HPP
#define POMDOG_MAIDCHANGAME_FB2D5E96_HPP
#include <Pomdog.Experimental/InGameEditor/detail/EditorBackground.hpp>
#include <Pomdog.Experimental/Skeletal2D/detail/AnimationTimer.hpp>
#include <Pomdog.Experimental/Experimental.hpp>
#include <Pomdog/Pomdog.hpp>
namespace Pomdog {
class SpriteBatch;
class SpriteRenderer;
}// namespace Pomdog
namespace TestApp {
using namespace Pomdog;
class MaidChanGame: public Game {
public:
explicit MaidChanGame(std::shared_ptr<GameHost> const& gameHost);
~MaidChanGame();
void Initialize();
void Update();
void Draw();
private:
void DrawSprites();
private:
std::shared_ptr<GameHost> gameHost;
std::shared_ptr<GameWindow> window;
std::shared_ptr<GraphicsDevice> graphicsDevice;
std::shared_ptr<GraphicsContext> graphicsContext;
std::shared_ptr<Texture2D> texture;
std::unique_ptr<SpriteRenderer> spriteRenderer;
std::shared_ptr<SamplerState> samplerPoint;
std::shared_ptr<RenderTarget2D> renderTarget;
std::unique_ptr<FXAA> fxaa;
std::unique_ptr<ScreenQuad> screenQuad;
std::unique_ptr<SceneEditor::InGameEditor> gameEditor;
std::unique_ptr<SceneEditor::EditorBackground> editorBackground;
std::shared_ptr<UI::ScenePanel> scenePanel;
std::shared_ptr<UI::Slider> slider1;
std::shared_ptr<UI::Slider> slider2;
std::shared_ptr<UI::ToggleSwitch> toggleSwitch1;
std::shared_ptr<UI::ToggleSwitch> toggleSwitch2;
std::shared_ptr<UI::ToggleSwitch> toggleSwitch3;
std::shared_ptr<UI::ToggleSwitch> toggleSwitch4;
GameWorld gameWorld;
GameObject mainCamera;
AnimationSystem animationSystem;
std::shared_ptr<Skeleton> maidSkeleton;
std::shared_ptr<SkeletonPose> maidSkeletonPose;
std::shared_ptr<AnimationState> maidAnimationState;
std::shared_ptr<Texture2D> maidTexture;
std::vector<Matrix3x2> maidGlobalPose;
Detail::Skeletal2D::AnimationTimer maidAnimationTimer;
Skin maidSkin;
std::vector<Detail::Skeletal2D::SpriteAnimationTrack> maidSpriteAnimationTracks;
ConnectionList connections;
Viewport clientViewport;
};
}// namespace TestApp
#endif // POMDOG_MAIDCHANGAME_FB2D5E96_HPP
| 28.414634
| 84
| 0.762661
|
bis83
|
5d9a97058e433a3b6d127826efd220407aac5e5a
| 694
|
cpp
|
C++
|
Array/Kadane's Algorithm/05. PrintLongestEvenOddSubarray.cpp
|
sohamnandi77/Cpp-Data-Structures-And-Algorithm
|
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
|
[
"MIT"
] | 2
|
2021-05-21T17:10:02.000Z
|
2021-05-29T05:13:06.000Z
|
Array/Kadane's Algorithm/05. PrintLongestEvenOddSubarray.cpp
|
sohamnandi77/Cpp-Data-Structures-And-Algorithm
|
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
|
[
"MIT"
] | null | null | null |
Array/Kadane's Algorithm/05. PrintLongestEvenOddSubarray.cpp
|
sohamnandi77/Cpp-Data-Structures-And-Algorithm
|
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
void printLongestEvenOddOP(int arr[], int n)
{
int res = 1, curr = 1, endIndex = 0;
for (int i = 1; i < n; i++)
{
if ((arr[i] % 2 == 0 && arr[i - 1] % 2 != 0) || (arr[i] % 2 != 0 && arr[i - 1] % 2 == 0))
{
curr++;
if (res < curr)
{
res = curr;
endIndex = i;
}
}
else
curr = 1;
}
int startIndex = endIndex - res + 1;
for (int i = startIndex; i <= endIndex; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {5, 10, 20, 6, 3, 8}, n = 6;
printLongestEvenOddOP(arr, n);
return 0;
}
| 21.6875
| 97
| 0.403458
|
sohamnandi77
|
5d9c42384fa7a6528beb8ffb7c9d16dfa8a4cc67
| 3,429
|
cpp
|
C++
|
Source/TitaniumKit/src/Contacts/Group.cpp
|
garymathews/titanium_mobile_windows
|
ff2a02d096984c6cad08f498e1227adf496f84df
|
[
"Apache-2.0"
] | 20
|
2015-04-02T06:55:30.000Z
|
2022-03-29T04:27:30.000Z
|
Source/TitaniumKit/src/Contacts/Group.cpp
|
garymathews/titanium_mobile_windows
|
ff2a02d096984c6cad08f498e1227adf496f84df
|
[
"Apache-2.0"
] | 692
|
2015-04-01T21:05:49.000Z
|
2020-03-10T10:11:57.000Z
|
Source/TitaniumKit/src/Contacts/Group.cpp
|
garymathews/titanium_mobile_windows
|
ff2a02d096984c6cad08f498e1227adf496f84df
|
[
"Apache-2.0"
] | 22
|
2015-04-01T20:57:51.000Z
|
2022-01-18T17:33:15.000Z
|
/**
* TitaniumKit Titanium.Contacts.Group
*
* Copyright (c) 2015-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#include "Titanium/Contacts/Group.hpp"
#include "Titanium/Contacts/Person.hpp"
#include "Titanium/detail/TiImpl.hpp"
namespace Titanium
{
namespace Contacts
{
Group::Group(const JSContext& js_context, const std::vector<JSValue>& arguments) TITANIUM_NOEXCEPT
: Module(js_context, "Ti.Contacts.Group")
{
}
TITANIUM_PROPERTY_READ(Group, std::string, identifier)
TITANIUM_PROPERTY_READWRITE(Group, std::string, name)
TITANIUM_PROPERTY_READWRITE(Group, uint32_t, recordId)
void Group::add(const std::shared_ptr<Person>& person) TITANIUM_NOEXCEPT
{
TITANIUM_LOG_WARN("Group::add: Unimplemented");
}
std::vector<std::shared_ptr<Person>> Group::members() TITANIUM_NOEXCEPT
{
TITANIUM_LOG_WARN("Group::members: Unimplemented");
return std::vector<std::shared_ptr<Person>>();
}
void Group::remove(const std::shared_ptr<Person>& person) TITANIUM_NOEXCEPT
{
TITANIUM_LOG_WARN("Group::remove: Unimplemented");
}
std::vector<std::shared_ptr<Person>> Group::sortedMembers(const SORT& sortBy) TITANIUM_NOEXCEPT
{
TITANIUM_LOG_WARN("Group::sortedMembers: Unimplemented");
return std::vector<std::shared_ptr<Person>>();
}
void Group::JSExportInitialize() {
JSExport<Group>::SetClassVersion(1);
JSExport<Group>::SetParent(JSExport<Module>::Class());
TITANIUM_ADD_PROPERTY_READONLY(Group, identifier);
TITANIUM_ADD_PROPERTY(Group, name);
TITANIUM_ADD_PROPERTY(Group, recordId);
TITANIUM_ADD_FUNCTION(Group, add);
TITANIUM_ADD_FUNCTION(Group, members);
TITANIUM_ADD_FUNCTION(Group, remove);
TITANIUM_ADD_FUNCTION(Group, sortedMembers);
TITANIUM_ADD_FUNCTION(Group, getName);
TITANIUM_ADD_FUNCTION(Group, setName);
TITANIUM_ADD_FUNCTION(Group, getRecordId);
TITANIUM_ADD_FUNCTION(Group, setRecordId);
}
TITANIUM_PROPERTY_GETTER_STRING(Group, identifier);
TITANIUM_PROPERTY_GETTER_STRING(Group, name);
TITANIUM_PROPERTY_SETTER_STRING(Group, name);
TITANIUM_PROPERTY_GETTER_UINT(Group, recordId);
TITANIUM_PROPERTY_SETTER_UINT(Group, recordId);
TITANIUM_FUNCTION(Group, add)
{
ENSURE_OBJECT_AT_INDEX(person, 0);
add(person.GetPrivate<Person>());
return get_context().CreateUndefined();
}
TITANIUM_FUNCTION(Group, members)
{
std::vector<JSValue> values;
for (auto value : members()) {
values.push_back(value->get_object());
}
return get_context().CreateArray(values);
}
TITANIUM_FUNCTION(Group, remove)
{
ENSURE_OBJECT_AT_INDEX(person, 0);
remove(person.GetPrivate<Person>());
return get_context().CreateUndefined();
}
TITANIUM_FUNCTION(Group, sortedMembers)
{
ENSURE_ENUM_AT_INDEX(sortBy, 0, SORT);
std::vector<JSValue> values;
for (auto value : sortedMembers(sortBy)) {
values.push_back(value->get_object());
}
return get_context().CreateArray(values);
}
TITANIUM_FUNCTION_AS_GETTER(Group, getIdentifier, identifier)
TITANIUM_FUNCTION_AS_GETTER(Group, getName, name)
TITANIUM_FUNCTION_AS_SETTER(Group, setName, name)
TITANIUM_FUNCTION_AS_GETTER(Group, getRecordId, recordId)
TITANIUM_FUNCTION_AS_SETTER(Group, setRecordId, recordId)
} // namespace Contacts
} // namespace Titanium
| 29.059322
| 100
| 0.748906
|
garymathews
|
5da16658b607fe7a8707377b605c51f20f3efe09
| 6,555
|
cpp
|
C++
|
experimental/graphite/src/DrawWriter.cpp
|
stayf/skia
|
454c04e8f3b45ba0c518cbdd49f67bfb95d83c35
|
[
"BSD-3-Clause"
] | 5
|
2022-02-12T07:52:56.000Z
|
2022-03-10T23:55:51.000Z
|
experimental/graphite/src/DrawWriter.cpp
|
stayf/skia
|
454c04e8f3b45ba0c518cbdd49f67bfb95d83c35
|
[
"BSD-3-Clause"
] | 3
|
2019-07-05T17:29:15.000Z
|
2019-08-19T15:01:09.000Z
|
experimental/graphite/src/DrawWriter.cpp
|
stayf/skia
|
454c04e8f3b45ba0c518cbdd49f67bfb95d83c35
|
[
"BSD-3-Clause"
] | 2
|
2022-02-12T07:52:59.000Z
|
2022-03-03T03:06:23.000Z
|
/*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "experimental/graphite/src/DrawWriter.h"
#include "experimental/graphite/src/DrawBufferManager.h"
#include "src/gpu/BufferWriter.h"
namespace skgpu {
DrawWriter::DrawWriter(DrawDispatcher* dispatcher, DrawBufferManager* bufferManager)
: DrawWriter(dispatcher, bufferManager, PrimitiveType::kTriangles, 0, 0) {}
DrawWriter::DrawWriter(DrawDispatcher* dispatcher,
DrawBufferManager* bufferManager,
PrimitiveType primitiveType,
size_t vertexStride,
size_t instanceStride)
: fDispatcher(dispatcher)
, fManager(bufferManager)
, fPrimitiveType(primitiveType)
, fVertexStride(vertexStride)
, fInstanceStride(instanceStride) {
SkASSERT(dispatcher && bufferManager);
}
void DrawWriter::setTemplateInternal(BindBufferInfo vertices,
BindBufferInfo indices,
unsigned int count,
bool drawPendingVertices) {
SkASSERT(!vertices || fVertexStride > 0);
if (vertices != fFixedVertexBuffer ||
indices != fFixedIndexBuffer ||
count != fFixedVertexCount) {
// Issue any accumulated data that referred to the old template.
if (drawPendingVertices) {
this->drawPendingVertices();
}
fFixedBuffersDirty = true;
fFixedVertexBuffer = vertices;
fFixedIndexBuffer = indices;
fFixedVertexCount = count;
}
}
void DrawWriter::drawInternal(BindBufferInfo instances,
unsigned int base,
unsigned int instanceCount) {
// Draw calls that are only 1 instance and have no extra instance data get routed to
// the simpler draw APIs.
// TODO: Is there any benefit to this? Does it help hint to drivers? Avoid more bugs?
// Or should we always call drawInstanced and drawIndexedInstanced?
const bool useNonInstancedDraw =
!SkToBool(instances) && base == 0 && instanceCount == 1;
SkASSERT(!useNonInstancedDraw || fInstanceStride == 0);
// Issue new buffer binds only as necessary
// TODO: Should this instead be the responsibility of the CB or DrawDispatcher to remember
// what was last bound?
if (fFixedBuffersDirty || instances != fLastInstanceBuffer) {
fDispatcher->bindDrawBuffers(fFixedVertexBuffer, instances, fFixedIndexBuffer);
fFixedBuffersDirty = false;
fLastInstanceBuffer = instances;
}
if (useNonInstancedDraw) {
if (fFixedIndexBuffer) {
// Should only get here from a direct draw, in which case base should be 0 and any
// offset needs to be embedded in the BindBufferInfo by caller.
SkASSERT(base == 0);
fDispatcher->drawIndexed(fPrimitiveType, 0, fFixedVertexCount, 0);
} else {
// 'base' offsets accumulated vertex data from another DrawWriter across a state change.
fDispatcher->draw(fPrimitiveType, base, fFixedVertexCount);
}
} else {
// 'base' offsets accumulated instance data (or is 0 for a direct instanced draw). It is
// assumed that any base vertex and index have been folded into the BindBufferInfos already.
if (fFixedIndexBuffer) {
fDispatcher->drawIndexedInstanced(fPrimitiveType, 0, fFixedVertexCount, 0,
base, instanceCount);
} else {
fDispatcher->drawInstanced(fPrimitiveType, 0, fFixedVertexCount, base, instanceCount);
}
}
}
void DrawWriter::drawPendingVertices() {
if (fPendingCount > 0) {
if (fPendingMode == VertexMode::kInstances) {
// This uses instanced draws, so 'base' will be interpreted in instance units.
this->drawInternal(fPendingAttrs, fPendingBaseVertex, fPendingCount);
} else {
// This triggers a non-instanced draw call so 'base' passed to drawInternal is
// interpreted in vertex units.
this->setTemplateInternal(fPendingAttrs, {}, fPendingCount, /*drawPending=*/false);
this->drawInternal({}, fPendingBaseVertex, 1);
}
fPendingCount = 0;
fPendingBaseVertex = 0;
fPendingAttrs = {};
}
}
VertexWriter DrawWriter::appendData(VertexMode mode, size_t stride, unsigned int count) {
if (fPendingMode != mode) {
// Switched between accumulating vertices and instances, so issue draws for the old data.
this->drawPendingVertices();
fPendingMode = mode;
}
auto [writer, nextChunk] = fManager->getVertexWriter(count * stride);
// Check if next chunk's data is contiguous with what's previously been appended
if (nextChunk.fBuffer == fPendingAttrs.fBuffer &&
fPendingAttrs.fOffset + (fPendingBaseVertex + fPendingCount) * stride
== nextChunk.fOffset) {
// It is, so the next chunk's vertices that will be written can be folded into the next draw
fPendingCount += count;
} else {
// Alignment mismatch, or the old buffer filled up
this->drawPendingVertices();
fPendingCount = count;
fPendingBaseVertex = 0;
fPendingAttrs = nextChunk;
}
return std::move(writer);
}
void DrawWriter::newDynamicState() {
// Remember where we left off after we draw, since drawPendingVertices() resets all pending data
BindBufferInfo base = fPendingAttrs;
unsigned int baseVertex = fPendingBaseVertex + fPendingCount;
// Draw anything that used the previous dynamic state
this->drawPendingVertices();
fPendingAttrs = base;
fPendingBaseVertex = baseVertex;
}
void DrawWriter::newPipelineState(PrimitiveType type,
size_t vertexStride,
size_t instanceStride) {
// Draw anything that used the previous pipeline
this->drawPendingVertices();
// For simplicity, if there's a new pipeline, just forget about any previous buffer bindings,
// in which case the new writer only needs to use the dispatcher and buffer manager.
this->setTemplateInternal({}, {}, 0, false);
fLastInstanceBuffer = {};
fPrimitiveType = type;
fVertexStride = vertexStride;
fInstanceStride = instanceStride;
}
} // namespace skgpu
| 39.727273
| 100
| 0.646529
|
stayf
|
5da91969a5720632623d148beafd7ec7359bd343
| 26,468
|
cpp
|
C++
|
source/App/TAppDownConvert/TAppDownConvert.cpp
|
mdasari823/shvc
|
17c99abbb2bcab3a382d092d75a42e57b74cff1d
|
[
"BSD-3-Clause"
] | null | null | null |
source/App/TAppDownConvert/TAppDownConvert.cpp
|
mdasari823/shvc
|
17c99abbb2bcab3a382d092d75a42e57b74cff1d
|
[
"BSD-3-Clause"
] | null | null | null |
source/App/TAppDownConvert/TAppDownConvert.cpp
|
mdasari823/shvc
|
17c99abbb2bcab3a382d092d75a42e57b74cff1d
|
[
"BSD-3-Clause"
] | null | null | null |
/* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2016, ITU/ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file TAppDownConvert.cpp
\brief Down convert application main
*/
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "DownConvert.h"
typedef struct
{
int stride;
int lines;
short* data;
short* data2;
} ColorComponent;
typedef struct
{
int inputBitDepth;
int outputBitDepth;
ColorComponent y;
ColorComponent u;
ColorComponent v;
} YuvFrame;
void
createColorComponent( ColorComponent& c, int maxwidth, int maxheight )
{
maxwidth = ( ( maxwidth + 15 ) >> 4 ) << 4;
maxheight = ( ( maxheight + 15 ) >> 4 ) << 4;
int size = maxwidth * maxheight;
c.stride = maxwidth;
c.lines = maxheight;
c.data = new short [ size ];
c.data2 = new short [ size ];
if( ! c.data || ! c.data2 )
{
fprintf(stderr, "\nERROR: memory allocation failed!\n\n");
exit(1);
}
}
void
deleteColorComponent( ColorComponent& c )
{
delete[] c.data;
delete[] c.data2;
c.stride = 0;
c.lines = 0;
c.data = 0;
c.data2 = 0;
}
int
readColorComponent( ColorComponent& c, FILE* file, int width, int height, int inputBitDepth, bool second )
{
assert( width <= c.stride );
assert( height <= c.lines );
unsigned char *temp=NULL;
int iMaxPadWidth = gMin( c.stride, ( ( width + 15 ) >> 4 ) << 4 );
int iMaxPadHeight = gMin( c.lines, ( ( height + 31 ) >> 5 ) << 5 );
for( int i = 0; i < height; i++ )
{
short* buffer = ( second ? c.data2 : c.data ) + i * c.stride;
int rsize;
if (inputBitDepth == 10)
{
rsize = (int)fread( buffer, sizeof(short), width, file );
}
else
{
if (temp == NULL)
temp = (unsigned char * )calloc(width, sizeof(unsigned char));
rsize = (int)fread( temp, sizeof(unsigned char), width, file );
for (int j = 0; j < width; j++)
buffer[j] = (short) temp[j];
}
if( rsize != width )
{
return 1;
}
for( int xp = width; xp < iMaxPadWidth; xp++ )
{
buffer[xp] = buffer[xp-1];
}
}
for( int yp = height; yp < iMaxPadHeight; yp++ )
{
short* buffer = ( second ? c.data2 : c.data ) + yp * c.stride;
short* bufferX = buffer - c.stride;
for( int xp = 0; xp < c.stride; xp++ )
{
buffer[xp] = bufferX[xp];
}
}
if (temp!=NULL)
free(temp);
return 0;
}
void
duplicateColorComponent( ColorComponent& c )
{
memcpy( c.data2, c.data, c.stride * c.lines * sizeof(short) );
}
void
combineTopAndBottomInColorComponent( ColorComponent& c, Bool bBotField )
{
int offs = ( bBotField ? c.stride : 0 );
short* pDes = c.data + offs;
short* pSrc = c.data2 + offs;
for( int i = 0; i < c.lines / 2; i++, pDes += 2*c.stride, pSrc += 2*c.stride )
{
memcpy( pDes, pSrc, c.stride * sizeof(short) );
}
}
void
writeColorComponent( ColorComponent& c, FILE* file, int width, int height, int outputBitDepth, bool second )
{
assert( width <= c.stride );
assert( height <= c.lines );
unsigned char* temp = NULL;
for( int i = 0; i < height; i++ )
{
short* buffer = ( second ? c.data2 : c.data ) + i * c.stride;
int wsize;
if ( outputBitDepth == 8 )
{
if (temp == NULL)
temp = (unsigned char * )calloc(width, sizeof(unsigned char));
for (int j = 0; j < width; j ++)
temp[j] = (unsigned char)buffer[j];
wsize = (int)fwrite( temp, sizeof(unsigned char), width, file );
}
else
{
wsize = (int)fwrite( buffer, sizeof(short), width, file );
}
if( wsize != width )
{
fprintf(stderr, "\nERROR: while writing to output file!\n\n");
exit(1);
}
}
}
void
createFrame( YuvFrame& f, int width, int height, int inputBitDepth, int outputBitDepth )
{
f.inputBitDepth = inputBitDepth;
f.outputBitDepth = outputBitDepth;
createColorComponent( f.y, width, height );
createColorComponent( f.u, width >> 1, height >> 1 );
createColorComponent( f.v, width >> 1, height >> 1 );
}
void
deleteFrame( YuvFrame& f )
{
deleteColorComponent( f.y );
deleteColorComponent( f.u );
deleteColorComponent( f.v );
}
int
readFrame( YuvFrame& f, FILE* file, int width, int height, bool second = false )
{
ROTRS( readColorComponent( f.y, file, width, height, f.inputBitDepth, second ), 1 );
ROTRS( readColorComponent( f.u, file, width >> 1, height >> 1, f.inputBitDepth, second ), 1 );
ROTRS( readColorComponent( f.v, file, width >> 1, height >> 1, f.inputBitDepth, second ), 1 );
return 0;
}
void
duplicateFrame( YuvFrame& f )
{
duplicateColorComponent( f.y );
duplicateColorComponent( f.u );
duplicateColorComponent( f.v );
}
void
combineTopAndBottomInFrame( YuvFrame& f, Bool botField )
{
combineTopAndBottomInColorComponent( f.y, botField );
combineTopAndBottomInColorComponent( f.u, botField );
combineTopAndBottomInColorComponent( f.v, botField );
}
void
writeFrame( YuvFrame& f, FILE* file, int width, int height, bool both = false )
{
writeColorComponent( f.y, file, width, height, f.outputBitDepth, false );
writeColorComponent( f.u, file, width >> 1, height >> 1, f.outputBitDepth, false );
writeColorComponent( f.v, file, width >> 1, height >> 1, f.outputBitDepth, false );
if( both )
{
writeColorComponent( f.y, file, width, height, f.outputBitDepth, true );
writeColorComponent( f.u, file, width >> 1, height >> 1, f.outputBitDepth, true );
writeColorComponent( f.v, file, width >> 1, height >> 1, f.outputBitDepth, true );
}
}
void
print_usage_and_exit( int test, const char* name, const char* message = 0 )
{
if( test )
{
if( message )
{
fprintf ( stderr, "\nERROR: %s\n", message );
}
fprintf ( stderr, "\nUsage: %s <win> <hin> <in> <wout> <hout> <out> [<bin> <bout> <method> <t> [<skip> [<frms>]]] [[-phase <args>] ]\n\n", name );
fprintf ( stderr, " win : input width (luma samples)\n" );
fprintf ( stderr, " hin : input height (luma samples)\n" );
fprintf ( stderr, " in : input file\n" );
fprintf ( stderr, " wout : output width (luma samples)\n" );
fprintf ( stderr, " hout : output height (luma samples)\n" );
fprintf ( stderr, " out : output file\n" );
fprintf ( stderr, "\n--------------------------- OPTIONAL ---------------------------\n\n" );
fprintf ( stderr, " bin : input bit depth (8 or 10) (default: 8)\n" );
fprintf ( stderr, " bout : output bit depth (8 or 10) (default: 8)\n" );
fprintf ( stderr, " method : sampling method (0, 1, 2, 3, 4) (default: 0)\n" );
fprintf ( stderr, " t : number of temporal downsampling stages (default: 0)\n" );
fprintf ( stderr, " skip : number of frames to skip at start (default: 0)\n" );
fprintf ( stderr, " frms : number of frames wanted in output file (default: max)\n" );
fprintf ( stderr, "\n-------------------------- OVERLOADED --------------------------\n\n" );
fprintf ( stderr, " -phase <in_uv_ph_x> <in_uv_ph_y> <out_uv_ph_x> <out_uv_ph_y>\n");
fprintf ( stderr, " in_uv_ph_x : input chroma phase shift in horizontal direction (default:-1)\n" );
fprintf ( stderr, " in_uv_ph_y : input chroma phase shift in vertical direction (default: 0)\n" );
fprintf ( stderr, " out_uv_ph_x: output chroma phase shift in horizontal direction (default:-1)\n" );
fprintf ( stderr, " out_uv_ph_y: output chroma phase shift in vertical direction (default: 0)\n" );
fprintf ( stderr, "\n-------------------------- EXAMPLE --------------------------\n\n" );
fprintf ( stderr, "\nUsage: %s 4096 2048 input_video_4096x2048_10bits.yuv 2048 1024 output_video_2048x1024_8bits.yuv 10 8\n\n", name );
fprintf ( stderr, "\n\n");
exit ( 1 );
}
}
void
updateCropParametersFromFile( ResizeParameters& cRP, FILE* cropFile, int resamplingMethod, char* name )
{
int crop_x0 = 0;
int crop_y0 = 0;
int crop_w = 0;
int crop_h = 0;
if( fscanf( cropFile, "%d,%d,%d,%d\n", &crop_x0, &crop_y0, &crop_w, &crop_h ) == 4 )
{
cRP.m_iLeftFrmOffset = crop_x0;
cRP.m_iTopFrmOffset = crop_y0;
cRP.m_iScaledRefFrmWidth = crop_w;
cRP.m_iScaledRefFrmHeight = crop_h;
}
print_usage_and_exit( cRP.m_iLeftFrmOffset & 1 || cRP.m_iTopFrmOffset & 1, name, "cropping parameters must be even values" );
print_usage_and_exit( cRP.m_iScaledRefFrmWidth & 1 || cRP.m_iScaledRefFrmHeight & 1, name, "cropping parameters must be even values" );
print_usage_and_exit( resamplingMethod == 2 && cRP.m_iScaledRefFrmWidth != gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "crop dimensions must be the same as the minimal dimensions" );
print_usage_and_exit( resamplingMethod == 2 && cRP.m_iScaledRefFrmHeight != gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "crop dimensions must be the same as the minimal dimensions" );
print_usage_and_exit( cRP.m_iScaledRefFrmWidth > gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "wrong crop window size" );
print_usage_and_exit( cRP.m_iScaledRefFrmHeight > gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "wrong crop window size" );
print_usage_and_exit( cRP.m_iScaledRefFrmWidth < gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "wrong crop window size" );
print_usage_and_exit( cRP.m_iScaledRefFrmHeight < gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "wrong crop window size" );
print_usage_and_exit( cRP.m_iLeftFrmOffset + cRP.m_iScaledRefFrmWidth > gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "wrong crop window size and origin" );
print_usage_and_exit( cRP.m_iTopFrmOffset + cRP.m_iScaledRefFrmHeight > gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "wrong crop window size and origin" );
}
void
resampleFrame( YuvFrame& rcFrame,
DownConvert& rcDownConvert,
ResizeParameters& rcRP,
int resamplingMethod,
int resamplingMode,
bool resampling,
bool upsampling,
bool bSecondInputFrame )
{
assert( upsampling == 0 );
//===== downsampling =====
ResizeParameters cRP = rcRP;
{
Int iRefVerMbShift = ( cRP.m_bRefLayerFrameMbsOnlyFlag ? 4 : 5 );
Int iScaledVerShift = ( cRP.m_bFrameMbsOnlyFlag ? 1 : 2 );
Int iHorDiv = ( cRP.m_iFrameWidth << 1 );
Int iVerDiv = ( cRP.m_iFrameHeight << iScaledVerShift );
Int iRefFrmW = ( ( cRP.m_iFrameWidth + ( 1 << 4 ) - 1 ) >> 4 ) << 4; // round to next multiple of 16
Int iRefFrmH = ( ( cRP.m_iFrameHeight + ( 1 << iRefVerMbShift ) - 1 ) >> iRefVerMbShift ) << iRefVerMbShift; // round to next multiple of 16 or 32 (for interlaced)
Int iScaledRefFrmW = ( ( cRP.m_iScaledRefFrmWidth * iRefFrmW + ( iHorDiv >> 1 ) ) / iHorDiv ) << 1; // scale and round to next multiple of 2
Int iScaledRefFrmH = ( ( cRP.m_iScaledRefFrmHeight * iRefFrmH + ( iVerDiv >> 1 ) ) / iVerDiv ) << iScaledVerShift; // scale and round to next multiple of 2 or 4 (for interlaced)
cRP.m_iFrameWidth = iRefFrmW;
cRP.m_iFrameHeight = iRefFrmH;
cRP.m_iScaledRefFrmWidth = iScaledRefFrmW;
cRP.m_iScaledRefFrmHeight = iScaledRefFrmH;
cRP.inputBitDepth = rcFrame.inputBitDepth;
cRP.outputBitDepth = rcFrame.outputBitDepth;
}
assert( resamplingMethod == 0 );
if( resamplingMode < 4 )
{
rcDownConvert.downsamplingSVC ( rcFrame.y.data, rcFrame.y.stride, rcFrame.u.data, rcFrame.u.stride, rcFrame.v.data, rcFrame.v.stride, &cRP, resamplingMode == 3 );
return;
}
}
int
main( int argc, char *argv[] )
{
//===== set standard resize parameters =====
ResizeParameters cRP;
cRP.m_bRefLayerFrameMbsOnlyFlag = true;
cRP.m_bFrameMbsOnlyFlag = true;
cRP.m_bRefLayerFieldPicFlag = false;
cRP.m_bFieldPicFlag = false;
cRP.m_bRefLayerBotFieldFlag = false;
cRP.m_bBotFieldFlag = false;
cRP.m_bRefLayerIsMbAffFrame = false;
cRP.m_bIsMbAffFrame = false;
#if ZERO_PHASE
cRP.m_iRefLayerChromaPhaseX = 0;
cRP.m_iRefLayerChromaPhaseY = 1;
cRP.m_iChromaPhaseX = 0;
cRP.m_iChromaPhaseY = 1;
#else
cRP.m_iRefLayerChromaPhaseX = -1;
cRP.m_iRefLayerChromaPhaseY = 0;
cRP.m_iChromaPhaseX = -1;
cRP.m_iChromaPhaseY = 0;
#endif
cRP.m_iRefLayerFrmWidth = 0;
cRP.m_iRefLayerFrmHeight = 0;
cRP.m_iScaledRefFrmWidth = 0;
cRP.m_iScaledRefFrmHeight = 0;
cRP.m_iFrameWidth = 0;
cRP.m_iFrameHeight = 0;
cRP.m_iLeftFrmOffset = 0;
cRP.m_iTopFrmOffset = 0;
//cRP.m_iExtendedSpatialScalability = 0;
cRP.m_iLevelIdc = 0;
//===== init parameters =====
FILE* inputFile = 0;
FILE* outputFile = 0;
FILE* croppingParametersFile = 0;
int inputBitDepth = 8;
int outputBitDepth = 8;
int resamplingMethod = 0;
int resamplingMode = 0;
bool croppingInitialized = false;
bool phaseInitialized = false;
bool methodInitialized = false;
bool resampling = false;
bool upsampling = false;
int numSpatialDyadicStages = 0;
int skipBetween = 0;
int skipAtStart = 0;
int maxNumOutputFrames = 0;
//===== read input parameters =====
print_usage_and_exit( ( argc < 7 || argc > 24 ), argv[0], "wrong number of arguments" );
cRP.m_iRefLayerFrmWidth = atoi ( argv[1] );
cRP.m_iRefLayerFrmHeight = atoi ( argv[2] );
inputFile = fopen ( argv[3], "rb" );
cRP.m_iFrameWidth = atoi ( argv[4] );
cRP.m_iFrameHeight = atoi ( argv[5] );
outputFile = fopen ( argv[6], "wb" );
print_usage_and_exit( ! inputFile, argv[0], "failed to open input file" );
print_usage_and_exit( ! outputFile, argv[0], "failed to open input file" );
print_usage_and_exit( cRP.m_iRefLayerFrmWidth > cRP.m_iFrameWidth && cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight, argv[0], "mixed upsampling and downsampling not supported" );
print_usage_and_exit( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth && cRP.m_iRefLayerFrmHeight > cRP.m_iFrameHeight, argv[0], "mixed upsampling and downsampling not supported" );
for( int i = 7; i < argc; )
{
if( ! strcmp( argv[i], "-phase" ) )
{
print_usage_and_exit( resamplingMethod != 0, argv[0], "phases only supported in normative resampling" );
print_usage_and_exit( phaseInitialized || argc < i+5, argv[0], "wrong number of phase parameters" );
phaseInitialized = true;
i++;
cRP.m_iRefLayerChromaPhaseX = atoi( argv[i++] );
cRP.m_iRefLayerChromaPhaseY = atoi( argv[i++] );
cRP.m_iChromaPhaseX = atoi( argv[i++] );
cRP.m_iChromaPhaseY = atoi( argv[i++] );
print_usage_and_exit( cRP.m_iRefLayerChromaPhaseX > 0 || cRP.m_iRefLayerChromaPhaseX < -1, argv[0], "wrong phase x parameters (range : [-1, 0])");
print_usage_and_exit( cRP.m_iRefLayerChromaPhaseY > 1 || cRP.m_iRefLayerChromaPhaseY < -1, argv[0], "wrong phase x parameters (range : [-1, 1])");
print_usage_and_exit( cRP.m_iChromaPhaseX > 0 || cRP.m_iChromaPhaseX < -1, argv[0], "wrong phase x parameters (range : [-1, 0])");
print_usage_and_exit( cRP.m_iChromaPhaseY > 1 || cRP.m_iChromaPhaseY < -1, argv[0], "wrong phase x parameters (range : [-1, 1])");
}
else if (i == 7) // input bit depth
{
inputBitDepth = atoi( argv[i++] );
print_usage_and_exit( inputBitDepth != 8 && inputBitDepth != 10, argv[0], "wrong input bit depth (8 bit or 10 bit)");
}
else if (i == 8) // output bit depth
{
outputBitDepth = atoi( argv[i++] );
print_usage_and_exit( outputBitDepth != 8 && outputBitDepth != 10, argv[0], "wrong output bit depth (8 bit or 10 bit)");
}
else if (i == 9) // downsampling methods
{
methodInitialized = true;
resamplingMethod = atoi( argv[i++] );
print_usage_and_exit( resamplingMethod < 0 || resamplingMethod > 4, argv[0], "unsupported method" );
if( resamplingMethod > 2 )
{
print_usage_and_exit( cRP.m_iRefLayerFrmWidth > cRP.m_iFrameWidth, argv[0], "method 3 and 4 are not supported for downsampling" );
print_usage_and_exit( cRP.m_iRefLayerFrmHeight > cRP.m_iFrameHeight, argv[0], "method 3 and 4 are not supported for downsampling" );
}
if( resamplingMethod != 2 )
{
resampling = true;
upsampling = ( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth ) || ( cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight );
}
if( resamplingMethod == 1 )
{
if( upsampling )
{
int div = cRP.m_iFrameWidth / cRP.m_iRefLayerFrmWidth;
if ( div == 1) numSpatialDyadicStages = 0;
else if( div == 2) numSpatialDyadicStages = 1;
else if( div == 4) numSpatialDyadicStages = 2;
else if( div == 8) numSpatialDyadicStages = 3;
else numSpatialDyadicStages = -1;
print_usage_and_exit( numSpatialDyadicStages < 0, argv[0], "ratio not supported for dyadic upsampling method" );
print_usage_and_exit( div * cRP.m_iRefLayerFrmWidth != cRP.m_iFrameWidth, argv[0], "ratio is not dyadic in dyadic mode" );
print_usage_and_exit( div * cRP.m_iRefLayerFrmHeight != cRP.m_iFrameHeight, argv[0], "different horizontal and vertical ratio in dyadic mode" );
}
else
{
int div = cRP.m_iRefLayerFrmWidth / cRP.m_iFrameWidth;
if ( div == 1) numSpatialDyadicStages = 0;
else if( div == 2) numSpatialDyadicStages = 1;
else if( div == 4) numSpatialDyadicStages = 2;
else if( div == 8) numSpatialDyadicStages = 3;
else numSpatialDyadicStages = -1;
print_usage_and_exit( numSpatialDyadicStages < 0, argv[0], "ratio not supported for dyadic downsampling method" );
print_usage_and_exit( div * cRP.m_iFrameWidth != cRP.m_iRefLayerFrmWidth, argv[0], "ratio is not dyadic in dyadic mode" );
print_usage_and_exit( div * cRP.m_iFrameHeight != cRP.m_iRefLayerFrmHeight, argv[0], "different horizontal and vertical ratio in dyadic mode" );
}
}
}
else if( i == 10 ) // temporal stages
{
int TStages = atoi( argv[i++] );
skipBetween = ( 1 << TStages ) - 1;
print_usage_and_exit( TStages < 0, argv[0], "negative number of temporal stages" );
}
else if( i == 11 ) // skipped frames
{
skipAtStart = atoi( argv[i++] );
print_usage_and_exit( skipAtStart < 0, argv[0], "negative number of skipped frames at start" );
}
else if( i == 12 ) // output frames
{
maxNumOutputFrames = atoi( argv[i++] );
print_usage_and_exit( maxNumOutputFrames < 0 , argv[0], "negative number of output frames" );
}
else
{
print_usage_and_exit( true, argv[0], "error in command line parameters" );
}
}
if( ! methodInitialized )
{
resampling = true;
upsampling = ( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth ) || ( cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight );
}
if( ! croppingInitialized )
{
if( resamplingMethod == 2 )
{
cRP.m_iScaledRefFrmWidth = gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth );
cRP.m_iScaledRefFrmHeight = gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
}
else
{
cRP.m_iScaledRefFrmWidth = gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth );
cRP.m_iScaledRefFrmHeight = gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
}
}
//===== set basic parameters for resampling control =====
if( resamplingMethod == 0 )
{
if( resamplingMode == 1 )
{
cRP.m_bRefLayerFrameMbsOnlyFlag = false;
cRP.m_bFrameMbsOnlyFlag = false;
}
else if( resamplingMode == 2 || resamplingMode == 3 )
{
cRP.m_bFrameMbsOnlyFlag = false;
if( ! upsampling )
{
cRP.m_bFieldPicFlag = true;
cRP.m_bBotFieldFlag = ( resamplingMode == 3 );
}
}
else if( resamplingMode == 4 || resamplingMode == 5 )
{
cRP.m_bRefLayerFrameMbsOnlyFlag = false;
cRP.m_bRefLayerFieldPicFlag = true;
}
}
//===== initialize classes =====
YuvFrame cFrame;
DownConvert cDownConvert;
{
int maxWidth = gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth );
int maxHeight = gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
int minWidth = gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth );
int minHeight = gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
int minWRnd16 = ( ( minWidth + 15 ) >> 4 ) << 4;
int minHRnd32 = ( ( minHeight + 31 ) >> 5 ) << 5;
maxWidth = ( ( maxWidth * minWRnd16 + ( minWidth << 4 ) - 1 ) / ( minWidth << 4 ) ) << 4;
maxHeight = ( ( maxHeight * minHRnd32 + ( minHeight << 4 ) - 1 ) / ( minHeight << 4 ) ) << 4;
createFrame( cFrame, maxWidth, maxHeight, inputBitDepth, outputBitDepth );
cDownConvert.init( maxWidth, maxHeight );
}
printf("Resampler\n\n");
//===== loop over frames =====
int skip = skipAtStart;
int writtenFrames = 0;
int numInputFrames = ( resamplingMode >= 4 && ! upsampling ? 2 : 1 );
int numOutputFrames = ( resamplingMode >= 4 && upsampling ? 2 : 1 );
bool bFinished = false;
long startTime = clock();
while( ! bFinished )
{
for( int inputFrame = 0; inputFrame < numInputFrames && ! bFinished; inputFrame++ )
{
//===== read input frame =====
for( int numToRead = skip + 1; numToRead > 0 && ! bFinished; numToRead-- )
{
bFinished = ( readFrame( cFrame, inputFile, cRP.m_iRefLayerFrmWidth, cRP.m_iRefLayerFrmHeight, inputFrame != 0 ) != 0 );
}
skip = skipBetween;
if( cRP.m_iExtendedSpatialScalability == 2 && ! bFinished )
{
updateCropParametersFromFile( cRP, croppingParametersFile, resamplingMethod, argv[0] );
}
//===== set resampling parameter =====
if( resamplingMethod != 0 &&
cRP.m_iScaledRefFrmWidth == gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ) &&
cRP.m_iScaledRefFrmHeight == gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ) )
{
resampling = false;
}
else
{
resampling = true;
}
//===== resample input frame =====
if( ! bFinished )
{
resampleFrame( cFrame, cDownConvert, cRP, resamplingMethod, resamplingMode, resampling, upsampling, inputFrame != 0 );
}
}
//===== write output frame =====
if( ! bFinished )
{
Bool bWriteTwoFrames = ( numOutputFrames == 2 && ( maxNumOutputFrames == 0 || writtenFrames + 1 < maxNumOutputFrames ) );
writeFrame( cFrame, outputFile, cRP.m_iFrameWidth, cRP.m_iFrameHeight, bWriteTwoFrames );
writtenFrames += ( bWriteTwoFrames ? 2 : 1 );
bFinished = ( maxNumOutputFrames != 0 && writtenFrames == maxNumOutputFrames );
fprintf( stderr, "\r%6d frames converted", writtenFrames );
}
}
long endTime = clock();
deleteFrame( cFrame );
fclose ( inputFile );
fclose ( outputFile );
if( croppingParametersFile )
{
fclose ( croppingParametersFile );
}
fprintf( stderr, "\n" );
double deltaInSecond = (double)( endTime - startTime) / (double)CLOCKS_PER_SEC;
fprintf( stderr, "in %.2lf seconds => %.0lf ms/frame\n", deltaInSecond, deltaInSecond / (double)writtenFrames * 1000.0 );
if( writtenFrames < maxNumOutputFrames )
{
fprintf( stderr, "\nNOTE: less output frames generated than specified!!!\n\n" );
}
return 0;
}
| 40.972136
| 202
| 0.610737
|
mdasari823
|
5da9227781eb96f71864d43896619633bcd7ce2b
| 725
|
hpp
|
C++
|
ProjectMajestic/Chunk.hpp
|
Edgaru089/ProjectMajestic
|
16cda6f86fd5ad02baedc9481609d6140cdda62a
|
[
"MIT"
] | 1
|
2018-08-29T06:36:23.000Z
|
2018-08-29T06:36:23.000Z
|
ProjectMajestic/Chunk.hpp
|
Edgaru089/ProjectMajestic
|
16cda6f86fd5ad02baedc9481609d6140cdda62a
|
[
"MIT"
] | null | null | null |
ProjectMajestic/Chunk.hpp
|
Edgaru089/ProjectMajestic
|
16cda6f86fd5ad02baedc9481609d6140cdda62a
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include "Main.hpp"
#include "TextureManager.hpp"
#include "Data.hpp"
#include "Block.hpp"
const int chunkSize = 16;
class Chunk {
public:
friend class TerrainManager;
~Chunk();
void updateLogic();
void getRenderList(VertexArray & verts);
void getLightMask(VertexArray& verts);
void setChunkId(int x, int y);
Vector2i getChunkId();
shared_ptr<Block> getBlock(Vector2i inChunkCoord);
void setBlock(Vector2i inChunkCoord, shared_ptr<Block> block);
void _resize(int width, int height);
// First: pos(global coords); Second: strength
map<Uuid, pair<Vector2i, int>> lightSources;
vector<vector<shared_ptr<Block>>> blocks;
vector<vector<int>> lightLevel;
Vector2i id;
};
| 18.125
| 63
| 0.736552
|
Edgaru089
|
5dad7dc4efc0d79571baeb86707000cbb1329e53
| 499
|
cpp
|
C++
|
0x7E9FB/hand file/Socket/Sockets.cpp
|
518651/0x7E9FB-Net-Project
|
ec6ad70aa8c0df1eaa318034b2513c6394d9fbe6
|
[
"MIT"
] | 1
|
2022-02-28T02:57:30.000Z
|
2022-02-28T02:57:30.000Z
|
0x7E9FB/hand file/Socket/Sockets.cpp
|
518651/0x7E9FB-Net-Project
|
ec6ad70aa8c0df1eaa318034b2513c6394d9fbe6
|
[
"MIT"
] | null | null | null |
0x7E9FB/hand file/Socket/Sockets.cpp
|
518651/0x7E9FB-Net-Project
|
ec6ad70aa8c0df1eaa318034b2513c6394d9fbe6
|
[
"MIT"
] | null | null | null |
//#include "Sockets.h"
#include "../../Un-main.h"
bool GetSocketAddress(char* host, sockaddr_in* address)
{
struct addrinfo* result = NULL;
struct addrinfo* ptr = NULL;
struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(host, "http", &hints, &result)) return false;
*address = *(sockaddr_in*)(result[0].ai_addr);
freeaddrinfo(result);
return true;
}
| 24.95
| 63
| 0.687375
|
518651
|
5dae83510a21f412177fed4a4c7bcdab8c2d77d4
| 1,068
|
cpp
|
C++
|
debian/passenger-2.2.15/benchmark/ApplicationPool.cpp
|
brightbox/nginx-brightbox
|
cbb27b979ff8de2a6d3f57cebb214f0cde348d3f
|
[
"BSD-2-Clause"
] | 4
|
2016-05-09T12:50:34.000Z
|
2020-10-08T07:28:46.000Z
|
benchmark/ApplicationPool.cpp
|
chad/passenger
|
74fb3cf821d5b5d5bae37e03ba7ccaffc13ce9d0
|
[
"MIT"
] | null | null | null |
benchmark/ApplicationPool.cpp
|
chad/passenger
|
74fb3cf821d5b5d5bae37e03ba7ccaffc13ce9d0
|
[
"MIT"
] | 1
|
2020-10-08T07:51:20.000Z
|
2020-10-08T07:51:20.000Z
|
//#define USE_SERVER
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#ifdef USE_SERVER
#include "ApplicationPoolServer.h"
#else
#include "StandardApplicationPool.h"
#endif
#include "Utils.h"
#include "Logging.h"
using namespace std;
using namespace boost;
using namespace Passenger;
#define TRANSACTIONS 20000
#define CONCURRENCY 24
ApplicationPoolPtr pool;
static void
threadMain(unsigned int times) {
for (unsigned int i = 0; i < times; i++) {
Application::SessionPtr session(pool->get("test/stub/minimal-railsapp"));
for (int x = 0; x < 200000; x++) {
// Do nothing.
}
}
}
int
main() {
thread_group tg;
#ifdef USE_SERVER
ApplicationPoolServer server("ext/apache2/ApplicationPoolServerExecutable",
"bin/passenger-spawn-server");
pool = server.connect();
#else
pool = ptr(new StandardApplicationPool("bin/passenger-spawn-server"));
#endif
pool->setMax(6);
for (int i = 0; i < CONCURRENCY; i++) {
tg.create_thread(boost::bind(&threadMain, TRANSACTIONS / CONCURRENCY));
}
tg.join_all();
return 0;
}
| 20.150943
| 77
| 0.714419
|
brightbox
|
5db66d7a1f7ee5905f64100438a12008879295df
| 5,129
|
cxx
|
C++
|
examples/structure.cxx
|
elcuco/mimetic
|
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
|
[
"MIT"
] | null | null | null |
examples/structure.cxx
|
elcuco/mimetic
|
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
|
[
"MIT"
] | null | null | null |
examples/structure.cxx
|
elcuco/mimetic
|
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
|
[
"MIT"
] | 1
|
2022-02-24T19:24:28.000Z
|
2022-02-24T19:24:28.000Z
|
/***************************************************************************
copyright : (C) 2002-2008 by Stefano Barbato
email : stefano@codesink.org
$Id: structure.cxx,v 1.6 2008-10-07 11:06:25 tat Exp $
***************************************************************************/
/** \example structure.cc
* Usage: structure [-ed] [in_file [out_file]]
*
* Reads in_file (or standard input) and writes its MIME structure to out_file
* (or standard output)
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <iterator>
#include <streambuf>
#include <mimetic/mimetic.h>
#include <mimetic/utils.h>
using namespace std;
using namespace mimetic;
int g_verbose; // verbose mode on/off
int g_quiet; // quiet mode
int g_entityCount; // num of entities found
void printTabs(int c)
{
while(c--)
cout << " ";
}
void printMimeStructure(const std::shared_ptr<MimeEntity>& pMe, int tabcount = 0)
{
++g_entityCount;
if(!g_quiet)
{
Header& h = pMe->header();
ContentType ct = h.contentType();
cout << g_entityCount << " ";
printTabs(tabcount);
cout << ct.type() << "/" << ct.subtype() << endl;
if(g_verbose)
{
ContentType::ParamList::iterator bit, eit;
bit = ct.paramList().begin();
eit = ct.paramList().end();
for(; bit != eit; ++bit)
{
printTabs(tabcount);
cout << "param: " << bit->name() << " = "
<< bit->value() << endl;
}
if(h.hasField(ContentTransferEncoding::label))
{
printTabs(tabcount);
cout << "encoding: "
<< h.contentTransferEncoding().mechanism()
<< endl;
}
if(h.hasField(ContentDisposition::label))
{
printTabs(tabcount);
const ContentDisposition cd = h.contentDisposition();
cout << "disposition: " << cd.type() << endl;
ContentDisposition::ParamList::const_iterator
bit, eit;
bit = cd.paramList().begin();
eit = cd.paramList().end();
for(; bit != eit; ++bit)
{
printTabs(tabcount);
cout << "param: " << bit->name() << " = "
<< bit->value() << endl;
}
}
Header::iterator hbit, heit;
hbit = pMe->header().begin();
heit = pMe->header().end();
for(; hbit != heit; ++hbit)
{
printTabs(tabcount);
cout << "h: " << hbit->name() << " = "
<< hbit->value() << endl;
}
if(pMe->body().preamble().length())
{
printTabs(tabcount);
cout << "preamble: " << pMe->body().preamble()
<< endl;
}
if(pMe->body().epilogue().length())
{
printTabs(tabcount);
cout << "epilogue: " << pMe->body().epilogue()
<< endl;
}
printTabs(tabcount);
cout << "part size: " << pMe->size() << endl;
printTabs(tabcount);
cout << "body size: " << pMe->body().length() << endl;
cout << endl;
}
}
MimeEntityList::iterator mbit = pMe->body().parts().begin(),
meit = pMe->body().parts().end();
for(;mbit!=meit;++mbit)
printMimeStructure(*mbit, 1 + tabcount);
}
void usage()
{
cout << "structure [-v] [in_file]..." << endl;
cout << " -v Verbose mode" << endl;
cout << " -q totally quiet; exit code = num of entities" << endl;
cout << endl;
exit(1);
}
#if defined(BUILD_MONOLITHIC)
#define main(cnt, arr) smime_structure_main(cnt, arr)
#endif
int main(int argc, const char** argv)
{
std::ios_base::sync_with_stdio(false);
int fidx = 1;
int iMask = imBody | imPreamble | imEpilogue;
if(argc > 1)
{
g_verbose = 0;
string first = argv[1];
if(first == "-h")
usage();
else if(first == "-v")
g_verbose = 1;
else if(first == "-q")
g_quiet = 1;
fidx = (g_verbose || g_quiet ? 2 : 1); // first filename idx
}
if(argc == fidx)
{
istreambuf_iterator<char> bit(std::cin), eit;
std::shared_ptr<MimeEntity> me = MimeEntity::create(bit, eit, iMask);
printMimeStructure(me);
} else {
for(int fc = fidx; fc < argc; ++fc)
{
File in(argv[fc]);
if(!in)
{
cerr << "ERR: unable to open file "
<< argv[fc]
<< endl;
continue;
}
std::shared_ptr<MimeEntity> me = MimeEntity::create(in.begin(), in.end(), iMask);
printMimeStructure(me);
}
}
return g_entityCount;
}
| 29.819767
| 93
| 0.454475
|
elcuco
|
5db6b84160fefe6dbb129a5b04cfe16bf03ac470
| 24,205
|
cpp
|
C++
|
example-hard-decode-pybind/src/ffhdd/cuvid_decoder.cpp
|
shouxieai/tensorRT_Pro
|
963c8250c3cefc568d7d13f3b1b6769393d7b94e
|
[
"MIT"
] | 537
|
2021-10-03T10:51:49.000Z
|
2022-03-31T10:07:05.000Z
|
example-hard-decode-pybind/src/ffhdd/cuvid_decoder.cpp
|
shouxieai/tensorRT_Pro
|
963c8250c3cefc568d7d13f3b1b6769393d7b94e
|
[
"MIT"
] | 52
|
2021-10-04T09:05:35.000Z
|
2022-03-31T07:35:22.000Z
|
example-hard-decode-pybind/src/ffhdd/cuvid_decoder.cpp
|
shouxieai/tensorRT_Pro
|
963c8250c3cefc568d7d13f3b1b6769393d7b94e
|
[
"MIT"
] | 146
|
2021-10-11T00:46:19.000Z
|
2022-03-31T02:19:37.000Z
|
#include "cuvid_decoder.hpp"
#include "cuda_tools.hpp"
#include <nvcuvid.h>
#include <mutex>
#include <vector>
#include <sstream>
#include <string.h>
#include <assert.h>
using namespace std;
void convert_nv12_to_bgr_invoker(
const uint8_t* y, const uint8_t* uv, int width, int height, int linesize, uint8_t* dst_bgr,
cudaStream_t stream
);
namespace FFHDDecoder{
static float GetChromaHeightFactor(cudaVideoSurfaceFormat eSurfaceFormat)
{
float factor = 0.5;
switch (eSurfaceFormat)
{
case cudaVideoSurfaceFormat_NV12:
case cudaVideoSurfaceFormat_P016:
factor = 0.5;
break;
case cudaVideoSurfaceFormat_YUV444:
case cudaVideoSurfaceFormat_YUV444_16Bit:
factor = 1.0;
break;
}
return factor;
}
static int GetChromaPlaneCount(cudaVideoSurfaceFormat eSurfaceFormat)
{
int numPlane = 1;
switch (eSurfaceFormat)
{
case cudaVideoSurfaceFormat_NV12:
case cudaVideoSurfaceFormat_P016:
numPlane = 1;
break;
case cudaVideoSurfaceFormat_YUV444:
case cudaVideoSurfaceFormat_YUV444_16Bit:
numPlane = 2;
break;
}
return numPlane;
}
IcudaVideoCodec ffmpeg2NvCodecId(int ffmpeg_codec_id) {
switch (ffmpeg_codec_id) {
/*AV_CODEC_ID_MPEG1VIDEO*/ case 1 : return cudaVideoCodec_MPEG1;
/*AV_CODEC_ID_MPEG2VIDEO*/ case 2 : return cudaVideoCodec_MPEG2;
/*AV_CODEC_ID_MPEG4*/ case 12 : return cudaVideoCodec_MPEG4;
/*AV_CODEC_ID_VC1*/ case 70 : return cudaVideoCodec_VC1;
/*AV_CODEC_ID_H264*/ case 27 : return cudaVideoCodec_H264;
/*AV_CODEC_ID_HEVC*/ case 173 : return cudaVideoCodec_HEVC;
/*AV_CODEC_ID_VP8*/ case 139 : return cudaVideoCodec_VP8;
/*AV_CODEC_ID_VP9*/ case 167 : return cudaVideoCodec_VP9;
/*AV_CODEC_ID_MJPEG*/ case 7 : return cudaVideoCodec_JPEG;
default : return cudaVideoCodec_NumCodecs;
}
}
class CUVIDDecoderImpl : public CUVIDDecoder{
public:
bool create(bool bUseDeviceFrame, int gpu_id, cudaVideoCodec eCodec, bool bLowLatency = false,
const CropRect *pCropRect = nullptr, const ResizeDim *pResizeDim = nullptr, int max_cache = -1,
int maxWidth = 0, int maxHeight = 0, unsigned int clkRate = 1000, bool output_bgr=false)
{
m_bUseDeviceFrame = bUseDeviceFrame;
m_eCodec = eCodec;
m_nMaxWidth = maxWidth;
m_nMaxHeight = maxHeight;
m_nMaxCache = max_cache;
m_gpuID = gpu_id;
m_output_bgr = output_bgr;
if(m_gpuID == -1){
checkCudaRuntime(cudaGetDevice(&m_gpuID));
}
CUDATools::AutoDevice auto_device_exchange(m_gpuID);
if (pCropRect) m_cropRect = *pCropRect;
if (pResizeDim) m_resizeDim = *pResizeDim;
CUcontext cuContext = nullptr;
checkCudaDriver(cuCtxGetCurrent(&cuContext));
if(cuContext == nullptr){
INFOE("Current Context is nullptr.");
return false;
}
if(!checkCudaDriver(cuvidCtxLockCreate(&m_ctxLock, cuContext))) return false;
if(!checkCudaRuntime(cudaStreamCreate(&m_cuvidStream))) return false;
CUVIDPARSERPARAMS videoParserParameters = {};
videoParserParameters.CodecType = eCodec;
videoParserParameters.ulMaxNumDecodeSurfaces = 1;
videoParserParameters.ulClockRate = clkRate;
videoParserParameters.ulMaxDisplayDelay = bLowLatency ? 0 : 1;
videoParserParameters.pUserData = this;
videoParserParameters.pfnSequenceCallback = handleVideoSequenceProc;
videoParserParameters.pfnDecodePicture = handlePictureDecodeProc;
videoParserParameters.pfnDisplayPicture = handlePictureDisplayProc;
if(!checkCudaDriver(cuvidCreateVideoParser(&m_hParser, &videoParserParameters))) return false;
return true;
}
int decode(const uint8_t *pData, int nSize, int64_t nTimestamp=0) override
{
m_nDecodedFrame = 0;
m_nDecodedFrameReturned = 0;
CUVIDSOURCEDATAPACKET packet = { 0 };
packet.payload = pData;
packet.payload_size = nSize;
packet.flags = CUVID_PKT_TIMESTAMP;
packet.timestamp = nTimestamp;
if (!pData || nSize == 0) {
packet.flags |= CUVID_PKT_ENDOFSTREAM;
}
try{
CUDATools::AutoDevice auto_device_exchange(m_gpuID);
if(!checkCudaDriver(cuvidParseVideoData(m_hParser, &packet)))
return -1;
}catch(...){
return -1;
}
return m_nDecodedFrame;
}
static int CUDAAPI handleVideoSequenceProc(void *pUserData, CUVIDEOFORMAT *pVideoFormat) { return ((CUVIDDecoderImpl *)pUserData)->handleVideoSequence(pVideoFormat); }
static int CUDAAPI handlePictureDecodeProc(void *pUserData, CUVIDPICPARAMS *pPicParams) { return ((CUVIDDecoderImpl *)pUserData)->handlePictureDecode(pPicParams); }
static int CUDAAPI handlePictureDisplayProc(void *pUserData, CUVIDPARSERDISPINFO *pDispInfo) { return ((CUVIDDecoderImpl *)pUserData)->handlePictureDisplay(pDispInfo); }
virtual int device() override{
return this->m_gpuID;
}
virtual bool is_gpu_frame() override{
return this->m_bUseDeviceFrame;
}
int handleVideoSequence(CUVIDEOFORMAT *pVideoFormat){
int nDecodeSurface = pVideoFormat->min_num_decode_surfaces;
CUVIDDECODECAPS decodecaps;
memset(&decodecaps, 0, sizeof(decodecaps));
decodecaps.eCodecType = pVideoFormat->codec;
decodecaps.eChromaFormat = pVideoFormat->chroma_format;
decodecaps.nBitDepthMinus8 = pVideoFormat->bit_depth_luma_minus8;
checkCudaDriver(cuvidGetDecoderCaps(&decodecaps));
if(!decodecaps.bIsSupported){
throw std::runtime_error("Codec not supported on this GPU");
return nDecodeSurface;
}
if ((pVideoFormat->coded_width > decodecaps.nMaxWidth) ||
(pVideoFormat->coded_height > decodecaps.nMaxHeight)){
std::ostringstream errorString;
errorString << std::endl
<< "Resolution : " << pVideoFormat->coded_width << "x" << pVideoFormat->coded_height << std::endl
<< "Max Supported (wxh) : " << decodecaps.nMaxWidth << "x" << decodecaps.nMaxHeight << std::endl
<< "Resolution not supported on this GPU";
const std::string cErr = errorString.str();
throw std::runtime_error(cErr);
return nDecodeSurface;
}
if ((pVideoFormat->coded_width>>4)*(pVideoFormat->coded_height>>4) > decodecaps.nMaxMBCount){
std::ostringstream errorString;
errorString << std::endl
<< "MBCount : " << (pVideoFormat->coded_width >> 4)*(pVideoFormat->coded_height >> 4) << std::endl
<< "Max Supported mbcnt : " << decodecaps.nMaxMBCount << std::endl
<< "MBCount not supported on this GPU";
const std::string cErr = errorString.str();
throw std::runtime_error(cErr);
return nDecodeSurface;
}
// eCodec has been set in the constructor (for parser). Here it's set again for potential correction
m_eCodec = pVideoFormat->codec;
m_eChromaFormat = pVideoFormat->chroma_format;
m_nBitDepthMinus8 = pVideoFormat->bit_depth_luma_minus8;
m_nBPP = m_nBitDepthMinus8 > 0 ? 2 : 1;
// Set the output surface format same as chroma format
if (m_eChromaFormat == cudaVideoChromaFormat_420)
m_eOutputFormat = pVideoFormat->bit_depth_luma_minus8 ? cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
else if (m_eChromaFormat == cudaVideoChromaFormat_444)
m_eOutputFormat = pVideoFormat->bit_depth_luma_minus8 ? cudaVideoSurfaceFormat_YUV444_16Bit : cudaVideoSurfaceFormat_YUV444;
else if (m_eChromaFormat == cudaVideoChromaFormat_422)
m_eOutputFormat = cudaVideoSurfaceFormat_NV12; // no 4:2:2 output format supported yet so make 420 default
// Check if output format supported. If not, check falback options
if (!(decodecaps.nOutputFormatMask & (1 << m_eOutputFormat)))
{
if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_NV12))
m_eOutputFormat = cudaVideoSurfaceFormat_NV12;
else if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_P016))
m_eOutputFormat = cudaVideoSurfaceFormat_P016;
else if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_YUV444))
m_eOutputFormat = cudaVideoSurfaceFormat_YUV444;
else if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_YUV444_16Bit))
m_eOutputFormat = cudaVideoSurfaceFormat_YUV444_16Bit;
else
throw std::runtime_error("No supported output format found");
}
m_videoFormat = *pVideoFormat;
CUVIDDECODECREATEINFO videoDecodeCreateInfo = { 0 };
videoDecodeCreateInfo.CodecType = pVideoFormat->codec;
videoDecodeCreateInfo.ChromaFormat = pVideoFormat->chroma_format;
videoDecodeCreateInfo.OutputFormat = m_eOutputFormat;
videoDecodeCreateInfo.bitDepthMinus8 = pVideoFormat->bit_depth_luma_minus8;
if (pVideoFormat->progressive_sequence)
videoDecodeCreateInfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;
else
videoDecodeCreateInfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Adaptive;
videoDecodeCreateInfo.ulNumOutputSurfaces = 2;
// With PreferCUVID, JPEG is still decoded by CUDA while video is decoded by NVDEC hardware
videoDecodeCreateInfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
videoDecodeCreateInfo.ulNumDecodeSurfaces = nDecodeSurface;
videoDecodeCreateInfo.vidLock = m_ctxLock;
videoDecodeCreateInfo.ulWidth = pVideoFormat->coded_width;
videoDecodeCreateInfo.ulHeight = pVideoFormat->coded_height;
if (m_nMaxWidth < (int)pVideoFormat->coded_width)
m_nMaxWidth = pVideoFormat->coded_width;
if (m_nMaxHeight < (int)pVideoFormat->coded_height)
m_nMaxHeight = pVideoFormat->coded_height;
videoDecodeCreateInfo.ulMaxWidth = m_nMaxWidth;
videoDecodeCreateInfo.ulMaxHeight = m_nMaxHeight;
if (!(m_cropRect.r && m_cropRect.b) && !(m_resizeDim.w && m_resizeDim.h)) {
m_nWidth = pVideoFormat->display_area.right - pVideoFormat->display_area.left;
m_nLumaHeight = pVideoFormat->display_area.bottom - pVideoFormat->display_area.top;
videoDecodeCreateInfo.ulTargetWidth = pVideoFormat->coded_width;
videoDecodeCreateInfo.ulTargetHeight = pVideoFormat->coded_height;
} else {
if (m_resizeDim.w && m_resizeDim.h) {
videoDecodeCreateInfo.display_area.left = pVideoFormat->display_area.left;
videoDecodeCreateInfo.display_area.top = pVideoFormat->display_area.top;
videoDecodeCreateInfo.display_area.right = pVideoFormat->display_area.right;
videoDecodeCreateInfo.display_area.bottom = pVideoFormat->display_area.bottom;
m_nWidth = m_resizeDim.w;
m_nLumaHeight = m_resizeDim.h;
}
if (m_cropRect.r && m_cropRect.b) {
videoDecodeCreateInfo.display_area.left = m_cropRect.l;
videoDecodeCreateInfo.display_area.top = m_cropRect.t;
videoDecodeCreateInfo.display_area.right = m_cropRect.r;
videoDecodeCreateInfo.display_area.bottom = m_cropRect.b;
m_nWidth = m_cropRect.r - m_cropRect.l;
m_nLumaHeight = m_cropRect.b - m_cropRect.t;
}
videoDecodeCreateInfo.ulTargetWidth = m_nWidth;
videoDecodeCreateInfo.ulTargetHeight = m_nLumaHeight;
}
m_nChromaHeight = (int)(m_nLumaHeight * GetChromaHeightFactor(m_eOutputFormat));
m_nNumChromaPlanes = GetChromaPlaneCount(m_eOutputFormat);
m_nSurfaceHeight = videoDecodeCreateInfo.ulTargetHeight;
m_nSurfaceWidth = videoDecodeCreateInfo.ulTargetWidth;
m_displayRect.b = videoDecodeCreateInfo.display_area.bottom;
m_displayRect.t = videoDecodeCreateInfo.display_area.top;
m_displayRect.l = videoDecodeCreateInfo.display_area.left;
m_displayRect.r = videoDecodeCreateInfo.display_area.right;
checkCudaDriver(cuvidCreateDecoder(&m_hDecoder, &videoDecodeCreateInfo));
return nDecodeSurface;
}
int handlePictureDecode(CUVIDPICPARAMS *pPicParams){
if (!m_hDecoder)
{
throw std::runtime_error("Decoder not initialized.");
return false;
}
m_nPicNumInDecodeOrder[pPicParams->CurrPicIdx] = m_nDecodePicCnt++;
checkCudaDriver(cuvidDecodePicture(m_hDecoder, pPicParams));
return 1;
}
int handlePictureDisplay(CUVIDPARSERDISPINFO *pDispInfo){
CUVIDPROCPARAMS videoProcessingParameters = {};
videoProcessingParameters.progressive_frame = pDispInfo->progressive_frame;
videoProcessingParameters.second_field = pDispInfo->repeat_first_field + 1;
videoProcessingParameters.top_field_first = pDispInfo->top_field_first;
videoProcessingParameters.unpaired_field = pDispInfo->repeat_first_field < 0;
videoProcessingParameters.output_stream = m_cuvidStream;
CUdeviceptr dpSrcFrame = 0;
unsigned int nSrcPitch = 0;
checkCudaDriver(cuvidMapVideoFrame(m_hDecoder, pDispInfo->picture_index, &dpSrcFrame,
&nSrcPitch, &videoProcessingParameters));
CUVIDGETDECODESTATUS DecodeStatus;
memset(&DecodeStatus, 0, sizeof(DecodeStatus));
CUresult result = cuvidGetDecodeStatus(m_hDecoder, pDispInfo->picture_index, &DecodeStatus);
if (result == CUDA_SUCCESS && (DecodeStatus.decodeStatus == cuvidDecodeStatus_Error || DecodeStatus.decodeStatus == cuvidDecodeStatus_Error_Concealed))
{
printf("Decode Error occurred for picture %d\n", m_nPicNumInDecodeOrder[pDispInfo->picture_index]);
}
uint8_t *pDecodedFrame = nullptr;
{
if ((unsigned)++m_nDecodedFrame > m_vpFrame.size())
{
/*
如果超过了缓存限制,则覆盖最后一个图
*/
bool need_alloc = true;
if(m_nMaxCache != -1){
if(m_vpFrame.size() >= m_nMaxCache){
--m_nDecodedFrame;
need_alloc = false;
}
}
if(need_alloc){
uint8_t *pFrame = nullptr;
if (m_bUseDeviceFrame)
//checkCudaDriver(cuMemAlloc((CUdeviceptr *)&pFrame, get_frame_bytes()));
checkCudaRuntime(cudaMalloc(&pFrame, get_frame_bytes()));
else
checkCudaRuntime(cudaMallocHost(&pFrame, get_frame_bytes()));
m_vpFrame.push_back(pFrame);
m_vTimestamp.push_back(0);
}
}
pDecodedFrame = m_vpFrame[m_nDecodedFrame - 1];
m_vTimestamp[m_nDecodedFrame - 1] = pDispInfo->timestamp;
}
if(m_output_bgr){
if(m_pYUVFrame == 0){
checkCudaDriver(cuMemAlloc(&m_pYUVFrame, m_nWidth * (m_nLumaHeight + m_nChromaHeight * m_nNumChromaPlanes) * m_nBPP));
}
if(m_pBGRFrame == 0){
checkCudaDriver(cuMemAlloc(&m_pBGRFrame, m_nWidth * m_nLumaHeight * 3));
}
CUDA_MEMCPY2D m = { 0 };
m.srcMemoryType = CU_MEMORYTYPE_DEVICE;
m.srcDevice = dpSrcFrame;
m.srcPitch = nSrcPitch;
m.dstMemoryType = CU_MEMORYTYPE_DEVICE;
m.dstDevice = (CUdeviceptr)(m.dstHost = (uint8_t*)m_pYUVFrame);
m.dstPitch = m_nWidth * m_nBPP;
m.WidthInBytes = m_nWidth * m_nBPP;
m.Height = m_nLumaHeight;
checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream));
m.srcDevice = (CUdeviceptr)((uint8_t *)dpSrcFrame + m.srcPitch * m_nSurfaceHeight);
m.dstDevice = (CUdeviceptr)(m.dstHost = (uint8_t*)m_pYUVFrame + m.dstPitch * m_nLumaHeight);
m.Height = m_nChromaHeight;
checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream));
uint8_t* y = (uint8_t*)m_pYUVFrame;
uint8_t* uv = y + m_nWidth * m_nLumaHeight;
convert_nv12_to_bgr_invoker(y, uv, m_nWidth, m_nLumaHeight, m_nWidth, (uint8_t*)m_pBGRFrame, m_cuvidStream);
if(m_bUseDeviceFrame){
checkCudaDriver(cuMemcpyDtoDAsync((CUdeviceptr)pDecodedFrame, m_pBGRFrame, m_nWidth * m_nLumaHeight * 3, m_cuvidStream));
}else{
checkCudaDriver(cuMemcpyDtoHAsync(pDecodedFrame, m_pBGRFrame, m_nWidth * m_nLumaHeight * 3, m_cuvidStream));
}
}else{
CUDA_MEMCPY2D m = { 0 };
m.srcMemoryType = CU_MEMORYTYPE_DEVICE;
m.srcDevice = dpSrcFrame;
m.srcPitch = nSrcPitch;
m.dstMemoryType = m_bUseDeviceFrame ? CU_MEMORYTYPE_DEVICE : CU_MEMORYTYPE_HOST;
m.dstDevice = (CUdeviceptr)(m.dstHost = pDecodedFrame);
m.dstPitch = m_nWidth * m_nBPP;
m.WidthInBytes = m_nWidth * m_nBPP;
m.Height = m_nLumaHeight;
checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream));
m.srcDevice = (CUdeviceptr)((uint8_t *)dpSrcFrame + m.srcPitch * m_nSurfaceHeight);
m.dstDevice = (CUdeviceptr)(m.dstHost = pDecodedFrame + m.dstPitch * m_nLumaHeight);
m.Height = m_nChromaHeight;
checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream));
if (m_nNumChromaPlanes == 2){
m.srcDevice = (CUdeviceptr)((uint8_t *)dpSrcFrame + m.srcPitch * m_nSurfaceHeight * 2);
m.dstDevice = (CUdeviceptr)(m.dstHost = pDecodedFrame + m.dstPitch * m_nLumaHeight * 2);
m.Height = m_nChromaHeight;
checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream));
}
}
if(!m_bUseDeviceFrame){
// 确保数据是到位的
checkCudaDriver(cuStreamSynchronize(m_cuvidStream));
}
checkCudaDriver(cuvidUnmapVideoFrame(m_hDecoder, dpSrcFrame));
return 1;
}
virtual ICUStream get_stream() override{
return m_cuvidStream;
}
int get_frame_bytes() override {
assert(m_nWidth);
if(m_output_bgr){
return m_nWidth * m_nLumaHeight * 3;
}
return m_nWidth * (m_nLumaHeight + m_nChromaHeight * m_nNumChromaPlanes) * m_nBPP;
}
int get_width() override { assert(m_nWidth); return m_nWidth; }
int get_height() override { assert(m_nLumaHeight); return m_nLumaHeight; }
unsigned int get_frame_index() override { return m_iFrameIndex; }
unsigned int get_num_decoded_frame() override {return m_nDecodedFrame;}
cudaVideoSurfaceFormat get_output_format() { return m_eOutputFormat; }
uint8_t* get_frame(int64_t* pTimestamp = nullptr, unsigned int* pFrameIndex = nullptr) override{
if (m_nDecodedFrame > 0){
if (pFrameIndex)
*pFrameIndex = m_iFrameIndex;
if (pTimestamp)
*pTimestamp = m_vTimestamp[m_nDecodedFrameReturned];
m_nDecodedFrame--;
m_iFrameIndex++;
return m_vpFrame[m_nDecodedFrameReturned++];
}
return nullptr;
}
virtual ~CUVIDDecoderImpl(){
if (m_hParser)
cuvidDestroyVideoParser(m_hParser);
if (m_hDecoder)
cuvidDestroyDecoder(m_hDecoder);
for (uint8_t *pFrame : m_vpFrame){
if (m_bUseDeviceFrame)
//cuMemFree((CUdeviceptr)pFrame);
cudaFree(pFrame);
else
cudaFreeHost(pFrame);
}
if(m_pYUVFrame){
cuMemFree((CUdeviceptr)m_pYUVFrame);
m_pYUVFrame = 0;
}
if(m_pBGRFrame){
cuMemFree((CUdeviceptr)m_pBGRFrame);
m_pBGRFrame = 0;
}
cuvidCtxLockDestroy(m_ctxLock);
}
private:
CUvideoctxlock m_ctxLock = nullptr;
CUvideoparser m_hParser = nullptr;
CUvideodecoder m_hDecoder = nullptr;
bool m_bUseDeviceFrame = false;
// dimension of the output
unsigned int m_nWidth = 0, m_nLumaHeight = 0, m_nChromaHeight = 0;
unsigned int m_nNumChromaPlanes = 0;
// height of the mapped surface
int m_nSurfaceHeight = 0;
int m_nSurfaceWidth = 0;
cudaVideoCodec m_eCodec = cudaVideoCodec_NumCodecs;
cudaVideoChromaFormat m_eChromaFormat;
cudaVideoSurfaceFormat m_eOutputFormat;
int m_nBitDepthMinus8 = 0;
int m_nBPP = 1;
CUVIDEOFORMAT m_videoFormat = {};
CropRect m_displayRect = {};
mutex m_lock;
// stock of frames
std::vector<uint8_t *> m_vpFrame;
CUdeviceptr m_pYUVFrame = 0;
CUdeviceptr m_pBGRFrame = 0;
// timestamps of decoded frames
std::vector<int64_t> m_vTimestamp;
int m_nDecodedFrame = 0, m_nDecodedFrameReturned = 0;
int m_nDecodePicCnt = 0, m_nPicNumInDecodeOrder[32];
CUstream m_cuvidStream = 0;
CropRect m_cropRect = {};
ResizeDim m_resizeDim = {};
unsigned int m_iFrameIndex = 0;
int m_nMaxCache = -1;
int m_gpuID = -1;
unsigned int m_nMaxWidth = 0, m_nMaxHeight = 0;
bool m_output_bgr = true;
};
std::shared_ptr<CUVIDDecoder> create_cuvid_decoder(
bool bUseDeviceFrame, IcudaVideoCodec eCodec, int max_cache, int gpu_id,
const CropRect *pCropRect, const ResizeDim *pResizeDim, bool output_bgr){
shared_ptr<CUVIDDecoderImpl> instance(new CUVIDDecoderImpl());
if(!instance->create(bUseDeviceFrame, gpu_id, (cudaVideoCodec)eCodec, false, pCropRect, pResizeDim, max_cache, 0, 0, 1000, output_bgr))
instance.reset();
return instance;
}
}; //FFHDDecoder
| 45.842803
| 177
| 0.599215
|
shouxieai
|
5dbbb8e8f2cf49cd4bf76f284d059b5a80443409
| 1,347
|
cpp
|
C++
|
Dynamic Programming/139. Word Break/main.cpp
|
Minecodecraft/LeetCode-Minecode
|
185fd6efe88d8ffcad94e581915c41502a0361a0
|
[
"MIT"
] | 1
|
2021-11-19T19:58:33.000Z
|
2021-11-19T19:58:33.000Z
|
Dynamic Programming/139. Word Break/main.cpp
|
Minecodecraft/LeetCode-Minecode
|
185fd6efe88d8ffcad94e581915c41502a0361a0
|
[
"MIT"
] | null | null | null |
Dynamic Programming/139. Word Break/main.cpp
|
Minecodecraft/LeetCode-Minecode
|
185fd6efe88d8ffcad94e581915c41502a0361a0
|
[
"MIT"
] | 2
|
2021-11-26T12:47:27.000Z
|
2022-01-13T16:14:46.000Z
|
//
// main.cpp
// 139. Word Break
//
// Created by 边俊林 on 2019/8/22.
// Copyright © 2019 Minecode.Link. All rights reserved.
//
/* ------------------------------------------------------ *\
https://leetcode.com/problems/word-break/
\* ------------------------------------------------------ */
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/// Solution:
//
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.length();
unordered_set<string> hasa (wordDict.begin(), wordDict.end());
vector<bool> dp (len+1, false);
dp[0] = true;
for (int i = 1; i <= len; ++i) {
for (int j = 1; j <= i; ++j) {
if (dp[j-1] && hasa.find(s.substr(j-1, i-j+1)) != hasa.end())
dp[i] = true;
}
}
return dp[len];
}
};
int main() {
Solution sol = Solution();
// string s = "leetcode";
// vector<string> words = {"leet", "code"};
string s = "applepenapple";
vector<string> words = {"apple", "pen"};
auto res = sol.wordBreak(s, words);
cout << (res ? "true" : "false") << endl;
return 0;
}
| 24.053571
| 77
| 0.504826
|
Minecodecraft
|
5dbed243bc1ef60853dcabaa4ecd87938ddc8c71
| 1,059
|
cpp
|
C++
|
Leetcode/Day026/add_2_num_LL_2.cpp
|
SujalAhrodia/Practice_2020
|
59b371ada245ed8253d12327f18deee3e47f31d6
|
[
"MIT"
] | null | null | null |
Leetcode/Day026/add_2_num_LL_2.cpp
|
SujalAhrodia/Practice_2020
|
59b371ada245ed8253d12327f18deee3e47f31d6
|
[
"MIT"
] | null | null | null |
Leetcode/Day026/add_2_num_LL_2.cpp
|
SujalAhrodia/Practice_2020
|
59b371ada245ed8253d12327f18deee3e47f31d6
|
[
"MIT"
] | null | null | null |
// not sure if this is not reversing the list.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* ans = NULL;
ListNode* prev = ans;
stack<int> s1, s2;
while(l1)
{
s1.push(l1->val);
l1=l1->next;
}
while(l2)
{
s2.push(l2->val);
l2=l2->next;
}
int carry=0;
while(!s1.empty() || !s2.empty() || carry)
{
if(!s1.empty())
{
carry+=s1.top(); s1.pop();
}
if(!s2.empty())
{
carry+=s2.top(); s2.pop();
}
ans= new ListNode(carry%10);
carry=carry/10;
ans->next=prev;
prev=ans;
}
return ans;
}
};
| 20.365385
| 56
| 0.390935
|
SujalAhrodia
|
5dbfb9eee1c05aef2e5a2211f35767cb136b519a
| 3,728
|
cpp
|
C++
|
PhysXChips_Dlg/PhysXMaterial_Dlg.cpp
|
snaxgameengine/PhysXForSnaX
|
aa18d93a30e6cfe11b0258af3733b65de0adf832
|
[
"BSD-3-Clause"
] | 3
|
2021-04-27T08:52:40.000Z
|
2021-05-19T18:05:40.000Z
|
PhysXChips_Dlg/PhysXMaterial_Dlg.cpp
|
snaxgameengine/PhysXForSnaX
|
aa18d93a30e6cfe11b0258af3733b65de0adf832
|
[
"BSD-3-Clause"
] | null | null | null |
PhysXChips_Dlg/PhysXMaterial_Dlg.cpp
|
snaxgameengine/PhysXForSnaX
|
aa18d93a30e6cfe11b0258af3733b65de0adf832
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright(c) 2013-2019, mCODE A/S
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and /or other materials provided with the distribution.
// 3. Neither the name of the copyright holders 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 HOLDERS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "pch.h"
#include "PhysXMaterial_Dlg.h"
using namespace m3d;
DIALOGDESC_DEF(PhysXMaterial_Dlg, PHYSXMATERIAL_GUID);
void PhysXMaterial_Dlg::Init()
{
AddDoubleSpinBox(L"Static Friction", GetChip()->GetStaticFriction(), 0, FLT_MAX, 0.1f, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetStaticFriction(v.ToFloat()); });
AddDoubleSpinBox(L"Dynamic Friction", GetChip()->GetDynamicFriction(), 0, FLT_MAX, 0.1f, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetDynamicFriction(v.ToFloat()); });
AddDoubleSpinBox(L"Restitution", GetChip()->GetRestitution(), 0, 1, 0.1f, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetRestitution(v.ToFloat()); });
AddCheckBox(1, L"Disable Friction", GetChip()->IsDisableFriction() ? RCheckState::Checked : RCheckState::Unchecked, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetDisableFriction(v.ToUInt() == RCheckState::Checked); _enableButtons(); });
AddCheckBox(2, L"Disable Strong Friction", GetChip()->IsDisableStrongFriction() ? RCheckState::Checked : RCheckState::Unchecked, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetDisableStrongFriction(v.ToUInt() == RCheckState::Checked); });
ComboBoxInitList lst;
lst.push_back(std::make_pair(String(L"Average"), RVariant(physx::PxCombineMode::eAVERAGE)));
lst.push_back(std::make_pair(String(L"Minimum"), RVariant(physx::PxCombineMode::eMIN)));
lst.push_back(std::make_pair(String(L"Multiply"), RVariant(physx::PxCombineMode::eMULTIPLY)));
lst.push_back(std::make_pair(String(L"Maximum"), RVariant(physx::PxCombineMode::eMAX)));
AddComboBox(3, L"Friction Combine Mode", lst, GetChip()->GetFrictionCombineMode(), [this](Id id, RVariant v) { SetDirty(); GetChip()->SetFrictionCombineMode((physx::PxCombineMode::Enum)v.ToUInt()); });
AddComboBox(4, L"Restitution Combine Mode", lst, GetChip()->GetRestitutionCombineMode(), [this](Id id, RVariant v) { SetDirty(); GetChip()->SetRestitutionCombineMode((physx::PxCombineMode::Enum)v.ToUInt()); });
_enableButtons();
}
void PhysXMaterial_Dlg::_enableButtons()
{
bool b = GetValueFromWidget(1).ToUInt() == RCheckState::Unchecked;
SetWidgetEnabled(2, b);
SetWidgetEnabled(3, b);
}
| 63.186441
| 246
| 0.747049
|
snaxgameengine
|
5dc9027100b9729b1d99f263135cc6893f3370aa
| 758
|
hpp
|
C++
|
include/eve/function/operator.hpp
|
orao/eve
|
a8bdc6a9cab06d905e8749354cde63776ab76846
|
[
"MIT"
] | null | null | null |
include/eve/function/operator.hpp
|
orao/eve
|
a8bdc6a9cab06d905e8749354cde63776ab76846
|
[
"MIT"
] | null | null | null |
include/eve/function/operator.hpp
|
orao/eve
|
a8bdc6a9cab06d905e8749354cde63776ab76846
|
[
"MIT"
] | null | null | null |
//==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#pragma once
// **=======================================================
// helper file to include all operators
#include <eve/function/add.hpp>
#include <eve/function/plus.hpp>
#include <eve/function/sub.hpp>
#include <eve/function/minus.hpp>
#include <eve/function/div.hpp>
#include <eve/function/rem.hpp>
#include <eve/function/inc.hpp>
#include <eve/function/dec.hpp>
#include <eve/function/rshl.hpp>
#include <eve/function/rshl.hpp>
| 36.095238
| 100
| 0.488127
|
orao
|
5dcb6f415d3d60d3f591f35cd1f585a5ae2cadc7
| 1,596
|
cpp
|
C++
|
crnlib/crn_checksum.cpp
|
HugoPeters/crunch
|
44c8402e24441c7524ca364941fd224ab3b971e9
|
[
"Zlib"
] | 478
|
2015-01-04T16:59:53.000Z
|
2022-03-07T20:28:07.000Z
|
crnlib/crn_checksum.cpp
|
HugoPeters/crunch
|
44c8402e24441c7524ca364941fd224ab3b971e9
|
[
"Zlib"
] | 83
|
2015-01-15T21:45:06.000Z
|
2021-11-08T11:01:48.000Z
|
crnlib/crn_checksum.cpp
|
HugoPeters/crunch
|
44c8402e24441c7524ca364941fd224ab3b971e9
|
[
"Zlib"
] | 175
|
2015-01-04T03:30:39.000Z
|
2020-01-27T17:08:14.000Z
|
// File: crn_checksum.cpp
#include "crn_core.h"
namespace crnlib
{
// From the public domain stb.h header.
uint adler32(const void* pBuf, size_t buflen, uint adler32)
{
const uint8* buffer = static_cast<const uint8*>(pBuf);
const unsigned long ADLER_MOD = 65521;
unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;
size_t blocklen;
unsigned long i;
blocklen = buflen % 5552;
while (buflen) {
for (i=0; i + 7 < blocklen; i += 8) {
s1 += buffer[0], s2 += s1;
s1 += buffer[1], s2 += s1;
s1 += buffer[2], s2 += s1;
s1 += buffer[3], s2 += s1;
s1 += buffer[4], s2 += s1;
s1 += buffer[5], s2 += s1;
s1 += buffer[6], s2 += s1;
s1 += buffer[7], s2 += s1;
buffer += 8;
}
for (; i < blocklen; ++i)
s1 += *buffer++, s2 += s1;
s1 %= ADLER_MOD, s2 %= ADLER_MOD;
buflen -= blocklen;
blocklen = 5552;
}
return (s2 << 16) + s1;
}
uint16 crc16(const void* pBuf, size_t len, uint16 crc)
{
crc = ~crc;
const uint8* p = reinterpret_cast<const uint8*>(pBuf);
while (len)
{
const uint16 q = *p++ ^ (crc >> 8);
crc <<= 8U;
uint16 r = (q >> 4) ^ q;
crc ^= r;
r <<= 5U;
crc ^= r;
r <<= 7U;
crc ^= r;
len--;
}
return static_cast<uint16>(~crc);
}
} // namespace crnlib
| 24.9375
| 63
| 0.43609
|
HugoPeters
|
5dcbdd5bf5ae328f67ff8dc9898c6ee5ad78fa67
| 3,407
|
cpp
|
C++
|
libs/image/color_ops.cpp
|
kdt3rd/gecko
|
756a4e4587eb5023495294d9b6c6d80ebd79ebde
|
[
"MIT"
] | 15
|
2017-10-18T05:08:16.000Z
|
2022-02-02T11:01:46.000Z
|
libs/image/color_ops.cpp
|
kdt3rd/gecko
|
756a4e4587eb5023495294d9b6c6d80ebd79ebde
|
[
"MIT"
] | null | null | null |
libs/image/color_ops.cpp
|
kdt3rd/gecko
|
756a4e4587eb5023495294d9b6c6d80ebd79ebde
|
[
"MIT"
] | 1
|
2018-11-10T03:12:57.000Z
|
2018-11-10T03:12:57.000Z
|
// SPDX-License-Identifier: MIT
// Copyright contributors to the gecko project.
#include "color_ops.h"
#include "threading.h"
#include <color/color.h>
#include <sstream>
////////////////////////////////////////
namespace color
{
engine::hash &operator<<( engine::hash &h, const state &p );
/// \todo { do something smarter (fewer memory allocs) here than serialize to a string }
engine::hash &operator<<( engine::hash &h, const state &p )
{
std::stringstream tmp;
tmp << p;
h << tmp.str();
return h;
}
} // namespace color
////////////////////////////////////////
namespace image
{
////////////////////////////////////////
static void colorspace_line(
size_t,
int s,
int e,
image_buf & ret,
const image_buf & src,
const color::state &from,
const color::state &to )
{
plane & xOut = ret[0];
plane & yOut = ret[1];
plane & zOut = ret[2];
const plane &xIn = src[0];
const plane &yIn = src[1];
const plane &zIn = src[2];
int w = ret.width();
for ( int y = s; y < e; ++y )
{
float * xLine = xOut.line( y );
float * yLine = yOut.line( y );
float * zLine = zOut.line( y );
const float *xInLine = xIn.line( y );
const float *yInLine = yIn.line( y );
const float *zInLine = zIn.line( y );
for ( int x = 0; x < w; ++x )
{
float xV = xInLine[x];
float yV = yInLine[x];
float zV = zInLine[x];
/// \todo { extract the logic inside here out to a higher level... }
color::convert( xV, yV, zV, from, to, 32 );
xLine[x] = xV;
yLine[x] = yV;
zLine[x] = zV;
}
for ( size_t i = 3; i < ret.size(); ++i )
std::copy(
src[i].line( y ), src[i].line( y ) + w, ret[i].line( y ) );
}
}
////////////////////////////////////////
static image_buf
compute_colorspace( const image_buf &a, color::state from, color::state to )
{
image_buf ret;
for ( size_t i = 0; i != a.size(); ++i )
ret.add_plane( plane( a.x1(), a.y1(), a.x2(), a.y2() ) );
threading::get().dispatch(
std::bind(
colorspace_line,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::ref( ret ),
std::cref( a ),
std::cref( from ),
std::cref( to ) ),
a.y1(),
a.height() );
return ret;
}
////////////////////////////////////////
image_buf colorspace(
const image_buf &a, const color::state &from, const color::state &to )
{
if ( a.size() < 3 )
throw std::logic_error(
"Attempt to convert color space on an image with fewer than 3 planes" );
engine::dimensions d = a.dims();
d.planes = static_cast<engine::dimensions::value_type>( a.size() );
d.images = 1;
return image_buf( "i.colorspace", d, a, from, to );
}
////////////////////////////////////////
void add_color_ops( engine::registry &r )
{
using namespace engine;
r.register_constant<color::state>();
// we will just do a threaded op so we can optimize the from / to operations applied once
r.add( op( "i.colorspace", compute_colorspace, op::threaded ) );
}
} // namespace image
| 26.207692
| 93
| 0.487526
|
kdt3rd
|
5dd1174a5b97fe10eb3ec2729a3225b446f3c65e
| 13,323
|
cpp
|
C++
|
src/kernel/Version.cpp
|
PHP-OPEN-HUB/polarphp
|
70ff4046e280fd99d718d4761686168fa8012aa5
|
[
"PHP-3.01"
] | null | null | null |
src/kernel/Version.cpp
|
PHP-OPEN-HUB/polarphp
|
70ff4046e280fd99d718d4761686168fa8012aa5
|
[
"PHP-3.01"
] | null | null | null |
src/kernel/Version.cpp
|
PHP-OPEN-HUB/polarphp
|
70ff4046e280fd99d718d4761686168fa8012aa5
|
[
"PHP-3.01"
] | null | null | null |
//===--- Version.cpp - Swift Version Number -------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
//===----------------------------------------------------------------------===//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2019/04/26.
//===----------------------------------------------------------------------===//
//
// This file defines several version-related utility functions for polarphp.
//
//===----------------------------------------------------------------------===//
#include "polarphp/basic/CharInfo.h"
#include "polarphp/basic/adt/SmallString.h"
#include "polarphp/basic/adt/StringExtras.h"
#include "polarphp/utils/RawOutStream.h"
#include "polarphp/kernel/Version.h"
#include "polarphp/ast/DiagnosticsParse.h"
#include <vector>
#define TOSTR2(X) #X
#define TOSTR(X) TOSTR2(X)
#ifdef POLAR_VERSION_PATCHLEVEL
/// Helper macro for POLAR_VERSION_STRING.
#define POLAR_MAKE_VERSION_STRING(X, Y, Z) TOSTR(X) "." TOSTR(Y) "." TOSTR(Z)
/// A string that describes the Swift version number, e.g., "1.0".
#define POLAR_VERSION_STRING \
POLAR_MAKE_VERSION_STRING(POLAR_VERSION_MAJOR, POLAR_VERSION_MINOR, \
POLAR_VERSION_PATCHLEVEL)
#else
/// Helper macro for POLAR_VERSION_STRING.
#define POLAR_MAKE_VERSION_STRING(X, Y) TOSTR(X) "." TOSTR(Y)
/// A string that describes the Swift version number, e.g., "1.0".
#define POLAR_VERSION_STRING \
POLAR_MAKE_VERSION_STRING(POLAR_VERSION_MAJOR, POLAR_VERSION_MINOR)
#endif
namespace polar::version {
using polar::utils::RawOutStream;
using polar::utils::RawStringOutStream;
using polar::utils::RawSvectorOutStream;
using polar::parser::SourceLoc;
using polar::parser::SourceRange;
using polar::basic::SmallVectorImpl;
using polar::basic::SmallString;
/// Print a string of the form "LLVM xxxxx, Clang yyyyy, Swift zzzzz",
/// where each placeholder is the revision for the associated repository.
//static void print_full_revision_string(RawOutStream &out)
//{
//}
static void split_version_components(
SmallVectorImpl<std::pair<StringRef, SourceRange>> &splitComponents,
StringRef &versionString, SourceLoc loc,
bool skipQuote = false)
{
SourceLoc start = (loc.isValid() && skipQuote) ? loc.getAdvancedLoc(1) : loc;
SourceLoc end = start;
// Split the version string into tokens separated by the '.' character.
while (!versionString.empty()) {
StringRef SplitComponent, Rest;
std::tie(SplitComponent, Rest) = versionString.split('.');
if (loc.isValid()) {
end = end.getAdvancedLoc(SplitComponent.size());
}
auto range = loc.isValid() ? SourceRange(start, end) : SourceRange();
if (loc.isValid()) {
end = end.getAdvancedLoc(1);
}
start = end;
splitComponents.push_back({SplitComponent, range});
versionString = Rest;
}
}
std::optional<Version> Version::parseCompilerVersionString(
StringRef versionString, SourceLoc loc, DiagnosticEngine *diags)
{
Version CV;
SmallString<16> digits;
RawSvectorOutStream OS(digits);
SmallVector<std::pair<StringRef, SourceRange>, 5> splitComponents;
split_version_components(splitComponents, versionString, loc,
/*skipQuote=*/true);
// uint64_t componentNumber;
bool isValidVersion = true;
// auto checkVersionComponent = [&](unsigned Component, SourceRange range) {
// unsigned limit = CV.m_components.empty() ? 9223371 : 999;
// if (Component > limit) {
// if (diags)
// diags->diagnose(range.start,
// polar::ast::diag::compiler_version_component_out_of_range, limit);
// isValidVersion = false;
// }
// };
// for (size_t i = 0; i < splitComponents.size(); ++i) {
// StringRef SplitComponent;
// SourceRange range;
// std::tie(SplitComponent, range) = splitComponents[i];
// // Version components can't be empty.
// if (SplitComponent.empty()) {
// if (diags)
// diags->diagnose(range.start, diag::empty_version_component);
// isValidVersion = false;
// continue;
// }
// // The second version component isn't used for comparison.
// if (i == 1) {
// if (!SplitComponent.equals("*")) {
// if (diags)
// diags->diagnose(range.start, diag::unused_compiler_version_component)
// .fixItReplaceChars(range.start, range.end, "*");
// }
// CV.m_components.push_back(0);
// continue;
// }
// // All other version components must be numbers.
// if (!SplitComponent.getAsInteger(10, componentNumber)) {
// checkVersionComponent(componentNumber, range);
// CV.m_components.push_back(componentNumber);
// continue;
// } else {
// if (diags)
// diags->diagnose(range.start, diag::version_component_not_number);
// isValidVersion = false;
// }
// }
// if (CV.m_components.size() > 5) {
// if (diags)
// diags->diagnose(loc, diag::compiler_version_too_many_components);
// isValidVersion = false;
// }
return isValidVersion ? std::optional<Version>(CV) : std::nullopt;
}
std::optional<Version> Version::parseVersionString(StringRef versionString,
SourceLoc loc,
DiagnosticEngine *diags)
{
Version TheVersion;
SmallString<16> digits;
RawSvectorOutStream OS(digits);
SmallVector<std::pair<StringRef, SourceRange>, 5> splitComponents;
// Skip over quote character in string literal.
// if (versionString.empty()) {
// if (diags)
// diags->diagnose(loc, diag::empty_version_string);
// return None;
// }
split_version_components(splitComponents, versionString, loc, diags);
// uint64_t componentNumber;
bool isValidVersion = true;
// for (size_t i = 0; i < splitComponents.size(); ++i) {
// StringRef SplitComponent;
// SourceRange range;
// std::tie(SplitComponent, range) = splitComponents[i];
// // Version components can't be empty.
// if (SplitComponent.empty()) {
// if (diags)
// diags->diagnose(range.start, diag::empty_version_component);
// isValidVersion = false;
// continue;
// }
// // All other version components must be numbers.
// if (!SplitComponent.getAsInteger(10, componentNumber)) {
// TheVersion.m_components.push_back(componentNumber);
// continue;
// } else {
// if (diags)
// diags->diagnose(range.start,
// diag::version_component_not_number);
// isValidVersion = false;
// }
// }
return isValidVersion ? std::optional<Version>(TheVersion) : std::nullopt;
}
Version::Version(StringRef versionString,
SourceLoc loc,
DiagnosticEngine *diags)
: Version(*parseVersionString(versionString, loc, diags))
{}
Version Version::getCurrentCompilerVersion()
{
//#ifdef POLARPHP_VERSION
// auto currentVersion = Version::parseVersionString(
// POLARPHP_VERSION, SourceLoc(), nullptr);
// assert(currentVersion.hasValue() &&
// "Embedded polarphp language version couldn't be parsed: '"
// POLARPHP_VERSION
// "'");
// return currentVersion.getValue();
//#else
// return Version();
//#endif
return Version();
}
Version Version::getCurrentLanguageVersion()
{
#if POLAR_VERSION_PATCHLEVEL
return {0, 1, 1};
#else
return {0, 1};
#endif
}
RawOutStream &operator<<(RawOutStream &outStream, const Version &version)
{
if (version.empty()) {
return outStream;
}
outStream << version[0];
for (size_t i = 1, e = version.size(); i != e; ++i) {
outStream << '.' << version[i];
}
return outStream;
}
std::string
Version::preprocessorDefinition(StringRef macroName,
ArrayRef<uint64_t> componentWeights) const
{
uint64_t versionConstant = 0;
for (size_t i = 0, e = std::min(componentWeights.getSize(), m_components.size());
i < e; ++i) {
versionConstant += componentWeights[i] * m_components[i];
}
std::string define("-D");
RawStringOutStream(define) << macroName << '=' << versionConstant;
// This isn't using stream.str() so that we get move semantics.
return define;
}
Version::operator VersionTuple() const
{
switch (m_components.size()) {
case 0:
return VersionTuple();
case 1:
return VersionTuple((unsigned)m_components[0]);
case 2:
return VersionTuple((unsigned)m_components[0],
(unsigned)m_components[1]);
case 3:
return VersionTuple((unsigned)m_components[0],
(unsigned)m_components[1],
(unsigned)m_components[2]);
case 4:
case 5:
return VersionTuple((unsigned)m_components[0],
(unsigned)m_components[1],
(unsigned)m_components[2],
(unsigned)m_components[3]);
default:
polar_unreachable("polar::version::Version with 6 or more components");
}
}
std::optional<Version> Version::getEffectiveLanguageVersion() const
{
switch (size()) {
case 0:
return std::nullopt;
case 1:
break;
case 2:
// The only valid explicit language version with a minor
// component is 4.2.
if (m_components[0] == 4 && m_components[1] == 2) {
break;
}
return std::nullopt;
default:
// We do not want to permit users requesting more precise effective language
// versions since accepting such an argument promises more than we're able
// to deliver.
return std::nullopt;
}
// FIXME: When we switch to Swift 5 by default, the "4" case should return
// a version newer than any released 4.x compiler, and the
// "5" case should start returning getCurrentLanguageVersion. We should
// also check for the presence of SWIFT_VERSION_PATCHLEVEL, and if that's
// set apply it to the "3" case, so that Swift 4.0.1 will automatically
// have a compatibility mode of 3.2.1.
switch (m_components[0]) {
case 4:
// Version '4' on its own implies '4.1.50'.
if (size() == 1) {
return Version{4, 1, 50};
}
// This should be true because of the check up above.
assert(size() == 2 && m_components[0] == 4 && m_components[1] == 2);
return Version{4, 2};
case 5:
// static_assert(POLAR_VERSION_MAJOR == 5,
// "getCurrentLanguageVersion is no longer correct here");
return Version::getCurrentLanguageVersion();
default:
return std::nullopt;
}
}
Version Version::asMajorVersion() const
{
if (empty()) {
return {};
}
Version res;
res.m_components.push_back(m_components[0]);
return res;
}
std::string Version::asAPINotesVersionString() const
{
// Other than for "4.2.x", map the Swift major version into
// the API notes version for Swift. This has the effect of allowing
// API notes to effect changes only on Swift major versions,
// not minor versions.
if (size() >= 2 && m_components[0] == 4 && m_components[1] == 2) {
return "4.2";
}
return polar::basic::itostr(m_components[0]);
}
bool operator>=(const class Version &lhs,
const class Version &rhs) {
// The empty compiler version represents the latest possible version,
// usually built from the source repository.
if (lhs.empty())
return true;
auto n = std::max(lhs.size(), rhs.size());
for (size_t i = 0; i < n; ++i) {
auto lv = i < lhs.size() ? lhs[i] : 0;
auto rv = i < rhs.size() ? rhs[i] : 0;
if (lv < rv)
return false;
else if (lv > rv)
return true;
}
// Equality
return true;
}
bool operator<(const class Version &lhs, const class Version &rhs) {
return !(lhs >= rhs);
}
bool operator==(const class Version &lhs,
const class Version &rhs) {
auto n = std::max(lhs.size(), rhs.size());
for (size_t i = 0; i < n; ++i) {
auto lv = i < lhs.size() ? lhs[i] : 0;
auto rv = i < rhs.size() ? rhs[i] : 0;
if (lv != rv) {
return false;
}
}
return true;
}
std::pair<unsigned, unsigned> retrieve_polarphp_numeric_version()
{
return { 0, 1 };
}
std::string retrieve_polarphp_full_version(Version effectiveVersion)
{
return "";
}
std::string retrieve_polarphp_revision()
{
return "";
}
} // polar::version
| 31.201405
| 96
| 0.61953
|
PHP-OPEN-HUB
|
5dd14a1d5e434f04c1ee055a0d27bf099a7e7f5a
| 1,245
|
hpp
|
C++
|
sprout/numeric/dft/cxx14/spectrum.hpp
|
kevcadieux/Sprout
|
6b5addba9face0a6403e66e7db2aa94d87387f61
|
[
"BSL-1.0"
] | 691
|
2015-01-15T18:52:23.000Z
|
2022-03-15T23:39:39.000Z
|
sprout/numeric/dft/cxx14/spectrum.hpp
|
kevcadieux/Sprout
|
6b5addba9face0a6403e66e7db2aa94d87387f61
|
[
"BSL-1.0"
] | 22
|
2015-03-11T01:22:56.000Z
|
2021-03-29T01:51:45.000Z
|
sprout/numeric/dft/cxx14/spectrum.hpp
|
kevcadieux/Sprout
|
6b5addba9face0a6403e66e7db2aa94d87387f61
|
[
"BSL-1.0"
] | 57
|
2015-03-11T07:52:29.000Z
|
2021-12-16T09:15:33.000Z
|
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_NUMERIC_DFT_CXX14_SPECTRUM_HPP
#define SPROUT_NUMERIC_DFT_CXX14_SPECTRUM_HPP
#include <sprout/config.hpp>
#include <sprout/iterator/type_traits/is_iterator_of.hpp>
#include <sprout/type_traits/enabler_if.hpp>
#include <sprout/numeric/dft/cxx14/amplitude_spectrum.hpp>
#include <sprout/numeric/dft/cxx14/phase_spectrum.hpp>
namespace sprout {
//
// spectrum
//
template<
typename InputIterator, typename OutputIterator,
typename sprout::enabler_if<sprout::is_iterator_outputable<OutputIterator>::value>::type = sprout::enabler
>
inline SPROUT_CXX14_CONSTEXPR OutputIterator
spectrum(InputIterator first, InputIterator last, OutputIterator result) {
return sprout::amplitude_spectrum(first, last, result);
}
} // namespace sprout
#endif // #ifndef SPROUT_NUMERIC_DFT_CXX14_SPECTRUM_HPP
| 38.90625
| 109
| 0.680321
|
kevcadieux
|
5dd7a523db90223a3c025dd6f203d0d8374852dc
| 52
|
cc
|
C++
|
vector/Vector.cc
|
me701/cpp_classes
|
302d10855069bbb818d317cc98d21ae9d7f8f3eb
|
[
"MIT"
] | null | null | null |
vector/Vector.cc
|
me701/cpp_classes
|
302d10855069bbb818d317cc98d21ae9d7f8f3eb
|
[
"MIT"
] | null | null | null |
vector/Vector.cc
|
me701/cpp_classes
|
302d10855069bbb818d317cc98d21ae9d7f8f3eb
|
[
"MIT"
] | null | null | null |
#include "Vector.hh"
// Member definitions go here
| 13
| 29
| 0.730769
|
me701
|
5ddf649cbcc500b7ebfe96f1e6cc58a638ac0ebf
| 4,661
|
cpp
|
C++
|
src/Devantech_CMPS11.cpp
|
sgparry/Devantech_Compass
|
d49fea0d03ff2adf0c9e527c81bab9ddfd728356
|
[
"MIT"
] | null | null | null |
src/Devantech_CMPS11.cpp
|
sgparry/Devantech_Compass
|
d49fea0d03ff2adf0c9e527c81bab9ddfd728356
|
[
"MIT"
] | null | null | null |
src/Devantech_CMPS11.cpp
|
sgparry/Devantech_Compass
|
d49fea0d03ff2adf0c9e527c81bab9ddfd728356
|
[
"MIT"
] | null | null | null |
/***********************************************************************************
* Copyright (c) 2018 EduMake Limited and Stephen Parry (sgparry@mainscreen.com)
* See file LICENSE for further details
* MIT license, this line and all text above must be included in any redistribution
***********************************************************************************/
// Derived from code by Dirk Grappendorf (www.grappendorf.net)
// for the SRF02 sensor.
#if ARDUINO >= 100
#include "Arduino.h"
#define WIRE_WRITE Wire.write
#define WIRE_READ Wire.read
#else
#include "WProgram.h"
#define WIRE_WRITE Wire.send
#define WIRE_READ Wire.receive
#endif
#include "Wire.h"
#include "Devantech_CMPS11.h"
const int REG_MAGX_HIGH = 6;
const int REG_MAGX_LOW = 7;
const int REG_MAGY_HIGH = 8;
const int REG_MAGY_LOW = 9;
const int REG_MAGZ_HIGH = 10;
const int REG_MAGZ_LOW = 11;
const int REG_ACCX_HIGH = 12;
const int REG_ACCX_LOW = 13;
const int REG_ACCY_HIGH = 14;
const int REG_ACCY_LOW = 15;
const int REG_ACCZ_HIGH = 16;
const int REG_ACCZ_LOW = 17;
const int REG_GYRX_HIGH = 18;
const int REG_GYRX_LOW = 19;
const int REG_GYRY_HIGH = 20;
const int REG_GYRY_LOW = 21;
const int REG_GYRZ_HIGH = 22;
const int REG_GYRZ_LOW = 23;
const int REG_TEMP_HIGH = 24;
const int REG_TEMP_LOW = 25;
const int REG_PITCH_NK = 26;
const int REG_ROLL_NK = 27;
const int REG_CMD = 0;
int16_t Devantech_CMPS11::magX()
{
return (int16_t)regReadWord(REG_MAGX_HIGH);
}
int16_t Devantech_CMPS11::magY()
{
return (int16_t)regReadWord(REG_MAGY_HIGH);
}
int16_t Devantech_CMPS11::magZ()
{
return (int16_t)regReadWord(REG_MAGZ_HIGH);
}
int16_t Devantech_CMPS11::accX()
{
return (int16_t)regReadWord(REG_ACCX_HIGH);
}
int16_t Devantech_CMPS11::accY()
{
return (int16_t)regReadWord(REG_ACCY_HIGH);
}
int16_t Devantech_CMPS11::accZ()
{
return (int16_t)regReadWord(REG_ACCZ_HIGH);
}
int16_t Devantech_CMPS11::gyrX()
{
return (int16_t)regReadWord(REG_GYRX_HIGH);
}
int16_t Devantech_CMPS11::gyrY()
{
return (int16_t)regReadWord(REG_GYRY_HIGH);
}
int16_t Devantech_CMPS11::gyrZ()
{
return (int16_t)regReadWord(REG_GYRZ_HIGH);
}
int8_t Devantech_CMPS11::pitchNK()
{
return (int8_t)(regReadByte(REG_PITCH_NK));
}
int8_t Devantech_CMPS11::rollNK()
{
return (int8_t)(regReadByte(REG_ROLL_NK));
}
int16_t Devantech_CMPS11::temp()
{
return (int16_t)(regReadWord(REG_TEMP_HIGH));
}
Devantech_Compass::CompassStatus Devantech_CMPS11::doCalibration(CompassPoint cp)
{
if( regWriteByteFrame(REG_CMD,0xF0,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0xF5,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0xF7,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
return CS_READY_COMMIT;
}
Devantech_Compass::CompassStatus Devantech_CMPS11::doCalibration3D()
{
if( regWriteByteFrame(REG_CMD,0xF0,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0xF5,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0xF6,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
return CS_READY_COMMIT;
}
Devantech_Compass::CompassStatus Devantech_CMPS11::commitCalibration()
{
if( regWriteByteFrame(REG_CMD,0xF8,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
return CS_ALL_COMPLETE;
}
Devantech_Compass::CompassStatus Devantech_CMPS11::resetCalibration()
{
if( regWriteByteFrame(REG_CMD,0x20,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0x2A,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0x60,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
return CS_ALL_COMPLETE;
}
Devantech_Compass::CompassStatus Devantech_CMPS11::configureDeviceId(uint8_t newDeviceId)
{
if( regWriteByteFrame(REG_CMD,0xA0,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0xAA,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,0xA5,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
if( regWriteByteFrame(REG_CMD,newDeviceId << 1,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR;
this->deviceId = newDeviceId;
return CS_ALL_COMPLETE;
}
Devantech_Compass::CompassCaps Devantech_CMPS11::getCaps()
{
return CompassCaps(
CC_CALIBRATE |
CC_FACTORY_RESET |
CC_CALIBRATE_3D |
CC_PITCH_AND_ROLL |
CC_MAG_XYZ |
CC_ACC_XYZ |
CC_GYRO_XYZ |
CC_TEMP |
CC_PITCH_AND_ROLL_NK |
CC_CONFIG_DEVICE_ID);
}
| 29.314465
| 111
| 0.750483
|
sgparry
|
5de3630a88b02043850ea8c06e3e3203199c0546
| 214
|
cpp
|
C++
|
reverse_strings.cpp
|
HeyIamJames/Learning-C-
|
623fad8cb50d71e7404f270f965c8915f8a02c64
|
[
"MIT"
] | null | null | null |
reverse_strings.cpp
|
HeyIamJames/Learning-C-
|
623fad8cb50d71e7404f270f965c8915f8a02c64
|
[
"MIT"
] | null | null | null |
reverse_strings.cpp
|
HeyIamJames/Learning-C-
|
623fad8cb50d71e7404f270f965c8915f8a02c64
|
[
"MIT"
] | null | null | null |
void reverseChar(char* str) {
const size_t len = strlen(str);
for(size_t i=0; i<len/2; i++)
swap(str[i], str[len-i-1]);
}
void reverseChar(char* str) {
std::reverse(str, str + strlen(str));
}
| 19.454545
| 41
| 0.584112
|
HeyIamJames
|
5de59cb07f002d870ba38d424909ae56214de11f
| 6,492
|
hpp
|
C++
|
src/tpl/simpool/DynamicPoolAllocator.hpp
|
nanzifan/Umpire-edit
|
990895b527bef0716aaa0fbb0c0f2017e8e15882
|
[
"MIT"
] | null | null | null |
src/tpl/simpool/DynamicPoolAllocator.hpp
|
nanzifan/Umpire-edit
|
990895b527bef0716aaa0fbb0c0f2017e8e15882
|
[
"MIT"
] | null | null | null |
src/tpl/simpool/DynamicPoolAllocator.hpp
|
nanzifan/Umpire-edit
|
990895b527bef0716aaa0fbb0c0f2017e8e15882
|
[
"MIT"
] | null | null | null |
#ifndef _DYNAMICPOOLALLOCATOR_HPP
#define _DYNAMICPOOLALLOCATOR_HPP
#include <cstddef>
#include <cassert>
#include "umpire/tpl/simpool/StdAllocator.hpp"
#include "umpire/tpl/simpool/FixedPoolAllocator.hpp"
#include "umpire/strategy/AllocationStrategy.hpp"
template <class IA = StdAllocator>
class DynamicPoolAllocator
{
protected:
struct Block
{
char *data;
std::size_t size;
bool isHead;
Block *next;
};
// Allocator for the underlying data
typedef FixedPoolAllocator<struct Block, IA, (1<<6)> BlockAlloc;
BlockAlloc blockAllocator;
// Start of the nodes of used and free block lists
struct Block *usedBlocks;
struct Block *freeBlocks;
// Total size allocated (bytes)
std::size_t totalBytes;
// Allocated size (bytes)
std::size_t allocBytes;
// Minimum size for allocations
std::size_t minBytes;
// Pointer to our allocator's allocation strategy
std::shared_ptr<umpire::strategy::AllocationStrategy> allocator;
// Search the list of free blocks and return a usable one if that exists, else NULL
void findUsableBlock(struct Block *&best, struct Block *&prev, std::size_t size) {
best = prev = NULL;
for ( struct Block *iter = freeBlocks, *iterPrev = NULL ; iter ; iter = iter->next ) {
if ( iter->size >= size && (!best || iter->size < best->size) ) {
best = iter;
prev = iterPrev;
}
iterPrev = iter;
}
}
inline std::size_t alignmentAdjust(const std::size_t size) {
const std::size_t AlignmentBoundary = 16;
return std::size_t (size + (AlignmentBoundary-1)) & ~(AlignmentBoundary-1);
}
// Allocate a new block and add it to the list of free blocks
void allocateBlock(struct Block *&curr, struct Block *&prev, const std::size_t size) {
const std::size_t sizeToAlloc = std::max(alignmentAdjust(size), minBytes);
curr = prev = NULL;
void *data = NULL;
// Allocate data
data = allocator->allocate(sizeToAlloc);
totalBytes += sizeToAlloc;
assert(data);
// Find next and prev such that next->data is still smaller than data (keep ordered)
struct Block *next;
for ( next = freeBlocks; next && next->data < data; next = next->next ) {
prev = next;
}
// Allocate the block
curr = (struct Block *) blockAllocator.allocate();
if (!curr) return;
curr->data = static_cast<char *>(data);
curr->size = sizeToAlloc;
curr->isHead = true;
curr->next = next;
// Insert
if (prev) prev->next = curr;
else freeBlocks = curr;
}
void splitBlock(struct Block *&curr, struct Block *&prev, const std::size_t size) {
struct Block *next;
const std::size_t alignedsize = alignmentAdjust(size);
if ( curr->size == size || curr->size == alignedsize ) {
// Keep it
next = curr->next;
}
else {
// Split the block
std::size_t remaining = curr->size - alignedsize;
struct Block *newBlock = (struct Block *) blockAllocator.allocate();
if (!newBlock) return;
newBlock->data = curr->data + alignedsize;
newBlock->size = remaining;
newBlock->isHead = false;
newBlock->next = curr->next;
next = newBlock;
curr->size = alignedsize;
}
if (prev) prev->next = next;
else freeBlocks = next;
}
void releaseBlock(struct Block *curr, struct Block *prev) {
assert(curr != NULL);
if (prev) prev->next = curr->next;
else usedBlocks = curr->next;
// Find location to put this block in the freeBlocks list
prev = NULL;
for ( struct Block *temp = freeBlocks ; temp && temp->data < curr->data ; temp = temp->next ) {
prev = temp;
}
// Keep track of the successor
struct Block *next = prev ? prev->next : freeBlocks;
// Check if prev and curr can be merged
if ( prev && prev->data + prev->size == curr->data && !curr->isHead ) {
prev->size = prev->size + curr->size;
blockAllocator.deallocate(curr); // keep data
curr = prev;
}
else if (prev) {
prev->next = curr;
}
else {
freeBlocks = curr;
}
// Check if curr and next can be merged
if ( next && curr->data + curr->size == next->data && !next->isHead ) {
curr->size = curr->size + next->size;
curr->next = next->next;
blockAllocator.deallocate(next); // keep data
}
else {
curr->next = next;
}
}
void freeAllBlocks() {
// Release the used blocks
while(usedBlocks) {
releaseBlock(usedBlocks, NULL);
}
// Release the unused blocks
while(freeBlocks) {
assert(freeBlocks->isHead);
allocator->deallocate(freeBlocks->data);
totalBytes -= freeBlocks->size;
struct Block *curr = freeBlocks;
freeBlocks = freeBlocks->next;
blockAllocator.deallocate(curr);
}
}
public:
DynamicPoolAllocator(
std::shared_ptr<umpire::strategy::AllocationStrategy> strat,
const std::size_t _minBytes = (1 << 8))
: blockAllocator(),
usedBlocks(NULL),
freeBlocks(NULL),
totalBytes(0),
allocBytes(0),
minBytes(_minBytes),
allocator(strat) { }
~DynamicPoolAllocator() { freeAllBlocks(); }
void *allocate(std::size_t size) {
struct Block *best, *prev;
findUsableBlock(best, prev, size);
// Allocate a block if needed
if (!best) allocateBlock(best, prev, size);
assert(best);
// Split the free block
splitBlock(best, prev, size);
// Push node to the list of used nodes
best->next = usedBlocks;
usedBlocks = best;
// Increment the allocated size
allocBytes += size;
// Return the new pointer
return usedBlocks->data;
}
void deallocate(void *ptr) {
assert(ptr);
// Find the associated block
struct Block *curr = usedBlocks, *prev = NULL;
for ( ; curr && curr->data != ptr; curr = curr->next ) {
prev = curr;
}
if (!curr) return;
// Remove from allocBytes
allocBytes -= curr->size;
// Release it
releaseBlock(curr, prev);
}
std::size_t allocatedSize() const { return allocBytes; }
std::size_t totalSize() const {
return totalBytes + blockAllocator.totalSize();
}
std::size_t numFreeBlocks() const {
std::size_t nb = 0;
for (struct Block *temp = freeBlocks; temp; temp = temp->next) nb++;
return nb;
}
std::size_t numUsedBlocks() const {
std::size_t nb = 0;
for (struct Block *temp = usedBlocks; temp; temp = temp->next) nb++;
return nb;
}
};
#endif
| 26.606557
| 99
| 0.628928
|
nanzifan
|
5de9de20e00b94b067e4445dd7c48b5a84932e64
| 4,185
|
hpp
|
C++
|
include/itp/core_bits/core_fileio.hpp
|
TING2938/Gmx2020PostAnalysis
|
0859383946c05c7424adb1ffa72fd2f8066ce850
|
[
"MIT"
] | 4
|
2021-11-23T15:02:13.000Z
|
2022-03-21T16:32:09.000Z
|
include/itp/core_bits/core_fileio.hpp
|
jianghuili/Gmx2020PostAnalysis
|
0859383946c05c7424adb1ffa72fd2f8066ce850
|
[
"MIT"
] | null | null | null |
include/itp/core_bits/core_fileio.hpp
|
jianghuili/Gmx2020PostAnalysis
|
0859383946c05c7424adb1ffa72fd2f8066ce850
|
[
"MIT"
] | 1
|
2021-11-23T15:01:49.000Z
|
2021-11-23T15:01:49.000Z
|
#ifndef __CORE_FILEIO_HPP__
#define __CORE_FILEIO_HPP__
#include <fstream>
#include "../core"
namespace itp
{
namespace inner
{
inline bool is_comment(std::string& line, std::string& comments)
{
auto np = line.find_first_not_of(" ");
return np == std::string::npos || (comments.size() != 0 &&
comments.find_first_of(line[np]) != std::string::npos);
}
}
/**
* @brief 读取文本数据文件
* @tparam T 数据标量类型
* @param is 文件流
* @param nrows 行数,默认自动确定
* @param ncols 列数,默认自动确定
* @param comments 注释字符
* @param skiprows 跳过开头行数
* @return 数据矩阵
*/
template <typename T = double>
Eigen::Array<T, Dynamic, Dynamic> loadtxt(std::istream& is,
int nrows = Dynamic, int ncols = Dynamic, std::string comments = "#@", int skiprows = 0)
{
std::string line;
T buff;
std::stringstream ss;
for (int i = 0; i != skiprows; ++i)
std::getline(is, line);
if (ncols == Dynamic) {
ncols = 0;
while (std::getline(is, line))
if (!inner::is_comment(line, comments)) {
ss.str(line);
while (ss >> buff)
++ncols;
break;
}
} else {
std::getline(is, line);
}
if (nrows == Dynamic) {
std::vector<T> vec;
do {
if (!inner::is_comment(line, comments)) {
ss.clear();
ss.str(line);
for (int i = 0; i != ncols; ++i) {
ss >> buff;
vec.push_back(buff);
}
}
} while (std::getline(is, line));
Eigen::Array<T, Dynamic, Dynamic> res(vec.size() / ncols, ncols);
for (int i = 0; i != res.rows(); ++i) {
for (int j = 0; j != res.cols(); ++j) {
res(i, j) = vec[ncols * i + j];
}
}
return res;
}
Eigen::Array<T, Dynamic, Dynamic> data(nrows, ncols);
int i = 0;
do {
if (!inner::is_comment(line, comments)) {
ss.clear();
ss.str(line);
for (int j = 0; j != ncols; ++j)
ss >> data(i, j);
++i;
}
} while (i != nrows && std::getline(is, line));
return data;
}
/**
* @brief 读取文本数据文件
* @tparam T 数据标量类型
* @param fileName 文件名称
* @param nrows 行数,默认自动确定
* @param ncols 列数,默认自动确定
* @param comments 注释字符
* @param skiprows 跳过开头行数
* @return 数据矩阵
*/
template <typename T = double>
Eigen::Array<T, Dynamic, Dynamic> loadtxt(std::string fileName,
int nrows = Dynamic, int ncols = Dynamic, std::string comments = "#@", int skiprows = 0)
{
std::ifstream is(fileName);
ITP_ASSERT(is.is_open(), "Can not open this file: " + fileName);
return loadtxt<T>(is, nrows, ncols, comments, skiprows);
}
/**
* @brief 读取文本数据文件并写入到data中,写入量由data的大小决定
* @tparam T 数据标量类型
* @param is 文件流
* @param data 需要写入的容器
* @param comments 注释字符
* @param skiprows 跳过开头行数
*/
template <typename T>
bool loadtxt(std::istream& is, Eigen::Array<T, Dynamic, Dynamic>& data, std::string comments = "#@", int skiprows = 0)
{
std::string line;
std::stringstream ss;
for (int i = 0; i != skiprows; ++i)
if (!std::getline(is, line)) {
return false;
}
for (int i = 0; i != data.rows(); ) {
if (!std::getline(is, line)) {
return false;
}
if (!inner::is_comment(line, comments)) {
ss.clear();
ss.str(line);
for (int j = 0; j != data.cols(); ++j)
ss >> data(i, j);
++i;
}
}
return true;
}
} // !namespace itp;
#endif // !__CORE_FILEIO_HPP__
/* vim: set filetype=cpp et sw=2 ts=2 ai: */
| 28.469388
| 122
| 0.45687
|
TING2938
|
5dea70019f2b53cda332b8cad86fefc279ad2e3c
| 77,691
|
cc
|
C++
|
src/cxx/libsparse/libsparse2d/MR_NoiseModel.cc
|
jstarck/cosmostat
|
f686efe4c00073272487417da15e207a529f07e7
|
[
"MIT"
] | null | null | null |
src/cxx/libsparse/libsparse2d/MR_NoiseModel.cc
|
jstarck/cosmostat
|
f686efe4c00073272487417da15e207a529f07e7
|
[
"MIT"
] | null | null | null |
src/cxx/libsparse/libsparse2d/MR_NoiseModel.cc
|
jstarck/cosmostat
|
f686efe4c00073272487417da15e207a529f07e7
|
[
"MIT"
] | null | null | null |
/******************************************************************************
** Copyright (C) 1996 by CEA
*******************************************************************************
**
** UNIT
**
** Version: 18:28:57
**
** Author: Jean-Luc Starck
**
** Date: 97/05/06
**
** File: MR_NoiseModel.cc
**
*******************************************************************************
**
** DESCRIPTION noise modelling
** -----------
**
*******************************************************************************
**
** MRNoiseModel::MRNoiseModel(type_noise TNoise, int Nl_Imag,
** int Nc_Imag, int ScaleNumber, type_transform Trans)
**
** Class builder
** type_noise TNoise is the type of noise in the data
** Nl_Imag,Nc_Imag size of the image
** ScaleNumber: number of scales of the transform
** type_transform Trans: type of multiresoltuion transform
**
******************************************************************************/
#include "MR_Obj.h"
#include "IM_Noise.h"
#include "MR_Noise.h"
#include "MR_NoiseModel.h"
#include "MR_Sigma.h"
#include "MR_Abaque.h"
#include "MR_Psupport.h"
#include "NR.h"
#include "MR1D_Obj.h"
#include "FFTN_2D.h"
#include "Mr_FewEvent2d.h"
#define WRITE_DATA 0
/************************************************************************/
Bool one_level_per_pos_2d(type_noise TNoise)
// return True if we need only one level per position
// in the multiresolution space
{
Bool ValRet= False;
if ((TNoise == NOISE_EVENT_POISSON) || (TNoise == NOISE_NON_UNI_ADD)
|| (TNoise == NOISE_NON_UNI_MULT) || (TNoise == NOISE_UNDEFINED)) ValRet = True;
return ValRet;
}
/************************************************************************/
void MRNoiseModel::init_param()
{
TabLevel = NULL;
TabSupport = NULL;
NbrScale = 0;
NbrBand = 0;
Nl = 0;
Nc = 0;
Size = 0;
//CEventPois = NULL;
CFewEventPoisson2d = NULL;
CFewEvent2d = NULL;
CSpeckle = NULL;
CorrelNoiseMap = NULL;
Transform=T_UNDEFINED;
Set_Transform=S_UNDEFINED;
SigmaApprox = False;
FilterBank = NULL;
TypeNorm = DEF_SB_NORM;
NbrUndecimatedScale = -1;
GradientAnalysis = False;
NoCompDistrib = False;
PoissonFisz = False;
MadEstimFromCenter = False;
TypeThreshold = DEF_THRESHOLD;
U_Filter = DEF_UNDER_FILTER;
mOldPoisson = False;
mWriteThreshold = False;
}
/************************************************************************/
void MRNoiseModel::alloc(type_noise TNoise, int Nl_Imag,
int Nc_Imag, int ScaleNumber, type_transform Trans,
FilterAnaSynt *FAS, sb_type_norm Norm, int NbrUndec, int FCT_NDir)
{
int s, Nl_s=Nl_Imag, Nc_s=Nc_Imag;
Nl = Nl_Imag;
Nc = Nc_Imag;
NbrScale = ScaleNumber;
TypeNoise = TNoise;
Transform = Trans;
Set_Transform = SetTransform(Trans);
NbrBand = NbrScale;
FilterBank = FAS;
TypeNorm = Norm;
NbrUndecimatedScale = (NbrUndec >= 0) ? NbrUndec: NbrScale;
if (Set_Transform == TRANSF_DIADIC_MALLAT) NbrBand = NbrScale*2-1;
else if ((Set_Transform == TRANSF_UNDECIMATED_MALLAT)|| (Set_Transform == TRANSF_MALLAT))
NbrBand = (NbrScale-1)*3+1;
if (Set_Transform != TRANSF_UNDECIMATED_MALLAT)
{
TabNl.alloc(NbrBand);
TabNc.alloc(NbrBand);
TabPos.alloc(NbrBand);
TabBandScale.alloc(NbrBand);
}
switch (Set_Transform)
{
case TRANSF_UNDECIMATED_MALLAT:
{
if (Trans == TC_FCT)
{
NbrBand = fct_real_get_band_size(NbrScale, Nl, Nc, FCT_NDir, TabNl, TabNc);
// cout << NbrScale << " " << NbrScale << " " << NbrBand << " " << FCT_NDir << endl;
TabPos.alloc(NbrBand);
TabBandScale.alloc(NbrBand);
Size=0;
for (s = 0; s < NbrBand-1; s++)
{
TabPos(s) = Size;
Size += TabNl(s)*TabNc(s);
}
}
else if (Trans == TO_LC)
{
NbrScale = get_nbr_scale(Nc_Imag);
int NbrBandPerResol = get_nbr_scale(Nl_Imag);
NbrBand = NbrScale * NbrBandPerResol;
cout << NbrScale << " " << NbrBandPerResol << " " << NbrBand << endl;
TabNl.alloc(NbrBand);
TabNc.alloc(NbrBand);
TabPos.alloc(NbrBand);
TabBandScale.alloc(NbrBand);
Size=0;
for (int i=0; i < NbrBand; i++)
{
TabNl(i) =Nl_s;
TabNc(i) = Nc_s;
TabPos(i) = Size;
Size += (Nl_s*Nc_s);
}
}
else
{
Size=0;
int NbrBandPerResol = 3;
TabNl.alloc(NbrBand);
TabNc.alloc(NbrBand);
TabPos.alloc(NbrBand);
TabBandScale.alloc(NbrBand);
for (s = 0; s < NbrBand-1; s+=NbrBandPerResol)
{
if (s/NbrBandPerResol >= NbrUndecimatedScale)
{
TabNl(s) = (Nl_s+1)/2;
TabNc(s) = Nc_s/2;
TabPos(s) = Size;
Size += TabNl(s)*TabNc(s);
TabNl(s+1) = Nl_s/2;
TabNc(s+1) = (Nc_s+1)/2;
TabPos(s+1) = Size;
Size += TabNl(s+1)*TabNc(s+1);
TabNl(s+2) = Nl_s/2;
TabNc(s+2) = Nc_s/2;
TabPos(s+2) = Size;
Size += TabNl(s+2)*TabNc(s+2);
Nl_s = (Nl_s+1)/2;
Nc_s = (Nc_s+1)/2;
}
else
{
TabNl(s) = TabNl(s+1) = TabNl(s+2) = Nl_s;
TabNc(s) = TabNc(s+1) = TabNc(s+2) = Nc_s;
TabPos(s) = Size;
TabPos(s+1) = Size+Nl_s*Nc_s;
TabPos(s+2) = Size+2*(Nl_s*Nc_s);
Size += 3*(Nl_s*Nc_s);
}
}
}
}
//for (s = 0; s < NbrBand-1; s++)
// cout << "Band " << s+1 << " " << TabNl(s) << " " << TabNc(s) << endl;
break;
case TRANSF_DIADIC_MALLAT:
case TRANSF_PAVE:
Size = Nl*Nc*(NbrBand-1);
for (s = 0; s < NbrBand-1; s++)
{
TabNl(s) = Nl;
TabNc(s) = Nc;
TabPos(s) = s*Nl*Nc;
}
break;
case TRANSF_PYR:
case TRANSF_SEMIPYR:
Size=0;
TabNl(0) = Nl_s;
TabNc(0) = Nc_s;
TabPos(0) = 0;
for (s = 0; s < NbrScale-1; s++)
{
Size += Nl_s*Nc_s;
TabPos(s+1) = TabPos(s)+Nl_s*Nc_s;
if ((s != 0) || (Set_Transform != TRANSF_SEMIPYR))
{
Nl_s = (Nl_s+1)/2;
Nc_s = (Nc_s+1)/2;
}
TabNl(s+1) = Nl_s;
TabNc(s+1) = Nc_s;
}
break;
case TRANSF_MALLAT:
NbrBand = 3*(NbrScale -1)+1;
TabPos(0) = 0;
// cout << Nl_s << " " << Nc_s << endl;
Size = 0;
for (s = 0; s < NbrBand-1; s+=3)
{
TabNl(s) = (Nl_s+1)/2;
TabNc(s) = Nc_s/2;
TabPos(s) = Size;
Size += TabNl(s)*TabNc(s);
TabNl(s+1) = Nl_s/2;
TabNc(s+1) = (Nc_s+1)/2;
TabPos(s+1) = Size;
Size += TabNl(s+1)*TabNc(s+1);
TabNl(s+2) = Nl_s/2;
TabNc(s+2) = Nc_s/2;
TabPos(s+2) = Size;
Size += TabNl(s+2)*TabNc(s+2);
Nl_s = (Nl_s+1)/2;
Nc_s = (Nc_s+1)/2;
// cout << "Band " << s << ": " << TabNl(s) << " " << TabNc(s) << " " << TabPos(s) << endl;
// cout << "Band " << s+1 << ": " << TabNl(s+1) << " " << TabNc(s+1) << " " << TabPos(s+1) << endl;
// cout << "Band " << s+2 << ": " << TabNl(s+2) << " " << TabNc(s+2) << " " << TabPos(s+2) << endl;
}
s= NbrBand-1;
TabNl(s) = Nl_s;
TabNc(s) = Nc_s;
TabPos(s) = Size;
Size = Nl*Nc;
// for (s = 0; s < NbrBand-1; s++) cout << "bb " << s << ": " << TabNl(s) << " " << TabNc(s) << " " << TabPos(s) << endl;
break;
case TRANSF_FEAUVEAU:
NbrBand = 2*( NbrScale-1)+1;
TabPos(0) = 0;
for (s = 0; s < NbrBand-1; s+=2)
{
int Nlw = Nl_s;
int Ncw = Nc_s/2;
TabNl(s) = Nlw;
TabNc(s) = Ncw;
TabPos(s+1) = TabPos(s) + Nlw*Ncw;
Nlw /= 2;
Ncw = (Nc_s+1)/2;
TabNl(s+1) = Nlw;
TabNc(s+1) = Ncw;
TabPos(s+2) = TabPos(s+1) + Nlw*Ncw;
Nl_s = (Nl_s+1)/2;
Nc_s = (Nc_s+1)/2;
}
s= NbrBand-1;
TabNl(s) = Nl_s;
TabNc(s) = Nc_s;
// Size = TabPos(s);
Size=Nl*Nc;
break;
default: cerr << "Not implemented" << endl;
exit (0);
break;
}
// if (one_level_per_pos_2d(TNoise) == True) TabLevel = new float[Size];
if (one_level_per_pos_2d(TNoise) == True)
{
TabLevel = (float *) alloc_buffer((size_t) (Size*sizeof(float)));
}
else TabLevel = new float[NbrBand];
// TabSupport = new unsigned char [Size];
TabSupport = (unsigned char *) alloc_buffer((size_t) (Size*sizeof(char)));
for (s = 0; s < Size; s++) TabSupport[s] = VAL_SupNull;
// cout << "Size = " << Size << endl;
CCD_Gain = 1.;
CCD_ReadOutSigma=0.;
CCD_ReadOutMean=0.;
SigmaNoise=0.;
for (s = 0; s < NbrBand-1; s++)
{
details which_detail;
band2scale(s, Transform, NbrBand, TabBandScale(s), which_detail);
NSigma[s] = DEF_NSIGMA_DETECT;
TabEps[s] = DEFAULT_EPSILON;
if (TabBandScale(s) == 0) NSigma[s] += 1;
// cout << " band " << s+1 << " scale = " << TabBandScale(s) << " NSigma " << NSigma[s] << endl;
}
BadPixelVal=0.;
BadPixel=False;
MinEvent=False;
SupIsol=False;
FirstDectectScale = DEF_FIRST_DETECT_SCALE;
OnlyPositivDetect=False;
DilateSupport=False;
GetEgde=False;
MinEventNumber=DEF_MINEVENT_NUMBER;
SigmaDetectionMethod = DEF_SIGMA_METHOD;
NiterSigmaClip = 1;
SizeBlockSigmaNoise = DEFAULT_SIZE_BLOCK_SIG;
TransImag=False;
NewStatNoise = TNoise;
UseRmsMap = False;
GetRmsCoeffGauss = True;
//CEventPois = NULL;
CFewEventPoisson2d = NULL;
CFewEvent2d = NULL;
CSpeckle = NULL;
CorrelNoiseMap = NULL;
Border = DEFAULT_BORDER;
SigmaApprox = False;
switch (TypeNoise)
{
case NOISE_GAUSSIAN:
case NOISE_NON_UNI_ADD:
case NOISE_UNDEFINED:
TransImag=False;
break;
case NOISE_POISSON:
case NOISE_GAUSS_POISSON:
case NOISE_MULTI:
case NOISE_NON_UNI_MULT:
TransImag=True;
SigmaNoise=1.;
break;
case NOISE_EVENT_POISSON:
TransImag=True;
MinEvent=True;
// CEventPois = new StatEventPoisson;
if( mOldPoisson ) {
CFewEventPoisson2d = new FewEventPoisson;
if (!NoCompDistrib) { // call from mr_pfilter (Abaque exist)
// CEventPois->compute_distrib();
CFewEventPoisson2d->compute_distribution();
}
} else{
CFewEvent2d = new FewEvent;
CFewEvent2d->write_threshold( mWriteThreshold );
if (!NoCompDistrib)
CFewEvent2d->compute_distribution();
}
break;
case NOISE_UNI_UNDEFINED:
NiterSigmaClip = 3;
break;
case NOISE_CORREL:
break;
case NOISE_SPECKLE:
TransImag=True;
CSpeckle = new StatRayleigh(TSPECKLE, NbrScale, 1, Transform);
break;
}
}
/************************************************************************/
MRNoiseModel::MRNoiseModel()
{
(*this).init_param();
}
/************************************************************************/
MRNoiseModel::MRNoiseModel(type_noise TNoise, int Nl_Imag,
int Nc_Imag, int ScaleNumber, type_transform Trans)
{
(*this).init_param();
(*this).alloc(TNoise, Nl_Imag, Nc_Imag, ScaleNumber, Trans);
}
/****************************************************************************/
MRNoiseModel::MRNoiseModel (type_noise TNoise, MultiResol &MR_Data)
{
int Nl_s = MR_Data.size_ima_nl();
int Nc_s = MR_Data.size_ima_nc();
(*this).init_param();
(*this).alloc(TNoise, Nl_s, Nc_s, MR_Data.nbr_scale(),
MR_Data.Type_Transform, MR_Data.filter_bank(),
MR_Data.TypeNorm, MR_Data.nbr_undec_scale());
//MRNoiseModel(TNoise, Nl_s, Nc_s,
// MR_Data.nbr_scale(), MR_Data.Type_Transform);
}
/****************************************************************************/
void MRNoiseModel::pos_mrcoeff(int NumCoef, int &b, int &i, int &j)
{
int PosCoef = NumCoef;
b=0;
while (PosCoef > TabNc(b)*TabNl(b))
{
PosCoef -= TabNc(b)*TabNl(b);
b++;
}
i = PosCoef / TabNc(b);
j = PosCoef - i * TabNc(b);
}
/****************************************************************************/
Bool MRNoiseModel::operator() (int b,int i,int j)
{
Bool ValRet=False;
int Ind = index(b,i,j);
// cout << b << " " << i << " " << j << " ==> " << Ind << endl;
if ((TabSupport[Ind] > 0) && (TabSupport[Ind] <= VAL_SupLastOK)) ValRet = True;
return ValRet;
}
// ***************
Bool MRNoiseModel::operator() (int s,int i,int j, details which_detail)
{
int b = scale2band(s,Transform, NbrBand,which_detail);
return (*this)(b,i,j);
}
// ***************
Bool MRNoiseModel::operator() (int NumCoef)
{
int b,i,j;
pos_mrcoeff(NumCoef, b, i, j);
return (*this)(b,i,j);
}
/****************************************************************************/
float & MRNoiseModel::sigma(int b, int i, int j)
{
int Ind;
if (one_level_per_pos_2d(TypeNoise) == True) Ind = index(b,i,j);
else Ind = b;
return TabLevel[Ind];
}
// ***************
float & MRNoiseModel::sigma(int s,int i,int j, details which_detail)
{
int b = scale2band(s,Transform, NbrBand,which_detail);
return sigma(b,i,j);
}
// ***************
float & MRNoiseModel::sigma(int NumCoef)
{
if (one_level_per_pos_2d(TypeNoise) == True) {
int i,j,b;
pos_mrcoeff(NumCoef, b, i, j);
return sigma(b,i,j);
} else {
return TabLevel[NumCoef];
}
}
/****************************************************************************/
float MRNoiseModel::nsigma(int b)
{
return NSigma[b];
}
/****************************************************************************/
unsigned char & MRNoiseModel::support(int b,int i,int j)
{
int Ind = index(b,i,j);
// cout << b << " " << i << " " << j << " ==> " << Ind << endl;
return TabSupport[Ind];
}
// ***************
unsigned char & MRNoiseModel::support(int s,int i,int j, details which_detail)
{
int b = scale2band(s,Transform, NbrBand,which_detail);
return support(b,i,j);
}
// ***************
unsigned char & MRNoiseModel::support(int NumCoef)
{
int i,j,b;
pos_mrcoeff(NumCoef, b, i, j);
return support(b,i,j);
}
/****************************************************************************/
Bool MRNoiseModel::signif (float Val, int b, int i, int j, float LevelMin, float LevelMax)
{
Bool ValRet = False;
float Level;
Level = sigma(b,i,j)*NSigma[b];
if (OnlyPositivDetect == True)
{
if (Val > LevelMax) ValRet = True;
}
else if ((Val > LevelMax) || (Val < LevelMin)) ValRet = True;
if ((TabBandScale(b) < FirstDectectScale) && (ValRet == True)) ValRet = False;
return ValRet;
}
/****************************************************************************/
Bool MRNoiseModel::signif (float Val, int b, int i, int j)
{
Bool ValRet = False;
float Level;
Level = sigma(b,i,j)*NSigma[b];
if (OnlyPositivDetect == True)
{
if (Val > Level) ValRet = True;
}
else if (ABS(Val) > Level) ValRet = True;
if ((TabBandScale(b) < FirstDectectScale) && (ValRet == True)) ValRet = False;
return ValRet;
}
Bool MRNoiseModel::signif (float Val, int b, int i, int j, fltarray & TNsigma)
{
Bool ValRet = False;
float Level;
Level = sigma(b,i,j) * TNsigma(b);
if (OnlyPositivDetect == True)
{
if (Val > Level) ValRet = True;
}
else if (ABS(Val) > Level) ValRet = True;
if ((TabBandScale(b) < FirstDectectScale) && (ValRet == True)) ValRet = False;
return ValRet;
}
// ***************
Bool MRNoiseModel::signif (float Val, int s, int i, int j, details which_detail)
{
int b = scale2band(s,Transform, NbrBand,which_detail);
return signif(Val, b,i,j);
}
/****************************************************************************/
float MRNoiseModel::prob(float Val, int b, int i, int j)
{
float Sig,P=0.;
switch (TypeNoise)
{
case NOISE_EVENT_POISSON:
{
int k,l,Win = (int) (pow((double)2., (double)(b+2)) + 0.5);
double Nevent = 0;
for (k =i-Win; k <= i+Win; k++)
for (l =j-Win; l <= j+Win; l++)
Nevent += Event_Image(k, l, Border);
if (NoCompDistrib) {
cout << "Error: histogram have to be computed first ..." << endl;
exit(-1);
}
//P = CEventPois->a_trou_prob(Val, Nevent, b);
if( mOldPoisson )
P = CFewEventPoisson2d->a_trou_prob( Val, (int ) (Nevent+0.5), b );
else
P = CFewEvent2d->a_trou_prob( Val, (int ) (Nevent+0.5), b );
}
break;
case NOISE_CORREL:
P = CorrelNoiseMap->prob(b, Val);
break;
case NOISE_SPECKLE:
P = CSpeckle->prob(b, Val);
break;
default:
Sig = sigma(b,i,j);
P = exp(-Val*Val / (2*Sig*Sig) ) / sqrt(2.*PI);
break;
}
return P;
}
// ***************
float MRNoiseModel::prob (float Val, int s, int i, int j, details which_detail)
{
int b = scale2band(s,Transform, NbrBand,which_detail);
return prob(Val,b,i,j);
}
/****************************************************************************/
void MRNoiseModel::prob (MultiResol &MR_Data, Bool Complement)
{
float Sig,Val;
int s,i,j;
switch (TypeNoise)
{
case NOISE_EVENT_POISSON:
{
Ifloat EventCount(Nl,Nc,"ImagCount");
for (s = 0; s < MR_Data.nbr_band()-1; s++)
{
event_one_scale(Event_Image, s, EventCount, MR_Data.Border);
for (i=0; i< MR_Data.size_band_nl(s); i++)
for (j=0; j< MR_Data.size_band_nc(s); j++)
{
if (NoCompDistrib) {
cout << "Error: histogram have to be computed first ... " << endl;
exit(-1);
}
//MR_Data(s,i,j) = CEventPois->a_trou_prob(MR_Data(s,i,j), EventCount(i,j), s);
if( mOldPoisson )
MR_Data(s,i,j) = CFewEventPoisson2d->a_trou_prob( MR_Data(s,i,j), (int) ( EventCount(i,j)+0.5), s );
else
MR_Data(s,i,j) = CFewEvent2d->a_trou_prob( MR_Data(s,i,j), (int) ( EventCount(i,j)+0.5), s );
if (Complement == True) MR_Data(s,i,j) = 1. - MR_Data(s,i,j) ;
}
}
}
break;
case NOISE_CORREL:
for (s = 0; s < MR_Data.nbr_band()-1; s++)
for (i=0; i< MR_Data.size_band_nl(s); i++)
for (j=0; j< MR_Data.size_band_nc(s); j++)
{
Val = MR_Data(s,i,j);
MR_Data(s,i,j) = CorrelNoiseMap->prob(s, Val);
}
break;
case NOISE_SPECKLE:
for (s = 0; s < MR_Data.nbr_band()-1; s++)
for (i=0; i< MR_Data.size_band_nl(s); i++)
for (j=0; j< MR_Data.size_band_nc(s); j++)
{
Val = MR_Data(s,i,j);
MR_Data(s,i,j) = CSpeckle->prob(s, Val);
}
break;
default:
for (s = 0; s < MR_Data.nbr_band()-1; s++)
for (i=0; i< MR_Data.size_band_nl(s); i++)
for (j=0; j< MR_Data.size_band_nc(s); j++)
{
Val = MR_Data(s,i,j);
Sig = sigma(s,i,j);
if (Sig > FLOAT_EPSILON)
Val = 1. / sqrt(2.*PI)*exp(-Val*Val / (2*Sig*Sig));
else Val = 0.;
if (Complement == True) Val = 1. - Val;
MR_Data(s,i,j) = Val;
}
break;
}
}
/****************************************************************************/
void MRNoiseModel::prob_noise (MultiResol &MR_Data, Bool Complement)
{
int s,i,j;
switch (TypeNoise)
{
case NOISE_EVENT_POISSON:
{
Ifloat EventCount(Nl,Nc,"ImagCount");
for (s = 0; s < MR_Data.nbr_band()-1; s++)
{
event_one_scale(Event_Image, s, EventCount, MR_Data.Border);
for (i=0; i< MR_Data.size_band_nl(s); i++)
for (j=0; j< MR_Data.size_band_nc(s); j++)
{
if (NoCompDistrib) {
cout << "Error: histogram have to be computed first ..." << endl;
exit(-1);
}
//float P = CEventPois->a_trou_repartition(MR_Data(s,i,j),
// EventCount(i,j) , s);
double P1, P2;
//std::cout << "s:" << s << ", [x:" << i << ",y:" << j << "]" << std::endl;
if( mOldPoisson ) {
P1 = CFewEventPoisson2d->a_trou_repartition( MR_Data(s,i,j), (int) (EventCount(i,j)+0.5), s);
if (MR_Data(s,i,j) > 0) P1 = 1. - P1;
if (Complement == True) MR_Data(s,i,j) = 1. - P1;
else MR_Data(s,i,j) = P1;
} else {
P1 = CFewEvent2d->a_trou_repartition( MR_Data(s,i,j), (int) (EventCount(i,j)+0.5), s);
P2 = CFewEvent2d->a_trou_repartition( MR_Data(s,i,j), (int) (EventCount(i,j)+0.5), s, True);
//std::cout << "MRNoiseModel::prob_noise : P1 = " << P1 << ", 1-P1 = " << 1. - P1
// << ", P2 = " << P2 << std::endl;
if (Complement == True) MR_Data(s,i,j) = 1. - P2;
else MR_Data(s,i,j) = P2;
}
}
}
}
break;
default:
for (s = 0; s < MR_Data.nbr_band()-1; s++)
for (i=0; i< MR_Data.size_band_nl(s); i++)
for (j=0; j< MR_Data.size_band_nc(s); j++)
{
MR_Data(s,i,j) = prob_noise(MR_Data(s,i,j), s, i, j);
if (Complement == True) MR_Data(s,i,j) = 1. - MR_Data(s,i,j);
}
break;
}
}
/****************************************************************************/
float MRNoiseModel::prob_noise(float Val, int b, int i, int j)
{
float Sig,P=0.;
double Vn=0.;
switch (TypeNoise)
{
case NOISE_EVENT_POISSON:
{
if (NoCompDistrib) {
cout << "Error: histogram have to be computed first ..." << endl;
exit(-1);
}
int k,l,Win = (int) (pow((double)2., (double)(b+2)) + 0.5);
float Nevent = 0;
for (k =i-Win; k <= i+Win; k++)
for (l =j-Win; l <= j+Win; l++)
Nevent += Event_Image(k, l, Border);
//P = CEventPois->a_trou_repartition(Val, Nevent, b);
if( mOldPoisson ) {
P = CFewEventPoisson2d->a_trou_repartition(Val, (int) (Nevent+0.5), b);
if (Val > 0) P = 1. - P;
} else {
//double P1 = CFewEvent2d->a_trou_repartition(Val, Nevent, b);
double P2 = CFewEvent2d->a_trou_repartition( Val, (int) (Nevent+0.5), b, True );
// std::cout << "MRNoiseModel::prob_noise : P1 = " << P1 << ", 1-P1 = " << 1. - P1 << ", P2 = " << P2 << std::endl;
P = P2;
}
}
break;
case NOISE_CORREL:
P = CorrelNoiseMap->repartition(b, Val);
if (Val > 0) P = 1. - P;
break;
case NOISE_SPECKLE:
P = CSpeckle-> repartition(b, Val);
if (Val > 0) P = 1. - P;
break;
default:
Sig = sigma(b,i,j);
if (ABS(Val) < FLOAT_EPSILON) P = 1.;
else
{
if (Sig < FLOAT_EPSILON) P = 0;
else
{
Vn = ABS(Val) / (sqrt(2.)*Sig);
if (Vn > 3.5) P = 0;
else P = (float) erfc (Vn);
}
}
break;
}
return P;
}
/****************************************************************************/
double MRNoiseModel:: prob_signal_few_event( float Val, int b, int i, int j )
{
double P = 0 ;
if( NoCompDistrib ) {
std::cout << "Error: histogram have to be computed first ..." << std::endl ;
exit( -1 ) ;
}
int k,l,Win = (int) ( pow((double)2., (double)( b+2 )) + 0.5) ;
float Nevent = 0.;
for( k =i-Win; k <= i+Win; k++ )
for( l =j-Win; l <= j+Win; l++ )
Nevent += Event_Image(k, l, Border) ;
if( mOldPoisson ) {
P = CFewEventPoisson2d->a_trou_repartition( Val, (int) (Nevent+0.5), b ) ;
if( Val > 0 ) P = 1. - P ;
} else {
//double P1 = CFewEvent2d->a_trou_repartition(Val, Nevent, b);
P = CFewEvent2d->a_trou_repartition( Val, (int) (Nevent+0.5), b, True ) ;
//std::cout << "MRNoiseModel::prob_signal_few_event : P = " << std::endl ;
}
if (kill_coef( b, i, j, Val, False ) == True ) P = 1. ;
return P;
}
// ***************
float MRNoiseModel::prob_noise(float Val, int s, int i,
int j, details which_detail)
{
int b = scale2band(s,Transform, NbrBand,which_detail);
return prob_noise(Val,b,i,j);
}
/****************************************************************************/
float MRNoiseModel::prob_signal(float Val, int b, int i, int j)
{
return (1. - prob_noise(Val,b,i,j));
}
/****************************************************************************/
float MRNoiseModel::prob_signal(float Val, int s, int i,
int j, details which_detail)
{
int b = scale2band(s,Transform, NbrBand,which_detail);
return (1. - prob_noise(Val,b,i,j));
}
/****************************************************************************/
float MRNoiseModel::val_transform(float Val)
{
float ValRet = Val;
switch (TypeNoise)
{
case NOISE_POISSON:
case NOISE_GAUSS_POISSON:
ValRet = Val*CCD_Gain + 3. / 8. * CCD_Gain*CCD_Gain +
CCD_ReadOutSigma*CCD_ReadOutSigma - CCD_Gain*CCD_ReadOutMean;
if (ValRet < 0.) ValRet=0;
else ValRet = 2. / CCD_Gain *sqrt(ValRet);
break;
case NOISE_GAUSSIAN:
case NOISE_NON_UNI_ADD:
case NOISE_UNDEFINED:
case NOISE_UNI_UNDEFINED:
case NOISE_CORREL:
break;
case NOISE_MULTI:
case NOISE_NON_UNI_MULT:
case NOISE_SPECKLE:
if (Val > 0) ValRet = log(Val+1.);
else ValRet = 0.;
break;
case NOISE_EVENT_POISSON:
break;
}
return ValRet;
}
/****************************************************************************/
float MRNoiseModel::val_invtransform(float Val)
{
float ValRet = Val;
switch (TypeNoise)
{
case NOISE_POISSON:
case NOISE_GAUSS_POISSON:
ValRet = Val*Val/4.*CCD_Gain - ( 3./8.*CCD_Gain*CCD_Gain +
CCD_ReadOutSigma*CCD_ReadOutSigma -
CCD_Gain*CCD_ReadOutMean ) / CCD_Gain;
break;
case NOISE_GAUSSIAN:
case NOISE_NON_UNI_ADD:
case NOISE_UNDEFINED:
case NOISE_UNI_UNDEFINED:
case NOISE_CORREL:
break;
case NOISE_MULTI:
case NOISE_NON_UNI_MULT:
case NOISE_SPECKLE:
if (Val > 0) ValRet = exp(Val) - 1.;
else ValRet = 0.;
break;
case NOISE_EVENT_POISSON:
break;
}
return ValRet;
}
/****************************************************************************/
void MRNoiseModel::im_transform(Ifloat &Image)
{
switch (TypeNoise)
{
case NOISE_POISSON:
if (PoissonFisz == False) noise_poisson_transform (Image, Image);
else fisz2d_trans(Image);
SigmaNoise = 1.;
break;
case NOISE_GAUSS_POISSON:
noise_poisson_transform (Image, Image);
SigmaNoise = 1.;
break;
case NOISE_GAUSSIAN:
case NOISE_NON_UNI_ADD:
case NOISE_UNDEFINED:
case NOISE_UNI_UNDEFINED:
case NOISE_CORREL:
break;
case NOISE_MULTI:
case NOISE_NON_UNI_MULT:
case NOISE_SPECKLE:
noise_log_transform (Image, Image);
break;
case NOISE_EVENT_POISSON:
// event_poisson_transform (Image, Event_Image);
building_imag_imag(Image, Event_Image);
break;
}
}
/****************************************************************************/
void MRNoiseModel::im_invtransform(Ifloat &Image)
{
switch (TypeNoise)
{
case NOISE_POISSON:
if (PoissonFisz == False) noise_inverse_poisson_transform (Image, Image);
else fisz2d_inv(Image);
break;
case NOISE_GAUSS_POISSON:
noise_inverse_poisson_transform (Image, Image);
break;
case NOISE_GAUSSIAN:
case NOISE_NON_UNI_ADD:
case NOISE_UNDEFINED:
case NOISE_UNI_UNDEFINED:
case NOISE_CORREL:
break;
case NOISE_MULTI:
case NOISE_NON_UNI_MULT:
case NOISE_SPECKLE:
noise_inv_log_transform (Image, Image);
break;
case NOISE_EVENT_POISSON:
break;
}
}
/****************************************************************************/
void MRNoiseModel::get_sigma_from_rms_map(Ifloat &Ima_Sigma)
{
int RmsNl = Ima_Sigma.nl();
int RmsNc = Ima_Sigma.nc();
Ifloat Ptr_Rms;
Ifloat Dirac;
int i,j,s;
int Ind;
FFTN_2D FFT;
FFT.CenterZeroFreq = True;
Dirac.alloc(RmsNl,RmsNc,"Dirac");
Ptr_Rms.alloc(RmsNl,RmsNc,"Ptr_Rms");
Dirac(RmsNl/2-1,RmsNc/2-1)=1.;
// First we compute the square image of Rms
for(i=0; i < RmsNl; i++)
for(j=0; j < RmsNc; j++) Ptr_Rms(i,j) = Ima_Sigma(i,j)*Ima_Sigma(i,j);
// Then we transform the dirac image :
MultiResol MR_Dirac(RmsNl, RmsNc, NbrScale, Transform, "Dirac");
MR_Dirac.transform(Dirac);
// Then we compute the square of the Dirac transform ...
for (s=0 ; s < MR_Dirac.nbr_band()-1; s++)
for (i=0 ; i < RmsNl; i++)
for (j=0 ; j < RmsNc; j++) MR_Dirac(s,i,j) *= MR_Dirac(s,i,j);
// Then we convolve the RMS by the Dirac (at each scale)
// The problem is now to take the sqrt of the result image. The FFT may
// produce some negative values. Since the result is lower for high number
// of scales, we cannot use a test based on a comparision of FLOAT_EPSILON
// or some power of it. We look simply if there was something at the place
// on the original map ...
for (s=0 ; s < MR_Dirac.nbr_band()-1 ; s++)
{
FFT.convolve(MR_Dirac.band(s), Ptr_Rms);
for (i=0 ; i < RmsNl ; i++)
for (j=0 ; j < RmsNc ; j++)
{
Ind = index(s,i,j);
if (MR_Dirac(s,i,j) <= 0) TabLevel[Ind] = 0;
else TabLevel[Ind] = sqrt(MR_Dirac(s,i,j));
}
}
}
/****************************************************************/
void MRNoiseModel::max_sigma_in_scale(Ifloat &Ima_Sigma)
{
int s,i,j,Kb,Ke,Lb,Le,k,l;
int Nls=Nl,Ncs=Nc,Nlp=Nl,Ncp=Nc;
int Ind, Indp,Step,SizeWave=2;
float Max;
extern float mr_tab_noise(int s);
// FIRST SCALE:
// find the maximum noise standard deviation in a box
// put the result in TabLevel
for (i=0; i< Nl-1; i++)
for (j=0; j< Nc-1; j++)
{
Max = Ima_Sigma(i,j);
Kb = (i-SizeWave >= 0) ? i-SizeWave : 0;
Ke = (i+SizeWave <= Nl-1) ? i+SizeWave : Nl-1;
Lb = (j-SizeWave >= 0) ? j-SizeWave : 0;
Le = (j+SizeWave <= Nc-1) ? j+SizeWave : Nc-1;
for (k=Kb; k<= Ke; k++)
for (l=Lb; l<= Le; l++)
if (Max < Ima_Sigma(k,l)) Max =Ima_Sigma(k,l);
Ind = index(0,i,j);
TabLevel[Ind] = Max*mr_tab_noise(0) / 0.972463;
}
Step=1;
for (s=1; s < NbrBand-1; s++)
{
Nls = TabNl(s);
Ncs = TabNc(s);
Nlp = TabNl(s-1);
Ncp = TabNc(s-1);
if ((Set_Transform == TRANSF_PAVE) ||
((Set_Transform == TRANSF_SEMIPYR) && (s == 1)))
{
Step = 2*Step;
}
for (i=0; i< Nls-1; i++)
for (j=0; j< Ncs-1; j++)
{
Max = 0.;
if ((Set_Transform == TRANSF_PAVE) ||
((Set_Transform == TRANSF_SEMIPYR) && (s == 1)))
{
Kb = (i-Step >= 0) ? i-Step : i;
Ke = (i+Step <= Nl-1) ? i+Step : i;
Lb = (j-Step >= 0) ? j-Step : j;
Le = (j+Step <= Nc-1) ? j+Step : j;
}
else
{
Kb = (2*i-2 >= 0) ? 2*i-2 : 0;
Ke = (2*i+2 <= Nlp-1) ? 2*i+2 : Nlp-1;
Lb = (2*j-2 >= 0) ? 2*j-2 : 0;
Le = (2*j+2 <= Ncp-1) ? 2*j+2 : Ncp-1;
}
for (k=Kb; k<= Ke; k+=Step)
for (l=Lb; l<= Le; l+=Step)
{
Indp = index(s-1,k,l);
if (Max < TabLevel[Indp]) Max = TabLevel[Indp];
}
Ind = index(s,i,j);
TabLevel[Ind] = Max*mr_tab_noise(s)/mr_tab_noise(s-1);
}
}
}
/****************************************************************************/
void MRNoiseModel::kill_isol(int s)
{
int i,j;
Bool PutZero;
int Nls=Nl;
int Ncs=Nl;
// cout << "kill_isol" << endl;
if (Set_Transform == TRANSF_PYR)
{
Nls = TabNl(s);
Ncs = TabNc(s);
}
if (Set_Transform == TRANSF_PAVE)
{
for (i = 1; i < Nl-1; i++)
for (j = 1; j < Nc-1; j++)
{
PutZero = True;
if (support(s,i,j) == VAL_SupOK)
{
if (support(s,i-1,j) == VAL_SupOK) PutZero = False;
else if (support(s,i+1,j) == VAL_SupOK) PutZero = False;
else if (support(s,i,j+1) == VAL_SupOK) PutZero = False;
else if (support(s,i,j-1) == VAL_SupOK) PutZero = False;
else if (support(s+1,i,j) == VAL_SupOK) PutZero = False;
if (PutZero == True) support(s,i,j) = VAL_SupKill;
}
}
}
else if ((Set_Transform == TRANSF_PYR) || (Set_Transform == TRANSF_SEMIPYR)
|| (Set_Transform == TRANSF_DIADIC_MALLAT)
|| (Set_Transform == TRANSF_UNDECIMATED_MALLAT))
{
Nls = TabNl(s);
Ncs = TabNc(s);
for (i = 1; i < Nls-1; i++)
for (j = 1; j < Ncs-1; j++)
{
PutZero = True;
if (support(s,i,j) == VAL_SupOK)
{
if (support(s,i-1,j) == VAL_SupOK) PutZero = False;
else if (support(s,i+1,j) == VAL_SupOK) PutZero = False;
else if (support(s,i,j+1) == VAL_SupOK) PutZero = False;
else if (support(s,i,j-1) == VAL_SupOK) PutZero = False;
// else if (support(s+1,i/2,j/2) == VAL_SupOK) PutZero = False;
if (PutZero == True) support(s,i,j) = VAL_SupKill;
}
}
}
}
/****************************************************************************/
void MRNoiseModel::dilate_support(int s)
{
int dim=1;
int Ind;
unsigned char *Buff;
int i,j,k,l,Nls,Ncs;
int kb,ke,lb,le;
unsigned char Max;
if ((Set_Transform == TRANSF_PYR) || (Set_Transform == TRANSF_PAVE)
|| (Set_Transform == TRANSF_SEMIPYR)
|| (Set_Transform == TRANSF_DIADIC_MALLAT)
|| (Set_Transform == TRANSF_UNDECIMATED_MALLAT))
{
if (Set_Transform == TRANSF_PAVE)
dim = (int)(pow((double)2., (double) (s+1)) + 0.5);
Nls = TabNl(s);
Ncs = TabNc(s);
Buff = new unsigned char [Nls*Ncs];
for (i = 0; i < Nls*Ncs; i++) Buff[i] =0;
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
{
Max = ( (*this)(s,i,j) == True ) ? 1 : 0;
kb = (i-dim >= 0) ? i-dim: 0;
lb = (j-dim >= 0) ? j-dim: 0;
ke = (i+dim < Nls) ? i+dim: Nls-1;
le = (j+dim < Ncs) ? j+dim: Ncs-1;
k=kb;
while ( (Max == 0) && (k <= ke))
{
l = lb;
while ( (Max == 0) && (l <= le))
{
if ((*this)(s,k,l) == True) Max=1;
l++;
}
k++;
}
Ind = i*Ncs+j;
Buff[Ind] = Max;
}
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
{
Ind = i*Ncs+j;
if ((support(s,i,j) != VAL_SupOK) && (Buff[Ind] == 1))
{
support(s,i,j) = VAL_SupDill;
}
}
delete [] Buff;
}
}
/****************************************************************************/
void MRNoiseModel::hierarchical_dilate_support()
{
int dim=1;
int i,j,k,l,Nls,Ncs;
int kb,ke,lb,le;
unsigned char Max;
if (Set_Transform == TRANSF_PAVE)
for (int s = NbrBand-3; s >= 0; s--)
{
int NextScale = s+1;
dim = (int)(pow((double)2., (double) s) + 0.5);
Nls = TabNl(s);
Ncs = TabNc(s);
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
{
Max = ( (*this)(NextScale,i,j) == True ) ? 1 : 0;
kb = (i-dim >= 0) ? i-dim: 0;
lb = (j-dim >= 0) ? j-dim: 0;
ke = (i+dim < Nls) ? i+dim: Nls-1;
le = (j+dim < Ncs) ? j+dim: Ncs-1;
k=kb;
if ((*this)(s,i,j) == False)
{
while ( (Max == 1) && (k <= ke))
{
l = lb;
while ( (Max == 1) && (l <= le))
{
if ((*this)(NextScale,k,l) == False) Max=0;
l++;
}
k++;
}
if (Max == 1) support(s,i,j) = VAL_SupDill;
}
}
}
}
/****************************************************************************/
void MRNoiseModel::kill_event(int s, Ifloat &IEvent_Image, int FirstWin)
{
int i,j,k,l,kb,ke,Nls,Ncs,sc=0;
int Step=1;
int Win = FirstWin/2;
float Total;
if (Set_Transform == TRANSF_PAVE)
{
Nls = TabNl(s);
Ncs = TabNc(s);
while (sc++ < s) Win*=2;
for (i =0; i < Nl; i++)
{
Total = 0;
kb = (i-Win < 0) ? 0: i-Win;
ke = (i+Win >= Nls) ? Nls-1: i+Win;
for (k =kb; k <= ke; k++)
for (l =0; l <= Win; l++) Total += IEvent_Image(k, l);
if ((support(s,i,0) == VAL_SupOK) && (Total < MinEventNumber))
support(s,i,0) = VAL_SupMinEv;
for (j =1; j < Nc; j+=Step)
{
for (k = -Win; k <= Win; k++)
{
Total -= (int) IEvent_Image(kb,j-Win-1,I_ZERO);
Total += (int) IEvent_Image(kb,j+Win,I_ZERO);
}
if ((support(s,i,j) == VAL_SupOK) && (Total < MinEventNumber))
support(s,i,j) = VAL_SupMinEv;
}
}
}
}
/****************************************************************************/
float MRNoiseModel::sure_estimation(MultiResol &MR_Data)
{
int s,i,j;
int Ind = 1;
unsigned long N = 0;
for (s = 0; s < MR_Data.nbr_band()-1; s++)
N += MR_Data.size_band_nl(s) * MR_Data.size_band_nc(s);
float *Tab = new float [N+1];
for (s = 0; s < MR_Data.nbr_band()-1; s++)
for (i = 0; i < MR_Data.size_band_nl(s) ; i++)
for (j = 0; j < MR_Data.size_band_nc(s) ; j++)
{
float Coef = MR_Data(s,i,j) / sigma(s,i,j);
Tab[Ind++] = Coef*Coef;
}
sort(N, Tab);
double MinRisk=0.;
double CumVal = 0;
int IndRisk=0;
for (i = 1; i <= (int) N; i++)
{
CumVal += Tab[i];
int c = N-i;
double s = CumVal + c * Tab[i];
double r = ((double) N - (2.*i) + s) / (double) N;
if ((i == 1) || (r < MinRisk))
{
MinRisk = r;
IndRisk = i;
}
}
double T = sqrt(Tab[IndRisk]);
delete [] Tab;
return (float) T;
}
/********************************************************************/
float MRNoiseModel::multi_sure_estimation(MultiResol & MR_Data, int b)
{
int i,j;
int Ind = 1;
int Nl = MR_Data.size_band_nl(b);
int Nc = MR_Data.size_band_nc(b);
unsigned long N = Nl*Nc;
float *Tab = new float [N+1];
for (i = 0; i < MR_Data.size_band_nl(b) ; i++)
for (j = 0; j < MR_Data.size_band_nc(b) ; j++)
{
float Coef = MR_Data(b,i,j) / sigma(b,i,j);
Tab[Ind++] = Coef*Coef;
}
sort(N, Tab);
double MinRisk=0.;
double CumVal = 0;
int IndRisk=0;
for (i = 1; i <= (int) N; i++)
{
CumVal += Tab[i];
int c = N-i;
double s = CumVal + c * Tab[i];
double r = ((double) N - (2.*i) + s) / (double) N;
if ((i == 1) || (r < MinRisk))
{
MinRisk = r;
IndRisk = i;
}
}
double T = sqrt(Tab[IndRisk]);
delete [] Tab;
return (float) T;
}
/********************************************************************/
void MRNoiseModel::set_support(MultiResol &MR_Data)
{
int b,i,j;
int Nls, Ncs;
float SureLevel;
if ((Transform == TO_DIADIC_MALLAT) && (GradientAnalysis == True))
{
for (b = 0; b < NbrBand-1; b+=2)
{
Nls = MR_Data.size_band_nl(b);
Ncs = MR_Data.size_band_nc(b);
for (i = 0; i < Nls;i++)
for (j = 0; j < Ncs; j++)
{
float Coef = sqrt(POW(MR_Data(b,i,j),2.)+POW(MR_Data(b+1,i,j), 2.));
if (signif(Coef, b,i,j) == True)
{
support(b,i,j)=VAL_SupOK;
support(b+1,i,j)=VAL_SupOK;
}
else
{
support(b,i,j)=VAL_SupNull;
support(b+1,i,j)=VAL_SupNull;
}
}
}
}
else
{
switch (TypeThreshold)
{
case T_FDR:
for (b = 0; b < NbrBand-1; b++)
{
Nls = MR_Data.size_band_nl(b);
Ncs = MR_Data.size_band_nc(b);
dblarray TabPValue(Ncs,Nls);
for (i = 0; i < Nls;i++)
for (j = 0; j < Ncs; j++) TabPValue(j,i) = prob_noise(MR_Data(b,i,j), b, i, j);
float Alpha = (b==0) ? 1. - erf(NSigma[b] / sqrt(2.)): Alpha*2;
if (Alpha > 0.5) Alpha = 0.5;
double PDet = fdr_pvalue(TabPValue.buffer(), Nls*Ncs, Alpha);
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
{
if (TabPValue(j,i) < PDet)
{
support(b,i,j) = VAL_SupOK;
if ((OnlyPositivDetect == True) && (MR_Data(b,i,j) < 0))
support(b,i,j) = VAL_SupNull;
if (TabBandScale(b) < FirstDectectScale) support(b,i,j) = VAL_SupFirstScale;
}
else support(b,i,j) = VAL_SupNull;
}
TabEps[b] = PDet;
//if (PDet < DOUBLE_EPSILON) NSigma[b] = 5.;
//else
// NSigma[b] = ABS(xerf(PDet/2.));
NSigma[b] = ABS(xerfc(0.5+(1-PDet)/2.));
if((NSigma[b] < 5) && (NSigma[b] > 0))
NSigma[b] = ABS(xerfc(0.5+(1-PDet)/2.));
else
NSigma[b] = 5;
// if (Verbose == True)
printf("FDR: band %d ==> Alpha = %f, NSigma = %f\n", b+1, Alpha, NSigma[b]);
}
break;
case T_SURE:
SureLevel = sure_estimation(MR_Data);
break;
case T_KSIGMA:
break;
case T_UNIVERSAL:
for (b = 0; b < NbrBand-1; b++)
NSigma[b] = sqrt(2.*log((float)(MR_Data.size_band_nl(b)*MR_Data.size_band_nc(b))));
break;
case T_MRSURE:
for (b = 0; b < NbrBand-1; b++)
NSigma[b] = multi_sure_estimation(MR_Data,b);
break;
}
if (TypeThreshold != T_FDR)
{
for (b = 0; b < NbrBand-1; b++)
for (i = 0; i < MR_Data.size_band_nl(b); i++)
for (j = 0; j < MR_Data.size_band_nc(b); j++)
support(b,i,j) = (signif(MR_Data(b,i,j), b,i,j) == True) ?
VAL_SupOK: VAL_SupNull;
}
}
Bool SpatialAdaptiv = False;
if ((Transform == TO_UNDECIMATED_NON_ORTHO) && (SpatialAdaptiv == True))
{
// Here we compare the SNR for each coeff in the three bands to the
// SNR of the sum of the coeff. If the SNR(SUM) > MAX(SNR_i) i=1,2,3 then we habe an isotropic feature
// and we set the support to 1 in the three bands.
for (b = 0; b < NbrBand-1; b+=3)
{
extern double TabNormPaveB3Spline[MAX_SCALE];
extern double TabNormUndecNonOrth_B3SPLINE_ISOTROP_2[MAX_SCALE];
float SumBand;
Nls = MR_Data.size_band_nl(b);
Ncs = MR_Data.size_band_nc(b);
for (i = 0; i < Nls;i++)
for (j = 0; j < Ncs;j++)
{
float Sig1 = sigma(b,i,j); // std of the noise in horiz band
float Sig2 = sigma(b+1,i,j);// std of the noise in vertical band
float Sig3 = sigma(b+2,i,j); //std of the noise in diag band
float MaxSig = MAX(MR_Data(b,i,j)/Sig1, MR_Data(b+1,i,j)/Sig2);
MaxSig = MAX(MaxSig, MR_Data(b+3,i,j)/Sig3); // get the MAX SNR of the three bands
float NSigMIN = MIN(NSigma[b], NSigma[b+1]); //
NSigMIN = MIN(NSigMIN,NSigma[b+2]); // get the detection level parameter
float SigSum=0;
SumBand = (MR_Data(b,i,j) + MR_Data(b+1,i,j) + MR_Data(b+2,i,j)); // Sum of the three bands
if (NewStatNoise == NOISE_GAUSSIAN)
{
switch(U_Filter)
{
case U_B3SPLINE:SigSum = TabNormPaveB3Spline[b/3]*SigmaNoise; break;
case U_B3SPLINE_2:SigSum = TabNormUndecNonOrth_B3SPLINE_ISOTROP_2[b/3]*SigmaNoise; break;
default: SumBand = 0; SigSum = 1; break;
}
}
else SigSum = sqrt(Sig1*Sig1+Sig2*Sig2+Sig3*Sig3)*1.23; // Correction because of the correlation of the coef.
SumBand /= SigSum;
if ((SumBand > MaxSig) && (SumBand > NSigMIN))
{
support(b,i,j) = support(b+1,i,j) = support(b+2,i,j) = VAL_SupOK;
}
}
}
}
/*
if ((GetEgde == True) && (Transform == TO_PAVE_BSPLINE))
{
for (b = 0; b < NbrBand-1; b++)
{
int b1,E_Nscale;
Nls = MR_Data.size_band_nl(b);
Ncs = MR_Data.size_band_nc(b);
Ifloat Buff(Nls,Ncs,"Buff");
E_Nscale = iround((float)log((float) (MIN(Nls,Ncs) / 4. * 3.) / log(2.)));
if (one_level_per_pos_2d(TypeNoise) == True)
{
cout << "Error: this noise model cannot be used with this option ... " << endl;
exit(-1);
}
float Level = TabLevel[b] * NSigma[b];
MultiResol MR_EDGE(Nls, Ncs, E_Nscale, TO_MALLAT, "MR EDGE");
MR_EDGE.TypeNorm = NORM_L2;
// MR_EDGE.SBFilter=F_HAAR;
MR_EDGE.SBFilter=F_MALLAT_7_9;
MR_EDGE.transform(MR_Data.band(b));
for (b1= 0; b1 < MR_EDGE.nbr_band(); b1 ++)
for (i = 0; i < MR_EDGE.size_band_nl(b1); i++)
for (j = 0; j < MR_EDGE.size_band_nc(b1); j++)
if (ABS(MR_EDGE(b1,i,j)) < Level) MR_EDGE(b1,i,j) = 0.;
MR_EDGE.recons(Buff);
for (i = 0; i < Nls;i++)
for (j = 0; j < Ncs; j++)
if ((support(b,i,j)==VAL_SupNull) &&
(ABS(Buff(i,j)) > FLOAT_EPSILON)) support(b,i,j)=VAL_SupEdge;
}
}
if ((GetEgde == True)
&& ((Set_Transform == TRANSF_DIADIC_MALLAT) ||
(Set_Transform == TRANSF_MALLAT)))
{
for (b = 0; b < NbrBand-1; b++)
{
int s,b1,w,Np,LC_Nscale;
details which_detail;
MR_Data.band_to_scale(b, s, which_detail);
switch (which_detail)
{
case D_HORIZONTAL:
LC_Nscale = iround((float)log((float) (Ncs / 4. * 3.) / log(2.))) - s ;
Np = Ncs;
break;
case D_VERTICAL:
LC_Nscale = iround((float)log((float) (Nls / 4. * 3.) / log(2.))) - s ;
Np = Nls;
break;
default: LC_Nscale = 0; break;
}
if (LC_Nscale > 1)
{
MR_1D MR_LINE(Np, TO1_MALLAT, "line trans", LC_Nscale);
MR_LINE.SB_Filter=F_HAAR;
MR_LINE.Norm = NORM_L2;
MR_LINE.Border = I_CONT;
fltarray Col(Np);
float Nsig = 2.*NSigma[b];
if (which_detail == D_HORIZONTAL)
{
for (j = 0; j < Ncs; j++)
{
for (i = 0; i < Np; i++) Col(i) = MR_Data(b,i,j);
MR_LINE.transform(Col);
// thresholding assuming Gaussian noise
for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++)
for (w = 0; w < MR_LINE.size_scale_np(b1); w++)
if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.;
MR_LINE.recons(Col);
for (i = 0; i < Np; i++)
if ((support(b,i,j)==VAL_SupNull) &&
(ABS(Col(i)) > FLOAT_EPSILON)) support(b,i,j)=VAL_SupEdge;
}
}
else
{
for (i = 0; i < Nls; i++)
{
for (j = 0; j < Np; j++) Col(j) = MR_Data(b,i,j);
MR_LINE.transform(Col);
// thresholding assuming Gaussian noise
for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++)
for (w = 0; w < MR_LINE.size_scale_np(b1); w++)
if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.;
MR_LINE.recons(Col);
for (j = 0; j < Np; j++)
if ((support(b,i,j)==VAL_SupNull) &&
(ABS(Col(j)) > FLOAT_EPSILON)) support(b,i,j)=VAL_SupEdge;
}
}
}
}
}
*/
if (SupIsol == True) for (b = 0; b < NbrBand-2; b++) kill_isol(b);
if (DilateSupport == True)
for (b = 0; b < NbrBand-1; b++) dilate_support(b);
}
/****************************************************************************/
void MRNoiseModel::mod_support(MultiResol &MR_Data, fltarray Nsigma)
{
int i,j,k,s;
int Nls, Ncs;
for (s = 0; s < NbrBand-1; s++) {
Nls = MR_Data.size_band_nl(s);
Ncs = MR_Data.size_band_nc(s);
for (i = 0; i < Nls;i++)
for (j = 0; j < Ncs; j++)
{
if (support(s,i,j) == VAL_SupOK)
{
for (k=0; k<NbrBand; k++)
if (signif(MR_Data(k,i,j), k,i,j, Nsigma) == True)
support(k,i,j)=VAL_SupOK;
else support(k,i,j)=VAL_SupNull;
}
}
}
//if (SupIsol == True) for (s = 0; s < NbrBand-2; s++) kill_isol(s);
//if (DilateSupport == True)
// for (s = 0; s < NbrBand-1; s++) dilate_support(s);
}
/****************************************************************************/
Bool MRNoiseModel::kill_coef(int b,int i,int j, float Val, Bool SetSupport)
{
Bool ValRet=False;
if ((*this)(b,i,j) == False)
{
if (SetSupport == False) ValRet = True;
else
{
if ((support(b,i,j) == VAL_SupNull) &&
(signif(Val, b,i,j) == True))
{
support(b,i,j)=VAL_SupOK;
}
else ValRet = True;
}
}
return ValRet;
}
/****************************************************************************/
void MRNoiseModel::threshold(MultiResol &MR_Data, Bool SetSupport)
{
int i,j,b;
int Nls, Ncs;
for (b = 0; b < NbrBand-1; b++)
{
// int w, LC_Nscale, Np;
int b1,s;
details which_detail;
MR_Data.band_to_scale(b, s, which_detail);
Nls = TabNl(b);
Ncs = TabNc(b);
if ((GetEgde == True) && (Transform == TO_PAVE_BSPLINE))
{
int E_Nscale;
Ifloat Buff(Nls,Ncs,"Buff");
E_Nscale = iround((float)log((float) (MIN(Nls,Ncs) / 4. * 3.) / log(2.)));
if (one_level_per_pos_2d(TypeNoise) == True)
{
cout << "Error: this noise model cannot be used with this option ... " << endl;
exit(-1);
}
float Level = TabLevel[b] * NSigma[b];
MultiResol MR_EDGE(Nls, Ncs, E_Nscale, TO_MALLAT, "MR EDGE");
MR_EDGE.TypeNorm = NORM_L2;
// MR_EDGE.SBFilter=F_HAAR;
MR_EDGE.SBFilter=F_MALLAT_7_9;
MR_EDGE.transform(MR_Data.band(b));
for (b1= 0; b1 < MR_EDGE.nbr_band(); b1 ++)
for (i = 0; i < MR_EDGE.size_band_nl(b1); i++)
for (j = 0; j < MR_EDGE.size_band_nc(b1); j++)
if (ABS(MR_EDGE(b1,i,j)) < Level) MR_EDGE(b1,i,j) = 0.;
MR_EDGE.recons(Buff);
for (i = 0; i < Nls;i++)
for (j = 0; j < Ncs; j++)
if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True)
MR_Data(b,i,j) = Buff(i,j);
}
/* if ((GetEgde == True)
&& ((Set_Transform == TRANSF_DIADIC_MALLAT) ||
(Set_Transform == TRANSF_MALLAT)))
{
switch (which_detail)
{
case D_HORIZONTAL:
LC_Nscale = iround((float)log((float) (Ncs / 4. * 3.) / log(2.))) - s ;
Np = Ncs;
break;
case D_VERTICAL:
LC_Nscale = iround((float)log((float) (Nls / 4. * 3.) / log(2.))) - s ;
Np = Nls;
break;
default: LC_Nscale = 0; break;
}
}
else LC_Nscale = 0;
LC_Nscale = 0;
if (LC_Nscale > 1)
{
MR_1D MR_LINE(Np, TO1_MALLAT, "line trans", LC_Nscale);
MR_LINE.SB_Filter=F_HAAR;
MR_LINE.Norm = NORM_L2;
MR_LINE.Border = I_CONT;
fltarray Col(Np);
float Nsig = 2.*NSigma[b];
if (which_detail == D_HORIZONTAL)
{
for (j = 0; j < Ncs; j++)
{
for (i = 0; i < Np; i++) Col(i) = MR_Data(b,i,j);
MR_LINE.transform(Col);
// thresholding assuming Gaussian noise
for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++)
for (w = 0; w < MR_LINE.size_scale_np(b1); w++)
if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.;
MR_LINE.recons(Col);
for (i = 0; i < Np; i++)
if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True)
MR_Data(b,i,j)=Col(i);
}
}
else
{
for (i = 0; i < Nls; i++)
{
for (j = 0; j < Np; j++) Col(j) = MR_Data(b,i,j);
MR_LINE.transform(Col);
// thresholding assuming Gaussian noise
for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++)
for (w = 0; w < MR_LINE.size_scale_np(b1); w++)
if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.;
MR_LINE.recons(Col);
for (j = 0; j < Np; j++)
if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True)
MR_Data(b,i,j)=Col(j);
}
}
} */
else
{
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True)
MR_Data(b,i,j)=0.;
}
}
}
/****************************************************************************/
void MRNoiseModel::refresh_support(MultiResol &MR_Data)
{
int i,j,s;
int ValSup;
int Nls, Ncs;
float CoefMr;
for (s = 0; s < NbrBand-1; s++)
{
Nls = TabNl(s);
Ncs = TabNc(s);
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
{
CoefMr = MR_Data(s,i,j);
ValSup = support(s,i,j);
if ( (ValSup == VAL_SupNull) && (signif(CoefMr,s,i,j) == True))
support(s,i,j)=VAL_SupOK;
}
}
}
/****************************************************************************/
void MRNoiseModel::weight_snr(MultiResol &MR_Data, Bool SetSupport)
{
int i,j,s;
int ValSup;
int Nls, Ncs;
float CoefMr,Weight;
for (s = 0; s < NbrBand-1; s++)
{
Nls = TabNl(s);
Ncs = TabNc(s);
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
{
CoefMr = MR_Data(s, i, j);
ValSup = support(s,i,j);
if ( (SetSupport == True) && (ValSup == VAL_SupNull)
&& (signif(CoefMr,s,i,j) == True))
support(s,i,j)=VAL_SupOK;
Weight = ABS(CoefMr) / (NSigma[s]*sigma(s,i,j));
if (Weight > 1.) Weight = 1.;
MR_Data(s, i, j) *= Weight;
}
}
}
/****************************************************************************/
void MRNoiseModel::weight_invsnr(MultiResol &MR_Data, Bool SetSupport)
{
int i,j,s;
float CoefMr,Weight;
int ValSup;
int Nls, Ncs;
for (s = 0; s < NbrBand-1; s++)
{
Nls = TabNl(s);
Ncs = TabNc(s);
for (i = 0; i < Nls; i++)
for (j = 0; j < Ncs; j++)
{
CoefMr = MR_Data(s, i, j);
ValSup = support(s,i,j);
if ( (SetSupport == True) && (ValSup == VAL_SupNull)
&& (signif(CoefMr,s,i,j) == True))
support(s,i,j)=VAL_SupOK;
Weight = ABS(CoefMr) / (NSigma[s]*sigma(s,i,j));
if (Weight > 1.) Weight = 1.;
MR_Data(s, i, j) *= (1. - Weight);
}
}
}
/****************************************************************************/
void MRNoiseModel::set_sigma(Ifloat & Imag, MultiResol &MR_Data)
{
extern float mr_tab_noise(int s);
int b, s,i,j,Ind;
noise_compute (MR_Data);
// cout << "noise_compute: set_sigma : Noise = " << SigmaNoise << endl;
//Imag.info("MM");
if ((SigmaNoise < FLOAT_EPSILON) && (NewStatNoise == NOISE_GAUSSIAN))
{
switch (SigmaDetectionMethod)
{
case SIGMA_MEDIAN: SigmaNoise = detect_noise_from_med (Imag); break;
case SIGMA_BSPLINE:
SigmaNoise = detect_noise_from_bspline (Imag); break;
case SIGMA_CLIPIMA:SigmaNoise = detect_noise_sigma (Imag); break;
case SIGMA_SUPPORT:
SigmaNoise=detect_noise_from_support(Imag,MR_Data,(*this));
break;
default: cerr<< "Error: MRNoiseModel:set_sigma, unknown method" << endl;
exit(0);break;
}
}
// cout << "After set_sigma : Noise = " << SigmaNoise << endl;
switch (NewStatNoise)
{
case NOISE_SPECKLE:
{
// we assume that the level at 3.719sigma (eps = 1e-4) gives
// a good fit of the gaussian law to the rayley noise distribution
fltarray R_Eps(NbrBand-1);
fltarray Tmin(NbrBand-1);
fltarray Tmax(NbrBand-1);
for (s = 0; s < NbrBand-1; s++) R_Eps(NbrBand-1) = 1.e-04;
CSpeckle->find_threshold(NbrBand,R_Eps, Tmin, Tmax);
for (s = 0; s < NbrBand-1; s++)
{
float Max = ABS(Tmin(s));
if (ABS(Tmin(s)) < ABS(Tmax(s))) Max = Tmax(s);
TabLevel[s] = Max / 3.719;
}
}
break;
case NOISE_CORREL:
for (s = 0; s < NbrBand-1; s++)
TabLevel[s] = CorrelNoiseMap->sigma_band(s);
break;
case NOISE_GAUSSIAN:
if ((Transform == TO_DIADIC_MALLAT) && (GradientAnalysis == True))
{
extern double TabNormGradDiadicMallat[MAX_SCALE];
for (s = 0; s < NbrBand-1; s++)
TabLevel[s] = SigmaNoise*TabNormGradDiadicMallat[s/2];
}
else for (s = 0; s < NbrBand-1; s++)
TabLevel[s] = SigmaNoise*MR_Data.band_norm(s);
break;
case NOISE_NON_UNI_ADD:
if ((Set_Transform == TRANSF_MALLAT) ||
(Set_Transform == TRANSF_FEAUVEAU))
{
cerr << "Error: this kind of transform cannot be used " << endl;
cerr << " with this noise model " << endl;
exit(-1);
}
if (UseRmsMap == False)
{
// Ifloat ImaSigmaNoise(Nl, Nc, "ImaSigmaNoise");
Ifloat Buff(Nl, Nc, "Buff");
RmsMap.alloc(Nl, Nc, "ImaSigmaNoise");
smooth_mediane (Imag, Buff, I_MIRROR, 0, 3);
Buff = Imag - Buff;
im_sigma(Buff, RmsMap, SizeBlockSigmaNoise, NiterSigmaClip);
// io_write_ima_float("xx_rms.fits", RmsMap);
}
// calculate the true sigma at each scale :
if ((RmsMap.nl() != Nl) || (RmsMap.nc() != Nc))
{
cerr << "Error: RMS map is not correctly initialized ... " << endl;
exit(0);
}
if (((Transform == TO_PAVE_BSPLINE) && (GetRmsCoeffGauss == True))
|| (Transform == TO_UNDECIMATED_MALLAT)
|| (Transform == TO_UNDECIMATED_NON_ORTHO)
|| (Transform == TO_PAVE_FEAUVEAU)
|| (Transform == TO_DIADIC_MALLAT))
get_sigma_from_rms_map(RmsMap);
else max_sigma_in_scale(RmsMap);
UseRmsMap=True;
break;
case NOISE_UNI_UNDEFINED:
for (b = 0; b < NbrBand-1; b ++)
{
//float SigmaScale, MeanScale;
//sigma_clip(MR_Data.band(b), MeanScale, SigmaScale, NiterSigmaClip);
//TabLevel[b] = SigmaScale;
TabLevel[b] = detect_noise_from_mad(MR_Data.band(b), MadEstimFromCenter);
}
break;
case NOISE_UNDEFINED:
{
// cout << "NOISE_UNDEFINED " << endl;
Ifloat ImaSigmaNoise(Nl, Nc, "ImaSigmaNoise");
int BlockSize = SizeBlockSigmaNoise;
for (b = 0; b < NbrBand-1; b++)
{
// cout << "Band " << b+1 << endl;
int Nlb = MR_Data.size_band_nl(b);
int Ncb = MR_Data.size_band_nc(b);
float SigmaScale, MeanScale;
//details which_detail;
//MR_Data.band_to_scale(b, s, which_detail);
// cout << "sigma_clip " << Nlb << " " << Ncb << endl;
sigma_clip(MR_Data.band(b), MeanScale, SigmaScale, NiterSigmaClip);
ImaSigmaNoise.resize(Nlb, Ncb);
// If we want the full resolution, we need to uncomment the next line.
// Otherwise the noise standard deviation is calculated on for position
// at a distance of BlockSize/2
// im_sigma(MR_Data.band(b), ImaSigmaNoise, BlockSize, NiterSigmaClip);
// use the MAD instead of sigma_clipping: im_sigma_block_mad(MR_Data.band(b), ImaSigmaNoise, BlockSize, 32);
// cout << "im_sigma_block " << BlockSize << " " << NiterSigmaClip << " " << BlockSize/2 << endl;
im_sigma_block(MR_Data.band(b), ImaSigmaNoise, BlockSize, NiterSigmaClip, BlockSize/2);
// cout << "out_sigma_block " << Nlb << " " << Ncb << endl;
for (i = 0; i < Nlb;i++)
for (j = 0; j < Ncb; j++)
{
Ind = index(b,i,j);
TabLevel[Ind] = ImaSigmaNoise(i,j); // MAX(SigmaScale, ImaSigmaNoise(i,j));
}
if ((Set_Transform == TRANSF_PAVE)
|| ((Set_Transform == TRANSF_UNDECIMATED_MALLAT) && (b%3 == 2))
|| ((Set_Transform == TRANSF_DIADIC_MALLAT) && (b%2 == 1)))
BlockSize *=2;
}
// cout << "END NOISE_UNDEFINED " << endl;
}
break;
case NOISE_EVENT_POISSON:
{
Ifloat EventCount(Nl,Nc,"ImagCount");
float alpha;
for (s = 0; s < MR_Data.nbr_band()-1; s++)
{
alpha=1.;
for (int sc=0; sc < s; sc++) alpha *= 4.;
event_one_scale(Event_Image, s, EventCount, MR_Data.Border);
for (i=0;i<Nl;i++)
for (j=0;j<Nc;j++)
{
Ind = index(s,i,j);
TabLevel[Ind] = SIGMA_BSPLINE_WAVELET * sqrt((float) EventCount(i,j)) / alpha;
}
}
}
break;
default: break;
}
}
/****************************************************************************/
void MRNoiseModel::speckle_support(MultiResol &MR_Data)
{
int Nlb, Ncb, i,j,b;
float Max;
fltarray R_Eps(NbrBand-1);
fltarray Tmin(NbrBand-1);
fltarray Tmax(NbrBand-1);
for (b = 0; b < NbrBand-1; b++) R_Eps(b) = TabEps[b];
CSpeckle->find_threshold(MR_Data.nbr_band(), R_Eps, Tmin, Tmax);
for (b = 0; b < MR_Data.nbr_band()-1; b++)
{
Max = ABS(Tmin(b));
if (Max < ABS(Tmax(b))) Max = Tmax(b);
TabLevel[b] = ABS(Max) / NSigma[b];
Nlb = MR_Data.size_band_nl(b);
Ncb = MR_Data.size_band_nc(b);
for (i = 0; i < Nlb;i++)
for (j = 0; j < Ncb; j++)
{
if (signif(MR_Data(b,i,j), b,i,j,Tmin(b),Tmax(b)) == True)
support(b,i,j)=VAL_SupOK;
else support(b,i,j)=VAL_SupNull;
}
}
if (SupIsol == True) for (b = 0; b < NbrBand-2; b++) kill_isol(b);
if (DilateSupport == True)
for (b = 0; b < NbrBand-1; b++) dilate_support(b);
}
/****************************************************************************/
void MRNoiseModel::correl_support(MultiResol &MR_Data)
{
int Nlb, Ncb, i,j,b;
fltarray R_Eps(NbrBand-1);
fltarray Tmin(NbrBand-1);
fltarray Tmax(NbrBand-1);
for (b = 0; b < NbrBand-1; b++) R_Eps(b) = TabEps[b];
CorrelNoiseMap->find_threshold(MR_Data.nbr_band(), R_Eps, Tmin, Tmax);
for (b = 0; b < MR_Data.nbr_band()-1; b++)
{
TabLevel[b] = CorrelNoiseMap->sigma_band(b);
Nlb = MR_Data.size_band_nl(b);
Ncb = MR_Data.size_band_nc(b);
for (i = 0; i < Nlb;i++)
for (j = 0; j < Ncb; j++)
{
if (signif(MR_Data(b,i,j), b,i,j,Tmin(b),Tmax(b)) == True)
support(b,i,j)=VAL_SupOK;
else support(b,i,j)=VAL_SupNull;
}
}
if (SupIsol == True) for (b = 0; b < NbrBand-2; b++) kill_isol(b);
if (DilateSupport == True)
for (b = 0; b < NbrBand-1; b++) dilate_support(b);
}
/****************************************************************************/
void MRNoiseModel::model(Ifloat & Imag, MultiResol &MR_Data)
{
NewStatNoise = TypeNoise;
//int s;
// if TypeNoise != NOISE_EVENT_POISSON and MinEvent == True
// the parameter Event_Image must be intialized before the
// call to model
if ((MinEvent == True) && (TypeNoise != NOISE_EVENT_POISSON))
{
if ( (TypeNoise == NOISE_EVENT_POISSON)
&& (Imag.nl() != Event_Image.nl())
&& (Imag.nc() != Event_Image.nc()))
{
cerr << "Error: MRNoiseModel::model : Event_Image is not correctly Initialized ..." << endl;
exit(-1);
}
}
// if TypeNoise == NOISE_EVENT_POISSON and TransImag == False
// the parameter Event_Image must be intialized before the
// call to model
if ( (TypeNoise == NOISE_EVENT_POISSON) && (TransImag == False) &&
((Imag.nl() != Event_Image.nl()) || (Imag.nc() != Event_Image.nc())))
{
cerr << "Error: MRNoiseModel::model : Event_Image is not correctly Initialized ..." << endl;
exit(-1);
}
switch (TypeNoise)
{
case NOISE_POISSON:
case NOISE_GAUSS_POISSON:
SigmaNoise = 1.;
case NOISE_MULTI:
if (TransImag == True) im_transform(Imag);
NewStatNoise = NOISE_GAUSSIAN;
break;
case NOISE_GAUSSIAN:
case NOISE_NON_UNI_ADD:
case NOISE_UNI_UNDEFINED:
case NOISE_UNDEFINED:
case NOISE_CORREL:
break;
case NOISE_NON_UNI_MULT:
if (TransImag == True) im_transform(Imag);
NewStatNoise = NOISE_NON_UNI_ADD;
break;
case NOISE_EVENT_POISSON:
if (TransImag == True) im_transform(Imag);
// in case of Poisson noise, the MIRROR border must be used
MR_Data.Border = I_MIRROR;
TransImag = False;
SigmaNoise = 1.;
break;
case NOISE_SPECKLE:
if (TransImag == True) im_transform(Imag);
break;
}
// transform the input data
Border = MR_Data.Border;
U_Filter = MR_Data.U_Filter;
TypeNorm = MR_Data.TypeNorm;
FilterBank = MR_Data.filter_bank();
NbrUndecimatedScale = MR_Data.nbr_undec_scale();
MR_Data.SigmaNoise = SigmaNoise;
// cout << "MR_Data.transform" << endl;
MR_Data.transform(Imag);
switch (TypeNoise)
{
case NOISE_POISSON:
case NOISE_GAUSS_POISSON:
case NOISE_MULTI:
case NOISE_NON_UNI_MULT:
set_sigma(Imag, MR_Data);
set_support(MR_Data);
if (TransImag == True) im_invtransform(Imag);
break;
case NOISE_GAUSSIAN:
case NOISE_NON_UNI_ADD:
case NOISE_UNDEFINED:
case NOISE_UNI_UNDEFINED:
// cout << "set_sigma" << endl;
set_sigma(Imag, MR_Data);
// cout << "set_support" << endl;
set_support(MR_Data);
// cout << "ok" << endl;
break;
case NOISE_CORREL:
if (CorrelNoiseMap != NULL) delete CorrelNoiseMap;
CorrelNoiseMap = new StatNoiseMap(RmsMap, NbrScale, Transform,
FilterBank, TypeNorm, NbrUndecimatedScale, U_Filter);
if (SigmaApprox == False) correl_support(MR_Data);
else
{
set_sigma(Imag, MR_Data);
set_support(MR_Data);
}
break;
case NOISE_EVENT_POISSON:
if (SigmaApprox == False) // Default
{
Bool WriteAllInfo = False;
mr2d_psupport( MR_Data, (*this), MR_Data.Border, WriteAllInfo );
//mr_psupport(MR_Data, (*this), MR_Data.Border);
if (SupIsol == True) for (int b = 0; b < NbrBand-2; b++) kill_isol(b);
}
else
{
set_sigma(Imag, MR_Data);
set_support(MR_Data);
}
break;
case NOISE_SPECKLE:
if (SigmaApprox == False) speckle_support(MR_Data);
else
{
set_sigma(Imag, MR_Data);
set_support(MR_Data);
}
if (TransImag == True) im_invtransform(Imag);
break;
}
// ALREADY done in MR_Psup.cc
// verify if minimum number of count OK
// if (MinEvent == True)
// {
// // if (TypeNoise == NOISE_EVENT_POISSON)
// // for (int s=0; s < NbrBand-1; s++) kill_event(s, Imag);
// }
}
/****************************************************************************/
void MRNoiseModel::model(Ifloat & Imag)
{
// MultiResol MR_Data(Nl, Nc, NbrScale, Transform, "MRNoiseModel");
MultiResol MR_Data;
MR_Data.alloc (Nl, Nc, NbrScale, Transform, FilterBank, TypeNorm, NbrUndecimatedScale, U_Filter);
model(Imag, MR_Data);
}
/****************************************************************************/
void MRNoiseModel::free()
{
if (Size > 0)
{
if (one_level_per_pos_2d(TypeNoise) == True) free_buffer((char *) TabLevel);
else delete [] TabLevel;
free_buffer((char *) TabSupport);
NbrScale = 0;
Nl = 0;
Nc = 0;
Size = 0;
//if (CEventPois != NULL) delete CEventPois;
if (CFewEventPoisson2d != NULL) delete CFewEventPoisson2d;
if (CFewEvent2d != NULL) delete CFewEvent2d;
if (CSpeckle != NULL) delete CSpeckle;
if (CorrelNoiseMap != NULL) delete CorrelNoiseMap;
}
}
/****************************************************************************/
MRNoiseModel::~MRNoiseModel()
{
(*this).free();
}
/****************************************************************************/
void MRNoiseModel::mr_obj(MultiResol &MR_Data)
{
int i,j,s;
for (s = 0; s < NbrBand-1; s++)
for (i = 0; i < TabNl(s);i++)
for (j = 0; j < TabNc(s); j++)
{
if ((*this)(s,i,j) == True) MR_Data(s,i,j) = 1.;
else MR_Data(s,i,j) = 0.;
}
}
/****************************************************************************/
void MRNoiseModel::write_support_mr(char *FileName)
{
MultiResol MR_Data;
MR_Data.alloc (Nl, Nc, NbrScale, Transform, FilterBank,
TypeNorm, NbrUndecimatedScale);
(*this).mr_obj(MR_Data);
MR_Data.write(FileName);
}
/****************************************************************************/
void MRNoiseModel::write_support_ima(char *FileName)
{
MultiResol MR_Data;
MR_Data.alloc (Nl, Nc, NbrScale, Transform, FilterBank,
TypeNorm, NbrUndecimatedScale);
(*this).mr_obj(MR_Data);
float Coef;
Ifloat Ima(Nl, Nc, "MRNoiseModel write");
int s,i,j;
Ima.init();
switch (Set_Transform)
{
case TRANSF_PAVE:
case TRANSF_PYR:
case TRANSF_DIADIC_MALLAT:
case TRANSF_UNDECIMATED_MALLAT:
case TRANSF_SEMIPYR:
{
Ifloat Dat(Nl, Nc, "MRNoiseModel write");
for (s = NbrBand-2; s >= 0; s--)
{
Coef = (float) ( 1 << (NbrBand-1-s));
im_block_extend(MR_Data.band(s), Dat);
// cout << "Coef = " << Coef << endl;
// cout << MR_Data.band(s).nl() << " to " << Dat.nl() << endl;
// cout << MR_Data.band(s).nc() << " to " << Dat.nc() << endl;
for (i = 0; i < Dat.nl();i++)
for (j = 0; j < Dat.nc(); j++)
if (Dat(i,j) > FLOAT_EPSILON) Ima(i,j) = Coef;
}
}
break;
case TRANSF_MALLAT:
case TRANSF_FEAUVEAU:
ortho_trans_to_ima(MR_Data, Ima);
break;
default:
cerr << "Error: Unknown set transform ... " << endl;
exit(0);
break;
}
io_write_ima_float(FileName, Ima);
}
void MRNoiseModel::set_old_poisson( Bool Flag ) {
mOldPoisson = Flag;
if( mOldPoisson )
std::cout << "!!! Odl poisson few event class is used !!!"
<< std::endl;
}
Bool MRNoiseModel::old_poisson() {
return mOldPoisson;
}
void MRNoiseModel::write_threshold( Bool Flag ) {
mWriteThreshold = Flag;
}
void MRNoiseModel::write_in_few_event( Bool Write ) {
if( CFewEvent2d != (FewEvent*)NULL )
CFewEvent2d->set_write_all( Write ) ;
}
/****************************************************************************/
void MRNoiseModel::trace() {
cout << "class MRNoiseModel" << endl;
cout << "------------------" << endl;
cout << "NbrScale = " << NbrScale << endl;
cout << "NbrBand = " << NbrBand << endl;
cout << "Nl = " << Nl << endl;
cout << "Nc = " << Nc << endl;
cout << "Size = " << Size << endl;
cout << "Transform = " << StringTransform(Transform) << endl;
cout << "Set_Transform = " << StringSetTransform(Set_Transform) << endl;
cout << "TypeNoise = " << StringNoise(TypeNoise) << endl;
cout << "Border = " << (int)Border << endl;
cout << "NSigma : " << endl;
for (int i=0;i<NbrBand;i++)
cout << " scale[i] : " << NSigma[i] << endl;
if (SigmaApprox) cout << "SigmaApprox = true" << endl;
cout << "TypeNorm = " << (int)DEF_SB_NORM << endl;
cout << "NbrUndecimatedScale = " << (int)NbrUndecimatedScale << endl;
if (GradientAnalysis) cout << "GradientAnalysis = true" << endl;
if (NoCompDistrib) cout << "NoCompDistrib = true" << endl;
cout << "Size = " << (int)Size << endl;
cout << "BadPixelVal = " << BadPixelVal << endl;
if (BadPixel) cout << "BadPixel = true" << endl;
if (MinEvent) cout << "MinEvent = true" << endl;
if (SupIsol) cout << "SupIsol = true" << endl;
cout << "FirstDectectScale = " << FirstDectectScale << endl;
if (OnlyPositivDetect) cout << "OnlyPositivDetect = true" << endl;
if (DilateSupport) cout << "DilateSupport = true" << endl;
if (GetEgde) cout << "GetEgde = true" << endl;
cout << "MinEventNumber = " << MinEventNumber << endl;
cout << "SigmaDetectionMethod = " << (int)SigmaDetectionMethod << endl;
cout << "NiterSigmaClip = " << (int)NiterSigmaClip << endl;
cout << "SizeBlockSigmaNoise = " << SizeBlockSigmaNoise << endl;
if (TransImag) cout << "TransImag = true" << endl;
if (UseRmsMap) cout << "UseRmsMap = true" << endl;
if (GetRmsCoeffGauss) cout << "GetRmsCoeffGauss = true" << endl;
if (SigmaApprox) cout << "SigmaApprox = true" << endl;
if (TabLevel == NULL) cout << "TabLevel = NULL" << endl;
if (TabSupport == NULL) cout << "TabSupport = NULL" << endl;
//if (CEventPois == NULL) cout << "CEventPois = NULL" << endl;
if (CFewEventPoisson2d == NULL) cout << "CFewEventPoisson2d = NULL" << endl;
if (CFewEvent2d == NULL) cout << "CFewEventPoisson2d = NULL" << endl;
if (CSpeckle == NULL) cout << "CSpeckle = NULL" << endl;
if (CorrelNoiseMap == NULL) cout << "CorrelNoiseMap = NULL" << endl;
if (FilterBank == NULL) cout << "FilterBank = NULL" << endl;
cout << "end class MRNoiseModel" << endl;
}
| 31.77546
| 129
| 0.477404
|
jstarck
|
5deb11b2b625dc4a762fa6ca09adcf714906b83c
| 1,519
|
cpp
|
C++
|
src/PlayMusicOnStartC.cpp
|
NoVariableGlobal/g.shift
|
35907cd4aa931dbef8d15cade76d8cab1d11716c
|
[
"MIT"
] | null | null | null |
src/PlayMusicOnStartC.cpp
|
NoVariableGlobal/g.shift
|
35907cd4aa931dbef8d15cade76d8cab1d11716c
|
[
"MIT"
] | null | null | null |
src/PlayMusicOnStartC.cpp
|
NoVariableGlobal/g.shift
|
35907cd4aa931dbef8d15cade76d8cab1d11716c
|
[
"MIT"
] | 1
|
2020-10-07T15:09:57.000Z
|
2020-10-07T15:09:57.000Z
|
#include "PlayMusicOnStartC.h"
#include "ComponentsManager.h"
#include "Entity.h"
#include "FactoriesFactory.h"
#include "Scene.h"
#include "SoundComponent.h"
#include <json.h>
// COMPONENT CODE
void PlayMusicOnStartC::destroy() {
stopCurrentMusic(music_);
setActive(false);
scene_->getComponentsManager()->eraseDC(this);
}
void PlayMusicOnStartC::setMusic(const std::string& sound) {
if (music_ != sound) {
reinterpret_cast<SoundComponent*>(
father_->getComponent("SoundComponent"))
->stopSound(music_);
music_ = sound;
reinterpret_cast<SoundComponent*>(
father_->getComponent("SoundComponent"))
->playSound(music_);
}
}
void PlayMusicOnStartC::stopCurrentMusic(const std::string& sound) {
reinterpret_cast<SoundComponent*>(father_->getComponent("SoundComponent"))
->stopSound(sound);
}
// FACTORY INFRASTRUCTURE DEFINITION
PlayMusicOnStartCFactory::PlayMusicOnStartCFactory() = default;
Component* PlayMusicOnStartCFactory::create(Entity* _father, Json::Value& _data,
Scene* _scene) {
PlayMusicOnStartC* play = new PlayMusicOnStartC();
_scene->getComponentsManager()->addDC(play);
play->setFather(_father);
play->setScene(_scene);
if (!_data["sound"].isString())
throw std::exception("PlayMusicOnStartC: sound is not a string");
play->setMusic(_data["sound"].asString());
return play;
}
DEFINE_FACTORY(PlayMusicOnStartC)
| 27.618182
| 80
| 0.677419
|
NoVariableGlobal
|
5def05c6497532561c420c99e28ef891b12862e6
| 496
|
cpp
|
C++
|
source/main.cpp
|
Sticky-Bits/voxel_engine
|
d730c6bc652df11d0ca6cfe750bf32fb71906440
|
[
"MIT"
] | null | null | null |
source/main.cpp
|
Sticky-Bits/voxel_engine
|
d730c6bc652df11d0ca6cfe750bf32fb71906440
|
[
"MIT"
] | null | null | null |
source/main.cpp
|
Sticky-Bits/voxel_engine
|
d730c6bc652df11d0ca6cfe750bf32fb71906440
|
[
"MIT"
] | null | null | null |
#include <stdlib.h>
#include "Game.h"
int main()
{
// Load settings
Settings* p_settings = new Settings();
p_settings->load_settings();
// Create game using settings
Game* p_game = Game::get_instance();
p_game->create(p_settings);
// Main loop
while (!p_game->should_close())
{
// Poll input events
p_game->poll_events();
// Update
p_game->update();
// Render
p_game->render();
}
// Destroy objects, window etc.
p_game->destroy();
// Exit
exit(EXIT_SUCCESS);
}
| 14.588235
| 39
| 0.65121
|
Sticky-Bits
|
5def8e8e8d39e584d096d1f97b7676a1d132b9bc
| 2,639
|
cpp
|
C++
|
graph-source-code/404-C/9402829.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/404-C/9402829.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/404-C/9402829.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: GNU C++0x
//created by Yash Sadhwani
//sadhwaniyash6
#include<stdio.h>
#include<iostream>
#include<vector>
#include<string.h>
#include<algorithm>
#include<deque>
#include<map>
#include<set>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<functional>
using namespace std;
#define ll long long
#define si(x) scanf("%d",&x)
#define sc(x) scanf("%c",&x)
#define vl vector<ll>
#define vi vector<int>
#define vvl vector< vl >
#define vvi vector< vi >
#define pb push_back
#define mod 1000000009
#define mem(x,y) memset(x,y,sizeof(x))
#define f(i,a,b) for(int i=(a);i<(b);i++)
#define max_int_value 2147483647
#define max_long_value 9223372036854775807
//qsort(ww,cc,sizeof(tp),compare);
/*int compare(const void *a,const void *b){
ll y=((((tp*)a)->w)-(((tp*)b)->w));
if(y>0)return 1;
else if(y==0)return 0;
else return -1;
}*/
#define MAXN 100010
#define ii pair<int,int>
ii d[MAXN];
int N,K;
int edges[MAXN];
vector<ii> ans;
int len[MAXN];
inline void ReadInput(void){
si(N); si(K);
for(int i=1;i<=N;i++){
int x; si(x);
d[i]=ii(x,i);
len[i]=x;
}
}
inline void solve(void){
if(N==1 && K==0){
if(d[1].first==0){
cout<<"0\n";
return;
}else{
cout<<"-1\n";
return;
}
}
else if(N==1){
cout<<"-1\n";
return;
}
else if(K==0){
cout<<"-1\n";
return;
}
sort(d+1,d+N+1);
queue<int> pp;
pp.push(d[1].second);
if(d[1].first!=0){
cout<<"-1\n";
return;
}
for(int i=2;i<=N;i++){
while(!pp.empty() && (edges[pp.front()]==K || len[pp.front()]<len[d[i].second]-1))pp.pop();
if(pp.empty()){
cout<<"-1\n";
return;
}
int u=pp.front();
//cout<<u<<" "<<d[i].second<<endl;
if(len[u]==len[d[i].second]){
cout<<"-1\n";
return;
}
//cout<<"hello\n";
if(edges[u]<K && len[u]+1==len[d[i].second]){
edges[u]++;
edges[d[i].second]++;
pp.push(d[i].second);
ans.pb(ii(u,d[i].second));
if(edges[u]==K)pp.pop();
//cout<<u<<" "<<d[i].second<<endl;
}
}
cout<<ans.size()<<endl;
for(int i=0;i<ans.size();i++)cout<<ans[i].first<<" "<<ans[i].second<<endl;
}
inline void Refresh(void){
fill(edges,edges+MAXN,0);
}
int main()
{
ReadInput();
Refresh();
solve();
return 0;
}
| 21.991667
| 101
| 0.483516
|
AmrARaouf
|
5df3db5beeb54baf4b1d1c617d7f80cd345c849c
| 2,401
|
cpp
|
C++
|
src/qt/qtbase/tests/manual/widgets/itemviews/qtreeview/main.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | 1
|
2020-04-30T15:47:35.000Z
|
2020-04-30T15:47:35.000Z
|
src/qt/qtbase/tests/manual/widgets/itemviews/qtreeview/main.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/tests/manual/widgets/itemviews/qtreeview/main.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QFileSystemModel model;
QWidget window;
QTreeView *tree = new QTreeView(&window);
tree->setMaximumSize(1000, 600);
QHBoxLayout *layout = new QHBoxLayout;
layout->setSizeConstraint(QLayout::SetFixedSize);
layout->addWidget(tree);
window.setLayout(layout);
model.setRootPath("");
tree->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
tree->setModel(&model);
tree->setAnimated(false);
tree->setIndentation(20);
tree->setSortingEnabled(true);
tree->header()->setStretchLastSection(false);
window.setWindowTitle(QObject::tr("Dir View"));
tree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
window.show();
return app.exec();
}
| 36.938462
| 77
| 0.688047
|
power-electro
|
5df3f62863952cbba5581906d60a098a129cc588
| 436
|
hpp
|
C++
|
cpp/include/init_numpy.hpp
|
davidkleiven/WangLandau
|
0b253dd98033c53560fe95c76f5e38257834bdf6
|
[
"MIT"
] | 2
|
2022-02-10T00:38:53.000Z
|
2022-03-17T22:08:40.000Z
|
cpp/include/init_numpy.hpp
|
davidkleiven/CEMC
|
0b253dd98033c53560fe95c76f5e38257834bdf6
|
[
"MIT"
] | 30
|
2018-05-21T14:52:00.000Z
|
2021-02-24T07:45:09.000Z
|
cpp/include/init_numpy.hpp
|
davidkleiven/WangLandau
|
0b253dd98033c53560fe95c76f5e38257834bdf6
|
[
"MIT"
] | 3
|
2018-10-09T14:03:32.000Z
|
2022-02-09T05:36:05.000Z
|
#ifndef INIT_NUMPY_H
#define INIT_NUMPY_H
#include <Python.h>
#define PY_ARRAY_UNIQUE_SYMBOL CE_UPDATER_ARRAY_API
#include "numpy/ndarrayobject.h"
#if PY_MAJOR_VERSION >= 3
inline int* init_numpy()
{
import_array();
// Avoid compilation warning
// import_array is a macro that inserts a return statement
// so it has no practical effect
return NULL;
};
#else
inline void init_numpy()
{
import_array();
};
#endif
#endif
| 18.166667
| 61
| 0.743119
|
davidkleiven
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.