blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
67879890f45457ea227b60462a4b84e55b8cff63 | b5d0c75ff267f8bd4fc975cc4a1895690def153d | /lib/include/pglue/pglue.h | 1016b4b52953dfaf5ca9032c55e59226e2b26a10 | [] | no_license | littlemole/moe | f234c4b22ca3dcf41ea9a209704b3ab9ae1d94f5 | beeaf81152b345b27ad480ff7e0cd819a535f193 | refs/heads/master | 2022-12-02T05:32:03.885314 | 2020-11-11T20:37:14 | 2020-11-11T20:37:14 | 11,985,545 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 61,639 | h | #ifndef _MOL_DEF_GUARD_DEFINE_PERL_GLUE_HELPER_DEF_
#define _MOL_DEF_GUARD_DEFINE_PERL_GLUE_HELPER_DEF_
#include <map>
#include <list>
#include <vector>
#include <string>
#include <sstream>
#ifdef __cplusplus
extern "C" {
#endif
#include <EXTERN.h>
#include <perl.h>
#include "XSUB.h"
#ifdef __cplusplus
}
#endif
namespace PerlGlue {
//////////////////////////////////////////////////////////////////
//
// perlglue c++ template lib - the mole 2007
//
// glue for embedding the Perl interpreter into C++ programs
// and injecting custom c++ objects into the script engine.
// intended to be used for making application automation
// possible by using Perl as the end user scripting language
// and exposing a custom object model and providing a bridge
// between (User Scripting) Perl and C++ (Application) code
//
// example code:
/*
#include "pglue.h"
class Test
{
public:
// mark class as exposed to Perl
perl_exposed(Test);
// mark method as exported to Perl
perl_export(test)
int terror( const std::string& s, double d )
{
std::cout << s << " : " << d << std::endl;
return 42;
}
};
int main(int argc, char **argv, char **env)
{
PerlInit pi(argc, argv, env);
Test t;
Perl perl;
perl.addClassDef<Test>();
// use this to run and parse a file:
//perl.parse( argc, argv, env );
//perl.run();
// or feed the interpreter manually:
perl.embed();
// set a perl variable $val to 42:
//perl.set_val(42,"val");
// inject C++ Test object into Perl engine, named $test:
perl.inject(&t, "test");
// or construct from perl. only empty constructors
// (no parameters) allow in this case:
//perl.eval( "$t = new Test;" );
// eval arbitary perl code:
perl.eval( "print $test->test("huhu",3.12);" );
}
*/
//////////////////////////////////////////////////////////////////
//
// restriction for exposed C++ classes:
// - must have default constructor. from perl, only this is callable
// - exposed methods may not have more than 8 parameters
// - return values are supposed to be simple ints, doubles, char*s
// or std::strings
//
//////////////////////////////////////////////////////////////////
//
// perl to c++ type mappings for function signatures:
//
// Perl C++
// skalar int,double, (const) char*, const std::string&
// skalar ref int&,double&, (const)char*&, std::string&
//
//use the ref type if you want to modify parameters using [in/out]
//behaviour.
//
// array support:
//
// Perl C++
// @array std::vector< int|double|char*|std::string >&
// \@array-ref std::vector< int|double|char*|std::string >*
//
// hash support:
//
// Perl C++
// %hash std::map<std::string, int|double|char*|std::string >&
// \%hash-ref std::map<std::string, int|double|char*|std::string >*
//
// passing c++ objects back and forth to/from perl:
//
// Perl C++
// $object T*
// \$object-ref T**/T*&
//
// declaring the type of the C++ object as T** or T*& gives you
// pass-by-value [in/out] behaviour. Use it if you want to
// modify (ie replace) the passed object
//
// for lower level access, define your functions parameters of type SV*
// that will give you Perls native C Scalar-Value-Representation to play
// with.
//
// for even lower access, define your functions static with this signature:
//
// static void testLowLevel(PerlInterpreter*,CV* cv);
//
// now you have a static global function like in XSUB programming,
// you now can define dXSARGS; and access the Stach via ST(x).
// note the first param will be the this pointer, which you have
// to extract yourself, you are now in a global function!
//
//////////////////////////////////////////////////////////////////
// compilation:
// g++ yourapp.cpp `perl -MExtUtils::Embed -e ccopts -e ldopts`
//
//
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// dereference an SV*
//////////////////////////////////////////////////////////////////
inline SV* dereference( SV* sv )
{
SV* tmp = sv;
while( SvROK(tmp) )
{
tmp = (SV*)SvRV(tmp);
}
return tmp;
}
//////////////////////////////////////////////////////////////////
// get a c++ pointer from SV*
//////////////////////////////////////////////////////////////////
template<class T>
T get_obj( SV* sv )
{
return (T)(I32)SvIV(dereference(sv));
}
//////////////////////////////////////////////////////////////////
// get std::string from SV*
//////////////////////////////////////////////////////////////////
inline std::string str_val( SV* sv )
{
STRLEN len;
const char* c = (const char*)SvPV(dereference(sv),len);
return std::string(c,len);
}
//////////////////////////////////////////////////////////////////
// get int from SV*
//////////////////////////////////////////////////////////////////
inline int int_val( SV* sv )
{
return SvIV(dereference(sv));
}
//////////////////////////////////////////////////////////////////
// get double from SV*
//////////////////////////////////////////////////////////////////
inline double double_val( SV* sv )
{
return SvNV(dereference(sv));
}
//////////////////////////////////////////////////////////////////
// get HV* from SV*
//////////////////////////////////////////////////////////////////
inline HV* hash_val(SV* sv)
{
return (HV*)(dereference(sv));
}
//////////////////////////////////////////////////////////////////
// get AV* from SV*
//////////////////////////////////////////////////////////////////
inline AV* array_val(SV* sv)
{
return (AV*)(dereference(sv));
}
//////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////
// bless an SV* into a package
//////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////
inline SV* bless( SV* sv, const char* classname )
{
SV* ref = sv;
if ( !SvROK(ref) )
ref = newRV_inc( sv );
HV* stash = gv_stashpv( classname, 1);
return sv_bless( ref, stash );
}
//////////////////////////////////////////////////////////////////
// inside a blessed method, Self retrieves a SV* to "this"
//////////////////////////////////////////////////////////////////
#define Self dereference( (SV*)ST(0) )
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// generate mortal SV*
//////////////////////////////////////////////////////////////////
template<class T>
SV* mortal( T* t )
{
SV* sv = sv_newmortal();
sv_setref_iv( sv, (char*)T::PerlClassName(), (I32)t );
return sv;
}
inline SV* mortal( )
{
return sv_newmortal();
}
inline SV* mortal( int i )
{
return sv_2mortal(newSViv(i));
}
inline SV* mortal( double d )
{
return sv_2mortal(newSVnv(d));
}
inline SV* mortal( const char* c )
{
return sv_2mortal(newSVpv(c,0));
}
inline SV* mortal( char* c )
{
return sv_2mortal(newSVpvn(c,strlen(c)));
}
inline SV* mortal( const std::string& s )
{
return sv_2mortal(newSVpv(s.c_str(),s.size()));
}
inline SV* mortal( SV* sv )
{
return sv_2mortal(sv);
}
inline SV* mortal( AV* av )
{
return sv_2mortal((SV*)av);
}
inline SV* mortal( HV* hv )
{
return sv_2mortal((SV*)hv);
}
inline SV* mortal( CV* cv )
{
return sv_2mortal((SV*)cv);
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// get a reference to a SV*
//////////////////////////////////////////////////////////////////
inline SV* ref( SV* sv )
{
return newRV_inc(sv);
}
inline SV* ref( AV* av )
{
return newRV_inc((SV*)av);
}
inline SV* ref( HV* hv )
{
return newRV_inc((SV*)hv);
}
inline SV* ref( CV* cv )
{
return newRV_inc((SV*)cv);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// convert T to a scalar value
//////////////////////////////////////////////////////////////////
template<class T>
SV* scalar( T* t )
{
SV* sv = sv_newmortal();
sv_setref_iv( sv, (char*)T::PerlClassName(), (I32)t );
return sv;
}
inline SV* scalar( int i )
{
return newSViv(i);
}
inline SV* scalar( double d )
{
return newSVnv(d);
}
inline SV* scalar( const char* c )
{
return newSVpv(c,0);
}
inline SV* scalar( const std::string& s )
{
return newSVpv(s.c_str(),s.size());
}
inline SV* scalar( SV* s )
{
return newSVsv(s);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// two parameter form sets a scalar value to existing SV
//////////////////////////////////////////////////////////////////
template<class T>
void scalar( SV* sv, T* t )
{
sv_setref_iv( sv, (char*)T::PerlClassName(), (I32)t );
}
inline void scalar( SV* sv, int i)
{
sv_setiv( dereference(sv), (I32)i );
}
inline void scalar( SV* sv, double d)
{
sv_setnv( dereference(sv), d );
}
inline void scalar( SV* sv, const char* c)
{
sv_setpv( dereference(sv), c );
}
inline void scalar( SV* sv, const std::string& s)
{
sv_setpv( dereference(sv), s.c_str() );
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Init helpers
//////////////////////////////////////////////////////////////////
EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
class PerlInit
{
public:
PerlInit(int argc = 0, char **argv = 0, char **env = 0)
{
PERL_SYS_INIT3(&argc,&argv,&env);
}
~PerlInit()
{
fprintf(stderr,"~PerlInit()\r\n");
//PERL_SYS_TERM();
fprintf(stderr,"~PerlInit() done\r\n");
}
};
//////////////////////////////////////////////////////////////////
struct xs_init_helper
{
typedef void (*xs_func) (pTHX_ CV* cv);
xs_init_helper( const std::string& n, void (*fun) (pTHX_ CV* cv), const std::string& f )
: name(n), func(fun), file(f)
{}
std::string name;
xs_func func;
std::string file;
};
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Perl Array wrapper
//////////////////////////////////////////////////////////////////
class Array
{
public:
Array()
{
av = newAV();
}
Array( SV* sv)
{
av = (AV*)dereference(sv);
}
Array( AV* a)
{
av = a;
}
void undef()
{
av_undef(av);
}
int size()
{
return av_len(av);
}
SV* item( int i )
{
SV** svp = av_fetch( av, i, 0 );
if (!svp)
return 0;
return dereference(*svp);
}
void set( int i, SV* sv )
{
av_store( av, i, sv );
}
void clear()
{
av_clear(av);
}
void extend(int i )
{
av_extend(av,i);
}
void push(SV* sv)
{
av_push(av,sv);
}
SV* pop(SV* sv)
{
av_pop(av);
}
SV* shift(SV* sv)
{
av_shift(av);
}
void unshift(SV* sv)
{
av_unshift(av,1);
av_store(av,0,sv);
}
operator SV*()
{
return (SV*)av;
}
AV* av;
};
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Perl Hash wrapper
//////////////////////////////////////////////////////////////////
class Hash
{
public:
Hash()
{
hv = newHV();
}
Hash( SV* sv )
{
hv = (HV*)dereference(sv);
}
Hash( HV* h )
{
hv = h;
}
void undef()
{
hv_undef(hv);
}
bool exists( const char* key )
{
return hv_exists( hv, key, strlen(key) );
}
SV* item( const char* key )
{
SV** psv = hv_fetch( hv, key, strlen(key), 0 );
if ( psv )
{
return dereference(*psv);
}
return 0;
}
void store( const char* key, SV* sv )
{
hv_store( hv, key, strlen(key), sv, 0 );
}
void erase( const char* key )
{
SV** psv = hv_fetch( hv, key, strlen(key), 1 );
if ( psv )
{
hv_delete( hv, key, strlen(key), G_DISCARD );
}
}
int clear()
{
hv_clear(hv);
}
int each()
{
return hv_iterinit(hv);
}
SV* next( int iter, char** key )
{
iter--;
if ( iter <= 0 )
return 0;
I32 len;
SV* val = hv_iternextsv( hv, key, &len );
return dereference(val);
}
operator SV*()
{
return (SV*)hv;
}
HV* hv;
};
////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// invoke perl functions by SV*
//////////////////////////////////////////////////////////////////
inline void invoke( SV* handler)
{
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
PUTBACK;
call_sv(handler,G_VOID|G_DISCARD);
FREETMPS;
LEAVE;
}
inline void invoke( SV* handler, SV* sv )
{
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv );
PUTBACK;
call_sv(handler,G_VOID|G_DISCARD);
FREETMPS;
LEAVE;
}
inline void invoke( SV* handler, SV* sv1, SV* sv2 )
{
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv1 );
XPUSHs( sv2 );
PUTBACK;
call_sv(handler,G_VOID|G_DISCARD);
FREETMPS;
LEAVE;
}
inline void invoke( SV* handler, SV* sv1, SV* sv2, SV* sv3 )
{
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv1 );
XPUSHs( sv2 );
XPUSHs( sv3 );
PUTBACK;
call_sv(handler,G_VOID|G_DISCARD);
FREETMPS;
LEAVE;
}
inline void invoke( SV* handler, SV* sv1, SV* sv2, SV* sv3, SV* sv4 )
{
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv1 );
XPUSHs( sv2 );
XPUSHs( sv3 );
XPUSHs( sv4 );
PUTBACK;
call_sv(handler,G_VOID|G_DISCARD);
FREETMPS;
LEAVE;
}
//////////////////////////////////////////////////////////////////
// call perl functions by SV*
//////////////////////////////////////////////////////////////////
inline SV* call( SV* handler)
{
SV* ret = 0;
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
PUTBACK;
int cnt = call_sv(handler,G_SCALAR);
SPAGAIN;
if ( cnt == 1 )
ret = mortal(scalar(POPs));
PUTBACK;
FREETMPS;
LEAVE;
return ret;
}
inline SV* call( SV* handler, SV* sv )
{
SV* ret = 0;
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv );
PUTBACK;
int cnt = call_sv(handler,G_SCALAR);
SPAGAIN;
if ( cnt == 1 )
ret = mortal(scalar(POPs));
PUTBACK;
FREETMPS;
LEAVE;
return ret;
}
inline SV* call( SV* handler, SV* sv1, SV* sv2 )
{
SV* ret = 0;
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv1 );
XPUSHs( sv2 );
PUTBACK;
int cnt = call_sv(handler,G_SCALAR);
SPAGAIN;
if ( cnt == 1 )
ret = mortal(scalar(POPs));
PUTBACK;
FREETMPS;
LEAVE;
return ret;
}
inline SV* call( SV* handler, SV* sv1, SV* sv2, SV* sv3 )
{
SV* ret = 0;
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv1 );
XPUSHs( sv2 );
XPUSHs( sv3 );
PUTBACK;
int cnt = call_sv(handler,G_SCALAR);
SPAGAIN;
if ( cnt == 1 )
ret = mortal(scalar(POPs));
PUTBACK;
FREETMPS;
LEAVE;
return ret;
}
inline SV* call( SV* handler, SV* sv1, SV* sv2, SV* sv3, SV* sv4 )
{
SV* ret = 0;
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs( sv1 );
XPUSHs( sv2 );
XPUSHs( sv3 );
XPUSHs( sv4 );
PUTBACK;
int cnt = call_sv(handler,G_SCALAR);
SPAGAIN;
if ( cnt == 1 )
ret = mortal(scalar(POPs));
PUTBACK;
FREETMPS;
LEAVE;
return ret;
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Perl/C++ Bindings
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// get typed perl_value functions for templates
//////////////////////////////////////////////////////////////////
template<class T>
void get_perl_value( SV* sv , T** t)
{
*t = (T*)(I32)SvIV(dereference(sv));
}
inline void get_perl_value( SV* sv, const char** c )
{
STRLEN na;
*c = (const char*)SvPV(dereference(sv),na);
}
inline void get_perl_value( SV* sv, char** c )
{
STRLEN na;
*c = (char*)SvPV(dereference(sv),na);
}
inline void get_perl_value( SV* sv, std::string* s )
{
STRLEN na;
*s = (const char*)SvPV(dereference(sv),na);
}
inline void get_perl_value( SV* sv, int* i )
{
*i = SvIV(dereference(sv));
}
inline void get_perl_value(SV* sv, double* d )
{
*d = SvNV(dereference(sv));
}
inline void get_perl_value(SV* sv, AV** av )
{
*av = (AV*)(dereference(sv));
}
inline void get_perl_value(SV* sv, HV** hv )
{
*hv = (HV*)(dereference(sv));
}
//////////////////////////////////////////////////////////////////
// typed xsreturn functions for templates
//////////////////////////////////////////////////////////////////
inline void xs_return( const I32 ax )
{
XSRETURN(0);
}
inline void xs_return(const I32 ax, int i)
{
ST(0) = sv_newmortal();
sv_setiv( ST(0), (I32)i );
XSRETURN(1);
}
inline void xs_return(const I32 ax, double d)
{
ST(0) = sv_newmortal();
sv_setnv( ST(0), d );
XSRETURN(1);
}
inline void xs_return(const I32 ax, const char* c)
{
ST(0) = sv_newmortal();
sv_setpv( ST(0), c );
XSRETURN(1);
}
inline void xs_return(const I32 ax, const std::string& s)
{
ST(0) = sv_newmortal();
sv_setpv( ST(0), s.c_str() );
XSRETURN(1);
}
template<class T>
void xs_return( const I32 ax, T* t)
{
ST(0) = sv_newmortal();
sv_setref_iv( ST(0), T::PerlClassName(), (I32)t );
XSRETURN(1);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Param Types used by Perl/C++ bindings
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType
{
public:
typedef T StackType;
static void get_value( SV* sv, T* t)
{
get_perl_value(sv,t);
}
static void set_ref_value( SV* sv, T* t)
{
}
static T ParamValue( T* t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<T&>
{
public:
typedef T StackType;
static void get_value( SV* sv, T* t)
{
get_perl_value(sv,t);
}
static void set_ref_value( SV* sv, T* t)
{
set_perl_value( sv, *t );
}
static T& ParamValue( T* t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<void>
{
public:
typedef void* StackType;
static void get_value( SV* sv, void** t)
{
}
static void set_ref_value( SV* sv, void** t)
{
}
static void* ParamValue( void* t )
{
return t;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<T*>
{
public:
typedef T* StackType;
static void get_value( SV* sv, T** t)
{
get_perl_value<T>( sv,t );
}
static void set_ref_value( SV* sv, T** t)
{
}
static T* ParamValue( T** t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<T*&>
{
public:
typedef T* StackType;
static void get_value( SV* sv, T** t)
{
get_perl_value<T>( sv,t);
}
static void set_ref_value( SV* sv, T** t)
{
SV* tmp = dereference(sv);
I32 old = (I32)SvIV(tmp);
if ( *t != (T*)old)
{
delete (T*)old;
sv_setiv( tmp, (I32)(void*)(*t) );
}
}
static T*& ParamValue( T**& t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<T**>
{
public:
typedef T* StackType;
static void get_value( SV* sv, T** t)
{
get_perl_value<T>( sv, t );
}
static void set_ref_value( SV* sv, T** t)
{
SV* tmp = dereference(sv);
I32 old = (I32)SvIV(tmp);
if ( *t != (T*)old)
{
delete (T*)old;
sv_setiv( tmp, (I32)(void*)(*t) );
}
}
static T** ParamValue( T** t )
{
return t;
}
};
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<SV*>
{
public:
typedef SV* StackType;
static void get_value( SV* sv, SV** t)
{
*t = sv;
}
static void set_ref_value( SV* sv, SV** t)
{
}
static SV* ParamValue( SV** t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<char*>
{
public:
typedef char* StackType;
static void get_value( SV* sv, char** c)
{
get_perl_value( sv, c );
}
static void set_ref_value( SV* sv, char** c)
{
}
static char* ParamValue( char** c )
{
return *c;
}
};
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<char*&>
{
public:
typedef char* StackType;
static void get_value( SV* sv, char** c)
{
get_perl_value( sv, c );
}
static void set_ref_value( SV* sv, char** c)
{
sv_setpv( dereference(sv), *c );
}
static char*& ParamValue( char** c )
{
return *c;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<const char*>
{
public:
typedef char* StackType;
static void get_value( SV* sv, char** c)
{
get_perl_value( sv, c );
}
static void set_ref_value( SV* sv, char** c)
{
}
static const char* ParamValue( char** c )
{
return *c;
}
};
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<const char*&>
{
public:
typedef const char* StackType;
static void get_value( SV* sv, const char** c)
{
get_perl_value( sv, c );
}
static void set_ref_value( SV* sv, const char** c)
{
sv_setpv( dereference(sv), *c );
}
static const char*& ParamValue( const char** c )
{
return *c;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<const std::string&>
{
public:
typedef std::string StackType;
static void get_value( SV* sv, std::string* s)
{
get_perl_value( sv, s );
}
static void set_ref_value( SV* sv, std::string* s)
{
}
static StackType& ParamValue( StackType* t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
template<>
class PerlParamType<std::string&>
{
public:
typedef std::string StackType;
static void get_value( SV* sv, std::string* s)
{
get_perl_value( sv, s );
}
static void set_ref_value( SV* sv, std::string* s)
{
sv_setpv( dereference(sv), (char*)s->c_str() );
}
static StackType& ParamValue( StackType* t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<std::vector<T>& >
{
public:
typedef std::vector<T> StackType;
typedef T ItemType;
static void get_value( SV* sv, std::vector<T>* v)
{
SV* tmp = dereference(sv);
if ( SvTYPE(tmp) != SVt_PVAV )
return;
Array array( (AV*)tmp );
int len = array.size();
for ( int i = 0; i <= len; i++ )
{
T it;
SV* sv = array.item( i );
get_perl_value( sv, &it );
v->push_back(it);
}
}
static void set_ref_value( SV* sv,std::vector<T>* v)
{
}
static StackType& ParamValue( StackType* t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<std::vector<T>* >
{
public:
typedef std::vector<T> StackType;
typedef T ItemType;
static void get_value( SV* sv, std::vector<T>* v)
{
PerlParamType<std::vector<T>&>::get_value( sv, v );
}
static void set_ref_value( SV* sv, std::vector<T>* v)
{
SV* tmp = dereference(sv);
if ( SvTYPE(tmp) != SVt_PVAV )
return;
Array array( (AV*)tmp );
array.clear();
array.extend(v->size() );
for ( int i = 0; i < v->size(); i++ )
{
array.push( scalar( v->at(i) ) );
}
}
static StackType* ParamValue( StackType* t )
{
return t;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<std::map<std::string,T>& >
{
public:
typedef std::map<std::string,T> StackType;
typedef T ItemType;
static void get_value( SV* sv, std::map<std::string,T>* m)
{
SV* tmp = dereference(sv);
if ( SvTYPE(tmp) != SVt_PVHV )
return;
Hash hash( (HV*)tmp );
int it = hash.each();
char* key;
while( SV* sv = hash.next(it,&key) )
{
T it;
get_perl_value( sv, &it );
m->insert( std::make_pair( std::string(key), it ) );
}
}
static void set_ref_value( SV* sv,std::map<std::string,T>* v)
{
}
static StackType& ParamValue( StackType* t )
{
return *t;
}
};
//////////////////////////////////////////////////////////////////
template<class T>
class PerlParamType<std::map<std::string,T>* >
{
public:
typedef std::map<std::string,T> StackType;
typedef T ItemType;
static void get_value( SV* sv, std::map<std::string,T>* m)
{
PerlParamType<std::map<std::string,T>&>::get_value( sv, m );
}
static void set_ref_value( SV* sv,std::map<std::string,T>* m)
{
SV* tmp = dereference(sv);
if ( SvTYPE(tmp) != SVt_PVHV )
return;
Hash hash( (HV*)tmp );
hash.clear();
typename std::map<std::string,T>::iterator it = m->begin();
for ( it; it != m->end(); it++ )
{
hash.store( (*it).first.c_str(), scalar( (*it).second ) );
}
}
static StackType* ParamValue( StackType* t )
{
return t;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Signatures for Perl/C++ bindings
//////////////////////////////////////////////////////////////////
template< class R,
class T,
class P1 = void,
class P2 = void,
class P3 = void,
class P4 = void,
class P5 = void,
class P6 = void,
class P7 = void,
class P8 = void >
class Signature
{
public:
typedef R (T::*signature)(P1,P2,P3,P4,P5,P6,P7,P8);
};
template<class R, class T, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
class Signature<R,T,P1,P2,P3,P4,P5,P6,P7,void>
{
public:
typedef R (T::*signature)(P1,P2,P3,P4,P5,P6,P7);
};
template<class R, class T, class P1, class P2, class P3, class P4, class P5, class P6>
class Signature<R,T,P1,P2,P3,P4,P5,P6,void,void>
{
public:
typedef R (T::*signature)(P1,P2,P3,P4,P5,P6);
};
template<class R, class T, class P1, class P2, class P3, class P4, class P5>
class Signature<R,T,P1,P2,P3,P4,P5,void,void,void>
{
public:
typedef R (T::*signature)(P1,P2,P3,P4,P5);
};
template<class R, class T, class P1, class P2, class P3, class P4>
class Signature<R,T,P1,P2,P3,P4,void,void,void,void>
{
public:
typedef R (T::*signature)(P1,P2,P3,P4);
};
template<class R, class T, class P1, class P2, class P3>
class Signature<R,T,P1,P2,P3,void,void,void,void,void>
{
public:
typedef R (T::*signature)(P1,P2,P3);
};
template<class R, class T, class P1, class P2>
class Signature<R,T,P1,P2,void,void,void,void,void,void>
{
public:
typedef R (T::*signature)(P1,P2);
};
template<class R, class T, class P1>
class Signature<R,T,P1,void,void,void,void,void,void,void>
{
public:
typedef R (T::*signature)(P1);
};
template<class R, class T>
class Signature<R,T,void,void,void,void,void,void,void,void>
{
public:
typedef R (T::*signature)();
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Invokers for Perl/C++ bindings
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
class Invoker
{
public:
typedef typename Signature<R,T,P1,P2,P3,P4,P5,P6,P7,P8>::signature Member;
static void invoke8( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5,
typename PerlParamType<P6>::StackType* p6,
typename PerlParamType<P7>::StackType* p7,
typename PerlParamType<P8>::StackType* p8 )
{
R retval = (t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5),
PerlParamType<P6>::ParamValue(p6),
PerlParamType<P7>::ParamValue(p7),
PerlParamType<P8>::ParamValue(p8)
);
xs_return( ax, retval );
}
static void invoke7( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5,
typename PerlParamType<P6>::StackType* p6,
typename PerlParamType<P7>::StackType* p7 )
{
R retval = (t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5),
PerlParamType<P6>::ParamValue(p6),
PerlParamType<P7>::ParamValue(p7)
);
xs_return( ax, retval );
}
static void invoke6( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5,
typename PerlParamType<P6>::StackType* p6 )
{
R retval = (t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5),
PerlParamType<P6>::ParamValue(p6)
);
xs_return( ax, retval );
}
static void invoke5( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5 )
{
R retval = (t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5)
);
xs_return( ax, retval );
}
static void invoke4( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4 )
{
R retval = (t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4)
);
xs_return( ax, retval );
}
static void invoke3( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3 )
{
R retval = (t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3)
);
xs_return( ax, retval );
}
static void invoke2( const I32 ax, T* t, Member member, typename PerlParamType<P1>::StackType* p1, typename PerlParamType<P2>::StackType* p2 )
{
R retval = (t->*member)(PerlParamType<P1>::ParamValue(p1),PerlParamType<P2>::ParamValue(p2));
xs_return( ax, retval );
}
static void invoke1( const I32 ax, T* t, Member member, typename PerlParamType<P1>::StackType* p1 )
{
R retval = (t->*member)(PerlParamType<P1>::ParamValue(p1));
xs_return( ax, retval );
}
static void invoke0( const I32 ax, T* t, Member member)
{
R retval = (t->*member)();
xs_return( ax, retval );
}
};
//////////////////////////////////////////////////////////////////
template<class T, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
class Invoker<void,T,P1,P2,P3,P4,P5,P6,P7,P8>
{
public:
typedef typename Signature<void,T,P1,P2,P3,P4,P5,P6,P7,P8>::signature Member;
static void invoke8( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5,
typename PerlParamType<P6>::StackType* p6,
typename PerlParamType<P7>::StackType* p7,
typename PerlParamType<P8>::StackType* p8 )
{
(t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5),
PerlParamType<P6>::ParamValue(p6),
PerlParamType<P7>::ParamValue(p7),
PerlParamType<P8>::ParamValue(p8)
);
xs_return( ax );
}
static void invoke7( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5,
typename PerlParamType<P6>::StackType* p6,
typename PerlParamType<P7>::StackType* p7 )
{
(t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5),
PerlParamType<P6>::ParamValue(p6),
PerlParamType<P7>::ParamValue(p7)
);
xs_return( ax );
}
static void invoke6( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5,
typename PerlParamType<P6>::StackType* p6 )
{
(t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5),
PerlParamType<P6>::ParamValue(p6)
);
xs_return( ax );
}
static void invoke5( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4,
typename PerlParamType<P5>::StackType* p5 )
{
(t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4),
PerlParamType<P5>::ParamValue(p5)
);
xs_return( ax );
}
static void invoke4( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3,
typename PerlParamType<P4>::StackType* p4 )
{
(t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3),
PerlParamType<P4>::ParamValue(p4)
);
xs_return( ax );
}
static void invoke3( const I32 ax, T* t, Member member,
typename PerlParamType<P1>::StackType* p1,
typename PerlParamType<P2>::StackType* p2,
typename PerlParamType<P3>::StackType* p3 )
{
(t->*member)(
PerlParamType<P1>::ParamValue(p1),
PerlParamType<P2>::ParamValue(p2),
PerlParamType<P3>::ParamValue(p3)
);
xs_return( ax );
}
static void invoke2( const I32 ax, T* t, Member member, typename PerlParamType<P1>::StackType* p1, typename PerlParamType<P2>::StackType* p2 )
{
(t->*member)(PerlParamType<P1>::ParamValue(p1),PerlParamType<P2>::ParamValue(p2));
xs_return( ax );
}
static void invoke1( const I32 ax, T* t, Member member, typename PerlParamType<P1>::StackType* p1 )
{
(t->*member)(PerlParamType<P1>::ParamValue(p1));
xs_return( ax );
}
static void invoke0( const I32 ax, T* t, Member member)
{
(t->*member)();
xs_return( ax );
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
class PerlClassCallBase
{
public:
virtual ~PerlClassCallBase() {}
virtual void jump(pTHX_ CV* cv) = 0;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R,
class T,
class P1 = void,
class P2 = void,
class P3 = void,
class P4 = void,
class P5 = void,
class P6 = void,
class P7 = void,
class P8 = void >
class PerlClassCall : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,P2,P3,P4,P5,P6,P7,P8>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
typename PerlParamType<P2>::StackType p2;
typename PerlParamType<P3>::StackType p3;
typename PerlParamType<P4>::StackType p4;
typename PerlParamType<P5>::StackType p5;
typename PerlParamType<P6>::StackType p6;
typename PerlParamType<P7>::StackType p7;
typename PerlParamType<P8>::StackType p8;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::get_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::get_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::get_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::get_value( ST(5), &p5 );
if ( items > 6 ) PerlParamType<P6>::get_value( ST(6), &p6 );
if ( items > 7 ) PerlParamType<P7>::get_value( ST(7), &p7 );
if ( items > 8 ) PerlParamType<P8>::get_value( ST(8), &p8 );
Invoker<R,T,P1,P2,P3,P4,P5,P6,P7,P8>::invoke8( ax, t, member, &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::set_ref_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::set_ref_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::set_ref_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::set_ref_value( ST(5), &p5 );
if ( items > 6 ) PerlParamType<P6>::set_ref_value( ST(6), &p6 );
if ( items > 7 ) PerlParamType<P7>::set_ref_value( ST(7), &p7 );
if ( items > 8 ) PerlParamType<P8>::set_ref_value( ST(8), &p8 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T, class P1, class P2, class P3, class P4, class P5, class P6, class P7 >
class PerlClassCall<R,T,P1,P2,P3,P4,P5,P6,P7,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,P2,P3,P4,P5,P6,P7,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
typename PerlParamType<P2>::StackType p2;
typename PerlParamType<P3>::StackType p3;
typename PerlParamType<P4>::StackType p4;
typename PerlParamType<P5>::StackType p5;
typename PerlParamType<P6>::StackType p6;
typename PerlParamType<P7>::StackType p7;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::get_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::get_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::get_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::get_value( ST(5), &p5 );
if ( items > 6 ) PerlParamType<P6>::get_value( ST(6), &p6 );
if ( items > 7 ) PerlParamType<P7>::get_value( ST(7), &p7 );
Invoker<R,T,P1,P2,P3,P4,P5,P6,P7,void>::invoke7( ax, t, member, &p1, &p2, &p3, &p4, &p5, &p6, &p7 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::set_ref_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::set_ref_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::set_ref_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::set_ref_value( ST(5), &p5 );
if ( items > 6 ) PerlParamType<P6>::set_ref_value( ST(6), &p6 );
if ( items > 7 ) PerlParamType<P7>::set_ref_value( ST(7), &p7 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T, class P1, class P2, class P3, class P4, class P5, class P6>
class PerlClassCall<R,T,P1,P2,P3,P4,P5,P6,void,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,P2,P3,P4,P5,P6,void,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
typename PerlParamType<P2>::StackType p2;
typename PerlParamType<P3>::StackType p3;
typename PerlParamType<P4>::StackType p4;
typename PerlParamType<P5>::StackType p5;
typename PerlParamType<P6>::StackType p6;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::get_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::get_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::get_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::get_value( ST(5), &p5 );
if ( items > 6 ) PerlParamType<P6>::get_value( ST(6), &p6 );
Invoker<R,T,P1,P2,P3,P4,P5,P6,void,void>::invoke6( ax, t, member, &p1, &p2, &p3, &p4, &p5, &p6 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::set_ref_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::set_ref_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::set_ref_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::set_ref_value( ST(5), &p5 );
if ( items > 6 ) PerlParamType<P6>::set_ref_value( ST(6), &p6 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T, class P1, class P2, class P3, class P4, class P5>
class PerlClassCall<R,T,P1,P2,P3,P4,P5,void,void,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,P2,P3,P4,P5,void,void,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
typename PerlParamType<P2>::StackType p2;
typename PerlParamType<P3>::StackType p3;
typename PerlParamType<P4>::StackType p4;
typename PerlParamType<P5>::StackType p5;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::get_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::get_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::get_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::get_value( ST(5), &p5 );
Invoker<R,T,P1,P2,P3,P4,P5,void,void,void>::invoke5( ax, t, member, &p1, &p2, &p3, &p4, &p5 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::set_ref_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::set_ref_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::set_ref_value( ST(4), &p4 );
if ( items > 5 ) PerlParamType<P5>::set_ref_value( ST(5), &p5 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T, class P1, class P2, class P3, class P4 >
class PerlClassCall<R,T,P1,P2,P3,P4,void,void,void,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,P2,P3,P4,void,void,void,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
typename PerlParamType<P2>::StackType p2;
typename PerlParamType<P3>::StackType p3;
typename PerlParamType<P4>::StackType p4;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::get_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::get_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::get_value( ST(4), &p4 );
Invoker<R,T,P1,P2,P3,P4,void,void,void,void>::invoke4( ax, t, member, &p1, &p2, &p3, &p4 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::set_ref_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::set_ref_value( ST(3), &p3 );
if ( items > 4 ) PerlParamType<P4>::set_ref_value( ST(4), &p4 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T, class P1, class P2, class P3>
class PerlClassCall<R,T,P1,P2,P3,void,void,void,void,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,P2,P3,void,void,void,void,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
typename PerlParamType<P2>::StackType p2;
typename PerlParamType<P3>::StackType p3;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::get_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::get_value( ST(3), &p3 );
Invoker<R,T,P1,P2,P3,void,void,void,void,void>::invoke3( ax, t, member, &p1, &p2, &p3 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::set_ref_value( ST(2), &p2 );
if ( items > 3 ) PerlParamType<P3>::set_ref_value( ST(3), &p3 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T, class P1, class P2>
class PerlClassCall<R,T,P1,P2,void,void,void,void,void,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,P2,void,void,void,void,void,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
typename PerlParamType<P2>::StackType p2;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::get_value( ST(2), &p2 );
Invoker<R,T,P1,P2,void,void,void,void,void,void>::invoke2( ax, t, member, &p1, &p2 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
if ( items > 2 ) PerlParamType<P2>::set_ref_value( ST(2), &p2 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T, class P1>
class PerlClassCall<R,T,P1,void,void,void,void,void,void,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,P1,void,void,void,void,void,void,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
typename PerlParamType<P1>::StackType p1;
if ( items > 1 ) PerlParamType<P1>::get_value( ST(1), &p1 );
Invoker<R,T,P1,void,void,void,void,void,void,void>::invoke1( ax, t, member, &p1 );
if ( items > 1 ) PerlParamType<P1>::set_ref_value( ST(1), &p1 );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template< class R, class T>
class PerlClassCall<R,T,void,void,void,void,void,void,void,void> : public PerlClassCallBase
{
public:
typedef T PerlClass;
typedef typename Signature<R,T,void,void,void,void,void,void,void,void>::signature Member;
PerlClassCall( Member m )
: member(m)
{}
void jump(pTHX_ CV* cv)
{
dXSARGS;
if ( items > 0 )
{
T* t;
get_perl_value(ST(0),&t);
Invoker<R,T,void,void,void,void,void,void,void,void>::invoke0( ax, t, member );
return;
}
xs_return(ax);
}
Member member;
};
//////////////////////////////////////////////////////////////////
// PerlInterpreter* pp, CV* cv
//////////////////////////////////////////////////////////////////
template<>
class PerlClassCall<void,void,PerlInterpreter*,CV*,void,void,void,void,void,void> : public PerlClassCallBase
{
public:
typedef void PerlClass;
typedef void (*Member)(PerlInterpreter*,CV* cv);
PerlClassCall( Member m )
: member(m)
{}
void jump(PerlInterpreter* pp, CV* cv)
{
(*member)(pp,cv);
}
Member member;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// template functions to use template argument deduction for
// perl/c++ bindings
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1,P2,P3,P4,P5,P6,P7,P8) )
{
return new PerlClassCall<R,T,P1,P2,P3,P4,P5,P6,P7,P8>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1,P2,P3,P4,P5,P6,P7) )
{
return new PerlClassCall<R,T,P1,P2,P3,P4,P5,P6,P7>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2, class P3, class P4, class P5, class P6>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1,P2,P3,P4,P5,P6) )
{
return new PerlClassCall<R,T,P1,P2,P3,P4,P5,P6>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2, class P3, class P4, class P5>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1,P2,P3,P4,P5) )
{
return new PerlClassCall<R,T,P1,P2,P3,P4,P5>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2, class P3, class P4>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1,P2,P3,P4) )
{
return new PerlClassCall<R,T,P1,P2,P3,P4>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2, class P3>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1,P2,P3) )
{
return new PerlClassCall<R,T,P1,P2,P3>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1, class P2>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1,P2) )
{
return new PerlClassCall<R,T,P1,P2>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T, class P1>
PerlClassCallBase* make_perl_class_call( R (T::*member)(P1) )
{
return new PerlClassCall<R,T,P1>(member);
}
//////////////////////////////////////////////////////////////////
template<class R, class T>
PerlClassCallBase* make_perl_class_call( R (T::*member)() )
{
return new PerlClassCall<R,T>(member);
}
//////////////////////////////////////////////////////////////////
// low level support case
//////////////////////////////////////////////////////////////////
inline PerlClassCallBase* make_perl_class_call( void (*member)(PerlInterpreter*,CV*) )
{
return new PerlClassCall<void,void,PerlInterpreter*,CV*>(member);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// hacky Meta Data Class Def Insertion Macros
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#define perl_exposed_as(type,classname) \
typedef type PerlClassType; \
static const char* PerlClassName() { return classname; } \
static void xs_init() \
{ \
type t; \
for ( std::list<PerlGlue::xs_init_helper>::iterator it = xs_inits().begin(); it != xs_inits().end(); it++ ) \
{ \
newXS( (char*)(*it).name.c_str(), (*it).func, (char*)(*it).file.c_str() ); \
} \
} \
static std::list<PerlGlue::xs_init_helper>& xs_inits() \
{ \
static std::list<PerlGlue::xs_init_helper> xi; \
return xi; \
} \
static void static_##type##_new(pTHX_ CV* cv) \
{ \
dXSARGS; \
if ( items == 1 ) \
{ \
STRLEN na; \
char* CLASS; \
PerlGlue::get_perl_value( ST(0), &CLASS ); \
type* t = new type; \
PerlGlue::xs_return( ax, t ); \
return; \
} \
XSRETURN(0); \
} \
static void static_##type##_DESTROY(pTHX_ CV* cv) \
{ \
dXSARGS; \
if ( items == 1 ) \
{ \
type* t; \
PerlGlue::get_perl_value(ST(0),&t); \
delete t; \
} \
XSRETURN(0); \
} \
class inner_perl_meta_class \
{ \
public: \
inner_perl_meta_class() \
{ \
static int i = init(); \
} \
int init() \
{ \
std::ostringstream oss1; \
oss1 << PerlClassType::PerlClassName() << "::new"; \
xs_inits().push_back( \
PerlGlue::xs_init_helper( oss1.str(), \
&PerlClassType::static_##type##_new, \
__FILE__ ) ); \
std::ostringstream oss2; \
oss2 << PerlClassType::PerlClassName() << "::DESTROY"; \
xs_inits().push_back( \
PerlGlue::xs_init_helper( oss2.str(), \
&PerlClassType::static_##type##_DESTROY, \
__FILE__ ) ); \
return 1; \
} \
} inner_perl_meta_class_member;
#define perl_exposed(type) perl_exposed_as(type,#type)
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#define perl_boot_as(Type,Name) \
extern "C" { \
XS(boot_##Name); \
XS(boot_##Name) \
{ \
dXSARGS; \
XS_VERSION_BOOTCHECK ; \
Type::xs_init(); \
XSRETURN_YES; \
} }
#define perl_boot(Type) perl_boot_as(Type,#Type)
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#define perl_export(member) \
class inner_perl_callable_##member##_class \
{ \
public: \
inner_perl_callable_##member##_class() \
{ \
static int i = init(); \
} \
int init() \
{ \
std::ostringstream oss; \
oss << PerlClassType::PerlClassName() << "::" << #member; \
xs_inits().push_back( \
PerlGlue::xs_init_helper( oss.str(), \
&PerlClassType::static_##member##_trampoline, \
__FILE__ ) ); \
return 1; \
} \
} inner_perl_callable_##member##_class_member; \
\
static void static_##member##_trampoline(PerlInterpreter* pp, CV* cv) \
{ \
static PerlGlue::PerlClassCallBase* pccb = \
PerlGlue::make_perl_class_call( &PerlClassType::member); \
pccb->jump(pp,cv); \
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// embedded perl interpreter
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
class Perl
{
public:
typedef void (*initializer)();
Perl(int argc = 0, char **argv = 0, char **env = 0)
{
init();
}
~Perl()
{
destroy();
}
void init()
{
my_perl = perl_alloc();
PL_perl_destruct_level = 1;
perl_construct(my_perl);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
theMap().insert(std::make_pair(my_perl,this));
}
void destroy()
{
theMap().erase(my_perl);
perl_destruct(my_perl);
perl_free(my_perl);
}
// parse, then run or call
void parse( int argc, char** argv, char** env = NULL)
{
perl_parse(my_perl, &Perl::xs_init, argc, argv, env);
}
void run()
{
perl_run(my_perl);
}
void call( const std::string& fun, int opts = G_DISCARD | G_NOARGS, char** args = 0 )
{
call_argv( fun.c_str(), opts, args);
}
// embedd, then eval
void embed( char** env = NULL )
{
char *embedding[] = { "", "-e", "0" };
parse( 3, embedding, env );
}
void eval( const std::string& code , bool croak_on_err = true)
{
eval_pv( code.c_str(), croak_on_err );
}
// get/set global Perl vars
template<class T>
void get_val( T& t, const std::string& name )
{
SV* sv = 0;
sv = perl_get_sv( name.c_str(), TRUE );
get_perl_value( sv, &t );
}
template<class T>
void set_val(const T& t, const std::string& name )
{
SV* sv = 0;
sv = perl_get_sv( name.c_str(), TRUE );
set_perl_value( sv, t );
}
// inject some c++ obj into perl
// inject a pointer to obj. Perl will own and delete it
template<class T>
void inject(T* t, const std::string& name)
{
SV* sv = 0;
sv = perl_get_sv( name.c_str(), TRUE );
set_perl_value( sv, t );
}
// inject a reference to obj. Perl will NOT own and NOT delete it
template<class T>
void inject(T& t, const std::string& name)
{
SV* sv = 0;
sv = perl_get_sv( name.c_str(), TRUE );
set_perl_value( sv, &t );
SvREFCNT_inc(dereference(sv));
}
// make perl aware of a class definition in c++
template<class T>
void addClassDef()
{
xs_inits_.push_back((initializer)&T::xs_init);
}
// main xs_init hook
static void xs_init(PerlInterpreter* pi)
{
if ( theMap().count(pi) > 0 )
{
theMap()[pi]->xs_init_impl();
}
}
void set_ctx()
{
PERL_SET_CONTEXT(my_perl);
}
private:
void xs_init_impl()
{
newXS( "DynaLoader::boot_DynaLoader", boot_DynaLoader, __FILE__ );
for ( std::list<initializer>::iterator it = xs_inits_.begin(); it != xs_inits_.end(); it++ )
{
(*it)();
}
}
PerlInterpreter* my_perl;
std::list<initializer> xs_inits_;
typedef std::map<PerlInterpreter*,Perl*> MapType;
static MapType& theMap()
{
static MapType theMap_;
return theMap_;
}
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
} // end namespace PerlGlue
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#endif
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
c182e4e4a5df38113f87bd59bfbe7c265588980f | 66d8ea74e6ec6effebb3649782a61c28eaf58ddd | /arduino/sketchbook/libraries/RichUNOKitC/examples/Advanced/L31_Speak_Pi/L31_Speak_Pi.ino | f5438ec28523fb29c636a41be94dd0f5099d36c6 | [] | no_license | philipp68/IOT-Experiments | ca35273bc45e0e0e18e2d9ac4b030721c8a136f7 | bcaf76f559be84012d5244374b7d32401dab8dbc | refs/heads/master | 2021-06-29T13:45:08.037205 | 2019-04-16T19:55:09 | 2019-04-16T19:55:09 | 134,470,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,249 | ino | /************************************************* ************************************************** ******
* OPEN-SMART Rich UNO R3 Lesson 31: Speak pi
If you have done in lesson 25, you ignore these notes below.
NOTE!!! First of all you should download the voice resources from our google drive:
https://drive.google.com/drive/folders/0B6uNNXJ2z4CxbTduWWYzRU13a1U?usp=sharing
Then unzip it and find the 01 and 02 folder and put them into your TF card (should not larger than 32GB).
Note 2: Use the audio cable to connect the mono amplifier module with the MP3 module together,
then use the DuPont cable to connect the 3.3V power supply of IO Shield with power supply pins of the amplifier module.
* You can learn how to play a number according to the value and the filename of digit.
*
* The following functions are available:
*
mp3.waitStop();//Waiting for the end of song, commonly used in voice broadcast, because the voice is short, will soon feedback a stop command.
mp3.playWithFileName(int8_t directory, int8_t file);//play a song according to the folder name and prefix of its file name
//foler name must be 01 02 03...09 10...99
//prefix of file name must be 001...009 010...255
************************************************** **************************************************/
/*****************************CHINESE******************** ************************************************** ******
* OPEN-SMART Rich UNO R3 第31课: 将圆周率的前几位有效数字读出来
如果已经学习了25课,可以忽略这两个注意事项。
注意:在本课开始之前你要下载好需要用的语音资源,可以从我们的百度网盘下载
http://pan.baidu.com/s/1skEjoqp
然后将01和02文件夹复制到TF卡的根目录中
注意2:用音频线将单路功放模块和MP3模块连接器,再用杜邦线将IO扩展板的3.3V电源接到功放模块的电源引脚,注意电源正负
* 您可以根据数字的值和文件名来学习如何播报数字语音,学习如何组合播放,这对于语音播报项目非常重要。
*
* The following functions are available:
*
* mp3.waitStop();//等待播放结束,常用语音播报,由于语音较短,很快就会有播放结束命令反馈
* mp3.playWithFileName(int8_t directory, int8_t file);//按照文件夹名字和文件名前缀播放相应曲目
//文件夹名字必须是01 02 03...09 10...99
//曲目名字的前面3个字符必须是 001...009 010...255,例如001xxx.mp3的文件名就是合法的
************************************************** **************************************************/
#include <Wire.h>
#include <SoftwareSerial.h>
#include "RichUNOKitCMP3.h"
#define MP3_RX 7//RX of Serial MP3 module connect to D7 of Arduino
#define MP3_TX 8//TX to D8
MP3 mp3(MP3_RX, MP3_TX);
int8_t volume = 0x1e;//0~0x1e (30 adjustable level)
int8_t folderName = 2;//folder name must be 01 02 03 04 ...
int8_t fileName = 1; // prefix of file name must be 001xxx 002xxx 003xxx 004xxx ...
#define NUM_OFFSET 2//offset between number and file name, such as file name of 0 is 002, 1 is 003
const char pi[] = "3.14159265";//The 9-digit effective number of pi
void setup()
{
delay(500);//Requires 500ms to wait for the MP3 module to initialize
}
void loop()
{
uint8_t num = sizeof(pi);
mp3.playWithFileName(folderName,39);//039 pi is
delay(200);
mp3.waitStop();
for(uint8_t i = 0; i < num; i++)
{
speaknum(pi[i]);//
}
while(1);
}
void speaknum(char c) {
if ('0' <= c && c <= '9') {
fileName = c - 0x30 + NUM_OFFSET;
}
else if(c == '.')
{
fileName = 1;//001 point
}
else if (c != '.') {
// error if not period
return;
}
mp3.playWithFileName(folderName,fileName);
mp3.waitStop();//Waiting for a voice to end
delay(200);
}
/*********************************************************************************************************
The end of file
*********************************************************************************************************/
| [
"[email protected]"
] | |
1a429d3ca7fc32204ef898abc85530dbc709aaf1 | 703137e3a9caa49c3535aa34497d2a710af9f134 | /1236C.cpp | b8b3116d13c7f2cc8951ca32ed51e91fbf7ced08 | [] | no_license | toha993/Codeforces-My-Code | a558d175204d08167cb1b8e70dd0fb0d2b727d0e | 8521f325be45775a477c63a4dddb1e21e486d824 | refs/heads/master | 2022-12-21T06:07:22.131597 | 2020-10-04T11:50:26 | 2020-10-04T11:50:26 | 301,116,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | cpp | #include<cstdio>
#include<sstream>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<iostream>
#include<fstream>
#include<numeric>
#include<string>
#include<vector>
#include<cstring>
#include<map>
#include<iterator>
#include <iomanip>
using namespace std;
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
// typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> ordered_set;
int main()
{
int n;
cin >> n;
int k=n*n;
int ck=1;
vector<int>v[305];
for (int i = 1; i <= n; ++i)
{
if(i%2)
for (int j = 1; j <= n; ++j)
{
v[j].push_back(ck++);
}
else
for (int j = n; j>=1; --j)
{
v[j].push_back(ck++);
}
}
for (int i = 1; i <=n; ++i)
{
for (int j = 0; j < v[i].size(); ++j)
{
cout << v[i][j] << " ";
}
cout << endl;
}
} | [
"[email protected]"
] | |
38f19a16f747c680ca04089abbe532c83ade54c1 | b85b4b4903dc3134f4c5368972802c9d2b4cfb62 | /ParseCan/src/ParseCan.cpp | 7c2ced0f52c1d12156c60b6ba398122686359d1a | [] | no_license | surpriserom/Protocole_SimpleCan_Arduino | b64608f8c586b6fbc370676099e7aa16a51d16be | 2cd863c07de011500f1d849e07bd70fc78bac066 | refs/heads/master | 2021-01-23T10:00:31.809935 | 2015-06-19T12:53:06 | 2015-06-19T12:53:06 | 35,426,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,297 | cpp | //fonction pour decouper les messages CAN
//basée sur le code de http://savvymicrocontrollersolutions.com/arduino.php?article=adafruit-ultimate-gps-shield-seeedstudio-can-bus-shield
//un int est stocke pour la leonardo sur 16octets
//un float est stocke sur 32 octets
#include "parseCan.h"
ParseCan::ParseCan(bool val)
{
init = val;
}
//convertie 2 char d'un tableau en entier
int ParseCan::ucharToInt(unsigned char buff[], int offset)
{
int nb = ((int) buff[offset] << 8) + buff[offset+1];
return nb;
}
//convertie 4 char d'un tableau en float
float ParseCan::ucharToFloat(unsigned char buff[], int offset)
{
union {
float a;
unsigned char bytes[4];
} thing;
for(int i = 0; i< 4; i++)
{
thing.bytes[i] = buff[offset+i];
}
return thing.a;
}
//stocke les 2 octets d'un int dans 2 case d'un tableau à partire de offset
void ParseCan::intToUChar(unsigned char buff[], int offset, int val)
{
buff[offset] = (val >> 8) & 0xff;
buff[offset+1] = val & 0xff;
}
//stocke les 4 octets d'un float dans 4 case d'un tableaux
void ParseCan::floatToUChar(unsigned char buff[], int offset, float val)
{
union {
float a;
unsigned char bytes[4];
} thing;
thing.a = val;
for(int i = 0; i< 4; i++)
{
buff[offset+i] = thing.bytes[i];
}
}
| [
"[email protected]"
] | |
ffe0ea1d187b882e07158efc3a180677f9e5560a | 42ab5074bb469e6d32bdb401ca248dbe908f6c41 | /WS06/WS06_submit/Car.h | 23f2e8ae39e355cf898398f254a8b357ff560cd8 | [] | no_license | Genne23v/myOOP345_Workhop | c2eb64368b0b207a6c8c64bfe9f1d4cd6a01a0f1 | ad11fd89cae75358f214d7c80f6c64a79abcf1ca | refs/heads/main | 2023-07-09T09:33:24.620976 | 2021-07-30T01:32:39 | 2021-07-30T01:32:39 | 370,092,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | h | // Workshop 6: Part 2
// Date: 2021/07/06
// Author: Wonkeun No
// Student #: 145095196
// Description:
// Car.h
///////////////////////////////////////////////////
// I have done all the coding by myself and only copied the code that my professor
// provided to complete my workshops and assignments.
///////////////////////////////////////////////////
#ifndef SDDS_CAR_H
#define SDDS_CAR_H
#include <string>
#include <iostream>
#include "Vehicle.h"
namespace sdds
{
class Car : public Vehicle
{
std::string m_maker;
std::string m_condition;
double m_topSpeed;
public:
Car(std::istream& is);
~Car() {};
std::string condition() const;
double topSpeed() const;
void display(std::ostream& out) const;
};
std::string removeSpaces(std::string str);
}
#endif // !SDDS_CAR_H
| [
"[email protected]"
] | |
0f0a6260837041003f4fc8e55b83de4c68dea7cc | e267a066b7ee39f6d3fe2cb983725fd55196c63b | /360VR_refactor/arduino/with_unity/lickometerOptical/lickometerOptical.ino | e355979d53ccd8ff562fa47aec82a130e37ed0e1 | [] | no_license | AndreasHogstrand/VR_pyControl | 147e70aeda54eaaf797ab23c503a66d27c26ab03 | 91d720cfdc5bce43fd021af7a55d7a0a7ae7374a | refs/heads/master | 2021-01-02T07:42:45.004912 | 2020-09-29T08:57:08 | 2020-09-29T08:57:08 | 239,552,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | ino | //Edit this threshold to change the sensibility of the lickometer
int lickThreshold = 80;
//Synchronization variables
bool isLicking = false;
int lickoVal = 0;
int rewardConsumed = 0;
void setup() {
Serial.begin(57600);
pinMode(A4, INPUT);
}
void loop() {
//Flush the serial console (to avoid buffering)
Serial.flush();
//This code implements the FSM of the attached figure
if(isLicking){
lickoVal = analogRead(A4);
if(lickoVal <= lickThreshold) isLicking = false;
} else {
lickoVal = analogRead(A4);
if(lickoVal > lickThreshold){
isLicking = true;
Serial.print('l');
} else isLicking = false;
}
}
| [
"[email protected]"
] | |
d70b200a336b090bb933bf27002c83c75d72b819 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/Halide/2015/4/LLVM_Runtime_Linker.cpp | b7a5cc4822d32600f43f808f20d242c99dc26398 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 24,862 | cpp | #include "LLVM_Runtime_Linker.h"
#include "LLVM_Headers.h"
namespace Halide {
using std::string;
using std::vector;
using Internal::vec;
namespace {
llvm::Module *parse_bitcode_file(llvm::StringRef buf, llvm::LLVMContext *context, const char *id) {
#if LLVM_VERSION >= 36
llvm::MemoryBufferRef bitcode_buffer = llvm::MemoryBufferRef(buf, id);
#else
llvm::MemoryBuffer *bitcode_buffer = llvm::MemoryBuffer::getMemBuffer(buf);
#endif
#if LLVM_VERSION >= 35
llvm::Module *mod = llvm::parseBitcodeFile(bitcode_buffer, *context).get();
#else
llvm::Module *mod = llvm::ParseBitcodeFile(bitcode_buffer, *context);
#endif
#if LLVM_VERSION < 36
delete bitcode_buffer;
#endif
mod->setModuleIdentifier(id);
return mod;
}
}
#define DECLARE_INITMOD(mod) \
extern "C" unsigned char halide_internal_initmod_##mod[]; \
extern "C" int halide_internal_initmod_##mod##_length; \
llvm::Module *get_initmod_##mod(llvm::LLVMContext *context) { \
llvm::StringRef sb = llvm::StringRef((const char *)halide_internal_initmod_##mod, \
halide_internal_initmod_##mod##_length); \
llvm::Module *module = parse_bitcode_file(sb, context, #mod); \
return module; \
}
#define DECLARE_NO_INITMOD(mod) \
llvm::Module *get_initmod_##mod(llvm::LLVMContext *, bool) { \
user_error << "Halide was compiled without support for this target\n"; \
return NULL; \
} \
llvm::Module *get_initmod_##mod##_ll(llvm::LLVMContext *) { \
user_error << "Halide was compiled without support for this target\n"; \
return NULL; \
}
#define DECLARE_CPP_INITMOD(mod) \
DECLARE_INITMOD(mod ## _32_debug) \
DECLARE_INITMOD(mod ## _64_debug) \
DECLARE_INITMOD(mod ## _32) \
DECLARE_INITMOD(mod ## _64) \
llvm::Module *get_initmod_##mod(llvm::LLVMContext *context, bool bits_64, bool debug) { \
if (bits_64) { \
if (debug) return get_initmod_##mod##_64_debug(context); \
else return get_initmod_##mod##_64(context); \
} else { \
if (debug) return get_initmod_##mod##_32_debug(context); \
else return get_initmod_##mod##_32(context); \
} \
}
#define DECLARE_LL_INITMOD(mod) \
DECLARE_INITMOD(mod ## _ll)
DECLARE_CPP_INITMOD(android_clock)
DECLARE_CPP_INITMOD(android_host_cpu_count)
DECLARE_CPP_INITMOD(android_io)
DECLARE_CPP_INITMOD(android_opengl_context)
DECLARE_CPP_INITMOD(ios_io)
DECLARE_CPP_INITMOD(cuda)
DECLARE_CPP_INITMOD(destructors)
DECLARE_CPP_INITMOD(windows_cuda)
DECLARE_CPP_INITMOD(fake_thread_pool)
DECLARE_CPP_INITMOD(gcd_thread_pool)
DECLARE_CPP_INITMOD(linux_clock)
DECLARE_CPP_INITMOD(linux_host_cpu_count)
DECLARE_CPP_INITMOD(linux_opengl_context)
DECLARE_CPP_INITMOD(osx_opengl_context)
DECLARE_CPP_INITMOD(opencl)
DECLARE_CPP_INITMOD(windows_opencl)
DECLARE_CPP_INITMOD(opengl)
DECLARE_CPP_INITMOD(osx_host_cpu_count)
DECLARE_CPP_INITMOD(posix_allocator)
DECLARE_CPP_INITMOD(posix_clock)
DECLARE_CPP_INITMOD(windows_clock)
DECLARE_CPP_INITMOD(osx_clock)
DECLARE_CPP_INITMOD(posix_error_handler)
DECLARE_CPP_INITMOD(posix_io)
DECLARE_CPP_INITMOD(ssp)
DECLARE_CPP_INITMOD(windows_io)
DECLARE_CPP_INITMOD(posix_math)
DECLARE_CPP_INITMOD(posix_thread_pool)
DECLARE_CPP_INITMOD(windows_thread_pool)
DECLARE_CPP_INITMOD(tracing)
DECLARE_CPP_INITMOD(write_debug_image)
DECLARE_CPP_INITMOD(posix_print)
DECLARE_CPP_INITMOD(gpu_device_selection)
DECLARE_CPP_INITMOD(cache)
DECLARE_CPP_INITMOD(nacl_host_cpu_count)
DECLARE_CPP_INITMOD(to_string)
DECLARE_CPP_INITMOD(module_jit_ref_count)
DECLARE_CPP_INITMOD(module_aot_ref_count)
DECLARE_CPP_INITMOD(device_interface)
DECLARE_CPP_INITMOD(metadata)
DECLARE_CPP_INITMOD(matlab)
DECLARE_CPP_INITMOD(posix_get_symbol)
DECLARE_CPP_INITMOD(osx_get_symbol)
DECLARE_CPP_INITMOD(windows_get_symbol)
DECLARE_CPP_INITMOD(renderscript)
#ifdef WITH_ARM
DECLARE_LL_INITMOD(arm)
DECLARE_LL_INITMOD(arm_no_neon)
#else
DECLARE_NO_INITMOD(arm)
DECLARE_NO_INITMOD(arm_no_neon)
#endif
#ifdef WITH_AARCH64
DECLARE_LL_INITMOD(aarch64)
#else
DECLARE_NO_INITMOD(aarch64)
#endif
DECLARE_LL_INITMOD(posix_math)
DECLARE_LL_INITMOD(pnacl_math)
DECLARE_LL_INITMOD(win32_math)
DECLARE_LL_INITMOD(ptx_dev)
DECLARE_LL_INITMOD(renderscript_dev)
#ifdef WITH_PTX
DECLARE_LL_INITMOD(ptx_compute_20)
DECLARE_LL_INITMOD(ptx_compute_30)
DECLARE_LL_INITMOD(ptx_compute_35)
#endif
#ifdef WITH_X86
DECLARE_LL_INITMOD(x86_avx)
DECLARE_LL_INITMOD(x86)
DECLARE_LL_INITMOD(x86_sse41)
#else
DECLARE_NO_INITMOD(x86_avx)
DECLARE_NO_INITMOD(x86)
DECLARE_NO_INITMOD(x86_sse41)
#endif
#ifdef WITH_MIPS
DECLARE_LL_INITMOD(mips)
#else
DECLARE_NO_INITMOD(mips)
#endif
namespace {
// Link all modules together and with the result in modules[0],
// all other input modules are destroyed.
void link_modules(std::vector<llvm::Module *> &modules) {
#if LLVM_VERSION >= 35
// LLVM is moving to requiring data layouts to exist. Use the
// datalayout of the first module that has one for all modules.
const llvm::DataLayout *data_layout = NULL;
for (size_t i = 0; data_layout == NULL && i < modules.size(); i++) {
#if LLVM_VERSION >= 37
data_layout = &modules[i]->getDataLayout();
#else
data_layout = modules[i]->getDataLayout();
#endif
}
// If LLVM is 3.5 or greater, we have C++11.
std::unique_ptr<llvm::DataLayout> default_layout;
if (data_layout == NULL) {
// An empty data layout is acceptable as a last ditch default.
default_layout.reset(new llvm::DataLayout(""));
data_layout = default_layout.get();
}
#endif
// Link them all together
for (size_t i = 1; i < modules.size(); i++) {
#if LLVM_VERSION >= 37
modules[i]->setDataLayout(*data_layout);
#elif LLVM_VERSION >= 35
modules[i]->setDataLayout(data_layout);
#endif
// This is a workaround to silence some linkage warnings during
// tests: normally all modules will have the same triple,
// but on 64-bit targets some may have "x86_64-unknown-unknown-unknown"
// as a workaround for -m64 requiring an explicit 64-bit target.
modules[i]->setTargetTriple(modules[0]->getTargetTriple());
string err_msg;
#if LLVM_VERSION >= 36
bool failed = llvm::Linker::LinkModules(modules[0], modules[i]);
#else
bool failed = llvm::Linker::LinkModules(modules[0], modules[i],
llvm::Linker::DestroySource, &err_msg);
#endif
if (failed) {
internal_error << "Failure linking initial modules: " << err_msg << "\n";
}
}
// Now remark most weak symbols as linkonce. They are only weak to
// prevent llvm from stripping them during initial module
// assembly. This means they can be stripped later.
// The symbols that we might want to call as a user even if not
// used in the Halide-generated code must remain weak. This is
// handled automatically by assuming any symbol starting with
// "halide_" that is weak will be retained. There are a few
// compiler generated symbols for which this convention is not
// followed and these are in this array.
string retain[] = {"__stack_chk_guard",
"__stack_chk_fail",
""};
llvm::Module *module = modules[0];
// Enumerate the global variables.
for (llvm::Module::global_iterator iter = module->global_begin(); iter != module->global_end(); iter++) {
if (llvm::GlobalValue *gv = llvm::dyn_cast<llvm::GlobalValue>(iter)) {
// No variables are part of the public interface (even the ones labelled halide_)
llvm::GlobalValue::LinkageTypes t = gv->getLinkage();
if (t == llvm::GlobalValue::WeakAnyLinkage) {
gv->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
} else if (t == llvm::GlobalValue::WeakODRLinkage) {
gv->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
}
}
}
// Enumerate the functions.
for (llvm::Module::iterator iter = module->begin(); iter != module->end(); iter++) {
llvm::Function *f = (llvm::Function *)(iter);
bool can_strip = true;
for (size_t i = 0; !retain[i].empty(); i++) {
if (f->getName() == retain[i]) {
can_strip = false;
}
}
bool is_halide_extern_c_sym = Internal::starts_with(f->getName(), "halide_");
internal_assert(!is_halide_extern_c_sym || f->isWeakForLinker() || f->isDeclaration())
<< " for function " << (std::string)f->getName() << "\n";
can_strip = can_strip && !is_halide_extern_c_sym;
if (can_strip) {
llvm::GlobalValue::LinkageTypes t = f->getLinkage();
if (t == llvm::GlobalValue::WeakAnyLinkage) {
f->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
} else if (t == llvm::GlobalValue::WeakODRLinkage) {
f->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
}
}
}
// Now remove the force-usage global that prevented clang from
// dropping functions from the initial module.
llvm::GlobalValue *llvm_used = module->getNamedGlobal("llvm.used");
if (llvm_used) {
llvm_used->eraseFromParent();
}
}
}
namespace Internal {
/** When JIT-compiling on 32-bit windows, we need to rewrite calls
* to name-mangled win32 api calls to non-name-mangled versions.
*/
void undo_win32_name_mangling(llvm::Module *m) {
llvm::IRBuilder<> builder(m->getContext());
// For every function prototype...
for (llvm::Module::iterator iter = m->begin(); iter != m->end(); ++iter) {
llvm::Function *f = (llvm::Function *)(iter);
string n = f->getName();
// if it's a __stdcall call that starts with \01_, then we're making a win32 api call
if (f->getCallingConv() == llvm::CallingConv::X86_StdCall &&
f->empty() &&
n.size() > 2 && n[0] == 1 && n[1] == '_') {
// Unmangle the name.
string unmangled_name = n.substr(2);
size_t at = unmangled_name.rfind('@');
unmangled_name = unmangled_name.substr(0, at);
// Extern declare the unmangled version.
llvm::Function *unmangled = llvm::Function::Create(f->getFunctionType(), f->getLinkage(), unmangled_name, m);
unmangled->setCallingConv(f->getCallingConv());
// Add a body to the mangled version that calls the unmangled version.
llvm::BasicBlock *block = llvm::BasicBlock::Create(m->getContext(), "entry", f);
builder.SetInsertPoint(block);
vector<llvm::Value *> args;
for (llvm::Function::arg_iterator iter = f->arg_begin();
iter != f->arg_end(); ++iter) {
args.push_back(iter);
}
llvm::CallInst *c = builder.CreateCall(unmangled, args);
c->setCallingConv(f->getCallingConv());
if (f->getReturnType()->isVoidTy()) {
builder.CreateRetVoid();
} else {
builder.CreateRet(c);
}
}
}
}
void add_underscore_to_posix_call(llvm::CallInst *call, llvm::Function *fn, llvm::Module *m) {
string new_name = "_" + fn->getName().str();
llvm::Function *alt = m->getFunction(new_name);
if (!alt) {
alt = llvm::Function::Create(fn->getFunctionType(),
llvm::GlobalValue::ExternalLinkage,
new_name, m);
}
internal_assert(alt->getName() == new_name);
call->setCalledFunction(alt);
}
/** Windows uses _close, _open, _write, etc instead of the posix
* names. Defining stubs that redirect causes mis-compilations inside
* of mcjit, so we just rewrite uses of these functions to include an
* underscore. */
void add_underscores_to_posix_calls_on_windows(llvm::Module *m) {
string posix_fns[] = {"vsnprintf", "open", "close", "write"};
string *posix_fns_begin = posix_fns;
string *posix_fns_end = posix_fns + sizeof(posix_fns) / sizeof(posix_fns[0]);
for (llvm::Module::iterator iter = m->begin(); iter != m->end(); ++iter) {
for (llvm::Function::iterator f_iter = iter->begin(); f_iter != iter->end(); ++f_iter) {
for (llvm::BasicBlock::iterator b_iter = f_iter->begin(); b_iter != f_iter->end(); ++b_iter) {
llvm::Value *inst = (llvm::Value *)b_iter;
if (llvm::CallInst *call = llvm::dyn_cast<llvm::CallInst>(inst)) {
if (llvm::Function *fn = call->getCalledFunction()) {
if (std::find(posix_fns_begin, posix_fns_end, fn->getName()) != posix_fns_end) {
add_underscore_to_posix_call(call, fn, m);
}
}
}
}
}
}
}
/** Create an llvm module containing the support code for a given target. */
llvm::Module *get_initial_module_for_target(Target t, llvm::LLVMContext *c, bool for_shared_jit_runtime, bool just_gpu) {
enum InitialModuleType {
ModuleAOT,
ModuleJITShared,
ModuleJITInlined,
ModuleGPU
} module_type;
if (t.has_feature(Target::JIT)) {
if (just_gpu) {
module_type = ModuleGPU;
} else if (for_shared_jit_runtime) {
module_type = ModuleJITShared;
} else {
module_type = ModuleJITInlined;
}
} else {
module_type = ModuleAOT;
}
// Halide::Internal::debug(0) << "Getting initial module type " << (int)module_type << "\n";
internal_assert(t.bits == 32 || t.bits == 64);
// NaCl always uses the 32-bit runtime modules, because pointers
// and size_t are 32-bit in 64-bit NaCl, and that's the only way
// in which the 32- and 64-bit runtimes differ.
bool bits_64 = (t.bits == 64) && (t.os != Target::NaCl);
bool debug = t.has_feature(Target::Debug);
vector<llvm::Module *> modules;
if (module_type != ModuleGPU) {
if (module_type != ModuleJITInlined) {
// OS-dependent modules
if (t.os == Target::Linux) {
modules.push_back(get_initmod_linux_clock(c, bits_64, debug));
modules.push_back(get_initmod_posix_io(c, bits_64, debug));
modules.push_back(get_initmod_linux_host_cpu_count(c, bits_64, debug));
modules.push_back(get_initmod_posix_thread_pool(c, bits_64, debug));
modules.push_back(get_initmod_posix_get_symbol(c, bits_64, debug));
} else if (t.os == Target::OSX) {
modules.push_back(get_initmod_osx_clock(c, bits_64, debug));
modules.push_back(get_initmod_posix_io(c, bits_64, debug));
modules.push_back(get_initmod_gcd_thread_pool(c, bits_64, debug));
modules.push_back(get_initmod_osx_get_symbol(c, bits_64, debug));
} else if (t.os == Target::Android) {
modules.push_back(get_initmod_android_clock(c, bits_64, debug));
modules.push_back(get_initmod_android_io(c, bits_64, debug));
modules.push_back(get_initmod_android_host_cpu_count(c, bits_64, debug));
modules.push_back(get_initmod_posix_thread_pool(c, bits_64, debug));
modules.push_back(get_initmod_posix_get_symbol(c, bits_64, debug));
} else if (t.os == Target::Windows) {
modules.push_back(get_initmod_windows_clock(c, bits_64, debug));
modules.push_back(get_initmod_windows_io(c, bits_64, debug));
modules.push_back(get_initmod_windows_thread_pool(c, bits_64, debug));
modules.push_back(get_initmod_windows_get_symbol(c, bits_64, debug));
} else if (t.os == Target::IOS) {
modules.push_back(get_initmod_posix_clock(c, bits_64, debug));
modules.push_back(get_initmod_ios_io(c, bits_64, debug));
modules.push_back(get_initmod_gcd_thread_pool(c, bits_64, debug));
} else if (t.os == Target::NaCl) {
modules.push_back(get_initmod_posix_clock(c, bits_64, debug));
modules.push_back(get_initmod_posix_io(c, bits_64, debug));
modules.push_back(get_initmod_nacl_host_cpu_count(c, bits_64, debug));
modules.push_back(get_initmod_posix_thread_pool(c, bits_64, debug));
modules.push_back(get_initmod_ssp(c, bits_64, debug));
}
}
if (module_type != ModuleJITShared) {
// The first module for inline only case has to be C/C++ compiled otherwise the
// datalayout is not properly setup.
modules.push_back(get_initmod_posix_math(c, bits_64, debug));
// Math intrinsics vary slightly across platforms
if (t.os == Target::Windows && t.bits == 32) {
modules.push_back(get_initmod_win32_math_ll(c));
} else if (t.arch == Target::PNaCl) {
modules.push_back(get_initmod_pnacl_math_ll(c));
} else {
modules.push_back(get_initmod_posix_math_ll(c));
}
modules.push_back(get_initmod_destructors(c, bits_64, debug));
}
if (module_type != ModuleJITInlined) {
// These modules are always used and shared
modules.push_back(get_initmod_gpu_device_selection(c, bits_64, debug));
modules.push_back(get_initmod_tracing(c, bits_64, debug));
modules.push_back(get_initmod_write_debug_image(c, bits_64, debug));
modules.push_back(get_initmod_posix_allocator(c, bits_64, debug));
modules.push_back(get_initmod_posix_error_handler(c, bits_64, debug));
modules.push_back(get_initmod_posix_print(c, bits_64, debug));
modules.push_back(get_initmod_cache(c, bits_64, debug));
modules.push_back(get_initmod_to_string(c, bits_64, debug));
modules.push_back(get_initmod_device_interface(c, bits_64, debug));
modules.push_back(get_initmod_metadata(c, bits_64, debug));
}
if (module_type != ModuleJITShared) {
// These modules are optional
if (t.arch == Target::X86) {
modules.push_back(get_initmod_x86_ll(c));
}
if (t.arch == Target::ARM) {
if (t.bits == 64) {
modules.push_back(get_initmod_aarch64_ll(c));
} else if (t.has_feature(Target::ARMv7s)) {
modules.push_back(get_initmod_arm_ll(c));
} else if (!t.has_feature(Target::NoNEON)) {
modules.push_back(get_initmod_arm_ll(c));
} else {
modules.push_back(get_initmod_arm_no_neon_ll(c));
}
}
if (t.arch == Target::MIPS) {
modules.push_back(get_initmod_mips_ll(c));
}
if (t.has_feature(Target::SSE41)) {
modules.push_back(get_initmod_x86_sse41_ll(c));
}
if (t.has_feature(Target::AVX)) {
modules.push_back(get_initmod_x86_avx_ll(c));
}
}
}
if (module_type == ModuleJITShared || module_type == ModuleGPU) {
modules.push_back(get_initmod_module_jit_ref_count(c, bits_64, debug));
} else if (module_type == ModuleAOT) {
modules.push_back(get_initmod_module_aot_ref_count(c, bits_64, debug));
}
if (module_type == ModuleAOT || module_type == ModuleGPU) {
if (t.has_feature(Target::CUDA)) {
if (t.os == Target::Windows) {
modules.push_back(get_initmod_windows_cuda(c, bits_64, debug));
} else {
modules.push_back(get_initmod_cuda(c, bits_64, debug));
}
} else if (t.has_feature(Target::OpenCL)) {
if (t.os == Target::Windows) {
modules.push_back(get_initmod_windows_opencl(c, bits_64, debug));
} else {
modules.push_back(get_initmod_opencl(c, bits_64, debug));
}
} else if (t.has_feature(Target::OpenGL)) {
modules.push_back(get_initmod_opengl(c, bits_64, debug));
if (t.os == Target::Linux) {
modules.push_back(get_initmod_linux_opengl_context(c, bits_64, debug));
} else if (t.os == Target::OSX) {
modules.push_back(get_initmod_osx_opengl_context(c, bits_64, debug));
} else if (t.os == Target::Android) {
modules.push_back(get_initmod_android_opengl_context(c, bits_64, debug));
} else {
// You're on your own to provide definitions of halide_opengl_get_proc_address and halide_opengl_create_context
}
} else if (t.has_feature(Target::Renderscript)) {
modules.push_back(get_initmod_renderscript(c, bits_64, debug));
}
}
if (module_type == ModuleAOT && t.has_feature(Target::Matlab)) {
modules.push_back(get_initmod_matlab(c, bits_64, debug));
}
link_modules(modules);
if (t.os == Target::Windows &&
t.bits == 32 &&
(t.has_feature(Target::JIT))) {
undo_win32_name_mangling(modules[0]);
}
if (t.os == Target::Windows) {
add_underscores_to_posix_calls_on_windows(modules[0]);
}
return modules[0];
}
#ifdef WITH_PTX
llvm::Module *get_initial_module_for_ptx_device(Target target, llvm::LLVMContext *c) {
std::vector<llvm::Module *> modules;
modules.push_back(get_initmod_ptx_dev_ll(c));
llvm::Module *module;
// This table is based on the guidance at:
// http://docs.nvidia.com/cuda/libdevice-users-guide/basic-usage.html#linking-with-libdevice
if (target.has_feature(Target::CUDACapability35)) {
module = get_initmod_ptx_compute_35_ll(c);
} else if (target.features_any_of(vec(Target::CUDACapability32,
Target::CUDACapability50))) {
// For some reason sm_32 and sm_50 use libdevice 20
module = get_initmod_ptx_compute_20_ll(c);
} else if (target.has_feature(Target::CUDACapability30)) {
module = get_initmod_ptx_compute_30_ll(c);
} else {
module = get_initmod_ptx_compute_20_ll(c);
}
modules.push_back(module);
link_modules(modules);
// For now, the PTX backend does not handle calling functions. So mark all functions
// AvailableExternally to ensure they are inlined or deleted.
for (llvm::Module::iterator iter = modules[0]->begin(); iter != modules[0]->end(); iter++) {
llvm::Function *f = (llvm::Function *)(iter);
// This is intended to set all definitions (not extern declarations)
// to "available externally" which should guarantee they do not exist
// after the resulting module is finalized to code. That is they must
// be inlined to be used.
//
// However libdevice has a few routines that are marked
// "noinline" which must either be changed to alow inlining or
// preserved in generated code. This preserves the intent of
// keeping these routines out-of-line and hence called by
// not marking them AvailableExternally.
if (!f->isDeclaration() && !f->hasFnAttribute(llvm::Attribute::NoInline)) {
f->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
}
// Also mark the halide_gpu_thread_barrier as noduplicate.
#if LLVM_VERSION > 32
if (f->getName() == "halide_gpu_thread_barrier") {
f->addFnAttr(llvm::Attribute::NoDuplicate);
}
#endif
}
return modules[0];
}
#endif
#ifdef WITH_RENDERSCRIPT
llvm::Module *get_initial_module_for_renderscript_device(Target target, llvm::LLVMContext *c) {
return get_initmod_renderscript_dev_ll(c);
}
#endif
}
}
| [
"[email protected]"
] | |
0d3ccfe4f2b29268a33148a1cfa8bdd9df8a1582 | 155c4955c117f0a37bb9481cd1456b392d0e9a77 | /Tessa/TessaInstructions/InlineMethodInstruction.h | 06d791cf16dff05e06563e429b97f950180b74ac | [] | no_license | zwetan/tessa | 605720899aa2eb4207632700abe7e2ca157d19e6 | 940404b580054c47f3ced7cf8995794901cf0aaa | refs/heads/master | 2021-01-19T19:54:00.236268 | 2011-08-31T00:18:24 | 2011-08-31T00:18:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | h | namespace TessaInstructions {
class InlineMethodInstruction : public CallInstruction {
public:
InlineMethodInstruction(TessaInstruction* receiverObject, Traits* resultTraits, ArrayOfInstructions* arguments, uintptr_t methodId, MethodInfo* methodInfo, TessaVM::BasicBlock* insertAtEnd);
void visit(TessaVisitorInterface* tessaVisitor);
bool isInlineMethod();
};
} | [
"[email protected]"
] | |
1f11b886a8c7172d2fb37bd078c2f248305a06fc | 702b1e89e5212bf724af31beeec7a4d619ab4214 | /online/include/TcpConnection.h | 181d305254341ef8c7914f66179977a8603f0b80 | [] | no_license | a445116/searchEngine | 055d5678085a0b3ced10f3c7b7e7e1e180435715 | 8eeccb145d0884cb610284b87be64f5da0b6b47f | refs/heads/master | 2020-04-04T16:45:42.632009 | 2018-11-04T14:27:34 | 2018-11-04T14:27:34 | 156,092,306 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,400 | h | ///
/// @file TcpConnection.h
/// @author lemon([email protected])
/// @date 2018-07-31 17:14:47
///
#ifndef __ZCL_TCPCONNECTION_H__
#define __ZCL_TCPCONNECTION_H__
#include "Noncopyable.h"
#include "IntAddress.h"
#include "Socket.h"
#include "SocketIO.h"
#include <string>
#include <memory>
#include <functional>
namespace zcl
{
class EpollPoller;
class TcpConnection;
typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;
class TcpConnection
:Noncopyable,
public std::enable_shared_from_this<TcpConnection>
{
public:
typedef std::function<void(const TcpConnectionPtr &)>
TcpConnectionCallback;
TcpConnection(int sockfd, EpollPoller * loop);
~TcpConnection();
std::string receive();
void send(const std::string & msg);
void sendInLoop(const std::string & msg);
void shutdown();
std::string toString();
void setConnectionCallback(TcpConnectionCallback cb);
void setMessageCallback(TcpConnectionCallback cb);
void setCloseCallback(TcpConnectionCallback cb);
void handleConnectionCallback();
void handleMessageCallback();
void handleCloseCallback();
private:
Socket _sockfd;
SocketIO _sockIO;
const InetAddress _localAddr;
const InetAddress _peerAddr;
bool _isShutdownWrite;
EpollPoller * _loop;
TcpConnectionCallback _onConnectionCb;
TcpConnectionCallback _onMessageCb;
TcpConnectionCallback _onCloseCb;
};
}//end of namespace zcl
#endif
| [
"[email protected]"
] | |
fc11589bd323add471145ca93e76226f42a06e1d | ac9e5a2ad42b0bb657fa70c0700a5eefcb5265d2 | /patternBlending/repetendExtract.cpp | 76bf3e6f9cec0e4e118e0fe95c426086598ae363 | [] | no_license | Rosaniline/patternBlending | ed39530a0adb1679b500368829b675281941a6e9 | 11730137d689800832fd30705003e5d519012232 | refs/heads/master | 2020-05-17T21:55:00.830224 | 2013-06-24T14:45:14 | 2013-06-24T14:45:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,394 | cpp | //
// repetendExtract.cpp
// repetitionExtract
//
// Created by Rosani Lin on 13/5/6.
// Copyright (c) 2013年 Rosani Lin. All rights reserved.
//
#include "repetendExtract.h"
repetendExtract::repetendExtract() {};
repetendExtract::~repetendExtract() {};
bool aa(const element A, const element B) {
return A.min_radius < B.min_radius;
}
void repetendExtract::extract(tattingPattern tatting) {
// SIFTFeatureSaliency(pattern);
vector<vector<Point> > elements = extractElementBoundary(tatting);
vector<element> re_element;
for (int i = 0; i < elements.size(); i ++) {
if ( contourArea(elements[i]) > 20 ) {
element local_element = element(elements[i], tatting);
re_element.push_back(local_element);
}
}
Point centroid = tatting.centroid;//Point(296, 301);//getCentroid(src);
sort(re_element.begin(), re_element.end(), aa);
re_element.erase(re_element.begin());
Mat plot = Mat::zeros(tatting.pattern.size(), CV_8UC1);
int class_id_counter = 0;
for (int i = 0; i < re_element.size(); i ++) {
plot.setTo(0);
vector<int> similar_idx;
vector<int> temp_distance;
for (int j = 0; j < re_element.size(); j ++) {
if ( i != j && ((re_element[j].min_radius <= re_element[i].min_radius && re_element[j].max_radius > re_element[i].min_radius) || (re_element[j].min_radius >= re_element[i].min_radius && re_element[j].min_radius < re_element[i].max_radius ) ) ){
temp_distance.push_back(abs(re_element[i].area - re_element[j].area));
similar_idx.push_back(j);
// vector< vector<Point> > temp_contour;
// temp_contour.push_back(re_element[j].contour);
// drawContours(plot, temp_contour, 0, 100);
// vector< vector<Point> >().swap(temp_contour);
}
}
double dis_threshold = *min_element(temp_distance.begin(), temp_distance.end())*1.5;
for (int i = 0; i < similar_idx.size(); ) {
if ( temp_distance[i] > dis_threshold ) {
temp_distance.erase(temp_distance.begin() + i);
similar_idx.erase(similar_idx.begin() + i);
}
else {
i ++;
}
}
vector< vector<Point> > temp_contour;
temp_contour.push_back(re_element[i].contour);
drawContours(plot, temp_contour, 0, 255);
//
// if ( re_element[i].class_id == -1 ) {
//
// re_element[i].class_id = class_id_counter ++;
//
// cout<<"not found, assign id = "<<class_id_counter - 1;
// }
bool exist_found = false;
int exist_id = 0;
for (int k = 0; k < similar_idx.size(); k ++) {
if ( re_element[similar_idx[k]].class_id != -1 ) {
exist_found = true;
exist_id = re_element[similar_idx[k]].class_id;
break;
}
// vector< vector<Point> > temp_contour;
// temp_contour.push_back(re_element[similar_idx[k]].contour);
// drawContours(plot, temp_contour, 0, 100);
// vector< vector<Point> >().swap(temp_contour);
}
if ( exist_found ) {
for (int k = 0; k < similar_idx.size(); k ++) {
re_element[similar_idx[k]].class_id = exist_id;
}
re_element[i].class_id = exist_id;
}
else {
for (int k = 0; k < similar_idx.size(); k ++) {
re_element[similar_idx[k]].class_id = class_id_counter;
}
re_element[i].class_id = class_id_counter;
class_id_counter ++;
}
// showMat(plot, 0);
// vector< vector<Point> >().swap(temp_contour);
}
plot.setTo(0);
for (int i = 0; i < class_id_counter; i ++) {
for (int j = 0; j < re_element.size(); j ++) {
if ( re_element[j].class_id == i ) {
vector< vector<Point> > temp_contour;
temp_contour.push_back(re_element[j].contour);
drawContours(plot, temp_contour, 0, 255);
vector< vector<Point> >().swap(temp_contour);
}
}
}
// showMat(plot);
imwrite("/Users/xup6qup3/Desktop/t.jpg", plot);
// multimap<double, vector<Point> > concentrc_pt;
//
// for (int i = 0; i < elements.size(); i ++) {
//
// pair<double, vector<Point> > temp_pair;
//
// temp_pair.first = getElementRadius(elements[i], centroid);
// temp_pair.second = elements[i];
//
// concentrc_pt.insert(temp_pair);
//
// }
//
//
//
//
// Mat temp = Mat::zeros(pattern.getPattern().size(), CV_8UC1);
//
// for (multimap<double, vector<Point> >::iterator it = concentrc_pt.begin(); it != concentrc_pt.end(); it ++) {
//
// if ( contourArea(it->second) > 20 ) {
//
//
// for (int i = 0; i < it->second.size(); i ++) {
// temp.at<uchar>(it->second[i]) = 255;
// }
//
// showMat(temp, "t", 1);
// }
//
// }
//
// showMat(temp);
// for (int i = 0; i < elements.size(); i ++) {
//
// int min_idx = 0;
// double min_error = INFINITY;
//
// for (int j = 0; j < elements.size(); j ++) {
//
// if ( contourArea(elements[i]) > 20 && contourArea(elements[j]) > 20 && i != j ) {
//
// double local_error = matchShapes(elements[i], elements[j], CV_CONTOURS_MATCH_I1, 0);
//
// // cout<<local_error<<", ";
//
// if ( local_error < min_error ) {
//
// min_error = local_error;
// min_idx = j;
// }
// }
//
// }
//
// Mat temp = Mat::zeros(pattern.getPattern().size(), CV_8UC1);
//
// for (int j = 0; j < elements[i].size(); j ++) {
// temp.at<uchar>(elements[i][j]) = 255;
// }
//
// showMat(temp, "t1", 1);
//
// temp.setTo(0);
//
// cout<<min_idx<<endl;
//
// for (int j = 0; j < elements[min_idx].size(); j ++) {
// temp.at<uchar>(elements[min_idx][j]) = 255;
// }
//
// showMat(temp, "t2", 0);
// }
}
vector<vector<Point> > repetendExtract::extractElementBoundary(tattingPattern tatting) {
vector<vector<Point> > contours;
Mat src_temp = tatting.pattern.clone();
threshold(src_temp, src_temp, 0, 255, THRESH_OTSU);
findContours(src_temp, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);
src_temp.release();
return contours;
}
double repetendExtract::getElementRadius (const vector<Point> &element, const Point ¢roid) {
double avg_radius = 0.0;
for (int i = 0; i < element.size(); i ++) {
avg_radius += sqrt( pow(element[i].x - centroid.x, 2.0) + pow(element[i].y - centroid.y, 2.0) );
}
return avg_radius/element.size();
}
Point repetendExtract::getElementCentroid(const vector<Point> &element) {
Point centroid(0);
for (int i = 0; i < element.size(); i ++) {
centroid += element[i];
}
centroid.x /= element.size();
centroid.y /= element.size();
return centroid;
}
void repetendExtract::plotContour(cv::Mat &img, const vector<Point> &contour) {
for (int i = 0; i < contour.size(); i ++) {
img.at<uchar>(contour[i]) = 255;
}
}
void repetendExtract::SIFTFeatureSaliency(tattingPattern &tatting) {
/* threshold = 0.04;
edge_threshold = 10.0;
magnification = 3.0; */
// SIFT feature detector and feature extractor
cv::SiftFeatureDetector detector( 0.05, 5.0 );
cv::SiftDescriptorExtractor extractor( 3.0 );
/* In case of SURF, you apply the below two lines
cv::SurfFeatureDetector detector();
cv::SurfDescriptorExtractor extractor();
*/
// Feature detection
std::vector<KeyPoint> keypoints;
detector.detect( tatting.pattern, keypoints );
// Feature display
Mat temp = Mat::zeros(tatting.pattern.size(), CV_64FC1);
RNG rng = RNG();
vector<double> response;
for (int i = 0; i < keypoints.size(); i ++) {
response.push_back(keypoints[i].response);
}
double max_response = *max_element(response.begin(), response.end()), min_response = *min(response.begin(), response.end());
cout<<max_response<<", "<<min_response<<endl;
double threshold = (max_response - min_response)/10;
vector<double> similar_count;
for (int i = 0; i < response.size(); i ++) {
double local_count = 0;
Mat tt = tatting.pattern.clone();
tt -= 150;
for (int j = 0; j < response.size(); j ++) {
if ( i != j && abs(response[i] - response[j]) < threshold ) {
circle(tt, keypoints[j].pt, 5, 200, 1);
local_count ++;
}
}
circle(tt, keypoints[i].pt, 7, 255, 2);
// showMat(tt);
similar_count.push_back(local_count);
}
normalizeVector(similar_count);
for (int i = 0; i < similar_count.size(); i ++) {
// cout<<similar_count[i]<<", ";
// temp.at<double>(keypoints[i].pt) = similar_count[i];
circle(temp, keypoints[i].pt, 3, similar_count[i], 3);
}
// showMat(temp);
// double threshold = (*max_element(keypoint_res.begin(), keypoint_res.end()) - *min_element(keypoint_res.begin(), keypoint_res.end())) / 10;
// vector<int> cohere_count;
//
// for (int i = 0; i < keypoints.size(); i ++) {
//
// int cohere = 0;
//
// for (int j = 0; j < keypoints.size(); j ++) {
//
// if ( threshold > abs(keypoints[i].response - keypoints[j].response) ) {
// cohere ++;
// }
//
// }
//
// cohere_count.push_back(cohere);
//
// }
//
//
// for (int i = 0; i < cohere_count.size(); i ++) {
//
// int color = ((double)cohere_count[i] / *max_element(cohere_count.begin(), cohere_count.end()))*255;
//
// circle(temp, keypoints[i].pt, 3, CV_RGB(color, color, color), 3);
//
//
// }
// Mat gau_kernel = getGaussianKernel(23, 7.0);
//
// gau_kernel = gau_kernel*gau_kernel.t();
// s
// cout<<gau_kernel.size();
//
//
// for (int i = 0; i < keypoints1.size(); i ++) {
//
// for (int m = -gau_kernel.rows/2; m <= gau_kernel.rows/2; m ++) {
// for (int n = -gau_kernel.cols/2; n <= gau_kernel.cols/2; n ++) {
//
// temp.at<double>(keypoints1[i].pt.y + m, keypoints1[i].pt.x + n) += gau_kernel.at<double>(11 + m, 11 + n);
//
// }
// }
//
// }
//
//
// double max, min;
//
// minMaxIdx(temp, &min, &max);
//
// temp = (temp - min) / (max - min);
//
//
// Mat tt = pattern.getPattern().clone();
// tt.convertTo(tt, CV_64FC1);
// temp = temp + tt;
// showMat(temp);
}
| [
"[email protected]"
] | |
dcaab11bfb3f44b6df57821b8ad88333f0889cdd | 84524e09a9b167d2de8324b6af1dda07671afd10 | /MSN/expansion_penalty/expansion_penalty.cpp | bb7adc74231f1c4b6a24d433fb55640f86c871b0 | [
"Apache-2.0"
] | permissive | wangyida/softpool | 9c1844e60f2c3aca945f7b23298ac74c8849e2f8 | 31a2d18d0adfbeb14840a74c6bf30e90785c6258 | refs/heads/master | 2023-05-16T07:23:29.495658 | 2022-01-30T00:33:57 | 2022-01-30T00:33:57 | 210,187,897 | 72 | 6 | Apache-2.0 | 2021-03-02T16:52:46 | 2019-09-22T17:34:20 | Python | UTF-8 | C++ | false | false | 1,048 | cpp | #include <torch/extension.h>
#include <vector>
int expansion_penalty_cuda_forward(at::Tensor xyz, int primitive_size, at::Tensor father, at::Tensor dist, double alpha, at::Tensor neighbor, at::Tensor cost, at::Tensor mean_mst_length);
int expansion_penalty_cuda_backward(at::Tensor xyz, at::Tensor gradxyz, at::Tensor graddist, at::Tensor idx);
int expansion_penalty_forward(at::Tensor xyz, int primitive_size, at::Tensor father, at::Tensor dist, double alpha, at::Tensor neighbor, at::Tensor cost, at::Tensor mean_mst_length) {
return expansion_penalty_cuda_forward(xyz, primitive_size, father, dist, alpha, neighbor, cost, mean_mst_length);
}
int expansion_penalty_backward(at::Tensor xyz, at::Tensor gradxyz, at::Tensor graddist, at::Tensor idx) {
return expansion_penalty_cuda_backward(xyz, gradxyz, graddist, idx);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &expansion_penalty_forward, "expansion_penalty forward (CUDA)");
m.def("backward", &expansion_penalty_backward, "expansion_penalty backward (CUDA)");
} | [
"[email protected]"
] | |
63f85172e6ffb05beec15c4e982622a1f73e41fa | bcded75e01a396cd83d1541ba97632f8e87f463b | /src/main.cpp | 47945fa2f3affcd5dec253fc3834e63453c1a3d3 | [] | no_license | IvanGlebov/ESP8266_Watchdog | 30097787b6d42e50cb2accd036b941858ed7602f | 7dbdabfe7f59bfa0d6da74845a1afb43d0fbb957 | refs/heads/master | 2023-06-17T17:34:21.817923 | 2021-07-10T22:11:30 | 2021-07-10T22:11:30 | 371,633,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,000 | cpp | #include <Arduino.h>
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>
#include <EEPROM.h>
#define USE_LOCAL_SERVER true
// Пин для проверки "живости" мастера
#define master_pin D8
#define master_reboot_pin D1
#define blynkMasterAlivePin V10
#define check_delay 20 // Задержка проверки мастера в секундах
// Локальный ключ.
char auth[] = "qD_9-u6CLaII9eHjmrR_JJw4OZimugzQ";
// Боевой ключ
// char auth[] = "9-KQWyfz0hoNqhtdCl7_o4ukSJyE6Byr";
char ssid_prod[] = "Farm_router"; // prod
char ssid_local[] = "Keenetic-4926"; // home
char pass_prod[] = "zqecxwrv123"; // prod
char pass_local[] = "Q4WmFQTa"; // home
int reboot_counter;
long master_check;
bool down_flag = false;
bool watch_after_master = false;
// bool first_start_flag = true;
WidgetTerminal terminal(V0);
WidgetRTC rtc;
// Пин для терминала - V0
// Пин дл таблички - V86
// Пин для сброса таблички - V87
enum timeShowModes
{
timestamp = 1,
hms
};
class logger
{
private:
char workMode = 'M';
char messageType = 'S';
int messageNumber = 0;
bool sendToTerminal = true;
bool sendToTable = true;
bool showLogs = true;
long time = 0;
int timeShowMode = hms;
public:
logger(char workmode, char messagetype, bool sendtoterminal, bool showlogs) : workMode(workmode), messageType(messagetype), messageNumber(0), sendToTerminal(sendtoterminal), showLogs(showlogs){};
void setLogsState(bool state, int logType);
void setMode(char mode) { workMode = mode; }
void setType(char type) { messageType = type; }
void print(String text);
void println(String text);
void setTimestamp(long timestamp) { time = timestamp; }
void setTimeShowMode(int mode) { timeShowMode = (mode == timestamp) ? 1 : 2; }
};
void logger::println(String text)
{
String output;
String timeStr = (timeShowMode != hms) ? String(time) : String(time / 3600) + ":" + String(time % 3600 / 60) + ":" + String(time % 60);
output += "<" + String(timeStr) + "> " + "[" + String(workMode) + String(messageType) + "_" + String(messageNumber) + "] ";
output += text;
if (showLogs)
{
if (sendToTerminal == true)
{
terminal.println(output);
terminal.flush();
}
if (sendToTable == true)
{
Blynk.virtualWrite(V86, "add", messageNumber, text, timeStr);
}
Serial.println(output);
}
messageNumber++;
}
void logger::print(String text)
{
String output;
String timeStr = (timeShowMode != hms) ? String(time) : String(time / 3600) + ":" + String(time % 3600 / 60) + ":" + String(time % 60);
output += "<" + String(timeStr) + "> " + "[" + String(workMode) + String(messageType) + "_" + String(messageNumber) + "] ";
output += text;
if (showLogs)
{
if (sendToTerminal == true)
{
terminal.print(output);
terminal.flush();
}
Serial.print(output);
}
messageNumber++;
}
// Сброс таблицы логов
BLYNK_WRITE(V87)
{
int a = param.asInt();
if (a == 1)
{
Blynk.virtualWrite(V86, "clr");
}
}
logger logg('M', 'S', true, true);
void reboot_master();
BLYNK_CONNECTED()
{
rtc.begin();
}
// Количество перезагрузок
BLYNK_WRITE(V1)
{
int a = param.asInt();
reboot_counter = a;
}
// Перезапустить мастера
BLYNK_WRITE(V2)
{
int a = param.asInt();
if (a == 1)
{
long curr_time = hour() * 3600 + minute() * 60 + second();
logg.setTimestamp(curr_time);
logg.setMode('M');
logg.setType('S');
logg.println("Rebooting master");
reboot_master();
}
}
// Сбросить перезапуски
BLYNK_WRITE(V3)
{
int a = param.asInt();
if (a == 1)
{
long curr_time = hour() * 3600 + minute() * 60 + second();
logg.setTimestamp(curr_time);
logg.setMode('M');
logg.println("Master reboots dropped");
}
}
// Флаг слежения за мастером
BLYNK_WRITE(V4)
{
int a = param.asInt();
if (a == 1)
{
long curr_time = hour() * 3600 + minute() * 60 + second();
logg.setTimestamp(curr_time);
logg.setMode('M');
logg.println("Now I'm watching after master");
watch_after_master = true;
}
else
{
long curr_time = hour() * 3600 + minute() * 60 + second();
logg.setTimestamp(curr_time);
logg.setMode('M');
logg.println("Master is free now");
watch_after_master = false;
}
}
BlynkTimer checkMasterTimer;
// Специальная переменная, которая будет увеличиваться каждые 2 секунды.
// Если она перевалит указанное заранее значение, то мастер будет отправлен в ребут
int masterCalls = 0;
void increaseTimer() {
masterCalls++;
if (masterCalls % 5 == 0){
Blynk.virtualWrite(blynkMasterAlivePin, 2);
}
Serial.println("Master calls: " + String(masterCalls));
if (masterCalls >= 20) {
masterCalls = 0;
reboot_master();
}
}
void dropMasterChecks(){
Serial.println("Master is alive");
Blynk.virtualWrite(blynkMasterAlivePin, 1);
masterCalls = 0;
}
void setup()
{
EEPROM.begin(5);
Serial.begin(115200);
pinMode(master_pin, INPUT);
pinMode(master_reboot_pin, OUTPUT);
digitalWrite(master_reboot_pin, LOW);
// Если на пине D7 был получен высокий сигнал от мастера, то дропаем флаг
// attachInterrupt(D7, dropMasterChecks, CHANGE);
reboot_counter = EEPROM.read(1);
// Показывать как обычное вермя. Если нужна метка, то режим timestamp
logg.setTimeShowMode(hms);
checkMasterTimer.setInterval(2000L, increaseTimer);
if (USE_LOCAL_SERVER)
{
Blynk.begin(auth, ssid_local, pass_local, IPAddress(192, 168, 1, 106), 8080);
}
else
{
Blynk.begin(auth, ssid_prod, pass_prod, IPAddress(10, 1, 92, 35), 8080);
}
}
void loop()
{
Blynk.run();
checkMasterTimer.run();
// Ребут после полуночи
if ((20 < (hour()*3600 + minute()*60 + second())) && ((hour()*3600 + minute()*60 + second()) < 30))
{
reboot_master();
}
if (digitalRead(master_pin) == HIGH) {
dropMasterChecks();
}
// Если надо следить за мастером, то бдим
// if (watch_after_master)
// {
// long curr_time = hour() * 3600 + minute() * 60 + second();
// // Проверить жив ли мастер
// if (digitalRead(master_pin) == HIGH)
// {
// down_flag = false;
// }
// // Если мастер упал и это произошло только сейчас то добавим ребут и ждём оживления n секунд,
// // если мастер всё ещё мёртв, то добавляем в счётчик ребута ещё 1 и посылаем сигнал ребута
// if (digitalRead(master_pin) == LOW && down_flag == false)
// {
// master_check = curr_time + check_delay;
// reboot_counter++;
// down_flag = true;
// logg.setTimestamp(curr_time);
// logg.setMode('A');
// logg.setType('E');
// logg.println("Master is down!");
// }
// if (curr_time - 2 < master_check && master_check < curr_time + 2)
// {
// reboot_counter++;
// logg.setTimestamp(curr_time);
// logg.setMode('A');
// logg.setType('E');
// logg.println("Master forced reboot!");
// reboot_master();
// delay(500);
// if (digitalRead(master_pin) == HIGH)
// {
// down_flag = false;
// }
// }
// }
}
void reboot_master()
{
digitalWrite(master_reboot_pin, HIGH);
delay(100);
// digitalWrite(master_reboot_pin, );
digitalWrite(master_reboot_pin, LOW);
reboot_counter++;
Blynk.virtualWrite(V1, reboot_counter);
EEPROM.write(1, reboot_counter);
EEPROM.commit();
} | [
"[email protected]"
] | |
3e0f84024df0363e51f445f27bbadef13a0fb2b0 | ed08b1308bdb5b21bea8e2fc58e7d03eb82df016 | /src/blocksignature.cpp | 383be17175e17adedb6ffd33c93e20e58a2faf1b | [
"MIT"
] | permissive | ygtars/geacoinold | b31e946601aeec3223ddfd1fa5a98804844a0ffc | 142a16fa81f5c255d923d274fb0094d8c21a3d28 | refs/heads/master | 2020-04-15T18:56:32.159141 | 2019-01-14T18:01:02 | 2019-01-14T18:01:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,954 | cpp | // Copyright (c) 2017-2018 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "blocksignature.h"
#include "main.h"
#include "zgeachain.h"
bool SignBlockWithKey(CBlock& block, const CKey& key)
{
if (!key.Sign(block.GetHash(), block.vchBlockSig))
return error("%s: failed to sign block hash with key", __func__);
return true;
}
bool GetKeyIDFromUTXO(const CTxOut& txout, CKeyID& keyID)
{
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY) {
keyID = CPubKey(vSolutions[0]).GetID();
} else if (whichType == TX_PUBKEYHASH) {
keyID = CKeyID(uint160(vSolutions[0]));
}
return true;
}
bool SignBlock(CBlock& block, const CKeyStore& keystore)
{
CKeyID keyID;
if (block.IsProofOfWork()) {
bool fFoundID = false;
for (const CTxOut& txout :block.vtx[0].vout) {
if (!GetKeyIDFromUTXO(txout, keyID))
continue;
fFoundID = true;
break;
}
if (!fFoundID)
return error("%s: failed to find key for PoW", __func__);
} else {
if (!GetKeyIDFromUTXO(block.vtx[1].vout[1], keyID))
return error("%s: failed to find key for PoS", __func__);
}
CKey key;
if (!keystore.GetKey(keyID, key))
return error("%s: failed to get key from keystore", __func__);
return SignBlockWithKey(block, key);
}
bool CheckBlockSignature(const CBlock& block)
{
if (block.IsProofOfWork())
return block.vchBlockSig.empty();
if (block.vchBlockSig.empty())
return error("%s: vchBlockSig is empty!", __func__);
/** Each block is signed by the private key of the input that is staked. This can be either zGEA or normal UTXO
* zGEA: Each zGEA has a keypair associated with it. The serial number is a hash of the public key.
* UTXO: The public key that signs must match the public key associated with the first utxo of the coinstake tx.
*/
CPubKey pubkey;
bool fzGEAStake = block.vtx[1].IsZerocoinSpend();
if (fzGEAStake) {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(block.vtx[1].vin[0]);
pubkey = spend.getPubKey();
} else {
txnouttype whichType;
std::vector<valtype> vSolutions;
const CTxOut& txout = block.vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY || whichType == TX_PUBKEYHASH) {
valtype& vchPubKey = vSolutions[0];
pubkey = CPubKey(vchPubKey);
}
}
if (!pubkey.IsValid())
return error("%s: invalid pubkey %s", __func__, pubkey.GetHex());
return pubkey.Verify(block.GetHash(), block.vchBlockSig);
} | [
"[email protected]"
] | |
9d9e59a6b7aa60956d69e76717d36c16fa053a9d | fe2362eda423bb3574b651c21ebacbd6a1a9ac2a | /VTK-7.1.1/Common/DataModel/vtkQuadraticTriangle.cxx | c4adff94be5cd33bd2b2a4cd6ca5120f6927ab10 | [
"BSD-3-Clause"
] | permissive | likewatchk/python-pcl | 1c09c6b3e9de0acbe2f88ac36a858fe4b27cfaaf | 2a66797719f1b5af7d6a0d0893f697b3786db461 | refs/heads/master | 2023-01-04T06:17:19.652585 | 2020-10-15T21:26:58 | 2020-10-15T21:26:58 | 262,235,188 | 0 | 0 | NOASSERTION | 2020-05-08T05:29:02 | 2020-05-08T05:29:01 | null | UTF-8 | C++ | false | false | 13,299 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkQuadraticTriangle.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
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 "vtkQuadraticTriangle.h"
#include "vtkObjectFactory.h"
#include "vtkMath.h"
#include "vtkLine.h"
#include "vtkQuadraticEdge.h"
#include "vtkTriangle.h"
#include "vtkDoubleArray.h"
#include "vtkPoints.h"
vtkStandardNewMacro(vtkQuadraticTriangle);
//----------------------------------------------------------------------------
// Construct the line with two points.
vtkQuadraticTriangle::vtkQuadraticTriangle()
{
this->Edge = vtkQuadraticEdge::New();
this->Face = vtkTriangle::New();
this->Scalars = vtkDoubleArray::New();
this->Scalars->SetNumberOfTuples(3);
this->Points->SetNumberOfPoints(6);
this->PointIds->SetNumberOfIds(6);
for (int i = 0; i < 6; i++)
{
this->Points->SetPoint(i, 0.0, 0.0, 0.0);
this->PointIds->SetId(i,0);
}
}
//----------------------------------------------------------------------------
vtkQuadraticTriangle::~vtkQuadraticTriangle()
{
this->Edge->Delete();
this->Face->Delete();
this->Scalars->Delete();
}
//----------------------------------------------------------------------------
vtkCell *vtkQuadraticTriangle::GetEdge(int edgeId)
{
edgeId = (edgeId < 0 ? 0 : (edgeId > 2 ? 2 : edgeId ));
int p = (edgeId+1) % 3;
// load point id's
this->Edge->PointIds->SetId(0,this->PointIds->GetId(edgeId));
this->Edge->PointIds->SetId(1,this->PointIds->GetId(p));
this->Edge->PointIds->SetId(2,this->PointIds->GetId(edgeId+3));
// load coordinates
this->Edge->Points->SetPoint(0,this->Points->GetPoint(edgeId));
this->Edge->Points->SetPoint(1,this->Points->GetPoint(p));
this->Edge->Points->SetPoint(2,this->Points->GetPoint(edgeId+3));
return this->Edge;
}
//----------------------------------------------------------------------------
// order picked carefully for parametric coordinate conversion
static int LinearTris[4][3] = { {0,3,5}, {3, 1,4}, {5,4,2}, {4,5,3} };
int vtkQuadraticTriangle::EvaluatePosition(double* x, double* closestPoint,
int& subId, double pcoords[3],
double& minDist2, double *weights)
{
double pc[3], dist2;
int ignoreId, i, returnStatus=0, status;
double tempWeights[3];
double closest[3];
//four linear triangles are used
for (minDist2=VTK_DOUBLE_MAX, i=0; i < 4; i++)
{
this->Face->Points->SetPoint(
0,this->Points->GetPoint(LinearTris[i][0]));
this->Face->Points->SetPoint(
1,this->Points->GetPoint(LinearTris[i][1]));
this->Face->Points->SetPoint(
2,this->Points->GetPoint(LinearTris[i][2]));
status = this->Face->EvaluatePosition(x,closest,ignoreId,pc,dist2,
tempWeights);
if ( status != -1 && dist2 < minDist2 )
{
returnStatus = status;
minDist2 = dist2;
subId = i;
pcoords[0] = pc[0];
pcoords[1] = pc[1];
}
}
// adjust parametric coordinates
if ( returnStatus != -1 )
{
if ( subId == 0 )
{
pcoords[0] /= 2.0;
pcoords[1] /= 2.0;
}
else if ( subId == 1 )
{
pcoords[0] = 0.5 + (pcoords[0]/2.0);
pcoords[1] /= 2.0;
}
else if ( subId == 2 )
{
pcoords[0] /= 2.0;
pcoords[1] = 0.5 + (pcoords[1]/2.0);
}
else
{
pcoords[0] = 0.5 - pcoords[0]/2.0;
pcoords[1] = 0.5 - pcoords[1]/2.0;
}
pcoords[2] = 0.0;
if(closestPoint!=0)
{
// Compute both closestPoint and weights
this->EvaluateLocation(subId,pcoords,closestPoint,weights);
}
else
{
// Compute weights only
this->InterpolationFunctions(pcoords,weights);
}
}
return returnStatus;
}
//----------------------------------------------------------------------------
void vtkQuadraticTriangle::EvaluateLocation(int& vtkNotUsed(subId),
double pcoords[3],
double x[3], double *weights)
{
int i;
double a0[3], a1[3], a2[3], a3[3], a4[3], a5[3];
this->Points->GetPoint(0, a0);
this->Points->GetPoint(1, a1);
this->Points->GetPoint(2, a2);
this->Points->GetPoint(3, a3);
this->Points->GetPoint(4, a4);
this->Points->GetPoint(5, a5);
this->InterpolationFunctions(pcoords,weights);
for (i=0; i<3; i++)
{
x[i] = a0[i]*weights[0] + a1[i]*weights[1] + a2[i]*weights[2] +
a3[i]*weights[3] + a4[i]*weights[4] + a5[i]*weights[5];
}
}
//----------------------------------------------------------------------------
int vtkQuadraticTriangle::CellBoundary(int subId, double pcoords[3],
vtkIdList *pts)
{
return this->Face->CellBoundary(subId, pcoords, pts);
}
//----------------------------------------------------------------------------
void vtkQuadraticTriangle::Contour(double value,
vtkDataArray* cellScalars,
vtkIncrementalPointLocator* locator,
vtkCellArray *verts,
vtkCellArray* lines,
vtkCellArray* polys,
vtkPointData* inPd,
vtkPointData* outPd,
vtkCellData* inCd,
vtkIdType cellId,
vtkCellData* outCd)
{
for ( int i=0; i < 4; i++)
{
this->Face->Points->SetPoint(0,this->Points->GetPoint(LinearTris[i][0]));
this->Face->Points->SetPoint(1,this->Points->GetPoint(LinearTris[i][1]));
this->Face->Points->SetPoint(2,this->Points->GetPoint(LinearTris[i][2]));
if ( outPd )
{
this->Face->PointIds->SetId(0,this->PointIds->GetId(LinearTris[i][0]));
this->Face->PointIds->SetId(1,this->PointIds->GetId(LinearTris[i][1]));
this->Face->PointIds->SetId(2,this->PointIds->GetId(LinearTris[i][2]));
}
this->Scalars->SetTuple(0,cellScalars->GetTuple(LinearTris[i][0]));
this->Scalars->SetTuple(1,cellScalars->GetTuple(LinearTris[i][1]));
this->Scalars->SetTuple(2,cellScalars->GetTuple(LinearTris[i][2]));
this->Face->Contour(value, this->Scalars, locator, verts,
lines, polys, inPd, outPd, inCd, cellId, outCd);
}
}
//----------------------------------------------------------------------------
// Line-line intersection. Intersection has to occur within [0,1] parametric
// coordinates and with specified tolerance.
int vtkQuadraticTriangle::IntersectWithLine(double* p1,
double* p2,
double tol,
double& t,
double* x,
double* pcoords,
int& subId)
{
int subTest, i;
subId = 0;
for (i=0; i < 4; i++)
{
this->Face->Points->SetPoint(0,this->Points->GetPoint(LinearTris[i][0]));
this->Face->Points->SetPoint(1,this->Points->GetPoint(LinearTris[i][1]));
this->Face->Points->SetPoint(2,this->Points->GetPoint(LinearTris[i][2]));
if (this->Face->IntersectWithLine(p1, p2, tol, t, x, pcoords, subTest) )
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkQuadraticTriangle::Triangulate(int vtkNotUsed(index), vtkIdList *ptIds,
vtkPoints *pts)
{
pts->Reset();
ptIds->Reset();
// Create four linear triangles
for ( int i=0; i < 4; i++)
{
ptIds->InsertId(3*i,this->PointIds->GetId(LinearTris[i][0]));
pts->InsertPoint(3*i,this->Points->GetPoint(LinearTris[i][0]));
ptIds->InsertId(3*i+1,this->PointIds->GetId(LinearTris[i][1]));
pts->InsertPoint(3*i+1,this->Points->GetPoint(LinearTris[i][1]));
ptIds->InsertId(3*i+2,this->PointIds->GetId(LinearTris[i][2]));
pts->InsertPoint(3*i+2,this->Points->GetPoint(LinearTris[i][2]));
}
return 1;
}
//----------------------------------------------------------------------------
void vtkQuadraticTriangle::Derivatives(int vtkNotUsed(subId),
double vtkNotUsed(pcoords)[3],
double *vtkNotUsed(values),
int vtkNotUsed(dim),
double *vtkNotUsed(derivs))
{
}
//----------------------------------------------------------------------------
// Clip this quadratic triangle using the scalar value provided. Like
// contouring, except that it cuts the triangle to produce other quads
// and triangles.
void vtkQuadraticTriangle::Clip(double value,
vtkDataArray* cellScalars,
vtkIncrementalPointLocator* locator,
vtkCellArray* polys,
vtkPointData* inPd,
vtkPointData* outPd,
vtkCellData* inCd,
vtkIdType cellId,
vtkCellData* outCd,
int insideOut)
{
for ( int i=0; i < 4; i++)
{
this->Face->Points->SetPoint(0,this->Points->GetPoint(LinearTris[i][0]));
this->Face->Points->SetPoint(1,this->Points->GetPoint(LinearTris[i][1]));
this->Face->Points->SetPoint(2,this->Points->GetPoint(LinearTris[i][2]));
this->Face->PointIds->SetId(0,this->PointIds->GetId(LinearTris[i][0]));
this->Face->PointIds->SetId(1,this->PointIds->GetId(LinearTris[i][1]));
this->Face->PointIds->SetId(2,this->PointIds->GetId(LinearTris[i][2]));
this->Scalars->SetTuple(0,cellScalars->GetTuple(LinearTris[i][0]));
this->Scalars->SetTuple(1,cellScalars->GetTuple(LinearTris[i][1]));
this->Scalars->SetTuple(2,cellScalars->GetTuple(LinearTris[i][2]));
this->Face->Clip(value, this->Scalars, locator, polys, inPd, outPd,
inCd, cellId, outCd, insideOut);
}
}
//----------------------------------------------------------------------------
// Compute maximum parametric distance to cell
double vtkQuadraticTriangle::GetParametricDistance(double pcoords[3])
{
int i;
double pDist, pDistMax=0.0;
double pc[3];
pc[0] = pcoords[0];
pc[1] = pcoords[1];
pc[2] = 1.0 - pcoords[0] - pcoords[1];
for (i=0; i<3; i++)
{
if ( pc[i] < 0.0 )
{
pDist = -pc[i];
}
else if ( pc[i] > 1.0 )
{
pDist = pc[i] - 1.0;
}
else //inside the cell in the parametric direction
{
pDist = 0.0;
}
if ( pDist > pDistMax )
{
pDistMax = pDist;
}
}
return pDistMax;
}
//----------------------------------------------------------------------------
// Compute interpolation functions. The first three nodes are the triangle
// vertices; the others are mid-edge nodes.
void vtkQuadraticTriangle::InterpolationFunctions(double pcoords[3],
double weights[6])
{
double r = pcoords[0];
double s = pcoords[1];
double t = 1.0 - r - s;
weights[0] = t*(2.0*t - 1.0);
weights[1] = r*(2.0*r - 1.0);
weights[2] = s*(2.0*s - 1.0);
weights[3] = 4.0 * r * t;
weights[4] = 4.0 * r * s;
weights[5] = 4.0 * s * t;
}
//----------------------------------------------------------------------------
// Derivatives in parametric space.
void vtkQuadraticTriangle::InterpolationDerivs(double pcoords[3],
double derivs[12])
{
double r = pcoords[0];
double s = pcoords[1];
// r-derivatives
derivs[0] = 4.0*r + 4.0*s - 3.0;
derivs[1] = 4.0*r - 1.0;
derivs[2] = 0.0;
derivs[3] = 4.0 - 8.0*r - 4.0*s;
derivs[4] = 4.0*s;
derivs[5] = -4.0*s;
// s-derivatives
derivs[6] = 4.0*r + 4.0*s - 3.0;
derivs[7] = 0.0;
derivs[8] = 4.0*s - 1.0;
derivs[9] = -4.0*r;
derivs[10] = 4.0*r;
derivs[11] = 4.0 - 8.0*s - 4.0*r;
}
//----------------------------------------------------------------------------
static double vtkQTriangleCellPCoords[18] = {
0.0,0.0,0.0, 1.0,0.0,0.0, 0.0,1.0,0.0,
0.5,0.0,0.0, 0.5,0.5,0.0, 0.0,0.5,0.0};
double *vtkQuadraticTriangle::GetParametricCoords()
{
return vtkQTriangleCellPCoords;
}
//----------------------------------------------------------------------------
void vtkQuadraticTriangle::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Edge:\n";
this->Edge->PrintSelf(os,indent.GetNextIndent());
os << indent << "Edge:\n";
this->Edge->PrintSelf(os,indent.GetNextIndent());
os << indent << "Scalars:\n";
this->Scalars->PrintSelf(os,indent.GetNextIndent());
}
| [
"[email protected]"
] | |
beee4101fef87894a846d3ca90f6bf44ab67efdf | c0caed81b5b3e1498cbca4c1627513c456908e38 | /src/core/scoring/rna/RNA_ScoringInfo.fwd.hh | 1eba13f0c2d445f7732ad96f65cbc5010cf18d90 | [] | no_license | malaifa/source | 5b34ac0a4e7777265b291fc824da8837ecc3ee84 | fc0af245885de0fb82e0a1144422796a6674aeae | refs/heads/master | 2021-01-19T22:10:22.942155 | 2017-04-19T14:13:07 | 2017-04-19T14:13:07 | 88,761,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington UW TechTransfer, email: [email protected].
/// @file core/scoring/methods/RNA_BaseBasePotential.hh
/// @brief Statistically derived rotamer pair potential class implementation
/// @author Phil Bradley
/// @author Andrew Leaver-Fay
#ifndef INCLUDED_core_scoring_rna_RNA_ScoringInfo_fwd_hh
#define INCLUDED_core_scoring_rna_RNA_ScoringInfo_fwd_hh
// Project headers
// Utility headers
#include <utility/pointer/access_ptr.hh>
#include <utility/pointer/owning_ptr.hh>
// C++
namespace core {
namespace scoring {
namespace rna {
class RNA_ScoringInfo;
typedef utility::pointer::shared_ptr< RNA_ScoringInfo > RNA_ScoringInfoOP;
} //rna
} //scoring
} //core
#endif
| [
"[email protected]"
] | |
6d5793adee7fc0031b77363f79935b281e43fec9 | 599709e7687a78f92b268315590d6ad750ce97d6 | /math/nderiv.hpp | 361fd58e4248b3800c18a12ebb7d11180afcb6a7 | [] | no_license | ReiMatsuzaki/cbasis2 | b99d096150d87f9301ed0e34f7be5f0203e4a81e | 86f21146fab6fc6f750d02fb2200ea94616ca896 | refs/heads/master | 2021-01-19T23:15:32.864686 | 2017-04-27T07:29:26 | 2017-04-27T07:29:26 | 88,953,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | hpp | #include <boost/function.hpp>
namespace cbasis {
typedef boost::function<dcomplex (dcomplex)> CFunc;
dcomplex NDerivOne_R1(CFunc f, dcomplex x, dcomplex h);
dcomplex NDerivOne_C1(CFunc f, dcomplex x, dcomplex h);
dcomplex NDerivOne_R3(CFunc f, dcomplex x, dcomplex h);
dcomplex NDerivTwo_R1(CFunc f, dcomplex x, dcomplex h);
dcomplex NDerivTwo_C1(CFunc f, dcomplex x, dcomplex h);
dcomplex NDerivTwo_R3(CFunc f, dcomplex x, dcomplex h);
}
| [
"[email protected]"
] | |
f98cd0897b70dcae9c7f01dfc8d901271c31b50f | 3a1beda58ab673e42ec32d143bcdfd68ccbefd4d | /Lab04/main.cpp | 1b25568d4bd4cb54495b401c8414b3c41460ede4 | [] | no_license | piotrmoszkowicz-wfiis/WFiIS-IMN-2019 | 57b695972fcc747bc9b4243f7a8ad3b7ead3839c | 14a525e9f8d61d986a7b4a5dff0d42c0eb8ebbe4 | refs/heads/master | 2020-09-05T20:52:13.310113 | 2019-12-10T20:21:44 | 2019-12-10T20:21:44 | 220,211,412 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 7,172 | cpp | //
// Created by Piotr Moszkowicz on 27/11/2019.
//
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include "../utils/files_operations.h"
double firstDensity(double x, double y, double x_max, double y_max, double sigma_x, double sigma_y) {
return std::exp((-1.0 * std::pow(x - 0.35 * x_max, 2) / std::pow(sigma_x, 2)) -
(std::pow(y - 0.5 * y_max, 2) / std::pow(sigma_y, 2)));
}
double secondDensity(double x, double y, double x_max, double y_max, double sigma_x, double sigma_y) {
return -1.0 * std::exp((-1.0 * std::pow(x - 0.65 * x_max, 2) / std::pow(sigma_x, 2)) -
(std::pow(y - 0.5 * y_max, 2) / std::pow(sigma_y, 2)));
}
double finalDensity(double x, double y, double x_max, double y_max, double sigma_x, double sigma_y) {
return firstDensity(x, y, x_max, y_max, sigma_x, sigma_y) + secondDensity(x, y, x_max, y_max, sigma_x, sigma_y);
}
double countGlobal(double v_ip1_j, double v_im1_j, double v_i_jp1, double v_i_jm1, double delta, double epsilon,
double density) {
return 0.25 * (v_ip1_j + v_im1_j + v_i_jp1 + v_i_jm1 + density * std::pow(delta, 2) / epsilon);
}
double countStop(std::vector<std::vector<double>> &n, double delta, std::vector<std::vector<double>> &density, int N_X,
int N_Y) {
double s = 0.0;
for (int i = 0; i < N_X; i++) {
for (int j = 0; j < N_Y; j++) {
s += std::pow(delta, 2) *
(0.5 * std::pow((n[i + 1][j] - n[i][j]) / delta, 2) +
0.5 * std::pow((n[i][j + 1] - n[i][j]) / delta, 2) -
(density[i][j] * n[i][j]));
}
}
return s;
}
double
countLocal(double omega_l, double v_i_j, double v_ip1_j, double v_im1_j, double v_i_jp1, double v_i_jm1, double delta,
double epsilon,
double density) {
return (1.0 - omega_l) * v_i_j + (0.25 * omega_l) *
(v_ip1_j + v_im1_j + v_i_jp1 + v_i_jm1 + (std::pow(delta, 2) / epsilon) * density);
}
double
countErr(double v_ip1_j, double v_i_j, double v_im1_j, double v_i_jp1, double v_i_jm1, double delta, double density,
double epsilon) {
return ((v_ip1_j - 2.0 * v_i_j + v_im1_j) / std::pow(delta, 2) +
(v_i_jp1 - 2.0 * v_i_j + v_i_jm1) / (std::pow(delta, 2))) + density / epsilon;
}
void relaksacjaGlobalna() {
auto omega = std::vector<double>{
0.6, 1.0
};
const double TOL = std::pow(10, -8);
constexpr double EPSILON = 1.0;
constexpr double DELTA = 0.1;
constexpr int N_X = 150;
constexpr int N_Y = 100;
constexpr double V_1 = 10.0;
constexpr double X_MAX = DELTA * N_X;
constexpr double Y_MAX = DELTA * N_Y;
constexpr double SIGMA_X = 0.1 * X_MAX;
constexpr double SIGMA_Y = 0.1 * Y_MAX;
for (auto o : omega) {
std::string fileNameRes = "1_global_";
std::string fileNameGrid = "1_global_";
std::string fileNameErr = "1_global_";
fileNameRes += std::to_string(o) + "_res.dat";
fileNameGrid += std::to_string(o) + "_grid.dat";
fileNameErr += std::to_string(o) + "_err.dat";
clearFile(fileNameRes);
clearFile(fileNameGrid);
clearFile(fileNameErr);
std::vector<std::vector<double>> density(N_X + 1);
std::vector<std::vector<double>> s(N_X + 1);
std::vector<std::vector<double>> n(N_X + 1);
std::vector<std::vector<double>> err(N_X + 1);
for (int i = 0; i < N_X + 1; i++) {
density[i].resize(N_Y + 1, 0.0);
s[i].resize(N_Y + 1, 0.0);
n[i].resize(N_Y + 1, 0.0);
err[i].resize(N_Y + 1, 0.0);
s[i][0] = V_1;
n[i][0] = V_1;
for (int j = 0; j < N_Y + 1; j++) {
density[i][j] = finalDensity(i * DELTA, j * DELTA, X_MAX, Y_MAX, SIGMA_X, SIGMA_Y);
}
}
double S = 0.0;
double S_1;
int iter = 0;
do {
for (int i = 1; i < N_X; i++) {
for (int j = 1; j < N_Y; j++) {
n[i][j] = countGlobal(s[i + 1][j], s[i - 1][j], s[i][j + 1], s[i][j - 1], DELTA, EPSILON,
density[i][j]);
}
}
for (int i = 1; i < N_Y + 1; i++) {
n[0][i] = n[1][i];
n[N_X][i] = n[N_X - 1][i];
}
for (int i = 0; i < N_X + 1; i++) {
for (int j = 0; j < N_Y + 1; j++) {
s[i][j] = (1.0 - o) * s[i][j] + o * n[i][j];
}
}
S_1 = S;
S = countStop(n, DELTA, density, N_X, N_Y);
saveResults(fileNameRes, iter, S);
iter++;
} while (std::abs((S - S_1) / S_1) > TOL);
for (int i = 1; i < N_X; i++) {
for (int j = 1; j < N_Y; j++) {
err[i][j] = countErr(n[i + 1][j], n[i][j], n[i - 1][j], n[i][j + 1], n[i][j - 1], DELTA, density[i][j],
EPSILON);
saveResults(fileNameErr, i * DELTA, j * DELTA, err[i][j]);
saveResults(fileNameGrid, i * DELTA, j * DELTA, n[i][j]);
}
}
}
}
void relaksacjaLokalna() {
auto omega = std::vector<double>{
1.0, 1.4, 1.8, 1.9
};
const double TOL = std::pow(10, -8);
constexpr double EPSILON = 1.0;
constexpr double DELTA = 0.1;
constexpr int N_X = 150;
constexpr int N_Y = 100;
constexpr double V_1 = 10.0;
constexpr double X_MAX = DELTA * N_X;
constexpr double Y_MAX = DELTA * N_Y;
constexpr double SIGMA_X = 0.1 * X_MAX;
constexpr double SIGMA_Y = 0.1 * Y_MAX;
for (auto o : omega) {
std::string fileNameRes = "1_local_";
fileNameRes += std::to_string(o) + "_res.dat";
clearFile(fileNameRes);
std::vector<std::vector<double>> density(N_X + 1);
std::vector<std::vector<double>> n(N_X + 1);
for (int i = 0; i < N_X + 1; i++) {
density[i].resize(N_Y + 1, 0.0);
n[i].resize(N_Y + 1, 0.0);
n[i][0] = V_1;
for (int j = 0; j < N_Y + 1; j++) {
density[i][j] = finalDensity(i * DELTA, j * DELTA, X_MAX, Y_MAX, SIGMA_X, SIGMA_Y);
}
}
double S = 0.0;
double S_1;
int iter = 0;
do {
for (int i = 1; i < N_X; i++) {
for (int j = 1; j < N_Y; j++) {
n[i][j] = countLocal(o, n[i][j], n[i + 1][j], n[i - 1][j], n[i][j + 1], n[i][j - 1], DELTA, EPSILON,
density[i][j]);
}
}
for (int i = 1; i < N_Y; i++) {
n[0][i] = n[1][i];
n[N_X][i] = n[N_X - 1][i];
}
S_1 = S;
S = countStop(n, DELTA, density, N_X, N_Y);
saveResults(fileNameRes, iter, S);
iter++;
} while (std::abs((S - S_1) / S_1) > TOL);
}
}
int main() {
relaksacjaGlobalna();
// relaksacjaLokalna();
return 0;
} | [
"[email protected]"
] | |
ecd0e34161d72f957514b391454511a652e58780 | 6acb31a73c244e5157b5119969475cd7160e669c | /src/compiler/interpreter-assembler.cc | 35ddb074275ac06fc6b7587880a29bc954511300 | [
"bzip2-1.0.6",
"BSD-3-Clause"
] | permissive | uloga/v8 | db8a1591f579a1aed51d1c46f18835007cb72ccc | e3b1cf17263325d47c467f018c0c474af66eb3cd | refs/heads/master | 2020-04-01T20:49:37.239003 | 2015-12-07T03:24:21 | 2015-12-07T03:24:47 | 47,528,826 | 3 | 0 | null | 2015-12-07T04:14:15 | 2015-12-07T04:14:14 | null | UTF-8 | C++ | false | false | 21,688 | cc | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/interpreter-assembler.h"
#include <ostream>
#include "src/code-factory.h"
#include "src/compiler/graph.h"
#include "src/compiler/instruction-selector.h"
#include "src/compiler/linkage.h"
#include "src/compiler/pipeline.h"
#include "src/compiler/raw-machine-assembler.h"
#include "src/compiler/schedule.h"
#include "src/frames.h"
#include "src/interface-descriptors.h"
#include "src/interpreter/bytecodes.h"
#include "src/machine-type.h"
#include "src/macro-assembler.h"
#include "src/zone.h"
namespace v8 {
namespace internal {
namespace compiler {
InterpreterAssembler::InterpreterAssembler(Isolate* isolate, Zone* zone,
interpreter::Bytecode bytecode)
: bytecode_(bytecode),
raw_assembler_(new RawMachineAssembler(
isolate, new (zone) Graph(zone),
Linkage::GetInterpreterDispatchDescriptor(zone), kMachPtr,
InstructionSelector::SupportedMachineOperatorFlags())),
accumulator_(
raw_assembler_->Parameter(Linkage::kInterpreterAccumulatorParameter)),
context_(
raw_assembler_->Parameter(Linkage::kInterpreterContextParameter)),
code_generated_(false) {}
InterpreterAssembler::~InterpreterAssembler() {}
Handle<Code> InterpreterAssembler::GenerateCode() {
DCHECK(!code_generated_);
// Disallow empty handlers that never return.
DCHECK_NE(0, graph()->end()->InputCount());
const char* bytecode_name = interpreter::Bytecodes::ToString(bytecode_);
Schedule* schedule = raw_assembler_->Export();
// TODO(rmcilroy): use a non-testing code generator.
Handle<Code> code = Pipeline::GenerateCodeForCodeStub(
isolate(), raw_assembler_->call_descriptor(), graph(), schedule,
Code::STUB, bytecode_name);
#ifdef ENABLE_DISASSEMBLER
if (FLAG_trace_ignition_codegen) {
OFStream os(stdout);
code->Disassemble(bytecode_name, os);
os << std::flush;
}
#endif
code_generated_ = true;
return code;
}
Node* InterpreterAssembler::GetAccumulator() { return accumulator_; }
void InterpreterAssembler::SetAccumulator(Node* value) { accumulator_ = value; }
Node* InterpreterAssembler::GetContext() { return context_; }
void InterpreterAssembler::SetContext(Node* value) { context_ = value; }
Node* InterpreterAssembler::RegisterFileRawPointer() {
return raw_assembler_->Parameter(Linkage::kInterpreterRegisterFileParameter);
}
Node* InterpreterAssembler::BytecodeArrayTaggedPointer() {
return raw_assembler_->Parameter(Linkage::kInterpreterBytecodeArrayParameter);
}
Node* InterpreterAssembler::BytecodeOffset() {
return raw_assembler_->Parameter(
Linkage::kInterpreterBytecodeOffsetParameter);
}
Node* InterpreterAssembler::DispatchTableRawPointer() {
return raw_assembler_->Parameter(Linkage::kInterpreterDispatchTableParameter);
}
Node* InterpreterAssembler::RegisterFrameOffset(Node* index) {
return WordShl(index, kPointerSizeLog2);
}
Node* InterpreterAssembler::RegisterLocation(Node* reg_index) {
return IntPtrAdd(RegisterFileRawPointer(), RegisterFrameOffset(reg_index));
}
Node* InterpreterAssembler::LoadRegister(interpreter::Register reg) {
return raw_assembler_->Load(
kMachAnyTagged, RegisterFileRawPointer(),
RegisterFrameOffset(Int32Constant(reg.ToOperand())));
}
Node* InterpreterAssembler::LoadRegister(Node* reg_index) {
return raw_assembler_->Load(kMachAnyTagged, RegisterFileRawPointer(),
RegisterFrameOffset(reg_index));
}
Node* InterpreterAssembler::StoreRegister(Node* value, Node* reg_index) {
return raw_assembler_->Store(kMachAnyTagged, RegisterFileRawPointer(),
RegisterFrameOffset(reg_index), value,
kNoWriteBarrier);
}
Node* InterpreterAssembler::BytecodeOperand(int operand_index) {
DCHECK_LT(operand_index, interpreter::Bytecodes::NumberOfOperands(bytecode_));
DCHECK_EQ(interpreter::OperandSize::kByte,
interpreter::Bytecodes::GetOperandSize(bytecode_, operand_index));
return raw_assembler_->Load(
kMachUint8, BytecodeArrayTaggedPointer(),
IntPtrAdd(BytecodeOffset(),
Int32Constant(interpreter::Bytecodes::GetOperandOffset(
bytecode_, operand_index))));
}
Node* InterpreterAssembler::BytecodeOperandSignExtended(int operand_index) {
DCHECK_LT(operand_index, interpreter::Bytecodes::NumberOfOperands(bytecode_));
DCHECK_EQ(interpreter::OperandSize::kByte,
interpreter::Bytecodes::GetOperandSize(bytecode_, operand_index));
Node* load = raw_assembler_->Load(
kMachInt8, BytecodeArrayTaggedPointer(),
IntPtrAdd(BytecodeOffset(),
Int32Constant(interpreter::Bytecodes::GetOperandOffset(
bytecode_, operand_index))));
// Ensure that we sign extend to full pointer size
if (kPointerSize == 8) {
load = raw_assembler_->ChangeInt32ToInt64(load);
}
return load;
}
Node* InterpreterAssembler::BytecodeOperandShort(int operand_index) {
DCHECK_LT(operand_index, interpreter::Bytecodes::NumberOfOperands(bytecode_));
DCHECK_EQ(interpreter::OperandSize::kShort,
interpreter::Bytecodes::GetOperandSize(bytecode_, operand_index));
if (TargetSupportsUnalignedAccess()) {
return raw_assembler_->Load(
kMachUint16, BytecodeArrayTaggedPointer(),
IntPtrAdd(BytecodeOffset(),
Int32Constant(interpreter::Bytecodes::GetOperandOffset(
bytecode_, operand_index))));
} else {
int offset =
interpreter::Bytecodes::GetOperandOffset(bytecode_, operand_index);
Node* first_byte = raw_assembler_->Load(
kMachUint8, BytecodeArrayTaggedPointer(),
IntPtrAdd(BytecodeOffset(), Int32Constant(offset)));
Node* second_byte = raw_assembler_->Load(
kMachUint8, BytecodeArrayTaggedPointer(),
IntPtrAdd(BytecodeOffset(), Int32Constant(offset + 1)));
#if V8_TARGET_LITTLE_ENDIAN
return raw_assembler_->WordOr(WordShl(second_byte, kBitsPerByte),
first_byte);
#elif V8_TARGET_BIG_ENDIAN
return raw_assembler_->WordOr(WordShl(first_byte, kBitsPerByte),
second_byte);
#else
#error "Unknown Architecture"
#endif
}
}
Node* InterpreterAssembler::BytecodeOperandCount(int operand_index) {
switch (interpreter::Bytecodes::GetOperandSize(bytecode_, operand_index)) {
case interpreter::OperandSize::kByte:
DCHECK_EQ(
interpreter::OperandType::kCount8,
interpreter::Bytecodes::GetOperandType(bytecode_, operand_index));
return BytecodeOperand(operand_index);
case interpreter::OperandSize::kShort:
DCHECK_EQ(
interpreter::OperandType::kCount16,
interpreter::Bytecodes::GetOperandType(bytecode_, operand_index));
return BytecodeOperandShort(operand_index);
default:
UNREACHABLE();
return nullptr;
}
}
Node* InterpreterAssembler::BytecodeOperandImm(int operand_index) {
DCHECK_EQ(interpreter::OperandType::kImm8,
interpreter::Bytecodes::GetOperandType(bytecode_, operand_index));
return BytecodeOperandSignExtended(operand_index);
}
Node* InterpreterAssembler::BytecodeOperandIdx(int operand_index) {
switch (interpreter::Bytecodes::GetOperandSize(bytecode_, operand_index)) {
case interpreter::OperandSize::kByte:
DCHECK_EQ(
interpreter::OperandType::kIdx8,
interpreter::Bytecodes::GetOperandType(bytecode_, operand_index));
return BytecodeOperand(operand_index);
case interpreter::OperandSize::kShort:
DCHECK_EQ(
interpreter::OperandType::kIdx16,
interpreter::Bytecodes::GetOperandType(bytecode_, operand_index));
return BytecodeOperandShort(operand_index);
default:
UNREACHABLE();
return nullptr;
}
}
Node* InterpreterAssembler::BytecodeOperandReg(int operand_index) {
#ifdef DEBUG
interpreter::OperandType operand_type =
interpreter::Bytecodes::GetOperandType(bytecode_, operand_index);
DCHECK(operand_type == interpreter::OperandType::kReg8 ||
operand_type == interpreter::OperandType::kMaybeReg8);
#endif
return BytecodeOperandSignExtended(operand_index);
}
Node* InterpreterAssembler::Int32Constant(int value) {
return raw_assembler_->Int32Constant(value);
}
Node* InterpreterAssembler::IntPtrConstant(intptr_t value) {
return raw_assembler_->IntPtrConstant(value);
}
Node* InterpreterAssembler::NumberConstant(double value) {
return raw_assembler_->NumberConstant(value);
}
Node* InterpreterAssembler::HeapConstant(Handle<HeapObject> object) {
return raw_assembler_->HeapConstant(object);
}
Node* InterpreterAssembler::BooleanConstant(bool value) {
return raw_assembler_->BooleanConstant(value);
}
Node* InterpreterAssembler::SmiShiftBitsConstant() {
return Int32Constant(kSmiShiftSize + kSmiTagSize);
}
Node* InterpreterAssembler::SmiTag(Node* value) {
return raw_assembler_->WordShl(value, SmiShiftBitsConstant());
}
Node* InterpreterAssembler::SmiUntag(Node* value) {
return raw_assembler_->WordSar(value, SmiShiftBitsConstant());
}
Node* InterpreterAssembler::IntPtrAdd(Node* a, Node* b) {
return raw_assembler_->IntPtrAdd(a, b);
}
Node* InterpreterAssembler::IntPtrSub(Node* a, Node* b) {
return raw_assembler_->IntPtrSub(a, b);
}
Node* InterpreterAssembler::WordShl(Node* value, int shift) {
return raw_assembler_->WordShl(value, Int32Constant(shift));
}
Node* InterpreterAssembler::LoadConstantPoolEntry(Node* index) {
Node* constant_pool = LoadObjectField(BytecodeArrayTaggedPointer(),
BytecodeArray::kConstantPoolOffset);
Node* entry_offset =
IntPtrAdd(IntPtrConstant(FixedArray::kHeaderSize - kHeapObjectTag),
WordShl(index, kPointerSizeLog2));
return raw_assembler_->Load(kMachAnyTagged, constant_pool, entry_offset);
}
Node* InterpreterAssembler::LoadFixedArrayElement(Node* fixed_array,
int index) {
Node* entry_offset =
IntPtrAdd(IntPtrConstant(FixedArray::kHeaderSize - kHeapObjectTag),
WordShl(Int32Constant(index), kPointerSizeLog2));
return raw_assembler_->Load(kMachAnyTagged, fixed_array, entry_offset);
}
Node* InterpreterAssembler::LoadObjectField(Node* object, int offset) {
return raw_assembler_->Load(kMachAnyTagged, object,
IntPtrConstant(offset - kHeapObjectTag));
}
Node* InterpreterAssembler::LoadContextSlot(Node* context, int slot_index) {
return raw_assembler_->Load(kMachAnyTagged, context,
IntPtrConstant(Context::SlotOffset(slot_index)));
}
Node* InterpreterAssembler::LoadContextSlot(Node* context, Node* slot_index) {
Node* offset =
IntPtrAdd(WordShl(slot_index, kPointerSizeLog2),
Int32Constant(Context::kHeaderSize - kHeapObjectTag));
return raw_assembler_->Load(kMachAnyTagged, context, offset);
}
Node* InterpreterAssembler::StoreContextSlot(Node* context, Node* slot_index,
Node* value) {
Node* offset =
IntPtrAdd(WordShl(slot_index, kPointerSizeLog2),
Int32Constant(Context::kHeaderSize - kHeapObjectTag));
return raw_assembler_->Store(kMachAnyTagged, context, offset, value,
kFullWriteBarrier);
}
Node* InterpreterAssembler::LoadTypeFeedbackVector() {
Node* function = raw_assembler_->Load(
kMachAnyTagged, RegisterFileRawPointer(),
IntPtrConstant(InterpreterFrameConstants::kFunctionFromRegisterPointer));
Node* shared_info =
LoadObjectField(function, JSFunction::kSharedFunctionInfoOffset);
Node* vector =
LoadObjectField(shared_info, SharedFunctionInfo::kFeedbackVectorOffset);
return vector;
}
Node* InterpreterAssembler::CallConstruct(Node* new_target, Node* constructor,
Node* first_arg, Node* arg_count) {
Callable callable = CodeFactory::InterpreterPushArgsAndConstruct(isolate());
CallDescriptor* descriptor = Linkage::GetStubCallDescriptor(
isolate(), zone(), callable.descriptor(), 0, CallDescriptor::kNoFlags);
Node* code_target = HeapConstant(callable.code());
Node** args = zone()->NewArray<Node*>(5);
args[0] = arg_count;
args[1] = new_target;
args[2] = constructor;
args[3] = first_arg;
args[4] = GetContext();
return CallN(descriptor, code_target, args);
}
Node* InterpreterAssembler::CallN(CallDescriptor* descriptor, Node* code_target,
Node** args) {
Node* stack_pointer_before_call = nullptr;
if (FLAG_debug_code) {
stack_pointer_before_call = raw_assembler_->LoadStackPointer();
}
Node* return_val = raw_assembler_->CallN(descriptor, code_target, args);
if (FLAG_debug_code) {
Node* stack_pointer_after_call = raw_assembler_->LoadStackPointer();
AbortIfWordNotEqual(stack_pointer_before_call, stack_pointer_after_call,
kUnexpectedStackPointer);
}
return return_val;
}
Node* InterpreterAssembler::CallJS(Node* function, Node* first_arg,
Node* arg_count) {
Callable callable = CodeFactory::InterpreterPushArgsAndCall(isolate());
CallDescriptor* descriptor = Linkage::GetStubCallDescriptor(
isolate(), zone(), callable.descriptor(), 0, CallDescriptor::kNoFlags);
Node* code_target = HeapConstant(callable.code());
Node** args = zone()->NewArray<Node*>(4);
args[0] = arg_count;
args[1] = first_arg;
args[2] = function;
args[3] = GetContext();
return CallN(descriptor, code_target, args);
}
Node* InterpreterAssembler::CallIC(CallInterfaceDescriptor descriptor,
Node* target, Node** args) {
CallDescriptor* call_descriptor = Linkage::GetStubCallDescriptor(
isolate(), zone(), descriptor, 0, CallDescriptor::kNoFlags);
return CallN(call_descriptor, target, args);
}
Node* InterpreterAssembler::CallIC(CallInterfaceDescriptor descriptor,
Node* target, Node* arg1, Node* arg2,
Node* arg3) {
Node** args = zone()->NewArray<Node*>(4);
args[0] = arg1;
args[1] = arg2;
args[2] = arg3;
args[3] = GetContext();
return CallIC(descriptor, target, args);
}
Node* InterpreterAssembler::CallIC(CallInterfaceDescriptor descriptor,
Node* target, Node* arg1, Node* arg2,
Node* arg3, Node* arg4) {
Node** args = zone()->NewArray<Node*>(5);
args[0] = arg1;
args[1] = arg2;
args[2] = arg3;
args[3] = arg4;
args[4] = GetContext();
return CallIC(descriptor, target, args);
}
Node* InterpreterAssembler::CallIC(CallInterfaceDescriptor descriptor,
Node* target, Node* arg1, Node* arg2,
Node* arg3, Node* arg4, Node* arg5) {
Node** args = zone()->NewArray<Node*>(6);
args[0] = arg1;
args[1] = arg2;
args[2] = arg3;
args[3] = arg4;
args[4] = arg5;
args[5] = GetContext();
return CallIC(descriptor, target, args);
}
Node* InterpreterAssembler::CallRuntime(Node* function_id, Node* first_arg,
Node* arg_count) {
Callable callable = CodeFactory::InterpreterCEntry(isolate());
CallDescriptor* descriptor = Linkage::GetStubCallDescriptor(
isolate(), zone(), callable.descriptor(), 0, CallDescriptor::kNoFlags);
Node* code_target = HeapConstant(callable.code());
// Get the function entry from the function id.
Node* function_table = raw_assembler_->ExternalConstant(
ExternalReference::runtime_function_table_address(isolate()));
Node* function_offset = raw_assembler_->Int32Mul(
function_id, Int32Constant(sizeof(Runtime::Function)));
Node* function = IntPtrAdd(function_table, function_offset);
Node* function_entry = raw_assembler_->Load(
kMachPtr, function, Int32Constant(offsetof(Runtime::Function, entry)));
Node** args = zone()->NewArray<Node*>(4);
args[0] = arg_count;
args[1] = first_arg;
args[2] = function_entry;
args[3] = GetContext();
return CallN(descriptor, code_target, args);
}
Node* InterpreterAssembler::CallRuntime(Runtime::FunctionId function_id,
Node* arg1) {
return raw_assembler_->CallRuntime1(function_id, arg1, GetContext());
}
Node* InterpreterAssembler::CallRuntime(Runtime::FunctionId function_id,
Node* arg1, Node* arg2) {
return raw_assembler_->CallRuntime2(function_id, arg1, arg2, GetContext());
}
Node* InterpreterAssembler::CallRuntime(Runtime::FunctionId function_id,
Node* arg1, Node* arg2, Node* arg3,
Node* arg4) {
return raw_assembler_->CallRuntime4(function_id, arg1, arg2, arg3, arg4,
GetContext());
}
void InterpreterAssembler::Return() {
Node* exit_trampoline_code_object =
HeapConstant(isolate()->builtins()->InterpreterExitTrampoline());
// If the order of the parameters you need to change the call signature below.
STATIC_ASSERT(0 == Linkage::kInterpreterAccumulatorParameter);
STATIC_ASSERT(1 == Linkage::kInterpreterRegisterFileParameter);
STATIC_ASSERT(2 == Linkage::kInterpreterBytecodeOffsetParameter);
STATIC_ASSERT(3 == Linkage::kInterpreterBytecodeArrayParameter);
STATIC_ASSERT(4 == Linkage::kInterpreterDispatchTableParameter);
STATIC_ASSERT(5 == Linkage::kInterpreterContextParameter);
Node* args[] = { GetAccumulator(),
RegisterFileRawPointer(),
BytecodeOffset(),
BytecodeArrayTaggedPointer(),
DispatchTableRawPointer(),
GetContext() };
raw_assembler_->TailCallN(call_descriptor(), exit_trampoline_code_object,
args);
}
Node* InterpreterAssembler::Advance(int delta) {
return IntPtrAdd(BytecodeOffset(), Int32Constant(delta));
}
Node* InterpreterAssembler::Advance(Node* delta) {
return raw_assembler_->IntPtrAdd(BytecodeOffset(), delta);
}
void InterpreterAssembler::Jump(Node* delta) { DispatchTo(Advance(delta)); }
void InterpreterAssembler::JumpIfWordEqual(Node* lhs, Node* rhs, Node* delta) {
RawMachineLabel match, no_match;
Node* condition = raw_assembler_->WordEqual(lhs, rhs);
raw_assembler_->Branch(condition, &match, &no_match);
raw_assembler_->Bind(&match);
DispatchTo(Advance(delta));
raw_assembler_->Bind(&no_match);
Dispatch();
}
void InterpreterAssembler::Dispatch() {
DispatchTo(Advance(interpreter::Bytecodes::Size(bytecode_)));
}
void InterpreterAssembler::DispatchTo(Node* new_bytecode_offset) {
Node* target_bytecode = raw_assembler_->Load(
kMachUint8, BytecodeArrayTaggedPointer(), new_bytecode_offset);
// TODO(rmcilroy): Create a code target dispatch table to avoid conversion
// from code object on every dispatch.
Node* target_code_object = raw_assembler_->Load(
kMachPtr, DispatchTableRawPointer(),
raw_assembler_->Word32Shl(target_bytecode,
Int32Constant(kPointerSizeLog2)));
// If the order of the parameters you need to change the call signature below.
STATIC_ASSERT(0 == Linkage::kInterpreterAccumulatorParameter);
STATIC_ASSERT(1 == Linkage::kInterpreterRegisterFileParameter);
STATIC_ASSERT(2 == Linkage::kInterpreterBytecodeOffsetParameter);
STATIC_ASSERT(3 == Linkage::kInterpreterBytecodeArrayParameter);
STATIC_ASSERT(4 == Linkage::kInterpreterDispatchTableParameter);
STATIC_ASSERT(5 == Linkage::kInterpreterContextParameter);
Node* args[] = { GetAccumulator(),
RegisterFileRawPointer(),
new_bytecode_offset,
BytecodeArrayTaggedPointer(),
DispatchTableRawPointer(),
GetContext() };
raw_assembler_->TailCallN(call_descriptor(), target_code_object, args);
}
void InterpreterAssembler::Abort(BailoutReason bailout_reason) {
Node* abort_id = SmiTag(Int32Constant(bailout_reason));
CallRuntime(Runtime::kAbort, abort_id);
Return();
}
void InterpreterAssembler::AbortIfWordNotEqual(Node* lhs, Node* rhs,
BailoutReason bailout_reason) {
RawMachineLabel match, no_match;
Node* condition = raw_assembler_->WordEqual(lhs, rhs);
raw_assembler_->Branch(condition, &match, &no_match);
raw_assembler_->Bind(&no_match);
Abort(bailout_reason);
raw_assembler_->Bind(&match);
}
// static
bool InterpreterAssembler::TargetSupportsUnalignedAccess() {
#if V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64
return false;
#elif V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_PPC
return CpuFeatures::IsSupported(UNALIGNED_ACCESSES);
#elif V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X64 || V8_TARGET_ARCH_X87
return true;
#else
#error "Unknown Architecture"
#endif
}
// RawMachineAssembler delegate helpers:
Isolate* InterpreterAssembler::isolate() { return raw_assembler_->isolate(); }
Graph* InterpreterAssembler::graph() { return raw_assembler_->graph(); }
CallDescriptor* InterpreterAssembler::call_descriptor() const {
return raw_assembler_->call_descriptor();
}
Zone* InterpreterAssembler::zone() { return raw_assembler_->zone(); }
} // namespace compiler
} // namespace internal
} // namespace v8
| [
"[email protected]"
] | |
37358d8bdb70880bd5d45b54d9acc8db098a9c11 | 572340027d0feb71150b508c79bfcbca78006e0a | /mavlink_control.h | 393a2fa97cffbcdffd7c8d20230f2f8a7e3da41c | [
"MIT"
] | permissive | 970704/Copter_mavlink_companion_control | f87f2fb609115ac6137b72b1e905c9d7d6be0350 | 90c5846b9b68792fd5c4d0080adf236d0a6c47ea | refs/heads/master | 2021-09-21T17:04:07.600984 | 2018-08-29T12:49:32 | 2018-08-29T12:49:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,457 | h | /****************************************************************************
*
* Copyright (c) 2014 MAVlink Development Team. All rights reserved.
* Author: @author Peter XU, <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file mavlink_control.h
*
* @brief An example offboard control process via mavlink, definition
*
* This process connects an external MAVLink UART device to send an receive data
*
* @author Peter XU, <[email protected]>
*
*/
// ------------------------------------------------------------------------------
// Includes
// ------------------------------------------------------------------------------
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <wiringPi.h>
#include <opencv2/opencv.hpp>
#include "MarkerDetector.h"
#include "fire_recognition.h"
using std::string;
using namespace std;
#include <common/mavlink.h>
#include "autopilot_interface.h"
#include "serial_port.h"
// ------------------------------------------------------------------------------
// Prototypes
// ------------------------------------------------------------------------------
int main(int argc, char **argv);
int top(int argc, char **argv);
void readCameraParameter();
void commands(Autopilot_Interface &autopilot_interface);
void parse_commandline(int argc, char **argv, char *&uart_name, int &baudrate);
void Init_all();
void rtl(Autopilot_Interface &api, Mat frame);
void* servo_on_thread(void*);
void* servo_off_thread(void*);
void* detect_thread(void*);
void* task_thread(void*);
void detect_color(Mat frame);
int detect_marker(Mat frame);
// quit handler
Autopilot_Interface *autopilot_interface_quit;
Serial_Port *serial_port_quit;
void quit_handler( int sig );
| [
"[email protected]"
] | |
f9eb7f3198958b870e31c71b0064b0178517539f | 7860186d95c8cf895780bbdba5026697b146dbff | /lbr_miss_sample.h | da9bb524edc6e6c304e42c55f18aea66d8c43aef | [] | no_license | takhandipu/multiBBL | d2ea3c62b4ef5c215f2d78b0572e7d330fd83a1e | 0f5eb4d68be5be18a3a2fe212f8a1b1d9d99853a | refs/heads/master | 2021-01-04T08:13:26.786565 | 2020-02-26T21:30:31 | 2020-02-26T21:30:31 | 240,461,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,344 | h | #ifndef LBR_MISS_SAMPLE_H_
#define LBR_MISS_SAMPLE_H_
#include <bits/stdc++.h>
using namespace std;
#include <boost/algorithm/string.hpp>
#include "gz_reader.h"
#include "log.h"
#include "convert.h"
#include "cfg.h"
int measure_prefetch_length(uint64_t current, uint64_t next)
{
return (next>>6) - (current>>6);
}
unsigned int my_abs(int a)
{
if(a<0)return -a;
return a;
}
class Candidate
{
public:
uint64_t predecessor_bbl_address;
double covered_miss_ratio_to_predecessor_count;
Candidate(uint64_t addr, double c_ratio)
{
predecessor_bbl_address = addr;
covered_miss_ratio_to_predecessor_count = c_ratio;
}
bool operator < (const Candidate& right) const
{
return covered_miss_ratio_to_predecessor_count < right.covered_miss_ratio_to_predecessor_count;
}
};
struct prefetch_benefit
{
uint64_t addr;
uint64_t prefetch_count;
uint64_t covered_miss_count;
prefetch_benefit(uint64_t a, uint64_t p_count, uint64_t cm_count) : addr(a), prefetch_count(p_count), covered_miss_count(cm_count) {}
bool operator < (const prefetch_benefit& right) const
{
if(prefetch_count < 1)return false;
if(right.prefetch_count < 1) return true;
double left_ratio = (1.0 * covered_miss_count) / prefetch_count;
double right_ratio = (1.0 * right.covered_miss_count) / right.prefetch_count;
if (left_ratio == right_ratio)
{
if (covered_miss_count == right.covered_miss_count)
{
return prefetch_count < right.prefetch_count;
}
else
{
return covered_miss_count < right.covered_miss_count;
}
}
else
{
return left_ratio < right_ratio;
}
}
};
struct benefit
{
uint64_t missed_bbl_address;
uint64_t predecessor_bbl_address;
uint64_t covered_miss_counts;
double fan_in;
benefit (uint64_t m, uint64_t p, uint64_t c, double f) : missed_bbl_address(m), predecessor_bbl_address(p), covered_miss_counts(c), fan_in(f) {}
bool operator < (const benefit& right) const
{
if(right.fan_in>fan_in)return true;
else if(fan_in>right.fan_in)return false;
else
{
if(right.covered_miss_counts>covered_miss_counts)return true;
return false;
}
}
};
struct multi_bbl_benefit
{
uint64_t missed_bbl_address;
uint64_t predecessor_bbl_address;
uint64_t predicate_bbl_address;
uint64_t covered_miss_counts;
double fan_in;
uint64_t dynamic_prefetch_counts;
multi_bbl_benefit (uint64_t m, uint64_t predecessor, uint64_t predicate, uint64_t c, double f, uint64_t d_p_counts) : missed_bbl_address(m), predecessor_bbl_address(predecessor), predicate_bbl_address(predicate), covered_miss_counts(c), fan_in(f), dynamic_prefetch_counts(d_p_counts) {}
bool operator < (const multi_bbl_benefit& right) const
{
if(right.fan_in>fan_in)return true;
else if(fan_in>right.fan_in)return false;
else
{
if(right.covered_miss_counts>covered_miss_counts)return true;
return false;
}
}
};
class LBR_Sample
{
public:
vector<pair<uint64_t,uint64_t>> current_lbr;
LBR_Sample()
{
current_lbr.clear();
}
void push_pair(uint64_t prev_bbl, uint64_t cycle)
{
current_lbr.push_back(make_pair(prev_bbl, cycle));
}
void push(string lbr_pair)
{
vector<string> current_record;
boost::split(current_record,lbr_pair,boost::is_any_of(";"),boost::token_compress_on);
if(current_record.size() != 2)panic("LB-record does not contain exactly 2 entries\n");
push_pair(string_to_u64(current_record[0]),string_to_u64(current_record[1]));
}
uint64_t size()
{
return current_lbr.size();
}
void get_candidates(set<uint64_t> &candidates, Settings *settings, CFG *dynamic_cfg)
{
candidates.clear();
uint64_t current_distance = 0;
uint64_t min_distance = settings->get_min_distance();
uint64_t max_distance = settings->get_max_distance();
for(uint64_t i = 0; i<current_lbr.size(); i++)
{
if(settings->multiline_mode == 1)//ASMDB
{
current_distance+=dynamic_cfg->get_bbl_instr_count(current_lbr[i].first);
}
else // if(settings.multiline_mode == 2) OUR
{
current_distance+=dynamic_cfg->get_bbl_avg_cycles(current_lbr[i].first);//current_lbr[i].second;
}
if(current_distance>=min_distance)
{
if(current_distance>max_distance)return;
candidates.insert(current_lbr[i].first);
}
}
}
void get_correlated_candidates(uint64_t top_candidate, set<uint64_t> &candidates, Settings *settings, CFG *dynamic_cfg)
{
candidates.clear();
uint64_t current_distance = 0;
uint64_t min_distance = settings->get_min_distance();
uint64_t max_distance = settings->get_max_distance();
for(uint64_t i = 0; i<current_lbr.size(); i++)
{
if(settings->multiline_mode == 1)//ASMDB
{
current_distance+=dynamic_cfg->get_bbl_instr_count(current_lbr[i].first);
}
else // if(settings.multiline_mode == 2) OUR
{
current_distance+=dynamic_cfg->get_bbl_avg_cycles(current_lbr[i].first);//current_lbr[i].second;
}
if(current_distance>=min_distance)
{
if(current_distance>max_distance)return;
//candidates.insert(current_lbr[i].first);
if(current_lbr[i].first == top_candidate)
{
//insert previous 8 BBLs on the candidate list
for(uint64_t j=i+1; (j<current_lbr.size() && j<i+9); j++)
{
if(current_lbr[j].first == top_candidate)continue;
candidates.insert(current_lbr[j].first);
}
return;
}
}
}
}
bool is_covered(uint64_t predecessor_bbl_address, Settings *settings, CFG *dynamic_cfg)
{
uint64_t current_distance = 0;
uint64_t min_distance = settings->get_min_distance();
uint64_t max_distance = settings->get_max_distance();
for(uint64_t i = 0; i<current_lbr.size(); i++)
{
if(settings->multiline_mode == 1)//ASMDB
{
current_distance+=dynamic_cfg->get_bbl_instr_count(current_lbr[i].first);
}
else // if(settings.multiline_mode == 2) OUR
{
current_distance+=dynamic_cfg->get_bbl_avg_cycles(current_lbr[i].first);//current_lbr[i].second;
}
if(current_distance>=min_distance)
{
if(current_distance>max_distance)break;
if(current_lbr[i].first==predecessor_bbl_address)return true;
}
}
return false;
}
uint64_t count_accessed_cache_lines(Settings *settings, CFG *dynamic_cfg)
{
uint64_t min_distance = settings->get_min_distance();
uint64_t max_distance = settings->get_max_distance();
set<uint64_t> unique_cache_lines;
uint64_t current_distance = 0;
for(uint64_t i = 0; i<current_lbr.size(); i++)
{
if(settings->multiline_mode == 1)//ASMDB
{
current_distance+=dynamic_cfg->get_bbl_instr_count(current_lbr[i].first);
}
else // if(settings.multiline_mode == 2) OUR
{
current_distance+=dynamic_cfg->get_bbl_avg_cycles(current_lbr[i].first);//current_lbr[i].second;
}
if(current_distance>=min_distance)
{
if(current_distance>max_distance)break;
uint64_t start = current_lbr[i].first;
uint64_t end = start + dynamic_cfg->get_bbl_size(start);
start>>=6;
end>>=6;
for(uint64_t j=start; j<=end; j++)unique_cache_lines.insert(j);
}
}
return unique_cache_lines.size();
}
void clear()
{
current_lbr.clear();
}
};
class LBR_List
{
public:
vector<LBR_Sample *> all_misses;
LBR_List()
{
all_misses.clear();
}
void push_miss_sample(LBR_Sample *current_sample)
{
all_misses.push_back(current_sample);
}
void push(vector<string> lbr_pairs)
{
LBR_Sample *current_sample = new LBR_Sample();
for(uint64_t i=2/*omit first two items, cache line id and missed bbl address*/;i<lbr_pairs.size();i++)
{
current_sample->push(lbr_pairs[i]);
}
push_miss_sample(current_sample);
}
uint64_t size()
{
return all_misses.size();
}
void measure_prefetch_window_cdf(unordered_map<uint64_t,uint64_t> &table, Settings *settings, CFG *dynamic_cfg)
{
for(uint64_t i=0; i<all_misses.size(); i++)
{
uint64_t accessed_cache_line_count = all_misses[i]->count_accessed_cache_lines(settings, dynamic_cfg);
if(table.find(accessed_cache_line_count)==table.end())table[accessed_cache_line_count]=1;
else table[accessed_cache_line_count]+=1;
}
}
bool get_next_candidate(uint64_t *result, Settings *settings, set<uint64_t> &omit_list, CFG *dynamic_cfg)
{
unordered_map<uint64_t,uint64_t> candidate_counts;
set<uint64_t> candidates;
for(uint64_t i=0;i<all_misses.size();i++)
{
all_misses[i]->get_candidates(candidates, settings, dynamic_cfg);
for(auto it: candidates)
{
if(omit_list.find(it)!=omit_list.end())continue;
if(candidate_counts.find(it)==candidate_counts.end())candidate_counts[it]=1;
else candidate_counts[it]+=1;
}
}
vector<Candidate> sorted_candidates;
for(auto it: candidate_counts)
{
sorted_candidates.push_back(Candidate(it.first, ((1.0*it.second)/(dynamic_cfg->get_bbl_execution_count(it.first)))));
}
sort(sorted_candidates.begin(),sorted_candidates.end());
reverse(sorted_candidates.begin(),sorted_candidates.end());
if(sorted_candidates.size()<1)return false;
*result = sorted_candidates[0].predecessor_bbl_address;
return true;
}
bool get_top_candidate(vector<uint64_t> &result, vector<uint64_t> &result_counts, Settings *settings, CFG *dynamic_cfg)
{
result.clear();
result_counts.clear();
unordered_map<uint64_t,uint64_t> candidate_counts;
set<uint64_t> candidates;
for(uint64_t i=0;i<all_misses.size();i++)
{
all_misses[i]->get_candidates(candidates, settings, dynamic_cfg);
for(auto it: candidates)
{
if(candidate_counts.find(it)==candidate_counts.end())candidate_counts[it]=1;
else candidate_counts[it]+=1;
}
}
vector<Candidate> sorted_candidates;
for(auto it: candidate_counts)
{
sorted_candidates.push_back(Candidate(it.first, it.second));
}
sort(sorted_candidates.begin(),sorted_candidates.end());
reverse(sorted_candidates.begin(),sorted_candidates.end());
if(sorted_candidates.size()<1)return false;
for(int i=0;i<sorted_candidates.size();i++)
{
result.push_back(sorted_candidates[i].predecessor_bbl_address);
result_counts.push_back(sorted_candidates[i].covered_miss_ratio_to_predecessor_count);
}
sorted_candidates.clear();
candidate_counts.clear();
return true;
}
void get_candidate_counts(unordered_map<uint64_t,uint64_t> &candidate_counts, Settings *settings, set<uint64_t> &omit_list, CFG *dynamic_cfg)
{
set<uint64_t> candidates;
for(uint64_t i=0;i<all_misses.size();i++)
{
all_misses[i]->get_candidates(candidates, settings, dynamic_cfg);
for(auto it: candidates)
{
if(omit_list.find(it)!=omit_list.end())continue;
if(candidate_counts.find(it)==candidate_counts.end())candidate_counts[it]=1;
else candidate_counts[it]+=1;
}
}
}
uint64_t remove_covered_misses(uint64_t next, Settings *settings, CFG *dynamic_cfg)
{
vector<LBR_Sample *> tmp;
uint64_t total=0;
for(uint64_t i =0; i<all_misses.size();i++)
{
if(all_misses[i]->is_covered(next, settings, dynamic_cfg))
{
total+=1;
all_misses[i]->clear();
}
else
{
tmp.push_back(all_misses[i]);
}
}
all_misses.clear();
for(uint64_t i = 0; i< tmp.size(); i++)
{
all_misses.push_back(tmp[i]);
}
return total;
}
bool get_top_correlated_candidate(uint64_t *result, uint64_t *covered_miss_count, uint64_t next, uint64_t next_count, Settings *settings, CFG *dynamic_cfg)
{
unordered_map<uint64_t,uint64_t> candidate_counts;
set<uint64_t> candidates;
for(uint64_t i=0;i<all_misses.size();i++)
{
all_misses[i]->get_correlated_candidates(next, candidates, settings, dynamic_cfg);
for(auto it: candidates)
{
if(it==next)continue;
if(candidate_counts.find(it)==candidate_counts.end())candidate_counts[it]=1;
else candidate_counts[it]+=1;
}
}
vector<Candidate> sorted_candidates;
for(auto it: candidate_counts)
{
sorted_candidates.push_back(Candidate(it.first, it.second));
}
sort(sorted_candidates.begin(),sorted_candidates.end());
reverse(sorted_candidates.begin(),sorted_candidates.end());
if(sorted_candidates.size()<1)return false;
if(sorted_candidates[0].covered_miss_ratio_to_predecessor_count < next_count)return false;
*result = sorted_candidates[0].predecessor_bbl_address;
*covered_miss_count = sorted_candidates[0].covered_miss_ratio_to_predecessor_count;
sorted_candidates.clear();
candidate_counts.clear();
return true;
}
};
class Miss_Map
{
private:
ofstream *bbl_mapping_out = nullptr;
public:
unordered_map<uint64_t,LBR_List *> missed_pc_to_LBR_sample_list;
vector<uint64_t> miss_profile;
Miss_Map()
{
missed_pc_to_LBR_sample_list.clear();
}
~Miss_Map()
{
if(bbl_mapping_out!=nullptr)bbl_mapping_out->close();
missed_pc_to_LBR_sample_list.clear();
miss_profile.clear();
}
void set_bbl_mapping_out(string file_name)
{
bbl_mapping_out = new ofstream(file_name.c_str());
}
uint64_t size()
{
return missed_pc_to_LBR_sample_list.size();
}
uint64_t total_misses()
{
uint64_t total = 0;
for(auto it: missed_pc_to_LBR_sample_list)
{
total+=it.second->size();
}
return total;
}
void push(string line, CFG &dynamic_cfg)
{
boost::trim_if(line,boost::is_any_of(","));
vector<string> parsed;
boost::split(parsed,line,boost::is_any_of(",\n"),boost::token_compress_on);
if(parsed.size()<3)panic("ICache Miss LBR Sample contains less than 3 branch records");
uint64_t missed_cache_line_id = string_to_u64(parsed[0]);
uint64_t missed_bbl_address = string_to_u64(parsed[1]);
if(dynamic_cfg.is_self_modifying(missed_bbl_address))return;
miss_profile.push_back(missed_bbl_address);
if((missed_bbl_address>>6)!=missed_cache_line_id)panic("In access based next line prefetching system a icache miss cannot happen other than the start of a new BBL");
if(missed_pc_to_LBR_sample_list.find(missed_bbl_address)==missed_pc_to_LBR_sample_list.end())
{
missed_pc_to_LBR_sample_list[missed_bbl_address]=new LBR_List();
}
missed_pc_to_LBR_sample_list[missed_bbl_address]->push(parsed);
}
void measure_prefetch_window_cdf(Settings *settings, CFG *dynamic_cfg, ofstream &out)
{
unordered_map<uint64_t,uint64_t> table;
for(auto it: missed_pc_to_LBR_sample_list)
{
it.second->measure_prefetch_window_cdf(table, settings, dynamic_cfg);
}
uint64_t total = 0;
vector<uint64_t> sorted_counts;
for(auto it: table)
{
total+=it.second;
sorted_counts.push_back(it.first);
}
sort(sorted_counts.begin(),sorted_counts.end());
double value = 0.0;
for(uint64_t i=0;i<sorted_counts.size(); i++)
{
value+=table[sorted_counts[i]];
out<<sorted_counts[i]<<" "<<((100.0*value)/total)<<endl;
}
}
void generate_prefetch_locations(Settings *settings, CFG *dynamic_cfg, ofstream &out)
{
unordered_map<uint64_t,vector<uint64_t>> bbl_to_prefetch_targets;
vector<pair<uint64_t,uint64_t>> sorted_miss_pcs;
for(auto it: missed_pc_to_LBR_sample_list)
{
sorted_miss_pcs.push_back(make_pair(it.second->size(), it.first));
}
sort(sorted_miss_pcs.begin(), sorted_miss_pcs.end());
reverse(sorted_miss_pcs.begin(), sorted_miss_pcs.end());
uint64_t total_miss_sample_count = total_misses();
unordered_map<uint64_t,unordered_map<uint64_t,uint64_t>> neighbors;
for(uint64_t i = 0; i < miss_profile.size(); i++)
{
uint64_t missed_pc = miss_profile[i];
if(neighbors.find(missed_pc)==neighbors.end())
{
neighbors[missed_pc]=unordered_map<uint64_t,uint64_t>();
}
for(uint64_t j = 1; j<= settings->max_step_ahead; j++)
{
if(i+j>=miss_profile.size())break;
uint64_t neighbor_missed_pc = miss_profile[i+j];
int prefetch_length = measure_prefetch_length(missed_pc, neighbor_missed_pc);
if(my_abs(prefetch_length)<=settings->max_prefetch_length)
{
if(prefetch_length==0)continue;
if(neighbors[missed_pc].find(prefetch_length)==neighbors[missed_pc].end())
{
neighbors[missed_pc][neighbor_missed_pc]=1;
}
else
{
neighbors[missed_pc][neighbor_missed_pc]+=1;
}
}
}
}
vector<prefetch_benefit> multiline_sorted_missed_pcs;
map<uint64_t,vector<uint64_t>> prefetch_lists;
for(int i=0;i<sorted_miss_pcs.size();i++)
{
uint64_t current_pc = sorted_miss_pcs[i].second;
uint64_t prefetch_count = sorted_miss_pcs[i].first;
uint64_t covered_miss_count = prefetch_count;
prefetch_lists[current_pc]=vector<uint64_t>();
prefetch_lists[current_pc].push_back(current_pc);
for(auto it: neighbors[current_pc])
{
double ratio_percentage = (1.0 * it.second) / prefetch_count;
if(ratio_percentage>=settings->min_ratio_percentage)
{
covered_miss_count+=it.second;
prefetch_lists[current_pc].push_back(it.first);
}
}
multiline_sorted_missed_pcs.push_back(prefetch_benefit(current_pc, prefetch_count, covered_miss_count));
}
sort(multiline_sorted_missed_pcs.begin(), multiline_sorted_missed_pcs.end());
reverse(multiline_sorted_missed_pcs.begin(), multiline_sorted_missed_pcs.end());
uint64_t permissible_prefetch_count = settings->dyn_ins_count_inc_ratio * settings->total_dyn_ins_count;
uint64_t current_running_count = 0;
bool prefetch_count_finished = false;
bbl_to_prefetch_targets.clear();
uint64_t total_covered_miss_count=0;
set<uint64_t> omit_list;
vector<benefit> candidates;
for(int i =0; i<sorted_miss_pcs.size(); i++)
{
uint64_t missed_pc = sorted_miss_pcs[i].second;
unordered_map<uint64_t,uint64_t> candidate_counts;
missed_pc_to_LBR_sample_list[missed_pc]->get_candidate_counts(candidate_counts,settings,omit_list,dynamic_cfg);
for(auto it : candidate_counts)
{
uint64_t predecessor_bbl_address = it.first;
double fan_in = dynamic_cfg->get_fan_out(predecessor_bbl_address, missed_pc);
if(fan_in < 0.99)continue;
uint64_t miss_count = it.second;
candidates.push_back(benefit(missed_pc,predecessor_bbl_address,miss_count,fan_in));
}
candidate_counts.clear();
}
sort(candidates.begin(), candidates.end());
reverse(candidates.begin(),candidates.end());
for(int i = 0; i< candidates.size(); i++)
{
benefit &best_candidate = candidates[i];
uint64_t prefetch_candidate = best_candidate.predecessor_bbl_address;
uint64_t missed_pc = best_candidate.missed_bbl_address;
uint64_t inserted_prefetch_count = dynamic_cfg->get_bbl_execution_count(prefetch_candidate);
if( bbl_to_prefetch_targets.find(prefetch_candidate)==bbl_to_prefetch_targets.end() )bbl_to_prefetch_targets[prefetch_candidate]=vector<uint64_t>();
else if(bbl_to_prefetch_targets[prefetch_candidate].size()>0)
{
//Check if all the previous prefetch targets and this target are nearby
//if yes, okay
//else, not okay
uint64_t first_inserted_target = bbl_to_prefetch_targets[prefetch_candidate][0];
int prefetch_length = measure_prefetch_length(missed_pc, first_inserted_target);
if(my_abs(prefetch_length)<=settings->max_prefetch_length)
{
//this is good to insert
//and there is no extra static or dynamic instruction insert
//benfit
inserted_prefetch_count = 0;
}
}
uint64_t covered_miss_count = 0;
bbl_to_prefetch_targets[prefetch_candidate].push_back(missed_pc);
covered_miss_count+=missed_pc_to_LBR_sample_list[missed_pc]->remove_covered_misses(prefetch_candidate, settings, dynamic_cfg);
current_running_count += inserted_prefetch_count;
total_covered_miss_count+=covered_miss_count;
//if(current_running_count >= permissible_prefetch_count)break;
}
candidates.clear();
vector<multi_bbl_benefit> multi_bbl_candidates;
uint64_t iter = 0;
uint64_t added = 0;
for(int i =0; i<sorted_miss_pcs.size(); i++)
{
uint64_t missed_pc = sorted_miss_pcs[i].second;
//uint64_t still_missing = missed_pc_to_LBR_sample_list[missed_pc]->size();
//out<<missed_pc<<","<<still_missing<<endl;
vector<uint64_t> top_candidate;
vector<uint64_t> top_candidate_counts;
bool candidate_found = missed_pc_to_LBR_sample_list[missed_pc]->get_top_candidate(top_candidate,top_candidate_counts,settings,dynamic_cfg);
if(candidate_found == false)continue;
for(int j =0;j<top_candidate.size();j++)
{
uint64_t next_candidate;
uint64_t covered_miss_count;
uint64_t dynamic_prefetch_counts;
bool second_candidate_found = missed_pc_to_LBR_sample_list[missed_pc]->get_top_correlated_candidate(&next_candidate,&covered_miss_count,top_candidate[j], top_candidate_counts[j], settings,dynamic_cfg);
if(second_candidate_found == false)continue;
double fan_in_combined = dynamic_cfg->get_fan_in_for_multiple_prior_bbls(missed_pc,top_candidate[j],next_candidate,&dynamic_prefetch_counts);
iter+=1;
if(fan_in_combined>=0.99)
{
multi_bbl_candidates.push_back(multi_bbl_benefit(missed_pc,top_candidate[j],next_candidate,covered_miss_count,fan_in_combined,dynamic_prefetch_counts));
added+=1;
}
/*if(iter==100000)
{
cerr<<j<<endl;
break;
}*/
}
/*if(iter==100000)
{
cerr<<i<<endl;
break;
}*/
}
cerr<<iter<<","<<added<<endl;
//cerr<<iter<<endl;
sort(multi_bbl_candidates.begin(),multi_bbl_candidates.end());
reverse(multi_bbl_candidates.begin(),multi_bbl_candidates.end());
for(int i = 0; i< multi_bbl_candidates.size(); i++)
{
multi_bbl_benefit &best_candidate = multi_bbl_candidates[i];
uint64_t prefetch_candidate_predecessor = best_candidate.predecessor_bbl_address;
uint64_t prefetch_candidate_predicate = best_candidate.predicate_bbl_address;
uint64_t missed_pc = best_candidate.missed_bbl_address;
uint64_t covered_miss_count = best_candidate.covered_miss_counts;
uint64_t inserted_prefetch_count = best_candidate.dynamic_prefetch_counts;
current_running_count += inserted_prefetch_count;
total_covered_miss_count+=covered_miss_count;
out<<"CS,"<<prefetch_candidate_predicate<<","<<prefetch_candidate_predecessor<<","<<missed_pc<<endl;
}
multi_bbl_candidates.clear();
uint64_t static_prefetch_count = 0;
uint8_t size_of_prefetch_inst = (7+((settings->max_prefetch_length*1)/8));
cerr<<total_covered_miss_count<<","<<(100.0*total_covered_miss_count)/total_miss_sample_count<<","<<current_running_count<<","<<(100.0*current_running_count)/settings->total_dyn_ins_count<<endl;
uint64_t total_count = dynamic_cfg->get_static_count();
cerr<<"Static counts: "<<static_prefetch_count<<","<<total_count<<","<<(100.0*static_prefetch_count)/total_count<<endl;
uint64_t total_size = dynamic_cfg->get_static_size();
double static_prefetch_size = static_prefetch_count*size_of_prefetch_inst;
cerr<<"Static size: "<<static_prefetch_size<<","<<total_size<<","<<(100.0*static_prefetch_size)/total_size<<endl;
}
};
class Miss_Profile
{
public:
Miss_Map profile;
Miss_Profile(MyConfigWrapper &conf, Settings &settings, CFG &dynamic_cfg)
{
string miss_log_path = conf.lookup("miss_log", "/tmp/");
if(miss_log_path == "/tmp/")
{
panic("ICache Miss Log file is not present in the config");
}
vector<string> raw_icache_miss_lbr_sample_data;
read_full_file(miss_log_path, raw_icache_miss_lbr_sample_data);
for(uint64_t i = 0; i< raw_icache_miss_lbr_sample_data.size();i++)
{
string line = raw_icache_miss_lbr_sample_data[i];
profile.push(line, dynamic_cfg);
}
string output_name = "";
output_name+=to_string(settings.multiline_mode)+".";
output_name+=to_string(settings.min_distance_cycle_count)+".";
output_name+=to_string(settings.max_distance_cycle_count)+".";
output_name+=to_string(int(settings.dyn_ins_count_inc_ratio*100))+".";
output_name+=to_string(int(settings.fan_out_ratio*100))+".";
output_name+="txt";
ofstream prefetch_out(output_name.c_str());
profile.generate_prefetch_locations(&settings,&dynamic_cfg, prefetch_out);
}
};
#endif //LBR_MISS_SAMPLE_H_
| [
"[email protected]"
] | |
6dd82f3dc9da4c1cf6fb47c4b0958649f50ed3d5 | 903cc1b03935f5b551bd531142751e15698c4a37 | /lab9/propuestos/test/writeStrucuture.cpp | 6fcb71a558816887bc24279f013114d3f9bfb6cb | [] | no_license | ealvan/ProgSistemas | a25af731e4fa9c836f982e4eadbcaa678d3b2b3b | 035a95bce77bdcaa618244a00df5e0c6d4f0514f | refs/heads/main | 2023-07-10T10:25:40.540586 | 2021-08-20T04:18:43 | 2021-08-20T04:18:43 | 398,153,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | cpp | #include <iostream>
#include <fstream>
using namespace std;
struct Persona{
string nombre;
short int dia;
};
void writeData(ofstream & out, Persona* one){
unsigned size = one->nombre.size();
out.write((char*)&size, sizeof(size));
out.write(one->nombre.data(), size);
out.write((char*)&one->dia, sizeof(one->dia));
}
void readData(ifstream & in, Persona* one){
size_t nameSize =0;
in >> nameSize;
one->nombre.resize(nameSize);
in.read(&one->nombre[0], nameSize);
in >> one->dia;
}
int main(){
Persona p = {"nombre", 12};
ofstream file;
file.open("struct.dat", ios::out | ios::binary);
if(!file){
cerr << "Error de files"<<endl;
return 0;
}
writeData(file, &p);
file.close();
ifstream ifile;
ifile.open("struct.dat", ios::in | ios::binary);
Persona in;
readData(ifile, &in);
cout << "Nombre: "<<in.nombre << endl;
cout << "Dia : "<<in.dia << endl;
ifile.close();
} | [
"[email protected]"
] | |
2e9d85b64906fe178dee285b14d1abcc21a62fde | 624a7ca19d7a8e1ba0d1d2dc4c345f6ae06f4f94 | /sw/source/filter/ww8/rtfexport.cxx | 6e922245e6cbaadc5f2f763142d943e24f8bbb6e | [] | no_license | jonasfj/libreoffice-writer | e6c4c92ece47bc61f1f6bf93fe24b34a1836c53c | 2d415c9854fb6111ac924ee95044c7e1a931433c | refs/heads/master | 2021-01-25T08:42:25.367195 | 2010-10-03T14:16:52 | 2010-10-03T14:16:52 | 954,612 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 40,049 | cxx | /*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2010 Miklos Vajna.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "rtfexport.hxx"
#include "rtfexportfilter.hxx"
#include "rtfsdrexport.hxx"
#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
#include <com/sun/star/document/XDocumentProperties.hpp>
#include <com/sun/star/i18n/ScriptType.hdl>
#include <com/sun/star/frame/XModel.hpp>
#include <map>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <IMark.hxx>
#include <docsh.hxx>
#include <ndtxt.hxx>
#include <wrtww8.hxx>
#include <fltini.hxx>
#include <fmtline.hxx>
#include <fmtpdsc.hxx>
#include <frmfmt.hxx>
#include <section.hxx>
#include <pagedesc.hxx>
#include <swtable.hxx>
#include <fmtfsize.hxx>
#include <frmatr.hxx>
#include <ftninfo.hxx>
#include <fmthdft.hxx>
#include <editeng/fontitem.hxx>
#include <editeng/colritem.hxx>
#include <editeng/udlnitem.hxx>
#include <editeng/boxitem.hxx>
#include <editeng/brshitem.hxx>
#include <editeng/shaditem.hxx>
#include <editeng/lrspitem.hxx>
#include <editeng/ulspitem.hxx>
#include <editeng/paperinf.hxx>
#include <editeng/protitem.hxx>
#include <docary.hxx>
#include <numrule.hxx>
#include <charfmt.hxx>
#include <lineinfo.hxx>
#include <swmodule.hxx>
#include "ww8par.hxx"
#include "ww8scan.hxx"
#include <comphelper/string.hxx>
#include <rtl/ustrbuf.hxx>
#include <vcl/font.hxx>
#include <svtools/rtfkeywd.hxx>
#include <unotools/configmgr.hxx>
using namespace ::comphelper;
using namespace ::com::sun::star;
using rtl::OString;
using rtl::OUString;
using rtl::OStringBuffer;
using rtl::OUStringBuffer;
using sw::mark::IMark;
#if defined(UNX)
const sal_Char RtfExport::sNewLine = '\012';
#else
const sal_Char __FAR_DATA RtfExport::sNewLine[] = "\015\012";
#endif
// the default text encoding for the export, if it doesn't fit unicode will
// be used
#define DEF_ENCODING RTL_TEXTENCODING_ASCII_US
AttributeOutputBase& RtfExport::AttrOutput() const
{
return *m_pAttrOutput;
}
MSWordSections& RtfExport::Sections() const
{
return *m_pSections;
}
RtfSdrExport& RtfExport::SdrExporter() const
{
return *m_pSdrExport;
}
bool RtfExport::CollapseScriptsforWordOk( USHORT nScript, USHORT nWhich )
{
// FIXME is this actually true for rtf? - this is copied from DOCX
if ( nScript == i18n::ScriptType::ASIAN )
{
// for asian in ww8, there is only one fontsize
// and one fontstyle (posture/weight)
switch ( nWhich )
{
case RES_CHRATR_FONTSIZE:
case RES_CHRATR_POSTURE:
case RES_CHRATR_WEIGHT:
return false;
default:
break;
}
}
else if ( nScript != i18n::ScriptType::COMPLEX )
{
// for western in ww8, there is only one fontsize
// and one fontstyle (posture/weight)
switch ( nWhich )
{
case RES_CHRATR_CJK_FONTSIZE:
case RES_CHRATR_CJK_POSTURE:
case RES_CHRATR_CJK_WEIGHT:
return false;
default:
break;
}
}
return true;
}
void RtfExport::AppendBookmarks( const SwTxtNode& rNode, xub_StrLen nAktPos, xub_StrLen nLen )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
std::vector< OUString > aStarts;
std::vector< OUString > aEnds;
IMarkVector aMarks;
if ( GetBookmarks( rNode, nAktPos, nAktPos + nLen, aMarks ) )
{
for ( IMarkVector::const_iterator it = aMarks.begin(), end = aMarks.end();
it < end; ++it )
{
IMark* pMark = (*it);
xub_StrLen nStart = pMark->GetMarkStart().nContent.GetIndex();
xub_StrLen nEnd = pMark->GetMarkEnd().nContent.GetIndex();
if ( nStart == nAktPos )
aStarts.push_back( pMark->GetName() );
if ( nEnd == nAktPos )
aEnds.push_back( pMark->GetName() );
}
}
m_pAttrOutput->WriteBookmarks_Impl( aStarts, aEnds );
}
void RtfExport::AppendBookmark( const OUString& rName, bool /*bSkip*/ )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
std::vector<OUString> aStarts;
std::vector<OUString> aEnds;
aStarts.push_back(rName);
aEnds.push_back(rName);
m_pAttrOutput->WriteBookmarks_Impl(aStarts, aEnds);
}
void RtfExport::WriteChar( sal_Unicode )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
/* WriteChar() has nothing to do for rtf. */
}
static bool IsExportNumRule( const SwNumRule& rRule, BYTE* pEnd = 0 )
{
BYTE nEnd = MAXLEVEL;
while( nEnd-- && !rRule.GetNumFmt( nEnd ))
;
++nEnd;
const SwNumFmt* pNFmt;
BYTE nLvl;
for( nLvl = 0; nLvl < nEnd; ++nLvl )
if( SVX_NUM_NUMBER_NONE != ( pNFmt = &rRule.Get( nLvl ))
->GetNumberingType() || pNFmt->GetPrefix().Len() ||
(pNFmt->GetSuffix().Len() && pNFmt->GetSuffix() != aDotStr ))
break;
if( pEnd )
*pEnd = nEnd;
return nLvl != nEnd;
}
void RtfExport::BuildNumbering()
{
const SwNumRuleTbl& rListTbl = pDoc->GetNumRuleTbl();
for( USHORT n = rListTbl.Count()+1; n; )
{
SwNumRule* pRule;
--n;
if( n == rListTbl.Count() )
pRule = (SwNumRule*)pDoc->GetOutlineNumRule();
else
{
pRule = rListTbl[ n ];
if( !pDoc->IsUsed( *pRule ))
continue;
}
if( IsExportNumRule( *pRule ))
GetId( *pRule );
}
}
void RtfExport::WriteNumbering()
{
OSL_TRACE("%s start", OSL_THIS_FUNC);
if ( !pUsedNumTbl )
return; // no numbering is used
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_IGNORE << OOO_STRING_SVTOOLS_RTF_LISTTABLE;
AbstractNumberingDefinitions();
Strm() << '}';
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_LISTOVERRIDETABLE;
NumberingDefinitions();
Strm() << '}';
OSL_TRACE("%s end", OSL_THIS_FUNC);
}
void RtfExport::WriteRevTab()
{
OSL_TRACE("%s", OSL_THIS_FUNC);
int nRevAuthors = pDoc->GetRedlineTbl().Count();
if (nRevAuthors < 1)
return;
// RTF always seems to use Unknown as the default first entry
String sUnknown(RTL_CONSTASCII_USTRINGPARAM("Unknown"));
GetRedline(sUnknown);
for( USHORT i = 0; i < pDoc->GetRedlineTbl().Count(); ++i )
{
const SwRedline* pRedl = pDoc->GetRedlineTbl()[ i ];
GetRedline(SW_MOD()->GetRedlineAuthor(pRedl->GetAuthor()));
}
// Now write the table
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_IGNORE << OOO_STRING_SVTOOLS_RTF_REVTBL << ' ';
for(std::map<String,USHORT>::iterator aIter = m_aRedlineTbl.begin(); aIter != m_aRedlineTbl.end(); ++aIter)
Strm() << '{' << OutString((*aIter).first, eDefaultEncoding) << ";}";
Strm() << '}' << sNewLine;
}
void RtfExport::WriteHeadersFooters( BYTE nHeadFootFlags,
const SwFrmFmt& rFmt, const SwFrmFmt& rLeftFmt, const SwFrmFmt& rFirstPageFmt, BYTE /*nBreakCode*/ )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
// headers
if ( nHeadFootFlags & nsHdFtFlags::WW8_HEADER_EVEN )
WriteHeaderFooter( rLeftFmt, true, OOO_STRING_SVTOOLS_RTF_HEADERL );
if ( nHeadFootFlags & nsHdFtFlags::WW8_HEADER_ODD )
WriteHeaderFooter( rFmt, true, OOO_STRING_SVTOOLS_RTF_HEADER );
if ( nHeadFootFlags & nsHdFtFlags::WW8_HEADER_FIRST )
WriteHeaderFooter( rFirstPageFmt, true, OOO_STRING_SVTOOLS_RTF_HEADERF );
// footers
if ( nHeadFootFlags & nsHdFtFlags::WW8_FOOTER_EVEN )
WriteHeaderFooter( rLeftFmt, false, OOO_STRING_SVTOOLS_RTF_FOOTERL );
if ( nHeadFootFlags & nsHdFtFlags::WW8_FOOTER_ODD )
WriteHeaderFooter( rFmt, false, OOO_STRING_SVTOOLS_RTF_FOOTER );
if ( nHeadFootFlags & nsHdFtFlags::WW8_FOOTER_FIRST )
WriteHeaderFooter( rFirstPageFmt, false, OOO_STRING_SVTOOLS_RTF_FOOTERF );
}
void RtfExport::OutputField( const SwField* pFld, ww::eField eFldType, const String& rFldCmd, BYTE nMode )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
m_pAttrOutput->WriteField_Impl( pFld, eFldType, rFldCmd, nMode );
}
void RtfExport::WriteFormData( const ::sw::mark::IFieldmark& /*rFieldmark*/ )
{
OSL_TRACE("TODO: %s", OSL_THIS_FUNC);
}
void RtfExport::WriteHyperlinkData( const ::sw::mark::IFieldmark& /*rFieldmark*/ )
{
OSL_TRACE("TODO: %s", OSL_THIS_FUNC);
}
void RtfExport::DoComboBox(const rtl::OUString& /*rName*/,
const rtl::OUString& /*rHelp*/,
const rtl::OUString& /*rToolTip*/,
const rtl::OUString& /*rSelected*/,
uno::Sequence<rtl::OUString>& /*rListItems*/)
{
OSL_TRACE("%s", OSL_THIS_FUNC);
// this is handled in RtfAttributeOutput::OutputFlyFrame_Impl
}
void RtfExport::DoFormText(const SwInputField* /*pFld*/)
{
OSL_TRACE("%s", OSL_THIS_FUNC);
// this is hanled in RtfAttributeOutput::OutputFlyFrame_Impl
}
ULONG RtfExport::ReplaceCr( BYTE )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
// Completely unused for Rtf export... only here for code sharing
// purpose with binary export
return 0;
}
void RtfExport::WriteFonts()
{
Strm() << sNewLine << '{' << OOO_STRING_SVTOOLS_RTF_FONTTBL;
maFontHelper.WriteFontTable( *m_pAttrOutput );
Strm() << '}';
}
void RtfExport::WriteStyles()
{
OSL_TRACE("%s start", OSL_THIS_FUNC);
pStyles->OutputStylesTable();
OSL_TRACE("%s end", OSL_THIS_FUNC);
}
void RtfExport::WriteMainText()
{
OSL_TRACE("%s start", OSL_THIS_FUNC);
pCurPam->GetPoint()->nNode = pDoc->GetNodes().GetEndOfContent().StartOfSectionNode()->GetIndex();
WriteText();
OSL_TRACE("%s end", OSL_THIS_FUNC);
}
void RtfExport::WriteInfo()
{
OSL_TRACE("%s", OSL_THIS_FUNC);
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_INFO;
SwDocShell *pDocShell(pDoc->GetDocShell());
uno::Reference<document::XDocumentProperties> xDocProps;
if (pDocShell) {
uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
pDocShell->GetModel(), uno::UNO_QUERY);
xDocProps.set(xDPS->getDocumentProperties());
}
if (xDocProps.is()) {
OutUnicode(OOO_STRING_SVTOOLS_RTF_TITLE, xDocProps->getTitle());
OutUnicode(OOO_STRING_SVTOOLS_RTF_SUBJECT, xDocProps->getSubject());
OutUnicode(OOO_STRING_SVTOOLS_RTF_KEYWORDS,
::comphelper::string::convertCommaSeparated(xDocProps->getKeywords()));
OutUnicode(OOO_STRING_SVTOOLS_RTF_DOCCOMM, xDocProps->getDescription());
OutUnicode(OOO_STRING_SVTOOLS_RTF_AUTHOR, xDocProps->getAuthor());
OutDateTime(OOO_STRING_SVTOOLS_RTF_CREATIM, xDocProps->getCreationDate());
OutUnicode(OOO_STRING_SVTOOLS_RTF_AUTHOR,xDocProps->getModifiedBy());
OutDateTime(OOO_STRING_SVTOOLS_RTF_REVTIM, xDocProps->getModificationDate());
OutDateTime(OOO_STRING_SVTOOLS_RTF_PRINTIM, xDocProps->getPrintDate());
}
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_COMMENT << " ";
OUString sProduct;
utl::ConfigManager::GetDirectConfigProperty(utl::ConfigManager::PRODUCTNAME) >>= sProduct;
Strm() << OUStringToOString( sProduct, eCurrentEncoding) << "}{" << OOO_STRING_SVTOOLS_RTF_VERN;
OutULong( SUPD*10 ) << '}';
Strm() << '}';
}
void RtfExport::WritePageDescTable()
{
OSL_TRACE("%s", OSL_THIS_FUNC);
// Write page descriptions (page styles)
USHORT nSize = pDoc->GetPageDescCnt();
if( !nSize )
return;
Strm() << sNewLine; // a separator
bOutPageDescs = TRUE;
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_IGNORE << OOO_STRING_SVTOOLS_RTF_PGDSCTBL;
for( USHORT n = 0; n < nSize; ++n )
{
const SwPageDesc& rPageDesc =
const_cast<const SwDoc*>(pDoc)->GetPageDesc( n );
Strm() << sNewLine << '{' << OOO_STRING_SVTOOLS_RTF_PGDSC;
OutULong( n ) << OOO_STRING_SVTOOLS_RTF_PGDSCUSE;
OutULong( rPageDesc.ReadUseOn() );
OutPageDescription( rPageDesc, FALSE, FALSE );
// search for the next page description
USHORT i = nSize;
while( i )
if( rPageDesc.GetFollow() ==
&const_cast<const SwDoc *>(pDoc)->GetPageDesc( --i ) )
break;
Strm() << OOO_STRING_SVTOOLS_RTF_PGDSCNXT;
OutULong( i ) << ' ';
Strm() << OutString( rPageDesc.GetName(), eDefaultEncoding) << ";}";
}
Strm() << '}' << sNewLine;
bOutPageDescs = FALSE;
}
void RtfExport::ExportDocument_Impl()
{
#ifdef DEBUG
// MSWordExportBase::WriteText and others write debug messages to std::clog
// which is not interesting while debugging RtfExport
std::ostringstream aOss;
std::streambuf *pOldBuf = std::clog.rdbuf(aOss.rdbuf());
#endif
// Make the header
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_RTF << '1'
<< OOO_STRING_SVTOOLS_RTF_ANSI;
Strm() << OOO_STRING_SVTOOLS_RTF_DEFF;
OutULong( maFontHelper.GetId( (SvxFontItem&)pDoc->GetAttrPool().GetDefaultItem(
RES_CHRATR_FONT ) ));
// If this not exist, MS don't understand our ansi characters (0x80-0xff).
Strm() << "\\adeflang1025";
// Font table
WriteFonts();
pStyles = new MSWordStyles( *this );
// Color and stylesheet table
WriteStyles();
// List table
BuildNumbering();
WriteNumbering();
WriteRevTab();
WriteInfo();
// Default TabSize
Strm() << m_pAttrOutput->m_aTabStop.makeStringAndClear() << sNewLine;
// Page description
WritePageDescTable();
// Enable form protection by default if needed, as there is no switch to
// enable it on a per-section basis. OTOH don't always enable it as it
// breaks moving of drawings - so write it only in case there is really a
// protected section in the document.
{
const SfxItemPool& rPool = pDoc->GetAttrPool();
USHORT nMaxItem = rPool.GetItemCount(RES_PROTECT);
for( USHORT n = 0; n < nMaxItem; ++n )
{
const SvxProtectItem* pProtect = (const SvxProtectItem*)rPool.GetItem(RES_PROTECT, n);
if (pProtect && pProtect->IsCntntProtected())
{
Strm() << OOO_STRING_SVTOOLS_RTF_FORMPROT;
break;
}
}
}
// enable form field shading
Strm() << OOO_STRING_SVTOOLS_RTF_FORMSHADE;
// size and empty margins of the page
if( pDoc->GetPageDescCnt() )
{
//JP 06.04.99: Bug 64361 - Seeking the first SwFmtPageDesc. If
// no set, the default is valid
const SwFmtPageDesc* pSttPgDsc = 0;
{
const SwNode& rSttNd = *pDoc->GetNodes()[
pDoc->GetNodes().GetEndOfExtras().GetIndex() + 2 ];
const SfxItemSet* pSet = 0;
if( rSttNd.IsCntntNode() )
pSet = &rSttNd.GetCntntNode()->GetSwAttrSet();
else if( rSttNd.IsTableNode() )
pSet = &rSttNd.GetTableNode()->GetTable().
GetFrmFmt()->GetAttrSet();
else if( rSttNd.IsSectionNode() )
pSet = &rSttNd.GetSectionNode()->GetSection().
GetFmt()->GetAttrSet();
if( pSet )
{
USHORT nPosInDoc;
pSttPgDsc = (SwFmtPageDesc*)&pSet->Get( RES_PAGEDESC );
if( !pSttPgDsc->GetPageDesc() )
pSttPgDsc = 0;
else if( pDoc->FindPageDescByName( pSttPgDsc->
GetPageDesc()->GetName(), &nPosInDoc ))
{
Strm() << '{' << OOO_STRING_SVTOOLS_RTF_IGNORE << OOO_STRING_SVTOOLS_RTF_PGDSCNO;
OutULong( nPosInDoc ) << '}';
}
}
}
const SwPageDesc& rPageDesc = pSttPgDsc ? *pSttPgDsc->GetPageDesc()
: const_cast<const SwDoc *>(pDoc)->GetPageDesc( 0 );
const SwFrmFmt &rFmtPage = rPageDesc.GetMaster();
{
if( rPageDesc.GetLandscape() )
Strm() << OOO_STRING_SVTOOLS_RTF_LANDSCAPE;
const SwFmtFrmSize& rSz = rFmtPage.GetFrmSize();
// Clipboard document is always created without a printer, then
// the size will be always LONG_MAX! Solution then is to use A4
if( LONG_MAX == rSz.GetHeight() || LONG_MAX == rSz.GetWidth() )
{
Strm() << OOO_STRING_SVTOOLS_RTF_PAPERH;
Size a4 = SvxPaperInfo::GetPaperSize(PAPER_A4);
OutULong( a4.Height() ) << OOO_STRING_SVTOOLS_RTF_PAPERW;
OutULong( a4.Width() );
}
else
{
Strm() << OOO_STRING_SVTOOLS_RTF_PAPERH;
OutULong( rSz.GetHeight() ) << OOO_STRING_SVTOOLS_RTF_PAPERW;
OutULong( rSz.GetWidth() );
}
}
{
const SvxLRSpaceItem& rLR = rFmtPage.GetLRSpace();
Strm() << OOO_STRING_SVTOOLS_RTF_MARGL;
OutLong( rLR.GetLeft() ) << OOO_STRING_SVTOOLS_RTF_MARGR;
OutLong( rLR.GetRight() );
}
{
const SvxULSpaceItem& rUL = rFmtPage.GetULSpace();
Strm() << OOO_STRING_SVTOOLS_RTF_MARGT;
OutLong( rUL.GetUpper() ) << OOO_STRING_SVTOOLS_RTF_MARGB;
OutLong( rUL.GetLower() );
}
Strm() << OOO_STRING_SVTOOLS_RTF_SECTD << OOO_STRING_SVTOOLS_RTF_SBKNONE;
// All sections are unlocked by default
Strm() << OOO_STRING_SVTOOLS_RTF_SECTUNLOCKED;
OutLong(1);
OutPageDescription( rPageDesc, FALSE, TRUE ); // Changed bCheckForFirstPage to TRUE so headers
// following title page are correctly added - i13107
if( pSttPgDsc )
{
pAktPageDesc = &rPageDesc;
}
}
// line numbering
const SwLineNumberInfo& rLnNumInfo = pDoc->GetLineNumberInfo();
if ( rLnNumInfo.IsPaintLineNumbers() )
AttrOutput().SectionLineNumbering( 0, rLnNumInfo );
{
// write the footnotes and endnotes-out Info
const SwFtnInfo& rFtnInfo = pDoc->GetFtnInfo();
const char* pOut = FTNPOS_CHAPTER == rFtnInfo.ePos
? OOO_STRING_SVTOOLS_RTF_ENDDOC
: OOO_STRING_SVTOOLS_RTF_FTNBJ;
Strm() << pOut << OOO_STRING_SVTOOLS_RTF_FTNSTART;
OutLong( rFtnInfo.nFtnOffset + 1 );
switch( rFtnInfo.eNum )
{
case FTNNUM_PAGE: pOut = OOO_STRING_SVTOOLS_RTF_FTNRSTPG; break;
case FTNNUM_DOC: pOut = OOO_STRING_SVTOOLS_RTF_FTNRSTCONT; break;
// case FTNNUM_CHAPTER:
default: pOut = OOO_STRING_SVTOOLS_RTF_FTNRESTART; break;
}
Strm() << pOut;
switch( rFtnInfo.aFmt.GetNumberingType() )
{
case SVX_NUM_CHARS_LOWER_LETTER:
case SVX_NUM_CHARS_LOWER_LETTER_N: pOut = OOO_STRING_SVTOOLS_RTF_FTNNALC; break;
case SVX_NUM_CHARS_UPPER_LETTER:
case SVX_NUM_CHARS_UPPER_LETTER_N: pOut = OOO_STRING_SVTOOLS_RTF_FTNNAUC; break;
case SVX_NUM_ROMAN_LOWER: pOut = OOO_STRING_SVTOOLS_RTF_FTNNRLC; break;
case SVX_NUM_ROMAN_UPPER: pOut = OOO_STRING_SVTOOLS_RTF_FTNNRUC; break;
case SVX_NUM_CHAR_SPECIAL: pOut = OOO_STRING_SVTOOLS_RTF_FTNNCHI; break;
// case SVX_NUM_ARABIC:
default: pOut = OOO_STRING_SVTOOLS_RTF_FTNNAR; break;
}
Strm() << pOut;
const SwEndNoteInfo& rEndNoteInfo = pDoc->GetEndNoteInfo();
Strm() << OOO_STRING_SVTOOLS_RTF_AENDDOC << OOO_STRING_SVTOOLS_RTF_AFTNRSTCONT
<< OOO_STRING_SVTOOLS_RTF_AFTNSTART;
OutLong( rEndNoteInfo.nFtnOffset + 1 );
switch( rEndNoteInfo.aFmt.GetNumberingType() )
{
case SVX_NUM_CHARS_LOWER_LETTER:
case SVX_NUM_CHARS_LOWER_LETTER_N: pOut = OOO_STRING_SVTOOLS_RTF_AFTNNALC; break;
case SVX_NUM_CHARS_UPPER_LETTER:
case SVX_NUM_CHARS_UPPER_LETTER_N: pOut = OOO_STRING_SVTOOLS_RTF_AFTNNAUC; break;
case SVX_NUM_ROMAN_LOWER: pOut = OOO_STRING_SVTOOLS_RTF_AFTNNRLC; break;
case SVX_NUM_ROMAN_UPPER: pOut = OOO_STRING_SVTOOLS_RTF_AFTNNRUC; break;
case SVX_NUM_CHAR_SPECIAL: pOut = OOO_STRING_SVTOOLS_RTF_AFTNNCHI; break;
// case SVX_NUM_ARABIC:
default: pOut = OOO_STRING_SVTOOLS_RTF_AFTNNAR; break;
}
Strm() << pOut;
}
Strm() << sNewLine;
// Init sections
m_pSections = new MSWordSections( *this );
WriteMainText();
Strm() << '}';
#ifdef DEBUG
std::clog.rdbuf(pOldBuf);
#endif
}
void RtfExport::PrepareNewPageDesc( const SfxItemSet* pSet,
const SwNode& rNd, const SwFmtPageDesc* pNewPgDescFmt,
const SwPageDesc* pNewPgDesc )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
const SwSectionFmt* pFmt = GetSectionFormat( rNd );
const ULONG nLnNm = GetSectionLineNo( pSet, rNd );
OSL_ENSURE( pNewPgDescFmt || pNewPgDesc, "Neither page desc format nor page desc provided." );
if ( pNewPgDescFmt )
m_pSections->AppendSection( *pNewPgDescFmt, rNd, pFmt, nLnNm );
else if ( pNewPgDesc )
m_pSections->AppendSection( pNewPgDesc, rNd, pFmt, nLnNm );
AttrOutput().SectionBreak( msword::PageBreak, m_pSections->CurrentSectionInfo() );
}
bool RtfExport::DisallowInheritingOutlineNumbering( const SwFmt& rFmt )
{
bool bRet( false );
OSL_TRACE("%s", OSL_THIS_FUNC);
if (SFX_ITEM_SET != rFmt.GetItemState(RES_PARATR_NUMRULE, false))
{
if (const SwFmt *pParent = rFmt.DerivedFrom())
{
if (((const SwTxtFmtColl*)pParent)->IsAssignedToListLevelOfOutlineStyle())
{
// Level 9 disables the outline
Strm() << OOO_STRING_SVTOOLS_RTF_LEVEL << 9;
bRet = true;
}
}
}
return bRet;
}
void RtfExport::OutputGrfNode( const SwGrfNode& )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
/* noop, see RtfAttributeOutput::FlyFrameGraphic */
}
void RtfExport::OutputOLENode( const SwOLENode& )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
/* noop, see RtfAttributeOutput::FlyFrameOLE */
}
void RtfExport::AppendSection( const SwPageDesc* pPageDesc, const SwSectionFmt* pFmt, ULONG nLnNum )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
m_pSections->AppendSection( pPageDesc, pFmt, nLnNum );
AttrOutput().SectionBreak( msword::PageBreak, m_pSections->CurrentSectionInfo() );
}
RtfExport::RtfExport( RtfExportFilter *pFilter, SwDoc *pDocument, SwPaM *pCurrentPam, SwPaM *pOriginalPam, Writer* pWriter )
: MSWordExportBase( pDocument, pCurrentPam, pOriginalPam ),
m_pFilter( pFilter ),
m_pWriter( pWriter ),
m_pAttrOutput( NULL ),
m_pSections( NULL ),
m_pSdrExport( NULL ),
eDefaultEncoding(
rtl_getTextEncodingFromWindowsCharset(
sw::ms::rtl_TextEncodingToWinCharset(DEF_ENCODING))),
eCurrentEncoding(eDefaultEncoding),
bRTFFlySyntax(false)
{
// the attribute output for the document
m_pAttrOutput = new RtfAttributeOutput( *this );
// that just causes problems for RTF
bSubstituteBullets = false;
// needed to have a complete font table
maFontHelper.bLoadAllFonts = true;
// the related SdrExport
m_pSdrExport = new RtfSdrExport( *this );
if (!m_pWriter)
m_pWriter = &m_pFilter->m_aWriter;
}
RtfExport::~RtfExport()
{
delete m_pAttrOutput, m_pAttrOutput = NULL;
delete m_pSdrExport, m_pSdrExport = NULL;
}
SvStream& RtfExport::Strm()
{
return m_pWriter->Strm();
}
SvStream& RtfExport::OutULong( ULONG nVal )
{
return m_pWriter->OutULong( Strm(), nVal );
}
SvStream& RtfExport::OutLong( long nVal )
{
return m_pWriter->OutLong( Strm(), nVal );
}
void RtfExport::OutUnicode(const sal_Char *pToken, const String &rContent)
{
if (rContent.Len())
{
Strm() << '{' << pToken << ' ';
Strm() << OutString( rContent, eCurrentEncoding ).getStr();
Strm() << '}';
}
}
OString RtfExport::OutHex(ULONG nHex, BYTE nLen)
{
sal_Char aNToABuf[] = "0000000000000000";
OSL_ENSURE( nLen < sizeof(aNToABuf), "nLen is too big" );
if( nLen >= sizeof(aNToABuf) )
nLen = (sizeof(aNToABuf)-1);
// Set pointer to the buffer end
sal_Char* pStr = aNToABuf + (sizeof(aNToABuf)-1);
for( BYTE n = 0; n < nLen; ++n )
{
*(--pStr) = (sal_Char)(nHex & 0xf ) + 48;
if( *pStr > '9' )
*pStr += 39;
nHex >>= 4;
}
return OString(pStr);
}
OString RtfExport::OutChar(sal_Unicode c, int *pUCMode, rtl_TextEncoding eDestEnc)
{
OStringBuffer aBuf;
const sal_Char* pStr = 0;
// 0x0b instead of \n, etc because of the replacements in SwAttrIter::GetSnippet()
switch (c)
{
case 0x0b:
// hard line break
pStr = OOO_STRING_SVTOOLS_RTF_LINE;
break;
case '\t':
pStr = OOO_STRING_SVTOOLS_RTF_TAB;
break;
case '\\':
case '}':
case '{':
aBuf.append('\\');
aBuf.append((sal_Char)c);
break;
case 0xa0:
// non-breaking space
pStr = "\\~";
break;
case 0x1e:
// non-breaking hyphen
pStr = "\\_";
break;
case 0x1f:
// optional hyphen
pStr = "\\-";
break;
default:
if (c >= ' ' && c <= '~')
aBuf.append((sal_Char)c);
else {
//If we can't convert to the dest encoding, or if
//its an uncommon multibyte sequence which most
//readers won't be able to handle correctly, then
//If we can't convert to the dest encoding, then
//export as unicode
OUString sBuf(&c, 1);
OString sConverted;
sal_uInt32 nFlags =
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |
RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR;
bool bWriteAsUnicode = !(sBuf.convertToString(&sConverted,
eDestEnc, nFlags))
|| (RTL_TEXTENCODING_UTF8==eDestEnc); // #i43933# do not export UTF-8 chars in RTF;
if (bWriteAsUnicode)
sBuf.convertToString(&sConverted,
eDestEnc, OUSTRING_TO_OSTRING_CVTFLAGS);
const sal_Int32 nLen = sConverted.getLength();
if (bWriteAsUnicode && pUCMode)
{
// then write as unicode - character
if (*pUCMode != nLen)
{
aBuf.append("\\uc");
aBuf.append((sal_Int32)nLen);
// #i47831# add an additional whitespace, so that "document whitespaces" are not ignored.
aBuf.append(' ');
*pUCMode = nLen;
}
aBuf.append("\\u");
aBuf.append((sal_Int32)c);
}
for (sal_Int32 nI = 0; nI < nLen; ++nI)
{
aBuf.append("\\'");
aBuf.append(OutHex(sConverted.getStr()[nI], 2));
}
}
}
if (pStr) {
aBuf.append(pStr);
aBuf.append(' ');
}
return aBuf.makeStringAndClear();
}
OString RtfExport::OutString(const String &rStr, rtl_TextEncoding eDestEnc)
{
OSL_TRACE("%s, rStr = '%s'", OSL_THIS_FUNC,
OUStringToOString( OUString( rStr ), eCurrentEncoding ).getStr());
OStringBuffer aBuf;
int nUCMode = 1;
for (xub_StrLen n = 0; n < rStr.Len(); ++n)
aBuf.append(OutChar(rStr.GetChar(n), &nUCMode, eDestEnc));
if (nUCMode != 1) {
aBuf.append(OOO_STRING_SVTOOLS_RTF_UC);
aBuf.append((sal_Int32)1);
aBuf.append(" "); // #i47831# add an additional whitespace, so that "document whitespaces" are not ignored.;
}
return aBuf.makeStringAndClear();
}
void RtfExport::OutDateTime(const sal_Char* pStr, const util::DateTime& rDT )
{
Strm() << '{' << pStr << OOO_STRING_SVTOOLS_RTF_YR;
OutULong( rDT.Year ) << OOO_STRING_SVTOOLS_RTF_MO;
OutULong( rDT.Month ) << OOO_STRING_SVTOOLS_RTF_DY;
OutULong( rDT.Day ) << OOO_STRING_SVTOOLS_RTF_HR;
OutULong( rDT.Hours ) << OOO_STRING_SVTOOLS_RTF_MIN;
OutULong( rDT.Minutes ) << '}';
}
USHORT RtfExport::GetColor( const Color& rColor ) const
{
for (RtfColorTbl::const_iterator it=m_aColTbl.begin() ; it != m_aColTbl.end(); it++ )
if ((*it).second == rColor) {
OSL_TRACE("%s returning %d (%d,%d,%d)", OSL_THIS_FUNC, (*it).first, rColor.GetRed(), rColor.GetGreen(), rColor.GetBlue());
return (*it).first;
}
OSL_ENSURE( FALSE, "No such Color in m_aColTbl!" );
return 0;
}
void RtfExport::InsColor( const Color& rCol )
{
USHORT n;
for (RtfColorTbl::iterator it=m_aColTbl.begin() ; it != m_aColTbl.end(); it++ )
if ((*it).second == rCol)
return; // Already in the table
if (rCol.GetColor() == COL_AUTO)
n = 0;
else
{
n = m_aColTbl.size();
// Fix for the case when first a !COL_AUTO gets inserted as #0, then
// gets overwritten by COL_AUTO
if (!n)
n++;
}
m_aColTbl.insert(std::pair<USHORT,Color>( n, rCol ));
}
void RtfExport::InsColorLine( const SvxBoxItem& rBox )
{
const SvxBorderLine* pLine = 0;
if( rBox.GetTop() )
InsColor( (pLine = rBox.GetTop())->GetColor() );
if( rBox.GetBottom() && pLine != rBox.GetBottom() )
InsColor( (pLine = rBox.GetBottom())->GetColor() );
if( rBox.GetLeft() && pLine != rBox.GetLeft() )
InsColor( (pLine = rBox.GetLeft())->GetColor() );
if( rBox.GetRight() && pLine != rBox.GetRight() )
InsColor( rBox.GetRight()->GetColor() );
}
void RtfExport::OutColorTable()
{
// Build the table from rPool since the colors provided to
// RtfAttributeOutput callbacks are too late.
USHORT n, nMaxItem;
const SfxItemPool& rPool = pDoc->GetAttrPool();
// char color
{
const SvxColorItem* pCol = (const SvxColorItem*)GetDfltAttr(
RES_CHRATR_COLOR );
InsColor( pCol->GetValue() );
if( 0 != ( pCol = (const SvxColorItem*)rPool.GetPoolDefaultItem(
RES_CHRATR_COLOR ) ))
InsColor( pCol->GetValue() );
nMaxItem = rPool.GetItemCount(RES_CHRATR_COLOR);
for( n = 0; n < nMaxItem; ++n )
{
if( 0 != (pCol = (const SvxColorItem*)rPool.GetItem(
RES_CHRATR_COLOR, n ) ) )
InsColor( pCol->GetValue() );
}
const SvxUnderlineItem* pUnder = (const SvxUnderlineItem*)GetDfltAttr( RES_CHRATR_UNDERLINE );
InsColor( pUnder->GetColor() );
nMaxItem = rPool.GetItemCount(RES_CHRATR_UNDERLINE);
for( n = 0; n < nMaxItem;n++)
{
if( 0 != (pUnder = (const SvxUnderlineItem*)rPool.GetItem( RES_CHRATR_UNDERLINE, n ) ) )
InsColor( pUnder->GetColor() );
}
const SvxOverlineItem* pOver = (const SvxOverlineItem*)GetDfltAttr( RES_CHRATR_OVERLINE );
InsColor( pOver->GetColor() );
nMaxItem = rPool.GetItemCount(RES_CHRATR_OVERLINE);
for( n = 0; n < nMaxItem;n++)
{
if( 0 != (pOver = (const SvxOverlineItem*)rPool.GetItem( RES_CHRATR_OVERLINE, n ) ) )
InsColor( pOver->GetColor() );
}
}
// background color
static const USHORT aBrushIds[] = {
RES_BACKGROUND, RES_CHRATR_BACKGROUND, 0 };
for( const USHORT* pIds = aBrushIds; *pIds; ++pIds )
{
const SvxBrushItem* pBkgrd = (const SvxBrushItem*)GetDfltAttr( *pIds );
InsColor( pBkgrd->GetColor() );
if( 0 != ( pBkgrd = (const SvxBrushItem*)rPool.GetPoolDefaultItem(
*pIds ) ))
{
InsColor( pBkgrd->GetColor() );
}
nMaxItem = rPool.GetItemCount( *pIds );
for( n = 0; n < nMaxItem; ++n )
if( 0 != (pBkgrd = (const SvxBrushItem*)rPool.GetItem(
*pIds , n ) ))
{
InsColor( pBkgrd->GetColor() );
}
}
// shadow color
{
const SvxShadowItem* pShadow = (const SvxShadowItem*)GetDfltAttr(
RES_SHADOW );
InsColor( pShadow->GetColor() );
if( 0 != ( pShadow = (const SvxShadowItem*)rPool.GetPoolDefaultItem(
RES_SHADOW ) ))
{
InsColor( pShadow->GetColor() );
}
nMaxItem = rPool.GetItemCount(RES_SHADOW);
for( n = 0; n < nMaxItem; ++n )
if( 0 != (pShadow = (const SvxShadowItem*)rPool.GetItem(
RES_SHADOW, n ) ) )
{
InsColor( pShadow->GetColor() );
}
}
// frame border color
{
const SvxBoxItem* pBox;
if( 0 != ( pBox = (const SvxBoxItem*)rPool.GetPoolDefaultItem(
RES_BOX ) ))
InsColorLine( *pBox );
nMaxItem = rPool.GetItemCount(RES_BOX);
for( n = 0; n < nMaxItem; ++n )
if( 0 != (pBox = (const SvxBoxItem*)rPool.GetItem( RES_BOX, n ) ))
InsColorLine( *pBox );
}
for( n = 0; n < m_aColTbl.size(); n++ )
{
const Color& rCol = m_aColTbl[ n ];
if( n || COL_AUTO != rCol.GetColor() )
{
Strm() << OOO_STRING_SVTOOLS_RTF_RED;
OutULong( rCol.GetRed() ) << OOO_STRING_SVTOOLS_RTF_GREEN;
OutULong( rCol.GetGreen() ) << OOO_STRING_SVTOOLS_RTF_BLUE;
OutULong( rCol.GetBlue() );
}
Strm() << ';';
}
}
void RtfExport::InsStyle( USHORT nId, const OString& rStyle )
{
m_aStyTbl.insert(std::pair<USHORT,OString>(nId, rStyle) );
}
OString* RtfExport::GetStyle( USHORT nId )
{
std::map<USHORT,OString>::iterator i = m_aStyTbl.find(nId);
if (i != m_aStyTbl.end())
return &i->second;
return NULL;
}
USHORT RtfExport::GetRedline( const String& rAuthor )
{
std::map<String,USHORT>::iterator i = m_aRedlineTbl.find(rAuthor);
if (i != m_aRedlineTbl.end())
return i->second;
else
{
int nId = m_aRedlineTbl.size();
m_aRedlineTbl.insert(std::pair<String,USHORT>(rAuthor,nId));
return nId;
}
}
void RtfExport::OutContent( const SwNode& rNode )
{
OutputContentNode(*rNode.GetCntntNode());
}
void RtfExport::OutPageDescription( const SwPageDesc& rPgDsc, BOOL bWriteReset, BOOL bCheckForFirstPage )
{
OSL_TRACE("%s start", OSL_THIS_FUNC);
const SwPageDesc *pSave = pAktPageDesc;
pAktPageDesc = &rPgDsc;
if( bCheckForFirstPage && pAktPageDesc->GetFollow() &&
pAktPageDesc->GetFollow() != pAktPageDesc )
pAktPageDesc = pAktPageDesc->GetFollow();
if( bWriteReset )
{
if( pCurPam->GetPoint()->nNode == pOrigPam->Start()->nNode )
Strm() << OOO_STRING_SVTOOLS_RTF_SECTD << OOO_STRING_SVTOOLS_RTF_SBKNONE;
else
Strm() << OOO_STRING_SVTOOLS_RTF_SECT << OOO_STRING_SVTOOLS_RTF_SECTD;
}
if( pAktPageDesc->GetLandscape() )
Strm() << OOO_STRING_SVTOOLS_RTF_LNDSCPSXN;
const SwFmt *pFmt = &pAktPageDesc->GetMaster(); //GetLeft();
bOutPageDescs = true;
OutputFormat(*pFmt, true, false);
bOutPageDescs = false;
// normal header / footer (without a style)
const SfxPoolItem* pItem;
if( pAktPageDesc->GetLeft().GetAttrSet().GetItemState( RES_HEADER, FALSE,
&pItem ) == SFX_ITEM_SET)
WriteHeaderFooter(*pItem, true);
if( pAktPageDesc->GetLeft().GetAttrSet().GetItemState( RES_FOOTER, FALSE,
&pItem ) == SFX_ITEM_SET)
WriteHeaderFooter(*pItem, false);
// title page
if( pAktPageDesc != &rPgDsc )
{
pAktPageDesc = &rPgDsc;
if( pAktPageDesc->GetMaster().GetAttrSet().GetItemState( RES_HEADER,
FALSE, &pItem ) == SFX_ITEM_SET )
WriteHeaderFooter(*pItem, true);
if( pAktPageDesc->GetMaster().GetAttrSet().GetItemState( RES_FOOTER,
FALSE, &pItem ) == SFX_ITEM_SET )
WriteHeaderFooter(*pItem, false);
}
// numbering type
AttrOutput().SectionPageNumbering(pAktPageDesc->GetNumType().GetNumberingType(), 0);
pAktPageDesc = pSave;
//bOutPageDesc = bOldOut;
OSL_TRACE("%s end", OSL_THIS_FUNC);
}
void RtfExport::WriteHeaderFooter(const SfxPoolItem& rItem, bool bHeader)
{
if (bHeader)
{
const SwFmtHeader& rHeader = (const SwFmtHeader&)rItem;
if (!rHeader.IsActive())
return;
}
else
{
const SwFmtFooter& rFooter = (const SwFmtFooter&)rItem;
if (!rFooter.IsActive())
return;
}
OSL_TRACE("%s start", OSL_THIS_FUNC);
Strm() << (bHeader ? OOO_STRING_SVTOOLS_RTF_HEADERY : OOO_STRING_SVTOOLS_RTF_FOOTERY);
OutLong( pAktPageDesc->GetMaster().
GetULSpace().GetUpper() );
const sal_Char* pStr = (bHeader ? OOO_STRING_SVTOOLS_RTF_HEADER : OOO_STRING_SVTOOLS_RTF_FOOTER);
/* is this a title page? */
if( pAktPageDesc->GetFollow() && pAktPageDesc->GetFollow() != pAktPageDesc )
{
Strm() << OOO_STRING_SVTOOLS_RTF_TITLEPG;
pStr = (bHeader ? OOO_STRING_SVTOOLS_RTF_HEADERF : OOO_STRING_SVTOOLS_RTF_FOOTERF);
}
Strm() << '{' << pStr;
WriteHeaderFooterText(pAktPageDesc->GetMaster(), bHeader);
Strm() << '}';
OSL_TRACE("%s end", OSL_THIS_FUNC);
}
void RtfExport::WriteHeaderFooter(const SwFrmFmt& rFmt, bool bHeader, const sal_Char* pStr)
{
OSL_TRACE("%s start", OSL_THIS_FUNC);
m_pAttrOutput->WriteHeaderFooter_Impl( rFmt, bHeader, pStr );
OSL_TRACE("%s end", OSL_THIS_FUNC);
}
class SwRTFWriter : public Writer
{
public:
SwRTFWriter( const String& rFilterName, const String& rBaseURL );
virtual ~SwRTFWriter();
virtual ULONG WriteStream();
};
SwRTFWriter::SwRTFWriter( const String& /*rFltName*/, const String & rBaseURL )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
SetBaseURL( rBaseURL );
}
SwRTFWriter::~SwRTFWriter()
{}
ULONG SwRTFWriter::WriteStream()
{
OSL_TRACE("%s", OSL_THIS_FUNC);
RtfExport aExport( NULL, pDoc, new SwPaM( *pCurPam->End(), *pCurPam->Start() ), pCurPam, this );
aExport.ExportDocument( true );
return 0;
}
extern "C" SAL_DLLPUBLIC_EXPORT void SAL_CALL ExportRTF( const String& rFltName, const String& rBaseURL, WriterRef& xRet )
{
OSL_TRACE("%s", OSL_THIS_FUNC);
xRet = new SwRTFWriter( rFltName, rBaseURL );
}
/* vi:set shiftwidth=4 expandtab: */
| [
"[email protected]"
] | |
0b772c268455a926de6bf375d556634414841b19 | 3e554a92237370d1f7d6c48a6c6df08e4d14fac6 | /gui/thumbnailremover.cpp | 0e851dea39e0175eca6a6634a4b716803f38178e | [] | no_license | J0s3f/fourchan-dl | f6f8a009b7755aeed76704db925632f24cd193ce | a2749272fd59f88ad36bb5b094b4477eed72ce9f | refs/heads/master | 2016-09-16T07:30:11.444555 | 2013-08-01T21:04:29 | 2013-08-01T21:04:29 | 7,335,155 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,402 | cpp | #include "thumbnailremover.h"
ThumbnailRemover::ThumbnailRemover(QObject *parent) :
QObject(parent)
{
settings = new QSettings("settings.ini", QSettings::IniFormat);
}
void ThumbnailRemover::removeOutdated() {
QDateTime date;
mutex.lock();
dirName = settings->value("options/thumbnail_cache_folder", QString("%1/%2").arg(QCoreApplication::applicationDirPath())
.arg("tncache")).toString();
ttl = settings->value("options/thumbnail_TTL", 60).toInt();
mutex.unlock();
dir.setPath(dirName);
fileInfoList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
foreach (QFileInfo fi, fileInfoList) {
date = fi.lastModified();
if (date.addDays(ttl) < QDateTime::currentDateTime()) {
QFile::remove(fi.absoluteFilePath());
QLOG_INFO() << "ThumbnailRemover :: removed " << fi.absoluteFilePath() << " because it was created on " << date.toString("dd.MM.yyyy hh:mm:ss");
}
}
}
void ThumbnailRemover::removeFiles(QStringList fileList) {
foreach (QString s, fileList) {
QFile::remove(s);
}
}
void ThumbnailRemover::removeAll() {
if (dir.exists())//QDir::NoDotAndDotDot
{
fileInfoList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
foreach (QFileInfo fi, fileInfoList) {
QFile::remove(fi.absoluteFilePath());
}
}
}
| [
"[email protected]"
] | |
5e23207ea132e2e0d14133b84558fd5d87202728 | 002f0c4ee7819951c4f977e3c1e76f1d2f1cb96d | /src/util.cpp | 90d8ece07a9430b861d79f0df8248a5d6eb56651 | [
"MIT"
] | permissive | groupco/rizercoin | 373bf66c119ef073f82fcbddee7f45d886cb3ec7 | ae11e9eac970eaea962c4143e3e2599e0200f1d3 | refs/heads/master | 2020-07-15T10:23:52.607067 | 2016-11-16T22:10:31 | 2016-11-16T22:10:31 | 73,965,277 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,430 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fDebugSmsg = false;
bool fNoSmsg = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64_t> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed OpenSSL PRNG with current contents of the screen
RAND_screen();
#endif
// Seed OpenSSL PRNG with performance counter
RandAddSeed();
}
~CInit()
{
// Securely erase the memory used by the PRNG
RAND_cleanup();
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
static FILE* fileout = NULL;
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
while (true)
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%"PRId64".%08"PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "putincoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\putincoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\putincoin
// Mac: ~/Library/Application Support/putincoin
// Unix: ~/.putincoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "putincoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "putincoin";
#else
// Unix
return pathRet / ".putincoin";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "putincoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "putincoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64_t nTimeOffset = 0;
int64_t GetTimeOffset()
{
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRId64" (%+"PRId64" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong PutinCoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("PutinCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
printf("%+"PRId64" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRId64" (%+"PRId64" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
uint32_t insecure_rand_Rz = 11;
uint32_t insecure_rand_Rw = 11;
void seed_insecure_rand(bool fDeterministic)
{
//The seed values have some unlikely fixed points which we avoid.
if(fDeterministic)
{
insecure_rand_Rz = insecure_rand_Rw = 11;
} else {
uint32_t tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x9068ffffU);
insecure_rand_Rz=tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x464fffffU);
insecure_rand_Rw=tmp;
}
}
static const long hextable[] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-19
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 30-39
-1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, -1, -1, // 50-59
-1, -1, -1, -1, -1, 10, 11, 12, 13, 14,
15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 70-79
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 10, 11, 12, // 90-99
13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 110-109
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 130-139
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 150-159
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 170-179
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 190-199
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 210-219
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 230-239
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1
};
long hex2long(const char* hexString)
{
long ret = 0;
while (*hexString && ret >= 0)
{
ret = (ret << 4) | hextable[*hexString++];
}
return ret;
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
| [
"[email protected]"
] | |
ed3e1cf9bf48ca4eb1905416122b3f25223de2a7 | 6bee89060c7d22807b74c4ba44f6af1bbc1bd06a | /extreme/programs/witness_node/main.cpp | a88d7dc4ccc561e3b29500f826c6ee51eefcc9a0 | [
"MIT"
] | permissive | moonstonedac/extreme | eca29466e15497248211acd7e226d5450dda4b20 | fdfbd311e799df496eca9a56de96f91018dfd4cc | refs/heads/master | 2021-01-12T04:09:58.286426 | 2017-01-27T14:34:53 | 2017-01-27T14:34:53 | 77,524,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,944 | cpp | /*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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 <extreme/app/application.hpp>
#include <extreme/witness/witness.hpp>
#include <extreme/account_history/account_history_plugin.hpp>
#include <extreme/market_history/market_history_plugin.hpp>
#include <fc/exception/exception.hpp>
#include <fc/thread/thread.hpp>
#include <fc/interprocess/signals.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <iostream>
#include <fstream>
#ifdef WIN32
# include <signal.h>
#else
# include <csignal>
#endif
using namespace extreme;
namespace bpo = boost::program_options;
void write_default_logging_config_to_stream(std::ostream& out);
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename);
int main(int argc, char** argv) {
app::application* node = new app::application();
fc::oexception unhandled_exception;
try {
bpo::options_description app_options("Extreme Witness Node");
bpo::options_description cfg_options("Extreme Witness Node");
app_options.add_options()
("help,h", "Print this help message and exit.")
("data-dir,d", bpo::value<boost::filesystem::path>()->default_value("witness_node_data_dir"), "Directory containing databases, configuration file, etc.")
;
bpo::variables_map options;
auto witness_plug = node->register_plugin<witness_plugin::witness_plugin>();
auto history_plug = node->register_plugin<account_history::account_history_plugin>();
auto market_history_plug = node->register_plugin<market_history::market_history_plugin>();
try
{
bpo::options_description cli, cfg;
node->set_program_options(cli, cfg);
app_options.add(cli);
cfg_options.add(cfg);
bpo::store(bpo::parse_command_line(argc, argv, app_options), options);
}
catch (const boost::program_options::error& e)
{
std::cerr << "Error parsing command line: " << e.what() << "\n";
return 1;
}
fc::path data_dir;
if( options.count("data-dir") )
{
data_dir = options["data-dir"].as<boost::filesystem::path>();
if( data_dir.is_relative() )
data_dir = fc::current_path() / data_dir;
}
fc::path config_ini_path = data_dir / "config.ini";
if( fc::exists(config_ini_path) )
{
// get the basic options
bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(), cfg_options, true), options);
// try to get logging options from the config file.
try
{
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
catch (const fc::exception&)
{
wlog("Error parsing logging config from config file ${config}, using default config", ("config", config_ini_path.preferred_string()));
}
}
else
{
ilog("Writing new config file at ${path}", ("path", config_ini_path));
if( !fc::exists(data_dir) )
fc::create_directories(data_dir);
std::ofstream out_cfg(config_ini_path.preferred_string());
for( const boost::shared_ptr<bpo::option_description> od : cfg_options.options() )
{
if( !od->description().empty() )
out_cfg << "# " << od->description() << "\n";
boost::any store;
if( !od->semantic()->apply_default(store) )
out_cfg << "# " << od->long_name() << " = \n";
else {
auto example = od->format_parameter();
if( example.empty() )
// This is a boolean switch
out_cfg << od->long_name() << " = " << "false\n";
else {
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length()-1);
out_cfg << od->long_name() << " = " << example << "\n";
}
}
out_cfg << "\n";
}
write_default_logging_config_to_stream(out_cfg);
out_cfg.close();
// read the default logging config we just wrote out to the file and start using it
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
bpo::notify(options);
node->initialize(data_dir, options);
node->initialize_plugins( options );
node->startup();
node->startup_plugins();
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
fc::set_signal_handler([&exit_promise](int signal) {
elog( "Caught SIGINT attempting to exit cleanly" );
exit_promise->set_value(signal);
}, SIGINT);
fc::set_signal_handler([&exit_promise](int signal) {
elog( "Caught SIGTERM attempting to exit cleanly" );
exit_promise->set_value(signal);
}, SIGTERM);
ilog("Started witness node on a chain with ${h} blocks.", ("h", node->chain_database()->head_block_num()));
ilog("Chain ID is ${id}", ("id", node->chain_database()->get_chain_id()) );
int signal = exit_promise->wait();
ilog("Exiting from signal ${n}", ("n", signal));
node->shutdown_plugins();
node->shutdown();
delete node;
return 0;
} catch( const fc::exception& e ) {
// deleting the node can yield, so do this outside the exception handler
unhandled_exception = e;
}
if (unhandled_exception)
{
elog("Exiting with error:\n${e}", ("e", unhandled_exception->to_detail_string()));
node->shutdown();
delete node;
return 1;
}
}
// logging config is too complicated to be parsed by boost::program_options,
// so we do it by hand
//
// Currently, you can only specify the filenames and logging levels, which
// are all most users would want to change. At a later time, options can
// be added to control rotation intervals, compression, and other seldom-
// used features
void write_default_logging_config_to_stream(std::ostream& out)
{
out << "# declare an appender named \"stderr\" that writes messages to the console\n"
"[log.console_appender.stderr]\n"
"stream=std_error\n\n"
"# declare an appender named \"p2p\" that writes messages to p2p.log\n"
"[log.file_appender.p2p]\n"
"filename=logs/p2p/p2p.log\n"
"# filename can be absolute or relative to this config file\n\n"
"# route any messages logged to the default logger to the \"stderr\" logger we\n"
"# declared above, if they are info level are higher\n"
"[logger.default]\n"
"level=info\n"
"appenders=stderr\n\n"
"# route messages sent to the \"p2p\" logger to the p2p appender declared above\n"
"[logger.p2p]\n"
"level=info\n"
"appenders=p2p\n\n";
}
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename)
{
try
{
fc::logging_config logging_config;
bool found_logging_config = false;
boost::property_tree::ptree config_ini_tree;
boost::property_tree::ini_parser::read_ini(config_ini_filename.preferred_string().c_str(), config_ini_tree);
for (const auto& section : config_ini_tree)
{
const std::string& section_name = section.first;
const boost::property_tree::ptree& section_tree = section.second;
const std::string console_appender_section_prefix = "log.console_appender.";
const std::string file_appender_section_prefix = "log.file_appender.";
const std::string logger_section_prefix = "logger.";
if (boost::starts_with(section_name, console_appender_section_prefix))
{
std::string console_appender_name = section_name.substr(console_appender_section_prefix.length());
std::string stream_name = section_tree.get<std::string>("stream");
// construct a default console appender config here
// stdout/stderr will be taken from ini file, everything else hard-coded here
fc::console_appender::config console_appender_config;
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::debug,
fc::console_appender::color::green));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::warn,
fc::console_appender::color::brown));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::error,
fc::console_appender::color::cyan));
console_appender_config.stream = fc::variant(stream_name).as<fc::console_appender::stream::type>();
logging_config.appenders.push_back(fc::appender_config(console_appender_name, "console", fc::variant(console_appender_config)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, file_appender_section_prefix))
{
std::string file_appender_name = section_name.substr(file_appender_section_prefix.length());
fc::path file_name = section_tree.get<std::string>("filename");
if (file_name.is_relative())
file_name = fc::absolute(config_ini_filename).parent_path() / file_name;
// construct a default file appender config here
// filename will be taken from ini file, everything else hard-coded here
fc::file_appender::config file_appender_config;
file_appender_config.filename = file_name;
file_appender_config.flush = true;
file_appender_config.rotate = true;
file_appender_config.rotation_interval = fc::hours(1);
file_appender_config.rotation_limit = fc::days(1);
logging_config.appenders.push_back(fc::appender_config(file_appender_name, "file", fc::variant(file_appender_config)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, logger_section_prefix))
{
std::string logger_name = section_name.substr(logger_section_prefix.length());
std::string level_string = section_tree.get<std::string>("level");
std::string appenders_string = section_tree.get<std::string>("appenders");
fc::logger_config logger_config(logger_name);
logger_config.level = fc::variant(level_string).as<fc::log_level>();
boost::split(logger_config.appenders, appenders_string,
boost::is_any_of(" ,"),
boost::token_compress_on);
logging_config.loggers.push_back(logger_config);
found_logging_config = true;
}
}
if (found_logging_config)
return logging_config;
else
return fc::optional<fc::logging_config>();
}
FC_RETHROW_EXCEPTIONS(warn, "")
}
| [
"[email protected]"
] | |
c89edc3ce4c69567fa513e21fa347ae0008a06f8 | 91f0b78fd35295ca1a367eddbd8569788bc66652 | /ccC.cpp | 6c09624770ecdea0d31365dbf7d5863a26e61b05 | [] | no_license | prajjwal1999/algo- | a97581812f9924acf133d2dad6def0f472fb9d11 | 881efb49127c81cdac0e375cf4fc201f8affbe06 | refs/heads/master | 2022-12-02T16:00:25.674334 | 2020-08-13T13:22:54 | 2020-08-13T13:22:54 | 287,287,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
const ll MOD=1e9+7;
#define endl '\n'
#define F first
#define S second
const double PI = 3.141592653589793238460;
void c_p_c()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main()
{
c_p_c();
int t;cin>>t;
while(t--)
{
ll a,b;cin>>a>>b;
ll power_of_a;ll power_of_b;
if(a<10)
power_of_a=1;
else
{
if(a%9!=0)
power_of_a=(a/9)+1;
else
power_of_a=a/9;
}
if(b<10)
power_of_b=1;
else
{
if(b%9!=0)
power_of_b=(b/9)+1;
else
power_of_b=b/9;
}
if(power_of_b==power_of_a)
cout<<"1 "<<power_of_b<<endl;
else if(power_of_b<power_of_a)
cout<<"1 "<<power_of_b<<endl;
else
cout<<"0 "<<power_of_a<<endl;
}
} | [
"[email protected]"
] | |
8fe235545643d3e296663000a1c55afbcb053f6c | 28c26279987a2060bbdd60876b868a7b46e3a983 | /dbms/zDBCryptoKey.h | 85b1c95e0cab6e7f880259ad0d02b1c25ecc8a3f | [
"MIT"
] | permissive | djp952/data-legacy | 005c30062cd92b3aa2bdc04f43ad35a937a42b7f | 956e888fe3be303d6c71a3834b97547b27450ffd | refs/heads/master | 2016-09-13T22:41:15.981112 | 2016-05-17T21:51:24 | 2016-05-17T21:51:24 | 58,897,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,938 | h | //---------------------------------------------------------------------------
// Copyright (c) 2016 Michael G. Brehm
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------
#ifndef __ZDBCRYPTOKEY_H_
#define __ZDBCRYPTOKEY_H_
#pragma once
#pragma warning(push, 4) // Enable maximum compiler warnings
using namespace System;
using namespace System::ComponentModel;
using namespace System::Runtime::InteropServices;
using namespace System::Security;
using namespace System::Security::Cryptography;
using namespace System::Text;
BEGIN_NAMESPACE(zuki)
BEGIN_NAMESPACE(data)
BEGIN_NAMESPACE(dbms)
//---------------------------------------------------------------------------
// Class zDBCryptoKey (internal)
//
// zDBCryptoKey is used to generate and store the cryptography key(s) used
// with the ENCRYPT() and DECRYPT() scalar functions built into the provider.
//
// Note that this is a carry-over from the 1.1 provider in order to maintain
// compatibility with both it and the Windows CE version of it. It has been
// modified slightly to use SecureString, but otherwise it's pretty much an
// identical implementation. for better or worse.
//---------------------------------------------------------------------------
ref class zDBCryptoKey
{
public:
//-----------------------------------------------------------------------
// Constructor / Destructor
zDBCryptoKey(SecureString^ password);
//-----------------------------------------------------------------------
// Properties
// Key
//
// Returns the HCRYPTKEY handle
property HCRYPTKEY Key
{
HCRYPTKEY get(void) { return reinterpret_cast<HCRYPTKEY>(m_ptKey.ToPointer()); }
}
private:
// DESTRUCTOR / FINALIZER
~zDBCryptoKey() { this->!zDBCryptoKey(); m_disposed = true; }
!zDBCryptoKey();
//-----------------------------------------------------------------------
// Private Member Functions
// CreatePrivateExponentOneKey
//
// Used for key generation -- see code
static BOOL CreatePrivateExponentOneKey(LPCTSTR szProvider, DWORD dwProvType,
LPCTSTR szContainer, DWORD dwKeySpec, HCRYPTPROV *hProv, HCRYPTKEY *hPrivateKey);
// ImportPlainSessionBlob
//
// Used for key generation -- see code
static BOOL ImportPlainSessionBlob(HCRYPTPROV hProv, HCRYPTKEY hPrivateKey,
ALG_ID dwAlgId, const BYTE* pbKeyMaterial, DWORD dwKeyMaterial, HCRYPTKEY *hSessionKey);
//-----------------------------------------------------------------------
// Member Variables
bool m_disposed; // Object disposal flag
IntPtr m_ptProv; // Really HCRYPTPROV
IntPtr m_ptPrivKey; // Really HCRYPTKEY
IntPtr m_ptKey; // Really HCRYPTKEY
};
//---------------------------------------------------------------------------
END_NAMESPACE(dbms)
END_NAMESPACE(data)
END_NAMESPACE(zuki)
#pragma warning(pop)
#endif // __ZDBCRYPTOKEY_H_
| [
"[email protected]"
] | |
4539a22772c6c4a29b38b4f452ea5692aed446c8 | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /WallPaper/include/WallPaperThumbSettingsDlg.h | 3f966d62fb75704ae7690c894d80f831c49c448b | [] | no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,478 | h | /*
WallPaperThumbSettingsDlg.h
Dialogo per le opzioni relative alla miniature.
Luca Piergentili, 21/10/00
[email protected]
WallPaper (alias crawlpaper) - the hardcore of Windows desktop
http://www.crawlpaper.com/
copyright © 1998-2004 Luca Piergentili, all rights reserved
crawlpaper is a registered name, all rights reserved
This is a free software, released under the terms of the BSD license. Do not
attempt to use it in any form which violates the license or you will be persecuted
and charged for this.
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 "crawlpaper" nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _WALLPAPERTHUMBSETTINGSDLG_H
#define _WALLPAPERTHUMBSETTINGSDLG_H 1
#include "window.h"
#include "CIconStatic.h"
#include "CWndLayered.h"
#include "WallPaperConfig.h"
#include "WallPaperThumbSettingsFormatDlg.h"
#include "WallPaperThumbSettingsHtmlOutputDlg.h"
#include "WallPaperThumbSettingsHtmlTableDlg.h"
#define IDS_DIALOG_THUMBNAILS_SETTINGS_TITLE " Thumbnails Settings "
/*
CWallPaperThumbSettingsDlg
*/
class CWallPaperThumbSettingsDlg : public CDialog
{
public:
CWallPaperThumbSettingsDlg(CWnd* pParent,CWallPaperConfig* pConfig);
~CWallPaperThumbSettingsDlg() {}
private:
void DoDataExchange (CDataExchange*);
BOOL OnInitDialog (void);
void OnOk (void);
void OnCancel (void);
void OnSelchangingTree (NMHDR* pNMHDR,LRESULT* pResult);
void OnSelchangedTree (NMHDR* pNMHDR,LRESULT* pResult);
CIconStatic m_ctrlSettingsArea;
CTreeCtrl m_wndSettingsTree;
HTREEITEM m_hItemRoot;
HTREEITEM m_hItemFormat;
HTREEITEM m_hItemHtmlOutput;
HTREEITEM m_hItemHtmlTable;
DWORD m_dwRootData;
CWallPaperThumbSettingsFormatDlg m_dlgTreeFormat;
CWallPaperThumbSettingsHtmlOutputDlg m_dlgTreeHtmlOutput;
CWallPaperThumbSettingsHtmlTableDlg m_dlgTreeHtmlTable;
CWallPaperConfig* m_pConfig;
BOOL m_bGenerateHtml;
BOOL m_bCreated;
CWndLayered m_wndLayered;
DECLARE_MESSAGE_MAP()
};
#endif // _WALLPAPERTHUMBSETTINGSDLG_H
| [
"[email protected]"
] | |
65566fef9d63218a1f4c0adf91713ba8704e24df | 64c1b6db2502bbc156d522d1b35567911cc151c5 | /uwb_uav_simulation_ws/ros_packages/tello_dobots/control_tello/include/takeoff_land.h | 3d1ecab5869b29265095d5f3de0e008da28fed5f | [] | no_license | MatthiesBrouwer/UAV-RPI_Beacon-AutoNav | fdd7c8cbb341e2cc3a2351a6e25c23c5f1b91357 | 10ecb2c5cb1389c818d6628ee5dead25dfe21de2 | refs/heads/main | 2023-03-07T17:17:54.995263 | 2021-02-11T12:27:57 | 2021-02-11T12:27:57 | 319,273,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,378 | h | /*
* Author: bart
* Date: 25/09/2019
*
This is the header file of the start_search node.
*/
// This is for the compiler to check if this header file is already included, if not it is included.
#ifndef TAKEOFF_LAND_H
#define TAKEOFF_LAND_H
// include all necessary files, functions, and messages
#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <control_tello_msgs/StartAction.h> // action message header file
#include <std_msgs/Empty.h>
// The class definition is inside the talker namespace. Namespaces are used. e collisions.
namespace takeoff_land{
// Class definition
class TakeOffLand{
public:
// constructor definition
TakeOffLand(std::string name);
// member functions
void setMode(const control_tello_msgs::StartGoalConstPtr &goal);
private:
// action server attributes
ros::NodeHandle nh_;
actionlib::SimpleActionServer<control_tello_msgs::StartAction> as_st_;
control_tello_msgs::StartResult result_;
control_tello_msgs::StartFeedback feedback_;
std::string action_name_;
// attributes, according to styling conventions, have a traling underscore.
ros::Publisher pub_land_; // publisher of new setpoint
ros::Publisher pub_takeoff_; // publisher of new setpoint
std_msgs::Empty empty_msg_; // to be published new setpoint
}; // end class
} // end namespace
#endif
| [
"[email protected]"
] | |
1e63e8c74b29d1d60fa25a79273103ef58282f7f | d58abcd924dd4f3f517733edb7fe47964ab2367d | /Training Round 2/HOU - Young Buffalo/B_1.cpp | 8752a2001b36a77c5a8d74f4684981f846d9b8ae | [] | no_license | DinhHuyKhanh/Trainning | 15e7b7a4d918cc29b2a603192e3b460c48f8dac7 | 3efeab4e4c8968d02a70a390676020d28afdfa5c | refs/heads/main | 2023-08-21T08:59:06.405715 | 2021-10-23T09:22:55 | 2021-10-23T09:22:55 | 412,743,850 | 0 | 0 | null | 2021-10-02T09:00:00 | 2021-10-02T08:59:59 | null | UTF-8 | C++ | false | false | 2,436 | cpp | #include <bits/stdc++.h>
#define ff first
#define ss second
#define sz(x) x.size()
#define pb(x) push_back(x)
#define all(a) a.begin(),a.end()
#define setp(x) fixed << setprecision(x)
using namespace std;
typedef complex<long double> cd;
namespace input {
template<class T> void re(complex<T>& x);
template<class T1, class T2> void re(pair<T1,T2>& p);
template<class T> void re(vector<T>& a);
template<class T, size_t SZ> void re(array<T,SZ>& a);
template<class T> void re(T& x) { cin >> x; }
void re(double& x) { string t; re(t); x = stod(t); }
void re(long double& x) { string t; re(t); x = stold(t); }
template<class Arg, class... Args> void re(Arg& first, Args&... rest) {
re(first); re(rest...);
}
template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = cd(a,b); }
template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.ff,p.ss); }
template<class T> void re(vector<T>& a) {
for(auto &i:a)re(i);
}
template<class T, size_t SZ> void re(array<T,SZ>& a) {
for(int i=0;i<SZ;++i) re(a[i]);
}
}
using namespace input;
using ll = long long;
using u64 = unsigned long long;
using u32 = unsigned;
namespace io
{
void setIn(string s) { ifstream cin (s);}
void setOut(string s) {ofstream cout (s);}
void setIO(string s = "")
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin.exceptions(cin.failbit);
if (sz(s)) setIn(s+".inp"), setOut(s+".out");
}
}
using namespace io;
const int MOD = 10000;
const string tg = "welcome to code jam";
const int tgl= 19;
int dp(int i, int j, const string& ss, vector<vector<int>>& mem) {
if (ss.length() - i < tgl- j)
return 0;
if (mem[i][j] == -1) {
const string substr = ss.substr(i);
if (j == 18)
mem[i][j] = count(substr.begin(),substr.end(),tg.back());
else
mem[i][j] = ((ss[i] == tg[j] ? dp(i + 1, j + 1, ss, mem) : 0) + dp(i + 1, j, ss, mem)) % MOD;
}
return mem[i][j];
}
string dmm(const string& ss) {
vector<vector<int>> mem(ss.length(), vector<int>(19, -1));
string cnt = to_string(dp(0, 0, ss, mem));
return string(4 - cnt.length(), '0') + cnt;
}
int main() {
int t;
string ss;
cin >> t;
cin.ignore();
for (int i = 1; i <= t; ++i) {
getline(cin, ss);
cout << "Case #" << i << ": " <<dmm(ss) << '\n';
}
return 0;
} | [
"[email protected]"
] | |
4c4bc842f8014864127740e80f9ce433adbfd35b | da6d80c41f56064d007cf4ede58528973f796c66 | /RM_Arch/POSIX/Buffer.h | 017198e76c9f2a254f6061355bac778e9ee96495 | [] | no_license | SafeCOP/WP4 | 4f4d373f9a8dbfad6c349fabac8b1b5dc6aac9b4 | 5834e47df0cf555851c43ee430ad1b2b40827d95 | refs/heads/master | 2021-07-16T11:34:12.454256 | 2019-01-30T10:24:37 | 2019-01-30T10:24:37 | 142,432,612 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 8,433 | h | #ifndef _MONITOR_BUFFER_H_
#define _MONITOR_BUFFER_H_
#include <time.h>
#include <boost/atomic.hpp>
using namespace boost;
#include "types.h"
#include "Event.h"
#include "SeqLock.h"
#include "ArraySeqLock.h"
#include "pthread.h"
/**
* Data container for EventBuffer operators such as EventReader and EventWriter.
*
* Buffer is a Data Container for sharing buffer state, it contains data both readers and writers need. Buffer also
* defines some operations that can be done on the buffer, such as atomic reading and writing.
*
* This class exists as to avoid cyclic dependency where readers and writers would have to know the EventBuffer and
* the EventBuffer having to know reader and writers.
* Buffer also allows reader/writers to know only one object, instead of having several pointers to the data they need.
*
* @author Humberto Carvalho ([email protected])
* @date
*/
template<typename T>
class Buffer {
private:
/**
* The sequence used to protect read/writes.
*/
ArraySeqLock array_lock;
/** Last overwritten element timestamp.
* @see time.h
*/
SeqLock<struct timespec> lastOverwrittenTimestamp;
/** Last written index.
*/
atomic<length_t> index;
/** Constant pointer to the start of the array */
Event<T> *const array;
public:
/** Array Length */
const length_t length;
/**
* Instantiates a new buffer.
*
* The buffer begins at array and has a length of length. The lastOverwrittenTimestamp is zeroed out.
*
* @param array a reference to a constant pointer that points to the array.
* @param length the length of the array.
*/
Buffer(Event<T> *const &array, const length_t length);
/**
* Pushes an event to this circular buffer.
*
* Pushes events to the buffer in O(1) time using the monotonic clock as a timestamp reference.
*
* This method uses a custom sequential lock, for more information please check the ArraySeqLock and the SeqLock documentation.
*
* Since the index is always updated after writing an element, unless an overflow occurs the readers should never try
* to read this element, as readers always call getHead to obtain the current index.
*
* @param event the event to be pushed
*/
void push(const Event<T> &event);
/**
* Pushes data into this circular buffer.
*
* Pushes events to the buffer in O(1) time using the monotonic clock as a timestamp reference.
*
* This method uses a custom sequential lock, for more information please check the ArraySeqLock and the SeqLock documentation.
*
* Since the index is always updated after writing an element, unless an overflow occurs the readers should never try
* to read this element, as readers always call getHead to obtain the current index.
*
* @param data the data to be pushed.
*/
void push(const T &data);
/**
* Atomically reads an index from the buffer.
*
* @warning the index must be valid otherwise an overflow will occur
*
* @param event A reference to an event object where the data will be stored.
* @param index the index to read from.
*/
void readIndex(Event<T> &event, const length_t index) const;
/**
* Atomically reads the lastOverwritten timestamp.
*
* @param last_overwritten a reference to a struct timespec where the last_overwritten will be read to.
*/
void readLastOverwritten(struct timespec &last_overwritten) const;
/**
* Atomically reads a timestamp from an index.
*
* If we fail to read the index after 5 tries, pthread_yield is called to yield to the writer thread.
*
* @warning the index must be valid otherwise an overflow will occur
*
* @param time A reference to a struct timespec where the data will be stored.
* @param index the index to read from.
*/
void readTime(struct timespec &time, const length_t index) const;
/**
* Atomically reads the last written index.
*
* If we fail to read the index after 5 tries, pthread_yield is called to yield to the writer thread.
*
* @warning the index must be valid otherwise an overflow will occur
*
* @param time A reference to a struct timespec where the data will be stored.
* @param index the index to read from.
*
* @return the last written index
*/
length_t readLastWritten(struct timespec &time) const;
/**
* Gets the buffers head, the index where the writer last wrote.
*
* @return the index that was written.
*/
length_t getHead() const;
/**
* Gets the array length.
*
* @return the array length.
*/
length_t getLength() const;
/**
* Checks if the array is empty.
*
* Since the index to be written is index[1], this method checks if the
* Event on that index is null.
*
* @return if the array is empty.
*/
bool empty() const;
};
template<typename T>
Buffer<T>::Buffer(Event<T> *const &array, const length_t length) : array_lock(length), lastOverwrittenTimestamp(),
index(0), array(array), length(length) { }
template<typename T>
void Buffer<T>::readTime(struct timespec &time, const length_t index) const {
struct array_seq_lock tmp_lock;
do {
tmp_lock = array_lock.read_seqbegin(index);
time = array[index].getTime();
}while(array_lock.read_seqretry(tmp_lock, index));
}
template<typename T>
void Buffer<T>::push(const Event<T> &event) {
/* We must increment the writer_index on a temporary variable,
* otherwise if a reader calls getHead() he might get an index
* which is > than the array.
*/
const length_t tempIndex = array_lock.write_get_index();
Event<T> *tempEvent = &array[tempIndex];
lastOverwrittenTimestamp.store(tempEvent->getTime());
array_lock.write_seqbegin();
*tempEvent = event;
array_lock.write_seqend();
//Since the index is updated last, readers should never come across this element unless they overflow. Because
//the readers always call getHead() and check if that time > than lastRead or > than afterTime.
index.store(tempIndex, memory_order_relaxed);
};
template<typename T>
void Buffer<T>::push(const T &data) {
/* We must increment the writer_index on a temporary variable,
* otherwise if a reader calls getHead() he might get an index
* which is > than the array.
*/
struct timespec tmp_time;
clock_gettime(CLOCK_MONOTONIC, &tmp_time);
const length_t tempIndex = array_lock.write_get_index();
Event<T> *tempEvent = &array[tempIndex];
lastOverwrittenTimestamp.store(tempEvent->getTime());
array_lock.write_seqbegin();
tempEvent->getTime() = tmp_time;
tempEvent->getData() = data;
array_lock.write_seqend();
//Since the index is updated last, readers should never come across this element unless they overflow. Because
//the readers always call getHead() and check if that time > than lastRead or > than afterTime.
index.store(tempIndex, memory_order_relaxed);
}
template<typename T>
void Buffer<T>::readIndex(Event<T> &event, const length_t index) const {
struct array_seq_lock tmp_lock;
do {
tmp_lock = array_lock.read_seqbegin(index);
event = array[index];
} while (array_lock.read_seqretry(tmp_lock, index));
}
template<typename T>
void Buffer<T>::readLastOverwritten(struct timespec &last_overwritten) const {
lastOverwrittenTimestamp.load(last_overwritten);
}
template<typename T>
length_t Buffer<T>::readLastWritten(struct timespec &time) const {
struct array_seq_lock tmp_lock;
length_t tmp_index;
do {
tmp_index = this->index.load(memory_order_acquire);
tmp_lock = array_lock.read_seqbegin(tmp_index);
time = array[tmp_index].getTime();
} while(array_lock.read_seqretry(tmp_lock, tmp_index));
return tmp_index;
}
template<typename T>
length_t Buffer<T>::getHead() const {
return index.load(memory_order_relaxed);
}
template<typename T>
length_t Buffer<T>::getLength() const {
return length;
}
template<typename T>
bool Buffer<T>::empty() const {
struct timespec time;
readTime(time, 1);
return time.tv_nsec == 0 && time.tv_sec == 0;
}
#endif //_MONITOR_BUFFER_H_
| [
"[email protected]"
] | |
635a164dd805983d0fa3c0eaec8522341a4ffd33 | 24ab4757b476a29439ae9f48de3e85dc5195ea4a | /lib/magma-2.2.0/src/zgetrs_nopiv_batched.cpp | 45256fd611d1ab0e9d2f54b92582cde942f90772 | [] | no_license | caomw/cuc_double | 6025d2005a7bfde3372ebf61cbd14e93076e274e | 99db19f7cb56c0e3345a681b2c103ab8c88e491f | refs/heads/master | 2021-01-17T05:05:07.006372 | 2017-02-10T10:29:51 | 2017-02-10T10:29:51 | 83,064,594 | 10 | 2 | null | 2017-02-24T17:09:11 | 2017-02-24T17:09:11 | null | UTF-8 | C++ | false | false | 10,551 | cpp | /*
-- MAGMA (version 2.2.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date November 2016
@author Azzam Haidar
@precisions normal z -> s d c
*/
#include "magma_internal.h"
#include "batched_kernel_param.h"
/***************************************************************************//**
Purpose
-------
ZGETRS solves a system of linear equations
A * X = B, A**T * X = B, or A**H * X = B
with a general N-by-N matrix A using the LU factorization without pivoting computed by ZGETRF_NOPIV.
This is a batched version that solves batchCount N-by-N matrices in parallel.
dA, dB, become arrays with one entry per matrix.
Arguments
---------
@param[in]
trans magma_trans_t
Specifies the form of the system of equations:
- = MagmaNoTrans: A * X = B (No transpose)
- = MagmaTrans: A**T * X = B (Transpose)
- = MagmaConjTrans: A**H * X = B (Conjugate transpose)
---------
@param[in]
n INTEGER
The order of the matrix A. N >= 0.
@param[in]
nrhs INTEGER
The number of right hand sides, i.e., the number of columns
of the matrix B. NRHS >= 0.
@param[in,out]
dA_array Array of pointers, dimension (batchCount).
Each is a COMPLEX_16 array on the GPU, dimension (LDDA,N).
On entry, each pointer is an M-by-N matrix to be factored.
On exit, the factors L and U from the factorization
A = P*L*U; the unit diagonal elements of L are not stored.
@param[in]
ldda INTEGER
The leading dimension of each array A. LDDA >= max(1,M).
@param[in,out]
dB_array Array of pointers, dimension (batchCount).
Each is a COMPLEX_16 array on the GPU, dimension (LDDB,N).
On entry, each pointer is an right hand side matrix B.
On exit, each pointer is the solution matrix X.
@param[in]
lddb INTEGER
The leading dimension of the array B. LDB >= max(1,N).
@param[out]
info_array Array of INTEGERs, dimension (batchCount), for corresponding matrices.
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
or another error occured, such as memory allocation failed.
- > 0: if INFO = i, U(i,i) is exactly zero. The factorization
has been completed, but the factor U is exactly
singular, and division by zero will occur if it is used
to solve a system of equations.
@param[in]
batchCount INTEGER
The number of matrices to operate on.
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magma_getrs_nopiv_batched
*******************************************************************************/
extern "C" magma_int_t
magma_zgetrs_nopiv_batched(
magma_trans_t trans, magma_int_t n, magma_int_t nrhs,
magmaDoubleComplex **dA_array, magma_int_t ldda,
magmaDoubleComplex **dB_array, magma_int_t lddb,
magma_int_t *info_array,
magma_int_t batchCount, magma_queue_t queue)
{
/* Local variables */
magma_int_t notran = (trans == MagmaNoTrans);
magma_int_t info = 0;
if ( (! notran) &&
(trans != MagmaTrans) &&
(trans != MagmaConjTrans) ) {
info = -1;
} else if (n < 0) {
info = -2;
} else if (nrhs < 0) {
info = -3;
} else if (ldda < max(1,n)) {
info = -5;
} else if (lddb < max(1,n)) {
info = -8;
}
if (info != 0) {
magma_xerbla( __func__, -(info) );
return info;
}
/* Quick return if possible */
if (n == 0 || nrhs == 0) {
return info;
}
magmaDoubleComplex **dA_displ = NULL;
magmaDoubleComplex **dB_displ = NULL;
magmaDoubleComplex **dW1_displ = NULL;
magmaDoubleComplex **dW2_displ = NULL;
magmaDoubleComplex **dW3_displ = NULL;
magmaDoubleComplex **dW4_displ = NULL;
magmaDoubleComplex **dinvA_array = NULL;
magmaDoubleComplex **dwork_array = NULL;
magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ));
magma_malloc((void**)&dB_displ, batchCount * sizeof(*dB_displ));
magma_malloc((void**)&dW1_displ, batchCount * sizeof(*dW1_displ));
magma_malloc((void**)&dW2_displ, batchCount * sizeof(*dW2_displ));
magma_malloc((void**)&dW3_displ, batchCount * sizeof(*dW3_displ));
magma_malloc((void**)&dW4_displ, batchCount * sizeof(*dW4_displ));
magma_malloc((void**)&dinvA_array, batchCount * sizeof(*dinvA_array));
magma_malloc((void**)&dwork_array, batchCount * sizeof(*dwork_array));
magma_int_t invA_msize = magma_roundup( n, ZTRTRI_BATCHED_NB )*ZTRTRI_BATCHED_NB;
magma_int_t dwork_msize = n*nrhs;
magmaDoubleComplex* dinvA = NULL;
magmaDoubleComplex* dwork = NULL; // dinvA and dwork are workspace in ztrsm
magma_zmalloc( &dinvA, invA_msize * batchCount);
magma_zmalloc( &dwork, dwork_msize * batchCount );
/* check allocation */
if ( dW1_displ == NULL || dW2_displ == NULL || dW3_displ == NULL || dW4_displ == NULL ||
dinvA_array == NULL || dwork_array == NULL || dinvA == NULL || dwork == NULL ||
dA_displ == NULL || dB_displ == NULL ) {
magma_free(dA_displ);
magma_free(dB_displ);
magma_free(dW1_displ);
magma_free(dW2_displ);
magma_free(dW3_displ);
magma_free(dW4_displ);
magma_free(dinvA_array);
magma_free(dwork_array);
magma_free( dinvA );
magma_free( dwork );
info = MAGMA_ERR_DEVICE_ALLOC;
magma_xerbla( __func__, -(info) );
return info;
}
magmablas_zlaset( MagmaFull, invA_msize, batchCount, MAGMA_Z_ZERO, MAGMA_Z_ZERO, dinvA, invA_msize, queue );
magmablas_zlaset( MagmaFull, dwork_msize, batchCount, MAGMA_Z_ZERO, MAGMA_Z_ZERO, dwork, dwork_msize, queue );
magma_zset_pointer( dwork_array, dwork, n, 0, 0, dwork_msize, batchCount, queue );
magma_zset_pointer( dinvA_array, dinvA, ZTRTRI_BATCHED_NB, 0, 0, invA_msize, batchCount, queue );
magma_zdisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount, queue);
magma_zdisplace_pointers(dB_displ, dB_array, lddb, 0, 0, batchCount, queue);
if (notran) {
if (nrhs > 1)
{
// solve dwork = L^-1 * NRHS
magmablas_ztrsm_outofplace_batched( MagmaLeft, MagmaLower, MagmaNoTrans, MagmaUnit, 1,
n, nrhs,
MAGMA_Z_ONE,
dA_displ, ldda, // dA
dB_displ, lddb, // dB
dwork_array, n, // dX //output
dinvA_array, invA_msize,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
1, batchCount, queue );
// solve X = U^-1 * dwork
magmablas_ztrsm_outofplace_batched( MagmaLeft, MagmaUpper, MagmaNoTrans, MagmaNonUnit, 1,
n, nrhs,
MAGMA_Z_ONE,
dA_displ, ldda, // dA
dwork_array, n, // dB
dB_displ, lddb, // dX //output
dinvA_array, invA_msize,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
1, batchCount, queue );
}
else
{
// solve dwork = L^-1 * NRHS
magmablas_ztrsv_outofplace_batched( MagmaLower, MagmaNoTrans, MagmaUnit,
n,
dA_displ, ldda, // dA
dB_displ, 1, // dB
dwork_array, // dX //output
batchCount, queue, 0 );
// solve X = U^-1 * dwork
magmablas_ztrsv_outofplace_batched( MagmaUpper, MagmaNoTrans, MagmaNonUnit,
n,
dA_displ, ldda, // dA
dwork_array, 1, // dB
dB_displ, // dX //output
batchCount, queue, 0 );
}
}
else {
if (nrhs > 1)
{
/* Solve A**T * X = B or A**H * X = B. */
// solve
magmablas_ztrsm_outofplace_batched( MagmaLeft, MagmaUpper, trans, MagmaUnit, 1,
n, nrhs,
MAGMA_Z_ONE,
dA_displ, ldda, // dA
dB_displ, lddb, // dB
dwork_array, n, // dX //output
dinvA_array, invA_msize,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
1, batchCount, queue );
// solve
magmablas_ztrsm_outofplace_batched( MagmaLeft, MagmaLower, trans, MagmaNonUnit, 1,
n, nrhs,
MAGMA_Z_ONE,
dA_displ, ldda, // dA
dwork_array, n, // dB
dB_displ, lddb, // dX //output
dinvA_array, invA_msize,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
1, batchCount, queue );
}
else
{
/* Solve A**T * X = B or A**H * X = B. */
// solve
magmablas_ztrsv_outofplace_batched( MagmaUpper, trans, MagmaUnit,
n,
dA_displ, ldda, // dA
dB_displ, 1, // dB
dwork_array, // dX //output
batchCount, queue, 0 );
// solve
magmablas_ztrsv_outofplace_batched( MagmaLower, trans, MagmaNonUnit,
n,
dA_displ, ldda, // dA
dwork_array, 1, // dB
dB_displ, // dX //output
batchCount, queue, 0 );
}
}
magma_queue_sync(queue);
magma_free(dA_displ);
magma_free(dB_displ);
magma_free(dW1_displ);
magma_free(dW2_displ);
magma_free(dW3_displ);
magma_free(dW4_displ);
magma_free(dinvA_array);
magma_free(dwork_array);
magma_free( dinvA );
magma_free( dwork );
return info;
}
| [
"[email protected]"
] | |
4ea01d9a326edb0eb4810390990018fcee2163d4 | fa0c642ba67143982d3381f66c029690b6d2bd17 | /Source/Engine/Platform/android/Network/androidBluetooth.cpp | cc5fd40c77be5f5ee35debd18f437356fcabc26d | [
"MIT"
] | permissive | blockspacer/EasyGameEngine | 3f605fb2d5747ab250ef8929b0b60e5a41cf6966 | da0b0667138573948cbd2e90e56ece5c42cb0392 | refs/heads/master | 2023-05-05T20:01:31.532452 | 2021-06-01T13:35:54 | 2021-06-01T13:35:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,333 | cpp | //! @file androidBluetoothAdapter.cpp
//! @author LiCode
//! @version 1.1.0.522
//! @date 2011/01/05
//! Copyright 2009-2010 LiCode's Union.
#include "EGEEngine.h"
//----------------------------------------------------------------------------
// JNI Functions Implementation
//----------------------------------------------------------------------------
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnACLConnected, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnACLConnected( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnACLDisconnected, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnACLDisconnected( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnACLDisconnectRequested, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnACLDisconnectRequested( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnBondStateChanged, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnBondStateChanged( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnClassChanged, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnClassChanged( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnNameChanged, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnNameChanged( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnFoundDevice, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnFoundDevice( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnPairingRequest, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnPairingRequest( &device );
}
JNI_FUNC_1( void, AndroidBluetoothAdapter, OnUUID, jobject js_device )
{
androidBluetoothDevice device;
device.Initialize( js_device );
GetBluetoothAdapter( )->GetNotifier( )->OnUUID( &device );
}
//----------------------------------------------------------------------------
// androidBluetoothSocket Implementation
//----------------------------------------------------------------------------
androidBluetoothSocket::androidBluetoothSocket( )
{
}
androidBluetoothSocket::~androidBluetoothSocket( )
{
}
_ubool androidBluetoothSocket::Initialize( jobject socket )
{
if ( mBluetoothSocket.Initialize( _true, "com/ege/android/AndroidBluetoothSocket", socket ) == _false )
return _false;
return _true;
}
_void androidBluetoothSocket::Connect( )
{
// Get the remote device address
AString remote_device_address = GetRemoteDeviceAddress( );
// Connect to remote device
ALOG_TRACE_1( "Connecting to '%s' bluetooth remote server ...", remote_device_address.Str( ) );
mBluetoothSocket.CallVoidMethod( "connect", "()V" );
ALOG_TRACE_1( "Connected to '%s' bluetooth remote server OK", remote_device_address.Str( ) );
}
AStringR androidBluetoothSocket::GetRemoteDeviceAddress( )
{
jstring js_address = (jstring) mBluetoothSocket.CallObjectMethod( "getRemoteDeviceAddress", "()Ljava/lang/String;" );
if ( js_address == _null )
{
ALOG_ERROR( "Get BT remote device address failed" );
return AString( "" );
}
return J2CString( js_address ).ToStringA( );
}
_dword androidBluetoothSocket::GetAvailableBytes( )
{
return mBluetoothSocket.CallIntMethod( "getAvailableBytes", "()I" );
}
_dword androidBluetoothSocket::Send( const _byte* buffer, _dword size )
{
C2JArray js_buffer( size, buffer );
_dword send_size = mBluetoothSocket.CallIntMethod( "send", "([B)I", js_buffer.ToJArray( ) );
return send_size;
}
_dword androidBluetoothSocket::Recv( _byte* buffer, _dword size )
{
C2JArray js_buffer( size );
_dword recv_size = mBluetoothSocket.CallIntMethod( "recv", "([B)I", js_buffer.ToJArray( ) );
if ( recv_size != size )
{
ALOG_TRACE_2( "androidBluetoothSocket::recv( ) recv_size : %d, size : %d", recv_size, size );
return -1;
}
js_buffer.ReadBuffer( 0, recv_size, buffer );
return recv_size;
}
//----------------------------------------------------------------------------
// androidBluetoothServerSocket Implementation
//----------------------------------------------------------------------------
androidBluetoothServerSocket::androidBluetoothServerSocket( )
{
}
androidBluetoothServerSocket::~androidBluetoothServerSocket( )
{
}
_ubool androidBluetoothServerSocket::Initialize( jobject socket )
{
if ( mBluetoothServerSocket.Initialize( _true, "com/ege/android/AndroidBluetoothServerSocket", socket ) == _false )
return _false;
return _true;
}
IBluetoothSocketPassRef androidBluetoothServerSocket::Accept( _dword timeout )
{
jobject js_socket = (jobject) mBluetoothServerSocket.CallObjectMethod( "accept", "(I)Lcom/ege/android/AndroidBluetoothSocket;", jint( timeout ) );
if ( js_socket == _null )
return _null;
androidBluetoothSocket* socket = new androidBluetoothSocket( );
if ( socket->Initialize( js_socket ) == _false )
{ EGE_RELEASE( socket ); return _null; }
return socket;
}
//----------------------------------------------------------------------------
// androidBluetoothDevice Implementation
//----------------------------------------------------------------------------
androidBluetoothDevice::androidBluetoothDevice( )
{
}
androidBluetoothDevice::~androidBluetoothDevice( )
{
}
_ubool androidBluetoothDevice::GetDeviceName( )
{
jstring js_name = (jstring) mBluetoothDevice.CallObjectMethod( "getName", "()Ljava/lang/String;" );
if ( js_name == _null )
{
ALOG_ERROR( "Get BT device name failed" );
return _false;
}
mName = J2CString( js_name ).ToStringA( );
ALOG_TRACE_1( "Device name: %s", mName.Str( ) );
return _true;
}
_ubool androidBluetoothDevice::GetDeviceAddress( )
{
jstring js_address = (jstring) mBluetoothDevice.CallObjectMethod( "getAddress", "()Ljava/lang/String;" );
if ( js_address == _null )
{
ALOG_ERROR( "Get BT device address failed" );
return _false;
}
mAddress = J2CString( js_address ).ToStringA( );
ALOG_TRACE_1( "Device address: %s", mAddress.Str( ) );
return _true;
}
_ubool androidBluetoothDevice::Initialize( jobject device )
{
if ( mBluetoothDevice.Initialize( _true, "com/ege/android/AndroidBluetoothDevice", device ) == _false )
return _false;
// Get name
if ( GetDeviceName( ) == _false )
return _false;
// Get address
if ( GetDeviceAddress( ) == _false )
return _false;
return _true;
}
IBluetoothDevice::_STATE androidBluetoothDevice::GetState( ) const
{
_dword state = mBluetoothDevice.CallIntMethod( "getBondState", "()I" );
switch ( state )
{
case 0x0000000A: return _STATE_BOND_NONE;
case 0x0000000B: return _STATE_BOND_BONDING;
case 0x0000000C: return _STATE_BOND_BONDED;
default:
break;
}
return _STATE_BOND_NONE;
}
IBluetoothDevice::_TYPE androidBluetoothDevice::GetType( ) const
{
_dword type = mBluetoothDevice.CallIntMethod( "getType", "()I" );
switch ( type )
{
case 0x00000000: return _TYPE_UNKNOWN;
case 0x00000001: return _TYPE_CLASSIC;
case 0x00000002: return _TYPE_LE;
case 0x00000003: return _TYPE_DUAL;
default:
break;
}
return _TYPE_UNKNOWN;
}
IBluetoothSocketPassRef androidBluetoothDevice::CreateClientSocket( const UID128& uuid )
{
C2JString js_uuid( uuid.ToStringU( ) );
jobject js_socket = (jobject) mBluetoothDevice.CallObjectMethod( "createClientSocket", "(Ljava/lang/String;)Lcom/ege/android/AndroidBluetoothSocket;", js_uuid.ToJString( ) );
if ( js_socket == _null )
return _null;
androidBluetoothSocket* socket = new androidBluetoothSocket( );
if ( socket->Initialize( js_socket ) == _false )
{ EGE_RELEASE( socket ); return _null; }
return socket;
}
//----------------------------------------------------------------------------
// androidBluetoothAdapter Implementation
//----------------------------------------------------------------------------
androidBluetoothAdapter::androidBluetoothAdapter( )
{
mBluetoothAdapter.Initialize( "com/ege/android/AndroidBluetoothAdapter", _false );
mBluetoothAdapter.CallStaticVoidMethod( "init", "()V" );
}
androidBluetoothAdapter::~androidBluetoothAdapter( )
{
mBluetoothAdapter.CallStaticVoidMethod( "uninit", "()V" );
}
IBluetoothAdapter::_STATE androidBluetoothAdapter::GetState( ) const
{
_dword state = mBluetoothAdapter.CallStaticIntMethod( "getState", "()I" );
switch ( state )
{
case 0x0000000A: return _STATE_OFF;
case 0x0000000B: return _STATE_TURNING_ON;
case 0x0000000C: return _STATE_ON;
case 0x0000000D: return _STATE_TURNING_OFF;
default:
break;
}
return _STATE_OFF;
}
_ubool androidBluetoothAdapter::Enable( _ubool enable )
{
if ( mBluetoothAdapter.CallStaticBooleanMethod( "enable", "(Z)Z", jboolean( enable ) ) == _false )
return _false;
// Get address
jstring js_address = (jstring) mBluetoothAdapter.CallStaticObjectMethod( "getAddress", "()Ljava/lang/String;" );
if ( js_address == _null )
return _false;
mAddress = J2CString( js_address ).ToStringA( );
// Get name
jstring js_name = (jstring) mBluetoothAdapter.CallStaticObjectMethod( "getName", "()Ljava/lang/String;" );
if ( js_name == _null )
return _false;
mName = J2CString( js_name ).ToStringA( );
return _true;
}
_ubool androidBluetoothAdapter::IsEnabled( ) const
{
return mBluetoothAdapter.CallStaticBooleanMethod( "isEnabled", "()Z" );
}
IBluetoothDevicePassRef androidBluetoothAdapter::GetRemoteDevice( AStringPtr address )
{
C2JString js_address( address );
jobject js_device = (jobject) mBluetoothAdapter.CallStaticObjectMethod( "getRemoteDevice", "(Ljava/lang/String;)Lcom/ege/android/AndroidBluetoothDevice;", js_address.ToJString( ) );
if ( js_device == _null )
{
ALOG_ERROR_1( "The '%s' remote BT device is not existing when get remote device", address.Str( ) );
return _null;
}
androidBluetoothDevice* device = new androidBluetoothDevice( );
if ( device->Initialize( js_device ) == _false )
{ EGE_RELEASE( device ); return _null; }
return device;
}
_ubool androidBluetoothAdapter::CreateBondOfRemoteDevice( AStringPtr address )
{
C2JString js_address( address );
jobject js_device = (jobject) mBluetoothAdapter.CallStaticObjectMethod( "getRemoteDevice", "(Ljava/lang/String;)Lcom/ege/android/AndroidBluetoothDevice;", js_address.ToJString( ) );
if ( js_device == _null )
{
ALOG_ERROR_1( "The '%s' remote BT device is not existing when create bond of it", address.Str( ) );
return _false;
}
if ( mBluetoothAdapter.CallStaticBooleanMethod( "createBond", "(Lcom/ege/android/AndroidBluetoothDevice;)Z", js_device ) == _false )
{
ALOG_ERROR_1( "Create bond of '%s' remote BT device failed", address.Str( ) );
return _false;
}
return _true;
}
_ubool androidBluetoothAdapter::RemoveBondOfRemoteDevice( AStringPtr address )
{
C2JString js_address( address );
jobject js_device = (jobject) mBluetoothAdapter.CallStaticObjectMethod( "getRemoteDevice", "(Ljava/lang/String;)Lcom/ege/android/AndroidBluetoothDevice;", js_address.ToJString( ) );
if ( js_device == _null )
{
ALOG_ERROR_1( "The '%s' remote BT device is not existing when remove bond of it", address.Str( ) );
return _false;
}
if ( mBluetoothAdapter.CallStaticBooleanMethod( "removeBond", "(Lcom/ege/android/AndroidBluetoothDevice;)Z", js_device ) == _false )
{
ALOG_ERROR_1( "Remove bond of '%s' remote BT device failed", address.Str( ) );
return _false;
}
return _true;
}
_dword androidBluetoothAdapter::GetBondedDevicesNumber( )
{
return mBluetoothAdapter.CallStaticIntMethod( "getBondedDevicesNumber", "()I" );
}
IBluetoothDevicePassRef androidBluetoothAdapter::GetBondedDeviceByIndex( _dword index )
{
jobject js_device = (jobject) mBluetoothAdapter.CallStaticObjectMethod( "getBondedDeviceByIndex", "(I)Lcom/ege/android/AndroidBluetoothDevice;", jint( index ) );
if ( js_device == _null )
return _null;
androidBluetoothDevice* device = new androidBluetoothDevice( );
if ( device->Initialize( js_device ) == _false )
{ EGE_RELEASE( device ); return _null; }
return device;
}
_ubool androidBluetoothAdapter::StartDiscovery( )
{
return mBluetoothAdapter.CallStaticBooleanMethod( "startDiscovery", "()Z" );
}
_void androidBluetoothAdapter::CancelDiscovery( )
{
mBluetoothAdapter.CallStaticBooleanMethod( "cancelDiscovery", "()Z" );
}
_ubool androidBluetoothAdapter::IsDiscovering( ) const
{
return mBluetoothAdapter.CallStaticBooleanMethod( "isDiscovering", "()Z" );
}
IBluetoothServerSocketPassRef androidBluetoothAdapter::CreateServerSocket( const UID128& uuid )
{
C2JString js_uuid( uuid.ToStringU( ) );
jobject js_socket = (jobject) mBluetoothAdapter.CallStaticObjectMethod( "createServerSocket", "(Ljava/lang/String;)Lcom/ege/android/AndroidBluetoothServerSocket;", js_uuid.ToJString( ) );
if ( js_socket == _null )
return _null;
androidBluetoothServerSocket* socket = new androidBluetoothServerSocket( );
if ( socket->Initialize( js_socket ) == _false )
{ EGE_RELEASE( socket ); return _null; }
return socket;
}
| [
"[email protected]"
] | |
6f0f1f1b547ae9058ed444a9ac1eb9f311571987 | 38dbfc96c93ba56665cbd64d20542f8a22eb604e | /Laser.h | 1332f0fce2a9dbd2d18dbf740453282c4a963a13 | [] | no_license | jozefboris/SpaceCraft | 4121082b9b981d01cf4250dd8f50a68df828370d | caf9bd2a1ab523f89e12c049ddb255fe8c99353b | refs/heads/master | 2023-03-08T13:29:58.534092 | 2021-02-25T20:42:58 | 2021-02-25T20:42:58 | 342,373,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | #ifndef Laser_h
#define Laser_h
#include<iostream>
#include "Zbran.h"
using namespace std;
class Laser : public Zbran {
private:
int m_criticalBonus;
public:
Laser(string nazov, int cena, int sila, int critical);
int getCena();
string getNazev();
int getSila();
};
#endif
| [
"[email protected]"
] | |
7168931189717945c7ddd2573306bb19498b0d92 | 7d71fa3604d4b0538f19ed284bc5c7d8b52515d2 | /Clients/AG/Pm8/App/EFILEDAT.CPP | b7343f517684f38cbefeaaf23f88c02dec122f42 | [] | no_license | lineCode/ArchiveGit | 18e5ddca06330018e4be8ab28c252af3220efdad | f9cf965cb7946faa91b64e95fbcf8ad47f438e8b | refs/heads/master | 2020-12-02T09:59:37.220257 | 2016-01-20T23:55:26 | 2016-01-20T23:55:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,005 | cpp | /*
// Embedded file record.
//
// $Workfile: EFILEDAT.CPP $
// $Revision: 1 $
// $Date: 3/03/99 6:05p $
*/
/*
// Revision History:
//
// $Log: /PM8/App/EFILEDAT.CPP $
//
// 1 3/03/99 6:05p Gbeddow
//
// Rev 1.0 14 Aug 1997 15:20:28 Fred
// Initial revision.
//
// Rev 1.0 14 Aug 1997 09:38:16 Fred
// Initial revision.
//
// Rev 1.2 15 Aug 1996 15:56:26 Jay
// Improved read/write/sizeofdata
//
// Rev 1.1 24 May 1996 16:12:46 Fred
// TRACEx
//
// Rev 1.0 14 Mar 1996 13:33:12 Jay
// Initial revision.
//
// Rev 1.0 16 Feb 1996 12:28:18 FRED
// Initial revision.
//
// Rev 2.1 08 Feb 1995 13:36:22 JAY
// Reverted. New series.
//
// Rev 1.2 08 Nov 1994 11:14:30 JAY
// Strips off path to name before storing it in the document.
//
// Rev 1.1 04 Nov 1994 09:55:04 JAY
// Added ExtractFile().
//
// Rev 1.0 03 Nov 1994 15:53:52 JAY
// Initial revision.
//
// Rev 1.0 02 Nov 1994 12:54:48 JAY
// Initial revision.
*/
#include "stdafx.h"
#include "efiledat.h"
#include "file.h"
#include "util.h"
/*****************************************************************************/
/* EmbeddedFile record */
/*****************************************************************************/
/*
// The creator for an embedded file record.
*/
CStandardDataRecord* CEmbeddedFileData::Create()
{
return new CEmbeddedFileData;
}
/*
// The initialization routine for the embedded file record.
*/
BOOL CEmbeddedFileData::Init(DATAID id, DATATYPE type, CStandardDataManager* pManager, LPVOID pData, ST_DEV_POSITION* in_where)
{
if (CStandardDataRecord::Init(id, type, pManager, NULL, in_where))
{
if (pData != NULL)
{
if (EmbedFile((LPCSTR)pData) != ERRORCODE_None)
{
return FALSE;
}
}
}
return TRUE;
}
/*
// The constructor for an embedded file record.
*/
CEmbeddedFileData::CEmbeddedFileData()
{
memset(&m_Record, 0, sizeof(m_Record));
}
/*
// The destructor.
*/
CEmbeddedFileData::~CEmbeddedFileData()
{
}
/*
// Embed a file in this record.
*/
ERRORCODE CEmbeddedFileData::EmbedFile(LPCSTR pFileName)
{
ERRORCODE error;
/* Attach the file name. */
TRY
{
#if 0
m_csFileName = pFileName;
#else
// Save only the base file name.
Util::SplitPath(pFileName, NULL, &m_csFileName);
#endif
}
CATCH_ALL(e)
{
return ERRORCODE_Memory;
}
END_CATCH_ALL
/* Set up the two devices we will be dealing with. */
StorageDevicePtr pDevice = m_pManager->GetStorageDevice();
ReadOnlyFile SourceFile(pFileName);
/* Get the length of the file. */
if ((error = SourceFile.length(&m_Record.m_DataSize)) != ERRORCODE_None)
{
return error;
}
/* Finish filling out m_record. */
m_Record.m_Type = EMBEDDED_TYPE_FILE;
/*
// We need storage to be allocated now.
// Preallocate us.
*/
if ((error = Allocate(StorageElement::Type(), StorageElement::Id())) != ERRORCODE_None)
{
return error;
}
*m_pWhere = m_position;
/* Compute where the data will be. */
m_DataStart = *m_pWhere
+ (SizeofData(pDevice) - m_Record.m_DataSize);
/* Compute the range for the embedded file. */
ST_DEV_POSITION start = m_DataStart;
ST_DEV_POSITION end = start + m_Record.m_DataSize;
/* Restrict ourselves to this range. */
pDevice->io_limits(start, end);
/* Create a device on top of the database one so we can write to it virtually. */
StorageFile DestFile(pDevice);
DestFile.set_subfile(start, end);
error = copy_file(&SourceFile, &DestFile);
if (error != ERRORCODE_None)
{
// TRACE("Got error %d while copying %ld bytes of data [%ld, %ld]\n",
// error, end - start, start, end);
}
/* Restore unrestricted access. */
pDevice->io_limits();
return error;
}
/*
// ReadData()
//
// Read the record.
*/
ERRORCODE CEmbeddedFileData::ReadData(StorageDevicePtr pDevice)
{
ERRORCODE error;
if ((error = CStandardDataRecord::ReadData(pDevice)) == ERRORCODE_None
&& (error = pDevice->read_record(&m_Record, sizeof(m_Record))) == ERRORCODE_None
&& (error = pDevice->read_cstring(m_csFileName)) == ERRORCODE_None)
{
error = pDevice->tell(&m_DataStart);
}
return error;
}
/*
// WriteData()
//
// Write the record.
// Only the record is written. The actual data should already have been
// written.
*/
ERRORCODE CEmbeddedFileData::WriteData(StorageDevicePtr pDevice)
{
ERRORCODE error;
if ((error = CStandardDataRecord::WriteData(pDevice)) == ERRORCODE_None
&& (error = pDevice->write_record(&m_Record, sizeof(m_Record))) == ERRORCODE_None
&& (error = pDevice->write_cstring(m_csFileName)) == ERRORCODE_None)
{
error = pDevice->tell(&m_DataStart);
}
return error;
}
/*
// SizeofData()
//
// Return the size of the record.
// This is the complete size of the written part and the file image.
*/
ST_MAN_SIZE CEmbeddedFileData::SizeofData(StorageDevicePtr pDevice)
{
return CStandardDataRecord::SizeofData(pDevice)
+ pDevice->size_record(sizeof(m_Record))
+ pDevice->size_cstring(m_csFileName)
+ m_Record.m_DataSize;
}
/*
// Assign method.
*/
void CEmbeddedFileData::Assign(const CDataRecord& Record)
{
/* Assign the base record first. */
CStandardDataRecord::Assign(Record);
/**** INCOMPLETE ****/
// This NEEDS to take into account transferring between databases.
// Perhaps EmbedFile should take a StorageFile (optionally) which could
// be a mapped onto this database. Then we could just call EmbedFile to
// move the data across.
}
/*
// RelocateData()
//
// This is a function called by the storage manager if our storage is
// ever relocated. This allows us to move any data we want saved.
// We need this so that we can move the file image.
*/
ERRORCODE CEmbeddedFileData::RelocateData(StorageDevicePtr pDevice, ST_DEV_POSITION OldPosition, ST_DEV_POSITION NewPosition)
{
ERRORCODE error;
ST_DEV_POSITION NewDataPos = NewPosition
+ (SizeofData(pDevice) - m_Record.m_DataSize);
/* Move the file image from the old location to the new location. */
if ((error = pDevice->move(m_DataStart, NewDataPos, m_Record.m_DataSize)) == ERRORCODE_None)
{
/* Data is now here. */
m_DataStart = NewDataPos;
}
return error;
}
/*
// The file completion notify for a prepped normal embedded file record.
*/
void CEmbeddedFileData::EfileNormalCompletion(StorageFile* pFile, LPVOID pData)
{
CEmbeddedFileData* efile = (CEmbeddedFileData*)pData;
// TRACE1("Normal completion for record %ld\n", efile->Id());
efile->Release();
}
/*
// The file completion notify for a prepped read-only embedded file record.
*/
void CEmbeddedFileData::EfileReadonlyCompletion(StorageFile* pFile, LPVOID pData)
{
const CEmbeddedFileData* efile = (const CEmbeddedFileData*)pData;
// TRACE1("Read-only completion for record %ld\n", efile->Id());
efile->ReleaseReadOnly();
}
/*
// Prep a file using this record.
*/
ERRORCODE CEmbeddedFileData::PrepFile(StorageFile* pFile, BOOL fReadOnly) const
{
ERRORCODE error;
if ((error = pFile->set_based_device(m_pManager->GetStorageDevice())) == ERRORCODE_None)
{
ST_DEV_POSITION start = DataStart();
ST_DEV_POSITION end = start + DataSize();
/* Add a reference to us since the StorageFile now "owns" us. */
((CEmbeddedFileData*)this)->AddRef();
/* Total success. 'error' is set correctly. */
TRACE2("Using subfile %ld to %ld\n", start, end);
pFile->set_subfile(start, end);
pFile->set_completion_notify(fReadOnly
? EfileReadonlyCompletion
: EfileNormalCompletion,
(LPVOID)this);
// TRACE2("Prep for record %ld (%d)\n", Id(), fReadOnly);
/* Make sure we can actually access the file. */
if ((error = pFile->seek(0, ST_DEV_SEEK_SET)) != ERRORCODE_None)
{
/* Undo what we just did. */
// od("Inaccessible!\r\n");
pFile->reset();
}
}
return error;
}
/*
// Extract the file from this record.
*/
ERRORCODE CEmbeddedFileData::ExtractFile(LPCSTR pFileName)
{
ERRORCODE error;
/* Set up the two devices we will be dealing with. */
StorageDevicePtr pDevice = m_pManager->GetStorageDevice();
/* Compute the range for the embedded file. */
ST_DEV_POSITION start = m_DataStart;
ST_DEV_POSITION end = start + m_Record.m_DataSize;
/* Restrict ourselves to this range. */
pDevice->io_limits(start, end);
/* Create a device on top of the database one so we can read from it virtually. */
ReadOnlyFile SourceFile(pDevice);
SourceFile.set_subfile(start, end);
/* Set up the destination file so we can write to it. */
StorageFile DestFile(pFileName);
error = copy_file(&SourceFile, &DestFile);
/* Restore unrestricted access. */
pDevice->io_limits();
return error;
}
| [
"[email protected]"
] | |
d8463b85f4cd89704fa42416dea16ebbdfcbb751 | ede6bb95b22e8b2315fea50af2415691b17519a7 | /std/std-clamp/main.cc | a97c14573c49be2bc632077387b4bd5b21577692 | [
"MIT"
] | permissive | gusenov/examples-cpp | d3880c1bd436b7d0b8d4955266a580602a378f56 | f2e60b6d3d61cfcb7cc69aba1081162ce2de5193 | refs/heads/master | 2022-10-20T09:13:56.065787 | 2022-10-12T15:48:13 | 2022-10-12T15:48:13 | 154,664,278 | 21 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 387 | cc | #include <algorithm>
#include <iostream>
int main(int argc, char* argv[])
{
int lo = 10;
int hi = 30;
std::cout << std::clamp(9, lo, hi) << std::endl; // 10
std::cout << std::clamp(10, lo, hi) << std::endl; // 10
std::cout << std::clamp(30, lo, hi) << std::endl; // 30
std::cout << std::clamp(31, lo, hi) << std::endl; // 30
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
2012954c63d1118a6be54adc56a4432572221122 | efdec6b629075f9b4aa532cdabc70bf143d637e7 | /Chapter10/setDemo1.cpp | cb5b98772b8ac4bdf59aa238fd86378937c81be5 | [] | no_license | Zerrari/CppNotes | 8eee019db1f2c748545fa46c461a90f3b0e0d634 | 4d90e988d67016f6df0567abcd44991bf771a8d7 | refs/heads/main | 2023-05-24T07:05:15.877855 | 2021-06-14T10:08:15 | 2021-06-14T10:08:15 | 364,907,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | #include <iostream>
#include <vector>
#include <set>
using namespace std;
int main()
{
vector<int> ivec(10,1);
vector<int>::iterator iter = ivec.begin();
int i = 1;
while (iter != ivec.end())
{
*iter++ = i;
*iter++ = i++;
}
set<int> iset(ivec.begin(),ivec.end());
cout << iset.size() << endl;
return 0;
}
| [
"[email protected]"
] | |
8c8b535cc0eaccccc0951dea2e292e32fedf3245 | b2132bab46103e5d8024d5704c59a5d403057901 | /a1/nfa.cpp | 4d2f28fc4a66c721c88d4fd2ad2e1c908a3234e0 | [] | no_license | wijagels/CS373 | 54784da2eadfdd9c9e182a3a3e78a6483e50bde2 | 16710a8044956e36848d6076f83aae3f7d57b279 | refs/heads/master | 2021-03-22T04:14:39.942957 | 2017-03-19T19:42:37 | 2017-03-19T19:42:37 | 80,556,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,286 | cpp | #include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
struct State {
State(size_t idx) : State({}, false, false, idx) {}
State(const std::multimap<char, size_t>& transitions, bool start, bool accept,
size_t idx)
: transitions_{transitions}, start_{start}, accept_{accept}, idx_{idx} {}
void add_transition(const std::pair<char, size_t>& t) {
transitions_.insert(t);
}
std::multimap<char, size_t>
transitions_; // Mapping of symbols to destinations
bool start_;
bool accept_;
size_t idx_;
};
void fucking_nfa_function(const std::unordered_map<size_t, State>& shittynfa,
std::string shitfromuser) {
std::set<size_t> accepts, rejects;
std::queue<std::pair<std::string, State>> q{};
for (auto it : shittynfa) {
if (it.second.start_) q.push({shitfromuser, it.second});
}
while (!q.empty()) {
State s = q.front().second;
std::string str = q.front().first;
q.pop();
if (str.size() == 0) {
if (s.accept_) {
accepts.insert(s.idx_);
} else {
rejects.insert(s.idx_);
}
} else {
char symbol = str.front();
str = str.substr(1, str.size());
auto rng = s.transitions_.equal_range(symbol);
for (auto it = rng.first; it != rng.second; it++) {
q.push({str, shittynfa.at(it->second)});
}
}
}
if (!accepts.empty()) {
std::cout << "accept";
for (auto e : accepts) {
std::cout << " " << e;
}
} else {
std::cout << "reject";
for (auto e : rejects) {
std::cout << " " << e;
}
}
std::cout << std::endl;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
exit(1);
}
char* fuckingfilename = argv[1];
std::string input{argv[2]};
std::ifstream file{fuckingfilename};
if (!file.is_open()) {
exit(1);
}
std::string line;
std::unordered_map<size_t, State> shittynfa;
while (std::getline(file, line)) {
std::stringstream ss{line};
std::string command;
ss >> command;
if (command == "state") {
size_t fuckingstate;
std::string isitstartoraccept;
ss >> fuckingstate;
ss >> isitstartoraccept;
bool st = false;
bool ac = false;
if (isitstartoraccept == "start") {
st = true;
if (!ss.eof()) {
ss >> isitstartoraccept;
if (isitstartoraccept == "accept") {
ac = true;
}
}
} else if (isitstartoraccept == "accept") {
ac = true;
if (!ss.eof()) {
ss >> isitstartoraccept;
if (isitstartoraccept == "start") {
st = true;
}
}
} else if (isitstartoraccept == "acceptstart") {
ac = true;
st = true;
} else {
exit(1);
}
State muhstate{{}, st, ac, fuckingstate};
shittynfa.insert({fuckingstate, muhstate});
} else if (command == "transition") {
size_t from, to;
char sym;
ss >> from;
ss >> sym;
ss >> to;
if (shittynfa.find(from) == shittynfa.end())
shittynfa.emplace(from, from);
shittynfa.at(from).add_transition({sym, to});
}
}
fucking_nfa_function(shittynfa, input);
}
| [
"[email protected]"
] | |
218e757c3bd3493265275a97a041bda26c551ef8 | 3aa3a4a67636abb6ff1b285d0184bc5043143fa4 | /codeforces/723/B/sol.cpp | e28655e5c7ca685abe8ac1644feb2a130092b30e | [] | no_license | vivekdusad/dsa-algo | 30a649cb009854539ceb2388b19ca0198636ec20 | 6bd9f6d75477df995bd2ecf899504eee0629a1ec | refs/heads/master | 2023-06-04T16:31:08.048851 | 2021-06-25T05:14:41 | 2021-06-25T05:14:41 | 370,911,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | cpp | #include<bits/stdc++.h>
using namespace std;
#define gc getchar_unlocked
#define fo(i,n) for(i=0;i<n;i++)
#define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define ll long long
#define si(x) scanf("%d",&x)
#define sl(x) scanf("%lld",&x)
#define ss(s) scanf("%s",s)
#define pi(x) printf("%d\n",x)
#define pl(x) printf("%lld\n",x)
#define ps(s) printf("%s\n",s)
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define clr(x) memset(x, 0, sizeof(x))
#define sortall(x) sort(all(x))
#define tr(it, a) for(auto it = a.begin(); it != a.end(); it++)
#define PI 3.1415926535897932384626
typedef pair<int, int> pii;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpii;
typedef vector<pl> vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
void solve() {
int i, j, n, m;
cin>>n;
i = n%11;
j = n-i*111;
if(j>=0&&j%11==0){
cout<<"YES";
}
else{
cout<<"NO";
}
cout<<endl;
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
int t = 1;
cin >> t;
while(t--) {
solve();
}
return 0;
}
| [
"[email protected]"
] | |
b85127ff62b190b3354cf077c2a4a05870b9c30b | cb6984c461f25c804d901099bf7d49776e680f6a | /C++ Project/Dump/main.cpp | 964907dd0da233c6e9f138270036d2d0045c1fba | [] | no_license | DatAvgAsianBoi-zz/Dumpster_of_Old_Stuff | dbcc3edca294b3744f736d79005a27c7ee6942e6 | b98a7ddbc9b052ddc069bb965f4d652f542846f5 | refs/heads/master | 2022-11-16T01:20:38.651142 | 2020-07-18T02:09:42 | 2020-07-18T02:09:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 410 | cpp | #include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main(){
ifstream sin("out.txt");
if(!sin){
cout << "nani";
exit(1);
}
string s;
sin >> s;
cout << s;
return 0;
}
/*
1. B
3. B
4. C
5. C - A
7. A
8. B
9. B
10. D
12. D
14. D
15. B
16. D
17. C
19. A
20. C
21. D
*/
| [
"[email protected]"
] | |
3d3e2d5093a0af0f2aeddb959a3938c39240f4a4 | 269ed6526914de551ac1fa2b1c83ea8ba9e50525 | /app/src/main/cpp/k_util/k_socket.cpp | 21bffc032890873f9344de7281b662ef50d9b8b3 | [] | no_license | greenjim301/Titan | 7b824ee1d0ffda8238e01e7316f0c57bec7ebe22 | f47756ab7d7c1726d5dd06cd3b8c88b34de9d234 | refs/heads/master | 2020-03-19T05:05:22.933477 | 2018-06-04T01:30:26 | 2018-06-04T01:30:26 | 135,898,737 | 14 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,834 | cpp | #include "k_socket.h"
#include "k_errno.h"
#ifdef WIN32
#define K_INVALID_SOCKET INVALID_SOCKET
#else
#define K_INVALID_SOCKET -1
#endif
k_socket::k_socket()
: m_sock(K_INVALID_SOCKET)
{
}
k_socket::~k_socket()
{
if (m_sock != K_INVALID_SOCKET)
{
#ifdef WIN32
closesocket(m_sock);
#else
close(m_sock);
#endif
}
}
void k_socket::set_sock(int sock)
{
m_sock = sock;
}
int k_socket::get_sock()
{
return m_sock;
}
int k_socket::init(int af, int type)
{
m_sock = socket(af, type, 0);
if (m_sock == K_INVALID_SOCKET)
{
return -1;
}
return 0;
}
int k_socket::k_bind(k_sockaddr& sock_addr)
{
int ret = bind(m_sock, sock_addr.get_sockaddr(), sock_addr.get_size());
if (ret)
{
return -1;
}
return 0;
}
int k_socket::k_listen()
{
int ret = listen(m_sock, SOMAXCONN);
return ret;
}
int k_socket::k_accept(k_sockaddr& sock_addr, k_socket& sock)
{
while (true)
{
int fd = accept(m_sock, sock_addr.get_sockaddr(), sock_addr.get_size_ptr());
if (fd != K_INVALID_SOCKET)
{
sock.set_sock(fd);
return 0;
}
else
{
int err = k_errno::last_error();
if (k_errno::is_retry_error(err))
{
continue;
}
return -1;
}
}
}
int k_socket::k_connect(k_sockaddr& sock_addr)
{
while (true)
{
int ret = connect(m_sock, sock_addr.get_sockaddr(), sock_addr.get_size());
if (ret)
{
int err = k_errno::last_error();
if (k_errno::is_retry_error(err))
{
continue;
}
}
return ret;
}
}
int k_socket::k_send(char* buf, int buf_size)
{
int ret;
int offset = 0;
do
{
ret = send(m_sock, buf + offset, buf_size - offset, 0);
if (ret < 0)
{
int err = k_errno::last_error();
if (k_errno::is_retry_error(err))
{
continue;
}
else
{
break;
}
}
else
{
offset += ret;
}
} while (offset != buf_size);
if (offset != buf_size)
{
return ret;
}
else
{
return offset;
}
}
int k_socket::k_recv(char* buf, int buf_size)
{
while (true)
{
int ret = recv(m_sock, buf, buf_size, 0);
if (ret < 0)
{
int err = k_errno::last_error();
if (k_errno::is_retry_error(err))
{
continue;
}
}
return ret;
}
}
int k_socket::k_recv_n(char* buf, int buf_size)
{
int offset = 0;
int ret;
while (offset < buf_size)
{
ret = this->k_recv(buf + offset, buf_size - offset);
if (ret <= 0)
{
return -1;
}
offset += ret;
}
return 0;
}
int k_socket::k_setopt(int level, int optname, const char *optval, socklen_t optlen)
{
return setsockopt(m_sock, level, optname, optval, optlen);
}
#ifndef WIN32
int k_socket::k_write(char* buf, int buf_size)
{
return write(m_sock, buf, buf_size);
}
int k_socket::k_read(char* buf, int buf_size)
{
return read(m_sock, buf, buf_size);
}
#endif
int k_socket::k_recvfrom(char* buf, int buf_size, k_sockaddr& from_addr)
{
while (true)
{
int ret = recvfrom(m_sock, buf, buf_size, 0,
from_addr.get_sockaddr(), from_addr.get_size_ptr());
if (ret < 0)
{
int err = k_errno::last_error();
if (k_errno::is_retry_error(err))
{
continue;
}
}
return ret;
}
}
int k_socket::k_sendto(char* buf, int buf_size, k_sockaddr& to_addr)
{
int ret;
int offset = 0;
do
{
ret = sendto(m_sock, buf + offset, buf_size - offset, 0,
to_addr.get_sockaddr(), to_addr.get_size());
if (ret < 0)
{
int err = k_errno::last_error();
if (k_errno::is_retry_error(err))
{
continue;
}
else
{
break;
}
}
else
{
offset += ret;
}
} while (offset != buf_size);
if (offset != buf_size)
{
return ret;
}
else
{
return offset;
}
}
| [
"[email protected]"
] | |
5ecb59e2c3c3c34afb0995cbdc0f6439fddb2e25 | 3c444f7c0678d0a4d07990a4aea9ff891808b2e0 | /include/Directory.hpp | dfa64d5025bcfa60a3ad9cb5139d913501e3dff2 | [] | no_license | srikanth007m/spruce | ffeaa9f97b8b3c2ec446a72df449306e548769f7 | 89a29b3f4a5c2c84d3288b57f01363485885e8af | refs/heads/master | 2021-01-10T03:43:33.341546 | 2014-10-03T07:01:05 | 2014-10-03T07:01:05 | 49,263,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,204 | hpp | // Directory.hpp
//
// Copyright (C) 2011, Institute for System Programming
// of the Russian Academy of Sciences (ISPRAS)
//
// Author: Eduard Bagrov <[email protected]>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
#ifndef DIRECTORY_H
#define DIRECTORY_H
#include "Exception.hpp"
#include "UnixCommand.hpp"
#include <string>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
using std::cerr;
using std::string;
// Class representing a linux directory
// Example usage:
// Directory directory("newfile");
// int fd = directory.GetdirectoryDescriptor();
class Directory
{
public:
Directory():
_pathname(""),
_fd(-1),
_mode(0),
_flags(0)
{}
Directory(string pathname, mode_t mode = static_cast<mode_t>(S_IRUSR | S_IWUSR), int flags = O_DIRECTORY ) :
_pathname(pathname),
_fd(-1),
_mode(mode),
_flags(flags)
{
Open(pathname, mode, flags);
}
int Open(string pathname, mode_t mode = static_cast<mode_t>(S_IRUSR | S_IWUSR), int flags = O_DIRECTORY )
{
_pathname = pathname;
_mode = mode;
_flags = flags;
if (mkdir(_pathname.c_str(), _mode) == -1 && errno != EEXIST)
{
throw Exception("Cannot create directory " + _pathname +
": error = " + static_cast<string>(strerror(errno)));
}
errno = 0;
_fd = open( _pathname.c_str(), _flags );
if ( _fd == -1 )
{
throw Exception("Cannot open directory " + _pathname +
": error = " + static_cast<string>(strerror(errno)));
}
return _fd;
}
~Directory()
{
try
{
close(_fd);
//cerr<<"Removing directory "<<_pathname;
UnixCommand remove("rm");
vector<string> args;
args.push_back("-rf");
args.push_back(_pathname);
ProcessResult * res = remove.Execute(args);
if ( res == NULL || res->GetStatus() )
{
cerr << "Cannot remove Directory" << _pathname<<endl;
cerr << res->GetOutput() << endl;
}
delete res;
}
catch (Exception ex)
{
//cerr<<ex.GetMessage();
}
}
string GetPathname() const
{
return _pathname;
}
int GetDirectoryDescriptor() const
{
return _fd;
}
int GetFlags() const
{
return _flags;
}
mode_t GetMode() const
{
return _mode;
}
private:
string _pathname;
int _fd;
mode_t _mode;
int _flags;
};
#endif
| [
"[email protected]"
] | |
139ea5bc71013ba2a7ea74d8ac493ec788962d27 | e09af34f2d646e64b2ad2075bd3b250a635cb214 | /SDK/SoT_BP_Orderofsouls_MadameOlwen_classes.hpp | a4c44aa3fbe464538c43006951c2a35491fb4108 | [] | no_license | zanzo420/SoT-SDK | 349e6f8b4afcd7756879d8ce5416af86705d8a79 | 5bc545e1822151b3519666a1ed8fef1ba259fc52 | refs/heads/master | 2023-07-14T17:41:58.212853 | 2021-09-01T04:01:29 | 2021-09-01T04:01:29 | 138,799,955 | 1 | 0 | null | 2020-02-20T19:41:03 | 2018-06-26T22:21:26 | C++ | UTF-8 | C++ | false | false | 793 | hpp | #pragma once
// Sea of Thieves (2) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_Orderofsouls_MadameOlwen_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_Orderofsouls_MadameOlwen.BP_Orderofsouls_MadameOlwen_C
// 0x0000 (0x05D8 - 0x05D8)
class ABP_Orderofsouls_MadameOlwen_C : public ABP_Orderofsouls_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_Orderofsouls_MadameOlwen.BP_Orderofsouls_MadameOlwen_C"));
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
e25b60702aee497bcf573f579c8c753bf8db5472 | b2e7fe2f06bf4df87c42e3d01add817710eb3861 | /frameworks/fluidservice/libs/include/messaging/CondVar.h | 1b1673ba613be9cbdbc61be5b1b01a3ed00075ca | [] | no_license | ohsang1213/FLUID_Platform | 0e0624c679541e50b4d9817f83afd0a1dc4cab16 | 0b1c44ac491698fc637ee1d412dd2c645ef54d9d | refs/heads/master | 2022-04-11T07:05:38.884514 | 2020-03-11T01:40:02 | 2020-03-11T01:40:02 | 193,877,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | h | /*
* Copyright (C) 2011 Daniel Himmelein
*
* 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 MESSAGING_CONDVAR_H
#define MESSAGING_CONDVAR_H
#include <stdint.h>
#include <pthread.h>
#include <messaging/Utils.h>
namespace android {
namespace messaging {
class Lock;
class CondVar {
public:
CondVar(Lock& lock);
~CondVar();
void wait();
void wait(uint32_t timeout);
void wait(timespec& absTimestamp);
void notify();
void notifyAll();
private:
pthread_cond_t mCondVar;
pthread_condattr_t mCondVarAttributes;
Lock& mCondVarLock;
NO_COPY_CTOR_AND_ASSIGNMENT_OPERATOR(CondVar)
};
} /* namespace messaging */
} /* namespace android */
#endif
| [
"[email protected]"
] | |
55abb83413419adc586b7dc02cbc2c4b4d8910c8 | 8db3dfa3e15437e8cd7715bb76b7540d755846f3 | /src/dx_serie.h | 897ae05dfb270fa878236e6abecd41420d2ae76e | [
"MIT"
] | permissive | D33pBlue/Cinenote-3.0 | 0b39e8f4f54fae524efb00fd1c1483844075acfd | 7dd871b40c537fdf73e7489919c4bfef391864c2 | refs/heads/master | 2020-03-09T16:50:55.667849 | 2018-04-11T11:07:11 | 2018-04-11T11:07:11 | 128,895,531 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | h | #ifndef DX_SERIE_H
#define DX_SERIE_H
#include <QWidget>
#include <QtGui>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
class dx_serie : public QWidget
{
Q_OBJECT
public:
explicit dx_serie(QWidget *parent = 0);
private:
QLabel *t;
QPushButton *nuova;
QPushButton *viste;
QPushButton *attese;
QLineEdit *cer;
QPushButton *crono;
signals:
public slots:
void inseriscinuova();
void cercaserie();
};
#endif // DX_SERIE_H
| [
"[email protected]"
] | |
f9e3d753fe77792f09597b7169c1eed62df73b9b | ef686be54010f05f061046126b833df503aaa24d | /CondCore/CondDB/src/OraDbSchema.cc | 0897d1a61d027b7ea55886057510aa1b984e1dfd | [] | no_license | dmajumder/cmssw | b371a2cf810443680b5af930a34c541038f7e92f | 9a69e0fa4485cf1e5eea13431236284a86c3a2dd | refs/heads/CMSSW_7_1_X | 2021-01-17T00:03:19.655511 | 2015-04-17T11:02:21 | 2015-04-17T11:02:21 | 16,834,586 | 1 | 2 | null | 2016-02-26T19:06:43 | 2014-02-14T10:48:17 | C++ | UTF-8 | C++ | false | false | 12,624 | cc | #include "CondCore/CondDB/interface/Exception.h"
#include "OraDbSchema.h"
//
#include "CondCore/DBCommon/interface/TagMetadata.h"
#include "CondCore/IOVService/interface/IOVEditor.h"
#include "CondCore/MetaDataService/interface/MetaData.h"
#include "CondCore/TagCollection/interface/TagCollectionRetriever.h"
#include "CondCore/TagCollection/interface/TagDBNames.h"
//
// externals
#include "RelationalAccess/ISchema.h"
namespace cond {
namespace persistency {
IOVCache::IOVCache( cond::DbSession& s ):
m_iovAccess( s ){
}
cond::DbSession& IOVCache::session(){
return m_iovAccess.proxy().db();
}
cond::IOVProxy IOVCache::iovSequence(){
return m_iovAccess.proxy();
}
cond::IOVEditor IOVCache::editor(){
return m_iovAccess;
}
bool IOVCache::existsTag( const std::string& t ){
cond::MetaData metadata( session() );
return metadata.hasTag( t );
}
std::string IOVCache::getToken( const std::string& tag ){
if( tag != m_tag ){
cond::MetaData metadata( session() );
m_tag = tag;
m_token = metadata.getToken( tag );
}
return m_token;
}
void IOVCache::addTag( const std::string& tag, const std::string token ){
if( tag != m_tag ){
cond::MetaData metadata( session() );
metadata.addMapping( tag, token );
m_tag = tag;
m_token = token;
}
}
bool IOVCache::load( const std::string& tag ){
std::string token = getToken( tag );
if( token.empty() ) return false;
if(m_iovAccess.token() != token) m_iovAccess.load( token );
return true;
}
OraTagTable::OraTagTable( IOVCache& cache ):
m_cache( cache ){
}
bool OraTagTable::select( const std::string& name ){
return m_cache.existsTag( name );
}
bool OraTagTable::select( const std::string& name, cond::TimeType& timeType, std::string& objectType,
cond::SynchronizationType&, cond::Time_t& endOfValidity,
std::string& description, cond::Time_t& lastValidatedTime ){
if(!m_cache.load( name )) return false;
if( m_cache.iovSequence().size()==0 ) return false;
timeType = m_cache.iovSequence().timetype();
std::string ptok = m_cache.iovSequence().head(1).front().token();
objectType = m_cache.session().classNameForItem( ptok );
//if( m_cache.iovSequence().payloadClasses().size()==0 ) throwException( "No payload type information found.","OraTagTable::select");
//objectType = *m_cache.iovSequence().payloadClasses().begin();
endOfValidity = m_cache.iovSequence().lastTill();
description = m_cache.iovSequence().comment();
lastValidatedTime = m_cache.iovSequence().tail(1).back().since();
return true;
}
bool OraTagTable::getMetadata( const std::string& name, std::string& description,
boost::posix_time::ptime&, boost::posix_time::ptime& ){
if(!m_cache.load( name )) return false;
description = m_cache.iovSequence().comment();
// TO DO: get insertion / modification time from the Logger?
return true;
}
void OraTagTable::insert( const std::string& name, cond::TimeType timeType, const std::string&,
cond::SynchronizationType, cond::Time_t endOfValidity, const std::string& description,
cond::Time_t, const boost::posix_time::ptime& ){
std::string tok = m_cache.editor().create( timeType, endOfValidity );
if( !m_cache.validationMode() ){
m_cache.editor().stamp( description );
}
m_cache.addTag( name, tok );
}
void OraTagTable::update( const std::string& name, cond::Time_t& endOfValidity, const std::string& description,
cond::Time_t, const boost::posix_time::ptime& ){
std::string tok = m_cache.getToken( name );
if( tok.empty() ) throwException( "Tag \""+name+"\" has not been found in the database.","OraTagTable::update");
m_cache.editor().load( tok );
m_cache.editor().updateClosure( endOfValidity );
if( !m_cache.validationMode() ) m_cache.editor().stamp( description );
}
void OraTagTable::updateValidity( const std::string&, cond::Time_t,
const boost::posix_time::ptime& ){
// can't be done in this case...
}
void OraTagTable::setValidationMode(){
m_cache.setValidationMode();
}
OraPayloadTable::OraPayloadTable( DbSession& session ):
m_session( session ){
}
bool OraPayloadTable::select( const cond::Hash& payloadHash,
std::string& objectType,
cond::Binary& payloadData,
cond::Binary& //streamerInfoData
){
ora::Object obj = m_session.getObject( payloadHash );
objectType = obj.typeName();
payloadData.fromOraObject(obj );
return true;
}
bool OraPayloadTable::getType( const cond::Hash& payloadHash, std::string& objectType ){
objectType = m_session.classNameForItem( payloadHash );
return true;
}
cond::Hash OraPayloadTable::insertIfNew( const std::string& objectType,
const cond::Binary& payloadData,
const cond::Binary&, //streamerInfoData
const boost::posix_time::ptime& ){
ora::Object obj = payloadData.oraObject();
std::string tok = m_session.storeObject( obj, objectType );
m_session.flush();
return tok;
}
OraIOVTable::OraIOVTable( IOVCache& iovCache ):
m_cache( iovCache ){
}
size_t OraIOVTable::selectGroups( const std::string& tag, std::vector<cond::Time_t>& groups ){
if(!m_cache.load( tag )) return 0;
if( m_cache.iovSequence().size()>0 ){
groups.push_back( m_cache.iovSequence().firstSince() );
groups.push_back( m_cache.iovSequence().lastTill() );
return true;
}
return false;
}
size_t OraIOVTable::selectSnapshotGroups( const std::string& tag, const boost::posix_time::ptime&,
std::vector<cond::Time_t>& groups ){
// no (easy) way to do it...
return selectGroups( tag, groups );
}
size_t OraIOVTable::selectLatestByGroup( const std::string& tag, cond::Time_t lowerGroup, cond::Time_t upperGroup ,
std::vector<std::tuple<cond::Time_t,cond::Hash> >& iovs){
if(!m_cache.load( tag )) return 0;
cond::IOVRange range = m_cache.iovSequence().range( lowerGroup, upperGroup );
size_t ret = 0;
for( auto iov : range ){
iovs.push_back( std::make_tuple( iov.since(), iov.token() ) );
ret++;
}
return ret;
}
size_t OraIOVTable::selectSnapshotByGroup( const std::string& tag, cond::Time_t lowerGroup, cond::Time_t upperGroup,
const boost::posix_time::ptime&,
std::vector<std::tuple<cond::Time_t,cond::Hash> >& iovs){
// no (easy) way to do it...
return selectLatestByGroup( tag, lowerGroup, upperGroup, iovs );
}
size_t OraIOVTable::selectLatest( const std::string& tag, std::vector<std::tuple<cond::Time_t,cond::Hash> >& iovs){
// avoid this! copying the entire iov sequence...
if(!m_cache.load( tag )) return 0;
size_t ret = 0;
for( auto iov : m_cache.iovSequence() ){
iovs.push_back( std::make_tuple( iov.since(), iov.token() ) );
ret++;
}
return ret;
}
bool OraIOVTable::getLastIov( const std::string& tag, cond::Time_t& since, cond::Hash& hash ){
if(!m_cache.load( tag ) || m_cache.iovSequence().size()==0 ) return false;
cond::IOVElementProxy last = *(--m_cache.iovSequence().end());
since = last.since();
hash = last.token();
return true;
}
bool OraIOVTable::getSize( const std::string& tag, size_t& size ){
if(!m_cache.load( tag )) return false;
size = m_cache.iovSequence().size();
return true;
}
bool OraIOVTable::getSnapshotSize( const std::string& tag, const boost::posix_time::ptime&, size_t& size ){
// no (easy) way to do it...
return getSize( tag,size );
}
void OraIOVTable::insertOne( const std::string& tag, cond::Time_t since, cond::Hash payloadHash,
const boost::posix_time::ptime& ){
if(!m_cache.load(tag)) throwException("Tag "+tag+" has not been found in the database.",
"OraIOVTable::insertOne");
m_cache.editor().append( since, payloadHash );
}
void OraIOVTable::insertMany( const std::string& tag,
const std::vector<std::tuple<cond::Time_t,cond::Hash,boost::posix_time::ptime> >& iovs ){
if(!m_cache.load(tag)) throwException("Tag "+tag+" has not been found in the database.",
"OraIOVTable::insertOne");
std::vector<std::pair<cond::Time_t, std::string > > data;
data.reserve( iovs.size() );
for( auto v : iovs ){
data.push_back( std::make_pair( std::get<0>(v), std::get<1>(v) ) );
}
m_cache.editor().bulkAppend( data );
}
void OraIOVTable::erase( const std::string& ){
throwException( "Erase iovs from ORA database is not supported.",
"OraIOVTable::erase" );
}
OraIOVSchema::OraIOVSchema( DbSession& session ):
m_cache( session ),
m_tagTable( m_cache ),
m_iovTable( m_cache ),
m_payloadTable( session ){
};
bool OraIOVSchema::exists(){
return m_cache.session().storage().exists();
}
bool OraIOVSchema::create(){
return m_cache.session().createDatabase();
}
ITagTable& OraIOVSchema::tagTable(){
return m_tagTable;
}
IIOVTable& OraIOVSchema::iovTable(){
return m_iovTable;
}
IPayloadTable& OraIOVSchema::payloadTable(){
return m_payloadTable;
}
ITagMigrationTable& OraIOVSchema::tagMigrationTable(){
throwException("Tag Migration interface is not available in this implementation.",
"OraIOVSchema::tagMigrationTabl");
}
OraGTTable::OraGTTable( DbSession& session ):
m_session( session ){
}
bool OraGTTable::select( const std::string& name ){
cond::TagCollectionRetriever gtRetriever( m_session, "", "" );
return gtRetriever.existsTagCollection( name+"::All" );
}
bool OraGTTable::select( const std::string& name, cond::Time_t& validity, boost::posix_time::ptime& snapshotTime){
bool ret = false;
if( select( name ) ){
ret = true;
validity = cond::time::MAX_VAL;
snapshotTime = boost::posix_time::ptime();
}
return ret;
}
bool OraGTTable::select( const std::string& name, cond::Time_t& validity, std::string&,
std::string&, boost::posix_time::ptime& snapshotTime){
return select( name, validity, snapshotTime );
}
void OraGTTable::insert( const std::string&, cond::Time_t, const std::string&, const std::string&,
const boost::posix_time::ptime&, const boost::posix_time::ptime& ){
// not supported...
}
void OraGTTable::update( const std::string&, cond::Time_t, const std::string&, const std::string&,
const boost::posix_time::ptime&, const boost::posix_time::ptime& ){
// not supported...
}
OraGTMapTable::OraGTMapTable( DbSession& session ):
m_session( session ){
}
bool OraGTMapTable::select( const std::string& gtName, std::vector<std::tuple<std::string,std::string,std::string> >& tags ){
return select( gtName, "", "", tags );
}
bool OraGTMapTable::select( const std::string& gtName, const std::string& preFix, const std::string& postFix,
std::vector<std::tuple<std::string,std::string,std::string> >& tags ){
std::set<cond::TagMetadata> tmp;
cond::TagCollectionRetriever gtRetriever( m_session, preFix, postFix );
if(!gtRetriever.selectTagCollection( gtName, tmp ) ) return false;
if( tmp.size() ) tags.resize( tmp.size() );
size_t i = 0;
for( const auto& m : tmp ){
std::string tagFullName = m.tag+"@["+m.pfn+"]";
tags[ i ] = std::make_tuple( m.recordname, m.labelname, tagFullName );
i++;
}
return true;
}
void OraGTMapTable::insert( const std::string& gtName, const std::vector<std::tuple<std::string,std::string,std::string> >& tags ){
// not supported...
}
OraGTSchema::OraGTSchema( DbSession& session ):
m_session( session ),
m_gtTable( session ),
m_gtMapTable( session ){
}
bool OraGTSchema::exists(){
cond::TagCollectionRetriever gtRetriever( m_session, "", "" );
return gtRetriever.existsTagDatabase();
}
IGTTable& OraGTSchema::gtTable(){
return m_gtTable;
}
IGTMapTable& OraGTSchema::gtMapTable(){
return m_gtMapTable;
}
}
}
| [
"[email protected]"
] | |
2dfba5ea0a25dd619826e37b35569f2fd42b7fb1 | 362978f6a254981c985adc888cbafafd3f82efdb | /Configs.h | 95fbaf51af05612bb3264b6398e7bfed3e50779f | [] | no_license | DragonGongY/u2net-basnet-script | a88d959b7299497c574e9c12da4007be60660522 | 8be2979c94ad758e6c28b3447676c717c365822b | refs/heads/master | 2023-06-08T13:30:37.973207 | 2021-07-01T10:17:51 | 2021-07-01T10:17:51 | 381,970,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 205 | h | //
// Created by dp on 2021/6/29.
//
#include "opencv2/opencv.hpp"
#include "torch/script.h"
#include <memory>
#include <iostream>
#ifndef TEST_CONFIGS_H
#define TEST_CONFIGS_H
#endif //TEST_CONFIGS_H
| [
"[email protected]"
] | |
e31861692d7f2b302a722d8e3b6a98659bb3b3b9 | eaf4adc1ba2c030783680e63afb70eed970f2c40 | /Lintcode/83_single-number-ii/single-number-ii.cpp | 97630d5397efb92d9a9dcc99aafa326e5efae40b | [] | no_license | lingd3/OJ-CODE | 886770096e70ff873fdd8a2be8ae778073ac5681 | 008b3196c97fe54629e7db45ea6336b243562335 | refs/heads/master | 2021-06-15T18:25:14.690744 | 2019-10-11T12:17:56 | 2019-10-11T12:17:56 | 64,114,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | /*
@Copyright:LintCode
@Author: linqiao
@Problem: http://www.lintcode.com/problem/single-number-ii
@Language: C++
@Datetime: 17-03-13 13:38
*/
class Solution {
public:
/**
* @param A : An integer array
* @return : An integer
*/
int singleNumberII(vector<int> &A) {
// write your code here
int bit[35] = {0};
for (int i = 0; i < A.size(); i++) {
int count = 0, a = A[i];
while (a && count < 32) {
if ((a&1) != 0) {
bit[count]++;
}
a = a >> 1;
count++;
}
}
int num = 0;
for (int i = 0; i < 35; i++) {
bit[i] %= 3;
num += bit[i]*pow(2, i);
}
return num;
}
}; | [
"[email protected]"
] | |
457fc1f2fa1952adde15f25045e568fd2f9073c6 | ecfb350f9fde634ce78da03cf731a4779828aea6 | /C++/Limbaje Formale si Compilatoare/Tema0/ex2/ex2/Source.cpp | 683dc75a66ac83e26d914848ad3d8d0b9fd43b43 | [] | no_license | DogaruAlexandru/School-Projects | be4404baeb16c33804c2893ed284016cbc940bab | b6e59bccc243f164723b423038695e037cfd0bbe | refs/heads/main | 2023-05-25T19:12:13.623527 | 2023-05-18T10:31:45 | 2023-05-18T10:31:45 | 372,527,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 931 | cpp | #include <iostream>
#include <regex>
#include <string>
std::string FindNumberType(const std::string& number)
{
std::regex natural{ R"([0-9]+)" };
std::regex intreg{ R"([-+]?[0-9]+)" };
std::regex real{ R"([-+]?[0-9]+(\.[0-9]+([Ee]-[0-9]+)?)?)" };
if (std::regex_match(number, natural))
return " natural";
if (std::regex_match(number, intreg))
return " intreg";
if (std::regex_match(number, real))
return " real";
return " nu este numar";
}
int main()
{
std::cout << "23" << FindNumberType("23") << '\n';
std::cout << "23.04" << FindNumberType("23.04") << '\n';
std::cout << "-14" << FindNumberType("-14") << '\n';
std::cout << "24.345E-10" << FindNumberType("24.345E-10") << '\n';
std::cout << "2a37" << FindNumberType("2a37") << '\n';
std::cout << "23.4.5" << FindNumberType("23.4.5") << '\n';
std::cout << "34E" << FindNumberType("34E") << '\n';
std::cout << "34-E" << FindNumberType("34-E");
return 0;
} | [
"[email protected]"
] | |
96e19526a2e67dd357688d5da0803338923ae3f1 | 9cc95ed76343c3367827b9fd8b184c7ab288f3eb | /common_src/Socket.cpp | afb3d0e6fe39a2f776b9667c49d6a143c442d867 | [] | no_license | leogm99/tp3 | 4a8c271e8546d459cc6744a3acdff2d057775f31 | ead1693a3989626517b84173699e2cdd20cc6d2b | refs/heads/main | 2023-06-11T15:44:47.426472 | 2021-06-15T16:27:38 | 2021-06-15T16:27:38 | 368,842,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,909 | cpp | #include "Socket.h"
#include <cstring>
#include <iostream>
#include "SocketException.h"
#include "Macros.h"
Socket::Socket()
: fd(-1){
}
Socket::Socket(int fd) {
this->fd = fd;
}
struct addrinfo *Socket::getAddrInfo(const char *host,
const char *service,
int caller_flags) {
struct addrinfo hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = caller_flags;
struct addrinfo *results;
int addrinfo = getaddrinfo(host, service, &hints, &results);
if (addrinfo != 0){
throw SocketException(ADDR_INFO);
}
return results;
}
int Socket::bindAndListen(const char *service) {
struct addrinfo * results;
results = getAddrInfo(nullptr, service, AI_PASSIVE); // server
struct addrinfo * aux = results;
int bind_error = 0;
for (; aux && !bind_error; aux = aux->ai_next){
fd = socket(aux->ai_family,
aux->ai_socktype,
aux->ai_protocol);
// si el fd es invalido, rip
if (fd == -1){
freeaddrinfo(results);
throw SocketException(BIND_ERR, service);
}
if ((bind_error = bind(fd, aux->ai_addr, aux->ai_addrlen)) == 0){
break;
}
// falla bind, cierro el fd
close(fd);
fd = -1;
}
freeaddrinfo(results);
if (bind_error || (fd < 0)){
throw SocketException(BIND_ERR, service);
}
if (listen(fd, 10) == -1){
throw SocketException(BIND_ERR, service);
}
return 0;
}
Socket Socket::accept() {
int peerFd = ::accept(fd, nullptr, nullptr);
if (errno == EINVAL){
throw SocketException(LISTENER_CLOSED);
}
return Socket(peerFd);
}
int Socket::connect(const char *host, const char *service) {
struct addrinfo* results;
results = getAddrInfo(nullptr, service, 0);
struct addrinfo *aux = results;
for (; aux; aux = aux->ai_next){
int connect_error;
fd = socket(aux->ai_family,
aux->ai_socktype,
aux->ai_protocol);
if (fd == -1){
freeaddrinfo(results);
throw SocketException(CONNECT_ERR, service);
}
connect_error = ::connect(fd, aux->ai_addr, aux->ai_addrlen);
if (!connect_error){
freeaddrinfo(results);
return 0;
}
close(fd);
fd = -1;
}
freeaddrinfo(results);
throw SocketException(CONNECT_ERR, service);
}
void Socket::shutdown() {
if (fd > 0) {
::shutdown(fd, SHUT_RDWR);
close(fd);
fd = -1;
}
}
ssize_t Socket::send(const void *buffer, size_t length) {
ssize_t bytes_send = 0;
const char *aux = static_cast<const char *>(buffer);
while ((size_t) bytes_send < length){
ssize_t send_ret = ::send(fd, &aux[bytes_send],
length - bytes_send, MSG_NOSIGNAL);
if (send_ret == -1){
break;
}
bytes_send += send_ret;
}
return bytes_send;
}
ssize_t Socket::receive(void *buffer, size_t length) {
ssize_t bytes_recv = 0;
char *aux = static_cast<char *>(buffer);
while ((size_t) bytes_recv < length){
ssize_t recv_ret = recv(fd, &aux[bytes_recv],
length - bytes_recv, 0);
if (recv_ret == -1 || recv_ret == 0){
break;
}
bytes_recv += recv_ret;
}
return bytes_recv;
}
Socket::~Socket() {
if (fd > 0){
::shutdown(fd, SHUT_RDWR);
close(fd);
}
}
Socket::Socket(Socket &&other) noexcept
: fd(other.fd){
other.fd = -1;
}
Socket &Socket::operator=(Socket &&other) noexcept{
if (this == &other){
return *this;
}
this->fd = other.fd;
other.fd = -1;
return *this;
}
| [
"[email protected]"
] | |
7acb6074e28d5d104766fe5279074a540beed892 | 6d1b830241ec320f3525d9e1e6e29ae29ae2b420 | /src/gfx/ecs/ecs.hpp | fa5f9a9e91cf3fd25691e9699f8c7da9ff77241e | [
"MIT"
] | permissive | johannes-braun/graphics_utilities | acbbd4afc2f6d796d0c172dc78367f5176b843b3 | 191772a3ff1c14eea74b9b5614b6226cf1f8abb7 | refs/heads/master | 2020-03-29T10:20:04.853615 | 2018-10-29T14:19:52 | 2018-10-29T14:19:52 | 149,799,947 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,662 | hpp | #pragma once
#include "entity.hpp"
#include "listener.hpp"
#include "system.hpp"
#include <execution>
#include <unordered_map>
#include <cassert>
namespace gfx {
inline namespace v1 {
namespace ecs {
class ecs
{
friend class entity;
public:
ecs() = default;
ecs(const ecs& other) = default;
ecs(ecs&& other) = default;
ecs& operator=(const ecs& other) = default;
ecs& operator=(ecs&& other) = default;
~ecs();
void add_listener(listener& l);
entity create_entity(const component_base** components, const id_t* component_ids, size_t count);
void delete_entity(entity handle);
template<typename... Components, typename = std::void_t<traits::enable_if_component_t<Components>...>>
entity create_entity(const Components&... components);
unique_entity create_entity_unique(const component_base** components, const id_t* component_ids, size_t count);
template<typename... Components, typename = std::void_t<traits::enable_if_component_t<Components>...>>
unique_entity create_entity_unique(const Components&... components);
template<typename... Component>
void add_components(entity_handle handle, const Component&... component);
template<typename Component, typename... Components>
bool remove_components(entity_handle handle);
template<typename Component>
Component* get_component(entity_handle handle);
component_base* get_component(entity_handle handle, id_t cid);
void update(double delta, system_list& list);
private:
std::unordered_map<id_t, std::vector<std::byte>> _components;
std::vector<indexed_entity*> _entities;
std::vector<listener*> _listeners;
void delete_component(id_t id, size_t index);
bool remove_component_impl(entity_handle e, id_t component_id);
void add_component_impl(entity_handle e, id_t component_id, const component_base* component);
component_base* get_component_impl(entity_handle e, std::vector<std::byte>& carr, id_t component_id);
void update_multi_system(system_base& system, double delta, const std::vector<id_t>& types, std::vector<component_base*>& components,
std::vector<std::vector<std::byte>*>& component_arrays);
static indexed_entity* as_entity_ptr(entity_handle handle);
static uint32_t index_of(entity_handle handle);
static entity_info& as_entity(entity_handle handle);
};
} // namespace ecs
} // namespace v1
} // namespace gfx
#include "ecs.inl" | [
"[email protected]"
] | |
25f768a19ddd76a3f000f60d401ad4e6e0137f13 | 24335be310e2434e8421a53dc26ec669e062a238 | /smpl/include/smpl/ros/planning_space_allocator.h | 1b15c6a8c5a762f286f55c18670076a4c948639d | [] | no_license | amiller27/smpl | 11373ac1f6ab71859d86678017c65fc00a7fb249 | 0960e011d3b255a7a8a94db220c3d8fbd4c90659 | refs/heads/master | 2021-07-12T02:13:12.685699 | 2017-08-23T19:23:06 | 2017-08-23T19:23:06 | 101,213,327 | 0 | 0 | null | 2017-08-23T18:38:14 | 2017-08-23T18:38:14 | null | UTF-8 | C++ | false | false | 2,309 | h | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Andrew Dornbush
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright 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.
////////////////////////////////////////////////////////////////////////////////
/// \author Andrew Dornbush
#ifndef SMPL_PLANNING_SPACE_ALLOCATOR_H
#define SMPL_PLANNING_SPACE_ALLOCATOR_H
#include <smpl/forward.h>
#include <smpl/graph/robot_planning_space.h>
namespace sbpl {
namespace motion {
SBPL_CLASS_FORWARD(PlanningSpaceAllocator);
class PlanningSpaceAllocator
{
public:
virtual ~PlanningSpaceAllocator() { }
virtual RobotPlanningSpacePtr allocate(
RobotModel* robot,
CollisionChecker* checker,
PlanningParams* params) = 0;
};
} // namespace motion
} // namespace sbpl
#endif
| [
"[email protected]"
] | |
258902d07353e78a6255238751b5a5a1e020dd44 | 28cb75c35dfc1391f4cb22e5e729037dab191704 | /sources/libborc/felide/Version.hpp | a0ce5974cb6f8273d4452e5cf06c759ed15b45d0 | [] | no_license | fapablazacl-old/felide.old | eeb9cd9abdebe67e87bc0963619ea1ee2616731f | 2fc7a118b68fb844b97f2e940a803a38bf2dfebb | refs/heads/master | 2021-08-26T06:59:03.461014 | 2017-05-17T17:49:15 | 2017-05-17T17:49:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | hpp |
#pragma once
#ifndef __borc_version_hpp__
#define __borc_version_hpp__
#if defined(major)
#undef major
#endif
#if defined(minor)
#undef minor
#endif
namespace borc {
struct Version {
int major = 0;
int minor = 0;
int build = 0;
Version() {}
Version(int major_, int minor_, int build_=0)
: major(major_), minor(minor_), build(build_) {}
};
extern bool operator< (const Version &v1, const Version &v2);
extern bool operator== (const Version &v1, const Version &v2);
inline bool operator!= (const Version &v1, const Version &v2) {
return !(v1 == v2);
}
}
#endif
| [
"[email protected]"
] | |
2b4d52995a4183f2bb68c5d6c67ba0790684426d | edabddd23276d9a40c7f8bf6d6986fb451adbc34 | /Archive/hihocoder/Offer71/A.cpp | 6043d242bb9201922ee46430e58e03e519ab6b26 | [] | no_license | Akatsukis/ACM_Training | b70f49435b8c7bada6b52366e4a6a8010ff80ef9 | 0503f50bc033ba01c7993de346ac241b0d9d5625 | refs/heads/master | 2021-06-06T09:00:15.665775 | 2019-12-24T20:13:14 | 2019-12-24T20:13:14 | 103,283,338 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 919 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define sc(x) scanf("%d", &x)
#define pb push_back
#define mk make_pair
#define fi first
#define se second
#define ALL(x) x.begin(), x.end()
#define SZ(x) ((int)x.size())
#define sqr(x) ((x)*(x))
#define ABS(x) ((x)>=0?(x):(-(x)))
#define fastio ios::sync_with_stdio(0),cin.tie(0)
template<class T>T gcd(T a, T b){return b?gcd(b, a%b):a;}
int main()
{
int n, k;
sc(n); sc(k);
int ans1 = 0, ans2 = 0;
set<int> mp;
bool flg = 0;
for(int i = 0; i < n; i++){
int x; sc(x);
if(x%k == 0)ans1++;
else if(k%2 == 0 && x%k == k/2)ans2++;
if(mp.count(k-x%k))flg = 1;
mp.insert(x%k);
}
if(max(ans1, ans2) <= 1){
if(!flg)puts("-1");
else puts("2");
}
else printf("%d\n", max(ans1, ans2));
return 0;
}
| [
"[email protected]"
] | |
d0bdd7732d795f936c654433d9a09ca3343b4c5c | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /gpu/command_buffer/client/mapped_memory.h | c23e60259d3fd9b0dcc305e7ec77d6a4c9ce658e | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 8,185 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GPU_COMMAND_BUFFER_CLIENT_MAPPED_MEMORY_H_
#define GPU_COMMAND_BUFFER_CLIENT_MAPPED_MEMORY_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/bind.h"
#include "base/macros.h"
#include "base/trace_event/memory_dump_provider.h"
#include "gpu/command_buffer/client/fenced_allocator.h"
#include "gpu/command_buffer/common/buffer.h"
#include "gpu/gpu_export.h"
namespace gpu {
class CommandBufferHelper;
// Manages a shared memory segment.
class GPU_EXPORT MemoryChunk {
public:
MemoryChunk(int32_t shm_id,
scoped_refptr<gpu::Buffer> shm,
CommandBufferHelper* helper);
~MemoryChunk();
// Gets the size of the largest free block that is available without waiting.
unsigned int GetLargestFreeSizeWithoutWaiting() {
return allocator_.GetLargestFreeSize();
}
// Gets the size of the largest free block that can be allocated if the
// caller can wait.
unsigned int GetLargestFreeSizeWithWaiting() {
return allocator_.GetLargestFreeOrPendingSize();
}
// Gets the size of the chunk.
unsigned int GetSize() const {
return static_cast<unsigned int>(shm_->size());
}
// The shared memory id for this chunk.
int32_t shm_id() const {
return shm_id_;
}
gpu::Buffer* shared_memory() const { return shm_.get(); }
// Allocates a block of memory. If the buffer is out of directly available
// memory, this function may wait until memory that was freed "pending a
// token" can be re-used.
//
// Parameters:
// size: the size of the memory block to allocate.
//
// Returns:
// the pointer to the allocated memory block, or NULL if out of
// memory.
void* Alloc(unsigned int size) {
return allocator_.Alloc(size);
}
// Gets the offset to a memory block given the base memory and the address.
// It translates NULL to FencedAllocator::kInvalidOffset.
unsigned int GetOffset(void* pointer) {
return allocator_.GetOffset(pointer);
}
// Frees a block of memory.
//
// Parameters:
// pointer: the pointer to the memory block to free.
void Free(void* pointer) {
allocator_.Free(pointer);
}
// Frees a block of memory, pending the passage of a token. That memory won't
// be re-allocated until the token has passed through the command stream.
//
// Parameters:
// pointer: the pointer to the memory block to free.
// token: the token value to wait for before re-using the memory.
void FreePendingToken(void* pointer, unsigned int token) {
allocator_.FreePendingToken(pointer, token);
}
// Frees any blocks whose tokens have passed.
void FreeUnused() {
allocator_.FreeUnused();
}
// Gets the free size of the chunk.
unsigned int GetFreeSize() { return allocator_.GetFreeSize(); }
// Returns true if pointer is in the range of this block.
bool IsInChunk(void* pointer) const {
return pointer >= shm_->memory() &&
pointer <
reinterpret_cast<const int8_t*>(shm_->memory()) + shm_->size();
}
// Returns true of any memory in this chunk is in use or free pending token.
bool InUseOrFreePending() { return allocator_.InUseOrFreePending(); }
size_t bytes_in_use() const {
return allocator_.bytes_in_use();
}
FencedAllocator::State GetPointerStatusForTest(void* pointer,
int32_t* token_if_pending) {
return allocator_.GetPointerStatusForTest(pointer, token_if_pending);
}
private:
int32_t shm_id_;
scoped_refptr<gpu::Buffer> shm_;
FencedAllocatorWrapper allocator_;
DISALLOW_COPY_AND_ASSIGN(MemoryChunk);
};
// Manages MemoryChunks.
class GPU_EXPORT MappedMemoryManager {
public:
enum MemoryLimit {
kNoLimit = 0,
};
// |unused_memory_reclaim_limit|: When exceeded this causes pending memory
// to be reclaimed before allocating more memory.
MappedMemoryManager(CommandBufferHelper* helper,
size_t unused_memory_reclaim_limit);
~MappedMemoryManager();
unsigned int chunk_size_multiple() const {
return chunk_size_multiple_;
}
void set_chunk_size_multiple(unsigned int multiple) {
DCHECK(multiple % FencedAllocator::kAllocAlignment == 0);
chunk_size_multiple_ = multiple;
}
size_t max_allocated_bytes() const {
return max_allocated_bytes_;
}
void set_max_allocated_bytes(size_t max_allocated_bytes) {
max_allocated_bytes_ = max_allocated_bytes;
}
// Allocates a block of memory
// Parameters:
// size: size of memory to allocate.
// shm_id: pointer to variable to receive the shared memory id.
// shm_offset: pointer to variable to receive the shared memory offset.
// Returns:
// pointer to allocated block of memory. NULL if failure.
void* Alloc(
unsigned int size, int32_t* shm_id, unsigned int* shm_offset);
// Frees a block of memory.
//
// Parameters:
// pointer: the pointer to the memory block to free.
void Free(void* pointer);
// Frees a block of memory, pending the passage of a token. That memory won't
// be re-allocated until the token has passed through the command stream.
//
// Parameters:
// pointer: the pointer to the memory block to free.
// token: the token value to wait for before re-using the memory.
void FreePendingToken(void* pointer, int32_t token);
// Free Any Shared memory that is not in use.
void FreeUnused();
// Dump memory usage - called from GLES2Implementation.
bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd);
// Used for testing
size_t num_chunks() const {
return chunks_.size();
}
size_t bytes_in_use() const {
size_t bytes_in_use = 0;
for (size_t ii = 0; ii < chunks_.size(); ++ii) {
bytes_in_use += chunks_[ii]->bytes_in_use();
}
return bytes_in_use;
}
// Used for testing
size_t allocated_memory() const {
return allocated_memory_;
}
// Gets the status of a previous allocation, as well as the corresponding
// token if FREE_PENDING_TOKEN (and token_if_pending is not null).
FencedAllocator::State GetPointerStatusForTest(void* pointer,
int32_t* token_if_pending);
private:
typedef std::vector<std::unique_ptr<MemoryChunk>> MemoryChunkVector;
// size a chunk is rounded up to.
unsigned int chunk_size_multiple_;
CommandBufferHelper* helper_;
MemoryChunkVector chunks_;
size_t allocated_memory_;
size_t max_free_bytes_;
size_t max_allocated_bytes_;
// A process-unique ID used for disambiguating memory dumps from different
// mapped memory manager.
int tracing_id_;
DISALLOW_COPY_AND_ASSIGN(MappedMemoryManager);
};
// A class that will manage the lifetime of a mapped memory allocation
class GPU_EXPORT ScopedMappedMemoryPtr {
public:
ScopedMappedMemoryPtr(
uint32_t size,
CommandBufferHelper* helper,
MappedMemoryManager* mapped_memory_manager)
: buffer_(NULL),
size_(0),
shm_id_(0),
shm_offset_(0),
flush_after_release_(false),
helper_(helper),
mapped_memory_manager_(mapped_memory_manager) {
Reset(size);
}
~ScopedMappedMemoryPtr() {
Release();
}
bool valid() const {
return buffer_ != NULL;
}
void SetFlushAfterRelease(bool flush_after_release) {
flush_after_release_ = flush_after_release;
}
uint32_t size() const {
return size_;
}
int32_t shm_id() const {
return shm_id_;
}
uint32_t offset() const {
return shm_offset_;
}
void* address() const {
return buffer_;
}
void Release();
void Reset(uint32_t new_size);
private:
void* buffer_;
uint32_t size_;
int32_t shm_id_;
uint32_t shm_offset_;
bool flush_after_release_;
CommandBufferHelper* helper_;
MappedMemoryManager* mapped_memory_manager_;
DISALLOW_COPY_AND_ASSIGN(ScopedMappedMemoryPtr);
};
} // namespace gpu
#endif // GPU_COMMAND_BUFFER_CLIENT_MAPPED_MEMORY_H_
| [
"[email protected]"
] | |
0f649784dd4da6d8a4807c6dcbdd6852cdb9254b | da22ec31ada0c2dfc7fd40dc64fe533750b4ce9a | /Server/BusinessModules/OutputSTDOUTModule.hpp | 5f285452122443db773282835c2a0111a8d23d8a | [] | no_license | aguadoenzo/Spider | b660e2e12ac6f0afd48cc7dda092f29b3f54b7b5 | 366e0af524b488aa208c66ad6218b9455ac197a5 | refs/heads/master | 2021-01-12T00:49:29.069085 | 2016-11-17T11:16:36 | 2016-11-17T11:16:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,756 | hpp | //
// Created by hippolyteb on 11/8/16.
//
#ifndef SPIDER_SERVER_OUTPUTSTDINMODULE_HPP
#define SPIDER_SERVER_OUTPUTSTDINMODULE_HPP
#include <bits/unique_ptr.h>
#include <iostream>
#include "../Interfaces/ISpiderBusinessModule.hpp"
#include "../Interfaces/Event/ISpiderEventListener.hpp"
#include "../SpiderEventManager/SpiderEventListener.hpp"
#include "../SpiderEventManager/SpiderEventEmitter.hpp"
#include "../ProtoEnvelopes/Proto/SpiderKeyloggingPayload.pb.h"
#include "../ProtoEnvelopes/Proto/test.pb.h"
#include "../ProtoEnvelopes/Proto/SpiderMouseEvent.pb.h"
class OutputSTDOUTModule : public ISpiderBusinessModule {
std::unique_ptr<ISpiderEventListener<SpiderKeyLoggingPayload>> _eventKeylogListener = std::unique_ptr<ISpiderEventListener<SpiderKeyLoggingPayload>>(new SpiderEventListener<SpiderKeyLoggingPayload>());
std::unique_ptr<ISpiderEventListener<SpiderMouseEvent>> _eventMouseListener = std::unique_ptr<ISpiderEventListener<SpiderMouseEvent>>(new SpiderEventListener<SpiderMouseEvent>());
std::unique_ptr<ISpiderEventListener<testPayload>> _eventTestListener = std::unique_ptr<ISpiderEventListener<testPayload>>(new SpiderEventListener<testPayload>());
std::unique_ptr<ISpiderEventEmitter> _eventEmitter = std::unique_ptr<ISpiderEventEmitter>(new SpiderEventEmitter());
private:
public:
OutputSTDOUTModule() {
_eventKeylogListener->Register("SpiderKeyLoggingPayload", [&](std::string clientId, SpiderKeyLoggingPayload &payload) {
std::cout << "[Keylogging from client with ID " << clientId << "]" << std::endl;
if (payload.context().processname() != "" && payload.context().windowsname() != "")
std::cout << "From context : [Process : " << payload.context().processname() << "; Windows : " << payload.context().windowsname() <<"]" << std::endl;
if (payload.plaintextkeylog() != "")
std::cout << "==> " << payload.plaintextkeylog() << std::endl;
std::cout << "---------------------------------------------------" << std::endl;
});
_eventMouseListener->Register("SpiderMouseEvent", [&](std::string clientId, SpiderMouseEvent &payload) {
std::cout << "[Mouse activity from client with ID " << clientId << "]" << std::endl;
std::cout << "[TYPE : " << payload.type() << "] " << "X : " << payload.x() << " Y : " << payload.y() << std::endl;
std::cout << "---------------------------------------------------" << std::endl;
});
_eventTestListener->Register("testPayload", [&](std::string clientId, testPayload &payload){
std::cout << "testPayload : " << payload.content() << std::endl;
});
}
};
#endif //SPIDER_SERVER_OUTPUTSTDINMODULE_HPP
| [
"[email protected]"
] | |
eee1a7edffff5cdb0f5e7f21127f80852831668c | 537c37371d18dd98a97e8754adfb54304ae61355 | /BoBoDing/DlgDesktopSearch.h | 2ab016969d12b383e081632328df634d48ea6a7c | [] | no_license | boboding/Boboding | 25aabc86962e4540a053fe5fe64c8de9d3b7c1a4 | 6add79208a64bc364e145c5289ea2600b946d8b3 | refs/heads/master | 2021-01-10T14:16:14.363221 | 2015-10-12T06:03:58 | 2015-10-12T06:03:58 | 44,077,921 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,430 | h | #pragma once
#include "button\xskinbutton.h"
#include "afxwin.h"
// CDlgDesktopSearch 对话框
class CDlgDesktopSearch : public CDialogEx
{
DECLARE_DYNAMIC(CDlgDesktopSearch)
public:
CDlgDesktopSearch(CWnd* pParent = NULL); // 标准构造函数
virtual ~CDlgDesktopSearch();
// 对话框数据
enum { IDD = IDD_DIALOG_DESKTOPSEARCH };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
// afx_msg void OnBnClickedButtonMin();
//CxSkinButton m_Button_ctlMin;
afx_msg void OnBnClickedButtonSearch();
CEdit m_Edit_ctlSearch;
CButton m_Check_ctlButton;
CButton m_Check_ctlBaiDu;
afx_msg void OnBnClickedCheckGoogle();
BOOL m_Check_bGoogle;
CString GetIniPath();
BOOL m_Check_bBaiDu;
BOOL m_Check_bSouGou;
BOOL m_Check_bYouDao;
//BOOL m_Check_bWebsite;
//BOOL m_Check_bStart;
afx_msg void OnBnClickedCheckBaidu();
afx_msg void OnBnClickedCheckSougou();
afx_msg void OnBnClickedCheckYoudao();
//afx_msg void OnBnClickedCheckWebsite();
//afx_msg void OnBnClickedCheckStart();
CString FormatOutput(char* szIn);
CString URLEncode(LPCTSTR url);
BYTE toHex(const BYTE &x);
CString m_Edit_strSearch;
//CComboBox m_Combo_ctlSearch;
//CString m_Combo_strSearch;
CFont m_Font;
virtual BOOL PreTranslateMessage(MSG* pMsg);
};
| [
"[email protected]"
] | |
3f29a028abf4c699b7eff9777416af329ea7b73e | 792e697ba0f9c11ef10b7de81edb1161a5580cfb | /tools/clang/test/SemaCXX/warn-unused-but-set-variables-cpp.cpp | 400e9d7681b3103b42175fcf85249707e0ad45b0 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | opencor/llvmclang | 9eb76cb6529b6a3aab2e6cd266ef9751b644f753 | 63b45a7928f2a8ff823db51648102ea4822b74a6 | refs/heads/master | 2023-08-26T04:52:56.472505 | 2022-11-02T04:35:46 | 2022-11-03T03:55:06 | 115,094,625 | 0 | 1 | Apache-2.0 | 2021-08-12T22:29:21 | 2017-12-22T08:29:14 | LLVM | UTF-8 | C++ | false | false | 1,192 | cpp | // RUN: %clang_cc1 -fblocks -fsyntax-only -Wunused-but-set-variable -verify %s
struct S {
int i;
};
struct __attribute__((warn_unused)) SWarnUnused {
int j;
void operator +=(int);
};
int f0() {
int y; // expected-warning{{variable 'y' set but not used}}
y = 0;
int z __attribute__((unused));
z = 0;
// In C++, don't warn for structs. (following gcc's behavior)
struct S s;
struct S t;
s = t;
// Unless it's marked with the warn_unused attribute.
struct SWarnUnused swu; // expected-warning{{variable 'swu' set but not used}}
struct SWarnUnused swu2;
swu = swu2;
int x;
x = 0;
return x + 5;
}
void f1(void) {
(void)^() {
int y; // expected-warning{{variable 'y' set but not used}}
y = 0;
int x;
x = 0;
return x;
};
}
void f2() {
// Don't warn for either of these cases.
constexpr int x = 2;
const int y = 1;
char a[x];
char b[y];
}
void f3(int n) {
// Don't warn for overloaded compound assignment operators.
SWarnUnused swu;
swu += n;
}
template<typename T> void f4(T n) {
// Don't warn for (potentially) overloaded compound assignment operators in
// template code.
SWarnUnused swu;
swu += n;
}
| [
"[email protected]"
] | |
cd64e158556cba9466a5822751047a2000d0db40 | 447be6d71898f33ebbf3b71db8c4fdaaf670bc0b | /source/application/view/SunNode3D.h | 3f235c659f7cf123aa43334ba6b1fedd9c7a285b | [] | no_license | CST-Modelling-Tools/TonatiuhPP | 35bc1b6f4067364875471a5be99053df01df5883 | 664250e8ef38e7d6dab3ed35d6fab7f732edec19 | refs/heads/master | 2023-04-13T03:12:14.843634 | 2022-08-26T12:09:02 | 2022-08-26T12:09:02 | 380,948,961 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 478 | h | #pragma once
#include "kernel/scene/GridNode.h"
#include <Inventor/nodes/SoSeparator.h>
class SoSensor;
class SoNodeSensor;
class SunPosition;
class SoTransform;
class SunNode3D: public SoSeparator
{
public:
SunNode3D();
~SunNode3D();
void attach(SunPosition* sp);
void create();
SoTransform* getTransform() {return m_transform;}
protected:
SoTransform* m_transform;
SoNodeSensor* m_sensor;
static void update(void* data, SoSensor*);
};
| [
"[email protected]"
] | |
9dfcfbe3041c1e0c4c5b4608bddcbc60489f1786 | 573ec7174c611055faa025e0a8dc82d47ae489a6 | /NFAggregator/main.cpp | 429538cb96afe8c7658d2339b0a043e57a9012ff | [] | no_license | Olernov/netflow | d83902a98b0cf6d3e5d77f1476e366aa07c9f2a3 | 27d25c8690b7070ee04c8f58f72885b46666cfba | refs/heads/master | 2021-08-11T11:10:34.645679 | 2017-11-10T16:26:29 | 2017-11-10T16:26:29 | 104,724,756 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,104 | cpp | #include <iostream>
#include <cassert>
#include <signal.h>
#include "OTL_Header.h"
#include "DBConnect.h"
#include "otl_utils.h"
#include "Session.h"
#include "Common.h"
#include "MainLoopController.h"
#include "LogWriterOtl.h"
#include "Config.h"
#include "AlertSender.h"
Config config;
LogWriterOtl logWriter;
AlertSender alertSender("Netflow aggregator");
MainLoopController* mainLoopCtrl = nullptr;
void printUsage()
{
std::cerr << "IRBiS netflow aggregator. (c) Tenet Ltd. 2017" << std::endl
<< "Usage: " << std::endl << "nf-aggregator <config-file> [-test|-detail]" << std::endl
<< " -test runs unit tests and exits" << std::endl
<< " -detail runs detailed export of netflow data with no aggregation" << std::endl;
}
void SignalHandler(int signum, siginfo_t *info, void *ptr)
{
std::cout << "Received signal #" <<signum << " from process #" << info->si_pid << ". Stopping ..." << std::endl;
mainLoopCtrl->Stop();
}
int main(int argc, const char* argv[])
{
if (argc < 2) {
printUsage();
exit(EXIT_FAILURE);
}
const char* confFilename = argv[1];
bool runTests = false;
if (argc > 2 && !strncasecmp(argv[2], "-test", 5)) {
runTests = true;
}
if (argc > 2 && !strncasecmp(argv[2], "-detail", 7)) {
config.detailedExport = true;
}
std::ifstream confFile(confFilename, std::ifstream::in);
if (!confFile.is_open()) {
std::cerr << "Unable to open config file " << confFilename << std::endl;
exit(EXIT_FAILURE);
}
try {
config.ReadConfigFile(confFile);
config.ValidateParams();
}
catch(const std::exception& ex) {
std::cerr << "Error when parsing config file " << confFilename << std::endl;
std::cerr << ex.what() <<std::endl;
exit(EXIT_FAILURE);
}
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_sigaction = SignalHandler;
act.sa_flags = SA_SIGINFO;
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
size_t processIndex = 0;
// fork new process for every input directory
while (++processIndex <= config.inputDirs.size()) {
if (processIndex == config.inputDirs.size()) {
// stop forking
processIndex = 0;
break;
}
pid_t pid = fork();
if (pid < 0) {
std::cerr << "Unable to fork. Error code " << errno << std::endl;
exit(EXIT_FAILURE);
}
if (pid > 0) {
// we are in child process
break;
}
}
const std::string pidFilename = "/var/run/nf-aggregator" + std::to_string(processIndex) + ".pid";
std::ofstream pidFile(pidFilename, std::ofstream::out);
if (pidFile.is_open()) {
pidFile << getpid();
}
pidFile.close();
logWriter.Initialize(config.logDirs[processIndex], "nf", config.logLevel);
const int OTL_MULTITHREADED_MODE = 1;
otl_connect::otl_initialize(OTL_MULTITHREADED_MODE);
try {
alertSender.Initialize(config.connectString);
if (runTests) {
std::cout << "Running tests ..." << std::endl;
BillingInfo testBI(config.connectString);
testBI.RunTests();
std::cout << "Tests PASSED" << std::endl;
exit(EXIT_SUCCESS);
}
logWriter << "Netflow aggregator started";
logWriter << config.DumpAllSettings();
std::cout << "Netflow aggregator started" << std::endl;
mainLoopCtrl = new MainLoopController(config, processIndex);
mainLoopCtrl->Run();
}
catch(otl_exception& ex) {
std::string errMessage = OTL_Utils::OtlExceptionToText(ex);
std::cerr << errMessage << std::endl;
logWriter.Write(errMessage, mainThreadIndex, error);
}
catch(std::exception& ex) {
std::cerr << ex.what() << std::endl;
logWriter.Write(ex.what(), mainThreadIndex, error);
}
delete mainLoopCtrl;
logWriter << "Netflow aggregator shutdown";
remove(pidFilename.c_str());
return 0;
}
| [
"[email protected]"
] | |
cd0855492b424ba85e3498af1f3af872927790c4 | 99d0ed43da8afba70474d785779d09c1cb668443 | /Player.h | f52bb3236111afb37d4138b5308d1814d0051079 | [] | no_license | klyhthwy/Yahtzee | 48f05a5066d24e15ca6ec149edfeda019a821f98 | c3cc0f20e96eef50c93533650fca516cac265528 | refs/heads/master | 2021-01-13T01:41:36.509574 | 2018-02-28T20:23:36 | 2018-02-28T20:23:36 | 35,844,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | h | #ifndef _PLAYER_H_
#define _PLAYER_H_
#include "Yahtzee.h"
#include "Score.h"
#include <iostream>
class Player
{
public:
enum Contants
{
CHANCE = 0,
ACE = 1,
THREE_KIND = 7,
FOUR_KIND = 8,
FULL_HOUSE = 9,
SM_STRAIGHT = 10,
LG_STRAIGHT = 11,
YAHTZEE = 12,
NUM_SCORES = 13,
NAME_SIZE = 25
};
Player(char *);
virtual ~Player();
virtual void turn(Yahtzee &) = 0;
int score() const;
bool done() const;
const char *name() const;
void display(std::ostream &) const;
protected:
Player(const Player &);
Player &operator=(const Player &);
bool set_score(const Yahtzee &, char);
bool set_score(Score &, int);
bool invalid() const;
int upper() const;
int bonus() const;
int lower() const;
char *copy_name(char *) const;
void upper(std::ostream &) const;
void lower(std::ostream &) const;
char *name_;
Score scores_[NUM_SCORES];
int yahtzee_bonuses_;
};
std::ostream &operator<<(std::ostream &, Player *);
#endif | [
"[email protected]"
] | |
f1077832c571d44d5cc2ea6d30f93a6d3a2f3f18 | fdb9b553a23647f7ea06f690613707c40b54902f | /src/main/resources/resource/Arduino/MrlComm/MrlComm.h | fc99e0fbd5c7ebe32927558ab4469811f05fb4e1 | [
"Apache-2.0",
"CC-BY-2.5"
] | permissive | ShaunHolt/myrobotlab | d8d9f94e90457474cf363d36f4a45d396cfae900 | 92046d77abd560f0203050b3cccb21aa9df467f2 | refs/heads/develop | 2021-07-08T04:55:01.462116 | 2020-04-18T19:58:17 | 2020-04-18T19:58:17 | 122,795,957 | 0 | 0 | Apache-2.0 | 2020-04-18T19:58:18 | 2018-02-25T01:37:54 | Java | UTF-8 | C++ | false | false | 6,465 | h | #ifndef MrlComm_h
#define MrlComm_h
#include "ArduinoMsgCodec.h"
#include "MrlSerialRelay.h"
#if defined(ESP8266)
#include <WebSocketsServer.h>
extern "C"
{
#include "user_interface.h"
}
#endif
// forward defines to break circular dependency
class Device;
class Msg;
class MrlComm;
class Pin;
/***********************************************************************
* Class MrlComm - This class represents the Arduino service as a device. It
* can hosts devices such as Motors, Servos, Steppers, Sensors, etc. You can
* dynamically add or remove devices, and the deviceList should be in synch
* with the Java-Land deviceList. It has a list of pins which can be read from
* or written to. It also follows some of the same methods as the Device in
* Device.h It has an update() which is called each loop to do any necessary
* processing
*
*/
class MrlComm
{
private:
/**
* "global var"
*/
// The mighty device List. This contains all active devices that are attached
// to the arduino.
LinkedList<Device *> deviceList;
// list of pins currently being read from - can contain both digital and
// analog
LinkedList<Pin *> pinList;
unsigned char *config;
// performance metrics and load timing
// global debug setting, if set to true publishDebug will write to the serial port.
int byteCount;
int msgSize;
// last time board info was published
long lastBoardInfoUs;
// FIXME - DEPRECATE
boolean boardStatusEnabled;
// sends a series of get publishBoardInfo() back to the arduino every second
boolean boardInfoEnabled = true;
unsigned long lastBoardInfoTs = 0;
unsigned long lastHeartbeatUpdate;
byte customMsgBuffer[MAX_MSG_SIZE];
int customMsgSize;
// handles all messages to and from pc
Msg *msg;
bool heartbeatEnabled;
public:
// utility methods
int getFreeRam();
Device *getDevice(int id);
Msg *getMsg();
bool ackEnabled = true;
Device *addDevice(Device *device);
void update();
// Below are generated callbacks controlled by
// arduinoMsgs.schema
// <generatedCallBacks>
// > getBoardInfo
void getBoardInfo();
// > enablePin/address/type/b16 rate
void enablePin( byte address, byte type, int rate);
// > setDebug/bool enabled
void setDebug( boolean enabled);
// > setSerialRate/b32 rate
void setSerialRate( long rate);
// > softReset
void softReset();
// > enableAck/bool enabled
void enableAck( boolean enabled);
// > echo/f32 myFloat/myByte/f32 secondFloat
void echo( float myFloat, byte myByte, float secondFloat);
// > customMsg/[] msg
void customMsg( byte msgSize, const byte*msg);
// > deviceDetach/deviceId
void deviceDetach( byte deviceId);
// > i2cBusAttach/deviceId/i2cBus
void i2cBusAttach( byte deviceId, byte i2cBus);
// > i2cRead/deviceId/deviceAddress/size
void i2cRead( byte deviceId, byte deviceAddress, byte size);
// > i2cWrite/deviceId/deviceAddress/[] data
void i2cWrite( byte deviceId, byte deviceAddress, byte dataSize, const byte*data);
// > i2cWriteRead/deviceId/deviceAddress/readSize/writeValue
void i2cWriteRead( byte deviceId, byte deviceAddress, byte readSize, byte writeValue);
// > neoPixelAttach/deviceId/pin/b32 numPixels
void neoPixelAttach( byte deviceId, byte pin, long numPixels);
// > neoPixelSetAnimation/deviceId/animation/red/green/blue/b16 speed
void neoPixelSetAnimation( byte deviceId, byte animation, byte red, byte green, byte blue, int speed);
// > neoPixelWriteMatrix/deviceId/[] buffer
void neoPixelWriteMatrix( byte deviceId, byte bufferSize, const byte*buffer);
// > disablePin/pin
void disablePin( byte pin);
// > disablePins
void disablePins();
// > setTrigger/pin/triggerValue
void setTrigger( byte pin, byte triggerValue);
// > setDebounce/pin/delay
void setDebounce( byte pin, byte delay);
// > servoAttach/deviceId/pin/b16 initPos/b16 initVelocity/str name
void servoAttach( byte deviceId, byte pin, int initPos, int initVelocity, byte nameSize, const char*name);
// > servoAttachPin/deviceId/pin
void servoAttachPin( byte deviceId, byte pin);
// > servoDetachPin/deviceId
void servoDetachPin( byte deviceId);
// > servoSetVelocity/deviceId/b16 velocity
void servoSetVelocity( byte deviceId, int velocity);
// > servoSweepStart/deviceId/min/max/step
void servoSweepStart( byte deviceId, byte min, byte max, byte step);
// > servoSweepStop/deviceId
void servoSweepStop( byte deviceId);
// > servoMoveToMicroseconds/deviceId/b16 target
void servoMoveToMicroseconds( byte deviceId, int target);
// > servoSetAcceleration/deviceId/b16 acceleration
void servoSetAcceleration( byte deviceId, int acceleration);
// > serialAttach/deviceId/relayPin
void serialAttach( byte deviceId, byte relayPin);
// > serialRelay/deviceId/[] data
void serialRelay( byte deviceId, byte dataSize, const byte*data);
// > ultrasonicSensorAttach/deviceId/triggerPin/echoPin
void ultrasonicSensorAttach( byte deviceId, byte triggerPin, byte echoPin);
// > ultrasonicSensorStartRanging/deviceId
void ultrasonicSensorStartRanging( byte deviceId);
// > ultrasonicSensorStopRanging/deviceId
void ultrasonicSensorStopRanging( byte deviceId);
// > setAref/b16 type
void setAref( int type);
// > motorAttach/deviceId/type/[] pins
void motorAttach( byte deviceId, byte type, byte pinsSize, const byte*pins);
// > motorMove/deviceId/pwr
void motorMove( byte deviceId, byte pwr);
// > motorMoveTo/deviceId/pos
void motorMoveTo( byte deviceId, byte pos);
// > encoderAttach/deviceId/type/pin
void encoderAttach( byte deviceId, byte type, byte pin);
// > setZeroPoint/deviceId
void setZeroPoint( byte deviceId);
// > servoStop/deviceId
void servoStop( byte deviceId);
// </generatedCallBacks>
// end
public:
unsigned long loopCount; // main loop count
MrlComm();
~MrlComm();
void publishBoardStatus();
void publishVersion();
void publishBoardInfo();
void processCommand();
void processCommand(int ioType);
void updateDevices();
unsigned int getCustomMsg();
int getCustomMsgSize();
void begin(HardwareSerial &serial);
bool readMsg();
void onDisconnect();
void sendCustomMsg(const byte *msg, byte size);
#if defined(ESP8266)
void begin(WebSocketsServer &wsServer);
void webSocketEvent(unsigned char num, WStype_t type, unsigned char *payload, unsigned int lenght);
#endif
};
#endif
| [
"[email protected]"
] | |
7cf0a0108cb83e2cde53fa4165019aa604550edc | ba6ef4e867d6b611b0058fc8d33a72ca6074e02a | /tools/camprocess.cpp | 663d6eef90bfbbc922fbd04a19b5a97944d5677e | [] | no_license | Proxmiff/XaraVG-lib | 3d3f8c9d8176678a887672ab251b593e3913988c | 8fd443b42c94c9fce26e4e4337dec4647756c530 | refs/heads/master | 2021-01-11T13:33:51.866796 | 2016-05-14T14:48:36 | 2016-05-14T14:48:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,228 | cpp |
// The module that controls the OIL side of import/export filters.
#include "camtypes.h"
#include "camprocess.h"
CamProcess::CamProcess(CCLexFile* pInFile, CCLexFile* pOutFile)
{
m_bDead = true;
m_ReturnCode = -1;
m_pInFile = pInFile;
m_pOutFile = pOutFile;
m_BytesIn = 0;
m_BytesOut = 0;
}
CamProcess::~CamProcess()
{
if (!m_bDead)
{
TRACEUSER("Gerry", _T("Process not dead in ~CamProcess"));
}
}
INT32 CamProcess::Execute(const wxString& cmd)
{
// We're now running
m_bDead = false;
// Make sure redirection happens
Redirect();
long pid = wxExecute(cmd, wxEXEC_ASYNC, this);
if (pid == 0)
{
// Report problem
m_bDead = true;
return 123;
}
BYTE ReadBuffer[4096];
size_t ReadBytes = 0;
BYTE* ReadPtr = NULL;
bool bMoreInput = true;
size_t InFileLeft = 0;
if (m_pInFile)
{
InFileLeft = m_pInFile->Size();
// TRACEUSER("Gerry", _T("InFileSize = %d"), InFileLeft);
}
// Loop until m_bDead is true
while (!m_bDead)
{
// Call the virtual function to process any output on stderr
ProcessStdErr();
wxYield();
// If we have an output file
if (m_pOutFile)
{
// If there is output from the process
if (!m_bDead && IsInputAvailable())
{
// Copy the data to the file
size_t NumRead = 4096;
BYTE Buffer[4096];
// Read a buffer full
GetInputStream()->Read(Buffer, 4096);
NumRead = GetInputStream()->LastRead();
// Write the buffer to the file
if (NumRead > 0)
{
// TRACEUSER("Gerry", _T("Writing %d bytes of stdout"), NumRead);
m_pOutFile->write(Buffer, NumRead);
}
}
}
else
{
// Call the virtual function to process the output
if (!m_bDead)
ProcessStdOut();
}
wxYield();
// If we have an input file
if (m_pInFile)
{
// Copy some data to the process
// This was a while loop
if (!m_bDead && bMoreInput)
{
// If there is nothing in the buffer
if (ReadBytes == 0)
{
ReadBytes = 4096;
if (ReadBytes > InFileLeft)
ReadBytes = InFileLeft;
if (ReadBytes > 0)
{
// Read a buffer full
// TRACEUSER("Gerry", _T("Reading %d"), ReadBytes);
m_pInFile->read(ReadBuffer, ReadBytes);
InFileLeft -= ReadBytes;
ReadPtr = ReadBuffer;
}
}
// If there is something in the buffer
if (ReadBytes > 0 && GetOutputStream()->IsOk())
{
// TRACEUSER("Gerry", _T("Buffer contains %d"), ReadBytes);
// Try to write it to the process
GetOutputStream()->Write(ReadPtr, ReadBytes);
size_t Done = GetOutputStream()->LastWrite();
// TRACEUSER("Gerry", _T("Written %d"), Done);
// If we couldn't write it all
if (Done < ReadBytes)
{
// Update the buffer pointer
ReadPtr += Done;
}
// This is correct for all, part or none written
ReadBytes -= Done;
}
else
{
// Indicate there is no more stdin
// TRACEUSER("Gerry", _T("Buffer is empty - closing"));
CloseOutput();
bMoreInput = false;
}
}
}
else
{
// Call the virtual function to process the input
if (!m_bDead)
ProcessStdIn();
}
wxYield();
}
// TRACEUSER("Gerry", _T("Exiting with %d"), m_ReturnCode);
return m_ReturnCode;
}
void CamProcess::ProcessStdIn()
{
// Do nothing in here
}
void CamProcess::ProcessStdOut()
{
if (IsInputAvailable())
{
wxTextInputStream tis(*GetInputStream());
// This assumes that the output is always line buffered
while (IsInputAvailable())
{
wxString line;
line << tis.ReadLine();
// TRACEUSER("Gerry", _T("(stdout):%s"), line.c_str());
}
}
}
void CamProcess::ProcessStdErr()
{
if (IsErrorAvailable())
{
wxTextInputStream tis(*GetErrorStream());
// This assumes that the output is always line buffered
while (IsErrorAvailable())
{
wxString line;
line << tis.ReadLine();
// TRACEUSER("Gerry", _T("(stderr):%s"), line.c_str());
}
}
}
void CamProcess::OnTerminate(int /*TYPENOTE: Correct*/ pid, int /*TYPENOTE: Correct*/ status)
{
// TRACEUSER("Gerry", _T("CamProcess::OnTerminate pid = %d status = %d"), pid, status);
m_bDead = true;
m_ReturnCode = status;
// Process anything remaining on stderr and stdout
// If we have an output file
if (m_pOutFile)
{
// If there is output from the process
if (IsInputAvailable())
{
// Copy the data to the file
size_t NumRead = 4096;
BYTE Buffer[4096];
while (NumRead > 0)
{
// Read a buffer full
GetInputStream()->Read(Buffer, 4096);
NumRead = GetInputStream()->LastRead();
// Write the buffer to the file
if (NumRead > 0)
{
m_pOutFile->write(Buffer, NumRead);
}
}
}
}
else
{
// Call the virtual function to process the output
ProcessStdOut();
}
ProcessStdErr();
}
/*****************************************************************************************
class CamLaunchProcess implementation
*****************************************************************************************/
/********************************************************************************************
> CamLaunchProcess::CamLaunchProcess()
Author: Phil_Martin (Xara Group Ltd) <[email protected]>
Created: 19/May/2006
Inputs: -
Outputs: -
Returns: -
Purpose: CamLaunchProcess constructor
********************************************************************************************/
CamLaunchProcess::CamLaunchProcess()
{
m_pid = 0;
m_bDead = true;
m_ReturnCode = -1;
m_bConnected = false;
}
/********************************************************************************************
> CamLaunchProcess::~CamLaunchProcess()
Author: Phil_Martin (Xara Group Ltd) <[email protected]>
Created: 19/May/2006
Inputs: -
Outputs: -
Returns: -
Purpose: CamLaunchProcess destructor
********************************************************************************************/
CamLaunchProcess::~CamLaunchProcess()
{
if (m_bConnected)
{
TRACEUSER("Phil", _T("Process still connected in ~CamLaunchProcess"));
Disconnect();
}
}
/********************************************************************************************
> virtual BOOL CamLaunchProcess::Execute(const wxString& cmd)
Author: Phil_Martin (Xara Group Ltd) <[email protected]>
Created: 19/May/2006
Inputs: cmd - The command string including parameters
Outputs: -
Returns: TRUE if the command was launched successfully
FALSE otherwise
Purpose: Execute a command which should launch a long-running process
********************************************************************************************/
BOOL CamLaunchProcess::Execute(const wxString& cmd)
{
m_ReturnCode = 0; // Assume success until we find otherwise
// Make sure redirection happens
Redirect();
TRACEUSER("Phil", _T("Executing %s\n"), (LPCTSTR) cmd);
m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
if (m_pid==0)
{
// Couldn't even create a process for the command!
m_bDead = true;
return FALSE;
}
// We're now running
m_bDead = false;
m_bConnected = true;
// Give the command 100 milliseconds to return an error condition or die...
// After that we will either use the return code it passed back to OnTerminate
// or assume it is running successfully...
MonotonicTime graceperiod;
while (!m_bDead && m_ReturnCode==0 && !graceperiod.Elapsed(100))
{
ProcessStdErr(); // Process any output on stderr
wxMilliSleep(1);
wxYield();
}
TRACEUSER("Phil", _T("Exiting with %d\n"), m_ReturnCode);
return (m_ReturnCode==0);
}
/********************************************************************************************
> UINT32 CamLaunchProcess::Disconnect()
Author: Phil_Martin (Xara Group Ltd) <[email protected]>
Created: 19/May/2006
Inputs: -
Outputs: -
Returns: ProcessID of the process we have just allowed to live
Purpose: Allow a process to continue to run after this object is destroyed
********************************************************************************************/
INT32 CamLaunchProcess::Disconnect()
{
INT32 pid = m_pid;
m_pid = 0;
m_bConnected = false;
Detach();
return pid;
}
/********************************************************************************************
> wxKillError CamLaunchProcess::Terminate()
Author: Phil_Martin (Xara Group Ltd) <[email protected]>
Created: 19/May/2006
Inputs: -
Outputs: -
Returns: wxKillError enum giving result of termination
Purpose: Kill the process
********************************************************************************************/
wxKillError CamLaunchProcess::Terminate()
{
if (!m_bDead)
return Kill(m_pid, wxSIGTERM);
return wxKILL_OK;
}
/********************************************************************************************
> void CamLaunchProcess::ProcessStdErr()
Author: Phil_Martin (Xara Group Ltd) <[email protected]>
Gerry_Iles (Xara Group Ltd) <[email protected]>
Created: 19/May/2006
Inputs: -
Outputs: -
Returns: -
Purpose: Process anything the process writes to the error stream
********************************************************************************************/
void CamLaunchProcess::ProcessStdErr()
{
if (IsErrorAvailable())
{
wxTextInputStream tis(*GetErrorStream());
// This assumes that the output is always line buffered
while (!GetErrorStream()->Eof())
{
wxString line;
line << tis.ReadLine();
TRACEUSER("Phil", _T("(stderr):%s\n"), line.c_str());
}
m_ReturnCode = 42; // Signal failure
}
}
/********************************************************************************************
> void CamLaunchProcess::OnTerminate(int TYPENOTE: Correct pid, int TYPENOTE: Correct status)
Author: Phil_Martin (Xara Group Ltd) <[email protected]>
Created: 19/May/2006
Inputs: -
Outputs: -
Returns: -
Purpose: Process anything the process writes to the error stream
********************************************************************************************/
void CamLaunchProcess::OnTerminate(int /*TYPENOTE: Correct*/ pid, int /*TYPENOTE: Correct*/ status)
{
ProcessStdErr();
TRACEUSER("Phil", _T("CamProcess::OnTerminate pid = %d status = %d\n"), pid, status);
m_bDead = true;
m_ReturnCode = status;
m_bConnected = false;
}
| [
"[email protected]"
] | |
9caef07216d8fc1468255f542ab4c0ebb69003a5 | 5ad6ce43f5725b813a82145dd4c365c3f74f37de | /sim/common/WorldRG.hpp | f15c1cab1048187d395dc46984a9b872468515a1 | [] | no_license | eastskykang/SimBenchmark | 6ede6816d03198269dbf4076eb74072484e375f4 | 5dc98e7889f285ab942cce28a2a7dcc1130d1192 | refs/heads/master | 2021-07-12T20:24:54.919986 | 2019-01-23T14:11:51 | 2019-01-23T14:11:51 | 161,664,554 | 1 | 0 | null | 2018-12-13T16:18:26 | 2018-12-13T16:18:25 | null | UTF-8 | C++ | false | false | 5,111 | hpp | //
// Created by kangd on 19.02.18.
//
#ifndef BENCHMARK_WORLD_RG_HPP
#define BENCHMARK_WORLD_RG_HPP
#include <raiGraphics/RAI_graphics.hpp>
#include "math.hpp"
#include "Configure.hpp"
#include "UserHandle.hpp"
#include "interface/CheckerboardInterface.hpp"
namespace bo = benchmark::object;
namespace benchmark {
/**
* Options for GUI
*/
enum VisualizerOption {
NO_BACKGROUND = 1<<(1),
DISABLE_INTERACTION = 1<<(2)
};
/**
* WorldRG class is GUI wrapper of dynamics world.
* Each Sim (BtSim, MjcSim ...) inherit WorldRG
*/
class WorldRG {
public:
/// constructor and destructors
// constructor for visualization
WorldRG(int windowWidth,
int windowHeight,
float cms,
int flags = 0);
// constructor for no visualization
WorldRG() = default;
virtual ~WorldRG();
/// Visualization related methods
virtual void loop(double dt, double realTimeFactor = 1.0);
virtual void visStart();
virtual void visEnd();
virtual void cameraFollowObject(SingleBodyHandle followingObject, Eigen::Vector3d relativePosition);
virtual void cameraFollowObject(rai_graphics::object::SingleBodyObject *followingObject, Eigen::Vector3d relativePosition);
virtual void setLightPosition(float x, float y, float z);
virtual bool visualizerLoop(double dt, double realTimeFactor = 1.0);
virtual void startRecordingVideo(std::string dir, std::string fileName);
virtual void stopRecordingVideo();
/// add objects (pure virtuals)
virtual SingleBodyHandle addCheckerboard(double gridSize,
double xLength,
double yLength,
double reflectanceI,
bo::CheckerboardShape shape = bo::PLANE_SHAPE,
benchmark::CollisionGroupType collisionGroup = 1,
benchmark::CollisionGroupType collisionMask = -1,
int flags = 0) = 0;
virtual SingleBodyHandle addSphere(double radius,
double mass,
benchmark::CollisionGroupType collisionGroup = 1,
benchmark::CollisionGroupType collisionMask=-1) = 0;
virtual SingleBodyHandle addBox(double xLength,
double yLength,
double zLength,
double mass,
benchmark::CollisionGroupType collisionGroup = 1,
benchmark::CollisionGroupType collisionMask = -1) = 0;
virtual SingleBodyHandle addCylinder(double radius,
double height,
double mass,
benchmark::CollisionGroupType collisionGroup = 1,
benchmark::CollisionGroupType collisionMask=-1) = 0;
virtual SingleBodyHandle addCapsule(double radius,
double height,
double mass,
benchmark::CollisionGroupType collisionGroup = 1,
benchmark::CollisionGroupType collisionMask=-1) = 0;
/// pure virtual getter, setter
virtual int getNumObject() = 0;
virtual int getWorldNumContacts() = 0;
/// pure virtual simulation methods
virtual void updateFrame() = 0;
virtual void integrate(double dt) = 0;
virtual void integrate1(double dt) = 0;
virtual void integrate2(double dt) = 0;
virtual void setGravity(Eigen::Vector3d gravity) = 0;
virtual void setERP(double erp, double erp2, double frictionErp) = 0;
protected:
/// sub methods
virtual void checkFileExistance(std::string nm);
virtual void processSingleBody(SingleBodyHandle handle);
virtual void processGraphicalObject(rai_graphics::object::SingleBodyObject* go, int li);
virtual void adjustTransparency(rai_graphics::object::SingleBodyObject* ob, bool hidable);
/// object list
std::vector<SingleBodyHandle> sbHandles_;
std::vector<object::SingleBodyObjectInterface *> framesAndCOMobj_;
/// gui objects
std::unique_ptr<rai_graphics::RAI_graphics> gui_;
std::unique_ptr<rai_graphics::object::Arrow> contactNormalArrow_;
std::unique_ptr<rai_graphics::object::Sphere> contactPointMarker_;
std::unique_ptr<rai_graphics::object::Background> background_;
std::unique_ptr<rai_graphics::object::Sphere> graphicalComMarker_;
std::unique_ptr<rai_graphics::object::Arrow> frameX_, frameY_, frameZ_;
/// gui properties
rai_graphics::CameraProp cameraProperty_;
rai_graphics::LightProp lightProperty_;
/// gui watch timer
StopWatch watch_, visualizerWatch_;
/// gui window size
const int windowWidth_ = 800;
const int windowHeight_ = 600;
/// gui option and flags
int visualizerFlags_ = 0;
bool isReady_=false;
bool isEnded_=false;
};
} // benchmark
#endif //BENCHMARK_WORLD_RG_HPP
| [
"[email protected]"
] | |
b199c4eb518d38738640263ad16a4d933e98e0d5 | 98278b136825a0cf170bcb2d419ff72c5f28e435 | /svf/SVF/lib/Util/PathCondAllocator.cpp | 1bd13b68fade5f4a04c5fb8133ed357b5d3adde1 | [
"Apache-2.0",
"GPL-3.0-or-later",
"NCSA"
] | permissive | cponcelets/savior-source | b3a687430270593f75b82e9f00249bdb4e4ffe13 | ac553cafba66663399eebccec58d16277bd1718e | refs/heads/master | 2021-05-23T18:35:33.358488 | 2020-09-30T08:18:29 | 2020-09-30T08:18:29 | 299,001,996 | 1 | 0 | Apache-2.0 | 2020-09-27T09:57:26 | 2020-09-27T09:57:25 | null | UTF-8 | C++ | false | false | 17,225 | cpp | //===- PathAllocator.cpp -- Path condition analysis---------------------------//
//
// SVF: Static Value-Flow Analysis
//
// Copyright (C) <2013-2017> <Yulei Sui>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
/*
* PathAllocator.cpp
*
* Created on: Apr 3, 2014
* Author: Yulei Sui
*/
#include "Util/PathCondAllocator.h"
#include "Util/DataFlowUtil.h"
#include "Util/DPItem.h"
#include <llvm/IR/Module.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Analysis/PostDominators.h>
#include <llvm/IR/Dominators.h>
#include <limits.h>
using namespace llvm;
using namespace analysisUtil;
u64_t DPItem::maximumBudget = ULONG_MAX - 1;
u32_t ContextCond::maximumCxtLen = 0;
u32_t ContextCond::maximumCxt = 0;
u32_t VFPathCond::maximumPathLen = 0;
u32_t VFPathCond::maximumPath = 0;
u32_t PathCondAllocator::totalCondNum = 0;
BddCondManager* PathCondAllocator::bddCondMgr = NULL;
static cl::opt<bool> PrintPathCond("print-pc", cl::init(false),
cl::desc("Print out path condition"));
/*!
* Allocate path condition for each branch
*/
void PathCondAllocator::allocate(const Module& M) {
DBOUT(DGENERAL,outs() << pasMsg("path condition allocation starts\n"));
for (Module::const_iterator fit = M.begin(); fit != M.end(); ++fit) {
const Function & func = *fit;
if (!analysisUtil::isExtCall(&func)) {
// Allocate conditions for a program.
for (Function::const_iterator bit = func.begin(), ebit = func.end(); bit != ebit; ++bit) {
const BasicBlock & bb = *bit;
collectBBCallingProgExit(bb);
allocateForBB(bb);
}
}
}
if(PrintPathCond)
printPathCond();
DBOUT(DGENERAL,outs() << pasMsg("path condition allocation ends\n"));
}
/*!
* Allocate conditions for a basic block and propagate its condition to its successors.
*/
void PathCondAllocator::allocateForBB(const BasicBlock & bb)
{
u32_t succ_number = getBBSuccessorNum(&bb);
// if successor number greater than 1, allocate new decision variable for successors
if(succ_number > 1) {
//allocate log2(num_succ) decision variables
double num = log(succ_number)/log(2);
u32_t bit_num = (u32_t)ceil(num);
u32_t succ_index = 0;
std::vector<Condition*> condVec;
for(u32_t i = 0 ; i < bit_num; i++) {
condVec.push_back(newCond(bb.getTerminator()));
}
// iterate each successor
for (succ_const_iterator succ_it = succ_begin(&bb);
succ_it != succ_end(&bb);
succ_it++, succ_index++) {
const BasicBlock* succ = *succ_it;
Condition* path_cond = getTrueCond();
///TODO: handle BranchInst and SwitchInst individually here!!
// for each successor decide its bit representation
// decide whether each bit of succ_index is 1 or 0, if (three successor) succ_index is 000 then use C1^C2^C3
// if 001 use C1^C2^negC3
for(u32_t j = 0 ; j < bit_num; j++) {
//test each bit of this successor's index (binary representation)
u32_t tool = 0x01 << j;
if(tool & succ_index) {
path_cond = condAnd(path_cond, condVec.at(j));
}
else {
path_cond = condAnd(path_cond, (condNeg(condVec.at(j))));
}
}
setBranchCond(&bb,succ,path_cond);
}
}
}
/*!
* Get a branch condition
*/
PathCondAllocator::Condition* PathCondAllocator::getBranchCond(const llvm::BasicBlock * bb, const llvm::BasicBlock *succ) const {
u32_t pos = getBBSuccessorPos(bb,succ);
if(getBBSuccessorNum(bb) == 1)
return getTrueCond();
else {
BBCondMap::const_iterator it = bbConds.find(bb);
assert(it!=bbConds.end() && "basic block does not have branch and conditions??");
CondPosMap::const_iterator cit = it->second.find(pos);
assert(cit!=it->second.end() && "no condition on the branch??");
return cit->second;
}
}
/*!
* Set a branch condition
*/
void PathCondAllocator::setBranchCond(const llvm::BasicBlock *bb, const llvm::BasicBlock *succ, Condition* cond) {
/// we only care about basic blocks have more than one successor
assert(getBBSuccessorNum(bb) > 1 && "not more than one successor??");
u32_t pos = getBBSuccessorPos(bb,succ);
CondPosMap& condPosMap = bbConds[bb];
/// FIXME: llvm getNumSuccessors allows duplicated block in the successors, it makes this assertion fail
/// In this case we may waste a condition allocation, because the overwrite of the previous cond
//assert(condPosMap.find(pos) == condPosMap.end() && "this branch has already been set ");
condPosMap[pos] = cond;
}
/*!
* Evaluate null like expression for source-sink related bug detection in SABER
*/
PathCondAllocator::Condition* PathCondAllocator::evaluateTestNullLikeExpr(const BranchInst* brInst, const BasicBlock *succ, const Value* val) {
const BasicBlock* succ1 = brInst->getSuccessor(0);
if(isTestNullExpr(brInst->getCondition(),val)) {
// succ is then branch
if(succ1 == succ)
return getFalseCond();
// succ is else branch
else
return getTrueCond();
}
if(isTestNotNullExpr(brInst->getCondition(),val)) {
// succ is then branch
if(succ1 == succ)
return getTrueCond();
// succ is else branch
else
return getFalseCond();
}
return NULL;
}
/*!
* Evaluate condition for program exit (e.g., exit(0))
*/
PathCondAllocator::Condition* PathCondAllocator::evaluateProgExit(const BranchInst* brInst, const BasicBlock *succ) {
const BasicBlock* succ1 = brInst->getSuccessor(0);
const BasicBlock* succ2 = brInst->getSuccessor(1);
bool branch1 = isBBCallsProgExit(succ1);
bool branch2 = isBBCallsProgExit(succ2);
/// then branch calls program exit
if(branch1 == true && branch2 == false) {
// succ is then branch
if(succ1 == succ)
return getFalseCond();
// succ is else branch
else
return getTrueCond();
}
/// else branch calls program exit
else if(branch1 == false && branch2 == true) {
// succ is else branch
if(succ2 == succ)
return getFalseCond();
// succ is then branch
else
return getTrueCond();
}
// two branches both call program exit
else if(branch1 == true && branch2 == true) {
return getFalseCond();
}
/// no branch call program exit
else
return NULL;
}
/*!
* Evaluate loop exit branch to be true if
* bb is loop header and succ is the only exit basic block outside the loop (excluding exit bbs which call program exit)
* for all other case, we conservatively evaluate false for now
*/
PathCondAllocator::Condition* PathCondAllocator::evaluateLoopExitBranch(const BasicBlock * bb, const BasicBlock *dst) {
const Function* fun = bb->getParent();
assert(fun==dst->getParent() && "two basic blocks should be in the same function");
const LoopInfo* loopInfo = getLoopInfo(fun);
if(loopInfo->isLoopHeader(const_cast<BasicBlock*>(bb))) {
const Loop *loop = loopInfo->getLoopFor(bb);
SmallVector<BasicBlock*, 8> exitbbs;
std::set<BasicBlock*> filteredbbs;
loop->getExitBlocks(exitbbs);
/// exclude exit bb which calls program exit
while(!exitbbs.empty()) {
BasicBlock* eb = exitbbs.pop_back_val();
if(isBBCallsProgExit(eb) == false)
filteredbbs.insert(eb);
}
/// if the dst dominate all other loop exit bbs, then dst can certainly be reached
bool allPDT = true;
PostDominatorTree* pdt = getPostDT(fun);
for(std::set<BasicBlock*>::iterator it = filteredbbs.begin(), eit = filteredbbs.end(); it!=eit; ++it) {
if(pdt->dominates(dst,*it) == false)
allPDT =false;
}
if(allPDT)
return getTrueCond();
}
return NULL;
}
/*!
* (1) Evaluate a branch when it reaches a program exit
* (2) Evaluate a branch when it is loop exit branch
* (3) Evaluate a branch when it is a test null like condition
*/
PathCondAllocator::Condition* PathCondAllocator::evaluateBranchCond(const BasicBlock * bb, const BasicBlock *succ, const Value* val) {
if(getBBSuccessorNum(bb) == 1) {
assert(bb->getTerminator()->getSuccessor(0) == succ && "not the unique successor?");
return getTrueCond();
}
if(const BranchInst* brInst = dyn_cast<BranchInst>(bb->getTerminator())) {
assert(brInst->getNumSuccessors() == 2 && "not a two successors branch??");
const BasicBlock* succ1 = brInst->getSuccessor(0);
const BasicBlock* succ2 = brInst->getSuccessor(1);
assert((succ1 == succ || succ2 == succ) && "not a successor??");
Condition* evalLoopExit = evaluateLoopExitBranch(bb,succ);
if(evalLoopExit)
return evalLoopExit;
Condition* evalProgExit = evaluateProgExit(brInst,succ);
if(evalProgExit)
return evalProgExit;
Condition* evalTestNullLike = evaluateTestNullLikeExpr(brInst,succ,val);
if(evalTestNullLike)
return evalTestNullLike;
}
return getBranchCond(bb, succ);
}
bool PathCondAllocator::isEQCmp(const llvm::CmpInst* cmp) const {
return (cmp->getPredicate() == CmpInst::ICMP_EQ);
}
bool PathCondAllocator::isNECmp(const llvm::CmpInst* cmp) const {
return (cmp->getPredicate() == CmpInst::ICMP_NE);
}
bool PathCondAllocator::isTestNullExpr(const llvm::Value* test,const llvm::Value* val) const {
if(const CmpInst* cmp = dyn_cast<CmpInst>(test)) {
return isTestContainsNullAndTheValue(cmp,val) && isEQCmp(cmp);
}
return false;
}
bool PathCondAllocator::isTestNotNullExpr(const llvm::Value* test,const llvm::Value* val) const {
if(const CmpInst* cmp = dyn_cast<CmpInst>(test)) {
return isTestContainsNullAndTheValue(cmp,val) && isNECmp(cmp);
}
return false;
}
bool PathCondAllocator::isTestContainsNullAndTheValue(const llvm::CmpInst* cmp, const llvm::Value* val) const {
const Value* op0 = cmp->getOperand(0);
const Value* op1 = cmp->getOperand(1);
if((op0 == val && isa<ConstantPointerNull>(op1))
|| (op1 == val && isa<ConstantPointerNull>(op0)) )
return true;
return false;
}
/*!
* Whether this basic block contains program exit function call
*/
void PathCondAllocator::collectBBCallingProgExit(const BasicBlock & bb) {
for(BasicBlock::const_iterator it = bb.begin(), eit = bb.end(); it!=eit; it++) {
const Instruction* inst = &*it;
if(isa<CallInst>(inst) || isa<InvokeInst>(inst))
if(analysisUtil::isProgExitCall(inst)) {
funToExitBBsMap[bb.getParent()].insert(&bb);
}
}
}
/*!
* Whether this basic block contains program exit function call
*/
bool PathCondAllocator::isBBCallsProgExit(const llvm::BasicBlock* bb) {
const Function* fun = bb->getParent();
FunToExitBBsMap::const_iterator it = funToExitBBsMap.find(fun);
if(it!=funToExitBBsMap.end()) {
PostDominatorTree* pdt = getPostDT(fun);
for(BasicBlockSet::iterator bit = it->second.begin(), ebit= it->second.end(); bit!=ebit; bit++) {
if(pdt->dominates(*bit,bb))
return true;
}
}
return false;
}
/*!
* Get complement phi condition
* e.g., B0: dstBB; B1:incomingBB; B2:complementBB
* Assume B0 (phi node) is the successor of both B1 and B2.
* If B1 dominates B2, and B0 not dominate B2 then condition from B1-->B0 = neg(B1-->B2)^(B1-->B0)
*/
PathCondAllocator::Condition* PathCondAllocator::getPHIComplementCond(const BasicBlock* BB1, const BasicBlock* BB2, const BasicBlock* BB0) {
assert(BB1 && BB2 && "expect NULL BB here!");
DominatorTree* dt = getDT(BB1->getParent());
/// avoid both BB0 and BB1 dominate BB2 (e.g., while loop), then BB2 is not necessaryly a complement BB
if(dt->dominates(BB1,BB2) && !dt->dominates(BB0,BB2)) {
Condition* cond = ComputeIntraVFGGuard(BB1,BB2);
return condNeg(cond);
}
return trueCond();
}
/*!
* Compute calling inter-procedural guards between two SVFGNodes (from caller to callee)
* src --c1--> callBB --true--> funEntryBB --c2--> dst
* the InterCallVFGGuard is c1 ^ c2
*/
PathCondAllocator::Condition* PathCondAllocator::ComputeInterCallVFGGuard(const llvm::BasicBlock* srcBB, const llvm::BasicBlock* dstBB, const BasicBlock* callBB) {
const BasicBlock* funEntryBB = &dstBB->getParent()->getEntryBlock();
Condition* c1 = ComputeIntraVFGGuard(srcBB,callBB);
setCFCond(funEntryBB,condOr(getCFCond(funEntryBB),getCFCond(callBB)));
Condition* c2 = ComputeIntraVFGGuard(funEntryBB,dstBB);
return condAnd(c1,c2);
}
/*!
* Compute return inter-procedural guards between two SVFGNodes (from callee to caller)
* src --c1--> funExitBB --true--> retBB --c2--> dst
* the InterRetVFGGuard is c1 ^ c2
*/
PathCondAllocator::Condition* PathCondAllocator::ComputeInterRetVFGGuard(const llvm::BasicBlock* srcBB, const llvm::BasicBlock* dstBB, const BasicBlock* retBB) {
const BasicBlock* funExitBB = getFunExitBB(srcBB->getParent());
Condition* c1 = ComputeIntraVFGGuard(srcBB,funExitBB);
setCFCond(retBB,condOr(getCFCond(retBB),getCFCond(funExitBB)));
Condition* c2 = ComputeIntraVFGGuard(retBB,dstBB);
return condAnd(c1,c2);
}
/*!
* Compute intra-procedural guards between two SVFGNodes (inside same function)
*/
PathCondAllocator::Condition* PathCondAllocator::ComputeIntraVFGGuard(const llvm::BasicBlock* srcBB, const llvm::BasicBlock* dstBB) {
assert(srcBB->getParent() == dstBB->getParent() && "two basic blocks are not in the same function??");
PostDominatorTree* postDT = getPostDT(srcBB->getParent());
if(postDT->dominates(dstBB,srcBB))
return getTrueCond();
CFWorkList worklist;
worklist.push(srcBB);
setCFCond(srcBB,getTrueCond());
while(!worklist.empty()) {
const BasicBlock* bb = worklist.pop();
Condition* cond = getCFCond(bb);
/// if the dstBB is the eligible loop exit of the current basic block
/// we can early terminate the computation
if(Condition* loopExitCond = evaluateLoopExitBranch(bb,dstBB))
return condAnd(cond, loopExitCond);
for (succ_const_iterator succ_it = succ_begin(bb);
succ_it != succ_end(bb); succ_it++) {
const BasicBlock* succ = *succ_it;
/// calculate the branch condition
/// if succ post dominate bb, then we get brCond quicker by using postDT
/// note that we assume loop exit always post dominate loop bodys
/// which means loops are approximated only once.
Condition* brCond;
if(postDT->dominates(succ,bb))
brCond = getTrueCond();
else
brCond = getEvalBrCond(bb, succ);
DBOUT(DSaber, outs() << " bb (" << bb->getName() <<
") --> " << "succ_bb (" << succ->getName() << ") condition: " << brCond << "\n");
Condition* succPathCond = condAnd(cond, brCond);
if(setCFCond(succ, condOr(getCFCond(succ), succPathCond)))
worklist.push(succ);
}
}
DBOUT(DSaber, outs() << " src_bb (" << srcBB->getName() <<
") --> " << "dst_bb (" << dstBB->getName() << ") condition: " << getCFCond(dstBB) << "\n");
return getCFCond(dstBB);
}
/*!
* Release memory
*/
void PathCondAllocator::destroy() {
delete bddCondMgr;
bddCondMgr = NULL;
}
/*!
* Print path conditions
*/
void PathCondAllocator::printPathCond() {
outs() << "print path condition\n";
for(BBCondMap::iterator it = bbConds.begin(), eit = bbConds.end(); it!=eit; ++it) {
const BasicBlock* bb = it->first;
for(CondPosMap::iterator cit = it->second.begin(), ecit = it->second.end(); cit!=ecit; ++cit) {
const TerminatorInst *Term = bb->getTerminator();
const BasicBlock* succ = Term->getSuccessor(cit->first);
Condition* cond = cit->second;
outs() << bb->getName() << "-->" << succ->getName() << ":";
outs() << dumpCond(cond) << "\n";
}
}
}
| [
"[email protected]"
] | |
0137c9993dbdafa4fead4d8e28ce63369c5be002 | b6dcd7d9681a77fbf05afdd55164a9cd053615ab | /Chapter_10/stock10.h | 974b4c38f2b022e9074b878c63b1a199e2a5f796 | [] | no_license | BBlack-Hun/cpplearn | 756648e87a44350ea0da91a23fd14769b1a16031 | 22be6dd5d57c52cddf44985dac84ba02e3213d28 | refs/heads/master | 2022-12-28T10:03:03.159000 | 2020-10-13T07:34:23 | 2020-10-13T07:34:23 | 303,619,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 645 | h | // stock10.h -- 생성자들과 파괴자가 추가된 Stock 클래스 선언
#ifndef STOCK10_H_
#define STOCK10_H_
#include<string>
class Stock
{
private:
std::string company;
long shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val;}
public:
Stock(); // 디폴트 생성자
Stock(const std::string & co, long n = 0, double pr = 0.0);
~Stock(); // 파괴자
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
void show();
};
#endif | [
"[email protected]"
] | |
965e440c5bc83352082f2561d3c50c1170410f27 | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /v8_5_1/src/compiler/escape-analysis.cc | e29954d09e3db0f6d30f765770d1d8158742fdf6 | [
"BSD-3-Clause",
"bzip2-1.0.6",
"Apache-2.0"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 50,006 | cc | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/escape-analysis.h"
#include <limits>
#include "src/base/flags.h"
#include "src/bootstrapper.h"
#include "src/compilation-dependencies.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/graph-reducer.h"
#include "src/compiler/js-operator.h"
#include "src/compiler/node.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/operator-properties.h"
#include "src/compiler/simplified-operator.h"
#include "src/objects-inl.h"
#include "src/type-cache.h"
namespace v8 {
namespace internal {
namespace compiler {
using Alias = EscapeStatusAnalysis::Alias;
#ifdef DEBUG
#define TRACE(...) \
do { \
if (FLAG_trace_turbo_escape) PrintF(__VA_ARGS__); \
} while (false)
#else
#define TRACE(...)
#endif
const Alias EscapeStatusAnalysis::kNotReachable =
std::numeric_limits<Alias>::max();
const Alias EscapeStatusAnalysis::kUntrackable =
std::numeric_limits<Alias>::max() - 1;
class VirtualObject : public ZoneObject {
public:
enum Status {
kInitial = 0,
kTracked = 1u << 0,
kInitialized = 1u << 1,
kCopyRequired = 1u << 2,
};
typedef base::Flags<Status, unsigned char> StatusFlags;
VirtualObject(NodeId id, VirtualState* owner, Zone* zone)
: id_(id),
status_(kInitial),
fields_(zone),
phi_(zone),
object_state_(nullptr),
owner_(owner) {}
VirtualObject(VirtualState* owner, const VirtualObject& other)
: id_(other.id_),
status_(other.status_ & ~kCopyRequired),
fields_(other.fields_),
phi_(other.phi_),
object_state_(other.object_state_),
owner_(owner) {}
VirtualObject(NodeId id, VirtualState* owner, Zone* zone, size_t field_number,
bool initialized)
: id_(id),
status_(kTracked | (initialized ? kInitialized : kInitial)),
fields_(zone),
phi_(zone),
object_state_(nullptr),
owner_(owner) {
fields_.resize(field_number);
phi_.resize(field_number, false);
}
Node* GetField(size_t offset) { return fields_[offset]; }
bool IsCreatedPhi(size_t offset) { return phi_[offset]; }
void SetField(size_t offset, Node* node, bool created_phi = false) {
fields_[offset] = node;
phi_[offset] = created_phi;
}
bool IsTracked() const { return status_ & kTracked; }
bool IsInitialized() const { return status_ & kInitialized; }
bool SetInitialized() { return status_ |= kInitialized; }
VirtualState* owner() const { return owner_; }
Node** fields_array() { return &fields_.front(); }
size_t field_count() { return fields_.size(); }
bool ResizeFields(size_t field_count) {
if (field_count > fields_.size()) {
fields_.resize(field_count);
phi_.resize(field_count);
return true;
}
return false;
}
void ClearAllFields() {
for (size_t i = 0; i < fields_.size(); ++i) {
fields_[i] = nullptr;
phi_[i] = false;
}
}
bool AllFieldsClear() {
for (size_t i = 0; i < fields_.size(); ++i) {
if (fields_[i] != nullptr) {
return false;
}
}
return true;
}
bool UpdateFrom(const VirtualObject& other);
bool MergeFrom(MergeCache* cache, Node* at, Graph* graph,
CommonOperatorBuilder* common);
void SetObjectState(Node* node) { object_state_ = node; }
Node* GetObjectState() const { return object_state_; }
bool IsCopyRequired() const { return status_ & kCopyRequired; }
void SetCopyRequired() { status_ |= kCopyRequired; }
bool NeedCopyForModification() {
if (!IsCopyRequired() || !IsInitialized()) {
return false;
}
return true;
}
NodeId id() const { return id_; }
void id(NodeId id) { id_ = id; }
private:
bool MergeFields(size_t i, Node* at, MergeCache* cache, Graph* graph,
CommonOperatorBuilder* common);
NodeId id_;
StatusFlags status_;
ZoneVector<Node*> fields_;
ZoneVector<bool> phi_;
Node* object_state_;
VirtualState* owner_;
DISALLOW_COPY_AND_ASSIGN(VirtualObject);
};
DEFINE_OPERATORS_FOR_FLAGS(VirtualObject::StatusFlags)
bool VirtualObject::UpdateFrom(const VirtualObject& other) {
bool changed = status_ != other.status_;
status_ = other.status_;
phi_ = other.phi_;
if (fields_.size() != other.fields_.size()) {
fields_ = other.fields_;
return true;
}
for (size_t i = 0; i < fields_.size(); ++i) {
if (fields_[i] != other.fields_[i]) {
changed = true;
fields_[i] = other.fields_[i];
}
}
return changed;
}
class VirtualState : public ZoneObject {
public:
VirtualState(Node* owner, Zone* zone, size_t size)
: info_(size, nullptr, zone), owner_(owner) {}
VirtualState(Node* owner, const VirtualState& state)
: info_(state.info_.size(), nullptr, state.info_.get_allocator().zone()),
owner_(owner) {
for (size_t i = 0; i < info_.size(); ++i) {
if (state.info_[i]) {
info_[i] = state.info_[i];
}
}
}
VirtualObject* VirtualObjectFromAlias(size_t alias);
void SetVirtualObject(Alias alias, VirtualObject* state);
bool UpdateFrom(VirtualState* state, Zone* zone);
bool MergeFrom(MergeCache* cache, Zone* zone, Graph* graph,
CommonOperatorBuilder* common, Node* at);
size_t size() const { return info_.size(); }
Node* owner() const { return owner_; }
VirtualObject* Copy(VirtualObject* obj, Alias alias);
void SetCopyRequired() {
for (VirtualObject* obj : info_) {
if (obj) obj->SetCopyRequired();
}
}
private:
ZoneVector<VirtualObject*> info_;
Node* owner_;
DISALLOW_COPY_AND_ASSIGN(VirtualState);
};
class MergeCache : public ZoneObject {
public:
explicit MergeCache(Zone* zone)
: states_(zone), objects_(zone), fields_(zone) {
states_.reserve(5);
objects_.reserve(5);
fields_.reserve(5);
}
ZoneVector<VirtualState*>& states() { return states_; }
ZoneVector<VirtualObject*>& objects() { return objects_; }
ZoneVector<Node*>& fields() { return fields_; }
void Clear() {
states_.clear();
objects_.clear();
fields_.clear();
}
size_t LoadVirtualObjectsFromStatesFor(Alias alias);
void LoadVirtualObjectsForFieldsFrom(VirtualState* state,
const ZoneVector<Alias>& aliases);
Node* GetFields(size_t pos);
private:
ZoneVector<VirtualState*> states_;
ZoneVector<VirtualObject*> objects_;
ZoneVector<Node*> fields_;
DISALLOW_COPY_AND_ASSIGN(MergeCache);
};
size_t MergeCache::LoadVirtualObjectsFromStatesFor(Alias alias) {
objects_.clear();
DCHECK_GT(states_.size(), 0u);
size_t min = std::numeric_limits<size_t>::max();
for (VirtualState* state : states_) {
if (VirtualObject* obj = state->VirtualObjectFromAlias(alias)) {
objects_.push_back(obj);
min = std::min(obj->field_count(), min);
}
}
return min;
}
void MergeCache::LoadVirtualObjectsForFieldsFrom(
VirtualState* state, const ZoneVector<Alias>& aliases) {
objects_.clear();
size_t max_alias = state->size();
for (Node* field : fields_) {
Alias alias = aliases[field->id()];
if (alias >= max_alias) continue;
if (VirtualObject* obj = state->VirtualObjectFromAlias(alias)) {
objects_.push_back(obj);
}
}
}
Node* MergeCache::GetFields(size_t pos) {
fields_.clear();
Node* rep = pos >= objects_.front()->field_count()
? nullptr
: objects_.front()->GetField(pos);
for (VirtualObject* obj : objects_) {
if (pos >= obj->field_count()) continue;
Node* field = obj->GetField(pos);
if (field) {
fields_.push_back(field);
}
if (field != rep) {
rep = nullptr;
}
}
return rep;
}
VirtualObject* VirtualState::Copy(VirtualObject* obj, Alias alias) {
if (obj->owner() == this) return obj;
VirtualObject* new_obj =
new (info_.get_allocator().zone()) VirtualObject(this, *obj);
TRACE("At state %p, alias @%d (#%d), copying virtual object from %p to %p\n",
static_cast<void*>(this), alias, obj->id(), static_cast<void*>(obj),
static_cast<void*>(new_obj));
info_[alias] = new_obj;
return new_obj;
}
VirtualObject* VirtualState::VirtualObjectFromAlias(size_t alias) {
return info_[alias];
}
void VirtualState::SetVirtualObject(Alias alias, VirtualObject* obj) {
info_[alias] = obj;
}
bool VirtualState::UpdateFrom(VirtualState* from, Zone* zone) {
if (from == this) return false;
bool changed = false;
for (Alias alias = 0; alias < size(); ++alias) {
VirtualObject* ls = VirtualObjectFromAlias(alias);
VirtualObject* rs = from->VirtualObjectFromAlias(alias);
if (ls == rs || rs == nullptr) continue;
if (ls == nullptr) {
ls = new (zone) VirtualObject(this, *rs);
SetVirtualObject(alias, ls);
changed = true;
continue;
}
TRACE(" Updating fields of @%d\n", alias);
changed = ls->UpdateFrom(*rs) || changed;
}
return false;
}
namespace {
bool IsEquivalentPhi(Node* node1, Node* node2) {
if (node1 == node2) return true;
if (node1->opcode() != IrOpcode::kPhi || node2->opcode() != IrOpcode::kPhi ||
node1->op()->ValueInputCount() != node2->op()->ValueInputCount()) {
return false;
}
for (int i = 0; i < node1->op()->ValueInputCount(); ++i) {
Node* input1 = NodeProperties::GetValueInput(node1, i);
Node* input2 = NodeProperties::GetValueInput(node2, i);
if (!IsEquivalentPhi(input1, input2)) {
return false;
}
}
return true;
}
bool IsEquivalentPhi(Node* phi, ZoneVector<Node*>& inputs) {
if (phi->opcode() != IrOpcode::kPhi) return false;
if (phi->op()->ValueInputCount() != inputs.size()) {
return false;
}
for (size_t i = 0; i < inputs.size(); ++i) {
Node* input = NodeProperties::GetValueInput(phi, static_cast<int>(i));
if (!IsEquivalentPhi(input, inputs[i])) {
return false;
}
}
return true;
}
} // namespace
bool VirtualObject::MergeFields(size_t i, Node* at, MergeCache* cache,
Graph* graph, CommonOperatorBuilder* common) {
bool changed = false;
int value_input_count = static_cast<int>(cache->fields().size());
Node* rep = GetField(i);
if (!rep || !IsCreatedPhi(i)) {
Node* control = NodeProperties::GetControlInput(at);
cache->fields().push_back(control);
Node* phi = graph->NewNode(
common->Phi(MachineRepresentation::kTagged, value_input_count),
value_input_count + 1, &cache->fields().front());
SetField(i, phi, true);
#ifdef DEBUG
if (FLAG_trace_turbo_escape) {
PrintF(" Creating Phi #%d as merge of", phi->id());
for (int i = 0; i < value_input_count; i++) {
PrintF(" #%d (%s)", cache->fields()[i]->id(),
cache->fields()[i]->op()->mnemonic());
}
PrintF("\n");
}
#endif
changed = true;
} else {
DCHECK(rep->opcode() == IrOpcode::kPhi);
for (int n = 0; n < value_input_count; ++n) {
Node* old = NodeProperties::GetValueInput(rep, n);
if (old != cache->fields()[n]) {
changed = true;
NodeProperties::ReplaceValueInput(rep, cache->fields()[n], n);
}
}
}
return changed;
}
bool VirtualObject::MergeFrom(MergeCache* cache, Node* at, Graph* graph,
CommonOperatorBuilder* common) {
DCHECK(at->opcode() == IrOpcode::kEffectPhi ||
at->opcode() == IrOpcode::kPhi);
bool changed = false;
for (size_t i = 0; i < field_count(); ++i) {
if (Node* field = cache->GetFields(i)) {
changed = changed || GetField(i) != field;
SetField(i, field);
TRACE(" Field %zu agree on rep #%d\n", i, field->id());
} else {
int arity = at->opcode() == IrOpcode::kEffectPhi
? at->op()->EffectInputCount()
: at->op()->ValueInputCount();
if (cache->fields().size() == arity) {
changed = MergeFields(i, at, cache, graph, common) || changed;
} else {
if (GetField(i) != nullptr) {
TRACE(" Field %zu cleared\n", i);
changed = true;
}
SetField(i, nullptr);
}
}
}
return changed;
}
bool VirtualState::MergeFrom(MergeCache* cache, Zone* zone, Graph* graph,
CommonOperatorBuilder* common, Node* at) {
DCHECK_GT(cache->states().size(), 0u);
bool changed = false;
for (Alias alias = 0; alias < size(); ++alias) {
cache->objects().clear();
VirtualObject* mergeObject = VirtualObjectFromAlias(alias);
bool copy_merge_object = false;
size_t fields = std::numeric_limits<size_t>::max();
for (VirtualState* state : cache->states()) {
if (VirtualObject* obj = state->VirtualObjectFromAlias(alias)) {
cache->objects().push_back(obj);
if (mergeObject == obj) {
copy_merge_object = true;
}
fields = std::min(obj->field_count(), fields);
}
}
if (cache->objects().size() == cache->states().size()) {
if (!mergeObject) {
VirtualObject* obj = new (zone)
VirtualObject(cache->objects().front()->id(), this, zone, fields,
cache->objects().front()->IsInitialized());
SetVirtualObject(alias, obj);
mergeObject = obj;
changed = true;
} else if (copy_merge_object) {
VirtualObject* obj = new (zone) VirtualObject(this, *mergeObject);
SetVirtualObject(alias, obj);
mergeObject = obj;
changed = true;
} else {
changed = mergeObject->ResizeFields(fields) || changed;
}
#ifdef DEBUG
if (FLAG_trace_turbo_escape) {
PrintF(" Alias @%d, merging into %p virtual objects", alias,
static_cast<void*>(mergeObject));
for (size_t i = 0; i < cache->objects().size(); i++) {
PrintF(" %p", static_cast<void*>(cache->objects()[i]));
}
PrintF("\n");
}
#endif // DEBUG
changed = mergeObject->MergeFrom(cache, at, graph, common) || changed;
} else {
if (mergeObject) {
TRACE(" Alias %d, virtual object removed\n", alias);
changed = true;
}
SetVirtualObject(alias, nullptr);
}
}
return changed;
}
EscapeStatusAnalysis::EscapeStatusAnalysis(EscapeAnalysis* object_analysis,
Graph* graph, Zone* zone)
: stack_(zone),
object_analysis_(object_analysis),
graph_(graph),
zone_(zone),
status_(zone),
next_free_alias_(0),
status_stack_(zone),
aliases_(zone) {}
EscapeStatusAnalysis::~EscapeStatusAnalysis() {}
bool EscapeStatusAnalysis::HasEntry(Node* node) {
return status_[node->id()] & (kTracked | kEscaped);
}
bool EscapeStatusAnalysis::IsVirtual(Node* node) {
return IsVirtual(node->id());
}
bool EscapeStatusAnalysis::IsVirtual(NodeId id) {
return (status_[id] & kTracked) && !(status_[id] & kEscaped);
}
bool EscapeStatusAnalysis::IsEscaped(Node* node) {
return status_[node->id()] & kEscaped;
}
bool EscapeStatusAnalysis::IsAllocation(Node* node) {
return node->opcode() == IrOpcode::kAllocate ||
node->opcode() == IrOpcode::kFinishRegion;
}
bool EscapeStatusAnalysis::SetEscaped(Node* node) {
bool changed = !(status_[node->id()] & kEscaped);
status_[node->id()] |= kEscaped | kTracked;
return changed;
}
bool EscapeStatusAnalysis::IsInQueue(NodeId id) {
return status_[id] & kInQueue;
}
void EscapeStatusAnalysis::SetInQueue(NodeId id, bool on_stack) {
if (on_stack) {
status_[id] |= kInQueue;
} else {
status_[id] &= ~kInQueue;
}
}
void EscapeStatusAnalysis::ResizeStatusVector() {
if (status_.size() <= graph()->NodeCount()) {
status_.resize(graph()->NodeCount() * 1.1, kUnknown);
}
}
size_t EscapeStatusAnalysis::GetStatusVectorSize() { return status_.size(); }
void EscapeStatusAnalysis::RunStatusAnalysis() {
ResizeStatusVector();
while (!status_stack_.empty()) {
Node* node = status_stack_.back();
status_stack_.pop_back();
status_[node->id()] &= ~kOnStack;
Process(node);
status_[node->id()] |= kVisited;
}
}
void EscapeStatusAnalysis::EnqueueForStatusAnalysis(Node* node) {
DCHECK_NOT_NULL(node);
if (!(status_[node->id()] & kOnStack)) {
status_stack_.push_back(node);
status_[node->id()] |= kOnStack;
}
}
void EscapeStatusAnalysis::RevisitInputs(Node* node) {
for (Edge edge : node->input_edges()) {
Node* input = edge.to();
if (!(status_[input->id()] & kOnStack)) {
status_stack_.push_back(input);
status_[input->id()] |= kOnStack;
}
}
}
void EscapeStatusAnalysis::RevisitUses(Node* node) {
for (Edge edge : node->use_edges()) {
Node* use = edge.from();
if (!(status_[use->id()] & kOnStack) && !IsNotReachable(use)) {
status_stack_.push_back(use);
status_[use->id()] |= kOnStack;
}
}
}
void EscapeStatusAnalysis::Process(Node* node) {
switch (node->opcode()) {
case IrOpcode::kAllocate:
ProcessAllocate(node);
break;
case IrOpcode::kFinishRegion:
ProcessFinishRegion(node);
break;
case IrOpcode::kStoreField:
ProcessStoreField(node);
break;
case IrOpcode::kStoreElement:
ProcessStoreElement(node);
break;
case IrOpcode::kLoadField:
case IrOpcode::kLoadElement: {
if (Node* rep = object_analysis_->GetReplacement(node)) {
if (IsAllocation(rep) && CheckUsesForEscape(node, rep)) {
RevisitInputs(rep);
RevisitUses(rep);
}
}
RevisitUses(node);
break;
}
case IrOpcode::kPhi:
if (!HasEntry(node)) {
status_[node->id()] |= kTracked;
RevisitUses(node);
}
if (!IsAllocationPhi(node) && SetEscaped(node)) {
RevisitInputs(node);
RevisitUses(node);
}
CheckUsesForEscape(node);
default:
break;
}
}
bool EscapeStatusAnalysis::IsAllocationPhi(Node* node) {
for (Edge edge : node->input_edges()) {
Node* input = edge.to();
if (input->opcode() == IrOpcode::kPhi && !IsEscaped(input)) continue;
if (IsAllocation(input)) continue;
return false;
}
return true;
}
void EscapeStatusAnalysis::ProcessStoreField(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kStoreField);
Node* to = NodeProperties::GetValueInput(node, 0);
Node* val = NodeProperties::GetValueInput(node, 1);
if ((IsEscaped(to) || !IsAllocation(to)) && SetEscaped(val)) {
RevisitUses(val);
RevisitInputs(val);
TRACE("Setting #%d (%s) to escaped because of store to field of #%d\n",
val->id(), val->op()->mnemonic(), to->id());
}
}
void EscapeStatusAnalysis::ProcessStoreElement(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kStoreElement);
Node* to = NodeProperties::GetValueInput(node, 0);
Node* val = NodeProperties::GetValueInput(node, 2);
if ((IsEscaped(to) || !IsAllocation(to)) && SetEscaped(val)) {
RevisitUses(val);
RevisitInputs(val);
TRACE("Setting #%d (%s) to escaped because of store to field of #%d\n",
val->id(), val->op()->mnemonic(), to->id());
}
}
void EscapeStatusAnalysis::ProcessAllocate(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kAllocate);
if (!HasEntry(node)) {
status_[node->id()] |= kTracked;
TRACE("Created status entry for node #%d (%s)\n", node->id(),
node->op()->mnemonic());
NumberMatcher size(node->InputAt(0));
DCHECK(node->InputAt(0)->opcode() != IrOpcode::kInt32Constant &&
node->InputAt(0)->opcode() != IrOpcode::kInt64Constant &&
node->InputAt(0)->opcode() != IrOpcode::kFloat32Constant &&
node->InputAt(0)->opcode() != IrOpcode::kFloat64Constant);
RevisitUses(node);
if (!size.HasValue() && SetEscaped(node)) {
TRACE("Setting #%d to escaped because of non-const alloc\n", node->id());
// This node is already known to escape, uses do not have to be checked
// for escape.
return;
}
}
if (CheckUsesForEscape(node, true)) {
RevisitUses(node);
}
}
bool EscapeStatusAnalysis::CheckUsesForEscape(Node* uses, Node* rep,
bool phi_escaping) {
for (Edge edge : uses->use_edges()) {
Node* use = edge.from();
if (IsNotReachable(use)) continue;
if (edge.index() >= use->op()->ValueInputCount() +
OperatorProperties::GetContextInputCount(use->op()))
continue;
switch (use->opcode()) {
case IrOpcode::kPhi:
if (phi_escaping && SetEscaped(rep)) {
TRACE(
"Setting #%d (%s) to escaped because of use by phi node "
"#%d (%s)\n",
rep->id(), rep->op()->mnemonic(), use->id(),
use->op()->mnemonic());
return true;
}
// Fallthrough.
case IrOpcode::kStoreField:
case IrOpcode::kLoadField:
case IrOpcode::kStoreElement:
case IrOpcode::kLoadElement:
case IrOpcode::kFrameState:
case IrOpcode::kStateValues:
case IrOpcode::kReferenceEqual:
case IrOpcode::kFinishRegion:
if (IsEscaped(use) && SetEscaped(rep)) {
TRACE(
"Setting #%d (%s) to escaped because of use by escaping node "
"#%d (%s)\n",
rep->id(), rep->op()->mnemonic(), use->id(),
use->op()->mnemonic());
return true;
}
break;
case IrOpcode::kObjectIsSmi:
if (!IsAllocation(rep) && SetEscaped(rep)) {
TRACE("Setting #%d (%s) to escaped because of use by #%d (%s)\n",
rep->id(), rep->op()->mnemonic(), use->id(),
use->op()->mnemonic());
return true;
}
break;
case IrOpcode::kSelect:
if (SetEscaped(rep)) {
TRACE("Setting #%d (%s) to escaped because of use by #%d (%s)\n",
rep->id(), rep->op()->mnemonic(), use->id(),
use->op()->mnemonic());
return true;
}
break;
default:
if (use->op()->EffectInputCount() == 0 &&
uses->op()->EffectInputCount() > 0) {
TRACE("Encountered unaccounted use by #%d (%s)\n", use->id(),
use->op()->mnemonic());
UNREACHABLE();
}
if (SetEscaped(rep)) {
TRACE("Setting #%d (%s) to escaped because of use by #%d (%s)\n",
rep->id(), rep->op()->mnemonic(), use->id(),
use->op()->mnemonic());
return true;
}
}
}
return false;
}
void EscapeStatusAnalysis::ProcessFinishRegion(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kFinishRegion);
if (!HasEntry(node)) {
status_[node->id()] |= kTracked;
RevisitUses(node);
}
if (CheckUsesForEscape(node, true)) {
RevisitInputs(node);
}
}
void EscapeStatusAnalysis::DebugPrint() {
for (NodeId id = 0; id < status_.size(); id++) {
if (status_[id] & kTracked) {
PrintF("Node #%d is %s\n", id,
(status_[id] & kEscaped) ? "escaping" : "virtual");
}
}
}
EscapeAnalysis::EscapeAnalysis(Graph* graph, CommonOperatorBuilder* common,
Zone* zone)
: status_analysis_(this, graph, zone),
common_(common),
virtual_states_(zone),
replacements_(zone),
cache_(nullptr) {}
EscapeAnalysis::~EscapeAnalysis() {}
void EscapeAnalysis::Run() {
replacements_.resize(graph()->NodeCount());
status_analysis_.AssignAliases();
if (status_analysis_.AliasCount() > 0) {
cache_ = new (zone()) MergeCache(zone());
replacements_.resize(graph()->NodeCount());
status_analysis_.ResizeStatusVector();
RunObjectAnalysis();
status_analysis_.RunStatusAnalysis();
}
}
void EscapeStatusAnalysis::AssignAliases() {
size_t max_size = 1024;
size_t min_size = 32;
size_t stack_size =
std::min(std::max(graph()->NodeCount() / 5, min_size), max_size);
stack_.reserve(stack_size);
ResizeStatusVector();
stack_.push_back(graph()->end());
CHECK_LT(graph()->NodeCount(), kUntrackable);
aliases_.resize(graph()->NodeCount(), kNotReachable);
aliases_[graph()->end()->id()] = kUntrackable;
status_stack_.reserve(8);
TRACE("Discovering trackable nodes");
while (!stack_.empty()) {
Node* node = stack_.back();
stack_.pop_back();
switch (node->opcode()) {
case IrOpcode::kAllocate:
if (aliases_[node->id()] >= kUntrackable) {
aliases_[node->id()] = NextAlias();
TRACE(" @%d:%s#%u", aliases_[node->id()], node->op()->mnemonic(),
node->id());
EnqueueForStatusAnalysis(node);
}
break;
case IrOpcode::kFinishRegion: {
Node* allocate = NodeProperties::GetValueInput(node, 0);
DCHECK_NOT_NULL(allocate);
if (allocate->opcode() == IrOpcode::kAllocate) {
if (aliases_[allocate->id()] >= kUntrackable) {
if (aliases_[allocate->id()] == kNotReachable) {
stack_.push_back(allocate);
}
aliases_[allocate->id()] = NextAlias();
TRACE(" @%d:%s#%u", aliases_[allocate->id()],
allocate->op()->mnemonic(), allocate->id());
EnqueueForStatusAnalysis(allocate);
}
aliases_[node->id()] = aliases_[allocate->id()];
TRACE(" @%d:%s#%u", aliases_[node->id()], node->op()->mnemonic(),
node->id());
}
break;
}
default:
DCHECK_EQ(aliases_[node->id()], kUntrackable);
break;
}
for (Edge edge : node->input_edges()) {
Node* input = edge.to();
if (aliases_[input->id()] == kNotReachable) {
stack_.push_back(input);
aliases_[input->id()] = kUntrackable;
}
}
}
TRACE("\n");
}
bool EscapeStatusAnalysis::IsNotReachable(Node* node) {
if (node->id() >= aliases_.size()) {
return false;
}
return aliases_[node->id()] == kNotReachable;
}
void EscapeAnalysis::RunObjectAnalysis() {
virtual_states_.resize(graph()->NodeCount());
ZoneDeque<Node*> queue(zone());
queue.push_back(graph()->start());
ZoneVector<Node*> danglers(zone());
while (!queue.empty()) {
Node* node = queue.back();
queue.pop_back();
status_analysis_.SetInQueue(node->id(), false);
if (Process(node)) {
for (Edge edge : node->use_edges()) {
Node* use = edge.from();
if (IsNotReachable(use)) {
continue;
}
if (NodeProperties::IsEffectEdge(edge)) {
// Iteration order: depth first, but delay phis.
// We need DFS do avoid some duplication of VirtualStates and
// VirtualObjects, and we want to delay phis to improve performance.
if (use->opcode() == IrOpcode::kEffectPhi) {
if (!status_analysis_.IsInQueue(use->id())) {
queue.push_front(use);
}
} else if ((use->opcode() != IrOpcode::kLoadField &&
use->opcode() != IrOpcode::kLoadElement) ||
!IsDanglingEffectNode(use)) {
if (!status_analysis_.IsInQueue(use->id())) {
status_analysis_.SetInQueue(use->id(), true);
queue.push_back(use);
}
} else {
danglers.push_back(use);
}
}
}
// Danglers need to be processed immediately, even if they are
// on the stack. Since they do not have effect outputs,
// we don't have to track whether they are on the stack.
#if USING_VC6RT == 1
for (auto it = danglers.begin(); it != danglers.end(); ++it) {
queue.push_back(*it);
}
#else
queue.insert(queue.end(), danglers.begin(), danglers.end());
#endif
danglers.clear();
}
}
#ifdef DEBUG
if (FLAG_trace_turbo_escape) {
DebugPrint();
}
#endif
}
bool EscapeStatusAnalysis::IsDanglingEffectNode(Node* node) {
if (status_[node->id()] & kDanglingComputed) {
return status_[node->id()] & kDangling;
}
if (node->op()->EffectInputCount() == 0 ||
node->op()->EffectOutputCount() == 0 ||
(node->op()->EffectInputCount() == 1 &&
NodeProperties::GetEffectInput(node)->opcode() == IrOpcode::kStart)) {
// The start node is used as sentinel for nodes that are in general
// effectful, but of which an analysis has determined that they do not
// produce effects in this instance. We don't consider these nodes dangling.
status_[node->id()] |= kDanglingComputed;
return false;
}
for (Edge edge : node->use_edges()) {
Node* use = edge.from();
if (aliases_[use->id()] == kNotReachable) continue;
if (NodeProperties::IsEffectEdge(edge)) {
status_[node->id()] |= kDanglingComputed;
return false;
}
}
status_[node->id()] |= kDanglingComputed | kDangling;
return true;
}
bool EscapeStatusAnalysis::IsEffectBranchPoint(Node* node) {
if (status_[node->id()] & kBranchPointComputed) {
return status_[node->id()] & kBranchPoint;
}
int count = 0;
for (Edge edge : node->use_edges()) {
Node* use = edge.from();
if (aliases_[use->id()] == kNotReachable) continue;
if (NodeProperties::IsEffectEdge(edge)) {
if ((use->opcode() == IrOpcode::kLoadField ||
use->opcode() == IrOpcode::kLoadElement ||
use->opcode() == IrOpcode::kLoad) &&
IsDanglingEffectNode(use))
continue;
if (++count > 1) {
status_[node->id()] |= kBranchPointComputed | kBranchPoint;
return true;
}
}
}
status_[node->id()] |= kBranchPointComputed;
return false;
}
bool EscapeAnalysis::Process(Node* node) {
switch (node->opcode()) {
case IrOpcode::kAllocate:
ProcessAllocation(node);
break;
case IrOpcode::kBeginRegion:
ForwardVirtualState(node);
break;
case IrOpcode::kFinishRegion:
ProcessFinishRegion(node);
break;
case IrOpcode::kStoreField:
ProcessStoreField(node);
break;
case IrOpcode::kLoadField:
ProcessLoadField(node);
break;
case IrOpcode::kStoreElement:
ProcessStoreElement(node);
break;
case IrOpcode::kLoadElement:
ProcessLoadElement(node);
break;
case IrOpcode::kStart:
ProcessStart(node);
break;
case IrOpcode::kEffectPhi:
return ProcessEffectPhi(node);
break;
default:
if (node->op()->EffectInputCount() > 0) {
ForwardVirtualState(node);
}
ProcessAllocationUsers(node);
break;
}
return true;
}
void EscapeAnalysis::ProcessAllocationUsers(Node* node) {
for (Edge edge : node->input_edges()) {
Node* input = edge.to();
Node* use = edge.from();
if (edge.index() >= use->op()->ValueInputCount() +
OperatorProperties::GetContextInputCount(use->op()))
continue;
switch (node->opcode()) {
case IrOpcode::kStoreField:
case IrOpcode::kLoadField:
case IrOpcode::kStoreElement:
case IrOpcode::kLoadElement:
case IrOpcode::kFrameState:
case IrOpcode::kStateValues:
case IrOpcode::kReferenceEqual:
case IrOpcode::kFinishRegion:
case IrOpcode::kObjectIsSmi:
break;
default:
VirtualState* state = virtual_states_[node->id()];
if (VirtualObject* obj =
GetVirtualObject(state, ResolveReplacement(input))) {
if (!obj->AllFieldsClear()) {
obj = CopyForModificationAt(obj, state, node);
obj->ClearAllFields();
TRACE("Cleared all fields of @%d:#%d\n", GetAlias(obj->id()),
obj->id());
}
}
break;
}
}
}
VirtualState* EscapeAnalysis::CopyForModificationAt(VirtualState* state,
Node* node) {
if (state->owner() != node) {
VirtualState* new_state = new (zone()) VirtualState(node, *state);
virtual_states_[node->id()] = new_state;
TRACE("Copying virtual state %p to new state %p at node %s#%d\n",
static_cast<void*>(state), static_cast<void*>(new_state),
node->op()->mnemonic(), node->id());
return new_state;
}
return state;
}
VirtualObject* EscapeAnalysis::CopyForModificationAt(VirtualObject* obj,
VirtualState* state,
Node* node) {
if (obj->NeedCopyForModification()) {
state = CopyForModificationAt(state, node);
return state->Copy(obj, GetAlias(obj->id()));
}
return obj;
}
void EscapeAnalysis::ForwardVirtualState(Node* node) {
DCHECK_EQ(node->op()->EffectInputCount(), 1);
#ifdef DEBUG
if (node->opcode() != IrOpcode::kLoadField &&
node->opcode() != IrOpcode::kLoadElement &&
node->opcode() != IrOpcode::kLoad && IsDanglingEffectNode(node)) {
PrintF("Dangeling effect node: #%d (%s)\n", node->id(),
node->op()->mnemonic());
UNREACHABLE();
}
#endif // DEBUG
Node* effect = NodeProperties::GetEffectInput(node);
DCHECK_NOT_NULL(virtual_states_[effect->id()]);
if (virtual_states_[node->id()]) {
virtual_states_[node->id()]->UpdateFrom(virtual_states_[effect->id()],
zone());
} else {
virtual_states_[node->id()] = virtual_states_[effect->id()];
TRACE("Forwarding object state %p from %s#%d to %s#%d",
static_cast<void*>(virtual_states_[effect->id()]),
effect->op()->mnemonic(), effect->id(), node->op()->mnemonic(),
node->id());
if (IsEffectBranchPoint(effect) ||
OperatorProperties::GetFrameStateInputCount(node->op()) > 0) {
virtual_states_[node->id()]->SetCopyRequired();
TRACE(", effect input %s#%d is branch point", effect->op()->mnemonic(),
effect->id());
}
TRACE("\n");
}
}
void EscapeAnalysis::ProcessStart(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kStart);
virtual_states_[node->id()] =
new (zone()) VirtualState(node, zone(), AliasCount());
}
bool EscapeAnalysis::ProcessEffectPhi(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kEffectPhi);
bool changed = false;
VirtualState* mergeState = virtual_states_[node->id()];
if (!mergeState) {
mergeState = new (zone()) VirtualState(node, zone(), AliasCount());
virtual_states_[node->id()] = mergeState;
changed = true;
TRACE("Effect Phi #%d got new virtual state %p.\n", node->id(),
static_cast<void*>(mergeState));
}
cache_->Clear();
TRACE("At Effect Phi #%d, merging states into %p:", node->id(),
static_cast<void*>(mergeState));
for (int i = 0; i < node->op()->EffectInputCount(); ++i) {
Node* input = NodeProperties::GetEffectInput(node, i);
VirtualState* state = virtual_states_[input->id()];
if (state) {
cache_->states().push_back(state);
if (state == mergeState) {
mergeState = new (zone()) VirtualState(node, zone(), AliasCount());
virtual_states_[node->id()] = mergeState;
changed = true;
}
}
TRACE(" %p (from %d %s)", static_cast<void*>(state), input->id(),
input->op()->mnemonic());
}
TRACE("\n");
if (cache_->states().size() == 0) {
return changed;
}
changed =
mergeState->MergeFrom(cache_, zone(), graph(), common(), node) || changed;
TRACE("Merge %s the node.\n", changed ? "changed" : "did not change");
if (changed) {
status_analysis_.ResizeStatusVector();
}
return changed;
}
void EscapeAnalysis::ProcessAllocation(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kAllocate);
ForwardVirtualState(node);
VirtualState* state = virtual_states_[node->id()];
Alias alias = GetAlias(node->id());
// Check if we have already processed this node.
if (state->VirtualObjectFromAlias(alias)) {
return;
}
if (state->owner()->opcode() == IrOpcode::kEffectPhi) {
state = CopyForModificationAt(state, node);
}
NumberMatcher size(node->InputAt(0));
DCHECK(node->InputAt(0)->opcode() != IrOpcode::kInt32Constant &&
node->InputAt(0)->opcode() != IrOpcode::kInt64Constant &&
node->InputAt(0)->opcode() != IrOpcode::kFloat32Constant &&
node->InputAt(0)->opcode() != IrOpcode::kFloat64Constant);
if (size.HasValue()) {
VirtualObject* obj = new (zone()) VirtualObject(
node->id(), state, zone(), size.Value() / kPointerSize, false);
state->SetVirtualObject(alias, obj);
} else {
state->SetVirtualObject(
alias, new (zone()) VirtualObject(node->id(), state, zone()));
}
}
void EscapeAnalysis::ProcessFinishRegion(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kFinishRegion);
ForwardVirtualState(node);
Node* allocation = NodeProperties::GetValueInput(node, 0);
if (allocation->opcode() == IrOpcode::kAllocate) {
VirtualState* state = virtual_states_[node->id()];
VirtualObject* obj = state->VirtualObjectFromAlias(GetAlias(node->id()));
DCHECK_NOT_NULL(obj);
obj->SetInitialized();
}
}
Node* EscapeAnalysis::replacement(NodeId id) {
if (id >= replacements_.size()) return nullptr;
return replacements_[id];
}
Node* EscapeAnalysis::replacement(Node* node) {
return replacement(node->id());
}
bool EscapeAnalysis::SetReplacement(Node* node, Node* rep) {
bool changed = replacements_[node->id()] != rep;
replacements_[node->id()] = rep;
return changed;
}
bool EscapeAnalysis::UpdateReplacement(VirtualState* state, Node* node,
Node* rep) {
if (SetReplacement(node, rep)) {
if (rep) {
TRACE("Replacement of #%d is #%d (%s)\n", node->id(), rep->id(),
rep->op()->mnemonic());
} else {
TRACE("Replacement of #%d cleared\n", node->id());
}
return true;
}
return false;
}
Node* EscapeAnalysis::ResolveReplacement(Node* node) {
while (replacement(node)) {
node = replacement(node);
}
return node;
}
Node* EscapeAnalysis::GetReplacement(Node* node) {
return GetReplacement(node->id());
}
Node* EscapeAnalysis::GetReplacement(NodeId id) {
Node* node = nullptr;
while (replacement(id)) {
node = replacement(id);
id = node->id();
}
return node;
}
bool EscapeAnalysis::IsVirtual(Node* node) {
if (node->id() >= status_analysis_.GetStatusVectorSize()) {
return false;
}
return status_analysis_.IsVirtual(node);
}
bool EscapeAnalysis::IsEscaped(Node* node) {
if (node->id() >= status_analysis_.GetStatusVectorSize()) {
return false;
}
return status_analysis_.IsEscaped(node);
}
bool EscapeAnalysis::SetEscaped(Node* node) {
return status_analysis_.SetEscaped(node);
}
VirtualObject* EscapeAnalysis::GetVirtualObject(Node* at, NodeId id) {
if (VirtualState* states = virtual_states_[at->id()]) {
return states->VirtualObjectFromAlias(GetAlias(id));
}
return nullptr;
}
bool EscapeAnalysis::CompareVirtualObjects(Node* left, Node* right) {
DCHECK(IsVirtual(left) && IsVirtual(right));
left = ResolveReplacement(left);
right = ResolveReplacement(right);
if (IsEquivalentPhi(left, right)) {
return true;
}
return false;
}
int EscapeAnalysis::OffsetFromAccess(Node* node) {
DCHECK(OpParameter<FieldAccess>(node).offset % kPointerSize == 0);
return OpParameter<FieldAccess>(node).offset / kPointerSize;
}
void EscapeAnalysis::ProcessLoadFromPhi(int offset, Node* from, Node* load,
VirtualState* state) {
TRACE("Load #%d from phi #%d", load->id(), from->id());
cache_->fields().clear();
for (int i = 0; i < load->op()->ValueInputCount(); ++i) {
Node* input = NodeProperties::GetValueInput(load, i);
cache_->fields().push_back(input);
}
cache_->LoadVirtualObjectsForFieldsFrom(state,
status_analysis_.GetAliasMap());
if (cache_->objects().size() == cache_->fields().size()) {
cache_->GetFields(offset);
if (cache_->fields().size() == cache_->objects().size()) {
Node* rep = replacement(load);
if (!rep || !IsEquivalentPhi(rep, cache_->fields())) {
int value_input_count = static_cast<int>(cache_->fields().size());
cache_->fields().push_back(NodeProperties::GetControlInput(from));
Node* phi = graph()->NewNode(
common()->Phi(MachineRepresentation::kTagged, value_input_count),
value_input_count + 1, &cache_->fields().front());
status_analysis_.ResizeStatusVector();
SetReplacement(load, phi);
TRACE(" got phi created.\n");
} else {
TRACE(" has already phi #%d.\n", rep->id());
}
} else {
TRACE(" has incomplete field info.\n");
}
} else {
TRACE(" has incomplete virtual object info.\n");
}
}
void EscapeAnalysis::ProcessLoadField(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kLoadField);
ForwardVirtualState(node);
Node* from = ResolveReplacement(NodeProperties::GetValueInput(node, 0));
VirtualState* state = virtual_states_[node->id()];
if (VirtualObject* object = GetVirtualObject(state, from)) {
int offset = OffsetFromAccess(node);
if (!object->IsTracked() ||
static_cast<size_t>(offset) >= object->field_count()) {
return;
}
Node* value = object->GetField(offset);
if (value) {
value = ResolveReplacement(value);
}
// Record that the load has this alias.
UpdateReplacement(state, node, value);
} else if (from->opcode() == IrOpcode::kPhi &&
OpParameter<FieldAccess>(node).offset % kPointerSize == 0) {
int offset = OffsetFromAccess(node);
// Only binary phis are supported for now.
ProcessLoadFromPhi(offset, from, node, state);
} else {
UpdateReplacement(state, node, nullptr);
}
}
void EscapeAnalysis::ProcessLoadElement(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kLoadElement);
ForwardVirtualState(node);
Node* from = ResolveReplacement(NodeProperties::GetValueInput(node, 0));
VirtualState* state = virtual_states_[node->id()];
Node* index_node = node->InputAt(1);
NumberMatcher index(index_node);
DCHECK(index_node->opcode() != IrOpcode::kInt32Constant &&
index_node->opcode() != IrOpcode::kInt64Constant &&
index_node->opcode() != IrOpcode::kFloat32Constant &&
index_node->opcode() != IrOpcode::kFloat64Constant);
ElementAccess access = OpParameter<ElementAccess>(node);
if (index.HasValue()) {
int offset = index.Value() + access.header_size / kPointerSize;
if (VirtualObject* object = GetVirtualObject(state, from)) {
CHECK_GE(ElementSizeLog2Of(access.machine_type.representation()),
kPointerSizeLog2);
CHECK_EQ(access.header_size % kPointerSize, 0);
if (!object->IsTracked() ||
static_cast<size_t>(offset) >= object->field_count()) {
return;
}
Node* value = object->GetField(offset);
if (value) {
value = ResolveReplacement(value);
}
// Record that the load has this alias.
UpdateReplacement(state, node, value);
} else if (from->opcode() == IrOpcode::kPhi) {
ElementAccess access = OpParameter<ElementAccess>(node);
int offset = index.Value() + access.header_size / kPointerSize;
ProcessLoadFromPhi(offset, from, node, state);
} else {
UpdateReplacement(state, node, nullptr);
}
} else {
// We have a load from a non-const index, cannot eliminate object.
if (SetEscaped(from)) {
TRACE(
"Setting #%d (%s) to escaped because load element #%d from non-const "
"index #%d (%s)\n",
from->id(), from->op()->mnemonic(), node->id(), index_node->id(),
index_node->op()->mnemonic());
}
}
}
void EscapeAnalysis::ProcessStoreField(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kStoreField);
ForwardVirtualState(node);
Node* to = ResolveReplacement(NodeProperties::GetValueInput(node, 0));
VirtualState* state = virtual_states_[node->id()];
VirtualObject* obj = GetVirtualObject(state, to);
int offset = OffsetFromAccess(node);
if (obj && obj->IsTracked() &&
static_cast<size_t>(offset) < obj->field_count()) {
Node* val = ResolveReplacement(NodeProperties::GetValueInput(node, 1));
if (obj->GetField(offset) != val) {
obj = CopyForModificationAt(obj, state, node);
obj->SetField(offset, val);
}
}
}
void EscapeAnalysis::ProcessStoreElement(Node* node) {
DCHECK_EQ(node->opcode(), IrOpcode::kStoreElement);
ForwardVirtualState(node);
Node* to = ResolveReplacement(NodeProperties::GetValueInput(node, 0));
Node* index_node = node->InputAt(1);
NumberMatcher index(index_node);
DCHECK(index_node->opcode() != IrOpcode::kInt32Constant &&
index_node->opcode() != IrOpcode::kInt64Constant &&
index_node->opcode() != IrOpcode::kFloat32Constant &&
index_node->opcode() != IrOpcode::kFloat64Constant);
ElementAccess access = OpParameter<ElementAccess>(node);
VirtualState* state = virtual_states_[node->id()];
VirtualObject* obj = GetVirtualObject(state, to);
if (index.HasValue()) {
int offset = index.Value() + access.header_size / kPointerSize;
if (obj && obj->IsTracked() &&
static_cast<size_t>(offset) < obj->field_count()) {
CHECK_GE(ElementSizeLog2Of(access.machine_type.representation()),
kPointerSizeLog2);
CHECK_EQ(access.header_size % kPointerSize, 0);
Node* val = ResolveReplacement(NodeProperties::GetValueInput(node, 2));
if (obj->GetField(offset) != val) {
obj = CopyForModificationAt(obj, state, node);
obj->SetField(offset, val);
}
}
} else {
// We have a store to a non-const index, cannot eliminate object.
if (SetEscaped(to)) {
TRACE(
"Setting #%d (%s) to escaped because store element #%d to non-const "
"index #%d (%s)\n",
to->id(), to->op()->mnemonic(), node->id(), index_node->id(),
index_node->op()->mnemonic());
}
if (obj && obj->IsTracked()) {
if (!obj->AllFieldsClear()) {
obj = CopyForModificationAt(obj, state, node);
obj->ClearAllFields();
TRACE("Cleared all fields of @%d:#%d\n", GetAlias(obj->id()),
obj->id());
}
}
}
}
Node* EscapeAnalysis::GetOrCreateObjectState(Node* effect, Node* node) {
if ((node->opcode() == IrOpcode::kFinishRegion ||
node->opcode() == IrOpcode::kAllocate) &&
IsVirtual(node)) {
if (VirtualObject* vobj = GetVirtualObject(virtual_states_[effect->id()],
ResolveReplacement(node))) {
if (Node* object_state = vobj->GetObjectState()) {
return object_state;
} else {
cache_->fields().clear();
for (size_t i = 0; i < vobj->field_count(); ++i) {
if (Node* field = vobj->GetField(i)) {
cache_->fields().push_back(field);
}
}
int input_count = static_cast<int>(cache_->fields().size());
Node* new_object_state =
graph()->NewNode(common()->ObjectState(input_count, vobj->id()),
input_count, &cache_->fields().front());
vobj->SetObjectState(new_object_state);
TRACE(
"Creating object state #%d for vobj %p (from node #%d) at effect "
"#%d\n",
new_object_state->id(), static_cast<void*>(vobj), node->id(),
effect->id());
// Now fix uses of other objects.
for (size_t i = 0; i < vobj->field_count(); ++i) {
if (Node* field = vobj->GetField(i)) {
if (Node* field_object_state =
GetOrCreateObjectState(effect, field)) {
NodeProperties::ReplaceValueInput(
new_object_state, field_object_state, static_cast<int>(i));
}
}
}
return new_object_state;
}
}
}
return nullptr;
}
void EscapeAnalysis::DebugPrintObject(VirtualObject* object, Alias alias) {
PrintF(" Alias @%d: Object #%d with %zu fields\n", alias, object->id(),
object->field_count());
for (size_t i = 0; i < object->field_count(); ++i) {
if (Node* f = object->GetField(i)) {
PrintF(" Field %zu = #%d (%s)\n", i, f->id(), f->op()->mnemonic());
}
}
}
void EscapeAnalysis::DebugPrintState(VirtualState* state) {
PrintF("Dumping virtual state %p\n", static_cast<void*>(state));
for (Alias alias = 0; alias < AliasCount(); ++alias) {
if (VirtualObject* object = state->VirtualObjectFromAlias(alias)) {
DebugPrintObject(object, alias);
}
}
}
void EscapeAnalysis::DebugPrint() {
ZoneVector<VirtualState*> object_states(zone());
for (NodeId id = 0; id < virtual_states_.size(); id++) {
if (VirtualState* states = virtual_states_[id]) {
if (std::find(object_states.begin(), object_states.end(), states) ==
object_states.end()) {
object_states.push_back(states);
}
}
}
for (size_t n = 0; n < object_states.size(); n++) {
DebugPrintState(object_states[n]);
}
}
VirtualObject* EscapeAnalysis::GetVirtualObject(VirtualState* state,
Node* node) {
if (node->id() >= status_analysis_.GetAliasMap().size()) return nullptr;
Alias alias = GetAlias(node->id());
if (alias >= state->size()) return nullptr;
return state->VirtualObjectFromAlias(alias);
}
bool EscapeAnalysis::ExistsVirtualAllocate() {
for (size_t id = 0; id < status_analysis_.GetAliasMap().size(); ++id) {
Alias alias = GetAlias(static_cast<NodeId>(id));
if (alias < EscapeStatusAnalysis::kUntrackable) {
if (status_analysis_.IsVirtual(static_cast<int>(id))) {
return true;
}
}
}
return false;
}
} // namespace compiler
} // namespace internal
} // namespace v8
| [
"[email protected]"
] | |
d7f285bd3184948effd64d2295d2b6baad63e62c | 470ef861b8ae008990a3cab81ee1d1304939c5cc | /query/test.cpp | ef86f99a5fcb5d13bac34744cbceec2dd88bffe6 | [] | no_license | zigzed/indexs | 2cffe4e2f7735bb816cd058d8d3a45a5d987af8c | 2a63911928b7b95dbe7094c32e8dd553e72fd53d | refs/heads/master | 2021-01-22T08:13:58.008890 | 2013-01-27T10:08:12 | 2013-01-27T10:08:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | cpp | /** Copyright (C) 2013 [email protected]
*/
#include "common/config.h"
#include "common/gtest/gtest.h"
#include "query.h"
TEST(query, usage)
{
idx::query search("db");
idx::record result = search.find("大家 好处");
idx::record::brief b = result.matched();
while(!b.file.empty()) {
std::cout << "file: " << b.file << "\n"
<< " : " << b.line << "\n"
<< " : " << b.key << "\n\n";
b = result.matched();
}
}
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"[email protected]"
] | |
998a847b1acaf0090def59553a2bcf314d9d8f96 | 251aaf143dab1a24322cd47416e2a14de76bf773 | /STM32F469_Controller/Source/TouchGFX/TouchGFX/gui/include/gui/containers/FileItem.hpp | dff9977ce2e1a9c2aba431a700ef864dd3a4aa8d | [
"Zlib"
] | permissive | ftkalcevic/DCC | fddc7de6cc6c2c4b758451c444f7cc0131897224 | b68aebab35423f21e0a6a337c11d967f6f8912a2 | refs/heads/master | 2022-12-10T12:24:52.928864 | 2020-07-30T08:16:46 | 2020-07-30T08:16:46 | 121,176,875 | 0 | 0 | null | 2022-12-08T10:16:01 | 2018-02-11T23:12:08 | C | UTF-8 | C++ | false | false | 350 | hpp | #ifndef FILEITEM_HPP
#define FILEITEM_HPP
#include <gui_generated/containers/FileItemBase.hpp>
class FileItem : public FileItemBase
{
public:
FileItem();
virtual ~FileItem() {}
virtual void initialize();
void setText(const char16_t *s)
{
text.setWildcard((const Unicode::UnicodeChar*)s);
}
protected:
};
#endif // FILEITEM_HPP
| [
"[email protected]"
] | |
6d4f77db23e25435be51df9edff94a36de99dd6e | 6b33c9cc25bbdc43581af99306d55d4de97484bd | /object_recognition_ros_visualization/src/rviz_plugin/ork_object_visual.cpp | e30f3224078b2b7c76493f9aedc65ce4f1dca9b1 | [] | no_license | hajungong007/vision | 6cd12236348dc432d8f5dce893f06f053e7d20d0 | ef59daf12830c804fcabc2e275a8899a5a28493a | refs/heads/master | 2021-01-20T11:51:12.773805 | 2016-06-24T12:04:07 | 2016-06-24T12:04:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,247 | cpp | /*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <OGRE/OgreCommon.h>
#include <OGRE/OgreEntity.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSubEntity.h>
#include <OGRE/OgreVector3.h>
#include <rviz/display_context.h>
#include <rviz/display_factory.h>
#include <rviz/default_plugin/marker_display.h>
#include <rviz/ogre_helpers/arrow.h>
#include <rviz/ogre_helpers/axes.h>
#include <rviz/ogre_helpers/movable_text.h>
#include "ork_object_visual.h"
namespace object_recognition_ros
{
// BEGIN_TUTORIAL
OrkObjectVisual::OrkObjectVisual(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node,
rviz::DisplayContext* display_context) : display_context_(display_context),
mesh_entity_(0)
{
scene_manager_ = scene_manager;
// Ogre::SceneNode s form a tree, with each node storing the
// transform (position and orientation) of itself relative to its
// parent. Ogre does the math of combining those transforms when it
// is time to render.
//
// Here we create a node to store the pose of the Imu's header frame
// relative to the RViz fixed frame.
frame_node_ = parent_node->createChildSceneNode();
object_node_ = frame_node_->createChildSceneNode();
// Initialize the axes
axes_.reset(new rviz::Axes(scene_manager_, object_node_));
axes_->setScale(Ogre::Vector3(0.1, 0.1, 0.1));
// Initialize the name
name_.reset(new rviz::MovableText("EMPTY"));
name_->setTextAlignment(rviz::MovableText::H_CENTER,
rviz::MovableText::V_CENTER);
name_->setCharacterHeight(0.08);
name_->showOnTop();
name_->setColor(Ogre::ColourValue::White);
name_->setVisible(false);
object_node_->attachObject(name_.get());
}
OrkObjectVisual::~OrkObjectVisual()
{
// Destroy the frame node since we don't need it anymore.
if (mesh_entity_) {
display_context_->getSceneManager()->destroyEntity(mesh_entity_);
mesh_entity_ = 0;
}
scene_manager_->destroySceneNode(object_node_);
scene_manager_->destroySceneNode(frame_node_);
}
void
OrkObjectVisual::setMessage(const object_recognition_msgs::RecognizedObject& object, const std::string& name, const std::string& mesh_resource,
bool do_display_id, bool do_display_name, bool do_display_confidence)
{
Ogre::Vector3 position(object.pose.pose.pose.position.x,
object.pose.pose.pose.position.y,
object.pose.pose.pose.position.z);
object_node_->setOrientation(
Ogre::Quaternion(object.pose.pose.pose.orientation.w,
object.pose.pose.pose.orientation.x,
object.pose.pose.pose.orientation.y,
object.pose.pose.pose.orientation.z));
object_node_->setPosition(position);
// Set the name of the object
std::stringstream caption;
if ((!object.type.key.empty()) && (do_display_id))
caption << object.type.key << std::endl;
if ((!name.empty()) && (do_display_name))
caption << name << std::endl;
// Set the caption of the object
if (do_display_confidence)
caption << object.confidence;
if (caption.str().empty())
name_->setVisible(false);
else {
name_->setCaption(caption.str());
name_->setVisible(true);
name_->setLocalTranslation(Ogre::Vector3(0.1, 0, 0));
}
if (!mesh_resource.empty()) {
static uint32_t count = 0;
std::stringstream ss;
ss << "ork_mesh_resource_marker_" << count++;
std::string id = ss.str();
mesh_entity_ = display_context_->getSceneManager()->createEntity(
id, mesh_resource);
Ogre::MaterialPtr material = mesh_entity_->getSubEntity(0)->getMaterial();
material->setAmbient(0, 255, 0);
material->setDiffuse(0, 255, 0, 1);
material->setSpecular(0, 255, 0, 1);
material->setCullingMode(Ogre::CULL_NONE);
mesh_entity_->setMaterial(material);
object_node_->attachObject(mesh_entity_);
// In Ogre, mesh surface normals are not normalized if object is not
// scaled. This forces the surface normals to be renormalized by
// invisibly tweaking the scale.
Ogre::Vector3 scale(1, 1, 1.0001);
frame_node_->setScale(scale);
}
}
// Position and orientation are passed through to the SceneNode.
void
OrkObjectVisual::setFramePosition(const Ogre::Vector3& position)
{
frame_node_->setPosition(position);
}
void
OrkObjectVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
frame_node_->setOrientation(orientation);
}
} // end namespace object_recognition_ros
| [
"[email protected]"
] | |
4950454b37ac8ed2c0fd4c583fd790df24656c20 | 721afc5f47aff426a0aad789b9579197ff0ecc75 | /SQF/dayz_code/Configs/CfgVehicles/DZE/Doors.hpp | 5d1a6ff44ff20bd55c51ba8a9aa8f025624b9f90 | [] | no_license | CON5T4R/DayZ-Epoch | bb147364204843cab200ceb5e30d7637fc19297e | 74e0859e02adf58c4d943224b8d0ef2c524eecbd | refs/heads/master | 2021-01-22T14:15:17.539267 | 2013-10-17T17:30:20 | 2013-10-17T17:30:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,845 | hpp | /* Again your very own basic definition*/
class DZE_Base_Object : All {
scope = 0;
side = 3;
icon = "\ca\data\data\Unknown_object.paa";
nameSound = "object";
simulation = "house";
picture = "pictureStaticObject";
model="";
sound = "Building";
placement = "vertical";
ladders[] = {};
vehicleClass = "";
displayName = "";
coefInside = 1;
coefInsideHeur = 0.25;
mapSize = 7.5;
animated = true;
armor = 200;
destrType = "DestructBuilding";
damageResistance = 0.004;
class DestructionEffects {
class Sound {
simulation = "sound";
type = "DestrHouse";
position = "destructionEffect1";
intensity = 1;
interval = 1;
lifeTime = 0.05;
};
class DestroyPhase1 {
simulation = "destroy";
type = "DelayedDestruction";
lifeTime = 2.5;
position = "";
intensity = 1;
interval = 1;
};
class DamageAround1 {
simulation = "damageAround";
type = "DamageAroundHouse";
position = "";
intensity = 1;
interval = 1;
lifeTime = 1;
};
};
};
/* Your very own base class for buildings*/
class DZE_Housebase : DZE_Base_Object {
scope = 1;
model = "";
icon = "";
displayName = "";
animated = true;
vehicleClass = "Fortifications";
nameSound = "house";
accuracy = 0.2;
typicalCargo[] = {};
transportAmmo = 0;
transportRepair = 0;
transportFuel = 0;
mapSize = 11;
cost = 0;
armor = 800;
reversed = 0;
/*extern*/ class DestructionEffects;
};
class Land_DZE_WoodDoor_Base: DZE_Housebase {
model = "\z\addons\dayz_epoch\models\small_wall_door_anim.p3d"; /* path to the object */
displayName = "Wood Door Base"; /* entry in Stringtable.csv */
nameSound = "";
mapSize = 8; /* Size of the icon */
icon = "\ca\data\data\Unknown_object.paa"; /* Path to the picture shown in the editor. */
accuracy = 1000;
armor = 200; /* "Lifepoints", if you like to call it that way.*/
destrType = "DestructBuilding"; /* type of destruction, when armor = 0 */
scope = 2; /* Display it in the editor? 1 = No, 2 = Yes */
offset[] = {0,1.5,0};
class DestructionEffects : DestructionEffects
{
class Ruin1
{
simulation = "ruin";
type = "\z\addons\dayz_epoch\models\wood_wreck_frame.p3d"; /* path to the object*/
/* Warning, if you use a custom rubble model, it has to be defined in the cfgvehicles (see below)*/
position = "";
intensity = 1;
interval = 1;
lifeTime = 1;
};
};
maintainBuilding[] = {{"PartWoodPlywood",1},{"PartWoodLumber",1}};
};
class Land_DZE_WoodDoorLocked_Base: DZE_Housebase {
model = "\z\addons\dayz_epoch\models\small_wall_door_anim.p3d"; /* path to the object */
displayName = "Wood Door Base"; /* entry in Stringtable.csv */
nameSound = "";
mapSize = 8; /* Size of the icon */
icon = "\ca\data\data\Unknown_object.paa"; /* Path to the picture shown in the editor. */
accuracy = 1000;
armor = 200; /* "Lifepoints", if you like to call it that way.*/
destrType = "DestructBuilding"; /* type of destruction, when armor = 0 */
scope = 2; /* Display it in the editor? 1 = No, 2 = Yes */
offset[] = {0,1.5,0};
class DestructionEffects : DestructionEffects
{
class Ruin1
{
simulation = "ruin";
type = "\z\addons\dayz_epoch\models\wood_wreck_frame.p3d"; /* path to the object*/
/* Warning, if you use a custom rubble model, it has to be defined in the cfgvehicles (see below)*/
position = "";
intensity = 1;
interval = 1;
lifeTime = 1;
};
};
maintainBuilding[] = {{"PartWoodPlywood",1},{"PartWoodLumber",1}};
lockable = 3;
};
class CinderWallDoor_DZ_Base: DZE_Housebase {
model = "\z\addons\dayz_epoch\models\steel_garage_door.p3d"; /* path to the object */
displayName = "Block Garage Door Base"; /* entry in Stringtable.csv */
nameSound = "";
mapSize = 8; /* Size of the icon */
icon = "\ca\data\data\Unknown_object.paa"; /* Path to the picture shown in the editor. */
accuracy = 1000;
armor = 1000; /* "Lifepoints", if you like to call it that way.*/
destrType = "DestructBuilding"; /* type of destruction, when armor = 0 */
scope = 2; /* Display it in the editor? 1 = No, 2 = Yes */
offset[] = {0,1.5,0};
maintainBuilding[] = {{"MortarBucket",1}};
class DestructionEffects : DestructionEffects
{
class Ruin1
{
simulation = "ruin";
type = "\z\addons\dayz_epoch\models\wreck_cinder.p3d"; /* path to the object*/
/* Warning, if you use a custom rubble model, it has to be defined in the cfgvehicles (see below)*/
position = "";
intensity = 1;
interval = 1;
lifeTime = 1;
};
};
};
class CinderWallDoorLocked_DZ_Base: DZE_Housebase {
model = "\z\addons\dayz_epoch\models\steel_garage_door.p3d"; /* path to the object */
displayName = "Block Garage Door Base"; /* entry in Stringtable.csv */
nameSound = "";
mapSize = 8; /* Size of the icon */
icon = "\ca\data\data\Unknown_object.paa"; /* Path to the picture shown in the editor. */
accuracy = 1000;
armor = 1000; /* "Lifepoints", if you like to call it that way.*/
destrType = "DestructBuilding"; /* type of destruction, when armor = 0 */
scope = 2; /* Display it in the editor? 1 = No, 2 = Yes */
offset[] = {0,1.5,0};
maintainBuilding[] = {{"MortarBucket",1}};
lockable = 3;
class DestructionEffects : DestructionEffects
{
class Ruin1
{
simulation = "ruin";
type = "\z\addons\dayz_epoch\models\wreck_cinder.p3d"; /* path to the object*/
/* Warning, if you use a custom rubble model, it has to be defined in the cfgvehicles (see below)*/
position = "";
intensity = 1;
interval = 1;
lifeTime = 1;
};
};
};
/* Same name as stated in the Class DestructionEffects, but an "Land_" added infront*/
class Land_wood_wreck_frame : ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\wood_wreck_frame.p3d";
displayName = "Wood Wall ruins";
removeoutput[] = {{"PartWoodPlywood",{0,3}},{"PartWoodLumber",{0,3}}};
};
class Land_wood_wreck_third : ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\wood_wreck_third.p3d";
displayName = "Wood Wall 1/3 ruins";
removeoutput[] = {{"PartWoodPlywood",{0,1}},{"PartWoodLumber",{0,1}}};
};
class Land_wood_wreck_half : ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\wood_wreck_half.p3d";
displayName = "Wood Floor 1/2 ruins";
removeoutput[] = {{"PartWoodPlywood",{0,1}},{"PartWoodLumber",{0,1}}};
};
class Land_wood_wreck_floor : ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\wood_wreck_floor.p3d";
displayName = "Wood Floor ruins";
removeoutput[] = {{"PartWoodPlywood",{0,3}},{"PartWoodLumber",{0,3}}};
};
class Land_wood_wreck_quarter : ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\wood_wreck_quarter.p3d";
displayName = "Wood Floor 1/4 ruins";
removeoutput[] = {{"PartWoodPlywood",{0,1}},{"PartWoodLumber",{0,1}}};
};
class Land_wreck_cinder: ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\wreck_cinder.p3d";
displayName = "Cinder wall ruins";
removeoutput[] = {{"CinderBlocks",{0,1}}};
};
class Land_wreck_metal_floor: ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\wreck_metal_floor.p3d";
displayName = "Metal Floor ruins";
removeoutput[] = {{"ItemPole",{0,2}},{"ItemTankTrap",{0,2}}};
};
class Land_iron_vein_wreck: ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\iron_vein_wreck.p3d";
displayName = "iron vein ruins";
removeoutput[] = {{"PartOre",{6,4}},{"PartOreSilver",{0,1}},{"PartOreGold",{0,1}}};
};
class Land_silver_vein_wreck: ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\silver_vein_wreck.p3d";
displayName = "silver vein ruins";
removeoutput[] = {{"PartOreSilver",{6,4}},{"PartOre",{0,1}},{"PartOreGold",{0,1}}};
};
class Land_gold_vein_wreck: ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\gold_vein_wreck.p3d";
displayName = "gold vein ruins";
removeoutput[] = {{"PartOreGold",{6,4}},{"PartOre",{0,1}},{"PartOreSilver",{0,1}}};
};
class Land_ammo_supply_wreck: ruins {
scope = 1;
model = "\z\addons\dayz_epoch\models\ammo_supply_wreck.p3d";
displayName = "Supply Crate";
removeoutput[] = {{"100Rnd_762x54_PK",{0,1}},{"29Rnd_30mm_AGS30",{0,1}},{"50Rnd_127x107_DSHKM",{0,1}},{"100Rnd_127x99_M2",{0,1}},{"2000Rnd_762x51_M134",{0,1}},{"48Rnd_40mm_MK19",{0,1}},{"100Rnd_762x51_M240",{0,1}}};
};
/* Your doorsegment is derivated from the normal wall.*/
class Land_DZE_WoodDoor: Land_DZE_WoodDoor_Base {
model = "\z\addons\dayz_epoch\models\small_wall_door_anim.p3d";
displayName = "Wood Door";
GhostPreview = "WoodDoor_Preview_DZ";
upgradeBuilding[] = {"Land_DZE_WoodDoorLocked",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
condition="this animationPhase ""Open_door"" < 0.5";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
condition="this animationPhase ""Open_door"" >= 0.5";
statement="this animate [""Open_door"", 0];";
};
};
};
class Land_DZE_WoodDoorLocked: Land_DZE_WoodDoorLocked_Base {
model = "\z\addons\dayz_epoch\models\small_wall_door_locked_anim.p3d";
displayName = "Wood Door Locked";
GhostPreview = "WoodDoor_Preview_DZ";
downgradeBuilding[] = {"Land_DZE_WoodDoor",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
class Open_hinge {
source = "user";
animPeriod = 1; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
//condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_door"", 0]";
};
class Lock_Door : Open_Door
{
displayName="Lock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_hinge"", 0]";
};
class Unlock_Door : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
statement="this animate [""Open_hinge"", 1]";
};
class Unlock_Door_Dialog : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="DZE_Lock_Door != (this getvariable['CharacterID','0'])";
statement="dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;createdialog ""ComboLockUI""";
};
};
};
class Land_DZE_LargeWoodDoor: Land_DZE_WoodDoor_Base {
model = "\z\addons\dayz_epoch\models\large_wall_door_anim.p3d";
displayName = "Large Wood Door";
GhostPreview = "LargeWoodDoor_Preview_DZ";
upgradeBuilding[] = {"Land_DZE_LargeWoodDoorLocked",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
condition="this animationPhase ""Open_door"" < 0.5";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
condition="this animationPhase ""Open_door"" >= 0.5";
statement="this animate [""Open_door"", 0]";
};
};
};
class Land_DZE_LargeWoodDoorLocked: Land_DZE_WoodDoorLocked_Base {
model = "\z\addons\dayz_epoch\models\large_wall_door_locked_anim.p3d";
displayName = "Large Wood Door Locked";
GhostPreview = "LargeWoodDoor_Preview_DZ";
downgradeBuilding[] = {"Land_DZE_LargeWoodDoor",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
class Open_hinge {
source = "user";
animPeriod = 1; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
//condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_door"", 0]";
};
class Lock_Door : Open_Door
{
displayName="Lock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_hinge"", 0]";
};
class Unlock_Door : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
statement="this animate [""Open_hinge"", 1]";
};
class Unlock_Door_Dialog : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="DZE_Lock_Door != (this getvariable['CharacterID','0'])";
statement="dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;createdialog ""ComboLockUI""";
};
};
};
class Land_DZE_GarageWoodDoor: Land_DZE_WoodDoor_Base {
model = "\z\addons\dayz_epoch\models\Garage_door_anim.p3d";
displayName = "Garage Wood Door";
GhostPreview = "GarageWoodDoor_Preview_DZ";
upgradeBuilding[] = {"Land_DZE_GarageWoodDoorLocked",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
condition="this animationPhase ""Open_door"" < 0.5";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
condition="this animationPhase ""Open_door"" >= 0.5";
statement="this animate [""Open_door"", 0]";
};
};
};
class Land_DZE_GarageWoodDoorLocked: Land_DZE_WoodDoorLocked_Base {
model = "\z\addons\dayz_epoch\models\Garage_door_locked_anim.p3d";
displayName = "Garage Wood Door Locked";
GhostPreview = "GarageWoodDoor_Preview_DZ";
downgradeBuilding[] = {"Land_DZE_GarageWoodDoor",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
class Open_hinge {
source = "user";
animPeriod = 1; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
//condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_door"", 0]";
};
class Lock_Door : Open_Door
{
displayName="Lock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
statement="this animate [""Open_hinge"", 0]";
};
class Unlock_Door : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
statement="this animate [""Open_hinge"", 1]";
};
class Unlock_Door_Dialog : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="DZE_Lock_Door != (this getvariable['CharacterID','0'])";
statement="dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;createdialog ""ComboLockUI""";
};
};
};
class CinderWallDoorLocked_DZ: CinderWallDoorLocked_DZ_Base {
model = "\z\addons\dayz_epoch\models\steel_garage_locked.p3d";
displayName = "Block Garage Door Locked";
GhostPreview = "CinderWallDoorway_Preview_DZ";
downgradeBuilding[] = {"CinderWallDoor_DZ",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
class Open_latch {
source = "user";
animPeriod = 1; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_latch"" == 1)";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
//condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_latch"" == 1)";
statement="this animate [""Open_door"", 0]";
};
class Lock_Door : Open_Door
{
displayName="Lock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_latch"" == 1)";
statement="this animate [""Open_latch"", 0]";
};
class Unlock_Door : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_latch"" == 0)";
statement="this animate [""Open_latch"", 1]";
};
class Unlock_Door_Dialog : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="DZE_Lock_Door != (this getvariable['CharacterID','0'])";
statement="dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;createdialog ""ComboLockUI""";
};
};
};
class CinderWallDoor_DZ: CinderWallDoor_DZ_Base {
model = "\z\addons\dayz_epoch\models\steel_garage_door.p3d";
displayName = "Block Garage Door";
GhostPreview = "CinderWallDoorway_Preview_DZ";
upgradeBuilding[] = {"CinderWallDoorLocked_DZ",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
condition="this animationPhase ""Open_door"" < 0.5";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
condition="this animationPhase ""Open_door"" >= 0.5";
statement="this animate [""Open_door"", 0]";
};
};
};
class CinderWallDoorSmallLocked_DZ: CinderWallDoorLocked_DZ_Base {
model = "\z\addons\dayz_epoch\models\Steel_door_locked.p3d";
displayName = "Block Door Locked";
GhostPreview = "CinderWallSmallDoorway_Preview_DZ";
downgradeBuilding[] = {"CinderWallDoorSmall_DZ",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
class Open_latch {
source = "user";
animPeriod = 1; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_latch"" == 1)";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
//condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_hinge"" == 1)";
condition="(this animationPhase ""Open_door"" == 1) and (this animationPhase ""Open_latch"" == 1)";
statement="this animate [""Open_door"", 0]";
};
class Lock_Door : Open_Door
{
displayName="Lock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 1)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_latch"" == 1)";
statement="this animate [""Open_latch"", 0]";
};
class Unlock_Door : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="(DZE_Lock_Door == (this getvariable['CharacterID','0'])) and (this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_latch"" == 0)";
statement="this animate [""Open_latch"", 1]";
};
class Unlock_Door_Dialog : Open_Door
{
displayName="Unlock Door";
//condition="(this animationPhase ""Open_door"" == 0) and (this animationPhase ""Open_hinge"" == 0)";
condition="DZE_Lock_Door != (this getvariable['CharacterID','0'])";
statement="dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;createdialog ""ComboLockUI""";
};
};
};
class CinderWallDoorSmall_DZ: CinderWallDoor_DZ_Base {
model = "\z\addons\dayz_epoch\models\Steel_door.p3d";
displayName = "Block Door";
GhostPreview = "CinderWallSmallDoorway_Preview_DZ";
upgradeBuilding[] = {"CinderWallDoorSmallLocked_DZ",{{"ItemComboLock",1}}};
/* Arma needs to know, how the animation trigger is triggered*/
class AnimationSources {
/* name must be identical to the one given by the model.cfg ("Open_Door")" */
class Open_door {
source = "user";
animPeriod = 4; /* duration in seconds */
initPhase = 0;
};
};
/* The entry to the actionmenu */
class UserActions
{
class Open_Door
{
displayName="Open Door";
onlyforplayer = true;
position="Door_knopf";
radius=3; /* visibility distance of the entry */
condition="this animationPhase ""Open_door"" < 0.5";
statement="this animate [""Open_door"", 1]";
};
class Close_Door : Open_Door
{
displayName="Close Door";
condition="this animationPhase ""Open_door"" >= 0.5";
statement="this animate [""Open_door"", 0]";
};
};
}; | [
"[email protected]"
] | |
90cb7de0393ebcb96e9cb7262e2cbf8170954ab5 | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-robomaker/source/model/DescribeWorldTemplateResult.cpp | c38ac36b6f3d4e5dd6a8234fd3d7cf095be1546b | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 1,767 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/robomaker/model/DescribeWorldTemplateResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::RoboMaker::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeWorldTemplateResult::DescribeWorldTemplateResult()
{
}
DescribeWorldTemplateResult::DescribeWorldTemplateResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DescribeWorldTemplateResult& DescribeWorldTemplateResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("arn"))
{
m_arn = jsonValue.GetString("arn");
}
if(jsonValue.ValueExists("clientRequestToken"))
{
m_clientRequestToken = jsonValue.GetString("clientRequestToken");
}
if(jsonValue.ValueExists("name"))
{
m_name = jsonValue.GetString("name");
}
if(jsonValue.ValueExists("createdAt"))
{
m_createdAt = jsonValue.GetDouble("createdAt");
}
if(jsonValue.ValueExists("lastUpdatedAt"))
{
m_lastUpdatedAt = jsonValue.GetDouble("lastUpdatedAt");
}
if(jsonValue.ValueExists("tags"))
{
Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects();
for(auto& tagsItem : tagsJsonMap)
{
m_tags[tagsItem.first] = tagsItem.second.AsString();
}
}
if(jsonValue.ValueExists("version"))
{
m_version = jsonValue.GetString("version");
}
return *this;
}
| [
"[email protected]"
] | |
389864e8b4e1475ab99891177f0dc38629aec30a | 38cc8f98ac4810a82c60cd2b59ed62d09e754ae0 | /CodeForces/723-2/3-1/main.cpp | c99fa31bddd2cf5051ceee566cd02f99b8fd8417 | [] | no_license | himdhiman/Competitive-Codes | b4b37f1328e7258cc4346c8d5f27e301e871b915 | 43b4a512b1f896dd12560c9883c894415bcb5fd6 | refs/heads/master | 2023-06-29T05:10:27.236649 | 2021-07-26T07:00:52 | 2021-07-26T07:00:52 | 308,596,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,769 | cpp | #include<bits/stdc++.h>
#define int long long
#define MOD 1000000007
using namespace std;
const int N = 1000005;
int arr[N];
// int solve(int n){
// int dp[2][n];
// dp[0][0] = (arr[0] >= 0 ? arr[0] : 0);
// dp[1][0] = 0;
// for(int i = 1; i < n; i++){
// int temp1 = ((dp[0][i-1] + arr[i]) >= 0 ? dp[0][i-1]+arr[i] : 0);
// int temp2 = ((dp[1][i-1] + arr[i]) >= 0 ? dp[1][i-1]+arr[i] : 0);
// dp[0][i] = max(temp1, temp2);
// dp[1][i] = max(dp[0][i-1], dp[1][i-1]);
// }
// return max(dp[0][n-1], dp[1][n-1]);
// }
// int solve4(int n){
// int dp[2001][2001];
// for(int i = 0; i <= 2000; i++){
// for(int j = 0; j <= 2000; j++){
// dp[i][j] = INT_MIN;
// }
// }
// dp[1][0] = 0;
// dp[1][1] = (arr[1] >= 0 ? arr[1] : 0);
// for(int i = 2; i <= n; i++){
// for(int j = 0; j <= i; j++){
// if((dp[i-1][j-1] + arr[i]) >= 0){
// dp[i][j] = max(dp[i-1][j-1] + arr[i], dp[i-1][j]);
// }else{
// dp[i][j] = dp[i-1][j];
// }
// // dp[i][j] = ((dp[i-1][j-1]+arr[i]) >= 0 ? dp[i-1][j-1]+arr[i] : dp[i-1][j]);
// }
// }
// int idx = 0;
// int val = dp[n+1][0];
// for(int i = 1; i <= arr[n]; i++){
// if(dp[n+1][i] >= val){
// val = dp[n+1][i];
// idx = i;
// }
// }
// return idx;
// }
// int dp[2001][9001];
// int solve2(int n, int i, int health){
// if(i == n){
// return 0;
// }
// if(dp[i][health] != -1){
// return dp[i][health];
// }
// if((health + arr[i]) < 0){
// return solve2(n, i+1, health);
// }
// return dp[i][health] = max(1 + solve2(n, i+1, health + arr[i]), solve2(n, i+1, health));
// }
// int solve3(int n, int sum, int *dp){
// if(n == 0){
// return 0;
// }
// if(dp[n][sum] != -1){
// return dp[n][sum];
// }
// if((sum + arr[n-1]) < 0){
// return solve3(n-1, sum, dp);
// }
// return dp[n][sum] = max(1 + solve3(n-1, sum+arr[n-1], dp), solve3(n-1, sum, dp));
// }
int32_t main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n;
cin>>n;
for(int i = 1; i <= n; i++){
cin>>arr[i];
}
// memset(dp, -1, sizeof dp);
// int ans1 = solve(n);
// int *dp = new int[n+1][ans1+1];
// memset(dp, -1, sizeof dp);
// cout<<solve2(n, 0, 0)<<endl;
// cout<<solve4(n)<<endl;
// sort(arr, arr+n);
// int cnt = 0;
// int ans = 0;
// int idx = n-1;
// while(true){
// if((ans + arr[idx]) >= 0){
// cout<<arr[idx]<<" ";
// ans += arr[idx];
// cnt++;
// idx--;
// }else{
// break;
// }
// }
// cout<<cnt<<endl;
priority_queue<int, vector<int>, greater<int> > p;
int val = 0;
for(int i = 1; i <= n; i++){
p.push(arr[i]);
val += arr[i];
while(val < 0 and !p.empty()){
int curr = p.top();
p.pop();
val -= curr;
}
}
cout<<p.size()<<endl;
return 0;
} | [
"[email protected]"
] | |
e960acf700c898345d4a9d9b383a330f201222e7 | 6c2a0b2b307779ce9cf62801c398453e83550015 | /Threads/Thread.cpp | 8bcf1fde89788e02675155868fba33a6acf3ce91 | [] | no_license | pbabics/Project-Ikaros | f11b8aa2600d090a2d0eced8dcac74c35837dcf6 | 1558fcd6662aec209d7e97c4ff6ef96af9832677 | refs/heads/master | 2021-05-27T21:36:07.095534 | 2012-05-12T16:28:01 | 2012-05-12T16:28:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,253 | cpp | #include "Thread.h"
Thread* Thread::CreateThread(CalledFunction func, void *args)
{
Thread* n = new Thread();
if (pthread_create(&n->thread, NULL, func, args) == 0)
{
n->status = THREAD_ACTIVE;
n->function = func;
n->args = args;
return n ;
}
return NULL ;
}
int Thread::Kill() const
{
return pthread_kill(thread, SIGKILL);
}
int Thread::Terminate() const
{
return pthread_kill(thread, SIGTERM);
}
int Thread::Interrupt() const
{
return pthread_kill(thread, SIGINT);
}
int Thread::Continue() const
{
return pthread_kill(thread, SIGCONT);
}
int Thread::SendSignal(int sig)
{
return pthread_kill(thread, sig);
}
void Thread::Suspend()
{
sigset_t suspendSig;
int sig = SIGCONT;
sigemptyset(&suspendSig);
sigaddset(&suspendSig, SIGCONT);
sigaddset(&suspendSig, SIGINT);
sigaddset(&suspendSig, SIGTERM);
status = THREAD_SUSPENDED;
sigwait(&suspendSig, &sig);
status = THREAD_ACTIVE;
}
void Thread::SuspendThisThread()
{
sigset_t suspendSig;
int sig = SIGCONT;
sigemptyset(&suspendSig);
sigaddset(&suspendSig, SIGCONT);
sigaddset(&suspendSig, SIGINT);
sigaddset(&suspendSig, SIGTERM);
sigwait(&suspendSig, &sig);
}
| [
"[email protected]"
] | |
54c4dee8feb903eba0da75636118eff4a613853f | 79ae2509cd0b51a22896da5b94d410ace59eee86 | /include/OpenGLContext.hpp | b0db9eb0e849d8a8acb3b657649cd55ce4abe9b0 | [
"MIT"
] | permissive | Modzeleczek/WebcamFilter | 2d961a676e6ba1a52dbf8ce7c89b27759a6d2a0a | 7af1a54565b405eae681f90dd59e22b099ead9f0 | refs/heads/master | 2023-09-04T06:39:48.582228 | 2021-10-26T22:25:11 | 2021-10-26T22:25:11 | 398,092,042 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | hpp | #ifndef OpenGLContext_HPP
#define OpenGLContext_HPP
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
class OpenGLContext
{
protected:
GLFWwindow *Window;
const int Width, Height;
public:
OpenGLContext(int width, int height);
OpenGLContext(const OpenGLContext &object);
virtual ~OpenGLContext();
void UseOnCurrentThread();
void PrintGPUInfo();
};
#endif // OpenGLContext_HPP
| [
"[email protected]"
] | |
f29e42a423c61d5f6612beb3bdf29f6c9a8e11f0 | 765c82de19e89f7a467d004d529c739a3e038319 | /FlowCube/src/Swipe.h | 87358be6850ff2681d48fe158de5c0fb433cf34d | [] | no_license | ryo0306/February-Screening-panel | 712df4130153530b85a97f5704c5e6a9d3d1bffe | 44f38b25cf3d9f103be736d031785ccecbfedffa | refs/heads/master | 2021-01-10T03:54:22.463140 | 2016-03-05T08:08:00 | 2016-03-05T08:08:00 | 47,526,173 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,266 | h | #pragma once
#include "ScreenMake.h"
class Swipe
{
public:
Swipe(){};
void SetUp();
void Update();
// スワイプしている長さを取得
Vec2f GetRange(){ return range; }
// スワイプをしてるかどうか
bool GetSwiping(){ return swiping; }
// 強制的にスワイプを終了
void offSwiping(){ swiping = false; }
// どれぐらいスワイプすれば反応するかを設定
// float rangeLimit_ 長さ
void SetRangeLimit(Vec2f rangeLimit_){ rangeLimit = rangeLimit_; }
// 1フレーム前との差を取得
// if(GetOneFreameDifferencce() < num(距離))
// で右側にnum文スワイプ時の処理を書くことできる。
Vec2f GetOneFrameDifference();
private:
bool swiping; // スワイプしているかどうか
Vec2f mousePos; // マウスの位置
Vec2f startPos; // スワイプ開始位置
Vec2f endPos; // スワイプ終了位置(現在地)
Vec2f range; // スワイプしている距離
Vec2f putRange; // 1フレーム前のrange
Vec2f rangeLimit; // どれだけスワイプすれば反応するか
}; | [
"[email protected]"
] | |
6444d5ef94414aa37a955ee6436883b3e165415a | 4f307eb085ad9f340aaaa2b6a4aa443b4d3977fe | /lin.steele/FinalWithSFML/StopStartAnimationEvent.h | 5c9cbf9b97f9279fc970b36676a348e6152f079e | [] | no_license | Connellj99/GameArch | 034f4a0f52441d6dde37956a9662dce452a685c7 | 5c95e9bdfce504c02c73a0c3cb566a010299a9b8 | refs/heads/master | 2020-12-28T10:29:19.935573 | 2020-02-04T19:41:09 | 2020-02-04T19:41:09 | 238,286,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | h | #ifndef STOPSTARTANIMATIONEVENT_H
#define STOPSTARTANIMATIONEVENT_H
// Local includes
#include "GameEvent.h"
class StopStartAnimationEvent : public Event
{
public:
// Constructors
StopStartAnimationEvent() :Event((EventType)STOP_START_ANIMATION) {};
// Destructors
~StopStartAnimationEvent() {};
private:
};
#endif // !STOPSTARTANIMATIONEVENT_H
| [
"[email protected]"
] | |
63eff0d5608650c4ff518b0a42bcb11c4c714664 | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /third_party/WebKit/Source/core/paint/FramePainter.cpp | 7010f0987fb215576200376d3ca098f2e7d3457f | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 9,000 | cpp | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/paint/FramePainter.h"
#include "core/editing/markers/DocumentMarkerController.h"
#include "core/fetch/MemoryCache.h"
#include "core/frame/FrameView.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/layout/LayoutView.h"
#include "core/page/Page.h"
#include "core/paint/LayoutObjectDrawingRecorder.h"
#include "core/paint/PaintInfo.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/PaintLayerPainter.h"
#include "core/paint/ScrollbarPainter.h"
#include "core/paint/TransformRecorder.h"
#include "platform/fonts/FontCache.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/paint/ClipRecorder.h"
#include "platform/graphics/paint/ScopedPaintChunkProperties.h"
#include "platform/scroll/ScrollbarTheme.h"
namespace blink {
bool FramePainter::s_inPaintContents = false;
void FramePainter::paint(GraphicsContext& context, const GlobalPaintFlags globalPaintFlags, const CullRect& rect)
{
frameView().notifyPageThatContentAreaWillPaint();
IntRect documentDirtyRect = rect.m_rect;
IntRect visibleAreaWithoutScrollbars(frameView().location(), frameView().visibleContentRect().size());
documentDirtyRect.intersect(visibleAreaWithoutScrollbars);
bool shouldPaintContents = !documentDirtyRect.isEmpty();
bool shouldPaintScrollbars = !frameView().scrollbarsSuppressed() && (frameView().horizontalScrollbar() || frameView().verticalScrollbar());
if (!shouldPaintContents && !shouldPaintScrollbars)
return;
if (shouldPaintContents) {
// TODO(pdr): Creating frame paint properties here will not be needed once
// settings()->rootLayerScrolls() is enabled.
// TODO(pdr): Make this conditional on the rootLayerScrolls setting.
Optional<ScopedPaintChunkProperties> scopedPaintChunkProperties;
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
TransformPaintPropertyNode* transform = m_frameView->scrollTranslation() ? m_frameView->scrollTranslation() : m_frameView->preTranslation();
ClipPaintPropertyNode* clip = m_frameView->contentClip();
if (transform || clip) {
PaintChunkProperties properties(context.getPaintController().currentPaintChunkProperties());
if (transform)
properties.transform = transform;
if (clip)
properties.clip = clip;
scopedPaintChunkProperties.emplace(context.getPaintController(), *frameView().layoutView(), properties);
}
}
TransformRecorder transformRecorder(context, *frameView().layoutView(),
AffineTransform::translation(frameView().x() - frameView().scrollX(), frameView().y() - frameView().scrollY()));
ClipRecorder recorder(context, *frameView().layoutView(), DisplayItem::kClipFrameToVisibleContentRect, frameView().visibleContentRect());
documentDirtyRect.moveBy(-frameView().location() + frameView().scrollPosition());
paintContents(context, globalPaintFlags, documentDirtyRect);
}
if (shouldPaintScrollbars) {
IntRect scrollViewDirtyRect = rect.m_rect;
IntRect visibleAreaWithScrollbars(frameView().location(), frameView().visibleContentRect(IncludeScrollbars).size());
scrollViewDirtyRect.intersect(visibleAreaWithScrollbars);
scrollViewDirtyRect.moveBy(-frameView().location());
Optional<ScopedPaintChunkProperties> scopedPaintChunkProperties;
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
if (TransformPaintPropertyNode* transform = m_frameView->preTranslation()) {
PaintChunkProperties properties(context.getPaintController().currentPaintChunkProperties());
properties.transform = transform;
scopedPaintChunkProperties.emplace(context.getPaintController(), *frameView().layoutView(), properties);
}
}
TransformRecorder transformRecorder(context, *frameView().layoutView(),
AffineTransform::translation(frameView().x(), frameView().y()));
ClipRecorder recorder(context, *frameView().layoutView(), DisplayItem::kClipFrameScrollbars, IntRect(IntPoint(), visibleAreaWithScrollbars.size()));
paintScrollbars(context, scrollViewDirtyRect);
}
}
void FramePainter::paintContents(GraphicsContext& context, const GlobalPaintFlags globalPaintFlags, const IntRect& rect)
{
Document* document = frameView().frame().document();
if (frameView().shouldThrottleRendering() || !document->isActive())
return;
LayoutView* layoutView = frameView().layoutView();
if (!layoutView) {
DLOG(ERROR) << "called FramePainter::paint with nil layoutObject";
return;
}
// TODO(crbug.com/590856): It's still broken when we choose not to crash when the check fails.
if (!frameView().checkDoesNotNeedLayout())
return;
// TODO(wangxianzhu): The following check should be stricter, but currently this is blocked
// by the svg root issue (crbug.com/442939).
ASSERT(document->lifecycle().state() >= DocumentLifecycle::CompositingClean);
TRACE_EVENT1("devtools.timeline,rail", "Paint", "data", InspectorPaintEvent::data(layoutView, LayoutRect(rect), 0));
bool isTopLevelPainter = !s_inPaintContents;
s_inPaintContents = true;
FontCachePurgePreventer fontCachePurgePreventer;
// TODO(jchaffraix): GlobalPaintFlags should be const during a paint
// phase. Thus we should set this flag upfront (crbug.com/510280).
GlobalPaintFlags localPaintFlags = globalPaintFlags;
if (document->printing())
localPaintFlags |= GlobalPaintFlattenCompositingLayers | GlobalPaintPrinting;
PaintLayer* rootLayer = layoutView->layer();
#if ENABLE(ASSERT)
layoutView->assertSubtreeIsLaidOut();
LayoutObject::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(*rootLayer->layoutObject());
#endif
PaintLayerPainter layerPainter(*rootLayer);
float deviceScaleFactor = blink::deviceScaleFactor(rootLayer->layoutObject()->frame());
context.setDeviceScaleFactor(deviceScaleFactor);
layerPainter.paint(context, LayoutRect(rect), localPaintFlags);
if (rootLayer->containsDirtyOverlayScrollbars())
layerPainter.paintOverlayScrollbars(context, LayoutRect(rect), localPaintFlags);
// Regions may have changed as a result of the visibility/z-index of element changing.
if (document->annotatedRegionsDirty())
frameView().updateDocumentAnnotatedRegions();
if (isTopLevelPainter) {
// Everything that happens after paintContents completions is considered
// to be part of the next frame.
memoryCache()->updateFramePaintTimestamp();
s_inPaintContents = false;
}
InspectorInstrumentation::didPaint(layoutView->frame(), 0, context, LayoutRect(rect));
}
void FramePainter::paintScrollbars(GraphicsContext& context, const IntRect& rect)
{
if (frameView().horizontalScrollbar() && !frameView().layerForHorizontalScrollbar())
paintScrollbar(context, *frameView().horizontalScrollbar(), rect);
if (frameView().verticalScrollbar() && !frameView().layerForVerticalScrollbar())
paintScrollbar(context, *frameView().verticalScrollbar(), rect);
if (frameView().layerForScrollCorner())
return;
paintScrollCorner(context, frameView().scrollCornerRect());
}
void FramePainter::paintScrollCorner(GraphicsContext& context, const IntRect& cornerRect)
{
if (frameView().scrollCorner()) {
bool needsBackground = frameView().frame().isMainFrame();
if (needsBackground && !LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(context, *frameView().layoutView(), DisplayItem::kScrollbarCorner)) {
LayoutObjectDrawingRecorder drawingRecorder(context, *frameView().layoutView(), DisplayItem::kScrollbarCorner, FloatRect(cornerRect));
context.fillRect(cornerRect, frameView().baseBackgroundColor());
}
ScrollbarPainter::paintIntoRect(*frameView().scrollCorner(), context, cornerRect.location(), LayoutRect(cornerRect));
return;
}
ScrollbarTheme::theme().paintScrollCorner(context, *frameView().layoutView(), cornerRect);
}
void FramePainter::paintScrollbar(GraphicsContext& context, Scrollbar& bar, const IntRect& rect)
{
bool needsBackground = bar.isCustomScrollbar() && frameView().frame().isMainFrame();
if (needsBackground) {
IntRect toFill = bar.frameRect();
toFill.intersect(rect);
context.fillRect(toFill, frameView().baseBackgroundColor());
}
bar.paint(context, CullRect(rect));
}
const FrameView& FramePainter::frameView()
{
ASSERT(m_frameView);
return *m_frameView;
}
} // namespace blink
| [
"[email protected]"
] | |
12390f6b7f01cf212af9eb6ad8d150ca7124d4e4 | e8034f94f4361abe822d00fffeff6c13eddaae00 | /2011-2020/2013/baldini/mc-fastflow/ff/pipeline.hpp | 252fd77d8abd9d19cf18d62d8055b624ded0d650 | [] | no_license | lucaderi/sgr | fe76157830a999426e0e0772a6c989c3ef7b40a9 | 96128a6efbff5382bf6747d55cbf0da1f9552b45 | refs/heads/master | 2023-08-31T00:25:37.636590 | 2023-07-30T17:03:19 | 2023-07-30T17:03:19 | 119,234,988 | 19 | 220 | null | 2023-09-14T14:33:05 | 2018-01-28T06:43:52 | C | UTF-8 | C++ | false | false | 13,476 | hpp | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*! \file pipeline.hpp
* \brief This file describes the pipeline skeleton.
*/
#ifndef _FF_PIPELINE_HPP_
#define _FF_PIPELINE_HPP_
/* ***************************************************************************
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*
****************************************************************************
*/
#include <vector>
#include <ff/node.hpp>
namespace ff {
/*!
* \ingroup high_level
*
* @{
*/
/*!
* \class ff_pipeline
*
* \brief The Pipeline skeleton.
*
* Pipelining is one of the simplest parallel patterns where data flows through
* a series of stages (or nodes) and each stage processes the input data in some
* ways, producing as output a modified version or new data. A pipeline's stage
* can operate sequentially or in parallel and may or may not have an internal
* state.
*/
class ff_pipeline: public ff_node {
protected:
/// Prepare the Pipeline skeleton for execution
inline int prepare() {
// create input FFBUFFER
int nstages=static_cast<int>(nodes_list.size());
for(int i=1;i<nstages;++i) {
if (nodes_list[i]->create_input_buffer(in_buffer_entries, fixedsize)<0) {
error("PIPE, creating input buffer for node %d\n", i);
return -1;
}
}
// set output buffer
for(int i=0;i<(nstages-1);++i) {
if (nodes_list[i]->set_output_buffer(nodes_list[i+1]->get_in_buffer())<0) {
error("PIPE, setting output buffer to node %d\n", i);
return -1;
}
}
// Preparation of buffers for the accelerator
int ret = 0;
if (has_input_channel) {
if (create_input_buffer(in_buffer_entries, fixedsize)<0) {
error("PIPE, creating input buffer for the accelerator\n");
ret=-1;
} else {
if (get_out_buffer()) {
error("PIPE, output buffer already present for the accelerator\n");
ret=-1;
} else {
if (create_output_buffer(out_buffer_entries,fixedsize)<0) {
error("PIPE, creating output buffer for the accelerator\n");
ret = -1;
}
}
}
}
prepared=true;
return ret;
}
/*!
* This function is required when no manager threads are present in the
* pipeline, which would allow to freeze other threads before starting the
* computation.
*/
int freeze_and_run(bool=false) {
freeze();
int nstages=static_cast<int>(nodes_list.size());
if (!prepared) if (prepare()<0) return -1;
for(int i=0;i<nstages;++i) {
nodes_list[i]->set_id(i);
if (nodes_list[i]->freeze_and_run(true)<0) {
error("ERROR: PIPE, (freezing and) running stage %d\n", i);
return -1;
}
}
return 0;
}
public:
enum { DEF_IN_BUFF_ENTRIES=512, DEF_OUT_BUFF_ENTRIES=(DEF_IN_BUFF_ENTRIES+128)};
/*!
* Constructor
* \param input_ch = true to set accelerator mode
* \param in_buffer_entries = input queue length
* \param out_buffer_entries = output queue length
* \param fixedsize = true uses only fixed size queue
*/
ff_pipeline(bool input_ch=false,
int in_buffer_entries=DEF_IN_BUFF_ENTRIES,
int out_buffer_entries=DEF_OUT_BUFF_ENTRIES, bool fixedsize=true):
has_input_channel(input_ch),prepared(false),
in_buffer_entries(in_buffer_entries),
out_buffer_entries(out_buffer_entries),fixedsize(fixedsize) {
}
/**
* Add a stage to the Pipeline
*
* \param s a ff_node that is the stage to be added to the skeleton. The stage
* contains the task that has to be executed.
*/
int add_stage(ff_node * s) {
nodes_list.push_back(s);
return 0;
}
/**
* the last stage output queue will be connected
* to the first stage input queue (feedback channel).
*/
int wrap_around() {
if (nodes_list.size()<2) {
error("PIPE, too few pipeline nodes\n");
return -1;
}
fixedsize=false; // NOTE: force unbounded size for the queues!
if (create_input_buffer(out_buffer_entries, fixedsize)<0)
return -1;
if (set_output_buffer(get_in_buffer())<0)
return -1;
nodes_list[0]->skip1pop = true;
return 0;
}
/// Run the Pipeline skeleton.
int run(bool skip_init=false) {
int nstages=static_cast<int>(nodes_list.size());
if (!skip_init) {
// set the initial value for the barrier
if (!barrier) barrier = new BARRIER_T;
barrier->barrierSetup(cardinality(barrier));
}
if (!prepared) if (prepare()<0) return -1;
if (has_input_channel) {
/* freeze_and_run is required because in the pipeline
* where there are not any manager threads,
* which allow to freeze other threads before starting the
* computation
*/
for(int i=0;i<nstages;++i) {
nodes_list[i]->set_id(i);
if (nodes_list[i]->freeze_and_run(true)<0) {
error("ERROR: PIPE, running stage %d\n", i);
return -1;
}
}
} else {
for(int i=0;i<nstages;++i) {
nodes_list[i]->set_id(i);
if (nodes_list[i]->run(true)<0) {
error("ERROR: PIPE, running stage %d\n", i);
return -1;
}
}
}
return 0;
}
/// Run and wait all threads to finish.
int run_and_wait_end() {
if (isfrozen()) return -1; // FIX !!!!
stop();
if (run()<0) return -1;
if (wait()<0) return -1;
return 0;
}
/// Run and then freeze.
int run_then_freeze() {
if (isfrozen()) {
thaw();
freeze();
return 0;
}
if (!prepared) if (prepare()<0) return -1;
freeze();
return run();
}
/// Wait for a stage to complete its task
int wait(/* timeval */ ) {
int ret=0;
for(unsigned int i=0;i<nodes_list.size();++i)
if (nodes_list[i]->wait()<0) {
error("PIPE, waiting stage thread, id = %d\n",nodes_list[i]->get_my_id());
ret = -1;
}
return ret;
}
/// Wait freezing.
int wait_freezing(/* timeval */ ) {
int ret=0;
for(unsigned int i=0;i<nodes_list.size();++i)
if (nodes_list[i]->wait_freezing()<0) {
error("PIPE, waiting freezing of stage thread, id = %d\n",
nodes_list[i]->get_my_id());
ret = -1;
}
return ret;
}
/// Stop all stages
void stop() {
for(unsigned int i=0;i<nodes_list.size();++i) nodes_list[i]->stop();
}
/// Freeze all stages
void freeze() {
for(unsigned int i=0;i<nodes_list.size();++i) nodes_list[i]->freeze();
}
/// Thaw all frozen stages
void thaw() {
for(unsigned int i=0;i<nodes_list.size();++i) nodes_list[i]->thaw();
}
/** check if the pipeline is frozen */
bool isfrozen() {
int nstages=static_cast<int>(nodes_list.size());
for(int i=0;i<nstages;++i)
if (!nodes_list[i]->isfrozen()) return false;
return true;
}
/** Offload the given task to the pipeline */
inline bool offload(void * task,
unsigned int retry=((unsigned int)-1),
unsigned int ticks=ff_node::TICKS2WAIT) {
FFBUFFER * inbuffer = get_in_buffer();
if (inbuffer) {
for(unsigned int i=0;i<retry;++i) {
if (inbuffer->push(task)) return true;
ticks_wait(ticks);
}
return false;
}
if (!has_input_channel)
error("PIPE: accelerator is not set, offload not available\n");
else
error("PIPE: input buffer creation failed\n");
return false;
}
/*!
* Load results. If \p false, EOS arrived or too many retries.
* If \p true, there is a new value
*/
inline bool load_result(void ** task,
unsigned int retry=((unsigned int)-1),
unsigned int ticks=ff_node::TICKS2WAIT) {
FFBUFFER * outbuffer = get_out_buffer();
if (outbuffer) {
for(unsigned int i=0;i<retry;++i) {
if (outbuffer->pop(task)) {
if ((*task != (void *)FF_EOS)) return true;
else return false;
}
ticks_wait(ticks);
}
return false;
}
if (!has_input_channel)
error("PIPE: accelerator is not set, offload not available");
else
error("PIPE: output buffer not created");
return false;
}
// return values:
// false: no task present
// true : there is a new value, you should check if the task is an FF_EOS
inline bool load_result_nb(void ** task) {
FFBUFFER * outbuffer = get_out_buffer();
if (outbuffer) {
if (outbuffer->pop(task)) return true;
else return false;
}
if (!has_input_channel)
error("PIPE: accelerator is not set, offload not available");
else
error("PIPE: output buffer not created");
return false;
}
int cardinality(BARRIER_T * const barrier) {
int card=0;
for(unsigned int i=0;i<nodes_list.size();++i)
card += nodes_list[i]->cardinality(barrier);
return card;
}
/* the returned time comprise the time spent in svn_init and
* in svc_end methods
*/
double ffTime() {
return diffmsec(nodes_list[nodes_list.size()-1]->getstoptime(),
nodes_list[0]->getstarttime());
}
/* the returned time considers only the time spent in the svc
* methods
*/
double ffwTime() {
return diffmsec(nodes_list[nodes_list.size()-1]->getwstoptime(),
nodes_list[0]->getwstartime());
}
#if defined(TRACE_FASTFLOW)
void ffStats(std::ostream & out) {
out << "--- pipeline:\n";
for(unsigned int i=0;i<nodes_list.size();++i)
nodes_list[i]->ffStats(out);
}
#else
void ffStats(std::ostream & out) {
out << "FastFlow trace not enabled\n";
}
#endif
protected:
/// ff_node interface
void* svc(void * task) { return NULL; }
int svc_init() { return -1; };
void svc_end() {}
int get_my_id() const { return -1; };
void setAffinity(int) {
error("PIPE, setAffinity: cannot set affinity for the pipeline\n");
}
int getCPUId() { return -1;}
int create_input_buffer(int nentries, bool fixedsize) {
if (in) return -1;
if (nodes_list[0]->create_input_buffer(nentries, fixedsize)<0) {
error("PIPE, creating input buffer for node 0\n");
return -1;
}
ff_node::set_input_buffer(nodes_list[0]->get_in_buffer());
return 0;
}
int create_output_buffer(int nentries, bool fixedsize=false) {
int last = static_cast<int>(nodes_list.size())-1;
if (last<0) return -1;
if (nodes_list[last]->create_output_buffer(nentries, fixedsize)<0) {
error("PIPE, creating output buffer for node %d\n",last);
return -1;
}
ff_node::set_output_buffer(nodes_list[last]->get_out_buffer());
return 0;
}
int set_output_buffer(FFBUFFER * const o) {
int last = static_cast<int>(nodes_list.size())-1;
if (!last) return -1;
if (nodes_list[last]->set_output_buffer(o)<0) {
error("PIPE, setting output buffer for node %d\n",last);
return -1;
}
return 0;
}
private:
bool has_input_channel; // for accelerator
bool prepared;
int in_buffer_entries;
int out_buffer_entries;
std::vector<ff_node *> nodes_list;
bool fixedsize;
};
/*!
* @}
*/
} // namespace ff
#endif /* _FF_PIPELINE_HPP_ */
| [
"[email protected]"
] | |
cc09766e6393240509a8934ffc6796ae74c3d9b1 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14332/function14332_schedule_7/function14332_schedule_7_wrapper.cpp | c326da8a55ddd4d292599e218153d04670eaf49f | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | cpp | #include "Halide.h"
#include "function14332_schedule_7_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(64, 64);
Halide::Buffer<int32_t> buf01(64, 64, 64);
Halide::Buffer<int32_t> buf02(64, 64, 64);
Halide::Buffer<int32_t> buf03(64, 64, 64);
Halide::Buffer<int32_t> buf04(64, 64, 64);
Halide::Buffer<int32_t> buf05(64, 64, 64);
Halide::Buffer<int32_t> buf06(64, 64);
Halide::Buffer<int32_t> buf0(64, 64, 64, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14332_schedule_7(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14332/function14332_schedule_7/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"[email protected]"
] | |
ff02fb1b6e207d8a8579b4cdbbd02cfce0998558 | 2e935d641ef7431fbbbe7e210c6afa9e43131ba5 | /c++/Rok 3/grafika komputerowa/GK PROJEKT/171016/171016/171016.cpp | 040a9fca51c1c5e74d8432fb5b1d05fbd179a8a2 | [] | no_license | KamilMarkuszewski/Studia | 5d8bcaf19cbf13123bb036e42c028f809e1286f2 | 66f326884bf0a9d39cb84dbafa1c59cde5c617f1 | refs/heads/master | 2021-05-13T23:27:21.146080 | 2018-01-06T23:59:20 | 2018-01-06T23:59:20 | 116,513,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,603 | cpp | // RAY TRACING
// KAMIL MARKUSZEWSKI 171016
#include "stdafx.h"
#include <math.h>
#include <stdlib.h>
#include <string>
#include <GL/glut.h>
#include <GL/gl.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
/*************************************************************************************/
using namespace std;
typedef float punkt[3];
#define SKALA 1
#define MAX 2
#define R 5
#define PI 3.14
/*************************************************************************************/
punkt pkt;
int krok = 0;
float viewport_size =20.0;
int x_im_size = 0;
int y_im_size = 0;
float light_position[5][3];
float light_specular[5][3];
float light_diffuse[5][3];
float light_ambient[5][3];
float tlo[3];
float sphere_radius[9];
float kula_wspl[9][3];
float sphere_specular[9][3];
float sphere_diffuse[9][3];
float sphere_ambient[9][3];
float sphere_specularhininess[9];
float theta = 360.0;
float global_a[3];
punkt starting_punkt;
punkt starting_directions = {0.0, 0.0, -1.0};
GLubyte pixel[1][1][3];
bool start = false;
int numerek = 0;
bool start2 = false;
/*************************************************************************************/
struct punktTabsphere{
punkt pkt;
int light;
int status;
int nr_kuli;
};
struct struct_punkt{
punkt pkt;
};
/*************************************************************************************/
void wczytaj(void);
float dl_vector(struct_punkt vec);
float dotProduct(punkt p1, punkt p2);
struct_punkt Normalization(punkt q);
struct_punkt Normal(punkt q , int nr_kuli);
struct_punkt Reflect(punkt startpunkt, punkt qsphere, punkt normal);
punktTabsphere Intersect(punkt punktStart, punkt direct);
struct_punkt Phong(punkt qsphere, punkt normal, punkt dest, int nr_sphere);
struct_punkt Trace(punkt startpunkt, punkt dest, int krok_loc);
void RenderScene( void);
void wczytaj(void);
void Myinit(void);
double rad(float stopien);
void spinEgg();
/*************************************************************************************/
double rad(float stopien){
return (stopien*PI)/180;
}
void spinEgg(){
if(start){
glFlush();
theta += 50.0;
if( theta > 360.0 ) theta -= 360.0;
kula_wspl[2][0] = R * cos(rad(theta-60.0));
kula_wspl[2][1] = R * sin(rad(theta-60.0));
kula_wspl[3][0] = R * cos(rad(theta));
kula_wspl[3][1] = R * sin(rad(theta));
kula_wspl[4][0] = R * cos(rad(theta+60.0));
kula_wspl[4][1] = R * sin(rad(theta+60.0));
kula_wspl[5][0] = R * cos(rad(theta+60.0+60.0));
kula_wspl[5][1] = R * sin(rad(theta+60.0+60.0));
kula_wspl[6][0] = R * cos(rad(theta+60.0+60.0+60.0));
kula_wspl[6][1] = R * sin(rad(theta+60.0+60.0+60.0));
kula_wspl[7][0] = R * cos(rad(theta+60.0+60.0+60.0+60.0));
kula_wspl[7][1] = R * sin(rad(theta+60.0+60.0+60.0+60.0));
cout << "Kat: " << theta << endl;
glutPostRedisplay();
}
if(start2){
bool b1, b2,b3;
b1 = true;
b2 = false;
b2 = false;
if( (kula_wspl[0][0] < -1.0) && b1 && (numerek < 6)){
kula_wspl[0][0] += 0.5;
} else {
b2 = true;
}
if( (kula_wspl[1][0] < 6.0) && b2 && (numerek < 14)){
kula_wspl[1][0] += 0.5;
} else{
if((kula_wspl[0][0] < -1.0) && (kula_wspl[1][0] < 6.0) ){
b3 =true;
}
}
if( (kula_wspl[2][0] < 10) && b3){
kula_wspl[2][0] += 0.5;
}
numerek++;
glutPostRedisplay();
}
}
float dl_vector(struct_punkt vec){
return (vec.pkt[0]*vec.pkt[0]+vec.pkt[1]*vec.pkt[1]+vec.pkt[2]*vec.pkt[2]);
}
float dotProduct(punkt p1, punkt p2){
return (p1[0]*p2[0]+p1[1]*p2[1]+p1[2]*p2[2]);
}
struct_punkt Normal(punkt q , int nr_kuli){
struct_punkt ret;
ret.pkt[0] = (q[0] - kula_wspl[nr_kuli][0])/sphere_radius[nr_kuli];
ret.pkt[1] = (q[1] - kula_wspl[nr_kuli][1])/sphere_radius[nr_kuli];
ret.pkt[2] = (q[2] - kula_wspl[nr_kuli][2])/sphere_radius[nr_kuli];
return ret;
}
struct_punkt Normalization(punkt q){
struct_punkt ret;
ret.pkt[0] = 0.0;
ret.pkt[1] = 0.0;
ret.pkt[2] = 0.0;
float d = 0.0;
int i;
for( i=0; i<3; i++){
d += q[i] * q[i];
}
d = sqrt(d);
if(0.0 < d){
for( i=0; i<3; i++){
ret.pkt[i] = q[i] / (d*1.0);
}
}
return ret;
}
struct_punkt Reflect(punkt startpunkt, punkt qsphere, punkt normal){
struct_punkt ret;
punkt dv;
dv[0] = startpunkt[0] - qsphere[0];
dv[1] = startpunkt[1] - qsphere[1];
dv[2] = startpunkt[2] - qsphere[2];
struct_punkt direct_vec_loc;
direct_vec_loc = Normalization(dv);
dv[0] = direct_vec_loc.pkt[0];
dv[1] = direct_vec_loc.pkt[1];
dv[2] = direct_vec_loc.pkt[2];
float n_dot_l;
n_dot_l = dotProduct(dv, normal);
ret.pkt[0] = 2 * (n_dot_l) * normal[0] - dv[0];
ret.pkt[1] = 2 * (n_dot_l) * normal[1] - dv[1];
ret.pkt[2] = 2 * (n_dot_l) * normal[2] - dv[2];
if( 1.0 > dl_vector(ret) ){
return ret;
}
else{
return Normalization(ret.pkt);
}
}
punktTabsphere Intersect(punkt punktStart, punkt direct){
punktTabsphere ret;
ret.pkt[0] = 0.0;
ret.pkt[1] = 0.0;
ret.pkt[2] = 0.0;
ret.nr_kuli = 0;
ret.light = 0;
ret.status = 0;
int status = 0;
int light = 0;
float a, b, c, dl, r;
for( int light = 0; light < 6; light++){
float x,y,z;
x = light_position[light][0] - punktStart[0];
y = light_position[light][1] - punktStart[1];
z = light_position[light][2] - punktStart[2];
if( (x/direct[0]) == (y/direct[1]) && (y/direct[1]) == (z/direct[2]) ){
ret.pkt[0] = light_position[light][0];
ret.pkt[1] = light_position[light][1];
ret.pkt[2] = light_position[light][2];
ret.status = 2;
return ret;
}
}
for( int nr_kuli = 0; nr_kuli < 9; nr_kuli++){
a = direct[0]*direct[0] + direct[1]*direct[1] + direct[2]*direct[2];
b = 2*((punktStart[0] - kula_wspl[nr_kuli][0])*direct[0] + (punktStart[1] - kula_wspl[nr_kuli][1])*direct[1] + (punktStart[2] - kula_wspl[nr_kuli][2])*direct[2]);
float c1 = (punktStart[0] * punktStart[0] + punktStart[1] * punktStart[1] + punktStart[2] * punktStart[2]);
float c2 = (kula_wspl[nr_kuli][0] * kula_wspl[nr_kuli][0] + kula_wspl[nr_kuli][1] * kula_wspl[nr_kuli][1]+ kula_wspl[nr_kuli][2] * kula_wspl[nr_kuli][2]);
float c3 = 2 * (punktStart[0] * kula_wspl[nr_kuli][0] + punktStart[1] * kula_wspl[nr_kuli][1] + punktStart[2] * kula_wspl[nr_kuli][2]);
c = c1 + c2 - c3 - sphere_radius[nr_kuli]*sphere_radius[nr_kuli];
dl = pow((double)b,2.0)-4*a*c;
if (dl>=0){
r =( -b - sqrt(dl))/(2*a);
if( r > 0 ){
ret.pkt[0] = punktStart[0] + r*direct[0];
ret.pkt[1] = punktStart[1] + r*direct[1];
ret.pkt[2] = punktStart[2] + r*direct[2];
ret.nr_kuli = nr_kuli;
ret.status = 3;
break;
}
}
}
if( ret.status == 0){
ret.status = 1;
}
return ret;
}
struct_punkt Phong(punkt qsphere, punkt normal, punkt dest, int nr_sphere){
punkt light_vec;
punkt reflection_vector;
float n_dot_l, v_dot_r;
struct_punkt kolor;
kolor.pkt[0] = 0.0;
kolor.pkt[1] = 0.0;
kolor.pkt[2] = 0.0;
punkt viewer_v = {0.0, 0.0, 1.0};
float a,b,c,wspl;
a = 1.0;
b = 0.1;
c = 0.01;
wspl = 1/(a+b+c);
for( int k = 0; k < 5; k++){
light_vec[0] = light_position[k][0] - qsphere[0];
light_vec[1] = light_position[k][1] - qsphere[1];
light_vec[2] = light_position[k][2] - qsphere[2];
struct_punkt light_vec_loc;
light_vec_loc = Normalization(light_vec);
light_vec[0] = light_vec_loc.pkt[0];
light_vec[1] = light_vec_loc.pkt[1];
light_vec[2] = light_vec_loc.pkt[2];
n_dot_l = dotProduct(light_vec, normal);
reflection_vector[0] = 2*(n_dot_l)*normal[0] - light_vec[0];
reflection_vector[1] = 2*(n_dot_l)*normal[1] - light_vec[1];
reflection_vector[2] = 2*(n_dot_l)*normal[2] - light_vec[2];
struct_punkt reflection_vector_loc;
reflection_vector_loc = Normalization(reflection_vector);
reflection_vector[0] = reflection_vector_loc.pkt[0];
reflection_vector[1] = reflection_vector_loc.pkt[1];
reflection_vector[2] = reflection_vector_loc.pkt[2];
v_dot_r = dotProduct(reflection_vector, viewer_v);
if( v_dot_r < 0){
v_dot_r = 0;
}
if( n_dot_l > 0){
kolor.pkt[0] += wspl*(sphere_diffuse[nr_sphere][0]*light_diffuse[k][0]*n_dot_l + sphere_specular[nr_sphere][0]*light_specular[k][0]*pow(double(v_dot_r), double(sphere_specularhininess[nr_sphere])) ) + sphere_ambient[nr_sphere][0]*light_ambient[k][0] + sphere_ambient[nr_sphere][0]*global_a[0];
kolor.pkt[1] += wspl*(sphere_diffuse[nr_sphere][1]*light_diffuse[k][1]*n_dot_l + sphere_specular[nr_sphere][1]*light_specular[k][1]*pow(double(v_dot_r), double(sphere_specularhininess[nr_sphere])) ) + sphere_ambient[nr_sphere][1]*light_ambient[k][1] + sphere_ambient[nr_sphere][1]*global_a[1];
kolor.pkt[2] += wspl*(sphere_diffuse[nr_sphere][2]*light_diffuse[k][2]*n_dot_l + sphere_specular[nr_sphere][2]*light_specular[k][2]*pow(double(v_dot_r), double(sphere_specularhininess[nr_sphere])) ) + sphere_ambient[nr_sphere][2]*light_ambient[k][2] + sphere_ambient[nr_sphere][2]*global_a[2];
}
else{
kolor.pkt[0] += sphere_ambient[nr_sphere][0]*global_a[0];
kolor.pkt[1] += sphere_ambient[nr_sphere][1]*global_a[1];
kolor.pkt[2] += sphere_ambient[nr_sphere][2]*global_a[2];
}
}
return kolor;
}
struct_punkt Trace(punkt startpunkt, punkt dest, int krok_loc){
punkt qsphere;
punkt normal;
punkt reflect;
int status;
int nr_light;
int nr_sphere;
struct_punkt local;
local.pkt[0] = 0.0;
local.pkt[1] = 0.0;
local.pkt[2] = 0.0;
struct_punkt reflected;
reflected.pkt[0] = 0.0;
reflected.pkt[1] = 0.0;
reflected.pkt[2] = 0.0;
if( krok_loc > MAX){
local.pkt[0] += tlo[0];
local.pkt[1] += tlo[1];
local.pkt[2] += tlo[2];
return local;
}
punktTabsphere q_loc;
q_loc = Intersect(startpunkt,dest);
qsphere[0] = q_loc.pkt[0];
qsphere[1] = q_loc.pkt[1];
qsphere[2] = q_loc.pkt[2];
nr_sphere = q_loc.nr_kuli;
nr_light = q_loc.light;
status = q_loc.status;
if( status == 2){
local.pkt[0] += light_specular[nr_light][0];
local.pkt[0] += light_specular[nr_light][1];
local.pkt[0] += light_specular[nr_light][2];
return local;
}
if( status == 1){
local.pkt[0] += tlo[0];
local.pkt[0] += tlo[1];
local.pkt[0] += tlo[2];
return local;
}
struct_punkt n_loc;
n_loc = Normal(qsphere,nr_sphere);
normal[0] = n_loc.pkt[0];
normal[1] = n_loc.pkt[1];
normal[2] = n_loc.pkt[2];
struct_punkt r_loc;
r_loc = Reflect(startpunkt,qsphere,normal);
reflect[0] = r_loc.pkt[0];
reflect[1] = r_loc.pkt[1];
reflect[2] = r_loc.pkt[2];
local = Phong(qsphere,normal,dest, nr_sphere);
reflected = Trace(qsphere, reflect, krok_loc+1);
local.pkt[0] += reflected.pkt[0];
local.pkt[1] += reflected.pkt[1];
local.pkt[2] += reflected.pkt[2];
return local;
};
void RenderScene( void){
int x, y;
float x_fl, y_fl;
int x_im_size_2;
int y_im_size_2;
x_im_size_2 = x_im_size/2;
y_im_size_2 = y_im_size/2;
glClear(GL_COLOR_BUFFER_BIT);
for( y = y_im_size_2; y > -y_im_size_2; y--){
for( x = -x_im_size_2; x < x_im_size_2; x++){
x_fl = (float)x/(x_im_size/viewport_size);
y_fl = (float)y/(y_im_size/viewport_size);
starting_punkt[0] = x_fl;
starting_punkt[1] = y_fl;
starting_punkt[2] = viewport_size;
struct_punkt kolor;
kolor = Trace(starting_punkt, starting_directions, krok);
if( kolor.pkt[0] > 1){
pixel[0][0][0] = 255;
}
else{
pixel[0][0][0] = kolor.pkt[0]*255;
}
if( kolor.pkt[1] > 1){
pixel[0][0][1] = 255;
}
else{
pixel[0][0][1] = kolor.pkt[1]*255;
}
if( kolor.pkt[2] > 1){
pixel[0][0][2] = 255;
}
else{
pixel[0][0][2] = kolor.pkt[2]*255;
}
glRasterPos3f(x_fl, y_fl, 0);
glDrawPixels(1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixel);
}
}
glFlush();
}
void wczytaj(void){
string szukaj;
ifstream plik;
plik.open( "scene.txt" );
if( plik.is_open() == false){
cout << "Nie znaleziono pliku :( buuu " << endl;
}
else{
while( szukaj.find("dimensions") == string::npos ){
plik >> szukaj;
}
plik >> x_im_size;
plik >> y_im_size;
x_im_size = x_im_size/SKALA;
y_im_size = y_im_size/SKALA;
while( szukaj.find("background") == string::npos ){
plik >> szukaj;
}
plik >> tlo[0];
plik >> tlo[1];
plik >> tlo[2];
while( szukaj.find("global") == string::npos ){
plik >> szukaj;
}
plik >> global_a[0];
plik >> global_a[1];
plik >> global_a[2];
int i_sp = 0;
int i_so = 0;
do{
plik >> szukaj;
if( szukaj == "sphere"){
plik >> sphere_radius[i_sp];
plik >> kula_wspl[i_sp][0];
plik >> kula_wspl[i_sp][1];
plik >> kula_wspl[i_sp][2];
plik >> sphere_specular[i_sp][0];
plik >> sphere_specular[i_sp][1];
plik >> sphere_specular[i_sp][2];
plik >> sphere_diffuse[i_sp][0];
plik >> sphere_diffuse[i_sp][1];
plik >> sphere_diffuse[i_sp][2];
plik >> sphere_ambient[i_sp][0];
plik >> sphere_ambient[i_sp][1];
plik >> sphere_ambient[i_sp][2];
plik >> sphere_specularhininess[i_sp];
i_sp++;
}
else{
if( szukaj == "source"){
plik >> light_position[i_so][0];
plik >> light_position[i_so][1];
plik >> light_position[i_so][2];
plik >> light_specular[i_so][0];
plik >> light_specular[i_so][1];
plik >> light_specular[i_so][2];
plik >> light_diffuse[i_so][0];
plik >> light_diffuse[i_so][1];
plik >> light_diffuse[i_so][2];
plik >> light_ambient[i_so][0];
plik >> light_ambient[i_so][1];
plik >> light_ambient[i_so][2];
i_so++;
}
}
}while( szukaj.find("eof") == string::npos );
cout << "Wczytywanie zakonczone" << endl;
plik.close();
}
}
void Myinit(void)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-viewport_size/2.0f, viewport_size/2.0f, -viewport_size/2.0f, viewport_size/2.0f, -viewport_size/2.0f, viewport_size/2.0f);
glMatrixMode(GL_MODELVIEW);
}
void keys(unsigned char key, int x, int y){
if(key == 'p') start = true;
if(key == 's') start = false;
if(key == 'q') start2 = true;
if(key == 'w') start2 = false;
}
void main(void){
system("Pause");
wczytaj();
glutInitWindowSize(x_im_size, y_im_size);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
glutCreateWindow("Kulki Kamil Markuszewski");
glutIdleFunc(spinEgg);
glutKeyboardFunc(keys);
Myinit();
glutDisplayFunc(RenderScene);
glutMainLoop();
int a;
cin >> a;
}
| [
"[email protected]"
] | |
f4ef7cbb2c0f0c95bf557810fa9e13ecd00c0261 | dd656493066344e70123776c2cc31dd13f31c1d8 | /MITK/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.h | ebc31f9d03ee380ab99a205c68852891b46a650e | [] | no_license | david-guerrero/MITK | e9832b830cbcdd94030d2969aaed45da841ffc8c | e5fbc9993f7a7032fc936f29bc59ca296b4945ce | refs/heads/master | 2020-04-24T19:08:37.405353 | 2011-11-13T22:25:21 | 2011-11-13T22:25:21 | 2,372,730 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,805 | h | /*=========================================================================
Program: BlueBerry Platform
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef BERRYWORKBENCHPLUGIN_H_
#define BERRYWORKBENCHPLUGIN_H_
#include <Poco/Path.h>
#include <berryIExtensionPoint.h>
#include <berryIExtensionPointService.h>
#include <berryPlatform.h>
#include "../berryAbstractUICTKPlugin.h"
#include "../berryPlatformUI.h"
#include "../presentations/berryIPresentationFactory.h"
#include "berryViewRegistry.h"
#include "berryEditorRegistry.h"
#include "berryPerspectiveRegistry.h"
#include "intro/berryIntroRegistry.h"
namespace berry {
/**
* \ingroup org_blueberry_ui_internal
*
* This class represents the TOP of the workbench UI world
* A plugin class is effectively an application wrapper
* for a plugin & its classes. This class should be thought
* of as the workbench UI's application class.
*
* This class is responsible for tracking various registries
* font, preference, graphics, dialog store.
*
* This class is explicitly referenced by the
* workbench plugin's "plugin.xml" and places it
* into the UI start extension point of the main
* overall application harness
*
* When is this class started?
* When the Application
* calls createExecutableExtension to create an executable
* instance of our workbench class.
*/
class WorkbenchPlugin : public QObject, public AbstractUICTKPlugin {
Q_OBJECT
Q_INTERFACES(ctkPluginActivator)
private:
//static const std::string UI_BUNDLE_ACTIVATOR = "org.blueberry.ui.internal.UIPlugin"; //$NON-NLS-1$
// Default instance of the receiver
static WorkbenchPlugin* inst;
// The presentation factory
IPresentationFactory* presentationFactory;
// Manager that maps resources to descriptors of editors to use
EditorRegistry* editorRegistry;
// The context within which this plugin was started.
ctkPluginContext* bundleContext;
// Other data.
//WorkbenchPreferenceManager preferenceManager;
ViewRegistry* viewRegistry;
PerspectiveRegistry* perspRegistry;
IntroRegistry* introRegistry;
//SharedImages sharedImages;
public:
/**
* Global workbench ui plugin flag. Only workbench implementation is allowed to use this flag
* All other plugins, examples, or test cases must *not* use this flag.
*/
static bool DEBUG;
/**
* The character used to separate preference page category ids
*/
static char PREFERENCE_PAGE_CATEGORY_SEPARATOR;
/**
* Create an instance of the WorkbenchPlugin. The workbench plugin is
* effectively the "application" for the workbench UI. The entire UI
* operates as a good plugin citizen.
*/
WorkbenchPlugin();
~WorkbenchPlugin();
/**
* Creates an extension. If the extension plugin has not
* been loaded a busy cursor will be activated during the duration of
* the load.
*
* @param element the config element defining the extension
* @param classAttribute the name of the attribute carrying the class
* @return the extension object
* @throws CoreException if the extension cannot be created
*/
// template<class E>
// static E* CreateExtension(IConfigurationElement::ConstPointer element,
// const std::string& classAttribute) {
// try {
// // If plugin has been loaded create extension.
// // Otherwise, show busy cursor then create extension.
// if (BundleUtility.isActivated(element.getDeclaringExtension()
// .getNamespace())) {
// return element.createExecutableExtension(classAttribute);
// }
// final Object[] ret = new Object[1];
// final CoreException[] exc = new CoreException[1];
// BusyIndicator.showWhile(null, new Runnable() {
// public void run() {
// try {
// ret[0] = element
// .createExecutableExtension(classAttribute);
// } catch (CoreException e) {
// exc[0] = e;
// }
// }
// });
// if (exc[0] != null) {
// throw exc[0];
// }
// return ret[0];
//
// } catch (CoreException core) {
// throw core;
// } catch (Exception e) {
// throw new CoreException(new Status(IStatus.ERR, PI_WORKBENCH,
// IStatus.ERR, WorkbenchMessages.WorkbenchPlugin_extension,e));
// }
// }
/**
* Answers whether the provided element either has an attribute with the
* given name or a child element with the given name with an attribute
* called class.
*
* @param element
* the element to test
* @param extensionName
* the name of the extension to test for
* @return whether or not the extension is declared
* @since 3.3
*/
static bool HasExecutableExtension(IConfigurationElement::Pointer element,
const std::string& extensionName);
/**
* Checks to see if the provided element has the syntax for an executable
* extension with a given name that resides in a bundle that is already
* active. Determining the bundle happens in one of two ways:<br/>
* <ul>
* <li>The element has an attribute with the specified name or element text
* in the form <code>bundle.id/class.name[:optional attributes]</code></li>
* <li>The element has a child element with the specified name that has a
* <code>plugin</code> attribute</li>
* </ul>
*
* @param element
* the element to test
* @param extensionName
* the name of the extension to test for
* @return whether or not the bundle expressed by the above criteria is
* active. If the bundle cannot be determined then the state of the
* bundle that declared the element is returned.
* @since 3.3
*/
static bool IsBundleLoadedForExecutableExtension(
IConfigurationElement::Pointer element, const std::string& extensionName);
/**
* Returns the bundle that contains the class referenced by an executable
* extension. Determining the bundle happens in one of two ways:<br/>
* <ul>
* <li>The element has an attribute with the specified name or element text
* in the form <code>bundle.id/class.name[:optional attributes]</code></li>
* <li>The element has a child element with the specified name that has a
* <code>plugin</code> attribute</li>
* </ul>
*
* @param element
* the element to test
* @param extensionName
* the name of the extension to test for
* @return the bundle referenced by the extension. If that bundle cannot be
* determined the bundle that declared the element is returned. Note
* that this may be <code>null</code>.
* @since 3.3
*/
static IBundle::Pointer GetBundleForExecutableExtension(IConfigurationElement::Pointer element, const std::string& extensionName);
/**
* Return the default instance of the receiver. This represents the runtime plugin.
* @return WorkbenchPlugin
* @see AbstractUICTKPlugin for the typical implementation pattern for plugin classes.
*/
static WorkbenchPlugin* GetDefault();
std::size_t GetBundleCount();
/**
* Answer the manager that maps resource types to a the
* description of the editor to use
* @return IEditorRegistry the editor registry used
* by this plug-in.
*/
IEditorRegistry* GetEditorRegistry();
/**
* Returns the presentation factory with the given id, or <code>null</code> if not found.
* @param targetID The id of the presentation factory to use.
* @return IPresentationFactory or <code>null</code>
* if not factory matches that id.
*/
IPresentationFactory* GetPresentationFactory();
protected:
/**
* Returns the image registry for this plugin.
*
* Where are the images? The images (typically gifs) are found in the same
* plugins directory.
*
* @see ImageRegistry
*
* Note: The workbench uses the standard JFace ImageRegistry to track its
* images. In addition the class WorkbenchGraphicResources provides
* convenience access to the graphics resources and fast field access for
* some of the commonly used graphical images.
*/
// ImageRegistry createImageRegistry();
private:
/**
* Looks up the configuration element with the given id on the given extension point
* and instantiates the class specified by the class attributes.
*
* @param extensionPointId the extension point id (simple id)
* @param elementName the name of the configuration element, or <code>null</code>
* to match any element
* @param targetID the target id
* @return the instantiated extension object, or <code>null</code> if not found
*/
template<class C>
C* CreateExtension(const std::string extensionPointId, const std::string& elementName,
const std::string& targetID) {
const IExtensionPoint* extensionPoint = Platform::GetExtensionPointService()
->GetExtensionPoint("" + PlatformUI::PLUGIN_ID + "." + extensionPointId);
if (extensionPoint == 0) {
WorkbenchPlugin
::Log("Unable to find extension. Extension point: " + extensionPointId + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
return 0;
}
// Loop through the config elements.
IConfigurationElement::Pointer targetElement(0);
IConfigurationElement::vector elements(Platform::GetExtensionPointService()
->GetConfigurationElementsFor("" + PlatformUI::PLUGIN_ID + "." + extensionPointId));
for (unsigned int j = 0; j < elements.size(); j++) {
if (elementName == "" || elementName == elements[j]->GetName()) {
std::string strID;
elements[j]->GetAttribute("id", strID);
if (targetID == strID) {
targetElement = elements[j];
break;
}
}
}
if (targetElement.IsNull()) {
// log it since we cannot safely display a dialog.
WorkbenchPlugin::Log("Unable to find extension: " + targetID //$NON-NLS-1$
+ " in extension point: " + extensionPointId); //$NON-NLS-1$
return 0;
}
// Create the extension.
try {
C* impl = targetElement->CreateExecutableExtension<C>("class"); //$NON-NLS-1$
if (impl == 0)
{
// support legacy BlueBerry extensions
impl = targetElement->CreateExecutableExtension<C>("class", C::GetManifestName());
}
return impl;
} catch (CoreException e) {
// log it since we cannot safely display a dialog.
WorkbenchPlugin::Log("Unable to create extension: " + targetID //$NON-NLS-1$
+ " in extension point: " + extensionPointId); //$NON-NLS-1$
}
return 0;
}
public:
/**
* Return the perspective registry.
* @return IPerspectiveRegistry. The registry for the receiver.
*/
IPerspectiveRegistry* GetPerspectiveRegistry();
/**
* Returns the introduction registry.
*
* @return the introduction registry.
* @since 3.0
*/
IIntroRegistry* GetIntroRegistry();
/**
* Get the preference manager.
* @return PreferenceManager the preference manager for
* the receiver.
*/
// PreferenceManager getPreferenceManager();
/**
* Returns the shared images for the workbench.
*
* @return the shared image manager
*/
// ISharedImages getSharedImages();
/**
* Answer the view registry.
* @return IViewRegistry the view registry for the
* receiver.
*/
IViewRegistry* GetViewRegistry();
/**
* Logs the given message to the platform log.
*
* If you have an exception in hand, call log(String, Throwable) instead.
*
* If you have a status object in hand call log(String, IStatus) instead.
*
* This convenience method is for internal use by the Workbench only and
* must not be called outside the Workbench.
*
* @param message
* A high level UI message describing when the problem happened.
*/
static void Log(const std::string& message);
/**
* Log the throwable.
* @param t
*/
static void Log(const Poco::RuntimeException& exc);
/**
* Logs the given message and throwable to the platform log.
*
* If you have a status object in hand call log(String, IStatus) instead.
*
* This convenience method is for internal use by the Workbench only and
* must not be called outside the Workbench.
*
* @param message
* A high level UI message describing when the problem happened.
* @param t
* The throwable from where the problem actually occurred.
*/
static void Log(const std::string& message, const Poco::RuntimeException& t);
/**
* Logs the given throwable to the platform log, indicating the class and
* method from where it is being logged (this is not necessarily where it
* occurred).
*
* This convenience method is for internal use by the Workbench only and
* must not be called outside the Workbench.
*
* @param clazz
* The calling class.
* @param methodName
* The calling method name.
* @param t
* The throwable from where the problem actually occurred.
*/
static void Log(const std::string& clazz, const std::string& methodName, const Poco::RuntimeException& t);
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
void start(ctkPluginContext* context);
/**
* Return an array of all bundles contained in this workbench.
*
* @return an array of bundles in the workbench or an empty array if none
* @since 3.0
*/
//const std::vector<IBundle::Pointer> GetBundles();
/**
* Returns the bundle context associated with the workbench plug-in.
*
* @return the bundle context
* @since 3.1
*/
ctkPluginContext* GetPluginContext();
/* (non-Javadoc)
* @see org.blueberry.ui.plugin.AbstractUICTKPlugin#stop(org.osgi.framework.BundleContext)
*/
void stop(ctkPluginContext* context);
/**
* FOR INTERNAL WORKBENCH USE ONLY.
*
* Returns the path to a location in the file system that can be used
* to persist/restore state between workbench invocations.
* If the location did not exist prior to this call it will be created.
* Returns <code>null</code> if no such location is available.
*
* @return path to a location in the file system where this plug-in can
* persist data between sessions, or <code>null</code> if no such
* location is available.
* @since 3.1
*/
bool GetDataPath(Poco::Path& path);
};
}
#endif /*BERRYWORKBENCHPLUGIN_H_*/
| [
"[email protected]"
] | |
0356298e64c149384745730fe5e9d33fab39cdeb | 758f58a72af4a65fa8ce185455180c496fc84436 | /ExtMappingTool/upgrade_menu.cpp | 6dcf12b1a0369636d86e09f960f65114ed947f20 | [] | no_license | iquare/mapquare | 89ce363ed5db49a6a349ab67830b81f663e02ac5 | e34f830f2e6fb7b17f1ef9056c7a998d41eebd28 | refs/heads/master | 2022-11-05T00:37:04.233578 | 2020-06-17T15:13:34 | 2020-06-17T15:13:34 | 272,905,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,353 | cpp | #include "stdafx.h"
#include "upgrade_menu.h"
#include "triggerdialog.h"
#include "TriggerSystem.h"
#include "functions.h"
upgrade_menu::upgrade_menu(QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
scroll_area = new QScrollArea(this);
scroll_area->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
QWidget *viewport = new QWidget(this);
scroll_area->setWidget(viewport);
scroll_area->setWidgetResizable(true);
d_layout = new QVBoxLayout(this);
viewport->setLayout(d_layout);
d_layout->setSizeConstraint(QLayout::SetFixedSize);
setInterface(false);
api.first_open[DialogMenu::Upgrades] = true;
dialog_layout = new QVBoxLayout(this);
this->setLayout(dialog_layout);
this->layout()->addWidget(scroll_area);
this->setWindowIcon(this->style()->standardIcon(QStyle::SP_DialogOkButton));
}
upgrade_menu::~upgrade_menu()
{
}
void upgrade_menu::ResetInterface(bool read_from_data){
if (!read_from_data) {
scroll_area->deleteLater();
dialog_layout->deleteLater();
d_layout->deleteLater();
for (auto a : initialLevelBoxes) {
a->deleteLater();
}
for (auto a : maxLevelBoxes) {
a->deleteLater();
}
for (auto a : upgradeHeaderLabels) {
a->deleteLater();
}
for (auto a : upgradeNameLabels) {
a->deleteLater();
}
for (auto a : lowerEscalationButtons) {
a->deleteLater();
}
for (auto a : upperEscalationButtons) {
a->deleteLater();
}
for (auto a : initialLevelLabels) {
a->deleteLater();
}
for (auto a : maxLevelLabels) {
a->deleteLater();
}
for (auto a : buttonGroups) {
a->deleteLater();
}
for (auto a : dummy_labels) {
a->deleteLater();
}
for (auto a : playerButtons) {
a->deleteLater();
}
initialLevelBoxes.clear();
maxLevelBoxes.clear();
upgradeHeaderLabels.clear();
upgradeNameLabels.clear();
lowerEscalationButtons.clear();
upperEscalationButtons.clear();
buttonGroups.clear();
dummy_labels.clear();
playerButtons.clear();
}
setInterface(read_from_data);
}
void upgrade_menu::fillDataFromInterface() {
//add later
//unlike other menus, it fills from internal data instead of interface
//upgrades_data.resize(255);
upgrades_data.clear();
int size = 0;
for (auto a : internal_info) {
std::vector<Ext> upg;
upg.resize(256);
for (auto b : a.second) {
upg[b.second.upgrade_id] = b.second;
size++;
}
upgrades_data.push_back(upg);
}
QMessageBox::information(this, tr("Unable to open file"),
QString::fromStdString("Upgrades data size after filling: " +
WriteInt(upgrades_data.size())+" "+WriteInt(size)));
}
void upgrade_menu::maxBoxTextChanged(){
QPlainTextEdit *edit = qobject_cast<QPlainTextEdit*>(sender());
Q_ASSERT(edit);
auto text = edit->toPlainText();
auto string = text.toStdString();
auto index = qvariant_cast<int>(edit->property("upgrade"));
bool change = false;
if (string.length() > 0) {
/* QMessageBox::information(this, tr("Unable to open file"),
QString::fromStdString(string));*/
if (!is_numeric(string)) {
string = WriteInt(definitions[index].max_level);
change = true;
}
else {
if (StringToInt(string) > 255) {
string = "255";
change = true;
}
}
}
else {
string = "0";
change = true;
}
if (internal_info[currentPlayer][index].max != StringToInt(string)) {
change = true;
}
if (string == maxBoxRecursionCheck) {
return;
}
maxBoxRecursionCheck = string;
if (change) {
edit->setPlainText(QString::fromStdString(string));
internal_info[currentPlayer][index].max = StringToInt(string);
}
maxBoxRecursionCheck = "";
}
void upgrade_menu::initialBoxTextChanged(){
QPlainTextEdit *edit = qobject_cast<QPlainTextEdit*>(sender());
Q_ASSERT(edit);
auto text = edit->toPlainText();
auto string = text.toStdString();
auto index = qvariant_cast<int>(edit->property("upgrade"));
if (definitions[index].escalation) {
return;
}
bool change = false;
if (string.length() > 0) {
if (!is_numeric(string)) {
string = "0";
change = true;
}
else {
if (StringToInt(string) > 255) {
string = "255";
change = true;
}
}
}
else {
string = "0";
change = true;
}
if (internal_info[currentPlayer][index].initial != StringToInt(string)) {
change = true;
}
if (string == iniBoxRecursionCheck) {
return;
}
iniBoxRecursionCheck = string;
if (change) {
edit->setPlainText(QString::fromStdString(string));
}
if (change) {
edit->setPlainText(QString::fromStdString(string));
internal_info[currentPlayer][index].initial = StringToInt(string);
}
iniBoxRecursionCheck = "";
}
void upgrade_menu::escButtonLowClicked(){
QRadioButton *button = qobject_cast<QRadioButton*>(sender());
Q_ASSERT(button);
auto index = qvariant_cast<int>(button->property("upgrade"));
internal_info[currentPlayer][index].escalation_status = definitions[index].lower.id;
}
void upgrade_menu::escButtonHighClicked(){
QRadioButton *button = qobject_cast<QRadioButton*>(sender());
Q_ASSERT(button);
auto index = qvariant_cast<int>(button->property("upgrade"));
internal_info[currentPlayer][index].escalation_status = definitions[index].upper.id;
}
void upgrade_menu::playerButtonClicked() {
QPushButton *button = qobject_cast<QPushButton*>(sender());
Q_ASSERT(button);
auto index = qvariant_cast<int>(button->property("player"));
currentPlayer = index;
/*QMessageBox::information(this, tr("Unable to open file"),
QString::fromStdString("Set player to " + WriteInt(currentPlayer)));
QMessageBox::information(this, tr("Unable to open file"),
QString::fromStdString("Player 1 cyp max level: " + WriteInt(internal_info[0][62].max)));
*/
for(auto a : initialLevelBoxes){
int index = qvariant_cast<int>(a->property("upgrade"));
a->setPlainText(QString::fromStdString(WriteInt(internal_info[currentPlayer][index].initial)));
/*
if (internal_info[currentPlayer][index].escalation_status==0xe4) {
a->setPlainText("");
}
else {
a->setPlainText(QString::fromStdString(WriteInt(internal_info[currentPlayer][index].initial)));
}*/
}
for (auto a : maxLevelBoxes) {
int index = qvariant_cast<int>(a->property("upgrade"));
a->setPlainText(QString::fromStdString(WriteInt(internal_info[currentPlayer][index].max)));
}
for(auto a : lowerEscalationButtons){
int index = qvariant_cast<int>(a->property("upgrade"));
if (internal_info[currentPlayer][index].escalation_status != 0xe4) {
if (definitions[index].lower.id == internal_info[currentPlayer][index].escalation_status) {
a->click();
}
}
}
for (auto a : upperEscalationButtons) {
int index = qvariant_cast<int>(a->property("upgrade"));
if (internal_info[currentPlayer][index].escalation_status != 0xe4) {
if (definitions[index].upper.id == internal_info[currentPlayer][index].escalation_status) {
a->click();
}
}
}
recolorButtons();
}
void upgrade_menu::prepareWidgetForLayout(QWidget *widget, int pos_x, int pos_y, int bound_x, int bound_y) {
widget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
widget->setGeometry(pos_x, pos_y,
bound_x, bound_y);
widget->updateGeometry();
widget->setFixedSize(bound_x, bound_y);
}
void upgrade_menu::SetDataValuesFromArchive() {
iter_enumerated(upgrades_data, [&](std::vector<Ext> a, int i) {
int j = 0;
for (auto b : a) {
if (j >= 62) {
if (i == 0) {
/* QMessageBox::information(this, tr("Unable to open file"),
QString::fromStdString(WriteInt(j) + " " + WriteInt(b.upgrade_id) + " " + WriteInt(b.max) + " " + WriteInt(b.escalation_status)));
*/
}
internal_info[i][b.upgrade_id] = b;
}
j++;
}
});
for (int i = 0; i < initialLevelBoxes.size();i++) {
auto index = qvariant_cast<int>(initialLevelBoxes[i]->property("upgrade"));
initialLevelBoxes[i]->setPlainText(QString::fromStdString
(WriteInt(upgrades_data[currentPlayer][index].initial)));
maxLevelBoxes[i]->setPlainText(QString::fromStdString
(WriteInt(upgrades_data[currentPlayer][index].max)));
}
for (int i = 0; i < lowerEscalationButtons.size(); i++) {
auto index = qvariant_cast<int>(lowerEscalationButtons[i]->property("upgrade"));
if (internal_info[currentPlayer][index].escalation_status != 0xe4) {
if (upgrades_data[currentPlayer][index].escalation_status == definitions[index].lower.id) {
lowerEscalationButtons[i]->click();
}
else {
upperEscalationButtons[i]->click();
}
}
}
}
void upgrade_menu::colorize_button(QPushButton* button, u32 color) {
u32 r = color & 0xff;
u32 g = (color & 0xff00)>>8;
u32 b = (color & 0xff0000)>>16;
std::stringstream ss;
ss << "background-color: rgb(";
ss << WriteInt(r); ss << ", ";
ss << WriteInt(g); ss << ", ";
ss << WriteInt(b);
ss << "); color: rgb(0, 0, 0)";
button->setAutoFillBackground(true);
button->setStyleSheet(QString::fromStdString(ss.str()));
}
void upgrade_menu::recolorButtons() {
iter_enumerated(playerButtons, [&](QPushButton* button, int i) {
if (currentPlayer == i) {
colorize_button(button, 0xffffef);
}
else {
colorize_button(button, 0xdddddd);
}
});
}
void upgrade_menu::setInterface(bool read_from_data){
if (read_from_data) {
SetDataValuesFromArchive();
return;
}
currentPlayer = 0;
ui.upgradeName->hide();
ui.upgradeNameHeaderPlaceholder->hide();
ui.initialLevelPlaceholder->hide();
ui.maxLevelPlaceholder->hide();
ui.initialLevelTextbox->hide();
ui.maxLevelTextbox->hide();
ui.lowerEscalationButton->hide();
ui.upperEscalationButton->hide();
/*std::ifstream upgrade_def_config, ext_upgrades_data, escalations;
std::map<int, std::vector<std::string>> unit_name;
*/
auto dummy_layout = new QHBoxLayout(this);
d_layout->addLayout(dummy_layout);
internal_info.clear();
for (auto a : definitions) {
for (int i = 0; i < 8; i++) {
internal_info[i][a.first].initial = 0;
internal_info[i][a.first].max = a.second.max_level;
internal_info[i][a.first].upgrade_id = a.first;
if (a.second.escalation) {
internal_info[i][a.first].escalation_status = a.second.lower.id;
}
}
}
auto button_layout = new QHBoxLayout(this);
for (int i = 0; i < 8; i++) {
auto player = new QPushButton(this);
player->setProperty("player", QVariant::fromValue(i));
connect(player, SIGNAL(clicked()),
this, SLOT(playerButtonClicked()));
playerButtons.push_back(player);
player->setText(QString::fromStdString("Player "+WriteInt(i+1)));
prepareWidgetForLayout(player, 0, 0, 75, 23);
button_layout->addWidget(player);
}
recolorButtons();
d_layout->addLayout(button_layout);
for (auto a : definitions) {
int i = a.first - 62;
auto level_layout = new QHBoxLayout(this);
auto head_layout = new QBoxLayout(QBoxLayout::Direction::LeftToRight,this);
auto header = new QLabel("Upgrade", this);
upgradeHeaderLabels.push_back(header);
prepareWidgetForLayout(header, ui.upgradeNameHeaderPlaceholder->x(),
ui.upgradeNameHeaderPlaceholder->y() + 40 * i,
101, 16);
auto upgrade = new QLabel(QString::fromStdString(a.second.name), this);
upgradeNameLabels.push_back(upgrade);
prepareWidgetForLayout(upgrade, ui.upgradeName->x(),ui.upgradeName->y() + 40 * i,
171, 16);
head_layout->addWidget(header);
head_layout->addWidget(upgrade);
level_layout->addLayout(head_layout);
auto initial_box_layout = new QHBoxLayout(this);
initial_box_layout->setStretch(0, 0);
auto initial = new QLabel("Initial Level", this);
initialLevelLabels.push_back(initial);
//initial->setGeometry(ui.initialLevelPlaceholder->x(), ui.initialLevelPlaceholder->y() + 40 * i, 171, 16);
prepareWidgetForLayout(initial, ui.initialLevelPlaceholder->x(),
ui.initialLevelPlaceholder->y() + 40 * i,
61, 16);
initial_box_layout->addWidget(initial);
auto initial_textbox = new QPlainTextEdit(this);
initial_textbox->setProperty("upgrade", QVariant::fromValue(a.first));
initial_textbox->setProperty("count", QVariant::fromValue(initialLevelBoxes.size()));
connect(initial_textbox, SIGNAL(textChanged()),
this, SLOT(initialBoxTextChanged()));
initialLevelBoxes.push_back(initial_textbox);
int x = ui.initialLevelTextbox->x();
int y = ui.initialLevelTextbox->y();
// initial_textbox->setGeometry(x, y + 40 * i, 41, 21);
initial_textbox->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
initial_textbox->setFrameShape(QFrame::StyledPanel);
if (a.second.escalation) {
initial_textbox->setDisabled(true);
initial->setDisabled(true);/*
QMessageBox::information(this, tr("Unable to open file"),
QString::fromStdString("Disable: " + WriteInt(i) + " " + WriteInt(a.first)));*/
}
std::string str = "0";
if (!a.second.escalation) {
initial_textbox->setPlainText(QString::fromStdString(str));
}
prepareWidgetForLayout(initial_textbox, x, y, 41, 21);
initial_box_layout->addWidget(initial_textbox);
level_layout->addLayout(initial_box_layout);
auto max_layout = new QHBoxLayout(this);
auto max = new QLabel("Max Level", this);
maxLevelLabels.push_back(max);
prepareWidgetForLayout(max, x, y, 61, 16);
//max->setGeometry(ui.maxLevelPlaceholder->x(), ui.maxLevelPlaceholder->y() + 40 * i, 171, 16);
max_layout->addWidget(max);
auto max_textbox = new QPlainTextEdit(this);
max_textbox->setProperty("upgrade", QVariant::fromValue(a.first));
max_textbox->setProperty("count", QVariant::fromValue(maxLevelBoxes.size()));
// max_textbox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(max_textbox, SIGNAL(textChanged()),
this, SLOT(maxBoxTextChanged()));
maxLevelBoxes.push_back(max_textbox);
x = ui.maxLevelTextbox->x();
y = ui.maxLevelTextbox->y();
prepareWidgetForLayout(max_textbox, x, y, 41, 20);
max_textbox->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
max_textbox->setFrameShape(QFrame::StyledPanel);
str = WriteInt(a.second.max_level);
max_textbox->setPlainText(QString::fromStdString(str));
max_layout->addWidget(max_textbox);
level_layout->addLayout(max_layout);
auto escalation_layout = new QHBoxLayout(this);
if (definitions[a.first].escalation) {
auto esc_button_low = new QRadioButton(QString::fromStdString(a.second.lower.name),this);
connect(esc_button_low, SIGNAL(clicked()),
this, SLOT(escButtonLowClicked()));
esc_button_low->setProperty("upgrade", QVariant::fromValue(a.first));
esc_button_low->setProperty("escalation", QVariant::fromValue(a.first));
lowerEscalationButtons.push_back(esc_button_low);
x = ui.lowerEscalationButton->x();
y = ui.lowerEscalationButton->y();
//esc_button_low->setGeometry(x, y + 40 * i, 115, 17);
prepareWidgetForLayout(esc_button_low, x,y+40*i,115, 17);
escalation_layout->addWidget(esc_button_low);
auto esc_button_high = new QRadioButton(QString::fromStdString(a.second.upper.name),this);
connect(esc_button_high, SIGNAL(clicked()),
this, SLOT(escButtonHighClicked()));
esc_button_high->setProperty("upgrade", QVariant::fromValue(a.first));
esc_button_high->setProperty("escalation", QVariant::fromValue(a.second.escalation));
upperEscalationButtons.push_back(esc_button_high);
x = ui.upperEscalationButton->x();
y = ui.upperEscalationButton->y();
//esc_button_high->setGeometry(x, y + 40 * i, 115, 17);
prepareWidgetForLayout(esc_button_high, x, y + 40 * i, 115, 17);
escalation_layout->addWidget(esc_button_high);
level_layout->addLayout(escalation_layout);
//
auto group = new QButtonGroup(this);
group->addButton(esc_button_high);
group->addButton(esc_button_low);
buttonGroups.push_back(group);
esc_button_low->click();
}
else {
auto dummy = new QLabel(this);
x = ui.lowerEscalationButton->x();
y = ui.lowerEscalationButton->y();
prepareWidgetForLayout(dummy, x, y + 40 * i, 115, 17);
dummy_labels.push_back(dummy);
escalation_layout->addWidget(dummy);
//
x = ui.upperEscalationButton->x();
y = ui.upperEscalationButton->y();
prepareWidgetForLayout(dummy, x, y + 40 * i, 115, 17);
escalation_layout->addWidget(dummy);
}
level_layout->addLayout(escalation_layout);
d_layout->addLayout(level_layout);
}
/*
for (auto a : definitions) {
QMessageBox::information(this, tr("Unable to open file"),
QString::fromStdString("Key: " + WriteInt(a.first) + " Max: " + WriteInt(a.second.max_level) + " Name: " + a.second.name));
}*/
} | [
"[email protected]"
] | |
d1692fe3e689bb41b2101d65c43168c75790a819 | 9130fe27947256391831adcdccfbef41d8de2b3d | /public/perfmon.h | be425c3a4e0f36479f27b2b92731a4ae18cdad40 | [
"BSD-2-Clause"
] | permissive | apronchenkov/perfmon | f5e44f43ec9987fded738526e976401cd1370ffb | 4a3046d376a8a0ac44cf9f928d1cacdfae18ca0d | refs/heads/master | 2020-05-21T03:29:40.694015 | 2019-04-25T02:20:49 | 2019-04-25T02:20:49 | 8,254,583 | 3 | 2 | null | 2016-08-19T13:13:25 | 2013-02-17T18:37:09 | C++ | UTF-8 | C++ | false | false | 2,169 | h | /**
* Performance monitor library
*
* Usage:
*
* You could use the PERFMON_SCOPE for a scope inside of a function:
*
* {
* PERFMON_SCOPE("counter_name");
* ... // scope body
* }
*
* or the PERFMON_STATEMENT for a statement:
*
* PERFMON_STATEMENT("counter_name") {
* ... // statement
* }
*
* WARNING! Most probably you would not like to use the PERFMON macros in
* recursive scopes. You could, if you understand what you want; but values of
* tick counter would be a bit crazy for a human being.
*
* You could get current statistics in the following way:
*
* for (const auto& counter : PERFMON_COUNTERS()) {
* std::cout << counter.Name() << ' '
* << counter.Calls() << ' '
* << counter.Seconds() << std::endl;
* }
*
* Values of PERFMON_COUNTERS() can be influenced by non-atomicity
* of the integer arithmetic. I believe that this problem should be very rare.
* You can also call PERFMON_COUNTER() three times in row and use the median.
*
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace perfmon {
class Counter {
public:
/** Constructor */
Counter(const std::string *name_ptr, uint64_t calls, uint64_t ticks);
/** Name of the counter scope */
const std::string &Name() const;
/** Total number of calls */
uint64_t Calls() const;
/** Total ticks have spent */
uint64_t Ticks() const;
/** Total seconds have been spent */
double Seconds() const;
/** Average seconds have been spent per call */
double AverageSeconds() const;
private:
const std::string *name_ptr_;
uint64_t calls_;
uint64_t ticks_;
};
class Counters : public std::vector<Counter> {
public:
Counter operator[](const char *name) const;
};
} // namespace perfmon
/** Get list of the available counters */
#define PERFMON_COUNTERS()
/** Create a monitor for the following scope */
#define PERFMON_SCOPE(counter_name)
/** Create a monitor for the following statement */
#define PERFMON_STATEMENT(counter_name)
#define PERFMON_INL_H
#include "perfmon/perfmon_inl.h"
#undef PERFMON_INL_H
| [
"[email protected]"
] | |
7b0ef23c4b8f8b07ada31d4c25c4df1173f62599 | a203ab06b7293100b7b168de1986243a38e0ea0d | /UE/QtApplicationEnvironment/GUI/QtMainWindow.hpp | aec2eaec4dc02ba86a61935eeac179179cf317b5 | [] | no_license | Mular8/NOKIA-PK | ce9555ece983628065c4028ace0ae8f5d2b7aafe | 0762b575e3c828401b44c03fcc3577f244d50d62 | refs/heads/master | 2021-02-03T23:29:08.965604 | 2020-06-16T08:16:54 | 2020-06-16T08:16:54 | 243,572,881 | 0 | 0 | null | 2020-06-16T07:35:53 | 2020-02-27T17:13:28 | C++ | UTF-8 | C++ | false | false | 420 | hpp | #pragma once
#include "IUeGui.hpp"
#include <QMainWindow>
#include <QKeyEvent>
#include "Logger/ILogger.hpp"
namespace ue
{
class QtMainWindow : public QMainWindow
{
Q_OBJECT
public:
QtMainWindow();
void setCloseGuard(const IUeGui::CloseGuard &value);
void closeEvent(QCloseEvent* event) override;
private:
IUeGui::CloseGuard closeGuard;
bool closeAccepted();
};
}
| [
"[email protected]"
] | |
b494f724d1b467260073b3653c270143824c9ccc | 1b117b31656a47777920c9abeabc280cacbfa020 | /common/game/Obstacle.cpp | c5be42a4d645686d3fe71dfd756e73d73e25c7ae | [] | no_license | ucsd-cse125-sp21/cse125-sp21-group4 | 6af318033ddb4d00c2d2afb8124ab466351e5575 | 1591bed79d93f9fedbdd7081b128162518e31141 | refs/heads/main | 2023-05-09T10:55:07.359574 | 2021-06-04T21:34:06 | 2021-06-04T21:34:06 | 353,153,132 | 5 | 3 | null | 2021-06-04T21:34:07 | 2021-03-30T22:03:48 | C | UTF-8 | C++ | false | false | 179 | cpp | #include "Obstacle.h"
Obstacle::Obstacle() { setType(OBSTACLE); }
Obstacle::Obstacle(GridPosition position) {
setType(OBSTACLE);
setPosition(position.x, position.y);
}
| [
"[email protected]"
] | |
e2825b7937e0936d20da6d3835c16c17a793811e | 0bf0c508e18557941ae0f1480779145f56fa19fa | /examples/Effects/Freeverb_Stereo/Freeverb_Stereo.ino | b07c16eab415918331e2ffc0330689ae7688c1ce | [] | no_license | PaulStoffregen/Audio | 3b63c293f58951e3f8eedc2d527e3f53ba866103 | 4cee15b6d008dd9237ac413a946d84f1030790c0 | refs/heads/master | 2023-08-17T16:42:10.254817 | 2023-07-05T12:44:37 | 2023-07-05T12:44:37 | 15,644,096 | 926 | 468 | null | 2023-06-28T15:58:12 | 2014-01-05T02:31:09 | C++ | UTF-8 | C++ | false | false | 4,455 | ino | // Freeverb - High quality reverb effect
//
// Teensy 3.5 or higher is required to run this example
//
// The SD card may connect to different pins, depending on the
// hardware you are using. Uncomment or configure the SD card
// pins to match your hardware.
//
// Data files to put on your SD card can be downloaded here:
// http://www.pjrc.com/teensy/td_libs_AudioDataFiles.html
//
// This example code is in the public domain.
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
// GUItool: begin automatically generated code
AudioPlaySdWav playSdWav1; //xy=163,135
AudioMixer4 mixer1; //xy=332,167
AudioEffectFreeverbStereo freeverbs1; //xy=490,92
AudioMixer4 mixer3; //xy=653,231
AudioMixer4 mixer2; //xy=677,152
AudioOutputI2S i2s1; //xy=815,198
AudioConnection patchCord1(playSdWav1, 0, mixer1, 0);
AudioConnection patchCord2(playSdWav1, 1, mixer1, 1);
AudioConnection patchCord3(mixer1, 0, mixer2, 1);
AudioConnection patchCord4(mixer1, freeverbs1);
AudioConnection patchCord5(mixer1, 0, mixer3, 1);
AudioConnection patchCord6(freeverbs1, 0, mixer2, 0);
AudioConnection patchCord7(freeverbs1, 1, mixer3, 0);
AudioConnection patchCord8(mixer3, 0, i2s1, 1);
AudioConnection patchCord9(mixer2, 0, i2s1, 0);
AudioControlSGTL5000 sgtl5000_1; //xy=236,248
// GUItool: end automatically generated code
// Use these with the Teensy Audio Shield
#define SDCARD_CS_PIN 10
#define SDCARD_MOSI_PIN 7 // Teensy 4 ignores this, uses pin 11
#define SDCARD_SCK_PIN 14 // Teensy 4 ignores this, uses pin 13
// Use these with the Teensy 3.5 & 3.6 & 4.1 SD card
//#define SDCARD_CS_PIN BUILTIN_SDCARD
//#define SDCARD_MOSI_PIN 11 // not actually used
//#define SDCARD_SCK_PIN 13 // not actually used
// Use these for the SD+Wiz820 or other adaptors
//#define SDCARD_CS_PIN 4
//#define SDCARD_MOSI_PIN 11
//#define SDCARD_SCK_PIN 13
void setup() {
Serial.begin(9600);
// Audio connections require memory to work. For more
// detailed information, see the MemoryAndCpuUsage example
AudioMemory(10);
// Comment these out if not using the audio adaptor board.
// This may wait forever if the SDA & SCL pins lack
// pullup resistors
sgtl5000_1.enable();
sgtl5000_1.volume(0.5);
SPI.setMOSI(SDCARD_MOSI_PIN);
SPI.setSCK(SDCARD_SCK_PIN);
if (!(SD.begin(SDCARD_CS_PIN))) {
// stop here, but print a message repetitively
while (1) {
Serial.println("Unable to access the SD card");
delay(500);
}
}
mixer1.gain(0, 0.5);
mixer1.gain(1, 0.5);
mixer2.gain(0, 0.9); // hear 90% "wet"
mixer2.gain(1, 0.1); // and 10% "dry"
mixer3.gain(0, 0.9);
mixer3.gain(1, 0.1);
}
void playFile(const char *filename)
{
Serial.print("Playing file: ");
Serial.println(filename);
// Start playing the file. This sketch continues to
// run while the file plays.
playSdWav1.play(filename);
// A brief delay for the library read WAV info
delay(5);
elapsedMillis msec;
// Simply wait for the file to finish playing.
while (playSdWav1.isPlaying()) {
// while the music plays, adjust parameters and print info
if (msec > 250) {
msec = 0;
float knob_A1 = 0.9;
float knob_A2 = 0.5;
float knob_A3 = 0.5;
// Uncomment these lines to adjust parameters with analog inputs
//knob_A1 = (float)analogRead(A1) / 1023.0;
//knob_A2 = (float)analogRead(A2) / 1023.0;
//knob_A3 = (float)analogRead(A3) / 1023.0;
mixer2.gain(0, knob_A1);
mixer2.gain(1, 1.0 - knob_A1);
mixer3.gain(0, knob_A1);
mixer3.gain(1, 1.0 - knob_A1);
freeverbs1.roomsize(knob_A2);
freeverbs1.damping(knob_A3);
Serial.print("Reverb: mix=");
Serial.print(knob_A1 * 100.0);
Serial.print("%, roomsize=");
Serial.print(knob_A2 * 100.0);
Serial.print("%, damping=");
Serial.print(knob_A3 * 100.0);
Serial.print("%, CPU Usage=");
Serial.print(freeverbs1.processorUsage());
Serial.println("%");
}
}
}
void loop() {
playFile("SDTEST1.WAV"); // filenames are always uppercase 8.3 format
delay(500);
playFile("SDTEST2.WAV");
delay(500);
playFile("SDTEST3.WAV");
delay(500);
playFile("SDTEST4.WAV");
delay(1500);
}
| [
"[email protected]"
] | |
b3968a302fbb9afe2cd477b4162dc009f92f9173 | 1d015b1c32ad0540f48f4172a26b13d9df7f31dd | /lib/RenderCore_PrimeRef/kernels/.cuda.h | 511cd9a4941e318e289eed495a74576b30389bf4 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ICYou/lighthouse2 | 5475ede9a2334b863801aa15c988f9e049d14545 | 44ede1d83d109291ecd102a5f3eaa435612648b9 | refs/heads/master | 2020-09-15T09:29:29.421221 | 2019-11-25T21:42:51 | 2019-11-25T21:42:51 | 223,410,743 | 1 | 0 | Apache-2.0 | 2019-11-25T21:50:29 | 2019-11-22T13:34:19 | C++ | UTF-8 | C++ | false | false | 1,687 | h | /* .cuda.h - Copyright 2019 Utrecht University
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.
*/
// generic includes
#include <stdio.h>
// custom types
typedef unsigned int uint;
typedef unsigned char uchar;
// platform specific
#include "../CUDA/helper_math.h"
#ifdef __CUDACC__
#include "cuda_fp16.h"
#else
#include "half.hpp"
#endif
#include "../core_settings.h"
#include "common_settings.h"
#include "common_classes.h"
#if __CUDA_ARCH__ >= 700
#define THREADMASK __activemask() // volta, turing
#else
#define THREADMASK 0xffffffff // pascal, kepler, fermi
#endif
// suppress errors outside nvcc
#include "noerrors2.h"
// convenience macros
#define NEXTMULTIPLEOF(a,b) (((a)+((b)-1))&(0x7fffffff-((b)-1)))
// camera lens
#define APPERTURE_BLADES 9
// final pixel buffer for output
surface<void, cudaSurfaceType2D> renderTarget;
namespace lh2core
{
__host__ const surfaceReference* renderTargetRef()
{
const surfaceReference* s;
cudaGetSurfaceReference( &s, &renderTarget );
return s;
}
} // namespace lh2core
// function defintion helper
#define LH2_DEVFUNC static __forceinline__ __device__
// identify this compile as the OptixPrime one
#define OPTIXPRIMEBUILD
// EOF | [
"[email protected]"
] | |
e42e47381e89e15a0e7626b52245a8201b44403a | f9aff42b97bd9bf56d9edd4811dc2facd07ef496 | /src/evaluator/ops/k210/k210_ops.cpp | 6acdddbf17761840cdea8f483a106bccb6abecdc | [
"Apache-2.0"
] | permissive | Yuan-onion/nncase | 2027c3ee349c6a51e86522e36d218b7df0cd281b | 4f0ebb5bd2b34b6b3060c9026f9e2e2d2e8f177d | refs/heads/master | 2020-07-03T21:26:39.505612 | 2019-08-12T05:31:42 | 2019-08-12T05:31:42 | 202,055,392 | 1 | 0 | Apache-2.0 | 2019-08-13T03:18:46 | 2019-08-13T03:18:46 | null | UTF-8 | C++ | false | false | 2,527 | cpp | /* Copyright 2019 Canaan Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ir/evaluator.h>
#include <ir/ops/k210/fake_kpu_conv2d.h>
#include <kernels/k210/k210_kernels.h>
using namespace nncase;
using namespace nncase::scheduler;
using namespace nncase::ir;
using namespace nncase::ir::k210;
namespace nncase
{
namespace ir
{
void register_k210_evaluators()
{
register_evaluator(op_k210_fake_kpu_conv2d, [](ir::node &node, evaluate_context &context) {
auto &rnode = static_cast<fake_kpu_conv2d &>(node);
assert(rnode.input().type() == dt_float32);
auto input = context.memory_at<float>(rnode.input());
auto output = context.memory_at<float>(rnode.output());
auto in_shape = rnode.input().shape();
shape_t conv_out_shape { in_shape[0], (size_t)rnode.output_channels(), in_shape[2], in_shape[3] };
auto conv_out_fmap_size = xt::compute_size(conv_out_shape);
auto conv_output_tmp = std::make_unique<float[]>(conv_out_fmap_size);
#define KPU_CONV2D_IMPL(is_depthwise_val, filter_size_val) \
if (rnode.is_depthwise() == is_depthwise_val && runtime::k210::get_kpu_filter_size(rnode.filter_type()) == filter_size_val) \
kernels::k210::fake_kpu_conv2d<is_depthwise_val, filter_size_val>(input.data(), conv_output_tmp.get(), rnode.weights().data(), \
rnode.bias().data(), in_shape[2], in_shape[3], in_shape[1], rnode.output_channels(), rnode.fused_activation())
KPU_CONV2D_IMPL(true, 1);
else KPU_CONV2D_IMPL(true, 3);
else KPU_CONV2D_IMPL(false, 1);
else KPU_CONV2D_IMPL(false, 3);
kernels::k210::kpu_pool2d(conv_output_tmp.get(), output.data(), in_shape[2], in_shape[3], rnode.output_channels(),
rnode.pool_type());
});
}
}
}
| [
"[email protected]"
] | |
95a9b03e6cc5d14e433eaa4863f1ebdeebb7c4e3 | 087f98db3fe1ee6bdc5625f3d1888dfb5c0070f5 | /Q_learnig_by_STVIAN004/Q_learning/CDiscCollisionObject.cpp | 9359e9dee77e3da91b1752477653bd832b56545c | [] | no_license | IanStevens1/Q-Learning | 56bb5bbaa21df9476b247d8238e7c9711a842cb7 | f0082677e8236a6ac0e6db14a48a53d1baf52e02 | refs/heads/master | 2021-01-23T05:45:27.041872 | 2014-10-01T17:38:57 | 2014-10-01T17:38:57 | 24,688,225 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | #include "CDiscCollisionObject.h"
#include "SVector2D.h"
CDiscCollisionObject::CDiscCollisionObject(): CCollisionObject(ObjectType::Mine)
{
m_vPosition = new SVector2D<int>(0,0);
}
CDiscCollisionObject::CDiscCollisionObject(ObjectType objectType, SVector2D<int> position):CCollisionObject(objectType)
{
m_vPosition = new SVector2D<int>(position.x,position.y);
}
CDiscCollisionObject::~CDiscCollisionObject()
{
delete m_vPosition;
}
void CDiscCollisionObject::setPosition(SVector2D<int> position)
{
m_vPosition->x = position.x;
m_vPosition->y = position.y;
}
SVector2D<int> CDiscCollisionObject::getPosition() const
{
return *m_vPosition;
}
| [
"[email protected]"
] | |
dea2b8f1f2a1fd5ade42c8c5d850307d39060ec4 | 4dd75d9b666ca60c23f482e8ac465cfbb715769c | /Source file/untitled/ui_globalShiftAndScaleDlg.h | f972a01c034ff845bd29f95c6f498f653a9187ed | [] | no_license | shivareddyiirs/dharohar | 734b75fda992f53e1f7fc63aeac43d9950b544f8 | 12007a5e64f6a62aa6eef2a5cf4bb1f5fbde5ba3 | refs/heads/master | 2022-08-20T22:03:37.403135 | 2020-05-29T06:55:08 | 2020-05-29T06:55:08 | 145,975,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,393 | h | /********************************************************************************
** Form generated from reading UI file 'globalShiftAndScaleDlg.ui'
**
** Created by: Qt User Interface Compiler version 5.6.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_GLOBALSHIFTANDSCALEDLG_H
#define UI_GLOBALSHIFTANDSCALEDLG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_GlobalShiftAndScaleDlg
{
public:
QVBoxLayout *verticalLayout_5;
QFrame *titleFrame;
QVBoxLayout *verticalLayout;
QFrame *frame_2;
QHBoxLayout *horizontalLayout_3;
QSpacerItem *horizontalSpacer_3;
QLabel *messageLabel;
QToolButton *moreInfoToolButton;
QSpacerItem *horizontalSpacer_4;
QHBoxLayout *horizontalLayout_8;
QSpacerItem *horizontalSpacer;
QLabel *label_4;
QSpacerItem *horizontalSpacer_2;
QLabel *infoLabel;
QFrame *mainFrame;
QHBoxLayout *horizontalLayout_4;
QVBoxLayout *verticalLayout_3;
QFrame *bigCubeFrame;
QVBoxLayout *verticalLayout_7;
QLabel *label;
QFrame *originalPointFrame;
QVBoxLayout *verticalLayout_9;
QLabel *xOriginLabel;
QLabel *yOriginLabel;
QLabel *zOriginLabel;
QSpacerItem *verticalSpacer_6;
QLabel *diagOriginLabel;
QHBoxLayout *horizontalLayout;
QVBoxLayout *verticalLayout_2;
QSpacerItem *verticalSpacer_4;
QFrame *shiftFrame;
QGridLayout *gridLayout;
QDoubleSpinBox *scaleSpinBox;
QLabel *label_3;
QDoubleSpinBox *shiftX;
QLabel *label1;
QLabel *label_5;
QLabel *label1_2;
QDoubleSpinBox *shiftY;
QDoubleSpinBox *shiftZ;
QFrame *hLine2Frame;
QFrame *hLine3Frame;
QComboBox *loadComboBox;
QSpacerItem *verticalSpacer_3;
QVBoxLayout *verticalLayout_4;
QSpacerItem *verticalSpacer_2;
QFrame *smallCubeFrame;
QVBoxLayout *verticalLayout_8;
QLabel *label_2;
QFrame *destPointFrame;
QVBoxLayout *verticalLayout_10;
QLabel *xDestLabel;
QLabel *yDestLabel;
QLabel *zDestLabel;
QSpacerItem *verticalSpacer_7;
QLabel *diagDestLabel;
QSpacerItem *verticalSpacer_5;
QLabel *warningLabel;
QSpacerItem *verticalSpacer;
QFrame *frame;
QHBoxLayout *horizontalLayout_2;
QCheckBox *keepGlobalPosCheckBox;
QDialogButtonBox *buttonBox;
void setupUi(QDialog *GlobalShiftAndScaleDlg)
{
if (GlobalShiftAndScaleDlg->objectName().isEmpty())
GlobalShiftAndScaleDlg->setObjectName(QStringLiteral("GlobalShiftAndScaleDlg"));
GlobalShiftAndScaleDlg->resize(643, 389);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(GlobalShiftAndScaleDlg->sizePolicy().hasHeightForWidth());
GlobalShiftAndScaleDlg->setSizePolicy(sizePolicy);
verticalLayout_5 = new QVBoxLayout(GlobalShiftAndScaleDlg);
verticalLayout_5->setObjectName(QStringLiteral("verticalLayout_5"));
titleFrame = new QFrame(GlobalShiftAndScaleDlg);
titleFrame->setObjectName(QStringLiteral("titleFrame"));
titleFrame->setFrameShape(QFrame::StyledPanel);
titleFrame->setFrameShadow(QFrame::Raised);
verticalLayout = new QVBoxLayout(titleFrame);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
frame_2 = new QFrame(titleFrame);
frame_2->setObjectName(QStringLiteral("frame_2"));
frame_2->setFrameShape(QFrame::StyledPanel);
frame_2->setFrameShadow(QFrame::Raised);
horizontalLayout_3 = new QHBoxLayout(frame_2);
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_3);
messageLabel = new QLabel(frame_2);
messageLabel->setObjectName(QStringLiteral("messageLabel"));
QFont font;
font.setPointSize(10);
font.setBold(true);
font.setWeight(75);
messageLabel->setFont(font);
messageLabel->setAlignment(Qt::AlignCenter);
horizontalLayout_3->addWidget(messageLabel);
moreInfoToolButton = new QToolButton(frame_2);
moreInfoToolButton->setObjectName(QStringLiteral("moreInfoToolButton"));
horizontalLayout_3->addWidget(moreInfoToolButton);
horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_4);
verticalLayout->addWidget(frame_2);
horizontalLayout_8 = new QHBoxLayout();
horizontalLayout_8->setObjectName(QStringLiteral("horizontalLayout_8"));
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_8->addItem(horizontalSpacer);
label_4 = new QLabel(titleFrame);
label_4->setObjectName(QStringLiteral("label_4"));
QFont font1;
font1.setPointSize(10);
label_4->setFont(font1);
label_4->setAlignment(Qt::AlignCenter);
horizontalLayout_8->addWidget(label_4);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_8->addItem(horizontalSpacer_2);
verticalLayout->addLayout(horizontalLayout_8);
verticalLayout_5->addWidget(titleFrame);
infoLabel = new QLabel(GlobalShiftAndScaleDlg);
infoLabel->setObjectName(QStringLiteral("infoLabel"));
QFont font2;
font2.setItalic(true);
infoLabel->setFont(font2);
infoLabel->setStyleSheet(QStringLiteral("color: blue;"));
infoLabel->setAlignment(Qt::AlignCenter);
verticalLayout_5->addWidget(infoLabel);
mainFrame = new QFrame(GlobalShiftAndScaleDlg);
mainFrame->setObjectName(QStringLiteral("mainFrame"));
QSizePolicy sizePolicy1(QSizePolicy::Expanding, QSizePolicy::Maximum);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(mainFrame->sizePolicy().hasHeightForWidth());
mainFrame->setSizePolicy(sizePolicy1);
horizontalLayout_4 = new QHBoxLayout(mainFrame);
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
horizontalLayout_4->setContentsMargins(0, 9, 0, 9);
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
bigCubeFrame = new QFrame(mainFrame);
bigCubeFrame->setObjectName(QStringLiteral("bigCubeFrame"));
QSizePolicy sizePolicy2(QSizePolicy::Maximum, QSizePolicy::Maximum);
sizePolicy2.setHorizontalStretch(0);
sizePolicy2.setVerticalStretch(0);
sizePolicy2.setHeightForWidth(bigCubeFrame->sizePolicy().hasHeightForWidth());
bigCubeFrame->setSizePolicy(sizePolicy2);
bigCubeFrame->setMinimumSize(QSize(200, 200));
bigCubeFrame->setStyleSheet(QStringLiteral("background-color:rgb(187,224,227);"));
bigCubeFrame->setFrameShape(QFrame::Box);
bigCubeFrame->setFrameShadow(QFrame::Plain);
bigCubeFrame->setLineWidth(1);
verticalLayout_7 = new QVBoxLayout(bigCubeFrame);
verticalLayout_7->setObjectName(QStringLiteral("verticalLayout_7"));
label = new QLabel(bigCubeFrame);
label->setObjectName(QStringLiteral("label"));
QFont font3;
font3.setBold(true);
font3.setWeight(75);
label->setFont(font3);
label->setAlignment(Qt::AlignCenter);
verticalLayout_7->addWidget(label);
originalPointFrame = new QFrame(bigCubeFrame);
originalPointFrame->setObjectName(QStringLiteral("originalPointFrame"));
originalPointFrame->setFrameShape(QFrame::StyledPanel);
originalPointFrame->setFrameShadow(QFrame::Raised);
verticalLayout_9 = new QVBoxLayout(originalPointFrame);
verticalLayout_9->setObjectName(QStringLiteral("verticalLayout_9"));
verticalLayout_9->setContentsMargins(0, 0, 0, 0);
xOriginLabel = new QLabel(originalPointFrame);
xOriginLabel->setObjectName(QStringLiteral("xOriginLabel"));
xOriginLabel->setAlignment(Qt::AlignCenter);
verticalLayout_9->addWidget(xOriginLabel);
yOriginLabel = new QLabel(originalPointFrame);
yOriginLabel->setObjectName(QStringLiteral("yOriginLabel"));
yOriginLabel->setAlignment(Qt::AlignCenter);
verticalLayout_9->addWidget(yOriginLabel);
zOriginLabel = new QLabel(originalPointFrame);
zOriginLabel->setObjectName(QStringLiteral("zOriginLabel"));
zOriginLabel->setAlignment(Qt::AlignCenter);
verticalLayout_9->addWidget(zOriginLabel);
verticalLayout_7->addWidget(originalPointFrame);
verticalSpacer_6 = new QSpacerItem(20, 92, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_7->addItem(verticalSpacer_6);
diagOriginLabel = new QLabel(bigCubeFrame);
diagOriginLabel->setObjectName(QStringLiteral("diagOriginLabel"));
diagOriginLabel->setAlignment(Qt::AlignCenter);
verticalLayout_7->addWidget(diagOriginLabel);
verticalLayout_3->addWidget(bigCubeFrame);
horizontalLayout_4->addLayout(verticalLayout_3);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
verticalLayout_2 = new QVBoxLayout();
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
verticalSpacer_4 = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_2->addItem(verticalSpacer_4);
shiftFrame = new QFrame(mainFrame);
shiftFrame->setObjectName(QStringLiteral("shiftFrame"));
QSizePolicy sizePolicy3(QSizePolicy::Preferred, QSizePolicy::Maximum);
sizePolicy3.setHorizontalStretch(0);
sizePolicy3.setVerticalStretch(0);
sizePolicy3.setHeightForWidth(shiftFrame->sizePolicy().hasHeightForWidth());
shiftFrame->setSizePolicy(sizePolicy3);
gridLayout = new QGridLayout(shiftFrame);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
scaleSpinBox = new QDoubleSpinBox(shiftFrame);
scaleSpinBox->setObjectName(QStringLiteral("scaleSpinBox"));
scaleSpinBox->setMaximumSize(QSize(150, 16777215));
scaleSpinBox->setDecimals(8);
scaleSpinBox->setMinimum(1e-06);
scaleSpinBox->setMaximum(1e+06);
scaleSpinBox->setSingleStep(0.1);
scaleSpinBox->setValue(1);
gridLayout->addWidget(scaleSpinBox, 5, 4, 1, 1);
label_3 = new QLabel(shiftFrame);
label_3->setObjectName(QStringLiteral("label_3"));
label_3->setFont(font);
gridLayout->addWidget(label_3, 5, 2, 1, 1);
shiftX = new QDoubleSpinBox(shiftFrame);
shiftX->setObjectName(QStringLiteral("shiftX"));
QSizePolicy sizePolicy4(QSizePolicy::Expanding, QSizePolicy::Fixed);
sizePolicy4.setHorizontalStretch(0);
sizePolicy4.setVerticalStretch(0);
sizePolicy4.setHeightForWidth(shiftX->sizePolicy().hasHeightForWidth());
shiftX->setSizePolicy(sizePolicy4);
shiftX->setMaximumSize(QSize(150, 16777215));
shiftX->setMinimum(-1e+12);
shiftX->setMaximum(1e+12);
gridLayout->addWidget(shiftX, 2, 4, 1, 1);
label1 = new QLabel(shiftFrame);
label1->setObjectName(QStringLiteral("label1"));
QSizePolicy sizePolicy5(QSizePolicy::Maximum, QSizePolicy::Preferred);
sizePolicy5.setHorizontalStretch(0);
sizePolicy5.setVerticalStretch(0);
sizePolicy5.setHeightForWidth(label1->sizePolicy().hasHeightForWidth());
label1->setSizePolicy(sizePolicy5);
gridLayout->addWidget(label1, 2, 3, 1, 1);
label_5 = new QLabel(shiftFrame);
label_5->setObjectName(QStringLiteral("label_5"));
label_5->setFont(font);
gridLayout->addWidget(label_5, 2, 2, 1, 1);
label1_2 = new QLabel(shiftFrame);
label1_2->setObjectName(QStringLiteral("label1_2"));
sizePolicy5.setHeightForWidth(label1_2->sizePolicy().hasHeightForWidth());
label1_2->setSizePolicy(sizePolicy5);
gridLayout->addWidget(label1_2, 5, 3, 1, 1);
shiftY = new QDoubleSpinBox(shiftFrame);
shiftY->setObjectName(QStringLiteral("shiftY"));
sizePolicy4.setHeightForWidth(shiftY->sizePolicy().hasHeightForWidth());
shiftY->setSizePolicy(sizePolicy4);
shiftY->setMaximumSize(QSize(150, 16777215));
shiftY->setMinimum(-1e+12);
shiftY->setMaximum(1e+12);
gridLayout->addWidget(shiftY, 3, 4, 1, 1);
shiftZ = new QDoubleSpinBox(shiftFrame);
shiftZ->setObjectName(QStringLiteral("shiftZ"));
sizePolicy4.setHeightForWidth(shiftZ->sizePolicy().hasHeightForWidth());
shiftZ->setSizePolicy(sizePolicy4);
shiftZ->setMaximumSize(QSize(150, 16777215));
shiftZ->setMinimum(-1e+12);
shiftZ->setMaximum(1e+12);
gridLayout->addWidget(shiftZ, 4, 4, 1, 1);
hLine2Frame = new QFrame(shiftFrame);
hLine2Frame->setObjectName(QStringLiteral("hLine2Frame"));
sizePolicy4.setHeightForWidth(hLine2Frame->sizePolicy().hasHeightForWidth());
hLine2Frame->setSizePolicy(sizePolicy4);
hLine2Frame->setMinimumSize(QSize(20, 2));
hLine2Frame->setMaximumSize(QSize(16777215, 2));
hLine2Frame->setFrameShape(QFrame::Box);
hLine2Frame->setFrameShadow(QFrame::Plain);
hLine2Frame->setLineWidth(2);
gridLayout->addWidget(hLine2Frame, 2, 1, 1, 1);
hLine3Frame = new QFrame(shiftFrame);
hLine3Frame->setObjectName(QStringLiteral("hLine3Frame"));
sizePolicy.setHeightForWidth(hLine3Frame->sizePolicy().hasHeightForWidth());
hLine3Frame->setSizePolicy(sizePolicy);
hLine3Frame->setMinimumSize(QSize(20, 2));
hLine3Frame->setMaximumSize(QSize(16777215, 2));
hLine3Frame->setFrameShape(QFrame::Box);
hLine3Frame->setFrameShadow(QFrame::Plain);
hLine3Frame->setLineWidth(2);
gridLayout->addWidget(hLine3Frame, 5, 5, 1, 1);
loadComboBox = new QComboBox(shiftFrame);
loadComboBox->setObjectName(QStringLiteral("loadComboBox"));
gridLayout->addWidget(loadComboBox, 0, 4, 1, 1);
verticalLayout_2->addWidget(shiftFrame);
verticalSpacer_3 = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_2->addItem(verticalSpacer_3);
horizontalLayout->addLayout(verticalLayout_2);
verticalLayout_4 = new QVBoxLayout();
verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4"));
verticalSpacer_2 = new QSpacerItem(20, 25, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_4->addItem(verticalSpacer_2);
smallCubeFrame = new QFrame(mainFrame);
smallCubeFrame->setObjectName(QStringLiteral("smallCubeFrame"));
sizePolicy2.setHeightForWidth(smallCubeFrame->sizePolicy().hasHeightForWidth());
smallCubeFrame->setSizePolicy(sizePolicy2);
smallCubeFrame->setMinimumSize(QSize(150, 150));
smallCubeFrame->setMaximumSize(QSize(150, 150));
smallCubeFrame->setStyleSheet(QStringLiteral("background-color:rgb(187,224,227);"));
smallCubeFrame->setFrameShape(QFrame::Box);
smallCubeFrame->setFrameShadow(QFrame::Plain);
smallCubeFrame->setLineWidth(1);
verticalLayout_8 = new QVBoxLayout(smallCubeFrame);
verticalLayout_8->setObjectName(QStringLiteral("verticalLayout_8"));
label_2 = new QLabel(smallCubeFrame);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setFont(font3);
label_2->setAlignment(Qt::AlignCenter);
verticalLayout_8->addWidget(label_2);
destPointFrame = new QFrame(smallCubeFrame);
destPointFrame->setObjectName(QStringLiteral("destPointFrame"));
destPointFrame->setFrameShape(QFrame::StyledPanel);
destPointFrame->setFrameShadow(QFrame::Raised);
verticalLayout_10 = new QVBoxLayout(destPointFrame);
verticalLayout_10->setObjectName(QStringLiteral("verticalLayout_10"));
verticalLayout_10->setContentsMargins(0, 0, 0, 0);
xDestLabel = new QLabel(destPointFrame);
xDestLabel->setObjectName(QStringLiteral("xDestLabel"));
xDestLabel->setAlignment(Qt::AlignCenter);
verticalLayout_10->addWidget(xDestLabel);
yDestLabel = new QLabel(destPointFrame);
yDestLabel->setObjectName(QStringLiteral("yDestLabel"));
yDestLabel->setAlignment(Qt::AlignCenter);
verticalLayout_10->addWidget(yDestLabel);
zDestLabel = new QLabel(destPointFrame);
zDestLabel->setObjectName(QStringLiteral("zDestLabel"));
zDestLabel->setAlignment(Qt::AlignCenter);
verticalLayout_10->addWidget(zDestLabel);
verticalLayout_8->addWidget(destPointFrame);
verticalSpacer_7 = new QSpacerItem(20, 46, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_8->addItem(verticalSpacer_7);
diagDestLabel = new QLabel(smallCubeFrame);
diagDestLabel->setObjectName(QStringLiteral("diagDestLabel"));
diagDestLabel->setAlignment(Qt::AlignCenter);
verticalLayout_8->addWidget(diagDestLabel);
verticalLayout_4->addWidget(smallCubeFrame);
verticalSpacer_5 = new QSpacerItem(20, 25, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_4->addItem(verticalSpacer_5);
horizontalLayout->addLayout(verticalLayout_4);
horizontalLayout_4->addLayout(horizontalLayout);
verticalLayout_5->addWidget(mainFrame);
warningLabel = new QLabel(GlobalShiftAndScaleDlg);
warningLabel->setObjectName(QStringLiteral("warningLabel"));
warningLabel->setStyleSheet(QStringLiteral("color: red;"));
warningLabel->setAlignment(Qt::AlignCenter);
verticalLayout_5->addWidget(warningLabel);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_5->addItem(verticalSpacer);
frame = new QFrame(GlobalShiftAndScaleDlg);
frame->setObjectName(QStringLiteral("frame"));
frame->setFrameShape(QFrame::StyledPanel);
frame->setFrameShadow(QFrame::Raised);
horizontalLayout_2 = new QHBoxLayout(frame);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
horizontalLayout_2->setContentsMargins(0, 0, 0, 0);
keepGlobalPosCheckBox = new QCheckBox(frame);
keepGlobalPosCheckBox->setObjectName(QStringLiteral("keepGlobalPosCheckBox"));
horizontalLayout_2->addWidget(keepGlobalPosCheckBox);
buttonBox = new QDialogButtonBox(frame);
buttonBox->setObjectName(QStringLiteral("buttonBox"));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::No|QDialogButtonBox::Yes|QDialogButtonBox::YesToAll);
horizontalLayout_2->addWidget(buttonBox);
verticalLayout_5->addWidget(frame);
retranslateUi(GlobalShiftAndScaleDlg);
QObject::connect(buttonBox, SIGNAL(accepted()), GlobalShiftAndScaleDlg, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), GlobalShiftAndScaleDlg, SLOT(reject()));
loadComboBox->setCurrentIndex(-1);
QMetaObject::connectSlotsByName(GlobalShiftAndScaleDlg);
} // setupUi
void retranslateUi(QDialog *GlobalShiftAndScaleDlg)
{
GlobalShiftAndScaleDlg->setWindowTitle(QApplication::translate("GlobalShiftAndScaleDlg", "Global shift/scale", 0));
messageLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Coordinates are too big (original precision may be lost)!", 0));
#ifndef QT_NO_TOOLTIP
moreInfoToolButton->setToolTip(QApplication::translate("GlobalShiftAndScaleDlg", "More information about this issue", 0));
#endif // QT_NO_TOOLTIP
moreInfoToolButton->setText(QApplication::translate("GlobalShiftAndScaleDlg", "?", 0));
label_4->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Do you wish to translate/rescale the entity?", 0));
infoLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "shift/scale information is stored and used to restore the original coordinates at export time", 0));
#ifndef QT_NO_TOOLTIP
bigCubeFrame->setToolTip(QApplication::translate("GlobalShiftAndScaleDlg", "This version corresponds to the input (or output) file", 0));
#endif // QT_NO_TOOLTIP
label->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Point in original\n"
"coordinate system (on disk)", 0));
xOriginLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "x = 3213132123.3215", 0));
yOriginLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "y = 3213213143.34", 0));
zOriginLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "z = 3.87", 0));
diagOriginLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "diagonal = 3213132123.3215", 0));
label_3->setText(QApplication::translate("GlobalShiftAndScaleDlg", "x", 0));
label1->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Shift", 0));
label_5->setText(QApplication::translate("GlobalShiftAndScaleDlg", "+", 0));
label1_2->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Scale", 0));
#ifndef QT_NO_TOOLTIP
loadComboBox->setToolTip(QApplication::translate("GlobalShiftAndScaleDlg", "You can add default items to this list by placing a text file named <span style=\" font-weight:600;\">global_shift_list.txt</span> next to the application executable file. On each line you should define 5 items separated by semicolon characters: name ; ShiftX ; ShiftY ; ShiftZ ; scale", 0));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
smallCubeFrame->setToolTip(QApplication::translate("GlobalShiftAndScaleDlg", "This version is the one CloudCompare will work with. Mind the digits!", 0));
#endif // QT_NO_TOOLTIP
label_2->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Point in local\n"
"coordinate system", 0));
xDestLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "x = 123.3215", 0));
yDestLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "y = 143.34", 0));
zDestLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "z = 3.87", 0));
diagDestLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "diagonal = 321313", 0));
warningLabel->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Warning: previously used shift and/or scale don't seem adapted to this entity", 0));
#ifndef QT_NO_TOOLTIP
keepGlobalPosCheckBox->setToolTip(QApplication::translate("GlobalShiftAndScaleDlg", "The local coordinates will be changed so as to keep the global coordinates the same", 0));
#endif // QT_NO_TOOLTIP
keepGlobalPosCheckBox->setText(QApplication::translate("GlobalShiftAndScaleDlg", "Keep original position fixed", 0));
} // retranslateUi
};
namespace Ui {
class GlobalShiftAndScaleDlg: public Ui_GlobalShiftAndScaleDlg {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_GLOBALSHIFTANDSCALEDLG_H
| [
"[email protected]"
] | |
a4feb7a8fec3fc39e4c3df37d1fd83fedc1ed621 | e0d5ea777c571d2ab83def782e7112be14e86cdd | /floodFill.cpp | bfeb22bfd9373dc9155e78d4ad5cae9a8d3bf805 | [] | no_license | Daniel-D-Chen/Learning_OpenCV | 301769f8a8a6f2b281477ca3871cf7b119ac881b | be1cf4164610067c7826b32219adddb402884e74 | refs/heads/master | 2022-12-04T02:27:45.715718 | 2020-08-21T14:59:18 | 2020-08-21T14:59:18 | 289,069,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,047 | cpp | #include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
static String fileName = "ticket3.jpg";
int main_floodFill(int argc, char** argv) {
Mat_<uchar> srcImg = imread("./Resources/mine/" + fileName, IMREAD_GRAYSCALE);
/*Mat_<uchar> srcImg = Mat::zeros(400,512,CV_8UC1);
for (int x = 0; x < srcImg.cols; x++) {
for (int y = 0; y < srcImg.rows; y++) {
srcImg(y, x) = saturate_cast<uchar>(x/2);
}
}*/
Point seed = Point(100,100);
cout << "seed(" << seed.x << "," << seed.y << ")=" <<(int) srcImg(seed.y, seed.x) << endl;
Scalar LowDifference = Scalar(10);
Scalar UpDifference = Scalar(10);
Scalar newVal = Scalar(255);
int flags = 4 | FLOODFILL_FIXED_RANGE;
//circle(srcImg, seed, 20, Scalar(0));
floodFill(srcImg, seed, newVal, 0, LowDifference, UpDifference, flags);
namedWindow("Flood_Win",CV_WINDOW_AUTOSIZE);
imshow("Flood_Win", srcImg);
waitKey(0);
return EXIT_SUCCESS;
} | [
"[email protected]"
] | |
2132071e9674f2033c0f9ac981ecdb15db825417 | a715b800b1d230822e3a50ec02176626cbed7f67 | /cpp/Power of Four.cpp | f53797a485656682a13cc812a36fbb7cebfc48d5 | [] | no_license | SubhradeepSS/LeetCode-Solutions | 10c85f63059ae20ff91cf6dbc8102a4edd79c487 | 965e6390a76cccf84738d21340f5c049adcc223a | refs/heads/master | 2023-05-06T13:07:10.207287 | 2021-06-01T14:18:46 | 2021-06-01T14:18:46 | 370,042,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136 | cpp | class Solution {
public:
bool isPowerOfFour(int num) {
return num&&(ceil(log(num)/log(4))==floor(log(num)/log(4)));
}
}; | [
"[email protected]"
] | |
c96493d0515e209b73629b9feb6aa7e11b6c6495 | 3b11a8de751f402577389a7aafc64c535efbe63a | /LinkedList.hpp | 7d68505cd2bef6772132ae723be310ae68c02ce8 | [] | no_license | ufukygmr/Linked-List-Implementation | ed656a05b04257b73984a4d4866d9a8e2a31bf28 | f8226b8452d072235f9307e1019e61fa3199ad40 | refs/heads/master | 2022-07-03T00:35:00.592812 | 2020-01-11T18:12:11 | 2020-01-11T18:12:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,548 | hpp | #ifndef LINKED_LIST_HPP
#define LINKED_LIST_HPP
#include <iostream>
#include "Node.hpp"
template <class T>
class LinkedList
{
public: // DO NOT CHANGE THIS PART.
LinkedList();
LinkedList(const LinkedList &obj);
~LinkedList();
Node<T> *getFirstNode() const; //
Node<T> *getHead() const;
Node<T> *getTail() const;
int getNumberOfNodes();
bool isEmpty(); //
void insertAtTheFront(const T &data); //
void insertAtTheEnd(const T &data); //
void insertAfterGivenNode(const T &data, Node<T> *prev); //
void removeNode(Node<T> *node);
void removeAllNodes();
Node<T> *findNode(const T &data); //
void printAllNodes();
void printReversed();
LinkedList &operator=(const LinkedList &rhs);
private: // YOU MAY ADD YOUR OWN UTILITY MEMBER FUNCTIONS HERE.
private: // DO NOT CHANGE THIS PART.
Node<T> *head;
Node<T> *tail;
};
template<class T>
LinkedList<T>::LinkedList()
{
/* TODO */
Node<T> *dummy_head = new Node<T>();
Node<T> *dummy_tail = new Node<T>();
head = dummy_head;
tail = dummy_tail;
head->next = tail;
tail->prev = head;
}
template<class T>
LinkedList<T>::LinkedList(const LinkedList &obj)
{
/* TODO */
Node<T> *current = obj.head->next;
head = new Node<T>();
tail = new Node<T>();
head->next = tail;
tail->prev = head;
while(current->next){
insertAtTheEnd(current->element);
current = current->next;
}
}
// BSTNode<T> *min = NULL;
// BSTNode<T> *newCurrent = NULL;
// if(current->data == data){
// if(current->right){
// newCurrent = current->right;
// while(newCurrent->left){
// newCurrent = newCurrent->left;
// }
// min = newCurrent;
template<class T>
LinkedList<T>::~LinkedList()
{
/* TODO */
removeAllNodes();
delete head;
delete tail;
}
template<class T>
Node<T> * LinkedList<T>::getFirstNode() const
{
/* TODO */
if(head->next == tail){
return NULL;
}
return head->next;
}
template<class T>
Node<T> * LinkedList<T>::getHead() const
{
/* TODO */
return head;
}
template<class T>
Node<T> * LinkedList<T>::getTail() const
{
/* TODO */
return tail;
}
template<class T>
int LinkedList<T>::getNumberOfNodes()
{
/* TODO */
int i = 0;
Node<T> *current = head;
while(current->next){
i++;
current = current->next;
}
return i-1;
}
template<class T>
bool LinkedList<T>::isEmpty()
{
/* TODO */
if(head->next == tail){
return true;
}
return false;
}
template<class T>
void LinkedList<T>::insertAtTheFront(const T &data)
{
/* TODO */
Node <T> *New = new Node<T>();
Node <T> *oldFirst = head->next;
New->element = data;
New->prev = head;
New->next = oldFirst;
head->next = New;
oldFirst->prev = New;
}
template<class T>
void LinkedList<T>::insertAtTheEnd(const T &data)
{
/* TODO */
Node<T> *new_node = new Node<T> ();
if(head->next == tail){
new_node->element = data;
new_node->next = tail;
new_node->prev = head;
head->next = new_node;
tail->prev = new_node;
}
else{
Node<T> *last_node= tail->prev;
new_node->element = data;
new_node->next = tail;
new_node->prev = last_node;
last_node->next = new_node;
tail->prev = new_node;
}
}
template<class T>
void LinkedList<T>::insertAfterGivenNode(const T &data, Node<T> *prev)
{
/* TODO */
Node<T> *new_node = new Node<T>(data, prev, prev->next);
prev->next->prev = new_node;
prev->next = new_node;
}
template<class T>
void LinkedList<T>::removeNode(Node<T> *node)
{
/* TODO */
Node<T> *current = head->next;
while(current->next){
if(current == node){
current->prev->next = current->next;
current->next->prev = current->prev;
delete current;
break;
}
else {
current = current->next;
}
}
}
template<class T>
void LinkedList<T>::removeAllNodes()
{
/* TODO */
Node<T> *current = head->next;
while(current->next){
current = current->next;
delete current->prev;
}
head->next = tail;
tail->prev = head;
}
template<class T>
Node<T> * LinkedList<T>::findNode(const T &data)
{
/* TODO */
Node<T> *current = head->next;
while(current->next){
if(current->element == data){
return current;
break;
}
else {
current = current->next;
}
}
return NULL;
}
template<class T>
void LinkedList<T>::printAllNodes()
{
/* TODO */
Node<T> *current = head->next;
while(current->next){
std::cout << current->element << std::endl;
current = current->next;
}
}
template<class T>
void LinkedList<T>::printReversed()
{
/* TODO */
Node <T> *current = tail->prev;
while(current->prev){
std::cout << current->element << std::endl;
current = current->prev;
}
}
template<class T>
LinkedList<T> & LinkedList<T>::operator=(const LinkedList &rhs)
{
/* TODO */
removeAllNodes();
Node<T> *copyNode = rhs.head->next;
while(copyNode->next){
insertAtTheEnd(copyNode->element);
copyNode = copyNode->next;
}
return *this;
}
#endif //LINKED_LIST_HPP
| [
"[email protected]"
] | |
a23903d2be83124a9927b9707350e370f11b27da | e6ec3326bfba74656e5beb7f1599a87e210cc86b | /crypt/sha2.cpp | 3131063bf8703ed6714c026f432e84446d76cc77 | [] | no_license | fengjixuchui/syslib | 1d357983120386ab11d1a1cb64fd8ec30af24a56 | 8e3121e1d0cbd0021a155801badb53bd08fea6d9 | refs/heads/master | 2021-05-27T20:45:02.751275 | 2014-10-12T07:06:37 | 2014-10-12T07:06:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,576 | cpp | /*
* FILE: sha2.c
* AUTHOR: Aaron D. Gifford - http://www.aarongifford.com/
*
* Copyright (c) 2000-2001, Aaron D. Gifford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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.
*
* $Id: sha2.c,v 1.1 2001/11/08 00:01:51 adg Exp adg $
*/
#include "sys_includes.h"
namespace SYSLIB
{
#include "sha2.h"
/*
* ASSERT NOTE:
* Some sanity checking code is included using assert(). On my FreeBSD
* system, this additional code can be removed by compiling with NDEBUG
* defined. Check your own systems manpage on assert() to see how to
* compile WITHOUT the sanity checking code on your system.
*
* UNROLLED TRANSFORM LOOP NOTE:
* You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform
* loop version for the hash transform rounds (defined using macros
* later in this file). Either define on the command line, for example:
*
* cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c
*
* or define below:
*
* #define SHA2_UNROLL_TRANSFORM
*
*/
/*** SHA-256/384/512 Machine Architecture Definitions *****************/
/*
* BYTE_ORDER NOTE:
*
* Please make sure that your system defines BYTE_ORDER. If your
* architecture is little-endian, make sure it also defines
* LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are
* equivilent.
*
* If your system does not define the above, then you can do so by
* hand like this:
*
* #define LITTLE_ENDIAN 1234
* #define BIG_ENDIAN 4321
*
* And for little-endian machines, add:
*
* #define BYTE_ORDER LITTLE_ENDIAN
*
* Or for big-endian machines:
*
* #define BYTE_ORDER BIG_ENDIAN
*
* The FreeBSD machine this was written on defines BYTE_ORDER
* appropriately by including <sys/types.h> (which in turn includes
* <machine/endian.h> where the appropriate definitions are actually
* made).
*/
#define BYTE_ORDER LITTLE_ENDIAN
#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
#error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN
#endif
/*
* Define the followingsha2_* types to types of the correct length on
* the native archtecture. Most BSD systems and Linux define uintXX_t
* types. Machines with very recent ANSI C headers, can use the
* uintXX_t definintions from inttypes.h by defining SHA2_USE_INTTYPES_H
* during compile or in the sha.h header file.
*
* Machines that support neither uintXX_t nor inttypes.h's uintXX_t
* will need to define these three typedefs below (and the appropriate
* ones in sha.h too) by hand according to their system architecture.
*
* Thank you, Jun-ichiro itojun Hagino, for suggesting using uintXX_t
* types and pointing out recent ANSI C support for uintXX_t in inttypes.h.
*/
#ifdef SHA2_USE_INTTYPES_H
typedef uint8_t sha2_byte; /* Exactly 1 byte */
typedef uint32_t sha2_word32; /* Exactly 4 bytes */
typedef uint64_t sha2_word64; /* Exactly 8 bytes */
#else /* SHA2_USE_INTTYPES_H */
typedef uint8_t sha2_byte; /* Exactly 1 byte */
typedef uint32_t sha2_word32; /* Exactly 4 bytes */
typedef uint64_t sha2_word64; /* Exactly 8 bytes */
#endif /* SHA2_USE_INTTYPES_H */
/*** SHA-256/384/512 Various Length Definitions ***********************/
/* NOTE: Most of these are in sha2.h */
#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8)
#define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16)
#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16)
/*** ENDIAN REVERSAL MACROS *******************************************/
#if BYTE_ORDER == LITTLE_ENDIAN
#define REVERSE32(w,x) { \
sha2_word32 tmp = (w); \
tmp = (tmp >> 16) | (tmp << 16); \
(x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \
}
#define REVERSE64(w,x) { \
sha2_word64 tmp = (w); \
tmp = (tmp >> 32) | (tmp << 32); \
tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \
((tmp & 0x00ff00ff00ff00ffULL) << 8); \
(x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \
((tmp & 0x0000ffff0000ffffULL) << 16); \
}
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
/*
* Macro for incrementally adding the unsigned 64-bit integer n to the
* unsigned 128-bit integer (represented using a two-element array of
* 64-bit words):
*/
#define ADDINC128(w,n) { \
(w)[0] += (sha2_word64)(n); \
if ((w)[0] < (n)) { \
(w)[1]++; \
} \
}
/*
* Macros for copying blocks of memory and for zeroing out ranges
* of memory. Using these macros makes it easy to switch from
* using memset()/memcpy() and using bzero()/bcopy().
*
* Please define either SHA2_USE_MEMSET_MEMCPY or define
* SHA2_USE_BZERO_BCOPY depending on which function set you
* choose to use:
*/
#if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
/* Default to memset()/memcpy() if no option is specified */
#define SHA2_USE_MEMSET_MEMCPY 1
#endif
#if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
/* Abort with an error if BOTH options are defined */
#error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
#endif
#ifdef SHA2_USE_MEMSET_MEMCPY
#define MEMSET_BZERO(p,l) memset((p), 0, (l))
#define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l))
#endif
#ifdef SHA2_USE_BZERO_BCOPY
#define MEMSET_BZERO(p,l) bzero((p), (l))
#define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l))
#endif
/*** THE SIX LOGICAL FUNCTIONS ****************************************/
/*
* Bit shifting and rotation (used by the six SHA-XYZ logical functions:
*
* NOTE: The naming of R and S appears backwards here (R is a SHIFT and
* S is a ROTATION) because the SHA-256/384/512 description document
* (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this
* same "backwards" definition.
*/
/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
#define R(b,x) ((x) >> (b))
/* 32-bit Rotate-right (used in SHA-256): */
#define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b))))
/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
#define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b))))
/* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */
#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
/* Four of six logical functions used in SHA-256: */
#define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x)))
#define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x)))
#define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x)))
#define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x)))
/* Four of six logical functions used in SHA-384 and SHA-512: */
#define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x)))
#define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x)))
#define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x)))
#define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x)))
/*** INTERNAL FUNCTION PROTOTYPES *************************************/
/* NOTE: These should not be accessed directly from outside this
* library -- they are intended for private internal visibility/use
* only.
*/
void SHA512_Last(SHA512_CTX*);
void SHA256_Transform(SHA256_CTX*, const sha2_word32*);
void SHA512_Transform(SHA512_CTX*, const sha2_word64*);
/*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
/* Hash constant words K for SHA-256: */
const static sha2_word32 K256[64] = {
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL,
0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL,
0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL,
0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL,
0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL,
0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL,
0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
/* Initial hash value H for SHA-256: */
const static sha2_word32 sha256_initial_hash_value[8] = {
0x6a09e667UL,
0xbb67ae85UL,
0x3c6ef372UL,
0xa54ff53aUL,
0x510e527fUL,
0x9b05688cUL,
0x1f83d9abUL,
0x5be0cd19UL
};
/* Hash constant words K for SHA-384 and SHA-512: */
const static sha2_word64 K512[80] = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
};
/* Initial hash value H for SHA-384 */
const static sha2_word64 sha384_initial_hash_value[8] = {
0xcbbb9d5dc1059ed8ULL,
0x629a292a367cd507ULL,
0x9159015a3070dd17ULL,
0x152fecd8f70e5939ULL,
0x67332667ffc00b31ULL,
0x8eb44a8768581511ULL,
0xdb0c2e0d64f98fa7ULL,
0x47b5481dbefa4fa4ULL
};
/* Initial hash value H for SHA-512 */
const static sha2_word64 sha512_initial_hash_value[8] = {
0x6a09e667f3bcc908ULL,
0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL,
0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL,
0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL,
0x5be0cd19137e2179ULL
};
/*
* Constant used by SHA256/384/512_End() functions for converting the
* digest to a readable hexadecimal character string:
*/
static const char *sha2_hex_digits = "0123456789abcdef";
/*** SHA-256: *********************************************************/
void SHA256_Init(SHA256_CTX* context) {
if (context == (SHA256_CTX*)0) {
return;
}
MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH);
MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH);
context->bitcount = 0;
}
#ifdef SHA2_UNROLL_TRANSFORM
/* Unrolled SHA-256 round macros: */
#if BYTE_ORDER == LITTLE_ENDIAN
#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \
REVERSE32(*data++, W256[j]); \
T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
K256[j] + W256[j]; \
(d) += T1; \
(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
j++
#else /* BYTE_ORDER == LITTLE_ENDIAN */
#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \
T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
K256[j] + (W256[j] = *data++); \
(d) += T1; \
(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
j++
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
#define ROUND256(a,b,c,d,e,f,g,h) \
s0 = W256[(j+1)&0x0f]; \
s0 = sigma0_256(s0); \
s1 = W256[(j+14)&0x0f]; \
s1 = sigma1_256(s1); \
T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
(W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
(d) += T1; \
(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
j++
void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
sha2_word32 a, b, c, d, e, f, g, h, s0, s1;
sha2_word32 T1, *W256;
int j;
W256 = (sha2_word32*)context->buffer;
/* Initialize registers with the prev. intermediate value */
a = context->state[0];
b = context->state[1];
c = context->state[2];
d = context->state[3];
e = context->state[4];
f = context->state[5];
g = context->state[6];
h = context->state[7];
j = 0;
do {
/* Rounds 0 to 15 (unrolled): */
ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
} while (j < 16);
/* Now for the remaining rounds to 64: */
do {
ROUND256(a,b,c,d,e,f,g,h);
ROUND256(h,a,b,c,d,e,f,g);
ROUND256(g,h,a,b,c,d,e,f);
ROUND256(f,g,h,a,b,c,d,e);
ROUND256(e,f,g,h,a,b,c,d);
ROUND256(d,e,f,g,h,a,b,c);
ROUND256(c,d,e,f,g,h,a,b);
ROUND256(b,c,d,e,f,g,h,a);
} while (j < 64);
/* Compute the current intermediate hash value */
context->state[0] += a;
context->state[1] += b;
context->state[2] += c;
context->state[3] += d;
context->state[4] += e;
context->state[5] += f;
context->state[6] += g;
context->state[7] += h;
/* Clean up */
a = b = c = d = e = f = g = h = T1 = 0;
}
#else /* SHA2_UNROLL_TRANSFORM */
void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
sha2_word32 a, b, c, d, e, f, g, h, s0, s1;
sha2_word32 T1, T2, *W256;
int j;
W256 = (sha2_word32*)context->buffer;
/* Initialize registers with the prev. intermediate value */
a = context->state[0];
b = context->state[1];
c = context->state[2];
d = context->state[3];
e = context->state[4];
f = context->state[5];
g = context->state[6];
h = context->state[7];
j = 0;
do {
#if BYTE_ORDER == LITTLE_ENDIAN
/* Copy data while converting to host byte order */
REVERSE32(*data++,W256[j]);
/* Apply the SHA-256 compression function to update a..h */
T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
#else /* BYTE_ORDER == LITTLE_ENDIAN */
/* Apply the SHA-256 compression function to update a..h with copy */
T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++);
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
T2 = Sigma0_256(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 16);
do {
/* Part of the message block expansion: */
s0 = W256[(j+1)&0x0f];
s0 = sigma0_256(s0);
s1 = W256[(j+14)&0x0f];
s1 = sigma1_256(s1);
/* Apply the SHA-256 compression function to update a..h */
T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] +
(W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
T2 = Sigma0_256(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 64);
/* Compute the current intermediate hash value */
context->state[0] += a;
context->state[1] += b;
context->state[2] += c;
context->state[3] += d;
context->state[4] += e;
context->state[5] += f;
context->state[6] += g;
context->state[7] += h;
/* Clean up */
a = b = c = d = e = f = g = h = T1 = T2 = 0;
}
#endif /* SHA2_UNROLL_TRANSFORM */
void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
unsigned int freespace, usedspace;
if (len == 0) {
/* Calling with no data is valid - we do nothing */
return;
}
/* Sanity check: */
/// assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0);
usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
if (usedspace > 0) {
/* Calculate how much free space is available in the buffer */
freespace = SHA256_BLOCK_LENGTH - usedspace;
if (len >= freespace) {
/* Fill the buffer completely and process it */
MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
context->bitcount += freespace << 3;
len -= freespace;
data += freespace;
SHA256_Transform(context, (sha2_word32*)context->buffer);
} else {
/* The buffer is not yet full */
MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
context->bitcount += len << 3;
/* Clean up: */
usedspace = freespace = 0;
return;
}
}
while (len >= SHA256_BLOCK_LENGTH) {
/* Process as many complete blocks as we can */
SHA256_Transform(context, (sha2_word32*)data);
context->bitcount += SHA256_BLOCK_LENGTH << 3;
len -= SHA256_BLOCK_LENGTH;
data += SHA256_BLOCK_LENGTH;
}
if (len > 0) {
/* There's left-overs, so save 'em */
MEMCPY_BCOPY(context->buffer, data, len);
context->bitcount += len << 3;
}
/* Clean up: */
usedspace = freespace = 0;
}
void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
sha2_word32 *d = (sha2_word32*)digest;
unsigned int usedspace;
/* Sanity check: */
/// assert(context != (SHA256_CTX*)0);
/* If no digest buffer is passed, we don't bother doing this: */
if (digest != (sha2_byte*)0) {
usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert FROM host byte order */
REVERSE64(context->bitcount,context->bitcount);
#endif
if (usedspace > 0) {
/* Begin padding with a 1 bit: */
context->buffer[usedspace++] = 0x80;
if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) {
/* Set-up for the last transform: */
MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace);
} else {
if (usedspace < SHA256_BLOCK_LENGTH) {
MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace);
}
/* Do second-to-last transform: */
SHA256_Transform(context, (sha2_word32*)context->buffer);
/* And set-up for the last transform: */
MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
}
} else {
/* Set-up for the last transform: */
MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
/* Begin padding with a 1 bit: */
*context->buffer = 0x80;
}
/* Set the bit count: */
*(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount;
/* Final transform: */
SHA256_Transform(context, (sha2_word32*)context->buffer);
#if BYTE_ORDER == LITTLE_ENDIAN
{
/* Convert TO host byte order */
int j;
for (j = 0; j < 8; j++) {
REVERSE32(context->state[j],context->state[j]);
*d++ = context->state[j];
}
}
#else
MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH);
#endif
}
/* Clean up state data: */
MEMSET_BZERO(context, sizeof(context));
usedspace = 0;
}
char *SHA256_End(SHA256_CTX* context, char buffer[]) {
sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest;
int i;
/* Sanity check: */
/// assert(context != (SHA256_CTX*)0);
if (buffer != (char*)0) {
SHA256_Final(digest, context);
for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
*buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
*buffer++ = sha2_hex_digits[*d & 0x0f];
d++;
}
*buffer = (char)0;
} else {
MEMSET_BZERO(context, sizeof(context));
}
MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH);
return buffer;
}
char* SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) {
SHA256_CTX context;
SHA256_Init(&context);
SHA256_Update(&context, data, len);
return SHA256_End(&context, digest);
}
/*** SHA-512: *********************************************************/
void SHA512_Init(SHA512_CTX* context) {
if (context == (SHA512_CTX*)0) {
return;
}
MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH);
MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH);
context->bitcount[0] = context->bitcount[1] = 0;
}
#ifdef SHA2_UNROLL_TRANSFORM
/* Unrolled SHA-512 round macros: */
#if BYTE_ORDER == LITTLE_ENDIAN
#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \
REVERSE64(*data++, W512[j]); \
T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
K512[j] + W512[j]; \
(d) += T1, \
(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \
j++
#else /* BYTE_ORDER == LITTLE_ENDIAN */
#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \
T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
K512[j] + (W512[j] = *data++); \
(d) += T1; \
(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
j++
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
#define ROUND512(a,b,c,d,e,f,g,h) \
s0 = W512[(j+1)&0x0f]; \
s0 = sigma0_512(s0); \
s1 = W512[(j+14)&0x0f]; \
s1 = sigma1_512(s1); \
T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \
(W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \
(d) += T1; \
(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
j++
void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
sha2_word64 a, b, c, d, e, f, g, h, s0, s1;
sha2_word64 T1, *W512 = (sha2_word64*)context->buffer;
int j;
/* Initialize registers with the prev. intermediate value */
a = context->state[0];
b = context->state[1];
c = context->state[2];
d = context->state[3];
e = context->state[4];
f = context->state[5];
g = context->state[6];
h = context->state[7];
j = 0;
do {
ROUND512_0_TO_15(a,b,c,d,e,f,g,h);
ROUND512_0_TO_15(h,a,b,c,d,e,f,g);
ROUND512_0_TO_15(g,h,a,b,c,d,e,f);
ROUND512_0_TO_15(f,g,h,a,b,c,d,e);
ROUND512_0_TO_15(e,f,g,h,a,b,c,d);
ROUND512_0_TO_15(d,e,f,g,h,a,b,c);
ROUND512_0_TO_15(c,d,e,f,g,h,a,b);
ROUND512_0_TO_15(b,c,d,e,f,g,h,a);
} while (j < 16);
/* Now for the remaining rounds up to 79: */
do {
ROUND512(a,b,c,d,e,f,g,h);
ROUND512(h,a,b,c,d,e,f,g);
ROUND512(g,h,a,b,c,d,e,f);
ROUND512(f,g,h,a,b,c,d,e);
ROUND512(e,f,g,h,a,b,c,d);
ROUND512(d,e,f,g,h,a,b,c);
ROUND512(c,d,e,f,g,h,a,b);
ROUND512(b,c,d,e,f,g,h,a);
} while (j < 80);
/* Compute the current intermediate hash value */
context->state[0] += a;
context->state[1] += b;
context->state[2] += c;
context->state[3] += d;
context->state[4] += e;
context->state[5] += f;
context->state[6] += g;
context->state[7] += h;
/* Clean up */
a = b = c = d = e = f = g = h = T1 = 0;
}
#else /* SHA2_UNROLL_TRANSFORM */
void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
sha2_word64 a, b, c, d, e, f, g, h, s0, s1;
sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer;
int j;
/* Initialize registers with the prev. intermediate value */
a = context->state[0];
b = context->state[1];
c = context->state[2];
d = context->state[3];
e = context->state[4];
f = context->state[5];
g = context->state[6];
h = context->state[7];
j = 0;
do {
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
REVERSE64(*data++, W512[j]);
/* Apply the SHA-512 compression function to update a..h */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
#else /* BYTE_ORDER == LITTLE_ENDIAN */
/* Apply the SHA-512 compression function to update a..h with copy */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
T2 = Sigma0_512(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 16);
do {
/* Part of the message block expansion: */
s0 = W512[(j+1)&0x0f];
s0 = sigma0_512(s0);
s1 = W512[(j+14)&0x0f];
s1 = sigma1_512(s1);
/* Apply the SHA-512 compression function to update a..h */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
(W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
T2 = Sigma0_512(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 80);
/* Compute the current intermediate hash value */
context->state[0] += a;
context->state[1] += b;
context->state[2] += c;
context->state[3] += d;
context->state[4] += e;
context->state[5] += f;
context->state[6] += g;
context->state[7] += h;
/* Clean up */
a = b = c = d = e = f = g = h = T1 = T2 = 0;
}
#endif /* SHA2_UNROLL_TRANSFORM */
void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
unsigned int freespace, usedspace;
if (len == 0) {
/* Calling with no data is valid - we do nothing */
return;
}
/* Sanity check: */
/// assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0);
usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
if (usedspace > 0) {
/* Calculate how much free space is available in the buffer */
freespace = SHA512_BLOCK_LENGTH - usedspace;
if (len >= freespace) {
/* Fill the buffer completely and process it */
MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
ADDINC128(context->bitcount, freespace << 3);
len -= freespace;
data += freespace;
SHA512_Transform(context, (sha2_word64*)context->buffer);
} else {
/* The buffer is not yet full */
MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
ADDINC128(context->bitcount, len << 3);
/* Clean up: */
usedspace = freespace = 0;
return;
}
}
while (len >= SHA512_BLOCK_LENGTH) {
/* Process as many complete blocks as we can */
SHA512_Transform(context, (sha2_word64*)data);
ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
len -= SHA512_BLOCK_LENGTH;
data += SHA512_BLOCK_LENGTH;
}
if (len > 0) {
/* There's left-overs, so save 'em */
MEMCPY_BCOPY(context->buffer, data, len);
ADDINC128(context->bitcount, len << 3);
}
/* Clean up: */
usedspace = freespace = 0;
}
void SHA512_Last(SHA512_CTX* context) {
unsigned int usedspace;
usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert FROM host byte order */
REVERSE64(context->bitcount[0],context->bitcount[0]);
REVERSE64(context->bitcount[1],context->bitcount[1]);
#endif
if (usedspace > 0) {
/* Begin padding with a 1 bit: */
context->buffer[usedspace++] = 0x80;
if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) {
/* Set-up for the last transform: */
MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace);
} else {
if (usedspace < SHA512_BLOCK_LENGTH) {
MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace);
}
/* Do second-to-last transform: */
SHA512_Transform(context, (sha2_word64*)context->buffer);
/* And set-up for the last transform: */
MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2);
}
} else {
/* Prepare for final transform: */
MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH);
/* Begin padding with a 1 bit: */
*context->buffer = 0x80;
}
/* Store the length of input data (in bits): */
*(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1];
*(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0];
/* Final transform: */
SHA512_Transform(context, (sha2_word64*)context->buffer);
}
void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
sha2_word64 *d = (sha2_word64*)digest;
/* Sanity check: */
/// assert(context != (SHA512_CTX*)0);
/* If no digest buffer is passed, we don't bother doing this: */
if (digest != (sha2_byte*)0) {
SHA512_Last(context);
/* Save the hash data for output: */
#if BYTE_ORDER == LITTLE_ENDIAN
{
/* Convert TO host byte order */
int j;
for (j = 0; j < 8; j++) {
REVERSE64(context->state[j],context->state[j]);
*d++ = context->state[j];
}
}
#else
MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH);
#endif
}
/* Zero out state data */
MEMSET_BZERO(context, sizeof(context));
}
char *SHA512_End(SHA512_CTX* context, char buffer[]) {
sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest;
int i;
/* Sanity check: */
/// assert(context != (SHA512_CTX*)0);
if (buffer != (char*)0) {
SHA512_Final(digest, context);
for (i = 0; i < SHA512_DIGEST_LENGTH; i++) {
*buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
*buffer++ = sha2_hex_digits[*d & 0x0f];
d++;
}
*buffer = (char)0;
} else {
MEMSET_BZERO(context, sizeof(context));
}
MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH);
return buffer;
}
char* SHA512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) {
SHA512_CTX context;
SHA512_Init(&context);
SHA512_Update(&context, data, len);
return SHA512_End(&context, digest);
}
/*** SHA-384: *********************************************************/
void SHA384_Init(SHA384_CTX* context) {
if (context == (SHA384_CTX*)0) {
return;
}
MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH);
MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH);
context->bitcount[0] = context->bitcount[1] = 0;
}
void SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) {
SHA512_Update((SHA512_CTX*)context, data, len);
}
void SHA384_Final(sha2_byte digest[], SHA384_CTX* context) {
sha2_word64 *d = (sha2_word64*)digest;
/* Sanity check: */
/// assert(context != (SHA384_CTX*)0);
/* If no digest buffer is passed, we don't bother doing this: */
if (digest != (sha2_byte*)0) {
SHA512_Last((SHA512_CTX*)context);
/* Save the hash data for output: */
#if BYTE_ORDER == LITTLE_ENDIAN
{
/* Convert TO host byte order */
int j;
for (j = 0; j < 6; j++) {
REVERSE64(context->state[j],context->state[j]);
*d++ = context->state[j];
}
}
#else
MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH);
#endif
}
/* Zero out state data */
MEMSET_BZERO(context, sizeof(context));
}
char *SHA384_End(SHA384_CTX* context, char buffer[]) {
sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest;
int i;
/* Sanity check: */
/// assert(context != (SHA384_CTX*)0);
if (buffer != (char*)0) {
SHA384_Final(digest, context);
for (i = 0; i < SHA384_DIGEST_LENGTH; i++) {
*buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
*buffer++ = sha2_hex_digits[*d & 0x0f];
d++;
}
*buffer = (char)0;
} else {
MEMSET_BZERO(context, sizeof(context));
}
MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH);
return buffer;
}
char* SHA384_Data(const sha2_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) {
SHA384_CTX context;
SHA384_Init(&context);
SHA384_Update(&context, data, len);
return SHA384_End(&context, digest);
}
}
SYSLIBFUNC(BOOL) hash_CalcSHA512(const LPBYTE lpData,DWORD dwLen,LPBYTE lpHash)
{
BOOL bRet=false;
do
{
if (!SYSLIB_SAFE::CheckParamRead(lpData,dwLen))
break;
if (!SYSLIB_SAFE::CheckParamWrite(lpHash,SHA512_DIGEST_STRING_LENGTH))
break;
SYSLIB::SHA512_CTX ctx;
SYSLIB::SHA512_Init(&ctx);
SYSLIB::SHA512_Update(&ctx, lpData, dwLen);
SYSLIB::SHA512_End(&ctx,(char*) lpHash);
bRet=true;
}
while (false);
return bRet;
}
| [
"seledka"
] | seledka |
7f965b1fa9473e763fe2c18c1016f2253aefed2b | e1cf5a2edd69efee4d6161080e991c46aeba94bd | /ext/ons/aliyun-mq-cpp-sdk/include/ons/TransactionProducer.h | 74f0497bdf16f7172468cd5f91c61fe0ff141012 | [
"MIT"
] | permissive | souche/aliyun-ons-ruby-sdk | 1d3285c66b8aed7e01b938c4f4ac3942a977719e | 00d16d5fe4dc55929036544a7667c463694f6b1f | refs/heads/master | 2023-03-12T02:09:36.817571 | 2016-11-27T07:05:12 | 2016-11-27T07:05:12 | 65,178,678 | 16 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 742 | h | #ifndef __TRANSACTIONPRODUCER_H__
#define __TRANSACTIONPRODUCER_H__
#include "LocalTransactionExecuter.h"
namespace ons{
class TransactionProducer{
public:
TransactionProducer(){}
virtual ~TransactionProducer(){}
//before send msg, start must be called to allocate resources.
virtual void start()=0;
//before exit ons, shutdown must be called to release all resources allocated by ons internally.
virtual void shutdown()=0;
//retry max 3 times if send failed. if no exception throwed, it sends success;
virtual SendResultONS send(Message& msg, LocalTransactionExecuter *executer)=0;
};
}
#endif
| [
"[email protected]"
] | |
9327a628d3aaf5230f05cefd1587c65269978d9f | cbf37e782425e378676814be6b41fab5596ded65 | /backend/tests/test-seal-uint8_t-subtract.cpp | 2bc49b3adc3b7a397d31d571062521a509d1ccbf | [
"MIT"
] | permissive | PhilipTurk/SHEEP | 7c971fcdd6002b385208eba6701d83ed2817f415 | b0c95516184536cafe5111438b93fa8140538f22 | refs/heads/master | 2020-06-18T07:56:49.710405 | 2019-02-18T15:45:13 | 2019-02-18T15:45:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | cpp | #include <algorithm>
#include <cassert>
#include <cstdint>
#include "circuit-repo.hpp"
#include "circuit-test-util.hpp"
#include "context-seal.hpp"
#include "simple-circuits.hpp"
typedef std::chrono::duration<double, std::micro> DurationT;
int main(void) {
using namespace SHEEP;
CircuitRepo cr;
Circuit circ = cr.create_circuit(Gate::Subtract, 1);
std::cout << circ;
std::vector<DurationT> durations;
ContextSeal<uint8_t> ctx;
ctx.set_parameter("NumSlots", 4);
std::vector<std::vector<ContextSeal<uint8_t>::Plaintext>> pt_input = {
{22, 16, 100, 120}, {15, 12, 27, 0}};
std::vector<std::vector<ContextSeal<uint8_t>::Plaintext>> result =
ctx.eval_with_plaintexts(circ, pt_input);
std::vector<uint8_t> exp_values = {7, 4, 73, 120};
for (int i = 0; i < exp_values.size(); i++) {
std::cout << std::to_string(pt_input[0][i]) << " - "
<< std::to_string(pt_input[1][i]) << " = "
<< std::to_string(result[0][i]) << std::endl;
assert(result[0][i] == exp_values[i]);
}
}
| [
"[email protected]"
] | |
e4a8ab81a2bbb84ce58488e8634751746a4277e0 | 338a9f8e5f6d8b5b79b9c32b6319af16b02ff7b7 | /src/jet/live/DefaultProgramInfoLoader.hpp | bac55b43b6ad3153bb433632a515891dda3b7cbb | [
"MIT"
] | permissive | ddovod/jet-live | 26b60783cbd5ab76015c4386318731e49cbcdc00 | 59c38997f7c16f54ddf9e68a189384bd11878568 | refs/heads/master | 2022-08-26T18:52:46.584817 | 2022-01-28T09:00:25 | 2022-01-28T09:00:25 | 163,978,787 | 394 | 33 | MIT | 2020-01-18T10:28:27 | 2019-01-03T13:47:39 | C++ | UTF-8 | C++ | false | false | 360 | hpp |
#pragma once
#ifdef __linux__
#include "jet/live/_linux/ElfProgramInfoLoader.hpp"
namespace jet
{
using DefaultProgramInfoLoader = ElfProgramInfoLoader;
}
#elif __APPLE__
#include "jet/live/_macos/MachoProgramInfoLoader.hpp"
namespace jet
{
using DefaultProgramInfoLoader = MachoProgramInfoLoader;
}
#else
#error "Platform is not supported"
#endif
| [
"[email protected]"
] | |
d18c03ab211576079be5eee1002ca239c80d7ef3 | 6a408c6754e8cad8376ff030570129963a0f7b2c | /lesson5/l5-1/l5-1/main.cpp | 295bd33f7f0968fc35411b3173de5fe9776e1439 | [] | no_license | dimmkan/MSHP | e4ed8cb6528747f10900c6fe5bcf650238d3f9f6 | 956629ee2b83df28caacc2554bf7a00e1aad848c | refs/heads/master | 2020-09-07T00:56:01.756864 | 2020-05-30T08:54:08 | 2020-05-30T08:54:08 | 220,607,366 | 1 | 0 | null | 2020-01-31T15:52:26 | 2019-11-09T07:29:26 | C++ | UTF-8 | C++ | false | false | 233 | cpp | #include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
if((abs(a/1000)>=1)&&(abs(a/1000)<=9)&&(a%5==0)){
cout << "SUCCESS";
}else {
cout << "FAILURE";
}
return 0;
}
| [
"[email protected]"
] | |
8cc8243e8dab55b6f7f620e7ddbf03ad5420c86d | 90841e9ca7b21c2500a8ea5cd45a88625192978c | /Parallelisme/tpCCPitrouAdrien/MPI/Syracuse/maitre.cpp | 2fc7b1f89e2b60f70325298293d08922ad6ff5f4 | [] | no_license | pitrouA/CPlusPlus | 3475a09ab3de47160a179cb0aba81d2e05c85c52 | 4698bdfde8b26d6a2a1bc17ad8889a3e6684cdb9 | refs/heads/master | 2023-07-08T05:06:01.781741 | 2021-08-07T13:32:32 | 2021-08-07T13:32:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,314 | cpp | #include <mpi.h>
#include <iostream>
#include "syracuse.h"
using namespace std;
int main(int argc, char **argv) {
int nmasters, pid;
MPI_Comm intercom;
MPI_Comm intracom;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nmasters);
MPI_Comm_rank(MPI_COMM_WORLD, &pid);
int n = atoi(argv[1]); // la taille de la suite à vérifier
int nslaves = atoi(argv[2]); // le nombre d'esclaves à lancer
int mode = atoi(argv[3]); // le mode de la génération
if (nmasters != 1) {
cout << "Attention un seul master !";
MPI_Abort(MPI_COMM_WORLD, 0);
}
/* Génération de la suite sur le maître */
int *tab;
tab = new int[n];
switch (mode) {
case 0:
cout << "test génération aléatoire " << endl;
non_syracuse(n, tab);
break;
case 1:
cout << "test syracuse partielle" << endl;
demi_syracuse(n, tab);
break;
default:
cout << "test syracuse" << endl;
syracuse(n, tab);
}
cout << "tab : ";
for (int i=0; i<n; i++)
cout << tab[i] << " ";
cout << endl;
MPI_Comm_spawn("esclave", argv, nslaves, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &intercom, MPI_ERRCODES_IGNORE);
MPI_Intercomm_merge(intercom,0,&intracom);
int pid_intra;
MPI_Comm_rank(intracom,&pid_intra);
cout << "je suis le maître " << pid << " parmi " << nmasters << " maîtres et dans l'intra communicateur je suis " << pid_intra << endl;
MPI_Win TheWin; // Déclaration de la fenêtre
MPI_Win_create(tab, n*sizeof(int), sizeof(int),MPI_INFO_NULL, intracom,&TheWin);
//envoi de l'information aux esclaves
//mais en fait, ça pose des problemes de synchronisation -> se rabattre sur le get qui normalement fonctionne mieux
/*for (int i = 0; i < nslaves; i++){
if (i != pid){
MPI_Win_lock(MPI_LOCK_EXCLUSIVE,i,0,TheWin);
MPI_Put(tab, n, MPI_INT, i, pid, 1, MPI_INT, TheWin);
MPI_Win_unlock(i,TheWin);
}
}*/
MPI_Win_lock(MPI_LOCK_EXCLUSIVE,0,0,TheWin);
MPI_Win_unlock(0,TheWin);
free(tab);
MPI_Comm_free(&intercom);
MPI_Comm_free(&intracom);
MPI_Finalize();
return 0;
}
// make
// mpirun -np 1 ./maitre 16 4 0
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.