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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fd446aa32dcdc33d043b92b20b54002c03667412
| 8,538
|
hpp
|
C++
|
rice/Module_impl.hpp
|
keyme/rice
|
4b5e4ad3e2294a1b58886fb946eb26e3512599d9
|
[
"BSD-2-Clause"
] | 11
|
2015-02-09T12:13:45.000Z
|
2019-11-25T01:14:31.000Z
|
rice/Module_impl.hpp
|
jsomers/rice
|
6bbcc2dd85d010a1108a4d7ac7ece39b1c1210f5
|
[
"BSD-2-Clause"
] | null | null | null |
rice/Module_impl.hpp
|
jsomers/rice
|
6bbcc2dd85d010a1108a4d7ac7ece39b1c1210f5
|
[
"BSD-2-Clause"
] | 2
|
2019-11-25T01:14:35.000Z
|
2021-09-29T04:57:36.000Z
|
#ifndef Rice__Module_impl__hpp_
#define Rice__Module_impl__hpp_
#include "detail/Exception_Handler_defn.hpp"
#include "detail/ruby.hpp"
#include "Object_defn.hpp"
#include "Address_Registration_Guard_defn.hpp"
#include "Arg.hpp"
namespace Rice
{
class Module;
class Class;
template<typename T> class Data_Type;
/*! Holds all member data of Module_impl so it only exists in one place
* in the hierarchy.
*/
class Module_base
: public Object
{
public:
Module_base(VALUE v = rb_cObject);
Module_base(Module_base const & other);
Module_base & operator=(Module_base const & other);
void swap(Module_base & other);
protected:
template<typename Exception_T, typename Functor_T>
void add_handler(Functor_T functor);
Object handler() const;
private:
Object mutable handler_;
Address_Registration_Guard handler_guard_;
};
/*! An intermediate base class so we can always return the most-derived
* type (Module, Class, Data_Type, ...) without having to re-implement
* each function for each derived class.
*/
template<typename Base_T, typename Derived_T>
class Module_impl
: public Base_T
{
public:
Module_impl();
template<typename T>
Module_impl(T const & arg);
//! Define an exception handler.
/*! Whenever an exception of type Exception_T is thrown from a
* function defined on this class, functor will be called to
* translate the exception into a ruby exception.
* \param Exception_T a template parameter indicating the type of
* exception to be translated.
* \param functor a functor to be called to translate the exception
* into a ruby exception. This functor should re-throw the exception
* as an Exception.
* Example:
* \code
* class MyException : public std::exception { };
* Data_Type<MyException> rb_cMyException;
* Class rb_cFoo;
*
* void translate_my_exception(MyException const & ex)
* {
* Data_Object<MyException> ex_(
* new MyException(ex),
* rb_cMyException);
* throw Exception(ex_);
* }
*
* extern "C"
* void Init_MyExtension()
* {
* rb_cMyException = define_class("MyException");
* rb_cFoo = define_class("Foo")
* .add_handler<MyException>(translate_my_exception);
* }
* \endcode
*/
template<typename Exception_T, typename Functor_T>
Derived_T & add_handler(
Functor_T functor);
//! Define an instance method.
/*! The method's implementation can be any function or member
* function. A wrapper will be generated which will use from_ruby<>
* to convert the arguments from ruby types to C++ types before
* calling the function. The return value will be converted back to
* ruby by using to_ruby().
* \param name the name of the method
* \param func the implementation of the function, either a function
* pointer or a member function pointer.
* \param arguments the list of arguments of this function, used for
* defining default parameters (optional)
* \return *this
*/
template<typename Func_T>
Derived_T & define_method(
Identifier name,
Func_T func,
Arguments* arguments = 0);
// FIXME There's GOT to be a better way to
// do this. Handles the case where there is a single
// argument defined for this method
template<typename Func_T>
Derived_T & define_method(
Identifier name,
Func_T func,
Arg const& arg);
//! Define a singleton method.
/*! The method's implementation can be any function or member
* function. A wrapper will be generated which will use from_ruby<>
* to convert the arguments from ruby types to C++ types before
* calling the function. The return value will be converted back to
* ruby by using to_ruby().
* \param name the name of the method
* \param func the implementation of the function, either a function
* pointer or a member function pointer.
* \param arguments the list of arguments of this function, used for
* defining default parameters (optional)
* \return *this
*/
template<typename Func_T>
Derived_T & define_singleton_method(
Identifier name,
Func_T func,
Arguments* arguments = 0);
// FIXME: See define_method with Arg above
template<typename Func_T>
Derived_T & define_singleton_method(
Identifier name,
Func_T func,
Arg const& arg);
//! Define a module function.
/*! A module function is a function that can be accessed either as a
* singleton method or as an instance method.
* The method's implementation can be any function or member
* function. A wrapper will be generated which will use from_ruby<>
* to convert the arguments from ruby types to C++ types before
* calling the function. The return value will be converted back to
* ruby by using to_ruby().
* \param name the name of the method
* \param func the implementation of the function, either a function
* pointer or a member function pointer.
* \param arguments the list of arguments of this function, used for
* defining default parameters (optional)
* \return *this
*/
template<typename Func_T>
Derived_T & define_module_function(
Identifier name,
Func_T func,
Arguments* arguments = 0);
// FIXME: See define_method with Arg above
template<typename Func_T>
Derived_T & define_module_function(
Identifier name,
Func_T func,
Arg const& arg);
//! Define an iterator.
/*! Essentially this is a conversion from a C++-style begin/end
* iterator to a Ruby-style \#each iterator.
* \param begin a member function pointer to a function that returns
* an iterator to the beginning of the sequence.
* \param end a member function pointer to a function that returns an
* iterator to the end of the sequence.
* \param name the name of the iterator.
* \return *this
*/
template<typename T, typename Iterator_T>
Derived_T & define_iterator(
Iterator_T (T::*begin)(),
Iterator_T (T::*end)(),
Identifier name = "each");
//! Include a module.
/*! \param inc the module to be included.
* \return *this
*/
Derived_T & include_module(
Module const & inc);
//! Set a constant.
/*! \param name the name of the constant to set.
* \param value the value of the constant.
* \return *this
*/
Derived_T & const_set(
Identifier name,
Object value);
//! Get a constant.
/*! \param name the name of the constant to get.
* \return the value of the constant.
*/
Object const_get(
Identifier name) const;
//! Determine whether a constant is defined.
/*! \param name the name of the constant to check.
* \return true if the constant is defined in this module or false
* otherwise.
*/
bool const_defined(
Identifier name) const;
//! Remove a constant.
/*! \param name the name of the constant to remove.
*/
void remove_const(
Identifier name);
//! Define a module under this module.
/*! \param name the name of the module.
* \return the new class.
*/
Module define_module(
char const * name);
//! Define a class under this module.
/*! \param name the name of the class.
* \param superclass the base class to use.
* \return the new class.
*/
Class define_class(
char const * name,
Object superclass = rb_cObject);
//! Define a new data class under this module.
/*! The class will have a base class of Object.
* \param T the C++ type of the wrapped class.
* \return the new class.
*/
// This function needs to be defined inline to work around a bug in
// g++ 3.3.3.
template<typename T>
Data_Type<T>
define_class(
char const * name)
{
return this->define_class_with_object_as_base<T>(name);
}
//! Define a new data class under this module.
/*! The class with have a base class determined by Base_T (specifically,
* Data_Type<Base_T>::klass). Therefore, the type Base_T must already
* have been registered using define_class<> or define_class_under<>.
* \param T the C++ type of the wrapped class.
* \return the new class.
*/
template<typename T, typename T_Base_T>
Data_Type<T>
define_class(
char const * name);
private:
// Workaround for g++ 3.3.3 (see above).
template<typename T>
Data_Type<T>
define_class_with_object_as_base(
char const * name);
};
} // namespace Rice
#endif // Rice__Module_impl__hpp_
| 30.276596
| 74
| 0.680019
|
keyme
|
fd4a3bd9ab75254289366033aa26498457f6d242
| 12,986
|
cpp
|
C++
|
src/network/Transistor.cpp
|
aboelmakarem/casena
|
387c83a1bc6a5150684f5d54f8eba4712b81f827
|
[
"MIT"
] | null | null | null |
src/network/Transistor.cpp
|
aboelmakarem/casena
|
387c83a1bc6a5150684f5d54f8eba4712b81f827
|
[
"MIT"
] | null | null | null |
src/network/Transistor.cpp
|
aboelmakarem/casena
|
387c83a1bc6a5150684f5d54f8eba4712b81f827
|
[
"MIT"
] | null | null | null |
// Transistor.cpp
// Ahmed M. Hussein (amhussein4@gmail.com)
// 03/28/2021
#include "Transistor.h"
#include "Network.h"
#include "string.h"
#include "stdlib.h"
#include "math.h"
namespace CASENA
{
Transistor::Transistor(){Initialize();}
Transistor::Transistor(const Transistor& transistor) : Component(transistor){*this = transistor;}
Transistor::~Transistor(){Reset();}
Transistor& Transistor::operator=(const Transistor& transistor)
{
Component::operator=(transistor);
return *this;
}
void Transistor::Reset()
{
Initialize();
Component::Reset();
}
bool Transistor::IsTransistor(const char* line)
{
if(strncmp(line,"mosfet",6) == 0) return true;
if(strncmp(line,"bjt",3) == 0) return true;
return false;
}
unsigned int Transistor::ReadMaxNodeID(const char* line)
{
EZ::String line_string(line);
EZ::List<EZ::String*> tokens;
line_string.Tokenize(tokens," \t");
// read component type
EZ::ListItem<EZ::String*>* token = tokens.Start();
delete token->Data();
tokens.PopFront();
// read component name
token = tokens.Start();
delete token->Data();
tokens.PopFront();
// read node IDs
token = tokens.Start();
unsigned int node1_id = atoi((*(token->Data()))());
delete token->Data();
tokens.PopFront();
token = tokens.Start();
unsigned int node2_id = atoi((*(token->Data()))());
delete token->Data();
tokens.PopFront();
token = tokens.Start();
unsigned int node3_id = atoi((*(token->Data()))());
delete token->Data();
tokens.PopFront();
unsigned int node4_id = 0;
if(strncmp(line,"mosfet",6) == 0)
{
// This is a MOSFET, read the 4th node ID
token = tokens.Start();
node4_id = atoi((*(token->Data()))());
delete token->Data();
tokens.PopFront();
}
for(EZ::ListItem<EZ::String*>* item = tokens.Start() ; item != 0 ; item = item->Next())
{
delete item->Data();
}
tokens.Reset();
unsigned int max_node_id = (node1_id > node2_id ? node1_id:node2_id);
max_node_id = (max_node_id > node3_id ? max_node_id:node3_id);
max_node_id = (max_node_id > node4_id ? max_node_id:node4_id);
return max_node_id;
}
unsigned int Transistor::BranchCount(const char* line)
{
if(strncmp(line,"mosfet",6) == 0) return MOSFET::CurrentCount();
if(strncmp(line,"bjt",3) == 0) return BJT::CurrentCount();
return 0;
}
Component* Transistor::Create(const char* line)
{
if(strncmp(line,"mosfet",6) == 0) return new MOSFET;
if(strncmp(line,"bjt",3) == 0) return new BJT;
return 0;
}
bool Transistor::Read(const char* line)
{
EZ::String line_string(line);
EZ::List<EZ::String*> tokens;
line_string.Tokenize(tokens," \t");
// read component type
EZ::ListItem<EZ::String*>* token = tokens.Start();
delete token->Data();
tokens.PopFront();
// read component name
token = tokens.Start();
Name(*(token->Data()));
delete token->Data();
tokens.PopFront();
// read the rest of the string and pass it to properties reader
printf("passing transistor RP\n");
bool read_properties = ReadProperties(&tokens);
if(!read_properties)
{
printf("error: incorrect definition for transistor %s\n",Name()());
}
for(EZ::ListItem<EZ::String*>* item = tokens.Start() ; item != 0 ; item = item->Next())
{
delete item->Data();
}
tokens.Reset();
return read_properties;
}
void Transistor::Initialize(){}
MOSFET::MOSFET(){Initialize();}
MOSFET::MOSFET(const MOSFET& transistor) : Transistor(transistor){*this = transistor;}
MOSFET::~MOSFET(){Reset();}
MOSFET& MOSFET::operator=(const MOSFET& transistor)
{
Transistor::operator=(transistor);
gate_node_id = transistor.gate_node_id;
source_node_id = transistor.source_node_id;
drain_node_id = transistor.drain_node_id;
body_node_id = transistor.body_node_id;
np_type = transistor.np_type;
threshold_voltage = transistor.threshold_voltage;
early_voltage = transistor.early_voltage;
mu = transistor.mu;
cox = transistor.cox;
w = transistor.w;
l = transistor.l;
gamma = transistor.gamma;
phi = transistor.phi;
memcpy(currents,transistor.currents,HistoryCount*MOSFET_CURRENT_COUNT*sizeof(double));
return *this;
}
void MOSFET::Reset()
{
Initialize();
Transistor::Reset();
}
unsigned int MOSFET::ClaimIDs(const unsigned int& start_id)
{
// a MOSFET owns 4 branches with the following IDs in order
// gate branch: id
// drain branch: id + 1
// source branch: id + 2
// body branch: id + 3
ID(start_id);
return (start_id + MOSFET_CURRENT_COUNT);
}
void MOSFET::Equation(EZ::Math::Matrix& f) const
{
unsigned int id = ID();
// convention: all currents are flowing into the transistor (gate,
// drain, source, body)
if(Network::SteadyState())
{
// for steady state operation, gate and body currents
// are zero and source current is equal to drain current
// but in an opposite direction
double i_drain = SteadyStateDrainCurrent();
f(drain_node_id,0,f(drain_node_id,0) + i_drain);
f(source_node_id,0,f(source_node_id,0) - i_drain);
f(id,0,0.0);
f(id + 1,0,currents[HistoryCount] - i_drain);
// source current is the same as drain current but with an
// opposite sign
f(id + 2,0,currents[2*HistoryCount] + i_drain);
f(id + 3,0,0.0);
}
else
{
//TransientCurrents(i_gate,i_drain,i_source,i_body);
}
}
void MOSFET::Gradients(EZ::Math::Matrix& A) const
{
unsigned int id = ID();
if(Network::SteadyState())
{
A(drain_node_id,id + 1,1.0);
A(source_node_id,id + 2,1.0);
// gate branch equation: ig = 0
A(id,id,1.0);
// drain branch equation: is = -id or is + id = 0
A(id + 1,id + 1,1.0);
double vg_grad = 0.0;
double vd_grad = 0.0;
double vs_grad = 0.0;
double vb_grad = 0.0;
SteadyStateDrainCurrentGradients(vg_grad,vd_grad,vs_grad,vb_grad);
A(id + 1,gate_node_id,-vg_grad);
A(id + 1,drain_node_id,-vd_grad);
A(id + 1,source_node_id,-vs_grad);
A(id + 1,body_node_id,-vb_grad);
// source branch equation: is = -id or is + id = 0
A(id + 2,id + 1,1.0);
A(id + 2,id + 2,1.0);
// body branch equation: ib = 0
A(id + 3,id + 3,1.0);
}
else
{
}
}
void MOSFET::Update(const EZ::Math::Matrix& x,const unsigned int& id_offset)
{
unsigned int id = ID() - id_offset;
unsigned int target_index = 0;
unsigned int source_index = 0;
for(unsigned int i = HistoryCount - 1 ; i > 0 ; i--)
{
target_index = i*MOSFET_CURRENT_COUNT;
source_index = (i - 1)*MOSFET_CURRENT_COUNT;
memcpy(¤ts[target_index],¤ts[source_index],MOSFET_CURRENT_COUNT*sizeof(double));
}
currents[0] = x(id,0);
currents[1] = x(id + 1,0);
currents[2] = x(id + 2,0);
currents[3] = x(id + 3,0);
}
void MOSFET::Print() const
{
if(np_type == 1) printf("nmos %s\n",Name()());
else if(np_type == 2) printf("pmos %s\n",Name()());
printf("\tnodes (G/D/S/B): %u,%u,%u,%u\n",gate_node_id,drain_node_id,source_node_id,body_node_id);
printf("\tthreshold voltage = %e, Early voltage = %e\n",threshold_voltage,early_voltage);
printf("\tW = %e, L = %e, Cox = %e, mu = %e\n",w,l,cox,mu);
printf("\tgamma = %e, phi = %e\n",gamma,phi);
}
unsigned int MOSFET::CurrentCount(){return MOSFET_CURRENT_COUNT;}
void MOSFET::Initialize()
{
gate_node_id = 0;
source_node_id = 0;
drain_node_id = 0;
body_node_id = 0;
np_type = 1;
threshold_voltage = 0.0;
early_voltage = 0.0;
mu = 0.0;
cox = 0.0;
w = 0.0;
l = 0.0;
gamma = 0.0;
phi = 0.0;
memset(currents,0,HistoryCount*MOSFET_CURRENT_COUNT*sizeof(double));
}
bool MOSFET::ReadProperties(const EZ::List<EZ::String*>* line_tokens)
{
if(line_tokens->Size() != 13) return false;
EZ::ListItem<EZ::String*>* token = line_tokens->Start();
np_type = atoi((*(token->Data()))());
token = token->Next();
gate_node_id = atoi((*(token->Data()))());
token = token->Next();
drain_node_id = atoi((*(token->Data()))());
token = token->Next();
source_node_id = atoi((*(token->Data()))());
token = token->Next();
body_node_id = atoi((*(token->Data()))());
token = token->Next();
threshold_voltage = atof((*(token->Data()))());
token = token->Next();
early_voltage = atof((*(token->Data()))());
token = token->Next();
mu = atof((*(token->Data()))());
token = token->Next();
cox = atof((*(token->Data()))());
token = token->Next();
w = atof((*(token->Data()))());
token = token->Next();
l = atof((*(token->Data()))());
token = token->Next();
gamma = atof((*(token->Data()))());
token = token->Next();
phi = atof((*(token->Data()))());
return true;
}
double MOSFET::SteadyStateDrainCurrent() const
{
Network* network = Network::GetNetwork();
// node voltages
double vg = network->GetNode(gate_node_id)->Voltage();
double vd = network->GetNode(drain_node_id)->Voltage();
double vs = network->GetNode(source_node_id)->Voltage();
double vb = network->GetNode(body_node_id)->Voltage();
double vt = threshold_voltage + gamma*(sqrt(2.0*phi + fabs(vs - vb)) - sqrt(2.0*phi));
double vgs = vg - vs;
double vds = vd - vs;
double vov = vgs - vt;
// operation modes:
// 0: cut-off
// 1: triode region
// 2: saturation
int mode = -1;
double factor = mu*cox*w/l;
if(np_type == 1)
{
// NMOS transistor
if(vov < 0.0) mode = 0;
else
{
if(vds >= vov) mode = 2;
else mode = 1;
}
}
else if(np_type == 2)
{
// PMOS transistor
if(vov > 0.0) mode = 0;
else
{
if(vds <= vov) mode = 2;
else mode = 1;
}
factor = -factor;
}
if(mode < 1) return 0.0;
if(mode == 1) return (factor*(vov*vds - 0.5*vds*vds));
if(mode == 2) return (0.5*factor*vov*vov*(1.0 + vds/early_voltage));
return 0.0;
}
void MOSFET::TransientCurrents(double& i_gate,double& i_drain,double& i_source,double& i_body) const
{
// fix this
i_gate = 0.0;
i_body = 0.0;
i_drain = 0.0;
i_source = i_drain;
}
void MOSFET::SteadyStateDrainCurrentGradients(double& vg_grad,double& vd_grad,double& vs_grad,double& vb_grad) const
{
vg_grad = 0.0;
vd_grad = 0.0;
vs_grad = 0.0;
vb_grad = 0.0;
Network* network = Network::GetNetwork();
// node voltages
double vg = network->GetNode(gate_node_id)->Voltage();
double vd = network->GetNode(drain_node_id)->Voltage();
double vs = network->GetNode(source_node_id)->Voltage();
double vb = network->GetNode(body_node_id)->Voltage();
double sqrt_term = sqrt(2.0*phi + fabs(vs - vb));
double vt = threshold_voltage + gamma*(sqrt_term - sqrt(2.0*phi));
double dvtdvs = 0.5*gamma/sqrt_term;
if(vs < vb) dvtdvs = -dvtdvs;
double dvtdvb = -dvtdvs;
double vgs = vg - vs;
double vds = vd - vs;
double vov = vgs - vt;
// operation modes:
// 0: cut-off
// 1: triode region
// 2: saturation
int mode = -1;
double factor = mu*cox*w/l;
if(np_type == 1)
{
// NMOS transistor
if(vov < 0.0) mode = 0;
else
{
if(vds >= vov) mode = 2;
else mode = 1;
}
}
else if(np_type == 2)
{
// PMOS transistor
if(vov > 0.0) mode = 0;
else
{
if(vds <= vov) mode = 2;
else mode = 1;
}
factor = -factor;
}
if(mode < 1) return;
if(mode == 1)
{
// triode mode operation
vg_grad = factor*vds;
vd_grad = factor*(vov - vds);
vs_grad = -factor*(vov + vds*dvtdvs);
vb_grad = -factor*vds*dvtdvb;
}
if(mode == 2)
{
// saturation mode operation
vg_grad = factor*vov*(1.0 + vds/early_voltage);
vd_grad = 0.5*factor*vov*vov*(1.0/early_voltage);
vs_grad = -factor*vov*((1.0 + vds/early_voltage)*(1.0 + dvtdvs) + 0.5*vov*(1.0/early_voltage));
vb_grad = -factor*vov*(1.0 + vds/early_voltage)*dvtdvb;
}
}
BJT::BJT(){Initialize();}
BJT::BJT(const BJT& transistor) : Transistor(transistor){*this = transistor;}
BJT::~BJT(){Reset();}
BJT& BJT::operator=(const BJT& transistor)
{
Transistor::operator=(transistor);
base_node_id = transistor.base_node_id;
emitter_node_id = transistor.emitter_node_id;
collector_node_id = transistor.collector_node_id;
np_type = transistor.np_type;
memcpy(currents,transistor.currents,HistoryCount*BJT_CURRENT_COUNT*sizeof(double));
return *this;
}
void BJT::Reset()
{
Initialize();
Transistor::Reset();
}
unsigned int BJT::ClaimIDs(const unsigned int& start_id)
{
// a BJT owns 3 branches with the following IDs in order
// base branch: id
// emitter branch: id + 1
// collector branch: id + 2
ID(start_id);
return (start_id + BJT_CURRENT_COUNT);
}
void BJT::Equation(EZ::Math::Matrix& f) const
{
}
void BJT::Gradients(EZ::Math::Matrix& A) const
{
}
void BJT::Update(const EZ::Math::Matrix& x,const unsigned int& id_offset)
{
}
void BJT::Print() const
{
}
unsigned int BJT::CurrentCount(){return BJT_CURRENT_COUNT;}
void BJT::Initialize()
{
np_type = 0;
base_node_id = 0;
emitter_node_id = 0;
collector_node_id = 0;
memset(currents,0,HistoryCount*BJT_CURRENT_COUNT*sizeof(double));
}
bool BJT::ReadProperties(const EZ::List<EZ::String*>* line_tokens)
{
}
}
| 28.047516
| 117
| 0.640459
|
aboelmakarem
|
fd4c91f98ea28c4add132325644b39f218c16a34
| 19,368
|
hpp
|
C++
|
include/System/Data/Constraint.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/System/Data/Constraint.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/System/Data/Constraint.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | 1
|
2022-03-30T21:07:35.000Z
|
2022-03-30T21:07:35.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Data
namespace System::Data {
// Forward declaring type: DataSet
class DataSet;
// Forward declaring type: PropertyCollection
class PropertyCollection;
// Forward declaring type: DataTable
class DataTable;
// Forward declaring type: DataColumn
class DataColumn;
// Forward declaring type: ConstraintCollection
class ConstraintCollection;
// Forward declaring type: DataRow
class DataRow;
// Forward declaring type: DataRowAction
struct DataRowAction;
}
// Completed forward declares
// Type namespace: System.Data
namespace System::Data {
// Forward declaring type: Constraint
class Constraint;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Data::Constraint);
DEFINE_IL2CPP_ARG_TYPE(::System::Data::Constraint*, "System.Data", "Constraint");
// Type namespace: System.Data
namespace System::Data {
// Size: 0x38
#pragma pack(push, 1)
// Autogenerated type: System.Data.Constraint
// [TokenAttribute] Offset: FFFFFFFF
// [TypeConverterAttribute] Offset: 6B9D94
// [DefaultPropertyAttribute] Offset: 6B9D94
class Constraint : public ::Il2CppObject {
public:
public:
// private System.String _schemaName
// Size: 0x8
// Offset: 0x10
::StringW schemaName;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private System.Boolean _inCollection
// Size: 0x1
// Offset: 0x18
bool inCollection;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: inCollection and: dataSet
char __padding1[0x7] = {};
// private System.Data.DataSet _dataSet
// Size: 0x8
// Offset: 0x20
::System::Data::DataSet* dataSet;
// Field size check
static_assert(sizeof(::System::Data::DataSet*) == 0x8);
// System.String _name
// Size: 0x8
// Offset: 0x28
::StringW name;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// System.Data.PropertyCollection _extendedProperties
// Size: 0x8
// Offset: 0x30
::System::Data::PropertyCollection* extendedProperties;
// Field size check
static_assert(sizeof(::System::Data::PropertyCollection*) == 0x8);
public:
// Get instance field reference: private System.String _schemaName
[[deprecated("Use field access instead!")]] ::StringW& dyn__schemaName();
// Get instance field reference: private System.Boolean _inCollection
[[deprecated("Use field access instead!")]] bool& dyn__inCollection();
// Get instance field reference: private System.Data.DataSet _dataSet
[[deprecated("Use field access instead!")]] ::System::Data::DataSet*& dyn__dataSet();
// Get instance field reference: System.String _name
[[deprecated("Use field access instead!")]] ::StringW& dyn__name();
// Get instance field reference: System.Data.PropertyCollection _extendedProperties
[[deprecated("Use field access instead!")]] ::System::Data::PropertyCollection*& dyn__extendedProperties();
// public System.String get_ConstraintName()
// Offset: 0x14B1E64
::StringW get_ConstraintName();
// public System.Void set_ConstraintName(System.String value)
// Offset: 0x14B1E6C
void set_ConstraintName(::StringW value);
// System.String get_SchemaName()
// Offset: 0x14B22FC
::StringW get_SchemaName();
// System.Void set_SchemaName(System.String value)
// Offset: 0x14B2344
void set_SchemaName(::StringW value);
// System.Boolean get_InCollection()
// Offset: 0x14B2378
bool get_InCollection();
// System.Void set_InCollection(System.Boolean value)
// Offset: 0x14B2380
void set_InCollection(bool value);
// public System.Data.DataTable get_Table()
// Offset: 0xFFFFFFFFFFFFFFFF
::System::Data::DataTable* get_Table();
// public System.Data.PropertyCollection get_ExtendedProperties()
// Offset: 0x14B23D0
::System::Data::PropertyCollection* get_ExtendedProperties();
// protected System.Data.DataSet get__DataSet()
// Offset: 0x14B25B0
::System::Data::DataSet* get__DataSet();
// protected System.Void .ctor()
// Offset: 0x14B25C4
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static Constraint* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<Constraint*, creationType>()));
}
// System.Boolean ContainsColumn(System.Data.DataColumn column)
// Offset: 0xFFFFFFFFFFFFFFFF
bool ContainsColumn(::System::Data::DataColumn* column);
// System.Boolean CanEnableConstraint()
// Offset: 0xFFFFFFFFFFFFFFFF
bool CanEnableConstraint();
// System.Data.Constraint Clone(System.Data.DataSet destination)
// Offset: 0xFFFFFFFFFFFFFFFF
::System::Data::Constraint* Clone(::System::Data::DataSet* destination);
// System.Data.Constraint Clone(System.Data.DataSet destination, System.Boolean ignoreNSforTableLookup)
// Offset: 0xFFFFFFFFFFFFFFFF
::System::Data::Constraint* Clone(::System::Data::DataSet* destination, bool ignoreNSforTableLookup);
// System.Void CheckConstraint()
// Offset: 0x14B2438
void CheckConstraint();
// System.Void CheckCanAddToCollection(System.Data.ConstraintCollection constraint)
// Offset: 0xFFFFFFFFFFFFFFFF
void CheckCanAddToCollection(::System::Data::ConstraintCollection* constraint);
// System.Boolean CanBeRemovedFromCollection(System.Data.ConstraintCollection constraint, System.Boolean fThrowException)
// Offset: 0xFFFFFFFFFFFFFFFF
bool CanBeRemovedFromCollection(::System::Data::ConstraintCollection* constraint, bool fThrowException);
// System.Void CheckConstraint(System.Data.DataRow row, System.Data.DataRowAction action)
// Offset: 0xFFFFFFFFFFFFFFFF
void CheckConstraint(::System::Data::DataRow* row, ::System::Data::DataRowAction action);
// System.Void CheckState()
// Offset: 0xFFFFFFFFFFFFFFFF
void CheckState();
// protected System.Void CheckStateForProperty()
// Offset: 0x14B2498
void CheckStateForProperty();
// System.Boolean IsConstraintViolated()
// Offset: 0xFFFFFFFFFFFFFFFF
bool IsConstraintViolated();
// public override System.String ToString()
// Offset: 0x14B25B8
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::StringW ToString();
}; // System.Data.Constraint
#pragma pack(pop)
static check_size<sizeof(Constraint), 48 + sizeof(::System::Data::PropertyCollection*)> __System_Data_ConstraintSizeCheck;
static_assert(sizeof(Constraint) == 0x38);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Data::Constraint::get_ConstraintName
// Il2CppName: get_ConstraintName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Data::Constraint::*)()>(&System::Data::Constraint::get_ConstraintName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "get_ConstraintName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::set_ConstraintName
// Il2CppName: set_ConstraintName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)(::StringW)>(&System::Data::Constraint::set_ConstraintName)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "set_ConstraintName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::get_SchemaName
// Il2CppName: get_SchemaName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Data::Constraint::*)()>(&System::Data::Constraint::get_SchemaName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "get_SchemaName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::set_SchemaName
// Il2CppName: set_SchemaName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)(::StringW)>(&System::Data::Constraint::set_SchemaName)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "set_SchemaName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::get_InCollection
// Il2CppName: get_InCollection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Data::Constraint::*)()>(&System::Data::Constraint::get_InCollection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "get_InCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::set_InCollection
// Il2CppName: set_InCollection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)(bool)>(&System::Data::Constraint::set_InCollection)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "set_InCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::get_Table
// Il2CppName: get_Table
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Data::DataTable* (System::Data::Constraint::*)()>(&System::Data::Constraint::get_Table)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "get_Table", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::get_ExtendedProperties
// Il2CppName: get_ExtendedProperties
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Data::PropertyCollection* (System::Data::Constraint::*)()>(&System::Data::Constraint::get_ExtendedProperties)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "get_ExtendedProperties", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::get__DataSet
// Il2CppName: get__DataSet
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Data::DataSet* (System::Data::Constraint::*)()>(&System::Data::Constraint::get__DataSet)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "get__DataSet", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Data::Constraint::ContainsColumn
// Il2CppName: ContainsColumn
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Data::Constraint::*)(::System::Data::DataColumn*)>(&System::Data::Constraint::ContainsColumn)> {
static const MethodInfo* get() {
static auto* column = &::il2cpp_utils::GetClassFromName("System.Data", "DataColumn")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "ContainsColumn", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{column});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::CanEnableConstraint
// Il2CppName: CanEnableConstraint
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Data::Constraint::*)()>(&System::Data::Constraint::CanEnableConstraint)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "CanEnableConstraint", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::Clone
// Il2CppName: Clone
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Data::Constraint* (System::Data::Constraint::*)(::System::Data::DataSet*)>(&System::Data::Constraint::Clone)> {
static const MethodInfo* get() {
static auto* destination = &::il2cpp_utils::GetClassFromName("System.Data", "DataSet")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "Clone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{destination});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::Clone
// Il2CppName: Clone
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Data::Constraint* (System::Data::Constraint::*)(::System::Data::DataSet*, bool)>(&System::Data::Constraint::Clone)> {
static const MethodInfo* get() {
static auto* destination = &::il2cpp_utils::GetClassFromName("System.Data", "DataSet")->byval_arg;
static auto* ignoreNSforTableLookup = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "Clone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{destination, ignoreNSforTableLookup});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::CheckConstraint
// Il2CppName: CheckConstraint
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)()>(&System::Data::Constraint::CheckConstraint)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "CheckConstraint", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::CheckCanAddToCollection
// Il2CppName: CheckCanAddToCollection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)(::System::Data::ConstraintCollection*)>(&System::Data::Constraint::CheckCanAddToCollection)> {
static const MethodInfo* get() {
static auto* constraint = &::il2cpp_utils::GetClassFromName("System.Data", "ConstraintCollection")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "CheckCanAddToCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{constraint});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::CanBeRemovedFromCollection
// Il2CppName: CanBeRemovedFromCollection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Data::Constraint::*)(::System::Data::ConstraintCollection*, bool)>(&System::Data::Constraint::CanBeRemovedFromCollection)> {
static const MethodInfo* get() {
static auto* constraint = &::il2cpp_utils::GetClassFromName("System.Data", "ConstraintCollection")->byval_arg;
static auto* fThrowException = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "CanBeRemovedFromCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{constraint, fThrowException});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::CheckConstraint
// Il2CppName: CheckConstraint
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)(::System::Data::DataRow*, ::System::Data::DataRowAction)>(&System::Data::Constraint::CheckConstraint)> {
static const MethodInfo* get() {
static auto* row = &::il2cpp_utils::GetClassFromName("System.Data", "DataRow")->byval_arg;
static auto* action = &::il2cpp_utils::GetClassFromName("System.Data", "DataRowAction")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "CheckConstraint", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{row, action});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::CheckState
// Il2CppName: CheckState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)()>(&System::Data::Constraint::CheckState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "CheckState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::CheckStateForProperty
// Il2CppName: CheckStateForProperty
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Data::Constraint::*)()>(&System::Data::Constraint::CheckStateForProperty)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "CheckStateForProperty", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::IsConstraintViolated
// Il2CppName: IsConstraintViolated
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Data::Constraint::*)()>(&System::Data::Constraint::IsConstraintViolated)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "IsConstraintViolated", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Data::Constraint::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Data::Constraint::*)()>(&System::Data::Constraint::ToString)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Data::Constraint*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 54.252101
| 208
| 0.733891
|
v0idp
|
fd521e016f2c274edc4805578b097ad0bde9013e
| 8,177
|
cpp
|
C++
|
src/reconstruct/characteristic_cl.cpp
|
roarkhabegger/athena-public-version
|
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
|
[
"BSD-3-Clause"
] | 1
|
2021-03-05T20:59:04.000Z
|
2021-03-05T20:59:04.000Z
|
src/reconstruct/characteristic_cl.cpp
|
roarkhabegger/athena-public-version
|
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
|
[
"BSD-3-Clause"
] | null | null | null |
src/reconstruct/characteristic_cl.cpp
|
roarkhabegger/athena-public-version
|
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
|
[
"BSD-3-Clause"
] | 2
|
2019-02-26T18:49:13.000Z
|
2019-07-22T17:04:41.000Z
|
//========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file characteristic.cpp
// \brief Functions to transform vectors between primitive and characteristic variables
// C++ headers
#include <cmath>
// Athena++ headers
#include "reconstruction.hpp"
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../mesh/mesh.hpp"
#include "../eos/eos.hpp"
//----------------------------------------------------------------------------------------
//! \fn Reconstruction::LeftEigenmatrixDotVectorCL()
// \brief Computes inner-product of left-eigenmatrix of Roe's matrix A in the primitive
// variables and an input vector. This operation converts primitive to characteristic
// variables. The result is returned in the input vector, with the components of the
// characteristic field stored such that vect(1,i) is in the direction of the sweep.
//
// The order of the components in the input vector should be:
// (IDN,IVX,IVY,IVZ,IP11,IP22,IP33,IP12,IP13,IP23)
// and these are permuted according to the direction specified by the input flag "ivx".
//
// REFERENCES:
// - J. Stone, T. Gardiner, P. Teuben, J. Hawley, & J. Simon "Athena: A new code for
// astrophysical MHD", ApJS, (2008), Appendix A. Equation numbers refer to this paper.
// - S. Brown, (1996), PhD thesis
// - N.L. Mitchell, E.I. Vorobyov, and G. Hensler, "Collisionless stellar hydrodynamics as
// an efficient alternative to N-body methods", MNRAS 428, 2674-2687 (2013)
void Reconstruction::LeftEigenmatrixDotVectorCL(MeshBlock *pmb, const int ivx,
const int ip12, const int il, const int iu, const AthenaArray<Real> &w,
AthenaArray<Real> &vect) {
// permute components of input primitive vector depending on direction
int ivy = IVX + ((ivx -IVX )+1)%3;
int ivz = IVX + ((ivx -IVX )+2)%3;
// diagnol comp
int ip11 = IP11 + ((ivx -IVX ) )%3;
int ip22 = IP11 + ((ivx -IVX )+1)%3;
int ip33 = IP11 + ((ivx -IVX )+2)%3;
// off-diag comp
int ip13 = IP12 + ((ip12-IP12)+1)%3;
int ip23 = IP12 + ((ip12-IP12)+2)%3;
#pragma omp simd
for (int i=il; i<=iu; ++i) {
Real asq = w(ip11,i)/w(IDN,i);
Real d = w(IDN,i);
Real a = std::sqrt(asq);
Real sqt3 = std::sqrt(3.0);
Real sqt3a = sqt3*a;
Real inva = 1.0/a;
Real invasq = 1.0/asq;
Real dsq = SQR(d);
Real invd = 1.0/d;
Real invdsq = 1.0/dsq;
Real P11 = w(ip11, i);
Real P22 = w(ip22, i);
Real P33 = w(ip33, i);
Real P12 = w(ip12, i);
Real P13 = w(ip13, i);
Real P23 = w(ip23, i);
// Multiply row of L-eigenmatrix with vector using matrix elements
Real v_0 = -0.5*(invd/sqt3a)*vect(ivx,i) + (invasq*invdsq/6.0) * vect(ip11,i);
Real v_1 = 0.5*P12*inva*invd*vect(ivx,i) - 0.5*a*vect(ivy,i)
- 0.5*P12*invasq*invdsq*vect(ip11,i) + 0.5*invd*vect(ip12,i);
Real v_2 = 0.5*P13*inva*invd*vect(ivx,i) - 0.5*a*vect(ivz,0)
- 0.5*P13*invasq*invdsq*vect(ip11,i) + 0.5*invd*vect(ip13,i);
Real v_3 = invdsq*vect(IDN,i) - (invasq*invdsq/3.0) * vect(ip11,i);
Real v_4 = (4.0*SQR(P12)-asq*P22*d)*invdsq*vect(IDN,i) + asq*vect(ip22,i)
- 2.0*P12*invd*vect(ip12,i);
Real v_5 = (4.0*SQR(P13)-asq*P33*d)*invdsq*vect(IDN,i) + asq*vect(ip33,i)
- 2.0*P13*invd*vect(ip13,i);
Real v_6 = (4.0*P12*P13-asq*P23*d)*invdsq*vect(IDN,i) - P13*invd*vect(ip12,i)
- P13*invd*vect(ip13,i) + asq*vect(ip23,i);
Real v_7 = -0.5*P13*inva*invd*vect(ivx,i) + 0.5*a*vect(ivz,i)
- 0.5*P13*invasq*invdsq*vect(ip11,i) + 0.5*invd*vect(ip13,i);
Real v_8 = -0.5*P12*inva*invd*vect(ivx,i) + 0.5*a*vect(2,i)
- 0.5*P12*invasq*invdsq*vect(ip11,i) + 0.5*invd*vect(ip12,i);
Real v_9 = 0.5*(invd/sqt3a)*vect(ivx,i) + (invasq*invdsq/6.0) * vect(ip11,i);
// Permute components back into standard order for primitives on output
vect(0,i) = v_0;
vect(1,i) = v_1;
vect(2,i) = v_2;
vect(3,i) = v_3;
vect(4,i) = v_4;
vect(5,i) = v_5;
vect(7,i) = v_6;
vect(7,i) = v_7;
vect(8,i) = v_8;
vect(9,i) = v_9;
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn Reconstruction::RightEigenmatrixDotVectorCL()
// \brief Computes inner-product of right-eigenmatrix of Roe's matrix A in the primitive
// variables and an input vector. This operation converts characteristic to primitive
// variables. The result is returned in the input vector. This is for CLESS variables
//
// The order of the components in the input vector (characteristic fields) should be:
// (IDN,ivx,ivy,ivz,ip11,ip22,ip33,ip12,ip13,ip23)
// where the lower-case indices indicate that the characteristic field in the direction
// of the sweep (designated by the input flag "ivx") is stored first. On output, the
// components of velocity are in the standard order used for primitive variables.
//
// REFERENCES:
// - J. Stone, T. Gardiner, P. Teuben, J. Hawley, & J. Simon "Athena: A new code for
// astrophysical MHD", ApJS, (2008), Appendix A. Equation numbers refer to this paper.
// - S. Brown, (1996), PhD thesis.
void Reconstruction::RightEigenmatrixDotVectorCL(MeshBlock *pmb, const int ivx,
const int ip12, const int il, const int iu, const AthenaArray<Real> &w,
AthenaArray<Real> &vect) {
// permute components of output primitive vector depending on direction
int ivy = IVX + ((ivx -IVX )+1)%3;
int ivz = IVX + ((ivx -IVX )+2)%3;
// diagnol comp
int ip11 = IP11 + ((ivx -IVX ) )%3;
int ip22 = IP11 + ((ivx -IVX )+1)%3;
int ip33 = IP11 + ((ivx -IVX )+2)%3;
// off-diag comp
int ip13 = IP12 + ((ip12-IP12)+1)%3;
int ip23 = IP12 + ((ip12-IP12)+2)%3;
#pragma omp simd
for (int i=il; i<=iu; ++i) {
Real asq = w(ip11,i)/w(IDN,i);
Real d = w(IDN,i);
Real a = std::sqrt(asq);
Real sqt3 = std::sqrt(3.0);
Real sqt3a = sqt3*a;
Real inva = 1.0/a;
Real invasq = 1.0/asq;
Real dsq = SQR(d);
Real invd = 1.0/d;
Real invdsq = 1.0/dsq;
Real P11 = w(ip11, i);
Real P22 = w(ip22, i);
Real P33 = w(ip33, i);
Real P12 = w(ip12, i);
Real P13 = w(ip13, i);
Real P23 = w(ip23, i);
// Multiply row of R-eigenmatrix with vector using matrix elements
// Components of vect() are addressed directly as they are input in permuted order
Real v_0 = dsq*(vect(0,i) + vect(3,i) + vect(9,i));
Real v_1 = -sqt3a*d*vect(0,i) + sqt3a*d*vect(9,i);
Real v_2 = -sqt3*P12*inva*vect(0,i) - inva*vect(1,i) + inva*vect(8,i)
+ sqt3*P12*inva*vect(9,i);
Real v_3 = -sqt3*P13*inva*vect(0,i) - inva*vect(2,i) + inva*vect(7,i)
+ sqt3*P13*inva*vect(9,i);
Real v_4 = 3.0*asq*dsq*(vect(0,i) + vect(9,i));
Real v_5 = (2.0*SQR(P12)+asq*P22*d)*invasq*vect(0,i) + 2.0*P12*invasq*vect(1,i)
+ (asq*P22*d-4.0*SQR(P12))*invasq*vect(3,i) + invasq*vect(4,i)
+ 2.0*P12*invasq*vect(8,i) + (2.0*SQR(P12)+asq*P22*d)*invasq*vect(9,i);
Real v_6 = (2.0*SQR(P13)+asq*P33*d)*invasq*vect(0,i) + 2.0*P13*invasq*vect(2,i)
+ (asq*P33*d-4.0*SQR(P13))*invasq*vect(3,i) + invasq*vect(5,i)
+ 2.0*P13*invasq*vect(7,i) + (2.0*SQR(P13)+asq*P33*d)*invasq*vect(9,i);
Real v_7 = 3.0*P12*d*vect(0,i) + d*(vect(1,i) + vect(8,i)) + 3.0*P12*d*vect(9,i);
Real v_8 = 3.0*P13*d*vect(0,i) + d*(vect(2,i) + vect(7,i)) + 3.0*P13*d*vect(9,i);
Real v_9 = (2.0*P12*P13+asq*P23*d)*invasq*vect(0,i) + P13*invasq*vect(1,i)
+ P12*invasq*vect(2,i) + (asq*P23*d-4.0*P12*P13)*invasq*vect(3,i)
+ invasq*vect(6,i) + P12*invasq*vect(7,i) + P13*invasq*vect(8,i)
+ (2.0*P12*P13+asq*P23*d)*invasq*vect(9,i);
// Permute components back into standard order for primitives on output
vect(IDN ,i) = v_0;
vect(ivx ,i) = v_1;
vect(ivy ,i) = v_2;
vect(ivz ,i) = v_3;
vect(ip11,i) = v_4;
vect(ip22,i) = v_5;
vect(ip33,i) = v_6;
vect(ip12,i) = v_7;
vect(ip13,i) = v_8;
vect(ip23,i) = v_9;
}
return;
}
| 42.367876
| 90
| 0.598997
|
roarkhabegger
|
5b79c9f46b4b9d5bc210a2b039c8b5e652666541
| 2,362
|
cpp
|
C++
|
OpenGL-Sandbox/src/engineUtils/PerspectiveCameraController.cpp
|
MrLucyfer/OpenGL
|
b8a374afec8702742e96300bc45a2a88b806b65e
|
[
"Apache-2.0"
] | null | null | null |
OpenGL-Sandbox/src/engineUtils/PerspectiveCameraController.cpp
|
MrLucyfer/OpenGL
|
b8a374afec8702742e96300bc45a2a88b806b65e
|
[
"Apache-2.0"
] | null | null | null |
OpenGL-Sandbox/src/engineUtils/PerspectiveCameraController.cpp
|
MrLucyfer/OpenGL
|
b8a374afec8702742e96300bc45a2a88b806b65e
|
[
"Apache-2.0"
] | null | null | null |
#include "PerspectiveCameraController.h"
#include <GLCore/Core/Input.h>
#include <GLCore/Core/KeyCodes.h>
#include <GLCore/Core/MouseButtonCodes.h>
using namespace GLCore;
PerspectiveCameraController::PerspectiveCameraController() :
m_CameraPos{ 0.0f, 0.0f, 3.0f }, m_CameraTarget{ 0.0f, 0.0f, 0.0f },
m_Up{ 0.0, 1.0f, 0.0f }, m_CameraFront{ 0.0f, 0.0f, -1.0f }, zoomLevel(1.0f), cameraSpeed(0.01f)
{
m_CameraDirection = m_CameraTarget - m_CameraPos;
m_Camera.Translate(m_CameraDirection);
}
PerspectiveCameraController::~PerspectiveCameraController()
{
}
void PerspectiveCameraController::LookAt() {
glm::mat4 lookAt = glm::lookAt(m_CameraPos, m_CameraPos + m_CameraFront, m_Up);
m_Camera.setView(lookAt);
}
void PerspectiveCameraController::LookAt(glm::vec3 camPos) {
glm::mat4 lookAt = glm::lookAt(camPos, m_CameraTarget, m_Up);
m_Camera.setView(lookAt);
}
void PerspectiveCameraController::setCameraSpeed(const float& speed) {
cameraSpeed = speed;
}
void PerspectiveCameraController::Update(Timestep ts)
{
if (Input::IsKeyPressed(HZ_KEY_W)) {
m_CameraPos += (cameraSpeed * m_CameraFront * ts.GetMilliseconds());
}
if (Input::IsKeyPressed(HZ_KEY_A)) {
m_CameraPos -= (glm::normalize(glm::cross(m_CameraFront, m_Up)) * cameraSpeed * ts.GetMilliseconds());
}
if (Input::IsKeyPressed(HZ_KEY_S)) {
m_CameraPos -= (cameraSpeed * m_CameraFront * ts.GetMilliseconds());
}
if (Input::IsKeyPressed(HZ_KEY_D)) {
m_CameraPos += (glm::normalize(glm::cross(m_CameraFront, m_Up)) * cameraSpeed * ts.GetMilliseconds());
}
if (Input::IsMouseButtonPressed(HZ_MOUSE_BUTTON_2)) {
float actualX = Input::GetMouseX();
float actualY = Input::GetMouseY();
if (!mousePressed) {
lastX = actualX;
lastY = actualY;
mousePressed = true;
}
//Rotate IDK how
float offSetX = (actualX - lastX) * m_MouseSensitivity;
float offSetY = (lastY - actualY) * m_MouseSensitivity;
lastX = actualX;
lastY = actualY;
yaw += offSetX;
pitch += offSetY;
if (pitch > 89.0f)
pitch = 89.0f;
if (pitch < -89.0f)
pitch = -89.0f;
glm::vec3 direction;
direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
direction.y = sin(glm::radians(pitch));
direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
m_CameraFront = glm::normalize(direction);
}
else {
mousePressed = false;
}
LookAt();
}
| 28.457831
| 104
| 0.708721
|
MrLucyfer
|
5b7c9c3683d5c7deb59749bd55f127a72c548d29
| 4,602
|
cpp
|
C++
|
exiv2-0.24/samples/addmoddel.cpp
|
sdrpa/Exiv2Framework
|
76b2dd9a906ab08d39bf97c8f3d97037eb39c69d
|
[
"MIT"
] | 6
|
2016-10-04T10:12:11.000Z
|
2021-09-18T22:37:29.000Z
|
exiv2-0.24/samples/addmoddel.cpp
|
sdrpa/Exiv2Framework
|
76b2dd9a906ab08d39bf97c8f3d97037eb39c69d
|
[
"MIT"
] | null | null | null |
exiv2-0.24/samples/addmoddel.cpp
|
sdrpa/Exiv2Framework
|
76b2dd9a906ab08d39bf97c8f3d97037eb39c69d
|
[
"MIT"
] | 2
|
2018-05-20T08:32:40.000Z
|
2019-07-06T18:27:19.000Z
|
// ***************************************************************** -*- C++ -*-
// addmoddel.cpp, $Rev: 3090 $
// Sample program showing how to add, modify and delete Exif metadata.
#include <exiv2/exiv2.hpp>
#include <iostream>
#include <iomanip>
#include <cassert>
int main(int argc, char* const argv[])
try {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " file\n";
return 1;
}
std::string file(argv[1]);
// Container for exif metadata. This is an example of creating
// exif metadata from scratch. If you want to add, modify, delete
// metadata that exists in an image, start with ImageFactory::open
Exiv2::ExifData exifData;
// *************************************************************************
// Add to the Exif data
// This is the quickest way to add (simple) Exif data. If a metadatum for
// a given key already exists, its value is overwritten. Otherwise a new
// tag is added.
exifData["Exif.Image.Model"] = "Test 1"; // AsciiValue
exifData["Exif.Image.SamplesPerPixel"] = uint16_t(162); // UShortValue
exifData["Exif.Image.XResolution"] = int32_t(-2); // LongValue
exifData["Exif.Image.YResolution"] = Exiv2::Rational(-2, 3); // RationalValue
std::cout << "Added a few tags the quick way.\n";
// Create a ASCII string value (note the use of create)
Exiv2::Value::AutoPtr v = Exiv2::Value::create(Exiv2::asciiString);
// Set the value to a string
v->read("1999:12:31 23:59:59");
// Add the value together with its key to the Exif data container
Exiv2::ExifKey key("Exif.Photo.DateTimeOriginal");
exifData.add(key, v.get());
std::cout << "Added key \"" << key << "\", value \"" << *v << "\"\n";
// Now create a more interesting value (without using the create method)
Exiv2::URationalValue::AutoPtr rv(new Exiv2::URationalValue);
// Set two rational components from a string
rv->read("1/2 1/3");
// Add more elements through the extended interface of rational value
rv->value_.push_back(std::make_pair(2,3));
rv->value_.push_back(std::make_pair(3,4));
// Add the key and value pair to the Exif data
key = Exiv2::ExifKey("Exif.Image.PrimaryChromaticities");
exifData.add(key, rv.get());
std::cout << "Added key \"" << key << "\", value \"" << *rv << "\"\n";
// *************************************************************************
// Modify Exif data
// Since we know that the metadatum exists (or we don't mind creating a new
// tag if it doesn't), we can simply do this:
Exiv2::Exifdatum& tag = exifData["Exif.Photo.DateTimeOriginal"];
std::string date = tag.toString();
date.replace(0, 4, "2000");
tag.setValue(date);
std::cout << "Modified key \"" << key
<< "\", new value \"" << tag.value() << "\"\n";
// Alternatively, we can use findKey()
key = Exiv2::ExifKey("Exif.Image.PrimaryChromaticities");
Exiv2::ExifData::iterator pos = exifData.findKey(key);
if (pos == exifData.end()) throw Exiv2::Error(1, "Key not found");
// Get a pointer to a copy of the value
v = pos->getValue();
// Downcast the Value pointer to its actual type
Exiv2::URationalValue* prv = dynamic_cast<Exiv2::URationalValue*>(v.release());
if (prv == 0) throw Exiv2::Error(1, "Downcast failed");
rv = Exiv2::URationalValue::AutoPtr(prv);
// Modify the value directly through the interface of URationalValue
rv->value_[2] = std::make_pair(88,77);
// Copy the modified value back to the metadatum
pos->setValue(rv.get());
std::cout << "Modified key \"" << key
<< "\", new value \"" << pos->value() << "\"\n";
// *************************************************************************
// Delete metadata from the Exif data container
// Delete the metadatum at iterator position pos
key = Exiv2::ExifKey("Exif.Image.PrimaryChromaticities");
pos = exifData.findKey(key);
if (pos == exifData.end()) throw Exiv2::Error(1, "Key not found");
exifData.erase(pos);
std::cout << "Deleted key \"" << key << "\"\n";
// *************************************************************************
// Finally, write the remaining Exif data to the image file
Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file);
assert(image.get() != 0);
image->setExifData(exifData);
image->writeMetadata();
return 0;
}
catch (Exiv2::AnyError& e) {
std::cout << "Caught Exiv2 exception '" << e << "'\n";
return -1;
}
| 41.836364
| 83
| 0.571491
|
sdrpa
|
5b883c00c547b6ee8e88b87edf2b3fcae104fee8
| 1,998
|
cpp
|
C++
|
src/main.cpp
|
idincern/prm_sim
|
9c576d200eb4576a289dae42ca9c08729aceecd7
|
[
"MIT"
] | 3
|
2020-02-24T22:32:44.000Z
|
2021-05-06T23:13:11.000Z
|
src/main.cpp
|
idincern/prm_sim
|
9c576d200eb4576a289dae42ca9c08729aceecd7
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
idincern/prm_sim
|
9c576d200eb4576a289dae42ca9c08729aceecd7
|
[
"MIT"
] | 2
|
2020-06-12T12:24:22.000Z
|
2021-10-19T11:25:46.000Z
|
/*! @file
*
* @brief Entry point for the prm_sim_node.
*
* A probabilistic roadmap planner is a motion-planning algorithm in robotics,
* which solves the problem of determining a path between a starting and a goal
* configuration of the robot while avoiding collisions.
*
* The basic idea behind PRM is to take random samples from the configuration
* space of the robot, checking if they are in free space, then attempting to
* connect configurations (groups of samples) to other nearby configurations.
*
* When starting the prm_sim_node (using rosrun), the following parameters may
* be specified.
*
* - _map_size:=[size of supplied ogMap in meters]
* - _resolution:=[resolution of the opencv map image]
* - _density:=[max density the prm network can have]
* - _robot_diameter:=the diameter of the robot in meters]
*
* @author arosspope
* @date 23-10-2017
*/
#include "ros/ros.h"
#include "simulator.h"
#include "worldretrieve.h"
#include "types.h"
int main(int argc, char **argv) {
ros::init(argc, argv, "prm_sim_node");
//NodeHandle is the main access point to communications with the ROS system.
ros::NodeHandle nh;
//The WorldDataBuffer is populated by WorldRetrieve, and consumed by Simulator
TWorldDataBuffer buffer;
std::vector<std::thread> threads;
std::shared_ptr<WorldRetrieve> wr(new WorldRetrieve(nh, buffer));
std::shared_ptr<Simulator> sim(new Simulator(nh, buffer));
threads.push_back(std::thread(&Simulator::plannerThread, sim));
threads.push_back(std::thread(&Simulator::overlayThread, sim));
//ros::spin() will enter a loop, pumping callbacks. With this version, all
//callbacks will be called from within this thread (the main one).
//ros::spin() will exit when Ctrl-C is pressed, or the node is shutdown by the master.
ros::spin();
//Let's cleanup everything, shutdown ros and join the threads
ros::shutdown();
//Join threads and begin!
for(auto & t: threads){
t.join();
}
return 0;
}
| 32.225806
| 88
| 0.718719
|
idincern
|
5b8960b98b9589f4ed9c3043ec80ab0cc21163e1
| 1,960
|
cpp
|
C++
|
libs/bloom_filter/example/custom_hash.cpp
|
tetzank/boost-bloom-filters
|
7c6717f403c041a092187568908f3661782ddb24
|
[
"BSL-1.0"
] | 15
|
2016-10-18T16:05:37.000Z
|
2022-01-23T03:01:42.000Z
|
libs/bloom_filter/example/custom_hash.cpp
|
tetzank/boost-bloom-filters
|
7c6717f403c041a092187568908f3661782ddb24
|
[
"BSL-1.0"
] | null | null | null |
libs/bloom_filter/example/custom_hash.cpp
|
tetzank/boost-bloom-filters
|
7c6717f403c041a092187568908f3661782ddb24
|
[
"BSL-1.0"
] | 12
|
2016-04-15T18:17:24.000Z
|
2020-04-16T06:29:58.000Z
|
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Alejandro Cabrera 2011.
// Distributed under the Boost
// Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or
// copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/bloom_filter for documentation.
//
//////////////////////////////////////////////////////////////////////////////
// example demonstrating how to overload default hash function
// in order to support user-defined type
#include <boost/bloom_filter/basic_bloom_filter.hpp>
#include <sstream>
#include <string>
#include <iostream>
using namespace boost::bloom_filters;
using namespace std;
class URL {
public:
URL() : _data() {}
explicit URL(const string& url) : _data(url) {}
const string data() const {
return _data;
}
private:
string _data;
};
// provide an overload for your class
// alternatively, implement own Hasher that can handle your type
namespace boost {
namespace bloom_filters {
template <size_t Seed>
struct boost_hash<URL, Seed> {
size_t operator()(const URL& t) {
return boost::hash_value(t.data()) + Seed;
}
};
}
}
const URL gen_url(const size_t num)
{
static const string start_url("https://www.");
static const string end_url(".com/");
static stringstream stringer;
string result;
stringer << num;
stringer >> result;
stringer.clear();
return URL(start_url + result + end_url);
}
int main () {
static const size_t INSERT_MAX = 5000;
static const size_t CONTAINS_MAX = 10000;
static const size_t NUM_BITS = 32768; // 8KB
basic_bloom_filter<URL, NUM_BITS> bloom;
size_t collisions = 0;
for (size_t i = 0; i < INSERT_MAX; ++i) {
bloom.insert(gen_url(i));
}
for (size_t i = INSERT_MAX; i < CONTAINS_MAX; ++i) {
if (bloom.probably_contains(gen_url(i))) ++collisions;
}
cout << "collisions: " << collisions << endl;
return 0;
}
| 24.197531
| 78
| 0.631633
|
tetzank
|
5b9074ca6632c2367c19e708e54caf4622c821f7
| 446
|
cpp
|
C++
|
LeetCode/Plus One/main.cpp
|
Code-With-Aagam/competitive-programming
|
610520cc396fb13a03c606b5fb6739cfd68cc444
|
[
"MIT"
] | 2
|
2022-02-08T12:37:41.000Z
|
2022-03-09T03:48:56.000Z
|
LeetCode/Plus One/main.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | null | null | null |
LeetCode/Plus One/main.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | 2
|
2021-01-23T14:35:48.000Z
|
2021-03-15T05:04:24.000Z
|
auto speedup = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> ans;
int carry = 1, j = digits.size() - 1;
while (j >= 0) {
int curr = digits[j--] + carry;
ans.push_back(curr % 10);
carry = curr / 10;
}
if (carry > 0) ans.push_back(carry);
reverse(ans.begin(), ans.end());
return ans;
}
};
| 20.272727
| 43
| 0.598655
|
Code-With-Aagam
|
5b90df0e6e3645c85aeea4c01fe6d7ae17a20817
| 67
|
hpp
|
C++
|
LibData.hpp
|
mattfbacon/dynload
|
a2ff4ad3cf4ddc4f9f007d36c00acf35baba9ff7
|
[
"WTFPL"
] | null | null | null |
LibData.hpp
|
mattfbacon/dynload
|
a2ff4ad3cf4ddc4f9f007d36c00acf35baba9ff7
|
[
"WTFPL"
] | null | null | null |
LibData.hpp
|
mattfbacon/dynload
|
a2ff4ad3cf4ddc4f9f007d36c00acf35baba9ff7
|
[
"WTFPL"
] | null | null | null |
#pragma once
struct LibData {
std::string name;
void(*fn)();
};
| 9.571429
| 18
| 0.626866
|
mattfbacon
|
5b945f3f0e81df96263fd7caaef184bf8b177439
| 3,279
|
hh
|
C++
|
thirdparty/graph-tools-master/include/graphalign/LinearAlignment.hh
|
AlesMaver/ExpansionHunter
|
274903d26a33cfbc546aac98c85bbfe51701fd3b
|
[
"BSL-1.0",
"Apache-2.0"
] | 122
|
2017-01-06T16:19:31.000Z
|
2022-03-08T00:05:50.000Z
|
thirdparty/graph-tools-master/include/graphalign/LinearAlignment.hh
|
AlesMaver/ExpansionHunter
|
274903d26a33cfbc546aac98c85bbfe51701fd3b
|
[
"BSL-1.0",
"Apache-2.0"
] | 90
|
2017-01-04T00:23:34.000Z
|
2022-02-27T12:55:52.000Z
|
thirdparty/graph-tools-master/include/graphalign/LinearAlignment.hh
|
AlesMaver/ExpansionHunter
|
274903d26a33cfbc546aac98c85bbfe51701fd3b
|
[
"BSL-1.0",
"Apache-2.0"
] | 35
|
2017-03-02T13:39:58.000Z
|
2022-03-30T17:34:11.000Z
|
//
// GraphTools library
// Copyright 2017-2019 Illumina, Inc.
// All rights reserved.
//
// Author: Egor Dolzhenko <edolzhenko@illumina.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include <list>
#include <string>
#include "graphalign/Operation.hh"
namespace graphtools
{
// Represents a linear alignment
class Alignment
{
public:
using size_type = size_t;
using const_iterator = std::list<Operation>::const_iterator;
Alignment(int32_t reference_start, std::list<Operation> operations)
: reference_start_(reference_start)
, operations_(std::move(operations))
{
updateCounts();
}
Alignment(uint32_t reference_start, const std::string& cigar);
const std::list<Operation>& operations() const { return operations_; }
size_type numOperations() const { return operations_.size(); }
uint32_t queryLength() const;
uint32_t referenceLength() const;
uint32_t referenceStart() const { return reference_start_; }
void setReferenceStart(uint32_t reference_start) { reference_start_ = reference_start; }
const_iterator begin() const { return operations_.begin(); }
const_iterator end() const { return operations_.end(); }
const Operation& front() const { return operations_.front(); }
const Operation& back() const { return operations_.back(); }
size_type size() const { return operations_.size(); }
bool operator==(const Alignment& other) const
{
return operations_ == other.operations_ && reference_start_ == other.reference_start_;
}
bool operator<(const Alignment& other) const;
size_t numMatched() const { return matched_; }
size_t numMismatched() const { return mismatched_; }
size_t numClipped() const { return clipped_; }
size_t numInserted() const { return inserted_; }
size_t numDeleted() const { return deleted_; }
std::string generateCigar() const;
/**
* Reverses an alignment
*
* @param reference_length: Total length of the reference sequence
*/
void reverse(size_t reference_length);
/**
* Splits off a piece of the alignment at the given reference position
*
* @param reference_position: Position at which the alignment is to be split
* @return Suffix alignment
*/
Alignment splitAtReferencePosition(size_t reference_position);
protected:
void decodeCigar(const std::string& encoding);
void updateCounts();
private:
size_t matched_ = 0;
size_t mismatched_ = 0;
size_t clipped_ = 0;
size_t inserted_ = 0;
size_t deleted_ = 0;
size_t missing_ = 0;
int32_t reference_start_ = 0;
std::list<Operation> operations_;
};
std::ostream& operator<<(std::ostream& os, const Alignment& alignment);
}
| 32.465347
| 94
| 0.703568
|
AlesMaver
|
5b94d89453038ee864879e08ded28aa35acf34b2
| 1,224
|
hpp
|
C++
|
doc/quickbook/oglplus/quickref/enums/ext/graphics_reset_status_class.hpp
|
matus-chochlik/oglplus
|
76dd964e590967ff13ddff8945e9dcf355e0c952
|
[
"BSL-1.0"
] | 364
|
2015-01-01T09:38:23.000Z
|
2022-03-22T05:32:00.000Z
|
doc/quickbook/oglplus/quickref/enums/ext/graphics_reset_status_class.hpp
|
matus-chochlik/oglplus
|
76dd964e590967ff13ddff8945e9dcf355e0c952
|
[
"BSL-1.0"
] | 55
|
2015-01-06T16:42:55.000Z
|
2020-07-09T04:21:41.000Z
|
doc/quickbook/oglplus/quickref/enums/ext/graphics_reset_status_class.hpp
|
matus-chochlik/oglplus
|
76dd964e590967ff13ddff8945e9dcf355e0c952
|
[
"BSL-1.0"
] | 57
|
2015-01-07T18:35:49.000Z
|
2022-03-22T05:32:04.000Z
|
// File
// doc/quickbook/oglplus/quickref/enums/ext/graphics_reset_status_class.hpp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/ext/graphics_reset_status.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 Matus Chochlik.
// 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
//
//[oglplus_enums_ext_graphics_reset_status_class
#if !__OGLPLUS_NO_ENUM_VALUE_CLASSES
namespace enums {
template <typename Base, template <__GraphicsResetStatusARB> class Transform>
class __EnumToClass<Base, __GraphicsResetStatusARB, Transform> /*<
Specialization of __EnumToClass for the __GraphicsResetStatusARB enumeration.
>*/
: public Base {
public:
EnumToClass();
EnumToClass(Base&& base);
Transform<GraphicsResetStatusARB::NoError> NoError;
Transform<GraphicsResetStatusARB::GuiltyContextReset> GuiltyContextReset;
Transform<GraphicsResetStatusARB::InnocentContextReset>
InnocentContextReset;
Transform<GraphicsResetStatusARB::UnknownContextReset> UnknownContextReset;
};
} // namespace enums
#endif
//]
| 34
| 79
| 0.784314
|
matus-chochlik
|
5b9924f384c8137459704a4c16571f9707ae4f27
| 3,800
|
cpp
|
C++
|
Paladin/FileUtils.cpp
|
pahefu/Paladin
|
4fcb66c6cda7bb50b7597532bd0d7469fc33655b
|
[
"MIT"
] | 45
|
2018-10-05T21:50:17.000Z
|
2022-01-31T11:52:59.000Z
|
Paladin/FileUtils.cpp
|
pahefu/Paladin
|
4fcb66c6cda7bb50b7597532bd0d7469fc33655b
|
[
"MIT"
] | 163
|
2018-10-01T23:52:12.000Z
|
2022-02-15T18:05:58.000Z
|
Paladin/FileUtils.cpp
|
pahefu/Paladin
|
4fcb66c6cda7bb50b7597532bd0d7469fc33655b
|
[
"MIT"
] | 9
|
2018-10-01T23:48:02.000Z
|
2022-01-23T21:28:52.000Z
|
#include "FileUtils.h"
#include <Alert.h>
#include <Bitmap.h>
#include <Catalog.h>
#include <Directory.h>
#include <Locale.h>
#include <Mime.h>
#include <Path.h>
#include <Roster.h>
#include "Icons.h"
#include "Paladin.h"
#include "Project.h"
#include "DebugTools.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "FileUtils"
void
InitFileTypes(void)
{
BMimeType mime;
BString string;
BMessage msg,ext;
BBitmap large_icon(BRect(0, 0, B_LARGE_ICON - 1, B_LARGE_ICON - 1), B_COLOR_8_BIT);
memcpy(large_icon.Bits(),kProjectLargeIconBits,1024);
BBitmap mini_icon(BRect(0, 0, B_MINI_ICON - 1, B_MINI_ICON - 1), B_COLOR_8_BIT);
memcpy(mini_icon.Bits(),kProjectSmallIconBits,256);
mime.SetType(PROJECT_MIME_TYPE);
mime.SetShortDescription(B_TRANSLATE("Paladin project"));
mime.SetLongDescription(B_TRANSLATE("File to build a program with Paladin"));
mime.SetIcon(&large_icon, B_LARGE_ICON);
mime.SetIcon(&mini_icon, B_MINI_ICON);
#ifdef __HAIKU__
mime.SetIcon(kProjectVectorIconBits, sizeof(kProjectVectorIconBits));
#endif
mime.SetSnifferRule("0.50 [0:32]( -i \"NAME=\" | \"TARGETNAME=\" | "
"\"PLATFORM=\" | \"GROUP=\" | \"SOURCEFILE=\")");
mime.SetPreferredApp(APP_SIGNATURE);
mime.Install();
ext.AddString("extensions","pld");
mime.SetFileExtensions(&ext);
}
void
FindAndOpenFile(BMessage *msg)
{
if (!msg)
return;
BString filename;
if (msg->FindString("name",&filename) == B_OK)
{
BString foldername;
int32 i = 0;
while (msg->FindString("folder",i,&foldername) == B_OK)
{
entry_ref folderref;
BEntry entry(foldername.String());
if (entry.InitCheck() == B_OK)
{
entry.GetRef(&folderref);
entry_ref fileref = FindFile(folderref,filename.String());
if (fileref.name)
{
STRACE(2,("FileUtils open file message"));
BMessage refMessage(B_REFS_RECEIVED);
refMessage.AddRef("refs",&fileref);
be_app->PostMessage(&refMessage);
return;
}
}
i++;
}
BString errorstr = B_TRANSLATE("Couldn't find %file%.");
errorstr.ReplaceFirst("%file%",filename);
BAlert *alert = new BAlert("Paladin", errorstr.String(), B_TRANSLATE("OK"));
alert->Go();
}
}
entry_ref
FindFile(entry_ref folder, const char *name)
{
entry_ref ref,returnRef;
if (!folder.name || !name)
return returnRef;
BDirectory dir(&folder);
if (dir.InitCheck() != B_OK)
return returnRef;
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
struct stat statData;
stat(BPath(&ref).Path(),&statData);
// Is a directory?
if (S_ISDIR(statData.st_mode))
{
entry_ref innerref = FindFile(ref,name);
if (innerref.device != -1 && innerref.directory != -1)
return innerref;
}
}
BEntry entry;
if (dir.FindEntry(name,&entry) == B_OK)
entry.GetRef(&returnRef);
return returnRef;
}
entry_ref
FindProject(entry_ref folder, const char *name)
{
printf("Searching for %s in folder %s\n", name, folder.name);
entry_ref ref,returnRef;
if (!folder.name || !name)
return returnRef;
// Because projects can now have source control folders, skip the
// internal folders for Git, Mercurial, Subversion, and CVS
if (strcmp(folder.name, ".hg") == 0 || strcmp(folder.name, ".git") == 0 ||
strcmp(folder.name, ".svn") == 0 || strcmp(folder.name, "CVS") == 0)
return returnRef;
BDirectory dir(&folder);
if (dir.InitCheck() != B_OK)
return returnRef;
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
struct stat statData;
stat(BPath(&ref).Path(),&statData);
// Is a directory?
if (S_ISDIR(statData.st_mode))
{
entry_ref innerref = FindFile(ref,name);
if (innerref.device != -1 && innerref.directory != -1)
return innerref;
}
}
BEntry entry;
if (dir.FindEntry(name,&entry) == B_OK)
entry.GetRef(&returnRef);
return returnRef;
}
| 23.45679
| 84
| 0.68
|
pahefu
|
5b99f83f14dd3a4958fb74cd02e8b2da91cb47ab
| 4,777
|
cpp
|
C++
|
libs/mesh/src/meshCubatureSetupTri2D.cpp
|
MalachiTimothyPhillips/libparanumal
|
f3fd4505df56207b05aa86164124ab6bad83f92a
|
[
"MIT"
] | null | null | null |
libs/mesh/src/meshCubatureSetupTri2D.cpp
|
MalachiTimothyPhillips/libparanumal
|
f3fd4505df56207b05aa86164124ab6bad83f92a
|
[
"MIT"
] | null | null | null |
libs/mesh/src/meshCubatureSetupTri2D.cpp
|
MalachiTimothyPhillips/libparanumal
|
f3fd4505df56207b05aa86164124ab6bad83f92a
|
[
"MIT"
] | null | null | null |
/*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "mesh.hpp"
#include "mesh2D.hpp"
#include "mesh3D.hpp"
void meshTri3D::CubatureSetup(){
mesh_t *mesh_p = (mesh_t*) this;
meshTri2D* trimesh = (meshTri2D*) mesh_p;
trimesh->meshTri2D::CubatureSetup();
}
void meshTri2D::CubatureSetup(){
/* Cubature data */
cubN = 2*N; //cubature order
CubatureNodesTri2D(cubN, &cubNp, &cubr, &cubs, &cubw);
cubInterp = (dfloat *) malloc(Np*cubNp*sizeof(dfloat));
InterpolationMatrixTri2D(N, Np, r, s, cubNp, cubr, cubs, cubInterp);
cubDrW = (dfloat*) calloc(cubNp*Np, sizeof(dfloat));
cubDsW = (dfloat*) calloc(cubNp*Np, sizeof(dfloat));
cubProject = (dfloat*) calloc(cubNp*Np, sizeof(dfloat));
CubatureWeakDmatricesTri2D(N, Np, r, s, cubNp, cubr, cubs, cubw,
cubDrW, cubDsW, cubProject);
// cubN+1 point Gauss-Legendre quadrature for surface integrals
cubNq = cubN+1;
cubNfp = cubN+1;
intNfp = cubN+1;
intr = (dfloat *) malloc(cubNfp*sizeof(dfloat));
intw = (dfloat *) malloc(cubNfp*sizeof(dfloat));
JacobiGQ(0, 0, cubN, intr, intw);
intInterp = (dfloat*) calloc(intNfp*Nfaces*Nfp, sizeof(dfloat));
intLIFT = (dfloat*) calloc(Nfaces*intNfp*Np, sizeof(dfloat));
CubatureSurfaceMatricesTri2D(N, Np, r, s, faceNodes, intNfp, intr, intw,
intInterp, intLIFT);
// add compile time constants to kernels
props["defines/" "p_cubNq"]= cubNq;
props["defines/" "p_cubNp"]= cubNp;
props["defines/" "p_intNfp"]= intNfp;
props["defines/" "p_intNfpNfaces"]= intNfp*Nfaces;
props["defines/" "p_cubNfp"]= cubNfp;
// build volume cubature matrix transposes
int cubNpBlocked = Np*((cubNp+Np-1)/Np);
dfloat *cubDrWT = (dfloat*) calloc(cubNpBlocked*Np, sizeof(dfloat));
dfloat *cubDsWT = (dfloat*) calloc(cubNpBlocked*Np, sizeof(dfloat));
dfloat *cubDrsWT = (dfloat*) calloc(2*cubNp*Np, sizeof(dfloat));
dfloat *cubProjectT = (dfloat*) calloc(cubNp*Np, sizeof(dfloat));
dfloat *cubInterpT = (dfloat*) calloc(cubNp*Np, sizeof(dfloat));
for(int n=0;n<Np;++n){
for(int m=0;m<cubNp;++m){
cubDrWT[n+m*Np] = cubDrW[n*cubNp+m];
cubDsWT[n+m*Np] = cubDsW[n*cubNp+m];
cubDrsWT[n+m*Np] = cubDrW[n*cubNp+m];
cubDrsWT[n+m*Np+cubNp*Np] = cubDsW[n*cubNp+m];
cubProjectT[n+m*Np] = cubProject[n*cubNp+m];
cubInterpT[m+n*cubNp] = cubInterp[m*Np+n];
}
}
// build surface integration matrix transposes
dfloat *intLIFTT = (dfloat*) calloc(Np*Nfaces*intNfp, sizeof(dfloat));
dfloat *intInterpT = (dfloat*) calloc(Nfp*Nfaces*intNfp, sizeof(dfloat));
for(int n=0;n<Np;++n){
for(int m=0;m<Nfaces*intNfp;++m){
intLIFTT[n+m*Np] = intLIFT[n*intNfp*Nfaces+m];
}
}
for(int n=0;n<intNfp*Nfaces;++n){
for(int m=0;m<Nfp;++m){
intInterpT[n+m*Nfaces*intNfp] = intInterp[n*Nfp + m];
}
}
o_cubvgeo = o_vgeo;// dummy
o_cubsgeo = o_sgeo; //dummy cubature geo factors
o_cubInterpT =
device.malloc(Np*cubNp*sizeof(dfloat),
cubInterpT);
o_cubProjectT =
device.malloc(Np*cubNp*sizeof(dfloat),
cubProjectT);
o_cubDrWT =
device.malloc(Np*cubNp*sizeof(dfloat),
cubDrWT);
o_cubDsWT =
device.malloc(Np*cubNp*sizeof(dfloat),
cubDsWT);
o_cubDtWT =
device.malloc(Np*cubNp*sizeof(dfloat),
cubDsWT); // dummy to align with 3d
o_cubDWmatrices = device.malloc(2*cubNp*Np*sizeof(dfloat), cubDrsWT);
o_intInterpT =
device.malloc(Nfp*Nfaces*intNfp*sizeof(dfloat),
intInterpT);
o_intLIFTT =
device.malloc(Np*Nfaces*intNfp*sizeof(dfloat),
intLIFTT);
free(cubDrWT);
free(cubDsWT);
free(cubDrsWT);
free(cubProjectT);
free(cubInterpT);
}
| 32.719178
| 78
| 0.686414
|
MalachiTimothyPhillips
|
5b9bc17d148303d0411460e69ce360f47f474f7d
| 6,073
|
cpp
|
C++
|
DirectX11_Starter_2015/DirectX11_Starter/PostManager.cpp
|
QRayarch/ShootyBally
|
c98d2cdccbc34a346f59d1cedfc4dbd1571e0a46
|
[
"MIT"
] | 1
|
2016-03-14T01:58:26.000Z
|
2016-03-14T01:58:26.000Z
|
DirectX11_Starter_2015/DirectX11_Starter/PostManager.cpp
|
QRayarch/ShootyBally
|
c98d2cdccbc34a346f59d1cedfc4dbd1571e0a46
|
[
"MIT"
] | null | null | null |
DirectX11_Starter_2015/DirectX11_Starter/PostManager.cpp
|
QRayarch/ShootyBally
|
c98d2cdccbc34a346f59d1cedfc4dbd1571e0a46
|
[
"MIT"
] | null | null | null |
#include "PostManager.h"
PostManager::PostManager(ID3D11Device * deviceIn, ID3D11DeviceContext * deviceContextIn)
{
device = deviceIn;
deviceContext = deviceContextIn;
blurAmount = 5;
rtvOriginal = nullptr;
srvGBlur1 = nullptr;
srvGBlur2 = nullptr;
rtvGBlur1 = nullptr;
rtvGBlur2 = nullptr;
}
PostManager::~PostManager()
{
ReleaseResources();
delete psBlur;
delete vertexShader;
delete psBloom;
delete psBloomThreshold;
}
void PostManager::SetChainDest(ID3D11RenderTargetView * rtv)
{
rtvFinal = rtv;
//srvFinal = srv;
}
void PostManager::BuildResources(int windowWidth, int windowHeight)
{
BuildResourcePair(windowWidth, windowHeight, &rtvOriginal, &srvOriginal);
BuildResourcePair(windowWidth, windowHeight, &rtvGBlur1, &srvGBlur1);
BuildResourcePair(windowWidth, windowHeight, &rtvGBlur2, &srvGBlur2);
BuildResourcePair(windowWidth, windowHeight, &rtvBloom, &srvBloom);
//BuildResourcePair(windowWidth, windowHeight, &rtvBloomResult, &srvBloomResult);
}
void PostManager::ReleaseResources()
{
ReleaseMacro(rtvOriginal);
ReleaseMacro(srvGBlur1);
ReleaseMacro(srvGBlur2);
ReleaseMacro(rtvGBlur1);
ReleaseMacro(rtvGBlur2);
ReleaseMacro(rtvBloom);
//ReleaseMacro(rtvBloomResult);
ReleaseMacro(srvBloom);
//ReleaseMacro(srvBloomResult);
}
void PostManager::RunChain(int windowWidth, int windowHeight, ID3D11SamplerState* samplerState, UINT stride, UINT offset)
{
//resetting stuff to function propperly
const float color[4] = { 0.4f, 0.6f, 0.75f, 0.0f };
ID3D11Buffer* nothing = 0;
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Turn off existing vert/index buffers
deviceContext->IASetVertexBuffers(0, 1, ¬hing, &stride, &offset);
deviceContext->IASetIndexBuffer(0, DXGI_FORMAT_R32_UINT, 0);
//Bloom
deviceContext->OMSetRenderTargets(1, &rtvBloom, 0);
deviceContext->ClearRenderTargetView(rtvBloom, color);
vertexShader->SetShader();
psBloomThreshold->SetFloat("threshold", 0.3f);
psBloomThreshold->SetShaderResourceView("pixels", srvOriginal);
psBloomThreshold->SetSamplerState("trilinear", samplerState);
psBloomThreshold->SetShader();
deviceContext->Draw(3, 0);
psBloomThreshold->SetShaderResourceView("pixels", 0);
unbindResources();
// Set targets for blur
deviceContext->OMSetRenderTargets(1, &rtvGBlur1, 0);
deviceContext->ClearRenderTargetView(rtvGBlur1, color);
// Draw the post process
vertexShader->SetShader();
psBlur->SetInt("vertical", 1);
psBlur->SetInt("blurAmount", blurAmount);
psBlur->SetFloat("pixelWidth", 1.0f / windowWidth);
psBlur->SetFloat("pixelHeight", 1.0f / windowHeight);
psBlur->SetShaderResourceView("pixels", srvBloom);
psBlur->SetSamplerState("trilinear", samplerState);
psBlur->SetShader();
// Draw
deviceContext->Draw(3, 0);
// Unbind the SRV so the underlying texture isn't bound for
// both input and output at the start of next frame
psBlur->SetShaderResourceView("pixels", 0);
unbindResources();
//blur horizontal
deviceContext->OMSetRenderTargets(1, &rtvFinal, 0);
deviceContext->ClearRenderTargetView(rtvFinal, color);
vertexShader->SetShader();
psBlur->SetInt("vertical", 0);
psBlur->SetInt("blurAmount", blurAmount);
psBlur->SetFloat("pixelWidth", 1.0f / windowWidth);
psBlur->SetFloat("pixelHeight", 1.0f / windowHeight);
psBlur->SetShaderResourceView("pixels", srvGBlur1);
psBlur->SetSamplerState("trilinear", samplerState);
psBlur->SetShader();
deviceContext->Draw(3, 0);
psBloomThreshold->SetShaderResourceView("pixels", 0);
unbindResources();
//Final Bloom composite
deviceContext->OMSetRenderTargets(1, &rtvFinal, 0);
deviceContext->ClearRenderTargetView(rtvFinal, color);
vertexShader->SetShader();
psBloom->SetFloat("bloomIntensity", 1.3f);
psBloom->SetFloat("originalIntensity", 1.0f);
psBloom->SetFloat("bloomSaturation", 1.0f);
psBloom->SetFloat("originalSaturation", 1.0f);
psBloom->SetShaderResourceView("bloomThresh", srvGBlur2);
psBloom->SetShaderResourceView("cleanImage", srvOriginal);
psBloom->SetSamplerState("trilinear", samplerState);
psBloom->SetShader();
deviceContext->Draw(3, 0);
psBloomThreshold->SetShaderResourceView("pixels", 0);
unbindResources();
}
void PostManager::LoadShaders()
{
vertexShader = new SimpleVertexShader(device, deviceContext);
vertexShader->LoadShaderFile(L"VS_Post.cso");
psBlur = new SimplePixelShader(device, deviceContext);
psBlur->LoadShaderFile(L"PS_Blur.cso");
psBloom = new SimplePixelShader(device, deviceContext);
psBloom->LoadShaderFile(L"PS_Bloom.cso");
psBloomThreshold = new SimplePixelShader(device, deviceContext);
psBloomThreshold->LoadShaderFile(L"PS_BloomThreshold.cso");
}
void PostManager::BuildResourcePair(int windowWidth, int windowHeight, ID3D11RenderTargetView ** rtv, ID3D11ShaderResourceView ** srv)
{
//Target Texture
D3D11_TEXTURE2D_DESC texDesc = {};
texDesc.Width = windowWidth;
texDesc.Height = windowHeight;
texDesc.ArraySize = 1;
texDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.MipLevels = 1;
texDesc.MiscFlags = 0;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
ID3D11Texture2D* postTexture;
device->CreateTexture2D(&texDesc, 0, &postTexture);
//Render Target View
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
rtvDesc.Format = texDesc.Format;
rtvDesc.Texture2D.MipSlice = 0;
rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
device->CreateRenderTargetView(postTexture, &rtvDesc, rtv);
//Shader Resource View
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = texDesc.Format;
srvDesc.Texture2D.MipLevels = 1;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
device->CreateShaderResourceView(postTexture, &srvDesc, srv);
//Release Texture cleanup
ReleaseMacro(postTexture);
}
void PostManager::unbindResources()
{
ID3D11ShaderResourceView* null[] = { nullptr, nullptr };
deviceContext->PSSetShaderResources(0, 2, null);
}
| 31.14359
| 134
| 0.774411
|
QRayarch
|
5b9cae6d60f3e55810ffa35a8b38db841805909b
| 10,038
|
cc
|
C++
|
poppler-21.11.0/poppler/JArithmeticDecoder.cc
|
stackoverflowed/multimodal
|
95668d0b34d297e96b5ef76521e587578ef2581f
|
[
"MIT"
] | null | null | null |
poppler-21.11.0/poppler/JArithmeticDecoder.cc
|
stackoverflowed/multimodal
|
95668d0b34d297e96b5ef76521e587578ef2581f
|
[
"MIT"
] | null | null | null |
poppler-21.11.0/poppler/JArithmeticDecoder.cc
|
stackoverflowed/multimodal
|
95668d0b34d297e96b5ef76521e587578ef2581f
|
[
"MIT"
] | null | null | null |
//========================================================================
//
// JArithmeticDecoder.cc
//
// Copyright 2002-2004 Glyph & Cog, LLC
//
//========================================================================
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2019 Volker Krause <vkrause@kde.org>
// Copyright (C) 2020 Even Rouault <even.rouault@spatialys.com>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
#include <config.h>
#include "Object.h"
#include "Stream.h"
#include "JArithmeticDecoder.h"
//------------------------------------------------------------------------
// JArithmeticDecoderStates
//------------------------------------------------------------------------
JArithmeticDecoderStats::JArithmeticDecoderStats(int contextSizeA)
{
contextSize = contextSizeA;
cxTab = (unsigned char *)gmallocn_checkoverflow(contextSize, sizeof(unsigned char));
if (cxTab) {
reset();
}
}
JArithmeticDecoderStats::~JArithmeticDecoderStats()
{
gfree(cxTab);
}
JArithmeticDecoderStats *JArithmeticDecoderStats::copy()
{
JArithmeticDecoderStats *stats;
stats = new JArithmeticDecoderStats(contextSize);
memcpy(stats->cxTab, cxTab, contextSize);
return stats;
}
void JArithmeticDecoderStats::reset()
{
memset(cxTab, 0, contextSize);
}
void JArithmeticDecoderStats::copyFrom(JArithmeticDecoderStats *stats)
{
memcpy(cxTab, stats->cxTab, contextSize);
}
void JArithmeticDecoderStats::setEntry(unsigned int cx, int i, int mps)
{
cxTab[cx] = (i << 1) + mps;
}
//------------------------------------------------------------------------
// JArithmeticDecoder
//------------------------------------------------------------------------
unsigned const int JArithmeticDecoder::qeTab[47] = { 0x56010000, 0x34010000, 0x18010000, 0x0AC10000, 0x05210000, 0x02210000, 0x56010000, 0x54010000, 0x48010000, 0x38010000, 0x30010000, 0x24010000,
0x1C010000, 0x16010000, 0x56010000, 0x54010000, 0x51010000, 0x48010000, 0x38010000, 0x34010000, 0x30010000, 0x28010000, 0x24010000, 0x22010000,
0x1C010000, 0x18010000, 0x16010000, 0x14010000, 0x12010000, 0x11010000, 0x0AC10000, 0x09C10000, 0x08A10000, 0x05210000, 0x04410000, 0x02A10000,
0x02210000, 0x01410000, 0x01110000, 0x00850000, 0x00490000, 0x00250000, 0x00150000, 0x00090000, 0x00050000, 0x00010000, 0x56010000 };
const int JArithmeticDecoder::nmpsTab[47] = { 1, 2, 3, 4, 5, 38, 7, 8, 9, 10, 11, 12, 13, 29, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 45, 46 };
const int JArithmeticDecoder::nlpsTab[47] = { 1, 6, 9, 12, 29, 33, 6, 14, 14, 14, 17, 18, 20, 21, 14, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46 };
const int JArithmeticDecoder::switchTab[47] = { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
JArithmeticDecoder::JArithmeticDecoder()
{
str = nullptr;
dataLen = 0;
limitStream = false;
nBytesRead = 0;
}
inline unsigned int JArithmeticDecoder::readByte()
{
if (limitStream) {
--dataLen;
if (dataLen < 0) {
return 0xff;
}
}
++nBytesRead;
return (unsigned int)str->getChar() & 0xff;
}
JArithmeticDecoder::~JArithmeticDecoder()
{
cleanup();
}
void JArithmeticDecoder::start()
{
buf0 = readByte();
buf1 = readByte();
// INITDEC
c = (buf0 ^ 0xff) << 16;
byteIn();
c <<= 7;
ct -= 7;
a = 0x80000000;
}
void JArithmeticDecoder::restart(int dataLenA)
{
unsigned int cAdd;
bool prevFF;
int k, nBits;
if (dataLen >= 0) {
dataLen = dataLenA;
} else if (dataLen == -1) {
dataLen = dataLenA;
buf1 = readByte();
} else {
k = (-dataLen - 1) * 8 - ct;
dataLen = dataLenA;
cAdd = 0;
prevFF = false;
while (k > 0) {
buf0 = readByte();
if (prevFF) {
cAdd += 0xfe00 - (buf0 << 9);
nBits = 7;
} else {
cAdd += 0xff00 - (buf0 << 8);
nBits = 8;
}
prevFF = buf0 == 0xff;
if (k > nBits) {
cAdd <<= nBits;
k -= nBits;
} else {
cAdd <<= k;
ct = nBits - k;
k = 0;
}
}
c += cAdd;
buf1 = readByte();
}
}
void JArithmeticDecoder::cleanup()
{
if (limitStream) {
while (dataLen > 0) {
buf0 = buf1;
buf1 = readByte();
}
}
}
int JArithmeticDecoder::decodeBit(unsigned int context, JArithmeticDecoderStats *stats)
{
int bit;
unsigned int qe;
int iCX, mpsCX;
iCX = stats->cxTab[context] >> 1;
mpsCX = stats->cxTab[context] & 1;
qe = qeTab[iCX];
a -= qe;
if (c < a) {
if (a & 0x80000000) {
bit = mpsCX;
} else {
// MPS_EXCHANGE
if (a < qe) {
bit = 1 - mpsCX;
if (switchTab[iCX]) {
stats->cxTab[context] = (nlpsTab[iCX] << 1) | (1 - mpsCX);
} else {
stats->cxTab[context] = (nlpsTab[iCX] << 1) | mpsCX;
}
} else {
bit = mpsCX;
stats->cxTab[context] = (nmpsTab[iCX] << 1) | mpsCX;
}
// RENORMD
do {
if (ct == 0) {
byteIn();
}
a <<= 1;
c <<= 1;
--ct;
} while (!(a & 0x80000000));
}
} else {
c -= a;
// LPS_EXCHANGE
if (a < qe) {
bit = mpsCX;
stats->cxTab[context] = (nmpsTab[iCX] << 1) | mpsCX;
} else {
bit = 1 - mpsCX;
if (switchTab[iCX]) {
stats->cxTab[context] = (nlpsTab[iCX] << 1) | (1 - mpsCX);
} else {
stats->cxTab[context] = (nlpsTab[iCX] << 1) | mpsCX;
}
}
a = qe;
// RENORMD
do {
if (ct == 0) {
byteIn();
}
a <<= 1;
c <<= 1;
--ct;
} while (!(a & 0x80000000));
}
return bit;
}
int JArithmeticDecoder::decodeByte(unsigned int context, JArithmeticDecoderStats *stats)
{
int byte;
int i;
byte = 0;
for (i = 0; i < 8; ++i) {
byte = (byte << 1) | decodeBit(context, stats);
}
return byte;
}
bool JArithmeticDecoder::decodeInt(int *x, JArithmeticDecoderStats *stats)
{
int s;
unsigned int v;
int i;
prev = 1;
s = decodeIntBit(stats);
if (decodeIntBit(stats)) {
if (decodeIntBit(stats)) {
if (decodeIntBit(stats)) {
if (decodeIntBit(stats)) {
if (decodeIntBit(stats)) {
v = 0;
for (i = 0; i < 32; ++i) {
v = (v << 1) | decodeIntBit(stats);
}
v += 4436;
} else {
v = 0;
for (i = 0; i < 12; ++i) {
v = (v << 1) | decodeIntBit(stats);
}
v += 340;
}
} else {
v = 0;
for (i = 0; i < 8; ++i) {
v = (v << 1) | decodeIntBit(stats);
}
v += 84;
}
} else {
v = 0;
for (i = 0; i < 6; ++i) {
v = (v << 1) | decodeIntBit(stats);
}
v += 20;
}
} else {
v = decodeIntBit(stats);
v = (v << 1) | decodeIntBit(stats);
v = (v << 1) | decodeIntBit(stats);
v = (v << 1) | decodeIntBit(stats);
v += 4;
}
} else {
v = decodeIntBit(stats);
v = (v << 1) | decodeIntBit(stats);
}
if (s) {
if (v == 0) {
return false;
}
*x = -(int)v;
} else {
*x = (int)v;
}
return true;
}
int JArithmeticDecoder::decodeIntBit(JArithmeticDecoderStats *stats)
{
int bit;
bit = decodeBit(prev, stats);
if (prev < 0x100) {
prev = (prev << 1) | bit;
} else {
prev = (((prev << 1) | bit) & 0x1ff) | 0x100;
}
return bit;
}
unsigned int JArithmeticDecoder::decodeIAID(unsigned int codeLen, JArithmeticDecoderStats *stats)
{
unsigned int i;
int bit;
prev = 1;
for (i = 0; i < codeLen; ++i) {
bit = decodeBit(prev, stats);
prev = (prev << 1) | bit;
}
return prev - (1 << codeLen);
}
void JArithmeticDecoder::byteIn()
{
if (buf0 == 0xff) {
if (buf1 > 0x8f) {
if (limitStream) {
buf0 = buf1;
buf1 = readByte();
c = c + 0xff00 - (buf0 << 8);
}
ct = 8;
} else {
buf0 = buf1;
buf1 = readByte();
c = c + 0xfe00 - (buf0 << 9);
ct = 7;
}
} else {
buf0 = buf1;
buf1 = readByte();
c = c + 0xff00 - (buf0 << 8);
ct = 8;
}
}
| 27.729282
| 231
| 0.443415
|
stackoverflowed
|
5b9f34abcdb5e0ecc4b2bbc0fcd071f2530781ae
| 1,427
|
cc
|
C++
|
expectations/makeexp.cc
|
piki/pip
|
ffd91f8b4ff21d7070a41a3d9f961d4e44625111
|
[
"BSD-3-Clause"
] | 2
|
2017-10-18T22:33:52.000Z
|
2021-11-11T22:32:10.000Z
|
expectations/makeexp.cc
|
piki/pip
|
ffd91f8b4ff21d7070a41a3d9f961d4e44625111
|
[
"BSD-3-Clause"
] | null | null | null |
expectations/makeexp.cc
|
piki/pip
|
ffd91f8b4ff21d7070a41a3d9f961d4e44625111
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2005-2006 Duke University. All rights reserved.
* Please see COPYING for license terms.
*/
#include <assert.h>
#include <getopt.h>
#include <string>
#include <stdarg.h>
#include <stdio.h>
#include "path.h"
#include <map>
#include <set>
#include "aggregates.h"
#include "exptree.h"
#include "pathfactory.h"
#include "rcfile.h"
static void read_path(PathFactory *pf, int pathid);
static void usage(const char *prog) {
fprintf(stderr, "Usage:\n %s [options] table-name pathid\n\n", prog);
exit(1);
}
static bool use_regex = false;
int main(int argc, char **argv) {
std::map<std::string,RecognizerBase*>::const_iterator rp;
char c;
while ((c = getopt(argc, argv, "r")) != -1) {
switch (c) {
case 'r': use_regex = true; break;
default: usage(argv[0]);
}
}
if (argc - optind != 2) {
fprintf(stderr, "Usage:\n %s [options] table-name pathid\n\n", argv[0]);
return 1;
}
const char *base = argv[optind];
int pathid = atoi(argv[optind+1]);
PathFactory *pf = path_factory(base);
if (!pf->valid()) return 1;
read_path(pf, pathid);
delete pf;
return 0;
}
static void read_path(PathFactory *pf, int pathid) {
Path *path = pf->get_path(pathid);
if (!path->valid())
printf("# path %d malformed\n", pathid);
printf("// source=\"%s\" pathid=%d\n", pf->get_name().c_str(), pathid);
printf("validator val_%d {\n", pathid);
path->print_exp();
printf("}\n");
delete path;
}
| 22.296875
| 75
| 0.650315
|
piki
|
5ba17a20820780b4adb9a8a08fd68067576b6362
| 2,146
|
cpp
|
C++
|
gko-tracker-src/src/PeerInfo.cpp
|
yujinqiu/gingko
|
33f289b36d6d8176fa7be67275dda93d40efbfd7
|
[
"BSD-2-Clause"
] | 11
|
2018-01-31T12:31:56.000Z
|
2022-01-06T04:45:03.000Z
|
gko-tracker-src/src/PeerInfo.cpp
|
jaewon713/gingko
|
33f289b36d6d8176fa7be67275dda93d40efbfd7
|
[
"BSD-2-Clause"
] | null | null | null |
gko-tracker-src/src/PeerInfo.cpp
|
jaewon713/gingko
|
33f289b36d6d8176fa7be67275dda93d40efbfd7
|
[
"BSD-2-Clause"
] | 9
|
2017-10-31T06:51:24.000Z
|
2020-02-10T09:21:00.000Z
|
#include "bbts/tracker/PeerInfo.h"
#include "bbts/thrift_serializer.h"
#include "tracker_types.h"
using std::string;
namespace bbts {
namespace tracker {
string PeerInfo::tracker_id_;
PeerInfo::PeerInfo() : is_set_remote(false) {};
PeerInfo::PeerInfo(const PeerInfo &to_copy) {
this->is_set_remote = to_copy.GetIsSetRemote();
this->thrift_peer = to_copy.GetInnerPeer();
}
const tracker::StoredPeerInfo &PeerInfo::GetInnerPeer() const {
return thrift_peer;
}
StoredPeerInfo &PeerInfo::GetInnerPeerReference() {
return thrift_peer;
}
void PeerInfo::UpdateInfo(const PeerInfo& input_peer) {
const StoredPeerInfo &input_thrift_peer = input_peer.GetInnerPeer();
if (input_thrift_peer.__isset.info_hash == true) {
this->SetInfoHash(input_thrift_peer.info_hash);
} else {
return;
}
if (input_thrift_peer.__isset.peer_id == true) {
this->SetPeerId(input_thrift_peer.peer_id);
} else {
return;
}
uint64_t expire_interval;
if (input_thrift_peer.__isset.expire_time == true) {
expire_interval = input_thrift_peer.expire_time;
this->SetExpireTime(expire_interval);
}
this->SetTimeStamp((int64_t)time(NULL));
this->SetIp(input_thrift_peer.ip);
this->SetPort(input_thrift_peer.port);
this->SetStatus(input_thrift_peer.status);
this->SetUploaded(input_thrift_peer.uploaded);
this->SetDownloaded(input_thrift_peer.downloaded);
this->SetLeft(input_thrift_peer.left);
this->SetWantNumber(input_thrift_peer.want_number);
this->SetIsSeed(input_thrift_peer.is_seed);
this->SetTrackerId(input_thrift_peer.tracker_id);
this->SetIdc(input_thrift_peer.idc);
}
void PeerInfo::ConstructPeerInfoByString(const string &string_input) {
ThriftParseFromString(string_input, &(this->GetInnerPeerReference()));
if (!Base64Encode(this->GetInfoHash(), &base64_info_hash)) {
base64_info_hash = this->GetInfoHash();
}
if (Base64Encode(this->GetPeerId(), &base64_peer_id)) {
base64_peer_id = this->GetPeerId();
}
}
void PeerInfo::ConstructStringByPeerInfo(string *string_input) const {
assert(string_input);
ThriftSerializeToString(this->GetInnerPeer(), string_input);
}
}
}
| 27.87013
| 72
| 0.754893
|
yujinqiu
|
5ba461438693df359d936070475b867c750f34cf
| 764
|
cpp
|
C++
|
external/OpenGP/GL/Entity.cpp
|
sherrbss/ProceduralNoise
|
99162d9b00d52b50e33a64313911300406af0745
|
[
"MIT"
] | null | null | null |
external/OpenGP/GL/Entity.cpp
|
sherrbss/ProceduralNoise
|
99162d9b00d52b50e33a64313911300406af0745
|
[
"MIT"
] | null | null | null |
external/OpenGP/GL/Entity.cpp
|
sherrbss/ProceduralNoise
|
99162d9b00d52b50e33a64313911300406af0745
|
[
"MIT"
] | null | null | null |
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "Entity.h"
//=============================================================================
namespace OpenGP {
//=============================================================================
void Entity::update() {
for (auto &pair : components) {
pair.second->update();
}
}
Scene &Entity::get_scene() {
assert(scene != nullptr);
return *scene;
}
//=============================================================================
} // OpenGP::
//=============================================================================
| 25.466667
| 79
| 0.36911
|
sherrbss
|
5babcb7f1b5b38fd1221783d7ab8792423fd96d4
| 2,638
|
cpp
|
C++
|
main/String_format.cpp
|
ololoshka2871/NixieClock-ESP32-idf
|
1505f801ca6f5ff36d2648805b20dab5d1326c12
|
[
"Apache-2.0"
] | null | null | null |
main/String_format.cpp
|
ololoshka2871/NixieClock-ESP32-idf
|
1505f801ca6f5ff36d2648805b20dab5d1326c12
|
[
"Apache-2.0"
] | null | null | null |
main/String_format.cpp
|
ololoshka2871/NixieClock-ESP32-idf
|
1505f801ca6f5ff36d2648805b20dab5d1326c12
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdarg>
#include <string>
#include <vector>
#include <cinttypes>
#include "String_format.h"
#define INITIAL_BUF_SIZE 128
std::string vtformat_impl(const std::string &fmt,
const std::vector<std::string> &strs) {
static const char FORMAT_SYMBOL = '%';
std::string res;
std::string buf;
bool arg = false;
for (int i = 0; i <= static_cast<int>(fmt.size()); ++i) {
bool last = i == static_cast<int>(fmt.size());
char ch = fmt[i];
if (arg) {
if (ch >= '0' && ch <= '9') {
buf += ch;
} else {
int num = 0;
if (!buf.empty() && buf.length() < 10)
num = atoi(buf.c_str());
if (num >= 1 && num <= static_cast<int>(strs.size()))
res += strs[num - 1];
else
res += FORMAT_SYMBOL + buf;
buf.clear();
if (ch != FORMAT_SYMBOL) {
if (!last)
res += ch;
arg = false;
}
}
} else {
if (ch == FORMAT_SYMBOL) {
arg = true;
} else {
if (!last)
res += ch;
}
}
}
return res;
}
std::string to_string(int32_t x) {
// -2147483647
char buf[16];
snprintf(buf, sizeof(buf) - 2, "%d", x);
return std::string(buf);
}
std::string to_string(uint32_t x) {
// 4294967295
char buf[16];
snprintf(buf, sizeof(buf) - 2, "%u", x);
return std::string(buf);
}
std::string to_string(int64_t x) {
// 18446744073709551616
char buf[24];
snprintf(buf, sizeof(buf) - 2, "%" PRId64, x);
return std::string(buf);
}
std::string to_string(uint64_t x) {
// 18446744073709551616
char buf[24];
snprintf(buf, sizeof(buf) - 2, "%" PRIu64, x);
return std::string(buf);
}
std::string to_string(float x) {
char buf[24];
snprintf(buf, sizeof(buf) - 2, "%f", x);
return std::to_string(x);
}
std::string to_string(double x) {
char buf[24];
snprintf(buf, sizeof(buf) - 2, "%f", x);
return std::to_string(x);
}
std::string to_string(const char *x) { return std::string(x); }
std::string to_string(const std::string &x) { return x; }
std::string format(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
std::vector<char> v(INITIAL_BUF_SIZE);
while (true) {
va_list args2;
va_copy(args2, args);
int res = vsnprintf(v.data(), v.size(), fmt, args2);
if ((res >= 0) && (res < static_cast<int>(v.size()))) {
va_end(args);
va_end(args2);
return std::string(v.data());
}
size_t size;
if (res < 0)
size = v.size() * 2;
else
size = static_cast<size_t>(res) + 1;
v.clear();
v.resize(size);
va_end(args2);
}
}
| 22.547009
| 65
| 0.547763
|
ololoshka2871
|
5bb1489856b7e9e6fb42af4d732e91de66bda8ed
| 164
|
cpp
|
C++
|
CToC++/CToC++/Leetcode/LeetcodeSolution110.cpp
|
UCliwenbin/AlgorithmCPP
|
3cb4a6a9510682b5d4dc956826d263ab778a2a00
|
[
"MIT"
] | 1
|
2021-02-25T08:00:43.000Z
|
2021-02-25T08:00:43.000Z
|
CToC++/CToC++/Leetcode/LeetcodeSolution110.cpp
|
UCliwenbin/AlgorithmCPP
|
3cb4a6a9510682b5d4dc956826d263ab778a2a00
|
[
"MIT"
] | null | null | null |
CToC++/CToC++/Leetcode/LeetcodeSolution110.cpp
|
UCliwenbin/AlgorithmCPP
|
3cb4a6a9510682b5d4dc956826d263ab778a2a00
|
[
"MIT"
] | null | null | null |
//
// LeetcodeSolution110.cpp
// CToC++
//
// Created by mac on 2020/8/26.
// Copyright © 2020 lwb. All rights reserved.
//
#include "LeetcodeSolution110.hpp"
| 16.4
| 46
| 0.664634
|
UCliwenbin
|
5bb18e1d1794b48e0788c2d3ab27b3bfbbf9be55
| 481
|
cpp
|
C++
|
InterviewBit/Dynamic Programming/MinSumPathInAMatrix.cpp
|
CRAZYGEEKS04/competitive-programming-1
|
f27b8a718761b7bfeb8ff9e294398ca1a294cb5d
|
[
"MIT"
] | 2
|
2020-06-01T09:16:47.000Z
|
2021-09-04T12:39:41.000Z
|
InterviewBit/Dynamic Programming/MinSumPathInAMatrix.cpp
|
gauravsingh58/competitive-programming
|
fa5548f435cdf2aa059e1d6ab733885790c6a592
|
[
"MIT"
] | 1
|
2020-10-10T16:14:54.000Z
|
2020-10-10T16:14:54.000Z
|
InterviewBit/Dynamic Programming/MinSumPathInAMatrix.cpp
|
gauravsingh58/competitive-programming
|
fa5548f435cdf2aa059e1d6ab733885790c6a592
|
[
"MIT"
] | null | null | null |
int Solution::minPathSum(vector<vector<int>> &board) {
int n = board.size();
int m = board[0].size();
vector<vector<int>> dp(n, vector<int>(m, 0));
dp[0][0] = board[0][0];
for (int i = 1; i < n; i++)
dp[i][0] = board[i][0] + dp[i - 1][0];
for (int j = 1; j < m; j++)
dp[0][j] = board[0][j] + dp[0][j - 1];
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = board[i][j] + min(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[n - 1][m - 1];
}
| 20.913043
| 60
| 0.45738
|
CRAZYGEEKS04
|
5bb870e2e6f474a1563e0dae790ba713cddaaf0e
| 2,270
|
cpp
|
C++
|
source/tests/mars-test/mars_gps_sensor.cpp
|
eallak/mars_lib
|
9657fb669c48be39471e7504c3648319126c020b
|
[
"BSD-2-Clause"
] | null | null | null |
source/tests/mars-test/mars_gps_sensor.cpp
|
eallak/mars_lib
|
9657fb669c48be39471e7504c3648319126c020b
|
[
"BSD-2-Clause"
] | null | null | null |
source/tests/mars-test/mars_gps_sensor.cpp
|
eallak/mars_lib
|
9657fb669c48be39471e7504c3648319126c020b
|
[
"BSD-2-Clause"
] | null | null | null |
#include <gmock/gmock.h>
#include <mars/sensors/gps/gps_measurement_type.h>
#include <mars/sensors/gps/gps_sensor_class.h>
#include <mars/type_definitions/base_states.h>
#include <mars/type_definitions/buffer_data_type.h>
#include <mars/type_definitions/buffer_entry_type.h>
#include <Eigen/Dense>
class mars_gps_sensor_test : public testing::Test
{
public:
};
TEST_F(mars_gps_sensor_test, CTOR_GPS_SENSOR)
{
mars::CoreState core_states;
std::shared_ptr<mars::CoreState> core_states_sptr = std::make_shared<mars::CoreState>(core_states);
mars::GpsSensorClass gps_sensor("GPS", core_states_sptr);
}
TEST_F(mars_gps_sensor_test, GPS_SENSOR_MEASUREMENT)
{
Eigen::Vector3d position; // Position [x y z]
position << 1, 2, 3;
mars::GpsMeasurementType b(position);
Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, ", ", ";\n", "", "", "[", "]");
std::cout << b.position_.format(OctaveFmt) << std::endl;
}
TEST_F(mars_gps_sensor_test, GPS_SENSOR_INIT)
{
Eigen::Vector3d position; // Position [x y z]
position << 1, 2, 3;
mars::GpsMeasurementType measurement(position);
mars::CoreState core_states;
std::shared_ptr<mars::CoreState> core_states_sptr = std::make_shared<mars::CoreState>(core_states);
mars::GpsSensorClass gps_sensor("GPS", core_states_sptr);
gps_sensor.Initialize(1, std::make_shared<mars::GpsMeasurementType>(measurement),
std::make_shared<mars::CoreType>());
}
TEST_F(mars_gps_sensor_test, GPS_UPDATE)
{
Eigen::Vector3d position; // Position [x y z]
position << 1, 2, 3;
mars::GpsMeasurementType measurement(position);
mars::CoreState core_states;
std::shared_ptr<mars::CoreState> core_states_sptr = std::make_shared<mars::CoreState>(core_states);
mars::GpsSensorClass gps_sensor("GPS", core_states_sptr);
int timestamp = 1;
mars::CoreStateType prior_core_state;
mars::BufferDataType prior_sensor_buffer_data;
Eigen::Matrix<double, prior_core_state.size_error_ + 3, prior_core_state.size_error_ + 3> prior_cov;
prior_cov.setIdentity();
mars::BufferDataType test;
gps_sensor.CalcUpdate(timestamp, std::make_shared<mars::GpsMeasurementType>(measurement), prior_core_state,
prior_sensor_buffer_data.sensor_, prior_cov, &test);
}
| 32.898551
| 109
| 0.738767
|
eallak
|
5bbc29bc231e03a5f5520de57966cf0d54bc02ea
| 3,114
|
cpp
|
C++
|
examples/Script.cpp
|
dbpotato/sacs
|
70d2c45a6529e58ba8c216460c0d1e9d55b16040
|
[
"MIT"
] | null | null | null |
examples/Script.cpp
|
dbpotato/sacs
|
70d2c45a6529e58ba8c216460c0d1e9d55b16040
|
[
"MIT"
] | null | null | null |
examples/Script.cpp
|
dbpotato/sacs
|
70d2c45a6529e58ba8c216460c0d1e9d55b16040
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2020 Adam Kaniewski
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <stdlib.h>
#include <sstream>
#include "SacsWrapper.h"
std::string script = R"""(function script_test_init(module_id){
img = document.createElement('img');
img.src='https://icons-for-free.com/iconfiles/png/512/mario+mario+bros+mario+world+mushroom+toad+videogame+icon-1320196400529338074.png';
img.setAttribute("id", "script_test_img");
img.width = 400;
img.height = 400;
img.addEventListener("click", function(){
var props = [{id: 1, value : "1"}];
handlePopertiesActivated(module_id, props);
});
return img;
}
function script_test_update(properies) {
var vals = properies.split(' ');
img = document.getElementById("script_test_img");
img.width = parseInt(vals[0]);
img.height = parseInt(vals[1]);
}
)""";
void callback(int module_id, int count, const int* property_no, const char* const* property_val) {
std::stringstream str_stream;
str_stream << (rand() % 201 + 200) << " " << (rand() % 201 + 200);
std::vector<std::pair<int, std::string> > properties;
properties.emplace_back(0, str_stream.str());
properties.emplace_back(1, str_stream.str());
SacsWrapper::Instance().UpdateProperties(module_id, properties);
}
int main() {
/* Register Module with two text fileds and callback
*/
std::vector<ModuleProperty> properties;
properties.emplace_back(ModuleProperty::Type::TEXT_RO, "Current Size", "400 400");
properties.emplace_back(ModuleProperty::Type::SCRIPT, "script_test", script);
SacsWrapper::Instance().RegisterModule("Script", properties, callback);
while(true)
sleep(1);
}
| 42.081081
| 165
| 0.632306
|
dbpotato
|
5bc0a605ababf3b20136750c5822e93f518427b1
| 5,654
|
cpp
|
C++
|
Source/Common/SQLLite.cpp
|
g-maxime/MediaConch_SourceCode
|
54208791ca0b6eb3f7bffd17f67e236777f69d89
|
[
"BSD-2-Clause"
] | 29
|
2016-01-28T08:58:54.000Z
|
2021-12-19T16:49:58.000Z
|
Source/Common/SQLLite.cpp
|
g-maxime/MediaConch_SourceCode
|
54208791ca0b6eb3f7bffd17f67e236777f69d89
|
[
"BSD-2-Clause"
] | 218
|
2015-07-07T09:49:17.000Z
|
2022-03-21T06:18:37.000Z
|
Source/Common/SQLLite.cpp
|
g-maxime/MediaConch_SourceCode
|
54208791ca0b6eb3f7bffd17f67e236777f69d89
|
[
"BSD-2-Clause"
] | 18
|
2015-06-19T17:58:34.000Z
|
2021-12-08T15:02:26.000Z
|
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#ifdef HAVE_SQLITE
//---------------------------------------------------------------------------
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "SQLLite.h"
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
namespace MediaConch {
//***************************************************************************
// SQLLite
//***************************************************************************
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
//---------------------------------------------------------------------------
SQLLite::SQLLite()
{
db = NULL;
stmt = NULL;
}
//---------------------------------------------------------------------------
SQLLite::~SQLLite()
{
if (db)
sqlite3_close(db);
}
//---------------------------------------------------------------------------
int SQLLite::init(const std::string& db_dirname, const std::string& db_filename)
{
std::string db_file(db_dirname + db_filename);
int ret = sqlite3_open(db_file.c_str(), &db);
if (ret)
{
std::stringstream err("Error to open the DB: ");
err << sqlite3_errmsg(db);
error = err.str();
sqlite3_close(db);
db = NULL;
return -1;
}
return 0;
}
//---------------------------------------------------------------------------
int SQLLite::execute()
{
if (!db || !stmt)
return -1;
error.clear();
int ret;
while (1)
{
ret = sqlite3_step(stmt);
if (ret == SQLITE_DONE)
break;
else if (ret == SQLITE_ROW)
{
std::map<std::string, std::string> tmp;
for (int i = 0; i < sqlite3_column_count(stmt); ++i)
{
std::string name(sqlite3_column_name(stmt, i));
const void *blob = sqlite3_column_blob(stmt, i);
std::string value((const char *)blob, sqlite3_column_bytes(stmt, i));
tmp[name] = value;
}
reports.push_back(tmp);
}
else
{
ret = sqlite3_reset(stmt);
error = get_sqlite_error(ret);
break;
}
}
sqlite3_finalize(stmt);
stmt = NULL;
if(ret == SQLITE_DONE)
return 0;
return -1;
}
//---------------------------------------------------------------------------
long SQLLite::std_string_to_int(const std::string& str)
{
long val;
char *end = NULL;
val = strtol(str.c_str(), &end, 10);
// if (!end || *end != '\0')
// error;
return val;
}
//---------------------------------------------------------------------------
size_t SQLLite::std_string_to_uint(const std::string& str)
{
size_t val;
char *end = NULL;
val = strtoul(str.c_str(), &end, 10);
// if (!end || *end != '\0')
// error;
return val;
}
//---------------------------------------------------------------------------
int SQLLite::get_db_version(int& version)
{
reports.clear();
query = std::string("PRAGMA user_version;");
const char* end = NULL;
int ret = sqlite3_prepare_v2(db, query.c_str(), query.length() + 1, &stmt, &end);
if (ret != SQLITE_OK || !stmt || (end && *end))
return -1;
if (execute() < 0 || reports.size() != 1 || reports[0].find("user_version") == reports[0].end())
return -1;
version = std_string_to_int(reports[0]["user_version"]);
return 0;
}
//---------------------------------------------------------------------------
int SQLLite::set_db_version(int version)
{
reports.clear();
std::stringstream create;
create << "PRAGMA user_version=" << version << ";";
query = create.str();
std::string err;
if (prepare_v2(query, err) < 0)
return -1;
if (execute() < 0)
return -1;
return 0;
}
//---------------------------------------------------------------------------
const std::string& SQLLite::get_error() const
{
return error;
}
//---------------------------------------------------------------------------
std::string SQLLite::get_sqlite_error(int err)
{
#if SQLITE_VERSION_NUMBER >= 3007015
return sqlite3_errstr(err);
#else
return "An error occurs during execution";
#endif
}
//---------------------------------------------------------------------------
int SQLLite::prepare_v2(std::string& query, std::string& err)
{
const char* end = NULL;
int ret = sqlite3_prepare_v2(db, query.c_str(), query.length() + 1, &stmt, &end);
if (ret != SQLITE_OK || !stmt || (end && *end))
{
if (ret != SQLITE_OK)
err = get_sqlite_error(ret);
else
err = "Internal error when creating SQLLite query.";
return -1;
}
return 0;
}
}
#endif
| 27.715686
| 101
| 0.380969
|
g-maxime
|
5bc573c332ca4045f7adfd8ab675411288b4498c
| 1,446
|
cpp
|
C++
|
sample/core/platform_linux.cpp
|
asmwarrior/syncpp
|
df34b95b308d7f2e6479087d629017efa7ab9f1f
|
[
"Apache-2.0"
] | 1
|
2019-02-08T02:23:56.000Z
|
2019-02-08T02:23:56.000Z
|
sample/core/platform_linux.cpp
|
asmwarrior/syncpp
|
df34b95b308d7f2e6479087d629017efa7ab9f1f
|
[
"Apache-2.0"
] | null | null | null |
sample/core/platform_linux.cpp
|
asmwarrior/syncpp
|
df34b95b308d7f2e6479087d629017efa7ab9f1f
|
[
"Apache-2.0"
] | 1
|
2020-12-02T02:37:40.000Z
|
2020-12-02T02:37:40.000Z
|
/*
* Copyright 2014 Anton Karmanov
*
* 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.
*/
//Linux platform-dependent functions.
#include <chrono>
#include <ctime>
#include "platform.h"
namespace ss = syn_script;
namespace pf = ss::platform;
pf::Tick_t pf::get_current_tick_count() {
return get_current_time_millis();
}
pf::TimeMs_t pf::get_current_time_millis() {
auto now = std::chrono::system_clock::now();
auto time = now.time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(time).count();
}
void pf::get_current_time(DateTime& date_time) {
std::time_t time = std::time(nullptr);
//TODO This function is not thread-safe. Add synchronization.
struct std::tm* tm = localtime(&time);
date_time.m_year = tm->tm_year + 1900;
date_time.m_month = tm->tm_mon;
date_time.m_day = tm->tm_mday;
date_time.m_hour = tm->tm_hour;
date_time.m_minute = tm->tm_min;
date_time.m_second = tm->tm_sec;
}
| 28.92
| 76
| 0.731674
|
asmwarrior
|
5bd47017867bcd285918ffdad213aa1e03095a8a
| 4,413
|
cpp
|
C++
|
Library_MMDFiles/src/lib/SystemTexture.cpp
|
ChaseBro/MMDAgent
|
779cd3035954c27016333a2186896e1870e9ee54
|
[
"Libpng",
"Zlib",
"Unlicense"
] | 9
|
2017-08-17T01:01:55.000Z
|
2022-02-02T09:50:09.000Z
|
Library_MMDFiles/src/lib/SystemTexture.cpp
|
ChaseBro/MMDAgent
|
779cd3035954c27016333a2186896e1870e9ee54
|
[
"Libpng",
"Zlib",
"Unlicense"
] | null | null | null |
Library_MMDFiles/src/lib/SystemTexture.cpp
|
ChaseBro/MMDAgent
|
779cd3035954c27016333a2186896e1870e9ee54
|
[
"Libpng",
"Zlib",
"Unlicense"
] | 4
|
2017-08-17T01:01:57.000Z
|
2021-06-28T08:30:17.000Z
|
/* ----------------------------------------------------------------- */
/* The Toolkit for Building Voice Interaction Systems */
/* "MMDAgent" developed by MMDAgent Project Team */
/* http://www.mmdagent.jp/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 2009-2011 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* 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 MMDAgent project team nor the names of */
/* its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */
/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */
/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY */
/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* ----------------------------------------------------------------- */
/* headers */
#include "MMDFiles.h"
/* SystemTexture::initialize: initialize SystemTexture */
void SystemTexture::initialize()
{
int i;
for (i = 0; i < SYSTEMTEXTURE_NUMFILES; i++)
m_toonTextureID[i] = 0;
}
/* SystemTexture::clear: free SystemTexutre */
void SystemTexture::clear()
{
int i;
for (i = 0; i < SYSTEMTEXTURE_NUMFILES; i++)
m_toonTexture[i].release();
initialize();
}
/* SystemTexture::SystemTexutre: constructor */
SystemTexture::SystemTexture()
{
initialize();
}
/* SystemTexture::SystemTexutre:: destructor */
SystemTexture::~SystemTexture()
{
clear();
}
/* SystemTexture::load: load system texture from current directory */
bool SystemTexture::load(const char *dir)
{
int i;
bool ret = true;
const char *files[] = {SYSTEMTEXTURE_FILENAMES};
char buff[MMDFILES_MAXBUFLEN];
for (i = 0; i < SYSTEMTEXTURE_NUMFILES; i++) {
if (MMDFiles_strlen(dir) > 0)
sprintf(buff, "%s%c%s", dir, MMDFILES_DIRSEPARATOR, files[i]);
else
strcpy(buff, files[i]);
if (m_toonTexture[i].load(buff) == false)
ret = false;
m_toonTextureID[i] = m_toonTexture[i].getID();
}
return ret;
}
/* SystemTexture::getTextureID: get toon texture ID */
unsigned int SystemTexture::getTextureID(int i)
{
return m_toonTextureID[i];
}
/* SystemTexture::release: free SystemTexture */
void SystemTexture::release()
{
clear();
}
| 40.486239
| 72
| 0.519828
|
ChaseBro
|
5bd4bd0aa8ce443818d66072937e9145f4401d00
| 456
|
cpp
|
C++
|
AED 1/Prova 2/questao 1.cpp
|
andreflabr/EstudoCC
|
b89aa2dbe48cc8adeef1c955cd4f7775705f70e4
|
[
"MIT"
] | null | null | null |
AED 1/Prova 2/questao 1.cpp
|
andreflabr/EstudoCC
|
b89aa2dbe48cc8adeef1c955cd4f7775705f70e4
|
[
"MIT"
] | null | null | null |
AED 1/Prova 2/questao 1.cpp
|
andreflabr/EstudoCC
|
b89aa2dbe48cc8adeef1c955cd4f7775705f70e4
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
int main(){
double matriz[4][3], vetor[12];
int l, c, i=0;
for(l=0; l<4; l++){
for(c=0; c<3; c++){
scanf("%lf", &matriz[l][c]);
}
}
do{
for(l=0; l<4; l++){
for(c=0; c<3; c++){
vetor[i] = matriz[l][c];
printf("Vetor[%d] = %.1lf\n", i, vetor[i]);
i++;
}
}
}while(i<12);
return 0;
}
| 18.24
| 59
| 0.335526
|
andreflabr
|
5bd797bf482abadf0245f37962583fdb384dc2bd
| 711
|
cpp
|
C++
|
the-most-frequent.cpp
|
vargad/multi_target_cmake_project_example
|
c0d57ad498addd161ee852462ad70e7ae7822fc9
|
[
"MIT"
] | null | null | null |
the-most-frequent.cpp
|
vargad/multi_target_cmake_project_example
|
c0d57ad498addd161ee852462ad70e7ae7822fc9
|
[
"MIT"
] | null | null | null |
the-most-frequent.cpp
|
vargad/multi_target_cmake_project_example
|
c0d57ad498addd161ee852462ad70e7ae7822fc9
|
[
"MIT"
] | null | null | null |
// 2018 Daniel Varga (vargad88@gmail.com)
#include <list>
#include <vector>
#include <iostream>
#include <map>
#include <algorithm>
template <typename Container>
typename Container::value_type most_frequent(const Container &container) {
std::map<typename Container::value_type, std::size_t> counter;
for (auto const &elem : container) counter[elem]++;
return std::max_element(counter.begin(), counter.end(), [](auto const &lhs, auto const &rhs) { return lhs.second < rhs.second; })->first;
}
int main()
{
std::vector<int> v = { 1, 1, 3, 1, 1, 1, 2 };
std::cout << most_frequent(v) << std::endl;
std::cout << most_frequent(std::list<int>{2,2,2,3,4,5,6}) << std::endl;
return 0;
}
| 29.625
| 141
| 0.661041
|
vargad
|
5bd8757aeda5bc7d5dd2581d070dfa15bf13f5f3
| 526
|
cpp
|
C++
|
034/test/tst_remove_blank_line.cpp
|
Ponz-Tofu-N/ModernCppChallengePractice
|
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
|
[
"MIT"
] | null | null | null |
034/test/tst_remove_blank_line.cpp
|
Ponz-Tofu-N/ModernCppChallengePractice
|
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
|
[
"MIT"
] | null | null | null |
034/test/tst_remove_blank_line.cpp
|
Ponz-Tofu-N/ModernCppChallengePractice
|
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include "../remove_blank_line.h"
#include <fstream>
TEST(removeBlankLine, removeBlankLine)
{
std::string input("test.txt");
std::string output("test_out.txt");
removeBlankLines(input, output);
std::ifstream ifs_expected("test_expected.txt");
std::ifstream ifs_out(output);
EXPECT_TRUE(ifs_out.is_open());
for(std::string line, line_exp; std::getline(ifs_out, line); )
{
std::getline(ifs_expected, line_exp);
EXPECT_EQ(line, line_exp);
}
}
| 22.869565
| 66
| 0.663498
|
Ponz-Tofu-N
|
5bd93fc105bc08eef633d8ccb9e46ff34dc5d018
| 883
|
cpp
|
C++
|
Week_0/Ans1.cpp
|
s1orm/DAA-Lab-Assignment
|
47c3ec23fbc6da60c225a26abf9a13839db4c12d
|
[
"MIT"
] | null | null | null |
Week_0/Ans1.cpp
|
s1orm/DAA-Lab-Assignment
|
47c3ec23fbc6da60c225a26abf9a13839db4c12d
|
[
"MIT"
] | null | null | null |
Week_0/Ans1.cpp
|
s1orm/DAA-Lab-Assignment
|
47c3ec23fbc6da60c225a26abf9a13839db4c12d
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<fstream>
using namespace std;
void linear_search(int *a,int n,int ele)
{
int count=0,f=0;
fstream output;
output.open("ouput.txt",ios::app);
for(int i=0;i<n;i++)
{ count++;
if(a[i]==ele)
{
f=1;
break;
}
}
if(f==1)
output<<"Present!\n"<<count<<" times compared!"<<endl;
else
output<<"Not Present!\n"<<count<<" times compared!"<<endl;
output.close();
}
int main()
{
fstream input;
input.open("input.txt", ios::in);
if(!input)
{
cout<<"Invalid file!";
exit(1);
}
int t,n,ele;
input>>t;
while(t--)
{
input>>n;
int a[n];
for(int i=0;i<n;i++)
input>>a[i];
input>>ele;
linear_search(a,n,ele);
}
input.close();
return 0;
}
| 14.241935
| 62
| 0.463194
|
s1orm
|
5becbb836dbdd329dba6bf395945f62d35e6e6bf
| 6,803
|
cpp
|
C++
|
core/connections/wim/events/fetch_event_dlg_state.cpp
|
Vavilon3000/icq
|
9fe7a3c42c07eb665d2e3b0ec50052de382fd89c
|
[
"Apache-2.0"
] | 1
|
2021-03-18T20:00:07.000Z
|
2021-03-18T20:00:07.000Z
|
core/connections/wim/events/fetch_event_dlg_state.cpp
|
Vavilon3000/icq
|
9fe7a3c42c07eb665d2e3b0ec50052de382fd89c
|
[
"Apache-2.0"
] | null | null | null |
core/connections/wim/events/fetch_event_dlg_state.cpp
|
Vavilon3000/icq
|
9fe7a3c42c07eb665d2e3b0ec50052de382fd89c
|
[
"Apache-2.0"
] | null | null | null |
#include "stdafx.h"
#include "fetch_event_dlg_state.h"
#include "../wim_history.h"
#include "../wim_im.h"
#include "../wim_packet.h"
#include "../../../archive/archive_index.h"
#include "../../../log/log.h"
using namespace core;
using namespace wim;
fetch_event_dlg_state::fetch_event_dlg_state()
: tail_messages_(std::make_shared<archive::history_block>())
, intro_messages_(std::make_shared<archive::history_block>())
{
}
fetch_event_dlg_state::~fetch_event_dlg_state()
{
}
template <typename T>
int64_t get_older_msg_id(const T& value)
{
const auto iter_older_msgid = value.FindMember("olderMsgId");
if (iter_older_msgid != value.MemberEnd() && iter_older_msgid->value.IsInt64())
return iter_older_msgid->value.GetInt64();
return -1;
}
int32_t fetch_event_dlg_state::parse(const rapidjson::Value& _node_event_data)
{
const auto iter_sn = _node_event_data.FindMember("sn");
const auto iter_last_msg_id = _node_event_data.FindMember("lastMsgId");
if (
iter_sn == _node_event_data.MemberEnd() ||
iter_last_msg_id == _node_event_data.MemberEnd() ||
!iter_sn->value.IsString() ||
!iter_last_msg_id->value.IsInt64())
{
__TRACE(
"delivery",
"%1%",
"failed to parse incoming dlg state event");
return wpie_error_parse_response;
}
aimid_ = rapidjson_get_string(iter_sn->value);
state_.set_last_msgid(iter_last_msg_id->value.GetInt64());
const auto iter_unread_count = _node_event_data.FindMember("unreadCnt");
if (iter_unread_count != _node_event_data.MemberEnd() && iter_unread_count->value.IsUint())
state_.set_unread_count(iter_unread_count->value.GetUint());
const auto iter_mme_count = _node_event_data.FindMember("unreadMentionMeCount");
if (iter_mme_count != _node_event_data.MemberEnd() && iter_mme_count->value.IsUint())
state_.set_unread_mentions_count(iter_mme_count->value.GetInt());
const auto iter_yours = _node_event_data.FindMember("yours");
if (iter_yours != _node_event_data.MemberEnd() && iter_yours->value.IsObject())
{
auto iter_last_read = iter_yours->value.FindMember("lastRead");
if (iter_last_read != iter_yours->value.MemberEnd() && iter_last_read->value.IsInt64())
state_.set_yours_last_read(iter_last_read->value.GetInt64());
}
const auto iter_theirs = _node_event_data.FindMember("theirs");
if (iter_theirs != _node_event_data.MemberEnd() && iter_theirs->value.IsObject())
{
const auto iter_last_read = iter_theirs->value.FindMember("lastRead");
if (iter_last_read != iter_theirs->value.MemberEnd() && iter_last_read->value.IsInt64())
state_.set_theirs_last_read(iter_last_read->value.GetInt64());
const auto iter_last_delivered = iter_theirs->value.FindMember("lastDelivered");
if (iter_last_delivered != iter_theirs->value.MemberEnd() && iter_last_delivered->value.IsInt64())
state_.set_theirs_last_delivered(iter_last_delivered->value.GetInt64());
}
const auto iter_patch_version = _node_event_data.FindMember("patchVersion");
if (iter_patch_version != _node_event_data.MemberEnd())
{
std::string patch_version = rapidjson_get_string(iter_patch_version->value);
assert(!patch_version.empty());
state_.set_dlg_state_patch_version(std::move(patch_version));
}
const auto iter_del_up_to = _node_event_data.FindMember("delUpto");
if ((iter_del_up_to != _node_event_data.MemberEnd()) &&
iter_del_up_to->value.IsInt64())
{
state_.set_del_up_to(iter_del_up_to->value.GetInt64());
}
const core::archive::persons_map persons = parse_persons(_node_event_data);
const auto iter_tail = _node_event_data.FindMember("tail");
if (iter_tail != _node_event_data.MemberEnd() && iter_tail->value.IsObject())
{
const int64_t older_msg_id = get_older_msg_id(iter_tail->value);
if (!parse_history_messages_json(iter_tail->value, older_msg_id, aimid_, *tail_messages_, persons, message_order::reverse))
{
__TRACE(
"delivery",
"%1%",
"failed to parse incoming tail dlg state messages");
return wpie_error_parse_response;
}
}
const auto iter_intro = _node_event_data.FindMember("intro");
if (iter_intro != _node_event_data.MemberEnd() && iter_intro->value.IsObject())
{
const int64_t older_msg_id = get_older_msg_id(iter_intro->value);
if (!parse_history_messages_json(iter_intro->value, older_msg_id, aimid_, *intro_messages_, persons, message_order::direct))
{
__TRACE(
"delivery",
"%1%",
"failed to parse incoming intro dlg state messages");
return wpie_error_parse_response;
}
}
auto iter_person = persons.find(aimid_);
if (iter_person != persons.end())
{
state_.set_friendly(iter_person->second.friendly_);
state_.set_official(iter_person->second.official_);
}
if (::build::is_debug())
{
__INFO(
"delete_history",
"incoming dlg state event\n"
" contact=<%1%>\n"
" dlg-patch=<%2%>\n"
" del-up-to=<%3%>",
aimid_ % state_.get_dlg_state_patch_version() % state_.get_del_up_to()
);
__TRACE(
"delivery",
"parsed incoming tail dlg state event\n"
" size=<%1%>\n"
" last_msgid=<%2%>",
tail_messages_->size() %
state_.get_last_msgid());
__TRACE(
"delivery",
"parsed incoming intro dlg state event\n"
" size=<%1%>\n"
" last_msgid=<%2%>",
intro_messages_->size() %
state_.get_last_msgid());
for (const auto &message : *tail_messages_)
{
__TRACE(
"delivery",
"parsed incoming tail dlg state message\n"
" id=<%1%>",
message->get_msgid());
}
for (const auto &message : *intro_messages_)
{
__TRACE(
"delivery",
"parsed incoming intro dlg state message\n"
" id=<%1%>",
message->get_msgid());
}
}
return 0;
}
void fetch_event_dlg_state::on_im(std::shared_ptr<core::wim::im> _im, std::shared_ptr<auto_callback> _on_complete)
{
_im->on_event_dlg_state(this, _on_complete);
}
| 35.248705
| 133
| 0.616346
|
Vavilon3000
|
5bf097c4645bca073b693575d5dee8489b555aeb
| 2,178
|
cc
|
C++
|
moui/core/android/application_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 59
|
2015-01-23T01:02:50.000Z
|
2021-11-26T00:01:45.000Z
|
moui/core/android/application_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 2
|
2017-05-26T15:26:24.000Z
|
2020-09-25T03:54:01.000Z
|
moui/core/android/application_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 7
|
2015-09-25T08:09:20.000Z
|
2019-11-24T15:24:28.000Z
|
// Copyright (c) 2014 Ollix. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#include "moui/core/application.h"
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include "aasset.h" // NOLINT
#include "jni.h" // NOLINT
#include "moui/core/base_application.h"
#include "moui/core/device.h"
#include "moui/core/path.h"
namespace {
JavaVM* java_vm = nullptr;
JNIEnv* jni_env = nullptr;
jobject main_activity = nullptr;
} // namespace
namespace moui {
void Application::InitJNI(JNIEnv* env, jobject activity,
jobject asset_manager) {
if (env == jni_env && activity == main_activity) {
return;
}
if (main_activity != nullptr && env == jni_env) {
env->DeleteGlobalRef(main_activity);
}
jni_env = env;
env->GetJavaVM(&java_vm);
main_activity = reinterpret_cast<jobject>(env->NewGlobalRef(activity));
// Initializes the aasset library.
aasset_init(AAssetManager_fromJava(env, asset_manager));
// Initializes classes.
Device::Init();
Path::Init();
}
void Application::RegisterApp(jobject moui_fragment) {
jclass clazz = jni_env->GetObjectClass(moui_fragment);
jmethodID method = jni_env->GetMethodID(
clazz, "registerMainApplicationFromJNI", "(J)V");
jni_env->CallVoidMethod(moui_fragment, method,
reinterpret_cast<jlong>(Application::GetMainApplication()));
}
JNIEnv* Application::GetJNIEnv() {
JNIEnv* env;
java_vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
return env;
}
jobject Application::GetMainActivity() {
return main_activity;
}
} // namespace moui
| 26.888889
| 75
| 0.714876
|
ollix
|
5bf28511cae1daca6a315cdb69061cb14d4a3c28
| 8,293
|
cpp
|
C++
|
v-spmines/Script.cpp
|
root-cause/v-spmines
|
d62decaf0bafd540067159078de6d509dffae221
|
[
"MIT"
] | null | null | null |
v-spmines/Script.cpp
|
root-cause/v-spmines
|
d62decaf0bafd540067159078de6d509dffae221
|
[
"MIT"
] | null | null | null |
v-spmines/Script.cpp
|
root-cause/v-spmines
|
d62decaf0bafd540067159078de6d509dffae221
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Script.h"
std::unordered_map<Hash, MineSetData> g_mineSets;
std::unordered_map<Hash, Hash> g_vehicleModels; /* VehicleModelHash, MineSetNameHash */
int g_lastMineDrop;
void LoadModel(Hash modelHash)
{
if (!STREAMING::IS_MODEL_VALID(modelHash))
{
return;
}
STREAMING::REQUEST_MODEL(modelHash);
while (!STREAMING::HAS_MODEL_LOADED(modelHash)) WAIT(0);
}
// From 1868 decompiled scripts
Vector3 func_8595(const Vector3& vParam0, const Vector3& vParam1, float fParam2, float fParam3, float fParam4)
{
return Vector3{
// x
func_8596(vParam0.x, vParam1.x, fParam2, fParam3, fParam4),
0,
// y
func_8596(vParam0.y, vParam1.y, fParam2, fParam3, fParam4),
0,
// z
func_8596(vParam0.z, vParam1.z, fParam2, fParam3, fParam4),
0
};
}
float func_8596(float fParam0, float fParam1, float fParam2, float fParam3, float fParam4)
{
return (fParam1 - fParam0) / (fParam3 - fParam2) * (fParam4 - fParam2) + fParam0;
}
void func_8597(Vehicle vehicleEntity, Hash vehicleModel, Vector3& uParam2, Vector3& uParam3, Vector3& uParam4, Vector3& uParam5)
{
Vector3 min, max;
MISC::GET_MODEL_DIMENSIONS(vehicleModel, &min, &max);
uParam2 = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(vehicleEntity, min.x, max.y, min.z);
uParam3 = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(vehicleEntity, max.x, max.y, min.z);
uParam4 = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(vehicleEntity, min.x, min.y, min.z);
uParam5 = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(vehicleEntity, max.x, min.y, min.z);
}
// Blades?
bool func_8651(Vehicle vehicleEntity, Hash vehicleModel)
{
if (!ENTITY::DOES_ENTITY_EXIST(vehicleEntity))
{
return false;
}
bool isSpecial = false;
switch (vehicleModel)
{
case joaat::generate("zr380"):
case joaat::generate("zr3802"):
case joaat::generate("zr3803"):
case joaat::generate("deathbike"):
case joaat::generate("deathbike2"):
case joaat::generate("deathbike3"):
case joaat::generate("imperator"):
case joaat::generate("imperator2"):
case joaat::generate("imperator3"):
case joaat::generate("slamvan4"):
case joaat::generate("slamvan5"):
case joaat::generate("slamvan6"):
isSpecial = true;
break;
}
return isSpecial && VEHICLE::GET_VEHICLE_MOD(vehicleEntity, 44) > -1;
}
void ScriptInit()
{
#ifdef MOD_DEBUG
ScriptLog.SetLogLevel(LogLevel::LOG_DEBUG);
#endif
// Reset globals
g_mineSets.clear();
g_vehicleModels.clear();
g_lastMineDrop = 0;
fs::path dataFilePath = fs::current_path().append(fmt::format("{}.xml", MOD_NAME));
ScriptLog.Write(LogLevel::LOG_DEBUG, fmt::format("Data path: {}", dataFilePath.generic_string()));
// Load data
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(dataFilePath.c_str());
if (result)
{
// Load ptfx assets
ScriptLog.Write(LogLevel::LOG_DEBUG, "========== LOADING PTFX ASSETS ==========");
for (pugi::xpath_node ptfx : doc.select_nodes("//ParticleFxAssets/Item"))
{
pugi::xml_node node = ptfx.node();
STREAMING::REQUEST_NAMED_PTFX_ASSET(node.text().as_string());
ScriptLog.Write(LogLevel::LOG_DEBUG, fmt::format("Requested {}.", node.text().as_string()));
}
// Load mine sets
ScriptLog.Write(LogLevel::LOG_DEBUG, "========== LOADING MINESETS ==========");
for (pugi::xpath_node set : doc.select_nodes("//MineSets/Set"))
{
pugi::xml_node node = set.node();
pugi::xml_attribute name = node.attribute("name");
pugi::xml_attribute model = node.attribute("model");
if (name.empty() || model.empty())
{
ScriptLog.Write(LogLevel::LOG_ERROR, fmt::format("A MineSets node did not have a name or model (at {}), skipping it.", node.offset_debug()));
continue;
}
Hash setHash = joaat::generate(name.value());
if (g_mineSets.find(setHash) != g_mineSets.end())
{
ScriptLog.Write(LogLevel::LOG_ERROR, fmt::format("A MineSet node ({}) is defined already, skipping it.", name.value()));
continue;
}
Hash modelHash = joaat::generate(model.value());
if (!STREAMING::IS_MODEL_VALID(modelHash))
{
ScriptLog.Write(LogLevel::LOG_ERROR, fmt::format("A MineSet node ({}) has an invalid model ({}), skipping it.", name.value(), model.value()));
continue;
}
MineSetData& data = g_mineSets[setHash];
data.model = modelHash;
for (pugi::xml_node setItem : node.children("Item"))
{
data.weaponHashes.push_back(joaat::generate(setItem.text().as_string()));
ScriptLog.Write(LogLevel::LOG_DEBUG, fmt::format("Added {} to {}.", setItem.text().as_string(), name.value()));
}
ScriptLog.Write(LogLevel::LOG_DEBUG, fmt::format("Loaded set: {}, model: {}, items: {}.", name.value(), model.value(), data.weaponHashes.size()));
}
ScriptLog.Write(LogLevel::LOG_INFO, fmt::format("Loaded {} mine sets.", g_mineSets.size()));
// Load vehicle models
ScriptLog.Write(LogLevel::LOG_DEBUG, "========== LOADING VEHICLEMODELS ==========");
for (pugi::xpath_node model : doc.select_nodes("//VehicleModels/Model"))
{
pugi::xml_node node = model.node();
pugi::xml_attribute name = node.attribute("name");
pugi::xml_attribute mineSet = node.attribute("mineSet");
if (name.empty() || mineSet.empty())
{
ScriptLog.Write(LogLevel::LOG_ERROR, fmt::format("A VehicleModels node did not have a name or mineSet (at {}), skipping it.", node.offset_debug()));
continue;
}
Hash setHash = joaat::generate(mineSet.value());
if (g_mineSets.find(setHash) == g_mineSets.end())
{
ScriptLog.Write(LogLevel::LOG_ERROR, fmt::format("A VehicleModels node ({}) contains an invalid mineSet ({}), skipping it.", name.value(), mineSet.value()));
continue;
}
g_vehicleModels[ joaat::generate(name.value()) ] = setHash;
ScriptLog.Write(LogLevel::LOG_DEBUG, fmt::format("Loaded vehicle: {}, mineSet: {}.", name.value(), mineSet.value()));
}
ScriptLog.Write(LogLevel::LOG_INFO, fmt::format("Loaded {} vehicle models.", g_vehicleModels.size()));
}
else
{
ScriptLog.Write(LogLevel::LOG_ERROR, fmt::format("Failed to load data: {}", result.description()));
return;
}
// Start script loop
while (true)
{
ScriptUpdate();
WAIT(0);
}
}
void ScriptUpdate()
{
Ped playerPed = PLAYER::PLAYER_PED_ID();
if (HUD::IS_PAUSE_MENU_ACTIVE() || !PED::IS_PED_IN_ANY_VEHICLE(playerPed, false))
{
return;
}
Vehicle currentVehicle = PED::GET_VEHICLE_PED_IS_USING(playerPed);
if (!VEHICLE::IS_VEHICLE_DRIVEABLE(currentVehicle, false) || VEHICLE::GET_PED_IN_VEHICLE_SEAT(currentVehicle, -1, 0) != playerPed)
{
return;
}
Hash vehicleModel = ENTITY::GET_ENTITY_MODEL(currentVehicle);
if (g_vehicleModels.find(vehicleModel) == g_vehicleModels.end())
{
return;
}
int currentProxMine = VEHICLE::GET_VEHICLE_MOD(currentVehicle, 9);
const MineSetData& currentMineSet = g_mineSets[ g_vehicleModels[vehicleModel] ];
if (currentProxMine == -1 || currentProxMine >= currentMineSet.weaponHashes.size())
{
return;
}
if (!ENTITY::IS_ENTITY_UPRIGHT(currentVehicle, 90.0f) || !VEHICLE::IS_VEHICLE_ON_ALL_WHEELS(currentVehicle) || ENTITY::IS_ENTITY_UPSIDEDOWN(currentVehicle))
{
return;
}
PAD::DISABLE_CONTROL_ACTION(0, INPUT_VEH_HORN, true);
int gameTime = MISC::GET_GAME_TIMER();
if (PAD::IS_DISABLED_CONTROL_JUST_PRESSED(0, INPUT_VEH_HORN) && (gameTime - g_lastMineDrop) >= MineCooldown)
{
g_lastMineDrop = gameTime;
LoadModel(currentMineSet.model);
Vector3 vVar3, vVar4, vVar5, vVar6;
func_8597(currentVehicle, vehicleModel, vVar3, vVar4, vVar5, vVar6);
Vector3 vVar7 = func_8595(vVar3, vVar4, 0.0f, 1.0f, 0.5f);
Vector3 vVar8 = func_8595(vVar5, vVar6, 0.0f, 1.0f, 0.5f);
vVar7.z += 0.2f;
vVar8.z += 0.2f;
float fVar9 = (vehicleModel == joaat::generate("speedo4") || func_8651(currentVehicle, vehicleModel)) ? 1.0f : 0.7f;
Vector3 vVar10 = func_8595(vVar7, vVar8, 0.0f, 1.0f, fVar9);
vVar7.z -= 0.2f;
vVar8.z -= 0.2f;
Vector3 vVar11 = func_8595(vVar7, vVar8, 0.0f, 1.0f, fVar9 + 0.1f);
MISC::SHOOT_SINGLE_BULLET_BETWEEN_COORDS_IGNORE_ENTITY_NEW(
vVar10.x, vVar10.y, vVar10.z,
vVar11.x, vVar11.y, vVar11.z,
0,
1,
currentMineSet.weaponHashes[currentProxMine],
playerPed,
1,
1,
-1.0f,
0,
0,
0,
0,
1,
1,
false
);
STREAMING::SET_MODEL_AS_NO_LONGER_NEEDED(currentMineSet.model);
}
}
| 30.377289
| 161
| 0.6942
|
root-cause
|
5bf394fb0e7019ce8c0d0691770698b7799a97f9
| 5,131
|
cpp
|
C++
|
modules/examples/ex-exposure_times.cpp
|
theseankelly/libo3d3xx
|
01cdf9560d69b1ee91ca9b4298df7bb4efb45e52
|
[
"Apache-2.0"
] | 36
|
2015-04-04T15:19:50.000Z
|
2018-10-11T14:33:05.000Z
|
modules/examples/ex-exposure_times.cpp
|
theseankelly/libo3d3xx
|
01cdf9560d69b1ee91ca9b4298df7bb4efb45e52
|
[
"Apache-2.0"
] | 111
|
2015-04-22T16:12:55.000Z
|
2018-10-16T08:03:40.000Z
|
modules/examples/ex-exposure_times.cpp
|
theseankelly/libo3d3xx
|
01cdf9560d69b1ee91ca9b4298df7bb4efb45e52
|
[
"Apache-2.0"
] | 40
|
2015-07-13T09:29:31.000Z
|
2018-09-14T06:56:24.000Z
|
/*
* Copyright (C) 2016 Love Park Robotics, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distribted 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.
*/
//
// ex-exposure_times.cpp
//
// Shows how to change imager exposure times on the fly while streaming in
// pixel data and validating the setting of the exposure times registered to
// the frame data.
//
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <o3d3xx_camera.h>
#include <o3d3xx_framegrabber.h>
#include <o3d3xx_image.h>
int main(int argc, const char **argv)
{
o3d3xx::Logging::Init();
// example configuration for the camera we will use for exemplary purpose
// we will use a double exposure imager.
std::string json =
R"(
{
"o3d3xx":
{
"Device":
{
"ActiveApplication": "1"
},
"Apps":
[
{
"TriggerMode": "1",
"Index": "1",
"Imager":
{
"ExposureTime": "5000",
"ExposureTimeList": "125;5000",
"ExposureTimeRatio": "40",
"Type":"under5m_moderate"
}
}
]
}
}
)";
// instantiate the camera and set the configuration
o3d3xx::Camera::Ptr cam = std::make_shared<o3d3xx::Camera>();
std::cout << "Setting camera configuration: " << std::endl
<< json << std::endl;
cam->FromJSON(json);
// create our image buffer to hold frame data from the camera
o3d3xx::ImageBuffer::Ptr img = std::make_shared<o3d3xx::ImageBuffer>();
// instantiate our framegrabber and be sure to explicitly tell it to
// stream back the exposure times registered to the frame data
o3d3xx::FrameGrabber::Ptr fg =
std::make_shared<o3d3xx::FrameGrabber>(
cam, o3d3xx::DEFAULT_SCHEMA_MASK|o3d3xx::EXP_TIME);
// a vector to hold the exposure times (we will just print them to the
// screen)
std::vector<std::uint32_t> exposure_times;
// a map use to modulate the `ExposureTime` and `ExposureTimeRatio`
// on-the-fly. We seed it with data consistent with our config above
std::unordered_map<std::string, std::string> params =
{
{"imager_001/ExposureTime", "5000"},
{"imager_001/ExposureTimeRatio", "40"}
};
// create a session with the camera so we can modulate the exposure times
cam->RequestSession();
// set our session timeout --
//
// NOTE: I'm going to do nothing with this here. However, in a *real*
// application, you will have to send `Heartbeats` at least every `hb_secs`
// seconds to the camera. The best technique for doing that is left as an
// exercise for the reader.
int hb_secs = cam->Heartbeat(300);
// now we start looping over the image data, every 20 frames, we will
// change the exposure times, after 100 frames we will exit.
int i = 0;
while (true)
{
if (! fg->WaitForFrame(img.get(), 1000))
{
std::cerr << "Timeout waiting for camera!" << std::endl;
continue;
}
// get the exposure times registered to the frame data
exposure_times = img->ExposureTimes();
// depending on your imager config, you can have up to 3 exposure
// times. I'll print all three for exemplary purposes, but we know there
// are only two valid ones based on our double exposure imager
// configuration from above. We expect the third to be 0.
std::cout << "Exposure Time 0: " << exposure_times.at(0)
<< std::endl;
std::cout << "Exposure Time 1: " << exposure_times.at(1)
<< std::endl;
std::cout << "Exposure Time 2: " << exposure_times.at(2)
<< std::endl;
std::cout << "---" << std::endl;
i++;
if (i == 100)
{
break;
}
if (i % 20 == 0)
{
std::cout << "Setting long exposure time to: ";
if (exposure_times.at(1) == 5000)
{
std::cout << 10000 << std::endl;
params["ExposureTime"] = "10000";
}
else
{
std::cout << 5000 << std::endl;
params["ExposureTime"] = "5000";
}
cam->SetTemporaryApplicationParameters(params);
}
}
//
// In a long-running program, you will need to take care to
// clean up your session if necessary. Here we don't worry about it because
// the camera dtor will do that for us.
//
std::cout << "et voila." << std::endl;
return 0;
}
| 31.09697
| 78
| 0.593841
|
theseankelly
|
7500b589ab3b087506e3d46219a259dafec3b726
| 2,174
|
cpp
|
C++
|
Nova/Nova/Platform/OpenGLBuffer.cpp
|
Aaron-Berland/Nova
|
1b8587548c58adda27bd2b699bf4229e18f30e13
|
[
"Apache-2.0"
] | null | null | null |
Nova/Nova/Platform/OpenGLBuffer.cpp
|
Aaron-Berland/Nova
|
1b8587548c58adda27bd2b699bf4229e18f30e13
|
[
"Apache-2.0"
] | null | null | null |
Nova/Nova/Platform/OpenGLBuffer.cpp
|
Aaron-Berland/Nova
|
1b8587548c58adda27bd2b699bf4229e18f30e13
|
[
"Apache-2.0"
] | null | null | null |
#include "OpenGLBuffer.h"
#include <glad/glad.h>
namespace Nova
{
unsigned int BufferTypeToOpenGLEnum(BufferType type)
{
switch (type)
{
case Nova::BufferType::StaticDraw:
return GL_STATIC_DRAW;
case Nova::BufferType::DynamicDraw:
return GL_DYNAMIC_DRAW;
case Nova::BufferType::StreamDraw:
return GL_STREAM_DRAW;
default:
return GL_STATIC_DRAW;
}
}
OpenGLVertexBuffer::OpenGLVertexBuffer(const void* data, unsigned int size, const BufferLayout &layout, BufferType type) : m_layout(layout), m_openGLDrawType(BufferTypeToOpenGLEnum(type))
{
glCreateBuffers(1, &m_bufferID);
UpdateData(data, size);
}
OpenGLVertexBuffer::~OpenGLVertexBuffer()
{
glDeleteBuffers(1, &m_bufferID);
}
void OpenGLVertexBuffer::Bind() const
{
glBindBuffer(GL_ARRAY_BUFFER, m_bufferID);
}
void OpenGLVertexBuffer::Unbind() const
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void OpenGLVertexBuffer::UpdateData(const void* data, unsigned int size)
{
glNamedBufferData(m_bufferID, size, data, m_openGLDrawType);
}
void OpenGLVertexBuffer::UpdateSubData(const void* data, unsigned int size, unsigned int offset)
{
glNamedBufferSubData(m_bufferID, offset, size, data);
}
OpenGLIndexBuffer::OpenGLIndexBuffer(const unsigned int* data, unsigned int count, BufferType type) : m_openGLDrawType(BufferTypeToOpenGLEnum(type)), m_count(count)
{
glCreateBuffers(1, &m_bufferID);
UpdateData(data, m_count);
}
OpenGLIndexBuffer::~OpenGLIndexBuffer()
{
glDeleteBuffers(1, &m_bufferID);
}
void OpenGLIndexBuffer::Bind() const
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_bufferID);
}
void OpenGLIndexBuffer::Unbind() const
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void OpenGLIndexBuffer::UpdateData(const unsigned int* data, unsigned int count)
{
m_count = count;
glNamedBufferData(m_bufferID, count * sizeof(unsigned int), data, m_openGLDrawType);
}
void OpenGLIndexBuffer::UpdateSubData(const unsigned int* data, unsigned int count, unsigned int indexOffset)
{
m_count = count + indexOffset;
glNamedBufferSubData(m_bufferID, indexOffset * sizeof(unsigned int), count * sizeof(unsigned int), data);
}
}
| 24.155556
| 188
| 0.75483
|
Aaron-Berland
|
750feb4533c5e534328997d8fa1614ba44598e92
| 12,167
|
cpp
|
C++
|
VisualPipes/albaPipeVector.cpp
|
IOR-BIC/ALBA
|
b574968b05d9a3a2756dd2ac61d015a0d20232a4
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 9
|
2018-11-19T10:15:29.000Z
|
2021-08-30T11:52:07.000Z
|
VisualPipes/albaPipeVector.cpp
|
IOR-BIC/ALBA
|
b574968b05d9a3a2756dd2ac61d015a0d20232a4
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
VisualPipes/albaPipeVector.cpp
|
IOR-BIC/ALBA
|
b574968b05d9a3a2756dd2ac61d015a0d20232a4
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 3
|
2018-06-10T22:56:29.000Z
|
2019-12-12T06:22:56.000Z
|
/*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaPipeVector
Authors: Roberto Mucci
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "albaPipeVector.h"
#include "wx/busyinfo.h"
#include "albaSceneNode.h"
#include "albaGUI.h"
#include "albaGUIMaterialButton.h"
#include "mmaMaterial.h"
#include "albaVMEVector.h"
#include "vtkALBASmartPointer.h"
#include "vtkALBAAssembly.h"
#include "vtkAppendPolyData.h"
#include "vtkConeSource.h"
#include "vtkCellArray.h"
#include "vtkPointData.h"
#include "vtkImageData.h"
#include "vtkLineSource.h"
#include "vtkMath.h"
#include "vtkOutlineCornerFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyData.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkSphereSource.h"
#include <vector>
//----------------------------------------------------------------------------
albaCxxTypeMacro(albaPipeVector);
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
albaPipeVector::albaPipeVector()
:albaPipe()
//----------------------------------------------------------------------------
{
m_Data = NULL;
m_Sphere = NULL;
m_ArrowTip = NULL;
m_Apd = NULL;
m_Data = NULL;
m_Mapper = NULL;
m_Actor = NULL;
m_OutlineActor = NULL;
m_UseArrow = 1;
m_UseSphere = 1;
m_UseVTKProperty = 1;
m_Interval = 0;
m_Step = 20;
m_UseBunch = 0;
m_UseArrow = 1;
m_UseSphere = 1;
m_UseVTKProperty = 1;
m_AllBunch = 0;
}
//----------------------------------------------------------------------------
void albaPipeVector::Create(albaSceneNode *n)
//----------------------------------------------------------------------------
{
Superclass::Create(n);
m_Selected = false;
albaVMEOutputPolyline *out_polyline = albaVMEOutputPolyline::SafeDownCast(m_Vme->GetOutput());
assert(out_polyline);
m_Data = vtkPolyData::SafeDownCast(out_polyline->GetVTKData());
assert(m_Data);
m_Data->Update();
m_Vector = albaVMEVector::SafeDownCast(m_Vme);
m_Vector->GetTimeStamps(m_TimeVector);
m_Vme->AddObserver(this);
vtkNEW(m_ArrowTip); //Create the arrow
m_ArrowTip->SetResolution(20);
vtkNEW(m_Sphere); //Create the sphere on the Cop
m_Sphere->SetRadius(10);
m_Sphere->SetPhiResolution(20);
m_Sphere->SetThetaResolution(20);
m_Mapper = vtkPolyDataMapper::New();
m_MapperBunch = vtkPolyDataMapper::New();
UpdateProperty();
m_Sphere->Update();
m_Apd = vtkAppendPolyData::New();
m_Apd->AddInput(m_Data);
m_Apd->AddInput(m_Sphere->GetOutput());
m_Apd->AddInput(m_ArrowTip->GetOutput());
m_Apd->Update();
m_Mapper->SetInput(m_Apd->GetOutput());
int renderingDisplayListFlag = m_Vme->IsAnimated() ? 1 : 0;
m_Mapper->SetImmediateModeRendering(renderingDisplayListFlag);
m_Actor = vtkActor::New();
m_Actor->SetMapper(m_Mapper);
m_Material = out_polyline->GetMaterial();
if (m_Material)
m_Actor->SetProperty(m_Material->m_Prop);
vtkNEW(m_Bunch);
m_ActorBunch = vtkActor::New();
m_ActorBunch->GetProperty()->SetColor(0, 255, 0); //Color of bunch of vectors (Green)
m_ActorBunch->SetMapper(m_MapperBunch);
m_AssemblyFront->AddPart(m_Actor);
m_AssemblyFront->AddPart(m_ActorBunch);
vtkALBASmartPointer<vtkOutlineCornerFilter> corner;
corner->SetInput(m_Data);
vtkALBASmartPointer<vtkPolyDataMapper> corner_mapper;
corner_mapper->SetInput(corner->GetOutput());
vtkALBASmartPointer<vtkProperty> corner_props;
corner_props->SetColor(1,1,1);
corner_props->SetAmbient(1);
corner_props->SetRepresentationToWireframe();
corner_props->SetInterpolationToFlat();
m_OutlineActor = vtkActor::New();
m_OutlineActor->SetMapper(corner_mapper);
m_OutlineActor->VisibilityOff();
m_OutlineActor->PickableOff();
m_OutlineActor->SetProperty(corner_props);
m_AssemblyFront->AddPart(m_OutlineActor);
}
//----------------------------------------------------------------------------
albaPipeVector::~albaPipeVector()
//----------------------------------------------------------------------------
{
m_Vme->RemoveObserver(this);
m_AssemblyFront->RemovePart(m_Actor);
m_AssemblyFront->RemovePart(m_ActorBunch);
m_AssemblyFront->RemovePart(m_OutlineActor);
vtkDEL(m_Sphere);
vtkDEL(m_ArrowTip);
vtkDEL(m_Apd);
vtkDEL(m_Bunch);
vtkDEL(m_Mapper);
vtkDEL(m_MapperBunch);
vtkDEL(m_Actor);
vtkDEL(m_ActorBunch);
vtkDEL(m_OutlineActor);
}
//----------------------------------------------------------------------------
void albaPipeVector::Select(bool sel)
//----------------------------------------------------------------------------
{
m_Selected = sel;
if(m_Actor->GetVisibility())
{
m_OutlineActor->SetVisibility(sel);
}
}
//----------------------------------------------------------------------------
void albaPipeVector::UpdateProperty(bool fromTag)
//----------------------------------------------------------------------------
{
m_Data->Update();
double pointCop[3];
m_Data->GetPoint(0,pointCop);
if (m_UseSphere == TRUE)
{
m_Sphere->SetCenter(pointCop);
}
if (m_UseArrow == TRUE)
{
double pointForce[3];
m_Data->GetPoint(1,pointForce);
double length = sqrt(vtkMath::Distance2BetweenPoints(pointCop, pointForce));
m_ArrowTip->SetCenter(pointForce[0],pointForce[1],pointForce[2]);
m_ArrowTip->SetRadius(length/35.0);
m_ArrowTip->SetHeight(length/15.0);
double direction[3];
direction[0] = pointForce[0] - pointCop[0];
direction[1] = pointForce[1] - pointCop[1];
direction[2] = pointForce[2] - pointCop[2];
m_ArrowTip->SetDirection(direction);
}
}
//----------------------------------------------------------------------------
void albaPipeVector::AllVector(bool fromTag)
//----------------------------------------------------------------------------
{
// if(!m_TestMode)
wxBusyInfo wait(_("Creating Vectogram, please wait..."));
m_MatrixVector = m_Vector->GetMatrixVector();
albaTimeStamp t0;
t0 = m_Vector->GetTimeStamp();
if (m_MatrixVector)
{
int i;
for (i = 0; i< m_TimeVector.size(); i++)
{
if (m_TimeVector[i] > t0)
{
break;
}
}
i--;
if (i<0)
{
i=0;
}
int minValue = (i-m_Interval) < 0 ? 0 : (i-m_Interval);
int maxValue = (i + m_Interval) >= m_TimeVector.size() ? m_TimeVector.size() - 1 : (i + m_Interval);
for (albaTimeStamp n = (minValue + 1); n <= maxValue; n= n + m_Step) //Cicle to draw vectors
{
vtkALBASmartPointer<vtkLineSource> line;
double point1[3];
double point2[3];
m_Vector->SetTimeStamp(m_TimeVector[n]);
m_Vector->GetOutput()->GetVTKData()->GetPoint(0, point1);
m_Vector->GetOutput()->GetVTKData()->GetPoint(1, point2);
line->SetPoint1(point1);
line->SetPoint2(point2);
m_Bunch->AddInput(line->GetOutput());
}
if (m_Bunch->GetNumberOfInputs() == 0)
{
m_MapperBunch->SetInput(m_Bunch->GetOutput());
}
}
}
//----------------------------------------------------------------------------
albaGUI *albaPipeVector::CreateGui()
//----------------------------------------------------------------------------
{
assert(m_Gui == NULL);
m_Gui = new albaGUI(this);
m_Gui->Divider();
m_Gui->Bool(ID_USE_VTK_PROPERTY,_("property"),&m_UseVTKProperty);
m_MaterialButton = new albaGUIMaterialButton(m_Vme,this);
m_Gui->AddGui(m_MaterialButton->GetGui());
m_MaterialButton->Enable(m_UseVTKProperty != 0);
m_Gui->Divider();
m_Gui->Bool(ID_USE_ARROW,_("Arrow"),&m_UseArrow,1,_("To visualize the arrow tip"));
m_Gui->Bool(ID_USE_SPHERE,_("COP"),&m_UseSphere,1,_("To visualize sphere on COP"));
m_Gui->Divider();
m_Gui->Bool(ID_USE_BUNCH,_("Vectogram"),&m_UseBunch,0,_("To visualize the Vectogram"));
m_Gui->Divider();
m_Gui->Integer(ID_STEP,_("Step:"),&m_Step,0,(m_TimeVector.size()),_("1 To visualize every vector"));
m_Gui->Divider();
m_Gui->Integer(ID_INTERVAL,_("Interval:"),&m_Interval,0,(m_TimeVector.size()),_("Interval of frames to visualize"));
m_Gui->Divider();
m_Gui->Bool(ID_ALL_BUNCH,_("Complete"),&m_AllBunch,0,_("To visualize the whole bunch"));
m_Gui->Enable(ID_ALL_BUNCH, m_UseBunch == 1);
m_Gui->Enable(ID_INTERVAL, m_UseBunch == 1 && m_AllBunch == 0);
m_Gui->Enable(ID_STEP, m_UseBunch == 1);
m_Gui->Divider();
return m_Gui;
}
//----------------------------------------------------------------------------
void albaPipeVector::OnEvent(albaEventBase *alba_event)
//----------------------------------------------------------------------------
{
if (albaEvent *e = albaEvent::SafeDownCast(alba_event))
{
switch(e->GetId())
{
case ID_USE_VTK_PROPERTY:
if (m_UseVTKProperty != 0)
{
m_Actor->SetProperty(m_Material->m_Prop);
}
else
{
m_Actor->SetProperty(NULL);
}
m_MaterialButton->Enable(m_UseVTKProperty != 0);
GetLogicManager()->CameraUpdate();
break;
case ID_USE_ARROW:
if (m_UseArrow == FALSE)
{
m_Apd->RemoveInput(m_ArrowTip->GetOutput());
m_Apd->Update();
}
else
{
UpdateProperty();
m_Apd->AddInput(m_ArrowTip->GetOutput());
m_Apd->Update();
}
GetLogicManager()->CameraUpdate();
break;
case ID_USE_SPHERE:
if (m_UseSphere == FALSE)
{
m_Apd->RemoveInput(m_Sphere->GetOutput());
m_Apd->Update();
}
else
{
UpdateProperty();
m_Apd->AddInput(m_Sphere->GetOutput());
m_Apd->Update();
}
GetLogicManager()->CameraUpdate();
break;
case ID_USE_BUNCH:
if (m_UseBunch == TRUE)
{
m_Gui->Update();
AllVector();
}
else
{
m_Interval = 0;
m_AllBunch = 0;
m_Gui->Update();
m_Bunch->RemoveAllInputs();
}
EnableWidget();
GetLogicManager()->CameraUpdate();
break;
case ID_INTERVAL:
m_Bunch->RemoveAllInputs();
AllVector();
GetLogicManager()->CameraUpdate();
break;
case ID_STEP:
m_Bunch->RemoveAllInputs();
AllVector();
GetLogicManager()->CameraUpdate();
break;
case ID_ALL_BUNCH:
if (m_AllBunch == TRUE)
{
m_Bunch->RemoveAllInputs();
m_Interval = m_TimeVector.size();
m_Gui->Update();
AllVector();
}
else
{
m_Interval = 0;
m_Gui->Update();
m_Bunch->RemoveAllInputs();
}
EnableWidget();
GetLogicManager()->CameraUpdate();
break;
default:
albaEventMacro(*e);
break;
}
}
if (alba_event->GetId() == VME_TIME_SET)
{
UpdateProperty();
}
}
//----------------------------------------------------------------------------
void albaPipeVector::EnableWidget()
//----------------------------------------------------------------------------
{
m_Gui->Enable(ID_INTERVAL, m_UseBunch == 1 && m_AllBunch == 0);
m_Gui->Enable(ID_STEP, m_UseBunch == 1);
m_Gui->Enable(ID_ALL_BUNCH, m_UseBunch == 1);
}
| 29.318072
| 118
| 0.553546
|
IOR-BIC
|
75129a3b859d2a724fb2a4b1078d6b3b4c6ab5b0
| 1,721
|
tpp
|
C++
|
v1/include/GameObject.tpp
|
cherosene/learning_algorithms
|
8ec9d8b7f744a375170ac2396cfb8bc216f84f53
|
[
"MIT"
] | null | null | null |
v1/include/GameObject.tpp
|
cherosene/learning_algorithms
|
8ec9d8b7f744a375170ac2396cfb8bc216f84f53
|
[
"MIT"
] | null | null | null |
v1/include/GameObject.tpp
|
cherosene/learning_algorithms
|
8ec9d8b7f744a375170ac2396cfb8bc216f84f53
|
[
"MIT"
] | null | null | null |
template <class T>
GameObject<T>::GameObject(std::map<T,std::function<void()>> atm, int nx, int ny, float nspeed) : x(nx), y(ny), speed(nspeed), actionToMove(atm) {}
//// SPATIAL POSITION
template <class T>
void GameObject<T>::warp(int nx, int ny) { x = nx; y = ny; }
template <class T>
void GameObject<T>::move(direction dir, int distance)
{
switch(dir)
{
case UP:
y -= distance;
break;
case DOWN:
y += distance;
break;
case LEFT:
x -= distance;
break;
case RIGHT:
x += distance;
break;
}
}
template <class T>
void GameObject<T>::move(direction dir) { move(dir, speed); }
//// ACTIONS
template <class T>
void GameObject<T>::doAction(T act)
{
typename std::map<T,std::function<void()>>::iterator it = actionToMove.find(act);
if( it == actionToMove.end() )
{
// FIXME: raise an exception when the move is not valid
}
else
{
if( it->second != NULL )
{
(it->second)();
}
}
}
template <class T>
void GameObject<T>::bindAction(T act, std::function<void()> fun)
{
actionToMove[act] = fun;
}
template <class T>
void GameObject<T>::dropAction(T act)
{
typename std::map<T,std::function<void()>>::iterator itToErase;
itToErase = actionToMove.find(act);
if(itToErase != actionToMove.end()) {actionToMove.erase(itToErase);}
}
template <class T>
std::vector<T> GameObject<T>::validActions()
{
std::vector<T> result;
for(typename std::map<T,std::function<void()>>::iterator it = actionToMove.begin(); it != actionToMove.end(); ++it) { result.push_back(it->first); }
return result;
}
| 24.585714
| 152
| 0.583963
|
cherosene
|
75136d7c712e70d72e82bc145e9b0ff6bf537b1b
| 17,539
|
cpp
|
C++
|
src/flexui/Style/StyleProperty.cpp
|
mlomb/flexui
|
242790aa13b057e25b276b6a3df79a30735c2548
|
[
"MIT"
] | 23
|
2020-12-20T01:41:56.000Z
|
2021-11-14T20:26:40.000Z
|
src/flexui/Style/StyleProperty.cpp
|
mlomb/flexui
|
242790aa13b057e25b276b6a3df79a30735c2548
|
[
"MIT"
] | 2
|
2020-12-23T16:29:55.000Z
|
2021-11-29T05:35:12.000Z
|
src/flexui/Style/StyleProperty.cpp
|
mlomb/flexui
|
242790aa13b057e25b276b6a3df79a30735c2548
|
[
"MIT"
] | 4
|
2020-12-23T16:02:25.000Z
|
2021-09-30T08:37:51.000Z
|
#include "flexui/Style/StyleProperty.hpp"
#include <cmath> // powf
#include "flexui/Style/NamedColors.hpp"
namespace flexui {
/// Check if the character is a valid CSS property
inline bool isPropertyNameChar(const char c) {
return (c == '-') || (c >= 'a' && c <= 'z');
}
/// Converts decimal colors to Color
Color buildColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
// AABBGGRR
return ((uint32_t)(a) << 24) | ((uint32_t)(b) << 16) | ((uint32_t)(g) << 8) | ((uint32_t)(r));
}
bool parseNumber(const StringSection& input, size_t& pos, float& output, ParseResult* pr) {
bool valid = false;
bool negative = false;
bool mantissa = false;
int mantissa_place = 1;
float value = 0;
parser::ConsumeWhiteSpace(input, pos);
while (pos < input.length()) {
char chr = input[pos];
if (chr == '-') {
if (pos == 0) {
negative = true;
}
else {
if (pr)
pr->warnings.emplace_back("Unexpected '-'");
return false; // unexpected -
}
}
else if (chr == '.') {
if (mantissa) {
if (pr)
pr->warnings.emplace_back("Unexpected '.'");
return false; // unexpected .
}
mantissa = true;
}
else if (parser::IsNumeric(chr)) {
int num = chr - '0';
if (!mantissa) {
// whole part
value = value * 10 + num;
}
else {
// decimal part
value = value + (float)num / powf(10, (float)mantissa_place++);
}
valid = true;
}
else {
break; // unexpected character (probably a unit)
}
pos++;
}
output = negative ? -value : value;
return valid;
}
bool parseLength(const StringSection& input, StyleLength& output, ParseResult* pr) {
size_t pos = 0;
if (parseNumber(input, pos, output.number, pr)) {
// number parsed
if (pos < input.length()) {
// more to read, must be a unit
// set as AUTO, if continues to be AUTO after parsing, the unit was invalid
output.unit = StyleLengthUnit::AUTO;
if (input[pos] == '%') output.unit = StyleLengthUnit::PERCENT;
else if (pos + 1 < input.length()) { // enough for two char unit
if(false) { }
#define CHECK_LENGTH_UNIT(a, b, _unit) \
else if (input[pos] == a && input[pos + 1] == b) output.unit = _unit;
// absolute lengths
CHECK_LENGTH_UNIT('p', 'x', StyleLengthUnit::PX)
CHECK_LENGTH_UNIT('i', 'n', StyleLengthUnit::IN)
CHECK_LENGTH_UNIT('c', 'm', StyleLengthUnit::CM)
CHECK_LENGTH_UNIT('m', 'm', StyleLengthUnit::MM)
// font-relative lengths
CHECK_LENGTH_UNIT('e', 'm', StyleLengthUnit::EM)
// viewport lengths
CHECK_LENGTH_UNIT('v', 'w', StyleLengthUnit::VW)
CHECK_LENGTH_UNIT('v', 'h', StyleLengthUnit::VH)
#undef CHECK_LENGTH_UNIT
}
if(output.unit == StyleLengthUnit::AUTO){
// invalid unit
if (pr)
pr->warnings.emplace_back("Unexpected character '" + std::string(1, input[pos]) + "' parsing length");
return false; // unexpected character
}
}
else {
// by default pixels
output.unit = StyleLengthUnit::PX;
// annoying if using something like: margin: 0;
// pr.warnings.emplace_back("Defaulting to pixels due absence of length unit");
}
return true;
}
else if (input.length() >= 4) {
// check if auto
if (input[0] == 'a' && input[1] == 'u' && input[2] == 't' && input[3] == 'o') {
output.unit = StyleLengthUnit::AUTO;
return true;
}
}
return false;
}
bool parseColor(const StringSection& input, Color& output, ParseResult* pr) {
if (input.length() < 2)
return false;
if (input[0] == '#') { // hex color
// #RGB
if (input.length() == 4) {
if (parser::IsHex(input[1]) &&
parser::IsHex(input[2]) &&
parser::IsHex(input[3])) {
output = buildColor(
parser::HexToDec(input[1], input[1]),
parser::HexToDec(input[2], input[2]),
parser::HexToDec(input[3], input[3]),
(unsigned char)0xFF
);
return true;
}
else {
if (pr)
pr->warnings.emplace_back("Invalid #RGB hex value");
return false; // invalid hex
}
}
// #RRGGBB
else if (input.length() == 7) {
if (parser::IsHex(input[1]) &&
parser::IsHex(input[2]) &&
parser::IsHex(input[3]) &&
parser::IsHex(input[4]) &&
parser::IsHex(input[5]) &&
parser::IsHex(input[6])) {
output = buildColor(
parser::HexToDec(input[1], input[2]),
parser::HexToDec(input[3], input[4]),
parser::HexToDec(input[5], input[6]),
(unsigned char)0xFF
);
return true;
}
else {
if (pr)
pr->warnings.emplace_back("Invalid #RRGGBB hex value");
return false; // invalid hex
}
}
else {
if (pr)
pr->warnings.emplace_back("Invalid size for hex number (" + std::to_string(input.length()) + ")");
return false; // invalid size for hex number
}
}
else if (input.length() > 5 && input[0] == 'r' && input[1] == 'g' && input[2] == 'b') { // rgb/a color
auto k = input.str();
bool has_alpha = input[3] == 'a';
int num_components = has_alpha ? 4 : 3;
size_t pos = has_alpha ? 5 : 4;
float components[4];
for (int i = 0; i < num_components; i++) {
if (parseNumber(input, pos, components[i], pr)) {
if (pos < input.length()) {
if (input[pos] == '%') {
pos++; // skip %
}
if (input[pos] == ',') {
pos++; // skip ,
// next component
if (i + 1 >= num_components) {
if (pr)
pr->warnings.emplace_back("Too many components for rgb/a");
return false; // too many components
}
}
else if (input[pos] == ')') {
// check if matched all components
if (i + 1 < num_components) {
if (pr)
pr->warnings.emplace_back("Too few components for rgb/a");
return false; // too few components
}
output = buildColor(
(unsigned char)components[0],
(unsigned char)components[1],
(unsigned char)components[2],
has_alpha ? (unsigned char)((float)components[3] * 255.0f) : 0xFF
);
return true;
}
}
else {
if (pr)
pr->warnings.emplace_back("Incomplete rgb/a color");
return false;
}
}
else {
if (pr)
pr->warnings.emplace_back("Could not parse component number " + std::to_string(i) + " of rgb/a color");
return false;
}
}
return false;
}
else {
// try to match predefined colors
// See https://www.w3.org/TR/css-color-3/#svg-color
// BUG: for some unknown reason, in Emscripten 2.0.10
// the map NAMED_COLORS is empty
// printf("size: %lu\n", NAMED_COLORS.size());
auto it = NAMED_COLORS.find(input.str());
if (it != NAMED_COLORS.end()) {
output = (*it).second;
return true;
}
else {
if (pr)
pr->warnings.emplace_back("Named color '" + input.str() + "' not found");
return false;
}
}
if (pr)
pr->warnings.emplace_back("Expected color definition");
return false;
}
bool parseString(const StringSection& input, String*& output, ParseResult* pr)
{
if (input.length() < 2) // must have at least two quotes
return false;
bool _single = input[0] == '"' || input[input.length() - 1] == '"';
bool _double = input[0] == '\'' || input[input.length() - 1] == '\'';
if (!_single && !_double)
return false;
const size_t start = 1;
const size_t end = input.length() - 1;
output = new std::string(input.section(start, end).str());
return true;
}
bool ParseStylePropertyLine(const StringSection& line, std::vector<StyleProperty>& properties, ParseResult* pr)
{
// Example of valid property lines:
//
// margin: 5px
// margin-left: 5px
// color: #ff00ff
// background-color: rgba(255, 0, 255, 0.5)
// font-family: "default"
// justify-content: flex-start
size_t pos = 0;
parser::ConsumeWhiteSpace(line, pos);
if (pos >= line.length())
return false;
// consume a property name
size_t property_name_start = pos;
while (pos < line.length() && isPropertyNameChar(line[pos]))
pos++;
size_t property_name_end = pos;
if (property_name_start == property_name_end) {
if (pr)
pr->errors.push_back("Missing property name");
return false;
}
parser::ConsumeWhiteSpace(line, pos);
// next char must be :
if (pos >= line.length() || line[pos] != ':') {
if (pr)
pr->errors.push_back("Missing :");
return false;
}
pos++; // consume :
parser::ConsumeWhiteSpace(line, pos);
// consume whitespace backwards
size_t tail = line.length() - 1;
while (tail > pos && std::isspace(line[tail]))
tail--;
StringSection property_name = line.section(property_name_start, property_name_end);
StringSection raw_value = line.section(pos, tail + 1);
using ID = StylePropertyID;
StyleValue value = { 0 };
ID id = ID::LAST_PROPERTY_INVALID; // for enums
size_t dummy = 0; // for parseNumber
switch (property_name.hash()) {
#define PARSE_PROP(func, prop_name, prop_id, prop_key) \
case HashStr(prop_name): \
if (func(raw_value, value.prop_key, pr)) { \
properties.emplace_back(prop_id, value); \
return true; \
} \
break;
#define LENGTH_PROPERTY(prop_name, prop_id) PARSE_PROP(parseLength, prop_name, prop_id, length);
#define COLOR_PROPERTY(prop_name, prop_id) PARSE_PROP(parseColor, prop_name, prop_id, color);
#define STRING_PROPERTY(prop_name, prop_id) PARSE_PROP(parseString, prop_name, prop_id, string);
#define NUMBER_PROPERTY(prop_name, prop_id) \
case HashStr(prop_name): \
if (parseNumber(raw_value, dummy, value.number, pr)) { \
properties.emplace_back(prop_id, value); \
return true; \
} \
break;
#define PARSE_ENUM_START(prop_name, prop_id) \
case HashStr(prop_name): \
id = prop_id; \
switch (raw_value.hash()) {
#define PARSE_ENUM_ENTRY(key, a, b) \
case HashStr(a): value.key = b; break; \
#define PARSE_ENUM_END() \
default: \
return false; /* no match */ \
} \
properties.emplace_back(id, value); \
return true;
/// -----------------------
/// -----------------------
/// -----------------------
LENGTH_PROPERTY("width", ID::WIDTH);
LENGTH_PROPERTY("height", ID::HEIGHT);
LENGTH_PROPERTY("min-width", ID::MIN_WIDTH);
LENGTH_PROPERTY("min-height", ID::MIN_HEIGHT);
LENGTH_PROPERTY("max-width", ID::MAX_WIDTH);
LENGTH_PROPERTY("max-height", ID::MAX_HEIGHT);
LENGTH_PROPERTY("margin-left", ID::MARGIN_LEFT);
LENGTH_PROPERTY("margin-top", ID::MARGIN_TOP);
LENGTH_PROPERTY("margin-right", ID::MARGIN_RIGHT);
LENGTH_PROPERTY("margin-bottom", ID::MARGIN_BOTTOM);
LENGTH_PROPERTY("padding-left", ID::PADDING_LEFT);
LENGTH_PROPERTY("padding-top", ID::PADDING_TOP);
LENGTH_PROPERTY("padding-right", ID::PADDING_RIGHT);
LENGTH_PROPERTY("padding-bottom", ID::PADDING_BOTTOM);
COLOR_PROPERTY("border-color", ID::BORDER_COLOR);
LENGTH_PROPERTY("border-top-left-radius", ID::BORDER_TOP_LEFT_RADIUS);
LENGTH_PROPERTY("border-top-right-radius", ID::BORDER_TOP_RIGHT_RADIUS);
LENGTH_PROPERTY("border-bottom-left-radius", ID::BORDER_BOTTOM_LEFT_RADIUS);
LENGTH_PROPERTY("border-bottom-right-radius", ID::BORDER_BOTTOM_RIGHT_RADIUS);
LENGTH_PROPERTY("border-left-width", ID::BORDER_LEFT_WIDTH);
LENGTH_PROPERTY("border-top-width", ID::BORDER_TOP_WIDTH);
LENGTH_PROPERTY("border-right-width", ID::BORDER_RIGHT_WIDTH);
LENGTH_PROPERTY("border-bottom-width", ID::BORDER_BOTTOM_WIDTH);
NUMBER_PROPERTY("flex-grow", ID::FLEX_GROW);
NUMBER_PROPERTY("flex-shrink", ID::FLEX_SHRINK);
LENGTH_PROPERTY("flex-basis", ID::FLEX_BASIS);
PARSE_ENUM_START("flex-direction", ID::FLEX_DIRECTION);
PARSE_ENUM_ENTRY(direction, "row", FlexDirection::ROW);
PARSE_ENUM_ENTRY(direction, "column", FlexDirection::COLUMN);
PARSE_ENUM_ENTRY(direction, "row-reverse", FlexDirection::ROW_REVERSE);
PARSE_ENUM_ENTRY(direction, "column-reverse", FlexDirection::COLUMN_REVERSE);
PARSE_ENUM_END();
PARSE_ENUM_START("flex-wrap", ID::FLEX_WRAP);
PARSE_ENUM_ENTRY(wrap, "nowrap", FlexWrap::NOWRAP);
PARSE_ENUM_ENTRY(wrap, "wrap", FlexWrap::WRAP);
PARSE_ENUM_ENTRY(wrap, "wrap-reverse", FlexWrap::WRAP_REVERSE);
PARSE_ENUM_END();
#define ALIGN_ENUM_ENTRIES() \
PARSE_ENUM_ENTRY(align, "auto", Align::AUTO); \
PARSE_ENUM_ENTRY(align, "flex-start", Align::FLEX_START); \
PARSE_ENUM_ENTRY(align, "center", Align::CENTER); \
PARSE_ENUM_ENTRY(align, "flex-end", Align::FLEX_END); \
PARSE_ENUM_ENTRY(align, "stretch", Align::STRETCH); \
PARSE_ENUM_ENTRY(align, "baseline", Align::BASELINE); \
PARSE_ENUM_ENTRY(align, "space-between", Align::SPACE_BETWEEN); \
PARSE_ENUM_ENTRY(align, "space-around", Align::SPACE_AROUND);
PARSE_ENUM_START("align-self", ID::ALIGN_SELF);
ALIGN_ENUM_ENTRIES();
PARSE_ENUM_END();
PARSE_ENUM_START("align-items", ID::ALIGN_ITEMS);
ALIGN_ENUM_ENTRIES();
PARSE_ENUM_END();
PARSE_ENUM_START("align-content", ID::ALIGN_CONTENT);
ALIGN_ENUM_ENTRIES();
PARSE_ENUM_END();
PARSE_ENUM_START("justify-content", ID::JUSTIFY_CONTENT);
PARSE_ENUM_ENTRY(justify, "flex-start", Justify::FLEX_START);
PARSE_ENUM_ENTRY(justify, "center", Justify::CENTER);
PARSE_ENUM_ENTRY(justify, "flex-end", Justify::FLEX_END);
PARSE_ENUM_ENTRY(justify, "space-between", Justify::SPACE_BETWEEN);
PARSE_ENUM_ENTRY(justify, "space-around", Justify::SPACE_AROUND);
PARSE_ENUM_ENTRY(justify, "space-evenly", Justify::SPACE_EVENLY);
PARSE_ENUM_END();
PARSE_ENUM_START("position", ID::POSITION);
PARSE_ENUM_ENTRY(position, "relative", Position::RELATIVE);
PARSE_ENUM_ENTRY(position, "absolute", Position::ABSOLUTE);
PARSE_ENUM_END();
LENGTH_PROPERTY("left", ID::LEFT);
LENGTH_PROPERTY("top", ID::TOP);
LENGTH_PROPERTY("right", ID::RIGHT);
LENGTH_PROPERTY("bottom", ID::BOTTOM);
COLOR_PROPERTY("color", ID::COLOR);
COLOR_PROPERTY("background-color", ID::BACKGROUND_COLOR);
PARSE_ENUM_START("overflow", ID::OVERFLOW);
PARSE_ENUM_ENTRY(overflow, "visible", Overflow::VISIBLE);
PARSE_ENUM_ENTRY(overflow, "hidden", Overflow::HIDDEN);
PARSE_ENUM_ENTRY(overflow, "scroll", Overflow::SCROLL);
PARSE_ENUM_END();
PARSE_ENUM_START("display", ID::DISPLAY);
PARSE_ENUM_ENTRY(display, "flex", Display::FLEX);
PARSE_ENUM_ENTRY(display, "none", Display::NONE);
PARSE_ENUM_END();
STRING_PROPERTY("font-family", ID::FONT_FAMILY);
LENGTH_PROPERTY("font-size", ID::FONT_SIZE);
PARSE_ENUM_START("white-space", ID::WHITE_SPACE);
PARSE_ENUM_ENTRY(whiteSpace, "normal", WhiteSpace::NORMAL);
PARSE_ENUM_ENTRY(whiteSpace, "nowrap", WhiteSpace::NOWRAP);
PARSE_ENUM_END();
PARSE_ENUM_START("cursor", ID::CURSOR);
PARSE_ENUM_ENTRY(cursor, "auto", Cursor::AUTO);
PARSE_ENUM_ENTRY(cursor, "default", Cursor::DEFAULT);
PARSE_ENUM_ENTRY(cursor, "none", Cursor::NONE);
PARSE_ENUM_ENTRY(cursor, "help", Cursor::HELP);
PARSE_ENUM_ENTRY(cursor, "pointer", Cursor::POINTER);
PARSE_ENUM_ENTRY(cursor, "progress", Cursor::PROGRESS);
PARSE_ENUM_ENTRY(cursor, "wait", Cursor::WAIT);
PARSE_ENUM_ENTRY(cursor, "crosshair", Cursor::CROSSHAIR);
PARSE_ENUM_ENTRY(cursor, "text", Cursor::TEXT);
PARSE_ENUM_ENTRY(cursor, "move", Cursor::MOVE);
PARSE_ENUM_ENTRY(cursor, "not-allowed", Cursor::NOT_ALLOWED);
PARSE_ENUM_ENTRY(cursor, "all-scroll", Cursor::ALL_SCROLL);
PARSE_ENUM_ENTRY(cursor, "col-resize", Cursor::COL_RESIZE);
PARSE_ENUM_ENTRY(cursor, "row-resize", Cursor::ROW_RESIZE);
PARSE_ENUM_END();
// shorthands
#define FOUR_LENGTH_SHORTHAND(prop_name, a, b, c, d) \
case HashStr(prop_name): \
if (parseLength(raw_value, value.length, pr)) { \
properties.emplace_back(a, value); \
properties.emplace_back(b, value); \
properties.emplace_back(c, value); \
properties.emplace_back(d, value); \
return true; \
} \
break;
FOUR_LENGTH_SHORTHAND(
"border-radius",
ID::BORDER_TOP_LEFT_RADIUS,
ID::BORDER_TOP_RIGHT_RADIUS,
ID::BORDER_BOTTOM_LEFT_RADIUS,
ID::BORDER_BOTTOM_RIGHT_RADIUS
)
FOUR_LENGTH_SHORTHAND(
"border-width",
ID::BORDER_LEFT_WIDTH,
ID::BORDER_TOP_WIDTH,
ID::BORDER_RIGHT_WIDTH,
ID::BORDER_BOTTOM_WIDTH
)
FOUR_LENGTH_SHORTHAND(
"margin",
ID::MARGIN_LEFT,
ID::MARGIN_TOP,
ID::MARGIN_RIGHT,
ID::MARGIN_BOTTOM
)
FOUR_LENGTH_SHORTHAND(
"padding",
ID::PADDING_LEFT,
ID::PADDING_TOP,
ID::PADDING_RIGHT,
ID::PADDING_BOTTOM
)
// TODO: flex shorthand
default:
if (pr)
pr->warnings.emplace_back("Property '" + property_name.str() + "' is not supported");
break;
}
return true;
}
bool ParseStylePropertiesBlock(const StringSection& block, std::vector<StyleProperty>& properties, ParseResult* pr)
{
bool any = false;
size_t pos = 0;
while (pos < block.length()) {
any |= ParseStylePropertyLine(block.section_until(';', pos), properties, pr);
pos++; // skip ,
}
return any;
}
StyleProperty::StyleProperty(const StylePropertyID id, const StyleValue& value) :
m_ID(id),
m_Value(value)
{
}
StyleProperty::StyleProperty() :
m_ID(StylePropertyID::LAST_PROPERTY_INVALID),
m_Value({ 0 })
{
}
StyleProperty::~StyleProperty()
{
switch (m_ID)
{
case StylePropertyID::FONT_FAMILY:
delete m_Value.string;
break;
default:
break;
}
}
}
| 30.135739
| 116
| 0.640116
|
mlomb
|
7515f9da3f114383e24a8bfa46211b1e2a3977fd
| 2,176
|
cpp
|
C++
|
PAT_A/A1033|To Fill or Not to Fill|e.g.cpp
|
FunamiYui/PAT_Code_Akari
|
52e06689b6bf8177c43ab9256719258c47e80b25
|
[
"MIT"
] | null | null | null |
PAT_A/A1033|To Fill or Not to Fill|e.g.cpp
|
FunamiYui/PAT_Code_Akari
|
52e06689b6bf8177c43ab9256719258c47e80b25
|
[
"MIT"
] | null | null | null |
PAT_A/A1033|To Fill or Not to Fill|e.g.cpp
|
FunamiYui/PAT_Code_Akari
|
52e06689b6bf8177c43ab9256719258c47e80b25
|
[
"MIT"
] | null | null | null |
//example
//在距离为0处必须有加油站,否则无法出发,一定无法到达终点
//Cmax、D、Davg、油价、距离都可能是浮点型,不能设置成int型
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 510;
const int INF = 1000000000;
struct station {
double price, dis; //油价格、与起点的距离
} st[maxn];
bool cmp(station a, station b) {
return a.dis < b.dis; //按距离从小到大排序
}
int main() {
int n;
double Cmax, D, Davg;
scanf("%lf%lf%lf%d", &Cmax, &D, &Davg, &n);
for(int i = 0; i < n; i++) {
scanf("%lf%lf", &st[i].price, &st[i].dis);
}
st[n].price = 0; //数组最后面放置终点(也看成一个加油站),油价为0
st[n].dis = D; //终点距离为D
sort(st, st + n, cmp); //将所有加油站按距离从小到大排序(没算终点是因为终点距离最远而且已经在最后了)
if(st[0].dis != 0) { //如果排序后的第一个加油站距离不是0,说明无法前进
printf("The maximum travel distance = 0.00\n");
}
else {
int now = 0; //当前所处的加油站编号
//总花费、当前油量及满油行驶距离,Tank这里译为油量
double ans = 0, nowTank = 0, MAX = Cmax * Davg;
while(now < n) { //每次循环将选出下一个需要到达的加油站,下面的写法是将策略1和策略2的寻找加油站的过程合在一起
//选出从当前加油站满油能到达范围内的第一个油价低于当前油价的加油站
//如果没有低于当前油价的加油站,则选择油价最低的那个
int k = -1; //存放最低油价的加油站的编号,注意初值的设置
double priceMin = INF; //存放最低油价
for(int i = now + 1; i <= n && st[i].dis - st[now].dis <= MAX; i++) { //注意循环初值为now + 1 所考察所讨论的范围为从当前加油站满油能到达范围内
if(st[i].price < priceMin) { //如果油价 比 当前最低油价低
priceMin = st[i].price; //更新最低油价
k = i;
//如果找到第一个油价低于当前油价的加油站,直接中断循环
if(priceMin < st[now].price) {
break;
}
}
}
if(k == -1) {
break; //满油状态下无法找到加油站,退出循环输出结果
}
//下面为能找到可到达的加油站k,计算转移花费
//need为从now到k需要的油量
double need = (st[k].dis - st[now].dis) / Davg;
if(priceMin < st[now].price) { //如果加油站k的油价低于当前油价
//只买足够到达加油站k的油
if(nowTank < need) { //如果当前油量不足need
ans += (need - nowTank) * st[now].price; //补足need,然后就出发去加油站k
nowTank = 0; //到达加油站k后 油箱内油量为0
}
else { //如果当前油量超过need
nowTank -= need; //直接到达加油站k
}
}
else { //如果加油站k的油价高于当前油价
ans += (Cmax - nowTank) * st[now].price; //将油箱加满
//到达加油站k后油箱内油量为Cmax - need
nowTank = Cmax - need;
}
now = k; //到达加油站k,进入下一层循环
}
if(now == n) { //能到达终点
printf("%.2f\n", ans);
}
else { //不能到达终点
printf("The maximum travel distance = %.2f\n", st[now].dis + MAX);
}
}
return 0;
}
| 26.864198
| 114
| 0.606618
|
FunamiYui
|
751742c761ce67fed60a951e6889c7e7b8b0952a
| 11,004
|
cpp
|
C++
|
data-server/src/range/txn.cpp
|
13meimei/sharkstore
|
b73fd09e8cddf78fc1f690219529770b278b35b6
|
[
"Apache-2.0"
] | 1
|
2019-09-11T06:16:42.000Z
|
2019-09-11T06:16:42.000Z
|
data-server/src/range/txn.cpp
|
13meimei/sharkstore
|
b73fd09e8cddf78fc1f690219529770b278b35b6
|
[
"Apache-2.0"
] | null | null | null |
data-server/src/range/txn.cpp
|
13meimei/sharkstore
|
b73fd09e8cddf78fc1f690219529770b278b35b6
|
[
"Apache-2.0"
] | 1
|
2021-09-03T10:35:21.000Z
|
2021-09-03T10:35:21.000Z
|
#include "range.h"
namespace sharkstore {
namespace dataserver {
namespace range {
using namespace sharkstore::monitor;
using namespace txnpb;
bool Range::KeyInRange(const PrepareRequest& req, const metapb::RangeEpoch& epoch, errorpb::Error** err) {
assert(err != nullptr);
bool in_range = true;
std::string wrong_key;
for (const auto& intent: req.intents()) {
if (!KeyInRange(intent.key())) {
in_range = false;
wrong_key = intent.key();
break;
}
}
if (in_range) return true;
// not in range
if (!EpochIsEqual(epoch)) {
*err = StaleEpochError(epoch);
} else {
*err = KeyNotInRange(wrong_key);
}
return false;
}
bool Range::KeyInRange(const DecideRequest& req, const metapb::RangeEpoch& epoch, errorpb::Error** err) {
assert(err != nullptr);
bool in_range = true;
std::string wrong_key;
for (const auto& key: req.keys()) {
if (!KeyInRange(key)) {
in_range = false;
wrong_key = key;
break;
}
}
if (in_range) return true;
// not in range
if (!EpochIsEqual(epoch)) {
*err = StaleEpochError(epoch);
} else {
*err = KeyNotInRange(wrong_key);
}
return false;
}
void Range::TxnPrepare(RPCRequestPtr rpc, DsPrepareRequest& req) {
RANGE_LOG_DEBUG("TxnPrepare begin, req: %s", req.DebugString().c_str());
errorpb::Error *err = nullptr;
do {
if (!hasSpaceLeft(&err)) {
break;
}
if (!VerifyLeader(err)) {
break;
}
if (!KeyInRange(req.req(), req.header().range_epoch(), &err)) {
break;
}
// submit to raft
// TODO: check lock in memory
SubmitCmd<DsPrepareResponse>(std::move(rpc), req.header(),
[&req](raft_cmdpb::Command &cmd) {
cmd.set_cmd_type(raft_cmdpb::CmdType::TxnPrepare);
cmd.set_allocated_txn_prepare_req(req.release_req());
});
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("TxnPrepare error: %s", err->message().c_str());
DsPrepareResponse resp;
SendResponse(rpc, resp, req.header(), err);
}
}
Status Range::ApplyTxnPrepare(const raft_cmdpb::Command &cmd, uint64_t raft_index) {
RANGE_LOG_DEBUG("ApplyTxnPrepare begin at %" PRId64 ", req: %s", raft_index, cmd.DebugString().c_str());
Status ret;
auto &req = cmd.txn_prepare_req();
auto btime = NowMicros();
errorpb::Error *err = nullptr;
uint64_t bytes_written = 0;
std::unique_ptr<PrepareResponse> resp(new PrepareResponse);
do {
if (!KeyInRange(req, cmd.verify_epoch(), &err)) {
break;
}
bytes_written = store_->TxnPrepare(req, raft_index, resp.get());
} while (false);
if (cmd.cmd_id().node_id() == node_id_) {
DsPrepareResponse ds_resp;
ds_resp.set_allocated_resp(resp.release());
ReplySubmit(cmd, ds_resp, err, btime);
if (bytes_written > 0) {
CheckSplit(bytes_written);
}
} else if (err != nullptr) {
delete err;
}
return ret;
}
void Range::TxnDecide(RPCRequestPtr rpc, DsDecideRequest& req) {
RANGE_LOG_DEBUG("TxnDecide begin, req: %s", req.DebugString().c_str());
errorpb::Error *err = nullptr;
do {
if (!hasSpaceLeft(&err)) {
break;
}
if (!VerifyLeader(err)) {
break;
}
if (!KeyInRange(req.req(), req.header().range_epoch(), &err)) {
break;
}
// submit to raft
// TODO: check lock in memory
SubmitCmd<DsDecideResponse>(std::move(rpc), req.header(),
[&req](raft_cmdpb::Command &cmd) {
cmd.set_cmd_type(raft_cmdpb::CmdType::TxnDecide);
cmd.set_allocated_txn_decide_req(req.release_req());
});
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("TxnDecide error: %s", err->message().c_str());
DsDecideResponse resp;
SendResponse(rpc, resp, req.header(), err);
}
}
Status Range::ApplyTxnDecide(const raft_cmdpb::Command &cmd, uint64_t raft_index) {
RANGE_LOG_DEBUG("ApplyTxnDecide begin, cmd: %s", cmd.DebugString().c_str());
Status ret;
auto &req = cmd.txn_decide_req();
auto btime = NowMicros();
errorpb::Error *err = nullptr;
std::unique_ptr<DecideResponse> resp(new DecideResponse);
uint64_t bytes_written = 0;
do {
if (!KeyInRange(req, cmd.verify_epoch(), &err)) {
break;
}
bytes_written = store_->TxnDecide(req, resp.get());
} while (false);
if (cmd.cmd_id().node_id() == node_id_) {
txnpb::DsDecideResponse ds_resp;
ds_resp.set_allocated_resp(resp.release());
ReplySubmit(cmd, ds_resp, err, btime);
if (bytes_written > 0) {
CheckSplit(bytes_written);
}
} else if (err != nullptr) {
delete err;
}
return ret;
}
void Range::TxnClearup(RPCRequestPtr rpc, txnpb::DsClearupRequest& req) {
RANGE_LOG_DEBUG("TxnClearup begin, req: %s", req.DebugString().c_str());
errorpb::Error *err = nullptr;
do {
if (!hasSpaceLeft(&err)) {
break;
}
if (!VerifyLeader(err)) {
break;
}
if (!EpochIsEqual(req.header().range_epoch(), err)) {
break;
}
if (!KeyInRange(req.req().primary_key(), err)) {
break;
}
SubmitCmd<DsClearupResponse>(std::move(rpc), req.header(),
[&req](raft_cmdpb::Command &cmd) {
cmd.set_cmd_type(raft_cmdpb::CmdType::TxnClearup);
cmd.set_allocated_txn_clearup_req(req.release_req());
});
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("TxnClearup error: %s", err->message().c_str());
txnpb::DsClearupResponse resp;
return SendResponse(rpc, resp, req.header(), err);
}
}
Status Range::ApplyTxnClearup(const raft_cmdpb::Command &cmd, uint64_t raft_index) {
Status ret;
auto &req = cmd.txn_clearup_req();
auto btime = NowMicros();
errorpb::Error *err = nullptr;
std::unique_ptr<ClearupResponse> resp(new ClearupResponse);
do {
if (!EpochIsEqual(cmd.verify_epoch(), err)) {
break;
}
if (!KeyInRange(req.primary_key(), err)) {
break;
}
store_->TxnClearup(req, resp.get());
} while (false);
if (err != nullptr) {
RANGE_LOG_ERROR("TxnClearup %s failed: %s", req.primary_key().c_str(),
err->ShortDebugString().c_str());
} else if (resp->has_err()) {
RANGE_LOG_ERROR("TxnClearup %s failed: %s", req.primary_key().c_str(),
resp->err().ShortDebugString().c_str());
}
if (cmd.cmd_id().node_id() == node_id_) {
txnpb::DsClearupResponse ds_resp;
ds_resp.set_allocated_resp(resp.release());
ReplySubmit(cmd, ds_resp, err, btime);
} else if (err != nullptr) {
delete err;
}
return ret;
}
void Range::TxnGetLockInfo(RPCRequestPtr rpc, txnpb::DsGetLockInfoRequest& req) {
auto btime = NowMicros();
errorpb::Error *err = nullptr;
txnpb::DsGetLockInfoResponse ds_resp;
do {
if (!VerifyLeader(err)) {
break;
}
if (!EpochIsEqual(req.header().range_epoch(), err)) {
break;
}
if (!KeyInRange(req.req().key(), err)) {
break;
}
auto now = NowMicros();
store_->TxnGetLockInfo(req.req(), ds_resp.mutable_resp());
context_->Statistics()->PushTime(HistogramType::kStore, now - btime);
} while (false);
if (err != nullptr) {
RANGE_LOG_ERROR("TxnGetLockInfo failed: %s", err->ShortDebugString().c_str());
}
SendResponse(rpc, ds_resp, req.header(), err);
}
void Range::TxnSelect(RPCRequestPtr rpc, txnpb::DsSelectRequest& req) {
RANGE_LOG_DEBUG("Select begin, req: %s", req.DebugString().c_str());
auto btime = NowMicros();
errorpb::Error *err = nullptr;
txnpb::DsSelectResponse ds_resp;
do {
if (!VerifyLeader(err)) {
break;
}
if (!EpochIsEqual(req.header().range_epoch(), err)) {
break;
}
auto key = req.req().key();
if (!key.empty() && !KeyInRange(key, err)) {
break;
}
auto resp = ds_resp.mutable_resp();
auto ret = store_->TxnSelect(req.req(), resp);
auto etime = NowMicros();
context_->Statistics()->PushTime(HistogramType::kStore, etime - btime);
if (!ret.ok()) {
RANGE_LOG_ERROR("TxnSelect from store error: %s", ret.ToString().c_str());
resp->set_code(static_cast<int>(ret.code()));
break;
}
if (key.empty() && !EpochIsEqual(req.header().range_epoch(), err)) {
ds_resp.clear_resp();
RANGE_LOG_WARN("epoch change Select error: %s", err->message().c_str());
}
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("TxnSelect error: %s", err->message().c_str());
} else {
RANGE_LOG_DEBUG("TxnSelect result: code=%d, rows=%d",
(ds_resp.has_resp() ? ds_resp.resp().code() : 0),
(ds_resp.has_resp() ? ds_resp.resp().rows_size() : 0));
}
SendResponse(rpc, ds_resp, req.header(), err);
}
void Range::TxnScan(RPCRequestPtr rpc, txnpb::DsScanRequest& req) {
RANGE_LOG_DEBUG("TxnScan begin, req: %s", req.DebugString().c_str());
auto btime = NowMicros();
errorpb::Error *err = nullptr;
txnpb::DsScanResponse ds_resp;
do {
if (!VerifyLeader(err)) {
break;
}
if (!EpochIsEqual(req.header().range_epoch(), err)) {
break;
}
auto resp = ds_resp.mutable_resp();
auto ret = store_->TxnScan(req.req(), resp);
auto etime = NowMicros();
context_->Statistics()->PushTime(HistogramType::kStore, etime - btime);
if (!ret.ok()) {
RANGE_LOG_ERROR("TxnScan from store error: %s", ret.ToString().c_str());
resp->set_code(static_cast<int>(ret.code()));
break;
}
if (!EpochIsEqual(req.header().range_epoch(), err)) {
ds_resp.clear_resp();
RANGE_LOG_WARN("epoch change Select error: %s", err->message().c_str());
}
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("TxnScan error: %s", err->message().c_str());
} else {
RANGE_LOG_DEBUG("TxnSelect result: code=%d, size=%d",
(ds_resp.has_resp() ? ds_resp.resp().code() : 0),
(ds_resp.has_resp() ? ds_resp.resp().kvs_size() : 0));
}
SendResponse(rpc, ds_resp, req.header(), err);
}
} // namespace range
} // namespace dataserver
} // namespace sharkstore
| 29.983651
| 108
| 0.568339
|
13meimei
|
751c608d30ad28700117e76301ddaeb9a9f63d4a
| 884
|
cpp
|
C++
|
tools/converter/source/tensorflow/LRNTf.cpp
|
loveltyoic/MNN
|
ff405a307819a7228e0d1fc02c00c68021745b0a
|
[
"Apache-2.0"
] | 1
|
2019-08-09T03:16:49.000Z
|
2019-08-09T03:16:49.000Z
|
tools/converter/source/tensorflow/LRNTf.cpp
|
sunnythree/MNN
|
166fe68cd1ba05d02b018537bf6af03374431690
|
[
"Apache-2.0"
] | null | null | null |
tools/converter/source/tensorflow/LRNTf.cpp
|
sunnythree/MNN
|
166fe68cd1ba05d02b018537bf6af03374431690
|
[
"Apache-2.0"
] | 1
|
2021-01-15T06:28:11.000Z
|
2021-01-15T06:28:11.000Z
|
//
// LRNTf.cpp
// MNNConverter
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "TfUtils.hpp"
#include "tfOpConverter.hpp"
#include "graph.pb.h"
DECLARE_OP_CONVERTER(LRNTf);
MNN::OpType LRNTf::opType() {
return MNN::OpType_LRN;
}
MNN::OpParameter LRNTf::type() {
return MNN::OpParameter_LRN;
}
void LRNTf::run(MNN::OpT *dstOp, TmpNode *srcNode, TmpGraph *tempGraph) {
auto lrnParam = new MNN::LRNT;
lrnParam->regionType = 0;
tensorflow::AttrValue value;
find_attr_value(srcNode->tfNode, "alpha", value);
lrnParam->alpha = value.f();
find_attr_value(srcNode->tfNode, "beta", value);
lrnParam->beta = value.f();
find_attr_value(srcNode->tfNode, "depth_radius", value);
lrnParam->localSize = value.i();
dstOp->main.value = lrnParam;
}
REGISTER_CONVERTER(LRNTf, LRN);
| 21.560976
| 73
| 0.671946
|
loveltyoic
|
751ff5d92e904480af9b21c8687bffcfa46aacc0
| 1,688
|
hpp
|
C++
|
include/Nazara/Core/ResourceManager.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 11
|
2019-11-27T00:40:43.000Z
|
2020-01-29T14:31:52.000Z
|
include/Nazara/Core/ResourceManager.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7
|
2019-11-27T00:29:08.000Z
|
2020-01-08T18:53:39.000Z
|
include/Nazara/Core/ResourceManager.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7
|
2019-11-27T10:27:40.000Z
|
2020-01-15T17:43:33.000Z
|
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_CORE_RESOURCEMANAGER_HPP
#define NAZARA_CORE_RESOURCEMANAGER_HPP
#include <Nazara/Core/ResourceLoader.hpp>
#include <filesystem>
#include <memory>
#include <unordered_map>
namespace Nz
{
template<typename Type, typename Parameters>
class ResourceManager
{
public:
using Loader = ResourceLoader<Type, Parameters>;
ResourceManager(Loader& loader);
explicit ResourceManager(const ResourceManager&) = default;
ResourceManager(ResourceManager&&) noexcept = default;
~ResourceManager() = default;
void Clear();
std::shared_ptr<Type> Get(const std::filesystem::path& filePath);
const Parameters& GetDefaultParameters();
void Register(const std::filesystem::path& filePath, std::shared_ptr<Type> resource);
void SetDefaultParameters(Parameters params);
void Unregister(const std::filesystem::path& filePath);
ResourceManager& operator=(const ResourceManager&) = delete;
ResourceManager& operator=(ResourceManager&&) = delete;
private:
// https://stackoverflow.com/questions/51065244/is-there-no-standard-hash-for-stdfilesystempath
struct PathHash
{
std::size_t operator()(const std::filesystem::path& p) const
{
return hash_value(p);
}
};
std::unordered_map<std::filesystem::path, std::shared_ptr<Type>, PathHash> m_resources;
Loader& m_loader;
Parameters m_defaultParameters;
};
}
#include <Nazara/Core/ResourceManager.inl>
#endif // NAZARA_CORE_RESOURCEMANAGER_HPP
| 28.610169
| 98
| 0.747038
|
jayrulez
|
970ce570f73b212d2ae76a5c979443088090fd87
| 325
|
cc
|
C++
|
foobar/bar.cc
|
cbracken/cc_project_template_bazel
|
e3121a89130cf419f6cdc0e2978775b5a4a1b4e4
|
[
"BSD-3-Clause"
] | null | null | null |
foobar/bar.cc
|
cbracken/cc_project_template_bazel
|
e3121a89130cf419f6cdc0e2978775b5a4a1b4e4
|
[
"BSD-3-Clause"
] | null | null | null |
foobar/bar.cc
|
cbracken/cc_project_template_bazel
|
e3121a89130cf419f6cdc0e2978775b5a4a1b4e4
|
[
"BSD-3-Clause"
] | null | null | null |
#include "bar.h"
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace foobar {
std::string Bar(absl::string_view name) {
std::string greeting = "Hello";
if (name.size() >= 1) {
absl::StrAppend(&greeting, ", ", name);
}
return greeting;
}
} // namespace foobar
| 17.105263
| 43
| 0.655385
|
cbracken
|
970ddfa3638c99a8a745abecece32889169f9d57
| 4,962
|
hpp
|
C++
|
Lucy/include/RoundedRectangle.hpp
|
pL0ck/LUCY
|
3fdc467d2b32f8c53ed42d40c5ba12d9cccac913
|
[
"Zlib"
] | null | null | null |
Lucy/include/RoundedRectangle.hpp
|
pL0ck/LUCY
|
3fdc467d2b32f8c53ed42d40c5ba12d9cccac913
|
[
"Zlib"
] | null | null | null |
Lucy/include/RoundedRectangle.hpp
|
pL0ck/LUCY
|
3fdc467d2b32f8c53ed42d40c5ba12d9cccac913
|
[
"Zlib"
] | null | null | null |
#pragma once
#define _USE_MATH_DEFINES
#include <cmath>
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Shape.hpp>
#include "Config.hpp"
namespace Lucy
{
////////////////////////////////////////////////////////////
/// \brief Specialized shape representing a rectangle
/// with rounded corners
////////////////////////////////////////////////////////////
class LUCY_API RoundedRectangle : public sf::Shape
{
public:
RoundedRectangle();
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// \param size PsetSize of the rectangle
/// \param radius Radius for each rounded corner
/// \param cornerPointCount Number of points of each corner
///
////////////////////////////////////////////////////////////
void RoundedRectangle2(const sf::Vector2f& size = sf::Vector2f(0, 0), float radius = 0, unsigned int cornerPointCount = 0, const Lucy::Corners& displayCorners = Lucy::Corners::All);
////////////////////////////////////////////////////////////
/// \brief Set the size of the rounded rectangle
///
/// \param size New size of the rounded rectangle
///
/// \see getSize
///
////////////////////////////////////////////////////////////
void setSize(const sf::Vector2f& size);
////////////////////////////////////////////////////////////
/// \brief Get the size of the rounded rectangle
///
/// \return PsetSize of the rounded rectangle
///
/// \see PsetSize
///
////////////////////////////////////////////////////////////
const sf::Vector2f& getSize() const;
////////////////////////////////////////////////////////////
/// \brief Set the radius of the rounded corners
///
/// \param radius Radius of the rounded corners
///
/// \see getCornersRadius
///
////////////////////////////////////////////////////////////
void setCornerRadius(float radius);
////////////////////////////////////////////////////////////
/// \brief Get the radius of the rounded corners
///
/// \return Radius of the rounded corners
///
/// \see setCornersRadius
///
////////////////////////////////////////////////////////////
float getCornerRadius() const;
////////////////////////////////////////////////////////////
/// \brief Set the number of points of each corner
///
/// \param count New number of points of the rounded rectangle
///
/// \see getPointCount
///
////////////////////////////////////////////////////////////
void setCornerPointCount(unsigned int count);
////////////////////////////////////////////////////////////
/// \brief Set the corners to display
///
/// \param a list of corners
///
////////////////////////////////////////////////////////////
void setDisplayCorners(const Lucy::Corners& displayCorners);
////////////////////////////////////////////////////////////
/// \brief Get the number of points defining the rounded rectangle
///
/// \return Number of points of the rounded rectangle
///
////////////////////////////////////////////////////////////
virtual std::size_t getPointCount() const;
////////////////////////////////////////////////////////////
/// \brief Get a point of the rounded rectangle
///
/// The result is undefined if \a index is out of the valid range.
///
/// \param index Index of the point to get, in range [0 .. GetPointCount() - 1]
///
/// \return Index-th point of the shape
///
////////////////////////////////////////////////////////////
virtual sf::Vector2f getPoint(std::size_t index) const;
////////////////////////////////////////////////////////////
/// \brief Update teh shape when properties change
///
///
////////////////////////////////////////////////////////////
void UpdateShape();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
sf::Vector2f mySize;
float myRadius;
unsigned int myCornerPointCount;
unsigned int myCorners;
unsigned int NumberOfRoundedCorners;
unsigned int ActualPoints;
double deltaAngle;
mutable std::size_t centerIndex;
unsigned int swapIndex[4];
unsigned int IndexAdjustment[4] = { 0,0,0,0 };
};
}
| 36.755556
| 189
| 0.369206
|
pL0ck
|
97139e3a1b2e57e13367a666c0001d70f1885ff5
| 9,955
|
cpp
|
C++
|
vrclient_x64/vrclient_x64/struct_converters_0913.cpp
|
SSYSS000/Proton
|
79ddcc55688fffae9a74f230d825b1dbd6db82a9
|
[
"MIT",
"BSD-3-Clause"
] | 17,337
|
2018-08-21T21:43:27.000Z
|
2022-03-31T18:06:05.000Z
|
vrclient_x64/vrclient_x64/struct_converters_0913.cpp
|
SSYSS000/Proton
|
79ddcc55688fffae9a74f230d825b1dbd6db82a9
|
[
"MIT",
"BSD-3-Clause"
] | 5,641
|
2018-08-21T22:40:50.000Z
|
2022-03-31T23:58:40.000Z
|
vrclient_x64/vrclient_x64/struct_converters_0913.cpp
|
SSYSS000/Proton
|
79ddcc55688fffae9a74f230d825b1dbd6db82a9
|
[
"MIT",
"BSD-3-Clause"
] | 910
|
2018-08-21T22:54:53.000Z
|
2022-03-29T17:35:31.000Z
|
#include <stdlib.h>
#include <string.h>
#include "vrclient_private.h"
#include "vrclient_defs.h"
#include "openvr_v0.9.13/openvr.h"
using namespace vr;
extern "C" {
#include "struct_converters.h"
#pragma pack(push, 8)
struct winVRControllerState001_t_0913 {
uint32_t unPacketNum;
uint64_t ulButtonPressed;
uint64_t ulButtonTouched;
vr::VRControllerAxis_t rAxis[5];
} __attribute__ ((ms_struct));
#pragma pack(pop)
void struct_VRControllerState001_t_0913_lin_to_win(void *l, void *w, uint32_t sz)
{
struct winVRControllerState001_t_0913 *win = (struct winVRControllerState001_t_0913 *)w;
VRControllerState001_t *lin = (VRControllerState001_t *)l;
win->unPacketNum = lin->unPacketNum;
win->ulButtonPressed = lin->ulButtonPressed;
win->ulButtonTouched = lin->ulButtonTouched;
memcpy(win->rAxis, lin->rAxis, sizeof(win->rAxis));
}
void struct_VRControllerState001_t_0913_win_to_lin(void *w, void *l)
{
struct winVRControllerState001_t_0913 *win = (struct winVRControllerState001_t_0913 *)w;
VRControllerState001_t *lin = (VRControllerState001_t *)l;
lin->unPacketNum = win->unPacketNum;
lin->ulButtonPressed = win->ulButtonPressed;
lin->ulButtonTouched = win->ulButtonTouched;
memcpy(lin->rAxis, win->rAxis, sizeof(lin->rAxis));
}
#pragma pack(push, 8)
struct winCameraVideoStreamFrame_t_0913 {
vr::ECameraVideoStreamFormat m_nStreamFormat;
uint32_t m_nWidth;
uint32_t m_nHeight;
uint32_t m_nFrameSequence;
uint32_t m_nTimeStamp;
uint32_t m_nBufferIndex;
uint32_t m_nBufferCount;
uint32_t m_nImageDataSize;
double m_flFrameElapsedTime;
double m_flFrameCaptureTime;
bool m_bPoseIsValid;
vr::HmdMatrix34_t m_matDeviceToAbsoluteTracking __attribute__((aligned(4)));
float m_Pad[4];
void * m_pImageData;
} __attribute__ ((ms_struct));
#pragma pack(pop)
void struct_CameraVideoStreamFrame_t_0913_lin_to_win(void *l, void *w)
{
struct winCameraVideoStreamFrame_t_0913 *win = (struct winCameraVideoStreamFrame_t_0913 *)w;
CameraVideoStreamFrame_t *lin = (CameraVideoStreamFrame_t *)l;
win->m_nStreamFormat = lin->m_nStreamFormat;
win->m_nWidth = lin->m_nWidth;
win->m_nHeight = lin->m_nHeight;
win->m_nFrameSequence = lin->m_nFrameSequence;
win->m_nTimeStamp = lin->m_nTimeStamp;
win->m_nBufferIndex = lin->m_nBufferIndex;
win->m_nBufferCount = lin->m_nBufferCount;
win->m_nImageDataSize = lin->m_nImageDataSize;
win->m_flFrameElapsedTime = lin->m_flFrameElapsedTime;
win->m_flFrameCaptureTime = lin->m_flFrameCaptureTime;
win->m_bPoseIsValid = lin->m_bPoseIsValid;
win->m_matDeviceToAbsoluteTracking = lin->m_matDeviceToAbsoluteTracking;
memcpy(win->m_Pad, lin->m_Pad, sizeof(win->m_Pad));
win->m_pImageData = lin->m_pImageData;
}
void struct_CameraVideoStreamFrame_t_0913_win_to_lin(void *w, void *l)
{
struct winCameraVideoStreamFrame_t_0913 *win = (struct winCameraVideoStreamFrame_t_0913 *)w;
CameraVideoStreamFrame_t *lin = (CameraVideoStreamFrame_t *)l;
lin->m_nStreamFormat = win->m_nStreamFormat;
lin->m_nWidth = win->m_nWidth;
lin->m_nHeight = win->m_nHeight;
lin->m_nFrameSequence = win->m_nFrameSequence;
lin->m_nTimeStamp = win->m_nTimeStamp;
lin->m_nBufferIndex = win->m_nBufferIndex;
lin->m_nBufferCount = win->m_nBufferCount;
lin->m_nImageDataSize = win->m_nImageDataSize;
lin->m_flFrameElapsedTime = win->m_flFrameElapsedTime;
lin->m_flFrameCaptureTime = win->m_flFrameCaptureTime;
lin->m_bPoseIsValid = win->m_bPoseIsValid;
lin->m_matDeviceToAbsoluteTracking = win->m_matDeviceToAbsoluteTracking;
memcpy(lin->m_Pad, win->m_Pad, sizeof(lin->m_Pad));
lin->m_pImageData = win->m_pImageData;
}
#pragma pack(push, 8)
struct winCompositor_FrameTiming_0913 {
uint32_t size;
double frameStart;
float frameVSync;
uint32_t droppedFrames;
uint32_t frameIndex;
vr::TrackedDevicePose_t pose __attribute__((aligned(4)));
float prediction;
float m_flFrameIntervalMs;
float m_flSceneRenderCpuMs;
float m_flSceneRenderGpuMs;
float m_flCompositorRenderCpuMs;
float m_flCompositorRenderGpuMs;
float m_flPresentCallCpuMs;
float m_flRunningStartMs;
float m_flHandoffStartMs;
float m_flHandoffEndMs;
float m_flCompositorUpdateCpuMs;
} __attribute__ ((ms_struct));
#pragma pack(pop)
void struct_Compositor_FrameTiming_0913_lin_to_win(void *l, void *w)
{
struct winCompositor_FrameTiming_0913 *win = (struct winCompositor_FrameTiming_0913 *)w;
Compositor_FrameTiming *lin = (Compositor_FrameTiming *)l;
win->size = sizeof(*win);
win->frameStart = lin->frameStart;
win->frameVSync = lin->frameVSync;
win->droppedFrames = lin->droppedFrames;
win->frameIndex = lin->frameIndex;
win->pose = lin->pose;
win->prediction = lin->prediction;
win->m_flFrameIntervalMs = lin->m_flFrameIntervalMs;
win->m_flSceneRenderCpuMs = lin->m_flSceneRenderCpuMs;
win->m_flSceneRenderGpuMs = lin->m_flSceneRenderGpuMs;
win->m_flCompositorRenderCpuMs = lin->m_flCompositorRenderCpuMs;
win->m_flCompositorRenderGpuMs = lin->m_flCompositorRenderGpuMs;
win->m_flPresentCallCpuMs = lin->m_flPresentCallCpuMs;
win->m_flRunningStartMs = lin->m_flRunningStartMs;
win->m_flHandoffStartMs = lin->m_flHandoffStartMs;
win->m_flHandoffEndMs = lin->m_flHandoffEndMs;
win->m_flCompositorUpdateCpuMs = lin->m_flCompositorUpdateCpuMs;
}
void struct_Compositor_FrameTiming_0913_win_to_lin(void *w, void *l)
{
struct winCompositor_FrameTiming_0913 *win = (struct winCompositor_FrameTiming_0913 *)w;
Compositor_FrameTiming *lin = (Compositor_FrameTiming *)l;
lin->size = sizeof(*lin);
lin->frameStart = win->frameStart;
lin->frameVSync = win->frameVSync;
lin->droppedFrames = win->droppedFrames;
lin->frameIndex = win->frameIndex;
lin->pose = win->pose;
lin->prediction = win->prediction;
lin->m_flFrameIntervalMs = win->m_flFrameIntervalMs;
lin->m_flSceneRenderCpuMs = win->m_flSceneRenderCpuMs;
lin->m_flSceneRenderGpuMs = win->m_flSceneRenderGpuMs;
lin->m_flCompositorRenderCpuMs = win->m_flCompositorRenderCpuMs;
lin->m_flCompositorRenderGpuMs = win->m_flCompositorRenderGpuMs;
lin->m_flPresentCallCpuMs = win->m_flPresentCallCpuMs;
lin->m_flRunningStartMs = win->m_flRunningStartMs;
lin->m_flHandoffStartMs = win->m_flHandoffStartMs;
lin->m_flHandoffEndMs = win->m_flHandoffEndMs;
lin->m_flCompositorUpdateCpuMs = win->m_flCompositorUpdateCpuMs;
}
#pragma pack(push, 8)
struct winRenderModel_TextureMap_t_0913 {
uint16_t unWidth;
uint16_t unHeight;
const uint8_t * rubTextureMapData;
RenderModel_TextureMap_t *linux_side;
} __attribute__ ((ms_struct));
#pragma pack(pop)
void struct_RenderModel_TextureMap_t_0913_lin_to_win(void *l, void *w)
{
struct winRenderModel_TextureMap_t_0913 *win = (struct winRenderModel_TextureMap_t_0913 *)w;
RenderModel_TextureMap_t *lin = (RenderModel_TextureMap_t *)l;
win->unWidth = lin->unWidth;
win->unHeight = lin->unHeight;
win->rubTextureMapData = lin->rubTextureMapData;
}
void struct_RenderModel_TextureMap_t_0913_win_to_lin(void *w, void *l)
{
struct winRenderModel_TextureMap_t_0913 *win = (struct winRenderModel_TextureMap_t_0913 *)w;
RenderModel_TextureMap_t *lin = (RenderModel_TextureMap_t *)l;
lin->unWidth = win->unWidth;
lin->unHeight = win->unHeight;
lin->rubTextureMapData = win->rubTextureMapData;
}
struct winRenderModel_TextureMap_t_0913 *struct_RenderModel_TextureMap_t_0913_wrap(void *l)
{
struct winRenderModel_TextureMap_t_0913 *win = (struct winRenderModel_TextureMap_t_0913 *)malloc(sizeof(*win));
RenderModel_TextureMap_t *lin = (RenderModel_TextureMap_t *)l;
win->unWidth = lin->unWidth;
win->unHeight = lin->unHeight;
win->rubTextureMapData = lin->rubTextureMapData;
win->linux_side = lin;
return win;
}
struct RenderModel_TextureMap_t *struct_RenderModel_TextureMap_t_0913_unwrap(winRenderModel_TextureMap_t_0913 *w)
{
RenderModel_TextureMap_t *ret = w->linux_side;
free(w);
return ret;
}
#pragma pack(push, 8)
struct winRenderModel_t_0913 {
const vr::RenderModel_Vertex_t * rVertexData;
uint32_t unVertexCount;
const uint16_t * rIndexData;
uint32_t unTriangleCount;
vr::TextureID_t diffuseTextureId;
RenderModel_t *linux_side;
} __attribute__ ((ms_struct));
#pragma pack(pop)
void struct_RenderModel_t_0913_lin_to_win(void *l, void *w)
{
struct winRenderModel_t_0913 *win = (struct winRenderModel_t_0913 *)w;
RenderModel_t *lin = (RenderModel_t *)l;
win->rVertexData = lin->rVertexData;
win->unVertexCount = lin->unVertexCount;
win->rIndexData = lin->rIndexData;
win->unTriangleCount = lin->unTriangleCount;
win->diffuseTextureId = lin->diffuseTextureId;
}
void struct_RenderModel_t_0913_win_to_lin(void *w, void *l)
{
struct winRenderModel_t_0913 *win = (struct winRenderModel_t_0913 *)w;
RenderModel_t *lin = (RenderModel_t *)l;
lin->rVertexData = win->rVertexData;
lin->unVertexCount = win->unVertexCount;
lin->rIndexData = win->rIndexData;
lin->unTriangleCount = win->unTriangleCount;
lin->diffuseTextureId = win->diffuseTextureId;
}
struct winRenderModel_t_0913 *struct_RenderModel_t_0913_wrap(void *l)
{
struct winRenderModel_t_0913 *win = (struct winRenderModel_t_0913 *)malloc(sizeof(*win));
RenderModel_t *lin = (RenderModel_t *)l;
win->rVertexData = lin->rVertexData;
win->unVertexCount = lin->unVertexCount;
win->rIndexData = lin->rIndexData;
win->unTriangleCount = lin->unTriangleCount;
win->diffuseTextureId = lin->diffuseTextureId;
win->linux_side = lin;
return win;
}
struct RenderModel_t *struct_RenderModel_t_0913_unwrap(winRenderModel_t_0913 *w)
{
RenderModel_t *ret = w->linux_side;
free(w);
return ret;
}
}
| 37.284644
| 115
| 0.749874
|
SSYSS000
|
97166fc7c56eb66ec8f9dc088cb0383a9ead90db
| 4,080
|
cpp
|
C++
|
src/TGAMaker/DirectX/DirectSound/DirectSound.cpp
|
vitek-karas/WarPlusPlus
|
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
|
[
"MIT"
] | 4
|
2019-06-17T13:44:49.000Z
|
2021-01-19T10:39:48.000Z
|
src/TGAMaker/DirectX/DirectSound/DirectSound.cpp
|
vitek-karas/WarPlusPlus
|
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
|
[
"MIT"
] | null | null | null |
src/TGAMaker/DirectX/DirectSound/DirectSound.cpp
|
vitek-karas/WarPlusPlus
|
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
|
[
"MIT"
] | 4
|
2019-06-17T16:03:20.000Z
|
2020-02-15T09:14:30.000Z
|
// DirectSound.cpp: implementation of the CDirectSound class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "DirectSound.h"
#include "DirectSoundException.h"
#include "DSoundBuffer.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
IMPLEMENT_DYNAMIC(CDirectSound, CObserver);
BEGIN_OBSERVER_MAP(CDirectSound, CObserver)
BEGIN_ABORT()
ON_ABORT()
END_ABORT()
END_OBSERVER_MAP(CDirectSound, CObserver)
CDirectSound::CDirectSound()
{
m_lpDirectSound = NULL;
m_pBuffers = NULL;
m_bDummy = FALSE;
}
CDirectSound::~CDirectSound()
{
Delete();
}
CDirectSound *g_pDirectSound = NULL;
#ifdef _DEBUG
void CDirectSound::AssertValid() const
{
CObserver::AssertValid();
if(m_bDummy) return;
ASSERT(m_lpDirectSound != NULL);
}
void CDirectSound::Dump(CDumpContext &dc) const
{
CObserver::Dump(dc);
if(m_bDummy){
dc << "Dummy DirectSound object.\n";
}
else{
dc << "IDirectSound pointer : " << m_lpDirectSound << "\n";
}
}
#endif
BOOL CDirectSound::Create(CWnd *pWindow, DWORD dwFlags)
{
ASSERT(g_pDirectSound == NULL);
m_hResult = DirectSoundCreate(NULL, &m_lpDirectSound, NULL);
DIRECTSOUND_ERROR(m_hResult);
m_hResult = m_lpDirectSound->SetCooperativeLevel(pWindow->GetSafeHwnd(), dwFlags);
DIRECTSOUND_ERROR(m_hResult);
g_pDirectSound = this;
// we will react to the abort by destroying our object
g_AbortNotifier.Connect(this);
return TRUE;
}
void CDirectSound::Delete()
{
if(m_bDummy){
m_bDummy = FALSE;
return;
}
if(m_lpDirectSound){
// no more abort notifications needed
g_AbortNotifier.Disconnect(this);
ASSERT(g_pDirectSound == this);
g_pDirectSound = NULL;
m_lpDirectSound->Release();
m_lpDirectSound = NULL;
}
}
LPDIRECTSOUND CDirectSound::GetLP()
{
if(m_bDummy) return NULL;
m_lpDirectSound->AddRef();
return m_lpDirectSound;
}
BOOL CDirectSound::CreateSoundBuffer(CDSoundBuffer *pDSoundBuffer, DSBUFFERDESC *pDSBD)
{
PCMWAVEFORMAT pcmwf;
DSBUFFERDESC dsbdesc;
LPDIRECTSOUNDBUFFER lpDSBuffer;
if(!m_bDummy){
if(pDSBD == NULL){
memset(&pcmwf, 0, sizeof(PCMWAVEFORMAT));
pcmwf.wf.wFormatTag = WAVE_FORMAT_PCM;
memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
dsbdesc.dwSize = sizeof(DSBUFFERDESC);
dsbdesc.lpwfxFormat = (LPWAVEFORMATEX)&pcmwf;
if(!pDSoundBuffer->PreCreate(&dsbdesc, &pcmwf)) return FALSE;
pDSBD = &dsbdesc;
}
m_hResult = m_lpDirectSound->CreateSoundBuffer(pDSBD, &lpDSBuffer, NULL);
DIRECTSOUND_ERROR(m_hResult);
if(!pDSoundBuffer->PostCreate(lpDSBuffer)) return FALSE;
}
if(m_bDummy){
pDSoundBuffer->m_bDummy = TRUE;
}
// Add the buffer to the list of all surfaces
pDSoundBuffer->m_pDirectSound = this;
pDSoundBuffer->m_pNextSoundBuffer = m_pBuffers;
m_pBuffers = pDSoundBuffer;
pDSoundBuffer->m_bRemoveFromList = TRUE;
return TRUE;
}
void CDirectSound::DeleteSoundBuffer(CDSoundBuffer *pDSoundBuffer)
{
CDSoundBuffer *pCurrent;
if(m_pBuffers == pDSoundBuffer){
m_pBuffers = pDSoundBuffer->m_pNextSoundBuffer;
return;
}
pCurrent = m_pBuffers;
while(pCurrent->m_pNextSoundBuffer != pDSoundBuffer){
if(pCurrent->m_pNextSoundBuffer == NULL){
ASSERT(FALSE); // Given buffer was not created by us
return; // We failed to find it
}
pCurrent = pCurrent->m_pNextSoundBuffer;
}
// remove it from list
pCurrent->m_pNextSoundBuffer = pDSoundBuffer->m_pNextSoundBuffer;
}
// on abort we will destroy our object
void CDirectSound::OnAbort(DWORD dwExitCode)
{
Delete();
}
// creates this object with dummy data
// it means it will behave as normal, but no sound will be produced
void CDirectSound::CreateDummy()
{
m_bDummy = TRUE;
ASSERT(g_pDirectSound == NULL);
g_pDirectSound = this;
}
| 21.587302
| 87
| 0.67402
|
vitek-karas
|
971815529f54f7462b7f38abb6a878856dd610f4
| 856
|
hpp
|
C++
|
include/mudpp/engine/state/create.hpp
|
Klaim/mudpp
|
b54b855c394cb5eb5b4b43c4e116c879bd7f0a2f
|
[
"MIT"
] | null | null | null |
include/mudpp/engine/state/create.hpp
|
Klaim/mudpp
|
b54b855c394cb5eb5b4b43c4e116c879bd7f0a2f
|
[
"MIT"
] | null | null | null |
include/mudpp/engine/state/create.hpp
|
Klaim/mudpp
|
b54b855c394cb5eb5b4b43c4e116c879bd7f0a2f
|
[
"MIT"
] | null | null | null |
//==================================================================================================
/**
MudPP - MUD engine for C++
Copyright 2019-2020 Joel FALCOU
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#ifndef MUDPP_ENGINE_STATE_CREATE_HPP_INCLUDED
#define MUDPP_ENGINE_STATE_CREATE_HPP_INCLUDED
#include <mudpp/engine/game_state.hpp>
#include <memory>
namespace mudpp
{
struct player;
struct create_state final : public game_state
{
create_state(player* p);
static std::unique_ptr<create_state> make(player* p);
virtual game_state* process_input(std::string const& input);
private:
player* current_player_;
int current_step_;
};
}
#endif
| 24.457143
| 100
| 0.559579
|
Klaim
|
971b7705cd19a424225c4128cdf82793137b1471
| 1,182
|
cpp
|
C++
|
Trik.cpp
|
PapaFluff/Kattis
|
b646f66db1551cdb3601065125299b23da65df32
|
[
"MIT"
] | null | null | null |
Trik.cpp
|
PapaFluff/Kattis
|
b646f66db1551cdb3601065125299b23da65df32
|
[
"MIT"
] | null | null | null |
Trik.cpp
|
PapaFluff/Kattis
|
b646f66db1551cdb3601065125299b23da65df32
|
[
"MIT"
] | null | null | null |
// All needed preprocessor directives
#include <iostream>
#include <string>
using namespace std;
// Main function, the primary driver of the program
int main()
{
bool Ball[3] = {true, false, false}; // Creates an array bool for where the ball is located
string BorkosMoves; // Creates a string to be Borkos moves
cin >> BorkosMoves; // Takes input for string
// For loop that records his swaps based on diagram on Kattis
for(int i = 0; i < BorkosMoves.size(); i++)
{
if(BorkosMoves[i] == 'A')
{
swap(Ball[0], Ball[1]);
}
else if(BorkosMoves[i] == 'B')
{
swap(Ball[1], Ball[2]);
}
else if(BorkosMoves[i] == 'C')
{
swap(Ball[0], Ball[2]);
}
}
if(Ball[0]) // The ball is located at the 1st cup
{
cout << "1" << endl;
}
else if(Ball[1]) // The ball is located at the 2nd cup
{
cout << "2" << endl;
}
else if(Ball[2]) // The ball is located at the 3rd cup
{
cout << "3" << endl;
}
return 0; // Returns 0 to end program properly for int main
}
| 26.266667
| 98
| 0.521997
|
PapaFluff
|
971b8624b6e98c31b3979cd0d5a7bfded902d5af
| 697
|
cpp
|
C++
|
src/MathUtils.cpp
|
LeifNode/World-Generator
|
f9818fb6c5d507eede76141c2687a66f090cbdc1
|
[
"MIT"
] | 16
|
2015-02-12T20:56:01.000Z
|
2021-05-31T21:05:41.000Z
|
src/MathUtils.cpp
|
LeifNode/World-Generator
|
f9818fb6c5d507eede76141c2687a66f090cbdc1
|
[
"MIT"
] | null | null | null |
src/MathUtils.cpp
|
LeifNode/World-Generator
|
f9818fb6c5d507eede76141c2687a66f090cbdc1
|
[
"MIT"
] | 3
|
2017-02-05T15:52:34.000Z
|
2018-02-09T08:51:00.000Z
|
#include "MathUtils.h"
#include <float.h>
#include <cmath>
const float MathUtils::Infinity = FLT_MAX;
const float MathUtils::Pi = 3.1415926535f;
const float MathUtils::TwoPi = Pi * 2.0f;
const float MathUtils::PiOver2 = Pi / 2.0f;
const float MathUtils::PiOver4 = Pi / 4.0f;
float MathUtils::AngleFromXY(float x, float y)
{
float theta = 0.0f;
// Quadrant I or IV
if(x >= 0.0f)
{
// If x = 0, then atanf(y/x) = +pi/2 if y > 0
// atanf(y/x) = -pi/2 if y < 0
theta = atanf(y / x); // in [-pi/2, +pi/2]
if(theta < 0.0f)
theta += 2.0f*Pi; // in [0, 2*pi).
}
// Quadrant II or III
else
theta = atanf(y/x) + Pi; // in [0, 2*pi).
return theta;
}
| 22.483871
| 48
| 0.575323
|
LeifNode
|
9722b1f6a6381b4f07d49be09f94928ed22a43f7
| 1,040
|
hpp
|
C++
|
sc-memory/tests/performance/units/memory_test.hpp
|
FallenChromium/sc-machine-1
|
90c9605d9e1846e07705a7a579fe33ee8768c33a
|
[
"MIT"
] | null | null | null |
sc-memory/tests/performance/units/memory_test.hpp
|
FallenChromium/sc-machine-1
|
90c9605d9e1846e07705a7a579fe33ee8768c33a
|
[
"MIT"
] | 9
|
2022-03-01T07:33:48.000Z
|
2022-03-24T17:06:07.000Z
|
sc-memory/tests/performance/units/memory_test.hpp
|
FallenChromium/sc-machine-1
|
90c9605d9e1846e07705a7a579fe33ee8768c33a
|
[
"MIT"
] | 7
|
2022-02-18T13:34:24.000Z
|
2022-03-25T09:59:42.000Z
|
/*
* This source file is part of an OSTIS project. For the latest info, see http://ostis.net
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#pragma once
#include <memory>
#include "sc-memory/sc_memory.hpp"
#include "sc-core/sc_memory.h"
class TestMemory
{
public:
void Initialize(size_t objectsNum = 0)
{
sc_memory_params params;
sc_memory_params_clear(¶ms);
params.clear = SC_TRUE;
params.repo_path = "test_repo";
ScMemory::LogMute();
ScMemory::Initialize(params);
InitContext();
Setup(objectsNum);
}
void Shutdown()
{
m_ctx.reset();
ScMemory::Shutdown(false);
}
void InitContext()
{
m_ctx = std::make_unique<ScMemoryContext>(sc_access_lvl_make_min, "test");
}
void DestroyContext()
{
m_ctx.reset();
}
bool HasContext() const
{
return static_cast<bool>(m_ctx);
}
virtual void Setup(size_t objectsNum) {}
protected:
std::unique_ptr<ScMemoryContext> m_ctx {};
};
| 18.245614
| 89
| 0.680769
|
FallenChromium
|
97295eb4da822854ae5217d24dd717d462038d9a
| 4,175
|
hpp
|
C++
|
include/furi/pct_encode.hpp
|
LeonineKing1199/furi
|
f9d1cd4721950393b0c47d7fe4c5c8999c2bdddf
|
[
"BSL-1.0"
] | 4
|
2020-01-22T22:42:52.000Z
|
2021-03-21T16:49:41.000Z
|
include/furi/pct_encode.hpp
|
LeonineKing1199/furi
|
f9d1cd4721950393b0c47d7fe4c5c8999c2bdddf
|
[
"BSL-1.0"
] | null | null | null |
include/furi/pct_encode.hpp
|
LeonineKing1199/furi
|
f9d1cd4721950393b0c47d7fe4c5c8999c2bdddf
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/LeonineKing1199/furi
//
#ifndef FURI_PCT_ENCODE_HPP_
#define FURI_PCT_ENCODE_HPP_
#include <furi/uri.hpp>
#include <furi/utf8.hpp>
#include <furi/code_point_view.hpp>
#include <string_view>
#include <boost/locale/utf.hpp>
#include <boost/spirit/include/karma_generate.hpp>
#include <boost/spirit/include/karma_string.hpp>
#include <boost/spirit/include/karma_sequence.hpp>
#include <boost/spirit/include/karma_numeric.hpp>
#include <boost/spirit/include/karma_right_alignment.hpp>
#include <cstdint>
#include <cstring>
#include <string>
#include <array>
#include <iterator>
#include <type_traits>
namespace furi
{
namespace uri
{
template <class OutputIterator>
auto
encode_host(std::u32string_view const host, OutputIterator out) -> OutputIterator
{
namespace x3 = boost::spirit::x3;
namespace utf = boost::locale::utf;
namespace karma = boost::spirit::karma;
auto pos = host.begin();
auto match = x3::parse(pos, host.end(), unicode::ip_literal | unicode::ip_v4_address);
if (match) {
for (auto const code_point : host) { out = utf::utf_traits<char>::encode(code_point, out); }
return out;
}
for (auto const code_point : host) {
pos = host.begin();
// no need to encode the normal ascii set
//
if ((code_point > 32) && (code_point < 127) &&
std::u32string_view(U"\"#/<>?@[\\]^`{|}").find(code_point) == std::u32string_view::npos) {
out = utf::utf_traits<char>::encode(code_point, out);
continue;
}
auto buffer = std::array<char, 4>{0x7f, 0x7f, 0x7f, 0x7f};
auto const end = ::furi::utf8_encode(code_point, buffer.begin());
for (auto pos = buffer.begin(); pos < end; ++pos) {
karma::generate(out, karma::lit("%") << karma::right_align(2, karma::lit("0"))[karma::hex],
*pos);
}
}
return out;
}
template <class OutputIterator>
auto
encode_path(std::u32string_view const host, OutputIterator out) -> OutputIterator
{
namespace x3 = boost::spirit::x3;
namespace utf = boost::locale::utf;
namespace karma = boost::spirit::karma;
for (auto const code_point : host) {
// no need to encode the normal ascii set
//
if ((code_point > 32) && (code_point < 127) &&
std::u32string_view(U"\"#<>?[\\]^`{|}").find(code_point) == std::u32string_view::npos) {
out = utf::utf_traits<char>::encode(code_point, out);
continue;
}
auto buffer = std::array<char, 4>{0x7f, 0x7f, 0x7f, 0x7f};
auto const end = ::furi::utf8_encode(code_point, buffer.begin());
for (auto pos = buffer.begin(); pos < end; ++pos) {
karma::generate(out, karma::lit("%") << karma::right_align(2, karma::lit("0"))[karma::hex],
*pos);
}
}
return out;
}
template <class OutputIterator>
auto
encode_query(std::u32string_view const host, OutputIterator out) -> OutputIterator
{
namespace x3 = boost::spirit::x3;
namespace utf = boost::locale::utf;
namespace karma = boost::spirit::karma;
for (auto const code_point : host) {
// no need to encode the normal ascii set
//
if ((code_point > 32) && (code_point < 127) &&
std::u32string_view(U"\"#:<>@[\\]^`{|}").find(code_point) == std::u32string_view::npos) {
out = utf::utf_traits<char>::encode(code_point, out);
continue;
}
auto buffer = std::array<char, 4>{0x7f, 0x7f, 0x7f, 0x7f};
auto const end = ::furi::utf8_encode(code_point, buffer.begin());
for (auto pos = buffer.begin(); pos < end; ++pos) {
karma::generate(out, karma::lit("%") << karma::right_align(2, karma::lit("0"))[karma::hex],
*pos);
}
}
return out;
}
template <class OutputIterator>
auto
encode_fragment(std::u32string_view const host, OutputIterator out) -> OutputIterator
{
return encode_query(host, out);
}
} // namespace uri
} // namespace furi
#endif // FURI_PCT_ENCODE_HPP_
| 28.209459
| 100
| 0.651257
|
LeonineKing1199
|
972b06b0e3b76132887270234fca403d3d078242
| 983
|
cpp
|
C++
|
Leetcode/10.Regex.cpp
|
EdwaRen/Competitve_Programming
|
e8bffeb457936d28c75ecfefb5a1f316c15a9b6c
|
[
"MIT"
] | 1
|
2017-08-10T16:59:01.000Z
|
2017-08-10T16:59:01.000Z
|
Leetcode/10.Regex.cpp
|
EdwaRen/Competitve_Programming
|
e8bffeb457936d28c75ecfefb5a1f316c15a9b6c
|
[
"MIT"
] | null | null | null |
Leetcode/10.Regex.cpp
|
EdwaRen/Competitve_Programming
|
e8bffeb457936d28c75ecfefb5a1f316c15a9b6c
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
using namespace std;
bool isMatchAnswer(string s, string p) {
// if (p.empty()) return s.empty();
//
// if ('*' == p[1])
// // x* matches empty string or at least one character: x* -> xx*
// // *s is to ensure s is non-empty
// return (isMatch(s, p.substr(2)) || !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p));
// else
// return !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p.substr(1));
}
bool isMatch(string s, string p) {
if (p.empty()) {
return s.empty();
}
if (p[1] == '*') {
return ( isMatch(s, p.substr(2)) || !s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p) );
} else {
return ( (!s.empty() && isMatch(s.substr(1), p.substr(1)) && ((s[0] == p[0]) ||p[0] == '.' ) ) );
}
}
int main() {
int a = isMatch("aceer", "ace*.");
// string a = "ADSdASD"
cout << a << endl;
return 0;
}
| 26.567568
| 118
| 0.467955
|
EdwaRen
|
972d65d310a4f71805571224011b4bbd144c24e8
| 417
|
cpp
|
C++
|
libs/systems/src/systems/audio_player_default.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/systems/src/systems/audio_player_default.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/systems/src/systems/audio_player_default.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/systems/audio_player.hpp>
#include <sge/systems/audio_player_default.hpp>
sge::systems::audio_player sge::systems::audio_player_default()
{
return sge::systems::audio_player();
}
| 32.076923
| 63
| 0.721823
|
cpreh
|
9734e9ea05022aee2a533c0581a5661ee5677c55
| 1,211
|
hpp
|
C++
|
libs/core/render/include/bksge/core/render/vulkan/detail/shader_module.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/core/render/include/bksge/core/render/vulkan/detail/shader_module.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/core/render/include/bksge/core/render/vulkan/detail/shader_module.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file shader_module.hpp
*
* @brief ShaderModule クラスの定義
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_VULKAN_DETAIL_SHADER_MODULE_HPP
#define BKSGE_CORE_RENDER_VULKAN_DETAIL_SHADER_MODULE_HPP
#include <bksge/core/render/vulkan/detail/fwd/shader_module_fwd.hpp>
#include <bksge/core/render/vulkan/detail/fwd/device_fwd.hpp>
#include <bksge/core/render/vulkan/detail/vulkan.hpp>
#include <vector>
namespace bksge
{
namespace render
{
namespace vulkan
{
class ShaderModule
{
public:
explicit ShaderModule(
vulkan::DeviceSharedPtr const& device,
std::vector<unsigned int> const& spv);
~ShaderModule();
public:
operator ::VkShaderModule() const;
private:
// noncopyable
ShaderModule(ShaderModule const&) = delete;
ShaderModule& operator=(ShaderModule const&) = delete;
private:
::VkShaderModule m_shader_module;
vulkan::DeviceSharedPtr m_device;
};
} // namespace vulkan
} // namespace render
} // namespace bksge
#include <bksge/fnd/config.hpp>
#if defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/vulkan/detail/inl/shader_module_inl.hpp>
#endif
#endif // BKSGE_CORE_RENDER_VULKAN_DETAIL_SHADER_MODULE_HPP
| 20.183333
| 69
| 0.737407
|
myoukaku
|
97357305e510636efc3d730e5d874cc68148586b
| 8,695
|
cpp
|
C++
|
src/format.cpp
|
retrhelo/AST-Practice
|
2d2e23908d1d6877df35a41140b428a69c96470c
|
[
"MIT"
] | null | null | null |
src/format.cpp
|
retrhelo/AST-Practice
|
2d2e23908d1d6877df35a41140b428a69c96470c
|
[
"MIT"
] | null | null | null |
src/format.cpp
|
retrhelo/AST-Practice
|
2d2e23908d1d6877df35a41140b428a69c96470c
|
[
"MIT"
] | null | null | null |
#include <deque>
#include <string>
#include "../inc/format"
#pragma GCC dependence "../inc/format"
static std::deque<std::string> s;
static void enterDebug(std::string str) {
s.push_back(str);
}
static void debug_msg(std::string str) {
std::cerr << s.back() << ": "
<< str << std::endl;
}
static void debug_msg(char *str) {
std::cerr << s.back() << ": "
<< str << std::endl;
}
static void exitDebug(void) {
s.pop_back();
}
#define debug_error() \
do { \
std::cerr << lex.get_line() << ":" << lex.get_lineChar() << ": "; \
debug_msg("invalid token " + lex.get_token()); \
exitDebug(); \
return false; \
} while (false)
class token_pair {
public:
token_t type;
std::string token;
token_pair(token_t tp, std::string tk):
type(tp), token(tk) {}
};
static std::deque<token_pair> queue;
static void tokenMatchNext(Lexer &lex) {
queue.push_back(token_pair(lex.get_type(), lex.get_token()));
std::cerr << "matched: " <<
lex.get_line() << ":" << lex.get_lineChar() << ": "
<< lex.get_token() << std::endl;
lex.next();
}
static bool tokenTryMatchNext(Lexer &lex, token_t type) {
if (type == lex.get_type()) {
tokenMatchNext(lex);
return true;
}
else return false;
}
static bool storageTypeTryMatchNext(Lexer &lex) {
return tokenTryMatchNext(lex, keywordConst)
|| tokenTryMatchNext(lex, keywordAuto)
|| tokenTryMatchNext(lex, keywordStatic)
|| tokenTryMatchNext(lex, keywordVolatile)
|| tokenTryMatchNext(lex, keywordExtern);
}
static bool typeTryMatchNext(Lexer &lex) {
bool ret = tokenTryMatchNext(lex, keywordVoid)
||tokenTryMatchNext(lex, keywordChar)
|| tokenTryMatchNext(lex, keywordShort)
|| tokenTryMatchNext(lex, keywordInt)
|| tokenTryMatchNext(lex, keywordUnsigned)
|| tokenTryMatchNext(lex, keywordSigned)
|| tokenTryMatchNext(lex, keywordLong)
|| tokenTryMatchNext(lex, keywordFloat)
|| tokenTryMatchNext(lex, keywordDouble);
if (!ret && tokenTryMatchNext(lex, keywordStruct) ||
tokenTryMatchNext(lex, keywordUnion) ||
tokenTryMatchNext(lex, keywordEnum))
{
ret = tokenTryMatchNext(lex, tokenIdent);
}
return ret;
}
bool Format::formatProgramme(Lexer &lex, int indent) {
enterDebug("Programme");
bool ret;
while (lex.get_type() != tokenEOF) {
// struct-union-def
if (lex.get_type() == keywordStruct ||
lex.get_type() == keywordUnion)
{
stream << lex.get_token() << " ";
lex.next();
if (lex.get_type() != tokenIdent)
debug_error();
stream << lex.get_token() << " ";
lex.next();
if (lex.get_type() != punctLBrace)
debug_error();
stream << lex.get_token() << "\n";
lex.next();
while (lex.get_type() != punctRBrace) {
for (int i = 0; i < indent + 1; i ++)
stream << '\t';
while (true) {
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctSemicolon)
stream << " ";
else {
stream << lex.get_token() << std::endl;
lex.next();
break;
}
}
}
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctSemicolon)
debug_error();
else {
stream << ";\n\n";
lex.next();
}
}
// enum-def
else if (lex.get_type() == keywordEnum) {
lex.next();
stream << "enum " << lex.get_token();
lex.next();
if (lex.get_type() != punctLBrace)
debug_error();
stream << " {\n";
lex.next();
while (lex.get_type() != punctRBrace) {
for (int i = 0; i < indent + 1; i ++)
stream << '\t';
while (true) {
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctComma)
stream << ' ';
else {
stream << ",\n";
lex.next();
break;
}
}
}
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctSemicolon)
debug_error();
else {
stream << ";\n\n";
lex.next();
}
}
// var-def | func-def
else if (storageTypeTryMatchNext(lex)
|| typeTryMatchNext(lex))
{
typeTryMatchNext(lex);
while (lex.get_type() != punctSemicolon &&
lex.get_type() != punctLBrace)
{
tokenMatchNext(lex);
}
for (token_pair &it : queue)
stream << it.token << " ";
queue.clear();
if (lex.get_type() == punctLBrace) {
stream << lex.get_token() << std::endl;
lex.next();
ret = formatComplex(lex, indent + 1);
stream << "\n\n";
}
else {
stream << lex.get_token() << std::endl;
lex.next();
ret = true;
}
}
else debug_error();
}
exitDebug();
return ret;
}
/* pre-print:
"{"
*/
bool Format::formatComplex(Lexer &lex, int indent) {
enterDebug("Complex");
bool ret = true;
while (lex.get_type() != punctRBrace) {
for (int i = 0; i < indent; i ++)
stream << '\t';
switch (lex.get_type()) {
case keywordIf:
ret = formatIf(lex, indent + 1);
break;
case keywordWhile:
ret = formatWhile(lex, indent + 1);
break;
case keywordDo:
ret = formatDoWhile(lex, indent + 1);
break;
case keywordFor:
ret = formatFor(lex, indent + 1);
break;
default:
while (true) {
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctSemicolon)
stream << ' ';
else {
stream << ";\n";
lex.next();
break;
}
}
break;
}
}
for (int i = 0; i < indent - 1; i ++)
stream << '\t';
stream << '}';
lex.next();
if (false == ret) debug_error();
exitDebug();
return ret;
}
bool Format::formatIf(Lexer &lex, int indent) {
enterDebug("If");
bool ret = true;
stream << "if (";
lex.next(); lex.next();
int cnt = 1;
while (cnt > 0) {
if (lex.get_type() == punctLParen) cnt ++;
else if (lex.get_type() == punctRParen) cnt --;
stream << lex.get_token();
lex.next();
}
if (lex.get_type() == punctLBrace) {
stream << " {\n";
lex.next();
ret = formatComplex(lex, indent);
stream << std::endl;
}
else {
stream << std::endl;
ret = formatExpr(lex, indent);
}
if (lex.get_type() == keywordElse) {
for (int i = 0; i < indent - 1; i ++)
stream << '\t';
stream << "else ";
lex.next();
if (lex.get_type() == punctLBrace) {
stream << "{\n";
lex.next();
ret = formatComplex(lex, indent);
stream << std::endl;
}
else if (lex.get_type() == keywordIf)
ret = formatIf(lex, indent);
else {
stream << std::endl;
ret = formatExpr(lex, indent);
}
}
if (false == ret)
debug_error();
exitDebug();
return ret;
}
bool Format::formatWhile(Lexer &lex, int indent) {
enterDebug("While");
bool ret = true;
stream << "while (";
lex.next(); lex.next();
int cnt = 1;
while (cnt > 0) {
if (lex.get_type() == punctLParen) cnt ++;
else if (lex.get_type() == punctRParen) cnt --;
stream << lex.get_token();
lex.next();
}
if (lex.get_type() == punctLBrace) {
stream << " {\n";
lex.next();
ret = formatComplex(lex, indent);
stream << std::endl;
}
else {
stream << std::endl;
ret = formatExpr(lex, indent);
}
if (false == ret)
debug_error();
exitDebug();
return ret;
}
bool Format::formatDoWhile(Lexer &lex, int indent) {
enterDebug("DoWhile");
stream << "do {";
lex.next(); lex.next();
if (lex.get_type() == punctRBrace) {
stream << "} while (";
lex.next();lex.next();lex.next();
}
else {
stream << std::endl;
formatComplex(lex, indent);
stream << " while (";
lex.next(); lex.next();
}
while (lex.get_type() != punctSemicolon) {
stream << lex.get_token();
lex.next();
}
stream << ";\n";
lex.next();
exitDebug();
return true;
}
bool Format::formatFor(Lexer &lex, int indent) {
enterDebug("For");
stream << "for (";
lex.next(); lex.next();
while (true) {
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctSemicolon)
stream << ' ';
else {
stream << "; ";
lex.next();
break;
}
}
while (true) {
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctSemicolon)
stream << ' ';
else {
stream << "; ";
lex.next();
break;
}
}
while (true) {
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctRParen)
stream << ' ';
else {
stream << ") ";
lex.next();
break;
}
}
if (lex.get_type() == punctLBrace) {
stream << "{\n";
lex.next();
formatComplex(lex, indent);
stream << std::endl;
}
else {
stream << std::endl;
formatExpr(lex, indent);
}
exitDebug();
return true;
}
bool Format::formatExpr(Lexer &lex, int indent) {
enterDebug("Expression");
for (int i = 0; i < indent; i ++)
stream << '\t';
while (true) {
stream << lex.get_token();
lex.next();
if (lex.get_type() != punctSemicolon)
stream << ' ';
else {
stream << ";\n";
lex.next();
break;
}
}
exitDebug();
return true;
}
| 19.539326
| 69
| 0.576078
|
retrhelo
|
973607bb823caa5703c25364396bbb887e400846
| 1,085
|
cpp
|
C++
|
src/Actions/Sentences/SentenceListAction.cpp
|
viveret/script-ai
|
15f8dc561e55812de034bb729e83ff01bec61743
|
[
"BSD-3-Clause"
] | null | null | null |
src/Actions/Sentences/SentenceListAction.cpp
|
viveret/script-ai
|
15f8dc561e55812de034bb729e83ff01bec61743
|
[
"BSD-3-Clause"
] | null | null | null |
src/Actions/Sentences/SentenceListAction.cpp
|
viveret/script-ai
|
15f8dc561e55812de034bb729e83ff01bec61743
|
[
"BSD-3-Clause"
] | null | null | null |
#include "../Actions.hpp"
#include "../../Program.hpp"
#include "../../AIModelAdapter.hpp"
#include "../../Data/DAOs.hpp"
#include "../../Data/Commands/Sentences/SentenceQueryPagedCmd.hpp"
#include <math.h>
using namespace ScriptAI;
using namespace Sql;
SentenceListAction::SentenceListAction(AIProgram *prog): PagedAction(prog, 10) {
}
const char* SentenceListAction::label() {
return "sentence list";
}
std::string SentenceListAction::description() {
return "List the neural network's known sentences";
}
const char* SentenceListAction::empty_msg() {
return "Sentence list is empty";
}
size_t SentenceListAction::get_count() {
return SentenceCountCmd(SqlContext()).execute(nullptr);
}
size_t SentenceListAction::run_paged(size_t start) {
auto items = SentenceQueryPagedCmd(SqlContext()).execute(paged_position { start, this->page_size });
size_t i = 0;
for (auto it = items.begin(); it != items.end(); it++, i++) {
std::cout << (*it).id << "-" << (*it).source_id << ") ";
std::cout << (*it).speaker_name << ": " << (*it).what_said << std::endl;
}
return i;
}
| 25.232558
| 101
| 0.686636
|
viveret
|
9737c0c2a7ec2cd01cbd02e34a5a53854fed1b3b
| 2,060
|
cpp
|
C++
|
YorozuyaGSLib/source/ICsSendInterface.cpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
YorozuyaGSLib/source/ICsSendInterface.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
YorozuyaGSLib/source/ICsSendInterface.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
#include <ICsSendInterface.hpp>
START_ATF_NAMESPACE
void ICsSendInterface::SendMsg_BuyCashItem(uint16_t wSock, struct _param_cash_update* psheet, struct _param_cash_update* sheetplus)
{
using org_ptr = void (WINAPIV*)(uint16_t, struct _param_cash_update*, struct _param_cash_update*);
(org_ptr(0x14030c760L))(wSock, psheet, sheetplus);
};
void ICsSendInterface::SendMsg_CashDiscountEventInform(uint16_t wSock, char byEventType, struct _cash_discount_ini_* pIni)
{
using org_ptr = void (WINAPIV*)(uint16_t, char, struct _cash_discount_ini_*);
(org_ptr(0x14030cc30L))(wSock, byEventType, pIni);
};
void ICsSendInterface::SendMsg_CashEventInform(uint16_t wSock, char byEventType, char byStatus, struct _cash_event_ini* pIni, struct _cash_lim_sale* pLim)
{
using org_ptr = void (WINAPIV*)(uint16_t, char, char, struct _cash_event_ini*, struct _cash_lim_sale*);
(org_ptr(0x14030ce00L))(wSock, byEventType, byStatus, pIni, pLim);
};
void ICsSendInterface::SendMsg_ConditionalEventInform(uint16_t wSock, char byEventType, uint16_t wCsDiscount, char byStatus, char* pEMsg)
{
using org_ptr = void (WINAPIV*)(uint16_t, char, uint16_t, char, char*);
(org_ptr(0x14030d1a0L))(wSock, byEventType, wCsDiscount, byStatus, pEMsg);
};
void ICsSendInterface::SendMsg_Error(uint16_t wSock, int eCode)
{
using org_ptr = void (WINAPIV*)(uint16_t, int);
(org_ptr(0x14030c590L))(wSock, eCode);
};
void ICsSendInterface::SendMsg_GoodsList(uint16_t wSock, struct _param_cash_select* psheet)
{
using org_ptr = void (WINAPIV*)(uint16_t, struct _param_cash_select*);
(org_ptr(0x14030c620L))(wSock, psheet);
};
void ICsSendInterface::SendMsg_LimitedsaleEventInform(uint16_t wSock, char byTableCode, unsigned int dwIndex, uint16_t wNum)
{
using org_ptr = void (WINAPIV*)(uint16_t, char, unsigned int, uint16_t);
(org_ptr(0x14030d2b0L))(wSock, byTableCode, dwIndex, wNum);
};
END_ATF_NAMESPACE
| 50.243902
| 158
| 0.719903
|
lemkova
|
973b2809ce634c61f6516f7a81ba8aa0e5317e9e
| 1,869
|
cpp
|
C++
|
src/app/Welcome.cpp
|
wichern/leucht
|
403fc613e06241978696fb15f34fa64f2732549d
|
[
"MIT"
] | null | null | null |
src/app/Welcome.cpp
|
wichern/leucht
|
403fc613e06241978696fb15f34fa64f2732549d
|
[
"MIT"
] | null | null | null |
src/app/Welcome.cpp
|
wichern/leucht
|
403fc613e06241978696fb15f34fa64f2732549d
|
[
"MIT"
] | null | null | null |
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Paul Wichern
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "app/Welcome.h"
#include "Screen.h"
#include <iostream>
namespace app {
void Welcome::init(Screen& screen)
{
screen.clear();
screen.write(1 + 0, 3, 0, colour_alpha_t(255, 0, 0), "L");
screen.write(1 + 3, 3, 0, colour_alpha_t(0, 255, 0), "E");
screen.write(1 + 6, 3, 0, colour_alpha_t(0, 0, 255), "U");
screen.write(1 + 9, 3, 0, colour_alpha_t(255, 0, 255), "C");
screen.write(1 + 12, 3, 0, colour_alpha_t(255, 255, 0), "H");
screen.write(1 + 15, 3, 0, colour_alpha_t(0, 255, 255), "T");
}
void Welcome::update(Screen& screen)
{
(void)screen;
}
void Welcome::close()
{
}
void Welcome::keyPressed(Key key)
{
std::cout << "Key: " << key << std::endl;
}
} // namespace app
| 31.677966
| 81
| 0.693419
|
wichern
|
973c2951b38dd6a0bd1be51e43b4ee6b9d386e62
| 546
|
cpp
|
C++
|
lib/Render/SceneObject.cpp
|
chromapid/Monocle
|
5be990b05e89abbd1c6a222a9bcf412ba350aecd
|
[
"MIT"
] | null | null | null |
lib/Render/SceneObject.cpp
|
chromapid/Monocle
|
5be990b05e89abbd1c6a222a9bcf412ba350aecd
|
[
"MIT"
] | null | null | null |
lib/Render/SceneObject.cpp
|
chromapid/Monocle
|
5be990b05e89abbd1c6a222a9bcf412ba350aecd
|
[
"MIT"
] | null | null | null |
#include "monocle/Render/SceneObject.h"
#include "glm/glm/gtc/matrix_transform.hpp"
#include "glm/glm/gtc/quaternion.hpp"
#include "glm/glm/gtx/transform.hpp"
#include "glm/glm/vec3.hpp"
using namespace mncl;
glm::mat4 SceneObject::getObjectToWorldMatrix() {
return glm::translate(glm::scale(glm::toMat4(rotation), scale), position);
};
glm::mat4 SceneObject::getWorldToObjectMatrix() {
return glm::toMat4(glm::conjugate<float>(rotation)) * glm::scale(glm::translate<float>(-position),glm::vec3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z));
};
| 36.4
| 152
| 0.741758
|
chromapid
|
973eee2bd2e18096f86ea5ca9c4940860766ee21
| 1,059
|
hpp
|
C++
|
src/corelib/hall-switch-int.hpp
|
Abiram-Narayanaswamy/hall-switch
|
921c41bea246ada2588ba0be0eab8a43b1b0a5ab
|
[
"MIT"
] | 2
|
2020-05-30T14:26:43.000Z
|
2020-06-30T13:37:32.000Z
|
src/corelib/hall-switch-int.hpp
|
Abiram-Narayanaswamy/hall-switch
|
921c41bea246ada2588ba0be0eab8a43b1b0a5ab
|
[
"MIT"
] | 2
|
2019-12-04T20:30:40.000Z
|
2020-08-24T13:19:39.000Z
|
src/corelib/hall-switch-int.hpp
|
Abiram-Narayanaswamy/hall-switch
|
921c41bea246ada2588ba0be0eab8a43b1b0a5ab
|
[
"MIT"
] | 3
|
2020-01-29T10:26:00.000Z
|
2020-09-08T10:53:42.000Z
|
/**
* @file hall-switch-int.hpp
* @brief Hall Switch Interrupt Handler
* @date July 2019
* @copyright Copyright (c) 2019-2020 Infineon Technologies AG
*
* SPDX-License-Identifier: MIT
*/
#ifndef HALL_SWITCH_INT_HPP_
#define HALL_SWITCH_INT_HPP_
#include "hall-switch.hpp"
class HallSwitch::Interrupt
{
private:
#define GPIO_INT_PINS 4 /**< Maximum hardware interrupt signals */
static uint8_t idxNext; /**< Interrupt array allocation index*/
static HallSwitch *objPtrVector[GPIO_INT_PINS]; /**< Hall switch object pointers vector */
static void *fnPtrVector[GPIO_INT_PINS]; /**< Hall switch interrupt function handlers vector */
static void int0Handler ();
static void int1Handler ();
static void int2Handler ();
static void int3Handler ();
public:
static void *isrRegister(HallSwitch *objPtr);
};
#endif /** HALL_SWITCH_INT_HPP_ **/
| 35.3
| 114
| 0.601511
|
Abiram-Narayanaswamy
|
973f8188fe38d2b6d8724be3ae25d071979dca24
| 227
|
cpp
|
C++
|
Pbinfo/Gen.cpp
|
Al3x76/cpp
|
08a0977d777e63e0d36d87fcdea777de154697b7
|
[
"MIT"
] | 7
|
2019-01-06T19:10:14.000Z
|
2021-10-16T06:41:23.000Z
|
Pbinfo/Gen.cpp
|
Al3x76/cpp
|
08a0977d777e63e0d36d87fcdea777de154697b7
|
[
"MIT"
] | null | null | null |
Pbinfo/Gen.cpp
|
Al3x76/cpp
|
08a0977d777e63e0d36d87fcdea777de154697b7
|
[
"MIT"
] | 6
|
2019-01-06T19:17:30.000Z
|
2020-02-12T22:29:17.000Z
|
#include <iostream>
using namespace std;
int main()
{
int n, k;
cin>>n>>k;
for(int i=1; i<=n; i++)
cout<<1;
cout<<"01";
for(int i=1; i<=k; i++)
cout<<0;
cout<<10;
return 0;
}
| 9.869565
| 27
| 0.440529
|
Al3x76
|
974065eb4a0cec64d11885d99d4c33765451710d
| 19,415
|
cpp
|
C++
|
RTC/Kinect_Face/download/HDFaceBasics-D2D/ImageRenderer.cpp
|
rsdlab/LookThatWaySystem
|
842a8c021b1c9594b95a70d9e8302e77ceae6a97
|
[
"MIT"
] | null | null | null |
RTC/Kinect_Face/download/HDFaceBasics-D2D/ImageRenderer.cpp
|
rsdlab/LookThatWaySystem
|
842a8c021b1c9594b95a70d9e8302e77ceae6a97
|
[
"MIT"
] | null | null | null |
RTC/Kinect_Face/download/HDFaceBasics-D2D/ImageRenderer.cpp
|
rsdlab/LookThatWaySystem
|
842a8c021b1c9594b95a70d9e8302e77ceae6a97
|
[
"MIT"
] | null | null | null |
//------------------------------------------------------------------------------
// <copyright file="ImageRenderer.cpp" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
#include "stdafx.h"
#include <string>
#include "ImageRenderer.h"
using namespace DirectX;
static const float c_FaceBoxThickness = 6.0f;
static const float c_FacePointThickness = 10.0f;
static const float c_FacePointRadius = 1.0f;
static const float c_FacePropertyFontSize = 32.0f;
static const double c_FaceRotationIncrementInDegrees = 5.0f;
static const float c_TextLayoutWidth = 800;
static const float c_TextLayoutHeight = 600;
/// <summary>
/// Constructor
/// </summary>
ImageRenderer::ImageRenderer() :
m_hWnd(0),
m_sourceWidth(0),
m_sourceHeight(0),
m_sourceStride(0),
m_pD2DFactory(nullptr),
m_pRenderTarget(nullptr),
m_pBitmap(0),
m_pTextBrush(nullptr),
m_pTextFormat(0),
m_pDWriteFactory(nullptr)
{
for (int i = 0; i < BODY_COUNT; i++)
{
m_pFaceBrush[i] = nullptr;
m_pTextBGBrush[i] = nullptr;
}
}
/// <summary>
/// Destructor
/// </summary>
ImageRenderer::~ImageRenderer()
{
DiscardResources();
SafeRelease(m_pTextFormat);
SafeRelease(m_pDWriteFactory);
SafeRelease(m_pD2DFactory);
}
/// <summary>
/// Ensure necessary Direct2d resources are created
/// </summary>
/// <returns>indicates success or failure</returns>
HRESULT ImageRenderer::EnsureResources()
{
HRESULT hr = S_OK;
if (nullptr == m_pRenderTarget)
{
D2D1_SIZE_U size = D2D1::SizeU(m_sourceWidth, m_sourceHeight);
D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
rtProps.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE);
rtProps.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE;
// Create a hWnd render target, in order to render to the window set in initialize
hr = m_pD2DFactory->CreateHwndRenderTarget(
rtProps,
D2D1::HwndRenderTargetProperties(m_hWnd, size),
&m_pRenderTarget
);
if (SUCCEEDED(hr))
{
// Create a bitmap that we can copy image data into and then render to the target
hr = m_pRenderTarget->CreateBitmap(
size,
D2D1::BitmapProperties(D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE)),
&m_pBitmap
);
}
if (SUCCEEDED(hr))
{
hr = m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Red, 2.0f)), &m_pFaceBrush[0]);
HR(m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Red, 0.7f)), &m_pTextBGBrush[0]));
}
if (SUCCEEDED(hr))
{
hr = m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Green, 2.0f)), &m_pFaceBrush[1]);
HR(m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Green, 0.7f)), &m_pTextBGBrush[1]));
}
if (SUCCEEDED(hr))
{
hr = m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::White, 2.0f)), &m_pFaceBrush[2]);
HR(m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::White, 0.7f)), &m_pTextBGBrush[2]));
}
if (SUCCEEDED(hr))
{
hr = m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Purple, 2.0f)), &m_pFaceBrush[3]);
HR(m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Purple, 0.7f)), &m_pTextBGBrush[3]));
}
if (SUCCEEDED(hr))
{
hr = m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Orange, 2.0f)), &m_pFaceBrush[4]);
HR(m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Orange, 0.7f)), &m_pTextBGBrush[4]));
}
if (SUCCEEDED(hr))
{
hr = m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Pink, 2.0f)), &m_pFaceBrush[5]);
HR(m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Pink, 0.7f)), &m_pTextBGBrush[5]));
}
HR(m_pRenderTarget->CreateSolidColorBrush((D2D1::ColorF(D2D1::ColorF::Black, 1.0f)), &m_pTextBrush));
}
if (FAILED(hr))
{
DiscardResources();
}
return hr;
}
/// <summary>
/// Dispose of Direct2d resources
/// </summary>
void ImageRenderer::DiscardResources()
{
for (int i = 0; i < BODY_COUNT; i++)
{
SafeRelease(m_pFaceBrush[i]);
SafeRelease(m_pTextBGBrush[i]);
}
SafeRelease(m_pTextBrush);
SafeRelease(m_pRenderTarget);
SafeRelease(m_pBitmap);
}
/// <summary>
/// Set the window to draw to as well as the video format
/// Implied bits per pixel is 32
/// </summary>
/// <param name="hWnd">window to draw to</param>
/// <param name="pD2DFactory">already created D2D factory object</param>
/// <param name="sourceWidth">width (in pixels) of image data to be drawn</param>
/// <param name="sourceHeight">height (in pixels) of image data to be drawn</param>
/// <param name="sourceStride">length (in bytes) of a single scanline</param>
/// <returns>indicates success or failure</returns>
HRESULT ImageRenderer::Initialize(HWND hWnd, ID2D1Factory* pD2DFactory, int sourceWidth, int sourceHeight, int sourceStride)
{
if (nullptr == pD2DFactory)
{
return E_INVALIDARG;
}
m_hWnd = hWnd;
// One factory for the entire application so save a pointer here
m_pD2DFactory = pD2DFactory;
m_pD2DFactory->AddRef();
// Get the frame size
m_sourceWidth = sourceWidth;
m_sourceHeight = sourceHeight;
m_sourceStride = sourceStride;
HRESULT hr;
hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&m_pDWriteFactory));
if (SUCCEEDED(hr))
{
hr = m_pDWriteFactory->CreateTextFormat(
L"Georgia",
NULL,
DWRITE_FONT_WEIGHT_ULTRA_BLACK,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
c_FacePropertyFontSize,
L"en-us",
&m_pTextFormat
);
}
if (SUCCEEDED(hr))
{
hr = m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
}
if (SUCCEEDED(hr))
{
hr = m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
}
HR(m_pTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_WHOLE_WORD));
return hr;
}
/// <summary>
/// Prepare device to begin drawing
/// </summary>
/// <returns>indicates success or failure</returns>
HRESULT ImageRenderer::BeginDrawing()
{
// create the resources for this draw device
// they will be recreated if previously lost
HRESULT hr = EnsureResources();
if (SUCCEEDED(hr))
{
m_pRenderTarget->BeginDraw();
}
return hr;
}
/// <summary>
/// Ends drawing
/// </summary>
/// <returns>indicates success or failure</returns>
HRESULT ImageRenderer::EndDrawing()
{
HRESULT hr;
hr = m_pRenderTarget->EndDraw();
// Device lost, need to recreate the render target
// We'll dispose it now and retry drawing
if (hr == D2DERR_RECREATE_TARGET)
{
hr = S_OK;
DiscardResources();
}
return hr;
}
/// <summary>
/// Draws a 32 bit per pixel image of previously specified width, height, and stride to the associated hwnd
/// </summary>
/// <param name="pImage">image data in RGBX format</param>
/// <param name="cbImage">size of image data in bytes</param>
/// <returns>indicates success or failure</returns>
HRESULT ImageRenderer::DrawBackground(BYTE* pImage, unsigned long cbImage)
{
HRESULT hr = S_OK;
// incorrectly sized image data passed in
if (cbImage < ((m_sourceHeight - 1) * m_sourceStride) + (m_sourceWidth * 4))
{
hr = E_INVALIDARG;
}
if (SUCCEEDED(hr))
{
// Copy the image that was passed in into the direct2d bitmap
hr = m_pBitmap->CopyFromMemory(NULL, pImage, m_sourceStride);
if (SUCCEEDED(hr))
{
// Draw the bitmap stretched to the size of the window
m_pRenderTarget->DrawBitmap(m_pBitmap);
}
}
return hr;
}
/// <summary>
/// Draws face frame results
/// </summary>
/// <param name="iFace">the index of the face frame corresponding to a specific body in the FOV</param>
/// <param name="pFaceBox">face bounding box</param>
/// <param name="pFacePoints">face points</param>
/// <param name="pFaceRotation">face rotation</param>
/// <param name="pFaceProperties">face properties</param>
void ImageRenderer::DrawFaceFrameResults(int iFace, const RectI* pFaceBox, const PointF* pFacePoints, const Vector4* pFaceRotation, const DetectionResult* pFaceProperties, const CameraSpacePoint* pHeadPivot, const float* pAnimUnits)
{
// draw the face frame results only if the face bounding box is valid
if (ValidateFaceBoxAndPoints(pFaceBox, pFacePoints))
{
ID2D1SolidColorBrush* brush = m_pFaceBrush[iFace];
// draw the face bounding box
D2D1_RECT_F faceBox = D2D1::RectF(static_cast<FLOAT>(pFaceBox->Left),
static_cast<FLOAT>(pFaceBox->Top),
static_cast<FLOAT>(pFaceBox->Right),
static_cast<FLOAT>(pFaceBox->Bottom));
m_pRenderTarget->DrawRectangle(faceBox, brush, c_FaceBoxThickness);
//// draw each face point
//for (int i = 0; i < FacePointType::FacePointType_Count; i++)
//{
// D2D1_ELLIPSE facePoint= D2D1::Ellipse(D2D1::Point2F(pFacePoints[i].X, pFacePoints[i].Y), c_FacePointRadius, c_FacePointRadius);
// m_pRenderTarget->DrawEllipse(facePoint, brush, c_FacePointThickness);
//}
std::wstring faceText = L"";
// extract each face property information and store it is faceText
/*for (int iProperty = 0; iProperty < FaceProperty::FaceProperty_Count; iProperty++)
{
switch (iProperty)
{
case FaceProperty::FaceProperty_Happy:
faceText += L"Happy :";
break;
case FaceProperty::FaceProperty_Engaged:
faceText += L"Engaged :";
break;
case FaceProperty::FaceProperty_LeftEyeClosed:
faceText += L"LeftEyeClosed :";
break;
case FaceProperty::FaceProperty_RightEyeClosed:
faceText += L"RightEyeClosed :";
break;
case FaceProperty::FaceProperty_LookingAway:
faceText += L"LookingAway :";
break;
case FaceProperty::FaceProperty_MouthMoved:
faceText += L"MouthMoved :";
break;
case FaceProperty::FaceProperty_MouthOpen:
faceText += L"MouthOpen :";
break;
case FaceProperty::FaceProperty_WearingGlasses:
faceText += L"WearingGlasses :";
break;
default:
break;
}
*/
/*switch (pFaceProperties[iProperty])
{
case DetectionResult::DetectionResult_Unknown:
faceText += L" UnKnown";
break;
case DetectionResult::DetectionResult_Yes:
faceText += L" Yes";
break;
case DetectionResult::DetectionResult_No:
faceText += L" No";
break;
case DetectionResult::DetectionResult_Maybe:
faceText += L" Maybe";
break;
default:
break;
}
*/
//faceText += L"\n";
//}
faceText += L"HeadPivot Coordinates\n";
faceText += L" X-> " + std::to_wstring(pHeadPivot->X) + L" Y-> " + std::to_wstring(pHeadPivot->Y) + L" Z-> " + std::to_wstring(pHeadPivot->Z) + L" \n";
//get the HDFace animation units
for (int i = 0; i < FaceShapeAnimations_Count; i++)
{
FaceShapeAnimations faceAnim = (FaceShapeAnimations)i;
std::wstring strValue = std::to_wstring(pAnimUnits[faceAnim]);
//if (pAnimUnits[faceAnim] != 0.0)
{
switch (faceAnim)
{
case FaceShapeAnimations::FaceShapeAnimations_JawOpen:
faceText += L"JawOpened: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_JawSlideRight:
faceText += L"JawSlideRight: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LeftcheekPuff:
faceText += L"LeftCheekPuff: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LefteyebrowLowerer:
faceText += L"LeftEyeBrowLowered: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LefteyeClosed:
faceText += L"LeftEyeClosed: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_RighteyebrowLowerer:
faceText += L"RightEyeBrowLowered: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_RighteyeClosed:
faceText += L"RightEyeClosed: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LipCornerDepressorLeft:
faceText += L"LipCornerDepressedLeft: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LipCornerDepressorRight:
faceText += L"LipCornerDepressedRight: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LipCornerPullerLeft:
faceText += L"LipCornerPulledLeft: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LipCornerPullerRight:
faceText += L"LipCornerPulledRight: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LipPucker:
faceText += L"Lips Puckered: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LipStretcherLeft:
faceText += L"LipStretchLeft: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LipStretcherRight:
faceText += L"LipStretchRight: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LowerlipDepressorLeft:
faceText += L"LowerLipDepressedLeft: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_LowerlipDepressorRight:
faceText += L"LowerLipDepressedRight: " + strValue + L"\n";
break;
case FaceShapeAnimations::FaceShapeAnimations_RightcheekPuff:
faceText += L"RightCheekPuffed: " + strValue + L"\n";
break;
}
}
}
// extract face rotation in degrees as Euler angles
int pitch, yaw, roll;
ExtractFaceRotationInDegrees(pFaceRotation, &pitch, &yaw, &roll);
faceText += L"FaceYaw : " + std::to_wstring(yaw) + L"\n";
faceText += L"FacePitch : " + std::to_wstring(pitch) + L"\n";
faceText += L"FaceRoll : " + std::to_wstring(roll) + L"\n";
D2D1_RECT_F layoutBorderRect = D2D1::RectF(faceBox.right + 30 , faceBox.top - 230,
faceBox.right + c_TextLayoutWidth + 30,
faceBox.bottom + c_TextLayoutHeight + 30);
D2D1_RECT_F layoutRect = D2D1::RectF(faceBox.right+ 50, faceBox.top - 200,
faceBox.right + c_TextLayoutWidth,
faceBox.bottom + c_TextLayoutHeight);
// render the face property and face rotation information
m_pRenderTarget->FillRectangle(layoutBorderRect, m_pTextBGBrush[iFace]);
m_pRenderTarget->DrawTextW(faceText.c_str(),
static_cast<UINT32>(faceText.length()),
m_pTextFormat,
layoutRect,
m_pTextBrush);
}
}
/// <summary>
/// Validates face bounding box and face points to be within screen space
/// </summary>
/// <param name="pFaceBox">the face bounding box</param>
/// <param name="pFacePoints">the face points</param>
/// <returns>success or failure</returns>
bool ImageRenderer::ValidateFaceBoxAndPoints(const RectI* pFaceBox, const PointF* pFacePoints)
{
bool isFaceValid = false;
if (pFaceBox != nullptr)
{
INT32 screenWidth = m_sourceWidth;
INT32 screenHeight = m_sourceHeight;
INT32 width = pFaceBox->Right - pFaceBox->Left;
INT32 height = pFaceBox->Bottom - pFaceBox->Top;
// check if we have a valid rectangle within the bounds of the screen space
isFaceValid = width > 0 &&
height > 0 &&
pFaceBox->Right <= screenWidth &&
pFaceBox->Bottom <= screenHeight;
//if (isFaceValid)
//{
// for (int i = 0; i < FacePointType::FacePointType_Count; i++)
// {
// // check if we have a valid face point within the bounds of the screen space
// bool isFacePointValid = pFacePoints[i].X > 0.0f &&
// pFacePoints[i].Y > 0.0f &&
// pFacePoints[i].X < m_sourceWidth &&
// pFacePoints[i].Y < m_sourceHeight;
// if (!isFacePointValid)
// {
// isFaceValid = false;
// break;
// }
// }
//}
}
return isFaceValid;
}
/// <summary>
/// Converts rotation quaternion to Euler angles
/// And then maps them to a specified range of values to control the refresh rate
/// </summary>
/// <param name="pQuaternion">face rotation quaternion</param>
/// <param name="pPitch">rotation about the X-axis</param>
/// <param name="pYaw">rotation about the Y-axis</param>
/// <param name="pRoll">rotation about the Z-axis</param>
void ImageRenderer::ExtractFaceRotationInDegrees(const Vector4* pQuaternion, int* pPitch, int* pYaw, int* pRoll)
{
double x = pQuaternion->x;
double y = pQuaternion->y;
double z = pQuaternion->z;
double w = pQuaternion->w;
// convert face rotation quaternion to Euler angles in degrees
double dPitch, dYaw, dRoll;
dPitch = atan2(2 * (y * z + w * x), w * w - x * x - y * y + z * z) / M_PI * 180.0;
dYaw = asin(2 * (w * y - x * z)) / M_PI * 180.0;
dRoll = atan2(2 * (x * y + w * z), w * w + x * x - y * y - z * z) / M_PI * 180.0;
// clamp rotation values in degrees to a specified range of values to control the refresh rate
double increment = c_FaceRotationIncrementInDegrees;
*pPitch = static_cast<int>((dPitch + increment/2.0 * (dPitch > 0 ? 1.0 : -1.0)) / increment) * static_cast<int>(increment);
*pYaw = static_cast<int>((dYaw + increment/2.0 * (dYaw > 0 ? 1.0 : -1.0)) / increment) * static_cast<int>(increment);
*pRoll = static_cast<int>((dRoll + increment/2.0 * (dRoll > 0 ? 1.0 : -1.0)) / increment) * static_cast<int>(increment);
}
| 36.087361
| 233
| 0.609374
|
rsdlab
|
9744d4bedde54a3c60cc310bc94117bbc90556a1
| 17,911
|
cpp
|
C++
|
src/optical_flow.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
src/optical_flow.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
src/optical_flow.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
#include <opencv4/opencv2/opencv.hpp>
void OPticalFlowLucasKanade()
{
/*
Obsolete functions:
CalcOpticalFlowHS -> computes the flow for every pixel of the first input image using the Horn and Schunck algorithm
CalcOpticalFlowLK -> computes the flow for every pixel of the first input image using the Lucas and Kanade algorithm .
To track sparse features, use calcOpticalFlowPyrLK().
To track all the pixels, use calcOpticalFlowFarneback().
calcOpticalFlowSF -> Calculate an optical flow using “SimpleFlow” algorithm.
*/
}
void drawOptFlowMap(const cv::Mat& flow, cv::Mat& cflowmap, int step,double, const cv::Scalar& color)
{
// std::cout<<flow.channels() <<std::endl;
for(int y = 0; y < cflowmap.rows; y += step)
for(int x = 0; x < cflowmap.cols; x += step)
{
const cv::Point2f& fxy = flow.at<cv::Point2f>(y, x);
cv::line(cflowmap, cv::Point(x,y), cv::Point(cvRound(x+fxy.x), cvRound(y+fxy.y)), color);
cv::circle(cflowmap, cv::Point(x,y), 2, color, -1);
}
}
void drawMotionToColor(const cv::Mat& flow, cv::Mat &bgr)
{
//extraxt x and y channels
cv::Mat xy[2]; //X,Y
cv::split(flow, xy);
//calculate angle and magnitude
cv::Mat magnitude, angle;
cv::cartToPolar(xy[0], xy[1], magnitude, angle, true);
//translate magnitude to range [0;1]
double mag_max;
cv::minMaxLoc(magnitude, 0, &mag_max);
magnitude.convertTo(magnitude, -1, 1.0 / mag_max);
//build hsv image
cv::Mat _hsv[3], hsv;
_hsv[0] = angle;
_hsv[1] = cv::Mat::ones(angle.size(), CV_32F);
_hsv[2] = magnitude;
cv::merge(_hsv, 3, hsv);
//convert to BGR and show
/* cv::Mat bgr*/;//CV_32FC3 matrix
cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
}
void OPticalFlowPyramidLucasKanade(cv::Mat &previous_image,cv::Mat &next_image, std::vector<cv::Point2f>& previous_image_points,
std::vector<cv::Point2f>& next_image_points,std::vector<uchar>& status)
{
cv::Size winSize=cv::Size(21,21);
std::vector<float> err;
cv::TermCriteria termcrit=cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 30, 0.01);
cv::calcOpticalFlowPyrLK(previous_image, next_image, previous_image_points, next_image_points, status, err, winSize, 3, termcrit, 0, 0.001);
int indexCorrection = 0;
for( int i=0; i<status.size(); i++)
{ cv::Point2f pt = next_image_points.at(i- indexCorrection);
if ((status.at(i) == 0)||(pt.x<0)||(pt.y<0)) {
if((pt.x<0)||(pt.y<0)) {
status.at(i) = 0;
}
previous_image_points.erase (previous_image_points.begin() + (i - indexCorrection));
next_image_points.erase (next_image_points.begin() + (i - indexCorrection));
indexCorrection++;
}
}
}
void OpticalFlowFarneback(cv::Mat &previous_image,cv::Mat &next_image,cv::Mat &flow,double pyr_scale=0.5,
int levels=5,int winsize=13,int numIters = 10,int poly_n=5,int poly_sigma=1.1, int flags=cv::OPTFLOW_FARNEBACK_GAUSSIAN)
{
/*
pyr_scale=0.5; means a classical pyramid, where each next layer is twice smaller than the previous one.
int levels=5;//number of pyramid layers including the initial image; levels=1 means that no extra layers are
int winsize=13;//averaging window size; larger values increase the algorithm robustness to image noise and give more chances for fast motion detection, but yield more blurred motion field.
int numIters = 10; //number of iterations the algorithm does at each pyramid level.
int poly_n=5;//size of the pixel neighborhood used to find polynomial expansion in each pixel; larger values mean that the image will be approximated with smoother surfaces, yielding more robust algorithm and more blurred motion field, typically poly_n =5 or 7.
int poly_sigma=1.1;//standard deviation of the Gaussian that is used to smooth derivatives used as a basis for the polynomial expansion; for poly_n=5, you can set poly_sigma=1.1, for poly_n=7, a good value would be poly_sigma=1.5.
flags=
OPTFLOW_USE_INITIAL_FLOW-> uses the input flow as an initial flow approximation
OPTFLOW_FARNEBACK_GAUSSIAN ->uses the Gaussian winsize Xwinsize filter instead of a box filter of the same size for optical flow estimation; usually, this option gives z more accurate flow than with a box filter, at the cost of lower speed; normally, winsize for a Gaussian window should be set to a larger value to achieve the same level of robustness.
*/
cv::calcOpticalFlowFarneback(previous_image,next_image,flow,pyr_scale,levels,winsize,numIters,poly_n,poly_sigma,flags);
}
//using namespace cv;
//using namespace std;
//void temp()
//{
// // Load two images and allocate other structures
// Mat imgA = imread("../images/opticalflow/bt_0.png", CV_LOAD_IMAGE_GRAYSCALE);
// Mat imgB = imread("../images/opticalflow/bt_1.png", CV_LOAD_IMAGE_GRAYSCALE);
// Size img_sz = imgA.size();
// Mat imgC(img_sz,1);
// int win_size = 15;
// int maxCorners = 20;
// double qualityLevel = 0.05;
// double minDistance = 5.0;
// int blockSize = 3;
// double k = 0.04;
// std::vector<cv::Point2f> cornersA;
// cornersA.reserve(maxCorners);
// std::vector<cv::Point2f> cornersB;
//// cornersB.reserve(maxCorners);
// goodFeaturesToTrack( imgA,cornersA,maxCorners,qualityLevel,minDistance,cv::Mat());
// goodFeaturesToTrack( imgB,cornersB,maxCorners,qualityLevel,minDistance,cv::Mat());
// cornerSubPix( imgA, cornersA, Size( win_size, win_size ), Size( -1, -1 ),
// TermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03 ) );
//// cornerSubPix( imgB, cornersB, Size( win_size, win_size ), Size( -1, -1 ),
//// TermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03 ) );
// // Call Lucas Kanade algorithm
// CvSize pyr_sz = Size( img_sz.width+8, img_sz.height/3 );
// std::vector<uchar> features_found; //status : each element of the vector is set to 1 if the flow for the corresponding features has been found, otherwise, it is set to 0.
// features_found.reserve(maxCorners);
// std::vector<float> feature_errors;
// feature_errors.reserve(maxCorners);
// cornersB.clear();
// calcOpticalFlowPyrLK( imgA, imgB, cornersA, cornersB, features_found, feature_errors ,
// Size( win_size, win_size ), 5,
// cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.3 ), 0 );
// // Make an image of the results
// for( int i=0; i < features_found.size(); i++ ){
//// cout<<"Error is "<<feature_errors[i]<<endl;
//// //continue;
//// cout<<"Got it"<<endl;
// cout<< (int)features_found.at(i)<<endl;
// Point p0( ceil( cornersA[i].x ), ceil( cornersA[i].y ) );
// Point p1( ceil( cornersB[i].x ), ceil( cornersB[i].y ) );
// line( imgC, p0, p1, CV_RGB(255,255,255), 2 );
// }
// namedWindow( "ImageA", 0 );
// namedWindow( "ImageB", 0 );
// namedWindow( "LKpyr_OpticalFlow", 0 );
// imshow( "ImageA", imgA );
// imshow( "ImageB", imgB );
// imshow( "LKpyr_OpticalFlow", imgC );
// cvWaitKey(0);
// return ;
//}
void drawLukasOpticalFlow(cv::Mat &flow, std::vector<cv::Point2f> &corners_prev,std::vector<cv::Point2f> &corners_current,std::vector<uchar> &features_found)
{
// std::cout<<"features_found.size():"<<features_found.size() <<std::endl;
for( int i=0; i < features_found.size(); i++ )
{
// std::cout<< (int)features_found.at(i)<<std::endl;
cv::Point p0( std::ceil( corners_prev[i].x ), std::ceil( corners_prev[i].y ) );
cv::Point p1( std::ceil( corners_current[i].x ), std::ceil( corners_current[i].y ) );
cv::line( flow, p0, p1, CV_RGB(255,0,0), 2 );
}
}
static const double pi = 3.14159265358979323846;
inline static double square(int a)
{
return a * a;
}
int number_of_features;
void draw(cv::Mat &frame1, std::vector<cv::Point2f> &frame1_features,std::vector<cv::Point2f> &frame2_features,std::vector<uchar> &optical_flow_found_feature)
{
for(int i = 0; i < number_of_features; i++)
{
/* If Pyramidal Lucas Kanade didn't really find the feature, skip it. */
if ( optical_flow_found_feature[i] == 0 ) continue;
int line_thickness; line_thickness = 1;
/* CV_RGB(red, green, blue) is the red, green, and blue components
* of the color you want, each out of 255.
*/
cv::Scalar line_color; line_color = CV_RGB(255,0,0);
/* Let's make the flow field look nice with arrows. */
/* The arrows will be a bit too short for a nice visualization because of the
high framerate
* (ie: there's not much motion between the frames). So let's lengthen them
by a factor of 3.
*/
cv::Point p,q;
p.x = (int) frame1_features[i].x;
p.y = (int) frame1_features[i].y;
q.x = (int) frame2_features[i].x;
q.y = (int) frame2_features[i].y;
double angle; angle = atan2( (double) p.y - q.y, (double) p.x - q.x );
double hypotenuse;
hypotenuse = sqrt( square(p.y - q.y) + square(p.x - q.x) ) ;
/* Here we lengthen the arrow by a factor of three. */
q.x = (int) (p.x - 3 * hypotenuse * cos(angle));
q.y = (int) (p.y - 3 * hypotenuse * sin(angle));
/* Now we draw the main line of the arrow. */
/* "frame1" is the frame to draw on.
* "p" is the point where the line begins.
* "q" is the point where the line stops.
* "CV_AA" means antialiased drawing.
* "0" means no fractional bits in the center cooridinate or radius.
*/
cv::line( frame1, p, q, line_color, 1 );
//cv::line(img, cv::Point(100,100), cv::Point(200,200), cv::Scalar(0,255,0), 1);
/* Now draw the tips of the arrow. I do some scaling so that the
* tips look proportional to the main line of the arrow.
*/
p.x = (int) (q.x + 9 * cos(angle + pi / 4));
p.y = (int) (q.y + 9 * sin(angle + pi / 4));
cv::line( frame1, p, q, line_color, 0 );
p.x = (int) (q.x + 9 * cos(angle - pi / 4));
p.y = (int) (q.y + 9 * sin(angle - pi / 4));
cv::line( frame1, p, q, line_color, 0 );
}
}
//void OpticalFlowPyramidLukas(cv::Mat ¤t_gray, cv::Mat &prev_gray,cv::Mat &LKpyr_OpticalFlow)
//{
//}
void OpticalFlowPyramidLukas_test(int argc, char** argv)
{
/*
std::string camera_calibration_path="../data/front_webcam.yml";
cv::FileStorage fs(camera_calibration_path,cv::FileStorage::READ);
cv::Mat camera_matrix, distortion_coefficient;
fs["camera_matrix"]>>camera_matrix;
fs["distortion_coefficients"]>>distortion_coefficient;
std::cout<<"Camera Matrix:" <<std::endl;
std::cout<<camera_matrix <<std::endl;
std::cout<<"Fx: " <<camera_matrix.at<double>(0,0) <<std::endl;
std::cout<<"Fy: " <<camera_matrix.at<double>(1,1) <<std::endl;
std::cout<<"Cx: " <<camera_matrix.at<double>(0,2) <<std::endl;
std::cout<<"Cy: " <<camera_matrix.at<double>(1,2) <<std::endl;
std::cout<< "Distortion Coefficient:"<<std::endl;
std::cout<<distortion_coefficient <<std::endl;
std::cout<<"K1: "<<distortion_coefficient.at<double>(0,0) <<std::endl;
std::cout<<"K2: "<<distortion_coefficient.at<double>(0,1) <<std::endl;
std::cout<<"P1: "<<distortion_coefficient.at<double>(0,2) <<std::endl;
std::cout<<"P2: "<<distortion_coefficient.at<double>(0,3) <<std::endl;
std::cout<<"K3: "<<distortion_coefficient.at<double>(0,4) <<std::endl;
*/
cv::Mat camera_matrix = cv::Mat::eye(3, 3, CV_64F);
cv::Mat E, R, t;
int win_size = 15;
int maxCorners = 100;
number_of_features=maxCorners;
double qualityLevel = 0.05;
double minDistance = 5.0;
int blockSize = 3;
double k = 0.04;
std::vector<cv::Point2f> corners_prev;
std::vector<cv::Point2f> corners_current;
// cornersB.reserve(maxCorners);
std::vector<uchar> features_found; //status : each element of the vector is set to 1 if the flow for the corresponding features has been found, otherwise, it is set to 0.
features_found.reserve(maxCorners);
std::vector<float> feature_errors;
feature_errors.reserve(maxCorners);
cv::Mat current_gray, previous_gray,frame;
// cv::namedWindow( "previous_gray", 0 );
// cv::namedWindow( "current_gray", 0 );
cv::namedWindow( "LKpyr_OpticalFlow", 0 );
double x,y;
double x_ref, y_ref;
x_ref=0;
y_ref=0;
x=x_ref;
y=y_ref;
cv::VideoCapture vid;
if(argc>1)
{
vid.open(argv[1]);
}else
{
cv::VideoCapture camera(0);
vid=camera;
}
for(;;)
{
vid >> frame;
cv::cvtColor(frame, current_gray, cv::COLOR_BGR2GRAY);
if( !previous_gray.empty() )
{
cv::Size img_sz = previous_gray.size();
// cv::Mat LKpyr_OpticalFlow=cv::Mat::zeros(img_sz,1);
//cv::Mat LKpyr_OpticalFlow=previous_gray.clone();
cv::Mat LKpyr_OpticalFlow=frame.clone();
cv::goodFeaturesToTrack( previous_gray,corners_prev,maxCorners,qualityLevel,minDistance,cv::Mat());
cv::goodFeaturesToTrack( current_gray,corners_current,maxCorners,qualityLevel,minDistance,cv::Mat());
cv::cornerSubPix( previous_gray, corners_prev, cv::Size( win_size, win_size ), cv::Size( -1, -1 ),cv::TermCriteria( cv::TermCriteria::MAX_ITER|cv::TermCriteria::EPS, 20, 0.03 ) );
cv::calcOpticalFlowPyrLK( previous_gray, current_gray, corners_prev, corners_current, features_found, feature_errors , cv::Size( win_size, win_size ), 5, cv::TermCriteria( cv::TermCriteria::MAX_ITER|cv::TermCriteria::EPS, 20, 0.3 ), 0 );
// int indexCorrection = 0;
// for( int i=0; i<features_found.size(); i++)
// {
// cv::Point2f pt = corners_current.at(i- indexCorrection);
// if ((features_found.at(i) == 0)||(pt.x<0)||(pt.y<0))
// {
// if((pt.x<0)||(pt.y<0))
// {
// features_found.at(i) = 0;
// }
// corners_prev.erase (corners_prev.begin() + (i - indexCorrection));
// corners_current.erase (corners_current.begin() + (i - indexCorrection));
// indexCorrection++;
// }
// }
E=cv::findEssentialMat(corners_current,corners_prev,camera_matrix,cv::RANSAC);
// std::cout <<"Essential: " <<E <<std::endl;
cv::recoverPose(E, corners_current, corners_prev,camera_matrix, R, t);
// std::cout <<"Trasnlation" <<t <<std::endl;
// std::cout <<"X: " <<t.at<double>(0,0) <<std::endl;
// std::cout <<"Y: " <<t.at<double>(1,0) <<std::endl;
/*
std::cout <<x << ","<<y <<std::endl;
x=x+t.at<double>(0,0);
y=y+t.at<double>(1,0);
*/
// std::cout <<t.at<double>(0,0) << ","<<t.at<double>(1,0) <<std::endl;
// drawLukasOpticalFlow(LKpyr_OpticalFlow,corners_prev,corners_prev,features_found);
draw(LKpyr_OpticalFlow, corners_prev,corners_prev,features_found);
// cv::imshow( "previous_gray", previous_gray );
// cv::imshow( "current_gray", current_gray );
cv::imshow( "LKpyr_OpticalFlow", LKpyr_OpticalFlow );
}
if(cv::waitKey(30)>=0)
break;
std::swap(previous_gray, current_gray);
}
}
void OpticalFlowFarneback_test(int argc, char** argv)
{
cv::VideoCapture vid;
if(argc>1)
{
vid.open(argv[1]);
}else
{
cv::VideoCapture camera(0);
vid=camera;
}
cv::Mat flow, cflow,bgr ,frame;
cv::Mat gray, prevgray, uflow;
cv::namedWindow("flow", 1);
cv::namedWindow("motiontoflow", 1);
double pyr_scale=0.5;
int levels=5;
int winsize=13;
int numIters = 10;
int poly_n=5;
int poly_sigma=1.1;
int flags=cv::OPTFLOW_FARNEBACK_GAUSSIAN;
for(;;)
{
vid >> frame;
cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);
if( !prevgray.empty() )
{
OpticalFlowFarneback(prevgray,gray,uflow,pyr_scale,levels,winsize,numIters,poly_n,poly_sigma,flags);
cv::cvtColor(prevgray, cflow, cv::COLOR_GRAY2BGR);
uflow.copyTo(flow);
drawOptFlowMap(flow, cflow, 16, 1.5, cv::Scalar(0, 255, 0));
drawMotionToColor(flow, bgr);
cv::imshow("flow", cflow);
cv::imshow("motiontoflow", bgr);
}
if(cv::waitKey(30)>=0)
break;
std::swap(prevgray, gray);
}
return ;
}
std::string ZeroPadNumber(int num)
{
std::stringstream ss;
// the number is converted to string with the help of stringstream
ss << num;
std::string ret;
ss >> ret;
// Append zero chars
int str_length = ret.length();
for (int i = 0; i < 6 - str_length; i++)
ret = "0" + ret;
return ret;
}
void temp2(int argc, char ** argv)
{
cv::VideoCapture vid(argv[1]);
cv::Mat frame;
std::string file_name,file_path;
file_path="frames/";
std::cout<< int(vid.get(cv::CAP_PROP_FRAME_COUNT)) <<std::endl;
int totoal_number_of_frame=int(vid.get(cv::CAP_PROP_FRAME_COUNT));
for(std::size_t i=0;i<totoal_number_of_frame;i=i+1)
{
vid>>frame;
file_name=ZeroPadNumber(i)+".png";
std::cout<< file_name <<std::endl;
cv::imwrite(file_path+file_name,frame);
// i++;
}
}
int main(int argc, char** argv)
{
// OpticalFlowFarneback_test(argc, argv);
OpticalFlowPyramidLukas_test(argc, argv);
// temp2(argc, argv);
}
| 34.312261
| 357
| 0.615097
|
behnamasadi
|
974b43486e73052acd41f4bc735024f17e43dacc
| 1,262
|
cpp
|
C++
|
2_oop_basics/2_adv_oop/17_deduction.cpp
|
aalfianrachmat/CppND-practice
|
6c35141c106b9fa867392a846b35c482ded74e62
|
[
"MIT"
] | 27
|
2019-10-08T13:43:32.000Z
|
2021-08-30T08:00:28.000Z
|
2_oop_basics/2_adv_oop/17_deduction.cpp
|
aalfianrachmat/CppND-practice
|
6c35141c106b9fa867392a846b35c482ded74e62
|
[
"MIT"
] | 1
|
2020-10-11T23:20:15.000Z
|
2020-10-11T23:20:15.000Z
|
2_oop_basics/2_adv_oop/17_deduction.cpp
|
aalfianrachmat/CppND-practice
|
6c35141c106b9fa867392a846b35c482ded74e62
|
[
"MIT"
] | 14
|
2019-09-22T15:17:59.000Z
|
2021-07-13T06:06:37.000Z
|
/*
* Deduction occurs when an object is instantiated without explicitly identifying the types.
* Instead, the compiler "deduces" the types.
* This can be helpful for writing code that is generic and can handle a variety of inputs.
*
* OBJECTIVES
* 1. Declare a generic conditional function
* 2. Use it in conditional sorting
* 3. Declare another function which is used for processing generic types (this case is print())
*/
#include <iostream>
#include <vector>
// template function comparison of two numbers
template <typename T>
bool func(T x, T y) {
return (x < y);
}
// template for printing
template <typename T>
void print(std::vector<T> v) {
for (auto i : v) {
std::cout << i << " ";
}
std::cout << "\n";
}
int main() {
std::vector<float> v1 = {3, 2, 15.5, 57.6, 9, 12.9, 47.3};
std::vector<char> v2 = {'a', 'D', 'm', 'N', 'X', 'Y', 'z'};
// deducing function return type
std::sort(v1.begin(), v1.end(), func<float>);
print(v1);
// for input parameters as PrintVector we have total deduction,without specification
print(v2);
// this will support any type of that which has defined support for (in this case) < operator
std::sort(v2.begin(), v2.end(), func<char>);
print(v2);
}
| 28.681818
| 97
| 0.645008
|
aalfianrachmat
|
974d8e6e80120f908fbc79b311a3478a54edd81a
| 19,011
|
hh
|
C++
|
include/tracker/script.hh
|
bhgomes/tracker
|
dc44d40dd0275026ca8389898d47e35d19a3d9a7
|
[
"Unlicense"
] | 1
|
2019-10-29T16:40:39.000Z
|
2019-10-29T16:40:39.000Z
|
include/tracker/script.hh
|
bhgomes/tracker
|
dc44d40dd0275026ca8389898d47e35d19a3d9a7
|
[
"Unlicense"
] | 4
|
2019-04-01T16:31:31.000Z
|
2019-04-01T16:32:58.000Z
|
include/tracker/script.hh
|
bhgomes/tracker
|
dc44d40dd0275026ca8389898d47e35d19a3d9a7
|
[
"Unlicense"
] | null | null | null |
/*
* include/tracker/script.hh
*
* Copyright 2018 Brandon Gomes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TRACKER__SCRIPT_HH
#define TRACKER__SCRIPT_HH
#pragma once
#include <fstream>
#include <tracker/core/type.hh>
#include <tracker/core/units.hh>
#include <tracker/util/command_line_parser.hh>
#include <tracker/util/error.hh>
#include <tracker/util/io.hh>
#include <tracker/util/string.hh>
namespace MATHUSLA { namespace TRACKER {
namespace script { /////////////////////////////////////////////////////////////////////////////
using namespace type;
//__Path Types__________________________________________________________________________________
using path_type = std::string;
using path_vector = std::vector<path_type>;
//----------------------------------------------------------------------------------------------
//__Tracking Options Structure__________________________________________________________________
struct tracking_options {
path_type geometry_file = "";
path_type geometry_map_file = "";
path_type geometry_time_file = "";
real default_time_error = 2 * units::time;
path_vector data_directories = {""};
real_vector data_timing_offsets = {0};
std::string data_file_extension = "root";
std::string data_t_key = "";
std::string data_x_key = "";
std::string data_y_key = "";
std::string data_z_key = "";
std::string data_dt_key = "";
std::string data_dx_key = "";
std::string data_dy_key = "";
std::string data_dz_key = "";
std::string data_detector_key = "Detector";
std::string data_track_id_key = "Track";
std::string data_parent_id_key = "Parent";
std::string data_e_key = "";
std::string data_px_key = "";
std::string data_py_key = "";
std::string data_pz_key = "";
path_type statistics_directory = "";
path_type statistics_file_prefix = "statistics";
std::string statistics_file_extension = "root";
bool merge_input = false;
bool time_smearing = true;
real simulated_efficiency = 1;
real simulated_noise_rate = 0;
real_range event_time_window = {0, 0};
Coordinate layer_axis = Coordinate::Z;
real layer_depth = 0;
real line_width = 1;
size_t seed_size = 3;
real event_density_limit = 1;
real event_overload_limit = 2;
real track_density_limit = 1;
bool verbose_output = false;
bool draw_events = false;
};
//----------------------------------------------------------------------------------------------
namespace reserved { ///////////////////////////////////////////////////////////////////////////
//__Reserved Symbols____________________________________________________________________________
static const char comment_character = '#';
static const char space_character = ' ';
static const char key_value_separator = ':';
static const std::string& continuation_string = "...";
static const char continuation_line_character = '-';
//----------------------------------------------------------------------------------------------
} /* namespace reserved */ /////////////////////////////////////////////////////////////////////
//__Parse Line from Tracking Script_____________________________________________________________
void parse_line(const std::string& line,
std::string& key,
std::string& value);
//----------------------------------------------------------------------------------------------
//__Check that a Line has a Continuation String_________________________________________________
bool is_continuation_header(const std::string& key,
const std::string& value);
//----------------------------------------------------------------------------------------------
//__Check that a Line has a Continuation String_________________________________________________
bool is_continuation_body(const std::string& key,
const std::string& value);
//----------------------------------------------------------------------------------------------
//__Parse Line from a Continuation______________________________________________________________
void parse_continuation_line(const std::string& line,
std::string& entry);
//----------------------------------------------------------------------------------------------
//__Parse Key Value Pair into File Path_________________________________________________________
void parse_file_path(const std::string& key,
const std::string& value,
path_type& out,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse Data Key Value Pair___________________________________________________________________
void parse_data_keys(const std::string& key,
const std::string& value,
std::string& t_key,
std::string& x_key,
std::string& y_key,
std::string& z_key,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse Boolean Key Value_____________________________________________________________________
void parse_boolean(const std::string& key,
const std::string& value,
bool& out,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse Real Key Value________________________________________________________________________
void parse_real(const std::string& key,
const std::string& value,
real& out,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse Positive Real Key Value_______________________________________________________________
void parse_positive_real(const std::string& key,
const std::string& value,
real& out,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse Real Range Key Value__________________________________________________________________
void parse_real_range(const std::string& key,
const std::string& value,
real_range& out,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse Integer Key Value_____________________________________________________________________
void parse_integer(const std::string& key,
const std::string& value,
integer& out,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse Size Type Key Value___________________________________________________________________
void parse_size_type(const std::string& key,
const std::string& value,
std::size_t& out,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse R4 Key Value__________________________________________________________________________
void parse_r4_point(const std::string& key,
const std::string& value,
r4_point& out,
bool use_units=true,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse R3 Coordinate Key Value_______________________________________________________________
void parse_r3_coordinate(const std::string& key,
const std::string& value,
Coordinate& coordinate,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Parse R4 Coordinate Key Value_______________________________________________________________
void parse_r4_coordinate(const std::string& key,
const std::string& value,
Coordinate& coordinate,
bool exit_on_error=true);
//----------------------------------------------------------------------------------------------
//__Read and Parse Lines from Tracking Script___________________________________________________
template<class LineKeyValueParser>
void parse_lines(std::ifstream& file,
LineKeyValueParser f) {
std::string line, key, value;
bool continuation = false;
while (std::getline(file, line)) {
if (line.empty()) continue;
continuation = f(line, continuation, key, value);
if (!continuation)
key.clear();
value.clear();
}
}
template<class LineKeyValueParser>
void parse_lines(const path_type& path,
LineKeyValueParser f) {
std::ifstream file{path};
parse_lines(file, f);
}
//----------------------------------------------------------------------------------------------
//__Read Lines from Tracking Script_____________________________________________________________
template<class KeyValueParser>
void read_lines(std::ifstream& file,
KeyValueParser f) {
parse_lines(file, [&](const auto& line, const auto continuation, auto& key, auto& value) {
if (continuation) {
std::string test_key, test_value;
parse_line(line, test_key, test_value);
if (!is_continuation_body(test_key, test_value)) {
return f(test_key, test_value);
} else {
parse_continuation_line(line, value);
return f(key, value);
}
} else {
parse_line(line, key, value);
return f(key, value);
}
});
}
template<class KeyValueParser>
void read_lines(const path_type& path,
KeyValueParser f) {
std::ifstream file{path};
read_lines(file, f);
}
//----------------------------------------------------------------------------------------------
//__Default Tracking Script Options Extension Parser____________________________________________
inline void default_extension_parser(const std::string& key,
const std::string&,
tracking_options&) {
util::error::exit("[FATAL ERROR] Invalid Key in Tracking Script: \"", key, "\".\n");
}
//----------------------------------------------------------------------------------------------
//__Default Tracking Script Options Extension Parser Type_______________________________________
using default_extension_parser_t = decltype(default_extension_parser);
//----------------------------------------------------------------------------------------------
//__Tracking Script Options Parser______________________________________________________________
template<class ExtensionParser=default_extension_parser_t>
const tracking_options read(const path_type& path,
ExtensionParser& parser=default_extension_parser) {
tracking_options out{};
read_lines(path, [&](const auto& key, const auto& value) {
if (key.empty()) return false;
if (value.empty()) {
util::error::exit("[FATAL ERROR] Missing Value For Key: \"", key, "\".\n");
} else {
if (key == "geometry-file") {
parse_file_path(key, value, out.geometry_file);
} else if (key == "geometry-map-file") {
parse_file_path(key, value, out.geometry_map_file);
} else if (key == "geometry-map") {
if (is_continuation_header(key, value))
return true;
// TODO: implement
} else if (key == "data-directory") {
out.data_directories.clear();
out.data_directories.emplace_back();
parse_file_path(key, value, out.data_directories.back());
} else if (key == "data-directories") {
if (is_continuation_header(key, value)) {
out.data_directories.clear();
out.data_timing_offsets.clear();
return true;
}
util::string_vector tokens;
util::string::split(value, tokens, ",");
util::error::exit_when(tokens.size() != 2UL,
"[FATAL ERROR] Parallel Import Formatting for Data Directories is Invalid. \n",
" Expected \"path, offset\" but received \"", value, "\".\n");
out.data_directories.emplace_back();
auto& directories_back = out.data_directories.back();
parse_file_path(key, tokens[0], directories_back);
if (directories_back.empty()) {
out.data_directories.pop_back();
} else {
out.data_timing_offsets.emplace_back();
auto& offsets_back = out.data_timing_offsets.back();
parse_real(tokens[0], tokens[1], offsets_back);
}
return true;
} else if (key == "data-file-extension") {
out.data_file_extension = value;
} else if (key == "data-position-keys") {
parse_data_keys(key, value,
out.data_t_key, out.data_x_key, out.data_y_key, out.data_z_key);
} else if (key == "data-position-error-keys") {
parse_data_keys(key, value,
out.data_dt_key, out.data_dx_key, out.data_dy_key, out.data_dz_key);
} else if (key == "data-detector-key") {
out.data_detector_key = value;
} else if (key == "data-track-id-key") {
out.data_track_id_key = value;
} else if (key == "data-parent-id-key") {
out.data_parent_id_key = value;
} else if (key == "data-momentum-keys") {
parse_data_keys(key, value,
out.data_e_key, out.data_px_key, out.data_py_key, out.data_pz_key);
} else if (key == "geometry-default-time-error") {
parse_positive_real(key, value, out.default_time_error);
out.default_time_error *= units::time;
} else if (key == "time-smearing") {
parse_boolean(key, value, out.time_smearing);
} else if (key == "simulated-efficiency") {
parse_positive_real(key, value, out.simulated_efficiency);
} else if (key == "simulated-noise-rate") {
parse_positive_real(key, value, out.simulated_noise_rate);
} else if (key == "event-time-window") {
parse_real_range(key, value, out.event_time_window);
} else if (key == "layer-axis") {
parse_r3_coordinate(key, value, out.layer_axis);
} else if (key == "layer-depth") {
parse_positive_real(key, value, out.layer_depth);
out.layer_depth *= units::length;
} else if (key == "line-width") {
parse_positive_real(key, value, out.line_width);
out.line_width *= units::length;
} else if (key == "seed-size") {
parse_size_type(key, value, out.seed_size);
} else if (key == "event-density-limit") {
parse_positive_real(key, value, out.event_density_limit);
} else if (key == "event-overload-limit") {
parse_positive_real(key, value, out.event_overload_limit);
} else if (key == "track-density-limit") {
parse_positive_real(key, value, out.track_density_limit);
} else if (key == "statistics-directory") {
parse_file_path(key, value, out.statistics_directory);
} else if (key == "statistics-file-prefix") {
out.statistics_file_prefix = value;
} else if (key == "statistics-file-extension") {
out.statistics_file_extension = value;
} else if (key == "merge-input") {
parse_boolean(key, value, out.merge_input);
} else if (key == "verbose-output") {
parse_boolean(key, value, out.verbose_output);
} else if (key == "draw-events") {
parse_boolean(key, value, out.draw_events);
} else {
parser(key, value, out);
}
}
return false;
});
return out;
}
//----------------------------------------------------------------------------------------------
//__Parse Command Line Arguments________________________________________________________________
template<class ExtensionParser=default_extension_parser_t>
const tracking_options parse_command_line(int& argc,
char* argv[],
ExtensionParser& parser=default_extension_parser) {
using util::cli::option;
option help_opt ('h', "help", "MATHUSLA Tracking Algorithm", option::no_arguments);
option verbose_opt ('v', "verbose", "Verbose Output", option::no_arguments);
option quiet_opt ('q', "quiet", "Quiet Output", option::no_arguments);
option event_opt ( 0 , "draw-events", "Draw Events", option::no_arguments);
option script_opt ('s', "script", "Tracking Script", option::required_arguments);
util::cli::parse(argv, {&help_opt, &verbose_opt, &quiet_opt, &event_opt, &script_opt});
util::error::exit_when(!script_opt.count || argc == 1,
"[FATAL ERROR] Insufficient Arguments:\n",
" Must include arguments for a tracking script (-s).\n");
util::error::exit_when(!util::io::path_exists(script_opt.argument),
"[FATAL ERROR] Tracking Script Missing: The file \"", script_opt.argument, "\" cannot be found.\n");
auto out = script::read(script_opt.argument, parser);
if (!quiet_opt.count) {
out.verbose_output |= verbose_opt.count;
} else {
out.verbose_output = false;
}
if (event_opt.count)
out.draw_events |= event_opt.count;
return out;
}
//----------------------------------------------------------------------------------------------
} /* namespace script */ ///////////////////////////////////////////////////////////////////////
} } /* namespace MATHUSLA::TRACKER */
#endif /* TRACKER__SCRIPT_HH */
| 45.809639
| 104
| 0.549261
|
bhgomes
|
97513fee4bbd3df088e47e0d4560f541ee72d1b8
| 11,464
|
cpp
|
C++
|
src/ecal.cpp
|
IcicleF/undergraduate_project
|
57bc851834051ae5b167dcbf6790305905438d9e
|
[
"MIT"
] | 1
|
2021-11-13T03:20:46.000Z
|
2021-11-13T03:20:46.000Z
|
src/ecal.cpp
|
IcicleF/undergraduate_project
|
57bc851834051ae5b167dcbf6790305905438d9e
|
[
"MIT"
] | null | null | null |
src/ecal.cpp
|
IcicleF/undergraduate_project
|
57bc851834051ae5b167dcbf6790305905438d9e
|
[
"MIT"
] | null | null | null |
#include <ecal.hpp>
#include <debug.hpp>
//#define USE_RPC
/**
* Constructor initializes `memConf`.
* Also it initializes `clusterConf`, `myNodeConf` by instantiating an RPCInterface.
*/
ECAL::ECAL()
{
if (cmdConf == nullptr) {
d_err("cmdConf should be initialized!");
exit(-1);
}
if (memConf != nullptr)
d_warn("memConf is already initialized, skip");
else
memConf = new MemoryConfig(*cmdConf);
if (clusterConf != nullptr || myNodeConf != nullptr)
d_warn("clusterConf & myNodeConf were already initialized, skip");
else {
clusterConf = new ClusterConfig(cmdConf->clusterConfigFile);
auto myself = clusterConf->findMyself();
if (myself.id >= 0)
myNodeConf = new NodeConfig(myself);
else {
d_err("cannot find configuration of this node");
exit(-1);
}
}
allocTable = new BlockPool<BlockTy>();
rdma = new RDMASocket();
if (clusterConf->getClusterSize() % N != 0) {
d_err("FIXME: clusterSize %% N != 0, exit");
exit(-1);
}
/* Compute capacity */
int clusterNodeCount = clusterConf->getClusterSize();
capacity = (clusterNodeCount / N * K * allocTable->getCapacity()) / (Block4K::capacity / BlockTy::size);
/* Initialize EC Matrices */
gf_gen_cauchy1_matrix(encodeMatrix, N, K);
ec_init_tables(K, P, &encodeMatrix[K * K], gfTables);
for (int i = 0; i < P; ++i)
parity[i] = encodeBuffer + i * BlockTy::size;
#if 0
/* Start recovery process if this is a recovery */
if (cmdConf->recover) {
d_warn("start data recovery...");
int peerId = -1;
for (int i = 0; i < clusterConf->getClusterSize(); ++i) {
peerId = (*clusterConf)[i].id;
if (rpcInterface->isPeerAlive(peerId))
break;
}
if (peerId == -1) {
d_err("cannot find a valid peer!");
return;
}
/* Get remote write buffer MR & size */
Message request, response;
request.type = Message::MESG_RECOVER_START;
rpcInterface->rpcCall(peerId, &request, &response);
int writeLogLen = response.data.size;
size_t writeLogSize = writeLogLen * sizeof(uint64_t);
/* Allocate local write log space */
std::vector<uint64_t> blkNos;
blkNos.resize(writeLogLen);
uint64_t *localDst = blkNos.data();
ibv_mr *localLogMR = rpcInterface->getRDMASocket()->allocMR(localDst, writeLogSize, IBV_ACCESS_LOCAL_WRITE);
/* Perform RDMA read */
ibv_send_wr wr;
ibv_sge sge;
ibv_wc wc[2];
memset(&sge, 0, sizeof(ibv_sge));
sge.addr = (uint64_t)localDst;
sge.length = writeLogSize;
sge.lkey = localLogMR->lkey;
memset(&wr, 0, sizeof(ibv_send_wr));
wr.wr_id = WRID(peerId, SP_REMOTE_WRLOG_READ);
wr.sg_list = &sge;
wr.num_sge = 1;
wr.opcode = IBV_WR_RDMA_READ;
wr.send_flags = IBV_SEND_SIGNALED;
wr.wr.rdma.remote_addr = (uint64_t)response.data.mr.addr;
wr.wr.rdma.rkey = response.data.mr.rkey;
rpcInterface->getRDMASocket()->postSpecialSend(peerId, &wr);
expectPositive(rpcInterface->getRDMASocket()->pollSendCompletion(wc));
/* Retrieve & Recover */
int pagePerRow = clusterConf->getClusterSize() / N;
uint8_t *recoverSrc[K];
int decodeIndex[K];
for (int i = 0; i < writeLogLen; ++i) {
uint64_t row = blkNos[i];
uint64_t blockShift = getBlockShift(row);
int startNodeId = (row % pagePerRow) * N;
int selfId = -1;
for (int i = 0, j = 0; i < K && j < N; ++j) {
int idx = (j + startNodeId) % N;
if (idx != myNodeConf->id && rpcInterface->isPeerAlive(peerId))
decodeIndex[i++] = j;
else
selfId = j;
}
int taskCnt = 0;
for (int i = 0; i < K; ++i) {
int idx = (decodeIndex[i] + startNodeId) % N;
uint8_t *base = rpcInterface->getRDMASocket()->getReadRegion(peerId);
rpcInterface->remoteReadFrom(idx, blockShift, (uint64_t)base, BlockTy::size, i);
recoverSrc[i] = base;
++taskCnt;
}
ibv_wc wc[2];
while (taskCnt)
taskCnt -= rpcInterface->getRDMASocket()->pollSendCompletion(wc);
uint8_t decodeMatrix[1 * K];
uint8_t invertMatrix[K * K];
uint8_t b[K * K];
for (int i = 0; i < K; ++i)
memcpy(&b[K * i], &encodeMatrix[K * decodeIndex[i]], K);
gf_invert_matrix(b, invertMatrix, K);
if (selfId < K)
memcpy(decodeMatrix, &invertMatrix[K * selfId], K);
else
for (int i = 0; i < K; ++i) {
int s = 0;
for (int j = 0; j < K; ++j)
s ^= gf_mul(invertMatrix[j * K + i], encodeMatrix[K * selfId + j]);
decodeMatrix[i] = s;
}
uint8_t gfTbls[K * P * 32];
uint8_t *recoverOutput[1] = { reinterpret_cast<uint8_t *>(allocTable->at(row)) };
ec_init_tables(K, 1, decodeMatrix, gfTbls);
ec_encode_data(BlockTy::size, K, 1, gfTbls, recoverSrc, recoverOutput);
for (int i = 0; i < K; ++i) {
int idx = (decodeIndex[i] + startNodeId) % N;
rpcInterface->getRDMASocket()->freeReadRegion(idx, recoverSrc[i]);
}
}
/* Local & remote cleanup */
ibv_dereg_mr(localLogMR);
request.type = Message::MESG_RECOVER_END;
rpcInterface->rpcCall(peerId, &request, &response);
d_warn("finished data recovery! ECAL start.");
}
#endif
}
ECAL::~ECAL()
{
if (memConf) {
delete memConf;
memConf = nullptr;
}
}
int readCount = 0, writeCount = 0;
void ECAL::readBlock(uint64_t index, ECAL::Page &page)
{
#if 0
int decodeIndex[K], errIndex[K];
int cnt = 0, availMap = 0;
uint8_t *bases[N];
uint8_t *recoverSrc[N], *recoverOutput[N];
page.index = index;
memset(page.page.data, 0, Block4K::capacity);
auto pos = getDataPos(index);
/* Read data blocks from remote (or self) */
uint64_t blockShift = getBlockShift(pos.row);
int taskCnt = K;
for (int i = 0; i < N; ++i) {
int peerId = (i + pos.startNodeId) % N;
if (peerId != myNodeConf->id) {
uint8_t *base = rdma->getReadRegion(peerId);
rdma->postRead(peerId, blockShift, (uint64_t)base, BlockTy::size, i);
bases[i] = base;
}
else {
recoverSrc[cnt] = reinterpret_cast<uint8_t *>(allocTable->at(pos.row));
decodeIndex[cnt++] = i;
availMap |= 1 << i;
--taskCnt;
}
}
ibv_wc wc[MAX_NODES];
rdma->pollSendCompletion(wc, taskCnt);
for (int i = 0; i < taskCnt; ++i) {
int j = WRID_TASK(wc[i].wr_id);
recoverSrc[cnt] = bases[j];
decodeIndex[cnt++] = j;
availMap |= 1 << j;
}
int errs = 0;
for (int i = 0; i < N; ++i)
if ((availMap & (1 << i)) == 0)
recoverOutput[errs++] = page.page.data + i * BlockTy::size;
/* Copy intact data */
for (int i = 0; i < K; ++i)
if (decodeIndex[i] < K)
memcpy(page.page.data + decodeIndex[i] * BlockTy::size, recoverSrc[i], BlockTy::size);
if (errs == 0) {
for (int i = 0; i < N; ++i) {
int peerId = (i + pos.startNodeId) % N;
if (peerId != myNodeConf->id)
rdma->freeReadRegion(peerId, bases[i]);
}
return;
}
#else
int decodeIndex[K], errIndex[K];
uint8_t *recoverSrc[N], *recoverOutput[N];
page.index = index;
memset(page.page.data, 0, Block4K::capacity);
auto pos = getDataPos(index);
int errs = 0;
for (int i = 0, j = 0; i < K && j < N; ++j) {
int peerId = (j + pos.startNodeId) % N;
if (rdma->isPeerAlive(peerId))
decodeIndex[i++] = j;
else if (j < K) {
errIndex[errs] = j;
recoverOutput[errs++] = page.page.data + j * BlockTy::size;
}
}
/* Read data blocks from remote (or self) */
uint64_t blockShift = getBlockShift(pos.row);
ibv_wc wc[2];
for (int i = 0; i < K; ++i) {
int peerId = (decodeIndex[i] + pos.startNodeId) % N;
if (peerId != myNodeConf->id) {
uint8_t *base = rdma->getReadRegion(peerId);
rdma->postRead(peerId, blockShift, (uint64_t)base, BlockTy::size, i);
rdma->pollSendCompletion(wc);
recoverSrc[i] = base;
}
else
recoverSrc[i] = reinterpret_cast<uint8_t *>(allocTable->at(pos.row));
}
/* Copy intact data */
for (int i = 0; i < K; ++i)
if (decodeIndex[i] < K)
memcpy(page.page.data + decodeIndex[i] * BlockTy::size, recoverSrc[i], BlockTy::size);
if (errs == 0) {
for (int i = 0; i < K; ++i) {
int peerId = (decodeIndex[i] + pos.startNodeId) % N;
if (peerId != myNodeConf->id)
rdma->freeReadRegion(peerId, recoverSrc[i]);
}
return;
}
#endif
/* Perform decode */
uint8_t decodeMatrix[N * K];
uint8_t invertMatrix[N * K];
uint8_t b[K * K];
for (int i = 0; i < K; ++i)
memcpy(&b[K * i], &encodeMatrix[K * decodeIndex[i]], K);
if (gf_invert_matrix(b, invertMatrix, K) < 0) {
d_err("cannot do matrix invert!");
return;
}
for (int i = 0; i < errs; ++i)
memcpy(&decodeMatrix[K * i], &invertMatrix[K * errIndex[i]], K);
uint8_t gfTbls[K * P * 32];
ec_init_tables(K, errs, decodeMatrix, gfTbls);
ec_encode_data(BlockTy::size, K, errs, gfTbls, recoverSrc, recoverOutput);
for (int i = 0; i < K; ++i) {
int peerId = (decodeIndex[i] + pos.startNodeId) % N;
if (peerId != myNodeConf->id)
rdma->freeReadRegion(peerId, recoverSrc[i]);
}
}
void ECAL::writeBlock(ECAL::Page &page)
{
static uint8_t *data[K];
for (int i = 0; i < K; ++i)
data[i] = page.page.data + i * BlockTy::size;
ec_encode_data(BlockTy::size, K, P, gfTables, data, parity);
DataPosition pos = getDataPos(page.index);
uint64_t blockShift = getBlockShift(pos.row);
ibv_wc wc[2];
for (int i = 0; i < N; ++i) {
int peerId = (pos.startNodeId + i) % N;
uint8_t *blk = (i < K ? data[i] : parity[i - K]);
if (peerId == myNodeConf->id)
memcpy(allocTable->at(pos.row), blk, BlockTy::size);
else if (rdma->isPeerAlive(peerId)) {
#ifndef USE_RPC
uint8_t *base = rdma->getWriteRegion(peerId);
memcpy(base, blk, BlockTy::size);
rdma->postWrite(peerId, blockShift, (uint64_t)base, BlockTy::size);
rdma->pollSendCompletion(wc);
rdma->freeWriteRegion(peerId, base);
writeCount++;
#else
MemRequest req;
PureValueResponse resp;
req.addr = blockShift;
memcpy(req.data, blk, BlockTy::size);
netif->rpcCall(peerId, ErpcType::ERPC_MEMWRITE, req, resp);
#endif
}
}
}
| 32.568182
| 116
| 0.537858
|
IcicleF
|
9752f68711e6d453b8d71ea60bc1f6eca446b36a
| 4,377
|
cpp
|
C++
|
al/ALSoundEmitter.cpp
|
jomael/AudioEngine
|
48219cee71ad437760d7fe6a6a046c076b5fddd5
|
[
"Apache-2.0"
] | null | null | null |
al/ALSoundEmitter.cpp
|
jomael/AudioEngine
|
48219cee71ad437760d7fe6a6a046c076b5fddd5
|
[
"Apache-2.0"
] | null | null | null |
al/ALSoundEmitter.cpp
|
jomael/AudioEngine
|
48219cee71ad437760d7fe6a6a046c076b5fddd5
|
[
"Apache-2.0"
] | null | null | null |
#include "ALSoundEmitter.hpp"
namespace audio
{
namespace al
{
AudioEmitter::AudioEmitter(const std::string &path):
m_position(0.0f, 0.0f, 0.0f),
m_velocity(0.0f, 0.0f, 0.0f),
m_direction(0.0f, 0.0f, 0.0f),
m_minGain(0.0f),
m_maxGain(0.3f),
m_minDistance(0.0f),
m_maxDistance(0.3f),
m_idBuffer(0),
m_idSource(0)
{
LOG("Constructor");
createSource(path);
m_idBuffer = getSampleBuffer();
m_idSource = getSource();
alSourcei(m_idSource,
AL_BUFFER,
static_cast<ALint>(m_idBuffer));
if(AL_NO_ERROR != alGetError())
{
LOG("OpenAL error");
}
}
AudioEmitter::~AudioEmitter()
{
LOG("Destructor");
}
void AudioEmitter::setPosition(const glm::vec3 &position)
{
m_position = position;
alSource3f(m_idSource, AL_POSITION,
m_position.x, m_position.y, m_position.z);
}
void AudioEmitter::setPosition(const float &x, const float &y, const float &z)
{
m_position = glm::vec3(x, y, z);
alSource3f(m_idSource, AL_POSITION,
m_position.x, m_position.y, m_position.z);
}
void AudioEmitter::setVelocity(const glm::vec3 &velocity)
{
m_velocity = velocity;
alSource3f(m_idSource, AL_VELOCITY,
m_velocity.x, m_velocity.y, m_velocity.z);
}
void AudioEmitter::setVelocity(const float &x, const float &y, const float &z)
{
m_velocity = glm::vec3(x, y, z);
alSource3f(m_idSource, AL_VELOCITY,
m_velocity.x, m_velocity.y, m_velocity.z);
}
void AudioEmitter::setDirection(const glm::vec3 &direction)
{
m_direction = direction;
alSource3f(m_idSource, AL_DIRECTION,
m_direction.x, m_direction.y, m_direction.z);
}
void AudioEmitter::setDirection(const float &x, const float &y, const float &z)
{
m_direction = glm::vec3(x, y, z);
alSource3f(m_idSource, AL_DIRECTION,
m_direction.x, m_direction.y, m_direction.z);
}
void AudioEmitter::setVolume(float &volume)
{
m_volume = volume;
}
void AudioEmitter::setGain(const float &gain)
{
if(gain < 0.0f)
{
LOG("Warning: The gain must be set greater than 0 ");
return;
}
m_gain = gain;
alSourcef(m_idSource, AL_GAIN, m_gain);
}
void AudioEmitter::setLoop(bool loop)
{
m_loop = loop;
alSourcei(m_idSource, AL_LOOPING, loop);
}
void AudioEmitter::setPitch(const float pitch)
{
m_pitch = pitch;
alSourcef(m_idSource, AL_PITCH, m_pitch);
}
void AudioEmitter::setMinMaxDistance(const float &min, const float &max)
{
m_minDistance = min;
m_maxDistance = max;
alSourcef(m_idSource, AL_REFERENCE_DISTANCE, m_minDistance);
alSourcef(m_idSource, AL_REFERENCE_DISTANCE, m_maxDistance);
}
void AudioEmitter::setMinMaxGain(const float &min, const float &max)
{
if(min < 0.0f && max > 1.0f)
{
LOG("Warning: The gain must be range: [0.0 - 1.0]");
return;
}
m_minGain = min;
m_maxGain = max;
alSourcef(m_idSource, AL_MIN_GAIN, min);
alSourcef(m_idSource, AL_MAX_GAIN, max);
}
void AudioEmitter::setDopplerFactor(const float &strength)
{
alSourcef(m_idSource, AL_DOPPLER_FACTOR, strength);
}
void AudioEmitter::setSpeedOfSound(const float &speed)
{
alSpeedOfSound(speed);
}
void AudioEmitter::enableRelativeListener(bool relative)
{
alSourcei(m_idSource, AL_SOURCE_RELATIVE, relative);
}
void AudioEmitter::play()
{
alSourcePlay(m_idSource);
if(AL_NO_ERROR != alGetError())
{
LOG("OpenAL error");
}
}
void AudioEmitter::stop()
{
alSourceStop(m_idSource);
if(AL_NO_ERROR != alGetError())
{
LOG("OpenAL error");
}
}
void AudioEmitter::pause()
{
alSourcePause(m_idSource);
if(AL_NO_ERROR != alGetError())
{
LOG("OpenAL error");
}
}
ALuint AudioEmitter::getState()
{
ALint source_state;
ALuint state = 0;
alGetSourceiv(m_idSource,
AL_SOURCE_STATE, &source_state);
switch(source_state)
{
case(AL_INITIAL):
state = AL_INITIAL;
break;
case(AL_PLAYING):
state = AL_PLAYING;
break;
case(AL_PAUSED):
state = AL_PAUSED;
break;
case(AL_STOPPED):
state = AL_STOPPED;
break;
default:
LOG("Warning: Unknown source state!");
}
return state;
}
} // namespace audio::al
} // namespace al
| 21.043269
| 79
| 0.644277
|
jomael
|
97533821ace90add3aca9d676c86468dca292a5f
| 1,587
|
cpp
|
C++
|
oivlib/renderers/OIVD3D11Renderer/Source/OIVD3D11Renderer.cpp
|
OpenImageViewer/OpenImageViewer
|
95899bc34ca7a2daf3a5ee00c66aab09bc1f0e7b
|
[
"RSA-MD"
] | 19
|
2019-07-11T13:17:54.000Z
|
2022-03-12T14:05:20.000Z
|
oivlib/renderers/OIVD3D11Renderer/Source/OIVD3D11Renderer.cpp
|
OpenImageViewer/OpenImageViewer
|
95899bc34ca7a2daf3a5ee00c66aab09bc1f0e7b
|
[
"RSA-MD"
] | 48
|
2019-01-12T14:52:04.000Z
|
2022-02-16T19:09:48.000Z
|
oivlib/renderers/OIVD3D11Renderer/Source/OIVD3D11Renderer.cpp
|
OpenImageViewer/OIV
|
7b2b67ea156255bf77819ce77bf687c9d360e217
|
[
"RSA-MD"
] | 4
|
2017-07-23T13:37:12.000Z
|
2018-11-30T21:02:01.000Z
|
#include "OIVD3D11Renderer.h"
#include "D3D11/D3D11Renderer.h"
namespace OIV
{
OIVD3D11Renderer::OIVD3D11Renderer()
{
fD3D11Renderer = std::unique_ptr<D3D11Renderer>(new D3D11Renderer());
}
int OIVD3D11Renderer::SetSelectionRect(SelectionRect selectionRect)
{
return fD3D11Renderer->SetselectionRect(selectionRect);
}
int OIVD3D11Renderer::Init(const OIV_RendererInitializationParams& initParams)
{
return fD3D11Renderer->Init(initParams);
}
int OIVD3D11Renderer::SetViewParams(const ViewParameters& viewParams)
{
return fD3D11Renderer->SetViewParams(viewParams);
}
void OIVD3D11Renderer::UpdateGpuParameters()
{
fD3D11Renderer->UpdateGpuParameters();
}
int OIVD3D11Renderer::Redraw()
{
return fD3D11Renderer->Redraw();
}
int OIVD3D11Renderer::SetFilterLevel(OIV_Filter_type filterType)
{
return fD3D11Renderer->SetFilterLevel(filterType);
}
int OIVD3D11Renderer::SetExposure(const OIV_CMD_ColorExposure_Request& exposure)
{
return fD3D11Renderer->SetExposure(exposure);
}
int OIVD3D11Renderer::SetImageBuffer(uint32_t id, const IMCodec::ImageSharedPtr image)
{
return fD3D11Renderer->SetImageBuffer(id, image);
}
int OIVD3D11Renderer::SetImageProperties(const OIV_CMD_ImageProperties_Request& props)
{
return fD3D11Renderer->SetImageProperties(props);
}
int OIVD3D11Renderer::RemoveImage(uint32_t id)
{
return fD3D11Renderer->RemoveImage(id);
}
}
| 26.45
| 90
| 0.701323
|
OpenImageViewer
|
975b738cbf7c4a6aabc32005c5ecd5f2efb06e9c
| 2,887
|
cpp
|
C++
|
src/face/tracker/tracker.cpp
|
bububa/openvision
|
0864e48ec8e69ac13d6889d41f7e1171f53236dd
|
[
"Apache-2.0"
] | 1
|
2022-02-08T06:42:05.000Z
|
2022-02-08T06:42:05.000Z
|
src/face/tracker/tracker.cpp
|
bububa/openvision
|
0864e48ec8e69ac13d6889d41f7e1171f53236dd
|
[
"Apache-2.0"
] | null | null | null |
src/face/tracker/tracker.cpp
|
bububa/openvision
|
0864e48ec8e69ac13d6889d41f7e1171f53236dd
|
[
"Apache-2.0"
] | null | null | null |
#include "../tracker.h"
#include <queue>
IFaceTracker new_face_tracker() {
return new ovface::Tracker();
}
void destroy_face_tracker(IFaceTracker t) {
delete static_cast<ovface::Tracker*>(t);
}
int track_face(IFaceTracker t, const FaceInfoVector* curr_faces, TrackedFaceInfoVector* faces) {
std::vector<ovface::FaceInfo> cfaces;
for (int i = 0; i < curr_faces->length; ++i) {
cfaces.push_back(static_cast<ovface::FaceInfo>(curr_faces->faces[i]));
}
std::vector<ovface::TrackedFaceInfo> tfaces;
int ret = static_cast<ovface::Tracker*>(t)->Track(cfaces, &tfaces);
if (ret != 0) {
return ret;
}
faces->length = tfaces.size();
faces->faces = (TrackedFaceInfo*)malloc(faces->length * sizeof(TrackedFaceInfo));
for (size_t i = 0; i < faces->length; ++i) {
faces->faces[i] = tfaces.at(i);
}
return 0;
}
namespace ovface {
Tracker::Tracker() {
}
Tracker::~Tracker() {
}
int Tracker::Track(const std::vector<FaceInfo>& curr_faces, std::vector<TrackedFaceInfo>* faces) {
faces->clear();
int num_faces = static_cast<int>(curr_faces.size());
std::deque<TrackedFaceInfo>scored_tracked_faces(pre_tracked_faces_.begin(), pre_tracked_faces_.end());
std::vector<TrackedFaceInfo> curr_tracked_faces;
for (int i = 0; i < num_faces; ++i) {
auto& face = curr_faces.at(i);
for (auto scored_tracked_face : scored_tracked_faces) {
ComputeIOU(scored_tracked_face.face_info_.rect,
face.rect, &scored_tracked_face.iou_score_);
}
if (scored_tracked_faces.size() > 0) {
std::partial_sort(scored_tracked_faces.begin(),
scored_tracked_faces.begin() + 1,
scored_tracked_faces.end(),
[](const TrackedFaceInfo &a, const TrackedFaceInfo &b) {
return a.iou_score_ > b.iou_score_;
});
}
if (!scored_tracked_faces.empty() && scored_tracked_faces.front().iou_score_ > minScore_) {
TrackedFaceInfo matched_face = scored_tracked_faces.front();
scored_tracked_faces.pop_front();
TrackedFaceInfo &tracked_face = matched_face;
if (matched_face.iou_score_ < maxScore_) {
tracked_face.face_info_.rect.x = (tracked_face.face_info_.rect.x + face.rect.x) / 2;
tracked_face.face_info_.rect.y = (tracked_face.face_info_.rect.y + face.rect.y) / 2;
tracked_face.face_info_.rect.width = (tracked_face.face_info_.rect.width + face.rect.width) / 2;
tracked_face.face_info_.rect.height = (tracked_face.face_info_.rect.height + face.rect.height) / 2;
} else {
tracked_face.face_info_ = face;
}
curr_tracked_faces.push_back(tracked_face);
} else {
TrackedFaceInfo tracked_face;
tracked_face.face_info_ = face;
curr_tracked_faces.push_back(tracked_face);
}
}
pre_tracked_faces_ = curr_tracked_faces;
*faces = curr_tracked_faces;
return 0;
}
}
| 33.964706
| 106
| 0.678559
|
bububa
|
97663f775bd942d9a0a2bf746b7d3298be040587
| 1,773
|
hh
|
C++
|
backup/TussenEval/mobileip/RequestGenerator.hh
|
JeroenVerstraelen/Telecom
|
05f986e9c119fb8161d006711f968438bbddad74
|
[
"Apache-2.0"
] | null | null | null |
backup/TussenEval/mobileip/RequestGenerator.hh
|
JeroenVerstraelen/Telecom
|
05f986e9c119fb8161d006711f968438bbddad74
|
[
"Apache-2.0"
] | null | null | null |
backup/TussenEval/mobileip/RequestGenerator.hh
|
JeroenVerstraelen/Telecom
|
05f986e9c119fb8161d006711f968438bbddad74
|
[
"Apache-2.0"
] | null | null | null |
#ifndef CLICK_REQUESTGENERATOR_HH
#define CLICK_REQUESTGENERATOR_HH
#include <click/element.hh>
#include <click/timer.hh>
// Local imports
#include "structs/RegistrationData.hh"
CLICK_DECLS
/*
* Click element that will generate requests at the mobile node
* Mobile node will send requests when he has determined that his current agent is no longer online
* or if the mobile node has moved to a foreign network
*/
class RequestGenerator : public Element {
public:
RequestGenerator();
~RequestGenerator();
const char *class_name() const { return "RequestGenerator"; }
const char *port_count() const { return "0/1"; }
const char *processing() const { return PUSH; }
int configure(Vector<String>&, ErrorHandler*);
void run_timer(Timer* t);
// Generate a registration request and push it to output 0
void generateRequest(IPAddress agentAddress, IPAddress coa, uint16_t);
// Stop sending requests when MN is at home
void stopRequests();
private:
// Source address of the mobile node
IPAddress _srcAddress;
// IP address of the mobile node's home agent
IPAddress _homeAgent;
// IP address of the mobile node's current care of address
IPAddress _currentCoa;
// Timer to keep the registration data up to date
Timer _timer;
// Vector of datastructs with information about the pending registrations
Vector<RegistrationData> _pendingRegistrationsData;
// Vector of potential agents
// The generator will use the first IP address of the vector as destination address of its request message
Vector<IPAddress> _potentialAgents;
// Private methods
// Update the remainingLifetime field of each elemenet in the pendingRegistrationsData vector
void _updateRemainingLifetime();
};
CLICK_ENDDECLS
#endif
| 29.55
| 111
| 0.753525
|
JeroenVerstraelen
|
97686b26ef810f0b3a07b0c9ce66a0167b88f1d1
| 4,956
|
cpp
|
C++
|
aws-cpp-sdk-networkmanager/source/model/NetworkResource.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-05T18:20:03.000Z
|
2022-01-05T18:20:03.000Z
|
aws-cpp-sdk-networkmanager/source/model/NetworkResource.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-networkmanager/source/model/NetworkResource.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/networkmanager/model/NetworkResource.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace NetworkManager
{
namespace Model
{
NetworkResource::NetworkResource() :
m_registeredGatewayArnHasBeenSet(false),
m_coreNetworkIdHasBeenSet(false),
m_awsRegionHasBeenSet(false),
m_accountIdHasBeenSet(false),
m_resourceTypeHasBeenSet(false),
m_resourceIdHasBeenSet(false),
m_resourceArnHasBeenSet(false),
m_definitionHasBeenSet(false),
m_definitionTimestampHasBeenSet(false),
m_tagsHasBeenSet(false),
m_metadataHasBeenSet(false)
{
}
NetworkResource::NetworkResource(JsonView jsonValue) :
m_registeredGatewayArnHasBeenSet(false),
m_coreNetworkIdHasBeenSet(false),
m_awsRegionHasBeenSet(false),
m_accountIdHasBeenSet(false),
m_resourceTypeHasBeenSet(false),
m_resourceIdHasBeenSet(false),
m_resourceArnHasBeenSet(false),
m_definitionHasBeenSet(false),
m_definitionTimestampHasBeenSet(false),
m_tagsHasBeenSet(false),
m_metadataHasBeenSet(false)
{
*this = jsonValue;
}
NetworkResource& NetworkResource::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("RegisteredGatewayArn"))
{
m_registeredGatewayArn = jsonValue.GetString("RegisteredGatewayArn");
m_registeredGatewayArnHasBeenSet = true;
}
if(jsonValue.ValueExists("CoreNetworkId"))
{
m_coreNetworkId = jsonValue.GetString("CoreNetworkId");
m_coreNetworkIdHasBeenSet = true;
}
if(jsonValue.ValueExists("AwsRegion"))
{
m_awsRegion = jsonValue.GetString("AwsRegion");
m_awsRegionHasBeenSet = true;
}
if(jsonValue.ValueExists("AccountId"))
{
m_accountId = jsonValue.GetString("AccountId");
m_accountIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ResourceType"))
{
m_resourceType = jsonValue.GetString("ResourceType");
m_resourceTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("ResourceId"))
{
m_resourceId = jsonValue.GetString("ResourceId");
m_resourceIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ResourceArn"))
{
m_resourceArn = jsonValue.GetString("ResourceArn");
m_resourceArnHasBeenSet = true;
}
if(jsonValue.ValueExists("Definition"))
{
m_definition = jsonValue.GetString("Definition");
m_definitionHasBeenSet = true;
}
if(jsonValue.ValueExists("DefinitionTimestamp"))
{
m_definitionTimestamp = jsonValue.GetDouble("DefinitionTimestamp");
m_definitionTimestampHasBeenSet = true;
}
if(jsonValue.ValueExists("Tags"))
{
Array<JsonView> tagsJsonList = jsonValue.GetArray("Tags");
for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
{
m_tags.push_back(tagsJsonList[tagsIndex].AsObject());
}
m_tagsHasBeenSet = true;
}
if(jsonValue.ValueExists("Metadata"))
{
Aws::Map<Aws::String, JsonView> metadataJsonMap = jsonValue.GetObject("Metadata").GetAllObjects();
for(auto& metadataItem : metadataJsonMap)
{
m_metadata[metadataItem.first] = metadataItem.second.AsString();
}
m_metadataHasBeenSet = true;
}
return *this;
}
JsonValue NetworkResource::Jsonize() const
{
JsonValue payload;
if(m_registeredGatewayArnHasBeenSet)
{
payload.WithString("RegisteredGatewayArn", m_registeredGatewayArn);
}
if(m_coreNetworkIdHasBeenSet)
{
payload.WithString("CoreNetworkId", m_coreNetworkId);
}
if(m_awsRegionHasBeenSet)
{
payload.WithString("AwsRegion", m_awsRegion);
}
if(m_accountIdHasBeenSet)
{
payload.WithString("AccountId", m_accountId);
}
if(m_resourceTypeHasBeenSet)
{
payload.WithString("ResourceType", m_resourceType);
}
if(m_resourceIdHasBeenSet)
{
payload.WithString("ResourceId", m_resourceId);
}
if(m_resourceArnHasBeenSet)
{
payload.WithString("ResourceArn", m_resourceArn);
}
if(m_definitionHasBeenSet)
{
payload.WithString("Definition", m_definition);
}
if(m_definitionTimestampHasBeenSet)
{
payload.WithDouble("DefinitionTimestamp", m_definitionTimestamp.SecondsWithMSPrecision());
}
if(m_tagsHasBeenSet)
{
Array<JsonValue> tagsJsonList(m_tags.size());
for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
{
tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
}
payload.WithArray("Tags", std::move(tagsJsonList));
}
if(m_metadataHasBeenSet)
{
JsonValue metadataJsonMap;
for(auto& metadataItem : m_metadata)
{
metadataJsonMap.WithString(metadataItem.first, metadataItem.second);
}
payload.WithObject("Metadata", std::move(metadataJsonMap));
}
return payload;
}
} // namespace Model
} // namespace NetworkManager
} // namespace Aws
| 22.026667
| 102
| 0.726594
|
perfectrecall
|
9768f8885dd8eb4a3fa981293e505843016909c2
| 2,109
|
cpp
|
C++
|
src/plugin.cpp
|
iconmaster5326/Iconus
|
d6f265bd8ebb63199f7f8993864c051fae0484ac
|
[
"MIT"
] | null | null | null |
src/plugin.cpp
|
iconmaster5326/Iconus
|
d6f265bd8ebb63199f7f8993864c051fae0484ac
|
[
"MIT"
] | null | null | null |
src/plugin.cpp
|
iconmaster5326/Iconus
|
d6f265bd8ebb63199f7f8993864c051fae0484ac
|
[
"MIT"
] | null | null | null |
/*
* plugin.cpp
*
* Created on: Jan 21, 2019
* Author: iconmaster
*/
#include "plugin.hpp"
#include "error.hpp"
#include <dlfcn.h>
#include <boost/filesystem.hpp>
using namespace std;
using namespace iconus;
using namespace boost::filesystem;
Vector<Plugin> iconus::Plugin::plugins{};
iconus::Plugin::Plugin(const std::string& filename) : handle(dlopen(filename.c_str(), RTLD_LAZY | RTLD_LOCAL)) {
if (!handle) {
string error(dlerror());
throw Error("Unable to load plugin "+error);
}
auto nameFn = (string(*)()) dlsym(handle, "iconus_getName");
if (!nameFn) {
string error(dlerror());
throw Error("Unable to call iconus_getName in plugin "+error);
}
name = nameFn();
auto htmlFn = (string(*)()) dlsym(handle, "iconus_initHTML");
if (htmlFn) { // initHTML is optional
initHTML = htmlFn();
}
}
static bool endsWith(const string& fullString, const string& ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
void iconus::Plugin::loadPlugin(const std::string& filename) {
path p{filename};
if (is_directory(status(p))) {
for (directory_iterator it{p}; it != directory_iterator{}; it++) {
if (is_directory(it->status()) || endsWith(it->path().string(), ".icolib")) {
loadPlugin(it->path().string());
}
}
} else {
plugins.push_back(Plugin(filename));
}
}
void iconus::Plugin::initGlobalScope(GlobalScope& scope) {
auto fn = (void(*)(GlobalScope&)) dlsym(handle, "iconus_initGlobalScope");
if (!fn) {
string error(dlerror());
throw Error("Unable to call iconus_initGlobalScope in plugin "+name+": "+error);
}
fn(scope);
}
void iconus::Plugin::initSession(Session& session) {
auto fn = (void(*)(Execution&)) dlsym(handle, "iconus_initSession");
if (!fn) {
string error(dlerror());
throw Error("Unable to call iconus_initSession in plugin "+name+": "+error);
}
Execution exe{session};
fn(exe);
}
| 26.3625
| 113
| 0.638217
|
iconmaster5326
|
97725c5034fc7301c9c5d25b75d3e91b2f98b321
| 2,321
|
cpp
|
C++
|
Havtorn/Source/Engine/ECS/Systems/CameraSystem.cpp
|
nicolas-risberg/NewEngine
|
38441f0713167ca8a469a1c6c0e7a290b5e402de
|
[
"MIT"
] | null | null | null |
Havtorn/Source/Engine/ECS/Systems/CameraSystem.cpp
|
nicolas-risberg/NewEngine
|
38441f0713167ca8a469a1c6c0e7a290b5e402de
|
[
"MIT"
] | null | null | null |
Havtorn/Source/Engine/ECS/Systems/CameraSystem.cpp
|
nicolas-risberg/NewEngine
|
38441f0713167ca8a469a1c6c0e7a290b5e402de
|
[
"MIT"
] | 1
|
2022-01-09T12:01:24.000Z
|
2022-01-09T12:01:24.000Z
|
// Copyright 2022 Team Havtorn. All Rights Reserved.
#include "hvpch.h"
#include "CameraSystem.h"
#include "Engine.h"
#include "Scene/Scene.h"
#include "ECS/Components/TransformComponent.h"
#include "ECS/Components/CameraComponent.h"
#include "Input/InputMapper.h"
namespace Havtorn
{
CCameraSystem::CCameraSystem()
: CSystem()
{
CEngine::GetInstance()->GetInput()->GetAxisDelegate(EInputAxisEvent::Up).AddMember(this, &CCameraSystem::HandleAxisInput);
CEngine::GetInstance()->GetInput()->GetAxisDelegate(EInputAxisEvent::Right).AddMember(this, &CCameraSystem::HandleAxisInput);
CEngine::GetInstance()->GetInput()->GetAxisDelegate(EInputAxisEvent::Forward).AddMember(this, &CCameraSystem::HandleAxisInput);
CEngine::GetInstance()->GetInput()->GetAxisDelegate(EInputAxisEvent::Pitch).AddMember(this, &CCameraSystem::HandleAxisInput);
CEngine::GetInstance()->GetInput()->GetAxisDelegate(EInputAxisEvent::Yaw).AddMember(this, &CCameraSystem::HandleAxisInput);
}
CCameraSystem::~CCameraSystem()
{
}
void CCameraSystem::Update(CScene* scene)
{
const auto& transformComponents = scene->GetTransformComponents();
const auto& cameraComponents = scene->GetCameraComponents();
if (cameraComponents.empty())
return;
const I64 transformCompIndex = cameraComponents[0]->Entity->GetComponentIndex(EComponentType::TransformComponent);
auto& transformComp = transformComponents[transformCompIndex];
const F32 dt = CTimer::Dt();
transformComp->Transform.Translate(CameraMoveInput * dt);
transformComp->Transform.Rotate(CameraRotateInput * dt);
CameraMoveInput = SVector::Zero;
CameraRotateInput = SVector::Zero;
}
void CCameraSystem::HandleAxisInput(const SInputAxisPayload payload)
{
switch (payload.Event)
{
case EInputAxisEvent::Right:
CameraMoveInput += SVector::Right * payload.AxisValue;
return;
case EInputAxisEvent::Up:
CameraMoveInput += SVector::Up * payload.AxisValue;
return;
case EInputAxisEvent::Forward:
CameraMoveInput += SVector::Forward * payload.AxisValue;
return;
case EInputAxisEvent::Pitch:
CameraRotateInput.X += UMath::DegToRad(90.0f) * payload.AxisValue;
return;
case EInputAxisEvent::Yaw:
CameraRotateInput.Y += UMath::DegToRad(90.0f) * payload.AxisValue;
return;
default:
return;
}
}
}
| 33.637681
| 129
| 0.750539
|
nicolas-risberg
|
977335667972ede6f1574fdb5fd052ae49fd8556
| 6,582
|
cpp
|
C++
|
include/util/GLShapeRenderer.cpp
|
hvidal/GameEngine3D
|
1794ad891d2200260be935283645a03af3ebcfcc
|
[
"MIT"
] | 6
|
2020-07-03T21:14:56.000Z
|
2021-11-11T09:37:40.000Z
|
include/util/GLShapeRenderer.cpp
|
hvidal/GameEngine3D
|
1794ad891d2200260be935283645a03af3ebcfcc
|
[
"MIT"
] | null | null | null |
include/util/GLShapeRenderer.cpp
|
hvidal/GameEngine3D
|
1794ad891d2200260be935283645a03af3ebcfcc
|
[
"MIT"
] | 2
|
2020-08-15T22:37:21.000Z
|
2021-01-17T11:31:27.000Z
|
#include "GLShapeRenderer.h"
#include "ShaderUtils.h"
static constexpr const char* vsShape[] = {
"attribute vec4 position;"
"attribute vec4 normal;"
"uniform mat4 V;"
"uniform mat4 P;"
"uniform mat4 m16;"
"uniform vec3 sunPosition;"
"varying vec4 eyeV;"
"varying vec3 eyeN;"
"varying vec4 eyeL;"
,ShaderUtils::TO_MAT3,
"void main() {"
"vec4 worldV = m16 * position;"
"eyeN = toMat3(V) * toMat3(m16) * normal.xyz;"
"eyeL = V * vec4(sunPosition, 1.0);"
"eyeV = V * worldV;"
"gl_Position = P * V * worldV;"
"}"
};
static constexpr const char* fsShape[] = {
"varying vec4 eyeV;"
"varying vec3 eyeN;"
"varying vec4 eyeL;"
"const float Ka = 0.15;"
"const float Kd = 0.35;"
"const float Ks = 0.15;"
"const float Shininess = 0.5;"
"vec4 color(vec3 eyeV, vec3 eyeN, vec3 eyeL) {"
"vec3 n = normalize(eyeN);"
"vec3 s = normalize(eyeL - eyeV);"
"vec3 v = normalize(-eyeV);"
"vec3 halfWay = normalize(v + s);"
"float dotSN = abs(dot(s, eyeN));"
"float c = Ka + Kd * max(dotSN, 0.0) + Ks * pow(max(dot(halfWay, n), 0.0), Shininess);"
"return vec4(c, c, c, 1.0);"
"}"
"void main() {"
"gl_FragColor = color(eyeV.xyz, eyeN, eyeL.xyz);"
"}"
};
//-----------------------------------------------------------------------------
GLShapeRenderer::GLShapeRenderer() {
mShader = std::make_unique<Shader>(vsShape, fsShape);
mShader->bindAttribute(0, "position");
mShader->bindAttribute(1, "normal");
mShader->link();
}
GLShapeRenderer::~GLShapeRenderer() {
Log::debug("Deleting GLShapeRenderer");
}
GLShapeRenderer::ShapeCache* GLShapeRenderer::cache(btConvexShape* shape) {
ShapeCache* info = (ShapeCache*) shape->getUserPointer();
if (!info) {
auto pUniqueInfo = std::make_unique<ShapeCache>(shape);
info = pUniqueInfo.get();
shape->setUserPointer(info);
mShapeCaches.push_front(std::move(pUniqueInfo));
}
if (info->mEdges.size() == 0) {
info->mShapeHull.buildHull(shape->getMargin());
const int ni = info->mShapeHull.numIndices();
const int nv = info->mShapeHull.numVertices();
const unsigned int* pi = info->mShapeHull.getIndexPointer();
const btVector3* pv = info->mShapeHull.getVertexPointer();
btAlignedObjectArray<ShapeCache::Edge*> edges;
info->mEdges.reserve(ni);
edges.resize(nv * nv,0);
for(int i = 0; i < ni; i += 3) {
const unsigned int* ti = pi + i;
const btVector3& nrm = btCross(pv[ti[1]] - pv[ti[0]], pv[ti[2]] - pv[ti[0]]).normalized();
for(int j = 2, k = 0; k < 3; j = k++) {
const unsigned int a = ti[j];
const unsigned int b = ti[k];
ShapeCache::Edge*& e = edges[btMin(a, b) * nv + btMax(a, b)];
if (!e) {
info->mEdges.push_back(ShapeCache::Edge());
e = &info->mEdges[info->mEdges.size()-1];
e->n[0] = nrm;
e->n[1] = -nrm;
e->v[0] = a;
e->v[1] = b;
} else
e->n[1] = nrm;
}
}
}
return (info);
}
//-----------------------------------------------------------------------------
GLShapeRenderer::ShapeCache::ShapeCache(btConvexShape *s):
mShapeHull(s),
ready(false)
{}
GLShapeRenderer::ShapeCache::~ShapeCache() {
Log::debug("Deleting ShaperCache");
glDeleteBuffers(1, &mVbo);
glDeleteBuffers(1, &mNbo);
glDeleteBuffers(1, &mIbo);
}
void GLShapeRenderer::ShapeCache::bind() {
int nTriangles = mShapeHull.numTriangles();
if (nTriangles > 0) {
const btVector3* vtx = mShapeHull.getVertexPointer();
const unsigned int* idx = mShapeHull.getIndexPointer();
unsigned int index = 0;
for (unsigned int i = 0; i < nTriangles; i++) {
unsigned int i1 = index++;
unsigned int i2 = index++;
unsigned int i3 = index++;
mIndices.push_back(i1);
mIndices.push_back(i2);
mIndices.push_back(i3);
unsigned int index1 = idx[i1];
unsigned int index2 = idx[i2];
unsigned int index3 = idx[i3];
btVector3 v1 = vtx[index1];
btVector3 v2 = vtx[index2];
btVector3 v3 = vtx[index3];
btVector3 normal = (v3-v1).cross(v2-v1).normalized();
mVertices.push_back(v1);
mVertices.push_back(v2);
mVertices.push_back(v3);
mNormals.push_back(normal);
mNormals.push_back(normal);
mNormals.push_back(normal);
}
}
glGenBuffers(1, &mVbo);
glGenBuffers(1, &mNbo);
glGenBuffers(1, &mIbo);
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
glBufferData(GL_ARRAY_BUFFER, mVertices.size() * sizeof(btVector3), &mVertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, mNbo);
glBufferData(GL_ARRAY_BUFFER, mNormals.size() * sizeof(btVector3), &mNormals[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mIndices.size() * sizeof(unsigned int), &mIndices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
ready = true;
}
void GLShapeRenderer::ShapeCache::render() {
if (!ready)
bind();
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(btVector3), 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, mNbo);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(btVector3), 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo);
glDrawElements(GL_TRIANGLES, mIndices.size(), GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void GLShapeRenderer::render(const ICamera *camera, const ISky *sky, const btCollisionShape* shape, const Matrix4x4& m4x4, bool opaque) {
if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE) {
const btCompoundShape* compoundShape = static_cast<const btCompoundShape*>(shape);
for (int i = compoundShape->getNumChildShapes() - 1; i >= 0; i--) {
float m0[16];
compoundShape->getChildTransform(i).getOpenGLMatrix(m0);
// we have to multiply the matrices now
Matrix4x4 m_child(m0);
Matrix4x4 copy(m4x4);
copy.multiplyRight(m_child);
const btCollisionShape* colShape = compoundShape->getChildShape(i);
render(camera, sky, colShape, copy, opaque);
}
return;
}
if (shape->isConvex()) {
ShapeCache* info = cache((btConvexShape*) shape);
btShapeHull* hull = &info->mShapeHull;
int nTriangles = hull->numTriangles();
if (nTriangles > 0) {
int index = 0;
const unsigned int* idx = hull->getIndexPointer();
const btVector3* vtx = hull->getVertexPointer();
mShader->run();
camera->setMatrices(mShader.get());
mShader->set("m16", m4x4);
mShader->set("sunPosition", sky->getSunPosition());
info->render();
IShader::stop();
}
}
}
| 26.647773
| 137
| 0.660134
|
hvidal
|
97734d44b6bc7da7a7caa0a19af0eda06e174101
| 2,813
|
cc
|
C++
|
src/kinem/EDepSimRooTrackerKinematicsFactory.cc
|
andrewmogan/edep-sim
|
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
|
[
"MIT"
] | 15
|
2017-04-25T14:20:22.000Z
|
2022-03-15T19:39:43.000Z
|
src/kinem/EDepSimRooTrackerKinematicsFactory.cc
|
andrewmogan/edep-sim
|
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
|
[
"MIT"
] | 24
|
2017-11-08T21:16:48.000Z
|
2022-03-04T13:33:18.000Z
|
src/kinem/EDepSimRooTrackerKinematicsFactory.cc
|
andrewmogan/edep-sim
|
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
|
[
"MIT"
] | 20
|
2017-11-09T15:41:46.000Z
|
2022-01-25T20:52:32.000Z
|
#include <TFile.h>
#include <TTree.h>
#include <TBits.h>
#include <TObjString.h>
#include "kinem/EDepSimRooTrackerKinematicsFactory.hh"
#include "kinem/EDepSimRooTrackerKinematicsGenerator.hh"
EDepSim::RooTrackerKinematicsFactory::RooTrackerKinematicsFactory(
EDepSim::UserPrimaryGeneratorMessenger* parent)
: EDepSim::VKinematicsFactory("rooTracker",parent),
fInputFile("not-open"), fTreeName("gRooTracker"),
fGeneratorName("GENIE"), fOrder("consecutive"), fFirstEvent(0) {
fInputFileCMD = new G4UIcmdWithAString(CommandName("input"),this);
fInputFileCMD->SetGuidance("Set the input file.");
fInputFileCMD->SetParameterName("name",false);
fTreeNameCMD = new G4UIcmdWithAString(CommandName("tree"),this);
fTreeNameCMD->SetGuidance("Set the tree path in the input file.");
fTreeNameCMD->SetParameterName("tree",false);
fGeneratorNameCMD = new G4UIcmdWithAString(CommandName("generator"),this);
fGeneratorNameCMD->SetGuidance("Set the name of the kinematics source.");
fGeneratorNameCMD->SetParameterName("generator",false);
fOrderCMD = new G4UIcmdWithAString(CommandName("order"),this);
fOrderCMD->SetGuidance("Set order that events in the file are used.");
fOrderCMD->SetParameterName("order",false);
fOrderCMD->SetCandidates("consecutive stride random");
fFirstEventCMD = new G4UIcmdWithAnInteger(CommandName("first"),this);
fFirstEventCMD->SetGuidance("Set the first event to generate.");
fFirstEventCMD->SetParameterName("number",false);
}
EDepSim::RooTrackerKinematicsFactory::~RooTrackerKinematicsFactory() {
delete fInputFileCMD;
delete fTreeNameCMD;
delete fGeneratorNameCMD;
delete fOrderCMD;
delete fFirstEventCMD;
}
void EDepSim::RooTrackerKinematicsFactory::SetNewValue(G4UIcommand* command,
G4String newValue) {
if (command == fInputFileCMD) {
SetInputFile(newValue);
}
else if (command == fTreeNameCMD) {
SetTreeName(newValue);
}
else if (command == fGeneratorNameCMD) {
SetGeneratorName(newValue);
}
else if (command == fOrderCMD) {
SetOrder(newValue);
}
else if (command == fFirstEventCMD) {
SetFirstEvent(fFirstEventCMD->GetNewIntValue(newValue));
}
}
EDepSim::VKinematicsGenerator* EDepSim::RooTrackerKinematicsFactory::GetGenerator() {
EDepSim::VKinematicsGenerator* kine
= new EDepSim::RooTrackerKinematicsGenerator(GetGeneratorName(),
GetInputFile(),
GetTreeName(),
GetOrder(),
GetFirstEvent());
return kine;
}
| 38.534247
| 85
| 0.661927
|
andrewmogan
|
9776376067598d81822190da02d3f457274697d6
| 1,266
|
cpp
|
C++
|
Strings/valid_number.cpp
|
khushisinha20/Data-Structures-and-Algorithms
|
114d365d03f7ba7175eefeace281972820a7fc76
|
[
"Apache-2.0"
] | null | null | null |
Strings/valid_number.cpp
|
khushisinha20/Data-Structures-and-Algorithms
|
114d365d03f7ba7175eefeace281972820a7fc76
|
[
"Apache-2.0"
] | null | null | null |
Strings/valid_number.cpp
|
khushisinha20/Data-Structures-and-Algorithms
|
114d365d03f7ba7175eefeace281972820a7fc76
|
[
"Apache-2.0"
] | null | null | null |
//leetcode.com/problems/valid-number
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isNumber(string s) {
bool visitedDigit = false;
bool visitedE = false;
bool visitedDot = false;
int countPlusMinus = 0;
for (int i = 0; i < s.length(); ++i) {
if (isdigit(s[i])) {
visitedDigit = true;
} else if (s[i] == '+' || s[i] == '-') {
if (countPlusMinus == 2)
return false;
if (i > 0 && (s[i - 1] != 'e' && s[i - 1] != 'E'))
return false;
if (i == s.length() - 1)
return false;
++countPlusMinus;
} else if (s[i] == '.') {
if (visitedE || visitedDot)
return false;
if (i == s.length() - 1 && !visitedDigit)
return false;
visitedDot = true;
} else if (s[i] == 'e' || s[i] == 'E') {
if (visitedE || !visitedDigit || i == s.length() - 1)
return false;
visitedE = true;
} else {
return false;
}
}
return true;
}
};
| 31.65
| 69
| 0.390995
|
khushisinha20
|
977973b989c0951f9818dce1dbafdc5a6aeca9ea
| 775
|
cpp
|
C++
|
tools/src/entry.cpp
|
GameDevTecnico/cubos
|
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
|
[
"MIT"
] | 2
|
2021-09-28T14:13:27.000Z
|
2022-03-26T11:36:48.000Z
|
tools/src/entry.cpp
|
GameDevTecnico/cubos
|
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
|
[
"MIT"
] | 72
|
2021-09-29T08:55:26.000Z
|
2022-03-29T21:21:00.000Z
|
tools/src/entry.cpp
|
GameDevTecnico/cubos
|
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
|
[
"MIT"
] | null | null | null |
#include "tools.hpp"
#include <iostream>
#include <string>
/// Prints the help message of the program.
int runHelp(int, char**)
{
std::cerr << "Usage: cubinhos <TOOL>" << std::endl;
std::cerr << "Tools:" << std::endl;
for (size_t i = 0; i < sizeof(tools) / sizeof(tools[0]); ++i)
{
std::cerr << " " << tools[i].name << std::endl;
}
return 0;
}
int main(int argc, char** argv)
{
// Parse command line arguments.
if (argc >= 2)
{
// Find the desired tool.
for (size_t i = 0; i < sizeof(tools) / sizeof(tools[0]); ++i)
{
if (tools[i].name == argv[1])
{
return tools[i].run(argc - 2, argv + 2);
}
}
}
runHelp(argc, argv);
return 1;
}
| 21.527778
| 69
| 0.491613
|
GameDevTecnico
|
97799f60f7e6c20819954fce1914e2cf3f868043
| 4,360
|
cpp
|
C++
|
examples/connect4/muzero_connect4.cpp
|
tuero/muzero-cpp
|
a679275a2c6f6a6ff7fb38ede40423aced0afe10
|
[
"Apache-2.0"
] | 6
|
2022-01-13T07:41:50.000Z
|
2022-02-07T22:29:01.000Z
|
examples/connect4/muzero_connect4.cpp
|
tuero/muzero-cpp
|
a679275a2c6f6a6ff7fb38ede40423aced0afe10
|
[
"Apache-2.0"
] | null | null | null |
examples/connect4/muzero_connect4.cpp
|
tuero/muzero-cpp
|
a679275a2c6f6a6ff7fb38ede40423aced0afe10
|
[
"Apache-2.0"
] | 1
|
2022-01-19T01:29:23.000Z
|
2022-01-19T01:29:23.000Z
|
#include <algorithm>
#include <string>
#include <vector>
#include "absl/flags/flag.h"
#include "connect4.h"
#include "muzero-cpp/abstract_game.h"
#include "muzero-cpp/config.h"
#include "muzero-cpp/default_flags.h"
#include "muzero-cpp/muzero.h"
#include "muzero-cpp/types.h"
using namespace muzero_cpp;
using namespace muzero_cpp::types;
using namespace muzero_cpp::muzero_config;
class Connect4Env : public AbstractGame {
public:
Connect4Env(int seed) : env_(seed) {}
Connect4Env() = delete;
~Connect4Env() = default;
/**
* Reset the environment for a new game.
*/
Observation reset() override {
return env_.reset();
}
/**
* Apply the given action to the environment
* @param action The action to send to the environment
* @return A struct containing the observation, reward, and a flag indicating if the game is done
*/
StepReturn step(Action action) override {
StepReturn step_return = env_.step(action);
step_return.reward *= 10;
return step_return;
}
/**
* Returns the current player to play
* @return The player number to play
*/
Player to_play() const override {
return env_.to_play();
}
/**
* Return the legal actions for the current environment state.
* @returns Vector of legal action ids
*/
std::vector<Action> legal_actions() const override {
return env_.legal_actions();
}
/**
* Returns an action given by an expert player/bot.
* @returns An expert action which is legal
*/
Action expert_action() override {
return env_.expert_action();
}
/**
* Returns a legal action given by human input.
* @returns An action which is legal
*/
Action human_to_action() override {
std::vector<Action> legal_actions = env_.legal_actions();
Action action;
while (true) {
std::cout << "Enter a column to play: ";
std::cin >> action;
if (std::find(legal_actions.begin(), legal_actions.end(), action) != legal_actions.end()) {
break;
}
}
return action;
}
/**
* Render the environment for testing games.
*/
void render() override {
std::cout << env_.board_to_str() << std::endl;
}
/**
* Convert action to human readable string.
* @param action The action to convert
* @returns The string format of the action
*/
std::string action_to_string(types::Action action) const override {
return std::to_string(action);
}
private:
Connect4 env_; // Environment
};
// Encode action as feature plane of values 1/action
Observation encode_action(Action action) {
static const int num_actions = Connect4::action_space().size();
ObservationShape obs_shape = Connect4::obs_shape();
Observation obs(obs_shape.w * obs_shape.h, (double)action / num_actions);
return obs;
}
// Simple softmax schedule
double get_softmax(int step) {
if (step < 25000) {
return 1.0;
} else if (step < 50000) {
return 0.5;
}
return 0.125;
}
// Additional flag to choose whether to test or not
ABSL_FLAG(bool, test, false, "Test using human input.");
int main(int argc, char** argv) {
// parse flags
parse_flags(argc, argv);
MuZeroConfig config = get_initial_config();
// Set specific values for the game
config.observation_shape = Connect4::obs_shape();
config.action_space = Connect4::action_space();
config.network_config.normalize_hidden_states = true;
config.action_channels = 1;
config.num_players = 2;
config.value_upperbound = 10;
config.value_lowerbound = -10;
config.min_reward = -10;
config.max_reward = 10;
config.min_value = -10;
config.max_value = 10;
config.opponent_type = OpponentTypes::Expert;
config.action_representation_initial = encode_action;
config.action_representation_recurrent = encode_action;
config.visit_softmax_temperature = get_softmax;
// Perform learning or testing
if (absl::GetFlag(FLAGS_test)) {
config.opponent_type = OpponentTypes::Human;
return play_test_model(config, game_factory<Connect4Env>);
} else {
return muzero(config, game_factory<Connect4Env>);
}
return 0;
}
| 28.311688
| 103
| 0.648394
|
tuero
|
977e90456303ebbec60914f971122fcef7961fd6
| 154
|
cpp
|
C++
|
Extensions/ImGui/ImGui.cpp
|
LinkClinton/Code-Red
|
491621144aba559f068c7f91d71e3d0d7c87761e
|
[
"MIT"
] | 34
|
2019-09-11T09:12:16.000Z
|
2022-02-13T12:50:25.000Z
|
Extensions/ImGui/ImGui.cpp
|
LinkClinton/Code-Red
|
491621144aba559f068c7f91d71e3d0d7c87761e
|
[
"MIT"
] | 7
|
2019-09-22T14:21:26.000Z
|
2020-03-24T10:36:20.000Z
|
Extensions/ImGui/ImGui.cpp
|
LinkClinton/Code-Red
|
491621144aba559f068c7f91d71e3d0d7c87761e
|
[
"MIT"
] | 6
|
2019-10-21T18:05:55.000Z
|
2021-04-22T05:07:30.000Z
|
#include "ImGui.hpp"
#include <ThirdParties/ImGui/imgui_widgets.cpp>
#include <ThirdParties/ImGui/imgui_draw.cpp>
#include <ThirdParties/ImGui/imgui.cpp>
| 30.8
| 47
| 0.805195
|
LinkClinton
|
9784707529cad01bad713cef513a0bf27d9b440b
| 519
|
hpp
|
C++
|
src/String.hpp
|
enebe-nb/SokuLib
|
e4fdc913b6ce4bfce65d2fa7ccfcbdf9b5a2c910
|
[
"MIT"
] | 2
|
2021-03-06T08:32:44.000Z
|
2021-04-18T20:43:42.000Z
|
src/String.hpp
|
enebe-nb/SokuLib
|
e4fdc913b6ce4bfce65d2fa7ccfcbdf9b5a2c910
|
[
"MIT"
] | 4
|
2020-11-29T20:25:32.000Z
|
2021-12-11T14:38:34.000Z
|
src/String.hpp
|
enebe-nb/SokuLib
|
e4fdc913b6ce4bfce65d2fa7ccfcbdf9b5a2c910
|
[
"MIT"
] | 3
|
2021-02-18T19:59:14.000Z
|
2021-09-07T13:23:38.000Z
|
//
// Created by Gegel85 on 04/11/2020.
//
#ifndef SOKULIB_STRING_HPP
#define SOKULIB_STRING_HPP
#include <string>
namespace SokuLib
{
#pragma pack(push, 4)
// std::string ?
struct String {
enum { BUF_SIZE = 16 };
void *alloc;
union {
char buf[16];
char* ptr;
} body;
size_t size;
size_t res;
String();
operator char *();
operator const char *() const;
operator std::string() const;
String &operator=(const std::string &str);
};
#pragma pack(pop)
}
#endif //SOKULIB_STRING_HPP
| 14.027027
| 44
| 0.645472
|
enebe-nb
|
97857a096f016968ca5c463cac9d6c4412c2f3c7
| 1,664
|
cpp
|
C++
|
rosbag2_py/src/rosbag2_py/_reindexer.cpp
|
MourtazaKASSAMALY/rosbag2
|
d195b67186f2e63eeab6b3589250bf19c3ef95b7
|
[
"Apache-2.0"
] | 118
|
2018-04-27T10:48:44.000Z
|
2022-03-30T14:45:13.000Z
|
rosbag2_py/src/rosbag2_py/_reindexer.cpp
|
MourtazaKASSAMALY/rosbag2
|
d195b67186f2e63eeab6b3589250bf19c3ef95b7
|
[
"Apache-2.0"
] | 851
|
2018-05-16T19:11:49.000Z
|
2022-03-31T23:02:50.000Z
|
rosbag2_py/src/rosbag2_py/_reindexer.cpp
|
MourtazaKASSAMALY/rosbag2
|
d195b67186f2e63eeab6b3589250bf19c3ef95b7
|
[
"Apache-2.0"
] | 147
|
2018-04-03T17:05:06.000Z
|
2022-03-24T06:05:42.000Z
|
// Copyright 2021 DCS Corporation, All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// DISTRIBUTION A. Approved for public release; distribution unlimited.
// OPSEC #4584.
//
// Delivered to the U.S. Government with Unlimited Rights, as defined in DFARS
// Part 252.227-7013 or 7014 (Feb 2014).
//
// This notice must appear in all copies of this file and its derivatives.
#include <memory>
#include <string>
#include <vector>
#include "rosbag2_cpp/reindexer.hpp"
#include "rosbag2_storage/storage_options.hpp"
#include "./pybind11.hpp"
namespace rosbag2_py
{
class Reindexer
{
public:
Reindexer()
: reindexer_(std::make_unique<rosbag2_cpp::Reindexer>())
{
}
void reindex(const rosbag2_storage::StorageOptions & storage_options)
{
reindexer_->reindex(storage_options);
}
protected:
std::unique_ptr<rosbag2_cpp::Reindexer> reindexer_;
};
} // namespace rosbag2_py
PYBIND11_MODULE(_reindexer, m) {
m.doc() = "Python wrapper of the rosbag2_cpp reindexer API";
pybind11::class_<rosbag2_py::Reindexer>(
m, "Reindexer")
.def(pybind11::init())
.def("reindex", &rosbag2_py::Reindexer::reindex);
}
| 27.278689
| 78
| 0.733173
|
MourtazaKASSAMALY
|
9787a33301218116d1db62158535bc14ebd59d14
| 4,178
|
cc
|
C++
|
tests/unit/active/test_async_op.cc
|
rbuch/vt
|
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
|
[
"BSD-3-Clause"
] | 26
|
2019-11-26T08:36:15.000Z
|
2022-02-15T17:13:21.000Z
|
tests/unit/active/test_async_op.cc
|
rbuch/vt
|
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
|
[
"BSD-3-Clause"
] | 1,215
|
2019-09-09T14:31:33.000Z
|
2022-03-30T20:20:14.000Z
|
tests/unit/active/test_async_op.cc
|
rbuch/vt
|
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
|
[
"BSD-3-Clause"
] | 12
|
2019-09-08T00:03:05.000Z
|
2022-02-23T21:28:35.000Z
|
/*
//@HEADER
// *****************************************************************************
//
// test_async_op.cc
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#include <mpi.h>
#include "test_parallel_harness.h"
#include <vt/runtime/mpi_access.h>
#include <vt/messaging/async_op_mpi.h>
#include <vt/objgroup/manager.h>
#include <gtest/gtest.h>
namespace vt { namespace tests { namespace unit {
using TestAsyncOp = TestParallelHarness;
using MyMsg = Message;
struct MyObjGroup {
void handler(MyMsg* msg) {
auto const this_node = theContext()->getNode();
auto const num_nodes = theContext()->getNumNodes();
auto const to_node = (this_node + 1) % num_nodes;
from_node_ = this_node - 1;
if (from_node_ < 0) {
from_node_ = num_nodes - 1;
}
auto comm = theContext()->getComm();
int const tag = 299999;
MPI_Request req1;
send_val_ = this_node;
{
VT_ALLOW_MPI_CALLS; // MPI_Isend
MPI_Isend(&send_val_, 1, MPI_INT, to_node, tag, comm, &req1);
}
auto op1 = std::make_unique<messaging::AsyncOpMPI>(req1);
MPI_Request req2;
{
VT_ALLOW_MPI_CALLS; // MPI_Irecv
MPI_Irecv(&recv_val_, 1, MPI_INT, from_node_, tag, comm, &req2);
}
auto op2 = std::make_unique<messaging::AsyncOpMPI>(
req2, [this]{ done_ = true; }
);
// Register these async operations for polling; since these operations are
// enclosed in an epoch, they should inhibit the current epoch from
// terminating before they are done.
theMsg()->registerAsyncOp(std::move(op1));
theMsg()->registerAsyncOp(std::move(op2));
}
void check() {
EXPECT_EQ(from_node_, recv_val_);
EXPECT_TRUE(done_);
}
int send_val_ = 0;
int recv_val_ = -1000;
bool done_ = false;
NodeType from_node_ = 0;
};
TEST_F(TestAsyncOp, test_async_op_1) {
auto const this_node = theContext()->getNode();
auto p = theObjGroup()->makeCollective<MyObjGroup>();
auto ep = theTerm()->makeEpochRooted(term::UseDS{true});
// When this returns all the MPI requests should be done
runInEpoch(ep, [p, this_node]{
p[this_node].send<MyMsg, &MyObjGroup::handler>();
});
// Check async MPI ops are completed after return
p[this_node].get()->check();
}
}}} // end namespace vt::tests::unit
| 34.245902
| 81
| 0.675443
|
rbuch
|
9790391d9726de160df3cdf972093617182714b0
| 3,405
|
cpp
|
C++
|
NDD_VR_Viewer/src/application.cpp
|
Ezrit/VR_TCMPODS
|
bc114a4c98bf7af6a348825671fcea49004e22b5
|
[
"Unlicense"
] | null | null | null |
NDD_VR_Viewer/src/application.cpp
|
Ezrit/VR_TCMPODS
|
bc114a4c98bf7af6a348825671fcea49004e22b5
|
[
"Unlicense"
] | null | null | null |
NDD_VR_Viewer/src/application.cpp
|
Ezrit/VR_TCMPODS
|
bc114a4c98bf7af6a348825671fcea49004e22b5
|
[
"Unlicense"
] | null | null | null |
#include "application.hpp"
#include <iostream>
namespace msi_vr
{
Application::Application(GLFWwindow *window)
: window(window)
{
initInputManager(window);
}
Application::~Application()
{
}
void Application::run()
{
std::chrono::high_resolution_clock::time_point point = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> elapsedTime;
std::chrono::duration<float> accumulatedTime(0.f);
while (glfwWindowShouldClose(window) == 0)
{
auto newPoint = std::chrono::high_resolution_clock::now();
elapsedTime = newPoint - point;
point = newPoint;
accumulatedTime += elapsedTime;
while (accumulatedTime > fixedUpdateTime)
{
inputManager.update(fixedUpdateTime.count());
fixedUpdate(fixedUpdateTime);
accumulatedTime -= fixedUpdateTime;
}
update(elapsedTime);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
render();
// swap
glfwSwapBuffers(window);
glfwPollEvents();
}
}
GLFWwindow* Application::initWindow(int windowWidth, int windowHeight, std::string const &name)
{
glewExperimental = true;
if (!glfwInit())
{
std::cerr << "Failed to initialize GLFW!" << std::endl;
return NULL;
}
glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // We want OpenGL 3.3
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // We dont want the old OpenGL
// Open a window and create its opengl context
//std::unique_ptr<GLFWwindow> window = std::unique_ptr<GLFWwindow>(glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL));
GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, name.c_str(), NULL, NULL);
if (window == NULL)
{
std::cerr << "Failed to open GLFW Window!" << std::endl;
return NULL;
}
glfwMakeContextCurrent(window); // Initialize GLEW
glewExperimental = true;
if (glewInit() != GLEW_OK)
{
std::cerr << "Failed to initialize GLEW!" << std::endl;
return NULL;
}
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
glfwSetCursorPosCallback(window, Mouse::mouse_callback);
glfwSetMouseButtonCallback(window, Mouse::mouse_button_callback);
glfwSetScrollCallback(window, Mouse::mouse_scroll_callback);
return window;
}
bool Application::initInputManager(GLFWwindow *w)
{
if(!w) return false;
inputManager.setWindow(w);
glfwSetCursorPosCallback(window, Mouse::mouse_callback);
glfwSetMouseButtonCallback(window, Mouse::mouse_button_callback);
return true;
}
void Application::handleInput(std::chrono::duration<float> const &time)
{
inputManager.update(time.count());
}
} // namespace msi_vr
| 32.122642
| 131
| 0.601762
|
Ezrit
|
979bffedd639c532469e3d2a17c9be71dbd3a679
| 2,727
|
cpp
|
C++
|
src/editorLib/Render/AbstractLightRenderObserver.cpp
|
AluminiumRat/mtt
|
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
|
[
"MIT"
] | null | null | null |
src/editorLib/Render/AbstractLightRenderObserver.cpp
|
AluminiumRat/mtt
|
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
|
[
"MIT"
] | null | null | null |
src/editorLib/Render/AbstractLightRenderObserver.cpp
|
AluminiumRat/mtt
|
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
|
[
"MIT"
] | null | null | null |
#include <stdexcept>
#include <mtt/clPipeline/MeshTechniques/InstrumentalCompositeTechnique.h>
#include <mtt/clPipeline/constants.h>
#include <mtt/editorLib/Render/AbstractLightRenderObserver.h>
#include <mtt/editorLib/Objects/LightObject.h>
#include <mtt/editorLib/EditorApplication.h>
#include <mtt/render/Mesh/UidMeshTechnique.h>
#include <mtt/render/Pipeline/Buffer.h>
#include <mtt/render/SceneGraph/CompositeObjectNode.h>
#include <mtt/utilities/Box.h>
#include <mtt/utilities/Log.h>
using namespace mtt;
AbstractLightRenderObserver::AbstractLightRenderObserver(
LightObject& object,
CommonEditData& commonData,
const QString& iconFilename,
float iconSize) :
Object3DRenderObserver(object, commonData),
_object(object),
_lightRenderer(nullptr)
{
if (!iconFilename.isEmpty() && iconSize > 0)
{
_iconNode.emplace(iconFilename, iconSize);
registerUnculledDrawable(*_iconNode);
positionJoint().addChild(*_iconNode);
_iconNode->addModificator(visibleFilter());
_iconNode->addModificator(uidSetter());
_iconNode->addModificator(selectionModificator());
}
registerCulledDrawable(_hullNode);
positionRotateJoint().addChild(_hullNode);
_hullNode.addModificator(visibleFilter());
_hullNode.addModificator(uidSetter());
_hullNode.addModificator(selectionModificator());
connect(&_object,
&LightObject::enabledChanged,
this,
&AbstractLightRenderObserver::_updateEnabled,
Qt::DirectConnection);
_updateEnabled();
}
void AbstractLightRenderObserver::setLightObject(CompositeObjectNode& light)
{
_clearLightRenderer();
try
{
_lightRenderer = &light;
positionRotateJoint().addChild(*_lightRenderer);
if(_object.enabled()) registerCompositeObject(*_lightRenderer);
}
catch (...)
{
_clearLightRenderer();
throw;
}
}
void AbstractLightRenderObserver::_clearLightRenderer() noexcept
{
if(_lightRenderer != nullptr && _object.enabled())
{
unregisterCompositeObject(*_lightRenderer);
}
}
void AbstractLightRenderObserver::_updateEnabled() noexcept
{
if (_lightRenderer != nullptr)
{
try
{
if(_object.enabled()) registerCompositeObject(*_lightRenderer);
else unregisterCompositeObject(*_lightRenderer);
}
catch (std::exception& error)
{
Log() << "AbstractLightRenderObserver::_updateEnabled: " << error.what();
}
catch (...)
{
Log() << "AbstractLightRenderObserver::_updateEnabled: unable to register area modificator";
}
}
}
| 29.010638
| 98
| 0.678768
|
AluminiumRat
|
97a41693077f05f618eee91147e2c1cb301d881d
| 1,016
|
cpp
|
C++
|
termite/termite-#0060-kitt-green/main.cpp
|
OscarKro/hwlib-examples
|
112bc551f4142f841703dc348f528eda5f41ac30
|
[
"BSL-1.0"
] | null | null | null |
termite/termite-#0060-kitt-green/main.cpp
|
OscarKro/hwlib-examples
|
112bc551f4142f841703dc348f528eda5f41ac30
|
[
"BSL-1.0"
] | 1
|
2021-01-05T17:05:34.000Z
|
2021-01-05T20:18:13.000Z
|
termite/termite-#0060-kitt-green/main.cpp
|
OscarKro/hwlib-examples
|
112bc551f4142f841703dc348f528eda5f41ac30
|
[
"BSL-1.0"
] | 3
|
2021-01-05T14:39:39.000Z
|
2021-09-15T05:18:46.000Z
|
// ==========================================================================
//
// blink the LED on a blue-pill board
//
// (c) Wouter van Ooijen (wouter@voti.nl) 2017
//
// 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)
//
// ==========================================================================
#include "hwlib.hpp"
int main( void ){
auto g0 = hwlib::target::pin_out( hwlib::target::pins::b4 );
auto g1 = hwlib::target::pin_out( hwlib::target::pins::b6 );
auto g2 = hwlib::target::pin_out( hwlib::target::pins::b5 );
auto g3 = hwlib::target::pin_out( hwlib::target::pins::a0 );
auto g4 = hwlib::target::pin_out( hwlib::target::pins::b7 );
auto g5 = hwlib::target::pin_out( hwlib::target::pins::b0 );
auto g6 = hwlib::target::pin_out( hwlib::target::pins::b1 );
auto port = hwlib::port_out_from( g0, g1, g2, g3, g4, g5, g6 );
hwlib::kitt( port );
}
| 37.62963
| 77
| 0.534449
|
OscarKro
|
97a525f7c9091f17e708a69ca4f1fe300d8aa254
| 647
|
cpp
|
C++
|
hackerrank/interview-preparation-kit/string-manipulation/alternating-characters/main.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 18
|
2020-08-27T05:27:50.000Z
|
2022-03-08T02:56:48.000Z
|
hackerrank/interview-preparation-kit/string-manipulation/alternating-characters/main.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | null | null | null |
hackerrank/interview-preparation-kit/string-manipulation/alternating-characters/main.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 1
|
2020-10-13T05:23:58.000Z
|
2020-10-13T05:23:58.000Z
|
#include <bits/stdc++.h>
using namespace std;
// Complete the alternatingCharacters function below.
int alternatingCharacters(string s) {
int ans=0;
char c=s[0];
for(int i=1;i<s.size();i++){
char cc=s[i];
if(c==cc) ans++;
else c=cc;
}
return ans;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int q;
cin >> q;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int q_itr = 0; q_itr < q; q_itr++) {
string s;
getline(cin, s);
int result = alternatingCharacters(s);
fout << result << "\n";
}
fout.close();
return 0;
}
| 17.026316
| 56
| 0.540958
|
wingkwong
|
97a8fa014a4ece73019398eb4934399baeb767bf
| 12,209
|
cpp
|
C++
|
Life/boundaries.cpp
|
TheGitPuller/ParallelGameOfLife
|
a399704cf37efe69f37125b9cc6ef532c912cfc9
|
[
"MIT"
] | null | null | null |
Life/boundaries.cpp
|
TheGitPuller/ParallelGameOfLife
|
a399704cf37efe69f37125b9cc6ef532c912cfc9
|
[
"MIT"
] | null | null | null |
Life/boundaries.cpp
|
TheGitPuller/ParallelGameOfLife
|
a399704cf37efe69f37125b9cc6ef532c912cfc9
|
[
"MIT"
] | null | null | null |
#include "boundaries.h"
using namespace std;
// Constructor
boundary_communication::boundary_communication(bool**& grid, int imax_local, int jmax_local) : grid(grid), imax(imax_local), jmax(jmax_local)
{}
void boundary_communication::make_types()
{
// Declare storage vectors
vector<int> block_length;
vector<MPI_Aint> addresses;
vector<MPI_Datatype> typelist;
/*========================================================================================*/
// LEFT
/*========================================================================================*/
// Data is discontiguous in memory space, so we must extract the entire column iteratively
//Left side send type
for (int i = 1; i <= imax; i++)
{
block_length.push_back(1);
MPI_Aint ls_temp;
MPI_Get_address(&grid[i][1], &ls_temp);
addresses.push_back(ls_temp);
typelist.push_back(MPI_C_BOOL);
}
// Create datatype for sending left strip of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->left_send_type);
MPI_Type_commit(&this->left_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
// Data is discontiguous in memory space, so we must extract the entire column iteratively
//Left side recv type
for (int i = 1; i <= imax; i++)
{
block_length.push_back(1);
MPI_Aint lr_temp;
MPI_Get_address(&grid[i][0], &lr_temp);
addresses.push_back(lr_temp);
typelist.push_back(MPI_C_BOOL);
}
// Create datatype for sending left strip of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->left_recv_type);
MPI_Type_commit(&this->left_recv_type);
/*========================================================================================*/
// RIGHT
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
// Data is discontiguous in memory space, so we must extract the entire column iteratively
// Right side send type
for (int i = 1; i <= imax; i++)
{
block_length.push_back(1);
MPI_Aint rs_temp;
MPI_Get_address(&grid[i][jmax], &rs_temp);
addresses.push_back(rs_temp);
typelist.push_back(MPI_C_BOOL);
}
// Create datatype for sending right strip of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->right_send_type);
MPI_Type_commit(&this->right_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
// Data is discontiguous in memory space, so we must extract the entire column iteratively
// Right side recv type
for (int i = 1; i <= imax; i++)
{
block_length.push_back(1);
MPI_Aint rr_temp;
MPI_Get_address(&grid[i][jmax + 1], &rr_temp);
addresses.push_back(rr_temp);
typelist.push_back(MPI_C_BOOL);
}
// Create datatype for sending right strip of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->right_recv_type);
MPI_Type_commit(&this->right_recv_type);
/*========================================================================================*/
// TOP
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
MPI_Aint ts_temp;
// Top side send type
// Data is contiguous in space, so we can just grab the first pointer in that array
block_length.push_back(jmax);
MPI_Get_address(&grid[1][1], &ts_temp);
addresses.push_back(ts_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending top strip of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->top_send_type);
MPI_Type_commit(&this->top_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
MPI_Aint tr_temp;
// Top side recv type
// Data is contiguous in space, so we can just grab the first pointer in that array
block_length.push_back(jmax);
MPI_Get_address(&grid[0][1], &tr_temp);
addresses.push_back(tr_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending top strip of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &top_recv_type);
MPI_Type_commit(&this->top_recv_type);
/*========================================================================================*/
// BOTTOM
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
// bottom side send type
// Data is contiguous in space, so we can just grab the first pointer in that array
block_length.push_back(jmax);
MPI_Aint bs_temp;
MPI_Get_address(&grid[imax][1], &bs_temp);
addresses.push_back(bs_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending bottom strip of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->bottom_send_type);
MPI_Type_commit(&this->bottom_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
//top side recv type
block_length.push_back(jmax);
MPI_Aint br_temp;
MPI_Get_address(&grid[imax + 1][1], &br_temp);
addresses.push_back(br_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending bottom strip of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->bottom_recv_type);
MPI_Type_commit(&this->bottom_recv_type);
/*========================================================================================*/
// TOP - LEFT
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
//top-left corner send type
block_length.push_back(1);
MPI_Aint tls_temp;
MPI_Get_address(&grid[1][1], &tls_temp);
addresses.push_back(tls_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending top-left corner of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->top_left_send_type);
MPI_Type_commit(&this->top_left_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
//top-left corner recv type
block_length.push_back(1);
MPI_Aint tlr_temp;
MPI_Get_address(&grid[0][0], &tlr_temp);
addresses.push_back(tlr_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending top - left corner of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->top_left_recv_type);
MPI_Type_commit(&this->top_left_recv_type);
/*========================================================================================*/
// TOP - RIGHT
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
//top-right corner send type
block_length.push_back(1);
MPI_Aint trs_temp;
MPI_Get_address(&grid[1][jmax], &trs_temp);
addresses.push_back(trs_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending top - right corner of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->top_right_send_type);
MPI_Type_commit(&this->top_right_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
//top-right corner recv type
block_length.push_back(1);
MPI_Aint trr_temp;
MPI_Get_address(&grid[0][jmax + 1], &trr_temp);
addresses.push_back(trr_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending top - right corner of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->top_right_recv_type);
MPI_Type_commit(&this->top_right_recv_type);
/*========================================================================================*/
// BOTTOM - LEFT
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
// bottom-left corner send type
block_length.push_back(1);
MPI_Aint bls_temp;
MPI_Get_address(&grid[imax][1], &bls_temp);
addresses.push_back(bls_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending bottom - left corner of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->bottom_left_send_type);
MPI_Type_commit(&this->bottom_left_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
// bottom-left corner recv type
block_length.push_back(1);
MPI_Aint blr_temp;
MPI_Get_address(&grid[imax + 1][0], &blr_temp);
addresses.push_back(blr_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending bottom - left corner of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->bottom_left_recv_type);
MPI_Type_commit(&this->bottom_left_recv_type);
/*========================================================================================*/
// BOTTOM - RIGHT
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
//bottom-right corner send type
block_length.push_back(1);
MPI_Aint brs_temp;
MPI_Get_address(&grid[imax][jmax], &brs_temp);
addresses.push_back(brs_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending bottom - right corner of inner grid
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->bottom_right_send_type);
MPI_Type_commit(&this->bottom_right_send_type);
/*========================================================================================*/
block_length.clear();
addresses.clear();
typelist.clear();
//Bottom-right corner recv type
block_length.push_back(1);
MPI_Aint brr_temp;
MPI_Get_address(&grid[imax + 1][jmax + 1], &brr_temp);
addresses.push_back(brr_temp);
typelist.push_back(MPI_C_BOOL);
// Create datatype for sending bottom - right corner of halo
MPI_Type_create_struct(block_length.size(), &block_length[0], &addresses[0], &typelist[0], &this->bottom_right_recv_type);
MPI_Type_commit(&this->bottom_right_recv_type);
block_length.clear();
addresses.clear();
typelist.clear();
}
boundary_communication::~boundary_communication()
{
// Free the newly created datatypes when they're no longer needed
MPI_Type_free(&this->left_send_type);
MPI_Type_free(&this->left_recv_type);
MPI_Type_free(&this->right_send_type);
MPI_Type_free(&this->right_recv_type);
MPI_Type_free(&this->top_send_type);
MPI_Type_free(&this->top_recv_type);
MPI_Type_free(&this->bottom_send_type);
MPI_Type_free(&this->bottom_recv_type);
MPI_Type_free(&this->top_left_send_type);
MPI_Type_free(&this->top_left_recv_type);
MPI_Type_free(&this->top_right_send_type);
MPI_Type_free(&this->top_right_recv_type);
MPI_Type_free(&this->bottom_left_send_type);
MPI_Type_free(&this->bottom_left_recv_type);
MPI_Type_free(&this->bottom_right_send_type);
MPI_Type_free(&this->bottom_right_recv_type);
};
| 37.566154
| 142
| 0.593333
|
TheGitPuller
|
97af9a231d739e46cac30c34f7f3ac8e3805a74a
| 2,601
|
cpp
|
C++
|
src/libutility/utility.cpp
|
publiqnet/belt.pp
|
837112652885284cd0f8245b1c9cf31dcfad17e1
|
[
"MIT"
] | 4
|
2017-11-24T09:47:18.000Z
|
2019-02-18T14:43:05.000Z
|
src/libutility/utility.cpp
|
publiqnet/belt.pp
|
837112652885284cd0f8245b1c9cf31dcfad17e1
|
[
"MIT"
] | 1
|
2018-04-11T12:42:25.000Z
|
2018-04-11T12:42:25.000Z
|
src/libutility/utility.cpp
|
publiqnet/belt.pp
|
837112652885284cd0f8245b1c9cf31dcfad17e1
|
[
"MIT"
] | 2
|
2019-01-10T14:11:28.000Z
|
2021-05-31T11:14:46.000Z
|
#include "utility.hpp"
#include <random>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <exception>
#include <stdexcept>
namespace
{
std::string format_tm(std::tm const& t)
{
char buffer[80];
if (0 == strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", &t))
{
assert(false);
throw std::logic_error("format_tm");
}
return std::string(buffer);
}
bool scan_tm(std::string const& strt, std::tm& st)
{
if (6 !=
#ifdef B_OS_WINDOWS
sscanf_s(
#else
sscanf(
#endif
strt.c_str(),
"%d-%d-%d %d:%d:%d",
&st.tm_year,
&st.tm_mon,
&st.tm_mday,
&st.tm_hour,
&st.tm_min,
&st.tm_sec))
return false;
st.tm_year -= 1900;
--st.tm_mon;
if (format_tm(st) != strt)
return false;
return true;
}
}
namespace beltpp
{
tm gm_time_t_to_gm_tm(time_t t)
{
tm result;
#if defined B_OS_WINDOWS
gmtime_s(&result, &t);
#else
gmtime_r(&t, &result);
#endif
return result;
}
tm gm_time_t_to_lc_tm(time_t t)
{
tm result;
#if defined B_OS_WINDOWS
localtime_s(&result, &t);
#else
localtime_r(&t, &result);
#endif
return result;
}
time_t gm_tm_to_gm_time_t(std::tm const& t)
{
std::tm temp = t;
#if defined B_OS_WINDOWS
return _mkgmtime(&temp);
#else
return timegm(&temp);
#endif
}
time_t lc_tm_to_gm_time_t(std::tm const& t)
{
std::tm temp = t;
return mktime(&temp);
}
std::string gm_time_t_to_gm_string(time_t t)
{
std::tm st = gm_time_t_to_gm_tm(t);
return format_tm(st);
}
std::string gm_time_t_to_lc_string(time_t t)
{
std::tm st = gm_time_t_to_lc_tm(t);
return format_tm(st);
}
bool gm_string_to_gm_time_t(std::string const& strt, time_t& t)
{
std::tm st;
if (false == scan_tm(strt, st))
return false;
t = gm_tm_to_gm_time_t(st);
return true;
}
bool lc_string_to_gm_time_t(std::string const& strt, time_t& t)
{
std::tm st;
if (false == scan_tm(strt, st))
return false;
t = lc_tm_to_gm_time_t(st);
return true;
}
double random_in_range(double from, double to)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(from, to);
return dist(mt);
}
bool chance_one_of(uint32_t count)
{
if (0 == count)
return false;
if (1 == count)
return true;
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<uint32_t> dist(0, count - 1);
if (0 == dist(mt))
return true;
return false;
}
}
| 18.0625
| 63
| 0.600538
|
publiqnet
|
97b433e511b54b9483cb21af4f34833a5dcb7ab2
| 2,271
|
cpp
|
C++
|
lib/rdf/test/print_node_01_run.cpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 10
|
2017-12-21T05:20:40.000Z
|
2021-09-18T05:14:01.000Z
|
lib/rdf/test/print_node_01_run.cpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 2
|
2017-12-21T07:31:54.000Z
|
2021-06-23T08:52:35.000Z
|
lib/rdf/test/print_node_01_run.cpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 7
|
2016-02-17T13:20:31.000Z
|
2021-11-08T09:30:43.000Z
|
/** @file "/owlcpp/lib/rdf/test/print_node_01_run.cpp"
part of owlcpp project.
@n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt.
@n Copyright Mikhail K Levin 2012
*******************************************************************************/
#define BOOST_TEST_MODULE print_node_01_run
#include <iostream>
#include "boost/test/unit_test.hpp"
#include "test/exception_fixture.hpp"
#include "owlcpp/terms/node_tags_owl.hpp"
#include "owlcpp/rdf/print_node.hpp"
#include "owlcpp/rdf/node_iri.hpp"
#include "owlcpp/rdf/node_blank.hpp"
#include "owlcpp/rdf/node_literal.hpp"
namespace owlcpp{ namespace test{
namespace t = owlcpp::terms;
/**@test Print nodes without triple store
*******************************************************************************/
BOOST_AUTO_TEST_CASE( test_print_node_01 ) {
const Node_iri niri(Ns_id(42), "blah");
BOOST_CHECK_EQUAL(to_string(niri), "Ns42:blah");
Node const& riri = niri;
BOOST_CHECK_EQUAL(to_string(riri), "Ns42:blah");
std::cout << niri << std::endl;
const Node_blank nb(5, Doc_id(42));
BOOST_CHECK_EQUAL(to_string(nb), "_:Doc42-5");
Node const& rb = nb;
BOOST_CHECK_EQUAL(to_string(rb), "_:Doc42-5");
const Node_bool nbo1(1, t::xsd_boolean::id());
BOOST_CHECK( nbo1.value() );
BOOST_CHECK_EQUAL(to_string(nbo1), "true");
Node const& rbo1 = nbo1;
BOOST_CHECK_EQUAL(to_string(rbo1), "true");
const Node_bool nbo2("false");
BOOST_CHECK_EQUAL(to_string(nbo2), "false");
Node const& rbo2 = nbo2;
BOOST_CHECK_EQUAL(to_string(rbo2), "false");
const Node_string ns("blah");
BOOST_CHECK_EQUAL(to_string(ns), "\"blah\"");
Node const& rs = ns;
BOOST_CHECK_EQUAL(to_string(rs), "\"blah\"");
BOOST_CHECK_THROW(Node_int("0.1"), Rdf_err);
const Node_int ni("-1");
BOOST_CHECK_EQUAL(to_string(ni), "-1");
Node const& ri = ni;
BOOST_CHECK_EQUAL(to_string(ri), "-1");
const Node_unsigned nu("1123123");
BOOST_CHECK_EQUAL(to_string(nu), "1123123");
Node const& ru = nu;
BOOST_CHECK_EQUAL(to_string(ru), "1123123");
const Node_double nd("1.23");
BOOST_CHECK_EQUAL(to_string(nd), "1.23");
Node const& rd = nd;
BOOST_CHECK_EQUAL(to_string(rd), "1.23");
}
}//namespace test
}//namespace owlcpp
| 32.913043
| 85
| 0.653897
|
GreyMerlin
|
b638f7c03b0e5f8d8f751259faaf90e4741372d0
| 7,453
|
hpp
|
C++
|
include/termox/painter/dynamic_colors.hpp
|
skvl/TermOx
|
35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934
|
[
"MIT"
] | null | null | null |
include/termox/painter/dynamic_colors.hpp
|
skvl/TermOx
|
35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934
|
[
"MIT"
] | null | null | null |
include/termox/painter/dynamic_colors.hpp
|
skvl/TermOx
|
35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934
|
[
"MIT"
] | 1
|
2021-08-06T10:17:28.000Z
|
2021-08-06T10:17:28.000Z
|
#ifndef TERMOX_PAINTER_DYNAMIC_COLORS_HPP
#define TERMOX_PAINTER_DYNAMIC_COLORS_HPP
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <random>
#include <termox/painter/color.hpp>
#include <termox/system/system.hpp>
namespace ox::dynamic {
/// Dynamic_color type that cycles through every hue value in HSL color wheel.
class Rainbow {
public:
/// Creates a Rainbow Dynamic Color w/fixed saturation and lightness values.
Rainbow(std::uint8_t saturation, std::uint8_t lightness)
: saturation_{saturation}, lightness_{lightness}
{}
public:
auto operator()() -> True_color
{
return True_color{
HSL{this->postincrement_hue(), saturation_, lightness_}};
}
private:
std::uint16_t hue_ = 0;
std::uint8_t const saturation_;
std::uint8_t const lightness_;
private:
// Increments hue_, then returns the previous value, wraps at 360.
auto postincrement_hue() -> std::uint16_t
{
auto const old = hue_;
if (++hue_ == 360)
hue_ = 0;
return old;
}
};
/// Returns a Rainbow Dynamic_color object. Convinience for defining palettes.
inline auto rainbow(
Dynamic_color::Period_t period = std::chrono::milliseconds{40},
std::uint8_t saturation = 75,
std::uint8_t lightness = 75) -> Dynamic_color
{
return {period, Rainbow{saturation, lightness}};
}
/* ---------------------------------------------------------------------------*/
class Modulation_base {
protected:
/// Resolution is the number of steps to complete a full cycle.
Modulation_base(unsigned resolution)
: step_total_{static_cast<double>(resolution)}
{}
protected:
/// Finds the next ratio between from the current step and resolution.
auto get_next_ratio() -> double
{
return this->post_increment_step() / step_total_;
}
private:
double const step_total_;
int step_{0};
private:
/// Apply a wrapping post increment to step_ and return the previous value.
auto post_increment_step() -> int
{
return step_ == step_total_ ? (step_ = 0, step_total_) : step_++;
}
};
template <typename Function>
class Invert : public Function {
public:
using Function::Function;
public:
auto operator()() -> double { return -1. * Function::operator()() + 1.; }
};
template <typename Function>
class Concave : public Function {
public:
using Function::Function;
public:
auto operator()() -> double { return std::pow(Function::operator()(), 2.); }
};
template <typename Function>
class Convex : public Function {
public:
using Function::Function;
public:
auto operator()() -> double { return std::sqrt(Function::operator()()); }
};
class Triangle : private Modulation_base {
public:
/// Resolution is the number of steps to complete a full cycle.
Triangle(unsigned resolution) : Modulation_base{resolution} {}
public:
/// Returns value in range [0.0, 1.0]
auto operator()() -> double
{
return -1. * std::abs(2 * this->get_next_ratio() - 1.) + 1.;
}
};
class Sine : private Modulation_base {
public:
/// Resolution is the number of steps to complete a full cycle.
Sine(unsigned resolution) : Modulation_base{resolution} {}
public:
/// Returns value in range [0.0, 1.0]
auto operator()() -> double
{
auto constexpr pi = 3.1416;
return .5 * (1 + std::sin(2 * pi * (this->get_next_ratio() - .25)));
}
};
class Sawtooth_up : private Modulation_base {
public:
/// Resolution is the number of steps to complete a full cycle.
Sawtooth_up(unsigned resolution) : Modulation_base{resolution} {}
public:
/// Returns value in range [0.0, 1.0]
auto operator()() -> double { return this->get_next_ratio(); }
};
class Sawtooth_down : public Invert<Sawtooth_up> {
public:
using Invert::Invert;
};
class Square : private Modulation_base {
public:
/// Resolution is the number of steps to complete a full cycle.
Square(unsigned resolution) : Modulation_base{resolution} {}
public:
/// Returns value in range [0.0, 1.0]
auto operator()() -> double
{
return this->get_next_ratio() < 0.5 ? 0. : 1.;
}
};
class Random : private Modulation_base {
public:
/// Resolution is the number of steps to complete a full cycle.
Random(unsigned resolution) : Modulation_base{resolution} {}
public:
/// Returns value in range [0.0, 1.0]
auto operator()() -> double { return dist_(gen_); }
private:
std::mt19937 gen_{std::random_device{}()};
std::uniform_real_distribution<double> dist_{0., 1.};
};
/// Dynamic_color type that fades between two HSL Colors.
/** Modulation of the shift between the two colors controlled by Shape fn. */
template <typename Shape>
class Fade {
public:
/// Dynamic Color that cycles between \p a and \p b and back.
/** Shape function object should return ratio of where between the two
* colors the fade is at. */
Fade(HSL a, HSL b, Shape&& shape_fn)
: base_{a}, distance_{find_distance(a, b)}, shape_fn_{shape_fn}
{}
public:
auto operator()() -> True_color { return this->step(); }
private:
/// Holds the difference between two HSL values.
struct HSL_diff {
int hue_diff;
int saturation_diff;
int lightness_diff;
};
private:
HSL const base_;
HSL_diff const distance_;
Shape shape_fn_;
private:
/// Return HSL_diff composed of the distance between \p a and \p b.
static auto find_distance(HSL a, HSL b) -> HSL_diff
{
return {b.hue - a.hue, b.saturation - a.saturation,
b.lightness - a.lightness};
}
/// Performs a single step and returns the calculated HSL value.
auto step() -> HSL
{
double const ratio = shape_fn_();
double const h = base_.hue + distance_.hue_diff * ratio;
double const s = base_.saturation + distance_.saturation_diff * ratio;
double const l = base_.lightness + distance_.lightness_diff * ratio;
return this->shrink(h, s, l);
}
// Use to create an HSL from double values, performs narrowing conversions.
static auto shrink(double hue, double saturation, double lightness) -> HSL
{
return {static_cast<std::uint16_t>(hue),
static_cast<std::uint8_t>(saturation),
static_cast<std::uint8_t>(lightness)};
}
};
/// Returns a Fade Dynamic_color object. Convinience for defining palettes.
template <typename Shape>
auto fade(HSL a,
HSL b,
unsigned resolution = 400,
Dynamic_color::Period_t interval = std::chrono::milliseconds{40})
-> Dynamic_color
{
return {interval, Fade{a, b, Shape{resolution}}};
}
/// Returns a Fade Dynamic_color object. Convinience for defining palettes.
template <typename Shape>
auto fade(True_color a,
True_color b,
unsigned resolution = 400,
Dynamic_color::Period_t interval = std::chrono::milliseconds{40})
-> Dynamic_color
{
return fade<Shape>(True_color::rgb_to_hsl({a.red(), a.green(), a.blue()}),
True_color::rgb_to_hsl({b.red(), b.green(), b.blue()}),
resolution, interval);
}
} // namespace ox::dynamic
#endif // TERMOX_PAINTER_DYNAMIC_COLORS_HPP
| 28.555556
| 80
| 0.636791
|
skvl
|
b6399f12e2a03b94bd2b80a489a9795b02a5b90b
| 170
|
cpp
|
C++
|
Libraries/RobsJuceModules/rosic/filters/rosic_EllipticQuarterBandFilter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 34
|
2017-04-19T18:26:02.000Z
|
2022-02-15T17:47:26.000Z
|
Libraries/RobsJuceModules/rosic/filters/rosic_EllipticQuarterBandFilter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 307
|
2017-05-04T21:45:01.000Z
|
2022-02-03T00:59:01.000Z
|
Libraries/RobsJuceModules/rosic/filters/rosic_EllipticQuarterBandFilter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 4
|
2017-09-05T17:04:31.000Z
|
2021-12-15T21:24:28.000Z
|
rsEllipticQuarterBandFilter::rsEllipticQuarterBandFilter()
{
reset();
}
void rsEllipticQuarterBandFilter::reset()
{
for(int i = 0; i < 12; i++)
w[i] = 0.0;
}
| 14.166667
| 58
| 0.652941
|
RobinSchmidt
|
b6445ae5c5cea5d57686165e1b34aa076b15dbea
| 11,584
|
cpp
|
C++
|
Source/API/D3D12/FramebufferD3D12.cpp
|
KawBuma/Buma3D
|
73b1c7a99c979492f072d4ead89f2d357d5e048a
|
[
"MIT"
] | 5
|
2020-11-25T05:05:13.000Z
|
2022-02-09T09:35:21.000Z
|
Source/API/D3D12/FramebufferD3D12.cpp
|
KawBuma/Buma3D
|
73b1c7a99c979492f072d4ead89f2d357d5e048a
|
[
"MIT"
] | 5
|
2020-11-11T09:52:59.000Z
|
2021-12-15T13:27:37.000Z
|
Source/API/D3D12/FramebufferD3D12.cpp
|
KawBuma/Buma3D
|
73b1c7a99c979492f072d4ead89f2d357d5e048a
|
[
"MIT"
] | null | null | null |
#include "Buma3DPCH.h"
#include "FramebufferD3D12.h"
namespace buma3d
{
B3D_APIENTRY FramebufferD3D12::FramebufferD3D12()
: ref_count { 1 }
, name {}
, device {}
, desc {}
, desc_data {}
, device12 {}
, descriptors {}
, attachment_operators {}
{
}
B3D_APIENTRY FramebufferD3D12::~FramebufferD3D12()
{
Uninit();
}
BMRESULT
B3D_APIENTRY FramebufferD3D12::Init(DeviceD3D12* _device, const FRAMEBUFFER_DESC& _desc)
{
(device = _device)->AddRef();
device12 = _device->GetD3D12Device();
CopyDesc(_desc);
B3D_RET_IF_FAILED(ParseRenderPassAndAllocateDescriptor());
B3D_RET_IF_FAILED(CreateAttachmentOperators());
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY FramebufferD3D12::ParseRenderPassAndAllocateDescriptor()
{
/*
Framebuffer作成時にアタッチメントの数に応じてアドレスが連続したグローバルRTVディスクリプタを割り当て、View作成時のRTVディスクリプタをコピーします。
RTV/DSVディスクリプタはGPU不可視です(OMSetRenderTargetsにCPUディスクリプタをセットするのみでOK)。
TODO: GPU不可視ディスクリプタにもノードマスクの制約(CopyDescriptorsでノード0x1->0x2へのディスクリプタコピーが出来ない。の様なケースが)が存在するか確認する。(CBV_SRV_UAV、SAMPLERも同様)
*/
auto&& rpdesc = desc_data.render_pass12->GetDesc();
descriptors.resize(rpdesc.num_subpasses);
for (uint32_t i_pass = 0; i_pass < rpdesc.num_subpasses; i_pass++)
{
auto sp = rpdesc.subpasses[i_pass];
auto&& subpass_descriptor = descriptors[i_pass];
if (sp.num_color_attachments == 0)
{
// UAVのみを使用するケースなど、sp.num_color_attachmentsは0である可能性があります。
}
else if (sp.num_color_attachments == 1)
{
// 単一のレンダーターゲットビューの場合、作成時に割り当てられたディスクリプタをそのまま使用します。
auto index = sp.color_attachments[0].attachment_index;
subpass_descriptor.PrepareSingleRTVHandle(desc.attachments[index]->As<RenderTargetViewD3D12>()->GetCpuDescriptorAllocation()->handle.begin);
}
else
{
subpass_descriptor.rtv = device->GetCPUDescriptorAllocator(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, B3D_DEFAULT_NODE_MASK).Allocate(sp.num_color_attachments);
subpass_descriptor.PrepareRTVHandles();
for (uint32_t i = 0; i < sp.num_color_attachments; i++)
{
auto index = sp.color_attachments[i].attachment_index;
auto&& src_handle = *desc.attachments[index]->As<RenderTargetViewD3D12>()->GetCpuDescriptorAllocation();
device12->CopyDescriptorsSimple(1, subpass_descriptor.rtvhandles[i], src_handle.handle, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
}
}
if (sp.depth_stencil_attachment)
{
// 深度ステンシルビューは作成時に割り当てられたディスクリプタをそのまま使用します。
auto index = sp.depth_stencil_attachment->attachment_index;
subpass_descriptor.dsv = desc.attachments[index]->As<DepthStencilViewD3D12>()->GetCpuDescriptorAllocation()->handle.begin;
}
}
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY FramebufferD3D12::CreateAttachmentOperators()
{
attachment_operators.resize(desc.num_attachments);
auto attachment_operators_data = attachment_operators.data();
for (uint32_t i = 0; i < desc.num_attachments; i++)
{
auto at = desc.attachments[i];
switch (at->GetViewDesc().type)
{
case buma3d::VIEW_TYPE_SHADER_RESOURCE:
attachment_operators_data[i] = B3DMakeUniqueArgs(AttachmentOperatorSRV, at->As<ShaderResourceViewD3D12>());
break;
case buma3d::VIEW_TYPE_RENDER_TARGET:
attachment_operators_data[i] = B3DMakeUniqueArgs(AttachmentOperatorRTV, at->As<RenderTargetViewD3D12>());
break;
case buma3d::VIEW_TYPE_DEPTH_STENCIL:
attachment_operators_data[i] = B3DMakeUniqueArgs(AttachmentOperatorDSV, at->As<DepthStencilViewD3D12>());
break;
default:
return BMRESULT_FAILED_INVALID_PARAMETER;
}
}
return BMRESULT_SUCCEED;
}
void
B3D_APIENTRY FramebufferD3D12::CopyDesc(const FRAMEBUFFER_DESC& _desc)
{
desc = _desc;
desc_data.render_pass12 = desc.render_pass->As<RenderPassD3D12>();
desc_data.attachments.resize(desc.num_attachments);
auto attachments_data = desc_data.attachments.data();
for (uint32_t i = 0; i < desc.num_attachments; i++)
(attachments_data[i] = desc.attachments[i])->AddRef();
desc.attachments = attachments_data;
}
void
B3D_APIENTRY FramebufferD3D12::Uninit()
{
for (auto& i : descriptors)
{
if (i.rtv.handle)
{
device->GetCPUDescriptorAllocator(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, B3D_DEFAULT_NODE_MASK).Free(i.rtv);
i.rtv = {};
}
}
hlp::SwapClear(descriptors);
hlp::SwapClear(attachment_operators);
desc = {};
desc_data.Uninit();
hlp::SafeRelease(device);
device12 = nullptr;
name.reset();
}
BMRESULT
B3D_APIENTRY FramebufferD3D12::Create(DeviceD3D12* _device, const FRAMEBUFFER_DESC& _desc, FramebufferD3D12** _dst)
{
util::Ptr<FramebufferD3D12> ptr;
ptr.Attach(B3DCreateImplementationClass(FramebufferD3D12));
B3D_RET_IF_FAILED(ptr->Init(_device, _desc));
*_dst = ptr.Detach();
return BMRESULT_SUCCEED;
}
void
B3D_APIENTRY FramebufferD3D12::AddRef()
{
++ref_count;
B3D_REFCOUNT_DEBUG(ref_count);
}
uint32_t
B3D_APIENTRY FramebufferD3D12::Release()
{
B3D_REFCOUNT_DEBUG(ref_count - 1);
auto count = --ref_count;
if (count == 0)
B3DDestroyImplementationClass(this);
return count;
}
uint32_t
B3D_APIENTRY FramebufferD3D12::GetRefCount() const
{
return ref_count;
}
const char*
B3D_APIENTRY FramebufferD3D12::GetName() const
{
return name ? name->c_str() : nullptr;
}
BMRESULT
B3D_APIENTRY FramebufferD3D12::SetName(const char* _name)
{
if (!util::IsEnabledDebug(this))
return BMRESULT_FAILED;
if (name && !_name)
name.reset();
else
name = B3DMakeUniqueArgs(util::NameableObjStr, _name);
return BMRESULT_SUCCEED;
}
IDevice*
B3D_APIENTRY FramebufferD3D12::GetDevice() const
{
return device;
}
const FRAMEBUFFER_DESC&
B3D_APIENTRY FramebufferD3D12::GetDesc() const
{
return desc;
}
const util::DyArray<FramebufferD3D12::SUBPASS_DESCRIPTOR_DATA>&
B3D_APIENTRY FramebufferD3D12::GetSubpassesDescriptorData() const
{
return descriptors;
}
const util::DyArray<util::UniquePtr<FramebufferD3D12::IAttachmentOperator>>&
B3D_APIENTRY FramebufferD3D12::GetAttachmentOperators() const
{
return attachment_operators;
}
#pragma region AttachmentOperatorRTV
FramebufferD3D12::AttachmentOperatorRTV::AttachmentOperatorRTV(RenderTargetViewD3D12* _rtv)
: rtv { _rtv }
, params (_rtv, OPERATOR_PARAMS::RTV)
, dr {}
{
}
void FramebufferD3D12::AttachmentOperatorRTV::Clear(ID3D12GraphicsCommandList* _list, const CLEAR_VALUE& _cv, D3D12_CLEAR_FLAGS _dsv_clear, const D3D12_RECT* _render_area)
{
_list->ClearRenderTargetView(rtv->GetCpuDescriptorAllocation()->handle, &_cv.color.float4.x
, _render_area ? 1 : 0, _render_area);
}
void FramebufferD3D12::AttachmentOperatorRTV::Discard(ID3D12GraphicsCommandList* _list, const D3D12_RECT* _render_area, D3D12_CLEAR_FLAGS _dsv_discard)
{
B3D_UNREFERENCED(_render_area, _dsv_discard);
for (uint32_t i = 0; i < params.range->array_size; i++)
{
dr.FirstSubresource = params.first_subres + (i * params.subres_array_step_rate);
dr.NumSubresources = 1;
_list->DiscardResource(params.resource12, &dr);
}
}
void FramebufferD3D12::AttachmentOperatorRTV::Resolve(ID3D12GraphicsCommandList1* _list, const D3D12_RECT* _render_area, const IAttachmentOperator* _resolve_src_view)
{
B3D_UNREFERENCED(_render_area);
auto&& src_params = _resolve_src_view->GetParams();
_list->ResolveSubresourceRegion(params.resource12, params.first_subres
, 0, 0
, src_params.resource12, src_params.first_subres
, nullptr
, params.format, D3D12_RESOLVE_MODE_AVERAGE);
}
#pragma endregion AttachmentOperatorRTV
#pragma region AttachmentOperatorDSV
FramebufferD3D12::AttachmentOperatorDSV::AttachmentOperatorDSV(DepthStencilViewD3D12* _dsv)
: dsv { _dsv }
, params (_dsv, OPERATOR_PARAMS::DSV)
, dr {}
, clear_flags {}
{
auto aspect = dsv->GetDesc().texture.subresource_range.offset.aspect;
if (aspect & TEXTURE_ASPECT_FLAG_DEPTH)
clear_flags |= D3D12_CLEAR_FLAG_DEPTH;
if (aspect & TEXTURE_ASPECT_FLAG_STENCIL)
clear_flags |= D3D12_CLEAR_FLAG_STENCIL;
}
void FramebufferD3D12::AttachmentOperatorDSV::Clear(ID3D12GraphicsCommandList* _list, const CLEAR_VALUE& _cv, D3D12_CLEAR_FLAGS _dsv_clear, const D3D12_RECT* _render_area)
{
_list->ClearDepthStencilView(dsv->GetCpuDescriptorAllocation()->handle
, _dsv_clear, _cv.depth_stencil.depth, SCAST<uint8_t>(_cv.depth_stencil.stencil)
, _render_area ? 1 : 0, _render_area);
}
void FramebufferD3D12::AttachmentOperatorDSV::Discard(ID3D12GraphicsCommandList* _list, const D3D12_RECT* _render_area, D3D12_CLEAR_FLAGS _dsv_discard)
{
dr.NumRects = _render_area ? 1 : 0;
dr.pRects = _render_area;
dr.NumSubresources = 1;
if (_dsv_discard & D3D12_CLEAR_FLAG_DEPTH)
{
for (uint32_t i = 0; i < params.range->array_size; i++)
{
dr.FirstSubresource = params.CalcSubresourceIndex(0, i, /*stencil*/false);
_list->DiscardResource(params.resource12, &dr);
}
}
if (_dsv_discard & D3D12_CLEAR_FLAG_STENCIL)
{
for (uint32_t i = 0; i < params.range->array_size; i++)
{
dr.FirstSubresource = params.CalcSubresourceIndex(0, i, /*stencil*/true);
_list->DiscardResource(params.resource12, &dr);
}
}
}
void FramebufferD3D12::AttachmentOperatorDSV::Resolve(ID3D12GraphicsCommandList1* _list, const D3D12_RECT* _render_area, const IAttachmentOperator* _resolve_src_view)
{
// NOTE: D3D12では、深度ステンシルの解決操作時に separate depth stencilを使用することができません。(D3D12_RENDER_PASSを考慮する場合にVulkanとの互換性が保てなくなります)。
auto&& src_params = _resolve_src_view->GetParams();
_list->ResolveSubresourceRegion(params.resource12, params.first_subres
, 0, 0
, src_params.resource12, src_params.first_subres
, nullptr
, params.format, D3D12_RESOLVE_MODE_AVERAGE);
}
#pragma endregion AttachmentOperatorDSV
#pragma region AttachmentOperatorSRV
FramebufferD3D12::AttachmentOperatorSRV::AttachmentOperatorSRV(ShaderResourceViewD3D12* _srv)
: srv { _srv }
, params(_srv, OPERATOR_PARAMS::SRV)
{
}
void FramebufferD3D12::AttachmentOperatorSRV::Clear(ID3D12GraphicsCommandList* _list, const CLEAR_VALUE& _cv, D3D12_CLEAR_FLAGS _dsv_clear, const D3D12_RECT* _render_area)
{
}
void FramebufferD3D12::AttachmentOperatorSRV::Discard(ID3D12GraphicsCommandList* _list, const D3D12_RECT* _render_area, D3D12_CLEAR_FLAGS _dsv_discard)
{
}
void FramebufferD3D12::AttachmentOperatorSRV::Resolve(ID3D12GraphicsCommandList1* _list, const D3D12_RECT* _render_area, const IAttachmentOperator* _resolve_src_view)
{
}
#pragma endregion AttachmentOperatorSRV
}// namespace buma3d
| 32.448179
| 171
| 0.686205
|
KawBuma
|
b644c6a5682030bbf31fd1744dff9cc03dcc2692
| 264
|
cpp
|
C++
|
src/GLEW/Init.cpp
|
mattfbacon/modern-opengl
|
81da9afde947b5268b94a60f2975758cfc14bc20
|
[
"WTFPL"
] | null | null | null |
src/GLEW/Init.cpp
|
mattfbacon/modern-opengl
|
81da9afde947b5268b94a60f2975758cfc14bc20
|
[
"WTFPL"
] | null | null | null |
src/GLEW/Init.cpp
|
mattfbacon/modern-opengl
|
81da9afde947b5268b94a60f2975758cfc14bc20
|
[
"WTFPL"
] | null | null | null |
#include <GL/glew.h>
#include "GLEW/Error.hpp"
#include "GLEW/Init.hpp"
namespace GLEW {
Init::Init() {
glewExperimental = true;
if (GLenum const err = glewInit(); err != GLEW_OK) {
throw GLEW::Error{ err };
}
}
Init::~Init() {
//
}
} // namespace GLEW
| 13.894737
| 53
| 0.621212
|
mattfbacon
|
b64cf8a6828c258bb24d5303c9c9c21846609748
| 2,911
|
cpp
|
C++
|
src/flame/process.cpp
|
ymwang/php-flame
|
5e0141f0d54fcb30b6e6c96a507141d714e7e6bc
|
[
"MIT"
] | null | null | null |
src/flame/process.cpp
|
ymwang/php-flame
|
5e0141f0d54fcb30b6e6c96a507141d714e7e6bc
|
[
"MIT"
] | null | null | null |
src/flame/process.cpp
|
ymwang/php-flame
|
5e0141f0d54fcb30b6e6c96a507141d714e7e6bc
|
[
"MIT"
] | null | null | null |
#include "process.h"
#include "worker.h"
#include "coroutine.h"
namespace flame {
std::deque<php::callable> quit_cb;
process_type_t process_type;
std::string process_name;
uint8_t process_count;
process* process_self;
uv_loop_t* loop;
process* process::prepare() {
// 确认当前是父进程还是子进程
char* worker = std::getenv("FLAME_CLUSTER_WORKER");
if(worker == nullptr) {
process_type = PROCESS_MASTER;
flame::loop = uv_default_loop();
}else{
process_type = PROCESS_WORKER;
flame::loop = new uv_loop_t;
uv_loop_init(flame::loop);
}
process_self = new process();
return process_self;
}
// static void init_work_cb(uv_work_t* req) {}
// static void init_done_cb(uv_work_t* req, int status) {
// delete req;
// }
// static void init_thread() {
// // 设置环境变量
// char edata[8];
// size_t esize = sizeof(edata);
// int r = uv_os_getenv("UV_THREADPOOL_SIZE", edata, &esize);
// uv_os_setenv("UV_THREADPOOL_SIZE", "1");
// uv_work_t* req = new uv_work_t;
// uv_queue_work(flame::loop, req, init_work_cb, init_done_cb);
// if(r) {
// uv_os_setenv("UV_THREADPOOL_SIZE", edata);
// }else{
// uv_os_unsetenv("UV_THREADPOOL_SIZE");
// }
// }
static void master_exit_cb(uv_signal_t* handle, int signum) {
process* proc = reinterpret_cast<process*>(handle->data);
proc->worker_stop();
uv_stop(flame::loop);
}
static void worker_exit_cb(uv_signal_t* handle, int signum) {
process* proc = reinterpret_cast<process*>(handle->data);
uv_stop(flame::loop);
}
void process::init() {
if(process_type == PROCESS_MASTER) {
uv_signal_init(flame::loop, &signal_);
uv_signal_start_oneshot(&signal_, master_exit_cb, SIGTERM);
}else{
uv_signal_init(flame::loop, &signal_);
uv_signal_start_oneshot(&signal_, worker_exit_cb, SIGTERM);
}
signal_.data = this;
uv_unref((uv_handle_t*)&signal_);
// init_thread();
}
void process::run() {
if(process_type == PROCESS_MASTER) {
php::callable("cli_set_process_title").invoke(process_name + " (flame-master)");
worker_start();
}else{
php::callable("cli_set_process_title").invoke(process_name + " (flame)");
}
uv_run(flame::loop, UV_RUN_DEFAULT);
if(!EG(exception)) {
while(!quit_cb.empty()) {
coroutine::start(quit_cb.back());
quit_cb.pop_back();
}
uv_run(flame::loop, UV_RUN_NOWAIT);
}
if(process_type == PROCESS_WORKER) {
delete flame::loop;
// 标记退出状态用于确认是否自动重启工作进程
exit(99);
}
}
void process::worker_start() {
for(int i=0;i<process_count;++i) {// 创建子进程
worker* w = new worker(this);
w->start();
workers_.insert(w);
}
}
void process::worker_stop() {
for(auto i=workers_.begin();i!=workers_.end();++i) {
(*i)->kill();
}
}
void process::on_worker_stop(worker* w) {
workers_.erase(w);
delete w;
}
}
| 28.262136
| 84
| 0.643765
|
ymwang
|
b6504cb2aa5b039f55e1244a60e971f72b2535d3
| 4,076
|
cpp
|
C++
|
instancedExample_startingPoint/src/ofApp.cpp
|
res15-opengl/res15-opengl
|
759350479209b1bffa0685084c1510b85dfddbee
|
[
"MIT"
] | 70
|
2015-04-11T11:02:37.000Z
|
2021-02-03T09:11:37.000Z
|
instancedExample_startingPoint/src/ofApp.cpp
|
res15-opengl/res15-opengl
|
759350479209b1bffa0685084c1510b85dfddbee
|
[
"MIT"
] | 1
|
2015-04-20T17:09:58.000Z
|
2015-04-20T17:09:58.000Z
|
instancedExample_startingPoint/src/ofApp.cpp
|
res15-opengl/res15-opengl
|
759350479209b1bffa0685084c1510b85dfddbee
|
[
"MIT"
] | 9
|
2015-04-14T12:52:53.000Z
|
2019-10-12T16:52:00.000Z
|
#include "ofApp.h"
// _____ ___
// / / / / instancedExample
// / __/ * / /__ (c) ponies & light, 2015. All rights reserved.
// /__/ /_____/ poniesandlight.co.uk
//
// Created by @tgfrerer on 10/03/2014.
//
// 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.
// Here's the general idea:
//
// 1. Draw a field of instanced boxes, 256 in x, and 256 in y direction
// 2. Push boxes up in y direction based on a height value sampled from the texture
// 2.a Scale boxes in y direction to create "skyscrapers" based on sampled value
// 3. Modulate height map texture sampling to create a "radar scanline" effect
// 4. Add some colour effects
//
// BONUS POINTS: use the camera live feed as your height map texture.
const int TILE_LENGTH = 256; ///< how many boxes in each x and z direction
const int NUM_INSTANCES = TILE_LENGTH * TILE_LENGTH; ///< total number of boxes
//--------------------------------------------------------------
void ofApp::setup(){
// step 1: load our height map image
ofDisableArbTex(); ///< we need normalised image coordinates
ofLoadImage(mTex1, "elevation2.png");
ofEnableArbTex();
// step 2: we will want to draw our geometry as instances
// therefore, we will use a vbo
mMshBox = ofBoxPrimitive(1, 1, 1).getMesh();
// we will also need a camera, so we can move around in the scene
mCam1.setupPerspective(false, 60, 0.1, 5000);
mCam1.setDistance(1000); // set default camera distance to 1000
mCam1.boom(400); // move camera up a little
mCam1.lookAt(ofVec3f(0)); // look at centre of the world
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(0.65); // pro app gray =)
ofSetColor(ofColor::white);
mCam1.begin();
{
mMshBox.draw();
}
mCam1.end();
// draw our frame rate
ofSetColor(ofColor::white);
ofDrawBitmapString(ofToString(ofGetFrameRate(),2,4,' '), ofGetWidth() - 4 * 8 - 50, 16 + 20);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 30.878788
| 94
| 0.569676
|
res15-opengl
|
b65946389552ab58ef44b0282dc7f12879721043
| 8,403
|
cpp
|
C++
|
kits/cpp/simple/GameAlgo.cpp
|
shahed95/Lux-solution
|
57c2fd0c0cc3b13bd167cefb0c947915faf64da0
|
[
"Apache-2.0"
] | null | null | null |
kits/cpp/simple/GameAlgo.cpp
|
shahed95/Lux-solution
|
57c2fd0c0cc3b13bd167cefb0c947915faf64da0
|
[
"Apache-2.0"
] | null | null | null |
kits/cpp/simple/GameAlgo.cpp
|
shahed95/Lux-solution
|
57c2fd0c0cc3b13bd167cefb0c947915faf64da0
|
[
"Apache-2.0"
] | null | null | null |
vector<vector<char>> GameAlgo::createSimpleMap(GameMap &gameMap, Player &player, Player &opponent)
{
vector<vector<char>> simpleMap;
for (int i = 0; i < gameMap.height; i++)
{
vector<char> temp(gameMap.width, '.');
simpleMap.push_back(temp);
}
for (int y = 0; y < gameMap.height; y++)
{
for (int x = 0; x < gameMap.width; x++)
{
Cell *cell = gameMap.getCell(x, y);
if (cell->hasResource())
simpleMap[x][y] = cell->getResourceType();
}
}
for (auto city : player.cities)
{
for (auto citytiles : city.second.citytiles)
simpleMap[citytiles.pos.x][citytiles.pos.y] = 'y';
}
for (auto city : opponent.cities)
{
for (auto citytiles : city.second.citytiles)
simpleMap[citytiles.pos.x][citytiles.pos.y] = 'z';
}
for (auto &unit : player.units)
{
if (!unit.canAct() && simpleMap[unit.pos.x][unit.pos.y] == '.')
simpleMap[unit.pos.x][unit.pos.y] = 'b';
}
for (auto &unit : opponent.units)
{
if (!unit.canAct() && simpleMap[unit.pos.x][unit.pos.y] == '.')
simpleMap[unit.pos.x][unit.pos.y] = 'b';
}
return simpleMap;
}
vector<vector<char>> GameAlgo::createUnitMap(GameMap &gameMap, Player &player, Player &opponent)
{
vector<vector<char>> unitMap;
for (int i = 0; i < gameMap.height; i++)
{
vector<char> temp(gameMap.width, '.');
unitMap.push_back(temp);
}
for(auto u: player.units)
{
unitMap[u.pos.x][u.pos.y] = 'm';
}
for(auto u: opponent.units)
{
unitMap[u.pos.x][u.pos.y] = 'o';
}
return unitMap;
}
char GameAlgo::getCell(int x, int y, vector<vector<char>> &simpleMap)
{
if (x < 0 || x >= simpleMap.size() || y < 0 || y >= simpleMap[0].size())
return outside;
return simpleMap[x][y];
}
vector<vector<int>> GameAlgo::bfsOnMap(vector<pair<int, int>> startingPos, vector<pair<int, int>> unreachablePos, vector<vector<char>> &simpleMap)
{
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
vector<vector<int>> dist;
for (int i = 0; i < simpleMap.size(); i++)
{
vector<int> temp(simpleMap[0].size(), unvisited);
dist.push_back(temp);
}
for (int i = 0; i < unreachablePos.size(); i++)
{
dist[unreachablePos[i].first][unreachablePos[i].second] = unreachable;
}
queue<pair<int, int>> q;
for (int i = 0; i < startingPos.size(); i++)
{
q.push(startingPos[i]);
dist[startingPos[i].first][startingPos[i].second] = 0;
}
while (!q.empty())
{
auto curr = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = curr.first + dx[i];
int y = curr.second + dy[i];
if (getCell(x, y, simpleMap) == outside)
continue;
if (dist[x][y] == unvisited)
{
dist[x][y] = dist[curr.first][curr.second] + 1;
q.push({x, y});
}
}
}
return dist;
}
vector<vector<int>> GameAlgo::createDistanceArray(string sources, string blocks, vector<vector<char>> &simpleMap)
{
return bfsOnMap(getAllposition(sources, simpleMap), getAllposition(blocks, simpleMap), simpleMap);
}
vector<pair<int, int>> GameAlgo::getAllposition(string types, vector<vector<char>> &simpleMap)
{
vector<pair<int, int>> v;
for (int i = 0; i < simpleMap.size(); i++)
{
for (int j = 0; j < simpleMap[i].size(); j++)
{
if (types.find(simpleMap[i][j]) != std::string::npos)
{
v.push_back({i, j});
}
}
}
return v;
}
DIRECTIONS GameAlgo::moveDirection(Unit *unit, vector<vector<int>> &distArray, vector<vector<int>> &secondDistArray, vector<vector<char>> &simpleMap)
{
int DX[] = {0, 0, 0, -1, 1};
int DY[] = {0, 1, -1, 0, 0};
DIRECTIONS D[] = {CENTER, SOUTH, NORTH, WEST, EAST};
int closestDist = unvisited + 10;
DIRECTIONS closestDirection = CENTER;
int closestX = 0, closestY = 0;
vector<int> options;
for (int i = 0; i < 5; i++)
options.push_back(i);
random_shuffle(options.begin(), options.end());
for (auto i : options)
{
int goX = unit->pos.x + DX[i];
int goY = unit->pos.y + DY[i];
char goCellvalue = getCell(goX, goY, simpleMap);
if (goCellvalue != 'z' && goCellvalue != 'b' && goCellvalue != '*')
{
if (distArray[goX][goY] < closestDist)
{
closestDist = distArray[goX][goY];
closestDirection = D[i];
closestX = goX;
closestY = goY;
}
else if (distArray[goX][goY] == closestDist && secondDistArray[goX][goY] < secondDistArray[closestX][closestY])
{
closestDist = distArray[goX][goY];
closestDirection = D[i];
closestX = goX;
closestY = goY;
}
}
}
return closestDirection;
}
pair<int, int> GameAlgo::getPosition(int x, int y, DIRECTIONS d)
{
int DX[] = {0, 0, 0, -1, 1};
int DY[] = {0, 1, -1, 0, 0};
DIRECTIONS D[] = {CENTER, SOUTH, NORTH, WEST, EAST};
for (int i = 0; i < 5; i++)
{
if (D[i] == d)
{
return {x + DX[i], y + DY[i]};
}
}
}
vector<vector<int>> GameAlgo::makeDistfromCities(vector<vector<char>> &simpleMap, bool isOpponent)
{
if (isOpponent) return createDistanceArray("z", "yb", simpleMap);
return createDistanceArray("y", "zb", simpleMap);
}
vector<vector<int>> GameAlgo::makeDistfromDots(vector<vector<char>> &simpleMap)
{
return createDistanceArray(".", "yzb", simpleMap);
}
vector<vector<int>> GameAlgo::makeDistfromGoodDots(vector<vector<char>> &simpleMap)
{
vector<pair<int, int>> pos;
for (int i = 1; i < simpleMap.size() - 1; i++)
{
for (int j = 1; j < simpleMap.size() - 1; j++)
{
if (simpleMap[i][j] != '.')
continue;
map<char, int> cnt;
pair<int, int> dir[] = {{0, 0}, {0, 1}, {0, -1}, {-1, 0}, {1, 0}};
for (auto d : dir)
cnt[simpleMap[d.first + i][d.second + j]]++;
if (cnt['w'] + cnt['c'] + cnt['u'] >= 2)
{
pos.push_back({i, j});
}
else if (cnt['y'] >= 2)
{
pos.push_back({i, j});
}
}
}
return bfsOnMap(pos, getAllposition("yzb", simpleMap), simpleMap);
}
vector<vector<int>> GameAlgo::makeDistfromResource(vector<vector<char>> &simpleMap, string withResource, Player &player, Player &opponent)
{
auto tempMap = simpleMap;
auto distFromOpponent = makeDistfromOpponent(simpleMap, opponent);
auto distFromMyUnit = makeDistfromPlayer(simpleMap, player);
for (int i = 1; i < tempMap.size() - 1; i++)
{
for (int j = 1; j < tempMap.size() - 1; j++)
{
if (distFromOpponent[i][j] < 10 && player.cities.size() >= 2)
continue;
if (withResource.find(tempMap[i][j]) == std::string::npos)
continue;
int citycells = 0;
map<char, int> cnt;
pair<int, int> dir[] = {{0, 0}, {0, 1}, {0, -1}, {-1, 0}, {1, 0}};
for (auto d : dir)
cnt[tempMap[d.first + i][d.second + j]]++;
if (cnt['y'] >= 2)
{
for (auto u : dir)
{
if (tempMap[u.first + i][u.second + j] != 'y')
tempMap[u.first + i][u.second + j] = 'b';
}
}
}
}
return createDistanceArray(withResource, "zyb", tempMap);
}
vector<vector<int>> GameAlgo::makeDistfromPlayer(vector<vector<char>> &simpleMap, Player &player)
{
auto playerMap = simpleMap;
for (auto u : player.units)
playerMap[u.pos.x][u.pos.y] = 'm';
return createDistanceArray("m", "zb", playerMap);
}
vector<vector<int>> GameAlgo::makeDistfromOpponent(vector<vector<char>> &simpleMap, Player &opponent)
{
auto opponentMap = simpleMap;
for (auto u : opponent.units)
opponentMap[u.pos.x][u.pos.y] = 'o';
return createDistanceArray("o", "yb", opponentMap);
}
| 28.01
| 149
| 0.521956
|
shahed95
|
b659f8e3c3ac9d8b477732170e52c996b0813ca8
| 17,919
|
cpp
|
C++
|
coreseek-3.2.14/csft-3.2.14/src/py_helper.cpp
|
zbooa/sphinx-php7-ext
|
89c6900ebdbd1c73469d428b25ad360c3b57f29c
|
[
"PHP-3.01"
] | 1
|
2020-08-17T09:04:53.000Z
|
2020-08-17T09:04:53.000Z
|
coreseek-3.2.14/csft-3.2.14/src/py_helper.cpp
|
zbooa/sphinx-php7-ext
|
89c6900ebdbd1c73469d428b25ad360c3b57f29c
|
[
"PHP-3.01"
] | null | null | null |
coreseek-3.2.14/csft-3.2.14/src/py_helper.cpp
|
zbooa/sphinx-php7-ext
|
89c6900ebdbd1c73469d428b25ad360c3b57f29c
|
[
"PHP-3.01"
] | 2
|
2020-08-17T09:04:56.000Z
|
2022-01-14T06:37:54.000Z
|
#ifdef _WIN32
#pragma warning(disable:4996)
#endif
#include "sphinx.h"
#include "sphinxutils.h"
#include "sphinx_internal.h"
//#include "sphinxsearch.h"
#include "py_layer.h"
#include "sphinxquery.h"
#include "py_helper.h"
#include "py_source.h"
#if USE_PYTHON
#define RET_PYNONE { Py_INCREF(Py_None); return Py_None; }
PyObject * PyLowercaser_Helper_ToLower(PyObject *, PyObject* args) ;
PyObject * PyLowercaser_Helper_GetWordID(PyObject *, PyObject* args) ;
int Lowercaser_Helper::ToLower(int iCode)
{
if(m_lower) {
return m_lower->ToLower(iCode);
}
return 0;
}
/*
static void PyDelLowercaser_Helper(void *ptr)
{
Lowercaser_Helper * oldnum = static_cast<Lowercaser_Helper *>(ptr);
delete oldnum;
return;
}
*/
static PyMethodDef Helper_methods[] = {
//{"Numbers", Example_new_Numbers, METH_VARARGS},
{"toLower", PyLowercaser_Helper_ToLower, METH_VARARGS},
{"wordID", PyLowercaser_Helper_GetWordID, METH_VARARGS},
{NULL, NULL}
};
typedef struct {
PyObject_HEAD
/* Type-specific fields go here. */
CSphLowercaser* m_Lower;
} csfHelper_ToLowerObject;
static PyTypeObject csfHelper_ToLowerType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"csfHelper.ToLower", /*tp_name*/
sizeof(csfHelper_ToLowerObject), /*tp_basicsize*/
0, /*tp_itemsize*/
0, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"ToLower Helper", /* tp_doc */
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
Helper_methods, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
};
//PyObject *PyNewLowercaser_Helper(PyObject *, PyObject* args)
PyObject *PyNewLowercaser_Helper(CSphLowercaser* aLower)
{
if(!aLower) return NULL;
csfHelper_ToLowerObject *self;
self = (csfHelper_ToLowerObject *)PyType_GenericNew(&csfHelper_ToLowerType, NULL, NULL);
self->m_Lower = aLower;
return (PyObject*)self;
}
PyObject * PyLowercaser_Helper_ToLower(PyObject * self, PyObject* args)
{
int arg1;
int ok = PyArg_ParseTuple( args, "i", &arg1);
if(!ok) {
if(PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
RET_PYNONE;
}
csfHelper_ToLowerObject *self2 = (csfHelper_ToLowerObject *)self;
//PyObject* instance = PyObject_GetAttrString(self, "__c_lower");
if(self2) {
int result = self2->m_Lower->ToLower(arg1);
return Py_BuildValue("i",result);
}
return Py_BuildValue("i",0);
}
PyObject * PyLowercaser_Helper_GetWordID(PyObject *, PyObject* args)
{
char* key = NULL;
int ok = PyArg_ParseTuple( args, "s", &key ); //not inc the value refer
//FIXME:Should every PyArg_ParseTuple deal about PyErr_Occurred?
if(!ok) {
if(PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
RET_PYNONE;
}
if(!key) RET_PYNONE;
SphWordID_t wordid = sphCRCWord<SphWordID_t> ((const BYTE*)key );
#if USE_64BIT
return PyLong_FromUnsignedLongLong(wordid); //K = unsigned long long
#else
return PyLong_FromUnsignedLong(wordid); //k = unsigned long
#endif
}
//////////////////////////////////////////////////////////////////////////
typedef struct {
PyObject_HEAD
/* Type-specific fields go here. */
CSphSource_Python* m_Document; //only PySource is supported for the leak support of setField in other documents
} csfHelper_DocumentObject;
PyObject * PyDocument_Helper_SetAttr(PyObject * self, PyObject* args) {
char* key = NULL;
PyObject* pV = NULL;
int ok = PyArg_ParseTuple( args, "sO", &key, &pV); //not inc the value refer
if(!ok) return NULL;
csfHelper_DocumentObject *self2 = (csfHelper_DocumentObject *)self;
if(self2) {
int nRet = self2->m_Document->SetAttr(key, pV);
return Py_BuildValue("i",nRet);
}
return NULL;
}
PyObject * PyDocument_Helper_GetAttr(PyObject * self, PyObject* args) {
char* key = NULL;
int ok = PyArg_ParseTuple( args, "s", &key);
if(!ok) return NULL;
csfHelper_DocumentObject *self2 = (csfHelper_DocumentObject *)self;
if(self2) {
return self2->m_Document->GetAttr(key);
}
return NULL;
}
static PyMethodDef PyDocument_Helper_methods[] = {
//{"Numbers", Example_new_Numbers, METH_VARARGS},
{"SetAttr", PyDocument_Helper_SetAttr, METH_VARARGS},
{"GetAttr", PyDocument_Helper_GetAttr, METH_VARARGS},
{NULL, NULL}
};
static PyTypeObject csfHelper_DocumentType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"csfHelper.Document", /*tp_name*/
sizeof(csfHelper_DocumentObject), /*tp_basicsize*/
0, /*tp_itemsize*/
0, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"Document Helper", /* tp_doc */
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
PyDocument_Helper_methods, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
};
PyObject *PyNewDocument_Helper( CSphSource* pSource)
{
if(!pSource) return NULL;
CSphSource_Python* pPySource = dynamic_cast<CSphSource_Python*>(pSource);
if(!pPySource) return NULL;
csfHelper_DocumentObject *self;
self = (csfHelper_DocumentObject *)PyType_GenericNew(&csfHelper_DocumentType, NULL, NULL);
self->m_Document = pPySource;
return (PyObject*)self;
}
PyObject * PyHit_Push(PyObject * pSelf, PyObject* args, PyObject* kwargs);
PyObject * PyHit_PushWord(PyObject * pSelf, PyObject* args, PyObject* kwargs);
PyObject * PyHit_GetWordID(PyObject * pSelf, PyObject* args, PyObject* kwargs);
PyObject * PyHit_GetFieldName(PyObject *, PyObject* args);
PyObject * PyHit_GetFieldID(PyObject *, PyObject* args);
PyObject * PyHit_GetCurPos(PyObject *, PyObject* args);
PyObject * PyHit_GetCurPhraseID(PyObject *, PyObject* args);
static PyMethodDef HitCollector_methods[] = {
{"getFieldName", PyHit_GetFieldName, METH_VARARGS},
{"getFieldID", PyHit_GetFieldID, METH_VARARGS},
{"getCurrentPos", PyHit_GetCurPos, METH_VARARGS},
{"getCurrentPhraseID", PyHit_GetCurPhraseID, METH_VARARGS},
{"push", (PyCFunction)PyHit_Push, METH_VARARGS|METH_KEYWORDS},
{"pushWord", (PyCFunction)PyHit_PushWord, METH_VARARGS|METH_KEYWORDS},
{"wordID", (PyCFunction)PyHit_GetWordID, METH_VARARGS|METH_KEYWORDS},
{NULL, NULL}
};
typedef struct {
PyObject_HEAD
/* Type-specific fields go here. */
CSphSource* m_pSource;
CSphSchema* m_tSchema;
CSphString* m_FieldName;
int iPos;
int iPhrase;
int iField;
} csfHelper_HitCollectorObject;
static void PyHit_dealloc(csfHelper_HitCollectorObject* self);
static PyObject * PyHit_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int PyHit_clear(csfHelper_HitCollectorObject *self);
static int PyHit_traverse(csfHelper_HitCollectorObject *self, visitproc visit, void *arg);
static PyTypeObject csfHelper_HitCollectorType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"csfHelper.HitCollector", /*tp_name*/
sizeof(csfHelper_HitCollectorObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PyHit_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, // | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
"Hits Collector", /* tp_doc */
(traverseproc)PyHit_traverse, /*tp_traverse*/
(inquiry)PyHit_clear, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
HitCollector_methods, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, //(newfunc)PyHit_new, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
};
//////////////////////////////////////////////////////////////////////////
static PyObject *
PyHit_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
csfHelper_HitCollectorObject *x;
x = (csfHelper_HitCollectorObject *)PyType_GenericNew(type, args, kwds);
if (x == NULL)
return NULL;
//x->p_status = UNSAVED;
//x->p_serial = Integer_FromLong(0L);
//if (x->p_serial == NULL)
// return NULL;
//x->p_connection = Py_None;
//Py_INCREF(x->p_connection);
//x->p_oid = Py_None;
//Py_INCREF(x->p_oid);
return (PyObject *)x;
}
void AddHit(csfHelper_HitCollectorObject *self, SphWordID_t iWordID, int iPos, int iPhrase)
{
// copy from AddHitFor.
// TODO: append iPhrase here?
if ( !iWordID )
return;
CSphWordHit & tHit = self->m_pSource->m_dHits.Add();
tHit.m_iDocID = self->m_pSource->m_tDocInfo.m_iDocID;
tHit.m_iWordID = iWordID;
tHit.m_iWordPos = iPos;
}
// static void PyHit_dealloc(csfHelper_HitCollectorObject* self)
static void
PyHit_dealloc(csfHelper_HitCollectorObject *self)
{
/*
PyObject_GC_UnTrack(self);
Py_TRASHCAN_SAFE_BEGIN(self);
//Py_XDECREF(self->p_connection);
//Py_XDECREF(self->p_oid);
//Py_XDECREF(self->p_serial);
PyObject_GC_Del(self);
Py_TRASHCAN_SAFE_END(self);
*/
if(self->m_FieldName)
{
delete self->m_FieldName;
self->m_FieldName = NULL;
}
if(self->m_tSchema)
{
delete self->m_tSchema;
self->m_tSchema = NULL;
}
// i've no source.
self->ob_type->tp_free((PyObject *)self);
}
static int
PyHit_traverse(csfHelper_HitCollectorObject *self, visitproc visit, void *arg)
{
//Py_VISIT(self->p_connection);
//Py_VISIT(self->p_oid);
//Py_VISIT(self->p_serial);
return 0;
}
static int
PyHit_clear(csfHelper_HitCollectorObject *self)
{
//Py_CLEAR(self->p_connection);
//Py_CLEAR(self->p_oid);
//Py_CLEAR(self->p_serial);
return 0;
}
PyObject * PyHit_Push(PyObject * pSelf, PyObject* args, PyObject* kwargs)
{
//int iPos = HIT_PACK ( iField, iStartPos );
csfHelper_HitCollectorObject *self = (csfHelper_HitCollectorObject *)pSelf;
static char *kwlist[] = {"wordid", "pos", "phrase", "fieldindex", NULL};
SphWordID_t iWord;
int iPos = -1;
int iPhrase = -1;
int iField = -1;
#if USE_64BIT
int ok = PyArg_ParseTupleAndKeywords( args, kwargs, "l|iii", kwlist, &iWord,
#else
int ok = PyArg_ParseTupleAndKeywords( args, kwargs, "i|iii", kwlist, &iWord,
#endif
&iPos , &iPhrase, &iField ); //not inc the value refer
if(!ok) {
if(PyErr_Occurred()) {
PyErr_Print();
//PyErr_Clear();
}
return NULL;
}
if(iPos < 1 ) iPos = -1; // 0 and < is invalid.
if(iPhrase <1) iPhrase = -1;
// fast setting
if(!iWord) {
if(iPos != -1)
self->iPos = iPos;
if(iPhrase == -1)
self->iPhrase = iPhrase; //refresh iPos
RET_PYNONE;
}
// push hit
if(iPos == -1)
iPos = self->iPos;
else
{
if(iField == -1)
self->iPos = iPos; //refresh iPos
}
// no more than 24, if greater than 24, just leave field as current.
if(iField > 23 || iField < 0)
iField = -1;
if(iPhrase == -1)
iPhrase = self->iPhrase;
else
{
if(iField == -1)
self->iPhrase = iPhrase; //refresh iPos
}
if(iField == -1)
iField = self->iField; //NO, NO, u can NOT change field via a filled parameters' pushWord call...
{
iPos = HIT_PACK(iField, iPos);
AddHit(self, iWord, iPos, iPhrase);
self->iPos++ ;
}
RET_PYNONE;
}
PyObject * PyHit_PushWord(PyObject * pSelf, PyObject* args, PyObject* kwargs)
{
/*
= You can change the iPos & iPhrase setting without add a real hit by push a Empty word("").
@param:
- pos:
- phrase:
*/
csfHelper_HitCollectorObject *self = (csfHelper_HitCollectorObject *)pSelf;
static char *kwlist[] = {"word", "pos", "phrase", "fieldindex", NULL};
const char* sWord = NULL;
int iPos = -1;
int iPhrase = -1;
int iField = -1;
int ok = PyArg_ParseTupleAndKeywords( args, kwargs, "z|iii", kwlist, &sWord,
&iPos , &iPhrase, &iField ); //not inc the value refer
if(!ok) {
if(PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
return NULL;
}
if(iPos < 1 ) iPos = -1; // 0 and < is invalid.
if(iPhrase <1) iPhrase = -1;
//fast setting
if(!sWord) {
if(iPos != -1)
self->iPos = iPos;
if(iPhrase == -1)
self->iPhrase = iPhrase; //refresh iPos
RET_PYNONE;
}
if(iPos == -1)
iPos = self->iPos;
else
{
if(iField == -1)
self->iPos = iPos; //refresh iPos
}
// no more than 24, if greater than 24, just leave field as current.
if(iField > 23 || iField < 0)
iField = -1;
if(iPhrase == -1)
iPhrase = self->iPhrase;
else
{
if(iField == -1)
self->iPhrase = iPhrase; //refresh iPos
}
if(iField == -1)
iField = self->iField; //NO, NO, u can NOT change field via a filled parameters' pushWord call...
{
CSphSource_Python* pPySource = dynamic_cast<CSphSource_Python*>(self->m_pSource);
if(pPySource){
CSphDict* pDict = pPySource->GetDict();
SphWordID_t iWord = pDict->GetWordID ((BYTE*) sWord );
iPos = HIT_PACK(iField, iPos);
AddHit(self, iWord, iPos, iPhrase);
self->iPos++ ;
}
}
RET_PYNONE;
}
PyObject * PyHit_GetFieldID(PyObject * pSelf, PyObject* args)
{
csfHelper_HitCollectorObject *self = (csfHelper_HitCollectorObject *)pSelf;
const char* key = NULL;
int ok = PyArg_ParseTuple( args, "s", &key);
if(!ok) {
if(PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
return NULL;
}
int idx = self->m_tSchema->GetFieldIndex(key);
return PyInt_FromLong(idx);
}
PyObject * PyHit_GetWordID(PyObject * pSelf, PyObject* args, PyObject* kwargs)
{
/*
@param:
- Exact:
- Steam:
- ID with Marker:
*/
csfHelper_HitCollectorObject *self = (csfHelper_HitCollectorObject *)pSelf;
static char *kwlist[] = {"word", "exact", "steam", "idmarker", NULL };
char* sWord = NULL;
unsigned char bExact = 1;
unsigned char bSteam = 0;
unsigned char bIdMarker = 0;
int ok = PyArg_ParseTupleAndKeywords( args, kwargs, "s|BBB", kwlist, &sWord,
&bExact , &bSteam, &bIdMarker ); //not inc the value refer
if(!ok) {
if(PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
return NULL;
}
{
CSphSource_Python* pPySource = dynamic_cast<CSphSource_Python*>(self->m_pSource);
CSphDict* pDict = pPySource->GetDict();
SphWordID_t iWord = 0;
BYTE sBuf [ 16+3*SPH_MAX_WORD_LEN ];
int iBytes = strlen ( (const char*)sWord );
if ( bExact )
{
int iBytes = strlen ( (const char*)sWord );
memcpy ( sBuf + 1, sWord, iBytes );
sBuf[0] = MAGIC_WORD_HEAD_NONSTEMMED;
sBuf[iBytes+1] = '\0';
iWord = pDict->GetWordIDNonStemmed ( sBuf );
} else
if (bIdMarker)
{
memcpy ( sBuf + 1, sWord, iBytes );
sBuf[0] = MAGIC_WORD_HEAD;
sBuf[iBytes+1] = '\0';
iWord = pDict->GetWordIDWithMarkers ( sBuf ) ;
}
else
{
iWord = pDict->GetWordID ((BYTE*) sWord );
}
if(!iWord)
RET_PYNONE;
#if USE_64BIT
return PyLong_FromLongLong(iWord);
#else
return PyLong_FromLong(iWord);
#endif
}
}
PyObject * PyHit_GetFieldName(PyObject * pSelf, PyObject* )
{
csfHelper_HitCollectorObject *self = (csfHelper_HitCollectorObject *)pSelf;
return PyString_FromString(self->m_FieldName->cstr());
}
PyObject * PyHit_GetCurPos(PyObject * pSelf, PyObject* )
{
csfHelper_HitCollectorObject *self = (csfHelper_HitCollectorObject *)pSelf;
return PyInt_FromLong(self->iPos);
}
PyObject * PyHit_GetCurPhraseID(PyObject * pSelf, PyObject* )
{
csfHelper_HitCollectorObject *self = (csfHelper_HitCollectorObject *)pSelf;
return PyInt_FromLong(self->iPhrase);
}
//////////////////////////////////////////////////////////////////////////
PyObject *PyNewHitCollector(CSphSource* pSource, CSphString & aFieldName, int iField)
{
if(!pSource) RET_PYNONE;
CSphSource_Python* pPySource = dynamic_cast<CSphSource_Python*>(pSource);
if(!pPySource) RET_PYNONE;
csfHelper_HitCollectorObject *self;
self = (csfHelper_HitCollectorObject *)PyType_GenericNew(&csfHelper_HitCollectorType, NULL, NULL);
//self = PyObject_New(csfHelper_HitCollectorObject, &csfHelper_HitCollectorType);
self->m_tSchema = new CSphSchema();
self->m_FieldName = new CSphString();
self->iPhrase = 1;
self->iPos = 1; //all pos started with 1.
*(self->m_FieldName) = aFieldName;
self->m_pSource = pPySource;
CSphString sError;
pPySource->UpdateSchema(self->m_tSchema, sError);
self->iField = iField;
return (PyObject*)self;
}
PyMODINIT_FUNC initCsfHelper (void)
{
int nRet = 0;
/*
csfHelper_ToLowerType.tp_new = PyType_GenericNew;
if (PyType_Ready(&csfHelper_ToLowerType) < 0)
return;
csfHelper_DocumentType.tp_new = PyType_GenericNew;
if (PyType_Ready(&csfHelper_DocumentType) < 0)
return;
*/
csfHelper_HitCollectorType.tp_new = PyType_GenericNew;
if (PyType_Ready(&csfHelper_HitCollectorType) < 0)
return;
Py_INCREF(&csfHelper_HitCollectorType);
PyObject* m = Py_InitModule("csfHelper", Helper_methods);
//nRet = PyModule_AddObject(m, "ToLower", (PyObject *)&csfHelper_ToLowerType);
//nRet = PyModule_AddObject(m, "Document", (PyObject *)&csfHelper_DocumentType);
nRet = PyModule_AddObject(m, "HitCollector", (PyObject *)&csfHelper_HitCollectorType);
}
#endif //USE_PYTHON
| 24.052349
| 113
| 0.67967
|
zbooa
|
b65a57887584dd455866f07ebc39bdf20c55b4cc
| 599
|
cpp
|
C++
|
vox.render/timer.cpp
|
SummerTree/DigitalVox4
|
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
|
[
"MIT"
] | 8
|
2022-02-15T12:54:57.000Z
|
2022-03-30T16:35:58.000Z
|
vox.render/timer.cpp
|
yangfengzzz/DigitalArche
|
da6770edd4556a920b3f7298f38176107caf7e3a
|
[
"MIT"
] | null | null | null |
vox.render/timer.cpp
|
yangfengzzz/DigitalArche
|
da6770edd4556a920b3f7298f38176107caf7e3a
|
[
"MIT"
] | 1
|
2022-01-20T05:53:59.000Z
|
2022-01-20T05:53:59.000Z
|
// Copyright (c) 2022 Feng Yang
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "timer.h"
namespace vox {
Timer::Timer() :
_startTime{Clock::now()},
_previousTick{Clock::now()} {
}
void Timer::start() {
if (!_running) {
_running = true;
_startTime = Clock::now();
}
}
void Timer::lap() {
_lapping = true;
_lapTime = Clock::now();
}
bool Timer::isRunning() const {
return _running;
}
} // namespace vox
| 18.71875
| 73
| 0.63606
|
SummerTree
|
b65ee2fc45fda2d1db13bb1fc2cbedc0c9988464
| 2,407
|
cpp
|
C++
|
example.cpp
|
jgressmann/pokemon
|
36ecc55d7cb0838155fb112c1d74cdad286b67c4
|
[
"MIT"
] | 9
|
2015-09-23T13:28:46.000Z
|
2018-08-11T03:09:04.000Z
|
example.cpp
|
jgressmann/pokemon
|
36ecc55d7cb0838155fb112c1d74cdad286b67c4
|
[
"MIT"
] | 3
|
2015-09-26T01:05:12.000Z
|
2016-01-13T15:05:10.000Z
|
example.cpp
|
jgressmann/pokemon
|
36ecc55d7cb0838155fb112c1d74cdad286b67c4
|
[
"MIT"
] | 5
|
2015-09-28T03:09:24.000Z
|
2021-05-21T18:09:16.000Z
|
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#if defined(_WIN32) || defined(_WIN64)
# include <windows.h>
# define sleep(x) Sleep((DWORD)(x*1000))
#else
# include <unistd.h>
#endif
#include "pokemon.h"
using namespace std;
// Sleep function exported to Lua
static
int
Zzzzz(lua_State* L) {
(void)luaD_push_location(L, __FILE__, __LINE__);
sleep(lua_tointeger(L, 1));
(void)luaD_pop_location(L);
return 0;
}
static int s_Line = -1;
static
int
ResolveLocation( lua_State* L,
const lua_Debug* dbg,
const char** filePath,
int* line) {
assert(L);
assert(dbg);
assert(filePath);
assert(line);
if (dbg->source && strcmp(dbg->source, "EXAMPLE") == 0) {
*filePath = __FILE__;
*line = s_Line;
return PKMN_LC_RESOLVED;
}
return PKMN_LC_FALLBACK;
}
int
main(int argc, char** argv) {
// set up pokemon
int error = luaD_setup(&argc, argv);
if (error) {
fprintf(stderr, "Pokemon setup error %d\n", error);
return error;
}
// set location resolve callback
(void)luaD_set_location_callback(ResolveLocation);
// create Lua state and register packages
#if LUA_VERSION_NUM >= 502
lua_State* L = luaL_newstate();
#else
lua_State* L = lua_open();
#endif
// setup default libraries
luaL_openlibs(L);
// register a global C function with name 'sleep'
lua_pushcfunction(L, Zzzzz);
lua_setglobal(L, "sleep");
// register Lua state with the debugger
(void)luaD_register(L);
// register inline Lua code with the debugger
const char LuaCode[] = "dofile(\"" POKEMON_LUA_SOURCE_DIR "/example.lua\")"; s_Line = __LINE__ + 1;
// load inline code
error = luaL_loadbuffer(L, LuaCode, sizeof(LuaCode) - 1, "EXAMPLE");
if (error) {
fprintf(stderr, "luaL_loadbuffer error %d\n", error);
} else {
error = lua_pcall(L, 0, LUA_MULTRET, 0);
if (error) {
const char* errorMessage = lua_tostring(L, 1);
fprintf(stderr, "%s\n", errorMessage);
}
}
// unregister Lua state from the debugger
(void)luaD_unregister(L);
// destroy Lua state
lua_close(L);
// tear down pokemon
luaD_teardown();
return error;
}
| 20.930435
| 104
| 0.616951
|
jgressmann
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.